* fix(enable-banking): keep bank account mappings across reconnects and surface dead sessions A PSD2 reconnect silently moved the user's ledger mapping. Account identity came from the provider's account uid, which does not survive a re-authorization at every ASPSP, and a fresh connect to an already-connected bank mints a new bank_connections row regardless. Both paths looked like "an account we have never seen", so the allocator handed out the next free 19xx slot and a 1930/1940/1941 mapping came back as 1942-1946 on every consent renewal, roughly quarterly per connection. Match on the IBAN instead. resolvePsd2LedgerAccount() finds the existing cash_accounts row by normalized IBAN before allocating, and upsertFromPsd2 promotes that row in place rather than inserting a second one, so it keeps its id and its linked transactions and is re-pointed at the connection that just authorized. The previous holder's connection status is deliberately ignored: one IBAN is one physical account, and the old row often still reads 'active' because the bank killed the session without telling us. The allocator also stopped treating a 19xx number as free just because no cash_accounts row holds it. A chart imported from SIE carries the company's real bank accounts by name with no PSD2 row behind them, which is how a SEK company account got proposed as an unrelated brokerage account. Overflow now skips chart-occupied numbers, falling back only when nothing unnamed is left. Dead connections kept rendering as "Aktiv": status only ever changed when a transaction fetch failed, so a session killed bank-side stayed healthy-looking with a stale last_synced_at while the user read old balances as current. Add probeSessionHealth() and run it in the daily cron over every connection that run did not prove alive, including the ones the loop skips silently (capability gate, all accounts deselected) and the ones parked in pending_selection that the cron never looked at. It acts only on a definite dead answer; anything ambiguous leaves the row alone, since a wrong flip costs a full BankID re-authorization. The all-accounts-deselected branch is reclassified 'synced' to 'skipped' for the same reason: it never contacts the bank, so it must not count as proof of life. The settings row warns when an active connection has not synced in three days or has never synced. Which company a connection belongs to was invisible. Everything was already scoped to ctx.companyId, so there was no cross-tenant leak, but a bank authorized while the wrong company was active looked identical to the right one. Name the company on the connect surface and in the account picker, and say where the connection went when the callback lands under a different active company. Warn (bypassably) before authorizing a bank where the same user already holds live connections in other companies: several ASPSPs allow one active AIS session per login, so the new authorization can kill the others. The history start date already defaulted to the fiscal-year start; the card above it recommended a mid-year date and contradicted the selected option. It now states the fact and offers the shortcut without presenting it as advice. Not addressed: sharing one PSD2 session across companies. company_id is the tenancy anchor on bank_connections and cash_accounts hangs off (company_id, bank_connection_id), so that needs the session to become its own entity. See DECISIONS.md. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * fix(supplier-invoices): show the posted line description in the voucher preview The "Verifikation som bokförs" preview built its expense debit lines with description set to the raw account number, so the BESKRIVNING column showed "5615" or "6990" where the posted verifikat actually says "Leverantörsfaktura 123, ACME AB". A hardcoded 11-entry ACCOUNT_LABELS map masked this for 2440/2641/26xx, which is why the column read as a mix of friendly labels and bare account numbers, neither of which was the posted text. The preview now renders exactly the line_description the engine writes: the shared invoice-level text on expense lines and 2440, "Ingående moms {rate}% {desc}" on 2641, and the reverse-charge pair taken straight from generateReverseChargeLines instead of being re-derived locally. buildSupplierDescription moves into its own dependency-free module so the client-side preview can call it without pulling the journal engine (and its Supabase server client) into the browser bundle. The account name stays reachable on the AccountNumber hover card. Picked option A from the issue, keeping the fixed invoice-level description rather than propagating each item's own text: the customer-invoice side already writes invoice-level descriptions, so per-item text would create an inconsistency between the two invoice sides rather than remove one, and it would need an aggregation-collision policy in the journal engine. Rationale recorded in DECISIONS.md. Refs #1258 Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * fix(bookkeeping): restore the copy icon on verifikat rows The row-language rewrite in #1123 reused the copy icon's slot for the new expand toggle, removing the zero-click copy affordance from the bookkeeping list without mentioning it. The leftover orphaned copy_voucher_tooltip key in both message files is what identifies it as collateral rather than a product decision. Restore a copy icon in the row's right-edge action cell, reusing that key for aria-label and title. stopPropagation keeps the click off the row's expand toggle. The icon is hover-revealed on md+ and always visible below it: #1123 collapsed the desktop table and the mobile card into one responsive table, so hover-only would leave touch users with nothing. Copy is no longer gated on posted. The copy_from handler and the GET journal-entries route never looked at status, so copying a draft already worked end-to-end and only the detail-page button hid it; the two list surfaces were already ungated. Both list affordances now respect canWrite, which previously dropped read-only users into a dialog they could not submit. The repo does not render components in tests, which is why #1123 removed this silently. Pin the source shape instead, the same way the copy-invoice query is pinned. Closes #1266 Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * fix(transactions): revalidate stale invoice match pointers before offering a match potential_invoice_id / potential_supplier_invoice_id are written once, at bank import, and never revisited. When one of several identical recurring invoices was settled by a different transaction, every other transaction kept pointing at the now fully paid invoice. The match dialog then measured the bank amount against a 0 kr remaining balance and reported a "Beloppen skiljer sig ... fakturan blir delbetald" partial payment, and the worklist offered the same dead suggestion as a one-click confirm row. Worse, the manual escape hatch was hidden exactly when it was needed: TransactionInboxCard only shows "Matcha mot leverantörsfaktura" when no suggestion exists, so a stale pointer left the user with no way at all to reach the correct invoice. Fixed by revalidating at read time rather than by clearing sibling pointers on settle. Invoices are settled through many paths (both match routes, mark-paid, MCP, bank reconciliation, SIE import), so write-time cleanup leaks the moment one is missed, while the candidate lookup covers every route into the list. The shared accept-lists in lib/invoices/matchable-statuses.ts mirror the CAS guards the match routes already enforce. - listSuggestedMatches and the transactions page candidate fetch filter on status + remaining_amount, so a settled candidate yields no suggestion and the manual picker reappears on its own. - InvoiceMatchDialog blocks a settled target with a distinct message and a disabled confirm. Not advisory: both routes reject it outright with MATCH_INVOICE_ALREADY_PAID / MATCH_SI_ALREADY_PAID, so no override could succeed. - The supplier detail card now shows remaining_amount like the customer branch, instead of total. On a partially paid invoice it used to print "1 250 kr" directly beside "Differens: 1 250 kr". - match-supplier-invoice clears potential_supplier_invoice_id on the transaction it just matched, mirroring the customer route. No bookkeeping was ever at risk: both routes already refused a settled target before creating a voucher. The damage was confined to a misleading dialog and a dead end. createQueuedMockSupabase gains passive call recording (calls / findCall / findCalls) because the proxy swallowed filter and update arguments, which made the new assertions inexpressible. Refs #1259, #1260 Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * feat(webhooks): dispatch on emit instead of waiting for the next cron tick (#1256) * feat(webhooks): dispatch on emit instead of waiting for the next cron tick The webhook dispatcher ran only on a per-minute cron, so the floor on delivery latency was up to 60 seconds plus the request. An external consumer that wanted to react as a transaction landed had only one alternative: polling /api/events, which the 100 rpm per-key limit makes expensive and which still cannot beat the tick interval. Schedules one dispatch cycle as soon as deliveries are enqueued. The cron is unchanged and remains the retry and sweep path; this only moves the first attempt forward. Wired into the event-bus fanout plus the two routes that enqueue a delivery directly: the :test verb, whose entire purpose is telling someone whether their receiver works, and the manual delivery retry. Three properties are load-bearing and covered by tests. The kick is never awaited, because eventBus.emit is awaited at ~99 call sites including journal_entry.committed and each delivery can burn a 10 s receiver timeout. It coalesces per function instance, so a bulk booking that emits once per row does not schedule one claim round trip per row. It claims 5 rows rather than the cron's 50, because it runs on the tail of a user-facing request. Double delivery is not a risk: claim_due_webhook_deliveries already claims FOR UPDATE SKIP LOCKED and flips rows to in_flight in the same statement, so a kick racing the cron sees disjoint rows. Does not close #1201, which asks for a realtime stream for API consumers. This is the cheap half. Refs #1201 Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * docs(webhooks): stop claiming the kick makes double delivery impossible Adversarial review of the previous commit caught an overstatement in its own comments. SKIP LOCKED keeps a kick and the cron from claiming the same row at the same moment, but claim_due_webhook_deliveries autocommits before any POST is issued, so from then on ownership is only status='in_flight' and a later cycle's recoverStuckInFlight sweep can re-arm a row still queued behind an earlier cycle's serial loop. Delivery is at-least-once, which is what the public docs already tell receivers ("the same delivery id may arrive more than once ... idempotency is on you"). The comments contradicted that. No behaviour change. The kick does not create this window: the cron claims 50 rows serially against the same 20 s stuck threshold, which is wider than what a batch of 5 can open. Refs #1201 Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com> * fix(bokslut): add bokslut-flow depreciation (78xx) back to the bolagsskatt base (#1253) * fix(bokslut): add bokslut-flow depreciation (78xx) back to the bolagsskatt base sumPostedYearEndDispositions reconstructs resultat fore skatt for the tax calculation, because generateIncomeStatement excludes every source_type='year_end' entry. It summed class 88 and 7533 but not 78xx, so planenlig avskrivning posted by the bokslut flow (lib/bokslut/assets/depreciation-engine.ts) was dropped from the income statement and never added back. The bolagsskatt base and the periodiseringsfond 25 % cap were therefore computed on an overstated result: tax too high by roughly 20.6 % of the depreciation. Also exclude the period's final bokslutsverifikation from the fetch. It carries source_type='year_end' as well and reverses every P&L account, 78xx/88xx/7533 included (verified against production closing entries), so once the year is closed it would cancel the add-back this function exists to produce. That hazard already applied to 88xx and 7533; the fix closes it for all three rather than widening it. Scope is deliberately the tax base only. Making the standalone resultatrakning show bokslut entries is a separate, larger change: the same exclusion is duplicated in the kpi_report_aggregates RPC, it moves displayed profit for every company that ran the bokslut flow, and it means removing the add-back at four call sites. Refs #1051 Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * fix(bokslut): scope the closing-entry lookup to the company and fail loudly Review (CodeRabbit + the compliance swarm, ASVS V8.2.1) flagged the new fiscal_periods read in sumPostedYearEndDispositions on two counts, both fair. It filtered only on the period id while every sibling query in the same function carries the tenant scope. Primary key or not, service-role paths have no RLS to fall back on and the repo's rule is to filter company_id explicitly, so it now does. It also discarded the query error. That mattered more than it looks: a failed read fell through to closingEntryId = null, which silently re-admits the closing verifikat's 78xx/88xx reversals and understates the tax base, i.e. exactly the failure this lookup was added to prevent. It now throws, and the surrounding catch turns it into the existing 'Failed to read posted dispositions' error. A wrong bolagsskatt is worse than a loud failure. Two regression tests: the lookup carries both eq filters, and a lookup failure propagates instead of degrading to a wrong number. Refs #1051 Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com> * fix(storage): drop the client-side DELETE policy on the documents bucket (#1254) * fix(storage): drop the client-side DELETE policy on the documents bucket 20240101000024 documents this bucket as WORM: "No UPDATE or DELETE policies". That described the repo, not production. Production carries a users_delete_own_documents policy that exists in no migration file: FOR DELETE TO authenticated USING (bucket_id = 'documents' AND (storage.foldername(name))[2] = auth.uid()::text) Under it, the uploading user can delete the storage bytes of any document they uploaded under the legacy documents/{userId}/... layout, using nothing but their normal browser token. That includes documents linked to a posted verifikat, which are rakenskapsinformation under the BFL 7 kap 2 § seven-year retention duty. deleteDocument()'s linked-check and the block_document_deletion() trigger both guard the document_attachments ROW, not the object: the row survives, still pointing at a file that is gone. Reproduced against a local replay of the full migration stream: with the policy present the uploader's own DELETE removes the object; with it dropped the same statement matches zero rows. Company-scoped keys were never exposed (their second path segment is the company id, not auth.uid()), so this only ever reached the legacy layout, which is where most documents still live. Safe because every in-app remove() on this bucket already runs on the service role, covered by service_role_all_documents. Deliberately narrow: users_read_own_documents and users_upload_own_documents stay. The Phase B backfill from 20260726092000 has not run, so dropping the legacy SELECT policy now would make existing documents unreadable. That is Phase C. The pg-real test asserts no DELETE and no UPDATE policy over the bucket under ANY name: the hole arrived under a name this repo never used, so pinning a name would not have caught it. Refs #1208 Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * test(storage): make the WORM ratchet see FOR ALL and WITH CHECK policies Review caught two blind spots in the ratchet, both fair. It matched only polcmd 'd' and 'w', but polcmd '*' (FOR ALL) grants DELETE and UPDATE just as effectively, and FOR ALL is the shape the one legitimate policy on this table already uses, so a hostile one would look unremarkable in the catalogue. It also read only polqual, so an UPDATE policy carrying its bucket restriction in WITH CHECK was invisible. Both assertions now run through one helper that covers d/w/*, concatenates USING and WITH CHECK, and filters by grantee so service_role_all_documents (how the application does its authorized deletes) is excluded while every client-reachable role is not. A policy granted to PUBLIC has an empty polroles, which is the most permissive case there is, so it is treated as client-reachable rather than as "no roles". Matching on the substring rather than the exact `bucket_id = 'documents'` shape pg_get_expr emits today: a policy written as bucket_id::text or with the comparison reversed would slip past a stricter match, and for a WORM ratchet a false alarm is cheap while a silent hole is not. Adds a probe case that creates a FOR ALL policy and asserts the helper sees it, so the main assertion cannot pass vacuously. That case earned its keep immediately: it caught that node-postgres hands back a raw string for a name[] column, so the role filter needed rolname::text to work at all. Verified against a local replay of the full migration stream: red with the original prod FOR DELETE policy present, red with a FOR ALL probe, green without either. Full pg-real suite 933 passed. Refs #1208 Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * test(storage): catch a destructive policy that names no bucket at all Adversarial review of the previous commit found the ratchet still failed open, and reproduced it: a policy with no bucket_id predicate covers EVERY bucket, documents included, so gating on the bucket name discarded exactly the widest hole. The concrete shape is Supabase's own stock "Enable delete for users based on user_id" template, USING (auth.uid() = owner), which is the single most likely form of a future dashboard edit. A destructive policy is now in scope unless it provably cannot reach this bucket, i.e. only a bucket_id predicate naming some other bucket exempts it. The behavioural assertions had the matching blind spot: fixtures were seeded without an owner, so an owner-based policy matched NULL and the DELETE reported 0 rows for the wrong reason. Objects now carry an owner the way storage-api stamps them in production, so those tests fail loudly instead of passing by accident. Two probes pin both directions: a bucketless policy must be reported (and is shown to really permit the delete), and a policy scoped to another bucket must not be, so the ratchet cannot start crying wolf on receipts or sie-files and get switched off. Verified against a local replay of the full migration stream: red with the stock bucketless template installed, green without it. Full pg-real suite 935 passed. Refs #1208 Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com> * fix(kontoplan): make a deactivated account reachable again (#1262) is_active=false read as "does not exist" on every read path but as "exists" on the (company_id, account_number) unique constraint, so a deactivated account vanished from the kontoplan with no way back and re-creating it answered "Kontonummer X finns redan i din kontoplan." The write side was already correct: POST /accounts/activate has a toReactivate branch and PUT /accounts/[number] accepts is_active:true. Both were simply unreachable, so this opens routes to them rather than relaxing the read filters, which are load-bearing for AccountsNotInChartError. - Kontoplan gets a "Visa inaktiva" filter; inactive rows carry an "Inaktiv" chip and the existing per-row switch reactivates them in one click. - Deactivating an account that has posted lines now warns first, using the usage count already loaded for the Verifikat column. - POST /accounts distinguishes the two collisions and returns the new ACCOUNT_EXISTS_INACTIVE code; AddAccountDialog offers "Aktivera kontot istallet" rather than a dead-end 409. The stored account is left exactly as it was; values typed into the failed create form are not applied. - bas-lookup consults the company's own chart before the static BAS reference, so a deactivated custom account reads as known and "Aktivera och bokfor" is no longer disabled for it. New in_chart / is_active fields let callers tell "will be added" from "will be revived". - BAS-katalog stops showing "Aktiverat" for an account the company holds but has deactivated; it falls through to a relabelled Aktivera button, and the per-class counts follow. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * fix(supplier-invoices): flag foreign 0 % lines with reverse charge switched off (#1255) * fix(supplier-invoices): flag foreign 0 % lines with reverse charge switched off A foreign supplier charging no Swedish VAT is normally omvand skattskyldighet. With the reverse-charge switch off, createSupplierInvoiceRegistrationEntry emits neither the 26x4 output leg nor the 44xx/45xx basis lines, so ruta 20-24, 30-32 and 48 all stay empty and the momsdeklaration takes a shape Skatteverket rejects. For a fully deductible purchase the net moms att betala is unchanged, which is exactly why this goes unnoticed. The form already auto-ticks reverse charge for eu_business but not for non_eu_business, so that path slips through silently. Adds a pure helper plus a non-blocking banner cloned from the existing rc_account_warning block. Deliberately silent for swedish_business, where 0 % is a genuine exemption that belongs in no ruta at all, and phrased as a question rather than an assertion: a non-EU goods purchase cleared at customs is legitimately 0 % without reverse charge, and pushing that user into ticking the switch would manufacture a new wrong verifikat. Does not add the exempt/import/other picker the issue proposes: supplier_invoices.vat_treatment is metadata that no booking or ruta mapping reads, and the codebase cannot book import VAT at all, so an import option would imply ruta 50/60 were handled when they are not. Refs #1042 Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * fix(supplier-invoices): name the local-VAT case in the foreign 0 % hint Review flagged that the most common foreign document a Swedish small company sees is an invoice carrying the supplier's OWN local VAT, booked at 0 % Swedish VAT with reverse charge correctly off. The banner fires there, and the previous copy only offered "momsfri av annat skal, till exempel en varuimport" as the way out, which does not describe that invoice at all: it is not VAT-free, it carries foreign VAT. Names both legitimate cases explicitly and says 0 % is correct in them, so the hint cannot read as an instruction to tick reverse charge on a purchase where that would produce a wrong verifikat. Title also narrowed to "utan svensk moms" for the same reason. Refs #1042 Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com> * feat(sandbox): call the sandbox assistant Assistenten, not Anna (#1244) A named persona earns its name once someone has been through onboarding and chosen it: it is their assistant and they named it. Nobody in the sandbox chose anything, so a first name reads as a character the product invented and implies a relationship the visitor never opted into. Both halves move together, which is the point. profile_summary is the agent's own self-description inside the system prompt, so leaving it as "Du är Anna" would have the header say one thing while the assistant introduces itself as another in its first sentence. Nothing else in the stack checks that pairing, so a test now does. Scope: this changes the seed, so new sandbox companies get the new name. The 483 sandbox profiles already seeded keep 'Anna' (the seeder returns early once a profile exists, and its caller only runs while verified_at is null). Backfilling those is a production write on demo data and is being raised separately rather than smuggled into a code change. Co-authored-by: Claude Opus 5 <noreply@anthropic.com> * feat(reports): show the last posted voucher per series in report headers Adds a "Senaste bokforda verifikat: A 214, B 37" line to the balans- and resultatrapport, so a printed or exported report answers which vouchers are actually in it rather than only which dates it spans (#1267). Reads MAX(voucher_number) over posted entries, never voucher_sequences.last_number. The sequence counter is an allocation high-water mark that drifts from the books in both directions: next_voucher_number burns a number when the follow-up insert fails, delete_last_voucher decrements by one instead of resetting to the new MAX, and pre-RPC SIE imports left it behind. Since the point of the line is avstamning, an allocated number would send a reconciler chasing a gap that does not exist, so the label says plainly that the number is the posted one. Scoped to the report own date range, so a Q1 report printed in November says something true about Q1. The balansrapport keeps the fiscal-year start as its lower bound because it accumulates. Skipped on a dimension-filtered resultatrapport: that report already discloses it is partial, and an unfiltered voucher range beside a filtered result invites the wrong conclusion. Populated in both engines, so the JSON, PDF and XLSX routes all inherit it without signature changes. Best-effort: a header nicety never breaks a report. The pure formatter lives in its own module so the client view does not pull the Supabase query path into the browser bundle. No new i18n keys; both report views and the PDF template are hard-coded Swedish per the "stays Swedish" report surfaces in .claude/rules/i18n.md. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * fix(customers): stop rendering personnummer ciphertext, make unreadable rows editable, add a reveal path (#1263) customers.personal_number holds AES-256-GCM ciphertext (20260726110000). Three defects compounded into one broken surface for private customers. The list queried Supabase from the browser with select('*') and rendered the raw value, 76-82 chars of hex, into the nowrap identifier cell. It now reads GET /api/customers, which already masks every row, so the ciphertext never leaves the server. Searching by personnummer works again: the client filter had been matching against ciphertext and could never hit. A row whose value cannot be decrypted renders as the placeholder '********-????'. None of the three mask checks recognised it, each having its own '-1234'-only copy, so such a customer could not be edited in ANY field: name and address edits 400'd on a personnummer the user had no way to correct. All three now share one pattern from the new crypto-free lib/customers/mask-personal-number.ts, which the client form can import. Typing a fresh personnummer overwrites the unreadable value, which is the only repair possible: the rejected writes failed whole INSERTs, so there is nothing to backfill. The value was write-only by construction. GET /api/customers/{id}/personal-number is the deliberate drill-in, mirroring the employee convention, gated on the write role because .compliance/ropa.yaml listed no_full_value_read_endpoint as a safeguard for this column; that entry is rewritten rather than left stale, and reveals log actor and customer id but never the value. Also: arcim-migration wrote the identity number as plaintext, which aborts any import containing a Privatperson with 23514 since the constraint flip; and the customer embeds on /api/invoices shipped ciphertext to the browser on every invoice read. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * feat: enhance ruta 05 handling for dynamic revenue accounts - Introduced `fetchDynamicRuta05Accounts` to fetch company-specific revenue accounts marked with a VAT rate, addressing issue #1261. - Updated VAT declaration logic to include these dynamic accounts in ruta 05 calculations, ensuring accurate reporting for user-added accounts. - Modified `ACCOUNT_RUTA` to include account 3000 for completeness in ruta 05. - Enhanced tests to validate the inclusion of user-added revenue accounts in ruta 05 and ensure correct VAT calculations. - Seeded default VAT rates for BAS revenue accounts to ensure proper classification in the VAT declaration. * fix: enhance data handling and masking in customer and invoice APIs * fix(vat): resolve the 3000 gruppkonto's rate for the ruta 05 base split 3000 "Forsaljning inom Sverige" is mapped to ruta05 by ACCOUNT_RUTA, so a balance on it is filed in the right box already. What was missing is the rate split: unlike 3001/3002/3003 the account number carries no sats, and fetchDynamicRuta05Accounts skipped it because it is in ACCOUNT_TO_BOX. A company posting to the gruppkonto therefore got a ruta 05 total that breakdown.invoices.base25/12/6 did not add up to. Surface those rates separately as staticRateByAccount: rate-only on purpose, because the static map already sums the account and adding it to the dynamic account list would double the filed figure. A test pins that single-count property. Also add 3000 to the MCP server's RUTA_05_ACCOUNTS, which is the display list behind report.rutor.ruta05: without it a 3000 balance appeared in the filed projection but not in the report the agent reads back. The comment claiming SALES_OUTPUT_VAT_SHORTFALL reads base25/12/6 was wrong and is corrected. That check derives its expected base from the output-VAT rutor (ruta10/0.25 + ruta11/0.12 + ruta12/0.06); nothing reads the per-rate bases, which are reporting metadata. So the incomplete split never affected a filed return or a warning, only the breakdown. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com> Co-authored-by: Jakob Wennberg <149234542+jakobwennberg@users.noreply.github.com>
1378 lines
59 KiB
TypeScript
1378 lines
59 KiB
TypeScript
import type { Extension, ExtensionContext } from '@/lib/extensions/types'
|
|
import { NextResponse } from 'next/server'
|
|
import {
|
|
startAuthorization,
|
|
getASPSPs,
|
|
getPreferredAuthMethod,
|
|
deleteSession,
|
|
isSandboxMode,
|
|
SessionExpiredError,
|
|
REAUTH_REQUIRED_MESSAGE,
|
|
SYNC_FAILED_MESSAGE,
|
|
type ASPSP,
|
|
} from './lib/api-client'
|
|
import { syncAccountTransactions } from './lib/sync'
|
|
import {
|
|
runReconciliation,
|
|
DEFAULT_UNATTENDED_CONFIDENCE_THRESHOLD,
|
|
} from '@/lib/reconciliation/bank-reconciliation'
|
|
import { checkRateLimit } from '@/lib/auth/rate-limit-http'
|
|
import { requireCapability } from '@/lib/entitlements/has-capability'
|
|
import { CAPABILITY } from '@/lib/entitlements/keys'
|
|
import type { StoredAccount } from './types'
|
|
import type { Transaction } from '@/types'
|
|
|
|
// Per-user limits keep one tenant from spamming any single bank handler.
|
|
// Sliding 60s windows: generous enough for legitimate retry, tight enough
|
|
// to prevent UUID probing or status-machine abuse.
|
|
const RATE_LIMIT_ACCOUNTS = { maxRequests: 20, windowMs: 60_000 }
|
|
const RATE_LIMIT_SYNC = { maxRequests: 10, windowMs: 60_000 }
|
|
const RATE_LIMIT_DISCONNECT = { maxRequests: 10, windowMs: 60_000 }
|
|
|
|
const MAX_ENABLED_UIDS = 50
|
|
|
|
/**
|
|
* Enable Banking (PSD2) extension
|
|
*
|
|
* Provides automatic bank transaction sync via PSD2 open banking.
|
|
* This is an opt-in extension: uncomment the import in loader.ts to activate.
|
|
*
|
|
* Required environment variables:
|
|
* - ENABLE_BANKING_APP_ID
|
|
* - ENABLE_BANKING_PRIVATE_KEY (base64-encoded PEM)
|
|
* - ENABLE_BANKING_SANDBOX (optional, for sandbox mode)
|
|
*/
|
|
export const enableBankingExtension: Extension = {
|
|
id: 'enable-banking',
|
|
name: 'Enable Banking (PSD2)',
|
|
version: '1.0.0',
|
|
|
|
settingsPanel: {
|
|
label: 'Bankintegration (PSD2)',
|
|
path: '/settings/banking',
|
|
},
|
|
|
|
apiRoutes: [
|
|
{
|
|
method: 'GET',
|
|
path: '/banks',
|
|
handler: async (_request: Request, ctx?: ExtensionContext) => {
|
|
const log = ctx?.log ?? console
|
|
try {
|
|
// Detect PSU type from company entity_type
|
|
let psuType: 'personal' | 'business' = 'business'
|
|
if (ctx?.companyId && ctx?.supabase) {
|
|
const { data: company } = await ctx.supabase
|
|
.from('companies')
|
|
.select('entity_type')
|
|
.eq('id', ctx.companyId)
|
|
.single()
|
|
if (company?.entity_type === 'enskild_firma') {
|
|
psuType = 'personal'
|
|
}
|
|
}
|
|
|
|
const aspsps = await getASPSPs('SE', psuType)
|
|
const banks = aspsps.map((aspsp: ASPSP) => ({
|
|
name: aspsp.name,
|
|
country: aspsp.country,
|
|
logo: aspsp.logo,
|
|
bic: aspsp.bic,
|
|
}))
|
|
return NextResponse.json({ banks, psu_type: psuType, sandbox: isSandboxMode() })
|
|
} catch (error) {
|
|
log.error('Error fetching banks:', error)
|
|
return NextResponse.json({
|
|
banks: [
|
|
{ name: 'Nordea', country: 'SE', bic: 'NDEASESS' },
|
|
{ name: 'SEB', country: 'SE', bic: 'ESSESESS' },
|
|
{ name: 'Swedbank', country: 'SE', bic: 'SWEDSESS' },
|
|
{ name: 'Handelsbanken', country: 'SE', bic: 'HANDSESS' },
|
|
],
|
|
sandbox: isSandboxMode(),
|
|
})
|
|
}
|
|
},
|
|
},
|
|
{
|
|
method: 'POST',
|
|
path: '/connect',
|
|
handler: async (request: Request, ctx?: ExtensionContext) => {
|
|
const log = ctx?.log ?? console
|
|
const supabase = ctx?.supabase ?? await (await import('@/lib/supabase/server')).createClient()
|
|
const { data: { user } } = await supabase.auth.getUser()
|
|
|
|
if (!user) {
|
|
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
|
}
|
|
|
|
if (!ctx?.companyId) {
|
|
return NextResponse.json({ error: 'Company context required' }, { status: 400 })
|
|
}
|
|
const companyId = ctx.companyId
|
|
|
|
const blocked = await requireCapability(supabase, companyId, CAPABILITY.bank_sync)
|
|
if (blocked) return blocked
|
|
|
|
const { aspsp_name, aspsp_country, psu_type: explicitPsuType, connection_id: reconnectId } = await request.json()
|
|
|
|
// Reconnect mode: re-authorize an EXISTING connection in place (no
|
|
// disconnect required). The aspsp identity falls back to the stored row
|
|
// when the client omits it, so a closed/expired session can be renewed
|
|
// with one click. A fresh connect still needs the bank name + country.
|
|
const isReconnect = !!reconnectId
|
|
if (!isReconnect && (!aspsp_name || !aspsp_country)) {
|
|
return NextResponse.json(
|
|
{ error: 'aspsp_name and aspsp_country are required' },
|
|
{ status: 400 }
|
|
)
|
|
}
|
|
|
|
try {
|
|
// For reconnect, load the existing connection up front (company-scoped)
|
|
// so we can revoke its dead session and reuse its bank identity.
|
|
let existing:
|
|
| { id: string; bank_name: string; provider: string; session_id: string | null; psu_type: string | null }
|
|
| null = null
|
|
if (isReconnect) {
|
|
const { data, error: findErr } = await supabase
|
|
.from('bank_connections')
|
|
.select('id, bank_name, provider, session_id, psu_type')
|
|
.eq('id', reconnectId)
|
|
.eq('company_id', companyId)
|
|
.single()
|
|
if (findErr || !data) {
|
|
return NextResponse.json({ error: 'Connection not found' }, { status: 404 })
|
|
}
|
|
existing = data
|
|
}
|
|
|
|
// Resolve the aspsp identity. For a reconnect the bank is already
|
|
// known, so derive it authoritatively from the stored row and IGNORE
|
|
// any client-supplied aspsp_name/aspsp_country: the client
|
|
// (BankSyncNowButton) derives the country by string-splitting the
|
|
// provider slug, and trusting that back is needless attack surface
|
|
// (compliance: ASVS V8.2.1/V4.5). A fresh connect has no stored row,
|
|
// so it uses the client values (already required+validated above).
|
|
// The provider slug ends with the country code, e.g. "nordea-se".
|
|
const resolvedAspspName = isReconnect ? existing?.bank_name : aspsp_name
|
|
const resolvedAspspCountry = isReconnect
|
|
? existing?.provider?.split('-').pop()?.toUpperCase() || 'SE'
|
|
: aspsp_country
|
|
if (!resolvedAspspName) {
|
|
return NextResponse.json(
|
|
{ error: 'aspsp_name and aspsp_country are required' },
|
|
{ status: 400 }
|
|
)
|
|
}
|
|
|
|
// Detect PSU type: explicit override > stored type (reconnect) >
|
|
// company entity_type > default 'business'. Reusing the stored type on
|
|
// reconnect is the key fix: re-deriving from entity_type would flip a
|
|
// working 'personal' connection (e.g. an AB owner who signs with a
|
|
// personal Mobile BankID) back to 'business' on every consent renewal,
|
|
// failing at the bank's signing step. The client can still pass an
|
|
// explicit psu_type to switch account type in place.
|
|
let psuType: 'personal' | 'business' = 'business'
|
|
if (explicitPsuType === 'personal' || explicitPsuType === 'business') {
|
|
psuType = explicitPsuType
|
|
} else if (isReconnect && (existing?.psu_type === 'personal' || existing?.psu_type === 'business')) {
|
|
psuType = existing.psu_type
|
|
} else {
|
|
const { data: company } = await supabase
|
|
.from('companies')
|
|
.select('entity_type')
|
|
.eq('id', companyId)
|
|
.single()
|
|
if (company?.entity_type === 'enskild_firma') {
|
|
psuType = 'personal'
|
|
}
|
|
}
|
|
|
|
// Resolve the bank's preferred auth method. Handelsbanken (and some
|
|
// other Swedish banks) expose Mobile BankID only as a hidden DECOUPLED
|
|
// method; without this, Enable Banking defaults to the REDIRECT method,
|
|
// which for Handelsbanken *corporate* PSUs cannot complete with Mobile
|
|
// BankID: the user approves in the app and then hits an error. Returns
|
|
// undefined for banks with no decoupled method, leaving them untouched.
|
|
const authMethod = await getPreferredAuthMethod(
|
|
resolvedAspspName,
|
|
resolvedAspspCountry,
|
|
psuType
|
|
)
|
|
|
|
log.info('[enable-banking] Starting bank connection', {
|
|
user_id: user.id,
|
|
bank: resolvedAspspName,
|
|
country: resolvedAspspCountry,
|
|
psu_type: psuType,
|
|
auth_method: authMethod ?? '(aspsp default)',
|
|
reconnect: isReconnect,
|
|
})
|
|
|
|
// Reject if there's already a recent pending connection for this user+bank
|
|
// to prevent double-click race conditions that confuse the bank's consent
|
|
// flow. Skipped for reconnect: that deliberately re-authorizes a known row.
|
|
if (!isReconnect) {
|
|
const { data: recentPending } = await supabase
|
|
.from('bank_connections')
|
|
.select('id, created_at')
|
|
.eq('company_id', companyId)
|
|
.eq('bank_name', resolvedAspspName)
|
|
.eq('status', 'pending')
|
|
.order('created_at', { ascending: false })
|
|
.limit(1)
|
|
.maybeSingle()
|
|
|
|
if (recentPending) {
|
|
const pendingAge = Date.now() - new Date(recentPending.created_at).getTime()
|
|
const STALE_THRESHOLD_MS = 30 * 1000 // 30 seconds: long enough to cover the redirect handoff, short enough that an abandoned attempt doesn't block the user
|
|
|
|
if (pendingAge < STALE_THRESHOLD_MS) {
|
|
log.info('[enable-banking] Rejecting duplicate connect: recent pending exists', {
|
|
existing_id: recentPending.id,
|
|
age_ms: pendingAge,
|
|
})
|
|
return NextResponse.json(
|
|
{ error: 'En anslutning pågår redan. Vänta och försök igen.' },
|
|
{ status: 409 }
|
|
)
|
|
}
|
|
}
|
|
|
|
// Sweep failed attempts that never became a live connection:
|
|
// stale 'pending' rows (abandoned redirects past the threshold)
|
|
// and 'error' rows left by earlier denied/failed connects.
|
|
// DELETE instead of marking 'error': a parked 'error' row renders
|
|
// forever as an "Åtgärd krävs" card, so a failed attempt followed
|
|
// by a successful retry showed up as two connections to the same
|
|
// bank. The session_id/accounts_data guards protect established
|
|
// connections (anything that ever completed the callback has
|
|
// accounts_data); never-activated rows have no dependents, and
|
|
// the transactions/cash_accounts FKs are ON DELETE SET NULL.
|
|
const { data: sweptRows } = await supabase
|
|
.from('bank_connections')
|
|
.delete()
|
|
.eq('company_id', companyId)
|
|
.eq('bank_name', resolvedAspspName)
|
|
.in('status', ['pending', 'error'])
|
|
.is('session_id', null)
|
|
.is('accounts_data', null)
|
|
.select('id')
|
|
|
|
if (sweptRows?.length) {
|
|
log.info('[enable-banking] Swept never-activated connection attempts', {
|
|
count: sweptRows.length,
|
|
bank: resolvedAspspName,
|
|
})
|
|
}
|
|
}
|
|
|
|
const redirectUrl = `${process.env.NEXT_PUBLIC_APP_URL}/api/extensions/enable-banking/callback`
|
|
|
|
// Generate cryptographic state token for CSRF protection
|
|
const oauthState = crypto.randomUUID()
|
|
|
|
if (isReconnect && existing) {
|
|
// Persist the CSRF state to the existing row BEFORE asking the bank
|
|
// to start an authorization. The OAuth callback locates this row only
|
|
// by oauth_state, so writing it first guarantees that once the bank
|
|
// holds a session bound to this state a matching row already exists.
|
|
// If startAuthorization ran first and this UPDATE then failed, the
|
|
// bank session would be orphaned with no row to complete it.
|
|
//
|
|
// Reuse the SAME row: the callback drives it back to
|
|
// pending_selection → active, so existing transactions and the
|
|
// cash_accounts mirror stay linked. Deliberately keep status
|
|
// 'expired' (NOT 'pending') during the round-trip: this row's
|
|
// created_at is old and the cron deletes stale 'pending' rows after
|
|
// 1h: a reconnect must not be eligible for that. Staying 'expired'
|
|
// also keeps it visible in "Åtgärd krävs" so an abandoned reconnect
|
|
// is recoverable. The callback's oauth_state lookup accepts 'expired'.
|
|
const { error: stateError } = await supabase
|
|
.from('bank_connections')
|
|
.update({
|
|
oauth_state: oauthState,
|
|
status: 'expired',
|
|
session_id: null,
|
|
error_message: null,
|
|
psu_type: psuType,
|
|
})
|
|
.eq('id', existing.id)
|
|
.eq('company_id', companyId)
|
|
|
|
if (stateError) {
|
|
log.error('[enable-banking] Database error staging reconnect state', {
|
|
errorMessage: stateError.message,
|
|
errorCode: stateError.code,
|
|
connection_id: existing.id,
|
|
user_id: user.id,
|
|
})
|
|
throw new Error(`Failed to update connection: ${stateError.message}`)
|
|
}
|
|
|
|
// Best-effort revoke the dead consent at Enable Banking. A
|
|
// closed/expired session is often already gone, so a failure here is
|
|
// expected and non-fatal: the new authorization supersedes it.
|
|
// Logged at WARN so a systematic revoke failure is visible to
|
|
// monitoring (compliance: ASVS V16 / ISO 27001 A.8.15).
|
|
if (existing.session_id) {
|
|
try {
|
|
await deleteSession(existing.session_id)
|
|
} catch (revokeError) {
|
|
log.warn('[enable-banking] Old session revoke skipped (likely already expired)', {
|
|
message: revokeError instanceof Error ? revokeError.message : String(revokeError),
|
|
connection_id: existing.id,
|
|
})
|
|
}
|
|
}
|
|
|
|
const { url, authorization_id } = await startAuthorization(
|
|
resolvedAspspName,
|
|
resolvedAspspCountry,
|
|
redirectUrl,
|
|
oauthState,
|
|
psuType,
|
|
authMethod
|
|
)
|
|
|
|
// Record the bank's authorization_id for audit/traceability. The
|
|
// callback matches on oauth_state alone (already persisted above), so
|
|
// a failure here cannot orphan the flow: log and continue.
|
|
const { error: authIdError } = await supabase
|
|
.from('bank_connections')
|
|
.update({ authorization_id })
|
|
.eq('id', existing.id)
|
|
.eq('company_id', companyId)
|
|
|
|
if (authIdError) {
|
|
log.warn('[enable-banking] Could not persist authorization_id on reconnect (non-fatal)', {
|
|
errorMessage: authIdError.message,
|
|
connection_id: existing.id,
|
|
})
|
|
}
|
|
|
|
return NextResponse.json({
|
|
connection_id: existing.id,
|
|
authorization_url: url,
|
|
})
|
|
}
|
|
|
|
// Fresh connect: create the bank authorization, then persist the new
|
|
// row carrying its oauth_state so the callback can find it.
|
|
const { url, authorization_id } = await startAuthorization(
|
|
resolvedAspspName,
|
|
resolvedAspspCountry,
|
|
redirectUrl,
|
|
oauthState,
|
|
psuType,
|
|
authMethod
|
|
)
|
|
|
|
const { data: connection, error } = await supabase
|
|
.from('bank_connections')
|
|
.insert({
|
|
company_id: companyId,
|
|
user_id: user.id,
|
|
provider: `${resolvedAspspName.toLowerCase().replace(/\s+/g, '-')}-${resolvedAspspCountry.toLowerCase()}`,
|
|
bank_name: resolvedAspspName,
|
|
authorization_id,
|
|
oauth_state: oauthState,
|
|
status: 'pending',
|
|
psu_type: psuType,
|
|
})
|
|
.select()
|
|
.single()
|
|
|
|
if (error) {
|
|
log.error('[enable-banking] Database error storing connection', {
|
|
errorMessage: error.message,
|
|
errorCode: error.code,
|
|
errorDetails: error.details,
|
|
user_id: user.id,
|
|
bank: resolvedAspspName,
|
|
})
|
|
throw new Error(`Failed to store connection: ${error.message}`)
|
|
}
|
|
|
|
return NextResponse.json({
|
|
connection_id: connection.id,
|
|
authorization_url: url,
|
|
})
|
|
} catch (error) {
|
|
log.error('[enable-banking] Connect handler error', {
|
|
message: error instanceof Error ? error.message : String(error),
|
|
stack: error instanceof Error ? error.stack : undefined,
|
|
name: error instanceof Error ? error.name : undefined,
|
|
user_id: user.id,
|
|
aspsp_name,
|
|
aspsp_country,
|
|
})
|
|
return NextResponse.json(
|
|
{ error: error instanceof Error ? error.message : 'Connection failed' },
|
|
{ status: 500 }
|
|
)
|
|
}
|
|
},
|
|
},
|
|
{
|
|
method: 'POST',
|
|
path: '/sync',
|
|
handler: async (request: Request, ctx?: ExtensionContext) => {
|
|
const log = ctx?.log ?? console
|
|
const supabase = ctx?.supabase ?? await (await import('@/lib/supabase/server')).createClient()
|
|
const { data: { user } } = await supabase.auth.getUser()
|
|
|
|
if (!user) {
|
|
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
|
}
|
|
|
|
if (!ctx?.companyId) {
|
|
return NextResponse.json({ error: 'Company context required' }, { status: 400 })
|
|
}
|
|
const companyId = ctx.companyId
|
|
|
|
const blocked = await requireCapability(supabase, companyId, CAPABILITY.bank_sync)
|
|
if (blocked) return blocked
|
|
|
|
const rl = await checkRateLimit({
|
|
prefix: 'enable-banking:sync',
|
|
identifier: user.id,
|
|
...RATE_LIMIT_SYNC,
|
|
})
|
|
if (!rl.ok) return rl.response!
|
|
|
|
// Default 120 days: most callers (Sync Now button, post-activation gap fill)
|
|
// want a deep refresh, not a 30-day blip. Cron uses 7-day incrementals separately.
|
|
// Bank may still cap at ~90 days per PSD2 without fresh SCA: asking for more
|
|
// is harmless and surfaces whatever the ASPSP is willing to return.
|
|
const { connection_id, days_back: rawDaysBack = 120 } = await request.json()
|
|
const days_back = Math.min(Math.max(1, rawDaysBack), 365)
|
|
|
|
const { data: connection, error: connectionError } = await supabase
|
|
.from('bank_connections')
|
|
.select('*')
|
|
.eq('id', connection_id)
|
|
.eq('company_id', companyId)
|
|
.single()
|
|
|
|
if (connectionError || !connection) {
|
|
return NextResponse.json({ error: 'Connection not found' }, { status: 404 })
|
|
}
|
|
|
|
// 'error' is retryable: a transient upstream failure (e.g. ASPSP_ERROR)
|
|
// parks the connection in 'error' while the PSD2 session is still
|
|
// alive, so the UI's "Försök igen" must be allowed through; a
|
|
// successful sync below restores 'active'. 'expired' stays rejected:
|
|
// a dead consent needs re-authorization via /connect, not a retry.
|
|
if (connection.status !== 'active' && connection.status !== 'error') {
|
|
return NextResponse.json({ error: 'Connection is not active' }, { status: 400 })
|
|
}
|
|
|
|
try {
|
|
// Keep the full list for write-back; sync only the enabled subset.
|
|
// undefined enabled === true for back-compat with rows that predate
|
|
// the per-account toggle.
|
|
const allAccounts = (connection.accounts_data as StoredAccount[] || []).map(a => ({ ...a }))
|
|
const accounts = allAccounts.filter(a => a.enabled !== false)
|
|
|
|
if (accounts.length === 0) {
|
|
return NextResponse.json(
|
|
{ error: 'Inga konton är valda för synkning. Öppna "Hantera konton" för att aktivera minst ett.' },
|
|
{ status: 400 }
|
|
)
|
|
}
|
|
|
|
const toDate = new Date().toISOString().split('T')[0]
|
|
const fromDate = new Date(Date.now() - days_back * 24 * 60 * 60 * 1000)
|
|
.toISOString()
|
|
.split('T')[0]
|
|
const syncStartedAt = new Date().toISOString()
|
|
|
|
// Use ctx.services.ingestTransactions when available
|
|
const ingestFn = ctx?.services.ingestTransactions
|
|
|
|
// Detect SIE overlap: skip auto-categorization if the sync range
|
|
// overlaps with a completed SIE import to prevent double-booking.
|
|
// Reconciliation still links bank transactions to existing GL lines.
|
|
const { data: sieOverlap } = await supabase
|
|
.from('sie_imports')
|
|
.select('id')
|
|
.eq('company_id', companyId)
|
|
.eq('status', 'completed')
|
|
.gte('fiscal_year_end', fromDate)
|
|
.limit(1)
|
|
.maybeSingle()
|
|
|
|
// Check if user is a viewer: viewers get rawInsertOnly (no categorization)
|
|
const { data: membership } = await supabase
|
|
.from('company_members')
|
|
.select('role')
|
|
.eq('company_id', companyId)
|
|
.eq('user_id', user.id)
|
|
.maybeSingle()
|
|
const isViewer = membership?.role === 'viewer'
|
|
|
|
// Use strategy=longest when the caller asks for >= 30 days of history
|
|
// (initial sync, manual backfill). Short windows get the implicit
|
|
// default since there's no older data to surface.
|
|
const syncOptions = {
|
|
...(sieOverlap ? { skipAutoCategorization: true } : {}),
|
|
...(isViewer ? { rawInsertOnly: true } : {}),
|
|
...(days_back >= 30 ? { strategy: 'longest' as const } : {}),
|
|
}
|
|
|
|
if (sieOverlap) {
|
|
log.info('SIE import overlap detected: suppressing auto-categorization', {
|
|
sieImportId: sieOverlap.id,
|
|
fromDate,
|
|
toDate,
|
|
})
|
|
}
|
|
const results = await Promise.all(
|
|
accounts.map(account => syncAccountTransactions(
|
|
supabase,
|
|
companyId,
|
|
user.id,
|
|
connection.id,
|
|
account,
|
|
fromDate,
|
|
toDate,
|
|
ingestFn,
|
|
syncOptions
|
|
))
|
|
)
|
|
|
|
const totalImported = results.reduce((sum, r) => sum + r.imported, 0)
|
|
const totalDuplicates = results.reduce((sum, r) => sum + r.duplicates, 0)
|
|
|
|
// When SIE overlap is detected, run a batch reconciliation sweep.
|
|
// The greedy algorithm considers all candidates globally (highest-
|
|
// confidence first) and catches matches the inline per-transaction
|
|
// pass may have missed due to processing order.
|
|
// Skip for viewers: reconciliation updates transactions which viewers cannot do.
|
|
if (sieOverlap && totalImported > 0 && !isViewer) {
|
|
try {
|
|
const reconResult = await runReconciliation(supabase, companyId, user.id, {
|
|
dateFrom: fromDate,
|
|
dateTo: toDate,
|
|
// This sweep applies without a human reviewing a dry-run, so
|
|
// never commit low-confidence (fuzzy / date-range) matches.
|
|
confidenceThreshold: DEFAULT_UNATTENDED_CONFIDENCE_THRESHOLD,
|
|
})
|
|
if (reconResult.applied > 0 || reconResult.skippedBelowThreshold > 0) {
|
|
log.info('Post-sync batch reconciliation matched additional transactions', {
|
|
applied: reconResult.applied,
|
|
skippedBelowThreshold: reconResult.skippedBelowThreshold,
|
|
total: reconResult.matches.length,
|
|
})
|
|
}
|
|
} catch {
|
|
// Non-critical: transactions remain uncategorized for manual review
|
|
}
|
|
}
|
|
|
|
const syncedAt = new Date().toISOString()
|
|
await supabase
|
|
.from('bank_connections')
|
|
.update({
|
|
accounts_data: allAccounts,
|
|
last_synced_at: syncedAt,
|
|
// A successful sync proves the session works again: recover an
|
|
// 'error' connection to 'active' (so the cron picks it up again)
|
|
// and clear any stale failure message from the settings panel.
|
|
...(connection.status === 'error' ? { status: 'active' } : {}),
|
|
...(connection.status === 'error' || connection.error_message
|
|
? { error_message: null }
|
|
: {}),
|
|
})
|
|
.eq('id', connection.id)
|
|
|
|
if (totalImported > 0) {
|
|
const { data: syncedTransactions } = await supabase
|
|
.from('transactions')
|
|
.select('*')
|
|
.eq('company_id', companyId)
|
|
.eq('bank_connection_id', connection.id)
|
|
.gte('created_at', syncStartedAt)
|
|
.order('created_at', { ascending: false })
|
|
.limit(totalImported)
|
|
|
|
if (syncedTransactions && syncedTransactions.length > 0) {
|
|
const emit = ctx?.emit ?? (await import('@/lib/events/bus')).eventBus.emit.bind((await import('@/lib/events/bus')).eventBus)
|
|
await emit({
|
|
type: 'transaction.synced',
|
|
payload: { transactions: syncedTransactions as Transaction[], userId: user.id, companyId },
|
|
})
|
|
}
|
|
}
|
|
|
|
return NextResponse.json({
|
|
imported: totalImported,
|
|
duplicates: totalDuplicates,
|
|
last_synced_at: syncedAt,
|
|
})
|
|
} catch (error) {
|
|
log.error('[enable-banking] Sync handler error', {
|
|
message: error instanceof Error ? error.message : String(error),
|
|
stack: error instanceof Error ? error.stack : undefined,
|
|
name: error instanceof Error ? error.name : undefined,
|
|
user_id: user.id,
|
|
connection_id,
|
|
connectionStatus: connection.status,
|
|
bankName: connection.bank_name,
|
|
})
|
|
|
|
// A dead PSD2 session (closed/expired/invalid consent) can't be fixed
|
|
// by retrying: the user must re-authorize. Flip the connection to
|
|
// 'expired' so the UI surfaces the reconnect affordance, and tell the
|
|
// client re-auth is required (reauth_required) so it can offer a
|
|
// one-click "Förnya anslutning" instead of a dead-end error. No
|
|
// disconnect needed: /connect reconnects this same connection in place.
|
|
if (error instanceof SessionExpiredError) {
|
|
await supabase
|
|
.from('bank_connections')
|
|
.update({ status: 'expired', error_message: REAUTH_REQUIRED_MESSAGE })
|
|
.eq('id', connection.id)
|
|
.eq('company_id', companyId)
|
|
return NextResponse.json(
|
|
{
|
|
error: REAUTH_REQUIRED_MESSAGE,
|
|
code: 'SESSION_EXPIRED',
|
|
reauth_required: true,
|
|
connection_id: connection.id,
|
|
},
|
|
{ status: 409 }
|
|
)
|
|
}
|
|
|
|
// Non-session failure: the settings panel toasts this error verbatim
|
|
// and renders error_message on the connection card, so both must be
|
|
// the short Swedish message: the raw Enable Banking body (an English
|
|
// JSON envelope) is already in the server log above. Refresh the
|
|
// stored error_message on rows already in 'error' so a failed retry
|
|
// replaces any stale raw body persisted by older code.
|
|
if (connection.status === 'error') {
|
|
await supabase
|
|
.from('bank_connections')
|
|
.update({ error_message: SYNC_FAILED_MESSAGE })
|
|
.eq('id', connection.id)
|
|
.eq('company_id', companyId)
|
|
}
|
|
|
|
return NextResponse.json({ error: SYNC_FAILED_MESSAGE }, { status: 500 })
|
|
}
|
|
},
|
|
},
|
|
{
|
|
method: 'PATCH',
|
|
path: '/accounts',
|
|
handler: async (request: Request, ctx?: ExtensionContext) => {
|
|
const log = ctx?.log ?? console
|
|
const supabase = ctx?.supabase ?? await (await import('@/lib/supabase/server')).createClient()
|
|
const { data: { user } } = await supabase.auth.getUser()
|
|
|
|
if (!user) {
|
|
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
|
}
|
|
|
|
// company_id must come from the verified extension context, never fall
|
|
// back to user.id (which is a different identifier dimension and would
|
|
// silently mis-scope queries in multi-tenant deployments).
|
|
if (!ctx?.companyId) {
|
|
return NextResponse.json({ error: 'Company context required' }, { status: 400 })
|
|
}
|
|
const companyId = ctx.companyId
|
|
|
|
const rl = await checkRateLimit({
|
|
prefix: 'enable-banking:accounts',
|
|
identifier: user.id,
|
|
...RATE_LIMIT_ACCOUNTS,
|
|
})
|
|
if (!rl.ok) return rl.response!
|
|
|
|
const body = await request.json().catch(() => null)
|
|
const connection_id = body?.connection_id
|
|
const enabled_uids = body?.enabled_uids
|
|
const rawLookback = body?.initial_lookback_days
|
|
const rawLookbackFromDate = body?.initial_lookback_from_date
|
|
const account_mappings = body?.account_mappings
|
|
|
|
if (typeof connection_id !== 'string' || !connection_id) {
|
|
return NextResponse.json({ error: 'connection_id krävs' }, { status: 400 })
|
|
}
|
|
if (!Array.isArray(enabled_uids) || !enabled_uids.every(u => typeof u === 'string')) {
|
|
return NextResponse.json({ error: 'enabled_uids måste vara en lista av strängar' }, { status: 400 })
|
|
}
|
|
if (enabled_uids.length === 0) {
|
|
return NextResponse.json(
|
|
{ error: 'Välj minst ett konto, eller koppla bort banken om inga konton ska synkas.' },
|
|
{ status: 400 }
|
|
)
|
|
}
|
|
if (enabled_uids.length > MAX_ENABLED_UIDS) {
|
|
return NextResponse.json(
|
|
{ error: `Max ${MAX_ENABLED_UIDS} konton per anslutning.` },
|
|
{ status: 400 }
|
|
)
|
|
}
|
|
|
|
// account_mappings is optional. When present, it's an array of
|
|
// { uid, ledger_account } pairs that route per-account ingest to a
|
|
// specific BAS account (e.g. EUR account → 1932 instead of the default 1930).
|
|
// Restrict to BAS class 19 (kassa/bank). Accepting e.g. 3001 (revenue)
|
|
// or 2640 (input VAT) here would silently misroute every bank-side
|
|
// journal-entry leg into a revenue/VAT account, corrupting both the
|
|
// ledger and momsdeklaration. The chart-of-accounts existence check
|
|
// below is necessary but not sufficient: those accounts likely do
|
|
// exist in the chart, but they're the wrong class.
|
|
const BAS_ACCOUNT_PATTERN = /^19[0-9]{2}$/
|
|
type AccountMapping = { uid: string; ledger_account?: string | null }
|
|
let mappings: AccountMapping[] = []
|
|
if (account_mappings !== undefined) {
|
|
if (!Array.isArray(account_mappings)) {
|
|
return NextResponse.json(
|
|
{ error: 'account_mappings måste vara en lista' },
|
|
{ status: 400 }
|
|
)
|
|
}
|
|
for (const m of account_mappings) {
|
|
if (!m || typeof m !== 'object' || typeof m.uid !== 'string') {
|
|
return NextResponse.json(
|
|
{ error: 'account_mappings: varje post kräver uid (sträng)' },
|
|
{ status: 400 }
|
|
)
|
|
}
|
|
if (m.ledger_account != null && (typeof m.ledger_account !== 'string' || !BAS_ACCOUNT_PATTERN.test(m.ledger_account))) {
|
|
return NextResponse.json(
|
|
{ error: 'account_mappings: ledger_account måste vara ett BAS-konto i klass 19 (1900-1999)' },
|
|
{ status: 400 }
|
|
)
|
|
}
|
|
}
|
|
mappings = account_mappings as AccountMapping[]
|
|
}
|
|
|
|
// initial_lookback_days only applies on the pending_selection→active transition.
|
|
// Default 120; clamp to [30, 365]. Ignored for selection edits.
|
|
// PSD2 obliges ASPSPs to ~90 days without fresh SCA, but many Swedish banks
|
|
// return more if asked: request 120 and accept whatever the bank gives back.
|
|
//
|
|
// If the client sent initial_lookback_from_date (preferred for fiscal-year-anchored
|
|
// backfills), derive days from that and reject future dates outright. Otherwise
|
|
// fall back to initial_lookback_days (or the 120-day default).
|
|
if (typeof rawLookbackFromDate === 'string' && /^\d{4}-\d{2}-\d{2}$/.test(rawLookbackFromDate)) {
|
|
const from = new Date(rawLookbackFromDate + 'T00:00:00Z')
|
|
if (!Number.isFinite(from.getTime())) {
|
|
return NextResponse.json(
|
|
{ error: 'initial_lookback_from_date är inte ett giltigt datum.' },
|
|
{ status: 400 }
|
|
)
|
|
}
|
|
const diffMs = Date.now() - from.getTime()
|
|
const daysFromDate = Math.ceil(diffMs / (24 * 60 * 60 * 1000))
|
|
if (daysFromDate <= 0) {
|
|
return NextResponse.json(
|
|
{ error: 'initial_lookback_from_date måste ligga i det förflutna.' },
|
|
{ status: 400 }
|
|
)
|
|
}
|
|
}
|
|
const initialLookbackDays = (() => {
|
|
if (typeof rawLookbackFromDate === 'string' && /^\d{4}-\d{2}-\d{2}$/.test(rawLookbackFromDate)) {
|
|
const from = new Date(rawLookbackFromDate + 'T00:00:00Z')
|
|
// Future/invalid dates already rejected above; days > 0 is guaranteed.
|
|
const diffMs = Date.now() - from.getTime()
|
|
const days = Math.ceil(diffMs / (24 * 60 * 60 * 1000))
|
|
return Math.min(365, Math.max(1, days))
|
|
}
|
|
const n = typeof rawLookback === 'number' && Number.isFinite(rawLookback) ? rawLookback : 120
|
|
return Math.min(365, Math.max(30, Math.round(n)))
|
|
})()
|
|
|
|
const { data: connection, error: connectionError } = await supabase
|
|
.from('bank_connections')
|
|
.select('id, status, accounts_data, bank_name')
|
|
.eq('id', connection_id)
|
|
.eq('company_id', companyId)
|
|
.single()
|
|
|
|
if (connectionError || !connection) {
|
|
return NextResponse.json({ error: 'Connection not found' }, { status: 404 })
|
|
}
|
|
|
|
if (connection.status !== 'pending_selection' && connection.status !== 'active') {
|
|
return NextResponse.json(
|
|
{ error: 'Anslutningen kan inte konfigureras i nuvarande status.' },
|
|
{ status: 400 }
|
|
)
|
|
}
|
|
|
|
const existing = (connection.accounts_data as StoredAccount[] || []).map(a => ({ ...a }))
|
|
const knownUids = new Set(existing.map(a => a.uid))
|
|
const unknownUids = enabled_uids.filter(uid => !knownUids.has(uid))
|
|
if (unknownUids.length > 0) {
|
|
return NextResponse.json(
|
|
{ error: 'Ett eller flera konton kunde inte hittas.', unknown_uids: unknownUids },
|
|
{ status: 400 }
|
|
)
|
|
}
|
|
|
|
// Mirror the enabled_uids guard for account_mappings: without this,
|
|
// a typo'd UID in the mapping list is silently dropped (the entry
|
|
// never lands in the resulting accounts_data) while the response is
|
|
// still 200, leaving the client to believe the mapping was applied.
|
|
const unknownMappingUids = mappings.map(m => m.uid).filter(uid => !knownUids.has(uid))
|
|
if (unknownMappingUids.length > 0) {
|
|
return NextResponse.json(
|
|
{ error: 'account_mappings innehåller okända konto-uid.', unknown_uids: unknownMappingUids },
|
|
{ status: 400 }
|
|
)
|
|
}
|
|
|
|
// Verify any provided ledger_account values actually exist in the
|
|
// company's chart of accounts. Prevents users from typing arbitrary
|
|
// numbers via the API and breaking journal entry creation later.
|
|
const requestedLedgerAccounts = mappings
|
|
.map(m => m.ledger_account)
|
|
.filter((a): a is string => typeof a === 'string')
|
|
if (requestedLedgerAccounts.length > 0) {
|
|
const { data: chartRows } = await supabase
|
|
.from('chart_of_accounts')
|
|
.select('account_number')
|
|
.eq('company_id', companyId)
|
|
.in('account_number', requestedLedgerAccounts)
|
|
const validAccountNumbers = new Set((chartRows || []).map(r => r.account_number as string))
|
|
const invalid = requestedLedgerAccounts.filter(a => !validAccountNumbers.has(a))
|
|
if (invalid.length > 0) {
|
|
return NextResponse.json(
|
|
{
|
|
error: 'Ett eller flera bokföringskonton finns inte i kontoplanen.',
|
|
invalid_accounts: invalid,
|
|
},
|
|
{ status: 400 }
|
|
)
|
|
}
|
|
}
|
|
|
|
const enabledSet = new Set(enabled_uids)
|
|
const mappingsByUid = new Map(mappings.map(m => [m.uid, m]))
|
|
const updatedAccounts: StoredAccount[] = existing.map(a => {
|
|
const mapping = mappingsByUid.get(a.uid)
|
|
return {
|
|
...a,
|
|
enabled: enabledSet.has(a.uid),
|
|
// Apply ledger_account from mapping when present. Explicit null clears it.
|
|
// Absent mapping leaves the existing ledger_account untouched (back-compat
|
|
// with selection-edit calls that don't include account_mappings).
|
|
...(mapping
|
|
? { ledger_account: mapping.ledger_account ?? undefined }
|
|
: {}),
|
|
}
|
|
})
|
|
|
|
// Resolve the effective mirror ledger for every account up front and
|
|
// reject collisions with a 400 — the mirror pass below writes into
|
|
// cash_accounts, whose UNIQUE (company_id, ledger_account) constraint
|
|
// would otherwise fail per-account and get swallowed, leaving accounts
|
|
// silently unmirrored.
|
|
const { resolvePsd2LedgerAccount, upsertFromPsd2, getRevokedConnectionIds, normalizeIban } =
|
|
await import('@/lib/cash-accounts/service')
|
|
|
|
const { data: companyCashRows } = await supabase
|
|
.from('cash_accounts')
|
|
.select('id, external_uid, bank_connection_id, ledger_account, iban')
|
|
.eq('company_id', companyId)
|
|
const cashRows = (companyCashRows ?? []) as Array<{
|
|
id: string
|
|
external_uid: string | null
|
|
bank_connection_id: string | null
|
|
ledger_account: string
|
|
iban: string | null
|
|
}>
|
|
|
|
// Rows that already represent one of THIS connection's accounts, matched
|
|
// on IBAN rather than on the provider uid. After a re-authorization (new
|
|
// uids) or a fresh connect to an already-connected bank (new connection
|
|
// row), these are the user's own mappings wearing a stale owner: they
|
|
// must not be treated as another bank's territory, and the mirror pass
|
|
// below promotes them in place instead of inserting a second row.
|
|
const rowByIban = new Map<string, { id: string; ledger_account: string }>()
|
|
for (const r of cashRows) {
|
|
const normalized = normalizeIban(r.iban)
|
|
if (normalized && !rowByIban.has(normalized)) {
|
|
rowByIban.set(normalized, { id: r.id, ledger_account: r.ledger_account })
|
|
}
|
|
}
|
|
const reuseRowByUid = new Map<string, { id: string; ledger_account: string }>()
|
|
for (const a of updatedAccounts) {
|
|
const normalized = normalizeIban(a.iban)
|
|
const row = normalized ? rowByIban.get(normalized) : undefined
|
|
if (row) reuseRowByUid.set(a.uid, row)
|
|
}
|
|
const ownIbanRowIds = new Set([...reuseRowByUid.values()].map(r => r.id))
|
|
const existingLedgerByUid = new Map(
|
|
cashRows
|
|
.filter(r => r.bank_connection_id === connection.id && r.external_uid)
|
|
.map(r => [r.external_uid as string, r.ledger_account])
|
|
)
|
|
// Slots held by OTHER connections' PSD2 accounts — an explicit mapping
|
|
// onto one of those would violate the unique constraint. Manual rows
|
|
// are not foreign: upsertFromPsd2 promotes them in place. Rows held by
|
|
// a REVOKED connection are not foreign either: those are orphaned
|
|
// leftovers (disconnect predating the claim release, or a lost demote)
|
|
// and upsertFromPsd2 promotes them in place too. Excluding them here
|
|
// is the self-heal path for companies whose bank was disconnected
|
|
// before disconnect started releasing ledger claims.
|
|
const foreignConnectionIds = [
|
|
...new Set(
|
|
cashRows
|
|
.filter(r => r.bank_connection_id !== null && r.bank_connection_id !== connection.id)
|
|
.map(r => r.bank_connection_id as string)
|
|
),
|
|
]
|
|
const revokedConnectionIds = await getRevokedConnectionIds(
|
|
supabase,
|
|
companyId,
|
|
foreignConnectionIds
|
|
)
|
|
const foreignConnectedLedgers = new Set(
|
|
cashRows
|
|
.filter(
|
|
r =>
|
|
r.bank_connection_id !== null &&
|
|
r.bank_connection_id !== connection.id &&
|
|
!revokedConnectionIds.has(r.bank_connection_id) &&
|
|
// Same IBAN as one of this connection's accounts: the same
|
|
// physical account under a stale owner, not a foreign claim.
|
|
!ownIbanRowIds.has(r.id)
|
|
)
|
|
.map(r => r.ledger_account)
|
|
)
|
|
|
|
const effectiveLedgerByUid = new Map<string, string>()
|
|
const usedLedgers = new Set<string>()
|
|
const duplicateLedgers = new Set<string>()
|
|
const conflictingLedgers = new Set<string>()
|
|
|
|
// First pass: accounts with an explicit or previously mirrored ledger.
|
|
for (const a of updatedAccounts) {
|
|
const ledger = a.ledger_account ?? existingLedgerByUid.get(a.uid)
|
|
if (!ledger) continue
|
|
if (usedLedgers.has(ledger)) duplicateLedgers.add(ledger)
|
|
if (foreignConnectedLedgers.has(ledger) && existingLedgerByUid.get(a.uid) !== ledger) {
|
|
conflictingLedgers.add(ledger)
|
|
}
|
|
usedLedgers.add(ledger)
|
|
effectiveLedgerByUid.set(a.uid, ledger)
|
|
}
|
|
|
|
if (duplicateLedgers.size > 0) {
|
|
return NextResponse.json(
|
|
{
|
|
error: 'Flera bankkonton kan inte bokföras på samma konto. Välj olika bokföringskonton.',
|
|
duplicate_accounts: [...duplicateLedgers],
|
|
},
|
|
{ status: 400 }
|
|
)
|
|
}
|
|
if (conflictingLedgers.size > 0) {
|
|
return NextResponse.json(
|
|
{
|
|
error: 'Bokföringskontot används redan av ett bankkonto från en annan bankanslutning.',
|
|
conflicting_accounts: [...conflictingLedgers],
|
|
},
|
|
{ status: 400 }
|
|
)
|
|
}
|
|
|
|
// Second pass: allocate a free slot for accounts with no ledger at all
|
|
// (legacy connections mirrored before allocation existed, or mappings
|
|
// explicitly cleared). Allocation failure must never block selection
|
|
// save — fall back to the pre-allocator behavior (1930) and let the
|
|
// mirror pass surface any collision per-account, as before.
|
|
for (const a of updatedAccounts) {
|
|
if (effectiveLedgerByUid.has(a.uid)) continue
|
|
let allocated: string | null = null
|
|
try {
|
|
const resolved = await resolvePsd2LedgerAccount(supabase, companyId, user.id, {
|
|
iban: a.iban,
|
|
currency: a.currency,
|
|
accountName: a.name,
|
|
exclude: usedLedgers,
|
|
})
|
|
allocated = resolved?.ledgerAccount ?? null
|
|
} catch (allocErr) {
|
|
log.warn('[enable-banking] ledger allocation failed on selection save', {
|
|
connectionId: connection.id,
|
|
uid: a.uid,
|
|
error: allocErr instanceof Error ? allocErr.message : String(allocErr),
|
|
})
|
|
}
|
|
const ledger = allocated ?? '1930'
|
|
usedLedgers.add(ledger)
|
|
effectiveLedgerByUid.set(a.uid, ledger)
|
|
}
|
|
|
|
// accounts_data mirrors the resolved assignment so the picker
|
|
// pre-fills reality on the next open.
|
|
for (const a of updatedAccounts) {
|
|
a.ledger_account = effectiveLedgerByUid.get(a.uid)
|
|
}
|
|
|
|
// State machine: only transition pending_selection → active. Once
|
|
// active, the status field is omitted from the update so the same
|
|
// endpoint can be reused to change account selection without
|
|
// re-asserting a transition that has already happened.
|
|
const updatePayload: { accounts_data: StoredAccount[]; status?: 'active' } = {
|
|
accounts_data: updatedAccounts,
|
|
}
|
|
if (connection.status === 'pending_selection') {
|
|
updatePayload.status = 'active'
|
|
}
|
|
|
|
const { error: updateError } = await supabase
|
|
.from('bank_connections')
|
|
.update(updatePayload)
|
|
.eq('id', connection.id)
|
|
|
|
if (updateError) {
|
|
log.error('[enable-banking] Failed to update account selection', {
|
|
errorMessage: updateError.message,
|
|
connectionId: connection.id,
|
|
userId: user.id,
|
|
companyId,
|
|
})
|
|
return NextResponse.json({ error: 'Kunde inte spara kontoval' }, { status: 500 })
|
|
}
|
|
|
|
// Mirror the user's selection into cash_accounts so routing decisions
|
|
// and reconciliation pick up the new enabled state + ledger mapping
|
|
// without reading the JSONB column.
|
|
{
|
|
for (const a of updatedAccounts) {
|
|
const ledgerAccount = a.ledger_account ?? '1930'
|
|
// Only reuse the IBAN-matched row when it already sits on the
|
|
// ledger we are about to write. If the user deliberately remapped
|
|
// the account to a different BAS number, promoting the old row
|
|
// would move a row out from under the ledger it still holds.
|
|
const reuseRow = reuseRowByUid.get(a.uid)
|
|
const reuseCashAccountId =
|
|
reuseRow && reuseRow.ledger_account === ledgerAccount ? reuseRow.id : null
|
|
try {
|
|
await upsertFromPsd2(supabase, companyId, {
|
|
bank_connection_id: connection.id,
|
|
external_uid: a.uid,
|
|
currency: a.currency,
|
|
ledger_account: ledgerAccount,
|
|
iban: a.iban ?? null,
|
|
name: a.name ?? null,
|
|
balance: a.balance ?? null,
|
|
balance_updated_at: a.balance_updated_at ?? null,
|
|
enabled: a.enabled ?? true,
|
|
reuse_cash_account_id: reuseCashAccountId,
|
|
})
|
|
} catch (cashErr) {
|
|
log.error('[enable-banking] Failed to mirror cash_account on selection save', {
|
|
connectionId: connection.id,
|
|
uid: a.uid,
|
|
error: cashErr instanceof Error ? cashErr.message : String(cashErr),
|
|
})
|
|
}
|
|
}
|
|
}
|
|
|
|
const newStatus = updatePayload.status ?? connection.status
|
|
log.info('[enable-banking] Account selection saved', {
|
|
connectionId: connection.id,
|
|
enabledCount: enabled_uids.length,
|
|
totalCount: existing.length,
|
|
previousStatus: connection.status,
|
|
newStatus,
|
|
userId: user.id,
|
|
companyId,
|
|
})
|
|
|
|
try {
|
|
const emit = ctx?.emit ?? (await import('@/lib/events/bus')).eventBus.emit.bind((await import('@/lib/events/bus')).eventBus)
|
|
await emit({
|
|
type: 'bank_connection.account_selection_changed',
|
|
payload: {
|
|
connectionId: connection.id,
|
|
bankName: (connection as { bank_name?: string | null }).bank_name ?? null,
|
|
previousStatus: connection.status,
|
|
newStatus,
|
|
enabledCount: enabled_uids.length,
|
|
totalCount: existing.length,
|
|
userId: user.id,
|
|
companyId,
|
|
},
|
|
})
|
|
} catch (emitError) {
|
|
log.error('[enable-banking] Failed to emit account selection event', {
|
|
errorMessage: emitError instanceof Error ? emitError.message : String(emitError),
|
|
connectionId: connection.id,
|
|
userId: user.id,
|
|
companyId,
|
|
})
|
|
}
|
|
|
|
// Initial backfill on activation. Run inline so the user has data the
|
|
// moment they finish account selection: no 24h cron wait. Failures
|
|
// here don't fail the PATCH; the cron will retry on its next run
|
|
// (gated on initial_sync_completed_at IS NULL).
|
|
let initialSyncSummary: {
|
|
imported: number
|
|
duplicates: number
|
|
requested_from: string
|
|
returned_min_date: string | null
|
|
returned_max_date: string | null
|
|
} | null = null
|
|
let initialSyncError: string | null = null
|
|
|
|
if (connection.status === 'pending_selection') {
|
|
const accountsToSync = updatedAccounts.filter(a => a.enabled !== false)
|
|
const toDate = new Date().toISOString().split('T')[0]
|
|
const fromDate = new Date(Date.now() - initialLookbackDays * 24 * 60 * 60 * 1000)
|
|
.toISOString()
|
|
.split('T')[0]
|
|
|
|
log.info('[enable-banking] Starting inline initial backfill', {
|
|
connectionId: connection.id,
|
|
accountCount: accountsToSync.length,
|
|
lookbackDays: initialLookbackDays,
|
|
fromDate,
|
|
toDate,
|
|
})
|
|
|
|
let timeoutHandle: ReturnType<typeof setTimeout> | undefined
|
|
try {
|
|
const ingestFn = ctx?.services.ingestTransactions
|
|
const syncPromise = Promise.all(
|
|
accountsToSync.map(account => syncAccountTransactions(
|
|
supabase,
|
|
companyId,
|
|
user.id,
|
|
connection.id,
|
|
account,
|
|
fromDate,
|
|
toDate,
|
|
ingestFn,
|
|
{ strategy: 'longest' }
|
|
))
|
|
)
|
|
// If the timeout wins the race, the underlying Promise.all keeps
|
|
// running. Without a registered handler, a late rejection from the
|
|
// bank API would surface as an unhandledRejection: Node 22 (the
|
|
// self-hosted Docker runtime) terminates the process by default on
|
|
// those, taking the whole server down. The cron retries the
|
|
// backfill via initial_sync_completed_at IS NULL, so a no-op
|
|
// catch is the right policy here.
|
|
syncPromise.catch(() => {})
|
|
|
|
const TIMEOUT_MS = 60_000
|
|
const timeoutPromise = new Promise<never>((_, reject) => {
|
|
timeoutHandle = setTimeout(() => reject(new Error('initial_sync_timeout')), TIMEOUT_MS)
|
|
})
|
|
const results = await Promise.race([syncPromise, timeoutPromise])
|
|
|
|
const totalImported = results.reduce((sum, r) => sum + r.imported, 0)
|
|
const totalDuplicates = results.reduce((sum, r) => sum + r.duplicates, 0)
|
|
|
|
// Min/max booking date across all synced accounts
|
|
const minDates = results.map(r => r.returnedMinBookingDate).filter((d): d is string => !!d)
|
|
const maxDates = results.map(r => r.returnedMaxBookingDate).filter((d): d is string => !!d)
|
|
const returnedMin = minDates.length > 0 ? minDates.reduce((a, b) => (a < b ? a : b)) : null
|
|
const returnedMax = maxDates.length > 0 ? maxDates.reduce((a, b) => (a > b ? a : b)) : null
|
|
|
|
const completedAt = new Date().toISOString()
|
|
// Don't re-write accounts_data here: the first update already wrote it.
|
|
// Including it again races with any concurrent writer (e.g. cron firing in
|
|
// the sub-60s window) and would silently overwrite their changes.
|
|
const { error: metaUpdateError } = await supabase
|
|
.from('bank_connections')
|
|
.update({
|
|
last_synced_at: completedAt,
|
|
initial_sync_completed_at: completedAt,
|
|
initial_sync_requested_from: fromDate,
|
|
initial_sync_returned_min_date: returnedMin,
|
|
initial_sync_returned_max_date: returnedMax,
|
|
initial_sync_lookback_days: initialLookbackDays,
|
|
})
|
|
.eq('id', connection.id)
|
|
|
|
if (metaUpdateError) {
|
|
// The sync itself succeeded (transactions are ingested) but we
|
|
// couldn't persist that. Falsely reporting success would tell the
|
|
// client "imported N transactions" while the DB still has
|
|
// initial_sync_completed_at = NULL, causing the cron to re-run a
|
|
// 90-day backfill next morning. Surface this as initial_sync_error
|
|
// so the UI shows a "background sync needs retry" warning, and the
|
|
// cron's gate (initial_sync_completed_at IS NULL) will self-heal.
|
|
initialSyncError = `metadata_update_failed: ${metaUpdateError.message}`
|
|
log.error('[enable-banking] Failed to persist initial_sync metadata after backfill', {
|
|
connectionId: connection.id,
|
|
error: metaUpdateError.message,
|
|
userId: user.id,
|
|
companyId,
|
|
})
|
|
} else {
|
|
initialSyncSummary = {
|
|
imported: totalImported,
|
|
duplicates: totalDuplicates,
|
|
requested_from: fromDate,
|
|
returned_min_date: returnedMin,
|
|
returned_max_date: returnedMax,
|
|
}
|
|
|
|
log.info('[enable-banking] Inline initial backfill complete', {
|
|
connectionId: connection.id,
|
|
...initialSyncSummary,
|
|
})
|
|
}
|
|
} catch (syncError) {
|
|
initialSyncError = syncError instanceof Error ? syncError.message : String(syncError)
|
|
log.error('[enable-banking] Inline initial backfill failed: cron will retry', {
|
|
connectionId: connection.id,
|
|
error: initialSyncError,
|
|
userId: user.id,
|
|
companyId,
|
|
})
|
|
} finally {
|
|
if (timeoutHandle) clearTimeout(timeoutHandle)
|
|
}
|
|
}
|
|
|
|
return NextResponse.json({
|
|
success: true,
|
|
enabled_count: enabled_uids.length,
|
|
total_count: existing.length,
|
|
...(initialSyncSummary ? { initial_sync: initialSyncSummary } : {}),
|
|
...(initialSyncError ? { initial_sync_error: initialSyncError } : {}),
|
|
})
|
|
},
|
|
},
|
|
{
|
|
method: 'DELETE',
|
|
path: '/disconnect',
|
|
handler: async (request: Request, ctx?: ExtensionContext) => {
|
|
const log = ctx?.log ?? console
|
|
const supabase = ctx?.supabase ?? await (await import('@/lib/supabase/server')).createClient()
|
|
const { data: { user } } = await supabase.auth.getUser()
|
|
|
|
if (!user) {
|
|
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
|
}
|
|
|
|
if (!ctx?.companyId) {
|
|
return NextResponse.json({ error: 'Company context required' }, { status: 400 })
|
|
}
|
|
const companyId = ctx.companyId
|
|
|
|
const rl = await checkRateLimit({
|
|
prefix: 'enable-banking:disconnect',
|
|
identifier: user.id,
|
|
...RATE_LIMIT_DISCONNECT,
|
|
})
|
|
if (!rl.ok) return rl.response!
|
|
|
|
const { connection_id } = await request.json()
|
|
|
|
if (!connection_id) {
|
|
return NextResponse.json({ error: 'connection_id is required' }, { status: 400 })
|
|
}
|
|
|
|
const { data: connection, error: findError } = await supabase
|
|
.from('bank_connections')
|
|
.select('id, session_id, status, bank_name')
|
|
.eq('id', connection_id)
|
|
.eq('company_id', companyId)
|
|
.single()
|
|
|
|
if (findError || !connection) {
|
|
return NextResponse.json({ error: 'Connection not found' }, { status: 404 })
|
|
}
|
|
|
|
// Revoke PSD2 consent if session exists
|
|
if (connection.session_id) {
|
|
try {
|
|
await deleteSession(connection.session_id)
|
|
} catch (error) {
|
|
log.error('[enable-banking] Failed to revoke PSD2 session (may be expired)', {
|
|
message: error instanceof Error ? error.message : String(error),
|
|
sessionId: connection.session_id,
|
|
connectionId: connection_id,
|
|
connectionStatus: connection.status,
|
|
userId: user.id,
|
|
companyId,
|
|
})
|
|
}
|
|
}
|
|
|
|
const { error: updateError } = await supabase
|
|
.from('bank_connections')
|
|
.update({ status: 'revoked', session_id: null })
|
|
.eq('id', connection.id)
|
|
|
|
if (updateError) {
|
|
log.error('[enable-banking] Failed to mark connection revoked', {
|
|
errorMessage: updateError.message,
|
|
connectionId: connection.id,
|
|
userId: user.id,
|
|
companyId,
|
|
})
|
|
return NextResponse.json({ error: 'Failed to disconnect' }, { status: 500 })
|
|
}
|
|
|
|
// Release the connection's ledger claims by demoting its cash_accounts
|
|
// rows to manual (bank_connection_id = null). The rows themselves stay:
|
|
// transactions.cash_account_id and the ledger history reference them,
|
|
// and upsertFromPsd2 promotes a manual holder in place on reconnect so
|
|
// the same bank lands back on its original BAS account (e.g. 1930)
|
|
// instead of overflowing to the next free slot.
|
|
const { error: releaseError } = await supabase
|
|
.from('cash_accounts')
|
|
.update({ bank_connection_id: null })
|
|
.eq('company_id', companyId)
|
|
.eq('bank_connection_id', connection.id)
|
|
|
|
if (releaseError) {
|
|
// Don't fail the disconnect: the connection is already revoked, and
|
|
// the allocator / collision guard also skip revoked connections, so
|
|
// the orphaned rows self-heal on the next picker save.
|
|
log.error('[enable-banking] Failed to release cash_accounts ledger claims on disconnect', {
|
|
errorMessage: releaseError.message,
|
|
connectionId: connection.id,
|
|
userId: user.id,
|
|
companyId,
|
|
})
|
|
}
|
|
|
|
try {
|
|
const emit = ctx?.emit ?? (await import('@/lib/events/bus')).eventBus.emit.bind((await import('@/lib/events/bus')).eventBus)
|
|
await emit({
|
|
type: 'bank_connection.revoked',
|
|
payload: {
|
|
connectionId: connection.id,
|
|
bankName: (connection as { bank_name?: string | null }).bank_name ?? null,
|
|
userId: user.id,
|
|
companyId,
|
|
},
|
|
})
|
|
} catch (emitError) {
|
|
log.error('[enable-banking] Failed to emit revoke event', {
|
|
errorMessage: emitError instanceof Error ? emitError.message : String(emitError),
|
|
connectionId: connection.id,
|
|
userId: user.id,
|
|
companyId,
|
|
})
|
|
}
|
|
|
|
return NextResponse.json({ success: true })
|
|
},
|
|
},
|
|
],
|
|
|
|
eventHandlers: [],
|
|
}
|