Add/bokslut (#718)

* feat(arcim-migration): Briox provider with SIE-over-API import

- Briox auth via account ID + application token (no app-level
  credentials); both tokens rotate on refresh and are persisted
- New sie-fetcher pulls the general ledger as SIE through the
  provider API for Fortnox, Briox and Bjorn Lunden
- Wizard stops on a failed SIE import and surfaces the real errors
  instead of proceeding to the misleading migrate-guard message
- PROVIDER_SIE_ONLY_FORTNOX renamed to PROVIDER_SIE_NOT_SUPPORTED;
  new PROVIDER_TOKEN_INVALID for rejected provider credentials

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat(bookkeeping): per-line accruals (periodisering) on invoices and supplier invoices

Defer revenue/costs per invoice line to 29xx/17xx interim accounts with
automatic monthly dissolution (nightly cron + catch-up at registration),
schedule cancellation on credit, year-end auto-detect exclusion for
already-scheduled invoices, invoice-inbox service-period extraction for
prefill, and an MCP tool to list schedules.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat(bokslut): iXBRL arsredovisning generation and Bolagsverket digital filing

Generate the annual report as iXBRL from a generated taxonomy registry
(K2 element lists, taxonomy:generate/check scripts + CI guard), expose it
via the fiscal-period API, and add the bolagsverket extension for digital
submission to eget utrymme with webhook-driven status tracking
(submissions table + pg tests, lifecycle events, year-end wizard UI).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* test(mcp): raise origin-guard test timeout to 20s

The dynamic import pulls in the full server module; the parse alone
flirts with the 5s default under full-suite parallel load.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* Add new scripts and documentation for K2 AB taxonomy generation and validation

- Introduced `generate-taxonomy-registry.ts` to automate the generation of the iXBRL taxonomy concept registry from official element lists and tuple models.
- Added `validate-ixbrl.mjs` for validating generated iXBRL reports against the official taxonomy package using Arelle.
- Included new documentation files:
  - `k2-ab-arsredovisning-elementlista-2024-09-12_rev20250312_sv.xlsx`
  - `tuple-innehallsmodell-arsredovisning-k2-2024-09-12.xlsx`
  - `taxonomi-paket-2024-09-12_rev20250312.zip`

* Add tests for bookkeeping accruals dissolution and supplier invoices

- Implement tests for the POST /api/bookkeeping/accruals/[id]/dissolve route, covering success and error scenarios.
- Add tests for the DELETE /api/supplier-invoices/[id] route, including authentication checks and validation of invoice deletion conditions.
- Introduce tests for the Arcim migration provider client, ensuring token handling and error classification.
- Create tests for the Bolagsverket extension, validating submission role enforcement and environment settings.
- Add Zod schemas for Bolagsverket response payloads to ensure proper validation.
- Implement tests for MCP server's list accrual schedules, confirming registration and scope mapping.
- Add consistency tests for IXBRL document generation, ensuring duplicate facts and XML escaping are handled correctly.
- Introduce typed domain errors for accrual schedules to improve error handling in the service.
- Add tests for resolving consent with Briox token refresh concurrency, ensuring proper token management and error handling.

* fix(tests): update payload size guard comments to reflect recent changes in tool descriptions and ceiling adjustments

* fix(gitattributes): mark generated JSON files in bokslut taxonomy as linguist-generated

* feat(migrations): add backfill for invoices.journal_entry_id and fallback for next_voucher_number user_id

* feat(bokslut): enhance compliance and financial processing features with new submission details and security measures

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
Mattsson
2026-06-12 16:35:30 +02:00
committed by GitHub
co-authored by Claude Fable 5
parent 8e8b63a200
commit db8983ba9e
131 changed files with 33796 additions and 340 deletions
+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()
})
})
@@ -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)
})
})
@@ -6,7 +6,7 @@ import { seedCompany, insertDraftJournalEntry } from '@/tests/pg/fixtures'
import { getPool } from '@/tests/pg/setup'
/**
* pg-real coverage for 20260622120000_invoices_journal_entry_id_backfill.sql.
* pg-real coverage for 20260622121000_invoices_journal_entry_id_backfill.sql.
*
* invoices.journal_entry_id means "the registration verifikat that booked the
* invoice at issuance" — payment flows route on it (set → clear 1510; NULL →
@@ -25,7 +25,7 @@ import { getPool } from '@/tests/pg/setup'
// Run the real migration SQL so the test exercises exactly what ships.
const BACKFILL_SQL = readFileSync(
join(process.cwd(), 'supabase/migrations/20260622120000_invoices_journal_entry_id_backfill.sql'),
join(process.cwd(), 'supabase/migrations/20260622121000_invoices_journal_entry_id_backfill.sql'),
'utf8',
)
async function runBackfill(): Promise<void> {