panels-origin/api/payroll_http.ts
Alberto Martinez b9bf7044b2 refactor(core): migrate core CRUD to PostgreSQL RPC + unified HTTP errors
<!-- CURSOR_AGENT_PR_BODY_BEGIN -->
## Summary

Migrates the `core` schema business logic from inline `db.prepare()` calls in the API to PostgreSQL RPC functions (`core.fn_*`) with a unified JSON envelope for errors and HTTP status mapping.

### Database (Liquibase changesets 006–017)

- **006** — RPC infra: `rpc_ok`, `rpc_err`, `rpc_created`, `rpc_from_exception`
- **007** — Catalogs and tenant settings
- **008** — Companies CRUD
- **009** — Projects, checklists, document lists
- **010** — Workers CRUD, pipeline, checklist, assign
- **011** — Budget CRUD + `fn_budget_replace`
- **012** — Badge jobs
- **013** — Payroll (settings, attendance, loans, weeks, destajo)
- **014** — Worker import batch + document store
- **015** — Project/company/worker document metadata RPCs
- **016–017** — Fixes: `needs_badge` default on worker create; Liquibase `splitStatements:false` on function changesets

### API

- `api/rpc.ts` — `callCoreFn()`, `RpcCallError` (jsonb payload fix: pass JS object, not `JSON.stringify`)
- `api/http_errors.ts` — `mapRpcToStatus()`, `respondRpc()`, `respondApiError()`, `onAppError()`
- Refactored: `main.ts`, `companies.ts`, `db.ts`, `budget.ts`, `excel.ts`, `payroll.ts`, `payroll_http.ts`
- Front helpers: `web-panel/composables/api-response.ts`, `web-saas/composables/api-response.ts`

### Envelope contract

DB functions return `{ ok, code, layer: "db", message, context, data, errors }`. The API adds `status` (HTTP code) via `respondRpc()` / `respondApiError()`.

### Out of scope

`iam`, `platform`, `saas.ts`, auth/sessions, S3, PDF generation, Excel parsing, and bootstrap scripts still use direct SQL where appropriate.

## Test plan

- [x] `deno check main.ts` — compila sin errores de tipos
- [x] `npm run build` — web-panel y web-saas compilan
- [x] `deno test` — 25 tests unitarios (http_errors, companies, budget, mx, document_validity)
- [x] Liquibase migrations `006`–`017` aplicadas en Postgres local (`--context-filter=dev`)
- [x] API levantada localmente; `/v1/health` OK
- [x] Smoke CRUD vía `scripts/crud-smoke-test.sh`: empresas, proyectos, trabajadores, catálogos (create/get/list/patch)
- [ ] Import Excel de trabajadores (flujo multipart + S3/local storage)
- [ ] Import presupuesto desde Excel
- [ ] Flujo nómina: asistencia → cerrar semana
- [ ] CI en el remoto (sin checks reportados aún)
<!-- CURSOR_AGENT_PR_BODY_END -->

<div><a href="https://cursor.com/agents/bc-06667c14-38e8-42a8-9ed9-6b1322f12ae7?cursor_ref=pr_footer&cursor_cta=open_in_web"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/open-in-web-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/open-in-web-light.png"><img alt="Open in Web" width="114" height="28" src="https://cursor.com/assets/images/open-in-web-dark.png"></picture></a>&nbsp;<a href="https://cursor.com/background-agent?bcId=bc-06667c14-38e8-42a8-9ed9-6b1322f12ae7&cursor_ref=pr_footer&cursor_cta=open_in_cursor"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/open-in-cursor-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/open-in-cursor-light.png"><img alt="Open in Cursor" width="131" height="28" src="https://cursor.com/assets/images/open-in-cursor-dark.png"></picture></a>&nbsp;</div>
2026-09-04 02:34:43 +00:00

475 lines
15 KiB
TypeScript

