### Frontend Development Setup Source: https://github.com/astraonlineweb/astracampaign/blob/main/README.md Commands to set up and run the frontend development server. This involves installing dependencies and starting the Vite development server. ```bash cd frontend npm install npm run dev # Servidor de desenvolvimento (porta 3000) ``` -------------------------------- ### Backend Development Setup Source: https://github.com/astraonlineweb/astracampaign/blob/main/README.md Commands to set up and run the backend service for local development. This includes installing dependencies, running database migrations, and starting the development server. ```bash cd backend npm install npm run migrate:prod # Rodar migrações e seed npm run dev # Servidor de desenvolvimento ``` -------------------------------- ### GET /api/settings Source: https://context7.com/astraonlineweb/astracampaign/llms.txt Reads global and per-tenant settings. SUPERADMIN can specify a `tenantId` to manage settings for any tenant. ```APIDOC ## GET /api/settings — Read global and per-tenant settings ### Description Read global settings (WAHA, Evolution, QuePasa host/keys, company name, page title) and per-tenant settings (OpenAI key, Groq key, Chatwoot URL/token, Perfex URL/token). SUPERADMIN can pass `?tenantId=` to manage any tenant's AI/integration keys. ### Method GET ### Endpoint /api/settings ### Query Parameters - **tenantId** (string) - Optional - The ID of the tenant whose settings to retrieve. If not provided, retrieves settings for the authenticated user's tenant. ### Request Example ```bash TOKEN="" # Read combined settings curl -s http://localhost:3001/api/settings \ -H "Authorization: Bearer $TOKEN" | jq '{wahaHost, evolutionHost, openaiApiKey, chatwootUrl}' ``` ### Response #### Success Response (200) - **wahaHost** (string) - **evolutionHost** (string) - **openaiApiKey** (string) - **chatwootUrl** (string) - ... (other settings fields) ``` -------------------------------- ### GET /api/backup Source: https://context7.com/astraonlineweb/astracampaign/llms.txt Lists available backup files for a specified tenant. This endpoint is intended for SUPERADMIN users. ```APIDOC ## GET /api/backup — List available backups ### Description List available backups for a tenant (SUPERADMIN only). ### Method GET ### Endpoint /api/backup ### Query Parameters - **tenantId** (string) - Required - The ID of the tenant whose backups to list. ### Request Example ```bash SUPER_TOKEN="" curl -s "http://localhost:3001/api/backup?tenantId=ten_abc" \ -H "Authorization: Bearer $SUPER_TOKEN" | jq '.backups[].fileName' ``` ### Response #### Success Response (200) - **backups** (array) - **fileName** (string) - The name of the backup file. ``` -------------------------------- ### Get Tenant Statistics Source: https://github.com/astraonlineweb/astracampaign/blob/main/backend/docs/MULTI_TENANT_GUIDE.md Retrieve detailed statistics for a specific tenant, including user counts, active campaigns, connected sessions, and quota usage. ```bash GET /api/tenants/tenant-uuid ``` -------------------------------- ### Environment Variables Configuration Source: https://github.com/astraonlineweb/astracampaign/blob/main/README.md Example of essential environment variables to configure in `docker-stack.yml`. These variables control database connections, API keys for integrations, and system branding. ```yaml environment: - DATABASE_URL=postgresql://postgres:postgres@postgres:5432/contacts - JWT_SECRET=sua-chave-secreta-muito-segura - DEFAULT_WAHA_HOST=https://seu-waha.com - DEFAULT_WAHA_API_KEY=sua-waha-api-key - DEFAULT_EVOLUTION_HOST=https://seu-evolution.com - DEFAULT_EVOLUTION_API_KEY=sua-evolution-api-key - DEFAULT_QUEPASA_HOST=https://seu-quepasa.com - DEFAULT_QUEPASA_TOKEN=seu-quepasa-token - DEFAULT_CHATWOOT_URL=https://seu-chatwoot.com - DEFAULT_CHATWOOT_TOKEN=seu-chatwoot-token - DEFAULT_COMPANY_NAME=Sua Empresa - DEFAULT_PAGE_TITLE=Seu Sistema ``` -------------------------------- ### Create Text Campaign with Randomized Content Source: https://context7.com/astraonlineweb/astracampaign/llms.txt This command creates a new WhatsApp campaign with text messages. It supports randomized content from a list of predefined texts and can start immediately. Ensure the specified WhatsApp sessions are active. ```bash TOKEN="" # Text campaign with randomized content, starting immediately curl -s -X POST http://localhost:3001/api/campaigns \ -H "Authorization: Bearer $TOKEN" \ -H "Content-Type: application/json" \ -d '{ "nome": "Promoção Black Friday", "targetTags": ["cat_clientes_uuid", "cat_prospect_uuid"], "sessionNames": ["vendas_c52982e8"], "messageType": "text", "messageContent": { "texts": [ "Olá {{nome}}! Temos uma promoção especial para você!", "Oi {{nome}}, aproveite nossa oferta exclusiva!", "E aí {{nome}}? Promoção imperdível esperando por você!" ] }, "randomDelay": 8000, "startImmediately": true }' | jq '{id: .campaign.id, status: .campaign.status, totalContacts: .campaign.totalContacts}' ``` -------------------------------- ### Create Campaign Source: https://context7.com/astraonlineweb/astracampaign/llms.txt Creates a new WhatsApp campaign. Campaigns can be configured for text or image messages, with options for randomized content, delays, immediate start, or scheduled execution. ```APIDOC ## Create Campaign ### Description Creates and optionally starts a bulk WhatsApp campaign. It validates WhatsApp sessions, fetches contacts based on tags, and creates campaign records. Use `startImmediately` for immediate dispatch or `scheduledFor` for deferred execution. ### Method POST ### Endpoint /api/campaigns ### Parameters #### Request Body - **nome** (string) - Required - The name of the campaign. - **targetTags** (array of strings) - Required - List of category IDs (tags) to target contacts. - **sessionNames** (array of strings) - Required - List of WhatsApp session names to use for sending. - **messageType** (string) - Required - Type of message ('text' or 'image'). - **messageContent** (object) - Required - Content of the message. - **texts** (array of strings) - Required if `messageType` is 'text' - List of text messages to randomize. - **images** (array of strings) - Required if `messageType` is 'image' - List of image paths. - **captions** (array of strings) - Optional - Captions for images. - **randomDelay** (integer) - Optional - Random delay in milliseconds between sending messages. - **startImmediately** (boolean) - Optional - If true, starts the campaign immediately. Defaults to false. - **scheduledFor** (string) - Optional - ISO 8601 formatted date/time for scheduling the campaign. Required if `startImmediately` is false. ### Request Example ```json { "nome": "Promoção Black Friday", "targetTags": ["cat_clientes_uuid", "cat_prospect_uuid"], "sessionNames": ["vendas_c52982e8"], "messageType": "text", "messageContent": { "texts": [ "Olá {{nome}}! Temos uma promoção especial para você!", "Oi {{nome}}, aproveite nossa oferta exclusiva!", "E aí {{nome}}? Promoção imperdível esperando por você!" ] }, "randomDelay": 8000, "startImmediately": true } ``` ### Response #### Success Response (200) - **campaign** (object) - Details of the created campaign. - **id** (string) - The unique identifier for the campaign. - **status** (string) - The current status of the campaign. - **totalContacts** (integer) - The total number of contacts targeted. ``` -------------------------------- ### Publish Interactive Campaign Source: https://context7.com/astraonlineweb/astracampaign/llms.txt Publishes an interactive campaign, initiating its execution immediately or scheduling it for a future date. This transitions the campaign status to `STARTED` or `SCHEDULED` respectively. ```APIDOC ## POST /api/interactive-campaigns/:id/publish ### Description Publishes (starts or schedules) an interactive campaign. Immediately triggers dispatch via `interactiveCampaignDispatchService` (async, non-blocking) when no `scheduledDate` is provided. Transitions status to `STARTED` (immediate) or `SCHEDULED` (deferred). ### Method POST ### Endpoint /api/interactive-campaigns/:id/publish ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the campaign to publish. #### Request Body - **scheduledDate** (string) - Optional - The date and time to schedule the campaign for, in ISO 8601 format (e.g., `2024-12-25T09:00:00.000Z`). If omitted, the campaign is published immediately. ### Request Example ```bash # Publish immediately curl -s -X POST http://localhost:3001/api/interactive-campaigns/ic_abc/publish \ -H "Authorization: Bearer " \ -H "Content-Type: application/json" \ -d '{}' # Schedule for a future date curl -s -X POST http://localhost:3001/api/interactive-campaigns/ic_abc/publish \ -H "Authorization: Bearer " \ -H "Content-Type: application/json" \ -d '{"scheduledDate": "2024-12-25T09:00:00.000Z"}' ``` ### Response #### Success Response (200) - **status** (string) - The updated status of the campaign (`STARTED` or `SCHEDULED`). ``` -------------------------------- ### Publish Interactive Campaign Source: https://context7.com/astraonlineweb/astracampaign/llms.txt Publishes an interactive campaign, either immediately or scheduled for a future date. Requires the campaign ID and a user JWT. Transitions the campaign status to STARTED or SCHEDULED. ```bash TOKEN="" CAMP_ID="ic_abc" # Publish immediately curl -s -X POST http://localhost:3001/api/interactive-campaigns/$CAMP_ID/publish \ -H "Authorization: Bearer $TOKEN" \ -H "Content-Type: application/json" \ -d '{}' | jq .status # "STARTED" ``` ```bash TOKEN="" CAMP_ID="ic_abc" # Schedule for a future date curl -s -X POST http://localhost:3001/api/interactive-campaigns/$CAMP_ID/publish \ -H "Authorization: Bearer $TOKEN" \ -H "Content-Type: application/json" \ -d '{"scheduledDate": "2024-12-25T09:00:00.000Z"}' | jq .status # "SCHEDULED" ``` -------------------------------- ### Get Tenant Analytics Report Source: https://context7.com/astraonlineweb/astracampaign/llms.txt Retrieve campaign performance, contact stats, session activity, and usage for a tenant. Supports optional date range filters. Available to ADMIN and USER roles. ```bash TOKEN="" # All-time analytics curl -s http://localhost:3001/api/analytics/tenant \ -H "Authorization: Bearer $TOKEN" | jq .data ``` ```bash # Filtered by date range curl -s "http://localhost:3001/api/analytics/tenant?startDate=2024-11-01&endDate=2024-11-30" \ -H "Authorization: Bearer $TOKEN" | jq '.data.campaigns.totalSent' ``` ```bash # SUPERADMIN: system-wide analytics across all tenants SUPER_TOKEN="" curl -s http://localhost:3001/api/analytics/system \ -H "Authorization: Bearer $SUPER_TOKEN" | jq '.data.totalTenants' ``` -------------------------------- ### Create Tenant with Quotas and Admin User Source: https://context7.com/astraonlineweb/astracampaign/llms.txt Atomically creates a new tenant, its admin user, user-tenant association, quota record, and settings record. Auto-generates a unique URL slug. ```bash SUPER_TOKEN="" curl -s -X POST http://localhost:3001/api/tenants \ -H "Authorization: Bearer $SUPER_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "name": "Loja Nova LTDA", "adminUser": { "nome": "Gestor Loja", "email": "gestor@loja.com", "senha": "Senha123" }, "quotas": { "maxUsers": 20, "maxContacts": 5000, "maxCampaigns": 100, "maxConnections": 10 }, "allowedProviders": ["WAHA", "EVOLUTION"] }' | jq ``` -------------------------------- ### Get Tenant Statistics Source: https://github.com/astraonlineweb/astracampaign/blob/main/backend/docs/MULTI_TENANT_GUIDE.md Retrieves detailed statistics for a specific tenant. ```APIDOC ## GET /api/tenants/{tenant_uuid} ### Description Fetches detailed statistics for a given tenant, including user counts, active campaigns, and resource usage. ### Method GET ### Endpoint /api/tenants/{tenant_uuid} ### Parameters #### Path Parameters - **tenant_uuid** (string) - Required - The unique identifier of the tenant. ### Response #### Success Response (200) - **userCount** (integer) - Number of users in the tenant. - **contactCount** (integer) - Number of contacts in the tenant. - **activeCampaigns** (integer) - Number of active campaigns. - **connectedWhatsAppSessions** (integer) - Number of connected WhatsApp sessions. - **usageVsQuotas** (object) - Information about resource usage versus configured quotas. ``` -------------------------------- ### GET /api/chatwoot/tags Source: https://context7.com/astraonlineweb/astracampaign/llms.txt Retrieves a list of available tags from the configured Chatwoot instance. ```APIDOC ## GET /api/chatwoot/tags — Get Chatwoot tags ### Description Fetches available tags from the configured Chatwoot instance. ### Method GET ### Endpoint /api/chatwoot/tags ### Request Example ```bash TOKEN="" curl -s http://localhost:3001/api/chatwoot/tags \ -H "Authorization: Bearer $TOKEN" | jq '.tags' ``` ### Response #### Success Response (200) - **tags** (array) - A list of available tags from Chatwoot. ``` -------------------------------- ### Create WhatsApp Session (Tenant-Associated) Source: https://github.com/astraonlineweb/astracampaign/blob/main/backend/docs/MULTI_TENANT_GUIDE.md Use this endpoint to create a new WhatsApp session. Sessions are associated with the authenticated user's tenant. ```bash POST /api/waha/sessions { "name": "sessao-vendas", "provider": "EVOLUTION" } ``` -------------------------------- ### Create Campaign (Tenant-Isolated) Source: https://github.com/astraonlineweb/astracampaign/blob/main/backend/docs/MULTI_TENANT_GUIDE.md Use this endpoint to create a new campaign. Campaigns are isolated per tenant, and this endpoint ensures proper association. ```bash POST /api/campaigns { "nome": "Campanha Black Friday", "targetTags": "cliente,premium", "messageContent": "Oferta especial só hoje!", "sessionName": "sessao-principal" } ``` -------------------------------- ### Contribute to the Project Source: https://github.com/astraonlineweb/astracampaign/blob/main/README.md Steps for contributing to the open-source project, including forking, creating branches, committing changes, and opening pull requests. ```bash # 1. Fork o repositório # 2. Crie uma branch para sua feature (`git checkout -b feature/nova-feature`) # 3. Commit suas mudanças (`git commit -m 'Adiciona nova feature'`) # 4. Push para a branch (`git push origin feature/nova-feature`) # 5. Abra um Pull Request ``` -------------------------------- ### Verify Docker Services Source: https://github.com/astraonlineweb/astracampaign/blob/main/README.md After deployment, use these commands to list running services and view logs for the backend service to ensure everything is operational. ```bash docker service ls docker service logs -f work_backend ``` -------------------------------- ### GET /api/contatos Source: https://context7.com/astraonlineweb/astracampaign/llms.txt Retrieves a paginated list of contacts for the authenticated tenant, with support for search and category filtering. ```APIDOC ## GET /api/contatos — List contacts with pagination, search, and category filter ### Description Returns paginated contact records scoped to the authenticated tenant. Supports full-text search on name/phone and filtering by category ID. ### Method GET ### Endpoint /api/contatos ### Parameters #### Query Parameters - **page** (integer) - Required - The page number for pagination. - **pageSize** (integer) - Required - The number of contacts per page. - **search** (string) - Optional - Full-text search query for name or phone. - **tag** (string) - Optional - Filter contacts by category ID. ### Request Example ```bash TOKEN="" # List first 30 contacts curl -s "http://localhost:3001/api/contatos?page=1&pageSize=30" \ -H "Authorization: Bearer $TOKEN" | jq '{total: .total, count: (.contacts | length)}' # Search by name with category filter curl -s "http://localhost:3001/api/contatos?search=João&tag=cat_vip&page=1&pageSize=10" \ -H "Authorization: Bearer $TOKEN" | jq '.contacts[].nome' ``` ### Response #### Success Response (200) - **total** (integer) - The total number of contacts available. - **contacts** (array) - An array of contact objects. - **id** (string) - Unique identifier for the contact. - **nome** (string) - Name of the contact. - **telefone** (string) - Phone number of the contact. - **email** (string) - Email address of the contact. - **categoriaId** (string) - The ID of the contact's category. - **tenantId** (string) - The ID of the tenant the contact belongs to. - **criadoEm** (string) - Timestamp when the contact was created. - *Other fields may be present. ### Response Example ```json { "total": 150, "contacts": [ { "id": "cnt_xyz", "nome": "João Silva", "telefone": "+5511999999999", "email": "joao@email.com", "categoriaId": "cat_vip_uuid", "tenantId": "ten_abc", "criadoEm": "2024-12-01T12:00:00.000Z" } // ... more contacts ] } ``` ``` -------------------------------- ### GET /api/auth/profile Source: https://context7.com/astraonlineweb/astracampaign/llms.txt Retrieves the profile information of the currently authenticated user, including their associated tenant details. ```APIDOC ## GET /api/auth/profile ### Description Gets the authenticated user's profile. Returns the user object plus their associated tenant data. ### Method GET ### Endpoint `/api/auth/profile` ### Parameters #### Headers - **Authorization** (string) - Required - Bearer token for authentication. ### Response #### Success Response (200) - **success** (boolean) - Indicates if the profile retrieval was successful. - **data** (object) - Contains user and tenant information. - **user** (object) - User details. - **id** (string) - User's unique identifier. - **nome** (string) - User's full name. - **email** (string) - User's email address. - **role** (string) - User's role. - **ativo** (boolean) - Indicates if the user account is active. - **tenant** (object) - Tenant details associated with the user. - **id** (string) - Tenant's unique identifier. - **slug** (string) - Tenant's slug. - **name** (string) - Tenant's name. - **active** (boolean) - Indicates if the tenant is active. ``` -------------------------------- ### Build Docker Images for Backend and Frontend Source: https://github.com/astraonlineweb/astracampaign/blob/main/README.md Builds Docker images for the backend and frontend. Optionally, tags and pushes the backend image to a registry. Ensure you are in the correct directories before running. ```bash # Backend cd backend docker build --no-cache -t work-backend:latest . # Frontend cd frontend npm run build docker build -t work-frontend:latest . # Push para registry (opcional) docker tag work-backend:latest seu-registry/work-backend:latest docker push seu-registry/work-backend:latest ``` -------------------------------- ### Create Contact (Auto-associated with User Tenant) Source: https://github.com/astraonlineweb/astracampaign/blob/main/backend/docs/MULTI_TENANT_GUIDE.md Use this endpoint to create a new contact. The contact will be automatically associated with the tenant of the authenticated user. ```bash POST /api/contatos { "nome": "Cliente Exemplo", "telefone": "11999999999", "email": "cliente@exemplo.com", "tags": ["cliente", "premium"] } ``` -------------------------------- ### GET /api/analytics/export/:type Source: https://context7.com/astraonlineweb/astracampaign/llms.txt Exports tenant data as a CSV file. Supports exporting `contacts`, `campaigns`, or `analytics` data for the authenticated tenant. ```APIDOC ## GET /api/analytics/export/:type — Export tenant data as CSV ### Description Exports `contacts`, `campaigns`, or `analytics` data for the authenticated tenant as a downloadable CSV file. ### Method GET ### Endpoint /api/analytics/export/:type ### Path Parameters - **type** (string) - Required - The type of data to export. Accepted values: `contacts`, `campaigns`, `analytics`. ### Request Example ```bash TOKEN="" # Export all contacts as CSV curl -s "http://localhost:3001/api/analytics/export/contacts" \ -H "Authorization: Bearer $TOKEN" \ -o contacts-export.csv # Export campaign data curl -s "http://localhost:3001/api/analytics/export/campaigns" \ -H "Authorization: Bearer $TOKEN" \ -o campaigns-export.csv # Export analytics summary curl -s "http://localhost:3001/api/analytics/export/analytics" \ -H "Authorization: Bearer $TOKEN" \ -o analytics-export.csv ``` ``` -------------------------------- ### Verify Users by Tenant Source: https://github.com/astraonlineweb/astracampaign/blob/main/backend/docs/MULTI_TENANT_GUIDE.md SQL query to list users along with their email, role, and the name of the tenant they belong to. Joins users table with tenants table on tenant_id. ```sql -- Verificar usuários por tenant SELECT u.nome, u.email, u.role, t.name as tenant_name FROM users u LEFT JOIN tenants t ON u.tenant_id = t.id; ``` -------------------------------- ### Read and Update System Settings Source: https://context7.com/astraonlineweb/astracampaign/llms.txt Manage global and per-tenant settings, including AI keys and integration credentials. SUPERADMIN can manage any tenant's settings using the `?tenantId=` query parameter. Use multipart form data for logo uploads. ```bash TOKEN="" # Read combined settings curl -s http://localhost:3001/api/settings \ -H "Authorization: Bearer $TOKEN" | jq '{wahaHost, evolutionHost, openaiApiKey, chatwootUrl}' ``` ```bash # Update tenant AI keys and Chatwoot integration curl -s -X PUT http://localhost:3001/api/settings \ -H "Authorization: Bearer $TOKEN" \ -H "Content-Type: application/json" \ -d '{ "openaiApiKey": "sk-proj-xxxxxxxxxxxxxxxxxxxx", "groqApiKey": "gsk_xxxxxxxxxxxxxxxxxx", "chatwootUrl": "https://app.chatwoot.com", "chatwootAccountId": "42", "chatwootApiToken": "xxxxxxxxxxxxxxxxxxxxxx", "perfexUrl": "https://crm.empresa.com", "perfexToken": "your_perfex_api_token" }' | jq .message ``` ```bash # Upload white-label logo (multipart) curl -s -X POST http://localhost:3001/api/settings/logo \ -H "Authorization: Bearer $TOKEN" \ -F "logo=@./company-logo.png" | jq '{message: .message, logoUrl: .logoUrl}' ``` -------------------------------- ### Verify Users by Tenant Source: https://github.com/astraonlineweb/astracampaign/blob/main/backend/docs/MULTI_TENANT_GUIDE.md SQL query to list users and their associated tenant names. ```APIDOC ```sql -- Verificar usuários por tenant SELECT u.nome, u.email, u.role, t.name as tenant_name FROM users u LEFT JOIN tenants t ON u.tenant_id = t.id; ``` ``` -------------------------------- ### Get Campaign Report Source: https://context7.com/astraonlineweb/astracampaign/llms.txt Retrieves a detailed report for a specific campaign, including statistics, message statuses, and session breakdowns. Supports downloading the report in XLSX format. ```APIDOC ## Get Campaign Report ### Description Provides a detailed report for a campaign, including overall statistics, per-message statuses, and a breakdown by sending session. The report can also be downloaded in XLSX format. ### Method GET ### Endpoint /api/campaigns/:id/report ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier of the campaign. ### Response #### Success Response (200) - **stats** (object) - Summary statistics for the campaign. - **total** (integer) - Total contacts targeted. - **sent** (integer) - Total messages sent. - **failed** (integer) - Total messages failed. - **pending** (integer) - Total messages pending. - **sessionSummary** (array of strings) - Summary of messages sent per session. - **generatedAt** (string) - Timestamp when the report was generated. ## Download Campaign Report (XLSX) ### Description Downloads the campaign report in XLSX format. ### Method GET ### Endpoint /api/campaigns/:id/report/download ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier of the campaign. ### Response #### Success Response (200) - Returns an XLSX file containing the campaign report. ``` -------------------------------- ### Create Evolution API Session with Webhook Source: https://context7.com/astraonlineweb/astracampaign/llms.txt Creates a WhatsApp session using the Evolution API provider and enables interactive campaign webhooks. The response includes the session name and status. ```bash TOKEN="" # Create an Evolution API session with interactive campaign webhook curl -s -X POST http://localhost:3001/api/waha/sessions \ -H "Authorization: Bearer $TOKEN" \ -H "Content-Type: application/json" \ -d '{ "name": "suporte", "provider": "EVOLUTION", "interactiveCampaignEnabled": true }' | jq '{name: .name, status: .status}' ``` -------------------------------- ### Get Authenticated User Profile - API Source: https://context7.com/astraonlineweb/astracampaign/llms.txt Retrieves the profile of the currently authenticated user, including their associated tenant details. Requires a valid JWT in the Authorization header. ```bash TOKEN="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." curl -s http://localhost:3001/api/auth/profile \ -H "Authorization: Bearer $TOKEN" | jq # Expected response { "success": true, "data": { "user": { "id": "...", "nome": "Admin Empresa", "email": "admin@empresa.com", "role": "ADMIN", "ativo": true }, "tenant": { "id": "ten_xyz", "slug": "empresa", "name": "Empresa LTDA", "active": true } } } ``` -------------------------------- ### Download and Import Contact Template Source: https://context7.com/astraonlineweb/astracampaign/llms.txt Use these commands to download a contact template CSV, edit it, and then import it into the system. The import process returns a JSON response indicating the success or failure of the import. ```bash curl -s http://localhost:3001/api/contatos/template \ -H "Authorization: Bearer $TOKEN" \ -o template-contatos.csv ``` ```bash # template-contatos.csv columns: nome,telefone,email,observacoes,categoriaId # Edit the template, then import curl -s -X POST http://localhost:3001/api/contatos/import \ -H "Authorization: Bearer $TOKEN" \ -F "file=@./template-contatos.csv" | jq ``` ```json # Expected response (HTTP 200 on full success, 207 on partial) { "message": "Importação concluída com sucesso", "success": true, "imported": 42, "skipped": 3, "errors": [ { "row": 5, "error": "Telefone inválido: 123" } ] } ``` -------------------------------- ### Environment Variables for Backend Configuration Source: https://github.com/astraonlineweb/astracampaign/blob/main/README.md Sets up essential environment variables for database connections, JWT secrets, Redis, and WhatsApp provider configurations. Ensure these are securely managed. ```env # Backend (.env) DATABASE_URL=postgresql://user:pass@host:5432/db REDIS_URL=redis://redis:6379 JWT_SECRET=sua-chave-secreta-muito-segura JWT_EXPIRES_IN=24h # Provedores WhatsApp DEFAULT_WAHA_HOST=http://waha:3000 DEFAULT_WAHA_API_KEY=sua-waha-api-key DEFAULT_EVOLUTION_HOST=http://evolution:8080 DEFAULT_EVOLUTION_API_KEY=sua-evolution-api-key DEFAULT_QUEPASA_HOST=http://quepasa:31000 DEFAULT_QUEPASA_TOKEN=seu-quepasa-token # Integração Chatwoot DEFAULT_CHATWOOT_URL=https://seu-chatwoot.com DEFAULT_CHATWOOT_TOKEN=seu-chatwoot-token # Configurações Gerais DEFAULT_COMPANY_NAME=Astra Campaign DEFAULT_PAGE_TITLE=Sistema de Gestão de Contatos ``` -------------------------------- ### POST /api/tenants Source: https://context7.com/astraonlineweb/astracampaign/llms.txt Creates a new tenant with associated admin user, quota, and settings. It atomically generates a unique URL slug. ```APIDOC ## POST /api/tenants — Create a new tenant with quota and admin user ### Description Creates the tenant, its admin user, a `UserTenant` association, a `TenantQuota` record, and a `TenantSettings` record atomically inside a Prisma transaction. Auto-generates a unique URL slug. ### Method POST ### Endpoint /api/tenants ### Request Body - **name** (string) - Required - The name of the tenant. - **adminUser** (object) - Required - Details for the admin user. - **nome** (string) - Required - Name of the admin user. - **email** (string) - Required - Email of the admin user. - **senha** (string) - Required - Password for the admin user. - **quotas** (object) - Required - Quota limits for the tenant. - **maxUsers** (integer) - Optional - Maximum number of users. - **maxContacts** (integer) - Optional - Maximum number of contacts. - **maxCampaigns** (integer) - Optional - Maximum number of campaigns. - **maxConnections** (integer) - Optional - Maximum number of connections. - **allowedProviders** (array) - Required - List of allowed providers (e.g., ["WAHA", "EVOLUTION"]). ### Request Example ```json { "name": "Loja Nova LTDA", "adminUser": { "nome": "Gestor Loja", "email": "gestor@loja.com", "senha": "Senha123" }, "quotas": { "maxUsers": 20, "maxContacts": 5000, "maxCampaigns": 100, "maxConnections": 10 }, "allowedProviders": ["WAHA", "EVOLUTION"] } ``` ### Response #### Success Response (200) - **success** (boolean) - Indicates if the operation was successful. - **message** (string) - Confirmation message. - **tenant** (object) - Details of the created tenant. - **id** (string) - Unique identifier for the tenant. - **slug** (string) - URL-friendly identifier for the tenant. - **name** (string) - Name of the tenant. - **active** (boolean) - Activation status of the tenant. - **adminUser** (object) - Details of the created admin user. - **id** (string) - Unique identifier for the admin user. - **nome** (string) - Name of the admin user. - **email** (string) - Email of the admin user. - **role** (string) - Role of the user (e.g., "ADMIN"). ### Response Example ```json { "success": true, "message": "Tenant criado com sucesso", "tenant": { "id": "ten_abc", "slug": "loja-nova-ltda", "name": "Loja Nova LTDA", "active": true }, "adminUser": { "id": "usr_111", "nome": "Gestor Loja", "email": "gestor@loja.com", "role": "ADMIN" } } ``` ``` -------------------------------- ### Get Detailed Campaign Report Source: https://context7.com/astraonlineweb/astracampaign/llms.txt This command retrieves a detailed report for a specific campaign, including statistics, session summaries, and generation timestamp. The report can be used for analysis and monitoring. ```bash TOKEN="" CAMPAIGN_ID="camp_abc" curl -s http://localhost:3001/api/campaigns/$CAMPAIGN_ID/report \ -H "Authorization: Bearer $TOKEN" | jq '{ stats: .stats, sessionSummary: (.messagesBySession | keys), generatedAt: .generatedAt }' ``` ```json # Expected shape { "stats": { "total": 500, "sent": 487, "failed": 8, "pending": 5 }, "sessionSummary": ["vendas_c52982e8 (WAHA)", "suporte_c52982e8 (EVOLUTION)"], "generatedAt": "2024-12-01T15:30:00.000Z" } ``` -------------------------------- ### Production Docker Swarm Deployment for Astra Campaign Source: https://context7.com/astraonlineweb/astracampaign/llms.txt Provides commands for cloning the Astra Campaign repository, configuring the Docker Swarm deployment file, deploying the stack, and checking service status and logs. ```bash # Clone and configure git clone https://github.com/AstraOnlineWeb/astracampaign.git cd astracampaign nano docker-stack.yml # Set your DATABASE_URL, JWT_SECRET, provider hosts/keys, APP_URL # Deploy to Docker Swarm docker stack deploy -c docker-stack.yml astra # Check services docker service ls # NAME MODE REPLICAS IMAGE # astra_backend 1/1 replicated backend:latest # astra_frontend 1/1 replicated frontend:latest # astra_postgres 1/1 replicated postgres:16 # astra_redis 1/1 replicated redis:7 # View logs docker service logs -f astra_backend # Health check curl http://localhost:3001/api/health # Default credentials after first boot # SUPERADMIN: superadmin@astraonline.com.br / Admin123 # ADMIN: admin@astraonline.com.br / Admin123 ``` -------------------------------- ### Create Campaign Source: https://github.com/astraonlineweb/astracampaign/blob/main/backend/docs/MULTI_TENANT_GUIDE.md Creates a new campaign, isolated per tenant. ```APIDOC ## POST /api/campaigns ### Description Creates a new campaign that is isolated to the current tenant. ### Method POST ### Endpoint /api/campaigns ### Request Body - **nome** (string) - Required - The name of the campaign. - **targetTags** (string) - Optional - Comma-separated tags to target for the campaign. - **messageContent** (string) - Required - The content of the message for the campaign. - **sessionName** (string) - Required - The name of the WhatsApp session to use. ### Request Example ```json { "nome": "Campanha Black Friday", "targetTags": "cliente,premium", "messageContent": "Oferta especial só hoje!", "sessionName": "sessao-principal" } ``` ``` -------------------------------- ### Restore Tenant Backup Source: https://context7.com/astraonlineweb/astracampaign/llms.txt Restore a tenant's data from a specific backup file. This operation is available only to SUPERADMIN users. Use the GET /api/backup endpoint to list available backup files. ```bash SUPER_TOKEN="" # List available backups for a tenant curl -s "http://localhost:3001/api/backup?tenantId=ten_abc" \ -H "Authorization: Bearer $SUPER_TOKEN" | jq '.backups[].fileName' ``` ```bash # Restore from a specific backup file curl -s -X POST http://localhost:3001/api/backup/restore \ -H "Authorization: Bearer $SUPER_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "tenantId": "ten_abc", "backupFileName": "backup_ten_abc_2024-12-01T02-00-00.tar.gz" }' | jq .message ``` -------------------------------- ### Trigger Manual Backup Source: https://context7.com/astraonlineweb/astracampaign/llms.txt Initiate a manual backup for a tenant. ADMIN users back up their own tenant. SUPERADMIN can back up a specific tenant or all tenants using 'all: true'. ```bash TOKEN="" SUPER_TOKEN="" # Tenant admin: backup own data curl -s -X POST http://localhost:3001/api/backup \ -H "Authorization: Bearer $TOKEN" \ -H "Content-Type: application/json" \ -d '{}' | jq '.success, .backup.fileName' ``` ```bash # SUPERADMIN: backup all tenants at once curl -s -X POST http://localhost:3001/api/backup \ -H "Authorization: Bearer $SUPER_TOKEN" \ -H "Content-Type: application/json" \ -d '{"all": true}' | jq '{message: .message, results: [.results[] | {tenant: .tenantId, status: .status}]}' ``` ```bash # Configure automated daily backup schedule (SUPERADMIN only) curl -s -X POST http://localhost:3001/api/backup/schedule \ -H "Authorization: Bearer $SUPER_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "tenantId": "ten_abc", "enabled": true, "schedule": "0 2 * * *", "retentionDays": 30, "storageType": "local" }' | jq .message ``` -------------------------------- ### GET /api/waha/sessions/:sessionName/auth/qr Source: https://context7.com/astraonlineweb/astracampaign/llms.txt Retrieves a base64-encoded PNG QR code for scanning with the WhatsApp mobile app. This QR code expires in 5 minutes and is compatible with WAHA, Evolution, and QuePasa providers. ```APIDOC ### `GET /api/waha/sessions/:sessionName/auth/qr` — Get the QR code for a session Returns a base64-encoded PNG QR code (expires in 5 minutes) for scanning with the WhatsApp mobile app. Works for WAHA, Evolution, and QuePasa providers. ```bash TOKEN="" SESSION="vendas_c52982e8" curl -s http://localhost:3001/api/waha/sessions/$SESSION/auth/qr \ -H "Authorization: Bearer $TOKEN" | jq '{status: .status, expiresAt: .expiresAt}' # Expected response { "qr": "data:image/png;base64,iVBORw0KGgo...", "expiresAt": "2024-12-01T12:05:00.000Z", "status": "SCAN_QR_CODE", "provider": "WAHA", "message": "QR code obtido da WAHA API e convertido para base64" } ``` ``` -------------------------------- ### View Backend Service Logs Source: https://github.com/astraonlineweb/astracampaign/blob/main/backend/docs/MULTI_TENANT_GUIDE.md Command to view the logs for the backend service, useful for troubleshooting. ```bash docker service logs work_backend ``` -------------------------------- ### Register New User - API Source: https://context7.com/astraonlineweb/astracampaign/llms.txt Creates a new user account. Non-SUPERADMIN users can only create users within their own tenant. SUPERADMIN can create users in any tenant or other SUPERADMIN accounts. ```bash TOKEN="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." curl -s -X POST http://localhost:3001/api/auth/register \ -H "Authorization: Bearer $TOKEN" \ -H "Content-Type: application/json" \ -d '{ "nome": "Maria Operadora", "email": "maria@empresa.com", "senha": "Senha123", "role": "USER" }' | jq # Expected response { "success": true, "message": "Usuário criado com sucesso", "data": { "user": { "id": "clx9z8y7x6w5v4", "nome": "Maria Operadora", "email": "maria@empresa.com", "role": "USER", "ativo": true, "criadoEm": "2024-12-01T11:00:00.000Z" } } } ``` -------------------------------- ### Execute Flow with Graph and Context Source: https://context7.com/astraonlineweb/astracampaign/llms.txt Executes a defined flow graph starting from a trigger node, evaluating conditions and dispatching actions. Integrates with external services and returns a full execution trace. Loop detection is enforced. ```typescript import { flowEngineService } from './services/flowEngineService'; const graph = { nodes: [ { id: 'trig', type: 'trigger', data: { keywords: ['sim', 'yes'] } }, { id: 'cond', type: 'condition', data: { conditionType: 'contains', value: 'sim' } }, { id: 'act', type: 'action', data: { actionType: 'sendMessage', messageContent: 'Obrigado pela confirmação!' } }, { id: 'stop', type: 'stop', data: {} } ], edges: [ { id: 'e1', source: 'trig', target: 'cond' }, { id: 'e2', source: 'cond', target: 'act', sourceHandle: 'true' }, { id: 'e3', source: 'act', target: 'stop' } ] }; const context = { from: '+5511999999999', to: 'bot', content: 'sim', type: 'text', timestamp: new Date(), tenantId: 'ten_abc', phonenumber: '+5511999999999' }; const result = await flowEngineService.executeFlow(graph, context); console.log(result); ``` -------------------------------- ### POST /api/backup Source: https://context7.com/astraonlineweb/astracampaign/llms.txt Triggers a manual backup for the authenticated tenant. SUPERADMIN users can back up a specific tenant or all tenants. ```APIDOC ## POST /api/backup — Trigger a manual backup ### Description ADMIN users back up their own tenant. SUPERADMIN can back up a specific tenant (`tenantId` in body) or all tenants at once (`all: true`). ### Method POST ### Endpoint /api/backup ### Request Body - **all** (boolean) - Optional - If true, backs up all tenants. Requires SUPERADMIN role. - **tenantId** (string) - Optional - The ID of the tenant to back up. Required for SUPERADMIN if `all` is not true. ### Request Example ```bash TOKEN="" SUPER_TOKEN="" # Tenant admin: backup own data curl -s -X POST http://localhost:3001/api/backup \ -H "Authorization: Bearer $TOKEN" \ -H "Content-Type: application/json" \ -d '{}' | jq '.success, .backup.fileName' # SUPERADMIN: backup all tenants at once curl -s -X POST http://localhost:3001/api/backup \ -H "Authorization: Bearer $SUPER_TOKEN" \ -H "Content-Type: application/json" \ -d '{"all": true}' | jq '{message: .message, results: [.results[] | {tenant: .tenantId, status: .status}]}' # SUPERADMIN: backup a specific tenant curl -s -X POST http://localhost:3001/api/backup \ -H "Authorization: Bearer $SUPER_TOKEN" \ -H "Content-Type: application/json" \ -d '{"tenantId": "ten_abc"}' | jq '.success, .backup.fileName' ``` ### Response #### Success Response (200) - **success** (boolean) - **backup** (object) - **fileName** (string) ``` -------------------------------- ### Get QR Code for WhatsApp Session Source: https://context7.com/astraonlineweb/astracampaign/llms.txt Retrieves the base64-encoded QR code for a WhatsApp session, used for scanning with the WhatsApp mobile app. The QR code expires in 5 minutes. Works for WAHA, Evolution, and QuePasa providers. ```bash TOKEN="" SESSION="vendas_c52982e8" curl -s http://localhost:3001/api/waha/sessions/$SESSION/auth/qr \ -H "Authorization: Bearer $TOKEN" | jq '{status: .status, expiresAt: .expiresAt}' ```