Functional design · Nov 2026
Contabilidad APP — functional design

1. Purpose & scope

Audience

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.

What it's for

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.

Two versions of the same app

VersionDataWhat it adds
app_DEMO.html (online)Example data embedded in the file (__appData), kept in memory only: a reload brings the example backWelcome 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 fileFile 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.

In scope

  • Every capability currently reachable only through the UI — add/update/delete invoice, add/update/delete expense, mark an invoice paid/pending, manage years, save/open/import/export the ledger file — expressed as typed, callable operations.
  • The read/query surface: dashboard totals, quarterly and annual IVA/IRPF figures, invoice and expense lists.
  • Identity and permission rules for those operations.
  • Structured success/failure reporting back to the caller.
  • The tax rules the app applies, and which of them depend on Hacienda and must be checked every year (Section 8).

Out of scope

  • Any change to the visual interface — the existing screens keep working exactly as they do today; this API sits underneath them. The interface is built on the Mi Contabilidad Design System (Storybook + Figma library "Mi Contabilidad DS"), documented there.
  • The two assistants — Acceso fácil and Asistente Inteligente. They read the same figures and use the same rules as the screens, but their design is covered separately.
  • Multi-user or multi-account support — the product is single-user, file-based, and this design reflects that as-is.

Why this matters

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.

Terminology — English ↔ Spanish

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 documentActual app label
Invoices screenFacturación
Expenses screenGastos
VAT screenIVA
Income tax screenIRPF
Annual viewResumen anual
Q1 / Q2 / Q3 / Q41T·Ene–Mar / 2T·Abr–Jun / 3T·Jul–Sep / 4T·Oct–Dic
Invoice / ExpenseFactura / Gasto
National invoice / Tax-exempt invoiceFactura nacional (esp) / Factura exenta de impuestos (ext, foreign clients)
Paid / PendingCobrada / Pendiente

2. API layers overview

The API is organized into four functional layers.

LayerRoleApplied to this product
Action APIExposes each user capability as a discrete, callable operation with typed parameterscreate_invoice, update_invoice, delete_invoice, set_invoice_paid, create_expense, update_expense, delete_expense, add_year, delete_year
Search / Retrieval APIQueries app state in a form a caller can consume directlyDashboard totals, invoice/expense lists filtered by year or quarter, IVA/IRPF quarterly and annual figures
Identity & Permissions APIConfirms who is calling and what they're allowed to doTies every action to the authorized ledger file/session; blocks actions the caller isn't allowed to run
Notification / State-Change APIReports events back to the caller in real timeConfirms 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.

3. Functional requirements per layer

Action API

  • Every capability currently triggered by 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.
  • Actions must validate input server-side rather than relying on the browser form to catch it — including the date rules in Section 7 (format, year, quarter).
  • Actions must be idempotent-safe where the current UI already assumes it.
  • Deletions must be reversible for a short time, as the "Deshacer" toast allows today (a restore_* action or a soft delete).
  • Every action returns status (success / error), a machine-readable code on error, and a short human-readable message.

Search / Retrieval API

  • Must support the same filters the UI already offers: by year, by quarter (or the whole year), by invoice status (paid/pending), and expenses grouped by IRPF category or by IVA rate.
  • Must return the same computed totals the screens show today, rather than raw rows the caller has to recompute.
  • Must support a single-item lookup by ID in addition to list queries.

Identity & Permissions API

  • Confirms that a request is operating on the authorized, currently-open ledger.
  • Must reject any action targeting a year or record that isn't part of the currently loaded file.
  • Must reject writes to read-only views: the Resumen anual of Facturación and Gastos can't add or delete records.

Notification / State-Change API

  • Must replace today's feedback (toasts, the Atención! date warning and the remaining alert()/confirm()/prompt() calls) with structured events any caller can render its own way.
  • Must expose a "dirty state" flag equivalent to the local version's markChanged() / markSaved() logic, so a caller always knows if there are unsaved changes.

4. Example action schema

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.

5. Demo app mapping

Mapping from the app's current in-browser functions to the API actions this design proposes.

