Files
accounted/lib/reports/kpi.ts
T
Jakob Wennberg 88f49c0ccc fix(bookkeeping): harden correction flow and align VAT/cashflow reports (#726)
Bundles a set of bookkeeping-correctness fixes developed together.

Correction / storno flow
- correctEntry resolves (and seeds standard BAS) accounts for the
  corrected lines BEFORE writing the storno. The old order created and
  posted the storno first, then hit AccountsNotInChartError on the
  corrected lines and had to cancel it again — leaving a voided 0 kr
  storno in the chain and permanently burning a voucher number (an
  unexplained BFNAR 2013:2 gap). It now fails fast with nothing written.
- correctEntry re-points the bank transaction and underlag from the
  reversed original to the live corrected entry, so the transaction keeps
  reading as booked (and stays correctable) and the underlag travels with
  it. recordateEntry delegates both relinks to correctEntry.
- reverseEntry (engine) clears transactions.journal_entry_id for rows
  booked by the reversed entry, so a plain storno returns the bank row to
  "Att bokföra" with a re-booking affordance. The agent paths did this
  manually; the dashboard reverse route did not.
- findUnresolvableAccounts replaces findMissingActiveAccounts in the
  categorize routes: a standard BAS account merely absent from the chart
  is seeded on demand by the engine, so pre-validation must not 400 on it
  — only unknown numbers or deactivated accounts block.
- CorrectionChain dims cancelled (0 kr) entries and labels them so they
  no longer render like a live storno.

Report accuracy
- calculateVatLiability() (lib/reports/kpi.ts) is shared by the KPI route,
  the KPI xlsx export and the MCP period-summary tool, and uses the same
  26xx accounts as the momsdeklaration (ruta 49). Reverse-charge and
  import pairs (e.g. 2614 credit + 2645 debit) net to zero instead of
  inflating the receivable (#715). VAT_OUTPUT_ACCOUNTS / VAT_INPUT_ACCOUNTS
  are derived from ACCOUNT_RUTA so the widget can never drift from the
  declaration.
- Kassaflödesanalys records erhållna aktieägartillskott (2093) as a
  financing inflow and counts överkursfond (2086/2097) toward nyemission.
  2093 was previously unmapped, so any contribution broke the 19xx
  reconciliation by exactly the contributed amount (#716). Wired through
  the report type, both PDF templates, the K3 PDF, the dashboard client
  and the årsredovisning summary type.

Agent guidance
- shared-rules: describe the real Accounted correction flow (Rätta rader /
  Rätta datum / Radera verifikat, on-demand BAS backfill) so the assistant
  stops inventing flows that don't exist.
- verifikation-draft: clearer locked-period guidance.

Tests cover all of the above (storno fail-fast + seeding + relink,
reverseEntry unlink, findUnresolvableAccounts, VAT netting and the
cashflow reconciliation cases).

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-15 10:17:44 +02:00

115 lines
3.9 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import type { IncomeStatementReport, TrialBalanceRow } from '@/types'
import { VAT_INPUT_ACCOUNTS, VAT_OUTPUT_ACCOUNTS } from '@/lib/reports/vat-declaration'
/**
* Calculate gross margin from income statement.
* Gross margin = (revenue - COGS) / revenue × 100
* COGS = class 4 expense sections (Varor och material, etc.)
*/
export function calculateGrossMargin(incomeStatement: IncomeStatementReport): number | null {
const { total_revenue, expense_sections } = incomeStatement
if (total_revenue === 0) return null
// Class 4 expenses = cost of goods sold (account prefixes 40-49)
const cogs = expense_sections
.filter((s) => s.rows.some((r) => r.account_number.startsWith('4')))
.reduce((sum, s) => sum + s.subtotal, 0)
return Math.round(((total_revenue - cogs) / total_revenue) * 10000) / 100
}
/**
* Calculate cash position from trial balance rows.
* Sums closing balances for accounts matching 19xx (bank + cash accounts).
*/
export function calculateCashPosition(rows: TrialBalanceRow[]): number {
const cashRows = rows.filter((r) => r.account_number.startsWith('19'))
const total = cashRows.reduce(
(sum, r) => sum + (r.closing_debit - r.closing_credit),
0
)
return Math.round(total * 100) / 100
}
/**
* Calculate net VAT liability (positive = att betala) or receivable
* (negative = att återfå) from trial balance rows.
*
* Uses the same 26xx accounts as the momsdeklaration so the result mirrors
* ruta 49: output VAT (rutor 1012, 3032, 6062) input VAT (ruta 48).
* Reverse-charge and import pairs (e.g. 2614 credit + 2645 debit) therefore
* net to zero instead of inflating the receivable (#715).
*
* `accounts` overrides the default list (user KPI preferences); accounts in
* the 264x range count as input VAT, all other 26xx accounts as output VAT.
*/
export function calculateVatLiability(
rows: TrialBalanceRow[],
accounts?: string[]
): number {
const vatAccounts =
accounts && accounts.length > 0
? accounts
: [...VAT_OUTPUT_ACCOUNTS, ...VAT_INPUT_ACCOUNTS]
const outputVat = rows
.filter(
(r) =>
vatAccounts.includes(r.account_number) &&
r.account_number.startsWith('26') &&
!r.account_number.startsWith('264')
)
.reduce((sum, r) => sum + (r.closing_credit - r.closing_debit), 0)
const inputVat = rows
.filter(
(r) =>
vatAccounts.includes(r.account_number) && r.account_number.startsWith('264')
)
.reduce((sum, r) => sum + (r.closing_debit - r.closing_credit), 0)
return Math.round((outputVat - inputVat) * 100) / 100
}
/**
* Calculate revenue growth between two periods.
* Returns percentage or null if no previous period data.
*/
export function calculateRevenueGrowth(
currentRevenue: number,
previousRevenue: number | null
): number | null {
if (previousRevenue === null || previousRevenue === 0) return null
return Math.round(((currentRevenue - previousRevenue) / previousRevenue) * 10000) / 100
}
/**
* Calculate expense ratio from income statement.
* Expense ratio = total_expenses / total_revenue × 100
*/
export function calculateExpenseRatio(incomeStatement: IncomeStatementReport): number | null {
const { total_revenue, total_expenses } = incomeStatement
if (total_revenue === 0) return null
return Math.round((total_expenses / total_revenue) * 10000) / 100
}
/**
* Calculate average payment days from paid invoices.
* Returns null if fewer than 5 invoices with paid_at data.
*/
export function calculateAvgPaymentDays(
paidInvoices: { invoice_date: string; paid_at: string }[]
): number | null {
if (paidInvoices.length < 5) return null
const totalDays = paidInvoices.reduce((sum, inv) => {
const invoiceDate = new Date(inv.invoice_date)
const paidDate = new Date(inv.paid_at)
const days = Math.floor(
(paidDate.getTime() - invoiceDate.getTime()) / (1000 * 60 * 60 * 24)
)
return sum + Math.max(0, days)
}, 0)
return Math.round(totalDays / paidInvoices.length)
}