# WhatsApp Message Template Example

This document shows exactly how to create the `po_notification` template in Meta Business Suite.

---

## Template: Purchase Order Notification

### Basic Information

| Field | Value |
|-------|-------|
| **Template Name** | `po_notification` |
| **Category** | `UTILITY` |
| **Language** | `Spanish (es)` |

---

## Template Content

### Body Text (Required)

```
Hola {{1}}, has recibido una nueva orden de compra {{2}} por un total de {{3}}.
```

### Parameters

| Position | Parameter Name | Example Value | Description |
|----------|---------------|---------------|-------------|
| {{1}} | supplier_name | "Proveedor ABC" | Name of the supplier |
| {{2}} | po_number | "PO-2024-001" | Purchase order number |
| {{3}} | total_amount | "€1,250.00" | Total amount with currency |

---

## Preview Examples

### Example 1
```
Hola Proveedor ABC, has recibido una nueva orden de compra PO-2024-001 por un total de €1,250.00.
```

### Example 2
```
Hola Panadería Central, has recibido una nueva orden de compra PO-2024-052 por un total de €850.50.
```

### Example 3
```
Hola Distribuidora López, has recibido una nueva orden de compra PO-2024-123 por un total de €2,340.00.
```

---

## Step-by-Step Creation in Meta

### 1. Navigate to Template Manager

1. Go to: https://business.facebook.com/
2. Click **WhatsApp Manager**
3. Select **Message Templates**
4. Click **Create Template** button

### 2. Fill Basic Information

**Step 1 of 4: Select Template Category**
- Select: `Utility`
- Template name: `po_notification`
- Languages: Select `Spanish (es)`
- Click **Continue**

### 3. Build Template Content

**Step 2 of 4: Edit Template**

**Header (Optional)**: Skip or add:
- Type: Text
- Content: `Nueva Orden de Compra`
- Or use emoji: `🛒 Nueva Orden de Compra`

**Body (Required)**:
```
Hola {{1}}, has recibido una nueva orden de compra {{2}} por un total de {{3}}.
```

**How to add variables**:
1. Type the text up to where you want the first variable
2. Click **Add Variable** button
3. Continue typing
4. Repeat for {{2}} and {{3}}

**Footer (Optional)**:
```
Sistema de Gestión de Panadería
```

**Buttons (Optional)**: Skip for basic implementation

Click **Continue**

### 4. Add Sample Content

**Step 3 of 4: Add Sample Content**

For template approval, provide example values:

| Variable | Sample Value |
|----------|--------------|
| {{1}} | Proveedor ABC |
| {{2}} | PO-2024-001 |
| {{3}} | €1,250.00 |

**Preview will show**:
```
Hola Proveedor ABC, has recibido una nueva orden de compra PO-2024-001 por un total de €1,250.00.
```

Click **Continue**

### 5. Submit for Review

**Step 4 of 4: Submit**

Review your template:
- ✅ Category: Utility
- ✅ Language: Spanish
- ✅ Body has 3 variables
- ✅ Sample content provided

Click **Submit**

---

## Approval Timeline

| Status | Timeline | Action Required |
|--------|----------|-----------------|
| **Pending** | 0-24 hours | Wait for Meta review |
| **Approved** | ✅ Ready to use | Start sending messages |
| **Rejected** | Review feedback | Fix issues and resubmit |

---

## Common Rejection Reasons

❌ **Reason**: Variables in header or footer
- **Fix**: Only use variables in body text

❌ **Reason**: Too promotional
- **Fix**: Use UTILITY category, not MARKETING

❌ **Reason**: Unclear business purpose
- **Fix**: Make message clearly transactional

❌ **Reason**: Missing sample content
- **Fix**: Provide realistic examples for all variables

❌ **Reason**: Grammar/spelling errors
- **Fix**: Proofread carefully

---

## Code Implementation

### How This Template is Used in Code

```python
# services/notification/app/consumers/po_event_consumer.py

template_params = [
    data.get('supplier_name', 'Estimado proveedor'),  # {{1}}
    data.get('po_number', 'N/A'),                     # {{2}}
    f"€{data.get('total_amount', 0):.2f}"            # {{3}}
]

success = await self.whatsapp_service.send_message(
    to_phone=supplier_phone,
    message="",  # Not used for template messages
    template_name="po_notification",  # Must match exactly
    template_params=template_params,
    tenant_id=tenant_id
)
```