ScreenCurrent function(s)Proposed API action
FacturaciónaddFact(), updateFact(), deleteFact(), toggleCobrada(); mobile: mOpenInv() + mSaveInv()create_invoice, update_invoice, delete_invoice, set_invoice_paid
Facturación · Cálculo del salariosaveSalarioClientes()set_salary_clients
GastosaddGasto(), addGastoIva(), addIvaRate(), updateGasto(), deleteGasto(); mobile: mOpenGasto() + mSaveGasto()create_expense, update_expense, delete_expense
IVArenderIva(), renderIvaAnual(), saveIvaNota(), saveIvaPagado(), compensation checkbox and amountget_iva_summary, set_iva_note, set_iva_paid, set_iva_compensation
IRPFrenderIrpf(), renderIrpfAnual(), saveIrpfNota(), saveIrpfPagado()get_irpf_summary, set_irpf_note, set_irpf_paid
DashboardrenderDashboard()get_dashboard_summary
Year managementaddYear(), 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.

Data model (__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.

FieldContent
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_notaNotes 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_clientesClient(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).

6. End-to-end usage flow

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.

7. Domain & calculation logic (tax rules)

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.

Header

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.

File buttons (Local only)

  • "Guardar copia .html" — opens a dialog offering the current version with data, or a blank version to start fresh.
  • "Exportar .json" — downloads the full data set as JSON.
  • "Importar .json" — a hidden file input; selecting a file replaces the working data.
  • "Autorizar edición" — opens the instructions dialog (Spanish only): select the previously-downloaded .html file, and keep a .json backup. "Continuar" opens the browser's file picker (File System Access API); "Cancelar" or Escape closes it with nothing granted.
  • "✓ Guardado" / "Guardar cambios" — writes changes back; turns orange while there are unsaved changes.

Year strip special logic

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.

Alerts & dialogues

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.

Custom dialogs and feedback

  • Welcome dialog (on page load) — bilingual (ES default, EN switch), explains the app. Demo: invites visitors to try it and gives the contact email. Local: notes the app reflects "the rules in force at the time," footnoted (*) to a disclaimer — a portfolio demo, not a certified product; using it for real accounting is at the user's own risk. "Continuar" or Escape closes it. Full screen on mobile.
  • Atención! — the date warning (see Date rules). A small dialog with "Entendido"; it opens over everything, including the mobile forms.
  • Toast with "Deshacer" — after deleting an invoice or expense ("Factura 411 eliminada. Deshacer"), and after saving from a mobile form ("Factura F-099 guardada en el 3T 2026 como pendiente de cobro.").
  • Info tooltips (ⓘ) — every section and card with rules has one; they open on hover, focus or tap, and align to the button's side of the screen.
  • Instructions dialog and "Guardar copia .html" dialog (Local only) — see Header.

Native browser dialogues — alert()/confirm()/prompt(), no custom UI

  • Custom IVA rate (Gastos · Por % IVA) — "Introduce el % de IVA que quieres añadir" goes through a raw prompt. The new expense is created in category 8, Otros consumos de explotación: change the category afterwards if it's something else.
  • Delete-year confirmation and first-year prompt (dead code) — would name exactly how many invoices/expenses will be lost, if ever wired to a button.
  • Local only: browser support check ("Tu navegador no soporta esta función. Usa Chrome 86+."), save-before-authorize guard, save/parse failures ("Error: marcador no encontrado."), import results ("Formato no reconocido." / "✓ Datos importados. Guarda el archivo para conservarlos."), and the unsaved-changes prompt when closing the page.

The 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.

Date rules

The same rules in every form (desktop tables, mobile forms):

  • Format DD/MM/AAAA. Typed dates are normalized (1/9 → 01/09/2026). Phones and tablets use the native date picker instead.
  • The year is always the year selected in the strip. Typing 2025 or 2027 while 2026 is open gives 2026.
  • An impossible day moves to the last day of the month (31/06 → 30/06).
  • Date outside the quarter → Atención! "Revise que el trimestre seleccionado es el correcto ya que la fecha … no coincide." It's a warning, not a block: the record stays in the chosen quarter (trim).
    • Desktop: shown after editing the date in the table (the record is already saved).
    • Mobile forms: shown before saving; the form stays open to correct the date or the quarter. Guardar again with no change saves.
  • Two more messages exist for dates that can't be read: wrong format, and a day that doesn't exist.

Navigation

Dashboard Facturación Gastos IVA IRPF

Desktop: a fixed sidebar on the left. Mobile: a section menu (dropdown) in the header, in the colour of the current section. Both call goTo(sectionId) — the app's single routing function — which swaps the visible section, updates the active highlight, and re-renders from __appData.

Inside each section, a period selector: tabs on desktop (Resumen anual · 1T · 2T · 3T · 4T), a dropdown on mobile.

Mapping to the API: today each section re-renders directly from local state. Once the Section 3 layers exist, each section should call its read action on entry instead — Dashboard → get_dashboard_summary, Facturación → an invoice-list read — and every button inside should call the matching action instead of mutating __appData in place.

Dashboard

Header date: today for the current year, 31 Dec for past years.

  • "Salario neto del mes." An estimate for the current month: the base of the previous month's invoices from the configured client(s) (Facturación · Cálculo del salario), minus the base of all the previous month's expenses. Independent of whether invoices are paid. January uses December of the previous year. Past years show December. Served by getSalarioMainClientMonthly().
  • "Previsión de ahorro mensual." 12% of the salary figure above, floored at 0.
  • "IVA a pagar" / "IRPF a pagar" cards. Clickable (open the section). They always show the first quarter whose deadline hasn't passed, in three states: quarter in progress ("en curso · Previsión", or "Sin actividad" for IVA), filing window open ("vence 20 de octubre"), year closed ("Año 2026 cerrado", after 30 Jan). Same formulas as the IVA and IRPF screens; IVA shows 0 when the result is negative.
  • "Comparativa Ingresos · Gastos" line chart — month by month, paid invoices only against all expenses (base).
  • "Comparativa salario neto" bar chart — the monthly salary estimate of this year against the previous year.
  • Both charts have "Ver datos en tabla", the same figures as a table (accessibility).
  • "Distribución del gasto" — the whole year, all 10 categories (even at 0%), largest first, as % of total expenses (base).
  • "Últimas facturas" — the 6 most recent invoices by date; the paid/pending dot is clickable. Its ⓘ explains that the dot toggles the status and updates every total and chart.

Facturación

Periods: Resumen anual (read-only: no adding or deleting) · 1T–4T.

Insights on top

  • Total facturado — base amount, national + foreign, for the period in view.
  • Cobrado — base amount of paid invoices, period in view.
  • Pendiente de cobro non-obvious rule — accumulates every unpaid invoice from 1T through the selected quarter, plus every unpaid invoice from every previous year. A running "money owed to me" figure, not a quarter snapshot.
  • IRPF retenido — sum of the 15% retentions withheld, period in view.

Two tables: Facturas nacionales · Facturas exentas de impuestos

TypeIVARetentionTotal
esp (nacional)0/4/5/10/21% (default 21%)Optional, flat 15% (on by default)base + IVA − retention
ext (exenta, foreign client)NoneNonebase
  • Under each table: Total (neto). Under both: the grand total and the Cobrada/Pendiente legend.
  • Pendiente/Cobrada dot flips the status instantly and feeds the Dashboard and the Pendiente de cobro card. Every new invoice starts as Pendiente.
  • "Cálculo del salario" — the client(s) that drive the salary estimate, stored per year: several names joined with +, or Todas for all invoices. Its explanation is in the ⓘ next to the title.

Gastos

Insights on top

  • Total gastos — base amount, all expenses in view.
  • IVA soportado — total IVA, regardless of 303 status.
  • IVA incluido 303 — only expenses checked for the quarterly return (in Resumen anual: the whole year).
  • Total gastado — base + IVA.

The 10 IRPF categories

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)

