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 <noreply@anthropic.com>

* 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 <noreply@anthropic.com>

---------

Co-authored-by: Jakob Wennberg <311770904+jakobwennberg-oss@users.noreply.github.com>
Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
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
+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
}