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
@@ -482,3 +482,40 @@ describe('syncInvoiceStatusFromPaymentEntry', () => {
|
||||
expect(tablesUpdated('transactions').length).toBe(2)
|
||||
})
|
||||
})
|
||||
|
||||
describe('syncInvoiceStatusFromPaymentEntry: reclaimed ROT/RUT share (rot_rut_reclaim)', () => {
|
||||
// 25 000 invoice, 7 500 deduction, Skatteverket refused 2 500 and the
|
||||
// reclaim moved it onto the customer; customer paid 17 500 + 2 500. The
|
||||
// storno of the 2 500 payment must leave 2 500 open, not 0 (#2397 R1).
|
||||
it('keeps the refused share in the remaining after a payment storno', async () => {
|
||||
const { supabase, updatePayload } = createRecordingSupabase([
|
||||
{ data: { amount: 2500 } }, // invoice_payments select amount
|
||||
{
|
||||
data: {
|
||||
paid_amount: 20000,
|
||||
total: 25000,
|
||||
deduction_total: 7500,
|
||||
deduction_reclaimed_total: 2500,
|
||||
due_date: '2099-12-31',
|
||||
},
|
||||
}, // invoices select
|
||||
{ data: null }, // invoices update
|
||||
{ data: [] }, // invoice_payments select transaction_id
|
||||
{ data: null }, // invoice_payments delete
|
||||
{ data: null }, // transactions update
|
||||
])
|
||||
|
||||
await syncInvoiceStatusFromPaymentEntry(
|
||||
supabase,
|
||||
'co-1',
|
||||
{ id: 'entry-1', source_type: 'invoice_paid', source_id: 'invoice-1' } as JournalEntry,
|
||||
)
|
||||
|
||||
expect(updatePayload('invoices')).toEqual({
|
||||
status: 'partially_paid',
|
||||
paid_at: null,
|
||||
paid_amount: 17500,
|
||||
remaining_amount: 2500,
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -710,3 +710,40 @@ describe('proposePaymentLines: ROT/RUT-avdrag (fakturamodellen)', () => {
|
||||
expect(lines[0]).toMatchObject({ account_number: '1930', debit_amount: '12500' })
|
||||
})
|
||||
})
|
||||
|
||||
describe('proposePaymentLines: ROT/RUT invoice reopened by a reclaim (rot_rut_reclaim)', () => {
|
||||
it('proposes the reopened remaining as a plain 1510 clearing', () => {
|
||||
// 25 000 invoice, 7 500 deduction, customer paid 17 500, Skatteverket
|
||||
// refused 2 500 and the reclaim voucher moved it onto 1510.
|
||||
const lines = proposePaymentLines({
|
||||
invoice: {
|
||||
...makeInvoiceInput({ total: 25000 }),
|
||||
deduction_total: 7500,
|
||||
deduction_reclaimed_total: 2500,
|
||||
paid_amount: 17500,
|
||||
remaining_amount: 2500,
|
||||
},
|
||||
accountingMethod: 'accrual',
|
||||
entityType: 'enskild_firma',
|
||||
})
|
||||
|
||||
expect(lines).toHaveLength(2)
|
||||
expect(lines[0]).toMatchObject({ account_number: '1930', debit_amount: '2500' })
|
||||
expect(lines[1]).toMatchObject({ account_number: '1510', credit_amount: '2500' })
|
||||
})
|
||||
|
||||
it('leaves a ROT/RUT invoice without a reclaim on the legacy customer-share proposal', () => {
|
||||
const lines = proposePaymentLines({
|
||||
invoice: {
|
||||
...makeInvoiceInput({ total: 25000 }),
|
||||
deduction_total: 7500,
|
||||
paid_amount: 0,
|
||||
remaining_amount: 17500,
|
||||
},
|
||||
accountingMethod: 'accrual',
|
||||
entityType: 'enskild_firma',
|
||||
})
|
||||
expect(lines[0]).toMatchObject({ account_number: '1930', debit_amount: '17500' })
|
||||
expect(lines[1]).toMatchObject({ account_number: '1510', credit_amount: '17500' })
|
||||
})
|
||||
})
|
||||
|
||||
@@ -34,6 +34,7 @@ import {
|
||||
import { fetchEntryLines, type EntryLinesQuery } from '@/lib/bookkeeping/entry-lines'
|
||||
import { backfillStandardBASAccounts } from '@/lib/bookkeeping/account-backfill'
|
||||
import { syncInvoiceStatusFromPaymentEntry, isPaymentSourceType } from '@/lib/bookkeeping/payment-sync'
|
||||
import { syncRotRutReclaimAfterReversal } from '@/lib/invoices/rot-rut-reclaim-reversal'
|
||||
import { getActor } from '@/lib/bookkeeping/actor-context'
|
||||
import type {
|
||||
AssetDisposalType,
|
||||
@@ -1455,6 +1456,14 @@ export async function reverseEntry(
|
||||
await syncInvoiceStatusFromPaymentEntry(supabase, companyId, original as JournalEntry)
|
||||
}
|
||||
|
||||
// A reversed rot_rut_reclaim voucher hands the refused share back to
|
||||
// Skatteverket's side: the invoices it reopened close again, the begäran
|
||||
// becomes reclaimable again (same business-state mirror as the payment
|
||||
// sync above, skeptic #2397 R3).
|
||||
if (original.source_type === 'rot_rut_reclaim') {
|
||||
await syncRotRutReclaimAfterReversal(supabase, companyId, original.id)
|
||||
}
|
||||
|
||||
// Fetch complete reversal entry with lines
|
||||
const { data: completeEntry } = await supabase
|
||||
.from('journal_entries')
|
||||
|
||||
@@ -533,6 +533,7 @@ function invoiceOutstandingAmount(invoice: Invoice): number {
|
||||
remaining_amount?: number | null
|
||||
paid_amount?: number | null
|
||||
deduction_total?: number | null
|
||||
deduction_reclaimed_total?: number | null
|
||||
}
|
||||
// A payment is being booked, so a stored 0 cannot mean "settled": rows
|
||||
// written by paths that bypass buildInvoiceWriteData (imports, sandbox seed,
|
||||
@@ -544,7 +545,11 @@ function invoiceOutstandingAmount(invoice: Invoice): number {
|
||||
}
|
||||
const paid = typeof inv.paid_amount === 'number' ? inv.paid_amount : 0
|
||||
const deduction = typeof inv.deduction_total === 'number' ? inv.deduction_total : 0
|
||||
return roundOre(invoice.total - paid - deduction)
|
||||
// A refused deduction (rot_rut_reclaim) is the customer's again: same
|
||||
// formula as invoiceCustomerShare and the SQL INSERT guard.
|
||||
const reclaimed =
|
||||
typeof inv.deduction_reclaimed_total === 'number' ? inv.deduction_reclaimed_total : 0
|
||||
return roundOre(invoice.total - paid - deduction + reclaimed)
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -153,7 +153,7 @@ export async function syncInvoiceStatusFromPaymentEntry(
|
||||
|
||||
const { data: customerInvoice } = await supabase
|
||||
.from('invoices')
|
||||
.select('paid_amount, total, due_date, deduction_total')
|
||||
.select('paid_amount, total, due_date, deduction_total, deduction_reclaimed_total')
|
||||
.eq('id', entry.source_id)
|
||||
.eq('company_id', companyId)
|
||||
.single()
|
||||
@@ -185,12 +185,20 @@ export async function syncInvoiceStatusFromPaymentEntry(
|
||||
// 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.
|
||||
const deductionTotal =
|
||||
(customerInvoice as { deduction_total?: number | null }).deduction_total ?? 0
|
||||
// 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 },
|
||||
{
|
||||
total: customerInvoice.total,
|
||||
deduction_total: deductionTotal ?? 0,
|
||||
deduction_reclaimed_total: reclaimedTotal ?? 0,
|
||||
},
|
||||
safePaidAmount,
|
||||
),
|
||||
)
|
||||
|
||||
@@ -39,6 +39,13 @@ export interface ProposePaymentLinesInput {
|
||||
* doing so is what made every ROT/RUT invoice fail the overpayment guard.
|
||||
*/
|
||||
deduction_total?: number | null
|
||||
/**
|
||||
* The part of the deduction Skatteverket refused and that a
|
||||
* rot_rut_reclaim voucher moved back onto the customer (debit 1510).
|
||||
* When set, the invoice's remaining is a plain 1510 fordran again and the
|
||||
* remaining-aware proposal applies to it.
|
||||
*/
|
||||
deduction_reclaimed_total?: number | null
|
||||
/**
|
||||
* Dimensions PR7: the invoice's default bag. Stamped on every proposed
|
||||
* line: the payment dialog always submits its (editable) lines, so the
|
||||
@@ -145,7 +152,10 @@ export function proposePaymentLines(input: ProposePaymentLinesInput): FormLine[]
|
||||
* pure function does not carry; the dialog's FX path already handles it.
|
||||
* - On a ROT/RUT invoice the outstanding remainder is (or includes)
|
||||
* Skatteverket's share, which sits on 1513 and is settled by the ROT/RUT
|
||||
* payout flow, not by clearing 1510 here.
|
||||
* payout flow, not by clearing 1510 here. The one exception is a
|
||||
* deduction Skatteverket refused: the reclaim voucher has already moved
|
||||
* that share onto 1510 (deduction_reclaimed_total > 0), so the reopened
|
||||
* remaining is an ordinary customer fordran and is proposed as such.
|
||||
*
|
||||
* Two shapes:
|
||||
* - 0 < remaining < 1 kr (the stuck öresavrundning case): a bank-less
|
||||
@@ -163,11 +173,15 @@ function proposeRemainingAwareLines(
|
||||
): FormLine[] | null {
|
||||
if (accountingMethod !== 'accrual') return null
|
||||
if (invoice.currency !== 'SEK') return null
|
||||
if ((invoice.deduction_total ?? 0) > 0) return null
|
||||
const reclaimed = invoice.deduction_reclaimed_total ?? 0
|
||||
if ((invoice.deduction_total ?? 0) > 0 && !(reclaimed > 0)) return null
|
||||
|
||||
const total = roundOre(invoice.total)
|
||||
// With a reclaimed deduction the customer's whole fordran is total minus
|
||||
// the deduction plus the refused share; "partial" is measured against
|
||||
// that, not the printed total.
|
||||
const total = roundOre(invoice.total - (invoice.deduction_total ?? 0) + reclaimed)
|
||||
const remaining = roundOre(
|
||||
invoice.remaining_amount ?? invoice.total - (invoice.paid_amount ?? 0),
|
||||
invoice.remaining_amount ?? total - (invoice.paid_amount ?? 0),
|
||||
)
|
||||
const hasPartial = remaining > ORE_TOLERANCE && total - remaining > ORE_TOLERANCE
|
||||
if (!hasPartial) return null
|
||||
|
||||
@@ -132,3 +132,78 @@ export async function createRotRutPayoutEntry(
|
||||
],
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Reclaim voucher for the share of a begäran Skatteverket refused.
|
||||
*
|
||||
* The 1513 fordran booked at issue was never paid by Skatteverket, so it is
|
||||
* the buyer's again (HUSFL 2009:194; swedish-invoice-compliance section 8:
|
||||
* "SKV denies: Debit 1510, Credit 1513"):
|
||||
*
|
||||
* Debit 1510 Kundfordringar [refused share, per invoice]
|
||||
* Credit 1513 Skattereduktion rot/rut [refused share, per invoice]
|
||||
*
|
||||
* One voucher per begäran (source_id = request id, guarded by the partial
|
||||
* unique index journal_entries_rot_rut_reclaim_live_unique), one 1510 and one
|
||||
* 1513 leg per invoice so the kundreskontra can be read per faktura.
|
||||
*/
|
||||
export interface RotRutReclaimLeg {
|
||||
invoiceId: string
|
||||
invoiceNumber: string | null
|
||||
/** The refused share for this invoice (kr). */
|
||||
amount: number
|
||||
}
|
||||
|
||||
export async function createRotRutReclaimEntry(
|
||||
supabase: SupabaseClient,
|
||||
companyId: string,
|
||||
userId: string,
|
||||
params: {
|
||||
requestId: string
|
||||
requestName: string
|
||||
deductionType: 'rot' | 'rut'
|
||||
bookingDate: string
|
||||
/** One leg per invoice with a refused share; at least one, all > 0. */
|
||||
legs: RotRutReclaimLeg[]
|
||||
},
|
||||
): Promise<JournalEntry> {
|
||||
const legs = params.legs
|
||||
.map((leg) => ({ ...leg, amount: roundOre(leg.amount) }))
|
||||
.filter((leg) => leg.amount > 0)
|
||||
if (legs.length === 0) {
|
||||
throw new Error('A rot/rut reclaim voucher needs at least one refused share')
|
||||
}
|
||||
const fiscalPeriodId = await findFiscalPeriod(supabase, companyId, params.bookingDate)
|
||||
if (!fiscalPeriodId) {
|
||||
throw new Error(`No open fiscal period found for booking date ${params.bookingDate}`)
|
||||
}
|
||||
|
||||
const label = params.deductionType === 'rut' ? 'RUT' : 'ROT'
|
||||
const description = `Nekat ${label}-avdrag från Skatteverket (${params.requestName})`
|
||||
const legDescription = (leg: RotRutReclaimLeg) =>
|
||||
`Nekat ${label}-avdrag faktura ${leg.invoiceNumber ?? leg.invoiceId}`
|
||||
|
||||
const input: CreateJournalEntryInput = {
|
||||
fiscal_period_id: fiscalPeriodId,
|
||||
entry_date: params.bookingDate,
|
||||
description,
|
||||
source_type: 'rot_rut_reclaim',
|
||||
source_id: params.requestId,
|
||||
lines: [
|
||||
...legs.map((leg) => ({
|
||||
account_number: '1510',
|
||||
debit_amount: leg.amount,
|
||||
credit_amount: 0,
|
||||
line_description: legDescription(leg),
|
||||
})),
|
||||
...legs.map((leg) => ({
|
||||
account_number: '1513',
|
||||
debit_amount: 0,
|
||||
credit_amount: leg.amount,
|
||||
line_description: legDescription(leg),
|
||||
})),
|
||||
],
|
||||
}
|
||||
|
||||
return createJournalEntry(supabase, companyId, userId, input)
|
||||
}
|
||||
|
||||
@@ -153,6 +153,7 @@ export const STANDARD_VOUCHER_SERIES_MAP: Readonly<Record<JournalEntrySourceType
|
||||
invoice_paid: 'C',
|
||||
invoice_cash_payment: 'C',
|
||||
rot_rut_payout: 'C',
|
||||
rot_rut_reclaim: 'C',
|
||||
supplier_invoice_registered: 'D',
|
||||
supplier_credit_note: 'D',
|
||||
supplier_invoice_privately_paid: 'D',
|
||||
|
||||
Reference in New Issue
Block a user