docs(production): standardiserad produktionsberedskap och gap-analys

Lägger docs/production-readiness.md och siax/production-gaps.json enligt SIAX Master Definition of Done. Underlag: git-, kod- och live-evidens 2026-11-11. Nivån är evidensbaserad, inte ett leveransgodkännande.
This commit is contained in:
2026-11-10 09:15:21 +01:00
parent 0fda8cae48
commit 2bee8eb778
6135 changed files with 4 additions and 1718997 deletions
@@ -1,137 +0,0 @@
/**
* Tests for the sandbox cleanup cron route: the run loops small RPC batches
* (each PostgREST statement gets its own 8s window; a function-level
* statement_timeout cannot lift it), stops when a batch makes no progress,
* aggregates totals across batches, accepts the legacy bare-integer return
* shape, and logs failures at error level: the failure mode this route
* chain fixes was months of silently swallowed cleanup errors.
*/
import { describe, it, expect, vi, beforeEach } from 'vitest'
const h = vi.hoisted(() => ({
logInfo: vi.fn(),
logError: vi.fn(),
rpc: vi.fn(),
}))
vi.mock('@/lib/api/with-cron-context', () => ({
withCronContext:
(_name: string, handler: (req: Request, ctx: unknown) => Promise<Response>) =>
(req: Request) =>
handler(req, {
log: { info: h.logInfo, error: h.logError, warn: vi.fn() },
requestId: 'req_test',
}),
}))
vi.mock('@supabase/supabase-js', () => ({
createClient: vi.fn(() => ({ rpc: h.rpc })),
}))
import { GET, maxDuration } from '../route'
function cronRequest(): Request {
return new Request('http://localhost:3000/api/sandbox/cleanup/cron')
}
function batch(cleaned: number, failed = 0, orphans = 0) {
return { data: { cleaned, failed, orphans_removed: orphans }, error: null }
}
describe('GET /api/sandbox/cleanup/cron', () => {
beforeEach(() => {
vi.clearAllMocks()
process.env.NEXT_PUBLIC_SUPABASE_URL = 'https://example.supabase.co'
process.env.SUPABASE_SERVICE_ROLE_KEY = 'service-role-key'
})
it('reserves enough function time for the batch loop', () => {
expect(maxDuration).toBe(300)
})
it('loops full batches and stops on the first partial one, aggregating totals', async () => {
h.rpc
.mockResolvedValueOnce(batch(10))
.mockResolvedValueOnce(batch(10, 0, 0))
.mockResolvedValueOnce(batch(3, 1, 2))
.mockResolvedValueOnce(batch(0))
const res = await GET(cronRequest())
const body = await res.json()
expect(h.rpc).toHaveBeenCalledWith('cleanup_expired_sandbox_users', {
p_max_age_hours: 24,
p_limit: 10,
})
// Third batch still made progress (cleaned + orphans > 0), so a fourth
// call runs and returns zero progress, ending the loop.
expect(h.rpc).toHaveBeenCalledTimes(4)
expect(res.status).toBe(200)
expect(body).toEqual({
success: true,
cleaned: 23,
failed: 1,
orphans_removed: 2,
batches: 4,
})
})
it('stops immediately when the backlog is empty', async () => {
h.rpc.mockResolvedValue(batch(0))
const res = await GET(cronRequest())
const body = await res.json()
expect(h.rpc).toHaveBeenCalledTimes(1)
expect(body.batches).toBe(1)
expect(h.logInfo).toHaveBeenCalled()
expect(h.logError).not.toHaveBeenCalled()
})
it('stops when a batch yields only failures, and logs at error level', async () => {
h.rpc.mockResolvedValueOnce(batch(0, 4, 0))
const res = await GET(cronRequest())
const body = await res.json()
expect(h.rpc).toHaveBeenCalledTimes(1)
expect(body.failed).toBe(4)
expect(h.logError).toHaveBeenCalledWith(
'sandbox cleanup completed with failures',
expect.objectContaining({ failed: 4 }),
)
})
it('still accepts the legacy bare-integer return shape', async () => {
h.rpc.mockResolvedValueOnce({ data: 5, error: null }).mockResolvedValueOnce(batch(0))
const res = await GET(cronRequest())
const body = await res.json()
expect(res.status).toBe(200)
expect(body.cleaned).toBe(5)
})
it('returns an error envelope when the RPC fails mid-loop', async () => {
h.rpc
.mockResolvedValueOnce(batch(10))
.mockResolvedValueOnce({ data: null, error: { message: 'boom', code: 'XX000' } })
const res = await GET(cronRequest())
const body = await res.json()
expect(res.status).toBeGreaterThanOrEqual(400)
expect(body.error).toBeDefined()
expect(h.logError).toHaveBeenCalled()
})
it('returns an error when Supabase configuration is missing', async () => {
delete process.env.SUPABASE_SERVICE_ROLE_KEY
const res = await GET(cronRequest())
const body = await res.json()
expect(res.status).toBeGreaterThanOrEqual(500)
expect(body.error).toBeDefined()
})
})
-88
View File
@@ -1,88 +0,0 @@
import { createServiceRoleClient } from '@/lib/supabase/service-client'
import { NextResponse } from 'next/server'
import { withCronContext } from '@/lib/api/with-cron-context'
import { errorResponse, errorResponseFromCode } from '@/lib/errors/get-structured-error'
/**
* GET /api/sandbox/cleanup/cron: daily 04:00 UTC.
* Removes expired sandbox users (>24h old).
*
* Every PostgREST statement runs under authenticator's statement_timeout of
* 8s, and a function-level SET statement_timeout does NOT lift it (the timer
* arms when the top-level statement starts; verified empirically on prod
* 2026-08-07, same finding as the SIE import RPCs). One teardown costs
* ~220ms with the account_id index, so the run loops SMALL batches: each
* rpc() call is its own statement with its own 8s window, and the loop
* stops when a batch makes no progress (nothing left, or only failing
* users remain) or the route's time budget nears. Capacity per night is
* MAX_BATCHES * BATCH_LIMIT users; the nightly intake is a small fraction
* of that.
*/
export const maxDuration = 300
const BATCH_LIMIT = 10
const MAX_BATCHES = 25
const TIME_BUDGET_MS = 240_000
export const GET = withCronContext('cron.sandbox_cleanup', async (_request, ctx) => {
const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL
const supabaseServiceKey = process.env.SUPABASE_SERVICE_ROLE_KEY
if (!supabaseUrl || !supabaseServiceKey) {
return errorResponseFromCode('INTERNAL_ERROR', ctx.log, {
requestId: ctx.requestId,
details: { reason: 'Missing Supabase configuration' },
})
}
const supabase = createServiceRoleClient(supabaseUrl, supabaseServiceKey)
const started = Date.now()
const totals = { cleaned: 0, failed: 0, orphans_removed: 0, batches: 0 }
for (let i = 0; i < MAX_BATCHES; i++) {
if (Date.now() - started > TIME_BUDGET_MS) break
const { data, error } = await supabase.rpc('cleanup_expired_sandbox_users', {
p_max_age_hours: 24,
p_limit: BATCH_LIMIT,
})
if (error) {
ctx.log.error('sandbox cleanup rpc failed', { error, ...totals })
return errorResponse(error, ctx.log, { requestId: ctx.requestId })
}
// Migration 20260807130000 changed the RPC's return from a bare integer
// to a {cleaned, failed, orphans_removed} summary; accept both shapes so
// deploy/migration ordering cannot break the cron.
const batch =
typeof data === 'number'
? { cleaned: data, failed: 0, orphans_removed: 0 }
: {
cleaned: Number(data?.cleaned ?? 0),
failed: Number(data?.failed ?? 0),
orphans_removed: Number(data?.orphans_removed ?? 0),
}
totals.cleaned += batch.cleaned
totals.failed += batch.failed
totals.orphans_removed += batch.orphans_removed
totals.batches += 1
// No progress means only permanently-failing users (retried nightly and
// reported below) or an empty backlog: looping further would spin on the
// same rows.
if (batch.cleaned + batch.orphans_removed === 0) break
}
// Per-user failures used to be swallowed as Postgres WARNINGs, which is how
// the cleanup sat broken for months; surface them at error level instead.
if (totals.failed > 0) {
ctx.log.error('sandbox cleanup completed with failures', totals)
} else {
ctx.log.info('sandbox cleanup summary', totals)
}
return NextResponse.json({ success: true, ...totals })
})
@@ -1,96 +0,0 @@
import { describe, expect, it } from 'vitest'
import { buildSandboxArticles } from '../articles'
const input = { userId: 'user-1', companyId: 'company-1' }
/** The articles CHECK constraints from 20260621120000_artikelregister.sql. */
const ALLOWED_TYPES = ['vara', 'tjanst']
const ALLOWED_VAT_RATES = [0, 6, 12, 25]
describe('sandbox article seed data', () => {
it('seeds five articles scoped to the sandbox company', () => {
const articles = buildSandboxArticles(input)
expect(articles).toHaveLength(5)
expect(articles.every((a) => a.user_id === 'user-1' && a.company_id === 'company-1')).toBe(true)
expect(articles.every((a) => a.active === true)).toBe(true)
})
it('numbers the articles A-001 upwards without gaps', () => {
const articles = buildSandboxArticles(input)
expect(articles.map((a) => a.article_number)).toEqual([
'A-001',
'A-002',
'A-003',
'A-004',
'A-005',
])
// uq_articles_company_number is unique per company when article_number is set.
expect(new Set(articles.map((a) => a.article_number)).size).toBe(articles.length)
})
it('satisfies every CHECK constraint on articles', () => {
const articles = buildSandboxArticles(input)
for (const article of articles) {
expect(ALLOWED_TYPES).toContain(article.type)
expect(ALLOWED_VAT_RATES).toContain(article.vat_rate)
expect(article.unit.length).toBeGreaterThan(0)
expect(article.price_excl_vat).toBeGreaterThan(0)
expect(Number.isFinite(article.price_excl_vat)).toBe(true)
}
})
it('covers the mix the register is supposed to demonstrate', () => {
const articles = buildSandboxArticles(input)
// Hourly consulting, a fixed-price package, and a resold licence.
expect(articles.some((a) => a.type === 'tjanst' && a.unit === 'tim')).toBe(true)
expect(articles.some((a) => a.type === 'tjanst' && a.unit === 'st')).toBe(true)
expect(articles.some((a) => a.type === 'vara' && a.unit === 'st')).toBe(true)
})
it('only uses a reduced VAT rate where Swedish law allows one', () => {
const articles = buildSandboxArticles(input)
const reduced = articles.filter((a) => a.vat_rate !== 25)
// A printed book is 6 % (ML 9 kap. 7 §). Consulting, the fixed-price
// package and the rebilled licence are ordinary 25 % supplies: a reduced
// rate on any of them would be a VAT error shipped as demo data.
expect(reduced).toHaveLength(1)
expect(reduced[0].vat_rate).toBe(6)
expect(reduced[0].name).toContain('Handbok')
expect(articles.filter((a) => a.vat_rate === 25)).toHaveLength(4)
})
it('leaves the revenue account to the VAT treatment', () => {
const articles = buildSandboxArticles(input)
// NULL means "derive from the VAT treatment at line-create time". Pinning
// an override would freeze a 25 % account onto the 6 % book line.
expect(articles.every((a) => a.revenue_account === null)).toBe(true)
})
it('sets every optional column on every row', () => {
const articles = buildSandboxArticles(input)
// PostgREST normalizes columns across a bulk insert: a key present on one
// row and absent on another is sent as NULL instead of falling through to
// the schema default.
const keySets = articles.map((a) => Object.keys(a).sort().join(','))
expect(new Set(keySets).size).toBe(1)
for (const article of articles) {
expect(article).toHaveProperty('name_en')
expect(article).toHaveProperty('cost_price')
expect(article).toHaveProperty('ean')
expect(article).toHaveProperty('housework_type')
expect(article).toHaveProperty('notes')
expect(article.currency).toBe('SEK')
}
})
it('is deterministic', () => {
expect(buildSandboxArticles(input)).toEqual(buildSandboxArticles(input))
})
})
@@ -1,17 +0,0 @@
import { describe, expect, it } from 'vitest'
import { buildSandboxCustomers } from '../customers'
describe('sandbox customer seed data', () => {
it('sets the required VAT-validation state for every customer', () => {
const customers = buildSandboxCustomers('user-1', 'company-1')
expect(customers).toHaveLength(3)
expect(customers.every((customer) => typeof customer.vat_number_validated === 'boolean')).toBe(
true,
)
expect(customers.find((customer) => customer.customer_type === 'individual')).toMatchObject({
name: 'Anna Lindström',
vat_number_validated: false,
})
})
})
@@ -1,355 +0,0 @@
import { describe, expect, it } from 'vitest'
import { roundOre } from '@/lib/money'
import { BAS_REFERENCE } from '@/lib/bookkeeping/bas-data'
import {
buildSandboxLedgerHistory,
SANDBOX_LEDGER_ACCOUNT_NUMBERS,
type SandboxLedgerLineRow,
} from '../ledger-history'
/**
* The journal_entries.source_type allowlist as of
* 20260712100500_journal_source_type_stripe_payout.sql. A value outside this
* set is rejected by Postgres with 23514, so the seed would fail at runtime.
*/
const ALLOWED_SOURCE_TYPES = [
'manual',
'bank_transaction',
'invoice_created',
'invoice_paid',
'invoice_cash_payment',
'credit_note',
'salary_payment',
'opening_balance',
'year_end',
'storno',
'correction',
'import',
'system',
'inbox_item',
'supplier_invoice_registered',
'supplier_invoice_paid',
'supplier_invoice_cash_payment',
'supplier_credit_note',
'currency_revaluation',
'supplier_invoice_privately_paid',
'reminder_fee',
'accrual',
'result_appropriation',
'rot_rut_payout',
'vat_settlement',
'stripe_payout',
]
const BAS_ACCOUNT_NUMBERS = new Set(BAS_REFERENCE.map((a) => a.account_number))
const accountMap = Object.fromEntries(
SANDBOX_LEDGER_ACCOUNT_NUMBERS.map((n) => [n, `account-${n}`]),
)
/** August 6th: the history then covers January through July. */
const input = {
userId: 'user-1',
companyId: 'company-1',
fiscalPeriodId: 'fp-1',
today: new Date(2026, 7, 6),
accountMap,
}
function sums(lines: SandboxLedgerLineRow[]) {
return {
debit: roundOre(lines.reduce((n, l) => n + l.debit_amount, 0)),
credit: roundOre(lines.reduce((n, l) => n + l.credit_amount, 0)),
}
}
function allLines(history: ReturnType<typeof buildSandboxLedgerHistory>) {
return history.linesByEntryIndex.flat()
}
describe('sandbox ledger history', () => {
it('emits one line bucket per entry', () => {
const history = buildSandboxLedgerHistory(input)
expect(history.entries.length).toBe(history.linesByEntryIndex.length)
expect(history.entries.length).toBeGreaterThan(0)
})
it('covers January through the month before today, 4 to 7 entries per month', () => {
const history = buildSandboxLedgerHistory(input)
const byMonth = new Map<string, number>()
for (const entry of history.entries) {
const month = entry.entry_date.slice(0, 7)
byMonth.set(month, (byMonth.get(month) ?? 0) + 1)
}
expect([...byMonth.keys()]).toEqual([
'2026-01',
'2026-02',
'2026-03',
'2026-04',
'2026-05',
'2026-06',
'2026-07',
])
// January has no customer payment and no eget uttag yet (no cash in), and
// no periodic cost: 4. Every other month is 5 or 6, plus one for the
// quarter-close momsredovisning (March, June) and one for the Q1 payment
// (May). July has no periodic cost, so it stays at 5.
expect(byMonth.get('2026-01')).toBe(4)
expect(byMonth.get('2026-03')).toBe(7)
expect(byMonth.get('2026-05')).toBe(7)
expect(byMonth.get('2026-06')).toBe(7)
for (const [, count] of byMonth) {
expect(count).toBeGreaterThanOrEqual(4)
expect(count).toBeLessThanOrEqual(7)
}
expect(history.entries).toHaveLength(42)
})
it('produces no entries before the first full month has passed', () => {
const january = buildSandboxLedgerHistory({ ...input, today: new Date(2026, 0, 20) })
expect(january.entries).toEqual([])
expect(january.linesByEntryIndex).toEqual([])
})
it('balances every entry exactly, both sides above zero', () => {
const history = buildSandboxLedgerHistory(input)
history.linesByEntryIndex.forEach((lines, index) => {
const { debit, credit } = sums(lines)
expect(debit, `entry ${index} (${history.entries[index].description})`).toBe(credit)
expect(debit).toBeGreaterThan(0)
expect(credit).toBeGreaterThan(0)
// A line is either a debit or a credit, never both.
for (const line of lines) {
expect(line.debit_amount === 0 || line.credit_amount === 0).toBe(true)
expect(line.debit_amount).toBeGreaterThanOrEqual(0)
expect(line.credit_amount).toBeGreaterThanOrEqual(0)
}
})
})
it('keeps every amount rounded to whole öre', () => {
for (const line of allLines(buildSandboxLedgerHistory(input))) {
expect(line.debit_amount).toBe(roundOre(line.debit_amount))
expect(line.credit_amount).toBe(roundOre(line.credit_amount))
}
})
it('uses string BAS account numbers that exist in class 1 to 8', () => {
for (const line of allLines(buildSandboxLedgerHistory(input))) {
expect(typeof line.account_number).toBe('string')
expect(line.account_number).toMatch(/^[1-8]\d{3}$/)
expect(BAS_ACCOUNT_NUMBERS.has(line.account_number)).toBe(true)
expect(SANDBOX_LEDGER_ACCOUNT_NUMBERS).toContain(line.account_number)
}
})
it('resolves account_id through the caller-supplied map', () => {
const history = buildSandboxLedgerHistory(input)
for (const line of allLines(history)) {
expect(line.account_id).toBe(`account-${line.account_number}`)
}
// A chart lookup that came back short must degrade to null, not undefined:
// undefined would be dropped from the insert payload.
const partial = buildSandboxLedgerHistory({ ...input, accountMap: {} })
for (const line of allLines(partial)) {
expect(line.account_id).toBeNull()
}
})
it('sets an explicit dimensions bag on every single line', () => {
for (const line of allLines(buildSandboxLedgerHistory(input))) {
// NOT NULL on journal_entry_lines.dimensions, and PostgREST sends NULL
// for a key one row omits while another sets it.
expect(Object.prototype.hasOwnProperty.call(line, 'dimensions')).toBe(true)
expect(line.dimensions).toBeTypeOf('object')
expect(line.dimensions).not.toBeNull()
}
})
it('tags revenue lines with the seeded demo dimensions on some months only', () => {
const history = buildSandboxLedgerHistory(input)
const revenueLines = allLines(history).filter((l) => l.account_number === '3001')
const tagged = revenueLines.filter((l) => Object.keys(l.dimensions).length > 0)
expect(tagged.length).toBeGreaterThan(0)
expect(tagged.length).toBeLessThan(revenueLines.length)
// Only the four dimension_values the seed creates, on SIE dims 1 and 6.
for (const line of tagged) {
expect(Object.keys(line.dimensions).sort()).toEqual(['1', '6'])
expect(['BUTIK', 'WEBB']).toContain(line.dimensions['1'])
expect(['P001', 'P002']).toContain(line.dimensions['6'])
}
expect(tagged.some((l) => l.dimensions['1'] === 'BUTIK' && l.dimensions['6'] === 'P001')).toBe(true)
// Nothing but revenue carries dimensions.
const otherTagged = allLines(history).filter(
(l) => l.account_number !== '3001' && Object.keys(l.dimensions).length > 0,
)
expect(otherTagged).toEqual([])
})
it('keeps dates inside the fiscal year and leaves posting metadata to the engine', () => {
const history = buildSandboxLedgerHistory(input)
for (const entry of history.entries) {
expect(entry.entry_date >= '2026-01-01').toBe(true)
expect(entry.entry_date <= '2026-12-31').toBe(true)
expect(entry.entry_date).toMatch(/^\d{4}-\d{2}-\d{2}$/)
expect(ALLOWED_SOURCE_TYPES).toContain(entry.source_type)
expect(entry).not.toHaveProperty('status')
expect(entry).not.toHaveProperty('committed_at')
expect(entry).not.toHaveProperty('commit_method')
expect(entry.voucher_series).toBe('A')
expect(entry.fiscal_period_id).toBe('fp-1')
expect(entry.user_id).toBe('user-1')
expect(entry.company_id).toBe('company-1')
expect(entry.description.length).toBeGreaterThan(0)
}
})
it('carries no voucher_number: the caller assigns those via the RPC', () => {
const history = buildSandboxLedgerHistory(input)
for (const entry of history.entries) {
expect(entry).not.toHaveProperty('voucher_number')
expect(entry).not.toHaveProperty('id')
}
for (const line of allLines(history)) {
expect(line).not.toHaveProperty('journal_entry_id')
}
})
it('emits the entries in date order so the voucher sequence stays chronological', () => {
const dates = buildSandboxLedgerHistory(input).entries.map((e) => e.entry_date)
expect([...dates].sort()).toEqual(dates)
})
it('leaves a plausibly profitable year to date', () => {
const lines = allLines(buildSandboxLedgerHistory(input))
const revenue = roundOre(
lines
.filter((l) => l.account_number.startsWith('3'))
.reduce((n, l) => n + l.credit_amount - l.debit_amount, 0),
)
const costs = roundOre(
lines
.filter((l) => /^[4-7]/.test(l.account_number))
.reduce((n, l) => n + l.debit_amount - l.credit_amount, 0),
)
expect(revenue).toBeGreaterThan(0)
expect(costs).toBeGreaterThan(0)
expect(revenue).toBeGreaterThan(costs * 2)
})
it('keeps the bank account positive throughout the year to date', () => {
const history = buildSandboxLedgerHistory(input)
// A demo Balansrapport with a negative företagskonto reads as a bug. The
// January owner contribution is what prevents it: the fiscal year is the
// company's first period, so 1930 starts at zero.
let balance = 0
history.linesByEntryIndex.forEach((lines) => {
for (const line of lines) {
if (line.account_number !== '1930') continue
balance = roundOre(balance + line.debit_amount - line.credit_amount)
}
expect(balance).toBeGreaterThan(0)
})
})
it('books output VAT on 2611 and input VAT on 2641', () => {
const lines = allLines(buildSandboxLedgerHistory(input))
const outputVat = lines.filter((l) => l.account_number === '2611')
const inputVat = lines.filter((l) => l.account_number === '2641')
expect(outputVat.length).toBeGreaterThan(0)
expect(inputVat.length).toBeGreaterThan(0)
// Trading entries only: sales credit 2611, purchases debit 2641. The one
// exception each quarter is the momsredovisning, which clears both the
// other way. Identify it by the 2650 line rather than by sign, so this
// stays a real assertion about direction.
const settlementIndexes = new Set(
buildSandboxLedgerHistory(input)
.linesByEntryIndex.map((entryLines, index) =>
entryLines.some((l) => l.account_number === '2650') ? index : -1,
)
.filter((index) => index >= 0),
)
const tradingLines = buildSandboxLedgerHistory(input).linesByEntryIndex.flatMap(
(entryLines, index) => (settlementIndexes.has(index) ? [] : entryLines),
)
expect(
tradingLines
.filter((l) => l.account_number === '2611')
.every((l) => l.credit_amount > 0 && l.debit_amount === 0),
).toBe(true)
expect(
tradingLines
.filter((l) => l.account_number === '2641')
.every((l) => l.debit_amount > 0 && l.credit_amount === 0),
).toBe(true)
})
it('settles each closed VAT quarter to 2650 and pays it from the bank', () => {
const history = buildSandboxLedgerHistory(input)
// Each closed quarter clears its 26xx accounts to 2650 on the last day of
// the quarter: the ordinary period-close entry, not the filing itself.
// Today is 6 August 2026, so Q1 is cleared (31 March) and paid (12 May),
// and Q2 is cleared (30 June) but unpaid: its deadline is 17 August.
const declaration = history.entries.findIndex(e => e.description === 'Momsredovisning 2026 Q1')
const payment = history.entries.findIndex(e => e.description === 'Betald moms 2026 Q1')
expect(declaration).toBeGreaterThanOrEqual(0)
expect(payment).toBeGreaterThan(declaration)
expect(history.entries[declaration].entry_date).toBe('2026-03-31')
expect(history.entries[payment].entry_date).toBe('2026-05-12')
const q2Declaration = history.entries.find(e => e.description === 'Momsredovisning 2026 Q2')
expect(q2Declaration?.entry_date).toBe('2026-06-30')
expect(history.entries.some(e => e.description === 'Betald moms 2026 Q2')).toBe(false)
// The declaration carries the settlement SHAPE get_vat_declaration_totals
// looks for: a VAT-account line plus a 2650 line. Without it the quarter
// would be counted again in the next declaration.
const declarationLines = history.linesByEntryIndex[declaration]
expect(declarationLines.find(l => l.account_number === '2611')!.debit_amount).toBeGreaterThan(0)
expect(declarationLines.find(l => l.account_number === '2641')!.credit_amount).toBeGreaterThan(0)
const netPayable = declarationLines.find(l => l.account_number === '2650')!.credit_amount
expect(netPayable).toBeGreaterThan(0)
// The payment moves exactly that amount off the bank, and touches no VAT
// account, so it is not itself settlement-shaped.
const paymentLines = history.linesByEntryIndex[payment]
expect(paymentLines.find(l => l.account_number === '2650')!.debit_amount).toBe(netPayable)
expect(paymentLines.find(l => l.account_number === '1930')!.credit_amount).toBe(netPayable)
expect(paymentLines.some(l => ['2611', '2641'].includes(l.account_number))).toBe(false)
})
it('is deterministic', () => {
const first = buildSandboxLedgerHistory(input)
const second = buildSandboxLedgerHistory(input)
expect(first).toEqual(second)
expect(JSON.stringify(first)).toBe(JSON.stringify(second))
})
it('does not depend on the day of the month or the local clock', () => {
const early = buildSandboxLedgerHistory({ ...input, today: new Date(2026, 7, 1) })
const late = buildSandboxLedgerHistory({ ...input, today: new Date(2026, 7, 31) })
expect(early).toEqual(late)
})
})
@@ -1,101 +0,0 @@
import { describe, expect, it } from 'vitest'
import { roundOre } from '@/lib/money'
import { buildSandboxPendingOperations } from '../pending-operations'
const input = {
userId: 'user-1',
companyId: 'company-1',
inboxItemId: 'inbox-1',
supplierId: 'supplier-1',
invoiceDate: '2026-07-25',
dueDate: '2026-08-06',
transactionId: 'tx-1',
}
/** Sum of a kontering in the `lines` (account_number/debit_amount) spelling. */
function sums(lines: Array<{ debit_amount: number; credit_amount: number }>) {
return {
debit: lines.reduce((n, l) => n + l.debit_amount, 0),
credit: lines.reduce((n, l) => n + l.credit_amount, 0),
}
}
describe('sandbox pending-operation seed data', () => {
it('stages both demo operations under the RLS-required actor shape', () => {
const ops = buildSandboxPendingOperations(input)
expect(ops).toHaveLength(2)
// pending_operations_chat_insert is the only policy that lets a
// user-scoped client INSERT here, and it requires both fields.
expect(ops.every((op) => op.actor_type === 'agent_chat')).toBe(true)
expect(ops.every((op) => op.risk_level === 'low')).toBe(true)
expect(ops.every((op) => op.status === 'pending')).toBe(true)
expect(ops.every((op) => op.user_id === 'user-1' && op.company_id === 'company-1')).toBe(true)
})
it('threads the seeded row ids into the executor params', () => {
const [supplierInvoice, categorize] = buildSandboxPendingOperations(input)
expect(supplierInvoice.params).toMatchObject({
inbox_item_id: 'inbox-1',
supplier_id: 'supplier-1',
invoice_date: '2026-07-25',
due_date: '2026-08-06',
})
expect(categorize.params).toMatchObject({ transaction_id: 'tx-1' })
})
it('gives categorize_transaction the preview shape CategorizePreview reads', () => {
const categorize = buildSandboxPendingOperations(input).find(
(op) => op.operation_type === 'categorize_transaction',
)!
const preview = categorize.preview_data as {
amount?: unknown
debit_account?: unknown
credit_account?: unknown
lines?: Array<{ account_number: string; debit_amount: number; credit_amount: number }>
}
// The regression this guards: seeding only the generic `preview_lines` key
// dropped the card onto the legacy summary branch, which rendered blank
// accounts and "NaN kr" from formatCurrency(undefined).
expect(preview.lines).toBeDefined()
expect(preview.lines!.length).toBeGreaterThan(0)
expect(typeof preview.amount).toBe('number')
expect(Number.isFinite(preview.amount as number)).toBe(true)
expect(preview.debit_account).toBe('1930')
expect(preview.credit_account).toBe('3001')
})
it('previews a balanced verifikat for the 1 200 kr deposit', () => {
const categorize = buildSandboxPendingOperations(input).find(
(op) => op.operation_type === 'categorize_transaction',
)!
const preview = categorize.preview_data as {
amount: number
lines: Array<{ account_number: string; debit_amount: number; credit_amount: number }>
}
const { debit, credit } = sums(preview.lines)
expect(debit).toBe(credit)
// Gross on the bank line matches the summary amount the card headlines.
expect(debit).toBe(preview.amount)
expect(preview.lines.map((l) => l.account_number)).toEqual(['1930', '2611', '3001'])
})
it('keeps the supplier-invoice preview on the generic preview_lines shape', () => {
const supplierInvoice = buildSandboxPendingOperations(input).find(
(op) => op.operation_type === 'create_supplier_invoice_from_inbox',
)!
const preview = supplierInvoice.preview_data as {
preview_lines: Array<{ account: string; debit: number; credit: number }>
}
// No dedicated preview component for this type: GenericPreview renders a
// kontering under `preview_lines` in the account/debit/credit spelling.
expect(preview.preview_lines).toHaveLength(3)
const debit = preview.preview_lines.reduce((n, l) => n + l.debit, 0)
const credit = preview.preview_lines.reduce((n, l) => n + l.credit, 0)
expect(roundOre(debit)).toBe(roundOre(credit))
})
})
@@ -1,266 +0,0 @@
import { beforeEach, afterAll, describe, expect, it, vi } from 'vitest'
import { NextResponse } from 'next/server'
const mocks = vi.hoisted(() => ({
requireAuth: vi.fn(),
createJournalEntry: vi.fn(),
checkRateLimit: vi.fn(),
ensureSandboxAgentProfile: vi.fn(),
markEntriesNoDocRequired: vi.fn(),
}))
vi.mock('@/lib/auth/require-auth', () => ({ requireAuth: mocks.requireAuth }))
vi.mock('@/lib/bookkeeping/engine', () => ({ createJournalEntry: mocks.createJournalEntry }))
vi.mock('@/lib/init', () => ({ ensureInitialized: vi.fn() }))
vi.mock('@/lib/auth/rate-limit-http', () => ({ checkRateLimit: mocks.checkRateLimit }))
vi.mock('@/lib/sandbox/ensure-agent', () => ({
ensureSandboxAgentProfile: mocks.ensureSandboxAgentProfile,
}))
vi.mock('@/lib/bookkeeping/no-doc-required', () => ({
markEntriesNoDocRequired: mocks.markEntriesNoDocRequired,
}))
vi.mock('@/lib/logger', () => ({
createLogger: () => ({ info: vi.fn(), warn: vi.fn(), error: vi.fn() }),
}))
vi.mock('@/lib/bookkeeping/bas-reference', () => ({
getBASReference: (accountNumber: string) => ({
account_name: `Account ${accountNumber}`,
account_class: Number(accountNumber[0]),
account_group: accountNumber.slice(0, 2),
account_type: 'asset',
normal_balance: 'debit',
sru_code: null,
k2_excluded: false,
}),
}))
vi.mock('@/lib/salary/personnummer', () => ({
encryptPersonnummer: (value: string) => `encrypted:${value}`,
}))
vi.mock('../customers', () => ({
buildSandboxCustomers: () => [
{ name: 'Björk & Partner AB' },
{ name: 'Schmidt GmbH' },
{ name: 'Anna Lindström' },
],
}))
vi.mock('../pending-operations', () => ({ buildSandboxPendingOperations: () => [] }))
vi.mock('../articles', () => ({ buildSandboxArticles: () => [] }))
import { POST } from '../route'
interface MockSupabaseResult {
supabase: ReturnType<typeof makeClient>
deadlineInserts: unknown[][]
}
function makeClient() {
let rowId = 0
let attempt = 0
let state = 'new'
const deadlineInserts: unknown[][] = []
const from = vi.fn((table: string) => {
if (table === 'journal_entries' || table === 'journal_entry_lines') throw new Error('Seed must use the engine')
let insertPayload: unknown = undefined
const chain: Record<string, unknown> = {}
const insertedRows = () => {
if (insertPayload === undefined) return []
const rows = Array.isArray(insertPayload) ? insertPayload : [insertPayload]
return rows.map(row => ({
...(row as Record<string, unknown>),
id: `${table}-${++rowId}`,
}))
}
chain.insert = (payload: unknown) => {
insertPayload = payload
if (table === 'deadlines') deadlineInserts.push(payload as unknown[])
return chain
}
chain.update = () => chain
chain.select = () => chain
for (const method of ['eq', 'in', 'is', 'order', 'limit', 'gte', 'lte', 'not', 'or']) {
chain[method] = () => chain
}
chain.maybeSingle = async () => ({ data: null, error: null })
chain.single = async () => ({ data: insertedRows()[0] ?? { id: `${table}-${++rowId}` }, error: null })
chain.then = (resolve: (value: unknown) => void) => resolve({
data: insertedRows(),
error: null,
})
return chain
})
const supabase = {
from,
rpc: vi.fn(async (fn: string, args?: { p_success?: boolean }) => {
if (fn === 'claim_sandbox_seed') {
if (state === 'running') return { data: { status: 'busy' }, error: null }
if (state !== 'complete') { attempt++; state = 'running' }
return { data: { status: state, company_id: `company-${attempt}`, attempt_id: `attempt-${attempt}` }, error: null }
}
if (fn === 'finish_sandbox_seed') {
state = args?.p_success ? 'complete' : 'failed'
return { data: true, error: null }
}
return { data: null, error: null }
}),
}
return Object.assign(supabase, { deadlineInserts })
}
function createMockSupabase(): MockSupabaseResult {
const supabase = makeClient()
return { supabase, deadlineInserts: supabase.deadlineInserts }
}
function authenticate(supabase: ReturnType<typeof makeClient>) {
mocks.requireAuth.mockResolvedValue({
error: null, user: { id: 'user-1', is_anonymous: true }, supabase,
})
}
function request(): Request {
return new Request('http://localhost:3000/api/sandbox/seed', {
method: 'POST',
headers: { 'x-forwarded-for': '192.0.2.15' },
})
}
describe('POST /api/sandbox/seed', () => {
beforeEach(() => {
vi.clearAllMocks()
vi.useFakeTimers()
vi.setSystemTime(new Date(2026, 4, 15, 12, 0, 0))
mocks.checkRateLimit.mockResolvedValue({ ok: true })
mocks.createJournalEntry.mockImplementation(async (_db, companyId, _user, input) => ({
id: `entry-${mocks.createJournalEntry.mock.calls.length}`, company_id: companyId, ...input,
}))
mocks.ensureSandboxAgentProfile.mockResolvedValue(undefined)
mocks.markEntriesNoDocRequired.mockResolvedValue(undefined)
})
afterAll(() => {
vi.useRealTimers()
})
it('returns 401 when authentication fails', async () => {
mocks.requireAuth.mockResolvedValue({
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
})
const response = await POST(request())
expect(response.status).toBe(401)
})
it('inserts the canonical quarterly VAT deadline during a successful seed', async () => {
const { supabase, deadlineInserts } = createMockSupabase()
mocks.requireAuth.mockResolvedValue({
error: null,
user: { id: 'user-1', is_anonymous: true },
supabase,
})
const response = await POST(request())
expect(response.status).toBe(200)
await expect(response.json()).resolves.toEqual({ seeded: true })
expect(deadlineInserts).toHaveLength(1)
expect(deadlineInserts[0][0]).toMatchObject({
title: 'Momsdeklaration Q2 2026',
due_date: '2026-08-17',
tax_deadline_type: 'moms_quarterly',
tax_period: '2026-Q2',
})
})
it('rejects registered users without claiming or writing', async () => {
const db = makeClient()
mocks.requireAuth.mockResolvedValue({ error: null, user: { id: 'real', is_anonymous: false }, supabase: db })
expect((await POST(request())).status).toBe(403)
expect(db.rpc).not.toHaveBeenCalled()
expect(db.from).not.toHaveBeenCalled()
})
it('posts history, invoice and payroll through the engine without preset audit fields', async () => {
const db = makeClient()
authenticate(db)
expect((await POST(request())).status).toBe(200)
const inputs = mocks.createJournalEntry.mock.calls.map(call => call[3])
expect(new Set(inputs.map(input => input.source_type))).toEqual(
new Set(['manual', 'invoice_created', 'invoice_paid', 'salary_payment']),
)
for (const input of inputs) {
expect(input).not.toHaveProperty('committed_at')
expect(input).not.toHaveProperty('commit_method')
expect(input).not.toHaveProperty('voucher_number')
expect(input).not.toHaveProperty('status')
expect(input.lines.length).toBeGreaterThan(1)
}
expect(db.rpc).toHaveBeenLastCalledWith('finish_sandbox_seed', {
p_attempt_id: 'attempt-1', p_success: true,
})
})
it('does not seed again after completion', async () => {
const db = makeClient()
authenticate(db)
await POST(request())
const count = mocks.createJournalEntry.mock.calls.length
expect(await (await POST(request())).json()).toEqual({ seeded: false, topped_up: true })
expect(mocks.createJournalEntry).toHaveBeenCalledTimes(count)
})
it('retries a failed seed in a fresh company instead of topping up partial settings', async () => {
const db = makeClient()
authenticate(db)
mocks.createJournalEntry.mockRejectedValueOnce(new Error('posting failed'))
expect((await POST(request())).status).toBe(500)
expect(db.rpc).toHaveBeenLastCalledWith('finish_sandbox_seed', { p_attempt_id: 'attempt-1', p_success: false })
expect((await POST(request())).status).toBe(200)
expect(mocks.createJournalEntry.mock.calls[0][1]).toBe('company-1')
expect(mocks.createJournalEntry.mock.calls.at(-1)?.[1]).toBe('company-2')
})
it('returns 409 to a concurrent request without releasing the first request claim', async () => {
const db = makeClient()
authenticate(db)
let release!: () => void
let entered!: () => void
const posting = new Promise<void>(resolve => { entered = resolve })
mocks.createJournalEntry.mockImplementationOnce(async () => {
entered()
await new Promise<void>(resolve => { release = resolve })
return { id: 'first' }
})
const first = POST(request())
await posting
const second = await POST(request())
expect(second.status).toBe(409)
expect(second.headers.get('Retry-After')).toBe('5')
expect(db.rpc.mock.calls.filter(call => call[0] === 'finish_sandbox_seed')).toHaveLength(0)
release()
expect((await first).status).toBe(200)
})
it('fails closed if claim storage is unavailable', async () => {
const db = makeClient()
authenticate(db)
db.rpc.mockResolvedValueOnce({ data: null, error: null })
expect((await POST(request())).status).toBe(500)
expect(db.from).not.toHaveBeenCalled()
})
it('keeps every engine input inside the seeded period in January', async () => {
vi.setSystemTime(new Date(2026, 0, 3, 12))
authenticate(makeClient())
expect((await POST(request())).status).toBe(200)
for (const call of mocks.createJournalEntry.mock.calls) {
expect(call[3].entry_date >= '2026-01-01').toBe(true)
expect(call[3].entry_date <= '2026-12-31').toBe(true)
}
})
})
@@ -1,122 +0,0 @@
import { describe, it, expect } from 'vitest'
import { buildSandboxSalaryVouchers } from '../salary-vouchers'
const BASE = {
userId: 'user-1',
companyId: 'company-1',
fiscalPeriodId: 'fp-1',
salaryRunId: 'run-1',
paymentDate: '2026-07-25',
periodYear: 2026,
periodMonth: 7,
}
/** Numbers shaped like the seeded run: gross = tax + net, avgifter 31.42%,
* vacation accrual 12% of gross with avgifter on top. */
const TOTALS = {
totalGross: 57600,
totalTax: 16416,
totalNet: 41184,
totalAvgifter: 18097.92,
totalVacationAccrual: 6912,
totalVacationAvgifter: 2171.75,
}
const sum = (ns: number[]) => Math.round(ns.reduce((a, b) => a + b, 0) * 100) / 100
describe('buildSandboxSalaryVouchers', () => {
it('produces the three engine-equivalent vouchers', () => {
const vouchers = buildSandboxSalaryVouchers({ ...BASE, ...TOTALS })
expect(vouchers.map((v) => v.runColumn)).toEqual([
'salary_entry_id',
'avgifter_entry_id',
'vacation_entry_id',
])
})
it('balances every voucher with a non-zero total', () => {
for (const { entry, lines } of buildSandboxSalaryVouchers({ ...BASE, ...TOTALS })) {
const debit = sum(lines.map((l) => l.debit_amount))
const credit = sum(lines.map((l) => l.credit_amount))
expect(debit, `${entry.description} debit vs credit`).toBe(credit)
expect(debit).toBeGreaterThan(0)
}
})
it('books salary on 7210 against 2710 personalskatt and 1930 bank', () => {
const [salary] = buildSandboxSalaryVouchers({ ...BASE, ...TOTALS })
expect(salary.lines).toEqual([
expect.objectContaining({ account_number: '7210', debit_amount: 57600, credit_amount: 0 }),
expect.objectContaining({ account_number: '2710', debit_amount: 0, credit_amount: 16416 }),
expect.objectContaining({ account_number: '1930', debit_amount: 0, credit_amount: 41184 }),
])
})
it('books arbetsgivaravgifter on 7510 against 2731', () => {
const [, avgifter] = buildSandboxSalaryVouchers({ ...BASE, ...TOTALS })
expect(avgifter.lines.map((l) => l.account_number)).toEqual(['7510', '2731'])
})
it('books the vacation accrual on 7290/2920 and its avgifter on 7519/2940', () => {
const [, , vacation] = buildSandboxSalaryVouchers({ ...BASE, ...TOTALS })
expect(vacation.lines.map((l) => l.account_number)).toEqual(['7290', '2920', '7519', '2940'])
expect(vacation.lines.map((l) => l.sort_order)).toEqual([0, 1, 2, 3])
})
it('omits the vacation voucher when nothing accrued (the engine posts no zero voucher)', () => {
const vouchers = buildSandboxSalaryVouchers({
...BASE,
...TOTALS,
totalVacationAccrual: 0,
totalVacationAvgifter: 0,
})
expect(vouchers).toHaveLength(2)
expect(vouchers.some((v) => v.runColumn === 'vacation_entry_id')).toBe(false)
})
it('sets every line dimensions bag explicitly (PostgREST bulk-insert normalization)', () => {
for (const { lines } of buildSandboxSalaryVouchers({ ...BASE, ...TOTALS })) {
for (const line of lines) {
expect(line.dimensions).toEqual({})
}
}
})
it('links salary_payment to the run and leaves posting metadata to the engine', () => {
for (const { entry } of buildSandboxSalaryVouchers({ ...BASE, ...TOTALS })) {
expect(entry.source_type).toBe('salary_payment')
expect(entry.source_id).toBe('run-1')
expect(entry).not.toHaveProperty('status')
expect(entry.entry_date).toBe('2026-07-25')
expect(entry).not.toHaveProperty('committed_at')
expect(entry).not.toHaveProperty('commit_method')
expect(entry.voucher_series).toMatch(/^[A-Z]$/)
expect(entry.description).toContain('2026-07')
}
})
it('account numbers are strings, never numbers', () => {
for (const { lines } of buildSandboxSalaryVouchers({ ...BASE, ...TOTALS })) {
for (const line of lines) {
expect(typeof line.account_number).toBe('string')
}
}
})
it('throws rather than writing an unbalanced verifikat', () => {
expect(() =>
buildSandboxSalaryVouchers({ ...BASE, ...TOTALS, totalNet: 41000 }),
).toThrow(/would not balance/)
})
it('rounds to ore instead of accumulating float drift', () => {
const [salary] = buildSandboxSalaryVouchers({
...BASE,
...TOTALS,
totalGross: 0.1 + 0.2,
totalTax: 0.1,
totalNet: 0.2,
})
expect(salary.lines[0].debit_amount).toBe(0.3)
})
})
File diff suppressed because it is too large Load Diff
@@ -1,125 +0,0 @@
/**
* Explicit opt-in smoke test against the hosted staging branch only.
* SANDBOX_STAGING_ENV_FILE points to its credentials file. Never reads .env.local.
*/
import { readFileSync } from 'node:fs'
import { parse } from 'dotenv'
import { createClient, type SupabaseClient } from '@supabase/supabase-js'
import { beforeAll, describe, expect, it, vi } from 'vitest'
const context = vi.hoisted(() => ({ auth: vi.fn() }))
vi.mock('@/lib/auth/require-auth', () => ({ requireAuth: context.auth }))
vi.mock('@/lib/auth/rate-limit-http', () => ({ checkRateLimit: async () => ({ ok: true }) }))
describe.skipIf(!process.env.SANDBOX_STAGING_ENV_FILE)('hosted staging sandbox', () => {
let client: SupabaseClient
let service: SupabaseClient
let POST: typeof import('../route').POST
beforeAll(async () => {
const env = parse(readFileSync(process.env.SANDBOX_STAGING_ENV_FILE!, 'utf8'))
if (new URL(env.NEXT_PUBLIC_SUPABASE_URL).hostname !== 'metjnjrhvujscngnpzdv.supabase.co') {
throw new Error('Sandbox smoke test only permits the staging branch')
}
if (process.env.SANDBOX_STAGING_SERVICE_ROLE_KEY) {
env.SUPABASE_SERVICE_ROLE_KEY = process.env.SANDBOX_STAGING_SERVICE_ROLE_KEY
}
// Load only after checking the target. Includes the real event handlers.
Object.assign(process.env, env)
POST = (await import('../route')).POST
client = createClient(env.NEXT_PUBLIC_SUPABASE_URL, env.NEXT_PUBLIC_SUPABASE_ANON_KEY, {
auth: { persistSession: false, autoRefreshToken: false },
})
service = createClient(env.NEXT_PUBLIC_SUPABASE_URL, env.SUPABASE_SERVICE_ROLE_KEY, {
auth: { persistSession: false, autoRefreshToken: false },
})
const { error: credentialError } = await service.from('companies').select('id').limit(0)
if (credentialError) throw new Error('A working staging service key is required for event handlers and retention verification')
const { data, error } = await client.auth.signInAnonymously()
if (error || !data.user) throw error ?? new Error('No anonymous staging user')
context.auth.mockResolvedValue({ user: data.user, supabase: client, error: null })
}, 90_000)
it('seeds through real posting guards, links vouchers and repeats without duplicates', async () => {
const start = Date.now()
// These are separate concurrent PostgREST transactions, not an in-memory lock.
const claims = await Promise.all([client.rpc('claim_sandbox_seed'), client.rpc('claim_sandbox_seed')])
expect(claims.every(claim => !claim.error)).toBe(true)
expect(claims.map(claim => claim.data.status).sort()).toEqual(['busy', 'running'])
const owner = claims.find(claim => claim.data.status === 'running')!.data
await client.rpc('finish_sandbox_seed', { p_attempt_id: owner.attempt_id, p_success: false })
// Simulate an interruption AFTER real vouchers committed, before payroll.
const { data: { user: signedIn } } = await client.auth.getUser()
const failingClient = new Proxy(client, {
get(target, property) {
if (property === 'from') return (table: string) => {
if (table === 'salary_runs') return {
insert: () => ({ select: async () => ({ data: null, error: { message: 'Injected payroll interruption' } }) }),
}
return target.from(table)
}
return Reflect.get(target, property)
},
})
context.auth.mockResolvedValueOnce({ user: signedIn, supabase: failingClient, error: null })
expect((await POST(new Request('http://localhost/api/sandbox/seed', { method: 'POST' }))).status).toBe(500)
const { data: failed } = await client.from('sandbox_seed_attempts').select('*').single()
expect(failed.status).toBe('failed')
const { count: preservedCount } = await client.from('journal_entries').select('id', { head: true, count: 'exact' })
.eq('company_id', failed.company_id).eq('status', 'posted')
expect(preservedCount).toBeGreaterThan(0)
const first = await POST(new Request('http://localhost/api/sandbox/seed', { method: 'POST' }))
expect(await first.json()).toEqual({ seeded: true })
expect(first.status).toBe(200)
const { data: attempt, error } = await client.from('sandbox_seed_attempts').select('*').single()
expect(error).toBeNull()
expect(attempt.status).toBe('complete')
expect(attempt.company_id).not.toBe(failed.company_id)
const { data: archived } = await service.from('companies').select('archived_at').eq('id', failed.company_id).single()
expect(archived!.archived_at).toBeTruthy()
const { count: retainedCount } = await service.from('journal_entries').select('id', { head: true, count: 'exact' })
.eq('company_id', failed.company_id).eq('status', 'posted')
expect(retainedCount).toBe(preservedCount)
const { data: entries, error: entriesError } = await client.from('journal_entries')
.select('id, fiscal_period_id, status, committed_at, voucher_number, voucher_series, lines:journal_entry_lines(debit_amount,credit_amount)')
.eq('company_id', attempt.company_id)
expect(entriesError).toBeNull()
expect(entries!.length).toBeGreaterThanOrEqual(5)
const { data: { user } } = await client.auth.getUser()
const { error: invalidDraft } = await client.from('journal_entries').insert({
user_id: user!.id, company_id: attempt.company_id,
fiscal_period_id: entries![0].fiscal_period_id, voucher_number: 0,
entry_date: new Date().toISOString().slice(0, 10), description: 'Rejected test draft',
source_type: 'manual', status: 'draft', committed_at: new Date().toISOString(),
})
expect(invalidDraft?.code).toBe('42501')
for (const entry of entries!) {
expect(entry.status).toBe('posted')
expect(entry.committed_at).toBeTruthy()
expect(entry.voucher_number).toBeGreaterThan(0)
expect(Math.round(entry.lines.reduce((sum, line) => sum + line.debit_amount - line.credit_amount, 0) * 100)).toBe(0)
}
const { data: runs } = await client.from('salary_runs').select('salary_entry_id,avgifter_entry_id,vacation_entry_id')
.eq('company_id', attempt.company_id).eq('status', 'booked')
expect(runs).toHaveLength(1)
expect(Object.values(runs![0]).every(id => entries!.some(entry => entry.id === id))).toBe(true)
const { data: invoice } = await client.from('invoices').select('journal_entry_id')
.eq('company_id', attempt.company_id).eq('invoice_number', 'F-2026001').single()
expect(entries!.some(entry => entry.id === invoice!.journal_entry_id)).toBe(true)
const second = await POST(new Request('http://localhost/api/sandbox/seed', { method: 'POST' }))
expect(second.status).toBe(200)
expect(await second.json()).toEqual({ seeded: false, topped_up: true })
const { count } = await client.from('journal_entries').select('id', { count: 'exact', head: true })
.eq('company_id', attempt.company_id)
expect(count).toBe(entries!.length)
// A complete pre-migration demo has no attempt row. Adopt it without reseeding.
const { error: removeMarker } = await service.from('sandbox_seed_attempts').delete().eq('user_id', user!.id)
expect(removeMarker).toBeNull()
const legacy = await POST(new Request('http://localhost/api/sandbox/seed', { method: 'POST' }))
expect(await legacy.json()).toEqual({ seeded: false, topped_up: true })
const { data: adopted } = await client.from('sandbox_seed_attempts').select('company_id,status').single()
expect(adopted).toMatchObject({ company_id: attempt.company_id, status: 'complete' })
expect(Date.now() - start).toBeLessThan(300_000)
}, 300_000)
})
@@ -1,20 +0,0 @@
import { describe, expect, it } from 'vitest'
import { buildSandboxVatDeadline } from '../vat-deadline'
describe('buildSandboxVatDeadline', () => {
it('uses the August 17 deadline for a Q2 sandbox', () => {
expect(buildSandboxVatDeadline(new Date(2026, 4, 15))).toEqual({
title: 'Momsdeklaration Q2 2026',
dueDate: '2026-08-17',
period: '2026-Q2',
})
})
it('rolls the Q4 deadline into February of the following year', () => {
expect(buildSandboxVatDeadline(new Date(2026, 10, 15))).toEqual({
title: 'Momsdeklaration Q4 2026',
dueDate: '2027-02-12',
period: '2026-Q4',
})
})
})
-124
View File
@@ -1,124 +0,0 @@
/**
* Demo articles (artikelregister) for the sandbox company.
*
* /articles renders the Package empty state in a fresh sandbox, which hides an
* entire surface: reusable invoice-line presets are how most users actually
* build a faktura. Five rows are enough to show the register's shape (numbering,
* vara vs tjanst, unit, price excl VAT, VAT rate, active flag) without turning
* the demo into a catalogue.
*
* Modelled on a one-person Swedish IT/design consultancy (enskild firma), which
* is what the rest of the seed portrays: hourly work on löpande räkning, one
* fixed-price package, one rebilled licence, and one printed book.
*
* VAT rates are law, not decoration:
* - Consulting and design services, the fixed-price package and the rebilled
* software licence are all ordinary 25 % supplies (ML 6 kap.).
* - The printed handbook is 6 %: böcker, broschyrer och häften carry the
* reduced rate (ML 9 kap., the 6 % rates sit in §§ 8-15). No other article
* here qualifies for a reduced rate, so the rest stay at 25 %.
*
* revenue_account is left NULL on every row on purpose: NULL means "derive the
* revenue account from the VAT treatment at line-create time", which is the
* behaviour we want to demonstrate. Pinning an override would freeze a 25 %
* account onto the 6 % book line and misreport ruta 05.
*
* Every row sets every optional column explicitly (null where empty). PostgREST
* normalizes columns across the rows of a bulk insert, so a key present on one
* row and absent on another is sent as NULL rather than falling through to the
* schema default: the same gotcha documented on the journal lines in route.ts.
*/
export interface SandboxArticlesInput {
userId: string
companyId: string
}
export function buildSandboxArticles({ userId, companyId }: SandboxArticlesInput) {
const base = { user_id: userId, company_id: companyId, currency: 'SEK', active: true }
return [
{
...base,
article_number: 'A-001',
name: 'Konsulttimme, systemutveckling',
name_en: 'Consulting hour, software development',
type: 'tjanst',
unit: 'tim',
price_excl_vat: 1150,
vat_rate: 25,
revenue_account: null,
cost_price: null,
ean: null,
housework_type: null,
notes: 'Löpande räkning. Faktureras månadsvis i efterskott.',
},
{
...base,
article_number: 'A-002',
name: 'Konsulttimme, UX och gränssnittsdesign',
name_en: 'Consulting hour, UX and interface design',
type: 'tjanst',
unit: 'tim',
price_excl_vat: 995,
vat_rate: 25,
revenue_account: null,
cost_price: null,
ean: null,
housework_type: null,
notes: 'Löpande räkning. Faktureras månadsvis i efterskott.',
},
{
...base,
article_number: 'A-003',
name: 'Startpaket webbplats, fast pris',
name_en: 'Website starter package, fixed price',
type: 'tjanst',
unit: 'st',
price_excl_vat: 38000,
vat_rate: 25,
revenue_account: null,
cost_price: null,
ean: null,
housework_type: null,
notes: 'Fast pris: design, uppsättning och överlämning. Halva beloppet vid start.',
},
{
...base,
article_number: 'A-004',
name: 'Vidarefakturerad licens, designverktyg (1 plats, 12 mån)',
name_en: 'Rebilled licence, design tool (1 seat, 12 months)',
// A resold licence is a vara in the register's sense: a unit the customer
// buys, not time we spend. cost_price is display/margin only and is never
// posted to the ledger.
type: 'vara',
unit: 'st',
price_excl_vat: 5400,
vat_rate: 25,
revenue_account: null,
cost_price: 4860,
ean: null,
housework_type: null,
notes: 'Inköpspris plus påslag. Faktureras när licensen förnyas.',
},
{
...base,
article_number: 'A-005',
name: 'Handbok: Designsystem i praktiken (tryckt)',
name_en: 'Handbook: Design systems in practice (print)',
type: 'vara',
unit: 'st',
price_excl_vat: 320,
vat_rate: 6,
revenue_account: null,
cost_price: 118,
ean: null,
housework_type: null,
// The one reduced rate in the register, and the reason it is here: a
// printed book is 6 % under ML 9 kap., so the demo shows a mixed-rate
// register instead of a wall of 25 %. The note stays at chapter level:
// a paragraph-precise citation in demo copy is a liability if it drifts.
notes: 'Tryckt bok: 6 % moms enligt ML 9 kap.',
},
]
}
-47
View File
@@ -1,47 +0,0 @@
export function buildSandboxCustomers(userId: string, companyId: string) {
return [
{
user_id: userId,
company_id: companyId,
name: 'Björk & Partner AB',
customer_type: 'swedish_business',
email: '[email protected]',
org_number: '5566778899',
vat_number: 'SE556677889901',
vat_number_validated: true,
address_line1: 'Storgatan 10',
postal_code: '111 44',
city: 'Stockholm',
country: 'SE',
default_payment_terms: 30,
},
{
user_id: userId,
company_id: companyId,
name: 'Schmidt GmbH',
customer_type: 'eu_business',
email: '[email protected]',
org_number: 'HRB 12345',
vat_number: 'DE123456789',
vat_number_validated: true,
address_line1: 'Hauptstraße 5',
postal_code: '10115',
city: 'Berlin',
country: 'DE',
default_payment_terms: 30,
},
{
user_id: userId,
company_id: companyId,
name: 'Anna Lindström',
customer_type: 'individual',
email: '[email protected]',
vat_number_validated: false,
address_line1: 'Lillgatan 3',
postal_code: '222 33',
city: 'Malmö',
country: 'SE',
default_payment_terms: 30,
},
]
}
-13
View File
@@ -1,13 +0,0 @@
/**
* Date helpers shared by the sandbox seed modules. Seed-internal: the seed
* works in local-calendar parts on purpose (no toISOString UTC shift).
*/
export function pad2(n: number): string {
return String(n).padStart(2, '0')
}
/** Last calendar day of a 1-12 month: day 0 of the next month, leap years included. */
export function lastDayOfMonth(year: number, month: number): number {
return new Date(year, month, 0).getDate()
}
-446
View File
@@ -1,446 +0,0 @@
/**
* A month-by-month posted ledger for the sandbox's current fiscal year.
*
* The base seed posts two verifikat, which leaves Resultatrapport, Balansrapport,
* Nyckeltal and momsrapporten looking like a broken page rather than a demo. This
* builder produces the missing year-to-date: January through the month BEFORE
* today's month, at 4 to 7 verifikat per month, for the one-person Swedish
* IT/design consultancy (enskild firma) the rest of the seed portrays.
*
* Pure by construction. `today` is an input, there is no Math.random and no
* Date.now, and every amount is derived from a literal table or a modulo of the
* month index, so the same inputs always produce byte-identical rows and the
* unit test can assert the whole set.
*
* The monthly rhythm:
* day 3 Programvaror (SaaS-verktyg), 25 % ingående moms
* day 8 Mobiltelefon och abonnemang, 25 % ingående moms
* day 12 A rotating larger or periodic cost (some months have none)
* day 20 Kundinbetalning of the PREVIOUS month's faktura (not in January)
* day 25 Konsultarvode, faktura to a customer, 25 % utgående moms
* day 27 Eget uttag (not in January: no cash has come in yet)
* plus, in January only, an owner's capital contribution on day 2. The fiscal
* year is the sandbox company's first period and therefore has no ingående
* balans, so without that contribution konto 1930 would go negative before the
* first customer pays.
*
* Why the result is large: in an enskild firma the owner's own work is NOT a
* cost (compensation happens through egna uttag on 2013, an equity movement),
* so a consultancy billing ~1.1 MSEK legitimately shows a result of roughly the
* same order. That is what a real NE-bilaga looks like.
*
* Accounts are restricted to the set seed_chart_of_accounts activates for
* enskild_firma, so every row in the reports carries its BAS name instead of the
* "Konto 6212" fallback.
*
* The entries carry no posting metadata: the caller posts through the engine
* in array order. It assigns voucher numbers atomically when committing and
* links the lines to their journal entry.
*/
import { roundOre } from '@/lib/money'
import { lastDayOfMonth } from './date-utils'
/**
* Every BAS account this builder can emit. Exported so the seed's
* chart_of_accounts lookup can be widened in one place instead of drifting out
* of sync with the entries below.
*/
export const SANDBOX_LEDGER_ACCOUNT_NUMBERS: readonly string[] = [
'1510', // Kundfordringar
'1930', // Företagskonto / checkkonto
'2013', // Övriga egna uttag
'2018', // Övriga egna insättningar
'2611', // Utgående moms försäljning inom Sverige, 25 %
'2641', // Debiterad ingående moms
'2650', // Redovisningskonto för moms
'3001', // Försäljning inom Sverige, 25 % moms
'5410', // Förbrukningsinventarier
'5420', // Programvaror
'5460', // Förbrukningsmaterial
'5800', // Resekostnader
'5910', // Annonsering
'6110', // Kontorsmateriel
'6212', // Mobiltelefon
'6230', // Datakommunikation
'6530', // Redovisningstjänster
'6570', // Bankavgifter
]
export interface SandboxLedgerHistoryInput {
userId: string
companyId: string
fiscalPeriodId: string
/** "Now" as the seed sees it. The history stops at the end of the previous month. */
today: Date
/** account_number to chart_of_accounts.id. Missing entries fall back to null. */
accountMap: Record<string, string | undefined>
}
/** A journal_entries row WITHOUT voucher_number: the caller assigns that. */
export interface SandboxLedgerEntryRow {
user_id: string
company_id: string
fiscal_period_id: string
voucher_series: string
entry_date: string
description: string
source_type: 'manual'
source_id: null
}
/** A journal_entry_lines row WITHOUT journal_entry_id: the caller fills it in. */
export interface SandboxLedgerLineRow {
account_number: string
account_id: string | null
debit_amount: number
credit_amount: number
line_description: string
sort_order: number
/**
* Always set, never omitted. PostgREST normalizes columns across a bulk
* insert, so a row missing the key while a sibling sets it sends NULL and
* violates the NOT NULL on journal_entry_lines.dimensions.
*/
dimensions: Record<string, string>
}
export interface SandboxLedgerHistory {
entries: SandboxLedgerEntryRow[]
/** linesByEntryIndex[i] belongs to entries[i]. */
linesByEntryIndex: SandboxLedgerLineRow[][]
}
/**
* 'manual' is the only allowed source_type that dereferences nothing: every
* other candidate ('invoice_created', 'bank_transaction', ...) makes the voucher
* detail view look for a source row that this history does not have. The value
* must come from the journal_entries_source_type_check allowlist (see
* 20260712100500_journal_source_type_stripe_payout.sql).
*/
const SOURCE_TYPE = 'manual'
const VOUCHER_SERIES = 'A'
const MONTH_NAMES_SV = [
'januari',
'februari',
'mars',
'april',
'maj',
'juni',
'juli',
'augusti',
'september',
'oktober',
'november',
'december',
]
/** Billed hours per month. July is semester, autumn is the busy season. */
const CONSULTING_HOURS = [96, 104, 120, 112, 108, 88, 40, 72, 116, 124, 118, 84]
const HOURLY_RATE = 950
/** Owner's opening capital contribution, January only. */
const OWNER_CONTRIBUTION = 60000
interface PeriodicCost {
accountNumber: string
description: string
/** Amount excluding VAT. */
net: number
/** Integer percent. 0 means a VAT-exempt supply: no 2641 line at all. */
vatRate: number
}
/**
* The day-12 cost, by month index (0 = January). null means the month has none,
* which is what makes it read as occasional rather than as a subscription.
*
* VAT rates follow the supply, not the account: persontransport inom Sverige is
* 6 % and hotellrum 12 % (ML 9 kap.), and banktjänster are undantagna från
* moms (ML 10 kap. 33 §), so the December bank fee books gross with no input
* VAT. Deductible input VAT always lands on 2641 regardless of the rate.
*/
const PERIODIC_COSTS: Array<PeriodicCost | null> = [
null,
{ accountNumber: '5910', description: 'Annonsering, kampanj sociala medier', net: 2400, vatRate: 25 },
{ accountNumber: '6530', description: 'Redovisningskonsult, avstämning inför deklaration', net: 6500, vatRate: 25 },
{ accountNumber: '6230', description: 'Bredband kontorsplats, första halvåret', net: 1490, vatRate: 25 },
{ accountNumber: '5800', description: 'Tågbiljetter, kundmöten Göteborg', net: 1480, vatRate: 6 },
{ accountNumber: '5410', description: 'Extern skärm och dockningsstation', net: 4990, vatRate: 25 },
null,
{ accountNumber: '6110', description: 'Kontorsmateriel', net: 780, vatRate: 25 },
{ accountNumber: '5800', description: 'Hotell, kundprojekt Malmö', net: 3950, vatRate: 12 },
{ accountNumber: '6230', description: 'Bredband kontorsplats, andra halvåret', net: 1490, vatRate: 25 },
{ accountNumber: '5460', description: 'Förbrukningsmaterial, kontor', net: 1150, vatRate: 25 },
{ accountNumber: '6570', description: 'Bankavgifter, årsavgift företagskonto', net: 1200, vatRate: 0 },
]
/** Internal line shape: exactly one of debit/credit is set. */
interface LineSpec {
accountNumber: string
debit?: number
credit?: number
lineDescription: string
dimensions?: Record<string, string>
}
/** yyyy-MM-dd from calendar parts. Avoids toISOString(), which shifts to UTC. */
function dateStr(year: number, month: number, day: number): string {
return `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`
}
function vatOf(net: number, vatRate: number): number {
return roundOre((net * vatRate) / 100)
}
/**
* Deterministic per-month variation. `(month * factor) % cycle` walks the cycle
* in a non-obvious order, so the amounts look hand-entered without any
* randomness: the builder must be reproducible.
*/
function vary(base: number, month: number, factor: number, cycle: number, step: number): number {
return roundOre(base + (((month * factor) % cycle) * step))
}
/**
* Revenue-line dimension bag, by month. Three-month cycle so the dimension P&L
* report has data on both kostnadsställe/projekt pairs the seed creates AND a
* meaningful untagged remainder. Every other line in the history is untagged.
*/
function revenueDimensions(month: number): Record<string, string> {
const phase = month % 3
if (phase === 1) return { '1': 'BUTIK', '6': 'P001' }
if (phase === 2) return { '1': 'WEBB', '6': 'P002' }
return {}
}
export function buildSandboxLedgerHistory({
userId,
companyId,
fiscalPeriodId,
today,
accountMap,
}: SandboxLedgerHistoryInput): SandboxLedgerHistory {
const year = today.getFullYear()
/** 1-based; the history covers January through the month before this one. */
const lastMonth = today.getMonth()
const entries: SandboxLedgerEntryRow[] = []
const linesByEntryIndex: SandboxLedgerLineRow[][] = []
/**
* Running VAT, so the quarterly momsredovisning below settles the exact
* amounts the period's own entries produced rather than a re-derivation.
*/
let quarterOutputVat = 0
let quarterInputVat = 0
const accountId = (accountNumber: string): string | null =>
accountMap[accountNumber] ?? null
function addEntry(entryDate: string, description: string, lines: LineSpec[]): void {
entries.push({
user_id: userId,
company_id: companyId,
fiscal_period_id: fiscalPeriodId,
voucher_series: VOUCHER_SERIES,
entry_date: entryDate,
description,
source_type: SOURCE_TYPE,
source_id: null,
})
linesByEntryIndex.push(
lines.map((line, index) => ({
account_number: line.accountNumber,
account_id: accountId(line.accountNumber),
debit_amount: roundOre(line.debit ?? 0),
credit_amount: roundOre(line.credit ?? 0),
line_description: line.lineDescription,
sort_order: index,
dimensions: line.dimensions ?? {},
})),
)
}
/** Dr cost (+ Dr 2641), Cr 1930. The bank pays it the day it happens. */
function addBankPaidCost(entryDate: string, cost: PeriodicCost): void {
const vat = vatOf(cost.net, cost.vatRate)
const gross = roundOre(cost.net + vat)
const lines: LineSpec[] = [
{ accountNumber: cost.accountNumber, debit: cost.net, lineDescription: cost.description },
]
if (vat > 0) {
quarterInputVat = roundOre(quarterInputVat + vat)
lines.push({
accountNumber: '2641',
debit: vat,
lineDescription: `Ingående moms ${cost.vatRate} %`,
})
}
lines.push({
accountNumber: '1930',
credit: gross,
lineDescription: 'Betalt från företagskontot',
})
addEntry(entryDate, cost.description, lines)
}
/**
* Close one VAT quarter: clear 2611 and 2641 into 2650, then pay 2650 from
* the bank on the SFL 26 kap. 26 § deadline.
*
* Without this the sandbox reads as a company that has collected VAT all
* year and never remitted a krona: the moms liability and the bank balance
* both climb without limit, and every cash KPI derived from them is
* nonsense. The company files quarterly (company_settings.moms_period =
* 'quarterly'), so each quarter is declared after it closes and paid on the
* 12th of the second month after it.
*/
/** Payments owed but not yet emitted, keyed by the month they fall due. */
const vatPaymentsDue = new Map<number, { amount: number; label: string }>()
function declareVatQuarter(quarterEndMonth: number, paymentMonth: number, label: string): void {
const output = quarterOutputVat
const input = quarterInputVat
quarterOutputVat = 0
quarterInputVat = 0
const netPayable = roundOre(output - input)
// A refund quarter would need the opposite sign on 2650 and a bank
// deposit. This history is comfortably output-heavy every quarter, so
// rather than emit a voucher whose direction was never exercised, skip.
if (netPayable <= 0) return
// 2611 debit + 2641 credit + 2650 is the shape get_vat_declaration_totals
// classifies as a momsredovisning and drops from the period's totals, which
// is exactly right: a settlement must not feed the next declaration.
addEntry(
dateStr(year, quarterEndMonth, lastDayOfMonth(year, quarterEndMonth)),
`Momsredovisning ${label}`,
[
{ accountNumber: '2611', debit: output, lineDescription: 'Utgående moms för perioden' },
{ accountNumber: '2641', credit: input, lineDescription: 'Ingående moms för perioden' },
{ accountNumber: '2650', credit: netPayable, lineDescription: 'Redovisningskonto för moms' },
],
)
vatPaymentsDue.set(paymentMonth, { amount: netPayable, label })
}
/**
* Emitted from inside the payment month's own block, never from the quarter
* close: a 12 May voucher appended while building March would put the entry
* list out of date order, and the caller assigns voucher numbers in array
* order (BFNAR 2013:2 expects the sequence to follow the books).
*/
function payVatIfDue(month: number): void {
const due = vatPaymentsDue.get(month)
if (!due) return
vatPaymentsDue.delete(month)
addEntry(dateStr(year, month, 12), `Betald moms ${due.label}`, [
{ accountNumber: '2650', debit: due.amount, lineDescription: 'Redovisningskonto för moms' },
{ accountNumber: '1930', credit: due.amount, lineDescription: 'Betalt till skattekontot' },
])
}
for (let month = 1; month <= lastMonth; month++) {
const monthName = MONTH_NAMES_SV[month - 1]
const hours = CONSULTING_HOURS[month - 1]
const revenueNet = hours * HOURLY_RATE
const revenueVat = vatOf(revenueNet, 25)
const revenueGross = roundOre(revenueNet + revenueVat)
// ── day 2, January only: owner funds the business ────────────────────
// The fiscal year is the company's first period, so there is no ingående
// balans on 1930. Without this the bank account goes negative in January.
if (month === 1) {
addEntry(dateStr(year, month, 2), 'Egen insättning, startkapital', [
{ accountNumber: '1930', debit: OWNER_CONTRIBUTION, lineDescription: 'Insättning på företagskontot' },
{ accountNumber: '2018', credit: OWNER_CONTRIBUTION, lineDescription: 'Övriga egna insättningar' },
])
}
// ── day 3: software subscriptions ────────────────────────────────────
addBankPaidCost(dateStr(year, month, 3), {
accountNumber: '5420',
description: `Programvaror, molntjänster ${monthName}`,
net: vary(890, month, 7, 5, 60),
vatRate: 25,
})
// ── day 8: mobile and subscription ───────────────────────────────────
addBankPaidCost(dateStr(year, month, 8), {
accountNumber: '6212',
description: `Mobiltelefon och abonnemang, ${monthName}`,
net: vary(429, month, 5, 4, 35),
vatRate: 25,
})
// ── day 12: the rotating larger or periodic cost ─────────────────────
const periodic = PERIODIC_COSTS[month - 1]
if (periodic) {
addBankPaidCost(dateStr(year, month, 12), periodic)
}
// ── day 12: the previous quarter's moms leaves the bank ──────────────
// SFL 26 kap. 26 §: a quarterly filer declares and pays on the 12th of
// the second month after the period.
payVatIfDue(month)
// ── day 20: the previous month's faktura is paid ─────────────────────
// 30 day terms, so January has nothing to collect.
if (month > 1) {
const previousMonthName = MONTH_NAMES_SV[month - 2]
const previousNet = CONSULTING_HOURS[month - 2] * HOURLY_RATE
const previousGross = roundOre(previousNet + vatOf(previousNet, 25))
addEntry(
dateStr(year, month, 20),
`Kundinbetalning, konsultarvode ${previousMonthName}`,
[
{ accountNumber: '1930', debit: previousGross, lineDescription: 'Insättning på företagskontot' },
{ accountNumber: '1510', credit: previousGross, lineDescription: 'Kvittad kundfordran' },
],
)
}
// ── day 25: the month's consulting invoice ───────────────────────────
addEntry(
dateStr(year, month, 25),
`Faktura, konsultarvode ${monthName} (${hours} tim)`,
[
{ accountNumber: '1510', debit: revenueGross, lineDescription: 'Kundfordran' },
{
accountNumber: '3001',
credit: revenueNet,
lineDescription: `Konsultarvode ${hours} tim à ${HOURLY_RATE} kr`,
dimensions: revenueDimensions(month),
},
{ accountNumber: '2611', credit: revenueVat, lineDescription: 'Utgående moms 25 %' },
],
)
quarterOutputVat = roundOre(quarterOutputVat + revenueVat)
// ── day 27: eget uttag ───────────────────────────────────────────────
// Enskild firma: the owner is not an employee, so their compensation is an
// equity withdrawal on 2013, never a personnel cost. Skipped in January for
// the same cash reason as the customer payment.
if (month > 1) {
const withdrawal = vary(38000, month, 3, 4, 4000)
addEntry(dateStr(year, month, 27), `Eget uttag, ${monthName}`, [
{ accountNumber: '2013', debit: withdrawal, lineDescription: 'Övriga egna uttag' },
{ accountNumber: '1930', credit: withdrawal, lineDescription: 'Uttag från företagskontot' },
])
}
// ── quarter close: declare and pay the moms the quarter produced ──────
// Emitted inside the loop rather than appended afterwards so the
// verifikat stay in date order, which is what the voucher numbering the
// caller assigns will follow.
if (month === 3) declareVatQuarter(3, 5, `${year} Q1`)
if (month === 6) declareVatQuarter(6, 8, `${year} Q2`)
if (month === 9) declareVatQuarter(9, 11, `${year} Q3`)
}
return { entries, linesByEntryIndex }
}
-144
View File
@@ -1,144 +0,0 @@
/**
* Pre-staged pending_operations for the sandbox, so /pending isn't empty.
*
* These are the kind of operation the AI agent would stage; pre-seeded so the
* demo user can see the approval queue UI (preview, period status, risk level)
* without invoking the AI, which the sandbox blocks outright.
*
* Two shapes have to be right or the row is worse than absent:
* params: executor-complete. The commit executors in
* lib/pending-operations/commit.ts validate required fields on "Godkänn",
* so a display-only preview with a hollow params object fails to save.
* preview_data: whatever the operation's preview component in
* app/(dashboard)/pending/page.tsx actually reads. Most types fall through
* to GenericPreview, which renders a kontering under `preview_lines`;
* categorize_transaction has a dedicated CategorizePreview that reads
* `lines` + a summary `amount` instead.
*
* Extracted from route.ts so both shapes are assertable in a unit test: the
* seed handler itself is one long Supabase-bound function.
*/
export interface SandboxPendingOperationsInput {
userId: string
companyId: string
/** invoice_inbox_items row the supplier-invoice operation converts. */
inboxItemId: string
supplierId: string
invoiceDate: string
dueDate: string
/** The uncategorized 1 200 kr bankgiro deposit. */
transactionId: string
}
export function buildSandboxPendingOperations({
userId,
companyId,
inboxItemId,
supplierId,
invoiceDate,
dueDate,
transactionId,
}: SandboxPendingOperationsInput) {
return [
{
user_id: userId,
company_id: companyId,
operation_type: 'create_supplier_invoice_from_inbox',
status: 'pending',
// actor_type='agent_chat' + risk_level on the row itself is required by
// pending_operations_chat_insert (the only RLS policy that lets a
// user-scoped client INSERT into this table).
actor_type: 'agent_chat',
risk_level: 'low',
// Uses a distinct supplier_invoice_number so approving this pending
// operation creates a NEW supplier_invoices row instead of colliding
// with the Demokafé '88245' already booked by the seed (BFL 5 kap: each
// affärshändelse must be recorded exactly once).
title: 'Registrera leverantörsfaktura, Demokafé (representation, nytt underlag)',
// Mirrors what gnubok_create_supplier_invoice_from_inbox would stage:
// every field commitCreateSupplierInvoiceFromInbox requires
// (inbox_item_id, supplier_id, supplier_invoice_number, invoice_date,
// finite subtotal/vat_amount/total, and a non-empty items array).
params: {
inbox_item_id: inboxItemId,
supplier_id: supplierId,
document_id: null,
supplier_invoice_number: 'INKOMMANDE-2026-001',
invoice_date: invoiceDate,
due_date: dueDate,
currency: 'SEK',
exchange_rate: null,
vat_treatment: 'reduced_12',
subtotal: 240,
vat_amount: 28.80,
total: 268.80,
notes: 'Representation, kundmöte (demo)',
items: [
{
line_number: 1,
description: 'Kundmöte Demokafé (representation)',
quantity: 1,
unit: 'st',
unit_price: 240,
line_total: 240,
account_number: '5810',
vat_rate: 12,
vat_amount: 28.80,
},
],
},
preview_data: {
// Representation @ 12% VAT (café meal), 240 SEK excl. VAT for a single
// attendee. The avdragsrätt cap is 25% × 300 SEK × antal_personer =
// 75 SEK / person (ML 8 kap. 9 §); since the VAT here is 28.80 SEK the
// full amount is deductible and the cost lands in 5810: no split.
// GenericPreview renders this key, so the `account`/`debit`/`credit`
// spelling is the right one here.
preview_lines: [
{ account: '5810', description: 'Representation (12% moms, ≤ 75 SEK moms/pers)', debit: 240, credit: 0 },
{ account: '2641', description: 'Ingående moms', debit: 28.80, credit: 0 },
{ account: '2440', description: 'Leverantörsskulder', debit: 0, credit: 268.80 },
],
},
},
{
user_id: userId,
company_id: companyId,
operation_type: 'categorize_transaction',
status: 'pending',
actor_type: 'agent_chat',
risk_level: 'low',
title: 'Bokför insättning, bankgiro',
// commitCategorizeTransaction needs a real uncategorized transaction_id
// + a category that resolves to an account mapping. income_services →
// 3001 (Försäljning tjänster 25%), matching the 1930 / 2611 / 3001 split
// below for the 1 200 kr deposit.
params: {
transaction_id: transactionId,
category: 'income_services',
vat_treatment: 'standard_25',
},
// CategorizePreview reads `lines`, NOT the generic `preview_lines` the
// operation above uses. Seeding the generic shape here dropped the card
// onto its legacy summary branch: blank Debetkonto/Kreditkonto and
// "NaN kr" from formatCurrency(undefined) on the missing `amount`.
// Mirror exactly what gnubok_categorize_transaction stages.
preview_data: {
debit_account: '1930',
credit_account: '3001',
amount: 1200,
currency: 'SEK',
lines: [
{ account_number: '1930', debit_amount: 1200, credit_amount: 0, description: 'Företagskonto' },
{ account_number: '2611', debit_amount: 0, credit_amount: 240, description: 'Utgående moms 25%' },
{ account_number: '3001', debit_amount: 0, credit_amount: 960, description: 'Försäljning 25% moms' },
],
vat_lines: [
{ account_number: '2611', debit_amount: 0, credit_amount: 240, description: 'Utgående moms 25%' },
],
category: 'income_services',
},
},
]
}
File diff suppressed because it is too large Load Diff
-241
View File
@@ -1,241 +0,0 @@
/**
* Journal entries for the sandbox's BOOKED salary run.
*
* A run in status 'booked' that produced no verifikat would be a lie: in the
* real product `bookPaidSalaryRun` posts 2-4 entries through the bookkeeping
* engine before it advances the status. This module mirrors the account structure
* of `createSalaryRunEntries` in lib/salary/salary-entries.ts instead.
*
* Accounts come from SALARY_ACCOUNTS (lib/salary/account-mapping.ts), not from
* literals here, so a future BAS remap moves the seed with the engine.
*
* Pure builders, in the same style as ./customers.ts and ./pending-operations.ts:
* the caller posts through the engine and links the returned journal entry IDs.
*/
import { SALARY_ACCOUNTS } from '@/lib/salary/account-mapping'
/** Money rounding, per the project rule: never toFixed(). */
const ore = (n: number) => Math.round(n * 100) / 100
/**
* Every account these vouchers can touch, for the seed's chart-of-accounts
* check. seed_chart_of_accounts only lays down its 7xxx personnel block for
* aktiebolag, and the sandbox company is an enskild firma, so all of these are
* missing until the seed creates them.
*
* Derived from SALARY_ACCOUNTS rather than listed, so it cannot fall behind the
* account map. SICK_PAY and VACATION_PAY are in the map but unused by this
* seed; including them is harmless (the account simply exists in the chart) and
* keeps the list free of a hand-maintained subset.
*/
export const SANDBOX_SALARY_ACCOUNT_NUMBERS: readonly string[] =
Object.values(SALARY_ACCOUNTS)
export interface SalaryVoucherTotals {
/** Sum of gross_salary across the run's employees. */
totalGross: number
/** Sum of tax_withheld. */
totalTax: number
/** Sum of net_salary. */
totalNet: number
/** Sum of avgifter_amount (arbetsgivaravgifter on the payroll). */
totalAvgifter: number
/** Sum of vacation_accrual (semesterlöneskuld change). */
totalVacationAccrual: number
/** Sum of vacation_accrual_avgifter (avgifter on the accrued vacation). */
totalVacationAvgifter: number
}
export interface SalaryVoucherInput extends SalaryVoucherTotals {
userId: string
companyId: string
fiscalPeriodId: string
salaryRunId: string
/** ISO date the run pays out on; the entry date for all three vouchers. */
paymentDate: string
periodYear: number
periodMonth: number
}
export interface SeedJournalLine {
account_number: string
debit_amount: number
credit_amount: number
sort_order: number
/** Always set explicitly: PostgREST normalizes columns across a bulk insert,
* so omitting it on some rows while another row sets it sends null and
* violates NOT NULL instead of falling through to the '{}' default. */
dimensions: Record<string, string>
}
export interface SeedJournalEntry {
user_id: string
company_id: string
fiscal_period_id: string
entry_date: string
description: string
source_type: 'salary_payment'
source_id: string
voucher_series: string
}
export interface SalaryVoucher {
entry: SeedJournalEntry
lines: SeedJournalLine[]
/** Which salary_runs column should point at this entry once it is inserted. */
runColumn: 'salary_entry_id' | 'avgifter_entry_id' | 'vacation_entry_id'
}
/**
* Build the vouchers for one booked salary run.
*
* Entry 1 (lön): D 7210 brutto / C 2710 personalskatt + C 1930 netto
* Entry 2 (avgifter): D 7510 sociala avgifter / C 2731 avräkning sociala avgifter
* Entry 3 (semester): D 7290 + D 7519 / C 2920 + C 2940
*
* Entry 3 is omitted when the run accrued no vacation, mirroring the engine
* (a zero-amount voucher would violate the balance trigger's "total > 0").
*
* Throws when gross != tax + net. That identity holds for the seeded run
* (no benefits, no gross or net deductions), and an unbalanced verifikat must
* fail loudly rather than reach the ledger.
*/
export function buildSandboxSalaryVouchers(input: SalaryVoucherInput): SalaryVoucher[] {
const {
userId,
companyId,
fiscalPeriodId,
salaryRunId,
paymentDate,
periodYear,
periodMonth,
totalGross,
totalTax,
totalNet,
totalAvgifter,
totalVacationAccrual,
totalVacationAvgifter,
} = input
const gross = ore(totalGross)
const tax = ore(totalTax)
const net = ore(totalNet)
const avgifter = ore(totalAvgifter)
const vacation = ore(totalVacationAccrual)
const vacationAvgifter = ore(totalVacationAvgifter)
if (ore(tax + net) !== gross) {
throw new Error(
`Sandbox salary voucher would not balance: gross ${gross} != tax ${tax} + net ${net}`,
)
}
const periodLabel = `${periodYear}-${String(periodMonth).padStart(2, '0')}`
const base = {
user_id: userId,
company_id: companyId,
fiscal_period_id: fiscalPeriodId,
entry_date: paymentDate,
source_type: 'salary_payment' as const,
source_id: salaryRunId,
voucher_series: 'A',
}
const vouchers: SalaryVoucher[] = [
{
runColumn: 'salary_entry_id',
entry: { ...base, description: `Lön ${periodLabel}` },
lines: [
{
account_number: SALARY_ACCOUNTS.SALARY_EMPLOYEE,
debit_amount: gross,
credit_amount: 0,
sort_order: 0,
dimensions: {},
},
{
account_number: SALARY_ACCOUNTS.TAX_WITHHELD,
debit_amount: 0,
credit_amount: tax,
sort_order: 1,
dimensions: {},
},
{
account_number: SALARY_ACCOUNTS.BANK,
debit_amount: 0,
credit_amount: net,
sort_order: 2,
dimensions: {},
},
],
},
{
runColumn: 'avgifter_entry_id',
entry: { ...base, description: `Lön ${periodLabel}: arbetsgivaravgifter` },
lines: [
{
account_number: SALARY_ACCOUNTS.AVGIFTER_EXPENSE,
debit_amount: avgifter,
credit_amount: 0,
sort_order: 0,
dimensions: {},
},
{
account_number: SALARY_ACCOUNTS.AVGIFTER_LIABILITY,
debit_amount: 0,
credit_amount: avgifter,
sort_order: 1,
dimensions: {},
},
],
},
]
if (vacation > 0 || vacationAvgifter > 0) {
const lines: SeedJournalLine[] = []
if (vacation > 0) {
lines.push(
{
account_number: SALARY_ACCOUNTS.VACATION_ACCRUAL_EXPENSE,
debit_amount: vacation,
credit_amount: 0,
sort_order: lines.length,
dimensions: {},
},
{
account_number: SALARY_ACCOUNTS.VACATION_ACCRUAL_LIABILITY,
debit_amount: 0,
credit_amount: vacation,
sort_order: lines.length + 1,
dimensions: {},
},
)
}
if (vacationAvgifter > 0) {
lines.push(
{
account_number: SALARY_ACCOUNTS.VACATION_AVGIFTER_EXPENSE,
debit_amount: vacationAvgifter,
credit_amount: 0,
sort_order: lines.length,
dimensions: {},
},
{
account_number: SALARY_ACCOUNTS.VACATION_AVGIFTER_LIABILITY,
debit_amount: 0,
credit_amount: vacationAvgifter,
sort_order: lines.length + 1,
dimensions: {},
},
)
}
vouchers.push({
runColumn: 'vacation_entry_id',
entry: { ...base, description: `Lön ${periodLabel}: semesterlöneskuld` },
lines,
})
}
return vouchers
}
File diff suppressed because it is too large Load Diff
-33
View File
@@ -1,33 +0,0 @@
import { getVatDeadlineForPeriod } from '@/lib/tax/deadline-config'
import { adjustDeadlineToNextBankingDay } from '@/lib/tax/swedish-holidays'
export interface SandboxVatDeadline {
title: string
dueDate: string
period: string
}
/** Build the current quarter's canonical, banking-day-adjusted sandbox deadline. */
export function buildSandboxVatDeadline(today: Date): SandboxVatDeadline {
const year = today.getFullYear()
const quarter = Math.floor(today.getMonth() / 3) + 1
const rawDeadline = getVatDeadlineForPeriod('quarterly', year, quarter, {
vat_taxable_base_over_40m: false,
})
if (!rawDeadline) throw new Error('Could not resolve sandbox VAT deadline')
const deadline = adjustDeadlineToNextBankingDay(
new Date(rawDeadline.year, rawDeadline.month, rawDeadline.day),
)
const dueDate = [
deadline.getFullYear(),
String(deadline.getMonth() + 1).padStart(2, '0'),
String(deadline.getDate()).padStart(2, '0'),
].join('-')
return {
title: `Momsdeklaration Q${quarter} ${year}`,
dueDate,
period: `${year}-Q${quarter}`,
}
}