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>
This commit is contained in:
co-authored by
Claude Fable 5.1
parent
5d735097a1
commit
fdcb7d937e
@@ -115,6 +115,7 @@ import {
|
||||
type BatchAllocationResult,
|
||||
} from '@/lib/invoices/clear-settled-batch-allocations'
|
||||
import { linkTransactionToJournalEntry } from '@/lib/transactions/link-journal-entry'
|
||||
import { matchTransactionToRotRutPayout } from '@/lib/invoices/rot-rut-match-transaction'
|
||||
import {
|
||||
completeInboxItemsForBookedTransaction,
|
||||
resolveVoucherLinkedEntryIds,
|
||||
@@ -380,6 +381,85 @@ type ExecutorResult = {
|
||||
partialPostedIds?: Record<string, string>
|
||||
}
|
||||
|
||||
/**
|
||||
* settle_rot_rut_payout (gnubok_settle_rot_rut_payout): book Skatteverkets
|
||||
* ROT/RUT utbetalning from the bank row against its begäran (one or several,
|
||||
* #2239) through the same writer as the dashboard match route. The stage
|
||||
* already checked income/SEK/unlinked/sum; the writer re-checks everything
|
||||
* under its own CAS guards, so a race between approval and a manual match
|
||||
* ends in a coded refusal, never a second 1513 credit.
|
||||
*/
|
||||
async function commitSettleRotRutPayout(
|
||||
supabase: SupabaseClient,
|
||||
userId: string,
|
||||
companyId: string,
|
||||
params: Record<string, unknown>
|
||||
): Promise<ExecutorResult> {
|
||||
const transactionId = params.transaction_id as string | undefined
|
||||
const requestIds = Array.isArray(params.request_ids)
|
||||
? (params.request_ids as unknown[]).filter((id): id is string => typeof id === 'string')
|
||||
: []
|
||||
if (!transactionId || requestIds.length === 0) {
|
||||
return { error: 'transaction_id and request_ids are required', status: 400 }
|
||||
}
|
||||
|
||||
const outcome = await matchTransactionToRotRutPayout(
|
||||
supabase,
|
||||
userId,
|
||||
companyId,
|
||||
{ transactionId, requestIds },
|
||||
log,
|
||||
)
|
||||
|
||||
if (!outcome.ok) {
|
||||
if (outcome.kind === 'code') {
|
||||
const entry = getErrorEntry(outcome.code)
|
||||
// A race or a failed row link happens AFTER the voucher posted: the op
|
||||
// lands in failed_partial with the voucher id so nobody books it twice.
|
||||
const postedId =
|
||||
outcome.details && typeof outcome.details.journal_entry_id === 'string'
|
||||
? (outcome.details.journal_entry_id as string)
|
||||
: null
|
||||
return {
|
||||
error: entry?.message_en ?? outcome.code,
|
||||
errorCode: outcome.code,
|
||||
status: entry?.httpStatus ?? 500,
|
||||
data: outcome.details as Record<string, unknown> | undefined,
|
||||
...(postedId ? { partialPostedIds: { journal_entry_id: postedId } } : {}),
|
||||
}
|
||||
}
|
||||
const message = outcome.error instanceof Error ? outcome.error.message : 'rot/rut payout settle failed'
|
||||
// stage 'update' = the voucher posted and the request row did not absorb
|
||||
// it: failed_partial with the voucher id, never a plain retryable 500
|
||||
// (a retry would hit journal_entries_rot_rut_payout_live_unique).
|
||||
return {
|
||||
error: `${message} (stage: ${outcome.stage})`,
|
||||
status: 500,
|
||||
...(outcome.journalEntryId ? { partialPostedIds: { journal_entry_id: outcome.journalEntryId } } : {}),
|
||||
}
|
||||
}
|
||||
|
||||
// Audit-trail entry (ids only, no amounts or counterparty PII), same shape
|
||||
// as commitMatchBatchAllocate.
|
||||
log.info('settle_rot_rut_payout committed', {
|
||||
companyId,
|
||||
operationType: 'settle_rot_rut_payout',
|
||||
transactionId,
|
||||
journalEntryId: outcome.journalEntryId,
|
||||
requestCount: outcome.requests.length,
|
||||
})
|
||||
|
||||
return {
|
||||
data: {
|
||||
transaction_id: transactionId,
|
||||
journal_entry_id: outcome.journalEntryId,
|
||||
amount: outcome.amount,
|
||||
request_ids: outcome.requests.map((request) => request.id),
|
||||
request_statuses: outcome.requests.map((request) => request.status),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
async function commitCategorizeTransaction(
|
||||
supabase: SupabaseClient,
|
||||
userId: string,
|
||||
@@ -5147,6 +5227,18 @@ async function commitCreditInvoice(
|
||||
if (!['sent', 'paid', 'overdue'].includes(original.status)) {
|
||||
return { error: 'Only sent, paid, or overdue invoices can be credited', status: 400 }
|
||||
}
|
||||
// A refused ROT/RUT share booked onto the customer (rot_rut_reclaim) moved
|
||||
// kronor from 1513 to 1510 after issue; the credit note reverses the
|
||||
// issue-time split and would leave both accounts wrong. Reverse the reclaim
|
||||
// first (same guard as the dashboard and v1 credit routes).
|
||||
if (Number((original as { deduction_reclaimed_total?: number | null }).deduction_reclaimed_total ?? 0) > 0) {
|
||||
const entry = getErrorEntry('INVOICE_CREDIT_ROT_RUT_RECLAIMED')
|
||||
return {
|
||||
error: entry?.message_en ?? 'Reverse the ROT/RUT reclaim voucher before crediting the invoice',
|
||||
errorCode: 'INVOICE_CREDIT_ROT_RUT_RECLAIMED',
|
||||
status: entry?.httpStatus ?? 400,
|
||||
}
|
||||
}
|
||||
|
||||
const today = new Date().toISOString().split('T')[0]
|
||||
const creditNoteNumber = `KR-${original.invoice_number}`
|
||||
@@ -7355,6 +7447,9 @@ async function commitPendingOperationInner(
|
||||
case 'match_transaction_invoice':
|
||||
result = await commitMatchTransactionInvoice(supabase, userId, companyId, pendingOp.params)
|
||||
break
|
||||
case 'settle_rot_rut_payout':
|
||||
result = await commitSettleRotRutPayout(supabase, userId, companyId, pendingOp.params)
|
||||
break
|
||||
case 'link_invoice_voucher':
|
||||
result = await commitLinkInvoiceVoucher(supabase, userId, companyId, pendingOp.params)
|
||||
break
|
||||
|
||||
Reference in New Issue
Block a user