Files
accounted/lib/salary/__tests__/vacation-ledger.test.ts
T
MattssonandClaude Opus 5 3bbf2a051b 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>
2026-07-29 13:28:51 +02:00

228 lines
9.5 KiB
TypeScript

/**
* Vacation-year boundaries + ledger sync (payroll gap-closure 3.2).
*/
import { beforeEach, describe, expect, it, vi } from 'vitest'
import type { SupabaseClient } from '@supabase/supabase-js'
import { createQueuedMockSupabase } from '@/tests/helpers'
import {
getClosableYearStart,
getVacationYearBounds,
getVacationYearStart,
} from '@/lib/salary/vacation-year'
import { syncVacationLedgerForEmployees } from '@/lib/salary/vacation-ledger'
describe('vacation-year helpers', () => {
it('calendar basis: Jan 1 boundary', () => {
expect(getVacationYearStart('2026-07-13', 'calendar')).toBe('2026-01-01')
expect(getVacationYearStart('2026-01-01', 'calendar')).toBe('2026-01-01')
expect(getVacationYearBounds('2026-01-01')).toEqual({ start: '2026-01-01', end: '2027-01-01' })
expect(getClosableYearStart('2026-07-13', 'calendar')).toBe('2025-01-01')
})
it('statutory basis: Apr 1 boundary, Jan-Mar belongs to the previous start', () => {
expect(getVacationYearStart('2026-07-13', 'statutory_apr_mar')).toBe('2026-04-01')
expect(getVacationYearStart('2026-03-31', 'statutory_apr_mar')).toBe('2025-04-01')
expect(getVacationYearStart('2026-04-01', 'statutory_apr_mar')).toBe('2026-04-01')
expect(getVacationYearBounds('2025-04-01')).toEqual({ start: '2025-04-01', end: '2026-04-01' })
expect(getClosableYearStart('2026-02-15', 'statutory_apr_mar')).toBe('2024-04-01')
})
})
describe('syncVacationLedgerForEmployees', () => {
const COMPANY_ID = 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa'
const EMPLOYEE_ID = 'bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb'
let mock: ReturnType<typeof createQueuedMockSupabase>
let supabase: SupabaseClient
let upserted: Array<Record<string, unknown>> | null
beforeEach(() => {
vi.clearAllMocks()
upserted = null
mock = createQueuedMockSupabase()
// Wrap from() to capture the upsert payload while keeping queue behavior.
const originalFrom = mock.supabase.from
mock.supabase.from = vi.fn((table: string) => {
const chain = originalFrom(table) as Record<string, unknown>
return new Proxy(chain as object, {
get(target, prop) {
if (prop === 'upsert' && table === 'employee_vacation_balances') {
return (rows: Array<Record<string, unknown>>) => {
upserted = rows
return (target as Record<string, (...a: unknown[]) => unknown>).upsert?.(rows) ?? target
}
}
return (target as Record<string | symbol, unknown>)[prop]
},
})
}) as never
supabase = mock.supabase as unknown as SupabaseClient
})
const queueBase = (over: {
basis?: string
booked?: Array<{ employee_id: string; vacation_days_taken: number; salary_run: { period_year: number; period_month: number; status: string } }>
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({
data: [
{
id: EMPLOYEE_ID,
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
mock.enqueue({ data: over.opening ?? [] }) // opening balances
mock.enqueue({ data: over.openRows ?? [] }) // existing open ledger rows
mock.enqueue({ data: over.booked ?? [] }) // booked sre rows
mock.enqueue({ data: null }) // upsert result
}
it('lazy-seeds the current year and recomputes taken from booked runs', async () => {
queueBase({
booked: [
{ employee_id: EMPLOYEE_ID, vacation_days_taken: 3, salary_run: { period_year: 2026, period_month: 6, status: 'booked' } },
{ employee_id: EMPLOYEE_ID, vacation_days_taken: 2, salary_run: { period_year: 2026, period_month: 7, status: 'booked' } },
// Prior year: outside the current vacation year bounds.
{ employee_id: EMPLOYEE_ID, vacation_days_taken: 5, salary_run: { period_year: 2025, period_month: 7, status: 'booked' } },
],
})
const result = await syncVacationLedgerForEmployees(supabase, COMPANY_ID, [EMPLOYEE_ID], '2026-07-13')
expect(result.ok).toBe(true)
expect(upserted).toHaveLength(1)
const row = upserted![0]
expect(row.vacation_year_start).toBe('2026-01-01')
expect(row.entitled_days).toBe(25)
expect(row.taken_days).toBe(5)
// Calendar basis: sammanfallande year, accrued stays 0.
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: [
{
employee_id: EMPLOYEE_ID,
cutover_date: '2026-07-01',
vacation_paid_days_remaining: 12.5,
vacation_saved_days_by_year: { '2025': 5 },
},
],
})
const result = await syncVacationLedgerForEmployees(supabase, COMPANY_ID, [EMPLOYEE_ID], '2026-07-13')
expect(result.ok).toBe(true)
const row = upserted![0]
expect(row.entitled_days).toBe(12.5)
expect(row.saved_days).toEqual({ '2025': 5 })
})
it('seeds legacy vacation_days_saved under the previous year when no cutover row exists', async () => {
queueBase({ savedLegacy: 4 })
const result = await syncVacationLedgerForEmployees(supabase, COMPANY_ID, [EMPLOYEE_ID], '2026-07-13')
expect(result.ok).toBe(true)
const row = upserted![0]
expect(row.saved_days).toEqual({ '2025': 4 })
})
it('recomputes existing open rows instead of duplicating them', async () => {
queueBase({
openRows: [
{
id: 'row-1',
employee_id: EMPLOYEE_ID,
vacation_year_start: '2026-01-01',
entitled_days: 25,
accrued_days: 0,
taken_days: 99, // stale: recompute must overwrite from booked runs
saved_days: { '2025': 2 },
forced_payout_days: 0,
status: 'open',
},
],
booked: [
{ employee_id: EMPLOYEE_ID, vacation_days_taken: 1, salary_run: { period_year: 2026, period_month: 5, status: 'booked' } },
],
})
const result = await syncVacationLedgerForEmployees(supabase, COMPANY_ID, [EMPLOYEE_ID], '2026-07-13')
expect(result.ok).toBe(true)
expect(upserted).toHaveLength(1)
const row = upserted![0]
expect(row.taken_days).toBe(1)
expect(row.saved_days).toEqual({ '2025': 2 })
})
it('accrues toward next year on the statutory basis (elapsed months / 12)', async () => {
queueBase({ basis: 'statutory_apr_mar' })
const result = await syncVacationLedgerForEmployees(supabase, COMPANY_ID, [EMPLOYEE_ID], '2026-10-15')
expect(result.ok).toBe(true)
const row = upserted![0]
expect(row.vacation_year_start).toBe('2026-04-01')
// Apr -> Oct = 6 whole months: 6/12 x 25 = 12.5.
expect(row.accrued_days).toBe(12.5)
})
it('never throws: DB errors return ok:false (non-fatal contract)', async () => {
mock.enqueue({ data: null }) // company_settings (defaults calendar)
mock.enqueue({ data: null, error: { message: 'boom' } }) // employees fails
const result = await syncVacationLedgerForEmployees(supabase, COMPANY_ID, [EMPLOYEE_ID], '2026-07-13')
expect(result.ok).toBe(false)
})
})