feat: custom inbound mail domains, rot/rut payout file, invoice email texts, security hardening (#878)

* fix(security): guard MCP test keys, RLS role gate + voucher RPC guards, /api MFA gate, deps

- MCP: force dry-run / block writes for test-mode API keys in tools/call (extensions/general/mcp-server)
- DB: current_user_can_write role gate on write policies (40 tables) + tenant guards, SET search_path, REVOKE anon on commit_journal_entry / next_voucher_number / detect_voucher_gaps (migration 20260702093000)
- Middleware: MFA (AAL2) gate on cookie-authenticated /api routes via apiPathSkipsMfaGate
- Deps: npm audit fix clears mailparser/linkify-it/nodemailer/svix/uuid highs; xlsx -> SheetJS 0.20.3

Adds unit + pg-real tests. Does not touch in-progress ROT/RUT or invoice-email-texts work.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat(invoices): rot/rut begäran om utbetalning — HUS XML (V6), payout tracking + settlement, MCP tool

Generates Skatteverkets begäran-om-utbetalning file (schema V6) from paid
ROT/RUT invoices — no submission API exists, the file is uploaded manually
at skatteverket.se. Headless by design for now: API routes + MCP tool
(gnubok_generate_rot_rut_file), no UI surfaces.

- lib/invoices/rot-rut-file.ts: pure XML generator with deterministic
  per-invoice blockers (hours, work type, personnummer, property info,
  mixed rot+rut, XSD limits) + 31 January deadline warnings
- rot_rut_payout_requests(+items) tables: one active begäran per invoice
  (DB triggers incl. reactivation guard), RLS, audit, pg-real tests
- Settlement: POST /settle books debit 1930 / credit 1513 via the engine
  (source_type rot_rut_payout); partial payouts → partially_paid
- Work-type lists corrected against Begaran.xsd: IT-tjänster is rut-only,
  snöskottning/tillsyn/tvätt added (schablontjänster utfört-only)
- Fix: invoice-level fastighetsbeteckning was validated but never
  persisted — now stamped onto rot lines in build-invoice-write; API
  accepts bostadsrätt pair (lägenhetsnr + BRF orgnr, editor UI deferred)
- invoice_items.brf_org_number migration + MCP scope invoices:write

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat(invoices): per-company editable invoice email texts

Add an "E-posttexter" section under Settings -> Fakturering where the
subject, greeting, body and sign-off of the standard invoice email can
be customized per company in Swedish and English. Fields pre-fill with
the standard texts and only diffs from the standard are stored
(company_settings.invoice_email_texts JSONB), so future improvements to
the stock wording still reach companies that have not customized. Each
field has a reset-to-standard button; cleared fields snap back.

Texts support a fixed placeholder set (invoice number, customer name,
first name, company, due date, amount) substituted at send time in a
single pass; unknown placeholders stay literal. Custom texts are
HTML-escaped after substitution, newlines become <br> in the HTML
variant, and subject lines are flattened to a single header line.
Overrides apply to standard invoices only - credit notes, proforma and
delivery notes keep the stock texts. All send paths (UI, v1 API, MCP
approval, recurring) pick the texts up via the existing settings row.

The Zod schema half of this change (InvoiceEmailTextsSchema in
lib/api/schemas.ts) was inadvertently included in 8291f745.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(documents): accept PDFs with preamble before %PDF- header, surface content rejections as 400

detectFileMagic required the %PDF- signature at byte 0 (BOM aside),
rejecting genuine PDFs that carry a leading newline or junk bytes —
files every ISO 32000 reader opens fine. Now scan the first 1024 bytes
for the signature, matching real-reader behavior. Image types stay
strict at offset 0 to keep the anti-placeholder defense tight.

Magic-byte rejections were also mislabeled as DOC_UPLOAD_STORAGE_FAILED
(500 'Filen kunde inte sparas'), blaming storage for a client-side file
problem. Both upload routes now map them to a new
DOC_UPLOAD_INVALID_CONTENT (400) with an accurate message.

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

* feat(bookkeeping): full keyboard flow for manual journal entry

Enter now drives the whole verifikat flow: verifikationstext drops into
the first row missing an account, konto commits advance to debet, Enter
on an empty debet hops to kredit, and an entered amount jumps to the
next row. Once the voucher balances, Enter opens the review (unchanged
gate) and the auto-focused confirm posts it — including through the
no-underlag warning dialog. Escape in the inline review goes back to
the form.

Also fixes an Enter footgun in AccountCombobox: a bare Enter on a
freshly focused field no longer selects the first account in the list —
selection now requires typing or arrow navigation; otherwise Enter
re-commits the current value or bubbles to the form-level handler.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat: add custom inbound domains management for companies

- Implemented functionality to allow companies to claim and manage their own inbound email domains via Resend's API.
- Created a new table `company_inbound_domains` to store domain information, including status and DNS records.
- Added necessary RLS policies to restrict access based on user roles (owner/admin).
- Developed functions for domain normalization, validation, claiming, verification, and removal.
- Implemented webhook handling for domain status updates from Resend.
- Added comprehensive tests for RLS, constraints, and triggers related to the new domain management feature.

* fix: address PR #878 review findings and CI failures

- migrations: drop the ai_usage_tracking policy block from the role-gate
  migration — the table was removed by 20260504120000_remove_ai_subsystem
  and only lingers on staging as drift; a from-scratch chain (pg-real,
  Supabase preview) failed on it
- invoice-inbox: never flip a custom domain to verified off a domain.updated
  webhook alone — confirm the receiving capability with Resend first
  (fail-closed); normalize both sides of the orphan-adoption domain match
- rot/rut: block files where begärt belopp exceeds what the buyer paid
  (DEDUCTION_EXCEEDS_PAYMENT); tighten brf_org_number validation to real
  orgnr shapes; parameterize the settlement bank account (19xx, default 1930)
- rot/rut routes: log acting user on financial mutations, stop swallowing
  item mirror errors, narrow response projections (no customer ids through
  the invoice join); document the deliberate inline-XML decision
- documents: stop echoing raw storage-layer error messages to clients

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix: round-2 CI + compliance findings on PR #878

- migrations: the role-gate migration targeted automation_webhooks, which
  20260515170000_webhooks_v2 renamed to webhooks on the canonical chain
  (staging kept the old name — drift); gate public.webhooks instead,
  dropping legacy schema-sync policy names defensively. Restore the
  20260623130000 owner fallback in next_voucher_number that the stale
  copied-verbatim body silently reverted (caught by engine.pg locally).
  Full migration chain verified from scratch against supabase/postgres:15.
- mcp: bump the tools/list payload ceiling 44K -> 45K — main's #877
  qualified-identifier schemas plus this branch's rot/rut tool crossed the
  ceiling only in combination; documented in the test's history log.
- rot/rut: refuse partial settlement before Skatteverkets beslut is
  recorded (would bypass the PATCH lifecycle and strand the request);
  block zero-kronor ärenden (ZERO_DEDUCTION); require sekelsiffra 16 on
  12-digit brf orgnr in both schema validation and normalizeBrfOrgNr

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix: rename branch migrations off main's colliding versions

After the merge with main, two versions were shared by two files each
(20260702100000: rot_rut_payout_requests vs company_settings_dimensions_
enabled; 20260702130000: invoice_email_texts vs pending_operations_add_
create_dimension_value). psql-based CI applies by filename and doesn't
care, but Supabase branching records migrations by version (PK) — the
second file with the same version breaks the preview with a
schema_migrations_pkey duplicate. Neither branch migration is version-
recorded on staging or prod, so renaming to fresh 20260703 versions is
safe; nothing between the old and new positions depends on these objects.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(security): scope the /api MFA-gate bypass to real Bearer-auth surfaces

Any Authorization header — attacker-controlled — used to skip the AAL2
gate for every /api route, so a stolen-password AAL1 cookie session could
reach cookie-authenticated routes (which ignore the header) by attaching
`Authorization: x`. The skip is now scoped to the surfaces whose auth
contract IS the header (/api/v1 API keys, the MCP endpoint's OAuth
tokens); pure Bearer callers elsewhere (cron secret, signed webhooks)
carry no cookie session and were never touched by the gate, which only
fires for cookie users. Superagent P2 on PR #878.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* test: normalize path separators in dimension statutory guard scan

The route scan compared walked file paths against a POSIX-path allowlist,
so the suite failed on Windows (backslash separators) while passing on
Linux CI. Normalize the scanned paths to forward slashes.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
Mattsson
2026-07-03 13:57:59 +02:00
committed by GitHub
co-authored by Claude Fable 5
parent 678f2ccffd
commit 237b77a366
61 changed files with 7695 additions and 394 deletions
+434
View File
@@ -0,0 +1,434 @@
import { describe, it, expect } from 'vitest'
import type { Invoice, InvoiceItem } from '@/types'
import { makeInvoice } from '@/tests/helpers'
import { encryptPersonnummer } from '@/lib/salary/personnummer'
import {
buildRotRutFile,
evaluateInvoiceForFile,
isPastRequestDeadline,
normalizeBrfOrgNr,
} from '@/lib/invoices/rot-rut-file'
// Personnummer from Skatteverket's official example files (synthetic test
// identities published by the agency — never real people).
const PNR_A = '198406012388'
const PNR_B = '199604102393'
const TODAY = '2026-07-02'
function makeItem(overrides: Partial<InvoiceItem> = {}): InvoiceItem {
return {
id: 'item-1',
invoice_id: 'invoice-1',
sort_order: 0,
description: 'Arbete',
quantity: 1,
unit: 'tim',
unit_price: 10000,
line_total: 10000,
vat_rate: 25,
vat_amount: 2500,
deduction_type: 'rot',
deduction_amount: 3000,
labor_hours: 25,
work_type: 'BYGG',
housing_designation: 'Stockholm Vasastan 1:23',
apartment_number: null,
brf_org_number: null,
created_at: '2026-06-01T00:00:00Z',
...overrides,
}
}
function makeRotInvoice(overrides: Partial<Invoice> = {}, items?: InvoiceItem[]): Invoice {
return makeInvoice({
status: 'paid',
paid_at: '2026-06-20T10:00:00Z',
deduction_total: 3000,
deduction_personnummer_encrypted: encryptPersonnummer(PNR_A),
deduction_personnummer_last4: PNR_A.slice(-4),
items: items ?? [makeItem()],
...overrides,
})
}
describe('buildRotRutFile — rot', () => {
it('produces a schema-shaped rot file for a paid invoice', () => {
const result = buildRotRutFile({
type: 'rot',
name: 'ROT 2026-07-02',
invoices: [makeRotInvoice()],
today: TODAY,
})
expect(result.blockers).toHaveLength(0)
expect(result.arenden).toHaveLength(1)
expect(result.requested_total).toBe(3000)
expect(result.file_name).toBe('rot_begaran_2026-07-02.xml')
const xml = result.xml!
expect(xml).toContain('<?xml version="1.0" encoding="UTF-8"?>')
expect(xml).toContain('xmlns:ns1="http://xmls.skatteverket.se/se/skatteverket/ht/begaran/6.0"')
expect(xml).toContain('xmlns:ns2="http://xmls.skatteverket.se/se/skatteverket/ht/komponent/begaran/6.0"')
expect(xml).toContain('<ns2:NamnPaBegaran>ROT 2026-07-02</ns2:NamnPaBegaran>')
expect(xml).toContain('<ns2:RotBegaran>')
expect(xml).toContain(`<ns2:Kopare>${PNR_A}</ns2:Kopare>`)
expect(xml).toContain('<ns2:BetalningsDatum>2026-06-20</ns2:BetalningsDatum>')
expect(xml).toContain('<ns2:PrisForArbete>12500</ns2:PrisForArbete>')
expect(xml).toContain('<ns2:BetaltBelopp>9500</ns2:BetaltBelopp>')
expect(xml).toContain('<ns2:BegartBelopp>3000</ns2:BegartBelopp>')
expect(xml).toContain('<ns2:Ovrigkostnad>0</ns2:Ovrigkostnad>')
expect(xml).toContain('<ns2:Fastighetsbeteckning>Stockholm Vasastan 1:23</ns2:Fastighetsbeteckning>')
expect(xml).toContain('<ns2:Bygg>')
expect(xml).toContain('<ns2:AntalTimmar>25</ns2:AntalTimmar>')
expect(xml).toContain('<ns2:Materialkostnad>0</ns2:Materialkostnad>')
})
it('emits ärende elements in the XSD sequence order', () => {
const xml = buildRotRutFile({
type: 'rot',
name: 'Ordning',
invoices: [makeRotInvoice()],
today: TODAY,
}).xml!
const order = [
'Kopare',
'BetalningsDatum',
'PrisForArbete',
'BetaltBelopp',
'BegartBelopp',
'FakturaNr',
'Ovrigkostnad',
'Fastighetsbeteckning',
'UtfortArbete',
]
const positions = order.map((el) => xml.indexOf(`<ns2:${el}`))
for (const pos of positions) expect(pos).toBeGreaterThan(-1)
for (let i = 1; i < positions.length; i++) {
expect(positions[i]).toBeGreaterThan(positions[i - 1])
}
})
it('aggregates hours per work type and orders work elements per XSD', () => {
const items = [
makeItem({ id: 'i1', work_type: 'VVS', labor_hours: 3, line_total: 3000, vat_amount: 750, deduction_amount: 900 }),
makeItem({ id: 'i2', work_type: 'EL', labor_hours: 2, line_total: 2000, vat_amount: 500, deduction_amount: 600 }),
makeItem({ id: 'i3', work_type: 'VVS', labor_hours: 2.4, line_total: 1000, vat_amount: 250, deduction_amount: 300 }),
]
const xml = buildRotRutFile({
type: 'rot',
name: 'Aggregering',
invoices: [makeRotInvoice({}, items)],
today: TODAY,
}).xml!
// 3 + 2.4 h VVS → 5 (whole hours per XSD long)
expect(xml).toMatch(/<ns2:Vvs>\s*<ns2:AntalTimmar>5<\/ns2:AntalTimmar>/)
expect(xml).toMatch(/<ns2:El>\s*<ns2:AntalTimmar>2<\/ns2:AntalTimmar>/)
// El precedes Vvs in the XSD sequence
expect(xml.indexOf('<ns2:El>')).toBeLessThan(xml.indexOf('<ns2:Vvs>'))
})
it('uses lägenhetsnummer + normalized BRF orgnr for bostadsrätt', () => {
const items = [
makeItem({ housing_designation: null, apartment_number: '1101', brf_org_number: '769600-0000' }),
]
const xml = buildRotRutFile({
type: 'rot',
name: 'Brf',
invoices: [makeRotInvoice({}, items)],
today: TODAY,
}).xml!
expect(xml).not.toContain('Fastighetsbeteckning')
expect(xml).toContain('<ns2:LagenhetsNr>1101</ns2:LagenhetsNr>')
expect(xml).toContain('<ns2:BrfOrgNr>167696000000</ns2:BrfOrgNr>')
})
it('escapes XML special characters and clamps NamnPaBegaran to 16 chars', () => {
const items = [makeItem({ housing_designation: 'Gränby 1:2 & "Södra" <3' })]
const result = buildRotRutFile({
type: 'rot',
name: 'Väldigt långt namn på begäran som klipps',
invoices: [makeRotInvoice({ invoice_number: 'F<&>2026' }, items)],
today: TODAY,
})
const xml = result.xml!
expect(xml).toContain('Gränby 1:2 &amp; &quot;Södra&quot; &lt;3')
expect(xml).toContain('<ns2:FakturaNr>F&lt;&amp;&gt;2026</ns2:FakturaNr>')
const name = xml.match(/<ns2:NamnPaBegaran>(.*)<\/ns2:NamnPaBegaran>/)?.[1]
expect(name).toBe('Väldigt långt na')
})
})
describe('buildRotRutFile — rut', () => {
function makeRutInvoice(items: InvoiceItem[]): Invoice {
return makeRotInvoice(
{ deduction_personnummer_encrypted: encryptPersonnummer(PNR_B) },
items,
)
}
it('wraps ärenden in HushallBegaran and accepts IT-tjänster', () => {
const items = [
makeItem({ deduction_type: 'rut', work_type: 'IT', labor_hours: 4, housing_designation: null, deduction_amount: 5000 }),
]
const xml = buildRotRutFile({
type: 'rut',
name: 'RUT juni',
invoices: [makeRutInvoice(items)],
today: TODAY,
}).xml!
expect(xml).toContain('<ns2:HushallBegaran>')
expect(xml).not.toContain('RotBegaran')
expect(xml).toMatch(/<ns2:ItTjanster>\s*<ns2:AntalTimmar>4<\/ns2:AntalTimmar>/)
// No property elements for rut
expect(xml).not.toContain('Fastighetsbeteckning')
})
it('reports schablontjänster as Utfort without hours', () => {
const items = [
makeItem({ deduction_type: 'rut', work_type: 'TVATT', labor_hours: null, housing_designation: null, deduction_amount: 250 }),
]
const xml = buildRotRutFile({
type: 'rut',
name: 'Schablon',
invoices: [makeRutInvoice(items)],
today: TODAY,
}).xml!
expect(xml).toMatch(/<ns2:TvattVidTvattinrattning>\s*<ns2:Utfort>true<\/ns2:Utfort>/)
expect(xml).not.toContain('AntalTimmar')
})
})
describe('eligibility blockers', () => {
it('NOT_PAID for unpaid invoices', () => {
const result = evaluateInvoiceForFile('rot', makeRotInvoice({ status: 'sent' }))
expect(result.ok).toBe(false)
if (!result.ok) expect(result.blocker.code).toBe('NOT_PAID')
})
it('MISSING_PAYMENT_DATE when paid without paid_at', () => {
const result = evaluateInvoiceForFile('rot', makeRotInvoice({ paid_at: null }))
expect(result.ok).toBe(false)
if (!result.ok) expect(result.blocker.code).toBe('MISSING_PAYMENT_DATE')
})
it('NO_DEDUCTION_OF_TYPE when the invoice has no lines of the requested type', () => {
const result = evaluateInvoiceForFile('rut', makeRotInvoice())
expect(result.ok).toBe(false)
if (!result.ok) expect(result.blocker.code).toBe('NO_DEDUCTION_OF_TYPE')
})
it('MIXED_DEDUCTION_TYPES when rot and rut lines share an invoice', () => {
const items = [
makeItem(),
makeItem({ id: 'i2', deduction_type: 'rut', work_type: 'STAD', labor_hours: 2 }),
]
const result = evaluateInvoiceForFile('rot', makeRotInvoice({}, items))
expect(result.ok).toBe(false)
if (!result.ok) expect(result.blocker.code).toBe('MIXED_DEDUCTION_TYPES')
})
it('MISSING_PERSONNUMMER without an encrypted personnummer', () => {
const result = evaluateInvoiceForFile(
'rot',
makeRotInvoice({ deduction_personnummer_encrypted: null }),
)
expect(result.ok).toBe(false)
if (!result.ok) expect(result.blocker.code).toBe('MISSING_PERSONNUMMER')
})
it('PERSONNUMMER_UNREADABLE on undecryptable ciphertext', () => {
const result = evaluateInvoiceForFile(
'rot',
makeRotInvoice({ deduction_personnummer_encrypted: 'deadbeef' }),
)
expect(result.ok).toBe(false)
if (!result.ok) expect(result.blocker.code).toBe('PERSONNUMMER_UNREADABLE')
})
it('MISSING_WORK_TYPE when a deduction line has no arbetstyp', () => {
const result = evaluateInvoiceForFile(
'rot',
makeRotInvoice({}, [makeItem({ work_type: null })]),
)
expect(result.ok).toBe(false)
if (!result.ok) expect(result.blocker.code).toBe('MISSING_WORK_TYPE')
})
it('INVALID_WORK_TYPE for IT flagged as rot (rut-only service)', () => {
const result = evaluateInvoiceForFile(
'rot',
makeRotInvoice({}, [makeItem({ work_type: 'IT' })]),
)
expect(result.ok).toBe(false)
if (!result.ok) expect(result.blocker.code).toBe('INVALID_WORK_TYPE')
})
it('MISSING_HOURS when a non-schablon line lacks labor hours', () => {
const result = evaluateInvoiceForFile(
'rot',
makeRotInvoice({}, [makeItem({ labor_hours: null })]),
)
expect(result.ok).toBe(false)
if (!result.ok) expect(result.blocker.code).toBe('MISSING_HOURS')
})
it('HOURS_OUT_OF_RANGE above 999 hours', () => {
const result = evaluateInvoiceForFile(
'rot',
makeRotInvoice({}, [makeItem({ labor_hours: 1200 })]),
)
expect(result.ok).toBe(false)
if (!result.ok) expect(result.blocker.code).toBe('HOURS_OUT_OF_RANGE')
})
it('MISSING_PROPERTY when a rot invoice has no property info', () => {
const result = evaluateInvoiceForFile(
'rot',
makeRotInvoice({}, [makeItem({ housing_designation: null })]),
)
expect(result.ok).toBe(false)
if (!result.ok) expect(result.blocker.code).toBe('MISSING_PROPERTY')
})
it('INVALID_BRF_ORGNR on a malformed BRF orgnr', () => {
const result = evaluateInvoiceForFile(
'rot',
makeRotInvoice({}, [
makeItem({ housing_designation: null, apartment_number: '1101', brf_org_number: '123' }),
]),
)
expect(result.ok).toBe(false)
if (!result.ok) expect(result.blocker.code).toBe('INVALID_BRF_ORGNR')
})
it('PRICE_BELOW_MINIMUM when arbetskostnaden rounds below 2 kr', () => {
const result = evaluateInvoiceForFile(
'rot',
makeRotInvoice({}, [
makeItem({ line_total: 1, vat_amount: 0, deduction_amount: 0.3, labor_hours: 1 }),
]),
)
expect(result.ok).toBe(false)
if (!result.ok) expect(result.blocker.code).toBe('PRICE_BELOW_MINIMUM')
})
it('ZERO_DEDUCTION when the deduction rounds to 0 kr', () => {
const result = evaluateInvoiceForFile(
'rot',
makeRotInvoice({}, [
makeItem({ line_total: 100, vat_amount: 25, deduction_amount: 0, labor_hours: 1 }),
]),
)
expect(result.ok).toBe(false)
if (!result.ok) expect(result.blocker.code).toBe('ZERO_DEDUCTION')
})
it('DEDUCTION_EXCEEDS_PAYMENT when begärt belopp exceeds what the buyer paid', () => {
// 100 kr work, 60 kr deduction → buyer paid 40 kr < 60 kr requested.
const result = evaluateInvoiceForFile(
'rot',
makeRotInvoice({}, [
makeItem({ line_total: 80, vat_amount: 20, deduction_amount: 60, labor_hours: 1 }),
]),
)
expect(result.ok).toBe(false)
if (!result.ok) expect(result.blocker.code).toBe('DEDUCTION_EXCEEDS_PAYMENT')
})
it('allows begärt belopp equal to betalt belopp (50 % rut)', () => {
const result = evaluateInvoiceForFile(
'rut',
makeRotInvoice({}, [
makeItem({
deduction_type: 'rut',
work_type: 'STAD',
line_total: 80,
vat_amount: 20,
deduction_amount: 50,
labor_hours: 2,
housing_designation: null,
}),
]),
)
expect(result.ok).toBe(true)
})
it('collects blockers per invoice while still emitting eligible ones', () => {
const result = buildRotRutFile({
type: 'rot',
name: 'Blandat',
invoices: [makeRotInvoice(), makeRotInvoice({ status: 'sent', invoice_number: 'F-BAD' })],
today: TODAY,
})
expect(result.arenden).toHaveLength(1)
expect(result.blockers).toHaveLength(1)
expect(result.blockers[0].invoice_number).toBe('F-BAD')
expect(result.xml).not.toBeNull()
})
it('returns xml: null when nothing is eligible', () => {
const result = buildRotRutFile({
type: 'rot',
name: 'Tomt',
invoices: [makeRotInvoice({ status: 'sent' })],
today: TODAY,
})
expect(result.xml).toBeNull()
expect(result.requested_total).toBe(0)
})
})
describe('deadline + helpers', () => {
it('warns when the 31 January deadline has passed', () => {
const invoice = makeRotInvoice({ paid_at: '2024-12-30T00:00:00Z' })
const result = buildRotRutFile({ type: 'rot', name: 'Sen', invoices: [invoice], today: TODAY })
expect(result.warnings).toHaveLength(1)
expect(result.warnings[0]).toContain('31 januari')
})
it('isPastRequestDeadline boundary behavior', () => {
expect(isPastRequestDeadline('2025-06-01', '2026-01-31')).toBe(false)
expect(isPastRequestDeadline('2025-06-01', '2026-02-01')).toBe(true)
expect(isPastRequestDeadline('2026-01-15', '2026-07-02')).toBe(false)
})
it('normalizeBrfOrgNr handles 10/12 digits and rejects the rest', () => {
expect(normalizeBrfOrgNr('769600-0000')).toBe('167696000000')
expect(normalizeBrfOrgNr('167696000000')).toBe('167696000000')
expect(normalizeBrfOrgNr('76960')).toBeNull()
// 12 digits without the sekelsiffra 16 prefix is not a valid orgnr.
expect(normalizeBrfOrgNr('123456789012')).toBeNull()
})
it('matches the shape of Skatteverkets official rot example', () => {
// Mirror exempel_rot_3st.xml ärende 2: fastighet + one work type.
const items = [
makeItem({
work_type: 'GLAS_PLAT',
labor_hours: 4,
housing_designation: 'TEST 1:7',
line_total: 1600,
vat_amount: 400,
deduction_amount: 600,
}),
]
const xml = buildRotRutFile({
type: 'rot',
name: 'Exempel Rot',
invoices: [makeRotInvoice({}, items)],
today: TODAY,
}).xml!
expect(xml).toMatch(
/<ns2:Arenden>\s*<ns2:Kopare>\d{12}<\/ns2:Kopare>\s*<ns2:BetalningsDatum>\d{4}-\d{2}-\d{2}<\/ns2:BetalningsDatum>\s*<ns2:PrisForArbete>2000<\/ns2:PrisForArbete>\s*<ns2:BetaltBelopp>1400<\/ns2:BetaltBelopp>\s*<ns2:BegartBelopp>600<\/ns2:BegartBelopp>/,
)
expect(xml).toMatch(/<ns2:Fastighetsbeteckning>TEST 1:7<\/ns2:Fastighetsbeteckning>\s*<ns2:UtfortArbete>\s*<ns2:GlasPlatarbete>/)
})
})
+39 -3
View File
@@ -51,6 +51,7 @@ export interface InvoiceWriteItemInput {
work_type?: string | null
housing_designation?: string | null
apartment_number?: string | null
brf_org_number?: string | null
accrual_period_start?: string | null
accrual_period_end?: string | null
accrual_balance_account?: string | null
@@ -71,6 +72,9 @@ export interface InvoiceWriteInput {
ore_rounding?: boolean
deduction_personnummer?: string
deduction_housing_designation?: string
/** ROT i bostadsrätt: lägenhetsnummer + föreningens orgnr instead of fastighetsbeteckning. */
deduction_apartment_number?: string
deduction_brf_org_number?: string
/** Dimensions PR7: invoice-level bag applied to every generated journal line. */
default_dimensions?: Record<string, string>
items: InvoiceWriteItemInput[]
@@ -127,6 +131,7 @@ export type InvoiceWriteItemRow = {
work_type: string | null
housing_designation: string | null
apartment_number: string | null
brf_org_number: string | null
accrual_period_start: string | null
accrual_period_end: string | null
accrual_balance_account: string | null
@@ -260,7 +265,23 @@ export async function buildInvoiceWriteData(params: {
let deductionPersonnummerEncrypted: string | null = null
let deductionPersonnummerLast4: string | null = null
if (documentType === 'invoice') {
const housingProvided = !!input.deduction_housing_designation?.trim()
// Housing info satisfies the ROT requirement in either of two shapes
// (Begaran.xsd V6): fastighetsbeteckning (småhus/ägarlägenhet) OR
// lägenhetsnummer + bostadsrättsföreningens orgnr (bostadsrätt).
const fastighetProvided = !!input.deduction_housing_designation?.trim()
const apartmentProvided = !!input.deduction_apartment_number?.trim()
const brfProvided = !!input.deduction_brf_org_number?.trim()
if ((apartmentProvided || brfProvided) && !(apartmentProvided && brfProvided)) {
return {
ok: false,
code: 'INVOICE_CREATE_ROT_RUT_VALIDATION',
details: {
errors: ['För bostadsrätt krävs både lägenhetsnummer och föreningens organisationsnummer.'],
warnings: [],
},
}
}
const housingProvided = fastighetProvided || (apartmentProvided && brfProvided)
const personnummerRaw = input.deduction_personnummer?.trim() || ''
const personnummerProvided = personnummerRaw.length > 0
@@ -377,6 +398,7 @@ export async function buildInvoiceWriteData(params: {
work_type: null,
housing_designation: null,
apartment_number: null,
brf_org_number: null,
accrual_period_start: null,
accrual_period_end: null,
accrual_balance_account: null,
@@ -416,8 +438,22 @@ export async function buildInvoiceWriteData(params: {
deduction_amount: deductionAmount,
labor_hours: documentType === 'invoice' ? (item.labor_hours ?? null) : null,
work_type: documentType === 'invoice' ? (item.work_type ?? null) : null,
housing_designation: documentType === 'invoice' ? (item.housing_designation ?? null) : null,
apartment_number: documentType === 'invoice' ? (item.apartment_number ?? null) : null,
// Property info: per-line value wins, else the invoice-level claim-card
// value is stamped onto every deduction line so the Skatteverket file
// generator can read it off the line later. Non-deduction lines carry
// no property data (privacy by default).
housing_designation:
documentType === 'invoice' && deductionType
? (item.housing_designation ?? input.deduction_housing_designation?.trim() ?? null) || null
: null,
apartment_number:
documentType === 'invoice' && deductionType
? (item.apartment_number ?? input.deduction_apartment_number?.trim() ?? null) || null
: null,
brf_org_number:
documentType === 'invoice' && deductionType
? (item.brf_org_number ?? input.deduction_brf_org_number?.trim() ?? null) || null
: null,
// Periodisering (förutbetald intäkt): frozen onto the line. The schedule
// itself is created when the invoice is sent/booked. ROT/RUT lines never
// defer (schema-enforced); the guard above restricted this to real
+441
View File
@@ -0,0 +1,441 @@
import type { Invoice, InvoiceItem } from '@/types'
import { decryptPersonnummer } from '@/lib/salary/personnummer'
import type { DeductionType } from './rot-rut-rules'
/**
* Begäran om utbetalning — rot & rut (Skatteverkets husavdragstjänst).
*
* Generates the HUS XML file (schema V6) that is uploaded manually on
* Skatteverkets e-tjänst "Rot och rut – företag" → "Begär utbetalning via
* fil". There is NO submission API — the file replaces per-ärende manual
* entry, the upload + signature (e-legitimation) stays with the user.
*
* Schema (vendored in dev_docs/skatteverket/husavdrag/):
* root: http://xmls.skatteverket.se/se/skatteverket/ht/begaran/6.0
* types: http://xmls.skatteverket.se/se/skatteverket/ht/komponent/begaran/6.0
*
* Hard schema facts honoured here:
* - Rot and rut can NEVER be mixed in one file (choice of RotBegaran |
* HushallBegaran). One file per deduction type.
* - All amounts are whole kronor (xs:long). PrisForArbete min 2.
* - Kopare is a 12-digit personnummer.
* - NamnPaBegaran is 1–16 characters.
* - Element order inside an ärende is fixed: base fields, then (rot only)
* property fields, then UtfortArbete.
* - Ovrigkostnad is mandatory as soon as UtfortArbete reports hours or
* material. Accounted doesn't itemize övrig kostnad (travel/machines) —
* materials live on non-deduction rows — so 0 is emitted.
*
* Everything in this module is pure and deterministic: the caller passes the
* invoices and `today`; blockers are named per invoice, never guessed.
* File content stays Swedish (statutory surface, see .claude/rules/i18n.md).
*/
const ROOT_NS = 'http://xmls.skatteverket.se/se/skatteverket/ht/begaran/6.0'
const KOMPONENT_NS = 'http://xmls.skatteverket.se/se/skatteverket/ht/komponent/begaran/6.0'
/**
* work_type code → XSD element. Array order = the XSD sequence order, which
* is also the emission order inside UtfortArbete. `schablon` services are
* reported as <Utfort>true</Utfort> — no hours, no material.
*/
const WORK_TYPE_ELEMENTS: Record<DeductionType, ReadonlyArray<{
code: string
element: string
schablon?: boolean
}>> = {
rot: [
{ code: 'BYGG', element: 'Bygg' },
{ code: 'EL', element: 'El' },
{ code: 'GLAS_PLAT', element: 'GlasPlatarbete' },
{ code: 'MARK_DRAN', element: 'MarkDraneringarbete' },
{ code: 'MURNING', element: 'Murning' },
{ code: 'MALNING', element: 'MalningTapetsering' },
{ code: 'VVS', element: 'Vvs' },
],
rut: [
{ code: 'STAD', element: 'Stadning' },
{ code: 'KLAD', element: 'KladOchTextilvard' },
{ code: 'SNOSKOTTNING', element: 'Snoskottning' },
{ code: 'TRADGARD', element: 'Tradgardsarbete' },
{ code: 'BARNPASS', element: 'Barnpassning' },
{ code: 'PERSONLIG_OMS', element: 'Personligomsorg' },
{ code: 'FLYTT', element: 'Flyttjanster' },
{ code: 'IT', element: 'ItTjanster' },
{ code: 'REPARATION', element: 'ReparationAvVitvaror' },
{ code: 'MOBLERING', element: 'Moblering' },
{ code: 'TILLSYN', element: 'TillsynAvBostad' },
{ code: 'TRANSPORT', element: 'TransportTillForsaljning', schablon: true },
{ code: 'TVATT', element: 'TvattVidTvattinrattning', schablon: true },
],
}
export type RotRutBlockerCode =
| 'NOT_PAID'
| 'MISSING_PAYMENT_DATE'
| 'NO_DEDUCTION_OF_TYPE'
| 'MIXED_DEDUCTION_TYPES'
| 'MISSING_PERSONNUMMER'
| 'PERSONNUMMER_UNREADABLE'
| 'MISSING_WORK_TYPE'
| 'INVALID_WORK_TYPE'
| 'MISSING_HOURS'
| 'HOURS_OUT_OF_RANGE'
| 'MISSING_PROPERTY'
| 'INVALID_BRF_ORGNR'
| 'PROPERTY_TOO_LONG'
| 'PRICE_BELOW_MINIMUM'
| 'DEDUCTION_EXCEEDS_PAYMENT'
| 'ZERO_DEDUCTION'
export interface RotRutBlocker {
invoice_id: string
invoice_number: string | null
code: RotRutBlockerCode
/** Swedish — shown as-is in UI and MCP output (statutory surface). */
message: string
}
/** One ärende (buyer + invoice) accepted into the file. */
export interface RotRutArende {
invoice_id: string
invoice_number: string | null
personnummer_last4: string
betalnings_datum: string
/** Whole kronor, as emitted. */
pris_for_arbete: number
betalt_belopp: number
begart_belopp: number
}
export interface BuildRotRutFileResult {
/** null when no invoice passed eligibility. */
xml: string | null
file_name: string
arenden: RotRutArende[]
blockers: RotRutBlocker[]
/** Non-blocking notices (e.g. deadline passed). Swedish. */
warnings: string[]
/** Sum of begart_belopp, whole kronor. */
requested_total: number
}
interface EvaluatedArende {
arende: RotRutArende
/** Emission-ready fragments, in XSD order. */
kopare: string
fakturaNr: string | null
property: { fastighet?: string; lagenhetsNr?: string; brfOrgNr?: string } | null
/** element name → { hours, schablon } aggregated over lines. */
work: Array<{ element: string; schablon: boolean; hours: number }>
}
function isDeductionLine(item: InvoiceItem, type: DeductionType): boolean {
return item.deduction_type === type && item.line_type !== 'text'
}
/**
* Normalize a BRF orgnr to the 12-digit form Skatteverkets exempel uses
* (sekelsiffra 16 + 10-digit orgnr). Returns null when the input can't be
* normalized deterministically.
*/
export function normalizeBrfOrgNr(raw: string): string | null {
const digits = raw.replace(/\D/g, '')
// 12-digit orgnr must carry sekelsiffra 16 (juridisk person) — anything
// else is not a valid Swedish orgnr and fails SKV's schema at upload.
if (digits.length === 12) return digits.startsWith('16') ? digits : null
if (digits.length === 10) return `16${digits}`
return null
}
/**
* Evaluate one invoice against the file rules for `type`. Returns either an
* emission-ready ärende or the FIRST blocker hit (one clear reason beats a
* pile). Exported so the eligible-list API can show per-invoice reasons with
* exactly the same logic that later generates the file.
*/
export function evaluateInvoiceForFile(
type: DeductionType,
invoice: Invoice,
): { ok: true; value: EvaluatedArende } | { ok: false; blocker: RotRutBlocker } {
const block = (code: RotRutBlockerCode, message: string): { ok: false; blocker: RotRutBlocker } => ({
ok: false,
blocker: { invoice_id: invoice.id, invoice_number: invoice.invoice_number ?? null, code, message },
})
const items = invoice.items ?? []
const typeLines = items.filter((i) => isDeductionLine(i, type))
const otherType: DeductionType = type === 'rot' ? 'rut' : 'rot'
const otherLines = items.filter((i) => isDeductionLine(i, otherType))
if (typeLines.length === 0) {
return block('NO_DEDUCTION_OF_TYPE', `Fakturan har inga ${type.toUpperCase()}-rader.`)
}
// One invoice must map to exactly one ärende in exactly one file. Mixed
// rot+rut invoices would need to live in two active begäran at once, which
// the double-request guard (rightly) refuses — ask the user to split.
if (otherLines.length > 0) {
return block(
'MIXED_DEDUCTION_TYPES',
'Fakturan blandar ROT- och RUT-rader. Skatteverket tillåter inte båda i samma fil — dela upp i separata fakturor.',
)
}
if (invoice.status !== 'paid') {
return block('NOT_PAID', 'Kunden måste ha betalat sin del av fakturan innan utbetalning kan begäras.')
}
const paidDate = invoice.paid_at ? String(invoice.paid_at).slice(0, 10) : null
if (!paidDate) {
return block('MISSING_PAYMENT_DATE', 'Fakturan saknar betalningsdatum.')
}
if (!invoice.deduction_personnummer_encrypted) {
return block('MISSING_PERSONNUMMER', 'Fakturan saknar köparens personnummer.')
}
let kopare: string
try {
kopare = decryptPersonnummer(invoice.deduction_personnummer_encrypted).replace(/\D/g, '')
} catch {
return block('PERSONNUMMER_UNREADABLE', 'Köparens personnummer kunde inte läsas — öppna fakturautkastet och ange det igen.')
}
if (kopare.length !== 12) {
return block('PERSONNUMMER_UNREADABLE', 'Köparens personnummer är inte 12 siffror.')
}
// Aggregate hours per work type, in XSD element order.
const elementMap = WORK_TYPE_ELEMENTS[type]
const hoursByCode = new Map<string, number>()
for (const line of typeLines) {
const code = line.work_type ?? ''
if (!code) {
return block('MISSING_WORK_TYPE', 'Alla ROT/RUT-rader måste ha en arbetstyp. Öppna fakturan och välj arbetstyp per rad.')
}
const def = elementMap.find((e) => e.code === code)
if (!def) {
return block(
'INVALID_WORK_TYPE',
`Arbetstypen "${code}" är inte giltig för ${type.toUpperCase()} enligt Skatteverkets filformat.`,
)
}
if (!def.schablon) {
const hours = line.labor_hours ?? 0
if (hours <= 0) {
return block('MISSING_HOURS', 'Alla ROT/RUT-rader måste ha antal arbetstimmar (schablontjänster undantagna).')
}
hoursByCode.set(code, (hoursByCode.get(code) ?? 0) + hours)
} else {
hoursByCode.set(code, hoursByCode.get(code) ?? 0)
}
}
const work: EvaluatedArende['work'] = []
for (const def of elementMap) {
if (!hoursByCode.has(def.code)) continue
const hours = Math.round(hoursByCode.get(def.code) ?? 0)
if (!def.schablon && (hours < 1 || hours > 999)) {
return block('HOURS_OUT_OF_RANGE', `Antal timmar för ${def.element} måste vara 1–999 (är ${hours}).`)
}
work.push({ element: def.element, schablon: def.schablon === true, hours })
}
// Property info (rot only): fastighetsbeteckning OR lägenhetsnummer + BRF
// orgnr, read off the rot lines (stamped there at save time).
let property: EvaluatedArende['property'] = null
if (type === 'rot') {
const fastighet = typeLines.map((l) => l.housing_designation?.trim()).find(Boolean) ?? null
const lagenhet = typeLines.map((l) => l.apartment_number?.trim()).find(Boolean) ?? null
const brfRaw = typeLines.map((l) => l.brf_org_number?.trim()).find(Boolean) ?? null
if (brfRaw && lagenhet) {
const brf = normalizeBrfOrgNr(brfRaw)
if (!brf) {
return block('INVALID_BRF_ORGNR', `Föreningens organisationsnummer "${brfRaw}" är ogiltigt (10 eller 12 siffror krävs).`)
}
if (lagenhet.length > 25) {
return block('PROPERTY_TOO_LONG', 'Lägenhetsnumret är längre än 25 tecken.')
}
property = { lagenhetsNr: lagenhet, brfOrgNr: brf }
} else if (fastighet) {
if (fastighet.length > 40) {
return block('PROPERTY_TOO_LONG', 'Fastighetsbeteckningen är längre än 40 tecken (Skatteverkets maxlängd).')
}
property = { fastighet }
} else {
return block(
'MISSING_PROPERTY',
'ROT kräver fastighetsbeteckning eller lägenhetsnummer + föreningens orgnr. Komplettera fakturan.',
)
}
}
// Amounts, whole kronor. PrisForArbete = arbetskostnad inkl moms for the
// flagged lines; BegartBelopp mirrors the deduction the invoice actually
// credited (1513); BetaltBelopp = what the buyer paid for the work.
const prisForArbete = Math.round(
typeLines.reduce((sum, l) => sum + (l.line_total ?? 0) + (l.vat_amount ?? 0), 0),
)
const begartBelopp = Math.round(
typeLines.reduce((sum, l) => sum + (l.deduction_amount ?? 0), 0),
)
const betaltBelopp = prisForArbete - begartBelopp
if (prisForArbete < 2) {
return block('PRICE_BELOW_MINIMUM', 'Arbetskostnaden måste vara minst 2 kr (Skatteverkets filformat).')
}
// A zero-kronor ärende is rejected (or silently ignored) by Skatteverket —
// an invoice whose deduction rounds to 0 has nothing to request.
if (begartBelopp < 1) {
return block('ZERO_DEDUCTION', 'Fakturans ROT/RUT-avdrag är 0 kr — det finns inget belopp att begära.')
}
// The buyer must have paid at least as much as is being requested
// (skattereduktionen är max 50 % av arbetskostnaden). Independent rounding
// of pris/begärt could otherwise even push BetaltBelopp negative, which
// Skatteverkets schema rejects outright.
if (begartBelopp > betaltBelopp) {
return block(
'DEDUCTION_EXCEEDS_PAYMENT',
`Begärt belopp (${begartBelopp} kr) överstiger vad kunden betalat för arbetet (${betaltBelopp} kr) — Skatteverket avslår. Kontrollera avdragsraderna.`,
)
}
return {
ok: true,
value: {
arende: {
invoice_id: invoice.id,
invoice_number: invoice.invoice_number ?? null,
personnummer_last4: kopare.slice(-4),
betalnings_datum: paidDate,
pris_for_arbete: prisForArbete,
betalt_belopp: betaltBelopp,
begart_belopp: begartBelopp,
},
kopare,
fakturaNr: invoice.invoice_number ? String(invoice.invoice_number).slice(0, 20) : null,
property,
work,
},
}
}
function escapeXml(str: string): string {
return str
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&apos;')
}
/**
* The 31 January deadline: a begäran must reach Skatteverket no later than
* 31 January the year AFTER the buyer paid. Returns true when `paidDate`'s
* window has closed as of `today` (both YYYY-MM-DD).
*/
export function isPastRequestDeadline(paidDate: string, today: string): boolean {
const paidYear = Number(paidDate.slice(0, 4))
const deadline = `${paidYear + 1}-01-31`
return today > deadline
}
export function buildRotRutFile(params: {
type: DeductionType
/** NamnPaBegaran — clamped to the XSD's 16-char cap. */
name: string
invoices: Invoice[]
/** YYYY-MM-DD, injected for determinism. */
today: string
}): BuildRotRutFileResult {
const { type, invoices, today } = params
const arenden: RotRutArende[] = []
const evaluated: EvaluatedArende[] = []
const blockers: RotRutBlocker[] = []
const warnings: string[] = []
for (const invoice of invoices) {
const result = evaluateInvoiceForFile(type, invoice)
if (!result.ok) {
blockers.push(result.blocker)
continue
}
evaluated.push(result.value)
arenden.push(result.value.arende)
if (isPastRequestDeadline(result.value.arende.betalnings_datum, today)) {
warnings.push(
`Faktura ${result.value.arende.invoice_number ?? result.value.arende.invoice_id}: betalningen (${result.value.arende.betalnings_datum}) har passerat sista begäransdatum (31 januari året efter betalningsåret). Skatteverket kan avslå.`,
)
}
}
const fileName = `${type}_begaran_${today}.xml`
if (evaluated.length === 0) {
return { xml: null, file_name: fileName, arenden, blockers, warnings, requested_total: 0 }
}
const name = escapeXml(params.name.slice(0, 16))
const wrapper = type === 'rot' ? 'RotBegaran' : 'HushallBegaran'
const lines: string[] = []
lines.push('<?xml version="1.0" encoding="UTF-8"?>')
lines.push(
`<ns1:Begaran xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:ns1="${ROOT_NS}" xmlns:ns2="${KOMPONENT_NS}">`,
)
lines.push(`\t<ns2:NamnPaBegaran>${name}</ns2:NamnPaBegaran>`)
lines.push(`\t<ns2:${wrapper}>`)
for (const ev of evaluated) {
lines.push('\t\t<ns2:Arenden>')
lines.push(`\t\t\t<ns2:Kopare>${ev.kopare}</ns2:Kopare>`)
lines.push(`\t\t\t<ns2:BetalningsDatum>${ev.arende.betalnings_datum}</ns2:BetalningsDatum>`)
lines.push(`\t\t\t<ns2:PrisForArbete>${ev.arende.pris_for_arbete}</ns2:PrisForArbete>`)
lines.push(`\t\t\t<ns2:BetaltBelopp>${ev.arende.betalt_belopp}</ns2:BetaltBelopp>`)
lines.push(`\t\t\t<ns2:BegartBelopp>${ev.arende.begart_belopp}</ns2:BegartBelopp>`)
if (ev.fakturaNr) {
lines.push(`\t\t\t<ns2:FakturaNr>${escapeXml(ev.fakturaNr)}</ns2:FakturaNr>`)
}
// Mandatory when UtfortArbete reports hours; Accounted books övriga
// kostnader (resor, maskiner) outside the deduction rows → always 0.
lines.push('\t\t\t<ns2:Ovrigkostnad>0</ns2:Ovrigkostnad>')
if (ev.property?.fastighet) {
lines.push(`\t\t\t<ns2:Fastighetsbeteckning>${escapeXml(ev.property.fastighet)}</ns2:Fastighetsbeteckning>`)
}
if (ev.property?.lagenhetsNr) {
lines.push(`\t\t\t<ns2:LagenhetsNr>${escapeXml(ev.property.lagenhetsNr)}</ns2:LagenhetsNr>`)
lines.push(`\t\t\t<ns2:BrfOrgNr>${ev.property.brfOrgNr}</ns2:BrfOrgNr>`)
}
if (ev.work.length > 0) {
lines.push('\t\t\t<ns2:UtfortArbete>')
for (const w of ev.work) {
if (w.schablon) {
lines.push(`\t\t\t\t<ns2:${w.element}>`)
lines.push('\t\t\t\t\t<ns2:Utfort>true</ns2:Utfort>')
lines.push(`\t\t\t\t</ns2:${w.element}>`)
} else {
lines.push(`\t\t\t\t<ns2:${w.element}>`)
lines.push(`\t\t\t\t\t<ns2:AntalTimmar>${w.hours}</ns2:AntalTimmar>`)
// Materials are invoiced on non-deduction rows in Accounted's
// fakturamodell — the file reports 0 (XSD requires the element).
lines.push('\t\t\t\t\t<ns2:Materialkostnad>0</ns2:Materialkostnad>')
lines.push(`\t\t\t\t</ns2:${w.element}>`)
}
}
lines.push('\t\t\t</ns2:UtfortArbete>')
}
lines.push('\t\t</ns2:Arenden>')
}
lines.push(`\t</ns2:${wrapper}>`)
lines.push('</ns1:Begaran>')
const requestedTotal = arenden.reduce((sum, a) => sum + a.begart_belopp, 0)
return {
xml: lines.join('\n'),
file_name: fileName,
arenden,
blockers,
warnings,
requested_total: requestedTotal,
}
}
+18 -10
View File
@@ -37,9 +37,13 @@ export const RUT_MAX = 75000
export type DeductionType = 'rot' | 'rut'
/** Skatteverket work codes used by Husavdragstjänsten. Maps a free-text */
/** "what the worker did" label to the official code the Skatteverket file */
/** will need. v1 stores both — the label is shown on the PDF; the code is */
/** stored as `work_type` for the future submission file. */
/** "what the worker did" label to the official code. The code drives which */
/** element the begäran-om-utbetalning file (Begaran.xsd V6) reports the */
/** hours under — see WORK_TYPE_ELEMENTS in lib/invoices/rot-rut-file.ts. */
/** The lists mirror the XSD exactly: rot work types are the seven */
/** ArendeUtfortArbeteRotTYPE elements (IT-tjänster is a RUT service and was */
/** removed from the rot list 2026-07); rut covers all thirteen */
/** ArendeUtfortArbeteRutTYPE elements incl. the two schablontjänster. */
export const ROT_WORK_TYPES = [
{ code: 'BYGG', label: 'Byggnadsarbete' },
{ code: 'EL', label: 'Elarbete' },
@@ -48,20 +52,24 @@ export const ROT_WORK_TYPES = [
{ code: 'MURNING', label: 'Murnings- och putsarbete' },
{ code: 'MALNING', label: 'Mål- och tapetseringsarbete' },
{ code: 'VVS', label: 'VVS-arbete' },
{ code: 'IT', label: 'IT-tjänster i hemmet' },
] as const
export const RUT_WORK_TYPES = [
{ code: 'STAD', label: 'Städning, tvätt och vård av kläder' },
{ code: 'KLAD', label: 'Klädvård i hemmet' },
{ code: 'STAD', label: 'Städning' },
{ code: 'KLAD', label: 'Kläd- och textilvård' },
{ code: 'SNOSKOTTNING', label: 'Snöskottning' },
{ code: 'TRADGARD', label: 'Trädgårdsarbete' },
{ code: 'BARNPASS', label: 'Barnpassning' },
{ code: 'PERSONLIG_OMS', label: 'Personlig omsorg' },
{ code: 'FLYTT', label: 'Flytthjälp' },
{ code: 'REPARATION', label: 'Reparation av vitvaror' },
{ code: 'FLYTT', label: 'Flyttjänster' },
{ code: 'IT', label: 'IT-tjänster i hemmet' },
{ code: 'MOBLERING', label: 'Möblering och tillsyn av bostad' },
{ code: 'TRANSPORT', label: 'Transport till och från återvinning' },
{ code: 'REPARATION', label: 'Reparation av vitvaror' },
{ code: 'MOBLERING', label: 'Möblering' },
{ code: 'TILLSYN', label: 'Tillsyn av bostad' },
// Schablontjänster: reported as utförd/ej utförd in the Skatteverket file,
// never with hours or material.
{ code: 'TRANSPORT', label: 'Transport till försäljning (schablon)' },
{ code: 'TVATT', label: 'Tvätt vid tvättinrättning (schablon)' },
] as const
export interface ItemForDeduction {
+206
View File
@@ -0,0 +1,206 @@
import type { SupabaseClient } from '@supabase/supabase-js'
import type { Invoice } from '@/types'
import {
buildRotRutFile,
evaluateInvoiceForFile,
type BuildRotRutFileResult,
type RotRutBlocker,
} from './rot-rut-file'
import type { DeductionType } from './rot-rut-rules'
/**
* Shared service behind the rot/rut payout-file API routes and the MCP tool
* (gnubok_generate_rot_rut_file) — one implementation of "which invoices can
* go into a begäran" and "record the begäran", so the two surfaces can never
* drift apart.
*/
export interface RotRutCandidateSummary {
invoice_id: string
invoice_number: string | null
customer_name: string | null
personnummer_last4: string
betalnings_datum: string
pris_for_arbete: number
begart_belopp: number
}
export interface RotRutBlockedSummary {
invoice_id: string
invoice_number: string | null
customer_name: string | null
code: string
message: string
}
type InvoiceWithCustomer = Invoice & { customer?: { name?: string | null } | null }
/**
* Paid deduction-carrying invoices not yet claimed by an active begäran,
* evaluated against the file rules. Invoices whose deduction belongs solely
* to the other type are omitted entirely (they're the other list's business).
*/
export async function listRotRutCandidates(
supabase: SupabaseClient,
companyId: string,
type: DeductionType,
): Promise<
| { ok: true; eligible: RotRutCandidateSummary[]; blocked: RotRutBlockedSummary[] }
| { ok: false; dbError: unknown }
> {
const { data: invoices, error } = await supabase
.from('invoices')
.select('*, items:invoice_items(*), customer:customers(id, name)')
.eq('company_id', companyId)
.eq('document_type', 'invoice')
.eq('status', 'paid')
.gt('deduction_total', 0)
.order('paid_at', { ascending: true })
if (error) return { ok: false, dbError: error }
const { data: activeItems, error: activeError } = await supabase
.from('rot_rut_payout_request_items')
.select('invoice_id, request:rot_rut_payout_requests!inner(id, status, company_id)')
.eq('request.company_id', companyId)
.not('request.status', 'in', '("cancelled","rejected")')
if (activeError) return { ok: false, dbError: activeError }
const activeInvoiceIds = new Set((activeItems ?? []).map((r) => r.invoice_id))
const eligible: RotRutCandidateSummary[] = []
const blocked: RotRutBlockedSummary[] = []
for (const invoice of (invoices ?? []) as unknown as InvoiceWithCustomer[]) {
if (activeInvoiceIds.has(invoice.id)) continue
const result = evaluateInvoiceForFile(type, invoice)
if (result.ok) {
eligible.push({
invoice_id: invoice.id,
invoice_number: invoice.invoice_number ?? null,
customer_name: invoice.customer?.name ?? null,
personnummer_last4: result.value.arende.personnummer_last4,
betalnings_datum: result.value.arende.betalnings_datum,
pris_for_arbete: result.value.arende.pris_for_arbete,
begart_belopp: result.value.arende.begart_belopp,
})
} else if (result.blocker.code !== 'NO_DEDUCTION_OF_TYPE') {
blocked.push({
invoice_id: invoice.id,
invoice_number: invoice.invoice_number ?? null,
customer_name: invoice.customer?.name ?? null,
code: result.blocker.code,
message: result.blocker.message,
})
}
}
return { ok: true, eligible, blocked }
}
export type CreateRotRutRequestResult =
| { ok: true; request: Record<string, unknown>; file: BuildRotRutFileResult }
| {
ok: false
code:
| 'ROT_RUT_REQUEST_NOT_FOUND'
| 'ROT_RUT_NO_ELIGIBLE_INVOICES'
| 'ROT_RUT_INVOICES_BLOCKED'
| 'ROT_RUT_INVOICE_CONFLICT'
| 'ROT_RUT_FILE_CREATE_FAILED'
blockers?: RotRutBlocker[]
missingInvoiceIds?: string[]
}
/**
* Generate the begäran file for the given invoices and record the request +
* items. All-or-nothing: any blocked invoice rejects the whole call with the
* per-invoice blockers. The DB trigger enforce_single_active_rot_rut_request
* stays the authoritative double-request guard (surfaced as INVOICE_CONFLICT).
*
* Document archiving is deliberately NOT done here — it needs the storage
* bucket and differs per surface (the API route archives, best-effort).
*/
export async function createRotRutPayoutRequest(
supabase: SupabaseClient,
companyId: string,
userId: string,
params: {
type: DeductionType
invoiceIds: string[]
name?: string
today?: string
},
): Promise<CreateRotRutRequestResult> {
const today = params.today ?? new Date().toISOString().slice(0, 10)
const name = (params.name ?? `${params.type.toUpperCase()} ${today}`).slice(0, 16)
const { data: invoices, error: invoicesError } = await supabase
.from('invoices')
.select('*, items:invoice_items(*)')
.eq('company_id', companyId)
.eq('document_type', 'invoice')
.in('id', params.invoiceIds)
if (invoicesError) {
return { ok: false, code: 'ROT_RUT_FILE_CREATE_FAILED' }
}
const foundIds = new Set((invoices ?? []).map((i) => i.id))
const missing = params.invoiceIds.filter((id) => !foundIds.has(id))
if (missing.length > 0) {
return { ok: false, code: 'ROT_RUT_REQUEST_NOT_FOUND', missingInvoiceIds: missing }
}
const file = buildRotRutFile({
type: params.type,
name,
invoices: (invoices ?? []) as unknown as Invoice[],
today,
})
if (!file.xml) {
return { ok: false, code: 'ROT_RUT_NO_ELIGIBLE_INVOICES', blockers: file.blockers }
}
if (file.blockers.length > 0) {
return { ok: false, code: 'ROT_RUT_INVOICES_BLOCKED', blockers: file.blockers }
}
const { data: payoutRequest, error: insertError } = await supabase
.from('rot_rut_payout_requests')
.insert({
company_id: companyId,
user_id: userId,
deduction_type: params.type,
name,
status: 'generated',
requested_total: file.requested_total,
file_name: file.file_name,
})
.select()
.single()
if (insertError || !payoutRequest) {
return { ok: false, code: 'ROT_RUT_FILE_CREATE_FAILED' }
}
const itemRows = file.arenden.map((a) => ({
request_id: payoutRequest.id,
invoice_id: a.invoice_id,
requested_amount: a.begart_belopp,
}))
const { error: itemsError } = await supabase
.from('rot_rut_payout_request_items')
.insert(itemRows)
if (itemsError) {
// Roll back the header row — without items the request is meaningless.
await supabase.from('rot_rut_payout_requests').delete().eq('id', payoutRequest.id)
const conflict =
(itemsError as { code?: string }).code === '23505' ||
itemsError.message?.includes('active rot/rut payout request')
return { ok: false, code: conflict ? 'ROT_RUT_INVOICE_CONFLICT' : 'ROT_RUT_FILE_CREATE_FAILED' }
}
return { ok: true, request: payoutRequest, file }
}