Wachato CRM: versión marca blanca configurable por entorno
CRM de WhatsApp, Instagram, Messenger y TikTok de Wachato, basado en Vocero CRM (MIT), listo para desplegar un negocio por instancia: - Marca blanca: nombre, color, moneda y giro del negocio desde el .env (BRAND_NAME, BRAND_ACCENT, BRAND_CURRENCY, BUSINESS_DESCRIPTION); se aplican una vez y luego manda Ajustes → Marca. - Superadmin sembrado al arrancar (SUPERADMIN_*), idempotente. - Servicios y precios, campos personalizados, exportación a Excel/PDF, respaldos, agenda, atribución de anuncios y transcripción de notas de voz. - Diseño con contraste AAA, tema claro y oscuro. - Despliegue: docker compose (Caddy opcional), plantillas para paneles con reverse proxy (deploy/aapanel), imagen publicada en GHCR por la CI. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
commit
6edc6020d5
1316 files changed
+308543
No files matched your search
@@ -0,0 +1,249 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import {
|
||||
citasEnContexto,
|
||||
citasParaContexto,
|
||||
type FilaCita,
|
||||
} from "@/server/agenda/context";
|
||||
|
||||
/**
|
||||
* 015 — Las citas del contacto en el contexto de un cerebro externo
|
||||
* (`GET /api/bot/context` → `booking`).
|
||||
*
|
||||
* Nea pega este bloque tal cual en su prompt y lo trata como LA verdad sobre
|
||||
* las citas (`_booking_lines`): sin él, en la edición cloud, reservó una
|
||||
* segunda cita a quien no llegó a la primera, dijo a las 17:04 que la demo era
|
||||
* «hoy a las 10:30» y negó con un motivo inventado una cita que el equipo
|
||||
* había cancelado. Por eso la forma importa tanto como el contenido: la de la
|
||||
* edición cloud, para que un mismo cerebro sirva contra las dos.
|
||||
*/
|
||||
|
||||
const TZ = "America/Mexico_City";
|
||||
const DIA = 86_400_000;
|
||||
|
||||
// Lunes 14 de septiembre de 2026, 10:30 en CDMX (UTC-6).
|
||||
const LUNES_1030 = new Date("2026-09-14T16:30:00.000Z");
|
||||
// 17:04 del mismo lunes: la hora a la que el agente dijo «tu demo es hoy a las 10:30».
|
||||
const LUNES_1704 = new Date("2026-09-14T23:04:00.000Z");
|
||||
|
||||
function cita(extra: Partial<FilaCita> = {}): FilaCita {
|
||||
return {
|
||||
id: "bk_1",
|
||||
kind: "session",
|
||||
status: "agendada",
|
||||
isTest: false,
|
||||
scheduledAt: LUNES_1030,
|
||||
durationMinutes: 30,
|
||||
meetingLink: "https://meet.google.com/aza-iftw-wxp",
|
||||
linkPending: false,
|
||||
updatedAt: new Date("2026-09-10T12:00:00.000Z"),
|
||||
...extra,
|
||||
};
|
||||
}
|
||||
|
||||
describe("la forma de una cita en el contexto", () => {
|
||||
it("la etiqueta dice el DÍA en palabras, relativo a ahora, en la zona del negocio", () => {
|
||||
// Con la corta («lun 14 sep, 10:30») un modelo no tiene cómo saber que
|
||||
// esa cita es la de hoy.
|
||||
const antes = new Date("2026-09-14T15:00:00.000Z"); // 09:00 del mismo lunes
|
||||
expect(citasEnContexto([cita()], TZ, antes).next?.label).toBe(
|
||||
"hoy lunes, 14 de septiembre, 10:30"
|
||||
);
|
||||
const domingo = new Date("2026-09-13T18:00:00.000Z");
|
||||
expect(citasEnContexto([cita()], TZ, domingo).next?.label).toMatch(/^mañana lunes/);
|
||||
});
|
||||
|
||||
it("trae id, estado, inicio y fin en UTC, enlace y si está pendiente", () => {
|
||||
const { next } = citasEnContexto([cita()], TZ, new Date("2026-09-14T15:00:00.000Z"));
|
||||
expect(next).toEqual({
|
||||
id: "bk_1",
|
||||
status: "agendada",
|
||||
startUtc: "2026-09-14T16:30:00.000Z",
|
||||
endUtc: "2026-09-14T17:00:00.000Z",
|
||||
label: "hoy lunes, 14 de septiembre, 10:30",
|
||||
meetingLink: "https://meet.google.com/aza-iftw-wxp",
|
||||
linkPending: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("con el enlace pendiente lo dice, en vez de prometer uno", () => {
|
||||
const { next } = citasEnContexto(
|
||||
[cita({ meetingLink: null, linkPending: true })],
|
||||
TZ,
|
||||
new Date("2026-09-14T15:00:00.000Z")
|
||||
);
|
||||
expect(next).toMatchObject({ meetingLink: null, linkPending: true });
|
||||
});
|
||||
|
||||
it("siempre dice en qué zona están las etiquetas", () => {
|
||||
expect(citasEnContexto([], TZ, LUNES_1704).timezone).toBe(TZ);
|
||||
});
|
||||
});
|
||||
|
||||
describe("qué citas salen", () => {
|
||||
it("sin citas, el bloque existe con las tres vacías (la agenda SÍ se consultó)", () => {
|
||||
expect(citasEnContexto([], TZ, LUNES_1704)).toEqual({
|
||||
timezone: TZ,
|
||||
next: null,
|
||||
unresolved: null,
|
||||
lastClosed: null,
|
||||
});
|
||||
});
|
||||
|
||||
it("`next` es la agendada más próxima, no la última creada", () => {
|
||||
const martes = cita({ id: "bk_martes", scheduledAt: new Date("2026-09-15T16:30:00.000Z") });
|
||||
const jueves = cita({ id: "bk_jueves", scheduledAt: new Date("2026-09-17T16:30:00.000Z") });
|
||||
const { next } = citasEnContexto([jueves, martes], TZ, LUNES_1704);
|
||||
expect(next?.id).toBe("bk_martes");
|
||||
});
|
||||
|
||||
it("una cita que ya empezó y nadie cerró NO es la próxima: va en `unresolved`", () => {
|
||||
// El caso de las 17:04: darla por vigente es decir «tu demo es hoy a las 10:30».
|
||||
const r = citasEnContexto([cita()], TZ, LUNES_1704);
|
||||
expect(r.next).toBeNull();
|
||||
expect(r.unresolved?.id).toBe("bk_1");
|
||||
expect(r.unresolved?.endUtc).toBe("2026-09-14T17:00:00.000Z");
|
||||
});
|
||||
|
||||
it("una sin cerrar de hace más de 7 días ya no es tema de conversación", () => {
|
||||
const vieja = cita({ scheduledAt: new Date(LUNES_1704.getTime() - 8 * DIA) });
|
||||
expect(citasEnContexto([vieja], TZ, LUNES_1704).unresolved).toBeNull();
|
||||
});
|
||||
|
||||
it("una cancelada no es la próxima aunque sea futura: va en `lastClosed`", () => {
|
||||
const cancelada = cita({
|
||||
status: "cancelada",
|
||||
scheduledAt: new Date("2026-09-15T16:30:00.000Z"),
|
||||
updatedAt: new Date("2026-09-14T22:00:00.000Z"),
|
||||
});
|
||||
const r = citasEnContexto([cancelada], TZ, LUNES_1704);
|
||||
expect(r.next).toBeNull();
|
||||
expect(r.lastClosed).toMatchObject({
|
||||
id: "bk_1",
|
||||
status: "cancelada",
|
||||
closedAt: "2026-09-14T22:00:00.000Z",
|
||||
// En la raíz solo el equipo cancela: por /api/bot/* no existe cancelar.
|
||||
cancelledBy: "equipo",
|
||||
});
|
||||
});
|
||||
|
||||
it("`lastClosed` es la cerrada MÁS RECIENTE, y no lleva enlace: ya no sirve", () => {
|
||||
const realizada = cita({
|
||||
id: "bk_realizada",
|
||||
status: "realizada",
|
||||
scheduledAt: new Date("2026-09-11T16:30:00.000Z"),
|
||||
updatedAt: new Date("2026-09-11T18:00:00.000Z"),
|
||||
});
|
||||
const noShow = cita({
|
||||
id: "bk_no_show",
|
||||
status: "no_show",
|
||||
scheduledAt: new Date("2026-09-12T16:30:00.000Z"),
|
||||
updatedAt: new Date("2026-09-13T09:00:00.000Z"),
|
||||
});
|
||||
const { lastClosed } = citasEnContexto([realizada, noShow], TZ, LUNES_1704);
|
||||
expect(lastClosed?.id).toBe("bk_no_show");
|
||||
expect(lastClosed?.cancelledBy).toBeNull();
|
||||
expect(lastClosed).not.toHaveProperty("meetingLink");
|
||||
expect(lastClosed).not.toHaveProperty("linkPending");
|
||||
});
|
||||
|
||||
it("una cerrada hace más de 7 días ya no sale", () => {
|
||||
const vieja = cita({
|
||||
status: "cancelada",
|
||||
updatedAt: new Date(LUNES_1704.getTime() - 8 * DIA),
|
||||
});
|
||||
expect(citasEnContexto([vieja], TZ, LUNES_1704).lastClosed).toBeNull();
|
||||
});
|
||||
|
||||
it("una cita de PRUEBA jamás aparece, ni siendo la mejor candidata de cada bloque", () => {
|
||||
// Del Laboratorio: es de un cliente simulado. Presentarla como real le
|
||||
// haría al cerebro negar una cita nueva o defender una que no existe.
|
||||
const prueba = (extra: Partial<FilaCita>) => cita({ isTest: true, ...extra });
|
||||
const r = citasEnContexto(
|
||||
[
|
||||
prueba({ id: "t_next", scheduledAt: new Date("2026-09-15T16:30:00.000Z") }),
|
||||
prueba({ id: "t_unresolved", scheduledAt: LUNES_1030 }),
|
||||
prueba({ id: "t_closed", status: "cancelada", updatedAt: LUNES_1704 }),
|
||||
],
|
||||
TZ,
|
||||
LUNES_1704
|
||||
);
|
||||
expect(r).toEqual({ timezone: TZ, next: null, unresolved: null, lastClosed: null });
|
||||
});
|
||||
|
||||
it("un bloqueo del operador no es una cita de nadie", () => {
|
||||
const bloqueo = cita({ kind: "block", scheduledAt: new Date("2026-09-15T16:30:00.000Z") });
|
||||
expect(citasEnContexto([bloqueo], TZ, LUNES_1704).next).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
/* -------- citasParaContexto: la bandera y la degradación -------- */
|
||||
|
||||
// `vi.hoisted`: el módulo bajo prueba se importa arriba, y el mock tiene que
|
||||
// existir antes de que ese import resuelva `@/lib/db`.
|
||||
const { getDb } = vi.hoisted(() => ({ getDb: vi.fn() }));
|
||||
|
||||
vi.mock("@/lib/db", async (importOriginal) => {
|
||||
const original = await importOriginal<typeof import("@/lib/db")>();
|
||||
return { ...original, getDb };
|
||||
});
|
||||
|
||||
vi.mock("@/server/agenda/settings", async (importOriginal) => {
|
||||
const original = await importOriginal<typeof import("@/server/agenda/settings")>();
|
||||
return {
|
||||
...original,
|
||||
getSettings: vi.fn(async () => ({
|
||||
...original.DEFAULT_CALENDAR_SETTINGS,
|
||||
timezone: "America/Bogota",
|
||||
})),
|
||||
};
|
||||
});
|
||||
|
||||
/** Una base cuyo `select … from … where` devuelve `rows` (o revienta). */
|
||||
function baseCon(rows: FilaCita[] | Error) {
|
||||
const chain: Record<string, unknown> = {};
|
||||
for (const m of ["from", "where", "orderBy", "limit"]) chain[m] = () => chain;
|
||||
(chain as { then: unknown }).then = (
|
||||
resolve: (v: unknown) => void,
|
||||
reject: (e: unknown) => void
|
||||
) => (rows instanceof Error ? Promise.reject(rows) : Promise.resolve(rows)).then(resolve, reject);
|
||||
return { select: () => chain };
|
||||
}
|
||||
|
||||
describe("citasParaContexto", () => {
|
||||
beforeEach(() => {
|
||||
getDb.mockReset();
|
||||
});
|
||||
|
||||
it("con la agenda APAGADA no hay bloque, y ni se toca la base", async () => {
|
||||
vi.stubEnv("AGENDA", "");
|
||||
await expect(citasParaContexto("org_1", "ct_1")).resolves.toBeNull();
|
||||
expect(getDb).not.toHaveBeenCalled();
|
||||
vi.unstubAllEnvs();
|
||||
});
|
||||
|
||||
it("encendida, elige sobre lo que lee y etiqueta en la zona configurada", async () => {
|
||||
vi.stubEnv("AGENDA", "on");
|
||||
getDb.mockReturnValue(
|
||||
baseCon([
|
||||
cita({ id: "bk_prueba", isTest: true, scheduledAt: new Date("2026-09-15T15:00:00.000Z") }),
|
||||
cita({ id: "bk_real", scheduledAt: new Date("2026-09-16T15:00:00.000Z") }),
|
||||
])
|
||||
);
|
||||
const r = await citasParaContexto("org_1", "ct_1", LUNES_1704);
|
||||
expect(r?.timezone).toBe("America/Bogota");
|
||||
expect(r?.next?.id).toBe("bk_real");
|
||||
// 15:00Z es 10:00 en Bogotá (UTC-5).
|
||||
expect(r?.next?.label).toBe("miércoles, 16 de septiembre, 10:00");
|
||||
vi.unstubAllEnvs();
|
||||
});
|
||||
|
||||
it("si la lectura falla, no hay bloque — y el contexto no se cae por eso", async () => {
|
||||
vi.stubEnv("AGENDA", "on");
|
||||
getDb.mockReturnValue(baseCon(new Error("conexión perdida")));
|
||||
const consola = vi.spyOn(console, "error").mockImplementation(() => {});
|
||||
await expect(citasParaContexto("org_1", "ct_1", LUNES_1704)).resolves.toBeNull();
|
||||
expect(consola).toHaveBeenCalled();
|
||||
consola.mockRestore();
|
||||
vi.unstubAllEnvs();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,100 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
bookingErrorResponse,
|
||||
bookingErrorStatus,
|
||||
bookingPayload,
|
||||
} from "@/server/agenda/http";
|
||||
import { BookingError } from "@/server/agenda/service";
|
||||
import { agendaDisabledResponse } from "@/server/agenda/flag";
|
||||
|
||||
/**
|
||||
* 015 — El CONTRATO observable de la agenda, fijado en un test.
|
||||
*
|
||||
* No es purismo REST: los dos fallos que esto previene ocurrieron en
|
||||
* producción y ninguno lo detectaron los mocks, porque los mocks respondían
|
||||
* otra cosa que el servidor real. Aquí el cliente y el servidor miran la misma
|
||||
* definición.
|
||||
*/
|
||||
|
||||
const result = {
|
||||
booking: { id: "bk_123" },
|
||||
meetingLink: "https://meet.ejemplo.com/sala",
|
||||
linkPending: false,
|
||||
label: "mié 5 ago, 09:00",
|
||||
} as never;
|
||||
|
||||
describe("cuerpo de una reserva creada", () => {
|
||||
it("lleva el id, el enlace, si el enlace está pendiente y la etiqueta", () => {
|
||||
expect(bookingPayload(result)).toEqual({
|
||||
bookingId: "bk_123",
|
||||
meetingLink: "https://meet.ejemplo.com/sala",
|
||||
linkPending: false,
|
||||
label: "mié 5 ago, 09:00",
|
||||
});
|
||||
});
|
||||
|
||||
it("`linkPending` viaja SIEMPRE: es lo que decide si se promete el enlace", () => {
|
||||
const pendiente = bookingPayload({
|
||||
...(result as object),
|
||||
meetingLink: null,
|
||||
linkPending: true,
|
||||
} as never);
|
||||
expect(pendiente.meetingLink).toBeNull();
|
||||
expect(pendiente.linkPending).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("códigos de estado", () => {
|
||||
it("los conflictos de hueco son 409, no 400", () => {
|
||||
expect(bookingErrorStatus("slot_taken")).toBe(409);
|
||||
expect(bookingErrorStatus("slot_not_offered")).toBe(409);
|
||||
});
|
||||
|
||||
it("no encontrado es 404 y payload inválido 422", () => {
|
||||
expect(bookingErrorStatus("not_found")).toBe(404);
|
||||
expect(bookingErrorStatus("invalid")).toBe(422);
|
||||
});
|
||||
});
|
||||
|
||||
describe("forma del error", () => {
|
||||
it("el sobre va ANIDADO y `slots` es HERMANO de `error`", async () => {
|
||||
const slots = [{ startUtc: "2026-08-05T15:30:00.000Z", label: "mié 5 ago, 09:30" }];
|
||||
const res = bookingErrorResponse(
|
||||
new BookingError("slot_taken", "Ese horario acaba de ocuparse", slots)
|
||||
);
|
||||
expect(res.status).toBe(409);
|
||||
|
||||
const body = (await res.json()) as {
|
||||
error: { code: string; message: string };
|
||||
slots: { label: string }[];
|
||||
};
|
||||
// Anidado: un mock con la forma plana `{code}` hizo que todo 409 se leyera
|
||||
// como conflicto genérico y el camino de re-oferta nunca se activara.
|
||||
expect(body.error.code).toBe("slot_taken");
|
||||
expect(body.error.message).toContain("ocuparse");
|
||||
// Hermano: es lo que el cliente usa para re-ofrecer sin otra ida y vuelta.
|
||||
expect(body.slots).toHaveLength(1);
|
||||
expect(body.slots[0]!.label).toBe("mié 5 ago, 09:30");
|
||||
});
|
||||
|
||||
it("`invalid` sale como `invalid_body`, el código que ya usa el resto de la API", async () => {
|
||||
const res = bookingErrorResponse(new BookingError("invalid", "Instante inválido"));
|
||||
expect(res.status).toBe(422);
|
||||
const body = (await res.json()) as { error: { code: string } };
|
||||
expect(body.error.code).toBe("invalid_body");
|
||||
});
|
||||
|
||||
it("un error que no es del dominio se relanza en vez de disfrazarse de 409", () => {
|
||||
expect(() => bookingErrorResponse(new Error("se cayó la base"))).toThrow(
|
||||
"se cayó la base"
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("la agenda apagada", () => {
|
||||
it("responde 404 sin cuerpo: ese endpoint no existe en esta instancia", () => {
|
||||
const res = agendaDisabledResponse();
|
||||
// 404 y no 403: un 403 confirmaría que la agenda existe pero está vedada.
|
||||
expect(res.status).toBe(404);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,41 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { parseAgendaFlag } from "@/server/agenda/flag";
|
||||
|
||||
/**
|
||||
* 015 — La bandera de la agenda. El caso que importa es el DEFAULT: una
|
||||
* instancia que no la pidió no debe acabar con la agenda encendida por un
|
||||
* despiste de configuración.
|
||||
*/
|
||||
|
||||
describe("parseAgendaFlag", () => {
|
||||
it("sin variable, la agenda no existe", () => {
|
||||
expect(parseAgendaFlag(undefined)).toBe(false);
|
||||
expect(parseAgendaFlag("")).toBe(false);
|
||||
expect(parseAgendaFlag(" ")).toBe(false);
|
||||
});
|
||||
|
||||
it("`on` la enciende, con espacios y mayúsculas de por medio", () => {
|
||||
expect(parseAgendaFlag("on")).toBe(true);
|
||||
expect(parseAgendaFlag("ON")).toBe(true);
|
||||
expect(parseAgendaFlag(" On ")).toBe(true);
|
||||
});
|
||||
|
||||
it("acepta las otras formas de decir que sí", () => {
|
||||
expect(parseAgendaFlag("1")).toBe(true);
|
||||
expect(parseAgendaFlag("true")).toBe(true);
|
||||
expect(parseAgendaFlag("TRUE")).toBe(true);
|
||||
expect(parseAgendaFlag("si")).toBe(true);
|
||||
expect(parseAgendaFlag("sí")).toBe(true);
|
||||
expect(parseAgendaFlag("yes")).toBe(true);
|
||||
});
|
||||
|
||||
it("cualquier otra cosa deja la agenda apagada, incluido `off` y `false`", () => {
|
||||
expect(parseAgendaFlag("off")).toBe(false);
|
||||
expect(parseAgendaFlag("false")).toBe(false);
|
||||
expect(parseAgendaFlag("0")).toBe(false);
|
||||
expect(parseAgendaFlag("no")).toBe(false);
|
||||
expect(parseAgendaFlag("agenda")).toBe(false);
|
||||
// Un typo no enciende nada: apagada es el estado seguro.
|
||||
expect(parseAgendaFlag("onn")).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,64 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
CABECERA_HUECOS,
|
||||
findOffered,
|
||||
mapaDeHuecosParaModelo,
|
||||
} from "@/server/agenda/offers";
|
||||
|
||||
/**
|
||||
* 015 / issue #50 — Los huecos que el modelo puede usar de verdad.
|
||||
*
|
||||
* `book_slot` exige el `startUtc` y `findOffered` compara por epoch exacto,
|
||||
* sin tolerancia. Al modelo solo le llegaban el prompt y el historial de
|
||||
* TEXTO, donde están las etiquetas que leyó el cliente —«lun 7 sep, 11:00»—
|
||||
* sin año, sin zona y sin la fecha de hoy. Acertar el instante era cuestión de
|
||||
* suerte, el rechazo caía siempre en `slot_not_offered`, y la conversación se
|
||||
* quedaba en bucle repitiendo la misma lista.
|
||||
*/
|
||||
|
||||
const OFERTAS = [
|
||||
{ startUtc: "2026-09-07T15:00:00.000Z", label: "lun 7 sep, 09:00" },
|
||||
{ startUtc: "2026-09-07T17:00:00.000Z", label: "lun 7 sep, 11:00" },
|
||||
];
|
||||
|
||||
describe("mapaDeHuecosParaModelo", () => {
|
||||
it("empareja cada etiqueta con su instante exacto", () => {
|
||||
const mapa = mapaDeHuecosParaModelo(OFERTAS)!;
|
||||
expect(mapa).toContain('- "lun 7 sep, 09:00" → 2026-09-07T15:00:00.000Z');
|
||||
expect(mapa).toContain('- "lun 7 sep, 11:00" → 2026-09-07T17:00:00.000Z');
|
||||
});
|
||||
|
||||
it("lleva la cabecera que dice qué hacer con esos valores", () => {
|
||||
expect(mapaDeHuecosParaModelo(OFERTAS)).toContain(CABECERA_HUECOS);
|
||||
});
|
||||
|
||||
/**
|
||||
* Sin esto, el modelo podría inventarse una reserva antes de haber ofrecido
|
||||
* nada — y el motor la rechazaría, volviendo al bucle por otro camino.
|
||||
*/
|
||||
it("sin oferta vigente no hay bloque: hay que ofrecer antes de reservar", () => {
|
||||
expect(mapaDeHuecosParaModelo([])).toBeNull();
|
||||
});
|
||||
|
||||
/**
|
||||
* La invariante que cierra el círculo: lo que el mapa enseña tiene que ser
|
||||
* exactamente lo que `findOffered` acepta. Si el formato del ISO cambiara en
|
||||
* un lado y no en el otro, volveríamos al mismo bucle sin que nada avisara.
|
||||
*/
|
||||
it("todo instante del mapa es aceptado por findOffered", () => {
|
||||
const mapa = mapaDeHuecosParaModelo(OFERTAS)!;
|
||||
const instantes = mapa.match(/\d{4}-\d{2}-\d{2}T[\d:.]+Z/g) ?? [];
|
||||
expect(instantes).toHaveLength(OFERTAS.length);
|
||||
for (const iso of instantes) {
|
||||
expect(findOffered(OFERTAS, iso)).not.toBeNull();
|
||||
}
|
||||
});
|
||||
|
||||
it("una etiqueta con comillas no rompe el formato de la línea", () => {
|
||||
const mapa = mapaDeHuecosParaModelo([
|
||||
{ startUtc: "2026-09-07T15:00:00.000Z", label: 'mar 8 "temprano"' },
|
||||
])!;
|
||||
expect(mapa.split("\n")).toHaveLength(2);
|
||||
expect(mapa).toContain("→ 2026-09-07T15:00:00.000Z");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,409 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
buildCandidateSlots,
|
||||
filterFreeSlots,
|
||||
type AvailableSlot,
|
||||
} from "@/server/agenda/availability";
|
||||
import {
|
||||
DEFAULT_CALENDAR_SETTINGS,
|
||||
type CalendarSettings,
|
||||
} from "@/server/agenda/settings";
|
||||
import {
|
||||
aLoLargoDelDia,
|
||||
armarHuecos,
|
||||
HUECOS_POR_FECHA,
|
||||
spreadByDay,
|
||||
} from "@/server/agenda/spread";
|
||||
import type { SlotUtc } from "@/lib/time/slots";
|
||||
|
||||
/**
|
||||
* Huecos por fecha, repartidos a lo largo del día, y hasta dónde llega lo
|
||||
* consultado.
|
||||
*
|
||||
* Fija el fallo de la prueba de punta a punta raíz + Nea: a «¿tienen algo
|
||||
* mañana en la tarde?» el agente ofreció 10:00, 10:30 y 11:00 y dijo que el
|
||||
* martes solo había mañana, con la agenda libre de 12:00 a 18:30. El CRM
|
||||
* ignoraba `date` y solo devolvía las tres primeras horas de cada día.
|
||||
*/
|
||||
|
||||
const MX = "America/Mexico_City";
|
||||
const NY = "America/New_York";
|
||||
// Lunes 21 sep 2026, 09:00 en CDMX (UTC-6 todo el año desde 2022).
|
||||
const NOW = new Date("2026-09-21T15:00:00.000Z");
|
||||
|
||||
const LUN_A_VIE: CalendarSettings["weeklyHours"] = {
|
||||
mon: [{ start: "10:00", end: "19:00" }],
|
||||
tue: [{ start: "10:00", end: "19:00" }],
|
||||
wed: [{ start: "10:00", end: "19:00" }],
|
||||
thu: [{ start: "10:00", end: "19:00" }],
|
||||
fri: [{ start: "10:00", end: "19:00" }],
|
||||
};
|
||||
|
||||
function ajustes(over: Partial<CalendarSettings> = {}): CalendarSettings {
|
||||
return {
|
||||
...DEFAULT_CALENDAR_SETTINGS,
|
||||
weeklyHours: LUN_A_VIE,
|
||||
minNoticeHours: 0,
|
||||
maxDaysAhead: 7,
|
||||
timezone: MX,
|
||||
...over,
|
||||
};
|
||||
}
|
||||
|
||||
/** Lo que devolvería el motor para [from, to] con `busy` ocupado. */
|
||||
function libres(
|
||||
s: CalendarSettings,
|
||||
from: string,
|
||||
to: string,
|
||||
now: Date = NOW,
|
||||
busy: SlotUtc[] = []
|
||||
): AvailableSlot[] {
|
||||
return filterFreeSlots(buildCandidateSlots(s, from, to), busy, {
|
||||
now,
|
||||
minNoticeHours: s.minNoticeHours,
|
||||
timezone: s.timezone,
|
||||
});
|
||||
}
|
||||
|
||||
/** Una consulta por fecha, armada como la arma la ruta. */
|
||||
function porFecha(
|
||||
s: CalendarSettings,
|
||||
date: string,
|
||||
now: Date = NOW,
|
||||
busy: SlotUtc[] = []
|
||||
) {
|
||||
return armarHuecos({
|
||||
todos: libres(s, date, date, now, busy),
|
||||
timezone: s.timezone,
|
||||
now,
|
||||
maxDaysAhead: s.maxDaysAhead,
|
||||
limit: 12,
|
||||
perDay: 3,
|
||||
days: 5,
|
||||
date,
|
||||
candidatosDelDia: buildCandidateSlots(s, date, date).length,
|
||||
});
|
||||
}
|
||||
|
||||
const horas = (slots: { time: string }[]) => slots.map((s) => s.time);
|
||||
|
||||
describe("«¿mañana en la tarde?» (el fallo de la prueba de punta a punta)", () => {
|
||||
const s = ajustes();
|
||||
|
||||
it("el reparto de siempre solo ve la mañana de cada día… y ahora lo dice", () => {
|
||||
const { slots, query } = armarHuecos({
|
||||
todos: libres(s, "2026-09-21", "2026-09-28"),
|
||||
timezone: MX,
|
||||
now: NOW,
|
||||
maxDaysAhead: 7,
|
||||
limit: 12,
|
||||
perDay: 3,
|
||||
days: 5,
|
||||
});
|
||||
const manana = slots.filter((x) => x.dayIso === "2026-09-22");
|
||||
expect(horas(manana)).toEqual(["10:00", "10:30", "11:00"]);
|
||||
// 3 por día × 4 días = 12: el jueves 24 fue el último revisado.
|
||||
expect(query).toEqual({
|
||||
date: null,
|
||||
status: null,
|
||||
coveredUntil: "2026-09-24",
|
||||
horizonEnd: "2026-09-28",
|
||||
perDay: 3,
|
||||
});
|
||||
});
|
||||
|
||||
it("con date trae TODO el martes, tarde incluida", () => {
|
||||
const { slots, query } = porFecha(s, "2026-09-22");
|
||||
expect(slots).toHaveLength(18); // 10:00 … 18:30, cada 30 min
|
||||
expect(horas(slots)).toEqual(
|
||||
expect.arrayContaining(["12:00", "15:00", "18:30"])
|
||||
);
|
||||
expect(slots.every((x) => x.dayIso === "2026-09-22")).toBe(true);
|
||||
expect(slots[0]!.dayLabel).toMatch(/^mañana martes/);
|
||||
expect(query).toEqual({
|
||||
date: "2026-09-22",
|
||||
status: "available",
|
||||
coveredUntil: "2026-09-22",
|
||||
horizonEnd: "2026-09-28",
|
||||
perDay: null,
|
||||
});
|
||||
});
|
||||
|
||||
it("con date, limit/perDay/days no recortan el día", () => {
|
||||
const { slots } = armarHuecos({
|
||||
todos: libres(s, "2026-09-25", "2026-09-25"),
|
||||
timezone: MX,
|
||||
now: NOW,
|
||||
maxDaysAhead: 7,
|
||||
limit: 1,
|
||||
perDay: 1,
|
||||
days: 1, // el viernes 25 queda FUERA de una ventana de 1 día: no importa
|
||||
date: "2026-09-25",
|
||||
candidatosDelDia: 18,
|
||||
});
|
||||
expect(slots).toHaveLength(18);
|
||||
});
|
||||
|
||||
it("no mezcla otros días aunque vengan en la lista", () => {
|
||||
const { slots } = armarHuecos({
|
||||
todos: libres(s, "2026-09-21", "2026-09-28"),
|
||||
timezone: MX,
|
||||
now: NOW,
|
||||
maxDaysAhead: 7,
|
||||
limit: 12,
|
||||
perDay: 3,
|
||||
date: "2026-09-23",
|
||||
candidatosDelDia: 18,
|
||||
});
|
||||
expect(slots).toHaveLength(18);
|
||||
expect(slots.every((x) => x.dayIso === "2026-09-23")).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("repartidos a lo largo del día cuando no caben", () => {
|
||||
it("por debajo del tope, la lista tal cual", () => {
|
||||
const lista = [1, 2, 3];
|
||||
expect(aLoLargoDelDia(lista, 24)).toBe(lista);
|
||||
});
|
||||
|
||||
it("por encima, del primero al último, sin repetir", () => {
|
||||
const lista = Array.from({ length: 40 }, (_, i) => i);
|
||||
const elegidos = aLoLargoDelDia(lista, 24);
|
||||
expect(elegidos).toHaveLength(24);
|
||||
expect(elegidos[0]).toBe(0);
|
||||
expect(elegidos[23]).toBe(39);
|
||||
for (let i = 1; i < elegidos.length; i++) {
|
||||
expect(elegidos[i]!).toBeGreaterThan(elegidos[i - 1]!);
|
||||
}
|
||||
});
|
||||
|
||||
it("topes degenerados no revientan", () => {
|
||||
expect(aLoLargoDelDia([1, 2, 3], 1)).toEqual([1]);
|
||||
expect(aLoLargoDelDia([1, 2, 3], 0)).toEqual([]);
|
||||
});
|
||||
|
||||
it("un día de 48 turnos no se queda en la mañana", () => {
|
||||
const s = ajustes({
|
||||
slotMinutes: 15,
|
||||
weeklyHours: { tue: [{ start: "08:00", end: "20:00" }] },
|
||||
});
|
||||
const { slots, query } = porFecha(s, "2026-09-22");
|
||||
expect(query.status).toBe("available");
|
||||
expect(slots).toHaveLength(HUECOS_POR_FECHA);
|
||||
expect(slots[0]!.time).toBe("08:00");
|
||||
expect(slots[slots.length - 1]!.time).toBe("19:45");
|
||||
expect(horas(slots).filter((h) => h >= "12:00").length).toBeGreaterThan(10);
|
||||
});
|
||||
});
|
||||
|
||||
describe("por qué un día no tiene horas", () => {
|
||||
const s = ajustes();
|
||||
|
||||
it("cerrado: ese día el negocio no abre", () => {
|
||||
const { slots, query } = porFecha(s, "2026-09-26"); // sábado
|
||||
expect(slots).toEqual([]);
|
||||
expect(query).toMatchObject({ status: "closed", coveredUntil: "2026-09-26" });
|
||||
});
|
||||
|
||||
it("lleno: abre, pero ya no queda nada libre", () => {
|
||||
const todoElDia = { startUtc: "2026-09-22T16:00:00.000Z", endUtc: "2026-09-23T01:00:00.000Z" };
|
||||
const { slots, query } = porFecha(s, "2026-09-22", NOW, [todoElDia]);
|
||||
expect(slots).toEqual([]);
|
||||
expect(query.status).toBe("full");
|
||||
});
|
||||
|
||||
it("lleno también cuando hoy ya cerró", () => {
|
||||
const tarde = new Date("2026-09-22T01:30:00.000Z"); // lun 21, 19:30 CDMX
|
||||
expect(porFecha(s, "2026-09-21", tarde).query.status).toBe("full");
|
||||
});
|
||||
|
||||
it("un día que ya pasó se dice como tal", () => {
|
||||
expect(porFecha(s, "2026-09-20").query).toMatchObject({
|
||||
status: "past",
|
||||
coveredUntil: null,
|
||||
});
|
||||
});
|
||||
|
||||
it("más allá del horizonte no es «lleno»: aún no se abre agenda", () => {
|
||||
const { slots, query } = porFecha(s, "2026-09-29"); // hoy + 8
|
||||
expect(slots).toEqual([]);
|
||||
expect(query).toMatchObject({
|
||||
status: "beyond_horizon",
|
||||
horizonEnd: "2026-09-28",
|
||||
coveredUntil: null,
|
||||
});
|
||||
// El último día del horizonte todavía se agenda.
|
||||
expect(porFecha(s, "2026-09-28").query.status).toBe("available");
|
||||
});
|
||||
});
|
||||
|
||||
describe("la fecha es la del negocio, no la del servidor", () => {
|
||||
const s = ajustes();
|
||||
// Lunes 21, 22:30 en CDMX; en UTC ya es martes 22.
|
||||
const noche = new Date("2026-09-22T04:30:00.000Z");
|
||||
|
||||
function consultas() {
|
||||
const hoy = porFecha(s, "2026-09-21", noche);
|
||||
const manana = porFecha(s, "2026-09-22", noche);
|
||||
return {
|
||||
hoy: hoy.query.status,
|
||||
manana: manana.query.status,
|
||||
horas: horas(manana.slots),
|
||||
dia: manana.slots[0]?.dayLabel,
|
||||
primero: manana.slots[0]?.startUtc,
|
||||
horizonte: manana.query.horizonEnd,
|
||||
};
|
||||
}
|
||||
|
||||
it("«hoy» se decide en la zona del negocio", () => {
|
||||
const r = consultas();
|
||||
expect(r.hoy).toBe("full"); // el lunes sigue siendo hoy: no «past»
|
||||
expect(r.manana).toBe("available");
|
||||
expect(r.dia).toMatch(/^mañana martes/);
|
||||
expect(r.primero).toBe("2026-09-22T16:00:00.000Z"); // 10:00 CDMX
|
||||
expect(r.horizonte).toBe("2026-09-28");
|
||||
});
|
||||
|
||||
it("da lo mismo con el proceso en otra zona horaria", () => {
|
||||
const esperado = consultas();
|
||||
const original = process.env.TZ;
|
||||
try {
|
||||
const offsets = {
|
||||
"Pacific/Kiritimati": -840, // UTC+14: ya es otro día casi siempre
|
||||
"Pacific/Pago_Pago": 660, // UTC-11
|
||||
"Asia/Tokyo": -540,
|
||||
};
|
||||
for (const [tz, offset] of Object.entries(offsets)) {
|
||||
process.env.TZ = tz;
|
||||
// Que el cambio de zona sí surtió efecto en este proceso.
|
||||
expect(new Date("2026-01-01T00:00:00Z").getTimezoneOffset()).toBe(offset);
|
||||
expect(consultas()).toEqual(esperado);
|
||||
}
|
||||
} finally {
|
||||
if (original === undefined) delete process.env.TZ;
|
||||
else process.env.TZ = original;
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("horario de verano en la zona del negocio", () => {
|
||||
const diario = { start: "09:00", end: "18:00" };
|
||||
const s = ajustes({
|
||||
timezone: NY,
|
||||
weeklyHours: {
|
||||
mon: [diario], tue: [diario], wed: [diario], thu: [diario],
|
||||
fri: [diario], sat: [diario], sun: [diario],
|
||||
},
|
||||
});
|
||||
|
||||
it("el día que se adelanta el reloj: 09:00 es 13:00Z, y son las 18 horas", () => {
|
||||
const now = new Date("2026-03-07T12:00:00.000Z");
|
||||
const antes = porFecha(s, "2026-03-07", now);
|
||||
const cambio = porFecha(s, "2026-03-08", now);
|
||||
expect(antes.slots[0]!.startUtc).toBe("2026-03-07T14:00:00.000Z"); // EST
|
||||
expect(cambio.slots[0]!.startUtc).toBe("2026-03-08T13:00:00.000Z"); // EDT
|
||||
expect(cambio.slots).toHaveLength(18);
|
||||
expect(cambio.slots[17]!.time).toBe("17:30");
|
||||
expect(cambio.slots.every((x) => x.dayIso === "2026-03-08")).toBe(true);
|
||||
});
|
||||
|
||||
it("el día que se atrasa el reloj: 09:00 es 14:00Z", () => {
|
||||
const now = new Date("2026-10-31T12:00:00.000Z");
|
||||
const cambio = porFecha(s, "2026-11-01", now);
|
||||
expect(cambio.slots[0]!.startUtc).toBe("2026-11-01T14:00:00.000Z"); // EST
|
||||
expect(cambio.slots).toHaveLength(18);
|
||||
expect(new Set(horas(cambio.slots)).size).toBe(18);
|
||||
});
|
||||
|
||||
it("un hueco de noche cae en su día local aunque en UTC ya sea el siguiente", () => {
|
||||
const noche = ajustes({
|
||||
timezone: NY,
|
||||
weeklyHours: { sun: [{ start: "20:00", end: "23:30" }] },
|
||||
});
|
||||
const now = new Date("2026-03-07T12:00:00.000Z");
|
||||
const { slots, query } = porFecha(noche, "2026-03-08", now);
|
||||
expect(query.status).toBe("available");
|
||||
expect(horas(slots)).toEqual(["20:00", "20:30", "21:00", "21:30", "22:00", "22:30", "23:00"]);
|
||||
expect(slots[slots.length - 1]!.startUtc).toBe("2026-03-09T03:00:00.000Z");
|
||||
expect(slots.every((x) => x.dayIso === "2026-03-08")).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("sin date: el reparto de siempre, con cobertura", () => {
|
||||
const s = ajustes({ maxDaysAhead: 14 });
|
||||
const todos = libres(s, "2026-09-21", "2026-10-05");
|
||||
|
||||
/** La ruta ANTES de R10: repartir y luego recortar a `days`. */
|
||||
function antes(limit: number, perDay: number, days: number): string[] {
|
||||
const hoy = Date.parse("2026-09-21T00:00:00Z");
|
||||
return spreadByDay(todos, { timezone: MX, limit, perDay, now: NOW })
|
||||
.filter((x) => {
|
||||
const diff = (Date.parse(`${x.dayIso}T00:00:00Z`) - hoy) / 86_400_000;
|
||||
return diff >= 0 && diff < days;
|
||||
})
|
||||
.map((x) => x.startUtc);
|
||||
}
|
||||
|
||||
it.each([
|
||||
[12, 3, 5],
|
||||
[4, 3, 5],
|
||||
[48, 8, 14],
|
||||
[12, 3, 1],
|
||||
[12, 1, 2],
|
||||
[5, 2, 3],
|
||||
])("limit=%i perDay=%i days=%i da los mismos huecos que antes", (limit, perDay, days) => {
|
||||
const { slots } = armarHuecos({
|
||||
todos,
|
||||
timezone: MX,
|
||||
now: NOW,
|
||||
maxDaysAhead: 14,
|
||||
limit,
|
||||
perDay,
|
||||
days,
|
||||
});
|
||||
expect(slots.map((x) => x.startUtc)).toEqual(antes(limit, perDay, days));
|
||||
});
|
||||
|
||||
it("si no se llenó, se revisó toda la ventana", () => {
|
||||
// 2 días hábiles × 3 = 6 < 12: lo que falta en la ventana SÍ está cerrado.
|
||||
const { slots, query } = armarHuecos({
|
||||
todos,
|
||||
timezone: MX,
|
||||
now: NOW,
|
||||
maxDaysAhead: 14,
|
||||
limit: 12,
|
||||
perDay: 3,
|
||||
days: 2,
|
||||
});
|
||||
expect(slots).toHaveLength(6);
|
||||
expect(query.coveredUntil).toBe("2026-09-22");
|
||||
});
|
||||
|
||||
it("una ventana más larga que el horizonte se queda en el horizonte", () => {
|
||||
const { query } = armarHuecos({
|
||||
todos: libres(ajustes(), "2026-09-21", "2026-09-28"),
|
||||
timezone: MX,
|
||||
now: NOW,
|
||||
maxDaysAhead: 7,
|
||||
limit: 48,
|
||||
perDay: 8,
|
||||
days: 14,
|
||||
});
|
||||
expect(query.coveredUntil).toBe("2026-09-28");
|
||||
expect(query.horizonEnd).toBe("2026-09-28");
|
||||
});
|
||||
|
||||
it("sin huecos no inventa días y dice que revisó todo", () => {
|
||||
const { slots, query } = armarHuecos({
|
||||
todos: [],
|
||||
timezone: MX,
|
||||
now: NOW,
|
||||
maxDaysAhead: 7,
|
||||
limit: 12,
|
||||
perDay: 3,
|
||||
days: 5,
|
||||
});
|
||||
expect(slots).toEqual([]);
|
||||
expect(query.coveredUntil).toBe("2026-09-25");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,202 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
/**
|
||||
* 015 — El sandbox del Laboratorio en la agenda.
|
||||
*
|
||||
* Una cita de una conversación de prueba se registra, pero JAMÁS llega a un
|
||||
* conector: nadie crea una reunión de Zoom ni un evento en el calendario del
|
||||
* dueño por una simulación.
|
||||
*
|
||||
* Se prueba aquí y no en el arnés E2E por una razón concreta: las
|
||||
* conversaciones del Laboratorio no son alcanzables desde la API pública (a
|
||||
* propósito), así que no hay forma de conducirlas desde fuera. Este test sí
|
||||
* puede afirmar lo que importa —que el conector no se llama— en vez de
|
||||
* observarlo por ausencia.
|
||||
*
|
||||
* En el fork del que salió este motor la protección es ASIMÉTRICA: existe al
|
||||
* crear y está cableada a `false` al reprogramar y cancelar. Ahí no rompe nada
|
||||
* de milagro; aquí se comprueban las tres.
|
||||
*/
|
||||
|
||||
const settings = {
|
||||
weeklyHours: { wed: [{ start: "09:00", end: "18:00" }] },
|
||||
slotMinutes: 30,
|
||||
bufferMinutes: 0,
|
||||
minNoticeHours: 0,
|
||||
maxDaysAhead: 7,
|
||||
timezone: "America/Mexico_City",
|
||||
connector: "zoom" as const,
|
||||
meetingLink: null,
|
||||
};
|
||||
|
||||
const SLOT = "2026-08-05T15:00:00.000Z";
|
||||
|
||||
const createMeeting = vi.fn(async () => ({
|
||||
externalId: "zoom_1",
|
||||
joinUrl: "https://zoom.test/j/1",
|
||||
}));
|
||||
const updateMeeting = vi.fn(async () => {});
|
||||
const deleteMeeting = vi.fn(async () => {});
|
||||
const bindConnector = vi.fn(async () => ({
|
||||
id: "zoom",
|
||||
createMeeting,
|
||||
updateMeeting,
|
||||
deleteMeeting,
|
||||
testConnection: async () => ({ ok: true }),
|
||||
}));
|
||||
|
||||
vi.mock("@/server/agenda/settings", () => ({ getSettings: async () => settings }));
|
||||
vi.mock("@/server/agenda/availability", () => ({
|
||||
findSlot: async () => ({ startUtc: SLOT, endUtc: "…", label: "mié 5 ago, 09:00" }),
|
||||
computeAvailability: async () => [],
|
||||
}));
|
||||
vi.mock("@/server/agenda/offers", async (importOriginal) => {
|
||||
const original = await importOriginal<typeof import("@/server/agenda/offers")>();
|
||||
return {
|
||||
...original,
|
||||
getOffers: async () => [{ startUtc: SLOT, label: "mié 5 ago, 09:00" }],
|
||||
replaceOffers: async () => {},
|
||||
clearOffers: async () => {},
|
||||
};
|
||||
});
|
||||
vi.mock("@/server/agenda/connectors", () => ({
|
||||
bindConnector,
|
||||
markConnectorAuthError: async () => {},
|
||||
}));
|
||||
vi.mock("@/server/leads/stage-history", () => ({
|
||||
moveLeadToStage: async () => ({ ok: true }),
|
||||
}));
|
||||
vi.mock("@/server/events/bus", () => ({ publish: () => {} }));
|
||||
|
||||
const selectRows: unknown[][] = [];
|
||||
let lastInsert: Record<string, unknown> | null = null;
|
||||
/** La fila que devuelve un `update(...).returning()`. */
|
||||
let updatedRow: Record<string, unknown> = {};
|
||||
|
||||
function chain(rows: unknown[]) {
|
||||
const c: Record<string, unknown> = {};
|
||||
for (const m of ["from", "where", "orderBy", "leftJoin"]) c[m] = () => c;
|
||||
c.limit = () => Promise.resolve(rows);
|
||||
return c;
|
||||
}
|
||||
|
||||
vi.mock("@/lib/db", () => ({
|
||||
getDb: () => ({
|
||||
select: () => chain(selectRows.shift() ?? []),
|
||||
insert: () => ({
|
||||
values: (v: Record<string, unknown>) => ({
|
||||
returning: () => {
|
||||
lastInsert = v;
|
||||
return Promise.resolve([
|
||||
{ ...v, scheduledAt: new Date(SLOT), externalRef: null, linkPending: false },
|
||||
]);
|
||||
},
|
||||
}),
|
||||
}),
|
||||
update: () => ({
|
||||
set: (v: Record<string, unknown>) => ({
|
||||
where: () => ({
|
||||
returning: () => Promise.resolve([{ ...updatedRow, ...v }]),
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
schema: {
|
||||
booking: {},
|
||||
conversation: { organizationId: "organizationId", id: "id" },
|
||||
contact: { organizationId: "organizationId", id: "id", name: "name" },
|
||||
lead: { organizationId: "organizationId", contactId: "contactId" },
|
||||
pipelineStage: { organizationId: "organizationId" },
|
||||
offeredSlot: {},
|
||||
},
|
||||
}));
|
||||
|
||||
const CITA_DE_PRUEBA = {
|
||||
id: "bk_test",
|
||||
organizationId: "org_1",
|
||||
scheduledAt: new Date(SLOT),
|
||||
durationMinutes: 30,
|
||||
status: "agendada",
|
||||
isTest: true,
|
||||
connector: "zoom",
|
||||
// Aunque tuviera reunión, no debe tocarse: es de prueba.
|
||||
externalRef: "zoom_viejo",
|
||||
meetingLink: null,
|
||||
linkPending: false,
|
||||
notes: null,
|
||||
contactId: "ct_1",
|
||||
};
|
||||
|
||||
describe("una cita del Laboratorio jamás llega al proveedor", () => {
|
||||
beforeEach(() => {
|
||||
selectRows.length = 0;
|
||||
lastInsert = null;
|
||||
updatedRow = { ...CITA_DE_PRUEBA };
|
||||
createMeeting.mockClear();
|
||||
updateMeeting.mockClear();
|
||||
deleteMeeting.mockClear();
|
||||
bindConnector.mockClear();
|
||||
});
|
||||
|
||||
it("al CREAR: la cita se registra como de prueba y no se crea reunión", async () => {
|
||||
const { createSessionBooking } = await import("@/server/agenda/service");
|
||||
selectRows.push([{ contactId: "ct_1", isTest: true }]); // la conversación
|
||||
selectRows.push([{ name: "Persona simulada" }]); // el contacto
|
||||
selectRows.push([]); // sin lead
|
||||
|
||||
const result = await createSessionBooking({
|
||||
organizationId: "org_1",
|
||||
conversationId: "cv_lab",
|
||||
startUtc: SLOT,
|
||||
source: "ai",
|
||||
requireOffer: true,
|
||||
});
|
||||
|
||||
expect(lastInsert?.isTest).toBe(true);
|
||||
expect(result.booking.isTest).toBe(true);
|
||||
// Lo que importa: ni siquiera se resolvió el conector.
|
||||
expect(bindConnector).not.toHaveBeenCalled();
|
||||
expect(createMeeting).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("al REPROGRAMAR: no se mueve nada en el proveedor", async () => {
|
||||
const { rescheduleBooking } = await import("@/server/agenda/service");
|
||||
selectRows.push([CITA_DE_PRUEBA]);
|
||||
|
||||
await rescheduleBooking({
|
||||
organizationId: "org_1",
|
||||
bookingId: "bk_test",
|
||||
startUtc: SLOT,
|
||||
});
|
||||
|
||||
expect(updateMeeting).not.toHaveBeenCalled();
|
||||
expect(bindConnector).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("al CANCELAR: no se borra nada en el proveedor", async () => {
|
||||
const { cancelBooking } = await import("@/server/agenda/service");
|
||||
selectRows.push([CITA_DE_PRUEBA]);
|
||||
|
||||
await cancelBooking({ organizationId: "org_1", bookingId: "bk_test" });
|
||||
|
||||
expect(deleteMeeting).not.toHaveBeenCalled();
|
||||
expect(bindConnector).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("una cita REAL sí llega al proveedor (el guardarraíl no apaga todo)", async () => {
|
||||
const { createSessionBooking } = await import("@/server/agenda/service");
|
||||
selectRows.push([{ contactId: "ct_1", isTest: false }]);
|
||||
selectRows.push([{ name: "Cliente real" }]);
|
||||
selectRows.push([]);
|
||||
|
||||
await createSessionBooking({
|
||||
organizationId: "org_1",
|
||||
conversationId: "cv_real",
|
||||
startUtc: SLOT,
|
||||
source: "ai",
|
||||
requireOffer: true,
|
||||
});
|
||||
|
||||
expect(createMeeting).toHaveBeenCalledOnce();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,224 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { z } from "zod";
|
||||
import { chatJson, extractJson } from "@/lib/ai";
|
||||
import type { AiCredentialSecret } from "@/server/ai/credentials";
|
||||
|
||||
/**
|
||||
* #85 — La fila de Ajustes → IA de la organización, simulada. Sin fila
|
||||
* (`null`) el adaptador cae a las variables del entorno de abajo. Las marcas
|
||||
* de estado se capturan en vez de escribirse.
|
||||
*/
|
||||
const fila: { current: AiCredentialSecret | null } = { current: null };
|
||||
const marcas: { status: number; nuevo: string }[] = [];
|
||||
|
||||
vi.mock("@/server/ai/credentials", async (importOriginal) => {
|
||||
const original = await importOriginal<typeof import("@/server/ai/credentials")>();
|
||||
return {
|
||||
...original,
|
||||
getAiCredentialSecret: async () => fila.current,
|
||||
getAiCredentialPublic: async () => fila.current,
|
||||
marcarEstadoPorRespuesta: async (_org: string, status: number) => {
|
||||
const nuevo = original.estadoSegunRespuesta(status);
|
||||
if (!nuevo) return false;
|
||||
marcas.push({ status, nuevo });
|
||||
return true;
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
const FILA_ORG: AiCredentialSecret = {
|
||||
provider: "openai_compatible",
|
||||
baseUrl: "https://proveedor.test/v1",
|
||||
model: "org/modelo",
|
||||
tokenLast4: "1234",
|
||||
status: "active",
|
||||
statusReason: null,
|
||||
statusChangedAt: null,
|
||||
updatedAt: new Date(),
|
||||
token: "tok-org-1234",
|
||||
};
|
||||
|
||||
describe("extractJson (extracción robusta)", () => {
|
||||
it("JSON limpio", () => {
|
||||
expect(extractJson('{"action":"none"}')).toEqual({ action: "none" });
|
||||
});
|
||||
|
||||
it("bloque ```json con texto alrededor", () => {
|
||||
const raw = 'Claro, aquí está:\n```json\n{"action":"reply","text":"hola"}\n```\nEspero que sirva.';
|
||||
expect(extractJson(raw)).toEqual({ action: "reply", text: "hola" });
|
||||
});
|
||||
|
||||
it("JSON incrustado en prosa (primer { al último })", () => {
|
||||
const raw = 'La acción que tomaré es {"action":"handoff","reason":"cliente"} por lo dicho.';
|
||||
expect(extractJson(raw)).toEqual({ action: "handoff", reason: "cliente" });
|
||||
});
|
||||
|
||||
it("sin JSON → null", () => {
|
||||
expect(extractJson("no tengo nada que decir")).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("chatJson (reintentos y errores tipados)", () => {
|
||||
const schema = z.object({ action: z.literal("reply"), text: z.string() });
|
||||
|
||||
beforeEach(() => {
|
||||
vi.stubEnv("APP_BASE_URL", "http://localhost:3000");
|
||||
vi.stubEnv("DATABASE_URL", "postgresql://t:t@localhost:5432/t");
|
||||
vi.stubEnv("BETTER_AUTH_SECRET", "secret-de-test-suficiente");
|
||||
vi.stubEnv("ENCRYPTION_KEY", Buffer.alloc(32, 3).toString("base64"));
|
||||
vi.stubEnv("META_WEBHOOK_VERIFY_TOKEN", "verify-test");
|
||||
vi.stubEnv("OPENROUTER_API_TOKEN", "token-test");
|
||||
vi.stubEnv("OPENROUTER_MODEL", "modelo-test");
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllEnvs();
|
||||
vi.unstubAllGlobals();
|
||||
fila.current = null;
|
||||
marcas.length = 0;
|
||||
});
|
||||
|
||||
function providerResponse(content: string) {
|
||||
return new Response(
|
||||
JSON.stringify({ choices: [{ message: { content } }] }),
|
||||
{ status: 200, headers: { "content-type": "application/json" } }
|
||||
);
|
||||
}
|
||||
|
||||
it("salida inválida al primer intento → reintenta con STRICT y triunfa", async () => {
|
||||
const fetchMock = vi
|
||||
.fn()
|
||||
.mockResolvedValueOnce(providerResponse("no soy json"))
|
||||
.mockResolvedValueOnce(providerResponse('{"action":"reply","text":"ok"}'));
|
||||
vi.stubGlobal("fetch", fetchMock);
|
||||
|
||||
const result = await chatJson(schema, [{ role: "user", content: "hola" }]);
|
||||
expect(result.ok).toBe(true);
|
||||
if (result.ok) expect(result.data.text).toBe("ok");
|
||||
expect(fetchMock).toHaveBeenCalledTimes(2);
|
||||
// el reintento agrega la instrucción STRICT
|
||||
const secondBody = JSON.parse(fetchMock.mock.calls[1]![1]!.body as string);
|
||||
expect(JSON.stringify(secondBody.messages)).toContain("STRICT");
|
||||
});
|
||||
|
||||
it("proveedor caído (500 persistente) → error tipado, jamás excepción", async () => {
|
||||
const fetchMock = vi
|
||||
.fn()
|
||||
.mockImplementation(() =>
|
||||
Promise.resolve(new Response("boom", { status: 500 }))
|
||||
);
|
||||
vi.stubGlobal("fetch", fetchMock);
|
||||
|
||||
const result = await chatJson(schema, [{ role: "user", content: "hola" }]);
|
||||
expect(result.ok).toBe(false);
|
||||
if (!result.ok) expect(result.error).toBe("provider_error");
|
||||
expect(fetchMock).toHaveBeenCalledTimes(3); // agotó los 3 intentos
|
||||
});
|
||||
|
||||
it("salida que nunca cumple el esquema → invalid_output", async () => {
|
||||
const fetchMock = vi
|
||||
.fn()
|
||||
.mockImplementation(() =>
|
||||
Promise.resolve(providerResponse('{"action":"otra_cosa"}'))
|
||||
);
|
||||
vi.stubGlobal("fetch", fetchMock);
|
||||
|
||||
const result = await chatJson(schema, [{ role: "user", content: "hola" }]);
|
||||
expect(result.ok).toBe(false);
|
||||
if (!result.ok) expect(result.error).toBe("invalid_output");
|
||||
});
|
||||
|
||||
it("sin token → not_configured sin tocar la red", async () => {
|
||||
vi.stubEnv("OPENROUTER_API_TOKEN", "");
|
||||
const fetchMock = vi.fn();
|
||||
vi.stubGlobal("fetch", fetchMock);
|
||||
|
||||
const result = await chatJson(schema, [{ role: "user", content: "hola" }]);
|
||||
expect(result.ok).toBe(false);
|
||||
if (!result.ok) expect(result.error).toBe("not_configured");
|
||||
expect(fetchMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
// ---- #85: la fila de Ajustes → IA ----------------------------------------
|
||||
|
||||
it("la fila de la organización manda sobre el entorno: su base URL, su modelo y su llave", async () => {
|
||||
fila.current = FILA_ORG;
|
||||
const fetchMock = vi
|
||||
.fn()
|
||||
.mockResolvedValueOnce(providerResponse('{"action":"reply","text":"ok"}'));
|
||||
vi.stubGlobal("fetch", fetchMock);
|
||||
|
||||
const result = await chatJson(schema, [{ role: "user", content: "hola" }], {
|
||||
organizationId: "org_1",
|
||||
});
|
||||
expect(result.ok).toBe(true);
|
||||
const [url, init] = fetchMock.mock.calls[0]!;
|
||||
expect(url).toBe("https://proveedor.test/v1/chat/completions");
|
||||
expect((init as RequestInit).headers).toMatchObject({
|
||||
Authorization: "Bearer tok-org-1234",
|
||||
});
|
||||
expect(JSON.parse((init as RequestInit).body as string).model).toBe("org/modelo");
|
||||
});
|
||||
|
||||
it("401 sobre la fila → pausa por llave y NO reintenta", async () => {
|
||||
fila.current = FILA_ORG;
|
||||
const fetchMock = vi
|
||||
.fn()
|
||||
.mockImplementation(() => Promise.resolve(new Response("unauthorized", { status: 401 })));
|
||||
vi.stubGlobal("fetch", fetchMock);
|
||||
|
||||
const result = await chatJson(schema, [{ role: "user", content: "hola" }], {
|
||||
organizationId: "org_1",
|
||||
});
|
||||
expect(result.ok).toBe(false);
|
||||
if (!result.ok) expect(result.error).toBe("provider_error");
|
||||
expect(fetchMock).toHaveBeenCalledTimes(1);
|
||||
expect(marcas).toEqual([{ status: 401, nuevo: "paused_invalid_token" }]);
|
||||
});
|
||||
|
||||
it("402 sobre la fila → pausa por saldo", async () => {
|
||||
fila.current = FILA_ORG;
|
||||
vi.stubGlobal(
|
||||
"fetch",
|
||||
vi.fn().mockImplementation(() => Promise.resolve(new Response("", { status: 402 })))
|
||||
);
|
||||
await chatJson(schema, [{ role: "user", content: "hola" }], { organizationId: "org_1" });
|
||||
expect(marcas).toEqual([{ status: 402, nuevo: "paused_no_credit" }]);
|
||||
});
|
||||
|
||||
it("429 sobre la fila → no pausa y agota los reintentos", async () => {
|
||||
fila.current = FILA_ORG;
|
||||
const fetchMock = vi
|
||||
.fn()
|
||||
.mockImplementation(() => Promise.resolve(new Response("slow down", { status: 429 })));
|
||||
vi.stubGlobal("fetch", fetchMock);
|
||||
await chatJson(schema, [{ role: "user", content: "hola" }], { organizationId: "org_1" });
|
||||
expect(fetchMock).toHaveBeenCalledTimes(3);
|
||||
expect(marcas).toEqual([]);
|
||||
});
|
||||
|
||||
it("fila pausada → not_configured sin tocar la red, aunque el entorno tenga token", async () => {
|
||||
fila.current = { ...FILA_ORG, status: "paused_no_credit" };
|
||||
const fetchMock = vi.fn();
|
||||
vi.stubGlobal("fetch", fetchMock);
|
||||
const result = await chatJson(schema, [{ role: "user", content: "hola" }], {
|
||||
organizationId: "org_1",
|
||||
});
|
||||
expect(result.ok).toBe(false);
|
||||
if (!result.ok) {
|
||||
expect(result.error).toBe("not_configured");
|
||||
expect(result.detail).toContain("saldo");
|
||||
}
|
||||
expect(fetchMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("401 con la llave del entorno (sin fila) → reintenta y no marca nada", async () => {
|
||||
const fetchMock = vi
|
||||
.fn()
|
||||
.mockImplementation(() => Promise.resolve(new Response("", { status: 401 })));
|
||||
vi.stubGlobal("fetch", fetchMock);
|
||||
await chatJson(schema, [{ role: "user", content: "hola" }], { organizationId: "org_1" });
|
||||
expect(fetchMock).toHaveBeenCalledTimes(3);
|
||||
expect(marcas).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,42 @@
|
||||
import React from "react";
|
||||
import { renderToStaticMarkup } from "react-dom/server";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { AiClient } from "@/components/settings/ai-client";
|
||||
import { AvisoIaBanner } from "@/components/avisos/aviso-ia";
|
||||
|
||||
/**
|
||||
* #85 — Ajustes → IA y el banner, dibujados en el servidor (sin efectos):
|
||||
* la ayuda va plegada, la llave es un campo de contraseña y los dos botones
|
||||
* del proveedor existen antes de cargar nada.
|
||||
*/
|
||||
describe("Ajustes → IA", () => {
|
||||
it("ofrece la guía plegada, enlaza saldo y llaves, y pide la llave como contraseña", () => {
|
||||
const html = renderToStaticMarkup(React.createElement(AiClient));
|
||||
expect(html).toContain("¿Cómo consigo mi llave?");
|
||||
expect(html).not.toContain("<details open");
|
||||
expect(html).toContain('href="https://openrouter.ai/settings/credits"');
|
||||
expect(html).toContain('href="https://openrouter.ai/settings/keys"');
|
||||
expect(html).toContain('type="password"');
|
||||
expect(html).toContain("Probar conexión");
|
||||
expect(html).toContain("Traer modelos");
|
||||
expect(html).toContain("OpenRouter");
|
||||
expect(html).toContain("Otro compatible con OpenAI");
|
||||
// El respaldo del entorno se explica sin mandar a editar el .env.
|
||||
expect(html).toContain("OPENROUTER_API_TOKEN");
|
||||
expect(html).not.toContain("reinic");
|
||||
});
|
||||
});
|
||||
|
||||
describe("banner del agente sin IA", () => {
|
||||
it("manda a Ajustes → IA con la acción que toca; sin aviso no dibuja nada", () => {
|
||||
const html = renderToStaticMarkup(
|
||||
React.createElement(AvisoIaBanner, {
|
||||
aviso: { mensaje: "Tu agente está pausado.", accion: "Revisar mi conexión" },
|
||||
})
|
||||
);
|
||||
expect(html).toContain("Tu agente está pausado.");
|
||||
expect(html).toContain("Revisar mi conexión");
|
||||
expect(html).toContain('href="/settings/ai"');
|
||||
expect(renderToStaticMarkup(React.createElement(AvisoIaBanner, { aviso: null }))).toBe("");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,257 @@
|
||||
import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
|
||||
import {
|
||||
apiRoot,
|
||||
chatCompletionsUrl,
|
||||
last4,
|
||||
modelsUrl,
|
||||
OPENROUTER_BASE_URL,
|
||||
presetDeBaseUrl,
|
||||
} from "@/lib/ai/presets";
|
||||
import {
|
||||
envAiProvider,
|
||||
interpretarCredencial,
|
||||
mensajeDeEstado,
|
||||
resolver,
|
||||
type AiProvider,
|
||||
} from "@/lib/ai/provider";
|
||||
import { estadoSegunRespuesta } from "@/server/ai/credentials";
|
||||
import {
|
||||
aiModelsSchema,
|
||||
aiProbeSchema,
|
||||
aiSettingsPutSchema,
|
||||
baseUrlEfectiva,
|
||||
} from "@/server/ai/settings";
|
||||
import type { AiCredentialSecret } from "@/server/ai/credentials";
|
||||
|
||||
/**
|
||||
* #85 — Ajustes → IA. Las reglas puras: con quién habla el adaptador (la fila
|
||||
* manda, el entorno es respaldo), qué hace cada código del proveedor con el
|
||||
* estado, y qué acepta el `PUT`.
|
||||
*/
|
||||
|
||||
const FILA: AiCredentialSecret = {
|
||||
provider: "openrouter",
|
||||
baseUrl: OPENROUTER_BASE_URL,
|
||||
model: "org/modelo",
|
||||
tokenLast4: "1234",
|
||||
status: "active",
|
||||
statusReason: null,
|
||||
statusChangedAt: new Date("2026-10-01T00:00:00Z"),
|
||||
updatedAt: new Date("2026-10-01T00:00:00Z"),
|
||||
token: "sk-or-fila-1234",
|
||||
};
|
||||
|
||||
const ENTORNO: AiProvider = {
|
||||
source: "env",
|
||||
baseUrl: "https://entorno.test",
|
||||
model: "env/modelo",
|
||||
judgeModel: "env/juez",
|
||||
token: "tok-entorno-9999",
|
||||
};
|
||||
|
||||
describe("URLs del proveedor", () => {
|
||||
it("añade /v1 a la base del repo y no lo duplica si ya viene", () => {
|
||||
expect(apiRoot("https://openrouter.ai/api")).toBe("https://openrouter.ai/api/v1");
|
||||
expect(apiRoot("https://openrouter.ai/api/")).toBe("https://openrouter.ai/api/v1");
|
||||
expect(apiRoot("https://api.groq.com/openai/v1")).toBe("https://api.groq.com/openai/v1");
|
||||
expect(apiRoot("https://api.groq.com/openai/v1/")).toBe("https://api.groq.com/openai/v1");
|
||||
expect(chatCompletionsUrl("http://localhost:3000/api/dev/ai-mock")).toBe(
|
||||
"http://localhost:3000/api/dev/ai-mock/v1/chat/completions"
|
||||
);
|
||||
expect(modelsUrl("https://api.openai.com")).toBe("https://api.openai.com/v1/models");
|
||||
});
|
||||
|
||||
it("reconoce el preset por la base URL", () => {
|
||||
expect(presetDeBaseUrl("https://openrouter.ai/api")).toBe("openrouter");
|
||||
expect(presetDeBaseUrl("https://openrouter.ai/api/v1/")).toBe("openrouter");
|
||||
expect(presetDeBaseUrl("https://api.openai.com")).toBe("openai_compatible");
|
||||
});
|
||||
|
||||
it("last4 expone solo los últimos 4", () => {
|
||||
expect(last4("sk-or-abcdefgh-wxyz")).toBe("wxyz");
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolución: la fila manda, el entorno es respaldo", () => {
|
||||
it("fila activa → la fila, aunque el entorno tenga su propio token", () => {
|
||||
const r = resolver(FILA, ENTORNO);
|
||||
expect(r.ok).toBe(true);
|
||||
if (r.ok) {
|
||||
expect(r.provider.source).toBe("org");
|
||||
expect(r.provider.token).toBe(FILA.token);
|
||||
expect(r.provider.model).toBe("org/modelo");
|
||||
// Un solo modelo en la UI: el juez usa el mismo.
|
||||
expect(r.provider.judgeModel).toBe("org/modelo");
|
||||
}
|
||||
});
|
||||
|
||||
it("sin fila → el entorno tal cual (con su juez aparte)", () => {
|
||||
const r = resolver(null, ENTORNO);
|
||||
expect(r.ok).toBe(true);
|
||||
if (r.ok) expect(r.provider).toEqual(ENTORNO);
|
||||
});
|
||||
|
||||
it("sin nada → no configurado", () => {
|
||||
const r = resolver(null, null);
|
||||
expect(r).toEqual({ ok: false, estado: { activa: false, motivo: "sin_configurar" } });
|
||||
});
|
||||
|
||||
it("fila pausada NO cae al entorno: el dueño configuró su llave y debe ver el problema", () => {
|
||||
const r = resolver({ ...FILA, status: "paused_invalid_token" }, ENTORNO);
|
||||
expect(r.ok).toBe(false);
|
||||
if (!r.ok) {
|
||||
expect(r.estado).toEqual({
|
||||
activa: false,
|
||||
motivo: "token_invalido",
|
||||
last4: "1234",
|
||||
desde: FILA.statusChangedAt,
|
||||
});
|
||||
}
|
||||
const sinSaldo = resolver({ ...FILA, status: "paused_no_credit" }, null);
|
||||
expect(sinSaldo.ok).toBe(false);
|
||||
if (!sinSaldo.ok) expect(sinSaldo.estado.motivo).toBe("sin_saldo");
|
||||
});
|
||||
|
||||
it("interpretarCredencial distingue el origen", () => {
|
||||
expect(interpretarCredencial(FILA, { last4: "9999" })).toEqual({
|
||||
activa: true,
|
||||
origen: "org",
|
||||
last4: "1234",
|
||||
});
|
||||
expect(interpretarCredencial(null, { last4: "9999" })).toEqual({
|
||||
activa: true,
|
||||
origen: "env",
|
||||
last4: "9999",
|
||||
});
|
||||
expect(interpretarCredencial(null, null)).toEqual({
|
||||
activa: false,
|
||||
motivo: "sin_configurar",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("la máquina de estados la dicta quien cobra", () => {
|
||||
it("401 pausa por llave, 402 por saldo; 429 y 500 no pausan", () => {
|
||||
expect(estadoSegunRespuesta(401)).toBe("paused_invalid_token");
|
||||
expect(estadoSegunRespuesta(402)).toBe("paused_no_credit");
|
||||
expect(estadoSegunRespuesta(429)).toBeNull();
|
||||
expect(estadoSegunRespuesta(500)).toBeNull();
|
||||
expect(estadoSegunRespuesta(200)).toBeNull();
|
||||
});
|
||||
|
||||
it("cada motivo manda a Ajustes → IA; activa no dice nada", () => {
|
||||
expect(mensajeDeEstado({ activa: true, origen: "org", last4: "1234" })).toBeNull();
|
||||
for (const motivo of ["sin_configurar", "token_invalido", "sin_saldo"] as const) {
|
||||
const estado =
|
||||
motivo === "sin_configurar"
|
||||
? { activa: false as const, motivo }
|
||||
: { activa: false as const, motivo, last4: "1234", desde: null };
|
||||
expect(mensajeDeEstado(estado)).toContain("Ajustes → IA");
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("validación del PUT /api/settings/ai", () => {
|
||||
it("OpenRouter: proveedor + modelo + llave; la base URL la pone el preset", () => {
|
||||
const r = aiSettingsPutSchema.safeParse({
|
||||
provider: "openrouter",
|
||||
model: " anthropic/claude-sonnet-4.5 ",
|
||||
token: "sk-or-llave-larga",
|
||||
});
|
||||
expect(r.success).toBe(true);
|
||||
if (r.success) {
|
||||
expect(r.data.model).toBe("anthropic/claude-sonnet-4.5");
|
||||
expect(baseUrlEfectiva(r.data.provider, "https://otra.cosa")).toBe(OPENROUTER_BASE_URL);
|
||||
}
|
||||
});
|
||||
|
||||
it("«Otro compatible» exige base URL http(s); se le quita la barra final", () => {
|
||||
const sin = aiSettingsPutSchema.safeParse({
|
||||
provider: "openai_compatible",
|
||||
model: "gpt-4.1-mini",
|
||||
token: "sk-llave-larga",
|
||||
});
|
||||
expect(sin.success).toBe(false);
|
||||
if (!sin.success) {
|
||||
expect(sin.error.issues.some((i) => i.path.join(".") === "baseUrl")).toBe(true);
|
||||
}
|
||||
const ftp = aiSettingsPutSchema.safeParse({
|
||||
provider: "openai_compatible",
|
||||
baseUrl: "ftp://api.x.com",
|
||||
model: "m",
|
||||
token: "sk-llave-larga",
|
||||
});
|
||||
expect(ftp.success).toBe(false);
|
||||
const ok = aiSettingsPutSchema.safeParse({
|
||||
provider: "openai_compatible",
|
||||
baseUrl: "https://api.x.com/",
|
||||
model: "m",
|
||||
});
|
||||
expect(ok.success).toBe(true);
|
||||
if (ok.success) {
|
||||
expect(baseUrlEfectiva(ok.data.provider, ok.data.baseUrl)).toBe("https://api.x.com");
|
||||
}
|
||||
});
|
||||
|
||||
it("la llave es opcional (solo cambia proveedor/modelo), pero si viene tiene mínimo 8", () => {
|
||||
expect(
|
||||
aiSettingsPutSchema.safeParse({ provider: "openrouter", model: "m" }).success
|
||||
).toBe(true);
|
||||
expect(
|
||||
aiSettingsPutSchema.safeParse({ provider: "openrouter", model: "m", token: "corta" })
|
||||
.success
|
||||
).toBe(false);
|
||||
expect(
|
||||
aiSettingsPutSchema.safeParse({ provider: "openrouter", model: "", token: "sk-llave-larga" })
|
||||
.success
|
||||
).toBe(false);
|
||||
expect(
|
||||
aiSettingsPutSchema.safeParse({ provider: "otro", model: "m", token: "sk-llave-larga" })
|
||||
.success
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("probar exige modelo; traer modelos no", () => {
|
||||
expect(aiProbeSchema.safeParse({ provider: "openrouter" }).success).toBe(false);
|
||||
expect(aiProbeSchema.safeParse({ provider: "openrouter", model: "m" }).success).toBe(true);
|
||||
expect(aiModelsSchema.safeParse({ provider: "openrouter" }).success).toBe(true);
|
||||
expect(
|
||||
aiModelsSchema.safeParse({ provider: "openai_compatible", token: "sk-llave-larga" }).success
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("el respaldo del entorno", () => {
|
||||
const original = { ...process.env };
|
||||
|
||||
beforeAll(() => {
|
||||
vi.stubEnv("APP_BASE_URL", "http://localhost:3000");
|
||||
vi.stubEnv("DATABASE_URL", "postgresql://t:t@localhost:5432/t");
|
||||
vi.stubEnv("BETTER_AUTH_SECRET", "secret-de-test-suficiente");
|
||||
vi.stubEnv("ENCRYPTION_KEY", Buffer.alloc(32, 3).toString("base64"));
|
||||
vi.stubEnv("META_WEBHOOK_VERIFY_TOKEN", "verify-test");
|
||||
});
|
||||
|
||||
afterAll(() => {
|
||||
vi.unstubAllEnvs();
|
||||
process.env = { ...original };
|
||||
});
|
||||
|
||||
it("sin OPENROUTER_API_TOKEN → null, sin validar el resto del entorno", () => {
|
||||
vi.stubEnv("OPENROUTER_API_TOKEN", "");
|
||||
expect(envAiProvider()).toBeNull();
|
||||
});
|
||||
|
||||
it("con token → proveedor del entorno; el juez cae al modelo principal", () => {
|
||||
vi.stubEnv("OPENROUTER_API_TOKEN", "tok-entorno-9999");
|
||||
vi.stubEnv("OPENROUTER_MODEL", "env/modelo");
|
||||
const p = envAiProvider();
|
||||
expect(p).toMatchObject({
|
||||
source: "env",
|
||||
baseUrl: "https://openrouter.ai/api",
|
||||
model: "env/modelo",
|
||||
judgeModel: "env/modelo",
|
||||
token: "tok-entorno-9999",
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,173 @@
|
||||
import { beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
/**
|
||||
* #85 — La llave del proveedor de IA se guarda cifrada (jamás texto plano en
|
||||
* la fila), a la UI solo viajan sus últimos 4, y el estado lo escribe el
|
||||
* adaptador según lo que respondió el proveedor.
|
||||
*/
|
||||
|
||||
const inserted: Record<string, unknown>[] = [];
|
||||
const updated: Record<string, unknown>[] = [];
|
||||
/** Lo que devuelve el UPDATE … RETURNING: vacío = no había fila. */
|
||||
let filaExistente: Record<string, unknown>[] = [];
|
||||
|
||||
vi.mock("@/lib/db", () => ({
|
||||
getDb: () => ({
|
||||
insert: () => ({
|
||||
values: (v: Record<string, unknown>) => {
|
||||
inserted.push(v);
|
||||
return {
|
||||
onConflictDoUpdate: () => ({
|
||||
returning: () =>
|
||||
Promise.resolve([
|
||||
{ ...v, createdAt: new Date(), updatedAt: new Date() },
|
||||
]),
|
||||
}),
|
||||
};
|
||||
},
|
||||
}),
|
||||
update: () => ({
|
||||
set: (v: Record<string, unknown>) => {
|
||||
updated.push(v);
|
||||
return {
|
||||
where: () => {
|
||||
const rows = filaExistente.map((f) => ({ ...f, ...v }));
|
||||
return {
|
||||
returning: () => Promise.resolve(rows),
|
||||
then: (resolve: (x: unknown) => void) =>
|
||||
Promise.resolve(rows).then(resolve),
|
||||
};
|
||||
},
|
||||
};
|
||||
},
|
||||
}),
|
||||
}),
|
||||
schema: {
|
||||
aiCredentials: { organizationId: "organization_id" },
|
||||
},
|
||||
}));
|
||||
|
||||
beforeAll(() => {
|
||||
process.env.APP_BASE_URL = "http://localhost:3000";
|
||||
process.env.DATABASE_URL = "postgresql://t:t@localhost:5432/t";
|
||||
process.env.BETTER_AUTH_SECRET = "secret-de-test-suficiente";
|
||||
process.env.ENCRYPTION_KEY = Buffer.alloc(32, 9).toString("base64");
|
||||
process.env.META_WEBHOOK_VERIFY_TOKEN = "verify-test";
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
inserted.length = 0;
|
||||
updated.length = 0;
|
||||
filaExistente = [];
|
||||
});
|
||||
|
||||
describe("saveAiCredential", () => {
|
||||
it("cifra la llave: la fila no contiene el texto plano y queda activa", async () => {
|
||||
const { saveAiCredential } = await import("@/server/ai/credentials");
|
||||
const token = "sk-or-llave-super-secreta-abcd";
|
||||
const guardada = await saveAiCredential({
|
||||
organizationId: "org_1",
|
||||
provider: "openrouter",
|
||||
baseUrl: "https://openrouter.ai/api",
|
||||
model: "anthropic/claude-sonnet-4.5",
|
||||
token,
|
||||
});
|
||||
const row = inserted[0]!;
|
||||
expect(JSON.stringify(row)).not.toContain(token);
|
||||
expect(row.tokenCipher).toBeTruthy();
|
||||
expect(row.tokenIv).toBeTruthy();
|
||||
expect(row.tokenTag).toBeTruthy();
|
||||
expect(row.tokenLast4).toBe("abcd");
|
||||
expect(row.status).toBe("active");
|
||||
expect(row.statusReason).toBeNull();
|
||||
expect(String(row.id)).toMatch(/^aicred_/);
|
||||
|
||||
// y el cifrado es reversible con la clave de la instancia
|
||||
const { decryptSecret } = await import("@/lib/crypto");
|
||||
expect(
|
||||
decryptSecret({
|
||||
cipher: row.tokenCipher as string,
|
||||
iv: row.tokenIv as string,
|
||||
tag: row.tokenTag as string,
|
||||
})
|
||||
).toBe(token);
|
||||
|
||||
// lo que vuelve hacia fuera no trae el token ni el cifrado
|
||||
expect(JSON.stringify(guardada)).not.toContain(token);
|
||||
expect(guardada).not.toHaveProperty("tokenCipher");
|
||||
expect(guardada.tokenLast4).toBe("abcd");
|
||||
});
|
||||
|
||||
it("sin llave y sin fila → error tipado sin_token (no inserta nada)", async () => {
|
||||
const { saveAiCredential, AiCredentialError } = await import(
|
||||
"@/server/ai/credentials"
|
||||
);
|
||||
await expect(
|
||||
saveAiCredential({
|
||||
organizationId: "org_1",
|
||||
provider: "openrouter",
|
||||
baseUrl: "https://openrouter.ai/api",
|
||||
model: "m",
|
||||
})
|
||||
).rejects.toBeInstanceOf(AiCredentialError);
|
||||
expect(inserted).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("sin llave con fila → solo cambia proveedor/modelo y conserva el estado", async () => {
|
||||
filaExistente = [
|
||||
{
|
||||
id: "aicred_1",
|
||||
organizationId: "org_1",
|
||||
provider: "openrouter",
|
||||
baseUrl: "https://openrouter.ai/api",
|
||||
model: "viejo",
|
||||
tokenCipher: "c",
|
||||
tokenIv: "i",
|
||||
tokenTag: "t",
|
||||
tokenLast4: "zzzz",
|
||||
status: "paused_invalid_token",
|
||||
statusReason: "401",
|
||||
statusChangedAt: new Date(),
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
},
|
||||
];
|
||||
const { saveAiCredential } = await import("@/server/ai/credentials");
|
||||
const guardada = await saveAiCredential({
|
||||
organizationId: "org_1",
|
||||
provider: "openrouter",
|
||||
baseUrl: "https://openrouter.ai/api",
|
||||
model: "nuevo",
|
||||
});
|
||||
expect(guardada.model).toBe("nuevo");
|
||||
expect(guardada.status).toBe("paused_invalid_token");
|
||||
expect(updated[0]).not.toHaveProperty("status");
|
||||
expect(updated[0]).not.toHaveProperty("tokenCipher");
|
||||
});
|
||||
});
|
||||
|
||||
describe("el estado según el proveedor", () => {
|
||||
it("401 → paused_invalid_token con el detalle; 402 → paused_no_credit", async () => {
|
||||
const { marcarEstadoPorRespuesta } = await import("@/server/ai/credentials");
|
||||
expect(await marcarEstadoPorRespuesta("org_1", 401, "proveedor respondió 401")).toBe(true);
|
||||
expect(updated[0]).toMatchObject({
|
||||
status: "paused_invalid_token",
|
||||
statusReason: "proveedor respondió 401",
|
||||
});
|
||||
expect(await marcarEstadoPorRespuesta("org_1", 402)).toBe(true);
|
||||
expect(updated[1]).toMatchObject({ status: "paused_no_credit", statusReason: null });
|
||||
});
|
||||
|
||||
it("429 y 500 no tocan la fila", async () => {
|
||||
const { marcarEstadoPorRespuesta } = await import("@/server/ai/credentials");
|
||||
expect(await marcarEstadoPorRespuesta("org_1", 429)).toBe(false);
|
||||
expect(await marcarEstadoPorRespuesta("org_1", 500)).toBe(false);
|
||||
expect(updated).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("marcarActiva vuelve a active y limpia el motivo", async () => {
|
||||
const { marcarActiva } = await import("@/server/ai/credentials");
|
||||
await marcarActiva("org_1");
|
||||
expect(updated[0]).toMatchObject({ status: "active", statusReason: null });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,149 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { clasificarFallo, listModels, probeProvider } from "@/lib/ai/probe";
|
||||
|
||||
/**
|
||||
* #85 — «Probar conexión» y «Traer modelos» nunca lanzan: cada fallo vuelve
|
||||
* tipado y en el idioma del dueño, y la llave solo viaja en el header.
|
||||
*/
|
||||
|
||||
function respuesta(status: number, body: unknown) {
|
||||
return new Response(typeof body === "string" ? body : JSON.stringify(body), {
|
||||
status,
|
||||
headers: { "content-type": "application/json" },
|
||||
});
|
||||
}
|
||||
|
||||
describe("probeProvider", () => {
|
||||
it("un turno mínimo con el modelo y la llave en Authorization → ok con latencia", async () => {
|
||||
const fetchImpl = vi.fn().mockResolvedValue(
|
||||
respuesta(200, { choices: [{ message: { content: "ok" } }] })
|
||||
);
|
||||
const r = await probeProvider({
|
||||
baseUrl: "https://proveedor.test",
|
||||
model: "m/x",
|
||||
token: "sk-secreta",
|
||||
fetchImpl: fetchImpl as unknown as typeof fetch,
|
||||
});
|
||||
expect(r.ok).toBe(true);
|
||||
if (r.ok) expect(r.latencyMs).toBeGreaterThanOrEqual(0);
|
||||
const [url, init] = fetchImpl.mock.calls[0]!;
|
||||
expect(url).toBe("https://proveedor.test/v1/chat/completions");
|
||||
expect((init as RequestInit).headers).toMatchObject({
|
||||
Authorization: "Bearer sk-secreta",
|
||||
});
|
||||
const body = JSON.parse((init as RequestInit).body as string);
|
||||
expect(body.model).toBe("m/x");
|
||||
expect(body.max_tokens).toBeLessThanOrEqual(5);
|
||||
expect(JSON.stringify(body)).not.toContain("sk-secreta");
|
||||
});
|
||||
|
||||
it("clasifica los códigos del proveedor", () => {
|
||||
expect(clasificarFallo(401, "").code).toBe("invalid_token");
|
||||
expect(clasificarFallo(403, "").code).toBe("invalid_token");
|
||||
expect(clasificarFallo(402, "").code).toBe("no_credit");
|
||||
expect(clasificarFallo(404, "").code).toBe("model_not_found");
|
||||
expect(clasificarFallo(400, '{"error":{"message":"foo is not a valid model ID"}}').code).toBe(
|
||||
"model_not_found"
|
||||
);
|
||||
expect(clasificarFallo(400, "bad request").code).toBe("provider_error");
|
||||
expect(clasificarFallo(429, "").code).toBe("rate_limited");
|
||||
expect(clasificarFallo(500, "").code).toBe("provider_error");
|
||||
});
|
||||
|
||||
it("incluye el error.message del proveedor en el mensaje", () => {
|
||||
const r = clasificarFallo(401, '{"error":{"message":"User not found."}}');
|
||||
expect(r.message).toContain("User not found.");
|
||||
expect(r.httpStatus).toBe(401);
|
||||
});
|
||||
|
||||
it("200 sin choices → provider_error (no es una API de chat)", async () => {
|
||||
const fetchImpl = vi.fn().mockResolvedValue(respuesta(200, { hola: "mundo" }));
|
||||
const r = await probeProvider({
|
||||
baseUrl: "https://proveedor.test",
|
||||
model: "m",
|
||||
token: "sk-x",
|
||||
fetchImpl: fetchImpl as unknown as typeof fetch,
|
||||
});
|
||||
expect(r.ok).toBe(false);
|
||||
if (!r.ok) expect(r.code).toBe("provider_error");
|
||||
});
|
||||
|
||||
it("red caída → unreachable; URL inválida → bad_url sin tocar la red", async () => {
|
||||
const caida = vi.fn().mockRejectedValue(new TypeError("fetch failed"));
|
||||
const r = await probeProvider({
|
||||
baseUrl: "https://proveedor.test",
|
||||
model: "m",
|
||||
token: "sk-x",
|
||||
fetchImpl: caida as unknown as typeof fetch,
|
||||
});
|
||||
expect(r.ok).toBe(false);
|
||||
if (!r.ok) expect(r.code).toBe("unreachable");
|
||||
|
||||
const nunca = vi.fn();
|
||||
const mala = await probeProvider({
|
||||
baseUrl: "no es una url",
|
||||
model: "m",
|
||||
token: "sk-x",
|
||||
fetchImpl: nunca as unknown as typeof fetch,
|
||||
});
|
||||
expect(mala.ok).toBe(false);
|
||||
if (!mala.ok) expect(mala.code).toBe("bad_url");
|
||||
expect(nunca).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe("listModels", () => {
|
||||
it("devuelve la lista ordenada con la forma de OpenRouter/OpenAI", async () => {
|
||||
const fetchImpl = vi.fn().mockResolvedValue(
|
||||
respuesta(200, {
|
||||
data: [
|
||||
{ id: "z/ultimo", name: "Último" },
|
||||
{ id: "a/primero" },
|
||||
{ id: "", name: "sin id" },
|
||||
null,
|
||||
],
|
||||
})
|
||||
);
|
||||
const r = await listModels({
|
||||
baseUrl: "https://openrouter.ai/api",
|
||||
token: "sk-x",
|
||||
fetchImpl: fetchImpl as unknown as typeof fetch,
|
||||
});
|
||||
expect(r.ok).toBe(true);
|
||||
if (r.ok) {
|
||||
expect(r.modelos).toEqual([
|
||||
{ id: "a/primero", nombre: null },
|
||||
{ id: "z/ultimo", nombre: "Último" },
|
||||
]);
|
||||
}
|
||||
expect(fetchImpl.mock.calls[0]![0]).toBe("https://openrouter.ai/api/v1/models");
|
||||
});
|
||||
|
||||
it("404 o una respuesta que no es la lista → unsupported, sin romper", async () => {
|
||||
const r404 = await listModels({
|
||||
baseUrl: "https://proveedor.test",
|
||||
token: "sk-x",
|
||||
fetchImpl: vi.fn().mockResolvedValue(respuesta(404, "")) as unknown as typeof fetch,
|
||||
});
|
||||
expect(r404.ok).toBe(false);
|
||||
if (!r404.ok) expect(r404.code).toBe("unsupported");
|
||||
|
||||
const rRara = await listModels({
|
||||
baseUrl: "https://proveedor.test",
|
||||
token: "sk-x",
|
||||
fetchImpl: vi.fn().mockResolvedValue(respuesta(200, { modelos: [] })) as unknown as typeof fetch,
|
||||
});
|
||||
expect(rRara.ok).toBe(false);
|
||||
if (!rRara.ok) expect(rRara.code).toBe("unsupported");
|
||||
});
|
||||
|
||||
it("401 → invalid_token", async () => {
|
||||
const r = await listModels({
|
||||
baseUrl: "https://proveedor.test",
|
||||
token: "sk-x",
|
||||
fetchImpl: vi.fn().mockResolvedValue(respuesta(401, "")) as unknown as typeof fetch,
|
||||
});
|
||||
expect(r.ok).toBe(false);
|
||||
if (!r.ok) expect(r.code).toBe("invalid_token");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,107 @@
|
||||
import { createElement } from "react";
|
||||
import { renderToStaticMarkup } from "react-dom/server";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { schema } from "@/lib/db";
|
||||
import { rate, type BotBlockDto } from "@/lib/analytics";
|
||||
import { resolvePeriod } from "@/server/analytics/period";
|
||||
import { botBlock } from "@/server/analytics/bot";
|
||||
import { BotSection } from "@/components/results/bot-section";
|
||||
|
||||
/**
|
||||
* 019 — Con la bandera AGENDA apagada no hay citas en Resultados (spec 019,
|
||||
* D4): ni se consultan, ni viajan en la API, ni se pintan.
|
||||
*
|
||||
* La base es falsa y anota contra qué tabla corre cada consulta: así se prueba
|
||||
* que sin agenda la tabla `booking` ni siquiera se toca, no solo que el
|
||||
* resultado salga vacío.
|
||||
*/
|
||||
|
||||
const db = vi.hoisted(() => ({ tablas: [] as unknown[] }));
|
||||
|
||||
vi.mock("@/lib/db", async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import("@/lib/db")>();
|
||||
const builder: Record<string, unknown> = {};
|
||||
for (const m of [
|
||||
"select",
|
||||
"selectDistinctOn",
|
||||
"where",
|
||||
"innerJoin",
|
||||
"leftJoin",
|
||||
"groupBy",
|
||||
"orderBy",
|
||||
"limit",
|
||||
]) {
|
||||
builder[m] = () => builder;
|
||||
}
|
||||
builder.from = (tabla: unknown) => {
|
||||
db.tablas.push(tabla);
|
||||
return builder;
|
||||
};
|
||||
(builder as { then: unknown }).then = (resolve: (v: unknown) => void) => resolve([]);
|
||||
return { ...actual, getDb: () => builder };
|
||||
});
|
||||
|
||||
const periodo = resolvePeriod({
|
||||
from: "2026-03-01",
|
||||
to: "2026-03-31",
|
||||
timezone: "America/Mexico_City",
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
db.tablas = [];
|
||||
});
|
||||
|
||||
describe("botBlock y la bandera AGENDA", () => {
|
||||
it("apagada: `sessions` es null y la tabla de citas no se consulta", async () => {
|
||||
const b = await botBlock("org_1", periodo, false);
|
||||
expect(b.sessions).toBeNull();
|
||||
expect(db.tablas).not.toContain(schema.booking);
|
||||
// Lo demás del agente sigue ahí.
|
||||
expect(b.conversations).toBe(0);
|
||||
expect(b.empty).toBe(true);
|
||||
});
|
||||
|
||||
it("encendida: cuenta las citas del periodo", async () => {
|
||||
const b = await botBlock("org_1", periodo, true);
|
||||
expect(b.sessions).toEqual({
|
||||
booked: 0,
|
||||
done: 0,
|
||||
noShow: 0,
|
||||
cancelled: 0,
|
||||
showRate: { value: null, sample: 0, reliable: false },
|
||||
});
|
||||
expect(db.tablas).toContain(schema.booking);
|
||||
});
|
||||
});
|
||||
|
||||
describe("la sección del agente y la bandera AGENDA", () => {
|
||||
const datos: BotBlockDto = {
|
||||
period: periodo.dto,
|
||||
conversations: 12,
|
||||
aiReplyRate: rate(10, 11),
|
||||
firstResponseSeconds: 42,
|
||||
firstResponseSample: 10,
|
||||
handoffs: [{ key: "cliente", label: "El cliente pidió un humano", count: 2 }],
|
||||
handoffRate: rate(2, 12),
|
||||
sessions: { booked: 4, done: 2, noShow: 1, cancelled: 1, showRate: rate(2, 3) },
|
||||
fichaCoverage: null,
|
||||
empty: false,
|
||||
};
|
||||
const pintar = (agenda: boolean, data: BotBlockDto) =>
|
||||
renderToStaticMarkup(
|
||||
createElement(BotSection, { data, loading: false, error: null, agenda })
|
||||
);
|
||||
|
||||
it("apagada no habla de citas, aunque llegaran datos", () => {
|
||||
const html = pintar(false, datos);
|
||||
expect(html).not.toMatch(/cita/i);
|
||||
expect(html).not.toContain("Asistencia");
|
||||
expect(html).toContain("Contestó el agente");
|
||||
});
|
||||
|
||||
it("encendida enseña las citas del periodo", () => {
|
||||
const html = pintar(true, datos);
|
||||
expect(html).toContain("Citas del periodo");
|
||||
expect(html).toContain("Asistencia");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,181 @@
|
||||
import { beforeAll, describe, expect, it } from "vitest";
|
||||
|
||||
beforeAll(() => {
|
||||
process.env.APP_BASE_URL = "https://app.ejemplo.test";
|
||||
process.env.DATABASE_URL = "postgresql://t:t@localhost:5432/t";
|
||||
process.env.BETTER_AUTH_SECRET = "secret-de-test-suficiente";
|
||||
process.env.ENCRYPTION_KEY = Buffer.alloc(32, 11).toString("base64");
|
||||
process.env.META_WEBHOOK_VERIFY_TOKEN = "verify-test";
|
||||
});
|
||||
|
||||
const { daysApart, median, PeriodError, resolvePeriod } = await import(
|
||||
"@/server/analytics/period"
|
||||
);
|
||||
const { bucketsDelPeriodo } = await import("@/lib/analytics");
|
||||
const { shortcuts } = await import("@/components/results/range-picker");
|
||||
|
||||
/**
|
||||
* 019 — Los periodos de la pantalla Resultados (portado de Vocero Cloud).
|
||||
*
|
||||
* Lo que se fija aquí es que los cortes caen en la zona del NEGOCIO: con
|
||||
* cortes en UTC, todo lo que pasa después de las 18:00 en México cae en el día
|
||||
* siguiente y el dueño compararía su lunes contra un lunes que no existe.
|
||||
*/
|
||||
|
||||
const MX = "America/Mexico_City";
|
||||
|
||||
describe("resolvePeriod", () => {
|
||||
const ahora = new Date("2026-03-15T18:00:00Z");
|
||||
|
||||
it("sin fechas, son los últimos 30 días terminando hoy", () => {
|
||||
const p = resolvePeriod({ timezone: MX, now: ahora });
|
||||
expect(p.dto.to).toBe("2026-03-15");
|
||||
expect(p.dto.from).toBe("2026-02-14");
|
||||
expect(p.dto.days).toBe(30);
|
||||
});
|
||||
|
||||
it("'hoy' es el del negocio: las 20:00 del 5 en México siguen siendo el 5", () => {
|
||||
// 2026-03-06T02:00Z ya es día 6 en UTC.
|
||||
const p = resolvePeriod({ timezone: MX, now: new Date("2026-03-06T02:00:00Z") });
|
||||
expect(p.dto.to).toBe("2026-03-05");
|
||||
});
|
||||
|
||||
it("el periodo anterior dura LO MISMO y termina justo antes", () => {
|
||||
// Si no, la comparación mezclaría un mes de 30 días con uno de 31 y el
|
||||
// "+8 %" de la pantalla sería un artefacto del calendario.
|
||||
const p = resolvePeriod({ from: "2026-03-01", to: "2026-03-10", timezone: MX });
|
||||
expect(p.dto.days).toBe(10);
|
||||
expect(p.dto.previousTo).toBe("2026-02-28");
|
||||
expect(p.dto.previousFrom).toBe("2026-02-19");
|
||||
});
|
||||
|
||||
it("el fin es EXCLUSIVO: arranca el día siguiente", () => {
|
||||
const p = resolvePeriod({ from: "2026-03-01", to: "2026-03-01", timezone: MX });
|
||||
expect(p.dto.days).toBe(1);
|
||||
expect(p.end.getTime() - p.start.getTime()).toBe(86_400_000);
|
||||
});
|
||||
|
||||
it("los cortes son medianoche en la zona del negocio, no en UTC", () => {
|
||||
const p = resolvePeriod({ from: "2026-03-01", to: "2026-03-01", timezone: MX });
|
||||
// Medianoche del 1 de marzo en México (UTC-6) son las 06:00Z.
|
||||
expect(p.start.toISOString()).toBe("2026-03-01T06:00:00.000Z");
|
||||
});
|
||||
|
||||
it("un día con cambio de horario dura lo que dura en la zona", () => {
|
||||
// Nueva York adelanta el reloj el 8 de marzo de 2026: ese día tiene 23 h.
|
||||
const p = resolvePeriod({
|
||||
from: "2026-03-08",
|
||||
to: "2026-03-08",
|
||||
timezone: "America/New_York",
|
||||
});
|
||||
expect(p.end.getTime() - p.start.getTime()).toBe(23 * 3_600_000);
|
||||
});
|
||||
|
||||
it("el anterior termina EXACTAMENTE donde empieza el actual, sin hueco", () => {
|
||||
const p = resolvePeriod({ from: "2026-03-01", to: "2026-03-10", timezone: MX });
|
||||
expect(p.previousEnd.getTime()).toBe(p.start.getTime());
|
||||
});
|
||||
|
||||
it("pasados 92 días agrupa por mes", () => {
|
||||
const corto = resolvePeriod({ from: "2026-01-01", to: "2026-04-02", timezone: MX });
|
||||
expect(corto.dto.days).toBe(92);
|
||||
expect(corto.dto.granularity).toBe("day");
|
||||
|
||||
const largo = resolvePeriod({ from: "2026-01-01", to: "2026-04-03", timezone: MX });
|
||||
expect(largo.dto.granularity).toBe("month");
|
||||
});
|
||||
|
||||
it("rechaza el rango invertido", () => {
|
||||
expect(() =>
|
||||
resolvePeriod({ from: "2026-03-10", to: "2026-03-01", timezone: MX })
|
||||
).toThrow(PeriodError);
|
||||
});
|
||||
|
||||
it("rechaza más de 366 días", () => {
|
||||
expect(() =>
|
||||
resolvePeriod({ from: "2024-01-01", to: "2026-01-01", timezone: MX })
|
||||
).toThrow(PeriodError);
|
||||
});
|
||||
|
||||
it("rechaza una fecha con formato inventado o que no existe", () => {
|
||||
// Llega de la barra de direcciones: tiene que ser un 422 con mensaje, no
|
||||
// un NaN que se propague hasta una consulta.
|
||||
expect(() => resolvePeriod({ from: "ayer", to: "2026-03-01", timezone: MX })).toThrow(
|
||||
PeriodError
|
||||
);
|
||||
expect(() =>
|
||||
resolvePeriod({ from: "2026-02-31", to: "2026-03-01", timezone: MX })
|
||||
).toThrow(PeriodError);
|
||||
});
|
||||
|
||||
it("una zona horaria inválida no tumba la pantalla", () => {
|
||||
const p = resolvePeriod({ from: "2026-03-01", to: "2026-03-02", timezone: "Marte/Olimpo" });
|
||||
expect(p.timezone).toBe("America/Mexico_City");
|
||||
});
|
||||
});
|
||||
|
||||
describe("daysApart", () => {
|
||||
it("cuenta bien un año bisiesto y no se descuadra con el horario de verano", () => {
|
||||
expect(daysApart("2028-02-01", "2028-03-01")).toBe(29);
|
||||
expect(daysApart("2026-04-01", "2026-04-30")).toBe(29);
|
||||
});
|
||||
});
|
||||
|
||||
describe("bucketsDelPeriodo", () => {
|
||||
it("un día sin movimientos es una cubeta en cero, no un hueco", () => {
|
||||
expect(
|
||||
bucketsDelPeriodo({ from: "2026-02-27", to: "2026-03-02", granularity: "day" })
|
||||
).toEqual(["2026-02-27", "2026-02-28", "2026-03-01", "2026-03-02"]);
|
||||
});
|
||||
|
||||
it("por mes, cruzando el año", () => {
|
||||
expect(
|
||||
bucketsDelPeriodo({ from: "2025-11-15", to: "2026-02-03", granularity: "month" })
|
||||
).toEqual(["2025-11", "2025-12", "2026-01", "2026-02"]);
|
||||
});
|
||||
|
||||
it("el rango más largo cabe entero", () => {
|
||||
const p = resolvePeriod({ from: "2025-01-01", to: "2026-01-01", timezone: MX });
|
||||
expect(bucketsDelPeriodo(p.dto)).toHaveLength(13);
|
||||
});
|
||||
});
|
||||
|
||||
describe("atajos del rango", () => {
|
||||
it("se calculan sobre el hoy del negocio, en fechas de calendario", () => {
|
||||
const a = Object.fromEntries(shortcuts("2026-03-15").map((s) => [s.label, s.range]));
|
||||
expect(a["7 días"]).toEqual({ from: "2026-03-09", to: "2026-03-15" });
|
||||
expect(a["30 días"]).toEqual({ from: "2026-02-14", to: "2026-03-15" });
|
||||
expect(a["Este mes"]).toEqual({ from: "2026-03-01", to: "2026-03-15" });
|
||||
// Marzo: el mes pasado es un febrero de 28 días.
|
||||
expect(a["Mes pasado"]).toEqual({ from: "2026-02-01", to: "2026-02-28" });
|
||||
});
|
||||
|
||||
it("en enero, el mes pasado es diciembre del año anterior", () => {
|
||||
const a = Object.fromEntries(shortcuts("2026-01-05").map((s) => [s.label, s.range]));
|
||||
expect(a["Mes pasado"]).toEqual({ from: "2025-12-01", to: "2025-12-31" });
|
||||
});
|
||||
|
||||
it("'30 días' coincide con el periodo por defecto del servidor", () => {
|
||||
const hoy = "2026-03-15";
|
||||
const servidor = resolvePeriod({ timezone: MX, now: new Date("2026-03-15T18:00:00Z") });
|
||||
const cliente = shortcuts(hoy).find((s) => s.label === "30 días")!.range;
|
||||
expect(cliente).toEqual({ from: servidor.dto.from, to: servidor.dto.to });
|
||||
});
|
||||
});
|
||||
|
||||
describe("median", () => {
|
||||
it("con lista vacía es null, no cero", () => {
|
||||
// Cero significaría "contestó al instante"; null significa "no hubo nada
|
||||
// que medir". La pantalla los dice distinto.
|
||||
expect(median([])).toBeNull();
|
||||
});
|
||||
|
||||
it("impar toma el de en medio; par promedia los dos centrales", () => {
|
||||
expect(median([5, 1, 3])).toBe(3);
|
||||
expect(median([1, 2, 3, 4])).toBe(3);
|
||||
});
|
||||
|
||||
it("un valor extremo no la arrastra", () => {
|
||||
expect(median([2, 3, 4, 5, 100_000])).toBe(4);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,239 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { comparable, delta, MIN_SAMPLE, rate } from "@/lib/analytics";
|
||||
import { armarEmbudo, clasificarCierres, motivosDePerdida, type Desenlace } from "@/server/analytics/sales";
|
||||
import { MAX_ANUNCIOS, unirAnuncios, unirFuentes } from "@/server/analytics/ads";
|
||||
import { escalaLimpia, etiqueta } from "@/components/results/time-bars";
|
||||
|
||||
/**
|
||||
* 019 — La aritmética de la pantalla Resultados (portada de Vocero Cloud, sin
|
||||
* los casos del gasto publicitario ni de la probabilidad de cierre).
|
||||
*
|
||||
* Toda tasa de la pantalla pasa por `rate`. Estas pruebas son lo que permite
|
||||
* que la UI no divida nunca.
|
||||
*/
|
||||
|
||||
describe("rate", () => {
|
||||
it("sin denominador devuelve null, no cero", () => {
|
||||
// Cero por ciento significa "lo intenté y falló". Null significa "no ha
|
||||
// pasado nada todavía". La pantalla los dice con palabras distintas.
|
||||
const r = rate(0, 0);
|
||||
expect(r.value).toBeNull();
|
||||
expect(r.sample).toBe(0);
|
||||
expect(r.reliable).toBe(false);
|
||||
});
|
||||
|
||||
it("el denominador viaja SIEMPRE con el porcentaje", () => {
|
||||
expect(rate(1, 2).sample).toBe(2);
|
||||
});
|
||||
|
||||
it("marca la muestra chica en vez de esconderla", () => {
|
||||
// 1 de 1 es 100 %, y presentarlo como firme sería mentir con la verdad.
|
||||
const flaca = rate(1, 1);
|
||||
expect(flaca.value).toBe(100);
|
||||
expect(flaca.reliable).toBe(false);
|
||||
expect(rate(5, MIN_SAMPLE).reliable).toBe(true);
|
||||
});
|
||||
|
||||
it("redondea a entero", () => {
|
||||
expect(rate(1, 3).value).toBe(33);
|
||||
expect(rate(2, 3).value).toBe(67);
|
||||
});
|
||||
|
||||
it("un denominador negativo no revienta", () => {
|
||||
expect(rate(1, -5).value).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("delta", () => {
|
||||
it("sin base previa es null, no un aumento infinito", () => {
|
||||
// De 0 a 8 no es "+800 %": es que antes no había con qué comparar.
|
||||
expect(delta(comparable(8, 0))).toBeNull();
|
||||
});
|
||||
|
||||
it("calcula la variación en ambos sentidos", () => {
|
||||
expect(delta(comparable(12, 10))).toBe(20);
|
||||
expect(delta(comparable(8, 10))).toBe(-20);
|
||||
});
|
||||
});
|
||||
|
||||
const desenlace = (d: Partial<Desenlace> & Pick<Desenlace, "leadId" | "kind">): Desenlace => ({
|
||||
lossReason: null,
|
||||
amountCents: null,
|
||||
currency: null,
|
||||
...d,
|
||||
});
|
||||
|
||||
describe("clasificarCierres", () => {
|
||||
it("cuenta el LEAD, y el dinero solo en la moneda del negocio", () => {
|
||||
const c = clasificarCierres(
|
||||
[
|
||||
desenlace({ leadId: "a", kind: "won", amountCents: 100_00, currency: "MXN" }),
|
||||
// Sin moneda = la del negocio al capturarlo.
|
||||
desenlace({ leadId: "b", kind: "won", amountCents: 50_00 }),
|
||||
// Otra moneda: se cuenta como trato, no se suma.
|
||||
desenlace({ leadId: "c", kind: "won", amountCents: 999_00, currency: "USD" }),
|
||||
// Sin monto: trato ganado, no suma ni entra al ticket promedio.
|
||||
desenlace({ leadId: "d", kind: "won" }),
|
||||
desenlace({ leadId: "e", kind: "lost", lossReason: "precio" }),
|
||||
// Volvió al embudo dentro del rango: no cerró nada.
|
||||
desenlace({ leadId: "f", kind: "open", amountCents: 70_00 }),
|
||||
],
|
||||
"MXN"
|
||||
);
|
||||
expect(c.won).toEqual(["a", "b", "c", "d"]);
|
||||
expect(c.lost).toEqual(["e"]);
|
||||
expect(c.wonCents).toBe(150_00);
|
||||
expect(c.wonWithAmount).toBe(2);
|
||||
});
|
||||
});
|
||||
|
||||
describe("motivosDePerdida", () => {
|
||||
it("sale del mismo desenlace: solo los perdidos, del más frecuente al menos", () => {
|
||||
const m = motivosDePerdida([
|
||||
desenlace({ leadId: "a", kind: "lost", lossReason: "precio" }),
|
||||
desenlace({ leadId: "b", kind: "lost", lossReason: "precio" }),
|
||||
// Sembrado por la migración: perdido sin motivo capturado.
|
||||
desenlace({ leadId: "c", kind: "lost" }),
|
||||
desenlace({ leadId: "d", kind: "won" }),
|
||||
]);
|
||||
expect(m).toEqual([
|
||||
{ reason: "precio", label: "Le pareció caro", count: 2 },
|
||||
{ reason: "sin_registro", label: "Sin motivo registrado", count: 1 },
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("armarEmbudo", () => {
|
||||
const etapas = [
|
||||
{ id: "s1", name: "Nuevo", kind: "open" as const, position: 0 },
|
||||
{ id: "s2", name: "Interesado", kind: "open" as const, position: 1 },
|
||||
{ id: "s3", name: "Cotizado", kind: "open" as const, position: 2 },
|
||||
// Perdido con una posición alta: NO puede contar como "pasó por todas".
|
||||
{ id: "sl", name: "Perdido", kind: "lost" as const, position: 9 },
|
||||
{ id: "sw", name: "Cliente", kind: "won" as const, position: 3 },
|
||||
];
|
||||
|
||||
it("cada lead cuenta una vez por etapa y el acumulado solo corre sobre abiertas", () => {
|
||||
const pasos = armarEmbudo(etapas, [
|
||||
{ maxOpenPos: 0, won: 0 }, // se quedó en Nuevo
|
||||
{ maxOpenPos: 1, won: 0 }, // llegó a Interesado y se perdió
|
||||
{ maxOpenPos: 2, won: 1 }, // hasta Cotizado y se ganó
|
||||
{ maxOpenPos: 0, won: 1 }, // de Nuevo directo a Cliente
|
||||
{ maxOpenPos: null, won: 0 }, // sus etapas ya no existen
|
||||
]);
|
||||
expect(pasos.map((p) => [p.name, p.reached])).toEqual([
|
||||
["Nuevo", 4],
|
||||
["Interesado", 2],
|
||||
["Cotizado", 1],
|
||||
["Cliente", 2],
|
||||
]);
|
||||
expect(pasos.find((p) => p.name === "Perdido")).toBeUndefined();
|
||||
// La proporción que pasa a la siguiente, con su denominador.
|
||||
expect(pasos[0]!.advanceRate).toEqual({ value: 50, sample: 4, reliable: false });
|
||||
expect(pasos.at(-1)!.advanceRate).toBeNull();
|
||||
});
|
||||
|
||||
it("sin etapa ganada configurada, el último paso sigue llamándose Ganado", () => {
|
||||
const pasos = armarEmbudo([etapas[0]!], [{ maxOpenPos: 0, won: 1 }]);
|
||||
expect(pasos.at(-1)).toMatchObject({ name: "Ganado", kind: "won", reached: 1 });
|
||||
});
|
||||
});
|
||||
|
||||
describe("unirFuentes", () => {
|
||||
it("las seis fuentes en su orden fijo, solo las que tienen algo, y sin identificar al final", () => {
|
||||
const filas = unirFuentes(
|
||||
[
|
||||
{ key: null, n: 3 },
|
||||
{ key: "anuncio", n: 5 },
|
||||
],
|
||||
[
|
||||
{ key: "anuncio", leads: 4, won: 1 },
|
||||
{ key: "referido", leads: 1, won: 1 },
|
||||
]
|
||||
);
|
||||
expect(filas.map((f) => [f.value, f.conversations, f.leads, f.won])).toEqual([
|
||||
["anuncio", 5, 4, 1],
|
||||
["referido", 0, 1, 1],
|
||||
["desconocida", 3, 0, 0],
|
||||
]);
|
||||
expect(filas[0]!.label).toBe("Anuncio");
|
||||
expect(filas.at(-1)!.label).toBe("Sin identificar");
|
||||
// La tasa de la fila es ventas entre prospectos, calculada en el servidor.
|
||||
expect(filas[0]!.winRate).toEqual({ value: 25, sample: 4, reliable: false });
|
||||
expect(filas.at(-1)!.winRate.value).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("unirAnuncios", () => {
|
||||
const meta = (key: string, extra: Partial<Parameters<typeof unirAnuncios>[0][number]> = {}) => ({
|
||||
key,
|
||||
sourceId: key.startsWith("ad_") ? null : key,
|
||||
sourceType: "ad",
|
||||
headline: `Titular ${key}`,
|
||||
imageAssetId: null,
|
||||
lastAt: 1_000,
|
||||
...extra,
|
||||
});
|
||||
|
||||
it("junta conversaciones y prospectos del mismo anuncio en una fila", () => {
|
||||
const [fila] = unirAnuncios(
|
||||
[{ ...meta("1202"), conversations: 3 }],
|
||||
[{ ...meta("1202", { imageAssetId: "ma_1" }), leads: 2, won: 1 }]
|
||||
);
|
||||
expect(fila).toMatchObject({
|
||||
key: "1202",
|
||||
conversations: 3,
|
||||
leads: 2,
|
||||
won: 1,
|
||||
winRate: { value: 50, sample: 2 },
|
||||
// La imagen llega en cualquiera de las dos vistas: se conserva.
|
||||
imageAssetId: "ma_1",
|
||||
});
|
||||
});
|
||||
|
||||
it("un anuncio con prospectos pero sin conversaciones del periodo también sale", () => {
|
||||
const filas = unirAnuncios([], [{ ...meta("1203"), leads: 1, won: 0 }]);
|
||||
expect(filas).toHaveLength(1);
|
||||
expect(filas[0]).toMatchObject({ conversations: 0, leads: 1, won: 0 });
|
||||
});
|
||||
|
||||
it("más conversaciones primero; a igualdad, más prospectos y luego el más reciente", () => {
|
||||
const filas = unirAnuncios(
|
||||
[
|
||||
{ ...meta("viejo", { lastAt: 100 }), conversations: 2 },
|
||||
{ ...meta("nuevo", { lastAt: 900 }), conversations: 2 },
|
||||
{ ...meta("grande"), conversations: 7 },
|
||||
{ ...meta("con-prospectos", { lastAt: 50 }), conversations: 2 },
|
||||
],
|
||||
[{ ...meta("con-prospectos", { lastAt: 50 }), leads: 2, won: 0 }]
|
||||
);
|
||||
expect(filas.map((f) => f.key)).toEqual(["grande", "con-prospectos", "nuevo", "viejo"]);
|
||||
// El instante de orden no viaja al cliente.
|
||||
expect(filas[0]).not.toHaveProperty("lastAt");
|
||||
});
|
||||
|
||||
it(`corta en ${MAX_ANUNCIOS} filas`, () => {
|
||||
const muchas = Array.from({ length: MAX_ANUNCIOS + 5 }, (_, i) => ({
|
||||
...meta(`a${i}`),
|
||||
conversations: i + 1,
|
||||
}));
|
||||
const filas = unirAnuncios(muchas, []);
|
||||
expect(filas).toHaveLength(MAX_ANUNCIOS);
|
||||
expect(filas[0]!.conversations).toBe(MAX_ANUNCIOS + 5);
|
||||
});
|
||||
});
|
||||
|
||||
describe("escala y etiquetas de la serie", () => {
|
||||
it("el tope es un número limpio que cubre el máximo", () => {
|
||||
expect(escalaLimpia(0)).toBe(1);
|
||||
expect(escalaLimpia(1)).toBe(1);
|
||||
expect(escalaLimpia(3)).toBe(5);
|
||||
expect(escalaLimpia(37)).toBe(50);
|
||||
expect(escalaLimpia(120)).toBe(200);
|
||||
});
|
||||
|
||||
it("fechas cortas en español", () => {
|
||||
expect(etiqueta("2026-08-13")).toBe("13 ago");
|
||||
expect(etiqueta("2026-01")).toBe("ene 26");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,404 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import {
|
||||
COTAS,
|
||||
anuncioDeWhatsapp,
|
||||
sinIdentificadorDeClic,
|
||||
} from "@/server/attribution/referral";
|
||||
import {
|
||||
CREATIVO_MAX_BYTES,
|
||||
descargarConReintento,
|
||||
descargarCreativo,
|
||||
urlDeCreativoPermitida,
|
||||
} from "@/server/attribution/creativo";
|
||||
import {
|
||||
REPARAR_CADA_MS,
|
||||
anuncioParaGuardar,
|
||||
crearFreno,
|
||||
serializarAnuncio,
|
||||
} from "@/server/attribution/store";
|
||||
import { effectiveSource } from "@/server/contact-source";
|
||||
import {
|
||||
cuentaComoAnuncio,
|
||||
etiquetaDeOrigen,
|
||||
titularDeOrigen,
|
||||
} from "@/lib/anuncios";
|
||||
|
||||
/**
|
||||
* 018 — De qué anuncio llegó cada conversación.
|
||||
*
|
||||
* Lo que se prueba aquí es la única puerta por la que un payload externo llega
|
||||
* a una columna (la normalización), la única por la que ese payload hace que el
|
||||
* servidor descargue algo (la URL del creativo y la descarga), y lo que decide
|
||||
* la bandera ATRIBUCION: el identificador de clic, nada más.
|
||||
*/
|
||||
|
||||
const REFERRAL_CTWA = {
|
||||
source_url: "https://fb.me/2ZXjQ0aB1",
|
||||
source_id: "120212345678900001",
|
||||
source_type: "ad",
|
||||
headline: "Diagnóstico gratis para tu negocio",
|
||||
body: "Escríbenos y agenda tu llamada",
|
||||
media_type: "image",
|
||||
image_url: "https://scontent.xx.fbcdn.net/v/t45.1600-4/creativo.jpg?oe=66F0",
|
||||
ctwa_clid: "ARAkLkA8rmlFeiCktEJQ-QTwRiyYHAFDLMNDBH0CD3qpjd0HR4irJ6LEkR7JwFF4XvnO",
|
||||
};
|
||||
|
||||
describe("anuncioDeWhatsapp", () => {
|
||||
it("normaliza el referral completo de un anuncio Click-to-WhatsApp", () => {
|
||||
const a = anuncioDeWhatsapp(REFERRAL_CTWA);
|
||||
expect(a).toMatchObject({
|
||||
sourceId: "120212345678900001",
|
||||
sourceType: "ad",
|
||||
sourceUrl: "https://fb.me/2ZXjQ0aB1",
|
||||
headline: "Diagnóstico gratis para tu negocio",
|
||||
body: "Escríbenos y agenda tu llamada",
|
||||
mediaType: "image",
|
||||
ctwaClid: REFERRAL_CTWA.ctwa_clid,
|
||||
imageUrl: REFERRAL_CTWA.image_url,
|
||||
});
|
||||
expect(a?.raw).toMatchObject({ source_id: "120212345678900001" });
|
||||
});
|
||||
|
||||
it("prefiere la miniatura al creativo completo", () => {
|
||||
const a = anuncioDeWhatsapp({
|
||||
...REFERRAL_CTWA,
|
||||
media_type: "video",
|
||||
video_url: "https://video.xx.fbcdn.net/v.mp4",
|
||||
thumbnail_url: "https://scontent.xx.fbcdn.net/thumb.jpg",
|
||||
});
|
||||
expect(a?.imageUrl).toBe("https://scontent.xx.fbcdn.net/thumb.jpg");
|
||||
});
|
||||
|
||||
it("sin nada que identifique el anuncio no hay anuncio", () => {
|
||||
expect(anuncioDeWhatsapp(undefined)).toBeNull();
|
||||
expect(anuncioDeWhatsapp(null)).toBeNull();
|
||||
expect(anuncioDeWhatsapp("ad")).toBeNull();
|
||||
expect(anuncioDeWhatsapp([REFERRAL_CTWA])).toBeNull();
|
||||
expect(anuncioDeWhatsapp({})).toBeNull();
|
||||
expect(anuncioDeWhatsapp({ body: "solo texto", media_type: "image" })).toBeNull();
|
||||
expect(anuncioDeWhatsapp({ source_id: " ", headline: "" })).toBeNull();
|
||||
});
|
||||
|
||||
it("basta uno de los campos útiles, aunque falte el id del anuncio", () => {
|
||||
expect(anuncioDeWhatsapp({ ctwa_clid: "clid-1" })?.ctwaClid).toBe("clid-1");
|
||||
expect(anuncioDeWhatsapp({ headline: "Promo" })?.headline).toBe("Promo");
|
||||
});
|
||||
|
||||
it("ignora tipos equivocados en vez de guardarlos", () => {
|
||||
const a = anuncioDeWhatsapp({ source_id: 12345, headline: { x: 1 }, ctwa_clid: "c" });
|
||||
expect(a?.sourceId).toBeNull();
|
||||
expect(a?.headline).toBeNull();
|
||||
expect(a?.ctwaClid).toBe("c");
|
||||
});
|
||||
|
||||
it("solo acepta enlaces http(s): un javascript: jamás llega a un href", () => {
|
||||
const a = anuncioDeWhatsapp({
|
||||
...REFERRAL_CTWA,
|
||||
source_url: "javascript:alert(1)",
|
||||
image_url: "data:image/png;base64,AAAA",
|
||||
});
|
||||
expect(a?.sourceUrl).toBeNull();
|
||||
expect(a?.imageUrl).toBeNull();
|
||||
});
|
||||
|
||||
it("recorta cadenas gigantes y acota el raw", () => {
|
||||
const enorme = "x".repeat(50_000);
|
||||
const a = anuncioDeWhatsapp({
|
||||
source_id: enorme,
|
||||
headline: enorme,
|
||||
body: enorme,
|
||||
ctwa_clid: enorme,
|
||||
campo_nuevo_de_meta: enorme,
|
||||
});
|
||||
expect(a?.sourceId?.length).toBe(COTAS.id);
|
||||
expect(a?.headline?.length).toBe(COTAS.titular);
|
||||
expect(a?.body?.length).toBe(COTAS.texto);
|
||||
expect(JSON.stringify(a?.raw).length).toBeLessThanOrEqual(COTAS.raw);
|
||||
// Las claves que no conoce no llegan al raw.
|
||||
expect(a?.raw).not.toHaveProperty("campo_nuevo_de_meta");
|
||||
});
|
||||
});
|
||||
|
||||
describe("la bandera ATRIBUCION decide el identificador de clic, no el origen", () => {
|
||||
const original = process.env.ATRIBUCION;
|
||||
afterEach(() => {
|
||||
if (original === undefined) delete process.env.ATRIBUCION;
|
||||
else process.env.ATRIBUCION = original;
|
||||
});
|
||||
const anuncio = anuncioDeWhatsapp(REFERRAL_CTWA)!;
|
||||
|
||||
it("apagada: se guarda el anuncio sin ctwa_clid, ni en la columna ni en el raw", () => {
|
||||
delete process.env.ATRIBUCION;
|
||||
const a = anuncioParaGuardar(anuncio);
|
||||
expect(a.ctwaClid).toBeNull();
|
||||
expect(a.raw).not.toHaveProperty("ctwa_clid");
|
||||
expect(JSON.stringify(a)).not.toContain(REFERRAL_CTWA.ctwa_clid);
|
||||
// El resto del anuncio queda intacto: el origen se ve igual.
|
||||
expect(a).toMatchObject({
|
||||
sourceId: anuncio.sourceId,
|
||||
headline: anuncio.headline,
|
||||
imageUrl: anuncio.imageUrl,
|
||||
});
|
||||
expect(a.raw).toMatchObject({ image_url: REFERRAL_CTWA.image_url });
|
||||
});
|
||||
|
||||
it("encendida: se guarda con su ctwa_clid", () => {
|
||||
process.env.ATRIBUCION = "on";
|
||||
const a = anuncioParaGuardar(anuncio);
|
||||
expect(a.ctwaClid).toBe(REFERRAL_CTWA.ctwa_clid);
|
||||
expect(a.raw).toHaveProperty("ctwa_clid", REFERRAL_CTWA.ctwa_clid);
|
||||
});
|
||||
|
||||
it("quitar el clic no toca el objeto original", () => {
|
||||
sinIdentificadorDeClic(anuncio);
|
||||
expect(anuncio.ctwaClid).toBe(REFERRAL_CTWA.ctwa_clid);
|
||||
expect(anuncio.raw).toHaveProperty("ctwa_clid");
|
||||
});
|
||||
|
||||
const fila = {
|
||||
id: "att_1",
|
||||
organizationId: "org_1",
|
||||
contactId: "ct_1",
|
||||
conversationId: "cv_1",
|
||||
ctwaClid: "clid-secreto",
|
||||
sourceId: "1202",
|
||||
sourceType: "ad",
|
||||
sourceUrl: "https://fb.me/x",
|
||||
headline: "Promo",
|
||||
body: "Texto",
|
||||
mediaType: "video",
|
||||
imageAssetId: null,
|
||||
raw: { ctwa_clid: "clid-secreto" },
|
||||
createdAt: new Date("2026-09-21T15:00:00Z"),
|
||||
};
|
||||
|
||||
it("la tarjeta dice «Meta identificó el clic» solo con la bandera, y nunca el valor", () => {
|
||||
const encendida = serializarAnuncio(fila, true);
|
||||
const apagada = serializarAnuncio(fila, false);
|
||||
expect(encendida.hasCtwaClid).toBe(true);
|
||||
expect(apagada.hasCtwaClid).toBe(false);
|
||||
expect(serializarAnuncio({ ...fila, ctwaClid: null }, true).hasCtwaClid).toBe(false);
|
||||
for (const dto of [encendida, apagada]) {
|
||||
expect(JSON.stringify(dto)).not.toContain("clid-secreto");
|
||||
}
|
||||
process.env.ATRIBUCION = "on";
|
||||
expect(serializarAnuncio(fila).hasCtwaClid).toBe(true);
|
||||
delete process.env.ATRIBUCION;
|
||||
expect(serializarAnuncio(fila).hasCtwaClid).toBe(false);
|
||||
});
|
||||
|
||||
it("el enlace «Ver anuncio» solo sale si es https", () => {
|
||||
expect(serializarAnuncio(fila, false).sourceUrl).toBe("https://fb.me/x");
|
||||
expect(serializarAnuncio({ ...fila, sourceUrl: "http://fb.me/x" }, false).sourceUrl).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("urlDeCreativoPermitida", () => {
|
||||
it("acepta los CDN de Meta por https", () => {
|
||||
for (const u of [
|
||||
"https://scontent.xx.fbcdn.net/v/t45/creativo.jpg?oe=1",
|
||||
"https://scontent-dfw5-1.xx.fbcdn.net/x.jpg",
|
||||
"https://scontent.xx.fbcdn.net:443/x.jpg",
|
||||
"https://lookaside.fbsbx.com/whatsapp_business/attachments/?mid=1",
|
||||
"https://scontent.cdninstagram.com/foto.jpg",
|
||||
"https://www.facebook.com/ads/image/?d=1",
|
||||
]) {
|
||||
expect(urlDeCreativoPermitida(u), u).toBe(true);
|
||||
}
|
||||
});
|
||||
|
||||
it("rechaza lo que convertiría la ingesta en un proxy", () => {
|
||||
for (const u of [
|
||||
"http://scontent.xx.fbcdn.net/x.jpg", // sin TLS
|
||||
"https://evilfbcdn.net/x.jpg", // no es subdominio
|
||||
"https://fbcdn.net.atacante.com/x.jpg",
|
||||
"https://user:pass@scontent.xx.fbcdn.net/x.jpg",
|
||||
"https://scontent.xx.fbcdn.net@evil.example/x.jpg",
|
||||
"https://scontent.xx.fbcdn.net:8443/x.jpg", // puerto que no es de Meta
|
||||
"https://127.0.0.1/x.jpg",
|
||||
"https://[::1]/x.jpg",
|
||||
"http://localhost:3000/api/dev/wa-mock/media-file/creativo-1",
|
||||
"http://169.254.169.254/latest/meta-data/",
|
||||
"file:///etc/passwd",
|
||||
"https://example.com/creativo.png",
|
||||
"no es una url",
|
||||
"",
|
||||
]) {
|
||||
expect(urlDeCreativoPermitida(u), u).toBe(false);
|
||||
}
|
||||
});
|
||||
|
||||
it("el origen del mock solo vale cuando se pasa, y exacto", () => {
|
||||
const mock = "http://localhost:3500";
|
||||
const url = "http://localhost:3500/api/dev/wa-mock/media-file/creativo-1";
|
||||
expect(urlDeCreativoPermitida(url)).toBe(false);
|
||||
expect(urlDeCreativoPermitida(url, mock)).toBe(true);
|
||||
expect(urlDeCreativoPermitida("http://localhost:3501/api/x", mock)).toBe(false);
|
||||
expect(urlDeCreativoPermitida("http://127.0.0.1:3500/api/x", mock)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("descargarCreativo", () => {
|
||||
const META = "https://scontent.xx.fbcdn.net/v/creativo.jpg?oe=1";
|
||||
const png = new Uint8Array([137, 80, 78, 71, 1, 2, 3]);
|
||||
const imagen = (body: BodyInit = png, headers: Record<string, string> = {}) =>
|
||||
new Response(body, { headers: { "content-type": "image/png", ...headers } });
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
/** Cada llamada a fetch toma la siguiente respuesta (o función) de la lista. */
|
||||
function stubFetch(...respuestas: (Response | (() => Promise<Response>))[]) {
|
||||
const fetchMock = vi.fn(async () => {
|
||||
const r = respuestas.shift();
|
||||
if (!r) throw new Error("fetch de más");
|
||||
return typeof r === "function" ? r() : r;
|
||||
});
|
||||
vi.stubGlobal("fetch", fetchMock);
|
||||
return fetchMock;
|
||||
}
|
||||
|
||||
it("baja una imagen de Meta, sin seguir redirecciones por su cuenta", async () => {
|
||||
const f = stubFetch(imagen());
|
||||
const d = await descargarCreativo(META);
|
||||
expect(d).toMatchObject({ ok: true, mimeType: "image/png" });
|
||||
expect(d.ok && d.data.byteLength).toBe(png.byteLength);
|
||||
expect(f).toHaveBeenCalledWith(META, expect.objectContaining({ redirect: "manual" }));
|
||||
});
|
||||
|
||||
it("revalida cada salto: una redirección fuera de Meta ni se pide", async () => {
|
||||
const f = stubFetch(
|
||||
new Response(null, { status: 302, headers: { location: "http://169.254.169.254/x" } })
|
||||
);
|
||||
expect(await descargarCreativo(META)).toEqual({ ok: false, falla: "permanente" });
|
||||
expect(f).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("sigue una redirección dentro de Meta", async () => {
|
||||
const f = stubFetch(
|
||||
new Response(null, { status: 301, headers: { location: "/v/otra.jpg" } }),
|
||||
imagen()
|
||||
);
|
||||
expect((await descargarCreativo(META)).ok).toBe(true);
|
||||
expect(f).toHaveBeenLastCalledWith(
|
||||
"https://scontent.xx.fbcdn.net/v/otra.jpg",
|
||||
expect.anything()
|
||||
);
|
||||
});
|
||||
|
||||
it("corta tras 3 redirecciones", async () => {
|
||||
const salto = () =>
|
||||
new Response(null, { status: 302, headers: { location: META } });
|
||||
const f = stubFetch(salto(), salto(), salto(), salto(), imagen());
|
||||
expect(await descargarCreativo(META)).toEqual({ ok: false, falla: "permanente" });
|
||||
expect(f).toHaveBeenCalledTimes(4);
|
||||
});
|
||||
|
||||
it("solo JPEG, PNG, WebP o GIF: un SVG no pasa", async () => {
|
||||
stubFetch(imagen('<svg xmlns="http://www.w3.org/2000/svg"/>', { "content-type": "image/svg+xml" }));
|
||||
expect(await descargarCreativo(META)).toEqual({ ok: false, falla: "permanente" });
|
||||
stubFetch(imagen("<html>", { "content-type": "text/html" }));
|
||||
expect(await descargarCreativo(META)).toEqual({ ok: false, falla: "permanente" });
|
||||
});
|
||||
|
||||
it("más de 300 KB no se descarga, lo declare o no", async () => {
|
||||
stubFetch(imagen(png, { "content-length": String(CREATIVO_MAX_BYTES + 1) }));
|
||||
expect(await descargarCreativo(META)).toEqual({ ok: false, falla: "permanente" });
|
||||
|
||||
// Sin content-length: se corta al pasar el tope, sin leer el resto.
|
||||
let emitidos = 0;
|
||||
const infinito = new ReadableStream<Uint8Array>({
|
||||
pull(controller) {
|
||||
emitidos += 64_000;
|
||||
controller.enqueue(new Uint8Array(64_000));
|
||||
},
|
||||
});
|
||||
stubFetch(imagen(infinito));
|
||||
expect(await descargarCreativo(META)).toEqual({ ok: false, falla: "permanente" });
|
||||
expect(emitidos).toBeLessThan(CREATIVO_MAX_BYTES + 3 * 64_000);
|
||||
});
|
||||
|
||||
it("distingue lo que vale reintentar de lo que no", async () => {
|
||||
stubFetch(new Response(null, { status: 503 }));
|
||||
expect(await descargarCreativo(META)).toEqual({ ok: false, falla: "transitoria" });
|
||||
stubFetch(new Response(null, { status: 429 }));
|
||||
expect(await descargarCreativo(META)).toEqual({ ok: false, falla: "transitoria" });
|
||||
stubFetch(() => Promise.reject(new DOMException("timeout", "TimeoutError")));
|
||||
expect(await descargarCreativo(META)).toEqual({ ok: false, falla: "transitoria" });
|
||||
stubFetch(new Response(null, { status: 404 }));
|
||||
expect(await descargarCreativo(META)).toEqual({ ok: false, falla: "permanente" });
|
||||
stubFetch(imagen(new Uint8Array(0)));
|
||||
expect(await descargarCreativo(META)).toEqual({ ok: false, falla: "permanente" });
|
||||
});
|
||||
|
||||
it("un host no permitido no llega a pedirse", async () => {
|
||||
const f = stubFetch(imagen());
|
||||
expect(await descargarCreativo("https://example.com/x.png")).toEqual({
|
||||
ok: false,
|
||||
falla: "permanente",
|
||||
});
|
||||
expect(f).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("reintenta una vez un fallo transitorio, y ninguna uno permanente", async () => {
|
||||
let f = stubFetch(new Response(null, { status: 503 }), imagen());
|
||||
expect((await descargarConReintento(META, 0)).ok).toBe(true);
|
||||
expect(f).toHaveBeenCalledTimes(2);
|
||||
|
||||
f = stubFetch(new Response(null, { status: 503 }), new Response(null, { status: 503 }), imagen());
|
||||
expect((await descargarConReintento(META, 0)).ok).toBe(false);
|
||||
expect(f).toHaveBeenCalledTimes(2);
|
||||
|
||||
f = stubFetch(new Response(null, { status: 404 }), imagen());
|
||||
expect((await descargarConReintento(META, 0)).ok).toBe(false);
|
||||
expect(f).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe("freno de la reparación", () => {
|
||||
it("como mucho un intento por anuncio cada 10 minutos", () => {
|
||||
const freno = crearFreno();
|
||||
const t0 = 1_000_000;
|
||||
expect(freno.intentar("org:ad1", t0)).toBe(true);
|
||||
expect(freno.intentar("org:ad1", t0 + 1)).toBe(false);
|
||||
expect(freno.intentar("org:ad1", t0 + REPARAR_CADA_MS - 1)).toBe(false);
|
||||
// Otro anuncio no espera al primero.
|
||||
expect(freno.intentar("org:ad2", t0 + 1)).toBe(true);
|
||||
// Pasada la ventana, se vuelve a intentar.
|
||||
expect(freno.intentar("org:ad1", t0 + REPARAR_CADA_MS)).toBe(true);
|
||||
});
|
||||
|
||||
it("purga las claves vencidas para no crecer sin fin", () => {
|
||||
const freno = crearFreno(1_000, 3);
|
||||
for (const k of ["a", "b", "c"]) freno.intentar(k, 0);
|
||||
expect(freno.claves).toBe(3);
|
||||
freno.intentar("d", 5_000);
|
||||
expect(freno.claves).toBe(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe("fuente y etiquetas", () => {
|
||||
it("lo capturado manda sobre el anuncio", () => {
|
||||
expect(effectiveSource("referido", true)).toEqual({
|
||||
value: "referido",
|
||||
source: "capturada",
|
||||
});
|
||||
});
|
||||
|
||||
it("sin captura, un anuncio deduce la fuente", () => {
|
||||
expect(effectiveSource(null, true)).toEqual({ value: "anuncio", source: "deducida" });
|
||||
expect(effectiveSource(null)).toEqual({ value: "desconocida", source: "deducida" });
|
||||
});
|
||||
|
||||
it("una publicación se enseña pero no cuenta como anuncio", () => {
|
||||
expect(cuentaComoAnuncio({ sourceType: "post" })).toBe(false);
|
||||
expect(cuentaComoAnuncio({ sourceType: "ad" })).toBe(true);
|
||||
expect(cuentaComoAnuncio({ sourceType: null })).toBe(true);
|
||||
expect(cuentaComoAnuncio(null)).toBe(false);
|
||||
expect(etiquetaDeOrigen("post")).toBe("Publicación");
|
||||
expect(etiquetaDeOrigen("ad")).toBe("Anuncio");
|
||||
expect(titularDeOrigen(null, "ad")).toBe("Anuncio sin título");
|
||||
expect(titularDeOrigen("Promo", "post")).toBe("Promo");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,64 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
/** 062 · AC5 — La apariencia del negocio solo la cambia quien configura. */
|
||||
const mocks = vi.hoisted(() => ({ session: vi.fn(), guardar: vi.fn(), leer: vi.fn() }));
|
||||
|
||||
vi.mock("@/lib/auth/session", async (original) => ({
|
||||
...(await original<typeof import("@/lib/auth/session")>()),
|
||||
requireSession: mocks.session,
|
||||
}));
|
||||
vi.mock("@/server/apariencia", () => ({
|
||||
aparienciaDelNegocio: mocks.leer,
|
||||
guardarAparienciaDelNegocio: mocks.guardar,
|
||||
}));
|
||||
|
||||
import { GET, PUT } from "@/app/api/settings/appearance/route";
|
||||
|
||||
const valida = { tema: "papel", letra: "inter", tamano: "grande", densidad: "compacta" };
|
||||
const pedir = (body: unknown) =>
|
||||
PUT(
|
||||
new Request("http://localhost/api/settings/appearance", {
|
||||
method: "PUT",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify(body),
|
||||
})
|
||||
);
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mocks.session.mockResolvedValue({ organizationId: "org_a", role: "owner" });
|
||||
mocks.leer.mockResolvedValue(null);
|
||||
});
|
||||
|
||||
describe("062 — PUT /api/settings/appearance", () => {
|
||||
it("el dueño la guarda en su organización", async () => {
|
||||
const res = await pedir(valida);
|
||||
expect(res.status).toBe(200);
|
||||
expect(mocks.guardar).toHaveBeenCalledWith("org_a", valida);
|
||||
});
|
||||
|
||||
it("un miembro del equipo recibe 403 y no se guarda nada", async () => {
|
||||
mocks.session.mockResolvedValue({ organizationId: "org_a", role: "member" });
|
||||
expect((await pedir(valida)).status).toBe(403);
|
||||
expect(mocks.guardar).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("un tema que no existe o un tamaño inventado es 422", async () => {
|
||||
expect((await pedir({ ...valida, tema: "hackeado" })).status).toBe(422);
|
||||
expect((await pedir({ ...valida, tamano: "gigante" })).status).toBe(422);
|
||||
expect(mocks.guardar).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("un tema propio ilegible es 422 con el motivo", async () => {
|
||||
const res = await pedir({ ...valida, tema: "propio", propio: { fondo: "#ffffff", texto: "#eeeeee", marco: "#dddddd" } });
|
||||
expect(res.status).toBe(422);
|
||||
expect((await res.json()).error.message).toMatch(/no se lee/);
|
||||
});
|
||||
|
||||
it("GET devuelve la del negocio", async () => {
|
||||
mocks.leer.mockResolvedValue(valida);
|
||||
const res = await GET();
|
||||
expect(await res.json()).toEqual({ apariencia: valida });
|
||||
expect(mocks.leer).toHaveBeenCalledWith("org_a");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,257 @@
|
||||
import { readdirSync, readFileSync, statSync } from "node:fs";
|
||||
import { join, relative, sep } from "node:path";
|
||||
import { afterAll, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
/**
|
||||
* 069 — API pública v1: la puerta por llave.
|
||||
*
|
||||
* Lo que de verdad importa aquí es que la organización salga de la llave, que
|
||||
* con la bandera apagada no exista nada, y que el permiso nunca pase de lo que
|
||||
* tiene quien la creó. El camino completo contra la app viva lo ejerce
|
||||
* `scripts/e2e-api-mcp.mjs`.
|
||||
*/
|
||||
|
||||
const st = vi.hoisted(() => ({
|
||||
llave: null as null | Record<string, unknown>,
|
||||
instancia: "org_a" as string | null,
|
||||
role: "owner" as string | null,
|
||||
limite: true,
|
||||
usos: 0,
|
||||
}));
|
||||
|
||||
vi.mock("@/server/bot/auth", () => ({ resolveInstanceOrg: async () => st.instancia }));
|
||||
vi.mock("@/server/api-v1/acceso", async (orig) => {
|
||||
const real = await orig<typeof import("@/server/api-v1/acceso")>();
|
||||
return { ...real, rolVigente: async () => st.role };
|
||||
});
|
||||
vi.mock("@/lib/rate-limit", () => ({
|
||||
checkRateLimit: () => ({ allowed: st.limite, remaining: 0 }),
|
||||
clientIp: () => "1.2.3.4",
|
||||
}));
|
||||
vi.mock("@/server/oauth/servidor", () => ({ accesoPorValor: async () => null, registrarUsoGrant: async () => {} }));
|
||||
vi.mock("@/lib/db", () => {
|
||||
const update = () => ({
|
||||
set: () => ({
|
||||
where: () => {
|
||||
st.usos++;
|
||||
return Promise.resolve();
|
||||
},
|
||||
}),
|
||||
});
|
||||
return { getDb: () => ({ update }), schema: { organization: {}, apiKey: {} } };
|
||||
});
|
||||
vi.mock("@/server/api-v1/llaves", async (orig) => {
|
||||
const real = await orig<typeof import("@/server/api-v1/llaves")>();
|
||||
return { ...real, llavePorValor: async () => st.llave };
|
||||
});
|
||||
|
||||
import { generarLlave, hashLlave, normalizarScopes } from "@/server/api-v1/llaves";
|
||||
import { withApiKey } from "@/server/api-v1/handler";
|
||||
import { parseApiV1Flag } from "@/server/api-v1/flag";
|
||||
|
||||
const LLAVE = "vk_" + "a".repeat(40);
|
||||
const pedir = (auth: string | null = `Bearer ${LLAVE}`) =>
|
||||
new Request("https://crm.negocio.test/api/v1/contacts", { headers: auth ? { authorization: auth } : {} });
|
||||
|
||||
function llave(scopes: string[], organizationId = "org_a") {
|
||||
return { id: "ak_1", organizationId, prefix: "vk_aaaaaaa", last4: "aaaa", name: "n8n", scopes, createdByUserId: "usr_1" };
|
||||
}
|
||||
|
||||
const envAntes = { API_V1: process.env.API_V1, APP_BASE_URL: process.env.APP_BASE_URL };
|
||||
afterAll(() => {
|
||||
process.env.API_V1 = envAntes.API_V1;
|
||||
process.env.APP_BASE_URL = envAntes.APP_BASE_URL;
|
||||
});
|
||||
|
||||
describe("llaves", () => {
|
||||
it("genera vk_ + 40 caracteres y guarda solo el sha256", () => {
|
||||
const g = generarLlave();
|
||||
expect(g.valor).toMatch(/^vk_[A-Za-z0-9_-]{40}$/);
|
||||
expect(g.hash).toBe(hashLlave(g.valor));
|
||||
expect(g.hash).not.toContain(g.valor);
|
||||
expect(g.prefix).toBe(g.valor.slice(0, 10));
|
||||
expect(g.last4).toBe(g.valor.slice(-4));
|
||||
expect(generarLlave().valor).not.toBe(g.valor);
|
||||
});
|
||||
|
||||
it("leer va siempre, y mandar arrastra operar", () => {
|
||||
expect(normalizarScopes([])).toEqual(["read"]);
|
||||
expect(normalizarScopes(["send"])).toEqual(["read", "operate", "send"]);
|
||||
expect(normalizarScopes(["operate"])).toEqual(["read", "operate"]);
|
||||
// Configurar no arrastra operar: una llave de Claude que configura no mueve leads.
|
||||
expect(normalizarScopes(["configure"])).toEqual(["read", "configure"]);
|
||||
});
|
||||
|
||||
it("la bandera API_V1 se enciende solo con un valor explícito", () => {
|
||||
for (const v of ["on", "1", "true", "sí", " ON "]) expect(parseApiV1Flag(v)).toBe(true);
|
||||
for (const v of [undefined, "", "off", "0", "no", "api"]) expect(parseApiV1Flag(v)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("withApiKey", () => {
|
||||
const handler = vi.fn(async (session: { organizationId: string; role: string; capabilities?: string[] }, _req: Request) =>
|
||||
Response.json({ org: session.organizationId, role: session.role, caps: session.capabilities })
|
||||
);
|
||||
|
||||
beforeEach(() => {
|
||||
process.env.API_V1 = "on";
|
||||
st.instancia = "org_a";
|
||||
st.role = "owner";
|
||||
st.llave = llave(["read"]);
|
||||
st.limite = true;
|
||||
st.usos = 0;
|
||||
handler.mockClear();
|
||||
});
|
||||
|
||||
it("con la bandera apagada responde 404 sin mirar la llave (no delata la ruta)", async () => {
|
||||
process.env.API_V1 = "";
|
||||
expect((await withApiKey("read", handler)(pedir(null))).status).toBe(404);
|
||||
expect((await withApiKey("read", handler)(pedir())).status).toBe(404);
|
||||
expect(handler).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("sin llave: 401 missing_key, y no llama al handler", async () => {
|
||||
const res = await withApiKey("read", handler)(pedir(null));
|
||||
expect(res.status).toBe(401);
|
||||
expect((await res.json()).error.code).toBe("missing_key");
|
||||
expect(handler).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("una cookie no autentica: solo cuenta la cabecera Authorization", async () => {
|
||||
const req = new Request("https://crm.negocio.test/api/v1/contacts", { headers: { cookie: "better-auth.session_token=x" } });
|
||||
expect((await withApiKey("read", handler)(req)).status).toBe(401);
|
||||
});
|
||||
|
||||
it("llave desconocida o revocada: 401 invalid_key", async () => {
|
||||
st.llave = null;
|
||||
const res = await withApiKey("read", handler)(pedir());
|
||||
expect(res.status).toBe(401);
|
||||
expect((await res.json()).error.code).toBe("invalid_key");
|
||||
});
|
||||
|
||||
it("muchos fallos desde la misma IP: 429", async () => {
|
||||
st.llave = null;
|
||||
st.limite = false;
|
||||
expect((await withApiKey("read", handler)(pedir())).status).toBe(429);
|
||||
});
|
||||
|
||||
it("la organización sale de la llave y el permiso se recorta", async () => {
|
||||
const res = await withApiKey("read", handler)(pedir());
|
||||
expect(res.status).toBe(200);
|
||||
// Sin `configure`, el handler ve a un miembro aunque quien la creó sea dueño.
|
||||
expect(await res.json()).toEqual({ org: "org_a", role: "member", caps: ["read"] });
|
||||
expect(st.usos).toBe(1);
|
||||
});
|
||||
|
||||
it("una llave de otra organización (una base copiada) no sirve aquí", async () => {
|
||||
st.llave = llave(["read"], "org_b");
|
||||
const res = await withApiKey("read", handler)(pedir());
|
||||
expect(res.status).toBe(401);
|
||||
expect(handler).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("si quien la creó salió del equipo, la llave no sirve", async () => {
|
||||
st.role = null;
|
||||
const res = await withApiKey("read", handler)(pedir());
|
||||
expect(res.status).toBe(401);
|
||||
expect((await res.json()).error.code).toBe("key_owner_without_access");
|
||||
});
|
||||
|
||||
it("una llave de lectura no opera ni manda", async () => {
|
||||
expect((await withApiKey("operate", handler)(pedir())).status).toBe(403);
|
||||
expect((await withApiKey("send", handler)(pedir())).status).toBe(403);
|
||||
});
|
||||
|
||||
it("operar no basta para mandar: send es un permiso aparte", async () => {
|
||||
st.llave = llave(["read", "operate"]);
|
||||
expect((await withApiKey("operate", handler)(pedir())).status).toBe(200);
|
||||
expect((await withApiKey("send", handler)(pedir())).status).toBe(403);
|
||||
st.llave = llave(["read", "operate", "send"]);
|
||||
expect((await withApiKey("send", handler)(pedir())).status).toBe(200);
|
||||
});
|
||||
|
||||
it("configure es un permiso aparte: ni leer ni operar lo dan", async () => {
|
||||
st.llave = llave(["read", "operate", "send"]);
|
||||
const res = await withApiKey("configure", handler)(pedir());
|
||||
expect(res.status).toBe(403);
|
||||
expect((await res.json()).error.code).toBe("insufficient_scope");
|
||||
expect(handler).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("una llave configure de un dueño o administrador configura, con su rol", async () => {
|
||||
st.llave = llave(["read", "configure"]);
|
||||
const res = await withApiKey("configure", handler)(pedir());
|
||||
expect(res.status).toBe(200);
|
||||
expect(await res.json()).toMatchObject({ role: "owner", caps: ["read", "configure"] });
|
||||
st.role = "admin";
|
||||
expect((await withApiKey("configure", handler)(pedir())).status).toBe(200);
|
||||
// …y no opera: configurar no arrastra operar.
|
||||
expect((await withApiKey("operate", handler)(pedir())).status).toBe(403);
|
||||
});
|
||||
|
||||
it("si a quien la creó lo bajan a miembro, su llave deja de configurar", async () => {
|
||||
st.llave = llave(["read", "operate", "configure"]);
|
||||
st.role = "member";
|
||||
expect((await withApiKey("configure", handler)(pedir())).status).toBe(403);
|
||||
const res = await withApiKey("operate", handler)(pedir());
|
||||
expect(res.status).toBe(200);
|
||||
expect((await res.json()).role).toBe("member");
|
||||
});
|
||||
|
||||
it("pasado el límite: 429 con Retry-After", async () => {
|
||||
st.limite = false;
|
||||
const res = await withApiKey("read", handler)(pedir());
|
||||
expect(res.status).toBe(429);
|
||||
expect(res.headers.get("Retry-After")).toBe("60");
|
||||
expect(handler).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe("OpenAPI de la v1", () => {
|
||||
const raiz = join(process.cwd(), "src/app/api/v1");
|
||||
const spec = JSON.parse(readFileSync(join(process.cwd(), "src/server/api-v1/openapi.json"), "utf8")) as {
|
||||
paths: Record<string, Record<string, unknown>>;
|
||||
};
|
||||
|
||||
function rutas(dir: string): string[] {
|
||||
return readdirSync(dir).flatMap((n) => {
|
||||
const p = join(dir, n);
|
||||
if (statSync(p).isDirectory()) return rutas(p);
|
||||
return n === "route.ts" ? [p] : [];
|
||||
});
|
||||
}
|
||||
|
||||
it("cada ruta y cada verbo del código está documentado, y nada más", () => {
|
||||
const delCodigo = new Set<string>();
|
||||
for (const archivo of rutas(raiz)) {
|
||||
const path = "/" + relative(raiz, archivo).split(sep).slice(0, -1).join("/").replace(/\[(\w+)\]/g, "{$1}");
|
||||
for (const m of readFileSync(archivo, "utf8").matchAll(/export (?:const|(?:async )?function) (GET|POST|PATCH|PUT|DELETE)\b/g)) {
|
||||
delCodigo.add(`${m[1]!.toLowerCase()} ${path}`);
|
||||
}
|
||||
}
|
||||
const documentadas = new Set<string>();
|
||||
for (const [path, ops] of Object.entries(spec.paths)) {
|
||||
for (const verbo of Object.keys(ops)) if (verbo !== "parameters") documentadas.add(`${verbo} ${path}`);
|
||||
}
|
||||
expect([...documentadas].sort()).toEqual([...delCodigo].sort());
|
||||
});
|
||||
});
|
||||
|
||||
describe("/api/v1/openapi.json", () => {
|
||||
it("con la API encendida: el contrato con la URL pública de la instancia", async () => {
|
||||
process.env.API_V1 = "on";
|
||||
process.env.APP_BASE_URL = "https://crm.negocio.test/";
|
||||
const { GET } = await import("@/app/api/v1/openapi.json/route");
|
||||
const res = await GET();
|
||||
expect(res.status).toBe(200);
|
||||
const body = await res.json();
|
||||
expect(body.openapi).toBe("3.1.0");
|
||||
expect(body.servers[0].url).toBe("https://crm.negocio.test/api/v1");
|
||||
});
|
||||
|
||||
it("con la API apagada: 404", async () => {
|
||||
process.env.API_V1 = "off";
|
||||
const { GET } = await import("@/app/api/v1/openapi.json/route");
|
||||
expect((await GET()).status).toBe(404);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,85 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
ATAJOS,
|
||||
atajoBandeja,
|
||||
esAyuda,
|
||||
esBarraDeComandos,
|
||||
esCampoDeTexto,
|
||||
sirveEscribiendo,
|
||||
vecina,
|
||||
} from "@/lib/atajos";
|
||||
|
||||
/** 055 — Qué combinación es cuál, cuándo no se toca lo que se escribe y el orden. */
|
||||
const tecla = (p: Partial<{ key: string; code: string; altKey: boolean; ctrlKey: boolean; metaKey: boolean; shiftKey: boolean }>) => ({
|
||||
key: "",
|
||||
code: "",
|
||||
altKey: false,
|
||||
ctrlKey: false,
|
||||
metaKey: false,
|
||||
shiftKey: false,
|
||||
...p,
|
||||
});
|
||||
|
||||
describe("055 — combinaciones", () => {
|
||||
it("Ctrl+K y ⌘K abren la barra; con Alt o Shift, no", () => {
|
||||
expect(esBarraDeComandos(tecla({ key: "k", ctrlKey: true }))).toBe(true);
|
||||
expect(esBarraDeComandos(tecla({ key: "K", metaKey: true }))).toBe(true);
|
||||
expect(esBarraDeComandos(tecla({ key: "k", ctrlKey: true, shiftKey: true }))).toBe(false);
|
||||
expect(esBarraDeComandos(tecla({ key: "k", ctrlKey: true, altKey: true }))).toBe(false);
|
||||
expect(esBarraDeComandos(tecla({ key: "k" }))).toBe(false);
|
||||
});
|
||||
|
||||
it("«?» abre la ayuda aunque lleve Shift, no con Ctrl", () => {
|
||||
expect(esAyuda(tecla({ key: "?", shiftKey: true }))).toBe(true);
|
||||
expect(esAyuda(tecla({ key: "?", ctrlKey: true }))).toBe(false);
|
||||
});
|
||||
|
||||
it("los de la Bandeja miran la tecla física con Alt (Option+J en Mac escribe «∆»)", () => {
|
||||
expect(atajoBandeja(tecla({ key: "∆", code: "KeyJ", altKey: true }))).toBe("siguiente");
|
||||
expect(atajoBandeja(tecla({ key: "k", code: "KeyK", altKey: true }))).toBe("anterior");
|
||||
expect(atajoBandeja(tecla({ key: "r", code: "KeyR", altKey: true }))).toBe("responder");
|
||||
expect(atajoBandeja(tecla({ key: "n", code: "KeyN", altKey: true }))).toBe("nota");
|
||||
expect(atajoBandeja(tecla({ key: "/", code: "Slash" }))).toBe("buscar");
|
||||
expect(atajoBandeja(tecla({ key: "j", code: "KeyJ" }))).toBeNull();
|
||||
expect(atajoBandeja(tecla({ key: "j", code: "KeyJ", altKey: true, ctrlKey: true }))).toBeNull();
|
||||
});
|
||||
|
||||
it("los de Alt sirven escribiendo; «/» no (en el compositor abre las respuestas rápidas)", () => {
|
||||
expect(sirveEscribiendo("siguiente")).toBe(true);
|
||||
expect(sirveEscribiendo("nota")).toBe(true);
|
||||
expect(sirveEscribiendo("buscar")).toBe(false);
|
||||
});
|
||||
|
||||
it("la ayuda lista cada atajo que existe", () => {
|
||||
expect(ATAJOS.map((a) => a.teclas.join("+"))).toEqual(["Ctrl+K", "?", "Alt+J", "Alt+K", "/", "Alt+R", "Alt+N"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("055 — campos de texto", () => {
|
||||
it("input, textarea, select y contenteditable son campos; un botón no", () => {
|
||||
expect(esCampoDeTexto({ tagName: "INPUT" } as unknown as EventTarget)).toBe(true);
|
||||
expect(esCampoDeTexto({ tagName: "TEXTAREA" } as unknown as EventTarget)).toBe(true);
|
||||
expect(esCampoDeTexto({ tagName: "SELECT" } as unknown as EventTarget)).toBe(true);
|
||||
expect(esCampoDeTexto({ tagName: "DIV", isContentEditable: true } as unknown as EventTarget)).toBe(true);
|
||||
expect(esCampoDeTexto({ tagName: "BUTTON", isContentEditable: false } as unknown as EventTarget)).toBe(false);
|
||||
expect(esCampoDeTexto(null)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("055 — la conversación vecina", () => {
|
||||
const ids = ["a", "b", "c"];
|
||||
it("avanza y retrocede en el orden que se ve", () => {
|
||||
expect(vecina(ids, "a", 1)).toBe("b");
|
||||
expect(vecina(ids, "c", -1)).toBe("b");
|
||||
});
|
||||
it("sin ninguna elegida, a la primera o a la última", () => {
|
||||
expect(vecina(ids, null, 1)).toBe("a");
|
||||
expect(vecina(ids, null, -1)).toBe("c");
|
||||
expect(vecina(ids, "z", 1)).toBe("a");
|
||||
});
|
||||
it("en los extremos no da la vuelta, y sin lista no hay nada", () => {
|
||||
expect(vecina(ids, "c", 1)).toBeNull();
|
||||
expect(vecina(ids, "a", -1)).toBeNull();
|
||||
expect(vecina([], null, 1)).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,44 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { CAPACIDAD_ATENCION_HUMANA, capacidadesDelCrm } from "@/server/brains/contract";
|
||||
import { armarAtencion, MAX_TEXTO_ATENCION, recortarParaNota } from "@/server/brains/atencion-humana";
|
||||
|
||||
/**
|
||||
* 076 — «Hubo una persona», tal como lo ve un cerebro.
|
||||
*
|
||||
* `EVENTO_GEMELO` es el mismo cuerpo que fija Vocero Cloud, y el que prueba
|
||||
* `tests/test_atencion_humana.py` de nea-agent del otro lado: que
|
||||
* Nea lee este campo, lo pone en el prompt y, sin él, el prompt no cambia. Si
|
||||
* aquí cambia un nombre o el orden de una clave, esta prueba falla antes de
|
||||
* que Nea vuelva a contradecir al equipo.
|
||||
*/
|
||||
const EVENTO_GEMELO =
|
||||
'{"humanAttention":{"since":"2026-11-20T15:00:00.000Z",' +
|
||||
'"lastTeamMessageAt":"2026-11-20T15:05:00.000Z","messages":[' +
|
||||
'{"at":"2026-11-20T14:58:00.000Z","author":"customer","type":"text","text":"¿Cuánto cuesta la limpieza?"},' +
|
||||
'{"at":"2026-11-20T15:00:00.000Z","author":"team","type":"text","text":"La limpieza queda en $850 con la promoción de esta semana."},' +
|
||||
'{"at":"2026-11-20T15:05:00.000Z","author":"team","type":"image","text":null}]}}';
|
||||
|
||||
describe("contrato de la nota «hubo una persona»", () => {
|
||||
it("el CRM la anuncia en cada despacho", () => {
|
||||
expect(CAPACIDAD_ATENCION_HUMANA).toBe("atencion_humana");
|
||||
expect(capacidadesDelCrm()).toContain(CAPACIDAD_ATENCION_HUMANA);
|
||||
});
|
||||
|
||||
it("arma exactamente el cuerpo gemelo, en el mismo orden", () => {
|
||||
const campo = armarAtencion(new Date("2026-11-20T15:00:00.000Z"), new Date("2026-11-20T15:05:00.000Z"), [
|
||||
{ at: new Date("2026-11-20T14:58:00.000Z"), direction: "in", type: "text", text: "¿Cuánto cuesta la limpieza?" },
|
||||
{ at: new Date("2026-11-20T15:00:00.000Z"), direction: "out", type: "text", text: "La limpieza queda en $850 con la promoción de esta semana." },
|
||||
{ at: new Date("2026-11-20T15:05:00.000Z"), direction: "out", type: "image", text: null },
|
||||
]);
|
||||
expect(JSON.stringify({ humanAttention: campo })).toBe(EVENTO_GEMELO);
|
||||
});
|
||||
|
||||
it("recorta y limpia el texto, sin inventar nada", () => {
|
||||
expect(recortarParaNota(null)).toBeNull();
|
||||
expect(recortarParaNota(" ")).toBeNull();
|
||||
expect(recortarParaNota("hola\n\n qué tal")).toBe("hola qué tal");
|
||||
const largo = recortarParaNota("a".repeat(2000));
|
||||
expect(largo).toHaveLength(MAX_TEXTO_ATENCION);
|
||||
expect(largo?.endsWith("…")).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,39 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { parseAtribucionFlag } from "@/server/attribution/flag";
|
||||
|
||||
/**
|
||||
* 016 — La bandera de la atribución. El caso que importa es el DEFAULT: una
|
||||
* instancia que no la pidió no debe acabar guardando identificadores de clic
|
||||
* de Meta ni mandándole eventos por un despiste de configuración.
|
||||
*/
|
||||
|
||||
describe("parseAtribucionFlag", () => {
|
||||
it("sin variable, la atribución no existe", () => {
|
||||
expect(parseAtribucionFlag(undefined)).toBe(false);
|
||||
expect(parseAtribucionFlag("")).toBe(false);
|
||||
expect(parseAtribucionFlag(" ")).toBe(false);
|
||||
});
|
||||
|
||||
it("`on` la enciende, con espacios y mayúsculas de por medio", () => {
|
||||
expect(parseAtribucionFlag("on")).toBe(true);
|
||||
expect(parseAtribucionFlag("ON")).toBe(true);
|
||||
expect(parseAtribucionFlag(" On ")).toBe(true);
|
||||
});
|
||||
|
||||
it("acepta las otras formas de decir que sí", () => {
|
||||
expect(parseAtribucionFlag("1")).toBe(true);
|
||||
expect(parseAtribucionFlag("true")).toBe(true);
|
||||
expect(parseAtribucionFlag("si")).toBe(true);
|
||||
expect(parseAtribucionFlag("sí")).toBe(true);
|
||||
expect(parseAtribucionFlag("yes")).toBe(true);
|
||||
});
|
||||
|
||||
it("cualquier otra cosa la deja apagada, incluido `off` y `false`", () => {
|
||||
expect(parseAtribucionFlag("off")).toBe(false);
|
||||
expect(parseAtribucionFlag("false")).toBe(false);
|
||||
expect(parseAtribucionFlag("0")).toBe(false);
|
||||
expect(parseAtribucionFlag("no")).toBe(false);
|
||||
// Un typo no enciende nada: apagada es el estado seguro.
|
||||
expect(parseAtribucionFlag("onn")).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,236 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
buildCandidateSlots,
|
||||
filterFreeSlots,
|
||||
} from "@/server/agenda/availability";
|
||||
import {
|
||||
DEFAULT_CALENDAR_SETTINGS,
|
||||
normalizeWeeklyHours,
|
||||
type CalendarSettings,
|
||||
} from "@/server/agenda/settings";
|
||||
import { daysWithAgenda, spreadByDay } from "@/server/agenda/spread";
|
||||
|
||||
/** 015 — El motor: horario − ocupado, con aviso mínimo. Sin BD ni reloj real. */
|
||||
|
||||
const MX = "America/Mexico_City";
|
||||
|
||||
function settings(over: Partial<CalendarSettings> = {}): CalendarSettings {
|
||||
return { ...DEFAULT_CALENDAR_SETTINGS, ...over };
|
||||
}
|
||||
|
||||
describe("buildCandidateSlots", () => {
|
||||
it("solo genera slots en los días con horario (L-V por defecto)", () => {
|
||||
// 2026-08-08 es sábado; 2026-08-10 lunes.
|
||||
const slots = buildCandidateSlots(settings(), "2026-08-08", "2026-08-10");
|
||||
const días = new Set(slots.map((s) => s.startUtc.slice(0, 10)));
|
||||
expect(días.has("2026-08-08")).toBe(false); // sábado cerrado
|
||||
expect(días.has("2026-08-09")).toBe(false); // domingo cerrado
|
||||
expect(días.size).toBeGreaterThan(0); // el lunes sí
|
||||
});
|
||||
|
||||
it("respeta la duración configurada", () => {
|
||||
const cortos = buildCandidateSlots(
|
||||
settings({ slotMinutes: 30 }),
|
||||
"2026-08-05",
|
||||
"2026-08-05"
|
||||
);
|
||||
const largos = buildCandidateSlots(
|
||||
settings({ slotMinutes: 60 }),
|
||||
"2026-08-05",
|
||||
"2026-08-05"
|
||||
);
|
||||
// 09:00-18:00 ⇒ 18 slots de 30 min, 9 de 60.
|
||||
expect(cortos).toHaveLength(18);
|
||||
expect(largos).toHaveLength(9);
|
||||
});
|
||||
|
||||
it("un horario vacío no genera nada (negocio sin configurar días)", () => {
|
||||
expect(
|
||||
buildCandidateSlots(
|
||||
settings({ weeklyHours: {} }),
|
||||
"2026-08-03",
|
||||
"2026-08-07"
|
||||
)
|
||||
).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("filterFreeSlots", () => {
|
||||
const tz = MX;
|
||||
const candidates = buildCandidateSlots(
|
||||
settings(),
|
||||
"2026-08-05",
|
||||
"2026-08-05"
|
||||
);
|
||||
|
||||
it("descarta lo que no cumple el aviso mínimo", () => {
|
||||
// "Ahora" son las 09:00 locales del mismo día, con 2 h de aviso ⇒ el
|
||||
// primer hueco ofrecible es a las 11:00 locales (17:00Z).
|
||||
const now = new Date("2026-08-05T15:00:00.000Z");
|
||||
const free = filterFreeSlots(candidates, [], {
|
||||
now,
|
||||
minNoticeHours: 2,
|
||||
timezone: tz,
|
||||
});
|
||||
expect(free[0]!.startUtc).toBe("2026-08-05T17:00:00.000Z");
|
||||
});
|
||||
|
||||
it("sin aviso mínimo ofrece desde el instante actual", () => {
|
||||
const now = new Date("2026-08-05T15:00:00.000Z");
|
||||
const free = filterFreeSlots(candidates, [], {
|
||||
now,
|
||||
minNoticeHours: 0,
|
||||
timezone: tz,
|
||||
});
|
||||
expect(free[0]!.startUtc).toBe("2026-08-05T15:00:00.000Z");
|
||||
});
|
||||
|
||||
it("una cita ocupada retira su hueco y solo ese", () => {
|
||||
const now = new Date("2026-08-05T00:00:00.000Z");
|
||||
const ocupado = [
|
||||
{
|
||||
startUtc: "2026-08-05T16:00:00.000Z",
|
||||
endUtc: "2026-08-05T16:30:00.000Z",
|
||||
},
|
||||
];
|
||||
const libres = filterFreeSlots(candidates, ocupado, {
|
||||
now,
|
||||
minNoticeHours: 0,
|
||||
timezone: tz,
|
||||
});
|
||||
const inicios = libres.map((s) => s.startUtc);
|
||||
expect(inicios).not.toContain("2026-08-05T16:00:00.000Z");
|
||||
expect(inicios).toContain("2026-08-05T16:30:00.000Z");
|
||||
expect(inicios).toContain("2026-08-05T15:30:00.000Z");
|
||||
});
|
||||
|
||||
it("un bloqueo largo retira todos los huecos que toca", () => {
|
||||
const now = new Date("2026-08-05T00:00:00.000Z");
|
||||
const bloqueo = [
|
||||
{
|
||||
startUtc: "2026-08-05T15:00:00.000Z",
|
||||
endUtc: "2026-08-05T17:00:00.000Z", // 2 h ⇒ 4 slots de 30
|
||||
},
|
||||
];
|
||||
const libres = filterFreeSlots(candidates, bloqueo, {
|
||||
now,
|
||||
minNoticeHours: 0,
|
||||
timezone: tz,
|
||||
});
|
||||
expect(libres).toHaveLength(candidates.length - 4);
|
||||
});
|
||||
|
||||
it("devuelve los huecos ordenados y etiquetados", () => {
|
||||
const now = new Date("2026-08-05T00:00:00.000Z");
|
||||
const libres = filterFreeSlots([...candidates].reverse(), [], {
|
||||
now,
|
||||
minNoticeHours: 0,
|
||||
timezone: tz,
|
||||
});
|
||||
const tiempos = libres.map((s) => Date.parse(s.startUtc));
|
||||
expect([...tiempos].sort((a, b) => a - b)).toEqual(tiempos);
|
||||
expect(libres[0]!.label).toContain("09:00");
|
||||
});
|
||||
|
||||
it("agenda llena ⇒ lista vacía, no error", () => {
|
||||
const now = new Date("2026-08-05T00:00:00.000Z");
|
||||
const todo = candidates.map((c) => ({
|
||||
startUtc: c.startUtc,
|
||||
endUtc: c.endUtc,
|
||||
}));
|
||||
expect(
|
||||
filterFreeSlots(candidates, todo, {
|
||||
now,
|
||||
minNoticeHours: 0,
|
||||
timezone: tz,
|
||||
})
|
||||
).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* Sin reparto, los primeros huecos se los come el día de hoy y quien ofrece se
|
||||
* queda sin nada que decir cuando el lead pide otro día.
|
||||
*/
|
||||
describe("spreadByDay", () => {
|
||||
// 14:00Z son las 08:00 en México: "hoy" es el miércoles 5, no la víspera.
|
||||
// (Con 00:00Z el día local del negocio sería todavía el 4 — el motor decide
|
||||
// el día en la zona del negocio, no en la del servidor.)
|
||||
const now = new Date("2026-08-05T14:00:00.000Z");
|
||||
// Mié 5 a vie 7 de agosto, 09:00-18:00, citas de 30 ⇒ 18 huecos por día.
|
||||
const libres = filterFreeSlots(
|
||||
buildCandidateSlots(settings(), "2026-08-05", "2026-08-07"),
|
||||
[],
|
||||
{ now, minNoticeHours: 0, timezone: MX }
|
||||
);
|
||||
|
||||
it("toma como mucho `perDay` de cada día, en vez de los N más próximos", () => {
|
||||
const spread = spreadByDay(libres, {
|
||||
timezone: MX,
|
||||
limit: 12,
|
||||
perDay: 3,
|
||||
now,
|
||||
});
|
||||
expect(spread).toHaveLength(9); // 3 días × 3
|
||||
expect(daysWithAgenda(spread)).toEqual([
|
||||
"2026-08-05",
|
||||
"2026-08-06",
|
||||
"2026-08-07",
|
||||
]);
|
||||
});
|
||||
|
||||
it("el límite corta el total sin romper el reparto", () => {
|
||||
const spread = spreadByDay(libres, {
|
||||
timezone: MX,
|
||||
limit: 4,
|
||||
perDay: 3,
|
||||
now,
|
||||
});
|
||||
expect(spread).toHaveLength(4);
|
||||
// 3 del primer día + 1 del segundo: el límite no se come la variedad.
|
||||
expect(daysWithAgenda(spread)).toEqual(["2026-08-05", "2026-08-06"]);
|
||||
});
|
||||
|
||||
it("cada hueco viaja con su día EN PALABRAS y su hora", () => {
|
||||
const spread = spreadByDay(libres, {
|
||||
timezone: MX,
|
||||
limit: 3,
|
||||
perDay: 1,
|
||||
now,
|
||||
});
|
||||
expect(spread[0]!.dayLabel).toMatch(/^hoy /);
|
||||
expect(spread[1]!.dayLabel).toMatch(/^mañana /);
|
||||
expect(spread[0]!.time).toBe("09:00");
|
||||
});
|
||||
|
||||
it("sin huecos no inventa días", () => {
|
||||
expect(
|
||||
spreadByDay([], { timezone: MX, limit: 12, perDay: 3, now })
|
||||
).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("normalizeWeeklyHours", () => {
|
||||
it("descarta intervalos inválidos sin tumbar el resto del horario", () => {
|
||||
const out = normalizeWeeklyHours({
|
||||
mon: [
|
||||
{ start: "09:00", end: "18:00" },
|
||||
{ start: "20:00", end: "19:00" }, // fin antes del inicio
|
||||
{ start: "9:00", end: "18:00" }, // formato inválido
|
||||
],
|
||||
tue: [],
|
||||
});
|
||||
expect(out.mon).toEqual([{ start: "09:00", end: "18:00" }]);
|
||||
expect(out.tue).toBeUndefined(); // día sin franjas válidas = cerrado
|
||||
});
|
||||
|
||||
it("ordena las franjas por hora de inicio", () => {
|
||||
const out = normalizeWeeklyHours({
|
||||
wed: [
|
||||
{ start: "16:00", end: "18:00" },
|
||||
{ start: "09:00", end: "13:00" },
|
||||
],
|
||||
});
|
||||
expect(out.wed?.[0]?.start).toBe("09:00");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,19 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { tituloConNoLeidos } from "@/components/avisos-de-mensajes";
|
||||
|
||||
/** 045 — El contador de la pestaña, como «(3) WhatsApp». */
|
||||
describe("tituloConNoLeidos", () => {
|
||||
it("antepone los chats sin leer", () => {
|
||||
expect(tituloConNoLeidos("Vocero — CRM", 3)).toBe("(3) Vocero — CRM");
|
||||
});
|
||||
it("sin pendientes deja el título limpio", () => {
|
||||
expect(tituloConNoLeidos("(3) Vocero — CRM", 0)).toBe("Vocero — CRM");
|
||||
});
|
||||
it("no apila contadores al actualizar", () => {
|
||||
expect(tituloConNoLeidos("(3) Vocero — CRM", 5)).toBe("(5) Vocero — CRM");
|
||||
});
|
||||
it("más de 99 se muestra como 99+", () => {
|
||||
expect(tituloConNoLeidos("Vocero", 140)).toBe("(99+) Vocero");
|
||||
expect(tituloConNoLeidos("(99+) Vocero", 2)).toBe("(2) Vocero");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,68 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
AVISO_MAX_CARACTERES,
|
||||
cuerpoAviso,
|
||||
debeAvisarSistema,
|
||||
esperaReintento,
|
||||
urlDeAvisoSegura,
|
||||
urlDeConversacion,
|
||||
} from "@/lib/avisos-sistema";
|
||||
|
||||
/** 056 — Cuándo avisa (D2), qué dice (D3) y cuánto espera para reintentar (D6). */
|
||||
describe("056 — cuándo avisa", () => {
|
||||
const base = { direction: "in", campana: true, permiso: "granted", visible: false, foco: false };
|
||||
|
||||
it("un mensaje del cliente con Vocero oculto avisa", () => {
|
||||
expect(debeAvisarSistema(base)).toBe(true);
|
||||
});
|
||||
|
||||
it("visible pero sin el foco (otra ventana al frente) también", () => {
|
||||
expect(debeAvisarSistema({ ...base, visible: true, foco: false })).toBe(true);
|
||||
});
|
||||
|
||||
it("si el operador está mirando, no: ya suena", () => {
|
||||
expect(debeAvisarSistema({ ...base, visible: true, foco: true })).toBe(false);
|
||||
});
|
||||
|
||||
it("ni con la campana silenciada, ni sin permiso, ni un saliente", () => {
|
||||
expect(debeAvisarSistema({ ...base, campana: false })).toBe(false);
|
||||
expect(debeAvisarSistema({ ...base, permiso: "default" })).toBe(false);
|
||||
expect(debeAvisarSistema({ ...base, permiso: "denied" })).toBe(false);
|
||||
expect(debeAvisarSistema({ ...base, direction: "out" })).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("056 — qué dice", () => {
|
||||
it("el texto, en una línea y recortado a 120", () => {
|
||||
expect(cuerpoAviso({ text: "Hola,\n ¿tienen envíos?" })).toBe("Hola, ¿tienen envíos?");
|
||||
const largo = cuerpoAviso({ text: "x".repeat(300) });
|
||||
expect(largo).toHaveLength(AVISO_MAX_CARACTERES);
|
||||
expect(largo.endsWith("…")).toBe(true);
|
||||
});
|
||||
|
||||
it("un adjunto dice qué es, o su pie si trae", () => {
|
||||
expect(cuerpoAviso({ type: "audio", text: null, media: { kind: "audio" } })).toBe("Audio");
|
||||
expect(cuerpoAviso({ type: "image", text: null, media: { kind: "image", caption: "Así lo quiero" } })).toBe(
|
||||
"Así lo quiero"
|
||||
);
|
||||
expect(cuerpoAviso({ type: "location", text: null })).toBe("Ubicación");
|
||||
});
|
||||
|
||||
it("lleva a su conversación, y solo a rutas de la Bandeja", () => {
|
||||
expect(urlDeConversacion("cv_abc-1")).toBe("/inbox?conversation=cv_abc-1");
|
||||
expect(urlDeAvisoSegura("/inbox?conversation=cv_abc-1")).toBe("/inbox?conversation=cv_abc-1");
|
||||
expect(urlDeAvisoSegura("/inbox")).toBe("/inbox");
|
||||
expect(urlDeAvisoSegura("https://otro.sitio/inbox")).toBeNull();
|
||||
expect(urlDeAvisoSegura("//otro.sitio")).toBeNull();
|
||||
expect(urlDeAvisoSegura("/settings")).toBeNull();
|
||||
expect(urlDeAvisoSegura(42)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("056 — reintentos del tiempo real", () => {
|
||||
it("1 s, 2 s, 4 s… con tope de 30 s", () => {
|
||||
expect([0, 1, 2, 3, 4, 5, 6, 10].map(esperaReintento)).toEqual([
|
||||
1000, 2000, 4000, 8000, 16000, 30000, 30000, 30000,
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,244 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
/**
|
||||
* 015 — La carrera del hueco (FR-006).
|
||||
*
|
||||
* Dos confirmaciones simultáneas del mismo instante pasan las dos la
|
||||
* re-validación —entre leer y escribir cabe la otra— y es la BASE quien las
|
||||
* separa, con el índice único parcial. Lo que se fija aquí es la traducción de
|
||||
* ese choque: `23505` ⇒ `slot_taken` CON alternativas frescas, y jamás una
|
||||
* cita creada.
|
||||
*
|
||||
* La carrera de verdad, con dos peticiones concurrentes contra la app viva, la
|
||||
* corre el arnés E2E: esto asegura que cuando ocurra, la respuesta sea útil.
|
||||
*/
|
||||
|
||||
const settings = {
|
||||
weeklyHours: { wed: [{ start: "09:00", end: "18:00" }] },
|
||||
slotMinutes: 30,
|
||||
bufferMinutes: 0,
|
||||
minNoticeHours: 0,
|
||||
maxDaysAhead: 7,
|
||||
timezone: "America/Mexico_City",
|
||||
connector: "enlace-fijo" as const,
|
||||
meetingLink: "https://meet.ejemplo.com/sala",
|
||||
};
|
||||
|
||||
const SLOT = "2026-08-05T15:00:00.000Z";
|
||||
|
||||
const ALTERNATIVES = [
|
||||
{ startUtc: "2026-08-05T15:30:00.000Z", endUtc: "…", label: "mié 5 ago, 09:30" },
|
||||
{ startUtc: "2026-08-05T16:00:00.000Z", endUtc: "…", label: "mié 5 ago, 10:00" },
|
||||
];
|
||||
|
||||
const replaceOffers = vi.fn(async () => {});
|
||||
const clearOffers = vi.fn(async () => {});
|
||||
const moveLeadToStage = vi.fn(async () => ({ ok: true as const }));
|
||||
const createMeeting = vi.fn(async () => ({
|
||||
externalId: null,
|
||||
joinUrl: settings.meetingLink,
|
||||
}));
|
||||
|
||||
vi.mock("@/server/agenda/settings", () => ({
|
||||
getSettings: async () => settings,
|
||||
}));
|
||||
|
||||
vi.mock("@/server/agenda/availability", () => ({
|
||||
// El hueco se ve libre al re-validar: la otra confirmación aún no escribía.
|
||||
findSlot: async () => ({ startUtc: SLOT, endUtc: "…", label: "mié 5 ago, 09:00" }),
|
||||
computeAvailability: async () => ALTERNATIVES,
|
||||
}));
|
||||
|
||||
vi.mock("@/server/agenda/offers", async (importOriginal) => {
|
||||
const original = await importOriginal<typeof import("@/server/agenda/offers")>();
|
||||
return {
|
||||
...original,
|
||||
getOffers: async () => [{ startUtc: SLOT, label: "mié 5 ago, 09:00" }],
|
||||
replaceOffers,
|
||||
clearOffers,
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("@/server/agenda/connectors", () => ({
|
||||
bindConnector: async () => ({
|
||||
id: "enlace-fijo",
|
||||
createMeeting,
|
||||
updateMeeting: async () => {},
|
||||
deleteMeeting: async () => {},
|
||||
testConnection: async () => ({ ok: true }),
|
||||
}),
|
||||
markConnectorAuthError: async () => {},
|
||||
}));
|
||||
|
||||
vi.mock("@/server/leads/stage-history", () => ({ moveLeadToStage }));
|
||||
vi.mock("@/server/events/bus", () => ({ publish: () => {} }));
|
||||
|
||||
/** Cola de resultados para cada `select(...).limit(n)` en orden de llamada. */
|
||||
const selectRows: unknown[][] = [];
|
||||
/** Si tiene algo, el INSERT lo lanza en vez de insertar. */
|
||||
let insertThrows: unknown = null;
|
||||
const inserted: unknown[] = [];
|
||||
|
||||
function chain(rows: unknown[]) {
|
||||
const c: Record<string, unknown> = {};
|
||||
for (const m of ["from", "where", "orderBy", "leftJoin", "innerJoin"]) {
|
||||
c[m] = () => c;
|
||||
}
|
||||
c.limit = () => Promise.resolve(rows);
|
||||
return c;
|
||||
}
|
||||
|
||||
vi.mock("@/lib/db", () => ({
|
||||
getDb: () => ({
|
||||
select: () => chain(selectRows.shift() ?? []),
|
||||
insert: () => ({
|
||||
values: (v: unknown) => ({
|
||||
returning: () => {
|
||||
if (insertThrows) return Promise.reject(insertThrows);
|
||||
inserted.push(v);
|
||||
return Promise.resolve([
|
||||
{
|
||||
...(v as object),
|
||||
scheduledAt: new Date(SLOT),
|
||||
meetingLink: null,
|
||||
linkPending: false,
|
||||
isTest: false,
|
||||
externalRef: null,
|
||||
},
|
||||
]);
|
||||
},
|
||||
}),
|
||||
}),
|
||||
update: () => ({
|
||||
set: (v: unknown) => ({
|
||||
where: () => ({
|
||||
returning: () =>
|
||||
Promise.resolve([
|
||||
{
|
||||
id: "bk_1",
|
||||
organizationId: "org_1",
|
||||
scheduledAt: new Date(SLOT),
|
||||
durationMinutes: 30,
|
||||
isTest: false,
|
||||
connector: "enlace-fijo",
|
||||
notes: null,
|
||||
contactId: "ct_1",
|
||||
...(v as object),
|
||||
},
|
||||
]),
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
schema: {
|
||||
booking: {},
|
||||
conversation: { organizationId: "organizationId", id: "id" },
|
||||
contact: { organizationId: "organizationId", id: "id", name: "name" },
|
||||
lead: { organizationId: "organizationId", contactId: "contactId" },
|
||||
pipelineStage: { organizationId: "organizationId" },
|
||||
offeredSlot: {},
|
||||
},
|
||||
}));
|
||||
|
||||
function primeLookups() {
|
||||
// 1) la conversación, 2) el nombre del contacto, 3) el lead
|
||||
selectRows.push([{ contactId: "ct_1", isTest: false }]);
|
||||
selectRows.push([{ name: "Ana" }]);
|
||||
selectRows.push([{ id: "ld_1" }]);
|
||||
}
|
||||
|
||||
describe("la carrera del hueco", () => {
|
||||
beforeEach(() => {
|
||||
selectRows.length = 0;
|
||||
inserted.length = 0;
|
||||
insertThrows = null;
|
||||
replaceOffers.mockClear();
|
||||
clearOffers.mockClear();
|
||||
});
|
||||
|
||||
it("un 23505 se traduce a slot_taken con alternativas frescas, sin crear la cita", async () => {
|
||||
const { createSessionBooking, BookingError } = await import(
|
||||
"@/server/agenda/service"
|
||||
);
|
||||
primeLookups();
|
||||
insertThrows = { code: "23505" };
|
||||
|
||||
const promise = createSessionBooking({
|
||||
organizationId: "org_1",
|
||||
conversationId: "cv_1",
|
||||
startUtc: SLOT,
|
||||
source: "ai",
|
||||
requireOffer: true,
|
||||
});
|
||||
|
||||
await expect(promise).rejects.toBeInstanceOf(BookingError);
|
||||
await promise.catch((err) => {
|
||||
expect(err.code).toBe("slot_taken");
|
||||
// Con alternativas concretas: sin ellas, la conversación se queda sin
|
||||
// salida y el cliente sin cita.
|
||||
expect(err.slots).toHaveLength(2);
|
||||
expect(err.slots[0].label).toBe("mié 5 ago, 09:30");
|
||||
});
|
||||
|
||||
// Y quedan REGISTRADAS como la nueva oferta: el cliente puede aceptar una
|
||||
// de inmediato y la validación seguirá siendo válida.
|
||||
expect(replaceOffers).toHaveBeenCalledOnce();
|
||||
expect(inserted).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("el 23505 también se reconoce cuando el driver lo envuelve en `cause`", async () => {
|
||||
const { createSessionBooking } = await import("@/server/agenda/service");
|
||||
primeLookups();
|
||||
insertThrows = Object.assign(new Error("insert falló"), {
|
||||
cause: { code: "23505" },
|
||||
});
|
||||
|
||||
await expect(
|
||||
createSessionBooking({
|
||||
organizationId: "org_1",
|
||||
conversationId: "cv_1",
|
||||
startUtc: SLOT,
|
||||
source: "ai",
|
||||
requireOffer: true,
|
||||
})
|
||||
).rejects.toMatchObject({ code: "slot_taken" });
|
||||
});
|
||||
|
||||
it("un error que NO es la carrera se propaga tal cual, sin disfrazarse de slot_taken", async () => {
|
||||
const { createSessionBooking } = await import("@/server/agenda/service");
|
||||
primeLookups();
|
||||
insertThrows = { code: "23503", message: "foreign key" };
|
||||
|
||||
await expect(
|
||||
createSessionBooking({
|
||||
organizationId: "org_1",
|
||||
conversationId: "cv_1",
|
||||
startUtc: SLOT,
|
||||
source: "ai",
|
||||
requireOffer: true,
|
||||
})
|
||||
).rejects.toMatchObject({ code: "23503" });
|
||||
});
|
||||
|
||||
it("un instante que nunca se ofreció se rechaza ANTES de tocar la base", async () => {
|
||||
const { createSessionBooking } = await import("@/server/agenda/service");
|
||||
primeLookups();
|
||||
|
||||
const promise = createSessionBooking({
|
||||
organizationId: "org_1",
|
||||
conversationId: "cv_1",
|
||||
// Libre y válido, pero jamás ofrecido en esta conversación.
|
||||
startUtc: "2026-08-05T20:00:00.000Z",
|
||||
source: "ai",
|
||||
requireOffer: true,
|
||||
});
|
||||
|
||||
await expect(promise).rejects.toMatchObject({ code: "slot_not_offered" });
|
||||
await promise.catch((err) => {
|
||||
// Se devuelve lo que SÍ se ofreció, para que se re-ofrezca en vez de
|
||||
// inventar.
|
||||
expect(err.slots[0].startUtc).toBe(SLOT);
|
||||
});
|
||||
expect(inserted).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,234 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
/**
|
||||
* 215 (raíz) — `GET /api/bookings?from=&to=` de punta a punta hasta la BD
|
||||
* (falsa): el rango se corta a la medianoche del NEGOCIO, pasa por `scoped()`,
|
||||
* ya no se queda en las últimas 200 (fallo 4), avisa si toca el tope de
|
||||
* seguridad, y SIN parámetros responde exactamente lo de siempre, que es lo
|
||||
* que lee el guion E2E de 015.
|
||||
*/
|
||||
|
||||
const SETTINGS = {
|
||||
weeklyHours: { mon: [{ start: "09:00", end: "18:00" }] },
|
||||
slotMinutes: 30,
|
||||
bufferMinutes: 0,
|
||||
minNoticeHours: 0,
|
||||
maxDaysAhead: 14,
|
||||
timezone: "America/Mexico_City",
|
||||
connector: "enlace-fijo" as const,
|
||||
meetingLink: "https://meet.ejemplo.com/sala",
|
||||
};
|
||||
|
||||
type Call = { method: string; args: unknown[] };
|
||||
const state = vi.hoisted(() => ({
|
||||
agendaOn: true,
|
||||
calls: [] as { method: string; args: unknown[] }[],
|
||||
rows: [] as unknown[],
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/auth/session", () => ({
|
||||
UnauthorizedError: class UnauthorizedError extends Error {},
|
||||
requireSession: async () => ({ userId: "usr_1", organizationId: "org_a", role: "owner" }),
|
||||
getSessionOrNull: async () => ({ userId: "usr_1", organizationId: "org_a", role: "owner" }),
|
||||
}));
|
||||
|
||||
vi.mock("@/server/agenda/flag", async (importOriginal) => {
|
||||
const original = await importOriginal<typeof import("@/server/agenda/flag")>();
|
||||
return { ...original, agendaEnabled: () => state.agendaOn };
|
||||
});
|
||||
|
||||
vi.mock("@/server/agenda/settings", async (importOriginal) => {
|
||||
const original = await importOriginal<typeof import("@/server/agenda/settings")>();
|
||||
return { ...original, getSettings: async () => SETTINGS };
|
||||
});
|
||||
|
||||
// El tenant y los límites del rango, legibles en la prueba.
|
||||
vi.mock("@/lib/db/tenant", () => ({
|
||||
scoped: (_col: unknown, organizationId: string, ...conditions: unknown[]) => ({
|
||||
organizationId,
|
||||
conditions,
|
||||
}),
|
||||
}));
|
||||
vi.mock("drizzle-orm", async (importOriginal) => {
|
||||
const original = await importOriginal<typeof import("drizzle-orm")>();
|
||||
return {
|
||||
...original,
|
||||
gte: (_col: unknown, value: unknown) => ({ op: "gte", value }),
|
||||
lt: (_col: unknown, value: unknown) => ({ op: "lt", value }),
|
||||
asc: () => "asc",
|
||||
desc: () => "desc",
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("@/lib/db", async (importOriginal) => {
|
||||
const original = await importOriginal<typeof import("@/lib/db")>();
|
||||
const builder = () => {
|
||||
const b: Record<string, (...args: unknown[]) => unknown> = {};
|
||||
for (const m of ["select", "from", "leftJoin", "where", "orderBy"]) {
|
||||
b[m] = (...args: unknown[]) => {
|
||||
state.calls.push({ method: m, args });
|
||||
return b;
|
||||
};
|
||||
}
|
||||
b.limit = (n: unknown) => {
|
||||
state.calls.push({ method: "limit", args: [n] });
|
||||
return Promise.resolve(state.rows.slice(0, Number(n)));
|
||||
};
|
||||
return b;
|
||||
};
|
||||
return { ...original, getDb: () => builder() };
|
||||
});
|
||||
|
||||
const { GET } = await import("@/app/api/bookings/route");
|
||||
const { RANGE_LIMIT } = await import("@/server/agenda/queries");
|
||||
|
||||
function row(id: string, startIso: string, durationMinutes = 30) {
|
||||
return {
|
||||
booking: {
|
||||
id,
|
||||
organizationId: "org_a",
|
||||
kind: "session",
|
||||
status: "agendada",
|
||||
source: "ai",
|
||||
scheduledAt: new Date(startIso),
|
||||
durationMinutes,
|
||||
contactId: "ct_1",
|
||||
conversationId: "cv_1",
|
||||
connector: "enlace-fijo",
|
||||
meetingLink: "https://meet.ejemplo.com/sala",
|
||||
linkPending: false,
|
||||
isTest: false,
|
||||
notes: null,
|
||||
},
|
||||
contactId: "ct_1",
|
||||
contactName: "María",
|
||||
};
|
||||
}
|
||||
|
||||
const call = (method: string): Call | undefined => state.calls.find((c) => c.method === method);
|
||||
|
||||
async function get(query = "") {
|
||||
const res = await GET(new Request(`http://localhost/api/bookings${query}`));
|
||||
const body = (await res.json().catch(() => ({}))) as Record<string, unknown>;
|
||||
return { status: res.status, body };
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
state.agendaOn = true;
|
||||
state.calls = [];
|
||||
state.rows = [];
|
||||
});
|
||||
|
||||
describe("GET /api/bookings sin parámetros: la respuesta de siempre", () => {
|
||||
it("solo `bookings`, las últimas 200 en orden descendente", async () => {
|
||||
state.rows = Array.from({ length: 250 }, (_, i) =>
|
||||
row(`bk_${i}`, new Date(Date.UTC(2026, 8, 21, 15) - i * 3_600_000).toISOString())
|
||||
);
|
||||
const { status, body } = await get();
|
||||
expect(status).toBe(200);
|
||||
expect(Object.keys(body)).toEqual(["bookings"]);
|
||||
expect(body.bookings).toHaveLength(200);
|
||||
expect(call("limit")?.args).toEqual([200]);
|
||||
expect(call("orderBy")?.args).toEqual(["desc"]);
|
||||
const where = call("where")?.args[0] as { organizationId: string; conditions: unknown[] };
|
||||
expect(where).toEqual({ organizationId: "org_a", conditions: [] });
|
||||
});
|
||||
|
||||
it("cada cita trae la hora en la zona del negocio, como antes", async () => {
|
||||
state.rows = [row("bk_1", "2026-09-24T21:00:00.000Z")];
|
||||
const { body } = await get();
|
||||
const [b] = body.bookings as Record<string, unknown>[];
|
||||
expect(b).toMatchObject({
|
||||
id: "bk_1",
|
||||
scheduledAtUtc: "2026-09-24T21:00:00.000Z",
|
||||
time: "15:00",
|
||||
contact: { id: "ct_1", name: "María" },
|
||||
isTest: false,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("GET /api/bookings?from=&to=: el rango del calendario", () => {
|
||||
it("corta a la medianoche del negocio (mirando 24 h atrás) y pasa por el tenant", async () => {
|
||||
const { status, body } = await get("?from=2026-09-21&to=2026-09-27");
|
||||
expect(status).toBe(200);
|
||||
expect(body).toMatchObject({
|
||||
bookings: [],
|
||||
timezone: "America/Mexico_City",
|
||||
weeklyHours: SETTINGS.weeklyHours,
|
||||
range: { from: "2026-09-21", to: "2026-09-27" },
|
||||
truncated: false,
|
||||
});
|
||||
const where = call("where")?.args[0] as {
|
||||
organizationId: string;
|
||||
conditions: { op: string; value: Date }[];
|
||||
};
|
||||
expect(where.organizationId).toBe("org_a");
|
||||
// 00:00 del lunes 21 en CDMX = 06:00Z; se mira desde 24 h antes.
|
||||
expect(where.conditions[0]).toEqual({ op: "gte", value: new Date("2026-09-20T06:00:00.000Z") });
|
||||
// Hasta la medianoche del lunes 28 en CDMX, exclusiva.
|
||||
expect(where.conditions[1]).toEqual({ op: "lt", value: new Date("2026-09-28T06:00:00.000Z") });
|
||||
expect(call("orderBy")?.args).toEqual(["asc"]);
|
||||
});
|
||||
|
||||
it("fallo 4: más de 200 citas en el rango llegan todas", async () => {
|
||||
state.rows = Array.from({ length: 450 }, (_, i) =>
|
||||
row(`bk_${i}`, new Date(Date.UTC(2026, 8, 21, 14) + i * 30 * 60_000).toISOString())
|
||||
);
|
||||
const { body } = await get("?from=2026-09-21&to=2026-10-31");
|
||||
expect(body.bookings).toHaveLength(450);
|
||||
expect(body.truncated).toBe(false);
|
||||
expect(call("limit")?.args).toEqual([RANGE_LIMIT]);
|
||||
});
|
||||
|
||||
it("si toca el tope de seguridad lo dice en vez de esconder citas", async () => {
|
||||
state.rows = Array.from({ length: RANGE_LIMIT + 5 }, (_, i) =>
|
||||
row(`bk_${i}`, new Date(Date.UTC(2026, 8, 21, 14) + i * 15 * 60_000).toISOString(), 15)
|
||||
);
|
||||
const { body } = await get("?from=2026-09-21&to=2026-12-21");
|
||||
expect(body.bookings).toHaveLength(RANGE_LIMIT);
|
||||
expect(body.truncated).toBe(true);
|
||||
});
|
||||
|
||||
it("de lo que empezó el día anterior, solo lo que sigue ocupando el rango", async () => {
|
||||
state.rows = [
|
||||
// Terminó el domingo 20 a las 23:00 de CDMX: no toca el lunes.
|
||||
row("bk_ayer", "2026-09-21T04:00:00.000Z", 60),
|
||||
// Bloqueo nocturno del domingo 22:00 a 02:00 del lunes: sí lo toca.
|
||||
row("bk_nocturno", "2026-09-21T04:00:00.000Z", 240),
|
||||
row("bk_lunes", "2026-09-21T16:00:00.000Z"),
|
||||
];
|
||||
const { body } = await get("?from=2026-09-21&to=2026-09-21");
|
||||
expect((body.bookings as { id: string }[]).map((b) => b.id)).toEqual([
|
||||
"bk_nocturno",
|
||||
"bk_lunes",
|
||||
]);
|
||||
});
|
||||
|
||||
it.each([
|
||||
["solo from", "?from=2026-09-21"],
|
||||
["solo to", "?to=2026-09-21"],
|
||||
["fecha que no existe", "?from=2026-02-31&to=2026-03-02"],
|
||||
["formato raro", "?from=21-09-2026&to=2026-09-27"],
|
||||
["al revés", "?from=2026-09-27&to=2026-09-21"],
|
||||
["93 días", "?from=2026-09-01&to=2026-12-02"],
|
||||
])("rango inválido (%s) → 422 invalid_range sin tocar la BD", async (_name, query) => {
|
||||
const { status, body } = await get(query);
|
||||
expect(status).toBe(422);
|
||||
expect((body.error as { code: string }).code).toBe("invalid_range");
|
||||
expect(state.calls).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("92 días exactos sí caben", async () => {
|
||||
const { status } = await get("?from=2026-09-01&to=2026-12-01");
|
||||
expect(status).toBe(200);
|
||||
});
|
||||
|
||||
it("con la agenda apagada es 404, aunque el rango venga mal", async () => {
|
||||
state.agendaOn = false;
|
||||
expect((await get("?from=2026-09-21&to=2026-09-27")).status).toBe(404);
|
||||
expect((await get("?from=mal")).status).toBe(404);
|
||||
expect((await get()).status).toBe(404);
|
||||
expect(state.calls).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,78 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
CADUCIDAD_MS,
|
||||
claveBorrador,
|
||||
guardarEn,
|
||||
leerDe,
|
||||
limpiarEn,
|
||||
type Almacen,
|
||||
} from "@/lib/borradores";
|
||||
|
||||
/** 051 — Borrador por conversación: guardar, leer, caducar y limpiar. */
|
||||
|
||||
function memoria(): Almacen & { datos: Map<string, string> } {
|
||||
const datos = new Map<string, string>();
|
||||
return {
|
||||
datos,
|
||||
getItem: (k) => datos.get(k) ?? null,
|
||||
setItem: (k, v) => void datos.set(k, v),
|
||||
removeItem: (k) => void datos.delete(k),
|
||||
key: (i) => [...datos.keys()][i] ?? null,
|
||||
get length() {
|
||||
return datos.size;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
describe("guardar y leer", () => {
|
||||
it("lo escrito en una conversación vuelve en esa, y no en otra", () => {
|
||||
const a = memoria();
|
||||
guardarEn(a, "responder", "cv_a", "Te confirmo mañana");
|
||||
expect(leerDe(a, "responder", "cv_a")).toBe("Te confirmo mañana");
|
||||
expect(leerDe(a, "responder", "cv_b")).toBe("");
|
||||
});
|
||||
|
||||
it("la nota interna lleva su propio borrador", () => {
|
||||
const a = memoria();
|
||||
guardarEn(a, "responder", "cv_a", "para el cliente");
|
||||
guardarEn(a, "nota", "cv_a", "para el equipo");
|
||||
expect(leerDe(a, "responder", "cv_a")).toBe("para el cliente");
|
||||
expect(leerDe(a, "nota", "cv_a")).toBe("para el equipo");
|
||||
});
|
||||
|
||||
it("vaciar la caja (o solo espacios) borra el borrador", () => {
|
||||
const a = memoria();
|
||||
guardarEn(a, "responder", "cv_a", "algo");
|
||||
guardarEn(a, "responder", "cv_a", " ");
|
||||
expect(a.datos.has(claveBorrador("responder", "cv_a"))).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("caducidad", () => {
|
||||
it("un borrador de más de 7 días no vuelve y se elimina", () => {
|
||||
const a = memoria();
|
||||
const hace = 1_000_000;
|
||||
guardarEn(a, "responder", "cv_a", "viejo", hace);
|
||||
expect(leerDe(a, "responder", "cv_a", hace + CADUCIDAD_MS - 1)).toBe("viejo");
|
||||
expect(leerDe(a, "responder", "cv_a", hace + CADUCIDAD_MS + 1)).toBe("");
|
||||
expect(a.datos.size).toBe(0);
|
||||
});
|
||||
|
||||
it("un valor roto se descarta sin lanzar", () => {
|
||||
const a = memoria();
|
||||
a.setItem(claveBorrador("responder", "cv_a"), "{no es json");
|
||||
expect(leerDe(a, "responder", "cv_a")).toBe("");
|
||||
expect(a.datos.size).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe("cerrar sesión", () => {
|
||||
it("borra todos los borradores y nada más", () => {
|
||||
const a = memoria();
|
||||
guardarEn(a, "responder", "cv_a", "uno");
|
||||
guardarEn(a, "nota", "cv_b", "dos");
|
||||
a.setItem("vocero.sonido", "on");
|
||||
expect(limpiarEn(a)).toBe(2);
|
||||
expect([...a.datos.keys()]).toEqual(["vocero.sonido"]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,245 @@
|
||||
import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import type { CalendarSettings } from "@/server/agenda/settings";
|
||||
|
||||
/**
|
||||
* `GET /api/bot/availability` con `date` (R10): lo que la ruta REGISTRA como
|
||||
* oferta y lo que contesta. El motor de huecos es el de verdad; solo se
|
||||
* sustituyen la BD, la llave y el reloj.
|
||||
*
|
||||
* El cerebro externo (Nea) lee `query.date` para saber si el CRM consultó el
|
||||
* día que pidió; si no vuelve, no afirma nada de ese día. Y solo puede
|
||||
* reservar lo que quedó registrado aquí (`POST /api/bot/bookings` compara por
|
||||
* epoch exacto contra la oferta vigente).
|
||||
*/
|
||||
|
||||
const h = vi.hoisted(() => ({
|
||||
replaceOffers: vi.fn(async (..._args: unknown[]) => {}),
|
||||
computeCalls: [] as Array<{ fromISO?: string; toISO?: string }>,
|
||||
convRows: [{ id: "cv_1" }] as unknown[],
|
||||
}));
|
||||
|
||||
const SETTINGS: CalendarSettings = {
|
||||
weeklyHours: {
|
||||
mon: [{ start: "10:00", end: "19:00" }],
|
||||
tue: [{ start: "10:00", end: "19:00" }],
|
||||
wed: [{ start: "10:00", end: "19:00" }],
|
||||
thu: [{ start: "10:00", end: "19:00" }],
|
||||
fri: [{ start: "10:00", end: "19:00" }],
|
||||
},
|
||||
slotMinutes: 30,
|
||||
bufferMinutes: 0,
|
||||
minNoticeHours: 0,
|
||||
maxDaysAhead: 7,
|
||||
timezone: "America/Mexico_City",
|
||||
connector: "enlace-fijo",
|
||||
meetingLink: null,
|
||||
};
|
||||
|
||||
// Lunes 21 sep 2026, 09:00 CDMX.
|
||||
const NOW = new Date("2026-09-21T15:00:00.000Z");
|
||||
|
||||
vi.mock("@/server/agenda/flag", () => ({
|
||||
agendaEnabled: () => true,
|
||||
agendaDisabledResponse: () => new Response(null, { status: 404 }),
|
||||
}));
|
||||
|
||||
vi.mock("@/server/bot/auth", () => ({
|
||||
requireBotKey: () => null,
|
||||
resolveInstanceOrg: async () => "org_1",
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/db", async () => {
|
||||
const schema = await import("@/lib/db/schema");
|
||||
const chain = {
|
||||
select: () => chain,
|
||||
from: () => chain,
|
||||
where: () => chain,
|
||||
limit: async () => h.convRows,
|
||||
};
|
||||
return { schema, getDb: () => chain };
|
||||
});
|
||||
|
||||
vi.mock("@/server/agenda/settings", async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import("@/server/agenda/settings")>()),
|
||||
getSettings: async () => SETTINGS,
|
||||
}));
|
||||
|
||||
vi.mock("@/server/agenda/availability", async (importOriginal) => {
|
||||
const real = await importOriginal<typeof import("@/server/agenda/availability")>();
|
||||
const { addDaysISO, todayInTz } = await import("@/lib/time/slots");
|
||||
return {
|
||||
...real,
|
||||
// El motor real sin nada ocupado: horario semanal − aviso mínimo.
|
||||
computeAvailability: async (
|
||||
_org: string,
|
||||
opts: { fromISO?: string; toISO?: string; now: Date; settings: CalendarSettings }
|
||||
) => {
|
||||
h.computeCalls.push({ fromISO: opts.fromISO, toISO: opts.toISO });
|
||||
const from = opts.fromISO ?? todayInTz(opts.now, SETTINGS.timezone);
|
||||
const to = opts.toISO ?? addDaysISO(from, SETTINGS.maxDaysAhead);
|
||||
return real.filterFreeSlots(real.buildCandidateSlots(SETTINGS, from, to), [], {
|
||||
now: opts.now,
|
||||
minNoticeHours: SETTINGS.minNoticeHours,
|
||||
timezone: SETTINGS.timezone,
|
||||
});
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("@/server/agenda/offers", async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import("@/server/agenda/offers")>()),
|
||||
replaceOffers: h.replaceOffers,
|
||||
}));
|
||||
|
||||
let GET: typeof import("@/app/api/bot/availability/route").GET;
|
||||
|
||||
// La ruta se importa una vez y fuera de los casos: su primer import carga
|
||||
// medio servidor y, con la máquina ocupada, se comía los 5 s del primer caso
|
||||
// (y el segundo caía en cascada con la oferta a medio registrar).
|
||||
beforeAll(async () => {
|
||||
({ GET } = await import("@/app/api/bot/availability/route"));
|
||||
}, 60_000);
|
||||
|
||||
async function pedir(qs: string) {
|
||||
const res = await GET(new Request(`http://crm.test/api/bot/availability?${qs}`));
|
||||
let json: Record<string, unknown> | null = null;
|
||||
try {
|
||||
json = (await res.json()) as Record<string, unknown>;
|
||||
} catch {}
|
||||
return { status: res.status, json };
|
||||
}
|
||||
|
||||
type Slot = { startUtc: string; label: string; dayIso: string; time: string };
|
||||
const ofertaRegistrada = () =>
|
||||
(h.replaceOffers.mock.calls[0]?.[2] ?? []) as { startUtc: string; label: string }[];
|
||||
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers({ toFake: ["Date"] });
|
||||
vi.setSystemTime(NOW);
|
||||
h.replaceOffers.mockClear();
|
||||
h.computeCalls.length = 0;
|
||||
h.convRows = [{ id: "cv_1" }];
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
const COMO_NEA = "conversationId=cv_1&limit=12&perDay=3&days=5";
|
||||
|
||||
describe("con date: la tarde de mañana, y reservable", () => {
|
||||
it("devuelve el día completo con query.date y lo registra como oferta", async () => {
|
||||
const { status, json } = await pedir(`${COMO_NEA}&date=2026-09-22`);
|
||||
expect(status).toBe(200);
|
||||
const slots = json!.slots as Slot[];
|
||||
expect(slots).toHaveLength(18);
|
||||
expect(slots.map((s) => s.time)).toEqual(
|
||||
expect.arrayContaining(["12:00", "15:00", "18:30"])
|
||||
);
|
||||
expect(json!.query).toEqual({
|
||||
date: "2026-09-22",
|
||||
status: "available",
|
||||
coveredUntil: "2026-09-22",
|
||||
horizonEnd: "2026-09-28",
|
||||
perDay: null,
|
||||
});
|
||||
expect(json!.diasConAgenda).toEqual(["2026-09-22"]);
|
||||
// Solo se calculó ese día.
|
||||
expect(h.computeCalls).toEqual([{ fromISO: "2026-09-22", toISO: "2026-09-22" }]);
|
||||
// Lo registrado es EXACTAMENTE lo devuelto: cualquiera de esas horas se
|
||||
// puede reservar después.
|
||||
expect(h.replaceOffers).toHaveBeenCalledOnce();
|
||||
expect(h.replaceOffers.mock.calls[0]!.slice(0, 2)).toEqual(["org_1", "cv_1"]);
|
||||
expect(ofertaRegistrada()).toEqual(
|
||||
slots.map((s) => ({ startUtc: s.startUtc, label: s.label }))
|
||||
);
|
||||
});
|
||||
|
||||
it("un día cerrado dice por qué y NO borra la oferta vigente", async () => {
|
||||
const { status, json } = await pedir(`${COMO_NEA}&date=2026-09-26`);
|
||||
expect(status).toBe(200);
|
||||
expect(json!.slots).toEqual([]);
|
||||
expect(json!.query).toMatchObject({ date: "2026-09-26", status: "closed" });
|
||||
expect(h.replaceOffers).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each([
|
||||
["2026-09-20", "past"],
|
||||
["2026-09-29", "beyond_horizon"],
|
||||
])("%s → %s, sin calcular nada ni tocar la oferta", async (date, estado) => {
|
||||
const { status, json } = await pedir(`${COMO_NEA}&date=${date}`);
|
||||
expect(status).toBe(200);
|
||||
expect(json!.query).toMatchObject({ date, status: estado, horizonEnd: "2026-09-28" });
|
||||
expect(h.computeCalls).toEqual([]);
|
||||
expect(h.replaceOffers).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe("fecha inválida", () => {
|
||||
it.each(["2026-02-31", "2026-13-01", "22-09-2026", "2026-9-22", "mañana", "2026-09-22T10:00"])(
|
||||
"%s → 422 invalid_body, nunca un 500 ni el reparto callado",
|
||||
async (date) => {
|
||||
const { status, json } = await pedir(`${COMO_NEA}&date=${encodeURIComponent(date)}`);
|
||||
expect(status).toBe(422);
|
||||
expect((json!.error as { code: string }).code).toBe("invalid_body");
|
||||
expect(h.computeCalls).toEqual([]);
|
||||
expect(h.replaceOffers).not.toHaveBeenCalled();
|
||||
}
|
||||
);
|
||||
|
||||
it("date vacía cuenta como ausente: el reparto de siempre", async () => {
|
||||
const { status, json } = await pedir(`${COMO_NEA}&date=`);
|
||||
expect(status).toBe(200);
|
||||
expect((json!.query as { date: unknown }).date).toBeNull();
|
||||
});
|
||||
|
||||
it("sin conversationId sigue siendo 422 (la sonda de Nea depende de eso)", async () => {
|
||||
const { status } = await pedir("date=2026-09-22");
|
||||
expect(status).toBe(422);
|
||||
});
|
||||
|
||||
it("una conversación que no es de esta instancia → 404, sin oferta", async () => {
|
||||
h.convRows = [];
|
||||
const { status } = await pedir(`${COMO_NEA}&date=2026-09-22`);
|
||||
expect(status).toBe(404);
|
||||
expect(h.replaceOffers).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe("sin date: la misma forma de siempre, más query", () => {
|
||||
it("slots + diasConAgenda como antes, y la cobertura en query", async () => {
|
||||
const { status, json } = await pedir(COMO_NEA);
|
||||
expect(status).toBe(200);
|
||||
expect(Object.keys(json!).sort()).toEqual(["diasConAgenda", "query", "slots"]);
|
||||
const slots = json!.slots as Slot[];
|
||||
expect(slots).toHaveLength(12);
|
||||
expect(Object.keys(slots[0]!).sort()).toEqual(
|
||||
["dayIso", "dayLabel", "endUtc", "label", "startUtc", "time"]
|
||||
);
|
||||
expect(slots.filter((s) => s.dayIso === "2026-09-22").map((s) => s.time)).toEqual([
|
||||
"10:00",
|
||||
"10:30",
|
||||
"11:00",
|
||||
]);
|
||||
expect(json!.diasConAgenda).toEqual([
|
||||
"2026-09-21",
|
||||
"2026-09-22",
|
||||
"2026-09-23",
|
||||
"2026-09-24",
|
||||
]);
|
||||
expect(json!.query).toEqual({
|
||||
date: null,
|
||||
status: null,
|
||||
coveredUntil: "2026-09-24",
|
||||
horizonEnd: "2026-09-28",
|
||||
perDay: 3,
|
||||
});
|
||||
expect(ofertaRegistrada()).toHaveLength(12);
|
||||
});
|
||||
|
||||
it("sin limit/perDay/days aplica los defaults del contrato (12/3/5), no 1", async () => {
|
||||
const { json } = await pedir("conversationId=cv_1");
|
||||
expect(json!.slots as Slot[]).toHaveLength(12);
|
||||
expect(json!.query).toMatchObject({ perDay: 3, coveredUntil: "2026-09-24" });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,99 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import type { SQL } from "drizzle-orm";
|
||||
import { PgDialect } from "drizzle-orm/pg-core";
|
||||
import { findContactByIdentity, parseIdentity } from "@/server/inbox/identity";
|
||||
|
||||
/**
|
||||
* R11 — El cerebro externo pregunta por `bsuid:<id>` y el contacto escribió
|
||||
* primero CON teléfono (su `wa_identity` es el teléfono, de por vida, y el
|
||||
* BSUID quedó en `wa_user_id`). La ingesta ya lo reconciliaba; el contexto
|
||||
* del bot no, y respondía 404: el cliente se quedaba sin respuesta.
|
||||
*/
|
||||
|
||||
const { getDb } = vi.hoisted(() => ({ getDb: vi.fn() }));
|
||||
|
||||
vi.mock("@/lib/db", async (importOriginal) => {
|
||||
const original = await importOriginal<typeof import("@/lib/db")>();
|
||||
return { ...original, getDb };
|
||||
});
|
||||
|
||||
/** Una base cuyos `select` devuelven `resultados` en orden, y que guarda cada WHERE. */
|
||||
function base(resultados: unknown[][]) {
|
||||
const wheres: SQL[] = [];
|
||||
getDb.mockReturnValue({
|
||||
select: () => {
|
||||
const rows = resultados.shift() ?? [];
|
||||
const c: Record<string, unknown> = {};
|
||||
c.from = () => c;
|
||||
c.where = (w: SQL) => {
|
||||
wheres.push(w);
|
||||
return c;
|
||||
};
|
||||
c.orderBy = () => c;
|
||||
c.limit = () => Promise.resolve(rows);
|
||||
return c;
|
||||
},
|
||||
});
|
||||
return wheres;
|
||||
}
|
||||
|
||||
const sqlDe = (w: SQL) => new PgDialect().sqlToQuery(w);
|
||||
|
||||
const CONTACTO = { id: "ct_tel", waIdentity: "525550001234", waUserId: "MX.bsu.1" };
|
||||
|
||||
describe("parseIdentity (la identidad del cerebro, leída como la ingesta)", () => {
|
||||
it("bsuid:<id> es un BSUID sin teléfono", () => {
|
||||
expect(parseIdentity("bsuid:MX.bsu.1")).toEqual({
|
||||
identity: "bsuid:MX.bsu.1",
|
||||
phone: null,
|
||||
waUserId: "MX.bsu.1",
|
||||
profileName: null,
|
||||
});
|
||||
});
|
||||
|
||||
it("un teléfono se normaliza igual que el `from` del webhook (521 → 52)", () => {
|
||||
expect(parseIdentity("5215550001234")).toMatchObject({
|
||||
identity: "525550001234",
|
||||
phone: "525550001234",
|
||||
waUserId: null,
|
||||
});
|
||||
});
|
||||
|
||||
it("Instagram, Messenger y un BSUID vacío no se reconcilian", () => {
|
||||
expect(parseIdentity("ig:123")).toBeNull();
|
||||
expect(parseIdentity("fb:456")).toBeNull();
|
||||
expect(parseIdentity("bsuid:")).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("findContactByIdentity", () => {
|
||||
beforeEach(() => getDb.mockReset());
|
||||
|
||||
it("la llave exacta gana y no hay segunda consulta", async () => {
|
||||
const wheres = base([[CONTACTO]]);
|
||||
await expect(findContactByIdentity("org_1", "525550001234")).resolves.toBe(CONTACTO);
|
||||
expect(wheres).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("bsuid sin contacto propio → el de teléfono con ese BSUID guardado", async () => {
|
||||
const wheres = base([[], [CONTACTO]]);
|
||||
await expect(findContactByIdentity("org_1", "bsuid:MX.bsu.1")).resolves.toBe(CONTACTO);
|
||||
expect(wheres).toHaveLength(2);
|
||||
// La segunda es la regla de la ingesta: por wa_user_id, solo WhatsApp.
|
||||
const q = sqlDe(wheres[1]!);
|
||||
expect(q.sql).toContain('"wa_user_id" = ');
|
||||
expect(q.sql).toContain('"channel" = ');
|
||||
expect(q.params).toEqual(expect.arrayContaining(["org_1", "whatsapp", "MX.bsu.1"]));
|
||||
});
|
||||
|
||||
it("nadie con ese BSUID → undefined (el endpoint responde 404)", async () => {
|
||||
base([[], []]);
|
||||
await expect(findContactByIdentity("org_1", "bsuid:nadie")).resolves.toBeUndefined();
|
||||
});
|
||||
|
||||
it("una identidad de Instagram sin llave exacta no cae a la reconciliación", async () => {
|
||||
const wheres = base([[]]);
|
||||
await expect(findContactByIdentity("org_1", "ig:123")).resolves.toBeUndefined();
|
||||
expect(wheres).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,157 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import {
|
||||
etapasSiguientes,
|
||||
moverEtapaPorElCerebro,
|
||||
resolverEtapa,
|
||||
type EtapaDelPipeline,
|
||||
} from "@/server/bot/stage";
|
||||
|
||||
/** 038 — El cerebro mueve la etapa: reglas puras y decisión contra la BD. */
|
||||
|
||||
const dbState = vi.hoisted(() => ({ queue: [] as unknown[][] }));
|
||||
const movimientos = vi.hoisted(() => ({ llamadas: [] as unknown[], changed: true }));
|
||||
|
||||
vi.mock("@/lib/db", async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import("@/lib/db")>();
|
||||
const builder: Record<string, unknown> = {};
|
||||
for (const m of ["select", "from", "where", "limit", "orderBy"]) {
|
||||
builder[m] = () => builder;
|
||||
}
|
||||
(builder as { then: unknown }).then = (resolve: (v: unknown) => void) =>
|
||||
resolve(dbState.queue.shift() ?? []);
|
||||
return { ...actual, getDb: () => builder };
|
||||
});
|
||||
|
||||
vi.mock("@/server/leads/stage-history", () => ({
|
||||
moveLeadToStage: async (input: { leadId: string; toStageId: string }) => {
|
||||
movimientos.llamadas.push(input);
|
||||
return {
|
||||
ok: true,
|
||||
changed: movimientos.changed,
|
||||
lead: { id: input.leadId, contactId: "ct_1", stageId: input.toStageId },
|
||||
};
|
||||
},
|
||||
}));
|
||||
|
||||
const PIPELINE: EtapaDelPipeline[] = [
|
||||
{ id: "st_nuevo", name: "Nuevo", position: 0, kind: "open" },
|
||||
{ id: "st_calif", name: "Calificado", position: 1, kind: "open" },
|
||||
{ id: "st_cita", name: "Cita agendada", position: 2, kind: "open" },
|
||||
{ id: "st_ganado", name: "Ganado", position: 3, kind: "won" },
|
||||
{ id: "st_perdido", name: "Perdido", position: 4, kind: "lost" },
|
||||
];
|
||||
|
||||
describe("etapasSiguientes", () => {
|
||||
it("las abiertas después de la actual, en orden, aunque lleguen revueltas", () => {
|
||||
const revuelto = [...PIPELINE].reverse();
|
||||
expect(etapasSiguientes(revuelto, "st_nuevo").map((s) => s.id)).toEqual(["st_calif", "st_cita"]);
|
||||
});
|
||||
|
||||
it("vacía en la última abierta, en una de cierre o con una etapa que no existe", () => {
|
||||
expect(etapasSiguientes(PIPELINE, "st_cita")).toEqual([]);
|
||||
expect(etapasSiguientes(PIPELINE, "st_ganado")).toEqual([]);
|
||||
expect(etapasSiguientes(PIPELINE, "st_x")).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolverEtapa", () => {
|
||||
it("por id, por nombre exacto y sin mayúsculas ni espacios de los lados", () => {
|
||||
expect(resolverEtapa("st_cita", PIPELINE)?.id).toBe("st_cita");
|
||||
expect(resolverEtapa("Calificado", PIPELINE)?.id).toBe("st_calif");
|
||||
expect(resolverEtapa(" cita AGENDADA ", PIPELINE)?.id).toBe("st_cita");
|
||||
});
|
||||
|
||||
it("null si no existe o viene vacía", () => {
|
||||
expect(resolverEtapa("Propuesta", PIPELINE)).toBeNull();
|
||||
expect(resolverEtapa(" ", PIPELINE)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("moverEtapaPorElCerebro", () => {
|
||||
const conv = { id: "cv_1", contactId: "ct_1", aiEnabled: true, handoffAt: null };
|
||||
const mover = (stage: string) =>
|
||||
moverEtapaPorElCerebro({ organizationId: "org_1", conversationId: "cv_1", stage });
|
||||
|
||||
beforeEach(() => {
|
||||
dbState.queue = [];
|
||||
movimientos.llamadas = [];
|
||||
movimientos.changed = true;
|
||||
});
|
||||
|
||||
/** conversación, perfil, lead, etapas — el orden en que se consultan. */
|
||||
function base(opts: { tools?: string[] | null; leadStage?: string | null; conversacion?: object } = {}) {
|
||||
dbState.queue.push(
|
||||
[{ ...conv, ...(opts.conversacion ?? {}) }],
|
||||
[{ tools: opts.tools ?? null }],
|
||||
opts.leadStage === null ? [] : [{ id: "ld_1", stageId: opts.leadStage ?? "st_nuevo" }],
|
||||
PIPELINE
|
||||
);
|
||||
}
|
||||
|
||||
it("adelante a una abierta: mueve por la puerta única como bot", async () => {
|
||||
base();
|
||||
const res = await mover("calificado");
|
||||
expect(res).toEqual({
|
||||
ok: true,
|
||||
changed: true,
|
||||
lead: { id: "ld_1", stageName: "Calificado" },
|
||||
conversationId: "cv_1",
|
||||
});
|
||||
expect(movimientos.llamadas).toEqual([
|
||||
expect.objectContaining({ leadId: "ld_1", toStageId: "st_calif", source: "bot" }),
|
||||
]);
|
||||
});
|
||||
|
||||
it("la etapa actual es un reintento: pasa a la puerta, que contesta changed false", async () => {
|
||||
base({ leadStage: "st_calif" });
|
||||
movimientos.changed = false;
|
||||
const res = await mover("Calificado");
|
||||
expect(res.ok && res.changed).toBe(false);
|
||||
});
|
||||
|
||||
it.each([
|
||||
["hacia atrás", "Nuevo"],
|
||||
["a ganada", "Ganado"],
|
||||
["a perdida", "Perdido"],
|
||||
])("%s: 409 etapa_no_permitida con las válidas en el mensaje", async (_c, etapa) => {
|
||||
base({ leadStage: "st_calif" });
|
||||
const res = await mover(etapa);
|
||||
expect(res).toMatchObject({ ok: false, status: 409, code: "etapa_no_permitida" });
|
||||
expect(!res.ok && res.message).toContain("Cita agendada");
|
||||
expect(movimientos.llamadas).toEqual([]);
|
||||
});
|
||||
|
||||
it("una etapa que no existe: 422 etapa_desconocida", async () => {
|
||||
base();
|
||||
const res = await mover("Propuesta");
|
||||
expect(res).toMatchObject({ ok: false, status: 422, code: "etapa_desconocida" });
|
||||
expect(!res.ok && res.message).toContain("Calificado, Cita agendada");
|
||||
});
|
||||
|
||||
it("con la herramienta apagada: 409 herramienta_apagada y no mueve", async () => {
|
||||
base({ tools: ["ficha", "salida"] });
|
||||
const res = await mover("Calificado");
|
||||
expect(res).toMatchObject({ ok: false, status: 409, code: "herramienta_apagada" });
|
||||
expect(movimientos.llamadas).toEqual([]);
|
||||
});
|
||||
|
||||
it("con la herramienta en una lista explícita, sí mueve", async () => {
|
||||
base({ tools: ["etapa"] });
|
||||
expect((await mover("Calificado")).ok).toBe(true);
|
||||
});
|
||||
|
||||
it("con una persona al frente: 409 ai_paused", async () => {
|
||||
base({ conversacion: { handoffAt: new Date() } });
|
||||
expect(await mover("Calificado")).toMatchObject({ status: 409, code: "ai_paused" });
|
||||
dbState.queue = [];
|
||||
base({ conversacion: { aiEnabled: false } });
|
||||
expect(await mover("Calificado")).toMatchObject({ status: 409, code: "ai_paused" });
|
||||
});
|
||||
|
||||
it("sin conversación 404 not_found; sin lead 404 sin_lead", async () => {
|
||||
dbState.queue.push([]);
|
||||
expect(await mover("Calificado")).toMatchObject({ status: 404, code: "not_found" });
|
||||
base({ leadStage: null });
|
||||
expect(await mover("Calificado")).toMatchObject({ status: 404, code: "sin_lead" });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,193 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { BOT_API_BUDGET, BOT_AUTH_FAILURES, requireBotKey } from "@/server/bot/auth";
|
||||
import { mergeFicha, normalizeFicha } from "@/server/bot/ficha";
|
||||
import { toHandoffReason } from "@/server/bot/handoff";
|
||||
import { resetRateLimit } from "@/lib/rate-limit";
|
||||
|
||||
/** La puerta de toda la superficie `/api/bot/*`. */
|
||||
|
||||
const KEY = "clave-de-servicio-larga-0123456789abcdef";
|
||||
|
||||
function reqWith(key?: string): Request {
|
||||
return new Request("http://localhost/api/bot/context", {
|
||||
headers: key ? { "x-api-key": key } : {},
|
||||
});
|
||||
}
|
||||
|
||||
describe("requireBotKey", () => {
|
||||
beforeEach(() => {
|
||||
vi.stubEnv("BOT_API_KEY", KEY);
|
||||
resetRateLimit();
|
||||
});
|
||||
afterEach(() => vi.unstubAllEnvs());
|
||||
|
||||
it("key correcta → pasa (null)", () => {
|
||||
expect(requireBotKey(reqWith(KEY))).toBeNull();
|
||||
});
|
||||
|
||||
it("key incorrecta → 401", () => {
|
||||
const res = requireBotKey(reqWith("otra-clave-igual-de-larga-pero-mala!!"));
|
||||
expect(res?.status).toBe(401);
|
||||
});
|
||||
|
||||
it("sin header → 401", () => {
|
||||
expect(requireBotKey(reqWith())?.status).toBe(401);
|
||||
});
|
||||
|
||||
it("sin BOT_API_KEY configurada → 401 SIEMPRE (aunque manden algo)", () => {
|
||||
vi.stubEnv("BOT_API_KEY", "");
|
||||
expect(requireBotKey(reqWith("cualquier-cosa"))?.status).toBe(401);
|
||||
});
|
||||
|
||||
it("key demasiado corta configurada → 401 (no se acepta una key débil)", () => {
|
||||
vi.stubEnv("BOT_API_KEY", "corta");
|
||||
expect(requireBotKey(reqWith("corta"))?.status).toBe(401);
|
||||
});
|
||||
|
||||
it("longitudes distintas no filtran información (401 uniforme)", () => {
|
||||
const res = requireBotKey(reqWith("x"));
|
||||
expect(res?.status).toBe(401);
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* R11 — El límite ya no es un DoS de regalo. Antes: un cubo global contado
|
||||
* ANTES de autenticar, así que 600 requests anónimos por minuto dejaban al
|
||||
* cerebro en 429 y a los clientes sin respuesta.
|
||||
*/
|
||||
describe("requireBotKey: límites (autentica primero, cuenta después)", () => {
|
||||
const MALA = "clave-equivocada-del-mismo-largo-0000000";
|
||||
|
||||
function desde(ip: string, key?: string): Request {
|
||||
return new Request("http://localhost/api/bot/context", {
|
||||
headers: {
|
||||
// Primer salto = el cliente; el resto lo agregan los proxies.
|
||||
"x-forwarded-for": `${ip}, 10.0.0.2`,
|
||||
...(key ? { "x-api-key": key } : {}),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.stubEnv("BOT_API_KEY", KEY);
|
||||
resetRateLimit();
|
||||
});
|
||||
afterEach(() => vi.unstubAllEnvs());
|
||||
|
||||
it("700 requests sin key desde una IP → el cerebro sigue en 200", () => {
|
||||
const vistos = { 401: 0, 429: 0 };
|
||||
for (let i = 0; i < 700; i++) {
|
||||
const s = requireBotKey(desde("203.0.113.9", i % 2 ? MALA : undefined))?.status;
|
||||
if (s === 401 || s === 429) vistos[s]++;
|
||||
}
|
||||
expect(vistos).toEqual({ 401: BOT_AUTH_FAILURES.max, 429: 700 - BOT_AUTH_FAILURES.max });
|
||||
expect(requireBotKey(desde("198.51.100.7", KEY))).toBeNull();
|
||||
// Ni aunque comparta IP con quien inunda (mismo proxy, o "local").
|
||||
expect(requireBotKey(desde("203.0.113.9", KEY))).toBeNull();
|
||||
});
|
||||
|
||||
it("las fallidas se frenan POR IP: 30 → 401, la 31 → 429; otra IP sigue en 401", () => {
|
||||
for (let i = 0; i < BOT_AUTH_FAILURES.max; i++) {
|
||||
expect(requireBotKey(desde("203.0.113.9", MALA))?.status).toBe(401);
|
||||
}
|
||||
expect(requireBotKey(desde("203.0.113.9", MALA))?.status).toBe(429);
|
||||
expect(requireBotKey(desde("192.0.2.1", MALA))?.status).toBe(401);
|
||||
});
|
||||
|
||||
it("el presupuesto del cerebro autenticado sigue aplicando", () => {
|
||||
for (let i = 0; i < BOT_API_BUDGET.max; i++) {
|
||||
expect(requireBotKey(desde("198.51.100.7", KEY))).toBeNull();
|
||||
}
|
||||
expect(requireBotKey(desde("198.51.100.7", KEY))?.status).toBe(429);
|
||||
// Y los fallidos no se cuentan contra él: su respuesta sigue siendo 401.
|
||||
expect(requireBotKey(desde("192.0.2.1"))?.status).toBe(401);
|
||||
});
|
||||
});
|
||||
|
||||
describe("normalizeFicha (tolerante al drift del LLM)", () => {
|
||||
it("las claves las pone el negocio, no el CRM", () => {
|
||||
expect(
|
||||
normalizeFicha({ tratamiento: "ortodoncia", metros: 120, urgente: true })
|
||||
).toEqual({ tratamiento: "ortodoncia", metros: 120, urgente: true });
|
||||
});
|
||||
|
||||
it("recorta espacios y trunca a 500 caracteres", () => {
|
||||
const out = normalizeFicha({ notas: " hola ", largo: "x".repeat(900) });
|
||||
expect(out.notas).toBe("hola");
|
||||
expect((out.largo as string).length).toBe(500);
|
||||
});
|
||||
|
||||
it("la cadena vacía se descarta; null explícito sobrevive para borrar", () => {
|
||||
const out = normalizeFicha({ rubro: "", geo: null });
|
||||
expect("rubro" in out).toBe(false);
|
||||
expect(out.geo).toBeNull();
|
||||
});
|
||||
|
||||
it("objetos y arreglos se ignoran sin reventar", () => {
|
||||
expect(normalizeFicha({ nested: { a: 1 }, lista: [1, 2], ok: "sí" })).toEqual({
|
||||
ok: "sí",
|
||||
});
|
||||
});
|
||||
|
||||
it("números no finitos fuera; el cero sí es un dato", () => {
|
||||
expect(normalizeFicha({ a: Number.NaN, b: Infinity, empleados: 0 })).toEqual({
|
||||
empleados: 0,
|
||||
});
|
||||
});
|
||||
|
||||
it("claves vacías o larguísimas se descartan", () => {
|
||||
const out = normalizeFicha({ " ": "x", ["k".repeat(80)]: "y", bien: "z" });
|
||||
expect(out).toEqual({ bien: "z" });
|
||||
});
|
||||
|
||||
it("un bot en bucle no puede inflar la ficha sin límite", () => {
|
||||
const raw: Record<string, string> = {};
|
||||
for (let i = 0; i < 200; i++) raw[`campo${i}`] = "v";
|
||||
expect(Object.keys(normalizeFicha(raw)).length).toBe(40);
|
||||
});
|
||||
});
|
||||
|
||||
describe("toHandoffReason (el handoff nunca se pierde por el motivo)", () => {
|
||||
it("los motivos del catálogo pasan tal cual", () => {
|
||||
for (const r of ["cliente", "modelo", "error", "ventana", "hostilidad"]) {
|
||||
expect(toHandoffReason(r)).toBe(r);
|
||||
}
|
||||
});
|
||||
|
||||
it("un motivo inventado por el LLM cae a 'modelo' en vez de tirar el handoff", () => {
|
||||
expect(toHandoffReason("porque el señor se enojó")).toBe("modelo");
|
||||
});
|
||||
|
||||
it("ausente o vacío también cae a 'modelo'", () => {
|
||||
expect(toHandoffReason(undefined)).toBe("modelo");
|
||||
expect(toHandoffReason(" ")).toBe("modelo");
|
||||
});
|
||||
|
||||
it("tolera mayúsculas y espacios de sobra", () => {
|
||||
expect(toHandoffReason(" Hostilidad ")).toBe("hostilidad");
|
||||
});
|
||||
});
|
||||
|
||||
describe("mergeFicha", () => {
|
||||
it("lo ausente se conserva y lo nuevo se agrega", () => {
|
||||
expect(mergeFicha({ rubro: "dentista" }, { geo: "Querétaro" })).toEqual({
|
||||
rubro: "dentista",
|
||||
geo: "Querétaro",
|
||||
});
|
||||
});
|
||||
|
||||
it("un valor nuevo pisa al viejo", () => {
|
||||
expect(mergeFicha({ geo: "CDMX" }, { geo: "Querétaro" })).toEqual({
|
||||
geo: "Querétaro",
|
||||
});
|
||||
});
|
||||
|
||||
it("null borra la clave en vez de guardarla en null", () => {
|
||||
const out = mergeFicha({ rubro: "dentista", geo: "CDMX" }, { geo: null });
|
||||
expect(out).toEqual({ rubro: "dentista" });
|
||||
});
|
||||
|
||||
it("sin ficha previa parte de cero", () => {
|
||||
expect(mergeFicha(null, { a: 1 })).toEqual({ a: 1 });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,149 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import type { AiResolution } from "@/lib/ai/provider";
|
||||
|
||||
/**
|
||||
* 036 — `POST /api/bot/llm/{ruta}`: el CRM piensa por el cerebro con la llave
|
||||
* de Ajustes → IA. Lo que se protege: que solo entre quien trae `BOT_API_KEY`
|
||||
* (también como Bearer, que es lo que manda el SDK), que el cuerpo y la
|
||||
* respuesta viajen tal cual, que el 401/402 del proveedor pause la llave del
|
||||
* negocio, y que la llave de IA no vuelva nunca al cerebro.
|
||||
*/
|
||||
|
||||
const LLAVE_BOT = "b".repeat(32);
|
||||
const LLAVE_IA = "sk-or-secreta-9f3a";
|
||||
|
||||
const resolveAiProvider = vi.hoisted(() => vi.fn<() => Promise<AiResolution>>());
|
||||
vi.mock("@/lib/ai/provider", () => ({ resolveAiProvider }));
|
||||
const marcarEstadoPorRespuesta = vi.hoisted(() => vi.fn(async () => true));
|
||||
vi.mock("@/server/ai/credentials", () => ({ marcarEstadoPorRespuesta }));
|
||||
vi.mock("@/server/bot/auth", async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import("@/server/bot/auth")>()),
|
||||
resolveInstanceOrg: async () => "org_1",
|
||||
}));
|
||||
|
||||
import { POST } from "@/app/api/bot/llm/[...ruta]/route";
|
||||
import { resetRateLimit } from "@/lib/rate-limit";
|
||||
|
||||
const PROVEEDOR = (source: "org" | "env" = "org"): AiResolution => ({
|
||||
ok: true,
|
||||
provider: { source, baseUrl: "https://proveedor.test/api", model: "m/uno", judgeModel: "m/uno", token: LLAVE_IA },
|
||||
});
|
||||
|
||||
const CUERPO = JSON.stringify({ model: "m/uno", messages: [{ role: "user", content: "hola" }], extra: { x: 1 } });
|
||||
|
||||
function peticion(headers: Record<string, string>, ruta = ["chat", "completions"]) {
|
||||
return POST(
|
||||
new Request("http://crm.test/api/bot/llm/" + ruta.join("/"), {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json", ...headers },
|
||||
body: CUERPO,
|
||||
}),
|
||||
{ params: Promise.resolve({ ruta }) }
|
||||
);
|
||||
}
|
||||
|
||||
const fetchMock = vi.fn();
|
||||
|
||||
beforeEach(() => {
|
||||
vi.stubEnv("BOT_API_KEY", LLAVE_BOT);
|
||||
resetRateLimit();
|
||||
resolveAiProvider.mockReset().mockResolvedValue(PROVEEDOR());
|
||||
marcarEstadoPorRespuesta.mockClear();
|
||||
// Una respuesta nueva por llamada: un cuerpo solo se lee una vez.
|
||||
fetchMock.mockReset().mockImplementation(async () =>
|
||||
new Response(JSON.stringify({ choices: [{ message: { content: "hola!" } }] }), {
|
||||
status: 200,
|
||||
headers: { "content-type": "application/json" },
|
||||
})
|
||||
);
|
||||
vi.stubGlobal("fetch", fetchMock);
|
||||
});
|
||||
afterEach(() => {
|
||||
vi.unstubAllEnvs();
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
describe("/api/bot/llm — quién entra", () => {
|
||||
it("sin llave → 401 y no llama al proveedor", async () => {
|
||||
const res = await peticion({});
|
||||
expect(res.status).toBe(401);
|
||||
expect(fetchMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("con una llave equivocada → 401", async () => {
|
||||
expect((await peticion({ authorization: "Bearer " + "x".repeat(32) })).status).toBe(401);
|
||||
});
|
||||
|
||||
it("entra con Bearer (el SDK de OpenAI) y con X-API-Key", async () => {
|
||||
expect((await peticion({ authorization: `Bearer ${LLAVE_BOT}` })).status).toBe(200);
|
||||
expect((await peticion({ "x-api-key": LLAVE_BOT })).status).toBe(200);
|
||||
});
|
||||
});
|
||||
|
||||
describe("/api/bot/llm — el reenvío", () => {
|
||||
it("reenvía el cuerpo TAL CUAL a {base}/v1/{ruta} con la llave del negocio, y devuelve la respuesta tal cual", async () => {
|
||||
const res = await peticion({ authorization: `Bearer ${LLAVE_BOT}` });
|
||||
expect(fetchMock).toHaveBeenCalledTimes(1);
|
||||
const [url, init] = fetchMock.mock.calls[0] as [string, RequestInit];
|
||||
expect(url).toBe("https://proveedor.test/api/v1/chat/completions");
|
||||
expect(init.body).toBe(CUERPO);
|
||||
expect((init.headers as Record<string, string>).Authorization).toBe(`Bearer ${LLAVE_IA}`);
|
||||
expect(res.status).toBe(200);
|
||||
expect(await res.json()).toEqual({ choices: [{ message: { content: "hola!" } }] });
|
||||
});
|
||||
|
||||
it("el código del proveedor pasa tal cual (429)", async () => {
|
||||
fetchMock.mockResolvedValue(new Response('{"error":"lento"}', { status: 429 }));
|
||||
const res = await peticion({ authorization: `Bearer ${LLAVE_BOT}` });
|
||||
expect(res.status).toBe(429);
|
||||
expect(marcarEstadoPorRespuesta).toHaveBeenCalledWith("org_1", 429, '{"error":"lento"}');
|
||||
});
|
||||
|
||||
it("un 401 del proveedor llega a la función que pausa la llave del negocio", async () => {
|
||||
fetchMock.mockResolvedValue(new Response('{"error":"bad key"}', { status: 401 }));
|
||||
const res = await peticion({ authorization: `Bearer ${LLAVE_BOT}` });
|
||||
expect(res.status).toBe(401);
|
||||
expect(marcarEstadoPorRespuesta).toHaveBeenCalledWith("org_1", 401, '{"error":"bad key"}');
|
||||
});
|
||||
|
||||
it("con el respaldo del entorno no hay fila que pausar", async () => {
|
||||
resolveAiProvider.mockResolvedValue(PROVEEDOR("env"));
|
||||
fetchMock.mockResolvedValue(new Response("{}", { status: 402 }));
|
||||
expect((await peticion({ authorization: `Bearer ${LLAVE_BOT}` })).status).toBe(402);
|
||||
expect(marcarEstadoPorRespuesta).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("sin IA configurada → 402 sin_credencial, sin llamar al proveedor", async () => {
|
||||
resolveAiProvider.mockResolvedValue({ ok: false, estado: { activa: false, motivo: "sin_configurar" } });
|
||||
const res = await peticion({ authorization: `Bearer ${LLAVE_BOT}` });
|
||||
expect(res.status).toBe(402);
|
||||
expect((await res.json()).error.code).toBe("sin_credencial");
|
||||
expect(fetchMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("con la llave pausada → 402 sin_credencial que dice que está pausada", async () => {
|
||||
resolveAiProvider.mockResolvedValue({
|
||||
ok: false,
|
||||
estado: { activa: false, motivo: "sin_saldo", last4: "9f3a", desde: null },
|
||||
});
|
||||
const res = await peticion({ authorization: `Bearer ${LLAVE_BOT}` });
|
||||
expect(res.status).toBe(402);
|
||||
expect((await res.json()).error.message).toMatch(/pausada/);
|
||||
});
|
||||
|
||||
it("si el proveedor no contesta → 504 proveedor_sin_respuesta y NO pausa", async () => {
|
||||
fetchMock.mockRejectedValue(new TypeError("fetch failed"));
|
||||
const res = await peticion({ authorization: `Bearer ${LLAVE_BOT}` });
|
||||
expect(res.status).toBe(504);
|
||||
expect((await res.json()).error.code).toBe("proveedor_sin_respuesta");
|
||||
expect(marcarEstadoPorRespuesta).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("la llave de IA no aparece en ninguna respuesta, ni en los errores", async () => {
|
||||
const vistas: string[] = [];
|
||||
vistas.push(await (await peticion({ authorization: `Bearer ${LLAVE_BOT}` })).text());
|
||||
fetchMock.mockRejectedValue(new Error(`boom ${LLAVE_IA}`));
|
||||
vistas.push(await (await peticion({ authorization: `Bearer ${LLAVE_BOT}` })).text());
|
||||
for (const v of vistas) expect(v).not.toContain(LLAVE_IA);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,179 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { serializeBotProfile } from "@/server/bot/profile";
|
||||
import type { schema } from "@/lib/db";
|
||||
import { resetRateLimit } from "@/lib/rate-limit";
|
||||
// Estático a propósito: `vi.mock` se hoistea por encima de los imports, así que
|
||||
// la ruta ya nace con la BD falsa. Importarla DENTRO de cada test cargaba la
|
||||
// cadena de módulos con el reloj corriendo y, con la suite completa en
|
||||
// paralelo, el primero se pasaba de los 5 s de timeout.
|
||||
import { GET } from "@/app/api/bot/profile/route";
|
||||
|
||||
const dbState = vi.hoisted(() => ({ queue: [] as unknown[][] }));
|
||||
|
||||
vi.mock("@/lib/db", async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import("@/lib/db")>();
|
||||
const builder: Record<string, unknown> = {};
|
||||
for (const m of ["select", "from", "where", "limit", "orderBy"]) {
|
||||
builder[m] = () => builder;
|
||||
}
|
||||
(builder as { then: unknown }).then = (resolve: (v: unknown) => void) =>
|
||||
resolve(dbState.queue.shift() ?? []);
|
||||
return { ...actual, getDb: () => builder };
|
||||
});
|
||||
|
||||
vi.mock("@/server/bot/auth", async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import("@/server/bot/auth")>();
|
||||
return { ...actual, resolveInstanceOrg: async () => "org_1" };
|
||||
});
|
||||
|
||||
/** Perfil del agente + knowledge base vía la API de servicio `/api/bot/*`. */
|
||||
|
||||
type AgentProfile = typeof schema.agentProfile.$inferSelect;
|
||||
type KbEntry = typeof schema.kbEntry.$inferSelect;
|
||||
|
||||
function profileRow(overrides: Partial<AgentProfile> = {}): AgentProfile {
|
||||
return {
|
||||
id: "ap_1",
|
||||
organizationId: "org_1",
|
||||
reactivateAfterHours: null,
|
||||
enabled: false,
|
||||
name: "Sofi",
|
||||
tone: "cálido y directo",
|
||||
instructions: "Vendemos limpiezas dentales.",
|
||||
escalationRules: "Urgencias de dolor → humano.",
|
||||
greeting: "¡Hola! Soy Sofi 🦷",
|
||||
role: "calificador",
|
||||
tools: null,
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function qa(question: string, answer: string): KbEntry {
|
||||
return {
|
||||
id: `kb_${question}`,
|
||||
organizationId: "org_1",
|
||||
kind: "qa",
|
||||
question,
|
||||
answer,
|
||||
content: null,
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
};
|
||||
}
|
||||
|
||||
describe("034 — role y tools en el perfil", () => {
|
||||
it("con herramientas apagadas viajan solo las encendidas, y escalar siempre", () => {
|
||||
const out = serializeBotProfile(profileRow({ tools: ["ficha"] }), []);
|
||||
expect(out.profile.tools).toEqual(["ficha", "escalar"]);
|
||||
expect(out.profile.role).toBe("calificador");
|
||||
});
|
||||
|
||||
it("un rol que ya no existe cae al Calificador; claves desconocidas se ignoran", () => {
|
||||
const out = serializeBotProfile(profileRow({ role: "vendedor", tools: ["agendar", "volar"] }), []);
|
||||
expect(out.profile.role).toBe("calificador");
|
||||
expect(out.profile.tools).toEqual(["agendar", "escalar"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("serializeBotProfile", () => {
|
||||
it("perfil completo → shape exacto del contrato", () => {
|
||||
const out = serializeBotProfile(profileRow(), [
|
||||
qa("¿Cuánto cuesta?", "$800."),
|
||||
]);
|
||||
expect(out).toEqual({
|
||||
profile: {
|
||||
name: "Sofi",
|
||||
tone: "cálido y directo",
|
||||
instructions: "Vendemos limpiezas dentales.",
|
||||
escalationRules: "Urgencias de dolor → humano.",
|
||||
greeting: "¡Hola! Soy Sofi 🦷",
|
||||
role: "calificador",
|
||||
tools: ["ficha", "etapa", "agendar", "reprogramar", "salida", "escalar"],
|
||||
},
|
||||
kb: "P: ¿Cuánto cuesta?\nR: $800.",
|
||||
resources: [],
|
||||
llm: null,
|
||||
// sin catálogo, viaja vacío (llave aditiva).
|
||||
services: [],
|
||||
});
|
||||
});
|
||||
|
||||
it("036 — llm: el proxy y el modelo del negocio cuando hay con qué pensar", () => {
|
||||
const llm = { path: "/api/bot/llm", model: "openai/gpt-4o-mini" };
|
||||
expect(serializeBotProfile(profileRow(), [], llm).llm).toEqual(llm);
|
||||
});
|
||||
|
||||
it("opcionales vacíos viajan como null, no como cadenas", () => {
|
||||
const out = serializeBotProfile(
|
||||
profileRow({ tone: null, instructions: null, escalationRules: null, greeting: null }),
|
||||
[]
|
||||
);
|
||||
expect(out.profile.tone).toBeNull();
|
||||
expect(out.profile.instructions).toBeNull();
|
||||
expect(out.profile.escalationRules).toBeNull();
|
||||
expect(out.profile.greeting).toBeNull();
|
||||
});
|
||||
|
||||
it("KB vacío → render canónico '(knowledge base vacío)'", () => {
|
||||
expect(serializeBotProfile(profileRow(), []).kb).toBe("(knowledge base vacío)");
|
||||
});
|
||||
|
||||
it("enabled NO viaja: gobierna solo la IA in-process", () => {
|
||||
const out = serializeBotProfile(profileRow({ enabled: false }), []);
|
||||
expect("enabled" in out.profile).toBe(false);
|
||||
// Y enabled=true produce exactamente lo mismo:
|
||||
expect(serializeBotProfile(profileRow({ enabled: true }), [])).toEqual(out);
|
||||
});
|
||||
|
||||
it("resources siempre presente y vacío mientras no haya recursos reales", () => {
|
||||
expect(serializeBotProfile(profileRow(), []).resources).toEqual([]);
|
||||
});
|
||||
|
||||
it("bloques del KB van tal cual, mezclados con P/R en orden", () => {
|
||||
const block: KbEntry = { ...qa("x", "y"), kind: "block", question: null, answer: null, content: "Horario: L-V 9-18." };
|
||||
const out = serializeBotProfile(profileRow(), [qa("¿Dónde están?", "En Querétaro."), block]);
|
||||
expect(out.kb).toBe("P: ¿Dónde están?\nR: En Querétaro.\n\nHorario: L-V 9-18.");
|
||||
});
|
||||
});
|
||||
|
||||
describe("GET /api/bot/profile (ruta, DB fake)", () => {
|
||||
const KEY = "clave-de-servicio-larga-0123456789abcdef";
|
||||
|
||||
beforeEach(() => {
|
||||
vi.stubEnv("BOT_API_KEY", KEY);
|
||||
resetRateLimit();
|
||||
dbState.queue = [];
|
||||
});
|
||||
afterEach(() => vi.unstubAllEnvs());
|
||||
|
||||
function req(key?: string): Request {
|
||||
return new Request("http://localhost/api/bot/profile", {
|
||||
headers: key ? { "x-api-key": key } : {},
|
||||
});
|
||||
}
|
||||
|
||||
it("sin API key → 401 (no filtra existencia del perfil)", async () => {
|
||||
const res = await GET(req());
|
||||
expect(res.status).toBe(401);
|
||||
});
|
||||
|
||||
it("instancia sin perfil (legada) → 404 no_profile", async () => {
|
||||
dbState.queue = [[]];
|
||||
const res = await GET(req(KEY));
|
||||
expect(res.status).toBe(404);
|
||||
const body = (await res.json()) as { error?: { code?: string } };
|
||||
expect(body.error?.code).toBe("no_profile");
|
||||
});
|
||||
|
||||
it("perfil + KB → 200 con el payload del serializador", async () => {
|
||||
dbState.queue = [[profileRow()], [qa("¿Cuánto?", "$800.")]];
|
||||
const res = await GET(req(KEY));
|
||||
expect(res.status).toBe(200);
|
||||
const body = (await res.json()) as ReturnType<typeof serializeBotProfile>;
|
||||
expect(body.profile.name).toBe("Sofi");
|
||||
expect(body.kb).toBe("P: ¿Cuánto?\nR: $800.");
|
||||
expect(body.resources).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,474 @@
|
||||
import { createServer, type IncomingMessage, type Server } from "node:http";
|
||||
import type { AddressInfo } from "node:net";
|
||||
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import type { BrainDispatchDto, BrainHealthDto } from "@/lib/brain-status";
|
||||
import {
|
||||
SIN_DESPACHO,
|
||||
externalAnswerLabel,
|
||||
externalAnswering,
|
||||
externalBrainName,
|
||||
externalDown,
|
||||
haceCuanto,
|
||||
} from "@/lib/brain-status";
|
||||
import { resetRateLimit } from "@/lib/rate-limit";
|
||||
import { isBotKeyConfigured, requireBotKey } from "@/server/bot/auth";
|
||||
import {
|
||||
BRAIN_HEALTH_TTL_MS,
|
||||
EXTERNAL_SEEN_WINDOW_MS,
|
||||
botLastSeenAt,
|
||||
computeBrainStatus,
|
||||
fetchBrainHealth,
|
||||
getBrainHealth,
|
||||
markBotSeen,
|
||||
resetBrainStatusState,
|
||||
type BrainStatusInput,
|
||||
} from "@/server/bot/status";
|
||||
|
||||
/**
|
||||
* «Quién responde a tus clientes». Lo que se protege: que el dueño sepa si
|
||||
* contesta su agente (el cerebro al que el CRM despacha), si está apagado o si
|
||||
* la bandeja es manual — y que preguntarle a Nea jamás cuelgue la pantalla ni
|
||||
* filtre la URL con sus secretos.
|
||||
*/
|
||||
|
||||
const NOW = new Date("2026-09-21T18:00:00.000Z");
|
||||
const HACE_3_MIN = new Date(NOW.getTime() - 3 * 60_000);
|
||||
const HACE_25_H = new Date(NOW.getTime() - 25 * 3_600_000);
|
||||
|
||||
const EN_LINEA: BrainHealthDto = {
|
||||
reachable: true,
|
||||
host: "nea:8000",
|
||||
checkedAt: NOW.toISOString(),
|
||||
version: "1.0.0",
|
||||
mode: "estándar",
|
||||
};
|
||||
const CAIDA: BrainHealthDto = {
|
||||
reachable: false,
|
||||
host: "nea:8000",
|
||||
checkedAt: NOW.toISOString(),
|
||||
problem: "timeout",
|
||||
};
|
||||
|
||||
function status(over: Partial<BrainStatusInput>) {
|
||||
return computeBrainStatus({
|
||||
aiConfigured: false,
|
||||
agentEnabled: false,
|
||||
botKeyConfigured: false,
|
||||
lastSeenAt: null,
|
||||
health: null,
|
||||
now: NOW,
|
||||
...over,
|
||||
});
|
||||
}
|
||||
|
||||
const DESPACHANDO: BrainDispatchDto = {
|
||||
...SIN_DESPACHO,
|
||||
active: true,
|
||||
host: "nea:8000",
|
||||
};
|
||||
|
||||
describe("computeBrainStatus — 036: contesta el cerebro al que se le despacha", () => {
|
||||
it("sin despacho, la llave nueva es la de una instancia que no despacha", () => {
|
||||
expect(status({}).dispatch).toEqual(SIN_DESPACHO);
|
||||
});
|
||||
|
||||
it("despacho e interruptor: contesta el cerebro, sin aviso", () => {
|
||||
const s = status({
|
||||
aiConfigured: true,
|
||||
agentEnabled: true,
|
||||
botKeyConfigured: true,
|
||||
lastSeenAt: HACE_3_MIN,
|
||||
health: EN_LINEA,
|
||||
dispatch: DESPACHANDO,
|
||||
});
|
||||
expect(s.enabled).toBe(true);
|
||||
expect(s.aiConfigured).toBe(true);
|
||||
expect(s.external.active).toBe(true);
|
||||
expect(s.warning).toBeNull();
|
||||
expect(s.dispatch).toEqual(DESPACHANDO);
|
||||
expect(externalAnswering(s)).toBe(true);
|
||||
});
|
||||
|
||||
it("despacho con el interruptor apagado → aviso apagado, y no contesta nadie", () => {
|
||||
const s = status({ botKeyConfigured: true, health: EN_LINEA, dispatch: DESPACHANDO });
|
||||
expect(s.warning).toBe("apagado");
|
||||
expect(externalAnswering(s)).toBe(false);
|
||||
});
|
||||
|
||||
it("despacho e interruptor con el /health caído: se ve caído", () => {
|
||||
const s = status({ agentEnabled: true, botKeyConfigured: true, health: CAIDA, dispatch: DESPACHANDO });
|
||||
expect(s.warning).toBeNull();
|
||||
expect(externalDown(s)).toBe(true);
|
||||
expect(externalAnswering(s)).toBe(false);
|
||||
});
|
||||
|
||||
it("sin despacho → sin_cerebro (bandeja manual), con o sin IA e interruptor", () => {
|
||||
for (const aiConfigured of [false, true])
|
||||
for (const agentEnabled of [false, true]) {
|
||||
const s = status({ aiConfigured, agentEnabled, botKeyConfigured: true, health: EN_LINEA });
|
||||
expect(s.warning).toBe("sin_cerebro");
|
||||
expect(externalAnswering(s)).toBe(false);
|
||||
}
|
||||
});
|
||||
|
||||
it("despacho mal configurado cuenta como sin cerebro", () => {
|
||||
const roto: BrainDispatchDto = { ...SIN_DESPACHO, host: "nea:8000", problem: "sin_llave" };
|
||||
const s = status({ aiConfigured: true, agentEnabled: true, dispatch: roto });
|
||||
expect(s.warning).toBe("sin_cerebro");
|
||||
expect(s.dispatch.problem).toBe("sin_llave");
|
||||
});
|
||||
|
||||
it("activo: llamada reciente (≤ 24 h), /health en línea o despacho", () => {
|
||||
expect(status({ botKeyConfigured: true, lastSeenAt: HACE_3_MIN }).external.active).toBe(true);
|
||||
const justo = new Date(NOW.getTime() - EXTERNAL_SEEN_WINDOW_MS);
|
||||
expect(status({ botKeyConfigured: true, lastSeenAt: justo }).external.active).toBe(true);
|
||||
expect(status({ botKeyConfigured: true, lastSeenAt: HACE_25_H }).external.active).toBe(false);
|
||||
expect(status({ health: EN_LINEA }).external.active).toBe(true);
|
||||
expect(status({ health: CAIDA }).external.active).toBe(false);
|
||||
expect(status({ dispatch: DESPACHANDO }).external.active).toBe(true);
|
||||
// Sin llave, una llamada «reciente» no pudo haber pasado la autenticación.
|
||||
expect(status({ lastSeenAt: HACE_3_MIN }).external.active).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("textos compartidos", () => {
|
||||
it("«Nea» solo si su /health habla el contrato de Nea", () => {
|
||||
const conNea = status({ botKeyConfigured: true, health: EN_LINEA });
|
||||
expect(externalBrainName(conNea)).toBe("Nea");
|
||||
expect(externalAnswerLabel(conNea)).toBe("Responde tu cerebro externo (Nea)");
|
||||
const sinNombre = status({ botKeyConfigured: true, lastSeenAt: HACE_3_MIN });
|
||||
expect(externalBrainName(sinNombre)).toBeNull();
|
||||
expect(externalAnswerLabel(sinNombre)).toBe("Responde tu cerebro externo");
|
||||
});
|
||||
|
||||
it("«responde tu cerebro externo» solo si se le despacha, está encendido y no está caído", () => {
|
||||
const base = { agentEnabled: true, botKeyConfigured: true, dispatch: DESPACHANDO };
|
||||
const sano = status({ ...base, health: EN_LINEA });
|
||||
expect(externalAnswering(sano)).toBe(true);
|
||||
expect(externalDown(sano)).toBe(false);
|
||||
const caido = status({ ...base, lastSeenAt: HACE_3_MIN, health: CAIDA });
|
||||
expect(caido.external.active).toBe(true);
|
||||
expect(externalAnswering(caido)).toBe(false);
|
||||
expect(externalDown(caido)).toBe(true);
|
||||
// Sin URL de salud no se sabe si está caído: manda el despacho.
|
||||
expect(externalAnswering(status(base))).toBe(true);
|
||||
// Llamó hace 3 min pero el CRM no le despacha: no es quien contesta.
|
||||
expect(externalAnswering(status({ botKeyConfigured: true, lastSeenAt: HACE_3_MIN, health: EN_LINEA }))).toBe(false);
|
||||
});
|
||||
|
||||
it("con BRAIN_HEALTH_URL mal escrita no se le da por caído", () => {
|
||||
const mal: BrainHealthDto = { reachable: false, host: "", checkedAt: NOW.toISOString(), problem: "config" };
|
||||
const s = status({ agentEnabled: true, botKeyConfigured: true, health: mal, dispatch: DESPACHANDO });
|
||||
expect(externalDown(s)).toBe(false);
|
||||
expect(externalAnswering(s)).toBe(true);
|
||||
});
|
||||
|
||||
it("haceCuanto", () => {
|
||||
const t = NOW.getTime();
|
||||
expect(haceCuanto(new Date(t - 20_000).toISOString(), t)).toBe("hace unos segundos");
|
||||
expect(haceCuanto(new Date(t + 60_000).toISOString(), t)).toBe("hace unos segundos");
|
||||
expect(haceCuanto(HACE_3_MIN.toISOString(), t)).toBe("hace 3 min");
|
||||
expect(haceCuanto(new Date(t - 2 * 3_600_000).toISOString(), t)).toBe("hace 2 h");
|
||||
expect(haceCuanto(HACE_25_H.toISOString(), t)).toBe("hace 1 día");
|
||||
});
|
||||
});
|
||||
|
||||
describe("la última llamada del cerebro externo (requireBotKey)", () => {
|
||||
const KEY = "clave-de-servicio-larga-0123456789abcdef";
|
||||
const req = (key?: string) =>
|
||||
new Request("http://localhost/api/bot/context", {
|
||||
headers: key ? { "x-api-key": key } : {},
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
vi.stubEnv("BOT_API_KEY", KEY);
|
||||
resetRateLimit();
|
||||
resetBrainStatusState();
|
||||
});
|
||||
afterEach(() => vi.unstubAllEnvs());
|
||||
|
||||
it("solo una llamada autenticada la anota", () => {
|
||||
expect(botLastSeenAt()).toBeNull();
|
||||
expect(requireBotKey(req())?.status).toBe(401);
|
||||
expect(requireBotKey(req("otra-clave-igual-de-larga-pero-mala!!"))?.status).toBe(401);
|
||||
expect(botLastSeenAt()).toBeNull();
|
||||
const antes = Date.now();
|
||||
expect(requireBotKey(req(KEY))).toBeNull();
|
||||
expect(botLastSeenAt()!.getTime()).toBeGreaterThanOrEqual(antes);
|
||||
});
|
||||
|
||||
it("vive en memoria del proceso (compartida entre rutas)", () => {
|
||||
markBotSeen(HACE_3_MIN.getTime());
|
||||
expect(botLastSeenAt()?.toISOString()).toBe(HACE_3_MIN.toISOString());
|
||||
});
|
||||
|
||||
it("una key corta equivale a no tener llave", () => {
|
||||
expect(isBotKeyConfigured()).toBe(true);
|
||||
vi.stubEnv("BOT_API_KEY", "corta");
|
||||
expect(isBotKeyConfigured()).toBe(false);
|
||||
vi.stubEnv("BOT_API_KEY", "");
|
||||
expect(isBotKeyConfigured()).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// El /health, contra un servidor HTTP de verdad
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
let server: Server;
|
||||
let base = "";
|
||||
let hitsDestino = 0;
|
||||
let ultimaEco: { authorization?: string; url?: string } = {};
|
||||
|
||||
const NEA = {
|
||||
ok: true,
|
||||
version: "1.0.0",
|
||||
commit: "abc1234",
|
||||
commitVerified: true,
|
||||
mode: "estándar",
|
||||
relay: { pendientes: 0, masViejoSegundos: null, ultimoErrorEn: null },
|
||||
};
|
||||
|
||||
function json(res: import("node:http").ServerResponse, code: number, body: unknown) {
|
||||
res.writeHead(code, { "content-type": "application/json" });
|
||||
res.end(JSON.stringify(body));
|
||||
}
|
||||
|
||||
beforeAll(async () => {
|
||||
server = createServer((req: IncomingMessage, res) => {
|
||||
const path = (req.url ?? "").split("?")[0];
|
||||
switch (path) {
|
||||
case "/nea":
|
||||
return json(res, 200, NEA);
|
||||
case "/nea-real": // lo que de verdad manda Nea: `status`, no `ok`
|
||||
return json(res, 200, { status: "ok", db: "ok", version: "1.1.0", mode: "cloud" });
|
||||
case "/vieja":
|
||||
return json(res, 200, { status: "ok", db: "ok" });
|
||||
case "/degradada":
|
||||
return json(res, 503, { status: "degraded", db: "error", version: "1.1.0", mode: "estándar" });
|
||||
case "/500":
|
||||
res.writeHead(500, { "content-type": "text/plain" });
|
||||
return res.end("Internal Server Error");
|
||||
case "/html":
|
||||
res.writeHead(200, { "content-type": "text/html" });
|
||||
return res.end("<html><body>ok</body></html>");
|
||||
case "/sin-ok":
|
||||
return json(res, 200, { version: "1.0.0" });
|
||||
case "/arreglo":
|
||||
return json(res, 200, [{ ok: true }]);
|
||||
case "/redirige":
|
||||
res.writeHead(302, { location: "/destino" });
|
||||
return res.end();
|
||||
case "/destino":
|
||||
hitsDestino++;
|
||||
return json(res, 200, NEA);
|
||||
case "/cuelga":
|
||||
return; // nunca contesta
|
||||
case "/grande": {
|
||||
res.writeHead(200, { "content-type": "application/json" }); // sin content-length
|
||||
res.write(`{"ok":true,"relleno":"`);
|
||||
res.write("x".repeat(100 * 1024));
|
||||
return res.end(`"}`);
|
||||
}
|
||||
case "/raro":
|
||||
return json(res, 200, {
|
||||
ok: true,
|
||||
version: 123,
|
||||
commit: "no-es-hex!",
|
||||
commitVerified: "sí",
|
||||
mode: "turbo",
|
||||
relay: { pendientes: -1, masViejoSegundos: "x", ultimoErrorEn: "ayer" },
|
||||
});
|
||||
case "/tolerante":
|
||||
return json(res, 200, {
|
||||
ok: true,
|
||||
version: " v2.0.0 ",
|
||||
mode: "Estandar",
|
||||
relay: { pendientes: 2.7, masViejoSegundos: 95, ultimoErrorEn: "2026-09-21T17:55:00+00:00" },
|
||||
});
|
||||
case "/eco":
|
||||
ultimaEco = { authorization: req.headers.authorization, url: req.url };
|
||||
return json(res, 200, NEA);
|
||||
default:
|
||||
res.writeHead(404);
|
||||
return res.end();
|
||||
}
|
||||
});
|
||||
await new Promise<void>((r) => server.listen(0, "127.0.0.1", r));
|
||||
base = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
server.closeAllConnections();
|
||||
await new Promise<void>((r) => server.close(() => r()));
|
||||
});
|
||||
|
||||
describe("fetchBrainHealth", () => {
|
||||
it("Nea sana con el contrato completo → en línea con versión, modo y relevo", async () => {
|
||||
const h = await fetchBrainHealth(`${base}/nea`);
|
||||
expect(h).toMatchObject({
|
||||
reachable: true,
|
||||
host: base.replace("http://", ""),
|
||||
version: "1.0.0",
|
||||
commit: "abc1234",
|
||||
commitVerified: true,
|
||||
mode: "estándar",
|
||||
relay: { pendientes: 0, masViejoSegundos: null, ultimoErrorEn: null },
|
||||
});
|
||||
expect(h.problem).toBeUndefined();
|
||||
expect(Date.parse(h.checkedAt)).not.toBeNaN();
|
||||
});
|
||||
|
||||
it("la Nea de hoy manda `status: \"ok\"` en vez de `ok` → también en línea", async () => {
|
||||
const h = await fetchBrainHealth(`${base}/nea-real`);
|
||||
expect(h).toMatchObject({ reachable: true, version: "1.1.0", mode: "cloud" });
|
||||
});
|
||||
|
||||
it("una Nea vieja (solo `status`) → en línea, sin inventar versión ni modo", async () => {
|
||||
const h = await fetchBrainHealth(`${base}/vieja`);
|
||||
expect(h.reachable).toBe(true);
|
||||
expect(h.version).toBeUndefined();
|
||||
expect(h.mode).toBeUndefined();
|
||||
expect(h.relay).toBeUndefined();
|
||||
});
|
||||
|
||||
it("503 degradada → no en línea, pero conserva quién es", async () => {
|
||||
const h = await fetchBrainHealth(`${base}/degradada`);
|
||||
expect(h).toMatchObject({
|
||||
reachable: false,
|
||||
problem: "status",
|
||||
httpStatus: 503,
|
||||
version: "1.1.0",
|
||||
mode: "estándar",
|
||||
});
|
||||
});
|
||||
|
||||
it("500 en texto plano → problem status 500", async () => {
|
||||
const h = await fetchBrainHealth(`${base}/500`);
|
||||
expect(h).toMatchObject({ reachable: false, problem: "status", httpStatus: 500 });
|
||||
});
|
||||
|
||||
it("200 que no es JSON, JSON sin `ok`, o un arreglo → invalid", async () => {
|
||||
for (const p of ["/html", "/sin-ok", "/arreglo"]) {
|
||||
const h = await fetchBrainHealth(`${base}${p}`);
|
||||
expect(h, p).toMatchObject({ reachable: false, problem: "invalid" });
|
||||
}
|
||||
});
|
||||
|
||||
it("una redirección NO se sigue", async () => {
|
||||
hitsDestino = 0;
|
||||
const h = await fetchBrainHealth(`${base}/redirige`);
|
||||
expect(h).toMatchObject({ reachable: false, problem: "redirect", httpStatus: 302 });
|
||||
expect(hitsDestino).toBe(0);
|
||||
});
|
||||
|
||||
it("si no contesta, se rinde a tiempo (timeout) y no lanza", async () => {
|
||||
const t0 = Date.now();
|
||||
const h = await fetchBrainHealth(`${base}/cuelga`, { timeoutMs: 200 });
|
||||
expect(h).toMatchObject({ reachable: false, problem: "timeout" });
|
||||
expect(Date.now() - t0).toBeLessThan(1500);
|
||||
});
|
||||
|
||||
it("puerto cerrado → network", async () => {
|
||||
const libre = createServer();
|
||||
await new Promise<void>((r) => libre.listen(0, "127.0.0.1", r));
|
||||
const port = (libre.address() as AddressInfo).port;
|
||||
await new Promise<void>((r) => libre.close(() => r()));
|
||||
const h = await fetchBrainHealth(`http://127.0.0.1:${port}/health`);
|
||||
expect(h).toMatchObject({ reachable: false, problem: "network", host: `127.0.0.1:${port}` });
|
||||
});
|
||||
|
||||
it("una URL mal escrita ni se intenta → config, sin host", async () => {
|
||||
const fetchImpl = vi.fn();
|
||||
for (const url of ["nea:8000/health", "ftp://nea/health", "no es una url"]) {
|
||||
const h = await fetchBrainHealth(url, { fetchImpl: fetchImpl as unknown as typeof fetch });
|
||||
expect(h).toMatchObject({ reachable: false, host: "", problem: "config" });
|
||||
}
|
||||
expect(fetchImpl).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("un cuerpo enorme no se lee entero → invalid", async () => {
|
||||
const h = await fetchBrainHealth(`${base}/grande`);
|
||||
expect(h).toMatchObject({ reachable: false, problem: "invalid" });
|
||||
});
|
||||
|
||||
it("campos con basura se descartan; los tolerables se normalizan", async () => {
|
||||
const raro = await fetchBrainHealth(`${base}/raro`);
|
||||
expect(raro.reachable).toBe(true);
|
||||
expect(raro).not.toHaveProperty("version");
|
||||
expect(raro).not.toHaveProperty("commit");
|
||||
expect(raro).not.toHaveProperty("commitVerified");
|
||||
expect(raro).not.toHaveProperty("mode");
|
||||
expect(raro).not.toHaveProperty("relay");
|
||||
|
||||
const tol = await fetchBrainHealth(`${base}/tolerante`);
|
||||
expect(tol).toMatchObject({
|
||||
version: "v2.0.0",
|
||||
mode: "estándar",
|
||||
relay: { pendientes: 2, masViejoSegundos: 95, ultimoErrorEn: "2026-09-21T17:55:00.000Z" },
|
||||
});
|
||||
});
|
||||
|
||||
it("credenciales y query de la URL: se usan, pero jamás salen en la respuesta", async () => {
|
||||
const port = base.split(":").pop();
|
||||
const h = await fetchBrainHealth(
|
||||
`http://usuario:s3cr3t-pass@127.0.0.1:${port}/eco?token=tok-secreto`
|
||||
);
|
||||
expect(h.reachable).toBe(true);
|
||||
// Las credenciales viajan como Basic (fetch rechaza una URL que las trae)…
|
||||
expect(ultimaEco.authorization).toBe(
|
||||
`Basic ${Buffer.from("usuario:s3cr3t-pass").toString("base64")}`
|
||||
);
|
||||
expect(ultimaEco.url).toBe("/eco?token=tok-secreto");
|
||||
// …y de la URL solo vuelve el host.
|
||||
expect(h.host).toBe(`127.0.0.1:${port}`);
|
||||
const dump = JSON.stringify(h);
|
||||
for (const secreto of ["s3cr3t", "usuario", "tok-secreto", "token", "/eco"]) {
|
||||
expect(dump).not.toContain(secreto);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("getBrainHealth (caché de 15 s)", () => {
|
||||
beforeEach(() => resetBrainStatusState());
|
||||
|
||||
function contador() {
|
||||
let n = 0;
|
||||
const fetchImpl: typeof fetch = async () => {
|
||||
n++;
|
||||
return new Response(JSON.stringify({ ok: true }), { status: 200 });
|
||||
};
|
||||
return { fetchImpl, llamadas: () => n };
|
||||
}
|
||||
|
||||
it("sin BRAIN_HEALTH_URL no le pregunta a nadie", async () => {
|
||||
const c = contador();
|
||||
expect(await getBrainHealth(undefined, { fetchImpl: c.fetchImpl })).toBeNull();
|
||||
expect(c.llamadas()).toBe(0);
|
||||
});
|
||||
|
||||
it("reutiliza la respuesta 15 s y después vuelve a preguntar", async () => {
|
||||
const c = contador();
|
||||
let t = 1_000_000;
|
||||
const opts = { fetchImpl: c.fetchImpl, clock: () => t };
|
||||
await getBrainHealth("http://nea:8000/health", opts);
|
||||
t += BRAIN_HEALTH_TTL_MS - 1;
|
||||
await getBrainHealth("http://nea:8000/health", opts);
|
||||
expect(c.llamadas()).toBe(1);
|
||||
t += 2;
|
||||
await getBrainHealth("http://nea:8000/health", opts);
|
||||
expect(c.llamadas()).toBe(2);
|
||||
});
|
||||
|
||||
it("llamadas simultáneas comparten una sola pregunta", async () => {
|
||||
const c = contador();
|
||||
const opts = { fetchImpl: c.fetchImpl };
|
||||
const rs = await Promise.all([
|
||||
getBrainHealth("http://nea:8000/health", opts),
|
||||
getBrainHealth("http://nea:8000/health", opts),
|
||||
getBrainHealth("http://nea:8000/health", opts),
|
||||
]);
|
||||
expect(c.llamadas()).toBe(1);
|
||||
expect(rs.every((r) => r?.reachable === true)).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,234 @@
|
||||
import { readFileSync } from "node:fs";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
ACCENT_PRESETS,
|
||||
accentCssVariables,
|
||||
DEFAULT_BRANDING,
|
||||
isValidHex,
|
||||
normalizeBranding,
|
||||
resolveAccentSet,
|
||||
resolveNavAccentSet,
|
||||
} from "@/lib/branding";
|
||||
|
||||
const DARK_BG = "#13222b";
|
||||
const NAV_BG = "#0b1327";
|
||||
|
||||
/** Contraste WCAG entre dos hex, para afirmar sobre legibilidad y no sobre
|
||||
* valores concretos: lo que importa es que se LEA, no que dé cierto color. */
|
||||
function contrast(a: string, b: string): number {
|
||||
const lum = (hex: string) => {
|
||||
const ch = [1, 3, 5]
|
||||
.map((i) => parseInt(hex.slice(i, i + 2), 16) / 255)
|
||||
.map((v) => (v <= 0.03928 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4));
|
||||
return 0.2126 * ch[0]! + 0.7152 * ch[1]! + 0.0722 * ch[2]!;
|
||||
};
|
||||
const [l1, l2] = [lum(a), lum(b)];
|
||||
return (Math.max(l1, l2) + 0.05) / (Math.min(l1, l2) + 0.05);
|
||||
}
|
||||
|
||||
/** Variables de un bloque de globals.css, con el valor sin saltos de línea. */
|
||||
function variables(css: string, selector: string): Record<string, string> {
|
||||
const inicio = css.indexOf(selector);
|
||||
expect(inicio, `no está el bloque ${selector}`).toBeGreaterThanOrEqual(0);
|
||||
const cuerpo = css
|
||||
.slice(css.indexOf("{", inicio) + 1, css.indexOf("}", inicio))
|
||||
.replace(/\/\*[\s\S]*?\*\//g, ""); // un comentario puede nombrar un token
|
||||
return Object.fromEntries(
|
||||
[...cuerpo.matchAll(/(--[\w-]+):\s*([^;]+);/g)].map((m) => [
|
||||
m[1]!,
|
||||
m[2]!.replace(/\s+/g, " ").trim(),
|
||||
])
|
||||
);
|
||||
}
|
||||
|
||||
describe("white-label: acento", () => {
|
||||
it("preset devuelve el set exacto del handoff", () => {
|
||||
expect(resolveAccentSet("#3f5972")).toEqual(ACCENT_PRESETS["#3f5972"]!.set);
|
||||
expect(resolveAccentSet("#5f5470").soft).toBe("#e6e1ec");
|
||||
});
|
||||
|
||||
it("color personalizado deriva hover/soft/tint/text", () => {
|
||||
const s = resolveAccentSet("#7a3b5e");
|
||||
expect(isValidHex(s.hover)).toBe(true);
|
||||
expect(isValidHex(s.soft)).toBe(true);
|
||||
expect(isValidHex(s.tint)).toBe(true);
|
||||
expect(s.hover).not.toBe(s.accent);
|
||||
});
|
||||
|
||||
it("color demasiado claro se oscurece para contraste con texto blanco", () => {
|
||||
const s = resolveAccentSet("#ffee88"); // amarillo pálido, ilegible con blanco
|
||||
expect(s.accent).not.toBe("#ffee88");
|
||||
// el resultado debe ser notablemente más oscuro
|
||||
const lum = parseInt(s.accent.slice(1, 3), 16);
|
||||
expect(lum).toBeLessThan(0xd0);
|
||||
});
|
||||
|
||||
it("hex inválido cae al default (el turquesa)", () => {
|
||||
expect(resolveAccentSet("rojo")).toEqual(ACCENT_PRESETS["#009c98"]!.set);
|
||||
});
|
||||
|
||||
it("el turquesa del prototipo es el default, con tinta oscura (AA) encima", () => {
|
||||
expect(DEFAULT_BRANDING.accent).toBe("#009c98");
|
||||
expect(resolveAccentSet(DEFAULT_BRANDING.accent)).toEqual({
|
||||
accent: "#009c98",
|
||||
hover: "#00807d",
|
||||
soft: "#a6e0dd",
|
||||
tint: "#c8ecea",
|
||||
text: "#006b68",
|
||||
fg: "#0f1419",
|
||||
});
|
||||
expect(contrast("#0f1419", "#009c98")).toBeGreaterThanOrEqual(4.5);
|
||||
});
|
||||
|
||||
it("el azul eléctrico sigue disponible con los valores de siempre", () => {
|
||||
expect(resolveAccentSet("#0d5bff")).toEqual({
|
||||
accent: "#0d5bff",
|
||||
hover: "#0a4de6",
|
||||
soft: "#d3e2ff",
|
||||
tint: "#ebf1ff",
|
||||
text: "#0038d8",
|
||||
fg: "#ffffff",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("white-label: acento en tema oscuro", () => {
|
||||
it("un acento pensado para fondo blanco se aclara hasta despegarse del fondo", () => {
|
||||
// Azul profundo: sobre el azul marino de la página casi no se ve.
|
||||
const oscuro = resolveAccentSet("#12305a", "dark");
|
||||
expect(contrast("#12305a", DARK_BG)).toBeLessThan(3);
|
||||
expect(contrast(oscuro.accent, DARK_BG)).toBeGreaterThanOrEqual(3);
|
||||
});
|
||||
|
||||
it("la tinta del botón pasa AA sobre el acento ya aclarado", () => {
|
||||
for (const hex of ["#12305a", "#3f5972", "#ffee88", "#7a3b5e"]) {
|
||||
const s = resolveAccentSet(hex, "dark");
|
||||
expect(contrast(s.fg, s.accent)).toBeGreaterThanOrEqual(4.5);
|
||||
}
|
||||
});
|
||||
|
||||
it("el azul eléctrico conserva la tinta blanca en oscuro", () => {
|
||||
expect(resolveAccentSet("#0d5bff", "dark").fg).toBe("#ffffff");
|
||||
});
|
||||
|
||||
it("los presets NO se aplican tal cual: están calculados para fondo blanco", () => {
|
||||
const claro = resolveAccentSet("#3f5972", "light");
|
||||
const oscuro = resolveAccentSet("#3f5972", "dark");
|
||||
expect(oscuro.accent).not.toBe(claro.accent);
|
||||
// soft y tint se mezclan hacia el fondo oscuro, no hacia blanco
|
||||
expect(contrast(oscuro.tint, DARK_BG)).toBeLessThan(2);
|
||||
});
|
||||
|
||||
it("hex inválido en oscuro también cae al acento por defecto", () => {
|
||||
expect(resolveAccentSet("rojo", "dark")).toEqual(
|
||||
resolveAccentSet("#009c98", "dark")
|
||||
);
|
||||
});
|
||||
|
||||
it("el CSS inyectado trae los DOS temas: el botón cambia sin recargar", () => {
|
||||
const css = accentCssVariables("#3f5972");
|
||||
expect(css).toContain(":root:root{");
|
||||
expect(css).toContain(':root:root[data-theme="dark"]{');
|
||||
expect(css).toContain(resolveAccentSet("#3f5972", "light").accent);
|
||||
expect(css).toContain(resolveAccentSet("#3f5972", "dark").accent);
|
||||
});
|
||||
|
||||
it("el fondo de referencia del cálculo sigue al de globals.css", () => {
|
||||
// DARK_BG y NAV_BG viven duplicados en branding.ts porque el cálculo de
|
||||
// contraste es JS y el token es CSS. Si alguien cambia un fondo y no el
|
||||
// otro, los acentos se calculan contra un fondo que ya no existe.
|
||||
const css = readFileSync("src/app/globals.css", "utf8");
|
||||
const dark = variables(css, ':root[data-theme="dark"] {');
|
||||
expect(dark["--bg"]?.toLowerCase()).toBe(DARK_BG);
|
||||
expect(variables(css, ".nav-dark {")["--bg"]?.toLowerCase()).toBe(NAV_BG);
|
||||
// …y el cálculo de verdad los usa: el relleno se despega de cada uno.
|
||||
expect(contrast(resolveAccentSet("#12305a", "dark").accent, DARK_BG)).toBeGreaterThanOrEqual(3);
|
||||
expect(contrast(resolveNavAccentSet("#12305a").accent, NAV_BG)).toBeGreaterThanOrEqual(3.5);
|
||||
});
|
||||
});
|
||||
|
||||
describe("white-label: barra lateral bicolor (.nav-dark)", () => {
|
||||
it("la barra lleva SIEMPRE el acento calculado contra su propio fondo", () => {
|
||||
// Es azul marino aunque la página esté en claro: con el acento del tema
|
||||
// claro, un color pensado para fondo blanco se hundiría en ella.
|
||||
const css = accentCssVariables("#3f5972");
|
||||
const nav = /\.nav-dark\{([^}]*)\}/.exec(css)?.[1] ?? "";
|
||||
expect(nav).toContain(`--accent:${resolveNavAccentSet("#3f5972").accent};`);
|
||||
expect(nav).toContain(`--accent-fg:${resolveNavAccentSet("#3f5972").fg};`);
|
||||
expect(nav).not.toContain(resolveAccentSet("#3f5972", "light").accent);
|
||||
});
|
||||
|
||||
it("con el azul eléctrico, la barra se ve como siempre", () => {
|
||||
// La receta de la barra es la de antes: el ítem activo del tema claro no
|
||||
// cambia aunque el tema oscuro de la página sí.
|
||||
expect(resolveNavAccentSet("#0d5bff")).toEqual({
|
||||
accent: "#256bff",
|
||||
hover: "#4883ff",
|
||||
soft: "#122c63",
|
||||
tint: "#0e1e41",
|
||||
text: "#6295ff",
|
||||
fg: "#ffffff",
|
||||
});
|
||||
});
|
||||
|
||||
it("sus neutros son SUYOS: no copian al tema oscuro de la página", () => {
|
||||
// Antes `.nav-dark` repetía el bloque oscuro y barra y página quedaban a
|
||||
// 1.04:1. Ahora la página va un escalón arriba; si alguien vuelve a
|
||||
// igualarlas, el bicolor desaparece en oscuro: aquí se cae.
|
||||
const css = readFileSync("src/app/globals.css", "utf8");
|
||||
const oscuro = variables(css, ':root[data-theme="dark"] {');
|
||||
const nav = variables(css, ".nav-dark {");
|
||||
expect(Object.keys(nav)).toEqual(
|
||||
expect.arrayContaining(["--bg", "--bg-subtle", "--text", "--text-3", "--border"])
|
||||
);
|
||||
expect(nav["--bg-subtle"]).not.toBe(oscuro["--bg-subtle"]);
|
||||
expect(nav["--bg"]).not.toBe(oscuro["--bg"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("tema oscuro: las superficies se distinguen", () => {
|
||||
// Con los tokens de antes, lista, hilo y barra eran tres azules marino casi
|
||||
// iguales: bordes a 1.26:1 del fondo y chips del mismo color que su fila.
|
||||
// Se afirma sobre legibilidad, no sobre un hex: el que retoque el tema
|
||||
// oscuro puede mover los valores, no el piso.
|
||||
const css = readFileSync("src/app/globals.css", "utf8");
|
||||
const oscuro = variables(css, ':root[data-theme="dark"] {');
|
||||
const claro = variables(css, ":root {");
|
||||
const tono = (nombre: string) => oscuro[nombre] ?? `falta ${nombre}`;
|
||||
|
||||
it("los bordes separan las columnas: ≥ 1.6:1 contra el fondo", () => {
|
||||
expect(contrast(tono("--border"), tono("--bg"))).toBeGreaterThanOrEqual(1.6);
|
||||
expect(contrast(tono("--border-strong"), tono("--bg"))).toBeGreaterThan(
|
||||
contrast(tono("--border"), tono("--bg"))
|
||||
);
|
||||
});
|
||||
|
||||
it("el chip y la fila bajo el cursor se ACLARAN respecto al fondo", () => {
|
||||
// Contra --bg, que es el de la lista: un chip o un hover más oscuros se
|
||||
// leen como un hueco, no como una superficie.
|
||||
const blanco = "#ffffff";
|
||||
for (const nombre of ["--chip-bg", "--row-hover", "--bg-hover"]) {
|
||||
expect(contrast(tono(nombre), blanco), nombre).toBeLessThan(
|
||||
contrast(tono("--bg"), blanco)
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
it("en claro, chips y hover se ven igual que antes", () => {
|
||||
expect(claro["--chip-bg"]).toBe(claro["--bg"]);
|
||||
expect(claro["--row-hover"]).toBe(claro["--bg-subtle"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("white-label: normalización", () => {
|
||||
it("nombre vacío o nulo → default «CRM»; se recorta a 30", () => {
|
||||
expect(normalizeBranding(null).name).toBe("CRM");
|
||||
expect(normalizeBranding({ name: " " }).name).toBe("CRM");
|
||||
expect(normalizeBranding({ name: "x".repeat(50) }).name).toHaveLength(30);
|
||||
});
|
||||
|
||||
it("acento inválido → default", () => {
|
||||
expect(normalizeBranding({ accent: "azul" }).accent).toBe("#009c98");
|
||||
expect(normalizeBranding({ accent: "#3F6B66" }).accent).toBe("#3f6b66");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,46 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { buscaEnMensajes, fragmentoConCoincidencia, patronLike } from "@/lib/busqueda-mensajes";
|
||||
|
||||
const resaltado = (texto: string, q: string) =>
|
||||
fragmentoConCoincidencia(texto, q).filter((t) => t.coincide).map((t) => t.texto);
|
||||
|
||||
describe("079 — fragmento con la coincidencia resaltada", () => {
|
||||
it("resalta sobre el texto original aunque la consulta no lleve acentos", () => {
|
||||
expect(resaltado("Me pasas la CUÉNTA de Ana", "cuenta de ana")).toEqual(["CUÉNTA de Ana"]);
|
||||
expect(resaltado("la cuenta", "CUÉNTA")).toEqual(["cuenta"]);
|
||||
expect(resaltado("¿Hacen envíos a Toluca?", "envios")).toEqual(["envíos"]);
|
||||
});
|
||||
|
||||
it("la ñ cuenta como n, igual que en la base", () => {
|
||||
expect(resaltado("Quiero una piñata grande", "pinata")).toEqual(["piñata"]);
|
||||
});
|
||||
|
||||
it("recorta alrededor de la coincidencia con puntos suspensivos", () => {
|
||||
const largo = `${"palabra ".repeat(30)}cuenta de Ana ${"cola ".repeat(40)}`;
|
||||
const tramos = fragmentoConCoincidencia(largo, "cuenta");
|
||||
expect(tramos[0]!.texto.startsWith("…")).toBe(true);
|
||||
expect(tramos.at(-1)!.texto.endsWith("…")).toBe(true);
|
||||
expect(tramos.map((t) => t.texto).join("").length).toBeLessThan(largo.length);
|
||||
});
|
||||
|
||||
it("sin coincidencia devuelve el principio sin resaltar", () => {
|
||||
expect(fragmentoConCoincidencia("hola", "zzz")).toEqual([{ texto: "hola", coincide: false }]);
|
||||
});
|
||||
|
||||
it("colapsa saltos de línea", () => {
|
||||
expect(fragmentoConCoincidencia("uno\n\ndos cuenta", "cuenta").map((t) => t.texto).join("")).toBe(
|
||||
"uno dos cuenta"
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("079 — reglas", () => {
|
||||
it("escapa los comodines de LIKE", () => {
|
||||
expect(patronLike("100%_x\\")).toBe("%100\\%\\_x\\\\%");
|
||||
});
|
||||
it("busca en mensajes desde 3 caracteres, sin contar espacios", () => {
|
||||
expect(buscaEnMensajes("ho")).toBe(false);
|
||||
expect(buscaEnMensajes(" ho ")).toBe(false);
|
||||
expect(buscaEnMensajes("hol")).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,151 @@
|
||||
import { readFileSync } from "node:fs";
|
||||
import path from "node:path";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import {
|
||||
blockStartUtc,
|
||||
calendarVisible,
|
||||
coalesce,
|
||||
groupSlotsByDay,
|
||||
type DaySlot,
|
||||
} from "@/lib/time/calendar";
|
||||
|
||||
/**
|
||||
* 215 (raíz) — Los cuatro fallos que tenía la pantalla de Citas antes del
|
||||
* calendario, fijados para que no vuelvan. El cuarto (el tope de 200) se
|
||||
* prueba contra la consulta y la ruta en `bookings-rango-api.test.ts`.
|
||||
*/
|
||||
|
||||
describe("fallo 1 · bloquear usa la hora del NEGOCIO, no la del navegador", () => {
|
||||
const originalTz = process.env.TZ;
|
||||
afterEach(() => {
|
||||
if (originalTz === undefined) delete process.env.TZ;
|
||||
else process.env.TZ = originalTz;
|
||||
});
|
||||
|
||||
it("las 15:00 de Ciudad de México son las 21:00 UTC", () => {
|
||||
expect(blockStartUtc("2026-09-24", "15:00", "America/Mexico_City")).toBe(
|
||||
"2026-09-24T21:00:00.000Z"
|
||||
);
|
||||
});
|
||||
|
||||
it("la misma hora de pared en otra zona es otro instante", () => {
|
||||
expect(blockStartUtc("2026-09-24", "15:00", "Asia/Tokyo")).toBe("2026-09-24T06:00:00.000Z");
|
||||
expect(blockStartUtc("2026-09-24", "15:00", "Europe/Madrid")).toBe("2026-09-24T13:00:00.000Z");
|
||||
});
|
||||
|
||||
it("no depende de la zona del proceso (el navegador de quien mira)", () => {
|
||||
const results = ["Asia/Tokyo", "Europe/Madrid", "America/Mexico_City", "UTC"].map((tz) => {
|
||||
process.env.TZ = tz;
|
||||
return blockStartUtc("2026-09-24", "15:00", "America/Mexico_City");
|
||||
});
|
||||
expect(new Set(results)).toEqual(new Set(["2026-09-24T21:00:00.000Z"]));
|
||||
});
|
||||
|
||||
it("día u hora inexistentes no producen un instante", () => {
|
||||
expect(blockStartUtc("2026-02-31", "15:00", "America/Mexico_City")).toBeNull();
|
||||
expect(blockStartUtc("2026-09-24", "25:00", "America/Mexico_City")).toBeNull();
|
||||
expect(blockStartUtc("", "15:00", "America/Mexico_City")).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("fallo 2 · reprogramar ofrece TODA la ventana, por día", () => {
|
||||
const day = (i: number) => `2026-09-${String(21 + i).padStart(2, "0")}`;
|
||||
// 5 días × 16 huecos de 30 min = 80: antes la pantalla mostraba 12.
|
||||
const slots: DaySlot[] = Array.from({ length: 5 }, (_, d) =>
|
||||
Array.from({ length: 16 }, (_, h) => {
|
||||
const minutes = 9 * 60 + h * 30;
|
||||
const time = `${String(Math.floor(minutes / 60)).padStart(2, "0")}:${String(minutes % 60).padStart(2, "0")}`;
|
||||
return { startUtc: `${day(d)}T${time}:00.000Z`, dayIso: day(d), time };
|
||||
})
|
||||
).flat();
|
||||
|
||||
it("no recorta: los 80 huecos quedan disponibles", () => {
|
||||
const groups = groupSlotsByDay(slots);
|
||||
expect(groups).toHaveLength(5);
|
||||
expect(groups.reduce((n, [, list]) => n + list.length, 0)).toBe(80);
|
||||
expect(groups.map(([d, list]) => [d, list.length])).toEqual(
|
||||
[0, 1, 2, 3, 4].map((i) => [day(i), 16])
|
||||
);
|
||||
});
|
||||
|
||||
it("agrupa en orden de día aunque lleguen revueltos, sin reordenar las horas", () => {
|
||||
const shuffled = [...slots].reverse();
|
||||
const groups = groupSlotsByDay(shuffled);
|
||||
expect(groups.map(([d]) => d)).toEqual([0, 1, 2, 3, 4].map(day));
|
||||
expect(groups[0]?.[1][0]?.time).toBe("16:30");
|
||||
});
|
||||
|
||||
it("sin huecos, ningún día", () => {
|
||||
expect(groupSlotsByDay([])).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("fallo 3 · un evento SSE ya no recalcula la disponibilidad", () => {
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it("una ráfaga de eventos se paga con UNA recarga", () => {
|
||||
vi.useFakeTimers();
|
||||
const reload = vi.fn();
|
||||
const sse = coalesce(reload, 250);
|
||||
for (let i = 0; i < 5; i++) {
|
||||
sse.trigger();
|
||||
vi.advanceTimersByTime(100);
|
||||
}
|
||||
expect(reload).not.toHaveBeenCalled();
|
||||
vi.advanceTimersByTime(250);
|
||||
expect(reload).toHaveBeenCalledTimes(1);
|
||||
sse.trigger();
|
||||
vi.advanceTimersByTime(250);
|
||||
expect(reload).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("al desmontar, la recarga pendiente no corre", () => {
|
||||
vi.useFakeTimers();
|
||||
const reload = vi.fn();
|
||||
const sse = coalesce(reload, 250);
|
||||
sse.trigger();
|
||||
sse.cancel();
|
||||
vi.advanceTimersByTime(1000);
|
||||
expect(reload).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("la pantalla solo pide disponibilidad desde «Reprogramar»", () => {
|
||||
const dir = path.resolve(import.meta.dirname, "../../src/components/bookings");
|
||||
const read = (f: string) => readFileSync(path.join(dir, f), "utf8");
|
||||
// El cliente del calendario (lo que corre en cada evento SSE) no la pide…
|
||||
expect(read("bookings-client.tsx")).not.toContain("/api/calendar/availability");
|
||||
// …y el panel de la cita la pide una sola vez, al montar «Mover a».
|
||||
const drawer = read("booking-drawer.tsx");
|
||||
expect(drawer.match(/\/api\/calendar\/availability/g)).toHaveLength(1);
|
||||
expect(drawer).toContain("function Reschedule(");
|
||||
});
|
||||
});
|
||||
|
||||
describe("las citas del Laboratorio no ensucian el calendario", () => {
|
||||
const b = (id: string, status: string, isTest: boolean) => ({ id, status, isTest });
|
||||
const all = [
|
||||
b("real", "agendada", false),
|
||||
b("cancelada", "cancelada", false),
|
||||
b("prueba", "agendada", true),
|
||||
b("prueba-cancelada", "cancelada", true),
|
||||
];
|
||||
const ids = (xs: { id: string }[]) => xs.map((x) => x.id);
|
||||
|
||||
it("por defecto se ocultan las pruebas y las canceladas", () => {
|
||||
expect(ids(calendarVisible(all, { showCancelled: false, showTests: false }))).toEqual(["real"]);
|
||||
});
|
||||
|
||||
it("cada interruptor muestra lo suyo", () => {
|
||||
expect(ids(calendarVisible(all, { showCancelled: false, showTests: true }))).toEqual([
|
||||
"real",
|
||||
"prueba",
|
||||
]);
|
||||
expect(ids(calendarVisible(all, { showCancelled: true, showTests: false }))).toEqual([
|
||||
"real",
|
||||
"cancelada",
|
||||
]);
|
||||
expect(calendarVisible(all, { showCancelled: true, showTests: true })).toHaveLength(4);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,238 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
bookingSegments,
|
||||
clampListTo,
|
||||
datesOf,
|
||||
hhmm,
|
||||
isIsoDate,
|
||||
layoutOverlaps,
|
||||
longDayLabel,
|
||||
monthWeeks,
|
||||
offHoursBands,
|
||||
parseRangeQuery,
|
||||
rangeLabel,
|
||||
shiftRange,
|
||||
spanLabel,
|
||||
startOfWeek,
|
||||
tzOffsetLabel,
|
||||
visibleRange,
|
||||
wallClock,
|
||||
weekdayKeyOfDate,
|
||||
} from "@/lib/time/calendar";
|
||||
|
||||
/**
|
||||
* 215 — La aritmética del calendario de Citas. Lo que se prueba aquí es lo que
|
||||
* a simple vista "se ve bien" y sin embargo pinta una cita en el día o la hora
|
||||
* equivocados: la semana que empieza en lunes, el mes de seis filas, la zona
|
||||
* del negocio contra la del navegador y la cita que cruza la medianoche.
|
||||
*/
|
||||
|
||||
const MX = "America/Mexico_City";
|
||||
const NY = "America/New_York";
|
||||
const MADRID = "Europe/Madrid";
|
||||
|
||||
describe("fechas de calendario", () => {
|
||||
it("una fecha inexistente no pasa aunque Date.parse la acepte", () => {
|
||||
expect(isIsoDate("2026-09-18")).toBe(true);
|
||||
expect(isIsoDate("2026-02-31")).toBe(false);
|
||||
expect(isIsoDate("2026-9-18")).toBe(false);
|
||||
expect(isIsoDate(null)).toBe(false);
|
||||
expect(isIsoDate("2028-02-29")).toBe(true);
|
||||
});
|
||||
|
||||
it("la semana empieza en lunes, como el horario de Ajustes → Agenda", () => {
|
||||
expect(startOfWeek("2026-09-18")).toBe("2026-09-14"); // viernes → lunes
|
||||
expect(startOfWeek("2026-09-14")).toBe("2026-09-14"); // lunes → sí mismo
|
||||
expect(startOfWeek("2026-09-20")).toBe("2026-09-14"); // domingo → el lunes anterior
|
||||
expect(weekdayKeyOfDate("2026-09-20")).toBe("sun");
|
||||
});
|
||||
});
|
||||
|
||||
describe("visibleRange — qué días se ven", () => {
|
||||
it("día, semana y lista", () => {
|
||||
expect(visibleRange("dia", "2026-09-18")).toEqual({ from: "2026-09-18", to: "2026-09-18" });
|
||||
expect(visibleRange("semana", "2026-09-18")).toEqual({ from: "2026-09-14", to: "2026-09-20" });
|
||||
expect(visibleRange("lista", "2026-09-18")).toEqual({ from: "2026-09-18", to: "2026-10-17" });
|
||||
expect(visibleRange("lista", "2026-09-18", "2026-09-30")).toEqual({
|
||||
from: "2026-09-18",
|
||||
to: "2026-09-30",
|
||||
});
|
||||
});
|
||||
|
||||
it("el mes cubre semanas completas, de 4 a 6 filas", () => {
|
||||
// Septiembre 2026: el 1 es martes y el 30 miércoles → 5 filas.
|
||||
expect(visibleRange("mes", "2026-09-18")).toEqual({ from: "2026-08-31", to: "2026-10-04" });
|
||||
expect(monthWeeks("2026-09-18")).toHaveLength(5);
|
||||
// Agosto 2026: el 1 es sábado y el 31 lunes → 6 filas.
|
||||
expect(monthWeeks("2026-08-10")).toHaveLength(6);
|
||||
// Febrero 2027: empieza en lunes y tiene 28 días → 4 filas.
|
||||
expect(monthWeeks("2027-02-10")).toHaveLength(4);
|
||||
expect(monthWeeks("2026-09-18").every((w) => w.length === 7)).toBe(true);
|
||||
});
|
||||
|
||||
it("la Lista nunca pasa del máximo ni termina antes de empezar", () => {
|
||||
expect(clampListTo("2026-09-18", "2027-09-18")).toBe("2026-12-18"); // 92 días
|
||||
expect(datesOf({ from: "2026-09-18", to: clampListTo("2026-09-18", "2027-09-18") })).toHaveLength(92);
|
||||
expect(clampListTo("2026-09-18", "2026-09-01")).toBe("2026-09-18");
|
||||
expect(clampListTo("2026-09-18", "no-es-fecha")).toBe("2026-10-17");
|
||||
});
|
||||
});
|
||||
|
||||
describe("shiftRange — ‹ ›", () => {
|
||||
it("día y semana", () => {
|
||||
expect(shiftRange("dia", "2026-09-18", 1).anchor).toBe("2026-09-19");
|
||||
expect(shiftRange("semana", "2026-09-18", -1).anchor).toBe("2026-09-11");
|
||||
});
|
||||
|
||||
it("el mes salta al día 1 del mes vecino, también de diciembre a enero", () => {
|
||||
expect(shiftRange("mes", "2026-09-18", 1).anchor).toBe("2026-10-01");
|
||||
expect(shiftRange("mes", "2026-12-31", 1).anchor).toBe("2027-01-01");
|
||||
expect(shiftRange("mes", "2026-03-31", -1).anchor).toBe("2026-02-01");
|
||||
});
|
||||
|
||||
it("la Lista se desplaza su propio largo", () => {
|
||||
expect(shiftRange("lista", "2026-09-01", 1, "2026-09-10")).toEqual({
|
||||
anchor: "2026-09-11",
|
||||
listTo: "2026-09-20",
|
||||
});
|
||||
expect(shiftRange("lista", "2026-09-11", -1, "2026-09-20")).toEqual({
|
||||
anchor: "2026-09-01",
|
||||
listTo: "2026-09-10",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("etiquetas — lo que dice la barra", () => {
|
||||
it("semana en un mes, entre meses y entre años", () => {
|
||||
expect(rangeLabel("semana", "2026-09-18")).toBe("14 – 20 de sep de 2026");
|
||||
expect(rangeLabel("semana", "2026-09-30")).toBe("28 de sep – 4 de oct de 2026");
|
||||
expect(rangeLabel("semana", "2026-12-30")).toBe("28 de dic de 2026 – 3 de ene de 2027");
|
||||
});
|
||||
|
||||
it("día, mes y lista", () => {
|
||||
expect(rangeLabel("dia", "2026-09-18")).toBe("Viernes, 18 de septiembre de 2026");
|
||||
expect(rangeLabel("mes", "2026-09-18")).toBe("Septiembre de 2026");
|
||||
expect(rangeLabel("lista", "2026-09-18", "2026-10-17")).toBe("18 de sep – 17 de oct de 2026");
|
||||
expect(spanLabel({ from: "2026-09-18", to: "2026-09-18" })).toBe("18 de sep de 2026");
|
||||
expect(longDayLabel("2026-09-16")).toBe("miércoles, 16 de septiembre");
|
||||
});
|
||||
});
|
||||
|
||||
describe("wallClock y tramos — en la zona del NEGOCIO", () => {
|
||||
it("la hora de pared sale de la zona, no del proceso", () => {
|
||||
// 15:30 en México son las 21:30Z; en Madrid, las 23:30.
|
||||
expect(wallClock("2026-09-18T21:30:00.000Z", MX)).toEqual({ day: "2026-09-18", minutes: 15 * 60 + 30 });
|
||||
expect(wallClock("2026-09-18T21:30:00.000Z", MADRID)).toEqual({ day: "2026-09-18", minutes: 23 * 60 + 30 });
|
||||
// A las 02:00Z del 19 en México todavía es el 18.
|
||||
expect(wallClock("2026-09-19T02:00:00.000Z", MX).day).toBe("2026-09-18");
|
||||
expect(hhmm(15 * 60 + 5)).toBe("15:05");
|
||||
});
|
||||
|
||||
it("una cita normal es un tramo de su duración", () => {
|
||||
expect(bookingSegments("2026-09-18T16:00:00.000Z", 30, MX)).toEqual([
|
||||
{ day: "2026-09-18", startMin: 600, endMin: 630, continuesBefore: false, continuesAfter: false },
|
||||
]);
|
||||
});
|
||||
|
||||
it("la que cruza la medianoche se parte en dos días", () => {
|
||||
// 23:00 México + 120 min → 01:00 del día siguiente.
|
||||
expect(bookingSegments("2026-09-19T05:00:00.000Z", 120, MX)).toEqual([
|
||||
{ day: "2026-09-18", startMin: 1380, endMin: 1440, continuesBefore: false, continuesAfter: true },
|
||||
{ day: "2026-09-19", startMin: 0, endMin: 60, continuesBefore: true, continuesAfter: false },
|
||||
]);
|
||||
});
|
||||
|
||||
it("la que termina justo a medianoche no deja un tramo vacío al día siguiente", () => {
|
||||
expect(bookingSegments("2026-09-19T05:00:00.000Z", 60, MX)).toEqual([
|
||||
{ day: "2026-09-18", startMin: 1380, endMin: 1440, continuesBefore: false, continuesAfter: false },
|
||||
]);
|
||||
});
|
||||
|
||||
it("en el retroceso del horario de verano conserva su duración", () => {
|
||||
// Nueva York, 1 nov 2026: 01:30 (EDT) + 60 min = 01:30 (EST).
|
||||
const [seg] = bookingSegments("2026-11-01T05:30:00.000Z", 60, NY);
|
||||
expect(seg?.startMin).toBe(90);
|
||||
expect(seg?.endMin).toBe(150);
|
||||
});
|
||||
|
||||
it("el desfase se escribe como Google", () => {
|
||||
expect(tzOffsetLabel(MX, new Date("2026-09-18T12:00:00Z"))).toBe("GMT-6");
|
||||
expect(tzOffsetLabel("Asia/Kolkata", new Date("2026-09-18T12:00:00Z"))).toBe("GMT+5:30");
|
||||
expect(tzOffsetLabel("UTC", new Date("2026-09-18T12:00:00Z"))).toBe("GMT");
|
||||
});
|
||||
|
||||
it("con el reloj real (con milisegundos) el desfase sigue siendo entero", () => {
|
||||
expect(tzOffsetLabel(MX, new Date("2026-09-18T18:15:57.623Z"))).toBe("GMT-6");
|
||||
});
|
||||
});
|
||||
|
||||
describe("layoutOverlaps — lo que se solapa comparte el ancho", () => {
|
||||
it("sin solape, cada cita ocupa la columna entera", () => {
|
||||
const out = layoutOverlaps([
|
||||
{ id: "a", startMin: 600, endMin: 630 },
|
||||
{ id: "b", startMin: 630, endMin: 660 },
|
||||
]);
|
||||
expect(out.map((o) => [o.id, o.col, o.cols])).toEqual([
|
||||
["a", 0, 1],
|
||||
["b", 0, 1],
|
||||
]);
|
||||
});
|
||||
|
||||
it("dos que se tocan se reparten; la tercera reutiliza la columna libre", () => {
|
||||
const out = layoutOverlaps([
|
||||
{ id: "a", startMin: 660, endMin: 690 }, // 11:00–11:30
|
||||
{ id: "b", startMin: 675, endMin: 720 }, // 11:15–12:00
|
||||
{ id: "c", startMin: 690, endMin: 720 }, // 11:30–12:00
|
||||
]);
|
||||
const byId = Object.fromEntries(out.map((o) => [o.id, [o.col, o.cols]]));
|
||||
expect(byId).toEqual({ a: [0, 2], b: [1, 2], c: [0, 2] });
|
||||
});
|
||||
|
||||
it("un grupo aparte no hereda las columnas del anterior", () => {
|
||||
const out = layoutOverlaps([
|
||||
{ id: "a", startMin: 600, endMin: 660 },
|
||||
{ id: "b", startMin: 610, endMin: 640 },
|
||||
{ id: "c", startMin: 900, endMin: 930 },
|
||||
]);
|
||||
expect(out.find((o) => o.id === "c")).toMatchObject({ col: 0, cols: 1 });
|
||||
});
|
||||
});
|
||||
|
||||
describe("offHoursBands — lo que se sombrea", () => {
|
||||
const horario = {
|
||||
mon: [{ start: "09:00", end: "14:00" }, { start: "16:00", end: "19:00" }],
|
||||
};
|
||||
|
||||
it("horario partido: antes, entre y después", () => {
|
||||
expect(offHoursBands(horario, "2026-09-14")).toEqual([
|
||||
{ startMin: 0, endMin: 540 },
|
||||
{ startMin: 840, endMin: 960 },
|
||||
{ startMin: 1140, endMin: 1440 },
|
||||
]);
|
||||
});
|
||||
|
||||
it("un día cerrado se sombrea entero", () => {
|
||||
expect(offHoursBands(horario, "2026-09-15")).toEqual([{ startMin: 0, endMin: 1440 }]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("parseRangeQuery — ?from=&to= de /api/bookings", () => {
|
||||
it("sin parámetros, la lista de siempre", () => {
|
||||
expect(parseRangeQuery(null, null)).toEqual({ ok: true, range: null });
|
||||
});
|
||||
|
||||
it("un rango válido", () => {
|
||||
expect(parseRangeQuery("2026-09-14", "2026-09-20")).toEqual({
|
||||
ok: true,
|
||||
range: { from: "2026-09-14", to: "2026-09-20" },
|
||||
});
|
||||
});
|
||||
|
||||
it("rechaza lo que el calendario no puede pedir", () => {
|
||||
expect(parseRangeQuery("2026-09-14", null).ok).toBe(false);
|
||||
expect(parseRangeQuery("2026-02-31", "2026-03-05").ok).toBe(false);
|
||||
expect(parseRangeQuery("2026-09-20", "2026-09-14").ok).toBe(false);
|
||||
expect(parseRangeQuery("2026-01-01", "2026-04-03").ok).toBe(false); // 93 días
|
||||
expect(parseRangeQuery("2026-01-01", "2026-04-02").ok).toBe(true); // 92 días, el tope
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,177 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
claveDeEtiqueta,
|
||||
customFieldInputSchema,
|
||||
formatearValor,
|
||||
validarValor,
|
||||
validarValores,
|
||||
type CustomFieldDto,
|
||||
} from "@/lib/custom-fields";
|
||||
import {
|
||||
COLUMNAS_BASE,
|
||||
documentoPdf,
|
||||
libroExcel,
|
||||
nombreArchivo,
|
||||
tablaDeContactos,
|
||||
} from "@/lib/contacts-export";
|
||||
import { etiquetasDeTexto, normalizarEtiquetas } from "@/lib/contact-extras";
|
||||
import type { ContactDto } from "@/lib/types";
|
||||
|
||||
/** Campos personalizados y exportación de Contactos (Excel / PDF). */
|
||||
|
||||
function campo(p: Partial<CustomFieldDto>): CustomFieldDto {
|
||||
return {
|
||||
id: "cf_1",
|
||||
targetEntity: "contact",
|
||||
key: "campo",
|
||||
label: "Campo",
|
||||
fieldType: "text",
|
||||
options: [],
|
||||
required: false,
|
||||
position: 0,
|
||||
...p,
|
||||
};
|
||||
}
|
||||
|
||||
const MEDIDA = campo({ id: "cf_m", key: "medida", label: "Medida (cm)", fieldType: "number", position: 1 });
|
||||
const MATERIAL = campo({
|
||||
id: "cf_mat",
|
||||
key: "material",
|
||||
label: "Material",
|
||||
fieldType: "select",
|
||||
options: ["Acrílico", "Neón LED"],
|
||||
required: true,
|
||||
position: 0,
|
||||
});
|
||||
const ANTICIPO = campo({ id: "cf_a", key: "anticipo", label: "Anticipo", fieldType: "currency", position: 2 });
|
||||
const FECHA = campo({ id: "cf_f", key: "evento", label: "Evento", fieldType: "date", position: 3 });
|
||||
const URGENTE = campo({ id: "cf_u", key: "urgente", label: "Urgente", fieldType: "boolean", position: 4 });
|
||||
const EXTRAS = campo({
|
||||
id: "cf_x",
|
||||
key: "extras",
|
||||
label: "Extras",
|
||||
fieldType: "multiselect",
|
||||
options: ["Instalación", "Diseño"],
|
||||
position: 5,
|
||||
});
|
||||
|
||||
describe("campos personalizados", () => {
|
||||
it("la clave sale de la etiqueta, sin acentos ni símbolos", () => {
|
||||
expect(claveDeEtiqueta("Medida del letrero (cm)")).toBe("medida_del_letrero_cm");
|
||||
expect(claveDeEtiqueta("¿Ubicación?")).toBe("ubicacion");
|
||||
expect(claveDeEtiqueta("!!!")).toBe("campo");
|
||||
});
|
||||
|
||||
it("una lista sin opciones no se puede crear", () => {
|
||||
expect(customFieldInputSchema.safeParse({ label: "Material", fieldType: "select", options: [] }).success).toBe(false);
|
||||
const ok = customFieldInputSchema.parse({ label: "Material", fieldType: "select", options: ["A", "A", "B"] });
|
||||
expect(ok.options).toEqual(["A", "B"]);
|
||||
expect(ok.key).toBe("material");
|
||||
});
|
||||
|
||||
it("valida cada tipo y normaliza lo que manda un formulario", () => {
|
||||
expect(validarValor(MEDIDA, "12,5")).toEqual({ ok: true, value: 12.5 });
|
||||
expect(validarValor(MEDIDA, "abc").ok).toBe(false);
|
||||
expect(validarValor(ANTICIPO, 150_050)).toEqual({ ok: true, value: 150_050 });
|
||||
expect(validarValor(ANTICIPO, 10.5).ok).toBe(false);
|
||||
expect(validarValor(FECHA, "2026-12-04")).toEqual({ ok: true, value: "2026-12-04" });
|
||||
expect(validarValor(FECHA, "04/12/2026").ok).toBe(false);
|
||||
expect(validarValor(URGENTE, "sí")).toEqual({ ok: true, value: true });
|
||||
expect(validarValor(MATERIAL, "Madera").ok).toBe(false);
|
||||
expect(validarValor(EXTRAS, ["Diseño", "Diseño"])).toEqual({ ok: true, value: ["Diseño"] });
|
||||
expect(validarValor(MEDIDA, "")).toEqual({ ok: true, value: null });
|
||||
});
|
||||
|
||||
it("rechaza claves desconocidas y exige obligatorios en el alta", () => {
|
||||
const campos = [MATERIAL, MEDIDA];
|
||||
const r = validarValores(campos, { medida: 10, inventado: "x" }, true);
|
||||
expect(r.ok).toBe(false);
|
||||
if (!r.ok) {
|
||||
expect(r.errors).toContain("Campo desconocido: inventado");
|
||||
expect(r.errors).toContain("Material es obligatorio");
|
||||
}
|
||||
expect(validarValores(campos, { medida: 10 }, false).ok).toBe(true);
|
||||
});
|
||||
|
||||
it("formatea para pantalla y exportación", () => {
|
||||
expect(formatearValor(URGENTE, true)).toBe("Sí");
|
||||
expect(formatearValor(FECHA, "2026-12-04")).toBe("04/12/2026");
|
||||
expect(formatearValor(EXTRAS, ["A", "B"])).toBe("A, B");
|
||||
expect(formatearValor(ANTICIPO, 150_050, "MXN")).toContain("1,500.50");
|
||||
expect(formatearValor(MEDIDA, null)).toBe("");
|
||||
});
|
||||
});
|
||||
|
||||
describe("etiquetas", () => {
|
||||
it("se separan por coma, sin vacíos ni duplicados (sin importar mayúsculas)", () => {
|
||||
expect(etiquetasDeTexto("neón, Urgente, NEÓN, , sucursal centro")).toEqual(["neón", "Urgente", "sucursal centro"]);
|
||||
expect(normalizarEtiquetas(Array.from({ length: 30 }, (_, i) => `t${i}`))).toHaveLength(20);
|
||||
});
|
||||
});
|
||||
|
||||
const CONTACTOS: ContactDto[] = [
|
||||
{
|
||||
id: "ct_1",
|
||||
name: "Ferretería La Central",
|
||||
phone: "5215550001234",
|
||||
channel: "instagram",
|
||||
stageName: "Cotización enviada",
|
||||
tags: ["neón", "urgente"],
|
||||
source: { value: "anuncio", source: "capturada" },
|
||||
amountCents: 1_250_050,
|
||||
currency: "MXN",
|
||||
lastMessageAt: "2026-12-04T15:30:00.000Z",
|
||||
customFields: { material: "Acrílico", medida: 120, extras: ["Instalación"] },
|
||||
} as unknown as ContactDto,
|
||||
{ id: "ct_2", name: "Sin datos", phone: null } as unknown as ContactDto,
|
||||
];
|
||||
|
||||
describe("exportación de Contactos", () => {
|
||||
const campos = [MEDIDA, MATERIAL, EXTRAS];
|
||||
|
||||
it("columnas base + un campo personalizado por columna, en su orden", () => {
|
||||
const t = tablaDeContactos(CONTACTOS, campos, { currency: "MXN", timeZone: "America/Mexico_City" });
|
||||
expect(t.encabezados).toEqual([...COLUMNAS_BASE, "Material", "Medida (cm)", "Extras"]);
|
||||
expect(t.filas).toHaveLength(2);
|
||||
const [f] = t.filas;
|
||||
expect(f?.[0]).toBe("Ferretería La Central");
|
||||
expect(f?.[2]).toBe("Instagram");
|
||||
expect(f?.[4]).toBe("neón, urgente");
|
||||
expect(f?.[5]).toBe("Anuncio");
|
||||
expect(f?.[6]).toContain("12,500.50");
|
||||
expect(f?.[7]).toContain("04/12/2026");
|
||||
expect(f?.slice(-3)).toEqual(["Acrílico", "120", "Instalación"]);
|
||||
});
|
||||
|
||||
it("solo exporta lo que recibe (la lista ya filtrada) y rellena vacíos", () => {
|
||||
const t = tablaDeContactos([CONTACTOS[1]!], campos);
|
||||
expect(t.filas).toHaveLength(1);
|
||||
expect(t.filas[0]?.length).toBe(t.encabezados.length);
|
||||
expect(t.filas[0]?.[2]).toBe("WhatsApp");
|
||||
});
|
||||
|
||||
it("nombre del archivo a partir de la marca", () => {
|
||||
const d = new Date("2026-12-04T12:00:00Z");
|
||||
expect(nombreArchivo("Mi CRM", "xlsx", d)).toBe("mi-crm-contactos-2026-12-04.xlsx");
|
||||
expect(nombreArchivo("Señalética & Más", "pdf", d)).toBe("senaletica-mas-contactos-2026-12-04.pdf");
|
||||
});
|
||||
|
||||
it("genera un .xlsx válido (zip PK) con la hoja Contactos", async () => {
|
||||
const t = tablaDeContactos(CONTACTOS, campos);
|
||||
const bytes = await libroExcel(t, "Mi CRM");
|
||||
expect(bytes[0]).toBe(0x50);
|
||||
expect(bytes[1]).toBe(0x4b);
|
||||
const XLSX = await import("xlsx");
|
||||
const libro = XLSX.read(bytes, { type: "array" });
|
||||
expect(libro.SheetNames).toEqual(["Contactos"]);
|
||||
const filas = XLSX.utils.sheet_to_json<string[]>(libro.Sheets.Contactos!, { header: 1 });
|
||||
expect(filas[0]).toEqual(t.encabezados);
|
||||
expect(filas).toHaveLength(3);
|
||||
});
|
||||
|
||||
it("genera un PDF válido", async () => {
|
||||
const bytes = await documentoPdf(tablaDeContactos(CONTACTOS, campos), "Mi CRM", new Date("2026-12-04T12:00:00Z"));
|
||||
expect(new TextDecoder().decode(bytes.slice(0, 5))).toBe("%PDF-");
|
||||
expect(bytes.length).toBeGreaterThan(1000);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,165 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
/**
|
||||
* 016 — El evento que sale hacia Meta.
|
||||
*
|
||||
* Estos tests existen por un motivo muy concreto: el modo de fallar de
|
||||
* `POST {dataset}/events` es un **200 con `events_received: 0`**. Un campo mal
|
||||
* puesto se ve exactamente igual que uno bien puesto, así que la forma del
|
||||
* payload y la lectura del acuse se fijan aquí, donde sí se puede afirmar.
|
||||
*/
|
||||
|
||||
const graphRequest = vi.fn();
|
||||
|
||||
vi.mock("@/lib/meta/client", async (importOriginal) => {
|
||||
const original = await importOriginal<typeof import("@/lib/meta/client")>();
|
||||
return { ...original, graphRequest };
|
||||
});
|
||||
|
||||
const { buildEventPayload, sendBusinessMessagingEvent, isMetaBusinessMessagingEvent } =
|
||||
await import("@/lib/meta/capi");
|
||||
|
||||
const EVENT = {
|
||||
eventName: "QualifiedLead",
|
||||
eventTime: 1787000000,
|
||||
ctwaClid: "ARAaB_clic",
|
||||
wabaId: "WABA-1",
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
graphRequest.mockReset();
|
||||
});
|
||||
|
||||
describe("buildEventPayload", () => {
|
||||
it("arma el evento de mensajería con los campos que Meta exige", () => {
|
||||
const body = buildEventPayload(EVENT) as {
|
||||
data: Record<string, unknown>[];
|
||||
partner_agent: string;
|
||||
};
|
||||
const event = body.data[0]!;
|
||||
|
||||
expect(event.event_name).toBe("QualifiedLead");
|
||||
expect(event.event_time).toBe(1787000000);
|
||||
expect(event.action_source).toBe("business_messaging");
|
||||
expect(event.messaging_channel).toBe("whatsapp");
|
||||
expect(event.user_data).toEqual({
|
||||
ctwa_clid: "ARAaB_clic",
|
||||
whatsapp_business_account_id: "WABA-1",
|
||||
});
|
||||
// Quién integró el evento: el proyecto, no el negocio ni una agencia.
|
||||
expect(body.partner_agent).toBe("vocero-crm");
|
||||
});
|
||||
|
||||
it("hacia Meta no viaja NADA personal del contacto", () => {
|
||||
const body = buildEventPayload(EVENT) as {
|
||||
data: Record<string, unknown>[];
|
||||
};
|
||||
const userData = body.data[0]!.user_data as Record<string, unknown>;
|
||||
// `user_data` es el sobre donde Meta espera datos de persona: aquí solo
|
||||
// lleva el identificador del clic y el de la cuenta del negocio.
|
||||
expect(Object.keys(userData).sort()).toEqual([
|
||||
"ctwa_clid",
|
||||
"whatsapp_business_account_id",
|
||||
]);
|
||||
const raw = JSON.stringify(body);
|
||||
expect(raw).not.toContain("phone");
|
||||
expect(raw).not.toContain("email");
|
||||
expect(raw).not.toContain("\"name\"");
|
||||
});
|
||||
|
||||
it("incluye custom_data cuando lo hay, y lo omite cuando está vacío", () => {
|
||||
const con = buildEventPayload({
|
||||
...EVENT,
|
||||
customData: { lead_stage: "qualified" },
|
||||
}) as { data: Record<string, unknown>[] };
|
||||
expect(con.data[0]!.custom_data).toEqual({ lead_stage: "qualified" });
|
||||
|
||||
const sin = buildEventPayload({ ...EVENT, customData: {} }) as {
|
||||
data: Record<string, unknown>[];
|
||||
};
|
||||
// Un `custom_data: {}` no aporta nada reglable y ensucia el payload que
|
||||
// uno inspecciona cuando algo falla.
|
||||
expect(sin.data[0]!.custom_data).toBeUndefined();
|
||||
});
|
||||
|
||||
it("el valor de una venta viaja en unidades de la moneda", () => {
|
||||
const body = buildEventPayload({
|
||||
...EVENT,
|
||||
eventName: "Purchase",
|
||||
customData: { lead_stage: "won", value: 450.5, currency: "MXN" },
|
||||
}) as { data: Record<string, unknown>[] };
|
||||
expect(body.data[0]!.custom_data).toEqual({
|
||||
lead_stage: "won",
|
||||
value: 450.5,
|
||||
currency: "MXN",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("catálogo cerrado", () => {
|
||||
it("reconoce los nombres de Meta y rechaza los inventados", () => {
|
||||
expect(isMetaBusinessMessagingEvent("QualifiedLead")).toBe(true);
|
||||
expect(isMetaBusinessMessagingEvent("Purchase")).toBe(true);
|
||||
// El nombre de dominio del fork del que viene esta idea: NO existe en Meta.
|
||||
expect(isMetaBusinessMessagingEvent("LeadQualified")).toBe(false);
|
||||
expect(isMetaBusinessMessagingEvent("SessionBooked")).toBe(false);
|
||||
});
|
||||
|
||||
it("un nombre fuera del catálogo falla ANTES de salir a la red", async () => {
|
||||
await expect(
|
||||
sendBusinessMessagingEvent({
|
||||
datasetId: "ds_1",
|
||||
token: "tok",
|
||||
event: { ...EVENT, eventName: "LeadQualified" },
|
||||
})
|
||||
).rejects.toThrow(/catálogo/);
|
||||
expect(graphRequest).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe("el acuse de Meta", () => {
|
||||
it("con events_received >= 1 el evento cuenta como enviado", async () => {
|
||||
graphRequest.mockResolvedValue({
|
||||
events_received: 1,
|
||||
fbtrace_id: "Aki123",
|
||||
});
|
||||
const ack = await sendBusinessMessagingEvent({
|
||||
datasetId: "ds_1",
|
||||
token: "tok",
|
||||
event: EVENT,
|
||||
});
|
||||
expect(ack.eventsReceived).toBe(1);
|
||||
expect(ack.fbTraceId).toBe("Aki123");
|
||||
expect(graphRequest).toHaveBeenCalledWith(
|
||||
"ds_1/events",
|
||||
expect.objectContaining({ method: "POST", token: "tok" })
|
||||
);
|
||||
});
|
||||
|
||||
it("un 200 con events_received: 0 es un FALLO, no un envío", async () => {
|
||||
// Meta responde 200 aunque descarte el evento. Sin mirar el acuse,
|
||||
// "enviado" solo significaría "no hubo error HTTP".
|
||||
graphRequest.mockResolvedValue({
|
||||
events_received: 0,
|
||||
fbtrace_id: "AkiZZZ",
|
||||
});
|
||||
await expect(
|
||||
sendBusinessMessagingEvent({
|
||||
datasetId: "ds_1",
|
||||
token: "tok",
|
||||
event: EVENT,
|
||||
})
|
||||
).rejects.toThrow(/events_received=0/);
|
||||
});
|
||||
|
||||
it("una respuesta sin el campo tampoco se toma por buena", async () => {
|
||||
graphRequest.mockResolvedValue({});
|
||||
await expect(
|
||||
sendBusinessMessagingEvent({
|
||||
datasetId: "ds_1",
|
||||
token: "tok",
|
||||
event: EVENT,
|
||||
})
|
||||
).rejects.toThrow(/events_received=0/);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,78 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { CHANNEL_LABEL, CHANNEL_ORDER, isChannel } from "@/lib/channels";
|
||||
import { parseChannels } from "@/server/channels/enabled";
|
||||
import { capabilitiesFor, textFits } from "@/server/channels/capabilities";
|
||||
import { channelMark } from "@/components/channel-badge";
|
||||
|
||||
describe("CHANNELS: qué bandejas enciende la instancia (ADR-001)", () => {
|
||||
it("sin la variable, la instancia es de un solo canal", () => {
|
||||
expect([...parseChannels(undefined)]).toEqual(["whatsapp"]);
|
||||
expect([...parseChannels("")]).toEqual(["whatsapp"]);
|
||||
});
|
||||
|
||||
it("enciende lo que se le pida, con espacios y mayúsculas de por medio", () => {
|
||||
const on = parseChannels(" Instagram , WHATSAPP ");
|
||||
expect(on.has("instagram")).toBe(true);
|
||||
expect(on.has("whatsapp")).toBe(true);
|
||||
});
|
||||
|
||||
it("WhatsApp no se puede apagar: es el canal por el que existe el producto", () => {
|
||||
expect(parseChannels("instagram").has("whatsapp")).toBe(true);
|
||||
});
|
||||
|
||||
it("un canal que no existe se ignora, no tumba el arranque", () => {
|
||||
const on = parseChannels("telegram,instagram,,");
|
||||
expect([...on].sort()).toEqual(["instagram", "whatsapp"]);
|
||||
});
|
||||
|
||||
it("isChannel es la única lista: no hay uniones sueltas por ahí", () => {
|
||||
expect(isChannel("whatsapp")).toBe(true);
|
||||
expect(isChannel("instagram")).toBe(true);
|
||||
expect(isChannel("telegram")).toBe(false);
|
||||
expect(isChannel("")).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("capacidades por canal", () => {
|
||||
it("el nombre visible sale de un solo lugar", () => {
|
||||
for (const ch of CHANNEL_ORDER) {
|
||||
expect(capabilitiesFor(ch).label).toBe(CHANNEL_LABEL[ch]);
|
||||
}
|
||||
});
|
||||
|
||||
it("un canal desconocido cae en WhatsApp en vez de reventar", () => {
|
||||
const caps = capabilitiesFor("telegram" as never);
|
||||
expect(caps.label).toBe(CHANNEL_LABEL.whatsapp);
|
||||
});
|
||||
|
||||
it("el límite de Instagram es en BYTES: los acentos cuentan doble", () => {
|
||||
// 600 acentos = 1200 bytes. Contando caracteres esto pasaría, y Meta
|
||||
// rechazaría el envío con un 400 que el operador no sabría leer.
|
||||
expect(textFits("instagram", "é".repeat(600))).toBe(false);
|
||||
expect(textFits("instagram", "a".repeat(600))).toBe(true);
|
||||
expect(textFits("instagram", "a".repeat(1001))).toBe(false);
|
||||
});
|
||||
|
||||
it("WhatsApp declara su límite de 4,096 caracteres, que antes vivía en el esquema de la API", () => {
|
||||
// 022: el tope dejó de ser uno global para todos los canales (TikTok
|
||||
// admite 6,000), así que el de WhatsApp se declara aquí. Se cuenta en
|
||||
// caracteres: 4,096 acentos son 8,192 bytes y caben.
|
||||
expect(textFits("whatsapp", "a".repeat(4096))).toBe(true);
|
||||
expect(textFits("whatsapp", "é".repeat(4096))).toBe(true);
|
||||
expect(textFits("whatsapp", "a".repeat(5000))).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("distintivo de bandeja", () => {
|
||||
it("todo canal del catálogo tiene su marca dibujada", () => {
|
||||
// Sin esto, agregar un canal y olvidar su glifo no rompe nada: el
|
||||
// distintivo devuelve null y la bandeja se ve como si no tuviera canal.
|
||||
for (const ch of CHANNEL_ORDER) {
|
||||
expect(channelMark(ch)).not.toBeNull();
|
||||
}
|
||||
});
|
||||
|
||||
it("un canal desconocido no pinta nada en vez de tumbar la lista", () => {
|
||||
expect(channelMark("telegram" as never)).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,82 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { CIERRE_MAX_MS, QUIETUD_MS, esperarCalma } from "@/server/lab/cierre-de-turno";
|
||||
|
||||
/**
|
||||
* 071 — El turno del cerebro se cierra cuando deja de pasar algo, no tras un
|
||||
* margen fijo. Reloj simulado: `dormir` avanza el tiempo, y la huella es lo
|
||||
* que el cerebro ya hizo a esa hora.
|
||||
*/
|
||||
function cerebro(eventos: { a: number; que: string }[]) {
|
||||
let t = 0;
|
||||
const huella = async () =>
|
||||
eventos
|
||||
.filter((e) => e.a <= t)
|
||||
.map((e) => e.que)
|
||||
.join(",");
|
||||
return {
|
||||
huella,
|
||||
opciones: {
|
||||
ahora: () => t,
|
||||
dormir: async (ms: number) => {
|
||||
t += ms;
|
||||
},
|
||||
},
|
||||
tiempo: () => t,
|
||||
};
|
||||
}
|
||||
|
||||
describe("esperarCalma", () => {
|
||||
it("un mensaje y el traspaso 2.9 s después: espera al traspaso", async () => {
|
||||
// t=0 es cuando el turno ya vio el mensaje.
|
||||
const c = cerebro([
|
||||
{ a: 0, que: "mensaje" },
|
||||
{ a: 2_900, que: "traspaso" },
|
||||
]);
|
||||
const vistas: string[] = [];
|
||||
const motivo = await esperarCalma(async () => {
|
||||
const h = await c.huella();
|
||||
vistas.push(h);
|
||||
return h;
|
||||
}, c.opciones);
|
||||
expect(motivo).toBe("calma");
|
||||
expect(vistas.at(-1)).toBe("mensaje,traspaso");
|
||||
// Cerró una ventana completa después del traspaso, no antes.
|
||||
expect(c.tiempo()).toBeGreaterThanOrEqual(2_900 + QUIETUD_MS);
|
||||
});
|
||||
|
||||
it("traspasa primero y se despide después: la despedida entra en el turno", async () => {
|
||||
const c = cerebro([
|
||||
{ a: 0, que: "traspaso" },
|
||||
{ a: 1_200, que: "despedida" },
|
||||
]);
|
||||
let ultima = "";
|
||||
await esperarCalma(async () => (ultima = await c.huella()), c.opciones);
|
||||
expect(ultima).toBe("traspaso,despedida");
|
||||
});
|
||||
|
||||
it("sin novedades, cierra a los QUIETUD_MS", async () => {
|
||||
const c = cerebro([{ a: 0, que: "mensaje" }]);
|
||||
expect(await esperarCalma(c.huella, c.opciones)).toBe("calma");
|
||||
expect(c.tiempo()).toBeGreaterThanOrEqual(QUIETUD_MS);
|
||||
expect(c.tiempo()).toBeLessThan(QUIETUD_MS + 1_000);
|
||||
});
|
||||
|
||||
it("un cerebro que no para de escribir se corta al tope", async () => {
|
||||
const eventos = Array.from({ length: 200 }, (_, i) => ({ a: i * 1_000, que: `m${i}` }));
|
||||
const c = cerebro(eventos);
|
||||
expect(await esperarCalma(c.huella, c.opciones)).toBe("tope");
|
||||
expect(c.tiempo()).toBeGreaterThanOrEqual(CIERRE_MAX_MS);
|
||||
expect(c.tiempo()).toBeLessThan(CIERRE_MAX_MS + 1_000);
|
||||
});
|
||||
|
||||
it("varios mensajes seguidos extienden la ventana", async () => {
|
||||
const c = cerebro([
|
||||
{ a: 0, que: "uno" },
|
||||
{ a: 3_000, que: "dos" },
|
||||
{ a: 6_500, que: "tres" },
|
||||
]);
|
||||
let ultima = "";
|
||||
expect(await esperarCalma(async () => (ultima = await c.huella()), c.opciones)).toBe("calma");
|
||||
expect(ultima).toBe("uno,dos,tres");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,107 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { GOOGLE_SCOPE, googleConnector } from "@/server/agenda/connectors/google";
|
||||
import { clearGoogleTokenCache } from "@/server/agenda/connectors/google-credentials";
|
||||
|
||||
/**
|
||||
* 015 / issue #50, puntos 2 y 3 — Los dos fallos del conector de Google que
|
||||
* hacen que conectarlo parezca roto cuando no lo está.
|
||||
*
|
||||
* Los dos se comprueban por la FRONTERA de red: lo que importa no es cómo se
|
||||
* llame la función interna, sino a qué endpoint se llama y cuántas veces se
|
||||
* pide el token. Un test acoplado a los nombres pasaría con el bug puesto en
|
||||
* cuanto alguien renombrara algo.
|
||||
*/
|
||||
|
||||
const CREDS = {
|
||||
clientId: "cid",
|
||||
clientSecret: "secreto-1",
|
||||
refreshToken: "refresh-1",
|
||||
calendarId: "primary",
|
||||
} as never;
|
||||
|
||||
let llamadas: string[] = [];
|
||||
|
||||
function responder(url: string): Response {
|
||||
llamadas.push(url);
|
||||
if (url.includes("/token")) {
|
||||
return new Response(
|
||||
JSON.stringify({ access_token: `tok-${llamadas.length}`, expires_in: 3600 }),
|
||||
{ status: 200 }
|
||||
);
|
||||
}
|
||||
return new Response(JSON.stringify({ summary: "Mi calendario" }), {
|
||||
status: 200,
|
||||
});
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
llamadas = [];
|
||||
clearGoogleTokenCache();
|
||||
// `getEnv()` valida el entorno entero: sin lo mínimo, el conector falla
|
||||
// antes de tocar la red y el test mediría otra cosa.
|
||||
vi.stubEnv("APP_BASE_URL", "http://localhost:3000");
|
||||
vi.stubEnv("DATABASE_URL", "postgresql://t:t@localhost:5432/t");
|
||||
vi.stubEnv("BETTER_AUTH_SECRET", "secret-de-test-suficiente");
|
||||
vi.stubEnv("ENCRYPTION_KEY", Buffer.alloc(32, 3).toString("base64"));
|
||||
vi.stubEnv("META_WEBHOOK_VERIFY_TOKEN", "verify-test");
|
||||
vi.stubEnv("GOOGLE_OAUTH_BASE_URL", "https://oauth.test");
|
||||
vi.stubEnv("GOOGLE_CAL_BASE_URL", "https://cal.test");
|
||||
globalThis.fetch = ((url: string) =>
|
||||
Promise.resolve(responder(String(url)))) as typeof fetch;
|
||||
});
|
||||
|
||||
describe("punto 2 — la prueba de conexión cabe en el scope documentado", () => {
|
||||
/**
|
||||
* `GET /calendars/{id}` es `Calendars.Get`, y Google solo lo concede con
|
||||
* `calendar.readonly` o superior. Con el scope que este conector pide de
|
||||
* verdad, esa llamada devolvía 403 ACCESS_TOKEN_SCOPE_INSUFFICIENT: la
|
||||
* conexión funcionaba y su propia prueba fallaba.
|
||||
*/
|
||||
it("lista eventos en vez de leer el calendario", async () => {
|
||||
const r = await googleConnector.testConnection!(CREDS);
|
||||
expect(r.ok).toBe(true);
|
||||
|
||||
const api = llamadas.filter((u) => !u.includes("/token"));
|
||||
expect(api).toHaveLength(1);
|
||||
expect(api[0]).toContain("/events");
|
||||
// La llamada que exigía más permiso del documentado.
|
||||
expect(api[0]).not.toMatch(/\/calendars\/[^/]+$/);
|
||||
});
|
||||
|
||||
it("y el scope que se pide sigue siendo el mínimo", () => {
|
||||
// Si algún día hiciera falta `readonly`, esta prueba obliga a decirlo aquí
|
||||
// y en la guía de la pantalla, en vez de descubrirlo con un 403.
|
||||
expect(GOOGLE_SCOPE).toBe("https://www.googleapis.com/auth/calendar.events");
|
||||
});
|
||||
});
|
||||
|
||||
describe("punto 3 — el caché del token distingue credenciales", () => {
|
||||
it("las mismas credenciales reutilizan el token (el caché sirve)", async () => {
|
||||
await googleConnector.testConnection!(CREDS);
|
||||
await googleConnector.testConnection!(CREDS);
|
||||
expect(llamadas.filter((u) => u.includes("/token"))).toHaveLength(1);
|
||||
});
|
||||
|
||||
/**
|
||||
* El síntoma real: tras regenerar el refresh token, la prueba seguía
|
||||
* devolviendo el MISMO error, palabra por palabra, durante una hora. El
|
||||
* operador concluye que el token nuevo también está mal.
|
||||
*/
|
||||
it("un refresh token distinto pide un token NUEVO, sin esperar a que expire", async () => {
|
||||
await googleConnector.testConnection!(CREDS);
|
||||
await googleConnector.testConnection!({
|
||||
...(CREDS as object),
|
||||
refreshToken: "refresh-2",
|
||||
} as never);
|
||||
expect(llamadas.filter((u) => u.includes("/token"))).toHaveLength(2);
|
||||
});
|
||||
|
||||
it("y cambiar solo el secreto también cuenta", async () => {
|
||||
await googleConnector.testConnection!(CREDS);
|
||||
await googleConnector.testConnection!({
|
||||
...(CREDS as object),
|
||||
clientSecret: "secreto-2",
|
||||
} as never);
|
||||
expect(llamadas.filter((u) => u.includes("/token"))).toHaveLength(2);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,59 @@
|
||||
import { readdirSync, readFileSync, statSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
/**
|
||||
* Vigilancia: un `ON CONFLICT` sobre `contact` tiene que nombrar EXACTAMENTE
|
||||
* las columnas del índice único.
|
||||
*
|
||||
* Existe por un fallo real: la feature 014 cambió el índice de
|
||||
* `(organization_id, wa_identity)` a `(organization_id, channel, wa_identity)`
|
||||
* y dejó dos `onConflictDoNothing` apuntando al índice viejo. Postgres no falla
|
||||
* al compilar ni al arrancar: falla en la petición, con
|
||||
* "no unique or exclusion constraint matching the ON CONFLICT specification".
|
||||
*
|
||||
* El resultado fue que el Laboratorio y el alta manual de contactos quedaron
|
||||
* rotos en `main` sin que ninguna prueba lo notara — porque ninguna los
|
||||
* ejercitaba contra una base real. Este test es más barato que volver a
|
||||
* descubrirlo en producción.
|
||||
*/
|
||||
|
||||
const CONTACT_INDEX_COLUMNS = ["organizationId", "channel", "waIdentity"];
|
||||
|
||||
function tsFilesUnder(dir: string): string[] {
|
||||
const out: string[] = [];
|
||||
for (const entry of readdirSync(dir)) {
|
||||
const full = join(dir, entry);
|
||||
if (statSync(full).isDirectory()) out.push(...tsFilesUnder(full));
|
||||
else if (/\.tsx?$/.test(entry)) out.push(full);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
describe("ON CONFLICT sobre contact", () => {
|
||||
it("nombra las tres columnas del índice único, en todos los sitios", () => {
|
||||
const offenders: string[] = [];
|
||||
|
||||
for (const file of tsFilesUnder(join(process.cwd(), "src"))) {
|
||||
const source = readFileSync(file, "utf8");
|
||||
if (!source.includes("schema.contact.waIdentity")) continue;
|
||||
|
||||
// Solo interesan los `target: [...]` de un onConflict.
|
||||
const targets = source.matchAll(/target:\s*\[([^\]]*)\]/g);
|
||||
for (const match of targets) {
|
||||
const body = match[1] ?? "";
|
||||
if (!body.includes("schema.contact.waIdentity")) continue;
|
||||
const faltantes = CONTACT_INDEX_COLUMNS.filter(
|
||||
(col) => !body.includes(`schema.contact.${col}`)
|
||||
);
|
||||
if (faltantes.length > 0) {
|
||||
offenders.push(
|
||||
`${file.replace(process.cwd(), "")} — le falta: ${faltantes.join(", ")}`
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
expect(offenders).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,329 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { CONNECTOR_META, CONNECTOR_ORDER } from "@/lib/agenda-connectors";
|
||||
import { enlaceFijoConnector } from "@/server/agenda/connectors/enlace-fijo";
|
||||
import { zoomConnector, ZOOM_SCOPES } from "@/server/agenda/connectors/zoom";
|
||||
import { googleConnector } from "@/server/agenda/connectors/google";
|
||||
import { ConnectorError } from "@/server/agenda/connectors/types";
|
||||
import { clearZoomTokenCache } from "@/server/agenda/connectors/zoom-credentials";
|
||||
import { clearGoogleTokenCache } from "@/server/agenda/connectors/google-credentials";
|
||||
|
||||
/**
|
||||
* 015 — La suite de contrato de conectores.
|
||||
*
|
||||
* Es la misma para todos a propósito: agregar un conector en un fork significa
|
||||
* pasar ESTAS pruebas, no inventarse las suyas. Lo que se fija aquí son las
|
||||
* cuatro operaciones y las dos reglas que el motor da por hechas: borrar es
|
||||
* idempotente, y mover conserva el enlace.
|
||||
*/
|
||||
|
||||
vi.mock("@/lib/env", () => ({
|
||||
getEnv: () => ({
|
||||
ZOOM_BASE_URL: "https://zoom.test/v2",
|
||||
ZOOM_OAUTH_BASE_URL: "https://oauth.zoom.test",
|
||||
GOOGLE_CAL_BASE_URL: "https://cal.google.test/v3",
|
||||
GOOGLE_OAUTH_BASE_URL: "https://oauth.google.test",
|
||||
}),
|
||||
}));
|
||||
|
||||
const REQ = {
|
||||
topic: "Cita — Ana",
|
||||
startUtc: "2026-08-05T15:00:00.000Z",
|
||||
durationMinutes: 30,
|
||||
timezone: "America/Mexico_City",
|
||||
};
|
||||
|
||||
describe("el catálogo", () => {
|
||||
it("todo conector declarado tiene su ficha para la pantalla", () => {
|
||||
for (const id of CONNECTOR_ORDER) {
|
||||
const meta = CONNECTOR_META[id];
|
||||
expect(meta.label.length).toBeGreaterThan(0);
|
||||
expect(meta.description.length).toBeGreaterThan(0);
|
||||
}
|
||||
});
|
||||
|
||||
it("existe al menos un conector SIN dependencias externas", () => {
|
||||
// Es la condición constitucional: el camino soberano tiene que existir,
|
||||
// o los conectores externos no serían opcionales de verdad.
|
||||
expect(CONNECTOR_ORDER.some((id) => !CONNECTOR_META[id].external)).toBe(true);
|
||||
});
|
||||
|
||||
it("el default no habla con nadie", () => {
|
||||
expect(CONNECTOR_META["enlace-fijo"].external).toBe(false);
|
||||
expect(enlaceFijoConnector.requiresCredentials).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("enlace-fijo", () => {
|
||||
it("entrega la sala configurada, sin id externo", async () => {
|
||||
const out = await enlaceFijoConnector.createMeeting(
|
||||
{ meetingLink: "https://meet.ejemplo.com/sala" },
|
||||
REQ
|
||||
);
|
||||
expect(out).toEqual({
|
||||
externalId: null,
|
||||
joinUrl: "https://meet.ejemplo.com/sala",
|
||||
});
|
||||
});
|
||||
|
||||
it("sin sala configurada entrega null en vez de fallar", async () => {
|
||||
// La cita se crea igual: nadie promete un enlace que no existe.
|
||||
const out = await enlaceFijoConnector.createMeeting({ meetingLink: null }, REQ);
|
||||
expect(out.joinUrl).toBeNull();
|
||||
});
|
||||
|
||||
it("mover y borrar no hacen nada, y no lanzan", async () => {
|
||||
await expect(
|
||||
enlaceFijoConnector.updateMeeting({ meetingLink: null }, "x", REQ)
|
||||
).resolves.toBeUndefined();
|
||||
await expect(
|
||||
enlaceFijoConnector.deleteMeeting({ meetingLink: null }, "x")
|
||||
).resolves.toBeUndefined();
|
||||
});
|
||||
|
||||
it("siempre está conectado: no hay nada que conectar", async () => {
|
||||
await expect(
|
||||
enlaceFijoConnector.testConnection({ meetingLink: null })
|
||||
).resolves.toMatchObject({ ok: true });
|
||||
});
|
||||
});
|
||||
|
||||
describe("zoom", () => {
|
||||
const creds = {
|
||||
accountId: "acc_1",
|
||||
clientId: "cli_1",
|
||||
clientSecret: "sec_1",
|
||||
status: "connected" as const,
|
||||
};
|
||||
const calls: { url: string; method: string; body?: unknown }[] = [];
|
||||
let fetchMock: ReturnType<typeof vi.fn>;
|
||||
|
||||
beforeEach(() => {
|
||||
clearZoomTokenCache();
|
||||
calls.length = 0;
|
||||
fetchMock = vi.fn(async (url: string, init?: RequestInit) => {
|
||||
calls.push({
|
||||
url,
|
||||
method: init?.method ?? "GET",
|
||||
body: init?.body ? JSON.parse(String(init.body)) : undefined,
|
||||
});
|
||||
if (url.includes("/oauth/token")) {
|
||||
return Response.json({ access_token: "tk", expires_in: 3600 });
|
||||
}
|
||||
if (url.endsWith("/users/me/meetings")) {
|
||||
return Response.json({ id: 91234, join_url: "https://zoom.test/j/91234" });
|
||||
}
|
||||
if (url.endsWith("/users/me")) {
|
||||
return Response.json({ email: "dueño@negocio.test" });
|
||||
}
|
||||
return new Response(null, { status: 204 });
|
||||
});
|
||||
vi.stubGlobal("fetch", fetchMock);
|
||||
});
|
||||
|
||||
afterEach(() => vi.unstubAllGlobals());
|
||||
|
||||
it("la guía de scopes incluye el de leer usuario, que usa la prueba de conexión", () => {
|
||||
// El tropiezo real: documentar solo los de reunión hace que conectar falle
|
||||
// con credenciales que en realidad sirven.
|
||||
expect(ZOOM_SCOPES).toContain("user:read:user");
|
||||
expect(ZOOM_SCOPES).toContain("meeting:write:meeting");
|
||||
});
|
||||
|
||||
it("crear manda la reunión programada y devuelve id + enlace", async () => {
|
||||
const out = await zoomConnector.createMeeting(creds, REQ);
|
||||
expect(out).toEqual({
|
||||
externalId: "91234",
|
||||
joinUrl: "https://zoom.test/j/91234",
|
||||
});
|
||||
|
||||
const create = calls.find((c) => c.url.endsWith("/users/me/meetings"));
|
||||
const body = create?.body as Record<string, unknown>;
|
||||
expect(body.type).toBe(2);
|
||||
expect(body.topic).toBe("Cita — Ana");
|
||||
expect(body.timezone).toBe("America/Mexico_City");
|
||||
// Zoom rechaza los milisegundos.
|
||||
expect(body.start_time).toBe("2026-08-05T15:00:00Z");
|
||||
});
|
||||
|
||||
it("el token se pide una vez y se reutiliza", async () => {
|
||||
await zoomConnector.createMeeting(creds, REQ);
|
||||
await zoomConnector.createMeeting(creds, REQ);
|
||||
const tokenCalls = calls.filter((c) => c.url.includes("/oauth/token"));
|
||||
expect(tokenCalls).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("mover usa el MISMO id y solo manda la hora: el enlace no cambia", async () => {
|
||||
await zoomConnector.updateMeeting(creds, "91234", {
|
||||
startUtc: "2026-08-06T16:00:00.000Z",
|
||||
durationMinutes: 45,
|
||||
timezone: "America/Mexico_City",
|
||||
});
|
||||
const patch = calls.find((c) => c.method === "PATCH");
|
||||
expect(patch?.url).toContain("/meetings/91234");
|
||||
const body = patch?.body as Record<string, unknown>;
|
||||
expect(body.start_time).toBe("2026-08-06T16:00:00Z");
|
||||
expect(body.duration).toBe(45);
|
||||
// No re-manda el tema ni los ajustes: solo se movió de hora.
|
||||
expect(body.topic).toBeUndefined();
|
||||
});
|
||||
|
||||
it("borrar algo que ya no está es ÉXITO, no error (idempotencia)", async () => {
|
||||
fetchMock.mockImplementation(async (url: string) => {
|
||||
if (url.includes("/oauth/token")) {
|
||||
return Response.json({ access_token: "tk", expires_in: 3600 });
|
||||
}
|
||||
return new Response(null, { status: 404 });
|
||||
});
|
||||
await expect(
|
||||
zoomConnector.deleteMeeting(creds, "ya-borrada")
|
||||
).resolves.toBeUndefined();
|
||||
});
|
||||
|
||||
it("probar la conexión pega a users/me", async () => {
|
||||
const out = await zoomConnector.testConnection(creds);
|
||||
expect(out).toMatchObject({ ok: true, detail: "dueño@negocio.test" });
|
||||
});
|
||||
|
||||
it("credenciales rechazadas → error de AUTENTICACIÓN, para marcar la conexión rota", async () => {
|
||||
fetchMock.mockImplementation(async () =>
|
||||
Response.json({ error: "invalid_client" }, { status: 400 })
|
||||
);
|
||||
await expect(zoomConnector.createMeeting(creds, REQ)).rejects.toSatisfy(
|
||||
(err: unknown) =>
|
||||
err instanceof ConnectorError && err.isAuthError && err.connectorId === "zoom"
|
||||
);
|
||||
});
|
||||
|
||||
it("un 400 de la API (no del token) NO se confunde con credenciales rotas", async () => {
|
||||
fetchMock.mockImplementation(async (url: string) => {
|
||||
if (url.includes("/oauth/token")) {
|
||||
return Response.json({ access_token: "tk", expires_in: 3600 });
|
||||
}
|
||||
return Response.json({ message: "start_time inválido" }, { status: 400 });
|
||||
});
|
||||
await expect(zoomConnector.createMeeting(creds, REQ)).rejects.toSatisfy(
|
||||
(err: unknown) => err instanceof ConnectorError && !err.isAuthError
|
||||
);
|
||||
});
|
||||
|
||||
it("probar la conexión nunca lanza: devuelve el fallo como dato", async () => {
|
||||
fetchMock.mockImplementation(async () => {
|
||||
throw new Error("sin red");
|
||||
});
|
||||
const out = await zoomConnector.testConnection(creds);
|
||||
expect(out.ok).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("google", () => {
|
||||
const creds = {
|
||||
clientId: "cli_1",
|
||||
clientSecret: "sec_1",
|
||||
refreshToken: "ref_1",
|
||||
calendarId: "primary",
|
||||
status: "connected" as const,
|
||||
};
|
||||
const calls: { url: string; method: string }[] = [];
|
||||
let fetchMock: ReturnType<typeof vi.fn>;
|
||||
/** Lecturas del evento antes de que la conferencia esté lista. */
|
||||
let pendingReads = 0;
|
||||
|
||||
beforeEach(() => {
|
||||
clearGoogleTokenCache();
|
||||
calls.length = 0;
|
||||
pendingReads = 0;
|
||||
fetchMock = vi.fn(async (url: string, init?: RequestInit) => {
|
||||
const method = init?.method ?? "GET";
|
||||
calls.push({ url, method });
|
||||
|
||||
if (url.endsWith("/token")) {
|
||||
return Response.json({ access_token: "tk", expires_in: 3600 });
|
||||
}
|
||||
if (method === "POST") {
|
||||
// Como Google de verdad: el evento nace SIN enlace de Meet.
|
||||
return Response.json({
|
||||
id: "evt_1",
|
||||
conferenceData: { createRequest: { status: { statusCode: "pending" } } },
|
||||
});
|
||||
}
|
||||
if (method === "GET") {
|
||||
if (pendingReads > 0) {
|
||||
pendingReads -= 1;
|
||||
return Response.json({
|
||||
id: "evt_1",
|
||||
conferenceData: {
|
||||
createRequest: { status: { statusCode: "pending" } },
|
||||
},
|
||||
});
|
||||
}
|
||||
return Response.json({
|
||||
id: "evt_1",
|
||||
summary: "Calendario de prueba",
|
||||
conferenceData: {
|
||||
entryPoints: [
|
||||
{ entryPointType: "video", uri: "https://meet.google.test/abc" },
|
||||
],
|
||||
},
|
||||
});
|
||||
}
|
||||
return new Response(null, { status: 204 });
|
||||
});
|
||||
vi.stubGlobal("fetch", fetchMock);
|
||||
});
|
||||
|
||||
afterEach(() => vi.unstubAllGlobals());
|
||||
|
||||
it("crear re-lee el evento hasta que aparece el enlace de Meet", async () => {
|
||||
// La conferencia es ASÍNCRONA: quedarse con la respuesta del insert
|
||||
// dejaría todas las citas sin enlace.
|
||||
pendingReads = 1;
|
||||
const out = await googleConnector.createMeeting(creds, REQ);
|
||||
expect(out.externalId).toBe("evt_1");
|
||||
expect(out.joinUrl).toBe("https://meet.google.test/abc");
|
||||
expect(calls.filter((c) => c.method === "GET").length).toBeGreaterThan(1);
|
||||
});
|
||||
|
||||
it("si la conferencia sigue pendiente, devuelve el evento SIN enlace en vez de fallar", async () => {
|
||||
// El motor lo traduce a "cita sin enlace, reintentable": la cita no se
|
||||
// pierde por una demora del proveedor.
|
||||
pendingReads = 99;
|
||||
const out = await googleConnector.createMeeting(creds, REQ);
|
||||
expect(out.externalId).toBe("evt_1");
|
||||
expect(out.joinUrl).toBeNull();
|
||||
});
|
||||
|
||||
it("refrescar lee el MISMO evento: reintentar no duplica la cita en el calendario", async () => {
|
||||
const out = await googleConnector.refreshMeeting!(creds, "evt_1");
|
||||
expect(out.externalId).toBe("evt_1");
|
||||
expect(out.joinUrl).toBe("https://meet.google.test/abc");
|
||||
// Ni un solo POST a events: el del token no cuenta.
|
||||
expect(
|
||||
calls.some((c) => c.method === "POST" && c.url.includes("/events"))
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("borrar tolera el 404 (idempotencia)", async () => {
|
||||
fetchMock.mockImplementation(async (url: string) => {
|
||||
if (url.endsWith("/token")) {
|
||||
return Response.json({ access_token: "tk", expires_in: 3600 });
|
||||
}
|
||||
return new Response(null, { status: 404 });
|
||||
});
|
||||
await expect(
|
||||
googleConnector.deleteMeeting(creds, "evt_borrado")
|
||||
).resolves.toBeUndefined();
|
||||
});
|
||||
|
||||
it("un refresh token revocado es error de AUTENTICACIÓN y lo explica", async () => {
|
||||
fetchMock.mockImplementation(async () =>
|
||||
Response.json({ error: "invalid_grant" }, { status: 400 })
|
||||
);
|
||||
await expect(googleConnector.createMeeting(creds, REQ)).rejects.toSatisfy(
|
||||
(err: unknown) =>
|
||||
err instanceof ConnectorError &&
|
||||
err.isAuthError &&
|
||||
// El mensaje nombra la causa más común: la app OAuth en modo prueba.
|
||||
/modo prueba/.test(err.message)
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,103 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
detectColumns,
|
||||
normalizeImportPhone,
|
||||
parseCsv,
|
||||
prepareImport,
|
||||
readImportFile,
|
||||
} from "@/lib/contact-import";
|
||||
|
||||
describe("parseCsv", () => {
|
||||
it("respeta comillas, comas dentro de un campo y BOM", () => {
|
||||
const rows = parseCsv('nombre,telefono\r\n"Pérez, Ana",5215512345678\r\n');
|
||||
expect(rows).toEqual([
|
||||
["nombre", "telefono"],
|
||||
["Pérez, Ana", "5215512345678"],
|
||||
]);
|
||||
});
|
||||
|
||||
it("detecta el punto y coma de Excel en español", () => {
|
||||
expect(parseCsv("nombre;telefono\nAna;573001234567")).toEqual([
|
||||
["nombre", "telefono"],
|
||||
["Ana", "573001234567"],
|
||||
]);
|
||||
});
|
||||
|
||||
it("descarta renglones vacíos", () => {
|
||||
expect(parseCsv("nombre,telefono\n\n,\nAna,573001234567\n")).toHaveLength(2);
|
||||
});
|
||||
});
|
||||
|
||||
describe("detectColumns", () => {
|
||||
it("encuentra nombre, apellido y teléfono sin importar acentos ni mayúsculas", () => {
|
||||
expect(detectColumns(["Nombre", "Apellido", "Email", "Teléfono"])).toEqual({
|
||||
name: 0,
|
||||
surname: 1,
|
||||
phone: 3,
|
||||
});
|
||||
});
|
||||
|
||||
it("sin columna de teléfono no adivina", () => {
|
||||
expect(detectColumns(["nombre", "monto"])).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("normalizeImportPhone", () => {
|
||||
it("normaliza el 521 de México igual que la ingesta", () => {
|
||||
expect(normalizeImportPhone("+52 1 55 1234 5678")).toEqual({
|
||||
ok: true,
|
||||
phone: "525512345678",
|
||||
});
|
||||
});
|
||||
|
||||
it("rechaza un número local: sin código de país nunca casaría con quien escriba", () => {
|
||||
expect(normalizeImportPhone("55 1234 5678")).toEqual({
|
||||
ok: false,
|
||||
reason: "sin_codigo_pais",
|
||||
});
|
||||
});
|
||||
|
||||
it("distingue vacío de inválido", () => {
|
||||
expect(normalizeImportPhone("")).toEqual({ ok: false, reason: "sin_telefono" });
|
||||
expect(normalizeImportPhone("1234567890123456")).toEqual({
|
||||
ok: false,
|
||||
reason: "telefono_invalido",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("prepareImport", () => {
|
||||
it("quita repetidos aunque vengan escritos distinto", () => {
|
||||
const { valid, problems } = prepareImport([
|
||||
{ name: "Ana", phone: "5215512345678" },
|
||||
{ name: "Ana otra vez", phone: "+52 55 1234 5678" },
|
||||
]);
|
||||
expect(valid).toEqual([{ name: "Ana", phone: "525512345678" }]);
|
||||
expect(problems).toEqual([{ line: 3, name: "Ana otra vez", reason: "repetido" }]);
|
||||
});
|
||||
|
||||
it("sin nombre usa el teléfono, como la ingesta", () => {
|
||||
expect(prepareImport([{ name: " ", phone: "573001234567" }]).valid).toEqual([
|
||||
{ name: "573001234567", phone: "573001234567" },
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("readImportFile", () => {
|
||||
it("une nombre y apellido y reporta lo que se queda fuera con su renglón", () => {
|
||||
const read = readImportFile(
|
||||
"nombre,apellido,email,telefono,pais\nAna,Pérez,a@x.com,573001234567,CO\nLuis,Ruiz,l@x.com,,MX\n"
|
||||
);
|
||||
expect(read).toEqual({
|
||||
ok: true,
|
||||
total: 2,
|
||||
valid: [{ name: "Ana Pérez", phone: "573001234567" }],
|
||||
problems: [{ line: 3, name: "Luis Ruiz", reason: "sin_telefono" }],
|
||||
});
|
||||
});
|
||||
|
||||
it("explica qué columnas faltan en vez de importar basura", () => {
|
||||
const read = readImportFile("a,b\n1,2\n");
|
||||
expect(read.ok).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,52 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
effectiveSource,
|
||||
isSourceValue,
|
||||
SOURCE_LABELS,
|
||||
SOURCE_VALUES,
|
||||
} from "@/server/contact-source";
|
||||
|
||||
/* Fuente del prospecto: lo capturado manda, lo demás queda sin identificar. */
|
||||
|
||||
describe("fuente efectiva", () => {
|
||||
it("lo que capturó el dueño se marca como capturado", () => {
|
||||
expect(effectiveSource("referido")).toEqual({
|
||||
value: "referido",
|
||||
source: "capturada",
|
||||
});
|
||||
});
|
||||
|
||||
it("sin captura queda desconocida, y se dice que fue deducida", () => {
|
||||
// No se inventa: un contacto que solo escribió por WhatsApp no dice de
|
||||
// dónde salió, y presentarlo como dato sería mentir en el reporte.
|
||||
expect(effectiveSource(null)).toEqual({
|
||||
value: "desconocida",
|
||||
source: "deducida",
|
||||
});
|
||||
});
|
||||
|
||||
it("nunca inventa: 'desconocida' no es un valor capturable", () => {
|
||||
expect(isSourceValue("desconocida")).toBe(false);
|
||||
expect(SOURCE_VALUES).not.toContain("desconocida");
|
||||
});
|
||||
});
|
||||
|
||||
describe("catálogo de fuentes", () => {
|
||||
it("es cerrado y cubre lo que el dueño pidió", () => {
|
||||
expect([...SOURCE_VALUES].sort()).toEqual(
|
||||
["anuncio", "conocido", "organico", "otro", "referido"].sort()
|
||||
);
|
||||
});
|
||||
|
||||
it("toda fuente tiene etiqueta legible, incluida la desconocida", () => {
|
||||
for (const v of [...SOURCE_VALUES, "desconocida" as const]) {
|
||||
expect(SOURCE_LABELS[v]).toBeTruthy();
|
||||
}
|
||||
});
|
||||
|
||||
it("valida entradas basura", () => {
|
||||
expect(isSourceValue("facebook")).toBe(false);
|
||||
expect(isSourceValue(null)).toBe(false);
|
||||
expect(isSourceValue("referido")).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,66 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
/**
|
||||
* 003 / #51 — Cuándo se actualiza el nombre de un contacto.
|
||||
*
|
||||
* Se ponía SOLO al crearlo, así que quien cambiaba su nombre de WhatsApp
|
||||
* seguía apareciendo con el viejo para siempre (reportado por @federicorv25:
|
||||
* cambió de «Federico» a «Federicoso» y el CRM no se enteró).
|
||||
*
|
||||
* Pero actualizarlo siempre rompería otra cosa: el operador que renombró a
|
||||
* alguien como «Juan - obra Polanco» perdería ese trabajo con el siguiente
|
||||
* mensaje. De ahí `nameSource`.
|
||||
*
|
||||
* La decisión se prueba como TABLA y sin base de datos: es una regla de
|
||||
* negocio, y enterrarla en un test de integración la haría invisible.
|
||||
*/
|
||||
|
||||
/** La regla, tal cual la aplica `getOrCreateContactByIdentity`. */
|
||||
function nombreNuevo(
|
||||
actual: { name: string; nameSource: "perfil" | "manual" },
|
||||
perfil: string | null
|
||||
): string | null {
|
||||
const delPerfil = perfil?.trim();
|
||||
if (!delPerfil) return null;
|
||||
if (actual.nameSource !== "perfil") return null;
|
||||
if (delPerfil === actual.name) return null;
|
||||
return delPerfil;
|
||||
}
|
||||
|
||||
describe("el nombre que trae WhatsApp", () => {
|
||||
it("actualiza un nombre que vino del perfil (el caso reportado)", () => {
|
||||
expect(
|
||||
nombreNuevo({ name: "Federico", nameSource: "perfil" }, "Federicoso")
|
||||
).toBe("Federicoso");
|
||||
});
|
||||
|
||||
it("NO toca un nombre que escribió una persona", () => {
|
||||
expect(
|
||||
nombreNuevo(
|
||||
{ name: "Juan - obra Polanco", nameSource: "manual" },
|
||||
"Juan"
|
||||
)
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
it("sin nombre de perfil no hay nada que hacer", () => {
|
||||
expect(nombreNuevo({ name: "Federico", nameSource: "perfil" }, null)).toBeNull();
|
||||
expect(nombreNuevo({ name: "Federico", nameSource: "perfil" }, " ")).toBeNull();
|
||||
});
|
||||
|
||||
/**
|
||||
* Sin esto, cada mensaje escribiría el mismo nombre otra vez y movería
|
||||
* `updated_at`: ruido en la base y en cualquier cosa que ordene por él.
|
||||
*/
|
||||
it("el mismo nombre no genera escritura", () => {
|
||||
expect(
|
||||
nombreNuevo({ name: "Federico", nameSource: "perfil" }, "Federico")
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
it("recorta los espacios que manda WhatsApp", () => {
|
||||
expect(
|
||||
nombreNuevo({ name: "Federico", nameSource: "perfil" }, " Federicoso ")
|
||||
).toBe("Federicoso");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,91 @@
|
||||
import { readFileSync, readdirSync, statSync } from "node:fs";
|
||||
import path from "node:path";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import tailwindConfig from "../../tailwind.config";
|
||||
|
||||
/**
|
||||
* Contraste AAA del texto secundario. `muted` es TINTA (texto), con
|
||||
* #334155 en claro y #cbd5e1 en oscuro: ≥ 7:1 sobre cada superficie del
|
||||
* prototipo (--bg, --panel, --panel2). Y nada de modificadores de opacidad
|
||||
* (`text-muted/60`) sobre las variables hex: Tailwind 3 no los puede aplicar
|
||||
* a un `var()` y el contraste se rompería en silencio.
|
||||
*/
|
||||
|
||||
const RAIZ = path.resolve(import.meta.dirname, "..", "..");
|
||||
const css = readFileSync(path.join(RAIZ, "src/app/globals.css"), "utf8").replace(/\r\n?/g, "\n");
|
||||
|
||||
function bloque(inicio: string): string {
|
||||
const i = css.indexOf(inicio);
|
||||
expect(i, inicio).toBeGreaterThanOrEqual(0);
|
||||
const fin = css.indexOf("\n }", i);
|
||||
return css.slice(i, fin);
|
||||
}
|
||||
|
||||
function variable(texto: string, nombre: string): string {
|
||||
const m = texto.match(new RegExp(`--${nombre}:\\s*(#[0-9a-fA-F]{6})\\s*;`));
|
||||
expect(m, `--${nombre}`).not.toBeNull();
|
||||
return m![1]!.toLowerCase();
|
||||
}
|
||||
|
||||
function luminancia(hex: string): number {
|
||||
const [r, g, b] = [1, 3, 5].map((i) => {
|
||||
const c = parseInt(hex.slice(i, i + 2), 16) / 255;
|
||||
return c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4;
|
||||
}) as [number, number, number];
|
||||
return 0.2126 * r + 0.7152 * g + 0.0722 * b;
|
||||
}
|
||||
|
||||
function contraste(a: string, b: string): number {
|
||||
const [x, y] = [luminancia(a), luminancia(b)].sort((p, q) => q - p) as [number, number];
|
||||
return (x + 0.05) / (y + 0.05);
|
||||
}
|
||||
|
||||
const claro = bloque(" :root {");
|
||||
const oscuro = bloque(' :root[data-theme="dark"] {');
|
||||
|
||||
describe("tokens del prototipo", () => {
|
||||
it("--muted es #334155 en claro y #cbd5e1 en oscuro", () => {
|
||||
expect(variable(claro, "muted")).toBe("#334155");
|
||||
expect(variable(oscuro, "muted")).toBe("#cbd5e1");
|
||||
});
|
||||
|
||||
it("existen todos los tokens en los dos temas", () => {
|
||||
for (const t of ["panel", "panel2", "line", "fg", "muted", "on-accent", "bubble-ai", "wa", "ig", "fb", "ok", "warn", "bad"]) {
|
||||
expect(claro, t).toMatch(new RegExp(`--${t}:`));
|
||||
expect(oscuro, t).toMatch(new RegExp(`--${t}:`));
|
||||
}
|
||||
});
|
||||
|
||||
it.each([
|
||||
["claro", claro],
|
||||
["oscuro", oscuro],
|
||||
])("tema %s: --muted y --fg ≥ 7:1 (AAA) sobre --bg, --panel y --panel2", (_n, bloqueTema) => {
|
||||
for (const tinta of ["muted", "fg"]) {
|
||||
for (const fondo of ["bg", "panel", "panel2"]) {
|
||||
const c = contraste(variable(bloqueTema, tinta), variable(bloqueTema, fondo));
|
||||
expect(c, `${tinta} sobre ${fondo}`).toBeGreaterThanOrEqual(7);
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("tailwind", () => {
|
||||
it("muted.DEFAULT = var(--muted)", () => {
|
||||
const colors = (tailwindConfig.theme?.extend?.colors ?? {}) as Record<string, unknown>;
|
||||
expect((colors.muted as { DEFAULT?: string }).DEFAULT).toBe("var(--muted)");
|
||||
});
|
||||
|
||||
it("ningún componente aplica opacidad a una variable hex del prototipo", () => {
|
||||
const prohibido = /\b(?:text|bg|border|ring|fill|stroke)-(?:muted|panel2?|line|fg|on-accent|bubble-ai|wa|ig|fb|ok|warn|bad)\/\d+/;
|
||||
const malos: string[] = [];
|
||||
const recorrer = (dir: string) => {
|
||||
for (const n of readdirSync(dir)) {
|
||||
const p = path.join(dir, n);
|
||||
if (statSync(p).isDirectory()) recorrer(p);
|
||||
else if (/\.(tsx?|css)$/.test(n) && prohibido.test(readFileSync(p, "utf8"))) malos.push(path.relative(RAIZ, p));
|
||||
}
|
||||
};
|
||||
recorrer(path.join(RAIZ, "src"));
|
||||
expect(malos).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,314 @@
|
||||
import { readFileSync } from "node:fs";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
ACCENT_PRESETS,
|
||||
DEFAULT_BRANDING,
|
||||
resolveAccentSet,
|
||||
resolveNavAccentSet,
|
||||
} from "@/lib/branding";
|
||||
|
||||
/**
|
||||
* R8 — Pisos de contraste de los dos temas, medidos sobre los tokens REALES de
|
||||
* globals.css (no sobre una copia). El tema oscuro de antes pasaba todas las
|
||||
* pruebas y aun así se veía plano: barra y página a 1.04:1, chip y panel a
|
||||
* 1.01:1. Aquí vive cada par que importa con su piso, para que un retoque de
|
||||
* color que lo rompa truene en `pnpm test` y no en una captura.
|
||||
*
|
||||
* Pisos: texto de lectura ≥ 4.5:1 (WCAG AA); iconos, rellenos y anillo de
|
||||
* foco ≥ 3:1 (1.4.11); y para superficies y bordes, el escalón mínimo que se
|
||||
* alcanza a ver (≈ 1.1–1.25:1 entre superficies, ≥ 1.4:1 un borde).
|
||||
*/
|
||||
|
||||
type Vars = Record<string, string>;
|
||||
|
||||
function luminancia(hex: string): number {
|
||||
const ch = [1, 3, 5]
|
||||
.map((i) => parseInt(hex.slice(i, i + 2), 16) / 255)
|
||||
.map((v) => (v <= 0.03928 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4));
|
||||
return 0.2126 * ch[0]! + 0.7152 * ch[1]! + 0.0722 * ch[2]!;
|
||||
}
|
||||
|
||||
function contraste(a: string, b: string): number {
|
||||
const [l1, l2] = [luminancia(a), luminancia(b)];
|
||||
return (Math.max(l1, l2) + 0.05) / (Math.min(l1, l2) + 0.05);
|
||||
}
|
||||
|
||||
/** Variables de un bloque de globals.css, con el valor sin saltos de línea. */
|
||||
function bloque(css: string, selector: string): Vars {
|
||||
const inicio = css.indexOf(selector);
|
||||
expect(inicio, `no está el bloque ${selector}`).toBeGreaterThanOrEqual(0);
|
||||
const cuerpo = css
|
||||
.slice(css.indexOf("{", inicio) + 1, css.indexOf("}", inicio))
|
||||
.replace(/\/\*[\s\S]*?\*\//g, ""); // un comentario puede nombrar un token
|
||||
return Object.fromEntries(
|
||||
[...cuerpo.matchAll(/(--[\w-]+):\s*([^;]+);/g)].map((m) => [
|
||||
m[1]!,
|
||||
m[2]!.replace(/\s+/g, " ").trim(),
|
||||
])
|
||||
);
|
||||
}
|
||||
|
||||
const css = readFileSync("src/app/globals.css", "utf8");
|
||||
const claro = bloque(css, ":root {");
|
||||
const oscuroCrudo = bloque(css, ':root[data-theme="dark"] {');
|
||||
const nav = bloque(css, ".nav-dark {");
|
||||
|
||||
/** Tokens del tema oscuro: lo que el bloque no redeclara viene de `:root`. */
|
||||
const oscuro: Vars = { ...claro, ...oscuroCrudo };
|
||||
|
||||
/** Resuelve `var(--x)` contra el mismo bloque (un nivel alcanza aquí). */
|
||||
function hex(vars: Vars, nombre: string): string {
|
||||
const v = vars[nombre];
|
||||
expect(v, `falta ${nombre}`).toBeDefined();
|
||||
const ref = /^var\((--[\w-]+)\)$/.exec(v!)?.[1];
|
||||
const valor = ref ? vars[ref] : v;
|
||||
expect(valor, `${nombre} no es un hex`).toMatch(/^#[0-9a-f]{6}$/i);
|
||||
return valor!.toLowerCase();
|
||||
}
|
||||
|
||||
/** Afirma un piso con un mensaje que dice el par y su valor. */
|
||||
function piso(vars: Vars, a: string, b: string, min: number) {
|
||||
const c = contraste(hex(vars, a), hex(vars, b));
|
||||
expect(c, `${a} sobre ${b}: ${c.toFixed(2)} (piso ${min})`).toBeGreaterThanOrEqual(min);
|
||||
}
|
||||
|
||||
/** `a` es la superficie MÁS CLARA de las dos. */
|
||||
function arriba(vars: Vars, a: string, b: string) {
|
||||
expect(
|
||||
luminancia(hex(vars, a)),
|
||||
`${a} debería ir un escalón arriba de ${b}`
|
||||
).toBeGreaterThan(luminancia(hex(vars, b)));
|
||||
}
|
||||
|
||||
describe("061 — las tarjetas se despegan del marco", () => {
|
||||
// La barra azul marino (.nav-dark) ya no es el menú: en escritorio es el riel
|
||||
// de iconos, una tarjeta más. Lo que tiene que verse es la tarjeta contra el
|
||||
// marco que asoma entre ellas.
|
||||
it("en claro y en oscuro, la tarjeta y el marco no se confunden", () => {
|
||||
piso(claro, "--bg", "--marco-2", 1.1);
|
||||
piso(oscuro, "--bg", "--marco-2", 1.15);
|
||||
arriba(oscuro, "--bg", "--marco-2");
|
||||
});
|
||||
|
||||
it("el riel activo y el botón de enviar se ven y su icono se lee", () => {
|
||||
for (const t of [claro, oscuro]) {
|
||||
piso(t, "--riel-activo", "--bg", 3);
|
||||
piso(t, "--riel-activo-texto", "--riel-activo", 4.5);
|
||||
piso(t, "--enviar", "--chat-bg", 3);
|
||||
piso(t, "--enviar-texto", "--enviar", 4.5);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("tema oscuro: escalera de superficies", () => {
|
||||
it("hueco < página < fila bajo el cursor ≈ lo que flota < chip < panel < hover", () => {
|
||||
arriba(oscuro, "--bg", "--bg-subtle");
|
||||
arriba(oscuro, "--row-hover", "--bg");
|
||||
arriba(oscuro, "--bg-raised", "--bg");
|
||||
arriba(oscuro, "--chip-bg", "--row-hover");
|
||||
arriba(oscuro, "--bg-panel", "--chip-bg");
|
||||
arriba(oscuro, "--bg-panel", "--bg-raised");
|
||||
arriba(oscuro, "--bg-hover", "--bg-panel");
|
||||
});
|
||||
|
||||
it("cada escalón se ve", () => {
|
||||
piso(oscuro, "--bg", "--bg-subtle", 1.1);
|
||||
piso(oscuro, "--row-hover", "--bg", 1.07);
|
||||
piso(oscuro, "--bg-raised", "--bg", 1.08);
|
||||
// Un botón secundario (bg-secondary) dentro de un diálogo o un cajón.
|
||||
piso(oscuro, "--bg-panel", "--bg-raised", 1.1);
|
||||
piso(oscuro, "--bg-panel", "--bg", 1.2);
|
||||
piso(oscuro, "--chip-bg", "--bg", 1.15);
|
||||
piso(oscuro, "--chip-bg", "--row-hover", 1.07);
|
||||
piso(oscuro, "--bg-hover", "--bg", 1.35);
|
||||
// El contador dentro de un chip de filtro (bg-secondary sobre bg-chip):
|
||||
// antes 1.01:1, el círculo no se veía.
|
||||
piso(oscuro, "--bg-panel", "--chip-bg", 1.1);
|
||||
// Como en claro (1.03:1), el hover de un botón secundario es sutil.
|
||||
piso(oscuro, "--bg-hover", "--bg-panel", 1.05);
|
||||
piso(oscuro, "--bg-hover", "--bg-raised", 1.25);
|
||||
// 215 — el horario no hábil contra la rejilla (bg-card = --bg).
|
||||
piso(oscuro, "--bg", "--cal-off", 1.08);
|
||||
});
|
||||
|
||||
it("los bordes separan (≥ 1.6:1 en la página, ≥ 1.4:1 en lo que flota)", () => {
|
||||
piso(oscuro, "--border", "--bg", 1.6);
|
||||
piso(oscuro, "--border", "--bg-subtle", 1.5);
|
||||
piso(oscuro, "--border", "--bg-raised", 1.4);
|
||||
piso(oscuro, "--border-strong", "--bg", 2.2);
|
||||
piso(oscuro, "--border-strong", "--bg-raised", 2);
|
||||
});
|
||||
|
||||
it("las burbujas se despegan del hilo y lo de adentro se lee", () => {
|
||||
// 061 — Cada burbuja lleva su texto, su gris (hora, cita) y sus enlaces.
|
||||
for (const t of [claro, oscuro]) {
|
||||
piso(t, "--bubble-in", "--chat-bg", 1.3);
|
||||
piso(t, "--bubble-in-text", "--bubble-in", 7);
|
||||
piso(t, "--bubble-in-muted", "--bubble-in", 4.5);
|
||||
piso(t, "--bubble-in-link", "--bubble-in", 4.5);
|
||||
piso(t, "--bubble-in-text", "--bubble-in-raised", 7);
|
||||
piso(t, "--bubble-out-text", "--bubble-out", 7);
|
||||
piso(t, "--bubble-out-muted", "--bubble-out", 4.5);
|
||||
piso(t, "--bubble-out-border", "--chat-bg", 1.15);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("tema oscuro: texto", () => {
|
||||
const superficies = [
|
||||
"--bg-subtle",
|
||||
"--bg",
|
||||
"--row-hover",
|
||||
"--bg-raised",
|
||||
"--bg-panel",
|
||||
"--chip-bg",
|
||||
"--bg-hover",
|
||||
"--accent-tint",
|
||||
];
|
||||
|
||||
it("texto, secundario y terciario pasan AA sobre TODA superficie", () => {
|
||||
// `text-3` incluido: es el de la `.kicker` (10.5px) y de las horas.
|
||||
for (const s of superficies) {
|
||||
piso(oscuro, "--text", s, 7);
|
||||
piso(oscuro, "--text-2", s, 4.5);
|
||||
piso(oscuro, "--text-3", s, 4.5);
|
||||
}
|
||||
});
|
||||
|
||||
it("text-4 alcanza para iconos (≥ 3:1), no para leer", () => {
|
||||
for (const s of ["--bg", "--bg-raised", "--bg-panel", "--accent-tint"]) {
|
||||
piso(oscuro, "--text-4", s, 3);
|
||||
}
|
||||
});
|
||||
|
||||
it("las tríadas de estado se leen sobre su propio fondo", () => {
|
||||
for (const e of ["success", "warning", "danger", "info"]) {
|
||||
piso(oscuro, `--${e}-text`, `--${e}-tint`, 4.5);
|
||||
piso(oscuro, `--${e}-text`, "--bg", 4.5);
|
||||
arriba(oscuro, `--${e}-tint`, "--bg");
|
||||
piso(oscuro, `--${e}-soft`, `--${e}-tint`, 1.3);
|
||||
}
|
||||
piso(oscuro, "--danger-fg", "--danger", 4.5);
|
||||
});
|
||||
});
|
||||
|
||||
describe("tema oscuro: acento", () => {
|
||||
const set = resolveAccentSet(DEFAULT_BRANDING.accent, "dark");
|
||||
|
||||
it("el respaldo de globals.css es el que calcula lib/branding", () => {
|
||||
// Si alguien retoca la receta y no el respaldo (o al revés), el primer
|
||||
// pintado sin white-label sale de otro color que el resto.
|
||||
expect(hex(oscuro, "--accent")).toBe(set.accent);
|
||||
expect(hex(oscuro, "--accent-hover")).toBe(set.hover);
|
||||
expect(hex(oscuro, "--accent-soft")).toBe(set.soft);
|
||||
expect(hex(oscuro, "--accent-tint")).toBe(set.tint);
|
||||
expect(hex(oscuro, "--accent-text")).toBe(set.text);
|
||||
expect(hex(oscuro, "--accent-fg")).toBe(set.fg);
|
||||
});
|
||||
|
||||
it("la fila seleccionada se ve sin leer el color del texto (tint ≥ 1.25:1)", () => {
|
||||
piso(oscuro, "--accent-tint", "--bg", 1.25);
|
||||
piso(oscuro, "--accent-soft", "--bg", 1.5);
|
||||
});
|
||||
|
||||
it("el acento rellena (≥ 3:1) y su tinta se lee (≥ 4.5:1)", () => {
|
||||
piso(oscuro, "--accent", "--bg", 3);
|
||||
piso(oscuro, "--accent-fg", "--accent", 4.5);
|
||||
for (const s of ["--bg", "--bg-raised", "--accent-tint"]) {
|
||||
piso(oscuro, "--accent-ink", s, 4.5); // una hora, un enlace, «IA»
|
||||
}
|
||||
});
|
||||
|
||||
it("el anillo de foco se ve donde hay algo enfocable (≥ 3:1)", () => {
|
||||
for (const s of ["--bg-subtle", "--bg", "--bg-raised", "--bg-panel", "--accent-tint"]) {
|
||||
piso(oscuro, "--ring", s, 3);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("tema claro: no cambia", () => {
|
||||
it("lo que flota, la tinta y el anillo del acento son los de siempre", () => {
|
||||
expect(claro["--bg-raised"]).toBe(claro["--bg"]);
|
||||
expect(claro["--accent-ink"]).toBe("var(--accent)");
|
||||
expect(claro["--ring"]).toBe("var(--accent)");
|
||||
});
|
||||
|
||||
it("la barra (.nav-dark) conserva sus valores: se ve igual en los dos temas", () => {
|
||||
// Son los que tenía cuando copiaba al tema oscuro de antes; si la barra
|
||||
// cambia, cambia también en claro, que es el tema que al dueño le gusta.
|
||||
expect(nav).toMatchObject({
|
||||
"--bg": "#0b1327",
|
||||
"--bg-subtle": "#070e20",
|
||||
"--bg-panel": "#131f3d",
|
||||
"--bg-hover": "#182750",
|
||||
"--text": "#e8eefc",
|
||||
"--text-2": "#a9b8dc",
|
||||
"--text-3": "#7688b0",
|
||||
"--border": "#263866",
|
||||
"--border-strong": "#34498a",
|
||||
"--ring": "var(--accent)",
|
||||
});
|
||||
expect(css).toMatch(/\.nav-dark \{\s*color-scheme: dark;/);
|
||||
});
|
||||
|
||||
it("dentro de la barra el texto se lee", () => {
|
||||
piso(nav, "--text", "--bg-subtle", 7);
|
||||
piso(nav, "--text-2", "--bg-hover", 4.5);
|
||||
piso(nav, "--text-3", "--bg-subtle", 4.5);
|
||||
});
|
||||
});
|
||||
|
||||
describe("tinta sobre el acento: blanca solo si pasa AA (≥ 4.5:1)", () => {
|
||||
// Presets + colores que un negocio sí elige: un verde (antes 3.3:1 con
|
||||
// blanco), un amarillo, un rojo, un morado, un gris y un azul profundo.
|
||||
const acentos = [
|
||||
...Object.keys(ACCENT_PRESETS),
|
||||
"#16a34a",
|
||||
"#f59e0b",
|
||||
"#e11d48",
|
||||
"#7c3aed",
|
||||
"#6b7280",
|
||||
"#12305a",
|
||||
"#ffee88",
|
||||
];
|
||||
|
||||
it("en los dos temas y en la barra", () => {
|
||||
for (const a of acentos) {
|
||||
for (const [donde, s] of [
|
||||
["claro", resolveAccentSet(a, "light")],
|
||||
["oscuro", resolveAccentSet(a, "dark")],
|
||||
["barra", resolveNavAccentSet(a)],
|
||||
] as const) {
|
||||
const c = contraste(s.fg, s.accent);
|
||||
expect(c, `${a} en ${donde}: ${c.toFixed(2)}`).toBeGreaterThanOrEqual(4.5);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
it("un acento claro lleva tinta oscura en vez de oscurecerse más", () => {
|
||||
const verde = resolveAccentSet("#16a34a", "light");
|
||||
expect(verde.accent).toBe("#16a34a");
|
||||
expect(verde.fg).not.toBe("#ffffff");
|
||||
});
|
||||
|
||||
it("en oscuro cada acento se despega de la página y su tinta se lee", () => {
|
||||
const pagina = hex(oscuro, "--bg");
|
||||
for (const a of acentos) {
|
||||
const s = resolveAccentSet(a, "dark");
|
||||
expect(contraste(s.accent, pagina), `${a}: relleno`).toBeGreaterThanOrEqual(3);
|
||||
expect(contraste(s.text, s.tint), `${a}: tinta sobre tint`).toBeGreaterThanOrEqual(4.5);
|
||||
expect(contraste(s.text, pagina), `${a}: tinta sobre la página`).toBeGreaterThanOrEqual(4.5);
|
||||
// El tono ayuda (un rojo se distingue del azul marino aunque su
|
||||
// luminancia se le acerque); el azul Vocero lleva su propio piso, 1.25.
|
||||
expect(contraste(s.tint, pagina), `${a}: tint`).toBeGreaterThanOrEqual(1.1);
|
||||
}
|
||||
});
|
||||
|
||||
it("en la barra, el acento se calcula contra SU fondo (≥ 3.5:1)", () => {
|
||||
for (const a of acentos) {
|
||||
const s = resolveNavAccentSet(a);
|
||||
expect(contraste(s.accent, hex(nav, "--bg")), a).toBeGreaterThanOrEqual(3.5);
|
||||
expect(contraste(s.text, s.tint), `${a}: tinta sobre tint`).toBeGreaterThanOrEqual(4.5);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,107 @@
|
||||
import { readFileSync } from "node:fs";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
purchaseCustomData,
|
||||
toConversionActivityRow,
|
||||
} from "@/server/attribution/conversions";
|
||||
|
||||
/**
|
||||
* 016 — Las piezas puras del reporte de conversiones y dos guardarraíles que
|
||||
* se leen del código fuente porque afirman AUSENCIA (que algo no se llama),
|
||||
* y eso no se observa desde fuera.
|
||||
*/
|
||||
|
||||
describe("purchaseCustomData", () => {
|
||||
it("convierte centavos a unidades de la moneda", () => {
|
||||
// La base protege el dinero en centavos enteros; Meta espera unidades.
|
||||
expect(purchaseCustomData({ amountCents: 45050, currency: "MXN" })).toEqual({
|
||||
lead_stage: "won",
|
||||
value: 450.5,
|
||||
currency: "MXN",
|
||||
});
|
||||
});
|
||||
|
||||
it("sin monto, la venta se cuenta pero SIN precio", () => {
|
||||
// `value: 0` no significa "no sé cuánto": le enseñaría al optimizador que
|
||||
// las ventas de este negocio valen nada.
|
||||
expect(purchaseCustomData({ amountCents: null, currency: "MXN" })).toEqual({
|
||||
lead_stage: "won",
|
||||
});
|
||||
expect(purchaseCustomData({ amountCents: 0, currency: "MXN" })).toEqual({
|
||||
lead_stage: "won",
|
||||
});
|
||||
});
|
||||
|
||||
it("un monto negativo tampoco inventa un valor", () => {
|
||||
expect(purchaseCustomData({ amountCents: -100, currency: "MXN" })).toEqual({
|
||||
lead_stage: "won",
|
||||
});
|
||||
});
|
||||
|
||||
it("sin moneda capturada, manda el valor sin moneda antes que inventarla", () => {
|
||||
expect(purchaseCustomData({ amountCents: 12300, currency: null })).toEqual({
|
||||
lead_stage: "won",
|
||||
value: 123,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("toConversionActivityRow", () => {
|
||||
const base = {
|
||||
id: "cve_1",
|
||||
conversationId: "cv_1",
|
||||
eventName: "QualifiedLead",
|
||||
error: null,
|
||||
fbTraceId: "Aki1",
|
||||
contactName: "Marina",
|
||||
adHeadline: "Kit de verano",
|
||||
createdAt: new Date("2026-08-28T10:00:00.000Z"),
|
||||
};
|
||||
|
||||
it("muestra el momento del ENVÍO cuando lo hubo", () => {
|
||||
const row = toConversionActivityRow({
|
||||
...base,
|
||||
status: "sent",
|
||||
sentAt: new Date("2026-08-28T10:05:00.000Z"),
|
||||
});
|
||||
expect(row.at).toBe("2026-08-28T10:05:00.000Z");
|
||||
expect(row.adHeadline).toBe("Kit de verano");
|
||||
});
|
||||
|
||||
it("y el de creación cuando no salió", () => {
|
||||
const row = toConversionActivityRow({
|
||||
...base,
|
||||
status: "skipped",
|
||||
sentAt: null,
|
||||
error: "sin ctwa_clid",
|
||||
});
|
||||
expect(row.at).toBe("2026-08-28T10:00:00.000Z");
|
||||
// El motivo se conserva tal cual: es la respuesta a "¿por qué este lead no
|
||||
// aparece en Meta?".
|
||||
expect(row.error).toBe("sin ctwa_clid");
|
||||
});
|
||||
});
|
||||
|
||||
describe("guardarraíles del reporte", () => {
|
||||
const source = readFileSync("src/server/attribution/conversions.ts", "utf8");
|
||||
|
||||
it("una conversación de prueba jamás puede producir un evento", () => {
|
||||
// Mismo guardrail que el sender: el Laboratorio no toca el mundo real.
|
||||
expect(source).toContain("eq(schema.conversation.isTest, false)");
|
||||
});
|
||||
|
||||
it("el dedup es el UNIQUE de la base, no un chequeo previo", () => {
|
||||
// A Meta no se le puede des-enviar una compra: dos movimientos simultáneos
|
||||
// del mismo lead tienen que chocar en la base, no en un `if`.
|
||||
expect(source).toContain("onConflictDoNothing");
|
||||
});
|
||||
|
||||
it("la emisión cuelga de la puerta única de etapas", () => {
|
||||
const gate = readFileSync("src/server/leads/stage-history.ts", "utf8");
|
||||
expect(gate).toContain("reportStageChange");
|
||||
// Y ocurre DESPUÉS del commit: una llamada de red dentro de la transacción
|
||||
// la mantendría abierta mientras Meta piensa.
|
||||
const txEnd = gate.indexOf(" });");
|
||||
expect(gate.indexOf("reportStageChange(", txEnd)).toBeGreaterThan(txEnd);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,66 @@
|
||||
import { beforeAll, describe, expect, it, vi } from "vitest";
|
||||
|
||||
/**
|
||||
* FR-040/FR-080s: el token se guarda cifrado (jamás texto plano en la fila)
|
||||
* y a la UI solo viajan los últimos 4 caracteres.
|
||||
*/
|
||||
|
||||
const insertedRows: Record<string, unknown>[] = [];
|
||||
|
||||
vi.mock("@/lib/db", () => ({
|
||||
getDb: () => ({
|
||||
insert: () => ({
|
||||
values: (v: Record<string, unknown>) => {
|
||||
insertedRows.push(v);
|
||||
return {
|
||||
onConflictDoUpdate: () => Promise.resolve(),
|
||||
};
|
||||
},
|
||||
}),
|
||||
}),
|
||||
schema: {
|
||||
metaCredentials: { organizationId: "organization_id" },
|
||||
},
|
||||
}));
|
||||
|
||||
beforeAll(() => {
|
||||
process.env.APP_BASE_URL = "http://localhost:3000";
|
||||
process.env.DATABASE_URL = "postgresql://t:t@localhost:5432/t";
|
||||
process.env.BETTER_AUTH_SECRET = "secret-de-test-suficiente";
|
||||
process.env.ENCRYPTION_KEY = Buffer.alloc(32, 9).toString("base64");
|
||||
process.env.META_WEBHOOK_VERIFY_TOKEN = "verify-test";
|
||||
});
|
||||
|
||||
describe("credenciales de WhatsApp", () => {
|
||||
it("saveCredentials cifra el token: la fila no contiene el texto plano", async () => {
|
||||
const { saveCredentials } = await import("@/server/whatsapp/credentials");
|
||||
const token = "EAAG-token-super-secreto-abcd";
|
||||
await saveCredentials({
|
||||
organizationId: "org_1",
|
||||
wabaId: "waba1",
|
||||
phoneNumberId: "pn1",
|
||||
token,
|
||||
});
|
||||
const row = insertedRows[0]!;
|
||||
const serialized = JSON.stringify(row);
|
||||
expect(serialized).not.toContain(token);
|
||||
expect(row.tokenCipher).toBeTruthy();
|
||||
expect(row.tokenIv).toBeTruthy();
|
||||
expect(row.tokenTag).toBeTruthy();
|
||||
|
||||
// y el cifrado es reversible con la clave de la instancia
|
||||
const { decryptSecret } = await import("@/lib/crypto");
|
||||
expect(
|
||||
decryptSecret({
|
||||
cipher: row.tokenCipher as string,
|
||||
iv: row.tokenIv as string,
|
||||
tag: row.tokenTag as string,
|
||||
})
|
||||
).toBe(token);
|
||||
});
|
||||
|
||||
it("tokenLast4 expone solo los últimos 4 caracteres", async () => {
|
||||
const { tokenLast4 } = await import("@/server/whatsapp/credentials");
|
||||
expect(tokenLast4("EAAG-token-super-secreto-abcd")).toBe("abcd");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,37 @@
|
||||
import { beforeAll, describe, expect, it } from "vitest";
|
||||
|
||||
beforeAll(() => {
|
||||
process.env.APP_BASE_URL = "http://localhost:3000";
|
||||
process.env.DATABASE_URL = "postgresql://test:test@localhost:5432/test";
|
||||
process.env.BETTER_AUTH_SECRET = "secret-de-test-suficiente";
|
||||
process.env.ENCRYPTION_KEY = Buffer.alloc(32, 7).toString("base64");
|
||||
process.env.META_WEBHOOK_VERIFY_TOKEN = "verify-token-test";
|
||||
});
|
||||
|
||||
describe("crypto AES-256-GCM", () => {
|
||||
it("cifra y descifra (roundtrip)", async () => {
|
||||
const { encryptSecret, decryptSecret } = await import("@/lib/crypto");
|
||||
const value = encryptSecret("EAAG-token-super-secreto");
|
||||
expect(value.cipher).not.toContain("token");
|
||||
expect(Buffer.from(value.iv, "base64")).toHaveLength(12);
|
||||
expect(decryptSecret(value)).toBe("EAAG-token-super-secreto");
|
||||
});
|
||||
|
||||
it("dos cifrados del mismo texto producen ciphertexts distintos (IV aleatorio)", async () => {
|
||||
const { encryptSecret } = await import("@/lib/crypto");
|
||||
const a = encryptSecret("mismo-texto");
|
||||
const b = encryptSecret("mismo-texto");
|
||||
expect(a.cipher).not.toBe(b.cipher);
|
||||
expect(a.iv).not.toBe(b.iv);
|
||||
});
|
||||
|
||||
it("tag manipulado lanza (integridad GCM)", async () => {
|
||||
const { encryptSecret, decryptSecret } = await import("@/lib/crypto");
|
||||
const value = encryptSecret("dato");
|
||||
const tampered = {
|
||||
...value,
|
||||
tag: Buffer.alloc(16, 1).toString("base64"),
|
||||
};
|
||||
expect(() => decryptSecret(tampered)).toThrow();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,502 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
/**
|
||||
* 065 — El split de 2026: la Cuenta de WhatsApp (el número) y la Cuenta de
|
||||
* mensajes (plantillas y pago). Aquí se habla con el cliente real
|
||||
* (`graphRequest`) sobre un `fetch` falso, para ver a qué cuenta va cada
|
||||
* llamada:
|
||||
*
|
||||
* - el webhook se registra también en la cuenta de mensajes, con las
|
||||
* mismas reglas de respeto que la de WhatsApp;
|
||||
* - las plantillas se crean y se sincronizan en la cuenta de mensajes;
|
||||
* - el `2388339` sin cuenta de mensajes dice qué hacer;
|
||||
* - el sync importa lo que ya existe en Meta (puerto de la spec 101).
|
||||
*/
|
||||
|
||||
const env = vi.hoisted(() => ({
|
||||
APP_BASE_URL: "https://crm.ejemplo.test",
|
||||
META_WEBHOOK_VERIFY_TOKEN: "verify-token-xyz",
|
||||
META_GRAPH_BASE_URL: "https://graph.facebook.com",
|
||||
META_GRAPH_API_VERSION: "v25.0",
|
||||
}));
|
||||
vi.mock("@/lib/env", () => ({ getEnv: () => env }));
|
||||
|
||||
const creds = vi.hoisted(() => ({
|
||||
current: null as null | {
|
||||
id: string;
|
||||
organizationId: string;
|
||||
wabaId: string;
|
||||
messagingAccountId: string | null;
|
||||
phoneNumberId: string;
|
||||
displayPhoneNumber: string | null;
|
||||
verifiedName: string | null;
|
||||
status: "connected" | "reconnect_required";
|
||||
token: string;
|
||||
},
|
||||
}));
|
||||
vi.mock("@/server/whatsapp/credentials", async (importOriginal) => {
|
||||
const real = await importOriginal<typeof import("@/server/whatsapp/credentials")>();
|
||||
return {
|
||||
cuentaDePlantillas: real.cuentaDePlantillas,
|
||||
getCredentialsByOrg: async () => creds.current,
|
||||
getCredentialsByWabaId: async () => creds.current,
|
||||
markReconnectRequired: vi.fn(async () => {}),
|
||||
};
|
||||
});
|
||||
vi.mock("@/server/events/bus", () => ({ publish: () => {} }));
|
||||
vi.mock("@/server/inbox/send", () => ({
|
||||
callGraphSend: vi.fn(),
|
||||
SendError: class SendError extends Error {},
|
||||
}));
|
||||
vi.mock("@/server/inbox/ingest", () => ({ serializeMessage: (m: unknown) => m }));
|
||||
|
||||
/** Base de datos de mentira: lo justo para crear y sincronizar plantillas. */
|
||||
const db = vi.hoisted(() => ({
|
||||
local: [] as Record<string, unknown>[],
|
||||
insertados: [] as Record<string, unknown>[],
|
||||
actualizados: [] as Record<string, unknown>[],
|
||||
}));
|
||||
vi.mock("@/lib/db", () => ({
|
||||
getDb: () => ({
|
||||
select: () => ({ from: () => ({ where: async () => db.local }) }),
|
||||
insert: () => ({
|
||||
values: (v: Record<string, unknown>) => {
|
||||
db.insertados.push(v);
|
||||
const filas = async () => [{ ...v }];
|
||||
return {
|
||||
onConflictDoUpdate: () => ({ returning: filas }),
|
||||
onConflictDoNothing: () => ({ returning: filas }),
|
||||
};
|
||||
},
|
||||
}),
|
||||
update: () => ({
|
||||
set: (v: Record<string, unknown>) => ({
|
||||
where: async () => {
|
||||
db.actualizados.push(v);
|
||||
},
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
schema: {
|
||||
template: { id: "id", organizationId: "organization_id", name: "name", language: "language" },
|
||||
},
|
||||
}));
|
||||
|
||||
import {
|
||||
descubrirCuentaDeMensajes,
|
||||
registerWebhookForNumber,
|
||||
unregisterWebhookForMessagingAccount,
|
||||
} from "@/server/whatsapp/connect";
|
||||
import { cuentaDePlantillas } from "@/server/whatsapp/credentials";
|
||||
import { createTemplate, syncTemplates, TemplateError } from "@/server/whatsapp/templates";
|
||||
|
||||
const URL_PROPIA = "https://crm.ejemplo.test/api/webhooks/wa/verify-token-xyz";
|
||||
const RUTA_PROPIA = "/api/webhooks/wa/verify-token-xyz";
|
||||
const G = "https://graph.facebook.com/v25.0";
|
||||
|
||||
const fetchMock = vi.fn();
|
||||
const respond = (data: unknown, status = 200) =>
|
||||
fetchMock.mockResolvedValueOnce(new Response(JSON.stringify(data), { status }));
|
||||
const metaError = (status: number, code: number, extra: Record<string, unknown> = {}) =>
|
||||
respond({ error: { message: "error de Meta", code, type: "OAuthException", ...extra } }, status);
|
||||
const call = (i: number) => {
|
||||
const [url, init] = fetchMock.mock.calls[i]! as [string, RequestInit];
|
||||
return {
|
||||
url,
|
||||
method: init.method,
|
||||
body: init.body ? JSON.parse(String(init.body)) : undefined,
|
||||
};
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
vi.stubGlobal("fetch", fetchMock);
|
||||
fetchMock.mockReset();
|
||||
vi.spyOn(console, "log").mockImplementation(() => {});
|
||||
vi.spyOn(console, "warn").mockImplementation(() => {});
|
||||
db.local = [];
|
||||
db.insertados = [];
|
||||
db.actualizados = [];
|
||||
creds.current = {
|
||||
id: "cred_1",
|
||||
organizationId: "org_1",
|
||||
wabaId: "111",
|
||||
messagingAccountId: "333",
|
||||
phoneNumberId: "222",
|
||||
displayPhoneNumber: null,
|
||||
verifiedName: null,
|
||||
status: "connected",
|
||||
token: "EAAG-token",
|
||||
};
|
||||
});
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
describe("qué cuenta tiene las plantillas", () => {
|
||||
it("la de mensajes si se conoce; si no, la de WhatsApp", () => {
|
||||
expect(cuentaDePlantillas({ wabaId: "111", messagingAccountId: "333" })).toBe("333");
|
||||
expect(cuentaDePlantillas({ wabaId: "111", messagingAccountId: null })).toBe("111");
|
||||
expect(cuentaDePlantillas({ wabaId: "111", messagingAccountId: "" })).toBe("111");
|
||||
});
|
||||
});
|
||||
|
||||
describe("registro del webhook en la Cuenta de mensajes", () => {
|
||||
const opts = {
|
||||
wabaId: "111",
|
||||
phoneNumberId: "222",
|
||||
token: "EAAG-token",
|
||||
webhookUrl: URL_PROPIA,
|
||||
verifyToken: "verify-token-xyz",
|
||||
messagingAccountId: "333",
|
||||
};
|
||||
const sinOverride = () => respond({ data: [{ whatsapp_business_api_data: { id: "app-1" } }] });
|
||||
const conOverride = (uri: string) =>
|
||||
respond({ data: [{ whatsapp_business_api_data: { id: "app-1" }, override_callback_uri: uri }] });
|
||||
const numeroConfirmado = () =>
|
||||
respond({ webhook_configuration: { phone_number: URL_PROPIA, application: "https://app.test/wh" } });
|
||||
|
||||
it("suscribe la app con override en la cuenta de mensajes y lo confirma releyendo", async () => {
|
||||
sinOverride(); // GET 111/subscribed_apps
|
||||
respond({ success: true }); // POST 111/subscribed_apps
|
||||
sinOverride(); // GET 333/subscribed_apps — solo la app interna de Meta
|
||||
respond({ success: true }); // POST 333/subscribed_apps con override
|
||||
conOverride(URL_PROPIA); // GET 333/subscribed_apps — confirmado
|
||||
respond({ success: true }); // POST 222 override del número
|
||||
numeroConfirmado();
|
||||
|
||||
expect(await registerWebhookForNumber(opts)).toEqual({
|
||||
ok: true,
|
||||
appWithoutWebhook: false,
|
||||
messagingAccount: { ok: true },
|
||||
});
|
||||
expect(call(2)).toMatchObject({ url: `${G}/333/subscribed_apps`, method: "GET" });
|
||||
expect(call(3)).toMatchObject({
|
||||
url: `${G}/333/subscribed_apps`,
|
||||
method: "POST",
|
||||
body: { override_callback_uri: URL_PROPIA, verify_token: "verify-token-xyz" },
|
||||
});
|
||||
expect(call(4)).toMatchObject({ url: `${G}/333/subscribed_apps`, method: "GET" });
|
||||
expect(fetchMock).toHaveBeenCalledTimes(7);
|
||||
});
|
||||
|
||||
it("si ya tiene el override de esta instancia (aunque cambie el dominio), no lo toca", async () => {
|
||||
sinOverride();
|
||||
respond({ success: true });
|
||||
conOverride(`https://dominio-viejo.test${RUTA_PROPIA}`);
|
||||
respond({ success: true });
|
||||
numeroConfirmado();
|
||||
|
||||
const res = await registerWebhookForNumber(opts);
|
||||
expect(res).toMatchObject({ ok: true, messagingAccount: { ok: true } });
|
||||
expect(fetchMock).toHaveBeenCalledTimes(5);
|
||||
expect(call(3).url).toBe(`${G}/222`);
|
||||
});
|
||||
|
||||
it("un override ajeno se respeta y se informa; con «Recuperar» se reemplaza", async () => {
|
||||
sinOverride();
|
||||
respond({ success: true });
|
||||
conOverride("https://cerebro-ajeno.test/hook/secreto");
|
||||
respond({ success: true });
|
||||
numeroConfirmado();
|
||||
expect(await registerWebhookForNumber(opts)).toMatchObject({
|
||||
ok: true,
|
||||
messagingAccount: { ok: true, skipped: "override_ajeno", host: "cerebro-ajeno.test" },
|
||||
});
|
||||
|
||||
fetchMock.mockReset();
|
||||
sinOverride();
|
||||
respond({ success: true });
|
||||
conOverride("https://cerebro-ajeno.test/hook/secreto");
|
||||
respond({ success: true });
|
||||
conOverride(URL_PROPIA);
|
||||
respond({ success: true });
|
||||
numeroConfirmado();
|
||||
expect(await registerWebhookForNumber({ ...opts, forzar: true })).toMatchObject({
|
||||
ok: true,
|
||||
messagingAccount: { ok: true },
|
||||
});
|
||||
expect(call(3)).toMatchObject({ url: `${G}/333/subscribed_apps`, method: "POST" });
|
||||
});
|
||||
|
||||
it("si Meta niega el permiso en la cuenta de mensajes, el número queda igual y se explica", async () => {
|
||||
sinOverride();
|
||||
respond({ success: true });
|
||||
sinOverride();
|
||||
metaError(403, 200);
|
||||
respond({ success: true });
|
||||
numeroConfirmado();
|
||||
|
||||
const res = await registerWebhookForNumber(opts);
|
||||
expect(res).toMatchObject({
|
||||
ok: true,
|
||||
appWithoutWebhook: false,
|
||||
messagingAccount: { ok: false, code: "missing_permission" },
|
||||
});
|
||||
if (res.ok && "messagingAccount" in res && res.messagingAccount && !res.messagingAccount.ok) {
|
||||
expect(res.messagingAccount.message).toContain("Messaging accounts");
|
||||
}
|
||||
});
|
||||
|
||||
it("si no lo confirma al releer, avisa sin tumbar el número", async () => {
|
||||
sinOverride();
|
||||
respond({ success: true });
|
||||
sinOverride();
|
||||
respond({ success: true });
|
||||
sinOverride();
|
||||
respond({ success: true });
|
||||
numeroConfirmado();
|
||||
expect(await registerWebhookForNumber(opts)).toMatchObject({
|
||||
ok: true,
|
||||
messagingAccount: { ok: false, code: "meta_error" },
|
||||
});
|
||||
});
|
||||
|
||||
it("sin cuenta de mensajes —o si es la misma que la guardada como WABA— no hay llamadas extra", async () => {
|
||||
for (const messagingAccountId of [null, "111"]) {
|
||||
fetchMock.mockReset();
|
||||
sinOverride();
|
||||
respond({ success: true });
|
||||
respond({ success: true });
|
||||
numeroConfirmado();
|
||||
expect(await registerWebhookForNumber({ ...opts, messagingAccountId })).toEqual({
|
||||
ok: true,
|
||||
appWithoutWebhook: false,
|
||||
});
|
||||
expect(fetchMock).toHaveBeenCalledTimes(4);
|
||||
}
|
||||
});
|
||||
|
||||
it("si la cuenta de WhatsApp enruta a un override ajeno, la de mensajes tampoco se toca", async () => {
|
||||
conOverride("https://agencia.test/hook");
|
||||
respond({ webhook_configuration: {} }); // baja del número: no era nuestro
|
||||
expect(await registerWebhookForNumber(opts)).toEqual({
|
||||
ok: true,
|
||||
skipped: "waba_override",
|
||||
host: "agencia.test",
|
||||
});
|
||||
expect(fetchMock.mock.calls.some(([u]) => String(u).includes("/333/"))).toBe(false);
|
||||
});
|
||||
|
||||
// 066 — Desde la noche del 28-oct-2026 Meta también rechaza la suscripción
|
||||
// en la cuenta de WhatsApp partida; lo que cuenta es la de mensajes.
|
||||
const cuentaPartida = () => metaError(400, 100, { error_subcode: 2388339 });
|
||||
|
||||
it("2388339 en la cuenta de WhatsApp no es fatal si la de mensajes quedó (066)", async () => {
|
||||
sinOverride(); // GET 111
|
||||
cuentaPartida(); // POST 111 → 2388339
|
||||
sinOverride(); // GET 333
|
||||
respond({ success: true }); // POST 333 con override
|
||||
conOverride(URL_PROPIA); // GET 333 confirmado
|
||||
respond({ success: true }); // POST 222 override del número
|
||||
numeroConfirmado();
|
||||
expect(await registerWebhookForNumber(opts)).toEqual({
|
||||
ok: true,
|
||||
appWithoutWebhook: false,
|
||||
messagingAccount: { ok: true },
|
||||
});
|
||||
expect(call(5)).toMatchObject({ url: `${G}/222`, method: "POST" });
|
||||
});
|
||||
|
||||
it("2388339 con la de mensajes fallando devuelve ese error, y sin ella pide la ID (066)", async () => {
|
||||
sinOverride();
|
||||
cuentaPartida();
|
||||
sinOverride();
|
||||
metaError(403, 200);
|
||||
expect(await registerWebhookForNumber(opts)).toMatchObject({
|
||||
ok: false,
|
||||
code: "missing_permission",
|
||||
});
|
||||
expect(fetchMock.mock.calls.some(([u]) => String(u) === `${G}/222`)).toBe(false);
|
||||
|
||||
fetchMock.mockReset();
|
||||
sinOverride();
|
||||
cuentaPartida();
|
||||
const sinCuenta = await registerWebhookForNumber({ ...opts, messagingAccountId: null });
|
||||
expect(sinCuenta).toMatchObject({ ok: false, code: "meta_error" });
|
||||
expect(!sinCuenta.ok && sinCuenta.message).toContain("Cuenta de mensajes");
|
||||
});
|
||||
|
||||
it("otro error de la cuenta de WhatsApp sigue siendo fatal aunque haya cuenta de mensajes", async () => {
|
||||
sinOverride();
|
||||
metaError(403, 200);
|
||||
expect(await registerWebhookForNumber(opts)).toMatchObject({ ok: false, code: "missing_permission" });
|
||||
expect(fetchMock).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
});
|
||||
|
||||
describe("al desconectar, la cuenta de mensajes", () => {
|
||||
const baja = { messagingAccountId: "333", token: "EAAG-token", webhookPath: RUTA_PROPIA };
|
||||
|
||||
it("se le quita el override si es nuestro (POST sin cuerpo)", async () => {
|
||||
respond({ data: [{ override_callback_uri: URL_PROPIA }] });
|
||||
respond({ success: true });
|
||||
await unregisterWebhookForMessagingAccount(baja);
|
||||
expect(call(1)).toMatchObject({ url: `${G}/333/subscribed_apps`, method: "POST", body: undefined });
|
||||
});
|
||||
|
||||
it("uno ajeno no se toca y un error de Meta no lanza", async () => {
|
||||
respond({ data: [{ override_callback_uri: "https://otro.test/hook" }] });
|
||||
await unregisterWebhookForMessagingAccount(baja);
|
||||
expect(fetchMock).toHaveBeenCalledTimes(1);
|
||||
|
||||
fetchMock.mockReset();
|
||||
metaError(500, 2);
|
||||
await expect(unregisterWebhookForMessagingAccount(baja)).resolves.toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe("descubrir la cuenta de mensajes (best-effort)", () => {
|
||||
it("lee paid_messaging_account_id como cadena o como objeto", async () => {
|
||||
respond({ paid_messaging_account_id: "333", id: "111" });
|
||||
expect(await descubrirCuentaDeMensajes("111", "EAAG-token")).toBe("333");
|
||||
expect(call(0).url).toBe(`${G}/111?fields=paid_messaging_account_id`);
|
||||
respond({ paid_messaging_account_id: { id: "444" } });
|
||||
expect(await descubrirCuentaDeMensajes("111", "EAAG-token")).toBe("444");
|
||||
});
|
||||
|
||||
it("campo desconocido, vacío, raro o igual a la WABA → null, sin lanzar", async () => {
|
||||
metaError(400, 100);
|
||||
expect(await descubrirCuentaDeMensajes("111", "t")).toBeNull();
|
||||
respond({ id: "111" });
|
||||
expect(await descubrirCuentaDeMensajes("111", "t")).toBeNull();
|
||||
respond({ paid_messaging_account_id: "no-numérico" });
|
||||
expect(await descubrirCuentaDeMensajes("111", "t")).toBeNull();
|
||||
respond({ paid_messaging_account_id: "111" });
|
||||
expect(await descubrirCuentaDeMensajes("111", "t")).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("crear plantillas", () => {
|
||||
const nueva = { name: "Aviso pedido", language: "es_MX", category: "UTILITY", body: "Hola {{1}}" };
|
||||
|
||||
it("con cuenta de mensajes, el POST va a ella", async () => {
|
||||
respond({ id: "tpl_1", status: "PENDING" });
|
||||
await createTemplate("org_1", nueva);
|
||||
expect(call(0)).toMatchObject({ url: `${G}/333/message_templates`, method: "POST" });
|
||||
expect(db.insertados[0]).toMatchObject({ name: "aviso_pedido", waTemplateId: "tpl_1" });
|
||||
});
|
||||
|
||||
it("sin ella, va a la de WhatsApp como antes", async () => {
|
||||
creds.current!.messagingAccountId = null;
|
||||
respond({ id: "tpl_1", status: "PENDING" });
|
||||
await createTemplate("org_1", nueva);
|
||||
expect(call(0).url).toBe(`${G}/111/message_templates`);
|
||||
});
|
||||
|
||||
it("sin ella y con el 2388339 de Meta, el error dice dónde poner la Cuenta de mensajes", async () => {
|
||||
creds.current!.messagingAccountId = null;
|
||||
metaError(400, 100, {
|
||||
error_subcode: 2388339,
|
||||
message: "Invalid parameter",
|
||||
error_user_msg: "This API is not supported for this WhatsApp Business Account",
|
||||
});
|
||||
const err = await createTemplate("org_1", nueva).catch((e: unknown) => e);
|
||||
expect(err).toBeInstanceOf(TemplateError);
|
||||
expect((err as TemplateError).code).toBe("meta_error");
|
||||
expect((err as TemplateError).message).toContain("Cuenta de mensajes");
|
||||
expect((err as TemplateError).message).toContain("Ajustes → WhatsApp");
|
||||
expect(db.insertados).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("otros errores de Meta conservan su mensaje", async () => {
|
||||
metaError(400, 100, { message: "Invalid parameter" });
|
||||
await expect(createTemplate("org_1", nueva)).rejects.toMatchObject({
|
||||
code: "meta_error",
|
||||
message: "Invalid parameter",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("sincronizar plantillas", () => {
|
||||
const helloWorld = {
|
||||
id: "hw_1",
|
||||
name: "hello_world",
|
||||
language: "en_US",
|
||||
status: "APPROVED",
|
||||
category: "UTILITY",
|
||||
components: [
|
||||
{ type: "HEADER", format: "TEXT", text: "Hello World" },
|
||||
{ type: "BODY", text: "Welcome and congratulations!!" },
|
||||
{ type: "FOOTER", text: "WhatsApp Business Platform sample message" },
|
||||
],
|
||||
};
|
||||
|
||||
it("lee la cuenta de mensajes con components y recorre la paginación", async () => {
|
||||
respond({ data: [helloWorld], paging: { cursors: { after: "CUR" }, next: "https://graph/next" } });
|
||||
respond({ data: [], paging: { cursors: { after: "FIN" } } });
|
||||
await syncTemplates("org_1");
|
||||
expect(call(0).url).toBe(
|
||||
`${G}/333/message_templates?fields=id,name,language,status,category,rejected_reason,components&limit=100`
|
||||
);
|
||||
expect(call(1).url).toContain("&after=CUR");
|
||||
expect(fetchMock).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("trae TODAS las páginas (más de 20) y las importa todas", async () => {
|
||||
for (let i = 0; i < 25; i += 1) {
|
||||
respond({
|
||||
data: [{ ...helloWorld, id: `t_${i}`, name: `plantilla_${i}` }],
|
||||
paging: i < 24 ? { cursors: { after: `C${i}` }, next: "https://graph/next" } : {},
|
||||
});
|
||||
}
|
||||
expect(await syncTemplates("org_1")).toBe(25);
|
||||
expect(fetchMock).toHaveBeenCalledTimes(25);
|
||||
expect(db.insertados.map((f) => f.name)).toContain("plantilla_24");
|
||||
});
|
||||
|
||||
it("si Meta repite el cursor, se detiene en vez de dar vueltas", async () => {
|
||||
respond({ data: [helloWorld], paging: { cursors: { after: "MISMO" }, next: "https://graph/next" } });
|
||||
respond({ data: [], paging: { cursors: { after: "MISMO" }, next: "https://graph/next" } });
|
||||
await syncTemplates("org_1");
|
||||
expect(fetchMock).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("importa hello_world aprobada y deja fuera la de encabezado con imagen", async () => {
|
||||
respond({
|
||||
data: [
|
||||
helloWorld,
|
||||
{
|
||||
...helloWorld,
|
||||
id: "img_1",
|
||||
name: "promo_imagen",
|
||||
components: [{ type: "HEADER", format: "IMAGE" }, { type: "BODY", text: "Hola" }],
|
||||
},
|
||||
],
|
||||
});
|
||||
expect(await syncTemplates("org_1")).toBe(1);
|
||||
expect(db.insertados).toHaveLength(1);
|
||||
expect(db.insertados[0]).toMatchObject({
|
||||
organizationId: "org_1",
|
||||
name: "hello_world",
|
||||
language: "en_US",
|
||||
status: "approved",
|
||||
waTemplateId: "hw_1",
|
||||
body: "Welcome and congratulations!!",
|
||||
});
|
||||
});
|
||||
|
||||
it("lo que ya existe sigue el camino de siempre (estado y categoría), sin importar de nuevo", async () => {
|
||||
db.local = [
|
||||
{
|
||||
id: "tpl_local",
|
||||
name: "hello_world",
|
||||
language: "en_US",
|
||||
status: "pending",
|
||||
category: "UTILITY",
|
||||
waTemplateId: null,
|
||||
},
|
||||
];
|
||||
respond({ data: [helloWorld] });
|
||||
expect(await syncTemplates("org_1")).toBe(1);
|
||||
expect(db.insertados).toHaveLength(0);
|
||||
expect(db.actualizados[0]).toMatchObject({ status: "approved", waTemplateId: "hw_1" });
|
||||
});
|
||||
|
||||
it("sin cuenta de mensajes, lee la de WhatsApp", async () => {
|
||||
creds.current!.messagingAccountId = null;
|
||||
respond({ data: [] });
|
||||
await syncTemplates("org_1");
|
||||
expect(call(0).url).toContain(`${G}/111/message_templates?`);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,209 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { SIN_DESPACHO, despachoFallando } from "@/lib/brain-status";
|
||||
import { leerConfigDespacho } from "@/server/brains/config";
|
||||
import { hayMensajesSinDespachar, sinDespachar } from "@/server/brains/deliver";
|
||||
import { dispatchDto } from "@/server/dispatch/estado";
|
||||
import { checkDispatch } from "@/server/doctor/checks";
|
||||
import { BACKOFF_MS, MAX_INTENTOS, esperaDeReintento } from "@/server/dispatch/outbox";
|
||||
|
||||
/**
|
||||
* 021 — Cuándo hay despacho, y qué se dice cuando no.
|
||||
*
|
||||
* Lo que se protege: que una URL mal escrita o una llave ausente dejen el
|
||||
* despacho INACTIVO (y el agente incluido contestando como en 1.5) en vez de
|
||||
* una instancia muda, y que el motivo salga sin filtrar la ruta de la URL.
|
||||
*/
|
||||
|
||||
const LLAVE = "k".repeat(32);
|
||||
|
||||
describe("leerConfigDespacho", () => {
|
||||
it("sin variable: inactivo y sin problema (la instancia no despacha)", () => {
|
||||
expect(leerConfigDespacho({})).toEqual({ active: false, host: null, problem: null });
|
||||
expect(leerConfigDespacho({ BRAIN_DISPATCH_URL: " ", BOT_API_KEY: LLAVE })).toEqual({
|
||||
active: false,
|
||||
host: null,
|
||||
problem: null,
|
||||
});
|
||||
});
|
||||
|
||||
it("URL interna + llave: activo, y es válida aunque no sea pública", () => {
|
||||
const c = leerConfigDespacho({
|
||||
BRAIN_DISPATCH_URL: "http://nea:8000/vocero/dispatch",
|
||||
BOT_API_KEY: LLAVE,
|
||||
});
|
||||
expect(c).toEqual({
|
||||
active: true,
|
||||
url: "http://nea:8000/vocero/dispatch",
|
||||
host: "nea:8000",
|
||||
secret: LLAVE,
|
||||
});
|
||||
});
|
||||
|
||||
it("https público también", () => {
|
||||
const c = leerConfigDespacho({
|
||||
BRAIN_DISPATCH_URL: " https://nea.ejemplo.com/vocero/dispatch ",
|
||||
BOT_API_KEY: LLAVE,
|
||||
});
|
||||
expect(c.active).toBe(true);
|
||||
expect(c.host).toBe("nea.ejemplo.com");
|
||||
});
|
||||
|
||||
it.each(["nea:8000/vocero/dispatch", "no es una url", "ftp://nea/vocero", "file:///etc/passwd"])(
|
||||
"%s → problema de URL, inactivo",
|
||||
(url) => {
|
||||
const c = leerConfigDespacho({ BRAIN_DISPATCH_URL: url, BOT_API_KEY: LLAVE });
|
||||
expect(c).toMatchObject({ active: false, problem: "url" });
|
||||
}
|
||||
);
|
||||
|
||||
it("usuario y clave en la URL → problema de URL (el despacho ya va firmado)", () => {
|
||||
const c = leerConfigDespacho({
|
||||
BRAIN_DISPATCH_URL: "https://user:secreto@nea.ejemplo.com/vocero/dispatch",
|
||||
BOT_API_KEY: LLAVE,
|
||||
});
|
||||
expect(c).toEqual({ active: false, host: "nea.ejemplo.com", problem: "url" });
|
||||
expect(JSON.stringify(c)).not.toContain("secreto");
|
||||
});
|
||||
|
||||
it("sin BOT_API_KEY, o corta → sin_llave, inactivo, y solo sale el host", () => {
|
||||
const sin = leerConfigDespacho({ BRAIN_DISPATCH_URL: "http://nea:8000/vocero/dispatch?t=abc" });
|
||||
expect(sin).toEqual({ active: false, host: "nea:8000", problem: "sin_llave" });
|
||||
const corta = leerConfigDespacho({
|
||||
BRAIN_DISPATCH_URL: "http://nea:8000/vocero/dispatch",
|
||||
BOT_API_KEY: "corta",
|
||||
});
|
||||
expect(corta).toMatchObject({ active: false, problem: "sin_llave" });
|
||||
});
|
||||
});
|
||||
|
||||
describe("dispatchDto — lo que ve la tarjeta", () => {
|
||||
const activo = leerConfigDespacho({
|
||||
BRAIN_DISPATCH_URL: "http://nea:8000/vocero/dispatch",
|
||||
BOT_API_KEY: LLAVE,
|
||||
});
|
||||
const sinHechos = { lastDeliveredAt: null, lastFailure: null, pending: 0 };
|
||||
|
||||
it("sin variable, es exactamente SIN_DESPACHO", () => {
|
||||
expect(dispatchDto(leerConfigDespacho({}), sinHechos)).toEqual(SIN_DESPACHO);
|
||||
});
|
||||
|
||||
it("activo: host, fechas en ISO y jamás la llave ni la ruta", () => {
|
||||
const dto = dispatchDto(activo, {
|
||||
lastDeliveredAt: new Date("2026-10-08T10:00:00.000Z"),
|
||||
lastFailure: { at: new Date("2026-10-08T09:00:00.000Z"), detail: "el cerebro respondió 500" },
|
||||
pending: 2,
|
||||
});
|
||||
expect(dto).toEqual({
|
||||
active: true,
|
||||
host: "nea:8000",
|
||||
problem: null,
|
||||
lastDeliveredAt: "2026-10-08T10:00:00.000Z",
|
||||
lastFailure: { at: "2026-10-08T09:00:00.000Z", detail: "el cerebro respondió 500" },
|
||||
pending: 2,
|
||||
});
|
||||
expect(JSON.stringify(dto)).not.toContain(LLAVE);
|
||||
expect(JSON.stringify(dto)).not.toContain("/vocero/dispatch");
|
||||
});
|
||||
|
||||
it("mal configurado: el problema viaja y active es false", () => {
|
||||
const dto = dispatchDto(leerConfigDespacho({ BRAIN_DISPATCH_URL: "http://nea:8000/x" }), sinHechos);
|
||||
expect(dto).toMatchObject({ active: false, host: "nea:8000", problem: "sin_llave" });
|
||||
});
|
||||
});
|
||||
|
||||
describe("despachoFallando — cuándo es una alarma", () => {
|
||||
const base = { ...SIN_DESPACHO, active: true, host: "nea:8000" };
|
||||
const fallo = (at: string) => ({ at, detail: "el cerebro respondió 500" });
|
||||
|
||||
it("sin fallos, o inactivo → no", () => {
|
||||
expect(despachoFallando(base)).toBe(false);
|
||||
expect(despachoFallando({ ...SIN_DESPACHO, lastFailure: fallo("2026-10-08T10:00:00.000Z") })).toBe(false);
|
||||
});
|
||||
|
||||
it("falló y nunca ha entregado → sí", () => {
|
||||
expect(despachoFallando({ ...base, lastFailure: fallo("2026-10-08T10:00:00.000Z") })).toBe(true);
|
||||
});
|
||||
|
||||
it("el fallo es posterior a la última entrega → sí; anterior → no", () => {
|
||||
const entregado = "2026-10-08T10:00:00.000Z";
|
||||
expect(
|
||||
despachoFallando({ ...base, lastDeliveredAt: entregado, lastFailure: fallo("2026-10-08T10:05:00.000Z") })
|
||||
).toBe(true);
|
||||
expect(
|
||||
despachoFallando({ ...base, lastDeliveredAt: entregado, lastFailure: fallo("2026-10-08T09:55:00.000Z") })
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("reintentos", () => {
|
||||
it("tres intentos en total: se espera tras el primero y tras el segundo", () => {
|
||||
expect(MAX_INTENTOS).toBe(3);
|
||||
expect(BACKOFF_MS).toHaveLength(MAX_INTENTOS - 1);
|
||||
expect(esperaDeReintento(1)).toBe(1000);
|
||||
expect(esperaDeReintento(2)).toBe(4000);
|
||||
});
|
||||
|
||||
it("un contador fuera de rango no revienta ni da una espera de cero", () => {
|
||||
expect(esperaDeReintento(0)).toBe(1000);
|
||||
expect(esperaDeReintento(99)).toBe(4000);
|
||||
});
|
||||
});
|
||||
|
||||
describe("hayMensajesSinDespachar — lo que entró con el evento en vuelo", () => {
|
||||
it("la misma ráfaga → no", () => {
|
||||
expect(hayMensajesSinDespachar(["a", "b"], [{ id: "a" }, { id: "b" }])).toBe(false);
|
||||
});
|
||||
|
||||
it("un mensaje más → sí", () => {
|
||||
expect(hayMensajesSinDespachar(["a", "b"], [{ id: "a" }, { id: "b" }, { id: "c" }])).toBe(true);
|
||||
});
|
||||
|
||||
it("ráfaga vacía (ya se contestó) → no", () => {
|
||||
expect(hayMensajesSinDespachar(["a"], [])).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* 025 — Cuáles, no solo si hay: son los ids que el despacho siguiente lleva
|
||||
* anotados en `dispatch.message_ids`.
|
||||
*/
|
||||
describe("sinDespachar — lo que el cerebro todavía no recibió", () => {
|
||||
it("devuelve los que faltan, en el orden de la ráfaga", () => {
|
||||
expect(sinDespachar(["a"], [{ id: "a" }, { id: "b" }, { id: "c" }])).toEqual(["b", "c"]);
|
||||
});
|
||||
|
||||
it("todo entregado → nada", () => {
|
||||
expect(sinDespachar(["a", "b"], [{ id: "a" }, { id: "b" }])).toEqual([]);
|
||||
});
|
||||
|
||||
it("un debido que quedó detrás de la respuesta sigue debiéndose", () => {
|
||||
// `rafagaDe` lo trae por estar anotado, aunque la ráfaga ya esté cerrada.
|
||||
expect(sinDespachar(["a"], [{ id: "b" }])).toEqual(["b"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("pnpm doctor — la línea del despacho", () => {
|
||||
it("sin la variable: se salta, no es un problema", () => {
|
||||
expect(checkDispatch({}).status).toBe("skip");
|
||||
});
|
||||
|
||||
it("activo: ✓ con el host, sin la ruta ni la llave", () => {
|
||||
const r = checkDispatch({
|
||||
BRAIN_DISPATCH_URL: "http://nea:8000/vocero/dispatch?t=secreto",
|
||||
BOT_API_KEY: LLAVE,
|
||||
});
|
||||
expect(r.status).toBe("ok");
|
||||
expect(r.detail).toContain("nea:8000");
|
||||
expect(JSON.stringify(r)).not.toContain("secreto");
|
||||
expect(JSON.stringify(r)).not.toContain(LLAVE);
|
||||
});
|
||||
|
||||
it("mal puesta: aviso con el arreglo, nunca una ✗ (el CRM funciona igual)", () => {
|
||||
const url = checkDispatch({ BRAIN_DISPATCH_URL: "nea:8000", BOT_API_KEY: LLAVE });
|
||||
expect(url.status).toBe("warn");
|
||||
expect(url.fix).toContain("BRAIN_DISPATCH_URL=");
|
||||
const llave = checkDispatch({ BRAIN_DISPATCH_URL: "http://nea:8000/vocero/dispatch" });
|
||||
expect(llave.status).toBe("warn");
|
||||
expect(llave.fix).toContain("BOT_API_KEY=");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,364 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
armarEvento,
|
||||
clasificarRespuesta,
|
||||
firmaValida,
|
||||
firmarCuerpo,
|
||||
nombresDeTarjetas,
|
||||
ubicacionDe,
|
||||
CABECERA_DISPATCH,
|
||||
CABECERA_EVENTO,
|
||||
CABECERA_FIRMA,
|
||||
CABECERA_ORG,
|
||||
} from "@/server/brains/contract";
|
||||
import { entregar } from "@/server/brains/deliver";
|
||||
|
||||
/**
|
||||
* 021 — El contrato del despacho, fijado byte a byte.
|
||||
*
|
||||
* Lo que se protege: que el JSON que el CRM firma sea EXACTAMENTE este. Un
|
||||
* cerebro verifica la firma sobre el cuerpo crudo, así que reordenar una clave
|
||||
* o cambiar cómo se serializa una fecha rompe todas las instalaciones a la
|
||||
* vez, con un 401 mudo. La prueba gemela vive en el repo del cerebro
|
||||
* (nea-agent) con este mismo cuerpo y esta misma firma: cambiar un lado sin el
|
||||
* otro rompe una prueba, no una instalación.
|
||||
*/
|
||||
|
||||
const SECRETO = "llave-de-prueba-del-contrato-0001";
|
||||
|
||||
const CUERPO =
|
||||
'{"dispatchId":"dsp_prueba0000000000001","organization":{"id":"org_prueba","slug":"mi-negocio"},' +
|
||||
'"conversation":{"id":"cv_prueba","channel":"whatsapp","aiEnabled":true,"windowOpen":true,"windowExpiresAt":"2026-10-09T05:10:11.000Z"},' +
|
||||
'"contact":{"id":"ct_prueba","displayName":"Ana Pérez","identity":"5215512345678"},' +
|
||||
'"messages":[{"id":"msg_1","at":"2026-10-08T05:10:03.000Z","type":"text","text":"hola, ¿tienen el modelo azul?","mediaId":null},' +
|
||||
'{"id":"msg_2","at":"2026-10-08T05:10:11.000Z","type":"image","text":null,"mediaId":"1234567890","mimeType":"image/jpeg","caption":"este"}],' +
|
||||
'"firstMessageAt":"2026-10-08T05:10:03.000Z","lastMessageAt":"2026-10-08T05:10:11.000Z"}';
|
||||
|
||||
const FIRMA =
|
||||
"sha256=885074513a6fbd7e2d4443e7f45e3837246effed6c9efa596260057f4dd9008d";
|
||||
|
||||
function evento() {
|
||||
return armarEvento({
|
||||
dispatchId: "dsp_prueba0000000000001",
|
||||
organization: { id: "org_prueba", slug: "mi-negocio" },
|
||||
conversation: {
|
||||
id: "cv_prueba",
|
||||
channel: "whatsapp",
|
||||
aiEnabled: true,
|
||||
windowOpen: true,
|
||||
windowExpiresAt: new Date("2026-10-09T05:10:11.000Z"),
|
||||
},
|
||||
contact: { id: "ct_prueba", displayName: "Ana Pérez", identity: "5215512345678" },
|
||||
messages: [
|
||||
{
|
||||
id: "msg_1",
|
||||
createdAt: new Date("2026-10-08T05:10:03.000Z"),
|
||||
type: "text",
|
||||
text: "hola, ¿tienen el modelo azul?",
|
||||
media: null,
|
||||
},
|
||||
{
|
||||
id: "msg_2",
|
||||
createdAt: new Date("2026-10-08T05:10:11.000Z"),
|
||||
type: "image",
|
||||
text: null,
|
||||
media: { waMediaId: "1234567890", mimeType: "image/jpeg", caption: "este" },
|
||||
},
|
||||
],
|
||||
firstMessageAt: new Date("2026-10-08T05:10:03.000Z"),
|
||||
lastMessageAt: new Date("2026-10-08T05:10:11.000Z"),
|
||||
});
|
||||
}
|
||||
|
||||
describe("el evento de despacho — la forma es contrato", () => {
|
||||
it("se serializa exactamente así, clave por clave", () => {
|
||||
expect(JSON.stringify(evento())).toBe(CUERPO);
|
||||
});
|
||||
|
||||
it("y se firma exactamente así", () => {
|
||||
expect(firmarCuerpo(CUERPO, SECRETO)).toBe(FIRMA);
|
||||
expect(firmarCuerpo(JSON.stringify(evento()), SECRETO)).toBe(FIRMA);
|
||||
});
|
||||
|
||||
it("un adjunto sin media id (ubicación, contacto) no lleva mimeType ni caption", () => {
|
||||
const e = armarEvento({
|
||||
...datosMinimos(),
|
||||
messages: [
|
||||
{
|
||||
id: "msg_3",
|
||||
createdAt: new Date("2026-10-08T05:10:03.000Z"),
|
||||
type: "location",
|
||||
text: null,
|
||||
media: { waMediaId: null, mimeType: null, caption: null },
|
||||
},
|
||||
],
|
||||
});
|
||||
expect(Object.keys(e.messages[0]!)).toEqual(["id", "at", "type", "text", "mediaId"]);
|
||||
expect(e.messages[0]!.mediaId).toBeNull();
|
||||
});
|
||||
|
||||
it("una conversación sin entrantes viaja con la ventana cerrada y sin vencimiento", () => {
|
||||
const e = armarEvento({
|
||||
...datosMinimos(),
|
||||
conversation: {
|
||||
id: "cv_x",
|
||||
channel: "messenger",
|
||||
aiEnabled: true,
|
||||
windowOpen: false,
|
||||
windowExpiresAt: null,
|
||||
},
|
||||
});
|
||||
expect(e.conversation).toEqual({
|
||||
id: "cv_x",
|
||||
channel: "messenger",
|
||||
aiEnabled: true,
|
||||
windowOpen: false,
|
||||
windowExpiresAt: null,
|
||||
});
|
||||
});
|
||||
|
||||
it("no lleva nada que no sea del contrato (ni teléfono suelto, ni credenciales)", () => {
|
||||
expect(Object.keys(evento())).toEqual([
|
||||
"dispatchId",
|
||||
"organization",
|
||||
"conversation",
|
||||
"contact",
|
||||
"messages",
|
||||
"firstMessageAt",
|
||||
"lastMessageAt",
|
||||
]);
|
||||
expect(Object.keys(evento().contact)).toEqual(["id", "displayName", "identity"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("033 — conversation.test, solo en las del Laboratorio", () => {
|
||||
it("una conversación de prueba lleva test: true, al final de conversation", () => {
|
||||
const e = armarEvento({
|
||||
...datosMinimos(),
|
||||
conversation: { ...datosMinimos().conversation, test: true },
|
||||
});
|
||||
expect(Object.keys(e.conversation).at(-1)).toBe("test");
|
||||
expect(e.conversation.test).toBe(true);
|
||||
});
|
||||
|
||||
it("una real no lleva la llave (el cuerpo gemelo no cambia)", () => {
|
||||
const e = armarEvento({
|
||||
...datosMinimos(),
|
||||
conversation: { ...datosMinimos().conversation, test: false },
|
||||
});
|
||||
expect("test" in e.conversation).toBe(false);
|
||||
expect(JSON.stringify(evento())).toBe(CUERPO);
|
||||
});
|
||||
});
|
||||
|
||||
describe("031 — lo que el webhook le daba al cerebro, ahora en el despacho", () => {
|
||||
function unMensaje(m: Partial<Parameters<typeof armarEvento>[0]["messages"][number]>) {
|
||||
return armarEvento({
|
||||
...datosMinimos(),
|
||||
messages: [
|
||||
{
|
||||
id: "msg_9",
|
||||
createdAt: new Date("2026-10-19T05:10:03.000Z"),
|
||||
type: "text",
|
||||
text: null,
|
||||
media: null,
|
||||
...m,
|
||||
},
|
||||
],
|
||||
}).messages[0]!;
|
||||
}
|
||||
|
||||
it("un PDF con nombre lleva fileName, después de caption", () => {
|
||||
const m = unMensaje({
|
||||
type: "document",
|
||||
media: {
|
||||
waMediaId: "555",
|
||||
mimeType: "application/pdf",
|
||||
caption: null,
|
||||
fileName: "cotizacion.pdf",
|
||||
},
|
||||
});
|
||||
expect(Object.keys(m)).toEqual([
|
||||
"id", "at", "type", "text", "mediaId", "mimeType", "caption", "fileName",
|
||||
]);
|
||||
expect(m.fileName).toBe("cotizacion.pdf");
|
||||
});
|
||||
|
||||
it("un adjunto sin nombre no lleva fileName (el cuerpo gemelo no cambia)", () => {
|
||||
const m = unMensaje({
|
||||
type: "image",
|
||||
media: { waMediaId: "1", mimeType: "image/jpeg", caption: null, fileName: null },
|
||||
});
|
||||
expect("fileName" in m).toBe(false);
|
||||
});
|
||||
|
||||
it("una ubicación lleva sus coordenadas, y nombre y dirección si vinieron", () => {
|
||||
const m = unMensaje({
|
||||
type: "location",
|
||||
media: {
|
||||
waMediaId: null,
|
||||
mimeType: null,
|
||||
caption: null,
|
||||
payload: { latitude: 19.43, longitude: -99.13, name: "Oficina", address: " Reforma 1 " },
|
||||
},
|
||||
});
|
||||
expect(Object.keys(m)).toEqual(["id", "at", "type", "text", "mediaId", "location"]);
|
||||
expect(m.location).toEqual({
|
||||
latitude: 19.43,
|
||||
longitude: -99.13,
|
||||
name: "Oficina",
|
||||
address: "Reforma 1",
|
||||
});
|
||||
expect(ubicacionDe({ latitude: 1, longitude: 2 })).toEqual({ latitude: 1, longitude: 2 });
|
||||
expect(ubicacionDe({ latitude: "19", longitude: 2 })).toBeNull();
|
||||
expect(ubicacionDe(null)).toBeNull();
|
||||
});
|
||||
|
||||
it("una tarjeta de contacto lleva los nombres; sin nombres, no lleva la llave", () => {
|
||||
const m = unMensaje({
|
||||
type: "contacts",
|
||||
media: {
|
||||
waMediaId: null,
|
||||
mimeType: null,
|
||||
caption: null,
|
||||
payload: [
|
||||
{ name: { formatted_name: "Luis Gómez", first_name: "Luis" } },
|
||||
{ name: { first_name: "Marta" } },
|
||||
{ name: {} },
|
||||
"basura",
|
||||
],
|
||||
},
|
||||
});
|
||||
expect(m.contacts).toEqual([{ name: "Luis Gómez" }, { name: "Marta" }]);
|
||||
expect(nombresDeTarjetas([{ name: {} }])).toEqual([]);
|
||||
const vacia = unMensaje({
|
||||
type: "contacts",
|
||||
media: { waMediaId: null, mimeType: null, caption: null, payload: [] },
|
||||
});
|
||||
expect("contacts" in vacia).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
function datosMinimos() {
|
||||
return {
|
||||
dispatchId: "dsp_x",
|
||||
organization: { id: "org_x", slug: null },
|
||||
conversation: {
|
||||
id: "cv_x",
|
||||
channel: "instagram" as const,
|
||||
aiEnabled: true,
|
||||
windowOpen: true,
|
||||
windowExpiresAt: new Date("2026-10-09T05:10:11.000Z"),
|
||||
},
|
||||
contact: { id: "ct_x", displayName: "X", identity: "ig:123" },
|
||||
messages: [],
|
||||
firstMessageAt: new Date("2026-10-08T05:10:03.000Z"),
|
||||
lastMessageAt: new Date("2026-10-08T05:10:03.000Z"),
|
||||
};
|
||||
}
|
||||
|
||||
describe("la firma", () => {
|
||||
it("valida el cuerpo crudo con la llave correcta", () => {
|
||||
expect(firmaValida(CUERPO, SECRETO, FIRMA)).toBe(true);
|
||||
});
|
||||
|
||||
it("rechaza un byte cambiado, otra llave, la firma sin prefijo y la ausente", () => {
|
||||
expect(firmaValida(CUERPO.replace("Ana", "Ane"), SECRETO, FIRMA)).toBe(false);
|
||||
expect(firmaValida(CUERPO, `${SECRETO}x`, FIRMA)).toBe(false);
|
||||
expect(firmaValida(CUERPO, SECRETO, FIRMA.slice("sha256=".length))).toBe(false);
|
||||
expect(firmaValida(CUERPO, SECRETO, null)).toBe(false);
|
||||
expect(firmaValida(CUERPO, SECRETO, "")).toBe(false);
|
||||
});
|
||||
|
||||
it("re-serializar el JSON con otro formato NO valida: se firma el crudo", () => {
|
||||
const reformateado = JSON.stringify(JSON.parse(CUERPO), null, 2);
|
||||
expect(firmaValida(reformateado, SECRETO, FIRMA)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("qué entiende el CRM de la respuesta del cerebro", () => {
|
||||
it.each([200, 201, 202, 204])("%i → entregado", (status) => {
|
||||
expect(clasificarRespuesta(status)).toEqual({ ok: true });
|
||||
});
|
||||
|
||||
it.each([429, 500, 502, 503, 504])("%i → se reintenta", (status) => {
|
||||
expect(clasificarRespuesta(status)).toMatchObject({ ok: false, reintentable: true });
|
||||
});
|
||||
|
||||
it.each([301, 302, 400, 401, 404, 409, 422])("%i → no se reintenta", (status) => {
|
||||
expect(clasificarRespuesta(status)).toMatchObject({ ok: false, reintentable: false });
|
||||
});
|
||||
});
|
||||
|
||||
describe("entregar — el POST firmado", () => {
|
||||
const destino = { url: "http://nea:8000/vocero/dispatch", secret: SECRETO };
|
||||
|
||||
it("manda el cuerpo que firma, con las cabeceras del contrato y sin seguir redirecciones", async () => {
|
||||
const llamadas: { url: string; init: RequestInit }[] = [];
|
||||
const fetchImpl = (async (url: string | URL | Request, init?: RequestInit) => {
|
||||
llamadas.push({ url: String(url), init: init ?? {} });
|
||||
return new Response(null, { status: 202 });
|
||||
}) as typeof fetch;
|
||||
|
||||
const r = await entregar(evento(), destino, { fetchImpl });
|
||||
expect(r).toEqual({ ok: true });
|
||||
expect(llamadas).toHaveLength(1);
|
||||
|
||||
const { url, init } = llamadas[0]!;
|
||||
expect(url).toBe(destino.url);
|
||||
expect(init.method).toBe("POST");
|
||||
expect(init.redirect).toBe("manual");
|
||||
expect(init.body).toBe(CUERPO);
|
||||
const headers = init.headers as Record<string, string>;
|
||||
expect(headers[CABECERA_FIRMA]).toBe(FIRMA);
|
||||
expect(headers[CABECERA_DISPATCH]).toBe("dsp_prueba0000000000001");
|
||||
expect(headers[CABECERA_ORG]).toBe("mi-negocio");
|
||||
expect(headers[CABECERA_EVENTO]).toBeUndefined();
|
||||
expect(headers["content-type"]).toBe("application/json");
|
||||
});
|
||||
|
||||
it("sin slug, la cabecera de organización lleva el id", async () => {
|
||||
let cabecera = "";
|
||||
const fetchImpl = (async (_url: string | URL | Request, init?: RequestInit) => {
|
||||
cabecera = (init?.headers as Record<string, string>)[CABECERA_ORG] ?? "";
|
||||
return new Response(null, { status: 200 });
|
||||
}) as typeof fetch;
|
||||
await entregar(armarEvento(datosMinimos()), destino, { fetchImpl });
|
||||
expect(cabecera).toBe("org_x");
|
||||
});
|
||||
|
||||
it("un 500 es reintentable y un 422 no", async () => {
|
||||
const con = (status: number) =>
|
||||
(async () => new Response("x", { status })) as unknown as typeof fetch;
|
||||
expect(await entregar(evento(), destino, { fetchImpl: con(500) })).toMatchObject({
|
||||
ok: false,
|
||||
reintentable: true,
|
||||
});
|
||||
expect(await entregar(evento(), destino, { fetchImpl: con(422) })).toMatchObject({
|
||||
ok: false,
|
||||
reintentable: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("conexión rechazada → reintentable, y el motivo no trae la URL ni la llave", async () => {
|
||||
const fetchImpl = (async () => {
|
||||
throw new TypeError(`fetch failed: ECONNREFUSED ${destino.url} ${SECRETO}`);
|
||||
}) as unknown as typeof fetch;
|
||||
const r = await entregar(evento(), destino, { fetchImpl });
|
||||
expect(r).toEqual({
|
||||
ok: false,
|
||||
reintentable: true,
|
||||
detalle: "no se pudo conectar con el cerebro",
|
||||
});
|
||||
});
|
||||
|
||||
it("un cerebro que no contesta a tiempo → reintentable, con el tiempo en el motivo", async () => {
|
||||
const fetchImpl = ((_url: string | URL | Request, init?: RequestInit) =>
|
||||
new Promise<Response>((_resolve, reject) => {
|
||||
init?.signal?.addEventListener("abort", () => reject(new Error("aborted")));
|
||||
})) as typeof fetch;
|
||||
const r = await entregar(evento(), destino, { fetchImpl, timeoutMs: 30 });
|
||||
expect(r).toMatchObject({ ok: false, reintentable: true });
|
||||
expect((r as { detalle: string }).detalle).toContain("no contestó");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,61 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { destinatarioMeta, esBsuid } from "@/lib/meta/destinatario";
|
||||
|
||||
/**
|
||||
* A quién va un mensaje de la Cloud API.
|
||||
*
|
||||
* Meta pide el teléfono y el BSUID en campos DISTINTOS:
|
||||
*
|
||||
* teléfono → `{ to }`
|
||||
* BSUID → `{ recipient_type: "individual", recipient }`
|
||||
*
|
||||
* Se mandaba el BSUID en `to`, donde Meta espera un número, y respondía
|
||||
* 131026 — «el destinatario no puede recibir mensajes de WhatsApp (número
|
||||
* inexistente, sin cuenta o que no acepta mensajes de empresas)». O sea: el
|
||||
* CRM le echaba la culpa al cliente del miembro por un campo mal puesto.
|
||||
*
|
||||
* Se veía solo con algunos contactos porque Meta omite el teléfono cuando
|
||||
* coinciden TRES condiciones: el usuario activó su nombre de usuario, no ha
|
||||
* habido interacción con ese número de empresa en 30 días, y no está en la
|
||||
* agenda. Por eso parecía aleatorio.
|
||||
*/
|
||||
|
||||
describe("destinatarioMeta", () => {
|
||||
it("un teléfono va en `to`", () => {
|
||||
expect(destinatarioMeta("5214627015001", null)).toEqual({
|
||||
to: "5214627015001",
|
||||
});
|
||||
});
|
||||
|
||||
it("un BSUID va en `recipient`, con su `recipient_type`", () => {
|
||||
expect(destinatarioMeta(null, "CO.1502852711544066")).toEqual({
|
||||
recipient_type: "individual",
|
||||
recipient: "CO.1502852711544066",
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* La documentación dice que si van los dos, el teléfono tiene precedencia.
|
||||
* Mandar ambos solo añadiría un campo que Meta ignora.
|
||||
*/
|
||||
it("con los dos, gana el teléfono y el BSUID no viaja", () => {
|
||||
const d = destinatarioMeta("5214627015001", "CO.150285");
|
||||
expect(d).toEqual({ to: "5214627015001" });
|
||||
expect(JSON.stringify(d)).not.toContain("CO.150285");
|
||||
});
|
||||
|
||||
it("sin ninguno de los dos no hay destinatario", () => {
|
||||
expect(destinatarioMeta(null, null)).toBeNull();
|
||||
});
|
||||
|
||||
/**
|
||||
* La invariante que impide el fallo original: el BSUID NUNCA puede acabar
|
||||
* en `to`. Si alguien invierte la condición, esto lo dice.
|
||||
*/
|
||||
it("el BSUID jamás aparece en `to`", () => {
|
||||
const d = destinatarioMeta(null, "CO.1502852711544066")!;
|
||||
expect("to" in d).toBe(false);
|
||||
expect(esBsuid(d)).toBe(true);
|
||||
expect(esBsuid({ to: "521462" })).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,34 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { mockGuard } from "@/lib/dev-guard";
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllEnvs();
|
||||
});
|
||||
|
||||
describe("mockGuard (FR-080: mocks en producción → 404)", () => {
|
||||
it("producción con flag activo → 404 igualmente", () => {
|
||||
vi.stubEnv("WA_MOCK_ENABLED", "true");
|
||||
vi.stubEnv("NODE_ENV", "production");
|
||||
const res = mockGuard();
|
||||
expect(res).not.toBeNull();
|
||||
expect(res!.status).toBe(404);
|
||||
});
|
||||
|
||||
it("desarrollo sin flag → 404", () => {
|
||||
vi.stubEnv("WA_MOCK_ENABLED", "");
|
||||
vi.stubEnv("NODE_ENV", "development");
|
||||
expect(mockGuard()?.status).toBe(404);
|
||||
});
|
||||
|
||||
it("desarrollo con flag → permitido (null)", () => {
|
||||
vi.stubEnv("WA_MOCK_ENABLED", "true");
|
||||
vi.stubEnv("NODE_ENV", "development");
|
||||
expect(mockGuard()).toBeNull();
|
||||
});
|
||||
|
||||
it("test con flag → permitido (null)", () => {
|
||||
vi.stubEnv("WA_MOCK_ENABLED", "true");
|
||||
vi.stubEnv("NODE_ENV", "test");
|
||||
expect(mockGuard()).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,317 @@
|
||||
import { readFileSync } from "node:fs";
|
||||
import { mkdtemp, rm, writeFile } from "node:fs/promises";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { parseEnv } from "node:util";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
// Todo lo que toca la base recibe su sonda por parámetro; aquí no hay
|
||||
// Postgres ni drizzle. Se mockea la capa de BD para que el módulo cargue sin
|
||||
// ella (como en credentials.test.ts) y la prueba siga siendo unitaria.
|
||||
vi.mock("@/lib/db", () => ({ getDb: vi.fn(), schema: {}, PG_CONNECTION_OPTIONS: {} }));
|
||||
vi.mock("@/lib/db/tenant", () => ({ scoped: vi.fn() }));
|
||||
|
||||
import {
|
||||
checkDatabase,
|
||||
checkMediaDir,
|
||||
checkWhatsApp,
|
||||
describeDbError,
|
||||
evaluateComposeEnv,
|
||||
evaluateEnv,
|
||||
formatResult,
|
||||
requiredEnvKeys,
|
||||
summarize,
|
||||
type CheckResult,
|
||||
} from "@/server/doctor/checks";
|
||||
import { renderInitEnv } from "@/server/doctor/init-env";
|
||||
import type { Credentials } from "@/server/whatsapp/credentials";
|
||||
|
||||
/**
|
||||
* `pnpm doctor` usa el MISMO esquema que el arranque (safeParseEnv) y, para
|
||||
* cada ✗, dice el comando exacto. Y jamás imprime un secreto: aquí se busca
|
||||
* cada valor secreto en la salida formateada, no solo en los campos.
|
||||
*/
|
||||
|
||||
const RAIZ = path.resolve(import.meta.dirname, "..", "..");
|
||||
const EJEMPLO = readFileSync(path.join(RAIZ, ".env.example"), "utf8");
|
||||
|
||||
const VALIDO = {
|
||||
APP_BASE_URL: "https://localhost",
|
||||
DATABASE_URL: "postgresql://postgres:pw-secreta-xyz@postgres:5432/vocero",
|
||||
BETTER_AUTH_SECRET: "secreto-de-sesiones-" + "s".repeat(24),
|
||||
ENCRYPTION_KEY: Buffer.alloc(32, 7).toString("base64"),
|
||||
META_WEBHOOK_VERIFY_TOKEN: "token-verificacion-" + "t".repeat(45),
|
||||
};
|
||||
|
||||
const porLabel = (results: CheckResult[], label: string) =>
|
||||
results.find((r) => r.label === label);
|
||||
|
||||
const salida = (results: CheckResult[]) => results.map(formatResult).join("\n");
|
||||
|
||||
describe("requiredEnvKeys", () => {
|
||||
it("son las del esquema sin default ni optional, sin copiarlas a mano", () => {
|
||||
expect(requiredEnvKeys()).toEqual([
|
||||
"APP_BASE_URL",
|
||||
"DATABASE_URL",
|
||||
"BETTER_AUTH_SECRET",
|
||||
"ENCRYPTION_KEY",
|
||||
"META_WEBHOOK_VERIFY_TOKEN",
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("evaluateEnv", () => {
|
||||
it("un entorno válido: una ✓ por obligatoria y el env parseado", () => {
|
||||
const { results, env } = evaluateEnv(VALIDO);
|
||||
expect(results.map((r) => r.status)).toEqual(["ok", "ok", "ok", "ok", "ok"]);
|
||||
expect(env?.APP_BASE_URL).toBe("https://localhost");
|
||||
});
|
||||
|
||||
it("lo que deja pnpm init-env pasa entero", () => {
|
||||
const { results, env } = evaluateEnv(parseEnv(renderInitEnv(EJEMPLO).content));
|
||||
expect(results.every((r) => r.status === "ok")).toBe(true);
|
||||
expect(env).not.toBeNull();
|
||||
});
|
||||
|
||||
it("el .env.example copiado tal cual: cada placeholder sale ✗ con su comando", () => {
|
||||
const { results, env } = evaluateEnv(parseEnv(EJEMPLO));
|
||||
expect(env).toBeNull();
|
||||
for (const key of requiredEnvKeys()) {
|
||||
const r = porLabel(results, key);
|
||||
expect(r?.status, key).toBe("fail");
|
||||
expect(r?.detail, key).toContain("REEMPLAZA_");
|
||||
}
|
||||
expect(porLabel(results, "BETTER_AUTH_SECRET")?.fix).toContain("openssl rand -base64 32");
|
||||
expect(porLabel(results, "ENCRYPTION_KEY")?.fix).toContain("openssl rand -base64 32");
|
||||
expect(porLabel(results, "META_WEBHOOK_VERIFY_TOKEN")?.fix).toContain("openssl rand -hex 32");
|
||||
expect(porLabel(results, "APP_BASE_URL")?.fix).toContain("https://");
|
||||
// Las de compose las lista evaluateComposeEnv: aquí no se duplican.
|
||||
expect(porLabel(results, "DOMAIN")).toBeUndefined();
|
||||
expect(porLabel(results, "POSTGRES_PASSWORD")).toBeUndefined();
|
||||
});
|
||||
|
||||
it("una variable que falta y una ENCRYPTION_KEY mal generada: mensaje en español y el arreglo", () => {
|
||||
const source: Record<string, string> = { ...VALIDO, ENCRYPTION_KEY: "corta" };
|
||||
delete source.META_WEBHOOK_VERIFY_TOKEN;
|
||||
const { results } = evaluateEnv(source);
|
||||
const token = porLabel(results, "META_WEBHOOK_VERIFY_TOKEN");
|
||||
expect(token?.status).toBe("fail");
|
||||
expect(token?.detail).toBe("falta");
|
||||
expect(token?.fix).toContain("openssl rand -hex 32");
|
||||
const key = porLabel(results, "ENCRYPTION_KEY");
|
||||
expect(key?.status).toBe("fail");
|
||||
expect(key?.detail).toContain("32 bytes");
|
||||
});
|
||||
|
||||
it("una URL mal escrita y un secreto corto se explican sin inglés", () => {
|
||||
const { results } = evaluateEnv({
|
||||
...VALIDO,
|
||||
APP_BASE_URL: "crm.ejemplo.com",
|
||||
BETTER_AUTH_SECRET: "corto",
|
||||
});
|
||||
expect(porLabel(results, "APP_BASE_URL")?.detail).toContain("no es una URL válida");
|
||||
expect(porLabel(results, "BETTER_AUTH_SECRET")?.detail).toContain("mínimo 16");
|
||||
});
|
||||
|
||||
it("una opcional mal escrita también sale ✗: tumba el arranque igual", () => {
|
||||
const { results, env } = evaluateEnv({ ...VALIDO, OPENROUTER_BASE_URL: "no-es-url" });
|
||||
expect(env).toBeNull();
|
||||
expect(porLabel(results, "OPENROUTER_BASE_URL")?.status).toBe("fail");
|
||||
});
|
||||
|
||||
it("jamás imprime un secreto: ni en ✓ ni en ✗", () => {
|
||||
const texto = salida(evaluateEnv(VALIDO).results);
|
||||
expect(texto).not.toContain("pw-secreta-xyz");
|
||||
expect(texto).not.toContain(VALIDO.BETTER_AUTH_SECRET);
|
||||
expect(texto).not.toContain(VALIDO.ENCRYPTION_KEY);
|
||||
expect(texto).not.toContain(VALIDO.META_WEBHOOK_VERIFY_TOKEN);
|
||||
expect(texto).toContain("postgresql://postgres:***@postgres:5432/vocero");
|
||||
expect(texto).toContain("definida (44 caracteres)");
|
||||
|
||||
const roto = salida(
|
||||
evaluateEnv({ ...VALIDO, ENCRYPTION_KEY: "clave-rota-no-base64-zzz" }).results
|
||||
);
|
||||
expect(roto).not.toContain("clave-rota-no-base64-zzz");
|
||||
});
|
||||
});
|
||||
|
||||
describe("evaluateComposeEnv (DOMAIN y POSTGRES_PASSWORD)", () => {
|
||||
it("placeholder: ✗ con su arreglo; ausente: solo informativo", () => {
|
||||
const conPlaceholder = evaluateComposeEnv(parseEnv(EJEMPLO));
|
||||
expect(porLabel(conPlaceholder, "DOMAIN")?.status).toBe("fail");
|
||||
expect(porLabel(conPlaceholder, "POSTGRES_PASSWORD")?.status).toBe("fail");
|
||||
expect(porLabel(conPlaceholder, "POSTGRES_PASSWORD")?.fix).toContain("openssl rand -hex 24");
|
||||
|
||||
const ausentes = evaluateComposeEnv(VALIDO);
|
||||
expect(ausentes.map((r) => r.status)).toEqual(["skip", "skip"]);
|
||||
});
|
||||
|
||||
it("avisa cuando POSTGRES_PASSWORD no es la contraseña de DATABASE_URL (host postgres)", () => {
|
||||
const results = evaluateComposeEnv({ ...VALIDO, DOMAIN: "localhost", POSTGRES_PASSWORD: "otra" });
|
||||
const aviso = results.find((r) => r.status === "warn");
|
||||
expect(aviso?.label).toBe("POSTGRES_PASSWORD");
|
||||
expect(aviso?.fix).toContain("docker compose");
|
||||
expect(salida(results)).not.toContain("pw-secreta-xyz");
|
||||
});
|
||||
|
||||
it("no avisa cuando coinciden", () => {
|
||||
const results = evaluateComposeEnv({ ...VALIDO, DOMAIN: "localhost", POSTGRES_PASSWORD: "pw-secreta-xyz" });
|
||||
expect(results.every((r) => r.status === "ok")).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("checkDatabase", () => {
|
||||
const url = VALIDO.DATABASE_URL;
|
||||
|
||||
it("select 1 responde: ✓ con la URL sin contraseña", async () => {
|
||||
const r = await checkDatabase(url, async () => {});
|
||||
expect(r.status).toBe("ok");
|
||||
expect(r.detail).toContain("postgres:***@");
|
||||
expect(formatResult(r)).not.toContain("pw-secreta-xyz");
|
||||
});
|
||||
|
||||
it("ECONNREFUSED: nada escucha, y cómo arrancar Postgres", async () => {
|
||||
const r = await checkDatabase(url, async () => {
|
||||
throw Object.assign(new Error("connect ECONNREFUSED"), { code: "ECONNREFUSED" });
|
||||
});
|
||||
expect(r.status).toBe("fail");
|
||||
expect(r.detail).toContain("nada escucha");
|
||||
expect(r.fix).toContain("docker compose");
|
||||
});
|
||||
|
||||
it("el host «postgres» sin resolver no es un fallo: es la red interna de compose", () => {
|
||||
const r = describeDbError(Object.assign(new Error("getaddrinfo ENOTFOUND postgres"), { code: "ENOTFOUND" }), url);
|
||||
expect(r.status).toBe("skip");
|
||||
expect(r.fix).toContain("docker compose up -d");
|
||||
});
|
||||
|
||||
it("otro host sin resolver sí es ✗", () => {
|
||||
const r = describeDbError(
|
||||
Object.assign(new Error("ENOTFOUND"), { code: "ENOTFOUND" }),
|
||||
"postgresql://postgres:x@bd.interna:5432/vocero"
|
||||
);
|
||||
expect(r.status).toBe("fail");
|
||||
});
|
||||
|
||||
it("28P01: contraseña rechazada, y dónde se corrige", () => {
|
||||
const r = describeDbError(Object.assign(new Error("password authentication failed"), { code: "28P01" }), url);
|
||||
expect(r.status).toBe("fail");
|
||||
expect(r.detail).toContain("contraseña");
|
||||
expect(r.fix).toContain("POSTGRES_PASSWORD");
|
||||
expect(formatResult(r)).not.toContain("pw-secreta-xyz");
|
||||
});
|
||||
});
|
||||
|
||||
describe("checkMediaDir", () => {
|
||||
let tmp: string;
|
||||
beforeEach(async () => {
|
||||
tmp = await mkdtemp(path.join(os.tmpdir(), "vocero-doctor-media-"));
|
||||
});
|
||||
afterEach(async () => {
|
||||
await rm(tmp, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
it("directorio escribible (lo crea si falta): ✓", async () => {
|
||||
const r = await checkMediaDir(path.join(tmp, "media"));
|
||||
expect(r.status).toBe("ok");
|
||||
});
|
||||
|
||||
it("no escribible: ✗ con qué hacer dentro y fuera de Docker", async () => {
|
||||
const archivo = path.join(tmp, "no-soy-directorio");
|
||||
await writeFile(archivo, "x");
|
||||
const r = await checkMediaDir(path.join(archivo, "media"));
|
||||
expect(r.status).toBe("fail");
|
||||
expect(r.fix).toContain("/data");
|
||||
});
|
||||
});
|
||||
|
||||
describe("checkWhatsApp", () => {
|
||||
const credenciales = (token: string): Credentials => ({
|
||||
id: "cred_1",
|
||||
organizationId: "org_1",
|
||||
wabaId: "waba1",
|
||||
messagingAccountId: null,
|
||||
phoneNumberId: "pn1",
|
||||
displayPhoneNumber: "+52 1 55 0000 0000",
|
||||
verifiedName: "Ferretería",
|
||||
status: "connected",
|
||||
token,
|
||||
});
|
||||
const guardada = (token: string) => ({
|
||||
organization: "Ferretería El Martillo",
|
||||
phoneNumberId: "pn1",
|
||||
displayPhoneNumber: "+52 1 55 0000 0000",
|
||||
credentials: credenciales(token),
|
||||
});
|
||||
|
||||
it("sin conexión guardada: informativo, no ✗ (se conecta desde la app)", async () => {
|
||||
const [r] = await checkWhatsApp({ load: async () => [] });
|
||||
expect(r?.status).toBe("skip");
|
||||
expect(r?.detail).toContain("Configuración → WhatsApp");
|
||||
});
|
||||
|
||||
it("token vigente: ✓ con los últimos 4 del token y nunca el token entero", async () => {
|
||||
const token = "EAAG-token-super-secreto-abcd";
|
||||
const [r] = await checkWhatsApp({
|
||||
load: async () => [guardada(token)],
|
||||
test: async () => ({ ok: true, displayPhoneNumber: "+52 55 0000 0000", verifiedName: "Ferretería" }),
|
||||
});
|
||||
expect(r?.status).toBe("ok");
|
||||
expect(r?.detail).toContain("…abcd");
|
||||
expect(formatResult(r!)).not.toContain("EAAG-token");
|
||||
});
|
||||
|
||||
it("token vencido: ✗ y el arreglo es pegar uno nuevo en la app", async () => {
|
||||
const [r] = await checkWhatsApp({
|
||||
load: async () => [guardada("EAAG-vencido-9999")],
|
||||
test: async () => ({ ok: false, code: "invalid_token", message: "El token no es válido o expiró." }),
|
||||
});
|
||||
expect(r?.status).toBe("fail");
|
||||
expect(r?.fix).toContain("Configuración → WhatsApp");
|
||||
expect(formatResult(r!)).not.toContain("EAAG-vencido");
|
||||
});
|
||||
|
||||
it("Meta caída: aviso, no ✗ (no es algo que el usuario arregle)", async () => {
|
||||
const [r] = await checkWhatsApp({
|
||||
load: async () => [guardada("EAAG-x-1234")],
|
||||
test: async () => ({ ok: false, code: "meta_unavailable", message: "Meta no está disponible" }),
|
||||
});
|
||||
expect(r?.status).toBe("warn");
|
||||
});
|
||||
|
||||
it("una fila que no descifra apunta a la ENCRYPTION_KEY", async () => {
|
||||
const [r] = await checkWhatsApp({
|
||||
load: async () => [{ ...guardada("x"), credentials: null }],
|
||||
});
|
||||
expect(r?.status).toBe("fail");
|
||||
expect(r?.detail).toContain("ENCRYPTION_KEY");
|
||||
});
|
||||
|
||||
it("tablas sin migrar (42P01): informativo, con el paso que las crea", async () => {
|
||||
const [r] = await checkWhatsApp({
|
||||
load: async () => {
|
||||
throw Object.assign(new Error('relation "organization" does not exist'), { code: "42P01" });
|
||||
},
|
||||
});
|
||||
expect(r?.status).toBe("skip");
|
||||
expect(r?.fix).toContain("docker compose up -d");
|
||||
});
|
||||
});
|
||||
|
||||
describe("formatResult y summarize", () => {
|
||||
it("✓ en una línea; ✗ con la flecha del arreglo debajo", () => {
|
||||
expect(formatResult({ status: "ok", label: "X", detail: "bien" })).toBe("✓ X — bien");
|
||||
expect(formatResult({ status: "fail", label: "X", detail: "mal", fix: "haz esto" })).toBe(
|
||||
"✗ X — mal\n → haz esto"
|
||||
);
|
||||
});
|
||||
|
||||
it("sale con 1 solo si hay ✗: los avisos y lo informativo no cuentan", () => {
|
||||
const ok: CheckResult = { status: "ok", label: "a" };
|
||||
const warn: CheckResult = { status: "warn", label: "b" };
|
||||
const skip: CheckResult = { status: "skip", label: "c" };
|
||||
const fail: CheckResult = { status: "fail", label: "d" };
|
||||
expect(summarize([ok, warn, skip]).exitCode).toBe(0);
|
||||
expect(summarize([ok, warn, skip, fail])).toMatchObject({ ok: 1, warn: 1, skip: 1, fail: 1, exitCode: 1 });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,84 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { mediaInputFrom } from "@/server/inbox/ingest";
|
||||
import type { WebhookMessage } from "@/server/inbox/webhook";
|
||||
|
||||
/**
|
||||
* 008 — Parser tolerante de adjuntos del webhook (entrantes y echoes).
|
||||
* La integración completa (echo → hilo + pausa de IA) se ejercita en el
|
||||
* self-test E2E (scripts/e2e-selftest.mjs, sección 008).
|
||||
*/
|
||||
describe("mediaInputFrom (008)", () => {
|
||||
const base = { id: "wamid.x", timestamp: "1722800000" };
|
||||
|
||||
it("imagen con media id → asset pending con mime y caption", () => {
|
||||
const msg: WebhookMessage = {
|
||||
...base,
|
||||
type: "image",
|
||||
image: { id: "media9", mime_type: "image/jpeg", caption: "mira esto" },
|
||||
};
|
||||
expect(mediaInputFrom(msg)).toMatchObject({
|
||||
kind: "image",
|
||||
waMediaId: "media9",
|
||||
mimeType: "image/jpeg",
|
||||
caption: "mira esto",
|
||||
fetchStatus: "pending",
|
||||
});
|
||||
});
|
||||
|
||||
it("documento conserva filename", () => {
|
||||
const msg: WebhookMessage = {
|
||||
...base,
|
||||
type: "document",
|
||||
document: { id: "media10", mime_type: "application/pdf", filename: "cotizacion.pdf" },
|
||||
};
|
||||
expect(mediaInputFrom(msg)).toMatchObject({
|
||||
kind: "document",
|
||||
fileName: "cotizacion.pdf",
|
||||
});
|
||||
});
|
||||
|
||||
it("media sin id (payload incompleto) → null, el mensaje se conserva sin adjunto", () => {
|
||||
const msg: WebhookMessage = { ...base, type: "image", image: {} };
|
||||
expect(mediaInputFrom(msg)).toBeNull();
|
||||
});
|
||||
|
||||
it("ubicación válida → asset available con payload directo (sin binario)", () => {
|
||||
const msg: WebhookMessage = {
|
||||
...base,
|
||||
type: "location",
|
||||
location: { latitude: 21.019, longitude: -101.257, name: "Oficina" },
|
||||
};
|
||||
expect(mediaInputFrom(msg)).toMatchObject({
|
||||
kind: "location",
|
||||
waMediaId: null,
|
||||
fetchStatus: "available",
|
||||
payload: { latitude: 21.019, longitude: -101.257, name: "Oficina" },
|
||||
});
|
||||
});
|
||||
|
||||
it("ubicación sin coordenadas numéricas → null (tolerante, no revienta)", () => {
|
||||
const msg: WebhookMessage = {
|
||||
...base,
|
||||
type: "location",
|
||||
location: { name: "??" },
|
||||
};
|
||||
expect(mediaInputFrom(msg)).toBeNull();
|
||||
});
|
||||
|
||||
it("contacto compartido → asset available con la lista como payload", () => {
|
||||
const msg: WebhookMessage = {
|
||||
...base,
|
||||
type: "contacts",
|
||||
contacts: [{ name: { formatted_name: "Xavier" }, phones: [{ phone: "+52123" }] }],
|
||||
};
|
||||
expect(mediaInputFrom(msg)).toMatchObject({
|
||||
kind: "contacts",
|
||||
fetchStatus: "available",
|
||||
});
|
||||
});
|
||||
|
||||
it("texto plano → null", () => {
|
||||
const msg: WebhookMessage = { ...base, type: "text", text: { body: "hola" } };
|
||||
expect(mediaInputFrom(msg)).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,331 @@
|
||||
import { createServer, type Server } from "node:http";
|
||||
import type { AddressInfo } from "node:net";
|
||||
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
/**
|
||||
* 066 — «Conectar con Meta» (Embedded Signup v4).
|
||||
*
|
||||
* - el evento de sesión y las opciones de `FB.login` / `FB.init`;
|
||||
* - el alta en el servidor: canje del `code` (por `node:http` contra un
|
||||
* servidor local, como el wa-mock), número de la WABA, registro con PIN,
|
||||
* credenciales y webhook; nada se guarda si algo falla antes;
|
||||
* - la ruta: 404 sin configuración, rol, origen.
|
||||
*/
|
||||
|
||||
const env = vi.hoisted(() => ({
|
||||
APP_BASE_URL: "https://crm.ejemplo.test",
|
||||
META_WEBHOOK_VERIFY_TOKEN: "verify-token-xyz",
|
||||
META_GRAPH_BASE_URL: "http://127.0.0.1:1",
|
||||
META_GRAPH_API_VERSION: "v25.0",
|
||||
META_APP_ID: "1715957376325225" as string | undefined,
|
||||
META_EMBEDDED_CONFIG_ID: "998877" as string | undefined,
|
||||
META_APP_SECRET: "secreto-de-la-app" as string | undefined,
|
||||
}));
|
||||
vi.mock("@/lib/env", () => ({ getEnv: () => env }));
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
session: vi.fn(),
|
||||
save: vi.fn(),
|
||||
webhook: vi.fn(),
|
||||
descubrir: vi.fn(),
|
||||
}));
|
||||
vi.mock("@/lib/auth/session", async (original) => ({
|
||||
...(await original<typeof import("@/lib/auth/session")>()),
|
||||
requireSession: mocks.session,
|
||||
}));
|
||||
vi.mock("@/server/whatsapp/credentials", () => ({ saveCredentials: mocks.save }));
|
||||
vi.mock("@/server/whatsapp/connect", () => ({
|
||||
registerWebhookForNumber: mocks.webhook,
|
||||
descubrirCuentaDeMensajes: mocks.descubrir,
|
||||
}));
|
||||
|
||||
import {
|
||||
completarAltaEmbebida,
|
||||
EmbeddedSignupError,
|
||||
embeddedConfig,
|
||||
generarPin,
|
||||
} from "@/server/whatsapp/embedded";
|
||||
import { leerEventoDeAlta, opcionesDeInit, opcionesDeLogin } from "@/lib/meta/signup-event";
|
||||
import { GET, POST } from "@/app/api/settings/whatsapp/embedded/route";
|
||||
import { resetRateLimit } from "@/lib/rate-limit";
|
||||
|
||||
/** El canje de Meta: un servidor local, porque va por node:http y no por fetch. */
|
||||
let server: Server;
|
||||
const canjes: URLSearchParams[] = [];
|
||||
beforeAll(async () => {
|
||||
server = createServer((req, res) => {
|
||||
const url = new URL(req.url ?? "/", "http://x");
|
||||
canjes.push(url.searchParams);
|
||||
const ok =
|
||||
url.pathname === "/v25.0/oauth/access_token" &&
|
||||
url.searchParams.get("client_secret") === "secreto-de-la-app" &&
|
||||
url.searchParams.get("code") !== "code-malo";
|
||||
res.writeHead(ok ? 200 : 400, { "content-type": "application/json" });
|
||||
res.end(JSON.stringify(ok ? { access_token: "EAAG-del-cliente" } : { error: { message: "bad code", code: 100 } }));
|
||||
});
|
||||
await new Promise<void>((r) => server.listen(0, "127.0.0.1", r));
|
||||
env.META_GRAPH_BASE_URL = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
|
||||
});
|
||||
afterAll(() => new Promise<void>((r) => server.close(() => r())));
|
||||
|
||||
const fetchMock = vi.fn();
|
||||
const respond = (data: unknown, status = 200) =>
|
||||
fetchMock.mockResolvedValueOnce(new Response(JSON.stringify(data), { status }));
|
||||
const graphCall = (i: number) => {
|
||||
const [url, init] = fetchMock.mock.calls[i]! as [string, RequestInit];
|
||||
return { url, method: init.method ?? "GET", body: init.body ? JSON.parse(String(init.body)) : undefined };
|
||||
};
|
||||
const numero = (id: string, extra: Record<string, unknown> = {}) => ({
|
||||
id,
|
||||
display_phone_number: "+51 999 888 777",
|
||||
verified_name: "AvisaPe",
|
||||
status: "PENDING",
|
||||
...extra,
|
||||
});
|
||||
const WEBHOOK_OK = { ok: true, appWithoutWebhook: false, messagingAccount: { ok: true } };
|
||||
|
||||
beforeEach(() => {
|
||||
vi.stubGlobal("fetch", fetchMock);
|
||||
fetchMock.mockReset();
|
||||
canjes.length = 0;
|
||||
vi.clearAllMocks();
|
||||
env.META_APP_ID = "1715957376325225";
|
||||
env.META_EMBEDDED_CONFIG_ID = "998877";
|
||||
env.META_APP_SECRET = "secreto-de-la-app";
|
||||
mocks.session.mockResolvedValue({ organizationId: "org_1", userId: "usr_1", role: "owner" });
|
||||
mocks.save.mockResolvedValue(undefined);
|
||||
mocks.webhook.mockResolvedValue(WEBHOOK_OK);
|
||||
mocks.descubrir.mockResolvedValue("163890796811554");
|
||||
resetRateLimit();
|
||||
});
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
describe("el evento de sesión de Meta", () => {
|
||||
const FB = "https://www.facebook.com";
|
||||
const ev = (event: string, data: Record<string, unknown> = {}) => ({ type: "WA_EMBEDDED_SIGNUP", event, data });
|
||||
|
||||
it("FINISH trae la WABA y el número; también si llega como texto JSON", () => {
|
||||
const esperado = { kind: "finish", wabaId: "160228957180064", phoneNumberId: "555" };
|
||||
expect(leerEventoDeAlta(FB, ev("FINISH", { waba_id: "160228957180064", phone_number_id: "555" }))).toEqual(esperado);
|
||||
expect(
|
||||
leerEventoDeAlta(
|
||||
"https://business.facebook.com",
|
||||
JSON.stringify(ev("FINISH", { waba_id: "160228957180064", phone_number_id: "555" }))
|
||||
)
|
||||
).toEqual(esperado);
|
||||
});
|
||||
|
||||
it("FINISH_ONLY_WABA sin número deja phoneNumberId en null", () => {
|
||||
expect(leerEventoDeAlta(FB, ev("FINISH_ONLY_WABA", { waba_id: "1" }))).toEqual({
|
||||
kind: "finish",
|
||||
wabaId: "1",
|
||||
phoneNumberId: null,
|
||||
});
|
||||
});
|
||||
|
||||
it("cancelación, error y coexistencia se distinguen", () => {
|
||||
expect(leerEventoDeAlta(FB, ev("CANCEL", { current_step: "PHONE_NUMBER_SETUP" }))).toEqual({ kind: "cancel" });
|
||||
expect(leerEventoDeAlta(FB, ev("ERROR", { error_message: "falló" }))).toEqual({ kind: "error", message: "falló" });
|
||||
expect(leerEventoDeAlta(FB, ev("FINISH_WHATSAPP_BUSINESS_APP_ONBOARDING", { waba_id: "1" }))).toEqual({
|
||||
kind: "coexistence",
|
||||
});
|
||||
});
|
||||
|
||||
it("ignora otros orígenes, otros mensajes y IDs que no son números", () => {
|
||||
expect(leerEventoDeAlta("https://evil.test", ev("FINISH", { waba_id: "1", phone_number_id: "2" }))).toBeNull();
|
||||
expect(leerEventoDeAlta(FB, "no-es-json")).toBeNull();
|
||||
expect(leerEventoDeAlta(FB, { type: "OTRA_COSA" })).toBeNull();
|
||||
expect(leerEventoDeAlta(FB, ev("FINISH", { waba_id: "1;drop" }))).toBeNull();
|
||||
expect(leerEventoDeAlta(FB, ev("FINISH", {}))).toBeNull();
|
||||
});
|
||||
|
||||
it("FB.login pide el code con config_id y extras v4; FB.init apaga FedCM", () => {
|
||||
expect(opcionesDeLogin("998877")).toEqual({
|
||||
config_id: "998877",
|
||||
response_type: "code",
|
||||
override_default_response_type: true,
|
||||
extras: { setup: {}, sessionInfoVersion: "3", version: "v4" },
|
||||
});
|
||||
expect(opcionesDeInit("1715957376325225", "v25.0")).toMatchObject({
|
||||
appId: "1715957376325225",
|
||||
version: "v25.0",
|
||||
fedCM: false,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("configuración de la instancia (CA-1)", () => {
|
||||
it("lista solo con App ID, Config ID numéricos y el secreto", () => {
|
||||
expect(embeddedConfig().ready).toBe(true);
|
||||
env.META_EMBEDDED_CONFIG_ID = undefined;
|
||||
expect(embeddedConfig().ready).toBe(false);
|
||||
env.META_EMBEDDED_CONFIG_ID = "998877";
|
||||
env.META_APP_SECRET = undefined;
|
||||
expect(embeddedConfig().ready).toBe(false);
|
||||
env.META_APP_SECRET = "s";
|
||||
env.META_APP_ID = "abc";
|
||||
expect(embeddedConfig().ready).toBe(false);
|
||||
});
|
||||
|
||||
it("el PIN generado son seis dígitos", () => {
|
||||
for (let i = 0; i < 50; i++) expect(generarPin()).toMatch(/^\d{6}$/);
|
||||
});
|
||||
});
|
||||
|
||||
describe("el alta en el servidor", () => {
|
||||
const input = { organizationId: "org_1", code: "code-bueno", wabaId: "160228957180064", phoneNumberId: "555", pin: null };
|
||||
|
||||
it("canjea, verifica el número, lo registra con un PIN generado, guarda y registra el webhook", async () => {
|
||||
respond({ data: [numero("444"), numero("555")] }); // phone_numbers
|
||||
respond({ success: true }); // register
|
||||
|
||||
const r = await completarAltaEmbebida(input);
|
||||
|
||||
expect(canjes[0]!.get("client_id")).toBe("1715957376325225");
|
||||
expect(canjes[0]!.get("code")).toBe("code-bueno");
|
||||
expect(canjes[0]!.has("redirect_uri")).toBe(false);
|
||||
expect(graphCall(0).url).toContain("/160228957180064/phone_numbers?");
|
||||
expect(graphCall(1)).toMatchObject({
|
||||
url: expect.stringContaining("/555/register"),
|
||||
method: "POST",
|
||||
body: { messaging_product: "whatsapp", pin: r.generatedPin },
|
||||
});
|
||||
expect(r.generatedPin).toMatch(/^\d{6}$/);
|
||||
expect(mocks.save).toHaveBeenCalledWith({
|
||||
organizationId: "org_1",
|
||||
wabaId: "160228957180064",
|
||||
messagingAccountId: "163890796811554",
|
||||
phoneNumberId: "555",
|
||||
token: "EAAG-del-cliente",
|
||||
displayPhoneNumber: "+51 999 888 777",
|
||||
verifiedName: "AvisaPe",
|
||||
});
|
||||
expect(mocks.webhook).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
wabaId: "160228957180064",
|
||||
phoneNumberId: "555",
|
||||
token: "EAAG-del-cliente",
|
||||
messagingAccountId: "163890796811554",
|
||||
webhookUrl: "https://crm.ejemplo.test/api/webhooks/wa/verify-token-xyz",
|
||||
})
|
||||
);
|
||||
expect(r).toMatchObject({ registered: true, displayPhoneNumber: "+51 999 888 777", webhook: WEBHOOK_OK });
|
||||
expect(JSON.stringify(r)).not.toContain("EAAG-del-cliente");
|
||||
});
|
||||
|
||||
it("con el PIN del dueño lo usa y no lo devuelve; un número CONNECTED no se re-registra", async () => {
|
||||
respond({ data: [numero("555")] });
|
||||
respond({ success: true });
|
||||
const r = await completarAltaEmbebida({ ...input, pin: "123456" });
|
||||
expect(graphCall(1).body).toEqual({ messaging_product: "whatsapp", pin: "123456" });
|
||||
expect(r.generatedPin).toBeUndefined();
|
||||
|
||||
fetchMock.mockReset();
|
||||
respond({ data: [numero("555", { status: "CONNECTED" })] });
|
||||
const r2 = await completarAltaEmbebida({ ...input, code: "code-2" });
|
||||
expect(fetchMock).toHaveBeenCalledTimes(1);
|
||||
expect(r2).toMatchObject({ registered: false });
|
||||
expect(r2.generatedPin).toBeUndefined();
|
||||
});
|
||||
|
||||
it("sin phone_number_id usa el único número; con varios falla sin guardar (CA-3)", async () => {
|
||||
respond({ data: [numero("555")] });
|
||||
respond({ success: true });
|
||||
expect((await completarAltaEmbebida({ ...input, phoneNumberId: null })).phoneNumberId).toBe("555");
|
||||
|
||||
respond({ data: [numero("444"), numero("555")] });
|
||||
mocks.save.mockClear();
|
||||
await expect(completarAltaEmbebida({ ...input, code: "c3", phoneNumberId: null })).rejects.toMatchObject({
|
||||
code: "varios_numeros",
|
||||
});
|
||||
expect(mocks.save).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("un número que no es de la WABA, o ON_PREMISE, falla sin guardar", async () => {
|
||||
respond({ data: [numero("444")] });
|
||||
await expect(completarAltaEmbebida(input)).rejects.toMatchObject({ code: "asset_mismatch" });
|
||||
respond({ data: [numero("555", { platform_type: "ON_PREMISE" })] });
|
||||
await expect(completarAltaEmbebida(input)).rejects.toMatchObject({ code: "migration_required" });
|
||||
expect(mocks.save).not.toHaveBeenCalled();
|
||||
expect(mocks.webhook).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("si Meta no registra el número, no se guarda nada", async () => {
|
||||
respond({ data: [numero("555")] });
|
||||
respond({ error: { message: "PIN Mismatch", code: 133005 } }, 400);
|
||||
await expect(completarAltaEmbebida(input)).rejects.toMatchObject({ code: "registration_failed" });
|
||||
expect(mocks.save).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("un code que Meta no acepta falla sin hablar con la Graph API ni filtrar el secreto (CA-7)", async () => {
|
||||
const err = await completarAltaEmbebida({ ...input, code: "code-malo" }).catch((e: unknown) => e);
|
||||
expect(err).toBeInstanceOf(EmbeddedSignupError);
|
||||
expect((err as EmbeddedSignupError).code).toBe("exchange_failed");
|
||||
expect((err as Error).message).not.toContain("secreto-de-la-app");
|
||||
expect((err as Error).message).not.toContain("code-malo");
|
||||
expect(fetchMock).not.toHaveBeenCalled();
|
||||
expect(mocks.save).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe("la ruta /api/settings/whatsapp/embedded", () => {
|
||||
const post = (body: unknown, origin = "https://crm.ejemplo.test") =>
|
||||
POST(
|
||||
new Request("https://crm.ejemplo.test/api/settings/whatsapp/embedded", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json", origin, host: "crm.ejemplo.test" },
|
||||
body: JSON.stringify(body),
|
||||
})
|
||||
);
|
||||
const valido = { code: "code-bueno", wabaId: "160228957180064", phoneNumberId: "555", pin: null };
|
||||
|
||||
it("sin configuración, GET y POST responden 404 (CA-1)", async () => {
|
||||
env.META_APP_ID = undefined;
|
||||
expect((await GET()).status).toBe(404);
|
||||
expect((await post(valido)).status).toBe(404);
|
||||
});
|
||||
|
||||
it("GET da lo del SDK a quien configura, nunca el secreto; a un miembro, solo que no puede", async () => {
|
||||
const res = await GET();
|
||||
const data = await res.json();
|
||||
expect(data).toEqual({
|
||||
ready: true,
|
||||
canManage: true,
|
||||
appId: "1715957376325225",
|
||||
configId: "998877",
|
||||
graphVersion: "v25.0",
|
||||
});
|
||||
expect(JSON.stringify(data)).not.toContain("secreto");
|
||||
mocks.session.mockResolvedValue({ organizationId: "org_1", userId: "usr_2", role: "member" });
|
||||
expect(await (await GET()).json()).toEqual({ ready: true, canManage: false });
|
||||
});
|
||||
|
||||
it("un miembro, otro origen o un cuerpo inválido no llegan a Meta (CA-2)", async () => {
|
||||
mocks.session.mockResolvedValue({ organizationId: "org_1", userId: "usr_2", role: "member" });
|
||||
expect((await post(valido)).status).toBe(403);
|
||||
mocks.session.mockResolvedValue({ organizationId: "org_1", userId: "usr_1", role: "owner" });
|
||||
expect((await post(valido, "https://evil.test")).status).toBe(403);
|
||||
expect((await post({ ...valido, pin: "12" })).status).toBe(422);
|
||||
expect(canjes).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("completa el alta y responde el número, el webhook y el PIN generado", async () => {
|
||||
respond({ data: [numero("555")] });
|
||||
respond({ success: true });
|
||||
const res = await post(valido);
|
||||
expect(res.status).toBe(200);
|
||||
const data = await res.json();
|
||||
expect(data).toMatchObject({ connected: true, phoneNumberId: "555", registered: true, webhook: WEBHOOK_OK });
|
||||
expect(data.generatedPin).toMatch(/^\d{6}$/);
|
||||
expect(JSON.stringify(data)).not.toContain("EAAG-del-cliente");
|
||||
});
|
||||
|
||||
it("un fallo de Meta vuelve como error legible, sin guardar", async () => {
|
||||
respond({ data: [] });
|
||||
const res = await post(valido);
|
||||
expect(res.status).toBe(422);
|
||||
expect((await res.json()).error.code).toBe("asset_mismatch");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,98 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
EMOJIS,
|
||||
EMOJI_CATEGORIES,
|
||||
emojiSearchText,
|
||||
filterEmojis,
|
||||
insertAtSelection,
|
||||
} from "@/lib/emojis";
|
||||
|
||||
const labels = (list: readonly { label: string }[]) => list.map((e) => e.label);
|
||||
|
||||
describe("041 — catálogo de emojis", () => {
|
||||
it("cada emoji aparece una sola vez, con nombre y en una categoría que existe", () => {
|
||||
const values = EMOJIS.map((e) => e.value);
|
||||
expect(new Set(values).size).toBe(values.length);
|
||||
const ids = new Set<string>(EMOJI_CATEGORIES.map((c) => c.id));
|
||||
for (const emoji of EMOJIS) {
|
||||
expect(emoji.label.trim()).not.toBe("");
|
||||
expect(ids.has(emoji.category)).toBe(true);
|
||||
}
|
||||
});
|
||||
|
||||
it("los nombres no se repiten: el nombre accesible identifica al botón", () => {
|
||||
const names = EMOJIS.map((e) => e.label);
|
||||
expect(new Set(names).size).toBe(names.length);
|
||||
});
|
||||
|
||||
it("todas las categorías tienen emojis", () => {
|
||||
for (const { id } of EMOJI_CATEGORIES) {
|
||||
expect(EMOJIS.some((e) => e.category === id)).toBe(true);
|
||||
}
|
||||
});
|
||||
|
||||
it("es solo texto: ningún valor parece una URL o una ruta", () => {
|
||||
for (const { value } of EMOJIS) expect(value).not.toMatch(/[/:.<>]|^[\w\s]+$/);
|
||||
});
|
||||
});
|
||||
|
||||
describe("041 — búsqueda", () => {
|
||||
it("no distingue acentos ni mayúsculas", () => {
|
||||
expect(emojiSearchText("Corazón ROJO")).toBe("corazon rojo");
|
||||
expect(labels(filterEmojis("corazon rojo", "all"))).toEqual(["Corazón rojo"]);
|
||||
expect(labels(filterEmojis(" CORAZÓN EN LLAMAS ", "all"))).toEqual(["Corazón en llamas"]);
|
||||
});
|
||||
|
||||
it("busca en todo el catálogo aunque haya una categoría elegida", () => {
|
||||
const found = filterEmojis("sonrisa", "food");
|
||||
expect(found.length).toBeGreaterThan(0);
|
||||
expect(found.every((e) => e.category === "faces")).toBe(true);
|
||||
});
|
||||
|
||||
it("sin búsqueda enseña la categoría, o todo con «all»", () => {
|
||||
expect(filterEmojis("", "hearts").every((e) => e.category === "hearts")).toBe(true);
|
||||
expect(filterEmojis(" ", "all")).toHaveLength(EMOJIS.length);
|
||||
});
|
||||
|
||||
it("encuentra por el propio emoji pegado en la búsqueda", () => {
|
||||
expect(labels(filterEmojis("👍", "all"))).toEqual(["Pulgar arriba"]);
|
||||
});
|
||||
|
||||
it("sin coincidencias devuelve una lista vacía", () => {
|
||||
expect(filterEmojis("emojisincoincidencias", "all")).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("041 — insertar en el cursor", () => {
|
||||
it("inserta en el cursor y deja el cursor detrás del emoji", () => {
|
||||
expect(insertAtSelection("Hola mundo", 4, 4, "😀")).toEqual({ text: "Hola😀 mundo", caret: 6 });
|
||||
});
|
||||
|
||||
it("reemplaza solo la selección y conserva lo de antes y lo de después", () => {
|
||||
expect(insertAtSelection("Hola mundo, gracias", 5, 10, "❤️🔥")).toEqual({
|
||||
text: "Hola ❤️🔥, gracias",
|
||||
caret: 5 + "❤️🔥".length,
|
||||
});
|
||||
});
|
||||
|
||||
it("con el texto vacío o el cursor al final, añade al final", () => {
|
||||
expect(insertAtSelection("", 0, 0, "👋")).toEqual({ text: "👋", caret: 2 });
|
||||
expect(insertAtSelection("Listo", 5, 5, "✅")).toEqual({ text: "Listo✅", caret: 6 });
|
||||
});
|
||||
|
||||
it("aguanta una selección al revés o fuera de rango", () => {
|
||||
expect(insertAtSelection("abcdef", 4, 2, "-")).toEqual({ text: "ab-ef", caret: 3 });
|
||||
expect(insertAtSelection("abc", 10, 12, "!")).toEqual({ text: "abc!", caret: 4 });
|
||||
});
|
||||
|
||||
it("reemplazar un emoji por el mismo deja el texto igual", () => {
|
||||
const r = insertAtSelection("A😀B", 1, 3, "😀");
|
||||
expect(r).toEqual({ text: "A😀B", caret: 3 });
|
||||
});
|
||||
|
||||
it("varias inserciones seguidas se acumulan en orden", () => {
|
||||
let state = { text: "Hola ", caret: 5 };
|
||||
for (const e of ["🎉", "🎉", "👏"]) state = insertAtSelection(state.text, state.caret, state.caret, e);
|
||||
expect(state.text).toBe("Hola 🎉🎉👏");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,35 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
/**
|
||||
* `BRAIN_HEALTH_URL` es opcional y solo de diagnóstico: un valor mal escrito
|
||||
* no puede tumbar el CRM. Con `.url()` en el esquema, `getEnv()` lanzaba y
|
||||
* toda la app respondía 503 por una tarjeta. Ahora la tarjeta lo marca
|
||||
* (`problem: "config"`) y lo demás sigue.
|
||||
*/
|
||||
|
||||
const BASE = {
|
||||
APP_BASE_URL: "http://localhost:3000",
|
||||
DATABASE_URL: "postgresql://u:p@localhost:5432/db",
|
||||
BETTER_AUTH_SECRET: "x".repeat(32),
|
||||
ENCRYPTION_KEY: Buffer.alloc(32).toString("base64"),
|
||||
META_WEBHOOK_VERIFY_TOKEN: "token-de-prueba",
|
||||
};
|
||||
|
||||
const original = { ...process.env };
|
||||
|
||||
afterEach(() => {
|
||||
process.env = { ...original };
|
||||
vi.resetModules();
|
||||
});
|
||||
|
||||
describe("BRAIN_HEALTH_URL no tumba el arranque", () => {
|
||||
it.each(["nea:8000/health", "ftp://nea/health", "no es una url"])(
|
||||
"%s → getEnv no lanza y la conserva tal cual",
|
||||
async (valor) => {
|
||||
process.env = { ...original, ...BASE, BRAIN_HEALTH_URL: valor };
|
||||
vi.resetModules();
|
||||
const { getEnv } = await import("@/lib/env");
|
||||
expect(getEnv().BRAIN_HEALTH_URL).toBe(valor);
|
||||
}
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,194 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
avisoEsperandoDeCookie,
|
||||
claveDeEspera,
|
||||
cookieDeAvisoEsperando,
|
||||
esperasDe,
|
||||
estaEsperando,
|
||||
minutosDeEspera,
|
||||
MODOS_ESPERANDO,
|
||||
nivelDeEspera,
|
||||
nuevasParaAvisar,
|
||||
textoAviso,
|
||||
textoCintillo,
|
||||
textoMinutos,
|
||||
} from "@/lib/esperando";
|
||||
import { urlDeAvisoSegura } from "@/lib/avisos-sistema";
|
||||
import {
|
||||
calcularEspera,
|
||||
contestableHasta,
|
||||
necesitaPersona,
|
||||
primerMensajeSinRespuesta,
|
||||
VENTANA_MAXIMA_MS,
|
||||
type MensajeParaEspera,
|
||||
} from "@/server/inbox/esperando";
|
||||
|
||||
/** 077 — «Esperando a una persona»: la regla, el semáforo y los textos. */
|
||||
|
||||
const T0 = Date.parse("2026-11-23T15:00:00.000Z");
|
||||
const HORA = 3_600_000;
|
||||
const min = (n: number) => new Date(T0 + n * 60_000);
|
||||
|
||||
const entra = (m: number): MensajeParaEspera => ({ direction: "in", status: "delivered", aiGenerated: false, createdAt: min(m) });
|
||||
const equipo = (m: number, status = "sent"): MensajeParaEspera => ({ direction: "out", status, aiGenerated: false, createdAt: min(m) });
|
||||
const ia = (m: number): MensajeParaEspera => ({ direction: "out", status: "sent", aiGenerated: true, createdAt: min(m) });
|
||||
|
||||
const base = {
|
||||
isTest: false,
|
||||
aiEnabled: false,
|
||||
handoffAt: min(0) as Date | null,
|
||||
lastInboundAt: min(1) as Date | null,
|
||||
lastTeamOutAt: null as Date | null,
|
||||
channel: "whatsapp" as const,
|
||||
};
|
||||
const ahora = (m: number) => ({ ahora: min(m) });
|
||||
|
||||
describe("necesitaPersona", () => {
|
||||
it("traspaso abierto o IA en pausa; la IA activa, no", () => {
|
||||
expect(necesitaPersona({ aiEnabled: true, handoffAt: min(0) })).toBe(true);
|
||||
expect(necesitaPersona({ aiEnabled: false, handoffAt: null })).toBe(true);
|
||||
expect(necesitaPersona({ aiEnabled: true, handoffAt: null })).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("primerMensajeSinRespuesta", () => {
|
||||
it("el primer mensaje de la ráfaga sin respuesta, no el último", () => {
|
||||
expect(primerMensajeSinRespuesta([equipo(0), entra(2), entra(3), entra(9)], null)).toEqual(min(2));
|
||||
});
|
||||
it("si el equipo contestó al último, nadie espera", () => {
|
||||
expect(primerMensajeSinRespuesta([entra(1), equipo(2)], null)).toBeNull();
|
||||
});
|
||||
it("un saliente fallido no es una respuesta", () => {
|
||||
expect(primerMensajeSinRespuesta([entra(1), equipo(2, "failed")], null)).toEqual(min(1));
|
||||
});
|
||||
it("sin traspaso, lo que contestó la IA sí cuenta", () => {
|
||||
expect(primerMensajeSinRespuesta([entra(1), ia(2)], null)).toBeNull();
|
||||
});
|
||||
it("con traspaso, la despedida de la IA en el turno que escaló no cuenta", () => {
|
||||
// El cliente pide una persona (5), la IA se despide (6) y escala (6:30).
|
||||
const msgs = [entra(0), ia(1), entra(5), ia(6)];
|
||||
expect(primerMensajeSinRespuesta(msgs, new Date(min(6).getTime() + 30_000))).toEqual(min(5));
|
||||
});
|
||||
it("con traspaso, lo que la IA contestó ANTES de ese turno sí cuenta", () => {
|
||||
const msgs = [entra(0), ia(1), entra(5), ia(6), entra(9)];
|
||||
// Si la IA no se hubiera tomado en cuenta, la espera empezaría en 0.
|
||||
expect(primerMensajeSinRespuesta(msgs, min(7))).toEqual(min(5));
|
||||
});
|
||||
});
|
||||
|
||||
describe("calcularEspera", () => {
|
||||
it("traspaso + mensaje del cliente: espera desde ese mensaje", () => {
|
||||
const e = calcularEspera(base, [entra(1)], ahora(10));
|
||||
expect(e?.desde).toBe(min(1).toISOString());
|
||||
expect(e?.hasta).toBe(new Date(min(1).getTime() + 24 * HORA).toISOString());
|
||||
});
|
||||
it("el equipo contestó después del último mensaje del cliente: no espera", () => {
|
||||
expect(calcularEspera({ ...base, lastTeamOutAt: min(2) }, [entra(1), equipo(2)], ahora(10))).toBeNull();
|
||||
});
|
||||
it("el equipo escribió desde el teléfono (eco) después del cliente: no espera", () => {
|
||||
expect(calcularEspera({ ...base, lastTeamOutAt: min(3) }, [entra(1)], ahora(10))).toBeNull();
|
||||
});
|
||||
it("el cliente vuelve a escribir: espera desde ese mensaje nuevo", () => {
|
||||
const e = calcularEspera(
|
||||
{ ...base, lastInboundAt: min(8), lastTeamOutAt: min(2) },
|
||||
[entra(1), equipo(2), entra(8)],
|
||||
ahora(10)
|
||||
);
|
||||
expect(e?.desde).toBe(min(8).toISOString());
|
||||
});
|
||||
it("la IA activa contestando: no espera", () => {
|
||||
expect(calcularEspera({ ...base, aiEnabled: true, handoffAt: null }, [entra(1)], ahora(2))).toBeNull();
|
||||
});
|
||||
it("con la ventana de 24 h cerrada ya no cuenta", () => {
|
||||
expect(calcularEspera(base, [entra(1)], ahora(1 + 24 * 60))).toBeNull();
|
||||
});
|
||||
it("una conversación de prueba no cuenta", () => {
|
||||
expect(calcularEspera({ ...base, isTest: true }, [entra(1)], ahora(5))).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("contestableHasta", () => {
|
||||
it("WhatsApp: 24 h; Instagram y Messenger: los 7 días de agente humano; TikTok: 48 h", () => {
|
||||
const d = new Date(T0);
|
||||
expect(contestableHasta("whatsapp", d).getTime() - T0).toBe(24 * HORA);
|
||||
expect(contestableHasta("instagram", d).getTime() - T0).toBe(7 * 24 * HORA);
|
||||
expect(contestableHasta("messenger", d).getTime() - T0).toBe(7 * 24 * HORA);
|
||||
expect(contestableHasta("tiktok", d).getTime() - T0).toBe(48 * HORA);
|
||||
});
|
||||
it("la consulta se acota a la ventana más larga (7 días)", () => {
|
||||
expect(VENTANA_MAXIMA_MS).toBe(7 * 24 * HORA);
|
||||
});
|
||||
});
|
||||
|
||||
describe("lib/esperando", () => {
|
||||
const conv = (id: string, desde: number, hasta = 24 * 60) => ({
|
||||
id,
|
||||
contact: { name: `Cliente ${id}` },
|
||||
espera: { desde: min(desde).toISOString(), hasta: min(hasta).toISOString() },
|
||||
});
|
||||
|
||||
it("estaEsperando respeta la ventana", () => {
|
||||
expect(estaEsperando(conv("a", 0), min(5).getTime())).toBe(true);
|
||||
expect(estaEsperando(conv("a", 0, 4), min(5).getTime())).toBe(false);
|
||||
expect(estaEsperando({ espera: null }, min(5).getTime())).toBe(false);
|
||||
});
|
||||
|
||||
it("semáforo: neutro < 5, ámbar 5–14, rojo ≥ 15", () => {
|
||||
expect(nivelDeEspera(4)).toBe("neutro");
|
||||
expect(nivelDeEspera(5)).toBe("ambar");
|
||||
expect(nivelDeEspera(14)).toBe("ambar");
|
||||
expect(nivelDeEspera(15)).toBe("rojo");
|
||||
});
|
||||
|
||||
it("minutos y textos", () => {
|
||||
expect(minutosDeEspera(min(0).toISOString(), min(7).getTime() + 59_000)).toBe(7);
|
||||
expect(minutosDeEspera(min(10).toISOString(), min(7).getTime())).toBe(0);
|
||||
expect(textoMinutos(65)).toBe("1 h 05 min");
|
||||
expect(textoMinutos(180)).toBe("3 h");
|
||||
expect(textoCintillo(1, 3)).toBe("1 cliente espera a una persona · lleva 3 min");
|
||||
expect(textoCintillo(3, 42)).toBe("3 clientes esperan a una persona · el que más lleva: 42 min");
|
||||
});
|
||||
|
||||
it("esperasDe ordena de la que más lleva a la que menos y deja fuera a las que no esperan", () => {
|
||||
const lista = [conv("b", 10), conv("a", 0), { id: "c", contact: { name: "C" }, espera: null }];
|
||||
expect(esperasDe(lista, min(20).getTime()).map((e) => e.id)).toEqual(["a", "b"]);
|
||||
});
|
||||
|
||||
it("el aviso sale una vez por espera, y otra vez si es una espera nueva", () => {
|
||||
const esperas = esperasDe([conv("a", 0), conv("b", 10)], min(20).getTime());
|
||||
const nuevas = nuevasParaAvisar(esperas, new Set());
|
||||
expect(nuevas.map((e) => e.id)).toEqual(["a"]); // b lleva 10 min
|
||||
const vistas = new Set(nuevas.map(claveDeEspera));
|
||||
expect(nuevasParaAvisar(esperas, vistas)).toEqual([]);
|
||||
const otraVez = esperasDe([conv("a", 2)], min(20).getTime());
|
||||
expect(nuevasParaAvisar(otraVez, vistas).map((e) => e.id)).toEqual(["a"]);
|
||||
expect(textoAviso(nuevas)).toBe("Cliente a lleva 20 min esperando a una persona");
|
||||
expect(textoAviso([...nuevas, ...nuevas])).toBe("2 clientes llevan más de 15 min esperando a una persona");
|
||||
});
|
||||
});
|
||||
|
||||
describe("qué ve cada persona de «Esperando» (cookie)", () => {
|
||||
it("sin cookie, vacía o manipulada: ve todo y con sonido", () => {
|
||||
for (const v of [undefined, null, "", "basura", "a_veces.1", "%E0%A4%A"]) {
|
||||
expect(avisoEsperandoDeCookie(v)).toEqual({ modo: "todo", sonido: true });
|
||||
}
|
||||
});
|
||||
|
||||
it("guardar y leer da lo mismo en todas las combinaciones", () => {
|
||||
for (const modo of MODOS_ESPERANDO) {
|
||||
for (const sonido of [true, false]) {
|
||||
expect(avisoEsperandoDeCookie(cookieDeAvisoEsperando({ modo, sonido }))).toEqual({ modo, sonido });
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("el aviso del sistema puede abrir la pestaña «Esperando»", () => {
|
||||
it("acepta la Bandeja, una conversación, con o sin vista, y nada más", () => {
|
||||
expect(urlDeAvisoSegura("/inbox")).toBe("/inbox");
|
||||
expect(urlDeAvisoSegura("/inbox?vista=esperando")).toBe("/inbox?vista=esperando");
|
||||
expect(urlDeAvisoSegura("/inbox?conversation=cv_1&vista=esperando")).toBe("/inbox?conversation=cv_1&vista=esperando");
|
||||
expect(urlDeAvisoSegura("/inbox?vista=otra")).toBeNull();
|
||||
expect(urlDeAvisoSegura("https://otro.sitio/inbox")).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,60 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { textoEventoEtapa, textoTraspaso } from "@/lib/eventos-hilo";
|
||||
import { intercalarNotas } from "@/lib/notas";
|
||||
|
||||
/** 054 — El texto de cada evento del hilo y dónde cae entre los mensajes. */
|
||||
describe("054 — cambios de etapa", () => {
|
||||
const ev = (p: Partial<Parameters<typeof textoEventoEtapa>[0]> = {}) =>
|
||||
textoEventoEtapa({
|
||||
fromStageName: "Nuevo",
|
||||
toStageName: "Interesado",
|
||||
lossReason: null,
|
||||
source: "dueno",
|
||||
actorNombre: "Ana",
|
||||
...p,
|
||||
});
|
||||
|
||||
it("dice a dónde pasó y quién lo movió", () => {
|
||||
expect(ev()).toBe("Pasó a Interesado · por Ana");
|
||||
});
|
||||
|
||||
it("el nacimiento del lead dice que entró al embudo", () => {
|
||||
expect(ev({ fromStageName: null, toStageName: "Nuevo", actorNombre: null, source: "sistema" })).toBe(
|
||||
"Entró al embudo en Nuevo"
|
||||
);
|
||||
});
|
||||
|
||||
it("el agente se nombra; el sistema no", () => {
|
||||
expect(ev({ actorNombre: null, source: "bot" })).toBe("Pasó a Interesado · por el agente");
|
||||
expect(ev({ actorNombre: null, source: "sistema" })).toBe("Pasó a Interesado");
|
||||
});
|
||||
|
||||
it("pasar a perdido lleva el motivo", () => {
|
||||
expect(ev({ toStageName: "Perdido", lossReason: "precio" })).toBe(
|
||||
"Pasó a Perdido · Le pareció caro · por Ana"
|
||||
);
|
||||
expect(ev({ toStageName: "Perdido", lossReason: "inventado" })).toBe("Pasó a Perdido · por Ana");
|
||||
});
|
||||
});
|
||||
|
||||
describe("054 — traspaso a una persona", () => {
|
||||
it("con las palabras del panel del contacto", () => {
|
||||
expect(textoTraspaso("cliente")).toBe("La IA se pausó: el cliente pidió un humano");
|
||||
expect(textoTraspaso("hostilidad")).toBe("La IA se pausó: el cliente se puso agresivo y el agente se retiró");
|
||||
expect(textoTraspaso(null)).toBe("La IA se pausó");
|
||||
expect(textoTraspaso("desconocido")).toBe("La IA se pausó");
|
||||
});
|
||||
});
|
||||
|
||||
describe("054 — intercalado con mensajes y notas", () => {
|
||||
it("cada cosa cae en su lugar por hora; con la misma hora, después del mensaje", () => {
|
||||
const mensajes = [{ createdAt: "2026-10-23T10:00:00.000Z" }, { createdAt: "2026-10-23T12:00:00.000Z" }];
|
||||
const r = intercalarNotas(mensajes, [
|
||||
{ id: "e2", createdAt: "2026-10-23T13:00:00.000Z" },
|
||||
{ id: "e0", createdAt: "2026-10-23T09:00:00.000Z" },
|
||||
{ id: "n1", createdAt: "2026-10-23T10:00:00.000Z" },
|
||||
]);
|
||||
expect(r.antes.map((l) => l.map((x) => x.id))).toEqual([["e0"], ["n1"]]);
|
||||
expect(r.alFinal.map((x) => x.id)).toEqual(["e2"]);
|
||||
});
|
||||
});
|
||||
Binary file not shown.
@@ -0,0 +1,67 @@
|
||||
import { readdirSync, readFileSync, statSync } from "node:fs";
|
||||
import path from "node:path";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
/**
|
||||
* Guardarraíl de la ficha del lead.
|
||||
*
|
||||
* La ficha es información de calificación de los clientes de alguien: qué
|
||||
* presupuesto tiene, qué le duele, si decide él. Se escribe desde dos lados
|
||||
* —el cerebro externo por `PUT /api/bot/ficha` y el dueño desde la bandeja— y
|
||||
* las dos rutas entran por `upsertFicha`.
|
||||
*
|
||||
* Aquí se verifica que esa puerta filtre por organización POR SÍ MISMA, y no
|
||||
* confiando en que el llamador se acuerde. Ese "acuérdate de filtrar" es
|
||||
* exactamente como se filtran datos entre inquilinos: nada truena, y el
|
||||
* incidente se descubre cuando ya salió.
|
||||
*
|
||||
* Si estás leyendo esto porque el test se puso rojo: no lo relajes.
|
||||
*/
|
||||
|
||||
const SRC = path.resolve(import.meta.dirname, "..", "..", "src");
|
||||
const PUERTA = path.join(SRC, "server", "bot", "ficha.ts");
|
||||
|
||||
function archivosTs(dir: string): string[] {
|
||||
const out: string[] = [];
|
||||
for (const entry of readdirSync(dir)) {
|
||||
const full = path.join(dir, entry);
|
||||
if (statSync(full).isDirectory()) out.push(...archivosTs(full));
|
||||
else if (/\.(ts|tsx)$/.test(entry)) out.push(full);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
describe("guardarraíl: la ficha nunca se escribe sin organización", () => {
|
||||
const puerta = readFileSync(PUERTA, "utf8");
|
||||
|
||||
it("`upsertFicha` recibe la organización", () => {
|
||||
const firma = puerta.slice(puerta.indexOf("export async function upsertFicha"));
|
||||
expect(firma.slice(0, 200)).toContain("organizationId");
|
||||
});
|
||||
|
||||
it("y la usa: sus queries pasan por `scoped`, no por un `eq` pelón", () => {
|
||||
const cuerpo = puerta.slice(
|
||||
puerta.indexOf("export async function upsertFicha")
|
||||
);
|
||||
expect(cuerpo).toContain("scoped(");
|
||||
expect(cuerpo).toContain("schema.contact.organizationId");
|
||||
});
|
||||
|
||||
it("nadie más escribe `contact.ficha` por su cuenta", () => {
|
||||
const culpables: string[] = [];
|
||||
for (const file of archivosTs(SRC)) {
|
||||
if (path.resolve(file) === path.resolve(PUERTA)) continue;
|
||||
const code = readFileSync(file, "utf8");
|
||||
// `.set({ … ficha … })` sobre la tabla de contactos, fuera de la puerta.
|
||||
const re = /\.update\(\s*schema\.contact\s*\)/g;
|
||||
let m: RegExpExecArray | null;
|
||||
while ((m = re.exec(code)) !== null) {
|
||||
const bloque = code.slice(m.index, m.index + 400);
|
||||
if (/\bficha\b/.test(bloque)) {
|
||||
culpables.push(path.relative(SRC, file));
|
||||
}
|
||||
}
|
||||
}
|
||||
expect(culpables).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,72 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
fichaEntries,
|
||||
fichaLabel,
|
||||
fichaValueText,
|
||||
parseFichaValue,
|
||||
} from "@/lib/ficha";
|
||||
|
||||
describe("fichaLabel", () => {
|
||||
it("lee bonito lo que escribió un LLM, en cualquiera de sus manías", () => {
|
||||
expect(fichaLabel("dolor_principal")).toBe("Dolor principal");
|
||||
expect(fichaLabel("dolorPrincipal")).toBe("Dolor principal");
|
||||
expect(fichaLabel("dolor-principal")).toBe("Dolor principal");
|
||||
expect(fichaLabel("presupuesto")).toBe("Presupuesto");
|
||||
});
|
||||
|
||||
it("no se rompe con claves raras", () => {
|
||||
expect(fichaLabel("m2")).toBe("M2");
|
||||
expect(fichaLabel("__")).toBe("__");
|
||||
expect(fichaLabel("ZONA")).toBe("Zona");
|
||||
});
|
||||
});
|
||||
|
||||
describe("fichaValueText", () => {
|
||||
it("los booleanos se leen Sí/No: nadie califica en true", () => {
|
||||
expect(fichaValueText(true)).toBe("Sí");
|
||||
expect(fichaValueText(false)).toBe("No");
|
||||
});
|
||||
|
||||
it("números y textos pasan tal cual", () => {
|
||||
expect(fichaValueText(50000)).toBe("50000");
|
||||
expect(fichaValueText("Polanco")).toBe("Polanco");
|
||||
});
|
||||
});
|
||||
|
||||
describe("parseFichaValue", () => {
|
||||
it("editar NO cambia el tipo del dato", () => {
|
||||
// Del otro lado hay un bot que puede estar comparando; convertir en
|
||||
// silencio un número a texto es de los cambios que solo se descubren
|
||||
// cuando algo ya falló.
|
||||
expect(parseFichaValue("60000", 50000)).toBe(60000);
|
||||
expect(parseFichaValue("No", true)).toBe(false);
|
||||
expect(parseFichaValue("sí", false)).toBe(true);
|
||||
expect(parseFichaValue("Polanco", "Roma")).toBe("Polanco");
|
||||
});
|
||||
|
||||
it("pero sí lo cambia si lo escrito ya no es de ese tipo", () => {
|
||||
expect(parseFichaValue("como cinco mil", 5000)).toBe("como cinco mil");
|
||||
expect(parseFichaValue("depende", true)).toBe("depende");
|
||||
});
|
||||
|
||||
it("un dato nuevo entra como texto", () => {
|
||||
expect(parseFichaValue("42", undefined)).toBe("42");
|
||||
});
|
||||
|
||||
it("recorta los espacios de sobra", () => {
|
||||
expect(parseFichaValue(" Polanco ", "Roma")).toBe("Polanco");
|
||||
});
|
||||
});
|
||||
|
||||
describe("fichaEntries", () => {
|
||||
it("ordena para que la ficha no baile entre recargas", () => {
|
||||
const claves = fichaEntries({ zona: "Roma", dolor: "x", presupuesto: 1 }).map(
|
||||
([k]) => k
|
||||
);
|
||||
expect(claves).toEqual(["dolor", "presupuesto", "zona"]);
|
||||
});
|
||||
|
||||
it("una ficha vacía no truena", () => {
|
||||
expect(fichaEntries({})).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,120 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { fijadosPrimero, LIMITE_FIJADOS, MENSAJE_LIMITE_FIJADOS } from "@/lib/fijados";
|
||||
|
||||
/**
|
||||
* 070 — Fijar chats: el orden (FC-3, FC-4), las rutas (FC-2, FC-7) y que la
|
||||
* lista de la API v1 no lleve los fijados (FC-9). El límite con candado y la
|
||||
* cascada se prueban contra la base real en `scripts/e2e-fijar-chats.mjs`.
|
||||
*/
|
||||
|
||||
const c = (id: string, pinnedAt: string | null = null) => ({ id, pinnedAt });
|
||||
|
||||
describe("fijadosPrimero", () => {
|
||||
it("sube los fijados, el más reciente primero, y deja el resto en su orden", () => {
|
||||
const lista = [c("a"), c("b", "2026-11-23T10:00:00Z"), c("c"), c("d", "2026-11-23T11:00:00Z"), c("e")];
|
||||
expect(fijadosPrimero(lista).map((x) => x.id)).toEqual(["d", "b", "a", "c", "e"]);
|
||||
});
|
||||
|
||||
it("sin fijados, la lista queda igual", () => {
|
||||
expect(fijadosPrimero([c("z"), c("y"), c("x")]).map((x) => x.id)).toEqual(["z", "y", "x"]);
|
||||
});
|
||||
|
||||
it("no muta la entrada y trata pinnedAt ausente como no fijado", () => {
|
||||
const lista = [{ id: "a" }, { id: "b", pinnedAt: "2026-11-23T10:00:00Z" }];
|
||||
const copia = JSON.stringify(lista);
|
||||
expect(fijadosPrimero(lista).map((x) => x.id)).toEqual(["b", "a"]);
|
||||
expect(JSON.stringify(lista)).toBe(copia);
|
||||
});
|
||||
|
||||
it("el límite es 3, con su mensaje", () => {
|
||||
expect(LIMITE_FIJADOS).toBe(3);
|
||||
expect(MENSAJE_LIMITE_FIJADOS).toBe("Solo puedes fijar 3 chats. Desfija uno para fijar este.");
|
||||
});
|
||||
});
|
||||
|
||||
const m = vi.hoisted(() => ({
|
||||
session: vi.fn(),
|
||||
pin: vi.fn(),
|
||||
unpin: vi.fn(),
|
||||
list: vi.fn(),
|
||||
withPins: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/auth/session", async (original) => ({
|
||||
...(await original<typeof import("@/lib/auth/session")>()),
|
||||
requireSession: m.session,
|
||||
}));
|
||||
vi.mock("@/server/inbox/pins", async (original) => ({
|
||||
...(await original<typeof import("@/server/inbox/pins")>()),
|
||||
pinConversation: m.pin,
|
||||
unpinConversation: m.unpin,
|
||||
withPins: m.withPins,
|
||||
}));
|
||||
vi.mock("@/server/inbox/queries", () => ({ listConversations: m.list }));
|
||||
|
||||
const ctx = { params: Promise.resolve({ id: "cv_1" }) };
|
||||
const req = new Request("http://x/api", { method: "POST" });
|
||||
|
||||
beforeEach(() => {
|
||||
for (const f of Object.values(m)) f.mockReset();
|
||||
m.session.mockResolvedValue({ organizationId: "org_a", userId: "usr_1", role: "member" });
|
||||
});
|
||||
|
||||
describe("POST/DELETE /api/conversations/[id]/pin", () => {
|
||||
it("fija para el usuario de la sesión, en su organización", async () => {
|
||||
m.pin.mockResolvedValue({ pinnedAt: new Date("2026-11-23T12:00:00Z") });
|
||||
const { POST } = await import("@/app/api/conversations/[id]/pin/route");
|
||||
const res = await POST(req, ctx);
|
||||
expect(res.status).toBe(200);
|
||||
expect(await res.json()).toEqual({ pinned: true, pinnedAt: "2026-11-23T12:00:00.000Z" });
|
||||
expect(m.pin).toHaveBeenCalledWith("org_a", "usr_1", "cv_1");
|
||||
});
|
||||
|
||||
it("el cuarto → 409 pin_limit con el mensaje", async () => {
|
||||
const { PinError } = await import("@/server/inbox/pins");
|
||||
m.pin.mockRejectedValue(new PinError(409, "pin_limit", MENSAJE_LIMITE_FIJADOS));
|
||||
const { POST } = await import("@/app/api/conversations/[id]/pin/route");
|
||||
const res = await POST(req, ctx);
|
||||
expect(res.status).toBe(409);
|
||||
expect((await res.json()).error.code).toBe("pin_limit");
|
||||
});
|
||||
|
||||
it("ajena o del Laboratorio → 404", async () => {
|
||||
const { PinError } = await import("@/server/inbox/pins");
|
||||
m.unpin.mockRejectedValue(new PinError(404, "not_found", "Conversación no encontrada"));
|
||||
const { DELETE } = await import("@/app/api/conversations/[id]/pin/route");
|
||||
expect((await DELETE(req, ctx)).status).toBe(404);
|
||||
});
|
||||
|
||||
it("sin sesión → 401", async () => {
|
||||
const { UnauthorizedError } = await import("@/lib/auth/session");
|
||||
m.session.mockRejectedValue(new UnauthorizedError());
|
||||
const { POST } = await import("@/app/api/conversations/[id]/pin/route");
|
||||
expect((await POST(req, ctx)).status).toBe(401);
|
||||
expect(m.pin).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe("la lista de conversaciones", () => {
|
||||
const lista = [{ id: "cv_1" }, { id: "cv_2" }];
|
||||
|
||||
it("con sesión de la UI trae pinnedAt del usuario", async () => {
|
||||
m.list.mockResolvedValue(lista);
|
||||
m.withPins.mockResolvedValue([{ id: "cv_1", pinnedAt: "2026-11-23T12:00:00.000Z" }, { id: "cv_2", pinnedAt: null }]);
|
||||
const { GET } = await import("@/server/http/conversations");
|
||||
const res = await GET({ organizationId: "org_a", userId: "usr_1", role: "member" } as never, new Request("http://x/api"));
|
||||
expect(m.withPins).toHaveBeenCalledWith(lista, "org_a", "usr_1");
|
||||
expect((await res.json()).conversations[0].pinnedAt).toBe("2026-11-23T12:00:00.000Z");
|
||||
});
|
||||
|
||||
it("con la API v1 (sesión con capabilities) no los trae", async () => {
|
||||
m.list.mockResolvedValue(lista);
|
||||
const { GET } = await import("@/server/http/conversations");
|
||||
const res = await GET(
|
||||
{ organizationId: "org_a", userId: "usr_1", role: "member", capabilities: ["read"] } as never,
|
||||
new Request("http://x/api")
|
||||
);
|
||||
expect(m.withPins).not.toHaveBeenCalled();
|
||||
expect(await res.json()).toEqual({ conversations: lista });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,30 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { etiquetaVence, POR_VENCER_MS, porVencer } from "@/lib/filtros-bandeja";
|
||||
|
||||
/** 052 — El filtro «Por vencer» y el aviso «Vence en…» de la fila. */
|
||||
|
||||
const H = 3_600_000;
|
||||
const c = (windowOpen: boolean, windowRemainingMs: number) => ({ windowOpen, windowRemainingMs });
|
||||
|
||||
describe("por vencer", () => {
|
||||
it("ventana abierta con 2 h o menos", () => {
|
||||
expect(porVencer(c(true, 90 * 60_000))).toBe(true);
|
||||
expect(porVencer(c(true, POR_VENCER_MS))).toBe(true);
|
||||
expect(porVencer(c(true, POR_VENCER_MS + 1))).toBe(false);
|
||||
expect(porVencer(c(true, 23 * H))).toBe(false);
|
||||
});
|
||||
|
||||
it("una ventana ya cerrada no está «por vencer»", () => {
|
||||
expect(porVencer(c(false, 0))).toBe(false);
|
||||
expect(porVencer(c(true, 0))).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("el chip «Vence en…»", () => {
|
||||
it("horas y minutos, sin ceros de más", () => {
|
||||
expect(etiquetaVence(80 * 60_000)).toBe("Vence en 1 h 20 min");
|
||||
expect(etiquetaVence(2 * H)).toBe("Vence en 2 h");
|
||||
expect(etiquetaVence(45 * 60_000 + 30_000)).toBe("Vence en 45 min");
|
||||
expect(etiquetaVence(20_000)).toBe("Vence en menos de 1 min");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,247 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
/**
|
||||
* 042 — Reenviar una imagen del historial: el origen se valida dentro de la
|
||||
* organización antes de leer el archivo, y el destino antes de mandar nada.
|
||||
*/
|
||||
const mocks = vi.hoisted(() => ({
|
||||
rows: [] as unknown[],
|
||||
read: vi.fn(),
|
||||
ensure: vi.fn(),
|
||||
send: vi.fn(),
|
||||
conversation: vi.fn(),
|
||||
session: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/db", async () => {
|
||||
const schema = await import("@/lib/db/schema");
|
||||
const chain = {
|
||||
from: () => chain,
|
||||
innerJoin: () => chain,
|
||||
where: () => chain,
|
||||
limit: async () => mocks.rows,
|
||||
};
|
||||
return { schema, getDb: () => ({ select: () => chain }) };
|
||||
});
|
||||
vi.mock("@/server/whatsapp/media", async (original) => ({
|
||||
...(await original<typeof import("@/server/whatsapp/media")>()),
|
||||
readMediaFile: mocks.read,
|
||||
ensureAssetAvailable: mocks.ensure,
|
||||
// `leerAdjunto` (recupera de Meta un archivo perdido) se prueba aparte, en
|
||||
// scripts/e2e-adjunto-perdido.mjs: aquí solo lee con el mock.
|
||||
leerAdjunto: async (organizationId: string, asset: { id: string }) => {
|
||||
try {
|
||||
return { asset, data: await mocks.read(organizationId, asset.id) };
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
},
|
||||
}));
|
||||
vi.mock("@/server/inbox/send", async (original) => ({
|
||||
...(await original<typeof import("@/server/inbox/send")>()),
|
||||
sendMediaMessage: mocks.send,
|
||||
}));
|
||||
vi.mock("@/server/inbox/queries", () => ({ getConversation: mocks.conversation }));
|
||||
vi.mock("@/lib/auth/session", async (original) => ({
|
||||
...(await original<typeof import("@/lib/auth/session")>()),
|
||||
requireSession: mocks.session,
|
||||
}));
|
||||
|
||||
import { forwardImage } from "@/server/inbox/forward-image";
|
||||
import { POST } from "@/app/api/conversations/[id]/messages/forward-image/route";
|
||||
import { UnauthorizedError } from "@/lib/auth/session";
|
||||
import { SendError } from "@/server/inbox/send";
|
||||
import { IMAGEN_ADJUNTA, validarImagenAdjunta } from "@/lib/imagen-adjunta";
|
||||
import { MEDIA_LIMITS } from "@/server/whatsapp/media";
|
||||
|
||||
const input = {
|
||||
organizationId: "org_a",
|
||||
conversationId: "cv_destino",
|
||||
sourceMessageId: "msg_origen",
|
||||
};
|
||||
|
||||
function source(patch: Record<string, unknown> = {}, isTest = false) {
|
||||
return {
|
||||
message: { conversationId: "cv_origen" },
|
||||
conversation: { isTest },
|
||||
asset: {
|
||||
id: "ma_origen",
|
||||
kind: "image",
|
||||
mimeType: "image/png",
|
||||
fileName: "foto.png",
|
||||
caption: "Pie original",
|
||||
fetchStatus: "available",
|
||||
storagePath: "org_a/ma_origen",
|
||||
...patch,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mocks.rows = [source()];
|
||||
mocks.read.mockResolvedValue(Buffer.from("png"));
|
||||
mocks.ensure.mockResolvedValue({ fetchStatus: "available" });
|
||||
mocks.send.mockResolvedValue({ messageId: "msg_nuevo" });
|
||||
mocks.session.mockResolvedValue({ organizationId: "org_a" });
|
||||
mocks.conversation.mockResolvedValue({
|
||||
conversation: { channel: "whatsapp", isTest: false },
|
||||
});
|
||||
});
|
||||
|
||||
describe("042 — origen del reenvío", () => {
|
||||
it("lee el archivo de la organización y lo manda como adjunto nuevo con el pie editado", async () => {
|
||||
const original = structuredClone(mocks.rows[0]);
|
||||
await expect(forwardImage({ ...input, caption: "Pie nuevo" })).resolves.toEqual({
|
||||
messageId: "msg_nuevo",
|
||||
});
|
||||
expect(mocks.read).toHaveBeenCalledWith("org_a", "ma_origen");
|
||||
expect(mocks.send).toHaveBeenCalledWith({
|
||||
organizationId: "org_a",
|
||||
conversationId: "cv_destino",
|
||||
file: { data: Buffer.from("png"), mimeType: "image/png", fileName: "foto.png" },
|
||||
caption: "Pie nuevo",
|
||||
});
|
||||
expect(mocks.rows[0]).toEqual(original);
|
||||
});
|
||||
|
||||
it("sin pie conserva el del original; con un pie vacío sale sin pie", async () => {
|
||||
await forwardImage(input);
|
||||
expect(mocks.send.mock.calls[0]![0].caption).toBe("Pie original");
|
||||
await forwardImage({ ...input, caption: "" });
|
||||
expect(mocks.send.mock.calls[1]![0].caption).toBeUndefined();
|
||||
});
|
||||
|
||||
it.each([
|
||||
["no existe en la organización", [], "not_found"],
|
||||
["es del Laboratorio", [source({}, true)], "sandbox_violation"],
|
||||
["no es imagen", [source({ kind: "document", mimeType: "application/pdf" })], "invalid"],
|
||||
["es un sticker", [source({ kind: "sticker", mimeType: "image/webp" })], "invalid"],
|
||||
["es SVG", [source({ mimeType: "image/svg+xml" })], "invalid"],
|
||||
])("rechaza el origen que %s sin leer ni enviar", async (_caso, rows, code) => {
|
||||
mocks.rows = rows as unknown[];
|
||||
await expect(forwardImage(input)).rejects.toMatchObject({ code });
|
||||
expect(mocks.read).not.toHaveBeenCalled();
|
||||
expect(mocks.send).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("una imagen que todavía no se bajó de Meta se baja antes de reenviar", async () => {
|
||||
mocks.rows = [source({ fetchStatus: "pending", storagePath: null })];
|
||||
await forwardImage(input);
|
||||
expect(mocks.ensure).toHaveBeenCalledWith("org_a", "ma_origen");
|
||||
expect(mocks.send).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("si no se puede bajar, 410 sin enviar", async () => {
|
||||
mocks.rows = [source({ fetchStatus: "failed" })];
|
||||
mocks.ensure.mockResolvedValue(null);
|
||||
await expect(forwardImage(input)).rejects.toMatchObject({ status: 410, code: "gone" });
|
||||
expect(mocks.send).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("el archivo que falta en el almacén es 410, sin enviar", async () => {
|
||||
mocks.read.mockRejectedValue(new Error("ENOENT"));
|
||||
await expect(forwardImage(input)).rejects.toMatchObject({ status: 410, code: "gone" });
|
||||
expect(mocks.send).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("no se reenvía a la misma conversación", async () => {
|
||||
await expect(
|
||||
forwardImage({ ...input, conversationId: "cv_origen" })
|
||||
).rejects.toMatchObject({ code: "invalid" });
|
||||
expect(mocks.send).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
const request = (data: unknown = { sourceMessageId: "msg_origen" }) =>
|
||||
new Request("http://localhost/api/conversations/cv_destino/messages/forward-image", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify(data),
|
||||
});
|
||||
const params = { params: Promise.resolve({ id: "cv_destino" }) };
|
||||
|
||||
describe("042 — ruta de reenvío", () => {
|
||||
it("exige sesión", async () => {
|
||||
mocks.session.mockRejectedValue(new UnauthorizedError());
|
||||
expect((await POST(request(), params)).status).toBe(401);
|
||||
expect(mocks.conversation).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("busca el destino en la organización de la sesión; si no está, 404", async () => {
|
||||
mocks.conversation.mockResolvedValue(null);
|
||||
expect((await POST(request(), params)).status).toBe(404);
|
||||
expect(mocks.conversation).toHaveBeenCalledWith("org_a", "cv_destino");
|
||||
expect(mocks.read).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each([
|
||||
[true, "whatsapp", 403],
|
||||
[false, "instagram", 422],
|
||||
[false, "messenger", 422],
|
||||
[false, "tiktok", 422],
|
||||
])("destino de prueba o sin adjuntos (isTest=%s, %s) → %s", async (isTest, channel, status) => {
|
||||
mocks.conversation.mockResolvedValue({ conversation: { isTest, channel } });
|
||||
expect((await POST(request(), params)).status).toBe(status);
|
||||
expect(mocks.read).not.toHaveBeenCalled();
|
||||
expect(mocks.send).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ sourceMessageId: "../secreto" },
|
||||
{ sourceMessageId: "msg_origen", url: "http://example.test/imagen.png" },
|
||||
{ sourceMessageId: "msg_origen", path: "/etc/passwd" },
|
||||
{ sourceMessageId: "msg_origen", caption: "a".repeat(1025) },
|
||||
{},
|
||||
])("no acepta rutas, URLs ni pies de más (%j)", async (body) => {
|
||||
expect((await POST(request(body), params)).status).toBe(422);
|
||||
expect(mocks.read).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("traduce el error del envío y devuelve 201 al salir", async () => {
|
||||
mocks.send.mockRejectedValueOnce(new SendError("window_closed", "Ventana cerrada"));
|
||||
const cerrada = await POST(request(), params);
|
||||
expect(cerrada.status).toBe(409);
|
||||
expect((await cerrada.json()).error).toEqual({ code: "window_closed", message: "Ventana cerrada" });
|
||||
const bien = await POST(request(), params);
|
||||
expect(bien.status).toBe(201);
|
||||
expect(await bien.json()).toEqual({ messageId: "msg_nuevo" });
|
||||
});
|
||||
|
||||
it("el origen ajeno es 404 aunque el destino sea propio", async () => {
|
||||
mocks.rows = [];
|
||||
const res = await POST(request(), params);
|
||||
expect(res.status).toBe(404);
|
||||
expect(mocks.send).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe("042 — la imagen que acepta el compositor", () => {
|
||||
const png = (size = 10, type = "image/png", name = "a.png") =>
|
||||
new File([new Uint8Array(size)], name, { type });
|
||||
|
||||
it("son los límites de imagen del servidor", () => {
|
||||
expect(IMAGEN_ADJUNTA.maxBytes).toBe(MEDIA_LIMITS.image.maxBytes);
|
||||
expect(IMAGEN_ADJUNTA.mimes.source).toBe(MEDIA_LIMITS.image.mimes.source);
|
||||
});
|
||||
|
||||
it("acepta una imagen JPEG, PNG o WebP de hasta 5 MB", () => {
|
||||
for (const type of ["image/jpeg", "image/png", "image/webp"]) {
|
||||
expect(validarImagenAdjunta([png(10, type)], "paste")).toMatchObject({ ok: true });
|
||||
}
|
||||
expect(validarImagenAdjunta([png(5 * 1024 * 1024)], "paste").ok).toBe(true);
|
||||
});
|
||||
|
||||
it("rechaza varias, otro formato o más de 5 MB, con el verbo del gesto", () => {
|
||||
expect(validarImagenAdjunta([png(), png()], "paste")).toEqual({
|
||||
ok: false,
|
||||
error: "Pega una imagen a la vez.",
|
||||
});
|
||||
expect(validarImagenAdjunta([], "drop")).toEqual({ ok: false, error: "Arrastra una imagen a la vez." });
|
||||
expect(validarImagenAdjunta([png(10, "image/gif")], "paste")).toEqual({
|
||||
ok: false,
|
||||
error: "Pega una imagen JPEG, PNG o WebP.",
|
||||
});
|
||||
expect(validarImagenAdjunta([png(5 * 1024 * 1024 + 1)], "paste")).toMatchObject({ ok: false });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,198 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
/**
|
||||
* 059 — Reenviar cualquier mensaje: el texto sale por `sendText`, un adjunto
|
||||
* por `sendMediaMessage`, y lo que no se reenvía se rechaza sin mandar nada.
|
||||
*/
|
||||
const mocks = vi.hoisted(() => ({
|
||||
rows: [] as unknown[],
|
||||
read: vi.fn(),
|
||||
ensure: vi.fn(),
|
||||
sendMedia: vi.fn(),
|
||||
sendText: vi.fn(),
|
||||
conversation: vi.fn(),
|
||||
session: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/db", async () => {
|
||||
const schema = await import("@/lib/db/schema");
|
||||
const chain = {
|
||||
from: () => chain,
|
||||
innerJoin: () => chain,
|
||||
leftJoin: () => chain,
|
||||
where: () => chain,
|
||||
limit: async () => mocks.rows,
|
||||
};
|
||||
return { schema, getDb: () => ({ select: () => chain }) };
|
||||
});
|
||||
vi.mock("@/server/whatsapp/media", async (original) => ({
|
||||
...(await original<typeof import("@/server/whatsapp/media")>()),
|
||||
ensureAssetAvailable: mocks.ensure,
|
||||
leerAdjunto: async (organizationId: string, asset: { id: string }) => {
|
||||
try {
|
||||
return { asset, data: await mocks.read(organizationId, asset.id) };
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
},
|
||||
}));
|
||||
vi.mock("@/server/inbox/send", async (original) => ({
|
||||
...(await original<typeof import("@/server/inbox/send")>()),
|
||||
sendMediaMessage: mocks.sendMedia,
|
||||
sendText: mocks.sendText,
|
||||
}));
|
||||
vi.mock("@/server/inbox/queries", () => ({ getConversation: mocks.conversation }));
|
||||
vi.mock("@/lib/auth/session", async (original) => ({
|
||||
...(await original<typeof import("@/lib/auth/session")>()),
|
||||
requireSession: mocks.session,
|
||||
}));
|
||||
|
||||
import { forwardMessage } from "@/server/inbox/forward-message";
|
||||
import { POST } from "@/app/api/conversations/[id]/messages/forward/route";
|
||||
import { SendError } from "@/server/inbox/send";
|
||||
|
||||
const input = { organizationId: "org_a", conversationId: "cv_destino", sourceMessageId: "msg_origen" };
|
||||
|
||||
function texto(text: string | null, type = "text", isTest = false) {
|
||||
return {
|
||||
message: { conversationId: "cv_origen", type, text },
|
||||
conversation: { isTest },
|
||||
asset: null,
|
||||
};
|
||||
}
|
||||
function adjunto(patch: Record<string, unknown> = {}) {
|
||||
return {
|
||||
message: { conversationId: "cv_origen", type: "document", text: null },
|
||||
conversation: { isTest: false },
|
||||
asset: {
|
||||
id: "ma_origen",
|
||||
kind: "document",
|
||||
mimeType: "application/pdf",
|
||||
fileName: "cotizacion.pdf",
|
||||
caption: "Pie original",
|
||||
fetchStatus: "available",
|
||||
...patch,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mocks.rows = [texto("Precios: 1200")];
|
||||
mocks.read.mockResolvedValue(Buffer.from("pdf"));
|
||||
mocks.ensure.mockResolvedValue({ fetchStatus: "available" });
|
||||
mocks.sendMedia.mockResolvedValue({ messageId: "msg_nuevo" });
|
||||
mocks.sendText.mockResolvedValue({ messageId: "msg_nuevo" });
|
||||
mocks.session.mockResolvedValue({ organizationId: "org_a" });
|
||||
mocks.conversation.mockResolvedValue({ conversation: { channel: "whatsapp", isTest: false } });
|
||||
});
|
||||
|
||||
describe("059 — qué sale", () => {
|
||||
it("un texto sale como texto, al destino y con el mismo texto", async () => {
|
||||
await forwardMessage(input);
|
||||
expect(mocks.sendText).toHaveBeenCalledWith({
|
||||
organizationId: "org_a",
|
||||
conversationId: "cv_destino",
|
||||
text: "Precios: 1200",
|
||||
});
|
||||
expect(mocks.sendMedia).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("una plantilla también sale como texto libre", async () => {
|
||||
mocks.rows = [texto("Tu cita es mañana", "template")];
|
||||
await forwardMessage(input);
|
||||
expect(mocks.sendText.mock.calls[0]![0].text).toBe("Tu cita es mañana");
|
||||
});
|
||||
|
||||
it("un documento sale como archivo nuevo con su nombre y el pie editado", async () => {
|
||||
mocks.rows = [adjunto()];
|
||||
await forwardMessage({ ...input, caption: "Pie nuevo" });
|
||||
const llamada = mocks.sendMedia.mock.calls[0]![0];
|
||||
expect(llamada.file).toMatchObject({ mimeType: "application/pdf", fileName: "cotizacion.pdf" });
|
||||
expect(llamada.caption).toBe("Pie nuevo");
|
||||
expect(llamada.voz).toBe(false);
|
||||
});
|
||||
|
||||
it("un audio Ogg sale como nota de voz y sin pie", async () => {
|
||||
mocks.rows = [adjunto({ kind: "audio", mimeType: "audio/ogg; codecs=opus", caption: "x" })];
|
||||
await forwardMessage({ ...input, caption: "no va" });
|
||||
const llamada = mocks.sendMedia.mock.calls[0]![0];
|
||||
expect(llamada.voz).toBe(true);
|
||||
expect(llamada.caption).toBeUndefined();
|
||||
});
|
||||
|
||||
it("un sticker sale como su WebP (la Cloud API lo toma como imagen)", async () => {
|
||||
mocks.rows = [adjunto({ kind: "sticker", mimeType: "image/webp", caption: null })];
|
||||
await forwardMessage(input);
|
||||
expect(mocks.sendMedia.mock.calls[0]![0].file.mimeType).toBe("image/webp");
|
||||
});
|
||||
});
|
||||
|
||||
describe("059 — lo que se rechaza sin mandar nada", () => {
|
||||
it.each([
|
||||
["no existe en la organización", [], "not_found"],
|
||||
["es del Laboratorio", [texto("hola", "text", true)], "sandbox_violation"],
|
||||
["es una ubicación", [adjunto({ kind: "location", mimeType: null })], "invalid"],
|
||||
["es una reacción", [texto("👍", "reaction")], "invalid"],
|
||||
["no trae texto", [texto(null)], "invalid"],
|
||||
])("el origen que %s", async (_caso, rows, code) => {
|
||||
mocks.rows = rows as unknown[];
|
||||
await expect(forwardMessage(input)).rejects.toMatchObject({ code });
|
||||
expect(mocks.sendText).not.toHaveBeenCalled();
|
||||
expect(mocks.sendMedia).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("a la misma conversación", async () => {
|
||||
await expect(forwardMessage({ ...input, conversationId: "cv_origen" })).rejects.toMatchObject({
|
||||
code: "invalid",
|
||||
});
|
||||
expect(mocks.sendText).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("un archivo que ya no está es 410", async () => {
|
||||
mocks.rows = [adjunto()];
|
||||
mocks.read.mockRejectedValue(new Error("ENOENT"));
|
||||
await expect(forwardMessage(input)).rejects.toMatchObject({ status: 410, code: "gone" });
|
||||
expect(mocks.sendMedia).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe("059 — la ruta", () => {
|
||||
const pedir = (body: unknown) =>
|
||||
POST(
|
||||
new Request("http://localhost/api/conversations/cv_destino/messages/forward", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify(body),
|
||||
}),
|
||||
{ params: Promise.resolve({ id: "cv_destino" }) }
|
||||
);
|
||||
|
||||
it("201 al salir", async () => {
|
||||
const res = await pedir({ sourceMessageId: "msg_origen" });
|
||||
expect(res.status).toBe(201);
|
||||
expect(await res.json()).toEqual({ messageId: "msg_nuevo" });
|
||||
});
|
||||
|
||||
it("nunca al Laboratorio", async () => {
|
||||
mocks.conversation.mockResolvedValue({ conversation: { channel: "whatsapp", isTest: true } });
|
||||
expect((await pedir({ sourceMessageId: "msg_origen" })).status).toBe(403);
|
||||
expect(mocks.sendText).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("un destino ajeno es 404", async () => {
|
||||
mocks.conversation.mockResolvedValue(null);
|
||||
expect((await pedir({ sourceMessageId: "msg_origen" })).status).toBe(404);
|
||||
});
|
||||
|
||||
it("solo el id del mensaje: una URL es 422", async () => {
|
||||
expect((await pedir({ sourceMessageId: "msg_origen", url: "http://x.test" })).status).toBe(422);
|
||||
});
|
||||
|
||||
it("la ventana cerrada es 409 window_closed", async () => {
|
||||
mocks.sendText.mockRejectedValue(new SendError("window_closed", "Ventana cerrada"));
|
||||
const res = await pedir({ sourceMessageId: "msg_origen" });
|
||||
expect(res.status).toBe(409);
|
||||
expect((await res.json()).error.code).toBe("window_closed");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,204 @@
|
||||
import { readFileSync } from "node:fs";
|
||||
import { mkdtemp, readdir, rm, writeFile } from "node:fs/promises";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
/**
|
||||
* #82 — `/api/health` dice qué banderas están encendidas y si el volumen de
|
||||
* adjuntos se puede escribir. Es lo que una plataforma o un script pueden
|
||||
* confirmar con un `curl`, sin iniciar sesión: que `AGENDA=on` llegó al
|
||||
* contenedor, que `/data` quedó bien montado. Y la imagen deja de llevar lo
|
||||
* que el migrador nunca abre.
|
||||
*/
|
||||
|
||||
const RAIZ = path.resolve(import.meta.dirname, "..", "..");
|
||||
|
||||
const { getEnv, getDb } = vi.hoisted(() => ({
|
||||
getEnv: vi.fn(),
|
||||
getDb: vi.fn(),
|
||||
}));
|
||||
vi.mock("@/lib/env", () => ({ getEnv }));
|
||||
vi.mock("@/lib/db", () => ({ getDb, schema: {} }));
|
||||
|
||||
import { checkHealth, healthFeatures } from "@/server/health";
|
||||
import {
|
||||
MEDIA_DIR_PROBE_TTL_MS,
|
||||
mediaDirStatus,
|
||||
resetMediaDirCache,
|
||||
} from "@/server/media-dir";
|
||||
import { GET } from "@/app/api/health/route";
|
||||
|
||||
const ENV_ORIGINAL = { ...process.env };
|
||||
let tmp: string;
|
||||
|
||||
beforeEach(async () => {
|
||||
tmp = await mkdtemp(path.join(os.tmpdir(), "vocero-health-"));
|
||||
resetMediaDirCache();
|
||||
getDb.mockReturnValue({ execute: async () => [] });
|
||||
getEnv.mockReturnValue({ MEDIA_DIR: path.join(tmp, "media") });
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
process.env = { ...ENV_ORIGINAL };
|
||||
await rm(tmp, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
describe("features: las banderas de despliegue", () => {
|
||||
it("sin banderas: solo WhatsApp, agenda y atribución apagadas", () => {
|
||||
expect(healthFeatures({})).toEqual({
|
||||
agenda: false,
|
||||
channels: ["whatsapp"],
|
||||
atribucion: false,
|
||||
media: "disco",
|
||||
});
|
||||
});
|
||||
|
||||
it("con las tres encendidas, los canales van en el orden del catálogo", () => {
|
||||
// El de la variable no: dos instancias iguales tienen que responder igual.
|
||||
expect(
|
||||
healthFeatures({
|
||||
AGENDA: "on",
|
||||
CHANNELS: "messenger, Instagram",
|
||||
ATRIBUCION: "1",
|
||||
})
|
||||
).toEqual({
|
||||
agenda: true,
|
||||
channels: ["whatsapp", "instagram", "messenger"],
|
||||
atribucion: true,
|
||||
media: "disco",
|
||||
});
|
||||
});
|
||||
|
||||
it("un typo no enciende nada: dice lo que la app hace, no lo que se escribió", () => {
|
||||
// Mismos parsers que usan las rutas para responder 404: si aquí dijera
|
||||
// `true` y la agenda respondiera 404, el health mentiría.
|
||||
expect(
|
||||
healthFeatures({ AGENDA: "onn", CHANNELS: "telegram", ATRIBUCION: "off" })
|
||||
).toEqual({ agenda: false, channels: ["whatsapp"], atribucion: false, media: "disco" });
|
||||
});
|
||||
});
|
||||
|
||||
describe("mediaWritable: el volumen de adjuntos", () => {
|
||||
it("escribible → true, y el sondeo no deja rastro", async () => {
|
||||
const r = await checkHealth();
|
||||
expect(r.status).toBe(200);
|
||||
expect(r.body).toMatchObject({ ok: true, mediaWritable: true });
|
||||
expect(await readdir(path.join(tmp, "media"))).toEqual([]);
|
||||
});
|
||||
|
||||
it("no escribible → false, pero `ok` sigue en true y el código en 200", async () => {
|
||||
// Un healthcheck en rojo reiniciaría en bucle un contenedor que atiende
|
||||
// clientes: sin adjuntos el CRM funciona, y esto solo lo hace visible.
|
||||
const archivo = path.join(tmp, "no-soy-directorio");
|
||||
await writeFile(archivo, "x");
|
||||
getEnv.mockReturnValue({ MEDIA_DIR: path.join(archivo, "media") });
|
||||
|
||||
const r = await checkHealth();
|
||||
expect(r.status).toBe(200);
|
||||
expect(r.body).toMatchObject({ ok: true, mediaWritable: false });
|
||||
});
|
||||
|
||||
it("no escribe en cada llamada: el sondeo se recuerda un minuto", async () => {
|
||||
const dir = path.join(tmp, "media");
|
||||
const t0 = 1_000_000;
|
||||
expect((await mediaDirStatus(t0))?.writable).toBe(true);
|
||||
|
||||
// El directorio desaparece y en su lugar hay un archivo: un sondeo nuevo
|
||||
// diría false. Dentro del minuto se responde lo recordado; después, no.
|
||||
await rm(dir, { recursive: true, force: true });
|
||||
await writeFile(dir, "x");
|
||||
expect((await mediaDirStatus(t0 + MEDIA_DIR_PROBE_TTL_MS - 1))?.writable).toBe(true);
|
||||
expect((await mediaDirStatus(t0 + MEDIA_DIR_PROBE_TTL_MS))?.writable).toBe(false);
|
||||
});
|
||||
|
||||
it("si MEDIA_DIR cambia, se sondea el nuevo aunque el anterior esté fresco", async () => {
|
||||
const t0 = 1_000_000;
|
||||
expect((await mediaDirStatus(t0))?.writable).toBe(true);
|
||||
|
||||
const archivo = path.join(tmp, "no-soy-directorio");
|
||||
await writeFile(archivo, "x");
|
||||
getEnv.mockReturnValue({ MEDIA_DIR: path.join(archivo, "media") });
|
||||
expect((await mediaDirStatus(t0 + 1))?.writable).toBe(false);
|
||||
});
|
||||
|
||||
it("sin entorno válido no hay directorio que sondear", async () => {
|
||||
getEnv.mockImplementation(() => {
|
||||
throw new Error("Variables de entorno inválidas");
|
||||
});
|
||||
expect(await mediaDirStatus()).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("GET /api/health", () => {
|
||||
it("200 con la forma completa: lo de siempre más features y mediaWritable", async () => {
|
||||
process.env.AGENDA = "on";
|
||||
process.env.CHANNELS = "instagram";
|
||||
delete process.env.ATRIBUCION;
|
||||
|
||||
const res = await GET();
|
||||
expect(res.status).toBe(200);
|
||||
const cuerpo = await res.json();
|
||||
expect(cuerpo).toMatchObject({
|
||||
ok: true,
|
||||
features: { agenda: true, channels: ["whatsapp", "instagram"], atribucion: false, media: "disco" },
|
||||
mediaWritable: true,
|
||||
});
|
||||
expect(typeof cuerpo.version).toBe("string");
|
||||
// 047 — Los eventos de webhook sin entrar. Con la base de mentira no hay
|
||||
// tabla que contar: la llave sale en null y `ok` no se mueve.
|
||||
expect(cuerpo).toHaveProperty("webhooks", null);
|
||||
// Los campos de antes siguen delante: quien ya lee `ok` y `version` no
|
||||
// nota el cambio.
|
||||
expect(Object.keys(cuerpo).slice(0, 2)).toEqual(["ok", "version"]);
|
||||
});
|
||||
|
||||
it("BD caída: 503 y la misma respuesta de antes, sin features", async () => {
|
||||
getDb.mockReturnValue({
|
||||
execute: async () => {
|
||||
throw new Error("ECONNREFUSED");
|
||||
},
|
||||
});
|
||||
const res = await GET();
|
||||
expect(res.status).toBe(503);
|
||||
expect(await res.json()).toEqual({
|
||||
ok: false,
|
||||
error: { code: "db_unavailable", message: "Base de datos no disponible" },
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("la imagen no lleva lo que el migrador no lee", () => {
|
||||
it("el migrador de drizzle-orm abre meta/_journal.json y los .sql, nada más", () => {
|
||||
// Si una versión nueva de drizzle-orm empezara a leer los snapshots en
|
||||
// runtime, el .dockerignore de abajo rompería las migraciones del
|
||||
// arranque: esto lo atrapa antes.
|
||||
const migrador = readFileSync(
|
||||
path.join(RAIZ, "node_modules", "drizzle-orm", "migrator.js"),
|
||||
"utf8"
|
||||
);
|
||||
expect(migrador).toContain("meta/_journal.json");
|
||||
expect(migrador).toContain(".sql");
|
||||
expect(migrador).not.toMatch(/snapshot/i);
|
||||
});
|
||||
|
||||
it("scripts/migrate.mjs tampoco los toca", () => {
|
||||
const script = readFileSync(path.join(RAIZ, "scripts", "migrate.mjs"), "utf8");
|
||||
expect(script).toContain("drizzle-orm/postgres-js/migrator");
|
||||
expect(script).not.toMatch(/snapshot/i);
|
||||
});
|
||||
|
||||
it(".dockerignore deja fuera meta/ salvo el journal, y los .sql se quedan", () => {
|
||||
const lineas = readFileSync(path.join(RAIZ, ".dockerignore"), "utf8")
|
||||
.split(/\r?\n/)
|
||||
.map((l) => l.trim())
|
||||
.filter((l) => l && !l.startsWith("#"));
|
||||
const excluye = lineas.indexOf("drizzle/meta/*");
|
||||
const conserva = lineas.indexOf("!drizzle/meta/_journal.json");
|
||||
expect(excluye).toBeGreaterThanOrEqual(0);
|
||||
// La excepción tiene que venir DESPUÉS: en .dockerignore manda la última
|
||||
// regla que coincide.
|
||||
expect(conserva).toBeGreaterThan(excluye);
|
||||
expect(lineas.some((l) => /^drizzle\/?\*?$/.test(l) || l.endsWith(".sql"))).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,87 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { normalizeMx } from "@/lib/meta/client";
|
||||
import { BSUID_PREFIX, resolveIdentity } from "@/server/inbox/identity";
|
||||
import type { WebhookMessage, WebhookValue } from "@/server/inbox/webhook";
|
||||
|
||||
/** Feature 003: identidad resiliente de contacto (BSUID). */
|
||||
|
||||
function msg(partial: Partial<WebhookMessage>): WebhookMessage {
|
||||
return { id: "wamid.test.1", timestamp: "1752800000", type: "text", ...partial };
|
||||
}
|
||||
|
||||
describe("normalizeMx (simétrica ingest/envío)", () => {
|
||||
it("troncal MX 521 + 10 dígitos → 52 + 10 dígitos", () => {
|
||||
expect(normalizeMx("5215550001234")).toBe("525550001234");
|
||||
});
|
||||
|
||||
it("52 + 10 dígitos queda igual", () => {
|
||||
expect(normalizeMx("525550001234")).toBe("525550001234");
|
||||
});
|
||||
|
||||
it("otros países quedan intactos", () => {
|
||||
expect(normalizeMx("5491122334455")).toBe("5491122334455");
|
||||
expect(normalizeMx("14155551212")).toBe("14155551212");
|
||||
expect(normalizeMx("50761234567")).toBe("50761234567");
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveIdentity: teléfono presente", () => {
|
||||
const contacts: WebhookValue["contacts"] = [
|
||||
{ wa_id: "5215550001234", profile: { name: "Kevin" } },
|
||||
];
|
||||
|
||||
it("usa el teléfono NORMALIZADO como identidad", () => {
|
||||
const r = resolveIdentity(msg({ from: "5215550001234" }), contacts);
|
||||
expect(r).not.toBeNull();
|
||||
expect(r!.identity).toBe("525550001234");
|
||||
expect(r!.phone).toBe("525550001234");
|
||||
expect(r!.profileName).toBe("Kevin");
|
||||
});
|
||||
|
||||
it("521 y 52 resuelven a la MISMA identidad (dedup del bug MX)", () => {
|
||||
const a = resolveIdentity(msg({ from: "5215550001234" }), contacts);
|
||||
const b = resolveIdentity(msg({ from: "525550001234" }), []);
|
||||
expect(a!.identity).toBe(b!.identity);
|
||||
});
|
||||
|
||||
it("captura el BSUID si además viene user_id", () => {
|
||||
const r = resolveIdentity(msg({ from: "5215550001234" }), [
|
||||
{ wa_id: "5215550001234", user_id: "bsu_777", profile: { name: "Kevin" } },
|
||||
]);
|
||||
expect(r!.waUserId).toBe("bsu_777");
|
||||
expect(r!.identity).toBe("525550001234"); // el teléfono manda si existe
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveIdentity: sin wa_id (mundo BSUID)", () => {
|
||||
it("from_user_id en el mensaje → identidad bsuid:", () => {
|
||||
const r = resolveIdentity(msg({ from_user_id: "bsu_123" }), [
|
||||
{ user_id: "bsu_123", profile: { name: "Dueña Dental" } },
|
||||
]);
|
||||
expect(r).not.toBeNull();
|
||||
expect(r!.identity).toBe(`${BSUID_PREFIX}bsu_123`);
|
||||
expect(r!.phone).toBeNull();
|
||||
expect(r!.waUserId).toBe("bsu_123");
|
||||
expect(r!.profileName).toBe("Dueña Dental");
|
||||
});
|
||||
|
||||
it("user_id solo en contacts[] también resuelve", () => {
|
||||
const r = resolveIdentity(msg({}), [
|
||||
{ user_id: "bsu_456", profile: { name: "Cliente" } },
|
||||
]);
|
||||
expect(r).not.toBeNull();
|
||||
expect(r!.identity).toBe(`${BSUID_PREFIX}bsu_456`);
|
||||
});
|
||||
|
||||
it("sin from y sin user_id → null (descartar con log, no reventar)", () => {
|
||||
expect(resolveIdentity(msg({}), [])).toBeNull();
|
||||
expect(resolveIdentity(msg({}), undefined)).toBeNull();
|
||||
});
|
||||
|
||||
it("el nombre de perfil no cae al identificador crudo", () => {
|
||||
const r = resolveIdentity(msg({ from_user_id: "bsu_123" }), []);
|
||||
// Sin perfil: profileName null — el fallback de display se decide al crear
|
||||
// el contacto (nunca el BSUID crudo).
|
||||
expect(r!.profileName).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,175 @@
|
||||
import { readFileSync } from "node:fs";
|
||||
import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { parseEnv } from "node:util";
|
||||
import { afterEach, beforeEach, describe, expect, it } from "vitest";
|
||||
import { safeParseEnv } from "@/lib/env";
|
||||
import {
|
||||
generateSecrets,
|
||||
GENERATED_SECRETS,
|
||||
renderInitEnv,
|
||||
runInitEnv,
|
||||
} from "@/server/doctor/init-env";
|
||||
|
||||
/**
|
||||
* `pnpm init-env` existe para que `docker compose up -d` arranque sin editar
|
||||
* nada. Se prueba sobre el `.env.example` REAL del repo: si el ejemplo gana
|
||||
* una variable obligatoria sin generador, o cambia la forma de un
|
||||
* placeholder, esto se pone rojo antes que la instalación de alguien.
|
||||
*/
|
||||
|
||||
const RAIZ = path.resolve(import.meta.dirname, "..", "..");
|
||||
const EJEMPLO = readFileSync(path.join(RAIZ, ".env.example"), "utf8");
|
||||
|
||||
/** Solo las líneas activas (sin `#`), como las lee docker compose. */
|
||||
function activas(content: string): string[] {
|
||||
return content.split(/\r?\n/).filter((l) => /^[A-Z][A-Z0-9_]*=/.test(l));
|
||||
}
|
||||
|
||||
describe("generateSecrets", () => {
|
||||
it("genera justo los secretos que la documentación pedía con openssl, con la forma que exige el esquema", () => {
|
||||
const s = generateSecrets();
|
||||
expect(Object.keys(s).sort()).toEqual([
|
||||
"BETTER_AUTH_SECRET",
|
||||
"BOT_API_KEY",
|
||||
"ENCRYPTION_KEY",
|
||||
"META_WEBHOOK_VERIFY_TOKEN",
|
||||
"POSTGRES_PASSWORD",
|
||||
]);
|
||||
// AES-256-GCM: exactamente 32 bytes (44 caracteres en base64).
|
||||
expect(Buffer.from(s.ENCRYPTION_KEY, "base64")).toHaveLength(32);
|
||||
expect(s.ENCRYPTION_KEY).toHaveLength(44);
|
||||
expect(s.BETTER_AUTH_SECRET.length).toBeGreaterThanOrEqual(16);
|
||||
// hex: va dentro de una URL (DATABASE_URL) y del path del webhook sin escapar.
|
||||
expect(s.META_WEBHOOK_VERIFY_TOKEN).toMatch(/^[0-9a-f]{64}$/);
|
||||
expect(s.POSTGRES_PASSWORD).toMatch(/^[0-9a-f]{48}$/);
|
||||
// 2.0 — Firma el despacho al agente del compose: hex, en una cabecera.
|
||||
expect(s.BOT_API_KEY).toMatch(/^[0-9a-f]{64}$/);
|
||||
});
|
||||
|
||||
it("cada llamada produce valores distintos", () => {
|
||||
const a = generateSecrets();
|
||||
const b = generateSecrets();
|
||||
for (const key of Object.keys(GENERATED_SECRETS) as (keyof typeof GENERATED_SECRETS)[]) {
|
||||
expect(a[key]).not.toBe(b[key]);
|
||||
}
|
||||
});
|
||||
|
||||
it("cada secreto conserva el comando openssl equivalente (lo sugiere pnpm doctor)", () => {
|
||||
expect(GENERATED_SECRETS.ENCRYPTION_KEY.openssl).toBe("openssl rand -base64 32");
|
||||
expect(GENERATED_SECRETS.META_WEBHOOK_VERIFY_TOKEN.openssl).toBe("openssl rand -hex 32");
|
||||
expect(GENERATED_SECRETS.POSTGRES_PASSWORD.openssl).toBe("openssl rand -hex 24");
|
||||
});
|
||||
});
|
||||
|
||||
describe("renderInitEnv sobre el .env.example real", () => {
|
||||
it("deja un .env que pasa el esquema de arranque, sin REEMPLAZA_ activos y con DOMAIN=localhost", () => {
|
||||
const r = renderInitEnv(EJEMPLO);
|
||||
const vars = parseEnv(r.content);
|
||||
|
||||
expect(r.pending).toEqual([]);
|
||||
expect(activas(r.content).some((l) => l.includes("REEMPLAZA_"))).toBe(false);
|
||||
expect(vars.DOMAIN).toBe("localhost");
|
||||
expect(vars.APP_BASE_URL).toBe("https://localhost");
|
||||
|
||||
// Lo que importa de verdad: el mismo esquema que valida el arranque lo acepta.
|
||||
const parsed = safeParseEnv(vars);
|
||||
expect(parsed.success).toBe(true);
|
||||
});
|
||||
|
||||
it("la contraseña de Postgres es la misma en POSTGRES_PASSWORD y dentro de DATABASE_URL", () => {
|
||||
const secrets = { ...generateSecrets(), POSTGRES_PASSWORD: "abc123def456" };
|
||||
const vars = parseEnv(renderInitEnv(EJEMPLO, { secrets }).content);
|
||||
expect(vars.POSTGRES_PASSWORD).toBe("abc123def456");
|
||||
expect(vars.DATABASE_URL).toBe("postgresql://postgres:abc123def456@postgres:5432/vocero");
|
||||
});
|
||||
|
||||
it("--domain fija DOMAIN y APP_BASE_URL con https", () => {
|
||||
const vars = parseEnv(renderInitEnv(EJEMPLO, { domain: "crm.ejemplo.com" }).content);
|
||||
expect(vars.DOMAIN).toBe("crm.ejemplo.com");
|
||||
expect(vars.APP_BASE_URL).toBe("https://crm.ejemplo.com");
|
||||
});
|
||||
|
||||
it("conserva los comentarios y las opcionales comentadas: el .env sigue siendo la guía inline", () => {
|
||||
const r = renderInitEnv(EJEMPLO);
|
||||
const antes = EJEMPLO.split(/\r?\n/);
|
||||
const despues = r.content.split(/\r?\n/);
|
||||
expect(despues).toHaveLength(antes.length);
|
||||
antes.forEach((linea, i) => {
|
||||
if (!/^[A-Z][A-Z0-9_]*=/.test(linea)) expect(despues[i]).toBe(linea);
|
||||
});
|
||||
expect(r.content).toContain("# OPENROUTER_API_TOKEN=");
|
||||
// agenda, canales y atribución vienen ENCENDIDOS por defecto.
|
||||
expect(r.content).toMatch(/^AGENDA=on$/m);
|
||||
expect(r.content).toMatch(/^CHANNELS=whatsapp,instagram,messenger,tiktok$/m);
|
||||
expect(r.content).toMatch(/^ATRIBUCION=on$/m);
|
||||
expect(r.content).toContain("# SUPERADMIN_EMAIL=");
|
||||
});
|
||||
|
||||
it("reporta qué generó y qué fijó, por nombre y sin los valores", () => {
|
||||
const secrets = generateSecrets();
|
||||
const r = renderInitEnv(EJEMPLO, { secrets });
|
||||
expect(r.generated).toEqual([
|
||||
"POSTGRES_PASSWORD",
|
||||
"DATABASE_URL",
|
||||
"BETTER_AUTH_SECRET",
|
||||
"ENCRYPTION_KEY",
|
||||
"META_WEBHOOK_VERIFY_TOKEN",
|
||||
"BOT_API_KEY",
|
||||
]);
|
||||
expect(r.set).toEqual({ DOMAIN: "localhost", APP_BASE_URL: "https://localhost" });
|
||||
const resumen = JSON.stringify({ generated: r.generated, set: r.set });
|
||||
for (const valor of Object.values(secrets)) expect(resumen).not.toContain(valor);
|
||||
});
|
||||
|
||||
it("respeta el final de línea del ejemplo (CRLF en un checkout de Windows, LF en el VPS)", () => {
|
||||
const lf = EJEMPLO.replace(/\r\n/g, "\n");
|
||||
expect(renderInitEnv(lf).content).not.toContain("\r");
|
||||
const crlf = lf.replace(/\n/g, "\r\n");
|
||||
expect(renderInitEnv(crlf).content.split("\r\n").length).toBe(lf.split("\n").length);
|
||||
});
|
||||
});
|
||||
|
||||
describe("runInitEnv", () => {
|
||||
let dir: string;
|
||||
|
||||
beforeEach(async () => {
|
||||
dir = await mkdtemp(path.join(os.tmpdir(), "vocero-init-env-"));
|
||||
await writeFile(path.join(dir, ".env.example"), EJEMPLO);
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await rm(dir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
it("crea .env cuando no existe, con el contenido renderizado", async () => {
|
||||
const outcome = await runInitEnv({ dir });
|
||||
expect(outcome.status).toBe("created");
|
||||
if (outcome.status !== "created") return;
|
||||
const escrito = await readFile(path.join(dir, ".env"), "utf8");
|
||||
expect(escrito).toBe(outcome.rendered.content);
|
||||
expect(safeParseEnv(parseEnv(escrito)).success).toBe(true);
|
||||
});
|
||||
|
||||
it("no pisa un .env existente: avisa y no cambia ni un byte", async () => {
|
||||
// Un .env existente tiene los secretos reales de alguien (y quizá el
|
||||
// token de WhatsApp cifrado con ESA ENCRYPTION_KEY en su base).
|
||||
await writeFile(path.join(dir, ".env"), "MIO=1\n");
|
||||
const outcome = await runInitEnv({ dir });
|
||||
expect(outcome.status).toBe("exists");
|
||||
expect(await readFile(path.join(dir, ".env"), "utf8")).toBe("MIO=1\n");
|
||||
});
|
||||
|
||||
it("sin .env.example no inventa nada", async () => {
|
||||
await rm(path.join(dir, ".env.example"));
|
||||
const outcome = await runInitEnv({ dir });
|
||||
expect(outcome.status).toBe("no_example");
|
||||
});
|
||||
|
||||
it("rechaza un dominio con esquema o ruta (Caddy quiere solo el host)", async () => {
|
||||
expect((await runInitEnv({ dir, domain: "https://crm.ejemplo.com" })).status).toBe("bad_domain");
|
||||
expect((await runInitEnv({ dir, domain: "crm.ejemplo.com/app" })).status).toBe("bad_domain");
|
||||
expect((await runInitEnv({ dir, domain: "crm.ejemplo.com" })).status).toBe("created");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,173 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
/**
|
||||
* 036 — El interruptor de la pantalla Agente (`agent_profile.enabled`) ya no
|
||||
* enciende un agente que viva en el CRM: decide si el CRM le despacha al
|
||||
* cerebro. Lo que se protege:
|
||||
*
|
||||
* - Con el interruptor apagado, un mensaje real no se despacha: queda en la
|
||||
* bandeja para una persona.
|
||||
* - Encenderlo exige un cerebro configurado y sano (409 `sin_cerebro`):
|
||||
* encendido sin nadie que conteste, el dueño creería que contestan.
|
||||
* - Apagarlo siempre se puede.
|
||||
*/
|
||||
|
||||
const LLAVE = "k".repeat(32);
|
||||
|
||||
// Base falsa: cada `select` devuelve la siguiente respuesta de la cola.
|
||||
const cola = vi.hoisted(() => [] as unknown[][]);
|
||||
const updates = vi.hoisted(() => [] as unknown[]);
|
||||
vi.mock("@/lib/db", async (importOriginal) => {
|
||||
const real = await importOriginal<typeof import("@/lib/db")>();
|
||||
const consulta = () => {
|
||||
const q = {
|
||||
from: () => q,
|
||||
where: () => q,
|
||||
limit: () => q,
|
||||
then: (ok: (v: unknown[]) => unknown) => Promise.resolve(cola.shift() ?? []).then(ok),
|
||||
};
|
||||
return q;
|
||||
};
|
||||
return {
|
||||
...real,
|
||||
getDb: () => ({
|
||||
select: consulta,
|
||||
update: () => ({
|
||||
set: (v: unknown) => {
|
||||
updates.push(v);
|
||||
const w = { where: () => w, returning: async () => [{ id: "agp_1" }] };
|
||||
return w;
|
||||
},
|
||||
}),
|
||||
}),
|
||||
};
|
||||
});
|
||||
|
||||
const encolarDespacho = vi.hoisted(() => vi.fn(async () => ({ notBefore: new Date() })));
|
||||
vi.mock("@/server/dispatch/outbox", () => ({
|
||||
encolarDespacho,
|
||||
ventanaCoalesceMs: () => 3000,
|
||||
ventanaLargaMs: () => 8000,
|
||||
}));
|
||||
// 078 — El «escribiendo…» al encolar no toca Meta en las unitarias.
|
||||
const mostrarEscribiendo = vi.hoisted(() => vi.fn(async () => ({ ok: true })));
|
||||
vi.mock("@/server/whatsapp/escribiendo", () => ({ mostrarEscribiendo }));
|
||||
vi.mock("@/server/dispatch/worker", () => ({ iniciarWorker: () => {}, programarTanda: () => {} }));
|
||||
|
||||
const getBrainHealth = vi.hoisted(() => vi.fn());
|
||||
vi.mock("@/server/bot/status", () => ({ getBrainHealth }));
|
||||
|
||||
vi.mock("@/lib/auth/session", () => ({
|
||||
UnauthorizedError: class UnauthorizedError extends Error {},
|
||||
requireSession: async () => ({ userId: "usr_1", organizationId: "org_1", role: "owner" }),
|
||||
getSessionOrNull: async () => ({ userId: "usr_1", organizationId: "org_1", role: "owner" }),
|
||||
}));
|
||||
|
||||
import { despacharAlCerebro } from "@/server/dispatch/encolar";
|
||||
import { PUT } from "@/app/api/agent/profile/route";
|
||||
|
||||
const CONV_ABIERTA = { aiEnabled: true, handoffAt: null, isTest: false, channel: "whatsapp" };
|
||||
|
||||
beforeEach(() => {
|
||||
cola.length = 0;
|
||||
updates.length = 0;
|
||||
encolarDespacho.mockClear();
|
||||
mostrarEscribiendo.mockClear();
|
||||
getBrainHealth.mockReset();
|
||||
vi.stubEnv("BRAIN_DISPATCH_URL", "");
|
||||
vi.stubEnv("BRAIN_HEALTH_URL", "");
|
||||
vi.stubEnv("BOT_API_KEY", "");
|
||||
});
|
||||
afterEach(() => vi.unstubAllEnvs());
|
||||
|
||||
describe("el despacho respeta el interruptor", () => {
|
||||
it("encendido: se encola el turno y el cliente ve «escribiendo…»", async () => {
|
||||
cola.push([CONV_ABIERTA], [{ enabled: true }], [{ type: "text", text: "¿Cuánto cuesta la limpieza?" }]);
|
||||
await despacharAlCerebro("cv_1", "org_1", "msg_1");
|
||||
expect(encolarDespacho).toHaveBeenCalledWith({
|
||||
organizationId: "org_1",
|
||||
conversationId: "cv_1",
|
||||
messageIds: ["msg_1"],
|
||||
ventanaMs: 3000,
|
||||
});
|
||||
expect(mostrarEscribiendo).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("078 — un «Hola» espera la ventana larga", async () => {
|
||||
cola.push([CONV_ABIERTA], [{ enabled: true }], [{ type: "text", text: "Hola" }]);
|
||||
await despacharAlCerebro("cv_1", "org_1", "msg_1");
|
||||
expect(encolarDespacho).toHaveBeenCalledWith(expect.objectContaining({ ventanaMs: 8000 }));
|
||||
});
|
||||
|
||||
it("apagado: no se encola, queda en la bandeja", async () => {
|
||||
cola.push([CONV_ABIERTA], [{ enabled: false }]);
|
||||
await despacharAlCerebro("cv_1", "org_1", "msg_1");
|
||||
expect(encolarDespacho).not.toHaveBeenCalled();
|
||||
expect(mostrarEscribiendo).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("sin perfil: no se encola", async () => {
|
||||
cola.push([CONV_ABIERTA], []);
|
||||
await despacharAlCerebro("cv_1", "org_1", "msg_1");
|
||||
expect(encolarDespacho).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("la conversación pausada sigue mandando, aunque el interruptor esté encendido", async () => {
|
||||
cola.push([{ ...CONV_ABIERTA, aiEnabled: false }], [{ enabled: true }]);
|
||||
await despacharAlCerebro("cv_1", "org_1", "msg_1");
|
||||
expect(encolarDespacho).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
const encender = (enabled: boolean) =>
|
||||
PUT(
|
||||
new Request("http://crm.test/api/agent/profile", {
|
||||
method: "PUT",
|
||||
headers: { "content-type": "application/json", origin: "http://crm.test" },
|
||||
body: JSON.stringify({ enabled }),
|
||||
})
|
||||
);
|
||||
|
||||
describe("PUT /api/agent/profile {enabled}", () => {
|
||||
it("sin cerebro configurado → 409 sin_cerebro y no se guarda", async () => {
|
||||
const res = await encender(true);
|
||||
expect(res.status).toBe(409);
|
||||
const body = await res.json();
|
||||
expect(body.error.code).toBe("sin_cerebro");
|
||||
expect(body.error.message).toMatch(/BRAIN_DISPATCH_URL/);
|
||||
expect(updates).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("sin BOT_API_KEY → 409 que lo dice", async () => {
|
||||
vi.stubEnv("BRAIN_DISPATCH_URL", "http://nea:8000/vocero/dispatch");
|
||||
const res = await encender(true);
|
||||
expect(res.status).toBe(409);
|
||||
expect((await res.json()).error.message).toMatch(/BOT_API_KEY/);
|
||||
});
|
||||
|
||||
it("configurado pero el /health no contesta → 409", async () => {
|
||||
vi.stubEnv("BRAIN_DISPATCH_URL", "http://nea:8000/vocero/dispatch");
|
||||
vi.stubEnv("BOT_API_KEY", LLAVE);
|
||||
getBrainHealth.mockResolvedValue({ reachable: false, host: "nea:8000", checkedAt: "", problem: "network" });
|
||||
const res = await encender(true);
|
||||
expect(res.status).toBe(409);
|
||||
expect((await res.json()).error.message).toMatch(/no contesta/);
|
||||
expect(getBrainHealth).toHaveBeenCalledWith("http://nea:8000/health");
|
||||
});
|
||||
|
||||
it("configurado y sano → se enciende", async () => {
|
||||
vi.stubEnv("BRAIN_DISPATCH_URL", "http://nea:8000/vocero/dispatch");
|
||||
vi.stubEnv("BOT_API_KEY", LLAVE);
|
||||
getBrainHealth.mockResolvedValue({ reachable: true, host: "nea:8000", checkedAt: "" });
|
||||
const res = await encender(true);
|
||||
expect(res.status).toBe(200);
|
||||
expect(updates[0]).toMatchObject({ enabled: true });
|
||||
});
|
||||
|
||||
it("apagar siempre se puede, sin preguntarle a nadie", async () => {
|
||||
const res = await encender(false);
|
||||
expect(res.status).toBe(200);
|
||||
expect(updates[0]).toMatchObject({ enabled: false });
|
||||
expect(getBrainHealth).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,80 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const chatJson = vi.fn();
|
||||
|
||||
vi.mock("@/lib/ai", () => ({
|
||||
chatJson: (...args: unknown[]) => chatJson(...args),
|
||||
}));
|
||||
|
||||
import { computeScore, judgeCase } from "@/server/lab/judge";
|
||||
|
||||
describe("judgeCase (FR-032)", () => {
|
||||
beforeEach(() => chatJson.mockReset());
|
||||
|
||||
it("veredicto válido → done", async () => {
|
||||
chatJson.mockResolvedValue({
|
||||
ok: true,
|
||||
data: { veredicto: "verde", hallazgos: [] },
|
||||
raw: "{}",
|
||||
});
|
||||
const outcome = await judgeCase({
|
||||
organizationId: "org_1",
|
||||
personaKey: "comprador_decidido",
|
||||
transcript: [{ role: "cliente", text: "hola" }],
|
||||
kbText: "kb",
|
||||
behaviorText: "b",
|
||||
});
|
||||
expect(outcome.status).toBe("done");
|
||||
// usa el modelo del juez (opts.judge)
|
||||
expect(chatJson.mock.calls[0]![2]).toMatchObject({ judge: true });
|
||||
});
|
||||
|
||||
it("salida inválida tras reintentos internos → judge_failed (no lanza)", async () => {
|
||||
chatJson.mockResolvedValue({
|
||||
ok: false,
|
||||
error: "invalid_output",
|
||||
detail: "no cumple el esquema (raw=...)",
|
||||
});
|
||||
const outcome = await judgeCase({
|
||||
organizationId: "org_1",
|
||||
personaKey: "fuera_de_kb",
|
||||
transcript: [],
|
||||
kbText: "",
|
||||
behaviorText: "",
|
||||
});
|
||||
expect(outcome.status).toBe("judge_failed");
|
||||
});
|
||||
});
|
||||
|
||||
describe("computeScore (FR-033: judge_failed excluido del denominador)", () => {
|
||||
it("pondera verde=1, amarillo=0.5, rojo=0", () => {
|
||||
const score = computeScore([
|
||||
{ status: "done", veredicto: "verde" },
|
||||
{ status: "done", veredicto: "amarillo" },
|
||||
{ status: "done", veredicto: "rojo" },
|
||||
]);
|
||||
expect(score).toBe(50); // (1 + 0.5 + 0) / 3 = 0.5
|
||||
});
|
||||
|
||||
it("judge_failed NO cuenta en el denominador", () => {
|
||||
const score = computeScore([
|
||||
{ status: "done", veredicto: "verde" },
|
||||
{ status: "done", veredicto: "verde" },
|
||||
{ status: "judge_failed", veredicto: null },
|
||||
]);
|
||||
expect(score).toBe(100); // 2/2, no 2/3
|
||||
});
|
||||
|
||||
it("todo judge_failed → sin score (null)", () => {
|
||||
expect(
|
||||
computeScore([{ status: "judge_failed", veredicto: null }])
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
it("6 verdes → 100; 6 rojos → 0", () => {
|
||||
const verdes = Array(6).fill({ status: "done", veredicto: "verde" });
|
||||
const rojos = Array(6).fill({ status: "done", veredicto: "rojo" });
|
||||
expect(computeScore(verdes)).toBe(100);
|
||||
expect(computeScore(rojos)).toBe(0);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,29 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { buildJudgePrompt } from "@/server/ai/prompts";
|
||||
|
||||
/**
|
||||
* 033 — El traspaso a una persona no es un mensaje: el runner lo anota como
|
||||
* línea SISTEMA. Sin ella, el juez marcaba «debió escalar» a un agente que sí
|
||||
* escaló (visto en la primera corrida en vivo contra Nea, 2026-10-20).
|
||||
*/
|
||||
describe("el juez ve el traspaso", () => {
|
||||
const { system, user } = buildJudgePrompt({
|
||||
persona: "pide_humano",
|
||||
transcript: [
|
||||
{ role: "cliente", text: "quiero hablar con un humano" },
|
||||
{ role: "agente", text: "Claro, te paso con el equipo." },
|
||||
{ role: "sistema", text: "La conversación pasó a una persona (motivo: cliente)." },
|
||||
],
|
||||
kbText: "",
|
||||
behaviorText: "",
|
||||
});
|
||||
|
||||
it("la línea sale como SISTEMA, no como AGENTE", () => {
|
||||
expect(user).toContain("SISTEMA: La conversación pasó a una persona (motivo: cliente).");
|
||||
expect(user).not.toContain("AGENTE: La conversación pasó");
|
||||
});
|
||||
|
||||
it("y el juez sabe que un traspaso ahí es un escalado", () => {
|
||||
expect(system).toMatch(/SISTEMA.*Un traspaso registrado ahí ES un escalado/s);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,143 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
decidirVuelta,
|
||||
finDePausa,
|
||||
HORAS_REACTIVACION_NUEVAS,
|
||||
MOTIVOS_QUE_VUELVEN,
|
||||
type EstadoPausa,
|
||||
} from "@/server/inbox/reactivacion";
|
||||
import { textoVuelta } from "@/lib/eventos-hilo";
|
||||
|
||||
/** 076 — Cuándo vuelve la IA sola y la pausa con duración. */
|
||||
|
||||
const H = 3_600_000;
|
||||
const AHORA = new Date("2026-11-23T18:00:00.000Z");
|
||||
const hace = (horas: number) => new Date(AHORA.getTime() - horas * H);
|
||||
|
||||
function estado(o: Partial<EstadoPausa> = {}): EstadoPausa {
|
||||
return {
|
||||
isTest: false,
|
||||
aiEnabled: true,
|
||||
handoffAt: null,
|
||||
handoffReason: null,
|
||||
aiPausedUntil: null,
|
||||
lastTeamOutAt: null,
|
||||
...o,
|
||||
};
|
||||
}
|
||||
|
||||
describe("decidirVuelta — traspaso a una persona", () => {
|
||||
it("vuelve si el equipo lleva N horas sin escribir", () => {
|
||||
const c = estado({ handoffAt: hace(30), handoffReason: "manual_reply", lastTeamOutAt: hace(25) });
|
||||
expect(decidirVuelta(c, { horas: 24, now: AHORA })).toEqual({ motivo: "sin_equipo", horas: 24 });
|
||||
});
|
||||
|
||||
it("antes de N horas sigue en pausa, aunque el traspaso sea viejo", () => {
|
||||
// El equipo contestó hace 2 h en un traspaso de hace 3 días: la lleva una persona.
|
||||
const c = estado({ handoffAt: hace(72), handoffReason: "manual_reply", lastTeamOutAt: hace(2) });
|
||||
expect(decidirVuelta(c, { horas: 24, now: AHORA })).toBeNull();
|
||||
});
|
||||
|
||||
it("contestar apaga ai_enabled: con traspaso esa bandera no cuenta", () => {
|
||||
const c = estado({ aiEnabled: false, handoffAt: hace(30), handoffReason: "manual_reply", lastTeamOutAt: hace(30) });
|
||||
expect(decidirVuelta(c, { horas: 24, now: AHORA })?.motivo).toBe("sin_equipo");
|
||||
});
|
||||
|
||||
it("sin mensajes del equipo cuenta desde el traspaso", () => {
|
||||
const c = estado({ handoffAt: hace(23), handoffReason: "cliente" });
|
||||
expect(decidirVuelta(c, { horas: 24, now: AHORA })).toBeNull();
|
||||
expect(decidirVuelta({ ...c, handoffAt: hace(24) }, { horas: 24, now: AHORA })?.motivo).toBe("sin_equipo");
|
||||
});
|
||||
|
||||
it("con el ajuste vacío (null) nunca vuelve", () => {
|
||||
const c = estado({ handoffAt: hace(500), handoffReason: "modelo" });
|
||||
expect(decidirVuelta(c, { horas: null, now: AHORA })).toBeNull();
|
||||
expect(decidirVuelta(c, { horas: 0, now: AHORA })).toBeNull();
|
||||
});
|
||||
|
||||
it("nunca tras hostilidad ni con un motivo desconocido", () => {
|
||||
for (const motivo of ["hostilidad", "sin_credencial", "otro_que_no_existe"]) {
|
||||
const c = estado({ handoffAt: hace(500), handoffReason: motivo });
|
||||
expect(decidirVuelta(c, { horas: 1, now: AHORA })).toBeNull();
|
||||
}
|
||||
expect(MOTIVOS_QUE_VUELVEN).not.toContain("hostilidad");
|
||||
});
|
||||
|
||||
it("nunca en una conversación de prueba", () => {
|
||||
const c = estado({ isTest: true, handoffAt: hace(500), handoffReason: "cliente" });
|
||||
expect(decidirVuelta(c, { horas: 1, now: AHORA })).toBeNull();
|
||||
});
|
||||
|
||||
it("una IA que no está en pausa no «vuelve»", () => {
|
||||
expect(decidirVuelta(estado(), { horas: 1, now: AHORA })).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("decidirVuelta — pausa manual con fecha", () => {
|
||||
it("vuelve al vencer", () => {
|
||||
const c = estado({ aiEnabled: false, aiPausedUntil: hace(0.1) });
|
||||
expect(decidirVuelta(c, { horas: null, now: AHORA })).toEqual({ motivo: "pausa_vencida", horas: null });
|
||||
});
|
||||
|
||||
it("vigente, no vuelve aunque el traspaso ya cumpla las N horas", () => {
|
||||
const c = estado({ aiEnabled: false, aiPausedUntil: new Date(AHORA.getTime() + H), handoffAt: hace(100), handoffReason: "cliente" });
|
||||
expect(decidirVuelta(c, { horas: 24, now: AHORA })).toBeNull();
|
||||
});
|
||||
|
||||
it("sin fecha es indefinida", () => {
|
||||
const c = estado({ aiEnabled: false, aiPausedUntil: null });
|
||||
expect(decidirVuelta(c, { horas: 1, now: AHORA })).toBeNull();
|
||||
});
|
||||
|
||||
it("vencida, pero el equipo escribió hace poco por un camino que no pausa: sigue con el equipo", () => {
|
||||
const c = estado({ aiEnabled: false, aiPausedUntil: hace(1), lastTeamOutAt: hace(0.5) });
|
||||
expect(decidirVuelta(c, { horas: 24, now: AHORA })).toBeNull();
|
||||
});
|
||||
|
||||
it("vencida con traspaso: manda la regla del equipo", () => {
|
||||
const c = estado({ aiEnabled: false, aiPausedUntil: hace(1), handoffAt: hace(2), handoffReason: "manual_reply", lastTeamOutAt: hace(2) });
|
||||
expect(decidirVuelta(c, { horas: 24, now: AHORA })).toBeNull();
|
||||
expect(decidirVuelta(c, { horas: null, now: AHORA })).toBeNull();
|
||||
expect(decidirVuelta(c, { horas: 1, now: AHORA })).toEqual({ motivo: "sin_equipo", horas: 1 });
|
||||
});
|
||||
});
|
||||
|
||||
describe("finDePausa", () => {
|
||||
it("1 hora", () => {
|
||||
expect(finDePausa("1h", "America/Mexico_City", AHORA)?.toISOString()).toBe("2026-11-23T19:00:00.000Z");
|
||||
});
|
||||
|
||||
it("hasta mañana = las 9:00 del día siguiente en la zona del negocio", () => {
|
||||
// 18:00 UTC = 12:00 en CDMX (UTC−6): mañana 9:00 CDMX = 15:00 UTC.
|
||||
expect(finDePausa("manana", "America/Mexico_City", AHORA)?.toISOString()).toBe("2026-11-24T15:00:00.000Z");
|
||||
// En Madrid (UTC+1) ya son las 19:00: mañana 9:00 = 8:00 UTC.
|
||||
expect(finDePausa("manana", "Europe/Madrid", AHORA)?.toISOString()).toBe("2026-11-24T08:00:00.000Z");
|
||||
// A las 23:30 de CDMX sigue siendo la mañana siguiente.
|
||||
const noche = new Date("2026-11-24T05:30:00.000Z");
|
||||
expect(finDePausa("manana", "America/Mexico_City", noche)?.toISOString()).toBe("2026-11-24T15:00:00.000Z");
|
||||
});
|
||||
|
||||
it("de madrugada, «hasta mañana» es la mañana de ese mismo día", () => {
|
||||
// 1:00 en CDMX del 24: vuelve a las 9:00 del 24, no del 25.
|
||||
const madrugada = new Date("2026-11-24T07:00:00.000Z");
|
||||
expect(finDePausa("manana", "America/Mexico_City", madrugada)?.toISOString()).toBe("2026-11-24T15:00:00.000Z");
|
||||
// 5:00 ya es de día: la del día siguiente.
|
||||
const temprano = new Date("2026-11-24T11:00:00.000Z");
|
||||
expect(finDePausa("manana", "America/Mexico_City", temprano)?.toISOString()).toBe("2026-11-25T15:00:00.000Z");
|
||||
});
|
||||
|
||||
it("indefinida no tiene fin", () => {
|
||||
expect(finDePausa("indefinida", "America/Mexico_City", AHORA)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("valores por defecto y textos", () => {
|
||||
it("un negocio nuevo nace con 24 h", () => {
|
||||
expect(HORAS_REACTIVACION_NUEVAS).toBe(24);
|
||||
});
|
||||
|
||||
it("el hilo dice por qué volvió", () => {
|
||||
expect(textoVuelta("sin_equipo", 24)).toBe("La IA volvió a atender (24 h sin respuesta del equipo)");
|
||||
expect(textoVuelta("pausa_vencida", null)).toBe("La IA volvió a atender (terminó la pausa)");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,36 @@
|
||||
import { readdirSync, readFileSync, statSync } from "node:fs";
|
||||
import path from "node:path";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
/**
|
||||
* Guardián de la sesión de 7 días (073, ver `src/lib/auth/leer-sesion.ts`).
|
||||
*
|
||||
* En el servidor la sesión se lee siempre sin renovar: una lectura que renueva
|
||||
* alarga la base y pierde el `Set-Cookie`, y la cookie del navegador se queda
|
||||
* con la caducidad del login. Si alguien vuelve a llamar `api.getSession`
|
||||
* directo, esta prueba lo señala.
|
||||
*/
|
||||
const SRC = path.resolve(import.meta.dirname, "../../src");
|
||||
const PERMITIDO = path.join(SRC, "lib", "auth", "leer-sesion.ts");
|
||||
|
||||
function archivos(dir: string): string[] {
|
||||
return readdirSync(dir).flatMap((nombre) => {
|
||||
const ruta = path.join(dir, nombre);
|
||||
if (statSync(ruta).isDirectory()) return archivos(ruta);
|
||||
return /\.(ts|tsx)$/.test(nombre) ? [ruta] : [];
|
||||
});
|
||||
}
|
||||
|
||||
describe("lectura de la sesión en el servidor", () => {
|
||||
it("solo leerSesion llama a api.getSession", () => {
|
||||
const culpables = archivos(SRC)
|
||||
.filter((f) => f !== PERMITIDO)
|
||||
.filter((f) => /\.api\s*\.getSession\s*\(/.test(readFileSync(f, "utf8")))
|
||||
.map((f) => path.relative(SRC, f));
|
||||
expect(culpables).toEqual([]);
|
||||
});
|
||||
|
||||
it("leerSesion pide la sesión sin renovarla", () => {
|
||||
expect(readFileSync(PERMITIDO, "utf8")).toMatch(/disableRefresh:\s*true/);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,90 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { splitLinks } from "@/lib/linkify";
|
||||
|
||||
const links = (text: string) =>
|
||||
splitLinks(text).flatMap((p) => (p.type === "link" ? [p.href] : []));
|
||||
|
||||
describe("040 — splitLinks", () => {
|
||||
it("deja el texto sin ligas como un solo tramo", () => {
|
||||
expect(splitLinks("Lunes a sábado: 9:00 am a 7:00 pm")).toEqual([
|
||||
{ type: "text", text: "Lunes a sábado: 9:00 am a 7:00 pm" },
|
||||
]);
|
||||
});
|
||||
|
||||
it("reconoce la liga de un mapa y conserva el texto alrededor", () => {
|
||||
const text = "Dirección:\n\nAv. Siempre Viva 742, Centro\nhttps://maps.example.com/abc123";
|
||||
expect(splitLinks(text)).toEqual([
|
||||
{ type: "text", text: "Dirección:\n\nAv. Siempre Viva 742, Centro\n" },
|
||||
{
|
||||
type: "link",
|
||||
text: "https://maps.example.com/abc123",
|
||||
href: "https://maps.example.com/abc123",
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("conserva la ruta, los parámetros y el fragmento", () => {
|
||||
expect(links("Pago en línea: https://pagos.example.com/p/9?t=MTA2N&x=1#fin")).toEqual([
|
||||
"https://pagos.example.com/p/9?t=MTA2N&x=1#fin",
|
||||
]);
|
||||
});
|
||||
|
||||
it("no se come la puntuación ni el paréntesis que cierran la frase", () => {
|
||||
const parts = splitLinks("Aquí está (https://maps.example.com/abc).");
|
||||
expect(parts.map((p) => p.text)).toEqual(["Aquí está (", "https://maps.example.com/abc", ")."]);
|
||||
expect(links("¿Ya viste https://example.com/catalogo?")).toEqual(["https://example.com/catalogo"]);
|
||||
expect(links("«https://example.com/a»")).toEqual(["https://example.com/a"]);
|
||||
});
|
||||
|
||||
it("respeta los paréntesis que son parte de la liga", () => {
|
||||
expect(links("https://es.wikipedia.org/wiki/Martillo_(herramienta)")).toEqual([
|
||||
"https://es.wikipedia.org/wiki/Martillo_(herramienta)",
|
||||
]);
|
||||
});
|
||||
|
||||
it("completa https:// en las ligas que empiezan con www.", () => {
|
||||
expect(links("entra a www.example.com, ahí está")).toEqual(["https://www.example.com"]);
|
||||
expect(splitLinks("www.example.com")[0]).toMatchObject({ text: "www.example.com" });
|
||||
});
|
||||
|
||||
it("acepta HTTP y mayúsculas en el esquema", () => {
|
||||
expect(links("HTTPS://EXAMPLE.COM/A y http://example.com")).toEqual([
|
||||
"HTTPS://EXAMPLE.COM/A",
|
||||
"http://example.com",
|
||||
]);
|
||||
});
|
||||
|
||||
it("no convierte otros esquemas", () => {
|
||||
expect(links("javascript:alert(1) mailto:a@b.com ftp://x.com data:text/html,hola")).toEqual([]);
|
||||
});
|
||||
|
||||
it("no toma un «www.» o un «https://» sueltos", () => {
|
||||
expect(links("escribe www. y luego https:// nada más")).toEqual([]);
|
||||
expect(splitLinks("escribe www. nada")).toEqual([{ type: "text", text: "escribe www. nada" }]);
|
||||
});
|
||||
|
||||
it("no parte una palabra que contiene «www.» en medio", () => {
|
||||
expect(links("abcwww.example.com")).toEqual([]);
|
||||
});
|
||||
|
||||
it("encuentra varias ligas en un mensaje y el texto entre ellas", () => {
|
||||
const parts = splitLinks("https://a.example.com y https://b.example.com/x");
|
||||
expect(parts.map((p) => p.type)).toEqual(["link", "text", "link"]);
|
||||
expect(links("https://a.example.com y https://b.example.com/x")).toEqual([
|
||||
"https://a.example.com",
|
||||
"https://b.example.com/x",
|
||||
]);
|
||||
});
|
||||
|
||||
it("une los tramos y devuelve exactamente el texto original", () => {
|
||||
const text = "Mira (https://example.com/a), www.example.org. Fin";
|
||||
expect(splitLinks(text).map((p) => p.text).join("")).toBe(text);
|
||||
});
|
||||
|
||||
it("corta la liga en las comillas y los signos < >", () => {
|
||||
expect(links('<https://example.com/a> "https://example.com/b"')).toEqual([
|
||||
"https://example.com/a",
|
||||
"https://example.com/b",
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,114 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { unaALaVez } from "@/lib/lista-compartida";
|
||||
|
||||
/* 064 — Las recargas de la lista que llegan seguidas se juntan en una. */
|
||||
|
||||
describe("unaALaVez", () => {
|
||||
beforeEach(() => vi.useFakeTimers());
|
||||
afterEach(() => vi.useRealTimers());
|
||||
|
||||
it("diez llamadas seguidas son una sola petición", async () => {
|
||||
const fn = vi.fn(async () => "lista");
|
||||
const recargar = unaALaVez(fn, 300);
|
||||
const promesas = Array.from({ length: 10 }, () => recargar());
|
||||
await vi.advanceTimersByTimeAsync(300);
|
||||
expect(await Promise.all(promesas)).toEqual(Array(10).fill("lista"));
|
||||
expect(fn).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("lo que llega mientras pide agenda UNA más, no una por llamada", async () => {
|
||||
let soltar!: () => void;
|
||||
const fn = vi.fn(() => new Promise<number>((r) => { soltar = () => r(fn.mock.calls.length); }));
|
||||
const recargar = unaALaVez(fn, 300);
|
||||
const primera = recargar();
|
||||
await vi.advanceTimersByTimeAsync(300);
|
||||
expect(fn).toHaveBeenCalledTimes(1);
|
||||
// Ya está pidiendo: cinco eventos más.
|
||||
const otras = Array.from({ length: 5 }, () => recargar());
|
||||
soltar();
|
||||
expect(await primera).toBe(1);
|
||||
await vi.advanceTimersByTimeAsync(300);
|
||||
soltar();
|
||||
expect(new Set(await Promise.all(otras))).toEqual(new Set([2]));
|
||||
expect(fn).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("nunca corren dos a la vez", async () => {
|
||||
let enCurso = 0;
|
||||
let maximo = 0;
|
||||
const fn = vi.fn(async () => {
|
||||
enCurso++;
|
||||
maximo = Math.max(maximo, enCurso);
|
||||
await new Promise((r) => setTimeout(r, 1000));
|
||||
enCurso--;
|
||||
});
|
||||
const recargar = unaALaVez(fn, 100);
|
||||
for (let i = 0; i < 6; i++) {
|
||||
void recargar();
|
||||
await vi.advanceTimersByTimeAsync(250);
|
||||
}
|
||||
await vi.advanceTimersByTimeAsync(5000);
|
||||
expect(maximo).toBe(1);
|
||||
expect(fn.mock.calls.length).toBeLessThanOrEqual(3);
|
||||
});
|
||||
|
||||
it("si una petición falla, la siguiente igual corre", async () => {
|
||||
const fn = vi.fn<() => Promise<string>>()
|
||||
.mockRejectedValueOnce(new Error("red"))
|
||||
.mockResolvedValueOnce("ok");
|
||||
const recargar = unaALaVez(fn, 50);
|
||||
const primera = recargar().catch((e: Error) => e.message);
|
||||
await vi.advanceTimersByTimeAsync(50);
|
||||
expect(await primera).toBe("red");
|
||||
const segunda = recargar();
|
||||
await vi.advanceTimersByTimeAsync(50);
|
||||
expect(await segunda).toBe("ok");
|
||||
});
|
||||
});
|
||||
|
||||
describe("la lista que publica la Bandeja", () => {
|
||||
beforeEach(() => vi.stubGlobal("window", new EventTarget()));
|
||||
afterEach(() => vi.unstubAllGlobals());
|
||||
|
||||
const lista = [{ id: "cv_1", unreadCount: 2, contact: { name: "Ana", phone: null } }];
|
||||
|
||||
it("solo vale mientras la Bandeja sigue abierta", async () => {
|
||||
const { marcarBandejaMontada, publicarLista, listaVigente, bandejaMontada } = await import(
|
||||
"@/lib/lista-compartida"
|
||||
);
|
||||
expect(listaVigente()).toBeNull();
|
||||
const cerrar = marcarBandejaMontada();
|
||||
expect(bandejaMontada()).toBe(true);
|
||||
expect(listaVigente()).toBeNull();
|
||||
publicarLista(lista);
|
||||
expect(listaVigente()).toEqual(lista);
|
||||
cerrar();
|
||||
expect(bandejaMontada()).toBe(false);
|
||||
expect(listaVigente()).toBeNull();
|
||||
});
|
||||
|
||||
it("el menú recibe lo publicado y se entera cuando la Bandeja se cierra", async () => {
|
||||
const { marcarBandejaMontada, publicarLista, alPublicarLista, alDesmontarBandeja } = await import(
|
||||
"@/lib/lista-compartida"
|
||||
);
|
||||
const recibidas: unknown[] = [];
|
||||
const quitar = alPublicarLista((l) => recibidas.push(l));
|
||||
const desmontada = vi.fn();
|
||||
const quitarD = alDesmontarBandeja(desmontada);
|
||||
const cerrar = marcarBandejaMontada();
|
||||
publicarLista(lista);
|
||||
cerrar();
|
||||
expect(recibidas).toEqual([lista]);
|
||||
expect(desmontada).toHaveBeenCalledTimes(1);
|
||||
quitar();
|
||||
quitarD();
|
||||
});
|
||||
|
||||
it("esperarLista se salta la que no sirve y toma la siguiente", async () => {
|
||||
const { publicarLista, esperarLista } = await import("@/lib/lista-compartida");
|
||||
const espera = esperarLista(1000, (l) => l.some((c) => c.id === "cv_1"));
|
||||
publicarLista([]);
|
||||
publicarLista(lista);
|
||||
expect(await espera).toEqual(lista);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,212 @@
|
||||
import { readFileSync } from "node:fs";
|
||||
import path from "node:path";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { envSchema } from "@/lib/env";
|
||||
|
||||
/**
|
||||
* #88 — Un manifest por plataforma (Render, Fly, Railway) para desplegar la
|
||||
* imagen publicada fuera de Coolify con un comando. Cada uno declara lo que
|
||||
* su plataforma le deja declarar (puerto 3000, healthcheck /api/health,
|
||||
* volumen en /data, imagen fijada a la versión) y documenta, en comentarios,
|
||||
* lo que queda a mano. Las variables obligatorias salen del mismo esquema
|
||||
* que valida el arranque (src/lib/env.ts): si alguien agrega una nueva,
|
||||
* esto se pone rojo hasta que los tres manifests la lleven, declarada o en
|
||||
* el comando que la fija.
|
||||
*/
|
||||
|
||||
const RAIZ = path.resolve(import.meta.dirname, "..", "..");
|
||||
const pkg = JSON.parse(
|
||||
readFileSync(path.join(RAIZ, "package.json"), "utf8")
|
||||
) as { version: string };
|
||||
const IMAGEN = `ghcr.io/kevinrivm/vocero-crm:${pkg.version}`;
|
||||
|
||||
// Un checkout de Windows con autocrlf deja CRLF: se normaliza para que las
|
||||
// expresiones con `\n` lean lo mismo en cualquier máquina.
|
||||
const leer = (nombre: string) =>
|
||||
readFileSync(path.join(RAIZ, nombre), "utf8").replace(/\r\n?/g, "\n");
|
||||
/** Solo lo que la plataforma lee: sin las líneas de comentario. */
|
||||
const sinComentarios = (texto: string) =>
|
||||
texto
|
||||
.split("\n")
|
||||
.filter((linea) => !/^\s*#/.test(linea))
|
||||
.join("\n");
|
||||
|
||||
// Obligatoria = sin `.optional()` ni `.default()`. `isOptional()` solo prueba
|
||||
// `undefined` contra el tipo: no lee el entorno ni deja nada cacheado.
|
||||
const OBLIGATORIAS = Object.entries(envSchema.shape)
|
||||
.filter(([, tipo]) => !tipo.isOptional())
|
||||
.map(([clave]) => clave);
|
||||
|
||||
const render = leer("render.yaml");
|
||||
const fly = leer("fly.toml");
|
||||
const railway = leer("railway.toml");
|
||||
|
||||
/** El bloque YAML de una variable de render.yaml: desde su `- key:` hasta el siguiente. */
|
||||
function bloqueRender(clave: string): string {
|
||||
const m = render.match(
|
||||
new RegExp(`^\\s*- key: ${clave}\\n((?:(?!\\s*- key:).*\\n)*)`, "m")
|
||||
);
|
||||
expect(m, `render.yaml declara ${clave}`).not.toBeNull();
|
||||
return m?.[1] ?? "";
|
||||
}
|
||||
|
||||
describe("las variables obligatorias salen del esquema real", () => {
|
||||
it("son las cinco sin default", () => {
|
||||
expect(OBLIGATORIAS).toEqual(
|
||||
expect.arrayContaining([
|
||||
"APP_BASE_URL",
|
||||
"DATABASE_URL",
|
||||
"BETTER_AUTH_SECRET",
|
||||
"ENCRYPTION_KEY",
|
||||
"META_WEBHOOK_VERIFY_TOKEN",
|
||||
])
|
||||
);
|
||||
expect(OBLIGATORIAS).not.toContain("META_GRAPH_API_VERSION");
|
||||
expect(OBLIGATORIAS).not.toContain("MEDIA_DIR");
|
||||
});
|
||||
});
|
||||
|
||||
describe.each([
|
||||
["render.yaml", render],
|
||||
["fly.toml", fly],
|
||||
["railway.toml", railway],
|
||||
])("%s: lo común a los tres", (_nombre, texto) => {
|
||||
it("nombra cada variable obligatoria, declarada o en el comando que la fija", () => {
|
||||
for (const clave of OBLIGATORIAS) {
|
||||
expect(texto, clave).toMatch(new RegExp(`\\b${clave}\\b`));
|
||||
}
|
||||
});
|
||||
|
||||
it("fija la imagen publicada a la versión de package.json", () => {
|
||||
// Como el compose (tests/unit/version.test.ts): una etiqueta vieja en un
|
||||
// manifest instala la versión anterior mientras el CHANGELOG habla de
|
||||
// la nueva.
|
||||
expect(texto).toContain(IMAGEN);
|
||||
expect(texto).not.toMatch(/vocero-crm:latest/);
|
||||
});
|
||||
|
||||
it("apunta al healthcheck, al volumen de /data y al puerto de la imagen", () => {
|
||||
expect(texto).toContain("/api/health");
|
||||
expect(texto).toContain("/data");
|
||||
expect(texto).toMatch(/\b3000\b/);
|
||||
});
|
||||
|
||||
it("no define MEDIA_DIR: la imagen ya trae /data/media dentro del volumen", () => {
|
||||
// Definirla en la plataforma es exactamente cómo se mandan los adjuntos
|
||||
// fuera del volumen (INSTALL-IA.md, «Diagnóstico rápido»).
|
||||
expect(sinComentarios(texto)).not.toMatch(/MEDIA_DIR\s*[=:]/);
|
||||
});
|
||||
|
||||
it("genera cada secreto con el comando que pide .env.example", () => {
|
||||
// ENCRYPTION_KEY son 32 bytes en base64; el verify token va en la URL del
|
||||
// webhook, así que es hex (sin `/`). O lo genera la plataforma con ese
|
||||
// mismo formato, o el comando documentado lo hace.
|
||||
expect(texto).toMatch(/ENCRYPTION_KEY[\s\S]{0,200}(openssl rand -base64 32|generateValue: true)/);
|
||||
expect(texto).toMatch(/META_WEBHOOK_VERIFY_TOKEN[\s\S]{0,300}openssl rand -hex 32/);
|
||||
});
|
||||
});
|
||||
|
||||
describe("render.yaml: el Blueprint declara todo lo que Render deja declarar", () => {
|
||||
const activo = sinComentarios(render);
|
||||
|
||||
it("servicio web desde la imagen, con healthcheck y disco en /data", () => {
|
||||
expect(activo).toMatch(/^\s*runtime: image$/m);
|
||||
expect(activo).toMatch(new RegExp(`^\\s*url: ${IMAGEN.replace(/[.]/g, "\\.")}$`, "m"));
|
||||
expect(activo).toMatch(/^\s*healthCheckPath: \/api\/health$/m);
|
||||
expect(activo).toMatch(/^\s*mountPath: \/data$/m);
|
||||
});
|
||||
|
||||
it("fija PORT=3000: Render mete PORT=10000 por defecto y la imagen escucha en 3000", () => {
|
||||
expect(bloqueRender("PORT")).toMatch(/value: "3000"/);
|
||||
});
|
||||
|
||||
it("cada variable obligatoria es una entrada real de envVars", () => {
|
||||
for (const clave of OBLIGATORIAS) {
|
||||
expect(activo, clave).toMatch(new RegExp(`^\\s*- key: ${clave}$`, "m"));
|
||||
}
|
||||
});
|
||||
|
||||
it("DATABASE_URL viene de la base del Blueprint y APP_BASE_URL de la URL del servicio", () => {
|
||||
expect(bloqueRender("DATABASE_URL")).toMatch(/fromDatabase:[\s\S]*name: vocero-db[\s\S]*property: connectionString/);
|
||||
expect(activo).toMatch(/^databases:\n\s*- name: vocero-db$/m);
|
||||
expect(bloqueRender("APP_BASE_URL")).toMatch(/fromService:[\s\S]*envVarKey: RENDER_EXTERNAL_URL/);
|
||||
});
|
||||
|
||||
it("los secretos los genera Render (256 bits base64 = los 32 bytes de ENCRYPTION_KEY)", () => {
|
||||
expect(bloqueRender("BETTER_AUTH_SECRET")).toMatch(/generateValue: true/);
|
||||
expect(bloqueRender("ENCRYPTION_KEY")).toMatch(/generateValue: true/);
|
||||
});
|
||||
|
||||
it("el verify token NO se genera: en base64 llevaría `/` y es un segmento de la URL del webhook", () => {
|
||||
const bloque = bloqueRender("META_WEBHOOK_VERIFY_TOKEN");
|
||||
expect(bloque).toMatch(/sync: false/);
|
||||
expect(sinComentarios(bloque)).not.toMatch(/generateValue/);
|
||||
});
|
||||
|
||||
it("la base no queda abierta a cualquier IP", () => {
|
||||
expect(activo).toMatch(/^\s*ipAllowList: \[\]$/m);
|
||||
});
|
||||
});
|
||||
|
||||
describe("fly.toml: lo que cabe en el archivo y los comandos de lo que no", () => {
|
||||
const activo = sinComentarios(fly);
|
||||
|
||||
it("imagen publicada, volumen en /data, puerto 3000 y healthcheck", () => {
|
||||
expect(activo).toMatch(new RegExp(`^\\s*image = "${IMAGEN.replace(/[.]/g, "\\.")}"$`, "m"));
|
||||
expect(activo).toMatch(/^\s*destination = "\/data"$/m);
|
||||
expect(activo).toMatch(/^\s*internal_port = 3000$/m);
|
||||
expect(activo).toMatch(/^\s*path = "\/api\/health"$/m);
|
||||
});
|
||||
|
||||
it("APP_BASE_URL va en [env] y coincide con el nombre de la app", () => {
|
||||
const app = activo.match(/^app = "([^"]+)"$/m)?.[1];
|
||||
expect(app).toBeTruthy();
|
||||
expect(activo).toMatch(new RegExp(`^\\s*APP_BASE_URL = "https://${app}\\.fly\\.dev"$`, "m"));
|
||||
});
|
||||
|
||||
it("la máquina no se apaga sola: el agente, el Laboratorio y el SSE corren dentro del proceso", () => {
|
||||
expect(activo).toMatch(/^\s*auto_stop_machines = "off"$/m);
|
||||
});
|
||||
|
||||
it("los secretos van por `fly secrets set` y DATABASE_URL por `attach`", () => {
|
||||
for (const clave of ["BETTER_AUTH_SECRET", "ENCRYPTION_KEY", "META_WEBHOOK_VERIFY_TOKEN"]) {
|
||||
expect(fly).toMatch(new RegExp(`fly secrets set[\\s\\S]{0,300}${clave}=`));
|
||||
// Y no en [env], que es visible en el fly.toml del repo.
|
||||
expect(activo, clave).not.toMatch(new RegExp(`^\\s*${clave} =`, "m"));
|
||||
}
|
||||
expect(fly).toMatch(/fly postgres attach vocero-db --app vocero-crm/);
|
||||
expect(fly).toMatch(/fly volumes create vocero_data --app vocero-crm/);
|
||||
});
|
||||
});
|
||||
|
||||
describe("railway.toml: solo build, healthcheck y reinicio; el resto, con la CLI", () => {
|
||||
const activo = sinComentarios(railway);
|
||||
|
||||
it("construye desde el Dockerfile con healthcheck y reinicio ante fallos", () => {
|
||||
expect(activo).toMatch(/^\s*builder = "DOCKERFILE"$/m);
|
||||
expect(activo).toMatch(/^\s*healthcheckPath = "\/api\/health"$/m);
|
||||
expect(activo).toMatch(/^\s*restartPolicyType = "ON_FAILURE"$/m);
|
||||
});
|
||||
|
||||
it("documenta la base, el volumen en /data, el dominio al puerto 3000 y cada variable", () => {
|
||||
expect(railway).toMatch(/railway add --database postgres/);
|
||||
expect(railway).toMatch(/railway volume add --mount-path \/data/);
|
||||
expect(railway).toMatch(/railway domain --port 3000/);
|
||||
for (const clave of OBLIGATORIAS) {
|
||||
expect(railway, clave).toMatch(new RegExp(`railway variable set[\\s\\S]{0,600}${clave}=`));
|
||||
}
|
||||
expect(railway).toMatch(/DATABASE_URL=\$\{\{Postgres\.DATABASE_URL\}\}/);
|
||||
expect(railway).toMatch(/APP_BASE_URL=https:\/\/\$\{\{RAILWAY_PUBLIC_DOMAIN\}\}/);
|
||||
});
|
||||
});
|
||||
|
||||
describe("la documentación lleva a los manifests", () => {
|
||||
it("el README tiene la sección y enlaza los tres; INSTALL-IA.md apunta a ella", () => {
|
||||
const readme = leer("README.md");
|
||||
expect(readme).toMatch(/^### Otras plataformas/m);
|
||||
for (const archivo of ["render.yaml", "fly.toml", "railway.toml"]) {
|
||||
expect(readme).toContain(`](${archivo})`);
|
||||
}
|
||||
expect(leer("INSTALL-IA.md")).toMatch(/Otras plataformas/);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,417 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
/**
|
||||
* MCP de Vocero: el protocolo y la traducción herramienta → API v1.
|
||||
*
|
||||
* Los handlers de la API se sustituyen por espías: aquí importa qué petición
|
||||
* reciben (ruta, query, cuerpo, la MISMA llave). Que esas rutas no crucen
|
||||
* organizaciones ya lo cubren `api-v1.test.ts` y el arnés E2E
|
||||
* `scripts/e2e-api-mcp.mjs`, que llama al MCP contra la app viva.
|
||||
*/
|
||||
|
||||
const st = vi.hoisted(() => ({
|
||||
auth: { status: "ok" as "ok" | 401 | 403, scopes: ["read"] as string[] },
|
||||
limite: true,
|
||||
pedidas: [] as { ruta: string; method: string; url: URL; auth: string | null; body: unknown; params: unknown }[],
|
||||
respuesta: null as null | Response,
|
||||
}));
|
||||
|
||||
vi.mock("@/server/api-v1/handler", () => ({
|
||||
LIMITE_POR_MINUTO: 120,
|
||||
limitado: () => Response.json({ error: { code: "rate_limited" } }, { status: 429 }),
|
||||
autenticarLlave: async () =>
|
||||
st.auth.status === "ok"
|
||||
? { ctx: {}, llave: { id: "ak_1", scopes: st.auth.scopes } }
|
||||
: Response.json({ error: { code: st.auth.status === 401 ? "invalid_key" : "insufficient_scope" } }, { status: st.auth.status }),
|
||||
}));
|
||||
vi.mock("@/lib/rate-limit", () => ({ checkRateLimit: () => ({ allowed: st.limite, remaining: 1 }) }));
|
||||
process.env.APP_BASE_URL = "https://crm.negocio.test";
|
||||
|
||||
function espia(ruta: string) {
|
||||
return async (req: Request, ctx: { params: Promise<unknown> }) => {
|
||||
const texto = await req.text();
|
||||
st.pedidas.push({
|
||||
ruta,
|
||||
method: req.method,
|
||||
url: new URL(req.url),
|
||||
auth: req.headers.get("authorization"),
|
||||
body: texto ? JSON.parse(texto) : undefined,
|
||||
params: await ctx.params,
|
||||
});
|
||||
return st.respuesta ?? Response.json({ ok: ruta });
|
||||
};
|
||||
}
|
||||
vi.mock("@/app/api/v1/me/route", () => ({ GET: espia("me") }));
|
||||
vi.mock("@/app/api/v1/contacts/route", () => ({ GET: espia("contacts"), POST: espia("contacts") }));
|
||||
vi.mock("@/app/api/v1/contacts/[id]/route", () => ({ GET: espia("contact"), PATCH: espia("contact") }));
|
||||
vi.mock("@/app/api/v1/conversations/route", () => ({ GET: espia("conversations") }));
|
||||
vi.mock("@/app/api/v1/conversations/[id]/messages/route", () => ({ GET: espia("messages"), POST: espia("messages") }));
|
||||
vi.mock("@/app/api/v1/conversations/[id]/notes/route", () => ({ GET: espia("notes"), POST: espia("notes") }));
|
||||
vi.mock("@/app/api/v1/leads/[id]/route", () => ({ PATCH: espia("lead") }));
|
||||
vi.mock("@/app/api/v1/pipeline/stages/route", () => ({ GET: espia("stages"), POST: espia("stages") }));
|
||||
vi.mock("@/app/api/v1/bookings/route", () => ({ GET: espia("bookings"), POST: espia("bookings") }));
|
||||
// Las rutas de configuración.
|
||||
vi.mock("@/app/api/v1/agent/profile/route", () => ({ GET: espia("profile"), PUT: espia("profile") }));
|
||||
vi.mock("@/app/api/v1/agent/preset/route", () => ({ POST: espia("preset") }));
|
||||
vi.mock("@/app/api/v1/agent/readiness/route", () => ({ GET: espia("readiness") }));
|
||||
vi.mock("@/app/api/v1/agent/simulate/route", () => ({ POST: espia("simulate") }));
|
||||
vi.mock("@/app/api/v1/knowledge/route", () => ({ GET: espia("knowledge"), POST: espia("knowledge") }));
|
||||
vi.mock("@/app/api/v1/knowledge/[id]/route", () => ({ PATCH: espia("knowledge-entry"), DELETE: espia("knowledge-entry") }));
|
||||
vi.mock("@/app/api/v1/knowledge/size/route", () => ({ GET: espia("knowledge-size") }));
|
||||
vi.mock("@/app/api/v1/calendar/settings/route", () => ({ GET: espia("calendar"), PUT: espia("calendar") }));
|
||||
vi.mock("@/app/api/v1/calendar/availability/route", () => ({ GET: espia("availability") }));
|
||||
vi.mock("@/app/api/v1/pipeline/stages/[id]/route", () => ({ PATCH: espia("stage"), DELETE: espia("stage") }));
|
||||
vi.mock("@/app/api/v1/quick-replies/route", () => ({ GET: espia("quick-replies"), POST: espia("quick-replies") }));
|
||||
vi.mock("@/app/api/v1/quick-replies/[id]/route", () => ({ PATCH: espia("quick-reply"), DELETE: espia("quick-reply") }));
|
||||
vi.mock("@/app/api/v1/brain/route", () => ({ GET: espia("brain") }));
|
||||
vi.mock("@/app/api/v1/ai/route", () => ({ GET: espia("ai"), PUT: espia("ai") }));
|
||||
|
||||
import { responderMcp, VERSIONES } from "@/server/mcp/servidor";
|
||||
import { HERRAMIENTAS } from "@/server/mcp/herramientas";
|
||||
import { GUIA_CONFIGURAR } from "@/server/mcp/guia";
|
||||
import { GUIA_PROBAR } from "@/server/mcp/guia-probar";
|
||||
import { readFileSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
|
||||
const LLAVE = "Bearer vk_" + "a".repeat(40);
|
||||
let n = 0;
|
||||
function rpc(method: string, params?: unknown, extra: Record<string, unknown> = {}) {
|
||||
return responderMcp(
|
||||
new Request("https://crm.negocio.test/api/v1/mcp", {
|
||||
method: "POST",
|
||||
headers: { authorization: LLAVE, "content-type": "application/json", accept: "application/json, text/event-stream" },
|
||||
body: JSON.stringify({ jsonrpc: "2.0", id: ++n, method, params, ...extra }),
|
||||
})
|
||||
);
|
||||
}
|
||||
async function llamar(name: string, args: Record<string, unknown> = {}) {
|
||||
const res = await rpc("tools/call", { name, arguments: args });
|
||||
return (await res.json()) as { result?: { content: { text: string }[]; isError?: boolean; structuredContent?: unknown }; error?: { code: number } };
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
st.auth = { status: "ok", scopes: ["read"] };
|
||||
st.limite = true;
|
||||
st.pedidas = [];
|
||||
st.respuesta = null;
|
||||
});
|
||||
|
||||
describe("protocolo", () => {
|
||||
it("initialize negocia la versión y anuncia solo herramientas", async () => {
|
||||
const res = await rpc("initialize", { protocolVersion: "2025-06-18", capabilities: {}, clientInfo: { name: "t", version: "1" } });
|
||||
const body = await res.json();
|
||||
expect(body.result.protocolVersion).toBe("2025-06-18");
|
||||
expect(body.result.capabilities).toEqual({ tools: { listChanged: false }, prompts: { listChanged: false } });
|
||||
expect(body.result.serverInfo.name).toBe("vocero-crm");
|
||||
|
||||
const rara = await (await rpc("initialize", { protocolVersion: "1999-01-01" })).json();
|
||||
expect(rara.result.protocolVersion).toBe(VERSIONES[0]);
|
||||
});
|
||||
|
||||
it("una notificación se acepta con 202 y sin cuerpo", async () => {
|
||||
const res = await responderMcp(
|
||||
new Request("https://crm.negocio.test/api/v1/mcp", {
|
||||
method: "POST",
|
||||
headers: { authorization: LLAVE },
|
||||
body: JSON.stringify({ jsonrpc: "2.0", method: "notifications/initialized" }),
|
||||
})
|
||||
);
|
||||
expect(res.status).toBe(202);
|
||||
expect(await res.text()).toBe("");
|
||||
});
|
||||
|
||||
it("sin llave válida: 401 con WWW-Authenticate, sin tocar la API", async () => {
|
||||
st.auth.status = 401;
|
||||
const res = await rpc("tools/list");
|
||||
expect(res.status).toBe(401);
|
||||
expect(res.headers.get("WWW-Authenticate")).toMatch(/^Bearer/);
|
||||
// El 401 dice dónde está el OAuth: la propia instancia (APP_BASE_URL).
|
||||
expect(res.headers.get("WWW-Authenticate")).toContain(
|
||||
'resource_metadata="https://crm.negocio.test/.well-known/oauth-protected-resource/api/v1/mcp"'
|
||||
);
|
||||
st.auth.status = 403;
|
||||
expect((await rpc("tools/list")).status).toBe(403);
|
||||
expect(st.pedidas).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("método desconocido, JSON roto y herramienta inexistente son errores JSON-RPC", async () => {
|
||||
expect((await (await rpc("resources/list")).json()).error.code).toBe(-32601);
|
||||
const roto = await responderMcp(new Request("https://x/api/v1/mcp", { method: "POST", headers: { authorization: LLAVE }, body: "{" }));
|
||||
expect(roto.status).toBe(400);
|
||||
expect((await llamar("borrar_todo")).error?.code).toBe(-32602);
|
||||
});
|
||||
|
||||
it("initialize y tools/list cuentan contra el límite de la llave", async () => {
|
||||
st.limite = false;
|
||||
expect((await rpc("tools/list")).status).toBe(429);
|
||||
});
|
||||
});
|
||||
|
||||
describe("tools/list según los permisos de la llave", () => {
|
||||
const nombres = async () => ((await (await rpc("tools/list")).json()).result.tools as { name: string }[]).map((t) => t.name);
|
||||
|
||||
it("una llave de lectura solo ve herramientas de lectura", async () => {
|
||||
const vistas = await nombres();
|
||||
expect(vistas).toContain("search_contacts");
|
||||
expect(vistas).not.toContain("move_lead");
|
||||
expect(vistas).not.toContain("send_message");
|
||||
expect(vistas.length).toBe(HERRAMIENTAS.filter((t) => t.scope === "read").length);
|
||||
});
|
||||
|
||||
it("operate suma escribir; mandar al cliente no existe en el MCP ni con send", async () => {
|
||||
st.auth.scopes = ["read", "operate"];
|
||||
expect(await nombres()).toEqual(expect.arrayContaining(["move_lead", "book_appointment", "add_note"]));
|
||||
st.auth.scopes = ["read", "operate", "send", "configure"];
|
||||
const todas = await nombres();
|
||||
expect(todas).toHaveLength(HERRAMIENTAS.length);
|
||||
expect(todas).not.toContain("send_message");
|
||||
expect(HERRAMIENTAS.some((t) => (t.scope as string) === "send")).toBe(false);
|
||||
});
|
||||
|
||||
it("send_message no existe: error de herramienta desconocida, sin tocar la API", async () => {
|
||||
st.auth.scopes = ["read", "operate", "send"];
|
||||
expect((await llamar("send_message", { conversationId: "cv_1", text: "hola" })).error?.code).toBe(-32602);
|
||||
expect(st.pedidas).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("cada herramienta trae esquema de objeto y anotaciones coherentes", () => {
|
||||
for (const t of HERRAMIENTAS) {
|
||||
expect(t.inputSchema.type).toBe("object");
|
||||
// Leer nunca escribe; las de configuración pueden ser de lectura (get_*) con permiso configure.
|
||||
if (t.scope === "read") expect(t.annotations.readOnlyHint).toBe(true);
|
||||
if (t.scope === "operate") expect(t.annotations.readOnlyHint).toBe(false);
|
||||
if (t.annotations.readOnlyHint) expect(t.name).toMatch(/^(whoami|get_|list_|search_|read_|check_)/);
|
||||
}
|
||||
});
|
||||
|
||||
it("llamar a una herramienta sin permiso no llega a la API", async () => {
|
||||
const r = await llamar("move_lead", { leadId: "ld_1", stageId: "st_2" });
|
||||
expect(r.result?.isError).toBe(true);
|
||||
expect(r.result?.content[0]?.text).toContain("insufficient_scope");
|
||||
expect(st.pedidas).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe("tools/call pasa por la API v1 con la misma llave", () => {
|
||||
it("search_contacts arma la query y recorta la lista", async () => {
|
||||
st.respuesta = Response.json({ contacts: Array.from({ length: 80 }, (_, i) => ({ id: `ct_${i}` })) });
|
||||
const r = await llamar("search_contacts", { query: " Ana ", stage: "Nuevo", includeArchived: true, limit: 10 });
|
||||
const p = st.pedidas[0]!;
|
||||
expect(p.ruta).toBe("contacts");
|
||||
expect(p.auth).toBe(LLAVE);
|
||||
expect(p.url.pathname).toBe("/api/v1/contacts");
|
||||
expect(Object.fromEntries(p.url.searchParams)).toEqual({ q: "Ana", stage: "Nuevo", archived: "true" });
|
||||
const salida = r.result?.structuredContent as { contacts: unknown[]; total: number; truncated: boolean };
|
||||
expect(salida.contacts).toHaveLength(10);
|
||||
expect(salida).toMatchObject({ total: 80, truncated: true });
|
||||
});
|
||||
|
||||
it("read_conversation se queda con los mensajes más recientes", async () => {
|
||||
st.respuesta = Response.json({ messages: [1, 2, 3, 4, 5].map((i) => ({ id: `m${i}` })) });
|
||||
const r = await llamar("read_conversation", { conversationId: "cv_9", limit: 2 });
|
||||
expect(st.pedidas[0]!.params).toEqual({ id: "cv_9" });
|
||||
expect(st.pedidas[0]!.url.pathname).toBe("/api/v1/conversations/cv_9/messages");
|
||||
expect((r.result?.structuredContent as { messages: { id: string }[] }).messages.map((m) => m.id)).toEqual(["m4", "m5"]);
|
||||
});
|
||||
|
||||
it("list_conversations filtra por contacto", async () => {
|
||||
st.respuesta = Response.json({ conversations: [{ id: "cv_1", contact: { id: "ct_a" } }, { id: "cv_2", contact: { id: "ct_b" } }] });
|
||||
const r = await llamar("list_conversations", { contactId: "ct_b" });
|
||||
expect((r.result?.structuredContent as { conversations: { id: string }[] }).conversations.map((c) => c.id)).toEqual(["cv_2"]);
|
||||
});
|
||||
|
||||
it("move_lead y update_contact solo mandan lo que el modelo puso (null incluido)", async () => {
|
||||
st.auth.scopes = ["read", "operate"];
|
||||
await llamar("move_lead", { leadId: "ld_1", stageId: "st_2", priority: null });
|
||||
expect(st.pedidas[0]).toMatchObject({ ruta: "lead", method: "PATCH", params: { id: "ld_1" }, body: { stageId: "st_2", priority: null } });
|
||||
await llamar("update_contact", { contactId: "ct_1", aiPaused: true });
|
||||
expect(st.pedidas[1]!.body).toEqual({ aiPaused: true });
|
||||
});
|
||||
|
||||
it("book_appointment y block_time eligen el tipo de reserva", async () => {
|
||||
st.auth.scopes = ["read", "operate"];
|
||||
await llamar("book_appointment", { contactId: "ct_1", startUtc: "2026-11-10T17:00:00Z" });
|
||||
await llamar("block_time", { startUtc: "2026-11-10T18:00:00Z", durationMinutes: 30 });
|
||||
expect(st.pedidas.map((p) => (p.body as { kind: string }).kind)).toEqual(["session", "block"]);
|
||||
});
|
||||
|
||||
it("add_note traduce text → texto", async () => {
|
||||
st.auth.scopes = ["read", "operate"];
|
||||
await llamar("add_note", { conversationId: "cv_1", text: "llamar mañana" });
|
||||
expect(st.pedidas[0]!.body).toEqual({ texto: "llamar mañana" });
|
||||
});
|
||||
|
||||
it("un error de la API llega como resultado con isError, no como fallo del protocolo", async () => {
|
||||
st.respuesta = Response.json({ error: { code: "not_found", message: "Contacto no encontrado" } }, { status: 404 });
|
||||
const r = await llamar("get_contact", { contactId: "ct_ajeno" });
|
||||
expect(r.error).toBeUndefined();
|
||||
expect(r.result?.isError).toBe(true);
|
||||
expect(r.result?.content[0]?.text).toContain("not_found");
|
||||
});
|
||||
|
||||
it("un argumento obligatorio vacío se rechaza antes de llamar", async () => {
|
||||
const r = await llamar("get_contact", { contactId: "" });
|
||||
expect(r.result?.isError).toBe(true);
|
||||
expect(st.pedidas).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe("configurar el agente por el MCP", () => {
|
||||
const nombres = async () =>
|
||||
((await (await rpc("tools/list")).json()).result.tools as { name: string }[]).map((t) => t.name);
|
||||
|
||||
it("sin configure no se ve ninguna herramienta de configuración", async () => {
|
||||
st.auth.scopes = ["read", "operate", "send"];
|
||||
const ns = await nombres();
|
||||
for (const t of HERRAMIENTAS.filter((x) => x.scope === "configure")) expect(ns).not.toContain(t.name);
|
||||
expect(ns).toContain("move_lead");
|
||||
});
|
||||
|
||||
it("con configure se ven primero (después de whoami) y antes que las operativas", async () => {
|
||||
st.auth.scopes = ["read", "configure"];
|
||||
const ns = await nombres();
|
||||
expect(ns[0]).toBe("whoami");
|
||||
expect(ns[1]).toBe("get_setup_status");
|
||||
expect(ns).toContain("update_agent_config");
|
||||
expect(ns).toContain("save_ai_key");
|
||||
expect(ns).not.toContain("move_lead"); // configurar no arrastra operar
|
||||
expect(ns.indexOf("save_ai_key")).toBeLessThan(ns.indexOf("search_contacts"));
|
||||
});
|
||||
|
||||
it("sin configure, llamarla no llega a la API", async () => {
|
||||
st.auth.scopes = ["read", "operate"];
|
||||
const r = await llamar("update_agent_config", { instructions: "x" });
|
||||
expect(r.result?.isError).toBe(true);
|
||||
expect(st.pedidas).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("update_agent_config manda solo lo que puso el modelo (null incluido)", async () => {
|
||||
st.auth.scopes = ["read", "configure"];
|
||||
await llamar("update_agent_config", { instructions: "Agenda valoraciones", greeting: null, tools: ["escalar"], inventado: 1 });
|
||||
expect(st.pedidas[0]).toMatchObject({ ruta: "profile", method: "PUT", auth: LLAVE });
|
||||
expect(st.pedidas[0]!.body).toEqual({ instructions: "Agenda valoraciones", greeting: null, tools: ["escalar"] });
|
||||
});
|
||||
|
||||
it("load_role manda el rol a la ruta del preset", async () => {
|
||||
st.auth.scopes = ["read", "configure"];
|
||||
await llamar("load_role", { role: "calificador" });
|
||||
expect(st.pedidas[0]).toMatchObject({ ruta: "preset", method: "POST", body: { role: "calificador" } });
|
||||
});
|
||||
|
||||
it("get_setup_status resume: pendientes con enlaces, sin la huella de activación", async () => {
|
||||
st.auth.scopes = ["read", "configure"];
|
||||
st.respuesta = Response.json({
|
||||
enabled: false,
|
||||
steps: [{ key: "ai", label: "IA", status: "pending", nextAction: "x", href: "/settings/ai" }],
|
||||
pendientes: [{ key: "ai", enlaces: [{ titulo: "Crear", url: "https://openrouter.ai/settings/keys" }] }],
|
||||
otroCampo: "abc",
|
||||
});
|
||||
const r = await llamar("get_setup_status");
|
||||
const s = r.result?.structuredContent as Record<string, unknown>;
|
||||
expect(s.listoParaContestar).toBe(false);
|
||||
expect(JSON.stringify(s.pendientes)).toContain("https://openrouter.ai/settings/keys");
|
||||
expect(JSON.stringify(s)).not.toContain("abc");
|
||||
});
|
||||
|
||||
it("borrar conocimiento va por la ruta; la etapa mueve sus tarjetas por la query", async () => {
|
||||
st.auth.scopes = ["read", "configure"];
|
||||
await llamar("delete_knowledge", { entryId: "kb_1" });
|
||||
expect(st.pedidas[0]).toMatchObject({ ruta: "knowledge-entry", method: "DELETE", params: { id: "kb_1" } });
|
||||
await llamar("delete_pipeline_stage", { stageId: "stage_1", moveToStageId: "stage_2" });
|
||||
expect(st.pedidas[1]!.url.searchParams.get("moveTo")).toBe("stage_2");
|
||||
});
|
||||
|
||||
it("el cerebro solo se lee: se conecta en el despliegue", async () => {
|
||||
st.auth.scopes = ["read", "configure"];
|
||||
await llamar("get_brain");
|
||||
expect(st.pedidas[0]).toMatchObject({ ruta: "brain", method: "GET" });
|
||||
expect(HERRAMIENTAS.some((t) => t.name === "connect_nea")).toBe(false);
|
||||
});
|
||||
|
||||
it("save_ai_key guarda proveedor, modelo y llave, y nada más", async () => {
|
||||
st.auth.scopes = ["read", "configure"];
|
||||
await llamar("save_ai_key", { provider: "openrouter", model: "m/x", token: "sk-or-123456789", sobra: 1 });
|
||||
expect(st.pedidas[0]).toMatchObject({ ruta: "ai", method: "PUT", body: { provider: "openrouter", model: "m/x", token: "sk-or-123456789" } });
|
||||
});
|
||||
|
||||
it("add_knowledge manda solo los campos de su tipo", async () => {
|
||||
st.auth.scopes = ["read", "configure"];
|
||||
await llamar("add_knowledge", { kind: "block", content: "Servicios y precios", question: "sobra" });
|
||||
expect(st.pedidas[0]!.body).toEqual({ kind: "block", content: "Servicios y precios" });
|
||||
});
|
||||
|
||||
it("la guía se ofrece como prompt, y el plugin trae el mismo texto como skill", async () => {
|
||||
const lista = await (await rpc("prompts/list")).json();
|
||||
expect(lista.result.prompts.map((p: { name: string }) => p.name)).toEqual(["configurar_vocero", "probar_agente"]);
|
||||
expect(JSON.stringify(lista.result.prompts)).not.toContain("Reglas que no se rompen"); // la lista no trae el texto
|
||||
const p = await (await rpc("prompts/get", { name: "configurar_vocero" })).json();
|
||||
expect(p.result.messages[0].content.text).toBe(GUIA_CONFIGURAR);
|
||||
const desconocido = await (await rpc("prompts/get", { name: "otro" })).json();
|
||||
expect(desconocido.error.code).toBe(-32602);
|
||||
const skill = readFileSync(join(process.cwd(), "plugin/vocero/skills/configurar-vocero/SKILL.md"), "utf8").replace(/\r\n/g, "\n");
|
||||
expect(skill.replace(/^---\n[\s\S]*?\n---\n\n/, "")).toBe(GUIA_CONFIGURAR);
|
||||
});
|
||||
|
||||
it("cada herramienta que nombran las guías existe de verdad", () => {
|
||||
const existentes = new Set(HERRAMIENTAS.map((t) => t.name));
|
||||
// Lo que va entre comillas invertidas y no es herramienta: códigos de
|
||||
// error, tipos de acción de la simulación y los nombres de los prompts.
|
||||
const noSonHerramientas = new Set(["configurar_vocero", "probar_agente", "sin_cerebro"]);
|
||||
for (const guia of [GUIA_CONFIGURAR, GUIA_PROBAR]) {
|
||||
const nombradas = [...guia.matchAll(/`([a-z]+_[a-z_]+)`/g)].map((m) => m[1]!);
|
||||
expect(nombradas.filter((n) => !existentes.has(n) && !noSonHerramientas.has(n))).toEqual([]);
|
||||
}
|
||||
expect(GUIA_CONFIGURAR).toContain("`simulate_conversation`");
|
||||
});
|
||||
});
|
||||
|
||||
describe("probar el agente sin WhatsApp", () => {
|
||||
it("simulate_conversation es de configurar y manda solo los turnos, el historial y el nombre", async () => {
|
||||
st.auth.scopes = ["read", "operate"];
|
||||
const sin = await llamar("simulate_conversation", { turns: ["hola"] });
|
||||
expect(sin.result?.isError).toBe(true);
|
||||
expect(st.pedidas).toHaveLength(0);
|
||||
|
||||
st.auth.scopes = ["read", "configure"];
|
||||
await llamar("simulate_conversation", {
|
||||
turns: ["hola", "sí, el lunes"],
|
||||
history: [{ role: "customer", text: "antes" }],
|
||||
contactName: "Ana",
|
||||
inventado: true,
|
||||
});
|
||||
expect(st.pedidas[0]).toMatchObject({ ruta: "simulate", method: "POST", auth: LLAVE });
|
||||
expect(st.pedidas[0]!.body).toEqual({ turns: ["hola", "sí, el lunes"], history: [{ role: "customer", text: "antes" }], contactName: "Ana" });
|
||||
});
|
||||
|
||||
it("no se anuncia como de solo lectura: gasta saldo del negocio", () => {
|
||||
const t = HERRAMIENTAS.find((x) => x.name === "simulate_conversation")!;
|
||||
expect(t.scope).toBe("configure");
|
||||
expect(t.annotations.readOnlyHint).toBe(false);
|
||||
expect(t.annotations.openWorldHint).toBe(true);
|
||||
expect(t.description).toMatch(/gasta saldo/i);
|
||||
// Más turnos por llamada pasan del minuto y el cliente MCP corta la llamada.
|
||||
expect((t.inputSchema.properties.turns as { maxItems: number }).maxItems).toBe(3);
|
||||
});
|
||||
|
||||
it("más de 3 turnos se rechaza antes de llamar a la API", async () => {
|
||||
st.auth.scopes = ["read", "configure"];
|
||||
const r = await llamar("simulate_conversation", { turns: ["a", "b", "c", "d"] });
|
||||
expect(r.result?.isError).toBe(true);
|
||||
expect(r.result?.content[0]?.text).toContain("too_many_items");
|
||||
expect(st.pedidas).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("la guía para probar es un prompt y la misma skill del plugin, con su ventana", async () => {
|
||||
const p = await (await rpc("prompts/get", { name: "probar_agente" })).json();
|
||||
expect(p.result.messages[0].content.text).toBe(GUIA_PROBAR);
|
||||
const skill = readFileSync(join(process.cwd(), "plugin/vocero/skills/probar-agente/SKILL.md"), "utf8").replace(/\r\n/g, "\n");
|
||||
expect(skill.replace(/^---\n[\s\S]*?\n---\n\n/, "")).toBe(GUIA_PROBAR);
|
||||
const ventana = readFileSync(join(process.cwd(), "plugin/vocero/skills/probar-agente/ventana-chat.html"), "utf8");
|
||||
expect(ventana).toContain('"simulate_conversation"');
|
||||
expect(ventana).toContain("__CONECTOR__");
|
||||
// Los casos difíciles van siempre.
|
||||
for (const caso of ["Desconfianza", "Baja", "no está en el conocimiento", "hablar con una persona", "Otro bot"]) {
|
||||
expect(GUIA_PROBAR).toContain(caso);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,69 @@
|
||||
import { mkdtemp, readdir, rm, stat, writeFile } from "node:fs/promises";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi, type MockInstance } from "vitest";
|
||||
|
||||
/**
|
||||
* 008 — Si MEDIA_DIR no es escribible, el arranque lo dice con claridad (y qué
|
||||
* hacer) en vez de dejar que el primer síntoma sea un 500 al subir el logo o
|
||||
* un adjunto perdido. Y jamás tumba el arranque.
|
||||
*/
|
||||
|
||||
const { getEnv } = vi.hoisted(() => ({ getEnv: vi.fn() }));
|
||||
vi.mock("@/lib/env", () => ({ getEnv }));
|
||||
vi.mock("@/lib/db", () => ({ getDb: vi.fn(), schema: {} }));
|
||||
|
||||
import { checkMediaDir } from "@/instrumentation-node";
|
||||
import { resetMediaDirCache } from "@/server/media-dir";
|
||||
|
||||
let tmp: string;
|
||||
let error: MockInstance<typeof console.error>;
|
||||
|
||||
beforeEach(async () => {
|
||||
tmp = await mkdtemp(path.join(os.tmpdir(), "vocero-media-"));
|
||||
error = vi.spyOn(console, "error").mockImplementation(() => {});
|
||||
// El sondeo se cachea (#82): cada caso arranca sin resultado anterior.
|
||||
resetMediaDirCache();
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
error.mockRestore();
|
||||
await rm(tmp, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
describe("checkMediaDir (arranque)", () => {
|
||||
it("directorio escribible: lo crea si falta, no avisa y no deja rastro", async () => {
|
||||
const dir = path.join(tmp, "media");
|
||||
getEnv.mockReturnValue({ MEDIA_DIR: dir });
|
||||
|
||||
await checkMediaDir();
|
||||
|
||||
expect(error).not.toHaveBeenCalled();
|
||||
expect((await stat(dir)).isDirectory()).toBe(true);
|
||||
expect(await readdir(dir)).toEqual([]); // el archivo de prueba se borró
|
||||
});
|
||||
|
||||
it("no escribible: avisa qué pasa y qué hacer, sin lanzar", async () => {
|
||||
// Un archivo donde debería ir un directorio: mkdir falla en todo SO.
|
||||
const archivo = path.join(tmp, "no-soy-directorio");
|
||||
await writeFile(archivo, "x");
|
||||
getEnv.mockReturnValue({ MEDIA_DIR: path.join(archivo, "media") });
|
||||
|
||||
await expect(checkMediaDir()).resolves.toBeUndefined();
|
||||
|
||||
expect(error).toHaveBeenCalledTimes(1);
|
||||
const mensaje = String(error.mock.calls[0]?.[0]);
|
||||
expect(mensaje).toMatch(/^\[boot\] MEDIA_DIR=.+ no es escribible/);
|
||||
expect(mensaje).toMatch(/adjuntos/);
|
||||
expect(mensaje).toMatch(/volumen persistente en \/data/);
|
||||
});
|
||||
|
||||
it("entorno inválido: no es su problema, no lanza ni duplica el error", async () => {
|
||||
getEnv.mockImplementation(() => {
|
||||
throw new Error("Variables de entorno inválidas");
|
||||
});
|
||||
|
||||
await expect(checkMediaDir()).resolves.toBeUndefined();
|
||||
expect(error).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,171 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
baseMime,
|
||||
contentDisposition,
|
||||
contentTypeFor,
|
||||
isForbiddenUploadMime,
|
||||
isPreviewable,
|
||||
mediaResponseHeaders,
|
||||
} from "@/server/whatsapp/media-headers";
|
||||
|
||||
/**
|
||||
* #78 — Un adjunto es contenido ajeno servido desde el origen del CRM. Estas
|
||||
* pruebas fijan QUÉ se previsualiza y con qué cabeceras se sirve TODO.
|
||||
*/
|
||||
|
||||
describe("isPreviewable (lista cerrada)", () => {
|
||||
it("imagen, audio, video y PDF se muestran en el navegador", () => {
|
||||
for (const mime of [
|
||||
"image/jpeg",
|
||||
"image/png",
|
||||
"image/gif",
|
||||
"image/webp",
|
||||
"audio/ogg",
|
||||
"audio/mpeg",
|
||||
"audio/mp4",
|
||||
"audio/aac",
|
||||
"audio/amr",
|
||||
"video/mp4",
|
||||
"video/3gpp",
|
||||
"application/pdf",
|
||||
]) {
|
||||
expect(isPreviewable(mime), mime).toBe(true);
|
||||
}
|
||||
});
|
||||
|
||||
it("el códec de las notas de voz de Meta no estorba", () => {
|
||||
expect(isPreviewable("audio/ogg; codecs=opus")).toBe(true);
|
||||
expect(baseMime("audio/ogg; codecs=opus")).toBe("audio/ogg");
|
||||
});
|
||||
|
||||
it("sin distinguir mayúsculas", () => {
|
||||
expect(isPreviewable("IMAGE/JPEG")).toBe(true);
|
||||
expect(baseMime("Application/PDF")).toBe("application/pdf");
|
||||
});
|
||||
|
||||
it("todo lo demás se descarga, sea peligroso o solo desconocido", () => {
|
||||
for (const mime of [
|
||||
"text/html",
|
||||
"image/svg+xml",
|
||||
"application/xhtml+xml",
|
||||
"text/plain",
|
||||
"text/csv",
|
||||
"application/zip",
|
||||
"application/octet-stream",
|
||||
"application/vnd.openxmlformats-officedocument.wordprocessingml.document",
|
||||
"image/bmp",
|
||||
"video/x-msvideo",
|
||||
"",
|
||||
"nada",
|
||||
]) {
|
||||
expect(isPreviewable(mime), mime || "(vacío)").toBe(false);
|
||||
}
|
||||
expect(isPreviewable(null)).toBe(false);
|
||||
expect(isPreviewable(undefined)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("isForbiddenUploadMime (lo que no se envía ni como documento)", () => {
|
||||
it("HTML, XHTML y SVG, con o sin parámetros", () => {
|
||||
expect(isForbiddenUploadMime("text/html")).toBe(true);
|
||||
expect(isForbiddenUploadMime("text/html; charset=utf-8")).toBe(true);
|
||||
expect(isForbiddenUploadMime("application/xhtml+xml")).toBe(true);
|
||||
expect(isForbiddenUploadMime("image/svg+xml")).toBe(true);
|
||||
expect(isForbiddenUploadMime("Image/SVG+XML")).toBe(true);
|
||||
});
|
||||
|
||||
it("el resto de documentos sigue pasando", () => {
|
||||
expect(isForbiddenUploadMime("application/pdf")).toBe(false);
|
||||
expect(isForbiddenUploadMime("image/png")).toBe(false);
|
||||
expect(isForbiddenUploadMime("text/plain")).toBe(false);
|
||||
expect(isForbiddenUploadMime(null)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("contentTypeFor (lo que se declara)", () => {
|
||||
it("conserva un MIME bien formado, con sus parámetros", () => {
|
||||
expect(contentTypeFor("image/jpeg")).toBe("image/jpeg");
|
||||
expect(contentTypeFor("audio/ogg; codecs=opus")).toBe("audio/ogg; codecs=opus");
|
||||
expect(contentTypeFor(" Application/PDF ")).toBe("application/pdf");
|
||||
});
|
||||
|
||||
it("sin tipo o con basura → octet-stream (con nosniff: «descárgalo»)", () => {
|
||||
expect(contentTypeFor(null)).toBe("application/octet-stream");
|
||||
expect(contentTypeFor("")).toBe("application/octet-stream");
|
||||
expect(contentTypeFor("nada")).toBe("application/octet-stream");
|
||||
expect(contentTypeFor("text/html\r\nx-inyectada: 1")).toBe(
|
||||
"application/octet-stream"
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("contentDisposition (el nombre del archivo)", () => {
|
||||
it("sin nombre, solo el modo", () => {
|
||||
expect(contentDisposition("inline", null)).toBe("inline");
|
||||
expect(contentDisposition("attachment", "")).toBe("attachment");
|
||||
});
|
||||
|
||||
it("conserva acentos en filename* y deja un respaldo ASCII", () => {
|
||||
expect(contentDisposition("inline", "cotización.pdf")).toBe(
|
||||
"inline; filename=\"cotizaci_n.pdf\"; filename*=UTF-8''cotizaci%C3%B3n.pdf"
|
||||
);
|
||||
});
|
||||
|
||||
it("ni comillas, ni saltos de línea, ni rutas", () => {
|
||||
const cd = contentDisposition("attachment", 'a"b\r\nc/..\\d.txt');
|
||||
expect(cd).not.toMatch(/[\r\n]/);
|
||||
expect(cd).toContain('filename="a_b__c_.._d.txt"');
|
||||
expect(cd).not.toContain("/");
|
||||
});
|
||||
});
|
||||
|
||||
describe("mediaResponseHeaders (lo que ve el navegador)", () => {
|
||||
const siempre = (h: Record<string, string>) => {
|
||||
expect(h["x-content-type-options"]).toBe("nosniff");
|
||||
expect(h["content-security-policy"]).toBe("default-src 'none'; sandbox");
|
||||
expect(h["cache-control"]).toBe("private, max-age=86400");
|
||||
};
|
||||
|
||||
it("una imagen va inline, con nosniff y CSP sandbox", () => {
|
||||
const h = mediaResponseHeaders({ mimeType: "image/jpeg", fileName: null }, 1234);
|
||||
siempre(h);
|
||||
expect(h["content-type"]).toBe("image/jpeg");
|
||||
expect(h["content-length"]).toBe("1234");
|
||||
expect(h["content-disposition"]).toBe("inline");
|
||||
});
|
||||
|
||||
it("un PDF con nombre va inline y conserva el nombre", () => {
|
||||
const h = mediaResponseHeaders(
|
||||
{ mimeType: "application/pdf", fileName: "cotizacion.pdf" },
|
||||
10
|
||||
);
|
||||
siempre(h);
|
||||
expect(h["content-disposition"]).toMatch(/^inline; filename="cotizacion\.pdf"/);
|
||||
});
|
||||
|
||||
it("un .docx se descarga (attachment) con su nombre", () => {
|
||||
const h = mediaResponseHeaders(
|
||||
{
|
||||
mimeType:
|
||||
"application/vnd.openxmlformats-officedocument.wordprocessingml.document",
|
||||
fileName: "contrato.docx",
|
||||
},
|
||||
10
|
||||
);
|
||||
siempre(h);
|
||||
expect(h["content-disposition"]).toMatch(/^attachment; filename="contrato\.docx"/);
|
||||
});
|
||||
|
||||
it("un HTML que entró como «documento» desde WhatsApp jamás se abre como página", () => {
|
||||
const h = mediaResponseHeaders({ mimeType: "text/html", fileName: "factura.html" }, 10);
|
||||
siempre(h);
|
||||
expect(h["content-disposition"]).toMatch(/^attachment;/);
|
||||
});
|
||||
|
||||
it("un asset sin tipo se descarga como octet-stream", () => {
|
||||
const h = mediaResponseHeaders({ mimeType: null, fileName: null }, 10);
|
||||
siempre(h);
|
||||
expect(h["content-type"]).toBe("application/octet-stream");
|
||||
expect(h["content-disposition"]).toBe("attachment");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,144 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import {
|
||||
kindFromMime,
|
||||
MediaValidationError,
|
||||
validateOutgoing,
|
||||
} from "@/server/whatsapp/media";
|
||||
|
||||
/**
|
||||
* 008 — Validación previa de adjuntos salientes (FR-007): tipo y tamaño se
|
||||
* rechazan ANTES de tocar disco o la API; y el sandbox del Laboratorio
|
||||
* sigue siendo infranqueable también para adjuntos (FR-014).
|
||||
*/
|
||||
|
||||
const MB = 1024 * 1024;
|
||||
|
||||
describe("validateOutgoing (límites de la Cloud API)", () => {
|
||||
it("imagen jpeg de 1 MB → image", () => {
|
||||
expect(validateOutgoing("image/jpeg", 1 * MB)).toBe("image");
|
||||
});
|
||||
|
||||
it("imagen de 6 MB → too_large (límite 5 MB)", () => {
|
||||
expect(() => validateOutgoing("image/png", 6 * MB)).toThrowError(
|
||||
expect.objectContaining({ code: "too_large" })
|
||||
);
|
||||
});
|
||||
|
||||
it("imagen bmp (no nativa) → va como documento, igual que en WhatsApp", () => {
|
||||
expect(validateOutgoing("image/bmp", 1 * MB)).toBe("document");
|
||||
});
|
||||
|
||||
it("MIME malformado → unsupported_type", () => {
|
||||
expect(() => validateOutgoing("nada", 1 * MB)).toThrowError(
|
||||
expect.objectContaining({ code: "unsupported_type" })
|
||||
);
|
||||
});
|
||||
|
||||
it("HTML y SVG no se envían ni como documento (#78), con un mensaje que explica", () => {
|
||||
for (const mime of ["text/html", "image/svg+xml", "application/xhtml+xml"]) {
|
||||
expect(() => validateOutgoing(mime, 1024), mime).toThrowError(
|
||||
expect.objectContaining({
|
||||
code: "unsupported_type",
|
||||
message: expect.stringContaining("HTML y SVG"),
|
||||
})
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
it("pdf de 10 MB → document; de 101 MB → too_large", () => {
|
||||
expect(validateOutgoing("application/pdf", 10 * MB)).toBe("document");
|
||||
expect(() => validateOutgoing("application/pdf", 101 * MB)).toThrowError(
|
||||
MediaValidationError
|
||||
);
|
||||
});
|
||||
|
||||
it("video mp4 de 20 MB → too_large (límite 16 MB)", () => {
|
||||
expect(() => validateOutgoing("video/mp4", 20 * MB)).toThrowError(
|
||||
expect.objectContaining({ code: "too_large" })
|
||||
);
|
||||
});
|
||||
|
||||
it("clasificación por MIME", () => {
|
||||
expect(kindFromMime("audio/ogg")).toBe("audio");
|
||||
expect(kindFromMime("video/mp4")).toBe("video");
|
||||
expect(kindFromMime("application/zip")).toBe("document");
|
||||
});
|
||||
});
|
||||
|
||||
/* ---------- Sandbox del Laboratorio en el envío de adjuntos ---------- */
|
||||
|
||||
const { graphRequest, uploadGraphMedia, saveMediaFile } = vi.hoisted(() => ({
|
||||
graphRequest: vi.fn(),
|
||||
uploadGraphMedia: vi.fn(),
|
||||
saveMediaFile: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/meta/client", async (importOriginal) => {
|
||||
const original = await importOriginal<typeof import("@/lib/meta/client")>();
|
||||
return { ...original, graphRequest };
|
||||
});
|
||||
|
||||
vi.mock("@/server/whatsapp/media", async (importOriginal) => {
|
||||
const original =
|
||||
await importOriginal<typeof import("@/server/whatsapp/media")>();
|
||||
return { ...original, uploadGraphMedia, saveMediaFile };
|
||||
});
|
||||
|
||||
function makeChain(rows: unknown[]) {
|
||||
const chain: Record<string, unknown> = {};
|
||||
for (const m of ["from", "innerJoin", "where", "orderBy"]) {
|
||||
chain[m] = () => chain;
|
||||
}
|
||||
chain.limit = () => Promise.resolve(rows);
|
||||
return chain;
|
||||
}
|
||||
|
||||
const selectRows: unknown[][] = [];
|
||||
|
||||
vi.mock("@/lib/db", () => ({
|
||||
getDb: () => ({
|
||||
select: () => makeChain(selectRows.shift() ?? []),
|
||||
}),
|
||||
schema: {
|
||||
conversation: { contactId: "contactId", id: "id" },
|
||||
contact: { id: "id" },
|
||||
message: {},
|
||||
mediaAsset: {},
|
||||
},
|
||||
}));
|
||||
|
||||
describe("sandbox del Laboratorio en el envío de adjuntos", () => {
|
||||
beforeEach(() => {
|
||||
graphRequest.mockReset();
|
||||
uploadGraphMedia.mockReset();
|
||||
saveMediaFile.mockReset();
|
||||
selectRows.length = 0;
|
||||
});
|
||||
|
||||
it("conversación is_test → sandbox_violation sin tocar disco ni Graph", async () => {
|
||||
selectRows.push([
|
||||
{
|
||||
conversation: {
|
||||
id: "cv_test",
|
||||
organizationId: "org_1",
|
||||
isTest: true,
|
||||
lastInboundAt: new Date(),
|
||||
},
|
||||
contact: { id: "ct_1", phone: "5215511111111" },
|
||||
},
|
||||
]);
|
||||
const { sendMediaMessage } = await import("@/server/inbox/send");
|
||||
|
||||
await expect(
|
||||
sendMediaMessage({
|
||||
conversationId: "cv_test",
|
||||
organizationId: "org_1",
|
||||
file: { data: Buffer.from("x"), mimeType: "image/jpeg" },
|
||||
})
|
||||
).rejects.toMatchObject({ code: "sandbox_violation" });
|
||||
|
||||
expect(saveMediaFile).not.toHaveBeenCalled();
|
||||
expect(uploadGraphMedia).not.toHaveBeenCalled();
|
||||
expect(graphRequest).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,347 @@
|
||||
import { mkdtemp, mkdir, writeFile, readFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import { createHash } from "node:crypto";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
/**
|
||||
* 037 — Adjuntos en disco o en bucket (puerto de la spec 200 de la edición
|
||||
* cloud; conector opcional del Principio II.3).
|
||||
*
|
||||
* Lo que se prueba aquí es lo que puede perder el archivo de un cliente: que
|
||||
* la firma sea válida, que la bandera no escriba donde no debe, que la
|
||||
* LECTURA mire en los dos sitios —lo que permite mover la bandera sin ventana
|
||||
* de corte— y, propio de la raíz, que un bucket caído no pierda el archivo.
|
||||
*/
|
||||
|
||||
const BASE = {
|
||||
APP_BASE_URL: "http://localhost:3000",
|
||||
DATABASE_URL: "postgresql://t:t@localhost:5432/t",
|
||||
BETTER_AUTH_SECRET: "secret-de-test-suficiente",
|
||||
ENCRYPTION_KEY: Buffer.alloc(32, 9).toString("base64"),
|
||||
META_WEBHOOK_VERIFY_TOKEN: "verify-test",
|
||||
};
|
||||
|
||||
const CREDS = {
|
||||
MEDIA_BUCKET_ENDPOINT: "https://cuenta123.r2.cloudflarestorage.com",
|
||||
MEDIA_BUCKET_NAME: "vocero-media",
|
||||
MEDIA_BUCKET_KEY_ID: "AKIAEJEMPLO",
|
||||
MEDIA_BUCKET_SECRET: "secretoDeEjemplo1234567890",
|
||||
MEDIA_BUCKET_REGION: "auto",
|
||||
};
|
||||
|
||||
let dirTemporal: string;
|
||||
|
||||
async function montar(extra: Record<string, string | undefined>) {
|
||||
vi.resetModules();
|
||||
for (const k of Object.keys({ ...CREDS, MEDIA_STORE: "" })) delete process.env[k];
|
||||
Object.assign(process.env, BASE, { MEDIA_DIR: dirTemporal });
|
||||
for (const [k, v] of Object.entries(extra)) {
|
||||
if (v === undefined) delete process.env[k];
|
||||
else process.env[k] = v;
|
||||
}
|
||||
return import("@/lib/storage/medios");
|
||||
}
|
||||
|
||||
beforeEach(async () => {
|
||||
dirTemporal = await mkdtemp(path.join(tmpdir(), "vocero-medios-"));
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
describe("firma SigV4 del bucket", () => {
|
||||
it("produce la MISMA firma que botocore para la misma petición", async () => {
|
||||
const { firmarSolicitud } = await import("@/lib/storage/objetos");
|
||||
const r = firmarSolicitud({
|
||||
cfg: {
|
||||
endpoint: "https://cuenta123.r2.cloudflarestorage.com",
|
||||
bucket: "vocero-media",
|
||||
accessKeyId: "AKIAEJEMPLO",
|
||||
secretAccessKey: "secretoDeEjemplo1234567890",
|
||||
region: "auto",
|
||||
},
|
||||
metodo: "PUT",
|
||||
llave: "org_abc/asset_def",
|
||||
hashDelCuerpo: createHash("sha256").update("hola").digest("hex"),
|
||||
contentType: "text/plain",
|
||||
ahora: new Date("2026-09-08T04:30:00.000Z"),
|
||||
});
|
||||
|
||||
// Valor de referencia calculado con botocore (AWS oficial) para estas
|
||||
// mismas entradas. Si esta firma cambia, la culpa es nuestra.
|
||||
expect(r.headers.Authorization).toContain(
|
||||
"Signature=fe58228394eb5897a000e946894026e0bc343e2363eb5aab4d11546437633304"
|
||||
);
|
||||
expect(r.headers.Authorization).toContain(
|
||||
"SignedHeaders=content-type;host;x-amz-content-sha256;x-amz-date"
|
||||
);
|
||||
expect(r.url).toBe(
|
||||
"https://cuenta123.r2.cloudflarestorage.com/vocero-media/org_abc/asset_def"
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("llave del objeto", () => {
|
||||
it("es la ruta relativa de siempre, para que la BD no cambie", async () => {
|
||||
const { llaveDeMedia } = await montar({});
|
||||
expect(llaveDeMedia("org_1", "asset_2")).toBe("org_1/asset_2");
|
||||
});
|
||||
|
||||
it("rechaza segmentos que se salgan del prefijo de la organización", async () => {
|
||||
const { llaveDeMedia } = await montar({});
|
||||
expect(() => llaveDeMedia("../otra", "asset_2")).toThrow();
|
||||
expect(() => llaveDeMedia("org_1", "a/b")).toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
describe("dónde se escribe", () => {
|
||||
it("sin bandera, escribe en disco (una instancia que no pidió bucket)", async () => {
|
||||
const m = await montar({});
|
||||
expect(m.almacenActivo()).toBe("disco");
|
||||
await m.guardarMedia("org_1", "asset_1", Buffer.from("contenido"));
|
||||
expect(await readFile(path.join(dirTemporal, "org_1", "asset_1"), "utf8")).toBe(
|
||||
"contenido"
|
||||
);
|
||||
});
|
||||
|
||||
it("con la bandera pero SIN credenciales, avisa y NO pierde el archivo", async () => {
|
||||
const aviso = vi.spyOn(console, "warn").mockImplementation(() => {});
|
||||
const m = await montar({ MEDIA_STORE: "bucket" });
|
||||
expect(m.almacenActivo()).toBe("disco");
|
||||
await m.guardarMedia("org_1", "asset_1", Buffer.from("contenido"));
|
||||
expect(await readFile(path.join(dirTemporal, "org_1", "asset_1"), "utf8")).toBe(
|
||||
"contenido"
|
||||
);
|
||||
expect(aviso).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("con bandera y credenciales, hace PUT al bucket y no toca el disco", async () => {
|
||||
const fetchFalso = vi.fn(async () => new Response("", { status: 200 }));
|
||||
vi.stubGlobal("fetch", fetchFalso);
|
||||
const m = await montar({ MEDIA_STORE: "bucket", ...CREDS });
|
||||
|
||||
const ruta = await m.guardarMedia("org_1", "asset_1", Buffer.from("contenido"));
|
||||
|
||||
expect(ruta).toBe("org_1/asset_1");
|
||||
expect(fetchFalso).toHaveBeenCalledOnce();
|
||||
const [url, init] = fetchFalso.mock.calls[0] as unknown as [string, RequestInit];
|
||||
expect(url).toBe(
|
||||
"https://cuenta123.r2.cloudflarestorage.com/vocero-media/org_1/asset_1"
|
||||
);
|
||||
expect(init.method).toBe("PUT");
|
||||
await expect(
|
||||
readFile(path.join(dirTemporal, "org_1", "asset_1"))
|
||||
).rejects.toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
describe("una llave fija (el icono) no queda tapada al mover la bandera", () => {
|
||||
it("al escribir en el bucket, se quita la copia vieja del disco", async () => {
|
||||
vi.stubGlobal("fetch", vi.fn(async () => new Response("", { status: 200 })));
|
||||
const m = await montar({ MEDIA_STORE: "bucket", ...CREDS });
|
||||
await mkdir(path.join(dirTemporal, "org_1"), { recursive: true });
|
||||
await writeFile(path.join(dirTemporal, "org_1", "favicon"), "icono viejo");
|
||||
|
||||
await m.guardarMedia("org_1", "favicon", Buffer.from("icono nuevo"));
|
||||
|
||||
await expect(readFile(path.join(dirTemporal, "org_1", "favicon"))).rejects.toThrow();
|
||||
});
|
||||
|
||||
it("al escribir en disco con el bucket configurado, se borra la copia del bucket", async () => {
|
||||
const llamadas: string[] = [];
|
||||
vi.stubGlobal(
|
||||
"fetch",
|
||||
vi.fn(async (u: string, init?: RequestInit) => {
|
||||
llamadas.push(`${init?.method} ${u}`);
|
||||
return new Response("", { status: 204 });
|
||||
})
|
||||
);
|
||||
const m = await montar({ MEDIA_STORE: "disco", ...CREDS });
|
||||
await m.guardarMedia("org_1", "favicon", Buffer.from("icono nuevo"));
|
||||
expect(await readFile(path.join(dirTemporal, "org_1", "favicon"), "utf8")).toBe("icono nuevo");
|
||||
expect(llamadas).toEqual(["DELETE https://cuenta123.r2.cloudflarestorage.com/vocero-media/org_1/favicon"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("la lectura mira en los DOS sitios", () => {
|
||||
it("con el bucket encendido, un archivo viejo del disco se sigue leyendo", async () => {
|
||||
// 404 en el bucket: el archivo es de antes de migrar.
|
||||
vi.stubGlobal("fetch", vi.fn(async () => new Response("", { status: 404 })));
|
||||
const m = await montar({ MEDIA_STORE: "bucket", ...CREDS });
|
||||
|
||||
await mkdir(path.join(dirTemporal, "org_1"), { recursive: true });
|
||||
await writeFile(path.join(dirTemporal, "org_1", "viejo"), "de antes");
|
||||
|
||||
expect((await m.leerMedia("org_1", "viejo")).toString()).toBe("de antes");
|
||||
});
|
||||
|
||||
it("con el bucket apagado, un archivo que ya estaba en el bucket se recupera", async () => {
|
||||
// El caso de volver atrás: la bandera regresó a `disco` y hay objetos
|
||||
// escritos en el bucket. Sin esta rama, se perderían de vista.
|
||||
vi.stubGlobal(
|
||||
"fetch",
|
||||
vi.fn(async () => new Response("desde el bucket", { status: 200 }))
|
||||
);
|
||||
const m = await montar({ MEDIA_STORE: "disco", ...CREDS });
|
||||
|
||||
expect((await m.leerMedia("org_1", "nuevo")).toString()).toBe("desde el bucket");
|
||||
});
|
||||
|
||||
it("si no está en ninguno de los dos, falla como siempre falló", async () => {
|
||||
vi.stubGlobal("fetch", vi.fn(async () => new Response("", { status: 404 })));
|
||||
const m = await montar({ MEDIA_STORE: "bucket", ...CREDS });
|
||||
await expect(m.leerMedia("org_1", "fantasma")).rejects.toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
describe("037 — un bucket caído no pierde el archivo (D4)", () => {
|
||||
it("si el bucket rechaza el PUT, se guarda en disco, se avisa y se puede leer", async () => {
|
||||
const aviso = vi.spyOn(console, "warn").mockImplementation(() => {});
|
||||
vi.stubGlobal(
|
||||
"fetch",
|
||||
vi.fn(async (_u: string, init?: RequestInit) =>
|
||||
init?.method === "PUT" ? new Response("AccessDenied", { status: 403 }) : new Response("", { status: 404 })
|
||||
)
|
||||
);
|
||||
const m = await montar({ MEDIA_STORE: "bucket", ...CREDS });
|
||||
expect(await m.guardarMedia("org_1", "asset_1", Buffer.from("del cliente"))).toBe("org_1/asset_1");
|
||||
expect(await readFile(path.join(dirTemporal, "org_1", "asset_1"), "utf8")).toBe("del cliente");
|
||||
expect((await m.leerMedia("org_1", "asset_1")).toString()).toBe("del cliente");
|
||||
expect(aviso).toHaveBeenCalled();
|
||||
aviso.mockRestore();
|
||||
});
|
||||
|
||||
it("si el bucket no contesta (red), igual: al disco, y la lectura tampoco revienta", async () => {
|
||||
const aviso = vi.spyOn(console, "warn").mockImplementation(() => {});
|
||||
vi.stubGlobal(
|
||||
"fetch",
|
||||
vi.fn(async () => {
|
||||
throw new TypeError("fetch failed");
|
||||
})
|
||||
);
|
||||
const m = await montar({ MEDIA_STORE: "bucket", ...CREDS });
|
||||
await m.guardarMedia("org_1", "asset_2", Buffer.from("x"));
|
||||
expect(await readFile(path.join(dirTemporal, "org_1", "asset_2"), "utf8")).toBe("x");
|
||||
expect((await m.leerMedia("org_1", "asset_2")).toString()).toBe("x");
|
||||
aviso.mockRestore();
|
||||
});
|
||||
|
||||
it("los avisos no llevan la firma ni la llave", async () => {
|
||||
const vistos: string[] = [];
|
||||
const aviso = vi.spyOn(console, "warn").mockImplementation((...a: unknown[]) => {
|
||||
vistos.push(a.map(String).join(" "));
|
||||
});
|
||||
vi.stubGlobal("fetch", vi.fn(async () => new Response("<Error>Forbidden</Error>", { status: 403 })));
|
||||
const m = await montar({ MEDIA_STORE: "bucket", ...CREDS });
|
||||
await m.guardarMedia("org_1", "asset_3", Buffer.from("x"));
|
||||
await m.borrarMedia("org_1", "asset_3");
|
||||
expect(vistos.length).toBeGreaterThan(0);
|
||||
for (const v of vistos) {
|
||||
expect(v).not.toContain(CREDS.MEDIA_BUCKET_SECRET);
|
||||
expect(v).not.toContain("Credential=");
|
||||
}
|
||||
aviso.mockRestore();
|
||||
});
|
||||
|
||||
it("borrar borra en los dos sitios", async () => {
|
||||
const llamadas: string[] = [];
|
||||
vi.stubGlobal(
|
||||
"fetch",
|
||||
vi.fn(async (u: string, init?: RequestInit) => {
|
||||
llamadas.push(`${init?.method} ${u}`);
|
||||
return new Response("", { status: 204 });
|
||||
})
|
||||
);
|
||||
const m = await montar({ MEDIA_STORE: "disco", ...CREDS });
|
||||
await mkdir(path.join(dirTemporal, "org_1"), { recursive: true });
|
||||
await writeFile(path.join(dirTemporal, "org_1", "asset_4"), "x");
|
||||
await m.borrarMedia("org_1", "asset_4");
|
||||
await expect(readFile(path.join(dirTemporal, "org_1", "asset_4"))).rejects.toThrow();
|
||||
expect(llamadas).toEqual(["DELETE https://cuenta123.r2.cloudflarestorage.com/vocero-media/org_1/asset_4"]);
|
||||
});
|
||||
|
||||
it("un endpoint que no es http(s) cuenta como bucket mal configurado", async () => {
|
||||
const m = await montar({ MEDIA_STORE: "bucket", ...CREDS, MEDIA_BUCKET_ENDPOINT: "ftp://algo" });
|
||||
expect(m.leerConfigDelBucket()).toMatchObject({ cfg: null, problema: "endpoint" });
|
||||
expect(m.almacenActivo()).toBe("disco");
|
||||
});
|
||||
});
|
||||
|
||||
describe("037 — el sondeo prueba donde se escribe", () => {
|
||||
it("con el bucket sano: PUT y DELETE del objeto de sondeo; solo enseña el host", async () => {
|
||||
const metodos: string[] = [];
|
||||
vi.stubGlobal(
|
||||
"fetch",
|
||||
vi.fn(async (_u: string, init?: RequestInit) => {
|
||||
metodos.push(init?.method ?? "");
|
||||
return new Response("", { status: 200 });
|
||||
})
|
||||
);
|
||||
await montar({ MEDIA_STORE: "bucket", ...CREDS });
|
||||
const { probeAlmacen } = await import("@/server/media-dir");
|
||||
expect(await probeAlmacen(dirTemporal)).toEqual({
|
||||
store: "bucket",
|
||||
dir: "cuenta123.r2.cloudflarestorage.com",
|
||||
writable: true,
|
||||
});
|
||||
expect(metodos).toEqual(["PUT", "DELETE"]);
|
||||
});
|
||||
|
||||
it("con el bucket rechazando: no escribible, con el código", async () => {
|
||||
vi.stubGlobal("fetch", vi.fn(async () => new Response("", { status: 403 })));
|
||||
await montar({ MEDIA_STORE: "bucket", ...CREDS });
|
||||
const { probeAlmacen } = await import("@/server/media-dir");
|
||||
expect(await probeAlmacen(dirTemporal)).toMatchObject({ store: "bucket", writable: false, code: "bucket_403" });
|
||||
});
|
||||
|
||||
it("con la bandera y sin credenciales: no escribible (quien instala pidió el bucket)", async () => {
|
||||
await montar({ MEDIA_STORE: "bucket" });
|
||||
const { probeAlmacen } = await import("@/server/media-dir");
|
||||
expect(await probeAlmacen(dirTemporal)).toMatchObject({
|
||||
store: "bucket",
|
||||
writable: false,
|
||||
code: "bucket_incompleto",
|
||||
});
|
||||
});
|
||||
|
||||
it("sin la bandera: el disco, como siempre, y nadie le habla al bucket", async () => {
|
||||
const f = vi.fn();
|
||||
vi.stubGlobal("fetch", f);
|
||||
await montar({ ...CREDS });
|
||||
const { probeAlmacen } = await import("@/server/media-dir");
|
||||
expect(await probeAlmacen(dirTemporal)).toMatchObject({ store: "disco", writable: true });
|
||||
expect(f).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe("037 — doctor y salud", () => {
|
||||
it("sin la bandera, el doctor no menciona el bucket", async () => {
|
||||
const { checkMediaBucket } = await import("@/server/doctor/checks");
|
||||
expect(await checkMediaBucket({ ...CREDS })).toBeNull();
|
||||
});
|
||||
|
||||
it("con la bandera y variables faltantes, falla y dice cuáles", async () => {
|
||||
const { checkMediaBucket } = await import("@/server/doctor/checks");
|
||||
const r = await checkMediaBucket({ MEDIA_STORE: "bucket", MEDIA_BUCKET_ENDPOINT: CREDS.MEDIA_BUCKET_ENDPOINT });
|
||||
expect(r).toMatchObject({ status: "fail" });
|
||||
expect(r?.fix).toMatch(/MEDIA_BUCKET_SECRET/);
|
||||
});
|
||||
|
||||
it("con el bucket sano, ok sin enseñar llaves", async () => {
|
||||
vi.stubGlobal("fetch", vi.fn(async () => new Response("", { status: 200 })));
|
||||
const { checkMediaBucket } = await import("@/server/doctor/checks");
|
||||
const r = await checkMediaBucket({ MEDIA_STORE: "bucket", ...CREDS });
|
||||
expect(r).toMatchObject({ status: "ok" });
|
||||
expect(JSON.stringify(r)).not.toContain(CREDS.MEDIA_BUCKET_SECRET);
|
||||
expect(JSON.stringify(r)).not.toContain(CREDS.MEDIA_BUCKET_KEY_ID);
|
||||
});
|
||||
|
||||
it("/api/health dice el almacén pedido en features.media", async () => {
|
||||
const { healthFeatures } = await import("@/server/health");
|
||||
expect(healthFeatures({}).media).toBe("disco");
|
||||
expect(healthFeatures({ MEDIA_STORE: "bucket" }).media).toBe("bucket");
|
||||
expect(healthFeatures({ MEDIA_STORE: "s3" }).media).toBe("disco");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,353 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { CHANNEL_LABEL, CHANNEL_ORDER, isChannel } from "@/lib/channels";
|
||||
import { FB_PREFIX, IG_PREFIX, BSUID_PREFIX } from "@/server/inbox/identity";
|
||||
import { capabilitiesFor, textFits, windowClosedMessage } from "@/server/channels/capabilities";
|
||||
import { parseChannels } from "@/server/channels/enabled";
|
||||
import { channelMark } from "@/components/channel-badge";
|
||||
import {
|
||||
normalizeMetaPagePayload,
|
||||
normalizeZernioEvent,
|
||||
} from "@/server/messenger/ingest";
|
||||
import { buildMessengerSendBody } from "@/server/messenger/send";
|
||||
import {
|
||||
isValidZernioSignature,
|
||||
looksLikeMetaPayload,
|
||||
zernioSentAtSeconds,
|
||||
} from "@/server/zernio";
|
||||
import { zernioTargetChannel } from "@/server/zernio/dispatch";
|
||||
import { createHmac } from "node:crypto";
|
||||
|
||||
const PAGE = "1092837465";
|
||||
const PSID = "83719264018";
|
||||
const ACCOUNT = "665f1c2e8b3a4d0012345678";
|
||||
|
||||
/** Un webhook de Meta con lo que trae de verdad: `object: "page"`. */
|
||||
function metaWebhook(messaging: unknown[], overrides: Record<string, unknown> = {}) {
|
||||
return {
|
||||
object: "page",
|
||||
entry: [{ id: PAGE, time: 1_770_000_000_000, messaging }],
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
/** Un evento de Zernio, con la forma de su documentación. */
|
||||
function zernioEvent(over: Record<string, unknown> = {}) {
|
||||
return {
|
||||
id: "5f8e2a1c-0000",
|
||||
event: "message.received",
|
||||
message: {
|
||||
id: "665f0001",
|
||||
conversationId: "664a0001",
|
||||
direction: "incoming",
|
||||
text: "Hola",
|
||||
sender: { id: PSID, name: "Jane Doe", username: "jane_doe" },
|
||||
},
|
||||
account: { id: ACCOUNT, platform: "facebook" },
|
||||
...over,
|
||||
};
|
||||
}
|
||||
|
||||
describe("017 · Messenger en el catálogo de canales", () => {
|
||||
it("existe, se enciende con CHANNELS y tiene nombre y distintivo", () => {
|
||||
expect(isChannel("messenger")).toBe(true);
|
||||
expect(CHANNEL_ORDER).toContain("messenger");
|
||||
expect(CHANNEL_LABEL.messenger).toBe("Messenger");
|
||||
expect(parseChannels("whatsapp,messenger").has("messenger")).toBe(true);
|
||||
expect(parseChannels("instagram").has("messenger")).toBe(false);
|
||||
expect(channelMark("messenger")).not.toBeNull();
|
||||
});
|
||||
|
||||
it("capacidades: 24 h con etiqueta fuera de ventana, sin plantillas ni adjuntos salientes", () => {
|
||||
const caps = capabilitiesFor("messenger");
|
||||
expect(caps.windowMs).toBe(24 * 60 * 60 * 1000);
|
||||
expect(caps.outsideWindow).toBe("human_agent_tag");
|
||||
expect(caps.outboundMedia).toBe(false);
|
||||
expect(caps.deliveryReceipts).toBe(false);
|
||||
// Fuera de ventana no se le pide nada al operador: sale etiquetado solo.
|
||||
// 024: la extensión humana tiene tope (7 días) y su propio mensaje.
|
||||
expect(windowClosedMessage("messenger")).toContain("7 días");
|
||||
});
|
||||
|
||||
it("el límite de texto es de 2000 y se cuenta en BYTES", () => {
|
||||
expect(textFits("messenger", "a".repeat(2000))).toBe(true);
|
||||
expect(textFits("messenger", "a".repeat(2001))).toBe(false);
|
||||
// 1200 acentos = 2400 bytes: contando caracteres pasaría y Meta lo rechazaría.
|
||||
expect(textFits("messenger", "é".repeat(1200))).toBe(false);
|
||||
});
|
||||
|
||||
it("la identidad lleva su propio prefijo: nunca colisiona con WhatsApp ni Instagram", () => {
|
||||
expect(FB_PREFIX).toBe("fb:");
|
||||
expect(new Set([FB_PREFIX, IG_PREFIX, BSUID_PREFIX]).size).toBe(3);
|
||||
});
|
||||
});
|
||||
|
||||
describe("017 · normalizeMetaPagePayload (qué entra y qué se descarta)", () => {
|
||||
it("un texto entra con su página, su PSID, su mid y su hora en segundos", () => {
|
||||
const [evt, ...rest] = normalizeMetaPagePayload(
|
||||
metaWebhook([
|
||||
{
|
||||
sender: { id: PSID },
|
||||
recipient: { id: PAGE },
|
||||
timestamp: 1_770_000_123_456,
|
||||
message: { mid: "m_abc", text: "Hola, ¿tienen envíos?" },
|
||||
},
|
||||
])
|
||||
);
|
||||
expect(rest).toHaveLength(0);
|
||||
expect(evt).toEqual({
|
||||
routeKey: PAGE,
|
||||
psid: PSID,
|
||||
messageId: "m_abc",
|
||||
text: "Hola, ¿tienen envíos?",
|
||||
type: "text",
|
||||
timestamp: "1770000123",
|
||||
profileName: null,
|
||||
threadRef: null,
|
||||
attachments: [],
|
||||
});
|
||||
});
|
||||
|
||||
it("un adjunto sin texto entra con su tipo para que la bandeja enseñe qué llegó", () => {
|
||||
const [img] = normalizeMetaPagePayload(
|
||||
metaWebhook([
|
||||
{
|
||||
sender: { id: PSID },
|
||||
message: {
|
||||
mid: "m_img",
|
||||
attachments: [{ type: "image", payload: { url: "https://cdn/x.jpg" } }],
|
||||
},
|
||||
},
|
||||
])
|
||||
);
|
||||
expect(img?.type).toBe("image");
|
||||
expect(img?.text).toBeNull();
|
||||
|
||||
const [doc] = normalizeMetaPagePayload(
|
||||
metaWebhook([{ sender: { id: PSID }, message: { mid: "m_doc", attachments: [{ type: "file" }] } }])
|
||||
);
|
||||
expect(doc?.type).toBe("document");
|
||||
|
||||
const [sticker] = normalizeMetaPagePayload(
|
||||
metaWebhook([
|
||||
{
|
||||
sender: { id: PSID },
|
||||
message: { mid: "m_stk", attachments: [{ type: "image", payload: { sticker_id: 369239 } }] },
|
||||
},
|
||||
])
|
||||
);
|
||||
expect(sticker?.type).toBe("sticker");
|
||||
});
|
||||
|
||||
it("los echos (lo que mandó la página), los acuses y los postbacks NO son mensajes", () => {
|
||||
const events = normalizeMetaPagePayload(
|
||||
metaWebhook([
|
||||
{ sender: { id: PAGE }, recipient: { id: PSID }, message: { mid: "m_echo", text: "Gracias", is_echo: true } },
|
||||
{ sender: { id: PSID }, delivery: { mids: ["m_1"], watermark: 1 } },
|
||||
{ sender: { id: PSID }, read: { watermark: 1 } },
|
||||
{ sender: { id: PSID }, postback: { title: "Empezar", payload: "GET_STARTED" } },
|
||||
])
|
||||
);
|
||||
expect(events).toEqual([]);
|
||||
});
|
||||
|
||||
it("lo que no es un webhook de página se ignora entero", () => {
|
||||
expect(
|
||||
normalizeMetaPagePayload(metaWebhook([{ sender: { id: PSID }, message: { mid: "m", text: "x" } }], { object: "instagram" }))
|
||||
).toEqual([]);
|
||||
expect(normalizeMetaPagePayload(null)).toEqual([]);
|
||||
expect(normalizeMetaPagePayload("basura")).toEqual([]);
|
||||
expect(normalizeMetaPagePayload({ object: "page" })).toEqual([]);
|
||||
// Un evento de Zernio NO debe colarse por el normalizador de Meta.
|
||||
expect(normalizeMetaPagePayload(zernioEvent())).toEqual([]);
|
||||
});
|
||||
|
||||
it("sin remitente o sin mid no hay con qué identificar ni deduplicar: se descarta", () => {
|
||||
expect(
|
||||
normalizeMetaPagePayload(metaWebhook([{ message: { mid: "m", text: "x" } }, { sender: { id: PSID }, message: { text: "x" } }]))
|
||||
).toEqual([]);
|
||||
});
|
||||
|
||||
it("varias entradas y varios mensajes se aplanan en orden", () => {
|
||||
const events = normalizeMetaPagePayload({
|
||||
object: "page",
|
||||
entry: [
|
||||
{ id: PAGE, messaging: [{ sender: { id: "a" }, message: { mid: "1", text: "uno" } }] },
|
||||
{ id: "otra-pagina", messaging: [{ sender: { id: "b" }, message: { mid: "2", text: "dos" } }] },
|
||||
],
|
||||
});
|
||||
expect(events.map((e) => `${e.routeKey}/${e.psid}/${e.messageId}`)).toEqual([`${PAGE}/a/1`, "otra-pagina/b/2"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("017 · normalizeZernioEvent (la fuente unificada)", () => {
|
||||
it("un mensaje de Facebook entra con su cuenta, su PSID, su hilo y el nombre del perfil", () => {
|
||||
const [evt] = normalizeZernioEvent(zernioEvent());
|
||||
expect(evt?.routeKey).toBe(ACCOUNT);
|
||||
expect(evt?.psid).toBe(PSID);
|
||||
expect(evt?.messageId).toBe("665f0001");
|
||||
expect(evt?.text).toBe("Hola");
|
||||
expect(evt?.type).toBe("text");
|
||||
// El conversationId es lo ÚNICO con lo que se puede responder por Zernio.
|
||||
expect(evt?.threadRef).toBe("664a0001");
|
||||
expect(evt?.profileName).toBe("Jane Doe");
|
||||
});
|
||||
|
||||
it("sin nombre cae al usuario con arroba, que sigue siendo legible", () => {
|
||||
const [evt] = normalizeZernioEvent(
|
||||
zernioEvent({
|
||||
message: {
|
||||
id: "m1",
|
||||
conversationId: "c1",
|
||||
direction: "incoming",
|
||||
text: "hola",
|
||||
sender: { id: PSID, username: "jane_doe" },
|
||||
},
|
||||
})
|
||||
);
|
||||
expect(evt?.profileName).toBe("@jane_doe");
|
||||
});
|
||||
|
||||
it("el MISMO webhook trae otras plataformas: solo se ingiere Facebook/Messenger", () => {
|
||||
for (const platform of ["instagram", "whatsapp", "x", "tiktok", ""]) {
|
||||
expect(
|
||||
normalizeZernioEvent(zernioEvent({ account: { id: ACCOUNT, platform } }))
|
||||
).toEqual([]);
|
||||
}
|
||||
expect(
|
||||
normalizeZernioEvent(zernioEvent({ account: { id: ACCOUNT, platform: "MESSENGER" } }))
|
||||
).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("solo `message.received` entrante: lo demás es ruido de la bandeja de Zernio", () => {
|
||||
expect(normalizeZernioEvent(zernioEvent({ event: "message.sent" }))).toEqual([]);
|
||||
expect(normalizeZernioEvent(zernioEvent({ event: "message.read" }))).toEqual([]);
|
||||
expect(
|
||||
normalizeZernioEvent(
|
||||
zernioEvent({
|
||||
message: { id: "m", conversationId: "c", direction: "outgoing", text: "x", sender: { id: PSID } },
|
||||
})
|
||||
)
|
||||
).toEqual([]);
|
||||
});
|
||||
|
||||
it("sin cuenta, sin remitente o sin id de mensaje no se puede enrutar ni deduplicar", () => {
|
||||
expect(normalizeZernioEvent(zernioEvent({ account: { platform: "facebook" } }))).toEqual([]);
|
||||
expect(
|
||||
normalizeZernioEvent(zernioEvent({ message: { id: "m", direction: "incoming", text: "x" } }))
|
||||
).toEqual([]);
|
||||
expect(normalizeZernioEvent(null)).toEqual([]);
|
||||
expect(normalizeZernioEvent({ object: "page" })).toEqual([]);
|
||||
});
|
||||
|
||||
it("un adjunto de Zernio también entra con su tipo", () => {
|
||||
const [evt] = normalizeZernioEvent(
|
||||
zernioEvent({
|
||||
message: {
|
||||
id: "m_img",
|
||||
conversationId: "c1",
|
||||
direction: "incoming",
|
||||
text: null,
|
||||
attachments: [{ type: "image", url: "https://cdn/x.jpg" }],
|
||||
sender: { id: PSID },
|
||||
},
|
||||
})
|
||||
);
|
||||
expect(evt?.type).toBe("image");
|
||||
expect(evt?.text).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("017 · firma de Zernio (control de seguridad compartido)", () => {
|
||||
const body = JSON.stringify(zernioEvent());
|
||||
const secret = "s3cr3t0";
|
||||
const good = createHmac("sha256", secret).update(body).digest("hex");
|
||||
|
||||
it("acepta la firma correcta y rechaza la que no lo es", () => {
|
||||
expect(isValidZernioSignature(body, good, secret)).toBe(true);
|
||||
expect(isValidZernioSignature(body, good.toUpperCase(), secret)).toBe(true);
|
||||
expect(isValidZernioSignature(body, "deadbeef", secret)).toBe(false);
|
||||
expect(isValidZernioSignature(body + " ", good, secret)).toBe(false);
|
||||
expect(isValidZernioSignature(body, null, secret)).toBe(false);
|
||||
});
|
||||
|
||||
it("sin secreto configurado la capa queda desactivada, como en WhatsApp", () => {
|
||||
expect(isValidZernioSignature(body, null, null)).toBe(true);
|
||||
});
|
||||
|
||||
it("distingue un payload de Meta de uno de Zernio", () => {
|
||||
expect(looksLikeMetaPayload({ object: "page" }, "page")).toBe(true);
|
||||
expect(looksLikeMetaPayload({ object: "instagram" }, "page")).toBe(false);
|
||||
expect(looksLikeMetaPayload(zernioEvent(), "page")).toBe(false);
|
||||
expect(looksLikeMetaPayload(null, "page")).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("017 · la hora del mensaje sale del evento, no de la ingesta", () => {
|
||||
it("usa `sentAt` cuando viene", () => {
|
||||
// Importa porque `lastInboundAt` abre la ventana de 24 h: una reentrega
|
||||
// tardía sellada con la hora de llegada haría creer que la ventana está
|
||||
// abierta cuando la plataforma ya la cerró.
|
||||
expect(zernioSentAtSeconds("2026-09-02T00:56:04.336Z")).toBe("1788310564");
|
||||
});
|
||||
|
||||
it("un `sentAt` ausente o ilegible cae a la hora actual, nunca a NaN", () => {
|
||||
const ahora = Math.floor(Date.now() / 1000);
|
||||
for (const v of [undefined, "", "ayer por la tarde"]) {
|
||||
const s = Number(zernioSentAtSeconds(v));
|
||||
expect(Number.isFinite(s)).toBe(true);
|
||||
expect(Math.abs(s - ahora)).toBeLessThan(5);
|
||||
}
|
||||
});
|
||||
|
||||
it("el normalizador lo propaga", () => {
|
||||
const [evt] = normalizeZernioEvent(
|
||||
zernioEvent({
|
||||
message: {
|
||||
id: "m1",
|
||||
conversationId: "c1",
|
||||
direction: "incoming",
|
||||
text: "hola",
|
||||
sentAt: "2026-09-02T00:56:04.336Z",
|
||||
sender: { id: PSID, name: "Jane" },
|
||||
},
|
||||
})
|
||||
);
|
||||
expect(evt?.timestamp).toBe("1788310564");
|
||||
});
|
||||
});
|
||||
|
||||
describe("017 · reparto de Zernio por plataforma (un webhook, varios canales)", () => {
|
||||
it("manda cada plataforma a su canal", () => {
|
||||
// Zernio entrega TODAS las cuentas de la llave por un solo webhook: si
|
||||
// cada canal atendiera solo su URL, quien tenga el webhook apuntado a
|
||||
// Instagram vería sus mensajes de Messenger descartados en silencio.
|
||||
expect(zernioTargetChannel(zernioEvent({ account: { id: ACCOUNT, platform: "instagram" } }))).toBe("instagram");
|
||||
expect(zernioTargetChannel(zernioEvent({ account: { id: ACCOUNT, platform: "facebook" } }))).toBe("messenger");
|
||||
expect(zernioTargetChannel(zernioEvent({ account: { id: ACCOUNT, platform: "MESSENGER" } }))).toBe("messenger");
|
||||
});
|
||||
|
||||
it("una plataforma que Vocero no atiende no es de nadie", () => {
|
||||
// 022: `tiktok` salió de esta lista: ya es un canal (tests/unit/tiktok.test.ts).
|
||||
for (const platform of ["whatsapp", "x", "twitter", "linkedin", ""]) {
|
||||
expect(zernioTargetChannel(zernioEvent({ account: { id: ACCOUNT, platform } }))).toBeNull();
|
||||
}
|
||||
expect(zernioTargetChannel(null)).toBeNull();
|
||||
expect(zernioTargetChannel({ object: "page" })).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("017 · buildMessengerSendBody (transporte de Meta)", () => {
|
||||
it("dentro de la ventana es una RESPONSE normal", () => {
|
||||
expect(buildMessengerSendBody({ recipient: PSID, text: "Sí, a toda la ciudad", humanAgentTag: false })).toEqual({
|
||||
recipient: { id: PSID },
|
||||
message: { text: "Sí, a toda la ciudad" },
|
||||
messaging_type: "RESPONSE",
|
||||
});
|
||||
});
|
||||
|
||||
it("fuera de la ventana sale etiquetado como agente humano", () => {
|
||||
const body = buildMessengerSendBody({ recipient: PSID, text: "Ya te contesto", humanAgentTag: true });
|
||||
expect(body.messaging_type).toBe("MESSAGE_TAG");
|
||||
expect(body.tag).toBe("HUMAN_AGENT");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,80 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { MetaApiError, normalizeMx, normalizeRecipient } from "@/lib/meta/client";
|
||||
|
||||
describe("normalizeRecipient", () => {
|
||||
it("México móvil legado: 521 + 10 dígitos → 52 + 10 dígitos", () => {
|
||||
expect(normalizeRecipient("5215512345678")).toBe("525512345678");
|
||||
});
|
||||
|
||||
it("México ya normalizado queda intacto", () => {
|
||||
expect(normalizeRecipient("525512345678")).toBe("525512345678");
|
||||
});
|
||||
|
||||
it("Argentina móvil: 549 + 10 dígitos → 54 + 10 dígitos (issue #35)", () => {
|
||||
// Meta reporta `549…` pero la lista de destinatarios de prueba solo
|
||||
// acepta el número sin el 9: con el 9 responde 131030 y el panel muestra
|
||||
// el número como habilitado, así que el error manda a revisar donde no es.
|
||||
expect(normalizeRecipient("5491122334455")).toBe("541122334455");
|
||||
});
|
||||
|
||||
it("Argentina ya normalizada queda intacta", () => {
|
||||
expect(normalizeRecipient("541122334455")).toBe("541122334455");
|
||||
});
|
||||
|
||||
it("otros países quedan intactos", () => {
|
||||
expect(normalizeRecipient("14155552671")).toBe("14155552671");
|
||||
expect(normalizeRecipient("50761234567")).toBe("50761234567");
|
||||
});
|
||||
|
||||
it("no confunde números que empiezan en el troncal pero con otra longitud", () => {
|
||||
expect(normalizeRecipient("521123")).toBe("521123");
|
||||
expect(normalizeRecipient("549123")).toBe("549123");
|
||||
// 549 + 11 dígitos no es un móvil argentino: no se toca.
|
||||
expect(normalizeRecipient("54911223344556")).toBe("54911223344556");
|
||||
});
|
||||
|
||||
it("la identidad NO se toca: normalizar al enviar es asimétrico a propósito", () => {
|
||||
// Si la ingesta reescribiera `549…`, la identidad guardada dejaría de
|
||||
// coincidir con el `wa_id` de cada webhook y el contacto se partiría.
|
||||
expect(normalizeMx("5491122334455")).toBe("5491122334455");
|
||||
});
|
||||
});
|
||||
|
||||
describe("MetaApiError.isAuthError", () => {
|
||||
it("status 401 es error de auth", () => {
|
||||
expect(new MetaApiError("x", { status: 401 }).isAuthError).toBe(true);
|
||||
});
|
||||
|
||||
it("code 190 es error de auth (token vencido)", () => {
|
||||
expect(new MetaApiError("x", { status: 400, code: 190 }).isAuthError).toBe(
|
||||
true
|
||||
);
|
||||
});
|
||||
|
||||
it("OAuthException solo NO basta (Meta la usa en errores transitorios)", () => {
|
||||
// Incidente 2026-08-03: un 500 con type OAuthException (código 2,
|
||||
// "service temporarily unavailable") marcaba el token como vencido y
|
||||
// bloqueaba TODO envío. El type por sí solo jamás decide.
|
||||
expect(
|
||||
new MetaApiError("x", { status: 400, type: "OAuthException" }).isAuthError
|
||||
).toBe(false);
|
||||
expect(
|
||||
new MetaApiError("x", { status: 500, code: 2, type: "OAuthException" })
|
||||
.isAuthError
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("OAuthException con código 190 sí es error de auth", () => {
|
||||
expect(
|
||||
new MetaApiError("x", { status: 400, code: 190, type: "OAuthException" })
|
||||
.isAuthError
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("un 5xx JAMÁS es error de auth, ni con código 190", () => {
|
||||
expect(new MetaApiError("x", { status: 500 }).isAuthError).toBe(false);
|
||||
expect(
|
||||
new MetaApiError("x", { status: 500, code: 190 }).isAuthError
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,117 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
CURRENCIES,
|
||||
CURRENCY_GROUPS,
|
||||
CURRENCY_OPTIONS,
|
||||
DEFAULT_CURRENCY,
|
||||
formatMoneyCents,
|
||||
isCurrency,
|
||||
parseMoneyToCents,
|
||||
sumable,
|
||||
} from "@/lib/money";
|
||||
|
||||
describe("parseMoneyToCents", () => {
|
||||
it("acepta lo que la gente teclea de verdad", () => {
|
||||
expect(parseMoneyToCents("12500")).toBe(1_250_000);
|
||||
expect(parseMoneyToCents("12,500")).toBe(1_250_000);
|
||||
expect(parseMoneyToCents("12,500.50")).toBe(1_250_050);
|
||||
expect(parseMoneyToCents("$12 500.50")).toBe(1_250_050);
|
||||
expect(parseMoneyToCents(" 900 ")).toBe(90_000);
|
||||
});
|
||||
|
||||
it("un decimal solo no se confunde con millares", () => {
|
||||
// "12.5" son doce cincuenta, no doce mil quinientos.
|
||||
expect(parseMoneyToCents("12.5")).toBe(1_250);
|
||||
expect(parseMoneyToCents("12,5")).toBe(1_250);
|
||||
});
|
||||
|
||||
it("trata el punto de millares como millares, no como decimales", () => {
|
||||
// "12.500" con tres dígitos detrás es doce mil quinientos.
|
||||
expect(parseMoneyToCents("12.500")).toBe(1_250_000);
|
||||
});
|
||||
|
||||
it("sin número reconocible devuelve null, no cero", () => {
|
||||
// Un 0 se leería como "este trato no vale nada", que es un dato distinto
|
||||
// de "nadie capturó el monto".
|
||||
expect(parseMoneyToCents("")).toBeNull();
|
||||
expect(parseMoneyToCents(" ")).toBeNull();
|
||||
expect(parseMoneyToCents("$")).toBeNull();
|
||||
expect(parseMoneyToCents("no sé")).toBeNull();
|
||||
});
|
||||
|
||||
it("el cero explícito sí es un cero", () => {
|
||||
expect(parseMoneyToCents("0")).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe("sumable", () => {
|
||||
it("solo suma lo que está en la moneda del negocio", () => {
|
||||
expect(sumable({ amountCents: 1000, currency: "MXN" }, "MXN")).toBe(true);
|
||||
expect(sumable({ amountCents: 1000, currency: "USD" }, "MXN")).toBe(false);
|
||||
});
|
||||
|
||||
it("un monto sin moneda se asume en la del negocio", () => {
|
||||
// Es el caso de los leads capturados antes de que existiera la columna.
|
||||
expect(sumable({ amountCents: 1000, currency: null }, "MXN")).toBe(true);
|
||||
});
|
||||
|
||||
it("sin monto no suma, aunque la moneda coincida", () => {
|
||||
expect(sumable({ amountCents: null, currency: "MXN" }, "MXN")).toBe(false);
|
||||
});
|
||||
|
||||
it("cambiar la moneda del negocio cambia lo sumable", () => {
|
||||
const monto = { amountCents: 1000, currency: "USD" };
|
||||
expect(sumable(monto, "MXN")).toBe(false);
|
||||
expect(sumable(monto, "USD")).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("formatMoneyCents", () => {
|
||||
it("formatea en la moneda pedida", () => {
|
||||
const out = formatMoneyCents(1_250_050, "MXN");
|
||||
expect(out).toContain("12,500.50");
|
||||
});
|
||||
|
||||
it("null entra, null sale: no inventa un $0.00", () => {
|
||||
expect(formatMoneyCents(null, "MXN")).toBeNull();
|
||||
expect(formatMoneyCents(undefined, "MXN")).toBeNull();
|
||||
});
|
||||
|
||||
it("una moneda que el runtime no conoce degrada sin romper la pantalla", () => {
|
||||
const out = formatMoneyCents(1_000, "XXX_INVALIDA");
|
||||
expect(out).toBe("10.00 XXX_INVALIDA");
|
||||
});
|
||||
});
|
||||
|
||||
describe("catálogo de monedas", () => {
|
||||
it("valida entradas basura", () => {
|
||||
expect(isCurrency("MXN")).toBe(true);
|
||||
expect(isCurrency("mxn")).toBe(false);
|
||||
expect(isCurrency("pesos")).toBe(false);
|
||||
expect(isCurrency(null)).toBe(false);
|
||||
});
|
||||
|
||||
it("cubre los países hispanohablantes y ninguna moneda se repite", () => {
|
||||
for (const code of ["MXN", "GTQ", "HNL", "NIO", "CRC", "PAB", "DOP", "COP", "VES", "PEN", "BOB", "CLP", "ARS", "UYU", "PYG", "BRL", "USD", "EUR"]) {
|
||||
expect(isCurrency(code), code).toBe(true);
|
||||
}
|
||||
expect(new Set(CURRENCIES).size).toBe(CURRENCIES.length);
|
||||
});
|
||||
|
||||
it("la predeterminada existe y ningún grupo del selector queda vacío", () => {
|
||||
expect(isCurrency(DEFAULT_CURRENCY)).toBe(true);
|
||||
for (const g of CURRENCY_GROUPS) {
|
||||
expect(CURRENCY_OPTIONS.some((c) => c.group === g.id), g.id).toBe(true);
|
||||
}
|
||||
});
|
||||
|
||||
it("cada moneda tiene grupo y el runtime sabe formatearla", () => {
|
||||
const groups = new Set<string>(CURRENCY_GROUPS.map((g) => g.id));
|
||||
for (const c of CURRENCY_OPTIONS) {
|
||||
expect(groups.has(c.group), c.code).toBe(true);
|
||||
// Sin símbolo significaría que Intl no conoce el código: caería al
|
||||
// «1500.00 XXX» de emergencia.
|
||||
expect(formatMoneyCents(150_000, c.code), c.code).not.toMatch(new RegExp(`\\d ${c.code}$`));
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,168 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
appNavGroups,
|
||||
isNavActive,
|
||||
fechaEnEspanol,
|
||||
SETTINGS_GROUP_TITLE,
|
||||
SETTINGS_ITEM,
|
||||
settingsSections,
|
||||
tituloDeRuta,
|
||||
} from "@/lib/nav";
|
||||
|
||||
/**
|
||||
* #87 — El menú agrupado y Ajustes en tres secciones. Lo que aparece y lo
|
||||
* que no lo deciden las banderas (`AGENDA`, `CHANNELS`, `ATRIBUCION`) y el
|
||||
* rol; aquí se afirma sobre el modelo, sin dibujar nada.
|
||||
*/
|
||||
|
||||
const labels = (groups: { items: { label: string }[] }[]) =>
|
||||
groups.map((g) => g.items.map((i) => i.label));
|
||||
|
||||
describe("barra lateral agrupada", () => {
|
||||
it("con todo apagado y como miembro: CRM & Trabajo y Negocio & IA", () => {
|
||||
const groups = appNavGroups({ role: "member" });
|
||||
expect(groups.map((g) => g.title)).toEqual(["CRM & Trabajo", "Negocio & IA"]);
|
||||
expect(labels(groups)).toEqual([
|
||||
["Bandeja", "Pipeline", "Contactos", "Resultados"],
|
||||
["Servicios y Precios", "Agente", "Laboratorio"],
|
||||
]);
|
||||
});
|
||||
|
||||
it("AGENDA añade «Citas y Llamadas» antes de Resultados", () => {
|
||||
const [trabajo] = appNavGroups({ agenda: true, role: "member" });
|
||||
expect(trabajo!.items.map((i) => i.label)).toEqual([
|
||||
"Bandeja",
|
||||
"Pipeline",
|
||||
"Contactos",
|
||||
"Citas y Llamadas",
|
||||
"Resultados",
|
||||
]);
|
||||
expect(trabajo!.items[3]!.href).toBe("/bookings");
|
||||
});
|
||||
|
||||
it("la guía de inicio cierra Negocio & IA solo para quien configura", () => {
|
||||
for (const role of ["owner", "admin"]) {
|
||||
const negocio = appNavGroups({ role })[1]!;
|
||||
expect(negocio.items.at(-1)).toMatchObject({ href: "/onboarding", label: "Guía de inicio" });
|
||||
}
|
||||
for (const role of ["member", null, undefined]) {
|
||||
const negocio = appNavGroups({ role })[1]!;
|
||||
expect(negocio.items.map((i) => i.href)).not.toContain("/onboarding");
|
||||
}
|
||||
});
|
||||
|
||||
it("solo la Bandeja lleva el contador y Ajustes va en «Configuración», fuera de los grupos", () => {
|
||||
const todos = appNavGroups({ agenda: true, role: "owner" }).flatMap((g) => g.items);
|
||||
expect(todos.filter((i) => i.badge).map((i) => i.href)).toEqual(["/inbox"]);
|
||||
expect(todos.map((i) => i.href)).not.toContain("/settings");
|
||||
expect(SETTINGS_ITEM.href).toBe("/settings");
|
||||
expect(SETTINGS_GROUP_TITLE).toBe("Configuración");
|
||||
for (const item of [...todos, SETTINGS_ITEM]) expect(item.icon).toBeDefined();
|
||||
});
|
||||
|
||||
it("una ruta hija activa su entrada, y /settings no activa nada más", () => {
|
||||
expect(isNavActive("/inbox/cv_123", "/inbox")).toBe(true);
|
||||
expect(isNavActive("/inbox", "/inbox")).toBe(true);
|
||||
expect(isNavActive("/inboxes", "/inbox")).toBe(false);
|
||||
expect(isNavActive("/settings/ai", "/settings")).toBe(true);
|
||||
expect(isNavActive("/settings/ai", "/agent")).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("barra superior: título y fecha", () => {
|
||||
it("el título sigue a la ruta", () => {
|
||||
expect(tituloDeRuta("/settings")).toBe("Ajustes");
|
||||
expect(tituloDeRuta("/settings/backups")).toBe("Ajustes");
|
||||
expect(tituloDeRuta("/services")).toBe("Servicios y Precios");
|
||||
expect(tituloDeRuta("/inbox/cv_1")).toBe("Bandeja");
|
||||
expect(tituloDeRuta("/pipeline")).toBe("Pipeline");
|
||||
expect(tituloDeRuta("/contacts")).toBe("Contactos");
|
||||
expect(tituloDeRuta("/desconocida", "Mi CRM")).toBe("Mi CRM");
|
||||
});
|
||||
|
||||
it("la fecha va en español y con mayúscula inicial", () => {
|
||||
const f = fechaEnEspanol(new Date("2026-12-04T18:00:00Z"), "America/Mexico_City");
|
||||
expect(f).toMatch(/^Viernes, 4 de diciembre de 2026$/);
|
||||
});
|
||||
});
|
||||
|
||||
describe("ajustes en tres secciones", () => {
|
||||
const links = (s: { title: string; links: { label: string }[] }[]) =>
|
||||
Object.fromEntries(s.map((x) => [x.title, x.links.map((l) => l.label)]));
|
||||
|
||||
it("con todo apagado: Canales, Agente y Negocio con lo mínimo", () => {
|
||||
const sections = settingsSections({});
|
||||
expect(sections.map((s) => s.title)).toEqual(["Canales", "Agente", "Negocio"]);
|
||||
expect(links(sections)).toEqual({
|
||||
Canales: ["WhatsApp"],
|
||||
Agente: ["IA"],
|
||||
Negocio: ["Marca", "Apariencia", "Plantillas", "Respuestas rápidas", "Equipo", "Respaldos"],
|
||||
});
|
||||
});
|
||||
|
||||
it("cada bandera añade su enlace en su sección y en ninguna otra", () => {
|
||||
// 023: con un canal social, "Estado" abre la sección.
|
||||
expect(links(settingsSections({ messenger: true }))).toEqual({
|
||||
Canales: ["Estado", "WhatsApp", "Messenger"],
|
||||
Agente: ["IA"],
|
||||
Negocio: ["Marca", "Apariencia", "Plantillas", "Respuestas rápidas", "Equipo", "Respaldos"],
|
||||
});
|
||||
expect(links(settingsSections({ instagram: true })).Canales).toEqual([
|
||||
"Estado",
|
||||
"WhatsApp",
|
||||
"Instagram",
|
||||
]);
|
||||
expect(
|
||||
links(settingsSections({ instagram: true, messenger: true, tiktok: true })).Canales
|
||||
).toEqual(["Estado", "WhatsApp", "Instagram", "Messenger", "TikTok"]);
|
||||
expect(links(settingsSections({ agenda: true }))).toEqual({
|
||||
Canales: ["WhatsApp"],
|
||||
Agente: ["IA", "Agenda"],
|
||||
Negocio: ["Marca", "Apariencia", "Plantillas", "Respuestas rápidas", "Equipo", "Respaldos"],
|
||||
});
|
||||
expect(links(settingsSections({ atribucion: true }))).toEqual({
|
||||
Canales: ["WhatsApp"],
|
||||
Agente: ["IA"],
|
||||
Negocio: ["Marca", "Apariencia", "Plantillas", "Respuestas rápidas", "Equipo", "Respaldos", "Anuncios"],
|
||||
});
|
||||
});
|
||||
|
||||
it("con todo encendido, cada pantalla de Ajustes tiene exactamente un enlace", () => {
|
||||
const all = settingsSections({
|
||||
agenda: true,
|
||||
atribucion: true,
|
||||
instagram: true,
|
||||
messenger: true,
|
||||
tiktok: true,
|
||||
})
|
||||
.flatMap((s) => s.links)
|
||||
.map((l) => l.href);
|
||||
expect(new Set(all).size).toBe(all.length);
|
||||
expect(all.sort()).toEqual(
|
||||
[
|
||||
"/settings/channels",
|
||||
"/settings/whatsapp",
|
||||
"/settings/instagram",
|
||||
"/settings/messenger",
|
||||
"/settings/tiktok",
|
||||
"/settings/ai",
|
||||
"/settings/calendar",
|
||||
"/settings/branding",
|
||||
"/settings/appearance",
|
||||
"/settings/templates",
|
||||
"/settings/quick-replies",
|
||||
"/settings/team",
|
||||
"/settings/backups",
|
||||
"/settings/ads",
|
||||
].sort()
|
||||
);
|
||||
});
|
||||
|
||||
it("el Laboratorio no está en Ajustes: sigue en el menú principal", () => {
|
||||
const hrefs = settingsSections({ agenda: true, atribucion: true, messenger: true })
|
||||
.flatMap((s) => s.links)
|
||||
.map((l) => l.href);
|
||||
expect(hrefs).not.toContain("/lab");
|
||||
expect(appNavGroups({ role: "owner" }).flatMap((g) => g.items).map((i) => i.href)).toContain("/lab");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,53 @@
|
||||
import { readFileSync } from "node:fs";
|
||||
import path from "node:path";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { MediaValidationError, validateOutgoing } from "@/server/whatsapp/media";
|
||||
import { MIME_NOTA_DE_VOZ, prepararAudioSaliente } from "@/server/whatsapp/nota-de-voz";
|
||||
|
||||
/** 044 — Lo que graba el compositor sale como lo acepta WhatsApp. */
|
||||
const webm = readFileSync(path.join(import.meta.dirname, "../fixtures/nota-chrome.webm"));
|
||||
|
||||
describe("prepararAudioSaliente", () => {
|
||||
it("la grabación de Chrome (WebM) sale en Ogg/Opus y como nota de voz", () => {
|
||||
const { file, voice } = prepararAudioSaliente(
|
||||
{ data: webm, mimeType: "audio/webm;codecs=opus", fileName: "nota-de-voz.webm" },
|
||||
true
|
||||
);
|
||||
expect(voice).toBe(true);
|
||||
expect(file.mimeType).toBe(MIME_NOTA_DE_VOZ);
|
||||
expect(file.fileName).toBe("nota-de-voz.ogg");
|
||||
expect(file.data.subarray(0, 4).toString("latin1")).toBe("OggS");
|
||||
// Y ya pasa la validación de la Cloud API como audio.
|
||||
expect(validateOutgoing(file.mimeType, file.data.byteLength)).toBe("audio");
|
||||
});
|
||||
|
||||
it("un WebM subido con el clip también se convierte, pero no es nota de voz", () => {
|
||||
const { file, voice } = prepararAudioSaliente(
|
||||
{ data: webm, mimeType: "audio/webm", fileName: "reunion.webm" },
|
||||
false
|
||||
);
|
||||
expect(voice).toBe(false);
|
||||
expect(file.fileName).toBe("reunion.ogg");
|
||||
});
|
||||
|
||||
it("Firefox ya graba Ogg: pasa tal cual, con el MIME que pide Meta", () => {
|
||||
const ogg = Buffer.from("OggS…");
|
||||
const { file, voice } = prepararAudioSaliente({ data: ogg, mimeType: "audio/ogg" }, true);
|
||||
expect(voice).toBe(true);
|
||||
expect(file.mimeType).toBe(MIME_NOTA_DE_VOZ);
|
||||
expect(file.data).toBe(ogg);
|
||||
});
|
||||
|
||||
it("Safari graba MP4/AAC: sale como audio normal, no como nota de voz", () => {
|
||||
const mp4 = Buffer.from("....ftypM4A ");
|
||||
const { file, voice } = prepararAudioSaliente({ data: mp4, mimeType: "audio/mp4" }, true);
|
||||
expect(voice).toBe(false);
|
||||
expect(file.mimeType).toBe("audio/mp4");
|
||||
});
|
||||
|
||||
it("un WebM roto se rechaza con el motivo, no sale como documento", () => {
|
||||
expect(() =>
|
||||
prepararAudioSaliente({ data: Buffer.from("no es webm"), mimeType: "audio/webm" }, true)
|
||||
).toThrow(MediaValidationError);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,80 @@
|
||||
import { readdirSync, readFileSync, statSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { intercalarNotas, puedeBorrarNota } from "@/lib/notas";
|
||||
import { notaSchema } from "@/server/notas";
|
||||
|
||||
/**
|
||||
* 050 — Notas internas: el equipo anota dentro del hilo y el cliente nunca lo
|
||||
* ve. La garantía de fondo es que viven en su propia tabla y que nada de lo
|
||||
* que habla con Meta, con el cerebro o cuenta respuestas las lee.
|
||||
*/
|
||||
|
||||
describe("intercalar notas entre mensajes", () => {
|
||||
const m = (t: string) => ({ createdAt: `2026-10-23T10:${t}:00.000Z` });
|
||||
const n = (id: string, t: string) => ({ id, createdAt: `2026-10-23T10:${t}:00.000Z` });
|
||||
|
||||
it("cada nota va antes del primer mensaje posterior; las últimas, al final", () => {
|
||||
const mensajes = [m("00"), m("05"), m("10")];
|
||||
const r = intercalarNotas(mensajes, [n("b", "07"), n("a", "02"), n("z", "30")]);
|
||||
expect(r.antes.map((x) => x.map((y) => y.id))).toEqual([[], ["a"], ["b"]]);
|
||||
expect(r.alFinal.map((x) => x.id)).toEqual(["z"]);
|
||||
});
|
||||
|
||||
it("con la misma hora que un mensaje, la nota va después (se escribió leyéndolo)", () => {
|
||||
const r = intercalarNotas([m("00"), m("05")], [n("a", "05")]);
|
||||
expect(r.antes.flat()).toEqual([]);
|
||||
expect(r.alFinal.map((x) => x.id)).toEqual(["a"]);
|
||||
});
|
||||
|
||||
it("sin mensajes, todas al final y por hora", () => {
|
||||
const r = intercalarNotas([], [n("b", "09"), n("a", "01")]);
|
||||
expect(r.alFinal.map((x) => x.id)).toEqual(["a", "b"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("quién borra una nota", () => {
|
||||
it("el autor, o quien configura", () => {
|
||||
expect(puedeBorrarNota("u1", "u1", false)).toBe(true);
|
||||
expect(puedeBorrarNota("u1", "u2", false)).toBe(false);
|
||||
expect(puedeBorrarNota("u1", "u2", true)).toBe(true);
|
||||
// Si la cuenta del autor ya no existe, solo quien configura.
|
||||
expect(puedeBorrarNota(null, "u2", false)).toBe(false);
|
||||
expect(puedeBorrarNota(null, "u2", true)).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("validación", () => {
|
||||
it("texto de 1 a 4 096 caracteres, sin espacios a los lados", () => {
|
||||
expect(notaSchema.safeParse({ texto: " " }).success).toBe(false);
|
||||
expect(notaSchema.safeParse({ texto: "x".repeat(4097) }).success).toBe(false);
|
||||
expect(notaSchema.safeParse({ texto: " ofrécele 5 % " }).data?.texto).toBe("ofrécele 5 %");
|
||||
});
|
||||
});
|
||||
|
||||
describe("guardarraíl: las notas nunca llegan al cliente ni al cerebro", () => {
|
||||
function archivos(dir: string): string[] {
|
||||
const out: string[] = [];
|
||||
for (const e of readdirSync(dir)) {
|
||||
const full = join(dir, e);
|
||||
if (statSync(full).isDirectory()) out.push(...archivos(full));
|
||||
else if (/\.tsx?$/.test(e)) out.push(full);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
const raiz = join(process.cwd(), "src", "server");
|
||||
const vigilados = [
|
||||
...["dispatch", "brains", "bot", "analytics", "lab"].flatMap((d) => archivos(join(raiz, d))),
|
||||
join(raiz, "inbox", "send.ts"),
|
||||
join(raiz, "inbox", "ingest.ts"),
|
||||
join(raiz, "inbox", "window.ts"),
|
||||
join(process.cwd(), "src", "lib", "meta", "client.ts"),
|
||||
];
|
||||
|
||||
it("envío, despacho, bot, Laboratorio, métricas y la ventana no mencionan las notas", () => {
|
||||
const culpables = vigilados.filter((f) =>
|
||||
/conversationNote|conversation_note|server\/notas/.test(readFileSync(f, "utf8"))
|
||||
);
|
||||
expect(culpables).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,104 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import {
|
||||
DocumentoClienteInvalido,
|
||||
esClienteUrl,
|
||||
idLocalDeClienteUrl,
|
||||
PREFIJO_CLIENTE_URL,
|
||||
validarDocumento,
|
||||
} from "@/server/oauth/cliente-por-url";
|
||||
import { metadatosServidor } from "@/server/oauth/nucleo";
|
||||
import { direccionPublica } from "@/server/oauth/red";
|
||||
|
||||
const MUSE = "https://platform.muse.ai/oauth/client-metadata.json";
|
||||
|
||||
/** El documento que publica Muse de Meta (leído el 2026-11-30). */
|
||||
const DOC_MUSE = {
|
||||
client_id: MUSE,
|
||||
client_name: "Muse",
|
||||
client_uri: "https://muse.ai/",
|
||||
logo_uri: "https://muse.ai/images/pwa_icons/any/512.png",
|
||||
redirect_uris: ["https://platform.muse.ai/oauth/credential-test/callback"],
|
||||
grant_types: ["authorization_code", "refresh_token"],
|
||||
response_types: ["code"],
|
||||
token_endpoint_auth_method: "none",
|
||||
};
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllEnvs();
|
||||
});
|
||||
|
||||
describe("client_id por URL (Client ID Metadata Document)", () => {
|
||||
it("reconoce la URL de Muse y no un id registrado", () => {
|
||||
expect(esClienteUrl(MUSE)).toBe(true);
|
||||
expect(esClienteUrl("vc_abc123")).toBe(false);
|
||||
expect(esClienteUrl(null)).toBe(false);
|
||||
});
|
||||
|
||||
it("exige https con ruta, sin credenciales ni fragmento", () => {
|
||||
expect(esClienteUrl("https://muse.ai")).toBe(false);
|
||||
expect(esClienteUrl("https://muse.ai/")).toBe(false);
|
||||
expect(esClienteUrl("https://u:p@muse.ai/c.json")).toBe(false);
|
||||
expect(esClienteUrl("https://muse.ai/c.json#x")).toBe(false);
|
||||
expect(esClienteUrl("http://muse.ai/c.json")).toBe(false);
|
||||
expect(esClienteUrl(`https://muse.ai/${"a".repeat(600)}`)).toBe(false);
|
||||
});
|
||||
|
||||
it("http de loopback solo con los mocks encendidos (E2E local)", () => {
|
||||
expect(esClienteUrl("http://127.0.0.1:4999/c.json")).toBe(false);
|
||||
vi.stubEnv("WA_MOCK_ENABLED", "true");
|
||||
vi.stubEnv("NODE_ENV", "test");
|
||||
expect(esClienteUrl("http://127.0.0.1:4999/c.json")).toBe(true);
|
||||
expect(esClienteUrl("http://10.0.0.5/c.json")).toBe(false);
|
||||
});
|
||||
|
||||
it("id local estable, distinto por negocio y con su propio prefijo", () => {
|
||||
const a = idLocalDeClienteUrl("org_a", MUSE);
|
||||
expect(a).toBe(idLocalDeClienteUrl("org_a", MUSE));
|
||||
expect(a).not.toBe(idLocalDeClienteUrl("org_b", MUSE));
|
||||
expect(a.startsWith(PREFIJO_CLIENTE_URL)).toBe(true);
|
||||
expect(a.length).toBeLessThanOrEqual(64);
|
||||
});
|
||||
|
||||
it("acepta el documento real de Muse", () => {
|
||||
expect(validarDocumento(MUSE, DOC_MUSE)).toEqual({
|
||||
clientId: MUSE,
|
||||
nombre: "Muse",
|
||||
redirectUris: ["https://platform.muse.ai/oauth/credential-test/callback"],
|
||||
});
|
||||
});
|
||||
|
||||
it("rechaza un documento que dice ser de otra URL", () => {
|
||||
expect(() => validarDocumento("https://malo.example/c.json", DOC_MUSE)).toThrow(DocumentoClienteInvalido);
|
||||
});
|
||||
|
||||
it("rechaza clientes con secreto, sin código o con regresos inválidos", () => {
|
||||
expect(() => validarDocumento(MUSE, { ...DOC_MUSE, token_endpoint_auth_method: "client_secret_post" })).toThrow(
|
||||
DocumentoClienteInvalido
|
||||
);
|
||||
expect(() => validarDocumento(MUSE, { ...DOC_MUSE, grant_types: ["client_credentials"] })).toThrow(DocumentoClienteInvalido);
|
||||
expect(() => validarDocumento(MUSE, { ...DOC_MUSE, redirect_uris: ["javascript:alert(1)"] })).toThrow(DocumentoClienteInvalido);
|
||||
expect(() => validarDocumento(MUSE, { ...DOC_MUSE, redirect_uris: [] })).toThrow(DocumentoClienteInvalido);
|
||||
expect(() => validarDocumento(MUSE, "no es un objeto")).toThrow(DocumentoClienteInvalido);
|
||||
});
|
||||
|
||||
it("sin nombre usa el host del documento", () => {
|
||||
const { client_name: _, ...sinNombre } = DOC_MUSE;
|
||||
expect(validarDocumento(MUSE, sinNombre).nombre).toBe("platform.muse.ai");
|
||||
});
|
||||
|
||||
it("los metadatos del servidor lo anuncian", () => {
|
||||
expect(metadatosServidor("https://a.vocerocrm.com").client_id_metadata_document_supported).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("direccionPublica (guardia de la descarga)", () => {
|
||||
it("acepta direcciones de Internet", () => {
|
||||
expect(direccionPublica("157.240.22.35")).toBe(true);
|
||||
expect(direccionPublica("2a03:2880:f12f:83:face:b00c:0:25de")).toBe(true);
|
||||
});
|
||||
it("rechaza la red interna, loopback, metadatos de nube e IPv4 escondidas en IPv6", () => {
|
||||
for (const ip of ["127.0.0.1", "10.0.0.5", "172.18.0.2", "192.168.1.1", "169.254.169.254", "::1", "::ffff:10.0.0.1", "fd00::1", "nombre"]) {
|
||||
expect(direccionPublica(ip)).toBe(false);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,120 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
challengeValido,
|
||||
metadatosRecurso,
|
||||
metadatosServidor,
|
||||
normalizar,
|
||||
nuevoToken,
|
||||
parsearScopes,
|
||||
PREFIJO_ACCESO,
|
||||
recursoValido,
|
||||
redirectCoincide,
|
||||
redirectRegistrable,
|
||||
siguienteSeguro,
|
||||
urlDeRegreso,
|
||||
urlMetadatosRecurso,
|
||||
verificarPkce,
|
||||
} from "@/server/oauth/nucleo";
|
||||
|
||||
/**
|
||||
* 069 — Las piezas puras del OAuth del MCP. El camino completo (registro,
|
||||
* consentimiento, token, MCP) lo prueba `scripts/e2e-api-mcp.mjs` con
|
||||
* la app viva; aquí, que cada regla diga lo que dice.
|
||||
*/
|
||||
|
||||
const ORIGEN = "https://crm.negocio.test";
|
||||
|
||||
describe("PKCE S256", () => {
|
||||
const verifier = "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk";
|
||||
const challenge = createHash("sha256").update(verifier).digest("base64url");
|
||||
|
||||
it("acepta el verifier que corresponde", () => {
|
||||
expect(challengeValido(challenge)).toBe(true);
|
||||
expect(verificarPkce(verifier, challenge)).toBe(true);
|
||||
});
|
||||
it("rechaza otro verifier, uno corto o `plain`", () => {
|
||||
expect(verificarPkce(`${verifier.slice(0, -1)}A`, challenge)).toBe(false);
|
||||
expect(verificarPkce("corto", challenge)).toBe(false);
|
||||
expect(verificarPkce(verifier, verifier)).toBe(false);
|
||||
expect(challengeValido("x")).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("scopes", () => {
|
||||
it("sin scope o con uno desconocido se piden todos", () => {
|
||||
expect(parsearScopes(undefined)).toEqual(["read", "operate", "configure"]);
|
||||
expect(parsearScopes("openid profile")).toEqual(["read", "operate", "configure"]);
|
||||
});
|
||||
it("leer va siempre y `send` no existe por OAuth", () => {
|
||||
expect(parsearScopes("configure")).toEqual(["read", "configure"]);
|
||||
expect(parsearScopes("send operate")).toEqual(["read", "operate"]);
|
||||
expect(normalizar(["send"])).toEqual(["read"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("redirect_uri", () => {
|
||||
it("registra https, loopback http y esquemas de app; no http público ni javascript", () => {
|
||||
expect(redirectRegistrable("https://claude.ai/api/mcp/auth_callback")).toBe(true);
|
||||
expect(redirectRegistrable("http://localhost:53682/callback")).toBe(true);
|
||||
expect(redirectRegistrable("http://127.0.0.1/callback")).toBe(true);
|
||||
expect(redirectRegistrable("cursor://anysphere.cursor-retrieval/oauth/callback")).toBe(true);
|
||||
expect(redirectRegistrable("http://evil.example/callback")).toBe(false);
|
||||
expect(redirectRegistrable("javascript:alert(1)")).toBe(false);
|
||||
expect(redirectRegistrable("https://claude.ai/cb#x")).toBe(false);
|
||||
expect(redirectRegistrable("no es url")).toBe(false);
|
||||
});
|
||||
it("coincide exacto; en loopback el puerto puede cambiar (RFC 8252)", () => {
|
||||
const reg = ["https://claude.ai/api/mcp/auth_callback", "http://localhost:3118/callback"];
|
||||
expect(redirectCoincide(reg, "https://claude.ai/api/mcp/auth_callback")).toBe(true);
|
||||
expect(redirectCoincide(reg, "http://localhost:61000/callback")).toBe(true);
|
||||
expect(redirectCoincide(reg, "http://localhost:61000/otra")).toBe(false);
|
||||
expect(redirectCoincide(reg, "https://claude.ai/api/mcp/auth_callback/../x")).toBe(false);
|
||||
expect(redirectCoincide(reg, "https://evil.example/api/mcp/auth_callback")).toBe(false);
|
||||
});
|
||||
it("la URL de regreso conserva su query y suma code, state e iss", () => {
|
||||
const u = new URL(urlDeRegreso("https://app.example/cb?x=1", { code: "c", state: "s", iss: ORIGEN, error: undefined }));
|
||||
expect(Object.fromEntries(u.searchParams)).toEqual({ x: "1", code: "c", state: "s", iss: ORIGEN });
|
||||
});
|
||||
});
|
||||
|
||||
describe("metadatos", () => {
|
||||
it("el recurso es el MCP y su servidor de autorización es la propia instancia", () => {
|
||||
const r = metadatosRecurso(ORIGEN);
|
||||
expect(r.resource).toBe(`${ORIGEN}/api/v1/mcp`);
|
||||
expect(r.authorization_servers).toEqual([ORIGEN]);
|
||||
expect(urlMetadatosRecurso(ORIGEN)).toBe(`${ORIGEN}/.well-known/oauth-protected-resource/api/v1/mcp`);
|
||||
});
|
||||
it("el servidor anuncia PKCE S256, registro dinámico, revocación y clientes públicos", () => {
|
||||
const s = metadatosServidor(ORIGEN);
|
||||
expect(s.issuer).toBe(ORIGEN);
|
||||
expect(s.code_challenge_methods_supported).toEqual(["S256"]);
|
||||
expect(s.token_endpoint_auth_methods_supported).toEqual(["none"]);
|
||||
expect(s.registration_endpoint).toBe(`${ORIGEN}/api/oauth/register`);
|
||||
expect(s.revocation_endpoint).toBe(`${ORIGEN}/api/oauth/revoke`);
|
||||
expect(s.authorization_endpoint).toBe(`${ORIGEN}/oauth/authorize`);
|
||||
});
|
||||
it("resource: el MCP, el origen o nada; otro servidor no", () => {
|
||||
expect(recursoValido(ORIGEN, undefined)).toBe(true);
|
||||
expect(recursoValido(ORIGEN, `${ORIGEN}/api/v1/mcp`)).toBe(true);
|
||||
expect(recursoValido(ORIGEN, `${ORIGEN}/`)).toBe(true);
|
||||
expect(recursoValido(ORIGEN, "https://otra.vocerocrm.com/api/v1/mcp")).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("tokens y login", () => {
|
||||
it("un token nuevo lleva su prefijo y se guarda por hash", () => {
|
||||
const t = nuevoToken(PREFIJO_ACCESO);
|
||||
expect(t.valor.startsWith("vat_")).toBe(true);
|
||||
expect(t.hash).toBe(createHash("sha256").update(t.valor).digest("hex"));
|
||||
expect(nuevoToken(PREFIJO_ACCESO).valor).not.toBe(t.valor);
|
||||
});
|
||||
it("el login solo vuelve a la pantalla de consentimiento, nunca a otro sitio", () => {
|
||||
expect(siguienteSeguro("/oauth/authorize?client_id=vc_1")).toBe("/oauth/authorize?client_id=vc_1");
|
||||
expect(siguienteSeguro("https://evil.example")).toBeNull();
|
||||
expect(siguienteSeguro("//evil.example/oauth/authorize?")).toBeNull();
|
||||
expect(siguienteSeguro("/oauth/authorize?x=//evil")).toBeNull();
|
||||
expect(siguienteSeguro("/inbox")).toBeNull();
|
||||
expect(siguienteSeguro(["/oauth/authorize?a"])).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,61 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
findOffered,
|
||||
sameInstant,
|
||||
type OfferedSlot,
|
||||
} from "@/server/agenda/offers";
|
||||
|
||||
/**
|
||||
* 015 — La regla INNEGOCIABLE: solo se reserva lo que se ofreció, comparando
|
||||
* por instante EXACTO. Estos tests fijan lo que un LLM no puede saltarse.
|
||||
*/
|
||||
|
||||
const OFFERS: OfferedSlot[] = [
|
||||
{ startUtc: "2026-08-05T15:00:00.000Z", label: "mié 5 ago, 09:00" },
|
||||
{ startUtc: "2026-08-05T15:30:00.000Z", label: "mié 5 ago, 09:30" },
|
||||
{ startUtc: "2026-08-06T16:00:00.000Z", label: "jue 6 ago, 10:00" },
|
||||
];
|
||||
|
||||
describe("findOffered", () => {
|
||||
it("acepta un instante ofrecido", () => {
|
||||
expect(findOffered(OFFERS, "2026-08-05T15:30:00.000Z")?.label).toBe(
|
||||
"mié 5 ago, 09:30"
|
||||
);
|
||||
});
|
||||
|
||||
it("acepta el MISMO instante escrito con otro offset", () => {
|
||||
// 09:00 en México es el mismo instante que 15:00Z: es el mismo hueco.
|
||||
expect(findOffered(OFFERS, "2026-08-05T09:00:00.000-06:00")).not.toBeNull();
|
||||
});
|
||||
|
||||
it("rechaza un instante que no se ofreció, aunque sea cercano", () => {
|
||||
// Un minuto de diferencia NO es el hueco ofrecido.
|
||||
expect(findOffered(OFFERS, "2026-08-05T15:31:00.000Z")).toBeNull();
|
||||
// Un horario perfectamente válido pero nunca ofrecido tampoco vale.
|
||||
expect(findOffered(OFFERS, "2026-08-05T18:00:00.000Z")).toBeNull();
|
||||
});
|
||||
|
||||
it("rechaza basura sin lanzar (el modelo alucinó el formato)", () => {
|
||||
expect(findOffered(OFFERS, "el martes a las 10")).toBeNull();
|
||||
expect(findOffered(OFFERS, "")).toBeNull();
|
||||
});
|
||||
|
||||
it("sin oferta previa no hay nada reservable", () => {
|
||||
expect(findOffered([], "2026-08-05T15:00:00.000Z")).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("sameInstant", () => {
|
||||
it("compara instantes, no cadenas", () => {
|
||||
expect(
|
||||
sameInstant("2026-08-05T15:00:00.000Z", "2026-08-05T09:00:00-06:00")
|
||||
).toBe(true);
|
||||
expect(
|
||||
sameInstant("2026-08-05T15:00:00.000Z", "2026-08-05T15:00:01.000Z")
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("una fecha inválida nunca es igual a nada", () => {
|
||||
expect(sameInstant("nope", "2026-08-05T15:00:00.000Z")).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,144 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import {
|
||||
CABECERA_DISPATCH,
|
||||
CABECERA_EVENTO,
|
||||
CABECERA_FIRMA,
|
||||
CABECERA_ORG,
|
||||
construirEventoOlvido,
|
||||
firmarCuerpo,
|
||||
} from "@/server/brains/contract";
|
||||
import { avisarOlvido } from "@/server/brains/deliver";
|
||||
|
||||
/**
|
||||
* 026 — El contrato del olvido, fijado byte a byte.
|
||||
*
|
||||
* `CUERPO_GEMELO` y `FIRMA_GEMELA` están copiados de
|
||||
* `nea-agent/tests/test_olvido.py` (y de `tests/unit/olvido-contrato.test.ts`
|
||||
* de vocerocrm-cloud): es el contrato entre los repositorios. Cambiar uno
|
||||
* obliga a cambiar los otros. Si esta prueba falla, el cerebro deja de
|
||||
* entender el aviso o de aceptar su firma.
|
||||
*/
|
||||
const SECRETO_GEMELO = "secreto-gemelo-del-olvido";
|
||||
const CUERPO_GEMELO =
|
||||
'{"type":"conversation.deleted","eventId":"olv_gemelo1",' +
|
||||
'"organization":{"id":"org_gemela","slug":"gemela"},' +
|
||||
'"conversation":{"id":"cv_gemela1","channel":"whatsapp"},' +
|
||||
'"contact":{"id":"ct_gemelo1","identity":"5215550001111"},' +
|
||||
'"deletedAt":"2026-10-04T12:00:00.000Z"}';
|
||||
const FIRMA_GEMELA =
|
||||
"sha256=72adddfb8dbc0ad6f091adff55132be228ec4be16be05fb4dde9b34010b65ffa";
|
||||
|
||||
const evento = () =>
|
||||
construirEventoOlvido({
|
||||
eventId: "olv_gemelo1",
|
||||
organization: { id: "org_gemela", slug: "gemela" },
|
||||
conversation: { id: "cv_gemela1", channel: "whatsapp" },
|
||||
contact: { id: "ct_gemelo1", identity: "5215550001111" },
|
||||
deletedAt: new Date("2026-10-04T12:00:00.000Z"),
|
||||
});
|
||||
|
||||
describe("026 · el evento conversation.deleted", () => {
|
||||
it("el cuerpo es el gemelo, byte a byte y en ese orden de claves", () => {
|
||||
expect(JSON.stringify(evento())).toBe(CUERPO_GEMELO);
|
||||
});
|
||||
|
||||
it("la firma es la gemela", () => {
|
||||
expect(firmarCuerpo(CUERPO_GEMELO, SECRETO_GEMELO)).toBe(FIRMA_GEMELA);
|
||||
});
|
||||
|
||||
it("no lleva nada de lo borrado: solo con qué encontrarlo", () => {
|
||||
expect(Object.keys(evento())).toEqual([
|
||||
"type",
|
||||
"eventId",
|
||||
"organization",
|
||||
"conversation",
|
||||
"contact",
|
||||
"deletedAt",
|
||||
]);
|
||||
});
|
||||
|
||||
it("una organización sin slug viaja con slug null, no sin la clave", () => {
|
||||
const e = construirEventoOlvido({
|
||||
eventId: "olv_1",
|
||||
organization: { id: "org_1", slug: null },
|
||||
conversation: { id: "cv_1", channel: "instagram" },
|
||||
contact: { id: "ct_1", identity: "ig:123" },
|
||||
deletedAt: new Date("2026-10-13T00:00:00.000Z"),
|
||||
});
|
||||
expect(JSON.stringify(e)).toContain('"organization":{"id":"org_1","slug":null}');
|
||||
});
|
||||
});
|
||||
|
||||
describe("026 · avisarOlvido", () => {
|
||||
const destino = { url: "http://cerebro.test/vocero/dispatch", secret: SECRETO_GEMELO };
|
||||
|
||||
it("manda UN POST con el cuerpo gemelo, su firma y las cabeceras del evento", async () => {
|
||||
const fetchImpl = vi.fn(async () => new Response(null, { status: 204 }));
|
||||
const r = await avisarOlvido(evento(), { destino, fetchImpl: fetchImpl as never });
|
||||
expect(r).toBe("avisado");
|
||||
expect(fetchImpl).toHaveBeenCalledTimes(1);
|
||||
|
||||
const [url, init] = fetchImpl.mock.calls[0] as unknown as [string, RequestInit];
|
||||
expect(url).toBe(destino.url);
|
||||
expect(init.method).toBe("POST");
|
||||
expect(init.body).toBe(CUERPO_GEMELO);
|
||||
expect(init.redirect).toBe("manual");
|
||||
const h = init.headers as Record<string, string>;
|
||||
expect(h[CABECERA_FIRMA]).toBe(FIRMA_GEMELA);
|
||||
expect(h[CABECERA_EVENTO]).toBe("conversation.deleted");
|
||||
expect(h[CABECERA_ORG]).toBe("gemela");
|
||||
// No es un despacho: no lleva su id.
|
||||
expect(h[CABECERA_DISPATCH]).toBeUndefined();
|
||||
});
|
||||
|
||||
it("sin slug, la cabecera de organización lleva el id", async () => {
|
||||
const fetchImpl = vi.fn(async () => new Response(null, { status: 200 }));
|
||||
const e = construirEventoOlvido({
|
||||
eventId: "olv_1",
|
||||
organization: { id: "org_1", slug: null },
|
||||
conversation: { id: "cv_1", channel: "whatsapp" },
|
||||
contact: { id: "ct_1", identity: "521" },
|
||||
deletedAt: new Date(),
|
||||
});
|
||||
await avisarOlvido(e, { destino, fetchImpl: fetchImpl as never });
|
||||
const [, init] = fetchImpl.mock.calls[0] as unknown as [string, RequestInit];
|
||||
expect((init.headers as Record<string, string>)[CABECERA_ORG]).toBe("org_1");
|
||||
});
|
||||
|
||||
it("un cerebro que contesta 4xx o 5xx no confirmó, y NO se reintenta", async () => {
|
||||
for (const status of [400, 404, 500, 503]) {
|
||||
const fetchImpl = vi.fn(async () => new Response(null, { status }));
|
||||
expect(await avisarOlvido(evento(), { destino, fetchImpl: fetchImpl as never })).toBe(
|
||||
"sin_confirmar"
|
||||
);
|
||||
expect(fetchImpl).toHaveBeenCalledTimes(1);
|
||||
}
|
||||
});
|
||||
|
||||
it("un cerebro caído o que no contesta a tiempo no confirmó, y no lanza", async () => {
|
||||
const caido = vi.fn(async () => {
|
||||
throw new Error("ECONNREFUSED");
|
||||
});
|
||||
expect(await avisarOlvido(evento(), { destino, fetchImpl: caido as never })).toBe(
|
||||
"sin_confirmar"
|
||||
);
|
||||
|
||||
const lento = vi.fn(
|
||||
(_url: string, init: RequestInit) =>
|
||||
new Promise<Response>((_res, rej) => {
|
||||
init.signal?.addEventListener("abort", () => rej(new Error("abortado")));
|
||||
})
|
||||
);
|
||||
expect(
|
||||
await avisarOlvido(evento(), { destino, fetchImpl: lento as never, timeoutMs: 20 })
|
||||
).toBe("sin_confirmar");
|
||||
});
|
||||
|
||||
it("sin despacho no hay a quién avisar", async () => {
|
||||
const fetchImpl = vi.fn();
|
||||
expect(await avisarOlvido(evento(), { destino: null, fetchImpl: fetchImpl as never })).toBe(
|
||||
"no_aplica"
|
||||
);
|
||||
expect(fetchImpl).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,138 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
/**
|
||||
* #86 — La guía de inicio: de los pasos verificados (`onboardingStatus`) a
|
||||
* lo que ve el dueño, y cuándo es la primera pantalla. Puerto de la prueba de
|
||||
* Vocero Cloud con los pasos de la raíz: aquí no hay modelo de plataforma,
|
||||
* dueño invitado, cerebro compartido ni cobertura.
|
||||
*/
|
||||
|
||||
const onboardingStatus = vi.hoisted(() => vi.fn());
|
||||
vi.mock("@/server/onboarding/status", () => ({ onboardingStatus }));
|
||||
|
||||
import { GUIA_DEL_PAR, guideFirst, guideFrom } from "@/server/onboarding/guide";
|
||||
import type { ReadinessStep } from "@/server/onboarding/status";
|
||||
|
||||
const step = (
|
||||
key: ReadinessStep["key"],
|
||||
status: ReadinessStep["status"],
|
||||
extra: Partial<ReadinessStep> = {}
|
||||
): ReadinessStep => ({
|
||||
key,
|
||||
label: key,
|
||||
status,
|
||||
nextAction: "",
|
||||
href: null,
|
||||
problem: null,
|
||||
...extra,
|
||||
});
|
||||
|
||||
const all = (overrides: Partial<Record<ReadinessStep["key"], ReadinessStep["status"]>> = {}) =>
|
||||
(["profile", "ai", "whatsapp", "brain", "calendar"] as const).map((k) =>
|
||||
step(k, overrides[k] ?? "ready", {
|
||||
nextAction:
|
||||
k === "profile"
|
||||
? "Dale un nombre y escribe sus instrucciones o carga conocimiento del negocio"
|
||||
: "",
|
||||
})
|
||||
);
|
||||
|
||||
describe("guía de inicio", () => {
|
||||
it("son cinco pasos en el orden pedido: agente, IA, número, tu agente, agenda", () => {
|
||||
const guide = guideFrom({ steps: all(), enabled: false });
|
||||
expect(guide.steps.map((s) => s.key)).toEqual(["agent", "ai", "whatsapp", "brain", "calendar"]);
|
||||
expect(guide.steps.map((s) => s.href)).toEqual([
|
||||
"/agent",
|
||||
"/settings/ai",
|
||||
"/settings/whatsapp",
|
||||
GUIA_DEL_PAR,
|
||||
"/settings/calendar",
|
||||
]);
|
||||
expect(guide).toMatchObject({ complete: true, enabled: false, brainConnected: true });
|
||||
});
|
||||
|
||||
it("036 — «Conecta tu agente» es opcional: sin él la guía se completa (bandeja manual)", () => {
|
||||
const steps = all({ brain: "pending" });
|
||||
steps[3] = step("brain", "pending", { nextAction: "Levanta tu agente", problem: null });
|
||||
const guide = guideFrom({ steps, enabled: false });
|
||||
const brain = guide.steps.find((s) => s.key === "brain");
|
||||
expect(brain).toMatchObject({ done: false, optional: true, hint: "Levanta tu agente" });
|
||||
expect(guide).toMatchObject({ complete: true, brainConnected: false });
|
||||
});
|
||||
|
||||
it("sin agenda en la instancia el paso desaparece (no se pinta «no aplica»)", () => {
|
||||
const guide = guideFrom({ steps: all({ calendar: "not_applicable" }), enabled: false });
|
||||
expect(guide.steps.map((s) => s.key)).toEqual(["agent", "ai", "whatsapp", "brain"]);
|
||||
expect(guide.complete).toBe(true);
|
||||
});
|
||||
|
||||
it("el agente necesita perfil, y dice qué falta", () => {
|
||||
const sinPerfil = guideFrom({ steps: all({ profile: "pending" }), enabled: false });
|
||||
expect(sinPerfil.steps[0]?.done).toBe(false);
|
||||
expect(sinPerfil.steps[0]?.hint).toMatch(/nombre/);
|
||||
expect(sinPerfil.complete).toBe(false);
|
||||
});
|
||||
|
||||
it("una conexión pendiente deja la guía incompleta", () => {
|
||||
for (const key of ["ai", "whatsapp", "calendar"] as const) {
|
||||
expect(guideFrom({ steps: all({ [key]: "pending" }), enabled: false }).complete, key).toBe(
|
||||
false
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
it("lo que está mal (llave rechazada, token vencido, conector sin credencial) sale como pista", () => {
|
||||
const steps = all();
|
||||
steps[1] = step("ai", "pending", { problem: "El proveedor rechazó tu llave." });
|
||||
steps[2] = step("whatsapp", "pending", { problem: "Meta dejó de aceptar el token." });
|
||||
steps[3] = step("brain", "pending", { problem: "Falta BOT_API_KEY." });
|
||||
steps[4] = step("calendar", "pending", { problem: "Elegiste Zoom pero no está conectado." });
|
||||
const guide = guideFrom({ steps, enabled: false });
|
||||
expect(guide.steps.map((s) => s.hint)).toEqual([
|
||||
null,
|
||||
"El proveedor rechazó tu llave.",
|
||||
"Meta dejó de aceptar el token.",
|
||||
"Falta BOT_API_KEY.",
|
||||
"Elegiste Zoom pero no está conectado.",
|
||||
]);
|
||||
// Un conector desconocido también bloquea: no es «listo» ni «no aplica».
|
||||
steps[4] = step("calendar", "unsupported", { problem: "El conector no existe." });
|
||||
expect(guideFrom({ steps, enabled: false }).complete).toBe(false);
|
||||
});
|
||||
|
||||
it("un paso listo no enseña pista aunque la tenga guardada", () => {
|
||||
const steps = all();
|
||||
steps[0] = step("profile", "ready", { nextAction: "Revisado" });
|
||||
expect(guideFrom({ steps, enabled: false }).steps[0]?.hint).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("guideFirst: ¿la guía es la primera pantalla?", () => {
|
||||
beforeEach(() => onboardingStatus.mockReset());
|
||||
|
||||
it("un miembro del equipo nunca la ve: no puede hacer ninguno de los pasos", async () => {
|
||||
expect(await guideFirst({ organizationId: "org_1", role: "member" })).toBe(false);
|
||||
expect(onboardingStatus).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("al dueño lo manda a la guía mientras falte un paso", async () => {
|
||||
onboardingStatus.mockResolvedValue({ steps: all({ whatsapp: "pending" }), enabled: false });
|
||||
expect(await guideFirst({ organizationId: "org_1", role: "owner" })).toBe(true);
|
||||
});
|
||||
|
||||
it("…y también con todo listo pero el agente apagado: falta encenderlo", async () => {
|
||||
onboardingStatus.mockResolvedValue({ steps: all(), enabled: false });
|
||||
expect(await guideFirst({ organizationId: "org_1", role: "owner" })).toBe(true);
|
||||
});
|
||||
|
||||
it("036 — una bandeja manual (sin cerebro) no se queda atrapada en la guía", async () => {
|
||||
onboardingStatus.mockResolvedValue({ steps: all({ brain: "pending" }), enabled: false });
|
||||
expect(await guideFirst({ organizationId: "org_1", role: "owner" })).toBe(false);
|
||||
});
|
||||
|
||||
it("con todo listo y el agente encendido se entra a la Bandeja como siempre", async () => {
|
||||
onboardingStatus.mockResolvedValue({ steps: all(), enabled: true });
|
||||
expect(await guideFirst({ organizationId: "org_1", role: "owner" })).toBe(false);
|
||||
expect(await guideFirst({ organizationId: "org_1", role: "admin" })).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,95 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
/**
|
||||
* #86 — Quién entra a la guía y a dónde manda la raíz. Las dos páginas se
|
||||
* prueban con sus dependencias falsas: solo interesa la decisión.
|
||||
*/
|
||||
|
||||
const getSessionOrNull = vi.hoisted(() => vi.fn());
|
||||
const guideStatus = vi.hoisted(() => vi.fn());
|
||||
const guideFirst = vi.hoisted(() => vi.fn());
|
||||
|
||||
vi.mock("@/lib/auth/session", () => ({ getSessionOrNull }));
|
||||
vi.mock("@/server/onboarding/guide", () => ({ guideStatus, guideFirst }));
|
||||
vi.mock("@/components/onboarding/onboarding-client", () => ({
|
||||
OnboardingClient: () => null,
|
||||
}));
|
||||
vi.mock("next/navigation", () => ({
|
||||
redirect: (path: string) => {
|
||||
throw new Error(`redirect:${path}`);
|
||||
},
|
||||
}));
|
||||
vi.mock("@/lib/db", () => ({
|
||||
getDb: () => ({
|
||||
select: () => ({
|
||||
from: () => ({
|
||||
where: () => ({ limit: () => Promise.resolve([{ name: "Sofi" }]) }),
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
schema: { agentProfile: { organizationId: "organization_id", name: "name" } },
|
||||
}));
|
||||
|
||||
import OnboardingPage from "@/app/(app)/onboarding/page";
|
||||
import Home from "@/app/page";
|
||||
import { canConfigure } from "@/lib/auth/roles";
|
||||
|
||||
const owner = { userId: "usr_1", organizationId: "org_1", role: "owner" };
|
||||
const member = { userId: "usr_2", organizationId: "org_1", role: "member" };
|
||||
|
||||
beforeEach(() => {
|
||||
getSessionOrNull.mockReset();
|
||||
guideStatus.mockReset();
|
||||
guideFirst.mockReset();
|
||||
});
|
||||
|
||||
describe("quién configura", () => {
|
||||
it("el propietario y un admin; un miembro del equipo no", () => {
|
||||
expect(canConfigure("owner")).toBe(true);
|
||||
expect(canConfigure("admin")).toBe(true);
|
||||
expect(canConfigure("member")).toBe(false);
|
||||
expect(canConfigure(undefined)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("/onboarding", () => {
|
||||
it("sin sesión manda al login", async () => {
|
||||
getSessionOrNull.mockResolvedValue(null);
|
||||
await expect(OnboardingPage()).rejects.toThrow("redirect:/login");
|
||||
});
|
||||
|
||||
it("un miembro del equipo va a la Bandeja: no puede hacer ningún paso", async () => {
|
||||
getSessionOrNull.mockResolvedValue(member);
|
||||
await expect(OnboardingPage()).rejects.toThrow("redirect:/inbox");
|
||||
expect(guideStatus).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("el propietario ve la guía resuelta en el servidor", async () => {
|
||||
getSessionOrNull.mockResolvedValue(owner);
|
||||
guideStatus.mockResolvedValue({ steps: [], complete: false, enabled: false });
|
||||
const page = (await OnboardingPage()) as { props: { agentName: string | null } };
|
||||
expect(guideStatus).toHaveBeenCalledWith("org_1");
|
||||
expect(page.props.agentName).toBe("Sofi");
|
||||
});
|
||||
});
|
||||
|
||||
describe("la raíz", () => {
|
||||
it("sin sesión sigue yendo a la Bandeja (que manda al login)", async () => {
|
||||
getSessionOrNull.mockResolvedValue(null);
|
||||
await expect(Home()).rejects.toThrow("redirect:/inbox");
|
||||
expect(guideFirst).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("al dueño con pasos pendientes lo manda a la guía", async () => {
|
||||
getSessionOrNull.mockResolvedValue(owner);
|
||||
guideFirst.mockResolvedValue(true);
|
||||
await expect(Home()).rejects.toThrow("redirect:/onboarding");
|
||||
expect(guideFirst).toHaveBeenCalledWith(owner);
|
||||
});
|
||||
|
||||
it("con todo listo y el agente encendido, a la Bandeja como siempre", async () => {
|
||||
getSessionOrNull.mockResolvedValue(owner);
|
||||
guideFirst.mockResolvedValue(false);
|
||||
await expect(Home()).rejects.toThrow("redirect:/inbox");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,271 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import type { getDb } from "@/lib/db";
|
||||
import { schema } from "@/lib/db";
|
||||
import type { EstadoIa } from "@/lib/ai/provider";
|
||||
|
||||
/**
|
||||
* #86 — Los pasos verificados de la guía de inicio, con la base falsa: cada
|
||||
* paso sale de la misma fuente que ya decide si esa pieza funciona (la fila
|
||||
* de Ajustes → IA o el entorno, el `status` de la conexión, el catálogo de
|
||||
* conectores), y lo que está MAL se dice en `problem`.
|
||||
*/
|
||||
|
||||
const estadoIaDe = vi.hoisted(() => vi.fn<() => Promise<EstadoIa>>());
|
||||
vi.mock("@/lib/ai/provider", async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import("@/lib/ai/provider")>()),
|
||||
estadoIaDe,
|
||||
}));
|
||||
|
||||
const getBrainHealth = vi.hoisted(() => vi.fn());
|
||||
vi.mock("@/server/bot/status", () => ({ getBrainHealth }));
|
||||
|
||||
import { onboardingStatus } from "@/server/onboarding/status";
|
||||
import { verifyCalendar, hasWeeklyHours } from "@/server/onboarding/calendar-verifiers";
|
||||
|
||||
// Identidades REALES de las tablas; solo se reemplaza el transporte.
|
||||
const rows = new Map<unknown, unknown[]>();
|
||||
const db = {
|
||||
select: () => ({
|
||||
from: (table: unknown) => {
|
||||
const query = {
|
||||
where: () => query,
|
||||
limit: () => query,
|
||||
then: (resolve: (value: unknown[]) => unknown) =>
|
||||
Promise.resolve(rows.get(table) ?? []).then(resolve),
|
||||
};
|
||||
return query;
|
||||
},
|
||||
}),
|
||||
} as unknown as ReturnType<typeof getDb>;
|
||||
|
||||
const HORAS = { mon: [{ start: "09:00", end: "18:00" }] };
|
||||
const paso = async (key: string) =>
|
||||
(await onboardingStatus("org_1", db)).steps.find((s) => s.key === key);
|
||||
|
||||
beforeEach(() => {
|
||||
rows.clear();
|
||||
vi.stubEnv("AGENDA", "");
|
||||
vi.stubEnv("BRAIN_DISPATCH_URL", "");
|
||||
vi.stubEnv("BRAIN_HEALTH_URL", "");
|
||||
getBrainHealth.mockReset();
|
||||
getBrainHealth.mockResolvedValue(null);
|
||||
estadoIaDe.mockResolvedValue({ activa: false, motivo: "sin_configurar" });
|
||||
rows.set(schema.agentProfile, [{ name: "Asistente", instructions: null, enabled: false }]);
|
||||
});
|
||||
afterEach(() => vi.unstubAllEnvs());
|
||||
|
||||
describe("una instancia recién instalada", () => {
|
||||
it("tiene los tres pasos pendientes, la agenda no aplica y el agente apagado", async () => {
|
||||
const status = await onboardingStatus("org_1", db);
|
||||
expect(status.enabled).toBe(false);
|
||||
expect(status.steps.map((s) => [s.key, s.status])).toEqual([
|
||||
["profile", "pending"],
|
||||
["ai", "pending"],
|
||||
["whatsapp", "pending"],
|
||||
["brain", "pending"],
|
||||
["calendar", "not_applicable"],
|
||||
]);
|
||||
expect(status.steps.find((s) => s.key === "calendar")?.href).toBeNull();
|
||||
// Lo pendiente de un paso recién instalado no es un «problema».
|
||||
expect(status.steps.every((s) => s.problem === null)).toBe(true);
|
||||
});
|
||||
|
||||
it("cada paso lleva a su pantalla", async () => {
|
||||
const status = await onboardingStatus("org_1", db);
|
||||
expect(status.steps.map((s) => s.href)).toEqual([
|
||||
"/agent",
|
||||
"/settings/ai",
|
||||
"/settings/whatsapp",
|
||||
null,
|
||||
null,
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("036 — «Conecta tu agente»", () => {
|
||||
const LLAVE = "k".repeat(32);
|
||||
|
||||
it("sin BRAIN_DISPATCH_URL está pendiente y dice qué poner, sin «problema»", async () => {
|
||||
const s = await paso("brain");
|
||||
expect(s).toMatchObject({ status: "pending", problem: null });
|
||||
expect(s?.nextAction).toMatch(/BRAIN_DISPATCH_URL/);
|
||||
expect(getBrainHealth).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("sin BOT_API_KEY lo dice como problema", async () => {
|
||||
vi.stubEnv("BRAIN_DISPATCH_URL", "http://nea:8000/vocero/dispatch");
|
||||
vi.stubEnv("BOT_API_KEY", "");
|
||||
expect((await paso("brain"))?.problem).toMatch(/BOT_API_KEY/);
|
||||
});
|
||||
|
||||
it("configurado y con el /health en línea → listo; le pregunta al /health del mismo origen", async () => {
|
||||
vi.stubEnv("BRAIN_DISPATCH_URL", "http://nea:8000/vocero/dispatch");
|
||||
vi.stubEnv("BOT_API_KEY", LLAVE);
|
||||
getBrainHealth.mockResolvedValue({ reachable: true, host: "nea:8000", checkedAt: "", version: "2.0.0" });
|
||||
const s = await paso("brain");
|
||||
expect(s).toMatchObject({ status: "ready", problem: null });
|
||||
expect(s?.nextAction).toContain("2.0.0");
|
||||
expect(getBrainHealth).toHaveBeenCalledWith("http://nea:8000/health");
|
||||
});
|
||||
|
||||
it("configurado pero el /health no contesta → pendiente con el motivo", async () => {
|
||||
vi.stubEnv("BRAIN_DISPATCH_URL", "http://nea:8000/vocero/dispatch");
|
||||
vi.stubEnv("BOT_API_KEY", LLAVE);
|
||||
getBrainHealth.mockResolvedValue({ reachable: false, host: "nea:8000", checkedAt: "", problem: "network" });
|
||||
const s = await paso("brain");
|
||||
expect(s?.status).toBe("pending");
|
||||
expect(s?.problem).toMatch(/no responde/);
|
||||
});
|
||||
});
|
||||
|
||||
describe("paso 1: el agente", () => {
|
||||
it("está listo con instrucciones, o con conocimiento aunque no haya instrucciones", async () => {
|
||||
rows.set(schema.agentProfile, [{ name: "Sofi", instructions: "Vende limpiezas.", enabled: false }]);
|
||||
expect((await paso("profile"))?.status).toBe("ready");
|
||||
|
||||
rows.set(schema.agentProfile, [{ name: "Sofi", instructions: " ", enabled: false }]);
|
||||
rows.set(schema.kbEntry, [{ id: "kb_1" }]);
|
||||
expect((await paso("profile"))?.status).toBe("ready");
|
||||
});
|
||||
|
||||
it("el nombre de fábrica no basta: sin instrucciones ni conocimiento sigue pendiente y dice qué falta", async () => {
|
||||
const step = await paso("profile");
|
||||
expect(step?.status).toBe("pending");
|
||||
expect(step?.nextAction).toMatch(/nombre/);
|
||||
});
|
||||
|
||||
it("`enabled` sale del mismo perfil", async () => {
|
||||
rows.set(schema.agentProfile, [{ name: "Sofi", instructions: "x", enabled: true }]);
|
||||
expect((await onboardingStatus("org_1", db)).enabled).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("paso 2: el proveedor de IA (la fila manda, el entorno es respaldo)", () => {
|
||||
it("la llave guardada en Ajustes → IA lo deja listo", async () => {
|
||||
estadoIaDe.mockResolvedValue({ activa: true, origen: "org", last4: "abcd" });
|
||||
const step = await paso("ai");
|
||||
expect(step).toMatchObject({ status: "ready", problem: null });
|
||||
expect(step?.nextAction).toMatch(/Ajustes/);
|
||||
});
|
||||
|
||||
it("sin fila, OPENROUTER_* del entorno también cuenta", async () => {
|
||||
estadoIaDe.mockResolvedValue({ activa: true, origen: "env", last4: "abcd" });
|
||||
const step = await paso("ai");
|
||||
expect(step?.status).toBe("ready");
|
||||
expect(step?.nextAction).toMatch(/entorno/);
|
||||
});
|
||||
|
||||
it("una llave pausada NO está lista y el problema se dice (rechazada o sin saldo)", async () => {
|
||||
estadoIaDe.mockResolvedValue({
|
||||
activa: false,
|
||||
motivo: "token_invalido",
|
||||
last4: "abcd",
|
||||
desde: null,
|
||||
});
|
||||
const rechazada = await paso("ai");
|
||||
expect(rechazada?.status).toBe("pending");
|
||||
expect(rechazada?.problem).toMatch(/rechazó/);
|
||||
|
||||
estadoIaDe.mockResolvedValue({
|
||||
activa: false,
|
||||
motivo: "sin_saldo",
|
||||
last4: "abcd",
|
||||
desde: null,
|
||||
});
|
||||
expect((await paso("ai"))?.problem).toMatch(/saldo/);
|
||||
});
|
||||
});
|
||||
|
||||
describe("paso 3: WhatsApp", () => {
|
||||
it("conectado → listo", async () => {
|
||||
rows.set(schema.metaCredentials, [{ status: "connected" }]);
|
||||
expect(await paso("whatsapp")).toMatchObject({ status: "ready", problem: null });
|
||||
});
|
||||
|
||||
it("token vencido → pendiente, y se dice que hay que reconectar", async () => {
|
||||
rows.set(schema.metaCredentials, [{ status: "reconnect_required" }]);
|
||||
const step = await paso("whatsapp");
|
||||
expect(step?.status).toBe("pending");
|
||||
expect(step?.problem).toMatch(/token/);
|
||||
});
|
||||
});
|
||||
|
||||
describe("paso 4: la agenda, solo con AGENDA=on", () => {
|
||||
beforeEach(() => vi.stubEnv("AGENDA", "on"));
|
||||
|
||||
it("sin horarios guardados está pendiente y lleva a Ajustes → Agenda", async () => {
|
||||
expect(await paso("calendar")).toMatchObject({
|
||||
status: "pending",
|
||||
href: "/settings/calendar",
|
||||
problem: null,
|
||||
});
|
||||
});
|
||||
|
||||
it("enlace fijo con horarios → listo sin pedir credenciales de nadie", async () => {
|
||||
rows.set(schema.calendarSettings, [{ connector: "enlace-fijo", weeklyHours: HORAS }]);
|
||||
expect((await paso("calendar"))?.status).toBe("ready");
|
||||
});
|
||||
|
||||
it("horarios vacíos (todos los días cerrados) → pendiente", async () => {
|
||||
rows.set(schema.calendarSettings, [{ connector: "enlace-fijo", weeklyHours: {} }]);
|
||||
expect((await paso("calendar"))?.status).toBe("pending");
|
||||
});
|
||||
|
||||
it("un conector elegido sin credencial sigue pendiente y lo dice", async () => {
|
||||
rows.set(schema.calendarSettings, [{ connector: "zoom", weeklyHours: HORAS }]);
|
||||
const zoom = await paso("calendar");
|
||||
expect(zoom?.status).toBe("pending");
|
||||
expect(zoom?.problem).toMatch(/Zoom.*no está conectado/);
|
||||
|
||||
rows.set(schema.calendarSettings, [{ connector: "google", weeklyHours: HORAS }]);
|
||||
expect((await paso("calendar"))?.problem).toMatch(/Google/);
|
||||
});
|
||||
|
||||
it("con la credencial conectada → listo; rechazada por el proveedor → pendiente con el motivo", async () => {
|
||||
rows.set(schema.calendarSettings, [{ connector: "zoom", weeklyHours: HORAS }]);
|
||||
rows.set(schema.zoomCredentials, [{ status: "connected" }]);
|
||||
expect((await paso("calendar"))?.status).toBe("ready");
|
||||
|
||||
rows.set(schema.zoomCredentials, [{ status: "error" }]);
|
||||
const roto = await paso("calendar");
|
||||
expect(roto?.status).toBe("pending");
|
||||
expect(roto?.problem).toMatch(/rechazó/);
|
||||
|
||||
rows.set(schema.calendarSettings, [{ connector: "google", weeklyHours: HORAS }]);
|
||||
rows.set(schema.googleCredentials, [{ status: "connected" }]);
|
||||
expect((await paso("calendar"))?.status).toBe("ready");
|
||||
});
|
||||
|
||||
it("un conector que no existe en esta instancia (venías de un fork) → unsupported", async () => {
|
||||
rows.set(schema.calendarSettings, [{ connector: "calendly", weeklyHours: HORAS }]);
|
||||
const step = await paso("calendar");
|
||||
expect(step?.status).toBe("unsupported");
|
||||
expect(step?.problem).toMatch(/calendly/);
|
||||
});
|
||||
});
|
||||
|
||||
describe("verifyCalendar (pura)", () => {
|
||||
it("reconoce horarios bien formados y descarta los rotos", () => {
|
||||
expect(hasWeeklyHours(HORAS)).toBe(true);
|
||||
expect(hasWeeklyHours({ mon: [{ start: "18:00", end: "09:00" }] })).toBe(false);
|
||||
expect(hasWeeklyHours({ mon: [{ start: "9:00", end: "18:00" }] })).toBe(false);
|
||||
expect(hasWeeklyHours({ mon: [] })).toBe(false);
|
||||
expect(hasWeeklyHours(null)).toBe(false);
|
||||
expect(hasWeeklyHours("lunes")).toBe(false);
|
||||
});
|
||||
|
||||
it("la tabla de decisión", () => {
|
||||
expect(verifyCalendar(undefined)).toBe("pending");
|
||||
expect(verifyCalendar({ connector: "enlace-fijo", weeklyHours: HORAS })).toBe("ready");
|
||||
expect(verifyCalendar({ connector: "zoom", weeklyHours: HORAS })).toBe("pending");
|
||||
expect(
|
||||
verifyCalendar({ connector: "zoom", weeklyHours: HORAS }, { zoom: true, google: false })
|
||||
).toBe("ready");
|
||||
expect(
|
||||
verifyCalendar({ connector: "google", weeklyHours: HORAS }, { zoom: true, google: false })
|
||||
).toBe("pending");
|
||||
expect(verifyCalendar({ connector: "otro", weeklyHours: HORAS })).toBe("unsupported");
|
||||
// Sin horarios manda lo pendiente, aunque el conector sea desconocido.
|
||||
expect(verifyCalendar({ connector: "otro", weeklyHours: {} })).toBe("pending");
|
||||
});
|
||||
});
|
||||
Loaded 100 of 1316 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user