feat(invoices): named payee accounts and per-invoice choice of bank account (#2233)
* fix(enable-banking): read BBAN from AccountIdentification.other and store it on the account Enable Banking has no top-level `bban` key on AccountIdentification: a Swedish BBAN (clearing + account number) arrives as `other.identification` with `other.scheme_name = 'BBAN'`, or in `all_account_ids`. The client typed `bban?: string` and read `.bban`, so the value was always undefined: no connected account ever carried its clearing + account number, and domestic counterparty accounts on transactions were dropped. Type the identifiers per the OpenAPI spec, add extractBban() and pickAccountIdentifier(), read counterparty identifiers through the scheme list (IBAN, then BBAN/BGNR/PGNR, then anything), and store `bban` on StoredAccount from the OAuth callback. The external_id dedup scope stays IBAN-then-uid and is untouched. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01UaZTY21HVN57hJoPXKSLjV * feat(invoices): named payee accounts on cash_accounts with a default per currency A company had exactly one set of payment instructions per invoice currency (company_settings.invoice_payment_accounts), picked by currency alone. A second SEK bank account, or a second bankgiro number, had nowhere to live. cash_accounts is already the per-company bank-account entity. Migration 20260903150000 adds the payee fields (bankgiro, plusgiro, clearing + account number, BBAN, BIC, Swish, foreign routing) plus invoice_payee, a small invoice_payee_defaults table (one default account per currency; one account may be the default for several currencies, a SEK account with an IBAN is the usual EUR payee), and a SECURITY DEFINER mirror that rewrites the legacy map and the SEK bank columns from the default accounts. Every existing reader (PDF, email, reminders, v1, MCP) keeps working; the three writers that only touched legacy columns (PUT /api/settings, v1 settings, MCP update_company_settings) now write through to the default account, so what an agent sets is what the PDF prints. Peppol PaymentMeans is built from the resolver instead of the raw legacy column. bg_pg is dropped (never read or written; NULL on every prod and staging row). Backfill lands only on existing cash accounts (primary, IBAN match, or the only enabled account in the currency). Entries with no target stay in the map as the resolver fallback and get an attach action in settings. New: POST /api/cash-accounts (manual bank account on the next free 19xx), PATCH /api/cash-accounts/[id] payee fields (owner/admin), GET/PUT /api/cash-accounts/payee-defaults. Settings page rewritten as an account list with per-currency defaults. Behandlingshistorik and the full archive cover the new table and columns. Verified on staging: migration applied (11 defaults landed), mirror trigger observed rewriting company_settings from a payee edit. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01UaZTY21HVN57hJoPXKSLjV * feat(invoices): choose which bank account an invoice is paid to, frozen at issue Migration 20260903160000 adds invoices.payment_cash_account_id (FK to cash_accounts, SET NULL) and invoices.payment_details, the payee fields frozen when the account is chosen and refreshed at issue. Resolver: resolveInvoicePaymentAccount / companyWithInvoicePaymentAccount / assertInvoicePaymentAccountForRender take an optional override, and hasRequiredInvoicePaymentAccount reads it from the invoice row, so every surface (PDF, Swish QR, email, reminders, payment confirmation, Peppol, recurring, staged MCP send) prints the frozen payee when one exists and the company default per currency otherwise. Invoices that never chose an account behave exactly as before. Issue paths (mark-sent, send, v1 send, v1 mark-sent, Peppol send, recurring, MCP send and mark-sent) refresh the snapshot from the account as it is at issue; a chosen account that is disabled, un-flagged or unusable for the currency blocks with INVOICE_SEND_PAYMENT_ACCOUNT_INVALID. Writers: dashboard POST/PATCH, v1 create/update and MCP create_invoice accept payment_cash_account_id and validate it against the company's payee accounts (INVOICE_PAYEE_ACCOUNT_INVALID). Credit notes inherit the original's payee; copies carry the choice; preview-pdf renders the chosen account. The editor shows "Betalas till" under the currency when the company has two or more usable payee accounts for that currency. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01UaZTY21HVN57hJoPXKSLjV * feat(invoices): book manual payments on the invoice's chosen bank account Manual mark-paid (dashboard, v1, MCP gnubok_mark_invoice_as_paid) and the booking dialog's proposed lines debited 1930 regardless of which bank account the invoice asked to be paid to. They now resolve the chosen payee account's ledger account (resolveInvoiceSettlementAccount) and fall back to 1930 only when no account was chosen or the row is gone. Bank-transaction matching keeps debiting the account the money landed on and does not filter by the chosen account; between equal-confidence candidates it prefers the invoice that asked to be paid to the landing account. Scores are untouched, so nothing new auto-matches. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01UaZTY21HVN57hJoPXKSLjV * chore(invoices): keep the payload-size and phantom-column ceilings after the payee work Shorten the new gnubok_create_invoice argument description (tools/list payload was 29 bytes over the 60 kB budget), inline the cash-account payee UPDATE/INSERT payloads and the settings select strings as literals so the phantom-column scanner can read their columns, and reuse ACCOUNT_NUMBER_RE instead of a hand-rolled copy. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01UaZTY21HVN57hJoPXKSLjV * fix(invoices): harden the payee model after review (admin-only payee columns, separate payee IBAN, company-scoped FK) Review findings from CodeRabbit, Superagent, the Swedish accounting review and three skeptic passes, resolved in one batch: Schema (both migrations are unshipped and edited in place): - cash_accounts.payee_iban: the printed IBAN is its own column. iban stays the bank identity written by every sync and used to re-pair on reconnect, so a sync can no longer rewrite an invoice instruction or resurrect a cleared IBAN. The backfill copies each currency entry verbatim onto the target account (IBAN match first, then primary), so every invoice keeps printing exactly what it printed before; the bank IBAN is never pushed onto invoices that did not carry one. - Payee columns are owner/admin-only at the database (BEFORE trigger, service role exempt): cash_accounts is member-writable for bank sync, and the SECURITY DEFINER mirror would otherwise have let a member rewrite where customers pay. - Revoking an account as payee or disabling it drops its defaults; deleting a default drops that currency from the map and clears the legacy SEK columns (an admin saying "nothing to print" must not keep printing a closed account). The mirror leaves the legacy SEK columns alone when the map has no SEK entry, so legacy-only companies are never wiped by a mirror run for another currency. - Audit and mirror triggers fire on the same column set; anon and authenticated can no longer execute the trigger-only definer functions. - invoices.payment_cash_account_id is a composite same-company FK with SET NULL scoped to the account column. Code: - Only 19xx bank accounts can be payee: PATCH, the defaults PUT (which now also requires enabled, payee-flagged and usable for the currency), resolveInvoicePayeeChoice, and the mark-paid settlement resolver (which also refuses disabled rows and logs every fallback to 1930). - createManualBankAccount excludes every ledger slot any row already holds (findFreeLedgerAccount treats a manual holder as free; this path inserts). - The legacy settings writers (PUT /api/settings, v1, MCP) write through to the account BEFORE updating company_settings and fail the request on error; the account is written before it is adopted as default so the mirror never sees an empty payee. - snapshotInvoicePayee: dry runs no longer persist; a failed snapshot write blocks issue (INVOICE_PAYEE_SNAPSHOT_FAILED). v1 mark-sent/mark-paid projections carry the payee columns; v1 create validates the payee before the dry-run return and echoes it in the preview. - pickAccountIdentifier: supplementary IBAN wins over a primary BBAN, and non-account schemes (card PANs) are never persisted. - Editor shows the payee select for a single usable account with no default; the booking dialog waits for cash accounts before proposing lines; a failed default write no longer hides a created account. - Behandlingshistorik names the account on created/deleted defaults. - Regenerated skills/accounted-api; MCP argument description trimmed under the tools/list payload ceiling. Declined: clearing legacy columns via a forward migration (the mirror now does it on delete); Swedish review's "show the debit account in the mark-paid UI" (the booking dialog already proposes and lets the user edit the debit line); manual ledger collision (UNIQUE exists, and the create path now rejects it with a clear error); Peppol aligning to the PDF value for companies whose legacy column had drifted from the map (the PDF is the customer-facing document; both now agree). Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01UaZTY21HVN57hJoPXKSLjV * fix(invoices): read NEW.invoice_payee only on the cash_accounts branch of the mirror trigger trg_mirror_invoice_payee_defaults fires for both tables; plpgsql resolves record fields per expression, so the combined condition failed with "record new has no field invoice_payee" whenever a default row changed, which took down every pg-real case on the payee tables. The revoke/disable check now sits inside its own TG_TABLE_NAME branch. The MCP settings executor test mocks the payee write-through like the settings route test already does. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01UaZTY21HVN57hJoPXKSLjV * fix(invoices): keep member disables from revoking payee defaults, gate payee on 1920-1999, fit the MCP payload Cycle 3 of /resolve-pr on #2233. Superagent P1: the SECURITY DEFINER mirror trigger deleted an admin's invoice_payee_defaults rows whenever cash_accounts.enabled flipped to false, and enabled is member-writable (the bank picker's "Synkas ej"), so a member could undo an admin's payee decision. The trigger now drops defaults only on the admin-only invoice_payee true -> false revoke; the mirror trigger's WHEN no longer lists enabled. Disabled accounts stay out of the pick lists and the send gate already refuses an invoice that chose one. Applied to staging as the same function + trigger definition and probed inside a rolled-back block: disable keeps the default and the mirrored bankgiro, revoke clears both. pg-real: the admin-guard test ran three expectations inside one withUserContext transaction; the first raise aborted it and the next statement failed with "current transaction is aborted". One transaction per expectation now, and the member case also flips enabled to prove the column stays member-level. Swedish review: payee eligibility was /^19\d\d$/, which admits 1910 Kassa and the 1911-1919 tills. A customer pays to a giro or bank account, so isBankCashAccount, CreateCashAccountSchema.ledger_account and the PATCH route now require BAS 1920-1999; tests cover 1910 and 1919. Unit tests (3/4): the tools/list payload guard read 60 025, then 60 014 tokens after main merged #2166 and #2163 alongside this branch. The ceiling is not bumped and no read on this surface is a demotion candidate, so gnubok_create_invoice drops payment_cash_account_id; agent-created invoices print the per-currency default and v1 REST plus the editor keep the field. Recorded in DECISIONS.md. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01UaZTY21HVN57hJoPXKSLjV * chore(migrations): move invoices_payment_cash_account to 20260903183000 after colliding with main's KPI migration origin/main merged 20260903160000_kpi_monthly_include_reversed_originals while this branch held the same version; identical versions abort the Supabase apply. Staging's schema_migrations row was moved to the new version with the file. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01UaZTY21HVN57hJoPXKSLjV * fix(invoices): gate invoice_payee on BAS 1920-1999 at the database, and unblock the typecheck ratchet Cycle 4 of /resolve-pr on #2233, on Emil's go. Swedish review: the 1920-1999 payee rule lived only in the routes. The cash_accounts_payee_admin_only trigger now also refuses invoice_payee on any other ledger (INVOICE_PAYEE_ACCOUNT_INVALID, 23514), whoever writes it, and the backfill only targets giro/bank rows, so a company whose single enabled cash_accounts row is a Stripe clearing account keeps its legacy bankgiro in company_settings instead of landing it on 1686. pg test covers insert and update on 1686 and 1910; the function was applied to staging and probed. Typecheck ratchet: main is red from two merges that landed with failing Checks, and every branch that syncs it inherits the errors. - #2242 added POST(req) calls to the fiscal-periods route test without the route params argument withRouteContext handlers take (25 errors in the file, baseline 23). All 25 calls now pass createMockRouteParams({}). - #2247 made SyncResult.requestedFromDate and historyNarrowed required; the 13 mockedSync results in the enable-banking accounts-route test lacked them. They now carry a fixed date and historyNarrowed: false. Both files' tests pass unchanged in behaviour. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * chore(migrations): move invoices_payment_cash_account to 20260903193000 after colliding with main's party_promotion origin/main merged 20260903183000_party_promotion while this branch held the same version. Staging's schema_migrations row must follow (pending: the Supabase MCP was disconnected at the time of this commit). Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> --------- Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Fable 5.1
parent
88a5d78594
commit
d670fe6663
@@ -1528,6 +1528,9 @@ One line per decision: `[YYYY-MM-DD] <decision>: <why>`. Appended by agents and
|
||||
[2026-09-03] Cursor MCP OAuth callbacks are built-in allowlist entries, exact-matched: cursor://anysphere.cursor-mcp/oauth/callback and https://www.cursor.com/agents/mcp/oauth/callback (the loopback http://localhost:8787/callback already passes the local rule). Cursor's DCR sends all three in one request and /register rejects the whole set on any unknown URI, so the Cursor path advertised in Settings never worked (reported by a byrå user 2026-09-03). Exact match, not a cursor.com prefix, so no other cursor.com path can receive codes; the custom scheme is accepted despite RFC 8252 section 8.4 because the code is PKCE-bound and the loopback form carries the same local-machine trust. Users cannot self-register the cursor:// form (the settings panel requires https), which is why it is built in. Grok Bot rides on Cursor's MCP stack and stays broken on Cursor's side (forum thread 168052, open as of 2026-09-02); nothing server-side fixes that.
|
||||
[2026-09-03] Skattekonto through Connect = the existing data proxy plus CONNECT_SKV_CANARY_COMPANIES, not a separate sync operation: the provider logic is two GETs and the dedup keys stay on the ledger; system (certificate) auth is still not brokered because hosted has no certificate configured, so every hosted skattekonto read is a user-token call the proxy already carries.
|
||||
[2026-09-03] Old-address social identities are unlinked by a BEFORE UPDATE trigger on auth.users (migration 20260903110000), not by the /auth/callback done path: the callback never runs for a completing click from a browser without a session, and admin-side changes bypass it entirely; the trigger covers every path and keeps the email identity, password and BankID intact.
|
||||
[2026-09-03] Invoice payee accounts live on cash_accounts (payee columns + invoice_payee) with a per-currency default table (invoice_payee_defaults), and company_settings.invoice_payment_accounts plus the legacy SEK bank columns become a trigger-maintained mirror of the default account, NOT a third writable source: one account may be the default for several currencies (a SEK account with an IBAN is the normal EUR payee, so a per-currency boolean on the account was wrong), the mirror keeps every existing PDF/email/Peppol/v1/MCP reader unchanged, and the three legacy writers (PUT /api/settings, v1 settings, MCP update_company_settings) write through to the default account so they can no longer drift from what the PDF prints. Backfill lands only on existing cash accounts (prod 2026-09-03: 227 of 239 entries); the 12 foreign-currency entries with no account stay in the map as the resolver fallback and get an attach action in settings. bg_pg dropped: never read or written, NULL on every prod and staging row.
|
||||
[2026-09-03] Per-invoice payee is a nullable invoices.payment_cash_account_id plus a payment_details snapshot written when the account is chosen and refreshed at issue (send, mark-sent, Peppol, recurring), not a live join at render time: issued invoices are evidence and must print what they printed, so /pdf re-renders read the snapshot, while invoices that never chose an account keep resolving the company default per currency exactly as before (no snapshot, no behaviour change). A chosen account that is disabled, un-flagged or unusable for the currency at issue blocks with INVOICE_SEND_PAYMENT_ACCOUNT_INVALID (Odoo blocks posting the same way) instead of silently falling back. The editor shows the "Betalas till" select only when the company has two or more usable payee accounts for the invoice currency.
|
||||
[2026-09-03] Manual mark-paid (dashboard, v1, MCP) debits the invoice's chosen payee account (cash_accounts.ledger_account) instead of the hard-coded 1930 the 2026-07 decision kept for lack of context; without a choice it stays 1930. Bank-transaction matching keeps debiting where the money landed and does NOT filter by the chosen account (Enable Banking cannot tell which giro was paid, and a customer may pay the wrong account): the chosen account is only a tie-breaker between equal-confidence candidates, so nothing that did not auto-match before starts to.
|
||||
[2026-09-03] Kontakter is not a user-facing noun (founder, after the register walkthrough): the registers people see stay Leverantörer and Kunder, the new page is the queue 'Förslag från bokföringen' plus 'Bara i bokföringen', and confirming a suggestion creates the leverantör or kund row directly (promote_parties). A confirmed party with no role never appears in the UI. The party model underneath is unchanged
|
||||
[2026-09-03] SCB registry lookups are made for juridiska personer only (org number with 20 or more in the month slot): a sole trader's org number is a personnummer, and sending it to SCB is personal-data processing with SCB as an independent controller; the plan keeps natural persons out of registry enrichment until the Art. 14 notice exists. The SokPaVar wire format sits in one file (lib/parties/scb/client.ts) because SCB replaces the API with an API-key one from September 2026
|
||||
[2026-09-03] SCB name search is a picker, never a lookup: the user chooses among SCB's matches and the chosen org number is recorded as a fact with source user before any fetch; one match is shown, not auto-picked, because a trade name is not an identity (Adobe Systems Software resolves to an Irish entity and a Swedish one)
|
||||
@@ -1542,6 +1545,7 @@ One line per decision: `[YYYY-MM-DD] <decision>: <why>`. Appended by agents and
|
||||
[2026-09-03] KPI monthly breakdown counts reversed originals (#2201): the monthly section of get_kpi_report_aggregates (new migration 20260903160000) and lib/reports/monthly-breakdown.ts now use tb_ex_year_end's entry set verbatim (posted + reversed, minus the undone year-end chain) instead of posted-only. A same-year storno then cancels inside the months as it does in the year total, so sum(months) = Nettoresultat; the reversal shows as negative revenue in its own month, which is the honest month view. The pg-real pin "in tb, not in monthly" was flipped, not worked around. Unblocks the per-month sum on Nyckeltal (#2196).
|
||||
[2026-09-03] customers.country and suppliers.country are ISO 3166-1 alpha-2 at every writer (form select, internal + v1 REST, MCP, imports, provider migration), normalised through one helper (lib/vat/country-codes.ts) that also accepts the Swedish/English names the form used to write; unknown text is a 400 on write and left as-is by the backfill (migration 20260903173000 keeps the original in country_raw for a one-UPDATE rollback, and derives the country from the VAT prefix for eu_business rows whose country was null or only the old writer default SE: on prod that is one validated row plus sixteen without a country, and without it they would flip from reverse charge to 25% on their next invoice). No CHECK constraint on the column: unmapped legacy rows would violate it, and the periodisk report already warns on those. The country-vs-type rule (swedish_business = SE, eu_business = not SE and either in the EU VAT area with a matching prefix or holding an EU-trade VAT registration such as a Swiss company with a DE number or Northern Ireland XI, non_eu_business = outside the EU) is enforced on customers only, and on update only when type, country or VAT number is part of the change so a contradictory legacy row can still change its email; individuals are free (a foreign private person is still a Swedish-VAT customer) and suppliers get normalisation without the rule, since #2025/#2028 are about sales VAT. An omitted country on create is SE for Swedish types, derived from the VAT prefix for eu_business, and a 400 for non_eu_business: guessing a non-EU country is not possible, and Sweden-by-default was the bug. vat-rules.ts takes the country as a third optional argument and refuses reverse charge only for SE (a VIES-validated number outweighs a non-EU address), and not for an unknown/unmapped country: charging Swedish VAT to a genuine German customer whose row says Deutschland (Bayern) would be the worse error.
|
||||
[2026-09-03] AGI kvittens cron: dropped the apigw_config bucket (#963) and its warn-once suppression for ACCESS_DENIED (#2226). The bucket existed because the APIGW client was known to lack the AGI hantera subscription in Utvecklarportalen; with that subscription expected in place, a gateway refusal is a regression and belongs in the ordinary error path (error level, generic 'error' status) rather than a status that hides it as a known gap. Same pass: the connector-mode gateway-refusal message names the connector operator by host instead of "kontakta supporten", because hosted is itself a Connect installation for the canary companies and "support" no longer says whose. Merging before the portal subscription is active means the 15-minute cron logs at error level per pending declaration until it is.
|
||||
[2026-09-03] Per-invoice payee (PR #2233): the MCP gnubok_create_invoice tool does not take payment_cash_account_id; an agent-created invoice prints the company's per-currency default payee. The tools/list payload was 14 tokens over its 60 000 ceiling after main merged #2166/#2163 alongside this branch, the ceiling is not to be bumped, and no read tool on this PR's surface is a candidate for search-only demotion. The v1 REST create/update and the UI editor take the field; add it back to the MCP schema when a demotion elsewhere frees the room. Same pass: payee eligibility is BAS 1920-1999, not 19xx, so a till (1910 Kassa) never prints as a bank account; and a member disabling a synced account (enabled=false) no longer deletes the admin's invoice_payee_defaults rows, only the admin-only invoice_payee=false revoke does, since a member must not be able to undo an admin's payee decision through the SECURITY DEFINER mirror trigger.
|
||||
[2026-09-03] Payment terms 0 days (#2070): customer and supplier forms plus the three API schemas accept whole days 0-365 (0 = betalning direkt), and every `|| 30` fallback became `?? 30` so a stored 0 does not reopen as 30. Upper bound 365 is a sanity cap, not law; the invoice schema's own cap (90) is unchanged.
|
||||
[2026-09-03] getErrorMessage passthrough (#2086): kept the keyword list as the first gate and added looksLikeUserFacingSwedish as a second (å/ä/ö, a strong Swedish word, or two weak function words, and no technical-leak pattern) instead of flipping to "show unless technical": several routes still return English free text ("Failed to disconnect") that must keep falling through to the status/context fallback, which existing tests pin. A registry-wide test asserts every message_sv passes.
|
||||
[2026-09-03] SIE IB-imbalance warning (#2082): names the cause and links the manual IB wizard, but does NOT let the SIE import skip IB (the import refuses a period whose IB is already set), so the copy says the file is not imported on the manual path. Plugging the diff to 2010/2019 for enskild firma and running findUntransferredResults at parse time are separate founder calls.
|
||||
|
||||
@@ -17,8 +17,10 @@ vi.mock('@/lib/company/context', () => ({
|
||||
}))
|
||||
|
||||
const requireWriteMock = vi.fn()
|
||||
const getCompanyRoleMock = vi.fn()
|
||||
vi.mock('@/lib/auth/require-write', () => ({
|
||||
requireWritePermission: (...args: unknown[]) => requireWriteMock(...args),
|
||||
getCompanyRole: (...args: unknown[]) => getCompanyRoleMock(...args),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/auth/require-auth', () => ({
|
||||
@@ -51,6 +53,47 @@ describe('PATCH /api/cash-accounts/[id] (verifikationsserie per bankkonto)', ()
|
||||
error: null,
|
||||
})
|
||||
requireWriteMock.mockResolvedValue({ ok: true })
|
||||
getCompanyRoleMock.mockResolvedValue({ ok: true, role: 'owner', companyId: 'company-1' })
|
||||
})
|
||||
|
||||
it('payee fields: 403 for a member, no role lookup for a pure voucher_series write', async () => {
|
||||
getCompanyRoleMock.mockResolvedValue({ ok: true, role: 'member', companyId: 'company-1' })
|
||||
const forbidden = await PATCH(patchReq({ bankgiro: '5050-1055' }), createMockRouteParams({ id: CA_1 }))
|
||||
expect(forbidden.status).toBe(403)
|
||||
expect(findCalls('cash_accounts', 'update')).toHaveLength(0)
|
||||
|
||||
enqueue({ data: { id: CA_1, voucher_series: 'M' } })
|
||||
const series = await PATCH(patchReq({ voucher_series: 'M' }), createMockRouteParams({ id: CA_1 }))
|
||||
expect(series.status).toBe(200)
|
||||
expect(getCompanyRoleMock).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('payee fields: 400 on an invalid bankgiro or an unknown key', async () => {
|
||||
expect((await PATCH(patchReq({ bankgiro: '12' }), createMockRouteParams({ id: CA_1 }))).status).toBe(400)
|
||||
expect((await PATCH(patchReq({ ledger_account: '1931' }), createMockRouteParams({ id: CA_1 }))).status).toBe(400)
|
||||
expect(findCalls('cash_accounts', 'update')).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('payee fields: 400 on a PSP clearing account (1686): only 19xx bank accounts print as payee', async () => {
|
||||
enqueue({ data: { id: CA_1, ledger_account: '1686' } })
|
||||
const response = await PATCH(patchReq({ bankgiro: '5050-1055', invoice_payee: true }), createMockRouteParams({ id: CA_1 }))
|
||||
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(response)
|
||||
expect(status).toBe(400)
|
||||
expect(body.error.code).toBe('INVOICE_PAYEE_ACCOUNT_INVALID')
|
||||
expect(findCalls('cash_accounts', 'update')).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('payee fields: owner writes bankgiro, clears plusgiro with "", and flags the account as payee', async () => {
|
||||
enqueue({ data: { id: CA_1, ledger_account: '1930' } })
|
||||
enqueue({ data: { id: CA_1, bankgiro: '5050-1055', plusgiro: null, invoice_payee: true } })
|
||||
const response = await PATCH(
|
||||
patchReq({ bankgiro: '5050-1055', plusgiro: '', invoice_payee: true }),
|
||||
createMockRouteParams({ id: CA_1 }),
|
||||
)
|
||||
const { status, body } = await parseJsonResponse<{ data: { bankgiro: string } }>(response)
|
||||
expect(status).toBe(200)
|
||||
expect(body.data.bankgiro).toBe('5050-1055')
|
||||
expect((findCalls('cash_accounts', 'update')[0][0] as Record<string, unknown>)).toMatchObject({ bankgiro: '5050-1055', plusgiro: null, invoice_payee: true })
|
||||
})
|
||||
|
||||
it('returns 401 when not authenticated', async () => {
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { withRouteContext } from '@/lib/api/with-route-context'
|
||||
import { validateBody } from '@/lib/api/validate'
|
||||
import { UpdateCashAccountVoucherSeriesSchema } from '@/lib/api/schemas'
|
||||
import { errorResponse } from '@/lib/errors/get-structured-error'
|
||||
import { UpdateCashAccountSchema } from '@/lib/api/schemas'
|
||||
import { errorResponse, errorResponseFromCode } from '@/lib/errors/get-structured-error'
|
||||
import { setVoucherSeries } from '@/lib/cash-accounts/service'
|
||||
import { isBankCashAccount, updateCashAccountPayee, type PayeeUpdate } from '@/lib/cash-accounts/invoice-payee'
|
||||
import { getCompanyRole } from '@/lib/auth/require-write'
|
||||
import { UUID_RE } from '@/lib/invariants/uuid'
|
||||
|
||||
/** Canonical 404 for an id that is not one of the company's bank accounts. */
|
||||
@@ -20,28 +22,89 @@ function notFound(): NextResponse {
|
||||
)
|
||||
}
|
||||
|
||||
const PAYEE_KEYS = [
|
||||
'name',
|
||||
'bank_name',
|
||||
'clearing_number',
|
||||
'account_number',
|
||||
'bankgiro',
|
||||
'plusgiro',
|
||||
'swish',
|
||||
'iban',
|
||||
'bic',
|
||||
'bank_code',
|
||||
'foreign_account_number',
|
||||
'invoice_payee',
|
||||
] as const
|
||||
|
||||
/**
|
||||
* PATCH /api/cash-accounts/[id]
|
||||
*
|
||||
* Sets or clears the verifikationsserie override on one of the company's
|
||||
* bank accounts. Only this one field is editable here: ledger account and
|
||||
* primary flag have their own guarded flows (unique constraint, atomic RPC).
|
||||
* Two independent concerns on one of the company's bank accounts:
|
||||
* - voucher_series: the verifikationsserie override (any writer role).
|
||||
* - payee fields + invoice_payee + name: what customer invoices print
|
||||
* (owner/admin only, same gate as the payment instructions on
|
||||
* /api/settings; members never control where customers pay).
|
||||
* Ledger account and primary flag have their own guarded flows.
|
||||
*/
|
||||
export const PATCH = withRouteContext<{ params: Promise<{ id: string }> }>(
|
||||
'cash_accounts.update',
|
||||
async (request, { supabase, companyId, log, requestId }, { params }) => {
|
||||
async (request, { supabase, companyId, log, requestId, user }, { params }) => {
|
||||
const { id } = await params
|
||||
// A non-UUID id can never match a row; answer 404 instead of letting the
|
||||
// uuid cast surface as a 500 from Postgres.
|
||||
if (!UUID_RE.test(id)) return notFound()
|
||||
const validation = await validateBody(request, UpdateCashAccountVoucherSeriesSchema)
|
||||
const validation = await validateBody(request, UpdateCashAccountSchema)
|
||||
if (!validation.success) return validation.response
|
||||
const body = validation.data
|
||||
|
||||
let updated
|
||||
const payeeUpdate: PayeeUpdate = {}
|
||||
for (const key of PAYEE_KEYS) {
|
||||
if (body[key] !== undefined) {
|
||||
// '' from a cleared form field clears the column.
|
||||
;(payeeUpdate as Record<string, unknown>)[key] = body[key] === '' ? null : body[key]
|
||||
}
|
||||
}
|
||||
const touchesPayee = Object.keys(payeeUpdate).length > 0
|
||||
|
||||
if (touchesPayee) {
|
||||
const roleResult = await getCompanyRole(supabase, user.id, { companyId })
|
||||
if (!roleResult.ok) return roleResult.response
|
||||
if (!['owner', 'admin'].includes(roleResult.role)) {
|
||||
return errorResponseFromCode('FORBIDDEN', log, {
|
||||
requestId,
|
||||
details: { required_roles: ['owner', 'admin'] },
|
||||
})
|
||||
}
|
||||
// Only giro/bank accounts (1920-1999) can be printed as payee. Stripe, Woo and
|
||||
// Shopify clearing rows live in the same table and must stay out.
|
||||
const { data: existing, error: existingError } = await supabase
|
||||
.from('cash_accounts')
|
||||
.select('id, ledger_account')
|
||||
.eq('company_id', companyId)
|
||||
.eq('id', id)
|
||||
.maybeSingle()
|
||||
if (existingError) return errorResponse(existingError, log, { requestId })
|
||||
if (!existing) return notFound()
|
||||
if (!isBankCashAccount(existing as { ledger_account: string })) {
|
||||
return errorResponseFromCode('INVOICE_PAYEE_ACCOUNT_INVALID', log, {
|
||||
requestId,
|
||||
details: { cash_account_id: id, reason: 'not_bank_account' },
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
let updated = null
|
||||
try {
|
||||
updated = await setVoucherSeries(supabase, companyId, id, validation.data.voucher_series)
|
||||
if (body.voucher_series !== undefined) {
|
||||
updated = await setVoucherSeries(supabase, companyId, id, body.voucher_series)
|
||||
if (!updated) return notFound()
|
||||
}
|
||||
if (touchesPayee) {
|
||||
updated = await updateCashAccountPayee(supabase, companyId, id, payeeUpdate)
|
||||
}
|
||||
} catch (err) {
|
||||
log.error('cash_accounts voucher_series update failed', err as Error)
|
||||
log.error('cash_accounts update failed', err as Error)
|
||||
return errorResponse(err, log, { requestId })
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,112 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { parseJsonResponse, createQueuedMockSupabase, createMockRouteParams } from '@/tests/helpers'
|
||||
|
||||
const { supabase: mockSupabase, enqueue, reset, findCalls } = createQueuedMockSupabase()
|
||||
vi.mock('@/lib/supabase/server', () => ({
|
||||
createClient: () => Promise.resolve(mockSupabase),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/company/context', () => ({
|
||||
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
|
||||
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
|
||||
}))
|
||||
|
||||
const requireWriteMock = vi.fn()
|
||||
const getCompanyRoleMock = vi.fn()
|
||||
vi.mock('@/lib/auth/require-write', () => ({
|
||||
requireWritePermission: (...args: unknown[]) => requireWriteMock(...args),
|
||||
getCompanyRole: (...args: unknown[]) => getCompanyRoleMock(...args),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/auth/require-auth', () => ({
|
||||
requireAuth: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/import/account-sync', () => ({
|
||||
syncMappedAccounts: vi.fn().mockResolvedValue({ error: null }),
|
||||
}))
|
||||
|
||||
const findFreeLedgerAccountMock = vi.fn()
|
||||
vi.mock('@/lib/cash-accounts/service', () => ({
|
||||
listForCompany: vi.fn().mockResolvedValue([]),
|
||||
findFreeLedgerAccount: (...args: unknown[]) => findFreeLedgerAccountMock(...args),
|
||||
}))
|
||||
|
||||
import { POST } from '../route'
|
||||
import { requireAuth } from '@/lib/auth/require-auth'
|
||||
|
||||
function postReq(body: unknown) {
|
||||
return new Request('http://localhost/api/cash-accounts', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(body),
|
||||
})
|
||||
}
|
||||
|
||||
describe('POST /api/cash-accounts (manual bank account)', () => {
|
||||
const mockUser = { id: 'user-1', email: 'test@test.se' }
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
reset()
|
||||
vi.mocked(requireAuth).mockResolvedValue({
|
||||
user: mockUser as never,
|
||||
supabase: mockSupabase as never,
|
||||
error: null,
|
||||
})
|
||||
requireWriteMock.mockResolvedValue({ ok: true })
|
||||
getCompanyRoleMock.mockResolvedValue({ ok: true, role: 'admin', companyId: 'company-1' })
|
||||
findFreeLedgerAccountMock.mockResolvedValue('1931')
|
||||
})
|
||||
|
||||
it('returns 401 when not authenticated', async () => {
|
||||
vi.mocked(requireAuth).mockResolvedValue({
|
||||
user: null as never,
|
||||
supabase: mockSupabase as never,
|
||||
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
|
||||
})
|
||||
expect((await POST(postReq({ name: 'Sparkonto', currency: 'SEK' }), createMockRouteParams({}))).status).toBe(401)
|
||||
})
|
||||
|
||||
it('returns 400 on an invalid body: missing name, bad bankgiro, non-19xx ledger', async () => {
|
||||
expect((await POST(postReq({ currency: 'SEK' }), createMockRouteParams({}))).status).toBe(400)
|
||||
expect((await POST(postReq({ name: 'X', currency: 'SEK', payee: { bankgiro: '12' } }), createMockRouteParams({}))).status).toBe(400)
|
||||
expect((await POST(postReq({ name: 'X', currency: 'SEK', ledger_account: '1510' }), createMockRouteParams({}))).status).toBe(400)
|
||||
expect((await POST(postReq({ name: 'X', currency: 'SEK', ledger_account: '1910' }), createMockRouteParams({}))).status).toBe(400)
|
||||
expect(findCalls('cash_accounts', 'insert')).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('returns 403 for a member', async () => {
|
||||
getCompanyRoleMock.mockResolvedValue({ ok: true, role: 'member', companyId: 'company-1' })
|
||||
expect((await POST(postReq({ name: 'Sparkonto', currency: 'SEK' }), createMockRouteParams({}))).status).toBe(403)
|
||||
expect(findCalls('cash_accounts', 'insert')).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('creates the account on the next free 19xx slot with the payee fields (happy path)', async () => {
|
||||
enqueue({ data: [{ ledger_account: '1930' }] }) // rows the company already holds
|
||||
enqueue({ data: { id: 'ca-new', ledger_account: '1931', name: 'Sparkonto', bankgiro: '5050-1234' } })
|
||||
|
||||
const response = await POST(postReq({
|
||||
name: 'Sparkonto',
|
||||
currency: 'SEK',
|
||||
payee: { bankgiro: '5050-1234', plusgiro: '' },
|
||||
}), createMockRouteParams({}))
|
||||
const { status, body } = await parseJsonResponse<{ data: { id: string; ledger_account: string } }>(response)
|
||||
|
||||
expect(status).toBe(201)
|
||||
expect(body.data.ledger_account).toBe('1931')
|
||||
expect(findFreeLedgerAccountMock).toHaveBeenCalledWith(expect.anything(), 'company-1', 'SEK', new Set(['1930']))
|
||||
const [insert] = findCalls('cash_accounts', 'insert')
|
||||
expect(insert[0]).toMatchObject({
|
||||
company_id: 'company-1',
|
||||
ledger_account: '1931',
|
||||
currency: 'SEK',
|
||||
name: 'Sparkonto',
|
||||
source: 'manual',
|
||||
invoice_payee: true,
|
||||
bankgiro: '5050-1234',
|
||||
plusgiro: null,
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,145 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { parseJsonResponse, createQueuedMockSupabase, createMockRouteParams } from '@/tests/helpers'
|
||||
|
||||
const { supabase: mockSupabase, enqueue, reset, findCalls } = createQueuedMockSupabase()
|
||||
vi.mock('@/lib/supabase/server', () => ({
|
||||
createClient: () => Promise.resolve(mockSupabase),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/company/context', () => ({
|
||||
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
|
||||
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
|
||||
}))
|
||||
|
||||
const requireWriteMock = vi.fn()
|
||||
const getCompanyRoleMock = vi.fn()
|
||||
vi.mock('@/lib/auth/require-write', () => ({
|
||||
requireWritePermission: (...args: unknown[]) => requireWriteMock(...args),
|
||||
getCompanyRole: (...args: unknown[]) => getCompanyRoleMock(...args),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/auth/require-auth', () => ({
|
||||
requireAuth: vi.fn(),
|
||||
}))
|
||||
|
||||
import { GET, PUT } from '../route'
|
||||
import { requireAuth } from '@/lib/auth/require-auth'
|
||||
|
||||
const CA_1 = '11111111-1111-4111-8111-111111111111'
|
||||
|
||||
function putReq(body: unknown) {
|
||||
return new Request('http://localhost/api/cash-accounts/payee-defaults', {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(body),
|
||||
})
|
||||
}
|
||||
|
||||
describe('/api/cash-accounts/payee-defaults', () => {
|
||||
const mockUser = { id: 'user-1', email: 'test@test.se' }
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
reset()
|
||||
vi.mocked(requireAuth).mockResolvedValue({
|
||||
user: mockUser as never,
|
||||
supabase: mockSupabase as never,
|
||||
error: null,
|
||||
})
|
||||
requireWriteMock.mockResolvedValue({ ok: true })
|
||||
getCompanyRoleMock.mockResolvedValue({ ok: true, role: 'owner', companyId: 'company-1' })
|
||||
})
|
||||
|
||||
it('GET returns 401 when not authenticated', async () => {
|
||||
vi.mocked(requireAuth).mockResolvedValue({
|
||||
user: null as never,
|
||||
supabase: mockSupabase as never,
|
||||
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
|
||||
})
|
||||
const response = await GET(new Request('http://localhost/api/cash-accounts/payee-defaults'), createMockRouteParams({}))
|
||||
expect(response.status).toBe(401)
|
||||
})
|
||||
|
||||
it('GET lists bank-type accounts and the defaults, dropping PSP clearing accounts', async () => {
|
||||
enqueue({ data: [
|
||||
{ id: CA_1, ledger_account: '1930', currency: 'SEK' },
|
||||
{ id: 'stripe', ledger_account: '1686', currency: 'SEK' },
|
||||
] })
|
||||
enqueue({ data: [{ id: 'd1', currency: 'SEK', cash_account_id: CA_1 }] })
|
||||
|
||||
const response = await GET(new Request('http://localhost/api/cash-accounts/payee-defaults'), createMockRouteParams({}))
|
||||
const { status, body } = await parseJsonResponse<{ data: { accounts: { id: string }[]; defaults: { currency: string }[] } }>(response)
|
||||
|
||||
expect(status).toBe(200)
|
||||
expect(body.data.accounts.map((a) => a.id)).toEqual([CA_1])
|
||||
expect(body.data.defaults).toEqual([{ id: 'd1', currency: 'SEK', cash_account_id: CA_1 }])
|
||||
})
|
||||
|
||||
it('PUT returns 400 on an unknown currency or a malformed id', async () => {
|
||||
expect((await PUT(putReq({ currency: 'CHF', cash_account_id: CA_1 }), createMockRouteParams({}))).status).toBe(400)
|
||||
expect((await PUT(putReq({ currency: 'SEK', cash_account_id: 'nope' }), createMockRouteParams({}))).status).toBe(400)
|
||||
expect(findCalls('invoice_payee_defaults', 'upsert')).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('PUT returns 403 for a member: only owner/admin decide where customers pay', async () => {
|
||||
getCompanyRoleMock.mockResolvedValue({ ok: true, role: 'member', companyId: 'company-1' })
|
||||
const response = await PUT(putReq({ currency: 'SEK', cash_account_id: CA_1 }), createMockRouteParams({}))
|
||||
expect(response.status).toBe(403)
|
||||
expect(findCalls('invoice_payee_defaults', 'upsert')).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('PUT returns 400 when the account is disabled, not a payee, a PSP row, or unusable for the currency', async () => {
|
||||
for (const row of [
|
||||
{ id: CA_1, ledger_account: '1930', currency: 'SEK', enabled: false, invoice_payee: true, bankgiro: '5050-1055' },
|
||||
{ id: CA_1, ledger_account: '1930', currency: 'SEK', enabled: true, invoice_payee: false, bankgiro: '5050-1055' },
|
||||
{ id: CA_1, ledger_account: '1686', currency: 'SEK', enabled: true, invoice_payee: true, bankgiro: '5050-1055' },
|
||||
{ id: CA_1, ledger_account: '1930', currency: 'SEK', enabled: true, invoice_payee: true, bankgiro: '5050-1055', payee_iban: null },
|
||||
]) {
|
||||
enqueue({ data: row })
|
||||
const currency = row.payee_iban === null ? 'EUR' : 'SEK'
|
||||
const response = await PUT(putReq({ currency, cash_account_id: CA_1 }), createMockRouteParams({}))
|
||||
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(response)
|
||||
expect(status).toBe(400)
|
||||
expect(body.error.code).toBe('INVOICE_PAYEE_ACCOUNT_INVALID')
|
||||
}
|
||||
expect(findCalls('invoice_payee_defaults', 'upsert')).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('PUT returns 404 when the account is not one of the company\'s', async () => {
|
||||
enqueue({ data: null })
|
||||
const response = await PUT(putReq({ currency: 'SEK', cash_account_id: CA_1 }), createMockRouteParams({}))
|
||||
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(response)
|
||||
expect(status).toBe(404)
|
||||
expect(body.error.code).toBe('CASH_ACCOUNT_NOT_FOUND')
|
||||
})
|
||||
|
||||
it('PUT upserts the default and returns the refreshed state (happy path)', async () => {
|
||||
enqueue({ data: { id: CA_1, ledger_account: '1930', currency: 'SEK', invoice_payee: true, enabled: true, bankgiro: '5050-1055' } }) // account lookup
|
||||
enqueue({ data: null }) // upsert
|
||||
enqueue({ data: [{ id: CA_1, ledger_account: '1930', currency: 'SEK' }] })
|
||||
enqueue({ data: [{ id: 'd1', currency: 'SEK', cash_account_id: CA_1 }] })
|
||||
|
||||
const response = await PUT(putReq({ currency: 'SEK', cash_account_id: CA_1 }), createMockRouteParams({}))
|
||||
const { status, body } = await parseJsonResponse<{ data: { defaults: { cash_account_id: string }[] } }>(response)
|
||||
|
||||
expect(status).toBe(200)
|
||||
expect(body.data.defaults[0].cash_account_id).toBe(CA_1)
|
||||
expect(findCalls('invoice_payee_defaults', 'upsert')[0][0]).toEqual({
|
||||
company_id: 'company-1',
|
||||
currency: 'SEK',
|
||||
cash_account_id: CA_1,
|
||||
})
|
||||
})
|
||||
|
||||
it('PUT with null clears the default for that currency', async () => {
|
||||
enqueue({ data: null }) // delete
|
||||
enqueue({ data: [] })
|
||||
enqueue({ data: [] })
|
||||
|
||||
const response = await PUT(putReq({ currency: 'EUR', cash_account_id: null }), createMockRouteParams({}))
|
||||
expect(response.status).toBe(200)
|
||||
expect(findCalls('invoice_payee_defaults', 'delete')).toHaveLength(1)
|
||||
expect(findCalls('invoice_payee_defaults', 'eq')).toContainEqual(['currency', 'EUR'])
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,106 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { withRouteContext } from '@/lib/api/with-route-context'
|
||||
import { validateBody } from '@/lib/api/validate'
|
||||
import { SetInvoicePayeeDefaultSchema } from '@/lib/api/schemas'
|
||||
import { errorResponse, errorResponseFromCode } from '@/lib/errors/get-structured-error'
|
||||
import {
|
||||
isBankCashAccount,
|
||||
isUsableInvoicePayee,
|
||||
loadInvoicePayeeState,
|
||||
setInvoicePayeeDefault,
|
||||
} from '@/lib/cash-accounts/invoice-payee'
|
||||
import type { CashAccount } from '@/types'
|
||||
import { getCompanyRole } from '@/lib/auth/require-write'
|
||||
|
||||
/**
|
||||
* GET /api/cash-accounts/payee-defaults
|
||||
*
|
||||
* The company's bank accounts together with which one an invoice in each
|
||||
* currency prints as payee when the invoice does not choose.
|
||||
*/
|
||||
export const GET = withRouteContext(
|
||||
'cash_accounts.payee_defaults.list',
|
||||
async (_request, { supabase, companyId, log, requestId }) => {
|
||||
try {
|
||||
const state = await loadInvoicePayeeState(supabase, companyId)
|
||||
return NextResponse.json({ data: state })
|
||||
} catch (err) {
|
||||
log.error('invoice payee defaults load failed', err as Error)
|
||||
return errorResponse(err, log, { requestId })
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
/**
|
||||
* PUT /api/cash-accounts/payee-defaults
|
||||
*
|
||||
* Set (or clear with null) the default payee account for one currency.
|
||||
* Owner/admin only: this decides where every new invoice in that currency
|
||||
* tells the customer to pay. The mirror trigger rewrites the legacy
|
||||
* company_settings map from the chosen account.
|
||||
*/
|
||||
export const PUT = withRouteContext(
|
||||
'cash_accounts.payee_defaults.set',
|
||||
async (request, { supabase, companyId, log, requestId, user }) => {
|
||||
const validation = await validateBody(request, SetInvoicePayeeDefaultSchema)
|
||||
if (!validation.success) return validation.response
|
||||
const { currency, cash_account_id } = validation.data
|
||||
|
||||
const roleResult = await getCompanyRole(supabase, user.id, { companyId })
|
||||
if (!roleResult.ok) return roleResult.response
|
||||
if (!['owner', 'admin'].includes(roleResult.role)) {
|
||||
return errorResponseFromCode('FORBIDDEN', log, {
|
||||
requestId,
|
||||
details: { required_roles: ['owner', 'admin'] },
|
||||
})
|
||||
}
|
||||
|
||||
if (cash_account_id) {
|
||||
const { data: account, error } = await supabase
|
||||
.from('cash_accounts')
|
||||
.select('*')
|
||||
.eq('company_id', companyId)
|
||||
.eq('id', cash_account_id)
|
||||
.maybeSingle()
|
||||
if (error) {
|
||||
log.error('invoice payee default account lookup failed', error)
|
||||
return errorResponse(error, log, { requestId })
|
||||
}
|
||||
if (!account) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: {
|
||||
code: 'CASH_ACCOUNT_NOT_FOUND',
|
||||
message: 'Bankkontot hittades inte.',
|
||||
message_en: 'Bank account not found.',
|
||||
},
|
||||
},
|
||||
{ status: 404 },
|
||||
)
|
||||
}
|
||||
// A default must be printable for the currency: a bank-type account,
|
||||
// enabled, flagged as payee, with the identifiers the currency needs.
|
||||
const typed = account as CashAccount
|
||||
if (!isBankCashAccount(typed) || !isUsableInvoicePayee(typed, currency)) {
|
||||
return errorResponseFromCode('INVOICE_PAYEE_ACCOUNT_INVALID', log, {
|
||||
requestId,
|
||||
details: {
|
||||
cash_account_id,
|
||||
currency,
|
||||
reason: !isBankCashAccount(typed) ? 'not_bank_account' : !typed.enabled ? 'disabled' : !typed.invoice_payee ? 'not_payee' : 'unusable_for_currency',
|
||||
},
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
await setInvoicePayeeDefault(supabase, companyId, currency, cash_account_id)
|
||||
const state = await loadInvoicePayeeState(supabase, companyId)
|
||||
return NextResponse.json({ data: state })
|
||||
} catch (err) {
|
||||
log.error('invoice payee default set failed', err as Error)
|
||||
return errorResponse(err, log, { requestId })
|
||||
}
|
||||
},
|
||||
{ requireWrite: true },
|
||||
)
|
||||
@@ -1,6 +1,11 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { withRouteContext } from '@/lib/api/with-route-context'
|
||||
import { validateBody } from '@/lib/api/validate'
|
||||
import { CreateCashAccountSchema } from '@/lib/api/schemas'
|
||||
import { errorResponse, errorResponseFromCode } from '@/lib/errors/get-structured-error'
|
||||
import { listForCompany } from '@/lib/cash-accounts/service'
|
||||
import { createManualBankAccount } from '@/lib/cash-accounts/invoice-payee'
|
||||
import { getCompanyRole } from '@/lib/auth/require-write'
|
||||
|
||||
/**
|
||||
* GET /api/cash-accounts
|
||||
@@ -24,3 +29,48 @@ export const GET = withRouteContext('cash_accounts.list', async (request, ctx) =
|
||||
const accounts = await listForCompany(supabase, companyId, { enabledOnly })
|
||||
return NextResponse.json({ data: accounts })
|
||||
})
|
||||
|
||||
/**
|
||||
* POST /api/cash-accounts
|
||||
*
|
||||
* A bank account the user types in (no bank connection): name, currency and
|
||||
* the payee details customers pay to. Gets the next free 19xx ledger slot
|
||||
* for its currency unless one is given. Owner/admin only: it becomes a
|
||||
* printable payee.
|
||||
*/
|
||||
export const POST = withRouteContext(
|
||||
'cash_accounts.create',
|
||||
async (request, { supabase, companyId, log, requestId, user }) => {
|
||||
const validation = await validateBody(request, CreateCashAccountSchema)
|
||||
if (!validation.success) return validation.response
|
||||
const body = validation.data
|
||||
|
||||
const roleResult = await getCompanyRole(supabase, user.id, { companyId })
|
||||
if (!roleResult.ok) return roleResult.response
|
||||
if (!['owner', 'admin'].includes(roleResult.role)) {
|
||||
return errorResponseFromCode('FORBIDDEN', log, {
|
||||
requestId,
|
||||
details: { required_roles: ['owner', 'admin'] },
|
||||
})
|
||||
}
|
||||
|
||||
const payee = Object.fromEntries(
|
||||
Object.entries(body.payee ?? {}).map(([key, value]) => [key, value === '' ? null : value]),
|
||||
)
|
||||
|
||||
try {
|
||||
const account = await createManualBankAccount(supabase, companyId, user.id, {
|
||||
name: body.name,
|
||||
currency: body.currency,
|
||||
ledger_account: body.ledger_account ?? null,
|
||||
invoice_payee: body.invoice_payee,
|
||||
payee,
|
||||
})
|
||||
return NextResponse.json({ data: account }, { status: 201 })
|
||||
} catch (err) {
|
||||
log.error('cash_accounts create failed', err as Error)
|
||||
return errorResponse(err, log, { requestId })
|
||||
}
|
||||
},
|
||||
{ requireWrite: true },
|
||||
)
|
||||
|
||||
@@ -3,10 +3,16 @@ import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
// Mock dependencies: factory must not reference outer variables
|
||||
const mockCreateSession = vi.fn()
|
||||
const mockGetAccountBalance = vi.fn()
|
||||
vi.mock('@/extensions/general/enable-banking/lib/api-client', () => ({
|
||||
createSession: (...args: unknown[]) => mockCreateSession(...args),
|
||||
getAccountBalance: (...args: unknown[]) => mockGetAccountBalance(...args),
|
||||
}))
|
||||
vi.mock('@/extensions/general/enable-banking/lib/api-client', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('@/extensions/general/enable-banking/lib/api-client')>()
|
||||
return {
|
||||
// Pure identifier extraction: keep the real implementation so the stored
|
||||
// accounts carry what the bank actually sent.
|
||||
extractBban: actual.extractBban,
|
||||
createSession: (...args: unknown[]) => mockCreateSession(...args),
|
||||
getAccountBalance: (...args: unknown[]) => mockGetAccountBalance(...args),
|
||||
}
|
||||
})
|
||||
|
||||
// Use hoisted to safely create mock objects referenced in vi.mock factories
|
||||
const {
|
||||
@@ -363,7 +369,18 @@ describe('GET /api/extensions/enable-banking/callback', () => {
|
||||
mockCreateSession.mockResolvedValue({
|
||||
session_id: 'sess-1',
|
||||
accounts: [
|
||||
{ uid: 'acc-1', account_id: { iban: 'SE1234' }, name: 'Företagskonto', currency: 'SEK' },
|
||||
{
|
||||
uid: 'acc-1',
|
||||
account_id: { iban: 'SE1234' },
|
||||
// Swedish ASPSPs list the BBAN (clearing + account) alongside the
|
||||
// IBAN; it must land on the stored account for payee prefill.
|
||||
all_account_ids: [
|
||||
{ identification: 'SE1234', scheme_name: 'IBAN' },
|
||||
{ identification: '5000 1234567', scheme_name: 'BBAN' },
|
||||
],
|
||||
name: 'Företagskonto',
|
||||
currency: 'SEK',
|
||||
},
|
||||
{ uid: 'acc-2', account_id: { iban: 'SE5678' }, name: 'Privatkonto', currency: 'SEK' },
|
||||
],
|
||||
access: { valid_until: '2024-12-31T00:00:00Z' },
|
||||
@@ -404,9 +421,11 @@ describe('GET /api/extensions/enable-banking/callback', () => {
|
||||
const payload = capturedUpdates[0]
|
||||
expect(payload.status).toBe('pending_selection')
|
||||
expect(payload).not.toHaveProperty('last_synced_at')
|
||||
const accountsData = payload.accounts_data as Array<{ uid: string; enabled: boolean }>
|
||||
const accountsData = payload.accounts_data as Array<{ uid: string; enabled: boolean; bban?: string }>
|
||||
expect(accountsData).toHaveLength(2)
|
||||
expect(accountsData.every(a => a.enabled === true)).toBe(true)
|
||||
expect(accountsData.find(a => a.uid === 'acc-1')?.bban).toBe('50001234567')
|
||||
expect(accountsData.find(a => a.uid === 'acc-2')?.bban).toBeUndefined()
|
||||
|
||||
// Two same-currency accounts must NOT collide on the same BAS slot — the
|
||||
// second SEK account gets the next free 19xx sub-account, and the
|
||||
|
||||
@@ -3,7 +3,7 @@ import { createServiceClient } from '@/lib/supabase/server'
|
||||
import { NextResponse, after } from 'next/server'
|
||||
import { ensureInitialized } from '@/lib/init'
|
||||
import { createLogger } from '@/lib/logger'
|
||||
import { createSession, type AccountInfo } from '@/extensions/general/enable-banking/lib/api-client'
|
||||
import { createSession, extractBban, type AccountInfo } from '@/extensions/general/enable-banking/lib/api-client'
|
||||
import type { StoredAccount } from '@/extensions/general/enable-banking/types'
|
||||
import { eventBus } from '@/lib/events/bus'
|
||||
import {
|
||||
@@ -470,6 +470,7 @@ async function finalizeConnection(
|
||||
return {
|
||||
uid: account.uid,
|
||||
iban: account.account_id?.iban,
|
||||
bban: extractBban(account),
|
||||
name: account.name || account.product,
|
||||
currency: account.currency,
|
||||
// Carry the user's earlier choice for an account we have seen before;
|
||||
@@ -827,6 +828,7 @@ async function finalizeConnection(
|
||||
currency: account.currency,
|
||||
ledger_account: targetLedger,
|
||||
iban: account.iban ?? null,
|
||||
bban: account.bban ?? null,
|
||||
name: account.name ?? null,
|
||||
enabled: account.enabled ?? true,
|
||||
reuse_cash_account_id: reuseCashAccountId,
|
||||
|
||||
@@ -222,7 +222,7 @@ describe('POST /api/invoices/[id]/mark-paid', () => {
|
||||
undefined,
|
||||
expect.anything(),
|
||||
undefined, // paymentAmount: full settle
|
||||
undefined // settlementAccountNumber: default 1930
|
||||
'1930' // settlementAccountNumber: no chosen payee account, so the default
|
||||
)
|
||||
})
|
||||
|
||||
@@ -291,7 +291,7 @@ describe('POST /api/invoices/[id]/mark-paid', () => {
|
||||
expect.any(String),
|
||||
'enskild_firma',
|
||||
expect.anything(),
|
||||
undefined // settlementAccountNumber: default 1930
|
||||
'1930' // settlementAccountNumber: no chosen payee account, so the default
|
||||
)
|
||||
})
|
||||
|
||||
|
||||
@@ -6,6 +6,7 @@ import { errorResponse, errorResponseFromCode } from '@/lib/errors/get-structure
|
||||
import { deriveCustomerSettlementAmount } from '@/lib/invoices/apply-invoice-payment'
|
||||
import { findDuplicatePaymentCandidatesForInvoice } from '@/lib/invoices/duplicate-payment-candidates'
|
||||
import { settleInvoicePayment } from '@/lib/invoices/settle-invoice-payment'
|
||||
import { resolveInvoiceSettlementAccount } from '@/lib/invoices/invoice-payee'
|
||||
import { roundOre } from '@/lib/money'
|
||||
import type { EntityType, Invoice } from '@/types'
|
||||
|
||||
@@ -242,6 +243,9 @@ export const POST = withRouteContext(
|
||||
// paymentAmountInInvoiceCurrency was resolved above, before the
|
||||
// duplicate-payment guard, so the guard comparison and the ledger math run
|
||||
// in the same unit as remaining_amount.
|
||||
// The generated debit lands on the bank account the invoice asked to be
|
||||
// paid to (1930 when none was chosen). Custom lines carry their own.
|
||||
const settlementAccountNumber = await resolveInvoiceSettlementAccount(supabase, companyId!, invoice as Invoice)
|
||||
const result = await settleInvoicePayment(supabase, companyId!, user.id, {
|
||||
invoice: invoice as Invoice & { customer?: { name?: string | null } | null },
|
||||
paymentAmountInInvoiceCurrency,
|
||||
@@ -250,6 +254,7 @@ export const POST = withRouteContext(
|
||||
entityType,
|
||||
exchangeRateDifference,
|
||||
customLines,
|
||||
settlementAccountNumber,
|
||||
})
|
||||
|
||||
if (!result.ok) {
|
||||
|
||||
@@ -116,7 +116,10 @@ export const GET = withRouteContext<{ params: Promise<{ id: string }> }>(
|
||||
const { branding, company: renderCompany } = await prepareInvoicePdfRender(
|
||||
company as CompanySettings,
|
||||
(invoice as Invoice).currency,
|
||||
{ paymentAccountRequired: invoiceRequiresPaymentAccount(invoice as Invoice) },
|
||||
{
|
||||
paymentAccountRequired: invoiceRequiresPaymentAccount(invoice as Invoice),
|
||||
payee: (invoice as Invoice).payment_details ?? null,
|
||||
},
|
||||
)
|
||||
const swishQrDataUrl = await buildSwishQrDataUrl(renderCompany, invoice as Invoice)
|
||||
const paymentLinkQrDataUrl = await buildPaymentLinkQrDataUrl(invoice as Invoice)
|
||||
|
||||
@@ -7,6 +7,7 @@ import { ensureInitialized } from '@/lib/init'
|
||||
import { ensureInvoiceNumber } from '@/lib/invoices/ensure-invoice-number'
|
||||
import { issueAndBookInvoice, type IssueAndBookResult } from '@/lib/invoices/issue-and-book-invoice'
|
||||
import { hasRequiredInvoicePaymentAccount } from '@/lib/invoices/payment-accounts'
|
||||
import { snapshotInvoicePayee } from '@/lib/invoices/invoice-payee'
|
||||
import {
|
||||
PEPPOL_BIS_BILLING_INVOICE_DOCUMENT_TYPE_ID,
|
||||
PEPPOL_BIS_BILLING_PROFILE_ID,
|
||||
@@ -149,6 +150,16 @@ export const POST = withRouteContext<{ params: Promise<{ id: string }> }>(
|
||||
// A draft is issued (numbered, marked sent, booked) after the network
|
||||
// accepts it. Refuse up front what issuance would refuse afterwards, so an
|
||||
// invoice never reaches the buyer and then fails to book.
|
||||
if (wasDraft) {
|
||||
const payeeSnapshot = await snapshotInvoicePayee(supabase, companyId, invoice)
|
||||
if (!payeeSnapshot.ok) {
|
||||
return privateNoStore(errorResponseFromCode(payeeSnapshot.code, log, {
|
||||
requestId,
|
||||
details: payeeSnapshot.details,
|
||||
}))
|
||||
}
|
||||
invoice.payment_details = payeeSnapshot.payee
|
||||
}
|
||||
if (wasDraft && !hasRequiredInvoicePaymentAccount(company, invoice)) {
|
||||
return privateNoStore(errorResponseFromCode('INVOICE_SEND_PAYMENT_ACCOUNT_MISSING', log, {
|
||||
requestId,
|
||||
|
||||
@@ -5,6 +5,7 @@ import { withRouteContext } from '@/lib/api/with-route-context'
|
||||
import { validateBody } from '@/lib/api/validate'
|
||||
import { UpdateInvoiceSchema } from '@/lib/api/schemas'
|
||||
import { buildInvoiceWriteData } from '@/lib/invoices/build-invoice-write'
|
||||
import { resolveInvoicePayeeChoice, type InvoicePayeeFields } from '@/lib/invoices/invoice-payee'
|
||||
import { isEditableInvoiceDraft } from '@/lib/invoices/is-editable-draft'
|
||||
import { deleteDraftInvoice } from '@/lib/invoices/delete-draft-invoice'
|
||||
import { replaceInvoiceItems } from '@/lib/invoices/replace-invoice-items'
|
||||
@@ -165,6 +166,22 @@ export const PATCH = withRouteContext<{ params: Promise<{ id: string }> }>(
|
||||
return errorResponseFromCode(build.code, ctxLog, { requestId, details: build.details })
|
||||
}
|
||||
|
||||
// Payee choice: omitted = unchanged (a partial update must not clear a
|
||||
// draft's chosen account); null = back to the per-currency default.
|
||||
let payeeFields: Partial<InvoicePayeeFields> = {}
|
||||
if (input.payment_cash_account_id !== undefined) {
|
||||
const payeeChoice = await resolveInvoicePayeeChoice(
|
||||
supabase,
|
||||
companyId!,
|
||||
input.currency,
|
||||
input.payment_cash_account_id,
|
||||
)
|
||||
if (!payeeChoice.ok) {
|
||||
return errorResponseFromCode(payeeChoice.code, ctxLog, { requestId, details: payeeChoice.details })
|
||||
}
|
||||
payeeFields = payeeChoice.fields
|
||||
}
|
||||
|
||||
// Update the draft row. invoice_number + status are intentionally NOT in
|
||||
// build.invoiceFields, so they are preserved. The .eq('status','draft')
|
||||
// guard turns a concurrent send/finalize into a 0-row update (race), rather
|
||||
@@ -181,7 +198,12 @@ export const PATCH = withRouteContext<{ params: Promise<{ id: string }> }>(
|
||||
: build.invoiceFields
|
||||
const { data: updated, error: updateError } = await supabase
|
||||
.from('invoices')
|
||||
.update({ ...updateFields, updated_at: new Date().toISOString() })
|
||||
.update({
|
||||
...updateFields,
|
||||
payment_cash_account_id: payeeFields.payment_cash_account_id,
|
||||
payment_details: payeeFields.payment_details,
|
||||
updated_at: new Date().toISOString(),
|
||||
})
|
||||
.eq('id', id)
|
||||
.eq('company_id', companyId!)
|
||||
.eq('status', 'draft')
|
||||
|
||||
@@ -146,7 +146,7 @@ export const POST = withRouteContext<{ params: Promise<{ id: string }> }>(
|
||||
const { branding, company: renderCompany } = await prepareInvoicePdfRender(
|
||||
company as CompanySettings,
|
||||
(invoice as Invoice).currency,
|
||||
{ paymentAccountRequired },
|
||||
{ paymentAccountRequired, payee: (invoice as Invoice).payment_details ?? null },
|
||||
)
|
||||
const swishQrDataUrl = await buildSwishQrDataUrl(renderCompany, invoice as Invoice)
|
||||
const paymentLinkQrDataUrl = await buildPaymentLinkQrDataUrl(invoice as Invoice)
|
||||
|
||||
@@ -4,6 +4,7 @@ import { ensureInitialized } from '@/lib/init'
|
||||
import { renderToBuffer } from '@react-pdf/renderer'
|
||||
import { InvoicePDF } from '@/lib/invoices/pdf-template'
|
||||
import { prepareInvoicePdfRender, buildSwishQrDataUrl, buildPaymentLinkQrDataUrl } from '@/lib/invoices/pdf-render-helpers'
|
||||
import { snapshotInvoicePayee } from '@/lib/invoices/invoice-payee'
|
||||
import { getEmailService } from '@/lib/email/service'
|
||||
import { resolveInvoiceSender } from '@/lib/email/invoice-sender'
|
||||
import {
|
||||
@@ -191,6 +192,12 @@ export const POST = withRouteContext(
|
||||
|
||||
const invoiceCurrency = (invoice as Invoice).currency
|
||||
const paymentAccountRequired = invoiceRequiresPaymentAccount(invoice as Invoice)
|
||||
// Freeze the chosen bank account's payee at issue (no-op without a choice).
|
||||
const payeeSnapshot = await snapshotInvoicePayee(supabase, companyId, invoice as Invoice)
|
||||
if (!payeeSnapshot.ok) {
|
||||
return errorResponseFromCode(payeeSnapshot.code, opLog, { requestId, details: payeeSnapshot.details })
|
||||
}
|
||||
;(invoice as Invoice).payment_details = payeeSnapshot.payee
|
||||
if (!hasRequiredInvoicePaymentAccount(company as CompanySettings, invoice as Invoice)) {
|
||||
return errorResponseFromCode('INVOICE_SEND_PAYMENT_ACCOUNT_MISSING', opLog, {
|
||||
requestId,
|
||||
@@ -295,7 +302,7 @@ export const POST = withRouteContext(
|
||||
const preflight = await prepareInvoicePdfRender(
|
||||
company as CompanySettings,
|
||||
(invoice as Invoice).currency,
|
||||
{ paymentAccountRequired },
|
||||
{ paymentAccountRequired, payee: (invoice as Invoice).payment_details ?? null },
|
||||
)
|
||||
await renderToBuffer(
|
||||
InvoicePDF({
|
||||
@@ -360,7 +367,7 @@ export const POST = withRouteContext(
|
||||
const { branding, company: renderCompany } = await prepareInvoicePdfRender(
|
||||
company as CompanySettings,
|
||||
renderableInvoice.currency,
|
||||
{ paymentAccountRequired },
|
||||
{ paymentAccountRequired, payee: (invoice as Invoice).payment_details ?? null },
|
||||
)
|
||||
const swishQrDataUrl = await buildSwishQrDataUrl(renderCompany, renderableInvoice)
|
||||
const paymentLinkQrDataUrl = await buildPaymentLinkQrDataUrl(renderableInvoice)
|
||||
|
||||
@@ -6,9 +6,10 @@ import {
|
||||
makeInvoice,
|
||||
makeCustomer,
|
||||
} from '@/tests/helpers'
|
||||
import { createMockRouteParams } from '@/tests/helpers'
|
||||
import { eventBus } from '@/lib/events'
|
||||
|
||||
const { supabase: mockSupabase, enqueue, reset, findCall } = createQueuedMockSupabase()
|
||||
const { supabase: mockSupabase, enqueue, reset, findCall, findCalls } = createQueuedMockSupabase()
|
||||
vi.mock('@/lib/supabase/server', () => ({
|
||||
createClient: () => Promise.resolve(mockSupabase),
|
||||
}))
|
||||
@@ -158,6 +159,12 @@ describe('GET /api/invoices', () => {
|
||||
const VALID_UUID = '550e8400-e29b-41d4-a716-446655440000'
|
||||
const VALID_UUID_2 = '550e8400-e29b-41d4-a716-446655440001'
|
||||
|
||||
const mockResolveInvoicePayeeChoice = vi.hoisted(() => vi.fn())
|
||||
vi.mock('@/lib/invoices/invoice-payee', () => ({
|
||||
resolveInvoicePayeeChoice: (...args: unknown[]) => mockResolveInvoicePayeeChoice(...args),
|
||||
snapshotInvoicePayee: vi.fn().mockResolvedValue({ ok: true, payee: null }),
|
||||
}))
|
||||
|
||||
describe('POST /api/invoices (create invoice)', () => {
|
||||
const mockUser = { id: 'user-1', email: 'test@test.se' }
|
||||
|
||||
@@ -166,6 +173,40 @@ describe('POST /api/invoices (create invoice)', () => {
|
||||
reset()
|
||||
eventBus.clear()
|
||||
mockSupabase.auth.getUser.mockResolvedValue({ data: { user: mockUser } })
|
||||
mockResolveInvoicePayeeChoice.mockResolvedValue({
|
||||
ok: true,
|
||||
fields: { payment_cash_account_id: null, payment_details: null },
|
||||
})
|
||||
})
|
||||
|
||||
it('returns 400 when the chosen payee account is not usable for the invoice', async () => {
|
||||
enqueue({ data: makeCustomer({ id: VALID_UUID }) })
|
||||
mockResolveInvoicePayeeChoice.mockResolvedValue({
|
||||
ok: false,
|
||||
code: 'INVOICE_PAYEE_ACCOUNT_INVALID',
|
||||
details: { cash_account_id: VALID_UUID_2, currency: 'SEK', reason: 'not_payee' },
|
||||
})
|
||||
mockGetVatRules.mockReturnValue({ treatment: 'standard_25', rate: 25, momsRuta: '10', reverseChargeText: null })
|
||||
mockCalculateVat.mockReturnValue(250)
|
||||
|
||||
const request = createMockRequest('/api/invoices', {
|
||||
method: 'POST',
|
||||
body: {
|
||||
customer_id: VALID_UUID,
|
||||
invoice_date: '2024-06-15',
|
||||
due_date: '2024-07-15',
|
||||
currency: 'SEK',
|
||||
payment_cash_account_id: VALID_UUID_2,
|
||||
items: [{ description: 'Test', quantity: 1, unit: 'st', unit_price: 1000 }],
|
||||
},
|
||||
})
|
||||
const response = await POST(request, createMockRouteParams({}))
|
||||
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(response)
|
||||
|
||||
expect(status).toBe(400)
|
||||
expect(body.error.code).toBe('INVOICE_PAYEE_ACCOUNT_INVALID')
|
||||
expect(mockResolveInvoicePayeeChoice).toHaveBeenCalledWith(expect.anything(), 'company-1', 'SEK', VALID_UUID_2)
|
||||
expect(findCalls('invoices', 'insert')).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('returns 401 when not authenticated', async () => {
|
||||
|
||||
@@ -4,10 +4,11 @@ import { withRouteContext } from '@/lib/api/with-route-context'
|
||||
import { PRIVATE_NO_STORE_HEADERS, privateNoStore } from '@/lib/api/private-no-store'
|
||||
import { InvoicePDF, type InvoicePdfInvoice } from '@/lib/invoices/pdf-template'
|
||||
import { prepareInvoicePdfRender, buildSwishQrDataUrl, buildPaymentLinkQrDataUrl } from '@/lib/invoices/pdf-render-helpers'
|
||||
import { resolveInvoicePayeeChoice } from '@/lib/invoices/invoice-payee'
|
||||
import { getVatRules } from '@/lib/invoices/vat-rules'
|
||||
import { invoicePdfFilename } from '@/lib/invoices/pdf-filename'
|
||||
import { contentDisposition } from '@/lib/api/content-disposition'
|
||||
import type { InvoiceItem, Customer, CompanySettings, InvoiceDocumentType } from '@/types'
|
||||
import type { InvoiceItem, Customer, CompanySettings, Currency, InvoiceDocumentType } from '@/types'
|
||||
import { errorResponseFromCode } from '@/lib/errors/get-structured-error'
|
||||
import { computeDeduction, computeInvoiceDeductionTotal, type DeductionType } from '@/lib/invoices/rot-rut-rules'
|
||||
import { computeLineNet } from '@/lib/invoices/line-amounts'
|
||||
@@ -83,7 +84,7 @@ export const POST = withRouteContext('invoice.preview_pdf', async (request, {
|
||||
const {
|
||||
customer_id, invoice_date, due_date, delivery_date, valid_until, currency, items, your_reference, our_reference,
|
||||
invoice_marking, notes,
|
||||
document_type, invoice_number, payment_link_url,
|
||||
document_type, invoice_number, payment_link_url, payment_cash_account_id,
|
||||
deduction_personnummer, deduction_housing_designation, deduction_apartment_number, deduction_brf_org_number,
|
||||
} = body
|
||||
|
||||
@@ -124,10 +125,24 @@ export const POST = withRouteContext('invoice.preview_pdf', async (request, {
|
||||
)
|
||||
}
|
||||
|
||||
// The chosen bank account (draft not yet saved): same validation as the
|
||||
// create route, so the preview shows what the saved invoice will print.
|
||||
const payeeChoice = await resolveInvoicePayeeChoice(
|
||||
supabase,
|
||||
companyId,
|
||||
requestedCurrency as Currency,
|
||||
typeof payment_cash_account_id === 'string' && payment_cash_account_id ? payment_cash_account_id : null,
|
||||
)
|
||||
if (!payeeChoice.ok) {
|
||||
return privateNoStore(errorResponseFromCode(payeeChoice.code, log, { requestId, details: payeeChoice.details }))
|
||||
}
|
||||
const previewPayee = payeeChoice.fields.payment_details
|
||||
|
||||
if (!hasRequiredInvoicePaymentAccount(company as CompanySettings, {
|
||||
currency: requestedCurrency,
|
||||
document_type: docType,
|
||||
credited_invoice_id: null,
|
||||
payment_details: previewPayee,
|
||||
})) {
|
||||
return privateNoStore(errorResponseFromCode('INVOICE_SEND_PAYMENT_ACCOUNT_MISSING', log, {
|
||||
requestId,
|
||||
@@ -345,7 +360,7 @@ export const POST = withRouteContext('invoice.preview_pdf', async (request, {
|
||||
const { branding, company: renderCompany } = await prepareInvoicePdfRender(
|
||||
company as CompanySettings,
|
||||
previewInvoice.currency,
|
||||
{ paymentAccountRequired: invoiceRequiresPaymentAccount(previewInvoice) },
|
||||
{ paymentAccountRequired: invoiceRequiresPaymentAccount(previewInvoice), payee: previewPayee },
|
||||
)
|
||||
const swishQrDataUrl = await buildSwishQrDataUrl(renderCompany, previewInvoice)
|
||||
const paymentLinkQrDataUrl = await buildPaymentLinkQrDataUrl(previewInvoice)
|
||||
|
||||
@@ -6,6 +6,7 @@ import { CreateInvoiceSchema, CreateCreditNoteSchema } from '@/lib/api/schemas'
|
||||
import type { Invoice, InvoiceDocumentType, InvoiceItem } from '@/types'
|
||||
import { ensureInvoiceNumber } from '@/lib/invoices/ensure-invoice-number'
|
||||
import { buildInvoiceWriteData } from '@/lib/invoices/build-invoice-write'
|
||||
import { resolveInvoicePayeeChoice } from '@/lib/invoices/invoice-payee'
|
||||
import { buildCreditNoteItem } from '@/lib/invoices/build-credit-note-item'
|
||||
import { withRouteContext } from '@/lib/api/with-route-context'
|
||||
import { errorResponse, errorResponseFromCode } from '@/lib/errors/get-structured-error'
|
||||
@@ -117,6 +118,19 @@ export const POST = withRouteContext(
|
||||
})
|
||||
}
|
||||
|
||||
// Which bank account the customer pays to (null = the per-currency
|
||||
// default). Validated against the company's payee accounts; the payee
|
||||
// fields are frozen on the row and refreshed again at issue.
|
||||
const payeeChoice = await resolveInvoicePayeeChoice(
|
||||
supabase,
|
||||
companyId!,
|
||||
invoiceInput.currency,
|
||||
invoiceInput.payment_cash_account_id,
|
||||
)
|
||||
if (!payeeChoice.ok) {
|
||||
return errorResponseFromCode(payeeChoice.code, log, { requestId, details: payeeChoice.details })
|
||||
}
|
||||
|
||||
// Shared validation + computation (VAT rules, accrual guards, totals,
|
||||
// revenue-account override checks, server-side ROT/RUT, currency, item
|
||||
// rows). Identical to the PATCH (draft edit) path: see build-invoice-write.
|
||||
@@ -162,6 +176,8 @@ export const POST = withRouteContext(
|
||||
company_id: companyId,
|
||||
invoice_number: invoiceNumber,
|
||||
...build.invoiceFields,
|
||||
payment_cash_account_id: payeeChoice.fields.payment_cash_account_id,
|
||||
payment_details: payeeChoice.fields.payment_details,
|
||||
})
|
||||
.select()
|
||||
.single()
|
||||
@@ -409,6 +425,10 @@ async function createCreditNote(
|
||||
our_reference: originalInvoice.our_reference,
|
||||
// Same buyer routing on the kreditfaktura as the original.
|
||||
invoice_marking: originalInvoice.invoice_marking ?? null,
|
||||
// Same payee as the original: the credit note refers to the account
|
||||
// the customer paid (or was asked to pay) to.
|
||||
payment_cash_account_id: originalInvoice.payment_cash_account_id ?? null,
|
||||
payment_details: originalInvoice.payment_details ?? null,
|
||||
// Positive magnitude, unlike the negated amounts above: the DB has
|
||||
// CHECK (deduction_total >= 0), and every reader either recomputes the
|
||||
// ROT/RUT amount from the items or skips credit notes entirely.
|
||||
|
||||
@@ -5,6 +5,12 @@ import { createMockRequest, parseJsonResponse, createQueuedMockSupabase } from '
|
||||
const { supabase, enqueue, enqueueMany, reset } = createQueuedMockSupabase()
|
||||
|
||||
const requireAuthMock = vi.fn()
|
||||
// The payee write-through is its own unit (lib/cash-accounts/__tests__/invoice-payee.test.ts);
|
||||
// here it must not consume the queued company_settings results.
|
||||
vi.mock('@/lib/cash-accounts/invoice-payee', () => ({
|
||||
propagateLegacyPayeeWrite: vi.fn().mockResolvedValue(['SEK']),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/auth/require-auth', () => ({
|
||||
requireAuth: (...args: unknown[]) => requireAuthMock(...args),
|
||||
}))
|
||||
|
||||
@@ -11,6 +11,7 @@ import { validateBody } from '@/lib/api/validate'
|
||||
import { UpdateSettingsSchema } from '@/lib/api/schemas'
|
||||
import { getErrorMessage as getUserErrorMessage } from '@/lib/errors/get-error-message'
|
||||
import { errorResponseFromCode } from '@/lib/errors/get-structured-error'
|
||||
import { propagateLegacyPayeeWrite } from '@/lib/cash-accounts/invoice-payee'
|
||||
|
||||
export const GET = withRouteContext(
|
||||
'settings.get',
|
||||
@@ -252,6 +253,20 @@ export const PUT = withRouteContext(
|
||||
)
|
||||
}
|
||||
|
||||
// Payment instructions live on cash_accounts since migration
|
||||
// 20260903150000; the bank columns below are a mirror of the default
|
||||
// payee account per currency. Write the change through to the account
|
||||
// FIRST: if that fails nothing has been written and the caller gets an
|
||||
// error, instead of a settings row that the next mirror would undo.
|
||||
if (changesInvoicePaymentInstructions) {
|
||||
try {
|
||||
await propagateLegacyPayeeWrite(supabase, companyId, body)
|
||||
} catch (err) {
|
||||
log.error('failed to write payment instructions through to cash accounts', err as Error)
|
||||
return NextResponse.json({ error: getUserErrorMessage(err) }, { status: 500 })
|
||||
}
|
||||
}
|
||||
|
||||
const { data, error } = await supabase
|
||||
.from('company_settings')
|
||||
.update(body)
|
||||
@@ -266,6 +281,7 @@ export const PUT = withRouteContext(
|
||||
return NextResponse.json({ error: getUserErrorMessage(error) }, { status: 500 })
|
||||
}
|
||||
|
||||
|
||||
// Regenerate when the save touches tax-relevant fields: the statutory
|
||||
// dates are derived from them, and re-running also repairs rows created
|
||||
// by older schedule logic or lost to an earlier generation failure. The
|
||||
|
||||
@@ -37,6 +37,7 @@ import {
|
||||
createInvoiceCashEntry,
|
||||
createInvoicePaymentJournalEntry,
|
||||
} from '@/lib/bookkeeping/invoice-entries'
|
||||
import { resolveInvoiceSettlementAccount } from '@/lib/invoices/invoice-payee'
|
||||
import { createJournalEntry, findFiscalPeriod } from '@/lib/bookkeeping/engine'
|
||||
import { cashPartialBlockReason } from '@/lib/bookkeeping/booking-mode'
|
||||
import { cancelOrphanedPaymentEntry } from '@/lib/bookkeeping/cancel-orphaned-entry'
|
||||
@@ -58,7 +59,7 @@ import type { CreateJournalEntryInput, EntityType, Invoice } from '@/types'
|
||||
// payment/cash JE generators, which re-propagate the bag onto every leg —
|
||||
// dropping the column here silently untags the payment voucher.
|
||||
const INVOICE_MARK_PAID_RESPONSE_COLUMNS =
|
||||
'id, invoice_number, customer_id, invoice_date, due_date, delivery_date, status, currency, exchange_rate, exchange_rate_date, subtotal, subtotal_sek, vat_amount, vat_amount_sek, total, total_sek, vat_treatment, vat_rate, moms_ruta, your_reference, our_reference, notes, reverse_charge_text, credited_invoice_id, document_type, converted_from_id, paid_at, paid_amount, remaining_amount, default_dimensions, created_at, updated_at'
|
||||
'id, invoice_number, customer_id, invoice_date, due_date, delivery_date, status, currency, exchange_rate, exchange_rate_date, subtotal, subtotal_sek, vat_amount, vat_amount_sek, total, total_sek, vat_treatment, vat_rate, moms_ruta, your_reference, our_reference, notes, reverse_charge_text, credited_invoice_id, document_type, converted_from_id, paid_at, paid_amount, remaining_amount, default_dimensions, payment_cash_account_id, created_at, updated_at'
|
||||
|
||||
const InvoiceMarkPaidResponse = z.object({
|
||||
id: z.string().uuid(),
|
||||
@@ -490,6 +491,7 @@ export const POST = withApiV1<{ params: Promise<{ companyId: string; id: string
|
||||
)
|
||||
journalEntryId = entry?.id ?? null
|
||||
} else if (useCashEntry) {
|
||||
const settlementAccountNumber = await resolveInvoiceSettlementAccount(ctx.supabase, ctx.companyId!, typed)
|
||||
const entry = await createInvoiceCashEntry(
|
||||
ctx.supabase,
|
||||
ctx.companyId!,
|
||||
@@ -498,9 +500,11 @@ export const POST = withApiV1<{ params: Promise<{ companyId: string; id: string
|
||||
paymentDate,
|
||||
entityType,
|
||||
typed.customer?.name,
|
||||
settlementAccountNumber,
|
||||
)
|
||||
journalEntryId = entry?.id ?? null
|
||||
} else {
|
||||
const settlementAccountNumber = await resolveInvoiceSettlementAccount(ctx.supabase, ctx.companyId!, typed)
|
||||
const entry = await createInvoicePaymentJournalEntry(
|
||||
ctx.supabase,
|
||||
ctx.companyId!,
|
||||
@@ -511,6 +515,7 @@ export const POST = withApiV1<{ params: Promise<{ companyId: string; id: string
|
||||
typed.customer?.name,
|
||||
// Pass full or partial amount depending on path.
|
||||
customLines ? paymentAmount : undefined,
|
||||
settlementAccountNumber,
|
||||
)
|
||||
journalEntryId = entry?.id ?? null
|
||||
}
|
||||
|
||||
@@ -51,6 +51,7 @@ import { recordManualInvoiceDelivery } from '@/lib/invoices/invoice-deliveries'
|
||||
import {
|
||||
hasRequiredInvoicePaymentAccount,
|
||||
} from '@/lib/invoices/payment-accounts'
|
||||
import { snapshotInvoicePayee } from '@/lib/invoices/invoice-payee'
|
||||
import { hasRequiredSellerVatNumber } from '@/lib/invoices/seller-vat-number'
|
||||
import { eventBus } from '@/lib/events'
|
||||
import type { CompanySettings, EntityType, Invoice } from '@/types'
|
||||
@@ -60,7 +61,7 @@ import type { CompanySettings, EntityType, Invoice } from '@/types'
|
||||
// createInvoiceJournalEntry, which reads the bag off the row: dropping the
|
||||
// column here silently untags the revenue JE lines.
|
||||
const INVOICE_MARK_SENT_RESPONSE_COLUMNS =
|
||||
'id, invoice_number, customer_id, invoice_date, due_date, delivery_date, status, currency, exchange_rate, exchange_rate_date, subtotal, subtotal_sek, vat_amount, vat_amount_sek, total, total_sek, vat_treatment, vat_rate, moms_ruta, your_reference, our_reference, notes, reverse_charge_text, credited_invoice_id, document_type, converted_from_id, paid_at, paid_amount, remaining_amount, default_dimensions, created_at, updated_at'
|
||||
'id, invoice_number, customer_id, invoice_date, due_date, delivery_date, status, currency, exchange_rate, exchange_rate_date, subtotal, subtotal_sek, vat_amount, vat_amount_sek, total, total_sek, vat_treatment, vat_rate, moms_ruta, your_reference, our_reference, notes, reverse_charge_text, credited_invoice_id, document_type, converted_from_id, paid_at, paid_amount, remaining_amount, default_dimensions, payment_cash_account_id, payment_details, created_at, updated_at'
|
||||
|
||||
const InvoiceMarkSentResponse = z.object({
|
||||
id: z.string().uuid(),
|
||||
@@ -233,6 +234,15 @@ export const POST = withApiV1<{ params: Promise<{ companyId: string; id: string
|
||||
})
|
||||
}
|
||||
const companySettings = settings as CompanySettings
|
||||
// Freeze the chosen bank account's payee at issue (no-op without a choice).
|
||||
const payeeSnapshot = await snapshotInvoicePayee(ctx.supabase, ctx.companyId!, typed, { persist: !ctx.dryRun })
|
||||
if (!payeeSnapshot.ok) {
|
||||
return v1ErrorResponseFromCode(payeeSnapshot.code, ctx.log, {
|
||||
requestId: ctx.requestId,
|
||||
details: payeeSnapshot.details,
|
||||
})
|
||||
}
|
||||
typed.payment_details = payeeSnapshot.payee
|
||||
if (!hasRequiredInvoicePaymentAccount(companySettings, typed)) {
|
||||
return v1ErrorResponseFromCode('INVOICE_SEND_PAYMENT_ACCOUNT_MISSING', ctx.log, {
|
||||
requestId: ctx.requestId,
|
||||
|
||||
@@ -165,7 +165,7 @@ export const GET = withApiV1<{ params: Promise<{ companyId: string; id: string }
|
||||
const { branding, company: renderCompany } = await prepareInvoicePdfRender(
|
||||
company as CompanySettings,
|
||||
typed.currency,
|
||||
{ paymentAccountRequired: invoiceRequiresPaymentAccount(typed) },
|
||||
{ paymentAccountRequired: invoiceRequiresPaymentAccount(typed), payee: typed.payment_details ?? null },
|
||||
)
|
||||
const swishQrDataUrl = await buildSwishQrDataUrl(renderCompany, typed as Invoice)
|
||||
pdfBuffer = await renderToBuffer(
|
||||
|
||||
@@ -38,6 +38,7 @@ import { isEditableInvoiceDraft } from '@/lib/invoices/is-editable-draft'
|
||||
import { effectiveQuoteStatus } from '@/lib/invoices/quote-status'
|
||||
import { deleteDraftInvoice } from '@/lib/invoices/delete-draft-invoice'
|
||||
import { replaceInvoiceItems } from '@/lib/invoices/replace-invoice-items'
|
||||
import { resolveInvoicePayeeChoice } from '@/lib/invoices/invoice-payee'
|
||||
import type { Currency, Customer, InvoiceDocumentType } from '@/types'
|
||||
|
||||
// Allowed PATCH fields for a draft invoice. Excludes customer_id / currency /
|
||||
@@ -58,6 +59,10 @@ const V1PatchDraftInvoiceSchema = z.object({
|
||||
// Send {} to clear all tags. Codes are validated against the dimension
|
||||
// registry when the invoice posts at :send, not here.
|
||||
default_dimensions: DimensionsBagSchema.optional(),
|
||||
// Which of the company's bank accounts the invoice asks the customer to
|
||||
// pay to. null = back to the per-currency default. Must be one of the
|
||||
// company's payee accounts, usable for the invoice currency.
|
||||
payment_cash_account_id: z.union([z.string().uuid(), z.null()]).optional(),
|
||||
// FULL REPLACE when present. Same item shape as POST /invoices (article
|
||||
// linkage, ROT/RUT lines, accrual periods, per-line dimensions included).
|
||||
items: z.array(CreateInvoiceItemSchema).min(1, 'At least one item is required').optional(),
|
||||
@@ -291,7 +296,7 @@ export const PATCH = withApiV1<{ params: Promise<{ companyId: string; id: string
|
||||
if (body[key] !== undefined) updateData[key] = body[key]
|
||||
}
|
||||
|
||||
if (Object.keys(updateData).length === 0 && !body.items) {
|
||||
if (Object.keys(updateData).length === 0 && body.payment_cash_account_id === undefined && !body.items) {
|
||||
return v1ErrorResponseFromCode('VALIDATION_ERROR', ctx.log, {
|
||||
requestId: ctx.requestId,
|
||||
details: { field: 'body', message: 'At least one field must be supplied for update.' },
|
||||
@@ -318,6 +323,25 @@ export const PATCH = withApiV1<{ params: Promise<{ companyId: string; id: string
|
||||
details: { resource: 'invoice' },
|
||||
})
|
||||
}
|
||||
// Payee choice (null = back to the per-currency default): validated
|
||||
// against the company's payee accounts for the invoice's own currency.
|
||||
if (body.payment_cash_account_id !== undefined) {
|
||||
const payeeChoice = await resolveInvoicePayeeChoice(
|
||||
ctx.supabase,
|
||||
ctx.companyId!,
|
||||
(current as { currency: Currency }).currency,
|
||||
body.payment_cash_account_id,
|
||||
)
|
||||
if (!payeeChoice.ok) {
|
||||
return v1ErrorResponseFromCode(payeeChoice.code, ctx.log, {
|
||||
requestId: ctx.requestId,
|
||||
details: payeeChoice.details,
|
||||
})
|
||||
}
|
||||
updateData.payment_cash_account_id = payeeChoice.fields.payment_cash_account_id
|
||||
updateData.payment_details = payeeChoice.fields.payment_details
|
||||
}
|
||||
|
||||
// Shared predicate with the dashboard PATCH: draft, no verifikat, not a
|
||||
// received self-billing document, not a credit-note draft, and for a
|
||||
// quote not accepted or declined (a recorded decision must be reopened
|
||||
|
||||
@@ -48,6 +48,7 @@ import { withApiV1 } from '@/lib/api/v1/with-api-v1'
|
||||
import { v1ErrorResponse, v1ErrorResponseFromCode, v1ValidationError } from '@/lib/api/v1/errors'
|
||||
import { InvoicePDF } from '@/lib/invoices/pdf-template'
|
||||
import { prepareInvoicePdfRender, buildSwishQrDataUrl, buildPaymentLinkQrDataUrl } from '@/lib/invoices/pdf-render-helpers'
|
||||
import { snapshotInvoicePayee } from '@/lib/invoices/invoice-payee'
|
||||
import { applyPaymentLinkToInvoice } from '@/lib/extensions/payment-links'
|
||||
import { getEmailService } from '@/lib/email/service'
|
||||
import { resolveInvoiceSender } from '@/lib/email/invoice-sender'
|
||||
@@ -341,6 +342,15 @@ export const POST = withApiV1<{ params: Promise<{ companyId: string; id: string
|
||||
}
|
||||
const settings = company as CompanySettings & { accounting_method?: string }
|
||||
const paymentAccountRequired = invoiceRequiresPaymentAccount(typed)
|
||||
// Freeze the chosen bank account's payee at issue (no-op without a choice).
|
||||
const payeeSnapshot = await snapshotInvoicePayee(ctx.supabase, ctx.companyId!, typed, { persist: !ctx.dryRun })
|
||||
if (!payeeSnapshot.ok) {
|
||||
return v1ErrorResponseFromCode(payeeSnapshot.code, ctx.log, {
|
||||
requestId: ctx.requestId,
|
||||
details: payeeSnapshot.details,
|
||||
})
|
||||
}
|
||||
typed.payment_details = payeeSnapshot.payee
|
||||
if (!hasRequiredInvoicePaymentAccount(settings, typed)) {
|
||||
return v1ErrorResponseFromCode('INVOICE_SEND_PAYMENT_ACCOUNT_MISSING', ctx.log, {
|
||||
requestId: ctx.requestId,
|
||||
@@ -426,6 +436,7 @@ export const POST = withApiV1<{ params: Promise<{ companyId: string; id: string
|
||||
try {
|
||||
const preflight = await prepareInvoicePdfRender(settings, typed.currency, {
|
||||
paymentAccountRequired,
|
||||
payee: typed.payment_details ?? null,
|
||||
})
|
||||
await renderToBuffer(
|
||||
InvoicePDF({
|
||||
@@ -561,7 +572,7 @@ export const POST = withApiV1<{ params: Promise<{ companyId: string; id: string
|
||||
const { branding, company: renderCompany } = await prepareInvoicePdfRender(
|
||||
settings,
|
||||
renderableInvoice.currency,
|
||||
{ paymentAccountRequired },
|
||||
{ paymentAccountRequired, payee: typed.payment_details ?? null },
|
||||
)
|
||||
const swishQrDataUrl = await buildSwishQrDataUrl(renderCompany, renderableInvoice)
|
||||
const paymentLinkQrDataUrl = await buildPaymentLinkQrDataUrl(renderableInvoice)
|
||||
|
||||
@@ -30,6 +30,7 @@ import { readV1JsonBody } from '@/lib/api/v1/body'
|
||||
import { CreateInvoiceSchema } from '@/lib/api/schemas'
|
||||
import { INVOICE_FULL_COLUMNS, INVOICE_ITEM_FULL_COLUMNS } from '@/lib/api/v1/invoice-columns'
|
||||
import { buildInvoiceWriteData } from '@/lib/invoices/build-invoice-write'
|
||||
import { resolveInvoicePayeeChoice } from '@/lib/invoices/invoice-payee'
|
||||
import { effectiveQuoteStatus } from '@/lib/invoices/quote-status'
|
||||
import {
|
||||
resolveSelfBilledSaleDraft,
|
||||
@@ -626,6 +627,19 @@ export const POST = withApiV1<{ params: Promise<{ companyId: string }> }>(
|
||||
}
|
||||
const { invoiceFields, items: itemRows } = build
|
||||
|
||||
const payeeChoice = await resolveInvoicePayeeChoice(
|
||||
ctx.supabase,
|
||||
ctx.companyId!,
|
||||
input.currency,
|
||||
input.payment_cash_account_id,
|
||||
)
|
||||
if (!payeeChoice.ok) {
|
||||
return v1ErrorResponseFromCode(payeeChoice.code, ctx.log, {
|
||||
requestId: ctx.requestId,
|
||||
details: payeeChoice.details,
|
||||
})
|
||||
}
|
||||
|
||||
// Dry-run: validation-only preview. Drafts have no journal-entry side
|
||||
// effects yet, so no pending_operations staging needed; a staged
|
||||
// preview variant belongs to :send.
|
||||
@@ -639,6 +653,8 @@ export const POST = withApiV1<{ params: Promise<{ companyId: string }> }>(
|
||||
invoice_number: null,
|
||||
status: 'draft' as const,
|
||||
...previewFields,
|
||||
payment_cash_account_id: payeeChoice.fields.payment_cash_account_id,
|
||||
payment_details: payeeChoice.fields.payment_details,
|
||||
items: itemRows,
|
||||
},
|
||||
{ requestId: ctx.requestId, log: ctx.log },
|
||||
@@ -677,6 +693,8 @@ export const POST = withApiV1<{ params: Promise<{ companyId: string }> }>(
|
||||
company_id: ctx.companyId!,
|
||||
invoice_number: invoiceNumber,
|
||||
...invoiceFields,
|
||||
payment_cash_account_id: payeeChoice.fields.payment_cash_account_id,
|
||||
payment_details: payeeChoice.fields.payment_details,
|
||||
})
|
||||
.select(INVOICE_RESPONSE_COLUMNS)
|
||||
.single()
|
||||
|
||||
@@ -30,6 +30,7 @@ import { v1ErrorResponse, v1ErrorResponseFromCode } from '@/lib/api/v1/errors'
|
||||
import { readV1JsonBody } from '@/lib/api/v1/body'
|
||||
import { InvoiceEmailTextsSchema, UpdateSettingsSchema } from '@/lib/api/schemas'
|
||||
import { UpdateCompanySettingsParamsSchema } from '@/lib/pending-operations/schemas/company-settings'
|
||||
import { propagateLegacyPayeeWrite } from '@/lib/cash-accounts/invoice-payee'
|
||||
|
||||
// Flat body keys copied into the update payload verbatim. Mirrors the MCP
|
||||
// tool gnubok_update_company_settings field for field; contact_person is
|
||||
@@ -285,6 +286,16 @@ export const PATCH = withApiV1<{ params: Promise<{ companyId: string }> }>(
|
||||
// statically verify every column name. Fields the caller did not supply
|
||||
// are `undefined` here and are dropped by supabase-js JSON serialization,
|
||||
// so only supplied fields are written; explicit null still clears.
|
||||
// The bank columns mirror the default SEK payee account (migration
|
||||
// 20260903150000): write the change through to it FIRST so a failure
|
||||
// leaves nothing half-written, and the PDF prints what this call set.
|
||||
try {
|
||||
await propagateLegacyPayeeWrite(ctx.supabase, ctx.companyId!, changes)
|
||||
} catch (err) {
|
||||
ctx.log.error('companies.settings.update: payee write-through failed', err as Error)
|
||||
return v1ErrorResponse(err, ctx.log, { requestId: ctx.requestId })
|
||||
}
|
||||
|
||||
const { data, error } = await ctx.supabase
|
||||
.from('company_settings')
|
||||
.update({
|
||||
@@ -309,6 +320,7 @@ export const PATCH = withApiV1<{ params: Promise<{ companyId: string }> }>(
|
||||
if (error) {
|
||||
return v1ErrorResponse(error, ctx.log, { requestId: ctx.requestId })
|
||||
}
|
||||
|
||||
if (!data) {
|
||||
ctx.log.warn('companies.settings.update: settings row not found', {
|
||||
companyId: ctx.companyId,
|
||||
|
||||
@@ -84,6 +84,7 @@ import AccountCombobox from '@/components/bookkeeping/AccountCombobox'
|
||||
import LineDimensionFields from '@/components/dimensions/LineDimensionFields'
|
||||
import { DEFAULT_DEFERRED_REVENUE_ACCOUNT } from '@/lib/bookkeeping/accruals/account-suggestions'
|
||||
import { countCalendarMonths } from '@/lib/bookkeeping/accruals/compute'
|
||||
import { isUsableInvoicePayee } from '@/lib/cash-accounts/invoice-payee'
|
||||
import type { InvoiceCopyInitial } from '@/lib/invoices/copy-invoice'
|
||||
import { INVOICE_POSTING_ACCOUNT_REGEX } from '@/lib/invoices/posting-account'
|
||||
import {
|
||||
@@ -91,7 +92,17 @@ import {
|
||||
buildSelfBilledPayload,
|
||||
hasDimensionValues,
|
||||
} from '@/lib/invoices/editor-payload'
|
||||
import type { Customer, Currency, CreateCustomerInput, InvoiceDocumentType, Article, Invoice, InvoiceItem } from '@/types'
|
||||
import type {
|
||||
Article,
|
||||
CashAccount,
|
||||
CreateCustomerInput,
|
||||
Currency,
|
||||
Customer,
|
||||
Invoice,
|
||||
InvoiceDocumentType,
|
||||
InvoiceItem,
|
||||
InvoicePayeeDefault,
|
||||
} from '@/types'
|
||||
|
||||
const currencies: Currency[] = ['SEK', 'EUR', 'USD', 'GBP', 'NOK', 'DKK']
|
||||
const units = ['st', 'tim', 'dag', 'månad', 'km', 'kg']
|
||||
@@ -156,6 +167,16 @@ const CELL_SELECT_TRIGGER_CLASS =
|
||||
const SETTINGS_ROW_CLASS =
|
||||
'flex items-center justify-between gap-4 border-b border-border py-3 text-[13px]'
|
||||
|
||||
// Sentinel for "the company default" in the payee select: an empty option
|
||||
// value renders as the placeholder in Radix Select.
|
||||
const PAYEE_DEFAULT = '__default__'
|
||||
|
||||
/** "Företagskonto (1930)" or the bare ledger account when the row has no name. */
|
||||
function payeeAccountLabel(account: CashAccount): string {
|
||||
const name = account.name?.trim()
|
||||
return name ? `${name} (${account.ledger_account})` : account.ledger_account
|
||||
}
|
||||
|
||||
// Compact display of a dimensions bag, e.g. "KS01 · P001" (dim-number order).
|
||||
function compactDims(dims: Record<string, string>): string {
|
||||
return Object.entries(dims)
|
||||
@@ -363,6 +384,8 @@ export default function InvoiceEditor(props: InvoiceEditorProps = { mode: 'creat
|
||||
valid_until: z.string().optional(),
|
||||
delivery_date: z.string().optional(),
|
||||
currency: z.enum(['SEK', 'EUR', 'USD', 'GBP', 'NOK', 'DKK']),
|
||||
// Bank account the customer pays to; '' = the company default per currency.
|
||||
payment_cash_account_id: z.string().optional(),
|
||||
document_type: z.enum(['invoice', 'proforma', 'delivery_note', 'quote']),
|
||||
your_reference: z.string().optional(),
|
||||
our_reference: z.string().optional(),
|
||||
@@ -563,6 +586,7 @@ export default function InvoiceEditor(props: InvoiceEditorProps = { mode: 'creat
|
||||
initial.document_type === 'quote' ? initial.valid_until ?? initial.due_date : '',
|
||||
delivery_date: initial.delivery_date ?? '',
|
||||
currency: initial.currency,
|
||||
payment_cash_account_id: initial.payment_cash_account_id ?? '',
|
||||
document_type: (initial.document_type ?? 'invoice') as InvoiceDocumentType,
|
||||
your_reference: initial.your_reference ?? '',
|
||||
our_reference: initial.our_reference ?? '',
|
||||
@@ -606,6 +630,7 @@ export default function InvoiceEditor(props: InvoiceEditorProps = { mode: 'creat
|
||||
valid_until: '',
|
||||
delivery_date: '',
|
||||
currency: copyInitial.currency,
|
||||
payment_cash_account_id: copyInitial.payment_cash_account_id ?? '',
|
||||
document_type: 'invoice' as InvoiceDocumentType,
|
||||
your_reference: '',
|
||||
our_reference: copyInitial.our_reference,
|
||||
@@ -626,6 +651,7 @@ export default function InvoiceEditor(props: InvoiceEditorProps = { mode: 'creat
|
||||
due_date: '',
|
||||
valid_until: '',
|
||||
currency: 'SEK',
|
||||
payment_cash_account_id: '',
|
||||
document_type: createDocumentType,
|
||||
payment_link_url: '',
|
||||
payment_link_auto: true,
|
||||
@@ -670,6 +696,41 @@ export default function InvoiceEditor(props: InvoiceEditorProps = { mode: 'creat
|
||||
|
||||
const watchItems = watch('items')
|
||||
const watchCurrency = watch('currency')
|
||||
const watchPayeeAccount = watch('payment_cash_account_id')
|
||||
// The company's bank accounts that may be printed as payee, and the default
|
||||
// per currency. Loaded once; the select only renders when there is a real
|
||||
// choice (two or more usable accounts for the invoice currency).
|
||||
const [payeeState, setPayeeState] = useState<{ accounts: CashAccount[]; defaults: InvoicePayeeDefault[] } | null>(null)
|
||||
useEffect(() => {
|
||||
let cancelled = false
|
||||
fetch('/api/cash-accounts/payee-defaults')
|
||||
.then((res) => (res.ok ? res.json() : null))
|
||||
.then((json) => {
|
||||
if (!cancelled && json?.data) setPayeeState(json.data)
|
||||
})
|
||||
.catch(() => {
|
||||
// Best-effort: without the list the invoice simply uses the default.
|
||||
})
|
||||
return () => {
|
||||
cancelled = true
|
||||
}
|
||||
}, [])
|
||||
const payeeOptions = useMemo(
|
||||
() => (payeeState ? payeeState.accounts.filter((a) => isUsableInvoicePayee(a, watchCurrency as Currency)) : []),
|
||||
[payeeState, watchCurrency],
|
||||
)
|
||||
const defaultPayee = useMemo(() => {
|
||||
const id = payeeState?.defaults.find((d) => d.currency === watchCurrency)?.cash_account_id
|
||||
return id ? payeeState?.accounts.find((a) => a.id === id) ?? null : null
|
||||
}, [payeeState, watchCurrency])
|
||||
// A currency change can make the chosen account unusable (no IBAN for
|
||||
// EUR): fall back to the default rather than submit an invalid choice.
|
||||
useEffect(() => {
|
||||
if (!payeeState || !watchPayeeAccount) return
|
||||
if (!payeeOptions.some((a) => a.id === watchPayeeAccount)) {
|
||||
setValue('payment_cash_account_id', '', { shouldDirty: true })
|
||||
}
|
||||
}, [payeeState, payeeOptions, watchPayeeAccount, setValue])
|
||||
const watchCustomerId = watch('customer_id')
|
||||
const watchDocumentType = watch('document_type') as InvoiceDocumentType
|
||||
// Subscribed at render level so the Förval chip line and the next-step line
|
||||
@@ -1842,6 +1903,7 @@ export default function InvoiceEditor(props: InvoiceEditorProps = { mode: 'creat
|
||||
invoice_marking: data.invoice_marking,
|
||||
notes: data.notes,
|
||||
payment_link_url: data.payment_link_url,
|
||||
payment_cash_account_id: data.payment_cash_account_id || null,
|
||||
invoice_number: numberPreview,
|
||||
// ROT/RUT claim card: the preview shows the same masked personnummer
|
||||
// and fastighetsbeteckning in its deduction box as the created
|
||||
@@ -3020,6 +3082,41 @@ export default function InvoiceEditor(props: InvoiceEditorProps = { mode: 'creat
|
||||
/>
|
||||
</div>
|
||||
|
||||
{!isSelfBilled
|
||||
&& (watchDocumentType === 'invoice' || watchDocumentType === 'proforma')
|
||||
&& payeeState
|
||||
&& (payeeOptions.length > 1 || (payeeOptions.length === 1 && !defaultPayee) || (watchPayeeAccount && payeeOptions.length > 0)) && (
|
||||
<div className={SETTINGS_ROW_CLASS}>
|
||||
<Label className="text-[13px] font-normal">{t('payee_account_label')}</Label>
|
||||
<Controller
|
||||
name="payment_cash_account_id"
|
||||
control={control}
|
||||
render={({ field }) => (
|
||||
<Select
|
||||
value={field.value || PAYEE_DEFAULT}
|
||||
onValueChange={(value) => field.onChange(value === PAYEE_DEFAULT ? '' : value)}
|
||||
>
|
||||
<SelectTrigger className="h-8 w-64 text-[13px]">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value={PAYEE_DEFAULT}>
|
||||
{defaultPayee
|
||||
? t('payee_account_default', { account: payeeAccountLabel(defaultPayee) })
|
||||
: t('payee_account_default_none')}
|
||||
</SelectItem>
|
||||
{payeeOptions.map((account) => (
|
||||
<SelectItem key={account.id} value={account.id}>
|
||||
{payeeAccountLabel(account)}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Self-billed mode renders fakturadatum and mottagningsdatum
|
||||
uncollapsed next to the external number instead: they are
|
||||
transcription fields there, and registering the same RHF
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
'use client'
|
||||
|
||||
import { useState, useEffect, useMemo } from 'react'
|
||||
import { useAccounts, useCompanySettings } from '@/lib/reference-data/hooks'
|
||||
import { useAccounts, useCashAccounts, useCompanySettings } from '@/lib/reference-data/hooks'
|
||||
import { useRouter } from 'next/navigation'
|
||||
import { useTranslations } from 'next-intl'
|
||||
import {
|
||||
@@ -95,6 +95,13 @@ export default function PaymentBookingDialog({
|
||||
// debit, accrual against a 1510 credit.
|
||||
const accountingMethod: 'accrual' | 'cash' =
|
||||
companySettings?.accounting_method === 'cash' ? 'cash' : 'accrual'
|
||||
// The bank account the invoice asked to be paid to (1930 when none was
|
||||
// chosen): the proposed debit lands there, same as the route's default.
|
||||
const { cashAccounts, isLoading: cashAccountsLoading } = useCashAccounts()
|
||||
const chosenPaymentAccount = useMemo(() => {
|
||||
const id = (invoice as { payment_cash_account_id?: string | null }).payment_cash_account_id
|
||||
return id ? cashAccounts.find((a) => a.id === id)?.ledger_account ?? undefined : undefined
|
||||
}, [cashAccounts, invoice])
|
||||
// source_type the booking will use: drives the voucher-series preview so the
|
||||
// number shown matches what mark-paid will actually create.
|
||||
const [sourceType, setSourceType] =
|
||||
@@ -114,7 +121,7 @@ export default function PaymentBookingDialog({
|
||||
|
||||
// Reference data still loading (no seed, first mount of the session):
|
||||
// the effect re-runs once it lands.
|
||||
if (accountsLoading || settingsLoading) return
|
||||
if (accountsLoading || settingsLoading || cashAccountsLoading) return
|
||||
|
||||
let cancelled = false
|
||||
|
||||
@@ -167,6 +174,7 @@ export default function PaymentBookingDialog({
|
||||
},
|
||||
accountingMethod,
|
||||
entityType,
|
||||
paymentAccount: chosenPaymentAccount,
|
||||
companyOreRounding:
|
||||
typeof settings?.ore_rounding === 'boolean' ? settings.ore_rounding : undefined,
|
||||
})
|
||||
@@ -191,7 +199,7 @@ export default function PaymentBookingDialog({
|
||||
// background revalidation of the settings row must not re-run init()
|
||||
// (and reset the user's lines) mid-dialog.
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [open, invoice.id, company?.id, accountsLoading, settingsLoading, accountsError, settingsError])
|
||||
}, [open, invoice.id, company?.id, accountsLoading, settingsLoading, cashAccountsLoading, chosenPaymentAccount, accountsError, settingsError])
|
||||
|
||||
// Voucher-series preview: resolve the upcoming serie + nummer the same way the
|
||||
// booking engine will, so a misconfigured series is visible before confirming.
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1443,6 +1443,7 @@ export const enableBankingExtension: Extension = {
|
||||
currency: a.currency,
|
||||
ledger_account: ledgerAccount,
|
||||
iban: a.iban ?? null,
|
||||
bban: a.bban ?? null,
|
||||
name: a.name ?? null,
|
||||
balance: a.balance ?? null,
|
||||
available_balance: a.available_balance ?? null,
|
||||
|
||||
@@ -20,6 +20,7 @@ import {
|
||||
getAllTransactionsWithRaw,
|
||||
AspspUnavailableError,
|
||||
convertTransaction,
|
||||
extractBban,
|
||||
deleteSession,
|
||||
probeSessionHealth,
|
||||
startAuthorization,
|
||||
@@ -734,6 +735,65 @@ describe('convertTransaction', () => {
|
||||
expect(out.bank_transaction_code).toBe('PMNT/RCDT')
|
||||
expect(out.proprietary_bank_transaction_code).toBe('XB')
|
||||
})
|
||||
|
||||
// Enable Banking has no `bban` key on AccountIdentification: a Swedish
|
||||
// BBAN arrives as other.identification with scheme_name BBAN. The earlier
|
||||
// `.bban` read was always undefined, so domestic counterparties were lost.
|
||||
it('reads a Swedish BBAN counterparty from other.identification', () => {
|
||||
const tx = makeTx({
|
||||
credit_debit_indicator: 'CRDT',
|
||||
debtor_account: { other: { identification: '50001234567', scheme_name: 'BBAN' } },
|
||||
})
|
||||
expect(convertTransaction(tx, 'SEK').counterparty_account).toBe('50001234567')
|
||||
})
|
||||
|
||||
it('prefers IBAN over a domestic identifier, and a Bankgiro from the additional list over nothing', () => {
|
||||
const withIban = makeTx({
|
||||
creditor_account: { iban: 'SE4550000000058398257466', other: { identification: '1234567', scheme_name: 'BGNR' } },
|
||||
})
|
||||
expect(convertTransaction(withIban, 'SEK').counterparty_account).toBe('SE4550000000058398257466')
|
||||
|
||||
const bgOnly = makeTx({
|
||||
creditor_account_additional_identification: [{ identification: '5050-1234', scheme_name: 'BGNR' }],
|
||||
})
|
||||
expect(convertTransaction(bgOnly, 'SEK').counterparty_account).toBe('5050-1234')
|
||||
})
|
||||
|
||||
it('takes a supplementary IBAN over a primary BBAN, and never persists a card PAN or other non-account scheme', () => {
|
||||
const bbanWithIban = makeTx({
|
||||
creditor_account: { other: { identification: '50001234567', scheme_name: 'BBAN' } },
|
||||
creditor_account_additional_identification: [{ identification: 'SE4550000000058398257466', scheme_name: 'IBAN' }],
|
||||
})
|
||||
expect(convertTransaction(bbanWithIban, 'SEK').counterparty_account).toBe('SE4550000000058398257466')
|
||||
|
||||
const cardOnly = makeTx({
|
||||
creditor_account: { other: { identification: '4571********1234', scheme_name: 'CPAN' } },
|
||||
creditor_account_additional_identification: [{ identification: '12345', scheme_name: 'CUST' }],
|
||||
})
|
||||
expect(convertTransaction(cardOnly, 'SEK').counterparty_account).toBeUndefined()
|
||||
})
|
||||
})
|
||||
|
||||
describe('extractBban', () => {
|
||||
it('returns the primary BBAN without whitespace', () => {
|
||||
expect(extractBban({ account_id: { other: { identification: '5000 1234567', scheme_name: 'BBAN' } } }))
|
||||
.toBe('50001234567')
|
||||
})
|
||||
|
||||
it('falls back to all_account_ids when the primary identifier is an IBAN', () => {
|
||||
expect(extractBban({
|
||||
account_id: { iban: 'SE4550000000058398257466' },
|
||||
all_account_ids: [
|
||||
{ identification: 'SE4550000000058398257466', scheme_name: 'IBAN' },
|
||||
{ identification: '50001234567', scheme_name: 'BBAN' },
|
||||
],
|
||||
})).toBe('50001234567')
|
||||
})
|
||||
|
||||
it('is undefined when the ASPSP sent no BBAN', () => {
|
||||
expect(extractBban({ account_id: { iban: 'SE4550000000058398257466' } })).toBeUndefined()
|
||||
expect(extractBban({ account_id: { other: { identification: '1234567', scheme_name: 'BGNR' } } })).toBeUndefined()
|
||||
})
|
||||
})
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
@@ -73,19 +73,86 @@ export interface SessionResponse {
|
||||
status?: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Enable Banking GenericIdentification (OpenAPI 1.0.0). `scheme_name` is the
|
||||
* SchemeName enum: BBAN, IBAN, BGNR (Swedish Bankgiro), PGNR (Swedish
|
||||
* Plusgiro), CPAN, MIBN, ... For Swedish ASPSPs a BBAN is the bank clearing
|
||||
* number followed by the account number, no separator.
|
||||
*/
|
||||
export interface GenericIdentification {
|
||||
identification: string
|
||||
scheme_name: string
|
||||
issuer?: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Enable Banking AccountIdentification. There is NO top-level `bban` key in
|
||||
* the API: a BBAN arrives as `other.identification` with
|
||||
* `other.scheme_name = 'BBAN'`. Earlier versions of this client typed
|
||||
* `bban?: string` here and therefore never captured the Swedish clearing +
|
||||
* account number for any connected account.
|
||||
*/
|
||||
export interface AccountIdentification {
|
||||
iban?: string
|
||||
other?: GenericIdentification
|
||||
}
|
||||
|
||||
export interface AccountInfo {
|
||||
uid: string
|
||||
account_id?: {
|
||||
iban?: string
|
||||
bban?: string
|
||||
other?: string
|
||||
}
|
||||
account_id?: AccountIdentification
|
||||
/** Every identifier the ASPSP provided, including the primary one. */
|
||||
all_account_ids?: GenericIdentification[]
|
||||
name?: string
|
||||
product?: string
|
||||
currency: string
|
||||
identification_hash?: string
|
||||
}
|
||||
|
||||
const BBAN_SCHEMES = new Set(['BBAN'])
|
||||
const DOMESTIC_ACCOUNT_SCHEMES = new Set(['BBAN', 'BGNR', 'PGNR'])
|
||||
|
||||
/**
|
||||
* The account's BBAN (Swedish clearing + account number) if the ASPSP sent
|
||||
* one, from the primary identifier or the full identifier list.
|
||||
*/
|
||||
export function extractBban(
|
||||
account: Pick<AccountInfo, 'account_id' | 'all_account_ids'>,
|
||||
): string | undefined {
|
||||
const primary = account.account_id?.other
|
||||
if (primary && BBAN_SCHEMES.has(primary.scheme_name?.toUpperCase()) && primary.identification) {
|
||||
return primary.identification.replace(/\s+/g, '')
|
||||
}
|
||||
const listed = account.all_account_ids?.find(
|
||||
(id) => BBAN_SCHEMES.has(id.scheme_name?.toUpperCase()) && Boolean(id.identification),
|
||||
)
|
||||
return listed ? listed.identification.replace(/\s+/g, '') : undefined
|
||||
}
|
||||
|
||||
/**
|
||||
* Best single identifier for a counterparty account: IBAN first, then a
|
||||
* domestic scheme (BBAN, Bankgiro, Plusgiro) from the primary identifier or
|
||||
* the additional list, then whatever else the bank sent.
|
||||
*/
|
||||
export function pickAccountIdentifier(
|
||||
account: AccountIdentification | undefined,
|
||||
additional?: GenericIdentification[],
|
||||
): string | undefined {
|
||||
if (account?.iban) return account.iban
|
||||
const candidates: GenericIdentification[] = []
|
||||
if (account?.other) candidates.push(account.other)
|
||||
if (additional) candidates.push(...additional)
|
||||
const iban = candidates.find(
|
||||
(id) => id.scheme_name?.toUpperCase() === 'IBAN' && Boolean(id.identification),
|
||||
)
|
||||
if (iban) return iban.identification
|
||||
const domestic = candidates.find(
|
||||
(id) => DOMESTIC_ACCOUNT_SCHEMES.has(id.scheme_name?.toUpperCase()) && Boolean(id.identification),
|
||||
)
|
||||
// Anything else (card PANs, customer numbers, ...) is not an account and
|
||||
// must not land in transactions.counterparty_account.
|
||||
return domestic?.identification
|
||||
}
|
||||
|
||||
export interface Balance {
|
||||
balance_amount: {
|
||||
amount: string
|
||||
@@ -111,18 +178,16 @@ export interface Transaction {
|
||||
}
|
||||
credit_debit_indicator?: 'CRDT' | 'DBIT' // CRDT = credit (income), DBIT = debit (expense)
|
||||
creditor_name?: string
|
||||
creditor_account?: {
|
||||
iban?: string
|
||||
bban?: string
|
||||
}
|
||||
creditor_account?: AccountIdentification
|
||||
/** All other creditor account identifiers provided by the ASPSP. */
|
||||
creditor_account_additional_identification?: GenericIdentification[]
|
||||
creditor?: {
|
||||
name?: string
|
||||
}
|
||||
debtor_name?: string
|
||||
debtor_account?: {
|
||||
iban?: string
|
||||
bban?: string
|
||||
}
|
||||
debtor_account?: AccountIdentification
|
||||
/** All other debtor account identifiers provided by the ASPSP. */
|
||||
debtor_account_additional_identification?: GenericIdentification[]
|
||||
debtor?: {
|
||||
name?: string
|
||||
}
|
||||
@@ -1267,8 +1332,8 @@ export function convertTransaction(tx: Transaction, accountCurrency: string): Ba
|
||||
FALLBACK_DESCRIPTION,
|
||||
counterparty_name: isCredit ? debtorName : creditorName,
|
||||
counterparty_account: isCredit
|
||||
? tx.debtor_account?.iban || tx.debtor_account?.bban
|
||||
: tx.creditor_account?.iban || tx.creditor_account?.bban,
|
||||
? pickAccountIdentifier(tx.debtor_account, tx.debtor_account_additional_identification)
|
||||
: pickAccountIdentifier(tx.creditor_account, tx.creditor_account_additional_identification),
|
||||
merchant_category_code: tx.merchant_category_code,
|
||||
bank_transaction_code: tx.bank_transaction_code,
|
||||
proprietary_bank_transaction_code: tx.proprietary_bank_transaction_code,
|
||||
|
||||
@@ -3,6 +3,10 @@
|
||||
export interface StoredAccount {
|
||||
uid: string
|
||||
iban?: string
|
||||
// Swedish BBAN (clearing number + account number, no separator) when the
|
||||
// ASPSP provided one. Display and invoice-payee prefill only: dedup keys
|
||||
// stay IBAN-then-uid (see dedup_scope).
|
||||
bban?: string
|
||||
name?: string
|
||||
currency: string
|
||||
balance?: number
|
||||
|
||||
@@ -9,7 +9,18 @@ function makeCashAccount(overrides: Partial<CashAccount> = {}): CashAccount {
|
||||
bank_connection_id: null,
|
||||
external_uid: null,
|
||||
iban: null,
|
||||
bg_pg: null,
|
||||
bban: null,
|
||||
payee_iban: null,
|
||||
bank_name: null,
|
||||
clearing_number: null,
|
||||
account_number: null,
|
||||
bankgiro: null,
|
||||
plusgiro: null,
|
||||
swish: null,
|
||||
bic: null,
|
||||
bank_code: null,
|
||||
foreign_account_number: null,
|
||||
invoice_payee: false,
|
||||
name: null,
|
||||
currency: 'SEK',
|
||||
ledger_account: '1930',
|
||||
|
||||
@@ -634,6 +634,15 @@ const CreateInvoiceBaseSchema = z.object({
|
||||
.transform((v) => v || undefined)
|
||||
.optional(),
|
||||
received_date: optionalIsoDate,
|
||||
// Which of the company's bank accounts the invoice asks the customer to pay
|
||||
// to (migration 20260903193000). Omitted/null = the per-currency default.
|
||||
// The route checks the account belongs to the company, is flagged as a
|
||||
// payee and is usable for the invoice currency.
|
||||
payment_cash_account_id: z
|
||||
.union([uuid, z.literal('')])
|
||||
.transform((v) => v || null)
|
||||
.nullable()
|
||||
.optional(),
|
||||
items: z.array(CreateInvoiceItemSchema).min(1, 'At least one item is required'),
|
||||
})
|
||||
|
||||
@@ -2210,6 +2219,35 @@ const InvoicePaymentAccountSchema = z.object({
|
||||
.or(z.literal('')),
|
||||
})
|
||||
|
||||
/**
|
||||
* PATCH /api/cash-accounts/[id]: the verifikationsserie override plus the
|
||||
* payee fields (migration 20260903150000). Payee keys share the field rules
|
||||
* of InvoicePaymentAccountSchema so the settings form, the legacy settings
|
||||
* writers and this route agree on what a valid bankgiro is.
|
||||
*/
|
||||
export const UpdateCashAccountSchema = InvoicePaymentAccountSchema.extend({
|
||||
voucher_series: UpdateCashAccountVoucherSeriesSchema.shape.voucher_series.optional(),
|
||||
name: z.string().trim().min(1).max(100).nullable().optional(),
|
||||
invoice_payee: z.boolean().optional(),
|
||||
}).strict().refine((body) => Object.keys(body).length > 0, {
|
||||
message: 'Inget att uppdatera',
|
||||
})
|
||||
|
||||
/** POST /api/cash-accounts: a bank account typed by hand (no bank connection). */
|
||||
export const CreateCashAccountSchema = z.object({
|
||||
name: z.string().trim().min(1, 'Ange ett namn').max(100),
|
||||
currency: CurrencySchema,
|
||||
ledger_account: z.string().regex(/^19[2-9]\d$/, 'Bankkonton bokförs på 1920-1999').optional(),
|
||||
invoice_payee: z.boolean().optional(),
|
||||
payee: InvoicePaymentAccountSchema.optional(),
|
||||
}).strict()
|
||||
|
||||
/** PUT /api/cash-accounts/payee-defaults: which account invoices in a currency pay to. */
|
||||
export const SetInvoicePayeeDefaultSchema = z.object({
|
||||
currency: CurrencySchema,
|
||||
cash_account_id: uuid.nullable(),
|
||||
}).strict()
|
||||
|
||||
const InvoicePaymentAccountsSchema = z
|
||||
.partialRecord(CurrencySchema, InvoicePaymentAccountSchema)
|
||||
.superRefine((accounts, ctx) => {
|
||||
|
||||
@@ -12,7 +12,7 @@
|
||||
*/
|
||||
|
||||
export const INVOICE_FULL_COLUMNS =
|
||||
'id, invoice_number, customer_id, invoice_date, due_date, delivery_date, status, currency, exchange_rate, exchange_rate_date, subtotal, subtotal_sek, vat_amount, vat_amount_sek, total, total_sek, ore_rounding, vat_treatment, vat_rate, moms_ruta, your_reference, our_reference, invoice_marking, notes, payment_link_url, stripe_payment_link_id, payment_link_auto, reverse_charge_text, credited_invoice_id, document_type, converted_from_id, valid_until, quote_status, quote_decided_at, paid_at, paid_amount, remaining_amount, default_dimensions, deduction_total, deduction_personnummer_last4, created_at, updated_at'
|
||||
'id, invoice_number, customer_id, invoice_date, due_date, delivery_date, status, currency, exchange_rate, exchange_rate_date, subtotal, subtotal_sek, vat_amount, vat_amount_sek, total, total_sek, ore_rounding, vat_treatment, vat_rate, moms_ruta, your_reference, our_reference, invoice_marking, notes, payment_link_url, stripe_payment_link_id, payment_link_auto, payment_cash_account_id, payment_details, reverse_charge_text, credited_invoice_id, document_type, converted_from_id, valid_until, quote_status, quote_decided_at, paid_at, paid_amount, remaining_amount, default_dimensions, deduction_total, deduction_personnummer_last4, created_at, updated_at'
|
||||
|
||||
/**
|
||||
* Projection for the v1 PDF download route. Narrower than INVOICE_FULL_COLUMNS
|
||||
@@ -32,7 +32,10 @@ export const INVOICE_PDF_COLUMNS =
|
||||
'id, invoice_number, customer_id, invoice_date, due_date, delivery_date, status, document_type, ' +
|
||||
'currency, subtotal, vat_amount, total, ore_rounding, vat_treatment, vat_rate, moms_ruta, ' +
|
||||
'reverse_charge_text, your_reference, our_reference, invoice_marking, notes, credited_invoice_id, ' +
|
||||
'paid_amount, remaining_amount, deduction_total, deduction_personnummer_last4'
|
||||
'paid_amount, remaining_amount, deduction_total, deduction_personnummer_last4, ' +
|
||||
// The frozen payee: an issued invoice that chose a bank account must print
|
||||
// that account, not today's company default.
|
||||
'payment_cash_account_id, payment_details'
|
||||
|
||||
export const INVOICE_ITEM_FULL_COLUMNS =
|
||||
'id, sort_order, line_type, description, quantity, unit, unit_price, discount_percent, line_total, vat_rate, vat_amount, article_id, revenue_account, deduction_type, deduction_amount, labor_hours, work_type, housing_designation, apartment_number, brf_org_number, dimensions, sales_order_item_id, created_at'
|
||||
|
||||
@@ -0,0 +1,224 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { createQueuedMockSupabase } from '@/tests/helpers'
|
||||
import type { CashAccount } from '@/types'
|
||||
import {
|
||||
cashAccountPayee,
|
||||
createManualBankAccount,
|
||||
isBankCashAccount,
|
||||
isUsableInvoicePayee,
|
||||
propagateLegacyPayeeWrite,
|
||||
updateCashAccountPayee,
|
||||
} from '../invoice-payee'
|
||||
|
||||
vi.mock('@/lib/import/account-sync', () => ({
|
||||
syncMappedAccounts: vi.fn().mockResolvedValue({ error: null }),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/cash-accounts/service', () => ({
|
||||
findFreeLedgerAccount: vi.fn().mockResolvedValue('1931'),
|
||||
}))
|
||||
|
||||
const { supabase, enqueue, reset, findCalls } = createQueuedMockSupabase()
|
||||
|
||||
function account(overrides: Partial<CashAccount> = {}): CashAccount {
|
||||
return {
|
||||
id: 'ca-1',
|
||||
company_id: 'company-1',
|
||||
bank_connection_id: null,
|
||||
external_uid: null,
|
||||
iban: null,
|
||||
bban: null,
|
||||
payee_iban: null,
|
||||
bank_name: null,
|
||||
clearing_number: null,
|
||||
account_number: null,
|
||||
bankgiro: null,
|
||||
plusgiro: null,
|
||||
swish: null,
|
||||
bic: null,
|
||||
bank_code: null,
|
||||
foreign_account_number: null,
|
||||
invoice_payee: true,
|
||||
name: 'Företagskonto',
|
||||
currency: 'SEK',
|
||||
ledger_account: '1930',
|
||||
balance: null,
|
||||
available_balance: null,
|
||||
balance_updated_at: null,
|
||||
enabled: true,
|
||||
is_primary: true,
|
||||
source: 'manual',
|
||||
voucher_series: null,
|
||||
created_at: '2026-01-01T00:00:00Z',
|
||||
updated_at: '2026-01-01T00:00:00Z',
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
reset()
|
||||
})
|
||||
|
||||
describe('cashAccountPayee', () => {
|
||||
it('normalises IBAN and BIC and passes the giro numbers through', () => {
|
||||
const payee = cashAccountPayee(account({ payee_iban: 'se45 5000 0000 0583 9825 7466', bic: 'esse sess', bankgiro: '5050-1234' }))
|
||||
expect(payee.iban).toBe('SE4550000000058398257466')
|
||||
expect(payee.bic).toBe('ESSESESS')
|
||||
expect(payee.bankgiro).toBe('5050-1234')
|
||||
expect(payee.plusgiro).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('isUsableInvoicePayee', () => {
|
||||
it('needs the payee flag, enabled, and identifiers the currency accepts', () => {
|
||||
expect(isUsableInvoicePayee(account({ bankgiro: '5050-1234' }), 'SEK')).toBe(true)
|
||||
expect(isUsableInvoicePayee(account({ bankgiro: '5050-1234', invoice_payee: false }), 'SEK')).toBe(false)
|
||||
expect(isUsableInvoicePayee(account({ bankgiro: '5050-1234', enabled: false }), 'SEK')).toBe(false)
|
||||
expect(isUsableInvoicePayee(account(), 'SEK')).toBe(false)
|
||||
})
|
||||
|
||||
it('a SEK account with an IBAN is a usable EUR payee; a bankgiro-only one is not', () => {
|
||||
expect(isUsableInvoicePayee(account({ payee_iban: 'SE4550000000058398257466' }), 'EUR')).toBe(true)
|
||||
// The bank-identity iban never prints: only payee_iban counts.
|
||||
expect(isUsableInvoicePayee(account({ iban: 'SE4550000000058398257466' }), 'EUR')).toBe(false)
|
||||
expect(isUsableInvoicePayee(account({ bankgiro: '5050-1234' }), 'EUR')).toBe(false)
|
||||
})
|
||||
|
||||
it('accepts the USD routing triple without an IBAN', () => {
|
||||
expect(isUsableInvoicePayee(
|
||||
account({ currency: 'USD', ledger_account: '1933', bank_code: '021000021', foreign_account_number: '12345678', bic: 'CHASUS33' }),
|
||||
'USD',
|
||||
)).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('isBankCashAccount', () => {
|
||||
it('keeps giro/bank rows (1920-1999) and drops PSP clearing accounts and the cash till', () => {
|
||||
expect(isBankCashAccount({ ledger_account: '1920' })).toBe(true)
|
||||
expect(isBankCashAccount({ ledger_account: '1930' })).toBe(true)
|
||||
expect(isBankCashAccount({ ledger_account: '1945' })).toBe(true)
|
||||
expect(isBankCashAccount({ ledger_account: '1910' })).toBe(false)
|
||||
expect(isBankCashAccount({ ledger_account: '1919' })).toBe(false)
|
||||
expect(isBankCashAccount({ ledger_account: '1686' })).toBe(false)
|
||||
expect(isBankCashAccount({ ledger_account: '1584' })).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('updateCashAccountPayee', () => {
|
||||
it('writes only the supplied keys, clears with null, normalises IBAN/BIC', async () => {
|
||||
enqueue({ data: account({ bankgiro: '5050-1234' }) })
|
||||
await updateCashAccountPayee(supabase as never, 'company-1', 'ca-1', {
|
||||
bankgiro: '5050-1234',
|
||||
plusgiro: null,
|
||||
iban: 'se45 5000 0000 0583 9825 7466',
|
||||
invoice_payee: true,
|
||||
})
|
||||
const [update] = findCalls('cash_accounts', 'update')
|
||||
expect(update[0]).toMatchObject({
|
||||
bankgiro: '5050-1234',
|
||||
plusgiro: null,
|
||||
payee_iban: 'SE4550000000058398257466',
|
||||
invoice_payee: true,
|
||||
})
|
||||
// Untouched keys are undefined (dropped by supabase-js), never null.
|
||||
expect((update[0] as Record<string, unknown>).swish).toBeUndefined()
|
||||
expect((update[0] as Record<string, unknown>).iban).toBeUndefined()
|
||||
const eqCalls = findCalls('cash_accounts', 'eq')
|
||||
expect(eqCalls).toContainEqual(['company_id', 'company-1'])
|
||||
expect(eqCalls).toContainEqual(['id', 'ca-1'])
|
||||
})
|
||||
})
|
||||
|
||||
describe('createManualBankAccount', () => {
|
||||
it('allocates a free 19xx slot past every row the company already holds, syncs the chart, and inserts a manual payee row', async () => {
|
||||
enqueue({ data: [{ ledger_account: '1930' }] }) // existing rows (the seeded manual 1930)
|
||||
enqueue({ data: account({ id: 'ca-new', ledger_account: '1931', source: 'manual', bankgiro: '5050-1234' }) })
|
||||
const created = await createManualBankAccount(supabase as never, 'company-1', 'user-1', {
|
||||
name: 'Sparkonto',
|
||||
currency: 'sek',
|
||||
payee: { bankgiro: '5050-1234', iban: ' se45 5000 0000 0583 9825 7466 ' },
|
||||
})
|
||||
expect(created.id).toBe('ca-new')
|
||||
const [insert] = findCalls('cash_accounts', 'insert')
|
||||
expect(insert[0]).toMatchObject({
|
||||
company_id: 'company-1',
|
||||
ledger_account: '1931',
|
||||
currency: 'SEK',
|
||||
name: 'Sparkonto',
|
||||
source: 'manual',
|
||||
invoice_payee: true,
|
||||
is_primary: false,
|
||||
bankgiro: '5050-1234',
|
||||
iban: 'SE4550000000058398257466',
|
||||
payee_iban: 'SE4550000000058398257466',
|
||||
})
|
||||
// The seeded 1930 row is manual, which findFreeLedgerAccount treats as
|
||||
// free (the PSD2 path promotes it in place); this path inserts, so it
|
||||
// must be excluded or the insert trips the (company, ledger) UNIQUE.
|
||||
const { findFreeLedgerAccount } = await import('@/lib/cash-accounts/service')
|
||||
expect(findFreeLedgerAccount).toHaveBeenCalledWith(expect.anything(), 'company-1', 'SEK', new Set(['1930']))
|
||||
})
|
||||
|
||||
it('refuses a requested ledger account another row already holds', async () => {
|
||||
enqueue({ data: [{ ledger_account: '1930' }, { ledger_account: '1931' }] })
|
||||
await expect(createManualBankAccount(supabase as never, 'company-1', 'user-1', {
|
||||
name: 'X', currency: 'SEK', ledger_account: '1931',
|
||||
})).rejects.toThrow(/already a cash account/)
|
||||
expect(findCalls('cash_accounts', 'insert')).toHaveLength(0)
|
||||
})
|
||||
})
|
||||
|
||||
describe('propagateLegacyPayeeWrite', () => {
|
||||
it('writes a legacy SEK column change through to the SEK default account', async () => {
|
||||
enqueue({ data: [{ currency: 'SEK', cash_account_id: 'ca-1' }] }) // defaults
|
||||
enqueue({ data: account({ bankgiro: '5050-1234' }) }) // update
|
||||
const written = await propagateLegacyPayeeWrite(supabase as never, 'company-1', { bankgiro: '5050-1234' })
|
||||
expect(written).toEqual(['SEK'])
|
||||
expect(findCalls('cash_accounts', 'update')).toEqual([[{ invoice_payee: true, bankgiro: '5050-1234' }]])
|
||||
expect(findCalls('invoice_payee_defaults', 'upsert')).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('adopts the primary SEK account when no SEK default exists yet: fields first, then the default', async () => {
|
||||
enqueue({ data: [] }) // defaults: none
|
||||
enqueue({ data: { id: 'ca-primary', ledger_account: '1930' } }) // primary lookup
|
||||
enqueue({ data: account({ id: 'ca-primary', payee_iban: 'SE4550000000058398257466' }) }) // update
|
||||
enqueue({ data: null }) // upsert default
|
||||
const written = await propagateLegacyPayeeWrite(supabase as never, 'company-1', {
|
||||
iban: 'SE4550000000058398257466',
|
||||
bic: '',
|
||||
})
|
||||
expect(written).toEqual(['SEK'])
|
||||
expect(findCalls('invoice_payee_defaults', 'upsert')[0][0]).toEqual({
|
||||
company_id: 'company-1',
|
||||
currency: 'SEK',
|
||||
cash_account_id: 'ca-primary',
|
||||
})
|
||||
const [update] = findCalls('cash_accounts', 'update')
|
||||
expect(update[0]).toMatchObject({
|
||||
invoice_payee: true,
|
||||
payee_iban: 'SE4550000000058398257466',
|
||||
bic: null,
|
||||
})
|
||||
})
|
||||
|
||||
it('a full map entry replaces every payee field on the default account; currencies without a default are skipped', async () => {
|
||||
enqueue({ data: [{ currency: 'EUR', cash_account_id: 'ca-1' }] })
|
||||
enqueue({ data: account({ payee_iban: 'SE4550000000058398257466' }) })
|
||||
const written = await propagateLegacyPayeeWrite(supabase as never, 'company-1', {
|
||||
invoice_payment_accounts: {
|
||||
EUR: { iban: 'SE4550000000058398257466', bic: 'ESSESESS' },
|
||||
USD: { iban: 'GB33BUKB20201555555555' },
|
||||
},
|
||||
})
|
||||
expect(written).toEqual(['EUR'])
|
||||
const [payload] = findCalls('cash_accounts', 'update')[0] as [Record<string, unknown>]
|
||||
expect(payload).toMatchObject({ invoice_payee: true, payee_iban: 'SE4550000000058398257466', bic: 'ESSESESS', bankgiro: null, swish: null })
|
||||
})
|
||||
|
||||
it('does nothing when the change carries no payment instructions', async () => {
|
||||
const written = await propagateLegacyPayeeWrite(supabase as never, 'company-1', { email: 'x@y.se' } as never)
|
||||
expect(written).toEqual([])
|
||||
expect(findCalls('invoice_payee_defaults', 'select')).toHaveLength(0)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,405 @@
|
||||
import type { SupabaseClient } from '@supabase/supabase-js'
|
||||
import type {
|
||||
CashAccount,
|
||||
CashAccountPayeeFields,
|
||||
Currency,
|
||||
InvoicePayeeDefault,
|
||||
InvoicePaymentAccount,
|
||||
} from '@/types'
|
||||
import { createLogger } from '@/lib/logger'
|
||||
import { getBASReference } from '@/lib/bookkeeping/bas-reference'
|
||||
import { syncMappedAccounts } from '@/lib/import/account-sync'
|
||||
import {
|
||||
hasUsableInvoicePaymentAccount,
|
||||
isInvoicePaymentAccountCurrency,
|
||||
normalizeInvoicePaymentAccount,
|
||||
} from '@/lib/invoices/payment-accounts'
|
||||
import { findFreeLedgerAccount } from '@/lib/cash-accounts/service'
|
||||
|
||||
const log = createLogger('cash-accounts/invoice-payee')
|
||||
|
||||
export const PAYEE_FIELDS: readonly (keyof CashAccountPayeeFields)[] = [
|
||||
'bank_name',
|
||||
'clearing_number',
|
||||
'account_number',
|
||||
'bankgiro',
|
||||
'plusgiro',
|
||||
'swish',
|
||||
'iban',
|
||||
'bic',
|
||||
'bank_code',
|
||||
'foreign_account_number',
|
||||
]
|
||||
|
||||
/** A cash account's payee columns: the InvoicePaymentAccount keys, with the printed IBAN in payee_iban. */
|
||||
export type CashAccountPayeeSource = Omit<CashAccountPayeeFields, 'iban'> & { payee_iban: string | null }
|
||||
|
||||
/**
|
||||
* The payee fields of a cash account in the shape the invoice renderers read.
|
||||
* The printed IBAN is payee_iban, never the bank-identity iban column.
|
||||
*/
|
||||
export function cashAccountPayee(account: CashAccountPayeeSource): InvoicePaymentAccount {
|
||||
return normalizeInvoicePaymentAccount({
|
||||
bank_name: account.bank_name,
|
||||
clearing_number: account.clearing_number,
|
||||
account_number: account.account_number,
|
||||
bankgiro: account.bankgiro,
|
||||
plusgiro: account.plusgiro,
|
||||
swish: account.swish,
|
||||
iban: account.payee_iban,
|
||||
bic: account.bic,
|
||||
bank_code: account.bank_code,
|
||||
foreign_account_number: account.foreign_account_number,
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the account can be printed on an invoice in `currency`: enabled,
|
||||
* flagged as a payee, and carrying the identifiers that currency needs (an
|
||||
* IBAN for anything but SEK, or the USD/GBP routing triple).
|
||||
*/
|
||||
export function isUsableInvoicePayee(account: CashAccount, currency: Currency): boolean {
|
||||
return account.enabled
|
||||
&& account.invoice_payee
|
||||
&& hasUsableInvoicePaymentAccount(cashAccountPayee(account), currency)
|
||||
}
|
||||
|
||||
/**
|
||||
* Bank-type rows only: Stripe (1686), Woo (1680) and Shopify (1584) also live
|
||||
* in cash_accounts, and so may a till (1910 Kassa, 1911-1919). A customer is
|
||||
* paid to a giro or bank account (BAS 1920-1999), never to a cash till.
|
||||
*/
|
||||
export function isBankCashAccount(account: Pick<CashAccount, 'ledger_account'>): boolean {
|
||||
return /^19[2-9]\d$/.test(account.ledger_account)
|
||||
}
|
||||
|
||||
export interface InvoicePayeeState {
|
||||
accounts: CashAccount[]
|
||||
defaults: InvoicePayeeDefault[]
|
||||
}
|
||||
|
||||
/**
|
||||
* Every bank-type cash account of the company (payee or not: the settings
|
||||
* page lets the user promote one) plus the per-currency defaults.
|
||||
*/
|
||||
export async function loadInvoicePayeeState(
|
||||
supabase: SupabaseClient,
|
||||
companyId: string,
|
||||
): Promise<InvoicePayeeState> {
|
||||
const [accountsRes, defaultsRes] = await Promise.all([
|
||||
supabase
|
||||
.from('cash_accounts')
|
||||
.select('*')
|
||||
.eq('company_id', companyId)
|
||||
.order('is_primary', { ascending: false })
|
||||
.order('ledger_account', { ascending: true }),
|
||||
supabase
|
||||
.from('invoice_payee_defaults')
|
||||
.select('*')
|
||||
.eq('company_id', companyId),
|
||||
])
|
||||
if (accountsRes.error) {
|
||||
throw new Error(`invoice payee accounts lookup failed: ${accountsRes.error.message}`)
|
||||
}
|
||||
if (defaultsRes.error) {
|
||||
throw new Error(`invoice payee defaults lookup failed: ${defaultsRes.error.message}`)
|
||||
}
|
||||
return {
|
||||
accounts: ((accountsRes.data ?? []) as CashAccount[]).filter(isBankCashAccount),
|
||||
defaults: (defaultsRes.data ?? []) as InvoicePayeeDefault[],
|
||||
}
|
||||
}
|
||||
|
||||
/** The default payee account for `currency`, or null when none is configured. */
|
||||
export async function getDefaultInvoicePayee(
|
||||
supabase: SupabaseClient,
|
||||
companyId: string,
|
||||
currency: Currency,
|
||||
): Promise<CashAccount | null> {
|
||||
const { data, error } = await supabase
|
||||
.from('invoice_payee_defaults')
|
||||
.select('cash_account:cash_accounts!invoice_payee_defaults_same_company(*)')
|
||||
.eq('company_id', companyId)
|
||||
.eq('currency', currency)
|
||||
.maybeSingle()
|
||||
if (error) {
|
||||
log.warn('getDefaultInvoicePayee failed', { companyId, currency, error: error.message })
|
||||
return null
|
||||
}
|
||||
const account = (data as { cash_account: CashAccount | CashAccount[] | null } | null)?.cash_account
|
||||
if (!account) return null
|
||||
return Array.isArray(account) ? account[0] ?? null : account
|
||||
}
|
||||
|
||||
export type PayeeUpdate = Partial<CashAccountPayeeFields> & {
|
||||
name?: string | null
|
||||
invoice_payee?: boolean
|
||||
}
|
||||
|
||||
/**
|
||||
* Update payee fields on one of the company's cash accounts. Only supplied
|
||||
* keys are written; explicit null clears. The mirror trigger rewrites
|
||||
* company_settings from this row when it is a default for some currency.
|
||||
*/
|
||||
export async function updateCashAccountPayee(
|
||||
supabase: SupabaseClient,
|
||||
companyId: string,
|
||||
cashAccountId: string,
|
||||
update: PayeeUpdate,
|
||||
): Promise<CashAccount | null> {
|
||||
// Literal payload (the phantom-column guard reads literal keys): a key the
|
||||
// caller did not supply stays undefined and is dropped by supabase-js, so
|
||||
// only supplied fields are written and explicit null still clears.
|
||||
const has = (key: keyof PayeeUpdate) => key in update && update[key] !== undefined
|
||||
if (!(Object.keys(update) as (keyof PayeeUpdate)[]).some(has)) {
|
||||
const { data } = await supabase
|
||||
.from('cash_accounts')
|
||||
.select('*')
|
||||
.eq('company_id', companyId)
|
||||
.eq('id', cashAccountId)
|
||||
.maybeSingle()
|
||||
return (data as CashAccount | null) ?? null
|
||||
}
|
||||
const { data, error } = await supabase
|
||||
.from('cash_accounts')
|
||||
.update({
|
||||
bank_name: has('bank_name') ? clean(update.bank_name) : undefined,
|
||||
clearing_number: has('clearing_number') ? clean(update.clearing_number) : undefined,
|
||||
account_number: has('account_number') ? clean(update.account_number) : undefined,
|
||||
bankgiro: has('bankgiro') ? clean(update.bankgiro) : undefined,
|
||||
plusgiro: has('plusgiro') ? clean(update.plusgiro) : undefined,
|
||||
swish: has('swish') ? clean(update.swish) : undefined,
|
||||
payee_iban: has('iban') ? compact(clean(update.iban), true) : undefined,
|
||||
bic: has('bic') ? compact(clean(update.bic), true) : undefined,
|
||||
bank_code: has('bank_code') ? clean(update.bank_code) : undefined,
|
||||
foreign_account_number: has('foreign_account_number') ? clean(update.foreign_account_number) : undefined,
|
||||
name: has('name') ? clean(update.name) : undefined,
|
||||
invoice_payee: update.invoice_payee,
|
||||
})
|
||||
.eq('company_id', companyId)
|
||||
.eq('id', cashAccountId)
|
||||
.select('*')
|
||||
.maybeSingle()
|
||||
if (error) throw new Error(`cash_accounts payee update failed: ${error.message}`)
|
||||
return (data as CashAccount | null) ?? null
|
||||
}
|
||||
|
||||
/**
|
||||
* Make `cashAccountId` the default payee for `currency`, or clear the
|
||||
* default when null. The account must belong to the company: the composite
|
||||
* FK rejects a foreign id and the caller sees the error.
|
||||
*/
|
||||
export async function setInvoicePayeeDefault(
|
||||
supabase: SupabaseClient,
|
||||
companyId: string,
|
||||
currency: Currency,
|
||||
cashAccountId: string | null,
|
||||
): Promise<void> {
|
||||
if (cashAccountId === null) {
|
||||
const { error } = await supabase
|
||||
.from('invoice_payee_defaults')
|
||||
.delete()
|
||||
.eq('company_id', companyId)
|
||||
.eq('currency', currency)
|
||||
if (error) throw new Error(`invoice_payee_defaults delete failed: ${error.message}`)
|
||||
return
|
||||
}
|
||||
const { error } = await supabase
|
||||
.from('invoice_payee_defaults')
|
||||
.upsert(
|
||||
{ company_id: companyId, currency, cash_account_id: cashAccountId },
|
||||
{ onConflict: 'company_id,currency' },
|
||||
)
|
||||
if (error) throw new Error(`invoice_payee_defaults upsert failed: ${error.message}`)
|
||||
}
|
||||
|
||||
export interface CreateManualBankAccountInput {
|
||||
name: string
|
||||
currency: string
|
||||
ledger_account?: string | null
|
||||
payee?: Partial<CashAccountPayeeFields>
|
||||
invoice_payee?: boolean
|
||||
}
|
||||
|
||||
/**
|
||||
* A bank account the user types in (no PSD2 connection). Allocates the next
|
||||
* free 19xx slot for the currency unless one is given, and makes sure that
|
||||
* number exists in the chart so bookings and pickers can see it.
|
||||
*/
|
||||
export async function createManualBankAccount(
|
||||
supabase: SupabaseClient,
|
||||
companyId: string,
|
||||
userId: string,
|
||||
input: CreateManualBankAccountInput,
|
||||
): Promise<CashAccount> {
|
||||
const currency = input.currency.toUpperCase()
|
||||
// findFreeLedgerAccount treats a slot held by a manual row as free (the
|
||||
// PSD2 path promotes that row in place); this path INSERTS, so every slot
|
||||
// any row holds is taken.
|
||||
const { data: existing, error: existingError } = await supabase
|
||||
.from('cash_accounts')
|
||||
.select('ledger_account')
|
||||
.eq('company_id', companyId)
|
||||
if (existingError) throw new Error(`cash_accounts lookup failed: ${existingError.message}`)
|
||||
const taken = new Set(((existing ?? []) as { ledger_account: string }[]).map((r) => r.ledger_account))
|
||||
const requested = input.ledger_account?.trim()
|
||||
if (requested && taken.has(requested)) {
|
||||
throw new Error(`Ledger account ${requested} is already a cash account of this company`)
|
||||
}
|
||||
const ledger = requested || (await findFreeLedgerAccount(supabase, companyId, currency, taken))
|
||||
if (!ledger) {
|
||||
throw new Error('No free 19xx ledger account for a new bank account')
|
||||
}
|
||||
const chartName = getBASReference(ledger)?.account_name ?? `Bankkonto ${currency}`
|
||||
const sync = await syncMappedAccounts(
|
||||
supabase,
|
||||
companyId,
|
||||
userId,
|
||||
[{
|
||||
sourceAccount: ledger,
|
||||
sourceName: chartName,
|
||||
targetAccount: ledger,
|
||||
targetName: chartName,
|
||||
confidence: 1,
|
||||
matchType: 'exact',
|
||||
isOverride: false,
|
||||
}],
|
||||
false,
|
||||
)
|
||||
if (sync.error) {
|
||||
throw new Error(`chart sync failed for ${ledger}: ${sync.error}`)
|
||||
}
|
||||
|
||||
const payee = input.payee ?? {}
|
||||
const { data, error } = await supabase
|
||||
.from('cash_accounts')
|
||||
.insert({
|
||||
company_id: companyId,
|
||||
ledger_account: ledger,
|
||||
currency,
|
||||
name: input.name.trim(),
|
||||
enabled: true,
|
||||
is_primary: false,
|
||||
source: 'manual',
|
||||
invoice_payee: input.invoice_payee ?? true,
|
||||
bank_name: clean(payee.bank_name),
|
||||
clearing_number: clean(payee.clearing_number),
|
||||
account_number: clean(payee.account_number),
|
||||
bankgiro: clean(payee.bankgiro),
|
||||
plusgiro: clean(payee.plusgiro),
|
||||
swish: clean(payee.swish),
|
||||
// A typed account: the printed IBAN is also the account's identity, so
|
||||
// a later bank connection with the same IBAN promotes this row in place.
|
||||
iban: compact(clean(payee.iban), true),
|
||||
payee_iban: compact(clean(payee.iban), true),
|
||||
bic: compact(clean(payee.bic), true),
|
||||
bank_code: clean(payee.bank_code),
|
||||
foreign_account_number: clean(payee.foreign_account_number),
|
||||
})
|
||||
.select('*')
|
||||
.single()
|
||||
if (error) throw new Error(`cash_accounts insert failed: ${error.message}`)
|
||||
return data as CashAccount
|
||||
}
|
||||
|
||||
/**
|
||||
* Legacy writers (PUT /api/settings, v1 settings, MCP update_company_settings)
|
||||
* still send payment instructions as company_settings columns or as the
|
||||
* per-currency map. Write them through to the default cash account for each
|
||||
* currency so the account stays the truth; the mirror trigger then rewrites
|
||||
* the map and legacy columns from the account, which is what the caller
|
||||
* asked for. Currencies with no default account are left to the caller's
|
||||
* own company_settings write (the resolver's fallback).
|
||||
*
|
||||
* Returns the currencies that were written through, so callers can decide
|
||||
* whether their own company_settings write still needs those keys.
|
||||
*/
|
||||
export async function propagateLegacyPayeeWrite(
|
||||
supabase: SupabaseClient,
|
||||
companyId: string,
|
||||
changes: {
|
||||
invoice_payment_accounts?: Partial<Record<string, Partial<InvoicePaymentAccount> | null | undefined>>
|
||||
} & Partial<Record<keyof InvoicePaymentAccount, string | null | undefined>>,
|
||||
): Promise<Currency[]> {
|
||||
const entries = new Map<Currency, Partial<InvoicePaymentAccount>>()
|
||||
const map = changes.invoice_payment_accounts
|
||||
if (map) {
|
||||
for (const [currency, account] of Object.entries(map)) {
|
||||
if (!isInvoicePaymentAccountCurrency(currency) || !account) continue
|
||||
entries.set(currency, account)
|
||||
}
|
||||
}
|
||||
const legacyKeys: (keyof InvoicePaymentAccount)[] = [
|
||||
'bank_name', 'clearing_number', 'account_number', 'bankgiro', 'plusgiro', 'swish', 'iban', 'bic',
|
||||
]
|
||||
if (!entries.has('SEK') && legacyKeys.some((key) => changes[key] !== undefined)) {
|
||||
const partial: Partial<InvoicePaymentAccount> = {}
|
||||
for (const key of legacyKeys) {
|
||||
if (changes[key] !== undefined) partial[key] = changes[key] ?? null
|
||||
}
|
||||
entries.set('SEK', partial)
|
||||
}
|
||||
if (entries.size === 0) return []
|
||||
|
||||
const { data: defaultsData, error: defaultsError } = await supabase
|
||||
.from('invoice_payee_defaults')
|
||||
.select('currency, cash_account_id')
|
||||
.eq('company_id', companyId)
|
||||
if (defaultsError) {
|
||||
throw new Error(`invoice_payee_defaults lookup failed: ${defaultsError.message}`)
|
||||
}
|
||||
const defaults = new Map(
|
||||
((defaultsData ?? []) as { currency: string; cash_account_id: string }[])
|
||||
.map((row) => [row.currency, row.cash_account_id] as const),
|
||||
)
|
||||
|
||||
const written: Currency[] = []
|
||||
for (const [currency, account] of entries) {
|
||||
let target = defaults.get(currency) ?? null
|
||||
let adopt = false
|
||||
if (!target && currency === 'SEK') {
|
||||
// Every company is seeded with a primary SEK account: adopt it as the
|
||||
// SEK payee so a first-time bank-details save lands on an account.
|
||||
const { data: primary } = await supabase
|
||||
.from('cash_accounts')
|
||||
.select('id, ledger_account')
|
||||
.eq('company_id', companyId)
|
||||
.eq('currency', 'SEK')
|
||||
.eq('enabled', true)
|
||||
.eq('is_primary', true)
|
||||
.maybeSingle()
|
||||
const row = primary as { id: string; ledger_account: string } | null
|
||||
if (row && isBankCashAccount(row)) {
|
||||
target = row.id
|
||||
adopt = true
|
||||
}
|
||||
}
|
||||
if (!target) continue
|
||||
// A full map entry replaces the account's payee (the settings form sends
|
||||
// every field); a partial legacy write only touches the supplied keys.
|
||||
const update: PayeeUpdate = { invoice_payee: true }
|
||||
const full = map?.[currency] !== undefined
|
||||
for (const field of PAYEE_FIELDS) {
|
||||
if (full || field in account) update[field] = account[field] ?? null
|
||||
}
|
||||
// Fields first, default second: the default insert fires the mirror, and
|
||||
// it must see the filled account, never an empty one.
|
||||
await updateCashAccountPayee(supabase, companyId, target, update)
|
||||
if (adopt) await setInvoicePayeeDefault(supabase, companyId, 'SEK', target)
|
||||
written.push(currency)
|
||||
}
|
||||
return written
|
||||
}
|
||||
|
||||
function clean(value: string | null | undefined): string | null {
|
||||
if (value === undefined || value === null) return null
|
||||
const trimmed = value.trim()
|
||||
return trimmed ? trimmed : null
|
||||
}
|
||||
|
||||
/** Strip inner whitespace (IBAN, BIC), optionally upper-casing. */
|
||||
function compact(value: string | null, upper = false): string | null {
|
||||
if (value === null) return null
|
||||
const stripped = value.replace(/\s/g, '')
|
||||
return upper ? stripped.toUpperCase() : stripped
|
||||
}
|
||||
@@ -44,6 +44,8 @@ export interface UpsertFromPsd2Input {
|
||||
currency: string
|
||||
ledger_account: string
|
||||
iban?: string | null
|
||||
/** Raw BBAN from the ASPSP (Swedish: clearing + account number). */
|
||||
bban?: string | null
|
||||
name?: string | null
|
||||
balance?: number | null
|
||||
available_balance?: number | null
|
||||
@@ -1172,6 +1174,9 @@ export async function upsertFromPsd2(
|
||||
bank_connection_id: input.bank_connection_id,
|
||||
external_uid: input.external_uid,
|
||||
iban: input.iban ?? null,
|
||||
// Only overwrite when the bank sent one: a typed BBAN must survive a
|
||||
// sync from an ASPSP that reports IBAN only.
|
||||
...(input.bban ? { bban: input.bban } : {}),
|
||||
name: input.name ?? null,
|
||||
currency: input.currency.toUpperCase(),
|
||||
ledger_account: input.ledger_account,
|
||||
|
||||
@@ -231,7 +231,7 @@ function safeBrandingColor(value: string | null | undefined, fallback: string):
|
||||
*/
|
||||
export function generateInvoiceEmailHtml(data: InvoiceEmailData): string {
|
||||
const { invoice, customer } = data
|
||||
const company = companyWithInvoicePaymentAccount(data.company, invoice.currency)
|
||||
const company = companyWithInvoicePaymentAccount(data.company, invoice.currency, invoice.payment_details ?? null)
|
||||
|
||||
const lang = resolveLang(customer)
|
||||
const L = LABELS[lang]
|
||||
@@ -396,7 +396,7 @@ export function generateInvoiceEmailHtml(data: InvoiceEmailData): string {
|
||||
*/
|
||||
export function generateInvoiceEmailText(data: InvoiceEmailData): string {
|
||||
const { invoice, customer } = data
|
||||
const company = companyWithInvoicePaymentAccount(data.company, invoice.currency)
|
||||
const company = companyWithInvoicePaymentAccount(data.company, invoice.currency, invoice.payment_details ?? null)
|
||||
|
||||
const lang = resolveLang(customer)
|
||||
const L = LABELS[lang]
|
||||
|
||||
@@ -288,7 +288,7 @@ export function generateReminderEmailHtml(data: ReminderEmailData): string {
|
||||
} = data
|
||||
// Payment details follow the invoice currency, same as the invoice email
|
||||
// and PDF: a EUR reminder must never print the SEK account's IBAN.
|
||||
const company = companyWithInvoicePaymentAccount(data.company, invoice.currency)
|
||||
const company = companyWithInvoicePaymentAccount(data.company, invoice.currency, invoice.payment_details ?? null)
|
||||
const config = REMINDER_CONFIG[reminderLevel]
|
||||
const interestRatePercent = (interestRate * 100).toLocaleString('sv-SE', {
|
||||
minimumFractionDigits: 0,
|
||||
@@ -492,7 +492,7 @@ export function generateReminderEmailText(data: ReminderEmailData): string {
|
||||
} = data
|
||||
// Payment details follow the invoice currency, same as the invoice email
|
||||
// and PDF: a EUR reminder must never print the SEK account's IBAN.
|
||||
const company = companyWithInvoicePaymentAccount(data.company, invoice.currency)
|
||||
const company = companyWithInvoicePaymentAccount(data.company, invoice.currency, invoice.payment_details ?? null)
|
||||
const config = REMINDER_CONFIG[reminderLevel]
|
||||
const interestRatePercent = (interestRate * 100).toLocaleString('sv-SE', {
|
||||
minimumFractionDigits: 0,
|
||||
|
||||
@@ -1151,6 +1151,27 @@ const INVOICE: Record<string, StructuredErrorEntry> = {
|
||||
message_sv: 'Företagsinställningar saknas.',
|
||||
message_en: 'Company settings are missing.',
|
||||
},
|
||||
INVOICE_SEND_PAYMENT_ACCOUNT_INVALID: {
|
||||
httpStatus: 400,
|
||||
message_sv: 'Bankkontot som fakturan ska betalas till kan inte längre användas: det är avstängt, borttaget från kundfakturor eller saknar uppgifter för fakturans valuta. Välj ett annat konto på fakturan eller uppdatera kontot under Inställningar → Fakturering.',
|
||||
message_en: 'The bank account this invoice is to be paid to can no longer be used: it is disabled, no longer shown on customer invoices, or lacks details for the invoice currency. Pick another account on the invoice or update the account under Inställningar → Fakturering (Settings → Invoicing).',
|
||||
remediation: {
|
||||
description: 'Välj ett annat bankkonto på fakturan, eller återaktivera kontot och fyll i dess betaluppgifter under Inställningar → Fakturering.',
|
||||
},
|
||||
},
|
||||
INVOICE_PAYEE_SNAPSHOT_FAILED: {
|
||||
httpStatus: 500,
|
||||
message_sv: 'Betaluppgifterna kunde inte sparas på fakturan. Fakturan skickades inte; försök igen.',
|
||||
message_en: 'The payment details could not be saved on the invoice. The invoice was not sent; try again.',
|
||||
},
|
||||
INVOICE_PAYEE_ACCOUNT_INVALID: {
|
||||
httpStatus: 400,
|
||||
message_sv: 'Bankkontot kan inte användas som betalningsmottagare på fakturan: det tillhör inte företaget, visas inte på kundfakturor eller saknar uppgifter för fakturans valuta.',
|
||||
message_en: 'The bank account cannot be the payee on this invoice: it does not belong to the company, is not shown on customer invoices, or lacks details for the invoice currency.',
|
||||
remediation: {
|
||||
description: 'Välj ett av företagets bankkonton som är markerat "Visas på fakturor" och har betaluppgifter för fakturans valuta.',
|
||||
},
|
||||
},
|
||||
INVOICE_SEND_PAYMENT_ACCOUNT_MISSING: {
|
||||
httpStatus: 400,
|
||||
// Currency-neutral by necessity (the registry has no details). Surfaces
|
||||
|
||||
@@ -180,6 +180,24 @@ describe('findMatchingInvoices', () => {
|
||||
expect(queued.findCalls('invoices', 'eq')).toContainEqual(['document_type', 'invoice'])
|
||||
})
|
||||
|
||||
it('breaks a confidence tie in favour of the invoice that asked to be paid to the account the money landed on', async () => {
|
||||
const tx = makeTransaction({ amount: 12500, description: 'Betalning', merchant_name: null, cash_account_id: 'ca-1931' })
|
||||
const base = { total: 12500, status: 'sent' as const, remaining_amount: 12500, currency: 'SEK' as const }
|
||||
mockResult({
|
||||
data: [
|
||||
{ ...makeInvoice({ id: 'inv-default', invoice_number: 'F-1', ...base }), payment_cash_account_id: null },
|
||||
{ ...makeInvoice({ id: 'inv-1931', invoice_number: 'F-2', ...base }), payment_cash_account_id: 'ca-1931' },
|
||||
],
|
||||
error: null,
|
||||
})
|
||||
|
||||
const result = await findMatchingInvoices(supabase as never, 'company-1', tx)
|
||||
expect(result).toHaveLength(2)
|
||||
// Same score for both (exact amount, no customer name): scores untouched.
|
||||
expect(result[0].confidence).toBe(result[1].confidence)
|
||||
expect(result[0].invoice.id).toBe('inv-1931')
|
||||
})
|
||||
|
||||
it('matches by OCR reference with confidence 0.99', async () => {
|
||||
const tx = makeTransaction({ amount: 12500, reference: 'F-2024001' })
|
||||
mockResult({
|
||||
|
||||
@@ -0,0 +1,174 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { createQueuedMockSupabase } from '@/tests/helpers'
|
||||
import type { CashAccount } from '@/types'
|
||||
import { resolveInvoicePayeeChoice, resolveInvoiceSettlementAccount, snapshotInvoicePayee } from '../invoice-payee'
|
||||
|
||||
const { supabase, enqueue, reset, findCalls } = createQueuedMockSupabase()
|
||||
|
||||
const CA_1 = '11111111-1111-4111-8111-111111111111'
|
||||
|
||||
function account(overrides: Partial<CashAccount> = {}): CashAccount {
|
||||
return {
|
||||
id: CA_1,
|
||||
company_id: 'company-1',
|
||||
bank_connection_id: null,
|
||||
external_uid: null,
|
||||
iban: null,
|
||||
bban: null,
|
||||
payee_iban: null,
|
||||
bank_name: 'Testbanken',
|
||||
clearing_number: null,
|
||||
account_number: null,
|
||||
bankgiro: '5050-1055',
|
||||
plusgiro: null,
|
||||
swish: null,
|
||||
bic: null,
|
||||
bank_code: null,
|
||||
foreign_account_number: null,
|
||||
invoice_payee: true,
|
||||
name: 'Sparkonto',
|
||||
currency: 'SEK',
|
||||
ledger_account: '1931',
|
||||
balance: null,
|
||||
available_balance: null,
|
||||
balance_updated_at: null,
|
||||
enabled: true,
|
||||
is_primary: false,
|
||||
source: 'manual',
|
||||
voucher_series: null,
|
||||
created_at: '2026-01-01T00:00:00Z',
|
||||
updated_at: '2026-01-01T00:00:00Z',
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
reset()
|
||||
})
|
||||
|
||||
describe('resolveInvoicePayeeChoice', () => {
|
||||
it('no choice clears both columns without touching the database', async () => {
|
||||
const result = await resolveInvoicePayeeChoice(supabase as never, 'company-1', 'SEK', null)
|
||||
expect(result).toEqual({ ok: true, fields: { payment_cash_account_id: null, payment_details: null } })
|
||||
expect(findCalls('cash_accounts', 'select')).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('rejects an account that is not the company\'s, disabled, not a payee, or unusable for the currency', async () => {
|
||||
enqueue({ data: null })
|
||||
expect(await resolveInvoicePayeeChoice(supabase as never, 'company-1', 'SEK', CA_1)).toMatchObject({
|
||||
ok: false, code: 'INVOICE_PAYEE_ACCOUNT_INVALID', details: { reason: 'not_found' },
|
||||
})
|
||||
enqueue({ data: account({ enabled: false }) })
|
||||
expect(await resolveInvoicePayeeChoice(supabase as never, 'company-1', 'SEK', CA_1)).toMatchObject({
|
||||
ok: false, details: { reason: 'disabled' },
|
||||
})
|
||||
enqueue({ data: account({ invoice_payee: false }) })
|
||||
expect(await resolveInvoicePayeeChoice(supabase as never, 'company-1', 'SEK', CA_1)).toMatchObject({
|
||||
ok: false, details: { reason: 'not_payee' },
|
||||
})
|
||||
// A PSP clearing row (Stripe 1686) is never a payee, whatever its flags say.
|
||||
enqueue({ data: account({ ledger_account: '1686' }) })
|
||||
expect(await resolveInvoicePayeeChoice(supabase as never, 'company-1', 'SEK', CA_1)).toMatchObject({
|
||||
ok: false, details: { reason: 'not_bank_account' },
|
||||
})
|
||||
// Bankgiro only: fine for SEK, not for EUR (needs an IBAN).
|
||||
enqueue({ data: account() })
|
||||
expect(await resolveInvoicePayeeChoice(supabase as never, 'company-1', 'EUR', CA_1)).toMatchObject({
|
||||
ok: false, details: { reason: 'unusable_for_currency' },
|
||||
})
|
||||
})
|
||||
|
||||
it('freezes the account payee fields on a valid choice', async () => {
|
||||
enqueue({ data: account({ payee_iban: 'se45 5000 0000 0583 9825 7466' }) })
|
||||
const result = await resolveInvoicePayeeChoice(supabase as never, 'company-1', 'SEK', CA_1)
|
||||
expect(result.ok).toBe(true)
|
||||
if (!result.ok) return
|
||||
expect(result.fields.payment_cash_account_id).toBe(CA_1)
|
||||
expect(result.fields.payment_details).toMatchObject({
|
||||
bank_name: 'Testbanken',
|
||||
bankgiro: '5050-1055',
|
||||
iban: 'SE4550000000058398257466',
|
||||
plusgiro: null,
|
||||
})
|
||||
const eqCalls = findCalls('cash_accounts', 'eq')
|
||||
expect(eqCalls).toContainEqual(['company_id', 'company-1'])
|
||||
expect(eqCalls).toContainEqual(['id', CA_1])
|
||||
})
|
||||
})
|
||||
|
||||
describe('snapshotInvoicePayee', () => {
|
||||
it('leaves an invoice without a chosen account alone', async () => {
|
||||
const result = await snapshotInvoicePayee(supabase as never, 'company-1', {
|
||||
id: 'inv-1', currency: 'SEK', payment_cash_account_id: null, payment_details: null,
|
||||
})
|
||||
expect(result).toEqual({ ok: true, payee: null })
|
||||
expect(findCalls('cash_accounts', 'select')).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('skips credit notes and quotes even when they carry a stale account', async () => {
|
||||
const result = await snapshotInvoicePayee(supabase as never, 'company-1', {
|
||||
id: 'kr-1', currency: 'SEK', payment_cash_account_id: CA_1, credited_invoice_id: 'inv-1',
|
||||
payment_details: { bankgiro: '5050-1055' } as never,
|
||||
})
|
||||
expect(result).toMatchObject({ ok: true, payee: { bankgiro: '5050-1055' } })
|
||||
expect(findCalls('cash_accounts', 'select')).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('refreshes and persists the payee from the account as it is at issue', async () => {
|
||||
enqueue({ data: account({ plusgiro: '123456-7' }) })
|
||||
enqueue({ data: null }) // update
|
||||
const result = await snapshotInvoicePayee(supabase as never, 'company-1', {
|
||||
id: 'inv-1', currency: 'SEK', payment_cash_account_id: CA_1,
|
||||
payment_details: { bankgiro: '5050-1055' } as never,
|
||||
})
|
||||
expect(result.ok).toBe(true)
|
||||
if (!result.ok) return
|
||||
expect(result.payee).toMatchObject({ bankgiro: '5050-1055', plusgiro: '123456-7' })
|
||||
const [update] = findCalls('invoices', 'update')
|
||||
expect((update[0] as { payment_details: { plusgiro: string } }).payment_details.plusgiro).toBe('123456-7')
|
||||
expect(findCalls('invoices', 'eq')).toContainEqual(['id', 'inv-1'])
|
||||
})
|
||||
|
||||
it('does not rewrite an unchanged snapshot', async () => {
|
||||
const payee = {
|
||||
bank_name: 'Testbanken', clearing_number: null, account_number: null, bankgiro: '5050-1055',
|
||||
plusgiro: null, swish: null, iban: null, bic: null, bank_code: null, foreign_account_number: null,
|
||||
}
|
||||
enqueue({ data: account() })
|
||||
const result = await snapshotInvoicePayee(supabase as never, 'company-1', {
|
||||
id: 'inv-1', currency: 'SEK', payment_cash_account_id: CA_1, payment_details: payee,
|
||||
})
|
||||
expect(result.ok).toBe(true)
|
||||
expect(findCalls('invoices', 'update')).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('blocks issue when the chosen account can no longer be used', async () => {
|
||||
enqueue({ data: account({ invoice_payee: false }) })
|
||||
const result = await snapshotInvoicePayee(supabase as never, 'company-1', {
|
||||
id: 'inv-1', currency: 'SEK', payment_cash_account_id: CA_1, payment_details: null,
|
||||
})
|
||||
expect(result).toMatchObject({ ok: false, code: 'INVOICE_SEND_PAYMENT_ACCOUNT_INVALID' })
|
||||
expect(findCalls('invoices', 'update')).toHaveLength(0)
|
||||
})
|
||||
})
|
||||
|
||||
describe('resolveInvoiceSettlementAccount', () => {
|
||||
it('defaults to 1930 without a chosen account and never queries', async () => {
|
||||
expect(await resolveInvoiceSettlementAccount(supabase as never, 'company-1', { payment_cash_account_id: null })).toBe('1930')
|
||||
expect(findCalls('cash_accounts', 'select')).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('debits the chosen account\'s ledger account, and falls back to 1930 when the row is gone, disabled, or not a bank account', async () => {
|
||||
enqueue({ data: { ledger_account: '1931', enabled: true } })
|
||||
expect(await resolveInvoiceSettlementAccount(supabase as never, 'company-1', { payment_cash_account_id: CA_1 })).toBe('1931')
|
||||
expect(findCalls('cash_accounts', 'eq')).toContainEqual(['company_id', 'company-1'])
|
||||
enqueue({ data: null })
|
||||
expect(await resolveInvoiceSettlementAccount(supabase as never, 'company-1', { payment_cash_account_id: CA_1 })).toBe('1930')
|
||||
enqueue({ data: { ledger_account: '1931', enabled: false } })
|
||||
expect(await resolveInvoiceSettlementAccount(supabase as never, 'company-1', { payment_cash_account_id: CA_1 })).toBe('1930')
|
||||
// Stripe clearing (1686) is cleared by the payout, never by a bank transfer.
|
||||
enqueue({ data: { ledger_account: '1686', enabled: true } })
|
||||
expect(await resolveInvoiceSettlementAccount(supabase as never, 'company-1', { payment_cash_account_id: CA_1 })).toBe('1930')
|
||||
})
|
||||
})
|
||||
@@ -258,3 +258,40 @@ describe('describeMissingInvoicePaymentAccount (#2126)', () => {
|
||||
expect(isInvoicePaymentAccountCurrency(42)).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('per-invoice payee override (invoices.payment_details)', () => {
|
||||
const frozen = {
|
||||
bank_name: 'Sparbanken',
|
||||
clearing_number: null,
|
||||
account_number: null,
|
||||
bankgiro: '5050-1055',
|
||||
plusgiro: null,
|
||||
swish: null,
|
||||
iban: null,
|
||||
bic: null,
|
||||
bank_code: null,
|
||||
foreign_account_number: null,
|
||||
}
|
||||
|
||||
it('the invoice\'s frozen payee wins over the company account for the currency', () => {
|
||||
const settings = company({
|
||||
invoice_payment_accounts: {
|
||||
SEK: { ...frozen, bank_name: 'Huvudbanken', bankgiro: '991-2346' },
|
||||
},
|
||||
})
|
||||
expect(resolveInvoicePaymentAccount(settings, 'SEK', frozen)?.bankgiro).toBe('5050-1055')
|
||||
expect(resolveInvoicePaymentAccount(settings, 'SEK', null)?.bankgiro).toBe('991-2346')
|
||||
const rendered = companyWithInvoicePaymentAccount(settings, 'SEK', frozen)
|
||||
expect(rendered.bank_name).toBe('Sparbanken')
|
||||
expect(rendered.iban).toBeNull()
|
||||
})
|
||||
|
||||
it('the send gate reads the frozen payee from the invoice row', () => {
|
||||
const settings = company({ bankgiro: null, iban: null, plusgiro: null, swish: null, clearing_number: null, account_number: null })
|
||||
const invoice = makeInvoice({ currency: 'SEK', document_type: 'invoice', credited_invoice_id: null })
|
||||
expect(hasRequiredInvoicePaymentAccount(settings, invoice)).toBe(false)
|
||||
expect(hasRequiredInvoicePaymentAccount(settings, { ...invoice, payment_details: frozen })).toBe(true)
|
||||
// A frozen bankgiro-only payee is not enough for a EUR invoice.
|
||||
expect(hasRequiredInvoicePaymentAccount(settings, { ...invoice, currency: 'EUR', payment_details: frozen })).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -71,6 +71,38 @@ function makeValidInput() {
|
||||
}
|
||||
|
||||
describe('generatePeppolBisBillingInvoice', () => {
|
||||
it('prints the same payee as the PDF: the resolved SEK payment account, not the raw legacy column', () => {
|
||||
const input = makeValidInput()
|
||||
// Legacy column says one bankgiro, the resolver's SEK entry another (the
|
||||
// state a v1/MCP settings write used to leave behind). The XML must
|
||||
// follow the resolver, like the PDF and the email do.
|
||||
input.company = makeCompanySettings({
|
||||
...input.company,
|
||||
bankgiro: '991-2346',
|
||||
invoice_payment_accounts: {
|
||||
SEK: {
|
||||
bank_name: null,
|
||||
clearing_number: null,
|
||||
account_number: null,
|
||||
bankgiro: '5050-1055',
|
||||
plusgiro: null,
|
||||
swish: null,
|
||||
iban: null,
|
||||
bic: null,
|
||||
bank_code: null,
|
||||
foreign_account_number: null,
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
const result = generatePeppolBisBillingInvoice(input)
|
||||
|
||||
expect(result.ok).toBe(true)
|
||||
if (!result.ok) return
|
||||
expect(result.xml).toContain('<cbc:ID>50501055</cbc:ID>')
|
||||
expect(result.xml).not.toContain('9912346')
|
||||
})
|
||||
|
||||
it('generates a Swedish Peppol BIS Billing 3 invoice with reconciled VAT groups', () => {
|
||||
const result = generatePeppolBisBillingInvoice(makeValidInput())
|
||||
|
||||
|
||||
@@ -47,6 +47,8 @@ export interface InvoiceCopyInitial {
|
||||
notes: string
|
||||
ore_rounding: boolean | null
|
||||
default_dimensions: Record<string, string>
|
||||
/** The bank account the source asked to be paid to; reusable commercial content. */
|
||||
payment_cash_account_id: string | null
|
||||
items: InvoiceCopyItem[]
|
||||
}
|
||||
|
||||
@@ -78,6 +80,7 @@ export function buildInvoiceCopyInitial(source: InvoiceCopySource): InvoiceCopyI
|
||||
notes: source.notes ?? '',
|
||||
ore_rounding: source.ore_rounding,
|
||||
default_dimensions: source.default_dimensions ?? {},
|
||||
payment_cash_account_id: source.payment_cash_account_id ?? null,
|
||||
items: [...source.items]
|
||||
.sort((a, b) => a.sort_order - b.sort_order)
|
||||
.map((item) => ({
|
||||
|
||||
@@ -412,8 +412,14 @@ export async function findInvoiceMatchCandidates(
|
||||
}
|
||||
}
|
||||
|
||||
// Sort by confidence descending
|
||||
matches.sort((a, b) => b.confidence - a.confidence)
|
||||
// Sort by confidence descending. Ties (two open invoices for the same
|
||||
// amount on the same day) prefer the invoice that asked to be paid to the
|
||||
// account the money landed on. A tie-breaker only: scores are untouched, so
|
||||
// nothing that did not auto-match before starts to.
|
||||
const landedOn = (transaction as { cash_account_id?: string | null }).cash_account_id ?? null
|
||||
const prefers = (m: InvoiceMatch): number =>
|
||||
landedOn && m.invoice.payment_cash_account_id === landedOn ? 1 : 0
|
||||
matches.sort((a, b) => b.confidence - a.confidence || prefers(b) - prefers(a))
|
||||
|
||||
return {
|
||||
matches,
|
||||
|
||||
@@ -0,0 +1,178 @@
|
||||
import type { SupabaseClient } from '@supabase/supabase-js'
|
||||
import type { CashAccount, Currency, Invoice, InvoicePaymentAccount } from '@/types'
|
||||
import { cashAccountPayee, isBankCashAccount, isUsableInvoicePayee } from '@/lib/cash-accounts/invoice-payee'
|
||||
import { invoiceRequiresPaymentAccount } from '@/lib/invoices/payment-accounts'
|
||||
import { ACCOUNT_NUMBER_RE } from '@/lib/invariants'
|
||||
import { createLogger } from '@/lib/logger'
|
||||
|
||||
const log = createLogger('invoices/payee')
|
||||
|
||||
export type InvoicePayeeFields = {
|
||||
payment_cash_account_id: string | null
|
||||
payment_details: InvoicePaymentAccount | null
|
||||
}
|
||||
|
||||
export type InvoicePayeeChoiceResult =
|
||||
| { ok: true; fields: InvoicePayeeFields }
|
||||
| { ok: false; code: 'INVOICE_PAYEE_ACCOUNT_INVALID'; details: Record<string, unknown> }
|
||||
|
||||
async function loadPayeeAccount(
|
||||
supabase: SupabaseClient,
|
||||
companyId: string,
|
||||
cashAccountId: string,
|
||||
): Promise<CashAccount | null> {
|
||||
const { data, error } = await supabase
|
||||
.from('cash_accounts')
|
||||
.select('*')
|
||||
.eq('company_id', companyId)
|
||||
.eq('id', cashAccountId)
|
||||
.maybeSingle()
|
||||
if (error) throw new Error(`cash_accounts lookup failed: ${error.message}`)
|
||||
return (data as CashAccount | null) ?? null
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate a draft's choice of payee account and freeze its payee fields.
|
||||
* Used by every invoice create/update path (dashboard, v1, MCP) so the rule
|
||||
* cannot drift: the account must be the company's, flagged as a payee, and
|
||||
* usable for the invoice currency (an IBAN for anything but SEK).
|
||||
*
|
||||
* null/undefined = no choice: both columns are cleared and the invoice
|
||||
* resolves the company's default for its currency at render time.
|
||||
*/
|
||||
export async function resolveInvoicePayeeChoice(
|
||||
supabase: SupabaseClient,
|
||||
companyId: string,
|
||||
currency: Currency,
|
||||
cashAccountId: string | null | undefined,
|
||||
): Promise<InvoicePayeeChoiceResult> {
|
||||
if (!cashAccountId) {
|
||||
return { ok: true, fields: { payment_cash_account_id: null, payment_details: null } }
|
||||
}
|
||||
const account = await loadPayeeAccount(supabase, companyId, cashAccountId)
|
||||
if (!account || !isBankCashAccount(account) || !isUsableInvoicePayee(account, currency)) {
|
||||
return {
|
||||
ok: false,
|
||||
code: 'INVOICE_PAYEE_ACCOUNT_INVALID',
|
||||
details: {
|
||||
cash_account_id: cashAccountId,
|
||||
currency,
|
||||
reason: !account ? 'not_found' : !isBankCashAccount(account) ? 'not_bank_account' : !account.enabled ? 'disabled' : !account.invoice_payee ? 'not_payee' : 'unusable_for_currency',
|
||||
},
|
||||
}
|
||||
}
|
||||
return {
|
||||
ok: true,
|
||||
fields: { payment_cash_account_id: account.id, payment_details: cashAccountPayee(account) },
|
||||
}
|
||||
}
|
||||
|
||||
export type InvoicePayeeSnapshotResult =
|
||||
| { ok: true; payee: InvoicePaymentAccount | null }
|
||||
| { ok: false; code: 'INVOICE_SEND_PAYMENT_ACCOUNT_INVALID' | 'INVOICE_PAYEE_SNAPSHOT_FAILED'; details: Record<string, unknown> }
|
||||
|
||||
export interface SnapshotInvoicePayeeOptions {
|
||||
/** false = validate and return the payee without writing (dry runs). */
|
||||
persist?: boolean
|
||||
}
|
||||
|
||||
/**
|
||||
* At issue (send, mark-sent, Peppol, recurring): refresh the frozen payee of
|
||||
* an invoice that chose a bank account from the account as it is now, and
|
||||
* persist it. From here on the invoice prints these fields whatever happens
|
||||
* to the account. An account that can no longer be used blocks issue with a
|
||||
* specific error instead of silently printing the company default.
|
||||
*
|
||||
* Invoices without a chosen account are left alone (payee null): they keep
|
||||
* resolving the per-currency default exactly as before this feature.
|
||||
*/
|
||||
export async function snapshotInvoicePayee(
|
||||
supabase: SupabaseClient,
|
||||
companyId: string,
|
||||
invoice: Pick<Invoice, 'id' | 'currency'>
|
||||
& Partial<Pick<Invoice, 'payment_cash_account_id' | 'payment_details' | 'document_type' | 'credited_invoice_id'>>,
|
||||
opts: SnapshotInvoicePayeeOptions = {},
|
||||
): Promise<InvoicePayeeSnapshotResult> {
|
||||
const cashAccountId = invoice.payment_cash_account_id ?? null
|
||||
if (!cashAccountId) return { ok: true, payee: invoice.payment_details ?? null }
|
||||
// Credit notes, proformas, delivery notes and quotes print no payee: a
|
||||
// stale account on them must not block issue.
|
||||
if (!invoiceRequiresPaymentAccount({
|
||||
credited_invoice_id: invoice.credited_invoice_id ?? null,
|
||||
document_type: invoice.document_type ?? 'invoice',
|
||||
})) {
|
||||
return { ok: true, payee: invoice.payment_details ?? null }
|
||||
}
|
||||
|
||||
const account = await loadPayeeAccount(supabase, companyId, cashAccountId)
|
||||
if (!account || !isBankCashAccount(account) || !isUsableInvoicePayee(account, invoice.currency)) {
|
||||
return {
|
||||
ok: false,
|
||||
code: 'INVOICE_SEND_PAYMENT_ACCOUNT_INVALID',
|
||||
details: { cash_account_id: cashAccountId, currency: invoice.currency },
|
||||
}
|
||||
}
|
||||
const payee = cashAccountPayee(account)
|
||||
const current = invoice.payment_details ?? null
|
||||
if (opts.persist !== false && JSON.stringify(current) !== JSON.stringify(payee)) {
|
||||
const { error } = await supabase
|
||||
.from('invoices')
|
||||
.update({ payment_details: payee })
|
||||
.eq('id', invoice.id)
|
||||
.eq('company_id', companyId)
|
||||
if (error) {
|
||||
// Issue must not continue: the document would print a payee the row
|
||||
// does not carry, and a later re-render would disagree with it.
|
||||
log.error('invoice payee snapshot write failed', { invoiceId: invoice.id, error: error.message })
|
||||
return {
|
||||
ok: false,
|
||||
code: 'INVOICE_PAYEE_SNAPSHOT_FAILED',
|
||||
details: { cash_account_id: cashAccountId, invoice_id: invoice.id, pgMessage: error.message },
|
||||
}
|
||||
}
|
||||
}
|
||||
return { ok: true, payee }
|
||||
}
|
||||
|
||||
/**
|
||||
* The BAS account a manual "mark as paid" debits: the chosen payee account's
|
||||
* ledger account (1930, 1931, ...) when the invoice chose one and the row
|
||||
* still exists, else the 1930 default the generators have always used.
|
||||
* Bank-transaction matches never come here: they debit the account the
|
||||
* money actually landed on (resolveSettlementAccount on the transaction).
|
||||
*/
|
||||
export async function resolveInvoiceSettlementAccount(
|
||||
supabase: SupabaseClient,
|
||||
companyId: string,
|
||||
invoice: Partial<Pick<Invoice, 'payment_cash_account_id'>>,
|
||||
): Promise<string> {
|
||||
const cashAccountId = invoice.payment_cash_account_id ?? null
|
||||
if (!cashAccountId) return '1930'
|
||||
const { data, error } = await supabase
|
||||
.from('cash_accounts')
|
||||
.select('ledger_account, enabled')
|
||||
.eq('company_id', companyId)
|
||||
.eq('id', cashAccountId)
|
||||
.maybeSingle()
|
||||
if (error) {
|
||||
log.warn('settlement account lookup failed; defaulting to 1930', { cashAccountId, error: error.message })
|
||||
return '1930'
|
||||
}
|
||||
const row = data as { ledger_account?: string; enabled?: boolean } | null
|
||||
const ledger = row?.ledger_account
|
||||
// Only a live bank account (19xx) may take the debit: a PSP clearing
|
||||
// account (1686, 1680, 1584) cleared later by a payout must never receive
|
||||
// a bank transfer, and a disabled or deleted account is not where money
|
||||
// lands any more. Both fall back to 1930, and say so: the printed invoice
|
||||
// named another account, so the bookkeeper must know.
|
||||
if (!row || !ledger || !ACCOUNT_NUMBER_RE.test(ledger) || !isBankCashAccount({ ledger_account: ledger }) || row.enabled === false) {
|
||||
log.warn('chosen payee account is not a live bank account; debiting 1930 instead', {
|
||||
cashAccountId,
|
||||
ledger: ledger ?? null,
|
||||
enabled: row?.enabled ?? null,
|
||||
found: Boolean(row),
|
||||
})
|
||||
return '1930'
|
||||
}
|
||||
return ledger
|
||||
}
|
||||
@@ -9,6 +9,7 @@ import type { CustomIssuanceLine } from '@/lib/invoices/issuance-custom-lines'
|
||||
import { recordManualInvoiceDelivery } from '@/lib/invoices/invoice-deliveries'
|
||||
import { InvoicePDF } from '@/lib/invoices/pdf-template'
|
||||
import { prepareInvoicePdfRender, buildSwishQrDataUrl } from '@/lib/invoices/pdf-render-helpers'
|
||||
import { snapshotInvoicePayee } from '@/lib/invoices/invoice-payee'
|
||||
import { invoicePdfFilename } from '@/lib/invoices/pdf-filename'
|
||||
import {
|
||||
hasRequiredInvoicePaymentAccount,
|
||||
@@ -93,7 +94,7 @@ export async function archiveIssuedInvoicePdf(args: {
|
||||
const { branding, company: renderCompany } = await prepareInvoicePdfRender(
|
||||
settings,
|
||||
renderableInvoice.currency,
|
||||
{ paymentAccountRequired },
|
||||
{ paymentAccountRequired, payee: renderableInvoice.payment_details ?? null },
|
||||
)
|
||||
const swishQrDataUrl = await buildSwishQrDataUrl(renderCompany, renderableInvoice)
|
||||
const pdfBuffer = await renderToBuffer(
|
||||
@@ -160,6 +161,15 @@ export async function issueAndBookInvoice(
|
||||
const customLines = opts.customLines ?? null
|
||||
const id = invoice.id
|
||||
|
||||
// An invoice that chose a bank account freezes that account's payee now,
|
||||
// from the account as it is at issue; a chosen account that can no longer
|
||||
// be used blocks issue instead of silently printing the company default.
|
||||
const payeeSnapshot = await snapshotInvoicePayee(supabase, companyId, invoice as Invoice)
|
||||
if (!payeeSnapshot.ok) {
|
||||
return { ok: false, errorCode: payeeSnapshot.code, details: payeeSnapshot.details }
|
||||
}
|
||||
;(invoice as Invoice).payment_details = payeeSnapshot.payee
|
||||
|
||||
if (!hasRequiredInvoicePaymentAccount(settings, invoice as Invoice)) {
|
||||
return {
|
||||
ok: false,
|
||||
|
||||
@@ -93,10 +93,21 @@ export function normalizeInvoicePaymentAccount(
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The payee an invoice prints, in precedence order:
|
||||
* 1. `override`: the invoice's own frozen payee (invoices.payment_details,
|
||||
* written when the invoice chose a bank account and refreshed at issue).
|
||||
* 2. The company's payment account for the invoice currency
|
||||
* (company_settings.invoice_payment_accounts, mirrored from the default
|
||||
* cash account per currency since migration 20260903150000).
|
||||
* 3. For SEK only, the legacy flat bank columns.
|
||||
*/
|
||||
export function resolveInvoicePaymentAccount(
|
||||
company: CompanySettings,
|
||||
currency: Currency,
|
||||
override?: Partial<InvoicePaymentAccount> | null,
|
||||
): InvoicePaymentAccount | null {
|
||||
if (override) return normalizeInvoicePaymentAccount(override)
|
||||
const configured = company.invoice_payment_accounts?.[currency]
|
||||
if (configured) return normalizeInvoicePaymentAccount(configured)
|
||||
return currency === 'SEK' ? legacySekInvoicePaymentAccount(company) : null
|
||||
@@ -134,11 +145,12 @@ export function invoiceRequiresPaymentAccount(
|
||||
|
||||
export function hasRequiredInvoicePaymentAccount(
|
||||
company: CompanySettings,
|
||||
invoice: Pick<Invoice, 'credited_invoice_id' | 'currency' | 'document_type'>,
|
||||
invoice: Pick<Invoice, 'credited_invoice_id' | 'currency' | 'document_type'>
|
||||
& Partial<Pick<Invoice, 'payment_details'>>,
|
||||
): boolean {
|
||||
return !invoiceRequiresPaymentAccount(invoice)
|
||||
|| hasUsableInvoicePaymentAccount(
|
||||
resolveInvoicePaymentAccount(company, invoice.currency),
|
||||
resolveInvoicePaymentAccount(company, invoice.currency, invoice.payment_details ?? null),
|
||||
invoice.currency,
|
||||
)
|
||||
}
|
||||
@@ -190,10 +202,11 @@ export class InvoicePaymentAccountMissingError extends Error {
|
||||
export function assertInvoicePaymentAccountForRender(
|
||||
company: CompanySettings,
|
||||
currency: Currency,
|
||||
override?: Partial<InvoicePaymentAccount> | null,
|
||||
): void {
|
||||
if (
|
||||
!hasUsableInvoicePaymentAccount(
|
||||
resolveInvoicePaymentAccount(company, currency),
|
||||
resolveInvoicePaymentAccount(company, currency, override),
|
||||
currency,
|
||||
)
|
||||
) {
|
||||
@@ -203,13 +216,16 @@ export function assertInvoicePaymentAccountForRender(
|
||||
|
||||
/**
|
||||
* Return invoice render settings with only the matching payment account.
|
||||
* Foreign invoices never inherit the legacy SEK payment details.
|
||||
* Foreign invoices never inherit the legacy SEK payment details. `override`
|
||||
* is the invoice's own frozen payee (invoices.payment_details) when it chose
|
||||
* a bank account; the templates keep reading company.bankgiro etc.
|
||||
*/
|
||||
export function companyWithInvoicePaymentAccount(
|
||||
company: CompanySettings,
|
||||
currency: Currency,
|
||||
override?: Partial<InvoicePaymentAccount> | null,
|
||||
): CompanySettings {
|
||||
const account = resolveInvoicePaymentAccount(company, currency)
|
||||
const account = resolveInvoicePaymentAccount(company, currency, override)
|
||||
const updates = Object.fromEntries(
|
||||
PAYMENT_FIELDS.map((field) => [field, account?.[field] ?? null]),
|
||||
) as Pick<CompanySettings, keyof InvoicePaymentAccount>
|
||||
|
||||
@@ -20,7 +20,7 @@
|
||||
*/
|
||||
|
||||
import QRCode from 'qrcode'
|
||||
import type { CompanySettings, Currency, Invoice } from '@/types'
|
||||
import type { CompanySettings, Currency, Invoice, InvoicePaymentAccount } from '@/types'
|
||||
import { brandingFromCompanySettings, SHOW_SWISH_ON_INVOICE, type InvoiceBranding } from '@/lib/invoices/pdf-template'
|
||||
import { buildSwishQrPayload } from '@/lib/payments/swish'
|
||||
import { getAmountToPay } from '@/lib/invoices/rounding'
|
||||
@@ -53,6 +53,11 @@ export interface InvoicePdfRenderExtras {
|
||||
|
||||
export interface InvoicePdfRenderOptions {
|
||||
paymentAccountRequired?: boolean
|
||||
/**
|
||||
* The invoice's own frozen payee (invoices.payment_details) when it chose
|
||||
* a bank account. Null/undefined = the company's default for the currency.
|
||||
*/
|
||||
payee?: Partial<InvoicePaymentAccount> | null
|
||||
}
|
||||
|
||||
// A company's logo is reused across every invoice render, and twice per send
|
||||
@@ -236,14 +241,14 @@ export async function prepareInvoicePdfRender(
|
||||
options: InvoicePdfRenderOptions = {},
|
||||
): Promise<InvoicePdfRenderExtras> {
|
||||
if (currency && options.paymentAccountRequired !== false) {
|
||||
assertInvoicePaymentAccountForRender(company, currency)
|
||||
assertInvoicePaymentAccountForRender(company, currency, options.payee ?? null)
|
||||
}
|
||||
const branding = await prepareInvoiceFont(
|
||||
company,
|
||||
brandingFromCompanySettings(company),
|
||||
)
|
||||
const paymentCompany = currency
|
||||
? companyWithInvoicePaymentAccount(company, currency)
|
||||
? companyWithInvoicePaymentAccount(company, currency, options.payee ?? null)
|
||||
: company
|
||||
if (!paymentCompany.logo_url) return { branding, company: paymentCompany }
|
||||
|
||||
|
||||
@@ -5,6 +5,7 @@ import {
|
||||
validatePlusgiroNumber,
|
||||
} from '@/lib/bankgiro/luhn'
|
||||
import { isSaneDateString, normalizeOrgNumber } from '@/lib/invariants'
|
||||
import { resolveInvoicePaymentAccount } from '@/lib/invoices/payment-accounts'
|
||||
import { computeLineAmounts, hasLineDiscount } from '@/lib/invoices/line-amounts'
|
||||
import { getDisplayTotal } from '@/lib/invoices/rounding'
|
||||
import { equalOre, roundOre } from '@/lib/money'
|
||||
@@ -326,16 +327,19 @@ function prepareInvoice(input: PeppolInvoiceInput):
|
||||
phone: customer.phone,
|
||||
}, false, issues)
|
||||
|
||||
// Same payee the PDF and the email print: the resolver, not the raw legacy
|
||||
// columns. Peppol is SEK-only (validated above), so resolve for SEK.
|
||||
const payee = resolveInvoicePaymentAccount(company, 'SEK', invoice.payment_details ?? null)
|
||||
let payment: PreparedInvoice['payment'] | null = null
|
||||
if (hasText(company.bankgiro) && validateBankgiroNumber(company.bankgiro)) {
|
||||
if (hasText(payee?.bankgiro) && validateBankgiroNumber(payee.bankgiro)) {
|
||||
payment = {
|
||||
accountId: company.bankgiro.replace(/\D/g, ''),
|
||||
accountId: payee.bankgiro.replace(/\D/g, ''),
|
||||
branchId: 'SE:BANKGIRO',
|
||||
paymentId: generateOcrReference(invoice.invoice_number ?? ''),
|
||||
}
|
||||
} else if (hasText(company.plusgiro) && validatePlusgiroNumber(company.plusgiro)) {
|
||||
} else if (hasText(payee?.plusgiro) && validatePlusgiroNumber(payee.plusgiro)) {
|
||||
payment = {
|
||||
accountId: company.plusgiro.replace(/\D/g, ''),
|
||||
accountId: payee.plusgiro.replace(/\D/g, ''),
|
||||
branchId: 'SE:PLUSGIRO',
|
||||
paymentId: generateOcrReference(invoice.invoice_number ?? ''),
|
||||
}
|
||||
|
||||
@@ -53,6 +53,7 @@ import {
|
||||
import {
|
||||
hasRequiredInvoicePaymentAccount,
|
||||
} from '@/lib/invoices/payment-accounts'
|
||||
import { snapshotInvoicePayee } from '@/lib/invoices/invoice-payee'
|
||||
import { hasRequiredSellerVatNumber } from '@/lib/invoices/seller-vat-number'
|
||||
import { createLogger } from '@/lib/logger'
|
||||
import type {
|
||||
@@ -575,6 +576,15 @@ async function sendInvoiceFromSchedule(
|
||||
if (!company) {
|
||||
throw new Error('company settings missing: cannot send invoice')
|
||||
}
|
||||
const payeeSnapshot = await snapshotInvoicePayee(supabase, companyId, invoice)
|
||||
if (!payeeSnapshot.ok) {
|
||||
log.warn('chosen payee account is no longer usable; recurring schedule cannot auto-send', {
|
||||
invoiceId: invoice.id,
|
||||
...payeeSnapshot.details,
|
||||
})
|
||||
return false
|
||||
}
|
||||
invoice.payment_details = payeeSnapshot.payee
|
||||
if (!hasRequiredInvoicePaymentAccount(company, invoice)) {
|
||||
log.warn('invoice currency has no usable payment account; recurring schedule cannot auto-send', {
|
||||
invoiceId: invoice.id,
|
||||
@@ -647,6 +657,7 @@ async function sendInvoiceFromSchedule(
|
||||
const { branding, company: renderCompany } = await prepareInvoicePdfRender(
|
||||
company,
|
||||
renderableInvoice.currency,
|
||||
{ payee: renderableInvoice.payment_details ?? null },
|
||||
)
|
||||
const swishQrDataUrl = await buildSwishQrDataUrl(renderCompany, renderableInvoice)
|
||||
const paymentLinkQrDataUrl = await buildPaymentLinkQrDataUrl(renderableInvoice)
|
||||
|
||||
@@ -129,7 +129,7 @@ export async function sendReminder(
|
||||
// with no payment account for the invoice currency would print nothing to
|
||||
// pay to, or (before this gate) the SEK account's IBAN on a EUR invoice.
|
||||
const currency = invoice.currency
|
||||
if (!hasUsableInvoicePaymentAccount(resolveInvoicePaymentAccount(company, currency), currency)) {
|
||||
if (!hasUsableInvoicePaymentAccount(resolveInvoicePaymentAccount(company, currency, invoice.payment_details ?? null), currency)) {
|
||||
log.warn('Skipping reminder: no payment account configured for invoice currency', {
|
||||
invoiceId: invoice.id,
|
||||
invoiceNumber: invoice.invoice_number,
|
||||
@@ -306,7 +306,7 @@ export async function processOverdueReminders(): Promise<ProcessRemindersResult>
|
||||
const invoiceCurrency = invoice.currency
|
||||
if (
|
||||
!hasUsableInvoicePaymentAccount(
|
||||
resolveInvoicePaymentAccount(company as CompanySettings, invoiceCurrency),
|
||||
resolveInvoicePaymentAccount(company as CompanySettings, invoiceCurrency, invoice.payment_details ?? null),
|
||||
invoiceCurrency,
|
||||
)
|
||||
) {
|
||||
|
||||
@@ -1,6 +1,13 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import type { PendingOperation } from '@/types'
|
||||
import { createQueuedMockSupabase } from '@/tests/helpers'
|
||||
|
||||
// The payee write-through is its own unit (lib/cash-accounts/__tests__/invoice-payee.test.ts);
|
||||
// here it must not consume the queued company_settings results.
|
||||
vi.mock('@/lib/cash-accounts/invoice-payee', () => ({
|
||||
propagateLegacyPayeeWrite: vi.fn().mockResolvedValue(['SEK']),
|
||||
}))
|
||||
|
||||
import { commitPendingOperation } from '../commit'
|
||||
|
||||
function makePendingOp(params: Record<string, unknown>): PendingOperation {
|
||||
|
||||
@@ -59,6 +59,7 @@ import { buildInvoicePaymentClearingLines } from '@/lib/bookkeeping/invoice-paym
|
||||
import { resolveSekAmount } from '@/lib/bookkeeping/currency-utils'
|
||||
import { booksInvoicesOnIssue, cashPartialBlockReason, supplierCreditNoteNeedsJournalEntry } from '@/lib/bookkeeping/booking-mode'
|
||||
import { ensureManualCashAccount } from '@/lib/cash-accounts/service'
|
||||
import { propagateLegacyPayeeWrite } from '@/lib/cash-accounts/invoice-payee'
|
||||
import { createJournalEntry, findFiscalPeriod, getSwedishLocalDate, reverseEntry, validateBalance } from '@/lib/bookkeeping/engine'
|
||||
import {
|
||||
canApproveSupplierInvoice,
|
||||
@@ -135,6 +136,7 @@ import { linkToJournalEntry } from '@/lib/core/documents/document-service'
|
||||
import { renderToBuffer } from '@react-pdf/renderer'
|
||||
import { InvoicePDF } from '@/lib/invoices/pdf-template'
|
||||
import { prepareInvoicePdfRender, buildSwishQrDataUrl } from '@/lib/invoices/pdf-render-helpers'
|
||||
import { resolveInvoicePayeeChoice, resolveInvoiceSettlementAccount, snapshotInvoicePayee } from '@/lib/invoices/invoice-payee'
|
||||
import {
|
||||
describeMissingInvoicePaymentAccount,
|
||||
hasRequiredInvoicePaymentAccount,
|
||||
@@ -703,7 +705,17 @@ async function commitUpdateCompanySettings(
|
||||
throw err
|
||||
}
|
||||
|
||||
const { data, error } = await supabase
|
||||
// The bank columns mirror the default SEK payee account (migration
|
||||
// 20260903150000): write the change through FIRST so a failure leaves
|
||||
// nothing half-written, and the invoice PDF prints what the agent set.
|
||||
try {
|
||||
await propagateLegacyPayeeWrite(supabase, companyId, validated.changes)
|
||||
} catch (err) {
|
||||
log.error('update_company_settings: payee write-through failed', err as Error)
|
||||
return { error: err instanceof Error ? err.message : 'Payee write-through failed', status: 500 }
|
||||
}
|
||||
|
||||
const { data: row, error } = await supabase
|
||||
.from('company_settings')
|
||||
.update(validated.changes)
|
||||
.eq('company_id', companyId)
|
||||
@@ -717,22 +729,23 @@ async function commitUpdateCompanySettings(
|
||||
return { error: error.message, status: 500 }
|
||||
}
|
||||
|
||||
|
||||
return {
|
||||
data: {
|
||||
company_id: companyId,
|
||||
bank_name: data.bank_name ?? null,
|
||||
clearing_number: data.clearing_number ?? null,
|
||||
account_number: data.account_number ?? null,
|
||||
bankgiro: data.bankgiro ?? null,
|
||||
plusgiro: data.plusgiro ?? null,
|
||||
swish: data.swish ?? null,
|
||||
iban: data.iban ?? null,
|
||||
bic: data.bic ?? null,
|
||||
contact_person: data.default_our_reference ?? null,
|
||||
email: data.email ?? null,
|
||||
phone: data.phone ?? null,
|
||||
website: data.website ?? null,
|
||||
invoice_email_texts: data.invoice_email_texts ?? null,
|
||||
bank_name: row.bank_name ?? null,
|
||||
clearing_number: row.clearing_number ?? null,
|
||||
account_number: row.account_number ?? null,
|
||||
bankgiro: row.bankgiro ?? null,
|
||||
plusgiro: row.plusgiro ?? null,
|
||||
swish: row.swish ?? null,
|
||||
iban: row.iban ?? null,
|
||||
bic: row.bic ?? null,
|
||||
contact_person: row.default_our_reference ?? null,
|
||||
email: row.email ?? null,
|
||||
phone: row.phone ?? null,
|
||||
website: row.website ?? null,
|
||||
invoice_email_texts: row.invoice_email_texts ?? null,
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -2123,6 +2136,19 @@ async function commitCreateInvoice(
|
||||
quoteNumber = allocated as string
|
||||
}
|
||||
|
||||
// Which bank account the customer pays to; validated against the
|
||||
// company's payee accounts (same rule as the web and v1 routes).
|
||||
const payeeChoice = await resolveInvoicePayeeChoice(
|
||||
supabase,
|
||||
companyId,
|
||||
currency as Currency,
|
||||
typeof params.payment_cash_account_id === 'string' ? params.payment_cash_account_id : null,
|
||||
)
|
||||
if (!payeeChoice.ok) {
|
||||
const entry = getErrorEntry(payeeChoice.code)
|
||||
return { error: entry?.message_sv ?? payeeChoice.code, status: 400, data: payeeChoice.details }
|
||||
}
|
||||
|
||||
const { data: invoice, error: invoiceError } = await supabase
|
||||
.from('invoices')
|
||||
.insert({
|
||||
@@ -2165,6 +2191,8 @@ async function commitCreateInvoice(
|
||||
notes: (params.notes as string) || null,
|
||||
payment_link_url: paymentLinkUrl,
|
||||
default_dimensions: defaultDimensions ?? {},
|
||||
payment_cash_account_id: payeeChoice.fields.payment_cash_account_id,
|
||||
payment_details: payeeChoice.fields.payment_details,
|
||||
})
|
||||
.select()
|
||||
.single()
|
||||
@@ -2637,14 +2665,19 @@ async function commitMarkInvoicePaid(
|
||||
}
|
||||
|
||||
if (isRealInvoice) {
|
||||
// Debit the bank account the invoice asked to be paid to (1930 when none
|
||||
// was chosen): an agent marking a 1931-invoice paid must not land it on 1930.
|
||||
const settlementAccountNumber = await resolveInvoiceSettlementAccount(supabase, companyId, invoice as Invoice)
|
||||
if (useCashEntry) {
|
||||
const je = await createInvoiceCashEntry(
|
||||
supabase, companyId, userId, invoice as Invoice, paymentDate, entityType, invoice.customer?.name
|
||||
supabase, companyId, userId, invoice as Invoice, paymentDate, entityType, invoice.customer?.name,
|
||||
settlementAccountNumber,
|
||||
)
|
||||
journalEntryId = je?.id ?? null
|
||||
} else {
|
||||
const je = await createInvoicePaymentJournalEntry(
|
||||
supabase, companyId, userId, invoice as Invoice, paymentDate, undefined, invoice.customer?.name
|
||||
supabase, companyId, userId, invoice as Invoice, paymentDate, undefined, invoice.customer?.name,
|
||||
undefined, settlementAccountNumber,
|
||||
)
|
||||
journalEntryId = je?.id ?? null
|
||||
}
|
||||
@@ -2841,6 +2874,15 @@ async function commitSendInvoice(
|
||||
if (companyError || !company) return { error: 'Company settings missing', status: 500 }
|
||||
|
||||
const paymentAccountRequired = invoiceRequiresPaymentAccount(invoice as Invoice)
|
||||
// Freeze the chosen bank account's payee at issue (no-op without a choice).
|
||||
const payeeSnapshot = await snapshotInvoicePayee(supabase, companyId, invoice as Invoice)
|
||||
if (!payeeSnapshot.ok) {
|
||||
return {
|
||||
error: getErrorEntry(payeeSnapshot.code)?.message_sv ?? 'Bankkontot på fakturan kan inte längre användas.',
|
||||
status: 400,
|
||||
}
|
||||
}
|
||||
;(invoice as Invoice).payment_details = payeeSnapshot.payee
|
||||
if (!hasRequiredInvoicePaymentAccount(company as CompanySettings, invoice as Invoice)) {
|
||||
return {
|
||||
error: describeMissingInvoicePaymentAccount((invoice as Invoice).currency).sv,
|
||||
@@ -2897,7 +2939,7 @@ async function commitSendInvoice(
|
||||
const preflight = await prepareInvoicePdfRender(
|
||||
company as CompanySettings,
|
||||
(invoice as Invoice).currency,
|
||||
{ paymentAccountRequired },
|
||||
{ paymentAccountRequired, payee: (invoice as Invoice).payment_details ?? null },
|
||||
)
|
||||
await renderToBuffer(
|
||||
InvoicePDF({
|
||||
@@ -2954,7 +2996,7 @@ async function commitSendInvoice(
|
||||
const { branding, company: renderCompany } = await prepareInvoicePdfRender(
|
||||
company as CompanySettings,
|
||||
renderableInvoice.currency,
|
||||
{ paymentAccountRequired },
|
||||
{ paymentAccountRequired, payee: (invoice as Invoice).payment_details ?? null },
|
||||
)
|
||||
const swishQrDataUrl = await buildSwishQrDataUrl(renderCompany, renderableInvoice)
|
||||
const pdfBuffer = await renderToBuffer(
|
||||
@@ -3096,6 +3138,14 @@ async function commitMarkInvoiceSent(
|
||||
|
||||
if (settingsError || !settings) return { error: 'Company settings missing', status: 500 }
|
||||
|
||||
const payeeSnapshot = await snapshotInvoicePayee(supabase, companyId, invoice as Invoice)
|
||||
if (!payeeSnapshot.ok) {
|
||||
return {
|
||||
error: getErrorEntry(payeeSnapshot.code)?.message_sv ?? 'Bankkontot på fakturan kan inte längre användas.',
|
||||
status: 400,
|
||||
}
|
||||
}
|
||||
;(invoice as Invoice).payment_details = payeeSnapshot.payee
|
||||
if (!hasRequiredInvoicePaymentAccount(settings as CompanySettings, invoice as Invoice)) {
|
||||
return {
|
||||
error: describeMissingInvoicePaymentAccount((invoice as Invoice).currency).sv,
|
||||
|
||||
@@ -213,6 +213,9 @@ export const AUDITED_TABLES = [
|
||||
// the per-account override outranks the per-source-type map above, so it is
|
||||
// a behandlingsregel in the same sense.
|
||||
'cash_accounts',
|
||||
// Which bank account customer invoices pay to, per currency (migration
|
||||
// 20260903150000).
|
||||
'invoice_payee_defaults',
|
||||
] as const
|
||||
|
||||
/**
|
||||
@@ -236,7 +239,7 @@ export const GLOBAL_ACTIONS = [
|
||||
* names statically; a unit test pins it to AUDITED_TABLES / GLOBAL_ACTIONS.
|
||||
*/
|
||||
export const AUDIT_ROW_FILTER =
|
||||
'table_name.in.(journal_entries,chart_of_accounts,company_settings,fiscal_periods,api_keys,dimensions,dimension_values,account_dimension_rules,accrual_schedules,document_attachments,mapping_rules,categorization_templates,booking_template_library,sie_imports,bank_file_imports,cash_accounts),action.in.(SECURITY_EVENT,INTEGRITY_FAILURE,RETENTION_BLOCK,DOCUMENT_DELETE_BLOCKED)'
|
||||
'table_name.in.(journal_entries,chart_of_accounts,company_settings,fiscal_periods,api_keys,dimensions,dimension_values,account_dimension_rules,accrual_schedules,document_attachments,mapping_rules,categorization_templates,booking_template_library,sie_imports,bank_file_imports,cash_accounts,invoice_payee_defaults),action.in.(SECURITY_EVENT,INTEGRITY_FAILURE,RETENTION_BLOCK,DOCUMENT_DELETE_BLOCKED)'
|
||||
|
||||
const SOURCE_TYPE_LABELS: Record<string, string> = {
|
||||
manual: 'Manuell',
|
||||
@@ -422,6 +425,22 @@ const MAPPING_RULE_FIELDS: Record<string, string> = {
|
||||
*/
|
||||
const CASH_ACCOUNT_FIELDS: Record<string, string> = {
|
||||
voucher_series: 'Verifikationsserie',
|
||||
// Payee fields (migration 20260903150000): what customer invoices print.
|
||||
bank_name: 'Bank',
|
||||
clearing_number: 'Clearingnummer',
|
||||
account_number: 'Kontonummer',
|
||||
bankgiro: 'Bankgiro',
|
||||
plusgiro: 'Plusgiro',
|
||||
swish: 'Swish',
|
||||
iban: 'IBAN',
|
||||
bic: 'BIC/SWIFT',
|
||||
bank_code: 'Bankkod',
|
||||
foreign_account_number: 'Kontonummer (utländskt)',
|
||||
invoice_payee: 'Visas på kundfakturor',
|
||||
}
|
||||
|
||||
const INVOICE_PAYEE_DEFAULT_FIELDS: Record<string, string> = {
|
||||
cash_account_id: 'Bankkonto',
|
||||
}
|
||||
|
||||
const CATEGORIZATION_TEMPLATE_FIELDS: Record<string, string> = {
|
||||
@@ -1149,6 +1168,16 @@ export function auditRowToEvent(
|
||||
fields: CASH_ACCOUNT_FIELDS,
|
||||
objectKeys: ['name', 'ledger_account'],
|
||||
})
|
||||
case 'invoice_payee_defaults':
|
||||
return genericAuditEvent(row, {
|
||||
category: 'installningar',
|
||||
codePrefix: 'invoice_payee_default',
|
||||
noun: 'Standardkonto för kundfakturor',
|
||||
fields: INVOICE_PAYEE_DEFAULT_FIELDS,
|
||||
// Both keys on every action: a created or deleted default must name
|
||||
// the account, not just the currency.
|
||||
objectKeys: ['currency', 'cash_account_id'],
|
||||
})
|
||||
case 'salary_payroll_config':
|
||||
return payrollConfigAuditEvent(row)
|
||||
// The import tables emit their own events from the rows themselves; the
|
||||
@@ -1605,7 +1634,7 @@ async function fetchAuditRows(
|
||||
// Literal on purpose (not AUDIT_ROW_FILTER): the schema guard only
|
||||
// resolves string literals here. A test pins the two to each other.
|
||||
.or(
|
||||
'table_name.in.(journal_entries,chart_of_accounts,company_settings,fiscal_periods,api_keys,dimensions,dimension_values,account_dimension_rules,accrual_schedules,document_attachments,mapping_rules,categorization_templates,booking_template_library,sie_imports,bank_file_imports,cash_accounts),action.in.(SECURITY_EVENT,INTEGRITY_FAILURE,RETENTION_BLOCK,DOCUMENT_DELETE_BLOCKED)',
|
||||
'table_name.in.(journal_entries,chart_of_accounts,company_settings,fiscal_periods,api_keys,dimensions,dimension_values,account_dimension_rules,accrual_schedules,document_attachments,mapping_rules,categorization_templates,booking_template_library,sie_imports,bank_file_imports,cash_accounts,invoice_payee_defaults),action.in.(SECURITY_EVENT,INTEGRITY_FAILURE,RETENTION_BLOCK,DOCUMENT_DELETE_BLOCKED)',
|
||||
)
|
||||
.order('created_at', { ascending: true })
|
||||
.order('id', { ascending: true })
|
||||
|
||||
@@ -1079,6 +1079,9 @@ export const MASTER_DATA_DUMP_TABLES: MasterDataTableSpec[] = [
|
||||
{ name: 'transaction_voucher_links', file: 'transaction_voucher_links.json' },
|
||||
{ name: 'bank_file_imports', file: 'bank_file_imports.json', orderBy: 'created_at' },
|
||||
{ name: 'cash_accounts', file: 'cash_accounts.json' },
|
||||
// Which bank account customer invoices pay to, per currency; the payee
|
||||
// fields themselves are columns on cash_accounts one file up.
|
||||
{ name: 'invoice_payee_defaults', file: 'invoice_payee_defaults.json' },
|
||||
{ name: 'mapping_rules', file: 'mapping_rules.json' },
|
||||
{ name: 'categorization_templates', file: 'categorization_templates.json' },
|
||||
{ name: 'booking_template_library', file: 'booking_template_library.json' },
|
||||
|
||||
+40
-24
@@ -26,8 +26,7 @@
|
||||
"theme_system": "System",
|
||||
"logout": "Sign out",
|
||||
"logout_description": "Sign out of your account",
|
||||
"status": {
|
||||
},
|
||||
"status": {},
|
||||
"more_options": "More options",
|
||||
"popup_blocked_description": "Allow pop-ups for {appName} in your browser and try again.",
|
||||
"source_code": "Source code"
|
||||
@@ -2283,15 +2282,33 @@
|
||||
"try_again": "Try again."
|
||||
},
|
||||
"settings_invoice_payment_accounts": {
|
||||
"heading": "Payment accounts by currency",
|
||||
"description": "The invoice automatically shows the account matching its currency. A foreign-currency account must have an IBAN, or for USD/GBP a bank code, account number and BIC/SWIFT, before the invoice can be sent.",
|
||||
"currency_tabs_label": "Configured currencies",
|
||||
"heading": "Bank accounts for customer invoices",
|
||||
"description": "Each bank account can carry its own payment details (bankgiro, plusgiro, account number, IBAN, Swish). Per currency you choose which account an invoice shows by default; on the invoice you can pick another. A foreign-currency account needs an IBAN, or for USD/GBP a bank code, account number and BIC/SWIFT.",
|
||||
"loading": "Loading bank accounts",
|
||||
"load_failed": "Could not load bank accounts",
|
||||
"empty": "No bank accounts yet. Add one below or connect a bank.",
|
||||
"no_payee_details": "No payment details",
|
||||
"default_for": "Default for {currencies}",
|
||||
"hidden_on_invoices": "Not shown on invoices",
|
||||
"edit": "Edit",
|
||||
"cancel": "Cancel",
|
||||
"name_label": "Name",
|
||||
"name_placeholder": "E.g. Business account SEB",
|
||||
"currency_label": "Currency",
|
||||
"saving": "Saving...",
|
||||
"save_account": "Save account",
|
||||
"create_account": "Add account",
|
||||
"add_account": "Add bank account",
|
||||
"defaults_heading": "Default account per currency",
|
||||
"default_label": "Default {currency}",
|
||||
"default_none": "None",
|
||||
"default_unlinked_option": "Saved details without an account",
|
||||
"unlinked_hint": "Payment details for {currency} were saved before accounts existed. Pick an account to move them there.",
|
||||
"no_usable_sek": "No account has payment details yet. Edit an account above.",
|
||||
"no_usable_foreign": "No account has an IBAN (or bank code, account number and BIC) for {currency}.",
|
||||
"add_currency_label": "Add currency",
|
||||
"add_currency_placeholder": "Select currency",
|
||||
"add_currency": "Add account",
|
||||
"account_heading": "Payment account for {currency}",
|
||||
"foreign_account_hint": "This account is only used on invoices in {currency}.",
|
||||
"remove_currency": "Remove account",
|
||||
"add_currency": "Add",
|
||||
"bank_label": "Bank",
|
||||
"clearing_label": "Clearing number",
|
||||
"account_number_label": "Account number",
|
||||
@@ -2300,15 +2317,14 @@
|
||||
"plusgiro_label": "Plusgiro",
|
||||
"swish_label": "Swish",
|
||||
"iban_label": "IBAN",
|
||||
"iban_prefill": "Use the IBAN from your bank connection: {value}",
|
||||
"bic_label": "BIC/SWIFT",
|
||||
"routing_number": "Routing number (ABA)",
|
||||
"sort_code": "Sort code",
|
||||
"bank_code": "Bank code",
|
||||
"foreign_account_number_label": "Account number (foreign)",
|
||||
"non_iban_hint": "{currency} accounts often have no IBAN. Enter the bank code, account number and BIC/SWIFT instead; IBAN can be left empty.",
|
||||
"required_suffix": "(required)",
|
||||
"validation_title": "Check the payment account",
|
||||
"validation_title": "Check the payment details",
|
||||
"validation_name": "Enter a name for the account.",
|
||||
"validation_clearing": "The clearing number for {currency} must contain 4 to 5 digits.",
|
||||
"validation_account_number": "The account number for {currency} must contain 6 to 12 digits.",
|
||||
"validation_bankgiro": "The bankgiro number for {currency} is invalid.",
|
||||
@@ -2316,19 +2332,16 @@
|
||||
"validation_swish": "The Swish number for {currency} is invalid.",
|
||||
"validation_iban": "The IBAN for {currency} is invalid.",
|
||||
"validation_bic": "The BIC/SWIFT for {currency} is invalid.",
|
||||
"validation_foreign_iban": "Enter an IBAN for the {currency} payment account.",
|
||||
"validation_foreign_non_iban": "Enter an IBAN, or a bank code, account number and BIC/SWIFT, for the {currency} payment account.",
|
||||
"validation_foreign_iban": "Enter an IBAN for the {currency} account.",
|
||||
"validation_foreign_non_iban": "Enter an IBAN, or a bank code, account number and BIC/SWIFT, for the {currency} account.",
|
||||
"validation_bank_code": "The bank code for {currency} is invalid.",
|
||||
"validation_foreign_account_number": "The account number for {currency} is invalid.",
|
||||
"conflict_title": "Payment accounts changed elsewhere",
|
||||
"conflict_description": "Reload the latest saved values before saving. Your unsaved edits will be discarded.",
|
||||
"reload_server_values": "Reload saved values",
|
||||
"save_failed": "Could not save the payment accounts",
|
||||
"save_failed_title": "Could not save payment accounts",
|
||||
"saved_title": "Payment accounts saved",
|
||||
"saved_description": "New invoices use the account matching the invoice currency.",
|
||||
"saving": "Saving...",
|
||||
"save": "Save payment accounts"
|
||||
"saved_title": "Saved",
|
||||
"saved_account": "Payment details for {account} are saved.",
|
||||
"saved_default": "Invoices in {currency} now show {account}.",
|
||||
"cleared_default": "Invoices in {currency} no longer have a default account.",
|
||||
"save_failed_title": "Could not save",
|
||||
"iban_prefill": "Use the IBAN from your bank connection: {value}"
|
||||
},
|
||||
"settings_period_locking": {
|
||||
"heading": "Period locking",
|
||||
@@ -3806,7 +3819,10 @@
|
||||
"to_pay_label": "Amount to pay",
|
||||
"total_incl_vat_label": "Total incl. VAT",
|
||||
"review_customer_missing_title": "Customer details could not be loaded",
|
||||
"review_customer_missing_description": "Reload the page and try again. Contact support if the problem persists."
|
||||
"review_customer_missing_description": "Reload the page and try again. Contact support if the problem persists.",
|
||||
"payee_account_label": "Pay to",
|
||||
"payee_account_default": "Default: {account}",
|
||||
"payee_account_default_none": "Company default account"
|
||||
},
|
||||
"invoice_review": {
|
||||
"forval_currency": "Currency {currency}",
|
||||
|
||||
+40
-24
@@ -26,8 +26,7 @@
|
||||
"theme_system": "System",
|
||||
"logout": "Logga ut",
|
||||
"logout_description": "Logga ut från ditt konto",
|
||||
"status": {
|
||||
},
|
||||
"status": {},
|
||||
"more_options": "Fler alternativ",
|
||||
"popup_blocked_description": "Tillåt popupfönster för {appName} i webbläsaren och försök igen.",
|
||||
"source_code": "Källkod"
|
||||
@@ -2283,15 +2282,33 @@
|
||||
"try_again": "Försök igen."
|
||||
},
|
||||
"settings_invoice_payment_accounts": {
|
||||
"heading": "Betalningskonton per valuta",
|
||||
"description": "Fakturan visar automatiskt kontot som matchar fakturans valuta. Ett utländskt konto måste ha IBAN, eller för USD/GBP bankkod, kontonummer och BIC/SWIFT, för att fakturan ska kunna skickas.",
|
||||
"currency_tabs_label": "Konfigurerade valutor",
|
||||
"heading": "Bankkonton för kundfakturor",
|
||||
"description": "Varje bankkonto kan ha egna betaluppgifter (bankgiro, plusgiro, kontonummer, IBAN, Swish). Per valuta väljer du vilket konto en faktura visar som standard; i fakturan kan du välja ett annat. Ett konto för utländsk valuta behöver IBAN, eller för USD/GBP bankkod, kontonummer och BIC/SWIFT.",
|
||||
"loading": "Hämtar bankkonton",
|
||||
"load_failed": "Kunde inte hämta bankkonton",
|
||||
"empty": "Inga bankkonton ännu. Lägg till ett nedan eller koppla en bank.",
|
||||
"no_payee_details": "Inga betaluppgifter",
|
||||
"default_for": "Standard för {currencies}",
|
||||
"hidden_on_invoices": "Visas inte på fakturor",
|
||||
"edit": "Redigera",
|
||||
"cancel": "Avbryt",
|
||||
"name_label": "Namn",
|
||||
"name_placeholder": "T.ex. Företagskonto SEB",
|
||||
"currency_label": "Valuta",
|
||||
"saving": "Sparar...",
|
||||
"save_account": "Spara konto",
|
||||
"create_account": "Lägg till konto",
|
||||
"add_account": "Lägg till bankkonto",
|
||||
"defaults_heading": "Standardkonto per valuta",
|
||||
"default_label": "Standard {currency}",
|
||||
"default_none": "Inget",
|
||||
"default_unlinked_option": "Sparade uppgifter utan konto",
|
||||
"unlinked_hint": "Betaluppgifter för {currency} sparades innan konton fanns. Välj ett konto så flyttas de dit.",
|
||||
"no_usable_sek": "Inget konto har betaluppgifter ännu. Redigera ett konto ovan.",
|
||||
"no_usable_foreign": "Inget konto har IBAN (eller bankkod, kontonummer och BIC) för {currency}.",
|
||||
"add_currency_label": "Lägg till valuta",
|
||||
"add_currency_placeholder": "Välj valuta",
|
||||
"add_currency": "Lägg till konto",
|
||||
"account_heading": "Betalningskonto för {currency}",
|
||||
"foreign_account_hint": "Detta konto används bara på fakturor i {currency}.",
|
||||
"remove_currency": "Ta bort konto",
|
||||
"add_currency": "Lägg till",
|
||||
"bank_label": "Bank",
|
||||
"clearing_label": "Clearingnummer",
|
||||
"account_number_label": "Kontonummer",
|
||||
@@ -2300,15 +2317,14 @@
|
||||
"plusgiro_label": "Plusgiro",
|
||||
"swish_label": "Swish",
|
||||
"iban_label": "IBAN",
|
||||
"iban_prefill": "Hämta från bankkopplingen: {value}",
|
||||
"bic_label": "BIC/SWIFT",
|
||||
"routing_number": "Routing number (ABA)",
|
||||
"sort_code": "Sort code",
|
||||
"bank_code": "Bankkod",
|
||||
"foreign_account_number_label": "Kontonummer (utländskt)",
|
||||
"non_iban_hint": "Konton i {currency} saknar ofta IBAN. Ange då bankkod, kontonummer och BIC/SWIFT i stället; IBAN kan lämnas tomt.",
|
||||
"required_suffix": "(obligatoriskt)",
|
||||
"validation_title": "Kontrollera betalningskontot",
|
||||
"validation_title": "Kontrollera betaluppgifterna",
|
||||
"validation_name": "Ange ett namn på kontot.",
|
||||
"validation_clearing": "Clearingnumret för {currency} måste vara 4 till 5 siffror.",
|
||||
"validation_account_number": "Kontonumret för {currency} måste vara 6 till 12 siffror.",
|
||||
"validation_bankgiro": "Bankgironumret för {currency} är ogiltigt.",
|
||||
@@ -2316,19 +2332,16 @@
|
||||
"validation_swish": "Swish-numret för {currency} är ogiltigt.",
|
||||
"validation_iban": "IBAN för {currency} är ogiltigt.",
|
||||
"validation_bic": "BIC/SWIFT för {currency} är ogiltigt.",
|
||||
"validation_foreign_iban": "Ange IBAN för betalningskontot i {currency}.",
|
||||
"validation_foreign_non_iban": "Ange IBAN, eller bankkod, kontonummer och BIC/SWIFT, för betalningskontot i {currency}.",
|
||||
"validation_foreign_iban": "Ange IBAN för kontot i {currency}.",
|
||||
"validation_foreign_non_iban": "Ange IBAN, eller bankkod, kontonummer och BIC/SWIFT, för kontot i {currency}.",
|
||||
"validation_bank_code": "Bankkoden för {currency} är ogiltig.",
|
||||
"validation_foreign_account_number": "Kontonumret för {currency} är ogiltigt.",
|
||||
"conflict_title": "Betalningskontona har ändrats någon annanstans",
|
||||
"conflict_description": "Läs in de senast sparade värdena innan du sparar. Dina osparade ändringar tas bort.",
|
||||
"reload_server_values": "Läs in sparade värden",
|
||||
"save_failed": "Kunde inte spara betalningskontona",
|
||||
"save_failed_title": "Kunde inte spara betalningskonton",
|
||||
"saved_title": "Betalningskonton sparade",
|
||||
"saved_description": "Nya fakturor använder kontot som matchar fakturans valuta.",
|
||||
"saving": "Sparar...",
|
||||
"save": "Spara betalningskonton"
|
||||
"saved_title": "Sparat",
|
||||
"saved_account": "Betaluppgifterna för {account} är sparade.",
|
||||
"saved_default": "Fakturor i {currency} visar nu {account}.",
|
||||
"cleared_default": "Fakturor i {currency} har inget standardkonto längre.",
|
||||
"save_failed_title": "Kunde inte spara",
|
||||
"iban_prefill": "Hämta från bankkopplingen: {value}"
|
||||
},
|
||||
"settings_period_locking": {
|
||||
"heading": "Periodlåsning",
|
||||
@@ -3806,7 +3819,10 @@
|
||||
"to_pay_label": "Att betala",
|
||||
"total_incl_vat_label": "Totalt inkl. moms",
|
||||
"review_customer_missing_title": "Kunduppgifterna kunde inte laddas",
|
||||
"review_customer_missing_description": "Ladda om sidan och försök igen. Kontakta support om det inte hjälper."
|
||||
"review_customer_missing_description": "Ladda om sidan och försök igen. Kontakta support om det inte hjälper.",
|
||||
"payee_account_label": "Betalas till",
|
||||
"payee_account_default": "Standard: {account}",
|
||||
"payee_account_default_none": "Företagets standardkonto"
|
||||
},
|
||||
"invoice_review": {
|
||||
"forval_currency": "Valuta {currency}",
|
||||
|
||||
@@ -128,6 +128,7 @@ Request body:
|
||||
external_invoice_number?: string | "",
|
||||
self_billing_agreement_ref?: string,
|
||||
received_date?: string | "",
|
||||
payment_cash_account_id?: string | "",
|
||||
items: { line_type?: "product" | "text", description: string, quantity: number, unit: string, unit_price: number, discount_percent?: number, vat_rate?: number, article_id?: string, revenue_account?: string, sales_order_item_id?: string, deduction_type?: "rot" | "rut", labor_hours?: number, work_type?: string, housing_designation?: string, apartment_number?: string, brf_org_number?: string | "", accrual_period_start?: string, accrual_period_end?: string, accrual_balance_account?: string, dimensions?: Record<string, string> }[]
|
||||
}
|
||||
```
|
||||
@@ -314,6 +315,7 @@ Request body:
|
||||
our_reference?: string | unknown,
|
||||
notes?: string | unknown,
|
||||
default_dimensions?: Record<string, string>,
|
||||
payment_cash_account_id?: string | unknown,
|
||||
items?: { line_type?: "product" | "text", description: string, quantity: number, unit: string, unit_price: number, discount_percent?: number, vat_rate?: number, article_id?: string, revenue_account?: string, sales_order_item_id?: string, deduction_type?: "rot" | "rut", labor_hours?: number, work_type?: string, housing_designation?: string, apartment_number?: string, brf_org_number?: string | "", accrual_period_start?: string, accrual_period_end?: string, accrual_balance_account?: string, dimensions?: Record<string, string> }[]
|
||||
}
|
||||
```
|
||||
@@ -868,7 +870,7 @@ Bulk-creation endpoint. Each invoice in the request array is validated and inser
|
||||
Request body:
|
||||
```ts
|
||||
{
|
||||
invoices: { customer_id: string, invoice_date: string, due_date: string, delivery_date?: string | "", currency: "SEK" | "EUR" | "USD" | "GBP" | "NOK" | "DKK", document_type?: "invoice" | "proforma" | "delivery_note" | "quote", valid_until?: string | "", your_reference?: string, our_reference?: string, invoice_marking?: string, notes?: string, payment_link_url?: string | "", payment_link_auto?: boolean, deduction_personnummer?: string, deduction_housing_designation?: string, deduction_apartment_number?: string, deduction_brf_org_number?: string | "", save_as_draft?: boolean, ore_rounding?: boolean, default_dimensions?: Record<string, string>, is_self_billed?: boolean, external_invoice_number?: string | "", self_billing_agreement_ref?: string, received_date?: string | "", items: { line_type?: "product" | "text", description: string, quantity: number, unit: string, unit_price: number, discount_percent?: number, vat_rate?: number, article_id?: string, revenue_account?: string, sales_order_item_id?: string, deduction_type?: "rot" | "rut", labor_hours?: number, work_type?: string, housing_designation?: string, apartment_number?: string, brf_org_number?: string | "", accrual_period_start?: string, accrual_period_end?: string, accrual_balance_account?: string, dimensions?: Record<string, string> }[] }[],
|
||||
invoices: { customer_id: string, invoice_date: string, due_date: string, delivery_date?: string | "", currency: "SEK" | "EUR" | "USD" | "GBP" | "NOK" | "DKK", document_type?: "invoice" | "proforma" | "delivery_note" | "quote", valid_until?: string | "", your_reference?: string, our_reference?: string, invoice_marking?: string, notes?: string, payment_link_url?: string | "", payment_link_auto?: boolean, deduction_personnummer?: string, deduction_housing_designation?: string, deduction_apartment_number?: string, deduction_brf_org_number?: string | "", save_as_draft?: boolean, ore_rounding?: boolean, default_dimensions?: Record<string, string>, is_self_billed?: boolean, external_invoice_number?: string | "", self_billing_agreement_ref?: string, received_date?: string | "", payment_cash_account_id?: string | "", items: { line_type?: "product" | "text", description: string, quantity: number, unit: string, unit_price: number, discount_percent?: number, vat_rate?: number, article_id?: string, revenue_account?: string, sales_order_item_id?: string, deduction_type?: "rot" | "rut", labor_hours?: number, work_type?: string, housing_designation?: string, apartment_number?: string, brf_org_number?: string | "", accrual_period_start?: string, accrual_period_end?: string, accrual_balance_account?: string, dimensions?: Record<string, string> }[] }[],
|
||||
all_or_nothing?: boolean
|
||||
}
|
||||
```
|
||||
|
||||
@@ -0,0 +1,484 @@
|
||||
-- Named invoice payee accounts.
|
||||
--
|
||||
-- Until now a company had exactly one set of payment instructions per invoice
|
||||
-- currency (company_settings.invoice_payment_accounts, keyed SEK/EUR/...), and
|
||||
-- the invoice picked them by currency alone. A company with two SEK bank
|
||||
-- accounts, or two bankgiro numbers, had nowhere to put the second one.
|
||||
--
|
||||
-- cash_accounts is already the per-company bank-account entity (name, IBAN,
|
||||
-- currency, ledger account, primary flag). This migration makes it the single
|
||||
-- source for what a customer pays to:
|
||||
--
|
||||
-- 1. Payee columns on cash_accounts (bankgiro, plusgiro, clearing + account,
|
||||
-- payee IBAN, BIC, Swish, foreign routing) plus invoice_payee: "may be
|
||||
-- printed on an invoice". The payee IBAN is its own column: cash_accounts.iban
|
||||
-- is the bank's identity of the account (written by every PSD2 sync and
|
||||
-- used to re-pair accounts on reconnect), while payee_iban is what the
|
||||
-- company chooses to print; a sync must never rewrite an invoice
|
||||
-- instruction, and a cleared payee IBAN must stay cleared.
|
||||
-- bg_pg (one text for both giro kinds) was never read or written anywhere
|
||||
-- and is dropped; verified NULL on every prod and staging row 2026-09-03.
|
||||
-- 2. invoice_payee_defaults: which cash account an invoice in a given
|
||||
-- currency prints when the invoice itself does not choose. One account
|
||||
-- may be the default for several currencies: a SEK account with an IBAN
|
||||
-- is the normal EUR payee, so "default for EUR must be an EUR account"
|
||||
-- would be wrong.
|
||||
-- 3. A mirror: whenever a default account or its payee fields change, the
|
||||
-- old company_settings.invoice_payment_accounts map and the legacy SEK
|
||||
-- columns are rewritten from it. Every existing reader (PDF, email,
|
||||
-- reminders, Peppol, v1 settings, MCP) keeps working unchanged, and the
|
||||
-- three writers that only touched the legacy columns can no longer
|
||||
-- drift from what the PDF prints.
|
||||
-- 4. Payee columns are admin-only at the database, not just in the routes:
|
||||
-- cash_accounts writes are member-level (bank sync touches them), but
|
||||
-- where customers are told to pay was admin-only before this migration
|
||||
-- (company_settings RLS) and must stay so. Revoking an account as payee
|
||||
-- (invoice_payee = false, admin-only) drops its defaults. Disabling an
|
||||
-- account (enabled = false, member-level: the bank picker's "Synkas ej")
|
||||
-- does not: a member must not be able to undo an admin's payee choice;
|
||||
-- the pick lists exclude disabled accounts and the send gate refuses an
|
||||
-- invoice that chose one.
|
||||
-- 5. Backfill from today's map onto existing cash accounts, copying each
|
||||
-- currency entry verbatim (the map entry wins over anything the account
|
||||
-- knew, including the IBAN): every invoice keeps printing exactly what
|
||||
-- it printed before. No rows are created: an entry with no matching
|
||||
-- account stays in the map as the fallback the resolver already honours.
|
||||
--
|
||||
-- The mirror runs SECURITY DEFINER because company_settings updates are
|
||||
-- admin-gated by RLS. The admin guard in (4) is what makes that safe: only an
|
||||
-- admin (or the service role) can change what the mirror derives from.
|
||||
|
||||
-- ============================================================
|
||||
-- 1. Payee columns
|
||||
-- ============================================================
|
||||
|
||||
ALTER TABLE public.cash_accounts
|
||||
ADD COLUMN IF NOT EXISTS bank_name text,
|
||||
ADD COLUMN IF NOT EXISTS clearing_number text,
|
||||
ADD COLUMN IF NOT EXISTS account_number text,
|
||||
-- Raw BBAN as the ASPSP sent it (Swedish: clearing + account, no separator).
|
||||
ADD COLUMN IF NOT EXISTS bban text,
|
||||
ADD COLUMN IF NOT EXISTS bankgiro text,
|
||||
ADD COLUMN IF NOT EXISTS plusgiro text,
|
||||
ADD COLUMN IF NOT EXISTS swish text,
|
||||
ADD COLUMN IF NOT EXISTS payee_iban text,
|
||||
ADD COLUMN IF NOT EXISTS bic text,
|
||||
ADD COLUMN IF NOT EXISTS bank_code text,
|
||||
ADD COLUMN IF NOT EXISTS foreign_account_number text,
|
||||
ADD COLUMN IF NOT EXISTS invoice_payee boolean NOT NULL DEFAULT false;
|
||||
|
||||
ALTER TABLE public.cash_accounts DROP COLUMN IF EXISTS bg_pg;
|
||||
|
||||
COMMENT ON COLUMN public.cash_accounts.invoice_payee IS
|
||||
'True when this account may be printed as the payee on customer invoices. Payee columns are owner/admin-only (trigger cash_accounts_payee_admin_only).';
|
||||
COMMENT ON COLUMN public.cash_accounts.bban IS
|
||||
'Raw BBAN from the bank connection (Swedish: clearing number followed by account number). Prefill only; clearing_number/account_number are what prints.';
|
||||
COMMENT ON COLUMN public.cash_accounts.payee_iban IS
|
||||
'IBAN printed on customer invoices. Separate from iban (the bank identity written by sync) so a sync never rewrites an invoice instruction.';
|
||||
|
||||
-- (id, company_id) target so child tables can prove same-company membership
|
||||
-- with one composite FK (same pattern as parties in 20260902160000).
|
||||
ALTER TABLE public.cash_accounts
|
||||
ADD CONSTRAINT cash_accounts_id_company_unique UNIQUE (id, company_id);
|
||||
|
||||
-- ============================================================
|
||||
-- 2. Per-currency defaults
|
||||
-- ============================================================
|
||||
|
||||
CREATE TABLE public.invoice_payee_defaults (
|
||||
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
company_id uuid NOT NULL REFERENCES public.companies(id) ON DELETE CASCADE,
|
||||
currency text NOT NULL CHECK (currency IN ('SEK', 'EUR', 'USD', 'GBP', 'NOK', 'DKK')),
|
||||
cash_account_id uuid NOT NULL,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
updated_at timestamptz NOT NULL DEFAULT now(),
|
||||
UNIQUE (company_id, currency),
|
||||
CONSTRAINT invoice_payee_defaults_same_company
|
||||
FOREIGN KEY (cash_account_id, company_id)
|
||||
REFERENCES public.cash_accounts(id, company_id) ON DELETE CASCADE
|
||||
);
|
||||
|
||||
CREATE INDEX idx_invoice_payee_defaults_cash_account
|
||||
ON public.invoice_payee_defaults (cash_account_id);
|
||||
|
||||
ALTER TABLE public.invoice_payee_defaults ENABLE ROW LEVEL SECURITY;
|
||||
|
||||
CREATE POLICY "invoice_payee_defaults_select" ON public.invoice_payee_defaults
|
||||
FOR SELECT USING (company_id IN (SELECT public.user_company_ids()));
|
||||
CREATE POLICY "invoice_payee_defaults_insert" ON public.invoice_payee_defaults
|
||||
FOR INSERT WITH CHECK (public.user_is_company_admin(company_id));
|
||||
CREATE POLICY "invoice_payee_defaults_update" ON public.invoice_payee_defaults
|
||||
FOR UPDATE
|
||||
USING (public.user_is_company_admin(company_id))
|
||||
WITH CHECK (public.user_is_company_admin(company_id));
|
||||
CREATE POLICY "invoice_payee_defaults_delete" ON public.invoice_payee_defaults
|
||||
FOR DELETE USING (public.user_is_company_admin(company_id));
|
||||
|
||||
CREATE TRIGGER invoice_payee_defaults_updated_at
|
||||
BEFORE UPDATE ON public.invoice_payee_defaults
|
||||
FOR EACH ROW EXECUTE FUNCTION public.update_updated_at_column();
|
||||
|
||||
-- Behandlingshistorik: which account customer invoices pay to is a
|
||||
-- behandlingsregel (BFNAR 2013:2 p. 9.16), same as the voucher-series
|
||||
-- override on cash_accounts (20260902124513).
|
||||
CREATE TRIGGER audit_invoice_payee_defaults
|
||||
AFTER INSERT OR UPDATE OR DELETE ON public.invoice_payee_defaults
|
||||
FOR EACH ROW EXECUTE FUNCTION public.write_audit_log();
|
||||
|
||||
-- The payee columns, in one place: the audit trigger, the mirror trigger
|
||||
-- and the admin guard below all fire on exactly this set.
|
||||
CREATE OR REPLACE FUNCTION public.cash_account_payee_changed(old_row public.cash_accounts, new_row public.cash_accounts)
|
||||
RETURNS boolean
|
||||
LANGUAGE sql
|
||||
IMMUTABLE
|
||||
SET search_path = ''
|
||||
AS $$
|
||||
SELECT old_row.bank_name IS DISTINCT FROM new_row.bank_name
|
||||
OR old_row.clearing_number IS DISTINCT FROM new_row.clearing_number
|
||||
OR old_row.account_number IS DISTINCT FROM new_row.account_number
|
||||
OR old_row.bankgiro IS DISTINCT FROM new_row.bankgiro
|
||||
OR old_row.plusgiro IS DISTINCT FROM new_row.plusgiro
|
||||
OR old_row.swish IS DISTINCT FROM new_row.swish
|
||||
OR old_row.payee_iban IS DISTINCT FROM new_row.payee_iban
|
||||
OR old_row.bic IS DISTINCT FROM new_row.bic
|
||||
OR old_row.bank_code IS DISTINCT FROM new_row.bank_code
|
||||
OR old_row.foreign_account_number IS DISTINCT FROM new_row.foreign_account_number
|
||||
OR old_row.invoice_payee IS DISTINCT FROM new_row.invoice_payee
|
||||
$$;
|
||||
|
||||
DROP TRIGGER IF EXISTS audit_cash_accounts_invoice_payee ON public.cash_accounts;
|
||||
CREATE TRIGGER audit_cash_accounts_invoice_payee
|
||||
AFTER UPDATE ON public.cash_accounts
|
||||
FOR EACH ROW
|
||||
WHEN (
|
||||
OLD.bank_name IS DISTINCT FROM NEW.bank_name
|
||||
OR OLD.clearing_number IS DISTINCT FROM NEW.clearing_number
|
||||
OR OLD.account_number IS DISTINCT FROM NEW.account_number
|
||||
OR OLD.bankgiro IS DISTINCT FROM NEW.bankgiro
|
||||
OR OLD.plusgiro IS DISTINCT FROM NEW.plusgiro
|
||||
OR OLD.swish IS DISTINCT FROM NEW.swish
|
||||
OR OLD.payee_iban IS DISTINCT FROM NEW.payee_iban
|
||||
OR OLD.bic IS DISTINCT FROM NEW.bic
|
||||
OR OLD.bank_code IS DISTINCT FROM NEW.bank_code
|
||||
OR OLD.foreign_account_number IS DISTINCT FROM NEW.foreign_account_number
|
||||
OR OLD.invoice_payee IS DISTINCT FROM NEW.invoice_payee
|
||||
)
|
||||
EXECUTE FUNCTION public.write_audit_log();
|
||||
|
||||
-- ============================================================
|
||||
-- 3. Admin-only payee columns
|
||||
-- ============================================================
|
||||
|
||||
-- Where customers are told to pay was owner/admin-only before this migration
|
||||
-- (company_settings RLS, 20260422120000). cash_accounts is member-writable
|
||||
-- because bank sync runs on the member's session, so the payee columns need
|
||||
-- their own gate. The service role and migrations (auth.uid() IS NULL) pass;
|
||||
-- a session that is not owner/admin of the company is refused.
|
||||
CREATE OR REPLACE FUNCTION public.cash_accounts_payee_admin_only()
|
||||
RETURNS trigger
|
||||
LANGUAGE plpgsql
|
||||
SET search_path = ''
|
||||
AS $$
|
||||
DECLARE
|
||||
v_touches boolean;
|
||||
BEGIN
|
||||
IF TG_OP = 'INSERT' THEN
|
||||
v_touches := NEW.invoice_payee
|
||||
OR COALESCE(NEW.bank_name, NEW.clearing_number, NEW.account_number, NEW.bankgiro,
|
||||
NEW.plusgiro, NEW.swish, NEW.payee_iban, NEW.bic, NEW.bank_code,
|
||||
NEW.foreign_account_number) IS NOT NULL;
|
||||
ELSE
|
||||
v_touches := public.cash_account_payee_changed(OLD, NEW);
|
||||
END IF;
|
||||
IF v_touches AND auth.uid() IS NOT NULL AND NOT public.user_is_company_admin(NEW.company_id) THEN
|
||||
RAISE EXCEPTION 'INVOICE_PAYEE_ADMIN_ONLY: only owner or admin may change where customer invoices are paid'
|
||||
USING ERRCODE = '42501';
|
||||
END IF;
|
||||
-- A customer pays to a giro or bank account (BAS 1920-1999). A PSP clearing
|
||||
-- row (1584, 1680, 1686) or a till (1910-1919) can never be printed as
|
||||
-- payee, whoever writes it: the routes check this too, this is the floor.
|
||||
IF NEW.invoice_payee AND NEW.ledger_account !~ '^19[2-9]\d$' THEN
|
||||
RAISE EXCEPTION 'INVOICE_PAYEE_ACCOUNT_INVALID: only a giro or bank account (BAS 1920-1999) can be printed as payee, not %', NEW.ledger_account
|
||||
USING ERRCODE = '23514';
|
||||
END IF;
|
||||
RETURN NEW;
|
||||
END;
|
||||
$$;
|
||||
|
||||
REVOKE EXECUTE ON FUNCTION public.cash_accounts_payee_admin_only() FROM PUBLIC, anon, authenticated;
|
||||
|
||||
DROP TRIGGER IF EXISTS cash_accounts_payee_admin_only ON public.cash_accounts;
|
||||
CREATE TRIGGER cash_accounts_payee_admin_only
|
||||
BEFORE INSERT OR UPDATE ON public.cash_accounts
|
||||
FOR EACH ROW EXECUTE FUNCTION public.cash_accounts_payee_admin_only();
|
||||
|
||||
-- ============================================================
|
||||
-- 4. Mirror into company_settings
|
||||
-- ============================================================
|
||||
|
||||
-- The payee fields of one cash account in the exact shape
|
||||
-- company_settings.invoice_payment_accounts stores per currency
|
||||
-- (InvoicePaymentAccount in types/index.ts). Null fields are stripped, same
|
||||
-- as the 20260722191000 backfill did.
|
||||
CREATE OR REPLACE FUNCTION public.cash_account_payee_json(p_cash_account_id uuid)
|
||||
RETURNS jsonb
|
||||
LANGUAGE sql
|
||||
STABLE
|
||||
SET search_path = ''
|
||||
AS $$
|
||||
SELECT jsonb_strip_nulls(jsonb_build_object(
|
||||
'bank_name', NULLIF(btrim(ca.bank_name), ''),
|
||||
'clearing_number', NULLIF(btrim(ca.clearing_number), ''),
|
||||
'account_number', NULLIF(btrim(ca.account_number), ''),
|
||||
'bankgiro', NULLIF(btrim(ca.bankgiro), ''),
|
||||
'plusgiro', NULLIF(btrim(ca.plusgiro), ''),
|
||||
'swish', NULLIF(btrim(ca.swish), ''),
|
||||
'iban', NULLIF(upper(regexp_replace(ca.payee_iban, '\s', '', 'g')), ''),
|
||||
'bic', NULLIF(upper(regexp_replace(ca.bic, '\s', '', 'g')), ''),
|
||||
'bank_code', NULLIF(regexp_replace(ca.bank_code, '\s', '', 'g'), ''),
|
||||
'foreign_account_number', NULLIF(regexp_replace(ca.foreign_account_number, '\s', '', 'g'), '')
|
||||
))
|
||||
FROM public.cash_accounts ca
|
||||
WHERE ca.id = p_cash_account_id;
|
||||
$$;
|
||||
|
||||
-- Rewrite the company's invoice_payment_accounts map and legacy SEK columns
|
||||
-- from its invoice_payee_defaults.
|
||||
-- * A currency with a default row is overwritten from the account.
|
||||
-- * A currency whose default was just removed (p_drop_currency) loses its
|
||||
-- key: an admin who clears the default means "nothing to print", and
|
||||
-- the send gate then asks for an account instead of printing a closed one.
|
||||
-- * Any other currency keeps whatever the map held: entries that never
|
||||
-- landed on an account stay as the resolver's fallback.
|
||||
-- * The legacy SEK columns are written only when the map carries a SEK
|
||||
-- entry (or SEK was just dropped). A company whose only SEK instruction
|
||||
-- is the legacy columns must not have them nulled by a mirror run that
|
||||
-- concerns another currency.
|
||||
CREATE OR REPLACE FUNCTION public.mirror_invoice_payee_defaults(p_company_id uuid, p_drop_currency text DEFAULT NULL)
|
||||
RETURNS void
|
||||
LANGUAGE plpgsql
|
||||
SECURITY DEFINER
|
||||
SET search_path = ''
|
||||
AS $$
|
||||
DECLARE
|
||||
v_map jsonb;
|
||||
v_sek jsonb;
|
||||
v_write_legacy boolean;
|
||||
BEGIN
|
||||
SELECT COALESCE(cs.invoice_payment_accounts, '{}'::jsonb)
|
||||
INTO v_map
|
||||
FROM public.company_settings cs
|
||||
WHERE cs.company_id = p_company_id;
|
||||
IF NOT FOUND THEN
|
||||
RETURN;
|
||||
END IF;
|
||||
|
||||
IF p_drop_currency IS NOT NULL THEN
|
||||
v_map := v_map - p_drop_currency;
|
||||
END IF;
|
||||
|
||||
SELECT COALESCE(v_map || jsonb_object_agg(d.currency, public.cash_account_payee_json(d.cash_account_id)), v_map)
|
||||
INTO v_map
|
||||
FROM public.invoice_payee_defaults d
|
||||
WHERE d.company_id = p_company_id;
|
||||
|
||||
v_write_legacy := (v_map ? 'SEK') OR p_drop_currency = 'SEK';
|
||||
v_sek := v_map -> 'SEK';
|
||||
|
||||
UPDATE public.company_settings cs
|
||||
SET invoice_payment_accounts = v_map,
|
||||
bank_name = CASE WHEN v_write_legacy THEN v_sek ->> 'bank_name' ELSE cs.bank_name END,
|
||||
clearing_number = CASE WHEN v_write_legacy THEN v_sek ->> 'clearing_number' ELSE cs.clearing_number END,
|
||||
account_number = CASE WHEN v_write_legacy THEN v_sek ->> 'account_number' ELSE cs.account_number END,
|
||||
bankgiro = CASE WHEN v_write_legacy THEN v_sek ->> 'bankgiro' ELSE cs.bankgiro END,
|
||||
plusgiro = CASE WHEN v_write_legacy THEN v_sek ->> 'plusgiro' ELSE cs.plusgiro END,
|
||||
swish = CASE WHEN v_write_legacy THEN v_sek ->> 'swish' ELSE cs.swish END,
|
||||
iban = CASE WHEN v_write_legacy THEN v_sek ->> 'iban' ELSE cs.iban END,
|
||||
bic = CASE WHEN v_write_legacy THEN v_sek ->> 'bic' ELSE cs.bic END
|
||||
WHERE cs.company_id = p_company_id
|
||||
AND (
|
||||
cs.invoice_payment_accounts IS DISTINCT FROM v_map
|
||||
OR (v_write_legacy AND (
|
||||
cs.bank_name IS DISTINCT FROM (v_sek ->> 'bank_name')
|
||||
OR cs.clearing_number IS DISTINCT FROM (v_sek ->> 'clearing_number')
|
||||
OR cs.account_number IS DISTINCT FROM (v_sek ->> 'account_number')
|
||||
OR cs.bankgiro IS DISTINCT FROM (v_sek ->> 'bankgiro')
|
||||
OR cs.plusgiro IS DISTINCT FROM (v_sek ->> 'plusgiro')
|
||||
OR cs.swish IS DISTINCT FROM (v_sek ->> 'swish')
|
||||
OR cs.iban IS DISTINCT FROM (v_sek ->> 'iban')
|
||||
OR cs.bic IS DISTINCT FROM (v_sek ->> 'bic')
|
||||
))
|
||||
);
|
||||
END;
|
||||
$$;
|
||||
|
||||
-- Trigger-only writers: nothing in a session may call them (the anon key
|
||||
-- would otherwise get an unauthenticated cross-tenant rewrite of
|
||||
-- company_settings). PUBLIC included: anon is a member of PUBLIC.
|
||||
REVOKE EXECUTE ON FUNCTION public.mirror_invoice_payee_defaults(uuid, text) FROM PUBLIC, anon, authenticated;
|
||||
|
||||
CREATE OR REPLACE FUNCTION public.trg_mirror_invoice_payee_defaults()
|
||||
RETURNS trigger
|
||||
LANGUAGE plpgsql
|
||||
SECURITY DEFINER
|
||||
SET search_path = ''
|
||||
AS $$
|
||||
BEGIN
|
||||
-- An account revoked as payee stops being a default (the defaults DELETE
|
||||
-- trigger then drops that currency from the map). invoice_payee is
|
||||
-- admin-only (cash_accounts_payee_admin_only), so this cannot be reached
|
||||
-- by a member; enabled is member-level and deliberately does not revoke.
|
||||
-- The field read sits in its own branch: plpgsql resolves NEW.<field> per
|
||||
-- expression, and this function also fires for invoice_payee_defaults
|
||||
-- rows, which have no invoice_payee column.
|
||||
IF TG_TABLE_NAME = 'cash_accounts' THEN
|
||||
IF TG_OP = 'UPDATE' AND NEW.invoice_payee = false AND OLD.invoice_payee = true THEN
|
||||
DELETE FROM public.invoice_payee_defaults WHERE cash_account_id = NEW.id;
|
||||
END IF;
|
||||
END IF;
|
||||
IF TG_TABLE_NAME = 'invoice_payee_defaults' THEN
|
||||
IF TG_OP = 'DELETE' THEN
|
||||
PERFORM public.mirror_invoice_payee_defaults(OLD.company_id, OLD.currency);
|
||||
ELSIF TG_OP = 'UPDATE' AND OLD.currency IS DISTINCT FROM NEW.currency THEN
|
||||
PERFORM public.mirror_invoice_payee_defaults(NEW.company_id, OLD.currency);
|
||||
ELSE
|
||||
PERFORM public.mirror_invoice_payee_defaults(NEW.company_id);
|
||||
END IF;
|
||||
ELSE
|
||||
PERFORM public.mirror_invoice_payee_defaults(NEW.company_id);
|
||||
END IF;
|
||||
RETURN NULL;
|
||||
END;
|
||||
$$;
|
||||
|
||||
REVOKE EXECUTE ON FUNCTION public.trg_mirror_invoice_payee_defaults() FROM PUBLIC, anon, authenticated;
|
||||
|
||||
CREATE TRIGGER mirror_invoice_payee_defaults_on_defaults
|
||||
AFTER INSERT OR UPDATE OR DELETE ON public.invoice_payee_defaults
|
||||
FOR EACH ROW EXECUTE FUNCTION public.trg_mirror_invoice_payee_defaults();
|
||||
|
||||
-- Payee-field edits or a revoke on an account that is a default for some
|
||||
-- currency must reach the mirror too. Bank sync churn (balances, names, the
|
||||
-- enabled flag, the bank identity iban) never fires this.
|
||||
CREATE TRIGGER mirror_invoice_payee_defaults_on_cash_account
|
||||
AFTER UPDATE ON public.cash_accounts
|
||||
FOR EACH ROW
|
||||
WHEN (
|
||||
OLD.bank_name IS DISTINCT FROM NEW.bank_name
|
||||
OR OLD.clearing_number IS DISTINCT FROM NEW.clearing_number
|
||||
OR OLD.account_number IS DISTINCT FROM NEW.account_number
|
||||
OR OLD.bankgiro IS DISTINCT FROM NEW.bankgiro
|
||||
OR OLD.plusgiro IS DISTINCT FROM NEW.plusgiro
|
||||
OR OLD.swish IS DISTINCT FROM NEW.swish
|
||||
OR OLD.payee_iban IS DISTINCT FROM NEW.payee_iban
|
||||
OR OLD.bic IS DISTINCT FROM NEW.bic
|
||||
OR OLD.bank_code IS DISTINCT FROM NEW.bank_code
|
||||
OR OLD.foreign_account_number IS DISTINCT FROM NEW.foreign_account_number
|
||||
OR OLD.invoice_payee IS DISTINCT FROM NEW.invoice_payee
|
||||
)
|
||||
EXECUTE FUNCTION public.trg_mirror_invoice_payee_defaults();
|
||||
|
||||
-- ============================================================
|
||||
-- 5. Backfill from today's map (no row creation)
|
||||
-- ============================================================
|
||||
|
||||
-- One row per (company, currency) that has payment instructions today: the
|
||||
-- map entry, or for SEK the legacy columns when the map has no SEK key.
|
||||
CREATE TEMP TABLE payee_backfill_entries AS
|
||||
SELECT cs.company_id, k.key AS currency, k.value AS payee
|
||||
FROM public.company_settings cs
|
||||
CROSS JOIN LATERAL jsonb_each(cs.invoice_payment_accounts) k
|
||||
WHERE cs.invoice_payment_accounts <> '{}'::jsonb
|
||||
UNION ALL
|
||||
SELECT cs.company_id, 'SEK',
|
||||
jsonb_strip_nulls(jsonb_build_object(
|
||||
'bank_name', NULLIF(btrim(cs.bank_name), ''),
|
||||
'clearing_number', NULLIF(btrim(cs.clearing_number), ''),
|
||||
'account_number', NULLIF(btrim(cs.account_number), ''),
|
||||
'bankgiro', NULLIF(btrim(cs.bankgiro), ''),
|
||||
'plusgiro', NULLIF(btrim(cs.plusgiro), ''),
|
||||
'swish', NULLIF(btrim(cs.swish), ''),
|
||||
'iban', NULLIF(btrim(cs.iban), ''),
|
||||
'bic', NULLIF(btrim(cs.bic), '')
|
||||
))
|
||||
FROM public.company_settings cs
|
||||
WHERE NOT (COALESCE(cs.invoice_payment_accounts, '{}'::jsonb) ? 'SEK')
|
||||
AND COALESCE(
|
||||
NULLIF(btrim(cs.bank_name), ''), NULLIF(btrim(cs.clearing_number), ''),
|
||||
NULLIF(btrim(cs.account_number), ''), NULLIF(btrim(cs.bankgiro), ''),
|
||||
NULLIF(btrim(cs.plusgiro), ''), NULLIF(btrim(cs.swish), ''),
|
||||
NULLIF(btrim(cs.iban), ''), NULLIF(btrim(cs.bic), '')
|
||||
) IS NOT NULL;
|
||||
|
||||
-- Target account per entry, among giro/bank rows (BAS 1920-1999) only: the
|
||||
-- account whose bank IBAN equals the entry's IBAN, else the primary in that
|
||||
-- currency, else the only enabled account in that currency. Ambiguous or
|
||||
-- absent: no target, the entry stays in the map.
|
||||
CREATE TEMP TABLE payee_backfill_targets AS
|
||||
SELECT e.company_id, e.currency, e.payee,
|
||||
COALESCE(
|
||||
(SELECT ca.id FROM public.cash_accounts ca
|
||||
WHERE ca.company_id = e.company_id AND ca.enabled AND ca.currency = e.currency
|
||||
AND ca.ledger_account ~ '^19[2-9]\d$'
|
||||
AND e.payee ->> 'iban' IS NOT NULL
|
||||
AND upper(regexp_replace(ca.iban, '\s', '', 'g')) = upper(regexp_replace(e.payee ->> 'iban', '\s', '', 'g'))
|
||||
ORDER BY ca.created_at, ca.id
|
||||
LIMIT 1),
|
||||
(SELECT ca.id FROM public.cash_accounts ca
|
||||
WHERE ca.company_id = e.company_id AND ca.enabled AND ca.currency = e.currency AND ca.is_primary
|
||||
AND ca.ledger_account ~ '^19[2-9]\d$'
|
||||
LIMIT 1),
|
||||
(SELECT (array_agg(ca.id))[1] FROM public.cash_accounts ca
|
||||
WHERE ca.company_id = e.company_id AND ca.enabled AND ca.currency = e.currency
|
||||
AND ca.ledger_account ~ '^19[2-9]\d$'
|
||||
HAVING count(*) = 1)
|
||||
) AS cash_account_id
|
||||
FROM payee_backfill_entries e;
|
||||
|
||||
-- The entry is copied verbatim onto the account's payee columns: what the
|
||||
-- company printed yesterday is what it prints tomorrow. The bank identity
|
||||
-- column iban is left alone; the printed IBAN lives in payee_iban.
|
||||
UPDATE public.cash_accounts ca
|
||||
SET bank_name = t.payee ->> 'bank_name',
|
||||
clearing_number = t.payee ->> 'clearing_number',
|
||||
account_number = t.payee ->> 'account_number',
|
||||
bankgiro = t.payee ->> 'bankgiro',
|
||||
plusgiro = t.payee ->> 'plusgiro',
|
||||
swish = t.payee ->> 'swish',
|
||||
payee_iban = t.payee ->> 'iban',
|
||||
bic = t.payee ->> 'bic',
|
||||
bank_code = t.payee ->> 'bank_code',
|
||||
foreign_account_number = t.payee ->> 'foreign_account_number',
|
||||
invoice_payee = true
|
||||
FROM payee_backfill_targets t
|
||||
WHERE t.cash_account_id = ca.id
|
||||
-- One account may be the target for several currencies; the SEK entry
|
||||
-- (the legacy instruction set) wins when they disagree.
|
||||
AND t.currency = (
|
||||
SELECT t2.currency FROM payee_backfill_targets t2
|
||||
WHERE t2.cash_account_id = t.cash_account_id
|
||||
ORDER BY (t2.currency = 'SEK') DESC, t2.currency
|
||||
LIMIT 1
|
||||
);
|
||||
|
||||
INSERT INTO public.invoice_payee_defaults (company_id, currency, cash_account_id)
|
||||
SELECT t.company_id, t.currency, t.cash_account_id
|
||||
FROM payee_backfill_targets t
|
||||
WHERE t.cash_account_id IS NOT NULL
|
||||
ON CONFLICT (company_id, currency) DO NOTHING;
|
||||
|
||||
DO $$
|
||||
DECLARE
|
||||
v_total integer;
|
||||
v_landed integer;
|
||||
BEGIN
|
||||
SELECT count(*), count(cash_account_id) INTO v_total, v_landed FROM payee_backfill_targets;
|
||||
RAISE NOTICE 'invoice payee backfill: % of % currency entries landed on a cash account; the rest stay in company_settings.invoice_payment_accounts as fallback',
|
||||
v_landed, v_total;
|
||||
END;
|
||||
$$;
|
||||
|
||||
DROP TABLE payee_backfill_targets;
|
||||
DROP TABLE payee_backfill_entries;
|
||||
|
||||
NOTIFY pgrst, 'reload schema';
|
||||
@@ -0,0 +1,39 @@
|
||||
-- Per-invoice payee: which of the company's bank accounts this invoice tells
|
||||
-- the customer to pay to.
|
||||
--
|
||||
-- payment_cash_account_id: the account chosen on the invoice (NULL = the
|
||||
-- company's default for the invoice currency, invoice_payee_defaults).
|
||||
-- ON DELETE SET NULL: the snapshot below is what an issued invoice prints,
|
||||
-- so losing the reference never changes a sent document.
|
||||
-- payment_details: the payee fields as they were when the invoice was
|
||||
-- written and last refreshed at issue (send / mark-sent / Peppol). Same
|
||||
-- shape as company_settings.invoice_payment_accounts entries. Issued
|
||||
-- invoices render from this column; a later edit of the account changes
|
||||
-- new invoices only. NULL on invoices that never chose an account: they
|
||||
-- keep resolving the default per currency as before.
|
||||
|
||||
ALTER TABLE public.invoices
|
||||
ADD COLUMN IF NOT EXISTS payment_cash_account_id uuid,
|
||||
ADD COLUMN IF NOT EXISTS payment_details jsonb
|
||||
CHECK (payment_details IS NULL OR jsonb_typeof(payment_details) = 'object');
|
||||
|
||||
-- Same-company proof in the constraint itself (the composite target
|
||||
-- cash_accounts(id, company_id) exists since 20260903150000): a direct
|
||||
-- PostgREST write cannot attach another tenant's account. SET NULL is scoped
|
||||
-- to the account column (PG15 column list); company_id must never be nulled.
|
||||
ALTER TABLE public.invoices
|
||||
ADD CONSTRAINT invoices_payment_cash_account_same_company
|
||||
FOREIGN KEY (payment_cash_account_id, company_id)
|
||||
REFERENCES public.cash_accounts(id, company_id)
|
||||
ON DELETE SET NULL (payment_cash_account_id);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_invoices_payment_cash_account
|
||||
ON public.invoices (company_id, payment_cash_account_id)
|
||||
WHERE payment_cash_account_id IS NOT NULL;
|
||||
|
||||
COMMENT ON COLUMN public.invoices.payment_cash_account_id IS
|
||||
'Bank account (cash_accounts) this invoice asks the customer to pay to. NULL = the per-currency default. Editable while draft only.';
|
||||
COMMENT ON COLUMN public.invoices.payment_details IS
|
||||
'Payee fields frozen for this invoice (bankgiro, plusgiro, clearing/account, IBAN, BIC, Swish, ...). Written when an account is chosen and refreshed at issue; issued invoices print from here.';
|
||||
|
||||
NOTIFY pgrst, 'reload schema';
|
||||
@@ -0,0 +1,307 @@
|
||||
import { randomUUID } from 'node:crypto'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { insertAuthUser, insertCashAccount, insertCompany, insertCompanyMember } from './fixtures'
|
||||
import { getPool, withUserContext } from './setup'
|
||||
|
||||
/**
|
||||
* Migration 20260903150000: payee fields on cash_accounts, invoice_payee_defaults,
|
||||
* and the mirror that keeps company_settings.invoice_payment_accounts plus the
|
||||
* legacy SEK columns equal to the default account per currency.
|
||||
*/
|
||||
|
||||
async function setActiveCompany(userId: string, companyId: string): Promise<void> {
|
||||
await getPool().query(
|
||||
`INSERT INTO public.user_preferences (user_id, active_company_id)
|
||||
VALUES ($1, $2)
|
||||
ON CONFLICT (user_id) DO UPDATE SET active_company_id = EXCLUDED.active_company_id`,
|
||||
[userId, companyId],
|
||||
)
|
||||
}
|
||||
|
||||
async function insertSettings(userId: string, companyId: string): Promise<void> {
|
||||
await getPool().query(
|
||||
`INSERT INTO public.company_settings (user_id, company_id) VALUES ($1, $2)`,
|
||||
[userId, companyId],
|
||||
)
|
||||
}
|
||||
|
||||
async function settingsRow(companyId: string) {
|
||||
const res = await getPool().query<{
|
||||
invoice_payment_accounts: Record<string, Record<string, string>>
|
||||
bankgiro: string | null
|
||||
iban: string | null
|
||||
plusgiro: string | null
|
||||
bank_name: string | null
|
||||
}>(
|
||||
`SELECT invoice_payment_accounts, bankgiro, iban, plusgiro, bank_name
|
||||
FROM public.company_settings WHERE company_id = $1`,
|
||||
[companyId],
|
||||
)
|
||||
return res.rows[0]
|
||||
}
|
||||
|
||||
async function setDefault(companyId: string, currency: string, cashAccountId: string): Promise<void> {
|
||||
await getPool().query(
|
||||
`INSERT INTO public.invoice_payee_defaults (company_id, currency, cash_account_id)
|
||||
VALUES ($1, $2, $3)
|
||||
ON CONFLICT (company_id, currency) DO UPDATE SET cash_account_id = EXCLUDED.cash_account_id`,
|
||||
[companyId, currency, cashAccountId],
|
||||
)
|
||||
}
|
||||
|
||||
describe('invoice payee accounts (20260903150000)', () => {
|
||||
it('mirrors the default SEK account into the map and the legacy columns, and drops both when the default goes', async () => {
|
||||
const userId = await insertAuthUser()
|
||||
const companyId = await insertCompany({ createdBy: userId })
|
||||
await insertSettings(userId, companyId)
|
||||
const main = await insertCashAccount({ companyId, ledgerAccount: '1930', isPrimary: true })
|
||||
await getPool().query(
|
||||
`UPDATE public.cash_accounts
|
||||
SET bankgiro = '5050-1234', bank_name = 'Testbanken', payee_iban = 'SE45 5000 0000 0583 9825 7466', invoice_payee = true
|
||||
WHERE id = $1`,
|
||||
[main],
|
||||
)
|
||||
// No default yet: the settings row is untouched.
|
||||
expect((await settingsRow(companyId)).bankgiro).toBeNull()
|
||||
|
||||
await setDefault(companyId, 'SEK', main)
|
||||
let row = await settingsRow(companyId)
|
||||
expect(row.bankgiro).toBe('5050-1234')
|
||||
expect(row.bank_name).toBe('Testbanken')
|
||||
expect(row.iban).toBe('SE4550000000058398257466')
|
||||
expect(row.invoice_payment_accounts.SEK).toEqual({
|
||||
bankgiro: '5050-1234',
|
||||
bank_name: 'Testbanken',
|
||||
iban: 'SE4550000000058398257466',
|
||||
})
|
||||
|
||||
// Editing the account's payee fields re-mirrors.
|
||||
await getPool().query(`UPDATE public.cash_accounts SET plusgiro = '123456-7' WHERE id = $1`, [main])
|
||||
row = await settingsRow(companyId)
|
||||
expect(row.plusgiro).toBe('123456-7')
|
||||
expect(row.invoice_payment_accounts.SEK.plusgiro).toBe('123456-7')
|
||||
|
||||
// Bank-sync churn on the same row does not touch the settings row.
|
||||
const before = await getPool().query(`SELECT updated_at FROM public.company_settings WHERE company_id = $1`, [companyId])
|
||||
await getPool().query(`UPDATE public.cash_accounts SET balance = 1000, name = 'Nytt namn' WHERE id = $1`, [main])
|
||||
const after = await getPool().query(`SELECT updated_at FROM public.company_settings WHERE company_id = $1`, [companyId])
|
||||
expect(after.rows[0].updated_at).toEqual(before.rows[0].updated_at)
|
||||
|
||||
// A bank-sync write of the bank-identity iban is not a payee change.
|
||||
await getPool().query(`UPDATE public.cash_accounts SET iban = 'SE9999999999999999999999' WHERE id = $1`, [main])
|
||||
row = await settingsRow(companyId)
|
||||
expect(row.iban).toBe('SE4550000000058398257466')
|
||||
|
||||
// Removing the default drops the SEK key and clears the legacy columns:
|
||||
// the admin said "nothing to print", so the send gate asks for an
|
||||
// account instead of printing a possibly closed one.
|
||||
await getPool().query(`DELETE FROM public.invoice_payee_defaults WHERE company_id = $1`, [companyId])
|
||||
row = await settingsRow(companyId)
|
||||
expect(row.invoice_payment_accounts.SEK).toBeUndefined()
|
||||
expect(row.bankgiro).toBeNull()
|
||||
expect(row.plusgiro).toBeNull()
|
||||
})
|
||||
|
||||
it('lets one account be the default for several currencies and leaves other currencies alone', async () => {
|
||||
const userId = await insertAuthUser()
|
||||
const companyId = await insertCompany({ createdBy: userId })
|
||||
await insertSettings(userId, companyId)
|
||||
await getPool().query(
|
||||
`UPDATE public.company_settings
|
||||
SET invoice_payment_accounts = '{"USD": {"iban": "GB33BUKB20201555555555"}}'::jsonb
|
||||
WHERE company_id = $1`,
|
||||
[companyId],
|
||||
)
|
||||
const sek = await insertCashAccount({ companyId, ledgerAccount: '1930', isPrimary: true, iban: 'SE4550000000058398257466' })
|
||||
await getPool().query(`UPDATE public.cash_accounts SET payee_iban = 'SE4550000000058398257466', bic = 'ESSESESS', invoice_payee = true WHERE id = $1`, [sek])
|
||||
await setDefault(companyId, 'SEK', sek)
|
||||
await setDefault(companyId, 'EUR', sek)
|
||||
|
||||
const row = await settingsRow(companyId)
|
||||
expect(row.invoice_payment_accounts.SEK).toEqual({ iban: 'SE4550000000058398257466', bic: 'ESSESESS' })
|
||||
expect(row.invoice_payment_accounts.EUR).toEqual({ iban: 'SE4550000000058398257466', bic: 'ESSESESS' })
|
||||
// USD had no default: the legacy entry survives as fallback.
|
||||
expect(row.invoice_payment_accounts.USD).toEqual({ iban: 'GB33BUKB20201555555555' })
|
||||
})
|
||||
|
||||
it('rejects a second default for the same currency and an account from another company', async () => {
|
||||
const userId = await insertAuthUser()
|
||||
const companyId = await insertCompany({ createdBy: userId })
|
||||
await insertSettings(userId, companyId)
|
||||
const otherCompanyId = await insertCompany({ createdBy: userId, name: 'Annat AB' })
|
||||
await insertSettings(userId, otherCompanyId)
|
||||
const own = await insertCashAccount({ companyId, ledgerAccount: '1930', isPrimary: true })
|
||||
const foreign = await insertCashAccount({ companyId: otherCompanyId, ledgerAccount: '1930', isPrimary: true })
|
||||
|
||||
await setDefault(companyId, 'SEK', own)
|
||||
await expect(
|
||||
getPool().query(
|
||||
`INSERT INTO public.invoice_payee_defaults (company_id, currency, cash_account_id) VALUES ($1, 'SEK', $2)`,
|
||||
[companyId, own],
|
||||
),
|
||||
).rejects.toThrow(/duplicate key/)
|
||||
await expect(
|
||||
getPool().query(
|
||||
`INSERT INTO public.invoice_payee_defaults (company_id, currency, cash_account_id) VALUES ($1, 'EUR', $2)`,
|
||||
[companyId, foreign],
|
||||
),
|
||||
).rejects.toThrow(/invoice_payee_defaults_same_company/)
|
||||
})
|
||||
|
||||
it('RLS: members read the defaults, only owner/admin write them', async () => {
|
||||
const ownerId = await insertAuthUser()
|
||||
const memberId = await insertAuthUser()
|
||||
const companyId = await insertCompany({ createdBy: ownerId })
|
||||
await insertSettings(ownerId, companyId)
|
||||
await insertCompanyMember({ companyId, userId: ownerId, role: 'owner' })
|
||||
await insertCompanyMember({ companyId, userId: memberId, role: 'member' })
|
||||
await setActiveCompany(ownerId, companyId)
|
||||
await setActiveCompany(memberId, companyId)
|
||||
const account = await insertCashAccount({ companyId, ledgerAccount: '1930', isPrimary: true })
|
||||
|
||||
await withUserContext(ownerId, async (client) => {
|
||||
await client.query(
|
||||
`INSERT INTO public.invoice_payee_defaults (company_id, currency, cash_account_id) VALUES ($1, 'SEK', $2)`,
|
||||
[companyId, account],
|
||||
)
|
||||
const seen = await client.query(`SELECT count(*)::int AS n FROM public.invoice_payee_defaults WHERE company_id = $1`, [companyId])
|
||||
expect(seen.rows[0].n).toBe(1)
|
||||
})
|
||||
|
||||
await withUserContext(memberId, async (client) => {
|
||||
const res = await client.query(
|
||||
`INSERT INTO public.invoice_payee_defaults (company_id, currency, cash_account_id) VALUES ($1, 'EUR', $2)
|
||||
ON CONFLICT DO NOTHING RETURNING id`,
|
||||
[companyId, account],
|
||||
).catch((err: Error) => err)
|
||||
expect(res).toBeInstanceOf(Error)
|
||||
expect((res as Error).message).toMatch(/row-level security/)
|
||||
})
|
||||
})
|
||||
|
||||
it('audits payee edits on cash_accounts and default changes', async () => {
|
||||
const userId = await insertAuthUser()
|
||||
const companyId = await insertCompany({ createdBy: userId })
|
||||
await insertSettings(userId, companyId)
|
||||
const account = await insertCashAccount({ companyId, ledgerAccount: '1930', isPrimary: true })
|
||||
await getPool().query(`UPDATE public.cash_accounts SET bankgiro = '5050-1234' WHERE id = $1`, [account])
|
||||
await getPool().query(`UPDATE public.cash_accounts SET balance = 5 WHERE id = $1`, [account])
|
||||
const cashAudit = await getPool().query<{ action: string; new_bg: string | null }>(
|
||||
`SELECT action, new_state->>'bankgiro' AS new_bg FROM public.audit_log
|
||||
WHERE table_name = 'cash_accounts' AND record_id = $1 ORDER BY created_at, id`,
|
||||
[account],
|
||||
)
|
||||
expect(cashAudit.rows).toEqual([{ action: 'UPDATE', new_bg: '5050-1234' }])
|
||||
|
||||
await setDefault(companyId, 'SEK', account)
|
||||
const id = randomUUID()
|
||||
await getPool().query(
|
||||
`INSERT INTO public.invoice_payee_defaults (id, company_id, currency, cash_account_id) VALUES ($1, $2, 'EUR', $3)`,
|
||||
[id, companyId, account],
|
||||
)
|
||||
const defAudit = await getPool().query<{ action: string; company_id: string }>(
|
||||
`SELECT action, company_id FROM public.audit_log WHERE table_name = 'invoice_payee_defaults' AND record_id = $1`,
|
||||
[id],
|
||||
)
|
||||
expect(defAudit.rows).toEqual([{ action: 'INSERT', company_id: companyId }])
|
||||
})
|
||||
it('leaves the legacy SEK columns alone when the map has no SEK entry (legacy-only companies)', async () => {
|
||||
const userId = await insertAuthUser()
|
||||
const companyId = await insertCompany({ createdBy: userId })
|
||||
await insertSettings(userId, companyId)
|
||||
await getPool().query(
|
||||
`UPDATE public.company_settings SET bankgiro = '991-2346', invoice_payment_accounts = '{}'::jsonb WHERE company_id = $1`,
|
||||
[companyId],
|
||||
)
|
||||
const eur = await insertCashAccount({ companyId, ledgerAccount: '1932', currency: 'EUR' })
|
||||
await getPool().query(`UPDATE public.cash_accounts SET payee_iban = 'DE89370400440532013000', invoice_payee = true WHERE id = $1`, [eur])
|
||||
await setDefault(companyId, 'EUR', eur)
|
||||
const row = await settingsRow(companyId)
|
||||
expect(row.invoice_payment_accounts.EUR).toEqual({ iban: 'DE89370400440532013000' })
|
||||
expect(row.bankgiro).toBe('991-2346')
|
||||
})
|
||||
|
||||
it('refuses invoice_payee on anything but a giro/bank ledger (BAS 1920-1999), whoever writes it', async () => {
|
||||
const userId = await insertAuthUser()
|
||||
const companyId = await insertCompany({ createdBy: userId })
|
||||
await insertSettings(userId, companyId)
|
||||
for (const ledger of ['1686', '1910']) {
|
||||
const res = await getPool()
|
||||
.query(`INSERT INTO public.cash_accounts (company_id, ledger_account, currency, bankgiro, invoice_payee) VALUES ($1, $2, 'SEK', '5050-1234', true)`, [companyId, ledger])
|
||||
.catch((err: Error) => err)
|
||||
expect(res).toBeInstanceOf(Error)
|
||||
expect((res as Error).message).toMatch(/INVOICE_PAYEE_ACCOUNT_INVALID/)
|
||||
}
|
||||
const till = await insertCashAccount({ companyId, ledgerAccount: '1910' })
|
||||
const flip = await getPool()
|
||||
.query(`UPDATE public.cash_accounts SET invoice_payee = true WHERE id = $1`, [till])
|
||||
.catch((err: Error) => err)
|
||||
expect(flip).toBeInstanceOf(Error)
|
||||
const bank = await insertCashAccount({ companyId, ledgerAccount: '1920' })
|
||||
await getPool().query(`UPDATE public.cash_accounts SET bankgiro = '5050-1234', invoice_payee = true WHERE id = $1`, [bank])
|
||||
})
|
||||
|
||||
it('revoking an account as payee drops its defaults; disabling it (member-level) does not', async () => {
|
||||
const userId = await insertAuthUser()
|
||||
const companyId = await insertCompany({ createdBy: userId })
|
||||
await insertSettings(userId, companyId)
|
||||
const main = await insertCashAccount({ companyId, ledgerAccount: '1930', isPrimary: true })
|
||||
await getPool().query(`UPDATE public.cash_accounts SET bankgiro = '5050-1234', invoice_payee = true WHERE id = $1`, [main])
|
||||
await setDefault(companyId, 'SEK', main)
|
||||
await setDefault(companyId, 'EUR', main)
|
||||
|
||||
// "Synkas ej" in the bank picker is a member action and must not undo an
|
||||
// admin's payee choice: the defaults and the mirrored columns stay.
|
||||
await getPool().query(`UPDATE public.cash_accounts SET enabled = false WHERE id = $1`, [main])
|
||||
let left = await getPool().query(`SELECT count(*)::int AS n FROM public.invoice_payee_defaults WHERE company_id = $1`, [companyId])
|
||||
expect(left.rows[0].n).toBe(2)
|
||||
expect((await settingsRow(companyId)).bankgiro).toBe('5050-1234')
|
||||
|
||||
await getPool().query(`UPDATE public.cash_accounts SET invoice_payee = false WHERE id = $1`, [main])
|
||||
left = await getPool().query(`SELECT count(*)::int AS n FROM public.invoice_payee_defaults WHERE company_id = $1`, [companyId])
|
||||
expect(left.rows[0].n).toBe(0)
|
||||
expect((await settingsRow(companyId)).bankgiro).toBeNull()
|
||||
})
|
||||
|
||||
it('payee columns are owner/admin-only at the database; sync-style member writes to other columns still pass', async () => {
|
||||
const ownerId = await insertAuthUser()
|
||||
const memberId = await insertAuthUser()
|
||||
const companyId = await insertCompany({ createdBy: ownerId })
|
||||
await insertSettings(ownerId, companyId)
|
||||
await insertCompanyMember({ companyId, userId: ownerId, role: 'owner' })
|
||||
await insertCompanyMember({ companyId, userId: memberId, role: 'member' })
|
||||
await setActiveCompany(ownerId, companyId)
|
||||
await setActiveCompany(memberId, companyId)
|
||||
const main = await insertCashAccount({ companyId, ledgerAccount: '1930', isPrimary: true })
|
||||
|
||||
// One transaction per expectation: a raised error aborts the transaction
|
||||
// withUserContext runs in, so the next statement would fail for the
|
||||
// wrong reason.
|
||||
await withUserContext(memberId, async (client) => {
|
||||
const res = await client
|
||||
.query(`UPDATE public.cash_accounts SET bankgiro = '999-9999' WHERE id = $1`, [main])
|
||||
.catch((err: Error) => err)
|
||||
expect(res).toBeInstanceOf(Error)
|
||||
expect((res as Error).message).toMatch(/INVOICE_PAYEE_ADMIN_ONLY/)
|
||||
})
|
||||
await withUserContext(memberId, async (client) => {
|
||||
// Balance, the enabled flag and the bank-identity iban are what sync
|
||||
// and the bank picker write: allowed for a member.
|
||||
await client.query(`UPDATE public.cash_accounts SET balance = 10, enabled = false, iban = 'SE4550000000058398257466' WHERE id = $1`, [main])
|
||||
const seen = await client.query(`SELECT balance::int AS balance, enabled FROM public.cash_accounts WHERE id = $1`, [main])
|
||||
expect(seen.rows[0]).toEqual({ balance: 10, enabled: false })
|
||||
})
|
||||
await withUserContext(memberId, async (client) => {
|
||||
const insert = await client
|
||||
.query(`INSERT INTO public.cash_accounts (company_id, ledger_account, currency, bankgiro, invoice_payee) VALUES ($1, '1931', 'SEK', '999-9999', true)`, [companyId])
|
||||
.catch((err: Error) => err)
|
||||
expect(insert).toBeInstanceOf(Error)
|
||||
expect((insert as Error).message).toMatch(/INVOICE_PAYEE_ADMIN_ONLY/)
|
||||
})
|
||||
await withUserContext(ownerId, async (client) => {
|
||||
await client.query(`UPDATE public.cash_accounts SET bankgiro = '5050-1234', invoice_payee = true WHERE id = $1`, [main])
|
||||
const seen = await client.query(`SELECT bankgiro FROM public.cash_accounts WHERE id = $1`, [main])
|
||||
expect(seen.rows[0].bankgiro).toBe('5050-1234')
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,73 @@
|
||||
import { randomUUID } from 'node:crypto'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { insertAuthUser, insertCashAccount, insertCompany } from './fixtures'
|
||||
import { getPool } from './setup'
|
||||
|
||||
/**
|
||||
* Migration 20260903193000: invoices.payment_cash_account_id (FK, SET NULL)
|
||||
* and invoices.payment_details (object snapshot).
|
||||
*/
|
||||
|
||||
async function insertCustomer(companyId: string, userId: string): Promise<string> {
|
||||
const id = randomUUID()
|
||||
await getPool().query(
|
||||
`INSERT INTO public.customers (id, company_id, user_id, name, customer_type) VALUES ($1, $2, $3, 'Kund AB', 'swedish_business')`,
|
||||
[id, companyId, userId],
|
||||
)
|
||||
return id
|
||||
}
|
||||
|
||||
async function insertInvoice(companyId: string, userId: string, customerId: string, extra: Record<string, unknown> = {}): Promise<string> {
|
||||
const id = randomUUID()
|
||||
const cols = ['id', 'company_id', 'user_id', 'customer_id', 'invoice_date', 'due_date', 'status', 'currency', 'subtotal', 'vat_amount', 'total', 'vat_treatment', 'vat_rate', 'paid_amount', 'remaining_amount', ...Object.keys(extra)]
|
||||
const vals = [id, companyId, userId, customerId, '2026-09-01', '2026-10-01', 'draft', 'SEK', 100, 25, 125, 'standard_25', 25, 0, 125, ...Object.values(extra)]
|
||||
await getPool().query(
|
||||
`INSERT INTO public.invoices (${cols.join(', ')}) VALUES (${cols.map((_, i) => `$${i + 1}`).join(', ')})`,
|
||||
vals,
|
||||
)
|
||||
return id
|
||||
}
|
||||
|
||||
describe('invoice payee columns (20260903193000)', () => {
|
||||
it('stores the choice and the snapshot; deleting the account nulls the reference but keeps the snapshot', async () => {
|
||||
const userId = await insertAuthUser()
|
||||
const companyId = await insertCompany({ createdBy: userId })
|
||||
const customerId = await insertCustomer(companyId, userId)
|
||||
const account = await insertCashAccount({ companyId, ledgerAccount: '1931' })
|
||||
const invoiceId = await insertInvoice(companyId, userId, customerId, {
|
||||
payment_cash_account_id: account,
|
||||
payment_details: JSON.stringify({ bankgiro: '5050-1055' }),
|
||||
})
|
||||
|
||||
await getPool().query(`DELETE FROM public.cash_accounts WHERE id = $1`, [account])
|
||||
const row = await getPool().query<{ payment_cash_account_id: string | null; payment_details: { bankgiro: string } }>(
|
||||
`SELECT payment_cash_account_id, payment_details FROM public.invoices WHERE id = $1`,
|
||||
[invoiceId],
|
||||
)
|
||||
expect(row.rows[0].payment_cash_account_id).toBeNull()
|
||||
expect(row.rows[0].payment_details).toEqual({ bankgiro: '5050-1055' })
|
||||
})
|
||||
|
||||
it('rejects a non-object snapshot and an account id that does not exist', async () => {
|
||||
const userId = await insertAuthUser()
|
||||
const companyId = await insertCompany({ createdBy: userId })
|
||||
const customerId = await insertCustomer(companyId, userId)
|
||||
await expect(
|
||||
insertInvoice(companyId, userId, customerId, { payment_details: JSON.stringify(['not', 'an', 'object']) }),
|
||||
).rejects.toThrow(/payment_details/)
|
||||
await expect(
|
||||
insertInvoice(companyId, userId, customerId, { payment_cash_account_id: randomUUID() }),
|
||||
).rejects.toThrow(/foreign key/)
|
||||
})
|
||||
|
||||
it('rejects another company\'s cash account (composite same-company FK)', async () => {
|
||||
const userId = await insertAuthUser()
|
||||
const companyId = await insertCompany({ createdBy: userId })
|
||||
const otherCompanyId = await insertCompany({ createdBy: userId, name: 'Annat AB' })
|
||||
const customerId = await insertCustomer(companyId, userId)
|
||||
const foreign = await insertCashAccount({ companyId: otherCompanyId, ledgerAccount: '1930' })
|
||||
await expect(
|
||||
insertInvoice(companyId, userId, customerId, { payment_cash_account_id: foreign }),
|
||||
).rejects.toThrow(/invoices_payment_cash_account_same_company/)
|
||||
})
|
||||
})
|
||||
+50
-3
@@ -643,13 +643,39 @@ export interface BankAccount {
|
||||
// drops it 30 days after this PR.
|
||||
export type CashAccountSource = 'enable_banking' | 'manual' | 'sie_import'
|
||||
|
||||
export interface CashAccount {
|
||||
/**
|
||||
* What a customer pays to. Lives on cash_accounts (migration 20260903150000)
|
||||
* and is the single source for the payee printed on customer invoices; the
|
||||
* per-currency map on company_settings is a trigger-maintained mirror of the
|
||||
* default account per currency.
|
||||
*/
|
||||
export interface CashAccountPayeeFields {
|
||||
bank_name: string | null
|
||||
clearing_number: string | null
|
||||
account_number: string | null
|
||||
bankgiro: string | null
|
||||
plusgiro: string | null
|
||||
swish: string | null
|
||||
iban: string | null
|
||||
bic: string | null
|
||||
bank_code: string | null
|
||||
foreign_account_number: string | null
|
||||
}
|
||||
|
||||
export interface CashAccount extends CashAccountPayeeFields {
|
||||
id: string
|
||||
company_id: string
|
||||
bank_connection_id: string | null
|
||||
external_uid: string | null // PSD2 StoredAccount.uid
|
||||
iban: string | null
|
||||
bg_pg: string | null
|
||||
// Raw BBAN from the bank connection (Swedish: clearing + account number,
|
||||
// no separator). Prefill only; clearing_number/account_number print.
|
||||
bban: string | null
|
||||
// The IBAN printed on customer invoices. Separate from `iban` (the bank's
|
||||
// identity of the account, written by every sync and used to re-pair on
|
||||
// reconnect) so a sync never rewrites an invoice instruction.
|
||||
payee_iban: string | null
|
||||
// True when the account may be printed as the payee on customer invoices.
|
||||
invoice_payee: boolean
|
||||
name: string | null
|
||||
currency: string // 3-char ISO; broader than Currency union to
|
||||
// tolerate future currencies without DB-driven enum drift
|
||||
@@ -668,6 +694,20 @@ export interface CashAccount {
|
||||
updated_at: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Which cash account an invoice in `currency` prints as payee when the
|
||||
* invoice does not choose one itself. One account may be the default for
|
||||
* several currencies (a SEK account with an IBAN is the usual EUR payee).
|
||||
*/
|
||||
export interface InvoicePayeeDefault {
|
||||
id: string
|
||||
company_id: string
|
||||
currency: Currency
|
||||
cash_account_id: string
|
||||
created_at: string
|
||||
updated_at: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Closed vocabulary for HOW money moved (the payment rail), classified at
|
||||
* ingest by classifyTransactionMethod() (lib/transactions/transaction-method.ts).
|
||||
@@ -1323,6 +1363,13 @@ export interface Invoice {
|
||||
stripe_payment_link_id?: string | null
|
||||
// Per-invoice opt-out for automatic payment link creation on send.
|
||||
payment_link_auto?: boolean
|
||||
// Per-invoice payee (migration 20260903193000): the bank account this
|
||||
// invoice asks the customer to pay to (null = the per-currency default),
|
||||
// and its payee fields frozen when chosen and refreshed at issue. Issued
|
||||
// invoices print from payment_details; the resolver falls back to the
|
||||
// company default when it is null.
|
||||
payment_cash_account_id?: string | null
|
||||
payment_details?: InvoicePaymentAccount | null
|
||||
|
||||
// Notes
|
||||
notes: string | null
|
||||
|
||||
Reference in New Issue
Block a user