import type { Hono } from "hono"; import type { AuthUser } from "./auth.ts"; import { tenantScope } from "./auth.ts"; import { requireCoreAuth } from "./scope.ts"; import { requireAnyPermission } from "./permissions.ts"; import { callCoreFn } from "./rpc.ts"; import { respondRpc, routeLabel } from "./http_errors.ts"; type App = Hono<{ Variables: { user: AuthUser; db: Db } }>; type Db = import("./db.ts").Db; function tid(c: { get: (k: "user") => AuthUser }): number { return tenantScope(c.get("user")) ?? 0; } export function registerExpenseCatalogRoutes(app: App) { const view = [...requireCoreAuth, requireAnyPermission("expenses.view", "settings.view", "warehouse.view")] as const; const write = [...requireCoreAuth, requireAnyPermission("expenses.create", "settings.update", "warehouse.update")] as const; app.get("/v1/suppliers", ...view, async (c) => { const db = c.get("db"); const env = await callCoreFn(db, "core.fn_supplier_list", { tenant_id: tid(c), status: c.req.query("status"), }, { route: routeLabel(c) }); return respondRpc(c, env); }); app.post("/v1/suppliers", ...write, async (c) => { const body = await c.req.json>(); const db = c.get("db"); const env = await callCoreFn(db, "core.fn_supplier_create", { ...body, tenant_id: tid(c), }, { route: routeLabel(c) }); return respondRpc(c, env); }); app.patch("/v1/suppliers/:id", ...write, async (c) => { const body = await c.req.json>(); const db = c.get("db"); const env = await callCoreFn(db, "core.fn_supplier_update", { ...body, id: Number(c.req.param("id")), tenant_id: tid(c), }, { route: routeLabel(c) }); return respondRpc(c, env); }); app.get("/v1/measure-units", ...view, async (c) => { const db = c.get("db"); const env = await callCoreFn(db, "core.fn_measure_unit_list", { tenant_id: tid(c), }, { route: routeLabel(c) }); return respondRpc(c, env); }); app.post("/v1/measure-units", ...write, async (c) => { const body = await c.req.json>(); const db = c.get("db"); const env = await callCoreFn(db, "core.fn_measure_unit_add", { ...body, tenant_id: tid(c), }, { route: routeLabel(c) }); return respondRpc(c, env); }); }