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>
This commit is contained in:
Mattsson
2026-09-08 00:13:05 +02:00
committed by GitHub
co-authored by Claude Fable 5.1
parent 5d735097a1
commit fdcb7d937e
52 changed files with 4016 additions and 122 deletions
@@ -0,0 +1,142 @@
-- 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';
@@ -0,0 +1,96 @@
-- pending_operations.operation_type: add 'settle_rot_rut_payout'.
--
-- gnubok_settle_rot_rut_payout stages the match of an income bank row to the
-- ROT/RUT begäran Skatteverket paid with it (one or several, #2239). Same
-- expand pattern as 20260902141000: the full list is re-stated (hand-copied,
-- so keep it in step with types/index.ts PendingOperationType) and the new
-- value appended; the VALIDATE runs in the next migration.
--
-- pg-test: tests/pg/pending-operations-op-type-audit.pg.test.ts (collects
-- the staged op types from server.ts and OPERATION_RISK_TIERS).
ALTER TABLE public.pending_operations
DROP CONSTRAINT IF EXISTS pending_operations_operation_type_check;
ALTER TABLE public.pending_operations
ADD CONSTRAINT pending_operations_operation_type_check
CHECK (operation_type IN (
'categorize_transaction',
'create_customer',
'create_invoice',
'mark_invoice_paid',
'send_invoice',
'mark_invoice_sent',
'match_transaction_invoice',
'close_period',
'lock_period',
'unlock_period',
'set_opening_balances',
'run_year_end',
'post_kontantmetod_cutoff',
'run_currency_revaluation',
'import_sie',
'explain_voucher_gap',
'uncategorize_transaction',
'approve_supplier_invoice',
'credit_supplier_invoice',
'credit_invoice',
'convert_invoice',
'delete_draft_invoice',
'create_transaction',
'attach_document_to_transaction',
'create_voucher',
'correct_entry',
'reverse_entry',
'create_supplier',
'create_supplier_invoice_from_inbox',
'post_annual_depreciation',
'link_invoice_voucher',
'undo_sie_import',
'match_batch_allocate',
'bulk_book_transactions',
'create_salary_run',
'generate_agi',
'link_transaction_journal_entry',
'link_supplier_invoice_voucher',
'submit_vat_declaration',
'submit_agi',
'create_article',
'update_article',
'bulk_book_inbox_items',
'create_dimension_value',
'retag_line_dimensions',
'link_document_to_voucher',
'update_payslip_line',
'set_run_salary',
'update_salary_run',
'register_absence',
'create_employee',
'update_employee',
'set_employee_opening_balances',
'vacation_year_close',
'create_account',
'update_account',
'set_voucher_note',
'book_salary_run',
'delete_absence',
'update_company_settings',
'update_customer',
'update_invoice',
'create_recurring_schedule',
'update_recurring_schedule',
'log_mileage_trip',
'book_mileage_period',
'link_documents_to_vouchers',
'reconciliation_match',
'reconciliation_unmatch',
'reconciliation_signoff',
'reconciliation_residual',
'book_skattekonto_row',
'book_skattekonto_rows',
'ignore_transaction',
'create_sales_order',
'transition_sales_order',
'register_sales_order_delivery',
'create_invoice_from_sales_order',
'settle_rot_rut_payout'
)) NOT VALID;
@@ -0,0 +1,6 @@
-- Validate the operation type CHECK re-added in 20260907160100.
-- Separate transaction: avoids a full-table scan under the stronger lock of
-- the preceding migration (same split as 20260902141001).
ALTER TABLE public.pending_operations
VALIDATE CONSTRAINT pending_operations_operation_type_check;
@@ -0,0 +1,53 @@
-- Migration: voucher-series column default gains rot_rut_reclaim (series C).
--
-- 20260907160000 added 'rot_rut_reclaim' to the journal_entries.source_type
-- CHECK (Skatteverkets avslag booked back onto the customer, debit 1510 /
-- credit 1513). The column default for
-- company_settings.default_voucher_series_per_source_type must name every
-- source type the CHECK accepts (tests/pg/voucher-series-standard-default
-- .pg.test.ts asserts it against STANDARD_VOUCHER_SERIES_MAP), or a new
-- company's reclaim vouchers would fall back to 'A' through the resolver
-- while the settings picker shows them on C next to the payout vouchers.
--
-- Same rules as 20260906210500: only the DEFAULT changes. Existing rows are
-- NOT updated (a company on A keeps A until it chooses the standard set), and
-- rows already on the standard set fall back to 'A' for the missing key
-- exactly as they did for rot_rut_payout before their own migration; the
-- settings action writes the full map when the company touches it.
ALTER TABLE public.company_settings
ALTER COLUMN default_voucher_series_per_source_type
SET DEFAULT '{
"manual": "A",
"bank_transaction": "A",
"invoice_created": "B",
"credit_note": "B",
"reminder_fee": "B",
"invoice_paid": "C",
"invoice_cash_payment": "C",
"rot_rut_payout": "C",
"rot_rut_reclaim": "C",
"supplier_invoice_registered": "D",
"supplier_credit_note": "D",
"supplier_invoice_privately_paid": "D",
"supplier_invoice_paid": "E",
"supplier_invoice_cash_payment": "E",
"accrual": "H",
"year_end": "I",
"result_appropriation": "I",
"salary_payment": "K",
"webshop_order": "L",
"vat_settlement": "M",
"opening_balance": "A",
"currency_revaluation": "A",
"inbox_item": "A",
"import": "A",
"system": "A",
"storno": "A",
"correction": "A",
"stripe_payout": "A",
"expense_claim": "A",
"expense_payout": "A"
}'::jsonb;
NOTIFY pgrst, 'reload schema';
@@ -0,0 +1,68 @@
-- Rot & rut: atomic, idempotent apply of one reclaimed share to its invoice.
--
-- lib/invoices/rot-rut-reclaim.ts books the reclaim voucher (debit 1510 /
-- credit 1513), attaches it to the begäran, and then reopens every invoice
-- for its refused share. Those last writes used to be two UPDATEs per invoice
-- (invoices, then rot_rut_payout_request_items). A failure between the
-- voucher and the invoice update left the ledger reclaimed while the invoice
-- still read as paid, and the next call was refused as already done
-- (CodeRabbit on #2397). This function makes the per-invoice step one
-- transaction with the item row as the idempotency marker:
--
-- reclaimed_amount IS NULL on the item -> apply both writes, return true
-- already set -> touch nothing, return false
--
-- so the service can resume after a partial failure by re-applying every
-- leg: applied legs are no-ops, missing legs complete. SECURITY INVOKER so
-- RLS still scopes the rows; the company id is checked explicitly on the
-- invoice as defense in depth (service-role callers have no RLS).
CREATE OR REPLACE FUNCTION public.apply_rot_rut_reclaim_invoice(
p_item_id uuid,
p_invoice_id uuid,
p_company_id uuid,
p_reclaimed_amount numeric,
p_remaining_amount numeric,
p_status text
)
RETURNS boolean
LANGUAGE plpgsql
SECURITY INVOKER
SET search_path = public
AS $$
BEGIN
IF p_reclaimed_amount IS NULL OR p_reclaimed_amount <= 0 THEN
RAISE EXCEPTION 'apply_rot_rut_reclaim_invoice: reclaimed amount must be positive';
END IF;
UPDATE public.rot_rut_payout_request_items
SET reclaimed_amount = p_reclaimed_amount
WHERE id = p_item_id
AND invoice_id = p_invoice_id
AND reclaimed_amount IS NULL;
IF NOT FOUND THEN
-- Already applied (marker set) or not this invoice's item: nothing to do.
RETURN false;
END IF;
UPDATE public.invoices
SET deduction_reclaimed_total = COALESCE(deduction_reclaimed_total, 0) + p_reclaimed_amount,
remaining_amount = p_remaining_amount,
status = p_status
WHERE id = p_invoice_id
AND company_id = p_company_id;
IF NOT FOUND THEN
RAISE EXCEPTION 'apply_rot_rut_reclaim_invoice: invoice % not found in company %',
p_invoice_id, p_company_id;
END IF;
RETURN true;
END;
$$;
GRANT EXECUTE ON FUNCTION public.apply_rot_rut_reclaim_invoice(uuid, uuid, uuid, numeric, numeric, text) TO authenticated;
GRANT EXECUTE ON FUNCTION public.apply_rot_rut_reclaim_invoice(uuid, uuid, uuid, numeric, numeric, text) TO service_role;
NOTIFY pgrst, 'reload schema';
@@ -0,0 +1,219 @@
-- Rot & rut reclaim RPCs: the database owns the accounting values.
--
-- 20260907160300 let the caller supply remaining_amount and status. Review
-- (#2397, CWE-862): any writer-role member could call the function with
-- arbitrary values for an invoice they can see. This migration replaces it
-- with a function that takes only the reclaimed amount, VALIDATES it against
-- the locked item, request and invoice rows, and DERIVES remaining_amount and
-- status from the same formula as the INSERT guard
-- (invoices_derive_remaining_amount: total - paid - deduction + reclaimed),
-- and adds the mirror used when the reclaim voucher is reversed. Both are
-- idempotent through the item marker (reclaimed_amount): a second call is a
-- no-op, so a failed batch can be re-run leg by leg.
--
-- Returns jsonb { applied, remaining_amount, status } so the caller can
-- report what the row now says without a second read.
DROP FUNCTION IF EXISTS public.apply_rot_rut_reclaim_invoice(uuid, uuid, uuid, numeric, numeric, text);
CREATE OR REPLACE FUNCTION public.rot_rut_customer_outstanding(
p_total numeric,
p_paid numeric,
p_deduction numeric,
p_reclaimed numeric
)
RETURNS numeric
LANGUAGE sql
IMMUTABLE
AS $$
SELECT GREATEST(0, ROUND((COALESCE(p_total, 0) - COALESCE(p_paid, 0)
- COALESCE(p_deduction, 0) + COALESCE(p_reclaimed, 0))::numeric, 2));
$$;
CREATE OR REPLACE FUNCTION public.apply_rot_rut_reclaim_invoice(
p_item_id uuid,
p_invoice_id uuid,
p_company_id uuid,
p_reclaimed_amount numeric
)
RETURNS jsonb
LANGUAGE plpgsql
SECURITY INVOKER
SET search_path = public
AS $$
DECLARE
v_item public.rot_rut_payout_request_items%ROWTYPE;
v_request public.rot_rut_payout_requests%ROWTYPE;
v_invoice public.invoices%ROWTYPE;
v_paid numeric;
v_remaining numeric;
v_status text;
v_request_refused numeric;
BEGIN
IF p_reclaimed_amount IS NULL OR p_reclaimed_amount <= 0 THEN
RAISE EXCEPTION 'apply_rot_rut_reclaim_invoice: reclaimed amount must be positive';
END IF;
SELECT * INTO v_item
FROM public.rot_rut_payout_request_items
WHERE id = p_item_id AND invoice_id = p_invoice_id
FOR UPDATE;
IF NOT FOUND THEN
RAISE EXCEPTION 'apply_rot_rut_reclaim_invoice: item % not found for invoice %', p_item_id, p_invoice_id;
END IF;
IF v_item.reclaimed_amount IS NOT NULL THEN
-- Already applied: idempotent no-op.
RETURN jsonb_build_object('applied', false);
END IF;
SELECT * INTO v_request
FROM public.rot_rut_payout_requests
WHERE id = v_item.request_id AND company_id = p_company_id
FOR UPDATE;
IF NOT FOUND THEN
RAISE EXCEPTION 'apply_rot_rut_reclaim_invoice: request for item % not found in company %', p_item_id, p_company_id;
END IF;
IF v_request.decided_at IS NULL OR v_request.decided_total IS NULL THEN
RAISE EXCEPTION 'apply_rot_rut_reclaim_invoice: no beslut recorded on request %', v_request.id;
END IF;
IF v_request.reclaim_journal_entry_id IS NULL THEN
RAISE EXCEPTION 'apply_rot_rut_reclaim_invoice: request % has no reclaim voucher', v_request.id;
END IF;
SELECT * INTO v_invoice
FROM public.invoices
WHERE id = p_invoice_id AND company_id = p_company_id
FOR UPDATE;
IF NOT FOUND THEN
RAISE EXCEPTION 'apply_rot_rut_reclaim_invoice: invoice % not found in company %', p_invoice_id, p_company_id;
END IF;
-- The refused share can never exceed what the item requested, what the
-- beslut refused for the whole request, or what the invoice still carries
-- on 1513.
v_request_refused := GREATEST(0, v_request.requested_total - v_request.decided_total);
IF p_reclaimed_amount > v_item.requested_amount + 0.005
OR p_reclaimed_amount > v_request_refused + 0.005
OR p_reclaimed_amount > COALESCE(v_invoice.deduction_total, 0) - COALESCE(v_invoice.deduction_reclaimed_total, 0) + 0.005 THEN
RAISE EXCEPTION 'apply_rot_rut_reclaim_invoice: reclaimed amount % exceeds the refused share for item %', p_reclaimed_amount, p_item_id;
END IF;
-- A paid invoice with NULL paid_amount (older settlement paths) has settled
-- its customer share: that share stands in for the missing figure.
v_paid := COALESCE(
v_invoice.paid_amount,
CASE WHEN v_invoice.status = 'paid'
THEN v_invoice.total - COALESCE(v_invoice.deduction_total, 0)
ELSE 0 END
);
v_remaining := public.rot_rut_customer_outstanding(
v_invoice.total, v_paid, v_invoice.deduction_total,
COALESCE(v_invoice.deduction_reclaimed_total, 0) + p_reclaimed_amount
);
v_status := v_invoice.status;
IF v_remaining > 0 THEN
IF v_paid > 0 THEN
v_status := 'partially_paid';
ELSIF v_invoice.status = 'overdue' THEN
v_status := 'overdue';
ELSE
v_status := 'sent';
END IF;
END IF;
UPDATE public.rot_rut_payout_request_items
SET reclaimed_amount = p_reclaimed_amount
WHERE id = p_item_id;
UPDATE public.invoices
SET deduction_reclaimed_total = COALESCE(deduction_reclaimed_total, 0) + p_reclaimed_amount,
remaining_amount = v_remaining,
status = v_status
WHERE id = p_invoice_id AND company_id = p_company_id;
RETURN jsonb_build_object('applied', true, 'remaining_amount', v_remaining, 'status', v_status);
END;
$$;
-- Mirror for a reversed reclaim voucher: the item marker is the amount to
-- hand back; a NULL marker means this leg is already reverted (no-op).
CREATE OR REPLACE FUNCTION public.revert_rot_rut_reclaim_invoice(
p_item_id uuid,
p_invoice_id uuid,
p_company_id uuid
)
RETURNS jsonb
LANGUAGE plpgsql
SECURITY INVOKER
SET search_path = public
AS $$
DECLARE
v_item public.rot_rut_payout_request_items%ROWTYPE;
v_invoice public.invoices%ROWTYPE;
v_paid numeric;
v_reclaimed numeric;
v_remaining numeric;
v_status text;
BEGIN
SELECT * INTO v_item
FROM public.rot_rut_payout_request_items
WHERE id = p_item_id AND invoice_id = p_invoice_id
FOR UPDATE;
IF NOT FOUND THEN
RAISE EXCEPTION 'revert_rot_rut_reclaim_invoice: item % not found for invoice %', p_item_id, p_invoice_id;
END IF;
IF v_item.reclaimed_amount IS NULL THEN
RETURN jsonb_build_object('reverted', false);
END IF;
IF NOT EXISTS (
SELECT 1 FROM public.rot_rut_payout_requests
WHERE id = v_item.request_id AND company_id = p_company_id
) THEN
RAISE EXCEPTION 'revert_rot_rut_reclaim_invoice: request for item % not found in company %', p_item_id, p_company_id;
END IF;
SELECT * INTO v_invoice
FROM public.invoices
WHERE id = p_invoice_id AND company_id = p_company_id
FOR UPDATE;
IF NOT FOUND THEN
RAISE EXCEPTION 'revert_rot_rut_reclaim_invoice: invoice % not found in company %', p_invoice_id, p_company_id;
END IF;
v_reclaimed := GREATEST(0, COALESCE(v_invoice.deduction_reclaimed_total, 0) - v_item.reclaimed_amount);
v_paid := COALESCE(v_invoice.paid_amount, 0);
v_remaining := public.rot_rut_customer_outstanding(
v_invoice.total, v_paid, v_invoice.deduction_total, v_reclaimed
);
v_status := v_invoice.status;
IF v_invoice.status IN ('sent', 'overdue', 'partially_paid', 'paid') THEN
IF v_remaining <= 0 AND v_paid > 0 THEN
v_status := 'paid';
ELSIF v_paid > 0 THEN
v_status := 'partially_paid';
ELSIF v_invoice.due_date IS NOT NULL AND v_invoice.due_date < CURRENT_DATE THEN
v_status := 'overdue';
ELSE
v_status := 'sent';
END IF;
END IF;
UPDATE public.rot_rut_payout_request_items
SET reclaimed_amount = NULL
WHERE id = p_item_id;
UPDATE public.invoices
SET deduction_reclaimed_total = v_reclaimed,
remaining_amount = v_remaining,
status = v_status
WHERE id = p_invoice_id AND company_id = p_company_id;
RETURN jsonb_build_object('reverted', true, 'remaining_amount', v_remaining, 'status', v_status);
END;
$$;
GRANT EXECUTE ON FUNCTION public.rot_rut_customer_outstanding(numeric, numeric, numeric, numeric) TO authenticated, service_role;
GRANT EXECUTE ON FUNCTION public.apply_rot_rut_reclaim_invoice(uuid, uuid, uuid, numeric) TO authenticated, service_role;
GRANT EXECUTE ON FUNCTION public.revert_rot_rut_reclaim_invoice(uuid, uuid, uuid) TO authenticated, service_role;
NOTIFY pgrst, 'reload schema';