Files
accounted/lib/invoices/late-payment-interest.ts
T
Jakob WennbergandClaude Opus 4.8 c74b19df1b Accounted rebrand + swarm-skill cleanup + bank-reconciliation fixes (#643)
* feat(reconciliation): close the bank-feed loop on voucher links and re-tag mis-typed opening balances

Two related fixes to bank reconciliation correctness:

1. Auto-reconcile on voucher link. Linking an invoice or supplier invoice to
   an existing voucher previously advanced only the invoice — the bank
   transaction that paid it kept sitting in the Transactions inbox with a null
   journal_entry_id. linkInvoiceToVoucher / linkSupplierInvoiceToVoucher now
   call autoReconcileTransactionForLinkedVoucher (lib/reconciliation), which
   links the bank transaction to the same verifikat when exactly one unbooked
   line matches it. Best-effort and post-commit: a failure here never fails the
   link. The result surfaces reconciledTransactionId; the inbox row leaves the
   list and the UI shows link_success_tx_reconciled.

2. Re-tag mis-typed opening balances. getReconciliationStatus and the GL-line
   matching RPCs identify a cash account's ingående balans solely by
   journal_entries.source_type='opening_balance'. Companies migrated from other
   systems often booked the bank IB as an ordinary voucher (source_type
   'import' or 'manual'), so it was never excluded and surfaced as a phantom
   reconciliation difference equal to the opening balance. Adds:
   - migration mark_entry_as_opening_balance: a GUC-gated carve-out in the
     immutability trigger plus a SECURITY DEFINER RPC that validates the entry
     (balance-sheet lines only, dated on a fiscal-period boundary), flips the
     source_type, and writes an audit row — no blanket data sweep.
   - POST /api/reconciliation/bank/mark-opening-balance + MarkOpeningBalanceSchema.
   - BankReconciliationView action to trigger it from the IB diff.

The gnubok_create_voucher executor now accepts a typed is_opening_balance flag
and derives source_type='opening_balance' only after validating class 1/2 lines
on the period start, so new IBs land correctly typed.

Covered by lib/reconciliation auto-reconcile tests, voucher-executors tests,
and a mark-entry-as-opening-balance pg-real test.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* chore: rebrand gnubok → Accounted and prune swarm agent skills

Product rebrand and skills housekeeping. No runtime behaviour change.

Rebrand: replace user-visible "gnubok" with "Accounted" across docs, READMEs,
in-code comments, doc-site content, MCP skill/resource prose, and the
gnubok-mcp package description. The MCP resource URI scheme is moved gnubok://
→ Accounted:// consistently across resource registrations, the event-type
comment, and the resource/skill tests. Deliberately preserved as stable
identifiers (NOT rebranded): the gnubok-company-id cookie, gnubok_sk_ / gnubok_inv_
token prefixes, the gnubok-mcp npm bridge name, and the AGI <gem:Programnamn>
value (kept 'gnubok' per its source comment — it is the software identifier sent
to Skatteverket and must not churn across visual rebrands).

Skills: remove the 27 swarm-* agent SKILL.md atoms (no longer used; already
absent from the agent_atom_registry in prod), refresh the remaining skill docs,
add the .claude/rules/ path-scoped rule set, and regenerate the
seed_agent_atom_bodies migration + .skill-body-manifest.json via
`npm run skills:generate` so the DB-backed skill bodies match the trimmed set.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

---------

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

156 lines
5.7 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.
/**
* Statutory late-payment interest (dröjsmålsränta) per Räntelagen §6.
*
* The default rate is Riksbankens referensränta + 8 percentage points,
* applied as a simple annual interest on the overdue amount over the
* number of days the invoice has been overdue.
*
* Formula:
* interest = overdueAmount × annualRate × overdueDays / 365
*
* We use 365 days (not 360) — this matches Swedish practice and is what
* Skatteverket / Kronofogden use in their late-payment calculators.
*
* Companies may override the statutory rate via
* `company_settings.reminder_interest_rate_override`. When an override is
* supplied we apply it directly (i.e. NOT referensränta + override) since
* that's the simpler mental model for users entering "11.5% per year".
*
* Referensränta is set by Riksbanken twice a year on January 1 and July 1.
* We hardcode the lookup table here to avoid a network call on every
* reminder; the table is small (one row per six months) and the values
* are public, durable records. Update this table when Riksbanken publishes
* a new rate.
*/
/**
* Riksbankens referensränta history. Each entry is the rate effective from
* the given date onward (until the next entry). Most recent first is more
* efficient to search but for clarity we keep them in ascending order and
* walk from newest to oldest at lookup time.
*
* Source: https://www.riksbank.se/sv/statistik/rantor-och-valutakurser/referensranta/
*
* The "annual default rate" applied to invoices is referensränta + 0.08
* (eight percentage points, Räntelagen §6).
*/
const REFERENSRANTA_HISTORY: ReadonlyArray<{ from: string; rate: number }> = [
{ from: '2022-01-01', rate: 0.0 },
{ from: '2022-07-01', rate: 0.005 },
{ from: '2023-01-01', rate: 0.025 },
{ from: '2023-07-01', rate: 0.035 },
{ from: '2024-01-01', rate: 0.04 },
{ from: '2024-07-01', rate: 0.0425 },
{ from: '2025-01-01', rate: 0.0375 },
{ from: '2025-07-01', rate: 0.0325 },
{ from: '2026-01-01', rate: 0.025 },
] as const
const LATE_PAYMENT_PREMIUM = 0.08 // 8 procentenheter per Räntelagen §6
/**
* Look up the Riksbanken referensränta that was effective on a given date.
* Returns the rate as a decimal fraction (e.g. 0.025 = 2.5%).
*
* If the requested date is before the earliest entry in the table we fall
* back to the earliest entry (this is a defensive measure — should never
* happen in practice since Accounted was launched after 2022).
*/
export function getReferensrantaAt(date: string): number {
// Walk newest-first so the first match wins.
for (let i = REFERENSRANTA_HISTORY.length - 1; i >= 0; i--) {
const entry = REFERENSRANTA_HISTORY[i]
if (date >= entry.from) {
return entry.rate
}
}
return REFERENSRANTA_HISTORY[0].rate
}
/**
* Compute the statutory annual late-payment interest rate for a given
* "from date" (typically the invoice due date). If an override is
* supplied, it is returned as-is.
*/
export function getAnnualInterestRate(fromDate: string, overrideRate?: number | null): number {
if (overrideRate !== undefined && overrideRate !== null) {
return overrideRate
}
return getReferensrantaAt(fromDate) + LATE_PAYMENT_PREMIUM
}
export interface LatePaymentInterestInput {
/** Outstanding overdue amount (the invoice total or remaining balance). */
overdueAmount: number
/** Invoice due date (YYYY-MM-DD). Interest starts the day AFTER due date. */
dueDate: string
/** Reference date for the calculation (YYYY-MM-DD). Defaults to today. */
asOfDate: string
/**
* Optional annual rate override (e.g. 0.115 for 11.5%). When supplied
* we use this verbatim instead of looking up Räntelagen §6.
*/
overrideRate?: number | null
}
export interface LatePaymentInterestResult {
/** Annual rate actually applied (decimal fraction, e.g. 0.115 = 11.5%). */
rate: number
/** Computed interest amount in SEK, rounded to 2 decimals. */
amount: number
/** Start date used for the interest calc (= dueDate). */
fromDate: string
/** Number of overdue days (positive integer, 0 if not overdue). */
days: number
}
/**
* Compute statutory late-payment interest (dröjsmålsränta).
*
* Returns the rate that was applied, the rounded amount, the from-date
* used (= dueDate), and the number of overdue days. If the invoice is
* not yet overdue the amount and days are both 0.
*
* Throws if `overdueAmount` is negative (callers should clamp to 0 if
* they want to silently no-op, but this is almost always a bug).
*/
export function calculateLatePaymentInterest(
input: LatePaymentInterestInput,
): LatePaymentInterestResult {
const { overdueAmount, dueDate, asOfDate, overrideRate } = input
if (overdueAmount < 0) {
throw new Error('overdueAmount must be non-negative')
}
const days = daysBetween(dueDate, asOfDate)
const rate = getAnnualInterestRate(dueDate, overrideRate)
if (days <= 0 || overdueAmount === 0) {
return { rate, amount: 0, fromDate: dueDate, days: 0 }
}
const raw = overdueAmount * rate * (days / 365)
const amount = Math.round(raw * 100) / 100
return { rate, amount, fromDate: dueDate, days }
}
/**
* Compute whole-day difference between two YYYY-MM-DD dates. Positive if
* `to` is after `from`. Returns 0 if `to <= from`.
*
* We use UTC midnight to avoid DST artifacts (Sweden observes DST). The
* inputs are date-only strings so timezone doesn't affect the result as
* long as we anchor both at UTC.
*/
function daysBetween(from: string, to: string): number {
const fromMs = Date.parse(`${from}T00:00:00Z`)
const toMs = Date.parse(`${to}T00:00:00Z`)
if (Number.isNaN(fromMs) || Number.isNaN(toMs)) {
return 0
}
const diff = Math.floor((toMs - fromMs) / 86_400_000)
return diff > 0 ? diff : 0
}