CognxSafeTrack commited on
Commit ·
fb4b8be
1
Parent(s): f4e46e8
Refactor: Modularize WhatsAppLogic into specialized Handlers (Command Pattern)
Browse filesFiles changed (7)
- apps/whatsapp-worker/src/handlers/CommandHandler.tsAdded+60
- apps/whatsapp-worker/src/handlers/ExerciseHandler.tsAdded+140
- apps/whatsapp-worker/src/handlers/NavigationHandler.tsAdded+87
- apps/whatsapp-worker/src/handlers/OnboardingHandler.tsAdded+132
- apps/whatsapp-worker/src/handlers/types.tsAdded+21
- apps/whatsapp-worker/src/services/utils.tsAdded+32
- apps/whatsapp-worker/src/services/whatsapp-logic.ts+64-367
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960import { MessageContext, MessageHandler } from './types';import { isFuzzyMatch } from '../services/utils';import { PrismaClient } from '@repo/database';
const prisma = new PrismaClient();
export class CommandHandler implements MessageHandler { async canHandle(ctx: MessageContext): Promise<boolean> { const { normalizedText } = ctx; if (isFuzzyMatch(normalizedText, 'SEED')) return true; const dayActionMatch = normalizedText.match(/^DAY(\d+)_(EXERCISE|REPLAY|CONTINUE|PROMPT)$/); if (dayActionMatch) return true;
return false; }
async handle(ctx: MessageContext): Promise<boolean> { const { user, normalizedText, whatsappQueue } = ctx; if (!user) return false;
// --- 1. SEED --- if (isFuzzyMatch(normalizedText, 'SEED')) { try { // @ts-ignore const { seedDatabase } = await import('@repo/database/seed'); const result = await seedDatabase(prisma); await (prisma as any).businessProfile.deleteMany({ where: { userId: user.id } }); await prisma.user.update({ where: { id: user.id }, data: { activity: null } });
const msg = result.seeded ? "✅ Seeding terminé ! Le Cache Cognitif a été réinitialisé.\nEnvoie INSCRIPTION pour commencer." : "ℹ️ Les données existent déjà. Cache Cognitif purgé. Envoie INSCRIPTION."; await whatsappQueue.add('send-message', { userId: user.id, text: msg }); } catch (err) { await whatsappQueue.add('send-message', { userId: user.id, text: `❌ Erreur seed` }); } return true; }
// --- 2. DAY ACTIONS (List menus) --- const dayActionMatch = normalizedText.match(/^DAY(\d+)_(EXERCISE|REPLAY|CONTINUE|PROMPT)$/); if (dayActionMatch) { const action = dayActionMatch[2]; const enrollment = await prisma.enrollment.findFirst({ where: { userId: user.id, status: 'ACTIVE' } }); if (action === 'REPLAY' && enrollment) { await whatsappQueue.add('send-content', { userId: user.id, trackId: enrollment.trackId, dayNumber: enrollment.currentDay }); return true; } else if (action === 'EXERCISE') { const msg = user.language === 'WOLOF' ? "🎙️ Yónnee sa tontu :" : "🎙️ Envoie ta réponse :"; await whatsappQueue.add('send-message', { userId: user.id, text: msg }); return true; } }
return false; }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140import { MessageContext, MessageHandler } from './types';import { isFuzzyMatch } from '../services/utils';import { PrismaClient } from '@repo/database';import { logger } from '../logger';import { getTimeTravelContext } from '../timeTravelContext';
const prisma = new PrismaClient();
export class ExerciseHandler implements MessageHandler { async canHandle(ctx: MessageContext): Promise<boolean> { const { activeEnrollment } = ctx; if (!activeEnrollment) return false;
// Skip if it's a short message and NOT a system command // Note: The logic in whatsapp-logic.ts line 152 handles this as a block. // We'll handle it inside ExerciseHandler or in the central router. return true; }
async handle(ctx: MessageContext): Promise<boolean> { const { user, normalizedText, text, activeEnrollment, whatsappQueue, redis, traceId, imageUrl } = ctx; if (!user || !activeEnrollment) return false;
// --- 1. Identify pedagogical state --- const userProgress = await (prisma as any).userProgress.findUnique({ where: { userId_trackId: { userId: user.id, trackId: activeEnrollment.trackId } } });
const timeTravelDay = await getTimeTravelContext(user.id, redis as any); const effectiveDay = timeTravelDay ?? activeEnrollment.currentDay; const isTimeTravelMode = timeTravelDay !== null && timeTravelDay !== activeEnrollment.currentDay;
// --- 2. Re-validation & Correction Logic --- const fiveMinutesAgo = new Date(Date.now() - 5 * 60 * 1000); const tenMinutesAgo = new Date(Date.now() - 10 * 60 * 1000); const isRecentlyCompleted = userProgress?.exerciseStatus === 'COMPLETED' && userProgress.updatedAt > fiveMinutesAgo; const isImageForActiveExercise = !!imageUrl && ( userProgress?.exerciseStatus === 'PENDING' || userProgress?.exerciseStatus === 'PENDING_DEEPDIVE' || userProgress?.exerciseStatus === 'PENDING_REMEDIATION' || (userProgress?.exerciseStatus === 'COMPLETED' && userProgress.updatedAt > tenMinutesAgo) );
const shouldForceRevalidation = isImageForActiveExercise || isRecentlyCompleted;
if (shouldForceRevalidation && userProgress?.exerciseStatus === 'COMPLETED') { logger.info(`${traceId} 🔄 Re-validation triggered for User ${user.id} (Reason: ${imageUrl ? 'New Image' : 'Recent Correction'})`); await (prisma as any).userProgress.update({ where: { id: userProgress.id }, data: { exerciseStatus: 'PENDING' } }); }
// --- 3. Process Response --- const pendingProgress = await (prisma as any).userProgress.findFirst({ where: { userId: user.id, exerciseStatus: { in: ['PENDING', 'PENDING_REMEDIATION', 'PENDING_DEEPDIVE'] }, trackId: activeEnrollment.trackId }, });
if (!pendingProgress) { // If completed and no revalidation, send navigation guidance if (userProgress?.exerciseStatus === 'COMPLETED') { const reminder = user.language === 'WOLOF' ? "Mat nga bés bi ba pare ! ✨\nBindal *2* wala *SUITE* ngir dem ci bés bi ci kanam." : "Tu as déjà validé cette étape ! ✨\nEnvoie *2* ou *SUITE* pour passer à la suite."; await whatsappQueue.add('send-message', { userId: user.id, text: reminder }); return true; } return false; }
const trackDay = await prisma.trackDay.findFirst({ where: { trackId: activeEnrollment.trackId, dayNumber: effectiveDay } });
if (!trackDay) { logger.warn(`${traceId} ⚠️ No TrackDay found for Day ${effectiveDay}.`); return false; }
const isDeepDiveAction = pendingProgress.exerciseStatus === 'PENDING_DEEPDIVE'; const wordCount = (text || '').trim().split(/\s+/).length; // Bypasses (Button, Special, Vision) let isButtonChoice = false; const buttons = trackDay.buttonsJson as any[]; if (Array.isArray(buttons)) { isButtonChoice = buttons.some(b => isFuzzyMatch(normalizedText, b.title || '') || isFuzzyMatch(normalizedText, b.id || '')); }
const isDay7Special = activeEnrollment.currentDay === 7 && ( ['whatsapp', 'boutique', 'digital', 'physique', 'tel', 'e-commerce'].includes(normalizedText) );
const isVisionDay = !!imageUrl; const shouldBypassGuardrail = isButtonChoice || isDay7Special || isVisionDay; const minWordCount = shouldBypassGuardrail ? 1 : 3;
if (wordCount < minWordCount) { const msg = user.language === 'WOLOF' ? "Tontu bi gatt na..." : "Ta réponse est un peu courte."; await whatsappQueue.add('send-message', { userId: user.id, text: msg }); return true; }
await whatsappQueue.add('send-message', { userId: user.id, text: user.language === 'WOLOF' ? "⏳ Defar ak sa tontu..." : "⏳ Analyse de votre réponse..." });
let currentIterationCount = pendingProgress.iterationCount || 0; if (isDeepDiveAction) { currentIterationCount += 1; await (prisma as any).userProgress.update({ where: { id: pendingProgress.id }, data: { iterationCount: currentIterationCount } }); }
await prisma.response.create({ data: { enrollmentId: activeEnrollment.id, userId: user.id, dayNumber: effectiveDay, content: text } });
const previousResponsesData = await prisma.response.findMany({ where: { userId: user.id, enrollmentId: activeEnrollment.id }, orderBy: { dayNumber: 'asc' }, take: 5 }); const previousResponses = previousResponsesData.map(r => ({ day: r.dayNumber, response: r.content }));
logger.info(`${traceId} 🚀 Enqueuing generate-feedback (Day: ${effectiveDay}, TT: ${isTimeTravelMode})`); await whatsappQueue.add('generate-feedback', { userId: user.id, text, trackId: activeEnrollment.trackId, trackDayId: trackDay.id, enrollmentId: activeEnrollment.id, exercisePrompt: trackDay.exercisePrompt || '', lessonText: trackDay.lessonText || '', exerciseCriteria: trackDay.exerciseCriteria, pendingProgressId: pendingProgress.id, currentDay: effectiveDay, totalDays: activeEnrollment.track.duration, language: user.language, userActivity: user.activity, userRegion: user.city, previousResponses, isDeepDive: isDeepDiveAction, iterationCount: currentIterationCount, imageUrl: imageUrl, isButtonChoice: isButtonChoice, isTimeTravelMode, realCurrentDay: activeEnrollment.currentDay }, { attempts: 3, backoff: { type: 'exponential', delay: 2000 } });
return true; }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687import { MessageContext, MessageHandler } from './types';import { isFuzzyMatch } from '../services/utils';import { PrismaClient } from '@repo/database';import { logger } from '../logger';import { clearTimeTravelContext, getTimeTravelContext } from '../timeTravelContext';
const prisma = new PrismaClient();
export class NavigationHandler implements MessageHandler { async canHandle(ctx: MessageContext): Promise<boolean> { const { normalizedText, activeEnrollment } = ctx; if (!activeEnrollment) return false;
const isSuite = isFuzzyMatch(normalizedText, 'SUITE') || normalizedText === '2'; const isApprofondir = isFuzzyMatch(normalizedText, 'APPROFONDIR') || normalizedText === '1';
return isSuite || isApprofondir; }
async handle(ctx: MessageContext): Promise<boolean> { const { user, normalizedText, activeEnrollment, whatsappQueue, redis, traceId } = ctx; if (!user || !activeEnrollment) return false;
const isSuite = isFuzzyMatch(normalizedText, 'SUITE') || normalizedText === '2'; const isApprofondir = isFuzzyMatch(normalizedText, 'APPROFONDIR') || normalizedText === '1';
// --- 1. SUITE (Next Day Navigation) --- if (isSuite) { logger.info(`${traceId} User ${user.id} requested SUITE. Clearing Time-Travel.`); await clearTimeTravelContext(user.id, redis as any);
const userProgress = await (prisma as any).userProgress.findUnique({ where: { userId_trackId: { userId: user.id, trackId: activeEnrollment.trackId } } }); const lastResponse = await prisma.response.findFirst({ where: { userId: user.id, dayNumber: activeEnrollment.currentDay }, orderBy: { createdAt: 'desc' } });
if (userProgress?.exerciseStatus !== 'COMPLETED' && userProgress?.exerciseStatus !== 'PENDING_DEEPDIVE' && !lastResponse) { const msg = user.language === 'WOLOF' ? "Dafa laaj nga tontu !" : "Tu dois d'abord répondre !"; await whatsappQueue.add('send-message', { userId: user.id, text: msg }); return true; }
const nextDay = activeEnrollment.currentDay % 1 !== 0 ? Math.floor(activeEnrollment.currentDay) + 1 : activeEnrollment.currentDay + 1; await prisma.enrollment.update({ where: { id: activeEnrollment.id }, data: { currentDay: nextDay } }); await (prisma as any).userProgress.update({ where: { userId_trackId: { userId: user.id, trackId: activeEnrollment.trackId } }, data: { exerciseStatus: 'PENDING', iterationCount: 0 } }); await whatsappQueue.add('send-content', { userId: user.id, trackId: activeEnrollment.trackId, dayNumber: nextDay }); return true; }
// --- 2. APPROFONDIR (Deep Dive Transition) --- if (isApprofondir) { const timeTravelDay = await getTimeTravelContext(user.id, redis as any); const effectiveDay = timeTravelDay ?? activeEnrollment.currentDay;
const userProgress = await (prisma as any).userProgress.findUnique({ where: { userId_trackId: { userId: user.id, trackId: activeEnrollment.trackId } } }); const lastResponse = await prisma.response.findFirst({ where: { userId: user.id, dayNumber: effectiveDay }, orderBy: { createdAt: 'desc' } });
if (userProgress?.exerciseStatus === 'COMPLETED' || (userProgress?.exerciseStatus === 'PENDING' && lastResponse)) { await (prisma as any).userProgress.update({ where: { id: userProgress!.id }, data: { exerciseStatus: 'PENDING_DEEPDIVE' } }); const msg = user.language === 'WOLOF' ? "Wax ma ndox mi..." : "Très bien ! Quelle info ?"; await whatsappQueue.add('send-message', { userId: user.id, text: msg }); return true; } else { const msg = user.language === 'WOLOF' ? "Tontul exercice bi ba pare !" : "Réponds d'abord à l'exercice principal !"; await whatsappQueue.add('send-message', { userId: user.id, text: msg }); return true; } }
return false; }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132import { MessageContext, MessageHandler } from './types';import { isFuzzyMatch } from '../services/utils';import { PrismaClient } from '@repo/database';import { logger } from '../logger';import { clearTimeTravelContext } from '../timeTravelContext';
const prisma = new PrismaClient();
const SECTOR_LABELS: Record<string, { fr: string; wo: string }> = { SEC_COMMERCE: { fr: 'Commerce / Vente', wo: 'Njaay' }, SEC_AGRI: { fr: 'Agriculture / Élevage', wo: 'Mbay' }, SEC_FOOD: { fr: 'Alimentation / Restauration', wo: 'Lekk / Restauration' }, SEC_TECH: { fr: 'Tech / Digital', wo: 'Tech / Digital' }, SEC_BEAUTE: { fr: 'Beauté / Bien-être', wo: 'Rafet' }, SEC_COUTURE: { fr: 'Couture / Mode', wo: 'Couture' }, SEC_TRANSPORT: { fr: 'Transport / Livraison', wo: 'Transport / Yëgël' },};
export class OnboardingHandler implements MessageHandler { async canHandle(ctx: MessageContext): Promise<boolean> { const { normalizedText, user, activeEnrollment } = ctx; // 1. INSCRIPTION if (isFuzzyMatch(normalizedText, 'INSCRIPTION') || normalizedText.includes('INSCRI')) return true; // 2. Language Selection if (normalizedText === 'LANG_FR' || normalizedText === 'LANG_WO') return true; // 3. Sector Selection (only if not active enrollment) const sectorLabel = SECTOR_LABELS[normalizedText]; if (!activeEnrollment && (sectorLabel || normalizedText.startsWith('SEC_'))) return true; // 4. Activity detection (only if user exists but has no activity and isn't enrolled) if (user && !user.activity && !activeEnrollment && ctx.text.length > 2) return true;
return false; }
async handle(ctx: MessageContext): Promise<boolean> { const { phone, normalizedText, text, whatsappQueue, redis, traceId } = ctx; let user = ctx.user;
// --- 1. INSCRIPTION (Reset or First Time) --- if (isFuzzyMatch(normalizedText, 'INSCRIPTION') || normalizedText.includes('INSCRI')) { if (user) { logger.info(`${traceId} Hard Reset for User ${user.id}`); await clearTimeTravelContext(user.id, redis as any); await (prisma as any).userBadge.deleteMany({ where: { userProgress: { userId: user.id } } }); await (prisma as any).teamMember.deleteMany({ where: { businessProfile: { userId: user.id } } }); await prisma.enrollment.deleteMany({ where: { userId: user.id } }); await prisma.userProgress.deleteMany({ where: { userId: user.id } }); await prisma.response.deleteMany({ where: { userId: user.id } }); await prisma.message.deleteMany({ where: { userId: user.id } }); await (prisma as any).businessProfile.deleteMany({ where: { userId: user.id } }); user = await prisma.user.update({ where: { id: user.id }, data: { city: null, activity: null } }); } else { user = await prisma.user.create({ data: { phone } }); }
await whatsappQueue.add('send-interactive-buttons', { userId: user.id, bodyText: user.language === 'WOLOF' ? "Réinitialisation réussie – tànnal sa làkk :" : "Réinitialisation réussie – choisissez votre langue :", buttons: [ { id: 'LANG_FR', title: 'Français 🇫🇷' }, { id: 'LANG_WO', title: 'Wolof 🇸🇳' } ] }); return true; }
if (!user) return false;
// --- 2. Language selection --- if (normalizedText === 'LANG_FR' || normalizedText === 'LANG_WO') { const newLang = normalizedText === 'LANG_FR' ? 'FR' : 'WOLOF'; user = await prisma.user.update({ where: { id: user.id }, data: { language: newLang } }); const promptText = newLang === 'FR' ? "Parfait ! Dans quel domaine te trouves-tu ?" : "Baax na ! Ci ban mbir ngay yëngu ?"; await whatsappQueue.add('send-interactive-list', { userId: user.id, headerText: newLang === 'FR' ? "Ton secteur" : "Sa Mbir", bodyText: promptText, buttonLabel: newLang === 'FR' ? "Secteurs" : "Tànn", sections: [{ title: newLang === 'FR' ? 'Liste' : 'Mbir', rows: [ { id: 'SEC_COMMERCE', title: newLang === 'FR' ? 'Commerce / Vente' : 'Njaay' }, { id: 'SEC_AGRI', title: newLang === 'FR' ? 'Agri / Élevage' : 'Mbay / Samm' }, { id: 'SEC_FOOD', title: newLang === 'FR' ? 'Alimentation / Rest.' : 'Lekk / Restauration' }, { id: 'SEC_COUTURE', title: newLang === 'FR' ? 'Couture / Mode' : 'Couture' }, { id: 'SEC_BEAUTE', title: newLang === 'FR' ? 'Beauté / Bien-être' : 'Rafet' }, { id: 'SEC_TRANSPORT', title: newLang === 'FR' ? 'Transport / Livr.' : 'Transport / Yëgël' }, { id: 'SEC_TECH', title: newLang === 'FR' ? 'Tech / Digital' : 'Tech / Digital' }, { id: 'SEC_AUTRE', title: newLang === 'FR' ? 'Autre secteur' : 'Beneen mbir' } ] }] }); return true; }
// --- 3. Sector Selection --- const sectorLabel = SECTOR_LABELS[normalizedText]; if (sectorLabel || normalizedText.startsWith('SEC_')) { const activity = sectorLabel ? (user.language === 'WOLOF' ? sectorLabel.wo : sectorLabel.fr) : text.trim(); user = await prisma.user.update({ where: { id: user.id }, data: { activity } }); const msg = user.language === 'FR' ? `Secteur noté : *${activity}*` : `Bind nanu la ci: *${activity}*`; await whatsappQueue.add('send-message', { userId: user.id, text: msg }); const trackId = user.language === 'FR' ? "T1-FR" : "T1-WO"; await whatsappQueue.add('enroll-user', { userId: user.id, trackId }); return true; }
// --- 4. Free-text Activity detection --- if (!user.activity && text.length > 2) { user = await prisma.user.update({ where: { id: user.id }, data: { activity: text.trim() } }); const msg = user.language === 'FR' ? `Secteur noté : *${text.trim()}*` : `Bind nanu la ci: *${text.trim()}*`; await whatsappQueue.add('send-message', { userId: user.id, text: msg }); const trackId = user.language === 'FR' ? "T1-FR" : "T1-WO"; await whatsappQueue.add('enroll-user', { userId: user.id, trackId }); return true; }
return false; }}123456789101112131415161718192021import { User, Enrollment, Track } from '@repo/database';import Redis from 'ioredis';import { Queue } from 'bullmq';
export interface MessageContext { phone: string; text: string; normalizedText: string; audioUrl?: string; imageUrl?: string; traceId: string; user?: User; activeEnrollment?: Enrollment & { track: Track }; redis: Redis; whatsappQueue: Queue;}
export interface MessageHandler { canHandle(ctx: MessageContext): boolean | Promise<boolean>; handle(ctx: MessageContext): Promise<boolean>; // Returns true if it completely handled the message}1234567891011121314151617181920212223242526272829303132export function levenshteinDistance(a: string, b: string): number { const matrix: number[][] = []; for (let i = 0; i <= b.length; i++) matrix[i] = [i]; for (let j = 0; j <= a.length; j++) matrix[0][j] = j;
for (let i = 1; i <= b.length; i++) { for (let j = 1; j <= a.length; j++) { if (b.charAt(i - 1) === a.charAt(j - 1)) { matrix[i][j] = matrix[i - 1][j - 1]; } else { matrix[i][j] = Math.min( matrix[i - 1][j - 1] + 1, matrix[i][j - 1] + 1, matrix[i - 1][j] + 1 ); } } } return matrix[b.length][a.length];}
export function isFuzzyMatch(text: string, target: string, threshold = 0.8): boolean { const normalized = text.trim().toUpperCase(); const tar = target.toUpperCase(); if (normalized === tar) return true; if (normalized.includes(tar) || tar.includes(normalized)) return true;
const distance = levenshteinDistance(normalized, tar); const maxLength = Math.max(normalized.length, tar.length); const similarity = 1 - distance / maxLength; return similarity >= threshold;}1 unmodified line234567891011124 unmodified lines171819202122232425262728294 unmodified lines3435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224231 unmodified lineimport { PrismaClient } from '@repo/database';import { Queue } from 'bullmq';import Redis from 'ioredis';import { getTimeTravelContext, clearTimeTravelContext } from '../timeTravelContext';const prisma = new PrismaClient();// Setup local queue access for the worker-side serviceconst connection = process.env.REDIS_URL? new Redis(process.env.REDIS_URL, { maxRetriesPerRequest: null }): new Redis({4 unmodified linesconst whatsappQueue = new Queue('whatsapp-queue', { connection: connection as any });async function scheduleMessage(userId: string, text: string, delayMs: number = 0) {await whatsappQueue.add('send-message', { userId, text }, { delay: delayMs });}async function enrollUser(userId: string, trackId: string) {await whatsappQueue.add('enroll-user', { userId, trackId });}export class WhatsAppLogic {private static normalizeCommand(text: string): string {4 unmodified lines.toUpperCase();}private static detectIntent(text: string): 'YES' | 'NO' | 'UNKNOWN' {const normalized = text.trim().toLowerCase().replace(/[.,!?;:]+$/, "");const yesWords = ['oui', 'ouais', 'wi', 'waaw', 'yes', 'yep', 'ok', 'd’accord', 'daccord', 'da’accord'];const noWords = ['non', 'déet', 'deet', 'no', 'nah', 'nein'];if (yesWords.some(w => normalized.includes(w))) return 'YES';if (noWords.some(w => normalized.includes(w))) return 'NO';return 'UNKNOWN';}private static levenshteinDistance(a: string, b: string): number {const matrix: number[][] = [];for (let i = 0; i <= b.length; i++) matrix[i] = [i];for (let j = 0; j <= a.length; j++) matrix[0][j] = j;for (let i = 1; i <= b.length; i++) {for (let j = 1; j <= a.length; j++) {if (b.charAt(i - 1) === a.charAt(j - 1)) {matrix[i][j] = matrix[i - 1][j - 1];} else {matrix[i][j] = Math.min(matrix[i - 1][j - 1] + 1,matrix[i][j - 1] + 1,matrix[i - 1][j] + 1);}}}return matrix[b.length][a.length];}private static isFuzzyMatch(text: string, target: string, threshold = 0.8): boolean {const normalized = text.trim().toUpperCase();const tar = target.toUpperCase();if (normalized === tar) return true;if (normalized.includes(tar) || tar.includes(normalized)) return true;const distance = this.levenshteinDistance(normalized, tar);const maxLength = Math.max(normalized.length, tar.length);const similarity = 1 - distance / maxLength;return similarity >= threshold;}static async handleIncomingMessage(phone: string, text: string, audioUrl?: string, imageUrl?: string) {const traceId = audioUrl ? `[STT-FLOW-${phone.slice(-4)}]` : imageUrl ? `[IMG-FLOW-${phone.slice(-4)}]` : `[TXT-FLOW-${phone.slice(-4)}]`;const normalizedText = this.normalizeCommand(text);logger.info(`${traceId} Processing Inbound (Async): ${normalizedText} (Audio: ${audioUrl || 'N/A'})`);// 1. Find or Create Userlet user = await prisma.user.findUnique({ where: { phone } });if (!user) {const isInscription = this.isFuzzyMatch(normalizedText, 'INSCRIPTION') || normalizedText.includes('INSCRI');if (isInscription) {user = await prisma.user.create({ data: { phone } });await whatsappQueue.add('send-interactive-buttons', {userId: user.id,bodyText: "Dalal jàmm! Xamle ngay tàmbali. ⏳ 30s.\n(FR) Ton cours se prépare (30s).",buttons: [{ id: 'LANG_FR', title: 'Français 🇫🇷' },{ id: 'LANG_WO', title: 'Wolof 🇸🇳' }]});return;} else {await whatsappQueue.add('send-message-direct', {phone,text: "🎓 Bienvenue chez XAMLÉ !\nPour commencer ta formation gratuite, envoie le mot : *INSCRIPTION*\n\n(WO) Dalal jàmm ! Ngir tàmbali sa njàng mburu, bindal : *INSCRIPTION*"});return;}}// 1.2 Log messagetry {await prisma.message.create({data: {content: text,mediaUrl: audioUrl || imageUrl,direction: 'INBOUND',userId: user.id}});} catch (err) {}// 1.5. Testing / Cheat Codesif (this.isFuzzyMatch(normalizedText, 'INSCRIPTION')) {// 🚨 COUPE-CIRCUIT #1: Kill Time-Travel context BEFORE any DB resetawait clearTimeTravelContext(user.id, connection as any);await (prisma as any).userBadge.deleteMany({ where: { userProgress: { userId: user.id } } });await (prisma as any).teamMember.deleteMany({ where: { businessProfile: { userId: user.id } } });await prisma.enrollment.deleteMany({ where: { userId: user.id } });await prisma.userProgress.deleteMany({ where: { userId: user.id } });await prisma.response.deleteMany({ where: { userId: user.id } });await prisma.message.deleteMany({ where: { userId: user.id } });await (prisma as any).businessProfile.deleteMany({ where: { userId: user.id } });user = await prisma.user.update({where: { id: user.id },data: { city: null, activity: null }});await whatsappQueue.add('send-interactive-buttons', {userId: user.id,bodyText: "Réinitialisation réussie – choisissez votre langue / Tànnal sa làkk :",buttons: [{ id: 'LANG_FR', title: 'Français 🇫🇷' },{ id: 'LANG_WO', title: 'Wolof 🇸🇳' }]});return;}const systemCommands = ['1', '2', 'SUITE', 'APPROFONDIR', 'INSCRIPTION', 'SEED'];const isSystemCommand = systemCommands.some(cmd => this.isFuzzyMatch(normalizedText, cmd)) || normalizedText.includes('INSCRI');if (text.length < 2 && !isSystemCommand) {await scheduleMessage(user.id, user.language === 'WOLOF'? "Dama lay xaar nga wax ma lu gën a yaatu ci sa mbir. Waxtaanal ak man !": "Je n'ai pas bien compris. Peux-tu me réexpliquer en quelques mots ?");return;}if (this.isFuzzyMatch(normalizedText, 'SEED')) {try {// @ts-ignoreconst { seedDatabase } = await import('@repo/database/seed');const result = await seedDatabase(prisma);await (prisma as any).businessProfile.deleteMany({ where: { userId: user!.id } });await prisma.user.update({ where: { id: user!.id }, data: { activity: null } });await scheduleMessage(user.id, result.seeded? "✅ Seeding terminé ! Le Cache Cognitif a été réinitialisé.\nEnvoie INSCRIPTION pour commencer.": "ℹ️ Les données existent déjà. Cache Cognitif purgé. Envoie INSCRIPTION.");} catch (err) {await scheduleMessage(user.id, `❌ Erreur seed`);}return;}// Handle Interactive LIST menu (REPLAY, EXERCISE, etc.)const dayActionMatch = normalizedText.match(/^DAY(\d+)_(EXERCISE|REPLAY|CONTINUE|PROMPT)$/);if (dayActionMatch) {const action = dayActionMatch[2];const enrollment = await prisma.enrollment.findFirst({ where: { userId: user.id, status: 'ACTIVE' } });if (action === 'REPLAY' && enrollment) {await whatsappQueue.add('send-content', { userId: user.id, trackId: enrollment.trackId, dayNumber: enrollment.currentDay });return;} else if (action === 'EXERCISE') {await scheduleMessage(user.id, user.language === 'WOLOF' ? "🎙️ Yónnee sa tontu :" : "🎙️ Envoie ta réponse :");return;}}// Language selectionif (normalizedText === 'LANG_FR' || normalizedText === 'LANG_WO') {const newLang = normalizedText === 'LANG_FR' ? 'FR' : 'WOLOF';user = await prisma.user.update({ where: { id: user.id }, data: { language: newLang } });const promptText = newLang === 'FR' ? "Parfait ! Dans quel domaine te trouves-tu ?" : "Baax na ! Ci ban mbir ngay yëngu ?";await whatsappQueue.add('send-interactive-list', {userId: user.id,headerText: newLang === 'FR' ? "Ton secteur" : "Sa Mbir",bodyText: promptText,buttonLabel: newLang === 'FR' ? "Secteurs" : "Tànn",sections: [{title: newLang === 'FR' ? 'Liste' : 'Mbir',rows: [{ id: 'SEC_COMMERCE', title: newLang === 'FR' ? 'Commerce / Vente' : 'Njaay' },{ id: 'SEC_AGRI', title: newLang === 'FR' ? 'Agri / Élevage' : 'Mbay / Samm' },{ id: 'SEC_FOOD', title: newLang === 'FR' ? 'Alimentation / Rest.' : 'Lekk / Restauration' },{ id: 'SEC_COUTURE', title: newLang === 'FR' ? 'Couture / Mode' : 'Couture' },{ id: 'SEC_BEAUTE', title: newLang === 'FR' ? 'Beauté / Bien-être' : 'Rafet' },{ id: 'SEC_TRANSPORT', title: newLang === 'FR' ? 'Transport / Livr.' : 'Transport / Yëgël' },{ id: 'SEC_TECH', title: newLang === 'FR' ? 'Tech / Digital' : 'Tech / Digital' },{ id: 'SEC_AUTRE', title: newLang === 'FR' ? 'Autre secteur' : 'Beneen mbir' }]}]});return;}const SECTOR_LABELS: Record<string, { fr: string; wo: string }> = {SEC_COMMERCE: { fr: 'Commerce / Vente', wo: 'Njaay' },SEC_AGRI: { fr: 'Agriculture / Élevage', wo: 'Mbay' },SEC_FOOD: { fr: 'Alimentation / Restauration', wo: 'Lekk / Restauration' },SEC_TECH: { fr: 'Tech / Digital', wo: 'Tech / Digital' },SEC_BEAUTE: { fr: 'Beauté / Bien-être', wo: 'Rafet' },SEC_COUTURE: { fr: 'Couture / Mode', wo: 'Couture' },SEC_TRANSPORT: { fr: 'Transport / Livraison', wo: 'Transport / Yëgël' },};const sectorLabel = SECTOR_LABELS[normalizedText];const activeEnrollment = await prisma.enrollment.findFirst({where: { userId: user.id, status: 'ACTIVE' },include: { track: true }});if (activeEnrollment && (sectorLabel || normalizedText.startsWith('SEC_'))) return;if (!activeEnrollment && (sectorLabel || (!user.activity && text.length > 2))) {const activity = sectorLabel ? (user.language === 'WOLOF' ? sectorLabel.wo : sectorLabel.fr) : text.trim();user = await prisma.user.update({ where: { id: user.id }, data: { activity } });await scheduleMessage(user.id, user.language === 'FR' ? `Secteur noté : *${activity}*` : `Bind nanu la ci: *${activity}*`);const trackId = user.language === 'FR' ? "T1-FR" : "T1-WO";await enrollUser(user.id, trackId);return;}if (activeEnrollment) {this.detectIntent(text); // Scan for intent (log purposes or future use)// 🕰️ TIME-TRAVEL: Compute effectiveDay — single source of truth for actions & flowconst timeTravelDay = await getTimeTravelContext(user.id, connection as any);const effectiveDay = timeTravelDay ?? activeEnrollment.currentDay;const isTimeTravelMode = timeTravelDay !== null && timeTravelDay !== activeEnrollment.currentDay;const isSuite = this.isFuzzyMatch(normalizedText, 'SUITE') || normalizedText === '2';const isApprofondir = this.isFuzzyMatch(normalizedText, 'APPROFONDIR') || normalizedText === '1';if (isSuite) {// 🚨 COUPE-CIRCUIT #2: Kill Time-Travel context BEFORE any progression logicawait clearTimeTravelContext(user.id, connection as any);const userProgress = await prisma.userProgress.findUnique({ where: { userId_trackId: { userId: user.id, trackId: activeEnrollment.trackId } } });const lastResponse = await prisma.response.findFirst({ where: { userId: user.id, dayNumber: activeEnrollment.currentDay }, orderBy: { createdAt: 'desc' } });if (userProgress?.exerciseStatus !== 'COMPLETED' && userProgress?.exerciseStatus !== 'PENDING_DEEPDIVE' && !lastResponse) {await scheduleMessage(user.id, user.language === 'WOLOF' ? "Dafa laaj nga tontu !" : "Tu dois d'abord répondre !");return;}const nextDay = activeEnrollment.currentDay % 1 !== 0 ? Math.floor(activeEnrollment.currentDay) + 1 : activeEnrollment.currentDay + 1;await prisma.enrollment.update({ where: { id: activeEnrollment.id }, data: { currentDay: nextDay } });await prisma.userProgress.update({ where: { userId_trackId: { userId: user.id, trackId: activeEnrollment.trackId } }, data: { exerciseStatus: 'PENDING', iterationCount: 0 } });await whatsappQueue.add('send-content', { userId: user.id, trackId: activeEnrollment.trackId, dayNumber: nextDay });return;}if (isApprofondir) {const userProgress = await prisma.userProgress.findUnique({ where: { userId_trackId: { userId: user.id, trackId: activeEnrollment.trackId } } });// 🕰️ TIME-TRAVEL: check for response on the historical dayconst lastResponse = await prisma.response.findFirst({ where: { userId: user.id, dayNumber: effectiveDay }, orderBy: { createdAt: 'desc' } });if (userProgress?.exerciseStatus === 'COMPLETED' || (userProgress?.exerciseStatus === 'PENDING' && lastResponse)) {await prisma.userProgress.update({ where: { id: userProgress!.id }, data: { exerciseStatus: 'PENDING_DEEPDIVE' } });await scheduleMessage(user.id, user.language === 'WOLOF' ? "Wax ma ndox mi..." : "Très bien ! Quelle info ?");return;}}// 🚨 FLOW-SYNC: Identify current pedagogical stateconst userProgress = await prisma.userProgress.findUnique({where: { userId_trackId: { userId: user.id, trackId: activeEnrollment.trackId } }});logger.info(`[FLOW-SYNC] User ${user.id} at Day ${activeEnrollment.currentDay}, status: ${userProgress?.exerciseStatus}`);const fiveMinutesAgo = new Date(Date.now() - 5 * 60 * 1000);const tenMinutesAgo = new Date(Date.now() - 10 * 60 * 1000);const isRecentlyCompleted = userProgress?.exerciseStatus === 'COMPLETED' && userProgress.updatedAt > fiveMinutesAgo;// 🚨 Anti-Fantôme: Only revalidate with an image if the exercise is actively awaiting input// OR the image arrives shortly after completion (immediate retry). Orphan images (delayed// retries from Meta) arriving > 10 min after COMPLETED must NOT reset progression.const isImageForActiveExercise = !!imageUrl && (userProgress?.exerciseStatus === 'PENDING' ||userProgress?.exerciseStatus === 'PENDING_DEEPDIVE' ||userProgress?.exerciseStatus === 'PENDING_REMEDIATION' ||(userProgress?.exerciseStatus === 'COMPLETED' && userProgress.updatedAt > tenMinutesAgo));const shouldForceRevalidation = isImageForActiveExercise || isRecentlyCompleted;if (shouldForceRevalidation && userProgress?.exerciseStatus === 'COMPLETED') {logger.info(`[FLOW-SYNC] 🔄 Re-validation triggered for User ${user.id} (Reason: ${imageUrl ? 'New Image' : 'Recent Correction'})`);// Briefly reset to PENDING to allow the analysis block below to pick it upawait prisma.userProgress.update({where: { id: userProgress.id },data: { exerciseStatus: 'PENDING' }});}const pendingProgress = await prisma.userProgress.findFirst({where: {userId: user.id,exerciseStatus: { in: ['PENDING', 'PENDING_REMEDIATION', 'PENDING_DEEPDIVE'] },trackId: activeEnrollment.trackId},});if (pendingProgress) {// 🕰️ TIME-TRAVEL: Use pre-calculated effectiveDayif (isTimeTravelMode) {logger.info(`[TIME-TRAVEL] 🕰️ Worker: User ${user.id} replying to Day ${effectiveDay} (real currentDay: ${activeEnrollment.currentDay})`);}const trackDay = await prisma.trackDay.findFirst({ where: { trackId: activeEnrollment.trackId, dayNumber: effectiveDay } });if (trackDay) {logger.info(`[FLOW-SYNC] 🧠 User ${user.id} is at Day ${activeEnrollment.currentDay}, processing response for Day ${activeEnrollment.currentDay}.`);const isDeepDiveAction = pendingProgress.exerciseStatus === 'PENDING_DEEPDIVE';const wordCount = (text || '').trim().split(/\s+/).length;// 🚨 Card/Button Bypass Logic (Lead Product Designer Requirement)let isButtonChoice = false;const buttons = trackDay.buttonsJson as any[];if (Array.isArray(buttons)) {isButtonChoice = buttons.some(b =>this.isFuzzyMatch(normalizedText, b.title || '') ||this.isFuzzyMatch(normalizedText, b.id || ''));}// Special legacy keywords for Day 7const isDay7Special = activeEnrollment.currentDay === 7 && (['whatsapp', 'boutique', 'digital', 'physique', 'tel', 'e-commerce'].includes(normalizedText));const isVisionDay = !!imageUrl; // Any image should bypass wordcount to be analyzedconst shouldBypassGuardrail = isButtonChoice || isDay7Special || isVisionDay;if (isVisionDay) {logger.info(`[IMAGE-FLOW] 📸 Bypassing wordcount for image response on Day ${activeEnrollment.currentDay} for User ${user.id}`);}const minWordCount = shouldBypassGuardrail ? 1 : 3;if (wordCount < minWordCount) {await scheduleMessage(user.id, user.language === 'WOLOF' ? "Tontu bi gatt na..." : "Ta réponse est un peu courte.");return;}await scheduleMessage(user.id, user.language === 'WOLOF' ? "⏳ Defar ak sa tontu..." : "⏳ Analyse de votre réponse...");let currentIterationCount = pendingProgress.iterationCount || 0;if (isDeepDiveAction) {currentIterationCount += 1;await prisma.userProgress.update({ where: { id: pendingProgress.id }, data: { iterationCount: currentIterationCount } });}await prisma.response.create({ data: { enrollmentId: activeEnrollment.id, userId: user.id, dayNumber: effectiveDay, content: text } });const previousResponsesData = await prisma.response.findMany({ where: { userId: user.id, enrollmentId: activeEnrollment.id }, orderBy: { dayNumber: 'asc' }, take: 5 });const previousResponses = previousResponsesData.map(r => ({ day: r.dayNumber, response: r.content }));logger.info(`[LOGIC] 🚀 Enqueuing generate-feedback for User ${user.id} (effectiveDay: ${effectiveDay}, TT: ${isTimeTravelMode}, Button: ${isButtonChoice})`);await whatsappQueue.add('generate-feedback', {userId: user.id, text, trackId: activeEnrollment.trackId, trackDayId: trackDay.id,enrollmentId: activeEnrollment.id,exercisePrompt: trackDay.exercisePrompt || '', lessonText: trackDay.lessonText || '',exerciseCriteria: trackDay.exerciseCriteria, pendingProgressId: pendingProgress.id,currentDay: effectiveDay, // ← effectiveDay: single source of truthtotalDays: activeEnrollment.track.duration, language: user.language,userActivity: user.activity, userRegion: user.city, previousResponses,isDeepDive: isDeepDiveAction, iterationCount: currentIterationCount, imageUrl: imageUrl,isButtonChoice: isButtonChoice,isTimeTravelMode, // ← Worker uses this to skip COMPLETED updaterealCurrentDay: activeEnrollment.currentDay // ← For logging only}, { attempts: 3, backoff: { type: 'exponential', delay: 2000 } });return;} else {logger.info(`[LOGIC] ⚠️ Fall-through: User ${user.id} in enrollment but no matching pendingProgress (Status likely not PENDING).`);}} else {// Enrollment active but no trackDay found for currentDay?logger.warn(`[LOGIC] ⚠️ Active Enrollment for User ${user.id} but TrackDay ${activeEnrollment.currentDay} not found.`);}} else {logger.info(`[LOGIC] ℹ️ User ${user.id} has no active enrollment. Fall-through.`);}// 🌟 UX Guidance Fall-through 🌟// If we reach here, it means we found a user with an active enrollment but no pending exercise (likely COMPLETED).if (activeEnrollment) {const userProgress = await prisma.userProgress.findUnique({where: { userId_trackId: { userId: user.id, trackId: activeEnrollment.trackId } }});if (userProgress?.exerciseStatus === 'COMPLETED') {logger.info(`[LOGIC] 💡 User ${user.id} is COMPLETED. Sending navigation reminder.`);const reminder = user.language === 'WOLOF'? "Mat nga bés bi ba pare ! ✨\nBindal *2* wala *SUITE* ngir dem ci bés bi ci kanam.\n(Bindal *REPLAY* ngir dégtu mbind mi).": "Tu as déjà validé cette étape ! ✨\nEnvoie *2* ou *SUITE* pour passer à la suite.\n(Envoie *REPLAY* pour réécouter la leçon).";await scheduleMessage(user.id, reminder);}}}}1 unmodified line23456789101112131415164 unmodified lines2122232425262728293031324 unmodified lines3738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201 unmodified lineimport { PrismaClient } from '@repo/database';import { Queue } from 'bullmq';import Redis from 'ioredis';import { isFuzzyMatch } from './utils';import { MessageContext, MessageHandler } from '../handlers/types';import { OnboardingHandler } from '../handlers/OnboardingHandler';import { CommandHandler } from '../handlers/CommandHandler';import { NavigationHandler } from '../handlers/NavigationHandler';import { ExerciseHandler } from '../handlers/ExerciseHandler';const prisma = new PrismaClient();const connection = process.env.REDIS_URL? new Redis(process.env.REDIS_URL, { maxRetriesPerRequest: null }): new Redis({4 unmodified linesconst whatsappQueue = new Queue('whatsapp-queue', { connection: connection as any });const handlers: MessageHandler[] = [new OnboardingHandler(),new CommandHandler(),new NavigationHandler(),new ExerciseHandler(),];export class WhatsAppLogic {private static normalizeCommand(text: string): string {4 unmodified lines.toUpperCase();}static async handleIncomingMessage(phone: string, text: string, audioUrl?: string, imageUrl?: string) {const traceId = audioUrl ? `[STT-FLOW-${phone.slice(-4)}]` : imageUrl ? `[IMG-FLOW-${phone.slice(-4)}]` : `[TXT-FLOW-${phone.slice(-4)}]`;const normalizedText = this.normalizeCommand(text);logger.info(`${traceId} Orchestrating Inbound: ${normalizedText}`);// 1. Find User & Enrollmentconst user = await prisma.user.findUnique({ where: { phone } });const activeEnrollment = user ? await prisma.enrollment.findFirst({where: { userId: user.id, status: 'ACTIVE' },include: { track: true }}) as any : null;// 2. Log Message (Non-blocking)if (user) {prisma.message.create({data: {content: text,mediaUrl: audioUrl || imageUrl,direction: 'INBOUND',userId: user.id}}).catch(() => {});}const ctx: MessageContext = {phone,text,normalizedText,audioUrl,imageUrl,traceId,user: user || undefined,activeEnrollment: activeEnrollment || undefined,redis: connection as any,whatsappQueue};// 3. Short Message Guard (Safety)const systemCommands = ['1', '2', 'SUITE', 'APPROFONDIR', 'INSCRIPTION', 'SEED'];const isSystemCommand = systemCommands.some(cmd => isFuzzyMatch(normalizedText, cmd)) || normalizedText.includes('INSCRI');if (text.length < 2 && !isSystemCommand) {const lang = user?.language || 'FR';const msg = lang === 'WOLOF'? "Dama lay xaar nga wax ma lu gën a yaatu ci sa mbir. Waxtaanal ak man !": "Je n'ai pas bien compris. Peux-tu me réexpliquer en quelques mots ?";if (user) {await whatsappQueue.add('send-message', { userId: user.id, text: msg });} else {await whatsappQueue.add('send-message-direct', { phone, text: msg });}return;}// 4. Delegate to Handlersfor (const handler of handlers) {try {if (await handler.canHandle(ctx)) {const handled = await handler.handle(ctx);if (handled) {logger.info(`${traceId} Handled by ${handler.constructor.name}`);return;}}} catch (err: unknown) {logger.error(`${traceId} Error in ${handler.constructor.name}:`, (err instanceof Error ? err.message : String(err)));}}// 5. Fallback Managementif (!user) {await whatsappQueue.add('send-message-direct', {phone,text: "🎓 Bienvenue chez XAMLÉ !\nPour commencer ta formation gratuite, envoie le mot : *INSCRIPTION*"});} else {logger.info(`${traceId} No handler matched for user ${user.id}`);}}}
apps/whatsapp-worker/src/handlers/CommandHandler.tsAdded+60
apps/whatsapp-worker/src/handlers/ExerciseHandler.tsAdded+140
apps/whatsapp-worker/src/handlers/NavigationHandler.tsAdded+87
apps/whatsapp-worker/src/handlers/OnboardingHandler.tsAdded+132
apps/whatsapp-worker/src/handlers/types.tsAdded+21
apps/whatsapp-worker/src/services/utils.tsAdded+32
apps/whatsapp-worker/src/services/whatsapp-logic.ts+64-367