Solucionado submodulos y subiendo codigo real
This commit is contained in:
266
frontend/src/pages/Ventas.jsx
Normal file
266
frontend/src/pages/Ventas.jsx
Normal file
@@ -0,0 +1,266 @@
|
||||
// src/pages/Ventas.jsx
|
||||
import { useState, useEffect, useMemo } from "react";
|
||||
import { api } from "../lib/api";
|
||||
import { Loader, ErrorBox, Filters, Select } from "../components/UI";
|
||||
import Modal from "../components/Modal";
|
||||
import { useColumnasAjustables } from "../lib/useColumnasAjustables";
|
||||
|
||||
const MESES = ["ENERO","FEBRERO","MARZO","ABRIL","MAYO","JUNIO","JULIO","AGOSTO","SEPTIEMBRE","OCTUBRE","NOVIEMBRE","DICIEMBRE"];
|
||||
const ANOS = [2024, 2025, 2026];
|
||||
const SEDES = ["TODOS", "LIMA", "AREQUIPA", "PIURA", "TRUJILLO"];
|
||||
const PROGRAMAS = ["TODOS", "SEMINARIOS", "OTROS", "TEAC", "TERC"];
|
||||
const COLS = ["VENDEDOR","INSCRITOS","VENTA TOTAL","INSCRITOS P.C DEL MES","VENTA P.C DEL MES","INSCRITOS MES ANTERIOR","VENTA MES ANTERIOR","AVANCE P.C TOTAL","OPC."];
|
||||
const TIPOS = ["Venta Inscritos", "Venta P.C", "Venta Pendientes"];
|
||||
const HEADERS_DETALLE = ["VENDEDOR","ALUMNO","F. MATRÍCULA","F. CANCELACIÓN","TIPO","CUOTA PROM.","DESC. ESPECIAL","INV. NETA"];
|
||||
|
||||
export default function Ventas() {
|
||||
const hoy = new Date();
|
||||
const [ano, setAno] = useState(hoy.getFullYear());
|
||||
const [mes, setMes] = useState(hoy.getMonth() + 1);
|
||||
const [sede, setSede] = useState("TODOS");
|
||||
const [programa, setPrograma] = useState("TODOS");
|
||||
const [filas, setFilas] = useState([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState(null);
|
||||
const [modal, setModal] = useState(null); // { vendedor }
|
||||
const cols = useColumnasAjustables([200, 100, 130, 120, 130, 120, 130, 140, 100]);
|
||||
|
||||
useEffect(() => {
|
||||
let activo = true;
|
||||
setLoading(true); setError(null);
|
||||
api.ventas(ano, mes, sede, programa)
|
||||
.then((res) => { if (activo) { setFilas(res.filas || []); setLoading(false); } })
|
||||
.catch((e) => { if (activo) { setError(e.message); setLoading(false); } });
|
||||
return () => { activo = false; };
|
||||
}, [ano, mes, sede, programa]);
|
||||
|
||||
const total = useMemo(() => filas.find((f) => f[0] === "TOTAL GENERAL"), [filas]);
|
||||
const datos = useMemo(() => filas.filter((f) => f[0] !== "TOTAL GENERAL"), [filas]);
|
||||
|
||||
const KPIS = total ? [
|
||||
["👤","Vendedores", datos.length, "activos este mes"],
|
||||
["🎓","Total Inscritos", total[1], "matriculados"],
|
||||
["💵","Venta Total", total[2], "inversión neta"],
|
||||
["✅","Venta P.C del Mes", total[4], "pagos completos"],
|
||||
["🚀","Avance P.C Total", total[7], "P.C + Pendientes"],
|
||||
] : [];
|
||||
|
||||
// Exportar saldos por cuota — Excel con formato (anchos, encabezado de color,
|
||||
// fechas reales, montos numéricos en soles y fila TOTAL GENERAL).
|
||||
async function exportarCuota(tipoCuota) {
|
||||
const toNum = (v) => { const n = parseFloat(String(v).replace("S/","").replace(/,/g,"").trim()); return isNaN(n)?0:n; };
|
||||
// Convierte "dd-mm-yyyy" o "dd/mm/yyyy" a Date; si no puede, devuelve el texto original
|
||||
const toDate = (v) => {
|
||||
if (!v) return "";
|
||||
const s = String(v).trim().replace(/\//g,"-");
|
||||
const p = s.split("-");
|
||||
if (p.length === 3) {
|
||||
let [d,m,y] = p;
|
||||
if (y.length === 4) return new Date(+y, +m-1, +d);
|
||||
}
|
||||
return String(v);
|
||||
};
|
||||
|
||||
let res;
|
||||
try {
|
||||
res = await api.saldoPendiente(tipoCuota);
|
||||
} catch (e) {
|
||||
alert("No se pudo obtener los datos de saldos: " + e.message);
|
||||
return;
|
||||
}
|
||||
const datosS = res.datos || [];
|
||||
const colSaldo = `SALDO ${tipoCuota.toUpperCase()}`;
|
||||
const filtrados = datosS.filter((d) => toNum(d[colSaldo]) > 0.01);
|
||||
if (filtrados.length === 0) { alert(`No hay saldos pendientes para ${tipoCuota}.`); return; }
|
||||
|
||||
const COLS = ["MATRÍCULA","VENDEDOR","ALUMNO","PROGRAMA","F. INICIO","F. MATR.","SALDO MAT.",colSaldo,"VENCIMIENTO","INV. NETA"];
|
||||
const KEYS = ["MATRICULA","VENDEDOR","ALUMNO","PROGRAMA","FECHA INICIO","FECHA MATR.","SALDO MAT.",colSaldo,"VENCIMIENTO","INV. NETA"];
|
||||
const COL_MONTO = ["SALDO MAT.", colSaldo, "INV. NETA"];
|
||||
const COL_FECHA = ["F. INICIO","F. MATR.","VENCIMIENTO"];
|
||||
|
||||
const XLSX = await import("xlsx-js-style");
|
||||
|
||||
// Construir matriz de celdas (AOA) con tipos correctos
|
||||
const headerStyle = {
|
||||
font: { bold: true, color: { rgb: "FFFFFF" }, sz: 11 },
|
||||
fill: { fgColor: { rgb: "1E40AF" } },
|
||||
alignment: { horizontal: "center", vertical: "center" },
|
||||
};
|
||||
const moneyFmt = '"S/" #,##0';
|
||||
const dateFmt = "dd/mm/yyyy";
|
||||
|
||||
const ws = {};
|
||||
const range = { s: { r: 0, c: 0 }, e: { r: filtrados.length + 1, c: COLS.length - 1 } };
|
||||
|
||||
// Encabezado
|
||||
COLS.forEach((h, c) => {
|
||||
const ref = XLSX.utils.encode_cell({ r: 0, c });
|
||||
ws[ref] = { v: h, t: "s", s: headerStyle };
|
||||
});
|
||||
|
||||
// Filas de datos
|
||||
filtrados.forEach((d, ri) => {
|
||||
KEYS.forEach((k, c) => {
|
||||
const ref = XLSX.utils.encode_cell({ r: ri + 1, c });
|
||||
const col = COLS[c];
|
||||
if (COL_MONTO.includes(col)) {
|
||||
ws[ref] = { v: toNum(d[k]), t: "n", z: moneyFmt };
|
||||
} else if (COL_FECHA.includes(col)) {
|
||||
const dt = toDate(d[k]);
|
||||
if (dt instanceof Date) ws[ref] = { v: dt, t: "d", z: dateFmt };
|
||||
else ws[ref] = { v: dt, t: "s" };
|
||||
} else {
|
||||
ws[ref] = { v: d[k] ?? "", t: "s" };
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// Fila TOTAL GENERAL: promedio en SALDO MAT. y SALDO CUOTA, suma en INV. NETA
|
||||
const rTot = filtrados.length + 1;
|
||||
const sum = (k) => filtrados.reduce((s,d)=>s+toNum(d[k]),0);
|
||||
const prom = (k) => filtrados.length ? sum(k)/filtrados.length : 0;
|
||||
const totalStyle = { font: { bold: true }, fill: { fgColor: { rgb: "EFF6FF" } } };
|
||||
COLS.forEach((col, c) => {
|
||||
const ref = XLSX.utils.encode_cell({ r: rTot, c });
|
||||
if (c === 0) ws[ref] = { v: "TOTAL GENERAL", t: "s", s: totalStyle };
|
||||
else if (col === "SALDO MAT.") ws[ref] = { v: prom("SALDO MAT."), t: "n", z: moneyFmt, s: totalStyle };
|
||||
else if (col === colSaldo) ws[ref] = { v: prom(colSaldo), t: "n", z: moneyFmt, s: totalStyle };
|
||||
else if (col === "INV. NETA") ws[ref] = { v: sum("INV. NETA"), t: "n", z: moneyFmt, s: totalStyle };
|
||||
else ws[ref] = { v: "", t: "s", s: totalStyle };
|
||||
});
|
||||
|
||||
ws["!ref"] = XLSX.utils.encode_range(range);
|
||||
ws["!cols"] = [
|
||||
{ wch: 12 }, // MATRÍCULA
|
||||
{ wch: 22 }, // VENDEDOR
|
||||
{ wch: 28 }, // ALUMNO
|
||||
{ wch: 32 }, // PROGRAMA
|
||||
{ wch: 12 }, // F. INICIO
|
||||
{ wch: 12 }, // F. MATR.
|
||||
{ wch: 13 }, // SALDO MAT.
|
||||
{ wch: 15 }, // SALDO CUOTA
|
||||
{ wch: 13 }, // VENCIMIENTO
|
||||
{ wch: 13 }, // INV. NETA
|
||||
];
|
||||
|
||||
const wb = XLSX.utils.book_new();
|
||||
XLSX.utils.book_append_sheet(wb, ws, "Saldos");
|
||||
const nombre = tipoCuota.replace("°","").replace(/\s/g,"_");
|
||||
XLSX.writeFile(wb, `saldos_${nombre}.xlsx`);
|
||||
}
|
||||
|
||||
return (
|
||||
<div>
|
||||
<h1 className="page-title">🛒 Ventas</h1>
|
||||
|
||||
<Filters>
|
||||
<Select label="Año" value={ano} options={ANOS} onChange={(v) => setAno(+v)} />
|
||||
<Select label="Mes" value={mes} options={MESES.map((m,i)=>({value:i+1,label:m}))} onChange={(v) => setMes(+v)} />
|
||||
<Select label="Sede" value={sede} options={SEDES} onChange={setSede} />
|
||||
<Select label="Programa" value={programa} options={PROGRAMAS} onChange={setPrograma} />
|
||||
<div style={{display:"flex",gap:8,alignItems:"flex-end",marginLeft:"auto"}}>
|
||||
<button className="btn btn-primary" style={{height:38}} onClick={() => exportarCuota("1° Cuota")}>
|
||||
⬇️ Exportar 1° Cuota
|
||||
</button>
|
||||
<button className="btn btn-primary" style={{height:38}} onClick={() => exportarCuota("2° Cuota")}>
|
||||
⬇️ Exportar 2° Cuota
|
||||
</button>
|
||||
</div>
|
||||
</Filters>
|
||||
|
||||
{loading ? <Loader text="Calculando ventas..." /> :
|
||||
error ? <ErrorBox msg={error} /> :
|
||||
<>
|
||||
<div className="kpis" style={{ gridTemplateColumns: "repeat(5,1fr)" }}>
|
||||
{KPIS.map(([ico,label,val,sub]) => (
|
||||
<div className="kpi" key={label}>
|
||||
<div className="ico">{ico}</div>
|
||||
<div className="label" style={{fontSize:15}}>{label}</div>
|
||||
<div className="value" style={{fontSize:20}}>{val}</div>
|
||||
<div className="sub">{sub}</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div className="table-wrap" style={{overflowX:"auto"}}>
|
||||
<table {...cols.tableProps}>
|
||||
<cols.ColGroup />
|
||||
<thead><tr>{COLS.map((c, i) => <th key={c} style={{position:"relative"}}>{c}<cols.Resizer index={i} /></th>)}</tr></thead>
|
||||
<tbody>
|
||||
{datos.map((f, i) => (
|
||||
<tr key={i}>
|
||||
<td className="col-name">{f[0]}</td>
|
||||
<td>{f[1]}</td><td>{f[2]}</td>
|
||||
<td>{f[3]}</td><td>{f[4]}</td>
|
||||
<td>{f[5]}</td><td>{f[6]}</td>
|
||||
<td style={{fontWeight:600}}>{f[7]}</td>
|
||||
<td>
|
||||
<button className="btn btn-ghost" style={{padding:"4px 10px",fontSize:11}}
|
||||
onClick={() => setModal({ vendedor: f[0] })}>👁️ Ver</button>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
{total && (
|
||||
<tr className="total-row">
|
||||
<td className="col-name">TOTAL GENERAL</td>
|
||||
<td>{total[1]}</td><td>{total[2]}</td>
|
||||
<td>{total[3]}</td><td>{total[4]}</td>
|
||||
<td>{total[5]}</td><td>{total[6]}</td>
|
||||
<td>{total[7]}</td><td>—</td>
|
||||
</tr>
|
||||
)}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</>}
|
||||
|
||||
{modal && (
|
||||
<ModalDetalle vendedor={modal.vendedor} ano={ano} mes={mes} onClose={() => setModal(null)} />
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function ModalDetalle({ vendedor, ano, mes, onClose }) {
|
||||
const [tipo, setTipo] = useState(TIPOS[0]);
|
||||
const [filas, setFilas] = useState([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
|
||||
useEffect(() => {
|
||||
let activo = true;
|
||||
setLoading(true);
|
||||
api.ventasDetalle(vendedor, ano, mes, tipo)
|
||||
.then((res) => { if (activo) { setFilas(res.filas || []); setLoading(false); } })
|
||||
.catch(() => { if (activo) { setFilas([]); setLoading(false); } });
|
||||
return () => { activo = false; };
|
||||
}, [vendedor, ano, mes, tipo]);
|
||||
|
||||
// Columnas redimensionables (igual que las tablas principales)
|
||||
const colsDet = useColumnasAjustables([200, 260, 120, 130, 120, 120, 130, 120]);
|
||||
|
||||
return (
|
||||
<Modal title={`👤 ${vendedor}`} onClose={onClose} width={1500}>
|
||||
<div style={{ marginBottom: 14 }}>
|
||||
<Select label="Tipo de venta" value={tipo} options={TIPOS} onChange={setTipo} />
|
||||
</div>
|
||||
{loading ? <Loader text="Cargando detalle..." /> :
|
||||
filas.length === 0 ? <div style={{color:"#94a3b8",padding:20,textAlign:"center"}}>Sin registros para esta categoría.</div> :
|
||||
<div className="table-wrap" style={{overflowX:"auto"}}>
|
||||
<table {...colsDet.tableProps}>
|
||||
<colsDet.ColGroup />
|
||||
<thead><tr>{HEADERS_DETALLE.map((h, i) => <th key={h} style={{position:"relative", whiteSpace:"nowrap"}}>{h}<colsDet.Resizer index={i} /></th>)}</tr></thead>
|
||||
<tbody>
|
||||
{filas.map((f, i) => (
|
||||
<tr key={i}>
|
||||
{f.slice(0, HEADERS_DETALLE.length).map((v, j) => (
|
||||
<td key={j} className={j === 1 ? "col-name" : ""}
|
||||
style={{textAlign:"center", whiteSpace:"nowrap", overflow:"hidden", textOverflow:"ellipsis"}}>{v}</td>
|
||||
))}
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>}
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user