Two views, same data

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).

Por cat. IRPF Por % IVA
  • informative only The caps and rates in the category tooltips (30% suministros, manutención limits, 5%/2.000 € difícil justificación, 25% amortización…) are reference text only — the app doesn't calculate or enforce any of them. They are listed in Section 8 for the yearly check.
  • Seguridad Social / RETA never carries IVA enforced: choosing it sets IVA to 0% (locked, with the hint "La cuota de autónomos no lleva IVA.") and turns the 303 checkbox off. The data is also corrected on save (fixRetaIva()).

The 303 checkbox

  • Disabled — IVA rate is 0%, or category 1 (RETA).
  • Enabled — otherwise; on by default for new expenses with IVA.
  • When the quarter has no national invoices, the IVA screen shows a warning (see IVA) — the checkbox still works.

IVA (Modelo 303 · 390)

Deadlines: 20 Apr · 20 Jul · 20 Oct · 30 Jan (year+1). A quarter that hasn't started shows "—".

BoxMeaningFormula (that quarter)
c.01Base imponibleΣ base of esp invoices
c.03IVA repercutidoΣ base × iva% (esp invoices)
c.28Base gastos deduciblesΣ base of expenses with 303 on (IVA > 0, not RETA)
c.29IVA soportadoΣ base × iva% (same expenses)
c.120Operaciones 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.

