266 lines
12 KiB
JavaScript
266 lines
12 KiB
JavaScript
|
|
"use client";
|
||
|
|
import { useState, useRef } from "react";
|
||
|
|
import { useRouter } from "next/navigation";
|
||
|
|
import { abrirActividadAction, ejecutarAccionAction, deshacerAccionAction, refrescarPantallasAction } from "../../actividades/gestionActions";
|
||
|
|
import { actividadUrl } from "../../lib/constants";
|
||
|
|
import { addDays } from "../../lib/plan";
|
||
|
|
|
||
|
|
// Ventana emergente para completar, reprogramar o cancelar UNA actividad sin salir del informe. Pensada
|
||
|
|
// para pocos toques: fechas y horas por botones (no menús), nota breve con frases rápidas y «Deshacer».
|
||
|
|
// El mismo componente sirve luego a la versión móvil: no depende de la pantalla donde se abre.
|
||
|
|
|
||
|
|
const FRASES = {
|
||
|
|
Llamada: ["No contestó", "Dejé mensaje", "Habló con el decisor", "Interesado", "Pidió propuesta", "Llamar de nuevo"],
|
||
|
|
Cita: ["Visita realizada", "Se presentó la oferta", "Pidió ajustes", "Pasan a revisión interna", "Se definió fecha de firma"],
|
||
|
|
Tarea: ["Oferta enviada", "Contrato elaborado", "Seguimiento realizado", "Pendiente de respuesta del cliente"],
|
||
|
|
};
|
||
|
|
const HORAS = ["08:00", "09:00", "10:00", "11:00", "14:00", "15:00", "16:00"];
|
||
|
|
const DIAS = ["domingo", "lunes", "martes", "miércoles", "jueves", "viernes", "sábado"];
|
||
|
|
const MESES = ["ene", "feb", "mar", "abr", "may", "jun", "jul", "ago", "sep", "oct", "nov", "dic"];
|
||
|
|
|
||
|
|
const dow = (iso) => new Date(`${iso}T12:00:00Z`).getUTCDay();
|
||
|
|
const etiqueta = (iso) => {
|
||
|
|
const [y, m, d] = iso.split("-").map(Number);
|
||
|
|
return `${DIAS[dow(iso)]} ${d} ${MESES[m - 1]}`;
|
||
|
|
};
|
||
|
|
function proximoLunes(hoy) {
|
||
|
|
let d = addDays(hoy, 1);
|
||
|
|
while (dow(d) !== 1) d = addDays(d, 1);
|
||
|
|
return d;
|
||
|
|
}
|
||
|
|
const horaLocal = (iso) => {
|
||
|
|
if (!iso) return "";
|
||
|
|
const d = new Date(new Date(iso).getTime() - 6 * 3600 * 1000);
|
||
|
|
return `${String(d.getUTCHours()).padStart(2, "0")}:${String(d.getUTCMinutes()).padStart(2, "0")}`;
|
||
|
|
};
|
||
|
|
|
||
|
|
export default function GestionarActividad({ a, className, title, children }) {
|
||
|
|
const router = useRouter();
|
||
|
|
const [abierto, setAbierto] = useState(false);
|
||
|
|
const [carga, setCarga] = useState("idle"); // idle | cargando | listo | error
|
||
|
|
const [det, setDet] = useState(null);
|
||
|
|
const [error, setError] = useState("");
|
||
|
|
const [accion, setAccion] = useState("completar");
|
||
|
|
const [nota, setNota] = useState("");
|
||
|
|
const [dia, setDia] = useState("");
|
||
|
|
const [hora, setHora] = useState("");
|
||
|
|
const [confirma, setConfirma] = useState(false);
|
||
|
|
const [trabajando, setTrabajando] = useState(false);
|
||
|
|
const [hecho, setHecho] = useState(null); // { accionId, accion, ... }
|
||
|
|
const [deshecho, setDeshecho] = useState(false);
|
||
|
|
const huboCambio = useRef(false);
|
||
|
|
|
||
|
|
async function abrir() {
|
||
|
|
setAbierto(true);
|
||
|
|
setCarga("cargando");
|
||
|
|
setError("");
|
||
|
|
setHecho(null);
|
||
|
|
setDeshecho(false);
|
||
|
|
setConfirma(false);
|
||
|
|
setNota("");
|
||
|
|
setAccion("completar");
|
||
|
|
const r = await abrirActividadAction({ tipo: a.tipo, id: a.id });
|
||
|
|
if (!r.ok) {
|
||
|
|
setError(r.error);
|
||
|
|
setCarga("error");
|
||
|
|
return;
|
||
|
|
}
|
||
|
|
setDet(r.actividad);
|
||
|
|
setDia(r.actividad.hoy);
|
||
|
|
setHora(horaLocal(r.actividad.scheduledstart) || "09:00");
|
||
|
|
setCarga(r.apagado ? "apagado" : "listo");
|
||
|
|
}
|
||
|
|
|
||
|
|
async function cerrar() {
|
||
|
|
setAbierto(false);
|
||
|
|
if (huboCambio.current) {
|
||
|
|
huboCambio.current = false;
|
||
|
|
await refrescarPantallasAction(); // vacía la caché de datos de las pantallas afectadas
|
||
|
|
router.refresh();
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
async function ejecutar() {
|
||
|
|
if (accion === "completar" && !nota.trim() && !confirma) {
|
||
|
|
setConfirma(true);
|
||
|
|
return;
|
||
|
|
}
|
||
|
|
if (accion === "cancelar" && !confirma) {
|
||
|
|
setConfirma(true);
|
||
|
|
return;
|
||
|
|
}
|
||
|
|
setTrabajando(true);
|
||
|
|
setError("");
|
||
|
|
const r = await ejecutarAccionAction({ tipo: a.tipo, id: a.id, accion, nota, dia, hora });
|
||
|
|
setTrabajando(false);
|
||
|
|
if (!r.ok) {
|
||
|
|
setError(r.error);
|
||
|
|
setConfirma(false);
|
||
|
|
return;
|
||
|
|
}
|
||
|
|
huboCambio.current = true;
|
||
|
|
setHecho(r);
|
||
|
|
}
|
||
|
|
|
||
|
|
async function deshacer() {
|
||
|
|
setTrabajando(true);
|
||
|
|
setError("");
|
||
|
|
const r = await deshacerAccionAction(hecho.accionId);
|
||
|
|
setTrabajando(false);
|
||
|
|
if (!r.ok) {
|
||
|
|
setError(r.error);
|
||
|
|
return;
|
||
|
|
}
|
||
|
|
setDeshecho(true);
|
||
|
|
}
|
||
|
|
|
||
|
|
const cerrada = det && det.estado !== "abierta";
|
||
|
|
const conInvitados = det?.tipo === "Cita" && det.invitados > 0;
|
||
|
|
const bloqueaFecha = conInvitados && (accion === "reprogramar" || accion === "cancelar");
|
||
|
|
const hoy = det?.hoy;
|
||
|
|
const rapidos = hoy
|
||
|
|
? [["Hoy", hoy], ["Mañana", addDays(hoy, 1)], ["Pasado mañana", addDays(hoy, 2)], ["Lunes", proximoLunes(hoy)]]
|
||
|
|
: [];
|
||
|
|
const esTarea = a.tipo === "Tarea";
|
||
|
|
const crm = actividadUrl({ tipo: a.tipo, id: a.id });
|
||
|
|
const fraseDe = (f) => setNota((n) => (n.trim() ? `${n.trim()}. ${f}` : f));
|
||
|
|
|
||
|
|
const textoAccion = { completar: "Completar", reprogramar: "Reprogramar", cancelar: "Cancelar actividad" }[accion];
|
||
|
|
|
||
|
|
return (
|
||
|
|
<>
|
||
|
|
<button type="button" className={className} title={title} onClick={abrir}>
|
||
|
|
{children}
|
||
|
|
</button>
|
||
|
|
{abierto && (
|
||
|
|
<div className="gst-bd" onClick={cerrar}>
|
||
|
|
<div className="gst" role="dialog" aria-modal="true" aria-label="Gestionar actividad" onClick={(e) => e.stopPropagation()}>
|
||
|
|
<div className="gst-h">
|
||
|
|
<div>
|
||
|
|
<div className="gst-t">{a.tipo} · {det?.asunto || a.asunto}</div>
|
||
|
|
<div className="gst-s">
|
||
|
|
{det?.referente ? `${det.referente} · ` : ""}
|
||
|
|
{det?.scheduledend ? `Para el ${det.scheduledend.slice(0, 10).split("-").reverse().join("/")}` : ""}
|
||
|
|
{det?.owner ? ` · ${det.owner}` : ""}
|
||
|
|
</div>
|
||
|
|
</div>
|
||
|
|
<button type="button" className="gst-x" aria-label="Cerrar" onClick={cerrar}>✕</button>
|
||
|
|
</div>
|
||
|
|
|
||
|
|
{carga === "cargando" && <p className="gst-msg">Cargando desde Dynamics…</p>}
|
||
|
|
{carga === "error" && <p className="gst-err">{error}</p>}
|
||
|
|
{carga === "apagado" && <p className="gst-err">La gestión de actividades está en pausa por mantenimiento. Mientras tanto, <a href={crm} target="_blank" rel="noopener">ábrela en Dynamics</a>.</p>}
|
||
|
|
|
||
|
|
{carga === "listo" && det && !hecho && (
|
||
|
|
<>
|
||
|
|
{det.enNombreDeOtro && <p className="gst-aviso">Estás actuando en nombre de {det.owner}.</p>}
|
||
|
|
{cerrada ? (
|
||
|
|
<p className="gst-msg">Esta actividad ya está {det.estado}. <a href={crm} target="_blank" rel="noopener">Abrir en Dynamics ↗</a></p>
|
||
|
|
) : (
|
||
|
|
<>
|
||
|
|
<div className="gst-tabs">
|
||
|
|
{[["completar", "✓ Completar"], ["reprogramar", "📅 Reprogramar"], ["cancelar", "✕ Cancelar"]].map(([k, l]) => (
|
||
|
|
<button key={k} type="button" className={accion === k ? "on" : ""} onClick={() => { setAccion(k); setConfirma(false); setError(""); }}>{l}</button>
|
||
|
|
))}
|
||
|
|
</div>
|
||
|
|
|
||
|
|
{bloqueaFecha && (
|
||
|
|
<p className="gst-aviso">
|
||
|
|
Esta cita tiene {det.invitados} invitado{det.invitados === 1 ? "" : "s"}. Para no enviarles avisos por error, {accion === "cancelar" ? "cancélala" : "reprográmala"} directamente en Dynamics.{" "}
|
||
|
|
<a href={crm} target="_blank" rel="noopener">Abrir en Dynamics ↗</a>
|
||
|
|
</p>
|
||
|
|
)}
|
||
|
|
|
||
|
|
{accion === "reprogramar" && !bloqueaFecha && (
|
||
|
|
<div className="gst-sec">
|
||
|
|
<div className="gst-lbl">Nueva fecha</div>
|
||
|
|
<div className="gst-chips">
|
||
|
|
{rapidos.map(([l, v]) => (
|
||
|
|
<button key={l} type="button" className={`gst-chip${dia === v ? " on" : ""}`} onClick={() => setDia(v)}>{l}</button>
|
||
|
|
))}
|
||
|
|
<input type="date" className="gst-in" value={dia} min={hoy} max={addDays(hoy, 30)} onChange={(e) => setDia(e.target.value)} />
|
||
|
|
</div>
|
||
|
|
{!esTarea && (
|
||
|
|
<>
|
||
|
|
<div className="gst-lbl">Hora</div>
|
||
|
|
<div className="gst-chips">
|
||
|
|
{HORAS.map((h) => (
|
||
|
|
<button key={h} type="button" className={`gst-chip${hora === h ? " on" : ""}`} onClick={() => setHora(h)}>{h}</button>
|
||
|
|
))}
|
||
|
|
<input type="time" className="gst-in" value={hora} onChange={(e) => setHora(e.target.value)} />
|
||
|
|
</div>
|
||
|
|
</>
|
||
|
|
)}
|
||
|
|
{dia && <p className="gst-res">Nueva fecha: <strong>{etiqueta(dia)}{!esTarea && hora ? ` · ${hora}` : ""}</strong>{esTarea ? " (vence a las 16:00)" : ""}</p>}
|
||
|
|
</div>
|
||
|
|
)}
|
||
|
|
|
||
|
|
{accion !== "reprogramar" && !bloqueaFecha && (
|
||
|
|
<div className="gst-sec">
|
||
|
|
<div className="gst-lbl">{accion === "completar" ? "Nota breve: qué pasó y qué sigue" : "Motivo (opcional)"}</div>
|
||
|
|
<textarea
|
||
|
|
className="gst-ta"
|
||
|
|
rows={3}
|
||
|
|
maxLength={1500}
|
||
|
|
value={nota}
|
||
|
|
placeholder={accion === "completar" ? "Ej.: Habló con el gerente, pidió ajustar la oferta" : "Ej.: El cliente ya no está interesado"}
|
||
|
|
onChange={(e) => { setNota(e.target.value); setConfirma(false); }}
|
||
|
|
/>
|
||
|
|
{accion === "completar" && (
|
||
|
|
<div className="gst-chips">
|
||
|
|
{(FRASES[a.tipo] || []).map((f) => (
|
||
|
|
<button key={f} type="button" className="gst-chip" onClick={() => fraseDe(f)}>{f}</button>
|
||
|
|
))}
|
||
|
|
</div>
|
||
|
|
)}
|
||
|
|
{a.tipo === "Cita" && <p className="gst-ayuda">La nota se guarda en «Resultado de la visita». La descripción de la cita (la invitación) no se toca.</p>}
|
||
|
|
</div>
|
||
|
|
)}
|
||
|
|
|
||
|
|
{error && <p className="gst-err">{error}</p>}
|
||
|
|
{confirma && accion === "completar" && <p className="gst-aviso">No escribiste nota. La nota ayuda a ver el historial de la oportunidad. ¿Completar sin nota?</p>}
|
||
|
|
{confirma && accion === "cancelar" && <p className="gst-aviso">¿Seguro que quieres cancelar esta actividad? Podrás deshacerlo justo después.</p>}
|
||
|
|
|
||
|
|
<div className="gst-pie">
|
||
|
|
<a className="gst-link" href={crm} target="_blank" rel="noopener">Abrir en Dynamics ↗</a>
|
||
|
|
<button type="button" className="gst-sec-btn" onClick={cerrar}>Cerrar</button>
|
||
|
|
<button
|
||
|
|
type="button"
|
||
|
|
className={`gst-go${accion === "cancelar" ? " pel" : ""}`}
|
||
|
|
disabled={trabajando || bloqueaFecha || (accion === "reprogramar" && (!dia || (!esTarea && !hora)))}
|
||
|
|
onClick={ejecutar}
|
||
|
|
>
|
||
|
|
{trabajando ? "Guardando…" : confirma ? (accion === "completar" ? "Sí, completar sin nota" : "Sí, cancelar") : textoAccion}
|
||
|
|
</button>
|
||
|
|
</div>
|
||
|
|
</>
|
||
|
|
)}
|
||
|
|
</>
|
||
|
|
)}
|
||
|
|
|
||
|
|
{hecho && (
|
||
|
|
<div className="gst-ok">
|
||
|
|
<p className="gst-okt">
|
||
|
|
{deshecho
|
||
|
|
? "↩ Se deshizo: la actividad volvió a como estaba."
|
||
|
|
: hecho.accion === "completar"
|
||
|
|
? "✓ Actividad completada en Dynamics"
|
||
|
|
: hecho.accion === "cancelar"
|
||
|
|
? "✓ Actividad cancelada en Dynamics"
|
||
|
|
: `✓ Reprogramada para el ${etiqueta(dia)}${!esTarea ? ` a las ${hora}` : ""}`}
|
||
|
|
</p>
|
||
|
|
{error && <p className="gst-err">{error}</p>}
|
||
|
|
<div className="gst-pie">
|
||
|
|
<a className="gst-link" href={crm} target="_blank" rel="noopener">Abrir en Dynamics ↗</a>
|
||
|
|
{!deshecho && <button type="button" className="gst-sec-btn" disabled={trabajando} onClick={deshacer}>{trabajando ? "…" : "↩ Deshacer"}</button>}
|
||
|
|
<button type="button" className="gst-go" onClick={cerrar}>Listo</button>
|
||
|
|
</div>
|
||
|
|
</div>
|
||
|
|
)}
|
||
|
|
</div>
|
||
|
|
</div>
|
||
|
|
)}
|
||
|
|
</>
|
||
|
|
);
|
||
|
|
}
|