Files
crm-mgcoaching/tests/unit/servicios.test.ts
T
Andres Corazon Santana AquinoandClaude Opus 5.5 68f92ade52 fix: reglas del catálogo genéricas y subordinadas a las instrucciones del negocio
Quitan la mención a letreros que quedó del catálogo de ejemplo y dejan claro
que, si el negocio define cuándo y cómo dar precios, sus instrucciones mandan.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-04 21:58:05 -04:00

181 lines
6.5 KiB
TypeScript

import { describe, expect, it } from "vitest";
import {
CATALOGO_EJEMPLO,
CATALOGO_MARCADOR,
formatServicePrice,
llaveServicio,
REGLAS_MARCADOR,
reglasDelCatalogo,
renderServiciosKb,
semillasFaltantes,
serializeServiceForBot,
serviceInputSchema,
serviciosParaBot,
tienePrecio,
type ServiceDto,
} from "@/lib/services";
import { serializeBotProfile } from "@/server/bot/profile";
import type { schema } from "@/lib/db";
/**
* Catálogo «Servicios y Precios»: cómo se presenta un precio, qué
* viaja al cerebro y, sobre todo, que un servicio sin precio JAMÁS llegue al
* agente con un monto.
*/
function srv(p: Partial<ServiceDto> = {}): ServiceDto {
return {
id: "srv_1",
category: "Letreros Neón LED",
name: "Letrero neón flex",
description: "Neón LED flexible",
specifications: "Medidas, interior/exterior",
pricingType: "fixed",
priceCents: 150_000,
currency: "MXN",
unitLabel: "por m²",
deliveryTime: "7 a 10 días",
isActive: true,
position: 0,
...p,
};
}
describe("precios del catálogo", () => {
it("precio fijo: monto exacto, moneda y unidad", () => {
const t = formatServicePrice(srv());
expect(t).toContain("1,500.00");
expect(t).toContain("MXN");
expect(t).toContain("por m²");
expect(t.startsWith("Desde")).toBe(false);
});
it("precio desde: antepone «Desde»", () => {
expect(formatServicePrice(srv({ pricingType: "from", priceCents: 90_000 }))).toMatch(/^Desde .*900\.00/);
});
it("a cotizar o sin monto: «Requiere cotización personalizada»", () => {
expect(formatServicePrice(srv({ pricingType: "quote_required", priceCents: null }))).toBe(
"Requiere cotización personalizada"
);
expect(tienePrecio(srv({ pricingType: "fixed", priceCents: null }))).toBe(false);
expect(formatServicePrice(srv({ pricingType: "from", priceCents: null }))).toBe(
"Requiere cotización personalizada"
);
});
it("el esquema borra el monto de un servicio «a cotizar» (no se filtra uno viejo)", () => {
const r = serviceInputSchema.parse({
category: "Impresión 3D",
name: "Pieza a medida",
pricingType: "quote_required",
priceCents: 50_000,
});
expect(r.priceCents).toBeNull();
expect(r.currency).toBe("MXN");
});
it("el esquema rechaza montos negativos o con decimales", () => {
expect(serviceInputSchema.safeParse({ category: "A", name: "B", pricingType: "fixed", priceCents: -1 }).success).toBe(false);
expect(serviceInputSchema.safeParse({ category: "A", name: "B", pricingType: "fixed", priceCents: 10.5 }).success).toBe(false);
});
});
describe("serialización para el cerebro", () => {
it("sin precio viaja como quote_required, priceCents null", () => {
const b = serializeServiceForBot(srv({ pricingType: "fixed", priceCents: null }));
expect(b.quoteRequired).toBe(true);
expect(b.priceCents).toBeNull();
expect(b.pricingType).toBe("quote_required");
expect(b.priceText).toBe("Requiere cotización personalizada");
});
it("con precio viaja el monto y el texto ya redactado", () => {
const b = serializeServiceForBot(srv());
expect(b.quoteRequired).toBe(false);
expect(b.priceCents).toBe(150_000);
expect(b.priceText).toContain("1,500.00");
});
it("solo los activos y en orden de posición", () => {
const lista = serviciosParaBot([
srv({ id: "b", name: "B", position: 2 }),
srv({ id: "x", name: "Oculto", position: 0, isActive: false }),
srv({ id: "a", name: "A", position: 1 }),
]);
expect(lista.map((s) => s.id)).toEqual(["a", "b"]);
});
it("el kb lleva el marcador, la categoría y el precio de cada servicio", () => {
const kb = renderServiciosKb(serviciosParaBot([srv(), srv({ id: "q", name: "Caja de luz", pricingType: "quote_required", priceCents: null })]));
expect(kb.startsWith(CATALOGO_MARCADOR)).toBe(true);
expect(kb).toContain("## Letreros Neón LED");
expect(kb).toContain("Caja de luz — Requiere cotización personalizada");
expect(renderServiciosKb([])).toBe("");
});
it("las reglas prohíben inventar precios y ofrecen asesor o llamada", () => {
const r = reglasDelCatalogo({ agenda: true });
expect(r.startsWith(REGLAS_MARCADOR)).toBe(true);
expect(r).toMatch(/NUNCA inventes/);
expect(r).toContain("cotización personalizada");
expect(r).toMatch(/agenda del CRM/);
expect(reglasDelCatalogo({ agenda: false })).toMatch(/llamada telefónica/);
});
it("las reglas son genéricas y ceden ante las instrucciones del negocio", () => {
const r = reglasDelCatalogo({ agenda: true });
expect(r).not.toMatch(/letrero|neón|acrílico/i);
expect(r).toMatch(/instrucciones del negocio .* mandan/);
});
});
describe("perfil del bot con catálogo", () => {
const perfil = {
name: "Agente",
tone: null,
instructions: "Sé amable.",
escalationRules: null,
greeting: null,
role: null,
tools: null,
} as unknown as typeof schema.agentProfile.$inferSelect;
it("sin servicios, instrucciones y kb quedan iguales y services viaja vacío", () => {
const p = serializeBotProfile(perfil, [], null);
expect(p.profile.instructions).toBe("Sé amable.");
expect(p.services).toEqual([]);
expect(p.kb).not.toContain(CATALOGO_MARCADOR);
});
it("con servicios suma reglas a instructions y el catálogo al kb", () => {
const services = serviciosParaBot([srv()]);
const p = serializeBotProfile(perfil, [], null, services, { agenda: true });
expect(p.profile.instructions).toContain("Sé amable.");
expect(p.profile.instructions).toContain(REGLAS_MARCADOR);
expect(p.kb).toContain(CATALOGO_MARCADOR);
expect(p.services).toHaveLength(1);
});
});
describe("semilla del catálogo base (idempotente)", () => {
it("trae servicios de ejemplo, todos a cotizar (sin precios inventados)", () => {
expect(CATALOGO_EJEMPLO.length).toBeGreaterThanOrEqual(8);
for (const s of CATALOGO_EJEMPLO) {
expect(s.pricingType).toBe("quote_required");
expect(s.priceCents ?? null).toBeNull();
}
});
it("no repite lo que ya existe (sin importar mayúsculas)", () => {
const primero = CATALOGO_EJEMPLO[0]!;
const faltan = semillasFaltantes([{ category: primero.category.toUpperCase(), name: ` ${primero.name} ` }]);
expect(faltan).toHaveLength(CATALOGO_EJEMPLO.length - 1);
expect(faltan.map(llaveServicio)).not.toContain(llaveServicio(primero));
});
it("re-ejecutarla con todo creado no agrega nada", () => {
expect(semillasFaltantes(CATALOGO_EJEMPLO)).toEqual([]);
});
});