/** * Fiscal years (Geschäftsjahr, Wirtschaftsjahr): calendar years, deviating * years and short years (Rumpfwirtschaftsjahre), built from the dated * regimes of the month the years start in. Pure functions over days as * `YYYY-MM-DD` (UTC). * * The rules, as the law states them: * - "Die Dauer des Geschäftsjahrs darf zwölf Monate nicht überschreiten" * (§ 240 Abs. 2 Satz 2 HGB); "Das Wirtschaftsjahr umfasst einen Zeitraum von * zwölf Monaten" (§ 8b Satz 1 EStDV). * - It may be shorter "wenn 1. ein Betrieb eröffnet, erworben, aufgegeben oder * veräußert wird oder 2. ein Steuerpflichtiger von regelmäßigen Abschlüssen * auf einen bestimmten Tag zu regelmäßigen Abschlüssen auf einen anderen * bestimmten Tag übergeht" (§ 8b Satz 2 EStDV). * - A change from the calendar year to a deviating year, or from one deviating * year to another, counts only "wenn die Umstellung im Einvernehmen mit dem * Finanzamt vorgenommen wird" (§ 8b Satz 3 EStDV; § 4a Abs. 1 Nr. 2 Satz 2 * EStG). A change back to the calendar year needs no consent. * * Who may have a deviating year at all is tax law about the business (§ 4a * Abs. 1 EStG: a trader registered in the Handelsregister; other traders the * calendar year, Land- und Forstwirte 1 July to 30 June), and whether the * consent was given is a fact of the business; the caller decides both. This * module builds the calendar and says where a consent is needed. */ /** * From `from` on, fiscal years start on day `startDay` (1 when absent) of * `startMonth`; `from` is such a day. A regular year is twelve months, and * nothing in § 240 Abs. 2 HGB, § 8b EStDV or § 4a EStG ties it to the first * of a month. */ export interface IFiscalYearRegime { from: string; /** 1 (the calendar year) to 12 */ startMonth: number; /** * 1 when absent; at most the last day the month has in every year: 28 for * February, 30 for April, June, September and November, else 31 */ startDay?: number; } export interface IFiscalYearsInput { /** the regimes, in any order, each `from` at most once; the one in force on a day is the one with the latest `from` up to it */ regimes: readonly IFiscalYearRegime[]; /** the first day of the books: the opening of the business, or the first day of the first year kept here */ firstDay: string; /** the last day of the business, when it was closed or sold */ lastDay?: string; /** every year up to the one that contains this day */ through: string; } /** Why a fiscal year is shorter than twelve months (§ 8b Satz 2 EStDV). */ export type TShortYearReason = /** the books begin on a day that is no start of a year: the business opened or was acquired (Nr. 1) */ | 'opening' /** the business closed or was sold (Nr. 1) */ | 'closing' /** both within the one year */ | 'opening_and_closing' /** the closing day changed at its end (Nr. 2) */ | 'change'; export interface IFiscalYearSpan { /** the first and the last day, both included */ start: string; end: string; /** * the fewest months after `start` that reach past `end` (a month begun * counts whole): 2026-03-15..2026-12-31 is 10, 2026-03-15..2027-03-14 is 12. * Months are counted as § 188 Abs. 2, 3 BGB counts them (§ 108 Abs. 1 AO): * 2026-01-31..2026-02-28 is 1, 2026-08-31..2027-02-28 is 6. */ months: number; /** * a Rumpfwirtschaftsjahr: the day after `end` is not twelve months after * `start` (§ 188 Abs. 2, 3 BGB: 2028-02-29..2029-02-28 is twelve months), or * the year opens the books on a day that is no start of a year */ short: boolean; shortReason?: TShortYearReason; /** * The short year of a change to a closing day other than 31 December: * valid for tax only in agreement with the Finanzamt (§ 8b Satz 3 EStDV, * § 4a Abs. 1 Nr. 2 Satz 2 EStG). */ consentRequired: boolean; /** `2026`, or `2025/26` for a year that crosses the calendar year */ label: string; /** * The calendar year the fiscal year ends in: the year a trader's profit of * it counts in (§ 4a Abs. 2 Nr. 2 EStG). A Land- und Forstwirt's profit is * split between both calendar years instead (Nr. 1). */ taxYear: number; } const DAY_MS = 86_400_000; const ISO_DAY = /^\d{4}-\d{2}-\d{2}$/u; const parseDay = (valueArg: unknown): number | null => { if (typeof valueArg !== 'string' || !ISO_DAY.test(valueArg)) return null; const time = Date.parse(`${valueArg}T00:00:00.000Z`); if (Number.isNaN(time) || new Date(time).toISOString().slice(0, 10) !== valueArg) return null; return time; }; const requireDay = (valueArg: string, nameArg: string): number => { const time = parseDay(valueArg); if (time === null) throw new Error(`${nameArg} must be a day as YYYY-MM-DD, not "${String(valueArg)}"`); return time; }; const dayOf = (timeArg: number): string => new Date(timeArg).toISOString().slice(0, 10); /** The last day every year has in a month: 28 for February, 30 for April, June, September, November, else 31. */ const everyYearLastDayOf = (monthArg: number): number => (monthArg === 2 ? 28 : [4, 6, 9, 11].includes(monthArg) ? 30 : 31); /** * The first day after a period of `monthsArg` months that begins with the * start of `dayArg`. § 108 Abs. 1 AO applies §§ 187-193 BGB. Such a period * ends "mit dem Ablauf desjenigen Tages des letzten Monats, welcher dem Tage * vorhergeht, der durch seine … Zahl dem Anfangstag der Frist entspricht" * (§ 188 Abs. 2 BGB, with § 187 Abs. 2). Where the last month lacks that day, * it ends "mit dem Ablauf des letzten Tages dieses Monats" (§ 188 Abs. 3). So * the day after is the matching day, or else the 1st of the next month: * 2026-01-31 + 1 month = 2026-03-01, 2028-02-29 + 12 months = 2029-03-01. */ const periodAfter = (dayArg: number, monthsArg: number): number => { const date = new Date(dayArg); const monthIndex = date.getUTCMonth() + monthsArg; const year = date.getUTCFullYear() + Math.floor(monthIndex / 12); const month = ((monthIndex % 12) + 12) % 12; const lastDay = new Date(Date.UTC(year, month + 1, 0)).getUTCDate(); return date.getUTCDate() <= lastDay ? Date.UTC(year, month, date.getUTCDate()) : Date.UTC(year, month + 1, 1); }; /** Day `dayArg` of `monthArg` next after `afterArg`. */ const nextStartAfter = (afterArg: number, monthArg: number, dayArg: number): number => { const after = new Date(afterArg); const thisYear = Date.UTC(after.getUTCFullYear(), monthArg - 1, dayArg); return thisYear > afterArg ? thisYear : Date.UTC(after.getUTCFullYear() + 1, monthArg - 1, dayArg); }; /** The fewest months after `startArg` that reach past `endArg`. */ const monthsOf = (startArg: number, endArg: number): number => { let months = 1; while (periodAfter(startArg, months) <= endArg) months++; return months; }; /** * The fiscal years from the first day of the books through the year that * contains `through` (or to the business's last day). A year starts on the * first day of the books, on every `startDay` of the start month of the * regime in force, and on every regime's `from`; it ends the day before the * next start, or on the last day. Refuses a regime whose `from` is not day * `startDay` of its start month, a start month outside 1 to 12, a `startDay` * outside 1 to the month's every-year last day, a `from` given twice, a first * day before every regime, and `through` or the last day before the first day. */ export function fiscalYearsOf(input: IFiscalYearsInput): IFiscalYearSpan[] { const regimes = [...(input.regimes ?? [])] .map((regimeArg) => { if (!Number.isInteger(regimeArg.startMonth) || regimeArg.startMonth < 1 || regimeArg.startMonth > 12) { throw new Error(`a regime's startMonth is 1 to 12, not ${String(regimeArg.startMonth)}`); } const startDay = regimeArg.startDay ?? 1; const maxDay = everyYearLastDayOf(regimeArg.startMonth); if (!Number.isInteger(startDay) || startDay < 1 || startDay > maxDay) { throw new Error( `a regime's startDay in month ${regimeArg.startMonth} is 1 to ${maxDay}, the last day that month has in every year, not ${String(regimeArg.startDay)}`, ); } const from = requireDay(regimeArg.from, "a regime's from"); const date = new Date(from); if (date.getUTCDate() !== startDay || date.getUTCMonth() + 1 !== regimeArg.startMonth) { throw new Error(`the regime from ${regimeArg.from} must begin on day ${startDay} of its start month ${regimeArg.startMonth}`); } return { from, startMonth: regimeArg.startMonth, startDay }; }) .sort((leftArg, rightArg) => leftArg.from - rightArg.from); if (regimes.length === 0) throw new Error('the fiscal years need at least one regime of their start month'); regimes.forEach((regimeArg, indexArg) => { if (indexArg > 0 && regimes[indexArg - 1].from === regimeArg.from) { throw new Error(`the regime from ${dayOf(regimeArg.from)} is given twice`); } }); const firstDay = requireDay(input.firstDay, 'firstDay'); const through = requireDay(input.through, 'through'); const lastDay = input.lastDay === undefined ? undefined : requireDay(input.lastDay, 'lastDay'); if (through < firstDay) throw new Error(`through ${input.through} is before the first day ${input.firstDay}`); if (lastDay !== undefined && lastDay < firstDay) throw new Error(`the last day ${input.lastDay} is before the first day ${input.firstDay}`); if (regimes[0].from > firstDay) { throw new Error(`no regime is in force on the first day ${input.firstDay}: the earliest begins ${dayOf(regimes[0].from)}`); } const regimeOn = (dayArg: number): { from: number; startMonth: number; startDay: number } => regimes.filter((regimeArg) => regimeArg.from <= dayArg).pop() ?? regimes[0]; const isBoundary = (dayArg: number): boolean => { const date = new Date(dayArg); const regime = regimeOn(dayArg); return date.getUTCDate() === regime.startDay && date.getUTCMonth() + 1 === regime.startMonth; }; const years: IFiscalYearSpan[] = []; const stop = lastDay !== undefined && lastDay < through ? lastDay : through; let start = firstDay; while (start <= stop) { const regime = regimeOn(start); const boundary = nextStartAfter(start, regime.startMonth, regime.startDay); const nextRegime = regimes.find((regimeArg) => regimeArg.from > start)?.from; const next = nextRegime !== undefined && nextRegime < boundary ? nextRegime : boundary; const closes = lastDay !== undefined && lastDay < next; const end = closes && lastDay !== undefined ? lastDay : next - DAY_MS; const twelveMonthsOn = periodAfter(start, 12); if (end + DAY_MS > twelveMonthsOn) { throw new Error(`the fiscal year from ${dayOf(start)} to ${dayOf(end)} would be longer than twelve months (§ 240 Abs. 2 Satz 2 HGB)`); } const opens = years.length === 0 && !isBoundary(start); // twelve months counted as § 188 BGB counts them; an opening year that starts off a boundary is always short // (with § 188 counting it never reaches the twelve months anyway), and a closing on a year's last day leaves it whole const short = opens || end + DAY_MS !== twelveMonthsOn; const shortReason: TShortYearReason | undefined = !short ? undefined : opens && closes ? 'opening_and_closing' : closes ? 'closing' : opens ? 'opening' : 'change'; const startDay = dayOf(start); const endDay = dayOf(end); const startYear = Number(startDay.slice(0, 4)); const endYear = Number(endDay.slice(0, 4)); years.push({ start: startDay, end: endDay, months: monthsOf(start, end), short, ...(shortReason ? { shortReason } : {}), consentRequired: shortReason === 'change' && !endDay.endsWith('-12-31'), label: startYear === endYear ? String(startYear) : `${startYear}/${endDay.slice(2, 4)}`, taxYear: endYear, }); if (closes) break; start = end + DAY_MS; } return years; } /** The fiscal year among `spans` that contains the day, or undefined. */ export function fiscalYearOfDay(spans: readonly IFiscalYearSpan[], day: string): IFiscalYearSpan | undefined { requireDay(day, 'the day'); return spans.find((spanArg) => spanArg.start <= day && day <= spanArg.end); }