fix(salary): declare, book and pay AGI in whole kronor (SKV per-sats computation) (#1611)
* fix(salary): declare, book and pay AGI in whole kronor (SKV per-sats computation) A user's first lönekörning surfaced öre amounts in the AGI payable while Skatteverket deals in whole kronor. Three connected defects: - the AGI XML rounded amounts (Math.round); öretal bortfaller (SFF 2011:1261 22 kap. 1 §) requires truncation, and FK487 must be Skatteverket's own per-sats computation on the whole-krona underlag sums (IK587, kontroll B_006), not a truncation of the öre-exact engine sum - the salary booking credited 2731 with exact öre, leaving a residual after the whole-krona skattekonto draw; 2731 now carries the declared amount with the remainder on 3740 (Öres- och kronutjämning) - the LB payment file and TaxPaymentPanel paid/showed öre; they now use the declared whole-krona totals stored on agi_declarations (which also lets skattekonto auto-settlement match the draw); legacy öre rows keep paying öre-exact so pre-deploy bookings still clear 2731 New lib/salary/declared-avgifter.ts implements the SKV computation (per-IU whole-krona underlag, per-sats sums, youth/växa cap splits, exact integer math) shared by the AGI generator, the booking split and the preview. Review overrides route all legs through the same per-category truncation; basis overrides are inert on money totals (they never reach the filed IUs); the v1 book route gains override parity with book-run; F-skatt rows ignore avgifter overrides on every surface. Booked runs show their posted verifikat instead of a recomputed projection. tax_withheld_override requires whole kronor. Adversarially verified over three /skeptic rounds. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * chore: merge origin/main and re-ratchet the öre-round baseline The merge brought #1609 (net-pay öresavrundning) whose two new Math.round(x*100)/100 occurrences are counted against the baseline this branch had tightened from 637 to 629; 631 keeps the net -6 improvement without policing already-merged code. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(salary): address PR review (hybrid override computation, legacy youth cap, robustness) CodeRabbit round on #1611, all findings in one pass: - computeDeclaredAvgifterWithOverrides: one shared hybrid for the AGI generator AND the booking split. Overridden rows contribute their manual amounts per category; colleagues keep the SKV-exact per-sats underlag computation (a FoU override on one employee no longer costs the rest of the roster kronor of declared accuracy) - youth cap keys on the RESOLVED category so legacy null-category rows classified as youth by the rate heuristic still get the 25k split - F-skatt rows zero their avgifter_basis on both booking surfaces and in the preview, matching the AGI's isFSkattRow invariant - preview route: posted-voucher lookup errors return 500 instead of masquerading as a booked run with no vouchers; 400/500 tests added - run page clears stale AGI totals when the tax-payment fetch fails - SalaryOverridePanel truncates the tax override to whole kronor so the schema's .int() cannot bounce a decimal input with a 400 - v1 book route override parity pinned by a lifecycle test - DECISIONS.md format fixes + superseded entry marked; exempt category mapped explicitly; unified truncation-drift band with rationale Declined (recorded): dating the decision entries 2026-08-13 (bot assumed UTC; the decisions were made after midnight local time). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(salary): round-2 review nits (shared F-skatt helper, test hygiene) - isFSkattStatus in declared-avgifter.ts: single source for the F-skatt exclusion, consumed by book-run, the v1 book route, the preview route and the AGI generator, per the Swedish review's drift-risk finding - declared-avgifter test suite gets the standard beforeEach cleanup Declined (recorded for the summary): auto-generated correction voucher for regenerated legacy periods (data-repair follow-up needing Emil's go); SFF 22 kap. 1 par. citation doubt (verified against lagen.nu and already shipped in tax-tables.ts); 3740 scope doubt (BAS generic utjamning account, Visma praxis, matches the user's reference voucher). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> --------- Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Fable 5
parent
fbe4e18730
commit
4e14182a00
@@ -0,0 +1,181 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { NextResponse } from 'next/server'
|
||||
import {
|
||||
createMockRequest,
|
||||
createMockRouteParams,
|
||||
createQueuedMockSupabase,
|
||||
} from '@/tests/helpers'
|
||||
|
||||
const { supabase: mockSupabase, enqueue, reset } = createQueuedMockSupabase()
|
||||
|
||||
const requireAuthMock = vi.fn()
|
||||
vi.mock('@/lib/auth/require-auth', () => ({
|
||||
requireAuth: (...args: unknown[]) => requireAuthMock(...args),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/init', () => ({ ensureInitialized: vi.fn() }))
|
||||
|
||||
vi.mock('@/lib/company/context', () => ({
|
||||
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
|
||||
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
|
||||
}))
|
||||
|
||||
import { GET } from '../route'
|
||||
|
||||
const CALCULATED_RUN = {
|
||||
id: 'run-1',
|
||||
company_id: 'company-1',
|
||||
status: 'review',
|
||||
period_year: 2026,
|
||||
period_month: 7,
|
||||
calculation_params: { slpRate: 0.2426, avgifterTotal: 0.3142 },
|
||||
}
|
||||
|
||||
const EMPLOYEE_ROW = {
|
||||
employee_id: 'emp-1',
|
||||
employee: { employment_type: 'employee' },
|
||||
gross_salary: 51158,
|
||||
tax_withheld: 12268,
|
||||
net_salary: 38890,
|
||||
avgifter_amount: 16073.84,
|
||||
avgifter_amount_override: null,
|
||||
avgifter_basis: 51158,
|
||||
avgifter_rate: 0.3142,
|
||||
avgifter_category: 'standard',
|
||||
vacation_accrual: 0,
|
||||
vacation_accrual_avgifter: 0,
|
||||
line_items: [],
|
||||
}
|
||||
|
||||
describe('GET /api/salary/runs/[id]/preview', () => {
|
||||
const mockUser = { id: 'user-1', email: 'test@test.se' }
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
reset()
|
||||
requireAuthMock.mockResolvedValue({ user: mockUser, supabase: mockSupabase, error: null })
|
||||
})
|
||||
|
||||
it('returns 401 when not authenticated', async () => {
|
||||
requireAuthMock.mockResolvedValue({
|
||||
user: null,
|
||||
supabase: mockSupabase,
|
||||
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
|
||||
})
|
||||
const response = await GET(
|
||||
createMockRequest('/api/salary/runs/run-1/preview'),
|
||||
createMockRouteParams({ id: 'run-1' }),
|
||||
)
|
||||
expect(response.status).toBe(401)
|
||||
})
|
||||
|
||||
it('returns 404 for an unknown run', async () => {
|
||||
enqueue({ data: null, error: { message: 'not found' } })
|
||||
const response = await GET(
|
||||
createMockRequest('/api/salary/runs/run-1/preview'),
|
||||
createMockRouteParams({ id: 'run-1' }),
|
||||
)
|
||||
expect(response.status).toBe(404)
|
||||
})
|
||||
|
||||
it('returns 400 when the run has no calculated employees', async () => {
|
||||
enqueue({ data: CALCULATED_RUN }) // salary_runs
|
||||
enqueue({ data: [] }) // salary_run_employees: nothing calculated yet
|
||||
const response = await GET(
|
||||
createMockRequest('/api/salary/runs/run-1/preview'),
|
||||
createMockRouteParams({ id: 'run-1' }),
|
||||
)
|
||||
expect(response.status).toBe(400)
|
||||
})
|
||||
|
||||
it('returns 500 when the posted-voucher lookup fails for a booked run', async () => {
|
||||
enqueue({
|
||||
data: { ...CALCULATED_RUN, status: 'booked', salary_entry_id: 'je-1' },
|
||||
}) // salary_runs
|
||||
enqueue({ data: null, error: { message: 'rls denied' } }) // journal_entries
|
||||
const response = await GET(
|
||||
createMockRequest('/api/salary/runs/run-1/preview'),
|
||||
createMockRouteParams({ id: 'run-1' }),
|
||||
)
|
||||
// A failed lookup must not masquerade as "booked run with no vouchers".
|
||||
expect(response.status).toBe(500)
|
||||
})
|
||||
|
||||
it('previews the whole-krona 2731/3740 split for a calculated run', async () => {
|
||||
enqueue({ data: CALCULATED_RUN }) // salary_runs
|
||||
enqueue({ data: [EMPLOYEE_ROW] }) // salary_run_employees
|
||||
|
||||
const response = await GET(
|
||||
createMockRequest('/api/salary/runs/run-1/preview'),
|
||||
createMockRouteParams({ id: 'run-1' }),
|
||||
)
|
||||
expect(response.status).toBe(200)
|
||||
const { data } = await response.json()
|
||||
|
||||
expect(data.booked).toBeUndefined()
|
||||
const lines = data.avgifterEntry.lines as Array<{
|
||||
account_number: string
|
||||
debit_amount: number
|
||||
credit_amount: number
|
||||
}>
|
||||
expect(lines.find((l) => l.account_number === '7510')?.debit_amount).toBe(16073.84)
|
||||
expect(lines.find((l) => l.account_number === '2731')?.credit_amount).toBe(16073)
|
||||
expect(lines.find((l) => l.account_number === '3740')?.credit_amount).toBe(0.84)
|
||||
})
|
||||
|
||||
it('returns the ACTUAL posted verifikat for a booked run, voucher labels included', async () => {
|
||||
enqueue({
|
||||
data: {
|
||||
...CALCULATED_RUN,
|
||||
status: 'booked',
|
||||
salary_entry_id: 'je-1',
|
||||
avgifter_entry_id: 'je-2',
|
||||
vacation_entry_id: null,
|
||||
pension_entry_id: null,
|
||||
},
|
||||
}) // salary_runs
|
||||
enqueue({
|
||||
data: [
|
||||
{
|
||||
id: 'je-1',
|
||||
description: 'Lön 2026-07',
|
||||
voucher_series: 'A',
|
||||
voucher_number: 214,
|
||||
lines: [
|
||||
{ account_number: '7210', line_description: 'Lön', debit_amount: 51158, credit_amount: 0 },
|
||||
{ account_number: '2710', line_description: 'Personalskatt', debit_amount: 0, credit_amount: 12268 },
|
||||
{ account_number: '1930', line_description: 'Nettolön', debit_amount: 0, credit_amount: 38890 },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'je-2',
|
||||
description: 'Lön 2026-07: Arbetsgivaravgifter',
|
||||
voucher_series: 'A',
|
||||
voucher_number: 215,
|
||||
// A pre-whole-krona legacy voucher: the view must show the posted
|
||||
// öre-exact lines, never a recomputed projection with 3740.
|
||||
lines: [
|
||||
{ account_number: '7510', line_description: 'Arbetsgivaravgifter', debit_amount: 16073.84, credit_amount: 0 },
|
||||
{ account_number: '2731', line_description: 'Arbetsgivaravgifter', debit_amount: 0, credit_amount: 16073.84 },
|
||||
],
|
||||
},
|
||||
],
|
||||
}) // journal_entries
|
||||
|
||||
const response = await GET(
|
||||
createMockRequest('/api/salary/runs/run-1/preview'),
|
||||
createMockRouteParams({ id: 'run-1' }),
|
||||
)
|
||||
expect(response.status).toBe(200)
|
||||
const { data } = await response.json()
|
||||
|
||||
expect(data.booked).toBe(true)
|
||||
expect(data.salaryEntry.description).toBe('Lön 2026-07 (A-214)')
|
||||
expect(data.avgifterEntry.description).toBe('Lön 2026-07: Arbetsgivaravgifter (A-215)')
|
||||
const avgifterLines = data.avgifterEntry.lines as Array<{ account_number: string; credit_amount: number }>
|
||||
expect(avgifterLines.find((l) => l.account_number === '2731')?.credit_amount).toBe(16073.84)
|
||||
expect(avgifterLines.some((l) => l.account_number === '3740')).toBe(false)
|
||||
expect(data.vacationEntry).toBeNull()
|
||||
expect(data.pensionEntry).toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -2,6 +2,8 @@ import { NextResponse } from 'next/server'
|
||||
import { ensureInitialized } from '@/lib/init'
|
||||
import { withRouteContext } from '@/lib/api/with-route-context'
|
||||
import { SALARY_ACCOUNTS, getLineItemAccount } from '@/lib/salary/account-mapping'
|
||||
import { splitAvgifterLiability } from '@/lib/salary/salary-entries'
|
||||
import { isFSkattStatus } from '@/lib/salary/declared-avgifter'
|
||||
import { roundOre } from '@/lib/money'
|
||||
import type { CreateJournalEntryLineInput } from '@/types'
|
||||
|
||||
@@ -28,10 +30,78 @@ export const GET = withRouteContext<{ params: Promise<{ id: string }> }>(
|
||||
return NextResponse.json({ error: 'Lönekörning hittades inte' }, { status: 404 })
|
||||
}
|
||||
|
||||
// Booked/corrected runs return the ACTUAL posted verifikat instead of a
|
||||
// recomputed preview: a preview built by today's booking rules would
|
||||
// contradict an immutable voucher booked under earlier rules (e.g. the
|
||||
// 2731/3740 whole-krona split) exactly where users reconcile. Same
|
||||
// response shape, entries keyed by the run's entry ids, voucher labels
|
||||
// folded into the description.
|
||||
if (run.status === 'booked' || run.status === 'corrected') {
|
||||
const { data: posted, error: postedError } = await supabase
|
||||
.from('journal_entries')
|
||||
.select(
|
||||
'id, description, voucher_series, voucher_number, lines:journal_entry_lines(account_number, line_description, debit_amount, credit_amount)',
|
||||
)
|
||||
.eq('company_id', companyId)
|
||||
.eq('source_type', 'salary_payment')
|
||||
.eq('source_id', id)
|
||||
|
||||
// A failed lookup must not masquerade as "booked run with no vouchers".
|
||||
if (postedError) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Kunde inte läsa lönekörningens bokförda verifikat' },
|
||||
{ status: 500 },
|
||||
)
|
||||
}
|
||||
|
||||
const byId = new Map(
|
||||
((posted ?? []) as Array<{ id: string }>).map((e) => [e.id, e] as const),
|
||||
)
|
||||
const toEntry = (entryId: unknown) => {
|
||||
const entry = entryId ? (byId.get(entryId as string) as
|
||||
| {
|
||||
description: string
|
||||
voucher_series: string | null
|
||||
voucher_number: number | null
|
||||
lines: Array<{
|
||||
account_number: string
|
||||
line_description: string | null
|
||||
debit_amount: number | null
|
||||
credit_amount: number | null
|
||||
}>
|
||||
}
|
||||
| undefined) : undefined
|
||||
if (!entry) return null
|
||||
const voucher =
|
||||
entry.voucher_number != null
|
||||
? ` (${entry.voucher_series ?? ''}${entry.voucher_series ? '-' : ''}${entry.voucher_number})`
|
||||
: ''
|
||||
return {
|
||||
description: `${entry.description}${voucher}`,
|
||||
lines: entry.lines.map((l) => ({
|
||||
account_number: l.account_number,
|
||||
line_description: l.line_description ?? '',
|
||||
debit_amount: l.debit_amount,
|
||||
credit_amount: l.credit_amount,
|
||||
})),
|
||||
}
|
||||
}
|
||||
|
||||
return NextResponse.json({
|
||||
data: {
|
||||
booked: true,
|
||||
salaryEntry: toEntry(run.salary_entry_id),
|
||||
avgifterEntry: toEntry(run.avgifter_entry_id),
|
||||
vacationEntry: toEntry(run.vacation_entry_id),
|
||||
pensionEntry: toEntry(run.pension_entry_id),
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
// Load employees with line items
|
||||
const { data: employees } = await supabase
|
||||
.from('salary_run_employees')
|
||||
.select('*, employee:employees(employment_type), line_items:salary_line_items(*)')
|
||||
.select('*, employee:employees(employment_type, f_skatt_status), line_items:salary_line_items(*)')
|
||||
.eq('salary_run_id', id)
|
||||
|
||||
if (!employees || employees.length === 0) {
|
||||
@@ -107,8 +177,44 @@ export const GET = withRouteContext<{ params: Promise<{ id: string }> }>(
|
||||
// mirroring the vacation/pension guards below. The bookkeeping engine never
|
||||
// posts an all-zero 7510/2731 voucher (see book/route.ts nollkörning path),
|
||||
// so previewing one would falsely imply a verifikat that is never created.
|
||||
const totalAvgifter = employees.reduce((sum, e) => sum + e.avgifter_amount, 0)
|
||||
const roundedAvgifter = Math.round(totalAvgifter * 100) / 100
|
||||
// Override-coalesced, like the booking (book-run.ts): the preview must
|
||||
// project the voucher that would actually post. F-skatt rows ignore
|
||||
// avgifter overrides and carry no underlag, matching book-run and the
|
||||
// AGI's isFSkattRow invariant.
|
||||
const isFSkattRow = (e: { employee?: { f_skatt_status?: string | null } | null }) =>
|
||||
isFSkattStatus(e.employee?.f_skatt_status)
|
||||
const totalAvgifter = employees.reduce(
|
||||
(sum, e) =>
|
||||
sum +
|
||||
((isFSkattRow(e) ? e.avgifter_amount : e.avgifter_amount_override ?? e.avgifter_amount) ||
|
||||
0),
|
||||
0,
|
||||
)
|
||||
const roundedAvgifter = roundOre(totalAvgifter)
|
||||
// Identical split to createAvgifterEntry (shared function): 2731 gets the
|
||||
// whole-krona amount Skatteverket computes from the underlag, the
|
||||
// remainder goes to 3740; the 7510 cost side stays exact.
|
||||
const { liabilityAvgifter, oresutjamning } = splitAvgifterLiability(
|
||||
{
|
||||
employees: (employees as Array<Record<string, unknown>>).map((sre) => {
|
||||
const fSkatt = isFSkattRow(sre as never)
|
||||
return {
|
||||
avgifter_amount:
|
||||
((fSkatt
|
||||
? (sre.avgifter_amount as number)
|
||||
: (sre.avgifter_amount_override as number | null) ??
|
||||
(sre.avgifter_amount as number)) || 0),
|
||||
avgifter_basis: fSkatt ? 0 : (sre.avgifter_basis as number | undefined),
|
||||
avgifter_rate: sre.avgifter_rate as number,
|
||||
avgifter_category: (sre.avgifter_category as string | null) ?? null,
|
||||
avgifter_amount_overridden:
|
||||
!fSkatt && (sre.avgifter_amount_override as number | null) != null,
|
||||
}
|
||||
}),
|
||||
calculation_params: run.calculation_params as Record<string, unknown> | null,
|
||||
},
|
||||
roundedAvgifter,
|
||||
)
|
||||
const avgifterLines: CreateJournalEntryLineInput[] = roundedAvgifter !== 0
|
||||
? [
|
||||
{
|
||||
@@ -117,12 +223,26 @@ export const GET = withRouteContext<{ params: Promise<{ id: string }> }>(
|
||||
credit_amount: 0,
|
||||
line_description: `${desc}: Arbetsgivaravgifter`,
|
||||
},
|
||||
{
|
||||
account_number: SALARY_ACCOUNTS.AVGIFTER_LIABILITY,
|
||||
debit_amount: 0,
|
||||
credit_amount: roundedAvgifter,
|
||||
line_description: `${desc}: Arbetsgivaravgifter`,
|
||||
},
|
||||
...(liabilityAvgifter !== 0 || oresutjamning === 0
|
||||
? [
|
||||
{
|
||||
account_number: SALARY_ACCOUNTS.AVGIFTER_LIABILITY,
|
||||
debit_amount: 0,
|
||||
credit_amount: liabilityAvgifter,
|
||||
line_description: `${desc}: Arbetsgivaravgifter`,
|
||||
} satisfies CreateJournalEntryLineInput,
|
||||
]
|
||||
: []),
|
||||
...(oresutjamning > 0
|
||||
? [
|
||||
{
|
||||
account_number: SALARY_ACCOUNTS.ORESUTJAMNING,
|
||||
debit_amount: 0,
|
||||
credit_amount: oresutjamning,
|
||||
line_description: `${desc}: Öres- och kronutjämning`,
|
||||
} satisfies CreateJournalEntryLineInput,
|
||||
]
|
||||
: []),
|
||||
]
|
||||
: []
|
||||
|
||||
|
||||
Reference in New Issue
Block a user