import { prisma } from '@omniloq/db'; import type { InboundMessage, MessageStatusEvent } from '@omniloq/channels'; export interface IngestResult { acked: boolean; messageId?: string; jobId?: string; reason?: string; } /** * Ingestion d'un message entrant normalisé (déjà converti par l'adaptateur de canal). * Ne reçoit JAMAIS de JSON provider. Résout le compte via `channelAccountExternalId` * (ex: phone_number_id Meta) → ChannelAccount → tenant → agent routing (premier agent). * Crée Message inbound + Job dans UNE transaction courte, puis ACK immédiat. * Idempotence garantie par la DB : `Job @@unique([tenantId, dedupKey])`. */ export async function ingestInbound(inbound: InboundMessage): Promise { // 1. Résoudre ChannelAccount via l'identifiant externe du compte (multi-tenant, pas de hardcode) const account = await prisma.channelAccount.findFirst({ where: { channelType: inbound.channelType, externalAccountId: inbound.channelAccountExternalId }, include: { tenant: { include: { agents: { orderBy: { createdAt: 'asc' }, take: 1 } } } }, }); if (!account) return { acked: false, reason: 'channel_account_not_found' }; const agent = account.tenant.agents[0]; if (!agent) return { acked: false, reason: 'no_agent_for_tenant' }; // 2. Résoudre/créer ChannelIdentity (premier contact → création) let identity = await prisma.channelIdentity.findUnique({ where: { channelType_channelAccountId_externalUserId: { channelType: inbound.channelType, channelAccountId: account.id, externalUserId: inbound.externalUserId, }, }, }); if (!identity) { const contact = await prisma.contact.create({ data: { tenantId: account.tenantId } }); identity = await prisma.channelIdentity.create({ data: { tenantId: account.tenantId, contactId: contact.id, channelType: inbound.channelType, channelAccountId: account.id, externalUserId: inbound.externalUserId, }, }); } // 3. Résoudre/créer Conversation ouverte pour cet agent let conversation = await prisma.conversation.findFirst({ where: { tenantId: account.tenantId, agentId: agent.id, channelIdentityId: identity.id, status: 'open' }, }); if (!conversation) { conversation = await prisma.conversation.create({ data: { tenantId: account.tenantId, agentId: agent.id, channelIdentityId: identity.id }, }); } // 4. Idempotence : dedupKey stable par wamid const dedupKey = `meta:${account.id}:${inbound.externalMessageId}`; // 5. TX courte : Message inbound + Job (la contrainte unique décide en cas de doublon) try { const created = await prisma.$transaction(async (tx) => { const msg = await tx.message.create({ data: { conversationId: conversation.id, externalMessageId: inbound.externalMessageId, direction: 'inbound', senderType: 'contact', content: [{ type: 'text', text: inbound.text }] as any, status: 'received', }, }); const job = await tx.job.create({ data: { tenantId: account.tenantId, conversationId: conversation.id, type: 'process_message', payload: { messageId: msg.id } as any, status: 'pending', dedupKey, }, }); return { messageId: msg.id, jobId: job.id }; }); return { acked: true, messageId: created.messageId, jobId: created.jobId }; } catch (e: any) { // Violation d'unicité (P2002) → webhook dupliqué : ACK sans créer de doublon if (e?.code === 'P2002') { return { acked: true, reason: 'duplicate' }; } throw e; } } /** * Ingestion d'un statut de message sortant (sent/delivered/read/failed). * Met à jour le Message correspondant — ne déclenche JAMAIS d'AgentRun. */ export async function ingestStatus(event: MessageStatusEvent): Promise { const message = await prisma.message.findFirst({ where: { externalMessageId: event.externalMessageId }, }); if (!message) return; await prisma.message.update({ where: { id: message.id }, data: { status: event.status, // sent | delivered | read | failed deliveredAt: event.status === 'delivered' || event.status === 'read' ? event.timestamp : message.deliveredAt, readAt: event.status === 'read' ? event.timestamp : message.readAt, providerMetadata: { ...((message.providerMetadata as any) ?? {}), deliveryError: event.error ?? null } as any, }, }); }