informe-comercial-alfa/app/m/components/NuevaMovil.js

210 lines
11 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"use client";
import { useEffect, useRef, useState } from "react";
import { createPortal } from "react-dom";
import { useRouter } from "next/navigation";
import { buscarReferentesAction, crearActividadLibreAction } from "../../cuentas/cuentasActions";
import { deshacerSeguimientoAction, refrescarPantallasAction } from "../../actividades/gestionActions";
import { FRASES } from "../../components/actividades/GestionarActividad";
import { OBJETIVOS_LIBRES, localDeIso, minAHora, horaAMin } from "../../lib/agendador";
import { addDays, esHabil } from "../../lib/plan";
import { diaCortoES } from "../../lib/campo";
// Botón +: registrar en pocos toques lo que pasó en la calle o por WhatsApp (que hoy no llega al CRM) o agendar lo que sigue.
// Tipo → ¿con quién? → cuándo → «Ya la realicé» + resultado → Guardar. Usa la misma acción de alta que la web
// (crearActividadLibreAction): propietario, validaciones, bitácora y «Deshacer» son los de siempre.
const TIPOS = [["Llamada", "📞 Llamada"], ["Cita", "🤝 Visita"], ["Tarea", "☑ Tarea"]];
const DUR = { Llamada: 15, Cita: 60, Tarea: 0 };
const redondea = (m, paso) => Math.ceil(m / paso) * paso;
function sigHabil(dia) {
let d = addDays(dia, 1);
while (!esHabil(d)) d = addDays(d, 1);
return d;
}
// preset: { ref?: { tipo, id, nombre }, hora?: "HH:MM" }
export default function NuevaMovil({ hoy, preset = {}, onCerrar }) {
const router = useRouter();
const ahora = localDeIso(new Date().toISOString());
const [tipo, setTipo] = useState("Llamada");
const [ref, setRef] = useState(preset.ref || null);
const [q, setQ] = useState("");
const [res, setRes] = useState(null);
const [buscando, setBuscando] = useState(false);
const [cuando, setCuando] = useState(preset.hora ? "fecha" : "hoy");
const [dia, setDia] = useState(hoy);
const [hora, setHora] = useState(preset.hora || "");
const [realizada, setRealizada] = useState(false);
const [nota, setNota] = useState("");
const [objetivo, setObjetivo] = useState(preset.ref?.tipo === "account" ? "Prospección" : "Negociación");
const [verObj, setVerObj] = useState(false);
const [error, setError] = useState("");
const [trab, setTrab] = useState(false);
const [hecho, setHecho] = useState(null);
const [deshecho, setDeshecho] = useState(false);
const huboCambio = useRef(false);
const seq = useRef(0);
useEffect(() => {
const t = q.trim();
if (t.length < 2) { setRes(null); return; }
const mi = ++seq.current;
setBuscando(true);
const h = setTimeout(async () => {
const r = await buscarReferentesAction(t);
if (mi !== seq.current) return;
setBuscando(false);
if (r.ok) setRes(r); else { setRes(null); setError(r.error); }
}, 350);
return () => clearTimeout(h);
}, [q]);
// Opciones de «cuándo»: Ahora · Hoy HH:MM · Mañana · 📅
const hoyHH = redondea(ahora.min + 30, 30);
const hoyOpcion = hoyHH <= 17 * 60 && esHabil(hoy) ? minAHora(hoyHH) : null;
const manana = sigHabil(hoy);
const horaElegida = () => {
if (cuando === "ahora") return realizada ? minAHora(ahora.min) : minAHora(redondea(ahora.min + 5, 5));
if (cuando === "hoy") return hoyOpcion || minAHora(redondea(ahora.min + 30, 5));
if (cuando === "manana") return "09:00";
return hora || "09:00";
};
const diaElegido = cuando === "manana" ? manana : cuando === "fecha" ? dia : hoy;
// «Ya la realicé»: la fecha no puede ser futura. Si había elegido mañana, vuelve a «Ahora».
const alternarRealizada = (v) => {
setRealizada(v);
if (v && (cuando === "manana" || cuando === "hoy")) setCuando("ahora");
if (v && cuando === "fecha") setDia(hoy);
};
async function cerrar() {
if (huboCambio.current) {
huboCambio.current = false;
await refrescarPantallasAction();
router.refresh();
}
onCerrar();
}
async function guardar() {
setTrab(true);
setError("");
const hh = horaElegida();
const r = await crearActividadLibreAction({
tipo, referenteTipo: ref.tipo, referenteId: ref.id, objetivo, dia: diaElegido, hora: tipo === "Tarea" && !realizada ? "16:00" : hh,
duracion: DUR[tipo], realizada, nota: realizada ? nota : "", participantes: [], canal: "movil",
});
setTrab(false);
if (!r.ok) return setError(r.error);
huboCambio.current = true;
setHecho({ ...r, dia: diaElegido, hora: hh });
}
async function deshacer() {
setTrab(true);
const r = await deshacerSeguimientoAction(hecho.accionId);
setTrab(false);
if (!r.ok) return setError(r.error);
setDeshecho(true);
}
const listo = !!ref && !!objetivo && (cuando !== "fecha" || (!!dia && !!hora));
const sheet = (
<div className="m-bd" onClick={cerrar}>
<div className="m-sheet" role="dialog" aria-modal="true" aria-label="Nueva actividad" onClick={(e) => e.stopPropagation()}>
<div className="m-grab" aria-hidden="true" />
<div className="m-sh-h">
<div className="m-sh-t">¿Qué quieres registrar?</div>
<button type="button" className="m-x" aria-label="Cerrar" onClick={cerrar}>✕</button>
</div>
{hecho ? (
<div className="m-ok">
<p className="m-okt">{deshecho ? "↩ Se canceló la actividad que acabas de crear." : hecho.completada ? "✓ Registrada como realizada en Dynamics" : "✓ Agendada en Dynamics"}</p>
{!deshecho && <p className="m-nota-s">{hecho.asunto} · {diaCortoES(hecho.dia)}{tipo !== "Tarea" || realizada ? ` · ${hecho.hora}` : " (vence 16:00)"}</p>}
{hecho.avisoOpp && <p className="m-aviso">{hecho.avisoOpp}</p>}
{error && <p className="m-err">{error}</p>}
<div className="m-fila-btn fin">
{!deshecho && !hecho.completada && <button type="button" className="m-btn" disabled={trab} onClick={deshacer}>{trab ? "…" : "↩ Deshacer"}</button>}
<button type="button" className="m-btn pri" onClick={cerrar}>Listo</button>
</div>
</div>
) : (
<>
<div className="m-seg">
{TIPOS.map(([k, l]) => <button key={k} type="button" className={tipo === k ? "on" : ""} onClick={() => setTipo(k)}>{l}</button>)}
</div>
{ref ? (
<div className="m-ref">
<span><small>{ref.tipo === "opportunity" ? "Oportunidad" : "Cuenta"}</small><b>{ref.nombre}</b></span>
{!preset.ref && <button type="button" className="m-lnk" onClick={() => { setRef(null); setQ(""); }}>Cambiar</button>}
</div>
) : (
<>
<input className="m-in full" autoFocus value={q} placeholder="🔍 ¿Con quién? cliente u oportunidad…" onChange={(e) => setQ(e.target.value)} aria-label="Buscar cliente u oportunidad" />
{buscando && <p className="m-nota-s">Buscando en Dynamics…</p>}
{res && !buscando && (
<div className="m-res">
{res.opps.length > 0 && <div className="m-grp">Oportunidades abiertas</div>}
{res.opps.map((o) => (
<button type="button" key={o.id} className="m-opt" onClick={() => { setRef({ tipo: "opportunity", id: o.id, nombre: o.cliente ? `${o.cliente} — ${o.nombre}` : o.nombre }); setObjetivo("Negociación"); }}>
<b>{o.cliente || o.nombre}</b><small>{o.nombre}{o.propietario ? ` · ${o.propietario}` : ""}</small>
</button>
))}
{res.cuentas.length > 0 && <div className="m-grp">Cuentas</div>}
{res.cuentas.map((c) => (
<button type="button" key={c.id} className="m-opt" onClick={() => { setRef({ tipo: "account", id: c.id, nombre: c.nombre }); setObjetivo("Prospección"); }}>
<b>{c.nombre}</b><small>{[c.tipo, c.propietario].filter(Boolean).join(" · ")}</small>
</button>
))}
{!res.opps.length && !res.cuentas.length && <p className="m-nota-s">Sin coincidencias. Prueba con otra parte del nombre.</p>}
</div>
)}
</>
)}
<div className="m-lbl">¿Cuándo?</div>
<div className="m-chips-w">
<button type="button" className={`m-chip${cuando === "ahora" ? " on" : ""}`} onClick={() => setCuando("ahora")}>Ahora</button>
{!realizada && hoyOpcion && <button type="button" className={`m-chip${cuando === "hoy" ? " on" : ""}`} onClick={() => setCuando("hoy")}>Hoy {hoyOpcion}</button>}
{!realizada && <button type="button" className={`m-chip${cuando === "manana" ? " on" : ""}`} onClick={() => setCuando("manana")}>{manana === addDays(hoy, 1) ? "Mañana" : diaCortoES(manana)} 9:00</button>}
<button type="button" className={`m-chip${cuando === "fecha" ? " on" : ""}`} onClick={() => setCuando("fecha")} aria-label="Elegir fecha y hora">📅</button>
</div>
{cuando === "fecha" && (
<div className="m-chips-w">
<input type="date" className="m-in" value={dia} min={realizada ? addDays(hoy, -30) : hoy} max={realizada ? hoy : addDays(hoy, 30)} onChange={(e) => setDia(e.target.value)} />
<input type="time" className="m-in" value={hora} onChange={(e) => setHora(e.target.value)} aria-label="Hora" />
</div>
)}
<label className="m-check">
<input type="checkbox" checked={realizada} onChange={(e) => alternarRealizada(e.target.checked)} />
<span>Ya la realicé <small>(por teléfono o WhatsApp)</small></span>
</label>
{realizada && (
<>
<textarea className="m-ta" rows={3} maxLength={1500} value={nota} placeholder="Resultado: ¿qué pasó y qué sigue?" onChange={(e) => setNota(e.target.value)} />
<div className="m-chips-w">
{(FRASES[tipo] || []).map((f) => <button key={f} type="button" className="m-chip" onClick={() => setNota((n) => (n.trim() ? `${n.trim()}. ${f}` : f))}>{f}</button>)}
</div>
</>
)}
<button type="button" className="m-lnk obj" onClick={() => setVerObj((v) => !v)}>Objetivo: <b>{objetivo}</b> {verObj ? "▴" : "▾"}</button>
{verObj && (
<select className="m-in full" value={objetivo} onChange={(e) => setObjetivo(e.target.value)}>
{OBJETIVOS_LIBRES.map((o) => <option key={o} value={o}>{o}</option>)}
</select>
)}
{error && <p className="m-err">{error}</p>}
<button type="button" className="m-btn pri" disabled={!listo || trab} onClick={guardar}>{trab ? "Guardando…" : "Guardar en Dynamics"}</button>
{realizada && horaAMin(horaElegida()) == null && <p className="m-err">Elige una hora.</p>}
</>
)}
</div>
</div>
);
return typeof document !== "undefined" ? createPortal(sheet, document.body) : null;
}