b5c3c3ec04
* fix(reconciliation): surface bank transactions via robust cash_account_id scoping The per-account reconciliation scoping silently returned zero transactions for companies whose rows were NULL or mis-assigned mid-backfill (e.g. Arcim: 138 transactions, 101 unbooked, yet Bankavstämning showed "0 kr" while the 1930 GL movement and a large difference still displayed). Two causes, both fixed: - scopeTransactionsToAccount used a fragile nested or(...,and(is.null,...)) PostgREST filter. Replace it with a flat, reliable `currency = X AND (cash_account_id = id OR cash_account_id IS NULL)` and share the one implementation with /api/transactions so the status card and the lists can never drift. - The original best-effort backfill only touched NULL rows and an earlier revision mis-assigned cash_account_id (the since-fixed min(uuid) bug), which migrations cannot self-correct. Add an idempotent repair migration that re-seeds the default 1930 account and re-derives cash_account_id (correcting non-NULL mis-assignments) for booked rows and single-account companies. Also localise manualLink's user-facing errors to Swedish. Adds unit coverage for the new filter shape and pg-real coverage for the repair (incl. the Arcim single-account reproduction). Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * feat(transactions): match a bank transaction to an existing verifikat Adds a "Matcha mot befintlig verifikation" action to the Transactions inbox so a bank line that is already booked elsewhere (a salary run, a Fortnox/manual voucher, an invoice paid from the invoice page) can be linked to that existing verifikat with no new bokföring — the capability previously lived only in Reports → Bankavstämning. - Extract the searchable MatchVerifikationPicker into a shared client component. - New MatchVoucherDialog: resolves the tx's cash account, fetches candidates ranked server-side by reconciliation confidence, links via /api/reconciliation/bank/link (so the link is undoable in Bankavstämning). - unmatched-entries route gains an optional transaction_id that ranks candidates (ranking stays server-side; the recon lib is not client-safe). - Inbox row's overflow (⋯) menu gains the new action. Also fixes the Bankavstämning view: editing the date no longer auto-reloads (applies on Filtrera / account change only) and Datum till defaults to today. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix(transactions): actionable Swedish errors when a bank tx cannot be deleted The delete route returned a hardcoded English 409 that getErrorMessage mapped to the misleading generic "En konflikt uppstod. Ladda om sidan...". Return structured bilingual envelopes instead: - TRANSACTION_DELETE_BOOKED (409) for a booked/linked row — steers the user to unlink in Bankavstämning or storna the voucher. - TRANSACTION_DELETE_HAS_AUDIT_TRAIL (409) for the real, common case where an unbooked row carries payment_match_log rows: the cascade hits the audit-immutability trigger (P0001), previously surfaced as a bare 500. Steers the user to match-to-voucher or ignore instead. Updates the DELETE test suite and adds the P0001 case. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * feat(settings): surface DPA and privacy policy links The /dpa page (personuppgiftsbiträdesavtal, GDPR Art. 28) was complete but linked from nowhere. Add a "Sekretess och avtal" card on Inställningar → Konto linking to /privacy and /dpa, and a reciprocal link to the DPA from the privacy policy's sub-processor section. (The DPA already links back to /privacy.) Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix(review): address PR #623 feedback - unmatched-entries: when transaction_id is supplied but resolves to no row in the caller's company, return an empty candidate list instead of silently falling back to the full unranked list (Compliance Swarm V8.2.1, high). - MatchVoucherDialog: preserve a manually-picked voucher when the candidate list reloads (e.g. "Visa alla datum") instead of discarding it (Greptile P2). - DELETE /api/transactions/[id]: return the 404 as the structured { error: { code, message, message_en } } envelope like the handler's other errors, for a uniform contract (Greptile P2). Test updated. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * feat(bookkeeping): allow editing notes on a committed journal entry Saving a note on a posted verifikation failed with "Committed entries are immutable": enforce_journal_entry_immutability() had no posted→posted path, so a notes-only UPDATE fell through to the final RAISE. `notes` is internal annotation metadata (not verifikation content under BFL 5 kap. / BFNAR 2013:2), so add a narrow carve-out that permits a notes-only change on a committed entry — verified with a whole-row to_jsonb() diff so any other field change still raises, and only when status is unchanged. Period-lock enforcement is unaffected. CREATE OR REPLACE in a new migration (same pattern as 20260428160000_fix_journal_entry_immutability_delete_bypass); the migration-017 protections are extended, never weakened. Covered by a pg-real test asserting a notes edit succeeds while amount/description/account edits still fail. (Already applied to production; committing the file + test for repo consistency.) Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix(sandbox): make pre-staged pending operations executor-complete The seeded pending_operations existed only as display previews — approving them failed because commit executors in lib/pending-operations/commit.ts validate required fields on "Godkänn". Seed a backing invoice_inbox_items row and fill the supplier-invoice and categorize params with every field the executors require (inbox_item_id, full items array; real uncategorized transaction_id + category), so the sandbox approval queue is actually approvable end to end. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
107 lines
4.7 KiB
SQL
107 lines
4.7 KiB
SQL
-- Migration: repair transactions.cash_account_id
|
|
--
|
|
-- Why this exists: the original best-effort backfill
|
|
-- (20260606120100_transactions_cash_account_id_backfill.sql) only ever touched
|
|
-- rows whose cash_account_id was still NULL, and an earlier revision of its
|
|
-- single-account pass mis-assigned rows (the "min(uuid)" bug fixed in a later
|
|
-- commit). Migrations run exactly once, so any instance that applied the buggy
|
|
-- revision now carries WRONG (non-NULL) cash_account_id values that the
|
|
-- NULL-only backfill can never correct.
|
|
--
|
|
-- The visible symptom: Bankavstämning (Reports → Bank reconciliation) showed
|
|
-- "Banktransaktioner i perioden: 0 kr" while the 1930 GL movement and a large
|
|
-- difference were still displayed — because the per-account scoping filtered
|
|
-- every transaction out (its cash_account_id matched neither the resolved 1930
|
|
-- account nor the NULL fallback), while the GL side (scoped only by account
|
|
-- number) was unaffected.
|
|
--
|
|
-- This migration RE-DERIVES cash_account_id where it can do so deterministically,
|
|
-- correcting mis-assignments rather than only filling NULLs. It is idempotent:
|
|
-- every pass is a no-op once the data is already correct.
|
|
|
|
-- ------------------------------------------------------------
|
|
-- 0. Re-seed the default 1930 SEK cash account for any company missing one.
|
|
-- Mirrors 20260519154732_seed_default_cash_account.sql so a company created
|
|
-- through a path that skipped the seed (or before it existed) still has a
|
|
-- routable account to scope against. Idempotent via the unique constraint.
|
|
-- ------------------------------------------------------------
|
|
INSERT INTO public.cash_accounts (
|
|
company_id, ledger_account, currency, name, enabled, is_primary, source
|
|
)
|
|
SELECT
|
|
c.id,
|
|
'1930',
|
|
'SEK',
|
|
'Företagskonto (SEK)',
|
|
true,
|
|
NOT EXISTS (
|
|
SELECT 1 FROM public.cash_accounts ca2
|
|
WHERE ca2.company_id = c.id AND ca2.is_primary = true
|
|
),
|
|
'manual'
|
|
FROM public.companies c
|
|
WHERE NOT EXISTS (
|
|
SELECT 1 FROM public.cash_accounts ca
|
|
WHERE ca.company_id = c.id AND ca.ledger_account = '1930'
|
|
)
|
|
ON CONFLICT (company_id, ledger_account) DO NOTHING;
|
|
|
|
-- ------------------------------------------------------------
|
|
-- 1. Authoritative repair for BOOKED rows — from the voucher's single bank line.
|
|
-- Unlike the original pass (a) this does NOT require cash_account_id IS NULL,
|
|
-- so it CORRECTS a row that was mis-assigned. The voucher's 19xx line is the
|
|
-- ground truth for where a booked transaction settled.
|
|
--
|
|
-- Own-account transfers (>1 bank-class line, e.g. 1930 → 1931) are ambiguous
|
|
-- and left untouched, exactly as the original backfill skipped them.
|
|
-- ------------------------------------------------------------
|
|
UPDATE public.transactions t
|
|
SET cash_account_id = ca.id
|
|
FROM public.journal_entry_lines jel
|
|
JOIN public.cash_accounts ca
|
|
ON ca.ledger_account = jel.account_number
|
|
WHERE t.journal_entry_id IS NOT NULL
|
|
AND jel.journal_entry_id = t.journal_entry_id
|
|
AND ca.company_id = t.company_id
|
|
AND jel.account_number BETWEEN '1900' AND '1999'
|
|
AND t.cash_account_id IS DISTINCT FROM ca.id
|
|
AND (
|
|
SELECT count(*)
|
|
FROM public.journal_entry_lines x
|
|
WHERE x.journal_entry_id = t.journal_entry_id
|
|
AND x.account_number BETWEEN '1900' AND '1999'
|
|
) = 1;
|
|
|
|
-- ------------------------------------------------------------
|
|
-- 2. Deterministic repair for SINGLE-account-of-currency companies.
|
|
-- When a company has exactly one ENABLED cash account in a given currency,
|
|
-- every transaction of that currency unambiguously belongs to it — whether
|
|
-- the row is currently NULL or was mis-assigned. This fixes the entire
|
|
-- single-bank-account majority (the common enskild firma / aktiebolag with
|
|
-- one 1930 SEK account) in one shot.
|
|
--
|
|
-- Companies with two same-currency accounts (e.g. checking + savings) are
|
|
-- excluded (HAVING count(*) = 1): we must not guess between them. Their
|
|
-- booked rows are already corrected by pass 1; their unbooked rows keep
|
|
-- whatever they had and rely on the query-time currency fallback.
|
|
-- ------------------------------------------------------------
|
|
WITH single_ca AS (
|
|
SELECT company_id, currency, (array_agg(id))[1] AS cash_account_id
|
|
FROM public.cash_accounts
|
|
WHERE enabled = true
|
|
GROUP BY company_id, currency
|
|
HAVING count(*) = 1
|
|
)
|
|
UPDATE public.transactions t
|
|
SET cash_account_id = s.cash_account_id
|
|
FROM single_ca s
|
|
WHERE s.company_id = t.company_id
|
|
AND s.currency = t.currency
|
|
AND t.cash_account_id IS DISTINCT FROM s.cash_account_id;
|
|
|
|
-- Pass 3 — anything still NULL (multi-same-currency-account companies' unbooked
|
|
-- rows) is left as-is; the query-time currency fallback in
|
|
-- scopeTransactionsToAccount() covers it.
|
|
|
|
NOTIFY pgrst, 'reload schema';
|