* fix(invoices): return attachment filename in delivery history summaries The 20260723003000 hardening dropped attachment_filename from list_invoice_delivery_summaries, so the delivery history UI always fell back to the generic "faktura.pdf" label. Recreate the RPC with the filename included: it is derived from company name, customer name, invoice number, and date, all already visible to every company member, so the minimization boundary is unchanged. Addresses stay masked and message content, BCC, and checksums stay server-side. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(reconciliation): surface own-account transfer legs in match-to-voucher by default The second (incoming) leg of a transfer between two of the company's own bank accounts was hidden in the 'Matcha mot befintlig verifikation' dialog because the voucher counted as 'already matched' once its outgoing leg was linked, even though the incoming account's line had no settling transaction. Users read the empty default list as 'the app won't let me link this'. get_account_gl_lines_for_matching now counts links per settlement account: a transaction provably on another cash account no longer marks the voucher as matched for the requested account, so the unsettled transfer leg surfaces by default (and auto-selects on an exact match). Same-account N:1 stays behind the 'Visa aven matchade verifikationer' opt-in, and transactions without a resolvable cash account conservatively keep counting everywhere. get_unlinked_gl_lines is deliberately untouched (feeds auto-reconcile). Companion guard: mark_entry_as_opening_balance now refuses entries with linked bank transactions, since half-settled transfer vouchers became reachable in the reconciliation view's unmatched table where 'Mark som IB' renders; re-tagging one would strand its transaction against a movement- excluded entry. getReconciliationStatus counts unmatched GL lines with the account-scoped RPC so the status card agrees with the table. Fixes #1026 Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * perf(api): cut prod p95 latency via local JWT auth, single-RT company resolution, and report aggregate RPCs Baseline 2026-07-23 (487 prod samples): p50 160ms, p95 480ms, 13% of requests over 300ms. Target: p95 under 300ms. - requireAuth: verify JWTs locally via getClaims (ES256/JWKS) instead of a second network getUser per request; getUser fallback keeps HS256 self-hosted and existing test mocks working; middleware still revocation-checks every /api request - resolve_active_company RPC (20260723161000): one round trip replaces 2-3 queries in getActiveCompanyId and middleware; PGRST202/42501 fall back to the legacy query path - arsredovisning build-data: ~33 sequential round trips down to ~7, output byte-identical (snapshot-proven) - currency rate route: stop bypassing the exchange_rates cache (missing supabase arg caused an external Riksbanken call on every request) - document.get: parallelize row fetch, signed URL and audit event - list_company_accounts RPC (20260723170000): accounts list in one round trip instead of paging past PostgREST's 1000-row cap - vat-declaration route: drop a dead sequential company_settings query - get_kpi_report_aggregates RPC (20260723180000): KPI report's three full-period line scans collapsed into one aggregate call; dimension- filtered path unchanged - lint: fix 9 baseline errors, downgrade 4 react-hooks compiler rules to warn, zero the eslint baseline ratchet All four gates green: lint 0 errors, 9163 tests, check:guards, build. Migrations applied idempotently to staging only; prod receives them via Supabase branching on merge. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(review): resolve PR review findings across auth, VAT declaration, and IB retag - requireAuth getClaims fast path: pin iss (project URL) and aud ('authenticated'), log every fallback to getUser (ASVS V9.1 finding) - remove the ignored accountingMethod parameter from calculateVatDeclaration and the dead company_settings.accounting_method reads in xlsx/pdf/eskd routes; v1 API keeps accepting the query param but documents it as a no-op - close the mark_entry_as_opening_balance TOCTOU race with a transactions trigger (20260723190000, FOR KEY SHARE on journal_entries) + pg tests; applied to staging and smoke-verified both directions - re-add the 42501 tenant guard to branch-local migration 20260723160000 (function body had silently reverted to the pre-20260619130100 definition) - document the buildK3Noter tbFullRows full-TB contract (uppskjuten skatt opening balance per BFNAR 2012:1 ch.29) - add KPI VAT-liability test covering reduced-rate output accounts 2621/2631 Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(db): use NULL-safe caller_is_company_member in opening-balance retag guard The re-added tenant guard carried the pre-20260703180000 raw NOT IN (SELECT user_company_ids()) pattern, which the null-safe-tenant-guards ratchet blocks. Staging re-synced. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> --------- Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
373 lines
13 KiB
TypeScript
373 lines
13 KiB
TypeScript
/**
|
|
* Tests for /api/bookkeeping/accounts (list/create), /[number] (update/delete)
|
|
* and /activate.
|
|
*
|
|
* The DELETE usage check is asserted with a call-capturing mock: the count
|
|
* query must be scoped to the caller's company via the journal_entries join —
|
|
* without it, another company's use of the same BAS number (same user,
|
|
* multiple memberships under RLS) wrongly blocks deletion.
|
|
*/
|
|
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
|
import { NextResponse } from 'next/server'
|
|
import { createMockRequest, parseJsonResponse } from '@/tests/helpers'
|
|
|
|
const requireAuthMock = vi.fn()
|
|
vi.mock('@/lib/auth/require-auth', () => ({
|
|
requireAuth: (...args: unknown[]) => requireAuthMock(...args),
|
|
}))
|
|
|
|
vi.mock('@/lib/company/context', () => ({
|
|
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
|
|
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
|
|
}))
|
|
|
|
const requireWriteMock = vi.fn()
|
|
vi.mock('@/lib/auth/require-write', () => ({
|
|
requireWritePermission: (...args: unknown[]) => requireWriteMock(...args),
|
|
}))
|
|
|
|
import { GET as listGET, POST as createPOST } from '../route'
|
|
import { DELETE, PUT } from '../[number]/route'
|
|
import { POST as activatePOST } from '../activate/route'
|
|
|
|
interface CapturedCall {
|
|
method: string
|
|
args: unknown[]
|
|
}
|
|
|
|
/** Chainable builder recording calls; resolves queued {data,error,count} per from()/rpc(). */
|
|
function createCapturingSupabase(
|
|
results: { data?: unknown; error?: unknown; count?: number | null }[]
|
|
) {
|
|
const calls: CapturedCall[] = []
|
|
let idx = 0
|
|
const makeBuilder = () => {
|
|
const result = results[idx++] ?? { data: null, error: null, count: null }
|
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
const b: any = {}
|
|
for (const m of ['select', 'eq', 'in', 'gte', 'lte', 'is', 'order', 'limit', 'range', 'insert', 'update', 'delete', 'maybeSingle', 'single']) {
|
|
b[m] = (...args: unknown[]) => {
|
|
calls.push({ method: m, args })
|
|
return b
|
|
}
|
|
}
|
|
b.then = (resolve: (v: unknown) => void) =>
|
|
resolve({ data: result.data ?? null, error: result.error ?? null, count: result.count ?? null })
|
|
return b
|
|
}
|
|
const supabase = {
|
|
from: (table: string) => {
|
|
calls.push({ method: 'from', args: [table] })
|
|
return makeBuilder()
|
|
},
|
|
rpc: (...args: unknown[]) => {
|
|
calls.push({ method: 'rpc', args })
|
|
const result = results[idx++] ?? { data: null, error: null, count: null }
|
|
return Promise.resolve({ data: result.data ?? null, error: result.error ?? null })
|
|
},
|
|
}
|
|
return { supabase, calls }
|
|
}
|
|
|
|
const routeParams = { params: Promise.resolve({}) }
|
|
const numberParams = { params: Promise.resolve({ number: '5010' }) }
|
|
|
|
beforeEach(() => {
|
|
vi.clearAllMocks()
|
|
requireWriteMock.mockResolvedValue({ ok: true })
|
|
})
|
|
|
|
function auth(supabase: unknown) {
|
|
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase, error: null })
|
|
}
|
|
|
|
describe('GET /api/bookkeeping/accounts', () => {
|
|
it('returns 401 when not authenticated', async () => {
|
|
requireAuthMock.mockResolvedValue({
|
|
user: null,
|
|
supabase: {},
|
|
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
|
|
})
|
|
const res = await listGET(createMockRequest('/api/bookkeeping/accounts'), routeParams)
|
|
expect(res.status).toBe(401)
|
|
})
|
|
|
|
it('returns 400 for a non-numeric class filter', async () => {
|
|
const { supabase } = createCapturingSupabase([])
|
|
auth(supabase)
|
|
const req = createMockRequest('/api/bookkeeping/accounts', { searchParams: { class: 'abc' } })
|
|
const { status } = await parseJsonResponse(await listGET(req, routeParams))
|
|
expect(status).toBe(400)
|
|
})
|
|
|
|
it('lists accounts via the single-round-trip RPC', async () => {
|
|
const { supabase, calls } = createCapturingSupabase([
|
|
{ data: [{ account_number: '1930', account_name: 'Företagskonto' }] },
|
|
])
|
|
auth(supabase)
|
|
const { status, body } = await parseJsonResponse<{ data: unknown[] }>(
|
|
await listGET(createMockRequest('/api/bookkeeping/accounts'), routeParams)
|
|
)
|
|
expect(status).toBe(200)
|
|
expect(body.data).toHaveLength(1)
|
|
const rpcCall = calls.find((c) => c.method === 'rpc')
|
|
expect(rpcCall?.args).toEqual([
|
|
'list_company_accounts',
|
|
{ p_company_id: 'company-1', p_active_only: true, p_account_class: null },
|
|
])
|
|
// The RPC path must not also hit the table: exactly one round trip.
|
|
expect(calls.some((c) => c.method === 'from')).toBe(false)
|
|
})
|
|
|
|
it('maps ?class=3&active=false onto the RPC arguments', async () => {
|
|
const { supabase, calls } = createCapturingSupabase([{ data: [] }])
|
|
auth(supabase)
|
|
const req = createMockRequest('/api/bookkeeping/accounts', {
|
|
searchParams: { class: '3', active: 'false' },
|
|
})
|
|
const { status, body } = await parseJsonResponse<{ data: unknown[] }>(
|
|
await listGET(req, routeParams)
|
|
)
|
|
expect(status).toBe(200)
|
|
expect(body.data).toEqual([])
|
|
const rpcCall = calls.find((c) => c.method === 'rpc')
|
|
expect(rpcCall?.args[1]).toEqual({
|
|
p_company_id: 'company-1',
|
|
p_active_only: false,
|
|
p_account_class: 3,
|
|
})
|
|
})
|
|
|
|
it('falls back to the paged fetch when the RPC is not deployed (PGRST202)', async () => {
|
|
const { supabase, calls } = createCapturingSupabase([
|
|
{ error: { code: 'PGRST202', message: 'function not found in schema cache' } },
|
|
{ data: [{ account_number: '1930', account_name: 'Företagskonto' }] },
|
|
])
|
|
auth(supabase)
|
|
const { status, body } = await parseJsonResponse<{ data: unknown[] }>(
|
|
await listGET(createMockRequest('/api/bookkeeping/accounts'), routeParams)
|
|
)
|
|
expect(status).toBe(200)
|
|
expect(body.data).toHaveLength(1)
|
|
expect(calls.filter((c) => c.method === 'from').map((c) => c.args)).toContainEqual([
|
|
'chart_of_accounts',
|
|
])
|
|
expect(calls.filter((c) => c.method === 'eq').map((c) => c.args)).toContainEqual([
|
|
'company_id',
|
|
'company-1',
|
|
])
|
|
})
|
|
|
|
it('returns the legacy 500 { error: string } on a non-fallback RPC error', async () => {
|
|
const { supabase, calls } = createCapturingSupabase([
|
|
{ error: { code: 'XX000', message: 'boom' } },
|
|
])
|
|
auth(supabase)
|
|
const { status, body } = await parseJsonResponse<{ error: string }>(
|
|
await listGET(createMockRequest('/api/bookkeeping/accounts'), routeParams)
|
|
)
|
|
expect(status).toBe(500)
|
|
expect(typeof body.error).toBe('string')
|
|
// A non-deploy error must NOT silently fall back to the paged fetch.
|
|
expect(calls.some((c) => c.method === 'from')).toBe(false)
|
|
})
|
|
})
|
|
|
|
describe('POST /api/bookkeeping/accounts', () => {
|
|
it('returns 409 with a Swedish message on duplicate account number', async () => {
|
|
const { supabase } = createCapturingSupabase([{ error: { code: '23505', message: 'dup' } }])
|
|
auth(supabase)
|
|
const req = createMockRequest('/api/bookkeeping/accounts', {
|
|
method: 'POST',
|
|
body: {
|
|
account_number: '5010',
|
|
account_name: 'Lokalhyra',
|
|
account_type: 'expense',
|
|
normal_balance: 'debit',
|
|
},
|
|
})
|
|
const { status, body } = await parseJsonResponse<{ error: string }>(
|
|
await createPOST(req, routeParams)
|
|
)
|
|
expect(status).toBe(409)
|
|
expect(body.error).toContain('5010')
|
|
})
|
|
|
|
it('forwards default_vat_rate into the insert', async () => {
|
|
const { supabase, calls } = createCapturingSupabase([
|
|
{ data: { account_number: '3740', default_vat_rate: 0 } },
|
|
])
|
|
auth(supabase)
|
|
const req = createMockRequest('/api/bookkeeping/accounts', {
|
|
method: 'POST',
|
|
body: {
|
|
account_number: '3740',
|
|
account_name: 'Öres- och kronutjämning',
|
|
account_type: 'revenue',
|
|
normal_balance: 'debit',
|
|
default_vat_rate: 0,
|
|
},
|
|
})
|
|
const { status } = await parseJsonResponse(await createPOST(req, routeParams))
|
|
expect(status).toBe(200)
|
|
const insertArg = calls.find((c) => c.method === 'insert')?.args[0] as {
|
|
default_vat_rate?: number | null
|
|
}
|
|
expect(insertArg?.default_vat_rate).toBe(0)
|
|
})
|
|
})
|
|
|
|
describe('DELETE /api/bookkeeping/accounts/[number]', () => {
|
|
it('scopes the usage check to the company via the journal_entries join', async () => {
|
|
const { supabase, calls } = createCapturingSupabase([
|
|
{ data: { id: 'acc-1', is_system_account: false } }, // account fetch
|
|
{ count: 0 }, // usage count
|
|
{ data: null }, // delete
|
|
])
|
|
auth(supabase)
|
|
|
|
const { status } = await parseJsonResponse(
|
|
await DELETE(createMockRequest('/api/bookkeeping/accounts/5010'), numberParams)
|
|
)
|
|
|
|
expect(status).toBe(200)
|
|
const selectArgs = calls.filter((c) => c.method === 'select').map((c) => c.args[0])
|
|
expect(selectArgs).toContain('id, journal_entries!inner(company_id)')
|
|
const eqCalls = calls.filter((c) => c.method === 'eq').map((c) => c.args)
|
|
expect(eqCalls).toContainEqual(['journal_entries.company_id', 'company-1'])
|
|
})
|
|
|
|
it('refuses deleting an account used in this company with 400', async () => {
|
|
const { supabase } = createCapturingSupabase([
|
|
{ data: { id: 'acc-1', is_system_account: false } },
|
|
{ count: 3 },
|
|
])
|
|
auth(supabase)
|
|
|
|
const { status, body } = await parseJsonResponse<{ error: string }>(
|
|
await DELETE(createMockRequest('/api/bookkeeping/accounts/5010'), numberParams)
|
|
)
|
|
expect(status).toBe(400)
|
|
expect(body.error).toContain('Inaktivera')
|
|
})
|
|
|
|
it('refuses deleting a system account', async () => {
|
|
const { supabase } = createCapturingSupabase([
|
|
{ data: { id: 'acc-1', is_system_account: true } },
|
|
])
|
|
auth(supabase)
|
|
|
|
const { status } = await parseJsonResponse(
|
|
await DELETE(createMockRequest('/api/bookkeeping/accounts/5010'), numberParams)
|
|
)
|
|
expect(status).toBe(400)
|
|
})
|
|
})
|
|
|
|
describe('PUT /api/bookkeeping/accounts/[number]', () => {
|
|
it('returns 400 when the body has nothing to update', async () => {
|
|
const { supabase } = createCapturingSupabase([])
|
|
auth(supabase)
|
|
const req = createMockRequest('/api/bookkeeping/accounts/5010', { method: 'PUT', body: {} })
|
|
const { status } = await parseJsonResponse(await PUT(req, numberParams))
|
|
expect(status).toBe(400)
|
|
})
|
|
|
|
it('maps zero-rows (PGRST116) to 404', async () => {
|
|
const { supabase } = createCapturingSupabase([
|
|
{ error: { code: 'PGRST116', message: 'no rows' } },
|
|
])
|
|
auth(supabase)
|
|
const req = createMockRequest('/api/bookkeeping/accounts/5010', {
|
|
method: 'PUT',
|
|
body: { account_name: 'Nytt namn' },
|
|
})
|
|
const { status, body } = await parseJsonResponse<{ error: string }>(await PUT(req, numberParams))
|
|
expect(status).toBe(404)
|
|
expect(body.error).toBe('Kontot hittades inte')
|
|
})
|
|
|
|
it('updates the account', async () => {
|
|
const { supabase } = createCapturingSupabase([
|
|
{ data: { account_number: '5010', account_name: 'Nytt namn' } },
|
|
])
|
|
auth(supabase)
|
|
const req = createMockRequest('/api/bookkeeping/accounts/5010', {
|
|
method: 'PUT',
|
|
body: { account_name: 'Nytt namn' },
|
|
})
|
|
const { status, body } = await parseJsonResponse<{ data: { account_name: string } }>(
|
|
await PUT(req, numberParams)
|
|
)
|
|
expect(status).toBe(200)
|
|
expect(body.data.account_name).toBe('Nytt namn')
|
|
})
|
|
|
|
it('forwards default_vat_rate into the update', async () => {
|
|
const { supabase, calls } = createCapturingSupabase([
|
|
{ data: { account_number: '3740', default_vat_rate: 0 } },
|
|
])
|
|
auth(supabase)
|
|
const req = createMockRequest('/api/bookkeeping/accounts/3740', {
|
|
method: 'PUT',
|
|
body: { default_vat_rate: 0 },
|
|
})
|
|
const { status } = await parseJsonResponse(
|
|
await PUT(req, { params: Promise.resolve({ number: '3740' }) })
|
|
)
|
|
expect(status).toBe(200)
|
|
const updateArg = calls.find((c) => c.method === 'update')?.args[0] as {
|
|
default_vat_rate?: number | null
|
|
}
|
|
expect(updateArg?.default_vat_rate).toBe(0)
|
|
})
|
|
})
|
|
|
|
describe('POST /api/bookkeeping/accounts/activate', () => {
|
|
it('returns 400 (not a crash) on invalid JSON', async () => {
|
|
const { supabase } = createCapturingSupabase([])
|
|
auth(supabase)
|
|
const req = new Request('http://localhost/api/bookkeeping/accounts/activate', {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: '{not json',
|
|
})
|
|
const { status, body } = await parseJsonResponse<{ error: string }>(
|
|
await activatePOST(req, routeParams)
|
|
)
|
|
expect(status).toBe(400)
|
|
expect(body.error).toBe('account_numbers array required')
|
|
})
|
|
|
|
it('returns 400 when account_numbers is missing or empty', async () => {
|
|
const { supabase } = createCapturingSupabase([])
|
|
auth(supabase)
|
|
const req = createMockRequest('/api/bookkeeping/accounts/activate', {
|
|
method: 'POST',
|
|
body: { account_numbers: [] },
|
|
})
|
|
const { status } = await parseJsonResponse(await activatePOST(req, routeParams))
|
|
expect(status).toBe(400)
|
|
})
|
|
|
|
it('activates a known BAS account and buckets unknown numbers', async () => {
|
|
const { supabase } = createCapturingSupabase([
|
|
{ data: [] }, // existing lookup — none in chart
|
|
{ data: [{ account_number: '1930' }] }, // insert result
|
|
])
|
|
auth(supabase)
|
|
const req = createMockRequest('/api/bookkeeping/accounts/activate', {
|
|
method: 'POST',
|
|
body: { account_numbers: ['1930', '0000'] },
|
|
})
|
|
const { status, body } = await parseJsonResponse<{
|
|
activated: number
|
|
unknown: string[]
|
|
}>(await activatePOST(req, routeParams))
|
|
|
|
expect(status).toBe(200)
|
|
expect(body.activated).toBe(1)
|
|
expect(body.unknown).toEqual(['0000'])
|
|
})
|
|
})
|