### API Request Format

The service converts this to:

```json
{
  "messaging_product": "whatsapp",
  "to": "+34612345678",
  "type": "template",
  "template": {
    "name": "po_notification",
    "language": {
      "code": "es"
    },
    "components": [
      {
        "type": "body",
        "parameters": [
          {"type": "text", "text": "Proveedor ABC"},
          {"type": "text", "text": "PO-2024-001"},
          {"type": "text", "text": "€1,250.00"}
        ]
      }
    ]
  }
}
```

---

## Advanced Template (With Header & Buttons)

If you want a more feature-rich template:

### Template Name
`po_notification_advanced`

### Header
- Type: **Text**
- Content: `🛒 Nueva Orden de Compra`

### Body
```
Hola {{1}}, has recibido una nueva orden de compra {{2}} por un total de {{3}}.

Por favor, confirma la recepción de esta orden.
```

### Footer
```
Bakery Management System
```

### Buttons
1. **Quick Reply Button**: "✅ Confirmar Recepción"
2. **Phone Button**: "📞 Llamar" → Your bakery phone

### Preview
```
🛒 Nueva Orden de Compra

Hola Proveedor ABC, has recibido una nueva orden de compra PO-2024-001 por un total de €1,250.00.

Por favor, confirma la recepción de esta orden.

Bakery Management System

[✅ Confirmar Recepción] [📞 Llamar]
```

---

## Template Best Practices

### ✅ DO
- Keep messages concise and clear
- Use proper Spanish grammar
- Provide all variable examples
- Test with real phone numbers
- Use UTILITY category for transactional messages
- Include business name in footer

### ❌ DON'T
- Use promotional language for UTILITY templates
- Add too many variables (max 3-5 recommended)
- Use special characters excessively
- Mix languages within template
- Use uppercase only (LIKE THIS)
- Include pricing in UTILITY templates (use variables)

---

## Testing Your Template

### After Approval

1. **Get Template Status**
   ```bash
   # Check in Meta Business Suite
   WhatsApp Manager → Message Templates → po_notification → Status: APPROVED
   ```

2. **Send Test Message**
   ```bash
   curl -X POST http://localhost:8000/api/v1/tenants/{tenant_id}/notifications/send-whatsapp \
     -H "Content-Type: application/json" \
     -d '{
       "recipient_phone": "+34612345678",
       "template_name": "po_notification",
       "template_params": ["Test Supplier", "PO-TEST-001", "€100.00"]
     }'
   ```

3. **Verify Delivery**
   - Check recipient's WhatsApp
   - Check database: `SELECT * FROM whatsapp_messages WHERE template_name = 'po_notification'`
   - Check logs: `kubectl logs -f deployment/notification-service | grep po_notification`

---

## Additional Template Ideas

Once the basic template works, consider creating:

### Template: Order Confirmation
```
Hola {{1}}, tu orden {{2}} ha sido confirmada. Entrega prevista: {{3}}.
```

### Template: Delivery Notification
```
Hola {{1}}, tu orden {{2}} está en camino. Llegada estimada: {{3}}.
```

### Template: Payment Reminder
```
Hola {{1}}, recordatorio: factura {{2}} por {{3}} vence el {{4}}.
```

### Template: Order Cancelled
```
Hola {{1}}, la orden {{2}} ha sido cancelada. Motivo: {{3}}.
```

---

## Template Management

### Monitoring Template Performance

Check in Meta Business Suite:
- **Sent**: Total messages sent
- **Delivered**: Delivery rate
- **Read**: Read rate
- **Failed**: Failure reasons

### Updating Templates

⚠️ **Important**: You cannot edit approved templates

To make changes:
1. Create new template with modified content
2. Submit for approval
3. Update code to use new template name
4. Deprecate old template after transition

### Template Limits

- **Maximum templates**: 250 per WhatsApp Business Account
- **Maximum variables per template**: Unlimited (but keep it reasonable)
- **Template name**: lowercase, underscore only (e.g., `po_notification`)

---

## Summary

✅ Template Name: `po_notification`
✅ Category: UTILITY
✅ Language: Spanish (es)
✅ Variables: 3 (supplier, PO number, amount)
✅ Status: Must be APPROVED before use

**Next Step**: Create this template in Meta Business Suite and wait for approval (usually 15 mins - 24 hours).
