301 lines
15 KiB
JavaScript
301 lines
15 KiB
JavaScript
|
|
"use client";
|
||
|
|
import { useState, useEffect, useRef } from "react";
|
||
|
|
import { useRouter } from "next/navigation";
|
||
|
|
import { buscarReferentesAction, crearActividadLibreAction } from "../../cuentas/cuentasActions";
|
||
|
|
import { deshacerSeguimientoAction, refrescarPantallasAction } from "../../actividades/gestionActions";
|
||
|
|
import { OBJETIVOS_LIBRES } from "../../lib/agendador";
|
||
|
|
import { ROLES } from "../../lib/participantes";
|
||
|
|
import { addDays } from "../../lib/plan";
|
||
|
|
|
||
|
|
// Ventana para CREAR una actividad (llamada, visita o tarea) a una fecha y hora, ligada a una oportunidad o a
|
||
|
|
// una cuenta que se busca por nombre. Se abre desde el calendario de la Agenda (clic en una franja) y desde la
|
||
|
|
// ficha de la cuenta. Misma apariencia y «Deshacer» que la ventana de gestionar actividades.
|
||
|
|
|
||
|
|
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 etiqueta = (iso) => {
|
||
|
|
const [y, m, d] = iso.split("-").map(Number);
|
||
|
|
return `${DIAS[new Date(`${iso}T12:00:00Z`).getUTCDay()]} ${d} ${MESES[m - 1]}`;
|
||
|
|
};
|
||
|
|
const DUR = { Llamada: [15, 30, 45, 60], Cita: [30, 60, 90, 120] };
|
||
|
|
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 TIPOS = [["Llamada", "📞 Llamada"], ["Cita", "🤝 Visita"], ["Tarea", "☑ Tarea"]];
|
||
|
|
|
||
|
|
// Recordatorio al agendar una visita virtual: la app NO crea la reunión de Teams ni envía invitaciones (decisión de Marco, 2026-11-10).
|
||
|
|
function RecordatorioTeams() {
|
||
|
|
return (
|
||
|
|
<div className="gst-teams" role="note">
|
||
|
|
<b>Reunión virtual:</b> esta visita todavía no tiene enlace de Teams ni invitación.
|
||
|
|
<ol>
|
||
|
|
<li>Ábrela en Outlook (o con «Abrir en Dynamics») y agrega la reunión de Teams.</li>
|
||
|
|
<li>Agrega a tus contactos como invitados.</li>
|
||
|
|
<li>Envía la invitación.</li>
|
||
|
|
</ol>
|
||
|
|
Hasta entonces, el cliente no recibe nada.
|
||
|
|
</div>
|
||
|
|
);
|
||
|
|
}
|
||
|
|
|
||
|
|
// preset: { dia, hora, referente?: { tipo: "opportunity" | "account", id, nombre } }
|
||
|
|
export default function NuevaActividad({ hoy, preset, onClose }) {
|
||
|
|
const router = useRouter();
|
||
|
|
const [tipo, setTipo] = useState("Llamada");
|
||
|
|
const [ref, setRef] = useState(preset.referente || null);
|
||
|
|
const [q, setQ] = useState("");
|
||
|
|
const [res, setRes] = useState(null); // { opps, cuentas } | null
|
||
|
|
const [buscando, setBuscando] = useState(false);
|
||
|
|
const [objetivo, setObjetivo] = useState(preset.objetivo || "");
|
||
|
|
const [dia, setDia] = useState(preset.dia || hoy);
|
||
|
|
const [hora, setHora] = useState(preset.hora || "09:00");
|
||
|
|
const [dur, setDur] = useState(30);
|
||
|
|
const [error, setError] = useState("");
|
||
|
|
const [trabajando, setTrabajando] = useState(false);
|
||
|
|
const [realizada, setRealizada] = useState(!!preset.realizada); // «ya la hice»: se crea y se completa de una vez
|
||
|
|
const [nota, setNota] = useState("");
|
||
|
|
const [roles, setRoles] = useState([]);
|
||
|
|
const [modalidad, setModalidad] = useState("presencial"); // solo visitas: define el lugar (Oficina del cliente / Virtual)
|
||
|
|
const [hecho, setHecho] = useState(null);
|
||
|
|
const [deshecho, setDeshecho] = useState(false);
|
||
|
|
const huboCambio = useRef(false);
|
||
|
|
const seq = useRef(0);
|
||
|
|
|
||
|
|
// Búsqueda con pequeña espera para no consultar Dynamics en cada tecla.
|
||
|
|
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]);
|
||
|
|
|
||
|
|
useEffect(() => {
|
||
|
|
setDur(tipo === "Cita" ? 60 : 30);
|
||
|
|
}, [tipo]);
|
||
|
|
|
||
|
|
async function cerrar() {
|
||
|
|
if (huboCambio.current) {
|
||
|
|
huboCambio.current = false;
|
||
|
|
await refrescarPantallasAction();
|
||
|
|
router.refresh();
|
||
|
|
}
|
||
|
|
onClose();
|
||
|
|
}
|
||
|
|
|
||
|
|
async function crear() {
|
||
|
|
setTrabajando(true);
|
||
|
|
setError("");
|
||
|
|
const r = await crearActividadLibreAction({ tipo, referenteTipo: ref.tipo, referenteId: ref.id, objetivo, dia, hora, duracion: dur, realizada, nota, participantes: tipo === "Tarea" ? [] : roles, enNombreDe: !!preset.enNombreDe, modalidad });
|
||
|
|
setTrabajando(false);
|
||
|
|
if (!r.ok) {
|
||
|
|
setError(r.error);
|
||
|
|
return;
|
||
|
|
}
|
||
|
|
huboCambio.current = true;
|
||
|
|
setHecho(r);
|
||
|
|
}
|
||
|
|
|
||
|
|
async function deshacer() {
|
||
|
|
setTrabajando(true);
|
||
|
|
setError("");
|
||
|
|
const r = await deshacerSeguimientoAction(hecho.accionId);
|
||
|
|
setTrabajando(false);
|
||
|
|
if (!r.ok) {
|
||
|
|
setError(r.error);
|
||
|
|
return;
|
||
|
|
}
|
||
|
|
setDeshecho(true);
|
||
|
|
}
|
||
|
|
|
||
|
|
const listo = ref && objetivo && dia && hora;
|
||
|
|
const min = realizada ? addDays(hoy, -30) : hoy;
|
||
|
|
const max = realizada ? hoy : addDays(hoy, 30);
|
||
|
|
const alternar = (v) => {
|
||
|
|
setRealizada(v);
|
||
|
|
// Al cambiar de modo, la fecha vuelve a hoy (siempre válida en los dos).
|
||
|
|
setDia(hoy);
|
||
|
|
};
|
||
|
|
|
||
|
|
return (
|
||
|
|
<div className="gst-bd" onClick={cerrar}>
|
||
|
|
<div className="gst" role="dialog" aria-modal="true" aria-label="Nueva actividad" onClick={(e) => e.stopPropagation()}>
|
||
|
|
<div className="gst-h">
|
||
|
|
<div>
|
||
|
|
<div className="gst-t">Nueva actividad</div>
|
||
|
|
<div className="gst-s">{etiqueta(dia)} · {hora}{realizada ? " · ya realizada" : ""}</div>
|
||
|
|
</div>
|
||
|
|
<button type="button" className="gst-x" aria-label="Cerrar" onClick={cerrar}>✕</button>
|
||
|
|
</div>
|
||
|
|
|
||
|
|
{hecho ? (
|
||
|
|
<div className="gst-ok">
|
||
|
|
<p className="gst-okt">{deshecho ? "↩ Se canceló la actividad que acabas de crear." : hecho.completada ? `✓ Registrada como completada en Dynamics: ${hecho.asunto}` : `✓ Creada en Dynamics: ${hecho.asunto}`}</p>
|
||
|
|
{!deshecho && tipo === "Cita" && modalidad === "virtual" && <RecordatorioTeams />}
|
||
|
|
{!deshecho && <p className="gst-ayuda">{TIPOS.find((t) => t[0] === tipo)?.[1].replace(/^\S+ /, "")} el {etiqueta(dia)}{tipo !== "Tarea" ? ` a las ${hora}` : ` (vence a las ${hora})`}. Ya aparece en tu agenda.</p>}
|
||
|
|
{hecho.avisoOpp && <p className="gst-aviso">{hecho.avisoOpp}</p>}
|
||
|
|
{error && <p className="gst-err">{error}</p>}
|
||
|
|
<div className="gst-pie">
|
||
|
|
{!deshecho && !hecho.completada && <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 className="gst-tabs">
|
||
|
|
{TIPOS.map(([k, l]) => (
|
||
|
|
<button key={k} type="button" className={tipo === k ? "on" : ""} onClick={() => setTipo(k)}>{l}</button>
|
||
|
|
))}
|
||
|
|
</div>
|
||
|
|
|
||
|
|
<div className="gst-sec">
|
||
|
|
<div className="gst-lbl">¿Para qué oportunidad o cuenta?</div>
|
||
|
|
{ref && (
|
||
|
|
<div className="gst-ref">
|
||
|
|
<span><b>{ref.tipo === "opportunity" ? "Oportunidad" : "Cuenta"}:</b> {ref.nombre}</span>
|
||
|
|
{!preset.referente && <button type="button" className="gst-link" onClick={() => { setRef(null); setQ(""); }}>Cambiar</button>}
|
||
|
|
</div>
|
||
|
|
)}
|
||
|
|
{ref && preset.referente && preset.opciones?.length > 0 && (
|
||
|
|
<div className="gst-chips" style={{ marginTop: 8 }}>
|
||
|
|
<select
|
||
|
|
className="gst-in"
|
||
|
|
value={ref.tipo === "account" ? "account" : ref.id}
|
||
|
|
onChange={(e) => {
|
||
|
|
const v = e.target.value;
|
||
|
|
if (v === "account") setRef(preset.referente);
|
||
|
|
else setRef({ tipo: "opportunity", id: v, nombre: preset.opciones.find((o) => o.id === v)?.nombre || "" });
|
||
|
|
}}
|
||
|
|
>
|
||
|
|
<option value="account">Ligar a la cuenta</option>
|
||
|
|
{preset.opciones.map((o) => <option key={o.id} value={o.id}>Ligar a la oportunidad: {o.nombre}</option>)}
|
||
|
|
</select>
|
||
|
|
</div>
|
||
|
|
)}
|
||
|
|
{!ref && (
|
||
|
|
<>
|
||
|
|
<input className="gst-in gst-busca" autoFocus value={q} placeholder="Escribe el nombre de la oportunidad o del cliente…" onChange={(e) => setQ(e.target.value)} />
|
||
|
|
{buscando && <p className="gst-ayuda">Buscando en Dynamics…</p>}
|
||
|
|
{res && !buscando && (
|
||
|
|
<div className="gst-res-lista">
|
||
|
|
{res.opps.length > 0 && <div className="gst-grp">Oportunidades abiertas</div>}
|
||
|
|
{res.opps.map((o) => (
|
||
|
|
<button type="button" key={o.id} className="gst-opt" onClick={() => setRef({ tipo: "opportunity", id: o.id, nombre: o.cliente ? `${o.cliente} — ${o.nombre}` : o.nombre })}>
|
||
|
|
<b>{o.cliente || o.nombre}</b>
|
||
|
|
<span>{o.nombre}{o.propietario ? ` · ${o.propietario}` : ""}</span>
|
||
|
|
</button>
|
||
|
|
))}
|
||
|
|
{res.cuentas.length > 0 && <div className="gst-grp">Cuentas</div>}
|
||
|
|
{res.cuentas.map((c) => (
|
||
|
|
<button type="button" key={c.id} className="gst-opt" onClick={() => setRef({ tipo: "account", id: c.id, nombre: c.nombre })}>
|
||
|
|
<b>{c.nombre}</b>
|
||
|
|
<span>{[c.tipo, c.propietario].filter(Boolean).join(" · ")}</span>
|
||
|
|
</button>
|
||
|
|
))}
|
||
|
|
{!res.opps.length && !res.cuentas.length && <p className="gst-ayuda">Sin coincidencias. Prueba con otra parte del nombre.</p>}
|
||
|
|
</div>
|
||
|
|
)}
|
||
|
|
{!res && q.trim().length < 2 && <p className="gst-ayuda">Escribe al menos 2 letras.</p>}
|
||
|
|
</>
|
||
|
|
)}
|
||
|
|
</div>
|
||
|
|
|
||
|
|
<div className="gst-sec">
|
||
|
|
<div className="gst-lbl">Objetivo</div>
|
||
|
|
<div className="gst-chips">
|
||
|
|
<select className="gst-in" value={objetivo} onChange={(e) => setObjetivo(e.target.value)}>
|
||
|
|
<option value="">Elige un objetivo…</option>
|
||
|
|
{OBJETIVOS_LIBRES.map((o) => <option key={o} value={o}>{o}</option>)}
|
||
|
|
</select>
|
||
|
|
</div>
|
||
|
|
<div className="gst-lbl">Fecha y hora</div>
|
||
|
|
<div className="gst-chips">
|
||
|
|
<input type="date" className="gst-in" value={dia} min={min} max={max} onChange={(e) => setDia(e.target.value)} />
|
||
|
|
<input type="time" className="gst-in" value={hora} step={900} onChange={(e) => setHora(e.target.value)} />
|
||
|
|
</div>
|
||
|
|
{tipo !== "Tarea" && (
|
||
|
|
<>
|
||
|
|
<div className="gst-lbl">Duración</div>
|
||
|
|
<div className="gst-chips">
|
||
|
|
{DUR[tipo].map((m) => (
|
||
|
|
<button key={m} type="button" className={`gst-chip${dur === m ? " on" : ""}`} onClick={() => setDur(m)}>{m} min</button>
|
||
|
|
))}
|
||
|
|
</div>
|
||
|
|
</>
|
||
|
|
)}
|
||
|
|
{tipo === "Tarea" && !realizada && <p className="gst-ayuda">La tarea vence a la hora indicada.</p>}
|
||
|
|
{tipo === "Cita" && (
|
||
|
|
<>
|
||
|
|
<div className="gst-lbl">Modalidad</div>
|
||
|
|
<div className="gst-chips">
|
||
|
|
<button type="button" className={`gst-chip${modalidad === "presencial" ? " on" : ""}`} onClick={() => setModalidad("presencial")}>Presencial</button>
|
||
|
|
<button type="button" className={`gst-chip${modalidad === "virtual" ? " on" : ""}`} onClick={() => setModalidad("virtual")}>Virtual</button>
|
||
|
|
</div>
|
||
|
|
{modalidad === "presencial" ? (
|
||
|
|
<p className="gst-ayuda">El lugar se guarda como «Oficina del cliente». Si conoces la dirección, cámbiala en Dynamics o en Outlook; si no, déjalo así.</p>
|
||
|
|
) : (
|
||
|
|
<RecordatorioTeams />
|
||
|
|
)}
|
||
|
|
</>
|
||
|
|
)}
|
||
|
|
{tipo !== "Tarea" && !realizada && (
|
||
|
|
<>
|
||
|
|
<div className="gst-lbl">¿Quién participará? (opcional)</div>
|
||
|
|
<div className="gst-chips">
|
||
|
|
{ROLES.map((r) => (
|
||
|
|
<button key={r.codigo} type="button" className={`gst-chip${roles.includes(r.codigo) ? " on" : ""}`} aria-pressed={roles.includes(r.codigo)}
|
||
|
|
onClick={() => setRoles((x) => (x.includes(r.codigo) ? x.filter((c) => c !== r.codigo) : [...x, r.codigo]))}>{r.nombre}</button>
|
||
|
|
))}
|
||
|
|
</div>
|
||
|
|
<p className="gst-ayuda">Se guarda en la {tipo === "Cita" ? "visita" : "llamada"}; la oportunidad se actualiza cuando la completes.</p>
|
||
|
|
</>
|
||
|
|
)}
|
||
|
|
<label className="gst-check">
|
||
|
|
<input type="checkbox" checked={realizada} onChange={(e) => alternar(e.target.checked)} /> Ya la realicé: registrar el resultado ahora
|
||
|
|
</label>
|
||
|
|
{realizada && (
|
||
|
|
<>
|
||
|
|
<div className="gst-lbl">Resultado: qué pasó y qué sigue</div>
|
||
|
|
<textarea className="gst-ta" rows={3} maxLength={1500} value={nota} placeholder="Ej.: Habló con el gerente, pidió ajustar la oferta" onChange={(e) => setNota(e.target.value)} />
|
||
|
|
<div className="gst-chips">
|
||
|
|
{(FRASES[tipo] || []).map((f) => (
|
||
|
|
<button key={f} type="button" className="gst-chip" onClick={() => setNota((n) => (n.trim() ? `${n.trim()}. ${f}` : f))}>{f}</button>
|
||
|
|
))}
|
||
|
|
</div>
|
||
|
|
<div className="gst-lbl">¿Quién participó? (opcional)</div>
|
||
|
|
<div className="gst-chips">
|
||
|
|
{ROLES.map((r) => (
|
||
|
|
<button key={r.codigo} type="button" className={`gst-chip${roles.includes(r.codigo) ? " on" : ""}`} aria-pressed={roles.includes(r.codigo)}
|
||
|
|
onClick={() => setRoles((x) => (x.includes(r.codigo) ? x.filter((c) => c !== r.codigo) : [...x, r.codigo]))}>{r.nombre}</button>
|
||
|
|
))}
|
||
|
|
</div>
|
||
|
|
<p className="gst-ayuda">Se crea y se completa en un solo paso, con la fecha y hora que indiques (hoy o hasta 30 días atrás). Una vez completada ya no se puede deshacer desde aquí.</p>
|
||
|
|
</>
|
||
|
|
)}
|
||
|
|
{tipo === "Cita" && <p className="gst-ayuda">La visita se crea sin invitados ni descripción: nada se envía a ningún cliente. Agrega invitados, si hace falta, en Dynamics.</p>}
|
||
|
|
</div>
|
||
|
|
|
||
|
|
{error && <p className="gst-err">{error}</p>}
|
||
|
|
<div className="gst-pie">
|
||
|
|
<button type="button" className="gst-sec-btn" onClick={cerrar}>Cancelar</button>
|
||
|
|
<button type="button" className="gst-go" disabled={trabajando || !listo} onClick={crear}>{trabajando ? "Guardando…" : realizada ? "Registrar como completada" : "Crear actividad"}</button>
|
||
|
|
</div>
|
||
|
|
</>
|
||
|
|
)}
|
||
|
|
</div>
|
||
|
|
</div>
|
||
|
|
);
|
||
|
|
}
|