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
+64
View File
@@ -0,0 +1,64 @@
import { describe, it, expect } from 'vitest'
import { mapWithConcurrency } from '@/lib/concurrency'
describe('mapWithConcurrency', () => {
it('preserves input order in the result', async () => {
const items = [50, 10, 30, 0, 20]
const result = await mapWithConcurrency(items, 3, async (ms) => {
await new Promise((r) => setTimeout(r, ms))
return ms * 2
})
expect(result).toEqual([100, 20, 60, 0, 40])
})
it('never runs more than `limit` workers at once', async () => {
let inFlight = 0
let peak = 0
await mapWithConcurrency(Array.from({ length: 20 }, (_, i) => i), 4, async () => {
inFlight++
peak = Math.max(peak, inFlight)
await new Promise((r) => setTimeout(r, 5))
inFlight--
})
expect(peak).toBeLessThanOrEqual(4)
expect(peak).toBeGreaterThan(1)
})
it('processes every item exactly once', async () => {
const seen: number[] = []
await mapWithConcurrency(Array.from({ length: 13 }, (_, i) => i), 5, async (i) => {
seen.push(i)
})
expect(seen.slice().sort((a, b) => a - b)).toEqual(Array.from({ length: 13 }, (_, i) => i))
})
it('handles an empty input', async () => {
expect(await mapWithConcurrency([], 4, async () => 1)).toEqual([])
})
it('caps the pool at the item count', async () => {
// 2 items with limit 10 must not spin up idle workers that read past the
// end; the result stays correct.
expect(await mapWithConcurrency([1, 2], 10, async (n) => n + 1)).toEqual([2, 3])
})
it('passes the item index to the worker', async () => {
const idx = await mapWithConcurrency(['a', 'b', 'c'], 2, async (_item, i) => i)
expect(idx).toEqual([0, 1, 2])
})
it('rejects the whole map when a worker rejects (Promise.all semantics)', async () => {
await expect(
mapWithConcurrency([1, 2, 3], 2, async (n) => {
if (n === 2) throw new Error('boom')
return n
}),
).rejects.toThrow('boom')
})
it('rejects a non-positive limit instead of hanging', async () => {
await expect(mapWithConcurrency([1], 0, async (n) => n)).rejects.toThrow(
'limit must be >= 1',
)
})
})
+271
View File
@@ -0,0 +1,271 @@
/**
* Cron failure reporting (lib/auth/cron.ts).
*
* Lives here rather than next to lib/auth/__tests__/cron.test.ts, which covers
* the constant-time secret comparison and is left untouched.
*/
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
import {
CRON_REPORT_THROTTLE_MS,
reportCronFailure,
reportCronSuccess,
resetCronReportingState,
shouldReportCronFailure,
verifyCronSecret,
} from '../auth/cron'
import {
registerObservabilitySink,
resetObservabilitySink,
type ObservabilityContext,
type ObservabilityLevel,
} from '../observability/sink'
interface Captured {
kind: 'exception' | 'message'
error?: unknown
message?: string
level?: ObservabilityLevel
context: ObservabilityContext
}
let events: Captured[] = []
beforeEach(() => {
events = []
resetCronReportingState()
vi.unstubAllEnvs()
registerObservabilitySink({
name: 'test',
captureException(error, context) {
events.push({ kind: 'exception', error, context })
},
captureMessage(message, level, context) {
events.push({ kind: 'message', message, level, context })
},
async flush() {
return true
},
})
})
afterEach(() => {
resetObservabilitySink()
resetCronReportingState()
vi.unstubAllEnvs()
})
describe('shouldReportCronFailure', () => {
it('reports the first failure by default', () => {
expect(shouldReportCronFailure({ consecutiveFailures: 1, lastReportAt: null })).toBe(true)
})
it('waits for the threshold when one is given', () => {
expect(
shouldReportCronFailure({ consecutiveFailures: 2, lastReportAt: null, threshold: 3 }),
).toBe(false)
expect(
shouldReportCronFailure({ consecutiveFailures: 3, lastReportAt: null, threshold: 3 }),
).toBe(true)
})
it('throttles repeats inside the window and allows them after it', () => {
const now = 1_000_000_000
expect(
shouldReportCronFailure({ consecutiveFailures: 5, lastReportAt: now - 1000, now }),
).toBe(false)
expect(
shouldReportCronFailure({
consecutiveFailures: 5,
lastReportAt: now - CRON_REPORT_THROTTLE_MS - 1,
now,
}),
).toBe(true)
})
})
describe('reportCronFailure', () => {
it('sends a message event with cron context when there is no error object', () => {
reportCronFailure({ operation: 'cron.invoice-reminders', status: 500, reason: 'timeout' })
expect(events).toHaveLength(1)
expect(events[0].kind).toBe('message')
expect(events[0].level).toBe('error')
expect(events[0].context).toMatchObject({
cron: true,
alert: true,
operation: 'cron.invoice-reminders',
cronKind: 'run',
status: 500,
reason: 'timeout',
consecutiveFailures: 1,
})
})
it('sends an exception event when an error is supplied', () => {
reportCronFailure({
operation: 'cron.documents-verify',
error: new Error('storage unreachable'),
itemsTotal: 10,
itemsFailed: 4,
})
expect(events[0].kind).toBe('exception')
expect(events[0].error).toMatchObject({ name: 'Error', message: 'storage unreachable' })
expect(events[0].context).toMatchObject({ itemsTotal: 10, itemsFailed: 4 })
})
it('throttles a storm of failures from one operation into a single event', () => {
for (let i = 0; i < 500; i++) {
reportCronFailure({ operation: 'cron.accruals', kind: 'item', reason: 'boom' })
}
expect(events).toHaveLength(1)
})
it('keeps different operations and kinds on separate throttles', () => {
reportCronFailure({ operation: 'cron.a', kind: 'run' })
reportCronFailure({ operation: 'cron.a', kind: 'auth' })
reportCronFailure({ operation: 'cron.b', kind: 'run' })
expect(events).toHaveLength(3)
})
it('reports again once the throttle window has passed, with a growing streak', () => {
const t0 = 1_000_000_000
reportCronFailure({ operation: 'cron.a', now: t0 })
reportCronFailure({ operation: 'cron.a', now: t0 + 1000 })
reportCronFailure({ operation: 'cron.a', now: t0 + CRON_REPORT_THROTTLE_MS + 1 })
expect(events).toHaveLength(2)
expect(events[0].context.consecutiveFailures).toBe(1)
expect(events[1].context.consecutiveFailures).toBe(3)
})
it('reportCronSuccess clears the streak so the next outage reports fresh', () => {
const t0 = 1_000_000_000
reportCronFailure({ operation: 'cron.a', now: t0 })
reportCronSuccess('cron.a')
reportCronFailure({ operation: 'cron.a', now: t0 + 1000 })
expect(events).toHaveLength(2)
expect(events[1].context.consecutiveFailures).toBe(1)
})
it('evicts only the oldest tracked key at capacity, keeping live throttles intact', () => {
const t0 = 1_000_000_000
// Fill the map to MAX_TRACKED_CRON_KEYS (200 in lib/auth/cron.ts).
for (let i = 0; i < 200; i++) {
reportCronFailure({ operation: `cron.op-${i}`, now: t0 })
}
events.length = 0
// A new key at capacity used to clear() the whole map; now it evicts the
// single oldest entry (cron.op-0).
reportCronFailure({ operation: 'cron.new', now: t0 + 1 })
expect(events).toHaveLength(1)
// cron.op-199's throttle survived: an in-progress storm stays damped
// instead of re-reporting immediately after the map was cleared.
reportCronFailure({ operation: 'cron.op-199', now: t0 + 2 })
expect(events).toHaveLength(1)
// cron.op-0 was the one evicted: its next failure reports from a fresh
// streak rather than inheriting the old one.
reportCronFailure({ operation: 'cron.op-0', now: t0 + 3 })
expect(events).toHaveLength(2)
expect(events[1].context).toMatchObject({
operation: 'cron.op-0',
consecutiveFailures: 1,
})
})
it('redacts PII in the supplied context before it reaches the sink', () => {
reportCronFailure({
operation: 'cron.salary',
context: { note: 'employee 800101-1234 skipped', token: 'abc123' },
})
const ctx = events[0].context as { note: string; token: string }
expect(ctx.note).toBe('[REDACTED]')
expect(ctx.token).toBe('[REDACTED]')
})
it('never throws, even when the sink is broken', () => {
registerObservabilitySink({
name: 'broken',
captureException() {
throw new Error('provider down')
},
captureMessage() {
throw new Error('provider down')
},
async flush() {
return false
},
})
expect(() => reportCronFailure({ operation: 'cron.a' })).not.toThrow()
})
})
describe('verifyCronSecret reporting', () => {
function cronRequest(auth?: string): Request {
return new Request('http://localhost/api/invoices/recurring/cron', {
headers: auth ? { authorization: auth } : {},
})
}
it('reports a missing CRON_SECRET, the config error that silently kills every job', () => {
vi.stubEnv('CRON_SECRET', '')
const result = verifyCronSecret(cronRequest('Bearer whatever'))
expect(result?.status).toBe(401)
expect(events).toHaveLength(1)
expect(events[0].context).toMatchObject({
cron: true,
alert: true,
cronKind: 'auth',
status: 401,
reason: 'secret_not_configured',
operation: '/api/invoices/recurring/cron',
})
})
it('reports a token mismatch, i.e. a rotated secret the scheduler still has', () => {
vi.stubEnv('CRON_SECRET', 'correct-secret')
const result = verifyCronSecret(cronRequest('Bearer stale-secret'))
expect(result?.status).toBe(401)
expect(events[0].context.reason).toBe('token_mismatch')
})
it('reports a missing authorization header', () => {
vi.stubEnv('CRON_SECRET', 'correct-secret')
verifyCronSecret(cronRequest())
expect(events[0].context.reason).toBe('missing_authorization')
})
it('uses an explicit operation name when one is given', () => {
vi.stubEnv('CRON_SECRET', 'correct-secret')
verifyCronSecret(cronRequest('Bearer nope'), { operation: 'cron.invoice-reminders' })
expect(events[0].context.operation).toBe('cron.invoice-reminders')
})
it('reports nothing on a successful auth, and clears the streak', () => {
vi.stubEnv('CRON_SECRET', 'correct-secret')
verifyCronSecret(cronRequest('Bearer wrong'))
expect(events).toHaveLength(1)
expect(verifyCronSecret(cronRequest('Bearer correct-secret'))).toBeNull()
expect(events).toHaveLength(1)
// Streak was cleared, so the next failure reports immediately rather than
// being swallowed by the previous report's throttle window.
verifyCronSecret(cronRequest('Bearer wrong'))
expect(events).toHaveLength(2)
expect(events[1].context.consecutiveFailures).toBe(1)
})
it('can be told not to report', () => {
vi.stubEnv('CRON_SECRET', 'correct-secret')
verifyCronSecret(cronRequest('Bearer wrong'), { report: false })
expect(events).toHaveLength(0)
})
})
+80
View File
@@ -0,0 +1,80 @@
import { describe, it, expect } from 'vitest'
import { formatAmount, formatWholeKr, formatDateTime, formatDate, isSaneDateString } from '@/lib/utils'
// Intl sv-SE groups thousands with a non-breaking / narrow space (U+00A0 or
// U+202F depending on ICU version) and may render negatives with U+2212. Both
// vary across Node builds, so normalize them to plain ASCII before asserting:
// the test cares about format shape, not the exact whitespace codepoint.
const norm = (s: string) => s.replace(/\s/g, ' ').replace(/−/g, '-')
describe('formatAmount', () => {
it('renders two decimals with sv-SE grouping and no currency symbol', () => {
expect(norm(formatAmount(1234.5))).toBe('1 234,50')
expect(norm(formatAmount(0))).toBe('0,00')
expect(norm(formatAmount(-1234.56))).toBe('-1 234,56')
})
it('does not include "kr" or the SEK symbol', () => {
expect(formatAmount(100)).not.toMatch(/kr|SEK/)
})
})
describe('formatWholeKr', () => {
it('rounds to whole krona with grouping, no decimals', () => {
expect(norm(formatWholeKr(1234.56))).toBe('1 235')
expect(norm(formatWholeKr(999.4))).toBe('999')
expect(norm(formatWholeKr(0))).toBe('0')
})
})
describe('formatDateTime', () => {
it('renders ISO-ordered date and time', () => {
expect(formatDateTime('2026-05-11T14:30:00')).toBe('2026-05-11 14:30')
})
it('accepts a Date instance', () => {
expect(formatDateTime(new Date('2026-01-02T09:05:00'))).toBe('2026-01-02 09:05')
})
it('stays date-aligned with formatDate on the date portion', () => {
const iso = '2026-12-31T23:59:00'
expect(formatDateTime(iso).startsWith(formatDate(iso))).toBe(true)
})
})
describe('formatDate', () => {
it('formats a valid ISO date', () => {
expect(formatDate('2026-05-11')).toBe('2026-05-11')
})
it('fails closed on a malformed date instead of throwing', () => {
// Regression: a 6-digit year ('202403-02-05', the real incident) parses to
// an Invalid Date; date-fns format() throws on that and used to crash the
// whole transactions route via the error boundary. It must degrade, not throw.
expect(() => formatDate('202403-02-05')).not.toThrow()
expect(formatDate('202403-02-05')).toBe('-')
expect(formatDate('not-a-date')).toBe('-')
})
})
describe('isSaneDateString', () => {
it('accepts real, in-range YYYY-MM-DD dates', () => {
expect(isSaneDateString('2026-06-04')).toBe(true)
expect(isSaneDateString('2024-03-02')).toBe(true)
})
it('rejects the 6-digit-year corruption from native date inputs', () => {
expect(isSaneDateString('202403-02-05')).toBe(false)
})
it('rejects impossible and out-of-range dates', () => {
expect(isSaneDateString('2024-13-40')).toBe(false) // month 13 / day 40
expect(isSaneDateString('1899-12-31')).toBe(false) // below floor
expect(isSaneDateString('2101-01-01')).toBe(false) // above ceiling
})
it('rejects empty and non-date strings', () => {
expect(isSaneDateString('')).toBe(false)
expect(isSaneDateString('not-a-date')).toBe(false)
})
})
+254
View File
@@ -0,0 +1,254 @@
/**
* The logger -> observability sink bridge.
*
* The redaction assertions here are the load-bearing ones: these log records
* carry personnummer and financial data, and the sink ships them to a third
* party. If any of these fail, redaction is being bypassed on the way out.
*/
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
import { createLogger } from '../logger'
import {
registerObservabilitySink,
resetObservabilitySink,
type ObservabilityContext,
type ObservabilityLevel,
} from '../observability/sink'
interface Captured {
kind: 'exception' | 'message'
error?: unknown
message?: string
level?: ObservabilityLevel
context: ObservabilityContext
}
let events: Captured[] = []
beforeEach(() => {
events = []
// The logger still writes to the console; keep the suite quiet.
vi.spyOn(console, 'error').mockImplementation(() => {})
vi.spyOn(console, 'warn').mockImplementation(() => {})
vi.spyOn(console, 'log').mockImplementation(() => {})
registerObservabilitySink({
name: 'test',
captureException(error, context) {
events.push({ kind: 'exception', error, context })
},
captureMessage(message, level, context) {
events.push({ kind: 'message', message, level, context })
},
async flush() {
return true
},
})
})
afterEach(() => {
resetObservabilitySink()
vi.restoreAllMocks()
vi.unstubAllEnvs()
})
describe('logger -> observability sink', () => {
it('forwards every error record with its bound context', () => {
const log = createLogger('test/module', { requestId: 'req_1' }).child({ companyId: 'co_1' })
const err = new Error('insert failed')
;(err as Error & { code?: string }).code = '23505'
log.error('could not save entry', err, { operation: 'journal.commit' })
expect(events).toHaveLength(1)
expect(events[0].kind).toBe('exception')
expect(events[0].error).toMatchObject({ name: 'Error', message: 'insert failed', code: '23505' })
expect(events[0].context).toMatchObject({
module: 'test/module',
logLevel: 'error',
logMessage: 'could not save entry',
requestId: 'req_1',
companyId: 'co_1',
operation: 'journal.commit',
})
})
it('forwards an error record with no Error object as a message', () => {
const log = createLogger('m')
log.error('something went wrong', { status: 500 })
expect(events).toHaveLength(1)
expect(events[0].kind).toBe('message')
expect(events[0].message).toBe('something went wrong')
expect(events[0].level).toBe('error')
expect(events[0].context.status).toBe(500)
})
it('forwards alert-flagged info/warn at their own severity, not as error', () => {
const log = createLogger('m')
log.warn('tax table stale', { alert: true })
log.info('backup finished late', { alert: true })
expect(events).toHaveLength(2)
expect(events[0]).toMatchObject({ kind: 'message', level: 'warning' })
expect(events[1]).toMatchObject({ kind: 'message', level: 'info' })
})
it('does not forward plain info/warn records', () => {
const log = createLogger('m')
log.info('routine')
log.warn('mildly odd')
expect(events).toHaveLength(0)
})
it('forwards info/warn records flagged alert: true', () => {
const log = createLogger('m')
log.warn('year-end omföring skipped', { alert: true, companyId: 'co_1' })
expect(events).toHaveLength(1)
expect(events[0].context).toMatchObject({ alert: true, logLevel: 'warn', companyId: 'co_1' })
})
it('honours alert: true bound on a child logger', () => {
const log = createLogger('m').child({ alert: true })
log.info('this must page someone')
expect(events).toHaveLength(1)
expect(events[0].context.alert).toBe(true)
})
// --- redaction: the sink must never receive PII ---------------------------
it('strips a personnummer from the message before the sink sees it', () => {
const log = createLogger('m')
log.error('could not match payment for 800101-1234')
expect(events).toHaveLength(1)
expect(events[0].message).toBe('[REDACTED]')
expect(events[0].context.logMessage).toBe('[REDACTED]')
expect(JSON.stringify(events[0])).not.toContain('800101-1234')
})
it('strips a personnummer from context values and from the error message', () => {
const log = createLogger('m')
log.error('rot/rut lookup failed', new Error('no customer with 19800101-1234'), {
note: 'belongs to 800101-1234',
companyId: '57484518-3409-4b29-9d23-5d22f08bda63',
})
expect(events[0].context.note).toBe('[REDACTED]')
expect((events[0].error as { message: string }).message).toBe('[REDACTED]')
// UUIDs survive: they are identifiers, not personnummer.
expect(events[0].context.companyId).toBe('57484518-3409-4b29-9d23-5d22f08bda63')
expect(JSON.stringify(events[0])).not.toContain('800101-1234')
})
it('strips denylisted keys, however deeply nested, before the sink sees them', () => {
const log = createLogger('m')
log.error('provider call failed', {
user: 'alice',
personnummer: '800101-1234',
iban: 'SE4550000000058398257466',
headers: { authorization: 'Bearer super-secret', cookie: 'sess=abc' },
body: { credentials: { password: 'hunter2', api_key: 'gnubok_sk_live_xyz' } },
})
const ctx = events[0].context as {
user: string
personnummer: string
iban: string
headers: { authorization: string; cookie: string }
body: { credentials: unknown }
}
expect(ctx.personnummer).toBe('[REDACTED]')
expect(ctx.iban).toBe('[REDACTED]')
expect(ctx.headers.authorization).toBe('[REDACTED]')
expect(ctx.headers.cookie).toBe('[REDACTED]')
expect(ctx.body.credentials).toBe('[REDACTED]')
expect(ctx.user).toBe('alice')
const serialized = JSON.stringify(events[0])
expect(serialized).not.toContain('super-secret')
expect(serialized).not.toContain('hunter2')
expect(serialized).not.toContain('gnubok_sk_live_xyz')
expect(serialized).not.toContain('SE4550000000058398257466')
})
it('redacts PII carried in trailing details args', () => {
const log = createLogger('m')
log.error('legacy call', 'customer 800101-1234 not found', 42)
expect(events[0].context.details).toEqual(['[REDACTED]', 42])
})
it('scrubs API keys, emails and IBANs from free-text messages, not just denylisted keys', () => {
const log = createLogger('m')
log.error('key gnubok_sk_live_secret1 for [email protected] failed on SE4550000000058398257466')
expect(events[0].message).toBe(
'key [REDACTED_API_KEY] for [REDACTED_EMAIL] failed on [REDACTED_IBAN]',
)
const serialized = JSON.stringify(events[0])
expect(serialized).not.toContain('gnubok_sk_live_secret1')
expect(serialized).not.toContain('[email protected]')
expect(serialized).not.toContain('SE4550000000058398257466')
})
// --- stacks: the sink keeps them, production stdout drops them -------------
it('in production the sink receives a stack while the stdout JSON line drops it', () => {
vi.stubEnv('NODE_ENV', 'production')
const log = createLogger('m')
log.error('insert failed', new Error('clean failure'))
// Sink path: the error tracker only runs in production, so this is the
// one environment where a missing stack would make every event ungroupable.
const sinkErr = events[0].error as { message: string; stack?: string }
expect(typeof sinkErr.stack).toBe('string')
expect(sinkErr.stack).toContain('clean failure')
// Stdout path: unchanged contract, production log lines stay stackless.
const line = (console.error as unknown as ReturnType<typeof vi.fn>).mock.calls[0][0] as string
const parsed = JSON.parse(line) as { err: { message: string; stack?: unknown } }
expect(parsed.err.message).toBe('clean failure')
expect(parsed.err.stack).toBeUndefined()
})
it('the stack reaching the sink in production is redacted', () => {
vi.stubEnv('NODE_ENV', 'production')
const log = createLogger('m')
log.error('lookup failed', new Error('no customer with 800101-1234'))
const sinkErr = events[0].error as { message: string; stack?: string }
// The first stack line carries the message, so the whole-string
// personnummer rule nukes the stack rather than leaking it.
expect(sinkErr.message).toBe('[REDACTED]')
expect(sinkErr.stack).toBe('[REDACTED]')
expect(JSON.stringify(events[0])).not.toContain('800101-1234')
})
// --- resilience ----------------------------------------------------------
it('keeps logging when the sink throws', () => {
registerObservabilitySink({
name: 'broken',
captureException() {
throw new Error('provider down')
},
captureMessage() {
throw new Error('provider down')
},
async flush() {
return false
},
})
const log = createLogger('m')
expect(() => log.error('still works', new Error('boom'))).not.toThrow()
expect(console.error).toHaveBeenCalled()
})
it('is inert when no provider is registered', () => {
resetObservabilitySink()
const log = createLogger('m')
expect(() => log.error('no sink installed', new Error('boom'))).not.toThrow()
expect(events).toHaveLength(0)
})
})
+93
View File
@@ -0,0 +1,93 @@
import { describe, it, expect } from 'vitest'
import { createTestLogger } from '../logger'
// The sink element type is the (unexported) LogRecord from lib/logger.ts,
// recovered via Parameters<> so the test stays in sync with the real signature.
type Sink = Parameters<typeof createTestLogger>[1]
describe('logger', () => {
it('emits records with module + msg + level + ts', () => {
const sink: Sink = []
const log = createTestLogger('test/module', sink)
log.info('hello')
expect(sink).toHaveLength(1)
expect(sink[0]).toMatchObject({
level: 'info',
module: 'test/module',
msg: 'hello',
})
expect(typeof sink[0].ts).toBe('string')
})
it('merges base context into every record', () => {
const sink: Sink = []
const log = createTestLogger('m', sink, { requestId: 'req_1' })
log.info('hi')
expect(sink[0].requestId).toBe('req_1')
})
it('child() returns a logger that merges extra context', () => {
const sink: Sink = []
const log = createTestLogger('m', sink, { requestId: 'req_1' })
const child = log.child({ companyId: 'co_1', userId: 'u_1' })
child.warn('oops')
expect(sink[0]).toMatchObject({
requestId: 'req_1',
companyId: 'co_1',
userId: 'u_1',
})
})
it('treats Error args as the err field with name/message/code', () => {
const sink: Sink = []
const log = createTestLogger('m', sink)
const err = new Error('boom')
;(err as Error & { code?: string }).code = '23505'
log.error('insert failed', err)
expect(sink[0].err).toMatchObject({ name: 'Error', message: 'boom', code: '23505' })
})
it('merges plain-object args into context', () => {
const sink: Sink = []
const log = createTestLogger('m', sink)
log.info('done', { durationMs: 42, status: 200 })
expect(sink[0]).toMatchObject({ durationMs: 42, status: 200 })
})
it('redacts sensitive keys recursively', () => {
const sink: Sink = []
const log = createTestLogger('m', sink)
log.info('login', {
user: 'alice',
headers: { authorization: 'Bearer secret', cookie: 'sess=xxx' },
payload: { password: 'hunter2', token: 'tok' },
})
const rec = sink[0] as {
user: string
headers: { authorization: string; cookie: string }
payload: { password: string; token: string }
}
expect(rec.headers.authorization).toBe('[REDACTED]')
expect(rec.headers.cookie).toBe('[REDACTED]')
expect(rec.payload.password).toBe('[REDACTED]')
expect(rec.payload.token).toBe('[REDACTED]')
expect(rec.user).toBe('alice')
})
it('redacts personnummer-shaped strings while preserving UUIDs', () => {
const sink: Sink = []
const log = createTestLogger('m', sink)
log.info('processing for 800101-1234', { uuid: '57484518-3409-4b29-9d23-5d22f08bda63' })
expect(sink[0].msg).toBe('[REDACTED]')
expect(sink[0].uuid).toBe('57484518-3409-4b29-9d23-5d22f08bda63')
})
it('routes non-object, non-Error args into details', () => {
const sink: Sink = []
const log = createTestLogger('m', sink)
log.warn('legacy', 'string arg', 42)
expect(sink[0].details).toEqual(['string arg', 42])
})
})
+105
View File
@@ -0,0 +1,105 @@
import { describe, it, expect } from 'vitest'
import {
roundOre,
truncateToWholeKronor,
ORE_TOLERANCE,
equalOre,
isZeroOre,
sumOre,
} from '@/lib/money'
describe('roundOre', () => {
it('rounds exact-half öre values up where naive Math.round fails', () => {
// The whole reason this helper exists: 1.005 stored as 1.00499999… makes
// naive Math.round(x*100)/100 yield 1.00. roundOre must give 1.01.
expect(roundOre(1.005)).toBe(1.01)
expect(roundOre(2.675)).toBe(2.68)
expect(roundOre(0.615)).toBe(0.62)
})
it('leaves well-formed decimals untouched', () => {
expect(roundOre(1.234)).toBe(1.23)
expect(roundOre(1.235)).toBe(1.24)
expect(roundOre(100)).toBe(100)
expect(roundOre(1234.56)).toBe(1234.56)
})
it('preserves the sign of negative zero', () => {
expect(Object.is(roundOre(-0), -0)).toBe(true)
expect(roundOre(0)).toBe(0)
})
it('handles negative amounts', () => {
expect(roundOre(-1.234)).toBe(-1.23)
expect(roundOre(-99.999)).toBe(-100)
// The EPSILON nudge moves a stored negative value slightly toward zero, so
// an exact-half negative rounds toward +∞ (mirrors Math.round on negatives):
// -1.005 → -1.00, not -1.01. Documented so a refactor can't silently flip it.
expect(roundOre(-1.005)).toBe(-1)
})
})
describe('truncateToWholeKronor', () => {
it('drops the öre entirely: truncation, never rounding', () => {
// öretal bortfaller (SFF 2011:1261 22 kap. 1 §): 16 073,84 declares and
// draws as 16 073, and even ,99 never rounds up.
expect(truncateToWholeKronor(16073.84)).toBe(16073)
expect(truncateToWholeKronor(16073.99)).toBe(16073)
expect(truncateToWholeKronor(16073.5)).toBe(16073)
expect(truncateToWholeKronor(0.84)).toBe(0)
})
it('leaves whole-krona amounts untouched', () => {
expect(truncateToWholeKronor(16073)).toBe(16073)
expect(truncateToWholeKronor(0)).toBe(0)
})
it('does not lose a krona to IEEE drift just below an integer', () => {
// 51 158 × 0,3142 style float noise: a true 16 074,00 stored as
// 16 073,999999999998 must not truncate to 16 073.
expect(truncateToWholeKronor(16073.999999999998)).toBe(16074)
expect(truncateToWholeKronor(6.999999999999999)).toBe(7)
})
it('truncates negative amounts toward zero and normalizes -0', () => {
expect(truncateToWholeKronor(-5.99)).toBe(-5)
expect(truncateToWholeKronor(-0.84)).toBe(0)
expect(Object.is(truncateToWholeKronor(-0.84), -0)).toBe(false)
})
})
describe('ORE_TOLERANCE / equalOre / isZeroOre', () => {
it('is half an öre', () => {
expect(ORE_TOLERANCE).toBe(0.005)
})
it('treats sub-öre float drift as equal', () => {
expect(equalOre(0.1 + 0.2, 0.3)).toBe(true) // classic 0.30000000000000004
expect(equalOre(100.001, 100.0)).toBe(true)
})
it('flags a real one-öre discrepancy as not equal', () => {
expect(equalOre(100.01, 100.0)).toBe(false)
})
it('isZeroOre absorbs drift around zero', () => {
expect(isZeroOre(0.1 + 0.2 - 0.3)).toBe(true)
expect(isZeroOre(0.01)).toBe(false)
})
})
describe('sumOre', () => {
it('sums then rounds once', () => {
expect(sumOre([0.1, 0.2])).toBe(0.3)
expect(sumOre([1.005, 1.005])).toBe(2.01)
expect(sumOre([])).toBe(0)
})
})
describe('lib/bokslut/rounding back-compat re-export', () => {
it('exposes the same roundOre/ORE_TOLERANCE from the legacy path', async () => {
const legacy = await import('@/lib/bokslut/rounding')
expect(legacy.roundOre(1.005)).toBe(1.01)
expect(legacy.ORE_TOLERANCE).toBe(ORE_TOLERANCE)
})
})
+85
View File
@@ -0,0 +1,85 @@
import { describe, it, expect } from 'vitest'
import { resolveAccount } from '@/lib/cash-accounts/resolve-account'
import type { CashAccount } from '@/types'
function makeCashAccount(overrides: Partial<CashAccount> = {}): CashAccount {
return {
id: 'ca-1',
company_id: 'company-1',
bank_connection_id: null,
external_uid: null,
iban: null,
bban: null,
payee_iban: null,
bank_name: null,
clearing_number: null,
account_number: null,
bankgiro: null,
plusgiro: null,
swish: null,
bic: null,
bank_code: null,
foreign_account_number: null,
invoice_payee: false,
name: null,
currency: 'SEK',
ledger_account: '1930',
balance: null,
available_balance: null,
balance_updated_at: null,
enabled: true,
is_primary: true,
source: 'manual',
voucher_series: null,
created_at: '2024-01-01T00:00:00Z',
updated_at: '2024-01-01T00:00:00Z',
...overrides,
}
}
describe('resolveAccount', () => {
it('returns the ledger_account for the bound cash account when cash_account_id matches', () => {
const accounts = [
makeCashAccount({ id: 'ca-1', ledger_account: '1930' }),
makeCashAccount({ id: 'ca-2', ledger_account: '1940', is_primary: false }),
]
const result = resolveAccount(accounts, 'ca-2', 'SEK')
expect(result).toEqual({ account: '1940', fallback: false })
})
it('falls back to the sole enabled same-currency account when cash_account_id is null', () => {
const accounts = [makeCashAccount({ id: 'ca-1', ledger_account: '1920', currency: 'EUR' })]
const result = resolveAccount(accounts, null, 'EUR')
expect(result).toEqual({ account: '1920', fallback: false })
})
it('falls back to 1930 when cash_account_id is null and multiple same-currency accounts exist', () => {
const accounts = [
makeCashAccount({ id: 'ca-1', ledger_account: '1930', currency: 'SEK' }),
makeCashAccount({ id: 'ca-2', ledger_account: '1940', currency: 'SEK', is_primary: false }),
]
const result = resolveAccount(accounts, null, 'SEK')
expect(result).toEqual({ account: '1930', fallback: true })
})
it('falls back to 1930 when cash_account_id does not match any account', () => {
const accounts = [makeCashAccount({ id: 'ca-1', ledger_account: '1930' })]
const result = resolveAccount(accounts, 'ca-unknown', 'SEK')
expect(result).toEqual({ account: '1930', fallback: true })
})
it('falls back to 1930 when accounts list is empty', () => {
const result = resolveAccount([], null, 'SEK')
expect(result).toEqual({ account: '1930', fallback: true })
})
it('ignores disabled accounts in the currency fallback path', () => {
const accounts = [
makeCashAccount({ id: 'ca-1', ledger_account: '1930', enabled: true }),
makeCashAccount({ id: 'ca-2', ledger_account: '1940', enabled: false, is_primary: false }),
]
// Only one enabled SEK account → resolves without fallback
const result = resolveAccount(accounts, null, 'SEK')
expect(result).toEqual({ account: '1930', fallback: false })
})
})
+62
View File
@@ -0,0 +1,62 @@
import { describe, it, expect } from 'vitest'
import { swedishToday, formatCurrency, withTimeout } from '../utils'
describe('swedishToday', () => {
it('formats the date as ISO yyyy-MM-dd with a Swedish weekday', () => {
// 2026-01-01 is a Thursday → "torsdag". Noon UTC keeps us clear of any
// midnight boundary so the assertion is timezone-stable.
expect(swedishToday(new Date('2026-01-01T12:00:00Z'))).toBe('2026-01-01 (torsdag)')
})
it('reports the date in Europe/Stockholm, not UTC', () => {
// 23:30 UTC on 2026-05-26 is already 01:30 on 2026-05-27 in Stockholm
// (CEST, UTC+2). A naive UTC date would read the day before: the off-by-one
// we explicitly format around for users near midnight.
expect(swedishToday(new Date('2026-05-26T23:30:00Z'))).toBe('2026-05-27 (onsdag)')
})
it('omits clock time so the cached prompt prefix stays stable across a day', () => {
const morning = swedishToday(new Date('2026-05-27T06:00:00Z'))
const evening = swedishToday(new Date('2026-05-27T18:00:00Z'))
expect(morning).toBe(evening)
expect(morning).not.toMatch(/\d{2}:\d{2}/)
})
})
describe('formatCurrency', () => {
it('falls back to SEK for a NULL currency instead of throwing', () => {
// transactions.currency is nullable and NULL is legacy for the 'SEK'
// column default (migration 20260726100000), but the Transaction type
// declares it required. Intl throws RangeError on `currency: null`, and
// one such row used to blank the whole transactions list.
expect(() => formatCurrency(1234.5, null)).not.toThrow()
expect(formatCurrency(1234.5, null)).toBe(formatCurrency(1234.5, 'SEK'))
})
it('falls back to SEK for undefined and for an empty string', () => {
expect(formatCurrency(10, undefined)).toBe(formatCurrency(10, 'SEK'))
expect(formatCurrency(10, '')).toBe(formatCurrency(10, 'SEK'))
expect(formatCurrency(10)).toBe(formatCurrency(10, 'SEK'))
})
it('still honours a real currency code', () => {
expect(formatCurrency(10, 'EUR')).toContain('€')
})
})
describe('withTimeout', () => {
it('resolves with the promise value when it settles in time', async () => {
const result = await withTimeout(Promise.resolve('ok'), 1000)
expect(result).toBe('ok')
})
it('rejects when the promise exceeds the deadline', async () => {
const slow = new Promise<string>((resolve) => setTimeout(() => resolve('late'), 200))
await expect(withTimeout(slow, 50)).rejects.toThrow('Timeout after 50ms')
})
it('rejects when the promise itself rejects', async () => {
const failing = Promise.reject(new Error('boom'))
await expect(withTimeout(failing, 1000)).rejects.toThrow('boom')
})
})