* feat(reports): log behandlingsregler changes and program versions (BFNAR 2013:2 p. 9.16) Part 3 of the behandlingshistorik series (#1787 report, #1790 PDF). BFNAR 2013:2 punkt 9.16 second paragraph requires the behandlingshistorik to record "forandringar i bokforingssystemet som paverkar bokforingsposternas behandling samt nar dessa forandringar infordes", and BFN's commentary names behandlingsregler (automatkonteringar, fasta procentsatser) and new program versions as the examples. Until now both changed without a trace. Audit triggers on the behandlingsregler tables and the import logs: mapping_rules, booking_template_library, categorization_templates, salary_payroll_config, sie_imports, bank_file_imports. categorization_templates learns on every booking (occurrence_count, confidence, last_seen_date), so those telemetry-only updates are excluded by a WHEN clause the same way the api_keys request counters are (20260721115701): only real rule changes are logged. Measured against prod that is roughly 3 800 new audit rows a month against an audit_log already taking 371 688, so about +1 %. app_releases is an append-only log of program versions seen in production, written by the runtime the first time a build answers a request. Vercel exposes no build hook we can trust to write the row, so /api/version records it inside after(): the handler returns synchronously and a floating promise could be frozen before the insert lands, which is how a version log ends up silently empty. The service client is constructed lazily so the constantly polled public probe pays nothing once the module guard is set. Program versions are rolled up per Swedish calendar day in the report. main takes ~570 merges a month, so one event per version would be on the order of 7 000 a fiscal year: enough to trip the PDF's own 4 000-event guard and bury the ~400 events a real company's year contains. The statutory unit is the date, and the same sentence qualifies the requirement to changes that affect processing, which a deploy list cannot distinguish anyway. app_releases keeps the per-version truth for anyone who needs to go deeper. AuditLogEntry.user_id becomes string | null. The column is nullable and write_audit_log() falls back to auth.uid(), which is NULL for a service-role or global write; the company-less salary_payroll_config rows are the first that routinely hit it, and the read model already coded for it. Also restores the point citations the 2026-07-27 pass removed while the chapter was unverified: it is kapitel 9, not kapitel 8 (which is arkivering), verified against BFN's consolidated text. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01L3P2hr19PhQuCoTSGoegcY * test(pg): fix two fixture bugs in the behandlingshistorik trigger tests pg-real caught both, and neither is in the migration: the inserts fail before the trigger is reached. mapping_rules.rule_type is constrained to mcc_code / merchant_name / description_pattern / amount_threshold / combined; the test used 'merchant'. booking_template_library's btl_insert policy requires current_user_can_write() and company_id = current_active_company_id(), so the authenticated insert needs a company_members row and a user_preferences.active_company_id, the same setup booking-template-hidden.pg.test.ts uses. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01L3P2hr19PhQuCoTSGoegcY * test(pg): assert the booking-template audit row inside the user transaction withUserContext always rolls back, so the audit row the trigger writes is gone before an outside connection can see it. The trigger fires in the same transaction as the write, so the assertion belongs there too. The other cases in this file write on the pool (autocommit) and are unaffected. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01L3P2hr19PhQuCoTSGoegcY * fix(reports): name every build id in the per-day program-version entry Raised by the compliance review on #2097: the roll-up listed five ids and a count, which leaves an auditor unable to reconstruct which versions ran that day. app_releases keeps the full record, but the report is the surface anyone actually reads. A day is bounded by the deploy rate (~19), so the full list stays one readable cell. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01L3P2hr19PhQuCoTSGoegcY --------- Co-authored-by: Jakob Wennberg <311770904+jakobwennberg-oss@users.noreply.github.com> Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
114 lines
4.8 KiB
TypeScript
114 lines
4.8 KiB
TypeScript
import { describe, it, expect, beforeEach, vi } from 'vitest'
|
|
import {
|
|
fetchAppReleases,
|
|
recordAppRelease,
|
|
resetAppReleaseGuardForTests,
|
|
type AppReleaseRow,
|
|
} from '../app-releases'
|
|
|
|
/**
|
|
* Program version log (BFNAR 2013:2 p. 9.16: "nya programversioner"). The
|
|
* recorder sits on the public /api/version probe, so the properties that
|
|
* matter are the ones that keep a hot public route cheap and unbreakable:
|
|
* it never throws, it constructs nothing once the guard is set, and a failed
|
|
* write is retried rather than remembered as done.
|
|
*/
|
|
|
|
function upsertSpy(result: { error: { message: string } | null } = { error: null }) {
|
|
const upsert = vi.fn().mockResolvedValue(result)
|
|
return { upsert, client: { from: vi.fn().mockReturnValue({ upsert }) } }
|
|
}
|
|
|
|
describe('recordAppRelease', () => {
|
|
beforeEach(() => {
|
|
vi.clearAllMocks()
|
|
resetAppReleaseGuardForTests()
|
|
})
|
|
|
|
it('records the running version, truncated to the 12-character build id', async () => {
|
|
const { upsert, client } = upsertSpy()
|
|
await expect(recordAppRelease(client, 'b643e6ce6d4448ccb10b985b1ff3872a77f0dd63')).resolves.toBe('b643e6ce6d44')
|
|
expect(client.from).toHaveBeenCalledWith('app_releases')
|
|
expect(upsert).toHaveBeenCalledWith(
|
|
{ version: 'b643e6ce6d44', source: 'runtime' },
|
|
{ onConflict: 'version', ignoreDuplicates: true },
|
|
)
|
|
})
|
|
|
|
it('writes once per instance and version, then stops touching the database', async () => {
|
|
const { upsert, client } = upsertSpy()
|
|
await recordAppRelease(client, 'aaaaaaaaaaaa')
|
|
await recordAppRelease(client, 'aaaaaaaaaaaa')
|
|
await recordAppRelease(client, 'aaaaaaaaaaaa')
|
|
expect(upsert).toHaveBeenCalledTimes(1)
|
|
|
|
// A different build is a different row: the guard is per version.
|
|
await recordAppRelease(client, 'bbbbbbbbbbbb')
|
|
expect(upsert).toHaveBeenCalledTimes(2)
|
|
})
|
|
|
|
it('never constructs the service client once the guard is set', async () => {
|
|
const { client } = upsertSpy()
|
|
const factory = vi.fn().mockReturnValue(client)
|
|
await recordAppRelease(factory, 'cccccccccccc')
|
|
expect(factory).toHaveBeenCalledTimes(1)
|
|
await recordAppRelease(factory, 'cccccccccccc')
|
|
// The point of the factory form: /api/version is polled constantly and
|
|
// must not build a Supabase client per probe.
|
|
expect(factory).toHaveBeenCalledTimes(1)
|
|
})
|
|
|
|
it('swallows a throwing client factory: a missing service key must not break the version probe', async () => {
|
|
const factory = vi.fn(() => {
|
|
throw new Error('SUPABASE_SERVICE_ROLE_KEY is not set')
|
|
})
|
|
await expect(recordAppRelease(factory, 'dddddddddddd')).resolves.toBe('dddddddddddd')
|
|
})
|
|
|
|
it('retries on the next request when the write failed, rather than remembering it as done', async () => {
|
|
const failing = upsertSpy({ error: { message: 'permission denied' } })
|
|
await recordAppRelease(failing.client, 'eeeeeeeeeeee')
|
|
await recordAppRelease(failing.client, 'eeeeeeeeeeee')
|
|
expect(failing.upsert).toHaveBeenCalledTimes(2)
|
|
})
|
|
|
|
it('does nothing when the build id is unknown (local dev, self-hosted without VERCEL_GIT_COMMIT_SHA)', async () => {
|
|
const { upsert, client } = upsertSpy()
|
|
await expect(recordAppRelease(client, null)).resolves.toBeNull()
|
|
await expect(recordAppRelease(client, '')).resolves.toBeNull()
|
|
expect(upsert).not.toHaveBeenCalled()
|
|
})
|
|
})
|
|
|
|
describe('fetchAppReleases', () => {
|
|
const rows: AppReleaseRow[] = [
|
|
{ version: 'aaaaaaaaaaaa', first_seen_at: '2026-03-01T08:00:00.000Z', source: 'runtime' },
|
|
]
|
|
|
|
function selectClient(result: { data: AppReleaseRow[] | null; error: { message: string } | null }) {
|
|
const chain = {
|
|
select: vi.fn().mockReturnThis(),
|
|
gte: vi.fn().mockReturnThis(),
|
|
lte: vi.fn().mockReturnThis(),
|
|
order: vi.fn().mockResolvedValue(result),
|
|
}
|
|
return { chain, client: { from: vi.fn().mockReturnValue(chain) } }
|
|
}
|
|
|
|
it('windows on first_seen_at and returns the versions oldest first', async () => {
|
|
const { chain, client } = selectClient({ data: rows, error: null })
|
|
const out = await fetchAppReleases(client, { fromTs: '2026-01-01T00:00:00.000Z', toTs: '2026-12-31T23:59:59.999Z' })
|
|
expect(out).toEqual(rows)
|
|
expect(chain.gte).toHaveBeenCalledWith('first_seen_at', '2026-01-01T00:00:00.000Z')
|
|
expect(chain.lte).toHaveBeenCalledWith('first_seen_at', '2026-12-31T23:59:59.999Z')
|
|
expect(chain.order).toHaveBeenCalledWith('first_seen_at', { ascending: true })
|
|
})
|
|
|
|
it('throws on a read failure: a report that silently drops the version log is not a behandlingshistorik', async () => {
|
|
const { client } = selectClient({ data: null, error: { message: 'relation does not exist' } })
|
|
await expect(
|
|
fetchAppReleases(client, { fromTs: '2026-01-01T00:00:00.000Z', toTs: '2026-12-31T23:59:59.999Z' }),
|
|
).rejects.toThrow('Failed to fetch app releases: relation does not exist')
|
|
})
|
|
})
|