Whoever builds the API — you, a hired freelancer, or a future team — plus anyone reviewing or approving the scope beforehand. No prior knowledge of this codebase is assumed.
It also serves as durable context for an AI coding agent asked to implement or modify the API later: since the app itself is a single HTML file with no separate spec, an agent working from the code alone would have to infer intent from function names and DOM logic. This document states that intent explicitly, so a change made months from now — by a person or an agent — stays consistent with the original design instead of drifting from it.
A build-ready specification. It replaces the need to reverse-engineer requirements from the existing HTML/JS, so an implementer knows exactly which actions to build, what each one takes in and returns, and what's explicitly excluded — without having to ask. Kept alongside the codebase and updated whenever scope actually changes, it gives any future editor — human or AI agent — the same starting context it gives you now.
| Version | Data | What it adds |
|---|---|---|
app_DEMO.html (online) | Example data embedded in the file (__appData), kept in memory only: a reload brings the example back | Welcome dialog for visitors; nothing is saved |
app_LOCAL.html (on the user's computer) | The user's own data, written back into the same HTML file | File operations: Autorizar edición, Guardar cambios, Guardar copia .html, Exportar / Importar .json |
Both share the same screens, rules and calculations. Everything below applies to both unless a part is marked Local only. The local version is rebuilt from the demo, so the demo is the reference.
The application currently stores all data inside the HTML file itself, with no server and no callable actions — everything happens through direct DOM manipulation in the browser. Defining a proper action and read API is the foundation for reliable, testable, and maintainable operation of the product, whatever triggers a given action.
This document uses English terms for readability. Below is the mapping to the exact names shown in the app's own UI, so nothing gets lost in translation when cross-checking against the code or the screens.
| This document | Actual app label |
|---|---|
| Invoices screen | Facturación |
| Expenses screen | Gastos |
| VAT screen | IVA |
| Income tax screen | IRPF |
| Annual view | Resumen anual |
| Q1 / Q2 / Q3 / Q4 | 1T·Ene–Mar / 2T·Abr–Jun / 3T·Jul–Sep / 4T·Oct–Dic |
| Invoice / Expense | Factura / Gasto |
| National invoice / Tax-exempt invoice | Factura nacional (esp) / Factura exenta de impuestos (ext, foreign clients) |
| Paid / Pending | Cobrada / Pendiente |
The API is organized into four functional layers.
| Layer | Role | Applied to this product |
|---|---|---|
| Action API | Exposes each user capability as a discrete, callable operation with typed parameters | create_invoice, update_invoice, delete_invoice, set_invoice_paid, create_expense, update_expense, delete_expense, add_year, delete_year |
| Search / Retrieval API | Queries app state in a form a caller can consume directly | Dashboard totals, invoice/expense lists filtered by year or quarter, IVA/IRPF quarterly and annual figures |
| Identity & Permissions API | Confirms who is calling and what they're allowed to do | Ties every action to the authorized ledger file/session; blocks actions the caller isn't allowed to run |
| Notification / State-Change API | Reports events back to the caller in real time | Confirms a save succeeded, a record was deleted (with undo), a date looks wrong, or an operation failed — replacing today's toasts, warnings and alert() popups |
Design rules that apply across all four layers: actions must be atomic and composable, permission checks must live server-side (not only in UI logic), every action returns a structured success/failure result, and every state-changing action is logged consistently regardless of what triggered it.
addFact(), updateFact(), deleteFact(), toggleCobrada(), addGasto(), addGastoIva(), updateGasto(), deleteGasto(), the mobile forms (mSaveInv(), mSaveGasto()), addYear() or deleteYearConfirm() must have a corresponding action with a name, a typed parameter list, and a defined return shape.restore_* action or a soft delete).status (success / error), a machine-readable code on error, and a short human-readable message.alert()/confirm()/prompt() calls) with structured events any caller can render its own way.markChanged() / markSaved() logic, so a caller always knows if there are unsaved changes.The demo's addFact(type) / updateFact(id, field, value) / deleteFact(id) functions and the mobile form mSaveInv() map to one action family. Below is create_invoice, using the field names of the app's own data model — any caller, a script, an internal tool, or another integration, uses this shape.
{
"name": "create_invoice",
"description": "Creates a new invoice (factura) in the currently open ledger year.",
"parameters": {
"type": "object",
"properties": {
"type": { "type": "string", "enum": ["esp", "ext"], "description": "esp = nacional (IVA + optional retention) · ext = exenta (foreign client)" },
"num": { "type": "string", "description": "Invoice number" },
"fecha": { "type": "string", "pattern": "^\\d{2}/\\d{2}/\\d{4}$", "description": "DD/MM/AAAA, in the open year" },
"quarter": { "type": "integer", "enum": [1, 2, 3, 4], "description": "Quarter it is declared in (trim). Defaults to the quarter of fecha" },
"cliente": { "type": "string" },
"concepto": { "type": "string" },
"base": { "type": "number", "description": "Base imponible, net amount before IVA" },
"iva": { "type": "number", "enum": [0, 4, 10, 21], "description": "Only for esp. Allowed rates per year: see Section 8" },
"ret": { "type": "boolean", "default": true, "description": "Only for esp: apply the IRPF retention (15 %)" },
"cobrada": { "type": "boolean", "default": false }
},
"required": ["type", "num", "fecha", "cliente", "concepto", "base"]
},
"returns": {
"type": "object",
"properties": {
"status": { "type": "string", "enum": ["success", "error"] },
"invoice_id": { "type": "string" },
"warnings": { "type": "array", "items": { "type": "string" }, "description": "e.g. date_outside_quarter" },
"code": { "type": "string" },
"message": { "type": "string" }
}
}
}
The corresponding read action, get_dashboard_summary, would return the same totals renderDashboard() computes today — as structured data instead of rendered HTML.
Mapping from the app's current in-browser functions to the API actions this design proposes.
| Screen | Current function(s) | Proposed API action |
|---|---|---|
| Facturación | addFact(), updateFact(), deleteFact(), toggleCobrada(); mobile: mOpenInv() + mSaveInv() | create_invoice, update_invoice, delete_invoice, set_invoice_paid |
| Facturación · Cálculo del salario | saveSalarioClientes() | set_salary_clients |
| Gastos | addGasto(), addGastoIva(), addIvaRate(), updateGasto(), deleteGasto(); mobile: mOpenGasto() + mSaveGasto() | create_expense, update_expense, delete_expense |
| IVA | renderIva(), renderIvaAnual(), saveIvaNota(), saveIvaPagado(), compensation checkbox and amount | get_iva_summary, set_iva_note, set_iva_paid, set_iva_compensation |
| IRPF | renderIrpf(), renderIrpfAnual(), saveIrpfNota(), saveIrpfPagado() | get_irpf_summary, set_irpf_note, set_irpf_paid |
| Dashboard | renderDashboard() | get_dashboard_summary |
| Year management | addYear(), deleteYearConfirm(), setYear() | add_year, delete_year, list_years |
| File operations (Local only) | abrirArchivo(), guardarEnArchivo(), guardarJSON(), importarDatos() | save_ledger, export_ledger_backup, import_ledger_data |
Amortization has no screen or actions of its own: depreciable assets are entered as normal expenses in category 10, Otros desgravables, with the type written in the Objeto column (e.g. "Bienes amortizables"). No amortization actions are needed.
The app has no backend at all — the demo reads and writes the __appData JSON embedded in the HTML file, and the local version also rewrites that JSON into the file on save. Every function above needs to move behind the typed action interface before any external caller can use it.
__appData)One object per year, yr_2026, plus _years (the list of years). The .json backup of the local version uses the same content under cb_2026 / years.
| Field | Content |
|---|---|
facturas[] | id, type (esp / ext), num, fecha (DD/MM/AAAA), cliente, concepto, base, iva (%), ret (bool), cobrada (bool), trim (1–4) |
gastos[] | id, cat (one of the 10 IRPF categories), num, fecha, proveedor, concepto, base, iva (%), en303 (bool), trim, objeto (category 10 only) |
iva_notes[4], irpf_notes[4] | Notes per quarter |
iva_anual_nota, irpf_anual_nota | Notes of the Resumen anual |
iva_pagado[4], irpf_pagado[4] | Amount actually paid per quarter (IRPF: used as "pagos anteriores") |
iva_compensar_on[4], iva_compensar_amt[4] | "Aplicar compensación" checkbox and amount per quarter |
salario_clientes | Client(s) used for the salary estimate: names joined with +, or Todas |
non-obvious rule trim is stored, not derived: an invoice or expense is declared in the quarter it was saved in, which can differ from the quarter of its date (the app only warns — see Date rules).
Example: a caller records a new invoice as "paid." This shows how the four layers from Section 2 work together for a real action.
sequenceDiagram participant Caller participant IdentityAPI as Identity & Permissions API participant ActionAPI as Action API participant StateAPI as Notification / State-Change API Caller->>IdentityAPI: Confirm caller is authorized on this ledger IdentityAPI-->>Caller: Authorized Caller->>ActionAPI: set_invoice_paid(invoice_id, true) ActionAPI->>ActionAPI: Validate invoice exists and belongs to loaded ledger ActionAPI-->>StateAPI: Emit state-change event StateAPI-->>Caller: status: success, dirty_state: true
This flow works identically for any caller — a script, an internal tool, or a test harness — because the API layers don't change based on who is calling them.
Organized the way the app itself is laid out — top to bottom, screen by screen — so it reads alongside the UI. The values that depend on Hacienda are collected again in Section 8, for the yearly check.
User info area. Account name and a "DEMO" badge, plus an info icon. In the demo its tooltip presents the app: it organizes the accounting of autónomos in Spain, visitors can try it by adding invoices or expenses, and the assistants are examples of what AI collaboration can do. In the local version it is the onboarding text: the app runs entirely locally; to start editing, click "Autorizar edición," pick the saved copy of the HTML file, and every change is written back into that same file; a JSON backup is recommended.
Always 6 year slots, starting at the first year with data. Once the current year would fall outside them, the strip moves forward (the oldest year leaves), so the current year is always visible. States: active (selected), has data, future (disabled), or empty. On mobile only years that can be opened are shown. Clicking a year calls setYear(yr).
dead code addYear(), deleteYearConfirm() and pedirAnoInicial() exist in the code but aren't wired to any button. There is currently no way to add or delete a year through the UI — the strip only switches between years that already exist in the file. If rebuilt, this is a real gap to close deliberately.
A cross-cutting pattern — these surface from more than one screen. All the custom ones are built with the design system's Dialog and Toast.
alert()/confirm()/prompt(), no custom UIThe native ones are blocking and unstyled. A rebuilt/API-backed version should route them through the Notification/State-Change API instead, so a caller can render its own non-blocking UI; the custom dialogs above are already the right shape.
The same rules in every form (desktop tables, mobile forms):
trim).
Header date: today for the current year, 31 Dec for past years.
getSalarioMainClientMonthly().Periods: Resumen anual (read-only: no adding or deleting) · 1T–4T.
| Type | IVA | Retention | Total |
|---|---|---|---|
| esp (nacional) | 0/4/5/10/21% (default 21%) | Optional, flat 15% (on by default) | base + IVA − retention |
| ext (exenta, foreign client) | None | None | base |
+, or Todas for all invoices. Its explanation is in the ⓘ next to the title.Numbered 1–10 everywhere except the dashboard chart. Each has an ⓘ with its rule (text only — see below).
1 reta Seguridad Social / RETA
2 arr Arrendamientos y cánones
3 sum Suministros (30% cap)
4 osum Otros suministros
5 serv Otros servicios exteriores
6 trans Transporte y viajes
7 mant Manutención (26,67 € / 48,08 € día)
8 otros Otros consumos de explotación
9 oduc Otros gastos deducibles (5% / 2.000 €)
10 odeg Otros desgravables (+ Objeto column)
Expenses can be grouped by IRPF category ("Por cat. IRPF") or by IVA rate ("Por % IVA"). The expenses themselves don't change, only how they're grouped. Adding from a category opens the form with that category; adding from a rate opens it with that rate (in category 8).
fixRetaIva()).Deadlines: 20 Apr · 20 Jul · 20 Oct · 30 Jan (year+1). A quarter that hasn't started shows "—".
| Box | Meaning | Formula (that quarter) |
|---|---|---|
| c.01 | Base imponible | Σ base of esp invoices |
| c.03 | IVA repercutido | Σ base × iva% (esp invoices) |
| c.28 | Base gastos deducibles | Σ base of expenses with 303 on (IVA > 0, not RETA) |
| c.29 | IVA soportado | Σ base × iva% (same expenses) |
| c.120 | Operaciones no sujetas | Σ base of ext invoices |
Result: subtotal = c.03 − c.29; resultado = subtotal − compensar (if "Aplicar compensación" is on — the amount is typed by the user, not carried over automatically). Positive → "A ingresar este trimestre" and the "IVA pagado" field appears; negative → "A compensar próximo trimestre"; zero → "Sin actividad con IVA."
inconsistency With no national invoices in the quarter, a banner says "Sin facturación española → IVA soportado no deducible este trimestre," but the calculation still deducts it. See Section 8.
Resumen anual (Modelo 390): the five figures per quarter; a quarter whose deadline hasn't passed shows "Sin resultado hasta que termine el plazo de declaración". Total: "Resultado anual → Mod. 390". Notes per quarter and for the year.
Same deadlines as IVA. Figures are cumulative from 1T, not quarter-only. On top, one card per quarter with the cumulative amount paid.
labeling quirk The 1T card reads "IRPF abonado (1T)" while 2T–4T read "IRPF acumulado" — every card actually shows the same thing (cumulative paid through that quarter). Worth resolving, not carrying over, if rebuilt.
| Box | Meaning | Formula (cumulative) |
|---|---|---|
| c.01 | Ingresos íntegros | Σ base, all invoices, 1T→now |
| c.02 | Gastos deducibles | Σ base, all expenses, 1T→now |
| c.03 | Rendimiento neto | c.01 − c.02 |
| c.05 | 20% s/ rendimiento | c.03 × 20% |
| c.07 | Retenciones | Σ base × 15% (invoices with retention) |
| c.08 | Pagos anteriores | Σ "IRPF pagado" of the previous quarters |
Result: cuota = max(0, c.05 − c.07 − c.08) → "A ingresar este trimestre" or "Sin pago fraccionado este trimestre". Already floored — no negative state, unlike IVA. Resumen anual: "Pagado a cuenta → Mod. 100".
Same data and rules; only the way of working changes. On desktop you type straight into the tables; on mobile you add and review through full-screen dialogs.
Every figure below comes from tax or Social Security rules and is written into the app's code or texts. Each January (before the 4T returns, due 30 Jan), check them against the official sources and update the app if anything changed. Status as checked in November 2026.
ok matches the 2026 reference check to review, partly covered or not confirmed
This list is a maintenance aid, not tax advice. When in doubt, confirm with a gestoría or the Agencia Tributaria.
| Rule | In the app | 2026 reference | Status |
|---|---|---|---|
| IVA rates | 0 · 4 · 5 · 10 · 21% in every IVA list (IVA_RATES, mobile forms) | General 21%, reduced 10% and 4%, and 0%. The 5% was a temporary rate (energy measures after the war in Ukraine) and is no longer in force: keep it only for past years that used it | check 5% for past years only |
| Deadlines 303 | 20 Apr · 20 Jul · 20 Oct · 30 Jan (TRIM_DEADLINES, dashboard cards) | 1–20 Apr, Jul, Oct; 4T 1–30 Jan | ok |
| Modelo 390 (annual) | Resumen anual "→ Mod. 390" | 1–30 Jan of the following year | ok |
| Box numbers of the 303 | c.01, c.03, c.28, c.29, c.120 | Fixed by the yearly Orden that approves the form | check |
| Foreign (ext) invoices | No IVA, no retention, reported in c.120 | Services to foreign clients located outside Spain; for EU business clients, Modelo 349 may also apply (not covered by the app) | check |
| IVA soportado without national invoices | Banner says "no deducible" but the 303 still deducts it | Confirm which applies to costs linked to foreign services | check inconsistent |
| RETA and IVA | RETA never carries IVA, never in the 303 | Social Security fees carry no IVA | ok |
| Rule | In the app | 2026 reference | Status |
|---|---|---|---|
| Retention on invoices | Flat 15% (invoice total, c.07, IRPF retenido, Total factura) | 15% general. 7% for new autónomos: the year of alta and the two following, under conditions | check 7% not supported |
| Modelo 130 rate | 20% of the cumulative net income, minus retentions and previous payments | Same | ok |
| Modelo 130 obligation | Always calculated | Professionals with ~70% or more of the previous year's income under retention don't have to file it (check the exact threshold) | check |
| Deadlines 130 | Same as 303 | 1–20 Apr, Jul, Oct; 4T 1–30 Jan | ok |
| Box numbers of the 130 | c.01, c.02, c.03, c.05, c.07, c.08 | Fixed by the form's Orden | check |
| The 10 expense categories | CATS: names, order, tooltips; box numbers of the Modelo 100 in some tooltips (transporte → c.198, manutención → c.186) | The Modelo 100 can rename, split or add categories and boxes | check |
| Rule | In the app | 2026 reference | Status |
|---|---|---|---|
| 3 · Suministros of the home | "Límite: 30% del % de m² afectos" | 30% of the proportion of the home used for the activity — not confirmed this time | check |
| 7 · Manutención | 26,67 €/día España · 48,08 €/día extranjero; paid by card | Without overnight stay: 26,67 € / 48,08 €. With overnight stay: 53,34 € / 91,35 €. Paid by electronic means | check overnight limits missing |
| 9 · Gastos de difícil justificación | 5% of net income, max 2.000 € | 5%, max 2.000 € (simplificada) | ok |
| 10 · Amortización | "cuota anual 25%" | Simplified table: computers and software 26%, max 10 years | check 25% vs 26% |
| 1 · RETA | Fee typed by the user; "sin tope, deducible al 100%" | 2025 tables extended for 2026 (15 tramos, about 200–590 €/month); MEI up to 0,9% | check new fee each year |
| Other "sin tope" texts | Categories 2, 4, 5, 8 | Review the wording with the category list | check |
Sections 1–8 describe an API that could sit in front of the existing local, file-based app. Hosting it for real — a backend other devices could call — introduces problems that don't exist in the single-file model today.
"Authorized ledger" (Section 3) needs to become a real credential — an API key or session, since today there's nothing to log into. Whether this stays single-user is a decision to state explicitly, not leave implied.
Two open sessions editing the same data today silently overwrite each other on save. A host needs either optimistic concurrency control (reject a write if the data changed since it was read) or real-time sync — or at minimum, a way to tell a caller "this changed elsewhere" instead of losing data silently.
Only create_invoice has a full JSON schema today. Every other action named in the Demo Mapping table needs the same treatment — parameters, types, required fields, return shape — before this is truly build-ready. The data model in Section 5 gives the field names.
Actions are required to return a machine-readable code on failure, but no enumerated list of codes exists yet. The alerts catalogued above are the closest thing to a starting list — several map naturally (e.g. "Formato no reconocido" → invalid_import_format, the Atención! messages → invalid_date_format, date_does_not_exist, warning date_outside_quarter).
The Hacienda values in Section 8 are written into the code today. A hosted version should keep them in one configuration per tax year (rates, retention, limits, deadlines, categories), so updating them is a data change and past years keep the rules that applied to them.
Today's entire ledger lives as one JSON blob (__appData) embedded in the HTML file. The local version's "Exportar .json" button is the natural migration input — it already contains everything a hosted store would need, structured the way the app understands it (only the key names differ: cb_2026 instead of yr_2026).
Today's only backup is a manual "Exportar .json" click. A host holding real tax records needs automatic periodic backups and a version history — while the manual export likely stays available too, as a user-controlled backup independent of whatever the host does automatically.
This functional design now exists in more than one place — the app itself and this page, at minimum — with nothing keeping them in sync automatically. This isn't theoretical: a caveat about a dead salary function was correctly written once, then dropped during a later rewrite, and had to be manually restored after being spotted on review. Worth deciding which format is canonical before a real build starts.