Você é um engenheiro backend sênior. Sua tarefa é evoluir o sistema atual de integração com a API da Infobip para suportar arquitetura multi-WABA com múltiplos senders por conta, com seleção dinâmica de sender no momento do envio. --- # 🎯 OBJETIVO Refatorar o sistema atual para implementar: * 1 serviço = 1 WABA * 1 WABA = múltiplos senders (números WhatsApp) * Templates pertencem ao WABA (não ao sender) * Sender escolhido dinamicamente no envio * Sistema com fallback automático de sender --- # 📚 DOCUMENTAÇÃO (OBRIGATÓRIO USAR) * https://www.infobip.com/docs/api * https://www.infobip.com/docs/essentials/api-essentials/api-authentication * https://www.infobip.com/docs/api/channels/whatsapp/whatsapp-service-management/create-whatsapp-template * https://developers.facebook.com/documentation/business-messaging/whatsapp/messaging-limits --- # 🏗️ MODELAGEM DE DADOS Criar as seguintes estruturas: --- ## WABA (serviço principal) ```json { "id": "waba_1", "name": "Cliente X", "apiKey": "...", "baseUrl": "https://xxxxx.api.infobip.com", "wabaId": "123456" } ``` --- ## SENDERS (ligados ao WABA) ```json { "id": "sender_1", "wabaId": "waba_1", "number": "551199999999", "status": "ACTIVE", "quality": "HIGH", "lastUsedAt": null } ``` --- ## TEMPLATES (ligados ao WABA) ```json { "id": "template_1", "wabaId": "waba_1", "name": "welcome_message", "status": "APPROVED", "components": [] } ``` --- ## MESSAGES ```json { "id": "msg_1", "wabaId": "waba_1", "senderId": "sender_1", "to": "551199999999", "template": "welcome_message", "status": "SENT", "createdAt": 123456789 } ``` --- # 🧠 LÓGICA DE SELEÇÃO DE SENDER Implementar função: ```js function selectSender(wabaId) { const senders = getSendersByWaba(wabaId) const activeSenders = senders.filter(s => s.status === "ACTIVE") if (activeSenders.length === 0) { throw new Error("No active senders available") } // Ordenar por qualidade e menor uso return activeSenders.sort((a, b) => { if (a.quality !== b.quality) { return b.quality.localeCompare(a.quality) } return (a.lastUsedAt || 0) - (b.lastUsedAt || 0) })[0] } ``` --- # 🚀 ENVIO DE MENSAGEM Criar função: ```js async function sendTemplateMessage({ wabaId, to, templateName, params }) { const waba = getWaba(wabaId) const sender = selectSender(wabaId) const response = await fetch(`${waba.baseUrl}/whatsapp/1/message/template`, { method: "POST", headers: { "Authorization": `App ${waba.apiKey}`, "Content-Type": "application/json" }, body: JSON.stringify({ messages: [ { from: sender.number, to: to, content: { templateName: templateName, templateData: { body: { placeholders: params } } } } ] }) }) saveMessage({ wabaId, senderId: sender.id, to, templateName, status: "SENT" }) updateSenderUsage(sender.id) return response.json() } ``` --- # 🔁 FALLBACK AUTOMÁTICO Se falhar: ```js async function sendWithFallback(data) { const senders = getSendersByWaba(data.wabaId) for (const sender of senders) { try { return await sendWithSender(sender, data) } catch (err) { markSenderAsFailed(sender.id) } } throw new Error("All senders failed") } ``` --- # 📡 WEBHOOK (STATUS) Criar endpoint: POST /webhooks/infobip Processar: * SENT * DELIVERED * SEEN * FAILED Atualizar: * status da mensagem * qualidade do sender --- # 📊 ATUALIZAÇÃO DE QUALIDADE DO SENDER Regras: * FAILED → diminuir score * DELIVERED → manter * SEEN → aumentar score --- # 🔧 ENDPOINTS NECESSÁRIOS ## WABA POST /wabas GET /wabas --- ## SENDERS POST /wabas/:id/senders GET /wabas/:id/senders --- ## TEMPLATES POST /wabas/:id/templates GET /wabas/:id/templates --- ## MESSAGES POST /messages/send POST /messages/bulk --- # ⚠️ REGRAS IMPORTANTES * NÃO vincular template a sender * Sender sempre selecionado dinamicamente * Sistema deve suportar múltiplos clientes * Preparar para uso como SaaS --- # 🎯 RESULTADO ESPERADO Sistema backend capaz de: * gerenciar múltiplos WABAs * gerenciar múltiplos senders por WABA * enviar mensagens com fallback automático * acompanhar status em tempo real * escalar para alto volume --- # 💡 IMPORTANTE Essa arquitetura deve permitir: * trocar sender sem impacto * escalar envio * integrar facilmente com CRM no futuro