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57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
# Notification System - Developer Guide

## 🎯 Overview

The SwiftOps notification system is a **2-tier architecture** designed for reliability, scalability, and maintainability. It handles all notifications across the platform with a consistent, world-class approach.

### Architecture

```
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚                    NOTIFICATION SYSTEM                       β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚                                                              β”‚
β”‚  TIER 1: Notification Creation (Synchronous)                β”‚
β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”    β”‚
β”‚  β”‚  NotificationCreator                                β”‚    β”‚
β”‚  β”‚  - Creates notification records in database         β”‚    β”‚
β”‚  β”‚  - Synchronous, transaction-safe                    β”‚    β”‚
β”‚  β”‚  - Guaranteed to be saved                           β”‚    β”‚
β”‚  β”‚  - Rolls back with parent operation                 β”‚    β”‚
β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜    β”‚
β”‚                          ↓                                   β”‚
β”‚  TIER 2: Notification Delivery (Asynchronous)               β”‚
β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”    β”‚
β”‚  β”‚  NotificationDelivery                               β”‚    β”‚
β”‚  β”‚  - Delivers via external channels (WhatsApp, etc.)  β”‚    β”‚
β”‚  β”‚  - Non-blocking background tasks                    β”‚    β”‚
β”‚  β”‚  - Handles failures gracefully                      β”‚    β”‚
β”‚  β”‚  - Configurable per channel                         β”‚    β”‚
β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜    β”‚
β”‚                                                              β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
```

---

## πŸš€ Quick Start

### Basic Usage

```python
from fastapi import BackgroundTasks
from app.services.notification_creator import NotificationCreator
from app.services.notification_delivery import NotificationDelivery

# In your endpoint
@router.post("/tickets/assign")
def assign_ticket(
    background_tasks: BackgroundTasks,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    # Your business logic
    ticket = create_ticket(...)
    assignment = assign_to_agent(...)
    
    # TIER 1: Create notification (synchronous)
    notification = NotificationCreator.create(
        db=db,
        user_id=agent.id,
        title="New Ticket Assigned",
        message=f"You have been assigned to {ticket.ticket_name}",
        source_type="ticket",
        source_id=ticket.id,
        notification_type="assignment",
        channel="whatsapp",
        project_id=ticket.project_id,
        metadata={
            "ticket_number": ticket.ticket_number,
            "priority": "high",
            "action_url": f"/tickets/{ticket.id}"
        }
    )
    
    # Commit notification with your business logic
    db.commit()
    
    # TIER 2: Queue delivery (asynchronous, non-blocking)
    NotificationDelivery.queue_delivery(
        background_tasks=background_tasks,
        notification_id=notification.id
    )
    
    return {"status": "success"}
```

---

## πŸ“š API Reference

### NotificationCreator

#### `create()` - Create Single Notification

```python
notification = NotificationCreator.create(
    db: Session,                    # Database session
    user_id: UUID,                  # User to notify
    title: str,                     # Short title (for display)
    message: str,                   # Detailed message
    source_type: str,               # Entity type (ticket, expense, payroll, etc.)
    source_id: Optional[UUID],      # Entity ID (None for bulk operations)
    notification_type: str,         # Notification type (assignment, payment, alert, etc.)
    channel: str = "in_app",        # Delivery channel (in_app, whatsapp, email, sms, push)
    metadata: Optional[Dict] = None,# Additional data (action URLs, context, etc.)
    project_id: Optional[UUID] = None  # Optional project ID for filtering
) -> Notification
```

**Example:**
```python
notification = NotificationCreator.create(
    db=db,
    user_id=agent.id,
    title="Ticket Assigned",
    message="You have been assigned to install fiber at Customer A",
    source_type="ticket",
    source_id=ticket.id,
    notification_type="assignment",
    channel="whatsapp",
    project_id=ticket.project_id,
    metadata={
        "ticket_number": "TKT-001",
        "priority": "high",
        "action_url": f"/tickets/{ticket.id}"
    }
)
db.commit()
```

