import 'dotenv/config'; import { describe, it, expect } from 'vitest'; import { prisma } from '@omniloq/db'; import { WhatsAppMetaChannel } from '@omniloq/channels'; import type { InboundMessage } from '@omniloq/channels'; import { seedMetaDemo } from '../src/seed'; import { ingestInbound, ingestStatus } from '../src/ingest'; import { processNextJob } from '../src/worker'; process.env.SECRETS_MASTER_KEY = '0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef'; const TIMEOUT = 90000; let n = 0; function slug() { return `p2-${Date.now()}-${++n}`; } function wamid() { return `wamid.${Date.now()}.${++n}.${Math.random().toString(36).slice(2, 8)}`; } function mkInbound(overrides: Partial = {}): InboundMessage { return { channelType: 'whatsapp', channelAccountExternalId: 'phone-x', externalUserId: '212600000000', externalMessageId: wamid(), text: 'Bonjour', timestamp: new Date(), ...overrides, }; } function jsonResponse(body: unknown, status = 200): Response { return new Response(JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json' } }); } const META_PAYLOAD = { object: 'whatsapp_business_account', entry: [ { id: 'waba-1', changes: [ { field: 'messages', value: { messaging_product: 'whatsapp', metadata: { display_phone_number: '212600000000', phone_number_id: '12345' }, contacts: [{ profile: { name: 'Ahmed' }, wa_id: '212661234567' }], messages: [ { from: '212661234567', id: 'wamid.IN.1', timestamp: '1727000000', type: 'text', text: { body: 'Bonjour' } }, ], }, }, ], }, ], }; describe('Omniloq — Phase 2 (adaptateur Meta + ingestion asynchrone + worker + tracking)', () => { it('1. Vérification webhook valide → acceptée', () => { const channel = new WhatsAppMetaChannel({ phoneNumberId: 'x', accessToken: 't', verifyToken: 'my-token' }); const r = channel.verifyWebhook({ 'hub.mode': 'subscribe', 'hub.verify_token': 'my-token', 'hub.challenge': 'challenge-123' }); expect(r.verified).toBe(true); expect(r.challenge).toBe('challenge-123'); }); it('2. Vérification webhook invalide → refusée', () => { const channel = new WhatsAppMetaChannel({ phoneNumberId: 'x', accessToken: 't', verifyToken: 'my-token' }); const r = channel.verifyWebhook({ 'hub.mode': 'subscribe', 'hub.verify_token': 'wrong', 'hub.challenge': 'challenge-123' }); expect(r.verified).toBe(false); }); it('3. Message texte Meta → InboundMessage normalisé correctement', () => { const channel = new WhatsAppMetaChannel({ phoneNumberId: 'x', accessToken: 't' }); const events = channel.parseWebhook(META_PAYLOAD); expect(events).toHaveLength(1); const ev = events[0] as any; expect(ev.type).toBe('message_received'); expect(ev.inbound.channelAccountExternalId).toBe('12345'); expect(ev.inbound.externalUserId).toBe('212661234567'); expect(ev.inbound.externalMessageId).toBe('wamid.IN.1'); expect(ev.inbound.text).toBe('Bonjour'); }); it('4. phone_number_id → bon ChannelAccount / Tenant (multi-tenant)', async () => { const a = await seedMetaDemo(slug()); const b = await seedMetaDemo(slug()); const r = await ingestInbound(mkInbound({ channelAccountExternalId: b.phoneNumberId, externalUserId: '212600000001' })); expect(r.acked).toBe(true); const msg = await prisma.message.findUnique({ where: { id: r.messageId! } }); const conv = await prisma.conversation.findUnique({ where: { id: msg!.conversationId } }); expect(conv?.tenantId).toBe(b.tenant.id); expect(conv?.tenantId).not.toBe(a.tenant.id); }); it('5. Premier contact → création ChannelIdentity', async () => { const { channelAccount, phoneNumberId } = await seedMetaDemo(slug()); const r = await ingestInbound(mkInbound({ channelAccountExternalId: phoneNumberId, externalUserId: '212600000002' })); expect(r.acked).toBe(true); const identity = await prisma.channelIdentity.findUnique({ where: { channelType_channelAccountId_externalUserId: { channelType: 'whatsapp', channelAccountId: channelAccount.id, externalUserId: '212600000002', }, }, }); expect(identity).toBeTruthy(); }); it('6. Contact existant → identité réutilisée (pas de doublon)', async () => { const { channelAccount, phoneNumberId } = await seedMetaDemo(slug()); await ingestInbound(mkInbound({ channelAccountExternalId: phoneNumberId, externalUserId: '212600000003' })); await ingestInbound(mkInbound({ channelAccountExternalId: phoneNumberId, externalUserId: '212600000003' })); const identities = await prisma.channelIdentity.findMany({ where: { channelAccountId: channelAccount.id, externalUserId: '212600000003' }, }); expect(identities.length).toBe(1); }); it('7. Message webhook dupliqué → aucun doublon Message/Job', async () => { const { channelAccount, phoneNumberId } = await seedMetaDemo(slug()); const dupWamid = wamid(); const inbound = mkInbound({ channelAccountExternalId: phoneNumberId, externalMessageId: dupWamid }); const r1 = await ingestInbound(inbound); const r2 = await ingestInbound(inbound); expect(r1.acked).toBe(true); expect(r2.acked).toBe(true); // ACK silencieux const messages = await prisma.message.findMany({ where: { externalMessageId: dupWamid } }); expect(messages.length).toBe(1); const jobs = await prisma.job.findMany({ where: { dedupKey: `meta:${channelAccount.id}:${dupWamid}` } }); expect(jobs.length).toBe(1); }); it('8. Webhook → ACK sans attendre le runtime (Job pending, 0 AgentRun)', async () => { const { phoneNumberId } = await seedMetaDemo(slug()); const r = await ingestInbound(mkInbound({ channelAccountExternalId: phoneNumberId, text: 'Bonjour' })); expect(r.acked).toBe(true); const msg = await prisma.message.findUnique({ where: { id: r.messageId! } }); const runs = await prisma.agentRun.findMany({ where: { conversationId: msg!.conversationId } }); expect(runs.length).toBe(0); // le runtime n'a PAS tourné const job = await prisma.job.findUnique({ where: { id: r.jobId! } }); expect(job?.status).toBe('pending'); // en attente du worker }); it('9. Worker → runtime → réponse enregistrée et envoyée (wamid)', async () => { const { phoneNumberId } = await seedMetaDemo(slug()); const r = await ingestInbound(mkInbound({ channelAccountExternalId: phoneNumberId, text: 'Quel est mon solde ?' })); const outWamid = wamid(); const mockFetch: typeof fetch = async () => jsonResponse({ messages: [{ id: outWamid }] }); const processed = await processNextJob({ fetchImpl: mockFetch, jobId: r.jobId! }); expect(processed).toBe(true); const msg = await prisma.message.findUnique({ where: { id: r.messageId! } }); const runs = await prisma.agentRun.findMany({ where: { conversationId: msg!.conversationId } }); expect(runs.length).toBeGreaterThan(0); // le runtime a tourné const outbound = await prisma.message.findFirst({ where: { conversationId: msg!.conversationId, direction: 'outbound' } }); expect(outbound).toBeTruthy(); expect(outbound?.status).toBe('sent'); expect(outbound?.externalMessageId).toBe(outWamid); const job = await prisma.job.findUnique({ where: { id: r.jobId! } }); expect(job?.status).toBe('done'); }, TIMEOUT); it('10. sendMessage() → bon endpoint + vrai wamid retourné', async () => { let url = ''; let body = ''; const mockFetch: typeof fetch = async (input, init) => { url = String(input); body = String(init?.body ?? ''); return jsonResponse({ messages: [{ id: 'wamid.OUT.2' }] }); }; const channel = new WhatsAppMetaChannel({ phoneNumberId: '12345', accessToken: 'tok', graphApiVersion: 'v22.0' }, mockFetch); const r = await channel.sendMessage('212661234567', 'Bonjour !'); expect(r.status).toBe('sent'); expect(r.externalMessageId).toBe('wamid.OUT.2'); expect(url).toContain('/v22.0/12345/messages'); expect(body).toContain('Bonjour !'); expect(body).toContain('212661234567'); }); it('11. Webhook delivered/read → update Message, aucun AgentRun', async () => { const { tenant, agent, channelAccount } = await seedMetaDemo(slug()); const identity = await prisma.channelIdentity.create({ data: { tenantId: tenant.id, channelType: 'whatsapp', channelAccountId: channelAccount.id, externalUserId: '212600000004' }, }); const conv = await prisma.conversation.create({ data: { tenantId: tenant.id, agentId: agent.id, channelIdentityId: identity.id }, }); const outWamid = wamid(); await prisma.message.create({ data: { conversationId: conv.id, direction: 'outbound', senderType: 'agent', content: [{ type: 'text', text: 'Bonjour' }] as any, status: 'sent', externalMessageId: outWamid, }, }); const runsBefore = await prisma.agentRun.count(); await ingestStatus({ type: 'message_status', channelType: 'whatsapp', channelAccountExternalId: channelAccount.externalAccountId ?? '', externalMessageId: outWamid, status: 'delivered', timestamp: new Date(), }); const runsAfter = await prisma.agentRun.count(); expect(runsAfter).toBe(runsBefore); // aucun AgentRun déclenché const msg = await prisma.message.findFirst({ where: { externalMessageId: outWamid } }); expect(msg?.status).toBe('delivered'); expect(msg?.deliveredAt).toBeTruthy(); }); it('12. Erreur Graph API → Message outbound failed, runtime/audit conservés', async () => { const { phoneNumberId } = await seedMetaDemo(slug()); const r = await ingestInbound(mkInbound({ channelAccountExternalId: phoneNumberId, text: 'Quel est mon solde ?' })); const mockFetch: typeof fetch = async () => jsonResponse({ error: { message: 'Invalid OAuth access token' } }, 400); await processNextJob({ fetchImpl: mockFetch, jobId: r.jobId! }); const msg = await prisma.message.findUnique({ where: { id: r.messageId! } }); const outbound = await prisma.message.findFirst({ where: { conversationId: msg!.conversationId, direction: 'outbound' } }); expect(outbound?.status).toBe('failed'); expect((outbound?.providerMetadata as any)?.error).toBe('Invalid OAuth access token'); // le runtime a quand même tourné → audit conservé const run = await prisma.agentRun.findFirst({ where: { conversationId: msg!.conversationId } }); expect(run?.status).toBe('completed'); }, TIMEOUT); });