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:
Mattsson
2026-08-14 02:22:07 +02:00
committed by GitHub
co-authored by Claude Fable 5
parent fbe4e18730
commit 4e14182a00
28 changed files with 1642 additions and 102 deletions
@@ -487,6 +487,85 @@ describe('POST /salary-runs/:id/book', () => {
)
})
it('applies review overrides with book-run parity (tax/net reconciled, F-skatt avgifter override ignored)', async () => {
// Overrides set during dashboard review must reach the ledger the same
// way no matter which surface books the run: v1 previously ignored them,
// so the booked 2710/2731 diverged from the AGI by the override delta.
const overriddenRow = {
...employeeRow,
tax_withheld_override: 9000,
avgifter_amount_override: 10000,
avgifter_basis: 35000,
avgifter_category: 'standard',
}
const fSkattRow = {
...employeeRow,
employee_id: 'emp_2',
employee: { employment_type: 'employee', f_skatt_status: 'f_skatt' },
gross_salary: 15000,
tax_withheld: 0,
net_salary: 15000,
avgifter_amount: 0,
// An avgifter override on an F-skatt row must be ignored (the AGI's
// isFSkattRow invariant), and the underlag zeroed.
avgifter_amount_override: 500,
avgifter_basis: 15000,
avgifter_category: 'standard',
}
mockServiceClient.mockReturnValue(
makeFlexibleSupabase({
company_members: { data: { company_id: COMPANY_ID, role: 'owner' }, error: null },
salary_runs: [
{ data: paidRun, error: null },
{
data: {
id: RUN_ID, status: 'booked',
booked_at: '2026-05-26T09:15:00Z', booked_by: USER_ID,
salary_entry_id: 'je_salary', avgifter_entry_id: 'je_avg',
vacation_entry_id: null, pension_entry_id: null,
},
error: null,
},
],
salary_run_employees: { data: [overriddenRow, fSkattRow], error: null },
idempotency_keys: { data: null, error: null },
}),
)
mocks.checkPeriodLock.mockResolvedValue({ locked: false })
mocks.createSalaryRunEntries.mockResolvedValue({
salaryEntry: { id: 'je_salary', voucher_number: 'L2026-0024' },
avgifterEntry: { id: 'je_avg' },
vacationEntry: null,
pensionEntry: null,
})
const res = await book(
makeRequest(`https://x.test/api/v1/companies/${COMPANY_ID}/salary-runs/${RUN_ID}/book`, {
method: 'POST',
}),
detailParams(COMPANY_ID, RUN_ID),
)
expect(res.status).toBe(200)
const payload = mocks.createSalaryRunEntries.mock.calls[0][3] as {
employees: Array<Record<string, unknown>>
}
const [regular, fSkatt] = payload.employees
expect(regular).toMatchObject({
tax_withheld: 9000,
// net reconciles by the withheld difference: 25 500 + (9 500 - 9 000).
net_salary: 26000,
avgifter_amount: 10000,
avgifter_amount_overridden: true,
avgifter_basis: 35000,
})
expect(fSkatt).toMatchObject({
avgifter_amount: 0,
avgifter_amount_overridden: false,
avgifter_basis: 0,
})
})
it('returns PERIOD_LOCKED before invoking the engine when payment_date is locked', async () => {
mockServiceClient.mockReturnValue(
makeFlexibleSupabase({
@@ -34,6 +34,7 @@ import { withApiV1 } from '@/lib/api/v1/with-api-v1'
import { v1ErrorResponse, v1ErrorResponseFromCode } from '@/lib/api/v1/errors'
import { checkPeriodLock } from '@/lib/api/v1/check-period-lock'
import { createSalaryRunEntries } from '@/lib/salary/salary-entries'
import { isFSkattStatus } from '@/lib/salary/declared-avgifter'
import { syncVacationLedgerForEmployees } from '@/lib/salary/vacation-ledger'
import { isBookkeepingError } from '@/lib/bookkeeping/errors'
import { eventBus } from '@/lib/events'
@@ -156,7 +157,7 @@ export const POST = withApiV1<{ params: Promise<{ companyId: string; id: string
// 3. Load run + employees + line items for the engine.
const { data: employees, error: empErr } = await ctx.supabase
.from('salary_run_employees')
.select('*, employee:employees(employment_type, default_dimensions), line_items:salary_line_items(*)')
.select('*, employee:employees(employment_type, default_dimensions, f_skatt_status), line_items:salary_line_items(*)')
.eq('salary_run_id', salaryRunId)
if (empErr) {
return v1ErrorResponse(empErr, ctx.log, { requestId: ctx.requestId })
@@ -210,12 +211,20 @@ export const POST = withApiV1<{ params: Promise<{ companyId: string; id: string
// 4. Engine call. Strict-mode: any throw aborts before status flip.
type EmpRow = {
employee_id: string
employee: { employment_type: string; default_dimensions?: Record<string, string> } | null
employee: {
employment_type: string
default_dimensions?: Record<string, string>
f_skatt_status?: string | null
} | null
gross_salary: number
tax_withheld: number
tax_withheld_override: number | null
net_salary: number
avgifter_amount: number
avgifter_amount_override: number | null
avgifter_rate: number
avgifter_basis: number
avgifter_category: string | null
vacation_accrual: number
vacation_accrual_avgifter: number
line_items: Array<{
@@ -247,10 +256,28 @@ export const POST = withApiV1<{ params: Promise<{ companyId: string; id: string
employee_id: sre.employee_id,
employment_type: sre.employee?.employment_type || 'employee',
gross_salary: sre.gross_salary,
tax_withheld: sre.tax_withheld,
net_salary: sre.net_salary,
avgifter_amount: sre.avgifter_amount,
// Override parity with book-run.ts: review overrides must reach
// the ledger identically no matter which surface books the run,
// or the booked 2731/2710 diverge from the AGI totals by the full
// override delta. F-skatt rows ignore avgifter overrides (the AGI
// hard-excludes them via isFSkattRow).
tax_withheld: sre.tax_withheld_override ?? sre.tax_withheld,
net_salary:
sre.net_salary + (sre.tax_withheld - (sre.tax_withheld_override ?? sre.tax_withheld)),
avgifter_amount:
isFSkattStatus(sre.employee?.f_skatt_status)
? sre.avgifter_amount
: sre.avgifter_amount_override ?? sre.avgifter_amount,
avgifter_rate: sre.avgifter_rate,
// Declared-avgifter inputs: 2731 books the whole-krona amount
// Skatteverket computes from the underlag (declared-avgifter.ts).
// Zeroed for F-skatt rows, matching book-run and the AGI's
// isFSkattRow invariant.
avgifter_basis:
isFSkattStatus(sre.employee?.f_skatt_status) ? 0 : sre.avgifter_basis,
avgifter_category: sre.avgifter_category ?? null,
avgifter_amount_overridden:
!isFSkattStatus(sre.employee?.f_skatt_status) && sre.avgifter_amount_override != null,
vacation_accrual: sre.vacation_accrual,
vacation_accrual_avgifter: sre.vacation_accrual_avgifter,
// Dimensions PR8: read-at-book from the employee row.