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:
Mattsson
2026-09-03 21:06:45 +02:00
committed by GitHub
co-authored by Claude Fable 5.1
parent 88a5d78594
commit d670fe6663
69 changed files with 4025 additions and 611 deletions
@@ -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 () => {
+73 -10
View File
@@ -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 },
)
+50
View File
@@ -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
)
})
+5
View File
@@ -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) {
+4 -1
View File
@@ -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,
+23 -1
View File
@@ -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)
+9 -2
View File
@@ -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)
+42 -1
View File
@@ -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 () => {
+18 -3
View File
@@ -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)
+20
View File
@@ -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.
+6
View File
@@ -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),
}))
+16
View File
@@ -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,