# Order Notification System

## Overview
The order notification system automatically notifies buyers and sellers about important order events throughout the order lifecycle.

## Notification Events

### 1. **Order Created** (New Purchase)
- **Recipient**: All sellers whose products are in the order
- **Type**: `ORDER`
- **Title**: "New Order Received"
- **Message**: "You have received a new order #ORD-YYYY-XXXXX"
- **Triggered**: When a buyer creates a new order

### 2. **Payment Confirmed**
- **Recipients**: 
  - Buyer: "Payment Confirmed" - "Your payment for order #ORD-YYYY-XXXXX has been confirmed"
  - All Sellers: "Order Payment Received" - "Payment received for order #ORD-YYYY-XXXXX"
- **Type**: `ORDER`
- **Triggered**: When Stripe payment webhook confirms successful payment

### 3. **Order Status Updated**
- **Recipient**: Buyer
- **Type**: `ORDER`
- **Title**: "Order Status Updated"
- **Messages** (based on status):
  - `PROCESSING`: "Your order is being processed"
  - `SHIPPED`: "Your order has been shipped (Tracking: XXX)" (includes tracking number if provided)
  - `DELIVERED`: "Your order has been delivered"
  - `COMPLETED`: "Your order is complete"
- **Triggered**: When seller updates order status

### 4. **Order Cancelled**
- **Recipients**:
  - All Sellers: "Order Cancelled" - "Order #ORD-YYYY-XXXXX has been cancelled by the buyer"
  - Buyer (confirmation): "Order Cancelled" - "Your order #ORD-YYYY-XXXXX has been cancelled"
- **Type**: `ORDER`
- **Triggered**: When buyer cancels an order
- **Effects**:
  - Stock restored for physical products
  - Earnings reversed if order was paid
  - Seller balances adjusted

### 5. **Order Refunded**
- **Recipients**:
  - Buyer: "Order Refunded" - "Your order #ORD-YYYY-XXXXX has been refunded"
  - All Sellers: "Order Refunded" - "Order #ORD-YYYY-XXXXX has been refunded"
- **Type**: `ORDER`
- **Triggered**: When seller processes a refund
- **Effects**:
  - Stock restored for physical products
  - Earnings reversed
  - Seller balances adjusted
  - Stripe refund processed

## Implementation Details

### Backend (OrderService)

#### Helper Method
```typescript
private async createOrderNotification(
  userId: string,
  type: string,
  title: string,
  message: string,
  orderId: string,
)
```

Creates a notification in the database. Failures are logged but don't break the order flow.

#### Integration Points

1. **createOrder()** - Lines ~280-295
   - Notifies all sellers after order creation
   - Extracts unique seller IDs from order items

2. **markOrderAsPaid()** - Lines ~400-420
   - Notifies buyer of payment confirmation
   - Notifies all sellers of payment received

3. **updateOrderStatus()** - Lines ~605-625
   - Notifies buyer with status-specific message
   - Includes tracking number for shipped orders

4. **cancelOrder()** - Lines ~745-765
   - Notifies all sellers of cancellation
   - Sends confirmation notification to buyer

5. **refundOrder()** - Lines ~875-895
   - Notifies buyer of refund
   - Notifies all sellers of refund

### Database Schema

```prisma
model Notification {
  id        String   @id @default(cuid())
  userId    String
  type      String   // 'ORDER' for order-related notifications
  title     String   // Short notification title
  message   String   // Detailed notification message
  read      Boolean  @default(false)
  data      Json?    // Contains { orderId: string }
  createdAt DateTime @default(now())
  user      User     @relation(fields: [userId], references: [id], onDelete: Cascade)
}
```

### Frontend Integration

#### Seller UI (manage-orders.js)

**New Features:**
1. **Refund Button** - Red button next to "Update Status" for orders in PAID/PROCESSING/SHIPPED status
2. **Refund Modal** - Shows:
   - Warning about refund consequences (payment refund, stock restore, earnings deduction)
   - Required refund reason text area
   - Confirm/Cancel buttons
3. **Web Compatibility** - Uses `alert()` on web, `Alert.alert()` on mobile

**Action Buttons:**
```javascript
{['PAID', 'PROCESSING', 'SHIPPED'].includes(order.status) && (
  <>
    <UpdateStatusButton />
    <RefundButton />  // NEW
  </>
)}
```

#### Buyer UI
- Notifications appear in the user's notification list
- Each notification includes:
  - Icon badge (unread indicator)
  - Title and message
  - Link to order details (via `data.orderId`)
  - Timestamp

## API Endpoints

### Existing Notification Endpoints
```typescript
GET  /notifications           // Get user's notifications
GET  /notifications/unread    // Get unread count
POST /notifications/mark-read // Mark notification as read
POST /notifications/mark-all-read // Mark all as read
```

