f24b26a139
* 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> --------- Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
1170 lines
46 KiB
TypeScript
1170 lines
46 KiB
TypeScript
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||
|
||
// ============================================================
|
||
// Mock: sequential result queue
|
||
// ============================================================
|
||
|
||
let resultIdx: number
|
||
let results: Array<{ data?: unknown; error?: unknown }>
|
||
|
||
function makeBuilder() {
|
||
const b: Record<string, unknown> = {}
|
||
for (const m of ['select', 'eq', 'neq', 'in', 'gte', 'lte', 'lt', 'or', 'not', 'order', 'range', 'limit']) {
|
||
b[m] = vi.fn().mockReturnValue(b)
|
||
}
|
||
b.single = vi.fn().mockImplementation(async () => results[resultIdx++] ?? { data: null, error: null })
|
||
b.maybeSingle = vi.fn().mockImplementation(async () => results[resultIdx++] ?? { data: null, error: null })
|
||
b.then = (resolve: (v: unknown) => void) => resolve(results[resultIdx++] ?? { data: null, error: null })
|
||
return b
|
||
}
|
||
|
||
function makeClient() {
|
||
return {
|
||
from: vi.fn().mockImplementation(() => makeBuilder()),
|
||
rpc: vi.fn().mockImplementation(async () => results[resultIdx++] ?? { data: null, error: null }),
|
||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||
} as any
|
||
}
|
||
|
||
/**
|
||
* Seed one get_vat_declaration_totals RPC result from line-level fixtures.
|
||
* The helper only SUMS the seeded lines per account (plain arithmetic on the
|
||
* fixture, mirroring what SQL's GROUP BY returns); settlement-shape
|
||
* detection and exclusion happen inside the RPC and are covered by
|
||
* tests/pg/vat-declaration-totals-rpc.pg.test.ts against real Postgres.
|
||
*/
|
||
function seedLedger(
|
||
lines: Array<{ account_number: string; debit_amount: number; credit_amount: number }>,
|
||
sourceTypes: string[] = [],
|
||
) {
|
||
const byAccount = new Map<string, { debit: number; credit: number }>()
|
||
for (const l of lines) {
|
||
const t = byAccount.get(l.account_number) ?? { debit: 0, credit: 0 }
|
||
t.debit += l.debit_amount
|
||
t.credit += l.credit_amount
|
||
byAccount.set(l.account_number, t)
|
||
}
|
||
const source_type_counts: Record<string, number> = {}
|
||
for (const s of sourceTypes) source_type_counts[s] = (source_type_counts[s] ?? 0) + 1
|
||
results.push({
|
||
data: {
|
||
totals: [...byAccount].map(([account_number, t]) => ({
|
||
account_number,
|
||
debit: t.debit,
|
||
credit: t.credit,
|
||
})),
|
||
settlement_shaped_entries: [],
|
||
source_type_counts,
|
||
},
|
||
error: null,
|
||
})
|
||
}
|
||
|
||
import {
|
||
calculatePeriodDates,
|
||
formatPeriodLabel,
|
||
getVatDeclarationSummary,
|
||
calculateVatDeclaration,
|
||
rcInputTotalsFromDeclaration,
|
||
} from '../vat-declaration'
|
||
import { runVatDeclarationChecks } from '../vat-declaration-checks'
|
||
import type { VatDeclaration } from '@/types'
|
||
|
||
let supabase: ReturnType<typeof makeClient>
|
||
|
||
beforeEach(() => {
|
||
vi.clearAllMocks()
|
||
resultIdx = 0
|
||
results = []
|
||
supabase = makeClient()
|
||
})
|
||
|
||
// ============================================================
|
||
// Pure function tests: no mocks needed
|
||
// ============================================================
|
||
|
||
describe('calculatePeriodDates', () => {
|
||
it('returns correct dates for monthly period', () => {
|
||
const { start, end } = calculatePeriodDates('monthly', 2024, 1)
|
||
expect(start).toBe('2024-01-01')
|
||
expect(end).toBe('2024-01-31')
|
||
})
|
||
|
||
it('returns correct dates for monthly period 12 (December)', () => {
|
||
const { start, end } = calculatePeriodDates('monthly', 2024, 12)
|
||
expect(start).toBe('2024-12-01')
|
||
expect(end).toBe('2024-12-31')
|
||
})
|
||
|
||
it('returns correct dates for quarterly period', () => {
|
||
const q1 = calculatePeriodDates('quarterly', 2024, 1)
|
||
expect(q1.start).toBe('2024-01-01')
|
||
expect(q1.end).toBe('2024-03-31')
|
||
|
||
const q4 = calculatePeriodDates('quarterly', 2024, 4)
|
||
expect(q4.start).toBe('2024-10-01')
|
||
expect(q4.end).toBe('2024-12-31')
|
||
})
|
||
|
||
it('returns full year for yearly period', () => {
|
||
const { start, end } = calculatePeriodDates('yearly', 2024, 1)
|
||
expect(start).toBe('2024-01-01')
|
||
expect(end).toBe('2024-12-31')
|
||
})
|
||
})
|
||
|
||
describe('formatPeriodLabel', () => {
|
||
it('formats monthly period', () => {
|
||
expect(formatPeriodLabel('monthly', 2024, 1)).toBe('Januari 2024')
|
||
expect(formatPeriodLabel('monthly', 2024, 6)).toBe('Juni 2024')
|
||
expect(formatPeriodLabel('monthly', 2024, 12)).toBe('December 2024')
|
||
})
|
||
|
||
it('formats quarterly period', () => {
|
||
expect(formatPeriodLabel('quarterly', 2024, 3)).toBe('Kvartal 3 2024')
|
||
})
|
||
|
||
it('formats yearly period', () => {
|
||
expect(formatPeriodLabel('yearly', 2024, 1)).toBe('Helår 2024')
|
||
})
|
||
})
|
||
|
||
describe('getVatDeclarationSummary', () => {
|
||
const emptyRc = { ruta20: 0, ruta21: 0, ruta22: 0, ruta23: 0, ruta24: 0, ruta30: 0, ruta31: 0, ruta32: 0 }
|
||
const zeroExtras = { ruta08: 0, ruta35: 0, ruta36: 0, ruta37: 0, ruta38: 0, ruta41: 0, ruta42: 0, ruta50: 0, ruta60: 0, ruta61: 0, ruta62: 0 }
|
||
|
||
it('calculates totals and detects payment', () => {
|
||
const declaration: VatDeclaration = {
|
||
period: { type: 'monthly', year: 2024, period: 1, start: '2024-01-01', end: '2024-01-31' },
|
||
rutor: {
|
||
ruta05: 10000, ruta06: 0, ruta07: 0,
|
||
ruta10: 2500, ruta11: 0, ruta12: 0,
|
||
ruta20: 0, ruta21: 0, ruta22: 0, ruta23: 0, ruta24: 0,
|
||
ruta30: 0, ruta31: 0, ruta32: 0,
|
||
ruta39: 0, ruta40: 0,
|
||
ruta48: 1000, ruta49: 1500,
|
||
...zeroExtras,
|
||
},
|
||
invoiceCount: 5,
|
||
transactionCount: 10,
|
||
breakdown: {
|
||
invoices: { ruta05: 10000, ruta06: 0, ruta07: 0, ruta10: 2500, ruta11: 0, ruta12: 0, ruta39: 0, ruta40: 0, base25: 10000, base12: 0, base6: 0 },
|
||
transactions: { ruta48: 1000 },
|
||
receipts: { ruta48: 0 },
|
||
reverseCharge: emptyRc,
|
||
},
|
||
}
|
||
|
||
const summary = getVatDeclarationSummary(declaration)
|
||
expect(summary.totalOutputVat).toBe(2500)
|
||
expect(summary.totalInputVat).toBe(1000)
|
||
expect(summary.vatToPay).toBe(1500)
|
||
expect(summary.isRefund).toBe(false)
|
||
})
|
||
|
||
it('identifies refund when ruta49 is negative', () => {
|
||
const declaration: VatDeclaration = {
|
||
period: { type: 'monthly', year: 2024, period: 1, start: '2024-01-01', end: '2024-01-31' },
|
||
rutor: {
|
||
ruta05: 2000, ruta06: 0, ruta07: 0,
|
||
ruta10: 500, ruta11: 0, ruta12: 0,
|
||
ruta20: 0, ruta21: 0, ruta22: 0, ruta23: 0, ruta24: 0,
|
||
ruta30: 0, ruta31: 0, ruta32: 0,
|
||
ruta39: 0, ruta40: 0,
|
||
ruta48: 3000, ruta49: -2500,
|
||
...zeroExtras,
|
||
},
|
||
invoiceCount: 1,
|
||
transactionCount: 20,
|
||
breakdown: {
|
||
invoices: { ruta05: 2000, ruta06: 0, ruta07: 0, ruta10: 500, ruta11: 0, ruta12: 0, ruta39: 0, ruta40: 0, base25: 2000, base12: 0, base6: 0 },
|
||
transactions: { ruta48: 3000 },
|
||
receipts: { ruta48: 0 },
|
||
reverseCharge: emptyRc,
|
||
},
|
||
}
|
||
|
||
const summary = getVatDeclarationSummary(declaration)
|
||
expect(summary.isRefund).toBe(true)
|
||
expect(summary.vatToPay).toBe(-2500)
|
||
})
|
||
|
||
it('includes ruta30-32 in totalOutputVat', () => {
|
||
const declaration: VatDeclaration = {
|
||
period: { type: 'monthly', year: 2024, period: 1, start: '2024-01-01', end: '2024-01-31' },
|
||
rutor: {
|
||
ruta05: 10000, ruta06: 0, ruta07: 0,
|
||
ruta10: 2500, ruta11: 0, ruta12: 0,
|
||
ruta20: 0, ruta21: 5000, ruta22: 0, ruta23: 0, ruta24: 0,
|
||
ruta30: 1250, ruta31: 0, ruta32: 0,
|
||
ruta39: 0, ruta40: 0,
|
||
ruta48: 2250, ruta49: 1500,
|
||
...zeroExtras,
|
||
},
|
||
invoiceCount: 2,
|
||
transactionCount: 0,
|
||
breakdown: {
|
||
invoices: { ruta05: 10000, ruta06: 0, ruta07: 0, ruta10: 2500, ruta11: 0, ruta12: 0, ruta39: 0, ruta40: 0, base25: 10000, base12: 0, base6: 0 },
|
||
transactions: { ruta48: 0 },
|
||
receipts: { ruta48: 0 },
|
||
reverseCharge: { ruta20: 0, ruta21: 5000, ruta22: 0, ruta23: 0, ruta24: 0, ruta30: 1250, ruta31: 0, ruta32: 0 },
|
||
},
|
||
}
|
||
|
||
const summary = getVatDeclarationSummary(declaration)
|
||
// totalOutputVat = ruta10 + ruta30 = 2500 + 1250 = 3750
|
||
expect(summary.totalOutputVat).toBe(3750)
|
||
})
|
||
})
|
||
|
||
// ============================================================
|
||
// Ledger-based VAT declaration tests
|
||
//
|
||
// The calculator makes ONE get_vat_declaration_totals RPC call per period
|
||
// (per-account totals + settlement-shaped entries + source_type counts in a
|
||
// single jsonb payload). Yearly periods with a fiscalPeriodId additionally
|
||
// look up fiscal_periods first. Settlement-shape exclusion (#984) lives in
|
||
// the RPC's SQL and is covered by the pg-real test
|
||
// (tests/pg/vat-declaration-totals-rpc.pg.test.ts).
|
||
// ============================================================
|
||
|
||
describe('calculateVatDeclaration', () => {
|
||
it('returns all zeros when no ledger lines exist', async () => {
|
||
seedLedger([])
|
||
|
||
const result = await calculateVatDeclaration(supabase, 'company-1', 'monthly', 2024, 1)
|
||
|
||
expect(result.rutor.ruta05).toBe(0)
|
||
expect(result.rutor.ruta10).toBe(0)
|
||
expect(result.rutor.ruta11).toBe(0)
|
||
expect(result.rutor.ruta12).toBe(0)
|
||
expect(result.rutor.ruta30).toBe(0)
|
||
expect(result.rutor.ruta31).toBe(0)
|
||
expect(result.rutor.ruta32).toBe(0)
|
||
expect(result.rutor.ruta48).toBe(0)
|
||
expect(result.rutor.ruta49).toBe(0)
|
||
expect(result.invoiceCount).toBe(0)
|
||
expect(result.transactionCount).toBe(0)
|
||
})
|
||
|
||
it('does not report a refundable deposit credited to a liability account as turnover', async () => {
|
||
seedLedger(
|
||
[
|
||
{ account_number: '1510', debit_amount: 10000, credit_amount: 0 },
|
||
{ account_number: '2897', debit_amount: 0, credit_amount: 10000 },
|
||
],
|
||
['invoice_created'],
|
||
)
|
||
|
||
const result = await calculateVatDeclaration(supabase, 'company-1', 'monthly', 2024, 1)
|
||
|
||
expect(result.rutor.ruta05).toBe(0)
|
||
expect(result.rutor.ruta42).toBe(0)
|
||
expect(result.rutor.ruta49).toBe(0)
|
||
expect(result.invoiceCount).toBe(1)
|
||
})
|
||
|
||
it('sums output VAT to ruta10/11/12 and revenue to ruta05', async () => {
|
||
seedLedger(
|
||
[
|
||
{ account_number: '2611', debit_amount: 0, credit_amount: 2500 },
|
||
{ account_number: '2621', debit_amount: 0, credit_amount: 600 },
|
||
{ account_number: '2631', debit_amount: 0, credit_amount: 180 },
|
||
{ account_number: '3001', debit_amount: 0, credit_amount: 10000 },
|
||
{ account_number: '3002', debit_amount: 0, credit_amount: 5000 },
|
||
{ account_number: '3003', debit_amount: 0, credit_amount: 3000 },
|
||
],
|
||
['invoice_created', 'invoice_created'],
|
||
)
|
||
|
||
const result = await calculateVatDeclaration(supabase, 'company-1', 'monthly', 2024, 1)
|
||
|
||
expect(result.rutor.ruta10).toBe(2500)
|
||
expect(result.rutor.ruta11).toBe(600)
|
||
expect(result.rutor.ruta12).toBe(180)
|
||
expect(result.rutor.ruta05).toBe(18000)
|
||
expect(result.breakdown.invoices.base25).toBe(10000)
|
||
expect(result.breakdown.invoices.base12).toBe(5000)
|
||
expect(result.breakdown.invoices.base6).toBe(3000)
|
||
expect(result.invoiceCount).toBe(2)
|
||
})
|
||
|
||
it('sums input VAT from 2641 debit balance', async () => {
|
||
seedLedger(
|
||
[
|
||
{ account_number: '2641', debit_amount: 250, credit_amount: 0 },
|
||
{ account_number: '2641', debit_amount: 120, credit_amount: 0 },
|
||
],
|
||
['bank_transaction', 'bank_transaction'],
|
||
)
|
||
|
||
const result = await calculateVatDeclaration(supabase, 'company-1', 'monthly', 2024, 1)
|
||
|
||
expect(result.rutor.ruta48).toBe(370)
|
||
expect(result.transactionCount).toBe(2)
|
||
})
|
||
|
||
it('includes calculated input VAT (2645) from EU reverse charge in ruta48', async () => {
|
||
seedLedger([
|
||
{ account_number: '2645', debit_amount: 500, credit_amount: 0 },
|
||
{ account_number: '2641', debit_amount: 200, credit_amount: 0 },
|
||
])
|
||
|
||
const result = await calculateVatDeclaration(supabase, 'company-1', 'monthly', 2024, 1)
|
||
|
||
expect(result.rutor.ruta48).toBe(700)
|
||
})
|
||
|
||
it('maps EU/export revenue to ruta39/ruta40', async () => {
|
||
seedLedger([
|
||
{ account_number: '3308', debit_amount: 0, credit_amount: 8000 },
|
||
{ account_number: '3305', debit_amount: 0, credit_amount: 12000 },
|
||
])
|
||
|
||
const result = await calculateVatDeclaration(supabase, 'company-1', 'monthly', 2024, 1)
|
||
|
||
expect(result.rutor.ruta39).toBe(8000)
|
||
expect(result.rutor.ruta40).toBe(12000)
|
||
})
|
||
|
||
it('handles credit notes as net reduction on revenue/VAT accounts', async () => {
|
||
seedLedger(
|
||
[
|
||
// Invoice: C2611 2500, C3001 10000
|
||
{ account_number: '2611', debit_amount: 0, credit_amount: 2500 },
|
||
{ account_number: '3001', debit_amount: 0, credit_amount: 10000 },
|
||
// Credit note reversal: D2611 625, D3001 2500
|
||
{ account_number: '2611', debit_amount: 625, credit_amount: 0 },
|
||
{ account_number: '3001', debit_amount: 2500, credit_amount: 0 },
|
||
],
|
||
['invoice_created', 'credit_note'],
|
||
)
|
||
|
||
const result = await calculateVatDeclaration(supabase, 'company-1', 'monthly', 2024, 1)
|
||
|
||
expect(result.rutor.ruta10).toBe(1875)
|
||
expect(result.rutor.ruta05).toBe(7500)
|
||
expect(result.invoiceCount).toBe(2)
|
||
})
|
||
|
||
it('calculates ruta49 as output minus input VAT', async () => {
|
||
seedLedger([
|
||
{ account_number: '2611', debit_amount: 0, credit_amount: 2500 },
|
||
{ account_number: '3001', debit_amount: 0, credit_amount: 10000 },
|
||
{ account_number: '2641', debit_amount: 350, credit_amount: 0 },
|
||
])
|
||
|
||
const result = await calculateVatDeclaration(supabase, 'company-1', 'monthly', 2024, 1)
|
||
|
||
expect(result.rutor.ruta10).toBe(2500)
|
||
expect(result.rutor.ruta05).toBe(10000)
|
||
expect(result.rutor.ruta48).toBe(350)
|
||
expect(result.rutor.ruta49).toBe(2150) // 2500 - 350
|
||
})
|
||
|
||
it('detects refund when input VAT exceeds output VAT', async () => {
|
||
seedLedger([
|
||
{ account_number: '2611', debit_amount: 0, credit_amount: 500 },
|
||
{ account_number: '2641', debit_amount: 3000, credit_amount: 0 },
|
||
])
|
||
|
||
const result = await calculateVatDeclaration(supabase, 'company-1', 'monthly', 2024, 1)
|
||
|
||
expect(result.rutor.ruta49).toBe(-2500) // 500 - 3000
|
||
})
|
||
|
||
|
||
it('throws a labelled error when the RPC fails', async () => {
|
||
results = [{ data: null, error: { message: 'permission denied' } }]
|
||
|
||
await expect(
|
||
calculateVatDeclaration(supabase, 'company-1', 'monthly', 2024, 1),
|
||
).rejects.toThrow('get_vat_declaration_totals failed: permission denied')
|
||
})
|
||
|
||
it('handles all three VAT rates in a single period', async () => {
|
||
seedLedger([
|
||
{ account_number: '3001', debit_amount: 0, credit_amount: 10000 },
|
||
{ account_number: '2611', debit_amount: 0, credit_amount: 2500 },
|
||
{ account_number: '3002', debit_amount: 0, credit_amount: 5000 },
|
||
{ account_number: '2621', debit_amount: 0, credit_amount: 600 },
|
||
{ account_number: '3003', debit_amount: 0, credit_amount: 3000 },
|
||
{ account_number: '2631', debit_amount: 0, credit_amount: 180 },
|
||
{ account_number: '2641', debit_amount: 1000, credit_amount: 0 },
|
||
])
|
||
|
||
const result = await calculateVatDeclaration(supabase, 'company-1', 'quarterly', 2024, 1)
|
||
|
||
expect(result.rutor.ruta10).toBe(2500)
|
||
expect(result.rutor.ruta11).toBe(600)
|
||
expect(result.rutor.ruta12).toBe(180)
|
||
expect(result.rutor.ruta05).toBe(18000)
|
||
expect(result.rutor.ruta48).toBe(1000)
|
||
expect(result.rutor.ruta49).toBe(2280)
|
||
})
|
||
})
|
||
|
||
// ============================================================
|
||
// Reverse charge: purchase bases (ruta 20-24) sourced from cost accounts
|
||
// ============================================================
|
||
|
||
describe('calculateVatDeclaration: reverse charge', () => {
|
||
it('maps 2614/2624/2634 credit balances to ruta30/31/32', async () => {
|
||
seedLedger([
|
||
{ account_number: '2614', debit_amount: 0, credit_amount: 1250 },
|
||
{ account_number: '2624', debit_amount: 0, credit_amount: 120 },
|
||
{ account_number: '2634', debit_amount: 0, credit_amount: 60 },
|
||
{ account_number: '2645', debit_amount: 1430, credit_amount: 0 },
|
||
])
|
||
|
||
const result = await calculateVatDeclaration(supabase, 'company-1', 'monthly', 2024, 1)
|
||
|
||
expect(result.rutor.ruta30).toBe(1250)
|
||
expect(result.rutor.ruta31).toBe(120)
|
||
expect(result.rutor.ruta32).toBe(60)
|
||
expect(result.rutor.ruta48).toBe(1430)
|
||
// ruta49 = (0+0+0 + 1250+120+60) - 1430 = 0
|
||
expect(result.rutor.ruta49).toBe(0)
|
||
})
|
||
|
||
it('includes ruta30-32 in ruta49 formula', async () => {
|
||
seedLedger([
|
||
{ account_number: '2611', debit_amount: 0, credit_amount: 2500 },
|
||
{ account_number: '3001', debit_amount: 0, credit_amount: 10000 },
|
||
{ account_number: '2614', debit_amount: 0, credit_amount: 500 },
|
||
{ account_number: '2641', debit_amount: 300, credit_amount: 0 },
|
||
{ account_number: '2645', debit_amount: 500, credit_amount: 0 },
|
||
])
|
||
|
||
const result = await calculateVatDeclaration(supabase, 'company-1', 'monthly', 2024, 1)
|
||
|
||
expect(result.rutor.ruta10).toBe(2500)
|
||
expect(result.rutor.ruta30).toBe(500)
|
||
expect(result.rutor.ruta48).toBe(800)
|
||
expect(result.rutor.ruta49).toBe(2200) // (2500 + 500) - 800
|
||
})
|
||
|
||
it('populates ruta20 from EU goods cost accounts (4515/4516/4517)', async () => {
|
||
// EU goods purchase: D 4515 25000, D 2645 6250, C 2614 6250, C 2440 25000
|
||
seedLedger([
|
||
{ account_number: '4515', debit_amount: 25000, credit_amount: 0 },
|
||
{ account_number: '2614', debit_amount: 0, credit_amount: 6250 },
|
||
{ account_number: '2645', debit_amount: 6250, credit_amount: 0 },
|
||
])
|
||
|
||
const result = await calculateVatDeclaration(supabase, 'company-1', 'monthly', 2024, 1)
|
||
|
||
expect(result.rutor.ruta20).toBe(25000)
|
||
expect(result.rutor.ruta21).toBe(0)
|
||
expect(result.rutor.ruta30).toBe(6250)
|
||
expect(result.rutor.ruta48).toBe(6250)
|
||
// Reverse charge is VAT-neutral: output VAT exactly offsets input VAT
|
||
expect(result.rutor.ruta49).toBe(0)
|
||
})
|
||
|
||
it('populates ruta21 from EU services cost accounts (4535/4536/4537)', async () => {
|
||
seedLedger([
|
||
{ account_number: '4535', debit_amount: 5000, credit_amount: 0 },
|
||
{ account_number: '2614', debit_amount: 0, credit_amount: 1250 },
|
||
{ account_number: '2645', debit_amount: 1250, credit_amount: 0 },
|
||
])
|
||
|
||
const result = await calculateVatDeclaration(supabase, 'company-1', 'monthly', 2024, 1)
|
||
|
||
expect(result.rutor.ruta21).toBe(5000)
|
||
expect(result.rutor.ruta20).toBe(0)
|
||
expect(result.rutor.ruta22).toBe(0)
|
||
expect(result.rutor.ruta30).toBe(1250)
|
||
expect(result.breakdown.reverseCharge.ruta21).toBe(5000)
|
||
expect(result.breakdown.reverseCharge.ruta30).toBe(1250)
|
||
})
|
||
|
||
it('populates ruta22 from non-EU services cost accounts (4531/4532/4533)', async () => {
|
||
// Anthropic-style: D 4531 3000, D 2645 750, C 2614 750, C 2440 3000
|
||
seedLedger([
|
||
{ account_number: '4531', debit_amount: 3000, credit_amount: 0 },
|
||
{ account_number: '2614', debit_amount: 0, credit_amount: 750 },
|
||
{ account_number: '2645', debit_amount: 750, credit_amount: 0 },
|
||
])
|
||
|
||
const result = await calculateVatDeclaration(supabase, 'company-1', 'monthly', 2024, 1)
|
||
|
||
expect(result.rutor.ruta22).toBe(3000)
|
||
expect(result.rutor.ruta21).toBe(0)
|
||
expect(result.rutor.ruta20).toBe(0)
|
||
expect(result.rutor.ruta30).toBe(750)
|
||
})
|
||
|
||
it('populates ruta23 from domestic goods reverse-charge cost accounts (4415/4416/4417)', async () => {
|
||
// Domestic mobile reverse charge: D 4415 100000, D 2647 25000, C 2614 25000, C 2440 100000
|
||
seedLedger([
|
||
{ account_number: '4415', debit_amount: 100000, credit_amount: 0 },
|
||
{ account_number: '2614', debit_amount: 0, credit_amount: 25000 },
|
||
{ account_number: '2647', debit_amount: 25000, credit_amount: 0 },
|
||
])
|
||
|
||
const result = await calculateVatDeclaration(supabase, 'company-1', 'monthly', 2024, 1)
|
||
|
||
expect(result.rutor.ruta23).toBe(100000)
|
||
expect(result.rutor.ruta24).toBe(0)
|
||
expect(result.rutor.ruta30).toBe(25000)
|
||
expect(result.rutor.ruta48).toBe(25000)
|
||
expect(result.rutor.ruta49).toBe(0) // VAT-neutral
|
||
})
|
||
|
||
it('populates ruta24 from domestic services reverse-charge cost accounts (4425/4426/4427)', async () => {
|
||
seedLedger([
|
||
{ account_number: '4425', debit_amount: 8000, credit_amount: 0 },
|
||
{ account_number: '2614', debit_amount: 0, credit_amount: 2000 },
|
||
{ account_number: '2647', debit_amount: 2000, credit_amount: 0 },
|
||
])
|
||
|
||
const result = await calculateVatDeclaration(supabase, 'company-1', 'monthly', 2024, 1)
|
||
|
||
expect(result.rutor.ruta24).toBe(8000)
|
||
expect(result.rutor.ruta23).toBe(0)
|
||
expect(result.rutor.ruta30).toBe(2000)
|
||
})
|
||
|
||
it('returns zero ruta20-24 when no reverse-charge cost-account activity', async () => {
|
||
seedLedger([
|
||
{ account_number: '2611', debit_amount: 0, credit_amount: 2500 },
|
||
{ account_number: '3001', debit_amount: 0, credit_amount: 10000 },
|
||
])
|
||
|
||
const result = await calculateVatDeclaration(supabase, 'company-1', 'monthly', 2024, 1)
|
||
|
||
expect(result.rutor.ruta20).toBe(0)
|
||
expect(result.rutor.ruta21).toBe(0)
|
||
expect(result.rutor.ruta22).toBe(0)
|
||
expect(result.rutor.ruta23).toBe(0)
|
||
expect(result.rutor.ruta24).toBe(0)
|
||
})
|
||
|
||
it('reverse-charge credit notes net out the cost-account debit balance', async () => {
|
||
// Original purchase: D 4535 5000; reversal (credit note): C 4535 1000
|
||
seedLedger([
|
||
{ account_number: '4535', debit_amount: 5000, credit_amount: 0 },
|
||
{ account_number: '4535', debit_amount: 0, credit_amount: 1000 },
|
||
{ account_number: '2614', debit_amount: 0, credit_amount: 1250 },
|
||
{ account_number: '2614', debit_amount: 250, credit_amount: 0 },
|
||
{ account_number: '2645', debit_amount: 1250, credit_amount: 0 },
|
||
{ account_number: '2645', debit_amount: 0, credit_amount: 250 },
|
||
])
|
||
|
||
const result = await calculateVatDeclaration(supabase, 'company-1', 'monthly', 2024, 1)
|
||
|
||
expect(result.rutor.ruta21).toBe(4000) // 5000 - 1000
|
||
expect(result.rutor.ruta30).toBe(1000) // 1250 - 250
|
||
expect(result.rutor.ruta48).toBe(1000) // 1250 - 250
|
||
})
|
||
|
||
it('maps domestic reverse-charge input VAT (2647) to ruta48', async () => {
|
||
seedLedger([
|
||
{ account_number: '2647', debit_amount: 500, credit_amount: 0 },
|
||
{ account_number: '2614', debit_amount: 0, credit_amount: 500 },
|
||
])
|
||
|
||
const result = await calculateVatDeclaration(supabase, 'company-1', 'monthly', 2024, 1)
|
||
|
||
expect(result.rutor.ruta48).toBe(500)
|
||
expect(result.rutor.ruta30).toBe(500)
|
||
expect(result.rutor.ruta49).toBe(0)
|
||
})
|
||
})
|
||
|
||
// ============================================================
|
||
// Import (ruta 50, 60-62) and Ruta 06 (uttag) and Ruta 42 (exempt)
|
||
// ============================================================
|
||
|
||
describe('calculateVatDeclaration: import, uttag, exempt', () => {
|
||
it('maps import VAT accounts (2615/2625/2635) to ruta60/61/62', async () => {
|
||
seedLedger([
|
||
{ account_number: '2615', debit_amount: 0, credit_amount: 2500 },
|
||
{ account_number: '2625', debit_amount: 0, credit_amount: 600 },
|
||
{ account_number: '2635', debit_amount: 0, credit_amount: 180 },
|
||
{ account_number: '2641', debit_amount: 3280, credit_amount: 0 },
|
||
])
|
||
|
||
const result = await calculateVatDeclaration(supabase, 'company-1', 'monthly', 2024, 1)
|
||
|
||
expect(result.rutor.ruta60).toBe(2500)
|
||
expect(result.rutor.ruta61).toBe(600)
|
||
expect(result.rutor.ruta62).toBe(180)
|
||
expect(result.rutor.ruta49).toBe(0) // 3280 - 3280
|
||
})
|
||
|
||
it('populates ruta50 (import beskattningsunderlag) from 4545-4547', async () => {
|
||
// Full import flow: D 4545 10000, C 2615 2500, D 2641 2500
|
||
seedLedger([
|
||
{ account_number: '4545', debit_amount: 10000, credit_amount: 0 },
|
||
{ account_number: '2615', debit_amount: 0, credit_amount: 2500 },
|
||
{ account_number: '2641', debit_amount: 2500, credit_amount: 0 },
|
||
])
|
||
|
||
const result = await calculateVatDeclaration(supabase, 'company-1', 'monthly', 2024, 1)
|
||
|
||
// Ruta 50 (base) and Ruta 60 (output VAT) BOTH non-zero: required by SKV §4.1.1.4
|
||
// ERROR rule "Det måste finnas ett belopp i fält 50, eftersom det finns ett belopp i 60-62"
|
||
expect(result.rutor.ruta50).toBe(10000)
|
||
expect(result.rutor.ruta60).toBe(2500)
|
||
expect(result.rutor.ruta48).toBe(2500)
|
||
})
|
||
|
||
it('populates ruta06 from uttag accounts (3401/3402/3403)', async () => {
|
||
// Uttag: D 2010 (private withdrawal); C 3401 1000 + C 2612 250 (25% rate uttag)
|
||
seedLedger([
|
||
{ account_number: '3401', debit_amount: 0, credit_amount: 1000 },
|
||
{ account_number: '2612', debit_amount: 0, credit_amount: 250 },
|
||
])
|
||
|
||
const result = await calculateVatDeclaration(supabase, 'company-1', 'monthly', 2024, 1)
|
||
|
||
expect(result.rutor.ruta06).toBe(1000)
|
||
expect(result.rutor.ruta10).toBe(250) // 2612 maps to ruta10 (25% output VAT including uttag)
|
||
})
|
||
|
||
it('expanded ruta42 covers 3004, 3100, 3404, 3994, 3980', async () => {
|
||
seedLedger([
|
||
{ account_number: '3004', debit_amount: 0, credit_amount: 1000 },
|
||
{ account_number: '3100', debit_amount: 0, credit_amount: 2000 },
|
||
{ account_number: '3404', debit_amount: 0, credit_amount: 500 },
|
||
{ account_number: '3980', debit_amount: 0, credit_amount: 3000 },
|
||
{ account_number: '3994', debit_amount: 0, credit_amount: 1500 },
|
||
])
|
||
|
||
const result = await calculateVatDeclaration(supabase, 'company-1', 'monthly', 2024, 1)
|
||
|
||
expect(result.rutor.ruta42).toBe(8000) // 1000+2000+500+3000+1500
|
||
})
|
||
|
||
it('maps EU/export revenue variants (3108/3105) to ruta35/36', async () => {
|
||
seedLedger([
|
||
{ account_number: '3108', debit_amount: 0, credit_amount: 15000 },
|
||
{ account_number: '3105', debit_amount: 0, credit_amount: 8000 },
|
||
])
|
||
|
||
const result = await calculateVatDeclaration(supabase, 'company-1', 'monthly', 2024, 1)
|
||
|
||
expect(result.rutor.ruta35).toBe(15000)
|
||
expect(result.rutor.ruta36).toBe(8000)
|
||
})
|
||
|
||
it('maps output VAT variant accounts (2612/2623/2636) to correct rutor', async () => {
|
||
seedLedger([
|
||
{ account_number: '2612', debit_amount: 0, credit_amount: 1000 }, // egna uttag 25%
|
||
{ account_number: '2623', debit_amount: 0, credit_amount: 200 }, // uthyrning 12%
|
||
{ account_number: '2636', debit_amount: 0, credit_amount: 50 }, // VMB 6%
|
||
])
|
||
|
||
const result = await calculateVatDeclaration(supabase, 'company-1', 'monthly', 2024, 1)
|
||
|
||
expect(result.rutor.ruta10).toBe(1000)
|
||
expect(result.rutor.ruta11).toBe(200)
|
||
expect(result.rutor.ruta12).toBe(50)
|
||
})
|
||
|
||
it('handles zero output VAT on some rates but non-zero on others', async () => {
|
||
seedLedger(
|
||
[
|
||
{ account_number: '2621', debit_amount: 0, credit_amount: 600 },
|
||
{ account_number: '3002', debit_amount: 0, credit_amount: 5000 },
|
||
{ account_number: '2641', debit_amount: 200, credit_amount: 0 },
|
||
],
|
||
['invoice_created'],
|
||
)
|
||
|
||
const result = await calculateVatDeclaration(supabase, 'company-1', 'monthly', 2024, 1)
|
||
|
||
expect(result.rutor.ruta10).toBe(0)
|
||
expect(result.rutor.ruta11).toBe(600)
|
||
expect(result.rutor.ruta12).toBe(0)
|
||
expect(result.rutor.ruta48).toBe(200)
|
||
expect(result.rutor.ruta49).toBe(400) // 600 - 200
|
||
})
|
||
|
||
it('rounds sub-öre amounts via Math.round * 100 / 100', async () => {
|
||
seedLedger([
|
||
{ account_number: '2611', debit_amount: 0, credit_amount: 0.001 },
|
||
{ account_number: '3001', debit_amount: 0, credit_amount: 0.004 },
|
||
])
|
||
|
||
const result = await calculateVatDeclaration(supabase, 'company-1', 'monthly', 2024, 1)
|
||
|
||
expect(result.rutor.ruta10).toBe(0)
|
||
expect(result.rutor.ruta05).toBe(0)
|
||
})
|
||
})
|
||
|
||
// ============================================================
|
||
// SKV §4.1.1.4 cross-field contract checks
|
||
//
|
||
// Skatteverket's kontrollera endpoint runs these checks server-side. Mirror
|
||
// them locally so we catch declaration drift in unit tests, before a network
|
||
// call. ERROR rules block submission; WARNING rules don't.
|
||
// ============================================================
|
||
|
||
describe('SKV §4.1.1.4 cross-field contracts', () => {
|
||
it('ERROR: taxable sales base requires output VAT (rule 1)', async () => {
|
||
// SKV: if any of momspliktigForsaljning/momspliktigaUttag/vinstmarginal/hyresInkomst > 0,
|
||
// at least one of momsForsaljningUtgaende{Hog,Medel,Lag} must be > 0.
|
||
seedLedger([
|
||
{ account_number: '3001', debit_amount: 0, credit_amount: 10000 },
|
||
// No 2611/2621/2631 booked: would trigger SKV ERROR
|
||
])
|
||
|
||
const result = await calculateVatDeclaration(supabase, 'company-1', 'monthly', 2024, 1)
|
||
const r = result.rutor
|
||
|
||
const hasBase = r.ruta05 + r.ruta06 + r.ruta07 + r.ruta08 > 0
|
||
const hasOutput = r.ruta10 + r.ruta11 + r.ruta12 > 0
|
||
expect(hasBase).toBe(true)
|
||
expect(hasOutput).toBe(false)
|
||
// Local invariant: this combination would fail SKV kontrollera with ERROR.
|
||
// The calculator does not auto-correct: the ledger must be fixed upstream.
|
||
})
|
||
|
||
it('ERROR: reverse-charge purchase base requires output VAT (rule 3)', async () => {
|
||
// If any of inkopVarorEU/inkopTjansterEU/inkopTjansterUtanforEU/inkopVarorSE/inkopTjansterSE > 0,
|
||
// at least one of momsInkopUtgaende{Hog,Medel,Lag} must be > 0.
|
||
seedLedger([
|
||
{ account_number: '4535', debit_amount: 5000, credit_amount: 0 },
|
||
// No 2614/2624/2634 booked: would trigger SKV ERROR
|
||
])
|
||
|
||
const result = await calculateVatDeclaration(supabase, 'company-1', 'monthly', 2024, 1)
|
||
const r = result.rutor
|
||
|
||
const hasRcBase = r.ruta20 + r.ruta21 + r.ruta22 + r.ruta23 + r.ruta24 > 0
|
||
const hasRcOutput = r.ruta30 + r.ruta31 + r.ruta32 > 0
|
||
expect(hasRcBase).toBe(true)
|
||
expect(hasRcOutput).toBe(false)
|
||
})
|
||
|
||
it('ERROR: import base requires import output VAT (rule 5)', async () => {
|
||
// If import (ruta50) > 0, at least one of momsImportUtgaende{Hog,Medel,Lag} must be > 0.
|
||
seedLedger([
|
||
{ account_number: '4545', debit_amount: 10000, credit_amount: 0 },
|
||
// No 2615/2625/2635 booked: would trigger SKV ERROR
|
||
])
|
||
|
||
const result = await calculateVatDeclaration(supabase, 'company-1', 'monthly', 2024, 1)
|
||
const r = result.rutor
|
||
|
||
expect(r.ruta50).toBe(10000)
|
||
expect(r.ruta60 + r.ruta61 + r.ruta62).toBe(0)
|
||
})
|
||
|
||
it('ERROR: import output VAT requires import base (rule 6)', async () => {
|
||
// If any of momsImportUtgaende{Hog,Medel,Lag} > 0, import (ruta50) must be > 0.
|
||
// This is the BLOCKER scenario the Phase 1b refactor fixes: previously ruta50 was
|
||
// never populated, so any import VAT booking would fail SKV's contract.
|
||
seedLedger([
|
||
{ account_number: '2615', debit_amount: 0, credit_amount: 2500 },
|
||
{ account_number: '2641', debit_amount: 2500, credit_amount: 0 },
|
||
{ account_number: '4545', debit_amount: 10000, credit_amount: 0 },
|
||
])
|
||
|
||
const result = await calculateVatDeclaration(supabase, 'company-1', 'monthly', 2024, 1)
|
||
const r = result.rutor
|
||
|
||
// Both populated: passes SKV's rule 6
|
||
expect(r.ruta50).toBe(10000)
|
||
expect(r.ruta60).toBe(2500)
|
||
})
|
||
|
||
it('ERROR: summaMoms must equal (ruta10+11+12+30+31+32+60+61+62) − ruta48 (rule 7)', async () => {
|
||
// The calculator computes ruta49 from the formula directly, so this invariant
|
||
// holds by construction. This test is the canary that catches drift if anyone
|
||
// ever adds an extra term or rate to the form.
|
||
seedLedger([
|
||
{ account_number: '2611', debit_amount: 0, credit_amount: 2500 },
|
||
{ account_number: '2621', debit_amount: 0, credit_amount: 600 },
|
||
{ account_number: '2631', debit_amount: 0, credit_amount: 180 },
|
||
{ account_number: '2614', debit_amount: 0, credit_amount: 1250 },
|
||
{ account_number: '2615', debit_amount: 0, credit_amount: 500 },
|
||
{ account_number: '2641', debit_amount: 1000, credit_amount: 0 },
|
||
{ account_number: '2645', debit_amount: 1250, credit_amount: 0 },
|
||
])
|
||
|
||
const result = await calculateVatDeclaration(supabase, 'company-1', 'monthly', 2024, 1)
|
||
const r = result.rutor
|
||
|
||
const expected = r.ruta10 + r.ruta11 + r.ruta12
|
||
+ r.ruta30 + r.ruta31 + r.ruta32
|
||
+ r.ruta60 + r.ruta61 + r.ruta62
|
||
- r.ruta48
|
||
expect(r.ruta49).toBe(expected)
|
||
})
|
||
})
|
||
|
||
// ============================================================
|
||
// Parent/summary BAS accounts: 2610/2620/2630 (output),
|
||
// 2618/2628/2638 (vilande), 2640 (input parent).
|
||
//
|
||
// Users who post directly to the group account (manual entries, SIE imports,
|
||
// alternate templates) had their balances silently dropped before this fix
|
||
// because only the leaf accounts were mapped.
|
||
// ============================================================
|
||
|
||
describe('calculateVatDeclaration: parent/summary accounts', () => {
|
||
it('maps 2610 (parent) to ruta10 when posted directly', async () => {
|
||
seedLedger([
|
||
{ account_number: '3001', debit_amount: 0, credit_amount: 10000 },
|
||
{ account_number: '2610', debit_amount: 0, credit_amount: 2500 },
|
||
])
|
||
|
||
const result = await calculateVatDeclaration(supabase, 'company-1', 'monthly', 2024, 1)
|
||
|
||
expect(result.rutor.ruta05).toBe(10000)
|
||
expect(result.rutor.ruta10).toBe(2500)
|
||
expect(result.rutor.ruta49).toBe(2500) // owed, not refund
|
||
})
|
||
|
||
it('maps 2620 (parent) to ruta11 and 2630 (parent) to ruta12', async () => {
|
||
seedLedger([
|
||
{ account_number: '2620', debit_amount: 0, credit_amount: 600 },
|
||
{ account_number: '2630', debit_amount: 0, credit_amount: 180 },
|
||
])
|
||
|
||
const result = await calculateVatDeclaration(supabase, 'company-1', 'monthly', 2024, 1)
|
||
|
||
expect(result.rutor.ruta11).toBe(600)
|
||
expect(result.rutor.ruta12).toBe(180)
|
||
})
|
||
|
||
it('maps vilande output VAT (2618/2628/2638) to ruta10/11/12', async () => {
|
||
// Vilande accounts hold output VAT for invoices that have been sent but not
|
||
// yet paid, used by cash-method bookkeepers per BFNAR 2006:1.
|
||
seedLedger([
|
||
{ account_number: '2618', debit_amount: 0, credit_amount: 500 },
|
||
{ account_number: '2628', debit_amount: 0, credit_amount: 120 },
|
||
{ account_number: '2638', debit_amount: 0, credit_amount: 60 },
|
||
])
|
||
|
||
const result = await calculateVatDeclaration(supabase, 'company-1', 'monthly', 2024, 1)
|
||
|
||
expect(result.rutor.ruta10).toBe(500)
|
||
expect(result.rutor.ruta11).toBe(120)
|
||
expect(result.rutor.ruta12).toBe(60)
|
||
})
|
||
|
||
it('sums parent and sub-account balances on the same ruta', async () => {
|
||
// If a ledger has activity on both the parent and the sub-accounts (mixed
|
||
// bookkeeping practice, SIE imports, etc.), the ruta reflects the literal
|
||
// ledger total: accounting truth wins.
|
||
seedLedger([
|
||
{ account_number: '2610', debit_amount: 0, credit_amount: 1000 },
|
||
{ account_number: '2611', debit_amount: 0, credit_amount: 500 },
|
||
])
|
||
|
||
const result = await calculateVatDeclaration(supabase, 'company-1', 'monthly', 2024, 1)
|
||
|
||
expect(result.rutor.ruta10).toBe(1500)
|
||
})
|
||
|
||
it('maps 2640 (input VAT parent) to ruta48', async () => {
|
||
seedLedger([
|
||
{ account_number: '2640', debit_amount: 200, credit_amount: 0 },
|
||
])
|
||
|
||
const result = await calculateVatDeclaration(supabase, 'company-1', 'monthly', 2024, 1)
|
||
|
||
expect(result.rutor.ruta48).toBe(200)
|
||
expect(result.rutor.ruta49).toBe(-200) // refund
|
||
})
|
||
|
||
it('reproduces the user-reported bug: 2610 balance now reaches ruta10', async () => {
|
||
// Customer screenshot scenario (simplified): 3001 + 2610 booked with the
|
||
// correct VAT amount on the parent account. Before the fix, ruta10 read 0
|
||
// and ruta49 incorrectly showed a refund.
|
||
// Yearly without fiscalPeriodId now looks up the räkenskapsår ending in
|
||
// the year first; no fiscal period rows → calendar fallback.
|
||
results = [{ data: null, error: null }]
|
||
seedLedger([
|
||
{ account_number: '3001', debit_amount: 0, credit_amount: 21600 },
|
||
{ account_number: '2610', debit_amount: 0, credit_amount: 9768 },
|
||
{ account_number: '2641', debit_amount: 7048.45, credit_amount: 0 },
|
||
])
|
||
|
||
const result = await calculateVatDeclaration(supabase, 'company-1', 'yearly', 2025, 1)
|
||
|
||
expect(result.rutor.ruta05).toBe(21600)
|
||
expect(result.rutor.ruta10).toBe(9768)
|
||
expect(result.rutor.ruta48).toBe(7048.45)
|
||
expect(result.rutor.ruta49).toBe(2719.55) // 9768 − 7048.45, owed (was −7048.45 pre-fix)
|
||
})
|
||
})
|
||
|
||
describe('calculateVatDeclaration: annual VAT spans the räkenskapsår', () => {
|
||
it('uses the fiscal period bounds for yearly when a fiscalPeriodId is given', async () => {
|
||
// Förlängt räkenskapsår (extended first year, 18 months): annual VAT
|
||
// (helårsmoms) must cover the whole period, not the calendar year that
|
||
// period_start falls in. The first queued result feeds the fiscal_periods
|
||
// lookup; seedLedger then queues the RPC payload.
|
||
results = [
|
||
{ data: { period_start: '2025-07-03', period_end: '2026-12-31' }, error: null },
|
||
]
|
||
seedLedger([
|
||
{ account_number: '3001', debit_amount: 0, credit_amount: 21600 },
|
||
{ account_number: '2610', debit_amount: 0, credit_amount: 9768 },
|
||
{ account_number: '2641', debit_amount: 7048.45, credit_amount: 0 },
|
||
])
|
||
|
||
const result = await calculateVatDeclaration(
|
||
supabase, 'company-1', 'yearly', 2026, 1, 'accrual', { fiscalPeriodId: 'fp-1' },
|
||
)
|
||
|
||
expect(result.period.start).toBe('2025-07-03')
|
||
expect(result.period.end).toBe('2026-12-31')
|
||
expect(result.rutor.ruta05).toBe(21600)
|
||
expect(result.rutor.ruta10).toBe(9768)
|
||
expect(result.rutor.ruta48).toBe(7048.45)
|
||
})
|
||
|
||
it('falls back to the calendar year when the fiscal period cannot be resolved', async () => {
|
||
results = [
|
||
{ data: null, error: null }, // fiscal_periods lookup → not found
|
||
]
|
||
seedLedger([])
|
||
|
||
const result = await calculateVatDeclaration(
|
||
supabase, 'company-1', 'yearly', 2026, 1, 'accrual', { fiscalPeriodId: 'missing' },
|
||
)
|
||
|
||
expect(result.period.start).toBe('2026-01-01')
|
||
expect(result.period.end).toBe('2026-12-31')
|
||
})
|
||
|
||
it('resolves the räkenskapsår ending in the year for yearly WITHOUT a fiscalPeriodId', async () => {
|
||
// Broken FY 2025-07-01 → 2026-06-30: a yearly submission for 2026 with no
|
||
// explicit fiscal period (e.g. before the FY selector populated) must
|
||
// still target the actual räkenskapsår, not calendar 2026
|
||
// (SFL 26 kap 10-11 §§).
|
||
results = [
|
||
{ data: { period_start: '2025-07-01', period_end: '2026-06-30' }, error: null },
|
||
]
|
||
seedLedger([])
|
||
|
||
const result = await calculateVatDeclaration(
|
||
supabase, 'company-1', 'yearly', 2026, 1, 'accrual',
|
||
)
|
||
|
||
expect(result.period.start).toBe('2025-07-01')
|
||
expect(result.period.end).toBe('2026-06-30')
|
||
})
|
||
|
||
it('falls back to the calendar year for yearly without a fiscalPeriodId when no fiscal period exists', async () => {
|
||
results = [
|
||
{ data: null, error: null }, // no fiscal period ending in 2026
|
||
]
|
||
seedLedger([])
|
||
|
||
const result = await calculateVatDeclaration(
|
||
supabase, 'company-1', 'yearly', 2026, 1, 'accrual',
|
||
)
|
||
|
||
expect(result.period.start).toBe('2026-01-01')
|
||
expect(result.period.end).toBe('2026-12-31')
|
||
})
|
||
|
||
it('ignores fiscalPeriodId for monthly periods (calendar month, no lookup)', async () => {
|
||
seedLedger([])
|
||
|
||
const result = await calculateVatDeclaration(
|
||
supabase, 'company-1', 'monthly', 2026, 3, 'accrual', { fiscalPeriodId: 'fp-1' },
|
||
)
|
||
|
||
expect(result.period.start).toBe('2026-03-01')
|
||
expect(result.period.end).toBe('2026-03-31')
|
||
// The räkenskapsår path is yearly-only: monthly makes no table query at
|
||
// all, just the single totals RPC.
|
||
expect(supabase.from).not.toHaveBeenCalled()
|
||
expect(supabase.rpc).toHaveBeenCalledTimes(1)
|
||
})
|
||
})
|
||
|
||
// ============================================================
|
||
// The reverse-charge input pair that travels with the declaration
|
||
// ============================================================
|
||
//
|
||
// Why the declaration carries 2645/2647 at all: runVatDeclarationChecks only
|
||
// runs the sharp RC_INPUT_VAT_MISMATCH comparison when a caller hands it
|
||
// per-account totals. The web UI reads the declaration over HTTP and has no
|
||
// ledger access of its own, so without this pair on the response it was stuck
|
||
// with the ruta 48 fallback, and ruta 48 aggregates 2640-2649: ordinary
|
||
// debiterad ingående moms on 2641 hid a completely missing RC input.
|
||
|
||
/**
|
||
* Same per-account aggregation seedLedger feeds the RPC mock, as the FULL totals
|
||
* map. Used to prove the 2-entry projection produces identical findings, which
|
||
* is also what pins RC_INPUT_VAT_ACCOUNTS to the private RC_INPUT_ACCOUNTS list
|
||
* inside vat-declaration-checks: the fixtures below carry a balance on every
|
||
* OTHER ruta 48 account, so if one of them ever counted as reverse-charge input
|
||
* the two maps would disagree here.
|
||
*/
|
||
function totalsFromLines(
|
||
lines: Array<{ account_number: string; debit_amount: number; credit_amount: number }>,
|
||
): Map<string, { debit: number; credit: number }> {
|
||
const byAccount = new Map<string, { debit: number; credit: number }>()
|
||
for (const l of lines) {
|
||
const t = byAccount.get(l.account_number) ?? { debit: 0, credit: 0 }
|
||
t.debit += l.debit_amount
|
||
t.credit += l.credit_amount
|
||
byAccount.set(l.account_number, t)
|
||
}
|
||
return byAccount
|
||
}
|
||
|
||
const debit = (account_number: string, debit_amount: number) =>
|
||
({ account_number, debit_amount, credit_amount: 0 })
|
||
const credit = (account_number: string, credit_amount: number) =>
|
||
({ account_number, debit_amount: 0, credit_amount })
|
||
|
||
/**
|
||
* The masking case, as a ledger: 50 000 kr of fiktiv utgående moms (2614) with
|
||
* its basbelopp correctly on 4535, no beräknad ingående moms at all, and 60 000
|
||
* kr of ordinary 2641 alongside it. Every other ruta 48 account carries a
|
||
* balance too, so ruta 48 (70 000) stays above the RC output and the aggregate
|
||
* comparison is silent while 50 000 kr of deductible moms is missing.
|
||
*/
|
||
const MASKED_RC_LINES = [
|
||
debit('4535', 200000), // ruta 21 basis: 50 000 / 0.25, so no FK004 finding
|
||
credit('2614', 50000), // ruta 30 fiktiv utgående moms
|
||
debit('2641', 60000), // ordinary debiterad ingående moms: the mask
|
||
debit('2640', 1000),
|
||
debit('2642', 2000),
|
||
debit('2646', 3000),
|
||
debit('2649', 4000), // blandad verksamhet: deliberately NOT reverse-charge input
|
||
]
|
||
|
||
describe('calculateVatDeclaration: rcInputAccountTotals', () => {
|
||
it('exposes both RC input accounts, netting credits against debits', async () => {
|
||
seedLedger([
|
||
debit('2645', 12000),
|
||
credit('2645', 2000), // storno of one fiktiv-moms pair
|
||
debit('2647', 500),
|
||
debit('2641', 60000), // not part of the pair
|
||
])
|
||
|
||
const result = await calculateVatDeclaration(supabase, 'company-1', 'monthly', 2026, 1)
|
||
|
||
expect(result.rcInputAccountTotals).toEqual({
|
||
'2645': { debit: 12000, credit: 2000 },
|
||
'2647': { debit: 500, credit: 0 },
|
||
})
|
||
// Only the pair, never the rest of the period's account balances.
|
||
expect(Object.keys(result.rcInputAccountTotals!)).toEqual(['2645', '2647'])
|
||
})
|
||
|
||
it('carries both keys as zeros when the period has no RC input', async () => {
|
||
seedLedger([debit('2641', 60000)])
|
||
|
||
const result = await calculateVatDeclaration(supabase, 'company-1', 'monthly', 2026, 1)
|
||
|
||
// Present-and-zero, not absent: absent has to keep meaning "this producer
|
||
// does not carry the pair", which is what the HTTP fallback reads.
|
||
expect(result.rcInputAccountTotals).toEqual({
|
||
'2645': { debit: 0, credit: 0 },
|
||
'2647': { debit: 0, credit: 0 },
|
||
})
|
||
})
|
||
|
||
it('warns on the masked RC shortfall, which the ruta 48 fallback misses', async () => {
|
||
seedLedger(MASKED_RC_LINES)
|
||
|
||
const declaration = await calculateVatDeclaration(supabase, 'company-1', 'monthly', 2026, 1)
|
||
|
||
expect(declaration.rutor.ruta30).toBe(50000)
|
||
expect(declaration.rutor.ruta48).toBe(70000)
|
||
|
||
// Unwired: no second argument, so the check compares against ruta 48 and
|
||
// says nothing at all.
|
||
expect(runVatDeclarationChecks(declaration.rutor)).toEqual([])
|
||
|
||
// Wired the way the web UI now calls it.
|
||
const findings = runVatDeclarationChecks(
|
||
declaration.rutor,
|
||
rcInputTotalsFromDeclaration(declaration),
|
||
)
|
||
const mismatch = findings.find((f) => f.code === 'RC_INPUT_VAT_MISMATCH')
|
||
expect(mismatch?.status).toBe('WARNING')
|
||
// \s, not a literal space: sv-SE groups thousands with a no-break space.
|
||
expect(mismatch?.message).toMatch(/50\s000 kr saknas/)
|
||
})
|
||
|
||
it('behaves identically on the 2-entry projection and the full totals map', async () => {
|
||
seedLedger(MASKED_RC_LINES)
|
||
const declaration = await calculateVatDeclaration(supabase, 'company-1', 'monthly', 2026, 1)
|
||
|
||
expect(
|
||
runVatDeclarationChecks(declaration.rutor, rcInputTotalsFromDeclaration(declaration)),
|
||
).toEqual(
|
||
runVatDeclarationChecks(declaration.rutor, totalsFromLines(MASKED_RC_LINES)),
|
||
)
|
||
})
|
||
|
||
it('behaves identically on a partial shortfall too, values and not just zeros', async () => {
|
||
const lines = [...MASKED_RC_LINES, debit('2645', 20000)] // 20 000 of the 50 000 booked
|
||
seedLedger(lines)
|
||
const declaration = await calculateVatDeclaration(supabase, 'company-1', 'monthly', 2026, 1)
|
||
|
||
const projected = runVatDeclarationChecks(
|
||
declaration.rutor,
|
||
rcInputTotalsFromDeclaration(declaration),
|
||
)
|
||
expect(projected).toEqual(
|
||
runVatDeclarationChecks(declaration.rutor, totalsFromLines(lines)),
|
||
)
|
||
expect(
|
||
projected.find((f) => f.code === 'RC_INPUT_VAT_MISMATCH')?.message,
|
||
).toMatch(/30\s000 kr saknas/)
|
||
})
|
||
|
||
it('stays silent when 2645 mirrors the fiktiv utgående moms exactly', async () => {
|
||
seedLedger([...MASKED_RC_LINES, debit('2645', 50000)])
|
||
const declaration = await calculateVatDeclaration(supabase, 'company-1', 'monthly', 2026, 1)
|
||
|
||
expect(
|
||
runVatDeclarationChecks(declaration.rutor, rcInputTotalsFromDeclaration(declaration)),
|
||
).toEqual([])
|
||
})
|
||
|
||
it('leaves a company with no reverse charge at all untouched', async () => {
|
||
// Plain domestic SEK trading: sales with output VAT and ordinary input VAT.
|
||
seedLedger([
|
||
credit('3001', 400000),
|
||
credit('2611', 100000),
|
||
debit('2641', 60000),
|
||
])
|
||
const declaration = await calculateVatDeclaration(supabase, 'company-1', 'monthly', 2026, 1)
|
||
|
||
expect(
|
||
runVatDeclarationChecks(declaration.rutor, rcInputTotalsFromDeclaration(declaration)),
|
||
).toEqual([])
|
||
expect(runVatDeclarationChecks(declaration.rutor)).toEqual([])
|
||
})
|
||
})
|
||
|
||
describe('rcInputTotalsFromDeclaration', () => {
|
||
it('rebuilds the map the checks consume, keyed by account number', () => {
|
||
const map = rcInputTotalsFromDeclaration({
|
||
rcInputAccountTotals: { '2645': { debit: 1250, credit: 0 }, '2647': { debit: 0, credit: 0 } },
|
||
})
|
||
expect(map?.get('2645')).toEqual({ debit: 1250, credit: 0 })
|
||
expect(map?.size).toBe(2)
|
||
})
|
||
|
||
it('returns undefined, not an empty map, when the pair is absent', () => {
|
||
// A response from a deploy that predates the field. undefined makes the
|
||
// check fall back to ruta 48; an empty map would read as "0 kr beräknad
|
||
// ingående moms" and turn a correct declaration into a false warning.
|
||
expect(rcInputTotalsFromDeclaration({})).toBeUndefined()
|
||
})
|
||
})
|
||
|
||
// #984 (settlement-shaped entries never zero the report) moved to
|
||
// tests/pg/vat-declaration-totals-rpc.pg.test.ts: the shape detection and
|
||
// exclusion now live inside the get_vat_declaration_totals RPC, so the
|
||
// behavior is verified against real Postgres rather than a mocked client.
|