"use client";
import { useEffect, useRef, useState } from "react";
import { createPortal } from "react-dom";
import { useRouter } from "next/navigation";
import {
abrirEdicionOppAction, guardarOportunidadAction, deshacerOportunidadAction, buscarCompetidoresAction, crearNotaAction, deshacerNotaAction,
} from "../campoActions";
import { FORECAST_OPC, PROB_OPC, LUZ_OPC, TIPO_OPC, MAX_ESTADO_NEGOCIACION } from "../../lib/campo";
import { ROLES } from "../../lib/participantes";
import { GC } from "../../lib/participantes";
// Botones 📝 Nota y ✎ Editar de la ficha de oportunidad, con sus hojas. Nada se gana ni se pierde desde el teléfono.
// Guardar = PATCH con If-Match (etag de cuando se abrió) y «Deshacer» durante 10 minutos; el estado de la negociación
// puede quedar además como nota nativa en la línea de tiempo.
function Hoja({ titulo, onCerrar, children }) {
return createPortal(
e.stopPropagation()}>
{children}
,
document.body
);
}
export function BotonNota({ oppId, apagado }) {
const router = useRouter();
const [abierto, setAbierto] = useState(false);
const [texto, setTexto] = useState("");
const [trab, setTrab] = useState(false);
const [error, setError] = useState("");
const [hecho, setHecho] = useState(null);
const [deshecho, setDeshecho] = useState(false);
const cerrar = () => { setAbierto(false); if (hecho) router.refresh(); setHecho(null); setDeshecho(false); setTexto(""); setError(""); };
async function guardar() {
setTrab(true); setError("");
const r = await crearNotaAction({ id: oppId, texto });
setTrab(false);
if (!r.ok) return setError(r.error);
setHecho(r);
}
async function deshacer() {
setTrab(true);
const r = await deshacerNotaAction(hecho.accionId);
setTrab(false);
if (!r.ok) return setError(r.error);
setDeshecho(true);
}
return (
<>
setAbierto(true)}>📝 Nota
{abierto && (
{hecho ? (
{deshecho ? "↩ Se eliminó la nota." : "✓ Nota guardada en Dynamics"}
{error &&
{error}
}
{!deshecho && ↩ Deshacer }
Listo
) : (
<>
)}
>
);
}
export function BotonEditar({ oppId, apagado }) {
const router = useRouter();
const [abierto, setAbierto] = useState(false);
const [o, setO] = useState(null);
const [f, setF] = useState(null);
const [error, setError] = useState("");
const [trab, setTrab] = useState(false);
const [hecho, setHecho] = useState(null);
const [deshecho, setDeshecho] = useState(false);
const [qComp, setQComp] = useState("");
const [comps, setComps] = useState(null);
const [tambienNota, setTambienNota] = useState(true);
const [veComp, setVeComp] = useState(false);
const seq = useRef(0);
async function abrir() {
setAbierto(true); setO(null); setError(""); setHecho(null); setDeshecho(false); setComps(null); setVeComp(false);
const r = await abrirEdicionOppAction(oppId);
if (!r.ok) return setError(r.error);
if (r.apagado) return setError("La edición desde el teléfono está en pausa por mantenimiento. Ábrela en Dynamics.");
setO(r.opp);
setF({
forecast: r.opp.forecast, tipo: r.opp.tipo, prob: r.opp.prob, cierre: r.opp.cierre || "", mrr: String(r.opp.mrr ?? ""), luz: r.opp.luz,
competidorId: r.opp.competidorId, competidor: r.opp.competidor, estado: r.opp.estado || "",
participantes: [...(r.opp.gv ? [GC] : []), ...r.opp.participantes],
});
}
async function cerrar() { setAbierto(false); if (hecho) router.refresh(); }
useEffect(() => {
if (!veComp) return;
const mi = ++seq.current;
const h = setTimeout(async () => {
const r = await buscarCompetidoresAction(qComp);
if (mi === seq.current && r.ok) setComps(r.competidores);
}, 300);
return () => clearTimeout(h);
}, [qComp, veComp]);
const set = (k, v) => setF((x) => ({ ...x, [k]: v }));
const alternar = (c) => setF((x) => ({ ...x, participantes: x.participantes.includes(c) ? x.participantes.filter((y) => y !== c) : [...x.participantes, c] }));
const mrrN = f && f.mrr !== "" ? Number(f.mrr) : null;
const cruzaUniverso = o && f && f.tipo !== o.tipo;
// Chips de previsión 50–90 % (+ el valor actual si está fuera de ese rango, para que se vea seleccionado).
const chipsPrev = f ? FORECAST_OPC.filter(([v]) => v >= 100000004 || v === o?.forecast) : [];
async function guardar() {
setTrab(true); setError("");
const r = await guardarOportunidadAction({
id: oppId, etag: o.etag, tambienNota,
cambios: { forecast: f.forecast, tipo: f.tipo, prob: f.prob, cierre: f.cierre, mrr: mrrN, luz: f.luz, competidorId: f.competidorId, estado: f.estado, participantes: f.participantes },
});
setTrab(false);
if (!r.ok) return setError(r.error);
setHecho(r);
}
async function deshacer() {
setTrab(true); setError("");
const r = await deshacerOportunidadAction(hecho.accionId);
setTrab(false);
if (!r.ok) return setError(r.error);
setDeshecho(true);
}
return (
<>
✎ Editar
{abierto && (
{error && !f && {error}
}
{!o && !error && Leyendo desde Dynamics…
}
{hecho && (
{deshecho ? "↩ Se deshizo: la oportunidad volvió a como estaba." : "✓ Cambios guardados en Dynamics"}
{!deshecho &&
Campos: {hecho.campos.join(", ")}{hecho.notaId ? " · y nota en la línea de tiempo" : ""}. Puedes deshacerlo durante 10 minutos.
}
{hecho.avisoNota &&
{hecho.avisoNota}
}
{error &&
{error}
}
{!deshecho && ↩ Deshacer }
Listo
)}
{o && f && !hecho && (
<>
Previsión
{chipsPrev.map(([v, l]) => set("forecast", v)}>{l.split(" ")[0]} )}
{f.forecast != null && {FORECAST_OPC.find(([v]) => v === f.forecast)?.[1] || o.forecastTxt}
}
Tipo de oportunidad
set("tipo", Number(e.target.value))}>
{TIPO_OPC.map(([v, l]) => {l} )}
{cruzaUniverso && Cambiar el tipo puede mover la oportunidad entre Ventas, Renovaciones o SAC y cambiar su puntuación.
}
Nivel de probabilidad
{PROB_OPC.map(([v, l]) => set("prob", v)}>{l} )}
Cierre estimado
set("cierre", e.target.value)} />
MRR estimado (USD)
set("mrr", e.target.value)} />
Competidor
{!veComp ? (
{f.competidor || "Sin competidor"} { setVeComp(true); setQComp(""); }}>Cambiar
) : (
<>
setQComp(e.target.value)} autoFocus />
{(comps || []).map((c) => { setF((x) => ({ ...x, competidorId: c.id, competidor: c.nombre })); setVeComp(false); }}>{c.nombre} )}
>
)}
Luz amarilla
set("luz", Number(e.target.value))}>
{f.luz == null && — }
{LUZ_OPC.map(([v, l]) => {l} )}
Participantes
{ROLES.map((r) => alternar(r.codigo)}>{r.nombre} )}
Gerencia Comercial marca «Participación de GV» (suma a la puntuación).
Estado de la negociación
)}
>
);
}