mirror of
https://origin.cursor.com/mrdevmx/panels.git
synced 2026-10-09 10:43:18 +00:00
<!-- CURSOR_AGENT_PR_BODY_BEGIN --> ## Summary Implementa el módulo **Programa de obra** por proyecto, vinculado al presupuesto ya existente. ### Flujo 1. Cargar presupuesto (requisito) 2. Definir fechas de inicio/término en el proyecto 3. Crear programa: **importar Excel Neodata/Opus**, **generar automático** o **crear vacío** 4. Editar en cuadrícula (conceptos con `Barra=` y partidas con erogaciones semanales) 5. Visualizar Gantt resumido y comparativo **programado vs ejecutado** ### Backend - Tablas: `work_programs`, `work_program_periods`, `work_program_concept_slots`, `work_program_partida_amounts`, `work_program_progress` - RPC: list/get, replace (import), generate (wizard), update celdas, recalculate partidas, vs-cost - Parser Excel para formatos **por concepto** (`Barra=`) y **por partida** (montos semanales) - Tests con fixtures reales del usuario ### Frontend - Nueva página `/programa-obra` con pestañas: Conceptos, Partidas, Gantt, Programado vs costos - Diálogos de importación y generación automática - Menú principal, enlace en ficha de proyecto, banner en presupuesto ### Permisos Reutiliza `manage_budget` en MVP. ## Test plan - [x] `deno test api/work_program_excel_test.ts` (5 tests) - [x] `deno check` API modules - [x] `npm run build` web-panel - [ ] Migrar DB (`029`, `030`) en entorno con Postgres - [ ] Importar Excel por concepto y por partida en obra con presupuesto - [ ] Generar automático con estrategia keyword - [ ] Recalcular partidas desde conceptos - [ ] Verificar tab Programado vs costos con gastos registrados <!-- CURSOR_AGENT_PR_BODY_END --> <div><a href="https://cursor.com/agents/bc-3985fe74-d26b-4506-bd4d-f9ad57374141?cursor_ref=pr_footer&cursor_cta=open_in_web"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/open-in-web-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/open-in-web-light.png"><img alt="Open in Web" width="114" height="28" src="https://cursor.com/assets/images/open-in-web-dark.png"></picture></a> <a href="https://cursor.com/background-agent?bcId=bc-3985fe74-d26b-4506-bd4d-f9ad57374141&cursor_ref=pr_footer&cursor_cta=open_in_cursor"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/open-in-cursor-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/open-in-cursor-light.png"><img alt="Open in Cursor" width="131" height="28" src="https://cursor.com/assets/images/open-in-cursor-dark.png"></picture></a> </div>
245 lines
7 KiB
TypeScript
245 lines
7 KiB
TypeScript
import * as XLSX from "xlsx";
|
|
import type { Db } from "./db.ts";
|
|
import { callCoreFn, RpcCallError } from "./rpc.ts";
|
|
import { listBudget } from "./budget.ts";
|
|
import {
|
|
exportWorkProgramWorkbook,
|
|
matchWorkProgramImport,
|
|
parseWorkProgramWorkbook,
|
|
type WorkProgramExcelPreview,
|
|
} from "./work_program_excel.ts";
|
|
|
|
export type WorkProgramSummary = {
|
|
program: Record<string, unknown> | null;
|
|
periods: Record<string, unknown>[];
|
|
budget_subtotal: number;
|
|
curve: { period_index: number; label: string; amount: number; pct_period: number; pct_cumulative: number }[];
|
|
};
|
|
|
|
async function rpc<T>(db: Db, fn: string, payload: Record<string, unknown>): Promise<T> {
|
|
const env = await callCoreFn(db, fn, payload);
|
|
if (!env.ok) throw new RpcCallError(env);
|
|
return env.data as T;
|
|
}
|
|
|
|
export async function getWorkProgram(db: Db, projectId: number): Promise<WorkProgramSummary> {
|
|
return rpc(db, "core.fn_work_program_get", { project_id: projectId });
|
|
}
|
|
|
|
export async function listConcepts(db: Db, projectId: number) {
|
|
return rpc<{ periods: Record<string, unknown>[]; items: Record<string, unknown>[] }>(
|
|
db,
|
|
"core.fn_work_program_list_concepts",
|
|
{ project_id: projectId },
|
|
);
|
|
}
|
|
|
|
export async function listPartidas(db: Db, projectId: number) {
|
|
return rpc<{ periods: Record<string, unknown>[]; chapters: Record<string, unknown>[] }>(
|
|
db,
|
|
"core.fn_work_program_list_partidas",
|
|
{ project_id: projectId },
|
|
);
|
|
}
|
|
|
|
export async function getVsCost(db: Db, projectId: number) {
|
|
return rpc(db, "core.fn_work_program_vs_cost", { project_id: projectId });
|
|
}
|
|
|
|
export async function previewWorkProgramExcel(
|
|
bytes: Uint8Array,
|
|
projectId: number,
|
|
db: Db,
|
|
): Promise<WorkProgramExcelPreview & { match?: ReturnType<typeof matchWorkProgramImport> }> {
|
|
const parsed = parseWorkProgramWorkbook(bytes);
|
|
if (parsed.format === "none") return parsed;
|
|
|
|
const budget = await listBudget(db, projectId);
|
|
const ctx = {
|
|
items: budget.items.map((i) => ({
|
|
id: i.id,
|
|
code: i.code,
|
|
description: i.description,
|
|
unit: i.unit,
|
|
amount: Number(i.amount),
|
|
chapter_id: i.chapter_id,
|
|
})),
|
|
chapters: budget.chapters.map((c) => ({
|
|
id: c.id,
|
|
code: c.code,
|
|
name: c.name,
|
|
amount: budget.items.filter((i) => i.chapter_id === c.id).reduce((s, i) => s + Number(i.amount), 0),
|
|
})),
|
|
};
|
|
|
|
const matched = matchWorkProgramImport(parsed, ctx);
|
|
return { ...matched.preview, match: matched };
|
|
}
|
|
|
|
export async function importWorkProgramExcel(
|
|
db: Db,
|
|
projectId: number,
|
|
bytes: Uint8Array,
|
|
opts?: { createChapters?: boolean },
|
|
): Promise<Record<string, unknown>> {
|
|
const parsed = parseWorkProgramWorkbook(bytes);
|
|
const budget = await listBudget(db, projectId);
|
|
let chapters = [...budget.chapters];
|
|
|
|
const ctx = {
|
|
items: budget.items.map((i) => ({
|
|
id: i.id,
|
|
code: i.code,
|
|
description: i.description,
|
|
unit: i.unit,
|
|
amount: Number(i.amount),
|
|
chapter_id: i.chapter_id,
|
|
})),
|
|
chapters: chapters.map((c) => ({
|
|
id: c.id,
|
|
code: c.code,
|
|
name: c.name,
|
|
amount: budget.items.filter((i) => i.chapter_id === c.id).reduce((s, i) => s + Number(i.amount), 0),
|
|
})),
|
|
};
|
|
|
|
let { payload, preview } = matchWorkProgramImport(parsed, ctx);
|
|
|
|
if (opts?.createChapters !== false && payload.chapters_to_create.length) {
|
|
for (const ch of payload.chapters_to_create) {
|
|
await callCoreFn(db, "core.fn_budget_chapter_create", {
|
|
project_id: projectId,
|
|
code: ch.code,
|
|
name: ch.name,
|
|
sort_order: ch.sort_order,
|
|
});
|
|
}
|
|
const refreshed = await listBudget(db, projectId);
|
|
chapters = refreshed.chapters;
|
|
const chapterByCode = new Map(chapters.map((c) => [c.code.toUpperCase(), c]));
|
|
for (const row of preview.partidas) {
|
|
const ch = chapterByCode.get(row.code.toUpperCase());
|
|
if (!ch) continue;
|
|
row.amounts.forEach((amount, i) => {
|
|
if (amount !== 0) {
|
|
payload.partida_amounts.push({
|
|
budget_chapter_id: ch.id,
|
|
period_index: i + 1,
|
|
amount,
|
|
});
|
|
}
|
|
});
|
|
}
|
|
}
|
|
|
|
return rpc(db, "core.fn_work_program_replace", {
|
|
project_id: projectId,
|
|
source: "import",
|
|
status: "active",
|
|
concept_slots: payload.concept_slots,
|
|
partida_amounts: payload.partida_amounts,
|
|
chapters_to_create: [],
|
|
});
|
|
}
|
|
|
|
export async function createEmptyWorkProgram(db: Db, projectId: number) {
|
|
return rpc(db, "core.fn_work_program_replace", {
|
|
project_id: projectId,
|
|
source: "manual",
|
|
status: "draft",
|
|
concept_slots: [],
|
|
partida_amounts: [],
|
|
});
|
|
}
|
|
|
|
export async function generateWorkProgram(
|
|
db: Db,
|
|
projectId: number,
|
|
strategy: string,
|
|
) {
|
|
return rpc(db, "core.fn_work_program_generate", { project_id: projectId, strategy });
|
|
}
|
|
|
|
export async function updateConceptSlot(
|
|
db: Db,
|
|
projectId: number,
|
|
budgetItemId: number,
|
|
periodId: number,
|
|
start_pct: number,
|
|
end_pct: number,
|
|
) {
|
|
return rpc(db, "core.fn_work_program_update_concept", {
|
|
project_id: projectId,
|
|
budget_item_id: budgetItemId,
|
|
period_id: periodId,
|
|
start_pct,
|
|
end_pct,
|
|
});
|
|
}
|
|
|
|
export async function updatePartidaAmount(
|
|
db: Db,
|
|
projectId: number,
|
|
chapterId: number,
|
|
periodId: number,
|
|
amount: number,
|
|
) {
|
|
return rpc(db, "core.fn_work_program_update_partida", {
|
|
project_id: projectId,
|
|
budget_chapter_id: chapterId,
|
|
period_id: periodId,
|
|
amount,
|
|
});
|
|
}
|
|
|
|
export async function updateProgress(
|
|
db: Db,
|
|
projectId: number,
|
|
budgetItemId: number,
|
|
periodId: number,
|
|
pct_complete: number,
|
|
) {
|
|
return rpc(db, "core.fn_work_program_update_progress", {
|
|
project_id: projectId,
|
|
budget_item_id: budgetItemId,
|
|
period_id: periodId,
|
|
pct_complete,
|
|
});
|
|
}
|
|
|
|
export async function recalculatePartidas(db: Db, projectId: number) {
|
|
return rpc(db, "core.fn_work_program_recalculate_partidas", { project_id: projectId });
|
|
}
|
|
|
|
export async function exportWorkProgram(
|
|
db: Db,
|
|
projectId: number,
|
|
kind: "concepto" | "partida",
|
|
projectName: string,
|
|
): Promise<Uint8Array> {
|
|
const summary = await getWorkProgram(db, projectId);
|
|
const periodCount = summary.periods.length || 1;
|
|
|
|
if (kind === "concepto") {
|
|
const data = await listConcepts(db, projectId);
|
|
const items = (data.items || []).map((item) => ({
|
|
code: String(item.code || ""),
|
|
description: String(item.description || ""),
|
|
unit: String(item.unit || ""),
|
|
periods: ((item.periods as { period_index: number; start_pct: number; end_pct: number }[]) || []).filter(
|
|
(p) => Number(p.start_pct) !== 0 || Number(p.end_pct) !== 0,
|
|
),
|
|
}));
|
|
return exportWorkProgramWorkbook(kind, projectName, items, [], periodCount);
|
|
}
|
|
|
|
const data = await listPartidas(db, projectId);
|
|
const chapters = (data.chapters || []).map((ch) => ({
|
|
code: String(ch.code || ""),
|
|
name: String(ch.name || ""),
|
|
periods: ((ch.periods as { period_index: number; amount: number }[]) || []).filter((p) => Number(p.amount) !== 0),
|
|
}));
|
|
return exportWorkProgramWorkbook(kind, projectName, [], chapters, periodCount);
|
|
}
|
|
|
|
export { parseBarString } from "./work_program_excel.ts";
|