196 lines
10 KiB
JavaScript
196 lines
10 KiB
JavaScript
|
|
"use server";
|
||
|
|
import { revalidatePath } from "next/cache";
|
||
|
|
import { auth } from "../lib/auth";
|
||
|
|
import { puedeAgendarPara } from "../lib/authz";
|
||
|
|
import { resolveOwnerId, getSystemUsers } from "../lib/queries";
|
||
|
|
import { hoyManagua } from "../lib/plan";
|
||
|
|
import { TIPOS_AGENDADOR, OBJETIVOS_AGENDADOR, validar, resumenExistentes, localDeIso, ventanaDe, fechaMaxima } from "../lib/agendador";
|
||
|
|
import {
|
||
|
|
objetivosPorNombre, actividadesFrescas, oportunidadesFrescas, crearActividad, cancelarActividad,
|
||
|
|
} from "../lib/agendadorServer";
|
||
|
|
import { guardarLote, getLote, marcarDeshecho } from "../lib/agendadorLotes";
|
||
|
|
import { GC } from "../lib/participantes";
|
||
|
|
import { sumarParticipacionOpp, restaurarParticipacionOpp } from "../lib/actividadesServer";
|
||
|
|
|
||
|
|
// Igual que en gestionActions: con PARTICIPANTES_OPP=off no se toca la participación de la oportunidad.
|
||
|
|
const oppApagado = () => String(process.env.PARTICIPANTES_OPP || "").toLowerCase() === "off";
|
||
|
|
|
||
|
|
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
||
|
|
const MAX_ITEMS = 40;
|
||
|
|
|
||
|
|
const refrescar = () => {
|
||
|
|
revalidatePath("/agendador");
|
||
|
|
revalidatePath("/actividades");
|
||
|
|
revalidatePath("/plan");
|
||
|
|
revalidatePath("/prevision");
|
||
|
|
};
|
||
|
|
|
||
|
|
const errorDe = (e) =>
|
||
|
|
e?.message === "TOKEN_EXPIRED"
|
||
|
|
? "Tu sesión expiró. Vuelve a iniciar sesión y reintenta."
|
||
|
|
: "No se pudo completar la operación en Dynamics. Intenta de nuevo.";
|
||
|
|
|
||
|
|
// Crea en Dynamics las actividades propuestas por el agendador. El navegador solo manda QUÉ quiere
|
||
|
|
// (oportunidad, tipo, objetivo, día, hora): todo lo demás se vuelve a verificar AQUÍ, con datos de este
|
||
|
|
// momento — permisos, semana, que la oportunidad esté abierta y sea del ejecutivo, topes por día,
|
||
|
|
// horarios, que no se encime ni duplique. Si algo no cuadra, NO se crea nada.
|
||
|
|
export async function crearLoteAction({ ownerEmail, fecha, items }) {
|
||
|
|
const session = await auth();
|
||
|
|
if (!session?.email) return { ok: false, error: "Inicia sesión para agendar." };
|
||
|
|
const owner = String(ownerEmail || "").toLowerCase();
|
||
|
|
if (!puedeAgendarPara(session, owner)) return { ok: false, error: "No tienes permiso para agendar para este ejecutivo." };
|
||
|
|
|
||
|
|
const hoy = hoyManagua();
|
||
|
|
// Días de agendado: 5 días hábiles desde la fecha elegida (hoy como mínimo, hoy + 30 días como máximo).
|
||
|
|
const fechaTxt = String(fecha || "");
|
||
|
|
if (!/^\d{4}-\d{2}-\d{2}$/.test(fechaTxt) || fechaTxt > fechaMaxima(hoy)) {
|
||
|
|
return { ok: false, error: "La fecha de agendado debe estar entre hoy y los próximos 30 días." };
|
||
|
|
}
|
||
|
|
const dias = ventanaDe(fechaTxt, hoy);
|
||
|
|
if (!dias.length) return { ok: false, error: "No hay días hábiles para agendar con esa fecha." };
|
||
|
|
const rango = { desde: dias[0], hasta: dias[dias.length - 1] };
|
||
|
|
const ahoraMin = localDeIso(new Date().toISOString()).min;
|
||
|
|
|
||
|
|
if (!Array.isArray(items) || !items.length) return { ok: false, error: "No hay actividades para crear." };
|
||
|
|
if (items.length > MAX_ITEMS) return { ok: false, error: `Máximo ${MAX_ITEMS} actividades por tanda.` };
|
||
|
|
const limpios = items.map((i) => ({
|
||
|
|
key: String(i?.oppId || ""),
|
||
|
|
oppId: String(i?.oppId || ""),
|
||
|
|
nombre: String(i?.nombre || "").slice(0, 200),
|
||
|
|
cliente: i?.cliente ? String(i.cliente).slice(0, 200) : null,
|
||
|
|
tipo: String(i?.tipo || ""),
|
||
|
|
objetivo: String(i?.objetivo || ""),
|
||
|
|
dia: String(i?.dia || ""),
|
||
|
|
hora: String(i?.hora || ""),
|
||
|
|
gv: i?.gv === true && (i?.tipo === "Llamada" || i?.tipo === "Cita"), // «Con GV»: solo llamadas y visitas
|
||
|
|
}));
|
||
|
|
if (limpios.some((i) => !UUID.test(i.oppId))) return { ok: false, error: "Hay una oportunidad no válida en la lista." };
|
||
|
|
if (new Set(limpios.map((i) => i.oppId)).size !== limpios.length) return { ok: false, error: "Una oportunidad aparece más de una vez." };
|
||
|
|
if (limpios.some((i) => !TIPOS_AGENDADOR.includes(i.tipo) || !OBJETIVOS_AGENDADOR.includes(i.objetivo))) {
|
||
|
|
return { ok: false, error: "Hay un tipo u objetivo no permitido." };
|
||
|
|
}
|
||
|
|
|
||
|
|
try {
|
||
|
|
const token = session.accessToken;
|
||
|
|
const ownerId = await resolveOwnerId(owner, token);
|
||
|
|
if (!ownerId) return { ok: false, error: "No encontré al ejecutivo en Dynamics." };
|
||
|
|
const [opps, acts, objetivos, users] = await Promise.all([
|
||
|
|
oportunidadesFrescas(token, limpios.map((i) => i.oppId)),
|
||
|
|
actividadesFrescas(token, ownerId, rango.desde, rango.hasta),
|
||
|
|
objetivosPorNombre(token),
|
||
|
|
getSystemUsers(token),
|
||
|
|
]);
|
||
|
|
const ownerName = users.find((u) => u.id === ownerId)?.name || owner;
|
||
|
|
|
||
|
|
// Cada oportunidad debe estar abierta y ser del ejecutivo; si ya tiene algo pendiente esta semana, se omite.
|
||
|
|
const pendientes = new Set(acts.filter((a) => a.estado === "abierta" && a.oppId).map((a) => a.oppId));
|
||
|
|
const resultados = [];
|
||
|
|
const aCrear = [];
|
||
|
|
for (const it of limpios) {
|
||
|
|
const o = opps.get(it.oppId);
|
||
|
|
if (!o || !o.abierta) { resultados.push({ ...it, estado: "omitida", error: "La oportunidad no está abierta." }); continue; }
|
||
|
|
if (o.ownerId !== ownerId) { resultados.push({ ...it, estado: "omitida", error: "La oportunidad no es de este ejecutivo." }); continue; }
|
||
|
|
if (pendientes.has(it.oppId)) { resultados.push({ ...it, estado: "omitida", error: "Ya tiene una actividad pendiente en esos días." }); continue; }
|
||
|
|
if (!objetivos.get(it.objetivo)) { resultados.push({ ...it, estado: "omitida", error: "No encontré ese objetivo en Dynamics." }); continue; }
|
||
|
|
aCrear.push({ ...it, opp: o });
|
||
|
|
}
|
||
|
|
if (!aCrear.length) return { ok: false, error: "Ninguna actividad se puede crear: " + resultados.map((r) => r.error).join(" ") };
|
||
|
|
|
||
|
|
const { existentes, bloques } = resumenExistentes(acts);
|
||
|
|
const v = validar({ items: aCrear, dias, existentes, bloques, hoy, ahoraMin });
|
||
|
|
if (!v.ok) {
|
||
|
|
const detalle = aCrear.filter((i) => v.porItem[i.key]).map((i) => `${i.nombre || i.oppId}: ${v.porItem[i.key].join(" ")}`);
|
||
|
|
return { ok: false, error: "No se creó nada. Revisa: " + detalle.join(" · ") };
|
||
|
|
}
|
||
|
|
|
||
|
|
// Se crean de a 3 en paralelo; si una falla, las demás siguen y todo queda registrado.
|
||
|
|
const quien = session.email;
|
||
|
|
let i = 0;
|
||
|
|
const hechos = [];
|
||
|
|
const trabajador = async () => {
|
||
|
|
while (i < aCrear.length) {
|
||
|
|
const it = aCrear[i++];
|
||
|
|
try {
|
||
|
|
const id = await crearActividad(token, it, it.opp, ownerId, objetivos.get(it.objetivo), quien);
|
||
|
|
const hecho = { oppId: it.oppId, nombre: it.nombre, cliente: it.cliente, tipo: it.tipo, objetivo: it.objetivo, dia: it.dia, hora: it.hora, gv: it.gv, estado: "creada", activityId: id };
|
||
|
|
// «Con GV»: se marca «Participación de GV» en la oportunidad AL AGENDAR (decisión de Marco). Solo suma (nunca baja
|
||
|
|
// un Sí a No) y se guarda lo previo para «Deshacer». Si falla, la actividad queda creada y solo se avisa.
|
||
|
|
if (it.gv && !oppApagado()) {
|
||
|
|
try {
|
||
|
|
const r = await sumarParticipacionOpp(token, it.oppId, [GC]);
|
||
|
|
if (r.cambio) hecho.opp = { previo: r.previo, nuevo: r.nuevo };
|
||
|
|
} catch (e) {
|
||
|
|
if (e?.message === "TOKEN_EXPIRED") throw e;
|
||
|
|
hecho.avisoOpp = "No pude marcar la participación de GV en la oportunidad; márcala en Dynamics.";
|
||
|
|
}
|
||
|
|
}
|
||
|
|
hechos.push(hecho);
|
||
|
|
} catch (e) {
|
||
|
|
if (e?.message === "TOKEN_EXPIRED") throw e;
|
||
|
|
hechos.push({ oppId: it.oppId, nombre: it.nombre, cliente: it.cliente, tipo: it.tipo, objetivo: it.objetivo, dia: it.dia, hora: it.hora, gv: it.gv, estado: "error", error: String(e?.message || e).slice(0, 200) });
|
||
|
|
}
|
||
|
|
}
|
||
|
|
};
|
||
|
|
await Promise.all([trabajador(), trabajador(), trabajador()]);
|
||
|
|
|
||
|
|
const todos = [...hechos, ...resultados.map((r) => ({ oppId: r.oppId, nombre: r.nombre, tipo: r.tipo, estado: r.estado, error: r.error }))];
|
||
|
|
const loteId = guardarLote({ creadoPor: quien, ownerId, ownerEmail: owner, ownerName, desde: rango.desde, hasta: rango.hasta, items: todos });
|
||
|
|
refrescar();
|
||
|
|
return {
|
||
|
|
ok: true,
|
||
|
|
loteId,
|
||
|
|
creadas: hechos.filter((h) => h.estado === "creada").length,
|
||
|
|
errores: hechos.filter((h) => h.estado === "error").length,
|
||
|
|
omitidas: resultados.length,
|
||
|
|
conGV: hechos.filter((h) => h.estado === "creada" && h.gv).length,
|
||
|
|
avisosOpp: hechos.filter((h) => h.avisoOpp).length,
|
||
|
|
resultados: todos,
|
||
|
|
};
|
||
|
|
} catch (e) {
|
||
|
|
return { ok: false, error: errorDe(e) };
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
// «Deshacer» una tanda: cancela (nunca borra) lo que siga abierto. Lo ya completado o cancelado no se toca.
|
||
|
|
export async function deshacerLoteAction(loteId) {
|
||
|
|
const session = await auth();
|
||
|
|
if (!session?.email) return { ok: false, error: "Inicia sesión." };
|
||
|
|
const lote = getLote(Number(loteId));
|
||
|
|
if (!lote) return { ok: false, error: "No encontré esa tanda." };
|
||
|
|
if (lote.deshecho_en) return { ok: false, error: "Esa tanda ya se deshizo." };
|
||
|
|
if (!(puedeAgendarPara(session, lote.owner_email) || session.email === lote.creado_por)) {
|
||
|
|
return { ok: false, error: "No tienes permiso para deshacer esta tanda." };
|
||
|
|
}
|
||
|
|
try {
|
||
|
|
const resumen = { canceladas: 0, yaCerradas: 0, errores: 0, oppRestauradas: 0 };
|
||
|
|
for (const it of lote.items) {
|
||
|
|
if (it.estado !== "creada" || !it.activityId) continue;
|
||
|
|
try {
|
||
|
|
const r = await cancelarActividad(session.accessToken, it.tipo, it.activityId);
|
||
|
|
if (r === "cancelada") {
|
||
|
|
resumen.canceladas++;
|
||
|
|
// La oportunidad vuelve a su valor previo SOLO si esta tanda la cambió y la actividad se canceló aquí
|
||
|
|
// (si ya se completó, la participación de GV pudo ser real y se deja).
|
||
|
|
if (it.opp?.previo && it.opp?.nuevo && !oppApagado()) {
|
||
|
|
try {
|
||
|
|
await restaurarParticipacionOpp(session.accessToken, it.opp.previo, it.opp.nuevo);
|
||
|
|
resumen.oppRestauradas++;
|
||
|
|
} catch (e) {
|
||
|
|
if (e?.message === "TOKEN_EXPIRED") throw e;
|
||
|
|
resumen.errores++;
|
||
|
|
}
|
||
|
|
}
|
||
|
|
} else resumen.yaCerradas++;
|
||
|
|
} catch (e) {
|
||
|
|
if (e?.message === "TOKEN_EXPIRED") throw e;
|
||
|
|
resumen.errores++;
|
||
|
|
}
|
||
|
|
}
|
||
|
|
marcarDeshecho(lote.id, session.email, resumen);
|
||
|
|
refrescar();
|
||
|
|
return { ok: true, ...resumen };
|
||
|
|
} catch (e) {
|
||
|
|
return { ok: false, error: errorDe(e) };
|
||
|
|
}
|
||
|
|
}
|