| import { FastifyInstance } from 'fastify'; |
| import { prisma } from '../services/prisma'; |
| import OpenAI from 'openai'; |
| import { creditWallet } from '../services/wallet'; |
| import { auditService } from '../services/audit'; |
|
|
| const PLAN_LIMITS: Record<string, { aiCreditsLimit: number; label: string }> = { |
| STARTER: { aiCreditsLimit: 500, label: 'Démarrage' }, |
| GROWTH: { aiCreditsLimit: 3000, label: 'Croissance' }, |
| SCALE: { aiCreditsLimit: 10000, label: 'Scale' }, |
| ENTERPRISE: { aiCreditsLimit: 999999, label: 'Enterprise' }, |
| }; |
|
|
| export async function billingRoutes(fastify: FastifyInstance) { |
|
|
| |
| |
| fastify.get('/summary', async (req, reply) => { |
| const organizationId = (req as any).organizationId; |
| if (!organizationId) return reply.code(400).send({ error: 'Organization context required' }); |
|
|
| const org = await prisma.organization.findUnique({ |
| where: { id: organizationId }, |
| select: { |
| subscriptionPlan: true, |
| subscriptionStatus: true, |
| aiCreditsUsed: true, |
| aiCreditsLimit: true, |
| whatsappMessagesSent: true, |
| billingPeriodStart: true, |
| walletBalance: true, |
| isHardStopped: true, |
| } |
| }); |
| if (!org) return reply.code(404).send({ error: 'Organization not found' }); |
|
|
| const plan = org.subscriptionPlan ?? 'STARTER'; |
| const planInfo = PLAN_LIMITS[plan] ?? PLAN_LIMITS.STARTER; |
|
|
| |
| const periodStart = org.billingPeriodStart ?? new Date(new Date().getFullYear(), new Date().getMonth(), 1); |
| const costAgg = await prisma.usageEvent.aggregate({ |
| where: { organizationId, createdAt: { gte: periodStart } }, |
| _sum: { costUsd: true, tokensIn: true, tokensOut: true }, |
| _count: { id: true }, |
| }); |
|
|
| const costUsd = costAgg._sum.costUsd ?? 0; |
| const costFcfa = Math.round(costUsd * 600); |
|
|
| return { |
| plan, |
| planLabel: planInfo.label, |
| subscriptionStatus: org.subscriptionStatus, |
| period: { |
| start: periodStart, |
| end: new Date(periodStart.getFullYear(), periodStart.getMonth() + 1, 0), |
| }, |
| ai: { |
| creditsUsed: org.aiCreditsUsed, |
| creditsLimit: org.aiCreditsLimit, |
| percentUsed: org.aiCreditsLimit > 0 ? Math.round((org.aiCreditsUsed / org.aiCreditsLimit) * 100) : 0, |
| totalCalls: costAgg._count.id, |
| tokensIn: costAgg._sum.tokensIn ?? 0, |
| tokensOut: costAgg._sum.tokensOut ?? 0, |
| costUsd: Math.round(costUsd * 10000) / 10000, |
| costFcfa, |
| }, |
| whatsapp: { |
| messagesSent: org.whatsappMessagesSent, |
| note: 'Facturé directement par Meta sur votre compte WABA', |
| }, |
| wallet: { |
| balance: org.walletBalance, |
| isHardStopped: org.isHardStopped, |
| creditToFcfa: 10, |
| balanceFcfa: org.walletBalance * 10, |
| }, |
| }; |
| }); |
|
|
| |
| |
| fastify.get<{ Querystring: { days?: string } }>('/history', async (req, reply) => { |
| const organizationId = (req as any).organizationId; |
| if (!organizationId) return reply.code(400).send({ error: 'Organization context required' }); |
|
|
| const days = Math.min(parseInt(req.query.days ?? '30', 10), 90); |
| const since = new Date(); |
| since.setDate(since.getDate() - days); |
|
|
| const events = await prisma.usageEvent.findMany({ |
| where: { organizationId, createdAt: { gte: since } }, |
| select: { type: true, feature: true, costUsd: true, tokensIn: true, tokensOut: true, createdAt: true }, |
| orderBy: { createdAt: 'asc' }, |
| }); |
|
|
| |
| const byDay: Record<string, { date: string; aiCalls: number; whatsappMessages: number; costUsd: number; costFcfa: number }> = {}; |
| for (const e of events) { |
| const day = e.createdAt.toISOString().substring(0, 10); |
| if (!byDay[day]) byDay[day] = { date: day, aiCalls: 0, whatsappMessages: 0, costUsd: 0, costFcfa: 0 }; |
| if (e.type === 'WHATSAPP_SENT') byDay[day].whatsappMessages++; |
| else { byDay[day].aiCalls++; byDay[day].costUsd += e.costUsd; } |
| } |
| const result = Object.values(byDay).map(d => ({ ...d, costFcfa: Math.round(d.costUsd * 600) })); |
|
|
| return { days, history: result }; |
| }); |
|
|
| |
| |
| fastify.get('/breakdown', async (req, reply) => { |
| const organizationId = (req as any).organizationId; |
| if (!organizationId) return reply.code(400).send({ error: 'Organization context required' }); |
|
|
| const periodStart = new Date(new Date().getFullYear(), new Date().getMonth(), 1); |
|
|
| const raw = await prisma.usageEvent.groupBy({ |
| by: ['feature', 'type'], |
| where: { organizationId, createdAt: { gte: periodStart }, type: { not: 'WHATSAPP_SENT' } }, |
| _sum: { costUsd: true, tokensIn: true, tokensOut: true }, |
| _count: { id: true }, |
| }); |
|
|
| const breakdown = raw.map(r => ({ |
| feature: r.feature, |
| type: r.type, |
| calls: r._count.id, |
| tokensIn: r._sum.tokensIn ?? 0, |
| tokensOut: r._sum.tokensOut ?? 0, |
| costUsd: Math.round((r._sum.costUsd ?? 0) * 10000) / 10000, |
| costFcfa: Math.round((r._sum.costUsd ?? 0) * 600), |
| })); |
|
|
| return { period: periodStart, breakdown }; |
| }); |
|
|
| |
| |
| fastify.post<{ Body: { question: string; language?: string; page?: string } }>('/chat', async (req, reply) => { |
| const organizationId = (req as any).organizationId; |
| if (!organizationId) return reply.code(400).send({ error: 'Organization context required' }); |
|
|
| const { question, language = 'FR', page = 'billing' } = req.body; |
| if (!question?.trim()) return reply.code(400).send({ error: 'Question is required' }); |
|
|
| const langInstruction: Record<string, string> = { |
| FR: 'Réponds toujours en français.', |
| EN: 'Always reply in English.', |
| ES: 'Responde siempre en español.', |
| PT: 'Responde sempre em português.', |
| }; |
| const replyLang = langInstruction[language.toUpperCase()] ?? langInstruction.FR; |
|
|
| |
| const org = await prisma.organization.findUnique({ |
| where: { id: organizationId }, |
| select: { |
| name: true, subscriptionPlan: true, mode: true, |
| aiCreditsUsed: true, aiCreditsLimit: true, |
| whatsappMessagesSent: true, billingPeriodStart: true, |
| walletBalance: true, isHardStopped: true, |
| wabaId: true, systemUserToken: true, |
| personalityConfig: true, customPrompt: true, |
| } |
| }); |
| if (!org) return reply.code(404).send({ error: 'Organization not found' }); |
|
|
| const PLATFORM_KNOWLEDGE = ` |
| ## XAMLÉ — PLATEFORME D'AUTOMATISATION WHATSAPP BUSINESS |
| |
| ### MODES D'OPÉRATION (champ "mode" de l'organisation) |
| L'organisation fonctionne dans UN seul mode à la fois. Changer de mode change le comportement du bot WhatsApp. |
| |
| **EDTECH** (Formation & Éducation) |
| - Usage : Dispenser des formations structurées via WhatsApp (cours, exercices, certifications) |
| - Fonctionnement : Parcours de formation en plusieurs jours (ex : 21 jours). Chaque jour = 1 leçon + 1 exercice. |
| - L'IA génère des feedbacks personnalisés sur les réponses des apprenants. |
| - Les utilisateurs s'inscrivent à un "Track" (programme), progressent jour par jour. |
| - L'admin crée des Tracks et des TrackDays (contenus) dans le dashboard. |
| - Notifications automatiques : nudges si l'apprenant ne répond pas. |
| - Idéal pour : écoles, organismes de formation, RH, onboarding employés. |
| |
| **CRM_MARKETING** (CRM & Campagnes) |
| - Usage : Envoyer des messages en masse, gérer des contacts, faire des relances automatiques. |
| - Fonctionnement : Import de contacts (Excel/CSV), création de listes de diffusion, envoi de broadcasts via templates WhatsApp approuvés. |
| - L'admin crée des campagnes ciblées (ex : envoyer une promo à tous les clients). |
| - Idéal pour : e-commerce, boutiques, agences marketing, toute entreprise voulant communiquer à grande échelle. |
| |
| **AI_AGENT** (Agent IA Autonome) |
| - Usage : Bot conversationnel 24h/24 qui répond automatiquement aux clients WhatsApp. |
| - Fonctionnement : L'admin configure une "mission" (ex : "Tu es Sarah, assistante du restaurant Le Dakar") et un "ton" (Professionnel/Amical/Direct/Pédagogue). |
| - La "Base de Connaissance" (KB) est le cerveau du bot : documents PDF/DOCX/XLSX/CSV uploadés par l'admin = FAQ, tarifs, menus, fiches produit. |
| - Le bot utilise RAG (Retrieval-Augmented Generation) : il cherche dans la KB puis formule une réponse avec l'IA. |
| - Sans KB, l'agent répond uniquement avec sa mission et son ton, sans connaissance métier. |
| - Idéal pour : service client, hôtels, restaurants, prestataires de services. |
| |
| **CUSTOMER_SERVICE** (Support Client Humain) |
| - Usage : Gérer les conversations entrantes avec escalade vers un agent humain. |
| - Fonctionnement : Le bot peut répondre à des FAQ simples mais transfère les cas complexes à un humain. |
| - Idéal pour : centres d'appel, support technique, SAV. |
| |
| ### PLANS & TARIFICATION |
| **Système de crédits** : 1 crédit = 10 FCFA. Le wallet (portefeuille) est rechargé manuellement par l'équipe Xamlé. |
| - Chaque appel IA consomme des crédits selon la fonctionnalité. |
| - Quand le wallet tombe à 0, le service est suspendu (isHardStopped = true). Recharger pour reprendre. |
| - Les messages WhatsApp sont facturés directement par Meta sur le compte WABA (pas via Xamlé). |
| |
| **STARTER** : 500 crédits IA inclus/mois. Fonctionnalités de base. |
| **GROWTH** : 3 000 crédits IA inclus/mois. Adapté à une croissance modérée. |
| **SCALE** : 10 000 crédits IA inclus/mois + possibilité d'utiliser SES PROPRES clés API (BYOK). |
| **ENTERPRISE** : Crédits illimités, accès complet, SLA dédié. |
| |
| **BYOK (Bring Your Own Key)** : Sur le plan SCALE, l'admin peut entrer ses propres clés OpenAI et Google AI dans les Paramètres > Clés API. Cela permet d'utiliser son propre quota IA (non facturé en crédits Xamlé). |
| |
| ### CONFIGURATION WHATSAPP |
| Pour envoyer/recevoir des messages via WhatsApp Business API (Meta), 3 identifiants sont requis : |
| - **WABA ID** (WhatsApp Business Account ID) : L'identifiant du compte WhatsApp Business. Se trouve dans Meta Business Manager > Comptes WhatsApp Business > votre compte > ID. |
| - **Business ID** (Meta Business ID) : L'identifiant de l'entreprise sur Meta. Se trouve dans Meta Business Manager > Paramètres de l'entreprise > Informations de l'entreprise > ID d'entreprise. |
| - **Token Système** : Clé d'accès permanente (ne jamais utiliser un token temporaire). Généré dans Meta Business Manager > Utilisateurs système > Utilisateur système > Générer un jeton (sélectionner "Ne jamais expirer" + droits whatsapp_business_messaging). |
| - Option rapide : "Se connecter avec Facebook" dans l'onboarding = configuration automatique en 2 clics, Meta pré-remplit tout. |
| - Le token expire si on choisit une durée limitée. Si le bot ne répond plus, vérifier l'expiration du token dans Paramètres. |
| |
| ### TEMPLATES WHATSAPP |
| Les templates sont des messages pré-approuvés par Meta pour initier une conversation (hors fenêtre de 24h). |
| - **Variables** : Les parties dynamiques s'écrivent {{1}}, {{2}}, {{3}} (jamais {{nom}} — uniquement des numéros). |
| - **MARKETING** : Promotionnel, offres, actualités. Délai d'approbation Meta : 24-48h. Soumis à des frais Meta. |
| - **UTILITY** : Transactionnel, confirmations, rappels, notifications. Approuvé plus vite (quelques heures). Moins coûteux. |
| - **Bonnes pratiques** : Courts (< 160 caractères idéalement), clairs, sans fautes. Éviter le ton trop commercial pour UTILITY. |
| - L'admin crée le template dans le dashboard, il est soumis à Meta automatiquement. Statut : PENDING > APPROVED ou REJECTED. |
| - Un template rejeté peut être reformulé et resoumis. |
| |
| ### BASE DE CONNAISSANCE (MODE AI_AGENT) |
| - Formats acceptés : PDF, DOCX, XLSX, CSV (max ~10 Mo par fichier). |
| - Après upload, l'indexation prend 1-3 minutes (les documents sont découpés en chunks et vectorisés). |
| - **Qualité de couverture** : mesure la richesse de la KB. |
| - Excellent (> 80%) : L'agent peut répondre à la grande majorité des questions. |
| - Bon (50-80%) : Couverture correcte mais des lacunes possibles. |
| - Insuffisant (< 50%) : L'agent manque de contexte, réponses génériques probables. |
| - Plus les documents sont spécifiques (FAQ de l'entreprise, tarifs réels, procédures), meilleure est la qualité. |
| |
| ### PARAMÈTRES DE L'ORGANISATION |
| - **Mode** : Choix du mode d'opération (EDTECH, CRM_MARKETING, AI_AGENT, CUSTOMER_SERVICE). |
| - **Configuration avancée (Flow Config)** : JSON de configuration avancée du flux (réservé aux intégrateurs). |
| - **Clés API IA** (plan SCALE uniquement) : OpenAI API Key + Google AI API Key pour BYOK. |
| - **Token WhatsApp** : Si "Expiré" apparaît, regénérer un token dans Meta Business Manager. |
| |
| ### FACTURATION & WALLET |
| - Le **wallet** est le solde de crédits disponibles (1 crédit = 10 FCFA). |
| - Recharge : Contacter l'équipe Xamlé. Le paiement est manuel (virement, mobile money, etc.). |
| - **Alerte solde bas** : Quand le solde passe sous 200 crédits, une alerte apparaît. |
| - **Suspension (Hard Stop)** : Quand le wallet = 0, tous les appels IA sont bloqués. Le service reprend dès recharge. |
| - L'historique de facturation montre jour par jour les appels IA et leur coût. |
| - Le détail par fonctionnalité (LESSON, FEEDBACK, CAMPAIGN, etc.) permet d'identifier les postes de coût. |
| `; |
|
|
| const ADMIN_TOOLS: OpenAI.Chat.ChatCompletionTool[] = [ |
| { |
| type: 'function', |
| function: { |
| name: 'get_organization_settings', |
| description: 'Get the current organization settings including mode, plan, WhatsApp status, wallet, and personality config.', |
| parameters: { type: 'object', properties: {} }, |
| }, |
| }, |
| { |
| type: 'function', |
| function: { |
| name: 'change_organization_mode', |
| description: 'Change the organization operating mode. Only call this if the user explicitly asks to switch or change the mode.', |
| parameters: { |
| type: 'object', |
| properties: { |
| mode: { |
| type: 'string', |
| enum: ['EDTECH', 'CRM_MARKETING', 'AI_AGENT', 'CUSTOMER_SERVICE'], |
| description: 'The new operating mode', |
| }, |
| }, |
| required: ['mode'], |
| }, |
| }, |
| }, |
| { |
| type: 'function', |
| function: { |
| name: 'update_ai_agent_personality', |
| description: 'Update the AI agent personality (mission and/or tone). Only call if the user explicitly asks to update these settings.', |
| parameters: { |
| type: 'object', |
| properties: { |
| coreMission: { type: 'string', description: 'The system prompt / core mission of the AI agent' }, |
| toneDescription: { |
| type: 'string', |
| enum: ['Professionnel', 'Amical', 'Direct', 'Pédagogue'], |
| description: 'Communication tone', |
| }, |
| temperature: { type: 'number', description: 'Creativity level between 0 (precise) and 1 (creative)' }, |
| }, |
| }, |
| }, |
| }, |
| ]; |
|
|
| |
| const executeTool = async (name: string, args: Record<string, unknown>): Promise<string> => { |
| if (name === 'get_organization_settings') { |
| const full = await prisma.organization.findUnique({ |
| where: { id: organizationId }, |
| select: { |
| name: true, mode: true, subscriptionPlan: true, |
| walletBalance: true, isHardStopped: true, |
| wabaId: true, systemUserToken: true, systemUserTokenIssuedAt: true, |
| personalityConfig: true, customPrompt: true, |
| aiCreditsUsed: true, aiCreditsLimit: true, |
| openAiApiKey: true, googleAiApiKey: true, |
| }, |
| }); |
| if (!full) return JSON.stringify({ error: 'Organization not found' }); |
| return JSON.stringify({ |
| name: full.name, |
| mode: full.mode, |
| plan: full.subscriptionPlan, |
| wallet: { balance: full.walletBalance, hardStopped: full.isHardStopped }, |
| whatsapp: { |
| connected: !!(full.wabaId && full.systemUserToken), |
| tokenIssuedAt: full.systemUserTokenIssuedAt, |
| }, |
| aiCredits: { used: full.aiCreditsUsed, limit: full.aiCreditsLimit }, |
| byok: { openAi: !!full.openAiApiKey, google: !!full.googleAiApiKey }, |
| personalityConfig: full.personalityConfig, |
| customPrompt: full.customPrompt, |
| }); |
| } |
|
|
| if (name === 'change_organization_mode') { |
| |
| const callerRole = (req as any).user?.role ?? ''; |
| if (callerRole !== 'SUPER_ADMIN') { |
| return JSON.stringify({ error: 'Mode change requires SUPER_ADMIN privileges. You can update the personality config instead.' }); |
| } |
| const mode = args.mode as string; |
| const allowed = ['EDTECH', 'CRM_MARKETING', 'AI_AGENT', 'CUSTOMER_SERVICE']; |
| if (!allowed.includes(mode)) return JSON.stringify({ error: `Invalid mode. Allowed: ${allowed.join(', ')}` }); |
| await prisma.organization.update({ where: { id: organizationId }, data: { mode: mode as any } }); |
| auditService.log({ |
| action: 'ORG_MODE_CHANGED', |
| actorId: (req as any).user?.id, |
| resourceId: organizationId, |
| details: { newMode: mode, callerRole }, |
| }); |
| return JSON.stringify({ success: true, newMode: mode, message: `Mode changed to ${mode}` }); |
| } |
|
|
| if (name === 'update_ai_agent_personality') { |
| const current = await prisma.organization.findUnique({ |
| where: { id: organizationId }, |
| select: { personalityConfig: true }, |
| }); |
| const existing = (current?.personalityConfig as Record<string, unknown>) ?? {}; |
| const updated: Record<string, unknown> = { ...existing }; |
| if (args.coreMission) updated.coreMission = args.coreMission; |
| if (args.toneDescription) updated.toneDescription = args.toneDescription; |
| if (typeof args.temperature === 'number') updated.temperature = args.temperature; |
| await prisma.organization.update({ |
| where: { id: organizationId }, |
| data: { personalityConfig: updated as any }, |
| }); |
| return JSON.stringify({ success: true, updated }); |
| } |
|
|
| return JSON.stringify({ error: `Unknown tool: ${name}` }); |
| }; |
|
|
| let context: string; |
| let systemPrompt: string; |
|
|
| if (page === 'billing') { |
| const periodStart = org.billingPeriodStart ?? new Date(new Date().getFullYear(), new Date().getMonth(), 1); |
|
|
| const [costAgg, weekAgg, breakdown, recentDebits] = await Promise.all([ |
| prisma.usageEvent.aggregate({ |
| where: { organizationId, createdAt: { gte: periodStart } }, |
| _sum: { costUsd: true }, |
| _count: { id: true }, |
| }), |
| prisma.usageEvent.aggregate({ |
| where: { organizationId, type: { not: 'WHATSAPP_SENT' }, createdAt: { gte: new Date(Date.now() - 7 * 86_400_000) } }, |
| _sum: { costUsd: true }, |
| _count: true, |
| }), |
| prisma.usageEvent.groupBy({ |
| by: ['feature'], |
| where: { organizationId, createdAt: { gte: periodStart }, type: { not: 'WHATSAPP_SENT' } }, |
| _count: { id: true }, |
| orderBy: { _count: { id: 'desc' } }, |
| }), |
| prisma.walletTransaction.aggregate({ |
| where: { organizationId, amount: { lt: 0 }, createdAt: { gte: new Date(Date.now() - 7 * 86_400_000) } }, |
| _sum: { amount: true }, |
| }), |
| ]); |
|
|
| const topFeature = breakdown[0]?.feature ?? 'FEEDBACK'; |
| const topFeaturePct = breakdown[0] && costAgg._count.id > 0 |
| ? Math.round((breakdown[0]._count.id / costAgg._count.id) * 100) : 0; |
| const featureLabels: Record<string, string> = { |
| LESSON: 'Leçons', FEEDBACK: 'Feedbacks exercices', DEEPDIVE: 'Approfondissements', |
| TRANSCRIPTION: 'Transcriptions audio', IMAGE_ANALYSIS: 'Analyses image', |
| CAMPAIGN: 'Campagnes', ONBOARDING: 'Onboarding', OTHER: 'Autres', |
| }; |
| const weeklyDebit = Math.abs(recentDebits._sum.amount ?? 0); |
| const dailyBurn = weeklyDebit / 7; |
| const daysRemaining = dailyBurn > 0 ? Math.floor(org.walletBalance / dailyBurn) : null; |
| const burnInfo = daysRemaining !== null |
| ? `À ce rythme (${Math.round(dailyBurn)} crédits/jour), le solde durera encore environ ${daysRemaining} jour(s).` |
| : 'Aucune consommation récente détectée.'; |
| const walletStatus = org.isHardStopped ? 'SERVICE SUSPENDU (solde épuisé)' |
| : org.walletBalance <= 200 ? `Solde bas (${org.walletBalance} crédits)` |
| : `Actif (${org.walletBalance} crédits)`; |
|
|
| context = `Organisation: ${org.name} |
| Plan: ${org.subscriptionPlan} |
| Période actuelle: depuis le ${periodStart.toLocaleDateString('fr-FR')} |
| --- SOLDE DE CRÉDITS --- |
| Statut: ${walletStatus} |
| Crédits disponibles: ${org.walletBalance} (1 crédit = 10 FCFA) |
| Projection: ${burnInfo} |
| --- UTILISATION CE MOIS --- |
| Appels IA: ${costAgg._count.id} |
| Messages WhatsApp envoyés: ${org.whatsappMessagesSent} |
| Fonctionnalité la plus utilisée: ${featureLabels[topFeature] ?? topFeature} (${topFeaturePct}% des appels) |
| --- UTILISATION CETTE SEMAINE --- |
| Appels IA: ${typeof weekAgg._count === 'number' ? weekAgg._count : (weekAgg._count as any)?.id ?? 0} |
| Crédits consommés: ${weeklyDebit} crédits (= ${weeklyDebit * 10} FCFA)`; |
|
|
| systemPrompt = `Tu es un assistant copilote administrateur pour la plateforme Xamlé. Tu as une connaissance complète de la plateforme et tu peux aussi effectuer des actions d'administration directement (changer le mode, mettre à jour la personnalité de l'agent IA). |
| |
| CONNAISSANCE DE LA PLATEFORME: |
| ${PLATFORM_KNOWLEDGE} |
| |
| Réponds de façon simple, concrète et rassurante. Évite le jargon technique (tokens, API). Utilise les données de l'organisation ci-dessous pour personnaliser ta réponse. ${replyLang}`; |
|
|
| } else { |
| const waConnected = !!(org.wabaId && org.systemUserToken); |
| const modeLabels: Record<string, string> = { |
| EDTECH: 'Formation & EdTech', |
| CRM_MARKETING: 'CRM & Campagnes', |
| AI_AGENT: 'Agent IA Autonome', |
| CUSTOMER_SERVICE: 'Support Client', |
| }; |
|
|
| context = `Organisation: ${org.name} |
| Mode actuel: ${modeLabels[org.mode ?? ''] ?? org.mode} |
| Plan: ${org.subscriptionPlan} |
| WhatsApp connecté: ${waConnected ? 'Oui' : 'Non'} |
| Wallet: ${org.walletBalance} crédits${org.isHardStopped ? ' (SERVICE SUSPENDU)' : ''}`; |
|
|
| systemPrompt = `Tu es un assistant copilote administrateur pour la plateforme Xamlé. Tu as une connaissance complète de la plateforme et tu peux effectuer des actions d'administration directement (changer le mode, mettre à jour la personnalité de l'agent IA). |
| |
| CONNAISSANCE DE LA PLATEFORME: |
| ${PLATFORM_KNOWLEDGE} |
| |
| Réponds de façon directe et précise. Si la question concerne les modes, les templates, la KB, la facturation ou la configuration WhatsApp, utilise ta connaissance de la plateforme pour donner une réponse complète et utile — jamais "contactez le support" pour des questions courantes. Si l'utilisateur demande d'effectuer une action, utilise les outils disponibles. ${replyLang}`; |
| } |
|
|
| try { |
| const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY }); |
| const messages: OpenAI.Chat.ChatCompletionMessageParam[] = [ |
| { role: 'system', content: `${systemPrompt}\n\nDONNÉES ORGANISATION:\n${context}` }, |
| { role: 'user', content: question }, |
| ]; |
|
|
| |
| const first = await openai.chat.completions.create({ |
| model: 'gpt-4o-mini', |
| messages, |
| tools: ADMIN_TOOLS, |
| tool_choice: 'auto', |
| temperature: 0.3, |
| max_tokens: 600, |
| }); |
|
|
| const firstMsg = first.choices[0]?.message; |
| if (!firstMsg) return { answer: 'Je ne peux pas répondre à cette question pour le moment.' }; |
|
|
| |
| if (!firstMsg.tool_calls?.length) { |
| return { answer: firstMsg.content ?? 'Je ne peux pas répondre à cette question pour le moment.' }; |
| } |
|
|
| |
| messages.push(firstMsg); |
| for (const tc of firstMsg.tool_calls) { |
| let args: Record<string, unknown> = {}; |
| try { args = JSON.parse(tc.function.arguments); } catch { } |
| const result = await executeTool(tc.function.name, args); |
| messages.push({ role: 'tool', tool_call_id: tc.id, content: result }); |
| } |
|
|
| |
| const second = await openai.chat.completions.create({ |
| model: 'gpt-4o-mini', |
| messages, |
| temperature: 0.3, |
| max_tokens: 500, |
| }); |
| const answer = second.choices[0]?.message?.content ?? 'Action effectuée.'; |
| return { answer, actionPerformed: firstMsg.tool_calls.map(tc => tc.function.name) }; |
|
|
| } catch (err) { |
| return reply.code(500).send({ error: 'AI billing chat unavailable' }); |
| } |
| }); |
|
|
| |
| |
| fastify.post<{ Body: { description: string; language?: string } }>('/template-generate', async (req, reply) => { |
| const organizationId = (req as any).organizationId; |
| if (!organizationId) return reply.code(400).send({ error: 'Organization context required' }); |
|
|
| const { description, language = 'fr' } = req.body; |
| if (!description?.trim()) return reply.code(400).send({ error: 'description required' }); |
|
|
| const systemPrompt = `Tu es un expert des templates WhatsApp Business API. Génère un template pour l'utilisateur. |
| Réponds UNIQUEMENT avec un JSON valide, sans texte autour, au format: |
| {"name":"snake_case_max_30chars","category":"MARKETING ou UTILITY","body":"texte du template max 1024 chars"} |
| Règles: les variables s'écrivent {{1}}, {{2}} etc. MARKETING = promotionnel. UTILITY = transactionnel, confirmation, rappel. Langue: ${language}.`; |
|
|
| try { |
| const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY }); |
| const completion = await openai.chat.completions.create({ |
| model: 'gpt-4o-mini', |
| messages: [ |
| { role: 'system', content: systemPrompt }, |
| { role: 'user', content: description }, |
| ], |
| temperature: 0.4, |
| max_tokens: 400, |
| response_format: { type: 'json_object' }, |
| }); |
| const raw = completion.choices[0]?.message?.content ?? '{}'; |
| let parsed: { name?: string; category?: string; body?: string } = {}; |
| try { parsed = JSON.parse(raw); } catch { } |
| return { |
| name: parsed.name ?? '', |
| category: parsed.category ?? 'MARKETING', |
| body: parsed.body ?? '', |
| }; |
| } catch { |
| return reply.code(500).send({ error: 'Template generation unavailable' }); |
| } |
| }); |
|
|
| |
| |
| fastify.post<{ Body: { question: string } }>('/agent-test', async (req, reply) => { |
| const organizationId = (req as any).organizationId; |
| if (!organizationId) return reply.code(400).send({ error: 'Organization context required' }); |
|
|
| const { question } = req.body; |
| if (!question?.trim()) return reply.code(400).send({ error: 'question required' }); |
|
|
| const org = await prisma.organization.findUnique({ |
| where: { id: organizationId }, |
| select: { personalityConfig: true, customPrompt: true }, |
| }); |
| if (!org) return reply.code(404).send({ error: 'Organization not found' }); |
|
|
| const personality = (org.personalityConfig as any) ?? {}; |
| const mission = personality.coreMission || org.customPrompt || 'Tu es un assistant virtuel utile et poli.'; |
| const tone = personality.toneDescription || 'Professionnel'; |
|
|
| const systemPrompt = `${mission}\n\nTon de communication: ${tone}. Réponds de façon concise (2-3 phrases maximum). Ceci est un test de configuration — si tu ne connais pas la réponse, dis-le clairement et poliment.`; |
|
|
| try { |
| const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY }); |
| const completion = await openai.chat.completions.create({ |
| model: 'gpt-4o-mini', |
| messages: [ |
| { role: 'system', content: systemPrompt }, |
| { role: 'user', content: question }, |
| ], |
| temperature: 0.5, |
| max_tokens: 200, |
| }); |
| return { answer: completion.choices[0]?.message?.content ?? '' }; |
| } catch { |
| return reply.code(500).send({ error: 'Test unavailable' }); |
| } |
| }); |
|
|
| |
| |
| fastify.get('/wallet', async (req, reply) => { |
| const organizationId = (req as any).organizationId; |
| if (!organizationId) return reply.code(400).send({ error: 'Organization context required' }); |
|
|
| const org = await prisma.organization.findUnique({ |
| where: { id: organizationId }, |
| select: { walletBalance: true, isHardStopped: true }, |
| }); |
| if (!org) return reply.code(404).send({ error: 'Organization not found' }); |
|
|
| const transactions = await prisma.walletTransaction.findMany({ |
| where: { organizationId }, |
| orderBy: { createdAt: 'desc' }, |
| take: 20, |
| select: { id: true, amount: true, balanceAfter: true, type: true, description: true, byok: true, createdAt: true }, |
| }); |
|
|
| return { |
| walletBalance: org.walletBalance, |
| isHardStopped: org.isHardStopped, |
| transactions, |
| }; |
| }); |
|
|
| |
| |
| fastify.post<{ |
| Body: { organizationId: string; amount: number; description?: string } |
| }>('/admin/allocate', async (req, reply) => { |
| const user = (req as any).user; |
| if (!user || user.role !== 'SUPER_ADMIN') { |
| return reply.code(403).send({ error: 'SUPER_ADMIN role required' }); |
| } |
|
|
| const { organizationId, amount, description } = req.body; |
|
|
| if (!organizationId || typeof amount !== 'number' || amount <= 0) { |
| return reply.code(400).send({ error: 'Invalid payload: organizationId and positive amount required' }); |
| } |
|
|
| const org = await prisma.organization.findUnique({ |
| where: { id: organizationId }, |
| select: { id: true, name: true }, |
| }); |
| if (!org) return reply.code(404).send({ error: 'Organization not found' }); |
|
|
| const { newBalance } = await creditWallet({ |
| organizationId, |
| amount, |
| type: 'TOP_UP_MANUAL', |
| actorId: user.id, |
| description: description ?? `Manual top-up by ${user.id}`, |
| }); |
|
|
| return { |
| success: true, |
| organizationId, |
| name: org.name, |
| newBalance, |
| credited: amount, |
| }; |
| }); |
| } |
|
|