mirror of
https://origin.cursor.com/mrdevmx/panels.git
synced 2026-10-09 19:03:17 +00:00
Fase 2 (driver): - api/pg.ts: adaptador delgado sobre postgres.js (prepare/get/all/run, placeholders ? -> $n, withTenant con set_config para RLS), con parsers de tipo custom (numeric/date/timestamp(tz)/bigint) para que el resto del codigo heredado de SQLite (fechas/montos como string, ids como number) siga funcionando sin reescribir cada call-site a mano. - api/platform_db.ts, api/iam_db.ts (nuevo), api/db.ts: pools separados por base/esquema (panels_platform, panels_product.iam, panels_product.core), owner pool para bootstrap/scripts/lookups administrativos que cruzan tenant a proposito. - api/redis.ts: clientes iam/core separados (ACL panels_iam_redis / panels_core_redis). - api/sessions.ts + auth.ts: sesiones ahora en Redis (cookie = id opaco, no HMAC autocontenido); revocacion real (logout, cambio de password). - api/storage.ts (Fase 4c): documentos/PDFs via Contabo Object Storage (S3), con fallback a disco local si no hay credenciales S3 (dev). - api/scope.ts: middleware withCoreScope/requireCoreAuth que abre la transaccion con app.tenant_id fijado (RLS) para cada request. - api/cache.ts (Fase 4e): cache Redis con tenant_id obligatorio en la llave; aplicado a /v1/catalogs. Fase 3 (reescritura SQL, ~80 endpoints en main.ts/companies.ts/budget.ts/ payroll.ts/payroll_http.ts/excel.ts/saas.ts/smtp.ts): - Todo async/await, sintaxis Postgres (COALESCE, ~ regex, ON CONFLICT, now()/current_date, booleanos reales, RETURNING via lastInsertId()). - IDOR cross-tenant cerrado: GET/PATCH /v1/projects/:id, /v1/workers/:id ya no dependen de que el handler recuerde el WHERE tenant_id -- Row Level Security lo hace estructuralmente (verificado con un segundo tenant real: 404 en vez de fuga de datos). - API key ya no ve todos los tenants: ahora exige X-Tenant-Id explicito. Fase 3b (tests): api/test_helpers.ts corre cada test en una transaccion que siempre se revierte, contra el mismo baseline de Liquibase que produccion (ya no un esquema SQLite escrito a mano). payroll_test.ts reescrito con fixtures reales; 11/11 pasan contra Postgres. Fase 4 (IAM/RBAC): iam.roles/permissions/role_permissions formalizados (ver db/iam ya en fase 1); uploaded_by/created_by ahora son snapshot desnormalizado (uploaded_by_id/name); seed() en runtime eliminado, reemplazado por scripts/bootstrap-admin.ts (one-shot). Fase 4d (zona horaria): nuevo endpoint /v1/configuracion (GET/PUT), PAYROLL_TZ hardcodeado reemplazado por tenant_settings.timezone, document_validity.ts ya no usa new Date() crudo. Verificado end-to-end contra Postgres+Redis reales: login, sesiones, catalogos con cache, alta de trabajador, subida/descarga de documento cifrado, y el fix de IDOR probado con un segundo tenant real (403/404 en vez de fuga de datos). Co-authored-by: alberto.martinez <alberto.martinez@mrdev.mx>
459 lines
17 KiB
TypeScript
459 lines
17 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 { lastInsertId, projectById, projectMustBe, type Db } from "./db.ts";
|
|
import { generateLoanReceiptPdf } from "./pdf.ts";
|
|
import { fullName } from "./mx.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 rows = await db.prepare(
|
|
`SELECT a.*, w.first_name, w.last_name_p FROM attendance a
|
|
JOIN workers w ON w.id=a.worker_id
|
|
WHERE a.project_id=? AND a.work_date BETWEEN ? AND ?
|
|
ORDER BY a.work_date, w.last_name_p`,
|
|
).all(projectId, from, to);
|
|
return c.json({ attendance: rows });
|
|
});
|
|
|
|
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 c.json({ error: blocked.error }, blocked.status);
|
|
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 sql = workerId
|
|
? "SELECT l.*, w.first_name, w.last_name_p FROM loans l JOIN workers w ON w.id=l.worker_id WHERE l.worker_id=? ORDER BY l.id DESC"
|
|
: "SELECT l.*, w.first_name, w.last_name_p FROM loans l JOIN workers w ON w.id=l.worker_id ORDER BY l.id DESC";
|
|
const loans = workerId ? await db.prepare(sql).all(Number(workerId)) : await db.prepare(sql).all();
|
|
return c.json({ loans });
|
|
});
|
|
|
|
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 loan = await db.prepare(
|
|
`SELECT l.*, w.first_name, w.middle_name, w.last_name_p, w.last_name_m
|
|
FROM loans l JOIN workers w ON w.id=l.worker_id WHERE l.id=?`,
|
|
).get(id) as {
|
|
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;
|
|
} | undefined;
|
|
if (!loan) return c.json({ error: "Préstamo no encontrado" }, 404);
|
|
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 pay = await db.prepare(
|
|
`SELECT p.*, l.delivered, l.commission_pct, w.first_name, w.middle_name, w.last_name_p, w.last_name_m, wk.week_end
|
|
FROM loan_payments p
|
|
JOIN loans l ON l.id=p.loan_id
|
|
JOIN workers w ON w.id=l.worker_id
|
|
JOIN payroll_weeks wk ON wk.id=p.week_id
|
|
WHERE p.id=?`,
|
|
).get(id) as {
|
|
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;
|
|
} | undefined;
|
|
if (!pay) return c.json({ error: "Recibo no encontrado" }, 404);
|
|
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 c.json({ error: blocked.error }, blocked.status);
|
|
await db.prepare(
|
|
"INSERT INTO payroll_periods (project_id, week_start, week_end, status) VALUES (?, ?, ?, 'draft')",
|
|
).run(body.project_id, body.week_start, body.week_end);
|
|
const periodId = await lastInsertId(db);
|
|
const workers = await db.prepare(
|
|
`SELECT w.id, w.daily_wage FROM workers w
|
|
JOIN assignments a ON a.worker_id=w.id AND a.project_id=? AND a.active=true
|
|
WHERE w.status='activo'`,
|
|
).all(body.project_id) as { id: number; daily_wage: number }[];
|
|
const ins = db.prepare(
|
|
`INSERT INTO payroll_lines (period_id, worker_id, days, daily_wage, gross, discounts, loan_payment, net)
|
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
|
|
);
|
|
for (const w of workers) {
|
|
const att = await db.prepare(
|
|
`SELECT COUNT(*) AS n FROM attendance
|
|
WHERE worker_id=? AND project_id=? AND work_date BETWEEN ? AND ? AND present=true`,
|
|
).get(w.id, body.project_id, body.week_start, body.week_end) as { n: number };
|
|
const days = Number(att.n);
|
|
const gross = days * w.daily_wage;
|
|
const extra = Number(body.extra_discounts?.[w.id] ?? 0);
|
|
const net = gross - extra;
|
|
await ins.run(periodId, w.id, days, w.daily_wage, gross, extra, 0, net);
|
|
}
|
|
return c.json({ id: periodId });
|
|
});
|
|
|
|
app.get("/v1/payroll/periods", ...requireCoreAuth, async (c) => {
|
|
const db = c.get("db");
|
|
const projectId = c.req.query("project_id");
|
|
const sql = projectId
|
|
? `SELECT pe.*, p.name AS project_name FROM payroll_periods pe JOIN projects p ON p.id=pe.project_id WHERE pe.project_id=? ORDER BY pe.id DESC`
|
|
: `SELECT pe.*, p.name AS project_name FROM payroll_periods pe JOIN projects p ON p.id=pe.project_id ORDER BY pe.id DESC`;
|
|
const periods = projectId ? await db.prepare(sql).all(Number(projectId)) : await db.prepare(sql).all();
|
|
return c.json({ periods });
|
|
});
|
|
|
|
app.get("/v1/payroll/periods/:id", ...requireCoreAuth, async (c) => {
|
|
const id = Number(c.req.param("id"));
|
|
const db = c.get("db");
|
|
const period = await db.prepare(
|
|
`SELECT pe.*, p.name AS project_name FROM payroll_periods pe JOIN projects p ON p.id=pe.project_id WHERE pe.id=?`,
|
|
).get(id);
|
|
if (!period) return c.json({ error: "Periodo no encontrado" }, 404);
|
|
const lines = await db.prepare(
|
|
`SELECT l.*, w.first_name, w.last_name_p, w.position FROM payroll_lines l
|
|
JOIN workers w ON w.id=l.worker_id WHERE l.period_id=? ORDER BY w.last_name_p`,
|
|
).all(id);
|
|
return c.json({ period, lines });
|
|
});
|
|
|
|
app.get("/v1/payroll/periods/:id/csv", ...requireCoreAuth, async (c) => {
|
|
const id = Number(c.req.param("id"));
|
|
const db = c.get("db");
|
|
const lines = await db.prepare(
|
|
`SELECT w.first_name, w.last_name_p, l.days, l.daily_wage, l.gross, l.discounts, l.loan_payment, l.net
|
|
FROM payroll_lines l JOIN workers w ON w.id=l.worker_id WHERE l.period_id=?`,
|
|
).all(id) as Record<string, unknown>[];
|
|
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");
|
|
await db.prepare("UPDATE payroll_periods SET status=? WHERE id=?").run(status, id);
|
|
return c.json({ ok: true });
|
|
});
|
|
}
|