* 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>
754 lines
34 KiB
TypeScript
754 lines
34 KiB
TypeScript
import { NextResponse } from 'next/server'
|
|
import { createInvoiceCashEntry } from '@/lib/bookkeeping/invoice-entries'
|
|
import { buildInvoicePaymentClearingLines } from '@/lib/bookkeeping/invoice-payment-lines'
|
|
import { resolveSekAmount } from '@/lib/bookkeeping/currency-utils'
|
|
import { coerceDimensionsBag } from '@/lib/bookkeeping/dimension-resolver'
|
|
import { resolveSettlementAccount } from '@/lib/bookkeeping/settlement-account'
|
|
import { fetchExchangeRate } from '@/lib/currency/riksbanken'
|
|
import { reverseEntry, createJournalEntry, findFiscalPeriod } from '@/lib/bookkeeping/engine'
|
|
import { AccountsNotInChartError, isBookkeepingError } from '@/lib/bookkeeping/errors'
|
|
import { getErrorMessage } from '@/lib/errors/get-error-message'
|
|
import { withRouteContext } from '@/lib/api/with-route-context'
|
|
import { errorResponse, errorResponseFromCode } from '@/lib/errors/get-structured-error'
|
|
import { validateBody } from '@/lib/api/validate'
|
|
import { MatchInvoiceSchema } from '@/lib/api/schemas'
|
|
import { logMatchEvent } from '@/lib/invoices/match-log'
|
|
import { planInvoicePayment } from '@/lib/invoices/apply-invoice-payment'
|
|
import { detectDuplicatePaymentVoucher } from '@/lib/invoices/duplicate-payment-detection'
|
|
import { eventBus } from '@/lib/events/bus'
|
|
import { ensureInitialized } from '@/lib/init'
|
|
import type { Currency, EntityType, Invoice, Transaction } from '@/types'
|
|
|
|
ensureInitialized()
|
|
|
|
/**
|
|
* POST /api/transactions/[id]/match-invoice
|
|
*
|
|
* Confirms an invoice match for a transaction. Supports partial payments:
|
|
* 1. If transaction has an auto-categorization journal entry, storno it first
|
|
* 2. Links transaction to invoice (sets invoice_id)
|
|
* 3. Updates invoice status to 'paid' or 'partially_paid'
|
|
* 4. Records payment in invoice_payments table
|
|
* 5. Creates journal entry for payment receipt
|
|
* - Debit <resolved bank account> Företagskonto (Bank)
|
|
* - Credit 1510 Kundfordringar (Accounts Receivable)
|
|
*
|
|
* The bank leg is resolved from THIS transaction's own cash_account_id via
|
|
* resolveSettlementAccount (cash_account_id -> cash_accounts.ledger_account),
|
|
* never hardcoded to 1930: a receipt landing in a secondary SEK account or a
|
|
* foreign-currency account (e.g. 1940 for EUR) must book to that account, not
|
|
* silently to the primary bank account. Mirrors the fix already applied on
|
|
* the supplier-invoice side (match-supplier-invoice/route.ts), which resolves
|
|
* the credited account the same way instead of falling back to a stale
|
|
* company-wide setting.
|
|
*/
|
|
export const POST = withRouteContext(
|
|
'transaction.match_invoice',
|
|
async (request, ctx, { params }: { params: Promise<{ id: string }> }) => {
|
|
const { id: transactionId } = await params
|
|
const { user, supabase, companyId, log, requestId } = ctx
|
|
|
|
const validation = await validateBody(request, MatchInvoiceSchema, {
|
|
log,
|
|
operation: 'transaction.match_invoice',
|
|
})
|
|
if (!validation.success) return validation.response
|
|
const { invoice_id, force, expected_journal_entry_id, lines: customLines } = validation.data
|
|
|
|
const txLog = log.child({ transactionId, invoiceId: invoice_id })
|
|
|
|
const { data: transaction, error: fetchTxError } = await supabase
|
|
.from('transactions')
|
|
.select('*')
|
|
.eq('id', transactionId)
|
|
.eq('company_id', companyId)
|
|
.single()
|
|
|
|
if (fetchTxError || !transaction) {
|
|
return errorResponseFromCode('TX_CATEGORIZE_TX_NOT_FOUND', txLog, { requestId })
|
|
}
|
|
|
|
if (transaction.amount <= 0) {
|
|
return errorResponseFromCode('MATCH_INVOICE_NOT_INCOME', txLog, {
|
|
requestId,
|
|
details: { amount: transaction.amount },
|
|
})
|
|
}
|
|
|
|
if (transaction.invoice_id) {
|
|
return errorResponseFromCode('MATCH_INVOICE_TX_ALREADY_LINKED', txLog, {
|
|
requestId,
|
|
details: { existingInvoiceId: transaction.invoice_id },
|
|
})
|
|
}
|
|
|
|
const { data: invoice, error: fetchInvError } = await supabase
|
|
.from('invoices')
|
|
.select('*, customer:customers(*), items:invoice_items(*), credit_notes:invoices!credited_invoice_id(id, status, creation_complete)')
|
|
.eq('id', invoice_id)
|
|
.eq('company_id', companyId)
|
|
.single()
|
|
|
|
if (fetchInvError || !invoice) {
|
|
return errorResponseFromCode('MATCH_INVOICE_NOT_FOUND', txLog, { requestId })
|
|
}
|
|
|
|
// Defense-in-depth: the InvoicePicker UI filters proformas / delivery
|
|
// notes out of the candidate list, but a direct API call could still
|
|
// pass a proforma id. A proforma is not a faktura per ML 17 kap 24§:
|
|
// no VAT obligation, no binding payment: so matching one against a
|
|
// bank receipt would book income and VAT incorrectly.
|
|
const docType = (invoice as { document_type?: string }).document_type ?? 'invoice'
|
|
if (docType !== 'invoice') {
|
|
return errorResponseFromCode('MATCH_INVOICE_NOT_INVOICE_TYPE', txLog, {
|
|
requestId,
|
|
details: { documentType: docType },
|
|
})
|
|
}
|
|
|
|
if (invoice.credited_invoice_id) {
|
|
return errorResponseFromCode('MATCH_INVOICE_CREDIT_NOTE', txLog, { requestId })
|
|
}
|
|
|
|
const activeCreditNotes = ((invoice as { credit_notes?: Array<{
|
|
status: string
|
|
creation_complete?: boolean
|
|
}> }).credit_notes ?? []).filter(
|
|
(creditNote) => creditNote.status !== 'cancelled' && creditNote.creation_complete !== false,
|
|
)
|
|
if (activeCreditNotes.length > 0) {
|
|
return errorResponseFromCode('MATCH_INVOICE_CREDIT_NOTE', txLog, {
|
|
requestId,
|
|
details: { reason: 'active_credit_note' },
|
|
})
|
|
}
|
|
|
|
if (invoice.status !== 'sent' && invoice.status !== 'overdue' && invoice.status !== 'partially_paid') {
|
|
return errorResponseFromCode('MATCH_INVOICE_NOT_OPEN', txLog, {
|
|
requestId,
|
|
details: { currentStatus: invoice.status },
|
|
})
|
|
}
|
|
|
|
// Cross-currency settlement (replaces the PR #614 round-9 block).
|
|
//
|
|
// invoices.paid_amount / remaining_amount are denominated in
|
|
// invoice.currency; invoice_payments rows carry currency =
|
|
// invoice.currency with amount in that currency. When tx and invoice
|
|
// currencies differ, we convert tx.amount (SEK) to invoice currency
|
|
// using the Riksbanken spot rate on the payment date (ML 8 kap 21-23§)
|
|
// and accumulate / record in invoice currency throughout. The JE-lines
|
|
// helper gets the same converted amount so the verifikat balances
|
|
// exactly (FX-diff posted to 3960/7960). A manual rate may be supplied
|
|
// via the request body when the lookup fails (e.g. bank-statement rate
|
|
// when Riksbanken hasn't published for the date yet).
|
|
type FxConversion =
|
|
| { required: false }
|
|
| {
|
|
required: true
|
|
rate: number
|
|
rate_date: string
|
|
paidInInvoiceCurrency: number
|
|
// Provenance of the rate actually used, recorded for the audit
|
|
// trail: 'manual' = caller-supplied from a bank statement (Riksbanken
|
|
// had no rate for the date), 'riksbanken' = spot rate fetched on the
|
|
// payment date. A manual override on a money path must be traceable
|
|
// (BFL 5 kap 6-7§; ML 8 kap 21-23§).
|
|
source: 'manual' | 'riksbanken'
|
|
}
|
|
|
|
// A bank row is stored in ITS OWN currency: transactions.amount is
|
|
// denominated in transactions.currency, and the SEK value lives either in
|
|
// amount_sek (pre-computed at ingest) or is derivable from exchange_rate.
|
|
// Every journal entry line is SEK, so a foreign row whose SEK value cannot
|
|
// be established must not be booked or allocated at all: substituting the
|
|
// raw foreign number would settle a 500 USD receipt as 500 SEK, a tenth of
|
|
// the real payment. Rows in exactly that shape exist: when the Riksbanken
|
|
// lookup fails at ingest the transaction is written with neither field
|
|
// (lib/transactions/ingest.ts). Refuse loudly, the same way the
|
|
// match_batch_allocate RPC refuses with BATCH_FX_RATE_MISSING, instead of
|
|
// guessing a rate of 1.
|
|
const txIsForeign = !!transaction.currency && transaction.currency !== 'SEK'
|
|
if (
|
|
txIsForeign &&
|
|
transaction.amount_sek == null &&
|
|
!(transaction.exchange_rate != null && transaction.exchange_rate > 0)
|
|
) {
|
|
return errorResponseFromCode('MATCH_INVOICE_TX_FX_RATE_MISSING', txLog, {
|
|
requestId,
|
|
details: {
|
|
transactionCurrency: transaction.currency,
|
|
transactionDate: transaction.date,
|
|
},
|
|
})
|
|
}
|
|
// The actual SEK that hit the bank. Resolved through the SAME helper
|
|
// buildInvoicePaymentClearingLines uses for the bank leg (amount_sek first,
|
|
// then amount * exchange_rate), so the FX conversion below and the posted
|
|
// verifikat can never disagree on the SEK figure. SEK rows return
|
|
// Math.abs(amount) unchanged.
|
|
const txAbsSek =
|
|
Math.round(
|
|
resolveSekAmount(
|
|
Math.abs(transaction.amount),
|
|
transaction.amount_sek != null ? Math.abs(transaction.amount_sek) : null,
|
|
transaction.currency,
|
|
transaction.exchange_rate,
|
|
) * 100,
|
|
) / 100
|
|
|
|
let fx: FxConversion = { required: false }
|
|
if (transaction.currency !== invoice.currency) {
|
|
const manualRate =
|
|
typeof validation.data?.manual_exchange_rate === 'number' &&
|
|
validation.data.manual_exchange_rate > 0
|
|
? validation.data.manual_exchange_rate
|
|
: null
|
|
let rate = manualRate
|
|
let rateDate = transaction.date
|
|
if (rate == null) {
|
|
const rateInfo = await fetchExchangeRate(
|
|
invoice.currency as Currency,
|
|
new Date(transaction.date),
|
|
)
|
|
if (rateInfo && rateInfo.rate > 0) {
|
|
rate = rateInfo.rate
|
|
rateDate = rateInfo.date
|
|
}
|
|
}
|
|
if (rate == null || rate <= 0) {
|
|
return errorResponseFromCode('MATCH_INVOICE_FX_RATE_UNAVAILABLE', txLog, {
|
|
requestId,
|
|
details: {
|
|
transactionCurrency: transaction.currency,
|
|
invoiceCurrency: invoice.currency,
|
|
paymentDate: transaction.date,
|
|
},
|
|
})
|
|
}
|
|
const paidInInvoiceCurrency = Math.round((txAbsSek / rate) * 10000) / 10000
|
|
fx = {
|
|
required: true,
|
|
rate,
|
|
rate_date: rateDate,
|
|
paidInInvoiceCurrency,
|
|
source: manualRate != null ? 'manual' : 'riksbanken',
|
|
}
|
|
}
|
|
|
|
// Hard-duplicate guard: if the invoice is 'sent'/'overdue' but already
|
|
// has a payment voucher attached (status leak), refuse: booking again
|
|
// would double-credit 1510 / double-debit 1930. Partially-paid invoices
|
|
// pass through; additional payments are legitimate.
|
|
if (invoice.status === 'sent' || invoice.status === 'overdue') {
|
|
const { data: existingPayments } = await supabase
|
|
.from('invoice_payments')
|
|
.select('journal_entry_id')
|
|
.eq('company_id', companyId)
|
|
.eq('invoice_id', invoice_id)
|
|
.not('journal_entry_id', 'is', null)
|
|
.limit(1)
|
|
if (existingPayments && existingPayments.length > 0) {
|
|
return errorResponseFromCode('MATCH_INVOICE_ALREADY_HAS_PAYMENT_VOUCHER', txLog, {
|
|
requestId,
|
|
details: {
|
|
existing_journal_entry_id: (existingPayments[0] as { journal_entry_id: string }).journal_entry_id,
|
|
},
|
|
})
|
|
}
|
|
}
|
|
|
|
// Soft-duplicate guard: scan for a manual verifikation that already
|
|
// books this bank receipt outside the invoice flow. The customer's
|
|
// exact case: they posted Dr 1930 / Cr 3100 by hand; the matcher
|
|
// would otherwise create a second voucher and double-book. Bypassed
|
|
// with force=true after the user reviews the candidate in the UI.
|
|
//
|
|
// force=true is bound to a specific candidate via expected_journal_entry_id
|
|
// (validated by the schema). We re-detect the candidate server-side and
|
|
// refuse the bypass if it no longer matches: a stale or fabricated
|
|
// expected id cannot wave the guard away. The pre-flight runs even when
|
|
// a candidate is detected so the audit log records the verifikation the
|
|
// user opted to dismiss.
|
|
let dismissedCandidateId: string | null = null
|
|
try {
|
|
const candidate = await detectDuplicatePaymentVoucher(supabase, {
|
|
companyId: companyId!,
|
|
transactionId,
|
|
transactionDate: transaction.date,
|
|
transactionAmount: transaction.amount,
|
|
// `amount` is in `currency`; the 19xx legs the detector compares it
|
|
// against are always SEK. Selected above via select('*').
|
|
transactionCurrency: transaction.currency ?? null,
|
|
transactionAmountSek: transaction.amount_sek ?? null,
|
|
transactionExchangeRate: transaction.exchange_rate ?? null,
|
|
})
|
|
if (!force) {
|
|
if (candidate) {
|
|
return errorResponseFromCode('MATCH_INVOICE_POSSIBLE_DUPLICATE', txLog, {
|
|
requestId,
|
|
details: { candidate },
|
|
})
|
|
}
|
|
} else {
|
|
if (!candidate || candidate.journal_entry_id !== expected_journal_entry_id) {
|
|
// Either no current duplicate (force is moot: caller should retry
|
|
// without force) or the candidate the caller claims to have seen
|
|
// doesn't match what we detect now. Reject so an automation can't
|
|
// smuggle force=true past the guard with a guessed id.
|
|
return errorResponseFromCode('MATCH_INVOICE_FORCE_CANDIDATE_MISMATCH', txLog, {
|
|
requestId,
|
|
details: {
|
|
expected_journal_entry_id,
|
|
detected_journal_entry_id: candidate?.journal_entry_id ?? null,
|
|
},
|
|
})
|
|
}
|
|
dismissedCandidateId = candidate.journal_entry_id
|
|
}
|
|
} catch (err) {
|
|
// Detection failure must not block the non-force match: log and
|
|
// continue. force=true requires a successful detection, so re-throw
|
|
// its branch as a clean 500 via the wrapper.
|
|
if (force) {
|
|
txLog.error('duplicate-payment-voucher detection failed under force=true', err as Error)
|
|
return errorResponse(err, txLog, { requestId })
|
|
}
|
|
txLog.warn('duplicate-payment-voucher detection failed (continuing)', err as Error)
|
|
}
|
|
|
|
if (force && dismissedCandidateId) {
|
|
txLog.warn('soft-duplicate guard bypassed', {
|
|
reason: 'force=true',
|
|
requestId,
|
|
transactionId,
|
|
invoiceId: invoice_id,
|
|
userId: user.id,
|
|
// The verifikation the user reviewed and dismissed. Recorded so the
|
|
// override can be traced back to the specific duplicate that was
|
|
// surfaced in the pre-flight UI.
|
|
dismissedJournalEntryId: dismissedCandidateId,
|
|
})
|
|
}
|
|
|
|
// Storno conflicting auto-categorization JE before any other state change.
|
|
// If storno fails, return immediately: nothing else has been modified.
|
|
if (transaction.journal_entry_id) {
|
|
try {
|
|
await reverseEntry(supabase, companyId, user.id, transaction.journal_entry_id)
|
|
|
|
const { error: clearJeError } = await supabase
|
|
.from('transactions')
|
|
.update({ journal_entry_id: null })
|
|
.eq('id', transactionId)
|
|
if (clearJeError) {
|
|
txLog.warn('failed to clear journal_entry_id after storno', clearJeError)
|
|
}
|
|
|
|
logMatchEvent(supabase, user.id, transactionId, 'storno_conflict_resolved', {
|
|
invoiceId: invoice_id,
|
|
previousState: { journal_entry_id: transaction.journal_entry_id },
|
|
newState: { journal_entry_id: null },
|
|
})
|
|
} catch (err) {
|
|
txLog.error('failed to storno conflicting journal entry', err as Error)
|
|
return errorResponse(err, txLog, { requestId })
|
|
}
|
|
}
|
|
|
|
const now = new Date().toISOString()
|
|
// paidAmountInInvoiceCurrency is what gets accumulated into
|
|
// invoice.paid_amount / remaining_amount and stored on the
|
|
// invoice_payments row. For same-currency it's just tx.amount; for
|
|
// cross-currency it's the Riksbanken-rate conversion computed above.
|
|
// Using SEK directly for a USD invoice would corrupt the column units
|
|
// (the bug the PR #614 round-9 block was working around).
|
|
const paidAmountInInvoiceCurrency = fx.required
|
|
? fx.paidInInvoiceCurrency
|
|
: transaction.amount
|
|
|
|
// Overshoot guard + paid/remaining math: shared with the v1 and agent
|
|
// (commit) paths via planInvoicePayment so they cannot drift again. Runs
|
|
// before any JE is created, so a doomed match never burns a voucher number.
|
|
// Pure-SEK settlements absorb sub-krona öresavrundning (booked to 3740 by
|
|
// buildInvoicePaymentClearingLines) so a whole-krona payment settles in full.
|
|
const pureSek = transaction.currency === 'SEK' && invoice.currency === 'SEK'
|
|
const payment = planInvoicePayment(invoice, paidAmountInInvoiceCurrency, {
|
|
absorbOreRounding: pureSek,
|
|
})
|
|
if (!payment.ok) {
|
|
return errorResponseFromCode('MATCH_AMOUNT_EXCEEDS_REMAINING', txLog, {
|
|
requestId,
|
|
details: payment.details,
|
|
})
|
|
}
|
|
const { newPaidAmount, newRemaining, isFullyPaid, newStatus } = payment.plan
|
|
|
|
const { data: settings } = await supabase
|
|
.from('company_settings')
|
|
.select('accounting_method, entity_type')
|
|
.eq('company_id', companyId)
|
|
.single()
|
|
|
|
const accountingMethod = settings?.accounting_method || 'accrual'
|
|
const entityType = (settings?.entity_type as EntityType) || 'enskild_firma'
|
|
|
|
// Debit the cash account THIS transaction actually belongs to, never a
|
|
// hardcoded 1930: cash_account_id -> cash_accounts.ledger_account is the
|
|
// only source of truth for which bank/cash account a real, matched
|
|
// transaction settled into. A receipt into a secondary SEK account or a
|
|
// foreign-currency account (e.g. 1940 for EUR) must book there, not to
|
|
// the primary account, or the GL silently diverges from the actual bank
|
|
// statement it's meant to represent (BFL 5 kap 1-2§).
|
|
const paymentAccount = await resolveSettlementAccount(
|
|
supabase,
|
|
companyId!,
|
|
transaction.cash_account_id,
|
|
txLog,
|
|
)
|
|
|
|
// Drive the JE shape from the INVOICE'S booking state, not from the
|
|
// company's current accounting_method setting. If the invoice was already
|
|
// booked at send (Dr 1510 / Cr 30xx + VAT) we MUST clear 1510 here:
|
|
// otherwise the receivable stays orphaned and 30xx + VAT get double-
|
|
// counted. This happens when a company sent invoices under accrual,
|
|
// then flipped to kontantmetoden before payment arrived.
|
|
// Only when the invoice carries no prior JE (pure kontantmetoden, no
|
|
// receivable on the books) do we recognise revenue + VAT here.
|
|
const invoiceAlreadyBooked = !!(invoice as { journal_entry_id?: string | null }).journal_entry_id
|
|
const useCashEntry = !invoiceAlreadyBooked && accountingMethod === 'cash' && isFullyPaid
|
|
|
|
let journalEntryId: string | null = null
|
|
|
|
try {
|
|
if (customLines) {
|
|
// User-edited rows from the match dialog. Validate balance, then
|
|
// post via createJournalEntry directly. source_type still derives
|
|
// from the routing decision so downstream payment-sync (which keys
|
|
// off invoice_paid / invoice_cash_payment) keeps working.
|
|
const totalDebit = customLines.reduce((s, l) => s + l.debit_amount, 0)
|
|
const totalCredit = customLines.reduce((s, l) => s + l.credit_amount, 0)
|
|
if (Math.round((totalDebit - totalCredit) * 100) !== 0 || totalDebit <= 0) {
|
|
return errorResponseFromCode('INVOICE_PAID_LINES_UNBALANCED', txLog, {
|
|
requestId,
|
|
details: { totalDebit, totalCredit },
|
|
})
|
|
}
|
|
const fiscalPeriodId = await findFiscalPeriod(supabase, companyId!, transaction.date)
|
|
if (!fiscalPeriodId) {
|
|
return errorResponseFromCode('INVOICE_PAID_NO_FISCAL_PERIOD', txLog, {
|
|
requestId,
|
|
details: { paymentDate: transaction.date },
|
|
})
|
|
}
|
|
const sourceType = useCashEntry ? 'invoice_cash_payment' : 'invoice_paid'
|
|
const desc = invoice.customer?.name
|
|
? `Inbetalning kundfaktura ${invoice.invoice_number}, ${invoice.customer.name}`
|
|
: `Inbetalning kundfaktura ${invoice.invoice_number}`
|
|
const journalEntry = await createJournalEntry(supabase, companyId!, user.id, {
|
|
fiscal_period_id: fiscalPeriodId,
|
|
entry_date: transaction.date,
|
|
description: desc,
|
|
source_type: sourceType,
|
|
source_id: invoice.id,
|
|
lines: customLines,
|
|
})
|
|
journalEntryId = journalEntry?.id ?? null
|
|
} else if (useCashEntry) {
|
|
const journalEntry = await createInvoiceCashEntry(
|
|
supabase, companyId, user.id, invoice as Invoice, transaction.date,
|
|
entityType, invoice.customer?.name, paymentAccount,
|
|
)
|
|
journalEntryId = journalEntry?.id ?? null
|
|
} else {
|
|
// Clearing entry against 1510. Covers accrual, cash-with-prior-JE
|
|
// (mid-stream switch), and cash partial. The cash partial path is
|
|
// intentional: under kontantmetoden 1510 has no prior balance, so
|
|
// partials leave a credit on 1510 that gets resolved on final
|
|
// payment when createInvoiceCashEntry would normally run.
|
|
//
|
|
// Builds lines via buildInvoicePaymentClearingLines so the verifikat
|
|
// is byte-identical to what the preview route showed the user. For
|
|
// same-currency invoices that's just 1930/1510. For cross-currency
|
|
// it also posts a 3960/7960 FX-diff line so the verifikat balances
|
|
// per BFL 5 kap 4-5§. Bypasses createInvoicePaymentJournalEntry on
|
|
// this single path (mark-paid and other callers still use it):
|
|
// see lib/bookkeeping/invoice-payment-lines.ts for the contract.
|
|
const fiscalPeriodId = await findFiscalPeriod(supabase, companyId!, transaction.date)
|
|
if (!fiscalPeriodId) {
|
|
return errorResponseFromCode('INVOICE_PAID_NO_FISCAL_PERIOD', txLog, {
|
|
requestId,
|
|
details: { paymentDate: transaction.date },
|
|
})
|
|
}
|
|
const desc = invoice.customer?.name
|
|
? `Inbetalning kundfaktura ${invoice.invoice_number}, ${invoice.customer.name}`
|
|
: `Inbetalning kundfaktura ${invoice.invoice_number}`
|
|
const { lines: clearingLines } = buildInvoicePaymentClearingLines(
|
|
{
|
|
amount: transaction.amount,
|
|
amount_sek: transaction.amount_sek ?? null,
|
|
currency: transaction.currency,
|
|
exchange_rate: transaction.exchange_rate ?? null,
|
|
},
|
|
{
|
|
currency: invoice.currency,
|
|
exchange_rate: invoice.exchange_rate ?? null,
|
|
remaining_amount: invoice.remaining_amount ?? null,
|
|
total: invoice.total,
|
|
paid_amount: invoice.paid_amount ?? null,
|
|
},
|
|
desc,
|
|
// Cross-currency: pass the spot-rate-converted invoice-currency
|
|
// amount so the helper credits 1510 proportionally and posts the
|
|
// FX-diff line. Same-currency: undefined, helper just uses bankSek.
|
|
fx.required ? fx.paidInInvoiceCurrency : undefined,
|
|
paymentAccount,
|
|
)
|
|
// Re-propagate the invoice's default dimension bag onto every leg,
|
|
// including the FX result lines, so a project's kursvinst/kursförlust
|
|
// stays inside the project P&L. createInvoicePaymentJournalEntry does
|
|
// this for its own callers; the shared line-builder is dimension-
|
|
// agnostic, so the two routes that use it have to do it themselves or
|
|
// dimension users silently lose the tagging on payment vouchers.
|
|
// Copied per line: a shared object would let one line's mutation leak.
|
|
const defaultDimensions = coerceDimensionsBag(
|
|
(invoice as { default_dimensions?: unknown }).default_dimensions,
|
|
)
|
|
if (defaultDimensions) {
|
|
for (const line of clearingLines) line.dimensions = { ...defaultDimensions }
|
|
}
|
|
const journalEntry = await createJournalEntry(supabase, companyId!, user.id, {
|
|
fiscal_period_id: fiscalPeriodId,
|
|
entry_date: transaction.date,
|
|
description: desc,
|
|
source_type: 'invoice_paid',
|
|
source_id: invoice.id,
|
|
lines: clearingLines,
|
|
})
|
|
journalEntryId = journalEntry?.id ?? null
|
|
}
|
|
} catch (err) {
|
|
// AccountsNotInChart is fatal so the UI can open the activation dialog.
|
|
if (err instanceof AccountsNotInChartError) {
|
|
return errorResponse(err, txLog, { requestId })
|
|
}
|
|
// A foreign-currency invoice with no booking rate is a missing-input
|
|
// failure, not a transient booking failure: buildInvoicePaymentClearing
|
|
// Lines refuses rather than valuing the 1510 credit at a fabricated rate.
|
|
// Fully retryable once invoice.exchange_rate is on file.
|
|
// Dispatch on `code`, not instanceof: the class lives in a module route
|
|
// tests routinely vi.mock away, and the literal keeps a mocked-away
|
|
// export from turning into an `undefined === undefined` catch-all.
|
|
if ((err as { code?: unknown })?.code === 'MATCH_INVOICE_BOOKING_RATE_MISSING') {
|
|
return errorResponse(err, txLog, { requestId })
|
|
}
|
|
txLog.error('failed to create payment journal entry', err as Error)
|
|
// ANY failed payment voucher fails the whole match (mirrors
|
|
// match-supplier-invoice): proceeding used to mark the invoice paid and
|
|
// link the transaction with NO verifikat, an unrecoverable half-state:
|
|
// mark-paid rejects 'paid' invoices and this route rejects linked
|
|
// transactions, so no flow could ever complete the booking afterwards.
|
|
// Typed bookkeeping errors (period locked, no fiscal period, ...) map
|
|
// to their registered envelope; everything else returns the invoice-
|
|
// side payment-failure code with a Swedish reason via getErrorMessage,
|
|
// so the raw message never reaches the user (issue #337).
|
|
if (isBookkeepingError(err)) {
|
|
return errorResponse(err, txLog, { requestId })
|
|
}
|
|
return errorResponseFromCode('MATCH_INVOICE_RECORD_PAYMENT_FAILED', txLog, {
|
|
requestId,
|
|
details: { reason: getErrorMessage(err, { context: 'invoice' }) },
|
|
})
|
|
}
|
|
|
|
if (!journalEntryId) {
|
|
// createJournalEntry resolved without an id: the same unrecoverable
|
|
// half-state as a thrown failure, so the match aborts here too
|
|
// (mirrors the supplier route's !journalEntryId guard).
|
|
return errorResponseFromCode('MATCH_INVOICE_RECORD_PAYMENT_FAILED', txLog, { requestId })
|
|
}
|
|
|
|
// Underlag for the payment verifikation: re-attach the invoice PDF that
|
|
// was archived on send to the new payment journal entry. document_
|
|
// attachments.journal_entry_id is one-to-one, so we insert a parallel
|
|
// row pointing at the same storage_path. Same WORM file, second JE
|
|
// pointer: no copy, no schema change. Non-blocking (BFL 7 kap audit
|
|
// gap, but the bank line + invoice still exist as evidence).
|
|
if (journalEntryId && invoice.journal_entry_id) {
|
|
try {
|
|
const { data: invoiceDoc } = await supabase
|
|
.from('document_attachments')
|
|
.select('storage_path, file_name, file_size_bytes, mime_type, sha256_hash')
|
|
.eq('journal_entry_id', invoice.journal_entry_id)
|
|
.eq('company_id', companyId)
|
|
.eq('is_current_version', true)
|
|
.limit(1)
|
|
.maybeSingle()
|
|
if (invoiceDoc) {
|
|
// Destructure error: Supabase client returns { data, error } on
|
|
// postgres-level failures (unique constraint, RLS reject) instead
|
|
// of throwing, so the surrounding try/catch only covers thrown
|
|
// JS exceptions. Log via warn so attachment failures are visible
|
|
// in logs even though we don't abort the match.
|
|
const { error: attachErr } = await supabase.from('document_attachments').insert({
|
|
user_id: user.id,
|
|
company_id: companyId,
|
|
uploaded_by: user.id,
|
|
upload_source: 'system',
|
|
storage_path: invoiceDoc.storage_path,
|
|
file_name: invoiceDoc.file_name,
|
|
file_size_bytes: invoiceDoc.file_size_bytes,
|
|
mime_type: invoiceDoc.mime_type,
|
|
sha256_hash: invoiceDoc.sha256_hash,
|
|
journal_entry_id: journalEntryId,
|
|
})
|
|
if (attachErr) {
|
|
txLog.warn('failed to attach invoice PDF to payment journal entry', {
|
|
attachError: attachErr.message,
|
|
paymentJournalEntryId: journalEntryId,
|
|
invoiceJournalEntryId: invoice.journal_entry_id,
|
|
})
|
|
}
|
|
}
|
|
} catch (err) {
|
|
txLog.warn('failed to attach invoice PDF to payment journal entry', err as Error)
|
|
}
|
|
}
|
|
|
|
// Optimistic lock: only update if invoice is still in a matchable state.
|
|
const { data: updatedRows, error: updateInvError } = await supabase
|
|
.from('invoices')
|
|
.update({
|
|
status: newStatus,
|
|
paid_at: isFullyPaid ? now : null,
|
|
paid_amount: newPaidAmount,
|
|
remaining_amount: newRemaining,
|
|
})
|
|
.eq('id', invoice_id)
|
|
.in('status', ['sent', 'overdue', 'partially_paid'])
|
|
.select('id')
|
|
|
|
if (updateInvError) {
|
|
txLog.error('failed to update invoice status', updateInvError)
|
|
return errorResponse(updateInvError, txLog, { requestId })
|
|
}
|
|
|
|
if (!updatedRows || updatedRows.length === 0) {
|
|
return errorResponseFromCode('MATCH_INVOICE_ALREADY_PAID', txLog, { requestId })
|
|
}
|
|
|
|
// The "intäkt bokförs vid slutbetalning" note only applies to genuine
|
|
// kontantmetoden partials: invoices that were never booked. When the
|
|
// invoice was booked under accrual, the clearing entry already handles
|
|
// the partial cleanly and the note would be misleading.
|
|
const cashMethodNote = (!invoiceAlreadyBooked && accountingMethod === 'cash' && !isFullyPaid)
|
|
? 'Kontantmetoden: intäkt bokförs vid slutbetalning'
|
|
: null
|
|
|
|
// Provenance for a manually-supplied FX rate. The Riksbanken spot rate is
|
|
// self-documenting (rate + rate_date are reproducible), but a rate the
|
|
// user typed from their bank statement is an override of the ML 8 kap
|
|
// 21-23§ obligation and must leave a trail on the verifikat's payment row
|
|
// (BFL 5 kap 6-7§: the verifikation must reflect the actual affärshändelse).
|
|
const manualRateNote =
|
|
fx.required && fx.source === 'manual'
|
|
? `Manuell valutakurs ${fx.rate} ${invoice.currency}/SEK (betalningsdatum ${transaction.date})`
|
|
: null
|
|
|
|
const paymentNotes = [cashMethodNote, manualRateNote].filter(Boolean).join(' · ') || null
|
|
|
|
// Payment row stores amount in INVOICE currency (the column unit). For
|
|
// same-currency that's tx.amount; for cross-currency it's the spot-rate
|
|
// conversion above. exchange_rate records the rate ACTUALLY USED for
|
|
// this payment: Riksbanken (or manual override) on tx.date: per
|
|
// ML 8 kap 21-23§. Falling back to invoice.exchange_rate would record
|
|
// the invoice-date rate, which is what the round-7/8 bot reviews
|
|
// explicitly flagged as wrong.
|
|
const { error: paymentInsertError } = await supabase
|
|
.from('invoice_payments')
|
|
.insert({
|
|
user_id: user.id,
|
|
company_id: companyId,
|
|
invoice_id,
|
|
payment_date: transaction.date,
|
|
amount: paidAmountInInvoiceCurrency,
|
|
currency: invoice.currency,
|
|
exchange_rate: fx.required ? fx.rate : invoice.exchange_rate,
|
|
journal_entry_id: journalEntryId,
|
|
transaction_id: transactionId,
|
|
notes: paymentNotes,
|
|
})
|
|
|
|
if (paymentInsertError) {
|
|
if (paymentInsertError.code === '23505') {
|
|
return errorResponseFromCode('MATCH_INVOICE_DUPLICATE_PAYMENT', txLog, { requestId })
|
|
}
|
|
txLog.error('failed to record invoice payment', paymentInsertError)
|
|
return errorResponseFromCode('MATCH_INVOICE_RECORD_PAYMENT_FAILED', txLog, { requestId })
|
|
}
|
|
|
|
const { error: updateTxError } = await supabase
|
|
.from('transactions')
|
|
.update({
|
|
invoice_id: invoice_id,
|
|
potential_invoice_id: null,
|
|
journal_entry_id: journalEntryId,
|
|
is_business: true,
|
|
category: 'income_services',
|
|
})
|
|
.eq('id', transactionId)
|
|
|
|
if (updateTxError) {
|
|
txLog.error('failed to link transaction to invoice', updateTxError)
|
|
return errorResponseFromCode('MATCH_INVOICE_LINK_TX_FAILED', txLog, { requestId })
|
|
}
|
|
|
|
logMatchEvent(supabase, user.id, transactionId, 'matched', {
|
|
invoiceId: invoice_id,
|
|
matchConfidence: 1.0,
|
|
matchMethod: 'manual_confirm',
|
|
// rate_source / exchange_rate live inside new_state (the persisted JSON
|
|
// column) so a manual override: a user-supplied money-path input: is
|
|
// distinguishable from an automatic Riksbanken lookup in the audit trail
|
|
// (swarm V16 / SOC 2 CC6.1 / GDPR Art.5(1)(f)). Same-currency matches
|
|
// carry rate_source: null.
|
|
newState: {
|
|
status: newStatus,
|
|
paid_amount: newPaidAmount,
|
|
remaining_amount: newRemaining,
|
|
rate_source: fx.required ? fx.source : null,
|
|
exchange_rate: fx.required ? fx.rate : null,
|
|
},
|
|
})
|
|
|
|
try {
|
|
eventBus.emit({
|
|
type: 'invoice.match_confirmed',
|
|
payload: {
|
|
invoice: invoice as Invoice,
|
|
transaction: transaction as Transaction,
|
|
userId: user.id,
|
|
companyId,
|
|
},
|
|
})
|
|
} catch (err) {
|
|
txLog.warn('invoice.match_confirmed event emission failed', err as Error)
|
|
}
|
|
|
|
return NextResponse.json({
|
|
success: true,
|
|
invoice_status: newStatus,
|
|
paid_at: isFullyPaid ? now : null,
|
|
paid_amount: newPaidAmount,
|
|
remaining_amount: newRemaining,
|
|
journal_entry_id: journalEntryId,
|
|
// Always null since a failed voucher now aborts the whole match; the
|
|
// field survives for response-shape compatibility with existing callers.
|
|
journal_entry_error: null,
|
|
category: 'income_services',
|
|
})
|
|
},
|
|
{ requireWrite: true },
|
|
)
|