#### `create_bulk()` - Create Multiple Notifications

```python
notifications = NotificationCreator.create_bulk(
    db: Session,
    user_ids: List[UUID],           # List of users to notify
    title: str,                     # Same title for all
    message: str,                   # Same message for all
    source_type: str,
    source_id: Optional[UUID],
    notification_type: str,
    channel: str = "in_app",
    metadata: Optional[Dict] = None,
    project_id: Optional[UUID] = None
) -> List[Notification]
```

**Example:**
```python
# Notify all workers about payroll export
worker_ids = [worker1.id, worker2.id, worker3.id]
notifications = NotificationCreator.create_bulk(
    db=db,
    user_ids=worker_ids,
    title="πŸ’° Payment Processed",
    message="Your payment has been processed",
    source_type="payroll",
    source_id=None,
    notification_type="payment",
    channel="whatsapp"
)
db.commit()
```

#### `notify_project_team()` - Notify Team Members by Role

```python
notifications = NotificationCreator.notify_project_team(
    db: Session,
    project_id: UUID,               # Project ID
    title: str,
    message: str,
    source_type: str,
    source_id: Optional[UUID],
    notification_type: str,
    roles: Optional[List[AppRole]] = None,  # Filter by roles (PM, Dispatcher, etc.)
    channel: str = "in_app",
    metadata: Optional[Dict] = None,
    exclude_user_ids: Optional[List[UUID]] = None  # Exclude specific users
) -> List[Notification]
```

**Example:**
```python
# Notify all managers when ticket is dropped
notifications = NotificationCreator.notify_project_team(
    db=db,
    project_id=ticket.project_id,
    title="⚠️ Ticket Dropped - Action Required",
    message=f"{agent.name} dropped ticket: {ticket.name}",
    source_type="ticket",
    source_id=ticket.id,
    notification_type="ticket_dropped",
    roles=[AppRole.PROJECT_MANAGER, AppRole.DISPATCHER],
    exclude_user_ids=[agent.id]  # Don't notify the agent who dropped
)
db.commit()
```

---

### NotificationDelivery

#### `queue_delivery()` - Queue Single Notification

```python
NotificationDelivery.queue_delivery(
    background_tasks: BackgroundTasks,  # FastAPI BackgroundTasks
    notification_id: UUID               # Notification ID to deliver
) -> None
```

**Example:**
```python
NotificationDelivery.queue_delivery(
    background_tasks=background_tasks,
    notification_id=notification.id
)
```

#### `queue_bulk_delivery()` - Queue Multiple Notifications

```python
NotificationDelivery.queue_bulk_delivery(
    background_tasks: BackgroundTasks,
    notification_ids: List[UUID]        # List of notification IDs
) -> None
```

**Example:**
```python
NotificationDelivery.queue_bulk_delivery(
    background_tasks=background_tasks,
    notification_ids=[n.id for n in notifications]
)
```

---

## 🎨 Common Patterns

### Pattern 1: Single User Notification

```python
@router.post("/tickets/assign")
def assign_ticket(
    background_tasks: BackgroundTasks,
    db: Session = Depends(get_db)
):
    # Business logic
    assignment = create_assignment(...)

    # Create notification
    notification = NotificationCreator.create(
        db=db,
        user_id=agent.id,
        title="Ticket Assigned",
        message=f"You have been assigned to {ticket.name}",
        source_type="ticket",
        source_id=ticket.id,
        notification_type="assignment",
        channel="whatsapp"
    )
    db.commit()

    # Queue delivery
    NotificationDelivery.queue_delivery(
        background_tasks=background_tasks,
        notification_id=notification.id
    )

    return assignment
```

### Pattern 2: Notify Project Team by Role

