mirror of
https://origin.cursor.com/mrdevmx/panels.git
synced 2026-10-09 18:03:18 +00:00
El Excel Neodata por partida sí se leía (A001–A009, 9 semanas), pero
la API devolvía { ok, data } sin envelope y el panel no desembalaba
data: el diálogo mostraba 0 y «Sin match». Ahora se aplana la
respuesta y el preview lista las partidas encontradas.
Co-authored-by: alberto.martinez <alberto.martinez@mrdev.mx>
212 lines
8.3 KiB
TypeScript
212 lines
8.3 KiB
TypeScript
import type { Context, Hono } from "hono";
|
|
import type { AuthUser } from "./auth.ts";
|
|
import { requireCoreAuth } from "./scope.ts";
|
|
import type { Db } from "./db.ts";
|
|
import { projectById } from "./db.ts";
|
|
import { requirePermission } from "./permissions.ts";
|
|
import { denyUnlessProjectScope } from "./scope_enforcement.ts";
|
|
import { respondApiError, respondRpc, routeLabel } from "./http_errors.ts";
|
|
import {
|
|
createEmptyWorkProgram,
|
|
exportWorkProgram,
|
|
generateWorkProgram,
|
|
getVsCost,
|
|
getWorkProgram,
|
|
importWorkProgramExcel,
|
|
listConcepts,
|
|
listPartidas,
|
|
previewWorkProgramExcel,
|
|
recalculatePartidas,
|
|
updateConceptSlot,
|
|
updatePartidaAmount,
|
|
updateProgress,
|
|
} from "./work_program.ts";
|
|
|
|
type App = Hono<{ Variables: { user: AuthUser; db: Db } }>;
|
|
|
|
const viewAuth = [...requireCoreAuth, requirePermission("work_program.view")] as const;
|
|
|
|
async function ensureProject(c: Context, id: number): Promise<boolean> {
|
|
return await denyUnlessProjectScope(c, id);
|
|
}
|
|
|
|
function respondOk<T>(c: Context, data: T, message: string) {
|
|
return respondRpc(c, {
|
|
ok: true,
|
|
code: "OK",
|
|
layer: "api",
|
|
message,
|
|
data,
|
|
});
|
|
}
|
|
|
|
async function readUpload(c: Context): Promise<{ bytes: Uint8Array } | { response: Response }> {
|
|
const form = await c.req.formData();
|
|
const file = form.get("file");
|
|
if (!(file instanceof File)) {
|
|
return {
|
|
response: respondApiError(c, "VALIDATION", "Seleccione un archivo Excel (.xlsx o .xls) de programa de obra", {
|
|
route: routeLabel(c),
|
|
}),
|
|
};
|
|
}
|
|
const name = file.name.trim().toLowerCase();
|
|
if (!name.endsWith(".xlsx") && !name.endsWith(".xls")) {
|
|
return {
|
|
response: respondApiError(
|
|
c,
|
|
"VALIDATION",
|
|
`Solo se aceptan archivos Excel (.xlsx o .xls). «${file.name}» no es un Excel de programa de obra.`,
|
|
{ route: routeLabel(c), filename: file.name },
|
|
),
|
|
};
|
|
}
|
|
return { bytes: new Uint8Array(await file.arrayBuffer()) };
|
|
}
|
|
|
|
export function registerWorkProgramRoutes(app: App) {
|
|
app.get("/v1/projects/:id/work-program", ...viewAuth, async (c) => {
|
|
const id = Number(c.req.param("id"));
|
|
if (!await ensureProject(c, id)) return;
|
|
const db = c.get("db");
|
|
const data = await getWorkProgram(db, id);
|
|
return respondOk(c, data, data.program ? "Programa de obra cargado" : "La obra no tiene programa de obra");
|
|
});
|
|
|
|
app.get("/v1/projects/:id/work-program/concepts", ...viewAuth, async (c) => {
|
|
const id = Number(c.req.param("id"));
|
|
if (!await ensureProject(c, id)) return;
|
|
const db = c.get("db");
|
|
const data = await listConcepts(db, id);
|
|
return respondOk(c, data, "Conceptos del programa de obra");
|
|
});
|
|
|
|
app.get("/v1/projects/:id/work-program/partidas", ...viewAuth, async (c) => {
|
|
const id = Number(c.req.param("id"));
|
|
if (!await ensureProject(c, id)) return;
|
|
const db = c.get("db");
|
|
const data = await listPartidas(db, id);
|
|
return respondOk(c, data, "Partidas del programa de obra");
|
|
});
|
|
|
|
app.get("/v1/projects/:id/work-program/vs-cost", ...requireCoreAuth, requirePermission("cost_control.view"), async (c) => {
|
|
const id = Number(c.req.param("id"));
|
|
if (!await ensureProject(c, id)) return;
|
|
const db = c.get("db");
|
|
const data = await getVsCost(db, id);
|
|
return respondOk(c, data, "Comparativo programado vs costos");
|
|
});
|
|
|
|
app.post("/v1/projects/:id/work-program/preview", ...requireCoreAuth, requirePermission("work_program.create"), async (c) => {
|
|
const id = Number(c.req.param("id"));
|
|
if (!await ensureProject(c, id)) return;
|
|
const db = c.get("db");
|
|
const upload = await readUpload(c);
|
|
if ("response" in upload) return upload.response;
|
|
const preview = await previewWorkProgramExcel(upload.bytes, id, db);
|
|
const found = preview.format === "concepto" ? preview.concepts.length : preview.partidas.length;
|
|
return respondOk(
|
|
c,
|
|
preview,
|
|
preview.format === "none"
|
|
? "No se reconoció el formato del programa de obra"
|
|
: `${preview.format_label}: ${found} renglón(es), ${preview.period_count} semana(s)`,
|
|
);
|
|
});
|
|
|
|
app.post("/v1/projects/:id/work-program/import", ...requireCoreAuth, requirePermission("work_program.create"), async (c) => {
|
|
const id = Number(c.req.param("id"));
|
|
if (!await ensureProject(c, id)) return;
|
|
const db = c.get("db");
|
|
const upload = await readUpload(c);
|
|
if ("response" in upload) return upload.response;
|
|
const createChapters = c.req.query("create_chapters") !== "false";
|
|
const data = await importWorkProgramExcel(db, id, upload.bytes, { createChapters });
|
|
return respondOk(c, data, "Programa de obra importado");
|
|
});
|
|
|
|
app.post("/v1/projects/:id/work-program", ...requireCoreAuth, requirePermission("work_program.create"), async (c) => {
|
|
const id = Number(c.req.param("id"));
|
|
if (!await ensureProject(c, id)) return;
|
|
const db = c.get("db");
|
|
const data = await createEmptyWorkProgram(db, id);
|
|
return respondOk(c, data, "Programa de obra creado en blanco");
|
|
});
|
|
|
|
app.post("/v1/projects/:id/work-program/generate", ...requireCoreAuth, requirePermission("work_program.create"), async (c) => {
|
|
const id = Number(c.req.param("id"));
|
|
if (!await ensureProject(c, id)) return;
|
|
const db = c.get("db");
|
|
const body = await c.req.json().catch(() => ({})) as { strategy?: string };
|
|
const data = await generateWorkProgram(db, id, body.strategy || "keyword");
|
|
return respondOk(c, data, "Programa de obra generado");
|
|
});
|
|
|
|
app.post("/v1/projects/:id/work-program/recalculate-partidas", ...requireCoreAuth, requirePermission("work_program.update"), async (c) => {
|
|
const id = Number(c.req.param("id"));
|
|
if (!await ensureProject(c, id)) return;
|
|
const db = c.get("db");
|
|
const env = await recalculatePartidas(db, id);
|
|
return respondOk(c, env, "Erogaciones por partida recalculadas");
|
|
});
|
|
|
|
app.patch("/v1/projects/:id/work-program/concepts/:itemId/periods/:periodId", ...requireCoreAuth, requirePermission("work_program.update"), async (c) => {
|
|
const id = Number(c.req.param("id"));
|
|
if (!await ensureProject(c, id)) return;
|
|
const db = c.get("db");
|
|
const body = await c.req.json() as { start_pct?: number; end_pct?: number };
|
|
const data = await updateConceptSlot(
|
|
db,
|
|
id,
|
|
Number(c.req.param("itemId")),
|
|
Number(c.req.param("periodId")),
|
|
Number(body.start_pct ?? 0),
|
|
Number(body.end_pct ?? 0),
|
|
);
|
|
return respondOk(c, data, "Avance de concepto actualizado");
|
|
});
|
|
|
|
app.patch("/v1/projects/:id/work-program/partidas/:chapterId/periods/:periodId", ...requireCoreAuth, requirePermission("work_program.update"), async (c) => {
|
|
const id = Number(c.req.param("id"));
|
|
if (!await ensureProject(c, id)) return;
|
|
const db = c.get("db");
|
|
const body = await c.req.json() as { amount?: number };
|
|
const data = await updatePartidaAmount(
|
|
db,
|
|
id,
|
|
Number(c.req.param("chapterId")),
|
|
Number(c.req.param("periodId")),
|
|
Number(body.amount ?? 0),
|
|
);
|
|
return respondOk(c, data, "Erogación de partida actualizada");
|
|
});
|
|
|
|
app.patch("/v1/projects/:id/work-program/progress/:itemId/periods/:periodId", ...requireCoreAuth, requirePermission("work_program.update"), async (c) => {
|
|
const id = Number(c.req.param("id"));
|
|
if (!await ensureProject(c, id)) return;
|
|
const db = c.get("db");
|
|
const body = await c.req.json() as { pct_complete?: number };
|
|
const data = await updateProgress(
|
|
db,
|
|
id,
|
|
Number(c.req.param("itemId")),
|
|
Number(c.req.param("periodId")),
|
|
Number(body.pct_complete ?? 0),
|
|
);
|
|
return respondOk(c, data, "Porcentaje de avance actualizado");
|
|
});
|
|
|
|
app.get("/v1/projects/:id/work-program/export", ...viewAuth, async (c) => {
|
|
const db = c.get("db");
|
|
const id = Number(c.req.param("id"));
|
|
if (!await ensureProject(c, id)) return;
|
|
const kind = (c.req.query("kind") === "partida" ? "partida" : "concepto") as "concepto" | "partida";
|
|
const project = await projectById(db, id);
|
|
if (!project) return c.json({ error: "Proyecto no encontrado" }, 404);
|
|
const bytes = await exportWorkProgram(db, id, kind, String(project.name || "Obra"));
|
|
const filename = kind === "partida" ? "programa-partidas.xlsx" : "programa-conceptos.xlsx";
|
|
c.header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
|
|
c.header("Content-Disposition", `attachment; filename="${filename}"`);
|
|
return c.body(bytes.slice());
|
|
});
|
|
}
|