17a7a62ceb
* fix(settings): explain why account deletion is blocked The delete-account button was disabled while the user still owned companies, but the reason only lived behind the "?" on the blocker row, so the greyed-out button read as broken. Surface it as one visible attn sentence directly under the button, and point aria-describedby at it whenever the button is disabled, not only on a load error. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * feat(enable-banking): share one PSD2 consent across a user's companies Connecting the same bank for a second company required a second BankID, and at SEB that new authorization silently revoked the first one. A user with four companies at one bank therefore signed four times a quarter and ended up with three dead feeds, each still rendering as "Aktiv" with a stale last_synced_at until someone pressed Synka. Prod says this is not one customer: every SEB customer holding connections in more than one company has had an earlier company stop syncing at the moment the next was authorized, most of them while the consent was still formally valid for weeks. The same measurement over other banks is far quieter, so the one-active-session-per-PSU limit is real and ASPSP-side. Enable Banking already supports the shape we want. POST /auth carries no account restriction, so a session covers every account the user ticked at the bank, and GET /accounts/{uid}/transactions takes no session id, so a second company can sync its own accounts from an existing session. bank_connections has no unique constraint on session_id, so this needs no migration. Adds lib/session-sharing.ts plus GET /reusable-sessions and POST /attach. When a live session in another of the user's companies still exposes accounts no company syncs, the settings panel offers to reuse it: the new row shares session_id and consent_expires, carries only the unclaimed accounts, and lands in pending_selection so the existing IBAN-aware account picker does the ledger mapping. Only the consent is shared; accounts, cash_accounts and transactions stay strictly per-company. Sharing a session changes three lifecycle paths, all handled here: - Disconnect and reconnect now refcount before revoking. A blind revoke would take down a sibling company's feed, which is the exact failure this removes. The count runs on a service-role client because RLS hides a sibling in a company the user has since left, and it fails closed: an uncertain count is treated as shared, since a lingering consent lapses on its own in 90 days while a wrongly revoked one kills a working feed. - A renewed consent fans out to every company sharing the old session, and re-points their account uids by IBAN. Several ASPSPs reissue uids on re-authorization, so carrying the session id alone would have left siblings calling retired uids and re-broken them every quarter. This is also why the superseded session_id is no longer nulled at /connect: the callback needs it. - The nightly probe runs once per distinct session and applies the verdict to every row holding it, and expiry mails are keyed per (user, session), so one dead consent is one probe and one mail rather than four of each. Only enabled cash_accounts rows count as claiming an IBAN. The callback mirrors every account in a consent, deselected ones included, so counting any row as a claim would leave nothing offerable once the first company connects. An account handed to a company also stops being offered while that company's picker is still open, closing the window where two companies could book the same physical account. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * fix(ink2): read the resultaträkning from the pre-closing books INK2R summed journal entries raw, so it included the resultatavslut that zeroes every P&L account into 2099 at year-end. Nettoomsättning, kostnader, periodiseringsfond and skatt all came out as 0, which cascaded into INK2S 7650/7651 and the taxable result. INK2 is always filed after bokslut, so this was every real declaration, and nothing warned: with the P&L at zero the balance sheet still tied out. INK2R now reads two views of the same period. The balance sheet comes from the closed books so 7302 keeps arets resultat via 2099; the income statement comes from the pre-closing books via excludeFinalClosingEntry, which drops only fiscal_periods.closing_entry_id so skatt and bokslutsdispositioner stay on the form (7525, 7528). The equity adjustment is now conditional on a posted closing entry having moved the result into 2099. Second, independent bug: accounts were mapped by BAS number with no regard for the sign of the balance, so konto 1630 with a credit was reported as a negative fordran instead of a skatteskuld and konto 2641 with a debit was netted off the liabilities. The three sign-reclassification rules the K2 iXBRL mapper already had are extracted to lib/reports/sign-reclassification .ts and applied to INK2R too, so both statutory reports present the same balance sheet. Only the rule table is shared: k2-mapper keeps its sumOre arithmetic because the iXBRL path is ore-exact while INK2R truncates per SFL 22:1. NE-bilaga had the same empty-resultatrakning bug and gets the same fix. Adds the closed-period coverage that was missing: the old tests only exercised the mapping table against an open period, the one state in which the engine happened to work. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix(reports): make the year-end closing decision explicit at every call site generateTrialBalance took two optional booleans, so a caller that never thought about the resultatavslut silently got 'include'. That is the wrong default for anything summing class 3-8: the closing verifikat posts the mirror image of every P&L account into 2099 inside the same period, so the report reads ZERO across the board while the balance sheet still ties out and nothing warns. The booleans are replaced by a required closingEntry: 'include' | 'exclude-final' | 'exclude-all-year-end' with no default, so the build fails until each call site decides. All 40 were audited individually; every one keeps its current behaviour except the two that were provably broken: - Resultatrapport read zero on every line for a closed year, in JSON, PDF and XLSX, and its prior-year comparison column read zero for anyone whose previous year was closed. - Resultat per projekt (dimension-pnl) had the same defect and must stay in lockstep with Resultatrapport to keep reconciling. Both now pass 'exclude-all-year-end', which keeps them agreeing with the formal Resultaträkning rather than pre-empting Stage 2 of #1051 (DECISIONS.md:632). Deliberately unchanged and recorded in DECISIONS.md: the KPI expense composition, which is blank for a closed year but cannot be fixed without a migration and a displayed-figure change, and getBookedBolagsskatt, whose contract is an open period and whose call chain already caused a too-high-tax customer bug once. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix(vat): keep the resultatavslut out of the momsdeklaration The closing verifikat posts the mirror image of every P&L account into 2099 inside the same fiscal period. Revenue accounts drive rutor 05, 39 and 40, so any VAT period containing the fiscal-year end reported NEGATED turnover once the year was closed. get_vat_declaration_totals already excluded vat_settlement and opening_balance entries, but not this one. Reproduced read-only against production: for December of a closed year the December declaration reported ruta 39 = -794 734 kr. After the fix that period reports 0 and the January period carrying the real sale is unchanged at 794 734 kr. Keyed on fiscal_periods.closing_entry_id, not source_type = 'year_end': avskrivningar, periodiseringsfond and skatt share that source_type and must keep whatever VAT effect they carry. A reversed closing entry is retained together with its storno so the pair still nets to zero, the same predicate trial-balance.ts uses for closingEntry: 'exclude-final'. Migration applied to the staging branch only; prod gets it via merge. The pg test is written but has NOT been executed locally (no DATABASE_URL configured and no local Postgres), so CI is its first real run. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix(kpi): keep the resultatavslut off the monthly chart The monthly income/expense chart summed every posted entry in the fiscal period. The closing verifikat posts the mirror image of every P&L account, so once a year was closed the fiscal-year-end month charted the whole year's revenue as negative income. Measured read-only on production: 28 companies across 34 month-rows. The worst case charted December income as -10 347 459,81 kr where the real figure is +12,88 kr. Other examples: -1 868 731 -> +128 730, -1 850 501 -> +431 709. Both paths are fixed together so they keep agreeing: the RPC's monthly section now joins the tb_ex_ye_entries CTE it already computes for tb_ex_year_end, and monthly-breakdown.ts (the dimension-filtered fallback and the MCP path) gains the matching source_type filter plus the storno/correction chain of REVERSED year-end entries, so an undone bokslut does not leave half a pair behind. Migration 20260723180000 had recorded the omission as deliberate, on the grounds that it mirrored the JS scan. It did, but the JS scan was wrong. Migration applied to the staging branch (function body identical; three comment lines differ from the committed file). Prod gets the file via merge. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * test(reports): pin every statement generator against a closed fiscal year The per-generator suites all exercised an OPEN fiscal period, which is the one state in which a generator that forgets the resultatavslut happens to work. Declarations are filed AFTER bokslut, so the untested state was the only state that occurs in production. That is why the same defect could ship three times. Two new suites over one shared fixture (closed-year-fixture.ts, a synthetic closed AB with a resultatavslut, a credit 1630 and a debit 2641): closed-year-statements.test.ts enumerates the generators and asserts each reports the year's revenue rather than zero, plus its own bottom line. The table IS the checklist: a new report either appears in it or nothing stops it shipping with this bug. Verified by regressing income-statement back to closingEntry 'include', which fails 2 of its assertions. cross-surface-agreement.test.ts asserts the surfaces agree with each other, which is what every customer complaint actually was. INK2R and the K2 årsredovisning must produce the same årets resultat, the same fritt eget kapital, the same sign reclassifications and the same balance total. The operational family (Resultaträkning, Resultatrapport) must agree internally, and the gap BETWEEN the families is asserted explicitly as bokslutsdispositioner + skatt, so when Stage 2 of #1051 lands the test names the expectation to change instead of failing vaguely. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * chore(guards): ratchet against new reports that scan the ledger directly A statement generator that aggregates journal_entry_lines itself has to remember, on its own, that the resultatavslut posts the mirror image of every P&L account into 2099 inside the same fiscal period. Three forgot, and each read ZERO revenue for a closed year while the balance sheet still tied out, so nothing warned. generateTrialBalance now requires an explicit closingEntry mode, which makes that decision a compile error. This guard is what keeps NEW reports on that path: any generator under lib/reports or lib/bokslut that reads journal_entry_lines and is not in the baseline set fails CI. Verified by adding a throwaway report, which the guard rejects by name. Voucher and line listings (general-ledger, journal-register, SIE export, reconciliation, diagnostics) are sanctioned: they show the ledger as posted and have no closingEntry decision to make. Four existing lib/bokslut files are grandfathered rather than migrated. One of them is a genuine open follow-up recorded in DECISIONS.md: sarskild-loneskatt-calculator sums 7410-7419 with no year-end exclusion, so its basis reads ~0 if it runs against an already-closed period. Left alone deliberately: it is a tax figure whose call chain has caused a customer bug before and deserves its own verified change. Also ratchets naive-ore-round down 646 -> 641. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * test(reports): pin where sign reclassification applies, in both directions No behaviour change. The sweep asked whether the 1630/2641 sign reclassification should be extended to the remaining balance-sheet surfaces; the answer is that there are none left. Both STATUTORY presentations already have it: the K2 iXBRL årsredovisning since 2026-07-23 and INK2R since 2026-07-29. The other two balance-sheet surfaces must NOT have it: /rapporter Balansräkning and Balansrapport are organised by account number under BAS-prefix headings, and balansrapport documents an invariant that depends on every row staying debit-positive where it was booked. Moving konto 1630 into a liability section would break the add-the-rows-to-verify-the-balance property and hide the account from anyone looking it up by number. Asserting both halves is the point. The first half stops the reclassification silently disappearing from one statutory surface again, which is how a customer ended up comparing two of our own reports against each other. The second half stops a future sweep "fixing" the operational reports into disagreeing with their own documented contract. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * feat(reports): detect statement disagreement instead of waiting for a customer Every year-end problem reported so far was a DISAGREEMENT between two of our own screens, not a single wrong screen. The årsredovisning said one figure, INK2 said another, and the customer did the reconciliation for us. Nothing in the product noticed, because each screen tied out on its own. Two additions: INK2R self-checks. On a closed year it compares the årets resultat it is about to declare against the booked konto 2099, and warns in Swedish when they disagree. This is the alarm that was missing: when INK2R reported 0 kr against a booked 469 542 kr, the balance sheet still balanced, so no warning fired. Mirrors the equivalent check k2-mapper has had since 2026-07-23, so both statutory reports now catch the same fault. reconcileStatements + GET /api/reports/statement-reconciliation return årets resultat from every surface side by side, grouped into families. ledger + statutory must agree and a mismatch is named; operational legitimately differs by bokslutsdispositioner + skatt until Stage 2 of #1051 lands, so that gap is explained rather than flagged. The visual panel is deliberately not built here: it needs a /frontend-design pass against the locked concept conventions plus sv/en strings, and the warning above already puts the alarm where the user looks. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix(reports): address review findings from PR #1293 pg-real (7 failures, one signature): the new fixture called insertFiscalPeriod({ isClosed: true }) and then inserted journal entries into it, so enforce_period_lock (migration 017, legally required) refused the write. Not worked around: the RPC's predicate keys on fiscal_periods.closing_entry_id and never reads is_closed, so the fixture now links the closing entry and leaves the period open, which exercises the path that actually matters. CodeRabbit, closed-year-fixture: EX_YEAR_END_ROWS dropped only the P&L legs of the year_end entries (8811, 8910) and left their balance-sheet legs (2125, 2512) at pre-closing values, so the 'exclude-all-year-end' view sat 160 000 kr out of balance and misrepresented what generateTrialBalance returns. Latent, because today's consumers read class 3-8 only, but a shared fixture that does not balance is a trap for the next consumer. Both legs now go, and a new test asserts all three views sum to zero. CodeRabbit, INK2 totals: renamed totals.resultAfterFinancial to aretsResultat. It holds the result after bokslutsdispositioner AND skatt, which is årets resultat, not resultat efter finansiella poster, and build-data.ts uses the old name correctly for the different subtotal. The UI already labelled the value "Årets resultat", so the name was simply wrong. CodeRabbit, statement-reconciliation: the statutory branch called a generator and caught any throw as "wrong entity type", mapping genuine failures to a null figure that the comparison then skipped, so a real bug in a declaration generator made the function report isReconciled: true. That is the opposite of its purpose. It now dispatches on entity_type and surfaces a generation failure as a named disagreement. CodeRabbit, enable-banking (Emil's call to include): fetchClaimedIbans returned an empty Set on a cash_accounts read failure, which is indistinguishable from "nothing is claimed" and made every IBAN in the session offerable, including accounts another company already books to. Its own comment said it failed closed and its log said "offering nothing"; it failed open. Returns null now, and findReusableSessions offers nothing when the claimed set is unavailable. The test that pinned the fail-open asserted toHaveLength(1) under the name "offers nothing"; it now asserts []. Also removed an em dash per CLAUDE.md. The remaining enable-banking finding (consent-expiry cooldown stamped only on the selected connection, so it leaks one duplicate mail per sibling company) is deliberately left to Emil: it changes email-sending behaviour in his feature rather than fixing a stated contract. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix(reports): resolve second-round review findings on PR #1293 pg-real, two NEW signatures (the closed-period one from cycle 1 is gone): kpi-report-aggregates-rpc.pg.test.ts asserted the exact contract migration 20260730090000 deliberately changes. Its comment read "year_end entries are NOT excluded from monthly" and expected December expenses 1250. That fixture's December holds only year-end-chain entries, so with the fix the month drops out of the chart entirely, which is the correct operational view: a month whose only activity is bokslut has no operating result. Assertion and file docstring updated to the new contract rather than the test being removed. vat-totals-closing-entry.pg.test.ts passed the wrong account arrays. p_net_ accounts is VAT_SETTLEMENT_NET_ACCOUNTS (2650/1650, the momsredovisning settlement pair), not the output-VAT accounts. Putting 2611 there made the extra year_end entry match the settlement-SHAPE detector, so an ordinary sale-with-VAT was classified a momsredovisning and dropped, and the test read 0 instead of 10 000. The RPC was right; the fixture was not. CodeRabbit, statement-reconciliation: resolveEntityType checked neither query's error, so a genuine DB failure (RLS, permissions, connectivity) returned null indistinguishably from "no entity type set", fell into the unsupported-form branch and reported isReconciled: true. That is the same silent-false-reconciled bug the cycle-1 refactor closed, one level down. The companies error now throws; a missing company_settings ROW stays tolerated, because .single() errors on zero rows and many companies have none. Mirrors the pattern the INK2 and NE engines already use. Still open by Emil's explicit choice: the consent-expiry cooldown is stamped only on the connection it was handed, so it leaks one duplicate mail per sibling company on the shared session. That changes email-sending behaviour in his feature rather than fixing a stated contract, so it stays his. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
474 lines
18 KiB
TypeScript
474 lines
18 KiB
TypeScript
import type { SupabaseClient } from '@supabase/supabase-js'
|
|
import { normalizeIban } from '@/lib/cash-accounts/service'
|
|
import { createLogger } from '@/lib/logger'
|
|
import type { StoredAccount } from '../types'
|
|
|
|
const log = createLogger('enable-banking/session-sharing')
|
|
|
|
/**
|
|
* Cross-company PSD2 session reuse.
|
|
*
|
|
* Several ASPSPs (SEB most visibly) allow only one active AIS session per PSU.
|
|
* A user who signs for company A, then company B, then company C at the same
|
|
* bank ends up with only the newest session alive: each authorization revokes
|
|
* the previous one bank-side, without telling us. Prod bears this out: every
|
|
* SEB customer holding connections for more than one company has had an
|
|
* earlier company stop syncing at the moment the next one was authorized,
|
|
* usually while its consent was still formally valid for weeks.
|
|
*
|
|
* The fix is to stop minting one session per company. Enable Banking's
|
|
* authorization is per-PSU, not per-company: POST /auth carries no account
|
|
* restriction, so the returned session already covers every account the user
|
|
* ticked at the bank, and GET /accounts/{uid}/transactions takes no session id
|
|
* at all. So a second company can simply point at the first company's session
|
|
* and sync its own accounts from it, with no second BankID and nothing revoked.
|
|
*
|
|
* What is shared is exactly the consent: `session_id` and `consent_expires`.
|
|
* Everything else stays per-company — its own bank_connections row, its own
|
|
* accounts_data subset, its own cash_accounts and transactions. Company B's
|
|
* row never carries an account company A already claimed, so the shared
|
|
* session is not a window into another company's books.
|
|
*/
|
|
|
|
/** A live session belonging to one of the user's other companies. */
|
|
export interface ReusableSession {
|
|
/** The source connection whose session would be shared. */
|
|
connectionId: string
|
|
companyId: string
|
|
companyName: string | null
|
|
bankName: string | null
|
|
provider: string
|
|
sessionId: string
|
|
psuType: string | null
|
|
consentExpires: string | null
|
|
/** Accounts in that session no company has mapped to a ledger yet. */
|
|
availableAccounts: StoredAccount[]
|
|
}
|
|
|
|
/**
|
|
* Accounts in a session that no cash_accounts row has claimed.
|
|
*
|
|
* Identity is the IBAN, matching resolvePsd2LedgerAccount: the provider's
|
|
* account uid does not survive a re-authorization at every ASPSP, so it cannot
|
|
* decide ownership. Accounts WITHOUT an IBAN are deliberately never offered.
|
|
* We cannot prove such an account is unclaimed, and handing one to a second
|
|
* company risks two companies booking the same physical account, which is a
|
|
* far worse outcome than making the user authorize separately for it.
|
|
*/
|
|
export function unclaimedAccountsFor(
|
|
accounts: readonly StoredAccount[],
|
|
claimedIbans: ReadonlySet<string>,
|
|
): StoredAccount[] {
|
|
const out: StoredAccount[] = []
|
|
const seen = new Set<string>()
|
|
for (const account of accounts) {
|
|
const iban = normalizeIban(account.iban)
|
|
if (!iban) continue
|
|
if (claimedIbans.has(iban)) continue
|
|
// One session can list the same IBAN twice (some ASPSPs return a separate
|
|
// resource per balance type). Offering it twice would let the picker map
|
|
// two rows onto one ledger and trip the UNIQUE constraint on save.
|
|
if (seen.has(iban)) continue
|
|
seen.add(iban)
|
|
// The source company's enable/disable choice is its own; company B starts
|
|
// with everything on and unchecks in the picker. Drop the source's ledger
|
|
// mapping too: that number belongs to the other company's chart.
|
|
const { ledger_account: _ledger, ...rest } = account
|
|
out.push({ ...rest, enabled: true })
|
|
}
|
|
return out
|
|
}
|
|
|
|
/**
|
|
* Every IBAN a company is actually syncing. RLS scopes cash_accounts to
|
|
* user_company_ids(), which is exactly the set that could collide, so no
|
|
* explicit company filter is needed here.
|
|
*
|
|
* Only ENABLED rows count as claimed, and that distinction is what makes this
|
|
* feature work at all. The connect callback mirrors every account in the
|
|
* consent into cash_accounts, deselected ones included, so treating any row as
|
|
* a claim would mean a bank's whole consent is spoken for the moment the first
|
|
* company connects and no account is ever free to offer.
|
|
*
|
|
* Enabled-only also matches how people actually work: signing once at the bank
|
|
* returns every account the user can see, and they uncheck the other
|
|
* companies' accounts in the picker precisely because those do not belong in
|
|
* this company's books. Those are the accounts the next company should get.
|
|
*/
|
|
/**
|
|
* Returns null when the claimed set could not be read. An empty Set would be
|
|
* indistinguishable from "nothing is claimed", which makes every IBAN in the
|
|
* session offerable: the one outcome this feature must never produce. The
|
|
* caller turns null into an empty offer list.
|
|
*/
|
|
async function fetchClaimedIbans(supabase: SupabaseClient): Promise<Set<string> | null> {
|
|
const { data, error } = await supabase
|
|
.from('cash_accounts')
|
|
.select('iban')
|
|
.eq('enabled', true)
|
|
.not('iban', 'is', null)
|
|
|
|
if (error) {
|
|
// Fail closed: without the claimed set we cannot tell a free account from
|
|
// one another company already books to, and offering a claimed account is
|
|
// the one outcome this feature must never produce.
|
|
log.warn('claimed iban lookup failed, offering nothing', { error: error.message })
|
|
return null
|
|
}
|
|
|
|
const claimed = new Set<string>()
|
|
for (const row of (data ?? []) as Array<{ iban: string | null }>) {
|
|
const iban = normalizeIban(row.iban)
|
|
if (iban) claimed.add(iban)
|
|
}
|
|
return claimed
|
|
}
|
|
|
|
/**
|
|
* Live sessions the user holds in OTHER companies that still have accounts to
|
|
* give. Returns an empty list, not an error, whenever nothing qualifies: the
|
|
* caller renders an offer only when there is something to offer.
|
|
*
|
|
* Sources are restricted to status 'active'. A 'pending_selection' source is
|
|
* authorized and alive, but its owner has not finished picking accounts yet,
|
|
* so every account would read as unclaimed and company B could take one
|
|
* company A is seconds away from choosing.
|
|
*/
|
|
export async function findReusableSessions(
|
|
supabase: SupabaseClient,
|
|
userId: string,
|
|
activeCompanyId: string,
|
|
): Promise<ReusableSession[]> {
|
|
const nowIso = new Date().toISOString()
|
|
|
|
const { data: rows, error } = await supabase
|
|
.from('bank_connections')
|
|
.select('id, company_id, bank_name, provider, session_id, psu_type, consent_expires, accounts_data')
|
|
.eq('user_id', userId)
|
|
.eq('status', 'active')
|
|
.neq('company_id', activeCompanyId)
|
|
.not('session_id', 'is', null)
|
|
.gt('consent_expires', nowIso)
|
|
|
|
if (error) {
|
|
log.warn('reusable session lookup failed', { activeCompanyId, error: error.message })
|
|
return []
|
|
}
|
|
if (!rows || rows.length === 0) return []
|
|
|
|
const claimedIbans = await fetchClaimedIbans(supabase)
|
|
if (claimedIbans === null) {
|
|
// Offer nothing rather than everything: see fetchClaimedIbans.
|
|
return []
|
|
}
|
|
const ibanCarriers = await fetchIbanCarriers(supabase, userId)
|
|
|
|
const typed = rows as Array<{
|
|
id: string
|
|
company_id: string
|
|
bank_name: string | null
|
|
provider: string
|
|
session_id: string
|
|
psu_type: string | null
|
|
consent_expires: string | null
|
|
accounts_data: StoredAccount[] | null
|
|
}>
|
|
|
|
const companyNames = await fetchCompanyNames(
|
|
supabase,
|
|
[...new Set(typed.map(r => r.company_id))],
|
|
)
|
|
|
|
const sessions: ReusableSession[] = []
|
|
for (const row of typed) {
|
|
// A cash_accounts row is not the only way an account gets taken. Between
|
|
// attaching a company and finishing its picker, the account is carried in
|
|
// that company's accounts_data and nothing has claimed a ledger yet. Offer
|
|
// it again in that window and two companies end up booking one physical
|
|
// account, which is the failure this feature is supposed to prevent.
|
|
const unavailable = new Set(claimedIbans)
|
|
for (const [iban, carrierCompanyIds] of ibanCarriers) {
|
|
for (const carrierCompanyId of carrierCompanyIds) {
|
|
if (carrierCompanyId !== row.company_id) {
|
|
unavailable.add(iban)
|
|
break
|
|
}
|
|
}
|
|
}
|
|
|
|
const availableAccounts = unclaimedAccountsFor(row.accounts_data ?? [], unavailable)
|
|
if (availableAccounts.length === 0) continue
|
|
sessions.push({
|
|
connectionId: row.id,
|
|
companyId: row.company_id,
|
|
companyName: companyNames.get(row.company_id) ?? null,
|
|
bankName: row.bank_name,
|
|
provider: row.provider,
|
|
sessionId: row.session_id,
|
|
psuType: row.psu_type,
|
|
consentExpires: row.consent_expires,
|
|
availableAccounts,
|
|
})
|
|
}
|
|
return sessions
|
|
}
|
|
|
|
/**
|
|
* Which companies currently carry each IBAN in their connection metadata,
|
|
* whether or not a ledger has been mapped yet. This is what closes the window
|
|
* between attaching a company and that company finishing its account picker.
|
|
*/
|
|
async function fetchIbanCarriers(
|
|
supabase: SupabaseClient,
|
|
userId: string,
|
|
): Promise<Map<string, Set<string>>> {
|
|
const { data, error } = await supabase
|
|
.from('bank_connections')
|
|
.select('company_id, accounts_data')
|
|
.eq('user_id', userId)
|
|
.in('status', ['active', 'pending_selection'])
|
|
|
|
const carriers = new Map<string, Set<string>>()
|
|
if (error) {
|
|
log.warn('iban carrier lookup failed', { error: error.message })
|
|
return carriers
|
|
}
|
|
|
|
for (const row of (data ?? []) as Array<{ company_id: string; accounts_data: StoredAccount[] | null }>) {
|
|
for (const account of row.accounts_data ?? []) {
|
|
// Deselected accounts are not held. Freshly attached rows carry
|
|
// everything as enabled, so the attach-to-picker window is still closed;
|
|
// but once a company unchecks an account, it has to become available
|
|
// again or the first company to look at it would block it forever.
|
|
if (account.enabled === false) continue
|
|
const iban = normalizeIban(account.iban)
|
|
if (!iban) continue
|
|
const existing = carriers.get(iban)
|
|
if (existing) existing.add(row.company_id)
|
|
else carriers.set(iban, new Set([row.company_id]))
|
|
}
|
|
}
|
|
return carriers
|
|
}
|
|
|
|
async function fetchCompanyNames(
|
|
supabase: SupabaseClient,
|
|
companyIds: readonly string[],
|
|
): Promise<Map<string, string>> {
|
|
if (companyIds.length === 0) return new Map()
|
|
const { data, error } = await supabase
|
|
.from('companies')
|
|
.select('id, name')
|
|
.in('id', [...companyIds])
|
|
if (error) {
|
|
log.warn('company name lookup failed', { error: error.message })
|
|
return new Map()
|
|
}
|
|
return new Map(
|
|
((data ?? []) as Array<{ id: string; name: string | null }>)
|
|
.filter((c): c is { id: string; name: string } => !!c.name)
|
|
.map(c => [c.id, c.name]),
|
|
)
|
|
}
|
|
|
|
/**
|
|
* How many OTHER connections still depend on this session.
|
|
*
|
|
* Must run on a service-role client. RLS would hide a sibling living in a
|
|
* company the user has since left, and an invisible sibling reads as zero,
|
|
* which is precisely the case where revoking kills a feed that is still in use.
|
|
*
|
|
* Counts every non-revoked sibling, including ones parked in 'expired' or
|
|
* 'error'. The asymmetry is deliberate: leaving a consent un-revoked costs us
|
|
* nothing but a row at Enable Banking that lapses on its own within 90 days,
|
|
* while revoking one that another company is still syncing from takes down a
|
|
* working bank feed with no warning.
|
|
*/
|
|
export async function countLiveSiblings(
|
|
serviceSupabase: SupabaseClient,
|
|
sessionId: string,
|
|
excludeConnectionId: string,
|
|
): Promise<number> {
|
|
const { count, error } = await serviceSupabase
|
|
.from('bank_connections')
|
|
.select('id', { count: 'exact', head: true })
|
|
.eq('session_id', sessionId)
|
|
.neq('id', excludeConnectionId)
|
|
.neq('status', 'revoked')
|
|
|
|
if (error) {
|
|
log.error('sibling count failed, treating session as shared', {
|
|
sessionId: '[REDACTED]',
|
|
error: error.message,
|
|
})
|
|
// Fail closed again: pretend a sibling exists rather than revoke a session
|
|
// we could not prove is unshared.
|
|
return 1
|
|
}
|
|
return count ?? 0
|
|
}
|
|
|
|
export interface SessionRenewalResult {
|
|
/** Sibling rows moved onto the new session. */
|
|
movedCount: number
|
|
}
|
|
|
|
/**
|
|
* Point a company's stored accounts at the uids the renewed session issued.
|
|
*
|
|
* Several ASPSPs mint fresh account uids on every re-authorization. The company
|
|
* that clicked "renew" gets remapped by the callback's own IBAN matching, but a
|
|
* sibling still holds the previous session's uids, and
|
|
* GET /accounts/{uid}/transactions against a superseded uid fails. So the
|
|
* quarterly renewal would keep breaking exactly the companies this feature
|
|
* exists to keep alive, one layer further down.
|
|
*
|
|
* The sibling's own choices (which accounts are enabled, which ledger each
|
|
* books to) are preserved: only the uid moves. An account whose IBAN is absent
|
|
* from the new session is left untouched rather than dropped, since silently
|
|
* discarding a mapped account is worse than a visible sync error.
|
|
*/
|
|
export function remapAccountUids(
|
|
accounts: readonly StoredAccount[],
|
|
sessionAccounts: readonly { uid: string; iban?: string | null }[],
|
|
): { accounts: StoredAccount[]; remapped: number; unmatched: number } {
|
|
const uidByIban = new Map<string, string>()
|
|
for (const account of sessionAccounts) {
|
|
const iban = normalizeIban(account.iban)
|
|
if (iban) uidByIban.set(iban, account.uid)
|
|
}
|
|
|
|
let remapped = 0
|
|
let unmatched = 0
|
|
const out = accounts.map(account => {
|
|
const iban = normalizeIban(account.iban)
|
|
const newUid = iban ? uidByIban.get(iban) : undefined
|
|
if (!newUid) {
|
|
unmatched += 1
|
|
return account
|
|
}
|
|
if (newUid === account.uid) return account
|
|
remapped += 1
|
|
return { ...account, uid: newUid }
|
|
})
|
|
|
|
return { accounts: out, remapped, unmatched }
|
|
}
|
|
|
|
/**
|
|
* Carry a renewed consent across to every company sharing the old session.
|
|
*
|
|
* One re-authorization is what the user performed, so one re-authorization is
|
|
* what every sharing company gets. Without this the other companies would keep
|
|
* pointing at the session the bank just replaced and would fail on their next
|
|
* sync, which is the original problem wearing a different hat.
|
|
*
|
|
* Siblings parked in 'expired'/'error' are revived to 'active' (a live session
|
|
* is exactly what they were missing); 'active' and 'pending_selection' rows
|
|
* keep their status, since pending_selection means the user still owes that
|
|
* company an account selection.
|
|
*/
|
|
export async function fanOutSessionRenewal(
|
|
supabase: SupabaseClient,
|
|
input: {
|
|
oldSessionId: string
|
|
newSessionId: string
|
|
consentExpires: string | null
|
|
excludeConnectionId: string
|
|
/** Accounts the renewed session returned, for remapping sibling uids. */
|
|
sessionAccounts?: readonly { uid: string; iban?: string | null }[]
|
|
},
|
|
): Promise<SessionRenewalResult> {
|
|
const { oldSessionId, newSessionId, consentExpires, excludeConnectionId, sessionAccounts } = input
|
|
if (!oldSessionId || oldSessionId === newSessionId) return { movedCount: 0 }
|
|
|
|
const { data: siblings, error: siblingError } = await supabase
|
|
.from('bank_connections')
|
|
.select('id, status, accounts_data')
|
|
.eq('session_id', oldSessionId)
|
|
.neq('id', excludeConnectionId)
|
|
.neq('status', 'revoked')
|
|
|
|
if (siblingError) {
|
|
log.error('failed to load siblings for session renewal', { error: siblingError.message })
|
|
return { movedCount: 0 }
|
|
}
|
|
if (!siblings || siblings.length === 0) return { movedCount: 0 }
|
|
|
|
let movedCount = 0
|
|
for (const sibling of siblings as Array<{
|
|
id: string
|
|
status: string
|
|
accounts_data: StoredAccount[] | null
|
|
}>) {
|
|
// Payloads stay object literals (never a built-up Record) so the
|
|
// no-phantom-columns guard can actually verify the column names.
|
|
// A session was the only thing a dead sibling was missing, so bring it
|
|
// back. 'pending_selection' is left alone: that company still owes an
|
|
// account selection, and flipping it to active would skip the picker.
|
|
const isDead = sibling.status === 'expired' || sibling.status === 'error'
|
|
const { error: updateError } = isDead
|
|
? await supabase
|
|
.from('bank_connections')
|
|
.update({
|
|
session_id: newSessionId,
|
|
consent_expires: consentExpires,
|
|
status: 'active',
|
|
error_message: null,
|
|
})
|
|
.eq('id', sibling.id)
|
|
: await supabase
|
|
.from('bank_connections')
|
|
.update({ session_id: newSessionId, consent_expires: consentExpires })
|
|
.eq('id', sibling.id)
|
|
|
|
if (updateError) {
|
|
log.error('failed to move sibling onto renewed session', {
|
|
connectionId: sibling.id,
|
|
error: updateError.message,
|
|
})
|
|
continue
|
|
}
|
|
movedCount += 1
|
|
|
|
// Re-pointing the uids is a separate write, and deliberately so: it only
|
|
// happens when the ASPSP actually reissued them, and keeping it out of the
|
|
// payload above means neither write needs a dynamically built object.
|
|
if (sessionAccounts && sessionAccounts.length > 0) {
|
|
const { accounts, remapped, unmatched } = remapAccountUids(
|
|
sibling.accounts_data ?? [],
|
|
sessionAccounts,
|
|
)
|
|
if (unmatched > 0) {
|
|
// The renewed consent no longer covers an account this company books
|
|
// to. Worth surfacing: it usually means the user unticked it at the
|
|
// bank, and that company's next sync will report the gap.
|
|
log.warn('renewed session does not cover every account a company uses', {
|
|
connectionId: sibling.id,
|
|
unmatched,
|
|
})
|
|
}
|
|
if (remapped > 0) {
|
|
const { error: remapError } = await supabase
|
|
.from('bank_connections')
|
|
.update({ accounts_data: accounts })
|
|
.eq('id', sibling.id)
|
|
if (remapError) {
|
|
log.error('failed to re-point sibling accounts at the renewed session', {
|
|
connectionId: sibling.id,
|
|
error: remapError.message,
|
|
})
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
if (movedCount > 0) {
|
|
log.info('renewed session carried to sibling connections', {
|
|
movedCount,
|
|
excludeConnectionId,
|
|
})
|
|
}
|
|
return { movedCount }
|
|
}
|