### Order Management Endpoints
```typescript
POST /orders/refund/:orderId  // Refund an order
PATCH /orders/:orderId/status // Update order status
POST /orders/:orderId/cancel  // Cancel an order
```

## User Flow Examples

### Example 1: Successful Order
1. Buyer creates order → **Sellers** get "New Order Received" notification
2. Buyer pays → **Buyer** gets "Payment Confirmed", **Sellers** get "Order Payment Received"
3. Seller updates to PROCESSING → **Buyer** gets "Your order is being processed"
4. Seller updates to SHIPPED with tracking → **Buyer** gets "Your order has been shipped (Tracking: 1Z999AA10123456784)"
5. Seller updates to DELIVERED → **Buyer** gets "Your order has been delivered"

### Example 2: Order Cancellation
1. Order in PAID status
2. Buyer cancels with reason "Changed my mind"
3. **Sellers** get "Order #ORD-2025-00123 has been cancelled by the buyer"
4. **Buyer** gets "Your order #ORD-2025-00123 has been cancelled"
5. Stock restored, earnings reversed

### Example 3: Order Refund
1. Order in PAID/PROCESSING/SHIPPED status
2. Seller clicks Refund button
3. Seller enters reason: "Product defect"
4. **Buyer** gets "Your order #ORD-2025-00123 has been refunded"
5. **Seller** gets "Order #ORD-2025-00123 has been refunded"
6. Stripe processes refund, stock restored, earnings reversed

## Error Handling

### Notification Failures
- Notification creation failures are logged but don't throw errors
- Order flow continues even if notification fails
- Error message: `"Error creating notification: [error]"`

### Refund Failures
- If Stripe refund fails, order status is NOT updated
- Transaction is rolled back
- User receives error alert
- Stock is NOT restored

## Future Enhancements

### Planned
1. **Real-time Notifications** - WebSocket/Socket.io integration for instant delivery
2. **Email Notifications** - Send emails for critical events (order received, payment confirmed, refunded)
3. **Push Notifications** - Mobile push notifications for order events
4. **Notification Preferences** - Let users configure which notifications they want to receive
5. **Notification Templates** - Customizable notification message templates
6. **Notification History** - Archive and search old notifications
7. **Bulk Actions** - Mark multiple notifications as read

### Technical Improvements
1. **Notification Queue** - Use Redis/Bull for reliable notification delivery
2. **Rate Limiting** - Prevent notification spam
3. **Notification Batching** - Combine multiple similar notifications
4. **Rich Notifications** - Add images, action buttons, deep links
5. **Analytics** - Track notification open rates and engagement

## Testing

### Manual Testing Checklist
- [ ] Create order → Verify seller receives notification
- [ ] Complete payment → Verify buyer and seller receive notifications
- [ ] Update order status → Verify buyer receives notification with correct message
- [ ] Update to SHIPPED with tracking → Verify tracking number in notification
- [ ] Cancel order → Verify buyer and seller receive notifications
- [ ] Refund order → Verify buyer and seller receive notifications
- [ ] Check notification list displays correctly
- [ ] Mark notification as read
- [ ] Check unread count updates

### API Testing
```bash
# Create order and check notifications
POST /orders
GET /notifications

# Update status and check notifications
PATCH /orders/:id/status
GET /notifications

# Refund and check notifications
POST /orders/refund/:id
GET /notifications
```

## Configuration

### Environment Variables
None required - notification system uses existing database connection and Prisma client.

### Database
No migrations needed - uses existing `Notification` table.

### Dependencies
- `@nestjs/common` - NestJS decorators and utilities
- `@prisma/client` - Database operations
- Existing `NotificationsService` - Notification business logic

## Monitoring

### Logs to Monitor
```
Error creating notification: [error details]
Error updating status: [error details]
Error refunding order: [error details]
```

### Metrics to Track
- Notification creation rate
- Notification failure rate
- Average notification delivery time
- User engagement with notifications (read rate)
- Order event frequency by type

## Support

### Common Issues

**Issue**: Notifications not appearing
- Check database connection
- Verify notification creation logs
- Check user ID matches in notification table

**Issue**: Duplicate notifications
- Check for multiple order status updates
- Review transaction handling

**Issue**: Missing notifications
- Check notification service availability
- Review error logs for creation failures
- Verify notification type filter

## Changelog

### Version 1.0.0 (Current)
- ✅ Notification system integrated into OrderService
- ✅ Auto-notifications for all order events
- ✅ Seller refund UI with modal
- ✅ Web compatibility for alerts
- ✅ Comprehensive error handling
- ✅ Transaction-safe notification creation
