Files
bakery-ia/docs/whatsapp/implementation-summary.md
2025-12-05 20:07:01 +01:00

11 KiB
Raw Permalink Blame History

WhatsApp Shared Account Implementation - Summary

What Was Implemented

A simplified WhatsApp notification system using a shared master account model, perfect for your 10-bakery pilot program. This eliminates the need for non-technical bakery owners to configure Meta credentials.


Key Changes Made

Backend Changes

  1. Tenant Settings Model - Removed per-tenant credentials, added display phone number

  2. Notification Service - Always uses shared master credentials with tenant-specific phone numbers

  3. Phone Number Management API - New admin endpoints for assigning phone numbers

Frontend Changes

  1. Simplified Settings UI - Removed credential inputs, shows assigned phone number only

  2. Admin Interface - New page for assigning phone numbers to tenants

Documentation

  1. Comprehensive Guides

Quick Start (For You - Platform Admin)

Step 1: Set Up Master WhatsApp Account (One-Time)

Follow the detailed guide: WHATSAPP_MASTER_ACCOUNT_SETUP.md

Summary:

  1. Create Meta Business Account
  2. Add WhatsApp product
  3. Verify business (1-3 days wait)
  4. Add 10 phone numbers
  5. Create message templates
  6. Get credentials (WABA ID, Access Token, Phone Number IDs)

Time: 2-3 hours + verification wait

Step 2: Configure Environment Variables

Edit services/notification/.env:

WHATSAPP_BUSINESS_ACCOUNT_ID=your-waba-id-here
WHATSAPP_ACCESS_TOKEN=your-access-token-here
WHATSAPP_PHONE_NUMBER_ID=default-phone-id-here
WHATSAPP_API_VERSION=v18.0
ENABLE_WHATSAPP_NOTIFICATIONS=true
WHATSAPP_WEBHOOK_VERIFY_TOKEN=your-secret-token-here

Step 3: Restart Services

docker-compose restart notification-service tenant-service

Step 4: Assign Phone Numbers to Bakeries

Option A: Via Admin UI (Recommended)

  1. Open: http://localhost:5173/app/admin/whatsapp
  2. For each bakery:
    • Select phone number from dropdown
    • Click assign

Option B: Via API

curl -X POST http://localhost:8001/api/v1/admin/whatsapp/tenants/{tenant_id}/assign-phone \
  -H "Content-Type: application/json" \
  -d '{
    "phone_number_id": "123456789012345",
    "display_phone_number": "+34 612 345 678"
  }'

Step 5: Test

  1. Login as a bakery owner
  2. Go to Settings → Notifications
  3. Toggle WhatsApp ON
  4. Verify phone number is displayed
  5. Create a test purchase order
  6. Supplier should receive WhatsApp message!

For Bakery Owners (What They Need to Do)

Before:

Navigate Meta Business Suite Create WhatsApp Business Account Get 3 different credential IDs Copy/paste into settings Time: 1-2 hours, high error rate

After:

Go to Settings → Notifications Toggle WhatsApp ON Done! Time: 30 seconds

No configuration needed - phone number is already assigned by you (admin)!


Architecture Overview

┌─────────────────────────────────────────────┐
│   Master WhatsApp Business Account          │
│   - Admin manages centrally                 │
│   - Single set of credentials               │
│   - 10 phone numbers (one per bakery)       │
└─────────────────────────────────────────────┘
                      │
        ┌─────────────┼─────────────┐
        │             │             │
   Phone #1       Phone #2      Phone #3
    +34 612       +34 612       +34 612
    345 678       345 679       345 680
        │             │             │
   Bakery A       Bakery B      Bakery C

API Endpoints Created

Admin Endpoints (New)

Method Endpoint Description
GET /api/v1/admin/whatsapp/phone-numbers List available phone numbers
GET /api/v1/admin/whatsapp/tenants List tenants with WhatsApp status
POST /api/v1/admin/whatsapp/tenants/{id}/assign-phone Assign phone to tenant
DELETE /api/v1/admin/whatsapp/tenants/{id}/unassign-phone Unassign phone from tenant

Test Commands

# View available phone numbers
curl http://localhost:8001/api/v1/admin/whatsapp/phone-numbers | jq

# View tenant WhatsApp status
curl http://localhost:8001/api/v1/admin/whatsapp/tenants | jq

# Assign phone to tenant
curl -X POST http://localhost:8001/api/v1/admin/whatsapp/tenants/{tenant_id}/assign-phone \
  -H "Content-Type: application/json" \
  -d '{"phone_number_id": "XXX", "display_phone_number": "+34 612 345 678"}'

Database Changes

Tenant Settings Schema

Before:

{
  "notification_settings": {
    "whatsapp_enabled": false,
    "whatsapp_phone_number_id": "",
    "whatsapp_access_token": "",           // REMOVED
    "whatsapp_business_account_id": "",    // REMOVED
    "whatsapp_api_version": "v18.0",       // REMOVED
    "whatsapp_default_language": "es"
  }
}

After:

{
  "notification_settings": {
    "whatsapp_enabled": false,
    "whatsapp_phone_number_id": "",            // Phone from shared account
    "whatsapp_display_phone_number": "",       // NEW: Display format
    "whatsapp_default_language": "es"
  }
}

