/** * Period-math helpers for time-tracking. * * Lives OUTSIDE `src/actions/time-tracking/timesheets.ts` because that * file uses the "use server" directive, which requires every export * to be an async function. Pure date math doesn't need to be a server * action — it can run on the client too (e.g. for date pickers). */ /** * Compute the pay-period [start, end] (inclusive) that contains the * given date, given a brand's settings. Falls back to weekly periods * starting Sunday when settings aren't configured. */ export function payPeriodForDate( date: Date, settings: { pay_period_start_day: number; pay_period_length_days: number; } | null, ): { start: Date; end: Date } { const len = settings?.pay_period_length_days ?? 7; if (len === 7) { // Weekly — anchor to Sunday const start = new Date(date); start.setHours(0, 0, 0, 0); start.setDate(date.getDate() - date.getDay()); const end = new Date(start); end.setDate(start.getDate() + 6); return { start, end }; } // Semi-monthly / monthly: anchor by day-of-month const anchor = settings?.pay_period_start_day ?? 1; const start = new Date(date.getFullYear(), date.getMonth(), anchor); if (start > date) start.setMonth(start.getMonth() - 1); const end = new Date(start); end.setDate(start.getDate() + len - 1); if (end < date) { start.setMonth(start.getMonth() + 1); end.setMonth(end.getMonth() + 1); } return { start, end }; } /** YYYY-MM-DD in UTC. */ export function toIsoDate(d: Date): string { return d.toISOString().slice(0, 10); }