elevenlabs-webhook-nodejs 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude/settings.local.json +27 -0
- package/.dockerignore +6 -0
- package/.env.example +43 -0
- package/BEFORE-PRODUCTION.md +32 -0
- package/Dockerfile +23 -0
- package/SYSTEM_OVERVIEW.md +942 -0
- package/SYSTEM_STATUS.md +332 -0
- package/backup_script/main.py +146 -0
- package/baileys/.dockerignore +7 -0
- package/baileys/Dockerfile +13 -0
- package/baileys/README.md +412 -0
- package/baileys/index.js +499 -0
- package/baileys/package-lock.json +2532 -0
- package/baileys/package.json +25 -0
- package/baileys/server.js +96 -0
- package/baileys/src/config.js +55 -0
- package/baileys/src/middleware/api-key.js +16 -0
- package/baileys/src/routes/accounts.js +51 -0
- package/baileys/src/routes/chats.js +103 -0
- package/baileys/src/routes/webhooks.js +34 -0
- package/baileys/src/services/account-store.js +259 -0
- package/baileys/src/services/webhook-dispatcher.js +161 -0
- package/baileys/src/services/worker-manager.js +597 -0
- package/baileys/src/utils/jid.js +79 -0
- package/baileys/src/utils/logger.js +16 -0
- package/baileys/src/utils/use-mongodb-auth-state.js +122 -0
- package/baileys/worker.js +721 -0
- package/dist/app.d.ts +1 -0
- package/dist/app.js +84 -0
- package/dist/app.js.map +1 -0
- package/dist/config/agentPrompts.json +19 -0
- package/dist/config/database.d.ts +1 -0
- package/dist/config/database.js +26 -0
- package/dist/config/database.js.map +1 -0
- package/dist/config/env.d.ts +41 -0
- package/dist/config/env.js +81 -0
- package/dist/config/env.js.map +1 -0
- package/dist/config/index.d.ts +3 -0
- package/dist/config/index.js +73 -0
- package/dist/config/index.js.map +1 -0
- package/dist/controllers/webhook.controller.d.ts +10 -0
- package/dist/controllers/webhook.controller.js +128 -0
- package/dist/controllers/webhook.controller.js.map +1 -0
- package/dist/errors/index.d.ts +4 -0
- package/dist/errors/index.js +13 -0
- package/dist/errors/index.js.map +1 -0
- package/dist/hooks/webhookValidator.d.ts +2 -0
- package/dist/hooks/webhookValidator.js +47 -0
- package/dist/hooks/webhookValidator.js.map +1 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.js +55 -0
- package/dist/index.js.map +1 -0
- package/dist/migrations/001_session-architecture.d.ts +3 -0
- package/dist/migrations/001_session-architecture.js +119 -0
- package/dist/migrations/001_session-architecture.js.map +1 -0
- package/dist/migrations/002_agent-ref.d.ts +3 -0
- package/dist/migrations/002_agent-ref.js +55 -0
- package/dist/migrations/002_agent-ref.js.map +1 -0
- package/dist/migrations/003_shift-schedule.d.ts +3 -0
- package/dist/migrations/003_shift-schedule.js +48 -0
- package/dist/migrations/003_shift-schedule.js.map +1 -0
- package/dist/migrations/004_invert-shift-to-clinic-hours.d.ts +3 -0
- package/dist/migrations/004_invert-shift-to-clinic-hours.js +27 -0
- package/dist/migrations/004_invert-shift-to-clinic-hours.js.map +1 -0
- package/dist/migrations/005_composite-baileys-chat-ids.d.ts +3 -0
- package/dist/migrations/005_composite-baileys-chat-ids.js +47 -0
- package/dist/migrations/005_composite-baileys-chat-ids.js.map +1 -0
- package/dist/migrations/migration.model.d.ts +18 -0
- package/dist/migrations/migration.model.js +45 -0
- package/dist/migrations/migration.model.js.map +1 -0
- package/dist/migrations/migration.routes.d.ts +2 -0
- package/dist/migrations/migration.routes.js +37 -0
- package/dist/migrations/migration.routes.js.map +1 -0
- package/dist/migrations/migration.runner.d.ts +19 -0
- package/dist/migrations/migration.runner.js +74 -0
- package/dist/migrations/migration.runner.js.map +1 -0
- package/dist/models/ConversationClaim.d.ts +13 -0
- package/dist/models/ConversationClaim.js +44 -0
- package/dist/models/ConversationClaim.js.map +1 -0
- package/dist/models/ConversationEvaluation.d.ts +23 -0
- package/dist/models/ConversationEvaluation.js +92 -0
- package/dist/models/ConversationEvaluation.js.map +1 -0
- package/dist/models/Summary.d.ts +37 -0
- package/dist/models/Summary.js +78 -0
- package/dist/models/Summary.js.map +1 -0
- package/dist/models/Transcription.d.ts +34 -0
- package/dist/models/Transcription.js +71 -0
- package/dist/models/Transcription.js.map +1 -0
- package/dist/models/WhatsAppRecipient.d.ts +23 -0
- package/dist/models/WhatsAppRecipient.js +53 -0
- package/dist/models/WhatsAppRecipient.js.map +1 -0
- package/dist/modules/admin/admin.routes.d.ts +2 -0
- package/dist/modules/admin/admin.routes.js +1966 -0
- package/dist/modules/admin/admin.routes.js.map +1 -0
- package/dist/modules/admin/elevenlabs-test-chat.routes.d.ts +2 -0
- package/dist/modules/admin/elevenlabs-test-chat.routes.js +158 -0
- package/dist/modules/admin/elevenlabs-test-chat.routes.js.map +1 -0
- package/dist/modules/admin/whatsapp-test-chat.routes.d.ts +2 -0
- package/dist/modules/admin/whatsapp-test-chat.routes.js +204 -0
- package/dist/modules/admin/whatsapp-test-chat.routes.js.map +1 -0
- package/dist/modules/agents/agent.model.d.ts +38 -0
- package/dist/modules/agents/agent.model.js +92 -0
- package/dist/modules/agents/agent.model.js.map +1 -0
- package/dist/modules/agents/agent.routes.d.ts +2 -0
- package/dist/modules/agents/agent.routes.js +61 -0
- package/dist/modules/agents/agent.routes.js.map +1 -0
- package/dist/modules/appointment-validation/appointment-validation.model.d.ts +76 -0
- package/dist/modules/appointment-validation/appointment-validation.model.js +118 -0
- package/dist/modules/appointment-validation/appointment-validation.model.js.map +1 -0
- package/dist/modules/appointment-validation/appointment-validation.routes.d.ts +2 -0
- package/dist/modules/appointment-validation/appointment-validation.routes.js +202 -0
- package/dist/modules/appointment-validation/appointment-validation.routes.js.map +1 -0
- package/dist/modules/appointment-validation/appointment-validation.service.d.ts +53 -0
- package/dist/modules/appointment-validation/appointment-validation.service.js +827 -0
- package/dist/modules/appointment-validation/appointment-validation.service.js.map +1 -0
- package/dist/modules/auth/auth.model.d.ts +17 -0
- package/dist/modules/auth/auth.model.js +64 -0
- package/dist/modules/auth/auth.model.js.map +1 -0
- package/dist/modules/auth/auth.routes.d.ts +2 -0
- package/dist/modules/auth/auth.routes.js +202 -0
- package/dist/modules/auth/auth.routes.js.map +1 -0
- package/dist/modules/auth/auth.service.d.ts +28 -0
- package/dist/modules/auth/auth.service.js +183 -0
- package/dist/modules/auth/auth.service.js.map +1 -0
- package/dist/modules/auth/refresh-token.model.d.ts +13 -0
- package/dist/modules/auth/refresh-token.model.js +52 -0
- package/dist/modules/auth/refresh-token.model.js.map +1 -0
- package/dist/modules/billing/billing-alert.model.d.ts +16 -0
- package/dist/modules/billing/billing-alert.model.js +47 -0
- package/dist/modules/billing/billing-alert.model.js.map +1 -0
- package/dist/modules/billing/billing-period-snapshot.model.d.ts +35 -0
- package/dist/modules/billing/billing-period-snapshot.model.js +68 -0
- package/dist/modules/billing/billing-period-snapshot.model.js.map +1 -0
- package/dist/modules/billing/billing.model.d.ts +18 -0
- package/dist/modules/billing/billing.model.js +62 -0
- package/dist/modules/billing/billing.model.js.map +1 -0
- package/dist/modules/billing/billing.routes.d.ts +2 -0
- package/dist/modules/billing/billing.routes.js +63 -0
- package/dist/modules/billing/billing.routes.js.map +1 -0
- package/dist/modules/billing/billing.service.d.ts +69 -0
- package/dist/modules/billing/billing.service.js +498 -0
- package/dist/modules/billing/billing.service.js.map +1 -0
- package/dist/modules/billing/payment.model.d.ts +24 -0
- package/dist/modules/billing/payment.model.js +57 -0
- package/dist/modules/billing/payment.model.js.map +1 -0
- package/dist/modules/calls/call.model.d.ts +41 -0
- package/dist/modules/calls/call.model.js +97 -0
- package/dist/modules/calls/call.model.js.map +1 -0
- package/dist/modules/calls/call.routes.d.ts +2 -0
- package/dist/modules/calls/call.routes.js +103 -0
- package/dist/modules/calls/call.routes.js.map +1 -0
- package/dist/modules/campaigns/campaign.model.d.ts +45 -0
- package/dist/modules/campaigns/campaign.model.js +98 -0
- package/dist/modules/campaigns/campaign.model.js.map +1 -0
- package/dist/modules/campaigns/campaign.routes.d.ts +2 -0
- package/dist/modules/campaigns/campaign.routes.js +323 -0
- package/dist/modules/campaigns/campaign.routes.js.map +1 -0
- package/dist/modules/campaigns/campaign.service.d.ts +11 -0
- package/dist/modules/campaigns/campaign.service.js +86 -0
- package/dist/modules/campaigns/campaign.service.js.map +1 -0
- package/dist/modules/google-calendar/google-calendar.routes.d.ts +2 -0
- package/dist/modules/google-calendar/google-calendar.routes.js +32 -0
- package/dist/modules/google-calendar/google-calendar.routes.js.map +1 -0
- package/dist/modules/inbound-call/inbound-call-config.model.d.ts +20 -0
- package/dist/modules/inbound-call/inbound-call-config.model.js +68 -0
- package/dist/modules/inbound-call/inbound-call-config.model.js.map +1 -0
- package/dist/modules/inbound-call/inbound-call.routes.d.ts +2 -0
- package/dist/modules/inbound-call/inbound-call.routes.js +243 -0
- package/dist/modules/inbound-call/inbound-call.routes.js.map +1 -0
- package/dist/modules/leads/lead.model.d.ts +24 -0
- package/dist/modules/leads/lead.model.js +54 -0
- package/dist/modules/leads/lead.model.js.map +1 -0
- package/dist/modules/leads/lead.routes.d.ts +2 -0
- package/dist/modules/leads/lead.routes.js +201 -0
- package/dist/modules/leads/lead.routes.js.map +1 -0
- package/dist/modules/plans/plan.model.d.ts +25 -0
- package/dist/modules/plans/plan.model.js +59 -0
- package/dist/modules/plans/plan.model.js.map +1 -0
- package/dist/modules/surveys/survey.model.d.ts +30 -0
- package/dist/modules/surveys/survey.model.js +75 -0
- package/dist/modules/surveys/survey.model.js.map +1 -0
- package/dist/modules/surveys/survey.routes.d.ts +2 -0
- package/dist/modules/surveys/survey.routes.js +153 -0
- package/dist/modules/surveys/survey.routes.js.map +1 -0
- package/dist/modules/tenants/tenant.model.d.ts +86 -0
- package/dist/modules/tenants/tenant.model.js +127 -0
- package/dist/modules/tenants/tenant.model.js.map +1 -0
- package/dist/modules/tenants/tenant.routes.d.ts +2 -0
- package/dist/modules/tenants/tenant.routes.js +65 -0
- package/dist/modules/tenants/tenant.routes.js.map +1 -0
- package/dist/modules/users/user.routes.d.ts +2 -0
- package/dist/modules/users/user.routes.js +106 -0
- package/dist/modules/users/user.routes.js.map +1 -0
- package/dist/modules/webhooks/elevenlabs-tool.routes.d.ts +20 -0
- package/dist/modules/webhooks/elevenlabs-tool.routes.js +85 -0
- package/dist/modules/webhooks/elevenlabs-tool.routes.js.map +1 -0
- package/dist/modules/webhooks/elevenlabs-tool.service.d.ts +11 -0
- package/dist/modules/webhooks/elevenlabs-tool.service.js +360 -0
- package/dist/modules/webhooks/elevenlabs-tool.service.js.map +1 -0
- package/dist/modules/webhooks/elevenlabs.routes.d.ts +2 -0
- package/dist/modules/webhooks/elevenlabs.routes.js +34 -0
- package/dist/modules/webhooks/elevenlabs.routes.js.map +1 -0
- package/dist/modules/webhooks/elevenlabs.service.d.ts +6 -0
- package/dist/modules/webhooks/elevenlabs.service.js +512 -0
- package/dist/modules/webhooks/elevenlabs.service.js.map +1 -0
- package/dist/modules/webhooks/unipile.routes.d.ts +2 -0
- package/dist/modules/webhooks/unipile.routes.js +780 -0
- package/dist/modules/webhooks/unipile.routes.js.map +1 -0
- package/dist/modules/whatsapp/appointment.model.d.ts +27 -0
- package/dist/modules/whatsapp/appointment.model.js +58 -0
- package/dist/modules/whatsapp/appointment.model.js.map +1 -0
- package/dist/modules/whatsapp/operator-request.model.d.ts +29 -0
- package/dist/modules/whatsapp/operator-request.model.js +65 -0
- package/dist/modules/whatsapp/operator-request.model.js.map +1 -0
- package/dist/modules/whatsapp/stt-usage.model.d.ts +16 -0
- package/dist/modules/whatsapp/stt-usage.model.js +53 -0
- package/dist/modules/whatsapp/stt-usage.model.js.map +1 -0
- package/dist/modules/whatsapp/whatsapp-chat.model.d.ts +23 -0
- package/dist/modules/whatsapp/whatsapp-chat.model.js +55 -0
- package/dist/modules/whatsapp/whatsapp-chat.model.js.map +1 -0
- package/dist/modules/whatsapp/whatsapp-contact-profile.model.d.ts +23 -0
- package/dist/modules/whatsapp/whatsapp-contact-profile.model.js +54 -0
- package/dist/modules/whatsapp/whatsapp-contact-profile.model.js.map +1 -0
- package/dist/modules/whatsapp/whatsapp-message.model.d.ts +30 -0
- package/dist/modules/whatsapp/whatsapp-message.model.js +52 -0
- package/dist/modules/whatsapp/whatsapp-message.model.js.map +1 -0
- package/dist/modules/whatsapp/whatsapp-session.model.d.ts +33 -0
- package/dist/modules/whatsapp/whatsapp-session.model.js +65 -0
- package/dist/modules/whatsapp/whatsapp-session.model.js.map +1 -0
- package/dist/modules/whatsapp/whatsapp.routes.d.ts +2 -0
- package/dist/modules/whatsapp/whatsapp.routes.js +1237 -0
- package/dist/modules/whatsapp/whatsapp.routes.js.map +1 -0
- package/dist/plugins/cors.d.ts +3 -0
- package/dist/plugins/cors.js +11 -0
- package/dist/plugins/cors.js.map +1 -0
- package/dist/plugins/jwt.d.ts +3 -0
- package/dist/plugins/jwt.js +22 -0
- package/dist/plugins/jwt.js.map +1 -0
- package/dist/plugins/rawBody.d.ts +3 -0
- package/dist/plugins/rawBody.js +16 -0
- package/dist/plugins/rawBody.js.map +1 -0
- package/dist/plugins/rbac.d.ts +5 -0
- package/dist/plugins/rbac.js +29 -0
- package/dist/plugins/rbac.js.map +1 -0
- package/dist/routes/admin.routes.d.ts +2 -0
- package/dist/routes/admin.routes.js +169 -0
- package/dist/routes/admin.routes.js.map +1 -0
- package/dist/routes/health.routes.d.ts +2 -0
- package/dist/routes/health.routes.js +16 -0
- package/dist/routes/health.routes.js.map +1 -0
- package/dist/routes/webhook.routes.d.ts +2 -0
- package/dist/routes/webhook.routes.js +17 -0
- package/dist/routes/webhook.routes.js.map +1 -0
- package/dist/services/ai/base.ai.d.ts +19 -0
- package/dist/services/ai/base.ai.js +120 -0
- package/dist/services/ai/base.ai.js.map +1 -0
- package/dist/services/ai/gemini.service.d.ts +11 -0
- package/dist/services/ai/gemini.service.js +43 -0
- package/dist/services/ai/gemini.service.js.map +1 -0
- package/dist/services/ai/index.d.ts +2 -0
- package/dist/services/ai/index.js +26 -0
- package/dist/services/ai/index.js.map +1 -0
- package/dist/services/ai/openai.service.d.ts +11 -0
- package/dist/services/ai/openai.service.js +50 -0
- package/dist/services/ai/openai.service.js.map +1 -0
- package/dist/services/elevenlabs.service.d.ts +52 -0
- package/dist/services/elevenlabs.service.js +447 -0
- package/dist/services/elevenlabs.service.js.map +1 -0
- package/dist/services/google-calendar.service.d.ts +60 -0
- package/dist/services/google-calendar.service.js +494 -0
- package/dist/services/google-calendar.service.js.map +1 -0
- package/dist/services/inbound-call-schedule.service.d.ts +11 -0
- package/dist/services/inbound-call-schedule.service.js +162 -0
- package/dist/services/inbound-call-schedule.service.js.map +1 -0
- package/dist/services/netgsm.service.d.ts +41 -0
- package/dist/services/netgsm.service.js +89 -0
- package/dist/services/netgsm.service.js.map +1 -0
- package/dist/services/unipile.service.d.ts +41 -0
- package/dist/services/unipile.service.js +149 -0
- package/dist/services/unipile.service.js.map +1 -0
- package/dist/services/whatsapp-agent.service.d.ts +139 -0
- package/dist/services/whatsapp-agent.service.js +2055 -0
- package/dist/services/whatsapp-agent.service.js.map +1 -0
- package/dist/services/whatsapp.service.d.ts +26 -0
- package/dist/services/whatsapp.service.js +206 -0
- package/dist/services/whatsapp.service.js.map +1 -0
- package/dist/templates/index.d.ts +39 -0
- package/dist/templates/index.js +35 -0
- package/dist/templates/index.js.map +1 -0
- package/dist/templates/receptionist.d.ts +2 -0
- package/dist/templates/receptionist.js +39 -0
- package/dist/templates/receptionist.js.map +1 -0
- package/dist/templates/survey.d.ts +2 -0
- package/dist/templates/survey.js +41 -0
- package/dist/templates/survey.js.map +1 -0
- package/dist/types/index.d.ts +173 -0
- package/dist/types/index.js +3 -0
- package/dist/types/index.js.map +1 -0
- package/dist/utils/logger.d.ts +3 -0
- package/dist/utils/logger.js +105 -0
- package/dist/utils/logger.js.map +1 -0
- package/docker-compose.nestjs.yml +89 -0
- package/docker-compose.yml +78 -0
- package/docs/AI_AGENT_ENHANCEMENT_PLAN.md +164 -0
- package/docs/API.md +1193 -0
- package/docs/API_ENDPOINTS.md +344 -0
- package/docs/ARCHITECTURE.md +305 -0
- package/docs/AUTH_API.md +252 -0
- package/docs/BILLING_SMS_ALERTS.md +94 -0
- package/docs/CHAT_ASSIGNMENT_SYSTEM.md +118 -0
- package/docs/CLIENT_TOOLS_AND_FEATURES.md +337 -0
- package/docs/ELEVENLABS_WEBHOOK_TOOLS.md +644 -0
- package/docs/FRONTEND_CHECKLIST.md +227 -0
- package/docs/IMPLEMENTATION_STATUS.md +470 -0
- package/docs/MIGRATION_GUIDE.md +96 -0
- package/docs/MISSINGS_REPORT.md +507 -0
- package/docs/NESTJS_MIGRATION_REFERENCE.md +5136 -0
- package/docs/PROJECT_DESCRIPTION.md +1038 -0
- package/docs/SCALING.md +148 -0
- package/docs/SESSION_SUMMARY_2026_03_17.md +135 -0
- package/docs/WHATSAPP_AGENT.md +1086 -0
- package/docs/architecture/00-SYSTEM-OVERVIEW.md +318 -0
- package/docs/architecture/01-DATABASE-SCHEMA.md +2564 -0
- package/docs/architecture/02-AUTHENTICATION.md +1040 -0
- package/docs/architecture/03-MULTI-CLINIC.md +742 -0
- package/docs/architecture/04-WHATSAPP-AGENT.md +608 -0
- package/docs/architecture/05-OPERATOR-WORKFLOW.md +444 -0
- package/docs/architecture/06-BAILEYS-MICROSERVICE.md +616 -0
- package/docs/architecture/07-APPOINTMENTS.md +849 -0
- package/docs/architecture/08-VOICE-CALLS.md +470 -0
- package/docs/architecture/09-OUTBOUND-CAMPAIGNS.md +542 -0
- package/docs/architecture/10-CLIENT-TOOLS.md +665 -0
- package/docs/architecture/11-BILLING.md +458 -0
- package/docs/architecture/12-SECURITY.md +216 -0
- package/docs/architecture/13-LOGGING-AUDIT.md +549 -0
- package/docs/architecture/14-META-BUSINESS-API.md +454 -0
- package/docs/architecture/15-AI-MODULE.md +479 -0
- package/docs/architecture/16-BACKGROUND-JOBS.md +469 -0
- package/docs/architecture/17-REALTIME-LIVECHAT.md +447 -0
- package/docs/architecture/18-FILE-STORAGE.md +410 -0
- package/docs/architecture/19-PATIENTS.md +1034 -0
- package/docs/architecture/20-TREATMENTS-AND-PLANS.md +774 -0
- package/docs/architecture/21-BEFORE-AFTER-PHOTOS.md +519 -0
- package/docs/database.md +456 -0
- package/docs/ornek-randevu-onay.csv +3 -0
- package/ecosystem.config.js +16 -0
- package/elevenlabs-convai-api-reference.md +1171 -0
- package/frontend/.dockerignore +2 -0
- package/frontend/Dockerfile +24 -0
- package/frontend/README.md +75 -0
- package/frontend/components.json +25 -0
- package/frontend/eslint.config.js +23 -0
- package/frontend/index.html +13 -0
- package/frontend/nginx.conf +37 -0
- package/frontend/package-lock.json +8709 -0
- package/frontend/package.json +71 -0
- package/frontend/public/favicon.svg +1 -0
- package/frontend/public/icons.svg +24 -0
- package/frontend/src/App.tsx +125 -0
- package/frontend/src/components/error-boundary.tsx +50 -0
- package/frontend/src/components/shared/activity-timeline.tsx +66 -0
- package/frontend/src/components/shared/appointment-calendar.css +80 -0
- package/frontend/src/components/shared/appointment-calendar.tsx +245 -0
- package/frontend/src/components/shared/chat-bubble.tsx +72 -0
- package/frontend/src/components/shared/combobox.tsx +119 -0
- package/frontend/src/components/shared/confirm-dialog.tsx +57 -0
- package/frontend/src/components/shared/data-table-pagination.tsx +97 -0
- package/frontend/src/components/shared/data-table-toolbar.tsx +39 -0
- package/frontend/src/components/shared/empty-state.tsx +27 -0
- package/frontend/src/components/shared/file-upload.tsx +140 -0
- package/frontend/src/components/shared/index.ts +20 -0
- package/frontend/src/components/shared/language-switcher.tsx +29 -0
- package/frontend/src/components/shared/notification-dropdown.tsx +115 -0
- package/frontend/src/components/shared/page-header.tsx +23 -0
- package/frontend/src/components/shared/stat-card.tsx +37 -0
- package/frontend/src/components/shared/status-badge.tsx +70 -0
- package/frontend/src/components/shared/status-dot.tsx +43 -0
- package/frontend/src/components/ui/alert-dialog.tsx +187 -0
- package/frontend/src/components/ui/alert.tsx +76 -0
- package/frontend/src/components/ui/avatar.tsx +109 -0
- package/frontend/src/components/ui/badge.tsx +52 -0
- package/frontend/src/components/ui/breadcrumb.tsx +125 -0
- package/frontend/src/components/ui/button.tsx +60 -0
- package/frontend/src/components/ui/calendar.tsx +219 -0
- package/frontend/src/components/ui/card.tsx +103 -0
- package/frontend/src/components/ui/chart.tsx +371 -0
- package/frontend/src/components/ui/checkbox.tsx +29 -0
- package/frontend/src/components/ui/collapsible.tsx +19 -0
- package/frontend/src/components/ui/command.tsx +194 -0
- package/frontend/src/components/ui/dialog.tsx +158 -0
- package/frontend/src/components/ui/dropdown-menu.tsx +268 -0
- package/frontend/src/components/ui/input-group.tsx +156 -0
- package/frontend/src/components/ui/input.tsx +20 -0
- package/frontend/src/components/ui/label.tsx +20 -0
- package/frontend/src/components/ui/pagination.tsx +130 -0
- package/frontend/src/components/ui/popover.tsx +90 -0
- package/frontend/src/components/ui/progress.tsx +83 -0
- package/frontend/src/components/ui/radio-group.tsx +36 -0
- package/frontend/src/components/ui/scroll-area.tsx +54 -0
- package/frontend/src/components/ui/select.tsx +199 -0
- package/frontend/src/components/ui/separator.tsx +23 -0
- package/frontend/src/components/ui/sheet.tsx +138 -0
- package/frontend/src/components/ui/sidebar.tsx +723 -0
- package/frontend/src/components/ui/skeleton.tsx +13 -0
- package/frontend/src/components/ui/sonner.tsx +47 -0
- package/frontend/src/components/ui/switch.tsx +30 -0
- package/frontend/src/components/ui/table.tsx +114 -0
- package/frontend/src/components/ui/tabs.tsx +82 -0
- package/frontend/src/components/ui/textarea.tsx +18 -0
- package/frontend/src/components/ui/toggle-group.tsx +89 -0
- package/frontend/src/components/ui/toggle.tsx +43 -0
- package/frontend/src/components/ui/tooltip.tsx +64 -0
- package/frontend/src/hooks/use-mobile.ts +19 -0
- package/frontend/src/i18n/index.ts +20 -0
- package/frontend/src/i18n/locales/en.json +786 -0
- package/frontend/src/i18n/locales/tr.json +786 -0
- package/frontend/src/index.css +134 -0
- package/frontend/src/layouts/admin-layout.tsx +111 -0
- package/frontend/src/layouts/app-header.tsx +130 -0
- package/frontend/src/layouts/app-layout.tsx +19 -0
- package/frontend/src/layouts/app-sidebar.tsx +212 -0
- package/frontend/src/layouts/auth-guard.tsx +31 -0
- package/frontend/src/layouts/mobile-sidebar.tsx +120 -0
- package/frontend/src/lib/api.ts +68 -0
- package/frontend/src/lib/hooks/use-appointments.ts +224 -0
- package/frontend/src/lib/hooks/use-availability-blocks.ts +83 -0
- package/frontend/src/lib/hooks/use-chats.ts +236 -0
- package/frontend/src/lib/hooks/use-clinic-detail.ts +171 -0
- package/frontend/src/lib/hooks/use-clinics.ts +37 -0
- package/frontend/src/lib/hooks/use-doctor-calendar.ts +80 -0
- package/frontend/src/lib/hooks/use-examinations.ts +89 -0
- package/frontend/src/lib/hooks/use-medical-history.ts +52 -0
- package/frontend/src/lib/hooks/use-patients.ts +296 -0
- package/frontend/src/lib/hooks/use-photo-sets.ts +118 -0
- package/frontend/src/lib/hooks/use-treatment-plans.ts +152 -0
- package/frontend/src/lib/hooks/use-treatments.ts +125 -0
- package/frontend/src/lib/hooks/use-users.ts +172 -0
- package/frontend/src/lib/utils.ts +6 -0
- package/frontend/src/main.tsx +17 -0
- package/frontend/src/pages/admin/agents/detail.tsx +774 -0
- package/frontend/src/pages/admin/agents/import.tsx +280 -0
- package/frontend/src/pages/admin/agents/index.tsx +245 -0
- package/frontend/src/pages/admin/ai-playground.tsx +543 -0
- package/frontend/src/pages/appointments/create-appointment-dialog.tsx +390 -0
- package/frontend/src/pages/appointments/index.tsx +860 -0
- package/frontend/src/pages/audit/index.tsx +24 -0
- package/frontend/src/pages/auth/login.tsx +194 -0
- package/frontend/src/pages/billing/index.tsx +24 -0
- package/frontend/src/pages/calendar/index.tsx +704 -0
- package/frontend/src/pages/calendar-connections/index.tsx +295 -0
- package/frontend/src/pages/calls/index.tsx +24 -0
- package/frontend/src/pages/campaigns/index.tsx +24 -0
- package/frontend/src/pages/chats/index.tsx +981 -0
- package/frontend/src/pages/clinics/index.tsx +224 -0
- package/frontend/src/pages/clinics/settings.tsx +412 -0
- package/frontend/src/pages/components-showcase.tsx +773 -0
- package/frontend/src/pages/connections/index.tsx +328 -0
- package/frontend/src/pages/dashboard.tsx +50 -0
- package/frontend/src/pages/leads/index.tsx +24 -0
- package/frontend/src/pages/my-schedule/index.tsx +496 -0
- package/frontend/src/pages/patients/create-patient-dialog.tsx +358 -0
- package/frontend/src/pages/patients/detail.tsx +1195 -0
- package/frontend/src/pages/patients/edit-patient-dialog.tsx +387 -0
- package/frontend/src/pages/patients/examinations-tab.tsx +460 -0
- package/frontend/src/pages/patients/index.tsx +381 -0
- package/frontend/src/pages/patients/medical-history-dialog.tsx +207 -0
- package/frontend/src/pages/patients/photo-sets-tab.tsx +616 -0
- package/frontend/src/pages/patients/timeline-tab.tsx +164 -0
- package/frontend/src/pages/patients/treatment-plans-tab.tsx +598 -0
- package/frontend/src/pages/phone-numbers/detail.tsx +427 -0
- package/frontend/src/pages/phone-numbers/index.tsx +455 -0
- package/frontend/src/pages/platform/index.tsx +454 -0
- package/frontend/src/pages/settings/index.tsx +126 -0
- package/frontend/src/pages/treatments/index.tsx +487 -0
- package/frontend/src/pages/users/doctor-profile.tsx +672 -0
- package/frontend/src/pages/users/edit.tsx +329 -0
- package/frontend/src/pages/users/index.tsx +407 -0
- package/frontend/src/pages/validation/index.tsx +24 -0
- package/frontend/src/stores/auth.store.ts +108 -0
- package/frontend/src/stores/ui.store.ts +41 -0
- package/frontend/tsconfig.app.json +32 -0
- package/frontend/tsconfig.json +13 -0
- package/frontend/tsconfig.node.json +26 -0
- package/frontend/vite.config.ts +29 -0
- package/nestjs/.dockerignore +5 -0
- package/nestjs/.env.docker +64 -0
- package/nestjs/.prettierrc +4 -0
- package/nestjs/Dockerfile +36 -0
- package/nestjs/README.md +98 -0
- package/nestjs/eslint.config.mjs +35 -0
- package/nestjs/nest-cli.json +8 -0
- package/nestjs/package-lock.json +13390 -0
- package/nestjs/package.json +114 -0
- package/nestjs/prisma/migrations/20260409161536_add_message_metadata_fields/migration.sql +1746 -0
- package/nestjs/prisma/migrations/20260410140436_add_agent_ai_fields/migration.sql +36 -0
- package/nestjs/prisma/migrations/20260410175519_add_agent_clinic_assignments/migration.sql +21 -0
- package/nestjs/prisma/migrations/20260412094344_make_agent_tenant_optional/migration.sql +2 -0
- package/nestjs/prisma/migrations/20260412110008_add_admin_chat_sessions/migration.sql +47 -0
- package/nestjs/prisma/migrations/migration_lock.toml +3 -0
- package/nestjs/prisma/schema.prisma +1843 -0
- package/nestjs/prisma/seed.ts +375 -0
- package/nestjs/prisma.config.ts +14 -0
- package/nestjs/src/admin/admin.controller.ts +27 -0
- package/nestjs/src/admin/admin.module.ts +16 -0
- package/nestjs/src/admin/admin.service.ts +91 -0
- package/nestjs/src/admin/ai-chat-session.service.ts +454 -0
- package/nestjs/src/admin/ai-test.controller.ts +191 -0
- package/nestjs/src/admin/superadmin.controller.ts +106 -0
- package/nestjs/src/agents/agents.controller.ts +262 -0
- package/nestjs/src/agents/agents.module.ts +13 -0
- package/nestjs/src/agents/agents.service.ts +733 -0
- package/nestjs/src/agents/dto/create-agent.dto.ts +99 -0
- package/nestjs/src/agents/dto/index.ts +2 -0
- package/nestjs/src/agents/dto/update-agent.dto.ts +148 -0
- package/nestjs/src/app.module.ts +115 -0
- package/nestjs/src/appointment-validation/appointment-validation.controller.ts +194 -0
- package/nestjs/src/appointment-validation/appointment-validation.module.ts +16 -0
- package/nestjs/src/appointment-validation/appointment-validation.service.ts +450 -0
- package/nestjs/src/appointment-validation/dto/create-batch.dto.ts +105 -0
- package/nestjs/src/appointment-validation/dto/index.ts +1 -0
- package/nestjs/src/appointment-validation/processors/validation-dispatch.processor.ts +26 -0
- package/nestjs/src/appointment-validation/processors/validation-sync.processor.ts +23 -0
- package/nestjs/src/appointments/appointments.controller.ts +268 -0
- package/nestjs/src/appointments/appointments.module.ts +13 -0
- package/nestjs/src/appointments/appointments.service.ts +773 -0
- package/nestjs/src/appointments/dto/create-appointment.dto.ts +72 -0
- package/nestjs/src/appointments/dto/index.ts +4 -0
- package/nestjs/src/appointments/dto/query-appointments.dto.ts +60 -0
- package/nestjs/src/appointments/dto/update-appointment.dto.ts +43 -0
- package/nestjs/src/appointments/dto/update-status.dto.ts +18 -0
- package/nestjs/src/appointments/processors/reminder.processor.ts +243 -0
- package/nestjs/src/audit/audit.controller.ts +84 -0
- package/nestjs/src/audit/audit.decorator.ts +20 -0
- package/nestjs/src/audit/audit.interceptor.ts +67 -0
- package/nestjs/src/audit/audit.interfaces.ts +15 -0
- package/nestjs/src/audit/audit.module.ts +12 -0
- package/nestjs/src/audit/audit.service.ts +177 -0
- package/nestjs/src/auth/auth.controller.ts +116 -0
- package/nestjs/src/auth/auth.module.ts +25 -0
- package/nestjs/src/auth/auth.service.ts +612 -0
- package/nestjs/src/auth/dto/change-password.dto.ts +13 -0
- package/nestjs/src/auth/dto/forgot-password.dto.ts +8 -0
- package/nestjs/src/auth/dto/index.ts +6 -0
- package/nestjs/src/auth/dto/login.dto.ts +13 -0
- package/nestjs/src/auth/dto/refresh.dto.ts +8 -0
- package/nestjs/src/auth/dto/register.dto.ts +28 -0
- package/nestjs/src/auth/dto/reset-password.dto.ts +13 -0
- package/nestjs/src/auth/permissions.config.ts +85 -0
- package/nestjs/src/availability-blocks/availability-blocks.controller.ts +83 -0
- package/nestjs/src/availability-blocks/availability-blocks.module.ts +10 -0
- package/nestjs/src/availability-blocks/availability-blocks.service.ts +202 -0
- package/nestjs/src/billing/billing.controller.ts +104 -0
- package/nestjs/src/billing/billing.module.ts +12 -0
- package/nestjs/src/billing/billing.service.ts +398 -0
- package/nestjs/src/billing/dto/index.ts +2 -0
- package/nestjs/src/billing/dto/query-billing.dto.ts +29 -0
- package/nestjs/src/billing/dto/record-payment.dto.ts +60 -0
- package/nestjs/src/billing/processors/alerts.processor.ts +216 -0
- package/nestjs/src/billing/processors/snapshot.processor.ts +181 -0
- package/nestjs/src/calls/calls.controller.ts +92 -0
- package/nestjs/src/calls/calls.module.ts +10 -0
- package/nestjs/src/calls/calls.service.ts +359 -0
- package/nestjs/src/calls/dto/index.ts +1 -0
- package/nestjs/src/calls/dto/query-calls.dto.ts +46 -0
- package/nestjs/src/clinics/clinics.controller.ts +226 -0
- package/nestjs/src/clinics/clinics.module.ts +11 -0
- package/nestjs/src/clinics/clinics.service.ts +203 -0
- package/nestjs/src/clinics/dto/create-clinic.dto.ts +40 -0
- package/nestjs/src/clinics/dto/create-meta-connection.dto.ts +44 -0
- package/nestjs/src/clinics/dto/index.ts +4 -0
- package/nestjs/src/clinics/dto/update-clinic.dto.ts +133 -0
- package/nestjs/src/clinics/dto/update-meta-connection.dto.ts +22 -0
- package/nestjs/src/clinics/meta-connections.service.ts +210 -0
- package/nestjs/src/common/decorators/accessible-clinics.decorator.ts +9 -0
- package/nestjs/src/common/decorators/current-user.decorator.ts +10 -0
- package/nestjs/src/common/decorators/features.decorator.ts +7 -0
- package/nestjs/src/common/decorators/index.ts +4 -0
- package/nestjs/src/common/decorators/permissions.decorator.ts +13 -0
- package/nestjs/src/common/gateways/events.gateway.ts +157 -0
- package/nestjs/src/common/guards/clinic-access.guard.ts +40 -0
- package/nestjs/src/common/guards/features.guard.ts +38 -0
- package/nestjs/src/common/guards/index.ts +5 -0
- package/nestjs/src/common/guards/jwt-auth.guard.ts +54 -0
- package/nestjs/src/common/guards/permissions.guard.ts +50 -0
- package/nestjs/src/common/guards/superadmin.guard.ts +35 -0
- package/nestjs/src/common/interceptors/request-context.interceptor.ts +32 -0
- package/nestjs/src/common/interceptors/superadmin-tenant.interceptor.ts +42 -0
- package/nestjs/src/common/interfaces/jwt-payload.interface.ts +11 -0
- package/nestjs/src/config/config.module.ts +13 -0
- package/nestjs/src/database/database.module.ts +9 -0
- package/nestjs/src/database/prisma.service.ts +20 -0
- package/nestjs/src/database/tenant-context.ts +27 -0
- package/nestjs/src/google-calendar/google-calendar.controller.ts +259 -0
- package/nestjs/src/google-calendar/google-calendar.module.ts +10 -0
- package/nestjs/src/google-calendar/google-calendar.service.ts +811 -0
- package/nestjs/src/integrations/ai/ai.interface.ts +74 -0
- package/nestjs/src/integrations/ai/ai.module.ts +11 -0
- package/nestjs/src/integrations/ai/ai.service.ts +148 -0
- package/nestjs/src/integrations/ai/providers/anthropic.provider.ts +146 -0
- package/nestjs/src/integrations/ai/providers/openai.provider.ts +158 -0
- package/nestjs/src/integrations/elevenlabs/elevenlabs.module.ts +8 -0
- package/nestjs/src/integrations/elevenlabs/elevenlabs.service.ts +226 -0
- package/nestjs/src/integrations/encryption/encryption.module.ts +9 -0
- package/nestjs/src/integrations/encryption/encryption.service.ts +31 -0
- package/nestjs/src/integrations/image/image.module.ts +9 -0
- package/nestjs/src/integrations/image/image.service.ts +61 -0
- package/nestjs/src/integrations/meta-business/meta-business.module.ts +10 -0
- package/nestjs/src/integrations/meta-business/meta-instagram.service.ts +94 -0
- package/nestjs/src/integrations/meta-business/meta-webhook.service.ts +52 -0
- package/nestjs/src/integrations/meta-business/meta-whatsapp.service.ts +254 -0
- package/nestjs/src/integrations/minio/minio.module.ts +9 -0
- package/nestjs/src/integrations/minio/minio.service.ts +88 -0
- package/nestjs/src/integrations/netgsm/netgsm.module.ts +8 -0
- package/nestjs/src/integrations/netgsm/netgsm.service.ts +17 -0
- package/nestjs/src/integrations/tektippay/tektippay.module.ts +8 -0
- package/nestjs/src/integrations/tektippay/tektippay.service.ts +23 -0
- package/nestjs/src/leads/dto/index.ts +2 -0
- package/nestjs/src/leads/dto/query-leads.dto.ts +50 -0
- package/nestjs/src/leads/dto/update-lead.dto.ts +26 -0
- package/nestjs/src/leads/leads.controller.ts +184 -0
- package/nestjs/src/leads/leads.module.ts +10 -0
- package/nestjs/src/leads/leads.service.ts +375 -0
- package/nestjs/src/logging/logging.controller.ts +82 -0
- package/nestjs/src/logging/logging.module.ts +11 -0
- package/nestjs/src/logging/logging.service.ts +180 -0
- package/nestjs/src/main.ts +86 -0
- package/nestjs/src/outbound-campaigns/dto/create-campaign.dto.ts +47 -0
- package/nestjs/src/outbound-campaigns/dto/index.ts +3 -0
- package/nestjs/src/outbound-campaigns/dto/update-campaign.dto.ts +31 -0
- package/nestjs/src/outbound-campaigns/dto/upload-entries.dto.ts +35 -0
- package/nestjs/src/outbound-campaigns/outbound-campaigns.controller.ts +307 -0
- package/nestjs/src/outbound-campaigns/outbound-campaigns.module.ts +13 -0
- package/nestjs/src/outbound-campaigns/outbound-campaigns.service.ts +471 -0
- package/nestjs/src/outbound-campaigns/processors/campaign-dispatch.processor.ts +366 -0
- package/nestjs/src/patients/documents.service.ts +231 -0
- package/nestjs/src/patients/dto/create-examination.dto.ts +34 -0
- package/nestjs/src/patients/dto/create-note.dto.ts +14 -0
- package/nestjs/src/patients/dto/create-patient.dto.ts +86 -0
- package/nestjs/src/patients/dto/create-photo-set.dto.ts +32 -0
- package/nestjs/src/patients/dto/index.ts +10 -0
- package/nestjs/src/patients/dto/update-examination.dto.ts +29 -0
- package/nestjs/src/patients/dto/update-medical-history.dto.ts +47 -0
- package/nestjs/src/patients/dto/update-patient.dto.ts +87 -0
- package/nestjs/src/patients/dto/update-photo-set.dto.ts +28 -0
- package/nestjs/src/patients/dto/upload-document.dto.ts +31 -0
- package/nestjs/src/patients/dto/upload-photo.dto.ts +27 -0
- package/nestjs/src/patients/examinations.service.ts +271 -0
- package/nestjs/src/patients/medical-history.service.ts +149 -0
- package/nestjs/src/patients/notes.service.ts +172 -0
- package/nestjs/src/patients/patients.controller.ts +485 -0
- package/nestjs/src/patients/patients.module.ts +22 -0
- package/nestjs/src/patients/patients.service.ts +412 -0
- package/nestjs/src/patients/photo-sets.service.ts +389 -0
- package/nestjs/src/phone-numbers/dto/create-phone-number.dto.ts +57 -0
- package/nestjs/src/phone-numbers/dto/index.ts +3 -0
- package/nestjs/src/phone-numbers/dto/update-phone-number.dto.ts +38 -0
- package/nestjs/src/phone-numbers/dto/update-schedule.dto.ts +39 -0
- package/nestjs/src/phone-numbers/phone-numbers.controller.ts +125 -0
- package/nestjs/src/phone-numbers/phone-numbers.module.ts +10 -0
- package/nestjs/src/phone-numbers/phone-numbers.service.ts +209 -0
- package/nestjs/src/plans/dto/create-plan.dto.ts +70 -0
- package/nestjs/src/plans/dto/index.ts +2 -0
- package/nestjs/src/plans/dto/update-plan.dto.ts +80 -0
- package/nestjs/src/plans/plans.controller.ts +50 -0
- package/nestjs/src/plans/plans.module.ts +10 -0
- package/nestjs/src/plans/plans.service.ts +115 -0
- package/nestjs/src/platform/dto/create-tenant.dto.ts +36 -0
- package/nestjs/src/platform/dto/index.ts +2 -0
- package/nestjs/src/platform/dto/update-tenant-platform.dto.ts +44 -0
- package/nestjs/src/platform/platform.controller.ts +79 -0
- package/nestjs/src/platform/platform.module.ts +10 -0
- package/nestjs/src/platform/platform.service.ts +301 -0
- package/nestjs/src/queue/queue.module.ts +56 -0
- package/nestjs/src/redis/redis.module.ts +20 -0
- package/nestjs/src/tenants/dto/index.ts +1 -0
- package/nestjs/src/tenants/dto/update-tenant.dto.ts +15 -0
- package/nestjs/src/tenants/tenants.controller.ts +45 -0
- package/nestjs/src/tenants/tenants.module.ts +10 -0
- package/nestjs/src/tenants/tenants.service.ts +41 -0
- package/nestjs/src/tools/adapters/elevenlabs-http.adapter.ts +51 -0
- package/nestjs/src/tools/adapters/elevenlabs-ws.adapter.ts +59 -0
- package/nestjs/src/tools/handlers/calendar.tools.ts +441 -0
- package/nestjs/src/tools/handlers/notification.tools.ts +34 -0
- package/nestjs/src/tools/handlers/operator.tools.ts +303 -0
- package/nestjs/src/tools/handlers/patient.tools.ts +242 -0
- package/nestjs/src/tools/handlers/payment.tools.ts +43 -0
- package/nestjs/src/tools/handlers/validation.tools.ts +152 -0
- package/nestjs/src/tools/tool-registry.service.ts +221 -0
- package/nestjs/src/tools/tool.decorator.ts +16 -0
- package/nestjs/src/tools/tool.interfaces.ts +26 -0
- package/nestjs/src/tools/tools.module.ts +50 -0
- package/nestjs/src/treatments/dto/create-plan-item.dto.ts +27 -0
- package/nestjs/src/treatments/dto/create-treatment-plan.dto.ts +69 -0
- package/nestjs/src/treatments/dto/create-treatment.dto.ts +59 -0
- package/nestjs/src/treatments/dto/index.ts +6 -0
- package/nestjs/src/treatments/dto/update-plan-item.dto.ts +23 -0
- package/nestjs/src/treatments/dto/update-treatment-plan.dto.ts +22 -0
- package/nestjs/src/treatments/dto/update-treatment.dto.ts +70 -0
- package/nestjs/src/treatments/treatment-plans.service.ts +362 -0
- package/nestjs/src/treatments/treatments.controller.ts +265 -0
- package/nestjs/src/treatments/treatments.module.ts +14 -0
- package/nestjs/src/treatments/treatments.service.ts +165 -0
- package/nestjs/src/users/doctor-profiles.service.ts +202 -0
- package/nestjs/src/users/dto/index.ts +4 -0
- package/nestjs/src/users/dto/invite-user.dto.ts +52 -0
- package/nestjs/src/users/dto/update-clinic-assignments.dto.ts +9 -0
- package/nestjs/src/users/dto/update-doctor-profile.dto.ts +49 -0
- package/nestjs/src/users/dto/update-user.dto.ts +41 -0
- package/nestjs/src/users/users.controller.ts +142 -0
- package/nestjs/src/users/users.module.ts +11 -0
- package/nestjs/src/users/users.service.ts +250 -0
- package/nestjs/src/webhooks/elevenlabs-tool.controller.ts +66 -0
- package/nestjs/src/webhooks/elevenlabs-webhook.controller.ts +60 -0
- package/nestjs/src/webhooks/meta-webhook.controller.ts +178 -0
- package/nestjs/src/webhooks/processors/elevenlabs-webhook.processor.ts +28 -0
- package/nestjs/src/webhooks/webhooks.module.ts +17 -0
- package/nestjs/src/whatsapp/chat-context.service.ts +281 -0
- package/nestjs/src/whatsapp/dto/add-blacklist.dto.ts +13 -0
- package/nestjs/src/whatsapp/dto/index.ts +2 -0
- package/nestjs/src/whatsapp/dto/send-message.dto.ts +14 -0
- package/nestjs/src/whatsapp/listeners/meta-message.listener.ts +579 -0
- package/nestjs/src/whatsapp/meta-auth.controller.ts +268 -0
- package/nestjs/src/whatsapp/meta-instagram-auth.controller.ts +244 -0
- package/nestjs/src/whatsapp/operator.service.ts +692 -0
- package/nestjs/src/whatsapp/processors/cost-sweep.processor.ts +130 -0
- package/nestjs/src/whatsapp/processors/grace.processor.ts +191 -0
- package/nestjs/src/whatsapp/processors/message-buffer.processor.ts +138 -0
- package/nestjs/src/whatsapp/processors/message-cleanup.processor.ts +148 -0
- package/nestjs/src/whatsapp/processors/meta-token-refresh.processor.ts +114 -0
- package/nestjs/src/whatsapp/processors/operator-expiry.processor.ts +105 -0
- package/nestjs/src/whatsapp/processors/profile-update.processor.ts +234 -0
- package/nestjs/src/whatsapp/processors/session-cleanup.processor.ts +178 -0
- package/nestjs/src/whatsapp/processors/session-labels.processor.ts +248 -0
- package/nestjs/src/whatsapp/whatsapp-agent.service.ts +2506 -0
- package/nestjs/src/whatsapp/whatsapp-recovery.service.ts +117 -0
- package/nestjs/src/whatsapp/whatsapp.controller.ts +398 -0
- package/nestjs/src/whatsapp/whatsapp.module.ts +51 -0
- package/nestjs/src/whatsapp/whatsapp.service.ts +592 -0
- package/nestjs/test/app.e2e-spec.ts +25 -0
- package/nestjs/test/jest-e2e.json +9 -0
- package/nestjs/tsconfig.build.json +4 -0
- package/nestjs/tsconfig.json +25 -0
- package/nginx.example.conf +18 -0
- package/package.json +47 -0
- package/scripts/addRecipient.ts +48 -0
- package/scripts/listRecipients.ts +31 -0
- package/scripts/migrate-agent-ref.ts +86 -0
- package/scripts/migrate-sessions.ts +183 -0
- package/scripts/promote.ts +27 -0
- package/scripts/retrigger.ts +84 -0
- package/scripts/seed.ts +435 -0
- package/scripts/testSend.ts +63 -0
- package/src/app.ts +85 -0
- package/src/config/agentPrompts.json +19 -0
- package/src/config/database.ts +21 -0
- package/src/config/env.ts +94 -0
- package/src/config/index.ts +86 -0
- package/src/controllers/webhook.controller.ts +150 -0
- package/src/errors/index.ts +9 -0
- package/src/hooks/webhookValidator.ts +55 -0
- package/src/index.ts +68 -0
- package/src/migrations/001_session-architecture.ts +138 -0
- package/src/migrations/002_agent-ref.ts +65 -0
- package/src/migrations/003_shift-schedule.ts +55 -0
- package/src/migrations/004_invert-shift-to-clinic-hours.ts +30 -0
- package/src/migrations/005_composite-baileys-chat-ids.ts +60 -0
- package/src/migrations/migration.model.ts +27 -0
- package/src/migrations/migration.routes.ts +40 -0
- package/src/migrations/migration.runner.ts +112 -0
- package/src/models/ConversationClaim.ts +17 -0
- package/src/models/ConversationEvaluation.ts +91 -0
- package/src/models/Summary.ts +77 -0
- package/src/models/Transcription.ts +68 -0
- package/src/models/WhatsAppRecipient.ts +37 -0
- package/src/modules/admin/admin.routes.ts +2385 -0
- package/src/modules/admin/elevenlabs-test-chat.routes.ts +193 -0
- package/src/modules/admin/whatsapp-test-chat.routes.ts +244 -0
- package/src/modules/agents/agent.model.ts +93 -0
- package/src/modules/agents/agent.routes.ts +65 -0
- package/src/modules/appointment-validation/appointment-validation.model.ts +163 -0
- package/src/modules/appointment-validation/appointment-validation.routes.ts +275 -0
- package/src/modules/appointment-validation/appointment-validation.service.ts +1028 -0
- package/src/modules/auth/auth.model.ts +42 -0
- package/src/modules/auth/auth.routes.ts +199 -0
- package/src/modules/auth/auth.service.ts +210 -0
- package/src/modules/auth/refresh-token.model.ts +26 -0
- package/src/modules/billing/billing-alert.model.ts +28 -0
- package/src/modules/billing/billing-period-snapshot.model.ts +68 -0
- package/src/modules/billing/billing.model.ts +42 -0
- package/src/modules/billing/billing.routes.ts +67 -0
- package/src/modules/billing/billing.service.ts +562 -0
- package/src/modules/billing/payment.model.ts +42 -0
- package/src/modules/calls/call.model.ts +102 -0
- package/src/modules/calls/call.routes.ts +118 -0
- package/src/modules/campaigns/campaign.model.ts +111 -0
- package/src/modules/campaigns/campaign.routes.ts +402 -0
- package/src/modules/campaigns/campaign.service.ts +99 -0
- package/src/modules/google-calendar/google-calendar.routes.ts +31 -0
- package/src/modules/inbound-call/inbound-call-config.model.ts +49 -0
- package/src/modules/inbound-call/inbound-call.routes.ts +289 -0
- package/src/modules/leads/lead.model.ts +40 -0
- package/src/modules/leads/lead.routes.ts +246 -0
- package/src/modules/logs/log.model.ts +27 -0
- package/src/modules/logs/log.routes.ts +102 -0
- package/src/modules/plans/plan.model.ts +45 -0
- package/src/modules/surveys/survey.model.ts +70 -0
- package/src/modules/surveys/survey.routes.ts +187 -0
- package/src/modules/tenants/tenant.model.ts +181 -0
- package/src/modules/tenants/tenant.routes.ts +78 -0
- package/src/modules/users/user.routes.ts +126 -0
- package/src/modules/webhooks/elevenlabs-tool.routes.ts +94 -0
- package/src/modules/webhooks/elevenlabs-tool.service.ts +491 -0
- package/src/modules/webhooks/elevenlabs.routes.ts +34 -0
- package/src/modules/webhooks/elevenlabs.service.ts +565 -0
- package/src/modules/webhooks/unipile.routes.ts +917 -0
- package/src/modules/whatsapp/appointment.model.ts +47 -0
- package/src/modules/whatsapp/operator-request.model.ts +58 -0
- package/src/modules/whatsapp/stt-usage.model.ts +30 -0
- package/src/modules/whatsapp/whatsapp-chat.model.ts +39 -0
- package/src/modules/whatsapp/whatsapp-contact-profile.model.ts +41 -0
- package/src/modules/whatsapp/whatsapp-message.model.ts +41 -0
- package/src/modules/whatsapp/whatsapp-session.model.ts +60 -0
- package/src/modules/whatsapp/whatsapp.routes.ts +1435 -0
- package/src/plugins/cors.ts +7 -0
- package/src/plugins/jwt.ts +18 -0
- package/src/plugins/rawBody.ts +12 -0
- package/src/plugins/rbac.ts +24 -0
- package/src/routes/admin.routes.ts +208 -0
- package/src/routes/health.routes.ts +12 -0
- package/src/routes/webhook.routes.ts +12 -0
- package/src/services/ai/base.ai.ts +132 -0
- package/src/services/ai/gemini.service.ts +41 -0
- package/src/services/ai/index.ts +24 -0
- package/src/services/ai/openai.service.ts +48 -0
- package/src/services/elevenlabs.service.ts +532 -0
- package/src/services/google-calendar.service.ts +656 -0
- package/src/services/inbound-call-schedule.service.ts +174 -0
- package/src/services/netgsm.service.ts +128 -0
- package/src/services/unipile.service.ts +200 -0
- package/src/services/whatsapp-agent.service.ts +2479 -0
- package/src/services/whatsapp.service.ts +245 -0
- package/src/templates/index.ts +71 -0
- package/src/templates/receptionist.ts +44 -0
- package/src/templates/survey.ts +44 -0
- package/src/types/index.ts +218 -0
- package/src/utils/logger.ts +83 -0
- package/tsconfig.json +19 -0
- package/web/.dockerignore +4 -0
- package/web/Dockerfile +18 -0
- package/web/README.md +73 -0
- package/web/components.json +23 -0
- package/web/eslint.config.js +23 -0
- package/web/index.html +14 -0
- package/web/nginx.conf +18 -0
- package/web/package-lock.json +10292 -0
- package/web/package.json +48 -0
- package/web/public/favicon.ico +0 -0
- package/web/public/vite.svg +1 -0
- package/web/src/App.tsx +191 -0
- package/web/src/assets/react.svg +1 -0
- package/web/src/components/Layout.tsx +261 -0
- package/web/src/components/LeadConversation.tsx +251 -0
- package/web/src/components/ProtectedRoute.tsx +20 -0
- package/web/src/components/conversation-review/CardAudioPlayer.tsx +200 -0
- package/web/src/components/conversation-review/CardEvaluation.tsx +351 -0
- package/web/src/components/conversation-review/CardMetadata.tsx +44 -0
- package/web/src/components/conversation-review/ConversationCard.tsx +95 -0
- package/web/src/components/conversation-review/ReviewContainer.tsx +120 -0
- package/web/src/components/conversation-review/ReviewFilters.tsx +88 -0
- package/web/src/components/empty-state.tsx +15 -0
- package/web/src/components/page-header.tsx +19 -0
- package/web/src/components/page-loader.tsx +32 -0
- package/web/src/components/pagination.tsx +38 -0
- package/web/src/components/stat-card.tsx +27 -0
- package/web/src/components/status-badge.tsx +125 -0
- package/web/src/components/ui/alert.tsx +66 -0
- package/web/src/components/ui/badge.tsx +48 -0
- package/web/src/components/ui/button.tsx +64 -0
- package/web/src/components/ui/card.tsx +92 -0
- package/web/src/components/ui/checkbox.tsx +32 -0
- package/web/src/components/ui/dialog.tsx +158 -0
- package/web/src/components/ui/dropdown-menu.tsx +255 -0
- package/web/src/components/ui/input.tsx +21 -0
- package/web/src/components/ui/label.tsx +22 -0
- package/web/src/components/ui/progress.tsx +29 -0
- package/web/src/components/ui/select.tsx +188 -0
- package/web/src/components/ui/separator.tsx +28 -0
- package/web/src/components/ui/sheet.tsx +123 -0
- package/web/src/components/ui/skeleton.tsx +13 -0
- package/web/src/components/ui/sonner.tsx +35 -0
- package/web/src/components/ui/table.tsx +116 -0
- package/web/src/components/ui/tabs.tsx +89 -0
- package/web/src/components/ui/textarea.tsx +18 -0
- package/web/src/components/ui/tooltip.tsx +57 -0
- package/web/src/components/whatsapp/ChatDetail.tsx +417 -0
- package/web/src/components/whatsapp/ChatHeader.tsx +78 -0
- package/web/src/components/whatsapp/ChatList.tsx +107 -0
- package/web/src/components/whatsapp/ChatListItem.tsx +60 -0
- package/web/src/components/whatsapp/MessageBubble.tsx +46 -0
- package/web/src/components/whatsapp/MessageInput.tsx +63 -0
- package/web/src/components/whatsapp/MessageStream.tsx +135 -0
- package/web/src/components/whatsapp/SessionDivider.tsx +65 -0
- package/web/src/components/whatsapp/SessionHistory.tsx +119 -0
- package/web/src/components/whatsapp/settings/AiSettingsTab.tsx +268 -0
- package/web/src/components/whatsapp/settings/CalendarTab.tsx +339 -0
- package/web/src/components/whatsapp/settings/ConnectionTab.tsx +236 -0
- package/web/src/components/whatsapp/settings/NotificationsTab.tsx +109 -0
- package/web/src/components/whatsapp/settings/OperatorTab.tsx +303 -0
- package/web/src/contexts/AuthContext.tsx +103 -0
- package/web/src/index.css +130 -0
- package/web/src/lib/api.ts +92 -0
- package/web/src/lib/utils.ts +6 -0
- package/web/src/main.tsx +10 -0
- package/web/src/pages/AppointmentDetail.tsx +206 -0
- package/web/src/pages/AppointmentValidation.tsx +157 -0
- package/web/src/pages/AppointmentValidationDetail.tsx +617 -0
- package/web/src/pages/AppointmentValidationNew.tsx +1005 -0
- package/web/src/pages/Appointments.tsx +283 -0
- package/web/src/pages/Billing.tsx +126 -0
- package/web/src/pages/CallDetail.tsx +293 -0
- package/web/src/pages/CallSettings.tsx +313 -0
- package/web/src/pages/Calls.tsx +188 -0
- package/web/src/pages/CampaignDetail.tsx +216 -0
- package/web/src/pages/CampaignNew.tsx +277 -0
- package/web/src/pages/CampaignResults.tsx +185 -0
- package/web/src/pages/Campaigns.tsx +171 -0
- package/web/src/pages/Dashboard.tsx +336 -0
- package/web/src/pages/InboundSchedule.tsx +246 -0
- package/web/src/pages/LeadDetail.tsx +183 -0
- package/web/src/pages/Leads.tsx +258 -0
- package/web/src/pages/Login.tsx +99 -0
- package/web/src/pages/Register.tsx +129 -0
- package/web/src/pages/Settings.tsx +133 -0
- package/web/src/pages/SurveyDetail.tsx +232 -0
- package/web/src/pages/SurveyPreview.tsx +179 -0
- package/web/src/pages/Surveys.tsx +207 -0
- package/web/src/pages/Users.tsx +199 -0
- package/web/src/pages/WhatsApp.tsx +147 -0
- package/web/src/pages/WhatsAppSettings.tsx +215 -0
- package/web/src/pages/admin/AdminBaileysMessageLog.tsx +331 -0
- package/web/src/pages/admin/AdminBaileysRawMessages.tsx +318 -0
- package/web/src/pages/admin/AdminConversationReview.tsx +116 -0
- package/web/src/pages/admin/AdminCredits.tsx +467 -0
- package/web/src/pages/admin/AdminElevenLabsAgentDetail.tsx +332 -0
- package/web/src/pages/admin/AdminElevenLabsAgents.tsx +164 -0
- package/web/src/pages/admin/AdminElevenLabsBatchCallDetail.tsx +214 -0
- package/web/src/pages/admin/AdminElevenLabsBatchCalls.tsx +293 -0
- package/web/src/pages/admin/AdminElevenLabsConversationDetail.tsx +230 -0
- package/web/src/pages/admin/AdminElevenLabsConversations.tsx +228 -0
- package/web/src/pages/admin/AdminElevenLabsInboundCalls.tsx +293 -0
- package/web/src/pages/admin/AdminElevenLabsPhoneNumbers.tsx +506 -0
- package/web/src/pages/admin/AdminElevenLabsTestChat.tsx +258 -0
- package/web/src/pages/admin/AdminElevenLabsWebhooks.tsx +289 -0
- package/web/src/pages/admin/AdminEvaluationDashboard.tsx +520 -0
- package/web/src/pages/admin/AdminLeads.tsx +339 -0
- package/web/src/pages/admin/AdminLogs.tsx +283 -0
- package/web/src/pages/admin/AdminMigrations.tsx +247 -0
- package/web/src/pages/admin/AdminPlans.tsx +313 -0
- package/web/src/pages/admin/AdminSystem.tsx +391 -0
- package/web/src/pages/admin/AdminTenantBillableItems.tsx +464 -0
- package/web/src/pages/admin/AdminTenantDetail.tsx +1317 -0
- package/web/src/pages/admin/AdminTenants.tsx +274 -0
- package/web/src/pages/admin/AdminWhatsApp.tsx +618 -0
- package/web/src/pages/admin/AdminWhatsAppTestChat.tsx +328 -0
- package/web/src/types/index.ts +242 -0
- package/web/tsconfig.app.json +32 -0
- package/web/tsconfig.json +13 -0
- package/web/tsconfig.node.json +26 -0
- package/web/vite.config.ts +23 -0
|
@@ -0,0 +1,1435 @@
|
|
|
1
|
+
import type { FastifyInstance } from 'fastify';
|
|
2
|
+
import mongoose from 'mongoose';
|
|
3
|
+
import { requireRole, requireFeature } from '../../plugins/rbac';
|
|
4
|
+
import WhatsAppChat from './whatsapp-chat.model';
|
|
5
|
+
import WhatsAppSession from './whatsapp-session.model';
|
|
6
|
+
import WhatsAppMessage from './whatsapp-message.model';
|
|
7
|
+
import unipileService from '../../services/unipile.service';
|
|
8
|
+
import whatsappAgentService from '../../services/whatsapp-agent.service';
|
|
9
|
+
import Tenant from '../tenants/tenant.model';
|
|
10
|
+
import Agent from '../agents/agent.model';
|
|
11
|
+
import WhatsAppContactProfile from './whatsapp-contact-profile.model';
|
|
12
|
+
import googleCalendarService from '../../services/google-calendar.service';
|
|
13
|
+
import Appointment from './appointment.model';
|
|
14
|
+
import logger from '../../utils/logger';
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Derives backward-compatible virtual fields (mode, session_status, taken_over_by, etc.)
|
|
18
|
+
* from the chat's active session, for frontend consumption.
|
|
19
|
+
*/
|
|
20
|
+
async function enrichChat(chatDoc: any): Promise<any> {
|
|
21
|
+
const chat = typeof chatDoc.toObject === 'function' ? chatDoc.toObject() : { ...chatDoc };
|
|
22
|
+
|
|
23
|
+
let session: any = null;
|
|
24
|
+
if (chat.active_session_id) {
|
|
25
|
+
session = await WhatsAppSession.findById(chat.active_session_id)
|
|
26
|
+
.populate('taken_over_by', 'name email')
|
|
27
|
+
.lean();
|
|
28
|
+
if (session && session.status === 'resolved') {
|
|
29
|
+
session = null;
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
if (!session) {
|
|
34
|
+
chat.mode = chat.is_closed ? 'closed' : 'ai';
|
|
35
|
+
chat.session_status = 'idle';
|
|
36
|
+
chat.taken_over_by = null;
|
|
37
|
+
chat.taken_over_at = null;
|
|
38
|
+
chat.session_started_at = null;
|
|
39
|
+
chat.session_grace_deadline = null;
|
|
40
|
+
chat.session_resolved_by = null;
|
|
41
|
+
} else if (session.status === 'waiting') {
|
|
42
|
+
chat.mode = 'human';
|
|
43
|
+
chat.session_status = 'waiting';
|
|
44
|
+
chat.taken_over_by = null;
|
|
45
|
+
chat.taken_over_at = null;
|
|
46
|
+
chat.session_started_at = session.started_at;
|
|
47
|
+
chat.session_grace_deadline = session.grace_deadline;
|
|
48
|
+
chat.session_resolved_by = null;
|
|
49
|
+
} else if (session.status === 'active') {
|
|
50
|
+
const isHuman = !!(session.taken_over_by || session.taken_over_at);
|
|
51
|
+
chat.mode = isHuman ? 'human' : 'ai';
|
|
52
|
+
chat.session_status = 'idle';
|
|
53
|
+
chat.taken_over_by = session.taken_over_by || null;
|
|
54
|
+
chat.taken_over_at = session.taken_over_at || null;
|
|
55
|
+
chat.session_started_at = session.started_at;
|
|
56
|
+
chat.session_grace_deadline = null;
|
|
57
|
+
chat.session_resolved_by = null;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
// Remove internal-only fields
|
|
61
|
+
delete chat.active_session_id;
|
|
62
|
+
delete chat.is_closed;
|
|
63
|
+
|
|
64
|
+
// Remove aggregation pipeline temporary fields
|
|
65
|
+
delete chat._session;
|
|
66
|
+
delete chat._activeSession;
|
|
67
|
+
delete chat._mode;
|
|
68
|
+
|
|
69
|
+
return chat;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Enrich multiple chats in parallel.
|
|
74
|
+
*/
|
|
75
|
+
async function enrichChats(chatDocs: any[]): Promise<any[]> {
|
|
76
|
+
return Promise.all(chatDocs.map(c => enrichChat(c)));
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
export default async function whatsappRoutes(fastify: FastifyInstance): Promise<void> {
|
|
80
|
+
fastify.addHook('preHandler', fastify.authenticate);
|
|
81
|
+
fastify.addHook('preHandler', requireFeature('whatsapp_agent'));
|
|
82
|
+
|
|
83
|
+
// ─── Connection Management ───────────────────────────────
|
|
84
|
+
|
|
85
|
+
// POST /whatsapp/connect — Initiate WhatsApp QR code connection
|
|
86
|
+
fastify.post('/connect', {
|
|
87
|
+
preHandler: [requireRole('admin')],
|
|
88
|
+
}, async (request, reply) => {
|
|
89
|
+
const tenant = await Tenant.findById(request.user.tenant_id);
|
|
90
|
+
const provider = unipileService.getProviderForTenant(tenant);
|
|
91
|
+
const existingAccountId = tenant?.settings?.whatsapp_agent?.unipile_account_id;
|
|
92
|
+
|
|
93
|
+
// Try to reconnect existing account first
|
|
94
|
+
if (existingAccountId) {
|
|
95
|
+
try {
|
|
96
|
+
const result = await unipileService.reconnectAccount(provider, existingAccountId);
|
|
97
|
+
logger.info('WhatsApp reconnect result', { provider, accountId: existingAccountId, result: JSON.stringify(result).substring(0, 500) });
|
|
98
|
+
|
|
99
|
+
await Tenant.findByIdAndUpdate(request.user.tenant_id, {
|
|
100
|
+
$set: { 'settings.whatsapp_agent.unipile_account_status': 'pending' }
|
|
101
|
+
});
|
|
102
|
+
|
|
103
|
+
return result;
|
|
104
|
+
} catch (err) {
|
|
105
|
+
logger.warn('Reconnect failed, creating new account', {
|
|
106
|
+
accountId: existingAccountId,
|
|
107
|
+
error: (err as Error).message,
|
|
108
|
+
});
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
// Create new account
|
|
113
|
+
const result = await unipileService.connectWhatsApp(provider);
|
|
114
|
+
logger.info('WhatsApp connect result keys', { keys: Object.keys(result), result: JSON.stringify(result).substring(0, 500) });
|
|
115
|
+
|
|
116
|
+
const newAccountId = (result.account_id || '') as string;
|
|
117
|
+
|
|
118
|
+
if (newAccountId) {
|
|
119
|
+
await Tenant.findByIdAndUpdate(request.user.tenant_id, {
|
|
120
|
+
$set: {
|
|
121
|
+
'settings.whatsapp_agent.unipile_account_id': newAccountId,
|
|
122
|
+
'settings.whatsapp_agent.unipile_account_status': 'pending',
|
|
123
|
+
}
|
|
124
|
+
});
|
|
125
|
+
|
|
126
|
+
// Update existing chats to use new account ID so they're not orphaned
|
|
127
|
+
const chatsToMigrate = await WhatsAppChat.find({
|
|
128
|
+
tenant_id: request.user.tenant_id,
|
|
129
|
+
unipile_account_id: { $ne: newAccountId },
|
|
130
|
+
});
|
|
131
|
+
|
|
132
|
+
if (chatsToMigrate.length > 0) {
|
|
133
|
+
const isBaileys = provider === 'baileys';
|
|
134
|
+
let migrated = 0;
|
|
135
|
+
for (const chat of chatsToMigrate) {
|
|
136
|
+
const updates: Record<string, string> = {
|
|
137
|
+
unipile_account_id: newAccountId,
|
|
138
|
+
};
|
|
139
|
+
|
|
140
|
+
if (isBaileys && chat.unipile_chat_id) {
|
|
141
|
+
const colonIdx = chat.unipile_chat_id.indexOf(':');
|
|
142
|
+
if (colonIdx !== -1 && chat.unipile_chat_id.includes('@')) {
|
|
143
|
+
// Existing composite ID — re-prefix
|
|
144
|
+
const jid = chat.unipile_chat_id.slice(colonIdx + 1);
|
|
145
|
+
updates.unipile_chat_id = `${newAccountId}:${jid}`;
|
|
146
|
+
} else if (chat.unipile_chat_id.includes('@')) {
|
|
147
|
+
// Plain JID from Unipile — add composite prefix for Baileys
|
|
148
|
+
updates.unipile_chat_id = `${newAccountId}:${chat.unipile_chat_id}`;
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
await WhatsAppChat.updateOne({ _id: chat._id }, { $set: updates });
|
|
153
|
+
migrated++;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
logger.info('Migrated chats to new account ID', {
|
|
157
|
+
from: existingAccountId ?? '(none)',
|
|
158
|
+
to: newAccountId,
|
|
159
|
+
provider,
|
|
160
|
+
count: migrated,
|
|
161
|
+
});
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
// Forward the full response — Unipile may return checkpoint, qr_code, object, etc.
|
|
166
|
+
return result;
|
|
167
|
+
});
|
|
168
|
+
|
|
169
|
+
// GET /whatsapp/connection-status — Check connection status
|
|
170
|
+
fastify.get('/connection-status', {
|
|
171
|
+
preHandler: [requireRole('admin', 'manager', 'viewer')],
|
|
172
|
+
}, async (request) => {
|
|
173
|
+
const tenant = await Tenant.findById(request.user.tenant_id);
|
|
174
|
+
const provider = unipileService.getProviderForTenant(tenant);
|
|
175
|
+
const accountId = tenant?.settings?.whatsapp_agent?.unipile_account_id;
|
|
176
|
+
|
|
177
|
+
// Helper to extract google calendar fields (never exposes encrypted_refresh_token)
|
|
178
|
+
const gcalFields = (t: typeof tenant) => {
|
|
179
|
+
const gc = t?.settings?.whatsapp_agent?.google_calendar;
|
|
180
|
+
return {
|
|
181
|
+
google_calendar_connected: gc?.connected ?? false,
|
|
182
|
+
google_calendar_email: gc?.google_email ?? null,
|
|
183
|
+
google_calendar_calendar_id: gc?.calendar_id ?? null,
|
|
184
|
+
google_calendar_calendar_name: gc?.calendar_name ?? null,
|
|
185
|
+
google_calendar_appointment_duration_minutes: gc?.appointment_duration_minutes ?? 30,
|
|
186
|
+
google_calendar_working_hours: gc?.working_hours ?? [],
|
|
187
|
+
google_calendar_blocked_dates: gc?.blocked_dates ?? [],
|
|
188
|
+
google_calendar_timezone: gc?.timezone ?? 'Europe/Istanbul',
|
|
189
|
+
};
|
|
190
|
+
};
|
|
191
|
+
|
|
192
|
+
if (!accountId) {
|
|
193
|
+
return {
|
|
194
|
+
connected: false,
|
|
195
|
+
status: 'not_configured',
|
|
196
|
+
bridge_provider: provider,
|
|
197
|
+
ai_shift_enabled: tenant?.settings?.whatsapp_agent?.ai_shift_enabled ?? false,
|
|
198
|
+
ai_shift_schedule: tenant?.settings?.whatsapp_agent?.ai_shift_schedule ?? [],
|
|
199
|
+
grace_period_seconds: tenant?.settings?.whatsapp_agent?.grace_period_seconds ?? 180,
|
|
200
|
+
fixed_first_message_enabled: tenant?.settings?.whatsapp_agent?.fixed_first_message_enabled ?? false,
|
|
201
|
+
fixed_first_message: tenant?.settings?.whatsapp_agent?.fixed_first_message ?? '',
|
|
202
|
+
operator_workflow_enabled: tenant?.settings?.whatsapp_agent?.operator_workflow_enabled ?? false,
|
|
203
|
+
operator_phone: tenant?.settings?.whatsapp_agent?.operator_phone ?? null,
|
|
204
|
+
operator_ref_prefix: tenant?.settings?.whatsapp_agent?.operator_ref_prefix ?? 'R',
|
|
205
|
+
operator_request_timeout_hours: tenant?.settings?.whatsapp_agent?.operator_request_timeout_hours ?? 24,
|
|
206
|
+
operator_example_photo_enabled: tenant?.settings?.whatsapp_agent?.operator_example_photo_enabled ?? false,
|
|
207
|
+
has_example_photo: !!tenant?.settings?.whatsapp_agent?.operator_example_photo_base64,
|
|
208
|
+
operator_example_photo_base64: tenant?.settings?.whatsapp_agent?.operator_example_photo_base64 ?? null,
|
|
209
|
+
operator_example_photo_caption: tenant?.settings?.whatsapp_agent?.operator_example_photo_caption ?? '',
|
|
210
|
+
outbound_call_enabled: tenant?.settings?.whatsapp_agent?.outbound_call_enabled ?? false,
|
|
211
|
+
outbound_call_phone_number_id: tenant?.settings?.whatsapp_agent?.outbound_call_phone_number_id ?? null,
|
|
212
|
+
outbound_call_agent_id: tenant?.settings?.whatsapp_agent?.outbound_call_agent_id?.toString() ?? null,
|
|
213
|
+
sms_notification_enabled: tenant?.settings?.whatsapp_agent?.sms_notification_enabled ?? false,
|
|
214
|
+
sms_notification_phones: tenant?.settings?.whatsapp_agent?.sms_notification_phones ?? [],
|
|
215
|
+
...gcalFields(tenant),
|
|
216
|
+
};
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
try {
|
|
220
|
+
const account = await unipileService.getAccountStatus(provider, accountId);
|
|
221
|
+
|
|
222
|
+
// Unipile nests status in sources[0].status, not top-level
|
|
223
|
+
const sources = account.sources as Array<{ id: string; status: string }> | undefined;
|
|
224
|
+
const sourceStatus = sources?.[0]?.status || '';
|
|
225
|
+
const topStatus = (account.status as string) || '';
|
|
226
|
+
const statusStr = (sourceStatus || topStatus).toLowerCase();
|
|
227
|
+
|
|
228
|
+
const isConnected = statusStr === 'ok' || statusStr === 'connected';
|
|
229
|
+
const phone = (account.connection_params as any)?.im?.phone_number || null;
|
|
230
|
+
|
|
231
|
+
await Tenant.findByIdAndUpdate(request.user.tenant_id, {
|
|
232
|
+
$set: {
|
|
233
|
+
'settings.whatsapp_agent.unipile_account_status': sourceStatus || topStatus,
|
|
234
|
+
...(isConnected ? { 'settings.whatsapp_agent.connected_at': new Date() } : {}),
|
|
235
|
+
...(phone ? { 'settings.whatsapp_agent.connected_phone': phone } : {}),
|
|
236
|
+
}
|
|
237
|
+
});
|
|
238
|
+
|
|
239
|
+
// Resolve agent info
|
|
240
|
+
const agentObjId = tenant?.settings?.whatsapp_agent?.agent_id;
|
|
241
|
+
const agentDoc = agentObjId ? await Agent.findById(agentObjId).lean() : null;
|
|
242
|
+
|
|
243
|
+
return {
|
|
244
|
+
connected: isConnected,
|
|
245
|
+
status: sourceStatus || topStatus,
|
|
246
|
+
account_id: accountId,
|
|
247
|
+
phone,
|
|
248
|
+
bridge_provider: provider,
|
|
249
|
+
agent_id: agentObjId?.toString() || null,
|
|
250
|
+
agent_name: agentDoc ? `${agentDoc.agent_template} (${agentDoc.phone_number})` : null,
|
|
251
|
+
agent_active: agentDoc?.is_active ?? false,
|
|
252
|
+
grace_period_seconds: tenant?.settings?.whatsapp_agent?.grace_period_seconds ?? 180,
|
|
253
|
+
ai_shift_enabled: tenant?.settings?.whatsapp_agent?.ai_shift_enabled ?? false,
|
|
254
|
+
ai_shift_schedule: tenant?.settings?.whatsapp_agent?.ai_shift_schedule ?? [],
|
|
255
|
+
fixed_first_message_enabled: tenant?.settings?.whatsapp_agent?.fixed_first_message_enabled ?? false,
|
|
256
|
+
fixed_first_message: tenant?.settings?.whatsapp_agent?.fixed_first_message ?? '',
|
|
257
|
+
operator_workflow_enabled: tenant?.settings?.whatsapp_agent?.operator_workflow_enabled ?? false,
|
|
258
|
+
operator_phone: tenant?.settings?.whatsapp_agent?.operator_phone ?? null,
|
|
259
|
+
operator_ref_prefix: tenant?.settings?.whatsapp_agent?.operator_ref_prefix ?? 'R',
|
|
260
|
+
operator_request_timeout_hours: tenant?.settings?.whatsapp_agent?.operator_request_timeout_hours ?? 24,
|
|
261
|
+
operator_example_photo_enabled: tenant?.settings?.whatsapp_agent?.operator_example_photo_enabled ?? false,
|
|
262
|
+
has_example_photo: !!tenant?.settings?.whatsapp_agent?.operator_example_photo_base64,
|
|
263
|
+
operator_example_photo_base64: tenant?.settings?.whatsapp_agent?.operator_example_photo_base64 ?? null,
|
|
264
|
+
operator_example_photo_caption: tenant?.settings?.whatsapp_agent?.operator_example_photo_caption ?? '',
|
|
265
|
+
outbound_call_enabled: tenant?.settings?.whatsapp_agent?.outbound_call_enabled ?? false,
|
|
266
|
+
outbound_call_phone_number_id: tenant?.settings?.whatsapp_agent?.outbound_call_phone_number_id ?? null,
|
|
267
|
+
outbound_call_agent_id: tenant?.settings?.whatsapp_agent?.outbound_call_agent_id?.toString() ?? null,
|
|
268
|
+
sms_notification_enabled: tenant?.settings?.whatsapp_agent?.sms_notification_enabled ?? false,
|
|
269
|
+
sms_notification_phones: tenant?.settings?.whatsapp_agent?.sms_notification_phones ?? [],
|
|
270
|
+
...gcalFields(tenant),
|
|
271
|
+
};
|
|
272
|
+
} catch (err) {
|
|
273
|
+
return {
|
|
274
|
+
connected: false,
|
|
275
|
+
status: 'error',
|
|
276
|
+
error: (err as Error).message,
|
|
277
|
+
bridge_provider: provider,
|
|
278
|
+
ai_shift_enabled: tenant?.settings?.whatsapp_agent?.ai_shift_enabled ?? false,
|
|
279
|
+
ai_shift_schedule: tenant?.settings?.whatsapp_agent?.ai_shift_schedule ?? [],
|
|
280
|
+
grace_period_seconds: tenant?.settings?.whatsapp_agent?.grace_period_seconds ?? 180,
|
|
281
|
+
fixed_first_message_enabled: tenant?.settings?.whatsapp_agent?.fixed_first_message_enabled ?? false,
|
|
282
|
+
fixed_first_message: tenant?.settings?.whatsapp_agent?.fixed_first_message ?? '',
|
|
283
|
+
operator_workflow_enabled: tenant?.settings?.whatsapp_agent?.operator_workflow_enabled ?? false,
|
|
284
|
+
operator_phone: tenant?.settings?.whatsapp_agent?.operator_phone ?? null,
|
|
285
|
+
operator_ref_prefix: tenant?.settings?.whatsapp_agent?.operator_ref_prefix ?? 'R',
|
|
286
|
+
operator_request_timeout_hours: tenant?.settings?.whatsapp_agent?.operator_request_timeout_hours ?? 24,
|
|
287
|
+
operator_example_photo_enabled: tenant?.settings?.whatsapp_agent?.operator_example_photo_enabled ?? false,
|
|
288
|
+
has_example_photo: !!tenant?.settings?.whatsapp_agent?.operator_example_photo_base64,
|
|
289
|
+
operator_example_photo_base64: tenant?.settings?.whatsapp_agent?.operator_example_photo_base64 ?? null,
|
|
290
|
+
operator_example_photo_caption: tenant?.settings?.whatsapp_agent?.operator_example_photo_caption ?? '',
|
|
291
|
+
outbound_call_enabled: tenant?.settings?.whatsapp_agent?.outbound_call_enabled ?? false,
|
|
292
|
+
outbound_call_phone_number_id: tenant?.settings?.whatsapp_agent?.outbound_call_phone_number_id ?? null,
|
|
293
|
+
outbound_call_agent_id: tenant?.settings?.whatsapp_agent?.outbound_call_agent_id?.toString() ?? null,
|
|
294
|
+
sms_notification_enabled: tenant?.settings?.whatsapp_agent?.sms_notification_enabled ?? false,
|
|
295
|
+
sms_notification_phones: tenant?.settings?.whatsapp_agent?.sms_notification_phones ?? [],
|
|
296
|
+
...gcalFields(tenant),
|
|
297
|
+
};
|
|
298
|
+
}
|
|
299
|
+
});
|
|
300
|
+
|
|
301
|
+
// POST /whatsapp/disconnect — Disconnect WhatsApp
|
|
302
|
+
fastify.post('/disconnect', {
|
|
303
|
+
preHandler: [requireRole('admin')],
|
|
304
|
+
}, async (request) => {
|
|
305
|
+
const tenant = await Tenant.findById(request.user.tenant_id);
|
|
306
|
+
const provider = unipileService.getProviderForTenant(tenant);
|
|
307
|
+
const accountId = tenant?.settings?.whatsapp_agent?.unipile_account_id;
|
|
308
|
+
|
|
309
|
+
if (accountId) {
|
|
310
|
+
try {
|
|
311
|
+
await unipileService.disconnectAccount(provider, accountId);
|
|
312
|
+
} catch (err) {
|
|
313
|
+
logger.warn('Failed to disconnect account', { provider, error: (err as Error).message });
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
await Tenant.findByIdAndUpdate(request.user.tenant_id, {
|
|
318
|
+
$set: {
|
|
319
|
+
'settings.whatsapp_agent.unipile_account_id': null,
|
|
320
|
+
'settings.whatsapp_agent.unipile_account_status': null,
|
|
321
|
+
'settings.whatsapp_agent.connected_at': null,
|
|
322
|
+
'settings.whatsapp_agent.connected_phone': null,
|
|
323
|
+
}
|
|
324
|
+
});
|
|
325
|
+
|
|
326
|
+
return { disconnected: true };
|
|
327
|
+
});
|
|
328
|
+
|
|
329
|
+
// PUT /whatsapp/config — Update agent and/or grace_period for WhatsApp AI
|
|
330
|
+
fastify.put('/config', {
|
|
331
|
+
preHandler: [requireRole('admin')],
|
|
332
|
+
}, async (request) => {
|
|
333
|
+
const {
|
|
334
|
+
agent_id, profile_agent_id, grace_period_seconds,
|
|
335
|
+
ai_shift_enabled, ai_shift_schedule,
|
|
336
|
+
fixed_first_message_enabled, fixed_first_message,
|
|
337
|
+
operator_workflow_enabled, operator_phone,
|
|
338
|
+
operator_ref_prefix, operator_request_timeout_hours,
|
|
339
|
+
operator_example_photo_enabled, operator_example_photo_base64, operator_example_photo_caption,
|
|
340
|
+
outbound_call_enabled, outbound_call_phone_number_id,
|
|
341
|
+
outbound_call_agent_id,
|
|
342
|
+
sms_notification_enabled,
|
|
343
|
+
sms_notification_phones,
|
|
344
|
+
google_calendar_appointment_duration_minutes,
|
|
345
|
+
google_calendar_working_hours,
|
|
346
|
+
google_calendar_blocked_dates,
|
|
347
|
+
google_calendar_timezone,
|
|
348
|
+
} = request.body as {
|
|
349
|
+
agent_id?: string | null;
|
|
350
|
+
profile_agent_id?: string | null;
|
|
351
|
+
grace_period_seconds?: number;
|
|
352
|
+
ai_shift_enabled?: boolean;
|
|
353
|
+
ai_shift_schedule?: Array<{ day: number; start: string; end: string }>;
|
|
354
|
+
fixed_first_message_enabled?: boolean;
|
|
355
|
+
fixed_first_message?: string;
|
|
356
|
+
operator_workflow_enabled?: boolean;
|
|
357
|
+
operator_phone?: string | null;
|
|
358
|
+
operator_ref_prefix?: string;
|
|
359
|
+
operator_request_timeout_hours?: number;
|
|
360
|
+
operator_example_photo_enabled?: boolean;
|
|
361
|
+
operator_example_photo_base64?: string | null;
|
|
362
|
+
operator_example_photo_caption?: string;
|
|
363
|
+
outbound_call_enabled?: boolean;
|
|
364
|
+
outbound_call_phone_number_id?: string | null;
|
|
365
|
+
outbound_call_agent_id?: string | null;
|
|
366
|
+
sms_notification_enabled?: boolean;
|
|
367
|
+
sms_notification_phones?: string[];
|
|
368
|
+
google_calendar_appointment_duration_minutes?: number;
|
|
369
|
+
google_calendar_working_hours?: Array<{ day: number; start: string; end: string }>;
|
|
370
|
+
google_calendar_blocked_dates?: Array<{ date: string; reason?: string }>;
|
|
371
|
+
google_calendar_timezone?: string;
|
|
372
|
+
};
|
|
373
|
+
|
|
374
|
+
// Feature-gate checks
|
|
375
|
+
const tenant = await Tenant.findById(request.user.tenant_id).lean();
|
|
376
|
+
const enabledFeatures = tenant?.enabled_features ?? [];
|
|
377
|
+
|
|
378
|
+
const operatorFields = operator_workflow_enabled !== undefined || operator_phone !== undefined
|
|
379
|
+
|| operator_ref_prefix !== undefined || operator_request_timeout_hours !== undefined
|
|
380
|
+
|| operator_example_photo_enabled !== undefined || operator_example_photo_base64 !== undefined
|
|
381
|
+
|| operator_example_photo_caption !== undefined;
|
|
382
|
+
if (operatorFields && !enabledFeatures.includes('operator_workflow')) {
|
|
383
|
+
throw { statusCode: 403, message: 'Operator workflow feature is not enabled for this tenant' };
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
const smsFields = sms_notification_enabled !== undefined || sms_notification_phones !== undefined;
|
|
387
|
+
if (smsFields && !enabledFeatures.includes('sms_notifications')) {
|
|
388
|
+
throw { statusCode: 403, message: 'SMS notifications feature is not enabled for this tenant' };
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
const calendarFields = google_calendar_appointment_duration_minutes !== undefined
|
|
392
|
+
|| google_calendar_working_hours !== undefined || google_calendar_blocked_dates !== undefined
|
|
393
|
+
|| google_calendar_timezone !== undefined;
|
|
394
|
+
if (calendarFields && !enabledFeatures.includes('google_calendar')) {
|
|
395
|
+
throw { statusCode: 403, message: 'Google Calendar feature is not enabled for this tenant' };
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
const update: Record<string, unknown> = {};
|
|
399
|
+
if (agent_id !== undefined) {
|
|
400
|
+
if (agent_id) {
|
|
401
|
+
// Validate that the agent exists and belongs to this tenant
|
|
402
|
+
const agent = await Agent.findOne({
|
|
403
|
+
_id: agent_id,
|
|
404
|
+
tenant_id: request.user.tenant_id,
|
|
405
|
+
});
|
|
406
|
+
if (!agent) {
|
|
407
|
+
throw { statusCode: 400, message: 'Agent not found or does not belong to this tenant' };
|
|
408
|
+
}
|
|
409
|
+
update['settings.whatsapp_agent.agent_id'] = new mongoose.Types.ObjectId(agent_id);
|
|
410
|
+
} else {
|
|
411
|
+
update['settings.whatsapp_agent.agent_id'] = null;
|
|
412
|
+
}
|
|
413
|
+
}
|
|
414
|
+
if (profile_agent_id !== undefined) {
|
|
415
|
+
if (profile_agent_id) {
|
|
416
|
+
const agent = await Agent.findOne({
|
|
417
|
+
_id: profile_agent_id,
|
|
418
|
+
tenant_id: request.user.tenant_id,
|
|
419
|
+
});
|
|
420
|
+
if (!agent) {
|
|
421
|
+
throw { statusCode: 400, message: 'Profile agent not found or does not belong to this tenant' };
|
|
422
|
+
}
|
|
423
|
+
update['settings.whatsapp_agent.profile_agent_id'] = new mongoose.Types.ObjectId(profile_agent_id);
|
|
424
|
+
} else {
|
|
425
|
+
update['settings.whatsapp_agent.profile_agent_id'] = null;
|
|
426
|
+
}
|
|
427
|
+
}
|
|
428
|
+
if (grace_period_seconds !== undefined) {
|
|
429
|
+
update['settings.whatsapp_agent.grace_period_seconds'] = Math.max(5, Math.min(1800, grace_period_seconds));
|
|
430
|
+
}
|
|
431
|
+
if (ai_shift_enabled !== undefined) {
|
|
432
|
+
update['settings.whatsapp_agent.ai_shift_enabled'] = !!ai_shift_enabled;
|
|
433
|
+
}
|
|
434
|
+
if (ai_shift_schedule !== undefined) {
|
|
435
|
+
if (!Array.isArray(ai_shift_schedule)) {
|
|
436
|
+
throw { statusCode: 400, message: 'ai_shift_schedule must be an array' };
|
|
437
|
+
}
|
|
438
|
+
for (const entry of ai_shift_schedule) {
|
|
439
|
+
if (typeof entry.day !== 'number' || entry.day < 0 || entry.day > 6) {
|
|
440
|
+
throw { statusCode: 400, message: 'Each schedule entry day must be 0-6' };
|
|
441
|
+
}
|
|
442
|
+
if (!/^\d{2}:\d{2}$/.test(entry.start) || !/^\d{2}:\d{2}$/.test(entry.end)) {
|
|
443
|
+
throw { statusCode: 400, message: 'Each schedule entry start/end must be in HH:MM format' };
|
|
444
|
+
}
|
|
445
|
+
}
|
|
446
|
+
update['settings.whatsapp_agent.ai_shift_schedule'] = ai_shift_schedule;
|
|
447
|
+
}
|
|
448
|
+
if (fixed_first_message_enabled !== undefined) {
|
|
449
|
+
update['settings.whatsapp_agent.fixed_first_message_enabled'] = !!fixed_first_message_enabled;
|
|
450
|
+
}
|
|
451
|
+
if (fixed_first_message !== undefined) {
|
|
452
|
+
if (typeof fixed_first_message !== 'string' || fixed_first_message.length > 1000) {
|
|
453
|
+
throw { statusCode: 400, message: 'fixed_first_message must be a string (max 1000 chars)' };
|
|
454
|
+
}
|
|
455
|
+
update['settings.whatsapp_agent.fixed_first_message'] = fixed_first_message;
|
|
456
|
+
}
|
|
457
|
+
if (operator_workflow_enabled !== undefined) {
|
|
458
|
+
update['settings.whatsapp_agent.operator_workflow_enabled'] = !!operator_workflow_enabled;
|
|
459
|
+
}
|
|
460
|
+
if (operator_phone !== undefined) {
|
|
461
|
+
update['settings.whatsapp_agent.operator_phone'] = operator_phone || null;
|
|
462
|
+
}
|
|
463
|
+
if (operator_ref_prefix !== undefined) {
|
|
464
|
+
if (typeof operator_ref_prefix !== 'string' || !/^[A-Z]$/.test(operator_ref_prefix)) {
|
|
465
|
+
throw { statusCode: 400, message: 'operator_ref_prefix must be a single uppercase letter' };
|
|
466
|
+
}
|
|
467
|
+
update['settings.whatsapp_agent.operator_ref_prefix'] = operator_ref_prefix;
|
|
468
|
+
}
|
|
469
|
+
if (operator_request_timeout_hours !== undefined) {
|
|
470
|
+
update['settings.whatsapp_agent.operator_request_timeout_hours'] = Math.max(1, Math.min(168, operator_request_timeout_hours));
|
|
471
|
+
}
|
|
472
|
+
if (operator_example_photo_enabled !== undefined) {
|
|
473
|
+
update['settings.whatsapp_agent.operator_example_photo_enabled'] = !!operator_example_photo_enabled;
|
|
474
|
+
}
|
|
475
|
+
if (operator_example_photo_base64 !== undefined) {
|
|
476
|
+
if (operator_example_photo_base64 && !operator_example_photo_base64.startsWith('data:image/')) {
|
|
477
|
+
throw { statusCode: 400, message: 'operator_example_photo_base64 must be a data:image/* URL' };
|
|
478
|
+
}
|
|
479
|
+
if (operator_example_photo_base64 && operator_example_photo_base64.length > 2_000_000) {
|
|
480
|
+
throw { statusCode: 400, message: 'Example photo too large (max ~1.5MB)' };
|
|
481
|
+
}
|
|
482
|
+
update['settings.whatsapp_agent.operator_example_photo_base64'] = operator_example_photo_base64 || null;
|
|
483
|
+
}
|
|
484
|
+
if (operator_example_photo_caption !== undefined) {
|
|
485
|
+
update['settings.whatsapp_agent.operator_example_photo_caption'] = (operator_example_photo_caption || '').substring(0, 500);
|
|
486
|
+
}
|
|
487
|
+
if (outbound_call_enabled !== undefined) {
|
|
488
|
+
update['settings.whatsapp_agent.outbound_call_enabled'] = !!outbound_call_enabled;
|
|
489
|
+
}
|
|
490
|
+
if (outbound_call_phone_number_id !== undefined) {
|
|
491
|
+
update['settings.whatsapp_agent.outbound_call_phone_number_id'] = outbound_call_phone_number_id || null;
|
|
492
|
+
}
|
|
493
|
+
if (outbound_call_agent_id !== undefined) {
|
|
494
|
+
if (outbound_call_agent_id) {
|
|
495
|
+
const agent = await Agent.findOne({
|
|
496
|
+
_id: outbound_call_agent_id,
|
|
497
|
+
tenant_id: request.user.tenant_id,
|
|
498
|
+
});
|
|
499
|
+
if (!agent) {
|
|
500
|
+
throw { statusCode: 400, message: 'Outbound call agent not found or does not belong to this tenant' };
|
|
501
|
+
}
|
|
502
|
+
update['settings.whatsapp_agent.outbound_call_agent_id'] = new mongoose.Types.ObjectId(outbound_call_agent_id);
|
|
503
|
+
} else {
|
|
504
|
+
update['settings.whatsapp_agent.outbound_call_agent_id'] = null;
|
|
505
|
+
}
|
|
506
|
+
}
|
|
507
|
+
|
|
508
|
+
// SMS Notifications
|
|
509
|
+
if (sms_notification_enabled !== undefined) {
|
|
510
|
+
update['settings.whatsapp_agent.sms_notification_enabled'] = !!sms_notification_enabled;
|
|
511
|
+
}
|
|
512
|
+
if (sms_notification_phones !== undefined) {
|
|
513
|
+
if (!Array.isArray(sms_notification_phones)) {
|
|
514
|
+
throw { statusCode: 400, message: 'sms_notification_phones must be an array' };
|
|
515
|
+
}
|
|
516
|
+
// Clean phone numbers
|
|
517
|
+
update['settings.whatsapp_agent.sms_notification_phones'] = sms_notification_phones
|
|
518
|
+
.map(p => p.replace(/[^0-9]/g, ''))
|
|
519
|
+
.filter(p => p.length >= 10);
|
|
520
|
+
}
|
|
521
|
+
|
|
522
|
+
// Google Calendar settings
|
|
523
|
+
if (google_calendar_appointment_duration_minutes !== undefined) {
|
|
524
|
+
const allowed = [10, 15, 20, 30, 45, 60];
|
|
525
|
+
if (!allowed.includes(google_calendar_appointment_duration_minutes)) {
|
|
526
|
+
throw { statusCode: 400, message: 'appointment_duration_minutes must be one of: 10, 15, 20, 30, 45, 60' };
|
|
527
|
+
}
|
|
528
|
+
update['settings.whatsapp_agent.google_calendar.appointment_duration_minutes'] = google_calendar_appointment_duration_minutes;
|
|
529
|
+
}
|
|
530
|
+
if (google_calendar_working_hours !== undefined) {
|
|
531
|
+
if (!Array.isArray(google_calendar_working_hours)) {
|
|
532
|
+
throw { statusCode: 400, message: 'google_calendar_working_hours must be an array' };
|
|
533
|
+
}
|
|
534
|
+
for (const entry of google_calendar_working_hours) {
|
|
535
|
+
if (typeof entry.day !== 'number' || entry.day < 0 || entry.day > 6) {
|
|
536
|
+
throw { statusCode: 400, message: 'Each working_hours entry day must be 0-6' };
|
|
537
|
+
}
|
|
538
|
+
if (!/^\d{2}:\d{2}$/.test(entry.start) || !/^\d{2}:\d{2}$/.test(entry.end)) {
|
|
539
|
+
throw { statusCode: 400, message: 'Each working_hours entry start/end must be HH:MM' };
|
|
540
|
+
}
|
|
541
|
+
}
|
|
542
|
+
update['settings.whatsapp_agent.google_calendar.working_hours'] = google_calendar_working_hours;
|
|
543
|
+
}
|
|
544
|
+
if (google_calendar_blocked_dates !== undefined) {
|
|
545
|
+
if (!Array.isArray(google_calendar_blocked_dates)) {
|
|
546
|
+
throw { statusCode: 400, message: 'google_calendar_blocked_dates must be an array' };
|
|
547
|
+
}
|
|
548
|
+
for (const entry of google_calendar_blocked_dates) {
|
|
549
|
+
if (!/^\d{4}-\d{2}-\d{2}$/.test(entry.date)) {
|
|
550
|
+
throw { statusCode: 400, message: 'Each blocked_dates entry date must be YYYY-MM-DD' };
|
|
551
|
+
}
|
|
552
|
+
}
|
|
553
|
+
update['settings.whatsapp_agent.google_calendar.blocked_dates'] = google_calendar_blocked_dates.map(e => ({
|
|
554
|
+
date: e.date,
|
|
555
|
+
reason: e.reason || '',
|
|
556
|
+
}));
|
|
557
|
+
}
|
|
558
|
+
if (google_calendar_timezone !== undefined) {
|
|
559
|
+
update['settings.whatsapp_agent.google_calendar.timezone'] = google_calendar_timezone;
|
|
560
|
+
}
|
|
561
|
+
|
|
562
|
+
await Tenant.findByIdAndUpdate(request.user.tenant_id, { $set: update });
|
|
563
|
+
return { updated: true };
|
|
564
|
+
});
|
|
565
|
+
|
|
566
|
+
// ─── Google Calendar ──────────────────────────────────────
|
|
567
|
+
|
|
568
|
+
// GET /whatsapp/google-calendar/auth-url — Get OAuth consent URL
|
|
569
|
+
fastify.get('/google-calendar/auth-url', {
|
|
570
|
+
preHandler: [requireRole('admin'), requireFeature('google_calendar')],
|
|
571
|
+
}, async (request) => {
|
|
572
|
+
const url = googleCalendarService.getAuthUrl(request.user.tenant_id);
|
|
573
|
+
return { url };
|
|
574
|
+
});
|
|
575
|
+
|
|
576
|
+
// POST /whatsapp/google-calendar/disconnect — Revoke and remove Google Calendar
|
|
577
|
+
fastify.post('/google-calendar/disconnect', {
|
|
578
|
+
preHandler: [requireRole('admin'), requireFeature('google_calendar')],
|
|
579
|
+
}, async (request) => {
|
|
580
|
+
await googleCalendarService.disconnect(request.user.tenant_id);
|
|
581
|
+
return { disconnected: true };
|
|
582
|
+
});
|
|
583
|
+
|
|
584
|
+
// GET /whatsapp/google-calendar/calendars — List available calendars
|
|
585
|
+
fastify.get('/google-calendar/calendars', {
|
|
586
|
+
preHandler: [requireRole('admin'), requireFeature('google_calendar')],
|
|
587
|
+
}, async (request) => {
|
|
588
|
+
const calendars = await googleCalendarService.listCalendars(request.user.tenant_id);
|
|
589
|
+
return { calendars };
|
|
590
|
+
});
|
|
591
|
+
|
|
592
|
+
// PUT /whatsapp/google-calendar/calendar — Select calendar to use
|
|
593
|
+
fastify.put('/google-calendar/calendar', {
|
|
594
|
+
preHandler: [requireRole('admin'), requireFeature('google_calendar')],
|
|
595
|
+
}, async (request) => {
|
|
596
|
+
const { calendar_id } = request.body as { calendar_id: string };
|
|
597
|
+
if (!calendar_id) {
|
|
598
|
+
throw { statusCode: 400, message: 'calendar_id is required' };
|
|
599
|
+
}
|
|
600
|
+
await googleCalendarService.selectCalendar(request.user.tenant_id, calendar_id);
|
|
601
|
+
return { updated: true };
|
|
602
|
+
});
|
|
603
|
+
|
|
604
|
+
// ─── Appointments ────────────────────────────────────────
|
|
605
|
+
|
|
606
|
+
// GET /whatsapp/appointments — Paginated appointment list
|
|
607
|
+
fastify.get<{
|
|
608
|
+
Querystring: { page?: string; limit?: string; status?: string; from?: string; to?: string };
|
|
609
|
+
}>('/appointments', {
|
|
610
|
+
preHandler: [requireRole('admin', 'manager', 'viewer')],
|
|
611
|
+
}, async (request) => {
|
|
612
|
+
const page = Math.max(1, parseInt(request.query.page || '1', 10));
|
|
613
|
+
const limit = Math.min(parseInt(request.query.limit || '50', 10), 200);
|
|
614
|
+
const skip = (page - 1) * limit;
|
|
615
|
+
|
|
616
|
+
const filter: Record<string, unknown> = { tenant_id: request.user.tenant_id };
|
|
617
|
+
if (request.query.status === 'scheduled' || request.query.status === 'cancelled') {
|
|
618
|
+
filter.status = request.query.status;
|
|
619
|
+
}
|
|
620
|
+
if (request.query.from || request.query.to) {
|
|
621
|
+
filter.start_time = {};
|
|
622
|
+
if (request.query.from) (filter.start_time as Record<string, unknown>).$gte = new Date(request.query.from);
|
|
623
|
+
if (request.query.to) (filter.start_time as Record<string, unknown>).$lte = new Date(request.query.to);
|
|
624
|
+
}
|
|
625
|
+
|
|
626
|
+
const [appointments, total] = await Promise.all([
|
|
627
|
+
Appointment.find(filter).sort({ start_time: -1 }).skip(skip).limit(limit).lean(),
|
|
628
|
+
Appointment.countDocuments(filter),
|
|
629
|
+
]);
|
|
630
|
+
|
|
631
|
+
return { appointments, total, page, totalPages: Math.ceil(total / limit) };
|
|
632
|
+
});
|
|
633
|
+
|
|
634
|
+
// GET /whatsapp/appointments/:id — Single appointment detail
|
|
635
|
+
fastify.get<{
|
|
636
|
+
Params: { id: string };
|
|
637
|
+
}>('/appointments/:id', {
|
|
638
|
+
preHandler: [requireRole('admin', 'manager', 'viewer')],
|
|
639
|
+
}, async (request, reply) => {
|
|
640
|
+
const appointment = await Appointment.findOne({
|
|
641
|
+
_id: request.params.id,
|
|
642
|
+
tenant_id: request.user.tenant_id,
|
|
643
|
+
}).lean();
|
|
644
|
+
if (!appointment) {
|
|
645
|
+
return reply.status(404).send({ error: 'Appointment not found' });
|
|
646
|
+
}
|
|
647
|
+
return appointment;
|
|
648
|
+
});
|
|
649
|
+
|
|
650
|
+
// GET /whatsapp/appointments/stats — Analytics summary
|
|
651
|
+
fastify.get<{
|
|
652
|
+
Querystring: { from?: string; to?: string };
|
|
653
|
+
}>('/appointments/stats', {
|
|
654
|
+
preHandler: [requireRole('admin', 'manager', 'viewer')],
|
|
655
|
+
}, async (request) => {
|
|
656
|
+
const tenantId = new mongoose.Types.ObjectId(request.user.tenant_id);
|
|
657
|
+
const now = new Date();
|
|
658
|
+
const from = request.query.from ? new Date(request.query.from) : new Date(now.getTime() - 30 * 24 * 60 * 60 * 1000);
|
|
659
|
+
const to = request.query.to ? new Date(request.query.to) : now;
|
|
660
|
+
|
|
661
|
+
const [stats] = await Appointment.aggregate([
|
|
662
|
+
{ $match: { tenant_id: tenantId, start_time: { $gte: from, $lte: to } } },
|
|
663
|
+
{ $facet: {
|
|
664
|
+
totals: [
|
|
665
|
+
{ $group: {
|
|
666
|
+
_id: null,
|
|
667
|
+
total_scheduled: { $sum: { $cond: [{ $eq: ['$status', 'scheduled'] }, 1, 0] } },
|
|
668
|
+
total_cancelled: { $sum: { $cond: [{ $eq: ['$status', 'cancelled'] }, 1, 0] } },
|
|
669
|
+
}},
|
|
670
|
+
],
|
|
671
|
+
by_day_of_week: [
|
|
672
|
+
{ $match: { status: 'scheduled' } },
|
|
673
|
+
{ $group: { _id: { $dayOfWeek: '$start_time' }, count: { $sum: 1 } } },
|
|
674
|
+
{ $project: { _id: 0, day: '$_id', count: 1 } },
|
|
675
|
+
{ $sort: { day: 1 } },
|
|
676
|
+
],
|
|
677
|
+
by_hour: [
|
|
678
|
+
{ $match: { status: 'scheduled' } },
|
|
679
|
+
{ $group: { _id: { $hour: '$start_time' }, count: { $sum: 1 } } },
|
|
680
|
+
{ $project: { _id: 0, hour: '$_id', count: 1 } },
|
|
681
|
+
{ $sort: { hour: 1 } },
|
|
682
|
+
],
|
|
683
|
+
}},
|
|
684
|
+
]);
|
|
685
|
+
|
|
686
|
+
const totals = stats?.totals?.[0] || { total_scheduled: 0, total_cancelled: 0 };
|
|
687
|
+
const total = totals.total_scheduled + totals.total_cancelled;
|
|
688
|
+
const upcoming = await Appointment.countDocuments({
|
|
689
|
+
tenant_id: tenantId,
|
|
690
|
+
status: 'scheduled',
|
|
691
|
+
start_time: { $gte: now },
|
|
692
|
+
});
|
|
693
|
+
|
|
694
|
+
return {
|
|
695
|
+
total_scheduled: totals.total_scheduled,
|
|
696
|
+
total_cancelled: totals.total_cancelled,
|
|
697
|
+
cancellation_rate: total > 0 ? Math.round((totals.total_cancelled / total) * 10000) / 100 : 0,
|
|
698
|
+
by_day_of_week: stats?.by_day_of_week || [],
|
|
699
|
+
by_hour: stats?.by_hour || [],
|
|
700
|
+
upcoming,
|
|
701
|
+
};
|
|
702
|
+
});
|
|
703
|
+
|
|
704
|
+
// GET /whatsapp/agents — List available agents for this tenant (for agent selection dropdown)
|
|
705
|
+
fastify.get('/agents', {
|
|
706
|
+
preHandler: [requireRole('admin', 'manager')],
|
|
707
|
+
}, async (request) => {
|
|
708
|
+
const agents = await Agent.find({ tenant_id: request.user.tenant_id })
|
|
709
|
+
.select('_id phone_number agent_template is_active elevenlabs_agent_id')
|
|
710
|
+
.sort({ is_active: -1, createdAt: -1 })
|
|
711
|
+
.lean();
|
|
712
|
+
|
|
713
|
+
const tenant = await Tenant.findById(request.user.tenant_id).lean();
|
|
714
|
+
const currentAgentId = tenant?.settings?.whatsapp_agent?.agent_id?.toString() || null;
|
|
715
|
+
|
|
716
|
+
return { agents, currentAgentId };
|
|
717
|
+
});
|
|
718
|
+
|
|
719
|
+
// POST /whatsapp/register-webhook — Register webhook for this server
|
|
720
|
+
fastify.post('/register-webhook', {
|
|
721
|
+
preHandler: [requireRole('admin')],
|
|
722
|
+
}, async (request) => {
|
|
723
|
+
const { webhook_url } = request.body as { webhook_url: string };
|
|
724
|
+
|
|
725
|
+
if (!webhook_url?.trim()) {
|
|
726
|
+
throw { statusCode: 400, message: 'webhook_url is required' };
|
|
727
|
+
}
|
|
728
|
+
|
|
729
|
+
const tenant = await Tenant.findById(request.user.tenant_id);
|
|
730
|
+
const provider = unipileService.getProviderForTenant(tenant);
|
|
731
|
+
const result = await unipileService.createWebhook(provider, webhook_url.trim());
|
|
732
|
+
return { webhook_id: result.id, url: webhook_url, provider };
|
|
733
|
+
});
|
|
734
|
+
|
|
735
|
+
// ─── Blacklist ──────────────────────────────────────────────
|
|
736
|
+
|
|
737
|
+
// GET /whatsapp/blacklist — Get blacklisted numbers
|
|
738
|
+
fastify.get('/blacklist', {
|
|
739
|
+
preHandler: [requireRole('admin', 'manager')],
|
|
740
|
+
}, async (request) => {
|
|
741
|
+
const tenant = await Tenant.findById(request.user.tenant_id);
|
|
742
|
+
return { numbers: tenant?.settings?.whatsapp_agent?.blacklisted_numbers || [] };
|
|
743
|
+
});
|
|
744
|
+
|
|
745
|
+
// POST /whatsapp/blacklist — Add number to blacklist
|
|
746
|
+
fastify.post('/blacklist', {
|
|
747
|
+
preHandler: [requireRole('admin', 'manager')],
|
|
748
|
+
}, async (request, reply) => {
|
|
749
|
+
const { phone } = request.body as { phone: string };
|
|
750
|
+
const cleaned = phone?.replace(/\s/g, '');
|
|
751
|
+
if (!cleaned) return reply.status(400).send({ error: 'phone is required' });
|
|
752
|
+
|
|
753
|
+
const tenant = await Tenant.findById(request.user.tenant_id);
|
|
754
|
+
if (!tenant) return reply.status(404).send({ error: 'Tenant not found' });
|
|
755
|
+
|
|
756
|
+
const current = tenant.settings?.whatsapp_agent?.blacklisted_numbers || [];
|
|
757
|
+
if (current.includes(cleaned)) {
|
|
758
|
+
return { numbers: current };
|
|
759
|
+
}
|
|
760
|
+
|
|
761
|
+
const updated = [...current, cleaned];
|
|
762
|
+
await Tenant.findByIdAndUpdate(request.user.tenant_id, {
|
|
763
|
+
$set: { 'settings.whatsapp_agent.blacklisted_numbers': updated }
|
|
764
|
+
});
|
|
765
|
+
|
|
766
|
+
return { numbers: updated };
|
|
767
|
+
});
|
|
768
|
+
|
|
769
|
+
// DELETE /whatsapp/blacklist/:phone — Remove number from blacklist
|
|
770
|
+
fastify.delete<{ Params: { phone: string } }>('/blacklist/:phone', {
|
|
771
|
+
preHandler: [requireRole('admin', 'manager')],
|
|
772
|
+
}, async (request) => {
|
|
773
|
+
const { phone } = request.params;
|
|
774
|
+
const tenant = await Tenant.findById(request.user.tenant_id);
|
|
775
|
+
const current = tenant?.settings?.whatsapp_agent?.blacklisted_numbers || [];
|
|
776
|
+
const updated = current.filter(n => n !== phone);
|
|
777
|
+
|
|
778
|
+
await Tenant.findByIdAndUpdate(request.user.tenant_id, {
|
|
779
|
+
$set: { 'settings.whatsapp_agent.blacklisted_numbers': updated }
|
|
780
|
+
});
|
|
781
|
+
|
|
782
|
+
return { numbers: updated };
|
|
783
|
+
});
|
|
784
|
+
|
|
785
|
+
// ─── Stats ────────────────────────────────────────────────
|
|
786
|
+
|
|
787
|
+
fastify.get('/stats', {
|
|
788
|
+
preHandler: [requireRole('admin', 'manager', 'viewer')],
|
|
789
|
+
}, async (request) => {
|
|
790
|
+
const tenantId = new mongoose.Types.ObjectId(request.user.tenant_id);
|
|
791
|
+
|
|
792
|
+
const [totalChats, closedChats, waitingSessions, activeSessions, totalMessages] = await Promise.all([
|
|
793
|
+
WhatsAppChat.countDocuments({ tenant_id: tenantId }),
|
|
794
|
+
WhatsAppChat.countDocuments({ tenant_id: tenantId, is_closed: true }),
|
|
795
|
+
WhatsAppSession.countDocuments({ tenant_id: tenantId, status: 'waiting' }),
|
|
796
|
+
WhatsAppSession.countDocuments({ tenant_id: tenantId, status: 'active' }),
|
|
797
|
+
WhatsAppMessage.countDocuments({ tenant_id: tenantId }),
|
|
798
|
+
]);
|
|
799
|
+
|
|
800
|
+
// Derive AI vs human from active sessions
|
|
801
|
+
const humanTakeoverCount = await WhatsAppSession.countDocuments({
|
|
802
|
+
tenant_id: tenantId,
|
|
803
|
+
status: 'active',
|
|
804
|
+
$or: [
|
|
805
|
+
{ taken_over_by: { $ne: null } },
|
|
806
|
+
{ taken_over_at: { $ne: null } },
|
|
807
|
+
],
|
|
808
|
+
});
|
|
809
|
+
|
|
810
|
+
const aiChats = activeSessions - humanTakeoverCount;
|
|
811
|
+
const humanChats = humanTakeoverCount + waitingSessions; // waiting = human has first chance
|
|
812
|
+
|
|
813
|
+
return {
|
|
814
|
+
stats: {
|
|
815
|
+
totalChats,
|
|
816
|
+
aiChats,
|
|
817
|
+
humanChats,
|
|
818
|
+
closedChats,
|
|
819
|
+
waitingChats: waitingSessions,
|
|
820
|
+
totalMessages,
|
|
821
|
+
},
|
|
822
|
+
};
|
|
823
|
+
});
|
|
824
|
+
|
|
825
|
+
// ─── Chat Management ─────────────────────────────────────
|
|
826
|
+
|
|
827
|
+
// GET /whatsapp/chats — List all chats for this tenant
|
|
828
|
+
fastify.get<{
|
|
829
|
+
Querystring: { page?: string; limit?: string; mode?: string };
|
|
830
|
+
}>('/chats', {
|
|
831
|
+
preHandler: [requireRole('admin', 'manager', 'viewer')],
|
|
832
|
+
}, async (request) => {
|
|
833
|
+
const page = parseInt(request.query.page || '1', 10);
|
|
834
|
+
const limit = Math.min(parseInt(request.query.limit || '20', 10), 100);
|
|
835
|
+
const skip = (page - 1) * limit;
|
|
836
|
+
const modeFilter = request.query.mode;
|
|
837
|
+
|
|
838
|
+
// For mode filtering, we need to derive mode from sessions
|
|
839
|
+
if (modeFilter && ['ai', 'human', 'closed'].includes(modeFilter)) {
|
|
840
|
+
// Use aggregation to filter by derived mode
|
|
841
|
+
const tenantId = new mongoose.Types.ObjectId(request.user.tenant_id);
|
|
842
|
+
|
|
843
|
+
const pipeline: any[] = [
|
|
844
|
+
{ $match: { tenant_id: tenantId, deleted_at: null } },
|
|
845
|
+
// Left join with active session
|
|
846
|
+
{
|
|
847
|
+
$lookup: {
|
|
848
|
+
from: 'whatsappsessions',
|
|
849
|
+
let: { sid: '$active_session_id' },
|
|
850
|
+
pipeline: [
|
|
851
|
+
{ $match: { $expr: { $eq: ['$_id', '$$sid'] } } },
|
|
852
|
+
{ $match: { status: { $ne: 'resolved' } } },
|
|
853
|
+
],
|
|
854
|
+
as: '_session',
|
|
855
|
+
},
|
|
856
|
+
},
|
|
857
|
+
{ $addFields: { _activeSession: { $arrayElemAt: ['$_session', 0] } } },
|
|
858
|
+
// Derive mode
|
|
859
|
+
{
|
|
860
|
+
$addFields: {
|
|
861
|
+
_mode: {
|
|
862
|
+
$switch: {
|
|
863
|
+
branches: [
|
|
864
|
+
// No active session + is_closed
|
|
865
|
+
{
|
|
866
|
+
case: { $and: [{ $eq: [{ $ifNull: ['$_activeSession', null] }, null] }, { $eq: ['$is_closed', true] }] },
|
|
867
|
+
then: 'closed',
|
|
868
|
+
},
|
|
869
|
+
// No active session + not closed
|
|
870
|
+
{
|
|
871
|
+
case: { $eq: [{ $ifNull: ['$_activeSession', null] }, null] },
|
|
872
|
+
then: 'ai',
|
|
873
|
+
},
|
|
874
|
+
// Session waiting
|
|
875
|
+
{
|
|
876
|
+
case: { $eq: ['$_activeSession.status', 'waiting'] },
|
|
877
|
+
then: 'human',
|
|
878
|
+
},
|
|
879
|
+
// Session active + taken over
|
|
880
|
+
{
|
|
881
|
+
case: {
|
|
882
|
+
$and: [
|
|
883
|
+
{ $eq: ['$_activeSession.status', 'active'] },
|
|
884
|
+
{
|
|
885
|
+
$or: [
|
|
886
|
+
{ $ne: [{ $ifNull: ['$_activeSession.taken_over_by', null] }, null] },
|
|
887
|
+
{ $ne: [{ $ifNull: ['$_activeSession.taken_over_at', null] }, null] },
|
|
888
|
+
],
|
|
889
|
+
},
|
|
890
|
+
],
|
|
891
|
+
},
|
|
892
|
+
then: 'human',
|
|
893
|
+
},
|
|
894
|
+
// Session active + no takeover
|
|
895
|
+
{
|
|
896
|
+
case: { $eq: ['$_activeSession.status', 'active'] },
|
|
897
|
+
then: 'ai',
|
|
898
|
+
},
|
|
899
|
+
],
|
|
900
|
+
default: 'ai',
|
|
901
|
+
},
|
|
902
|
+
},
|
|
903
|
+
},
|
|
904
|
+
},
|
|
905
|
+
{ $match: { _mode: modeFilter } },
|
|
906
|
+
{ $sort: { last_message_at: -1 as const } },
|
|
907
|
+
{
|
|
908
|
+
$facet: {
|
|
909
|
+
data: [{ $skip: skip }, { $limit: limit }],
|
|
910
|
+
count: [{ $count: 'total' }],
|
|
911
|
+
},
|
|
912
|
+
},
|
|
913
|
+
];
|
|
914
|
+
|
|
915
|
+
const [result] = await WhatsAppChat.aggregate(pipeline);
|
|
916
|
+
const rawChats = result?.data || [];
|
|
917
|
+
const total = result?.count?.[0]?.total || 0;
|
|
918
|
+
const chats = await enrichChats(rawChats);
|
|
919
|
+
|
|
920
|
+
return { chats, total, page, totalPages: Math.ceil(total / limit) };
|
|
921
|
+
}
|
|
922
|
+
|
|
923
|
+
// No mode filter — simple query
|
|
924
|
+
const filter: Record<string, unknown> = { tenant_id: request.user.tenant_id, deleted_at: null };
|
|
925
|
+
|
|
926
|
+
const [rawChats, total] = await Promise.all([
|
|
927
|
+
WhatsAppChat.find(filter)
|
|
928
|
+
.sort({ last_message_at: -1 })
|
|
929
|
+
.skip(skip)
|
|
930
|
+
.limit(limit)
|
|
931
|
+
.lean(),
|
|
932
|
+
WhatsAppChat.countDocuments(filter),
|
|
933
|
+
]);
|
|
934
|
+
|
|
935
|
+
const chats = await enrichChats(rawChats);
|
|
936
|
+
return { chats, total, page, totalPages: Math.ceil(total / limit) };
|
|
937
|
+
});
|
|
938
|
+
|
|
939
|
+
// GET /whatsapp/chats/:chatId — Get single chat detail
|
|
940
|
+
fastify.get<{ Params: { chatId: string } }>('/chats/:chatId', {
|
|
941
|
+
preHandler: [requireRole('admin', 'manager', 'viewer')],
|
|
942
|
+
}, async (request, reply) => {
|
|
943
|
+
const { chatId } = request.params;
|
|
944
|
+
const rawChat = await WhatsAppChat.findOne({
|
|
945
|
+
_id: chatId,
|
|
946
|
+
tenant_id: request.user.tenant_id,
|
|
947
|
+
}).lean();
|
|
948
|
+
|
|
949
|
+
if (!rawChat) return reply.status(404).send({ error: 'Chat not found' });
|
|
950
|
+
|
|
951
|
+
const chat = await enrichChat(rawChat);
|
|
952
|
+
|
|
953
|
+
// Include contact profile if linked
|
|
954
|
+
if (rawChat.contact_profile_id) {
|
|
955
|
+
chat.contact_profile = await WhatsAppContactProfile.findById(rawChat.contact_profile_id).lean();
|
|
956
|
+
}
|
|
957
|
+
|
|
958
|
+
return { chat };
|
|
959
|
+
});
|
|
960
|
+
|
|
961
|
+
// GET /whatsapp/chats/:chatId/messages — Get messages for a chat
|
|
962
|
+
fastify.get<{
|
|
963
|
+
Params: { chatId: string };
|
|
964
|
+
Querystring: { page?: string; limit?: string };
|
|
965
|
+
}>('/chats/:chatId/messages', {
|
|
966
|
+
preHandler: [requireRole('admin', 'manager', 'viewer')],
|
|
967
|
+
}, async (request, reply) => {
|
|
968
|
+
const { chatId } = request.params;
|
|
969
|
+
const page = parseInt(request.query.page || '1', 10);
|
|
970
|
+
const limit = Math.min(parseInt(request.query.limit || '50', 10), 200);
|
|
971
|
+
const skip = (page - 1) * limit;
|
|
972
|
+
|
|
973
|
+
// Verify chat belongs to tenant
|
|
974
|
+
const chat = await WhatsAppChat.findOne({
|
|
975
|
+
_id: chatId,
|
|
976
|
+
tenant_id: request.user.tenant_id,
|
|
977
|
+
});
|
|
978
|
+
if (!chat) return reply.status(404).send({ error: 'Chat not found' });
|
|
979
|
+
|
|
980
|
+
const [messages, total] = await Promise.all([
|
|
981
|
+
WhatsAppMessage.find({ chat_id: chatId })
|
|
982
|
+
.sort({ createdAt: 1 })
|
|
983
|
+
.skip(skip)
|
|
984
|
+
.limit(limit)
|
|
985
|
+
.lean(),
|
|
986
|
+
WhatsAppMessage.countDocuments({ chat_id: chatId }),
|
|
987
|
+
]);
|
|
988
|
+
|
|
989
|
+
return { messages, total, page, totalPages: Math.ceil(total / limit) };
|
|
990
|
+
});
|
|
991
|
+
|
|
992
|
+
// GET /whatsapp/chats/:chatId/sessions — Get session history for a chat
|
|
993
|
+
fastify.get<{
|
|
994
|
+
Params: { chatId: string };
|
|
995
|
+
Querystring: { page?: string; limit?: string };
|
|
996
|
+
}>('/chats/:chatId/sessions', {
|
|
997
|
+
preHandler: [requireRole('admin', 'manager', 'viewer')],
|
|
998
|
+
}, async (request, reply) => {
|
|
999
|
+
const { chatId } = request.params;
|
|
1000
|
+
const page = parseInt(request.query.page || '1', 10);
|
|
1001
|
+
const limit = Math.min(parseInt(request.query.limit || '20', 10), 50);
|
|
1002
|
+
const skip = (page - 1) * limit;
|
|
1003
|
+
|
|
1004
|
+
const chat = await WhatsAppChat.findOne({
|
|
1005
|
+
_id: chatId,
|
|
1006
|
+
tenant_id: request.user.tenant_id,
|
|
1007
|
+
});
|
|
1008
|
+
if (!chat) return reply.status(404).send({ error: 'Chat not found' });
|
|
1009
|
+
|
|
1010
|
+
const [sessions, total] = await Promise.all([
|
|
1011
|
+
WhatsAppSession.find({ chat_id: chatId })
|
|
1012
|
+
.populate('taken_over_by', 'name email')
|
|
1013
|
+
.sort({ started_at: -1 })
|
|
1014
|
+
.skip(skip)
|
|
1015
|
+
.limit(limit)
|
|
1016
|
+
.lean(),
|
|
1017
|
+
WhatsAppSession.countDocuments({ chat_id: chatId }),
|
|
1018
|
+
]);
|
|
1019
|
+
|
|
1020
|
+
return { sessions, total, page, totalPages: Math.ceil(total / limit) };
|
|
1021
|
+
});
|
|
1022
|
+
|
|
1023
|
+
// ─── Takeover / Release / Close / Reopen ──────────────────
|
|
1024
|
+
|
|
1025
|
+
// POST /whatsapp/chats/:chatId/takeover
|
|
1026
|
+
fastify.post<{ Params: { chatId: string } }>('/chats/:chatId/takeover', {
|
|
1027
|
+
preHandler: [requireRole('admin', 'manager')],
|
|
1028
|
+
}, async (request, reply) => {
|
|
1029
|
+
const { chatId } = request.params;
|
|
1030
|
+
const chat = await WhatsAppChat.findOne({
|
|
1031
|
+
_id: chatId,
|
|
1032
|
+
tenant_id: request.user.tenant_id,
|
|
1033
|
+
});
|
|
1034
|
+
if (!chat) return reply.status(404).send({ error: 'Chat not found' });
|
|
1035
|
+
|
|
1036
|
+
// Look up active session
|
|
1037
|
+
const session = chat.active_session_id
|
|
1038
|
+
? await WhatsAppSession.findById(chat.active_session_id)
|
|
1039
|
+
: null;
|
|
1040
|
+
|
|
1041
|
+
if (!session || session.status === 'resolved') {
|
|
1042
|
+
return reply.status(400).send({ error: 'No active session to take over' });
|
|
1043
|
+
}
|
|
1044
|
+
|
|
1045
|
+
// If session is waiting, cancel the grace timer
|
|
1046
|
+
if (session.status === 'waiting') {
|
|
1047
|
+
whatsappAgentService.cancelSession(session._id.toString());
|
|
1048
|
+
session.status = 'active';
|
|
1049
|
+
}
|
|
1050
|
+
|
|
1051
|
+
// Close the ElevenLabs WebSocket
|
|
1052
|
+
whatsappAgentService.closeConnection(chat.unipile_chat_id);
|
|
1053
|
+
|
|
1054
|
+
session.taken_over_by = new mongoose.Types.ObjectId(request.user.id);
|
|
1055
|
+
session.taken_over_at = new Date();
|
|
1056
|
+
await session.save();
|
|
1057
|
+
|
|
1058
|
+
const enriched = await enrichChat(chat);
|
|
1059
|
+
return { chat: enriched };
|
|
1060
|
+
});
|
|
1061
|
+
|
|
1062
|
+
// POST /whatsapp/chats/:chatId/release
|
|
1063
|
+
fastify.post<{ Params: { chatId: string } }>('/chats/:chatId/release', {
|
|
1064
|
+
preHandler: [requireRole('admin', 'manager')],
|
|
1065
|
+
}, async (request, reply) => {
|
|
1066
|
+
const { chatId } = request.params;
|
|
1067
|
+
const { immediate } = (request.body as { immediate?: boolean }) || {};
|
|
1068
|
+
|
|
1069
|
+
const chat = await WhatsAppChat.findOne({
|
|
1070
|
+
_id: chatId,
|
|
1071
|
+
tenant_id: request.user.tenant_id,
|
|
1072
|
+
});
|
|
1073
|
+
if (!chat) return reply.status(404).send({ error: 'Chat not found' });
|
|
1074
|
+
|
|
1075
|
+
// Look up active session
|
|
1076
|
+
const session = chat.active_session_id
|
|
1077
|
+
? await WhatsAppSession.findById(chat.active_session_id)
|
|
1078
|
+
: null;
|
|
1079
|
+
|
|
1080
|
+
if (!session || session.status === 'resolved') {
|
|
1081
|
+
return reply.status(400).send({ error: 'No active session to release' });
|
|
1082
|
+
}
|
|
1083
|
+
|
|
1084
|
+
// Verify it's in human mode (taken over)
|
|
1085
|
+
if (!session.taken_over_by && !session.taken_over_at) {
|
|
1086
|
+
return reply.status(400).send({ error: 'Chat is not in human mode' });
|
|
1087
|
+
}
|
|
1088
|
+
|
|
1089
|
+
// Clear human takeover, reset EL fields so a new conversation starts
|
|
1090
|
+
session.taken_over_by = null;
|
|
1091
|
+
session.taken_over_at = null;
|
|
1092
|
+
session.elevenlabs_conversation_id = null;
|
|
1093
|
+
session.elevenlabs_conversation_created_at = null;
|
|
1094
|
+
session.elevenlabs_last_interaction_at = null;
|
|
1095
|
+
await session.save();
|
|
1096
|
+
|
|
1097
|
+
let pendingCount = 0;
|
|
1098
|
+
|
|
1099
|
+
if (immediate) {
|
|
1100
|
+
const tenant = await Tenant.findById(request.user.tenant_id).lean();
|
|
1101
|
+
const agentObjId = tenant?.settings?.whatsapp_agent?.agent_id;
|
|
1102
|
+
const agentDoc = agentObjId ? await Agent.findById(agentObjId).lean() : null;
|
|
1103
|
+
const agentId = (agentDoc && agentDoc.is_active) ? agentDoc.elevenlabs_agent_id : null;
|
|
1104
|
+
|
|
1105
|
+
if (agentId) {
|
|
1106
|
+
const result = await whatsappAgentService.replayPendingMessages({
|
|
1107
|
+
tenantId: request.user.tenant_id,
|
|
1108
|
+
agentId,
|
|
1109
|
+
session,
|
|
1110
|
+
});
|
|
1111
|
+
pendingCount = result.pendingCount;
|
|
1112
|
+
} else {
|
|
1113
|
+
logger.warn('Immediate AI response requested but no agent configured', { chatId });
|
|
1114
|
+
}
|
|
1115
|
+
}
|
|
1116
|
+
|
|
1117
|
+
const enriched = await enrichChat(chat);
|
|
1118
|
+
return { chat: enriched, pendingCount };
|
|
1119
|
+
});
|
|
1120
|
+
|
|
1121
|
+
// POST /whatsapp/chats/:chatId/close
|
|
1122
|
+
fastify.post<{ Params: { chatId: string } }>('/chats/:chatId/close', {
|
|
1123
|
+
preHandler: [requireRole('admin', 'manager')],
|
|
1124
|
+
}, async (request, reply) => {
|
|
1125
|
+
const { chatId } = request.params;
|
|
1126
|
+
const chat = await WhatsAppChat.findOne({
|
|
1127
|
+
_id: chatId,
|
|
1128
|
+
tenant_id: request.user.tenant_id,
|
|
1129
|
+
});
|
|
1130
|
+
if (!chat) return reply.status(404).send({ error: 'Chat not found' });
|
|
1131
|
+
|
|
1132
|
+
// Resolve active session if any
|
|
1133
|
+
let resolvedSessionId: string | null = null;
|
|
1134
|
+
if (chat.active_session_id) {
|
|
1135
|
+
const session = await WhatsAppSession.findById(chat.active_session_id);
|
|
1136
|
+
if (session && session.status !== 'resolved') {
|
|
1137
|
+
if (session.status === 'waiting') {
|
|
1138
|
+
whatsappAgentService.cancelSession(session._id.toString());
|
|
1139
|
+
}
|
|
1140
|
+
session.status = 'resolved';
|
|
1141
|
+
session.resolved_by = 'manual';
|
|
1142
|
+
session.resolved_at = new Date();
|
|
1143
|
+
await session.save();
|
|
1144
|
+
resolvedSessionId = session._id.toString();
|
|
1145
|
+
}
|
|
1146
|
+
chat.active_session_id = null;
|
|
1147
|
+
}
|
|
1148
|
+
|
|
1149
|
+
whatsappAgentService.closeConnection(chat.unipile_chat_id);
|
|
1150
|
+
|
|
1151
|
+
chat.is_closed = true;
|
|
1152
|
+
await chat.save();
|
|
1153
|
+
|
|
1154
|
+
if (resolvedSessionId) {
|
|
1155
|
+
whatsappAgentService.updateContactProfileSummary(resolvedSessionId).catch(err => {
|
|
1156
|
+
logger.error('Profile summary update failed after close', { error: (err as Error).message });
|
|
1157
|
+
});
|
|
1158
|
+
whatsappAgentService.generateSessionLabels(resolvedSessionId).catch(err => {
|
|
1159
|
+
logger.error('Session labelling failed after close', { error: (err as Error).message });
|
|
1160
|
+
});
|
|
1161
|
+
}
|
|
1162
|
+
|
|
1163
|
+
const enriched = await enrichChat(chat);
|
|
1164
|
+
return { chat: enriched };
|
|
1165
|
+
});
|
|
1166
|
+
|
|
1167
|
+
// POST /whatsapp/chats/:chatId/reopen
|
|
1168
|
+
fastify.post<{ Params: { chatId: string } }>('/chats/:chatId/reopen', {
|
|
1169
|
+
preHandler: [requireRole('admin', 'manager')],
|
|
1170
|
+
}, async (request, reply) => {
|
|
1171
|
+
const { chatId } = request.params;
|
|
1172
|
+
const chat = await WhatsAppChat.findOne({
|
|
1173
|
+
_id: chatId,
|
|
1174
|
+
tenant_id: request.user.tenant_id,
|
|
1175
|
+
});
|
|
1176
|
+
if (!chat) return reply.status(404).send({ error: 'Chat not found' });
|
|
1177
|
+
|
|
1178
|
+
chat.is_closed = false;
|
|
1179
|
+
await chat.save();
|
|
1180
|
+
|
|
1181
|
+
const enriched = await enrichChat(chat);
|
|
1182
|
+
return { chat: enriched };
|
|
1183
|
+
});
|
|
1184
|
+
|
|
1185
|
+
// DELETE /whatsapp/chats/:chatId — Soft-delete a chat (hidden until contact messages again)
|
|
1186
|
+
fastify.delete<{ Params: { chatId: string } }>('/chats/:chatId', {
|
|
1187
|
+
preHandler: [requireRole('admin', 'manager')],
|
|
1188
|
+
}, async (request, reply) => {
|
|
1189
|
+
const { chatId } = request.params;
|
|
1190
|
+
const chat = await WhatsAppChat.findOne({
|
|
1191
|
+
_id: chatId,
|
|
1192
|
+
tenant_id: request.user.tenant_id,
|
|
1193
|
+
});
|
|
1194
|
+
if (!chat) return reply.status(404).send({ error: 'Chat not found' });
|
|
1195
|
+
|
|
1196
|
+
// Resolve active session if any
|
|
1197
|
+
let deletedSessionId: string | null = null;
|
|
1198
|
+
if (chat.active_session_id) {
|
|
1199
|
+
const session = await WhatsAppSession.findById(chat.active_session_id);
|
|
1200
|
+
if (session && session.status !== 'resolved') {
|
|
1201
|
+
session.status = 'resolved';
|
|
1202
|
+
session.resolved_by = 'manual';
|
|
1203
|
+
session.resolved_at = new Date();
|
|
1204
|
+
await session.save();
|
|
1205
|
+
whatsappAgentService.cancelSession(session._id.toString());
|
|
1206
|
+
deletedSessionId = session._id.toString();
|
|
1207
|
+
}
|
|
1208
|
+
chat.active_session_id = null;
|
|
1209
|
+
}
|
|
1210
|
+
|
|
1211
|
+
// Close EL WebSocket if connected
|
|
1212
|
+
whatsappAgentService.closeConnection(chat.unipile_chat_id);
|
|
1213
|
+
|
|
1214
|
+
chat.is_closed = true;
|
|
1215
|
+
chat.deleted_at = new Date();
|
|
1216
|
+
await chat.save();
|
|
1217
|
+
|
|
1218
|
+
if (deletedSessionId) {
|
|
1219
|
+
whatsappAgentService.updateContactProfileSummary(deletedSessionId).catch(err => {
|
|
1220
|
+
logger.error('Profile summary update failed after delete', { error: (err as Error).message });
|
|
1221
|
+
});
|
|
1222
|
+
whatsappAgentService.generateSessionLabels(deletedSessionId).catch(err => {
|
|
1223
|
+
logger.error('Session labelling failed after delete', { error: (err as Error).message });
|
|
1224
|
+
});
|
|
1225
|
+
}
|
|
1226
|
+
|
|
1227
|
+
return { success: true };
|
|
1228
|
+
});
|
|
1229
|
+
|
|
1230
|
+
// ─── Manual Message ───────────────────────────────────────
|
|
1231
|
+
|
|
1232
|
+
// POST /whatsapp/chats/:chatId/send
|
|
1233
|
+
fastify.post<{ Params: { chatId: string } }>('/chats/:chatId/send', {
|
|
1234
|
+
preHandler: [requireRole('admin', 'manager')],
|
|
1235
|
+
}, async (request, reply) => {
|
|
1236
|
+
const { chatId } = request.params;
|
|
1237
|
+
const { text } = request.body as { text: string };
|
|
1238
|
+
|
|
1239
|
+
if (!text?.trim()) {
|
|
1240
|
+
return reply.status(400).send({ error: 'Message text is required' });
|
|
1241
|
+
}
|
|
1242
|
+
|
|
1243
|
+
const chat = await WhatsAppChat.findOne({
|
|
1244
|
+
_id: chatId,
|
|
1245
|
+
tenant_id: request.user.tenant_id,
|
|
1246
|
+
});
|
|
1247
|
+
if (!chat) return reply.status(404).send({ error: 'Chat not found' });
|
|
1248
|
+
|
|
1249
|
+
// Verify chat is in human mode (has an active session with takeover)
|
|
1250
|
+
const session = chat.active_session_id
|
|
1251
|
+
? await WhatsAppSession.findById(chat.active_session_id)
|
|
1252
|
+
: null;
|
|
1253
|
+
|
|
1254
|
+
const isHumanMode = session
|
|
1255
|
+
&& session.status !== 'resolved'
|
|
1256
|
+
&& (session.taken_over_by || session.taken_over_at || session.status === 'waiting');
|
|
1257
|
+
|
|
1258
|
+
if (!isHumanMode) {
|
|
1259
|
+
return reply.status(400).send({ error: 'Chat must be in human mode to send manual messages' });
|
|
1260
|
+
}
|
|
1261
|
+
|
|
1262
|
+
// If session was waiting, the human is now responding — cancel grace timer and resolve
|
|
1263
|
+
if (session!.status === 'waiting') {
|
|
1264
|
+
whatsappAgentService.cancelSession(session!._id.toString());
|
|
1265
|
+
session!.status = 'resolved';
|
|
1266
|
+
session!.resolved_by = 'human';
|
|
1267
|
+
session!.resolved_at = new Date();
|
|
1268
|
+
await session!.save();
|
|
1269
|
+
chat.active_session_id = null;
|
|
1270
|
+
await chat.save();
|
|
1271
|
+
|
|
1272
|
+
whatsappAgentService.updateContactProfileSummary(session!._id.toString()).catch(err => {
|
|
1273
|
+
logger.error('Profile summary update failed after send', { error: (err as Error).message });
|
|
1274
|
+
});
|
|
1275
|
+
whatsappAgentService.generateSessionLabels(session!._id.toString()).catch(err => {
|
|
1276
|
+
logger.error('Session labelling failed after send', { error: (err as Error).message });
|
|
1277
|
+
});
|
|
1278
|
+
}
|
|
1279
|
+
|
|
1280
|
+
// Send via bridge provider
|
|
1281
|
+
const tenant = await Tenant.findById(request.user.tenant_id);
|
|
1282
|
+
const provider = unipileService.getProviderForTenant(tenant);
|
|
1283
|
+
const result = await unipileService.sendMessage(provider, chat.unipile_chat_id, text.trim());
|
|
1284
|
+
|
|
1285
|
+
// Store in DB
|
|
1286
|
+
const message = await WhatsAppMessage.create({
|
|
1287
|
+
chat_id: chat._id,
|
|
1288
|
+
session_id: session!._id,
|
|
1289
|
+
tenant_id: chat.tenant_id,
|
|
1290
|
+
unipile_message_id: result.message_id || null,
|
|
1291
|
+
sender: 'human',
|
|
1292
|
+
sender_name: request.user.id,
|
|
1293
|
+
text: text.trim(),
|
|
1294
|
+
sent_via_unipile: true,
|
|
1295
|
+
});
|
|
1296
|
+
|
|
1297
|
+
// Update chat
|
|
1298
|
+
chat.last_message_at = new Date();
|
|
1299
|
+
chat.last_message_preview = text.trim().substring(0, 100);
|
|
1300
|
+
chat.message_count += 1;
|
|
1301
|
+
await chat.save();
|
|
1302
|
+
|
|
1303
|
+
return { message: message.toObject() };
|
|
1304
|
+
});
|
|
1305
|
+
|
|
1306
|
+
// ─── Contact Profiles ──────────────────────────────────────
|
|
1307
|
+
|
|
1308
|
+
// GET /whatsapp/contacts — List contact profiles
|
|
1309
|
+
fastify.get<{
|
|
1310
|
+
Querystring: { page?: string; limit?: string; search?: string };
|
|
1311
|
+
}>('/contacts', {
|
|
1312
|
+
preHandler: [requireRole('admin', 'manager', 'viewer')],
|
|
1313
|
+
}, async (request) => {
|
|
1314
|
+
const page = parseInt(request.query.page || '1', 10);
|
|
1315
|
+
const limit = Math.min(parseInt(request.query.limit || '20', 10), 100);
|
|
1316
|
+
const skip = (page - 1) * limit;
|
|
1317
|
+
const search = request.query.search?.trim();
|
|
1318
|
+
|
|
1319
|
+
const filter: Record<string, unknown> = { tenant_id: request.user.tenant_id };
|
|
1320
|
+
if (search) {
|
|
1321
|
+
filter.$or = [
|
|
1322
|
+
{ display_name: { $regex: search, $options: 'i' } },
|
|
1323
|
+
{ phone: { $regex: search, $options: 'i' } },
|
|
1324
|
+
{ tags: { $in: [new RegExp(search, 'i')] } },
|
|
1325
|
+
];
|
|
1326
|
+
}
|
|
1327
|
+
|
|
1328
|
+
const [profiles, total] = await Promise.all([
|
|
1329
|
+
WhatsAppContactProfile.find(filter)
|
|
1330
|
+
.sort({ last_seen_at: -1 })
|
|
1331
|
+
.skip(skip)
|
|
1332
|
+
.limit(limit)
|
|
1333
|
+
.lean(),
|
|
1334
|
+
WhatsAppContactProfile.countDocuments(filter),
|
|
1335
|
+
]);
|
|
1336
|
+
|
|
1337
|
+
return { profiles, total, page, totalPages: Math.ceil(total / limit) };
|
|
1338
|
+
});
|
|
1339
|
+
|
|
1340
|
+
// GET /whatsapp/contacts/:profileId — Get single profile with linked chats
|
|
1341
|
+
fastify.get<{ Params: { profileId: string } }>('/contacts/:profileId', {
|
|
1342
|
+
preHandler: [requireRole('admin', 'manager', 'viewer')],
|
|
1343
|
+
}, async (request, reply) => {
|
|
1344
|
+
const profile = await WhatsAppContactProfile.findOne({
|
|
1345
|
+
_id: request.params.profileId,
|
|
1346
|
+
tenant_id: request.user.tenant_id,
|
|
1347
|
+
}).lean();
|
|
1348
|
+
|
|
1349
|
+
if (!profile) return reply.status(404).send({ error: 'Profile not found' });
|
|
1350
|
+
|
|
1351
|
+
const chats = await WhatsAppChat.find({
|
|
1352
|
+
tenant_id: request.user.tenant_id,
|
|
1353
|
+
contact_phone: profile.phone,
|
|
1354
|
+
deleted_at: null,
|
|
1355
|
+
}).sort({ last_message_at: -1 }).lean();
|
|
1356
|
+
|
|
1357
|
+
return { profile, chats };
|
|
1358
|
+
});
|
|
1359
|
+
|
|
1360
|
+
// PUT /whatsapp/contacts/:profileId — Update profile notes/tags
|
|
1361
|
+
fastify.put<{ Params: { profileId: string } }>('/contacts/:profileId', {
|
|
1362
|
+
preHandler: [requireRole('admin', 'manager')],
|
|
1363
|
+
}, async (request, reply) => {
|
|
1364
|
+
const { notes, tags } = request.body as { notes?: string; tags?: string[] };
|
|
1365
|
+
|
|
1366
|
+
const update: Record<string, unknown> = {};
|
|
1367
|
+
if (notes !== undefined) update.notes = notes;
|
|
1368
|
+
if (tags !== undefined) update.tags = tags;
|
|
1369
|
+
|
|
1370
|
+
const profile = await WhatsAppContactProfile.findOneAndUpdate(
|
|
1371
|
+
{ _id: request.params.profileId, tenant_id: request.user.tenant_id },
|
|
1372
|
+
{ $set: update },
|
|
1373
|
+
{ new: true },
|
|
1374
|
+
);
|
|
1375
|
+
|
|
1376
|
+
if (!profile) return reply.status(404).send({ error: 'Profile not found' });
|
|
1377
|
+
return { profile };
|
|
1378
|
+
});
|
|
1379
|
+
|
|
1380
|
+
// POST /whatsapp/chats/:chatId/generate-summary — Manually trigger profile summary for a chat's latest session
|
|
1381
|
+
fastify.post<{ Params: { chatId: string } }>('/chats/:chatId/generate-summary', {
|
|
1382
|
+
preHandler: [requireRole('admin')],
|
|
1383
|
+
}, async (request, reply) => {
|
|
1384
|
+
const { chatId } = request.params;
|
|
1385
|
+
const chat = await WhatsAppChat.findOne({
|
|
1386
|
+
_id: chatId,
|
|
1387
|
+
tenant_id: request.user.tenant_id,
|
|
1388
|
+
});
|
|
1389
|
+
if (!chat) return reply.status(404).send({ error: 'Chat not found' });
|
|
1390
|
+
|
|
1391
|
+
// Ensure a contact profile exists — auto-create from chat data if missing
|
|
1392
|
+
if (!chat.contact_profile_id) {
|
|
1393
|
+
const profile = await WhatsAppContactProfile.findOneAndUpdate(
|
|
1394
|
+
{ tenant_id: chat.tenant_id, phone: chat.contact_phone },
|
|
1395
|
+
{
|
|
1396
|
+
$set: { display_name: chat.contact_name, last_seen_at: new Date() },
|
|
1397
|
+
$setOnInsert: { first_seen_at: new Date(), notes: '', tags: [], ai_summary: '', metadata: {} },
|
|
1398
|
+
},
|
|
1399
|
+
{ upsert: true, new: true },
|
|
1400
|
+
);
|
|
1401
|
+
chat.contact_profile_id = profile._id;
|
|
1402
|
+
await WhatsAppChat.updateOne({ _id: chat._id }, { $set: { contact_profile_id: profile._id } });
|
|
1403
|
+
}
|
|
1404
|
+
|
|
1405
|
+
// Find the latest session with messages
|
|
1406
|
+
const latestSession = await WhatsAppSession.findOne({ chat_id: chatId })
|
|
1407
|
+
.sort({ started_at: -1 })
|
|
1408
|
+
.lean();
|
|
1409
|
+
|
|
1410
|
+
if (!latestSession) {
|
|
1411
|
+
return reply.status(400).send({ error: 'No sessions found for this chat' });
|
|
1412
|
+
}
|
|
1413
|
+
|
|
1414
|
+
const messageCount = await WhatsAppMessage.countDocuments({ session_id: latestSession._id });
|
|
1415
|
+
if (messageCount < 2) {
|
|
1416
|
+
return reply.status(400).send({ error: 'Session has fewer than 2 messages' });
|
|
1417
|
+
}
|
|
1418
|
+
|
|
1419
|
+
// Run synchronously so we can return the result
|
|
1420
|
+
try {
|
|
1421
|
+
await whatsappAgentService.updateContactProfileSummary(latestSession._id.toString());
|
|
1422
|
+
} catch (err) {
|
|
1423
|
+
return reply.status(500).send({ error: (err as Error).message });
|
|
1424
|
+
}
|
|
1425
|
+
|
|
1426
|
+
// Return updated profile
|
|
1427
|
+
const profile = await WhatsAppContactProfile.findById(chat.contact_profile_id).lean();
|
|
1428
|
+
|
|
1429
|
+
return {
|
|
1430
|
+
session_id: latestSession._id,
|
|
1431
|
+
session_message_count: messageCount,
|
|
1432
|
+
profile,
|
|
1433
|
+
};
|
|
1434
|
+
});
|
|
1435
|
+
}
|