Files
accounted/lib/invoices/invoice-register-coverage.ts
T
MattssonandClaude Fable 5.1 fdcb7d937e feat(rot-rut): overview page, beslutsfil import, avslag reclaim, MCP list + settle (#2397)
* feat(rot-rut): overview page, beslutsfil import, avslag reclaim, MCP list + settle

Follow-up to #2239/#2360 for firms whose every invoice carries ROT/RUT.

- /invoices/rot-rut: tiles (at Skatteverket on 1513, awaiting beslut,
  refused to book, ready to request) and one row per begaran with mark
  uploaded, cancel, download and "Bokfor nekat belopp"; the Fakturor
  button links here, ?rot-rut=1 still opens the file dialog.
- Beslutsfil import from the UI through the existing import route.
- Reclaim of the share Skatteverket refused: one voucher debit 1510 /
  credit 1513 per invoice (source_type rot_rut_reclaim), CAS-attached to
  the begaran and guarded by a partial unique index; the invoice reopens
  for the refused share via invoices.deduction_reclaimed_total, with the
  customer-share formula and its SQL twin gaining the same term. The
  payment dialog and bank match then settle the reopened remaining as a
  plain 1510 clearing; a booked kontantmetod invoice is proposed accrual-
  shaped so revenue is never recognised twice. Unknown per-invoice split
  of a partial beslut is refused, never allocated.
- MCP: gnubok_list_rot_rut_payout_requests (search-only read) and
  gnubok_settle_rot_rut_payout (staged write, op settle_rot_rut_payout)
  sharing one pre-flight + settle with the dashboard match route.
- Migrations 20260907140000 (reclaim state, source_type, INSERT guard),
  20260907140100/140101 (pending_operations op type).

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01D9wvsGnvu5tHGqYnJnjnaB

* chore(rot-rut): renumber migrations after merging main

Main already carries 20260907143000 and 20260907150000, so the three
rot-rut migrations move to 20260907160000/160100/160101 to keep the
applied order monotonic (see memory: migration-version-collisions).

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01D9wvsGnvu5tHGqYnJnjnaB

* fix(rot-rut): close the reclaim gaps found by skeptics, CI and review

Skeptic refutations (#2397):
- payment-sync recomputes remaining with deduction_reclaimed_total, so a
  storno of a payment on a reopened invoice no longer strands the refused
  share (R1).
- Reclaim refused while an invoice sits in a later live begäran
  (ROT_RUT_RECLAIM_INVOICE_REREQUESTED); the overview and the MCP list hide
  the action for the same case (C2).
- A reclaimed invoice is blocked from a new begäran (DEDUCTION_RECLAIMED)
  until the reclaim voucher is reversed (R2/C3).
- Storno of the reclaim voucher syncs the invoices and the begäran back
  (rot-rut-reclaim-reversal.ts, hooked into reverseEntry) (R3).
- A paid invoice with NULL paid_amount counts its customer share as paid
  (C4). Crediting an invoice with a reclaimed share is refused on the
  dashboard, v1 and MCP paths (R4).

CI and review:
- Build: custom-coded MCP errors via Object.assign, not codedError.
- pg-real: column default for default_voucher_series_per_source_type
  re-stated with rot_rut_reclaim (20260907160200); the default test now
  re-applies the latest default migration.
- Checks: accounted-api skill regenerated (journal-entries source types).
- CodeRabbit/Superagent: per-item refused shares must reconcile with the
  request-level beslut; per-invoice reopen through the idempotent RPC
  apply_rot_rut_reclaim_invoice (20260907160300) with a resume path;
  update-stage settle failures keep the voucher id (failed_partial);
  Stockholm calendar date for the booking; existing-voucher tab uses the
  same proposal method; MCP stage checks bank_line junction rows.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01D9wvsGnvu5tHGqYnJnjnaB

* fix(rot-rut): carry the voucher id through the match outcome type; date the reclaim on the beslut

- The shared match outcome now declares journalEntryId on update-stage
  errors, matching the settle service (Core Build TS2339 on 2d6cece1a).
- The reclaim voucher is dated on the Swedish calendar day of Skatteverkets
  beslut (decided_at), today only when no decision date is recorded, and
  the confirm dialog states the date (Swedish accounting review: BFL 5 kap
  6-7 §, datum for affarshandelsen).

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01D9wvsGnvu5tHGqYnJnjnaB

* fix(rot-rut): reclaim RPCs validate the share and derive the invoice state; idempotent revert; v1 credit guard reads the column

- apply_rot_rut_reclaim_invoice (20260907160400 replaces the 160300
  signature) takes only the refused share, validates it against the locked
  item, request and invoice, and derives remaining_amount and status from
  the INSERT-guard formula (review: caller-supplied accounting values,
  CWE-862). revert_rot_rut_reclaim_invoice mirrors it for a reversed
  reclaim voucher; the request link is cleared only after every leg.
- v1 credit route projection includes deduction_reclaimed_total so the
  reclaim guard actually fires there.
- Overview keeps "Bokfor nekat belopp" available while legs are pending
  (resume after a partial failure).
- Match and settle routes attach journal_entry_id on update-stage errors.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01D9wvsGnvu5tHGqYnJnjnaB

---------

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-08 00:13:05 +02:00

163 lines
6.6 KiB
TypeScript

import type { SupabaseClient } from '@supabase/supabase-js'
/**
* Coverage of the invoice register (the `invoices` table) relative to the
* company's bookkeeping. The register only holds invoices created in
* Accounted: a company migrated mid-year (SIE import) or backfilled through
* manual/API verifikat has real customer invoices that exist ONLY as journal
* entries. Every surface that answers "which invoices do we have" from the
* register alone looks complete while silently omitting that period; this
* helper computes the disclosure those surfaces show.
*
* Detection is AR-based, not import-based: `fetchMigrationCoverageEnd()`
* keys on source_type='import', which misses invoice history recreated as
* plain manual verifikat (the 2026-09-01 user report: a full spring of
* "Kundfakturor" with source_type='manual'). An invoice booked as a
* verifikat DEBITS the receivable on 1510/1513, so posted pre-boundary AR
* debit lines from outside the invoice engine are the signal. Credits are
* deliberately not counted (a manually booked advance payment before the
* first invoice credits 1510 and says nothing about register coverage), and
* every invoice-engine source type is excluded, storno/correction included:
* a rättelse of an engine entry may be re-dated before the boundary
* (storno-service newEntryDate) and must not flag its own register invoice
* as external. Kontantmetod invoice history booked straight against 1930
* stays undetected; accepted, because widening to all class-3 revenue would
* flag cash sales (webshop orders, kassa) that were never register material.
*
* The probe is driven from journal_entries (company-indexed) with the line
* condition as an inner embed, never from journal_entry_lines with entry
* filters on the embed: that inverted shape compiles to a lateral scan of
* the whole lines table across tenants (see lib/bookkeeping/entry-lines.ts).
*/
export interface InvoiceRegisterCoverage {
/**
* Earliest invoice_date of a real, non-draft invoice in the register, i.e.
* where register-backed answers start being complete. Drafts, proformas
* and delivery notes are excluded: a backdated one would move the boundary
* and suppress the disclosure for exactly the period it exists to cover.
* Null when the register is empty (the empty state already routes the
* user to migration) OR when the lookup failed: null always means
* "unknown", never "complete".
*/
covers_from: string | null
/**
* True when posted non-invoice-engine verifikat carry AR (1510/1513)
* debit lines dated before covers_from: invoices likely exist outside the
* register for that period. False only when the probe RAN and found
* nothing; a failed probe returns NO_INVOICE_REGISTER_COVERAGE instead,
* so a DB error can never assert completeness.
*/
has_pre_register_invoices: boolean
}
export const NO_INVOICE_REGISTER_COVERAGE: InvoiceRegisterCoverage = {
covers_from: null,
has_pre_register_invoices: false,
}
/**
* Every source_type the invoice engine (and its correction paths) writes.
* Pre-boundary AR debits from these are the register's own bookkeeping, not
* evidence of register-external invoices.
*/
export const INVOICE_ENGINE_SOURCE_TYPES = [
'invoice_created',
'invoice_paid',
'invoice_cash_payment',
'credit_note',
'reminder_fee',
'rot_rut_payout',
'rot_rut_reclaim',
'storno',
'correction',
] as const
/** PostgREST `in` literal for the NOT-IN filter. */
const INVOICE_ENGINE_SOURCE_TYPES_FILTER =
'(' + INVOICE_ENGINE_SOURCE_TYPES.map((t) => `"${t}"`).join(',') + ')'
const AR_ACCOUNTS = ['1510', '1513']
/**
* True when a posted, non-engine verifikat with an AR debit line exists
* before `coversFrom`. Optionally scoped to one fiscal period (used by the
* 1510 reconciliation, which compares period-scoped balances: a settled
* pre-boundary residual in an EARLIER period cannot explain this period's
* difference and must not be offered as an explanation).
* Returns null when the probe itself failed (unknown, not false).
*/
async function probePreRegisterArDebits(
supabase: SupabaseClient,
companyId: string,
coversFrom: string,
fiscalPeriodId?: string,
): Promise<boolean | null> {
let query = supabase
.from('journal_entries')
.select('id, journal_entry_lines!inner(id)')
.eq('company_id', companyId)
.eq('status', 'posted')
.lt('entry_date', coversFrom)
.not('source_type', 'in', INVOICE_ENGINE_SOURCE_TYPES_FILTER)
.in('journal_entry_lines.account_number', AR_ACCOUNTS)
.gt('journal_entry_lines.debit_amount', 0)
if (fiscalPeriodId) query = query.eq('fiscal_period_id', fiscalPeriodId)
const { data, error } = await query.limit(1).maybeSingle()
if (error) return null
return data != null
}
export async function fetchInvoiceRegisterCoverage(
supabase: SupabaseClient,
companyId: string,
): Promise<InvoiceRegisterCoverage> {
const { data: firstInvoice, error: firstError } = await supabase
.from('invoices')
.select('invoice_date')
.eq('company_id', companyId)
.neq('status', 'draft')
// Proformas and delivery notes are not register invoices (no AR posting);
// an early one would move the boundary without covering anything.
.eq('document_type', 'invoice')
.order('invoice_date', { ascending: true })
.limit(1)
.maybeSingle()
if (firstError) return NO_INVOICE_REGISTER_COVERAGE
const coversFrom = (firstInvoice as { invoice_date?: string } | null)?.invoice_date ?? null
if (!coversFrom) return NO_INVOICE_REGISTER_COVERAGE
const hasPreRegister = await probePreRegisterArDebits(supabase, companyId, coversFrom)
// Probe failure means UNKNOWN: never report a confident "complete".
if (hasPreRegister === null) return NO_INVOICE_REGISTER_COVERAGE
return {
covers_from: coversFrom,
has_pre_register_invoices: hasPreRegister,
}
}
/**
* Period-scoped variant for the 1510/1513 reconciliation: does pre-boundary
* non-engine AR debit activity exist INSIDE the given fiscal period? Only
* then may the reconciliation offer "migrated/backfilled invoices" as an
* explanation for its difference. Returns false on any lookup failure (no
* explanation is the safe degrade: the red badge stands unqualified).
*/
export async function hasPreRegisterArInPeriod(
supabase: SupabaseClient,
companyId: string,
fiscalPeriodId: string,
): Promise<boolean> {
const coverage = await fetchInvoiceRegisterCoverage(supabase, companyId)
if (!coverage.has_pre_register_invoices || !coverage.covers_from) return false
const inPeriod = await probePreRegisterArDebits(
supabase,
companyId,
coverage.covers_from,
fiscalPeriodId,
)
return inPeriod === true
}