import { ReportData, ReportPeriod, PeriodType, } from "./report.models"; /* ---------- ID BUILDING ---------- */ function formatDate(d: Date): string { const y = d.getUTCFullYear(); const m = String(d.getUTCMonth() + 1).padStart(2, "0"); const day = String(d.getUTCDate()).padStart(2, "0"); return `${y}-${m}-${day}`; } function buildPeriodId( type: PeriodType, start: Date, end: Date ): string { const s = formatDate(start); const e = formatDate(end); switch (type) { case "daily": return `D:${s}_${e}`; case "weekly": return `W:${s}_${e}`; case "monthly": return `M:${s}_${e}`; case "all": return `ALL:${s}_${e}`; default: return `${s}_${e}`; } } /* ---------- LABEL BUILDING ---------- */ const dayFmt = new Intl.DateTimeFormat("en-GB", { day: "numeric", month: "short", timeZone: "UTC", }); const monthDayFmt = new Intl.DateTimeFormat("en-GB", { month: "short", day: "numeric", timeZone: "UTC", }); const monthFmt = new Intl.DateTimeFormat("en-GB", { month: "short", timeZone: "UTC", }); const yearFmt = new Intl.DateTimeFormat("en-GB", { year: "numeric", timeZone: "UTC", }); function buildLabel( type: PeriodType, start: Date, end: Date ): string { switch (type) { case "daily": return dayFmt.format(start); case "weekly": { const sDay = start.getUTCDate(); const m = monthFmt.format(start); return `${sDay} ${m}`; } case "monthly": return `${monthFmt.format(start)} ${yearFmt.format(start)}`; default: return `${monthDayFmt.format(start)} - ${monthDayFmt.format(end)}`; } } /* ---------- MAIN ---------- */ function decoratePeriods( type: PeriodType, periods: ReportPeriod[] ): (ReportPeriod & { id: string; label: string })[] { return periods.map((p) => ({ ...p, id: buildPeriodId(type, new Date(p.start + "Z"), new Date(p.end + "Z")), label: buildLabel(type, new Date(p.start + "Z"), new Date(p.end + "Z")), })); } export function prepareReport(reportData: ReportData): ReportData { return { ...reportData, buckets: reportData.buckets.map((bucket) => { const newPeriods: typeof bucket.periods = {}; for (const type of reportData.periods) { const arr = bucket.periods[type]; if (arr) { newPeriods[type] = decoratePeriods(type, arr); } } return { ...bucket, periods: newPeriods, }; }), }; }