IRPF (Modelo 130 · 100)

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.

BoxMeaningFormula (cumulative)
c.01Ingresos íntegrosΣ base, all invoices, 1T→now
c.02Gastos deduciblesΣ base, all expenses, 1T→now
c.03Rendimiento netoc.01 − c.02
c.0520% s/ rendimientoc.03 × 20%
c.07RetencionesΣ base × 15% (invoices with retention)
c.08Pagos 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".

Mobile (screens up to 1023px)

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.

  • Dashboard — one column: Comparativa Ingresos · Gastos, Últimas facturas, then the salary, savings, IVA and IRPF cards. The salary bar chart and Distribución del gasto aren't shown (Distribución appears in mobile Gastos).
  • Facturación / Gastos — the period dropdown, summary cards with "Añadir factura / gasto", and "Ver todas las facturas / todos los gastos", which opens the list: one card per table or category, each invoice or expense as a record (Gastos keeps the Por cat. IRPF / Por % IVA toggle), grand totals at the end. Delete with the bin, undo with the toast.
  • Nueva factura / Nuevo gasto — full-screen forms. On top, a quarter dropdown: the quarter the record is saved in, starting on the quarter on screen; opened from Resumen anual it follows the date. A live total: Total factura = base + IVA − 15% retention (exenta: the base), Total gasto = base + IVA. Required fields show their error under the field. After saving, the list behind switches to the chosen quarter.
  • IVA / IRPF — the quarterly forms as on desktop; the Resumen anual becomes one block per quarter.

8. Rules that depend on Hacienda — check every year

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.

IVA

RuleIn the app2026 referenceStatus
IVA rates0 · 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 itcheck
5% for past years only
Deadlines 30320 Apr · 20 Jul · 20 Oct · 30 Jan (TRIM_DEADLINES, dashboard cards)1–20 Apr, Jul, Oct; 4T 1–30 Janok
Modelo 390 (annual)Resumen anual "→ Mod. 390"1–30 Jan of the following yearok
Box numbers of the 303c.01, c.03, c.28, c.29, c.120Fixed by the yearly Orden that approves the formcheck
Foreign (ext) invoicesNo IVA, no retention, reported in c.120Services 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 invoicesBanner says "no deducible" but the 303 still deducts itConfirm which applies to costs linked to foreign servicescheck
inconsistent
RETA and IVARETA never carries IVA, never in the 303Social Security fees carry no IVAok

IRPF

RuleIn the app2026 referenceStatus
Retention on invoicesFlat 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 conditionscheck
7% not supported
Modelo 130 rate20% of the cumulative net income, minus retentions and previous paymentsSameok
Modelo 130 obligationAlways calculatedProfessionals with ~70% or more of the previous year's income under retention don't have to file it (check the exact threshold)check
Deadlines 130Same as 3031–20 Apr, Jul, Oct; 4T 1–30 Janok
Box numbers of the 130c.01, c.02, c.03, c.05, c.07, c.08Fixed by the form's Ordencheck
The 10 expense categoriesCATS: 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 boxescheck

Expense limits (texts in the category ⓘ, not calculated)

RuleIn the app2026 referenceStatus
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 timecheck
7 · Manutención26,67 €/día España · 48,08 €/día extranjero; paid by cardWithout overnight stay: 26,67 € / 48,08 €. With overnight stay: 53,34 € / 91,35 €. Paid by electronic meanscheck
overnight limits missing
9 · Gastos de difícil justificación5% 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 yearscheck
25% vs 26%
1 · RETAFee 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" textsCategories 2, 4, 5, 8Review the wording with the category listcheck

Where to check

9. Considerations for a real hosted API

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.

Identity & auth model

"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.

Multi-window / concurrent-session sync

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.

Complete action schema catalog

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.

Error code catalog

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).

Yearly rule updates

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.

Data migration

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).

Backups & versioning

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.

Keeping the descriptions in sync real example, not hypothetical

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.