Fix/bank sync bas (#1284)

* fix(year-end): stop revaluing FX items that were not on the balance sheet

The year-end close ran currency revaluation as an unconditional step before
the irreversible close, and the revaluation queried LIVE open invoices with
no date scoping. An invoice issued after balansdagen, settled before it, or
never booked at all was therefore revalued into the year being closed,
writing down a 1510/2440 that stood at zero. Because the entry lands inside
the same run that closes the period, the only remedy left was a rattelse in
the following year.

The population is now measured as of balansdagen, reusing the reconstruction
the reskontra reports already use (fetchPaymentsAsOf / outstandingAsOf): the
invoice_date ceiling is unconditional (post-dated invoices make the bug
reachable for a current period too) and the widening to 'paid' applies only
to a historical date, where a since-settled invoice was still open then.

Rows that carry no balance-sheet exposure are skipped per row rather than per
company: an unbooked registration is not on 1510/2440. Deliberately NOT keyed
on accounting_method, since BFL 5 kap 2 § 3 st requires kontantmetoden
companies to book their outstanding fordringar/skulder at balansdagen, and
those converted rows are genuine exposure that ARL 4 kap. 13 § must value.

The readiness warning stays ungated on purpose: an unbooked FX row is exactly
what deserves a warning, because /book still posts it into the year about to
close and lockPeriod/closePeriod then removes that remedy for good.

The wizard preview now lists the per-invoice revaluation rows it will post
instead of three aggregate numbers, so the user approves line-level content
before the close.

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

* fix(bookkeeping): reach accounts outside BAS 2026 from a verifikat rattelse

A user could not move a verifikat line to konto 8022: the picker reported no
such account and offered no way forward. 8022 was dropped from BAS 2026 (it
is in BAS 2018), so it is a legitimate company-specific underkonto rather
than a catalog gap. Verified against the official bas.se kontoplan that our
BAS reference already matches BAS 2026, so 8022 is deliberately NOT added to
it: seeding a retired account would push it onto every company.

StrikeLinesDialog and CorrectionEntryDialog were the only account pickers in
the app that never passed onCreateAccount, so their combobox rendered a dead
empty state. Both now open AddAccountDialog prefilled, then refetch the chart
and select the new account on the initiating line, leaving the half-finished
rattelse intact.

AccountCombobox closed its dropdown on the fourth digit of any committed
number, which hid the empty state before it was ever painted and made the
create affordance unreachable for exactly the numbers that need it. It now
closes only when the number matches something, so focus still advances to the
belopp field for real accounts.

No change to posting rules: correct_entry_lines_inline validates chart
membership, not BAS membership, and account creation already required the
same write role.

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

* fix(vacation): adjust vacation accrual calculations for mid-year hires and update related logic

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Mattsson
2026-07-29 13:28:51 +02:00
committed by GitHub
co-authored by Claude Opus 5
parent 108f348c84
commit 3bbf2a051b
19 changed files with 1063 additions and 109 deletions
@@ -7,6 +7,7 @@ import {
calculateVacationAccrual,
prorateBaseSalaryForPeriod,
} from '../calculation-engine'
import { calculateVacationPay } from '../absence-calculator'
import type { PayrollConfig } from '../payroll-config'
import type { TaxTableRate } from '../tax-tables'
@@ -641,8 +642,8 @@ describe('hardening: vacation rule contract', () => {
)
expect(r.grossSalary).toBe(40000)
expect(r.vacationCompensation).toBe(0)
// dagslön 40000/21 × 0.43% × 25 ≈ 204.76
expect(r.vacationAccrual).toBeCloseTo(204.76, 1)
// månadslön 40000 × 0.43% × 25/12 ≈ 358.33
expect(r.vacationAccrual).toBeCloseTo(358.33, 1)
})
it('none: nothing accrued, nothing paid out', () => {
@@ -755,8 +756,48 @@ describe('hardening: sammalöneregeln', () => {
}),
config2026, emptyTaxRates
)
// 40000/21 × 0.8% × 25 ≈ 380.95
expect(r.vacationAccrual).toBeCloseTo(380.95, 1)
// 40000 × 0.8% × 25/12 ≈ 666.67
expect(r.vacationAccrual).toBeCloseTo(666.67, 1)
})
it('values the tillägg on the monthly salary, not the dagslön', () => {
const r = calculateSalary(
makeBasicInput({
vacationRule: 'sammaloneregeln', monthlySalary: 36000,
lineItems: [baseLineItem(36000)],
}),
config2026, emptyTaxRates
)
// Semesterlagen 16a §: the tillägg is a share of the MONTHLY salary per
// vacation day (154.80/day here), and only the month's earned share
// (25/12 days) accrues. Valuing it off a dagslön (36000/21) and booking
// all 25 days every run produced 184.29, under-provisioning 2920 by ~43%.
expect(r.vacationAccrual).toBeCloseTo(322.5, 1)
})
it('accrues a day at exactly what absence-calculator later pays out for it', () => {
const monthlySalary = 36000
const semestertillaggRate = 0.0043
const run = calculateSalary(
makeBasicInput({
vacationRule: 'sammaloneregeln', monthlySalary, semestertillaggRate,
lineItems: [baseLineItem(monthlySalary)],
}),
config2026, emptyTaxRates
)
const accrualPerDay = run.vacationAccrual / (25 / 12)
const payoutPerDay = calculateVacationPay({
monthlySalary,
vacationDaysTaken: 1,
vacationRule: 'sammaloneregeln',
semestertillaggRate,
vacationDaysPerYear: 25,
}).tillagg
// 2920 is credited here and relieved there. When the two bases disagreed
// the liability drifted negative on every taken day, which is the defect
// this pins: provision and payout must value a day identically.
expect(accrualPerDay).toBeCloseTo(payoutPerDay, 2)
})
})
@@ -945,8 +986,8 @@ describe('calculateVacationAccrual (standalone export)', () => {
vacationBasis: 40000,
})
expect(partTime.accrual).toBeCloseTo(fullTime.accrual / 2, 1)
// Independent check: 20000/21 × 0.43% × 25 ≈ 102.38
expect(partTime.accrual).toBeCloseTo(102.38, 1)
// Independent check: 20000 × 0.43% × 25/12 ≈ 179.17
expect(partTime.accrual).toBeCloseTo(179.17, 1)
})
it('semesterersattning: 0 accrual with the correct step label', () => {
@@ -65,6 +65,7 @@ describe('syncVacationLedgerForEmployees', () => {
openRows?: Array<Record<string, unknown>>
opening?: Array<Record<string, unknown>>
savedLegacy?: number
employmentStart?: string
}) => {
mock.enqueue({ data: { salary_vacation_year_basis: over.basis ?? 'calendar' } }) // company_settings
mock.enqueue({
@@ -74,6 +75,8 @@ describe('syncVacationLedgerForEmployees', () => {
vacation_days_per_year: 25,
vacation_days_saved: over.savedLegacy ?? 0,
vacation_rule: 'procentregeln',
// Long-tenured by default so the pro-rating cases stay opt-in.
employment_start: over.employmentStart ?? '2015-01-01',
},
],
}) // employees
@@ -104,6 +107,49 @@ describe('syncVacationLedgerForEmployees', () => {
expect(row.accrued_days).toBe(0)
})
it('pro-rates entitled days for a mid-intjänandeår hire (Semesterlagen 7 §)', async () => {
// Hired 2025-05-19. For semesteråret starting 2026-04-01 the intjänandeår
// is 2025-04-01 to 2026-04-01 (365 days), of which 317 were employed:
// 317/365 x 25 = 21.71, rounded UP to 22. Reporting a flat 25 told the
// employee they had three paid days they had not earned.
queueBase({ basis: 'statutory_apr_mar', employmentStart: '2025-05-19' })
const result = await syncVacationLedgerForEmployees(supabase, COMPANY_ID, [EMPLOYEE_ID], '2026-07-13')
expect(result.ok).toBe(true)
const row = upserted![0]
expect(row.vacation_year_start).toBe('2026-04-01')
expect(row.entitled_days).toBe(22)
})
it('gives a full entitlement to someone employed the whole intjänandeår', async () => {
queueBase({ basis: 'statutory_apr_mar', employmentStart: '2015-01-01' })
const result = await syncVacationLedgerForEmployees(supabase, COMPANY_ID, [EMPLOYEE_ID], '2026-07-13')
expect(result.ok).toBe(true)
expect(upserted![0].entitled_days).toBe(25)
})
it('accrues from the employment date, not the vacation-year boundary', async () => {
// Hired 2026-07-01, three whole months into the year starting 2026-04-01
// as of 2026-10-15: 3/12 x 25 = 6.25, held to half days = 6.5. Counting
// from the year boundary instead would credit 12.5.
queueBase({ basis: 'statutory_apr_mar', employmentStart: '2026-07-01' })
const result = await syncVacationLedgerForEmployees(supabase, COMPANY_ID, [EMPLOYEE_ID], '2026-10-15')
expect(result.ok).toBe(true)
expect(upserted![0].accrued_days).toBe(6.5)
})
it('keeps the flat entitlement on a sammanfallande calendar year', async () => {
// Earning and taking share the year there, commonly with förskottssemester,
// so mid-year hires are a CBA question rather than a statutory one.
queueBase({ basis: 'calendar', employmentStart: '2026-05-19' })
const result = await syncVacationLedgerForEmployees(supabase, COMPANY_ID, [EMPLOYEE_ID], '2026-07-13')
expect(result.ok).toBe(true)
expect(upserted![0].entitled_days).toBe(25)
})
it('seeds entitled + saved days from the cutover opening row', async () => {
queueBase({
opening: [
@@ -81,24 +81,20 @@ describe('non-default schedule: 4-day week (divisor 17.33)', () => {
expect(unpaid.amount).toBe(-1731.1)
})
it('sammalöneregeln accrual values days by the schedule divisor', () => {
const fourDay = calculateVacationAccrual({
monthlySalary: 30000,
vacationRule: 'sammaloneregeln',
vacationDaysPerYear: 25,
semestertillaggRate: 0.0043,
vacationBasis: 30000,
dailyDivisor: divisor,
})
const fiveDay = calculateVacationAccrual({
it('sammalöneregeln accrual does NOT take the schedule divisor', () => {
const accrual = calculateVacationAccrual({
monthlySalary: 30000,
vacationRule: 'sammaloneregeln',
vacationDaysPerYear: 25,
semestertillaggRate: 0.0043,
vacationBasis: 30000,
})
// dailyRate 1731.1 vs 1428.57; tillägg = dailyRate x 0.43% x 25 days.
expect(fourDay.accrual).toBe(186.09)
expect(fiveDay.accrual).toBe(153.57)
// Semestertillägg is a share of the MONTHLY salary per vacation day, so a
// 4-day week earns the same tillägg as a 5-day week on the same monthly
// salary: 30000 x 0.43% x 25/12. The function deliberately exposes no
// divisor parameter; part-time is carried by vacationBasis instead.
// Previously this valued a day at monthly/divisor, which made the accrual
// vary with workdays per week and under-provisioned 2920 in every case.
expect(accrual.accrual).toBeCloseTo(268.75, 2)
})
})
+42 -17
View File
@@ -36,8 +36,10 @@ export interface SalaryCalculationInput {
semestertillaggRate: number
/** Work-schedule daily-rate divisor (arbetsschema-lite). Defaults to the
* legacy 21 (5-day week); callers with a part-time schedule pass
* dailyDivisor(workdays_per_week) from lib/salary/work-schedule. Used by
* the sammalöneregeln day valuation. */
* dailyDivisor(workdays_per_week) from lib/salary/work-schedule. Feeds the
* daily-rate absence paths only. Deliberately NOT the sammalöneregeln
* accrual: semestertillägg is a share of the monthly salary per vacation
* day and does not vary with workdays per week. */
dailyDivisor?: number
/** Växa-stöd */
@@ -545,19 +547,36 @@ export function calculateSalary(
})
} else {
// Sammalöneregeln (§16a): employee keeps regular salary during vacation
// + semestertillägg per day (min 0.43%, often 0.8% per CBA)
// + semestertillägg per vacation day (min 0.43%, often 0.8% per CBA)
// Accrual = tillägg only (salary cost is already in normal monthly expense)
// The liability (2920) for sammalöneregeln is the tillägg portion,
// since the base salary is expensed monthly regardless of vacation.
//
// The tillägg is a share of the MONTHLY salary per vacation day, never of
// the dagslön. Valuing it off a daily rate under-provisioned 2920 by the
// whole divisor, while absence-calculator.ts relieves that same 2920 at
// the correct monthly base when a day is taken, so the liability drifted
// further negative with every taken day.
//
// Only the month's earned share accrues. The full annual entitlement used
// to be booked in every single run; the two errors partly cancelled, which
// is why the monthly total looked plausible while both halves were wrong.
//
// Use baseSalary (degree-adjusted): a 50% part-timer's tillägg should be
// half a full-timer's, not the same.
const dailyRate = r(baseSalary / (input.dailyDivisor ?? 21))
const tillagg = r(dailyRate * input.semestertillaggRate * input.vacationDaysPerYear)
// half a full-timer's, not the same. The schedule divisor deliberately
// plays no part: semestertillägg does not depend on workdays per week.
const daysEarnedThisMonth = input.vacationDaysPerYear / 12
const tillagg = r(baseSalary * input.semestertillaggRate * daysEarnedThisMonth)
vacationAccrual = tillagg
steps.push({
label: `Semesteravsättning (sammalöneregeln, tillägg ${fmtPct(input.semestertillaggRate)})`,
formula: `dagslön × ${fmtPct(input.semestertillaggRate)} × semesterdagar`,
input: { daily_rate: dailyRate, semestertillagg_rate: input.semestertillaggRate, vacation_days: input.vacationDaysPerYear },
formula: `månadslön × ${fmtPct(input.semestertillaggRate)} × semesterdagar / 12`,
input: {
monthly_base: baseSalary,
semestertillagg_rate: input.semestertillaggRate,
vacation_days_per_year: input.vacationDaysPerYear,
days_earned_this_month: r(daysEarnedThisMonth),
},
output: vacationAccrual,
})
}
@@ -775,8 +794,6 @@ export function calculateVacationAccrual(params: {
vacationDaysPerYear: number
semestertillaggRate: number
vacationBasis: number
/** Arbetsschema-lite daily-rate divisor; legacy 21 when omitted. */
dailyDivisor?: number
}): { accrual: number; steps: CalculationStep[] } {
const steps: CalculationStep[] = []
@@ -811,15 +828,23 @@ export function calculateVacationAccrual(params: {
})
return { accrual, steps }
} else {
// Sammalöneregeln: tillägg per vacation day. Use vacationBasis as the
// degree-adjusted reference: callers must pass the part-time-adjusted
// monthly amount, never the raw full-time monthlySalary.
const dailyRate = r(params.vacationBasis / (params.dailyDivisor ?? 21))
const accrual = r(dailyRate * params.semestertillaggRate * params.vacationDaysPerYear)
// Sammalöneregeln: tillägg per vacation day, valued on the MONTHLY salary
// and accrued one month's earned share at a time. See the mirrored branch
// in calculateSalary for why neither a dagslön base nor the full annual
// entitlement belongs here. Use vacationBasis as the degree-adjusted
// reference: callers must pass the part-time-adjusted monthly amount,
// never the raw full-time monthlySalary.
const daysEarnedThisMonth = params.vacationDaysPerYear / 12
const accrual = r(params.vacationBasis * params.semestertillaggRate * daysEarnedThisMonth)
steps.push({
label: `Semesteravsättning (sammalöneregeln ${fmtPct(params.semestertillaggRate)})`,
formula: `dagslön × ${fmtPct(params.semestertillaggRate)} × semesterdagar`,
input: { daily_rate: dailyRate, rate: params.semestertillaggRate, days: params.vacationDaysPerYear },
formula: `månadslön × ${fmtPct(params.semestertillaggRate)} × semesterdagar / 12`,
input: {
monthly_base: params.vacationBasis,
rate: params.semestertillaggRate,
vacation_days_per_year: params.vacationDaysPerYear,
days_earned_this_month: r(daysEarnedThisMonth),
},
output: accrual,
})
return { accrual, steps }
+87 -10
View File
@@ -73,7 +73,7 @@ export async function syncVacationLedgerForEmployees(
const { data: employees, error: empErr } = await supabase
.from('employees')
.select('id, vacation_days_per_year, vacation_days_saved, vacation_rule')
.select('id, vacation_days_per_year, vacation_days_saved, vacation_rule, employment_start')
.eq('company_id', companyId)
.in('id', employeeIds)
if (empErr) return { ok: false, message: empErr.message }
@@ -83,6 +83,7 @@ export async function syncVacationLedgerForEmployees(
vacation_days_per_year: number
vacation_days_saved: number
vacation_rule: string
employment_start: string
}>).map((e) => [e.id, e]),
)
@@ -156,7 +157,7 @@ export async function syncVacationLedgerForEmployees(
employee_id: employeeId,
vacation_year_start: row.vacation_year_start,
entitled_days: row.entitled_days,
accrued_days: computeAccruedDays(basis, row.vacation_year_start, asOfDate, employee.vacation_days_per_year),
accrued_days: computeAccruedDays(basis, row.vacation_year_start, asOfDate, employee.vacation_days_per_year, employee.employment_start),
taken_days: takenInYear(employeeId, row.vacation_year_start),
saved_days: row.saved_days ?? {},
forced_payout_days: row.forced_payout_days ?? 0,
@@ -189,11 +190,18 @@ export async function syncVacationLedgerForEmployees(
company_id: companyId,
employee_id: employeeId,
vacation_year_start: currentYearStart,
// A cutover opening balance is the migrated truth from the previous
// system and outranks any recomputation.
entitled_days:
cutoverInThisYear && opening
? opening.vacation_paid_days_remaining
: employee.vacation_days_per_year,
accrued_days: computeAccruedDays(basis, currentYearStart, asOfDate, employee.vacation_days_per_year),
: computeEntitledDays(
basis,
currentYearStart,
employee.vacation_days_per_year,
employee.employment_start,
),
accrued_days: computeAccruedDays(basis, currentYearStart, asOfDate, employee.vacation_days_per_year, employee.employment_start),
taken_days: takenInYear(employeeId, currentYearStart),
saved_days: savedDays,
forced_payout_days: 0,
@@ -220,24 +228,93 @@ export async function syncVacationLedgerForEmployees(
* Apr-Mar basis, where intjänandeår (this year) and semesterår (next year)
* are split. Sammanfallande calendar years earn and take in the same year,
* so the live number is entitled - taken and accrued stays 0.
*
* Earning starts on the employment date, not on the year boundary: a mid-year
* hire has not earned the months before their first day, and showing them the
* full year's accrual overstates what they may take.
*/
function computeAccruedDays(
basis: VacationYearBasis,
yearStart: string,
asOfDate: string,
vacationDaysPerYear: number,
employmentStart: string,
): number {
if (basis !== 'statutory_apr_mar') return 0
const bounds = getVacationYearBounds(yearStart)
if (asOfDate < bounds.start) return 0
if (asOfDate >= bounds.end) return vacationDaysPerYear
const startYear = Number(yearStart.slice(0, 4))
const startMonth = Number(yearStart.slice(5, 7))
const asOfYear = Number(asOfDate.slice(0, 4))
const asOfMonth = Number(asOfDate.slice(5, 7))
const elapsedMonths = (asOfYear - startYear) * 12 + (asOfMonth - startMonth)
// Employed only after this earning year closed: nothing earned in it.
if (employmentStart >= bounds.end) return 0
const earningStart = employmentStart > bounds.start ? employmentStart : bounds.start
const effectiveAsOf = asOfDate >= bounds.end ? bounds.end : asOfDate
const elapsedMonths = wholeMonthsBetween(earningStart, effectiveAsOf)
// Whole elapsed months / 12, rounded to half days (Semesterlagen 3a §
// rounds UP to whole days at payout; the running accrual view keeps halves
// for transparency).
return Math.round(((elapsedMonths / 12) * vacationDaysPerYear) * 2) / 2
}
/** Whole calendar months from `from` to `to`, day-of-month ignored (the
* pre-existing convention of this view). */
function wholeMonthsBetween(from: string, to: string): number {
const months =
(Number(to.slice(0, 4)) - Number(from.slice(0, 4))) * 12 +
(Number(to.slice(5, 7)) - Number(from.slice(5, 7)))
return months > 0 ? months : 0
}
/**
* Betalda semesterdagar for a semesterår, per Semesterlagen 7 §:
*
* anställningsdagar under intjänandeåret / dagar under intjänandeåret
* x semesterdagar, and "om ett brutet tal då uppstår, avrundas detta till
* närmast högre hela tal" (round UP, always).
*
* The intjänandeår is the twelve months immediately preceding the semesterår
* (3 §), so someone hired part-way through it earns proportionally fewer PAID
* days while keeping the right to take unpaid ones.
*
* Two deliberate omissions, both of which can only overstate entitlement and
* never understate it, so neither can silently deny an employee a paid day:
*
* - 7 § also subtracts days of unpaid full-day absence. The ledger has no
* unpaid-absence day source, so that term is not modelled.
* - 4 § second sentence caps semesterLEDIGHET at five days when employment
* starts after 31 August of the semesterår. That is a cap on days off,
* paid or unpaid, which is a different quantity from the paid days 7 §
* computes, so it does not belong in this number.
*
* Only applied on the statutory basis. Under sammanfallande semesterår the
* employee earns and takes in the same year, commonly with förskottssemester,
* and how a mid-year hire is treated is a collective-agreement question rather
* than a statutory one. Those companies keep the flat entitlement until that
* is decided.
*/
export function computeEntitledDays(
basis: VacationYearBasis,
yearStart: string,
vacationDaysPerYear: number,
employmentStart: string,
): number {
if (basis !== 'statutory_apr_mar') return vacationDaysPerYear
// The intjänandeår is the year immediately BEFORE this semesterår.
const semesterBounds = getVacationYearBounds(yearStart)
const earningStart = shiftYear(semesterBounds.start, -1)
const earningEnd = semesterBounds.start
if (employmentStart >= earningEnd) return 0
const totalDays = daysBetween(earningStart, earningEnd)
if (totalDays <= 0) return vacationDaysPerYear
const employedFrom = employmentStart > earningStart ? employmentStart : earningStart
const employedDays = daysBetween(employedFrom, earningEnd)
const quota = (employedDays / totalDays) * vacationDaysPerYear
return Math.min(vacationDaysPerYear, Math.ceil(quota))
}
function shiftYear(iso: string, delta: number): string {
return `${Number(iso.slice(0, 4)) + delta}${iso.slice(4)}`
}
function daysBetween(from: string, to: string): number {
const ms = Date.parse(`${to}T00:00:00Z`) - Date.parse(`${from}T00:00:00Z`)
return Math.round(ms / 86_400_000)
}