import { Router } from "express"; import { requireAuth, requireRole } from "../auth/middleware.js"; import { buildMonthlyReport, isPeriodId, lastFullMonth, monthlyReportText, recentPeriods } from "../services/monthlyReport.js"; import { recordAudit } from "../services/audit.js"; import { notifyNow } from "../services/notify.js"; import { getSettings } from "../services/settingsStore.js"; import { asyncHandler } from "../utils/asyncHandler.js"; export const reportsRouter = Router(); reportsRouter.use(requireAuth); /** The month, quarter or year asked for, or the last whole month; null when what was asked is not one that can be had. */ async function monthFrom(query: unknown): Promise<({ id: string } & ReturnType) | null> { const tz = (await getSettings()).notifications.timezone || "UTC"; const options = recentPeriods(new Date(), tz); if (query === undefined || query === "") return { id: lastFullMonth(new Date(), tz), ...options }; const all = [...options.months, ...options.quarters, ...options.years]; if (!isPeriodId(query) || !all.some((m) => m.id === query)) return null; return { id: query, ...options }; } // How a month, a quarter or a year went, for everyone signed in: it is only what the pages it comes from already show them. ?month=2026-09 (or ?month=2026-Q3, // ?month=2026), the last whole month by default; ?format=text is the plain-text version a notification carries. reportsRouter.get("/monthly", asyncHandler(async (req, res) => { const picked = await monthFrom(req.query.month ?? req.query.period); if (!picked) return res.status(400).json({ error: "invalid_month", message: "Ask for one of the last twelve months (2026-09), the last eight quarters (2026-Q3) or the last three years (2026)." }); const report = await buildMonthlyReport(picked.id); if (req.query.format === "text") return res.json(monthlyReportText(report)); res.json({ report, months: picked.months, quarters: picked.quarters, years: picked.years }); })); // Send it now to the notification channels, as if it were the day. Administrators. reportsRouter.post("/monthly/send", requireRole("admin"), asyncHandler(async (req, res) => { const picked = await monthFrom((req.body as { month?: unknown } | undefined)?.month); if (!picked) return res.status(400).json({ error: "invalid_month", message: "Ask for one of the last twelve months (2026-09), the last eight quarters (2026-Q3) or the last three years (2026)." }); const { title, message } = monthlyReportText(await buildMonthlyReport(picked.id)); await notifyNow(title, message); await recordAudit({ actor: req.currentUser!, category: "report", action: "send_monthly", targetType: "report", detail: { month: picked.id } }); res.json({ sent: true }); }));