* feat(api): test-mode API keys force dry-run on the v1 REST API A key created with mode='test' (prefix gnubok_sk_test_) binds to the real company, but the v1 wrapper forces dry_run on every write so nothing is persisted or sent. Mutations on endpoints that can't be simulated (dryRunSupported=false or unregistered) are refused with 403 TEST_KEY_WRITE_BLOCKED — fail-closed. Reads pass through unchanged and every test-key response carries X-Gnubok-Mode: test. Live keys are unaffected (mode defaults to 'live'). Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * feat(invoices): company default "Vår referens" + per-line sales-account override Add company_settings.default_our_reference (settings form, schema, type); the invoice editor pre-fills our_reference from it on new invoices only, never overwriting an edited draft. Separately, add an optional per-line försäljningskonto (class-3) override in the editor — left blank, the engine still derives the revenue account from the VAT rate, and reverse-charge/export lines ignore the override. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * feat(invoices): render a Swish payment QR on invoice PDFs Build the Swish "Type C" QR payload offline (no Swish API call) and embed it as a PNG in the invoice PDF payment box when Swish display is enabled, the invoice is in SEK, and the amount is positive. Also surface the invoice number in the payment box. Wired through every PDF render path: send, mark-sent and pdf routes (both legacy and v1), the recurring-schedule sender, and the staged-send commit. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * feat(bookkeeping): draft exclusion + correction-chain collapse on verifikationslista Extend list_fiscal_period_entries_with_related with two opt-in params: p_exclude_draft (keep drafts off the committed list — they get their own surface) and p_collapse_corrections (render a correction group as the single live correction, hiding the mechanical storno and the reversed original). Both default false; nothing is deleted, every voucher keeps its number, and a "show all" toggle exposes the full chain. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix(reports): link multi-year SIE periods so resultatrapport shows the prior year SIE import now sets fiscal_periods.previous_period_id in both directions when creating a period, so multi-year files chain correctly regardless of #RAR order. A backfill migration repairs periods imported before this (idempotent; only touches NULL links on first-of-month periods). generateResultatrapport falls back to the date-adjacent prior period when the chain is still null, so the comparison column works for legacy data too. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix(articles): hide the VAT field for non-momsregistrerade companies The article form reads company_settings.vat_registered and, when false, hides the moms field and forces vat_rate to 0 on submit — mirroring the invoice editor so a non-VAT-registered company never sets a rate it can't charge. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * feat(import): allow file-based imports in the sandbox Bank-file, CSV/Excel and SIE imports run entirely on uploaded data with no external service, so they're now reachable in the sandbox. Only the API-backed options that need live third-party credentials (PSD2 bank connection, provider migration) stay disabled. Updates the sandbox notice copy to match. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * feat(bookkeeping): add edit draft functionality for journal entries * feat(database): add default "Vår referens" column to company_settings for invoicing * fix(tests): set SHOW_SWISH_ON_INVOICE to false in PDF template mocks * @ fix(payments): use roundOre for Swish amount formatting Replace naive Math.round(x*100)/100 with roundOre from @/lib/money to satisfy the antipattern guard. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> @ --------- Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
229 lines
7.8 KiB
TypeScript
229 lines
7.8 KiB
TypeScript
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
|
import { createMockRequest, parseJsonResponse } from '@/tests/helpers'
|
|
|
|
// ── Mocks ──────────────────────────────────────────────────────────
|
|
// withRouteContext resolves auth via requireAuth (createClient under the hood),
|
|
// the active company via getActiveCompanyId, and the write gate via
|
|
// requireWritePermission. Mock all three so we can drive each branch.
|
|
|
|
const mockSupabase = {
|
|
auth: { getUser: vi.fn() },
|
|
from: vi.fn(),
|
|
}
|
|
|
|
vi.mock('@/lib/supabase/server', () => ({
|
|
createClient: () => Promise.resolve(mockSupabase),
|
|
}))
|
|
|
|
const getActiveCompanyIdMock = vi.fn()
|
|
vi.mock('@/lib/company/context', () => ({
|
|
getActiveCompanyId: (...args: unknown[]) => getActiveCompanyIdMock(...args),
|
|
}))
|
|
|
|
const requireWritePermissionMock = vi.fn()
|
|
vi.mock('@/lib/auth/require-write', () => ({
|
|
requireWritePermission: (...args: unknown[]) => requireWritePermissionMock(...args),
|
|
}))
|
|
|
|
import { POST } from '../route'
|
|
|
|
const mockUser = { id: 'user-1', email: 'test@test.se' }
|
|
|
|
// Records the payload passed to .insert(), and lets us program the count
|
|
// returned by the quota pre-check and the row returned by the insert.
|
|
function setupFrom(opts: {
|
|
count?: number | null
|
|
insertResult?: { data?: unknown; error?: unknown }
|
|
}) {
|
|
const insertSpy = vi.fn()
|
|
|
|
mockSupabase.from.mockImplementation(() => {
|
|
// The quota pre-check: .select(..., { head: true }).eq().is() → resolves
|
|
// to { count }. The insert: .insert().select().single() → resolves to the
|
|
// row. We expose both via a single chainable proxy whose terminal value
|
|
// depends on whether insert() was called.
|
|
let isInsert = false
|
|
const result = () =>
|
|
isInsert
|
|
? Promise.resolve({
|
|
data: opts.insertResult?.data ?? null,
|
|
error: opts.insertResult?.error ?? null,
|
|
})
|
|
: Promise.resolve({ count: opts.count ?? 0, data: null, error: null })
|
|
|
|
const chain: Record<string, unknown> = {}
|
|
const handler: ProxyHandler<object> = {
|
|
get(_t, prop) {
|
|
if (prop === 'then') {
|
|
return (resolve: (v: unknown) => void) => resolve(result() as unknown)
|
|
}
|
|
if (prop === 'insert') {
|
|
return (payload: unknown) => {
|
|
isInsert = true
|
|
insertSpy(payload)
|
|
return new Proxy(chain, handler)
|
|
}
|
|
}
|
|
if (prop === 'single' || prop === 'maybeSingle') {
|
|
return () => result()
|
|
}
|
|
return () => new Proxy(chain, handler)
|
|
},
|
|
}
|
|
return new Proxy(chain, handler)
|
|
})
|
|
|
|
return { insertSpy }
|
|
}
|
|
|
|
beforeEach(() => {
|
|
vi.clearAllMocks()
|
|
mockSupabase.auth.getUser.mockResolvedValue({ data: { user: mockUser } })
|
|
getActiveCompanyIdMock.mockResolvedValue('company-1')
|
|
requireWritePermissionMock.mockResolvedValue({ ok: true })
|
|
})
|
|
|
|
describe('POST /api/settings/api-keys', () => {
|
|
it('returns 401 when not authenticated', async () => {
|
|
mockSupabase.auth.getUser.mockResolvedValue({ data: { user: null } })
|
|
const res = await POST(
|
|
createMockRequest('/api/settings/api-keys', {
|
|
method: 'POST',
|
|
body: { name: 'k', scopes: ['reports:read'] },
|
|
}),
|
|
)
|
|
expect(res.status).toBe(401)
|
|
})
|
|
|
|
it('returns 400 for an invalid scope', async () => {
|
|
setupFrom({ count: 0 })
|
|
const res = await POST(
|
|
createMockRequest('/api/settings/api-keys', {
|
|
method: 'POST',
|
|
body: { name: 'k', scopes: ['totally:bogus'] },
|
|
}),
|
|
)
|
|
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(res)
|
|
expect(status).toBe(400)
|
|
expect(body.error.code).toBe('API_KEY_SCOPE_INVALID')
|
|
})
|
|
|
|
it('returns 409 API_KEY_SOD_CONFLICT for stage+approve without acknowledgement', async () => {
|
|
setupFrom({ count: 0 })
|
|
const res = await POST(
|
|
createMockRequest('/api/settings/api-keys', {
|
|
method: 'POST',
|
|
body: {
|
|
name: 'k',
|
|
scopes: ['invoices:write', 'pending_operations:approve'],
|
|
},
|
|
}),
|
|
)
|
|
const { status, body } = await parseJsonResponse<{
|
|
error: { code: string; details: { conflicting_scope: string; approve_scope: string } }
|
|
}>(res)
|
|
expect(status).toBe(409)
|
|
expect(body.error.code).toBe('API_KEY_SOD_CONFLICT')
|
|
expect(body.error.details.conflicting_scope).toBe('invoices:write')
|
|
expect(body.error.details.approve_scope).toBe('pending_operations:approve')
|
|
})
|
|
|
|
it('records sod_acknowledged_at/by in the insert when acknowledge_sod is true', async () => {
|
|
const { insertSpy } = setupFrom({
|
|
count: 0,
|
|
insertResult: {
|
|
data: {
|
|
id: 'ak-1',
|
|
key_prefix: 'gnubok_sk_abcd',
|
|
name: 'k',
|
|
scopes: ['invoices:write', 'pending_operations:approve'],
|
|
created_at: '2026-06-05T10:00:00Z',
|
|
},
|
|
},
|
|
})
|
|
const res = await POST(
|
|
createMockRequest('/api/settings/api-keys', {
|
|
method: 'POST',
|
|
body: {
|
|
name: 'k',
|
|
scopes: ['invoices:write', 'pending_operations:approve'],
|
|
acknowledge_sod: true,
|
|
},
|
|
}),
|
|
)
|
|
const { status, body } = await parseJsonResponse<{ data: { key: string } }>(res)
|
|
expect(status).toBe(200)
|
|
expect(body.data.key).toMatch(/^gnubok_sk_/)
|
|
|
|
expect(insertSpy).toHaveBeenCalledTimes(1)
|
|
const payload = insertSpy.mock.calls[0][0] as Record<string, unknown>
|
|
expect(payload.sod_acknowledged_by).toBe('user-1')
|
|
expect(typeof payload.sod_acknowledged_at).toBe('string')
|
|
// ISO timestamp
|
|
expect(payload.sod_acknowledged_at).toMatch(/^\d{4}-\d{2}-\d{2}T/)
|
|
})
|
|
|
|
it('creates a clean key without approve scope and does not set SoD fields', async () => {
|
|
const { insertSpy } = setupFrom({
|
|
count: 0,
|
|
insertResult: {
|
|
data: {
|
|
id: 'ak-2',
|
|
key_prefix: 'gnubok_sk_efgh',
|
|
name: 'reader',
|
|
scopes: ['reports:read'],
|
|
created_at: '2026-06-05T10:00:00Z',
|
|
},
|
|
},
|
|
})
|
|
const res = await POST(
|
|
createMockRequest('/api/settings/api-keys', {
|
|
method: 'POST',
|
|
body: { name: 'reader', scopes: ['reports:read'] },
|
|
}),
|
|
)
|
|
const { status } = await parseJsonResponse(res)
|
|
expect(status).toBe(200)
|
|
|
|
const payload = insertSpy.mock.calls[0][0] as Record<string, unknown>
|
|
expect(payload).not.toHaveProperty('sod_acknowledged_at')
|
|
expect(payload).not.toHaveProperty('sod_acknowledged_by')
|
|
expect(payload.scopes).toEqual(['reports:read'])
|
|
// Default mode is live, bound to the active company.
|
|
expect(payload.mode).toBe('live')
|
|
expect(payload.company_id).toBe('company-1')
|
|
})
|
|
|
|
it('creates a test key bound to the active company with mode=test', async () => {
|
|
const { insertSpy } = setupFrom({
|
|
count: 0,
|
|
insertResult: {
|
|
data: {
|
|
id: 'ak-3',
|
|
key_prefix: 'gnubok_sk_test_abc',
|
|
name: 'pilot',
|
|
scopes: ['reports:read'],
|
|
mode: 'test',
|
|
created_at: '2026-06-05T10:00:00Z',
|
|
},
|
|
},
|
|
})
|
|
const res = await POST(
|
|
createMockRequest('/api/settings/api-keys', {
|
|
method: 'POST',
|
|
body: { name: 'pilot', scopes: ['reports:read'], mode: 'test' },
|
|
}),
|
|
)
|
|
const { status, body } = await parseJsonResponse<{ data: { key: string } }>(res)
|
|
expect(status).toBe(200)
|
|
// Real generateApiKey('test') runs — the returned secret carries the infix.
|
|
expect(body.data.key).toMatch(/^gnubok_sk_test_/)
|
|
|
|
const payload = insertSpy.mock.calls[0][0] as Record<string, unknown>
|
|
expect(payload.mode).toBe('test')
|
|
// Test keys are simulation-only — they bind to the active company (the v1
|
|
// wrapper forces dry-run so they never persist).
|
|
expect(payload.company_id).toBe('company-1')
|
|
})
|
|
})
|