Migration: No SQL migration needed (JSONB is schema-less). Existing data will work with defaults.


Cost Estimate

WhatsApp Messaging Costs (Spain)

  • Per conversation: €0.0319 - €0.0699
  • Conversation window: 24 hours
  • User-initiated: Free

Monthly Estimate (10 Bakeries)

5 POs per bakery per day × 10 bakeries × 30 days = 1,500 messages/month
1,500 × €0.05 (avg) = €75/month

Setup Cost Savings

Old Model (Per-Tenant):

  • 10 bakeries × 1.5 hours × €50/hr = €750 in setup time

New Model (Shared Account):

  • Admin: 2 hours setup (one time)
  • Per bakery: 5 minutes × 10 = €0 in bakery time

Savings: €750 in bakery owner time + reduced support tickets


Monitoring & Maintenance

Check Quality Rating (Weekly)

curl -X GET "https://graph.facebook.com/v18.0/{PHONE_NUMBER_ID}" \
  -H "Authorization: Bearer {ACCESS_TOKEN}" \
  | jq '.quality_rating'

Quality Ratings:

  • GREEN - All good
  • YELLOW ⚠️ - Review messaging patterns
  • RED - Fix immediately

View Message Logs

# Docker logs
docker logs -f notification-service | grep whatsapp

# Database query
SELECT tenant_id, recipient_phone, status, created_at, error_message
FROM whatsapp_messages
WHERE created_at > NOW() - INTERVAL '24 hours'
ORDER BY created_at DESC;

Rotate Access Token (Every 60 Days)

  1. Generate new token in Meta Business Manager
  2. Update WHATSAPP_ACCESS_TOKEN in .env
  3. Restart notification service
  4. Revoke old token

Troubleshooting

Bakery doesn't receive WhatsApp messages

Checklist:

  1. WhatsApp enabled in tenant settings?
  2. Phone number assigned to tenant?
  3. Master credentials in environment variables?
  4. Template approved by Meta?
  5. Recipient phone in E.164 format (+34612345678)?

Check logs:

docker logs -f notification-service | grep -i "whatsapp\|error"

Phone assignment fails: "Already assigned"

Find which tenant has it:

curl http://localhost:8001/api/v1/admin/whatsapp/tenants | \
  jq '.[] | select(.phone_number_id == "YOUR_PHONE_ID")'

Unassign first:

curl -X DELETE http://localhost:8001/api/v1/admin/whatsapp/tenants/{tenant_id}/unassign-phone

"WhatsApp master account not configured"

Ensure environment variables are set:

docker exec notification-service env | grep WHATSAPP

Should show all variables (WABA ID, Access Token, Phone Number ID).


Next Steps

Immediate (Before Pilot)

  • Complete master account setup (follow WHATSAPP_MASTER_ACCOUNT_SETUP.md)
  • Assign phone numbers to all 10 pilot bakeries
  • Send email to bakeries: "WhatsApp notifications are ready - just toggle ON in settings"
  • Test with 2-3 bakeries first
  • Monitor for first week

Short-term (During Pilot)

  • Collect bakery feedback
  • Monitor quality rating daily
  • Track message costs
  • Document common support questions

Long-term (After Pilot)

  • Consider WhatsApp Embedded Signup for self-service (if scaling beyond 10)
  • Create additional templates (inventory alerts, production alerts)
  • Implement rich media messages (images, documents)
  • Add interactive buttons (approve/reject PO via WhatsApp)

Files Modified/Created

Backend

Modified:

  • services/tenant/app/models/tenant_settings.py
  • services/tenant/app/schemas/tenant_settings.py
  • services/notification/app/services/whatsapp_business_service.py
  • services/tenant/app/main.py

Created:

  • services/tenant/app/api/whatsapp_admin.py

Frontend

Modified:

  • frontend/src/pages/app/database/ajustes/cards/NotificationSettingsCard.tsx
  • frontend/src/api/types/settings.ts

Created:

  • frontend/src/pages/app/admin/WhatsAppAdminPage.tsx

Documentation

Created:

  • WHATSAPP_SHARED_ACCOUNT_GUIDE.md - Full implementation guide
  • WHATSAPP_MASTER_ACCOUNT_SETUP.md - Admin setup instructions
  • WHATSAPP_IMPLEMENTATION_SUMMARY.md - This file

Support

Questions?

Common Issues:

  • Most problems are due to missing/incorrect environment variables
  • Check logs: docker logs -f notification-service
  • Verify Meta credentials haven't expired
  • Ensure templates are APPROVED (not PENDING)

Summary

Zero configuration for bakery users 5-minute setup per bakery (admin) €750 saved in setup costs Lower support burden Perfect for 10-bakery pilot Can scale to 120 bakeries with same model

Next: Set up your master WhatsApp account following WHATSAPP_MASTER_ACCOUNT_SETUP.md


Implementation Date: 2025-01-17 Status: Complete and Ready for Pilot Estimated Setup Time: 2-3 hours (one-time) Per-Bakery Time: 5 minutes