Files
accounted/supabase/migrations/20260907160000_rot_rut_reclaim.sql
Mattsson 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

143 lines
6.1 KiB
PL/PgSQL

-- ROT/RUT: Skatteverkets avslag becomes a fordran on the customer.
--
-- Under fakturamodellen the deduction is booked as a fordran on Skatteverket
-- (1513) when the invoice is issued. When Skatteverket refuses an ärende (in
-- full or in part) that fordran is not gone: the buyer owes the refused share
-- (HUSFL 2009:194; swedish-invoice-compliance section 8: "SKV denies: Debit
-- 1510, Credit 1513, re-invoice customer"). Until now the request was only
-- marked rejected/partially_paid and the refused kronor stayed on 1513 forever
-- while the invoice read as paid.
--
-- This migration adds the state for the reclaim voucher that moves the refused
-- share back onto the customer and reopens the invoice:
--
-- invoices.deduction_reclaimed_total what Skatteverket refused and the
-- customer must now pay (invoice
-- currency, always SEK for ROT/RUT)
-- rot_rut_payout_requests.reclaim_journal_entry_id / reclaimed_at
-- the voucher (one per begäran)
-- rot_rut_payout_request_items.reclaimed_amount
-- per-invoice refused share
-- journal_entries.source_type 'rot_rut_reclaim'
--
-- The invoice document itself stays as issued: deduction_total keeps the
-- deduction the customer was granted on paper, and the customer share is
-- total - deduction_total + deduction_reclaimed_total (lib/invoices/
-- customer-share.ts; the INSERT guard below is its SQL twin and gains the
-- same term so the two definitions cannot drift).
-- 1. invoices.deduction_reclaimed_total -------------------------------------
ALTER TABLE public.invoices
ADD COLUMN IF NOT EXISTS deduction_reclaimed_total NUMERIC(12,2) NOT NULL DEFAULT 0;
COMMENT ON COLUMN public.invoices.deduction_reclaimed_total IS
'ROT/RUT share Skatteverket refused and moved back onto the customer (debit 1510 / credit 1513, source_type rot_rut_reclaim). Customer share = total - deduction_total + deduction_reclaimed_total.';
ALTER TABLE public.invoices
DROP CONSTRAINT IF EXISTS invoices_deduction_reclaimed_total_check;
ALTER TABLE public.invoices
ADD CONSTRAINT invoices_deduction_reclaimed_total_check
CHECK (
deduction_reclaimed_total >= 0
AND deduction_reclaimed_total <= COALESCE(deduction_total, 0)
) NOT VALID;
ALTER TABLE public.invoices
VALIDATE CONSTRAINT invoices_deduction_reclaimed_total_check;
-- The INSERT guard from 20260817191708 is the SQL twin of
-- invoiceCustomerShare(): same formula, now with the reclaimed term.
CREATE OR REPLACE FUNCTION public.invoices_derive_remaining_amount()
RETURNS trigger
LANGUAGE plpgsql
AS $$
BEGIN
IF COALESCE(NEW.remaining_amount, 0) = 0
AND NEW.credited_invoice_id IS NULL
AND COALESCE(NEW.document_type, 'invoice') = 'invoice'
AND COALESCE(NEW.total, 0) > 0
AND COALESCE(NEW.status, 'draft') NOT IN ('paid', 'cancelled', 'credited')
THEN
NEW.remaining_amount := GREATEST(
0,
ROUND((
NEW.total
- COALESCE(NEW.paid_amount, 0)
- COALESCE(NEW.deduction_total, 0)
+ COALESCE(NEW.deduction_reclaimed_total, 0)
)::numeric, 2)
);
END IF;
RETURN NEW;
END;
$$;
COMMENT ON FUNCTION public.invoices_derive_remaining_amount() IS
'BEFORE INSERT guard: an unpaid real invoice inserted with remaining_amount NULL/0 gets total - paid_amount - deduction_total + deduction_reclaimed_total, so the NOT NULL DEFAULT 0 can never read as "settled".';
-- 2. Request + item reclaim state -------------------------------------------
ALTER TABLE public.rot_rut_payout_requests
ADD COLUMN IF NOT EXISTS reclaim_journal_entry_id uuid NULL
REFERENCES public.journal_entries(id) ON DELETE SET NULL,
ADD COLUMN IF NOT EXISTS reclaimed_at timestamptz NULL;
COMMENT ON COLUMN public.rot_rut_payout_requests.reclaim_journal_entry_id IS
'Voucher that moved the refused share of this begäran from 1513 back onto the customers (1510). One per begäran; NULL until booked.';
ALTER TABLE public.rot_rut_payout_request_items
ADD COLUMN IF NOT EXISTS reclaimed_amount NUMERIC(12,2) NULL
CHECK (reclaimed_amount >= 0);
COMMENT ON COLUMN public.rot_rut_payout_request_items.reclaimed_amount IS
'The refused share (requested_amount - decided_amount) booked back onto this invoice by the reclaim voucher.';
-- 3. journal_entries.source_type: add 'rot_rut_reclaim' ---------------------
-- Same expansion pattern as 20260904170000: full list preserved, new value
-- appended. TS (JournalEntrySourceType) and Zod (JournalEntrySourceTypeSchema)
-- gain the value in the same change.
ALTER TABLE public.journal_entries
DROP CONSTRAINT IF EXISTS journal_entries_source_type_check;
ALTER TABLE public.journal_entries
ADD CONSTRAINT journal_entries_source_type_check
CHECK (source_type IN (
'manual', 'bank_transaction', 'invoice_created',
'invoice_paid', 'invoice_cash_payment', 'credit_note', 'salary_payment',
'opening_balance', 'year_end',
'storno', 'correction', 'import', 'system',
'inbox_item',
'supplier_invoice_registered', 'supplier_invoice_paid',
'supplier_invoice_cash_payment', 'supplier_credit_note',
'currency_revaluation',
'supplier_invoice_privately_paid',
'reminder_fee',
'accrual',
'result_appropriation',
'rot_rut_payout',
'vat_settlement',
'stripe_payout',
'webshop_order',
'expense_claim',
'expense_payout',
'rot_rut_reclaim'
)) NOT VALID;
ALTER TABLE public.journal_entries
VALIDATE CONSTRAINT journal_entries_source_type_check;
-- 4. One live reclaim voucher per begäran -----------------------------------
-- Same race guard as journal_entries_rot_rut_payout_live_unique
-- (20260904021000): two concurrent reclaims must not both debit 1510 for the
-- same refused share. draft included so the loser fails at the draft insert.
-- pg-test: tests/pg/rot-rut-reclaim.pg.test.ts
CREATE UNIQUE INDEX IF NOT EXISTS journal_entries_rot_rut_reclaim_live_unique
ON public.journal_entries (company_id, source_id)
WHERE source_type = 'rot_rut_reclaim'
AND source_id IS NOT NULL
AND status IN ('draft', 'posted');
NOTIFY pgrst, 'reload schema';