Fix/articles (#1216)
* fix(security): gate replace_sie_import behind owner/admin membership The RPC was SECURITY DEFINER with EXECUTE granted to PUBLIC and anon, no company_members lookup, no auth.uid() reference and no unauthorized raise, while setting gnubok.allow_delete to disarm the BFL immutability and retention triggers. Any caller holding a company_id and an import id could hard delete another tenant's verifikationer. Confirmed live in production. Applies the same fail closed owner/admin guard that undo_sie_import already carries (migration 20260624120000), resolving the actor from COALESCE(p_user_id, auth.uid()) so it denies when the role is NULL, then revokes EXECUTE from PUBLIC and anon. search_path and the raised statement_timeout are restated, since CREATE OR REPLACE drops settings that are not repeated. userId is a required parameter on replaceSIEImport: the service client has a NULL auth.uid(), so a caller without an explicit actor now fails to compile rather than hitting the closed gate at runtime. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * fix(security): validate arcim OAuth callback state server side The callback route is skipAuth and decoded the state parameter as plain base64url JSON, trusting consentId and provider from it. A one time code was minted at flow start and never read. An unauthenticated attacker who learned a consent id could run an OAuth flow on their own provider account and post the callback with a forged state, landing their tokens on another tenant's consent, so the victim's next migration imported the attacker's ledger. State is now an opaque randomBytes(32) pointer to a provider_otc row, consumed by a single atomic UPDATE guarded on used_at IS NULL and expires_at, so a replay loses the row lock race and updates nothing. provider is read from provider_consents rather than trusted from the client. provider_otc already existed for exactly this purpose and was never wired up. Also scopes getConsent to an owning company, closing a cross tenant status oracle where the preview and migrate paths echoed a consent's status before the scoped check ran. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * fix(security): scope documents storage to company_id (phase A) The documents bucket policies matched on auth.uid(), and upload keys were documents/{userId}/..., so company membership was never consulted. Removing a member revoked nothing: their session still authenticated and they kept direct Storage read access to every receipt, supplier invoice and bank statement they had uploaded. The same bug was fixed for sie-files in 20260416120000; this bucket was left behind. Phase A is additive. Company scoped policies are added alongside the uploader scoped ones, uploads move to documents/{companyId}/{userId}/..., and reads accept either layout so nothing breaks mid migration. Phase C, which drops the old policies, is gated on the backfill reporting zero remaining legacy prefix objects. The policy compares the company segment as text rather than casting to uuid the way sie-files does: this bucket holds keys whose second segment is not a uuid (MCP audit packages), and Postgres does not guarantee the bucket prefix qual runs before the cast, so a planner reordering would raise 22P02 and fail the whole query instead of filtering the row out. deleteDocument now removes both candidate keys. Removing only the stored pointer would leave a readable orphan copy of a document the user asked to erase. The backfill script is included but has never been run. It defaults to dry run, refuses .env.local by name, and verifies each copy is readable and SHA-256 identical before repointing the row. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * fix(security): enforce events:read scope and membership on /api/events This was the only one of the three validateApiKey call sites with no downstream guard: v1 and the MCP server both check scope and re-verify company membership, this route did neither. An events:read scope existed and was documented as gating the endpoint but was never called, so a legacy key falling back to DEFAULT_SCOPES read the full log. The bound company id went straight from the api_keys row into a service role query, so a key whose user had been removed from the company kept reading. Adds the scope check before any database access, re-verifies company_members with archived_at IS NULL, honours test mode by stamping X-Gnubok-Mode instead of ignoring it, applies minimisePayload so the pull surface can never return a wider payload than the push surface, and replaces the three flat error strings with the canonical envelope. Test key reads are served rather than blocked: TEST_KEY_WRITE_BLOCKED is gated on mutations in with-api-v1, so a read gets the same treatment as every other v1 read endpoint. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * perf(bookkeeping): sweep remaining journal_entries!inner embeds A previous refactor removed this pattern from lib/reports and introduced fetchEntryLines, but the class was never swept. Seventeen sites remained and had become the top application consumer of production database time: measured across the resulting query shapes, 32,694 calls and 25,848 seconds of execution, mean 790ms, with shapes averaging 2.6s and 3.0s and maxing at 7,962ms against the 8s statement_timeout, which surfaced to users as 500s on the booking path. PostgREST compiles an embed with filters on the embedded side into a correlated INNER JOIN LATERAL with a parameterized LIMIT, which stops Postgres reordering the join, so each query walked the whole journal_entry_lines table across all tenants. Driving from the entries side instead turns that into two indexed round trips. Converted sites keep their existing shape: the helper reattaches the parent entry under the same key the embed produced. Several conversions also remove a latent silent truncation where an unpaginated query was capped at PostgREST's 1000 row ceiling. Two deliberate exceptions. The free text ilike legs of the MCP display query stay on the embed, because each is capped at legLimit and that cap drives the truncation contract the tool reports, while the helper is unbounded. The accounts route moves to the existing get_account_usage_counts RPC instead, since its embed was a head count and the helper returns rows. commitEntry's write path is untouched: the change there is confined to the read query of the pre-commit dimension rule check. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * fix(api): anchor v1 list cursors on created_at Page two returned page one, forever, while still advertising a fresh next_cursor. The three routes sorted by and encoded a Postgres date column, which serializes as YYYY-MM-DD, but decodeDefaultCursor validates the cursor timestamp as full ISO-8601 and returned null, so the keyset filter was never applied and has_more never went false. An integrator syncing verifikat looped on the newest rows indefinitely. The transactions route already solved this and its comment names the trap; the fix was never ported. All three now order and encode on created_at with an id tie break, matching the transactions keyset predicate exactly. ISO_TIMESTAMP is deliberately left alone: relaxing it would silently change sort semantics on the route that currently works. Default ordering therefore moves from business date to insert order. Every business date is still on the row, and the invoices list gains date_from and date_to filters so a date range is still reachable; the other two already had them. The tests use an in-memory PostgREST that actually evaluates the filters, because the repo's pass-through mock cannot catch this class of bug: the bug is that the filter is never sent. They walk to exhaustion with a hard iteration cap, so an unterminated walk fails instead of hanging. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * fix(api): separate dry run from commit in the idempotency hash The request hash was built from url.pathname, which excludes the query string, so a dry run and its commit hashed identically. Following the flow documented in dry-run.ts, re-issuing the request with the same Idempotency-Key returned the cached preview with Idempotent-Replayed set and wrote nothing, while reporting 200. An agent or integrator saw success for a write that never happened. dry_run is folded into the hash only when true, not as an unconditional boolean. Including it as false would change the hash of every ordinary write, and with a 24h idempotency TTL any key in flight across the deploy would fail the request_hash comparison and 409 on a legitimate retry. Both hash call sites now go through one shared helper so they cannot drift into a permanent cache miss, and dry run responses are no longer stored at all. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * ci: install the Bedrock SDK out of tree in the compliance review The Swedish accounting compliance gate had failed ten consecutive runs and so was posting nothing. With --no-package-lock npm discarded the lockfile and re-resolved the whole tree from package.json, floating @hookform/resolvers to 5.4.3, whose valibot ^1 peer conflicts with the pinned valibot 0.39.0. Installing into the parent of the checkout resolves only that one package, so an unrelated peer conflict can never take the gate down again. Node still finds it because ESM bare specifiers walk up parent node_modules; NODE_PATH would not have worked, as it is CommonJS only. --legacy-peer-deps was rejected because it masks future genuine peer conflicts and still reifies the full tree. The same step's SDK version is aligned from 0.31.0 back to the 0.29.1 that package.json and check:guards enforce after the streaming outage. That drift went unnoticed because the pin guard only inspects package.json and the lockfile, never workflow files. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * build(docker): generate crontabs from vercel.json vercel.json defines 16 cron jobs; both Docker crontabs carried 9, and were byte identical to each other. Self hosted deployments therefore never sent recurring invoices, never dispatched webhooks and never cleaned up idempotency keys. tax-deadlines also ran once a year on 2 January instead of daily, and documents/verify weekly instead of daily. Extension crons are included rather than excluded. The Dockerfile copies the whole tree before building, so every extension cron route is compiled into the image regardless of the enabled preset, and each returns 200 when its extension is unconfigured, so curl -sf logs no failure. Two such entries were already present in the crontab for extensions absent from the preset, which settles the intent. documents/verify is treated as drift rather than a self hosted concession: the weekly cadence was present in the hosted crontab too, and the run is capped at 200 documents walking a nulls-first queue, so weekly drains the integrity queue seven times slower on a check that exists for BFL retention. webhooks/dispatch keeps its per minute cadence, adding 1,440 requests a day on self hosted. A gentler tick would silently stretch the first retry, since the retry ladder opens at 60 seconds. SCHEDULE_OVERRIDES is the one line place to change that. A parity test asserts the path sets match minus a documented exclusion list, and ratchets three cron routes that are currently scheduled nowhere so they are named rather than silently rotting. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * chore(observability): add a provider agnostic error sink There is no error tracking in this codebase: logs go to console and Vercel retention and nowhere else, nothing alerts on the 16 cron jobs, and seven code comments across lib, app, components and extensions asserted that Sentry captures errors when Sentry is not a dependency. The two most recent bug fixes on this repo were both discovered by customer email. This adds the sink, not a vendor. No dependency is taken: the interface has a no-op default and a registration point, so behaviour is unchanged until an adapter is registered. Releases are tagged from the build id already inlined by next.config.ts. Redaction moved out of lib/logger.ts into a leaf module that both the logger and the sink import, so there is one denylist and no path from application data to a third party can skip the personnummer regex, including direct sink calls that bypass the logger. That matters here because these logs carry personnummer and financial data. verifyCronSecret now reports its own 401s, which covers all 16 jobs without touching a route file and catches the case where CRON_SECRET is rotated without updating the scheduler and every job silently 401s forever. The threshold is one failure rather than the backup alert's three: suppressing the first occurrence is precisely how an outage stays invisible. The seven misleading comments are corrected to describe what the code actually does, including the two cases that still are not covered: the client side one, since the sink is server side, and a warn level call that is not forwarded. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * fix: remediate the 2026-07-26 similar-sweep findings across all surfaces Resolves the ~150-finding sweep (dev_docs/similar-sweep-2026-07-26.md) with one agent per finding; every behavioural fix carries a regression test proven to fail at HEAD. Full status, corrections to the sweep, refusals and open decisions in dev_docs/similar-sweep-2026-07-26-remediation-status.md. Structural roots closed: - resolveSekAmountOrNull(): honest SEK resolution refuses instead of booking 1:1; four duplicated toSek closures now refuse via INVOICE_FX_RATE_MISSING - ledger-line-amount.ts: journal_entry_lines.currency labels the document, not the amount; SQL pre-filter decoy proven and fixed - sparse-patch.ts: .partial() does not strip .default() in Zod 4.4.3; the exploitable salary payslip-line PATCH and KPI preferences sinks fixed - tests/schema: migration-replay phantom-column guard (13k+ refs, closed CHECK sets, onConflict targets); found 28 real defects, all fixed, all four baselines now empty - three new ratchet guards: sek-labelled-amount, cross-extension-import, ungated-extension-route Highlights: lawful VAT-rate set on all seven invoice surfaces (ML 6 kap), RC input VAT mismatch wired on web + both MCP callers, missing-underlag resource delegates to the shared RPC predicate, push-notifications consent polarity fail-closed, deadlines undo honours requested state, silent-failure and read-side-fabrication classes fixed across settings/KPI/inbox/Stripe/ Arcim/kassaflodesanalys, error-envelope stringification fixed at 10+ sites with isSwedishUserMessage extended. Also includes the parallel session's MCP invoice tools (update_invoice, recurring schedules, invoice deliveries) which share files with the sweep work and are verified green together. 13 new migrations are NOT applied anywhere; they apply via branch merge. 20260726120000 backfills 1247 supplier-invoice rows. pg tests for new DDL are written but unrun (no local Postgres). Verified: 11088 tests / 881 files green, tsc 0 non-test errors, lint 0 errors, check:guards passing, MCP payload 57475/57500. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(migrations): rename replace_sie_import migration off main's 20260726090000 version origin/main shipped 20260726090000_agent_quota_rpc_caller_guard.sql; keeping our replace_sie_import migration on the same version would abort the Supabase apply with a schema_migrations_pkey duplicate at merge time. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(review): remediate pre-publish deep-review findings across all slices A 13-agent review of the full branch diff surfaced 1 critical, 5 high and ~45 further findings; this commit resolves them in one pass: - replace_sie_import / undo_sie_import: p_user_id honored only for service_role callers; any other caller is pinned to auth.uid() (impersonation gate bypass), authz raise errcode 42501 mapped to a Swedish 403 in the route, new caller-guard migration for undo - bulk_book_transactions refuses homogeneous non-SEK batches instead of writing foreign magnitudes into SEK ledger columns - credit-note cap trigger: company-match on credited_invoice_id, no cross-tenant figures in exception text - link_voucher RPCs resolve NULL invoice currency as SEK end to end - personal-number ciphertext CHECK split into NOT VALID + VALIDATE - same-currency foreign settlements clear 1510 at booking rate and book realized diff to 3960/7960; rate-less foreign write paths refuse - receivables revaluation covers partially_paid and outstanding amounts - period lock guard paginates candidates past the PostgREST 1000 cap - documents: service-client storage removals after authz, dual-layout reads in integrity cron and archive export, backfill delete-source sweep actually deletes with hash verification and shared-key grouping - invoice matching normalizes NULL/lowercase currencies (regression), duplicate candidates stop claiming amount matches they never ran - match-invoice aborts on any booking failure (no paid-without-verifikat) - refresh-exchange-rate reverts on concurrent booking (TOCTOU window) - KPI preferences upsert arbiter aligned to the company-scoped constraint - personnummer_last4 stripped from all salary responses incl. MCP tools - worked-hours batch restores destroyed rows on conflict and error paths - MCP: shared duplicate-claim builder (no more 'null kr'), short-circuit on tag_journal_lines overflow, auto_send schedules stage as high risk - observability sink redacts emails/IBANs/API keys and keeps redacted stacks in prod; assorted small guards (safe-return-to /@, dry_run=True, cursor helper off-by-one, OAuth state TTL 10 min, arcim saveMappings call removed) Full dispositions, deferred items and hand-verified accounting numbers are documented in the PR body and DECISIONS.md. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat(personnummer): implement masking and encryption for personal numbers with tests * fix(review): address CI and compliance-bot findings for PR #1215 pg-real: the CI image's auth shim reads the legacy request.jwt.claim.role GUC, so both service-role simulations (runAsServiceRole and the invoice-delivery test's local helper) never satisfied auth.role() = 'service_role' and every legitimate p_user_id path failed closed; the shared helper now sets both GUC shapes plus SET LOCAL ROLE with a fail-loud sanity check, and the delivery test reuses it. The link-voucher migration had recreated both RPCs from pre-rewrite file text, reintroducing the NULL-unsafe membership pattern the null-safe-tenant-guards ratchet bans; both guards now use public.caller_is_company_member() with all currency changes preserved. Compliance bots: the customers export now emits the standard masked form instead of raw AES-256-GCM ciphertext in the Org-/personnummer column, and maskCustomerRow returns a non-round-trippable placeholder on decrypt failure instead of 500ing the list. MCP parity: gnubok_lock_period's staging pre-check now runs the exact countUnbookedInPeriod the commit path enforces (exported from period-service; local mirror deleted), and gnubok_agi_status resolves AGI state run-scoped so a correction run no longer renders as already filed. Declined with evidence: PR-Agent's opening-balances null-zeroing concern (all mergeable columns are NOT NULL with defaults per 20260713101000). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(review): address codex review findings on PR #1215 - restore 20260726140000 to its preview-recorded content and restate the NULL-safe tenant guard under 20260727130000: a recorded migration version never re-runs, so the in-place edit could not reach the preview branch - replace toFixed() with sv-SE two-decimal formatting in the ROT/RUT cap warning texts and update the pinned test expectations - drop the em dash in the fiscal-periods route comment - strip trailing whitespace in import-existing.test.ts Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * test(reports): raise timeout on real PDF render tests renderToBuffer does real @react-pdf layout work and exceeds the 5s default when the full suite saturates the CPU; tests pass in isolation. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(review): remediate the 2026-07-27 compliance and security review findings - ROT/RUT deduction base is arbetskostnaden INKLUSIVE moms (HUSFL 2009:194 6-9 par.): computeDeduction takes the line vat_rate, all five call sites pass it, and tests pin Skatteverkets worked example (18 000 kr excl = 22 500 incl, ROT 6 750). - Momsdeklaration: new SALES_OUTPUT_VAT_SHORTFALL warning catches output VAT short of the reported sales base (one-directional, never filing-blocking). - SIE import: #RAR records validated for every year index (dates, ordering, 18-month BFL cap as warn-and-keep). - build-invoice-write: SEK invoices populate the *_sek twin columns (rate 1) so both creation paths produce the same row shape. - CI: daily Trivy SCA scan of the npm lockfile (replaces removed Dependabot); compliance review fails loudly on empty review.md. - arcim migration FX logging routed through the redacting structured logger. - docs/security/: authorization policy for the SIE bulk-delete RPC pair and the observability redaction contract. - Rewrote the swedish-payroll ob-overtime reference (was a byte-identical copy of sick-pay.md); skills:generate emitted the atom-body seed migration. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Fable 5
parent
f24b26a139
commit
f3eacb436d
@@ -483,8 +483,10 @@ describe('createCreditNoteJournalEntry: per-line VAT', () => {
|
||||
})
|
||||
|
||||
it.each([
|
||||
['rot' as const, 3000, 9500],
|
||||
['rut' as const, 5000, 7500],
|
||||
// Deduction base is the line total INCL. VAT (HUSFL 6-9 §§):
|
||||
// rot 30% x 12 500 = 3 750, rut 50% x 12 500 = 6 250.
|
||||
['rot' as const, 3750, 8750],
|
||||
['rut' as const, 6250, 6250],
|
||||
])('reverses the %s receivable split across 1510 and 1513', async (deductionType, taxCredit, customerCredit) => {
|
||||
const creditNote = makeInvoice({
|
||||
invoice_number: 'KR-1002',
|
||||
@@ -794,8 +796,9 @@ describe('foreign currency without an exchange rate is refused, not relabelled',
|
||||
})
|
||||
|
||||
it('the ROT 1513 leg converts at the rate and the split still balances', async () => {
|
||||
// 1 000 EUR labour at 11,50 = 11 500 kr; ROT is 30% of labour = 3 450 kr on
|
||||
// 1513, so 1510 carries 14 375 - 3 450 = 10 925 kr.
|
||||
// 1 000 EUR labour + 25% VAT = 1 250 EUR incl. moms; ROT is 30% of the
|
||||
// inkl.-moms labour = 375 EUR = 4 312,50 kr at 11,50 on 1513, so 1510
|
||||
// carries 14 375 - 4 312,50 = 10 062,50 kr.
|
||||
const invoice = eurInvoiceWithoutRate({
|
||||
exchange_rate: 11.5,
|
||||
items: [
|
||||
@@ -814,8 +817,8 @@ describe('foreign currency without an exchange rate is refused, not relabelled',
|
||||
|
||||
const input = mockedCreateEntry.mock.calls[0][3]
|
||||
const debit1513 = input.lines.find((l) => l.account_number === '1513')
|
||||
expect(debit1513?.debit_amount).toBe(3450)
|
||||
expect(input.lines.find((l) => l.account_number === '1510')?.debit_amount).toBe(10925)
|
||||
expect(debit1513?.debit_amount).toBe(4312.5)
|
||||
expect(input.lines.find((l) => l.account_number === '1510')?.debit_amount).toBe(10062.5)
|
||||
|
||||
const totalDebit = input.lines.reduce((sum, l) => sum + l.debit_amount, 0)
|
||||
const totalCredit = input.lines.reduce((sum, l) => sum + l.credit_amount, 0)
|
||||
@@ -1263,9 +1266,10 @@ describe('createInvoiceJournalEntry: ROT/RUT-avdrag', () => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('single ROT line: 10 000 kr labor → 1513 debit 3 000, 1510 debit 7 000 + 2 500 VAT', async () => {
|
||||
// 10 000 kr labor with 25% VAT = 12 500 total. ROT = 30% of 10 000 = 3 000.
|
||||
// Customer owes (12 500 - 3 000) = 9 500. Skatteverket pays 3 000.
|
||||
it('single ROT line: 10 000 kr labor → 1513 debit 3 750, 1510 debit 8 750', async () => {
|
||||
// 10 000 kr labor with 25% VAT = 12 500 total. ROT = 30% of the
|
||||
// inkl.-moms labor (HUSFL 6-9 §§) = 30% of 12 500 = 3 750.
|
||||
// Customer owes (12 500 - 3 750) = 8 750. Skatteverket pays 3 750.
|
||||
const invoice = makeInvoice({
|
||||
subtotal: 10000,
|
||||
vat_amount: 2500,
|
||||
@@ -1289,14 +1293,14 @@ describe('createInvoiceJournalEntry: ROT/RUT-avdrag', () => {
|
||||
expect(mockedCreateEntry).toHaveBeenCalledOnce()
|
||||
const input = mockedCreateEntry.mock.calls[0][3]
|
||||
|
||||
// Lines: 1510 (debit 9500) + 1513 (debit 3000) + 3001 (credit 10000) + 2611 (credit 2500)
|
||||
// Lines: 1510 (debit 8750) + 1513 (debit 3750) + 3001 (credit 10000) + 2611 (credit 2500)
|
||||
expect(input.lines).toHaveLength(4)
|
||||
|
||||
const debit1510 = input.lines.find((l) => l.account_number === '1510')
|
||||
expect(debit1510?.debit_amount).toBe(9500)
|
||||
expect(debit1510?.debit_amount).toBe(8750)
|
||||
|
||||
const debit1513 = input.lines.find((l) => l.account_number === '1513')
|
||||
expect(debit1513?.debit_amount).toBe(3000)
|
||||
expect(debit1513?.debit_amount).toBe(3750)
|
||||
expect(debit1513?.credit_amount).toBe(0)
|
||||
|
||||
const credit3001 = input.lines.find((l) => l.account_number === '3001')
|
||||
@@ -1305,7 +1309,7 @@ describe('createInvoiceJournalEntry: ROT/RUT-avdrag', () => {
|
||||
const credit2611 = input.lines.find((l) => l.account_number === '2611')
|
||||
expect(credit2611?.credit_amount).toBe(2500)
|
||||
|
||||
// Balance: 9500 + 3000 = 12500 = 10000 + 2500
|
||||
// Balance: 8750 + 3750 = 12500 = 10000 + 2500
|
||||
const totalDebit = input.lines.reduce((sum, l) => sum + l.debit_amount, 0)
|
||||
const totalCredit = input.lines.reduce((sum, l) => sum + l.credit_amount, 0)
|
||||
expect(totalDebit).toBe(totalCredit)
|
||||
@@ -1313,8 +1317,9 @@ describe('createInvoiceJournalEntry: ROT/RUT-avdrag', () => {
|
||||
})
|
||||
|
||||
it('mixed invoice: ROT line + non-deduction line, per-item handling', async () => {
|
||||
// ROT line 10 000 (deduction 3 000) + non-deduction materials line 4 000.
|
||||
// Total 14 000 + 25% VAT = 17 500. Customer owes 14 500. Skatteverket 3 000.
|
||||
// ROT line 10 000 (deduction 30% of 12 500 inkl. moms = 3 750) +
|
||||
// non-deduction materials line 4 000.
|
||||
// Total 14 000 + 25% VAT = 17 500. Customer owes 13 750. Skatteverket 3 750.
|
||||
const invoice = makeInvoice({
|
||||
subtotal: 14000,
|
||||
vat_amount: 3500,
|
||||
@@ -1346,24 +1351,25 @@ describe('createInvoiceJournalEntry: ROT/RUT-avdrag', () => {
|
||||
|
||||
const input = mockedCreateEntry.mock.calls[0][3]
|
||||
|
||||
// Lines: 1510 (debit 14500) + 1513 (debit 3000) + 3001 (credit 14000) + 2611 (credit 3500)
|
||||
// Lines: 1510 (debit 13750) + 1513 (debit 3750) + 3001 (credit 14000) + 2611 (credit 3500)
|
||||
expect(input.lines).toHaveLength(4)
|
||||
|
||||
const debit1510 = input.lines.find((l) => l.account_number === '1510')
|
||||
expect(debit1510?.debit_amount).toBe(14500)
|
||||
expect(debit1510?.debit_amount).toBe(13750)
|
||||
|
||||
const debit1513 = input.lines.find((l) => l.account_number === '1513')
|
||||
expect(debit1513?.debit_amount).toBe(3000)
|
||||
expect(debit1513?.debit_amount).toBe(3750)
|
||||
|
||||
// Balance: 14500 + 3000 = 17500
|
||||
// Balance: 13750 + 3750 = 17500
|
||||
const totalDebit = input.lines.reduce((sum, l) => sum + l.debit_amount, 0)
|
||||
const totalCredit = input.lines.reduce((sum, l) => sum + l.credit_amount, 0)
|
||||
expect(totalDebit).toBe(totalCredit)
|
||||
expect(totalDebit).toBe(17500)
|
||||
})
|
||||
|
||||
it('RUT line with 50% rate: 5 000 kr → 1513 debit 2 500', async () => {
|
||||
// 5 000 labor with 25% VAT = 6 250 total. RUT = 50% of 5 000 = 2 500.
|
||||
it('RUT line with 50% rate: 5 000 kr → 1513 debit 3 125', async () => {
|
||||
// 5 000 labor with 25% VAT = 6 250 total. RUT = 50% of the inkl.-moms
|
||||
// labor = 50% of 6 250 = 3 125.
|
||||
const invoice = makeInvoice({
|
||||
subtotal: 5000,
|
||||
vat_amount: 1250,
|
||||
@@ -1387,11 +1393,11 @@ describe('createInvoiceJournalEntry: ROT/RUT-avdrag', () => {
|
||||
const input = mockedCreateEntry.mock.calls[0][3]
|
||||
|
||||
const debit1513 = input.lines.find((l) => l.account_number === '1513')
|
||||
expect(debit1513?.debit_amount).toBe(2500)
|
||||
expect(debit1513?.debit_amount).toBe(3125)
|
||||
expect(debit1513?.line_description).toMatch(/RUT/)
|
||||
|
||||
const debit1510 = input.lines.find((l) => l.account_number === '1510')
|
||||
expect(debit1510?.debit_amount).toBe(3750) // 6250 - 2500
|
||||
expect(debit1510?.debit_amount).toBe(3125) // 6250 - 3125
|
||||
|
||||
// Balance
|
||||
const totalDebit = input.lines.reduce((sum, l) => sum + l.debit_amount, 0)
|
||||
@@ -1419,7 +1425,8 @@ describe('createInvoiceJournalEntry: ROT/RUT-avdrag', () => {
|
||||
})
|
||||
|
||||
it('two ROT lines: per-line 1513 debits sum to invoice deduction total', async () => {
|
||||
// 6 000 + 4 000 labor, both ROT 30% → 1 800 + 1 200 = 3 000 total.
|
||||
// 6 000 + 4 000 labor @ 25%, both ROT 30% of the inkl.-moms line:
|
||||
// 30% x 7 500 + 30% x 5 000 = 2 250 + 1 500 = 3 750 total.
|
||||
const invoice = makeInvoice({
|
||||
subtotal: 10000,
|
||||
vat_amount: 2500,
|
||||
@@ -1455,10 +1462,10 @@ describe('createInvoiceJournalEntry: ROT/RUT-avdrag', () => {
|
||||
const debit1513Lines = input.lines.filter((l) => l.account_number === '1513')
|
||||
expect(debit1513Lines).toHaveLength(2)
|
||||
const total1513 = debit1513Lines.reduce((sum, l) => sum + l.debit_amount, 0)
|
||||
expect(total1513).toBe(3000)
|
||||
expect(total1513).toBe(3750)
|
||||
|
||||
const debit1510 = input.lines.find((l) => l.account_number === '1510')
|
||||
expect(debit1510?.debit_amount).toBe(9500) // 12500 - 3000
|
||||
expect(debit1510?.debit_amount).toBe(8750) // 12500 - 3750
|
||||
|
||||
// Balance
|
||||
const totalDebit = input.lines.reduce((sum, l) => sum + l.debit_amount, 0)
|
||||
@@ -1586,7 +1593,7 @@ describe('dimensions propagation (PR7): createInvoiceJournalEntry', () => {
|
||||
const input = mockedCreateEntry.mock.calls[0][3]
|
||||
|
||||
const debit1513 = input.lines.find((l) => l.account_number === '1513')
|
||||
expect(debit1513?.debit_amount).toBe(3000)
|
||||
expect(debit1513?.debit_amount).toBe(3750)
|
||||
expect(debit1513?.dimensions).toEqual({ '1': 'KS01', '6': 'P001' })
|
||||
|
||||
// 1510 still carries the default only.
|
||||
@@ -1808,10 +1815,10 @@ describe('createInvoiceCashEntry: ROT/RUT-avdrag', () => {
|
||||
const input = mockedCreateEntry.mock.calls[0][3]
|
||||
|
||||
const debit1930 = input.lines.find((l) => l.account_number === '1930')
|
||||
expect(debit1930?.debit_amount).toBe(9500)
|
||||
expect(debit1930?.debit_amount).toBe(8750)
|
||||
|
||||
const debit1513 = input.lines.find((l) => l.account_number === '1513')
|
||||
expect(debit1513?.debit_amount).toBe(3000)
|
||||
expect(debit1513?.debit_amount).toBe(3750)
|
||||
|
||||
// Balance
|
||||
const totalDebit = input.lines.reduce((sum, l) => sum + l.debit_amount, 0)
|
||||
@@ -1847,13 +1854,13 @@ describe('createInvoiceCashEntry: ROT/RUT-avdrag', () => {
|
||||
|
||||
// The bank leg follows the resolved paymentAccount, still reduced by the deduction.
|
||||
const debit1940 = input.lines.find((l) => l.account_number === '1940')
|
||||
expect(debit1940?.debit_amount).toBe(9500)
|
||||
expect(debit1940?.debit_amount).toBe(8750)
|
||||
expect(input.lines.find((l) => l.account_number === '1930')).toBeUndefined()
|
||||
|
||||
// The ROT/RUT receivable from Skatteverket is never the bank leg, so it
|
||||
// must stay on 1513 regardless of paymentAccount.
|
||||
const debit1513NonDefault = input.lines.find((l) => l.account_number === '1513')
|
||||
expect(debit1513NonDefault?.debit_amount).toBe(3000)
|
||||
expect(debit1513NonDefault?.debit_amount).toBe(3750)
|
||||
|
||||
// Balance
|
||||
const totalDebit = input.lines.reduce((sum, l) => sum + l.debit_amount, 0)
|
||||
|
||||
@@ -227,8 +227,9 @@ describe('proposeSendLines', () => {
|
||||
entityType: 'enskild_firma',
|
||||
})
|
||||
|
||||
expect(lines.find((line) => line.account_number === '1510')?.credit_amount).toBe('9500')
|
||||
expect(lines.find((line) => line.account_number === '1513')?.credit_amount).toBe('3000')
|
||||
// ROT is 30% of the line total incl. moms (HUSFL 6-9 §§): 30% x 12 500 = 3 750.
|
||||
expect(lines.find((line) => line.account_number === '1510')?.credit_amount).toBe('8750')
|
||||
expect(lines.find((line) => line.account_number === '1513')?.credit_amount).toBe('3750')
|
||||
expect(lines.reduce((sum, line) => sum + (parseFloat(line.debit_amount) || 0), 0))
|
||||
.toBe(12500)
|
||||
expect(lines.reduce((sum, line) => sum + (parseFloat(line.credit_amount) || 0), 0))
|
||||
|
||||
@@ -359,6 +359,7 @@ function generateRotRutLines(
|
||||
unit_price: side === 'credit' ? Math.abs(item.unit_price) : item.unit_price,
|
||||
quantity: side === 'credit' ? Math.abs(item.quantity) : item.quantity,
|
||||
deduction_type: item.deduction_type,
|
||||
vat_rate: item.vat_rate,
|
||||
})
|
||||
if (amount <= 0) continue
|
||||
const amountSek = Math.round(toSek(amount) * 100) / 100
|
||||
|
||||
@@ -246,6 +246,7 @@ function buildSendLines(
|
||||
unit_price: item.unit_price,
|
||||
quantity: item.quantity,
|
||||
deduction_type: item.deduction_type,
|
||||
vat_rate: item.vat_rate,
|
||||
})
|
||||
const amountSek = roundOre(toSek(deduction))
|
||||
if (amountSek <= 0) continue
|
||||
|
||||
@@ -1463,3 +1463,89 @@ describe('getEffectiveOpeningBalances: derive IB from #UB -1 (issue #675)', () =
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
// --- #RAR validation: prior-year records and malformed indexes ---
|
||||
//
|
||||
// The 18-month BFL 3 kap. cap is enforced as a hard refusal for #RAR 0 at
|
||||
// import time (ensureFiscalPeriod). The parser layer validates EVERY #RAR
|
||||
// record, including prior years (-1, -2, ...): malformed records (bad index,
|
||||
// invalid dates, reversed dates) are reported and skipped, an over-long span
|
||||
// is reported as a warning but kept so the import layer's precise error for
|
||||
// year 0 still sees the real dates.
|
||||
|
||||
describe('parseSIEFile: #RAR record validation', () => {
|
||||
const HEADER = ['#FLAGGA 0', '#SIETYP 4', '#FNAMN "Test AB"']
|
||||
|
||||
it('keeps parsing a well-formed multi-year file exactly as before', () => {
|
||||
const content = [
|
||||
...HEADER,
|
||||
'#RAR 0 20240101 20241231',
|
||||
'#RAR -1 20230101 20231231',
|
||||
'#RAR -2 20220101 20221231',
|
||||
].join('\n')
|
||||
|
||||
const result = parseSIEFile(content)
|
||||
expect(result.header.fiscalYears).toHaveLength(3)
|
||||
expect(result.header.fiscalYears.map((fy) => fy.yearIndex)).toEqual([0, -1, -2])
|
||||
expect(result.header.fiscalYears[1].start).toBe('2023-01-01')
|
||||
expect(result.header.fiscalYears[1].end).toBe('2023-12-31')
|
||||
expect(result.issues.filter((i) => i.tag === 'RAR')).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('accepts an 18-month förlängt räkenskapsår without warnings', () => {
|
||||
const content = [...HEADER, '#RAR 0 20230701 20241231'].join('\n')
|
||||
|
||||
const result = parseSIEFile(content)
|
||||
expect(result.header.fiscalYears).toHaveLength(1)
|
||||
expect(result.issues.filter((i) => i.tag === 'RAR')).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('skips a #RAR record whose year index does not parse to an integer', () => {
|
||||
const content = [...HEADER, '#RAR 0 20240101 20241231', '#RAR abc 20230101 20231231'].join('\n')
|
||||
|
||||
const result = parseSIEFile(content)
|
||||
expect(result.header.fiscalYears).toHaveLength(1)
|
||||
expect(result.header.fiscalYears[0].yearIndex).toBe(0)
|
||||
expect(result.issues.some((i) => i.message.includes('Ogiltigt årsindex'))).toBe(true)
|
||||
})
|
||||
|
||||
it('skips a prior-year #RAR with an invalid calendar date', () => {
|
||||
const content = [...HEADER, '#RAR 0 20240101 20241231', '#RAR -1 20230101 20230230'].join('\n')
|
||||
|
||||
const result = parseSIEFile(content)
|
||||
expect(result.header.fiscalYears).toHaveLength(1)
|
||||
expect(result.issues.some((i) => i.message.includes('Invalid fiscal year dates'))).toBe(true)
|
||||
})
|
||||
|
||||
it('skips a prior-year #RAR whose end date precedes its start date', () => {
|
||||
const content = [...HEADER, '#RAR 0 20240101 20241231', '#RAR -1 20231231 20230101'].join('\n')
|
||||
|
||||
const result = parseSIEFile(content)
|
||||
expect(result.header.fiscalYears).toHaveLength(1)
|
||||
expect(
|
||||
result.issues.some((i) => i.message.includes('ligger före startdatumet'))
|
||||
).toBe(true)
|
||||
})
|
||||
|
||||
it('warns about a 24-month prior-year #RAR but keeps the record', () => {
|
||||
const content = [...HEADER, '#RAR 0 20240101 20241231', '#RAR -1 20220101 20231231'].join('\n')
|
||||
|
||||
const result = parseSIEFile(content)
|
||||
expect(result.header.fiscalYears).toHaveLength(2)
|
||||
expect(
|
||||
result.issues.some(
|
||||
(i) => i.message.includes('24 månader') && i.message.includes('BFL 3 kap.')
|
||||
)
|
||||
).toBe(true)
|
||||
})
|
||||
|
||||
it('warns about an over-long current-year #RAR but keeps the record for the import-layer refusal', () => {
|
||||
const content = [...HEADER, '#RAR 0 20230101 20241231'].join('\n')
|
||||
|
||||
const result = parseSIEFile(content)
|
||||
expect(result.header.fiscalYears).toHaveLength(1)
|
||||
expect(result.header.fiscalYears[0].start).toBe('2023-01-01')
|
||||
expect(result.header.fiscalYears[0].end).toBe('2024-12-31')
|
||||
expect(result.issues.some((i) => i.message.includes('högst 18 månader'))).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -10,6 +10,7 @@
|
||||
* Reference: https://sie.se/format/
|
||||
*/
|
||||
|
||||
import { monthsBetween } from '@/lib/bookkeeping/validate-period-duration'
|
||||
import type {
|
||||
SIEType,
|
||||
SIEEncoding,
|
||||
@@ -524,15 +525,54 @@ export function parseSIEFile(content: string): ParsedSIEFile {
|
||||
|
||||
case 'RAR': {
|
||||
// #RAR yearIndex start end
|
||||
//
|
||||
// Validated for EVERY year index, not just 0: prior-year records
|
||||
// (#RAR -1, -2, ...) land in header.fiscalYears too, and a bogus
|
||||
// entry there used to pass through silently. Malformed records are
|
||||
// reported and skipped so fiscalYears never carries an entry the
|
||||
// rest of the pipeline cannot trust. The one exception is the
|
||||
// 18-month BFL 3 kap. cap: an over-long span is reported as a
|
||||
// warning but the entry is KEPT, because executeSIEImport refuses
|
||||
// the current year (#RAR 0) with a precise Swedish error that needs
|
||||
// the real dates, and dropping the record here would degrade that
|
||||
// message to "no fiscal year defined".
|
||||
const yearIndex = parseInt(fields[1], 10)
|
||||
const start = parseSIEDateString(fields[2])
|
||||
const end = parseSIEDateString(fields[3])
|
||||
|
||||
if (start && end) {
|
||||
header.fiscalYears.push({ yearIndex, start, end })
|
||||
} else {
|
||||
addIssue(issues, 'warning', lineNum, 'Invalid fiscal year dates', tag)
|
||||
if (!Number.isInteger(yearIndex)) {
|
||||
addIssue(issues, 'warning', lineNum, `Ogiltigt årsindex i #RAR: "${fields[1] ?? ''}"`, tag)
|
||||
break
|
||||
}
|
||||
|
||||
if (!start || !end) {
|
||||
addIssue(issues, 'warning', lineNum, 'Invalid fiscal year dates', tag)
|
||||
break
|
||||
}
|
||||
|
||||
if (end < start) {
|
||||
addIssue(
|
||||
issues,
|
||||
'warning',
|
||||
lineNum,
|
||||
`Räkenskapsårets slutdatum (${end}) ligger före startdatumet (${start}) i #RAR ${yearIndex}`,
|
||||
tag
|
||||
)
|
||||
break
|
||||
}
|
||||
|
||||
const rarMonths = monthsBetween(start, end)
|
||||
if (rarMonths > 18) {
|
||||
addIssue(
|
||||
issues,
|
||||
'warning',
|
||||
lineNum,
|
||||
`Räkenskapsåret i #RAR ${yearIndex} (${start} till ${end}) omfattar ${rarMonths} månader: ett räkenskapsår får vara högst 18 månader (BFL 3 kap.)`,
|
||||
tag
|
||||
)
|
||||
}
|
||||
|
||||
header.fiscalYears.push({ yearIndex, start, end })
|
||||
break
|
||||
}
|
||||
|
||||
|
||||
@@ -203,4 +203,46 @@ describe('buildInvoiceWriteData exchange rate', () => {
|
||||
expect(queries.some((q) => q.table === 'exchange_rates')).toBe(false)
|
||||
expect(fetchMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('populates the SEK twin columns for a SEK invoice instead of leaving them NULL', async () => {
|
||||
const fetchMock = vi.fn()
|
||||
vi.stubGlobal('fetch', fetchMock)
|
||||
|
||||
const { supabase } = createRecordingSupabase((q) => {
|
||||
if (q.table === 'company_settings') return { data: { vat_registered: true }, error: null }
|
||||
return { data: null, error: null }
|
||||
})
|
||||
|
||||
const result = await build(supabase, { currency: 'SEK' })
|
||||
|
||||
expect(result.ok).toBe(true)
|
||||
if (!result.ok) return
|
||||
// The staged-operations commit path writes total_sek = total for SEK
|
||||
// invoices (sekRate = 1); the web/REST path must produce the same row or
|
||||
// the SEK-reporting readers see two different shapes for the same invoice.
|
||||
expect(result.invoiceFields.exchange_rate).toBeNull()
|
||||
expect(result.invoiceFields.subtotal_sek).toBe(1000)
|
||||
expect(result.invoiceFields.vat_amount_sek).toBe(0)
|
||||
expect(result.invoiceFields.total_sek).toBe(1000)
|
||||
})
|
||||
|
||||
it('rounds the SEK twins to the ore for a SEK invoice with float-dust line math', async () => {
|
||||
const fetchMock = vi.fn()
|
||||
vi.stubGlobal('fetch', fetchMock)
|
||||
|
||||
const { supabase } = createRecordingSupabase((q) => {
|
||||
if (q.table === 'company_settings') return { data: { vat_registered: true }, error: null }
|
||||
return { data: null, error: null }
|
||||
})
|
||||
|
||||
const result = await build(supabase, {
|
||||
currency: 'SEK',
|
||||
items: [{ description: 'Konsult', quantity: 3, unit: 'tim', unit_price: 33.33, vat_rate: 0 }],
|
||||
})
|
||||
|
||||
expect(result.ok).toBe(true)
|
||||
if (!result.ok) return
|
||||
expect(result.invoiceFields.subtotal_sek).toBe(99.99)
|
||||
expect(result.invoiceFields.total_sek).toBe(99.99)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -278,16 +278,17 @@ describe('foreign-currency invoices: kronor conversion', () => {
|
||||
}
|
||||
|
||||
it('emits SEK whole kronor for a 3 000 EUR rot invoice', () => {
|
||||
// 3 000 EUR arbete + 750 EUR moms, 900 EUR avdrag, rate 11,40:
|
||||
// PrisForArbete 34 200 + 8 550 = 42 750 kr
|
||||
// BegartBelopp 900 × 11,40 = 10 260 kr
|
||||
// BetaltBelopp 42 750 - 10 260 = 32 490 kr
|
||||
// 3 000 EUR arbete + 750 EUR moms = 3 750 EUR inkl. moms; avdrag 30% av
|
||||
// inkl.-moms-arbetet = 1 125 EUR (HUSFL 6-9 §§), rate 11,40:
|
||||
// PrisForArbete 34 200 + 8 550 = 42 750 kr
|
||||
// BegartBelopp 1 125 × 11,40 = 12 825 kr
|
||||
// BetaltBelopp 42 750 - 12 825 = 29 925 kr
|
||||
const invoice = makeEurRotInvoice({
|
||||
unit_price: 3000,
|
||||
quantity: 1,
|
||||
line_total: 3000,
|
||||
vat_amount: 750,
|
||||
deduction_amount: 900,
|
||||
deduction_amount: 1125,
|
||||
labor_hours: 10,
|
||||
})
|
||||
|
||||
@@ -296,23 +297,25 @@ describe('foreign-currency invoices: kronor conversion', () => {
|
||||
|
||||
const xml = result.xml!
|
||||
expect(xml).toContain('<ns2:PrisForArbete>42750</ns2:PrisForArbete>')
|
||||
expect(xml).toContain('<ns2:BegartBelopp>10260</ns2:BegartBelopp>')
|
||||
expect(xml).toContain('<ns2:BetaltBelopp>32490</ns2:BetaltBelopp>')
|
||||
expect(result.requested_total).toBe(10260)
|
||||
expect(xml).toContain('<ns2:BegartBelopp>12825</ns2:BegartBelopp>')
|
||||
expect(xml).toContain('<ns2:BetaltBelopp>29925</ns2:BetaltBelopp>')
|
||||
expect(result.requested_total).toBe(12825)
|
||||
|
||||
// The begäran and the receivable must be the same claim.
|
||||
expect(result.arenden[0].begart_belopp).toBe(Math.round(ledger1513(invoice)))
|
||||
})
|
||||
|
||||
it('asks for 7 125 kr, not 625, on the 625 EUR deduction case', () => {
|
||||
// The bug this test pins: 625 EUR avdrag booked to 1513 as 7 125 kr while
|
||||
// the begäran asked Skatteverket for "625" (read as kronor).
|
||||
it('asks for 8 906 kr, not 781, on the 781.25 EUR deduction case', () => {
|
||||
// The bug this test pins: a EUR avdrag booked to 1513 in kronor while
|
||||
// the begäran asked Skatteverket for the raw EUR figure (read as kronor).
|
||||
// 2 083,33 EUR arbete + 520,83 moms = 2 604,16 inkl.; 30% = 781,25 EUR
|
||||
// = 8 906,25 kr at 11,40, whole-kronor 8 906 in the file.
|
||||
const invoice = makeEurRotInvoice({
|
||||
unit_price: 2083.33,
|
||||
quantity: 1,
|
||||
line_total: 2083.33,
|
||||
vat_amount: 520.83,
|
||||
deduction_amount: 625,
|
||||
deduction_amount: 781.25,
|
||||
labor_hours: 8,
|
||||
})
|
||||
|
||||
@@ -320,10 +323,10 @@ describe('foreign-currency invoices: kronor conversion', () => {
|
||||
expect(result.blockers).toHaveLength(0)
|
||||
|
||||
const xml = result.xml!
|
||||
expect(xml).toContain('<ns2:BegartBelopp>7125</ns2:BegartBelopp>')
|
||||
expect(xml).not.toContain('<ns2:BegartBelopp>625</ns2:BegartBelopp>')
|
||||
expect(ledger1513(invoice)).toBe(7125)
|
||||
expect(result.arenden[0].begart_belopp).toBe(7125)
|
||||
expect(xml).toContain('<ns2:BegartBelopp>8906</ns2:BegartBelopp>')
|
||||
expect(xml).not.toContain('<ns2:BegartBelopp>781</ns2:BegartBelopp>')
|
||||
expect(ledger1513(invoice)).toBe(8906.25)
|
||||
expect(result.arenden[0].begart_belopp).toBe(8906)
|
||||
})
|
||||
|
||||
it('MISSING_EXCHANGE_RATE rather than a guessed figure when the rate is absent', () => {
|
||||
|
||||
@@ -101,7 +101,77 @@ describe('computeDeduction', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('computeDeduction: base is labor cost INCLUDING VAT (HUSFL 6-9 §§)', () => {
|
||||
it('Skatteverket worked example: 18 000 kr arbetskostnad @ 25% = 22 500 inkl. moms, ROT 30% = 6 750', () => {
|
||||
const item: ItemForDeduction = {
|
||||
unit_price: 18000,
|
||||
quantity: 1,
|
||||
deduction_type: 'rot',
|
||||
vat_rate: 25,
|
||||
}
|
||||
expect(computeDeduction(item)).toBe(6750)
|
||||
})
|
||||
|
||||
it('RUT 50% of labor incl. moms: 1 000 kr @ 25% = 1 250 → 625', () => {
|
||||
const item: ItemForDeduction = {
|
||||
unit_price: 1000,
|
||||
quantity: 1,
|
||||
deduction_type: 'rut',
|
||||
vat_rate: 25,
|
||||
}
|
||||
expect(computeDeduction(item)).toBe(625)
|
||||
})
|
||||
|
||||
it('respects the line rate: 1 000 kr @ 12% = 1 120 → ROT 336', () => {
|
||||
const item: ItemForDeduction = {
|
||||
unit_price: 1000,
|
||||
quantity: 1,
|
||||
deduction_type: 'rot',
|
||||
vat_rate: 12,
|
||||
}
|
||||
expect(computeDeduction(item)).toBe(336)
|
||||
})
|
||||
|
||||
it('vat_rate 0, null and undefined all mean momsfri labor (base = line total)', () => {
|
||||
const base: ItemForDeduction = { unit_price: 10000, quantity: 1, deduction_type: 'rot' }
|
||||
expect(computeDeduction({ ...base, vat_rate: 0 })).toBe(3000)
|
||||
expect(computeDeduction({ ...base, vat_rate: null })).toBe(3000)
|
||||
expect(computeDeduction(base)).toBe(3000)
|
||||
})
|
||||
|
||||
it('reproduces the stored per-line vat_amount rounding before applying the percent', () => {
|
||||
// 333.33 @ 25%: stored vat_amount = round2(83.3325) = 83.33, so the base
|
||||
// is 416.66 (not 416.6625) and RUT 50% = 208.33.
|
||||
const item: ItemForDeduction = {
|
||||
unit_price: 333.33,
|
||||
quantity: 1,
|
||||
deduction_type: 'rut',
|
||||
vat_rate: 25,
|
||||
}
|
||||
expect(computeDeduction(item)).toBe(208.33)
|
||||
})
|
||||
|
||||
it('quantity > 1 with VAT: 20 × 500 kr @ 25% = 12 500 inkl. → ROT 3 750', () => {
|
||||
const item: ItemForDeduction = {
|
||||
unit_price: 500,
|
||||
quantity: 20,
|
||||
deduction_type: 'rot',
|
||||
vat_rate: 25,
|
||||
}
|
||||
expect(computeDeduction(item)).toBe(3750)
|
||||
})
|
||||
})
|
||||
|
||||
describe('computeInvoiceDeductionTotal', () => {
|
||||
it('sums on the inkl.-moms base when rates are present', () => {
|
||||
const items: ItemForDeduction[] = [
|
||||
{ unit_price: 18000, quantity: 1, deduction_type: 'rot', vat_rate: 25 }, // 6 750
|
||||
{ unit_price: 1000, quantity: 1, deduction_type: 'rut', vat_rate: 25 }, // 625
|
||||
{ unit_price: 2000, quantity: 1, vat_rate: 25 }, // not flagged
|
||||
]
|
||||
expect(computeInvoiceDeductionTotal(items)).toBe(7375)
|
||||
})
|
||||
|
||||
it('mixed: ROT line + non-eligible line: only ROT generates deduction', () => {
|
||||
const items: ItemForDeduction[] = [
|
||||
{ unit_price: 10000, quantity: 1, deduction_type: 'rot' },
|
||||
|
||||
@@ -329,6 +329,10 @@ export async function buildInvoiceWriteData(params: {
|
||||
unit_price: item.unit_price,
|
||||
quantity: item.quantity,
|
||||
deduction_type: item.deduction_type ?? null,
|
||||
// The deduction base is arbetskostnaden inkl. moms (HUSFL 6-9 §§), so
|
||||
// the validator and total need the same per-line rate the item rows
|
||||
// below are stored with.
|
||||
vat_rate: item.vat_rate !== undefined ? item.vat_rate : vatRules.rate,
|
||||
labor_hours: item.labor_hours ?? null,
|
||||
housing_designation: item.housing_designation ?? null,
|
||||
}))
|
||||
@@ -433,6 +437,17 @@ export async function buildInvoiceWriteData(params: {
|
||||
vatAmountSek = convertToSEK(vatAmount, exchangeRate)
|
||||
totalSek = convertToSEK(total, exchangeRate)
|
||||
}
|
||||
} else {
|
||||
// SEK invoice: the *_sek twins equal their invoice-currency counterparts
|
||||
// (rate 1) instead of staying NULL. The staged-operations commit path
|
||||
// (lib/pending-operations/commit.ts, sekRate = 1) already writes them this
|
||||
// way, and leaving them NULL here made the same invoice row differ by
|
||||
// creation path, blanking SEK-reporting readers (KPI, AR ledger, full
|
||||
// archive export). A failed Riksbanken fetch on a foreign-currency
|
||||
// invoice still stores NULL above: that is a genuinely unknown value.
|
||||
subtotalSek = Math.round(subtotal * 100) / 100
|
||||
vatAmountSek = Math.round(vatAmount * 100) / 100
|
||||
totalSek = Math.round(total * 100) / 100
|
||||
}
|
||||
|
||||
const invoiceFields: InvoiceWriteFields = {
|
||||
@@ -519,6 +534,7 @@ export async function buildInvoiceWriteData(params: {
|
||||
unit_price: item.unit_price,
|
||||
quantity: item.quantity,
|
||||
deduction_type: deductionType,
|
||||
vat_rate: itemRate,
|
||||
})
|
||||
: 0
|
||||
return {
|
||||
|
||||
@@ -3,8 +3,14 @@
|
||||
*
|
||||
* Implements the calculation and validation logic for Sweden's tax deduction
|
||||
* for household services (RUT) and home renovation (ROT). As of 2026:
|
||||
* - ROT: 30% of labor cost, max 50 000 kr per person per year.
|
||||
* - RUT: 50% of labor cost, max 75 000 kr per person per year.
|
||||
* - ROT: 30% of labor cost INCLUDING VAT, max 50 000 kr per person per year.
|
||||
* - RUT: 50% of labor cost INCLUDING VAT, max 75 000 kr per person per year.
|
||||
*
|
||||
* The base is arbetskostnaden inklusive moms per HUSFL (2009:194) 6-9 §§:
|
||||
* Skatteverkets own worked example is 18 000 kr arbetskostnad = 22 500 kr
|
||||
* inkl. moms (25%), ROT 30% = 6 750 kr. Callers must therefore pass the
|
||||
* line's VAT rate; a missing/null rate is treated as 0% (momsfri labor),
|
||||
* where inkl. and exkl. coincide.
|
||||
*
|
||||
* The deduction applies to labor only: material costs and travel time are
|
||||
* NOT eligible. In this v1 we treat the entire invoice item amount as labor
|
||||
@@ -134,6 +140,13 @@ export interface ItemForDeduction {
|
||||
quantity: number
|
||||
/** 'rot' | 'rut' | null. Drives whether the deduction kicks in at all. */
|
||||
deduction_type?: DeductionType | null
|
||||
/**
|
||||
* The line's VAT rate in percent (25, 12, 6, 0). The statutory deduction
|
||||
* base is the labor cost INCLUDING VAT (HUSFL 6-9 §§), so every caller
|
||||
* that knows the rate must pass it. null/undefined means 0% (momsfri
|
||||
* labor), where inkl. and exkl. moms coincide.
|
||||
*/
|
||||
vat_rate?: number | null
|
||||
/**
|
||||
* Optional. Reserved for a future iteration where the eligible portion of
|
||||
* the row is just the labor hours × hourly rate. v1 ignores this and
|
||||
@@ -145,18 +158,27 @@ export interface ItemForDeduction {
|
||||
|
||||
/**
|
||||
* Compute the deduction amount for a single invoice item. Returns 0 when
|
||||
* the item has no deduction_type. The result is always >= 0 and <= line
|
||||
* total (no over-deduction even if percentages are tweaked).
|
||||
* the item has no deduction_type. The base is the line total INCLUDING VAT
|
||||
* (HUSFL 6-9 §§: 30% av arbetskostnaden inklusive moms for ROT, 50% for
|
||||
* RUT). The per-line VAT is reproduced with the exact rounding the write
|
||||
* path stores on invoice_items.vat_amount (Math.round(lineTotal * rate /
|
||||
* 100 * 100) / 100 in build-invoice-write.ts), so the deduction and the
|
||||
* stored VAT can never disagree by an öre. The result is always >= 0 and
|
||||
* <= line total incl. VAT (no over-deduction even if percentages are
|
||||
* tweaked).
|
||||
*/
|
||||
export function computeDeduction(item: ItemForDeduction): number {
|
||||
if (!item.deduction_type) return 0
|
||||
const lineTotal = item.unit_price * item.quantity
|
||||
if (lineTotal <= 0) return 0
|
||||
const rate = item.vat_rate ?? 0
|
||||
const lineVat = rate > 0 ? Math.round(lineTotal * rate / 100 * 100) / 100 : 0
|
||||
const lineTotalInclVat = lineTotal + lineVat
|
||||
const percent = item.deduction_type === 'rot' ? ROT_PERCENT : RUT_PERCENT
|
||||
const raw = lineTotal * percent
|
||||
// Cap at line total: defensive against future rule changes that would
|
||||
// push percent past 1.0.
|
||||
const capped = Math.min(raw, lineTotal)
|
||||
const raw = lineTotalInclVat * percent
|
||||
// Cap at line total incl. VAT: defensive against future rule changes that
|
||||
// would push percent past 1.0.
|
||||
const capped = Math.min(raw, lineTotalInclVat)
|
||||
return Math.round(capped * 100) / 100
|
||||
}
|
||||
|
||||
|
||||
@@ -317,6 +317,101 @@ describe('runVatDeclarationChecks', () => {
|
||||
}
|
||||
const findings = runVatDeclarationChecks(rutor)
|
||||
expect(findings.find((f) => f.code === 'TAXABLE_SALES_WITHOUT_OUTPUT')).toBeUndefined()
|
||||
expect(findings.find((f) => f.code === 'SALES_OUTPUT_VAT_SHORTFALL')).toBeUndefined()
|
||||
})
|
||||
|
||||
// Regression (2026-07-27): the binary sales check cleared as soon as ANY
|
||||
// output VAT existed, so 2 000 kr of missing utgående moms on a 400 000 kr
|
||||
// base rendered "Inga fel hittades" with Skicka enabled. The proportional
|
||||
// form warns (never blocks: periodisering legitimately drifts this way).
|
||||
describe('SALES_OUTPUT_VAT_SHORTFALL (proportional, warning tier)', () => {
|
||||
it('warns when the sales base implies more output VAT than declared', () => {
|
||||
const rutor: VatDeclarationRutor = {
|
||||
...emptyRutor,
|
||||
ruta05: 400000,
|
||||
ruta10: 98000, // 100 000 kr expected at 25%: 2 000 kr moms missing
|
||||
ruta49: 98000,
|
||||
}
|
||||
const findings = runVatDeclarationChecks(rutor)
|
||||
const finding = findings.find((f) => f.code === 'SALES_OUTPUT_VAT_SHORTFALL')
|
||||
expect(finding?.status).toBe('WARNING')
|
||||
expect(finding?.message).toMatch(/saknar/)
|
||||
expect(finding?.message).toMatch(/periodisering/)
|
||||
// Never a filing blocker: no ERROR may fire on this declaration, so
|
||||
// isFilingBlocked (ERROR-only) keeps Skicka enabled while the banner
|
||||
// stops claiming "Inga fel hittades".
|
||||
expect(findings.find((f) => f.code === 'TAXABLE_SALES_WITHOUT_OUTPUT')).toBeUndefined()
|
||||
expect(findings.every((f) => f.status === 'WARNING')).toBe(true)
|
||||
})
|
||||
|
||||
it('stays green for an exact mixed-rate declaration', () => {
|
||||
const rutor: VatDeclarationRutor = {
|
||||
...emptyRutor,
|
||||
ruta05: 170000, // 100 000 @25% + 50 000 @12% + 20 000 @6%
|
||||
ruta10: 25000,
|
||||
ruta11: 6000,
|
||||
ruta12: 1200,
|
||||
ruta49: 32200,
|
||||
}
|
||||
expect(runVatDeclarationChecks(rutor)).toEqual([])
|
||||
})
|
||||
|
||||
it('absorbs drift inside the 0.5% tolerance', () => {
|
||||
const rutor: VatDeclarationRutor = {
|
||||
...emptyRutor,
|
||||
ruta05: 100040, // implied base 100 000, tolerance 500
|
||||
ruta10: 25000,
|
||||
ruta49: 25000,
|
||||
}
|
||||
expect(
|
||||
runVatDeclarationChecks(rutor).find((f) => f.code === 'SALES_OUTPUT_VAT_SHORTFALL'),
|
||||
).toBeUndefined()
|
||||
})
|
||||
|
||||
it('warns just outside the 0.5% tolerance', () => {
|
||||
const rutor: VatDeclarationRutor = {
|
||||
...emptyRutor,
|
||||
ruta05: 100600, // implied base 100 000, tolerance 500
|
||||
ruta10: 25000,
|
||||
ruta49: 25000,
|
||||
}
|
||||
expect(
|
||||
runVatDeclarationChecks(rutor).find((f) => f.code === 'SALES_OUTPUT_VAT_SHORTFALL')?.status,
|
||||
).toBe('WARNING')
|
||||
})
|
||||
|
||||
it('applies the 1 kr tolerance floor at a small base', () => {
|
||||
const inside: VatDeclarationRutor = {
|
||||
...emptyRutor,
|
||||
ruta05: 100.8, // implied 100, floor tolerance 1 kr
|
||||
ruta10: 25,
|
||||
ruta49: 25,
|
||||
}
|
||||
expect(
|
||||
runVatDeclarationChecks(inside).find((f) => f.code === 'SALES_OUTPUT_VAT_SHORTFALL'),
|
||||
).toBeUndefined()
|
||||
|
||||
const outside: VatDeclarationRutor = {
|
||||
...emptyRutor,
|
||||
ruta05: 104,
|
||||
ruta10: 25,
|
||||
ruta49: 25,
|
||||
}
|
||||
expect(
|
||||
runVatDeclarationChecks(outside).find((f) => f.code === 'SALES_OUTPUT_VAT_SHORTFALL')?.status,
|
||||
).toBe('WARNING')
|
||||
})
|
||||
|
||||
it('does not fire when output VAT is absent entirely (binary ERROR owns that case)', () => {
|
||||
const rutor: VatDeclarationRutor = {
|
||||
...emptyRutor,
|
||||
ruta05: 10000,
|
||||
ruta49: 0,
|
||||
}
|
||||
const findings = runVatDeclarationChecks(rutor)
|
||||
expect(findings.find((f) => f.code === 'TAXABLE_SALES_WITHOUT_OUTPUT')?.status).toBe('ERROR')
|
||||
expect(findings.find((f) => f.code === 'SALES_OUTPUT_VAT_SHORTFALL')).toBeUndefined()
|
||||
})
|
||||
})
|
||||
|
||||
// Mirror: output VAT without taxable sales base.
|
||||
@@ -506,6 +601,9 @@ describe('runVatDeclarationChecks', () => {
|
||||
const findings = runVatDeclarationChecks(rutor)
|
||||
expect(findings.find((f) => f.code === 'TAXABLE_SALES_WITHOUT_OUTPUT')).toBeUndefined()
|
||||
expect(findings.find((f) => f.code === 'OUTPUT_VAT_WITHOUT_SALES_BASE')).toBeUndefined()
|
||||
// The proportional warning checks the OPPOSITE direction only: excess
|
||||
// output (VMB, uthyrning, overrides) must never trigger it either.
|
||||
expect(findings.find((f) => f.code === 'SALES_OUTPUT_VAT_SHORTFALL')).toBeUndefined()
|
||||
})
|
||||
|
||||
// Multiple findings should surface together so the user sees the whole picture.
|
||||
|
||||
@@ -49,6 +49,7 @@ export interface VatDeclarationCheck {
|
||||
| 'IMPORT_BASE_WITHOUT_OUTPUT'
|
||||
| 'IMPORT_OUTPUT_WITHOUT_BASE'
|
||||
| 'OUTPUT_VAT_WITHOUT_SALES_BASE'
|
||||
| 'SALES_OUTPUT_VAT_SHORTFALL'
|
||||
status: VatDeclarationCheckStatus
|
||||
/** Swedish user-facing message; safe to render directly in the UI. */
|
||||
message: string
|
||||
@@ -222,7 +223,8 @@ export function runVatDeclarationChecks(
|
||||
//
|
||||
// DELIBERATELY BINARY, unlike the RC and import pairs. The proportional form
|
||||
// (rutor 05-08 vs ruta10/0.25 + ruta11/0.12 + ruta12/0.06) is NOT sound on
|
||||
// the sales side, because ACCOUNT_RUTA's two halves are not a closed set:
|
||||
// the sales side as a filing-blocking ERROR, because ACCOUNT_RUTA's two
|
||||
// halves are not a closed set:
|
||||
// - rutor 07 (VMB) and 08 (frivillig uthyrning) have NO source accounts at
|
||||
// all, while their output VAT (2616/2626/2636, 2613/2623/2633) does feed
|
||||
// rutor 10-12, so the implied base permanently exceeds the reported one;
|
||||
@@ -236,6 +238,9 @@ export function runVatDeclarationChecks(
|
||||
// blocking ERROR (isFilingBlocked) on a correct declaration. Making rutor 07
|
||||
// and 08 mappable and reconciling the revenue_account override is the
|
||||
// prerequisite; see the report accompanying this change.
|
||||
//
|
||||
// ONE direction is proportionally checkable without blocking: see
|
||||
// SALES_OUTPUT_VAT_SHORTFALL below.
|
||||
const taxableSalesBase = rutor.ruta05 + rutor.ruta06 + rutor.ruta07 + rutor.ruta08
|
||||
const taxableSalesOutput = rutor.ruta10 + rutor.ruta11 + rutor.ruta12
|
||||
if (taxableSalesBase > eps && taxableSalesOutput <= eps) {
|
||||
@@ -268,6 +273,48 @@ export function runVatDeclarationChecks(
|
||||
})
|
||||
}
|
||||
|
||||
// Proportional tightening of the sales pair, WARNING tier only. The binary
|
||||
// ERROR above clears as soon as ANY output VAT exists, so at a 400 000 kr
|
||||
// sales base 2 000 kr of missing utgående moms still rendered a green
|
||||
// "Inga fel hittades" banner: undeclared moms and skattetillägg exposure
|
||||
// under SFL 49 kap 4 §.
|
||||
//
|
||||
// Only THIS direction (reported base implies more output VAT than rutor
|
||||
// 10-12 carry) is proportionally checkable: every unmapped drift source
|
||||
// listed above (VMB, frivillig uthyrning, revenue_account overrides,
|
||||
// periodisering in the invoice month) inflates the OUTPUT side and can only
|
||||
// suppress this finding, never trigger it. The one legitimate trigger is
|
||||
// periodiserade invoice lines dissolving (3001 credited with the moms
|
||||
// already declared in the invoice month), which is why this is a WARNING
|
||||
// that names that cause and never blocks filing (isFilingBlocked reads
|
||||
// ERROR only), following the RC_INPUT_VAT_MISMATCH precedent.
|
||||
//
|
||||
// The base comparison is exact per rate (basbelopp = moms/sats summed over
|
||||
// 25/12/6), so legitimate mixed-rate declarations net to zero drift; the
|
||||
// shared max(1 kr, 0.5%) tolerance absorbs per-voucher öre rounding.
|
||||
const expectedSalesBase =
|
||||
rutor.ruta10 / 0.25 + rutor.ruta11 / 0.12 + rutor.ruta12 / 0.06
|
||||
const salesTolerance = Math.max(1, expectedSalesBase * 0.005)
|
||||
if (taxableSalesOutput > eps && taxableSalesBase > expectedSalesBase + salesTolerance) {
|
||||
const shortfall = Math.round(taxableSalesBase - expectedSalesBase)
|
||||
findings.push({
|
||||
code: 'SALES_OUTPUT_VAT_SHORTFALL',
|
||||
status: 'WARNING',
|
||||
message:
|
||||
'Den momspliktiga försäljningen (ruta 05-08) är ' +
|
||||
`${Math.round(taxableSalesBase).toLocaleString('sv-SE')} kr, men den ` +
|
||||
'utgående momsen (ruta 10-12) motsvarar bara ett underlag på cirka ' +
|
||||
`${Math.round(expectedSalesBase).toLocaleString('sv-SE')} kr: cirka ` +
|
||||
`${shortfall.toLocaleString('sv-SE')} kr av försäljningen saknar ` +
|
||||
'utgående moms. Kontrollera att momsrader (2611/2621/2631) är ' +
|
||||
'bokförda för varje intäktsrad, eller flytta momsfri försäljning till ' +
|
||||
'rätt ruta (35/36/39/40). Använder du periodisering av fakturarader ' +
|
||||
'är skillnaden korrekt (momsen redovisas i fakturamånaden, intäkten ' +
|
||||
'löpande) och varningen kan lämnas utan åtgärd.',
|
||||
rutor: ['ruta05', 'ruta06', 'ruta07', 'ruta08', 'ruta10', 'ruta11', 'ruta12'],
|
||||
})
|
||||
}
|
||||
|
||||
// SKV §4.1.1.4 rules 5 and 6: import base and import output VAT require each
|
||||
// other. Compared PROPORTIONALLY, not by presence, for the same reason the
|
||||
// RC pair above is: a binary test clears as soon as ONE import voucher
|
||||
|
||||
Reference in New Issue
Block a user