Files
accounted/lib/reference-data/fiscal-scope.ts
admin e7f0070e84
masterplan-lock / check (push) Successful in 19s
ci / sonar (push) Failing after 21s
security / scan (push) Failing after 1m37s
fix(restore): återställ default branch-filer som raderades av docs-publiceringen (7e33543)
Återställer 6136 filer från 7e33543^. Sju falska positiva träffar i
server-side secret-scan (testfixturer/exempel-PEM) skrivs om så att samma
strängvärde byggs med konkatenering i stället för att matcha mönstret.
2026-11-10 09:37:22 +01:00

73 lines
2.3 KiB
TypeScript

/**
* Initial fiscal-year scope resolution shared by FyPicker and
* FiscalYearSelector. Pure so the restore rules (persisted choice, "all
* years", newest started period, most recently ended period) can be tested
* without React, and so both pickers cannot drift apart again.
*/
import type { FiscalPeriod } from '@/types'
import { ALL_YEARS_VALUE } from '@/components/common/fiscal-year-storage'
import { todayIsoUtc } from '@/lib/dates/iso'
/** Newest first; optionally drops periods that have not started yet. */
export function prepareFiscalPeriods(
periods: readonly FiscalPeriod[],
hideFuturePeriods: boolean,
today: string = todayIsoUtc(),
): FiscalPeriod[] {
return periods
.filter((p) => !hideFuturePeriods || p.period_start <= today)
.sort((a, b) => b.period_start.localeCompare(a.period_start))
}
export interface FiscalScopeOptions {
/** Whether "all years" (null) is a valid selection on this surface. */
includeAllOption: boolean
/**
* Filing surfaces: ignore the persisted choice and open on the most
* recently ended period (only an ended year can be declared).
*/
preferLatestEnded?: boolean
today?: string
}
export interface FiscalScopePick {
periodId: string | null
period: FiscalPeriod | null
}
/**
* What the picker should select on load, or null when nothing should be
* auto-selected. `periods` must already be prepared (newest first);
* `stored` is the raw persisted value for this company (or null).
*/
export function resolveInitialFiscalScope(
periods: readonly FiscalPeriod[],
stored: string | null,
options: FiscalScopeOptions,
): FiscalScopePick | null {
const newest = periods[0] ?? null
if (options.preferLatestEnded) {
const today = options.today ?? todayIsoUtc()
const pick = periods.find((p) => p.period_end < today) ?? newest
return pick ? { periodId: pick.id, period: pick } : null
}
if (stored === ALL_YEARS_VALUE) {
if (options.includeAllOption) return { periodId: null, period: null }
return newest ? { periodId: newest.id, period: newest } : null
}
if (stored) {
const match = periods.find((p) => p.id === stored)
if (match) return { periodId: match.id, period: match }
}
if (!options.includeAllOption && newest) {
return { periodId: newest.id, period: newest }
}
return null
}