mirror of
https://origin.cursor.com/mrdevmx/panels.git
synced 2026-10-09 17:33:16 +00:00
460 lines
16 KiB
TypeScript
460 lines
16 KiB
TypeScript
import type { Hono } from "hono";
|
|
import type { AuthUser } from "./auth.ts";
|
|
import { tenantScope, requireAuth } from "./auth.ts";
|
|
import { getDb, lastInsertId, projectById, projectMustBe } 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,
|
|
saveSettings,
|
|
setAttendance,
|
|
tenantKey,
|
|
todayIso,
|
|
updateAdminLine,
|
|
weekContaining,
|
|
weekCsv,
|
|
} from "./payroll.ts";
|
|
|
|
type App = Hono<{ Variables: { user: AuthUser } }>;
|
|
|
|
function tid(c: { get: (k: "user") => AuthUser }): number {
|
|
return tenantKey(tenantScope(c.get("user")));
|
|
}
|
|
|
|
async function pdfBody(
|
|
c: { header: (k: string, v: string) => void; body: (data: ArrayBuffer) => unknown },
|
|
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", requireAuth, async (c) => {
|
|
const projectId = Number(c.req.query("project_id"));
|
|
const from = c.req.query("from") ?? "";
|
|
const to = c.req.query("to") ?? "";
|
|
const db = await getDb();
|
|
const rows = 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", requireAuth, async (c) => {
|
|
const body = await c.req.json<{
|
|
project_id: number;
|
|
worker_id: number;
|
|
work_date: string;
|
|
present: boolean;
|
|
}>();
|
|
const db = await getDb();
|
|
const blocked = projectMustBe(
|
|
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 = 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", requireAuth, async (c) => {
|
|
const db = await getDb();
|
|
const tenantId = tid(c);
|
|
return c.json({ settings: getSettings(db, tenantId), units: listUnits(db, tenantId) });
|
|
});
|
|
|
|
app.patch("/v1/payroll/settings", requireAuth, async (c) => {
|
|
const db = await getDb();
|
|
const body = await c.req.json<{
|
|
loan_commission_enabled?: number | boolean;
|
|
loan_commission_pct?: number;
|
|
loan_small_max?: number;
|
|
}>();
|
|
const settings = saveSettings(db, tid(c), {
|
|
loan_commission_enabled: body.loan_commission_enabled === undefined
|
|
? undefined
|
|
: body.loan_commission_enabled ? 1 : 0,
|
|
loan_commission_pct: body.loan_commission_pct,
|
|
loan_small_max: body.loan_small_max,
|
|
});
|
|
return c.json({ settings });
|
|
});
|
|
|
|
app.post("/v1/destajo/units", requireAuth, async (c) => {
|
|
const body = await c.req.json<{ code: string; label?: string }>();
|
|
const db = await getDb();
|
|
try {
|
|
const id = 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", requireAuth, async (c) => {
|
|
const db = await getDb();
|
|
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 ? db.prepare(sql).all(Number(workerId)) : db.prepare(sql).all();
|
|
return c.json({ loans });
|
|
});
|
|
|
|
app.post("/v1/loans", requireAuth, 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 = await getDb();
|
|
try {
|
|
const created = 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", requireAuth, async (c) => {
|
|
const id = Number(c.req.param("id"));
|
|
const db = await getDb();
|
|
const loan = 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", requireAuth, async (c) => {
|
|
const id = Number(c.req.param("id"));
|
|
const db = await getDb();
|
|
const pay = 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", requireAuth, async (c) => {
|
|
const db = await getDb();
|
|
const tenantId = tid(c);
|
|
const start = c.req.query("week_start") || weekContaining(todayIso()).weekStart;
|
|
const bundle = getWeekBundle(db, tenantId, start);
|
|
return c.json(bundle);
|
|
});
|
|
|
|
app.get("/v1/payroll/weeks/open", requireAuth, async (c) => {
|
|
const db = await getDb();
|
|
return c.json({ weeks: listOpenWeeks(db, tid(c)) });
|
|
});
|
|
|
|
app.post("/v1/payroll/weeks/:id/assemble", requireAuth, async (c) => {
|
|
const db = await getDb();
|
|
try {
|
|
assembleWeek(db, Number(c.req.param("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/pay", requireAuth, async (c) => {
|
|
const db = await getDb();
|
|
try {
|
|
payWeek(db, Number(c.req.param("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.get("/v1/payroll/weeks/:id/csv", requireAuth, async (c) => {
|
|
const id = Number(c.req.param("id"));
|
|
const db = await getDb();
|
|
const csv = 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", requireAuth, async (c) => {
|
|
const body = await c.req.json<{ project_id: number; worker_id: number }>();
|
|
const db = await getDb();
|
|
try {
|
|
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", requireAuth, async (c) => {
|
|
const body = await c.req.json<{ worker_id: number; amount: number; project_id?: number | null }>();
|
|
const db = await getDb();
|
|
try {
|
|
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", requireAuth, async (c) => {
|
|
const body = await c.req.json<{ amount: number }>();
|
|
const db = await getDb();
|
|
try {
|
|
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", requireAuth, async (c) => {
|
|
const db = await getDb();
|
|
try {
|
|
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", requireAuth, 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 = await getDb();
|
|
try {
|
|
const created = 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", requireAuth, async (c) => {
|
|
const body = await c.req.json<{
|
|
week_id: number;
|
|
qty_planned?: number;
|
|
qty_actual?: number;
|
|
qty_extra?: number;
|
|
}>();
|
|
const db = await getDb();
|
|
try {
|
|
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", requireAuth, async (c) => {
|
|
const body = await c.req.json<{
|
|
project_id: number;
|
|
week_start: string;
|
|
week_end: string;
|
|
extra_discounts?: Record<number, number>;
|
|
}>();
|
|
const db = await getDb();
|
|
const blocked = projectMustBe(
|
|
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);
|
|
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 = lastInsertId(db);
|
|
const workers = 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=1
|
|
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 = db.prepare(
|
|
`SELECT COUNT(*) AS n FROM attendance
|
|
WHERE worker_id=? AND project_id=? AND work_date BETWEEN ? AND ? AND present=1`,
|
|
).get(w.id, body.project_id, body.week_start, body.week_end) as { n: number };
|
|
const days = att.n;
|
|
const gross = days * w.daily_wage;
|
|
const extra = Number(body.extra_discounts?.[w.id] ?? 0);
|
|
const net = gross - extra;
|
|
ins.run(periodId, w.id, days, w.daily_wage, gross, extra, 0, net);
|
|
}
|
|
return c.json({ id: periodId });
|
|
});
|
|
|
|
app.get("/v1/payroll/periods", requireAuth, async (c) => {
|
|
const db = await getDb();
|
|
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 ? db.prepare(sql).all(Number(projectId)) : db.prepare(sql).all();
|
|
return c.json({ periods });
|
|
});
|
|
|
|
app.get("/v1/payroll/periods/:id", requireAuth, async (c) => {
|
|
const id = Number(c.req.param("id"));
|
|
const db = await getDb();
|
|
const period = 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 = 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", requireAuth, async (c) => {
|
|
const id = Number(c.req.param("id"));
|
|
const db = await getDb();
|
|
const lines = 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", requireAuth, async (c) => {
|
|
const id = Number(c.req.param("id"));
|
|
const { status } = await c.req.json<{ status: string }>();
|
|
const db = await getDb();
|
|
db.prepare("UPDATE payroll_periods SET status=? WHERE id=?").run(status, id);
|
|
return c.json({ ok: true });
|
|
});
|
|
}
|