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
@@ -1,52 +1,73 @@
|
||||
# Sjuklön (Sick Pay)
|
||||
# OB-tillägg and Övertid (Unsocial Hours and Overtime)
|
||||
|
||||
## The 14-day employer obligation
|
||||
## OB-tillägg is contractual, not statutory
|
||||
|
||||
Under Sjuklönelagen, the employer pays sick pay for the first 14 calendar days of each sjuklöneperiod.
|
||||
No Swedish law sets OB rates. OB-tillägg (obekväm arbetstid) comes from kollektivavtal or the individual employment contract. Arbetstidslagen (1982:673) limits WHEN and HOW MUCH people may work; it says nothing about premium pay. A company without a CBA has no OB obligation unless its contracts create one, so payroll software must treat every rate, window, and divisor as configuration, never as a statutory constant.
|
||||
|
||||
## Karensavdrag (day 1)
|
||||
### Common CBA window shapes (examples, always agreement-specific)
|
||||
|
||||
Replaces the old karensdag system (since 2019). Equals 20% of one average week's sjuklön:
|
||||
| Window | Typical span | Item type |
|
||||
|---|---|---|
|
||||
| Vardag kväll | weekday 18:00-22:00 (some CBAs 19:00-22:00) | ob_weekday_evening |
|
||||
| Natt | 22:00-06:00 (wraps midnight) | ob_night |
|
||||
| Helg | Fri/Sat evening through Sun 24:00 | ob_weekend |
|
||||
| Helgdag/storhelg | actual public holidays, highest rates | ob_holiday |
|
||||
|
||||
```
|
||||
average_weekly_pay = (monthly_salary × 12) / 52
|
||||
weekly_sjuklön = average_weekly_pay × 0.80
|
||||
karensavdrag = weekly_sjuklön × 0.20
|
||||
```
|
||||
### Common CBA formula shapes
|
||||
|
||||
For a 30,000 SEK/month employee at 40 hrs/week: karensavdrag ≈ 1,108 SEK.
|
||||
Two families, both agreement-specific:
|
||||
|
||||
Only one karensavdrag per sjuklöneperiod. The allmänt högriskskydd limits karensavdrag to maximum 10 per rolling 12-month period. After 10, no further deductions.
|
||||
- Percent of hourly wage: OB hour paid at base hourly rate × premium percent (e.g. 20%, 50%, 70%, 100%).
|
||||
- Monthly-salary divisors: OB hour paid at månadslön / divisor. Divisors like 600, 400, 300, 150 appear in white-collar CBAs, with smaller divisors (higher pay) for nights, weekends, and storhelg. These are CBA figures, not law: never hard-code them.
|
||||
|
||||
## Day 2-14: 80% of lost pay
|
||||
## Övertid vs mertid
|
||||
|
||||
Sjuklön = 80% of the salary and anställningsförmåner the employee loses due to sickness, calculated per scheduled work hour. Includes regular salary, shift supplements, and scheduled overtime premiums.
|
||||
- Övertid: time beyond ordinary full-time hours. CBAs commonly distinguish enkel övertid (weekday daytime, often ~50% premium or månadslön/94 per hour) from kvalificerad övertid (nights/weekends/holidays, often ~100% premium or månadslön/72 per hour). Divisor values vary by agreement.
|
||||
- Mertid: a part-time employee's hours up to the full-time ordinary schedule. Usually plain hourly pay, sometimes a small premium; becomes övertid only past full-time hours.
|
||||
- Kompensationsledighet: CBAs may allow overtime to be compensated as time off (commonly 1.5 or 2 hours per overtime hour) instead of pay.
|
||||
- Contracted-away overtime: managers and salaried staff often trade övertidsersättning for higher salary and/or extra vacation days; then no overtime lines are generated at all.
|
||||
|
||||
### Läkarintyg (medical certificate)
|
||||
## Arbetstidslagen (1982:673) limits
|
||||
|
||||
Required from day 8. The employer may require it from day 1 (förstadagsintyg) with written, time-limited justification.
|
||||
Limits govern hours, not pay; exceeding them is a sanction issue (sanktionsavgift via Arbetsmiljöverket), but payroll should be able to surface them:
|
||||
|
||||
## Återinsjuknande
|
||||
- Ordinary working time: max 40 h/week on average (5 §).
|
||||
- Allmän övertid: max 200 h/calendar year, and max 48 h per 4-week period or 50 h per calendar month (8 §).
|
||||
- Extra övertid: up to 150 h/year more when special reasons exist (8 a §).
|
||||
- Allmän mertid: max 200 h/calendar year for part-time employees (10 §).
|
||||
- Dygnsvila: 11 consecutive hours per 24-hour period; night rest should include 24:00-05:00 (13 §).
|
||||
- Veckovila: 36 consecutive hours per 7-day period (14 §).
|
||||
- EU Working Time Directive backstop: max 48 h/week average over 4 months, total time including overtime.
|
||||
|
||||
If the employee falls sick again within 5 calendar days, the same sjuklöneperiod continues (no new karensavdrag). The remaining days of the original 14-day period are used.
|
||||
ATL is semi-dispositive: CBAs may deviate from most limits, but only within the EU directive's frame.
|
||||
|
||||
## Day 15+: Försäkringskassan
|
||||
## How this codebase's engine models premiums
|
||||
|
||||
The employer must report to Försäkringskassan within 7 calendar days after the sjuklöneperiod ends.
|
||||
`lib/salary/shift-premium-engine.ts` turns worked days plus configured rules into salary line items:
|
||||
|
||||
Sjukpenning rates:
|
||||
- ~80% of SGI up to ceiling (10 × PBB, max ~1,284 SEK/day in 2025)
|
||||
- Up to 364 days within a 450-day frame
|
||||
- Then 75% (fortsättningsnivå)
|
||||
- A rule = day_of_week set + start/end time window + premium_percent + item_type + priority. Windows with end <= start wrap past midnight (22:00-06:00 covers both halves).
|
||||
- Item types: `overtime_50`, `overtime_100`, `ob_weekday_evening`, `ob_weekend`, `ob_night`, `ob_holiday`.
|
||||
- `ob_holiday` rules fire only when the worked date is an actual Swedish public holiday (calendar-driven via `isSwedishHolidayISO`); a regular Sunday is not a helgdag, a midweek Midsommarafton is.
|
||||
- Every worked minute is awarded to exactly one rule: highest priority wins, ties broken by higher premium_percent, so totals never double-count.
|
||||
- Amount per line = base hourly rate × hours × premium_percent / 100, rounded per the monetary rule (`Math.round(x * 100) / 100`).
|
||||
- Worked-day rows without explicit start_time/end_time fall back to an assumed 08:00-17:00 shift, so pure-night or pure-weekend rules never match legacy hours-only rows. Exact shift windows are required for correct night/weekend OB.
|
||||
|
||||
## Högkostnadsskydd
|
||||
## Payroll treatment
|
||||
|
||||
Abolished July 1, 2024 for general employers. Särskilt högriskskydd (for chronically ill employees) remains: Försäkringskassan reimburses the employer's sjuklönekostnader plus arbetsgivaravgifter.
|
||||
OB-tillägg and övertidsersättning are ordinary kontant bruttolön:
|
||||
|
||||
- Subject to skatteavdrag (part of the tax-table lookup base) and arbetsgivaravgifter.
|
||||
- Semesterlönegrundande (raises semesterlön under procentregeln) and sjuklönegrundande (day 2-14 sjuklön includes lost shift premiums).
|
||||
- PGI-grundande like any cash wage.
|
||||
- AGI: reported inside kontant bruttolön (FK011) on the individual statement; there is no separate fältkod for OB or övertid.
|
||||
|
||||
## BAS accounts
|
||||
|
||||
Booked on the same wage account as base salary and differentiated by line text on the verifikat and payslip (this codebase maps all premium item types to the base wage account):
|
||||
|
||||
| Account | Purpose |
|
||||
|---|---|
|
||||
| 7081 | Sjuklöner till kollektivanställda |
|
||||
| 7281 | Sjuklöner till tjänstemän |
|
||||
| 7650 | Sjuklöneförsäkring |
|
||||
| 7010 | Löner kollektivanställda (incl. OB and overtime premiums) |
|
||||
| 7210 | Löner tjänstemän (incl. OB and overtime premiums, engine default) |
|
||||
| 2710 | Personalskatt (withholding on the full gross incl. premiums) |
|
||||
| 2730 | Lagstadgade sociala avgifter (on the full gross incl. premiums) |
|
||||
|
||||
@@ -64,6 +64,8 @@ CRON_SECRET=generate-a-random-secret
|
||||
# and read them in the adapter, or replace them with the vendor's own names.
|
||||
# OBSERVABILITY_DSN= # server-side ingest endpoint / key
|
||||
# NEXT_PUBLIC_OBSERVABILITY_DSN= # browser ingest endpoint / key, if used
|
||||
# Any adapter reading these MUST forward only post-redaction payloads
|
||||
# (lib/observability/redact.ts): see docs/security/logging-and-observability.md
|
||||
# Optional overrides. Both have sensible defaults: the environment falls back
|
||||
# to VERCEL_ENV then NODE_ENV, and the release falls back to
|
||||
# NEXT_PUBLIC_BUILD_ID (the commit sha next.config.ts inlines at build time)
|
||||
|
||||
@@ -16,6 +16,18 @@ name: Scheduled Image Vulnerability Scan
|
||||
# 3. workflow_dispatch: run on demand from the Actions tab after a patch to
|
||||
# confirm clean.
|
||||
#
|
||||
# Severity gate policy (both jobs): only fixable CRITICAL/HIGH CVEs may fail a
|
||||
# run; LOW/MEDIUM findings must never turn a run red. Every sarif-format Trivy
|
||||
# step MUST keep `limit-severities-for-sarif: true`, otherwise trivy-action
|
||||
# unsets TRIVY_SEVERITY for SARIF output and the gate silently widens to all
|
||||
# severities (that exact misconfiguration shipped once; see the scan step).
|
||||
#
|
||||
# The `sca` job is the dependency-level counterpart of the image scan: a daily
|
||||
# Trivy filesystem scan of the npm lockfile. It exists because Dependabot was
|
||||
# deliberately removed (PR #1084) and two HIGH Next.js CVEs then sat
|
||||
# undetected until a manual check; this job is the automated SCA alerting
|
||||
# that replaces it.
|
||||
#
|
||||
# NOTE: GitHub only runs `schedule` and `workflow_run` triggers from the default
|
||||
# branch, so both start firing once this is merged to main.
|
||||
on:
|
||||
@@ -84,3 +96,47 @@ jobs:
|
||||
with:
|
||||
sarif_file: trivy-results.sarif
|
||||
category: trivy
|
||||
|
||||
sca:
|
||||
runs-on: ubuntu-latest
|
||||
# The lockfile does not change when an image is published, so the
|
||||
# workflow_run trigger is irrelevant here: run on the daily schedule and
|
||||
# on manual dispatch only.
|
||||
if: github.event_name != 'workflow_run'
|
||||
permissions:
|
||||
contents: read
|
||||
# SARIF upload to the repo's "Security" tab.
|
||||
security-events: write
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- name: Scan npm lockfile with Trivy
|
||||
uses: aquasecurity/trivy-action@v0.36.0
|
||||
with:
|
||||
# Filesystem scan: picks up package-lock.json and reports known CVEs
|
||||
# in the resolved dependency tree, including transitive pins. Same
|
||||
# gate policy as the image scan above: fail only on fixable
|
||||
# CRITICAL/HIGH, and keep limit-severities-for-sarif set (see the
|
||||
# header comment for why dropping it silently widens the gate).
|
||||
scan-type: fs
|
||||
scan-ref: .
|
||||
scanners: vuln
|
||||
severity: CRITICAL,HIGH
|
||||
exit-code: '1'
|
||||
ignore-unfixed: true
|
||||
format: sarif
|
||||
output: trivy-sca.sarif
|
||||
limit-severities-for-sarif: true
|
||||
|
||||
- name: Upload Trivy SCA results to GitHub Security tab
|
||||
# if: always() so findings reach the Security tab even when the scan
|
||||
# step failed the run. Distinct category from the image scan so
|
||||
# dependency alerts and image alerts stay separately traceable.
|
||||
if: always()
|
||||
uses: github/codeql-action/upload-sarif@v4
|
||||
with:
|
||||
sarif_file: trivy-sca.sarif
|
||||
category: trivy-sca
|
||||
|
||||
@@ -84,6 +84,20 @@ jobs:
|
||||
DIFF_FILE: diff.patch
|
||||
FILES_FILE: files.txt
|
||||
run: node scripts/swedish-compliance-review.mjs
|
||||
- name: Assert review produced output
|
||||
# This job once produced no compliance signal for 10 consecutive PR
|
||||
# runs (the in-tree npm install died on an unrelated peer conflict, see
|
||||
# the install step above) and nobody noticed: workflow_run-triggered
|
||||
# jobs do not appear on the PR checks list, so a red or silently empty
|
||||
# run is invisible from the PR. Fail loudly whenever the review script
|
||||
# finishes without writing a non-empty review.md, so "no output" can
|
||||
# never again pass as a green run.
|
||||
run: |
|
||||
set -euo pipefail
|
||||
if [ ! -s review.md ]; then
|
||||
echo "::error::Compliance review produced no output (review.md missing or empty)"
|
||||
exit 1
|
||||
fi
|
||||
- name: Find previous compliance comment
|
||||
uses: peter-evans/find-comment@b30e6a3c0ed37e7c023ccd3f1db5c6c0b0c23aad # v4.0.0
|
||||
id: find-comment
|
||||
|
||||
@@ -556,4 +556,19 @@ One line per decision: `[YYYY-MM-DD] <decision>: <why>`. Appended by agents and
|
||||
[2026-07-27] KPI preferences stay company-scoped (one row per company, last writer wins): the read path filters on (company_id, extension_id, key) with no user filter, so the broken upsert arbiter was aligned to the real unique constraint instead of introducing per-user semantics nothing reads.
|
||||
[2026-07-27] Booking-template updates scope-check company templates against the active company and team templates against the active company's team_id, instead of a blind company_id filter which would have broken team-shared template editing (team templates carry company_id NULL).
|
||||
[2026-07-27] Deferred from the pre-publish review, each needs its own decision: arcim OAuth state is not yet bound to the initiating browser session (TTL cut from 60 to 10 minutes as mitigation); customer invoices can still be created rate-less while supplier invoices refuse (the engine now refuses at booking instead); the v1 journal-entries dry-run commit still burns voucher numbers (pre-existing audit P0, route untouched by this branch).
|
||||
|
||||
[2026-07-27] Compliance-bot finding "getPermittedVatRates not applied at 6 sites" verified already resolved: all six write gates (commit.ts, mcp-server, bulk-create, recurring-schedule, self-billed, InvoiceEditor via line-vat-rates.ts) gate on the permitted set, pinned by vat-rate-gate-parity.test.ts; no code change needed.
|
||||
[2026-07-27] computeDeduction() base changed to arbetskostnad INKLUSIVE moms (HUSFL 2009:194 6-9 par., skill-confirmed: ROT 30%/RUT 50% of labor incl. VAT; Skatteverkets example 18 000 kr excl = 22 500 incl, ROT 6 750): ItemForDeduction gained vat_rate, all five call sites (build-invoice-write both sites, invoice-entries 1513 legs, propose-send-lines preview, InvoiceEditor both previews) pass the line rate, and the per-line VAT is reproduced with the exact stored-vat_amount rounding so the 1513 debit, deduction_total and the HUS-file BegartBelopp stay ore-consistent; missing/null vat_rate deliberately means 0% (momsfri labor) so unaware callers under- rather than over-deduct. Already-issued invoices keep their stored exkl.-based deduction_amount; correcting those is a separate decision for Emil.
|
||||
[2026-07-27] sie-parser #RAR validation: every #RAR record (prior years included) now validates index/dates/ordering and skips malformed records; the 18-month BFL 3 kap. overrun is warn-and-keep rather than skip, because ensureFiscalPeriod's hard refusal for #RAR 0 needs the real dates to produce its precise Swedish error, and dropping the entry would degrade it to "no fiscal year defined".
|
||||
[2026-07-27] Rewrote .claude/skills/swedish-payroll/references/ob-overtime.md (was a byte-identical copy of sick-pay.md since PR #202): content sourced from the swedish-payroll skill and shift-premium-engine.ts semantics; CBA-dependent figures (OB windows, divisors 600/400/300/150, 94/72) are labeled as examples, never statutory; skills:generate re-run because the atom manifest tracks reference files too (emitted 20260727121001_seed_agent_atom_bodies.sql).
|
||||
[2026-07-27] Momsdeklaration sales pair got a proportional check in ONE direction only (SALES_OUTPUT_VAT_SHORTFALL, WARNING tier): reported base above the output-implied base (ruta10/0.25 + ruta11/0.12 + ruta12/0.06, max(1 kr, 0.5%) tolerance) now warns instead of hiding inside the binary check, closing the 2000-kr-on-400000 green-banner gap from the compliance review; it stays a WARNING and the other direction stays binary because the 2026-07-26 entry's drift sources (VMB/uthyrning rutor 07/08 unmapped, revenue_account overrides, periodisering) all inflate the output side, so they can suppress but never false-positive this direction, while periodisering dissolution months legitimately trigger it and must not block filing.
|
||||
[2026-07-27] SCA alerting restored as a Trivy lockfile job in docker-image-scan.yml, not Dependabot: Dependabot was deliberately removed in #1084, so the daily fs-scan sca job (CRITICAL/HIGH, SARIF category trivy-sca) provides the automated CVE detection ASVS V13.1/SOC2 CC3.2 require without reversing that decision.
|
||||
[2026-07-27] swedish-compliance-review.yml now fails on empty review.md: workflow_run jobs never appear on PR checks, so the 10-run silent outage could recur invisibly; an explicit non-empty-output assertion turns "no signal" into a red run.
|
||||
[2026-07-27] Created docs/security/ (authorization-policy.md, logging-and-observability.md) as the authoritative record for the SIE bulk-delete RPC authorization model and the sink redaction contract: no authorization-matrix file exists in the repo, so the policy doc is the inventory until one is introduced. Declined the swarm's generic "CI check for SECURITY DEFINER grants to anon" ratchet for now: the concrete RPC is pinned by has_function_privilege assertions in sie-import.replace.pg.test.ts; a repo-wide ratchet is a separate piece of work.
|
||||
[2026-07-27] arcim migration FX-unresolved logging routed through lib/logger createLogger instead of console.error: invoice identifiers in log output now pass the observability redaction pipeline; the compliance finding named entity-mapper.ts but the call lived in migration-orchestrator.ts (logFxUnresolved).
|
||||
[2026-07-27] build-invoice-write.ts populates subtotal_sek/vat_amount_sek/total_sek = ore-rounded invoice-currency values for SEK invoices (was NULL): the staged-operations commit path already wrote sekRate=1 twins, so the same invoice row differed by creation path and blanked SEK-reporting readers; foreign-currency invoices with no obtainable rate still store NULL because a made-up rate is worse than an absent one.
|
||||
[2026-07-27] gnubok_set_employee_opening_balances null-carry finding closed as false positive: all eight mergeable columns are NOT NULL DEFAULT per migration 20260713101000, so the stored-value carry can never drop a legitimate NULL; documented at the merge site with a guard note for future nullable columns.
|
||||
[2026-07-27] pending-operations risk flatten ({ ...params, ...changes }) verified safe, no restriction added: only the two recurring-schedule op types are param-sensitive (auto_send), update's strict schema has no top-level auto_send to mask, create's strict allowlist admits no changes bag, and the approve gate consumes the stage-time risk_level so no unflattened re-derivation exists.
|
||||
[2026-07-27] Kept the '********-1234' mask sentinel in UpdateCustomerSchema against the swarm's V4.5 suggestion to strip it in the route pre-validation: the mask shape (asterisks) can never collide with a valid personnummer, CreateCustomerSchema stays strict so the sentinel only exists where a stored value exists to preserve, and moving the strip to the route would split the contract across two files for zero behavioral change.
|
||||
[2026-07-27] Restored 20260726140000 to its preview-recorded content (60b14193) and restated the NULL-safe tenant guard as 20260727130000: the PR #1215 preview branch recorded that version before review hardening edited it, an applied version never re-runs, and a bare rename would have orphaned the preview's version row; CREATE OR REPLACE makes both replay orders converge on identical prosrc.
|
||||
[2026-07-27] Voucher-link guard conflict, final resolution across the two parallel sessions: 20260726140000 is kept byte-identical to HEAD (NULL-safe caller_is_company_member form) instead of being reverted in place to the raw NOT-IN shape, because the guard edit landed pre-publish (60b14193 at 02:08, PR #1215 opened 02:14) so the preview most plausibly recorded the NULL-safe content, and reintroducing the ratchet-banned raw shape into a migration file was the costlier wrong-guess; 20260727130000 stays, restating the same final bodies via CREATE OR REPLACE, which converges preview, prod-at-merge and CI replays under either hypothesis about what the preview actually recorded.
|
||||
|
||||
@@ -841,17 +841,17 @@ describe('POST /api/v1/companies/:companyId/invoices', () => {
|
||||
|
||||
expect(res.status).toBe(201)
|
||||
expect(insertedInvoice).not.toBeNull()
|
||||
// ROT = 30% of 10000 labor.
|
||||
expect(insertedInvoice!.deduction_total).toBe(3000)
|
||||
// ROT = 30% of the labor incl. moms (HUSFL 6-9 §§): 30% x 12 500 = 3 750.
|
||||
expect(insertedInvoice!.deduction_total).toBe(3750)
|
||||
// Personnummer never stored in plaintext: ciphertext + last4 only.
|
||||
expect(insertedInvoice!.deduction_personnummer_encrypted).toBeTruthy()
|
||||
expect(insertedInvoice!.deduction_personnummer_encrypted).not.toContain(VALID_PNR)
|
||||
expect(insertedInvoice!.deduction_personnummer_last4).toBe('2388')
|
||||
// Customer share: total 12500 minus the 3000 Skatteverket pays via 1513.
|
||||
expect(insertedInvoice!.remaining_amount).toBe(9500)
|
||||
// Customer share: total 12500 minus the 3750 Skatteverket pays via 1513.
|
||||
expect(insertedInvoice!.remaining_amount).toBe(8750)
|
||||
expect(insertedItems).not.toBeNull()
|
||||
expect(insertedItems![0].deduction_type).toBe('rot')
|
||||
expect(insertedItems![0].deduction_amount).toBe(3000)
|
||||
expect(insertedItems![0].deduction_amount).toBe(3750)
|
||||
expect(insertedItems![0].work_type).toBe('BYGG')
|
||||
expect(insertedItems![0].labor_hours).toBe(10)
|
||||
// Invoice-level fastighetsbeteckning stamped onto the deduction line.
|
||||
@@ -927,11 +927,11 @@ describe('POST /api/v1/companies/:companyId/invoices', () => {
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const body = await res.json()
|
||||
// RUT = 50% of 2000 labor.
|
||||
expect(body.data.preview.deduction_total).toBe(1000)
|
||||
// RUT = 50% of the labor incl. moms (HUSFL 6-9 §§): 50% x 2 500 = 1 250.
|
||||
expect(body.data.preview.deduction_total).toBe(1250)
|
||||
expect(body.data.preview.deduction_personnummer_last4).toBe('2388')
|
||||
expect(body.data.preview.deduction_personnummer_encrypted).toBeUndefined()
|
||||
expect(body.data.preview.items[0].deduction_amount).toBe(1000)
|
||||
expect(body.data.preview.items[0].deduction_amount).toBe(1250)
|
||||
})
|
||||
|
||||
it('persists article_id + revenue_account on line items (validated against the chart)', async () => {
|
||||
|
||||
@@ -865,6 +865,9 @@ export default function InvoiceEditor(props: InvoiceEditorProps = { mode: 'creat
|
||||
unit_price: item.unit_price || 0,
|
||||
quantity: item.quantity || 0,
|
||||
deduction_type: item.deduction_type,
|
||||
// Same rate resolution as the VAT totals loop above: the deduction
|
||||
// base is the line total inkl. moms (HUSFL 6-9 §§).
|
||||
vat_rate: vatRegistered ? (item.vat_rate ?? (vatRules?.rate || 25)) : 0,
|
||||
})
|
||||
if (item.deduction_type === 'rot') deductionByKind.rot += amount
|
||||
else deductionByKind.rut += amount
|
||||
@@ -1941,6 +1944,9 @@ export default function InvoiceEditor(props: InvoiceEditorProps = { mode: 'creat
|
||||
unit_price: watchItems[index]?.unit_price || 0,
|
||||
quantity: watchItems[index]?.quantity || 0,
|
||||
deduction_type: watchItems[index]?.deduction_type,
|
||||
vat_rate: vatRegistered
|
||||
? (watchItems[index]?.vat_rate ?? (vatRules?.rate || 25))
|
||||
: 0,
|
||||
})
|
||||
return amt > 0 ? (
|
||||
<span className="text-xs tabular-nums text-muted-foreground">
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
# Authorization Policy: Privileged RPCs
|
||||
|
||||
This document records the access-control model of database functions that run
|
||||
with elevated privileges (SECURITY DEFINER) and can mutate or destroy tenant
|
||||
data. It exists so the authorization contract of each function is reviewable
|
||||
without reading migration SQL, and so changes to that contract are deliberate.
|
||||
|
||||
No machine-readable authorization matrix (authorization-matrix.csv or similar)
|
||||
exists in this repository yet; this document is currently the authoritative
|
||||
inventory. If such a matrix is introduced, every function listed here must get
|
||||
a row in it.
|
||||
|
||||
## SIE bulk-delete pair: `replace_sie_import` and `undo_sie_import`
|
||||
|
||||
Defined in:
|
||||
|
||||
- `supabase/migrations/20260727120000_replace_sie_import_authorize_actor.sql`
|
||||
- `supabase/migrations/20260727121000_undo_sie_import_caller_guard.sql`
|
||||
|
||||
Both functions hard-delete a completed SIE import's verifikationer so a fiscal
|
||||
period can be re-imported (replace) or restored to its pre-import state (undo).
|
||||
To do that they call `set_config('gnubok.allow_delete', 'true', true)`, which
|
||||
disarms the BFL immutability and 7-year retention triggers for the transaction.
|
||||
That makes them the two most dangerous entry points in the schema, and their
|
||||
authorization model is correspondingly strict.
|
||||
|
||||
### Why SECURITY DEFINER
|
||||
|
||||
The functions must bypass RLS and the enforcement triggers to perform the
|
||||
sanctioned bulk delete atomically. Running as the function owner is what allows
|
||||
the `gnubok.allow_delete` escape hatch to work; the compensating control is the
|
||||
in-function authorization gate described below, which runs before any mutation.
|
||||
|
||||
### Actor resolution
|
||||
|
||||
Each function takes `p_user_id uuid DEFAULT NULL` and resolves the acting user
|
||||
as follows:
|
||||
|
||||
- If `auth.role() = 'service_role'`: the actor is
|
||||
`COALESCE(p_user_id, auth.uid())`. The service-role client is the cookieless
|
||||
server client (`rpcClientForBulkDelete` in `lib/import/sie-import.ts`), used
|
||||
to escape the authenticator role's 8s statement timeout. Inside it
|
||||
`auth.uid()` is NULL, so the application passes the human user it already
|
||||
authenticated as `p_user_id`.
|
||||
- Every other caller is pinned to its own `auth.uid()`, regardless of what it
|
||||
passes as `p_user_id`. This closes the impersonation hole where an
|
||||
authenticated PostgREST caller could pass an owner's UUID and walk through
|
||||
the gate (the pre-fix behavior of `undo_sie_import`).
|
||||
|
||||
This is the same shape as `list_invoice_delivery_summaries_for_service`
|
||||
(migration `20260727100000`); treat it as the house pattern for any
|
||||
SECURITY DEFINER function that must accept a caller-asserted actor.
|
||||
|
||||
### Authorization gate
|
||||
|
||||
The resolved actor must hold the `owner` or `admin` role in
|
||||
`company_members` for `p_company_id`. The gate fails closed:
|
||||
|
||||
- An anon or unauthenticated caller has no membership row, `v_caller_role`
|
||||
resolves NULL, and the function raises before any mutation and before
|
||||
`gnubok.allow_delete` is ever set.
|
||||
- The raise uses `ERRCODE 42501` (insufficient_privilege) so application
|
||||
routes can map it to a 403.
|
||||
|
||||
### Grants
|
||||
|
||||
Supabase's default privileges grant EXECUTE on every new public function to
|
||||
PUBLIC and to anon/authenticated/service_role, and CREATE OR REPLACE
|
||||
re-introduces those grants. Both migrations therefore end with an explicit:
|
||||
|
||||
- `REVOKE EXECUTE ... FROM PUBLIC, anon` (revoking anon alone is not enough;
|
||||
anon is a member of PUBLIC and would stay callable through the PUBLIC grant)
|
||||
- `GRANT EXECUTE ... TO authenticated, service_role`
|
||||
|
||||
`authenticated` retains EXECUTE on purpose: on self-hosted installs without a
|
||||
`SUPABASE_SERVICE_ROLE_KEY`, the application falls back to running these RPCs
|
||||
on the caller's own session client. The in-function owner/admin gate scopes
|
||||
such callers to companies they actually administer, so this is tenant-scoped
|
||||
access, not a privilege escalation.
|
||||
|
||||
### Tenant isolation contract
|
||||
|
||||
Every mutation inside both functions filters on `p_company_id`, and the gate
|
||||
guarantees the actor administers that company. A caller can therefore never
|
||||
reach another tenant's data: the pre-fix `replace_sie_import` (no gate,
|
||||
EXECUTE held by anon) was a cross-tenant data-destruction primitive, and the
|
||||
gate plus the REVOKEs are what closed it.
|
||||
|
||||
### Verification
|
||||
|
||||
The contract is pinned by pg-real tests (run with `npm run test:pg`):
|
||||
|
||||
- `lib/import/__tests__/sie-import.replace.pg.test.ts`
|
||||
- `lib/import/__tests__/undo-sie-import-actor.pg.test.ts` (spoofed
|
||||
`p_user_id` rejection, the 42501 errcode, and the tightened grants)
|
||||
|
||||
Any change to either function's signature, gate, or grants must update these
|
||||
tests and this document in the same change.
|
||||
@@ -0,0 +1,58 @@
|
||||
# Logging and Observability Pipeline
|
||||
|
||||
This document states what the logging pipeline actually is in production, and
|
||||
the non-negotiable redaction contract for anything that forwards log data to a
|
||||
third party.
|
||||
|
||||
## The pipeline today
|
||||
|
||||
- `lib/logger.ts` writes structured log records to stdout/stderr. On hosted
|
||||
(Vercel) these are collected by the platform and delivered through the
|
||||
configured Vercel log drain, which is the production log delivery path.
|
||||
- `lib/observability/sink.ts` is a provider-agnostic seam for an error
|
||||
tracking vendor. It is a deliberate no-op until an adapter is registered
|
||||
with `registerObservabilitySink()` from a server-side init path. No adapter
|
||||
is registered by default, so self-hosted builds carry no third-party
|
||||
runtime dependency and setting the DSN environment variables alone changes
|
||||
nothing.
|
||||
|
||||
That means: until a vendor adapter is wired, error-level events reach a human
|
||||
only through the log drain. Any production deployment that wants alerting
|
||||
must either configure the log drain with alert rules or register a sink
|
||||
adapter; a no-op sink is not an alerting pipeline on its own.
|
||||
|
||||
## Redaction contract (GDPR, non-negotiable)
|
||||
|
||||
`lib/observability/redact.ts` is the single source of truth for what must
|
||||
never leave the process in clear text: a key denylist (passwords, tokens,
|
||||
IBAN, personnummer, ...), a personnummer regex applied to every string, and
|
||||
substring patterns for emails, Swedish IBANs, and gnubok API keys.
|
||||
|
||||
Structural guarantees, verified in the code:
|
||||
|
||||
- Every public entry point of the sink module (`captureException`,
|
||||
`captureMessage`) runs `redact()` / `redactString()` on the error, the
|
||||
message, and the context BEFORE the registered adapter sees anything. There
|
||||
is no code path from application data to a vendor that skips redaction.
|
||||
- Adapters receive errors already serialized and redacted as plain objects,
|
||||
never live `Error` instances, and must not re-fetch original values.
|
||||
- `redact()` is idempotent, so double-redaction on records the logger already
|
||||
cleaned is safe and is intentionally not "optimised away".
|
||||
|
||||
Rules for anyone adding an adapter or a new emission path:
|
||||
|
||||
1. Never call a vendor SDK directly from application code. Route through
|
||||
`captureException` / `captureMessage` so redaction stays structural.
|
||||
2. A browser-side adapter (one reading `NEXT_PUBLIC_OBSERVABILITY_DSN`) ships
|
||||
data straight from the user's browser to the vendor and bypasses every
|
||||
server-side control. It MUST apply the same redaction module before
|
||||
emitting: import from `lib/observability/redact.ts` and run all payloads
|
||||
through `redact()` / `redactString()` client-side. Do not register a
|
||||
browser adapter that forwards raw console or log payloads.
|
||||
3. Do not add a log emission path (new logger, direct `console.*` forwarding,
|
||||
CI log shipping) that reaches a third party without going through the
|
||||
redact module first.
|
||||
|
||||
The redaction behavior is pinned by unit tests under
|
||||
`lib/observability/__tests__/`; extend them when the denylist or patterns
|
||||
change.
|
||||
@@ -31,6 +31,7 @@ import {
|
||||
fetchSupplierInvoicesDirect,
|
||||
} from '@/lib/providers/provider-data-fetcher'
|
||||
import { fetchAllRows } from '@/lib/supabase/fetch-all'
|
||||
import { createLogger } from '@/lib/logger'
|
||||
import { reconcileSupplierInvoiceVouchers } from '@/lib/invoices/bulk-reconcile-supplier-vouchers'
|
||||
import {
|
||||
mapCustomer,
|
||||
@@ -43,6 +44,8 @@ import {
|
||||
type FxUnresolved,
|
||||
} from './entity-mapper'
|
||||
|
||||
const log = createLogger('extensions/arcim-migration/migration-orchestrator')
|
||||
|
||||
export interface MigrationOptions {
|
||||
consentId: string
|
||||
companyId: string
|
||||
@@ -91,11 +94,17 @@ function getOrgNumberFromParty(party: PartyDto): string | null {
|
||||
* migration reports it instead of passing it off as an ordinary import.
|
||||
*/
|
||||
function logFxUnresolved(kind: string, invoiceNumber: string, fx: FxUnresolved): void {
|
||||
console.error(
|
||||
`[migration] ${kind} ${invoiceNumber}: imported without a SEK conversion ` +
|
||||
`(${fx.currency} @ ${fx.date || 'okänt datum'}, reason=${fx.reason}). ` +
|
||||
`Set an exchange rate before booking it.`
|
||||
)
|
||||
// Structured logger, not console.error: the record passes the observability
|
||||
// redaction pipeline (lib/observability/redact.ts) before it can reach any
|
||||
// sink, so invoice identifiers in log output stay inside the same PII
|
||||
// controls as every other server log line.
|
||||
log.error('document imported without a SEK conversion; set an exchange rate before booking it', {
|
||||
entityType: kind,
|
||||
entityId: invoiceNumber,
|
||||
currency: fx.currency,
|
||||
documentDate: fx.date || null,
|
||||
reason: fx.reason,
|
||||
})
|
||||
}
|
||||
|
||||
// ── Main orchestrator ─────────────────────────────────────────────
|
||||
|
||||
@@ -324,6 +324,119 @@ describe('gnubok_tag_journal_lines: staging', () => {
|
||||
expect(insertCalls.some((args) => args[0] === 'pending_operations')).toBe(false)
|
||||
})
|
||||
|
||||
it('walks multiple entry pages: a full first page continues, and entries on later pages still match', async () => {
|
||||
// Regression target: the two-step fetch pages journal_entries with
|
||||
// .range() while filtering already-seen ids client-side (seenEntryIds).
|
||||
// This pins the interaction: a FULL first page (exactly ENTRY_PAGE_SIZE
|
||||
// rows) must not end the walk, an overlapping row on the next page (as a
|
||||
// shifted range can produce) must be dropped exactly once, and a genuinely
|
||||
// new entry on that page must survive the dedup and contribute its lines.
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
enqueue({ data: { dimensions_enabled: false }, error: null })
|
||||
|
||||
const entry = (i: number) => ({
|
||||
id: `je-${i}`,
|
||||
entry_date: '2024-03-01',
|
||||
voucher_number: i,
|
||||
voucher_series: 'A',
|
||||
status: 'posted',
|
||||
})
|
||||
const bareLine = (i: number, journalEntryId: string, account: string) => ({
|
||||
id: `00000000-0000-4000-8000-${String(i).padStart(12, '0')}`,
|
||||
journal_entry_id: journalEntryId,
|
||||
account_number: account,
|
||||
debit_amount: 250,
|
||||
credit_amount: 0,
|
||||
sort_order: 1,
|
||||
})
|
||||
|
||||
// Page 1: exactly ENTRY_PAGE_SIZE (1000) entries, so the loop must fetch
|
||||
// a second page. 1000 entries → 10 line chunks of 100 ids; only the first
|
||||
// chunk has a matching line.
|
||||
enqueue({ data: Array.from({ length: 1000 }, (_, i) => entry(i)), error: null })
|
||||
enqueue({ data: [bareLine(1, 'je-0', '4010')], error: null })
|
||||
for (let c = 1; c < 10; c++) enqueue({ data: [], error: null })
|
||||
|
||||
// Page 2 overlaps page 1 (je-999 returned again) and carries one new
|
||||
// entry. The duplicate is skipped; the new entry gets its own line chunk.
|
||||
enqueue({ data: [entry(999), entry(1000)], error: null })
|
||||
enqueue({ data: [bareLine(2, 'je-1000', '5010')], error: null })
|
||||
|
||||
enqueue({ data: { id: 'op-paging-1' }, error: null }) // pending_operations insert
|
||||
|
||||
const result = (await tagJournalLines.execute(
|
||||
{ dimensions: { '6': 'P01' }, reason: 'Retro-taggning', filters: { only_untagged: true } },
|
||||
'company-1',
|
||||
'user-1',
|
||||
supabase as never,
|
||||
)) as {
|
||||
staged: boolean
|
||||
preview: { matched_lines: number; sample: Array<{ account: string }> }
|
||||
}
|
||||
|
||||
expect(result.staged).toBe(true)
|
||||
// Both pages contributed: nothing on the far side of the page boundary
|
||||
// was silently dropped by the dedup.
|
||||
expect(result.preview.matched_lines).toBe(2)
|
||||
const sampleAccounts = result.preview.sample.map((s) => s.account)
|
||||
expect(sampleAccounts).toContain('4010') // line from page 1 (je-0)
|
||||
expect(sampleAccounts).toContain('5010') // line from page 2 (je-1000)
|
||||
|
||||
const fromCalls = (supabase.from as ReturnType<typeof vi.fn>).mock.calls
|
||||
// Exactly two entry pages were read (the loop terminated on the short
|
||||
// second page) and 11 line chunks ran: 10 for page 1, ONE for page 2:
|
||||
// the overlapping je-999 was deduped, so only je-1000 needed lines.
|
||||
expect(fromCalls.filter((args) => args[0] === 'journal_entries')).toHaveLength(2)
|
||||
expect(fromCalls.filter((args) => args[0] === 'journal_entry_lines')).toHaveLength(11)
|
||||
})
|
||||
|
||||
it('terminates when the match count is an exact multiple of the entry page size', async () => {
|
||||
// 1000 matches exactly: the raw first page is full, so the loop probes a
|
||||
// second page, finds it empty, and must stop instead of spinning (the
|
||||
// termination check reads the RAW page length, before dedup).
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
enqueue({ data: { dimensions_enabled: false }, error: null })
|
||||
|
||||
enqueue({
|
||||
data: Array.from({ length: 1000 }, (_, i) => ({
|
||||
id: `je-${i}`,
|
||||
entry_date: '2024-03-01',
|
||||
voucher_number: i,
|
||||
voucher_series: 'A',
|
||||
status: 'posted',
|
||||
})),
|
||||
error: null,
|
||||
})
|
||||
enqueue({
|
||||
data: [
|
||||
{
|
||||
id: '00000000-0000-4000-8000-000000000001',
|
||||
journal_entry_id: 'je-0',
|
||||
account_number: '4010',
|
||||
debit_amount: 250,
|
||||
credit_amount: 0,
|
||||
sort_order: 1,
|
||||
},
|
||||
],
|
||||
error: null,
|
||||
})
|
||||
for (let c = 1; c < 10; c++) enqueue({ data: [], error: null })
|
||||
enqueue({ data: [], error: null }) // page 2: empty, ends the walk
|
||||
enqueue({ data: { id: 'op-paging-2' }, error: null }) // pending_operations insert
|
||||
|
||||
const result = (await tagJournalLines.execute(
|
||||
{ dimensions: { '6': 'P01' }, reason: 'Retro-taggning', filters: { only_untagged: true } },
|
||||
'company-1',
|
||||
'user-1',
|
||||
supabase as never,
|
||||
)) as { staged: boolean; preview: { matched_lines: number } }
|
||||
|
||||
expect(result.staged).toBe(true)
|
||||
expect(result.preview.matched_lines).toBe(1)
|
||||
const fromCalls = (supabase.from as ReturnType<typeof vi.fn>).mock.calls
|
||||
expect(fromCalls.filter((args) => args[0] === 'journal_entries')).toHaveLength(2)
|
||||
})
|
||||
|
||||
it('dry_run previews the match without inserting a pending operation', async () => {
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
enqueue({ data: { dimensions_enabled: false }, error: null })
|
||||
|
||||
@@ -11410,6 +11410,11 @@ export const tools: McpTool[] = [
|
||||
const stored = storedByEmployee.get(p.employee_id as string)
|
||||
const carried: Record<string, unknown> = {}
|
||||
for (const field of MERGEABLE_FIELDS) {
|
||||
// The null-skip cannot drop a legitimately stored value: every
|
||||
// mergeable column is NOT NULL with a default (migration
|
||||
// 20260713101000), so a stored row never holds NULL here. If a
|
||||
// future migration adds a NULLABLE mergeable column, carry null
|
||||
// through explicitly or the schema .default() resets it on merge.
|
||||
const value = stored?.[field]
|
||||
if (value !== undefined && value !== null) carried[field] = value
|
||||
}
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -100,8 +100,8 @@
|
||||
"version": 2
|
||||
},
|
||||
"horizontal/swedish-payroll": {
|
||||
"hash": "a01f7a3ded13ec38fe224f1770d1b628efdda8d225ccd1e75eb0354f51ffec60",
|
||||
"version": 3
|
||||
"hash": "8cbedb0245ae1f3a042bc2310d9563424ed58ef9fc6f3e853693844323653faa",
|
||||
"version": 4
|
||||
},
|
||||
"horizontal/swedish-payroll/agi-filing": {
|
||||
"hash": "91aa490472fafff434088301dd193ed474589b36ae22bdaab640b42bc3b3c255",
|
||||
@@ -124,8 +124,8 @@
|
||||
"version": 1
|
||||
},
|
||||
"horizontal/swedish-payroll/ob-overtime": {
|
||||
"hash": "ba6b5dbdbb8e00edb9c592aae2185980ca52aa20888434bc5761ca307de712dd",
|
||||
"version": 1
|
||||
"hash": "4d4e079ae3178ab070ebd696c020d2598352e706430354de0f4bcbfcfcdbc471",
|
||||
"version": 2
|
||||
},
|
||||
"horizontal/swedish-payroll/sick-pay": {
|
||||
"hash": "ba6b5dbdbb8e00edb9c592aae2185980ca52aa20888434bc5761ca307de712dd",
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user