Cobrar en lote: - Se elimina el campo "Concepto del lote". - Cada cobro usa su concepto individual (autoConcepto del renglón), enviado por fila al backend. autoConcepto ahora usa la etiqueta en tipo "otro" (ej. WK-TENENCIA-CLIENTE-JUN26) en vez de "OTRO". - Botón "Seleccionar/Deseleccionar todos" (solo afecta renglones con número; los sin número no entran a la selección masiva). - (fix previo) autoselección y badge usan telefono_efectivo (override O directorio), no solo el override local. Backend: LoteFila.concepto opcional + CobrarLoteBody.concepto opcional; cobrar_lote usa el concepto por fila (cae al global si la fila no trae uno). Retrocompatible. 22 tests OK. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
1830 lines
110 KiB
HTML
1830 lines
110 KiB
HTML
<!DOCTYPE html>
|
||
<html lang="es">
|
||
<head>
|
||
<meta charset="UTF-8">
|
||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||
<title>Cobranza Acumulada · WK</title>
|
||
<link href="https://fonts.googleapis.com/css2?family=DM+Sans:wght@400;500;600;700&family=Space+Grotesk:wght@500;600;700&display=swap" rel="stylesheet">
|
||
<style>
|
||
* { margin: 0; padding: 0; box-sizing: border-box; -webkit-font-smoothing: antialiased; text-rendering: optimizeLegibility; }
|
||
:root {
|
||
--bg: #eef1f6;
|
||
--surface: #ffffff;
|
||
--surface-2: #f4f6fa;
|
||
--line: #e4e8ef;
|
||
--line-strong: #d4dae4;
|
||
|
||
--shadow-light: rgba(255,255,255,0.9);
|
||
--shadow-dark: rgba(20,28,46,0.10);
|
||
|
||
--text-primary: #131922;
|
||
--text-secondary: #586173;
|
||
--text-tertiary: #97a1b2;
|
||
|
||
--accent: #0e7c66;
|
||
--accent-strong: #0a6151;
|
||
--accent-soft: rgba(14,124,102,0.10);
|
||
--accent-glow: rgba(14,124,102,0.30);
|
||
|
||
--success: #15a06a;
|
||
--success-soft: rgba(21,160,106,0.12);
|
||
--wa: #1faf5a;
|
||
|
||
--danger: #d8473f;
|
||
--danger-soft: rgba(216,71,63,0.12);
|
||
--warning: #bd6b12;
|
||
--warning-soft: rgba(189,107,18,0.13);
|
||
|
||
--vr-soft: rgba(124,77,208,0.13);
|
||
--vr: #7c4dd0;
|
||
--extra-soft: rgba(176,101,12,0.15);
|
||
--extra: #aa620c;
|
||
--renta-soft: rgba(37,99,201,0.11);
|
||
--renta: #2563c9;
|
||
--otro-soft: rgba(71,85,105,0.13);
|
||
--otro: #475569;
|
||
|
||
/* legacy neumorphic tokens remapped to flat elevation */
|
||
--nm-out: 0 1px 2px rgba(18,24,38,.05), 0 8px 22px -8px rgba(18,24,38,.16);
|
||
--nm-in: inset 0 0 0 1px var(--line-strong);
|
||
--nm-subtle: 0 1px 2px rgba(18,24,38,.06), 0 0 0 1px var(--line);
|
||
--radius-card: 16px;
|
||
}
|
||
body { background: var(--bg); min-height: 100vh; font-family: 'DM Sans', sans-serif; color: var(--text-primary); padding: 1.5rem 1rem 5rem; }
|
||
.container { max-width: 600px; margin: 0 auto; }
|
||
|
||
.header { display: flex; align-items: center; gap: 13px; margin-bottom: 1.5rem; animation: fadeUp 0.6s ease both; }
|
||
.header-icon { width: 46px; height: 46px; border-radius: 13px; background: linear-gradient(150deg, var(--accent), var(--accent-strong)); color: #fff; box-shadow: 0 6px 16px -4px var(--accent-glow); display: flex; align-items: center; justify-content: center; font-family: 'Space Grotesk', sans-serif; font-weight: 700; font-size: 16px; letter-spacing: 0.5px; flex-shrink: 0; }
|
||
.header-text { min-width: 0; }
|
||
.header h1 { font-family: 'Space Grotesk', sans-serif; font-size: 19px; font-weight: 600; letter-spacing: -0.2px; line-height: 1.1; }
|
||
.header p { font-size: 12.5px; color: var(--text-secondary); margin-top: 3px; }
|
||
|
||
.tabs { display: flex; gap: 4px; background: var(--surface-2); border: 1px solid var(--line); border-radius: 12px; padding: 4px; margin-bottom: 1.4rem; animation: fadeUp 0.62s ease both; }
|
||
.tab { flex: 1; padding: 9px 8px; border: none; background: transparent; border-radius: 9px; font-size: 13px; font-weight: 600; font-family: 'DM Sans', sans-serif; color: var(--text-secondary); cursor: pointer; transition: all 0.18s ease; }
|
||
.tab:hover { color: var(--text-primary); }
|
||
.tab.active { background: var(--surface); box-shadow: 0 1px 2px rgba(18,24,38,.08), 0 0 0 1px var(--line); color: var(--accent); }
|
||
|
||
.disclaimer { display: flex; align-items: flex-start; gap: 10px; background: var(--surface); border: 1px solid var(--line); box-shadow: var(--nm-subtle); border-radius: 13px; padding: 0.85rem 1rem; margin-bottom: 1.3rem; font-size: 12.5px; color: var(--text-secondary); line-height: 1.5; }
|
||
.disclaimer strong { color: var(--accent); font-weight: 600; }
|
||
|
||
.dup-banner { display: none; align-items: center; gap: 11px; background: var(--warning-soft); border: 1px solid rgba(189,107,18,0.22); border-radius: 13px; padding: 0.8rem 1rem; margin-bottom: 1.3rem; font-size: 13px; color: var(--text-primary); }
|
||
.dup-banner.show { display: flex; }
|
||
.dup-banner .ico { font-size: 17px; }
|
||
.dup-banner .msg { flex: 1; line-height: 1.4; }
|
||
.dup-banner .msg b { color: var(--warning); font-weight: 700; }
|
||
.dup-banner button { padding: 8px 14px; border-radius: 10px; border: none; background: var(--warning); box-shadow: 0 4px 10px -3px rgba(189,107,18,.5); color: #fff; font-weight: 600; cursor: pointer; font-family: 'DM Sans', sans-serif; font-size: 12.5px; white-space: nowrap; transition: all 0.15s ease; }
|
||
.dup-banner button:active { transform: scale(0.96); }
|
||
|
||
.summary { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; margin-bottom: 1.4rem; }
|
||
.stat { background: var(--surface); border: 1px solid var(--line); border-radius: 15px; box-shadow: var(--nm-out); padding: 0.95rem 1.1rem; }
|
||
.stat-label { font-size: 10.5px; color: var(--text-tertiary); text-transform: uppercase; letter-spacing: 0.8px; font-weight: 600; }
|
||
.stat-value { font-family: 'Space Grotesk', sans-serif; font-size: 25px; font-weight: 600; margin-top: 5px; letter-spacing: -0.4px; font-variant-numeric: tabular-nums; color: var(--text-primary); }
|
||
.stat-value.accent { color: var(--accent); }
|
||
.stat-value.warning { color: var(--warning); }
|
||
|
||
/* Desglose del total por tipo de cobro */
|
||
.summary-breakdown { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; margin-bottom: 1.4rem; }
|
||
.stat.mini { padding: 0.7rem 0.85rem; border-left: 3px solid var(--line); }
|
||
.stat.mini.renta { border-left-color: var(--renta); }
|
||
.stat.mini.vr { border-left-color: var(--vr); }
|
||
.stat.mini.extra { border-left-color: var(--extra); }
|
||
.stat.mini.otro { border-left-color: var(--otro); }
|
||
.stat.mini .stat-label { display: flex; align-items: center; gap: 6px; }
|
||
.stat.mini .dot { width: 8px; height: 8px; border-radius: 50%; flex: 0 0 auto; }
|
||
.stat.mini.renta .dot { background: var(--renta); }
|
||
.stat.mini.vr .dot { background: var(--vr); }
|
||
.stat.mini.extra .dot { background: var(--extra); }
|
||
.stat.mini.otro .dot { background: var(--otro); }
|
||
.stat.mini .stat-value { font-size: 19px; margin-top: 3px; }
|
||
|
||
.section-label { font-size: 11px; font-weight: 700; color: var(--text-tertiary); text-transform: uppercase; letter-spacing: 0.9px; margin: 0 0 12px 2px; display: flex; align-items: center; gap: 7px; }
|
||
.btn-wide, .btn, .btn-save, .btn-cliente, .dup-banner button, .undo-fab, .btn-cobro, .btn-pagado, .btn-edit { display: inline-flex; align-items: center; justify-content: center; gap: 8px; }
|
||
.ic { flex: 0 0 auto; vertical-align: middle; }
|
||
.opt-num { flex: 0 0 auto; width: 20px; height: 20px; border-radius: 6px; background: var(--accent-soft); color: var(--accent); font-size: 12px; font-weight: 700; display: inline-flex; align-items: center; justify-content: center; }
|
||
|
||
.card { background: var(--surface); border: 1px solid var(--line); border-radius: var(--radius-card); box-shadow: var(--nm-out); padding: 1.15rem 1.25rem; margin-bottom: 14px; animation: fadeUp 0.5s ease both; }
|
||
.card-top { display: flex; justify-content: space-between; align-items: flex-start; margin-bottom: 0.8rem; gap: 10px; }
|
||
.card-cliente { font-size: 15px; font-weight: 700; line-height: 1.25; letter-spacing: -0.2px; }
|
||
.card-vehiculo { font-size: 12px; color: var(--text-secondary); margin-top: 2px; }
|
||
.pill-tipo { font-size: 10px; font-weight: 700; padding: 3px 9px; border-radius: 999px; text-transform: uppercase; letter-spacing: 0.4px; display: inline-block; margin-top: 7px; }
|
||
.pill-tipo.renta { background: var(--renta-soft); color: var(--renta); }
|
||
.pill-tipo.extra { background: var(--extra-soft); color: var(--extra); }
|
||
.pill-tipo.vr { background: var(--vr-soft); color: var(--vr); }
|
||
.pill-tipo.otro { background: var(--otro-soft); color: var(--otro); }
|
||
.badge-atraso { background: var(--warning-soft); color: var(--warning); border-radius: 999px; padding: 4px 11px; font-size: 11px; font-weight: 700; white-space: nowrap; flex-shrink: 0; font-variant-numeric: tabular-nums; }
|
||
|
||
.tel-row { display: flex; align-items: center; gap: 9px; background: var(--surface-2); border: 1px solid var(--line); border-radius: 10px; padding: 9px 12px; margin-bottom: 0.85rem; font-size: 12.5px; cursor: pointer; transition: all 0.15s ease; }
|
||
.tel-row:hover { border-color: var(--line-strong); }
|
||
.tel-row .tel-num { flex: 1; color: var(--text-primary); font-variant-numeric: tabular-nums; }
|
||
.tel-row.empty .tel-num { color: var(--text-tertiary); }
|
||
.tel-row .tel-edit { color: var(--accent); font-size: 11px; font-weight: 700; letter-spacing: 0.4px; }
|
||
|
||
.desglose { display: flex; flex-direction: column; gap: 7px; padding: 0.8rem 0; border-top: 1px solid var(--line); border-bottom: 1px solid var(--line); margin-bottom: 0.85rem; }
|
||
.desglose-row { display: flex; justify-content: space-between; font-size: 13px; gap: 10px; }
|
||
.desglose-row .lbl { color: var(--text-secondary); }
|
||
.desglose-row .val { font-weight: 600; font-variant-numeric: tabular-nums; }
|
||
.desglose-row.moratorio .val { color: var(--warning); }
|
||
.desglose-row.abono .val { color: var(--success); }
|
||
.mora-hint { font-size: 10px; color: var(--text-tertiary); font-weight: 400; }
|
||
|
||
/* Personalizar mensaje */
|
||
.cuenta-card { background: var(--surface); border: 1px solid var(--line); box-shadow: var(--nm-subtle); border-radius: 13px; padding: 0.95rem 1rem; margin-bottom: 12px; }
|
||
.cuenta-head { display: flex; justify-content: space-between; align-items: flex-start; margin-bottom: 10px; gap: 10px; }
|
||
.cuenta-titulo { font-size: 13px; font-weight: 700; flex: 1; line-height: 1.3; }
|
||
.cuenta-toggle { display: flex; align-items: center; gap: 8px; font-size: 11px; color: var(--text-secondary); white-space: nowrap; }
|
||
.cuenta-toggle input[type=checkbox] { width: 38px; height: 22px; appearance: none; -webkit-appearance: none; background: var(--line-strong); border-radius: 999px; position: relative; cursor: pointer; transition: background 0.2s; flex-shrink: 0; }
|
||
.cuenta-toggle input[type=checkbox]::before { content: ""; position: absolute; top: 2px; left: 2px; width: 18px; height: 18px; border-radius: 50%; background: #fff; box-shadow: 0 1px 2px rgba(0,0,0,.25); transition: all 0.2s; }
|
||
.cuenta-toggle input[type=checkbox]:checked { background: var(--accent); }
|
||
.cuenta-toggle input[type=checkbox]:checked::before { left: 18px; }
|
||
.cuenta-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 9px; }
|
||
.cuenta-grid .full { grid-column: 1 / -1; }
|
||
.cuenta-grid label { font-size: 10px; color: var(--text-tertiary); text-transform: uppercase; letter-spacing: 0.4px; display: block; margin-bottom: 4px; font-weight: 700; }
|
||
.cuenta-grid input { width: 100%; padding: 9px 11px; border-radius: 9px; background: var(--surface-2); border: 1px solid var(--line); font-size: 12.5px; color: var(--text-primary); font-family: 'DM Sans', sans-serif; outline: none; font-variant-numeric: tabular-nums; transition: all 0.15s ease; }
|
||
.cuenta-grid input:focus { border-color: var(--accent); box-shadow: 0 0 0 3px var(--accent-soft); background: #fff; }
|
||
.cuenta-actions { display: flex; justify-content: flex-end; gap: 8px; margin-top: 12px; align-items: center; }
|
||
.cuenta-actions .btn-row-del { padding: 8px 14px; }
|
||
|
||
.check-row { display: flex; align-items: center; gap: 11px; padding: 9px 2px; font-size: 13px; color: var(--text-primary); cursor: pointer; }
|
||
.check-row input[type=checkbox] { width: 20px; height: 20px; accent-color: var(--accent); cursor: pointer; }
|
||
|
||
.preview-msg { background: var(--surface-2); border: 1px solid var(--line); border-radius: 13px; padding: 1rem 1.1rem; font-size: 12.5px; color: var(--text-primary); white-space: pre-wrap; line-height: 1.6; font-family: 'DM Sans', sans-serif; }
|
||
|
||
.form-hint code { background: var(--accent-soft); color: var(--accent); padding: 1px 6px; border-radius: 5px; font-size: 11px; font-family: 'Space Grotesk', monospace; }
|
||
|
||
/* Renglones manuales */
|
||
.tag-manual { font-size: 9px; padding: 2px 7px; border-radius: 6px; font-weight: 700; letter-spacing: 0.4px; background: var(--accent-soft); color: var(--accent); vertical-align: middle; }
|
||
.btn-row-del { padding: 6px 12px; border-radius: 8px; background: transparent; border: none; cursor: pointer; color: var(--danger); font-size: 11px; font-weight: 700; letter-spacing: 0.4px; transition: all 0.15s ease; display: inline-flex; align-items: center; justify-content: center; white-space: nowrap; }
|
||
.btn-row-del:hover { background: var(--danger-soft); border-color: transparent; }
|
||
.btn-row-del:active { transform: scale(0.94); }
|
||
|
||
/* Abonos pendientes */
|
||
.pendientes-wrap { display: flex; flex-direction: column; gap: 8px; margin-bottom: 0.85rem; }
|
||
.ab-pendiente { display: flex; align-items: center; gap: 9px; background: var(--surface-2); border: 1px solid var(--line); border-radius: 11px; padding: 9px 11px; }
|
||
.ab-info { flex: 1; min-width: 0; }
|
||
.ab-monto { font-size: 13.5px; font-weight: 700; color: var(--text-primary); font-variant-numeric: tabular-nums; }
|
||
.ab-meta { font-size: 10.5px; color: var(--text-tertiary); margin-top: 2px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||
.badge-pend { font-size: 9px; padding: 3px 8px; border-radius: 6px; font-weight: 700; text-transform: uppercase; letter-spacing: 0.4px; background: var(--warning-soft); color: var(--warning); }
|
||
.ab-btn { flex: 0 0 auto; width: 32px; height: 32px; border-radius: 9px; background: var(--surface); border: 1px solid var(--line); cursor: pointer; font-size: 13px; transition: all 0.15s ease; }
|
||
.ab-btn.saldar { color: var(--success); }
|
||
.ab-btn.cancelar { color: var(--danger); }
|
||
.ab-btn:active { transform: scale(0.94); }
|
||
|
||
.progress-wrap { margin-bottom: 0.85rem; }
|
||
.progress-info { display: flex; justify-content: space-between; font-size: 12px; margin-bottom: 6px; }
|
||
.progress-info .pct { color: var(--success); font-weight: 700; font-variant-numeric: tabular-nums; }
|
||
.progress-bar { height: 7px; border-radius: 999px; background: var(--surface-2); border: 1px solid var(--line); overflow: hidden; }
|
||
.progress-fill { height: 100%; border-radius: 999px; background: linear-gradient(90deg, var(--success), #1bbd7d); transition: width 0.5s ease; }
|
||
.abonos-list { margin-top: 9px; padding-left: 2px; }
|
||
.abono-item { font-size: 11px; color: var(--text-tertiary); display: flex; justify-content: space-between; padding: 2px 0; font-variant-numeric: tabular-nums; }
|
||
|
||
.card-total { display: flex; justify-content: space-between; align-items: center; margin-bottom: 0.95rem; }
|
||
.card-total .lbl { font-size: 13px; color: var(--text-secondary); font-weight: 500; }
|
||
.card-total .val { font-family: 'Space Grotesk', sans-serif; font-size: 22px; font-weight: 600; font-variant-numeric: tabular-nums; letter-spacing: -0.3px; }
|
||
|
||
.card-actions { display: flex; gap: 9px; }
|
||
.btn { flex: 1; padding: 11px; border-radius: 11px; border: 1px solid transparent; font-size: 13px; font-weight: 600; font-family: 'DM Sans', sans-serif; cursor: pointer; transition: all 0.17s ease; display: flex; align-items: center; justify-content: center; gap: 6px; }
|
||
.btn-cobro { background: var(--accent); color: white; box-shadow: 0 6px 16px -5px var(--accent-glow); }
|
||
.btn-cobro:hover { background: var(--accent-strong); }
|
||
.btn-cobro:active { transform: scale(0.97); }
|
||
.btn-pagado { background: var(--surface); color: var(--success); border-color: var(--line); }
|
||
.btn-pagado:hover { background: var(--success-soft); border-color: transparent; }
|
||
.btn-pagado:active { transform: scale(0.97); }
|
||
.btn-edit { flex: 0 0 auto; width: auto; padding-left: 16px; padding-right: 16px; background: var(--surface); color: var(--text-secondary); border-color: var(--line); }
|
||
.btn-edit:hover { background: var(--surface-2); }
|
||
.btn-edit:active { transform: scale(0.97); }
|
||
.btn-danger-soft { background: var(--surface); color: var(--danger); border-color: var(--line); }
|
||
.btn-danger-soft:hover { background: var(--danger-soft); border-color: transparent; }
|
||
|
||
/* Modo edición inline */
|
||
.edit-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; margin-bottom: 1rem; }
|
||
.edit-field label { font-size: 10px; color: var(--text-tertiary); text-transform: uppercase; letter-spacing: 0.4px; display: block; margin-bottom: 5px; font-weight: 700; }
|
||
.edit-field input { width: 100%; padding: 10px 12px; border-radius: 10px; background: var(--surface-2); border: 1px solid var(--line); font-size: 13px; color: var(--text-primary); font-family: 'DM Sans', sans-serif; outline: none; transition: all 0.15s ease; }
|
||
.edit-field input:focus { border-color: var(--accent); box-shadow: 0 0 0 3px var(--accent-soft); background: #fff; }
|
||
.edit-field.full { grid-column: 1 / -1; }
|
||
.edit-actions { display: flex; gap: 10px; }
|
||
|
||
.footer-actions { display: flex; flex-direction: column; gap: 10px; margin-top: 1.5rem; }
|
||
.footer-actions.top { margin-top: 0; margin-bottom: 1.5rem; }
|
||
.btn-wide { width: 100%; padding: 13px; border-radius: 13px; border: 1px solid var(--line); font-size: 14px; font-weight: 600; font-family: 'DM Sans', sans-serif; cursor: pointer; transition: all 0.17s ease; display: flex; align-items: center; justify-content: center; gap: 8px; background: var(--surface); box-shadow: var(--nm-subtle); color: var(--text-primary); }
|
||
.btn-wide:hover { border-color: var(--line-strong); background: var(--surface-2); }
|
||
.btn-wide:active { transform: scale(0.99); }
|
||
.btn-wide.accent { color: var(--accent); }
|
||
.btn-wide.accent:hover { background: var(--accent-soft); border-color: transparent; }
|
||
.btn-wide.lote { color: var(--wa); }
|
||
.btn-wide.lote:hover { background: var(--success-soft); border-color: transparent; }
|
||
|
||
.undo-fab { position: fixed; bottom: 1.3rem; left: 1.3rem; z-index: 90; padding: 11px 17px; border-radius: 13px; border: 1px solid var(--line); background: var(--surface); box-shadow: 0 8px 22px -6px rgba(18,24,38,.22); color: var(--text-primary); font-family: 'DM Sans', sans-serif; font-size: 13px; font-weight: 600; cursor: pointer; display: flex; align-items: center; gap: 7px; transition: all 0.17s ease; }
|
||
.undo-fab:hover { background: var(--surface-2); }
|
||
.undo-fab:active { transform: scale(0.96); }
|
||
.undo-fab:disabled { opacity: 0.4; cursor: default; }
|
||
|
||
.tabla-wrap { overflow: auto; -webkit-overflow-scrolling: touch; max-height: 72vh; background: var(--surface); border: 1px solid var(--line); box-shadow: var(--nm-out); border-radius: 14px; }
|
||
table.tabla { width: 100%; border-collapse: separate; border-spacing: 0; background: var(--surface); font-size: 11px; }
|
||
table.tabla th { background: #eef1f6; color: var(--text-secondary); font-weight: 700; text-transform: uppercase; letter-spacing: 0.3px; padding: 11px 7px; text-align: right; font-size: 9.5px; }
|
||
table.tabla th:first-child, table.tabla td:first-child { text-align: left; padding-left: 13px; }
|
||
table.tabla td { padding: 14px 11px; text-align: right; border-top: 1px solid var(--line); background: var(--surface); font-variant-numeric: tabular-nums; }
|
||
table.tabla td.cliente { font-weight: 700; font-size: 11px; }
|
||
table.tabla td.veh { color: var(--text-secondary); font-size: 10px; font-weight: 400; }
|
||
table.tabla td.mora { color: var(--warning); }
|
||
table.tabla td.total { font-weight: 700; color: var(--accent); }
|
||
table.tabla .pill-tipo { font-size: 9px; padding: 2px 6px; }
|
||
table.tabla thead th { position: sticky; top: 0; z-index: 2; box-shadow: 0 2px 5px -3px rgba(18,24,38,.4); }
|
||
table.tabla tbody td:first-child { position: sticky; left: 0; z-index: 1; background: #ffffff; box-shadow: 3px 0 6px -4px rgba(18,24,38,.28); min-width: 150px; max-width: 220px; }
|
||
table.tabla thead th:first-child { position: sticky; left: 0; top: 0; z-index: 3; background: #e8ecf3; box-shadow: 3px 3px 6px -3px rgba(18,24,38,.35); min-width: 150px; max-width: 220px; }
|
||
|
||
.modal-overlay { display: none; position: fixed; inset: 0; background: rgba(19,25,34,0.40); backdrop-filter: blur(8px); -webkit-backdrop-filter: blur(8px); z-index: 100; align-items: center; justify-content: center; padding: 1.2rem; }
|
||
.modal-overlay.open { display: flex; animation: fadeIn 0.2s ease; }
|
||
.modal { background: var(--surface); border-radius: 20px; box-shadow: 0 24px 60px -12px rgba(15,22,38,.4); border: 1px solid var(--line); padding: 1.6rem; width: 100%; max-width: 440px; animation: slideUp 0.32s cubic-bezier(0.34,1.2,0.64,1) both; max-height: 90vh; overflow-y: auto; }
|
||
.modal.lote { max-width: 540px; }
|
||
.modal-header { display: flex; align-items: center; justify-content: space-between; margin-bottom: 1.3rem; }
|
||
.modal-title { font-family: 'Space Grotesk', sans-serif; font-size: 18px; font-weight: 600; letter-spacing: -0.2px; }
|
||
.modal-close { width: 32px; height: 32px; border-radius: 9px; background: var(--surface-2); border: 1px solid var(--line); cursor: pointer; color: var(--text-secondary); font-size: 18px; line-height: 1; transition: all 0.15s ease; }
|
||
.modal-close:hover { background: var(--danger-soft); color: var(--danger); border-color: transparent; }
|
||
|
||
/* Combobox buscable de cliente (alta de cobro personalizado) */
|
||
.cli-list { border: 1px solid var(--line); border-radius: 12px; background: var(--surface); margin-top: 8px; max-height: 260px; overflow-y: auto; -webkit-overflow-scrolling: touch; }
|
||
.cli-head { font-size: 10px; text-transform: uppercase; letter-spacing: 0.6px; color: var(--text-tertiary); font-weight: 700; padding: 9px 12px 4px; position: sticky; top: 0; background: var(--surface); }
|
||
.cli-item { padding: 9px 12px; font-size: 13.5px; cursor: pointer; display: flex; justify-content: space-between; gap: 10px; align-items: center; }
|
||
.cli-item:hover { background: var(--renta-soft); }
|
||
.cli-item .tel { color: var(--text-tertiary); font-size: 12px; white-space: nowrap; }
|
||
.cli-item.nuevo { color: var(--accent); font-weight: 600; }
|
||
.cli-empty { padding: 12px; text-align: center; color: var(--text-tertiary); font-size: 12.5px; }
|
||
|
||
.opt-card { background: var(--surface); border-radius: 13px; box-shadow: none; border: 1.5px solid var(--line); padding: 1rem 1.15rem; margin-bottom: 11px; cursor: pointer; transition: all 0.17s ease; }
|
||
.opt-card:hover { border-color: var(--accent); background: var(--accent-soft); }
|
||
.opt-card:active { transform: scale(0.99); }
|
||
.opt-title { font-size: 14px; font-weight: 700; display: flex; align-items: center; gap: 8px; }
|
||
.opt-desc { font-size: 12px; color: var(--text-secondary); margin-top: 5px; padding-left: 26px; }
|
||
.opt-monto { color: var(--accent); font-weight: 700; font-variant-numeric: tabular-nums; }
|
||
|
||
.form-group { margin-bottom: 1.1rem; }
|
||
.form-label { font-size: 11px; font-weight: 700; color: var(--text-secondary); text-transform: uppercase; letter-spacing: 0.5px; margin-bottom: 7px; display: block; }
|
||
.form-input { width: 100%; padding: 12px 14px; border-radius: 11px; background: var(--surface-2); border: 1px solid var(--line); font-size: 14px; color: var(--text-primary); font-family: 'DM Sans', sans-serif; outline: none; transition: all 0.15s ease; }
|
||
.form-input:focus { border-color: var(--accent); box-shadow: 0 0 0 3px var(--accent-soft); background: #fff; }
|
||
textarea.form-input { line-height: 1.5; resize: vertical; }
|
||
.form-hint { font-size: 11px; color: var(--text-tertiary); margin-top: 7px; line-height: 1.5; }
|
||
.btn-save { width: 100%; padding: 13px; border-radius: 12px; background: var(--accent); box-shadow: 0 8px 20px -6px var(--accent-glow); border: none; cursor: pointer; color: white; font-size: 14px; font-weight: 600; font-family: 'DM Sans', sans-serif; transition: all 0.17s ease; }
|
||
.btn-save:hover { background: var(--accent-strong); }
|
||
.btn-save:active { transform: scale(0.98); }
|
||
|
||
.link-result { background: var(--surface-2); border: 1px solid var(--line); border-radius: 12px; padding: 1rem; margin-bottom: 1rem; text-align: center; }
|
||
.link-result .check { font-size: 28px; margin-bottom: 8px; }
|
||
.link-result .ltext { font-size: 13px; color: var(--text-secondary); margin-bottom: 10px; }
|
||
.link-url { font-size: 12px; color: var(--accent); word-break: break-all; background: var(--accent-soft); padding: 8px 12px; border-radius: 9px; }
|
||
|
||
.entrega-label { font-size: 11px; font-weight: 700; color: var(--text-tertiary); text-transform: uppercase; letter-spacing: 0.9px; margin: 1rem 0 11px; text-align: center; }
|
||
.btn-cliente { width: 100%; padding: 13px; border-radius: 12px; background: var(--wa); box-shadow: 0 8px 20px -6px rgba(31,175,90,0.45); border: none; cursor: pointer; color: white; font-size: 14px; font-weight: 600; font-family: 'DM Sans', sans-serif; display: flex; align-items: center; justify-content: center; gap: 8px; margin-bottom: 14px; transition: all 0.17s ease; }
|
||
.btn-cliente:hover { filter: brightness(1.05); }
|
||
.btn-cliente:active { transform: scale(0.98); }
|
||
.reenvio-divider { text-align: center; font-size: 11px; color: var(--text-tertiary); margin-bottom: 11px; }
|
||
.reenvio-row { display: flex; gap: 10px; }
|
||
.reenvio-row select { flex: 1; padding: 12px 14px; border-radius: 11px; background: var(--surface-2); border: 1px solid var(--line); font-size: 13px; color: var(--text-primary); font-family: 'DM Sans', sans-serif; outline: none; -webkit-appearance: none; }
|
||
.reenvio-row select:focus { border-color: var(--accent); box-shadow: 0 0 0 3px var(--accent-soft); }
|
||
.btn-reenviar { flex: 0 0 auto; width: 54px; border-radius: 11px; background: var(--accent); border: none; cursor: pointer; color: #fff; font-size: 17px; transition: all 0.15s ease; }
|
||
.btn-reenviar:active { transform: scale(0.95); }
|
||
|
||
.lote-row { background: var(--surface); border: 1px solid var(--line); box-shadow: var(--nm-subtle); border-radius: 13px; padding: 0.9rem 0.95rem; margin-bottom: 11px; transition: opacity 0.2s ease, border-color 0.15s ease; }
|
||
.lote-row.off { opacity: 0.5; }
|
||
.lote-row-head { display: flex; align-items: center; gap: 11px; margin-bottom: 11px; }
|
||
.lote-check { width: 26px; height: 26px; border-radius: 8px; background: var(--surface-2); border: 1px solid var(--line-strong); cursor: pointer; color: #fff; font-size: 14px; display: flex; align-items: center; justify-content: center; flex-shrink: 0; transition: all 0.15s ease; }
|
||
.lote-check.on { background: var(--accent); border-color: var(--accent); }
|
||
.lote-cli { flex: 1; font-size: 13px; font-weight: 700; line-height: 1.3; }
|
||
.lote-veh { font-size: 10px; color: var(--text-secondary); font-weight: 400; }
|
||
.badge-sin { font-size: 9px; color: var(--danger); background: var(--danger-soft); padding: 3px 8px; border-radius: 6px; font-weight: 700; white-space: nowrap; }
|
||
.seg { display: grid; grid-template-columns: repeat(3, 1fr); gap: 6px; }
|
||
.seg-btn { padding: 8px 4px; border-radius: 9px; background: var(--surface-2); border: 1px solid var(--line); font-family: 'DM Sans', sans-serif; font-size: 10.5px; font-weight: 600; color: var(--text-secondary); cursor: pointer; line-height: 1.35; text-align: center; transition: all 0.15s ease; }
|
||
.seg-btn.active { background: var(--accent-soft); border-color: var(--accent); color: var(--accent); }
|
||
.seg-btn span { display: block; font-size: 10px; color: var(--text-tertiary); font-weight: 700; margin-top: 2px; font-variant-numeric: tabular-nums; }
|
||
.seg-btn.active span { color: var(--accent); }
|
||
.lote-personal { margin-top: 9px; }
|
||
.lote-personal input { width: 100%; padding: 9px 12px; border-radius: 10px; background: var(--surface-2); border: 1px solid var(--line); font-size: 13px; color: var(--text-primary); font-family: 'DM Sans', sans-serif; outline: none; }
|
||
.lote-personal input:focus { border-color: var(--accent); box-shadow: 0 0 0 3px var(--accent-soft); background: #fff; }
|
||
.lote-summary { display: flex; justify-content: space-between; align-items: center; font-size: 14px; margin: 1.2rem 0 1rem; padding: 0 2px; }
|
||
.lote-summary .lt { color: var(--text-secondary); }
|
||
.lote-summary .lv { font-family: 'Space Grotesk', sans-serif; font-weight: 600; color: var(--accent); font-size: 19px; font-variant-numeric: tabular-nums; }
|
||
|
||
.toast { position: fixed; bottom: 1.5rem; left: 50%; transform: translateX(-50%) translateY(90px); background: var(--text-primary); color: white; padding: 11px 22px; border-radius: 12px; font-size: 13px; font-weight: 600; box-shadow: 0 12px 28px rgba(15,22,38,0.35); transition: transform 0.35s cubic-bezier(0.34,1.56,0.64,1); z-index: 200; white-space: nowrap; max-width: 90vw; }
|
||
.toast.show { transform: translateX(-50%) translateY(0); }
|
||
|
||
.view { display: none; }
|
||
.view.active { display: block; animation: fadeUp 0.4s ease both; }
|
||
|
||
/* Directorio */
|
||
.dir-card { background: var(--surface); border: 1px solid var(--line); box-shadow: var(--nm-subtle); border-radius: 12px; padding: 0.85rem 1rem; margin-bottom: 9px; display: flex; align-items: center; gap: 11px; }
|
||
.dir-name { flex: 1; font-size: 13px; font-weight: 600; color: var(--text-primary); line-height: 1.3; word-break: break-word; }
|
||
.dir-tel { flex: 0 0 130px; padding: 9px 11px; border-radius: 9px; background: var(--surface-2); border: 1px solid var(--line); font-size: 12.5px; color: var(--text-primary); font-family: 'DM Sans', sans-serif; outline: none; font-variant-numeric: tabular-nums; transition: all 0.15s ease; }
|
||
.dir-tel:focus { border-color: var(--accent); box-shadow: 0 0 0 3px var(--accent-soft); background: #fff; }
|
||
.dir-save { flex: 0 0 auto; width: 38px; height: 38px; border-radius: 10px; background: var(--surface); border: 1px solid var(--line); cursor: pointer; color: var(--accent); font-size: 15px; transition: all 0.15s ease; }
|
||
.dir-save:hover { background: var(--accent-soft); border-color: transparent; }
|
||
.dir-save:active { transform: scale(0.94); }
|
||
.dir-save.saved { color: var(--success); background: var(--success-soft); border-color: transparent; }
|
||
.tel-fuente { font-size: 10px; padding: 2px 8px; border-radius: 6px; font-weight: 700; text-transform: uppercase; letter-spacing: 0.4px; margin-left: 6px; }
|
||
.tel-fuente.directorio { background: var(--accent-soft); color: var(--accent); }
|
||
.tel-fuente.personalizado { background: var(--warning-soft); color: var(--warning); }
|
||
|
||
/* Pantalla de Acceso expirado: oculta por default. */
|
||
.expired-screen { display: none; position: fixed; inset: 0; z-index: 300; background: var(--bg); align-items: center; justify-content: center; padding: 24px; }
|
||
.expired-card { background: var(--surface); border: 1px solid var(--line); border-radius: 22px; box-shadow: var(--nm-out); padding: 40px 32px; max-width: 380px; width: 100%; text-align: center; }
|
||
.expired-icon { width: 76px; height: 76px; border-radius: 50%; background: var(--accent-soft); display: flex; align-items: center; justify-content: center; margin: 0 auto 22px; font-size: 34px; }
|
||
.expired-card h1 { font-family: 'Space Grotesk', sans-serif; font-size: 22px; font-weight: 600; margin: 0 0 12px; color: var(--text-primary); }
|
||
.expired-card p { color: var(--text-secondary); font-size: 15px; line-height: 1.55; margin: 0; }
|
||
.expired-card strong { color: var(--accent); font-weight: 600; }
|
||
|
||
@keyframes fadeUp { from { opacity: 0; transform: translateY(16px); } to { opacity: 1; transform: translateY(0); } }
|
||
@keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } }
|
||
@keyframes slideUp { from { opacity: 0; transform: translateY(40px); } to { opacity: 1; transform: translateY(0); } }
|
||
</style>
|
||
</head>
|
||
<body>
|
||
<div class="container">
|
||
|
||
<div class="header">
|
||
<div class="header-icon">WK</div>
|
||
<div class="header-text">
|
||
<h1>Cobranza acumulada</h1>
|
||
<p id="userline">WK Cobranza</p>
|
||
</div>
|
||
</div>
|
||
|
||
<div class="tabs">
|
||
<button class="tab active" data-view="tarjetas" onclick="setView('tarjetas')">Tarjetas</button>
|
||
<button class="tab" data-view="tabla" onclick="setView('tabla')">Tabla</button>
|
||
<button class="tab" data-view="directorio" onclick="setView('directorio')">Directorio</button>
|
||
<button class="tab" data-view="mensaje" onclick="setView('mensaje')">Mensaje</button>
|
||
</div>
|
||
|
||
<div class="dup-banner" id="dup-banner">
|
||
<span class="ico"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round"><path d="M10.29 3.86 1.82 18a1 1 0 0 0 .86 1.5h16.64a1 1 0 0 0 .86-1.5L13.71 3.86a1 1 0 0 0-1.72 0z"/><path d="M12 9v4"/><path d="M12 17h.01"/></svg></span>
|
||
<span class="msg"><b id="dup-count">0</b> conceptos duplicados detectados.</span>
|
||
<button onclick="eliminarDuplicados()"><svg class="ic" width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round"><path d="M3 6h18M8 6V4a1 1 0 0 1 1-1h6a1 1 0 0 1 1 1v2m2 0v14a1 1 0 0 1-1 1H7a1 1 0 0 1-1-1V6"/></svg> Eliminar</button>
|
||
</div>
|
||
|
||
<div class="summary">
|
||
<div class="stat"><div class="stat-label">Total acumulado</div><div class="stat-value accent" id="stat-total">$0</div></div>
|
||
<div class="stat"><div class="stat-label">Interés moratorio</div><div class="stat-value warning" id="stat-mora">$0</div></div>
|
||
</div>
|
||
|
||
<div class="summary-breakdown">
|
||
<div class="stat mini renta"><div class="stat-label"><span class="dot"></span>Renta</div><div class="stat-value" id="stat-renta">$0</div></div>
|
||
<div class="stat mini vr"><div class="stat-label"><span class="dot"></span>Valor residual</div><div class="stat-value" id="stat-vr">$0</div></div>
|
||
<div class="stat mini extra"><div class="stat-label"><span class="dot"></span>Extraordinaria</div><div class="stat-value" id="stat-extra">$0</div></div>
|
||
<div class="stat mini otro"><div class="stat-label"><span class="dot"></span>Personalizados</div><div class="stat-value" id="stat-otro">$0</div></div>
|
||
</div>
|
||
|
||
<div class="view active" id="view-tarjetas">
|
||
<div class="footer-actions top">
|
||
<button class="btn-wide" onclick="abrirCrearRenglon()"><svg class="ic" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 5v14M5 12h14"/></svg> Agregar cobro personalizado</button>
|
||
<button class="btn-wide lote" onclick="abrirLote()"><svg class="ic" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round"><path d="M22 2 11 13M22 2l-7 20-4-9-9-4 20-7z"/></svg> Cobrar en lote</button>
|
||
<button class="btn-wide accent" onclick="cargarCobranza()"><svg class="ic" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4M7 10l5 5 5-5M12 15V3"/></svg> Cargar cobranza de hoy</button>
|
||
</div>
|
||
<div class="section-label" id="section-count">renglones</div>
|
||
<div id="lista"></div>
|
||
</div>
|
||
|
||
<div class="view" id="view-tabla">
|
||
<div class="section-label">Vista tabla — desliza horizontal →</div>
|
||
<button class="btn-wide" style="margin-bottom:12px" onclick="abrirCrearRenglon()"><svg class="ic" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 5v14M5 12h14"/></svg> Agregar cobro personalizado</button>
|
||
<div class="tabla-wrap"><table class="tabla" id="tabla"></table></div>
|
||
</div>
|
||
|
||
<div class="view" id="view-mensaje">
|
||
<div class="section-label"><svg class="ic" width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round"><path d="M3 21h18M4 10h16M5 6l7-3 7 3M5 10v11M19 10v11M9 14v3M15 14v3"/></svg> Cuentas para transferencia SPEI</div>
|
||
<div id="cuentas-lista"></div>
|
||
<button class="btn-wide" style="margin:0 0 22px" onclick="abrirNuevaCuenta()"><svg class="ic" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 5v14M5 12h14"/></svg> Agregar otra cuenta</button>
|
||
|
||
<div class="section-label"><svg class="ic" width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round"><rect x="2" y="4" width="20" height="16" rx="2"/><path d="m2 7 10 6 10-6"/></svg> Plantilla del mensaje</div>
|
||
<div class="form-group">
|
||
<label class="form-label">Saludo</label>
|
||
<textarea class="form-input" id="pl-saludo" rows="2" oninput="renderVistaPreviaMsg()"></textarea>
|
||
<div class="form-hint">Variables: <code>{cliente}</code> <code>{vehiculo}</code> <code>{monto}</code> <code>{concepto}</code> <code>{mes}</code></div>
|
||
</div>
|
||
<div class="form-group">
|
||
<label class="form-label">Despedida</label>
|
||
<textarea class="form-input" id="pl-despedida" rows="3" oninput="renderVistaPreviaMsg()"></textarea>
|
||
</div>
|
||
|
||
<div class="form-group">
|
||
<label class="form-label">Bloques del cuerpo</label>
|
||
<label class="check-row"><input type="checkbox" id="pl-cliente" onchange="renderVistaPreviaMsg()"> Incluir cliente</label>
|
||
<label class="check-row"><input type="checkbox" id="pl-vehiculo" onchange="renderVistaPreviaMsg()"> Incluir vehículo</label>
|
||
<label class="check-row"><input type="checkbox" id="pl-monto" onchange="renderVistaPreviaMsg()"> Incluir monto</label>
|
||
<label class="check-row"><input type="checkbox" id="pl-fecha" onchange="renderVistaPreviaMsg()"> Incluir fecha límite (hoy + 5 días)</label>
|
||
<label class="check-row"><input type="checkbox" id="pl-link" onchange="renderVistaPreviaMsg()"> Incluir link de pago (Conekta)</label>
|
||
</div>
|
||
|
||
<button class="btn-save" onclick="guardarPlantilla()">Guardar plantilla</button>
|
||
|
||
<div class="section-label" style="margin-top:24px"><svg class="ic" width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round"><path d="M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7-10-7-10-7z"/><circle cx="12" cy="12" r="3"/></svg> Vista previa</div>
|
||
<div class="preview-msg" id="preview-msg"></div>
|
||
</div>
|
||
|
||
<div class="view" id="view-directorio">
|
||
<div class="section-label">Contactos manuales</div>
|
||
<div id="manual-lista"></div>
|
||
<button class="btn-wide" style="margin:0 0 18px" onclick="abrirCrearManual()"><svg class="ic" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 5v14M5 12h14"/></svg> Agregar contacto manual</button>
|
||
|
||
<div class="section-label">Clientes del Sheet</div>
|
||
<input type="text" id="dir-buscar" class="form-input" placeholder="Buscar cliente…" oninput="renderDirectorio()" style="margin-bottom:14px">
|
||
<div id="dir-lista"></div>
|
||
</div>
|
||
|
||
</div>
|
||
|
||
<button class="undo-fab" id="undo-fab" onclick="deshacer()"><svg class="ic" width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round"><path d="M9 14 4 9l5-5"/><path d="M4 9h11a5 5 0 0 1 0 10h-1"/></svg> Deshacer</button>
|
||
|
||
<div class="modal-overlay" id="modal"><div class="modal" id="modal-inner"></div></div>
|
||
<div class="toast" id="toast"></div>
|
||
|
||
<section id="expired" class="expired-screen">
|
||
<div class="expired-card">
|
||
<div class="expired-icon"><svg width="40" height="40" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round"><rect x="5" y="11" width="14" height="10" rx="2"/><path d="M8 11V7a4 4 0 0 1 8 0v4"/></svg></div>
|
||
<h1>Link expirado</h1>
|
||
<p>Envía <strong>mi cobranza</strong> al bot de WhatsApp para obtener uno nuevo.</p>
|
||
</div>
|
||
</section>
|
||
|
||
<script>
|
||
const TOKEN = "__TOKEN__";
|
||
const API = "/admin/cobranza/api";
|
||
const CONTACTOS = ["Paulino", "Vianney", "Gustavo"];
|
||
const TIPO_LABEL = { renta: "Renta mensual", extra: "Extraordinaria", vr: "Valor residual", otro: "Otro" };
|
||
// Para tipo 'otro' mostramos la etiqueta personalizada del renglón.
|
||
function tipoLabel(r){ return r && r.tipo === "otro" ? (r.etiqueta || "Otro") : (TIPO_LABEL[(r||{}).tipo] || (r||{}).tipo); }
|
||
|
||
const fmt = n => "$" + (Number(n)||0).toLocaleString("es-MX",{minimumFractionDigits:2,maximumFractionDigits:2});
|
||
const fmtK = n => "$" + Math.round(Number(n)||0).toLocaleString("es-MX");
|
||
const fmtTel = t => t ? String(t).replace(/(\d{3})(\d{3})(\d{4})/, "$1 $2 $3") : "";
|
||
const fmtFechaEs = iso => {
|
||
if(!iso) return "";
|
||
const m = String(iso).match(/^(\d{4})-(\d{2})-(\d{2})/);
|
||
return m ? `${m[3]}/${m[2]}/${m[1]}` : iso;
|
||
};
|
||
|
||
let renglones = []; // solo activos (backend ya filtra)
|
||
let cobroState = {};
|
||
let loteState = null;
|
||
let editingId = null; // id del renglón en edición inline (o null)
|
||
let editDraft = {}; // draft de la edición inline
|
||
let directorio = []; // [{nombre, nombre_norm, telefono}] — el del Sheet enriquecido
|
||
let configGlobal = null; // {cuentas:[...], plantilla:{...}}
|
||
|
||
function showExpired(){
|
||
document.querySelectorAll(".container, .modal-overlay, .toast, .undo-fab")
|
||
.forEach(el => { el.style.display = "none"; });
|
||
document.getElementById("expired").style.display = "flex";
|
||
}
|
||
|
||
function toast(m){ const t=document.getElementById("toast"); t.textContent=m; t.classList.add("show"); setTimeout(()=>t.classList.remove("show"),2400); }
|
||
|
||
async function api(path, opts){
|
||
opts = opts || {};
|
||
const url = API + path + (path.includes("?") ? "&" : "?") + "token=" + TOKEN;
|
||
opts.headers = Object.assign({"Content-Type":"application/json"}, opts.headers||{});
|
||
const res = await fetch(url, opts);
|
||
if(res.status === 401){ showExpired(); throw new Error("expired"); }
|
||
if(!res.ok){
|
||
let detail = res.statusText;
|
||
try { const e = await res.json(); detail = e.detail || detail; } catch(_){}
|
||
throw new Error(detail);
|
||
}
|
||
return res.json();
|
||
}
|
||
|
||
async function validar(){
|
||
try {
|
||
const v = await api("/validate");
|
||
document.getElementById("userline").textContent =
|
||
"Sesión de " + (v.nombre || v.numero);
|
||
return true;
|
||
} catch(e) { return false; }
|
||
}
|
||
|
||
async function cargarRenglones(){
|
||
try { renglones = await api("/renglones"); }
|
||
catch(e){ renglones = []; }
|
||
render();
|
||
refrescarDuplicados();
|
||
}
|
||
|
||
async function cargarDirectorio(){
|
||
try {
|
||
const res = await api("/directorio");
|
||
directorio = (res && res.clientes) ? res.clientes : [];
|
||
} catch(e){ directorio = []; }
|
||
renderDirectorio();
|
||
}
|
||
|
||
function renderDirectorio(){
|
||
// Manuales: arriba, editables/eliminables.
|
||
const contManual = document.getElementById("manual-lista");
|
||
if(contManual){
|
||
const manuales = directorio.filter(c => c.origen === "manual");
|
||
if(!manuales.length){
|
||
contManual.innerHTML = `<div style="text-align:center;color:var(--text-tertiary);padding:16px;font-size:12.5px">Aún no hay contactos manuales.</div>`;
|
||
} else {
|
||
contManual.innerHTML = manuales.map(c => `
|
||
<div class="dir-card" data-id="${escapeAttr(c.id||'')}">
|
||
<div class="dir-name">${c.nombre}<div style="font-size:10px;color:var(--text-tertiary);font-weight:400">+521 ${fmtTel(c.telefono)}</div></div>
|
||
<button class="dir-save" style="color:var(--accent);width:auto;height:auto;padding:9px 14px;background:transparent;border:none;font-size:11px;font-weight:700;letter-spacing:0.4px;white-space:nowrap" onclick="abrirEditarManual('${escapeAttr(c.id||'')}')" title="Editar">EDITAR</button>
|
||
<button class="dir-save" style="color:var(--danger);width:auto;height:auto;padding:9px 14px;background:transparent;border:none;font-size:11px;font-weight:700;letter-spacing:0.4px;white-space:nowrap" onclick="eliminarManual('${escapeAttr(c.id||'')}')" title="Eliminar">BORRAR</button>
|
||
</div>`).join("");
|
||
}
|
||
}
|
||
|
||
// Sheet: lista filtrable, en el mismo formato anterior.
|
||
const cont = document.getElementById("dir-lista");
|
||
if(!cont) return;
|
||
const q = (document.getElementById("dir-buscar")?.value || "").trim().toLowerCase();
|
||
const items = directorio
|
||
.filter(c => c.origen !== "manual")
|
||
.filter(c => !q || c.nombre.toLowerCase().includes(q));
|
||
if(!items.length){
|
||
cont.innerHTML = `<div style="text-align:center;color:var(--text-tertiary);padding:24px;font-size:13px">Sin clientes que coincidan.</div>`;
|
||
return;
|
||
}
|
||
cont.innerHTML = items.map((c, i) => `
|
||
<div class="dir-card" data-norm="${escapeAttr(c.nombre_norm)}">
|
||
<div class="dir-name">${c.nombre}</div>
|
||
<input class="dir-tel" maxlength="10" inputmode="numeric" placeholder="10 dígitos"
|
||
value="${c.telefono||''}" data-norm="${escapeAttr(c.nombre_norm)}"
|
||
oninput="this.value=this.value.replace(/\\D/g,'').slice(0,10)">
|
||
<button class="dir-save" style="color:var(--renta);width:auto;height:auto;padding:9px 14px;background:transparent;border:none;font-size:11px;font-weight:700;letter-spacing:0.4px;white-space:nowrap" onclick="guardarDirectorio('${escapeAttr(c.nombre_norm)}', this)" title="Guardar">GUARDAR</button>
|
||
</div>`).join("");
|
||
}
|
||
|
||
function abrirCrearManual(){
|
||
document.getElementById("modal-inner").classList.remove("lote");
|
||
document.getElementById("modal-inner").innerHTML = `
|
||
<div class="modal-header"><span class="modal-title">Nuevo contacto manual</span><button class="modal-close" onclick="cerrar()">×</button></div>
|
||
<div class="form-group">
|
||
<label class="form-label">Nombre</label>
|
||
<input type="text" maxlength="100" class="form-input" id="cm-nombre" placeholder="Ej. Diego Corona">
|
||
</div>
|
||
<div class="form-group">
|
||
<label class="form-label">Teléfono (10 dígitos)</label>
|
||
<input type="tel" maxlength="10" inputmode="numeric" class="form-input" id="cm-tel" placeholder="2226176586"
|
||
oninput="this.value=this.value.replace(/\\D/g,'').slice(0,10)">
|
||
<div class="form-hint">Se envía a +521XXXXXXXXXX</div>
|
||
</div>
|
||
<button class="btn-save" onclick="crearManualDesdeDirectorio()">Crear</button>`;
|
||
document.getElementById("modal").classList.add("open");
|
||
setTimeout(() => document.getElementById("cm-nombre").focus(), 100);
|
||
}
|
||
async function crearManualDesdeDirectorio(){
|
||
const nombre = (document.getElementById("cm-nombre").value || "").trim();
|
||
const tel = (document.getElementById("cm-tel").value || "").replace(/\D/g,'');
|
||
if(!nombre){ toast("Falta el nombre"); return; }
|
||
if(tel.length !== 10){ toast("El teléfono debe tener 10 dígitos"); return; }
|
||
try {
|
||
await api("/contacto-manual", {method:"POST", body: JSON.stringify({nombre, telefono: tel})});
|
||
toast("Contacto manual creado");
|
||
cerrar();
|
||
await cargarDirectorio();
|
||
} catch(e){ toast("No se pudo crear: " + e.message); }
|
||
}
|
||
|
||
function abrirEditarManual(id){
|
||
const c = directorio.find(x => x.origen === "manual" && x.id === id);
|
||
if(!c) return;
|
||
document.getElementById("modal-inner").classList.remove("lote");
|
||
document.getElementById("modal-inner").innerHTML = `
|
||
<div class="modal-header"><span class="modal-title">Editar contacto manual</span><button class="modal-close" onclick="cerrar()">×</button></div>
|
||
<div class="form-group">
|
||
<label class="form-label">Nombre</label>
|
||
<input type="text" maxlength="100" class="form-input" id="cm-nombre" value="${escapeAttr(c.nombre)}">
|
||
</div>
|
||
<div class="form-group">
|
||
<label class="form-label">Teléfono (10 dígitos)</label>
|
||
<input type="tel" maxlength="10" inputmode="numeric" class="form-input" id="cm-tel" value="${escapeAttr(c.telefono||'')}"
|
||
oninput="this.value=this.value.replace(/\\D/g,'').slice(0,10)">
|
||
</div>
|
||
<button class="btn-save" onclick="guardarEditarManual('${escapeAttr(id)}')">Guardar</button>`;
|
||
document.getElementById("modal").classList.add("open");
|
||
setTimeout(() => document.getElementById("cm-nombre").focus(), 100);
|
||
}
|
||
async function guardarEditarManual(id){
|
||
const nombre = (document.getElementById("cm-nombre").value || "").trim();
|
||
const tel = (document.getElementById("cm-tel").value || "").replace(/\D/g,'');
|
||
if(!nombre){ toast("Falta el nombre"); return; }
|
||
if(tel.length !== 10){ toast("El teléfono debe tener 10 dígitos"); return; }
|
||
try {
|
||
await api("/contacto-manual", {method:"PUT", body: JSON.stringify({id, nombre, telefono: tel})});
|
||
toast("Contacto actualizado");
|
||
cerrar();
|
||
await cargarDirectorio();
|
||
await cargarRenglones();
|
||
} catch(e){ toast("No se pudo actualizar: " + e.message); }
|
||
}
|
||
async function eliminarManual(id){
|
||
if(!confirm("¿Eliminar este contacto manual?")) return;
|
||
try {
|
||
await api("/contacto-manual", {method:"DELETE", body: JSON.stringify({id})});
|
||
toast("Contacto eliminado");
|
||
await cargarDirectorio();
|
||
await cargarRenglones();
|
||
} catch(e){ toast("No se pudo eliminar: " + e.message); }
|
||
}
|
||
|
||
async function guardarDirectorio(nombreNorm, btnEl){
|
||
const card = btnEl.closest(".dir-card");
|
||
const input = card.querySelector(".dir-tel");
|
||
const tel = (input.value||"").replace(/\D/g,'');
|
||
if(tel && tel.length !== 10){ toast("Deben ser 10 dígitos (o vacío para borrar)"); return; }
|
||
try {
|
||
await api("/directorio", {method:"POST", body: JSON.stringify({nombre_norm: nombreNorm, telefono: tel})});
|
||
// Actualiza el estado local en memoria sin recargar la lista.
|
||
const item = directorio.find(c => c.nombre_norm === nombreNorm);
|
||
if(item) item.telefono = tel;
|
||
btnEl.classList.add("saved");
|
||
setTimeout(() => btnEl.classList.remove("saved"), 900);
|
||
toast(tel ? "Guardado en directorio" : "Eliminado del directorio");
|
||
// Las tarjetas pueden mostrar el nuevo teléfono sugerido; recargamos en background.
|
||
cargarRenglones();
|
||
} catch(e){ toast("No se pudo guardar: " + e.message); }
|
||
}
|
||
|
||
async function refrescarDuplicados(){
|
||
try {
|
||
const grupos = await api("/duplicados");
|
||
const banner = document.getElementById("dup-banner");
|
||
if(grupos && grupos.length){
|
||
// Total de renglones que se podrían eliminar (n-1 por grupo).
|
||
const total = grupos.reduce((s,g) => s + (g.renglones.length - 1), 0);
|
||
document.getElementById("dup-count").textContent = total;
|
||
banner.classList.add("show");
|
||
} else {
|
||
banner.classList.remove("show");
|
||
}
|
||
} catch(e){ /* sin banner */ }
|
||
}
|
||
|
||
function render(){ renderTarjetas(); renderTabla(); renderStats(); }
|
||
function renderStats(){
|
||
let total=0, mora=0;
|
||
// Desglose del total (saldo pendiente) por tipo de cobro.
|
||
const porTipo = { renta:0, vr:0, extra:0, otro:0 };
|
||
renglones.forEach(r => {
|
||
const saldo = Number(r.saldo)||0;
|
||
total += saldo;
|
||
mora += Number(r.moratorio)||0;
|
||
const tipo = (r.tipo in porTipo) ? r.tipo : "otro"; // tipos desconocidos → Otros
|
||
porTipo[tipo] += saldo;
|
||
});
|
||
document.getElementById("stat-total").textContent = fmtK(total);
|
||
document.getElementById("stat-mora").textContent = fmtK(mora);
|
||
document.getElementById("stat-renta").textContent = fmtK(porTipo.renta);
|
||
document.getElementById("stat-vr").textContent = fmtK(porTipo.vr);
|
||
document.getElementById("stat-extra").textContent = fmtK(porTipo.extra);
|
||
document.getElementById("stat-otro").textContent = fmtK(porTipo.otro);
|
||
}
|
||
|
||
function renderTarjetas(){
|
||
const lista = document.getElementById("lista");
|
||
lista.innerHTML = "";
|
||
let n = renglones.length;
|
||
renglones.forEach((r,i) => {
|
||
const card = document.createElement("div");
|
||
card.className = "card";
|
||
card.style.animationDelay = (i*0.04) + "s";
|
||
if(editingId === r.id){
|
||
card.innerHTML = renderEditInline(r);
|
||
} else {
|
||
card.innerHTML = renderCardNormal(r);
|
||
}
|
||
lista.appendChild(card);
|
||
});
|
||
document.getElementById("section-count").textContent =
|
||
n + (n === 1 ? " renglón activo" : " renglones activos");
|
||
}
|
||
|
||
function renderCardNormal(r){
|
||
const abon = Number(r.abonado)||0;
|
||
const saldo = Number(r.saldo)||0;
|
||
const bruto = (Number(r.capital)||0) + (Number(r.moratorio)||0);
|
||
const pct = bruto > 0 ? Math.min(100, Math.round(abon / bruto * 100)) : 0;
|
||
const telEf = r.telefono_efectivo || "";
|
||
const fuente = r.telefono_fuente || "ninguno";
|
||
let tel;
|
||
if(telEf){
|
||
// Nombre opcional asociado al override (solo cuando la fuente es
|
||
// "personalizado" y el renglón tiene telefono_nombre).
|
||
const nombreOverride = (fuente === "personalizado" && r.telefono_nombre)
|
||
? ` · ${r.telefono_nombre}` : "";
|
||
const badge = (fuente === "personalizado")
|
||
? `<span class="tel-fuente personalizado">personalizado</span>`
|
||
: `<span class="tel-fuente directorio">del directorio</span>`;
|
||
tel = `<div class="tel-row" onclick="editarTel('${r.id}')"><span class="tel-ico"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><rect x="6" y="2" width="12" height="20" rx="2"/><path d="M11 18h2"/></svg></span><span class="tel-num">+521 ${fmtTel(telEf)}${nombreOverride}${badge}</span><span class="tel-edit">EDITAR</span></div>`;
|
||
} else {
|
||
tel = `<div class="tel-row empty" onclick="editarTel('${r.id}')"><span class="tel-ico"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><rect x="6" y="2" width="12" height="20" rx="2"/><path d="M11 18h2"/></svg></span><span class="tel-num">Agregar número de cliente</span><span class="tel-edit">+</span></div>`;
|
||
}
|
||
const conceptoLbl = tipoLabel(r) || "Concepto";
|
||
const abonosArr = (r.abonos || []);
|
||
const pendientes = abonosArr.filter(a => (a.estado || "pagado") === "pendiente");
|
||
const pagados = abonosArr.filter(a => (a.estado || "pagado") === "pagado");
|
||
const sumPendientes = Number(r.abonado_pendiente) || pendientes.reduce((s,a)=>s+(Number(a.monto)||0),0);
|
||
let des = "";
|
||
des += `<div class="desglose-row"><span class="lbl">${conceptoLbl}</span><span class="val">${fmt(r.monto)}</span></div>`;
|
||
des += `<div class="desglose-row moratorio"><span class="lbl">Interés moratorio <span class="mora-hint">(${r.tasa_mensual}%/mes · ${r.dias_retraso}d)</span></span><span class="val">+${fmt(r.moratorio)}</span></div>`;
|
||
if(abon > 0){
|
||
des += `<div class="desglose-row abono"><span class="lbl">Abonos pagados</span><span class="val">−${fmt(abon)}</span></div>`;
|
||
}
|
||
if(sumPendientes > 0){
|
||
des += `<div class="desglose-row" style="color:var(--text-tertiary)"><span class="lbl">Abonos pendientes</span><span class="val">${fmt(sumPendientes)}</span></div>`;
|
||
}
|
||
|
||
// Lista de abonos pendientes con botón Saldar y Cancelar.
|
||
let pendientesHTML = "";
|
||
if(pendientes.length){
|
||
pendientesHTML = `<div class="pendientes-wrap">` + pendientes.map(a => `
|
||
<div class="ab-pendiente">
|
||
<div class="ab-info">
|
||
<div class="ab-monto">${fmt(a.monto)}</div>
|
||
<div class="ab-meta"><svg class="ic" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" style="vertical-align:-1px;margin-right:3px"><rect x="3" y="4" width="18" height="18" rx="2"/><path d="M16 2v4M8 2v4M3 10h18"/></svg>${fmtFechaEs(a.fecha) || a.fecha || ""}${a.concepto ? " · " + a.concepto : ""}</div>
|
||
</div>
|
||
<span class="badge-pend">pendiente</span>
|
||
<button class="ab-btn saldar" onclick="saldarAbono('${r.id}','${a.id}')" title="Saldar">✓</button>
|
||
<button class="ab-btn cancelar" onclick="cancelarAbono('${r.id}','${a.id}')" title="Cancelar">✕</button>
|
||
</div>`).join("") + `</div>`;
|
||
}
|
||
|
||
// Barra de progreso: solo si HAY abonos pagados.
|
||
let prog = "";
|
||
if(abon > 0){
|
||
const items = pagados.map(a => `<div class="abono-item"><span>${fmtFechaEs(a.fecha_pago || a.fecha) || a.fecha || ""}</span><span>${fmt(a.monto)}</span></div>`).join("");
|
||
prog = `<div class="progress-wrap">
|
||
<div class="progress-info"><span style="color:var(--text-secondary)">Abonado ${fmt(abon)}</span><span class="pct">${pct}%</span></div>
|
||
<div class="progress-bar"><div class="progress-fill" style="width:${pct}%"></div></div>
|
||
<div class="abonos-list">${items}</div>
|
||
</div>`;
|
||
}
|
||
let venceLinea = "";
|
||
if((r.tipo === "vr" || r.tipo === "extra") && r.fecha_vencimiento){
|
||
venceLinea = `<div style="font-size:11.5px;color:var(--text-secondary);margin-top:5px"><svg class="ic" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" style="vertical-align:-1px;margin-right:3px"><rect x="3" y="4" width="18" height="18" rx="2"/><path d="M16 2v4M8 2v4M3 10h18"/></svg>Vence: ${fmtFechaEs(r.fecha_vencimiento)}</div>`;
|
||
} else if(r.tipo === "renta" && r.dia_pago){
|
||
venceLinea = `<div style="font-size:11.5px;color:var(--text-secondary);margin-top:5px"><svg class="ic" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" style="vertical-align:-1px;margin-right:3px"><rect x="3" y="4" width="18" height="18" rx="2"/><path d="M16 2v4M8 2v4M3 10h18"/></svg>Día de pago: ${r.dia_pago} de cada mes</div>`;
|
||
}
|
||
return `
|
||
<div class="card-top">
|
||
<div>
|
||
<div class="card-cliente">${r.cliente}${r.origen === "manual" ? ' <span class="tag-manual">MANUAL</span>' : ''}</div>
|
||
<div class="card-vehiculo">${r.vehiculo}</div>
|
||
<div class="pill-tipo ${r.tipo}">${conceptoLbl}</div>
|
||
${venceLinea}
|
||
</div>
|
||
<div class="badge-atraso">${r.dias_retraso} días</div>
|
||
</div>
|
||
${tel}
|
||
<div class="desglose">${des}</div>
|
||
${pendientesHTML}
|
||
${prog}
|
||
<div class="card-total"><span class="lbl">Saldo pendiente</span><span class="val">${fmt(saldo)}</span></div>
|
||
<div class="card-actions">
|
||
<button class="btn btn-cobro" onclick="abrirCobro('${r.id}')"><svg class="ic" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round"><rect x="2" y="5" width="20" height="14" rx="2"/><path d="M2 10h20"/></svg> Generar cobro</button>
|
||
<button class="btn btn-pagado" onclick="marcarPagado('${r.id}')">✓ Saldar</button>
|
||
<button class="btn btn-edit" onclick="entrarEdicion('${r.id}')">Editar</button>
|
||
</div>`;
|
||
}
|
||
|
||
function renderEditInline(r){
|
||
// Pre-llenamos el draft si es la primera vez.
|
||
if(!editDraft || editDraft.id !== r.id){
|
||
editDraft = {
|
||
id: r.id,
|
||
cliente: r.cliente || "",
|
||
vehiculo: r.vehiculo || "",
|
||
monto: Number(r.monto)||0,
|
||
tasa_mensual: Number(r.tasa_mensual)||0,
|
||
telefono: r.telefono || "",
|
||
fecha_alta: r.fecha_alta || "",
|
||
};
|
||
}
|
||
const conceptoLbl = tipoLabel(r) || "Concepto";
|
||
return `
|
||
<div class="card-top">
|
||
<div>
|
||
<div class="card-cliente">Editar renglón</div>
|
||
<div class="card-vehiculo">${r.cliente} · ${r.vehiculo}</div>
|
||
<div class="pill-tipo ${r.tipo}">${conceptoLbl}</div>
|
||
</div>
|
||
</div>
|
||
<div class="edit-grid">
|
||
<div class="edit-field full"><label>Cliente</label><input value="${escapeAttr(editDraft.cliente)}" oninput="editDraft.cliente=this.value"></div>
|
||
<div class="edit-field full"><label>Vehículo</label><input value="${escapeAttr(editDraft.vehiculo)}" oninput="editDraft.vehiculo=this.value"></div>
|
||
<div class="edit-field"><label>Monto del concepto</label><input type="number" step="0.01" value="${editDraft.monto}" oninput="editDraft.monto=+this.value"></div>
|
||
<div class="edit-field"><label>Tasa moratoria %/mes</label><input type="number" step="0.1" value="${editDraft.tasa_mensual}" oninput="editDraft.tasa_mensual=+this.value"></div>
|
||
<div class="edit-field"><label>Fecha de alta</label><input type="date" value="${editDraft.fecha_alta}" oninput="editDraft.fecha_alta=this.value"></div>
|
||
<div class="edit-field"><label>Teléfono (10 díg.)</label><input value="${escapeAttr(editDraft.telefono)}" maxlength="10" inputmode="numeric" oninput="editDraft.telefono=this.value.replace(/\\D/g,'').slice(0,10)"></div>
|
||
</div>
|
||
<div class="edit-actions">
|
||
<button class="btn btn-cobro" style="background:var(--renta);box-shadow:0 6px 16px -5px rgba(37,99,201,0.4)" onclick="guardarEdicion()">Guardar</button>
|
||
<button class="btn btn-pagado" onclick="cancelarEdicion()">Cancelar</button>
|
||
<button class="btn btn-danger-soft" onclick="eliminarEditado()" title="Eliminar renglón">BORRAR</button>
|
||
</div>`;
|
||
}
|
||
|
||
function escapeAttr(s){ return String(s||"").replace(/"/g,'"').replace(/</g,'<'); }
|
||
|
||
function entrarEdicion(id){
|
||
editingId = id;
|
||
editDraft = {}; // se reconstruye en renderEditInline
|
||
renderTarjetas();
|
||
}
|
||
function cancelarEdicion(){
|
||
editingId = null;
|
||
editDraft = {};
|
||
renderTarjetas();
|
||
}
|
||
async function guardarEdicion(){
|
||
if(!editDraft.id) return;
|
||
const body = {
|
||
id: editDraft.id,
|
||
cliente: editDraft.cliente,
|
||
vehiculo: editDraft.vehiculo,
|
||
monto: Number(editDraft.monto)||0,
|
||
tasa_mensual: Number(editDraft.tasa_mensual)||0,
|
||
telefono: (editDraft.telefono||"").replace(/\D/g,''),
|
||
fecha_alta: editDraft.fecha_alta || null,
|
||
};
|
||
// Validación mínima: teléfono 10 dígitos o vacío.
|
||
if(body.telefono && body.telefono.length !== 10){
|
||
toast("El teléfono debe tener 10 dígitos"); return;
|
||
}
|
||
try {
|
||
await api("/renglon", {method:"PUT", body: JSON.stringify(body)});
|
||
editingId = null; editDraft = {};
|
||
await cargarRenglones();
|
||
toast("Guardado");
|
||
} catch(e){ toast("No se pudo guardar: " + e.message); }
|
||
}
|
||
async function eliminarEditado(){
|
||
if(!editDraft.id) return;
|
||
if(!confirm("¿Eliminar este renglón?")) return;
|
||
try {
|
||
await api("/renglon", {method:"DELETE", body: JSON.stringify({id: editDraft.id})});
|
||
editingId = null; editDraft = {};
|
||
await cargarRenglones();
|
||
toast("Eliminado");
|
||
} catch(e){ toast("No se pudo eliminar"); }
|
||
}
|
||
|
||
function renderTabla(){
|
||
const t = document.getElementById("tabla");
|
||
const head = `<tr><th>Cliente</th><th>Tipo</th><th>Día de pago</th><th>Monto</th><th>Días</th><th>Mora</th><th>Abonos</th><th>Saldo</th><th></th></tr>`;
|
||
const rows = renglones.map(r => {
|
||
const diaCol = (r.tipo === "renta")
|
||
? (r.dia_pago ? `${r.dia_pago} de cada mes` : "—")
|
||
: (r.fecha_vencimiento ? fmtFechaEs(r.fecha_vencimiento) : "—");
|
||
const origenTag = r.origen === "manual"
|
||
? ` <span class="tag-manual">M</span>` : "";
|
||
return `
|
||
<tr>
|
||
<td class="cliente">${r.cliente}${origenTag}<div class="veh">${r.vehiculo}</div></td>
|
||
<td><span class="pill-tipo ${r.tipo}">${tipoLabel(r)}</span></td>
|
||
<td>${diaCol}</td>
|
||
<td>${fmtK(r.monto)}</td>
|
||
<td>${r.dias_retraso||0}</td>
|
||
<td class="mora">${fmtK(r.moratorio)}</td>
|
||
<td style="color:var(--success)">${(Number(r.abonado)||0) > 0 ? fmtK(r.abonado) : "—"}</td>
|
||
<td class="total">${fmtK(r.saldo)}</td>
|
||
<td><button class="btn-row-del" onclick="eliminarRenglon('${r.id}', '${escapeAttr(r.cliente)}')" title="Eliminar">BORRAR</button></td>
|
||
</tr>`;
|
||
}).join("");
|
||
// Envolvemos en thead/tbody para que el sticky sea consistente entre browsers.
|
||
t.innerHTML = `<thead>${head}</thead><tbody>${rows}</tbody>`;
|
||
}
|
||
|
||
// ── Teléfono (modal: override + selector del directorio) ──────
|
||
function editarTel(id){
|
||
const r = renglones.find(x => x.id === id);
|
||
if(!r) return;
|
||
document.getElementById("modal-inner").classList.remove("lote");
|
||
const dirTel = r.telefono_directorio || "";
|
||
const override = r.telefono || "";
|
||
const yaSugerido = dirTel
|
||
? `<div style="font-size:12px;color:var(--text-secondary);margin-bottom:8px;"><svg class="ic" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" style="vertical-align:-2px;margin-right:4px"><path d="M4 19.5A2.5 2.5 0 0 1 6.5 17H20"/><path d="M6.5 2H20v20H6.5A2.5 2.5 0 0 1 4 19.5v-15A2.5 2.5 0 0 1 6.5 2z"/></svg>En el directorio: <strong>+521 ${fmtTel(dirTel)}</strong></div>`
|
||
: `<div style="font-size:12px;color:var(--text-tertiary);margin-bottom:8px;">Este cliente aún no tiene número en el directorio.</div>`;
|
||
// Dropdown agrupado: contactos del Sheet, contactos manuales, opción
|
||
// de "Agregar contacto nuevo…" siempre al final.
|
||
// `data-nombre` permite que el handler de "Usar este contacto" herede
|
||
// automáticamente el nombre del contacto al guardar el override.
|
||
const sheetOpts = directorio
|
||
.filter(c => c.telefono && c.origen !== "manual")
|
||
.map(c => `<option value="${c.telefono}" data-nombre="${escapeAttr(c.nombre)}">${c.nombre} — +521 ${fmtTel(c.telefono)}</option>`)
|
||
.join("");
|
||
const manualOpts = directorio
|
||
.filter(c => c.telefono && c.origen === "manual")
|
||
.map(c => `<option value="${c.telefono}" data-nombre="${escapeAttr(c.nombre)}">${c.nombre} — +521 ${fmtTel(c.telefono)}</option>`)
|
||
.join("");
|
||
let selectorHTML = `<option value="">— elegir contacto —</option>`;
|
||
if(sheetOpts) selectorHTML += `<optgroup label="Clientes del Sheet">${sheetOpts}</optgroup>`;
|
||
if(manualOpts) selectorHTML += `<optgroup label="Contactos manuales">${manualOpts}</optgroup>`;
|
||
selectorHTML += `<option value="__nuevo__">+ Agregar contacto nuevo…</option>`;
|
||
|
||
document.getElementById("modal-inner").innerHTML = `
|
||
<div class="modal-header"><span class="modal-title">Número de cobro</span><button class="modal-close" onclick="cerrar()">×</button></div>
|
||
<p style="font-size:13px;color:var(--text-secondary);margin-bottom:0.5rem;">${r.cliente}<br>${r.vehiculo}</p>
|
||
${yaSugerido}
|
||
<div class="form-group">
|
||
<label class="form-label">Vía 1 — Número personalizado para este renglón</label>
|
||
<input type="tel" maxlength="10" class="form-input" id="inp-tel" value="${override}" placeholder="222 617 6586" inputmode="numeric"
|
||
oninput="this.value=this.value.replace(/\\D/g,'').slice(0,10)">
|
||
<input type="text" maxlength="100" class="form-input" id="inp-nombre" value="${escapeAttr(r.telefono_nombre || '')}" placeholder="Nombre (opcional)" style="margin-top:8px">
|
||
<div class="form-hint">Override local. El nombre es opcional; se muestra junto al número en la tarjeta.</div>
|
||
<button class="btn-save" style="margin-top:10px" onclick="guardarTel('${id}')">Guardar personalizado</button>
|
||
</div>
|
||
<div class="form-group">
|
||
<label class="form-label">Vía 2 — Tomar del directorio (incluye contactos manuales)</label>
|
||
<select class="form-input" id="inp-dir" onchange="onSelectorContacto(this)">
|
||
${selectorHTML}
|
||
</select>
|
||
<div class="form-hint" id="hint-selector" style="display:none"></div>
|
||
<button id="btn-usar-contacto" class="btn btn-cobro" style="display:none;width:100%;margin-top:10px;padding:11px"
|
||
data-dir-tel="${escapeAttr(dirTel)}"
|
||
onclick="usarContactoSeleccionado('${id}', '${dirTel}')">Usar este contacto</button>
|
||
</div>
|
||
<div class="form-group" id="nuevo-contacto-wrap" style="display:none">
|
||
<label class="form-label">Nuevo contacto manual</label>
|
||
<input type="text" maxlength="100" class="form-input" id="inp-nuevo-nombre" placeholder="Nombre del contacto" style="margin-bottom:8px">
|
||
<input type="tel" maxlength="10" inputmode="numeric" class="form-input" id="inp-nuevo-tel" placeholder="Teléfono (10 díg.)"
|
||
oninput="this.value=this.value.replace(/\\D/g,'').slice(0,10)">
|
||
<button class="btn btn-cobro" style="width:100%;margin-top:10px;padding:11px" onclick="crearContactoNuevoYUsar('${id}')">Guardar y usar para este cobro</button>
|
||
<div class="form-hint" style="margin-top:6px">El contacto queda disponible en el dropdown para futuras tarjetas.</div>
|
||
</div>
|
||
${override ? `<button class="btn btn-pagado" style="width:100%;margin-top:10px;padding:12px" onclick="quitarOverride('${id}')">Quitar personalizado y usar directorio</button>` : ``}
|
||
`;
|
||
document.getElementById("modal").classList.add("open");
|
||
setTimeout(() => document.getElementById("inp-tel").focus(), 100);
|
||
}
|
||
|
||
function onSelectorContacto(sel){
|
||
const wrap = document.getElementById("nuevo-contacto-wrap");
|
||
const btn = document.getElementById("btn-usar-contacto");
|
||
const hint = document.getElementById("hint-selector");
|
||
// Reset visual común.
|
||
if(btn) btn.style.display = "none";
|
||
if(hint){ hint.style.display = "none"; hint.textContent = ""; }
|
||
if(wrap) wrap.style.display = "none";
|
||
|
||
if(sel.value === "__nuevo__"){
|
||
if(wrap) wrap.style.display = "block";
|
||
sel.value = ""; // resetea el select; el form de abajo toma el relevo
|
||
setTimeout(() => document.getElementById("inp-nuevo-nombre").focus(), 50);
|
||
return;
|
||
}
|
||
if(!sel.value) return;
|
||
|
||
// IMPORTANTE: NO escribimos en inp-tel. El dropdown es una vía aparte.
|
||
// Decidimos qué pasará al pulsar "Usar este contacto" comparando con el
|
||
// teléfono del directorio del cliente del renglón actual (data-dir-tel).
|
||
const dirTelBtn = btn ? (btn.getAttribute("data-dir-tel") || "") : "";
|
||
const elegido = sel.value;
|
||
if(btn) btn.style.display = "block";
|
||
if(hint){
|
||
hint.style.display = "block";
|
||
if(dirTelBtn && elegido === dirTelBtn){
|
||
hint.textContent = "Coincide con el del directorio. Al usarlo, se quitará el override y la tarjeta quedará como “del directorio”.";
|
||
} else {
|
||
hint.textContent = "Distinto al del directorio del cliente. Quedará como “personalizado”.";
|
||
}
|
||
}
|
||
}
|
||
|
||
async function usarContactoSeleccionado(idRenglon, telefonoDirectorio){
|
||
const sel = document.getElementById("inp-dir");
|
||
const elegido = (sel && sel.value) ? sel.value : "";
|
||
if(!elegido){ toast("Selecciona un contacto del dropdown"); return; }
|
||
// Hereda el nombre del contacto desde el option (data-nombre) para el
|
||
// Caso B (override) — en Caso A se limpia tanto número como nombre.
|
||
const opt = sel.options[sel.selectedIndex];
|
||
const nombreContacto = opt ? (opt.getAttribute("data-nombre") || "") : "";
|
||
// Caso A: coincide con el del directorio del cliente → limpiar override.
|
||
// Caso B: otro contacto → override con nombre heredado.
|
||
const limpiar = telefonoDirectorio && elegido === telefonoDirectorio;
|
||
try {
|
||
await api("/telefono", {method:"POST", body: JSON.stringify({
|
||
id: idRenglon,
|
||
telefono: limpiar ? "" : elegido,
|
||
nombre: limpiar ? "" : nombreContacto,
|
||
})});
|
||
toast(limpiar ? "Usando el del directorio" : "Contacto asignado (personalizado)");
|
||
cerrar(); await cargarRenglones();
|
||
} catch(e){ toast("No se pudo asignar: " + e.message); }
|
||
}
|
||
|
||
async function crearContactoNuevoYUsar(idRenglon){
|
||
const nombre = (document.getElementById("inp-nuevo-nombre").value || "").trim();
|
||
const tel = (document.getElementById("inp-nuevo-tel").value || "").replace(/\D/g,'');
|
||
if(!nombre){ toast("Falta el nombre"); return; }
|
||
if(tel.length !== 10){ toast("El teléfono debe tener 10 dígitos"); return; }
|
||
try {
|
||
// 1) Crea el contacto manual en el directorio.
|
||
await api("/contacto-manual", {method:"POST", body: JSON.stringify({nombre, telefono: tel})});
|
||
// 2) Registra el teléfono en el índice del directorio (por nombre) para que
|
||
// se resuelva por nombre en futuras tarjetas/renglones del mismo contacto.
|
||
try {
|
||
await api("/directorio", {method:"POST", body: JSON.stringify({nombre_norm: normNombre(nombre), telefono: tel})});
|
||
} catch(e){ /* el contacto manual ya quedó creado; el índice es complementario */ }
|
||
// 3) Refresca el directorio en memoria (para que aparezca en próximos selectores).
|
||
await cargarDirectorio();
|
||
// 4) Lo asigna como override del renglón con nombre heredado del contacto manual.
|
||
await api("/telefono", {method:"POST", body: JSON.stringify({id: idRenglon, telefono: tel, nombre})});
|
||
toast("Contacto creado y asignado a este cobro");
|
||
cerrar();
|
||
await cargarRenglones();
|
||
} catch(e){ toast("No se pudo crear: " + e.message); }
|
||
}
|
||
async function guardarTel(id){
|
||
const v = document.getElementById("inp-tel").value.replace(/\D/g,'');
|
||
if(v && v.length !== 10){ toast("Deben ser 10 dígitos"); return; }
|
||
const nombreEl = document.getElementById("inp-nombre");
|
||
const nombre = (nombreEl ? nombreEl.value : "").trim();
|
||
const r = renglones.find(x => x.id === id);
|
||
try {
|
||
await api("/telefono", {method:"POST", body: JSON.stringify({id, telefono:v, nombre})});
|
||
// Además del override del renglón, el número se guarda en el directorio
|
||
// bajo el nombre del cliente para que quede reutilizable. (Best-effort:
|
||
// si falla, el override ya quedó guardado.)
|
||
if(v && r && r.cliente){
|
||
try {
|
||
await api("/directorio", {method:"POST", body: JSON.stringify({nombre_norm: normNombre(r.cliente), telefono: v})});
|
||
} catch(e){ /* el override ya se guardó; el directorio es complementario */ }
|
||
}
|
||
toast(v ? "Número guardado (renglón y directorio)" : "Override eliminado");
|
||
cerrar(); await cargarDirectorio(); await cargarRenglones();
|
||
} catch(e){ toast("No se pudo guardar"); }
|
||
}
|
||
async function quitarOverride(id){
|
||
try {
|
||
await api("/telefono", {method:"POST", body: JSON.stringify({id, telefono:""})});
|
||
toast("Override eliminado");
|
||
cerrar(); await cargarRenglones();
|
||
} catch(e){ toast("No se pudo eliminar"); }
|
||
}
|
||
|
||
// ── Generar cobro ────────────────────────────────────────────
|
||
function abrirCobro(id){
|
||
const r = renglones.find(x => x.id === id);
|
||
if(!r) return;
|
||
cobroState = {renglon:r};
|
||
document.getElementById("modal-inner").classList.remove("lote");
|
||
const saldo = Number(r.saldo)||0;
|
||
const capital_neto = (Number(r.capital)||0) - (Number(r.abonado)||0);
|
||
document.getElementById("modal-inner").innerHTML = `
|
||
<div class="modal-header"><span class="modal-title">Generar cobro</span><button class="modal-close" onclick="cerrar()">×</button></div>
|
||
<p style="font-size:13px;color:var(--text-secondary);margin-bottom:1.2rem;">Cliente: <strong style="color:var(--text-primary)">${r.cliente}</strong><br>${r.vehiculo}<br><span class="pill-tipo ${r.tipo}">${tipoLabel(r)}</span></p>
|
||
<div class="opt-card" onclick="cobroConfirmar('saldo', ${saldo})"><div class="opt-title"><span class="opt-num">1</span> Replicar saldo acumulado</div><div class="opt-desc">Total con intereses: <span class="opt-monto">${fmt(saldo)}</span></div></div>
|
||
<div class="opt-card" onclick="cobroConfirmar('sinmora', ${capital_neto})"><div class="opt-title"><span class="opt-num">2</span> Sin intereses moratorios</div><div class="opt-desc">Solo capital: <span class="opt-monto">${fmt(capital_neto)}</span></div></div>
|
||
<div class="opt-card" onclick="cobroPersonalForm()"><div class="opt-title"><span class="opt-num">3</span> Monto personalizado / abono</div><div class="opt-desc">Define monto y concepto</div></div>`;
|
||
document.getElementById("modal").classList.add("open");
|
||
}
|
||
// ── Flujo UNIFICADO de cobro (plantilla + opcional link Conekta) ──
|
||
|
||
function _incluirLinkActivo(){
|
||
const pl = (configGlobal && configGlobal.plantilla) || {};
|
||
return pl.incluir_link !== false; // default true si no está definido
|
||
}
|
||
|
||
/** Saldo total / sin intereses: muestra paso intermedio para editar
|
||
* concepto (autogenerado) y luego ejecuta el cobro. */
|
||
function cobroConfirmar(tipo, monto){
|
||
const r = cobroState.renglon;
|
||
const conceptoDefault = autoConcepto(r);
|
||
document.getElementById("modal-inner").innerHTML = `
|
||
<div class="modal-header"><span class="modal-title">${tipo==='saldo'?'Saldo acumulado':'Sin intereses'}</span><button class="modal-close" onclick="cerrar()">×</button></div>
|
||
<p style="font-size:13px;color:var(--text-secondary);margin-bottom:1.2rem">${r.cliente}<br>${r.vehiculo}<br>Monto: <strong style="color:var(--text-primary)">${fmt(monto)}</strong></p>
|
||
<div class="form-group">
|
||
<label class="form-label">Concepto (editable)</label>
|
||
<input type="text" class="form-input" id="inp-concepto" value="${escapeAttr(conceptoDefault)}">
|
||
<div class="form-hint">Autogenerado: tipo · primer cliente · mes/año.</div>
|
||
</div>
|
||
<button class="btn-save" onclick="ejecutarCobroDesdeForm('${tipo}', ${monto})">Generar mensaje</button>`;
|
||
setTimeout(() => document.getElementById("inp-concepto").focus(), 80);
|
||
}
|
||
|
||
function cobroPersonalForm(){
|
||
const saldo = Number(cobroState.renglon.saldo)||0;
|
||
const conceptoDefault = autoConcepto(cobroState.renglon);
|
||
document.getElementById("modal-inner").innerHTML = `
|
||
<div class="modal-header"><span class="modal-title">Monto / abono</span><button class="modal-close" onclick="cerrar()">×</button></div>
|
||
<div class="form-group"><label class="form-label">Monto del abono</label><input type="number" step="0.01" class="form-input" id="inp-monto" placeholder="0.00" inputmode="decimal"><div class="form-hint">Saldo actual: ${fmt(saldo)}</div></div>
|
||
<div class="form-group"><label class="form-label">Concepto (editable)</label><input type="text" class="form-input" id="inp-concepto" value="${escapeAttr(conceptoDefault)}"></div>
|
||
<button class="btn-save" onclick="ejecutarCobroPersonalDesdeForm()">Generar mensaje</button>`;
|
||
setTimeout(()=>document.getElementById("inp-monto").focus(),100);
|
||
}
|
||
|
||
function ejecutarCobroDesdeForm(tipo, monto){
|
||
const concepto = (document.getElementById("inp-concepto").value || "").trim()
|
||
|| autoConcepto(cobroState.renglon);
|
||
ejecutarCobro(tipo, monto, concepto);
|
||
}
|
||
|
||
function ejecutarCobroPersonalDesdeForm(){
|
||
const m = parseFloat(document.getElementById("inp-monto").value);
|
||
if(!m || m <= 0){ toast("Monto inválido"); return; }
|
||
const concepto = (document.getElementById("inp-concepto").value || "").trim()
|
||
|| autoConcepto(cobroState.renglon);
|
||
ejecutarCobro("personal", m, concepto);
|
||
}
|
||
|
||
/** Orquestador: decide si llamar Conekta según el toggle `incluir_link`. */
|
||
async function ejecutarCobro(tipo, monto, concepto){
|
||
const r = cobroState.renglon;
|
||
cobroState.monto = monto;
|
||
cobroState.concepto = concepto;
|
||
cobroState.link = "";
|
||
cobroState.id_abono = "";
|
||
|
||
if(_incluirLinkActivo()){
|
||
try {
|
||
const payload = {id: r.id, tipo, concepto};
|
||
if(tipo === "personal") payload.monto = monto;
|
||
const res = await api("/generar-cobro", {method:"POST", body: JSON.stringify(payload)});
|
||
cobroState.link = res.link || "";
|
||
cobroState.id_abono = res.id_abono || "";
|
||
// El backend devuelve el monto real (puede diferir levemente en sinmora).
|
||
if(res.monto) cobroState.monto = res.monto;
|
||
if(res.concepto) cobroState.concepto = res.concepto;
|
||
} catch(e){
|
||
toast("Error al generar link: " + e.message);
|
||
return;
|
||
}
|
||
}
|
||
|
||
const texto = armarMensajeCobro(r, cobroState.monto, cobroState.concepto, cobroState.link);
|
||
mostrarPreviewCobro(r, cobroState.monto, cobroState.concepto, cobroState.link, texto);
|
||
}
|
||
|
||
function mostrarPreviewCobro(r, monto, concepto, link, texto){
|
||
const opciones = CONTACTOS.map(c => `<option>${c}</option>`).join("");
|
||
const avisoPendiente = cobroState.id_abono
|
||
? `<div style="font-size:12px;color:var(--text-secondary);background:var(--warning-soft);border-radius:11px;padding:9px 12px;margin-bottom:14px;line-height:1.45">
|
||
<svg class="ic" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" style="vertical-align:-2px;margin-right:4px"><circle cx="12" cy="12" r="9"/><path d="M12 7v5l3 2"/></svg>Se registró un <strong style="color:var(--warning)">abono pendiente</strong> por ${fmt(monto)}. El saldo de la tarjeta NO baja hasta que el abono se salde (manualmente o por pago Conekta).
|
||
</div>` : "";
|
||
const linkBlock = link
|
||
? `<div style="font-size:11px;color:var(--accent);word-break:break-all;background:var(--accent-soft);padding:8px 12px;border-radius:10px;margin-bottom:14px">${link}</div>`
|
||
: "";
|
||
document.getElementById("modal-inner").innerHTML = `
|
||
<div class="modal-header"><span class="modal-title">Mensaje listo</span><button class="modal-close" onclick="cerrar()">×</button></div>
|
||
<div style="font-size:13px;color:var(--text-secondary);margin-bottom:0.8rem">${r.cliente}<br>Monto: <strong style="color:var(--text-primary)">${fmt(monto)}</strong><br><span style="font-size:11px">${concepto}</span></div>
|
||
${linkBlock}
|
||
${avisoPendiente}
|
||
<div class="form-group">
|
||
<label class="form-label">Mensaje (editable antes de enviar)</label>
|
||
<textarea class="form-input" id="cobro-texto" rows="14" style="font-family:'DM Sans',sans-serif;font-size:12.5px;line-height:1.5">${escapeAttr(texto)}</textarea>
|
||
</div>
|
||
<div class="entrega-label">¿Cómo lo entregas?</div>
|
||
<button class="btn-cliente" onclick="enviarMensajeCobroCliente()"><svg class="ic" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round"><path d="M22 2 11 13M22 2l-7 20-4-9-9-4 20-7z"/></svg> Enviar al cliente</button>
|
||
<div class="reenvio-divider">o reenviar a un contacto</div>
|
||
<div class="reenvio-row">
|
||
<select id="sel-contacto-cobro">${opciones}</select>
|
||
<button class="btn-reenviar" onclick="reenviarMensajeCobroContacto()"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M5 12h14M13 6l6 6-6 6"/></svg></button>
|
||
</div>`;
|
||
}
|
||
|
||
async function enviarMensajeCobroCliente(){
|
||
const r = cobroState.renglon;
|
||
if(!r.telefono_efectivo){ toast("Agrega el número del cliente primero"); editarTel(r.id); return; }
|
||
const texto = document.getElementById("cobro-texto").value;
|
||
try {
|
||
await api("/enviar-mensaje-cliente", {method:"POST", body: JSON.stringify({id:r.id, texto})});
|
||
toast("Mensaje enviado al cliente"); cerrar();
|
||
} catch(e){ toast("No se pudo enviar: " + e.message); }
|
||
}
|
||
|
||
async function reenviarMensajeCobroContacto(){
|
||
const c = document.getElementById("sel-contacto-cobro").value;
|
||
const texto = document.getElementById("cobro-texto").value;
|
||
try {
|
||
await api("/reenviar-mensaje-contacto", {method:"POST", body: JSON.stringify({id:cobroState.renglon.id, contacto:c, texto})});
|
||
toast("Mensaje reenviado a " + c); cerrar();
|
||
} catch(e){ toast("No se pudo reenviar: " + e.message); }
|
||
}
|
||
|
||
// ── Marcar pagado ────────────────────────────────────────────
|
||
async function marcarPagado(id){
|
||
try {
|
||
await api("/marcar-pagado", {method:"POST", body: JSON.stringify({id})});
|
||
toast("Saldado"); await cargarRenglones();
|
||
} catch(e){ toast("No se pudo saldar"); }
|
||
}
|
||
|
||
// ── Renglones manuales (alta y baja) ─────────────────────────
|
||
// Normalización de nombre equivalente a `_norm` del backend
|
||
// (mayúsculas + sin puntos + espacios colapsados), para el match con el
|
||
// directorio (clave nombre_norm).
|
||
function normNombre(s){
|
||
return (s||"").toUpperCase().replace(/\./g,"").replace(/\s+/g," ").trim();
|
||
}
|
||
|
||
let rmCliSel = null; // contacto elegido: {nombre,nombre_norm,telefono} | "__nuevo__" | null
|
||
let rmCliShown = []; // items actualmente listados (para resolver por índice)
|
||
|
||
function abrirCrearRenglon(){
|
||
document.getElementById("modal-inner").classList.remove("lote");
|
||
const hoyISO = new Date().toISOString().slice(0,10);
|
||
rmCliSel = null; rmCliShown = [];
|
||
document.getElementById("modal-inner").innerHTML = `
|
||
<div class="modal-header"><span class="modal-title">Nuevo cobro personalizado</span><button class="modal-close" onclick="cerrar()">×</button></div>
|
||
<div class="form-group">
|
||
<label class="form-label">Cliente o razón social</label>
|
||
<input type="text" class="form-input" id="rm-cli-search" autocomplete="off" placeholder="Buscar o seleccionar cliente…"
|
||
oninput="rmCliRender(this.value)" onfocus="this.select(); rmCliRender('')"
|
||
onblur="setTimeout(()=>{var l=document.getElementById('rm-cli-list'); if(l) l.style.display='none';},160)">
|
||
<div class="cli-list" id="rm-cli-list" style="display:none"></div>
|
||
</div>
|
||
<div id="rm-nuevo-contacto" style="display:none">
|
||
<div class="form-group">
|
||
<label class="form-label">Nombre del nuevo contacto</label>
|
||
<input type="text" maxlength="100" class="form-input" id="rm-new-nombre" placeholder="Ej. Diego Corona">
|
||
</div>
|
||
<div class="form-group">
|
||
<label class="form-label">Teléfono (10 dígitos)</label>
|
||
<input type="tel" maxlength="10" inputmode="numeric" class="form-input" id="rm-new-tel" placeholder="2226176586"
|
||
oninput="this.value=this.value.replace(/\\D/g,'').slice(0,10)">
|
||
<div class="form-hint">Se guardará como contacto manual en el directorio.</div>
|
||
</div>
|
||
</div>
|
||
<div class="form-group">
|
||
<label class="form-label">Vehículo</label>
|
||
<input type="text" maxlength="120" class="form-input" id="rm-vehiculo" placeholder="Modelo / descripción">
|
||
</div>
|
||
<div class="form-group">
|
||
<label class="form-label">Nombre del concepto</label>
|
||
<input type="text" maxlength="60" class="form-input" id="rm-etiqueta" placeholder="Ej. Tenencia, Multa, Reparación">
|
||
<div class="form-hint">Texto libre que aparecerá como etiqueta del renglón.</div>
|
||
</div>
|
||
<div class="form-group">
|
||
<label class="form-label">Monto del concepto</label>
|
||
<input type="number" step="0.01" class="form-input" id="rm-monto" placeholder="0.00" inputmode="decimal">
|
||
</div>
|
||
<div class="form-group">
|
||
<label class="form-label">Tasa moratoria %/mes</label>
|
||
<input type="number" step="0.1" class="form-input" id="rm-tasa" value="4">
|
||
</div>
|
||
<div class="form-group">
|
||
<label class="form-label">Fecha de vencimiento</label>
|
||
<input type="date" class="form-input" id="rm-fecha" value="${hoyISO}">
|
||
<div class="form-hint">El moratorio cuenta desde esta fecha (0 días si aún no vence).</div>
|
||
</div>
|
||
<button class="btn-save" onclick="crearRenglonSubmit()">Crear cobro</button>`;
|
||
document.getElementById("modal").classList.add("open");
|
||
setTimeout(() => document.getElementById("rm-cli-search").focus(), 100);
|
||
}
|
||
|
||
// Normaliza para búsqueda: minúsculas + sin acentos.
|
||
function _busqStr(s){ return (s||"").toLowerCase().normalize("NFD").replace(/[̀-ͯ]/g,""); }
|
||
|
||
// Listas seccionadas del directorio: personalizados (manuales) y Sheet,
|
||
// deduplicadas por nombre_norm. Un nombre que exista como manual NO se repite
|
||
// en la sección del Sheet.
|
||
function rmCliListas(){
|
||
const dedupe = (arr) => {
|
||
const m = new Map();
|
||
arr.forEach(c => {
|
||
const k = c.nombre_norm || normNombre(c.nombre);
|
||
const prev = m.get(k);
|
||
if(!prev || (!prev.telefono && c.telefono)) m.set(k, {nombre_norm:k, nombre:c.nombre, telefono:c.telefono||""});
|
||
});
|
||
return [...m.values()].sort((a,b)=>a.nombre.localeCompare(b.nombre,'es'));
|
||
};
|
||
const manuales = dedupe((directorio||[]).filter(c => c.origen === "manual"));
|
||
const claveManual = new Set(manuales.map(c => c.nombre_norm));
|
||
const sheet = dedupe((directorio||[]).filter(c => c.origen !== "manual"))
|
||
.filter(c => !claveManual.has(c.nombre_norm));
|
||
return {manuales, sheet};
|
||
}
|
||
|
||
// Render del desplegable buscable. Orden: Agregar nuevo → Personalizados → Sheet.
|
||
function rmCliRender(filtro){
|
||
const list = document.getElementById("rm-cli-list");
|
||
if(!list) return;
|
||
list.style.display = "block";
|
||
const q = _busqStr(filtro);
|
||
const {manuales, sheet} = rmCliListas();
|
||
const fil = (arr) => arr.filter(c => !q || _busqStr(c.nombre).includes(q));
|
||
const fm = fil(manuales), fs = fil(sheet);
|
||
rmCliShown = [];
|
||
const item = (c) => {
|
||
const i = rmCliShown.push(c) - 1;
|
||
return `<div class="cli-item" onmousedown="rmCliPickIdx(${i})"><span>${c.nombre}</span>${c.telefono?`<span class="tel">+521 ${fmtTel(c.telefono)}</span>`:""}</div>`;
|
||
};
|
||
let html = `<div class="cli-item nuevo" onmousedown="rmCliPickNuevo()"><span>➕ Agregar contacto nuevo…</span></div>`;
|
||
if(fm.length){ html += `<div class="cli-head">Personalizados</div>` + fm.map(item).join(""); }
|
||
if(fs.length){ html += `<div class="cli-head">Directorio (Sheet)</div>` + fs.map(item).join(""); }
|
||
if(!fm.length && !fs.length){ html += `<div class="cli-empty">Sin coincidencias. Usa “Agregar contacto nuevo”.</div>`; }
|
||
list.innerHTML = html;
|
||
}
|
||
|
||
function rmCliPickIdx(i){
|
||
const c = rmCliShown[i];
|
||
if(!c) return;
|
||
rmCliSel = c;
|
||
const inp = document.getElementById("rm-cli-search");
|
||
if(inp) inp.value = c.nombre + (c.telefono ? " · +521 "+fmtTel(c.telefono) : "");
|
||
const list = document.getElementById("rm-cli-list"); if(list) list.style.display = "none";
|
||
const blk = document.getElementById("rm-nuevo-contacto"); if(blk) blk.style.display = "none";
|
||
}
|
||
|
||
function rmCliPickNuevo(){
|
||
rmCliSel = "__nuevo__";
|
||
const inp = document.getElementById("rm-cli-search");
|
||
if(inp) inp.value = "➕ Contacto nuevo";
|
||
const list = document.getElementById("rm-cli-list"); if(list) list.style.display = "none";
|
||
const blk = document.getElementById("rm-nuevo-contacto"); if(blk) blk.style.display = "block";
|
||
setTimeout(() => { const e = document.getElementById("rm-new-nombre"); if(e) e.focus(); }, 50);
|
||
}
|
||
|
||
async function crearRenglonSubmit(){
|
||
// El alta manual siempre crea un cobro personalizado (tipo 'otro').
|
||
const sel = (rmCliSel === "__nuevo__") ? "__nuevo__" : (rmCliSel ? rmCliSel.nombre_norm : "");
|
||
const vehiculo = (document.getElementById("rm-vehiculo").value || "").trim();
|
||
const etiqueta = (document.getElementById("rm-etiqueta").value || "").trim();
|
||
const monto = parseFloat(document.getElementById("rm-monto").value);
|
||
const tasa = parseFloat(document.getElementById("rm-tasa").value);
|
||
const fecha = (document.getElementById("rm-fecha").value || "").trim();
|
||
|
||
// ── 1) Validar TODO antes de cualquier escritura (no crear contacto si el
|
||
// cobro es inválido) ──
|
||
if(!sel){ toast("Selecciona un cliente"); return; }
|
||
let modoNuevo = sel === "__nuevo__";
|
||
let nuevoNombre = "", nuevoTel = "";
|
||
let contacto = null;
|
||
if(modoNuevo){
|
||
nuevoNombre = (document.getElementById("rm-new-nombre").value || "").trim();
|
||
nuevoTel = (document.getElementById("rm-new-tel").value || "").replace(/\D/g,'');
|
||
if(!nuevoNombre){ toast("Falta el nombre del nuevo contacto"); return; }
|
||
if(nuevoTel.length !== 10){ toast("El teléfono debe tener 10 dígitos"); return; }
|
||
} else {
|
||
contacto = (rmCliSel && typeof rmCliSel === "object") ? rmCliSel : null;
|
||
if(!contacto){ toast("Cliente no válido"); return; }
|
||
}
|
||
if(!vehiculo){ toast("Falta vehículo"); return; }
|
||
if(!etiqueta){ toast("Falta el nombre del concepto"); return; }
|
||
if(!monto || monto <= 0){ toast("Monto inválido"); return; }
|
||
if(isNaN(tasa) || tasa < 0){ toast("Tasa inválida"); return; }
|
||
if(!/^\d{4}-\d{2}-\d{2}$/.test(fecha)){ toast("Fecha de vencimiento inválida"); return; }
|
||
|
||
// ── 2) Resolver/persistir el contacto ──
|
||
let cliente;
|
||
if(modoNuevo){
|
||
cliente = nuevoNombre;
|
||
const norm = normNombre(nuevoNombre);
|
||
const yaExiste = (directorio||[]).some(c => (c.nombre_norm||normNombre(c.nombre)) === norm);
|
||
try {
|
||
if(!yaExiste){
|
||
await api("/contacto-manual", {method:"POST", body: JSON.stringify({nombre: nuevoNombre, telefono: nuevoTel})});
|
||
}
|
||
// Guarda el teléfono en el directorio para que el cobro lo resuelva.
|
||
await api("/directorio", {method:"POST", body: JSON.stringify({nombre_norm: norm, telefono: nuevoTel})});
|
||
} catch(e){ toast("No se pudo guardar el contacto: " + e.message); return; }
|
||
} else {
|
||
cliente = contacto.nombre;
|
||
if(contacto.telefono){
|
||
// Asegura el teléfono en el directorio (no-op si ya estaba; cubre los
|
||
// contactos manuales que aún no estaban en el índice de resolución).
|
||
try { await api("/directorio", {method:"POST", body: JSON.stringify({nombre_norm: contacto.nombre_norm, telefono: contacto.telefono})}); }
|
||
catch(e){ /* el cobro se crea igual; el tel se puede ajustar luego */ }
|
||
}
|
||
}
|
||
|
||
// ── 3) Crear el cobro ──
|
||
const body = {
|
||
cliente, vehiculo, tipo: "otro", etiqueta,
|
||
monto, tasa_mensual: tasa, fecha_vencimiento: fecha,
|
||
};
|
||
try {
|
||
await api("/renglon-manual", {method:"POST", body: JSON.stringify(body)});
|
||
toast("Cobro personalizado creado");
|
||
cerrar();
|
||
await cargarDirectorio();
|
||
await cargarRenglones();
|
||
} catch(e){ toast("No se pudo crear: " + e.message); }
|
||
}
|
||
|
||
async function eliminarRenglon(id, etiqueta){
|
||
if(!confirm(`¿Eliminar el renglón${etiqueta ? " de " + etiqueta : ""}?`)) return;
|
||
try {
|
||
await api("/renglon", {method:"DELETE", body: JSON.stringify({id})});
|
||
toast("Renglón eliminado");
|
||
await cargarRenglones();
|
||
} catch(e){ toast("No se pudo eliminar: " + e.message); }
|
||
}
|
||
|
||
async function saldarAbono(idRenglon, idAbono){
|
||
try {
|
||
await api("/abono/saldar", {method:"POST", body: JSON.stringify({id_renglon: idRenglon, id_abono: idAbono})});
|
||
toast("Abono saldado"); await cargarRenglones();
|
||
} catch(e){ toast("No se pudo saldar el abono: " + e.message); }
|
||
}
|
||
|
||
async function cancelarAbono(idRenglon, idAbono){
|
||
if(!confirm("¿Cancelar este abono pendiente?")) return;
|
||
try {
|
||
await api("/abono/cancelar", {method:"POST", body: JSON.stringify({id_renglon: idRenglon, id_abono: idAbono})});
|
||
toast("Abono cancelado"); await cargarRenglones();
|
||
} catch(e){ toast("No se pudo cancelar: " + e.message); }
|
||
}
|
||
|
||
// ── Lote ─────────────────────────────────────────────────────
|
||
function abrirLote(){
|
||
if(!renglones.length){ toast("No hay renglones activos"); return; }
|
||
loteState = {
|
||
// Autoseleccionar los que YA tienen teléfono efectivo (override O directorio),
|
||
// no solo el override local.
|
||
filas: renglones.map(r => ({ id:r.id, incluido: !!(r.telefono_efectivo || r.telefono), tipo:"saldo", montoPersonal:"" })),
|
||
};
|
||
renderLote();
|
||
document.getElementById("modal").classList.add("open");
|
||
}
|
||
function _findR(id){ return renglones.find(x => x.id === id); }
|
||
function montoFila(f){
|
||
const r = _findR(f.id);
|
||
if(!r) return 0;
|
||
if(f.tipo === "saldo") return Number(r.saldo)||0;
|
||
if(f.tipo === "sinmora") return (Number(r.capital)||0) - (Number(r.abonado)||0);
|
||
return parseFloat(f.montoPersonal) || 0;
|
||
}
|
||
function renderLote(){
|
||
const inner = document.getElementById("modal-inner");
|
||
inner.classList.add("lote");
|
||
const rows = loteState.filas.map((f,i) => {
|
||
const r = _findR(f.id); if(!r) return "";
|
||
const conI = Number(r.saldo)||0;
|
||
const sinI = (Number(r.capital)||0) - (Number(r.abonado)||0);
|
||
const sinNum = !(r.telefono_efectivo || r.telefono);
|
||
return `
|
||
<div class="lote-row ${f.incluido?'':'off'}">
|
||
<div class="lote-row-head">
|
||
<button class="lote-check ${f.incluido?'on':''}" onclick="toggleLote(${i})">${f.incluido?'✓':''}</button>
|
||
<div class="lote-cli">${r.cliente} <span class="pill-tipo ${r.tipo}" style="font-size:9px;padding:1px 6px;margin-left:4px">${tipoLabel(r)}</span><div class="lote-veh">${r.vehiculo}</div></div>
|
||
${sinNum?'<span class="badge-sin">sin número</span>':''}
|
||
</div>
|
||
<div class="seg">
|
||
<button class="seg-btn ${f.tipo==='saldo'?'active':''}" onclick="setLoteTipo(${i},'saldo')">Con interés<span>${fmtK(conI)}</span></button>
|
||
<button class="seg-btn ${f.tipo==='sinmora'?'active':''}" onclick="setLoteTipo(${i},'sinmora')">Sin interés<span>${fmtK(sinI)}</span></button>
|
||
<button class="seg-btn ${f.tipo==='personal'?'active':''}" onclick="setLoteTipo(${i},'personal')">Personal.<span>monto</span></button>
|
||
</div>
|
||
${f.tipo==='personal'
|
||
? `<div class="lote-personal"><input type="number" inputmode="decimal" placeholder="Monto personalizado" value="${f.montoPersonal}" oninput="setLotePersonal(${i},this.value)"></div>`
|
||
: ''}
|
||
</div>`;
|
||
}).join("");
|
||
const selables = loteState.filas.filter(f => { const r = _findR(f.id); return r && (r.telefono_efectivo || r.telefono); });
|
||
const todosSel = selables.length > 0 && selables.every(f => f.incluido);
|
||
inner.innerHTML = `
|
||
<div class="modal-header"><span class="modal-title">Cobrar en lote</span><button class="modal-close" onclick="cerrar()">×</button></div>
|
||
<div style="display:flex;align-items:center;justify-content:space-between;gap:10px;margin-bottom:12px">
|
||
<span class="section-label" style="margin:0">${loteState.filas.length} renglones · elige el tipo de cobro</span>
|
||
<button onclick="toggleLoteTodos()" style="background:transparent;border:none;color:var(--accent);font-size:11.5px;font-weight:700;letter-spacing:0.3px;cursor:pointer;white-space:nowrap;padding:4px 2px">${todosSel ? "Deseleccionar todos" : "Seleccionar todos"}</button>
|
||
</div>
|
||
${rows}
|
||
<div class="lote-summary"><span class="lt"><span id="lote-count">0</span> seleccionados</span><span class="lv" id="lote-total">$0</span></div>
|
||
<button class="btn-cliente" onclick="enviarLote()"><svg class="ic" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round"><path d="M22 2 11 13M22 2l-7 20-4-9-9-4 20-7z"/></svg> Enviar cobros automáticamente</button>`;
|
||
actualizarLoteSummary();
|
||
}
|
||
function setLoteTipo(i,t){ loteState.filas[i].tipo = t; renderLote(); }
|
||
function toggleLote(i){ loteState.filas[i].incluido = !loteState.filas[i].incluido; renderLote(); }
|
||
// Selecciona/deselecciona todos los que tienen número (los sin número no se
|
||
// pueden enviar, así que quedan fuera de la selección masiva).
|
||
function toggleLoteTodos(){
|
||
const tiene = (f) => { const r = _findR(f.id); return !!(r && (r.telefono_efectivo || r.telefono)); };
|
||
const selables = loteState.filas.filter(tiene);
|
||
const todosSel = selables.length > 0 && selables.every(f => f.incluido);
|
||
loteState.filas.forEach(f => { f.incluido = todosSel ? false : tiene(f); });
|
||
renderLote();
|
||
}
|
||
function setLotePersonal(i,v){ loteState.filas[i].montoPersonal = v; actualizarLoteSummary(); }
|
||
function actualizarLoteSummary(){
|
||
let total = 0, n = 0;
|
||
loteState.filas.forEach(f => { if(f.incluido){ total += montoFila(f); n++; } });
|
||
const ce = document.getElementById("lote-count"), te = document.getElementById("lote-total");
|
||
if(ce) ce.textContent = n; if(te) te.textContent = fmtK(total);
|
||
}
|
||
async function enviarLote(){
|
||
const incluidas = loteState.filas.filter(f => f.incluido);
|
||
if(!incluidas.length){ toast("Selecciona al menos un renglón"); return; }
|
||
for(const f of incluidas){
|
||
if(f.tipo === "personal" && (!parseFloat(f.montoPersonal) || parseFloat(f.montoPersonal) <= 0)){
|
||
const r = _findR(f.id); toast("Falta monto en " + (r ? r.cliente : f.id)); return;
|
||
}
|
||
}
|
||
const filas = incluidas.map(f => ({
|
||
id: f.id, tipo: f.tipo,
|
||
monto: f.tipo === "personal" ? parseFloat(f.montoPersonal) : null,
|
||
// Concepto individual de cada renglón (mismo que usa el cobro unitario).
|
||
concepto: autoConcepto(_findR(f.id)),
|
||
}));
|
||
try {
|
||
const res = await api("/cobrar-lote", {method:"POST", body: JSON.stringify({filas})});
|
||
let msg = `Enviados ${res.enviados}`;
|
||
if(res.omitidos_sin_telefono && res.omitidos_sin_telefono.length){
|
||
msg += ` · ${res.omitidos_sin_telefono.length} sin número omitidos`;
|
||
}
|
||
toast(msg); cerrar();
|
||
} catch(e){ toast("Error en el lote: " + e.message); }
|
||
}
|
||
|
||
// ── Cargar cobranza del día ──────────────────────────────────
|
||
async function cargarCobranza(){
|
||
try {
|
||
const res = await api("/cargar-dia", {method:"POST"});
|
||
const n = Number(res.agregados)||0;
|
||
toast(n > 0 ? `+${n} conceptos de hoy` : "Sin conceptos nuevos");
|
||
await cargarRenglones();
|
||
} catch(e){ toast("No se pudo cargar"); }
|
||
}
|
||
|
||
// ── Duplicados ───────────────────────────────────────────────
|
||
async function eliminarDuplicados(){
|
||
if(!confirm("¿Eliminar duplicados? Se conserva el más antiguo de cada grupo.")) return;
|
||
try {
|
||
const res = await api("/eliminar-duplicados", {method:"POST"});
|
||
toast(`${res.eliminados} renglones eliminados`);
|
||
await cargarRenglones();
|
||
} catch(e){ toast("No se pudo limpiar"); }
|
||
}
|
||
|
||
// ── Deshacer ─────────────────────────────────────────────────
|
||
async function deshacer(){
|
||
try {
|
||
const res = await api("/deshacer", {method:"POST"});
|
||
toast("Deshecho: " + (res.descripcion || "última acción"));
|
||
await cargarRenglones();
|
||
} catch(e){
|
||
if(e.message && e.message.toLowerCase().includes("nada")) toast("Nada que deshacer");
|
||
else toast("No se pudo deshacer");
|
||
}
|
||
}
|
||
|
||
function cerrar(){
|
||
document.getElementById("modal").classList.remove("open");
|
||
document.getElementById("modal-inner").classList.remove("lote");
|
||
}
|
||
const VISTAS_VALIDAS = ["tarjetas", "tabla", "directorio", "mensaje"];
|
||
const VIEW_KEY = "cobranza_view";
|
||
|
||
function setView(v){
|
||
if(!VISTAS_VALIDAS.includes(v)) v = "tarjetas";
|
||
document.querySelectorAll(".view").forEach(e => e.classList.remove("active"));
|
||
document.getElementById("view-"+v).classList.add("active");
|
||
document.querySelectorAll(".tab").forEach(t => t.classList.remove("active"));
|
||
const tab = document.querySelector('.tab[data-view="'+v+'"]');
|
||
if(tab) tab.classList.add("active");
|
||
try { localStorage.setItem(VIEW_KEY, v); } catch(e){}
|
||
if(v === "directorio") cargarDirectorio();
|
||
if(v === "mensaje") cargarConfigGlobal();
|
||
}
|
||
|
||
// Restaura la última sección visitada (persistida en localStorage).
|
||
function restaurarVista(){
|
||
let v = "tarjetas";
|
||
try { v = localStorage.getItem(VIEW_KEY) || "tarjetas"; } catch(e){}
|
||
setView(v);
|
||
}
|
||
|
||
// ── Config GLOBAL: cuentas SPEI + plantilla ───────────────────
|
||
async function cargarConfigGlobal(){
|
||
try {
|
||
configGlobal = await api("/config");
|
||
} catch(e){ configGlobal = {cuentas:[], plantilla:{}}; }
|
||
renderCuentasLista();
|
||
rellenarPlantillaInputs();
|
||
renderVistaPreviaMsg();
|
||
}
|
||
|
||
function renderCuentasLista(){
|
||
const cont = document.getElementById("cuentas-lista");
|
||
if(!cont) return;
|
||
const cuentas = (configGlobal && configGlobal.cuentas) ? configGlobal.cuentas : [];
|
||
if(!cuentas.length){
|
||
cont.innerHTML = `<div style="text-align:center;color:var(--text-tertiary);padding:16px;font-size:12.5px">Aún no hay cuentas registradas.</div>`;
|
||
return;
|
||
}
|
||
cont.innerHTML = cuentas.map((c, i) => `
|
||
<div class="cuenta-card" data-id="${escapeAttr(c.id)}">
|
||
<div class="cuenta-head">
|
||
<div class="cuenta-titulo">${escapeAttr(c.banco || "Cuenta")} · ${escapeAttr(c.beneficiario || "")}</div>
|
||
<label class="cuenta-toggle">
|
||
<input type="checkbox" ${c.incluir_en_mensaje ? "checked" : ""} onchange="toggleCuentaIncluir('${escapeAttr(c.id)}', this.checked)">
|
||
<span>en mensaje</span>
|
||
</label>
|
||
</div>
|
||
<div class="cuenta-grid">
|
||
<div class="full"><label>Beneficiario</label><input value="${escapeAttr(c.beneficiario)}" data-k="beneficiario" oninput="actualizarCampoCuenta('${escapeAttr(c.id)}','beneficiario',this.value)"></div>
|
||
<div><label>Banco</label><input value="${escapeAttr(c.banco)}" data-k="banco" oninput="actualizarCampoCuenta('${escapeAttr(c.id)}','banco',this.value)"></div>
|
||
<div><label>Cuenta</label><input value="${escapeAttr(c.cuenta||'')}" data-k="cuenta" oninput="actualizarCampoCuenta('${escapeAttr(c.id)}','cuenta',this.value)"></div>
|
||
<div class="full"><label>CLABE (18 dígitos)</label><input value="${escapeAttr(c.clabe||'')}" maxlength="18" inputmode="numeric" oninput="this.value=this.value.replace(/\\D/g,'').slice(0,18); actualizarCampoCuenta('${escapeAttr(c.id)}','clabe',this.value)"></div>
|
||
</div>
|
||
<div class="cuenta-actions">
|
||
<button class="btn-save" style="padding:9px 18px;width:auto;font-size:12.5px" onclick="guardarCuenta('${escapeAttr(c.id)}')">Guardar</button>
|
||
<button class="btn-row-del" onclick="eliminarCuenta('${escapeAttr(c.id)}')" title="Eliminar">BORRAR</button>
|
||
</div>
|
||
</div>`).join("");
|
||
}
|
||
|
||
function actualizarCampoCuenta(id, campo, valor){
|
||
if(!configGlobal || !configGlobal.cuentas) return;
|
||
const c = configGlobal.cuentas.find(x => x.id === id);
|
||
if(c){ c[campo] = valor; renderVistaPreviaMsg(); }
|
||
}
|
||
|
||
async function toggleCuentaIncluir(id, incluir){
|
||
actualizarCampoCuenta(id, "incluir_en_mensaje", incluir);
|
||
await guardarCuenta(id, true);
|
||
}
|
||
|
||
function abrirNuevaCuenta(){
|
||
// Agrega un placeholder local y lo renderiza inmediatamente. Se persiste al
|
||
// pulsar Guardar.
|
||
const id = "tmp_" + Math.random().toString(36).slice(2,8);
|
||
configGlobal.cuentas = configGlobal.cuentas || [];
|
||
configGlobal.cuentas.push({id, beneficiario:"", banco:"", cuenta:"", clabe:"", incluir_en_mensaje:true});
|
||
renderCuentasLista();
|
||
// Focus en el primer input del nuevo bloque.
|
||
setTimeout(() => {
|
||
const all = document.querySelectorAll(".cuenta-card");
|
||
const last = all[all.length-1];
|
||
if(last) last.querySelector("input").focus();
|
||
}, 50);
|
||
}
|
||
|
||
async function guardarCuenta(id, silent){
|
||
const c = configGlobal.cuentas.find(x => x.id === id);
|
||
if(!c) return;
|
||
const payload = {
|
||
id: id.startsWith("tmp_") ? null : c.id,
|
||
beneficiario: c.beneficiario || "",
|
||
banco: c.banco || "",
|
||
cuenta: c.cuenta || "",
|
||
clabe: c.clabe || "",
|
||
incluir_en_mensaje: !!c.incluir_en_mensaje,
|
||
};
|
||
try {
|
||
const nuevo = await api("/config/cuenta", {method:"POST", body: JSON.stringify(payload)});
|
||
// Reemplaza el placeholder por el real
|
||
const idx = configGlobal.cuentas.findIndex(x => x.id === id);
|
||
if(idx >= 0) configGlobal.cuentas[idx] = nuevo;
|
||
if(!silent) toast("Cuenta guardada");
|
||
renderCuentasLista();
|
||
renderVistaPreviaMsg();
|
||
} catch(e){ toast("No se pudo guardar: " + e.message); }
|
||
}
|
||
|
||
async function eliminarCuenta(id){
|
||
if(!confirm("¿Eliminar esta cuenta?")) return;
|
||
if(id.startsWith("tmp_")){
|
||
configGlobal.cuentas = configGlobal.cuentas.filter(x => x.id !== id);
|
||
renderCuentasLista(); renderVistaPreviaMsg();
|
||
return;
|
||
}
|
||
try {
|
||
await api("/config/cuenta", {method:"DELETE", body: JSON.stringify({id})});
|
||
configGlobal.cuentas = configGlobal.cuentas.filter(x => x.id !== id);
|
||
toast("Cuenta eliminada");
|
||
renderCuentasLista(); renderVistaPreviaMsg();
|
||
} catch(e){ toast("No se pudo eliminar: " + e.message); }
|
||
}
|
||
|
||
function rellenarPlantillaInputs(){
|
||
const p = (configGlobal && configGlobal.plantilla) ? configGlobal.plantilla : {};
|
||
document.getElementById("pl-saludo").value = p.saludo || "";
|
||
document.getElementById("pl-despedida").value = p.despedida || "";
|
||
document.getElementById("pl-cliente").checked = p.incluir_cliente !== false;
|
||
document.getElementById("pl-vehiculo").checked = p.incluir_vehiculo !== false;
|
||
document.getElementById("pl-monto").checked = p.incluir_monto !== false;
|
||
document.getElementById("pl-fecha").checked = !!p.incluir_fecha_limite;
|
||
document.getElementById("pl-link").checked = p.incluir_link !== false;
|
||
}
|
||
|
||
async function guardarPlantilla(){
|
||
const body = {
|
||
saludo: document.getElementById("pl-saludo").value,
|
||
despedida: document.getElementById("pl-despedida").value,
|
||
incluir_cliente: document.getElementById("pl-cliente").checked,
|
||
incluir_vehiculo: document.getElementById("pl-vehiculo").checked,
|
||
incluir_monto: document.getElementById("pl-monto").checked,
|
||
incluir_fecha_limite: document.getElementById("pl-fecha").checked,
|
||
incluir_link: document.getElementById("pl-link").checked,
|
||
};
|
||
try {
|
||
const pl = await api("/config/plantilla", {method:"POST", body: JSON.stringify(body)});
|
||
if(configGlobal) configGlobal.plantilla = pl;
|
||
toast("Plantilla guardada");
|
||
renderVistaPreviaMsg();
|
||
} catch(e){ toast("No se pudo guardar: " + e.message); }
|
||
}
|
||
|
||
// ── Mensaje SPEI ──────────────────────────────────────────────
|
||
const _MESES_CORTO = ["ENE","FEB","MAR","ABR","MAY","JUN","JUL","AGO","SEP","OCT","NOV","DIC"];
|
||
|
||
function autoConcepto(r){
|
||
const tipo = (r && r.tipo) ? r.tipo.toUpperCase() : "COBRO";
|
||
let tipoStr;
|
||
if(tipo === "OTRO" && r && r.etiqueta){
|
||
// Cobro personalizado: usa la etiqueta del concepto (ej. TENENCIA).
|
||
tipoStr = r.etiqueta.toUpperCase().replace(/\s+/g, "-");
|
||
} else {
|
||
const tipoMap = {RENTA: "RENTA", VR: "VR", EXTRA: "EXTRA"};
|
||
tipoStr = tipoMap[tipo] || tipo;
|
||
}
|
||
const cliente = (r && r.cliente ? r.cliente : "CLIENTE").split(/\s+/)[0].toUpperCase();
|
||
const d = new Date();
|
||
return `WK-${tipoStr}-${cliente}-${_MESES_CORTO[d.getMonth()]}${String(d.getFullYear()).slice(-2)}`;
|
||
}
|
||
|
||
function _aplicarVariables(tpl, vars){
|
||
return (tpl || "").replace(/\{(\w+)\}/g, (_, k) => (vars[k] != null ? vars[k] : ""));
|
||
}
|
||
|
||
/**
|
||
* Arma el mensaje de cobro a partir de la PLANTILLA GLOBAL.
|
||
* - `link` opcional: si viene y la plantilla tiene `incluir_link=true`,
|
||
* agrega la línea con el enlace de pago Conekta.
|
||
* - Si no hay cuentas SPEI activadas Y no hay link, deja una nota.
|
||
* UNA SOLA función para cualquier vía de cobro.
|
||
*/
|
||
function armarMensajeCobro(r, monto, concepto, link){
|
||
const cfg = configGlobal || {plantilla:{}, cuentas:[]};
|
||
const pl = cfg.plantilla || {};
|
||
const cuentas = (cfg.cuentas || []).filter(c => c.incluir_en_mensaje);
|
||
const d = new Date();
|
||
const vars = {
|
||
cliente: r.cliente || "",
|
||
vehiculo: r.vehiculo || "",
|
||
monto: fmt(monto),
|
||
concepto: concepto || "",
|
||
mes: _MESES_CORTO[d.getMonth()] + " " + d.getFullYear(),
|
||
};
|
||
const incluirLink = (pl.incluir_link !== false) && !!link;
|
||
|
||
let out = "";
|
||
if(pl.saludo) out += _aplicarVariables(pl.saludo, vars) + "\n\n";
|
||
out += "Le compartimos los datos para realizar su pago:\n\n";
|
||
out += `Concepto: ${concepto}\n`;
|
||
if(pl.incluir_cliente !== false && r.cliente) out += `Cliente: ${r.cliente}\n`;
|
||
if(pl.incluir_vehiculo !== false && r.vehiculo) out += `Vehículo: ${r.vehiculo}\n`;
|
||
if(pl.incluir_monto !== false) out += `Monto: ${fmt(monto)}\n`;
|
||
if(pl.incluir_fecha_limite){
|
||
const f = new Date(); f.setDate(f.getDate() + 5);
|
||
out += `Fecha límite: ${f.toLocaleDateString("es-MX",{day:"2-digit",month:"2-digit",year:"numeric"})}\n`;
|
||
}
|
||
out += "\n";
|
||
if(cuentas.length){
|
||
cuentas.forEach(c => {
|
||
out += `🏦 ${c.banco || ""}\n`;
|
||
if(c.beneficiario) out += `Beneficiario: ${c.beneficiario}\n`;
|
||
if(c.cuenta) out += `Cuenta: ${c.cuenta}\n`;
|
||
if(c.clabe) out += `CLABE: ${c.clabe}\n`;
|
||
out += "\n";
|
||
});
|
||
}
|
||
if(incluirLink){
|
||
out += `Puede pagar con tarjeta, SPEI o efectivo en Oxxo desde este link:\n${link}\n\n`;
|
||
}
|
||
if(!cuentas.length && !incluirLink){
|
||
out += "⚠️ No hay cuentas activadas ni link configurado.\n\n";
|
||
}
|
||
if(pl.despedida) out += _aplicarVariables(pl.despedida, vars);
|
||
return out.trim();
|
||
}
|
||
|
||
// Alias para compat con código que aún use armarMensajeSPEI.
|
||
const armarMensajeSPEI = armarMensajeCobro;
|
||
|
||
function renderVistaPreviaMsg(){
|
||
const wrap = document.getElementById("preview-msg");
|
||
if(!wrap) return;
|
||
const rejemplo = {tipo:"renta", cliente:"DESARROLLOS ELLIOTS", vehiculo:"VIRTUS TRENDLINE"};
|
||
const concepto = autoConcepto(rejemplo);
|
||
const incluirLink = document.getElementById("pl-link").checked;
|
||
const liveCfg = {
|
||
cuentas: (configGlobal && configGlobal.cuentas) ? configGlobal.cuentas : [],
|
||
plantilla: {
|
||
saludo: document.getElementById("pl-saludo").value,
|
||
despedida: document.getElementById("pl-despedida").value,
|
||
incluir_cliente: document.getElementById("pl-cliente").checked,
|
||
incluir_vehiculo: document.getElementById("pl-vehiculo").checked,
|
||
incluir_monto: document.getElementById("pl-monto").checked,
|
||
incluir_fecha_limite: document.getElementById("pl-fecha").checked,
|
||
incluir_link: incluirLink,
|
||
},
|
||
};
|
||
const prevCfg = configGlobal; configGlobal = liveCfg;
|
||
const linkEjemplo = incluirLink ? "https://pay.conekta.com/link/example_abc123" : "";
|
||
wrap.textContent = armarMensajeCobro(rejemplo, 8050.14, concepto, linkEjemplo);
|
||
configGlobal = prevCfg;
|
||
}
|
||
document.getElementById("modal").addEventListener("click", e => { if(e.target.id === "modal") cerrar(); });
|
||
|
||
(async () => {
|
||
if(!(await validar())) return;
|
||
// En paralelo: renglones (tarjetas/tabla), directorio (modal teléfono),
|
||
// config global (cuentas SPEI + plantilla para vía SPEI del cobro).
|
||
await Promise.all([cargarRenglones(), cargarDirectorio(), cargarConfigGlobal()]);
|
||
// Restaura la sección activa que el usuario tenía antes de refrescar.
|
||
restaurarVista();
|
||
})();
|
||
</script>
|
||
</body>
|
||
</html>
|