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

395 lines
24 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 Link from "next/link";
import { useRouter } from "next/navigation";
import {
abrirActividadAction, ejecutarAccionAction, deshacerAccionAction, refrescarPantallasAction, crearSeguimientoAction, deshacerSeguimientoAction,
editarActividadAction, deshacerEdicionAction,
} from "../../actividades/gestionActions";
import { contactoReferenteAction } from "../campoActions";
import { FRASES } from "../../components/actividades/GestionarActividad";
import BotonesContacto from "./BotonesContacto";
import { ROLES } from "../../lib/participantes";
import { AGENDADOR, OBJETIVOS_LIBRES, horasLibres, horaAMin, localDeIso, minAHora } from "../../lib/agendador";
import { addDays, esHabil } from "../../lib/plan";
import { ICONO_TIPO, ROTULO_TIPO } from "../../lib/agendaDia";
import { diaCortoES } from "../../lib/campo";
import { money, registroUrl, actividadUrl } from "../../lib/constants";
// Hoja de acciones (hoja inferior) de UNA actividad, pensada para la calle: contactar, ver participantes, escribir el
// RESULTADO y completar en un toque. Toda escritura pasa por las MISMAS acciones de servidor de la web
// (actividades/gestionActions.js): reglas, permisos, deshacer y bitácora son los de siempre.
const HORAS = ["08:30", "09:00", "10:00", "11:00", "14:00", "15:00", "16:00"];
const proximoLunes = (hoy) => {
let d = addDays(hoy, 1);
while (new Date(`${d}T12:00:00Z`).getUTCDay() !== 1) d = addDays(d, 1);
return d;
};
export default function HojaActividad({ item, onCerrar }) {
const router = useRouter();
const [det, setDet] = useState(null);
const [contacto, setContacto] = useState(null);
const [error, setError] = useState("");
const [vista, setVista] = useState("main"); // main | seg | repro | edit | cancelar
const [nota, setNota] = useState("");
const [roles, setRoles] = useState([]);
const [confirma, setConfirma] = useState(false);
const [trab, setTrab] = useState(false);
const [hecho, setHecho] = useState(null); // { accionId, accion, ... }
const [deshecho, setDeshecho] = useState(false);
const [seg, setSeg] = useState(null); // seguimiento creado { accionId, tipo, dia, hora }
const [segError, setSegError] = useState("");
// seguimiento
const [segTipo, setSegTipo] = useState("Llamada");
const [segObj, setSegObj] = useState("");
const [segDia, setSegDia] = useState("");
const [segHora, setSegHora] = useState("");
// reprogramar
const [dia, setDia] = useState("");
const [hora, setHora] = useState("09:00");
// editar
const [objEd, setObjEd] = useState("");
const [durEd, setDurEd] = useState(null);
const [notaEd, setNotaEd] = useState("");
const huboCambio = useRef(false);
const notaRef = useRef(null);
useEffect(() => {
let vivo = true;
(async () => {
const [r, c] = await Promise.all([
abrirActividadAction({ tipo: item.tipo, id: item.id }),
item.etn ? contactoReferenteAction({ tipo: item.etn, id: item.refId }) : Promise.resolve(null),
]);
if (!vivo) return;
if (c?.ok) setContacto(c);
else if (c) setContacto({ destinos: [], cuenta: null });
if (!r.ok) return setError(r.error);
const a = r.actividad;
setDet({ ...a, apagado: r.apagado });
setRoles(a.participantes || []);
setObjEd(OBJETIVOS_LIBRES.includes(a.objetivo) ? a.objetivo : "");
setDurEd(a.duracion || null);
setSegTipo(item.tipo === "Cita" ? "Llamada" : item.tipo);
setSegObj(OBJETIVOS_LIBRES.includes(a.objetivo) ? a.objetivo : "");
setDia(a.hoy);
let sig = addDays(a.hoy, 1);
while (!esHabil(sig)) sig = addDays(sig, 1);
setSegDia(sig);
})();
return () => { vivo = false; };
}, [item.id, item.tipo, item.etn, item.refId]);
async function cerrar() {
if (hecho && hecho.accion === "completar" && !deshecho && vista === "seg" && !seg && !window.confirm("Tienes un seguimiento sin guardar. ¿Cerrar sin guardarlo?")) return;
if (huboCambio.current) {
huboCambio.current = false;
await refrescarPantallasAction();
router.refresh();
}
onCerrar();
}
const cerrada = det && det.estado !== "abierta";
const conInvitados = det?.tipo === "Cita" && det.invitados > 0;
const esTarea = item.tipo === "Tarea";
const hoy = det?.hoy;
const ahoraMin = localDeIso(new Date().toISOString()).min;
const bloquesHoy = det?.hoyAgenda?.bloques || [];
const horasSeg = hoy ? horasLibres({ tipo: segTipo, dia: segDia, hoy, ahoraMin, bloques: bloquesHoy }) : [];
const horaSeg = horasSeg.includes(segHora) ? segHora : horasSeg[0] || "";
const hoyHabil = !!hoy && esHabil(hoy);
const cupoHoy = hoyHabil && (segTipo === "Tarea" ? ahoraMin < AGENDADOR.horaTarea : horasLibres({ tipo: segTipo, dia: hoy, hoy, ahoraMin, bloques: bloquesHoy }).length > 0)
&& (det?.hoyAgenda?.cuenta?.[segTipo] ?? 0) < AGENDADOR.topes[segTipo];
const segSinHoras = segTipo !== "Tarea" && !!segDia && horasSeg.length === 0;
const segListo = !!segObj && !!segDia && esHabil(segDia) && !segSinHoras;
const horaPasada = !esTarea && dia === hoy && (horaAMin(hora) ?? 9999) < ahoraMin;
const muestraPart = item.tipo === "Cita" || det?.tieneOpp;
const noContestó = /no contest/i.test(nota);
const frase = (f) => { setNota((n) => (n.trim() ? `${n.trim()}. ${f}` : f)); setConfirma(false); };
const alternarRol = (c) => setRoles((x) => (x.includes(c) ? x.filter((y) => y !== c) : [...x, c]));
async function guardarSeg() {
setSegError("");
const r = await crearSeguimientoAction({ tipo: item.tipo, id: item.id, nuevoTipo: segTipo, objetivo: segObj, dia: segDia, hora: segTipo === "Tarea" ? "" : horaSeg });
if (!r.ok) { setSegError(r.error); return false; }
huboCambio.current = true;
setSeg(r);
return true;
}
async function ejecutar(accion, { conSeg = false } = {}) {
setError("");
if (accion === "completar" && !nota.trim() && !confirma) return setConfirma(true);
setTrab(true);
const r = await ejecutarAccionAction({ tipo: item.tipo, id: item.id, accion, nota, dia, hora, participantes: accion === "completar" ? roles : [] });
if (!r.ok) { setTrab(false); setConfirma(false); return setError(r.error); }
huboCambio.current = true;
setHecho(r);
setVista("main");
if (accion === "completar" && conSeg && det?.tieneOpp) await guardarSeg();
setTrab(false);
}
async function guardarEdicion() {
setTrab(true);
setError("");
const r = await editarActividadAction({ tipo: item.tipo, id: item.id, objetivo: objEd, duracion: esTarea ? null : durEd, nota: notaEd, participantes: item.tipo === "Cita" || item.tipo === "Llamada" ? roles : null });
setTrab(false);
if (!r.ok) return setError(r.error);
huboCambio.current = true;
setHecho(r);
setVista("main");
}
async function deshacer() {
setTrab(true);
setError("");
const r = hecho.accion === "editar" ? await deshacerEdicionAction(hecho.accionId) : await deshacerAccionAction(hecho.accionId);
setTrab(false);
if (!r.ok) return setError(r.error);
setDeshecho(true);
}
async function deshacerSeg() {
setTrab(true);
const r = await deshacerSeguimientoAction(seg.accionId);
setTrab(false);
if (!r.ok) return setSegError(r.error);
setSeg(null);
setSegError("");
}
// «No contestó» → «Llamar de nuevo hoy, más tarde»: la primera hora libre de hoy con al menos 30 min de margen.
async function llamarDeNuevo() {
const hs = horasLibres({ tipo: "Llamada", dia: hoy, hoy, ahoraMin: ahoraMin + 25, bloques: bloquesHoy });
if (!hs.length) return setSegError("Ya no quedan horas libres hoy. Usa «Reprogramar» o agenda otro día.");
setTrab(true);
setSegError("");
const r = await crearSeguimientoAction({ tipo: item.tipo, id: item.id, nuevoTipo: "Llamada", objetivo: OBJETIVOS_LIBRES.includes(det?.objetivo) ? det.objetivo : "Negociación", dia: hoy, hora: hs[0] });
setTrab(false);
if (!r.ok) return setSegError(r.error);
huboCambio.current = true;
setSeg(r);
}
const titulo = item.cliente || item.oppNombre || "Actividad";
const subt = [ROTULO_TIPO[item.tipo], item.hora, item.objetivo, item.valor != null ? money(item.valor) : null].filter(Boolean).join(" · ");
const crm = actividadUrl({ tipo: item.tipo, id: item.id });
const enlaceRef = item.etn === "opportunity" ? { href: `/m/oportunidad/${item.refId}`, txt: "💼 Oportunidad" } : item.etn === "account" ? { href: `/m/cuentas/${item.refId}`, txt: "🏢 Cuenta" } : null;
const extraRef = enlaceRef ? <Link className="m-acc" href={enlaceRef.href} onClick={cerrar}><i>{enlaceRef.txt.slice(0, 2)}</i>{enlaceRef.txt.slice(3)}</Link> : <a className="m-acc" href={registroUrl(item.etn || "incident", item.refId)} target="_blank" rel="noopener"><i>↗</i>Dynamics</a>;
const sheet = (
<div className="m-bd" onClick={cerrar}>
<div className="m-sheet" role="dialog" aria-modal="true" aria-label="Acciones de la actividad" onClick={(e) => e.stopPropagation()}>
<div className="m-grab" aria-hidden="true" />
<div className="m-sh-h">
<div>
<div className="m-sh-t">{ICONO_TIPO[item.tipo]} {titulo}</div>
<div className="m-sh-s">{subt}{item.oppNombre ? ` · ${item.oppNombre}` : ""}</div>
</div>
<button type="button" className="m-x" aria-label="Cerrar" onClick={cerrar}>✕</button>
</div>
<BotonesContacto info={contacto} extra={extraRef} />
{!det && !error && <p className="m-msg">Cargando desde Dynamics…</p>}
{error && !det && <p className="m-err">{error}</p>}
{det?.apagado && <p className="m-err">La gestión de actividades está en pausa por mantenimiento. <a href={crm} target="_blank" rel="noopener">Ábrela en Dynamics ↗</a></p>}
{det && !det.apagado && !hecho && (
cerrada ? (
<p className="m-msg">Esta actividad ya está {det.estado}.{det.nota ? <><br /><b>Resultado:</b> {det.nota}</> : null}</p>
) : (
<>
{det.enNombreDeOtro && <p className="m-aviso">Estás actuando en nombre de {det.owner}.</p>}
{det.nota && <p className="m-prev"><b>{item.tipo === "Cita" ? "Resultado" : "Nota"} previo:</b> {det.nota}</p>}
{vista === "main" && (
<>
{muestraPart && (
<>
<div className="m-lbl">Participantes</div>
<div className="m-chips-w">
{ROLES.map((r) => (
<button key={r.codigo} type="button" className={`m-chip${roles.includes(r.codigo) ? " on" : ""}`} aria-pressed={roles.includes(r.codigo)} onClick={() => alternarRol(r.codigo)}>{r.nombre}</button>
))}
</div>
</>
)}
<div className="m-lbl">Resultado: ¿qué pasó y qué sigue?</div>
<textarea ref={notaRef} className="m-ta" rows={3} maxLength={1500} value={nota} placeholder="Ej.: Habló con el decisor. Pidió ajustar el precio." onChange={(e) => { setNota(e.target.value); setConfirma(false); }} />
<div className="m-chips-w">
{(FRASES[item.tipo] || []).map((f) => <button key={f} type="button" className="m-chip" onClick={() => frase(f)}>{f}</button>)}
</div>
{confirma && <p className="m-aviso">No escribiste el resultado. Ayuda a ver el historial de la oportunidad. ¿Completar sin resultado?</p>}
{error && <p className="m-err">{error}</p>}
<button type="button" className="m-btn pri" disabled={trab} onClick={() => ejecutar("completar")}>
{trab ? "Guardando…" : confirma ? "Sí, completar sin resultado" : "✓ Completar con este resultado"}
</button>
<div className="m-fila-btn">
{det.tieneOpp && <button type="button" className="m-btn" onClick={() => { setVista("seg"); setConfirma(false); }}>+ Completar y seguimiento</button>}
<button type="button" className="m-btn" onClick={() => { setVista("repro"); setError(""); }}>↻ Reprogramar</button>
<button type="button" className="m-btn sq" aria-label="Editar sin completar" onClick={() => { setVista("edit"); setError(""); }}>✎</button>
<button type="button" className="m-btn sq pel" aria-label="Cancelar actividad" onClick={() => { setVista("cancelar"); setError(""); }}>✕</button>
</div>
</>
)}
{vista === "seg" && (
<>
<div className="m-vol"><button type="button" onClick={() => setVista("main")}>‹ Volver</button><b>Seguimiento</b></div>
<div className="m-chips-w">
{["Llamada", "Cita", "Tarea"].map((t) => <button key={t} type="button" className={`m-chip${segTipo === t ? " on" : ""}`} onClick={() => setSegTipo(t)}>{ICONO_TIPO[t]} {ROTULO_TIPO[t]}</button>)}
</div>
<div className="m-lbl">Objetivo</div>
<select className="m-in" value={segObj} onChange={(e) => setSegObj(e.target.value)}>
<option value="">Elige un objetivo…</option>
{OBJETIVOS_LIBRES.map((o) => <option key={o} value={o}>{o}</option>)}
</select>
<div className="m-lbl">Cuándo (lunes a viernes)</div>
<div className="m-chips-w">
{hoyHabil && <button type="button" className={`m-chip${segDia === hoy ? " on" : ""}`} disabled={!cupoHoy} onClick={() => setSegDia(hoy)}>{cupoHoy ? "Hoy, más tarde" : "Hoy: sin horas"}</button>}
{[["Mañana", addDays(hoy, 1)], ["En 2 días", addDays(hoy, 2)], ["Lunes", proximoLunes(hoy)]].map(([l, v]) => <button key={l} type="button" className={`m-chip${segDia === v ? " on" : ""}`} onClick={() => setSegDia(v)}>{l}</button>)}
<input type="date" className="m-in" value={segDia} min={hoy} max={addDays(hoy, 30)} onChange={(e) => setSegDia(e.target.value)} />
</div>
{segTipo !== "Tarea" && (
<select className="m-in" value={horaSeg} onChange={(e) => setSegHora(e.target.value)} aria-label="Hora del seguimiento">
{horasSeg.map((h) => <option key={h} value={h}>{h}</option>)}
</select>
)}
{segDia && !esHabil(segDia) && <p className="m-err">Elige un día hábil: no se agenda en sábado ni domingo.</p>}
{segSinHoras && esHabil(segDia) && <p className="m-err">{segDia === hoy ? "Ya no quedan horas libres hoy." : "No hay horas disponibles ese día."}</p>}
{segListo && <p className="m-res">Se agenda: <b>{ROTULO_TIPO[segTipo]} · {diaCortoES(segDia)}{segTipo !== "Tarea" ? ` · ${horaSeg}` : " (vence 16:00)"}</b></p>}
<div className="m-lbl">Resultado de esta actividad</div>
<textarea className="m-ta" rows={2} maxLength={1500} value={nota} onChange={(e) => setNota(e.target.value)} placeholder="Qué pasó…" />
{error && <p className="m-err">{error}</p>}
<button type="button" className="m-btn pri" disabled={trab || !segListo} onClick={() => ejecutar("completar", { conSeg: true })}>{trab ? "Guardando…" : "Completar y agendar seguimiento"}</button>
</>
)}
{vista === "repro" && (
<>
<div className="m-vol"><button type="button" onClick={() => setVista("main")}>‹ Volver</button><b>Reprogramar</b></div>
{conInvitados ? (
<p className="m-aviso">Esta visita tiene {det.invitados} invitado{det.invitados === 1 ? "" : "s"}. Reprográmala en Dynamics para no enviarles avisos por error. <a href={crm} target="_blank" rel="noopener">Abrir en Dynamics ↗</a></p>
) : (
<>
<div className="m-chips-w">
{[["Hoy", hoy], ["Mañana", addDays(hoy, 1)], ["Pasado mañana", addDays(hoy, 2)], ["Lunes", proximoLunes(hoy)]].map(([l, v]) => <button key={l} type="button" className={`m-chip${dia === v ? " on" : ""}`} onClick={() => setDia(v)}>{l}</button>)}
<input type="date" className="m-in" value={dia} min={hoy} max={addDays(hoy, 30)} onChange={(e) => setDia(e.target.value)} />
</div>
{!esTarea && (
<>
<div className="m-lbl">Hora</div>
<div className="m-chips-w">
{HORAS.filter((h) => dia !== hoy || horaAMin(h) >= ahoraMin + 5).map((h) => <button key={h} type="button" className={`m-chip${hora === h ? " on" : ""}`} onClick={() => setHora(h)}>{h}</button>)}
<input type="time" className="m-in" value={hora} onChange={(e) => setHora(e.target.value)} />
</div>
</>
)}
{horaPasada && <p className="m-err">Esa hora ya pasó. Elige una más tarde o cambia el día.</p>}
{error && <p className="m-err">{error}</p>}
<button type="button" className="m-btn pri" disabled={trab || !dia || (!esTarea && !hora) || horaPasada} onClick={() => ejecutar("reprogramar")}>{trab ? "Guardando…" : "Guardar nueva fecha"}</button>
</>
)}
</>
)}
{vista === "edit" && (
<>
<div className="m-vol"><button type="button" onClick={() => setVista("main")}>‹ Volver</button><b>Editar sin completar</b></div>
<div className="m-lbl">Objetivo</div>
<select className="m-in" value={objEd} onChange={(e) => setObjEd(e.target.value)}>
<option value="">Sin cambio</option>
{OBJETIVOS_LIBRES.map((o) => <option key={o} value={o}>{o}</option>)}
</select>
{!esTarea && !conInvitados && (
<>
<div className="m-lbl">Duración</div>
<div className="m-chips-w">
{(item.tipo === "Cita" ? [30, 60, 90, 120] : [10, 15, 30, 45, 60]).map((m) => <button key={m} type="button" className={`m-chip${durEd === m ? " on" : ""}`} onClick={() => setDurEd(m)}>{m} min</button>)}
</div>
</>
)}
<div className="m-lbl">Agregar una nota (se suma arriba de lo anterior)</div>
<textarea className="m-ta" rows={3} maxLength={1500} value={notaEd} onChange={(e) => setNotaEd(e.target.value)} placeholder="Ej.: Llevar la propuesta actualizada" />
{error && <p className="m-err">{error}</p>}
<button type="button" className="m-btn pri" disabled={trab} onClick={guardarEdicion}>{trab ? "Guardando…" : "Guardar cambios"}</button>
</>
)}
{vista === "cancelar" && (
<>
<div className="m-vol"><button type="button" onClick={() => setVista("main")}>‹ Volver</button><b>Cancelar actividad</b></div>
{conInvitados ? (
<p className="m-aviso">Esta visita tiene invitados. Cancélala en Dynamics para no enviarles avisos por error. <a href={crm} target="_blank" rel="noopener">Abrir en Dynamics ↗</a></p>
) : (
<>
<p className="m-aviso">¿Seguro que quieres cancelar esta actividad? Podrás deshacerlo justo después.</p>
{error && <p className="m-err">{error}</p>}
<button type="button" className="m-btn pri pel" disabled={trab} onClick={() => ejecutar("cancelar")}>{trab ? "Cancelando…" : "Sí, cancelar actividad"}</button>
</>
)}
</>
)}
</>
)
)}
{hecho && (
<div className="m-ok">
<p className="m-okt">
{deshecho ? "↩ Se deshizo: la actividad volvió a como estaba."
: hecho.accion === "completar" ? `✓ ${ROTULO_TIPO[item.tipo]} completada en Dynamics`
: hecho.accion === "editar" ? "✓ Cambios guardados en Dynamics"
: hecho.accion === "cancelar" ? "✓ Actividad cancelada en Dynamics"
: `✓ Reprogramada para el ${diaCortoES(dia)}${!esTarea ? ` a las ${hora}` : ""}`}
</p>
{!deshecho && hecho.opp?.marcoGV && <p className="m-nota-s">Se marcó «Participación de GV» en la oportunidad.</p>}
{!deshecho && hecho.opp?.roles && <p className="m-nota-s">Se sumó a la oportunidad: {hecho.opp.roles}.</p>}
{hecho.avisoOpp && <p className="m-aviso">{hecho.avisoOpp}</p>}
{seg && (
<p className="m-okt s">✓ Seguimiento: {ROTULO_TIPO[seg.tipo]} · {diaCortoES(seg.dia)}{seg.hora ? ` ${seg.hora}` : ""}{" "}
<button type="button" className="m-lnk" disabled={trab} onClick={deshacerSeg}>↩ Deshacer</button></p>
)}
{!deshecho && !seg && hecho.accion === "completar" && item.tipo === "Llamada" && noContestó && det?.tieneOpp && hoyHabil && (
<button type="button" className="m-btn" disabled={trab} onClick={llamarDeNuevo}>📞 Llamar de nuevo hoy, más tarde</button>
)}
{!deshecho && !seg && hecho.accion === "completar" && det?.tieneOpp && vista !== "seg" && !(item.tipo === "Llamada" && noContestó && hoyHabil) && (
<button type="button" className="m-btn" onClick={() => setVista("seg")}>+ Programar seguimiento</button>
)}
{vista === "seg" && !seg && hecho.accion === "completar" && !deshecho && (
<>
<div className="m-chips-w">
{["Llamada", "Cita", "Tarea"].map((t) => <button key={t} type="button" className={`m-chip${segTipo === t ? " on" : ""}`} onClick={() => setSegTipo(t)}>{ICONO_TIPO[t]} {ROTULO_TIPO[t]}</button>)}
</div>
<select className="m-in" value={segObj} onChange={(e) => setSegObj(e.target.value)}>
<option value="">Objetivo…</option>
{OBJETIVOS_LIBRES.map((o) => <option key={o} value={o}>{o}</option>)}
</select>
<div className="m-chips-w">
{hoyHabil && <button type="button" className={`m-chip${segDia === hoy ? " on" : ""}`} disabled={!cupoHoy} onClick={() => setSegDia(hoy)}>Hoy, más tarde</button>}
{[["Mañana", addDays(hoy, 1)], ["En 2 días", addDays(hoy, 2)], ["Lunes", proximoLunes(hoy)]].map(([l, v]) => <button key={l} type="button" className={`m-chip${segDia === v ? " on" : ""}`} onClick={() => setSegDia(v)}>{l}</button>)}
</div>
{segTipo !== "Tarea" && <select className="m-in" value={horaSeg} onChange={(e) => setSegHora(e.target.value)}>{horasSeg.map((h) => <option key={h} value={h}>{h}</option>)}</select>}
<button type="button" className="m-btn pri" disabled={trab || !segListo} onClick={async () => { setTrab(true); await guardarSeg(); setTrab(false); }}>Guardar seguimiento</button>
</>
)}
{segError && <p className="m-err">{segError}</p>}
{error && <p className="m-err">{error}</p>}
<div className="m-fila-btn fin">
{!deshecho && <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>
)}
<a className="m-dyn" href={crm} target="_blank" rel="noopener">Abrir actividad en Dynamics ↗</a>
</div>
</div>
);
return typeof document !== "undefined" ? createPortal(sheet, document.body) : null;
}