228 lines
12 KiB
JavaScript
228 lines
12 KiB
JavaScript
"use client";
|
||
|
||
import { useMemo, useState, useTransition } from "react";
|
||
import { useRouter } from "next/navigation";
|
||
import { money, actividadUrl } from "../../lib/constants";
|
||
import { diaCorto } from "../../lib/plan";
|
||
import {
|
||
AGENDADOR, TIPOS_AGENDADOR, OBJETIVOS_AGENDADOR, proponer, validar, horasDe, minAHora, horaAMin,
|
||
} from "../../lib/agendador";
|
||
import { crearLoteAction, deshacerLoteAction } from "../../actividades/agendadorActions";
|
||
|
||
const NOMBRE_PLURAL = { Llamada: "llamadas", Cita: "visitas", Tarea: "tareas" };
|
||
const fechaHora = (iso) =>
|
||
new Intl.DateTimeFormat("es-NI", { timeZone: "America/Managua", day: "2-digit", month: "2-digit", hour: "2-digit", minute: "2-digit" }).format(new Date(iso));
|
||
|
||
// Agendador sugerido de la semana (PILOTO). Propone una actividad por oportunidad «por planificar»,
|
||
// con el objetivo sugerido, repartidas en la semana dentro del horario y los máximos por día; la
|
||
// persona revisa y cambia lo que quiera, y «Crear en Dynamics» las crea de una vez, con el propietario
|
||
// de la oportunidad. Nada se escribe hasta ese botón. Diseño: agendador-automatico-diseno.md.
|
||
export default function AgendadorPanel({ ownerEmail, ownerName, periodo, dias, hoy, ahoraMin, candidatos, existentes, bloques, lotes }) {
|
||
const router = useRouter();
|
||
const [pendiente, empezar] = useTransition();
|
||
const base = { dias, existentes, bloques, hoy, ahoraMin };
|
||
const [tipoTodas, setTipoTodas] = useState("Llamada");
|
||
const [items, setItems] = useState(() => proponer({ candidatos, ...base, tipo: "Llamada" }));
|
||
const [resultado, setResultado] = useState(null);
|
||
const [aviso, setAviso] = useState(null);
|
||
|
||
const incluidos = items.filter((i) => i.incluir && !i.creada);
|
||
const val = useMemo(() => validar({ items: incluidos, ...base }), [items, dias, existentes, bloques, hoy, ahoraMin]); // eslint-disable-line react-hooks/exhaustive-deps
|
||
const cambiar = (key, cambios) => setItems((prev) => prev.map((i) => (i.key === key ? { ...i, ...cambios } : i)));
|
||
|
||
const cambiarTipo = (it, tipo) => {
|
||
const horas = horasDe(tipo).map(minAHora);
|
||
const hora = tipo === "Tarea" ? minAHora(AGENDADOR.horaTarea) : horas.includes(it.hora) ? it.hora : horas[0];
|
||
cambiar(it.key, { tipo, hora });
|
||
};
|
||
const cambiarDia = (it, dia) => {
|
||
const horas = horasDe(it.tipo).map(minAHora);
|
||
const hora = it.tipo === "Tarea" ? minAHora(AGENDADOR.horaTarea) : it.hora && horas.includes(it.hora) ? it.hora : horas[0] || "";
|
||
cambiar(it.key, { dia: dia || null, hora: dia ? hora : null, incluir: !!dia || it.incluir, sinCupo: !dia });
|
||
};
|
||
const reproponer = (tipo) => {
|
||
setTipoTodas(tipo);
|
||
const nuevos = proponer({ candidatos: candidatos.filter((c) => !items.find((i) => i.key === c.id)?.creada), ...base, tipo });
|
||
setItems([...items.filter((i) => i.creada), ...nuevos]);
|
||
};
|
||
|
||
const crear = () => {
|
||
setAviso(null);
|
||
if (!incluidos.length || !val.ok) return;
|
||
const resumen = TIPOS_AGENDADOR.map((t) => [t, incluidos.filter((i) => i.tipo === t).length]).filter(([, n]) => n).map(([t, n]) => `${n} ${NOMBRE_PLURAL[t]}`).join(", ");
|
||
if (!window.confirm(`Se crearán en Dynamics ${incluidos.length} actividades (${resumen}) para ${ownerName}, a su nombre. ¿Continuar?`)) return;
|
||
empezar(async () => {
|
||
const r = await crearLoteAction({
|
||
ownerEmail,
|
||
periodo,
|
||
items: incluidos.map((i) => ({ oppId: i.oppId, nombre: i.nombre, cliente: i.cliente, tipo: i.tipo, objetivo: i.objetivo, dia: i.dia, hora: i.hora })),
|
||
});
|
||
if (!r.ok) { setAviso({ mal: true, texto: r.error }); return; }
|
||
const creadas = new Map(r.resultados.filter((x) => x.estado === "creada").map((x) => [x.oppId, x]));
|
||
setItems((prev) => prev.map((i) => (creadas.has(i.oppId) ? { ...i, creada: creadas.get(i.oppId) } : i)));
|
||
setResultado(r);
|
||
router.refresh();
|
||
});
|
||
};
|
||
|
||
const deshacer = (id) => {
|
||
if (!window.confirm("Se cancelarán en Dynamics las actividades de esa tanda que sigan abiertas. ¿Deshacer?")) return;
|
||
empezar(async () => {
|
||
const r = await deshacerLoteAction(id);
|
||
setAviso(r.ok ? { texto: `Tanda deshecha: ${r.canceladas} cancelada(s)${r.yaCerradas ? `, ${r.yaCerradas} ya estaban cerradas` : ""}${r.errores ? `, ${r.errores} con error` : ""}.` } : { mal: true, texto: r.error });
|
||
router.refresh();
|
||
});
|
||
};
|
||
|
||
const hayCitas = incluidos.some((i) => i.tipo === "Cita");
|
||
|
||
return (
|
||
<section className="panel plan-agd no-print">
|
||
<h3>Agendador de la semana — {ownerName} <span className="agd-piloto">piloto</span></h3>
|
||
<p className="hint">
|
||
Propone una actividad por cada oportunidad por planificar, con el objetivo sugerido, repartidas de lunes a viernes entre 9:00–12:00 y
|
||
14:00–16:00 (máximo por día: {AGENDADOR.topes.Llamada} llamadas, {AGENDADOR.topes.Cita} visitas, {AGENDADOR.topes.Tarea} tareas). Revisa y cambia lo que
|
||
quieras; no se crea nada en Dynamics hasta que pulses «Crear». Quedan a nombre del propietario de la oportunidad.
|
||
</p>
|
||
|
||
{candidatos.length === 0 ? (
|
||
<p>No hay oportunidades por planificar esta semana: todas tienen alguna actividad.</p>
|
||
) : (
|
||
<>
|
||
<div className="agd-barra">
|
||
<label htmlFor="agd-tipo">Tipo para todas:</label>
|
||
<select id="agd-tipo" value={tipoTodas} onChange={(e) => reproponer(e.target.value)} disabled={pendiente}>
|
||
{TIPOS_AGENDADOR.map((t) => <option key={t} value={t}>{t}</option>)}
|
||
</select>
|
||
<button type="button" className="agd-btn-sec" onClick={() => reproponer(tipoTodas)} disabled={pendiente} title="Vuelve a repartir todas las que no se han creado">Proponer de nuevo</button>
|
||
<span className="hint">
|
||
{incluidos.length} propuesta{incluidos.length === 1 ? "" : "s"} para crear
|
||
{items.filter((i) => i.sinCupo && !i.dia && !i.creada).length > 0 && ` · ${items.filter((i) => i.sinCupo && !i.dia && !i.creada).length} sin cupo esta semana (no caben con los máximos por día)`}
|
||
</span>
|
||
</div>
|
||
|
||
<div className="agd-dias">
|
||
{dias.map((d) => {
|
||
const c = val.porDia[d] || { Llamada: 0, Cita: 0, Tarea: 0, ...(existentes[d] || {}) };
|
||
const exc = TIPOS_AGENDADOR.some((t) => c[t] > AGENDADOR.topes[t]);
|
||
return (
|
||
<span key={d} className={`agd-dia${exc ? " mal" : ""}`} title="Incluye lo que ya tiene agendado ese día">
|
||
<b>{diaCorto(d)}</b> {c.Llamada} llam. · {c.Cita} vis. · {c.Tarea} tar.
|
||
</span>
|
||
);
|
||
})}
|
||
</div>
|
||
|
||
<div className="ts" style={{ maxHeight: 520, overflowY: "auto" }}>
|
||
<table>
|
||
<thead>
|
||
<tr>
|
||
<th></th>
|
||
<th>Cliente / oportunidad</th>
|
||
<th className="num">Valor</th>
|
||
<th>Tipo</th>
|
||
<th>Día</th>
|
||
<th>Hora</th>
|
||
<th>Objetivo</th>
|
||
<th>Avisos</th>
|
||
</tr>
|
||
</thead>
|
||
<tbody>
|
||
{items.map((it) => {
|
||
const probs = val.porItem[it.key] || [];
|
||
const horas = horasDe(it.tipo).map(minAHora);
|
||
return (
|
||
<tr key={it.key} style={it.creada ? { opacity: 0.6 } : undefined}>
|
||
<td>
|
||
<input type="checkbox" checked={!!it.incluir && !it.creada} disabled={!!it.creada || pendiente} onChange={(e) => cambiar(it.key, { incluir: e.target.checked })} aria-label="Incluir" />
|
||
</td>
|
||
<td>
|
||
<strong>{it.cliente || it.nombre}</strong>
|
||
{it.cliente && <div style={{ fontSize: 11, color: "var(--tinta-suave)" }}>{it.nombre}</div>}
|
||
</td>
|
||
<td className="num">{money(it.valor)}{it.pct ? <div style={{ fontSize: 11, color: "var(--tinta-suave)" }}>{it.pct}%</div> : null}</td>
|
||
<td>
|
||
<select value={it.tipo} disabled={!!it.creada || pendiente} onChange={(e) => cambiarTipo(it, e.target.value)}>
|
||
{TIPOS_AGENDADOR.map((t) => <option key={t} value={t}>{t}</option>)}
|
||
</select>
|
||
</td>
|
||
<td>
|
||
<select value={it.dia || ""} disabled={!!it.creada || pendiente} onChange={(e) => cambiarDia(it, e.target.value)}>
|
||
<option value="">— elegir —</option>
|
||
{dias.map((d) => <option key={d} value={d}>{diaCorto(d)}</option>)}
|
||
</select>
|
||
</td>
|
||
<td>
|
||
{it.tipo === "Tarea" ? (
|
||
<span title="Las tareas vencen a las 16:00">vence {minAHora(AGENDADOR.horaTarea)}</span>
|
||
) : (
|
||
<select value={it.hora || ""} disabled={!!it.creada || pendiente || !it.dia} onChange={(e) => cambiar(it.key, { hora: e.target.value })}>
|
||
<option value="">—</option>
|
||
{horas.map((h) => <option key={h} value={h}>{h}</option>)}
|
||
</select>
|
||
)}
|
||
</td>
|
||
<td>
|
||
<select value={it.objetivo} disabled={!!it.creada || pendiente} onChange={(e) => cambiar(it.key, { objetivo: e.target.value })}>
|
||
<option value="">— elegir —</option>
|
||
{OBJETIVOS_AGENDADOR.map((o) => <option key={o} value={o}>{o}</option>)}
|
||
</select>
|
||
</td>
|
||
<td>
|
||
{it.creada ? (
|
||
<a className="agd-ok" href={actividadUrl({ tipo: it.creada.tipo, id: it.creada.activityId })} target="_blank" rel="noreferrer">✓ Creada · abrir en CRM</a>
|
||
) : it.sinCupo && !it.dia ? (
|
||
<span className="agd-mal">Sin cupo esta semana: elige un día o déjala fuera.</span>
|
||
) : it.incluir && probs.length ? (
|
||
<span className="agd-mal">{probs.join(" ")}</span>
|
||
) : it.tipo === "Cita" && it.incluir ? (
|
||
<span className="hint">Se crea genérica: completa lugar y participantes en el CRM.</span>
|
||
) : null}
|
||
</td>
|
||
</tr>
|
||
);
|
||
})}
|
||
</tbody>
|
||
</table>
|
||
</div>
|
||
|
||
<div className="agd-pie">
|
||
<button type="button" className="agd-btn" disabled={pendiente || !incluidos.length || !val.ok} onClick={crear}>
|
||
{pendiente ? "Trabajando…" : `Crear ${incluidos.length} actividad${incluidos.length === 1 ? "" : "es"} en Dynamics`}
|
||
</button>
|
||
{!val.ok && incluidos.length > 0 && <span className="agd-mal">Corrige los avisos en rojo para poder crear.</span>}
|
||
</div>
|
||
{hayCitas && (
|
||
<p className="hint">Las visitas se crean con lo básico (fecha, hora, objetivo, oportunidad). Después de crearlas, abre cada una con «abrir en CRM» para agregar el lugar y los participantes.</p>
|
||
)}
|
||
</>
|
||
)}
|
||
|
||
{aviso && <p className={aviso.mal ? "agd-mal" : "agd-ok"} role="status">{aviso.texto}</p>}
|
||
{resultado && (
|
||
<div className="agd-res">
|
||
<strong>Tanda #{resultado.loteId}:</strong> {resultado.creadas} creada(s){resultado.errores ? `, ${resultado.errores} con error` : ""}{resultado.omitidas ? `, ${resultado.omitidas} omitida(s)` : ""}.
|
||
{resultado.resultados.filter((x) => x.estado !== "creada").map((x) => (
|
||
<div key={x.oppId} className="agd-mal">{x.nombre || x.oppId}: {x.error}</div>
|
||
))}
|
||
</div>
|
||
)}
|
||
|
||
{lotes.length > 0 && (
|
||
<details className="agd-lotes">
|
||
<summary>Tandas creadas esta semana ({lotes.length})</summary>
|
||
<ul>
|
||
{lotes.map((l) => (
|
||
<li key={l.id}>
|
||
#{l.id} · {fechaHora(l.creado_en)} · {l.creado_por} · {l.items.filter((x) => x.estado === "creada").length} actividad(es)
|
||
{l.deshecho_en ? <span> — deshecha {fechaHora(l.deshecho_en)}</span> : (
|
||
<button type="button" className="agd-btn-sec" disabled={pendiente} onClick={() => deshacer(l.id)} style={{ marginLeft: 8 }}>Deshacer</button>
|
||
)}
|
||
</li>
|
||
))}
|
||
</ul>
|
||
</details>
|
||
)}
|
||
</section>
|
||
);
|
||
}
|