* fix(reports): stabilize fetchAllRows paging to stop doubled/dropped balances (#790, #791) PostgREST `.range()` paging is only correct when the underlying query has a stable TOTAL order. Several aggregating report queries (general ledger, trial balance, grundbok, supplier/AR ledgers, etc.) paginated without `.order()`, so on datasets larger than one 1000-row page Postgres could return rows in a different order between requests — silently DUPLICATING or SKIPPING rows on a page boundary and doubling or dropping financial totals. - fetch-all.ts: document the ordering invariant and add an optional `dedupeBy` defense-in-depth that drops cross-page duplicates and warns when it fires (surfaces a missing `.order()` in logs instead of corrupting money). - Add a stable `.order()` (line PK or account_number) to every paginated query in lib/reports/ and the account-balances route; pass `dedupeBy` on the money-aggregating line queries. - Add fetch-all unit tests and update report test fixtures to carry row ids. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix(api): declare the real { data, meta } envelope on v1 single/write/204 endpoints (#794) The OpenAPI generator derives each endpoint's documented body purely from its registered `response.success` Zod schema, and that schema is never validated at runtime — so a route could advertise a shape its handler never sends. #802 fixed this for list endpoints; the same drift was latent on single-resource and write endpoints, which declared the bare resource schema instead of the `{ data, meta }` envelope the handlers actually return. - registry.ts: extend `ResponseMetaSchema` with the optional `audit` block and `partial_expansions` list that writes/expansions emit; add the `NoBodyResponse` sentinel so 204 DELETE handlers document a bare 204 instead of a phantom 200. - Wrap every single/write endpoint's `response.success` in `dataEnvelope(...)` (or `NoBodyResponse` for 204s) across the v1 routes. - Add a response-envelope contract test that fails CI if any JSON endpoint forgets to wrap its schema, with binary downloads and 204s as the only exemptions. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix(reports): extend paging dedupeBy to rc-basis-gaps and opening-balances Address PR review: these two money-aggregating line queries already had the stable `.order('id')` (so paging was correct) but didn't carry `id` in the select, so they couldn't use the `dedupeBy` defense-in-depth that general-ledger and trial-balance got. Select `id` and pass `dedupeBy: r => r.id` so the whole report layer applies the ordering invariant consistently. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
150 lines
5.1 KiB
TypeScript
150 lines
5.1 KiB
TypeScript
import type { SupabaseClient } from '@supabase/supabase-js'
|
|
import { fetchAllRows } from '@/lib/supabase/fetch-all'
|
|
|
|
/**
|
|
* Semesterlöneskuld — Vacation liability report per BFNAR 2016:10.
|
|
*
|
|
* Per BFNAR 2016:10 kap 16: Vacation liability must be calculated per employee,
|
|
* not as a lump sum. This report shows earned/taken days, accrued SEK amount
|
|
* on account 2920, and accrued avgifter on account 2940.
|
|
*
|
|
* The report is required for year-end closing and ongoing monthly review.
|
|
* Per BFL 7 kap: retained 7 years as part of räkenskapsinformation.
|
|
*/
|
|
|
|
export interface VacationLiabilityRow {
|
|
employeeId: string
|
|
employeeName: string
|
|
personnummerLast4: string
|
|
vacationRule: string
|
|
vacationDaysEntitled: number
|
|
vacationDaysTaken: number
|
|
vacationDaysRemaining: number
|
|
vacationDaysSaved: number
|
|
accruedAmount: number // Account 2920
|
|
accruedAvgifter: number // Account 2940
|
|
avgifterRate: number
|
|
totalLiability: number // 2920 + 2940
|
|
}
|
|
|
|
export interface VacationLiabilityReport {
|
|
rows: VacationLiabilityRow[]
|
|
totals: {
|
|
accruedAmount: number // Sum for account 2920
|
|
accruedAvgifter: number // Sum for account 2940
|
|
totalLiability: number
|
|
}
|
|
asOfDate: string
|
|
}
|
|
|
|
/**
|
|
* Generate vacation liability report.
|
|
*
|
|
* Aggregates vacation accruals from all booked salary runs in the year
|
|
* and compares against vacation days taken.
|
|
*/
|
|
export async function generateVacationLiability(
|
|
supabase: SupabaseClient,
|
|
companyId: string,
|
|
year: number
|
|
): Promise<VacationLiabilityReport> {
|
|
const r = (x: number) => Math.round(x * 100) / 100
|
|
|
|
// Load active employees who actually accrue vacation. Employees on
|
|
// 'none' or 'semesterersattning' have no semesterlöneskuld liability —
|
|
// including them in the report would just show empty rows.
|
|
const employees = await fetchAllRows(({ from, to }) =>
|
|
supabase
|
|
.from('employees')
|
|
.select('id, first_name, last_name, personnummer_last4, vacation_rule, vacation_days_per_year, vacation_days_saved')
|
|
.eq('company_id', companyId)
|
|
.eq('is_active', true)
|
|
.not('vacation_rule', 'in', '(none,semesterersattning)')
|
|
.order('last_name')
|
|
// id tiebreaker — last_name is not unique, so it alone is not a stable
|
|
// total order for paging (see fetch-all.ts).
|
|
.order('id', { ascending: true })
|
|
.range(from, to)
|
|
)
|
|
|
|
// Load salary run employees for booked runs this year (server-side filtered via !inner join)
|
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
const bookedForYear: any[] = await fetchAllRows(({ from, to }) =>
|
|
supabase
|
|
.from('salary_run_employees')
|
|
.select(`
|
|
employee_id,
|
|
vacation_accrual,
|
|
vacation_accrual_avgifter,
|
|
avgifter_rate,
|
|
vacation_days_taken,
|
|
salary_run:salary_runs!inner(period_year, status)
|
|
`)
|
|
.eq('company_id', companyId)
|
|
.eq('salary_runs.period_year', year)
|
|
.eq('salary_runs.status', 'booked')
|
|
// Stable total order for correct paging (see fetch-all.ts).
|
|
.order('id', { ascending: true })
|
|
.range(from, to)
|
|
)
|
|
|
|
// Client-side safety check: ensure server-side !inner filter was applied
|
|
const verifiedBookedForYear = bookedForYear.filter(sre => {
|
|
const run = sre.salary_run as unknown as { period_year: number; status: string } | null
|
|
return run && run.period_year === year && run.status === 'booked'
|
|
})
|
|
|
|
// Aggregate per employee
|
|
const accrualsByEmployee = new Map<string, {
|
|
totalAccrual: number
|
|
totalAvgifter: number
|
|
totalDaysTaken: number
|
|
lastRate: number
|
|
}>()
|
|
|
|
for (const sre of verifiedBookedForYear) {
|
|
const current = accrualsByEmployee.get(sre.employee_id) || {
|
|
totalAccrual: 0, totalAvgifter: 0, totalDaysTaken: 0, lastRate: 0.3142,
|
|
}
|
|
current.totalAccrual += sre.vacation_accrual
|
|
current.totalAvgifter += sre.vacation_accrual_avgifter
|
|
current.totalDaysTaken += sre.vacation_days_taken
|
|
current.lastRate = sre.avgifter_rate
|
|
accrualsByEmployee.set(sre.employee_id, current)
|
|
}
|
|
|
|
const rows: VacationLiabilityRow[] = employees.map(emp => {
|
|
const accruals = accrualsByEmployee.get(emp.id)
|
|
const accruedAmount = r(accruals?.totalAccrual || 0)
|
|
const accruedAvgifter = r(accruals?.totalAvgifter || 0)
|
|
const daysTaken = accruals?.totalDaysTaken || 0
|
|
|
|
return {
|
|
employeeId: emp.id,
|
|
employeeName: `${emp.first_name} ${emp.last_name}`,
|
|
personnummerLast4: emp.personnummer_last4,
|
|
vacationRule: emp.vacation_rule,
|
|
vacationDaysEntitled: emp.vacation_days_per_year,
|
|
vacationDaysTaken: daysTaken,
|
|
vacationDaysRemaining: emp.vacation_days_per_year - daysTaken,
|
|
vacationDaysSaved: emp.vacation_days_saved,
|
|
accruedAmount,
|
|
accruedAvgifter,
|
|
avgifterRate: accruals?.lastRate || 0.3142,
|
|
totalLiability: r(accruedAmount + accruedAvgifter),
|
|
}
|
|
})
|
|
|
|
const totals = {
|
|
accruedAmount: r(rows.reduce((s, row) => s + row.accruedAmount, 0)),
|
|
accruedAvgifter: r(rows.reduce((s, row) => s + row.accruedAvgifter, 0)),
|
|
totalLiability: r(rows.reduce((s, row) => s + row.totalLiability, 0)),
|
|
}
|
|
|
|
return {
|
|
rows,
|
|
totals,
|
|
asOfDate: `${year}-12-31`,
|
|
}
|
|
}
|