* 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>
1078 lines
37 KiB
TypeScript
1078 lines
37 KiB
TypeScript
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
|
import type { CreateJournalEntryInput, Currency } from '@/types'
|
|
import { makeInvoice, makeSupplierInvoice } from '@/tests/helpers'
|
|
import { getErrorMessage } from '@/lib/errors/get-error-message'
|
|
|
|
// Mock riksbanken. The revaluation deliberately uses fetchExchangeRate, the
|
|
// documented booking path that returns null rather than one of the hardcoded
|
|
// display-only fallback constants, so the mock returns null for any currency
|
|
// the test did not price.
|
|
vi.mock('@/lib/currency/riksbanken', () => ({
|
|
fetchExchangeRate: vi.fn(),
|
|
}))
|
|
|
|
// Mock engine
|
|
vi.mock('../engine', () => ({
|
|
createJournalEntry: vi.fn().mockImplementation(
|
|
async (_supabase: unknown, _companyId: string, _userId: string, input: CreateJournalEntryInput) => ({
|
|
id: 'entry-1',
|
|
...input,
|
|
lines: input.lines,
|
|
status: 'posted',
|
|
voucher_number: 1,
|
|
voucher_series: 'A',
|
|
user_id: _userId,
|
|
committed_at: '2024-12-31T00:00:00Z',
|
|
reversed_by_id: null,
|
|
reverses_id: null,
|
|
correction_of_id: null,
|
|
attachment_urls: null,
|
|
created_at: '2024-12-31T00:00:00Z',
|
|
updated_at: '2024-12-31T00:00:00Z',
|
|
})
|
|
),
|
|
}))
|
|
|
|
// Mock supabase server
|
|
vi.mock('@/lib/supabase/server', () => ({
|
|
createClient: vi.fn(),
|
|
}))
|
|
|
|
const { fetchExchangeRate } = await import('@/lib/currency/riksbanken')
|
|
const mockedFetchRate = vi.mocked(fetchExchangeRate)
|
|
|
|
const { createJournalEntry } = await import('../engine')
|
|
const mockedCreateEntry = vi.mocked(createJournalEntry)
|
|
|
|
const {
|
|
getOpenForeignCurrencyReceivables,
|
|
getOpenForeignCurrencyPayables,
|
|
previewCurrencyRevaluation,
|
|
executeCurrencyRevaluation,
|
|
} = await import('../currency-revaluation')
|
|
|
|
/**
|
|
* Price the given currencies. Anything not listed resolves to null, which is
|
|
* exactly what fetchExchangeRate does when Riksbanken is unreachable and the
|
|
* cache is empty: no rate at all, never a fabricated one.
|
|
*/
|
|
function mockRates(rates: Partial<Record<Currency, number>>) {
|
|
mockedFetchRate.mockImplementation(async (currency: Currency) => {
|
|
const rate = rates[currency]
|
|
return rate === undefined ? null : { currency, rate, date: '2024-12-31' }
|
|
})
|
|
}
|
|
|
|
// Helper to build mock supabase
|
|
function createMockSupabase(config: {
|
|
invoices?: ReturnType<typeof makeInvoice>[]
|
|
supplierInvoices?: ReturnType<typeof makeSupplierInvoice>[]
|
|
existingRevaluation?: boolean
|
|
}) {
|
|
const fromMap: Record<string, unknown[]> = {
|
|
invoices: config.invoices || [],
|
|
supplier_invoices: config.supplierInvoices || [],
|
|
}
|
|
|
|
const supabase = {
|
|
from: vi.fn().mockImplementation((table: string) => {
|
|
if (table === 'journal_entries') {
|
|
// For idempotency check
|
|
return {
|
|
select: vi.fn().mockReturnValue({
|
|
eq: vi.fn().mockReturnThis(),
|
|
then: undefined,
|
|
count: undefined,
|
|
// Build chain that resolves with count
|
|
...((() => {
|
|
const chain: Record<string, unknown> = {}
|
|
chain.eq = vi.fn().mockReturnValue(chain)
|
|
chain.select = vi.fn().mockReturnValue(chain)
|
|
// Terminal: return count
|
|
Object.defineProperty(chain, 'then', {
|
|
value: (resolve: (val: unknown) => void) => {
|
|
resolve({
|
|
count: config.existingRevaluation ? 1 : 0,
|
|
error: null,
|
|
})
|
|
},
|
|
})
|
|
return chain
|
|
})()),
|
|
}),
|
|
}
|
|
}
|
|
|
|
const data = fromMap[table] || []
|
|
const chain = buildFilterChain(data)
|
|
return chain
|
|
}),
|
|
}
|
|
|
|
return supabase
|
|
}
|
|
|
|
function buildFilterChain(data: unknown[]) {
|
|
let filtered = [...data]
|
|
|
|
const chain: Record<string, unknown> = {}
|
|
|
|
chain.select = vi.fn().mockImplementation(() => {
|
|
return chain
|
|
})
|
|
|
|
chain.eq = vi.fn().mockImplementation((col: string, val: unknown) => {
|
|
filtered = filtered.filter((row) => (row as Record<string, unknown>)[col] === val)
|
|
return chain
|
|
})
|
|
|
|
chain.neq = vi.fn().mockImplementation((col: string, val: unknown) => {
|
|
filtered = filtered.filter((row) => (row as Record<string, unknown>)[col] !== val)
|
|
return chain
|
|
})
|
|
|
|
chain.in = vi.fn().mockImplementation((col: string, vals: unknown[]) => {
|
|
filtered = filtered.filter((row) => vals.includes((row as Record<string, unknown>)[col]))
|
|
return chain
|
|
})
|
|
|
|
chain.not = vi.fn().mockImplementation((col: string, op: string, _val: unknown) => {
|
|
if (op === 'is') {
|
|
filtered = filtered.filter((row) => (row as Record<string, unknown>)[col] != null)
|
|
}
|
|
return chain
|
|
})
|
|
|
|
// Paging stability order: no-op in the mock (data is already deterministic).
|
|
chain.order = vi.fn().mockImplementation(() => chain)
|
|
|
|
// fetchAllRows paginates via .range(from, to); slice so pagination terminates
|
|
// correctly even when a test supplies more than one page of rows.
|
|
chain.range = vi.fn().mockImplementation((from: number, to: number) => ({
|
|
then: (resolve: (val: unknown) => void) =>
|
|
resolve({ data: filtered.slice(from, to + 1), error: null }),
|
|
}))
|
|
|
|
// Make it thenable for await (used by callers that don't paginate)
|
|
chain.then = (resolve: (val: unknown) => void) => {
|
|
resolve({ data: filtered, error: null })
|
|
}
|
|
|
|
return chain
|
|
}
|
|
|
|
// Better mock for supabase that supports journal_entries idempotency check
|
|
function createFullMockSupabase(config: {
|
|
invoices?: ReturnType<typeof makeInvoice>[]
|
|
supplierInvoices?: ReturnType<typeof makeSupplierInvoice>[]
|
|
existingRevaluation?: boolean
|
|
}) {
|
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
const supabase: any = {
|
|
from: vi.fn().mockImplementation((table: string) => {
|
|
if (table === 'journal_entries') {
|
|
const countResult = {
|
|
count: config.existingRevaluation ? 1 : 0,
|
|
error: null,
|
|
}
|
|
const journalChain: Record<string, unknown> = {}
|
|
journalChain.select = vi.fn().mockReturnValue(journalChain)
|
|
journalChain.eq = vi.fn().mockReturnValue(journalChain)
|
|
journalChain.then = (resolve: (val: unknown) => void) => {
|
|
resolve(countResult)
|
|
}
|
|
return journalChain
|
|
}
|
|
|
|
const fromMap: Record<string, unknown[]> = {
|
|
invoices: config.invoices || [],
|
|
supplier_invoices: config.supplierInvoices || [],
|
|
}
|
|
return buildFilterChain(fromMap[table] || [])
|
|
}),
|
|
}
|
|
|
|
return supabase
|
|
}
|
|
|
|
describe('currency-revaluation', () => {
|
|
beforeEach(() => {
|
|
vi.clearAllMocks()
|
|
})
|
|
|
|
describe('getOpenForeignCurrencyReceivables', () => {
|
|
it('returns non-SEK invoices with sent/overdue status', async () => {
|
|
const eurInvoice = makeInvoice({
|
|
status: 'sent',
|
|
currency: 'EUR',
|
|
exchange_rate: 11.5,
|
|
total: 1000,
|
|
})
|
|
const sekInvoice = makeInvoice({
|
|
status: 'sent',
|
|
currency: 'SEK',
|
|
total: 5000,
|
|
})
|
|
|
|
const supabase = createMockSupabase({ invoices: [eurInvoice, sekInvoice] })
|
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
const result = await getOpenForeignCurrencyReceivables(supabase as any, 'company-1')
|
|
|
|
expect(result).toHaveLength(1)
|
|
expect(result[0].currency).toBe('EUR')
|
|
})
|
|
|
|
it('excludes paid invoices', async () => {
|
|
const paidEurInvoice = makeInvoice({
|
|
status: 'paid',
|
|
currency: 'EUR',
|
|
exchange_rate: 11.5,
|
|
total: 1000,
|
|
})
|
|
|
|
const supabase = createMockSupabase({ invoices: [paidEurInvoice] })
|
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
const result = await getOpenForeignCurrencyReceivables(supabase as any, 'company-1')
|
|
|
|
expect(result).toHaveLength(0)
|
|
})
|
|
|
|
it('includes partially_paid invoices: the unpaid remainder is still an open FX item', async () => {
|
|
// payment-sync.ts moves a customer invoice to 'partially_paid' on a
|
|
// partial settlement. Omitting the status made these receivables
|
|
// entirely invisible to the balansdagen revaluation (ÅRL 4 kap. 13 §);
|
|
// the payables side has always included it.
|
|
const partialEur = makeInvoice({
|
|
status: 'partially_paid',
|
|
currency: 'EUR',
|
|
exchange_rate: 11.0,
|
|
total: 1000,
|
|
paid_amount: 400,
|
|
remaining_amount: 600,
|
|
})
|
|
|
|
const supabase = createMockSupabase({ invoices: [partialEur] })
|
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
const result = await getOpenForeignCurrencyReceivables(supabase as any, 'company-1')
|
|
|
|
expect(result).toHaveLength(1)
|
|
expect(result[0].status).toBe('partially_paid')
|
|
})
|
|
|
|
// INVERTED (was: 'excludes invoices without exchange_rate'). The SQL
|
|
// `.not('exchange_rate','is',null)` filter meant the invoices with the
|
|
// largest unmeasured FX exposure never reached the caller and were never
|
|
// reported. The fetcher now returns them; previewCurrencyRevaluation
|
|
// partitions and counts them (see 'reports unconverted rows' below).
|
|
it('returns invoices without exchange_rate so the caller can report them', async () => {
|
|
const noRateInvoice = makeInvoice({
|
|
status: 'sent',
|
|
currency: 'EUR',
|
|
exchange_rate: null,
|
|
total: 1000,
|
|
})
|
|
|
|
const supabase = createMockSupabase({ invoices: [noRateInvoice] })
|
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
const result = await getOpenForeignCurrencyReceivables(supabase as any, 'company-1')
|
|
|
|
expect(result).toHaveLength(1)
|
|
expect(result[0].exchange_rate).toBeNull()
|
|
})
|
|
})
|
|
|
|
describe('getOpenForeignCurrencyPayables', () => {
|
|
it('returns non-SEK supplier invoices with open status', async () => {
|
|
const eurSI = makeSupplierInvoice({
|
|
status: 'registered',
|
|
currency: 'EUR',
|
|
exchange_rate: 11.5,
|
|
remaining_amount: 5000,
|
|
})
|
|
const sekSI = makeSupplierInvoice({
|
|
status: 'registered',
|
|
currency: 'SEK',
|
|
remaining_amount: 3000,
|
|
})
|
|
|
|
const supabase = createMockSupabase({ supplierInvoices: [eurSI, sekSI] })
|
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
const result = await getOpenForeignCurrencyPayables(supabase as any, 'company-1')
|
|
|
|
expect(result).toHaveLength(1)
|
|
expect(result[0].currency).toBe('EUR')
|
|
})
|
|
|
|
it('includes partially_paid supplier invoices', async () => {
|
|
const partialSI = makeSupplierInvoice({
|
|
status: 'partially_paid',
|
|
currency: 'USD',
|
|
exchange_rate: 10.5,
|
|
remaining_amount: 2000,
|
|
})
|
|
|
|
const supabase = createMockSupabase({ supplierInvoices: [partialSI] })
|
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
const result = await getOpenForeignCurrencyPayables(supabase as any, 'company-1')
|
|
|
|
expect(result).toHaveLength(1)
|
|
expect(result[0].remaining_amount).toBe(2000)
|
|
})
|
|
|
|
it('excludes paid supplier invoices', async () => {
|
|
const paidSI = makeSupplierInvoice({
|
|
status: 'paid',
|
|
currency: 'EUR',
|
|
exchange_rate: 11.5,
|
|
})
|
|
|
|
const supabase = createMockSupabase({ supplierInvoices: [paidSI] })
|
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
const result = await getOpenForeignCurrencyPayables(supabase as any, 'company-1')
|
|
|
|
expect(result).toHaveLength(0)
|
|
})
|
|
})
|
|
|
|
describe('previewCurrencyRevaluation', () => {
|
|
it('returns empty preview when no foreign currency items', async () => {
|
|
const supabase = createMockSupabase({
|
|
invoices: [],
|
|
supplierInvoices: [],
|
|
})
|
|
|
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
const preview = await previewCurrencyRevaluation(supabase as any, 'company-1', '2024-12-31')
|
|
|
|
expect(preview.items).toHaveLength(0)
|
|
expect(preview.lines).toHaveLength(0)
|
|
expect(preview.netEffect).toBe(0)
|
|
})
|
|
|
|
it('computes receivable gain (closing rate > original rate)', async () => {
|
|
const eurInvoice = makeInvoice({
|
|
id: 'inv-1',
|
|
status: 'sent',
|
|
currency: 'EUR',
|
|
exchange_rate: 11.0,
|
|
total: 1000,
|
|
invoice_number: 'F-001',
|
|
})
|
|
|
|
mockRates({ EUR: 11.5 })
|
|
|
|
const supabase = createMockSupabase({ invoices: [eurInvoice] })
|
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
const preview = await previewCurrencyRevaluation(supabase as any, 'company-1', '2024-12-31')
|
|
|
|
expect(preview.items).toHaveLength(1)
|
|
expect(preview.items[0].type).toBe('receivable')
|
|
expect(preview.items[0].difference_sek).toBe(500) // 1000 * (11.5 - 11.0)
|
|
|
|
// Should debit 1510 (receivable up), credit 3960 (gain)
|
|
const debit1510 = preview.lines.find(l => l.account_number === '1510' && l.debit_amount > 0)
|
|
const credit3960 = preview.lines.find(l => l.account_number === '3960' && l.credit_amount > 0)
|
|
expect(debit1510).toBeDefined()
|
|
expect(debit1510!.debit_amount).toBe(500)
|
|
expect(credit3960).toBeDefined()
|
|
expect(credit3960!.credit_amount).toBe(500)
|
|
|
|
expect(preview.totalGain).toBe(500)
|
|
expect(preview.totalLoss).toBe(0)
|
|
expect(preview.netEffect).toBe(500)
|
|
})
|
|
|
|
it('computes receivable loss (closing rate < original rate)', async () => {
|
|
const eurInvoice = makeInvoice({
|
|
id: 'inv-2',
|
|
status: 'overdue',
|
|
currency: 'EUR',
|
|
exchange_rate: 12.0,
|
|
total: 1000,
|
|
invoice_number: 'F-002',
|
|
})
|
|
|
|
mockRates({ EUR: 11.5 })
|
|
|
|
const supabase = createMockSupabase({ invoices: [eurInvoice] })
|
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
const preview = await previewCurrencyRevaluation(supabase as any, 'company-1', '2024-12-31')
|
|
|
|
expect(preview.items[0].difference_sek).toBe(-500) // 1000 * (11.5 - 12.0)
|
|
|
|
// Should credit 1510 (receivable down), debit 7960 (loss)
|
|
const credit1510 = preview.lines.find(l => l.account_number === '1510' && l.credit_amount > 0)
|
|
const debit7960 = preview.lines.find(l => l.account_number === '7960' && l.debit_amount > 0)
|
|
expect(credit1510).toBeDefined()
|
|
expect(credit1510!.credit_amount).toBe(500)
|
|
expect(debit7960).toBeDefined()
|
|
expect(debit7960!.debit_amount).toBe(500)
|
|
|
|
expect(preview.totalLoss).toBe(500)
|
|
expect(preview.totalGain).toBe(0)
|
|
expect(preview.netEffect).toBe(-500)
|
|
})
|
|
|
|
it('computes payable loss (closing rate > original rate: liability grew)', async () => {
|
|
const eurSI = makeSupplierInvoice({
|
|
id: 'si-1',
|
|
status: 'registered',
|
|
currency: 'EUR',
|
|
exchange_rate: 11.0,
|
|
remaining_amount: 2000,
|
|
supplier_invoice_number: 'LF-001',
|
|
})
|
|
|
|
mockRates({ EUR: 11.5 })
|
|
|
|
const supabase = createMockSupabase({ supplierInvoices: [eurSI] })
|
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
const preview = await previewCurrencyRevaluation(supabase as any, 'company-1', '2024-12-31')
|
|
|
|
expect(preview.items[0].type).toBe('payable')
|
|
expect(preview.items[0].difference_sek).toBe(1000) // 2000 * (11.5 - 11.0)
|
|
|
|
// Should debit 7960 (loss), credit 2440 (liability up)
|
|
const debit7960 = preview.lines.find(l => l.account_number === '7960' && l.debit_amount > 0)
|
|
const credit2440 = preview.lines.find(l => l.account_number === '2440' && l.credit_amount > 0)
|
|
expect(debit7960).toBeDefined()
|
|
expect(debit7960!.debit_amount).toBe(1000)
|
|
expect(credit2440).toBeDefined()
|
|
expect(credit2440!.credit_amount).toBe(1000)
|
|
})
|
|
|
|
it('computes payable gain (closing rate < original rate: liability shrank)', async () => {
|
|
const eurSI = makeSupplierInvoice({
|
|
id: 'si-2',
|
|
status: 'approved',
|
|
currency: 'EUR',
|
|
exchange_rate: 12.0,
|
|
remaining_amount: 2000,
|
|
supplier_invoice_number: 'LF-002',
|
|
})
|
|
|
|
mockRates({ EUR: 11.5 })
|
|
|
|
const supabase = createMockSupabase({ supplierInvoices: [eurSI] })
|
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
const preview = await previewCurrencyRevaluation(supabase as any, 'company-1', '2024-12-31')
|
|
|
|
expect(preview.items[0].difference_sek).toBe(-1000) // 2000 * (11.5 - 12.0)
|
|
|
|
// Should debit 2440 (liability down), credit 3960 (gain)
|
|
const debit2440 = preview.lines.find(l => l.account_number === '2440' && l.debit_amount > 0)
|
|
const credit3960 = preview.lines.find(l => l.account_number === '3960' && l.credit_amount > 0)
|
|
expect(debit2440).toBeDefined()
|
|
expect(debit2440!.debit_amount).toBe(1000)
|
|
expect(credit3960).toBeDefined()
|
|
expect(credit3960!.credit_amount).toBe(1000)
|
|
})
|
|
|
|
it('handles mixed currencies correctly', async () => {
|
|
const eurInvoice = makeInvoice({
|
|
id: 'inv-eur',
|
|
status: 'sent',
|
|
currency: 'EUR',
|
|
exchange_rate: 11.0,
|
|
total: 1000,
|
|
invoice_number: 'F-EUR',
|
|
})
|
|
const usdInvoice = makeInvoice({
|
|
id: 'inv-usd',
|
|
status: 'sent',
|
|
currency: 'USD',
|
|
exchange_rate: 10.0,
|
|
total: 500,
|
|
invoice_number: 'F-USD',
|
|
})
|
|
|
|
mockRates({ EUR: 11.5, USD: 10.5 })
|
|
|
|
const supabase = createMockSupabase({ invoices: [eurInvoice, usdInvoice] })
|
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
const preview = await previewCurrencyRevaluation(supabase as any, 'company-1', '2024-12-31')
|
|
|
|
expect(preview.items).toHaveLength(2)
|
|
// EUR: 1000 * (11.5 - 11.0) = 500
|
|
// USD: 500 * (10.5 - 10.0) = 250
|
|
expect(preview.totalGain).toBe(750)
|
|
})
|
|
|
|
it('aggregates journal lines correctly with mixed gains and losses', async () => {
|
|
const gainInvoice = makeInvoice({
|
|
id: 'inv-gain',
|
|
status: 'sent',
|
|
currency: 'EUR',
|
|
exchange_rate: 11.0,
|
|
total: 1000,
|
|
invoice_number: 'F-GAIN',
|
|
})
|
|
const lossSI = makeSupplierInvoice({
|
|
id: 'si-loss',
|
|
status: 'registered',
|
|
currency: 'EUR',
|
|
exchange_rate: 11.0,
|
|
remaining_amount: 2000,
|
|
supplier_invoice_number: 'LF-LOSS',
|
|
})
|
|
|
|
// EUR went up to 11.5
|
|
mockRates({ EUR: 11.5 })
|
|
|
|
const supabase = createMockSupabase({
|
|
invoices: [gainInvoice],
|
|
supplierInvoices: [lossSI],
|
|
})
|
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
const preview = await previewCurrencyRevaluation(supabase as any, 'company-1', '2024-12-31')
|
|
|
|
// Receivable gain: 1000 * 0.5 = 500 → Debit 1510, Credit 3960
|
|
// Payable loss: 2000 * 0.5 = 1000 → Debit 7960, Credit 2440
|
|
expect(preview.totalGain).toBe(500)
|
|
expect(preview.totalLoss).toBe(1000)
|
|
expect(preview.netEffect).toBe(-500)
|
|
|
|
// Verify all entries balance
|
|
const totalDebit = preview.lines.reduce((sum, l) => sum + l.debit_amount, 0)
|
|
const totalCredit = preview.lines.reduce((sum, l) => sum + l.credit_amount, 0)
|
|
expect(Math.round(totalDebit * 100) / 100).toBe(Math.round(totalCredit * 100) / 100)
|
|
})
|
|
|
|
it('uses remaining_amount for partially paid supplier invoices', async () => {
|
|
const partialSI = makeSupplierInvoice({
|
|
id: 'si-partial',
|
|
status: 'partially_paid',
|
|
currency: 'EUR',
|
|
exchange_rate: 11.0,
|
|
total: 10000,
|
|
remaining_amount: 5000, // Half paid
|
|
supplier_invoice_number: 'LF-PARTIAL',
|
|
})
|
|
|
|
mockRates({ EUR: 11.5 })
|
|
|
|
const supabase = createMockSupabase({ supplierInvoices: [partialSI] })
|
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
const preview = await previewCurrencyRevaluation(supabase as any, 'company-1', '2024-12-31')
|
|
|
|
// Only remaining 5000 EUR is revalued, not full 10000
|
|
expect(preview.items[0].amount_in_currency).toBe(5000)
|
|
expect(preview.items[0].difference_sek).toBe(2500) // 5000 * (11.5 - 11.0)
|
|
})
|
|
|
|
it('revalues only the outstanding amount of a partially paid receivable', async () => {
|
|
// Hand-computed: 1 000 EUR invoiced at 11,00 (11 000 kr on 1510),
|
|
// 400 EUR since paid. Outstanding = 600 EUR. Closing 11,50:
|
|
// originalSek = 600 * 11,00 = 6 600,00
|
|
// closingSek = 600 * 11,50 = 6 900,00
|
|
// unrealized gain = 300,00 kr (NOT 500,00 from the 1 000 EUR face value)
|
|
const partialEur = makeInvoice({
|
|
id: 'inv-partial',
|
|
status: 'partially_paid',
|
|
currency: 'EUR',
|
|
exchange_rate: 11.0,
|
|
total: 1000,
|
|
paid_amount: 400,
|
|
remaining_amount: 600,
|
|
invoice_number: 'F-PARTIAL',
|
|
})
|
|
|
|
mockRates({ EUR: 11.5 })
|
|
|
|
const supabase = createMockSupabase({ invoices: [partialEur] })
|
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
const preview = await previewCurrencyRevaluation(supabase as any, 'company-1', '2024-12-31')
|
|
|
|
expect(preview.items).toHaveLength(1)
|
|
expect(preview.items[0].amount_in_currency).toBe(600)
|
|
expect(preview.items[0].original_sek).toBe(6600)
|
|
expect(preview.items[0].closing_sek).toBe(6900)
|
|
expect(preview.items[0].difference_sek).toBe(300)
|
|
|
|
const debit1510 = preview.lines.find(l => l.account_number === '1510' && l.debit_amount > 0)
|
|
const credit3960 = preview.lines.find(l => l.account_number === '3960' && l.credit_amount > 0)
|
|
expect(debit1510!.debit_amount).toBe(300)
|
|
expect(credit3960!.credit_amount).toBe(300)
|
|
|
|
// Balanced to the öre.
|
|
const totalDebit = preview.lines.reduce((sum, l) => sum + l.debit_amount, 0)
|
|
const totalCredit = preview.lines.reduce((sum, l) => sum + l.credit_amount, 0)
|
|
expect(Math.round(totalDebit * 100)).toBe(Math.round(totalCredit * 100))
|
|
})
|
|
|
|
it('skips a receivable with nothing outstanding instead of revaluing its face value', async () => {
|
|
// Edge: status still open but paid_amount covers the total (e.g. the
|
|
// status update lagged the payment sync). There is no monetary item
|
|
// left to value and nothing to report as unconverted either.
|
|
const settledEur = makeInvoice({
|
|
id: 'inv-settled',
|
|
status: 'partially_paid',
|
|
currency: 'EUR',
|
|
exchange_rate: 11.0,
|
|
total: 1000,
|
|
paid_amount: 1000,
|
|
remaining_amount: 0,
|
|
})
|
|
|
|
mockRates({ EUR: 11.5 })
|
|
|
|
const supabase = createMockSupabase({ invoices: [settledEur] })
|
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
const preview = await previewCurrencyRevaluation(supabase as any, 'company-1', '2024-12-31')
|
|
|
|
expect(preview.items).toHaveLength(0)
|
|
expect(preview.lines).toHaveLength(0)
|
|
expect(preview.unconvertedFxCount).toBe(0)
|
|
expect(mockedFetchRate).not.toHaveBeenCalled()
|
|
})
|
|
|
|
it('reports the outstanding amount (not face value) for an unrated partially paid receivable', async () => {
|
|
const unratedPartial = makeInvoice({
|
|
id: 'inv-unrated-partial',
|
|
status: 'partially_paid',
|
|
currency: 'USD',
|
|
exchange_rate: null,
|
|
total: 4000,
|
|
paid_amount: 1500,
|
|
remaining_amount: 2500,
|
|
invoice_number: 'F-UNRATED-PARTIAL',
|
|
})
|
|
|
|
mockRates({})
|
|
|
|
const supabase = createMockSupabase({ invoices: [unratedPartial] })
|
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
const preview = await previewCurrencyRevaluation(supabase as any, 'company-1', '2024-12-31')
|
|
|
|
expect(preview.unconvertedFxCount).toBe(1)
|
|
expect(preview.unconvertedFx[0]).toMatchObject({
|
|
source_id: 'inv-unrated-partial',
|
|
type: 'receivable',
|
|
currency: 'USD',
|
|
amount_in_currency: 2500,
|
|
})
|
|
})
|
|
|
|
it('skips items with zero difference', async () => {
|
|
const eurInvoice = makeInvoice({
|
|
id: 'inv-same',
|
|
status: 'sent',
|
|
currency: 'EUR',
|
|
exchange_rate: 11.5,
|
|
total: 1000,
|
|
invoice_number: 'F-SAME',
|
|
})
|
|
|
|
// Closing rate equals original rate
|
|
mockRates({ EUR: 11.5 })
|
|
|
|
const supabase = createMockSupabase({ invoices: [eurInvoice] })
|
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
const preview = await previewCurrencyRevaluation(supabase as any, 'company-1', '2024-12-31')
|
|
|
|
expect(preview.items).toHaveLength(0)
|
|
expect(preview.lines).toHaveLength(0)
|
|
})
|
|
|
|
it('reports rows with no exchange_rate as unconverted instead of dropping them', async () => {
|
|
const ratedInvoice = makeInvoice({
|
|
id: 'inv-rated',
|
|
status: 'sent',
|
|
currency: 'EUR',
|
|
exchange_rate: 11.0,
|
|
total: 1000,
|
|
invoice_number: 'F-RATED',
|
|
})
|
|
const unratedInvoice = makeInvoice({
|
|
id: 'inv-unrated',
|
|
status: 'sent',
|
|
currency: 'USD',
|
|
exchange_rate: null,
|
|
total: 4000,
|
|
invoice_number: 'F-UNRATED',
|
|
})
|
|
const unratedSI = makeSupplierInvoice({
|
|
id: 'si-unrated',
|
|
status: 'registered',
|
|
currency: 'GBP',
|
|
exchange_rate: null,
|
|
remaining_amount: 700,
|
|
supplier_invoice_number: 'LF-UNRATED',
|
|
})
|
|
|
|
mockRates({ EUR: 11.5 })
|
|
|
|
const supabase = createMockSupabase({
|
|
invoices: [ratedInvoice, unratedInvoice],
|
|
supplierInvoices: [unratedSI],
|
|
})
|
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
const preview = await previewCurrencyRevaluation(supabase as any, 'company-1', '2024-12-31')
|
|
|
|
// Only the rated invoice is revalued.
|
|
expect(preview.items).toHaveLength(1)
|
|
expect(preview.items[0].source_id).toBe('inv-rated')
|
|
|
|
// The other two are surfaced, not silently swallowed.
|
|
expect(preview.unconvertedFxCount).toBe(2)
|
|
expect(preview.unconvertedFx.map((u) => u.source_id).sort()).toEqual([
|
|
'inv-unrated',
|
|
'si-unrated',
|
|
])
|
|
expect(preview.unconvertedFx.find((u) => u.source_id === 'inv-unrated')).toMatchObject({
|
|
type: 'receivable',
|
|
currency: 'USD',
|
|
reference: 'F-UNRATED',
|
|
amount_in_currency: 4000,
|
|
})
|
|
expect(preview.unconvertedFx.find((u) => u.source_id === 'si-unrated')).toMatchObject({
|
|
type: 'payable',
|
|
currency: 'GBP',
|
|
reference: 'LF-UNRATED',
|
|
amount_in_currency: 700,
|
|
})
|
|
|
|
// No rate was ever requested for a currency we cannot revalue anyway.
|
|
expect(mockedFetchRate).toHaveBeenCalledTimes(1)
|
|
expect(mockedFetchRate.mock.calls[0][0]).toBe('EUR')
|
|
// Looked up for the closing date (not "today") and through the shared
|
|
// exchange_rates cache, so the balansdagen rate stays reproducible.
|
|
expect(mockedFetchRate.mock.calls[0][1]).toEqual(new Date('2024-12-31'))
|
|
expect(mockedFetchRate.mock.calls[0][2]).toBe(supabase)
|
|
})
|
|
|
|
it('treats a zero exchange_rate as unconverted instead of valuing the row at 0 SEK', async () => {
|
|
const zeroRateInvoice = makeInvoice({
|
|
id: 'inv-zero',
|
|
status: 'sent',
|
|
currency: 'EUR',
|
|
exchange_rate: 0,
|
|
total: 1000,
|
|
invoice_number: 'F-ZERO',
|
|
})
|
|
|
|
mockRates({ EUR: 11.5 })
|
|
|
|
const supabase = createMockSupabase({ invoices: [zeroRateInvoice] })
|
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
const preview = await previewCurrencyRevaluation(supabase as any, 'company-1', '2024-12-31')
|
|
|
|
// A 0 original rate makes originalSek 0, so the whole 11 500 SEK would
|
|
// read as an orealiserad kursvinst on 3960. Same > 0 rule the reskontra
|
|
// reports use for unconverted_fx_count.
|
|
expect(preview.items).toHaveLength(0)
|
|
expect(preview.lines).toHaveLength(0)
|
|
expect(preview.unconvertedFxCount).toBe(1)
|
|
expect(preview.unconvertedFx[0].source_id).toBe('inv-zero')
|
|
expect(mockedFetchRate).not.toHaveBeenCalled()
|
|
})
|
|
|
|
it('reports a missing closing rate instead of substituting a fallback constant', async () => {
|
|
const eurInvoice = makeInvoice({
|
|
id: 'inv-norate',
|
|
status: 'sent',
|
|
currency: 'EUR',
|
|
exchange_rate: 11.0,
|
|
total: 1000,
|
|
invoice_number: 'F-NORATE',
|
|
})
|
|
|
|
// Riksbanken unreachable and cache empty: fetchExchangeRate resolves null.
|
|
mockRates({})
|
|
|
|
const supabase = createMockSupabase({ invoices: [eurInvoice] })
|
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
const preview = await previewCurrencyRevaluation(supabase as any, 'company-1', '2024-12-31')
|
|
|
|
expect(preview.missingClosingRates).toEqual([{ currency: 'EUR', date: '2024-12-31' }])
|
|
// Nothing is valued off a guessed rate: no items, no lines, no 11.5.
|
|
expect(preview.items).toHaveLength(0)
|
|
expect(preview.lines).toHaveLength(0)
|
|
expect(preview.closingRates).toEqual({})
|
|
})
|
|
|
|
it('all generated journal lines balance (debits === credits)', async () => {
|
|
const eurInvoice = makeInvoice({
|
|
id: 'inv-bal',
|
|
status: 'sent',
|
|
currency: 'EUR',
|
|
exchange_rate: 11.0,
|
|
total: 1234.56,
|
|
invoice_number: 'F-BAL',
|
|
})
|
|
const gbpSI = makeSupplierInvoice({
|
|
id: 'si-bal',
|
|
status: 'overdue',
|
|
currency: 'GBP',
|
|
exchange_rate: 14.0,
|
|
remaining_amount: 789.12,
|
|
supplier_invoice_number: 'LF-BAL',
|
|
})
|
|
|
|
mockRates({ EUR: 11.8, GBP: 13.5 })
|
|
|
|
const supabase = createMockSupabase({
|
|
invoices: [eurInvoice],
|
|
supplierInvoices: [gbpSI],
|
|
})
|
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
const preview = await previewCurrencyRevaluation(supabase as any, 'company-1', '2024-12-31')
|
|
|
|
const totalDebit = preview.lines.reduce((sum, l) => sum + l.debit_amount, 0)
|
|
const totalCredit = preview.lines.reduce((sum, l) => sum + l.credit_amount, 0)
|
|
expect(Math.round(totalDebit * 100)).toBe(Math.round(totalCredit * 100))
|
|
})
|
|
})
|
|
|
|
describe('executeCurrencyRevaluation', () => {
|
|
it('returns null when no foreign currency items exist', async () => {
|
|
const supabase = createFullMockSupabase({
|
|
invoices: [],
|
|
supplierInvoices: [],
|
|
existingRevaluation: false,
|
|
})
|
|
|
|
mockRates({})
|
|
|
|
const result = await executeCurrencyRevaluation(supabase, 'company-1', '2024-12-31', 'period-1')
|
|
|
|
expect(result).toBeNull()
|
|
expect(mockedCreateEntry).not.toHaveBeenCalled()
|
|
})
|
|
|
|
it('creates journal entry with correct source_type', async () => {
|
|
const eurInvoice = makeInvoice({
|
|
status: 'sent',
|
|
currency: 'EUR',
|
|
exchange_rate: 11.0,
|
|
total: 1000,
|
|
invoice_number: 'F-001',
|
|
})
|
|
|
|
mockRates({ EUR: 11.5 })
|
|
|
|
const supabase = createFullMockSupabase({
|
|
invoices: [eurInvoice],
|
|
existingRevaluation: false,
|
|
})
|
|
|
|
const result = await executeCurrencyRevaluation(supabase, 'company-1', '2024-12-31', 'period-1')
|
|
|
|
expect(result).not.toBeNull()
|
|
expect(mockedCreateEntry).toHaveBeenCalledOnce()
|
|
|
|
const callArgs = mockedCreateEntry.mock.calls[0]
|
|
expect(callArgs[3].source_type).toBe('currency_revaluation')
|
|
expect(callArgs[3].fiscal_period_id).toBe('period-1')
|
|
expect(callArgs[3].entry_date).toBe('2024-12-31')
|
|
expect(callArgs[3].description).toContain('Omvärdering utländsk valuta')
|
|
})
|
|
|
|
it('throws when revaluation already exists for period (idempotency)', async () => {
|
|
const supabase = createFullMockSupabase({
|
|
existingRevaluation: true,
|
|
})
|
|
|
|
await expect(
|
|
executeCurrencyRevaluation(supabase, 'company-1', '2024-12-31', 'period-1')
|
|
).rejects.toThrow('Currency revaluation already exists for this period')
|
|
|
|
expect(mockedCreateEntry).not.toHaveBeenCalled()
|
|
})
|
|
|
|
it('books the receivable gain to 1510 / 3960 with a real Riksbanken rate', async () => {
|
|
const eurInvoice = makeInvoice({
|
|
status: 'sent',
|
|
currency: 'EUR',
|
|
exchange_rate: 11.0,
|
|
total: 1000,
|
|
invoice_number: 'F-001',
|
|
})
|
|
const gbpSI = makeSupplierInvoice({
|
|
status: 'registered',
|
|
currency: 'GBP',
|
|
exchange_rate: 14.0,
|
|
remaining_amount: 500,
|
|
supplier_invoice_number: 'LF-001',
|
|
})
|
|
|
|
// EUR up (receivable gain), GBP down (payable gain).
|
|
mockRates({ EUR: 11.5, GBP: 13.5 })
|
|
|
|
const supabase = createFullMockSupabase({
|
|
invoices: [eurInvoice],
|
|
supplierInvoices: [gbpSI],
|
|
existingRevaluation: false,
|
|
})
|
|
|
|
await executeCurrencyRevaluation(supabase, 'company-1', '2024-12-31', 'period-1')
|
|
|
|
const lines = mockedCreateEntry.mock.calls[0][3].lines
|
|
const find = (account: string, side: 'debit_amount' | 'credit_amount') =>
|
|
lines.find((l) => l.account_number === account && l[side] > 0)
|
|
|
|
// Receivable revalued up 1000 * 0.5 = 500 → Dr 1510 / Cr 3960
|
|
expect(find('1510', 'debit_amount')!.debit_amount).toBe(500)
|
|
// Payable shrank 500 * 0.5 = 250 → Dr 2440 / Cr 3960
|
|
expect(find('2440', 'debit_amount')!.debit_amount).toBe(250)
|
|
expect(find('3960', 'credit_amount')!.credit_amount).toBe(750)
|
|
expect(find('7960', 'debit_amount')).toBeUndefined()
|
|
|
|
const totalDebit = lines.reduce((s, l) => s + l.debit_amount, 0)
|
|
const totalCredit = lines.reduce((s, l) => s + l.credit_amount, 0)
|
|
expect(Math.round(totalDebit * 100) / 100).toBe(Math.round(totalCredit * 100) / 100)
|
|
expect(totalDebit).toBeGreaterThan(0)
|
|
})
|
|
|
|
it('refuses to post when the closing rate is unavailable', async () => {
|
|
const eurInvoice = makeInvoice({
|
|
status: 'sent',
|
|
currency: 'EUR',
|
|
exchange_rate: 11.0,
|
|
total: 1000,
|
|
invoice_number: 'F-001',
|
|
})
|
|
|
|
// No rate at all. Before the fix, fetchMultipleRates padded its Map with
|
|
// the display-only fallback (EUR 11.5) and this posted a real 3960/7960
|
|
// verifikat computed from a hardcoded constant.
|
|
mockRates({})
|
|
|
|
const supabase = createFullMockSupabase({
|
|
invoices: [eurInvoice],
|
|
existingRevaluation: false,
|
|
})
|
|
|
|
await expect(
|
|
executeCurrencyRevaluation(supabase, 'company-1', '2024-12-31', 'period-1')
|
|
).rejects.toMatchObject({
|
|
code: 'FX_CLOSING_RATE_UNAVAILABLE',
|
|
missingRates: [{ currency: 'EUR', date: '2024-12-31' }],
|
|
})
|
|
|
|
expect(mockedCreateEntry).not.toHaveBeenCalled()
|
|
})
|
|
|
|
it('translates the refusal into a Swedish message naming currency and date', async () => {
|
|
const eurInvoice = makeInvoice({
|
|
status: 'sent',
|
|
currency: 'EUR',
|
|
exchange_rate: 11.0,
|
|
total: 1000,
|
|
invoice_number: 'F-001',
|
|
})
|
|
|
|
mockRates({})
|
|
|
|
const supabase = createFullMockSupabase({
|
|
invoices: [eurInvoice],
|
|
existingRevaluation: false,
|
|
})
|
|
|
|
const err = await executeCurrencyRevaluation(
|
|
supabase, 'company-1', '2024-12-31', 'period-1'
|
|
).catch((e: unknown) => e)
|
|
|
|
const message = getErrorMessage(err)
|
|
expect(message).toContain('EUR per 2024-12-31')
|
|
expect(message).toContain('har inte bokförts')
|
|
// Never leak the raw English engine message into a Swedish UI.
|
|
expect(message).not.toContain('Riksbanken exchange rate available')
|
|
})
|
|
|
|
it('refuses a partial valuation when only some currencies have a rate', async () => {
|
|
const eurInvoice = makeInvoice({
|
|
id: 'inv-eur',
|
|
status: 'sent',
|
|
currency: 'EUR',
|
|
exchange_rate: 11.0,
|
|
total: 1000,
|
|
invoice_number: 'F-EUR',
|
|
})
|
|
const usdInvoice = makeInvoice({
|
|
id: 'inv-usd',
|
|
status: 'sent',
|
|
currency: 'USD',
|
|
exchange_rate: 10.0,
|
|
total: 500,
|
|
invoice_number: 'F-USD',
|
|
})
|
|
|
|
mockRates({ EUR: 11.5 })
|
|
|
|
const supabase = createFullMockSupabase({
|
|
invoices: [eurInvoice, usdInvoice],
|
|
existingRevaluation: false,
|
|
})
|
|
|
|
await expect(
|
|
executeCurrencyRevaluation(supabase, 'company-1', '2024-12-31', 'period-1')
|
|
).rejects.toMatchObject({
|
|
code: 'FX_CLOSING_RATE_UNAVAILABLE',
|
|
missingRates: [{ currency: 'USD', date: '2024-12-31' }],
|
|
})
|
|
|
|
expect(mockedCreateEntry).not.toHaveBeenCalled()
|
|
})
|
|
|
|
it('surfaces unconverted rows on the result so the caller can warn', async () => {
|
|
const ratedInvoice = makeInvoice({
|
|
id: 'inv-rated',
|
|
status: 'sent',
|
|
currency: 'EUR',
|
|
exchange_rate: 11.0,
|
|
total: 1000,
|
|
invoice_number: 'F-RATED',
|
|
})
|
|
const unratedInvoice = makeInvoice({
|
|
id: 'inv-unrated',
|
|
status: 'sent',
|
|
currency: 'EUR',
|
|
exchange_rate: null,
|
|
total: 9000,
|
|
invoice_number: 'F-UNRATED',
|
|
})
|
|
|
|
mockRates({ EUR: 11.5 })
|
|
|
|
const supabase = createFullMockSupabase({
|
|
invoices: [ratedInvoice, unratedInvoice],
|
|
existingRevaluation: false,
|
|
})
|
|
|
|
const result = await executeCurrencyRevaluation(
|
|
supabase, 'company-1', '2024-12-31', 'period-1'
|
|
)
|
|
|
|
expect(result).not.toBeNull()
|
|
expect(result!.preview.unconvertedFxCount).toBe(1)
|
|
expect(result!.preview.unconvertedFx[0].source_id).toBe('inv-unrated')
|
|
})
|
|
|
|
it('returns entry and preview in result', async () => {
|
|
const eurInvoice = makeInvoice({
|
|
status: 'sent',
|
|
currency: 'EUR',
|
|
exchange_rate: 11.0,
|
|
total: 1000,
|
|
invoice_number: 'F-001',
|
|
})
|
|
|
|
mockRates({ EUR: 12.0 })
|
|
|
|
const supabase = createFullMockSupabase({
|
|
invoices: [eurInvoice],
|
|
existingRevaluation: false,
|
|
})
|
|
|
|
const result = await executeCurrencyRevaluation(supabase, 'company-1', '2024-12-31', 'period-1')
|
|
|
|
expect(result).not.toBeNull()
|
|
expect(result!.entry).toBeDefined()
|
|
expect(result!.preview).toBeDefined()
|
|
expect(result!.preview.items).toHaveLength(1)
|
|
expect(result!.preview.totalGain).toBe(1000) // 1000 * (12 - 11)
|
|
})
|
|
})
|
|
})
|