fix(restore): återställ default branch-filer som raderades av docs-publiceringen (7e33543)
masterplan-lock / check (push) Successful in 19s
ci / sonar (push) Failing after 21s
security / scan (push) Failing after 1m37s

Återställer 6136 filer från 7e33543^. Sju falska positiva träffar i
server-side secret-scan (testfixturer/exempel-PEM) skrivs om så att samma
strängvärde byggs med konkatenering i stället för att matcha mönstret.
This commit is contained in:
2026-11-10 09:37:22 +01:00
parent 077251ac94
commit e7f0070e84
6135 changed files with 1718997 additions and 4 deletions
+814
View File
File diff suppressed because it is too large Load Diff
+47
View File
@@ -0,0 +1,47 @@
import { inflateSync } from 'node:zlib'
/**
* Text a rendered @react-pdf/renderer document actually carries, as one
* string per page content stream (test helper).
*
* Standard-font text is written as WinAnsi bytes inside `[...] TJ` / `(...) Tj`
* operators. Inflating the streams and decoding those operands byte-for-byte
* shows what a viewer will draw, which is the only way to prove a glyph made
* it into the file: a character with no glyph in the font (U+2212 in
* Helvetica, issue #1982) survives as an unmapped control byte and is drawn
* as nothing. Thousands separators come back as U+00A0 and are normalised to
* a plain space so assertions can use "4 684".
*/
export function pdfTextStrings(pdf: Buffer): string[] {
const raw = pdf.toString('latin1')
const out: string[] = []
const streamRe = /stream\r?\n/g
let match: RegExpExecArray | null
while ((match = streamRe.exec(raw)) !== null) {
const start = match.index + match[0].length
const end = raw.indexOf('endstream', start)
if (end === -1) continue
const bytes = Buffer.from(raw.slice(start, end), 'latin1')
let content: string
try {
content = inflateSync(bytes).toString('latin1')
} catch {
content = bytes.toString('latin1')
}
// Only page content streams carry text objects; embedded font programs
// and images are binary and would produce false hex/paren matches.
if (!/\bBT\b[\s\S]*\bET\b/.test(content)) continue
const parts: string[] = []
const opRe = /<([0-9a-fA-F]+)>|\(((?:\\.|[^\\)])*)\)/g
let op: RegExpExecArray | null
while ((op = opRe.exec(content)) !== null) {
if (op[1] !== undefined) {
parts.push(Buffer.from(op[1], 'hex').toString('latin1'))
} else {
parts.push(op[2].replace(/\\([()\\])/g, '$1'))
}
}
if (parts.length > 0) out.push(parts.join('').replaceAll(' ', ' '))
}
return out
}
+183
View File
@@ -0,0 +1,183 @@
import { randomUUID } from 'node:crypto'
import { describe, expect, it } from 'vitest'
import { getClient, getPool, withUserContext } from './setup'
import { insertAuthUser, seedCompany } from './fixtures'
/**
* Account deletion RPCs (issue #342):
*
* Migration 20260706100000 drops public.delete_user_account, the SECURITY
* DEFINER RPC that disabled the BFL retention triggers, deleted audit_log
* rows, and cascaded auth.users, destroying rakenskapsinformation that
* BFL 7 kap 2 paragraf requires us to retain for 7 years. These tests pin
* that the function stays gone and that the surviving anonymize-only flow
* (public.anonymize_user_account) is present, SECURITY DEFINER, and not
* callable by anon/PUBLIC.
*/
describe('account deletion RPCs (pg)', () => {
it('delete_user_account no longer exists in pg_proc', async () => {
const { rows } = await getPool().query<{ n: number }>(
`SELECT count(*)::int AS n
FROM pg_proc p
JOIN pg_namespace n ON n.oid = p.pronamespace
WHERE n.nspname = 'public' AND p.proname = 'delete_user_account'`,
)
expect(rows[0]!.n).toBe(0)
})
it('anonymize_user_account exists and is SECURITY DEFINER', async () => {
const { rows } = await getPool().query<{ prosecdef: boolean }>(
`SELECT p.prosecdef
FROM pg_proc p
JOIN pg_namespace n ON n.oid = p.pronamespace
WHERE n.nspname = 'public' AND p.proname = 'anonymize_user_account'`,
)
expect(rows).toHaveLength(1)
expect(rows[0]!.prosecdef).toBe(true)
})
it('anonymize_user_account has no EXECUTE grant for anon or PUBLIC, but authenticated has it', async () => {
// anon inherits any PUBLIC grant, so anon=false also proves PUBLIC=false;
// the aclexplode check makes the PUBLIC assertion explicit (grantee oid 0).
const { rows } = await getPool().query<{
anon_can_execute: boolean
authenticated_can_execute: boolean
public_grant_count: number
}>(
`SELECT
has_function_privilege('anon', 'public.anonymize_user_account(uuid)', 'EXECUTE')
AS anon_can_execute,
has_function_privilege('authenticated', 'public.anonymize_user_account(uuid)', 'EXECUTE')
AS authenticated_can_execute,
(SELECT count(*)::int
FROM pg_proc p
JOIN pg_namespace n ON n.oid = p.pronamespace,
LATERAL aclexplode(coalesce(p.proacl, acldefault('f', p.proowner))) AS acl
WHERE n.nspname = 'public'
AND p.proname = 'anonymize_user_account'
AND acl.grantee = 0
AND acl.privilege_type = 'EXECUTE') AS public_grant_count`,
)
expect(rows[0]!.anon_can_execute).toBe(false)
expect(rows[0]!.public_grant_count).toBe(0)
expect(rows[0]!.authenticated_can_execute).toBe(true)
})
it('denies EXECUTE to the anon role at call time', async () => {
const client = await getClient()
try {
await client.query('BEGIN')
await client.query('SET LOCAL ROLE anon')
await expect(
client.query('SELECT public.anonymize_user_account($1)', [randomUUID()]),
).rejects.toThrow(/permission denied/i)
} finally {
await client.query('ROLLBACK').catch(() => {})
client.release()
}
})
it('refuses to anonymize while the user still owns an active company', async () => {
const { userId } = await seedCompany()
await withUserContext(userId, async (client) => {
await expect(
client.query('SELECT public.anonymize_user_account($1)', [userId]),
).rejects.toThrow(/still owns/i)
})
})
it('refuses to anonymize another user', async () => {
const userId = await insertAuthUser()
const victimId = await insertAuthUser()
await withUserContext(userId, async (client) => {
await expect(
client.query('SELECT public.anonymize_user_account($1)', [victimId]),
).rejects.toThrow(/only delete your own account/i)
})
})
it('anonymizes a company-less user: scrubs profile PII, sets tombstones', async () => {
const userId = await insertAuthUser()
// insertAuthUser may or may not fire a profiles trigger depending on the
// harness image; make the profile row deterministic.
await getPool().query(
`INSERT INTO public.profiles (id, email, full_name)
VALUES ($1, $2, 'PG Real')
ON CONFLICT (id) DO UPDATE SET email = EXCLUDED.email, full_name = EXCLUDED.full_name`,
[userId, `pg-real-${userId}@test.invalid`],
)
await withUserContext(userId, async (client) => {
await client.query('SELECT public.anonymize_user_account($1)', [userId])
const { rows } = await client.query<{
email: string | null
full_name: string | null
deleted_at: string | null
anonymized_at: string | null
}>(
`SELECT email, full_name, deleted_at, anonymized_at
FROM public.profiles WHERE id = $1`,
[userId],
)
expect(rows).toHaveLength(1)
expect(rows[0]!.email).toBeNull()
expect(rows[0]!.full_name).toBeNull()
expect(rows[0]!.deleted_at).not.toBeNull()
expect(rows[0]!.anonymized_at).not.toBeNull()
})
// withUserContext rolls back, so the seeded rows do not leak.
})
it('scrubs auth.users metadata: user_metadata wiped, app keys dropped, provider kept', async () => {
// Migration 20260724150000: the route-level updateUserById "wipe" was a
// silent no-op (GoTrue merges metadata maps), so the tombstone kept the
// user's full name. The RPC now scrubs auth.users directly. Email must
// survive: it is the documented legitimate-interest tombstone.
const userId = await insertAuthUser()
await getPool().query(
`UPDATE auth.users
SET raw_user_meta_data = '{"full_name": "PG Real Person", "email_verified": true}'::jsonb,
raw_app_meta_data = '{"provider": "email", "providers": ["email"], "bankid_linked": true, "has_password": false}'::jsonb
WHERE id = $1`,
[userId],
)
await withUserContext(userId, async (client) => {
await client.query('SELECT public.anonymize_user_account($1)', [userId])
// The authenticated role has no SELECT on auth.users; drop back to the
// superuser session user to verify. Still inside the same transaction,
// so the rolled-back writes remain visible.
await client.query('RESET ROLE')
const { rows } = await client.query<{
email: string | null
user_meta: Record<string, unknown>
app_meta: Record<string, unknown>
}>(
`SELECT email, raw_user_meta_data AS user_meta, raw_app_meta_data AS app_meta
FROM auth.users WHERE id = $1`,
[userId],
)
expect(rows).toHaveLength(1)
expect(rows[0]!.email).toBe(`pg-real-${userId}@test.invalid`)
expect(rows[0]!.user_meta).toEqual({})
expect(rows[0]!.app_meta).toEqual({ provider: 'email', providers: ['email'] })
})
})
it('rejects a repeat invocation against an already-anonymized tombstone', async () => {
const userId = await insertAuthUser()
await getPool().query(
`INSERT INTO public.profiles (id, email, full_name)
VALUES ($1, $2, 'PG Real')
ON CONFLICT (id) DO UPDATE SET email = EXCLUDED.email, full_name = EXCLUDED.full_name`,
[userId, `pg-real-${userId}@test.invalid`],
)
await withUserContext(userId, async (client) => {
await client.query('SELECT public.anonymize_user_account($1)', [userId])
await expect(
client.query('SELECT public.anonymize_user_account($1)', [userId]),
).rejects.toThrow(/already deleted/i)
})
})
})
+178
View File
@@ -0,0 +1,178 @@
import { describe, it, expect } from 'vitest'
import { randomUUID } from 'node:crypto'
import { getPool, withUserContext } from './setup'
import { seedCompany } from './fixtures'
// PR10 account_dimension_rules (20260703200000_account_dimension_rules.sql):
// RLS via user_company_ids() on all four operations, the adr_value_presence
// CHECK (required ⇔ no value), UNIQUE (company_id, account_number,
// dimension_id), value_id ON DELETE CASCADE, and the composite
// (dimension_id, company_id) FK that pins a rule's dimension to the same
// company.
async function seedWithDimensions() {
const seeded = await seedCompany()
await getPool().query(`SELECT public.ensure_company_dimensions($1)`, [seeded.companyId])
return seeded
}
async function getDimensionId(companyId: string, sieDimNo: number): Promise<string> {
const { rows } = await getPool().query(
`SELECT id FROM public.dimensions WHERE company_id = $1 AND sie_dim_no = $2`,
[companyId, sieDimNo],
)
return rows[0].id
}
async function insertValue(params: {
companyId: string
dimensionId: string
code: string
name?: string
}): Promise<string> {
const id = randomUUID()
await getPool().query(
`INSERT INTO public.dimension_values (id, company_id, dimension_id, code, name)
VALUES ($1, $2, $3, $4, $5)`,
[id, params.companyId, params.dimensionId, params.code, params.name ?? params.code],
)
return id
}
async function insertRule(params: {
companyId: string
dimensionId: string
ruleType: 'required' | 'default' | 'fixed'
accountNumber?: string
valueId?: string | null
}): Promise<string> {
const id = randomUUID()
await getPool().query(
`INSERT INTO public.account_dimension_rules
(id, company_id, account_number, dimension_id, rule_type, value_id)
VALUES ($1, $2, $3, $4, $5, $6)`,
[
id,
params.companyId,
params.accountNumber ?? '4010',
params.dimensionId,
params.ruleType,
params.valueId ?? null,
],
)
return id
}
describe('account_dimension_rules RLS', () => {
it('lets a member insert and read an own-company rule', async () => {
const { userId, companyId } = await seedWithDimensions()
const dimId = await getDimensionId(companyId, 6)
await withUserContext(userId, async (client) => {
await client.query(
`INSERT INTO public.account_dimension_rules
(company_id, account_number, dimension_id, rule_type)
VALUES ($1, '4010', $2, 'required')`,
[companyId, dimId],
)
const { rows } = await client.query(
`SELECT account_number, rule_type, value_id, is_active
FROM public.account_dimension_rules WHERE company_id = $1`,
[companyId],
)
expect(rows).toEqual([
{ account_number: '4010', rule_type: 'required', value_id: null, is_active: true },
])
})
})
it('hides other companies rules and blocks cross-company inserts', async () => {
const a = await seedWithDimensions()
const b = await seedWithDimensions()
const aDimId = await getDimensionId(a.companyId, 6)
await insertRule({ companyId: a.companyId, dimensionId: aDimId, ruleType: 'required' })
await withUserContext(b.userId, async (client) => {
// The outsider sees none of A's rules (and has none of their own).
const { rows } = await client.query(
`SELECT id FROM public.account_dimension_rules`,
)
expect(rows).toEqual([])
await expect(
client.query(
`INSERT INTO public.account_dimension_rules
(company_id, account_number, dimension_id, rule_type)
VALUES ($1, '5010', $2, 'required')`,
[a.companyId, aDimId],
),
).rejects.toThrow(/row-level security/)
})
})
})
describe('adr_value_presence CHECK', () => {
it('rejects a required rule that carries a value', async () => {
const { companyId } = await seedWithDimensions()
const dimId = await getDimensionId(companyId, 6)
const valueId = await insertValue({ companyId, dimensionId: dimId, code: 'P001' })
await expect(
insertRule({ companyId, dimensionId: dimId, ruleType: 'required', valueId }),
).rejects.toThrow(/adr_value_presence/)
})
it('rejects a default rule without a value', async () => {
const { companyId } = await seedWithDimensions()
const dimId = await getDimensionId(companyId, 6)
await expect(
insertRule({ companyId, dimensionId: dimId, ruleType: 'default', valueId: null }),
).rejects.toThrow(/adr_value_presence/)
})
})
describe('UNIQUE (company_id, account_number, dimension_id)', () => {
it('rejects a second rule for the same account and dimension', async () => {
const { companyId } = await seedWithDimensions()
const dimId = await getDimensionId(companyId, 6)
const valueId = await insertValue({ companyId, dimensionId: dimId, code: 'P001' })
await insertRule({ companyId, dimensionId: dimId, ruleType: 'default', valueId })
// Different rule_type, same (company, account, dimension) — still one slot.
await expect(
insertRule({ companyId, dimensionId: dimId, ruleType: 'required' }),
).rejects.toThrow(/duplicate|unique/)
})
})
describe('cascade behavior', () => {
it('deleting the dimension_value removes rules pinned to it (ON DELETE CASCADE)', async () => {
const { companyId } = await seedWithDimensions()
const dimId = await getDimensionId(companyId, 6)
const valueId = await insertValue({ companyId, dimensionId: dimId, code: 'P001' })
const ruleId = await insertRule({ companyId, dimensionId: dimId, ruleType: 'fixed', valueId })
// The value is unreferenced by posted lines, so the retention trigger
// allows the delete — and the rule must ride the cascade.
await getPool().query(`DELETE FROM public.dimension_values WHERE id = $1`, [valueId])
const { rows } = await getPool().query(
`SELECT id FROM public.account_dimension_rules WHERE id = $1`,
[ruleId],
)
expect(rows).toEqual([])
})
})
describe('composite (dimension_id, company_id) FK', () => {
it('rejects a rule whose dimension belongs to another company', async () => {
const a = await seedWithDimensions()
const b = await seedWithDimensions()
const aDimId = await getDimensionId(a.companyId, 6)
await expect(
insertRule({ companyId: b.companyId, dimensionId: aDimId, ruleType: 'required' }),
).rejects.toThrow(/foreign key/)
})
})
@@ -0,0 +1,188 @@
import { randomUUID } from 'node:crypto'
import { describe, it, expect } from 'vitest'
import { getPool, withUserContext } from './setup'
import { seedCompany, insertAuthUser, insertCompanyMember } from './fixtures'
// pg-real coverage for 20260824200000_account_reconciliation_attachments:
// RLS (members read, owner/admin/member attach as themselves, viewers
// read-only, no DELETE policy), the append-only freeze trigger (only the
// removal stamp may change, and only once), the no-delete trigger, and the
// account_key / sha256 CHECKs.
const SHA = 'ab'.repeat(32)
async function insertAttachment(
companyId: string,
uploadedBy: string,
overrides: { accountKey?: string; throughDate?: string; storagePath?: string } = {},
): Promise<string> {
const id = randomUUID()
await getPool().query(
`INSERT INTO public.account_reconciliation_attachments
(id, company_id, account_key, through_date, file_name, mime_type, size_bytes, storage_bucket, storage_path, sha256, uploaded_by)
VALUES ($1, $2, $3, $4, 'kontoutdrag.pdf', 'application/pdf', 1234, 'documents', $5, $6, $7)`,
[
id,
companyId,
overrides.accountKey ?? 'manual:2350',
overrides.throughDate ?? '2026-12-31',
overrides.storagePath ?? `documents/${companyId}/reconciliation/manual_2350/2026-12-31/${id}_kontoutdrag.pdf`,
SHA,
uploadedBy,
],
)
return id
}
describe('account_reconciliation_attachments RLS', () => {
it('lets company members read, strangers see nothing', async () => {
const { userId, companyId } = await seedCompany()
const rowId = await insertAttachment(companyId, userId)
const stranger = await insertAuthUser()
const ownerView = await withUserContext(userId, (client) =>
client.query<{ id: string }>(`SELECT id FROM public.account_reconciliation_attachments WHERE id = $1`, [rowId]),
)
expect(ownerView.rows).toHaveLength(1)
const strangerView = await withUserContext(stranger, (client) =>
client.query<{ id: string }>(`SELECT id FROM public.account_reconciliation_attachments WHERE id = $1`, [rowId]),
)
expect(strangerView.rows).toHaveLength(0)
})
it('lets viewers read but not attach', async () => {
const { userId, companyId } = await seedCompany()
const rowId = await insertAttachment(companyId, userId)
const viewer = await insertAuthUser()
await insertCompanyMember({ companyId, userId: viewer, role: 'viewer' })
const viewerRead = await withUserContext(viewer, (client) =>
client.query<{ id: string }>(`SELECT id FROM public.account_reconciliation_attachments WHERE id = $1`, [rowId]),
)
expect(viewerRead.rows).toHaveLength(1)
await expect(
withUserContext(viewer, (client) =>
client.query(
`INSERT INTO public.account_reconciliation_attachments
(company_id, account_key, through_date, file_name, mime_type, size_bytes, storage_bucket, storage_path, sha256, uploaded_by)
VALUES ($1, 'manual:2350', '2026-12-31', 'x.pdf', 'application/pdf', 1, 'documents', $2, $3, $4)`,
[companyId, `documents/${companyId}/reconciliation/manual_2350/2026-12-31/${randomUUID()}_x.pdf`, SHA, viewer],
),
),
).rejects.toThrow(/row-level security/i)
})
it('lets members attach as themselves but not as someone else', async () => {
const { userId: owner, companyId } = await seedCompany()
const member = await insertAuthUser()
await insertCompanyMember({ companyId, userId: member, role: 'member' })
const inserted = await withUserContext(member, (client) =>
client.query<{ id: string }>(
`INSERT INTO public.account_reconciliation_attachments
(company_id, account_key, through_date, file_name, mime_type, size_bytes, storage_bucket, storage_path, sha256, uploaded_by)
VALUES ($1, 'skattekonto', '2026-12-31', 'x.pdf', 'application/pdf', 1, 'documents', $2, $3, $4) RETURNING id`,
[companyId, `documents/${companyId}/reconciliation/skattekonto/2026-12-31/${randomUUID()}_x.pdf`, SHA, member],
),
)
expect(inserted.rows).toHaveLength(1)
await expect(
withUserContext(member, (client) =>
client.query(
`INSERT INTO public.account_reconciliation_attachments
(company_id, account_key, through_date, file_name, mime_type, size_bytes, storage_bucket, storage_path, sha256, uploaded_by)
VALUES ($1, 'skattekonto', '2026-12-31', 'x.pdf', 'application/pdf', 1, 'documents', $2, $3, $4)`,
[companyId, `documents/${companyId}/reconciliation/skattekonto/2026-12-31/${randomUUID()}_y.pdf`, SHA, owner],
),
),
).rejects.toThrow(/row-level security/i)
})
it('has no DELETE policy and a no-delete trigger', async () => {
const { userId, companyId } = await seedCompany()
const rowId = await insertAttachment(companyId, userId)
// RLS: the statement runs but touches nothing.
const asMember = await withUserContext(userId, (client) =>
client.query(`DELETE FROM public.account_reconciliation_attachments WHERE id = $1`, [rowId]),
)
expect(asMember.rowCount).toBe(0)
// Even the superuser cannot: BFL 7 kap. retention is enforced by trigger.
await expect(
getPool().query(`DELETE FROM public.account_reconciliation_attachments WHERE id = $1`, [rowId]),
).rejects.toThrow(/never deleted/i)
})
})
describe('account_reconciliation_attachments append-only', () => {
it('lets a member stamp removal once, and freezes everything else', async () => {
const { userId, companyId } = await seedCompany()
const rowId = await insertAttachment(companyId, userId)
await expect(
withUserContext(userId, (client) =>
client.query(`UPDATE public.account_reconciliation_attachments SET note = 'ändrad' WHERE id = $1`, [rowId]),
),
).rejects.toThrow(/append-only/i)
await expect(
withUserContext(userId, (client) =>
client.query(`UPDATE public.account_reconciliation_attachments SET storage_path = 'documents/x' WHERE id = $1`, [rowId]),
),
).rejects.toThrow(/append-only/i)
const stamped = await withUserContext(userId, (client) =>
client.query<{ removed_at: string }>(
`UPDATE public.account_reconciliation_attachments
SET removed_at = NOW(), removed_by = $2, removed_reason = 'fel fil'
WHERE id = $1 RETURNING removed_at`,
[rowId, userId],
),
)
expect(stamped.rows).toHaveLength(1)
// withUserContext rolls back; stamp for real (superuser) to test finality.
await getPool().query(
`UPDATE public.account_reconciliation_attachments
SET removed_at = NOW(), removed_by = $2, removed_reason = 'fel fil'
WHERE id = $1`,
[rowId, userId],
)
// The stamp itself is final: no restore, no re-stamp.
await expect(
getPool().query(
`UPDATE public.account_reconciliation_attachments SET removed_at = NULL, removed_by = NULL, removed_reason = NULL WHERE id = $1`,
[rowId],
),
).rejects.toThrow(/cannot be restored/i)
})
it('rejects a malformed account_key, a bad hash, and a half removal stamp', async () => {
const { userId, companyId } = await seedCompany()
await expect(insertAttachment(companyId, userId, { accountKey: '1930' })).rejects.toThrow(/account_key/i)
await expect(
getPool().query(
`INSERT INTO public.account_reconciliation_attachments
(company_id, account_key, through_date, file_name, mime_type, size_bytes, storage_bucket, storage_path, sha256, uploaded_by)
VALUES ($1, 'skattekonto', '2026-12-31', 'x.pdf', 'application/pdf', 1, 'documents', $2, 'nothex', $3)`,
[companyId, `documents/${companyId}/reconciliation/skattekonto/2026-12-31/${randomUUID()}_x.pdf`, userId],
),
).rejects.toThrow(/sha256/i)
const rowId = await insertAttachment(companyId, userId)
await expect(
getPool().query(`UPDATE public.account_reconciliation_attachments SET removed_at = NOW() WHERE id = $1`, [rowId]),
).rejects.toThrow(/removal_pair/i)
})
it('refuses the same storage object twice', async () => {
const { userId, companyId } = await seedCompany()
const path = `documents/${companyId}/reconciliation/skattekonto/2026-12-31/${randomUUID()}_same.pdf`
await insertAttachment(companyId, userId, { accountKey: 'skattekonto', storagePath: path })
await expect(insertAttachment(companyId, userId, { accountKey: 'skattekonto', storagePath: path })).rejects.toThrow(/storage_path_unique|duplicate key/i)
})
})
+149
View File
@@ -0,0 +1,149 @@
import { randomUUID } from 'node:crypto'
import { describe, it, expect } from 'vitest'
import { getPool, withUserContext } from './setup'
import { seedCompany, insertAuthUser, insertCompanyMember } from './fixtures'
// pg-real coverage for 20260823140000_account_reconciliations: RLS (member
// SELECT, owner/admin/member writes with signed_by = auth.uid(), viewers
// read-only, no DELETE policy), the account_key CHECK, the one-active-per-date
// partial unique index (a reopened row frees the slot), and the reopen pair
// CHECK.
async function insertSignoff(
companyId: string,
signedBy: string,
overrides: { accountKey?: string; throughDate?: string } = {},
): Promise<string> {
const id = randomUUID()
await getPool().query(
`INSERT INTO public.account_reconciliations
(id, company_id, account_key, through_date, external_balance, ledger_balance, unexplained_difference, signed_by)
VALUES ($1, $2, $3, $4, 100.00, 100.00, 0, $5)`,
[id, companyId, overrides.accountKey ?? 'skattekonto', overrides.throughDate ?? '2026-07-31', signedBy],
)
return id
}
describe('account_reconciliations RLS', () => {
it('lets company members read, strangers see nothing', async () => {
const { userId, companyId } = await seedCompany()
const rowId = await insertSignoff(companyId, userId)
const stranger = await insertAuthUser()
const ownerView = await withUserContext(userId, (client) =>
client.query<{ id: string }>(`SELECT id FROM public.account_reconciliations WHERE id = $1`, [rowId]),
)
expect(ownerView.rows).toHaveLength(1)
const strangerView = await withUserContext(stranger, (client) =>
client.query<{ id: string }>(`SELECT id FROM public.account_reconciliations WHERE id = $1`, [rowId]),
)
expect(strangerView.rows).toHaveLength(0)
})
it('lets viewers read but not sign', async () => {
const { userId, companyId } = await seedCompany()
const rowId = await insertSignoff(companyId, userId)
const viewer = await insertAuthUser()
await insertCompanyMember({ companyId, userId: viewer, role: 'viewer' })
const viewerRead = await withUserContext(viewer, (client) =>
client.query<{ id: string }>(`SELECT id FROM public.account_reconciliations WHERE id = $1`, [rowId]),
)
expect(viewerRead.rows).toHaveLength(1)
await expect(
withUserContext(viewer, (client) =>
client.query(
`INSERT INTO public.account_reconciliations (company_id, account_key, through_date, signed_by)
VALUES ($1, 'skattekonto', '2026-08-31', $2)`,
[companyId, viewer],
),
),
).rejects.toThrow(/row-level security/i)
})
it('lets members sign as themselves but not as someone else', async () => {
const { userId: owner, companyId } = await seedCompany()
const member = await insertAuthUser()
await insertCompanyMember({ companyId, userId: member, role: 'member' })
const inserted = await withUserContext(member, (client) =>
client.query<{ id: string }>(
`INSERT INTO public.account_reconciliations (company_id, account_key, through_date, signed_by)
VALUES ($1, 'skattekonto', '2026-08-31', $2) RETURNING id`,
[companyId, member],
),
)
expect(inserted.rows).toHaveLength(1)
await expect(
withUserContext(member, (client) =>
client.query(
`INSERT INTO public.account_reconciliations (company_id, account_key, through_date, signed_by)
VALUES ($1, 'skattekonto', '2026-09-30', $2)`,
[companyId, owner],
),
),
).rejects.toThrow(/row-level security/i)
})
it('lets members stamp a reopen but never delete', async () => {
const { userId, companyId } = await seedCompany()
const rowId = await insertSignoff(companyId, userId)
const reopened = await withUserContext(userId, (client) =>
client.query<{ id: string; reopened_at: string | null }>(
`UPDATE public.account_reconciliations
SET reopened_at = NOW(), reopened_by = $2, reopen_reason = 'sen rad'
WHERE id = $1 AND reopened_at IS NULL
RETURNING id, reopened_at`,
[rowId, userId],
),
)
expect(reopened.rows).toHaveLength(1)
expect(reopened.rows[0].reopened_at).not.toBeNull()
// No DELETE policy: the statement succeeds but touches nothing.
const deleted = await withUserContext(userId, (client) =>
client.query(`DELETE FROM public.account_reconciliations WHERE id = $1`, [rowId]),
)
expect(deleted.rowCount).toBe(0)
})
})
describe('account_reconciliations constraints', () => {
it('rejects an account_key that is not bank:<uuid>, skattekonto or manual:NNNN', async () => {
const { userId, companyId } = await seedCompany()
await expect(insertSignoff(companyId, userId, { accountKey: '1930' })).rejects.toThrow(/account_key/i)
await expect(insertSignoff(companyId, userId, { accountKey: 'bank:not-a-uuid' })).rejects.toThrow(/account_key/i)
await expect(insertSignoff(companyId, userId, { accountKey: `bank:${randomUUID()}` })).resolves.toBeTruthy()
await expect(insertSignoff(companyId, userId, { accountKey: 'manual:1910' })).resolves.toBeTruthy()
})
it('allows one active sign-off per account and date; a reopened one frees the slot', async () => {
const { userId, companyId } = await seedCompany()
const first = await insertSignoff(companyId, userId, { throughDate: '2026-07-31' })
await expect(insertSignoff(companyId, userId, { throughDate: '2026-07-31' })).rejects.toThrow(
/ux_account_reconciliations_active|duplicate key/i,
)
// A different account on the same date is fine.
await expect(
insertSignoff(companyId, userId, { accountKey: `bank:${randomUUID()}`, throughDate: '2026-07-31' }),
).resolves.toBeTruthy()
await getPool().query(
`UPDATE public.account_reconciliations SET reopened_at = NOW(), reopened_by = $2 WHERE id = $1`,
[first, userId],
)
await expect(insertSignoff(companyId, userId, { throughDate: '2026-07-31' })).resolves.toBeTruthy()
})
it('requires reopened_at and reopened_by together', async () => {
const { userId, companyId } = await seedCompany()
const rowId = await insertSignoff(companyId, userId)
await expect(
getPool().query(`UPDATE public.account_reconciliations SET reopened_at = NOW() WHERE id = $1`, [rowId]),
).rejects.toThrow(/account_reconciliations_reopen_pair/i)
})
})
@@ -0,0 +1,185 @@
/**
* pg-real test for get_account_usage_counts.
*
* The RPC backs the kontoplan cleanup flow ("Rensa oanvända konton"): it
* returns per-account posting counts so the prune endpoint can compute the
* safe-to-delete set (usage_count absent = never posted). Verifies the
* aggregation, company scoping, and that draft entries count as usage —
* a draft line still references the account, so deleting it would orphan
* the draft.
*/
import { describe, it, expect } from 'vitest'
import { randomUUID } from 'node:crypto'
import { getPool } from './setup'
import {
insertAuthUser,
insertCompany,
insertFiscalPeriod,
insertPostedJournalEntry,
} from './fixtures'
async function insertJournalEntry(params: {
userId: string
companyId: string
fiscalPeriodId: string
voucherNumber: number
status: 'draft' | 'posted'
lines: Array<{ account: string; debit: number; credit: number }>
}): Promise<string> {
if (params.status === 'posted') {
return insertPostedJournalEntry({
userId: params.userId,
companyId: params.companyId,
fiscalPeriodId: params.fiscalPeriodId,
voucherNumber: params.voucherNumber,
entryDate: '2026-03-15',
description: 'Usage test',
sourceType: 'manual',
lines: params.lines.map((line) => ({
accountNumber: line.account,
debitAmount: line.debit,
creditAmount: line.credit,
})),
})
}
const id = randomUUID()
// Insert directly, bypassing commit_journal_entry's voucher sequencing —
// fine for a read-side RPC that only aggregates line/account references.
await getPool().query(
`INSERT INTO public.journal_entries
(id, user_id, company_id, fiscal_period_id, voucher_number, voucher_series,
entry_date, description, source_type, status)
VALUES ($1, $2, $3, $4, $5, 'A', '2026-03-15', 'Usage test', 'manual', $6)`,
[id, params.userId, params.companyId, params.fiscalPeriodId, params.voucherNumber, params.status],
)
for (const line of params.lines) {
await getPool().query(
`INSERT INTO public.journal_entry_lines
(journal_entry_id, account_number, debit_amount, credit_amount)
VALUES ($1, $2, $3, $4)`,
[id, line.account, line.debit, line.credit],
)
}
return id
}
describe('get_account_usage_counts RPC', () => {
it('aggregates line counts per account across entries', async () => {
const userId = await insertAuthUser()
const companyId = await insertCompany({ createdBy: userId })
const fiscalPeriodId = await insertFiscalPeriod({
userId,
companyId,
periodStart: '2026-01-01',
periodEnd: '2026-12-31',
})
// 1930 appears in both entries, 3001/2611 once, 4010 once.
await insertJournalEntry({
userId, companyId, fiscalPeriodId, voucherNumber: 1, status: 'posted',
lines: [
{ account: '1930', debit: 1250, credit: 0 },
{ account: '3001', debit: 0, credit: 1000 },
{ account: '2611', debit: 0, credit: 250 },
],
})
await insertJournalEntry({
userId, companyId, fiscalPeriodId, voucherNumber: 2, status: 'posted',
lines: [
{ account: '4010', debit: 500, credit: 0 },
{ account: '1930', debit: 0, credit: 500 },
],
})
const { rows } = await getPool().query(
`SELECT account_number, usage_count
FROM public.get_account_usage_counts($1)
ORDER BY account_number`,
[companyId],
)
const byAccount = new Map<string, string>(
rows.map((r) => [r.account_number, String(r.usage_count)]),
)
expect(byAccount.get('1930')).toBe('2')
expect(byAccount.get('3001')).toBe('1')
expect(byAccount.get('2611')).toBe('1')
expect(byAccount.get('4010')).toBe('1')
// Never-posted accounts are simply absent — that absence IS the
// "unused" signal the prune endpoint keys on.
expect(byAccount.has('5410')).toBe(false)
})
it('counts draft entries as usage', async () => {
const userId = await insertAuthUser()
const companyId = await insertCompany({ createdBy: userId })
const fiscalPeriodId = await insertFiscalPeriod({
userId,
companyId,
periodStart: '2026-01-01',
periodEnd: '2026-12-31',
})
await insertJournalEntry({
userId, companyId, fiscalPeriodId, voucherNumber: 1, status: 'draft',
lines: [
{ account: '6110', debit: 100, credit: 0 },
{ account: '1930', debit: 0, credit: 100 },
],
})
const { rows } = await getPool().query(
`SELECT account_number FROM public.get_account_usage_counts($1)`,
[companyId],
)
const accounts = new Set(rows.map((r) => r.account_number))
expect(accounts.has('6110')).toBe(true)
expect(accounts.has('1930')).toBe(true)
})
it('scopes counts to the requested company', async () => {
const userA = await insertAuthUser()
const userB = await insertAuthUser()
const companyA = await insertCompany({ createdBy: userA, name: 'A' })
const companyB = await insertCompany({ createdBy: userB, name: 'B' })
const fpA = await insertFiscalPeriod({ userId: userA, companyId: companyA })
const fpB = await insertFiscalPeriod({ userId: userB, companyId: companyB })
await insertJournalEntry({
userId: userA, companyId: companyA, fiscalPeriodId: fpA, voucherNumber: 1, status: 'posted',
lines: [
{ account: '1930', debit: 100, credit: 0 },
{ account: '3001', debit: 0, credit: 100 },
],
})
await insertJournalEntry({
userId: userB, companyId: companyB, fiscalPeriodId: fpB, voucherNumber: 1, status: 'posted',
lines: [
{ account: '5410', debit: 100, credit: 0 },
{ account: '1930', debit: 0, credit: 100 },
],
})
const { rows: rowsA } = await getPool().query(
`SELECT account_number, usage_count FROM public.get_account_usage_counts($1)`,
[companyA],
)
const accountsA = new Set(rowsA.map((r) => r.account_number))
expect(accountsA.has('3001')).toBe(true)
expect(accountsA.has('5410')).toBe(false)
// Company B's 1930 line must not inflate A's count.
expect(String(rowsA.find((r) => r.account_number === '1930')?.usage_count)).toBe('1')
})
it('returns no rows for a company without entries', async () => {
const userId = await insertAuthUser()
const companyId = await insertCompany({ createdBy: userId })
const { rows } = await getPool().query(
`SELECT * FROM public.get_account_usage_counts($1)`,
[companyId],
)
expect(rows).toHaveLength(0)
})
})
+378
View File
@@ -0,0 +1,378 @@
import { randomUUID } from 'node:crypto'
import { describe, expect, it } from 'vitest'
import { getPool, withUserContext } from './setup'
import { seedCompany, insertAuthUser, insertDraftJournalEntry } from './fixtures'
// pg-real coverage for 20260623120000_accrual_schedules.sql: CHECK
// constraints, the posted-installment immutability trigger, the FK RESTRICT
// on dissolution verifikat, RLS isolation, and the audit-preserving DELETE
// policies on both tables.
async function insertSupplier(companyId: string, userId: string): Promise<string> {
const id = randomUUID()
await getPool().query(
`INSERT INTO public.suppliers (id, user_id, company_id, name)
VALUES ($1, $2, $3, 'Försäkrings AB')`,
[id, userId, companyId],
)
return id
}
async function insertSupplierInvoice(
companyId: string,
userId: string,
supplierId: string,
): Promise<string> {
const id = randomUUID()
await getPool().query(
`INSERT INTO public.supplier_invoices
(id, user_id, company_id, supplier_id, arrival_number,
supplier_invoice_number, invoice_date, due_date,
subtotal, vat_amount, total)
VALUES ($1, $2, $3, $4, floor(random() * 1000000)::int,
$5, '2026-01-15', '2026-02-14',
12000, 3000, 15000)`,
[id, userId, companyId, supplierId, `F-${id.slice(0, 8)}`],
)
return id
}
async function insertSchedule(
params: {
companyId: string
userId: string
supplierInvoiceId: string
direction?: string
supplierInvoiceIdOverride?: string | null
invoiceId?: string | null
balanceAccount?: string
targetAccount?: string
periodStart?: string
periodEnd?: string
},
): Promise<string> {
const id = randomUUID()
await getPool().query(
`INSERT INTO public.accrual_schedules
(id, user_id, company_id, direction, supplier_invoice_id, invoice_id,
balance_account, target_account, total_amount,
period_start, period_end, months)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, 12000, $9, $10, 12)`,
[
id,
params.userId,
params.companyId,
params.direction ?? 'expense',
params.supplierInvoiceIdOverride === undefined
? params.supplierInvoiceId
: params.supplierInvoiceIdOverride,
params.invoiceId ?? null,
params.balanceAccount ?? '1730',
params.targetAccount ?? '6310',
params.periodStart ?? '2026-01-01',
params.periodEnd ?? '2026-12-31',
],
)
return id
}
async function insertCustomerInvoice(companyId: string, userId: string): Promise<string> {
const customerId = randomUUID()
await getPool().query(
`INSERT INTO public.customers (id, user_id, company_id, name, customer_type)
VALUES ($1, $2, $3, 'Kund AB', 'swedish_business')`,
[customerId, userId, companyId],
)
const id = randomUUID()
await getPool().query(
`INSERT INTO public.invoices
(id, user_id, company_id, customer_id, invoice_number, invoice_date, due_date,
currency, subtotal, vat_amount, total, vat_treatment, vat_rate, status,
paid_amount, remaining_amount)
VALUES ($1, $2, $3, $4, $5, '2026-01-15', '2026-02-14', 'SEK',
12000, 3000, 15000, 'standard_25', 25, 'sent', 0, 15000)`,
[id, userId, companyId, customerId, `F-${id.slice(0, 8)}`],
)
return id
}
async function insertInstallment(params: {
companyId: string
userId: string
scheduleId: string
periodMonth?: string
status?: string
journalEntryId?: string | null
}): Promise<string> {
const id = randomUUID()
await getPool().query(
`INSERT INTO public.accrual_schedule_installments
(id, user_id, company_id, schedule_id, period_month, amount, status, journal_entry_id)
VALUES ($1, $2, $3, $4, $5, 1000, $6, $7)`,
[
id,
params.userId,
params.companyId,
params.scheduleId,
params.periodMonth ?? '2026-01-01',
params.status ?? 'pending',
params.journalEntryId ?? null,
],
)
return id
}
async function seedScheduleContext() {
const { userId, companyId, fiscalPeriodId } = await seedCompany()
const supplierId = await insertSupplier(companyId, userId)
const supplierInvoiceId = await insertSupplierInvoice(companyId, userId, supplierId)
return { userId, companyId, fiscalPeriodId, supplierId, supplierInvoiceId }
}
describe('accrual_schedules constraints', () => {
it('rejects a schedule without any source invoice', async () => {
const ctx = await seedScheduleContext()
await expect(
insertSchedule({ ...ctx, supplierInvoiceIdOverride: null }),
).rejects.toThrow(/one_source|direction_matches_source/i)
})
it('rejects a direction that does not match the source side', async () => {
const ctx = await seedScheduleContext()
// Accounts are valid for the 'revenue' direction so the only violated
// constraint is direction_matches_source (supplier invoice → expense).
await expect(
insertSchedule({
...ctx,
direction: 'revenue',
balanceAccount: '2970',
targetAccount: '3001',
}),
).rejects.toThrow(/direction_matches_source/i)
})
it('rejects period_end before period_start', async () => {
const ctx = await seedScheduleContext()
await expect(
insertSchedule({ ...ctx, periodStart: '2026-06-01', periodEnd: '2026-01-31' }),
).rejects.toThrow(/period_valid/i)
})
it('rejects a non-17xx balance account on an expense schedule', async () => {
const ctx = await seedScheduleContext()
await expect(
insertSchedule({ ...ctx, balanceAccount: '2970' }),
).rejects.toThrow(/balance_account_range/i)
await expect(
insertSchedule({ ...ctx, balanceAccount: '5010' }),
).rejects.toThrow(/balance_account_range/i)
})
it('rejects a non-29xx balance account on a revenue schedule', async () => {
const ctx = await seedScheduleContext()
const invoiceId = await insertCustomerInvoice(ctx.companyId, ctx.userId)
await expect(
insertSchedule({
...ctx,
direction: 'revenue',
supplierInvoiceIdOverride: null,
invoiceId,
balanceAccount: '1730',
targetAccount: '3001',
}),
).rejects.toThrow(/balance_account_range/i)
// The mirrored valid combination passes.
await expect(
insertSchedule({
...ctx,
direction: 'revenue',
supplierInvoiceIdOverride: null,
invoiceId,
balanceAccount: '2970',
targetAccount: '3001',
}),
).resolves.toBeDefined()
})
it('rejects an implausible BAS target account', async () => {
const ctx = await seedScheduleContext()
await expect(
insertSchedule({ ...ctx, targetAccount: '9999' }),
).rejects.toThrow(/target_account_range/i)
await expect(
insertSchedule({ ...ctx, targetAccount: '631' }),
).rejects.toThrow(/target_account_range/i)
})
})
describe('accrual_schedule_installments constraints', () => {
it('rejects a period_month that is not the first day of a month', async () => {
const ctx = await seedScheduleContext()
const scheduleId = await insertSchedule(ctx)
await expect(
insertInstallment({ ...ctx, scheduleId, periodMonth: '2026-02-15' }),
).rejects.toThrow(/month_normalized/i)
})
it('rejects two installments for the same schedule and month', async () => {
const ctx = await seedScheduleContext()
const scheduleId = await insertSchedule(ctx)
await insertInstallment({ ...ctx, scheduleId, periodMonth: '2026-03-01' })
await expect(
insertInstallment({ ...ctx, scheduleId, periodMonth: '2026-03-01' }),
).rejects.toThrow(/duplicate|unique/i)
})
it('rejects status=posted without a journal entry link', async () => {
const ctx = await seedScheduleContext()
const scheduleId = await insertSchedule(ctx)
await expect(
insertInstallment({ ...ctx, scheduleId, status: 'posted', journalEntryId: null }),
).rejects.toThrow(/posted_consistent/i)
})
})
describe('posted installment immutability + verifikat protection', () => {
it('freezes amount and period_month once a journal entry is linked', async () => {
const ctx = await seedScheduleContext()
const scheduleId = await insertSchedule(ctx)
const entryId = await insertDraftJournalEntry(ctx)
const installmentId = await insertInstallment({
...ctx,
scheduleId,
status: 'posted',
journalEntryId: entryId,
})
await expect(
getPool().query(
`UPDATE public.accrual_schedule_installments SET amount = 999 WHERE id = $1`,
[installmentId],
),
).rejects.toThrow(/posted accrual installment/i)
// Non-financial fields stay editable (cron error bookkeeping).
await expect(
getPool().query(
`UPDATE public.accrual_schedule_installments SET last_error = 'x' WHERE id = $1`,
[installmentId],
),
).resolves.toBeDefined()
})
it('blocks deleting a journal entry referenced by an installment', async () => {
const ctx = await seedScheduleContext()
const scheduleId = await insertSchedule(ctx)
const entryId = await insertDraftJournalEntry(ctx)
await insertInstallment({
...ctx,
scheduleId,
status: 'posted',
journalEntryId: entryId,
})
// The engine-level delete guard fires before the FK RESTRICT can: either
// layer blocking the delete satisfies the verifikat-protection invariant.
await expect(
getPool().query(`DELETE FROM public.journal_entries WHERE id = $1`, [entryId]),
).rejects.toThrow(/foreign key|violates|cannot delete journal entries/i)
})
})
describe('accrual RLS', () => {
it('isolates schedules and installments by company', async () => {
const ctx = await seedScheduleContext()
const scheduleId = await insertSchedule(ctx)
await insertInstallment({ ...ctx, scheduleId })
const stranger = await insertAuthUser()
const ownerSchedules = await withUserContext(ctx.userId, (client) =>
client.query(`SELECT id FROM public.accrual_schedules WHERE id = $1`, [scheduleId]),
)
expect(ownerSchedules.rows).toHaveLength(1)
const strangerSchedules = await withUserContext(stranger, (client) =>
client.query(`SELECT id FROM public.accrual_schedules WHERE id = $1`, [scheduleId]),
)
expect(strangerSchedules.rows).toHaveLength(0)
const strangerInstallments = await withUserContext(stranger, (client) =>
client.query(
`SELECT id FROM public.accrual_schedule_installments WHERE schedule_id = $1`,
[scheduleId],
),
)
expect(strangerInstallments.rows).toHaveLength(0)
})
it('lets owners delete only unposted rows', async () => {
const ctx = await seedScheduleContext()
const scheduleId = await insertSchedule(ctx)
const entryId = await insertDraftJournalEntry(ctx)
const postedId = await insertInstallment({
...ctx,
scheduleId,
periodMonth: '2026-01-01',
status: 'posted',
journalEntryId: entryId,
})
const pendingId = await insertInstallment({
...ctx,
scheduleId,
periodMonth: '2026-02-01',
})
await withUserContext(ctx.userId, async (client) => {
const posted = await client.query(
`DELETE FROM public.accrual_schedule_installments WHERE id = $1`,
[postedId],
)
expect(posted.rowCount).toBe(0)
const schedule = await client.query(
`DELETE FROM public.accrual_schedules WHERE id = $1`,
[scheduleId],
)
expect(schedule.rowCount).toBe(0)
const pending = await client.query(
`DELETE FROM public.accrual_schedule_installments WHERE id = $1`,
[pendingId],
)
expect(pending.rowCount).toBe(1)
})
})
})
describe('invoice item accrual columns', () => {
it('rejects a period start without an end and non-17xx balance accounts', async () => {
const ctx = await seedScheduleContext()
const insertItem = (columns: string, values: string) =>
getPool().query(
`INSERT INTO public.supplier_invoice_items
(supplier_invoice_id, description, line_total, account_number, ${columns})
VALUES ($1, 'Försäkring', 12000, '6310', ${values})`,
[ctx.supplierInvoiceId],
)
await expect(
insertItem('accrual_period_start', `'2026-01-01'`),
).rejects.toThrow(/accrual_atomic/i)
await expect(
insertItem(
'accrual_period_start, accrual_period_end, accrual_balance_account',
`'2026-01-01', '2026-12-31', '5010'`,
),
).rejects.toThrow(/account_range/i)
await expect(
insertItem(
'accrual_period_start, accrual_period_end, accrual_balance_account',
`'2026-01-01', '2026-12-31', '1730'`,
),
).resolves.toBeDefined()
})
})
+95
View File
@@ -0,0 +1,95 @@
import { describe, expect, it } from 'vitest'
import { seedCompany } from '@/tests/pg/fixtures'
import { withUserContext } from '@/tests/pg/setup'
describe('agent_atom_registry.pg: seed + RLS', () => {
it('seed migration populated active atoms with non-null bodies and no swarm-* ids', async () => {
const { userId } = await seedCompany()
const rows = await withUserContext(userId, async (client) => {
const res = await client.query<{ id: string; body: string | null; mcp_exposed: boolean }>(
`SELECT id, body, mcp_exposed FROM public.agent_atom_registry WHERE is_active`,
)
return res.rows
})
// The generated seed migration (…_seed_agent_atom_bodies.sql) runs during replay.
expect(rows.length).toBeGreaterThan(0)
// Every active atom has a real body inlined: the production read path depends
// on this (no disk fallback in prod).
for (const r of rows) {
expect(r.body, `atom ${r.id} body should be non-empty`).toBeTruthy()
expect(r.mcp_exposed).toBe(true)
}
// swarm-* audit skills must never become atoms; a curated horizontal must be present.
expect(rows.some((r) => r.id.includes('swarm'))).toBe(false)
expect(rows.some((r) => r.id === 'horizontal/swedish-vat')).toBe(true)
})
it('seeds reference children whose parent_atom_id points at a real top-level skill', async () => {
const { userId } = await seedCompany()
const { children, orphans, vatRef } = await withUserContext(userId, async (client) => {
const childRes = await client.query<{ n: number }>(
`SELECT count(*)::int AS n FROM public.agent_atom_registry WHERE parent_atom_id IS NOT NULL`,
)
// FK already guarantees this, but assert there are no dangling links anyway.
const orphanRes = await client.query<{ n: number }>(
`SELECT count(*)::int AS n
FROM public.agent_atom_registry c
WHERE c.parent_atom_id IS NOT NULL
AND NOT EXISTS (
SELECT 1 FROM public.agent_atom_registry p WHERE p.id = c.parent_atom_id
)`,
)
const vatRefRes = await client.query<{ id: string; body: string | null; parent_atom_id: string }>(
`SELECT id, body, parent_atom_id FROM public.agent_atom_registry
WHERE id = 'horizontal/swedish-vat/vat-compliance-reference'`,
)
return { children: childRes.rows[0]!.n, orphans: orphanRes.rows[0]!.n, vatRef: vatRefRes.rows[0] }
})
expect(children).toBeGreaterThan(0)
expect(orphans).toBe(0)
expect(vatRef?.parent_atom_id).toBe('horizontal/swedish-vat')
expect(vatRef?.body).toBeTruthy()
})
it('catalog filter (parent_atom_id IS NULL) hides references but the parent footer exposes them', async () => {
const { userId } = await seedCompany()
const { listed, vatBody } = await withUserContext(userId, async (client) => {
// The query every catalog uses: top-level skills only.
const listedRes = await client.query<{ id: string }>(
`SELECT id FROM public.agent_atom_registry
WHERE is_active AND parent_atom_id IS NULL`,
)
const vatRes = await client.query<{ body: string }>(
`SELECT body FROM public.agent_atom_registry WHERE id = 'horizontal/swedish-vat'`,
)
return { listed: listedRes.rows.map((r) => r.id), vatBody: vatRes.rows[0]?.body ?? '' }
})
// No reference id (three-segment, "<tier>/<slug>/<ref>") survives the filter.
expect(listed.some((id) => id.split('/').length === 3)).toBe(false)
expect(listed).toContain('horizontal/swedish-vat')
// …yet the loadable id is reachable from the parent body once loaded.
expect(vatBody).toContain('gnubok_load_skill("horizontal/swedish-vat/vat-compliance-reference")')
})
it('authenticated users can read the catalog but not write it', async () => {
const { userId } = await seedCompany()
await withUserContext(userId, async (client) => {
const sel = await client.query<{ n: number }>(
`SELECT count(*)::int AS n FROM public.agent_atom_registry`,
)
expect(sel.rows[0]!.n).toBeGreaterThan(0)
// No INSERT policy for authenticated: the catalog ships via service-role
// migrations only.
await expect(
client.query(
`INSERT INTO public.agent_atom_registry (id, tier, title, description, body_path)
VALUES ('horizontal/hacker', 'horizontal', 'x', 'x', 'x')`,
),
).rejects.toThrow()
})
})
})
@@ -0,0 +1,128 @@
import { describe, expect, it } from 'vitest'
import type { PoolClient } from 'pg'
import { getClient, getPool } from './setup'
import { insertAuthUser } from './fixtures'
/**
* Caller guard on check_and_increment_agent_quota (migration 20260726090000).
*
* The function is SECURITY DEFINER in `public`, so PostgREST exposes it to any
* authenticated user, and p_user_id is a plain argument. Without a guard, one
* user could spend another user's minute/day budget and lock them out of every
* agent endpoint. This test pins the guard against a real Postgres, because a
* mocked Supabase client cannot see a PL/pgSQL condition at all.
*
* Locks in:
* - An authenticated caller may spend their OWN quota.
* - An authenticated caller spending someone else's quota raises 42501 and
* leaves the victim's counters untouched.
* - A service-role/superuser connection (auth.uid() IS NULL) may still pass
* an explicit user id: cron, tests and backend jobs rely on that.
*/
async function asRole<T>(
role: 'authenticated' | 'anon',
userId: string | null,
fn: (client: PoolClient) => Promise<T>,
): Promise<T> {
const client = await getClient()
try {
await client.query('BEGIN')
await client.query(`SELECT set_config('request.jwt.claims', $1, true)`, [
JSON.stringify(userId ? { sub: userId, role } : { role }),
])
await client.query(`SELECT set_config('request.jwt.claim.sub', $1, true)`, [userId ?? ''])
await client.query(`SELECT set_config('request.jwt.claim.role', $1, true)`, [role])
await client.query(`SET LOCAL ROLE ${role}`)
const result = await fn(client)
await client.query('COMMIT')
return result
} catch (error) {
await client.query('ROLLBACK').catch(() => {})
throw error
} finally {
client.release()
}
}
function asAuthenticatedUser<T>(
userId: string,
fn: (client: PoolClient) => Promise<T>,
): Promise<T> {
return asRole('authenticated', userId, fn)
}
async function counterFor(userId: string): Promise<number> {
const res = await getPool().query<{ count: number }>(
`SELECT COALESCE(SUM(count), 0)::int AS count
FROM public.agent_rate_counters
WHERE user_id = $1`,
[userId],
)
return res.rows[0]?.count ?? 0
}
describe('check_and_increment_agent_quota caller guard.pg', () => {
it('lets an authenticated user spend their own quota', async () => {
const userId = await insertAuthUser()
const result = await asAuthenticatedUser(userId, async (client) => {
const res = await client.query<{ result: { ok: boolean } }>(
`SELECT public.check_and_increment_agent_quota($1::uuid, 30, 1000) AS result`,
[userId],
)
return res.rows[0]!.result
})
expect(result.ok).toBe(true)
expect(await counterFor(userId)).toBeGreaterThan(0)
})
it('refuses to spend another user quota and leaves their counters untouched', async () => {
const attacker = await insertAuthUser()
const victim = await insertAuthUser()
await expect(
asAuthenticatedUser(attacker, async (client) => {
await client.query(
`SELECT public.check_and_increment_agent_quota($1::uuid, 30, 1000) AS result`,
[victim],
)
}),
).rejects.toMatchObject({ code: '42501' })
expect(await counterFor(victim)).toBe(0)
})
it('refuses an unauthenticated anon caller entirely', async () => {
// The anon key ships in the browser bundle, so this RPC is reachable
// without a session. auth.uid() is NULL for anon exactly as it is for
// backend roles, so a uid-only guard would have let this through.
const victim = await insertAuthUser()
await expect(
asRole('anon', null, async (client) => {
await client.query(
`SELECT public.check_and_increment_agent_quota($1::uuid, 30, 1000) AS result`,
[victim],
)
}),
).rejects.toMatchObject({ code: expect.stringMatching(/^42501$/) })
expect(await counterFor(victim)).toBe(0)
})
it('still allows a service-role connection to pass an explicit user id', async () => {
const userId = await insertAuthUser()
// The shared pool connects as the migration/superuser role, so auth.uid()
// is NULL here: the same shape cron jobs and backend scripts run under.
const res = await getPool().query<{ result: { ok: boolean } }>(
`SELECT public.check_and_increment_agent_quota($1::uuid, 30, 1000) AS result`,
[userId],
)
expect(res.rows[0]!.result.ok).toBe(true)
expect(await counterFor(userId)).toBeGreaterThan(0)
})
})
File diff suppressed because it is too large Load Diff
+72
View File
@@ -0,0 +1,72 @@
import { randomUUID } from 'node:crypto'
import { describe, expect, it } from 'vitest'
import { insertAuthUser, insertCompany } from './fixtures'
import { getPool } from './setup'
describe('API-key audit history', () => {
it('skips request telemetry while retaining security and configuration changes', async () => {
const userId = await insertAuthUser()
const companyId = await insertCompany({ createdBy: userId })
const apiKeyId = randomUUID()
const keyHash = randomUUID().replaceAll('-', '')
await getPool().query(
`INSERT INTO public.api_keys
(id, user_id, company_id, key_hash, key_prefix, name, scopes)
VALUES ($1, $2, $3, $4, 'gnubok_sk_test', 'Audit test key', $5)`,
[apiKeyId, userId, companyId, keyHash, ['reports:read']],
)
await getPool().query(
`SELECT * FROM public.validate_and_increment_api_key($1)`,
[keyHash],
)
await getPool().query(
`SELECT * FROM public.validate_and_increment_api_key($1)`,
[keyHash],
)
const afterTelemetry = await getPool().query<{ action: string }>(
`SELECT action
FROM public.audit_log
WHERE table_name = 'api_keys'
AND record_id = $1
ORDER BY created_at, id`,
[apiKeyId],
)
expect(afterTelemetry.rows.map((row) => row.action)).toEqual(['INSERT'])
await getPool().query(
`UPDATE public.api_keys
SET name = 'Renamed audit test key',
scopes = ARRAY['reports:read', 'customers:read']::text[]
WHERE id = $1`,
[apiKeyId],
)
const afterConfigurationChange = await getPool().query<{
action: string
old_name: string | null
new_name: string | null
}>(
`SELECT
action,
old_state ->> 'name' AS old_name,
new_state ->> 'name' AS new_name
FROM public.audit_log
WHERE table_name = 'api_keys'
AND record_id = $1
ORDER BY created_at, id`,
[apiKeyId],
)
expect(afterConfigurationChange.rows).toEqual([
{ action: 'INSERT', old_name: null, new_name: 'Audit test key' },
{
action: 'UPDATE',
old_name: 'Audit test key',
new_name: 'Renamed audit test key',
},
])
})
})
@@ -0,0 +1,138 @@
import { randomUUID } from 'node:crypto'
import { describe, expect, it } from 'vitest'
import { insertAuthUser, insertCompany, insertCompanyMember } from './fixtures'
import { getPool } from './setup'
/**
* api_keys.unattended_commit_limit (migration 20260831111519).
*
* The column is the storage half of the approval-authority envelope; the
* enforcement half is TypeScript (lib/pending-operations/unattended-limit.ts),
* deliberately, because a RAISE inside commit_journal_entry is swallowed into
* a retryable 500 and burns the staged operation.
*
* What must hold in the database, and is what these tests pin:
* 1. the column exists, is nullable, and defaults to NULL (unlimited), so
* every key that existed before this migration keeps its behaviour;
* 2. the CHECK rejects 0 and negatives, so "limit = 0" can never be stored
* and silently read back as falsy-therefore-unlimited;
* 3. validate_and_increment_api_key returns it, with exactly ONE signature
* (adding a parameter or return column to a Postgres function creates an
* overload rather than replacing it, and PostgREST then 300s on the
* ambiguity: see migration 20260421140000);
* 4. writing it produces an audit_log row, since changing how much an agent
* may post without a human is a change to who approves the company's
* bookkeeping (BFL 5 kap. 11 paragraf).
*/
describe('api_keys.unattended_commit_limit (pg)', () => {
async function seedKey(limit: number | null = null) {
const userId = await insertAuthUser()
const companyId = await insertCompany({ createdBy: userId })
await insertCompanyMember({ companyId, userId, role: 'owner' })
const apiKeyId = randomUUID()
const keyHash = randomUUID().replaceAll('-', '')
await getPool().query(
`INSERT INTO public.api_keys
(id, user_id, company_id, key_hash, key_prefix, name, scopes, unattended_commit_limit)
VALUES ($1, $2, $3, $4, 'gnubok_sk_test', 'Envelope test key', $5, $6)`,
[apiKeyId, userId, companyId, keyHash, ['reports:read'], limit],
)
return { userId, companyId, apiKeyId, keyHash }
}
it('defaults to NULL so pre-existing keys stay unlimited', async () => {
const userId = await insertAuthUser()
const companyId = await insertCompany({ createdBy: userId })
await insertCompanyMember({ companyId, userId, role: 'owner' })
// Deliberately omits the column instead of storing an explicit NULL: this
// test exists to pin the DATABASE DEFAULT, and passing NULL in would keep
// it green even if the default changed to a positive ceiling, which is the
// one change that would silently start blocking every existing key.
const { rows } = await getPool().query<{ unattended_commit_limit: string | null }>(
`INSERT INTO public.api_keys
(user_id, company_id, key_hash, key_prefix, name, scopes)
VALUES ($1, $2, $3, 'gnubok_sk_test', 'Default test key', $4)
RETURNING unattended_commit_limit`,
[userId, companyId, randomUUID().replaceAll('-', ''), ['reports:read']],
)
expect(rows[0]!.unattended_commit_limit).toBeNull()
})
it('rejects a zero or negative ceiling with the CHECK constraint', async () => {
const userId = await insertAuthUser()
const companyId = await insertCompany({ createdBy: userId })
await insertCompanyMember({ companyId, userId, role: 'owner' })
for (const bad of [0, -1]) {
await expect(
getPool().query(
`INSERT INTO public.api_keys
(user_id, company_id, key_hash, key_prefix, name, scopes, unattended_commit_limit)
VALUES ($1, $2, $3, 'gnubok_sk_test', 'Bad ceiling', $4, $5)`,
[userId, companyId, randomUUID().replaceAll('-', ''), ['reports:read'], bad],
),
).rejects.toMatchObject({
code: '23514',
constraint: 'api_keys_unattended_commit_limit_positive',
})
}
})
it('validate_and_increment_api_key returns the ceiling, and has exactly one signature', async () => {
const { keyHash } = await seedKey(2500)
const overloads = await getPool().query<{ n: number }>(
`SELECT count(*)::int AS n
FROM pg_proc p
JOIN pg_namespace n ON n.oid = p.pronamespace
WHERE n.nspname = 'public' AND p.proname = 'validate_and_increment_api_key'`,
)
expect(overloads.rows[0]!.n).toBe(1)
const { rows } = await getPool().query<{
unattended_commit_limit: string | null
rate_limited: boolean
}>(`SELECT * FROM public.validate_and_increment_api_key($1)`, [keyHash])
expect(rows).toHaveLength(1)
expect(rows[0]!.rate_limited).toBe(false)
// numeric comes back as a string from node-postgres; compare numerically.
expect(Number(rows[0]!.unattended_commit_limit)).toBe(2500)
})
it('returns NULL for a key with no ceiling, not 0', async () => {
const { keyHash } = await seedKey(null)
const { rows } = await getPool().query<{ unattended_commit_limit: string | null }>(
`SELECT * FROM public.validate_and_increment_api_key($1)`,
[keyHash],
)
// The whole guard is written NULL-first. A 0 here would read as a real
// ceiling on the way in and block every commit the key attempts.
expect(rows[0]!.unattended_commit_limit).toBeNull()
})
it('records a ceiling change in audit_log', async () => {
const { apiKeyId } = await seedKey(null)
await getPool().query(
`UPDATE public.api_keys SET unattended_commit_limit = 10000 WHERE id = $1`,
[apiKeyId],
)
const { rows } = await getPool().query<{
action: string
old_limit: string | null
new_limit: string | null
}>(
`SELECT action,
old_state ->> 'unattended_commit_limit' AS old_limit,
new_state ->> 'unattended_commit_limit' AS new_limit
FROM public.audit_log
WHERE table_name = 'api_keys' AND record_id = $1 AND action = 'UPDATE'
ORDER BY created_at, id`,
[apiKeyId],
)
expect(rows).toHaveLength(1)
expect(rows[0]!.old_limit).toBeNull()
expect(Number(rows[0]!.new_limit)).toBe(10000)
})
})
@@ -0,0 +1,193 @@
import { randomUUID } from 'crypto'
import { describe, expect, it } from 'vitest'
import { seedCompany } from '@/tests/pg/fixtures'
import { getPool } from '@/tests/pg/setup'
/**
* pg-real coverage for migration 20260619140000_api_keys_sod_ack_and_agent_write.
*
* Locks in:
* - The two SoD-acknowledgement columns exist with the expected types and
* the sod_acknowledged_by FK targets auth.users(id).
* - The grandfather UPDATE shipped agent:write onto every non-revoked key
* that already carried an explicit scope list (idempotent: running it
* again adds no duplicate).
* - NULL-scopes (legacy full/default access) and revoked keys were left
* untouched.
*
* Inserts go through the pool (superuser, RLS-bypassing): this is a schema /
* data-migration smoke, not an RLS test.
*/
async function insertApiKey(params: {
userId: string
companyId: string
scopes: string[] | null
revoked?: boolean
}): Promise<string> {
const id = randomUUID()
const hash = randomUUID().replace(/-/g, '').padEnd(64, '0')
await getPool().query(
`INSERT INTO public.api_keys
(id, user_id, company_id, key_hash, key_prefix, name, scopes, revoked_at)
VALUES ($1, $2, $3, $4, 'gnubok_sk_test', 'pg-real key', $5, $6)`,
[
id,
params.userId,
params.companyId,
hash,
params.scopes,
params.revoked ? new Date() : null,
],
)
return id
}
async function scopesOf(id: string): Promise<string[] | null> {
const { rows } = await getPool().query<{ scopes: string[] | null }>(
`SELECT scopes FROM public.api_keys WHERE id = $1`,
[id],
)
return rows[0]?.scopes ?? null
}
describe('api_keys SoD-ack columns + agent:write grandfathering', () => {
it('exposes sod_acknowledged_at / sod_acknowledged_by with the expected shape', async () => {
const { rows } = await getPool().query<{
column_name: string
data_type: string
}>(
`SELECT column_name, data_type
FROM information_schema.columns
WHERE table_schema = 'public'
AND table_name = 'api_keys'
AND column_name IN ('sod_acknowledged_at', 'sod_acknowledged_by')
ORDER BY column_name`,
)
const byName = Object.fromEntries(rows.map((r) => [r.column_name, r.data_type]))
expect(byName['sod_acknowledged_at']).toBe('timestamp with time zone')
expect(byName['sod_acknowledged_by']).toBe('uuid')
})
it('sod_acknowledged_by references auth.users(id)', async () => {
// pg_constraint, not information_schema: the constraint crosses schemas
// (public → auth) and information_schema's constraint_column_usage hides
// referenced tables outside the constrained table's schema.
const { rows } = await getPool().query<{ foreign_table: string }>(
`SELECT c.confrelid::regclass::text AS foreign_table
FROM pg_constraint c
JOIN pg_attribute a
ON a.attrelid = c.conrelid
AND a.attnum = ANY (c.conkey)
WHERE c.conrelid = 'public.api_keys'::regclass
AND c.contype = 'f'
AND a.attname = 'sod_acknowledged_by'`,
)
expect(rows[0]?.foreign_table).toBe('auth.users')
})
it('accepts a write that records the SoD acknowledgement', async () => {
const { userId, companyId } = await seedCompany()
const keyId = await insertApiKey({
userId,
companyId,
scopes: ['invoices:write', 'pending_operations:approve'],
})
await getPool().query(
`UPDATE public.api_keys
SET sod_acknowledged_at = now(), sod_acknowledged_by = $2
WHERE id = $1`,
[keyId, userId],
)
const { rows } = await getPool().query<{
sod_acknowledged_at: string | null
sod_acknowledged_by: string | null
}>(
`SELECT sod_acknowledged_at, sod_acknowledged_by
FROM public.api_keys WHERE id = $1`,
[keyId],
)
expect(rows[0]?.sod_acknowledged_at).not.toBeNull()
expect(rows[0]?.sod_acknowledged_by).toBe(userId)
})
it('rejects a partial SoD acknowledgement (paired-NULL CHECK)', async () => {
const { userId, companyId } = await seedCompany()
const keyId = await insertApiKey({
userId,
companyId,
scopes: ['invoices:write', 'pending_operations:approve'],
})
// Timestamp without acknowledger: the audit pair must be both-or-neither.
await expect(
getPool().query(
`UPDATE public.api_keys SET sod_acknowledged_at = now() WHERE id = $1`,
[keyId],
),
).rejects.toMatchObject({ code: '23514' }) // check_violation
// Acknowledger without timestamp: equally rejected.
await expect(
getPool().query(
`UPDATE public.api_keys SET sod_acknowledged_by = $2 WHERE id = $1`,
[keyId, userId],
),
).rejects.toMatchObject({ code: '23514' })
})
it('grandfather UPDATE adds agent:write to scoped, non-revoked keys (idempotent)', async () => {
const { userId, companyId } = await seedCompany()
// Mimic a pre-migration key created with an explicit scope list but WITHOUT
// agent:write (the column existed before this migration).
const keyId = await insertApiKey({
userId,
companyId,
scopes: ['transactions:read', 'reports:read'],
})
// Re-run the migration's grandfather statement; it must be idempotent.
const run = () =>
getPool().query(
`UPDATE public.api_keys
SET scopes = array_append(scopes, 'agent:write')
WHERE id = $1
AND revoked_at IS NULL
AND scopes IS NOT NULL
AND NOT ('agent:write' = ANY(scopes))`,
[keyId],
)
await run()
await run()
const scopes = await scopesOf(keyId)
expect(scopes).toContain('agent:write')
expect(scopes?.filter((s) => s === 'agent:write')).toHaveLength(1)
})
it('leaves NULL-scopes and revoked keys untouched', async () => {
const { userId, companyId } = await seedCompany()
const nullKey = await insertApiKey({ userId, companyId, scopes: null })
const revokedKey = await insertApiKey({
userId,
companyId,
scopes: ['transactions:read'],
revoked: true,
})
await getPool().query(
`UPDATE public.api_keys
SET scopes = array_append(scopes, 'agent:write')
WHERE id = ANY($1::uuid[])
AND revoked_at IS NULL
AND scopes IS NOT NULL
AND NOT ('agent:write' = ANY(scopes))`,
[[nullKey, revokedKey]],
)
expect(await scopesOf(nullKey)).toBeNull()
expect(await scopesOf(revokedKey)).toEqual(['transactions:read'])
})
})
+41
View File
@@ -0,0 +1,41 @@
import { describe, expect, it } from 'vitest'
import { randomUUID, createHash } from 'node:crypto'
import { getPool } from './setup'
import { insertAuthUser } from './fixtures'
/**
* Unbound API keys (migration 20260826090000): a key minted from the OAuth
* popup before the user's first company exists carries company_id NULL.
* The NOT NULL from 20260330130000's dynamic loop made the token endpoint's
* insert fail with a plain 500 on every fresh Claude.ai authorization; a
* mocked client cannot see a column constraint, so this pins it on real
* Postgres.
*/
describe('api_keys unbound insert.pg', () => {
it('accepts a key with no company binding', async () => {
const userId = await insertAuthUser()
const keyHash = createHash('sha256').update(randomUUID()).digest('hex')
const inserted = await getPool().query<{ id: string; company_id: string | null }>(
`INSERT INTO public.api_keys (user_id, company_id, key_hash, key_prefix, name, scopes)
VALUES ($1, NULL, $2, 'gnubok_sk_test', 'MCP-klient (OAuth)', ARRAY['companies:read'])
RETURNING id, company_id`,
[userId, keyHash],
)
expect(inserted.rows[0]!.company_id).toBeNull()
// The lazy bind heals exactly the unbound row.
const companyRes = await getPool().query<{ id: string }>(
`SELECT public.create_company_for_user($1::uuid, 'Bind AB', 'aktiebolag', NULL) AS id`,
[userId],
)
await getPool().query(
`UPDATE public.api_keys SET company_id = $1 WHERE id = $2 AND company_id IS NULL`,
[companyRes.rows[0]!.id, inserted.rows[0]!.id],
)
const healed = await getPool().query<{ company_id: string | null }>(
`SELECT company_id FROM public.api_keys WHERE id = $1`,
[inserted.rows[0]!.id],
)
expect(healed.rows[0]!.company_id).toBe(companyRes.rows[0]!.id)
})
})
@@ -0,0 +1,326 @@
import { randomUUID } from 'node:crypto'
import { describe, it, expect } from 'vitest'
import { getPool, withUserContext } from './setup'
import { seedCompany, insertAuthUser } from './fixtures'
// pg-real coverage for 20260622120000_bolagsverket_arsredovisning_submissions:
// RLS isolation on all three tables, the post-upload immutability trigger, and
// the status-transition state machine (GUIDE §5.2.2).
async function insertSubmission(
companyId: string,
userId: string,
fiscalPeriodId: string,
overrides: { status?: string; uploadedAt?: string | null; idnummer?: string | null } = {},
): Promise<string> {
const id = randomUUID()
await getPool().query(
`INSERT INTO public.arsredovisning_submissions
(id, company_id, user_id, fiscal_period_id, taxonomy_version, entry_point, status, uploaded_at, idnummer)
VALUES ($1, $2, $3, $4, '2024-09-12', 'k2-ab-risbs-2024-09-12', $5, $6, $7)`,
[
id,
companyId,
userId,
fiscalPeriodId,
overrides.status ?? 'draft',
overrides.uploadedAt ?? null,
overrides.idnummer ?? null,
],
)
return id
}
describe('arsredovisning_submissions RLS', () => {
it('members see their company rows, outsiders see nothing', async () => {
const { userId, companyId, fiscalPeriodId } = await seedCompany()
const outsider = await insertAuthUser()
await insertSubmission(companyId, userId, fiscalPeriodId)
const ownRows = await withUserContext(userId, async (client) => {
const res = await client.query(
`SELECT id FROM public.arsredovisning_submissions WHERE company_id = $1`,
[companyId],
)
return res.rowCount
})
expect(ownRows).toBe(1)
const outsiderRows = await withUserContext(outsider, async (client) => {
const res = await client.query(
`SELECT id FROM public.arsredovisning_submissions WHERE company_id = $1`,
[companyId],
)
return res.rowCount
})
expect(outsiderRows).toBe(0)
})
it('users cannot DELETE submissions (no policy: audit trail)', async () => {
const { userId, companyId, fiscalPeriodId } = await seedCompany()
const id = await insertSubmission(companyId, userId, fiscalPeriodId)
const deleted = await withUserContext(userId, async (client) => {
const res = await client.query(
`DELETE FROM public.arsredovisning_submissions WHERE id = $1`,
[id],
)
return res.rowCount
})
expect(deleted).toBe(0)
})
})
describe('arsredovisning_submissions immutability after upload', () => {
it('freezes identity/fingerprint columns once uploaded_at is set', async () => {
const { userId, companyId, fiscalPeriodId } = await seedCompany()
const id = await insertSubmission(companyId, userId, fiscalPeriodId, {
status: 'uploaded',
uploadedAt: new Date().toISOString(),
idnummer: '49679',
})
await expect(
getPool().query(
`UPDATE public.arsredovisning_submissions SET idnummer = 'tampered' WHERE id = $1`,
[id],
),
).rejects.toThrow(/kan inte ändras/)
await expect(
getPool().query(
`UPDATE public.arsredovisning_submissions SET taxonomy_version = '2021-10-31' WHERE id = $1`,
[id],
),
).rejects.toThrow(/kan inte ändras/)
})
it('still allows status-tracking updates after upload', async () => {
const { userId, companyId, fiscalPeriodId } = await seedCompany()
const id = await insertSubmission(companyId, userId, fiscalPeriodId, {
status: 'uploaded',
uploadedAt: new Date().toISOString(),
})
const res = await getPool().query(
`UPDATE public.arsredovisning_submissions
SET status = 'inkommen', error_message = NULL
WHERE id = $1 RETURNING status`,
[id],
)
expect(res.rows[0].status).toBe('inkommen')
})
it('draft rows remain freely editable', async () => {
const { userId, companyId, fiscalPeriodId } = await seedCompany()
const id = await insertSubmission(companyId, userId, fiscalPeriodId)
const res = await getPool().query(
`UPDATE public.arsredovisning_submissions
SET entry_point = 'k2-ab-risbs-2024-09-12', kontrollera_utfall = '[]'::jsonb
WHERE id = $1 RETURNING entry_point`,
[id],
)
expect(res.rows[0].entry_point).toBe('k2-ab-risbs-2024-09-12')
})
})
describe('arsredovisning_submissions audit survival on user deletion', () => {
it('keeps the submission row with user_id NULL when the filing user is deleted', async () => {
const { companyId, fiscalPeriodId } = await seedCompany()
// A separate filer (not the company creator) so the company itself survives.
const filer = await insertAuthUser()
const id = await insertSubmission(companyId, filer, fiscalPeriodId, {
status: 'uploaded',
uploadedAt: new Date().toISOString(),
idnummer: '70001',
})
await getPool().query(`DELETE FROM auth.users WHERE id = $1`, [filer])
const res = await getPool().query(
`SELECT user_id, status, idnummer FROM public.arsredovisning_submissions WHERE id = $1`,
[id],
)
expect(res.rowCount).toBe(1)
expect(res.rows[0].user_id).toBeNull()
expect(res.rows[0].status).toBe('uploaded')
expect(res.rows[0].idnummer).toBe('70001')
})
it('keeps avtal acceptances with user_id NULL when the accepting user is deleted', async () => {
const { companyId } = await seedCompany()
const acceptor = await insertAuthUser()
const inserted = await getPool().query(
`INSERT INTO public.bolagsverket_avtal_acceptances (company_id, user_id, avtalstext_andrad)
VALUES ($1, $2, '2017-12-06') RETURNING id`,
[companyId, acceptor],
)
await getPool().query(`DELETE FROM auth.users WHERE id = $1`, [acceptor])
const res = await getPool().query(
`SELECT user_id FROM public.bolagsverket_avtal_acceptances WHERE id = $1`,
[inserted.rows[0].id],
)
expect(res.rowCount).toBe(1)
expect(res.rows[0].user_id).toBeNull()
})
})
describe('arsredovisning_submissions status machine', () => {
it('follows the documented flow inkommen → forelagd → komplettering → registrerad', async () => {
const { userId, companyId, fiscalPeriodId } = await seedCompany()
const id = await insertSubmission(companyId, userId, fiscalPeriodId, {
status: 'uploaded',
uploadedAt: new Date().toISOString(),
})
for (const next of ['inkommen', 'forelagd', 'komplettering', 'registrerad']) {
await getPool().query(
`UPDATE public.arsredovisning_submissions SET status = $2 WHERE id = $1`,
[id, next],
)
}
const final = await getPool().query(
`SELECT status, registered_at FROM public.arsredovisning_submissions WHERE id = $1`,
[id],
)
expect(final.rows[0].status).toBe('registrerad')
})
it('allows forward jumps between Bolagsverket-asserted statuses (missed webhooks)', async () => {
const { userId, companyId, fiscalPeriodId } = await seedCompany()
// uploaded → komplettering directly (skipping inkommen + forelagd).
const skipAhead = await insertSubmission(companyId, userId, fiscalPeriodId, {
status: 'uploaded',
uploadedAt: new Date().toISOString(),
})
const res1 = await getPool().query(
`UPDATE public.arsredovisning_submissions SET status = 'komplettering' WHERE id = $1 RETURNING status`,
[skipAhead],
)
expect(res1.rows[0].status).toBe('komplettering')
// inkommen → komplettering (skipping forelagd).
const inkommen = await insertSubmission(companyId, userId, fiscalPeriodId, {
status: 'uploaded',
uploadedAt: new Date().toISOString(),
})
await getPool().query(
`UPDATE public.arsredovisning_submissions SET status = 'inkommen' WHERE id = $1`,
[inkommen],
)
const res2 = await getPool().query(
`UPDATE public.arsredovisning_submissions SET status = 'komplettering' WHERE id = $1 RETURNING status`,
[inkommen],
)
expect(res2.rows[0].status).toBe('komplettering')
})
it('allows error capture and retry transitions (draft/kontrollerad → error → draft)', async () => {
const { userId, companyId, fiscalPeriodId } = await seedCompany()
const id = await insertSubmission(companyId, userId, fiscalPeriodId, { status: 'kontrollerad' })
const errored = await getPool().query(
`UPDATE public.arsredovisning_submissions
SET status = 'error', error_message = 'inlamning failed'
WHERE id = $1 RETURNING status, error_message`,
[id],
)
expect(errored.rows[0].status).toBe('error')
expect(errored.rows[0].error_message).toBe('inlamning failed')
const retried = await getPool().query(
`UPDATE public.arsredovisning_submissions SET status = 'draft' WHERE id = $1 RETURNING status`,
[id],
)
expect(retried.rows[0].status).toBe('draft')
})
it('rejects undocumented transitions (registrerad → draft, draft → inkommen)', async () => {
const { userId, companyId, fiscalPeriodId } = await seedCompany()
const id = await insertSubmission(companyId, userId, fiscalPeriodId, {
status: 'uploaded',
uploadedAt: new Date().toISOString(),
})
await getPool().query(
`UPDATE public.arsredovisning_submissions SET status = 'registrerad' WHERE id = $1`,
[id],
)
await expect(
getPool().query(
`UPDATE public.arsredovisning_submissions SET status = 'draft' WHERE id = $1`,
[id],
),
).rejects.toThrow(/Ogiltig statusövergång/)
const draftId = await insertSubmission(companyId, userId, fiscalPeriodId)
await expect(
getPool().query(
`UPDATE public.arsredovisning_submissions SET status = 'inkommen' WHERE id = $1`,
[draftId],
),
).rejects.toThrow(/Ogiltig statusövergång/)
})
})
describe('bolagsverket_avtal_acceptances', () => {
it('is insert-once per (company, user, avtalstext version) and RLS-scoped', async () => {
const { userId, companyId } = await seedCompany()
const outsider = await insertAuthUser()
await withUserContext(userId, async (client) => {
await client.query(
`INSERT INTO public.bolagsverket_avtal_acceptances (company_id, user_id, avtalstext_andrad)
VALUES ($1, $2, '2017-12-06')`,
[companyId, userId],
)
await expect(
client.query(
`INSERT INTO public.bolagsverket_avtal_acceptances (company_id, user_id, avtalstext_andrad)
VALUES ($1, $2, '2017-12-06')`,
[companyId, userId],
),
).rejects.toThrow(/duplicate key/)
})
// Outsider cannot accept on behalf of someone else's company.
await withUserContext(outsider, async (client) => {
await expect(
client.query(
`INSERT INTO public.bolagsverket_avtal_acceptances (company_id, user_id, avtalstext_andrad)
VALUES ($1, $2, '2017-12-06')`,
[companyId, outsider],
),
).rejects.toThrow(/row-level security/)
})
})
})
describe('bolagsverket_subscriptions', () => {
it('is unique per (company, orgnr, url, environment) and RLS-scoped', async () => {
const { userId, companyId } = await seedCompany()
const outsider = await insertAuthUser()
await getPool().query(
`INSERT INTO public.bolagsverket_subscriptions
(company_id, user_id, orgnr, url, auth_secret, environment, expires_at)
VALUES ($1, $2, '5560001111', 'https://example.test/hook', 's3cret', 'test', now() + interval '6 months')`,
[companyId, userId],
)
await expect(
getPool().query(
`INSERT INTO public.bolagsverket_subscriptions
(company_id, user_id, orgnr, url, auth_secret, environment, expires_at)
VALUES ($1, $2, '5560001111', 'https://example.test/hook', 'other', 'test', now() + interval '6 months')`,
[companyId, userId],
),
).rejects.toThrow(/duplicate key/)
const visible = await withUserContext(outsider, async (client) => {
const res = await client.query(
`SELECT id FROM public.bolagsverket_subscriptions WHERE company_id = $1`,
[companyId],
)
return res.rowCount
})
expect(visible).toBe(0)
})
})
+190
View File
@@ -0,0 +1,190 @@
import { randomUUID } from 'node:crypto'
import { describe, it, expect } from 'vitest'
import { getPool, withUserContext } from './setup'
import { seedCompany, insertAuthUser } from './fixtures'
// pg-real coverage for the artikelregister migration: the generate_article_number
// RPC (atomic + idempotent), the per-company unique article_number index, RLS
// isolation, and the updated_at + audit triggers.
async function seedSettings(companyId: string, userId: string): Promise<void> {
// seedCompany() inserts companies/members/period but not company_settings
// (the real flow creates it via create_company_with_owner). The RPC reads the
// per-company next_article_number counter, so seed a row (defaults to 1).
await getPool().query(
`INSERT INTO public.company_settings (user_id, company_id) VALUES ($1, $2)`,
[userId, companyId],
)
}
async function insertArticle(
companyId: string,
userId: string,
overrides: { name?: string; articleNumber?: string | null; revenueAccount?: string | null } = {},
): Promise<string> {
const id = randomUUID()
await getPool().query(
`INSERT INTO public.articles (id, company_id, user_id, name, article_number, revenue_account)
VALUES ($1, $2, $3, $4, $5, $6)`,
[
id,
companyId,
userId,
overrides.name ?? 'Konsulttimme',
overrides.articleNumber ?? null,
overrides.revenueAccount ?? null,
],
)
return id
}
describe('generate_article_number RPC', () => {
it('assigns sequential numbers, is idempotent, and advances the counter exactly once', async () => {
const { userId, companyId } = await seedCompany()
await seedSettings(companyId, userId)
const a1 = await insertArticle(companyId, userId, { name: 'A' })
const a2 = await insertArticle(companyId, userId, { name: 'B' })
const first = await getPool().query<{ n: string }>(
`SELECT public.generate_article_number($1, $2) AS n`,
[companyId, a1],
)
expect(first.rows[0].n).toBe('1')
// Idempotent: second call on the same article returns the same number and
// does NOT consume another sequence value.
const firstAgain = await getPool().query<{ n: string }>(
`SELECT public.generate_article_number($1, $2) AS n`,
[companyId, a1],
)
expect(firstAgain.rows[0].n).toBe('1')
const second = await getPool().query<{ n: string }>(
`SELECT public.generate_article_number($1, $2) AS n`,
[companyId, a2],
)
expect(second.rows[0].n).toBe('2')
const settings = await getPool().query<{ next_article_number: number }>(
`SELECT next_article_number FROM public.company_settings WHERE company_id = $1`,
[companyId],
)
// Started at 1, consumed by a1 and a2 → next free is 3.
expect(settings.rows[0].next_article_number).toBe(3)
})
it('raises when the article does not belong to the company', async () => {
const { userId, companyId } = await seedCompany()
await seedSettings(companyId, userId)
const other = await seedCompany()
const article = await insertArticle(companyId, userId)
await expect(
getPool().query(`SELECT public.generate_article_number($1, $2)`, [other.companyId, article]),
).rejects.toThrow()
})
})
describe('articles constraints + RLS', () => {
it('enforces a per-company unique article_number', async () => {
const { userId, companyId } = await seedCompany()
await insertArticle(companyId, userId, { name: 'A', articleNumber: '5' })
await expect(
insertArticle(companyId, userId, { name: 'B', articleNumber: '5' }),
).rejects.toThrow(/duplicate|unique/i)
})
it('isolates articles by company via RLS', async () => {
const { userId, companyId } = await seedCompany()
const articleId = await insertArticle(companyId, userId, { name: 'Secret' })
const stranger = await insertAuthUser()
const ownerView = await withUserContext(userId, (client) =>
client.query<{ id: string }>(`SELECT id FROM public.articles WHERE id = $1`, [articleId]),
)
expect(ownerView.rows).toHaveLength(1)
const strangerView = await withUserContext(stranger, (client) =>
client.query<{ id: string }>(`SELECT id FROM public.articles WHERE id = $1`, [articleId]),
)
expect(strangerView.rows).toHaveLength(0)
})
})
describe('articles.currency', () => {
it('defaults to SEK and accepts a code from the currencies table', async () => {
const { userId, companyId } = await seedCompany()
const articleId = await insertArticle(companyId, userId)
const def = await getPool().query<{ currency: string }>(
`SELECT currency FROM public.articles WHERE id = $1`,
[articleId],
)
expect(def.rows[0].currency).toBe('SEK')
// EUR is seeded in the currencies table, so the FK accepts it.
await expect(
getPool().query(`UPDATE public.articles SET currency = 'EUR' WHERE id = $1`, [articleId]),
).resolves.toBeDefined()
})
it('rejects a currency code missing from the currencies table (FK)', async () => {
const { userId, companyId } = await seedCompany()
const id = randomUUID()
await expect(
getPool().query(
`INSERT INTO public.articles (id, company_id, user_id, name, currency)
VALUES ($1, $2, $3, 'X', 'ZZZ')`,
[id, companyId, userId],
),
).rejects.toThrow(/foreign key|currencies/i)
})
})
describe('currencies reference table', () => {
it('is readable by any authenticated user via RLS', async () => {
const reader = await insertAuthUser()
const seen = await withUserContext(reader, (client) =>
client.query<{ code: string }>(`SELECT code FROM public.currencies WHERE code = 'SEK'`),
)
expect(seen.rows).toHaveLength(1)
})
})
describe('articles triggers', () => {
it('bumps updated_at on update', async () => {
const { userId, companyId } = await seedCompany()
const articleId = await insertArticle(companyId, userId)
const before = await getPool().query<{ updated_at: string }>(
`SELECT updated_at FROM public.articles WHERE id = $1`,
[articleId],
)
await getPool().query(
`UPDATE public.articles SET name = 'Renamed', updated_at = now() - interval '0 seconds' WHERE id = $1`,
[articleId],
)
const after = await getPool().query<{ updated_at: string }>(
`SELECT updated_at FROM public.articles WHERE id = $1`,
[articleId],
)
expect(new Date(after.rows[0].updated_at).getTime()).toBeGreaterThanOrEqual(
new Date(before.rows[0].updated_at).getTime(),
)
})
it('writes an audit row on insert', async () => {
const { userId, companyId } = await seedCompany()
const articleId = await insertArticle(companyId, userId)
const audit = await getPool().query<{ count: string }>(
`SELECT count(*)::text AS count FROM public.audit_log
WHERE table_name = 'articles' AND record_id = $1`,
[articleId],
)
expect(Number(audit.rows[0].count)).toBeGreaterThanOrEqual(1)
})
})
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,99 @@
import { randomUUID } from 'node:crypto'
import { describe, expect, it } from 'vitest'
import { getPool, withUserContext } from './setup'
import { insertAuthUser } from './fixtures'
/**
* bankid_consumed_sessions (migration 20260815120000) is the single-use guard
* for a BankID identification.
*
* The flow now lives in a cookie, so every tab of a browser shares one session
* and two of them can observe `status: complete` in the same poll tick. Both
* would call generateLink(), and the second magic link invalidates the first,
* so the tab the user is looking at may be the one that fails. Expiring the
* cookie on the way out does not prevent that: a Set-Cookie only applies once a
* response reaches the browser, and both requests already carried it.
*
* These pin the two properties the application actually relies on: the claim is
* atomic, and the table is invisible to end users. A session id is a bearer
* credential for a personnummer and for a Supabase session, and the row set is
* a record of who authenticated and when.
*/
describe('bankid_consumed_sessions (pg)', () => {
it('lets exactly one claim win for a given session id', async () => {
const sessionId = `sess-${randomUUID()}`
await getPool().query(
'INSERT INTO public.bankid_consumed_sessions (session_id) VALUES ($1)',
[sessionId],
)
await expect(
getPool().query(
'INSERT INTO public.bankid_consumed_sessions (session_id) VALUES ($1)',
[sessionId],
),
).rejects.toMatchObject({ code: '23505' })
})
it('does not collide across different sessions', async () => {
const a = `sess-${randomUUID()}`
const b = `sess-${randomUUID()}`
await getPool().query(
'INSERT INTO public.bankid_consumed_sessions (session_id) VALUES ($1), ($2)',
[a, b],
)
const { rows } = await getPool().query<{ n: number }>(
'SELECT count(*)::int AS n FROM public.bankid_consumed_sessions WHERE session_id IN ($1, $2)',
[a, b],
)
expect(rows[0]!.n).toBe(2)
})
it('stamps consumed_at so spent sessions can be aged out', async () => {
const sessionId = `sess-${randomUUID()}`
await getPool().query(
'INSERT INTO public.bankid_consumed_sessions (session_id) VALUES ($1)',
[sessionId],
)
const { rows } = await getPool().query<{ consumed_at: Date }>(
'SELECT consumed_at FROM public.bankid_consumed_sessions WHERE session_id = $1',
[sessionId],
)
expect(rows[0]!.consumed_at).toBeInstanceOf(Date)
})
it('has RLS on with no policies, so authenticated users see nothing', async () => {
const { rows: flags } = await getPool().query<{ relrowsecurity: boolean }>(
`SELECT c.relrowsecurity
FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace
WHERE n.nspname = 'public' AND c.relname = 'bankid_consumed_sessions'`,
)
expect(flags[0]!.relrowsecurity).toBe(true)
const { rows: policies } = await getPool().query<{ n: number }>(
`SELECT count(*)::int AS n FROM pg_policies
WHERE schemaname = 'public' AND tablename = 'bankid_consumed_sessions'`,
)
expect(policies[0]!.n).toBe(0)
// And the guard actually bites for a real user, not just on paper: the
// handlers write through the service role, which bypasses RLS.
const sessionId = `sess-${randomUUID()}`
await getPool().query(
'INSERT INTO public.bankid_consumed_sessions (session_id) VALUES ($1)',
[sessionId],
)
const userId = await insertAuthUser()
await withUserContext(userId, async (client) => {
const { rows } = await client.query<{ n: number }>(
'SELECT count(*)::int AS n FROM public.bankid_consumed_sessions WHERE session_id = $1',
[sessionId],
)
expect(rows[0]!.n).toBe(0)
})
})
})
@@ -0,0 +1,171 @@
import { readFileSync } from 'node:fs'
import { join } from 'node:path'
import { describe, expect, it } from 'vitest'
import { insertPostedJournalEntry, seedCompany } from '@/tests/pg/fixtures'
import { getPool } from '@/tests/pg/setup'
/**
* pg-real coverage for 20260908120449_backfill_bas2026_retired_12xx_labels.sql
* (#2413).
*
* The backfill renames 1249/1259/1269 only where the chart carries the
* contradictory pair the catalog used to hand out: a BAS 2026 free head
* (1240/1250/1260) next to a contra account still named after the retired
* bilar/inventarier/datorer accounts. Guards under test:
* - the pair is renamed (both catalog literals for the contra name)
* - an old-BAS chart (1240 "Bilar och andra transportmedel") is untouched
* - a user-renamed contra account is untouched
* - a contra account without its head is untouched
* - a contra account with journal lines (old-BAS SIE import re-labelled by
* the catalog on create) is untouched
* - idempotent (re-run is a no-op)
*/
const BACKFILL_SQL = readFileSync(
join(process.cwd(), 'supabase/migrations/20260908120449_backfill_bas2026_retired_12xx_labels.sql'),
'utf8',
)
const FREE_MASKINER = '(Fritt konto för Maskiner och andra tekniska anläggningar)'
const FREE_INVENTARIER = '(Fritt konto för Inventarier, verktyg och installationer)'
const CONTRA_MASKINER =
'Ackumulerade avskrivningar (fritt konto för Maskiner och andra tekniska anläggningar)'
const CONTRA_INVENTARIER =
'Ackumulerade avskrivningar (fritt konto för Inventarier, verktyg och installationer)'
async function runBackfill(): Promise<void> {
await getPool().query(BACKFILL_SQL)
}
async function insertAccounts(
userId: string,
companyId: string,
rows: Array<[number: string, name: string]>,
): Promise<void> {
for (const [number, name] of rows) {
await getPool().query(
`INSERT INTO public.chart_of_accounts
(user_id, company_id, account_number, account_name, account_class, account_group,
account_type, normal_balance, is_active)
VALUES ($1, $2, $3, $4, 1, '12', 'asset', $5, true)`,
[userId, companyId, number, name, number.endsWith('9') ? 'credit' : 'debit'],
)
}
}
async function names(companyId: string): Promise<Record<string, string>> {
const { rows } = await getPool().query<{ account_number: string; account_name: string }>(
`SELECT account_number, account_name FROM public.chart_of_accounts WHERE company_id = $1`,
[companyId],
)
return Object.fromEntries(rows.map((r) => [r.account_number, r.account_name]))
}
describe('backfill_bas2026_retired_12xx_labels', () => {
it('renames the contra account under a BAS 2026 free head, both catalog literals', async () => {
const { userId, companyId } = await seedCompany()
await insertAccounts(userId, companyId, [
['1240', FREE_MASKINER],
['1249', 'Ack. avskrivningar på bilar och andra transportmedel'],
['1250', FREE_INVENTARIER],
['1259', 'Ackumulerade avskrivningar på inventarier och verktyg'],
['1260', FREE_INVENTARIER],
['1269', 'Ack. avskrivningar på datorer'],
])
await runBackfill()
const after = await names(companyId)
expect(after['1249']).toBe(CONTRA_MASKINER)
expect(after['1259']).toBe(CONTRA_INVENTARIER)
expect(after['1269']).toBe(CONTRA_INVENTARIER)
expect(after['1240']).toBe(FREE_MASKINER)
})
it('leaves an old-BAS chart alone: 1240 Bilar next to 1249 Ack. avskr. bilar is consistent', async () => {
const { userId, companyId } = await seedCompany()
await insertAccounts(userId, companyId, [
['1240', 'Bilar och andra transportmedel'],
['1249', 'Ackumulerade avskrivningar på bilar och andra transportmedel'],
['1250', 'Datorer'],
['1259', 'Ackumulerade avskrivningar på datorer'],
])
await runBackfill()
const after = await names(companyId)
expect(after['1249']).toBe('Ackumulerade avskrivningar på bilar och andra transportmedel')
expect(after['1259']).toBe('Ackumulerade avskrivningar på datorer')
})
it('leaves a user rename alone', async () => {
const { userId, companyId } = await seedCompany()
await insertAccounts(userId, companyId, [
['1240', FREE_MASKINER],
['1249', 'Ack. avskrivningar maskiner och andra tekniska anläggningar'],
])
await runBackfill()
expect((await names(companyId))['1249']).toBe(
'Ack. avskrivningar maskiner och andra tekniska anläggningar',
)
})
it('leaves a contra account without its free head alone', async () => {
const { userId, companyId } = await seedCompany()
await insertAccounts(userId, companyId, [
['1249', 'Ack. avskrivningar på bilar och andra transportmedel'],
])
await runBackfill()
expect((await names(companyId))['1249']).toBe(
'Ack. avskrivningar på bilar och andra transportmedel',
)
})
it('leaves a contra account with journal lines alone, even under a free head', async () => {
// lib/import/account-sync.ts creates missing accounts with the catalog
// name when the SIE #KONTO names are not carried, so an old-BAS vehicle
// chart can hold the exact pair with real depreciation booked on 1249.
const { userId, companyId, fiscalPeriodId } = await seedCompany()
await insertAccounts(userId, companyId, [
['1240', FREE_MASKINER],
['1249', 'Ack. avskrivningar på bilar och andra transportmedel'],
['7832', 'Avskrivningar på inventarier'],
])
await insertPostedJournalEntry({
userId,
companyId,
fiscalPeriodId,
sourceType: 'import',
lines: [
{ accountNumber: '7832', debitAmount: 2500, creditAmount: 0 },
{ accountNumber: '1249', debitAmount: 0, creditAmount: 2500 },
],
})
await runBackfill()
expect((await names(companyId))['1249']).toBe(
'Ack. avskrivningar på bilar och andra transportmedel',
)
})
it('is idempotent', async () => {
const { userId, companyId } = await seedCompany()
await insertAccounts(userId, companyId, [
['1260', FREE_INVENTARIER],
['1269', 'Ackumulerade avskrivningar på datorer'],
])
await runBackfill()
const first = await names(companyId)
await runBackfill()
const second = await names(companyId)
expect(first['1269']).toBe(CONTRA_INVENTARIER)
expect(second).toEqual(first)
})
})
@@ -0,0 +1,256 @@
import { randomUUID } from 'node:crypto'
import { describe, expect, it } from 'vitest'
import { insertAuthUser, insertCashAccount, insertCompany, insertCompanyMember } from './fixtures'
import { getPool, withUserContext } from './setup'
/**
* Behandlingshistorik, part 3 (migrations 20260901103000 + 20260901200000): the behandlingsregler
* tables and the import logs write to the immutable audit_log, learning-only
* updates on categorization_templates are filtered, the global payroll
* constants are logged without a company, and app_releases is an append-only,
* read-for-all, service-role-written version log.
*/
async function setActiveCompany(userId: string, companyId: string): Promise<void> {
await getPool().query(
`INSERT INTO public.user_preferences (user_id, active_company_id)
VALUES ($1, $2)
ON CONFLICT (user_id) DO UPDATE SET active_company_id = EXCLUDED.active_company_id`,
[userId, companyId],
)
}
async function auditActions(table: string, recordId: string): Promise<string[]> {
const res = await getPool().query<{ action: string }>(
`SELECT action FROM public.audit_log
WHERE table_name = $1 AND record_id = $2
ORDER BY created_at, id`,
[table, recordId],
)
return res.rows.map((r) => r.action)
}
describe('behandlingshistorik audit triggers (BFNAR 2013:2 p. 9.16)', () => {
it('logs mapping_rules insert, update and delete with the company id', async () => {
const userId = await insertAuthUser()
const companyId = await insertCompany({ createdBy: userId })
const ruleId = randomUUID()
await getPool().query(
`INSERT INTO public.mapping_rules (id, user_id, company_id, rule_name, rule_type, debit_account, credit_account)
VALUES ($1, $2, $3, 'Kontorsmaterial', 'merchant_name', '6110', '1930')`,
[ruleId, userId, companyId],
)
await getPool().query(`UPDATE public.mapping_rules SET debit_account = '6540' WHERE id = $1`, [ruleId])
await getPool().query(`DELETE FROM public.mapping_rules WHERE id = $1`, [ruleId])
const rows = await getPool().query<{ action: string; company_id: string | null; old_debit: string | null; new_debit: string | null }>(
`SELECT action, company_id, old_state->>'debit_account' AS old_debit, new_state->>'debit_account' AS new_debit
FROM public.audit_log WHERE table_name = 'mapping_rules' AND record_id = $1
ORDER BY created_at, id`,
[ruleId],
)
expect(rows.rows).toEqual([
{ action: 'INSERT', company_id: companyId, old_debit: null, new_debit: '6110' },
{ action: 'UPDATE', company_id: companyId, old_debit: '6110', new_debit: '6540' },
{ action: 'DELETE', company_id: companyId, old_debit: '6540', new_debit: null },
])
})
it('logs categorization_templates rule changes but not learning-only updates', async () => {
const userId = await insertAuthUser()
const companyId = await insertCompany({ createdBy: userId })
const templateId = randomUUID()
await getPool().query(
`INSERT INTO public.categorization_templates (id, user_id, company_id, counterparty_name, debit_account, credit_account)
VALUES ($1, $2, $3, 'Spotify AB', '6540', '1930')`,
[templateId, userId, companyId],
)
// Learning on every booking: occurrence_count / confidence / last_seen_date,
// and counterparty_aliases, which the learning path merges in the same
// write (20260901200000; prod showed 15 of the first 16 audit rows were
// alias+learning noise).
await getPool().query(
`UPDATE public.categorization_templates
SET occurrence_count = occurrence_count + 1, confidence = 0.9, last_seen_date = CURRENT_DATE,
counterparty_aliases = ARRAY['SPOTIFY STOCKHOLM 4711']
WHERE id = $1`,
[templateId],
)
expect(await auditActions('categorization_templates', templateId)).toEqual(['INSERT'])
// But an account change arriving in the same write as learning columns is
// a behandlingsregel change and must still log (the automatkontering case).
await getPool().query(
`UPDATE public.categorization_templates
SET occurrence_count = occurrence_count + 1, credit_account = '1931',
counterparty_aliases = ARRAY['SPOTIFY STOCKHOLM 4711', 'SPOTIFY AB']
WHERE id = $1`,
[templateId],
)
expect(await auditActions('categorization_templates', templateId)).toEqual(['INSERT', 'UPDATE'])
// A plain rule change (the account) is logged.
await getPool().query(`UPDATE public.categorization_templates SET debit_account = '6212' WHERE id = $1`, [templateId])
expect(await auditActions('categorization_templates', templateId)).toEqual(['INSERT', 'UPDATE', 'UPDATE'])
await getPool().query(`DELETE FROM public.categorization_templates WHERE id = $1`, [templateId])
expect(await auditActions('categorization_templates', templateId)).toEqual(['INSERT', 'UPDATE', 'UPDATE', 'DELETE'])
})
it('logs booking_template_library changes (no user_id column: actor falls back to auth.uid())', async () => {
const userId = await insertAuthUser()
const companyId = await insertCompany({ createdBy: userId })
// btl_insert requires current_user_can_write() and company_id =
// current_active_company_id(), so the membership and the active-company
// preference both have to exist before the authenticated insert.
await insertCompanyMember({ companyId, userId })
await setActiveCompany(userId, companyId)
const templateId = randomUUID()
// Asserted INSIDE the user transaction: withUserContext always rolls back,
// so the audit row the trigger writes is gone by the time an outside
// connection could look for it. The row is what is under test, not its
// persistence, and the trigger fires in the same transaction as the write.
const rows = await withUserContext(userId, async (client) => {
await client.query(
`INSERT INTO public.booking_template_library (id, company_id, created_by, name, lines)
VALUES ($1, $2, $3, 'Hyra', '[{"account":"5010","side":"debit"}]'::jsonb)`,
[templateId, companyId, userId],
)
const audit = await client.query<{ action: string; company_id: string | null; user_id: string | null }>(
`SELECT action, company_id, user_id FROM public.audit_log
WHERE table_name = 'booking_template_library' AND record_id = $1`,
[templateId],
)
return audit.rows
})
// booking_template_library has no user_id column, so write_audit_log()
// falls back to auth.uid(): the actor is the authenticated writer.
expect(rows).toEqual([{ action: 'INSERT', company_id: companyId, user_id: userId }])
})
it('logs a cash_accounts voucher_series change but not bank-sync churn (20260902124513)', async () => {
const userId = await insertAuthUser()
const companyId = await insertCompany({ createdBy: userId })
const cashAccountId = await insertCashAccount({ companyId, ledgerAccount: '1931' })
// Bank sync touches balance and name all day: no behandlingsregel, no row.
await getPool().query(
`UPDATE public.cash_accounts SET balance = 250, name = 'Företagskort' WHERE id = $1`,
[cashAccountId],
)
expect(await auditActions('cash_accounts', cashAccountId)).toEqual([])
// Assigning the account its own verifikationsserie is a behandlingsregel.
await getPool().query(`UPDATE public.cash_accounts SET voucher_series = 'M' WHERE id = $1`, [cashAccountId])
// Clearing it back to "follow the per-type default" is one too.
await getPool().query(`UPDATE public.cash_accounts SET voucher_series = NULL WHERE id = $1`, [cashAccountId])
const rows = await getPool().query<{ action: string; company_id: string | null; old_series: string | null; new_series: string | null }>(
`SELECT action, company_id, old_state->>'voucher_series' AS old_series, new_state->>'voucher_series' AS new_series
FROM public.audit_log WHERE table_name = 'cash_accounts' AND record_id = $1
ORDER BY created_at, id`,
[cashAccountId],
)
expect(rows.rows).toEqual([
{ action: 'UPDATE', company_id: companyId, old_series: null, new_series: 'M' },
{ action: 'UPDATE', company_id: companyId, old_series: 'M', new_series: null },
])
// The CHECK from 20260902121420 still guards the column.
await expect(
getPool().query(`UPDATE public.cash_accounts SET voucher_series = 'ab' WHERE id = $1`, [cashAccountId]),
).rejects.toThrow(/check constraint/i)
})
it('logs the global payroll constants without a company (read via service role by the report)', async () => {
const id = randomUUID()
await getPool().query(
`INSERT INTO public.salary_payroll_config (
id, config_year, avgifter_total, avgifter_alderspension, avgifter_sjukforsakring,
avgifter_foraldraforsakring, avgifter_efterlevandepension, avgifter_arbetsmarknad,
avgifter_arbetsskada, avgifter_allman_loneavgift, avgifter_reduced_65plus,
avgifter_minimum_annual, egenavgifter_total, slp_rate, prisbasbelopp, inkomstbasbelopp,
max_pgi, sgi_ceiling, statlig_skatt_brytpunkt, traktamente_heldag, traktamente_halvdag,
traktamente_natt, milersattning_egen_bil, milersattning_formansbil_fossil,
milersattning_formansbil_el, kostforman_heldag, kostforman_lunch, kostforman_frukost,
friskvard_cap, bilforman_slr, reduced_avgift_age
) VALUES (
$1, 2099, 0.3142, 0.1021, 0.0355, 0.026, 0.006, 0.0264, 0.002, 0.1162, 0.1021,
1000, 0.2897, 0.2426, 60000, 85000, 600000, 500000, 650000, 290, 145, 145, 25, 12, 9.5,
110, 55, 55, 5000, 0.0196, 66
)`,
[id],
)
await getPool().query(`UPDATE public.salary_payroll_config SET prisbasbelopp = 61000 WHERE id = $1`, [id])
const rows = await getPool().query<{ action: string; company_id: string | null; new_pbb: string | null }>(
`SELECT action, company_id, new_state->>'prisbasbelopp' AS new_pbb FROM public.audit_log
WHERE table_name = 'salary_payroll_config' AND record_id = $1 ORDER BY created_at, id`,
[id],
)
expect(rows.rows.map((r) => [r.action, r.company_id])).toEqual([
['INSERT', null],
['UPDATE', null],
])
expect(Number(rows.rows[1].new_pbb)).toBe(61000)
await getPool().query(`DELETE FROM public.salary_payroll_config WHERE id = $1`, [id])
})
it('logs sie_imports and bank_file_imports rows incl. the undo status change', async () => {
const userId = await insertAuthUser()
const companyId = await insertCompany({ createdBy: userId })
const sieId = randomUUID()
const bankId = randomUUID()
await getPool().query(
`INSERT INTO public.sie_imports (id, user_id, company_id, filename, file_hash, sie_type, status)
VALUES ($1, $2, $3, 'bokio.se', $4, 4, 'completed')`,
[sieId, userId, companyId, randomUUID()],
)
await getPool().query(
`UPDATE public.sie_imports SET status = 'undone', replaced_at = now() WHERE id = $1`,
[sieId],
)
await getPool().query(
`INSERT INTO public.bank_file_imports (id, user_id, company_id, filename, file_hash, file_format)
VALUES ($1, $2, $3, 'seb.csv', $4, 'seb')`,
[bankId, userId, companyId, randomUUID()],
)
const sie = await getPool().query<{ action: string; new_status: string | null }>(
`SELECT action, new_state->>'status' AS new_status FROM public.audit_log
WHERE table_name = 'sie_imports' AND record_id = $1 ORDER BY created_at, id`,
[sieId],
)
expect(sie.rows).toEqual([
{ action: 'INSERT', new_status: 'completed' },
{ action: 'UPDATE', new_status: 'undone' },
])
expect(await auditActions('bank_file_imports', bankId)).toEqual(['INSERT'])
})
it('app_releases: readable by any signed-in user, writable only by the service role, immutable', async () => {
const userId = await insertAuthUser()
const version = `test-${randomUUID().slice(0, 8)}`
await getPool().query(`INSERT INTO public.app_releases (version) VALUES ($1)`, [version])
const seen = await withUserContext(userId, async (client) => {
const res = await client.query<{ version: string }>(
`SELECT version FROM public.app_releases WHERE version = $1`,
[version],
)
return res.rows.map((r) => r.version)
})
expect(seen).toEqual([version])
await expect(
withUserContext(userId, (client) =>
client.query(`INSERT INTO public.app_releases (version) VALUES ($1)`, [`${version}-user`]),
),
).rejects.toThrow(/row-level security/i)
await expect(
getPool().query(`UPDATE public.app_releases SET source = 'edited' WHERE version = $1`, [version]),
).rejects.toThrow()
await expect(
getPool().query(`DELETE FROM public.app_releases WHERE version = $1`, [version]),
).rejects.toThrow()
})
})
+160
View File
@@ -0,0 +1,160 @@
import { describe, expect, it } from 'vitest'
import { getPool } from './setup'
import { insertAuthUser, insertCompany, insertFiscalPeriod } from './fixtures'
describe('BFL retention expiry', () => {
it('runs the corrected retention trigger after the original migration 017 trigger', async () => {
const result = await getPool().query<{
trigger_name: string
trigger_definition: string
}>(
`SELECT
trigger.tgname AS trigger_name,
pg_get_triggerdef(trigger.oid) AS trigger_definition
FROM pg_trigger trigger
JOIN pg_class target ON target.oid = trigger.tgrelid
JOIN pg_namespace schema ON schema.oid = target.relnamespace
WHERE schema.nspname = 'public'
AND target.relname = 'fiscal_periods'
AND NOT trigger.tgisinternal
AND trigger.tgname IN (
'calculate_retention_expiry',
'zz_set_bfl_retention_expiry',
'enforce_period_start_day'
)
ORDER BY trigger.tgname`,
)
expect(result.rows).toEqual([
{
trigger_name: 'calculate_retention_expiry',
trigger_definition:
'CREATE TRIGGER calculate_retention_expiry BEFORE INSERT OR UPDATE ON public.fiscal_periods FOR EACH ROW EXECUTE FUNCTION calculate_retention_expiry()',
},
{
trigger_name: 'enforce_period_start_day',
trigger_definition:
'CREATE TRIGGER enforce_period_start_day BEFORE INSERT OR UPDATE OF company_id, period_start ON public.fiscal_periods FOR EACH ROW EXECUTE FUNCTION enforce_first_of_month_for_subsequent_periods()',
},
{
trigger_name: 'zz_set_bfl_retention_expiry',
trigger_definition:
'CREATE TRIGGER zz_set_bfl_retention_expiry BEFORE INSERT OR UPDATE ON public.fiscal_periods FOR EACH ROW EXECUTE FUNCTION set_bfl_retention_expiry()',
},
])
})
it('retains a fiscal year through the end of the seventh following calendar year', async () => {
const userId = await insertAuthUser()
const companyId = await insertCompany({ createdBy: userId })
const fiscalPeriodId = await insertFiscalPeriod({
userId,
companyId,
periodStart: '2025-07-01',
periodEnd: '2026-06-30',
name: '2025/2026',
})
const result = await getPool().query<{ retention_expires_at: string }>(
`SELECT retention_expires_at::text
FROM public.fiscal_periods
WHERE id = $1`,
[fiscalPeriodId],
)
expect(result.rows[0].retention_expires_at).toBe('2034-01-01')
})
it('recalculates the first allowed deletion date when an open period end changes', async () => {
const userId = await insertAuthUser()
const companyId = await insertCompany({ createdBy: userId })
const fiscalPeriodId = await insertFiscalPeriod({ userId, companyId })
await getPool().query(
`UPDATE public.fiscal_periods
SET period_end = '2027-03-31'
WHERE id = $1`,
[fiscalPeriodId],
)
const result = await getPool().query<{ retention_expires_at: string }>(
`SELECT retention_expires_at::text
FROM public.fiscal_periods
WHERE id = $1`,
[fiscalPeriodId],
)
expect(result.rows[0].retention_expires_at).toBe('2035-01-01')
})
it('does not restore the old expiry calculation on unrelated updates', async () => {
const userId = await insertAuthUser()
const companyId = await insertCompany({ createdBy: userId })
const fiscalPeriodId = await insertFiscalPeriod({
userId,
companyId,
periodStart: '2025-07-01',
periodEnd: '2026-06-30',
name: '2025/2026',
})
await getPool().query(
`UPDATE public.fiscal_periods
SET name = 'Updated 2025/2026'
WHERE id = $1`,
[fiscalPeriodId],
)
const result = await getPool().query<{ retention_expires_at: string }>(
`SELECT retention_expires_at::text
FROM public.fiscal_periods
WHERE id = $1`,
[fiscalPeriodId],
)
expect(result.rows[0].retention_expires_at).toBe('2034-01-01')
})
it('allows retention backfills when a historical mid-month start is unchanged', async () => {
const userId = await insertAuthUser()
const companyId = await insertCompany({ createdBy: userId })
const historicalPeriodId = await insertFiscalPeriod({
userId,
companyId,
periodStart: '2025-10-20',
periodEnd: '2025-12-31',
name: 'Historical period',
})
// Adding an earlier period makes the existing mid-month row match the
// historical state that used to abort unrelated fiscal-period updates.
await insertFiscalPeriod({
userId,
companyId,
periodStart: '2024-01-01',
periodEnd: '2024-12-31',
name: 'Earlier period',
})
await expect(
getPool().query(
`UPDATE public.fiscal_periods
SET retention_expires_at = make_date(
extract(year FROM period_end)::integer + 8,
1,
1
)
WHERE id = $1`,
[historicalPeriodId],
),
).resolves.toBeDefined()
const result = await getPool().query<{ retention_expires_at: string }>(
`SELECT retention_expires_at::text
FROM public.fiscal_periods
WHERE id = $1`,
[historicalPeriodId],
)
expect(result.rows[0].retention_expires_at).toBe('2033-01-01')
})
})
+113
View File
@@ -0,0 +1,113 @@
import { describe, it, expect } from 'vitest'
import { getPool, withUserContext } from './setup'
import { seedCompany, insertAuthUser, insertCompanyMember } from './fixtures'
// pg-real coverage for 20260824210000_bokslut_checklist_items: RLS (members
// read, owner/admin/member write as themselves, viewers read-only, no
// DELETE policy), the item_key and state CHECKs, the done pair CHECK and the
// composite primary key (one row per item and period).
async function tick(
companyId: string,
periodId: string,
userId: string,
overrides: { itemKey?: string; state?: string; doneAt?: string | null } = {},
): Promise<void> {
const state = overrides.state ?? 'done'
const doneAt = overrides.doneAt === undefined ? (state === 'open' ? null : new Date().toISOString()) : overrides.doneAt
await getPool().query(
`INSERT INTO public.bokslut_checklist_items
(company_id, fiscal_period_id, item_key, state, done_by, done_at, updated_by)
VALUES ($1, $2, $3, $4, $5, $6, $5)`,
[companyId, periodId, overrides.itemKey ?? 'inventory_valued', state, userId, doneAt],
)
}
describe('bokslut_checklist_items RLS', () => {
it('lets company members read, strangers see nothing', async () => {
const { userId, companyId, fiscalPeriodId } = await seedCompany()
await tick(companyId, fiscalPeriodId, userId)
const stranger = await insertAuthUser()
const ownerView = await withUserContext(userId, (client) =>
client.query(`SELECT item_key FROM public.bokslut_checklist_items WHERE fiscal_period_id = $1`, [fiscalPeriodId]),
)
expect(ownerView.rows).toHaveLength(1)
const strangerView = await withUserContext(stranger, (client) =>
client.query(`SELECT item_key FROM public.bokslut_checklist_items WHERE fiscal_period_id = $1`, [fiscalPeriodId]),
)
expect(strangerView.rows).toHaveLength(0)
})
it('lets viewers read but not tick', async () => {
const { userId, companyId, fiscalPeriodId } = await seedCompany()
await tick(companyId, fiscalPeriodId, userId)
const viewer = await insertAuthUser()
await insertCompanyMember({ companyId, userId: viewer, role: 'viewer' })
const read = await withUserContext(viewer, (client) =>
client.query(`SELECT item_key FROM public.bokslut_checklist_items WHERE fiscal_period_id = $1`, [fiscalPeriodId]),
)
expect(read.rows).toHaveLength(1)
await expect(
withUserContext(viewer, (client) =>
client.query(
`INSERT INTO public.bokslut_checklist_items (company_id, fiscal_period_id, item_key, state, done_by, done_at, updated_by)
VALUES ($1, $2, 'accruals_posted', 'done', $3, NOW(), $3)`,
[companyId, fiscalPeriodId, viewer],
),
),
).rejects.toThrow(/row-level security/i)
})
it('lets members tick as themselves, upsert their own rows, but not sign as someone else', async () => {
const { userId: owner, companyId, fiscalPeriodId } = await seedCompany()
const member = await insertAuthUser()
await insertCompanyMember({ companyId, userId: member, role: 'member' })
const inserted = await withUserContext(member, (client) =>
client.query(
`INSERT INTO public.bokslut_checklist_items (company_id, fiscal_period_id, item_key, state, done_by, done_at, updated_by)
VALUES ($1, $2, 'accruals_posted', 'done', $3, NOW(), $3)
ON CONFLICT (company_id, fiscal_period_id, item_key)
DO UPDATE SET state = EXCLUDED.state, done_by = EXCLUDED.done_by, done_at = EXCLUDED.done_at, updated_by = EXCLUDED.updated_by, updated_at = NOW()
RETURNING state`,
[companyId, fiscalPeriodId, member],
),
)
expect(inserted.rows[0].state).toBe('done')
await expect(
withUserContext(member, (client) =>
client.query(
`INSERT INTO public.bokslut_checklist_items (company_id, fiscal_period_id, item_key, state, done_by, done_at, updated_by)
VALUES ($1, $2, 'tax_provision', 'done', $3, NOW(), $3)`,
[companyId, fiscalPeriodId, owner],
),
),
).rejects.toThrow(/row-level security/i)
})
it('has no DELETE policy: a member delete touches nothing', async () => {
const { userId, companyId, fiscalPeriodId } = await seedCompany()
await tick(companyId, fiscalPeriodId, userId)
const res = await withUserContext(userId, (client) =>
client.query(`DELETE FROM public.bokslut_checklist_items WHERE fiscal_period_id = $1`, [fiscalPeriodId]),
)
expect(res.rowCount).toBe(0)
})
})
describe('bokslut_checklist_items constraints', () => {
it('rejects a malformed key, an unknown state, an open row with done_at, a done row without it, and a duplicate', async () => {
const { userId, companyId, fiscalPeriodId } = await seedCompany()
await expect(tick(companyId, fiscalPeriodId, userId, { itemKey: 'Not Valid' })).rejects.toThrow(/item_key/i)
await expect(tick(companyId, fiscalPeriodId, userId, { state: 'maybe' })).rejects.toThrow(/state/i)
await expect(tick(companyId, fiscalPeriodId, userId, { state: 'open', doneAt: new Date().toISOString() })).rejects.toThrow(/done_pair/i)
await expect(tick(companyId, fiscalPeriodId, userId, { state: 'done', doneAt: null })).rejects.toThrow(/done_pair/i)
await tick(companyId, fiscalPeriodId, userId, { itemKey: 'no_drafts', state: 'not_applicable' })
await expect(tick(companyId, fiscalPeriodId, userId, { itemKey: 'no_drafts' })).rejects.toThrow(/duplicate key/i)
})
})
+196
View File
@@ -0,0 +1,196 @@
import { describe, it, expect } from 'vitest'
import { getPool, withUserContext } from './setup'
import { seedCompany, insertAuthUser, insertCompanyMember } from './fixtures'
/**
* `booking_template_hidden` (migration 20260828100000).
*
* Per-company opt-in hiding of system templates. The RLS matters here: a hide
* row written by company A must never leak to, or be writable from, company B,
* and viewers must not be able to hide anything. All writes go through the
* authenticated role so the policies are what is actually under test.
*/
async function setActiveCompany(userId: string, companyId: string) {
await getPool().query(
`INSERT INTO public.user_preferences (user_id, active_company_id)
VALUES ($1, $2)
ON CONFLICT (user_id) DO UPDATE SET active_company_id = EXCLUDED.active_company_id`,
[userId, companyId],
)
}
async function systemTemplateId(): Promise<string> {
const { rows } = await getPool().query(
`SELECT id FROM public.booking_template_library WHERE is_system AND is_active LIMIT 1`,
)
return rows[0].id as string
}
describe('booking_template_hidden RLS', () => {
it('lets a write-role member hide and unhide for the active company', async () => {
const { userId, companyId } = await seedCompany()
await setActiveCompany(userId, companyId)
const templateId = await systemTemplateId()
await withUserContext(userId, async (client) => {
await client.query(
`INSERT INTO public.booking_template_hidden (template_id, company_id, hidden_by)
VALUES ($1, $2, $3)`,
[templateId, companyId, userId],
)
const { rows } = await client.query(
`SELECT template_id FROM public.booking_template_hidden WHERE company_id = $1`,
[companyId],
)
expect(rows).toHaveLength(1)
expect(rows[0].template_id).toBe(templateId)
const del = await client.query(
`DELETE FROM public.booking_template_hidden
WHERE template_id = $1 AND company_id = $2`,
[templateId, companyId],
)
expect(del.rowCount).toBe(1)
})
})
it('blocks hiding for a company that is not the active one', async () => {
const { userId, companyId } = await seedCompany()
const other = await seedCompany()
// Member of both, but acting in their own company.
await insertCompanyMember({ companyId: other.companyId, userId, role: 'owner' })
await setActiveCompany(userId, companyId)
const templateId = await systemTemplateId()
await withUserContext(userId, async (client) => {
await expect(
client.query(
`INSERT INTO public.booking_template_hidden (template_id, company_id, hidden_by)
VALUES ($1, $2, $3)`,
[templateId, other.companyId, userId],
),
).rejects.toThrow(/row-level security/)
})
})
it('blocks a viewer from hiding', async () => {
const { companyId } = await seedCompany()
const viewerId = await insertAuthUser()
await insertCompanyMember({ companyId, userId: viewerId, role: 'viewer' })
await setActiveCompany(viewerId, companyId)
const templateId = await systemTemplateId()
await withUserContext(viewerId, async (client) => {
await expect(
client.query(
`INSERT INTO public.booking_template_hidden (template_id, company_id, hidden_by)
VALUES ($1, $2, $3)`,
[templateId, companyId, viewerId],
),
).rejects.toThrow(/row-level security/)
})
})
it("does not leak another company's hide rows", async () => {
const a = await seedCompany()
const b = await seedCompany()
const templateId = await systemTemplateId()
// Seed A's hide row on the superuser connection so it persists for B's read.
await getPool().query(
`INSERT INTO public.booking_template_hidden (template_id, company_id, hidden_by)
VALUES ($1, $2, $3) ON CONFLICT DO NOTHING`,
[templateId, a.companyId, a.userId],
)
await setActiveCompany(b.userId, b.companyId)
await withUserContext(b.userId, async (client) => {
const { rows } = await client.query(
`SELECT template_id FROM public.booking_template_hidden`,
)
expect(rows).toEqual([])
})
// Cleanup the persisted seed row.
await getPool().query(
`DELETE FROM public.booking_template_hidden WHERE company_id = $1`,
[a.companyId],
)
})
it('re-hide via ON CONFLICT DO NOTHING succeeds despite no UPDATE policy', async () => {
// The route upserts with ignoreDuplicates (DO NOTHING). A DO UPDATE arm
// would be rejected by RLS here (no UPDATE policy on purpose), so this
// pins the exact conflict shape the route sends: second hide = no-op 0
// rows, not an error.
const { userId, companyId } = await seedCompany()
await setActiveCompany(userId, companyId)
const templateId = await systemTemplateId()
await withUserContext(userId, async (client) => {
const first = await client.query(
`INSERT INTO public.booking_template_hidden (template_id, company_id, hidden_by)
VALUES ($1, $2, $3)
ON CONFLICT (template_id, company_id) DO NOTHING`,
[templateId, companyId, userId],
)
expect(first.rowCount).toBe(1)
const second = await client.query(
`INSERT INTO public.booking_template_hidden (template_id, company_id, hidden_by)
VALUES ($1, $2, $3)
ON CONFLICT (template_id, company_id) DO NOTHING`,
[templateId, companyId, userId],
)
expect(second.rowCount).toBe(0)
})
})
it('blocks hiding a non-system (company) template even via direct insert', async () => {
const { userId, companyId } = await seedCompany()
await setActiveCompany(userId, companyId)
// A company-scoped template: has a real delete path, must not be hideable.
const { rows } = await getPool().query(
`INSERT INTO public.booking_template_library
(company_id, created_by, name, description, category, entity_type, is_system, lines)
VALUES ($1, $2, 'Egen mall', '', 'other', 'all', FALSE, '[]'::jsonb)
RETURNING id`,
[companyId, userId],
)
const companyTemplateId = rows[0].id as string
await withUserContext(userId, async (client) => {
await expect(
client.query(
`INSERT INTO public.booking_template_hidden (template_id, company_id, hidden_by)
VALUES ($1, $2, $3)`,
[companyTemplateId, companyId, userId],
),
).rejects.toThrow(/row-level security/)
})
await getPool().query(`DELETE FROM public.booking_template_library WHERE id = $1`, [
companyTemplateId,
])
})
it('enforces one hide row per (template, company)', async () => {
const { userId, companyId } = await seedCompany()
await setActiveCompany(userId, companyId)
const templateId = await systemTemplateId()
await withUserContext(userId, async (client) => {
await client.query(
`INSERT INTO public.booking_template_hidden (template_id, company_id, hidden_by)
VALUES ($1, $2, $3)`,
[templateId, companyId, userId],
)
await expect(
client.query(
`INSERT INTO public.booking_template_hidden (template_id, company_id, hidden_by)
VALUES ($1, $2, $3)`,
[templateId, companyId, userId],
),
).rejects.toThrow(/duplicate key/)
})
})
})
@@ -0,0 +1,97 @@
import { describe, it, expect } from 'vitest'
import { randomUUID } from 'node:crypto'
import { getPool } from './setup'
import { seedCompany } from './fixtures'
/**
* `booking_template_library.pack_slug` (migration 20260803230000).
*
* The column is the stable upsert key that lets system templates be synced from
* packs/*.yaml instead of living as rows frozen inside migration 20260413160000.
* Its three guards each stop a specific way the sync could corrupt the
* catalogue, so each is asserted here rather than trusted.
*/
describe('booking_template_library.pack_slug', () => {
it('backfilled every seeded system template', async () => {
const { rows } = await getPool().query(
`SELECT count(*) FILTER (WHERE pack_slug IS NULL) AS missing, count(*) AS total
FROM public.booking_template_library WHERE is_system`,
)
// A system template without a slug would be invisible to the sync and would
// silently persist as a duplicate of whatever pack replaced it.
expect(Number(rows[0].missing)).toBe(0)
expect(Number(rows[0].total)).toBeGreaterThan(0)
})
it('holds a unique slug per system template', async () => {
const { rows } = await getPool().query(
`SELECT pack_slug, count(*) AS n FROM public.booking_template_library
WHERE pack_slug IS NOT NULL GROUP BY pack_slug HAVING count(*) > 1`,
)
expect(rows).toEqual([])
})
it('rejects a second row claiming an existing slug', async () => {
const existing = await getPool().query(
`SELECT pack_slug FROM public.booking_template_library WHERE pack_slug IS NOT NULL LIMIT 1`,
)
const slug = existing.rows[0].pack_slug as string
await expect(
getPool().query(
`INSERT INTO public.booking_template_library
(name, description, category, entity_type, is_system, lines, pack_slug)
VALUES ('Dubblett', '', 'other', 'all', TRUE, '[]'::jsonb, $1)`,
[slug],
),
).rejects.toThrow(/btl_pack_slug_unique/)
})
it('rejects a slug that the pack loader would refuse', async () => {
for (const bad of ['Bad_Slug', 'trailing-', '-leading', 'double--dash', 'ÅÄÖ']) {
await expect(
getPool().query(
`INSERT INTO public.booking_template_library
(name, description, category, entity_type, is_system, lines, pack_slug)
VALUES ('Ogiltig', '', 'other', 'all', TRUE, '[]'::jsonb, $1)`,
[bad],
),
bad,
).rejects.toThrow(/btl_pack_slug_format/)
}
})
it('refuses a pack_slug on a COMPANY template, which would shadow the pack', async () => {
// Scoped to a real company so the pre-existing "company or team or system"
// CHECK is satisfied and pack_slug is genuinely the constraint under test.
const { companyId, userId } = await seedCompany()
await expect(
getPool().query(
`INSERT INTO public.booking_template_library
(id, company_id, created_by, name, description, category, entity_type,
is_system, lines, pack_slug)
VALUES ($1, $2, $3, 'Kapad mall', '', 'other', 'all', FALSE, '[]'::jsonb, 'kapad-mall')`,
[randomUUID(), companyId, userId],
),
).rejects.toThrow(/btl_pack_slug_system_only/)
})
it('still allows a company template with no slug', async () => {
const { companyId, userId } = await seedCompany()
const id = randomUUID()
await getPool().query(
`INSERT INTO public.booking_template_library
(id, company_id, created_by, name, description, category, entity_type, is_system, lines)
VALUES ($1, $2, $3, 'Egen mall', '', 'other', 'all', FALSE, '[]'::jsonb)`,
[id, companyId, userId],
)
const { rows } = await getPool().query(
`SELECT pack_slug FROM public.booking_template_library WHERE id = $1`,
[id],
)
expect(rows[0].pack_slug).toBeNull()
})
})
+80
View File
@@ -0,0 +1,80 @@
-- pg-real CI bootstrap.
--
-- The Supabase Postgres image ships a partial `storage` schema; the remaining
-- columns and functions are provisioned at runtime by the storage-api
-- service, which we do not run in CI. This bootstrap aligns the schema with
-- what our migrations expect so the replay loop succeeds. It is idempotent
-- and safe to run against a freshly-initialised container.
CREATE SCHEMA IF NOT EXISTS storage;
CREATE TABLE IF NOT EXISTS storage.buckets (
id text PRIMARY KEY,
name text NOT NULL,
owner uuid,
created_at timestamptz DEFAULT now(),
updated_at timestamptz DEFAULT now()
);
ALTER TABLE storage.buckets
ADD COLUMN IF NOT EXISTS public boolean DEFAULT false,
ADD COLUMN IF NOT EXISTS file_size_limit bigint,
ADD COLUMN IF NOT EXISTS allowed_mime_types text[];
CREATE TABLE IF NOT EXISTS storage.objects (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
bucket_id text REFERENCES storage.buckets(id) ON DELETE CASCADE,
name text,
owner uuid,
created_at timestamptz DEFAULT now(),
updated_at timestamptz DEFAULT now(),
last_accessed_at timestamptz DEFAULT now(),
metadata jsonb,
version text,
owner_id text
);
ALTER TABLE storage.objects ENABLE ROW LEVEL SECURITY;
-- storage.foldername(): splits a slash-delimited object name into segments.
-- Migrations use `(storage.foldername(name))[n]` to derive tenant scoping
-- from the object path.
CREATE OR REPLACE FUNCTION storage.foldername(name text)
RETURNS text[]
LANGUAGE sql
IMMUTABLE
AS $$
SELECT string_to_array(name, '/');
$$;
-- auth.identities is created by GoTrue at startup, not by the Postgres
-- image. Likewise, GoTrue's 20240214120130 migration adds is_anonymous;
-- sandbox authorization reads this server-owned flag, not user metadata.
ALTER TABLE auth.users
ADD COLUMN IF NOT EXISTS is_anonymous boolean NOT NULL DEFAULT false;
-- auth.identities is created by GoTrue at startup, not by the Postgres
-- image, and GoTrue does not run in CI. Triggers on auth.users that touch
-- identities (20260903110000 unlink_old_address_identities) need the table
-- to exist so an email change in a pg-real test does not fail with 42P01.
-- Shape mirrors GoTrue's migration (same PK, unique key, generated email).
CREATE TABLE IF NOT EXISTS auth.identities (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
provider_id text NOT NULL,
user_id uuid NOT NULL REFERENCES auth.users(id) ON DELETE CASCADE,
identity_data jsonb NOT NULL,
provider text NOT NULL,
last_sign_in_at timestamptz,
created_at timestamptz,
updated_at timestamptz,
email text GENERATED ALWAYS AS (lower(identity_data ->> 'email')) STORED,
CONSTRAINT identities_provider_id_provider_unique UNIQUE (provider_id, provider)
);
CREATE INDEX IF NOT EXISTS identities_user_id_idx ON auth.identities (user_id);
-- auth.audit_log_entries ships in the Postgres image without the ip_address
-- column GoTrue adds on first boot (NOT NULL DEFAULT '' on every hosted
-- project). unlink_old_address_identities writes GoTrue's audit table with
-- that column, so the CI double must carry it too.
ALTER TABLE IF EXISTS auth.audit_log_entries
ADD COLUMN IF NOT EXISTS ip_address varchar(64) NOT NULL DEFAULT '';
+336
View File
@@ -0,0 +1,336 @@
import { randomUUID } from 'node:crypto'
import { describe, expect, it } from 'vitest'
import { getPool, withUserContext } from '@/tests/pg/setup'
import { insertAuthUser } from '@/tests/pg/fixtures'
// Tests for 20260827120000_brand_invite_only_signup.sql: brands.signup_mode,
// the brand_signup_allowlist table (lowercase/format/unique CHECKs, cascade,
// team-scoped RLS with owner/admin-only writes) and the
// create_company_for_brand_signup RPC (allowlist-gated byrå team attachment).
async function insertTeam(params: {
createdBy: string
kind?: 'personal' | 'byra'
}): Promise<string> {
const id = randomUUID()
await getPool().query(
`INSERT INTO public.teams (id, name, created_by, kind)
VALUES ($1, 'Byra Team', $2, $3)`,
[id, params.createdBy, params.kind ?? 'byra'],
)
await getPool().query(
`INSERT INTO public.team_members (team_id, user_id, role)
VALUES ($1, $2, 'owner')`,
[id, params.createdBy],
)
return id
}
async function addTeamMember(teamId: string, userId: string, role: string): Promise<void> {
await getPool().query(
`INSERT INTO public.team_members (team_id, user_id, role) VALUES ($1, $2, $3)`,
[teamId, userId, role],
)
}
async function insertBrand(teamId: string, signupMode?: string): Promise<string> {
const id = randomUUID()
await getPool().query(
`INSERT INTO public.brands (id, team_id, domain, app_name, brand_color, support_email, signup_mode)
VALUES ($1, $2, $3, 'Testbrand', '#2563eb', '[email protected]', COALESCE($4, 'open'))`,
[id, teamId, `${randomUUID().slice(0, 8)}.accounted.se`, signupMode ?? null],
)
return id
}
async function insertAllowlistEntry(brandId: string, email: string): Promise<string> {
const id = randomUUID()
await getPool().query(
`INSERT INTO public.brand_signup_allowlist (id, brand_id, email) VALUES ($1, $2, $3)`,
[id, brandId, email],
)
return id
}
/** The deterministic email insertAuthUser gives an auth user. */
function authEmail(userId: string): string {
return `pg-real-${userId}@test.invalid`
}
async function expectSqlstate(fn: () => Promise<unknown>, expected: string): Promise<void> {
let sqlstate: string | undefined
try {
await fn()
} catch (err) {
sqlstate = (err as { code?: string }).code
}
expect(sqlstate).toBe(expected)
}
describe('brands.signup_mode', () => {
it('defaults to open and accepts invite_only', async () => {
const owner = await insertAuthUser()
const teamId = await insertTeam({ createdBy: owner })
const brandId = await insertBrand(teamId)
const { rows } = await getPool().query<{ signup_mode: string }>(
`SELECT signup_mode FROM public.brands WHERE id = $1`,
[brandId],
)
expect(rows[0].signup_mode).toBe('open')
await getPool().query(
`UPDATE public.brands SET signup_mode = 'invite_only' WHERE id = $1`,
[brandId],
)
})
it('rejects unknown modes (23514)', async () => {
const owner = await insertAuthUser()
const teamId = await insertTeam({ createdBy: owner })
const brandId = await insertBrand(teamId)
await expectSqlstate(
() =>
getPool().query(`UPDATE public.brands SET signup_mode = 'closed' WHERE id = $1`, [
brandId,
]),
'23514',
)
})
})
describe('brand_signup_allowlist: shape', () => {
it('rejects mixed-case and malformed emails (23514)', async () => {
const owner = await insertAuthUser()
const teamId = await insertTeam({ createdBy: owner })
const brandId = await insertBrand(teamId)
await expectSqlstate(() => insertAllowlistEntry(brandId, '[email protected]'), '23514')
await expectSqlstate(() => insertAllowlistEntry(brandId, 'not-an-email'), '23514')
await expectSqlstate(() => insertAllowlistEntry(brandId, 'a [email protected]'), '23514')
})
it('enforces one entry per brand and email (23505), same email ok on another brand', async () => {
const ownerA = await insertAuthUser()
const ownerB = await insertAuthUser()
const brandA = await insertBrand(await insertTeam({ createdBy: ownerA }))
const brandB = await insertBrand(await insertTeam({ createdBy: ownerB }))
await insertAllowlistEntry(brandA, '[email protected]')
await expectSqlstate(() => insertAllowlistEntry(brandA, '[email protected]'), '23505')
await insertAllowlistEntry(brandB, '[email protected]')
})
it('cascades on brand delete', async () => {
const owner = await insertAuthUser()
const brandId = await insertBrand(await insertTeam({ createdBy: owner }))
const entryId = await insertAllowlistEntry(brandId, '[email protected]')
await getPool().query(`DELETE FROM public.brands WHERE id = $1`, [brandId])
const { rows } = await getPool().query(
`SELECT 1 FROM public.brand_signup_allowlist WHERE id = $1`,
[entryId],
)
expect(rows).toHaveLength(0)
})
})
describe('brand_signup_allowlist: RLS', () => {
it('team members read their own list; outsiders see nothing', async () => {
const owner = await insertAuthUser()
const member = await insertAuthUser()
const stranger = await insertAuthUser()
const teamId = await insertTeam({ createdBy: owner })
await addTeamMember(teamId, member, 'member')
const brandId = await insertBrand(teamId)
await insertAllowlistEntry(brandId, '[email protected]')
for (const insider of [owner, member]) {
await withUserContext(insider, async (client) => {
const { rows } = await client.query(
`SELECT id FROM public.brand_signup_allowlist WHERE brand_id = $1`,
[brandId],
)
expect(rows).toHaveLength(1)
})
}
await withUserContext(stranger, async (client) => {
const { rows } = await client.query(
`SELECT id FROM public.brand_signup_allowlist WHERE brand_id = $1`,
[brandId],
)
expect(rows).toHaveLength(0)
})
})
it('owner/admin can insert and delete; plain members cannot', async () => {
const owner = await insertAuthUser()
const admin = await insertAuthUser()
const member = await insertAuthUser()
const teamId = await insertTeam({ createdBy: owner })
await addTeamMember(teamId, admin, 'admin')
await addTeamMember(teamId, member, 'member')
const brandId = await insertBrand(teamId)
// Admin INSERT passes the WITH CHECK (no 42501). withUserContext always
// rolls back, so this asserts the policy allows the write; it does not
// persist. The persistent row for the DELETE assertions is seeded on the
// superuser pool below.
await withUserContext(admin, async (client) => {
await client.query(
`INSERT INTO public.brand_signup_allowlist (brand_id, email, created_by)
VALUES ($1, '[email protected]', $2)`,
[brandId, admin],
)
})
// Plain member INSERT violates the with-check (42501).
let sqlstate: string | undefined
try {
await withUserContext(member, async (client) => {
await client.query(
`INSERT INTO public.brand_signup_allowlist (brand_id, email) VALUES ($1, '[email protected]')`,
[brandId],
)
})
} catch (err) {
sqlstate = (err as { code?: string }).code
}
expect(sqlstate).toBe('42501')
// Seed a row that persists (superuser pool, no rollback) so the DELETE
// assertions below act on a real row: member DELETE must be RLS-filtered
// to zero, owner DELETE must remove the one row.
await insertAllowlistEntry(brandId, '[email protected]')
// Plain member DELETE is silently filtered to zero rows.
await withUserContext(member, async (client) => {
const deleted = await client.query(
`DELETE FROM public.brand_signup_allowlist WHERE brand_id = $1`,
[brandId],
)
expect(deleted.rowCount).toBe(0)
})
// The member's rolled-back DELETE left the row intact; owner removes it.
await withUserContext(owner, async (client) => {
const deleted = await client.query(
`DELETE FROM public.brand_signup_allowlist WHERE brand_id = $1`,
[brandId],
)
expect(deleted.rowCount).toBe(1)
})
})
})
describe('create_company_for_brand_signup', () => {
it('creates a company on the brand team for an allowlisted user', async () => {
const byraOwner = await insertAuthUser()
const client = await insertAuthUser()
const teamId = await insertTeam({ createdBy: byraOwner })
const brandId = await insertBrand(teamId, 'invite_only')
await insertAllowlistEntry(brandId, authEmail(client))
const { rows } = await getPool().query<{ id: string }>(
`SELECT public.create_company_for_brand_signup($1, 'Kundbolaget AB', 'aktiebolag', $2) AS id`,
[client, brandId],
)
const companyId = rows[0].id
const { rows: companyRows } = await getPool().query<{
team_id: string
created_by: string
}>(`SELECT team_id, created_by FROM public.companies WHERE id = $1`, [companyId])
expect(companyRows[0]).toEqual({ team_id: teamId, created_by: client })
// The signup user owns the company; team sync gave the byrå access too.
const { rows: memberRows } = await getPool().query<{ user_id: string; role: string }>(
`SELECT user_id, role FROM public.company_members WHERE company_id = $1 ORDER BY role`,
[companyId],
)
expect(memberRows).toContainEqual({ user_id: client, role: 'owner' })
expect(memberRows.some((m) => m.user_id === byraOwner)).toBe(true)
})
it('matches the allowlist case-insensitively against the auth email', async () => {
const byraOwner = await insertAuthUser()
const client = await insertAuthUser()
const teamId = await insertTeam({ createdBy: byraOwner })
const brandId = await insertBrand(teamId, 'invite_only')
// Auth emails from the fixture are already lowercase; the allowlist
// stores lowercase by CHECK, so this is the canonical match.
await insertAllowlistEntry(brandId, authEmail(client))
const { rows } = await getPool().query<{ id: string }>(
`SELECT public.create_company_for_brand_signup($1, 'EF Kund', 'enskild_firma', $2) AS id`,
[client, brandId],
)
expect(rows[0].id).toBeTruthy()
})
it('refuses a user who is not on the allowlist (42501)', async () => {
const byraOwner = await insertAuthUser()
const stranger = await insertAuthUser()
const teamId = await insertTeam({ createdBy: byraOwner })
const brandId = await insertBrand(teamId, 'invite_only')
await expectSqlstate(
() =>
getPool().query(
`SELECT public.create_company_for_brand_signup($1, 'Rogue AB', 'aktiebolag', $2)`,
[stranger, brandId],
),
'42501',
)
})
it('refuses unknown brands (23503) and unknown users (23503)', async () => {
const byraOwner = await insertAuthUser()
const client = await insertAuthUser()
const teamId = await insertTeam({ createdBy: byraOwner })
const brandId = await insertBrand(teamId, 'invite_only')
await insertAllowlistEntry(brandId, authEmail(client))
await expectSqlstate(
() =>
getPool().query(
`SELECT public.create_company_for_brand_signup($1, 'X AB', 'aktiebolag', $2)`,
[client, randomUUID()],
),
'23503',
)
await expectSqlstate(
() =>
getPool().query(
`SELECT public.create_company_for_brand_signup($1, 'X AB', 'aktiebolag', $2)`,
[randomUUID(), brandId],
),
'23503',
)
})
it('is not executable by authenticated sessions (42501)', async () => {
const byraOwner = await insertAuthUser()
const client = await insertAuthUser()
const teamId = await insertTeam({ createdBy: byraOwner })
const brandId = await insertBrand(teamId, 'invite_only')
await insertAllowlistEntry(brandId, authEmail(client))
let sqlstate: string | undefined
try {
await withUserContext(client, async (session) => {
await session.query(
`SELECT public.create_company_for_brand_signup($1, 'Self AB', 'aktiebolag', $2)`,
[client, brandId],
)
})
} catch (err) {
sqlstate = (err as { code?: string }).code
}
expect(sqlstate).toBe('42501')
})
})
+237
View File
@@ -0,0 +1,237 @@
import { randomUUID } from 'node:crypto'
import { describe, expect, it } from 'vitest'
import { getPool, withUserContext } from '@/tests/pg/setup'
import { insertAuthUser } from '@/tests/pg/fixtures'
// Tests for 20260826130200_brands.sql (white-label foundation, WL-01/WL-02):
// one brand per team, one unique domain per brand, hex/hostname/status CHECK
// gates, read-only visibility for the owning team's members, and no write
// policies for user sessions (brand rows are ops-managed via service role).
async function insertTeam(params: {
createdBy: string
kind?: 'personal' | 'byra'
name?: string
}): Promise<string> {
const id = randomUUID()
await getPool().query(
`INSERT INTO public.teams (id, name, created_by, kind)
VALUES ($1, $2, $3, $4)`,
[id, params.name ?? 'Byra Team', params.createdBy, params.kind ?? 'byra'],
)
await getPool().query(
`INSERT INTO public.team_members (team_id, user_id, role)
VALUES ($1, $2, 'owner')`,
[id, params.createdBy],
)
return id
}
async function insertBrand(params: {
teamId: string
domain?: string
appName?: string
brandColor?: string
chromeColor?: string | null
senderDomainStatus?: string
}): Promise<string> {
const id = randomUUID()
await getPool().query(
`INSERT INTO public.brands
(id, team_id, domain, app_name, brand_color, chrome_color, support_email, sender_domain_status)
VALUES ($1, $2, $3, $4, $5, $6, $7, COALESCE($8, 'unverified'))`,
[
id,
params.teamId,
params.domain ?? `${randomUUID().slice(0, 8)}.accounted.se`,
params.appName ?? 'Siffra',
params.brandColor ?? '#2563eb',
params.chromeColor ?? null,
'[email protected]',
params.senderDomainStatus ?? null,
],
)
return id
}
async function expectSqlstate(fn: () => Promise<unknown>, expected: string): Promise<void> {
let sqlstate: string | undefined
try {
await fn()
} catch (err) {
sqlstate = (err as { code?: string }).code
}
expect(sqlstate).toBe(expected)
}
describe('brands: shape and defaults', () => {
it('inserts a valid brand and reads defaults back', async () => {
const owner = await insertAuthUser()
const teamId = await insertTeam({ createdBy: owner })
const brandId = await insertBrand({ teamId, domain: 'app.siffra.se' })
const { rows } = await getPool().query<{
domain: string
font_key: string
sender_domain_status: string
chrome_color: string | null
}>(`SELECT domain, font_key, sender_domain_status, chrome_color FROM public.brands WHERE id = $1`, [
brandId,
])
expect(rows[0]).toEqual({
domain: 'app.siffra.se',
font_key: 'default',
sender_domain_status: 'unverified',
chrome_color: null,
})
})
it('deleting the team cascades the brand', async () => {
const owner = await insertAuthUser()
const teamId = await insertTeam({ createdBy: owner })
const brandId = await insertBrand({ teamId })
await getPool().query(`DELETE FROM public.teams WHERE id = $1`, [teamId])
const { rows } = await getPool().query(`SELECT 1 FROM public.brands WHERE id = $1`, [brandId])
expect(rows).toHaveLength(0)
})
})
describe('brands: uniqueness', () => {
it('enforces one brand per team (unique team_id, 23505)', async () => {
const owner = await insertAuthUser()
const teamId = await insertTeam({ createdBy: owner })
await insertBrand({ teamId })
await expectSqlstate(() => insertBrand({ teamId }), '23505')
})
it('enforces globally unique domains (23505)', async () => {
const ownerA = await insertAuthUser()
const ownerB = await insertAuthUser()
const teamA = await insertTeam({ createdBy: ownerA })
const teamB = await insertTeam({ createdBy: ownerB })
const domain = `${randomUUID().slice(0, 8)}.accounted.se`
await insertBrand({ teamId: teamA, domain })
await expectSqlstate(() => insertBrand({ teamId: teamB, domain }), '23505')
})
})
describe('brands: CHECK constraints', () => {
async function freshTeam(): Promise<string> {
return insertTeam({ createdBy: await insertAuthUser() })
}
it('rejects non-hex brand_color values (23514)', async () => {
for (const bad of ['blue', '#12345', '#12345g', '1a2b3c']) {
await expectSqlstate(
() => insertBrand({ teamId: '00000000-0000-0000-0000-000000000000', brandColor: bad }),
'23514',
)
}
})
it('accepts upper- and lowercase hex colors, rejects bad chrome_color (23514)', async () => {
const teamId = await freshTeam()
await insertBrand({ teamId, brandColor: '#AABBCC', chromeColor: '#0f1722' })
await expectSqlstate(
() =>
insertBrand({
teamId: '00000000-0000-0000-0000-000000000000',
chromeColor: 'dark',
}),
'23514',
)
})
it('rejects domains with scheme, slash, uppercase, or leading dot (23514)', async () => {
for (const bad of [
'https://app.siffra.se',
'app.siffra.se/login',
'App.Siffra.se',
'.siffra.se',
'app siffra.se',
'',
]) {
await expectSqlstate(
() => insertBrand({ teamId: '00000000-0000-0000-0000-000000000000', domain: bad }),
'23514',
)
}
})
it('accepts bare hostnames including umbrella subdomains', async () => {
const teamA = await freshTeam()
const teamB = await freshTeam()
await insertBrand({ teamId: teamA, domain: `siffra-${randomUUID().slice(0, 6)}.accounted.se` })
await insertBrand({ teamId: teamB, domain: `app.rodvik-${randomUUID().slice(0, 6)}.se` })
})
it('rejects unknown sender_domain_status (23514)', async () => {
await expectSqlstate(
() =>
insertBrand({
teamId: '00000000-0000-0000-0000-000000000000',
senderDomainStatus: 'maybe',
}),
'23514',
)
})
})
describe('brands: RLS', () => {
it('members of the owning team can read their brand; outsiders cannot', async () => {
const owner = await insertAuthUser()
const stranger = await insertAuthUser()
const teamId = await insertTeam({ createdBy: owner })
const brandId = await insertBrand({ teamId })
await withUserContext(owner, async (client) => {
const { rows } = await client.query(`SELECT id FROM public.brands WHERE id = $1`, [brandId])
expect(rows).toHaveLength(1)
})
await withUserContext(stranger, async (client) => {
const { rows } = await client.query(`SELECT id FROM public.brands WHERE id = $1`, [brandId])
expect(rows).toHaveLength(0)
})
})
it('has no write policies: user sessions cannot insert, update, or delete', async () => {
const owner = await insertAuthUser()
const teamId = await insertTeam({ createdBy: owner })
const brandId = await insertBrand({ teamId })
await withUserContext(owner, async (client) => {
// UPDATE and DELETE are silently filtered to zero rows (no policy).
const updated = await client.query(
`UPDATE public.brands SET app_name = 'Hijacked' WHERE id = $1`,
[brandId],
)
expect(updated.rowCount).toBe(0)
const deleted = await client.query(`DELETE FROM public.brands WHERE id = $1`, [brandId])
expect(deleted.rowCount).toBe(0)
})
// INSERT is rejected outright (42501: violates row-level security).
const otherOwner = await insertAuthUser()
const otherTeam = await insertTeam({ createdBy: otherOwner })
let sqlstate: string | undefined
try {
await withUserContext(otherOwner, async (client) => {
await client.query(
`INSERT INTO public.brands (team_id, domain, app_name, brand_color, support_email)
VALUES ($1, $2, 'Rogue', '#2563eb', '[email protected]')`,
[otherTeam, `rogue-${randomUUID().slice(0, 6)}.accounted.se`],
)
})
} catch (err) {
sqlstate = (err as { code?: string }).code
}
expect(sqlstate).toBe('42501')
})
})
+219
View File
@@ -0,0 +1,219 @@
import { randomUUID } from 'node:crypto'
import { describe, expect, it } from 'vitest'
import {
insertAuthUser,
insertCompany,
insertCompanyMember,
insertFiscalPeriod,
} from '@/tests/pg/fixtures'
import { getPool, withUserContext } from '@/tests/pg/setup'
/**
* Covers 20260702201000_bulk_book_transactions_dimensions (dimensions PR7):
*
* - p_new_entry lines may carry a dimensions bag {sie_dim_no: code}. The
* RPC stores it on journal_entry_lines.dimensions; cost_center/project
* derive from keys '1'/'6' (GENERATED columns since the PR9 cutover:
* the mirror assertions below now exercise the generation expression).
* - Bag normalization mirrors DimensionsBagSchema: non-canonical keys
* (leading zeros, non-numeric) and blank values are dropped; values are
* trimmed.
* - Lines without a bag store '{}' with NULL mirrors (column default
* semantics preserved).
* - A present-but-malformed bag (non-object) is rejected with
* BULK_BOOK_INVALID_DIMENSIONS before any insert.
*/
async function insertTransaction(params: {
userId: string
companyId: string
amount: number
date?: string
}): Promise<string> {
const id = randomUUID()
await getPool().query(
`INSERT INTO public.transactions
(id, user_id, company_id, date, description, amount, currency, category)
VALUES ($1, $2, $3, $4, 'Bank tx', $5, 'SEK', 'uncategorized')`,
[id, params.userId, params.companyId, params.date ?? '2026-06-05', params.amount],
)
return id
}
async function seedTenant() {
const userId = await insertAuthUser()
const companyId = await insertCompany({ createdBy: userId })
await insertCompanyMember({ companyId, userId, role: 'owner' })
await insertFiscalPeriod({
userId,
companyId,
periodStart: '2026-01-01',
periodEnd: '2026-12-31',
})
await getPool().query(
`INSERT INTO public.chart_of_accounts
(user_id, company_id, account_number, account_name, account_class, account_type, normal_balance, is_active)
SELECT $1, $2, n, name, cls, atype, nbal, true
FROM (VALUES
('1930', 'Bankkonto', 1, 'asset', 'debit'),
('2611', 'Utgående moms 25%', 2, 'liability', 'credit'),
('3001', 'Försäljning 25% moms', 3, 'revenue', 'credit')
) AS t(n, name, cls, atype, nbal)`,
[userId, companyId],
)
return { userId, companyId }
}
interface RpcResult {
ok: boolean
code?: string
journal_entry_id?: string
}
interface LineRow {
account_number: string
dimensions: Record<string, string>
cost_center: string | null
project: string | null
}
/**
* Run the RPC and read back the created lines INSIDE the same
* withUserContext transaction: the harness rolls the context back after
* the callback, so any assertion data must be captured in here.
*/
async function callBulkBook(
userId: string,
companyId: string,
txIds: string[],
newEntry: unknown,
): Promise<{ result: RpcResult; lines: LineRow[]; linkCount: number }> {
return withUserContext(userId, async (client) => {
const r = await client.query<{ bulk_book_transactions: RpcResult }>(
`SELECT bulk_book_transactions($1::uuid[], $2, $3::jsonb, $4)`,
[txIds, null, JSON.stringify(newEntry), companyId],
)
const result = r.rows[0]!.bulk_book_transactions
let lines: LineRow[] = []
if (result.journal_entry_id) {
const lr = await client.query<LineRow>(
`SELECT account_number, dimensions, cost_center, project
FROM public.journal_entry_lines
WHERE journal_entry_id = $1 ORDER BY sort_order`,
[result.journal_entry_id],
)
lines = lr.rows
}
const links = await client.query(
`SELECT 1 FROM public.transaction_voucher_links WHERE transaction_id = ANY($1::uuid[])`,
[txIds],
)
return { result, lines, linkCount: links.rowCount ?? 0 }
})
}
describe('bulk_book_transactions: line dimensions (PR7)', () => {
it('stores the bag and derives cost_center/project mirrors from keys 1/6', async () => {
const { userId, companyId } = await seedTenant()
const tx = await insertTransaction({ userId, companyId, amount: 500 })
const { result, lines } = await callBulkBook(userId, companyId, [tx], {
description: 'Samlingsverifikation med dimensioner',
lines: [
{ account_number: '1930', debit_amount: 500, credit_amount: 0, currency: 'SEK' },
{
account_number: '3001', debit_amount: 0, credit_amount: 400, currency: 'SEK',
dimensions: { '1': 'KS01', '6': 'P001' },
},
{
account_number: '2611', debit_amount: 0, credit_amount: 100, currency: 'SEK',
dimensions: { '6': 'P001' },
},
],
})
expect(result.ok).toBe(true)
expect(lines).toHaveLength(3)
const bank = lines.find((l) => l.account_number === '1930')!
const revenue = lines.find((l) => l.account_number === '3001')!
const vat = lines.find((l) => l.account_number === '2611')!
expect(bank.dimensions).toEqual({})
expect(bank.cost_center).toBeNull()
expect(bank.project).toBeNull()
expect(revenue.dimensions).toEqual({ '1': 'KS01', '6': 'P001' })
expect(revenue.cost_center).toBe('KS01')
expect(revenue.project).toBe('P001')
expect(vat.dimensions).toEqual({ '6': 'P001' })
expect(vat.cost_center).toBeNull()
expect(vat.project).toBe('P001')
})
it('normalizes the bag: drops non-canonical keys and blank values, trims values', async () => {
const { userId, companyId } = await seedTenant()
const tx = await insertTransaction({ userId, companyId, amount: 250 })
const { result, lines } = await callBulkBook(userId, companyId, [tx], {
description: 'Normaliseringstest',
lines: [
{ account_number: '1930', debit_amount: 250, credit_amount: 0, currency: 'SEK' },
{
account_number: '3001', debit_amount: 0, credit_amount: 250, currency: 'SEK',
// '01' (leading zero), 'abc' (non-numeric) and blank values must be
// dropped; ' KS02 ' must be stored trimmed.
dimensions: { '01': 'GHOST', abc: 'X', '7': ' ', '1': ' KS02 ' },
},
],
})
expect(result.ok).toBe(true)
expect(lines).toHaveLength(2)
const revenue = lines.find((l) => l.account_number === '3001')!
expect(revenue.dimensions).toEqual({ '1': 'KS02' })
expect(revenue.cost_center).toBe('KS02')
expect(revenue.project).toBeNull()
})
it('rejects a present-but-malformed bag with BULK_BOOK_INVALID_DIMENSIONS', async () => {
const { userId, companyId } = await seedTenant()
const tx = await insertTransaction({ userId, companyId, amount: 100 })
const { result, linkCount } = await callBulkBook(userId, companyId, [tx], {
description: 'Trasig dimensionspayload',
lines: [
{ account_number: '1930', debit_amount: 100, credit_amount: 0, currency: 'SEK' },
{
account_number: '3001', debit_amount: 0, credit_amount: 100, currency: 'SEK',
dimensions: 'not-an-object',
},
],
})
expect(result.ok).toBe(false)
expect(result.code).toBe('BULK_BOOK_INVALID_DIMENSIONS')
// Nothing booked: the tx must remain unlinked.
expect(linkCount).toBe(0)
})
it('keeps dimension-less bookings byte-identical to before (default bag + NULL mirrors)', async () => {
const { userId, companyId } = await seedTenant()
const tx = await insertTransaction({ userId, companyId, amount: 300 })
const { result, lines } = await callBulkBook(userId, companyId, [tx], {
description: 'Utan dimensioner',
lines: [
{ account_number: '1930', debit_amount: 300, credit_amount: 0, currency: 'SEK' },
{ account_number: '3001', debit_amount: 0, credit_amount: 300, currency: 'SEK' },
],
})
expect(result.ok).toBe(true)
expect(lines).toHaveLength(2)
for (const line of lines) {
expect(line.dimensions).toEqual({})
expect(line.cost_center).toBeNull()
expect(line.project).toBeNull()
}
})
})
@@ -0,0 +1,240 @@
import { randomUUID } from 'node:crypto'
import { describe, expect, it } from 'vitest'
import {
insertAuthUser,
insertCompany,
insertCompanyMember,
insertFiscalPeriod,
} from '@/tests/pg/fixtures'
import { getPool, withUserContext } from '@/tests/pg/setup'
/**
* Covers 20260726100000_bulk_book_transactions_currency_guard:
*
* bulk_book_transactions used to sum v_tx.amount across the selection
* without looking at v_tx.currency, so a SEK + EUR batch produced a single
* scalar (100 EUR + 100 SEK = 200) and a samlingsverifikat stating an
* amount that matched no affärshändelse. BFL 4 kap 6 § requires one
* redovisningsvaluta; BFL 5 kap 7 § requires the verifikat's belopp to be
* the real one. The guard now refuses with BULK_BOOK_MIXED_CURRENCY.
*
* The SQL guard matters independently of the HTTP route: `authenticated`
* holds EXECUTE on this RPC, so a browser session can call it directly over
* PostgREST, and lib/pending-operations/commit.ts passes tx_ids straight
* through.
*
* A HOMOGENEOUS non-SEK batch is refused too (BULK_BOOK_FOREIGN_CURRENCY):
* journal_entry_lines.debit_amount / credit_amount are ALWAYS kronor, and the
* RPC has no exchange rate, so two EUR transactions of 100 + 200 would post a
* verifikat whose 300 reads as kronor in balansräkning, moms and SIE export.
*
* Cases:
* - create-new path refuses a mixed-currency selection
* - link-existing path refuses the same selection
* - NULL currency is read as the column default 'SEK' and stays bookable
* - a homogeneous non-SEK batch is refused and nothing is written
*/
async function insertTransaction(params: {
userId: string
companyId: string
amount: number
date?: string
currency?: string | null
}): Promise<string> {
const id = randomUUID()
await getPool().query(
`INSERT INTO public.transactions
(id, user_id, company_id, date, description, amount, currency, category)
VALUES ($1, $2, $3, $4, 'Bank tx', $5, $6, 'uncategorized')`,
[
id,
params.userId,
params.companyId,
params.date ?? '2026-06-05',
params.amount,
params.currency === undefined ? 'SEK' : params.currency,
],
)
return id
}
async function seedTenant() {
const userId = await insertAuthUser()
const companyId = await insertCompany({ createdBy: userId })
await insertCompanyMember({ companyId, userId, role: 'owner' })
const fiscalPeriodId = await insertFiscalPeriod({
userId,
companyId,
periodStart: '2026-01-01',
periodEnd: '2026-12-31',
})
await getPool().query(
`INSERT INTO public.chart_of_accounts
(user_id, company_id, account_number, account_name, account_class, account_type, normal_balance, is_active)
SELECT $1, $2, n, name, cls, atype, nbal, true
FROM (VALUES
('1930', 'Bankkonto', 1, 'asset', 'debit'),
('2611', 'Utgående moms 25%', 2, 'liability', 'credit'),
('3001', 'Försäljning 25% moms', 3, 'revenue', 'credit')
) AS t(n, name, cls, atype, nbal)`,
[userId, companyId],
)
return { userId, companyId, fiscalPeriodId }
}
interface RpcResult {
ok: boolean
code?: string
details?: { currencies?: string[]; currency?: string }
mode?: 'link_existing' | 'create_new'
journal_entry_id?: string
linked_tx_count?: number
tx_sum?: number
}
describe('bulk_book_transactions: currency homogeneity (BFL 4 kap 6 §)', () => {
it('refuses a mixed-currency selection on the create-new path', async () => {
const { userId, companyId } = await seedTenant()
const sekTx = await insertTransaction({ userId, companyId, amount: 100, currency: 'SEK' })
const eurTx = await insertTransaction({ userId, companyId, amount: 100, currency: 'EUR' })
// The caller-built lines look internally consistent against the naive
// scalar sum (200) the old body computed: that is exactly the booking
// the guard must stop.
const newEntry = {
description: 'Samlingsverifikation 2026-06-05',
lines: [
{ account_number: '1930', debit_amount: 200, credit_amount: 0, currency: 'SEK' },
{ account_number: '3001', debit_amount: 0, credit_amount: 200, currency: 'SEK' },
],
}
await withUserContext(userId, async (client) => {
const r = await client.query<{ bulk_book_transactions: RpcResult }>(
`SELECT bulk_book_transactions($1::uuid[], $2, $3::jsonb, $4)`,
[[sekTx, eurTx], null, JSON.stringify(newEntry), companyId],
)
const result = r.rows[0]!.bulk_book_transactions
expect(result.ok).toBe(false)
expect(result.code).toBe('BULK_BOOK_MIXED_CURRENCY')
expect(result.details?.currencies).toEqual(expect.arrayContaining(['SEK', 'EUR']))
// Nothing was posted and nothing was linked.
const jes = await client.query(
`SELECT id FROM public.journal_entries WHERE company_id = $1`,
[companyId],
)
expect(jes.rows).toHaveLength(0)
const links = await client.query(
`SELECT transaction_id FROM public.transaction_voucher_links WHERE company_id = $1`,
[companyId],
)
expect(links.rows).toHaveLength(0)
})
})
it('refuses a mixed-currency selection on the link-existing path', async () => {
const { userId, companyId, fiscalPeriodId } = await seedTenant()
const sekTx = await insertTransaction({ userId, companyId, amount: 100, currency: 'SEK' })
const eurTx = await insertTransaction({ userId, companyId, amount: 100, currency: 'EUR' })
// Posted verifikat whose bank net (+200) matches the naive scalar sum,
// so only the currency guard can reject this.
const jeId = randomUUID()
await getPool().query(
`INSERT INTO public.journal_entries
(id, user_id, company_id, fiscal_period_id, voucher_number, voucher_series,
entry_date, description, source_type, status)
VALUES ($1, $2, $3, $4, 1, 'A', '2026-06-05', 'Manual dagssumma', 'manual', 'draft')`,
[jeId, userId, companyId, fiscalPeriodId],
)
await getPool().query(
`INSERT INTO public.journal_entry_lines (journal_entry_id, account_number, debit_amount, credit_amount)
VALUES ($1, '1930', 200, 0), ($1, '3001', 0, 200)`,
[jeId],
)
await getPool().query(`UPDATE public.journal_entries SET status = 'posted' WHERE id = $1`, [jeId])
await withUserContext(userId, async (client) => {
const r = await client.query<{ bulk_book_transactions: RpcResult }>(
`SELECT bulk_book_transactions($1::uuid[], $2, $3, $4)`,
[[sekTx, eurTx], jeId, null, companyId],
)
const result = r.rows[0]!.bulk_book_transactions
expect(result.ok).toBe(false)
expect(result.code).toBe('BULK_BOOK_MIXED_CURRENCY')
const links = await client.query(
`SELECT transaction_id FROM public.transaction_voucher_links WHERE journal_entry_id = $1`,
[jeId],
)
expect(links.rows).toHaveLength(0)
})
})
it('treats NULL currency as the column default SEK and still books', async () => {
const { userId, companyId } = await seedTenant()
const legacyTx = await insertTransaction({ userId, companyId, amount: 100, currency: null })
const sekTx = await insertTransaction({ userId, companyId, amount: 200, currency: 'SEK' })
const newEntry = {
description: 'Samlingsverifikation 2026-06-05',
lines: [
{ account_number: '1930', debit_amount: 300, credit_amount: 0, currency: 'SEK' },
{ account_number: '3001', debit_amount: 0, credit_amount: 300, currency: 'SEK' },
],
}
await withUserContext(userId, async (client) => {
const r = await client.query<{ bulk_book_transactions: RpcResult }>(
`SELECT bulk_book_transactions($1::uuid[], $2, $3::jsonb, $4)`,
[[legacyTx, sekTx], null, JSON.stringify(newEntry), companyId],
)
const result = r.rows[0]!.bulk_book_transactions
expect(result.ok).toBe(true)
expect(result.linked_tx_count).toBe(2)
expect(result.tx_sum).toBe(300)
})
})
it('refuses a homogeneous non-SEK selection (the ledger columns are always kronor)', async () => {
const { userId, companyId } = await seedTenant()
const eur1 = await insertTransaction({ userId, companyId, amount: 100, currency: 'EUR' })
const eur2 = await insertTransaction({ userId, companyId, amount: 200, currency: 'EUR' })
// The old body accepted this batch and wrote 300 into the always-SEK
// debit/credit columns: a verifikat read as 300 kronor by balansräkning,
// moms and SIE while the affärshändelse was 300 euro.
const newEntry = {
description: 'Samlingsverifikation EUR 2026-06-05',
lines: [
{ account_number: '1930', debit_amount: 300, credit_amount: 0, currency: 'EUR' },
{ account_number: '3001', debit_amount: 0, credit_amount: 300, currency: 'EUR' },
],
}
await withUserContext(userId, async (client) => {
const r = await client.query<{ bulk_book_transactions: RpcResult }>(
`SELECT bulk_book_transactions($1::uuid[], $2, $3::jsonb, $4)`,
[[eur1, eur2], null, JSON.stringify(newEntry), companyId],
)
const result = r.rows[0]!.bulk_book_transactions
expect(result.ok).toBe(false)
expect(result.code).toBe('BULK_BOOK_FOREIGN_CURRENCY')
expect(result.details?.currency).toBe('EUR')
// Nothing was posted and nothing was linked.
const jes = await client.query(
`SELECT id FROM public.journal_entries WHERE company_id = $1`,
[companyId],
)
expect(jes.rows).toHaveLength(0)
const links = await client.query(
`SELECT transaction_id FROM public.transaction_voucher_links WHERE company_id = $1`,
[companyId],
)
expect(links.rows).toHaveLength(0)
})
})
})

Some files were not shown because too many files have changed in this diff Show More