fdcb7d937e
* 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>
256 lines
10 KiB
TypeScript
256 lines
10 KiB
TypeScript
import { randomUUID } from 'node:crypto'
|
|
import { describe, expect, it } from 'vitest'
|
|
import { getPool } from './setup'
|
|
import { insertPostedJournalEntry, seedCompany } from './fixtures'
|
|
|
|
/**
|
|
* Migration 20260907160000_rot_rut_reclaim:
|
|
* - journal_entries.source_type accepts 'rot_rut_reclaim'
|
|
* - one live reclaim voucher per begäran (partial unique index)
|
|
* - invoices.deduction_reclaimed_total never exceeds the deduction
|
|
* - the INSERT guard derives remaining_amount with the reclaimed term
|
|
*/
|
|
|
|
async function insertCustomerInvoice(
|
|
companyId: string,
|
|
userId: string,
|
|
cols: { deduction_total: number; deduction_reclaimed_total: number; remaining_amount?: number | null },
|
|
): Promise<string> {
|
|
const customerId = randomUUID()
|
|
await getPool().query(
|
|
`INSERT INTO public.customers (id, user_id, company_id, name, customer_type)
|
|
VALUES ($1, $2, $3, 'Kund AB', 'swedish_business')`,
|
|
[customerId, userId, companyId],
|
|
)
|
|
const id = randomUUID()
|
|
await getPool().query(
|
|
`INSERT INTO public.invoices
|
|
(id, user_id, company_id, customer_id, invoice_number, invoice_date, due_date,
|
|
currency, subtotal, vat_amount, total, vat_treatment, vat_rate, status,
|
|
paid_amount, remaining_amount, deduction_total, deduction_reclaimed_total)
|
|
VALUES ($1, $2, $3, $4, $5, '2026-01-15', '2026-02-14', 'SEK',
|
|
20000, 5000, 25000, 'standard_25', 25, 'sent', 0, $6, $7, $8)`,
|
|
[
|
|
id,
|
|
userId,
|
|
companyId,
|
|
customerId,
|
|
`F-${id.slice(0, 8)}`,
|
|
cols.remaining_amount ?? null,
|
|
cols.deduction_total,
|
|
cols.deduction_reclaimed_total,
|
|
],
|
|
)
|
|
return id
|
|
}
|
|
|
|
describe('rot/rut reclaim (migration 20260907160000)', () => {
|
|
it('accepts source_type rot_rut_reclaim and allows exactly one live reclaim voucher per begäran', async () => {
|
|
const seeded = await seedCompany()
|
|
const requestId = randomUUID()
|
|
const common = {
|
|
userId: seeded.userId,
|
|
companyId: seeded.companyId,
|
|
fiscalPeriodId: seeded.fiscalPeriodId,
|
|
entryDate: '2026-08-21',
|
|
description: 'Nekat RUT-avdrag från Skatteverket (RUT 2026-08)',
|
|
sourceType: 'rot_rut_reclaim',
|
|
sourceId: requestId,
|
|
lines: [
|
|
{ accountNumber: '1510', debitAmount: 2000, creditAmount: 0 },
|
|
{ accountNumber: '1513', debitAmount: 0, creditAmount: 2000 },
|
|
],
|
|
}
|
|
|
|
const results = await Promise.allSettled([
|
|
insertPostedJournalEntry({ ...common, voucherNumber: 51 }),
|
|
insertPostedJournalEntry({ ...common, voucherNumber: 52 }),
|
|
])
|
|
expect(results.filter((result) => result.status === 'fulfilled')).toHaveLength(1)
|
|
const rejected = results.find((result) => result.status === 'rejected')
|
|
expect(String((rejected as PromiseRejectedResult).reason)).toMatch(
|
|
/journal_entries_rot_rut_reclaim_live_unique/,
|
|
)
|
|
|
|
// A second begäran is not blocked, nor is the payout voucher of the same begäran.
|
|
await expect(
|
|
insertPostedJournalEntry({ ...common, sourceId: randomUUID(), voucherNumber: 53 }),
|
|
).resolves.toBeTruthy()
|
|
await expect(
|
|
insertPostedJournalEntry({
|
|
...common,
|
|
sourceType: 'rot_rut_payout',
|
|
voucherNumber: 54,
|
|
lines: [
|
|
{ accountNumber: '1930', debitAmount: 3000, creditAmount: 0 },
|
|
{ accountNumber: '1513', debitAmount: 0, creditAmount: 3000 },
|
|
],
|
|
}),
|
|
).resolves.toBeTruthy()
|
|
})
|
|
|
|
it('refuses a reclaimed total above the deduction', async () => {
|
|
const seeded = await seedCompany()
|
|
await expect(
|
|
insertCustomerInvoice(seeded.companyId, seeded.userId, {
|
|
deduction_total: 7500,
|
|
deduction_reclaimed_total: 9000,
|
|
remaining_amount: 17500,
|
|
}),
|
|
).rejects.toThrow(/invoices_deduction_reclaimed_total_check/)
|
|
await expect(
|
|
insertCustomerInvoice(seeded.companyId, seeded.userId, {
|
|
deduction_total: 7500,
|
|
deduction_reclaimed_total: 7500,
|
|
remaining_amount: 25000,
|
|
}),
|
|
).resolves.toBeTruthy()
|
|
})
|
|
|
|
it('derives remaining_amount with the reclaimed term when a writer omits it', async () => {
|
|
const seeded = await seedCompany()
|
|
const id = await insertCustomerInvoice(seeded.companyId, seeded.userId, {
|
|
deduction_total: 7500,
|
|
deduction_reclaimed_total: 2500,
|
|
remaining_amount: null,
|
|
})
|
|
const { rows } = await getPool().query<{ remaining_amount: string }>(
|
|
'SELECT remaining_amount FROM public.invoices WHERE id = $1',
|
|
[id],
|
|
)
|
|
// 25 000 - 0 paid - 7 500 deduction + 2 500 reclaimed
|
|
expect(Number(rows[0].remaining_amount)).toBe(20000)
|
|
})
|
|
})
|
|
|
|
describe('apply / revert rot_rut_reclaim RPCs (migration 20260907160400)', () => {
|
|
async function seedReclaimCase(opts: { decidedTotal: number; itemDecided: number | null; status: string }) {
|
|
const seeded = await seedCompany()
|
|
const invoiceId = await insertCustomerInvoice(seeded.companyId, seeded.userId, {
|
|
deduction_total: 7500,
|
|
deduction_reclaimed_total: 0,
|
|
remaining_amount: 0,
|
|
})
|
|
await getPool().query(
|
|
`UPDATE public.invoices SET status = 'paid', paid_amount = 17500 WHERE id = $1`,
|
|
[invoiceId],
|
|
)
|
|
const requestId = randomUUID()
|
|
const reclaimEntryId = await insertPostedJournalEntry({
|
|
userId: seeded.userId,
|
|
companyId: seeded.companyId,
|
|
fiscalPeriodId: seeded.fiscalPeriodId,
|
|
entryDate: '2026-08-21',
|
|
description: 'Nekat ROT-avdrag från Skatteverket',
|
|
sourceType: 'rot_rut_reclaim',
|
|
sourceId: requestId,
|
|
voucherNumber: 61,
|
|
lines: [
|
|
{ accountNumber: '1510', debitAmount: 2500, creditAmount: 0 },
|
|
{ accountNumber: '1513', debitAmount: 0, creditAmount: 2500 },
|
|
],
|
|
})
|
|
await getPool().query(
|
|
`INSERT INTO public.rot_rut_payout_requests
|
|
(id, company_id, user_id, deduction_type, name, status, requested_total, decided_total, decided_at, file_name, reclaim_journal_entry_id)
|
|
VALUES ($1, $2, $3, 'rot', 'ROT 2026-08', $4, 7500, $5, now(), 'rot.xml', $6)`,
|
|
[requestId, seeded.companyId, seeded.userId, opts.status, opts.decidedTotal, reclaimEntryId],
|
|
)
|
|
const itemId = randomUUID()
|
|
await getPool().query(
|
|
`INSERT INTO public.rot_rut_payout_request_items (id, request_id, invoice_id, requested_amount, decided_amount)
|
|
VALUES ($1, $2, $3, 7500, $4)`,
|
|
[itemId, requestId, invoiceId, opts.itemDecided],
|
|
)
|
|
return { ...seeded, invoiceId, requestId, itemId }
|
|
}
|
|
|
|
async function readInvoice(invoiceId: string) {
|
|
const { rows } = await getPool().query<{
|
|
deduction_reclaimed_total: string
|
|
remaining_amount: string
|
|
status: string
|
|
reclaimed_amount: string | null
|
|
}>(
|
|
`SELECT i.deduction_reclaimed_total, i.remaining_amount, i.status, it.reclaimed_amount
|
|
FROM public.invoices i
|
|
JOIN public.rot_rut_payout_request_items it ON it.invoice_id = i.id
|
|
WHERE i.id = $1`,
|
|
[invoiceId],
|
|
)
|
|
return rows[0]
|
|
}
|
|
|
|
it('applies once (marker + invoice, derived remaining/status) and is a no-op the second time', async () => {
|
|
const c = await seedReclaimCase({ decidedTotal: 5000, itemDecided: 5000, status: 'partially_paid' })
|
|
|
|
const first = await getPool().query<{ r: { applied: boolean; remaining_amount: number; status: string } }>(
|
|
`SELECT public.apply_rot_rut_reclaim_invoice($1, $2, $3, 2500) AS r`,
|
|
[c.itemId, c.invoiceId, c.companyId],
|
|
)
|
|
expect(first.rows[0].r).toMatchObject({ applied: true, remaining_amount: 2500, status: 'partially_paid' })
|
|
|
|
const second = await getPool().query<{ r: { applied: boolean } }>(
|
|
`SELECT public.apply_rot_rut_reclaim_invoice($1, $2, $3, 2500) AS r`,
|
|
[c.itemId, c.invoiceId, c.companyId],
|
|
)
|
|
expect(second.rows[0].r).toEqual({ applied: false })
|
|
|
|
const row = await readInvoice(c.invoiceId)
|
|
// 25 000 - 17 500 paid - 7 500 deduction + 2 500 reclaimed = 2 500, once.
|
|
expect(Number(row.deduction_reclaimed_total)).toBe(2500)
|
|
expect(Number(row.remaining_amount)).toBe(2500)
|
|
expect(row.status).toBe('partially_paid')
|
|
expect(Number(row.reclaimed_amount)).toBe(2500)
|
|
})
|
|
|
|
it('refuses an amount above the refused share and above the 1513 headroom', async () => {
|
|
const c = await seedReclaimCase({ decidedTotal: 5000, itemDecided: 5000, status: 'partially_paid' })
|
|
await expect(
|
|
getPool().query(`SELECT public.apply_rot_rut_reclaim_invoice($1, $2, $3, 4000)`, [
|
|
c.itemId, c.invoiceId, c.companyId,
|
|
]),
|
|
).rejects.toThrow(/exceeds the refused share/)
|
|
const row = await readInvoice(c.invoiceId)
|
|
expect(row.reclaimed_amount).toBeNull()
|
|
expect(Number(row.deduction_reclaimed_total)).toBe(0)
|
|
})
|
|
|
|
it('refuses a foreign company without touching the marker', async () => {
|
|
const c = await seedReclaimCase({ decidedTotal: 0, itemDecided: null, status: 'rejected' })
|
|
const other = await seedCompany()
|
|
await expect(
|
|
getPool().query(`SELECT public.apply_rot_rut_reclaim_invoice($1, $2, $3, 7500)`, [
|
|
c.itemId, c.invoiceId, other.companyId,
|
|
]),
|
|
).rejects.toThrow(/not found in company/)
|
|
const row = await readInvoice(c.invoiceId)
|
|
expect(row.reclaimed_amount).toBeNull()
|
|
})
|
|
|
|
it('revert hands the share back, closes the invoice, and is a no-op the second time', async () => {
|
|
const c = await seedReclaimCase({ decidedTotal: 5000, itemDecided: 5000, status: 'partially_paid' })
|
|
await getPool().query(`SELECT public.apply_rot_rut_reclaim_invoice($1, $2, $3, 2500)`, [
|
|
c.itemId, c.invoiceId, c.companyId,
|
|
])
|
|
|
|
const first = await getPool().query<{ r: { reverted: boolean; remaining_amount: number; status: string } }>(
|
|
`SELECT public.revert_rot_rut_reclaim_invoice($1, $2, $3) AS r`,
|
|
[c.itemId, c.invoiceId, c.companyId],
|
|
)
|
|
expect(first.rows[0].r).toMatchObject({ reverted: true, remaining_amount: 0, status: 'paid' })
|
|
|
|
const second = await getPool().query<{ r: { reverted: boolean } }>(
|
|
`SELECT public.revert_rot_rut_reclaim_invoice($1, $2, $3) AS r`,
|
|
[c.itemId, c.invoiceId, c.companyId],
|
|
)
|
|
expect(second.rows[0].r).toEqual({ reverted: false })
|
|
|
|
const row = await readInvoice(c.invoiceId)
|
|
expect(Number(row.deduction_reclaimed_total)).toBe(0)
|
|
expect(Number(row.remaining_amount)).toBe(0)
|
|
expect(row.status).toBe('paid')
|
|
expect(row.reclaimed_amount).toBeNull()
|
|
})
|
|
})
|