import { Router } from "express"; import { eq } from "drizzle-orm"; import { z } from "zod"; import { db } from "../db/client.js"; import { costItems } from "../db/schema.js"; import { requireAuth, requireRole } from "../auth/middleware.js"; import { recordAudit } from "../services/audit.js"; import { automaticCosts, costTotals, DEFAULT_CATEGORIES, isYmd, listCostItems, monthlyOf, nextRenewal, PERIODS, type CostRow } from "../services/costs.js"; import { localDate } from "../services/agenda.js"; import { getSettings } from "../services/settingsStore.js"; import { asyncHandler } from "../utils/asyncHandler.js"; export const costsRouter = Router(); costsRouter.use(requireAuth); const ymd = z .string() .regex(/^\d{4}-\d{2}-\d{2}$/) .refine((v) => isYmd(v), "not a date"); const body = z.object({ name: z.string().trim().min(1).max(100), amount: z.number().positive().max(10_000_000), currency: z.string().trim().regex(/^[A-Za-z]{3}$/).transform((c) => c.toUpperCase()), period: z.enum(PERIODS), category: z.string().trim().min(1).max(40).default("Other"), renewsOn: ymd.nullable().optional(), note: z.string().trim().max(300).nullable().optional(), }); const shape = (r: CostRow, today: string) => ({ id: r.id, name: r.name, amount: r.amount, currency: r.currency, period: r.period, category: r.category, renewsOn: r.renewsOn, /** The next day it is billed, worked out from the day given. */ nextRenewal: nextRenewal(r.renewsOn, r.period, today), monthly: Math.round(monthlyOf(r.amount, r.period) * 100) / 100, note: r.note, }); /** What it costs: the items typed in, the estimates that can be read, and the totals per currency. Everyone signed in can see it. */ costsRouter.get("/", asyncHandler(async (_req, res) => { const [items, automatic, settings] = await Promise.all([listCostItems(), automaticCosts(), getSettings()]); const today = localDate(new Date(), settings.notifications.timezone || "UTC"); res.json({ items: items.map((r) => shape(r, today)), automatic, totals: costTotals(items, automatic), categories: [...new Set([...DEFAULT_CATEGORIES, ...items.map((i) => i.category)])], }); })); costsRouter.post("/", requireRole("admin"), asyncHandler(async (req, res) => { const parsed = body.safeParse(req.body); if (!parsed.success) return res.status(400).json({ error: "invalid_body", message: "Give it a name, an amount above zero, a three-letter currency (EUR, SEK …) and say whether it is per month or per year." }); const now = new Date().toISOString(); const [created] = await db.insert(costItems).values({ ...parsed.data, renewsOn: parsed.data.renewsOn ?? null, note: parsed.data.note ?? null, createdAt: now, updatedAt: now }).returning(); await recordAudit({ actor: req.currentUser!, category: "cost", action: "create", targetType: "cost", targetId: created.id, detail: { name: created.name, amount: created.amount, currency: created.currency, period: created.period } }); res.status(201).json({ id: created.id }); })); costsRouter.put("/:id", requireRole("admin"), asyncHandler(async (req, res) => { const id = Number(req.params.id); if (!Number.isInteger(id)) return res.status(400).json({ error: "invalid_id" }); const parsed = body.safeParse(req.body); if (!parsed.success) return res.status(400).json({ error: "invalid_body", message: "Give it a name, an amount above zero, a three-letter currency (EUR, SEK …) and say whether it is per month or per year." }); const [updated] = await db.update(costItems).set({ ...parsed.data, renewsOn: parsed.data.renewsOn ?? null, note: parsed.data.note ?? null, updatedAt: new Date().toISOString() }).where(eq(costItems.id, id)).returning(); if (!updated) return res.status(404).json({ error: "not_found" }); await recordAudit({ actor: req.currentUser!, category: "cost", action: "update", targetType: "cost", targetId: id, detail: { name: updated.name, amount: updated.amount, currency: updated.currency, period: updated.period } }); res.json({ id }); })); costsRouter.delete("/:id", requireRole("admin"), asyncHandler(async (req, res) => { const id = Number(req.params.id); if (!Number.isInteger(id)) return res.status(400).json({ error: "invalid_id" }); const [removed] = await db.delete(costItems).where(eq(costItems.id, id)).returning(); if (!removed) return res.status(404).json({ error: "not_found" }); await recordAudit({ actor: req.currentUser!, category: "cost", action: "delete", targetType: "cost", targetId: id, detail: { name: removed.name } }); res.status(204).end(); }));