```python
@router.post("/tickets/{ticket_id}/drop")
def drop_ticket(
    background_tasks: BackgroundTasks,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    # Business logic
    ticket = drop_ticket(...)

    # Notify all managers and dispatchers
    notifications = NotificationCreator.notify_project_team(
        db=db,
        project_id=ticket.project_id,
        title="⚠️ Ticket Dropped",
        message=f"{current_user.name} dropped ticket: {ticket.name}",
        source_type="ticket",
        source_id=ticket.id,
        notification_type="ticket_dropped",
        roles=[AppRole.PROJECT_MANAGER, AppRole.DISPATCHER],
        exclude_user_ids=[current_user.id]
    )
    db.commit()

    # Queue delivery
    NotificationDelivery.queue_bulk_delivery(
        background_tasks=background_tasks,
        notification_ids=[n.id for n in notifications]
    )

    return ticket
```

---

## βš™οΈ Configuration

### Channel Configuration

For MVP, all external channels are **disabled by default**. Notifications are created but not delivered externally.

**File:** `src/app/services/notification_delivery.py`

```python
class NotificationDeliveryConfig:
    # For MVP, all external channels are disabled
    ENABLE_WHATSAPP = False  # Set to True when ready
    ENABLE_EMAIL = False     # Set to True when ready
    ENABLE_SMS = False       # Set to True when ready
    ENABLE_PUSH = False      # Set to True when ready

    # In-app notifications are always enabled
    ENABLE_IN_APP = True
```

**To enable a channel:**
1. Set the flag to `True` in `NotificationDeliveryConfig`
2. Implement the delivery method (e.g., `_deliver_whatsapp()`)
3. Test thoroughly
4. Deploy

---

## πŸ” Best Practices

### 1. Always Commit Notifications

```python
# βœ… CORRECT
notification = NotificationCreator.create(...)
db.commit()  # Commit before queuing delivery

NotificationDelivery.queue_delivery(...)
```

```python
# ❌ WRONG
notification = NotificationCreator.create(...)
NotificationDelivery.queue_delivery(...)  # Notification not committed yet!
db.commit()
```

### 2. Use Metadata for Context

```python
# βœ… CORRECT - Rich metadata
notification = NotificationCreator.create(
    db=db,
    user_id=user.id,
    title="Ticket Assigned",
    message="You have been assigned...",
    source_type="ticket",
    source_id=ticket.id,
    notification_type="assignment",
    metadata={
        "ticket_number": ticket.ticket_number,
        "priority": "high",
        "action_url": f"/tickets/{ticket.id}",
        "customer_name": ticket.customer_name
    }
)
```

### 3. Handle Notification Failures Gracefully

```python
# βœ… CORRECT - Don't fail business logic if notification fails
try:
    notification = NotificationCreator.create(...)
    db.commit()
    NotificationDelivery.queue_delivery(...)
except Exception as e:
    logger.error(f"Failed to create notification: {e}")
    # Continue with business logic
```

---

## πŸš€ Migration from Old System

### Old Pattern (NotificationHelper - Async)

```python
# ❌ OLD - Don't use this anymore
await NotificationHelper.notify_ticket_assigned(
    db=db,
    ticket=ticket,
    agent=agent
)
```

### New Pattern (NotificationCreator - Sync)

```python
# βœ… NEW - Use this instead
notification = NotificationCreator.create(
    db=db,
    user_id=agent.id,
    title="Ticket Assigned",
    message=f"You have been assigned to {ticket.name}",
    source_type="ticket",
    source_id=ticket.id,
    notification_type="assignment",
    channel="whatsapp"
)
db.commit()

NotificationDelivery.queue_delivery(
    background_tasks=background_tasks,
    notification_id=notification.id
)
```

---

## πŸ“ž Support

For questions or issues with the notification system:
1. Check this documentation
2. Review existing implementations in:
   - `src/app/api/v1/payroll.py` (payroll export)
   - `src/app/api/v1/ticket_assignments.py` (ticket drop)
   - `src/app/services/expense_service.py` (expense submission)
3. Contact the development team

---

**Last Updated:** 2024-12-12
**Version:** 1.0.0
**Status:** Production Ready βœ