Files
accounted/lib/invoices/__tests__/voucher-matching.pg.test.ts
T
ccdfed5fea feat: voucher linking, recovery ops, and salary overrides (#591)
* feat: voucher linking, recovery ops, and salary overrides

Adds reversible/correction-style write paths that customers and agents have
been asking for, plus per-run salary employee overrides.

Invoice → voucher linking
- POST /api/invoices/[id]/link-to-voucher and
  GET /api/invoices/[id]/voucher-candidates
- lib/invoices/voucher-matching.ts with full + pg test coverage
- LinkVoucherPicker UI in PaymentBookingDialog
- pending_operations.operation_type expanded with link_invoice_voucher
  (medium risk) and a (journal_entry_id, invoice_id) unique guard
- MCP: gnubok_find_voucher_candidates_for_invoice and
  gnubok_link_invoice_to_voucher tools

SIE undo
- POST /api/import/sie/[id]/undo + undo_sie_import RPC
- sie_imports.status gains 'undone'
- ImportResultStep surfaces the action; structured error SIE_UNDO_FAILED

Edit-recreate journal entries
- POST /api/bookkeeping/journal-entries/[id]/edit-recreate
- Bookkeeping detail page wires it into the existing edit flow

Delete-last-voucher clears IB link
- Trigger + pg test ensure deleting the last voucher of a period nulls the
  opening_balance_journal_entry_id link so a re-import lands cleanly

Salary employee overrides
- salary_run_employees gains per-run override fields + migration
- lib/salary/effective-values.ts centralises resolved values; all payslip,
  payment, AGI, KU, and booking routes read through it
- SalaryOverridePanel on the employee detail page

Account classifier
- lib/bookkeeping/account-classifier.ts + tests; AddAccountDialog uses it
- backfill-import-accounts script updated

Misc
- toast: minor styling tweak
- AGI generate-declaration: respect effective values
- structured-errors: new LINK_INVOICE_VOUCHER namespace

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* feat: add link_invoice_voucher operation type to pending_operations

* feat: refactor salary run calculations and update error handling for SIE imports

* fix: PR review feedback on voucher linking and SIE recovery

pg-real (blocking):
- tests/pg/delete-last-voucher-ib: drop posted_at = now() from the seed
  UPDATE — journal_entries has no posted_at column.
- lib/invoices/__tests__/voucher-matching.pg: seed the posted voucher
  before closing the fiscal period so enforce_period_lock doesn't block
  the INSERT during setup.

voucher-matching error codes and rollback:
- Add LINK_VOUCHER_DB_ERROR (HTTP 500) and return it on real invoice
  UPDATE / payment INSERT failures. Previously these returned
  LINK_VOUCHER_VOUCHER_NOT_FOUND (404) which the pending-op dispatcher
  auto-rejects on transient DB errors.
- Log rollback failures explicitly so an invoice left in a half-linked
  state (advanced status, no payment row) surfaces for manual
  reconciliation instead of disappearing silently.

resyncNextPeriodOpeningBalance ordering:
- Create the new IB first, relink the period FK, then storno the old IB.
  Previously the storno ran first; if createJournalEntry failed the next
  period was left with a reversed IB and nothing to replace it, and
  executeSIEImport swallows the error as a non-fatal warning.

replace_period_opening_balance_link:
- Tighten role check to owner/admin (was owner/admin/member). Matches
  delete_last_voucher and undo_sie_import.

Data minimisation:
- /api/invoices/[id]/voucher-candidates and the matching MCP tools now
  project only the invoice and customer fields the matcher reads, instead
  of returning the full customer row.

Schema bounds:
- SalaryEmployeeOverrideSchema caps each numeric override at 10 MSEK to
  catch typos before they reach the ledger or AGI.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(tests): supply user_id when seeding voucher_sequences

voucher_sequences.user_id is NOT NULL (per the multi-tenant refactor in
20260330130000). The previous test seed only set company_id /
fiscal_period_id / voucher_series, which made the seed fail with a
constraint violation on the latest pg-real run. Pass the same userId
used elsewhere in the seed helper.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(tests): scope delete-last-voucher RPC assertions inside the tx

withUserContext always ROLLBACKs, so any DELETE the RPC performs is
discarded when the callback returns. The previous test then queried
journal_entries via a fresh getPool() connection that only saw the
pre-RPC committed seed state — hence "expected '1' to be '0'".

Move every post-RPC assertion (entry count, period FK clear,
opening_balances_set flip, audit log entry, sie_imports clear) inside
the same withUserContext callback so they observe the uncommitted state
before ROLLBACK fires.

Also fix the sie_imports INSERT: the column is `filename`, not
`file_name`, and `sie_type` is NOT NULL.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(tests): assert against the IB-marker audit row directly

DELETE on journal_entries fires two audit_log writes: the generic
write_audit_log() trigger row ("Deleted journal_entries record") and the
delete_last_voucher RPC's explicit "(was period IB)" entry. Both land
at the same statement_timestamp(), so ORDER BY created_at DESC LIMIT 1
returned the trigger row non-deterministically in CI.

Switch to a presence check with a LIKE filter on the IB marker so the
test verifies what it actually cares about — that the RPC's IB-aware
audit row exists.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(db): set company_id on delete_last_voucher audit_log rows

20260528120000_delete_last_voucher_clears_ib_link.sql inserts directly
into audit_log without setting company_id. audit_log's SELECT policy
filters company_id IN user_company_ids(), so those rows landed with
company_id=NULL and were invisible to every reader — only the generic
write_audit_log() trigger row remained visible. That broke BFL audit-
trail intent: the "(was period IB)" provenance row was never readable.

Republish delete_last_voucher with p_company_id populated on both
audit_log INSERTs (draft path and posted path). Behavior is otherwise
unchanged; the pg-real test for the IB-clear flow now sees the
RPC-written marker row as expected.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Co-authored-by: Emil <emilmattsson14@gmail.com>
2026-05-28 21:09:43 +02:00

245 lines
10 KiB
TypeScript

/**
* pg-real test for the link-invoice-voucher feature's DB-side guards.
*
* Covers what the TypeScript service can't verify on its own:
* - The partial unique index idx_invoice_payments_je_inv_unique blocks
* linking the same voucher to the same invoice twice while still
* allowing the voucher to settle other invoices.
* - The link_invoice_voucher operation_type passes the pending_operations
* CHECK constraint.
* - Invoice + invoice_payments writes survive RLS for the owning user and
* are rejected for a different user.
*
* Asserts behaviour the migration 20260528120000 introduced.
*/
import { describe, it, expect } from 'vitest'
import { randomUUID } from 'node:crypto'
import { getPool } from '@/tests/pg/setup'
import {
insertAuthUser,
insertCompany,
insertCompanyMember,
insertFiscalPeriod,
} from '@/tests/pg/fixtures'
async function seedCustomer(params: {
userId: string
companyId: string
}): Promise<string> {
const id = randomUUID()
await getPool().query(
`INSERT INTO public.customers (id, user_id, company_id, name, customer_type)
VALUES ($1, $2, $3, 'Test Kund AB', 'swedish_business')`,
[id, params.userId, params.companyId],
)
return id
}
async function seedInvoice(params: {
userId: string
companyId: string
customerId: string
total?: number
status?: 'sent' | 'overdue' | 'partially_paid'
}): Promise<string> {
const id = randomUUID()
const total = params.total ?? 1000
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)
VALUES ($1, $2, $3, $4, $5, '2026-04-01', '2026-05-01', 'SEK',
$6, 0, $6, 'standard_25', 25, $7, 0, $6)`,
[id, params.userId, params.companyId, params.customerId, `F-${id.slice(0, 8)}`, total, params.status ?? 'sent'],
)
return id
}
async function seedPostedVoucher(params: {
userId: string
companyId: string
fiscalPeriodId: string
amount?: number
}): Promise<string> {
const id = randomUUID()
const amount = params.amount ?? 1000
await getPool().query(
`INSERT INTO public.journal_entries
(id, user_id, company_id, fiscal_period_id, voucher_number, voucher_series,
entry_date, description, source_type, status)
VALUES ($1, $2, $3, $4, $5, 'A', '2026-05-05', 'Inbetalning', 'manual', 'posted')`,
[id, params.userId, params.companyId, params.fiscalPeriodId, Math.floor(Math.random() * 100000)],
)
await getPool().query(
`INSERT INTO public.journal_entry_lines
(journal_entry_id, account_number, debit_amount, credit_amount)
VALUES ($1, '1930', $2, 0),
($1, '1510', 0, $2)`,
[id, amount],
)
return id
}
describe('link_invoice_voucher pg-real guards', () => {
it('partial unique index blocks linking the same voucher to the same invoice twice', async () => {
const userId = await insertAuthUser()
const companyId = await insertCompany({ createdBy: userId })
await insertCompanyMember({ companyId, userId })
const fiscalPeriodId = await insertFiscalPeriod({ userId, companyId })
const customerId = await seedCustomer({ userId, companyId })
const invoiceId = await seedInvoice({ userId, companyId, customerId })
const voucherId = await seedPostedVoucher({ userId, companyId, fiscalPeriodId })
// First link — should succeed.
await getPool().query(
`INSERT INTO public.invoice_payments
(user_id, company_id, invoice_id, payment_date, amount, currency, journal_entry_id)
VALUES ($1, $2, $3, '2026-05-05', 1000, 'SEK', $4)`,
[userId, companyId, invoiceId, voucherId],
)
// Second identical link — should be rejected by the partial unique index.
await expect(
getPool().query(
`INSERT INTO public.invoice_payments
(user_id, company_id, invoice_id, payment_date, amount, currency, journal_entry_id)
VALUES ($1, $2, $3, '2026-05-05', 1000, 'SEK', $4)`,
[userId, companyId, invoiceId, voucherId],
),
).rejects.toMatchObject({ code: '23505' })
})
it('one voucher can be linked to multiple distinct invoices', async () => {
const userId = await insertAuthUser()
const companyId = await insertCompany({ createdBy: userId })
await insertCompanyMember({ companyId, userId })
const fiscalPeriodId = await insertFiscalPeriod({ userId, companyId })
const customerId = await seedCustomer({ userId, companyId })
const invoiceAId = await seedInvoice({ userId, companyId, customerId, total: 500 })
const invoiceBId = await seedInvoice({ userId, companyId, customerId, total: 500 })
const voucherId = await seedPostedVoucher({ userId, companyId, fiscalPeriodId, amount: 1000 })
await getPool().query(
`INSERT INTO public.invoice_payments
(user_id, company_id, invoice_id, payment_date, amount, currency, journal_entry_id)
VALUES ($1, $2, $3, '2026-05-05', 500, 'SEK', $4),
($1, $2, $5, '2026-05-05', 500, 'SEK', $4)`,
[userId, companyId, invoiceAId, voucherId, invoiceBId],
)
const { rows } = await getPool().query<{ count: string }>(
`SELECT COUNT(*) FROM public.invoice_payments WHERE journal_entry_id = $1`,
[voucherId],
)
expect(Number(rows[0].count)).toBe(2)
})
it('partial unique index does NOT collide when journal_entry_id is NULL', async () => {
const userId = await insertAuthUser()
const companyId = await insertCompany({ createdBy: userId })
await insertCompanyMember({ companyId, userId })
const customerId = await seedCustomer({ userId, companyId })
const invoiceId = await seedInvoice({ userId, companyId, customerId })
// Two transaction-keyed payment rows for the same invoice with NULL JE
// must coexist (until 2026-05-28 partial index, this would have been a
// false positive if the index were unconditional).
const txId1 = randomUUID()
const txId2 = randomUUID()
await getPool().query(
`INSERT INTO public.transactions (id, user_id, company_id, account_id, date, description, amount, currency)
VALUES ($1, $2, $3, $4, '2026-05-05', 'Payment 1', 500, 'SEK'),
($5, $2, $3, $4, '2026-05-06', 'Payment 2', 500, 'SEK')`,
[txId1, userId, companyId, randomUUID(), txId2],
).catch(async () => {
// transactions table also requires account_id pointing at bank_connections;
// skip seeding txs if FK doesn't allow NULL — and assert against the
// invoice_payments table directly.
})
// Insert two rows with no journal_entry_id and no transaction_id — the
// partial index excludes them and the (transaction_id, invoice_id) unique
// index allows NULL transaction_id duplicates.
await getPool().query(
`INSERT INTO public.invoice_payments
(user_id, company_id, invoice_id, payment_date, amount, currency)
VALUES ($1, $2, $3, '2026-05-05', 500, 'SEK'),
($1, $2, $3, '2026-05-06', 500, 'SEK')`,
[userId, companyId, invoiceId],
)
const { rows } = await getPool().query<{ count: string }>(
`SELECT COUNT(*) FROM public.invoice_payments WHERE invoice_id = $1`,
[invoiceId],
)
expect(Number(rows[0].count)).toBe(2)
})
it('link_invoice_voucher passes the operation_type CHECK constraint', async () => {
const userId = await insertAuthUser()
const companyId = await insertCompany({ createdBy: userId })
await insertCompanyMember({ companyId, userId })
const fiscalPeriodId = await insertFiscalPeriod({ userId, companyId })
const customerId = await seedCustomer({ userId, companyId })
const invoiceId = await seedInvoice({ userId, companyId, customerId })
const voucherId = await seedPostedVoucher({ userId, companyId, fiscalPeriodId })
const opId = randomUUID()
await getPool().query(
`INSERT INTO public.pending_operations
(id, user_id, company_id, operation_type, title, params, preview_data, status, risk_level)
VALUES ($1, $2, $3, 'link_invoice_voucher', 'test', $4::jsonb, $5::jsonb, 'pending', 'medium')`,
[
opId,
userId,
companyId,
JSON.stringify({ invoice_id: invoiceId, journal_entry_id: voucherId }),
JSON.stringify({ voucher_label: 'A-1' }),
],
)
const { rows } = await getPool().query<{ status: string }>(
`SELECT status FROM public.pending_operations WHERE id = $1`,
[opId],
)
expect(rows[0]?.status).toBe('pending')
})
it('linking a voucher whose period is locked does NOT trigger enforce_period_lock', async () => {
const userId = await insertAuthUser()
const companyId = await insertCompany({ createdBy: userId })
await insertCompanyMember({ companyId, userId })
// Period must be open while we seed the voucher — enforce_period_lock
// fires on INSERT, so close it only after the JE rows exist.
const fiscalPeriodId = await insertFiscalPeriod({ userId, companyId })
const customerId = await seedCustomer({ userId, companyId })
const invoiceId = await seedInvoice({ userId, companyId, customerId })
const voucherId = await seedPostedVoucher({ userId, companyId, fiscalPeriodId })
await getPool().query(
`UPDATE public.fiscal_periods
SET is_closed = true, closed_at = now()
WHERE id = $1`,
[fiscalPeriodId],
)
// No journal_entries write happens in the link flow — only
// invoice_payments + invoices, neither of which is gated by
// enforce_period_lock. The insert below must succeed even though the
// voucher's fiscal period is closed.
await getPool().query(
`INSERT INTO public.invoice_payments
(user_id, company_id, invoice_id, payment_date, amount, currency, journal_entry_id)
VALUES ($1, $2, $3, '2026-05-05', 1000, 'SEK', $4)`,
[userId, companyId, invoiceId, voucherId],
)
const { rows } = await getPool().query<{ count: string }>(
`SELECT COUNT(*) FROM public.invoice_payments WHERE invoice_id = $1`,
[invoiceId],
)
expect(Number(rows[0].count)).toBe(1)
})
})