diff --git a/src/payload/InteractionWriter.ts b/src/payload/InteractionWriter.ts index fcf59b5..448247a 100644 --- a/src/payload/InteractionWriter.ts +++ b/src/payload/InteractionWriter.ts @@ -5,11 +5,10 @@ import type { PayloadClient } from './PayloadClient.js' const log = getLogger('interaction-writer') -/** - * Writes messages to community_interactions via Payload REST API. - * When direct DB access becomes available, this can be swapped to a - * pg Pool-based implementation for higher throughput. - */ +// WhatsApp platform + account IDs in CMS +const WHATSAPP_PLATFORM_ID = 4 +const WHATSAPP_ACCOUNT_ID = 1 + export class InteractionWriter { constructor(private payloadClient: PayloadClient) {} @@ -22,22 +21,28 @@ export class InteractionWriter { analysis: LLMResponse | null, ): Promise { try { + const data: Record = { + platform: WHATSAPP_PLATFORM_ID, + socialAccount: WHATSAPP_ACCOUNT_ID, + type: 'dm', + externalId: message.messageId, + author: { + name: message.senderName || message.from, + handle: message.from, + }, + message: message.text ?? `[${message.type}]`, + publishedAt: new Date().toISOString(), + status: 'new', + } + + if (analysis?.isMedicalQuestion) { + data.flags = { isMedicalQuestion: true } + data.analysis = { sentiment: 'question' } + } + const doc = await this.payloadClient.create<{ id: number }>( 'community-interactions', - { - type: 'dm', - externalId: message.messageId, - authorName: message.senderName, - authorHandle: message.from, - message: message.text ?? `[${message.type}]`, - messageType: message.type, - ...(analysis && { - analysisSentiment: 'neutral', - analysisIsMedicalQuestion: analysis.isMedicalQuestion, - }), - status: 'new', - tenant: 10, - }, + data, ) log.debug({ id: doc.id, messageId: message.messageId }, 'Incoming message stored') @@ -51,25 +56,31 @@ export class InteractionWriter { async writeOutgoing( to: string, text: string, - replyToMessageId: string, + _replyToMessageId: string, ): Promise { try { const doc = await this.payloadClient.create<{ id: number }>( 'community-interactions', { + platform: WHATSAPP_PLATFORM_ID, + socialAccount: WHATSAPP_ACCOUNT_ID, type: 'dm', - authorName: 'CCS Bot', - authorHandle: 'bot', + externalId: `bot-reply-${Date.now()}`, + author: { + name: 'CCS Bot', + handle: 'bot', + }, message: text, - messageType: 'text', - status: 'responded', - responseText: text, - responseType: 'bot', - tenant: 10, + publishedAt: new Date().toISOString(), + status: 'replied', + response: { + text, + sentAt: new Date().toISOString(), + }, }, ) - log.debug({ id: doc.id, to, replyTo: replyToMessageId }, 'Outgoing message stored') + log.debug({ id: doc.id, to }, 'Outgoing message stored') return doc.id } catch (err) { log.error({ error: (err as Error).message }, 'Failed to store outgoing message')