Files
accounted/lib/bookkeeping/payment-sync.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

331 lines
14 KiB
TypeScript

import type { SupabaseClient } from '@supabase/supabase-js'
import { createLogger } from '@/lib/logger'
import { roundOre } from '@/lib/money'
import { invoiceCustomerOutstanding } from '@/lib/invoices/customer-share'
import type { JournalEntry } from '@/types'
const log = createLogger('payment-sync')
export const PAYMENT_SOURCE_TYPES = [
'invoice_paid',
'invoice_cash_payment',
'supplier_invoice_paid',
'supplier_invoice_cash_payment',
] as const
export function isPaymentSourceType(sourceType: string | null | undefined): boolean {
if (!sourceType) return false
return (PAYMENT_SOURCE_TYPES as readonly string[]).includes(sourceType)
}
/**
* Revert the business-level paid status on the invoice or supplier invoice
* that a payment journal entry was attached to. Used by both reverseEntry()
* (storno) and the DELETE journal entry route: both paths leave the GL in a
* consistent state but the invoice's status/paid_amount/paid_at would otherwise
* stay stuck on "paid".
*
* Safe to call with any entry: returns early if source_type is not a payment.
*/
export async function syncInvoiceStatusFromPaymentEntry(
supabase: SupabaseClient,
companyId: string,
entry: Pick<JournalEntry, 'id' | 'source_type' | 'source_id'>
): Promise<void> {
if (!isPaymentSourceType(entry.source_type) || !entry.source_id) return
const entryId = entry.id
if (entry.source_type.startsWith('supplier_invoice')) {
// Scope to THIS invoice's payment row: a batch voucher (match_batch_allocate)
// carries one payment row per invoice under the same journal_entry_id, so an
// unfiltered .single() errors out on multi-row and silently yields null.
const { data: payment } = await supabase
.from('supplier_invoice_payments')
.select('amount')
.eq('journal_entry_id', entryId)
.eq('supplier_invoice_id', entry.source_id)
.eq('company_id', companyId)
.single()
// Column is `total`, not `total_amount` (supplier_invoices has never had a
// total_amount column). Selecting the wrong name made PostgREST reject the
// whole query, so `supplierInvoice` was always null: the restore below was
// silently skipped while the payment-row delete and the bank-line release
// still ran. The invoice then stayed 'paid' with a stale paid_amount and
// nothing behind it, so the AP ledger (leverantörsreskontra) showed money
// as paid that was never paid.
const { data: supplierInvoice, error: supplierInvoiceError } = await supabase
.from('supplier_invoices')
.select('paid_amount, total, due_date')
.eq('id', entry.source_id)
.eq('company_id', companyId)
.single()
// PGRST116 = no row: the invoice itself is gone, so there is nothing to
// restore and the cleanup below is still the right thing to do. Any OTHER
// error means we could not read the state we are about to overwrite.
// Deleting the payment row and releasing the bank line at that point would
// destroy the only evidence of the payment while the invoice stays 'paid':
// exactly the wrong-AP-ledger outcome above. Abort instead, at ERROR level
// so the failure is observable: the storno is already committed and both
// callers (reverseEntry, the DELETE voucher route) treat this sync as
// best-effort, so bailing out leaves invoice + payment row + bank line
// mutually consistent and the operation safely re-runnable.
if (supplierInvoiceError && supplierInvoiceError.code !== 'PGRST116') {
log.error(
'Failed to read supplier invoice for payment reversal: aborting status sync',
supplierInvoiceError,
{ companyId, journalEntryId: entryId, supplierInvoiceId: entry.source_id }
)
return
}
if (supplierInvoice) {
// Same fallback semantics as the customer branch below: a cash payment
// (supplier_invoice_cash_payment) books no payment row and is only ever
// a FULL payment, so reverting the whole paid_amount is correct. The
// old `&& payment` guard skipped the restore entirely for cash
// reversals, leaving the supplier invoice deadlocked on 'paid'.
const paymentAmount = payment?.amount ?? supplierInvoice.paid_amount
const newPaidAmount = roundOre(supplierInvoice.paid_amount - paymentAmount)
const newRemaining = roundOre(supplierInvoice.total - Math.max(0, newPaidAmount))
let newStatus: string
if (newPaidAmount > 0) {
newStatus = 'partially_paid'
} else if (supplierInvoice.due_date && new Date(supplierInvoice.due_date) < new Date()) {
newStatus = 'overdue'
} else {
newStatus = 'approved'
}
await supabase
.from('supplier_invoices')
.update({
status: newStatus,
paid_amount: Math.max(0, newPaidAmount),
remaining_amount: newRemaining,
paid_at: null,
payment_journal_entry_id: null,
})
.eq('id', entry.source_id)
.eq('company_id', companyId)
}
// Remove THIS invoice's payment row tied to the reversed voucher so a
// re-match of the same bank line doesn't double-count or trip the unique
// index on supplier_invoice_payments. Scoped to the source invoice: a
// batch voucher carries sibling rows for other invoices whose status this
// call does not restore, so deleting them here would desync paid_amount
// from the payment rows (PR #666 review, SOC 2 CC6.3). Capture the linked
// transaction id first so the bank line can be released back to the inbox.
const { data: spRows } = await supabase
.from('supplier_invoice_payments')
.select('transaction_id')
.eq('journal_entry_id', entryId)
.eq('supplier_invoice_id', entry.source_id)
.eq('company_id', companyId)
await supabase
.from('supplier_invoice_payments')
.delete()
.eq('journal_entry_id', entryId)
.eq('supplier_invoice_id', entry.source_id)
.eq('company_id', companyId)
await releaseLinkedTransactions(
supabase,
companyId,
entryId,
(spRows ?? []).map((r) => (r as { transaction_id: string | null }).transaction_id),
'supplier_invoice_id',
)
} else {
// Scoped like the supplier branch: filter by invoice_id + company_id so a
// batch voucher's sibling payment rows don't break the .single().
const { data: payment } = await supabase
.from('invoice_payments')
.select('amount')
.eq('journal_entry_id', entryId)
.eq('invoice_id', entry.source_id)
.eq('company_id', companyId)
.single()
const { data: customerInvoice } = await supabase
.from('invoices')
.select('paid_amount, total, due_date, deduction_total, deduction_reclaimed_total')
.eq('id', entry.source_id)
.eq('company_id', companyId)
.single()
if (customerInvoice) {
// For a partial reversal we take the exact amount from the payment row.
// The fallback (full paid_amount) only applies when no payment row exists:
// true for invoice_cash_payment, which is only ever booked on a FULL
// payment, so reverting the whole paid_amount is correct there. Guarding
// this keeps a future partial-cash path from over-reverting.
const paymentAmount = payment?.amount ?? customerInvoice.paid_amount
const newPaidAmount = roundOre(customerInvoice.paid_amount - paymentAmount)
const safePaidAmount = Math.max(0, newPaidAmount)
// The supplier branch already resets remaining_amount; the customer branch
// never did, leaving it stale (= total) after a reversal so the invoice
// showed fully unpaid yet stuck on 'paid'. Recompute from total. (The
// .in('status', …) guard below can leave status/remaining un-updated if
// the invoice isn't paid/partially_paid: only reachable on a non-storno
// path; the payment-row delete + tx release still run, freeing the line.)
//
// remaining_amount is the CUSTOMER share: net of the ROT/RUT deduction,
// exactly as build-invoice-write stores it at creation (total -
// deduction_total) and as the invoices_remaining_amount_guard trigger
// derives it. Recomputing gross here inflated remaining on ROT/RUT
// invoices after a storno, which made them permanently un-settleable
// once mark-paid started comparing the net customer settlement against
// remaining (a net payment can never reach a gross remaining, and the
// cash-partial block rejects the "partial"). The share comes from the
// one shared definition (lib/invoices/customer-share.ts); the
// Math.max(0, ...) mirrors the guard's GREATEST(0, ...) because this
// value is persisted into the column.
// A refused deduction that a rot_rut_reclaim voucher moved back onto
// the customer is the customer's again: without this term a storno of
// any payment on a reopened invoice wrote a remaining short by the
// reclaimed share and no path could settle it (skeptic #2397 R1).
const { deduction_total: deductionTotal = 0, deduction_reclaimed_total: reclaimedTotal = 0 } =
customerInvoice as { deduction_total?: number | null; deduction_reclaimed_total?: number | null }
const newRemaining = Math.max(
0,
invoiceCustomerOutstanding(
{
total: customerInvoice.total,
deduction_total: deductionTotal ?? 0,
deduction_reclaimed_total: reclaimedTotal ?? 0,
},
safePaidAmount,
),
)
const revertStatus = newPaidAmount > 0
? 'partially_paid'
: customerInvoice.due_date && new Date(customerInvoice.due_date) < new Date()
? 'overdue'
: 'sent'
await supabase
.from('invoices')
.update({
status: revertStatus,
paid_at: null,
paid_amount: safePaidAmount,
remaining_amount: newRemaining,
})
.eq('id', entry.source_id)
.eq('company_id', companyId)
.in('status', ['paid', 'partially_paid'])
}
// Remove THIS invoice's payment row tied to the reversed voucher so a
// re-match of the same bank line doesn't trip the (transaction_id,
// invoice_id) / (journal_entry_id, invoice_id) unique indexes on
// invoice_payments. Scoped to the source invoice: see the supplier
// branch comment for the batch-voucher rationale.
const { data: ipRows } = await supabase
.from('invoice_payments')
.select('transaction_id')
.eq('journal_entry_id', entryId)
.eq('invoice_id', entry.source_id)
.eq('company_id', companyId)
await supabase
.from('invoice_payments')
.delete()
.eq('journal_entry_id', entryId)
.eq('invoice_id', entry.source_id)
.eq('company_id', companyId)
await releaseLinkedTransactions(
supabase,
companyId,
entryId,
(ipRows ?? []).map((r) => (r as { transaction_id: string | null }).transaction_id),
'invoice_id',
)
}
}
/**
* Detach any bank transactions still pointing at a reversed payment voucher so
* the bank line returns to the inbox and becomes re-matchable. Without this, a
* standalone storno (the reverse route / MCP reverse tool / delete-last-voucher)
* leaves transactions.journal_entry_id pointing at a reversed JE: the match
* POST refuses (invoice no longer matchable once we also fix its status) and the
* line can't be re-booked or deleted. The match-invoice route already clears the
* tx when IT stornos a conflicting auto-categorization JE; this covers every
* other reversal path.
*
* Clears by journal_entry_id (covers the link even when the payment row was
* missing) and by the captured payment-row transaction ids (covers a partial
* match that cleared journal_entry_id but left invoice_id/category set). Only
* the link/categorization columns are reset; the transaction row is preserved.
*/
async function releaseLinkedTransactions(
supabase: SupabaseClient,
companyId: string,
entryId: string,
paymentTransactionIds: Array<string | null>,
invoiceColumn: 'invoice_id' | 'supplier_invoice_id',
): Promise<void> {
const resetFields = {
journal_entry_id: null,
[invoiceColumn]: null,
is_business: null,
category: null,
}
const { data: releasedByEntry, error: byEntryError } = await supabase
.from('transactions')
.update(resetFields)
.eq('company_id', companyId)
.eq('journal_entry_id', entryId)
.select('id')
if (byEntryError) {
// Best-effort like the rest of the sync: the storno itself already
// committed, but a failed release leaves the bank line stuck on a
// reversed JE, so it must be observable.
log.error('Failed to release transactions by journal_entry_id', byEntryError, {
companyId,
journalEntryId: entryId,
})
} else if (releasedByEntry && releasedByEntry.length > 0) {
// transactions has no write_audit_log trigger, so the clearing of the
// link/categorization columns is logged here for incident reconstruction.
log.info('Released bank transactions from reversed payment voucher', {
companyId,
journalEntryId: entryId,
invoiceColumn,
transactionIds: releasedByEntry.map((r) => (r as { id: string }).id),
})
}
const txIds = paymentTransactionIds.filter((id): id is string => !!id)
if (txIds.length > 0) {
const { data: releasedById, error: byIdError } = await supabase
.from('transactions')
.update(resetFields)
.eq('company_id', companyId)
.in('id', txIds)
.select('id')
if (byIdError) {
log.error('Failed to release transactions by payment transaction ids', byIdError, {
companyId,
journalEntryId: entryId,
transactionIds: txIds,
})
} else if (releasedById && releasedById.length > 0) {
log.info('Released payment-linked bank transactions from reversed voucher', {
companyId,
journalEntryId: entryId,
invoiceColumn,
transactionIds: releasedById.map((r) => (r as { id: string }).id),
})
}
}
}