Files
accounted/lib/reports/__tests__/sie-export.test.ts
T
Jakob Wennberg cc351158f8 Invoicing & account-security polish bundle (#550)
* feat: invoicing & account-security polish bundle

Five independent improvements bundled to ship together:

- BankID/password lockout fix: BankID-only users could enroll MFA and
  brick themselves (Supabase requires AAL2 to change password or unenroll
  MFA, and AAL2 needs a password sign-in). New app_metadata.has_password
  flag tracks this; middleware gates /mfa/enroll behind it, /account/set-
  password is the unlock path, SecuritySettings shows a banner, and
  /api/account/password is the single write path that flips the flag.
  Backfill script for existing users.

- Swish invoice payment method: company_settings.swish + invoice_show_swish
  columns, validation in lib/api/schemas.ts (accepts 123XXXXXXX företag or
  07XXXXXXXX mobile, strips whitespace/hyphens), rendered on invoice PDFs.

- Send-reminders kill switch: per-company company_settings.send_invoice_
  reminders toggle in PdfPrintSettings/Automatisering. Reminder processor
  also tightened: positive status allowlist (sent + overdue) so terminal
  statuses can never match; skip when customer already responded via
  reminder link; race-window re-check before send.

- First-invoice logo prompt: one-shot dialog when creating the first
  invoice without a logo (issue #520). Self-limits via head-only count.

- SIE export opening-balance fallback: route IB through getOpeningBalances
  so the compute_prior_opening_balances RPC supplies #IB after multi-year
  imports where opening_balance_entry_id is intentionally NULL. Previously
  #IB silently went to zero and #UB collapsed to current-period movements.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(account-polish): address PR review feedback

- BankID-link path (extensions/general/tic/index.ts): read-merge-write
  app_metadata instead of passing { bankid_linked: true } alone.
  updateUserById REPLACES app_metadata wholesale, so the previous code
  would have wiped has_password for any user who later linked BankID,
  causing the set-password banner to (incorrectly) reappear and blocking
  the standard MFA enrollment button. The comment is now corrected.

- Middleware (lib/supabase/middleware.ts): thread inner returnTo through
  the /mfa/enroll → /account/set-password redirect so the user lands on
  their original destination after the full chain completes, not on /.

- safeReturnTo helper (lib/auth/safe-return-to.ts): replace the
  starts-with-/-but-not-// guard on mfa/enroll and set-password pages.
  The previous guard let /\evil.com and /@evil.com through. The new
  helper parses against a synthetic base origin and verifies it matches.

- set-password page (app/(auth)/account/set-password/page.tsx): remove
  CLAUDE.md design system violations — bg-gradient-to-b on page bg,
  inline shadow-md style on the card, space-y-5, font-medium on the h1,
  rounded-xl on the card. Flat surface, hairline border, font-display
  h1 per the design tokens.

- Swish dedup (lib/payments/swish.ts): extract normaliseSwish() and
  isValidSwish() helpers and use them in lib/api/schemas.ts,
  components/settings/BankDetailsForm.tsx, and the invoicing settings
  page. Single source of truth for the regex.

- Password route (app/api/account/password/route.ts): emit a structured
  success log so the audit pipeline can detect password-set events, not
  just failures.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-21 16:44:09 +02:00

427 lines
16 KiB
TypeScript

import { describe, it, expect, vi, beforeEach } from 'vitest'
// ============================================================
// Mock — sequential result queue
// ============================================================
let resultIdx: number
let results: Array<{ data?: unknown; error?: unknown }>
function makeBuilder() {
const b: Record<string, unknown> = {}
for (const m of ['select', 'eq', 'in', 'order', 'range', 'lt', 'lte', 'gte', 'gt', 'limit']) {
b[m] = vi.fn().mockReturnValue(b)
}
b.single = vi.fn().mockImplementation(async () => results[resultIdx++] ?? { data: null, error: null })
b.then = (resolve: (v: unknown) => void) => resolve(results[resultIdx++] ?? { data: null, error: null })
return b
}
function makeClient() {
return {
from: vi.fn().mockImplementation(() => makeBuilder()),
// `rpc` drains the same queue so tests can intersperse RPC + table fetches.
// SIE export calls `compute_prior_opening_balances` via getOpeningBalances
// whenever `opening_balance_entry_id` is null (the multi-year-import path).
rpc: vi.fn().mockImplementation(async () => results[resultIdx++] ?? { data: null, error: null }),
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} as any
}
import { generateSIEExport } from '../sie-export'
let supabase: ReturnType<typeof makeClient>
beforeEach(() => {
vi.clearAllMocks()
resultIdx = 0
results = []
supabase = makeClient()
})
const baseOptions = {
fiscal_period_id: 'period-1',
company_name: 'Test AB',
org_number: '556677-8899',
program_name: 'ERPBase',
}
describe('generateSIEExport', () => {
it('throws when fiscal period not found', async () => {
results = [
// 0: fiscal_periods.single() → null
{ data: null, error: null },
]
await expect(generateSIEExport(supabase, 'company-1', baseOptions))
.rejects.toThrow('Fiscal period not found')
})
it('generates correct header format', async () => {
results = [
// 0: fiscal_periods
{ data: { id: 'period-1', period_start: '2024-01-01', period_end: '2024-12-31' }, error: null },
// 1: previous fiscal period (#RAR -1)
{ data: null, error: null },
// 2: chart_of_accounts (empty)
{ data: [], error: null },
// 3: journal_entries (empty)
{ data: [], error: null },
// 4: cost_centers (empty)
{ data: [], error: null },
// 5: projects (empty)
{ data: [], error: null },
// 6: compute_prior_opening_balances RPC (empty — no IB)
{ data: [], error: null },
]
const output = await generateSIEExport(supabase, 'company-1', baseOptions)
const lines = output.split('\r\n')
expect(lines[0]).toBe('#FLAGGA 0')
expect(lines[1]).toBe('#FORMAT PC8')
expect(lines[2]).toBe('#SIETYP 4')
expect(lines[3]).toMatch(/^#PROGRAM "ERPBase" "1\.0"$/)
expect(lines[4]).toMatch(/^#GEN \d{8}$/)
expect(lines[5]).toBe('#ORGNR 556677-8899')
expect(lines[6]).toBe('#FNAMN "Test AB"')
expect(lines[7]).toBe('#RAR 0 20240101 20241231')
})
it('omits #ORGNR when org_number is null', async () => {
results = [
{ data: { id: 'period-1', period_start: '2024-01-01', period_end: '2024-12-31' }, error: null },
{ data: null, error: null }, // prevPeriod
{ data: [], error: null },
{ data: [], error: null },
{ data: [], error: null },
{ data: [], error: null },
{ data: [], error: null }, // RPC fallback
]
const output = await generateSIEExport(supabase, 'company-1', {
...baseOptions,
org_number: null,
})
expect(output).not.toContain('#ORGNR')
})
it('generates #KONTO and #SRU for accounts', async () => {
results = [
{ data: { id: 'period-1', period_start: '2024-01-01', period_end: '2024-12-31' }, error: null },
{ data: null, error: null }, // prevPeriod
{
data: [
{ account_number: '1930', account_name: 'Företagskonto', sru_code: '7301', is_active: true },
{ account_number: '3001', account_name: 'Försäljning', sru_code: null, is_active: true },
],
error: null,
},
{ data: [], error: null },
{ data: [], error: null },
{ data: [], error: null },
{ data: [], error: null }, // RPC fallback
]
const output = await generateSIEExport(supabase, 'company-1', baseOptions)
expect(output).toContain('#KONTO 1930 "Företagskonto"')
expect(output).toContain('#SRU 1930 7301')
expect(output).toContain('#KONTO 3001 "Försäljning"')
// No SRU for 3001 since sru_code is null
expect(output).not.toContain('#SRU 3001')
})
it('generates #VER and #TRANS for journal entries', async () => {
results = [
{ data: { id: 'period-1', period_start: '2024-01-01', period_end: '2024-12-31' }, error: null },
{ data: null, error: null }, // prevPeriod
{ data: [], error: null }, // accounts
{
data: [
{
id: 'e1',
entry_date: '2024-03-15',
voucher_number: 1,
voucher_series: 'A',
description: 'Sale invoice',
status: 'posted',
lines: [
{ account_number: '1510', debit_amount: 1250, credit_amount: 0, line_description: null, cost_center: null, project: null },
{ account_number: '3001', debit_amount: 0, credit_amount: 1000, line_description: 'Revenue', cost_center: null, project: null },
{ account_number: '2611', debit_amount: 0, credit_amount: 250, line_description: null, cost_center: null, project: null },
],
},
],
error: null,
},
{ data: [], error: null }, // cost_centers
{ data: [], error: null }, // projects
{ data: [], error: null }, // RPC fallback
]
const output = await generateSIEExport(supabase, 'company-1', baseOptions)
expect(output).toContain('#VER "A" 1 20240315 "Sale invoice"')
expect(output).toContain('{')
expect(output).toContain('\t#TRANS 1510 {} 1250.00 20240315')
expect(output).toContain('\t#TRANS 3001 {} -1000.00 20240315 "Revenue"')
expect(output).toContain('\t#TRANS 2611 {} -250.00 20240315')
expect(output).toContain('}')
})
it('generates #DIM and #OBJEKT for dimensions', async () => {
results = [
{ data: { id: 'period-1', period_start: '2024-01-01', period_end: '2024-12-31' }, error: null },
{ data: null, error: null }, // prevPeriod
{ data: [], error: null },
{ data: [], error: null },
{
data: [
{ code: 'CC1', name: 'Avdelning 1', is_active: true },
],
error: null,
},
{
data: [
{ code: 'P001', name: 'Projekt Alpha', is_active: true },
],
error: null,
},
{ data: [], error: null }, // RPC fallback
]
const output = await generateSIEExport(supabase, 'company-1', baseOptions)
expect(output).toContain('#DIM 1 "Kostnadsställe"')
expect(output).toContain('#DIM 6 "Projekt"')
expect(output).toContain('#OBJEKT 1 "CC1" "Avdelning 1"')
expect(output).toContain('#OBJEKT 6 "P001" "Projekt Alpha"')
})
it('includes dimension objects in #TRANS lines', async () => {
results = [
{ data: { id: 'period-1', period_start: '2024-01-01', period_end: '2024-12-31' }, error: null },
{ data: null, error: null }, // prevPeriod
{ data: [], error: null },
{
data: [
{
id: 'e1',
entry_date: '2024-03-15',
voucher_number: 1,
voucher_series: 'A',
description: 'With dimensions',
status: 'posted',
lines: [
{ account_number: '5010', debit_amount: 8000, credit_amount: 0, line_description: null, cost_center: 'CC1', project: 'P001' },
{ account_number: '1930', debit_amount: 0, credit_amount: 8000, line_description: null, cost_center: null, project: null },
],
},
],
error: null,
},
{ data: [{ code: 'CC1', name: 'Avdelning 1', is_active: true }], error: null },
{ data: [{ code: 'P001', name: 'Projekt Alpha', is_active: true }], error: null },
{ data: [], error: null }, // RPC fallback
]
const output = await generateSIEExport(supabase, 'company-1', baseOptions)
expect(output).toContain('\t#TRANS 5010 {1 "CC1" 6 "P001"} 8000.00 20240315')
expect(output).toContain('\t#TRANS 1930 {} -8000.00 20240315')
})
it('generates #UB for class 1-2 and #RES for class 3-8', async () => {
results = [
{ data: { id: 'period-1', period_start: '2024-01-01', period_end: '2024-12-31' }, error: null },
{ data: null, error: null }, // prevPeriod
{ data: [], error: null },
{
data: [
{
id: 'e1',
entry_date: '2024-01-15',
voucher_number: 1,
voucher_series: 'A',
description: 'Sale',
status: 'posted',
lines: [
{ account_number: '1510', debit_amount: 1250, credit_amount: 0, line_description: null, cost_center: null, project: null },
{ account_number: '3001', debit_amount: 0, credit_amount: 1000, line_description: null, cost_center: null, project: null },
{ account_number: '2611', debit_amount: 0, credit_amount: 250, line_description: null, cost_center: null, project: null },
],
},
],
error: null,
},
{ data: [], error: null },
{ data: [], error: null },
{ data: [], error: null }, // RPC fallback
]
const output = await generateSIEExport(supabase, 'company-1', baseOptions)
// Account 1510 (class 1) → #UB, balance = 1250 - 0 = 1250
expect(output).toContain('#UB 0 1510 1250.00')
// Account 2611 (class 2) → #UB, balance = 0 - 250 = -250
expect(output).toContain('#UB 0 2611 -250.00')
// Account 3001 (class 3) → #RES, balance = 0 - 1000 = -1000
expect(output).toContain('#RES 0 3001 -1000.00')
})
it('escapes quotes in descriptions', async () => {
results = [
{ data: { id: 'period-1', period_start: '2024-01-01', period_end: '2024-12-31' }, error: null },
{ data: null, error: null }, // prevPeriod
{ data: [], error: null },
{
data: [
{
id: 'e1',
entry_date: '2024-01-15',
voucher_number: 1,
voucher_series: 'A',
description: 'Invoice for "consulting"',
status: 'posted',
lines: [
{ account_number: '1930', debit_amount: 100, credit_amount: 0, line_description: null, cost_center: null, project: null },
{ account_number: '3001', debit_amount: 0, credit_amount: 100, line_description: null, cost_center: null, project: null },
],
},
],
error: null,
},
{ data: [], error: null },
{ data: [], error: null },
{ data: [], error: null }, // RPC fallback
]
const output = await generateSIEExport(supabase, 'company-1', baseOptions)
expect(output).toContain('#VER "A" 1 20240115 "Invoice for \\"consulting\\""')
})
it('uses \\r\\n line endings', async () => {
results = [
{ data: { id: 'period-1', period_start: '2024-01-01', period_end: '2024-12-31' }, error: null },
{ data: null, error: null }, // prevPeriod
{ data: [], error: null },
{ data: [], error: null },
{ data: [], error: null },
{ data: [], error: null },
{ data: [], error: null }, // RPC fallback
]
const output = await generateSIEExport(supabase, 'company-1', baseOptions)
// Every line should end with \r\n
expect(output).toContain('\r\n')
// Should not have bare \n (that isn't preceded by \r)
const lines = output.split('\r\n')
for (const line of lines.slice(0, -1)) {
expect(line).not.toContain('\n')
}
// File should end with \r\n
expect(output.endsWith('\r\n')).toBe(true)
})
it('produces no #VER lines when no entries exist', async () => {
results = [
{ data: { id: 'period-1', period_start: '2024-01-01', period_end: '2024-12-31' }, error: null },
{ data: null, error: null }, // prevPeriod
{ data: [], error: null },
{ data: [], error: null },
{ data: [], error: null },
{ data: [], error: null },
{ data: [], error: null }, // RPC fallback
]
const output = await generateSIEExport(supabase, 'company-1', baseOptions)
expect(output).not.toContain('#VER')
expect(output).not.toContain('#TRANS')
})
it('produces no #DIM lines when no dimensions exist', async () => {
results = [
{ data: { id: 'period-1', period_start: '2024-01-01', period_end: '2024-12-31' }, error: null },
{ data: null, error: null }, // prevPeriod
{ data: [], error: null },
{ data: [], error: null },
{ data: [], error: null },
{ data: [], error: null },
{ data: [], error: null }, // RPC fallback
]
const output = await generateSIEExport(supabase, 'company-1', baseOptions)
expect(output).not.toContain('#DIM')
expect(output).not.toContain('#OBJEKT')
})
it('emits #IB from compute_prior_opening_balances RPC fallback when opening_balance_entry_id is null', async () => {
// Reproduces the user-reported bug: after a multi-year SIE import the
// continuation-import guard intentionally leaves opening_balance_entry_id
// NULL, and previously the SIE export silently produced zero #IB records,
// collapsing #UB to current-period movements only. The fix wires SIE
// export to getOpeningBalances() so the RPC backs up the missing link.
results = [
// period — note: no opening_balance_entry_id, so getOpeningBalances
// falls through to the RPC path
{ data: { id: 'period-1', period_start: '2024-01-01', period_end: '2024-12-31', opening_balance_entry_id: null }, error: null },
{ data: null, error: null }, // prevPeriod
{ data: [], error: null }, // accounts
{ data: [], error: null }, // journal_entries (no movements this period)
{ data: [], error: null }, // cost_centers
{ data: [], error: null }, // projects
// RPC fallback returns prior IBs derived from historical journal lines
{
data: [
{ account_number: '1930', debit: 50000, credit: 0 },
{ account_number: '2440', debit: 0, credit: 50000 },
],
error: null,
},
]
const output = await generateSIEExport(supabase, 'company-1', baseOptions)
expect(output).toContain('#IB 0 1930 50000.00')
expect(output).toContain('#IB 0 2440 -50000.00')
// UB = IB + period movements (zero this period), so #UB mirrors #IB
expect(output).toContain('#UB 0 1930 50000.00')
expect(output).toContain('#UB 0 2440 -50000.00')
})
it('reads #IB from explicit opening_balance_entry_id when set', async () => {
// When opening_balance_entry_id is set, getOpeningBalances uses the
// journal_entry_lines path (fetchAllRows) instead of the RPC, so the
// queue here serves the line rows rather than RPC rows.
results = [
{ data: { id: 'period-1', period_start: '2024-01-01', period_end: '2024-12-31', opening_balance_entry_id: 'ob-entry-1' }, error: null },
{ data: null, error: null }, // prevPeriod
{ data: [], error: null }, // accounts
{ data: [], error: null }, // journal_entries
{ data: [], error: null }, // cost_centers
{ data: [], error: null }, // projects
// fetchAllRows page 1 — explicit OB entry lines
{
data: [
{ account_number: '1930', debit_amount: 12000, credit_amount: 0 },
{ account_number: '2440', debit_amount: 0, credit_amount: 12000 },
],
error: null,
},
]
const output = await generateSIEExport(supabase, 'company-1', baseOptions)
expect(output).toContain('#IB 0 1930 12000.00')
expect(output).toContain('#IB 0 2440 -12000.00')
expect(output).toContain('#UB 0 1930 12000.00')
expect(output).toContain('#UB 0 2440 -12000.00')
})
})