Files
accounted/lib/bokslut/__tests__/k3-framework-dispositions.test.ts
T
MattssonandClaude Opus 4.7 32d9978f1b Fix/chrome pdf preview csp (#572)
* feat: add option to exclude year-end closing entries in SIE export and related reports

* delete docs

* fix: allow Chrome's PDF viewer in verifikat document preview

The /api/documents/:id/inline route shipped with
`object-src 'none'` in its CSP, which blocked Chrome's built-in PDF
viewer (it renders inline PDFs via an internal <embed>). Users on
Chrome saw "Det här innehållet har blockerats" when expanding a PDF
attachment in the bookkeeping view; Firefox (PDF.js) and Edge (own
viewer) were unaffected, and JPGs worked because <img> isn't subject
to object-src.

Drops the CSP for this route to the minimum needed for embeddability:
`frame-ancestors 'self'`. X-Content-Type-Options: nosniff plus the
fixed Content-Type from the handler already block MIME confusion;
X-Frame-Options: SAMEORIGIN + frame-ancestors still block clickjacking.

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

* feat(auth): add webmail deep link to email confirmation screens

Mirrors Stripe's signup UX: after asking the user to verify their email,
detect their webmail provider from the domain and show a button that
opens the inbox in a new tab. Gmail gets a from:<sender> search
pre-populated; Outlook/Yahoo/iCloud/Proton open the inbox directly.
Unknown / custom domains fall back to the existing copy.

Sender address is configurable via NEXT_PUBLIC_BRANDING_AUTH_EMAIL_FROM
(default noreply@gnubok.se) so white-label installs can match their
Supabase Auth SMTP config.

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

* fix(auth): unblock first-time password set for BankID users with MFA

Supabase rejects updateUser({password}) and mfa.unenroll with "AAL2 session
is required" whenever a TOTP factor is enrolled. BankID magic-link logins
produce AAL1, and middleware skips MFA enforcement for bankid_linked users,
so they had no path to AAL2 — leaving them unable to set a backup password
or disable MFA without going through the email-recovery escape hatch.

- /api/account/password: branch on app_metadata.has_password. First-time set
  writes via service.auth.admin.updateUserById (no existing credential to
  protect, AAL2 guard does not apply). Change-password keeps the user-session
  updateUser so AAL2 still fires for credential rotation.
- /mfa/verify: accept a safeReturnTo query param and route there after
  successful verify, so step-up flows can land back where they came from.
- SecuritySettings: detect the AAL2 error from both change-password and
  mfa.unenroll and redirect through /mfa/verify?returnTo=/settings/account
  instead of toasting a dead-end error.

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

* Add tests and rounding utility for öre precision in bokslut calculations

- Implemented `roundOre` function for rounding SEK amounts to two decimal places, ensuring consistent monetary calculations.
- Introduced `ORE_TOLERANCE` constant for comparing rounded amounts, facilitating invariant checks in financial entries.
- Created comprehensive tests for `roundOre`, covering typical cases, edge cases, and idempotency.
- Added year-end invariants tests to verify database-level guarantees for closing entries, ensuring they balance to the öre and reject discrepancies.
- Developed end-to-end tests for the dispositions chain, validating the correctness of calculations across various scenarios.

* fix: update PDF rendering to remove Swish QR code generation and set default to disable Swish visibility

* fix: enhance security by rejecting data URIs in safeReturnTo function tests

* fix: improve rounding logic in roundOre function and add customer_type migration

* fix: add customer_type column to customers and enforce CHECK constraint

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-26 22:29:41 +02:00

258 lines
9.0 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* K3 framework integration test for the dispositions builder.
*
* Verifies that:
* - K3 companies get an `uppskjuten_skatt` proposal at the end of the chain.
* - K2 companies (the default) do NOT receive that proposal.
* - The latent tax amount equals 20.6 % × projected closing 21xx − current
* 2240 balance.
*
* Mocks generateIncomeStatement and generateTrialBalance directly so the
* test can drive numeric inputs without touching the database.
*/
import { describe, it, expect, vi, beforeEach } from 'vitest'
vi.mock('@/lib/reports/income-statement', () => ({
generateIncomeStatement: vi.fn(),
}))
vi.mock('@/lib/reports/trial-balance', () => ({
generateTrialBalance: vi.fn(),
}))
import { buildDispositionsProposal } from '../dispositions-proposal-builder'
import { generateIncomeStatement } from '@/lib/reports/income-statement'
import { generateTrialBalance } from '@/lib/reports/trial-balance'
interface ChainableMock {
from: ReturnType<typeof vi.fn>
}
function makeSupabase(opts: {
entityType: 'aktiebolag' | 'enskild_firma'
accountingFramework: 'k2' | 'k3' | null
periodEnd?: string
/** Existing periodiseringsfond rows the builder queries. */
periodiseringsfondRows?: Array<{ account_number: string; cohort_year: number; balance: number; must_return_this_year: boolean }>
}): ChainableMock {
const periodEnd = opts.periodEnd ?? '2026-12-31'
// The builder makes several .from(...) queries. We respond per-table.
const from = vi.fn((table: string) => {
if (table === 'fiscal_periods') {
return {
select: () => ({
eq: () => ({
eq: () => ({
single: () =>
Promise.resolve({
data: {
id: 'fp1',
name: '2026',
period_start: '2026-01-01',
period_end: periodEnd,
},
error: null,
}),
}),
}),
}),
}
}
if (table === 'company_settings') {
return {
select: () => ({
eq: () => ({
maybeSingle: () =>
Promise.resolve({
data: { entity_type: opts.entityType },
error: null,
}),
}),
}),
}
}
if (table === 'companies') {
return {
select: () => ({
eq: () => ({
maybeSingle: () =>
Promise.resolve({
data: { accounting_framework: opts.accountingFramework },
error: null,
}),
}),
}),
}
}
if (table === 'journal_entry_lines') {
// Used by listExistingPeriodiseringsfonder and calculateSarskildLoneskatt.
// We return either the test-supplied periodiseringsfond rows (when the
// builder is walking 21xx) or an empty SLP result.
const rows = opts.periodiseringsfondRows
? opts.periodiseringsfondRows.flatMap((f) => [
{
account_number: f.account_number,
credit_amount: f.balance,
debit_amount: 0,
entry_date: `${f.cohort_year}-12-31`,
journal_entries: { entry_date: `${f.cohort_year}-12-31`, status: 'posted' },
},
])
: []
return {
select: () => {
// Make the chainable builder resolve to { data: rows, error: null }
const result: { data: typeof rows; error: null } = { data: rows, error: null }
const handler: ProxyHandler<object> = {
get(_t, prop) {
if (prop === 'then') {
return (resolve: (v: unknown) => void) => resolve(result)
}
return () => new Proxy({}, handler)
},
}
return new Proxy({}, handler)
},
}
}
// Catch-all chainable that resolves to empty.
const handler: ProxyHandler<object> = {
get(_t, prop) {
if (prop === 'then') {
return (resolve: (v: unknown) => void) =>
resolve({ data: null, error: null })
}
return () => new Proxy({}, handler)
},
}
return new Proxy({}, handler)
})
return { from } as ChainableMock
}
beforeEach(() => {
vi.clearAllMocks()
// Zero result so the builder doesn't propose a new avsättning — keeps the
// 21xx balance stable at the trial-balance value, which makes the latent
// tax math testable in isolation.
vi.mocked(generateIncomeStatement).mockResolvedValue({
net_result: 0,
} as Awaited<ReturnType<typeof generateIncomeStatement>>)
vi.mocked(generateTrialBalance).mockResolvedValue({
rows: [
// 100 000 in periodiseringsfond → 20 600 latent tax target.
{
account_number: '2125',
account_name: 'Periodiseringsfond 2025',
account_class: 2,
closing_credit: 100_000,
closing_debit: 0,
opening_credit: 0,
opening_debit: 0,
period_credit: 100_000,
period_debit: 0,
},
// No existing 2240 balance.
],
totalDebit: 0,
totalCredit: 100_000,
isBalanced: false,
} as unknown as Awaited<ReturnType<typeof generateTrialBalance>>)
})
describe('buildDispositionsProposal — K3 framework', () => {
it('appends an uppskjuten_skatt proposal for K3 aktiebolag', async () => {
const supabase = makeSupabase({ entityType: 'aktiebolag', accountingFramework: 'k3' })
const result = await buildDispositionsProposal(
supabase as unknown as Parameters<typeof buildDispositionsProposal>[0],
'co',
'fp1',
)
expect(result.entityType).toBe('aktiebolag')
const latentTax = result.proposals.find((p) => p.kind === 'uppskjuten_skatt')
expect(latentTax).toBeDefined()
expect(latentTax!.amount).toBe(20_600)
expect(latentTax!.lines).toHaveLength(2)
// Liability increased → debit 8940 / credit 2240.
const debit = latentTax!.lines.find((l) => l.account_number === '8940')!
const credit = latentTax!.lines.find((l) => l.account_number === '2240')!
expect(debit.debit_amount).toBe(20_600)
expect(credit.credit_amount).toBe(20_600)
})
it('does NOT add an uppskjuten_skatt proposal for K2 aktiebolag', async () => {
const supabase = makeSupabase({ entityType: 'aktiebolag', accountingFramework: 'k2' })
const result = await buildDispositionsProposal(
supabase as unknown as Parameters<typeof buildDispositionsProposal>[0],
'co',
'fp1',
)
expect(result.entityType).toBe('aktiebolag')
expect(result.proposals.find((p) => p.kind === 'uppskjuten_skatt')).toBeUndefined()
})
it('defaults to K2 when accounting_framework is null on the company row', async () => {
const supabase = makeSupabase({ entityType: 'aktiebolag', accountingFramework: null })
const result = await buildDispositionsProposal(
supabase as unknown as Parameters<typeof buildDispositionsProposal>[0],
'co',
'fp1',
)
expect(result.proposals.find((p) => p.kind === 'uppskjuten_skatt')).toBeUndefined()
})
it('does NOT add an uppskjuten_skatt proposal for enskild firma even if mislabelled K3', async () => {
// EF should never carry K3 (validation rejects it on the API side), but if
// somehow set the EF branch returns early with an empty proposal list.
const supabase = makeSupabase({ entityType: 'enskild_firma', accountingFramework: 'k3' })
const result = await buildDispositionsProposal(
supabase as unknown as Parameters<typeof buildDispositionsProposal>[0],
'co',
'fp1',
)
expect(result.entityType).toBe('enskild_firma')
expect(result.proposals).toEqual([])
})
it('skips uppskjuten_skatt when 2240 already matches target (no change)', async () => {
// Bump 2240 to exactly 20 600 so the delta is zero — calculator should
// return null and the builder skip the proposal entirely.
vi.mocked(generateTrialBalance).mockResolvedValue({
rows: [
{
account_number: '2125',
account_name: 'Periodiseringsfond 2025',
account_class: 2,
closing_credit: 100_000,
closing_debit: 0,
opening_credit: 0,
opening_debit: 0,
period_credit: 100_000,
period_debit: 0,
},
{
account_number: '2240',
account_name: 'Avsättningar för uppskjutna skatter',
account_class: 2,
closing_credit: 20_600,
closing_debit: 0,
opening_credit: 20_600,
opening_debit: 0,
period_credit: 0,
period_debit: 0,
},
],
totalDebit: 0,
totalCredit: 120_600,
isBalanced: false,
} as unknown as Awaited<ReturnType<typeof generateTrialBalance>>)
const supabase = makeSupabase({ entityType: 'aktiebolag', accountingFramework: 'k3' })
const result = await buildDispositionsProposal(
supabase as unknown as Parameters<typeof buildDispositionsProposal>[0],
'co',
'fp1',
)
expect(result.proposals.find((p) => p.kind === 'uppskjuten_skatt')).toBeUndefined()
})
})