Files
accounted/tests/pg/voucher-series-standard-default.pg.test.ts
T
MattssonandClaude Fable 5.1 fdcb7d937e 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>
2026-09-08 00:13:05 +02:00

97 lines
3.8 KiB
TypeScript

import { readFileSync } from 'node:fs'
import { join } from 'node:path'
import { describe, it, expect } from 'vitest'
import { getPool } from './setup'
import { seedCompany } from './fixtures'
import { STANDARD_VOUCHER_SERIES_MAP } from '@/lib/bookkeeping/voucher-series-resolver'
/**
* `company_settings.default_voucher_series_per_source_type` column default
* (migration 20260906210500, issue #2184).
*
* Three invariants, all against the real column:
* 1. a fresh row gets the standard set, equal to the TS constant the
* settings action writes, so a new company and "Använd
* standarduppsättningen" mean the same thing;
* 2. the default names every source type journal_entries accepts, so a new
* source type cannot slip back onto 'A' through the resolver's fallback
* the way seven of them had before this migration;
* 3. re-running the migration leaves an existing all-A row alone: the
* standard set reaches an existing company only when it asks for it.
* Superuser pool on purpose: the object under test is the default, not RLS.
*/
// The LATEST default-setting migration: every source type added since #2184
// re-states the whole map in a new migration (20260907160200 added
// rot_rut_reclaim), and re-applying an older one here would reset the
// default to a shorter map for every test that follows.
const MIGRATION_PATH = join(
process.cwd(),
'supabase/migrations/20260907160200_voucher_series_default_rot_rut_reclaim.sql',
)
type SeriesMap = Record<string, string>
const LEGACY_ALL_A: SeriesMap = Object.fromEntries(
Object.keys(STANDARD_VOUCHER_SERIES_MAP).map((sourceType) => [sourceType, 'A']),
)
async function insertSettings(): Promise<string> {
const { companyId } = await seedCompany()
// A trigger may already have created the row; either way one exists after this.
await getPool().query(
`INSERT INTO public.company_settings (company_id) VALUES ($1) ON CONFLICT DO NOTHING`,
[companyId],
)
return companyId
}
async function readMap(companyId: string): Promise<SeriesMap> {
const { rows } = await getPool().query<{ map: SeriesMap }>(
`SELECT default_voucher_series_per_source_type AS map
FROM public.company_settings
WHERE company_id = $1`,
[companyId],
)
return rows[0].map
}
describe('company_settings.default_voucher_series_per_source_type default', () => {
it('gives a fresh row the standard set, equal to STANDARD_VOUCHER_SERIES_MAP', async () => {
const companyId = await insertSettings()
expect(await readMap(companyId)).toEqual(STANDARD_VOUCHER_SERIES_MAP)
})
it('names every source type the journal_entries CHECK accepts', async () => {
const { rows } = await getPool().query<{ def: string }>(
`SELECT pg_get_constraintdef(oid) AS def
FROM pg_constraint
WHERE conrelid = 'public.journal_entries'::regclass
AND conname = 'journal_entries_source_type_check'`,
)
expect(rows).toHaveLength(1)
const accepted = Array.from(rows[0].def.matchAll(/'([a-z_]+)'/g), (m) => m[1]).sort()
expect(accepted.length).toBeGreaterThan(0)
const companyId = await insertSettings()
expect(Object.keys(await readMap(companyId)).sort()).toEqual(accepted)
})
it('re-applying the migration leaves an existing all-A row untouched', async () => {
const existing = await insertSettings()
await getPool().query(
`UPDATE public.company_settings
SET default_voucher_series_per_source_type = $2::jsonb
WHERE company_id = $1`,
[existing, JSON.stringify(LEGACY_ALL_A)],
)
await getPool().query(readFileSync(MIGRATION_PATH, 'utf8'))
expect(await readMap(existing)).toEqual(LEGACY_ALL_A)
// ...while a row created afterwards still starts on the standard set.
const fresh = await insertSettings()
expect(await readMap(fresh)).toEqual(STANDARD_VOUCHER_SERIES_MAP)
})
})