import type { Context, Hono } from "hono";
import type { AuthUser } from "./auth.ts";
import { tenantScope } from "./auth.ts";
import { requireCoreAuth } from "./scope.ts";
import { projectById, projectMustBe, type Db } from "./db.ts";
import { generateLoanReceiptPdf } from "./pdf.ts";
import { fullName } from "./mx.ts";
import { callCoreFn } from "./rpc.ts";
import { respondApiError, respondRpc, routeLabel } from "./http_errors.ts";
import {
addAdminLine,
addJornalWorker,
addUnit,
assembleWeek,
createDestajoJob,
createLoan,
getSettings,
getWeekBundle,
listOpenWeeks,
listUnits,
moneyLabel,
payWeek,
patchDestajoCut,
removeAdminLine,
resolveToday,
saveSettings,
setAttendance,
tenantKey,
updateAdminLine,
weekContaining,
weekCsv,
} from "./payroll.ts";
type App = Hono<{ Variables: { user: AuthUser; db: Db } }>;
function tid(c: { get: (k: "user") => AuthUser }): number {
return tenantKey(tenantScope(c.get("user")));
}
function pdfBody(c: Context, bytes: Uint8Array, filename: string) {
c.header("Content-Type", "application/pdf");
c.header("Content-Disposition", `attachment; filename="${filename}"`);
return c.body(bytes.buffer as ArrayBuffer);
}
export function registerPayrollRoutes(app: App) {
app.get("/v1/attendance", ...requireCoreAuth, async (c) => {
const projectId = Number(c.req.query("project_id"));
const from = c.req.query("from") ?? "";
const to = c.req.query("to") ?? "";
const db = c.get("db");
const env = await callCoreFn<{ attendance: unknown[] }>(
db,
"core.fn_attendance_list",
{ project_id: projectId, from, to },
{ route: routeLabel(c) },
);
return respondRpc(c, env);
});
app.put("/v1/attendance", ...requireCoreAuth, async (c) => {
const body = await c.req.json<{
project_id: number;
worker_id: number;
work_date: string;
present: boolean;
}>();
const db = c.get("db");
const blocked = projectMustBe(
await projectById(db, body.project_id),
["activo", "pausado"],
"No se registra asistencia en un proyecto concluido o cancelado",
);
if (blocked) {
return respondApiError(
c,
blocked.status === 404 ? "NOT_FOUND" : "VALIDATION",
blocked.error,
{ route: routeLabel(c), project_id: body.project_id },
);
}
const result = await setAttendance(db, tid(c), body);
if ("error" in result) {
return c.json({ error: result.error, other: result.other }, result.status === 409 ? 409 : 400);
}
return c.json({ ok: true });
});
app.get("/v1/payroll/settings", ...requireCoreAuth, async (c) => {
const db = c.get("db");
const tenantId = tid(c);
return c.json({ settings: await getSettings(db, tenantId), units: await listUnits(db, tenantId) });
});
app.patch("/v1/payroll/settings", ...requireCoreAuth, async (c) => {
const db = c.get("db");
const body = await c.req.json<{
loan_commission_enabled?: number | boolean;
loan_commission_pct?: number;
loan_small_max?: number;
}>();
const settings = await saveSettings(db, tid(c), {
loan_commission_enabled: body.loan_commission_enabled === undefined
? undefined
: Boolean(body.loan_commission_enabled),
loan_commission_pct: body.loan_commission_pct,
loan_small_max: body.loan_small_max,
});
return c.json({ settings });
});
app.post("/v1/destajo/units", ...requireCoreAuth, async (c) => {
const body = await c.req.json<{ code: string; label?: string }>();
const db = c.get("db");
try {
const id = await addUnit(db, tid(c), body.code, body.label ?? body.code);
return c.json({ id }, 201);
} catch (e) {
return c.json({ error: e instanceof Error ? e.message : "No se pudo guardar" }, 400);
}
});
app.get("/v1/loans", ...requireCoreAuth, async (c) => {
const db = c.get("db");
const workerId = c.req.query("worker_id");
const env = await callCoreFn<{ loans: unknown[] }>(
db,
"core.fn_loan_list",
workerId ? { worker_id: Number(workerId) } : {},
{ route: routeLabel(c) },
);
return respondRpc(c, env);
});
app.post("/v1/loans", ...requireCoreAuth, async (c) => {
const body = await c.req.json<{
worker_id: number;
amount?: number;
delivered?: number;
weekly_payment?: number;
note?: string;
commission_enabled?: boolean;
commission_pct?: number;
plan?: "single" | "installments";
installments_n?: number;
}>();
const db = c.get("db");
try {
const created = await createLoan(db, tid(c), {
worker_id: body.worker_id,
delivered: Number(body.delivered ?? body.amount ?? 0),
commission_enabled: body.commission_enabled,
commission_pct: body.commission_pct,
plan: body.plan,
installments_n: body.installments_n,
note: body.note,
});
return c.json(created, 201);
} catch (e) {
const err = e as Error & { status?: number };
return c.json({ error: err.message }, err.status === 404 ? 404 : 400);
}
});
app.get("/v1/loans/:id/recibo", ...requireCoreAuth, async (c) => {
const id = Number(c.req.param("id"));
const db = c.get("db");
const env = await callCoreFn<{ loan: {
delivered: number;
commission_pct: number;
commission_amount: number;
balance: number;
weekly_payment: number;
plan: string;
installments_n: number;
first_due: string;
created_at: string;
first_name: string;
middle_name: string | null;
last_name_p: string;
last_name_m: string;
note: string | null;
} }>(
db,
"core.fn_loan_get",
{ id },
{ route: routeLabel(c) },
);
if (!env.ok) return respondRpc(c, env);
const loan = env.data!.loan;
const bytes = await generateLoanReceiptPdf({
title: "Recibo de aceptación de préstamo",
subtitle: `Registrado ${String(loan.created_at).slice(0, 10)}`,
person: fullName(loan),
lines: [
{ label: "Entregado", value: moneyLabel(loan.delivered) },
{
label: "Comisión",
value: loan.commission_pct > 0
? `${loan.commission_pct}% · ${moneyLabel(loan.commission_amount)}`
: "Sin comisión",
},
{ label: "Saldo a descontar", value: moneyLabel(loan.delivered + loan.commission_amount) },
{
label: "Plan",
value: loan.plan === "installments" ? `${loan.installments_n} cuotas` : "1 exhibición",
},
{ label: "Primer descuento", value: loan.first_due || "—" },
{ label: "Abono", value: moneyLabel(loan.weekly_payment) },
{ label: "Nota", value: loan.note || "—" },
],
});
return pdfBody(c, bytes, `prestamo-aceptacion-${id}.pdf`);
});
app.get("/v1/loan-payments/:id/recibo", ...requireCoreAuth, async (c) => {
const id = Number(c.req.param("id"));
const db = c.get("db");
const env = await callCoreFn<{ payment: {
amount: number;
installment_n: number;
label: string;
delivered: number;
commission_pct: number;
first_name: string;
middle_name: string | null;
last_name_p: string;
last_name_m: string;
week_end: string;
} }>(
db,
"core.fn_loan_payment_get",
{ id },
{ route: routeLabel(c) },
);
if (!env.ok) return respondRpc(c, env);
const pay = env.data!.payment;
const bytes = await generateLoanReceiptPdf({
title: "Recibo de pago de préstamo",
subtitle: `Descuento del sábado ${pay.week_end}`,
person: fullName(pay),
lines: [
{ label: "Descuento", value: moneyLabel(pay.amount) },
{ label: "Exhibición", value: String(pay.installment_n) },
{ label: "Condiciones", value: pay.label || "—" },
],
});
return pdfBody(c, bytes, `prestamo-pago-${id}.pdf`);
});
app.get("/v1/payroll/weeks", ...requireCoreAuth, async (c) => {
const db = c.get("db");
const tenantId = tid(c);
const start = c.req.query("week_start") || weekContaining(await resolveToday(db, tenantId)).weekStart;
const bundle = await getWeekBundle(db, tenantId, start);
return c.json(bundle);
});
app.get("/v1/payroll/weeks/open", ...requireCoreAuth, async (c) => {
const db = c.get("db");
return c.json({ weeks: await listOpenWeeks(db, tid(c)) });
});
app.post("/v1/payroll/weeks/:id/assemble", ...requireCoreAuth, async (c) => {
const db = c.get("db");
try {
const nowIso = await resolveToday(db, tid(c));
await assembleWeek(db, Number(c.req.param("id")), nowIso);
return c.json({ ok: true });
} catch (e) {
const err = e as Error & { status?: number };
return c.json({ error: err.message }, err.status === 404 ? 404 : 400);
}
});
app.post("/v1/payroll/weeks/:id/pay", ...requireCoreAuth, async (c) => {
const db = c.get("db");
try {
const nowIso = await resolveToday(db, tid(c));
await payWeek(db, Number(c.req.param("id")), nowIso);
return c.json({ ok: true });
} catch (e) {
const err = e as Error & { status?: number };
return c.json({ error: err.message }, err.status === 404 ? 404 : 400);
}
});
app.get("/v1/payroll/weeks/:id/csv", ...requireCoreAuth, async (c) => {
const id = Number(c.req.param("id"));
const db = c.get("db");
const csv = await weekCsv(db, id);
c.header("Content-Type", "text/csv; charset=utf-8");
c.header("Content-Disposition", `attachment; filename="nomina-${id}.csv"`);
return c.body(csv);
});
app.post("/v1/payroll/weeks/:id/jornal", ...requireCoreAuth, async (c) => {
const body = await c.req.json<{ project_id: number; worker_id: number }>();
const db = c.get("db");
try {
await addJornalWorker(db, Number(c.req.param("id")), body.project_id, body.worker_id);
return c.json({ ok: true });
} catch (e) {
const err = e as Error & { status?: number };
return c.json({ error: err.message }, err.status === 404 ? 404 : 400);
}
});
app.post("/v1/payroll/weeks/:id/admin", ...requireCoreAuth, async (c) => {
const body = await c.req.json<{ worker_id: number; amount: number; project_id?: number | null }>();
const db = c.get("db");
try {
await addAdminLine(db, Number(c.req.param("id")), body);
return c.json({ ok: true });
} catch (e) {
const err = e as Error & { status?: number };
return c.json({ error: err.message }, err.status === 404 ? 404 : 400);
}
});
app.patch("/v1/payroll/weeks/:id/admin/:lineId", ...requireCoreAuth, async (c) => {
const body = await c.req.json<{ amount: number }>();
const db = c.get("db");
try {
await updateAdminLine(db, Number(c.req.param("id")), Number(c.req.param("lineId")), body.amount);
return c.json({ ok: true });
} catch (e) {
const err = e as Error & { status?: number };
return c.json({ error: err.message }, err.status === 404 ? 404 : 400);
}
});
app.delete("/v1/payroll/weeks/:id/admin/:lineId", ...requireCoreAuth, async (c) => {
const db = c.get("db");
try {
await removeAdminLine(db, Number(c.req.param("id")), Number(c.req.param("lineId")));
return c.json({ ok: true });
} catch (e) {
const err = e as Error & { status?: number };
return c.json({ error: err.message }, err.status === 404 ? 404 : 400);
}
});
app.post("/v1/destajo/jobs", ...requireCoreAuth, async (c) => {
const body = await c.req.json<{
week_id: number;
project_id: number;
worker_id: number;
concepto: string;
unit_code: string;
qty_total_estimated: number;
unit_price: number;
qty_planned?: number;
qty_extra?: number;
}>();
const db = c.get("db");
try {
const created = await createDestajoJob(db, tid(c), body.week_id, body);
return c.json(created, 201);
} catch (e) {
const err = e as Error & { status?: number };
return c.json({ error: err.message }, err.status === 404 ? 404 : 400);
}
});
app.patch("/v1/destajo/cuts/:id", ...requireCoreAuth, async (c) => {
const body = await c.req.json<{
week_id: number;
qty_planned?: number;
qty_actual?: number;
qty_extra?: number;
}>();
const db = c.get("db");
try {
await patchDestajoCut(db, body.week_id, Number(c.req.param("id")), body);
return c.json({ ok: true });
} catch (e) {
const err = e as Error & { status?: number };
return c.json({ error: err.message }, err.status === 404 ? 404 : 400);
}
});
app.post("/v1/payroll/periods", ...requireCoreAuth, async (c) => {
const body = await c.req.json<{
project_id: number;
week_start: string;
week_end: string;
extra_discounts?: Record<number, number>;
}>();
const db = c.get("db");
const blocked = projectMustBe(
await projectById(db, body.project_id),
["activo", "pausado"],
"No se genera nómina de un proyecto concluido o cancelado",
);
if (blocked) {
return respondApiError(
c,
blocked.status === 404 ? "NOT_FOUND" : "VALIDATION",
blocked.error,
{ route: routeLabel(c), project_id: body.project_id },
);
}
const env = await callCoreFn<{ id: number }>(
db,
"core.fn_payroll_period_create",
{
project_id: body.project_id,
week_start: body.week_start,
week_end: body.week_end,
extra_discounts: body.extra_discounts ?? {},
},
{ route: routeLabel(c) },
);
return respondRpc(c, env);
});
app.get("/v1/payroll/periods", ...requireCoreAuth, async (c) => {
const db = c.get("db");
const projectId = c.req.query("project_id");
const env = await callCoreFn<{ periods: unknown[] }>(
db,
"core.fn_payroll_period_list",
projectId ? { project_id: Number(projectId) } : {},
{ route: routeLabel(c) },
);
return respondRpc(c, env);
});
app.get("/v1/payroll/periods/:id", ...requireCoreAuth, async (c) => {
const id = Number(c.req.param("id"));
const db = c.get("db");
const env = await callCoreFn<{ period: unknown; lines: unknown[] }>(
db,
"core.fn_payroll_period_get",
{ id },
{ route: routeLabel(c) },
);
return respondRpc(c, env);
});
app.get("/v1/payroll/periods/:id/csv", ...requireCoreAuth, async (c) => {
const id = Number(c.req.param("id"));
const db = c.get("db");
const env = await callCoreFn<{ period: unknown; lines: Array<Record<string, unknown>> }>(
db,
"core.fn_payroll_period_get",
{ id },
{ route: routeLabel(c) },
);
if (!env.ok) return respondRpc(c, env);
const lines = env.data?.lines ?? [];
const header = "Nombre,Apellido,Dias,Jornal,Bruto,Descuentos,Prestamo,Neto";
const rows = lines.map((l) =>
[l.first_name, l.last_name_p, l.days, l.daily_wage, l.gross, l.discounts, l.loan_payment, l.net].join(",")
);
const csv = [header, ...rows].join("\n");
c.header("Content-Type", "text/csv; charset=utf-8");
c.header("Content-Disposition", `attachment; filename="nomina-${id}.csv"`);
return c.body(csv);
});
app.patch("/v1/payroll/periods/:id", ...requireCoreAuth, async (c) => {
const id = Number(c.req.param("id"));
const { status } = await c.req.json<{ status: string }>();
const db = c.get("db");
const env = await callCoreFn(
db,
"core.fn_payroll_period_patch",
{ id, status },
{ route: routeLabel(c) },
);
return respondRpc(c, env);
});
}