feat(reconciliation): suggest and book Skatteverkets bundled ROT/RUT payout against several begäran (#2360)

* feat(reconciliation): suggest and book Skatteverkets bundled ROT/RUT payout against several begäran

Skatteverket decides per begäran but pays everything it decided that day in
one transfer, so the bank row often equals no single open begäran and the 1:1
matcher from #2271 stayed silent; the settle service then refused the amount
and the dialog told the user to split the transaction by hand.

The candidate is now the exact covering set of 1..4 open begäran whose
expected payouts sum to the row (lib/invoices/rot-rut-payout-set-matching.ts,
over the existing findExactCoveringSet, ambiguity-refusing). It is computed
at read time from the open pool (inbox page, worklist, ingest), no hint
column. Confirming books ONE voucher (debit 19xx, one 1513 credit per
begäran) through the same writer, marks every begäran paid and links the row
once; a bundle is always booked at exactly the decided sums.

- match-rot-rut-payout accepts request_ids (1..10) beside request_id
- settleRotRutPayoutRequestSet shares the single path's tail
- createRotRutPayoutSetEntry; createRotRutPayoutEntry delegates (N=1 unchanged)
- inbox pill, RotRutPayoutMatchDialog, Att göra and ingest handle the set
- new error code ROT_RUT_SETTLE_SET_AMOUNT; sv/en strings for the set

Closes #2239

Claude-Session: https://claude.ai/code/session_01LvMaHcTnwAfxzgYD1fGYX1
Co-Authored-By: Claude Fable 5.1 <[email protected]>

* fix(invoices): PR #2360 review: partially decided begäran stays partially_paid in a bundle

The bundle path booked every leg as fully paid and mirrored requested_amount
onto every begäran's items, while the single path completes a begäran only
when the leg covers requested_total and otherwise leaves it partially_paid
for manual handling. A begäran Skatteverket decided at less than requested
is a legitimate bundle member (its leg is the beslut, the exact-sum rule is
unchanged), so the set path now computes fullyPaid per leg exactly like the
single path, passes it to the shared attachSettlementVoucher, and mirrors
only the fully paid legs; sibling hints are still cleared for every settled
begäran, which carries a voucher and is no longer matchable either way.

Claude-Session: https://claude.ai/code/session_01LvMaHcTnwAfxzgYD1fGYX1
Co-Authored-By: Claude Fable 5.1 <[email protected]>

---------

Co-authored-by: Jakob Wennberg <[email protected]>
Co-authored-by: Claude Fable 5.1 <[email protected]>
This commit is contained in:
Jakob Wennberg
2026-09-06 21:13:53 +02:00
committed by GitHub
co-authored by Claude Fable 5.1 Jakob Wennberg
parent 4bc007cdeb
commit 0069a3f59a
22 changed files with 1679 additions and 284 deletions
+14 -6
View File
@@ -2179,13 +2179,21 @@ export const CreateTransactionFromDocumentSchema = z.object({
})
/**
* POST /api/transactions/[id]/match-rot-rut-payout: settle a ROT/RUT begäran
* with the bank row that carried Skatteverkets utbetalning. Amount, date and
* bank account all come from the transaction, so the body is just the target.
* POST /api/transactions/[id]/match-rot-rut-payout: settle one or several
* ROT/RUT begäran with the bank row that carried Skatteverkets utbetalning.
* Amount, date and bank account all come from the transaction, so the body
* is just the target(s): `request_id` for one begäran, `request_ids` when
* Skatteverket paid several beslut in one transfer (#2239). Exactly one of
* the two.
*/
export const MatchRotRutPayoutSchema = z.object({
request_id: uuid,
})
export const MatchRotRutPayoutSchema = z
.object({
request_id: uuid.optional(),
request_ids: z.array(uuid).min(1).max(10).optional(),
})
.refine((body) => (body.request_id ? 1 : 0) + (body.request_ids ? 1 : 0) === 1, {
message: 'Ange antingen request_id eller request_ids',
})
/** Bank outflow → the registered utlägg it repays (one person). */
export const MatchExpensePayoutSchema = z.object({
+100 -33
View File
@@ -1,22 +1,110 @@
import type { SupabaseClient } from '@supabase/supabase-js'
import type { CreateJournalEntryInput, JournalEntry } from '@/types'
import { roundOre } from '@/lib/money'
import { createJournalEntry, findFiscalPeriod } from './engine'
/**
* Settlement voucher for a rot/rut payout from Skatteverket.
*
* When the agency pays out a begäran (one lump sum per request), the 1513
* receivable created at invoicing (fakturamodellen) clears against the bank:
* When the agency pays out a begäran, the 1513 receivable created at
* invoicing (fakturamodellen) clears against the bank:
*
* Debit 19xx bank account (default 1930) [amount]
* Credit 1513 Skattereduktion rot/rut [amount]
*
* One voucher per payout request: that mirrors the actual bank transaction.
* One voucher per bank transfer: that mirrors the actual bank transaction.
* Skatteverket decides per begäran but pays everything it decided that day
* in ONE transfer, so a voucher may clear several begäran: one 1513 leg per
* request (createRotRutPayoutSetEntry), the way match-batch books one bank
* row against several customer invoices. The request side of the link is
* rot_rut_payout_requests.settlement_journal_entry_id on every request the
* voucher settles; source_id carries the first of them.
*
* At partial approval (delvis beviljad) the paid amount clears here and the
* remainder stays on 1513 until the user corrects it (kundfordran/kundförlust
* depending on the outcome with the buyer): deliberately manual, never
* guessed.
*/
export interface RotRutPayoutLeg {
requestId: string
requestName: string
deductionType: 'rot' | 'rut'
/** What Skatteverket paid for this begäran (kr). */
amount: number
}
function deductionLabel(legs: Array<Pick<RotRutPayoutLeg, 'deductionType'>>): string {
const types = new Set(legs.map((leg) => leg.deductionType))
if (types.size === 1) return types.has('rut') ? 'RUT' : 'ROT'
return 'ROT/RUT'
}
function payoutDescription(label: string, names: string[]): string {
return `Utbetalning ${label}-avdrag från Skatteverket (${names.join(', ')})`
}
export async function createRotRutPayoutSetEntry(
supabase: SupabaseClient,
companyId: string,
userId: string,
params: {
paymentDate: string
/** BAS 19xx account the payout landed on. Defaults to 1930. */
bankAccount?: string
/** One leg per begäran the transfer settles; at least one. */
legs: RotRutPayoutLeg[]
},
): Promise<JournalEntry> {
if (params.legs.length === 0) {
throw new Error('A rot/rut payout voucher needs at least one begäran')
}
const fiscalPeriodId = await findFiscalPeriod(supabase, companyId, params.paymentDate)
if (!fiscalPeriodId) {
throw new Error(`No open fiscal period found for payment date ${params.paymentDate}`)
}
const legs = params.legs.map((leg) => ({
...leg,
amount: roundOre(leg.amount),
}))
const total = roundOre(legs.reduce((sum, leg) => sum + leg.amount, 0))
const bankAccount = params.bankAccount ?? '1930'
const description = payoutDescription(
deductionLabel(legs),
legs.map((leg) => leg.requestName),
)
const input: CreateJournalEntryInput = {
fiscal_period_id: fiscalPeriodId,
entry_date: params.paymentDate,
description,
source_type: 'rot_rut_payout',
source_id: legs[0].requestId,
lines: [
{
account_number: bankAccount,
debit_amount: total,
credit_amount: 0,
line_description: description,
},
...legs.map((leg) => ({
account_number: '1513',
debit_amount: 0,
credit_amount: leg.amount,
// A single begäran keeps the voucher text on both legs (as before);
// a bundle names its own begäran on each 1513 leg.
line_description:
legs.length === 1
? description
: payoutDescription(deductionLabel([leg]), [leg.requestName]),
})),
],
}
return createJournalEntry(supabase, companyId, userId, input)
}
/** One begäran: the bundle voucher with a single 1513 leg. */
export async function createRotRutPayoutEntry(
supabase: SupabaseClient,
companyId: string,
@@ -31,37 +119,16 @@ export async function createRotRutPayoutEntry(
bankAccount?: string
},
): Promise<JournalEntry> {
const fiscalPeriodId = await findFiscalPeriod(supabase, companyId, params.paymentDate)
if (!fiscalPeriodId) {
throw new Error(`No open fiscal period found for payment date ${params.paymentDate}`)
}
const amount = Math.round(params.amount * 100) / 100
const bankAccount = params.bankAccount ?? '1930'
const label = params.deductionType === 'rot' ? 'ROT' : 'RUT'
const description = `Utbetalning ${label}-avdrag från Skatteverket (${params.requestName})`
const input: CreateJournalEntryInput = {
fiscal_period_id: fiscalPeriodId,
entry_date: params.paymentDate,
description,
source_type: 'rot_rut_payout',
source_id: params.requestId,
lines: [
return createRotRutPayoutSetEntry(supabase, companyId, userId, {
paymentDate: params.paymentDate,
bankAccount: params.bankAccount,
legs: [
{
account_number: bankAccount,
debit_amount: amount,
credit_amount: 0,
line_description: description,
},
{
account_number: '1513',
debit_amount: 0,
credit_amount: amount,
line_description: description,
requestId: params.requestId,
requestName: params.requestName,
deductionType: params.deductionType,
amount: params.amount,
},
],
}
return createJournalEntry(supabase, companyId, userId, input)
})
}
+7
View File
@@ -977,6 +977,13 @@ const INVOICE: Record<string, StructuredErrorEntry> = {
message_en:
'The amount cannot be booked against the request: it exceeds the requested or decided amount. Book the transaction another way.',
},
ROT_RUT_SETTLE_SET_AMOUNT: {
httpStatus: 400,
message_sv:
'Beloppet stämmer inte med summan av de valda begäran. Skatteverket betalar ut exakt beslutade belopp, så flera begäran kan bara bokföras tillsammans när transaktionen motsvarar summan till öret.',
message_en:
'The amount does not equal the sum of the selected requests. Skatteverket pays exactly the decided amounts, so several requests can only be booked together when the transaction equals their sum to the öre.',
},
ROT_RUT_SETTLE_RACE: {
httpStatus: 409,
message_sv:
@@ -0,0 +1,134 @@
import { describe, it, expect } from 'vitest'
import { makeTransaction } from '@/tests/helpers'
import type { RotRutPayoutRequestCandidate } from '../rot-rut-payout-matching'
import {
findRotRutPayoutSetMatch,
matchTransactionsToRotRutPayoutSets,
} from '../rot-rut-payout-set-matching'
function makeRequest(
id: string,
requestedTotal: number,
overrides: Partial<RotRutPayoutRequestCandidate> = {},
): RotRutPayoutRequestCandidate {
return {
id,
name: `ROT ${id}`,
deduction_type: 'rot',
status: 'submitted',
requested_total: requestedTotal,
decided_total: null,
settlement_journal_entry_id: null,
...overrides,
}
}
const A = makeRequest('rr-a', 3000)
const B = makeRequest('rr-b', 2250)
const C = makeRequest('rr-c', 1200.5)
describe('findRotRutPayoutSetMatch', () => {
it('returns null with no open requests or no closing set', () => {
expect(findRotRutPayoutSetMatch(makeTransaction({ amount: 3000 }), [])).toBeNull()
// 3000 + 2250 = 5250; 5000 closes nothing.
expect(findRotRutPayoutSetMatch(makeTransaction({ amount: 5000 }), [A, B])).toBeNull()
})
it('matches a single begäran exactly like the 1:1 matcher', () => {
const match = findRotRutPayoutSetMatch(
makeTransaction({ amount: 3000, description: 'Insättning' }),
[A, B],
)
expect(match).toEqual({ requests: [A], total: 3000, confidence: 0.85, matchMethod: 'amount' })
})
it('matches the sum of several begäran paid in one transfer', () => {
const tx = makeTransaction({ amount: 6450.5, description: 'Skatteverket utbetalning' })
const match = findRotRutPayoutSetMatch(tx, [A, B, C])
expect(match?.requests.map((r) => r.id).sort()).toEqual(['rr-a', 'rr-b', 'rr-c'])
expect(match?.total).toBe(6450.5)
expect(match?.confidence).toBe(0.9)
expect(match?.matchMethod).toBe('amount_sum_skatteverket')
})
it('sums against the beslut amount when one is recorded', () => {
const decided = makeRequest('rr-d', 3000, { decided_total: 2500 })
expect(findRotRutPayoutSetMatch(makeTransaction({ amount: 4750 }), [decided, B])?.total).toBe(4750)
expect(findRotRutPayoutSetMatch(makeTransaction({ amount: 5250 }), [decided, B])).toBeNull()
})
it('still matches when Skatteverket is not named, at lower confidence', () => {
const tx = makeTransaction({ amount: 5250, description: 'Insättning' })
const match = findRotRutPayoutSetMatch(tx, [A, B])
expect(match?.requests.map((r) => r.id).sort()).toEqual(['rr-a', 'rr-b'])
expect(match?.confidence).toBe(0.8)
expect(match?.matchMethod).toBe('amount_sum')
})
it('never fuzzy-matches: an öre off closes nothing', () => {
const tx = makeTransaction({ amount: 5250.01, description: 'Skatteverket' })
expect(findRotRutPayoutSetMatch(tx, [A, B])).toBeNull()
})
it('refuses an ambiguous answer: two different sets of the same size close the row', () => {
const twin = makeRequest('rr-twin', 3000)
// {A, B} and {twin, B} both sum to 5250.
expect(findRotRutPayoutSetMatch(makeTransaction({ amount: 5250 }), [A, B, twin])).toBeNull()
// With the twin gone the answer is unique again.
expect(findRotRutPayoutSetMatch(makeTransaction({ amount: 5250 }), [A, B])).not.toBeNull()
})
it('ignores expenses, non-SEK rows and unmatchable requests', () => {
expect(findRotRutPayoutSetMatch(makeTransaction({ amount: -5250 }), [A, B])).toBeNull()
expect(
findRotRutPayoutSetMatch(makeTransaction({ amount: 5250, currency: 'EUR' as never }), [A, B]),
).toBeNull()
const settled = makeRequest('rr-a', 3000, { settlement_journal_entry_id: 'je-1' })
expect(findRotRutPayoutSetMatch(makeTransaction({ amount: 5250 }), [settled, B])).toBeNull()
const cancelled = makeRequest('rr-a', 3000, { status: 'cancelled' })
expect(findRotRutPayoutSetMatch(makeTransaction({ amount: 5250 }), [cancelled, B])).toBeNull()
})
it('respects the set-size cap', () => {
const tx = makeTransaction({ amount: 6450.5 })
expect(findRotRutPayoutSetMatch(tx, [A, B, C], { maxSize: 2 })).toBeNull()
expect(findRotRutPayoutSetMatch(tx, [A, B, C], { maxSize: 3 })).not.toBeNull()
})
})
describe('matchTransactionsToRotRutPayoutSets', () => {
it('pairs rows newest first and drains the pool so a begäran is offered once', () => {
const rows = [
makeTransaction({ id: 'tx-1', amount: 5250, date: '2026-07-12' }),
makeTransaction({ id: 'tx-2', amount: 5250, date: '2026-07-10' }),
makeTransaction({ id: 'tx-3', amount: 1200.5, date: '2026-07-09' }),
]
const out = matchTransactionsToRotRutPayoutSets(rows, [A, B, C])
expect([...out.keys()]).toEqual(['tx-1', 'tx-3'])
expect(out.get('tx-1')?.requests.map((r) => r.id).sort()).toEqual(['rr-a', 'rr-b'])
expect(out.get('tx-3')?.requests.map((r) => r.id)).toEqual(['rr-c'])
})
it('skips booked, reviewed and 1:1-hinted rows, and a hinted begäran leaves the pool', () => {
const rows = [
makeTransaction({ id: 'tx-booked', amount: 5250, journal_entry_id: 'je-9' }),
makeTransaction({ id: 'tx-reviewed', amount: 5250, is_business: true }),
makeTransaction({
id: 'tx-hinted',
amount: 3000,
potential_rot_rut_payout_request_id: 'rr-a',
}),
makeTransaction({ id: 'tx-set', amount: 5250 }),
makeTransaction({ id: 'tx-rest', amount: 3450.5 }),
]
const out = matchTransactionsToRotRutPayoutSets(rows, [A, B, C])
// A is claimed by the hint, so 5250 (A + B) cannot close; B + C = 3450.5 can.
expect([...out.keys()]).toEqual(['tx-rest'])
expect(out.get('tx-rest')?.requests.map((r) => r.id).sort()).toEqual(['rr-b', 'rr-c'])
})
it('returns an empty map without rows or requests', () => {
expect(matchTransactionsToRotRutPayoutSets([], [A]).size).toBe(0)
expect(matchTransactionsToRotRutPayoutSets([makeTransaction({ amount: 3000 })], []).size).toBe(0)
})
})
+254 -1
View File
@@ -3,8 +3,10 @@ import type { SupabaseClient } from '@supabase/supabase-js'
import { createQueuedMockSupabase } from '@/tests/helpers'
const mockCreatePayoutEntry = vi.fn()
const mockCreatePayoutSetEntry = vi.fn()
vi.mock('@/lib/bookkeeping/rot-rut-entries', () => ({
createRotRutPayoutEntry: (...args: unknown[]) => mockCreatePayoutEntry(...args),
createRotRutPayoutSetEntry: (...args: unknown[]) => mockCreatePayoutSetEntry(...args),
}))
const mockLogMatchEvent = vi.fn()
@@ -24,7 +26,7 @@ vi.mock('@/lib/transactions/inbox-underlag', () => ({
propagateUnderlagForBookedTransaction: (...args: unknown[]) => mockPropagateUnderlag(...args),
}))
import { settleRotRutPayoutRequest } from '../rot-rut-settle'
import { settleRotRutPayoutRequest, settleRotRutPayoutRequestSet } from '../rot-rut-settle'
const { supabase: mockSupabase, enqueue, reset, findCall, findCalls } = createQueuedMockSupabase()
const supabase = mockSupabase as unknown as SupabaseClient
@@ -319,3 +321,254 @@ describe('settleRotRutPayoutRequest', () => {
expect(findCalls('rot_rut_payout_requests', 'update')).toEqual([])
})
})
// ---------------------------------------------------------------------------
// Bundled payout: several begäran paid in ONE transfer (#2239)
// ---------------------------------------------------------------------------
const REQUEST_ID_2 = '33333333-3333-4333-8333-333333333333'
function makeSecondRequestRow(overrides: Record<string, unknown> = {}) {
return makeRequestRow({
id: REQUEST_ID_2,
name: 'RUT 2026-07',
deduction_type: 'rut',
requested_total: 2250,
...overrides,
})
}
describe('settleRotRutPayoutRequestSet', () => {
const setParams = {
requestIds: [REQUEST_ID, REQUEST_ID_2],
paymentDate: '2026-07-10',
amount: 5250,
bankAccount: '1930',
}
it('returns ROT_RUT_REQUEST_NOT_FOUND naming the begäran that are missing', async () => {
enqueue({ data: [makeRequestRow()] })
const outcome = await settleRotRutPayoutRequestSet(supabase, 'user-1', 'company-1', setParams)
expect(outcome).toEqual({
ok: false,
kind: 'code',
code: 'ROT_RUT_REQUEST_NOT_FOUND',
details: { request_ids: [REQUEST_ID_2] },
})
expect(mockCreatePayoutSetEntry).not.toHaveBeenCalled()
})
it('refuses when any begäran is settled or cancelled, before booking anything', async () => {
enqueue({ data: [makeRequestRow(), makeSecondRequestRow({ settlement_journal_entry_id: 'je-0' })] })
const outcome = await settleRotRutPayoutRequestSet(supabase, 'user-1', 'company-1', setParams)
expect(outcome).toMatchObject({
ok: false,
code: 'ROT_RUT_SETTLE_INVALID_STATE',
details: { request_id: REQUEST_ID_2, already_settled: true },
})
expect(mockCreatePayoutSetEntry).not.toHaveBeenCalled()
})
it('refuses a transfer that is not the exact sum of the expected payouts', async () => {
enqueue({ data: [makeRequestRow(), makeSecondRequestRow()] })
const outcome = await settleRotRutPayoutRequestSet(supabase, 'user-1', 'company-1', {
...setParams,
amount: 5000,
})
expect(outcome).toEqual({
ok: false,
kind: 'code',
code: 'ROT_RUT_SETTLE_SET_AMOUNT',
details: { amount: 5000, expected_total: 5250, request_ids: [REQUEST_ID, REQUEST_ID_2] },
})
expect(mockCreatePayoutSetEntry).not.toHaveBeenCalled()
expect(findCalls('rot_rut_payout_requests', 'update')).toEqual([])
})
it('sums against the recorded beslut, not the requested total', async () => {
enqueue({ data: [makeRequestRow({ decided_total: 2500 }), makeSecondRequestRow()] })
const outcome = await settleRotRutPayoutRequestSet(supabase, 'user-1', 'company-1', setParams)
expect(outcome).toMatchObject({ code: 'ROT_RUT_SETTLE_SET_AMOUNT', details: { expected_total: 4750 } })
})
it('books ONE voucher with a 1513 leg per begäran, marks every begäran paid and links the row', async () => {
enqueue({ data: [makeRequestRow(), makeSecondRequestRow()] })
mockCreatePayoutSetEntry.mockResolvedValue({ id: 'je-set' })
enqueue({
data: makeRequestRow({ status: 'paid', settlement_journal_entry_id: 'je-set', decided_total: 3000 }),
})
enqueue({
data: makeSecondRequestRow({ status: 'paid', settlement_journal_entry_id: 'je-set', decided_total: 2250 }),
})
enqueue({ data: [{ id: TX_ID }] }) // transactions CAS update
enqueue({ data: [{ id: 'item-1', requested_amount: 3000 }] }) // items, request 1
enqueue({ data: null }) // item mirror
enqueue({ data: [] }) // items, request 2
const outcome = await settleRotRutPayoutRequestSet(supabase, 'user-1', 'company-1', {
...setParams,
transactionId: TX_ID,
})
expect(outcome).toMatchObject({ ok: true, journalEntryId: 'je-set', amount: 5250 })
expect(outcome.ok && outcome.requests.map((r) => r.id)).toEqual([REQUEST_ID, REQUEST_ID_2])
expect(mockCreatePayoutSetEntry).toHaveBeenCalledTimes(1)
expect(mockCreatePayoutSetEntry).toHaveBeenCalledWith(expect.anything(), 'company-1', 'user-1', {
paymentDate: '2026-07-10',
bankAccount: '1930',
legs: [
{ requestId: REQUEST_ID, requestName: 'ROT 2026-07', deductionType: 'rot', amount: 3000 },
{ requestId: REQUEST_ID_2, requestName: 'RUT 2026-07', deductionType: 'rut', amount: 2250 },
],
})
// The single-request writer is never used for a bundle.
expect(mockCreatePayoutEntry).not.toHaveBeenCalled()
const requestUpdates = findCalls('rot_rut_payout_requests', 'update').map((c) => c[0])
expect(requestUpdates).toHaveLength(2)
for (const update of requestUpdates) {
expect(update).toMatchObject({ settlement_journal_entry_id: 'je-set', status: 'paid' })
}
expect(findCalls('rot_rut_payout_requests', 'is')).toEqual([
['settlement_journal_entry_id', null],
['settlement_journal_entry_id', null],
])
const txUpdate = findCall('transactions', 'update')?.[0] as Record<string, unknown>
expect(txUpdate).toMatchObject({
journal_entry_id: 'je-set',
is_business: true,
category: 'income_other',
potential_rot_rut_payout_request_id: null,
})
expect(mockLogMatchEvent).toHaveBeenCalledWith(
expect.anything(),
'user-1',
TX_ID,
'matched',
expect.objectContaining({
matchMethod: 'rot_rut_payout_manual_confirm',
newState: expect.objectContaining({
journal_entry_id: 'je-set',
rot_rut_payout_request_ids: [REQUEST_ID, REQUEST_ID_2],
}),
}),
)
expect(mockClearSuggestions).toHaveBeenCalledTimes(2)
expect(mockClearSuggestions).toHaveBeenCalledWith(
expect.anything(),
'company-1',
'rot_rut_payout_request',
REQUEST_ID_2,
{ exceptTransactionId: TX_ID },
)
})
it('reports ROT_RUT_SETTLE_RACE with the begäran that did attach when a later lock loses', async () => {
enqueue({ data: [makeRequestRow(), makeSecondRequestRow()] })
mockCreatePayoutSetEntry.mockResolvedValue({ id: 'je-set' })
enqueue({
data: makeRequestRow({ status: 'paid', settlement_journal_entry_id: 'je-set', decided_total: 3000 }),
})
enqueue({ data: null }) // second CAS matched 0 rows
const outcome = await settleRotRutPayoutRequestSet(supabase, 'user-1', 'company-1', {
...setParams,
transactionId: TX_ID,
})
expect(outcome).toEqual({
ok: false,
kind: 'code',
code: 'ROT_RUT_SETTLE_RACE',
details: { journal_entry_id: 'je-set', request_id: REQUEST_ID_2, settled_request_ids: [REQUEST_ID] },
})
// The loser never touches the bank row.
expect(findCalls('transactions', 'update')).toEqual([])
})
it('reports ROT_RUT_MATCH_TX_LINK_FAILED when the optimistic lock loses, keeping the voucher', async () => {
enqueue({ data: [makeRequestRow(), makeSecondRequestRow()] })
mockCreatePayoutSetEntry.mockResolvedValue({ id: 'je-set' })
enqueue({ data: makeRequestRow({ status: 'paid', settlement_journal_entry_id: 'je-set' }) })
enqueue({ data: makeSecondRequestRow({ status: 'paid', settlement_journal_entry_id: 'je-set' }) })
enqueue({ data: [] }) // CAS matched 0 rows: someone booked the row meanwhile
const outcome = await settleRotRutPayoutRequestSet(supabase, 'user-1', 'company-1', {
...setParams,
transactionId: TX_ID,
})
expect(outcome).toEqual({
ok: false,
kind: 'code',
code: 'ROT_RUT_MATCH_TX_LINK_FAILED',
details: { journal_entry_id: 'je-set', request_ids: [REQUEST_ID, REQUEST_ID_2] },
})
expect(mockLogMatchEvent).not.toHaveBeenCalled()
})
it('leaves a partially decided begäran partially_paid and un-mirrored inside a bundle', async () => {
// Skatteverket decided 2 500 of the 3 000 requested on the first begäran:
// its leg is the beslut, the bundle is 2 500 + 2 250 = 4 750 exactly.
enqueue({
data: [
makeRequestRow({ decided_total: 2500, decided_at: '2026-07-01T00:00:00Z' }),
makeSecondRequestRow(),
],
})
mockCreatePayoutSetEntry.mockResolvedValue({ id: 'je-set' })
enqueue({
data: makeRequestRow({
status: 'partially_paid',
settlement_journal_entry_id: 'je-set',
decided_total: 2500,
}),
})
enqueue({
data: makeSecondRequestRow({ status: 'paid', settlement_journal_entry_id: 'je-set', decided_total: 2250 }),
})
enqueue({ data: [{ id: 'item-2', requested_amount: 2250 }] }) // items, request 2 only
enqueue({ data: null }) // item mirror, request 2
const outcome = await settleRotRutPayoutRequestSet(supabase, 'user-1', 'company-1', {
...setParams,
amount: 4750,
})
expect(outcome).toMatchObject({ ok: true, journalEntryId: 'je-set', amount: 4750 })
expect(outcome.ok && outcome.requests.map((r) => r.status)).toEqual(['partially_paid', 'paid'])
expect(mockCreatePayoutSetEntry).toHaveBeenCalledWith(
expect.anything(),
'company-1',
'user-1',
expect.objectContaining({
legs: [
expect.objectContaining({ requestId: REQUEST_ID, amount: 2500 }),
expect.objectContaining({ requestId: REQUEST_ID_2, amount: 2250 }),
],
}),
)
const requestUpdates = findCalls('rot_rut_payout_requests', 'update').map((c) => c[0])
expect(requestUpdates).toEqual([
{ settlement_journal_entry_id: 'je-set', status: 'partially_paid', decided_total: 2500 },
expect.objectContaining({ settlement_journal_entry_id: 'je-set', status: 'paid', decided_total: 2250 }),
])
// Only the fully paid begäran mirrors requested_amount onto its items.
expect(
findCalls('rot_rut_payout_request_items', 'eq').filter((c) => c[0] === 'request_id'),
).toEqual([['request_id', REQUEST_ID_2]])
expect(findCalls('rot_rut_payout_request_items', 'update').map((c) => c[0])).toEqual([
{ decided_amount: 2250 },
])
// Both carry a voucher now, so both retire their sibling hints.
expect(mockClearSuggestions).toHaveBeenCalledTimes(2)
})
it('surfaces an engine failure as a raw error without touching any request', async () => {
enqueue({ data: [makeRequestRow(), makeSecondRequestRow()] })
mockCreatePayoutSetEntry.mockRejectedValue(new Error('No open fiscal period'))
const outcome = await settleRotRutPayoutRequestSet(supabase, 'user-1', 'company-1', setParams)
expect(outcome).toMatchObject({ ok: false, kind: 'error', stage: 'book' })
expect(findCalls('rot_rut_payout_requests', 'update')).toEqual([])
})
})
+187
View File
@@ -0,0 +1,187 @@
/**
* ROT/RUT payout SET matching: one bank row from Skatteverket that settles
* several open begäran at once.
*
* Skatteverket decides per begäran but pays out everything it decided that
* day in ONE transfer, so the bank row often equals no single request and the
* 1:1 matcher (rot-rut-payout-matching.ts) stays silent. The candidate here
* is the exact covering set: 1..4 open begäran whose expected payouts
* (decided_total ?? requested_total) sum to the row to the öre. The search is
* the reconciliation module's findExactCoveringSet; this file only decides
* what goes into the pool and what comes out.
*
* Same refusals as the 1:1 matcher: SEK income rows only, unmatchable
* requests never take part, and an ambiguous answer (a second, different set
* of the same size that also closes the row) yields no suggestion: the
* amount alone cannot say which begäran Skatteverket paid, and guessing
* would clear the wrong 1513 fordran. There is no fuzzy pass on purpose:
* Skatteverket pays exactly the decided sums.
*
* No hint column for a set. The inbox page, the worklist and the ingest path
* recompute it from the open pool (a handful of rows per company), the way
* expense-payout suggestions already are; a persisted uuid[] would need every
* clear path the single hint has and could still go stale (#1259).
*
* Pure and client-safe on purpose: the inbox page runs it in the browser.
*/
import { findExactCoveringSet } from '@/lib/reconciliation/covering-set'
import { roundOre } from '@/lib/money'
import {
expectedRotRutPayoutAmount,
isMatchableRotRutPayoutRequest,
mentionsSkatteverket,
type RotRutPayoutRequestCandidate,
} from './rot-rut-payout-matching'
/** Largest set considered. Skatteverket rarely bundles more decisions per transfer. */
const DEFAULT_MAX_SET_SIZE = 4
export interface RotRutPayoutSetMatch<
T extends RotRutPayoutRequestCandidate = RotRutPayoutRequestCandidate,
> {
/** The begäran the row settles, in the order they are booked (largest first). */
requests: T[]
/** Sum of the requests' expected payouts: equals the row amount to the öre. */
total: number
confidence: number
matchMethod: 'amount_skatteverket' | 'amount' | 'amount_sum_skatteverket' | 'amount_sum'
}
export interface RotRutSetMatchableTransaction {
amount: number
currency?: string | null
description?: string | null
merchant_name?: string | null
}
export interface RotRutSetMatchOptions {
/** Largest set considered. Default 4. */
maxSize?: number
}
interface PoolEntry<T extends RotRutPayoutRequestCandidate> {
id: string
amount: number
dateDistanceDays: number
request: T
}
function toPool<T extends RotRutPayoutRequestCandidate>(requests: T[]): PoolEntry<T>[] {
return requests
.filter((request) => isMatchableRotRutPayoutRequest(request))
.map((request) => ({
id: request.id,
amount: expectedRotRutPayoutAmount(request),
// No payout-date signal on a begäran: equal-size sets rank by amount,
// then id (findExactCoveringSet's own deterministic order).
dateDistanceDays: 0,
request,
}))
}
function searchSet<T extends RotRutPayoutRequestCandidate>(
target: number,
pool: PoolEntry<T>[],
maxSize: number,
): PoolEntry<T>[] | null {
return findExactCoveringSet(target, pool, { maxSize, maxCandidates: pool.length })
}
/**
* Find the open begäran (1..maxSize of them) whose expected payouts sum to
* an income transaction, or null. Pure: the caller loads the open requests
* once.
*/
export function findRotRutPayoutSetMatch<T extends RotRutPayoutRequestCandidate>(
transaction: RotRutSetMatchableTransaction,
openRequests: T[],
options: RotRutSetMatchOptions = {},
): RotRutPayoutSetMatch<T> | null {
if (openRequests.length === 0) return null
// Skatteverket pays in kronor only. A NULL currency on a legacy bank row
// means SEK (transactions.currency DEFAULT 'SEK').
if ((transaction.currency || 'SEK').toUpperCase() !== 'SEK') return null
if (!(transaction.amount > 0)) return null
const maxSize = Math.max(1, options.maxSize ?? DEFAULT_MAX_SET_SIZE)
const target = roundOre(transaction.amount)
const pool = toPool(openRequests)
if (pool.length === 0) return null
const best = searchSet(target, pool, maxSize)
if (!best) return null
// Ambiguity: any OTHER set of the same size that also closes the row must
// omit at least one member of `best`, so dropping each member in turn and
// searching again finds it if it exists. Sizes below |best| cannot appear
// (the search returns the smallest set first), so a hit is a genuine tie.
for (const member of best) {
const without = pool.filter((entry) => entry.id !== member.id)
if (searchSet(target, without, best.length)) return null
}
const named = mentionsSkatteverket(transaction)
const single = best.length === 1
return {
requests: best.map((entry) => entry.request),
total: roundOre(best.reduce((sum, entry) => sum + entry.amount, 0)),
// A sum over several begäran is a weaker signal than one exact amount:
// one notch below the 1:1 ladder (0.95 / 0.85).
confidence: single ? (named ? 0.95 : 0.85) : named ? 0.9 : 0.8,
matchMethod: single
? named
? 'amount_skatteverket'
: 'amount'
: named
? 'amount_sum_skatteverket'
: 'amount_sum',
}
}
export interface RotRutSetMatchableRow extends RotRutSetMatchableTransaction {
id: string
is_business?: boolean | null
journal_entry_id?: string | null
/**
* A persisted 1:1 hint (rot-rut-payout-matching.ts) wins for its row and
* takes its begäran out of the pool, so a set never offers a request that
* another row is already about to settle.
*/
potential_rot_rut_payout_request_id?: string | null
}
/**
* Pair unbooked SEK income rows with the set of open begäran they settle.
* Rows are walked in the order given (callers pass newest first); every set
* handed out drains the pool, mirroring the one-payout-per-begäran rule at
* bank ingest. Rows that are booked, already reviewed (is_business set) or
* carrying a persisted 1:1 hint are skipped: they have their own path.
*/
export function matchTransactionsToRotRutPayoutSets<T extends RotRutPayoutRequestCandidate>(
transactions: RotRutSetMatchableRow[],
openRequests: T[],
options: RotRutSetMatchOptions = {},
): Map<string, RotRutPayoutSetMatch<T>> {
const out = new Map<string, RotRutPayoutSetMatch<T>>()
if (transactions.length === 0 || openRequests.length === 0) return out
const claimed = new Set<string>()
for (const tx of transactions) {
if (tx.potential_rot_rut_payout_request_id) claimed.add(tx.potential_rot_rut_payout_request_id)
}
let pool = openRequests.filter((request) => !claimed.has(request.id))
for (const tx of transactions) {
if (pool.length === 0) break
if (tx.journal_entry_id) continue
if (tx.is_business !== null && tx.is_business !== undefined) continue
if (tx.potential_rot_rut_payout_request_id) continue
const match = findRotRutPayoutSetMatch(tx, pool, options)
if (!match) continue
out.set(tx.id, match)
const taken = new Set(match.requests.map((request) => request.id))
pool = pool.filter((request) => !taken.has(request.id))
}
return out
}
File diff suppressed because it is too large Load Diff
+47
View File
@@ -1812,6 +1812,53 @@ describe('ingestTransactions', () => {
expect(mockEvaluateMappingRules).not.toHaveBeenCalled()
})
// -----------------------------------------------------------------------
// 4a'. Skatteverket bundles the beslut it pays that day into ONE transfer
// (#2239): a row equal to the SUM of several open begäran gets no hint
// column (the inbox recomputes the set) but must still skip the mapping
// engine and drain the pool, exactly like a 1:1 hint.
// -----------------------------------------------------------------------
it('recognises a bundled ROT/RUT payout (sum of several begäran) without persisting a hint', async () => {
const { supabase, enqueue, updates } = createQueueMockSupabase()
const raw = makeRaw({ amount: 5250, description: 'Skatteverket utbetalning' })
const inserted = makeTransaction({
id: 'tx-skv-set',
amount: 5250,
currency: 'SEK',
description: 'Skatteverket utbetalning',
external_id: raw.external_id,
})
const request = (id: string, name: string, requestedTotal: number) => ({
id,
name,
deduction_type: 'rot' as const,
status: 'submitted',
requested_total: requestedTotal,
decided_total: null,
settlement_journal_entry_id: null,
})
mockLoadOpenRotRutPayoutRequests.mockResolvedValueOnce([
request('rr-1', 'ROT 2026-07', 3000),
request('rr-2', 'ROT 2026-08', 2250),
])
mockGetBestInvoiceMatch.mockResolvedValue(null)
enqueue({ data: [], error: null }) // booked map
enqueue({ data: [], error: null }) // unbooked bank-synced map
enqueue({ data: [], error: null }) // supplier invoices pool
enqueue({ data: [], error: null }) // external_id dedup
enqueue({ data: inserted, error: null }) // insert
const result = await ingestTransactions(supabase as never, COMPANY_ID, USER_ID, [raw])
expect(result.imported).toBe(1)
expect(result.auto_matched_invoices).toBe(1)
// No single begäran equals the row, so no 1:1 hint is written; the set is
// recomputed at read time instead of persisted.
expect(updates['transactions'] ?? []).toEqual([])
expect(mockEvaluateMappingRules).not.toHaveBeenCalled()
})
// -----------------------------------------------------------------------
// 4b. Supplier-invoice match at sync is ALWAYS a suggestion, never a hard
// link. Regression: a high-confidence hit used to set
+24
View File
@@ -9,6 +9,7 @@ import {
type RotRutPayoutRequestCandidate,
} from '@/lib/invoices/rot-rut-payout-matching'
import { loadOpenRotRutPayoutRequests } from '@/lib/invoices/rot-rut-payout-candidates'
import { findRotRutPayoutSetMatch } from '@/lib/invoices/rot-rut-payout-set-matching'
import { fetchExchangeRate } from '@/lib/currency/riksbanken'
import { logMatchEvent } from '@/lib/invoices/match-log'
import { fetchAllRows } from '@/lib/supabase/fetch-all'
@@ -1124,6 +1125,29 @@ export async function ingestTransactions(
result.auto_matched_invoices++
continue
}
// 3d. No single begäran equals the row: Skatteverket bundles the
// beslut it pays that day into one transfer, so try the exact
// covering set (#2239). A set has no hint column (the inbox and the
// worklist recompute it from the open pool), but the row must still
// skip the mapping engine and drain the pool exactly like a 1:1 hint.
if (!match) {
const set = findRotRutPayoutSetMatch(newTransaction as Transaction, openRotRutPayoutRequests)
if (set && set.requests.length > 1) {
const requestIds = set.requests.map((req) => req.id)
logMatchEvent(supabase, userId, newTransaction.id, 'auto_suggested', {
matchConfidence: set.confidence,
matchMethod: set.matchMethod,
newState: { rot_rut_payout_request_ids: requestIds },
})
for (const id of requestIds) matchedRotRutRequestIds.add(id)
openRotRutPayoutRequests = openRotRutPayoutRequests.filter(
(req) => !requestIds.includes(req.id),
)
result.auto_matched_invoices++
continue
}
}
} catch {
// Non-critical: continue processing
}
+70
View File
@@ -14,6 +14,7 @@ import {
countVerifikatMissingDocument,
listExpensePayoutsDue,
listExpensePayoutSuggestions,
listRotRutPayoutSetSuggestions,
listSuggestedMatches,
} from '../categories'
import {
@@ -266,6 +267,75 @@ describe('listSuggestedMatches', () => {
expect(lookup).toEqual(['settlement_journal_entry_id', null])
})
it('offers a bundled Skatteverket payout (sum of several begäran) with request_ids', async () => {
enqueue({ data: [] }) // no hinted rows
enqueue({ data: [] }) // expense_claims: nobody is owed
enqueue({
data: [
{ id: 'rr-1', name: 'ROT 2026-07', deduction_type: 'rot', status: 'submitted', requested_total: '3000.00', decided_total: null, settlement_journal_entry_id: null },
{ id: 'rr-2', name: 'RUT 2026-07', deduction_type: 'rut', status: 'submitted', requested_total: '2250.00', decided_total: null, settlement_journal_entry_id: null },
],
})
enqueue({
data: [
{
id: 'tx-bundle',
date: '2026-07-12',
description: 'SKATTEVERKET',
merchant_name: null,
amount: 5250,
currency: 'SEK',
is_business: null,
journal_entry_id: null,
potential_rot_rut_payout_request_id: null,
},
{
id: 'tx-other',
date: '2026-07-11',
description: 'Kund AB',
merchant_name: null,
amount: 4000,
currency: 'SEK',
is_business: null,
journal_entry_id: null,
potential_rot_rut_payout_request_id: null,
},
],
})
const matches = await listSuggestedMatches(supabase, COMPANY)
expect(matches).toEqual([
{
transaction_id: 'tx-bundle',
transaction_date: '2026-07-12',
transaction_description: 'SKATTEVERKET',
transaction_amount: 5250,
transaction_currency: 'SEK',
kind: 'rot_rut_payout',
candidate_id: 'rr-1',
candidate_number: 'ROT 2026-07 + RUT 2026-07',
counterparty_name: 'Skatteverket',
candidate_total: 5250,
request_ids: ['rr-1', 'rr-2'],
},
])
// The scan is bounded to the pool's amount range and to unbooked, unreviewed rows.
const gte = findCall('transactions', 'gte')
const lte = findCall('transactions', 'lte')
expect(gte).toEqual(['amount', 2250])
expect(lte).toEqual(['amount', 5250])
})
it('returns no bundle suggestions for a company with fewer than two open begäran', async () => {
enqueue({
data: [
{ id: 'rr-1', name: 'ROT 2026-07', deduction_type: 'rot', status: 'submitted', requested_total: 3000, decided_total: null, settlement_journal_entry_id: null },
],
})
await expect(listRotRutPayoutSetSuggestions(supabase, COMPANY)).resolves.toEqual([])
expect(findCalls('transactions', 'select')).toEqual([])
})
it('maps invoice and supplier-invoice hints to confirmable rows', async () => {
enqueue({
data: [
+100 -1
View File
@@ -8,9 +8,16 @@
* down the dashboard layout or the home page.
*/
import { OPEN_ROT_RUT_PAYOUT_STATUSES } from '@/lib/invoices/rot-rut-payout-matching'
import {
OPEN_ROT_RUT_PAYOUT_STATUSES,
expectedRotRutPayoutAmount,
isMatchableRotRutPayoutRequest,
} from '@/lib/invoices/rot-rut-payout-matching'
import { loadOpenRotRutPayoutRequests } from '@/lib/invoices/rot-rut-payout-candidates'
import { matchTransactionsToRotRutPayoutSets } from '@/lib/invoices/rot-rut-payout-set-matching'
import type { SupabaseClient } from '@supabase/supabase-js'
import { createLogger } from '@/lib/logger'
import { roundOre } from '@/lib/money'
import { fetchAllRows } from '@/lib/supabase/fetch-all'
import {
groupExpenseClaimsByPerson,
@@ -510,9 +517,101 @@ export async function listSuggestedMatches(
for (const m of expenseMatches) {
if (!seen.has(m.transaction_id)) matches.push(m)
}
// Skatteverket's bundled ROT/RUT payout (several begäran in one transfer):
// no hint column either, recomputed from the open begäran. Confirm endpoint
// is the same match-rot-rut-payout route, with request_ids.
const setMatches = await listRotRutPayoutSetSuggestions(supabase, companyId, limit)
for (const m of setMatches) {
if (!seen.has(m.transaction_id)) {
matches.push(m)
seen.add(m.transaction_id)
}
}
return matches
}
/** Newest unbooked income rows scanned for a bundled ROT/RUT payout. */
const ROT_RUT_SET_SCAN_LIMIT = 200
/**
* Unbooked SEK income rows that equal the SUM of several open begäran:
* Skatteverket bundles the beslut it pays that day into one transfer
* (#2239). Read-time pairing over the open pool, like the expense payouts:
* no hint column, and nothing at all for a company without two open
* begäran. The rule lives in lib/invoices/rot-rut-payout-set-matching.ts;
* a single-begäran hit is the persisted 1:1 hint's job and is not repeated
* here.
*/
export async function listRotRutPayoutSetSuggestions(
supabase: SupabaseClient,
companyId: string,
limit = 20,
): Promise<SuggestedMatch[]> {
const pool = (await loadOpenRotRutPayoutRequests(supabase, companyId)).filter((request) =>
isMatchableRotRutPayoutRequest(request),
)
if (pool.length < 2) return []
const expected = pool.map((request) => expectedRotRutPayoutAmount(request))
const minExpected = Math.min(...expected)
const maxTotal = roundOre(expected.reduce((sum, amount) => sum + amount, 0))
// An invoice hint wins over a begäran (same precedence as the hint path),
// so rows carrying one are not candidates. Rows with a 1:1 begäran hint
// ARE fetched: the matcher skips them but takes their begäran out of the
// pool, so a set never offers a request another row is about to settle.
const { data, error } = await supabase
.from('transactions')
.select(
'id, date, description, merchant_name, amount, currency, is_business, journal_entry_id, potential_rot_rut_payout_request_id',
)
.eq('company_id', companyId)
.is('is_business', null)
.eq('is_ignored', false)
.is('journal_entry_id', null)
.is('potential_invoice_id', null)
.gte('amount', minExpected)
.lte('amount', maxTotal)
.order('date', { ascending: false })
.limit(ROT_RUT_SET_SCAN_LIMIT)
if (error) {
log.error('worklist listRotRutPayoutSetSuggestions failed', { companyId, reason: error.message })
return []
}
type TxRow = {
id: string
date: string
description: string | null
merchant_name: string | null
amount: number
currency: string | null
is_business: boolean | null
journal_entry_id: string | null
potential_rot_rut_payout_request_id: string | null
}
const txs = (data ?? []) as TxRow[]
const paired = matchTransactionsToRotRutPayoutSets(txs, pool)
const out: SuggestedMatch[] = []
for (const tx of txs) {
const m = paired.get(tx.id)
if (!m || m.requests.length < 2) continue
out.push({
transaction_id: tx.id,
transaction_date: tx.date,
transaction_description: tx.description ?? '',
transaction_amount: tx.amount,
transaction_currency: tx.currency ?? 'SEK',
kind: 'rot_rut_payout',
candidate_id: m.requests[0].id,
candidate_number: m.requests.map((request) => request.name).join(' + '),
counterparty_name: 'Skatteverket',
candidate_total: m.total,
request_ids: m.requests.map((request) => request.id),
})
if (out.length >= limit) break
}
return out
}
/**
* Accounts not signed off through the end of the previous month. Cheap by
* construction (three small reads, no bridge computation) and zero for
+7
View File
@@ -168,6 +168,13 @@ export interface SuggestedMatch {
candidate_number: string | null
counterparty_name: string | null
candidate_total: number | null
/**
* rot_rut_payout only: every begäran the transfer settles. Absent for a
* persisted 1:1 hint (candidate_id is the request); several when
* Skatteverket paid a bundle of beslut in one transfer (#2239), in which
* case candidate_number joins their names.
*/
request_ids?: string[]
/** expense_payout only: the registered claims this transfer pays. */
claim_ids?: string[]
}