127 lines
9 KiB
JavaScript
127 lines
9 KiB
JavaScript
|
|
"use server";
|
|||
|
|
import { revalidatePath } from "next/cache";
|
|||
|
|
import { auth } from "../lib/auth";
|
|||
|
|
import { esAsistente } from "../lib/authz";
|
|||
|
|
import { resolveOwnerId } from "../lib/queries";
|
|||
|
|
import { hoyManagua, addDays } from "../lib/plan";
|
|||
|
|
import { TIPOS_AGENDADOR, OBJETIVOS_LIBRES, horaAMin, localDeIso, fechaMaxima, asuntoDe, actividadParaDe } from "../lib/agendador";
|
|||
|
|
import { objetivosPorNombre, oportunidadesFrescas } from "../lib/agendadorServer";
|
|||
|
|
import { buscarCuentas, buscarOportunidades, crearActividadLibre, esGuid } from "../lib/cuentasServer";
|
|||
|
|
import { dvFresh } from "../lib/dataverse";
|
|||
|
|
import { registrarAccion } from "../lib/actividadAcciones";
|
|||
|
|
import { leerActividad, completarActividad, leerParticipacionOpp, sumarParticipacionOpp } from "../lib/actividadesServer";
|
|||
|
|
import { CODIGOS } from "../lib/participantes";
|
|||
|
|
import { aUtc, minAHora } from "../lib/agendador";
|
|||
|
|
|
|||
|
|
const apagado = () => String(process.env.ACTIVIDADES_ACCIONES || "").toLowerCase() === "off";
|
|||
|
|
const DURACIONES = { Llamada: [15, 30, 45, 60], Cita: [30, 60, 90, 120] };
|
|||
|
|
|
|||
|
|
// Busca, para ligarles una actividad, oportunidades abiertas (las del propio ejecutivo) y cuentas.
|
|||
|
|
export async function buscarReferentesAction(q) {
|
|||
|
|
const session = await auth();
|
|||
|
|
if (!session?.email) return { ok: false, error: "Inicia sesión." };
|
|||
|
|
try {
|
|||
|
|
const mio = await resolveOwnerId(session.email, session.accessToken);
|
|||
|
|
// Gerente y asistente de ventas ven todo; el ejecutivo, solo sus oportunidades y cuentas.
|
|||
|
|
const veTodo = session.isAdmin || esAsistente(session.email);
|
|||
|
|
const [opps, cuentas] = await Promise.all([
|
|||
|
|
buscarOportunidades(session.accessToken, q, veTodo ? null : mio),
|
|||
|
|
buscarCuentas(session.accessToken, q, 8, veTodo ? null : mio),
|
|||
|
|
]);
|
|||
|
|
return { ok: true, opps, cuentas };
|
|||
|
|
} catch (e) {
|
|||
|
|
console.error("[cuentas] buscar", String(e?.message || e).slice(0, 300));
|
|||
|
|
return e?.message === "TOKEN_EXPIRED" ? { ok: false, error: "Tu sesión expiró. Vuelve a iniciar sesión." } : { ok: false, error: "No pude buscar en Dynamics. Intenta de nuevo." };
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// Crea una actividad (llamada, cita o tarea) a nombre del usuario que la pide, ligada a una oportunidad o a
|
|||
|
|
// una cuenta. El navegador solo dice QUÉ quiere; permisos, estado y fechas se vuelven a validar aquí.
|
|||
|
|
export async function crearActividadLibreAction({ tipo, referenteTipo, referenteId, objetivo, dia, hora, duracion, realizada = false, nota = "", participantes = [], enNombreDe = false, modalidad = "presencial", canal = "web" }) {
|
|||
|
|
const session = await auth();
|
|||
|
|
if (!session?.email) return { ok: false, error: "Inicia sesión." };
|
|||
|
|
if (apagado()) return { ok: false, error: "La gestión de actividades está en pausa por mantenimiento." };
|
|||
|
|
if (!TIPOS_AGENDADOR.includes(tipo) || !["opportunity", "account"].includes(referenteTipo) || !esGuid(referenteId)) return { ok: false, error: "Solicitud no válida." };
|
|||
|
|
if (!OBJETIVOS_LIBRES.includes(String(objetivo || ""))) return { ok: false, error: "Elige un objetivo." };
|
|||
|
|
const hoy = hoyManagua();
|
|||
|
|
const yaHecha = realizada === true;
|
|||
|
|
const desde = yaHecha ? addDays(hoy, -30) : hoy;
|
|||
|
|
const hasta = yaHecha ? hoy : fechaMaxima(hoy);
|
|||
|
|
if (!/^\d{4}-\d{2}-\d{2}$/.test(String(dia || "")) || dia < desde || dia > hasta) {
|
|||
|
|
return { ok: false, error: yaHecha ? "Una actividad ya realizada debe tener fecha de hoy o de los últimos 30 días." : "La fecha debe estar entre hoy y los próximos 30 días." };
|
|||
|
|
}
|
|||
|
|
const m = horaAMin(String(hora || ""));
|
|||
|
|
if (m == null || m < 360 || m > 1200) return { ok: false, error: "Elige una hora entre 6:00 y 20:00." };
|
|||
|
|
if (!yaHecha && dia === hoy && m < localDeIso(new Date().toISOString()).min) return { ok: false, error: "Esa hora ya pasó." };
|
|||
|
|
if (yaHecha && dia === hoy && m > localDeIso(new Date().toISOString()).min) return { ok: false, error: "Una actividad ya realizada no puede tener una hora futura." };
|
|||
|
|
const texto = String(nota || "").slice(0, 1500);
|
|||
|
|
const roles = (Array.isArray(participantes) ? participantes : []).map(String).filter((c) => CODIGOS.includes(c));
|
|||
|
|
const dur = tipo === "Tarea" ? 0 : DURACIONES[tipo].includes(Number(duracion)) ? Number(duracion) : tipo === "Cita" ? 60 : 30;
|
|||
|
|
if (tipo !== "Tarea" && m + dur > 1260) return { ok: false, error: "La actividad terminaría muy tarde; elige una hora más temprano." };
|
|||
|
|
|
|||
|
|
try {
|
|||
|
|
const token = session.accessToken;
|
|||
|
|
let ownerId = await resolveOwnerId(session.email, token);
|
|||
|
|
if (!ownerId) return { ok: false, error: "No encontré tu usuario en Dynamics." };
|
|||
|
|
const objetivos = await objetivosPorNombre(token);
|
|||
|
|
const objetivoId = objetivos.get(objetivo);
|
|||
|
|
if (!objetivoId) return { ok: false, error: "No encontré ese objetivo en Dynamics." };
|
|||
|
|
|
|||
|
|
let nombre;
|
|||
|
|
let actividadPara;
|
|||
|
|
if (referenteTipo === "opportunity") {
|
|||
|
|
const o = (await oportunidadesFrescas(token, [referenteId])).get(referenteId);
|
|||
|
|
if (!o || !o.abierta) return { ok: false, error: "La oportunidad no está abierta." };
|
|||
|
|
nombre = o.nombre;
|
|||
|
|
actividadPara = actividadParaDe(o.tipoCodigo);
|
|||
|
|
// Desde las tablas de oportunidades la actividad queda a nombre del PROPIETARIO de la oportunidad (como hacía
|
|||
|
|
// el enlace a Dynamics). Solo el propio dueño, el administrador o la asistente de ventas pueden hacerlo.
|
|||
|
|
if (!enNombreDe && o.ownerId && o.ownerId !== ownerId && !(session.isAdmin || esAsistente(session.email))) return { ok: false, error: "Solo puedes agendar en tus propias oportunidades." };
|
|||
|
|
if (enNombreDe && o.ownerId && o.ownerId !== ownerId) {
|
|||
|
|
if (!(session.isAdmin || esAsistente(session.email))) return { ok: false, error: "Solo puedes agendar en tus propias oportunidades." };
|
|||
|
|
ownerId = o.ownerId;
|
|||
|
|
}
|
|||
|
|
} else {
|
|||
|
|
const c = await dvFresh(`accounts(${referenteId})?$select=name,customertypecode,statecode,_ownerid_value`, token);
|
|||
|
|
if (c.statecode !== 0) return { ok: false, error: "La cuenta no está activa." };
|
|||
|
|
if (!(session.isAdmin || esAsistente(session.email)) && c._ownerid_value !== ownerId) return { ok: false, error: "Solo puedes agendar en tus propias cuentas." };
|
|||
|
|
nombre = c.name;
|
|||
|
|
// Cliente (3) → Cliente Activo; prospecto u otro → Cliente Nuevo.
|
|||
|
|
actividadPara = c.customertypecode === 3 ? 100000000 : 100000001;
|
|||
|
|
}
|
|||
|
|
// Canal «whatsapp» (app de campo): el asunto lo indica, para distinguir estas llamadas registradas de las hechas por teléfono.
|
|||
|
|
const asunto = (canal === "whatsapp" ? "WhatsApp – " : "") + asuntoDe({ tipo, objetivo, cliente: nombre, nombre });
|
|||
|
|
const id = await crearActividadLibre(token, { tipo, referenteTipo, referenteId, asunto, objetivoId, ownerId, dia, hora, duracion: dur, actividadPara, participantes: yaHecha ? [] : roles, lugar: tipo === "Cita" ? (modalidad === "virtual" ? "Virtual" : "Oficina del cliente") : null });
|
|||
|
|
// «Ya la realicé»: se crea y se completa en el mismo paso, con la fecha real y la nota del resultado.
|
|||
|
|
let avisoOpp = null;
|
|||
|
|
let completada = false;
|
|||
|
|
if (yaHecha) {
|
|||
|
|
try {
|
|||
|
|
const act = await leerActividad(token, tipo, id);
|
|||
|
|
const fin = tipo === "Tarea" ? aUtc(dia, hora) : aUtc(dia, minAHora(m + dur));
|
|||
|
|
await completarActividad(token, act, texto, roles, fin);
|
|||
|
|
completada = true;
|
|||
|
|
if (roles.length && referenteTipo === "opportunity" && String(process.env.PARTICIPANTES_OPP || "").toLowerCase() !== "off") {
|
|||
|
|
try { await sumarParticipacionOpp(token, referenteId, roles); } catch { avisoOpp = "La actividad se registró, pero no pude actualizar la participación en la oportunidad."; }
|
|||
|
|
}
|
|||
|
|
} catch (e) {
|
|||
|
|
console.error("[cuentas] completar tras crear", String(e?.message || e).slice(0, 300));
|
|||
|
|
avisoOpp = "La actividad se creó pero no pude completarla; ábrela en la Agenda para completarla.";
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
const accionId = registrarAccion({
|
|||
|
|
actor: session.email, ownerId, ownerName: null, tipo, activityId: id, accion: "creacion", resultado: "ok",
|
|||
|
|
previo: { referenteTipo, referenteId }, nuevo: { dia, hora, objetivo, duracion: dur, realizada: completada }, canal: ["whatsapp", "movil"].includes(canal) ? canal : "web",
|
|||
|
|
});
|
|||
|
|
["/", "/actividades", "/plan", "/agendador", "/cuentas", "/m/hoy", "/m/semana", "/m/calendario", "/m/tuberia"].forEach((p) => revalidatePath(p));
|
|||
|
|
return { ok: true, id, accionId, asunto, completada, avisoOpp };
|
|||
|
|
} catch (e) {
|
|||
|
|
const msg = String(e?.message || e);
|
|||
|
|
console.error("[cuentas] crear", JSON.stringify({ actor: session.email, tipo, referenteTipo, error: msg.slice(0, 400) }));
|
|||
|
|
try { registrarAccion({ actor: session.email, tipo, activityId: referenteId, accion: "creacion", resultado: "error", error: msg }); } catch { /* ignorar */ }
|
|||
|
|
if (msg === "TOKEN_EXPIRED") return { ok: false, error: "Tu sesión expiró. Vuelve a iniciar sesión y reintenta." };
|
|||
|
|
if (msg.includes("DATAVERSE_403")) return { ok: false, error: "Dynamics no te permite crear actividades para este registro." };
|
|||
|
|
return { ok: false, error: `No se pudo crear la actividad en Dynamics${msg.match(/DATAVERSE_(\d+)/) ? ` (código ${msg.match(/DATAVERSE_(\d+)/)[1]})` : ""}. Intenta de nuevo; si persiste, avisa a Marco.` };
|
|||
|
|
}
|
|||
|
|
}
|