Files
accounted/lib/bookkeeping/rot-rut-entries.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

210 lines
6.9 KiB
TypeScript

import type { SupabaseClient } from '@supabase/supabase-js'
import type { CreateJournalEntryInput, JournalEntry } from '@/types'
import { roundOre } from '@/lib/money'
import { createJournalEntry, findFiscalPeriod } from './engine'
/**
* Settlement voucher for a rot/rut payout from Skatteverket.
*
* When the agency pays out a begäran, the 1513 receivable created at
* invoicing (fakturamodellen) clears against the bank:
*
* Debit 19xx bank account (default 1930) [amount]
* Credit 1513 Skattereduktion rot/rut [amount]
*
* One voucher per bank transfer: that mirrors the actual bank transaction.
* Skatteverket decides per begäran but pays everything it decided that day
* in ONE transfer, so a voucher may clear several begäran: one 1513 leg per
* request (createRotRutPayoutSetEntry), the way match-batch books one bank
* row against several customer invoices. The request side of the link is
* rot_rut_payout_requests.settlement_journal_entry_id on every request the
* voucher settles; source_id carries the first of them.
*
* At partial approval (delvis beviljad) the paid amount clears here and the
* remainder stays on 1513 until the user corrects it (kundfordran/kundförlust
* depending on the outcome with the buyer): deliberately manual, never
* guessed.
*/
export interface RotRutPayoutLeg {
requestId: string
requestName: string
deductionType: 'rot' | 'rut'
/** What Skatteverket paid for this begäran (kr). */
amount: number
}
function deductionLabel(legs: Array<Pick<RotRutPayoutLeg, 'deductionType'>>): string {
const types = new Set(legs.map((leg) => leg.deductionType))
if (types.size === 1) return types.has('rut') ? 'RUT' : 'ROT'
return 'ROT/RUT'
}
function payoutDescription(label: string, names: string[]): string {
return `Utbetalning ${label}-avdrag från Skatteverket (${names.join(', ')})`
}
export async function createRotRutPayoutSetEntry(
supabase: SupabaseClient,
companyId: string,
userId: string,
params: {
paymentDate: string
/** BAS 19xx account the payout landed on. Defaults to 1930. */
bankAccount?: string
/** One leg per begäran the transfer settles; at least one. */
legs: RotRutPayoutLeg[]
},
): Promise<JournalEntry> {
if (params.legs.length === 0) {
throw new Error('A rot/rut payout voucher needs at least one begäran')
}
const fiscalPeriodId = await findFiscalPeriod(supabase, companyId, params.paymentDate)
if (!fiscalPeriodId) {
throw new Error(`No open fiscal period found for payment date ${params.paymentDate}`)
}
const legs = params.legs.map((leg) => ({
...leg,
amount: roundOre(leg.amount),
}))
const total = roundOre(legs.reduce((sum, leg) => sum + leg.amount, 0))
const bankAccount = params.bankAccount ?? '1930'
const description = payoutDescription(
deductionLabel(legs),
legs.map((leg) => leg.requestName),
)
const input: CreateJournalEntryInput = {
fiscal_period_id: fiscalPeriodId,
entry_date: params.paymentDate,
description,
source_type: 'rot_rut_payout',
source_id: legs[0].requestId,
lines: [
{
account_number: bankAccount,
debit_amount: total,
credit_amount: 0,
line_description: description,
},
...legs.map((leg) => ({
account_number: '1513',
debit_amount: 0,
credit_amount: leg.amount,
// A single begäran keeps the voucher text on both legs (as before);
// a bundle names its own begäran on each 1513 leg.
line_description:
legs.length === 1
? description
: payoutDescription(deductionLabel([leg]), [leg.requestName]),
})),
],
}
return createJournalEntry(supabase, companyId, userId, input)
}
/** One begäran: the bundle voucher with a single 1513 leg. */
export async function createRotRutPayoutEntry(
supabase: SupabaseClient,
companyId: string,
userId: string,
params: {
requestId: string
requestName: string
deductionType: 'rot' | 'rut'
paymentDate: string
amount: number
/** BAS 19xx account the payout landed on. Defaults to 1930. */
bankAccount?: string
},
): Promise<JournalEntry> {
return createRotRutPayoutSetEntry(supabase, companyId, userId, {
paymentDate: params.paymentDate,
bankAccount: params.bankAccount,
legs: [
{
requestId: params.requestId,
requestName: params.requestName,
deductionType: params.deductionType,
amount: params.amount,
},
],
})
}
/**
* Reclaim voucher for the share of a begäran Skatteverket refused.
*
* The 1513 fordran booked at issue was never paid by Skatteverket, so it is
* the buyer's again (HUSFL 2009:194; swedish-invoice-compliance section 8:
* "SKV denies: Debit 1510, Credit 1513"):
*
* Debit 1510 Kundfordringar [refused share, per invoice]
* Credit 1513 Skattereduktion rot/rut [refused share, per invoice]
*
* One voucher per begäran (source_id = request id, guarded by the partial
* unique index journal_entries_rot_rut_reclaim_live_unique), one 1510 and one
* 1513 leg per invoice so the kundreskontra can be read per faktura.
*/
export interface RotRutReclaimLeg {
invoiceId: string
invoiceNumber: string | null
/** The refused share for this invoice (kr). */
amount: number
}
export async function createRotRutReclaimEntry(
supabase: SupabaseClient,
companyId: string,
userId: string,
params: {
requestId: string
requestName: string
deductionType: 'rot' | 'rut'
bookingDate: string
/** One leg per invoice with a refused share; at least one, all > 0. */
legs: RotRutReclaimLeg[]
},
): Promise<JournalEntry> {
const legs = params.legs
.map((leg) => ({ ...leg, amount: roundOre(leg.amount) }))
.filter((leg) => leg.amount > 0)
if (legs.length === 0) {
throw new Error('A rot/rut reclaim voucher needs at least one refused share')
}
const fiscalPeriodId = await findFiscalPeriod(supabase, companyId, params.bookingDate)
if (!fiscalPeriodId) {
throw new Error(`No open fiscal period found for booking date ${params.bookingDate}`)
}
const label = params.deductionType === 'rut' ? 'RUT' : 'ROT'
const description = `Nekat ${label}-avdrag från Skatteverket (${params.requestName})`
const legDescription = (leg: RotRutReclaimLeg) =>
`Nekat ${label}-avdrag faktura ${leg.invoiceNumber ?? leg.invoiceId}`
const input: CreateJournalEntryInput = {
fiscal_period_id: fiscalPeriodId,
entry_date: params.bookingDate,
description,
source_type: 'rot_rut_reclaim',
source_id: params.requestId,
lines: [
...legs.map((leg) => ({
account_number: '1510',
debit_amount: leg.amount,
credit_amount: 0,
line_description: legDescription(leg),
})),
...legs.map((leg) => ({
account_number: '1513',
debit_amount: 0,
credit_amount: leg.amount,
line_description: legDescription(leg),
})),
],
}
return createJournalEntry(supabase, companyId, userId, input)
}