mirror of
https://origin.cursor.com/mrdevmx/panels.git
synced 2026-10-09 15:33:17 +00:00
- Replace db.prepare() in payroll_http with callCoreFn for attendance, loans, loan receipts, and legacy payroll period routes - Use respondRpc/respondApiError for standardized HTTP responses - Add fn_loan_list/get, fn_loan_payment_get, and fn_payroll_period_* RPCs to 013-rpc-payroll.sql with grants - Refactor excel storeDocument to fn_worker_document_store (S3 stays in TS) - Refactor importExcel and upsertWorker to fn_workers_import_batch Co-authored-by: alberto.martinez <alberto.martinez@mrdev.mx>
475 lines
15 KiB
TypeScript
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);
|
|
});
|
|
}
|