mirror of
https://origin.cursor.com/mrdevmx/panels.git
synced 2026-10-09 18:03:18 +00:00
Reutiliza el catálogo de proveedores y agrega carga de facturas, conceptos de la semana, préstamos editables, finiquitos, dispersión, historial de personal, reportes y jornal de cotización. Co-authored-by: alberto.martinez <alberto.martinez@mrdev.mx>
699 lines
27 KiB
TypeScript
699 lines
27 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 { requirePermission } from "./permissions.ts";
|
|
import { denyUnlessProjectScope } from "./scope_enforcement.ts";
|
|
import { projectById, projectMustBe, type Db } from "./db.ts";
|
|
import { generateLoanReceiptPdf } from "./pdf.ts";
|
|
import { PDFDocument, StandardFonts } from "pdf-lib";
|
|
import * as XLSX from "xlsx";
|
|
import { randomBytes } from "node:crypto";
|
|
import { encryptBytes } from "./docs_crypto.ts";
|
|
import { dispersionDocKey, putObject } from "./storage.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, requirePermission("payroll.view"), 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, requirePermission("payroll.update"), 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, requirePermission("payroll.view"), 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, requirePermission("payroll.update"), 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, requirePermission("payroll.create"), 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, requirePermission("payroll.view"), 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, requirePermission("payroll.create"), 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, requirePermission("payroll.view"), 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, requirePermission("payroll.view"), 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, requirePermission("payroll.view"), 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, requirePermission("payroll.view"), async (c) => {
|
|
const db = c.get("db");
|
|
return c.json({ weeks: await listOpenWeeks(db, tid(c)) });
|
|
});
|
|
|
|
app.post("/v1/payroll/weeks/:id/assemble", ...requireCoreAuth, requirePermission("payroll.update"), 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, requirePermission("payroll.update"), 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, requirePermission("payroll.view"), 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, requirePermission("payroll.update"), 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, requirePermission("payroll.update"), 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, requirePermission("payroll.update"), 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, requirePermission("payroll.delete"), 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, requirePermission("payroll.create"), 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, requirePermission("payroll.update"), 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, requirePermission("payroll.create"), 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, requirePermission("payroll.view"), 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, requirePermission("payroll.view"), 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, requirePermission("payroll.view"), 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.get("/v1/payroll/adjustments", ...requireCoreAuth, requirePermission("payroll.view"), async (c) => {
|
|
const db = c.get("db");
|
|
return respondRpc(c, await callCoreFn(db, "core.fn_payroll_adjustment_list", {
|
|
tenant_id: tid(c),
|
|
week_id: c.req.query("week_id"),
|
|
worker_id: c.req.query("worker_id"),
|
|
project_id: c.req.query("project_id"),
|
|
kind: c.req.query("kind"),
|
|
}, { route: routeLabel(c) }));
|
|
});
|
|
|
|
app.post("/v1/payroll/adjustments", ...requireCoreAuth, requirePermission("payroll.update"), async (c) => {
|
|
const body = await c.req.json<Record<string, unknown>>();
|
|
const db = c.get("db");
|
|
return respondRpc(c, await callCoreFn(db, "core.fn_payroll_adjustment_save", {
|
|
...body, tenant_id: tid(c),
|
|
}, { route: routeLabel(c) }));
|
|
});
|
|
|
|
app.delete("/v1/payroll/adjustments/:id", ...requireCoreAuth, requirePermission("payroll.delete"), async (c) => {
|
|
const db = c.get("db");
|
|
return respondRpc(c, await callCoreFn(db, "core.fn_payroll_adjustment_delete", {
|
|
id: Number(c.req.param("id")), tenant_id: tid(c),
|
|
}, { route: routeLabel(c) }));
|
|
});
|
|
|
|
app.get("/v1/payroll/holidays", ...requireCoreAuth, requirePermission("payroll.view"), async (c) => {
|
|
const db = c.get("db");
|
|
return respondRpc(c, await callCoreFn(db, "core.fn_holiday_list", {
|
|
tenant_id: tid(c), date_from: c.req.query("date_from"), date_to: c.req.query("date_to"),
|
|
}, { route: routeLabel(c) }));
|
|
});
|
|
|
|
app.post("/v1/payroll/holidays", ...requireCoreAuth, requirePermission("payroll.update"), async (c) => {
|
|
const body = await c.req.json<Record<string, unknown>>();
|
|
const db = c.get("db");
|
|
return respondRpc(c, await callCoreFn(db, "core.fn_holiday_save", { ...body, tenant_id: tid(c) }, { route: routeLabel(c) }));
|
|
});
|
|
|
|
app.patch("/v1/loans/:id", ...requireCoreAuth, requirePermission("payroll.update"), async (c) => {
|
|
const body = await c.req.json<Record<string, unknown>>();
|
|
const db = c.get("db");
|
|
return respondRpc(c, await callCoreFn(db, "core.fn_loan_update", {
|
|
...body, id: Number(c.req.param("id")),
|
|
}, { route: routeLabel(c) }));
|
|
});
|
|
|
|
app.get("/v1/loans/:id/statement", ...requireCoreAuth, requirePermission("payroll.view"), async (c) => {
|
|
const db = c.get("db");
|
|
return respondRpc(c, await callCoreFn(db, "core.fn_loan_statement", { id: Number(c.req.param("id")) }, { route: routeLabel(c) }));
|
|
});
|
|
|
|
app.get("/v1/settlements", ...requireCoreAuth, requirePermission("payroll.view"), async (c) => {
|
|
const db = c.get("db");
|
|
return respondRpc(c, await callCoreFn(db, "core.fn_settlement_list", {
|
|
tenant_id: tid(c), worker_id: c.req.query("worker_id"),
|
|
}, { route: routeLabel(c) }));
|
|
});
|
|
|
|
app.get("/v1/settlements/:id", ...requireCoreAuth, requirePermission("payroll.view"), async (c) => {
|
|
const db = c.get("db");
|
|
return respondRpc(c, await callCoreFn(db, "core.fn_settlement_get", { id: Number(c.req.param("id")) }, { route: routeLabel(c) }));
|
|
});
|
|
|
|
app.post("/v1/settlements", ...requireCoreAuth, requirePermission("payroll.create"), async (c) => {
|
|
const body = await c.req.json<Record<string, unknown>>();
|
|
const db = c.get("db");
|
|
return respondRpc(c, await callCoreFn(db, "core.fn_settlement_save", { ...body, tenant_id: tid(c) }, { route: routeLabel(c) }));
|
|
});
|
|
|
|
app.post("/v1/settlements/:id/pay", ...requireCoreAuth, requirePermission("payroll.update"), async (c) => {
|
|
const db = c.get("db");
|
|
return respondRpc(c, await callCoreFn(db, "core.fn_settlement_pay", { id: Number(c.req.param("id")) }, { route: routeLabel(c) }));
|
|
});
|
|
|
|
app.get("/v1/payroll/weeks/:id/dispersion", ...requireCoreAuth, requirePermission("payroll.view"), async (c) => {
|
|
const db = c.get("db");
|
|
return respondRpc(c, await callCoreFn(db, "core.fn_dispersion_get", {
|
|
tenant_id: tid(c), week_id: Number(c.req.param("id")),
|
|
}, { route: routeLabel(c) }));
|
|
});
|
|
|
|
app.post("/v1/payroll/dispersions/:id/cut", ...requireCoreAuth, requirePermission("payroll.update"), async (c) => {
|
|
const db = c.get("db");
|
|
return respondRpc(c, await callCoreFn(db, "core.fn_dispersion_cut", { id: Number(c.req.param("id")) }, { route: routeLabel(c) }));
|
|
});
|
|
|
|
app.patch("/v1/payroll/dispersion-lines/:id", ...requireCoreAuth, requirePermission("payroll.update"), async (c) => {
|
|
const body = await c.req.json<Record<string, unknown>>();
|
|
const db = c.get("db");
|
|
return respondRpc(c, await callCoreFn(db, "core.fn_dispersion_line_update", {
|
|
...body, line_id: Number(c.req.param("id")),
|
|
}, { route: routeLabel(c) }));
|
|
});
|
|
|
|
app.post("/v1/payroll/dispersions/:id/finalize", ...requireCoreAuth, requirePermission("payroll.update"), async (c) => {
|
|
const body = await c.req.json<Record<string, unknown>>().catch(() => ({}));
|
|
const db = c.get("db");
|
|
return respondRpc(c, await callCoreFn(db, "core.fn_dispersion_finalize", {
|
|
...body, id: Number(c.req.param("id")),
|
|
}, { route: routeLabel(c) }));
|
|
});
|
|
|
|
app.post("/v1/payroll/dispersions/:id/attachment", ...requireCoreAuth, requirePermission("payroll.update"), async (c) => {
|
|
const id = Number(c.req.param("id"));
|
|
const form = await c.req.formData();
|
|
const file = form.get("file");
|
|
if (!(file instanceof File)) {
|
|
return respondApiError(c, "VALIDATION", "Adjunte el comprobante de la dispersión", { route: routeLabel(c) });
|
|
}
|
|
const bytes = new Uint8Array(await file.arrayBuffer());
|
|
const { iv, cipher } = await encryptBytes(bytes);
|
|
const storageName = `${Date.now()}-${randomBytes(8).toString("hex")}`;
|
|
await putObject(dispersionDocKey(id, storageName), cipher);
|
|
const db = c.get("db");
|
|
return respondRpc(c, await callCoreFn(db, "core.fn_dispersion_attachment_add", {
|
|
dispersion_id: id,
|
|
original_name: file.name,
|
|
mime: file.type || "application/pdf",
|
|
size_bytes: bytes.length,
|
|
sha256: "",
|
|
iv,
|
|
storage_name: storageName,
|
|
uploaded_by_name: c.get("user").display_name,
|
|
}, { route: routeLabel(c) }));
|
|
});
|
|
|
|
app.get("/v1/payroll/report.xlsx", ...requireCoreAuth, requirePermission("payroll.view"), async (c) => {
|
|
const db = c.get("db");
|
|
const env = await callCoreFn<{ lines: Record<string, unknown>[]; payable_total: number }>(db, "core.fn_payroll_report", {
|
|
tenant_id: tid(c),
|
|
date_from: c.req.query("date_from"),
|
|
date_to: c.req.query("date_to"),
|
|
worker_id: c.req.query("worker_id"),
|
|
project_id: c.req.query("project_id"),
|
|
}, { route: routeLabel(c) });
|
|
if (!env.ok || !env.data) return respondRpc(c, env);
|
|
const wb = XLSX.utils.book_new();
|
|
XLSX.utils.book_append_sheet(wb, XLSX.utils.json_to_sheet(env.data.lines ?? []), "Nomina");
|
|
const out = XLSX.write(wb, { type: "buffer", bookType: "xlsx" }) as Uint8Array;
|
|
c.header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
|
|
c.header("Content-Disposition", `attachment; filename="nomina.xlsx"`);
|
|
return c.body(out.buffer as ArrayBuffer);
|
|
});
|
|
|
|
app.get("/v1/payroll/report.pdf", ...requireCoreAuth, requirePermission("payroll.view"), async (c) => {
|
|
const db = c.get("db");
|
|
const env = await callCoreFn<{ lines: Record<string, unknown>[]; payable_total: number }>(db, "core.fn_payroll_report", {
|
|
tenant_id: tid(c),
|
|
date_from: c.req.query("date_from"),
|
|
date_to: c.req.query("date_to"),
|
|
worker_id: c.req.query("worker_id"),
|
|
project_id: c.req.query("project_id"),
|
|
}, { route: routeLabel(c) });
|
|
if (!env.ok || !env.data) return respondRpc(c, env);
|
|
const pdf = await PDFDocument.create();
|
|
const page = pdf.addPage([612, 792]);
|
|
const font = await pdf.embedFont(StandardFonts.Helvetica);
|
|
page.drawText(`Nómina ${c.req.query("date_from")} a ${c.req.query("date_to")}`, { x: 40, y: 750, size: 14, font });
|
|
page.drawText(`Neto ${env.data.payable_total}`, { x: 40, y: 730, size: 11, font });
|
|
let y = 700;
|
|
for (const line of (env.data.lines ?? []).slice(0, 30)) {
|
|
page.drawText(`${line.first_name ?? ""} ${line.last_name_p ?? ""} ${line.payable_net ?? ""}`, { x: 40, y, size: 9, font });
|
|
y -= 14;
|
|
if (y < 40) break;
|
|
}
|
|
const bytes = await pdf.save();
|
|
c.header("Content-Type", "application/pdf");
|
|
c.header("Content-Disposition", `attachment; filename="nomina.pdf"`);
|
|
return c.body(bytes.buffer as ArrayBuffer);
|
|
});
|
|
|
|
app.get("/v1/payroll/imss-quote.xlsx", ...requireCoreAuth, requirePermission("payroll.view"), async (c) => {
|
|
const db = c.get("db");
|
|
const env = await callCoreFn<{ quotes: Record<string, unknown>[] }>(db, "core.fn_imss_quote", {
|
|
tenant_id: tid(c),
|
|
worker_id: c.req.query("worker_id"),
|
|
date_from: c.req.query("date_from"),
|
|
date_to: c.req.query("date_to"),
|
|
}, { route: routeLabel(c) });
|
|
if (!env.ok || !env.data) return respondRpc(c, env);
|
|
const wb = XLSX.utils.book_new();
|
|
XLSX.utils.book_append_sheet(wb, XLSX.utils.json_to_sheet(env.data.quotes ?? []), "IMSS");
|
|
const out = XLSX.write(wb, { type: "buffer", bookType: "xlsx" }) as Uint8Array;
|
|
c.header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
|
|
c.header("Content-Disposition", `attachment; filename="imss.xlsx"`);
|
|
return c.body(out.buffer as ArrayBuffer);
|
|
});
|
|
|
|
app.get("/v1/payroll/report", ...requireCoreAuth, requirePermission("payroll.view"), async (c) => {
|
|
const db = c.get("db");
|
|
return respondRpc(c, await callCoreFn(db, "core.fn_payroll_report", {
|
|
tenant_id: tid(c),
|
|
date_from: c.req.query("date_from"),
|
|
date_to: c.req.query("date_to"),
|
|
worker_id: c.req.query("worker_id"),
|
|
project_id: c.req.query("project_id"),
|
|
}, { route: routeLabel(c) }));
|
|
});
|
|
|
|
app.get("/v1/payroll/imss-quote", ...requireCoreAuth, requirePermission("payroll.view"), async (c) => {
|
|
const db = c.get("db");
|
|
return respondRpc(c, await callCoreFn(db, "core.fn_imss_quote", {
|
|
tenant_id: tid(c),
|
|
worker_id: c.req.query("worker_id"),
|
|
date_from: c.req.query("date_from"),
|
|
date_to: c.req.query("date_to"),
|
|
}, { route: routeLabel(c) }));
|
|
});
|
|
|
|
app.get("/v1/workers/:id/movements", ...requireCoreAuth, requirePermission("workers.view"), async (c) => {
|
|
const db = c.get("db");
|
|
return respondRpc(c, await callCoreFn(db, "core.fn_worker_movement_list", {
|
|
worker_id: Number(c.req.param("id")),
|
|
}, { route: routeLabel(c) }));
|
|
});
|
|
|
|
app.patch("/v1/payroll/periods/:id", ...requireCoreAuth, requirePermission("payroll.update"), 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);
|
|
});
|
|
}
|