# CPD Export Engine - User Guide

## Overview

The **CPD Export Engine** is a powerful feature that allows you to export Continuing Professional Development (CPD) data for event attendees. It integrates with the ICTAZ Membership System to enrich attendance data with official member information.

---

## Features

✅ **Event-based Export** - Export CPD data for any event  
✅ **Membership System Integration** - Automatically looks up members by NRC/Passport  
✅ **Smart Fallback** - Uses attendance data if member not found in membership system  
✅ **CPD Points Configuration** - Set CPD points per event  
✅ **Data Preview** - Preview enriched data before exporting  
✅ **CSV Export** - Download formatted CSV file ready for submission  

---

## How It Works

### 1. Data Enrichment Process

```
┌─────────────────────────────────────────────────────────────┐
│  Attendance List (Selected Event)                           │
│  - Registration Code                                         │
│  - Full Name                                                 │
│  - Email                                                     │
│  - NRC/Passport Number                                       │
└─────────────────────┬───────────────────────────────────────┘
                      │
                      ▼
┌─────────────────────────────────────────────────────────────┐
│  Membership System API Lookup                                │
│  POST: /members/individual/lookup                            │
│  - Searches by NRC or Passport                               │
└─────────────────────┬───────────────────────────────────────┘
                      │
        ┌─────────────┴─────────────┐
        │                           │
        ▼                           ▼
┌───────────────┐         ┌──────────────────┐
│ Member Found  │         │ Member Not Found │
│ in System     │         │ in System        │
└───────┬───────┘         └────────┬─────────┘
        │                          │
        ▼                          ▼
┌───────────────────┐    ┌─────────────────────┐
│ Use Membership    │    │ Use Attendance      │
│ System Data:      │    │ List Data:          │
│ - Membership #    │    │ - Parse name        │
│ - Official Names  │    │ - Use email         │
│ - Email           │    │ - Use NRC/Passport  │
│ - Mobile          │    │ - No membership #   │
└───────┬───────────┘    └─────────┬───────────┘
        │                          │
        └──────────┬───────────────┘
                   ▼
        ┌──────────────────────┐
        │  CSV Export File     │
        │  with CPD Points     │
        └──────────────────────┘
```

### 2. CSV Output Format

The exported CSV contains the following columns:

| Column | Description | Source |
|--------|-------------|--------|
| **Membership Number** | Official ICTAZ membership number | Membership System (if found) |
| **National ID Type** | "NRC" or "Passport" | Detected from format |
| **National ID Number** | NRC or Passport number | Attendance List |
| **First Name** | Member's first name | Membership System → Attendance List |
| **Middle Name** | Member's middle name | Membership System → Attendance List |
| **Last Name** | Member's last name | Membership System → Attendance List |
| **Email** | Member's email address | Membership System → Attendance List |
| **Mobile** | Member's mobile number | Membership System only |
| **CPD Points** | CPD points for the event | Configured per event |

---

## Using the CPD Export Engine

### Step 1: Access the CPD Export Page

1. Log in to the admin dashboard
2. Click **"CPD Export"** in the sidebar navigation
3. You'll see the CPD Export Engine interface

### Step 2: Configure Export

1. **Select Event**
   - Choose the event from the dropdown
   - Only events with attendance records will have data

2. **Set CPD Points** (Optional)
   - Enter the CPD points value (e.g., 3.5)
   - Leave blank if CPD points not yet assigned
   - You can update this value later

### Step 3: Preview Data

1. Click **"Preview Data"** button
2. Review the enriched member data:
   - Check which members were found in membership system (green badge)
   - Verify which members use attendance list data (yellow badge)
   - Preview shows first 10 members

### Step 4: Export CSV

1. Click **"Export CSV"** button
2. CSV file will download automatically
3. Filename format: `cpd_export_[Event_Name].csv`

---

## API Endpoints

### Backend API Routes

#### 1. Preview CPD Data
```http
POST /api/cpd/configurations/preview_cpd_data/
Content-Type: application/json

{
  "event_id": 1,
  "cpd_points": 3.5
}
```

**Response:**
```json
{
  "event": {
    "id": 1,
    "name": "Training 1: Applied AI & Machine Learning"
  },
  "total_members": 184,
  "cpd_points": 3.5,
  "preview_data": [
    {
      "registration_code": "K3TGL",
      "membership_number": "FM000982",
      "national_id_type": "NRC",
      "national_id_number": "113773/10/1",
      "first_name": "Aaron",
      "middle_name": "",
      "last_name": "Nyirenda",
      "email": "nyonganyirenda@yahoo.com",
      "mobile": "260977123456",
      "cpd_points": 3.5,
      "source": "membership_system"
    }
  ]
}
```

#### 2. Export CPD CSV
```http
POST /api/cpd/configurations/export_cpd/
Content-Type: application/json

{
  "event_id": 1,
  "cpd_points": 3.5
}
```

**Response:** CSV file download

#### 3. Set CPD Points
```http
POST /api/cpd/configurations/set_cpd_points/
Content-Type: application/json

{
  "event_id": 1,
  "cpd_points": 3.5
}
```

---

## Membership System API Integration

### API Configuration

**Base URL:** Configured via environment variable `MEMBERSHIP_API_BASE_URL`

**Authentication Headers:**
```
X-API-Key: Configured via environment variable MEMBERSHIP_API_KEY
X-API-Secret: Configured via environment variable MEMBERSHIP_API_SECRET
```

**Note:** API credentials are stored securely in environment variables and should never be hardcoded or committed to version control.

### Member Lookup Endpoint

**Endpoint:** `POST /members/individual/lookup`

**Request (NRC):**
```json
{
  "nationalIdType": "NRC",
  "nationalIdNo": "535628/61/1"
}
```

**Request (Passport):**
```json
{
  "nationalIdType": "Passport",
  "nationalIdNo": "MWZ015434"
}
```

**Success Response:**
```json
{
  "data": {
    "memberId": 3999,
    "membershipNo": "AS000030",
    "membershipCategory": "Associate",
    "title": "Mr",
    "firstName": "Mulenga",
    "middleName": "",
    "lastName": "Mulenga",
    "email": "mulengacmulenga.org@gmail.com",
    "mobile": "260975701878",
    "nationalIdType": "NRC",
    "nationalIdNo": "535628/61/1",
    "countryCode": "ZM",
    "countryName": "ZM",
    "status": "Active"
  },
  "success": true
}
```

**Not Found Response:**
```json
{
  "error": {
    "code": "MEMBER_NOT_FOUND",
    "message": "No member found with the provided national ID"
  },
  "success": false
}
```

---

## Database Schema

### CPDConfiguration Model

```python
class CPDConfiguration(models.Model):
    event = models.OneToOneField(Event, on_delete=models.CASCADE)
    cpd_points = models.DecimalField(max_digits=5, decimal_places=2)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
```

**Fields:**
- `event` - One-to-one relationship with Event model
- `cpd_points` - CPD points value (e.g., 3.5)
- `created_at` - Timestamp when configuration was created
- `updated_at` - Timestamp when configuration was last updated

---

## Troubleshooting

### Issue: No members showing in preview

**Cause:** No attendance records for the selected event

**Solution:**
1. Verify members have checked in to the event
2. Check attendance list for the event
3. Ensure event category matches member registrations

### Issue: All members showing "Attendance" source

**Cause:** Members not found in membership system

**Possible reasons:**
1. NRC/Passport numbers don't match membership system records
2. Membership system API is down
3. Members are not registered in membership system

**Solution:**
1. Verify NRC/Passport numbers are correct in attendance list
2. Check membership system API connectivity
3. Contact ICTAZ membership team to verify member records

### Issue: Export button not working

**Cause:** Event not selected or no CPD points set

**Solution:**
1. Select an event from the dropdown
2. Optionally set CPD points (can be left blank)
3. Click "Preview Data" first to verify data

---

## Best Practices

1. **Always Preview First**
   - Preview data before exporting to verify accuracy
   - Check the source badges (green = membership system, yellow = attendance list)

2. **Set CPD Points**
   - Configure CPD points before exporting
   - Points can be updated and re-exported if needed

3. **Verify Member Data**
   - Cross-check membership numbers with official records
   - Verify email addresses are correct

4. **Regular Exports**
   - Export CPD data after each event
   - Keep exported CSV files for record-keeping

5. **Data Quality**
   - Ensure NRC/Passport numbers are correctly entered during registration
   - Use proper format: NRC (######/##/#), Passport (alphanumeric)

---

## File Locations

### Backend Files
- **App:** `/backend/apps/cpd/`
- **Models:** `/backend/apps/cpd/models.py`
- **Views:** `/backend/apps/cpd/views.py`
- **Services:** `/backend/apps/cpd/services.py`
- **Serializers:** `/backend/apps/cpd/serializers.py`
- **URLs:** `/backend/apps/cpd/urls.py`
- **Admin:** `/backend/apps/cpd/admin.py`

### Frontend Files
- **Page:** `/frontend/app/(admin)/cpd/page.tsx`
- **Sidebar:** `/frontend/components/layout/Sidebar.tsx`

### Configuration
- **Settings:** `/backend/config/settings/base.py` (INSTALLED_APPS)
- **URLs:** `/backend/config/urls.py` (API routing)

---

## Support

For issues or questions about the CPD Export Engine:

1. Check this documentation first
2. Review the troubleshooting section
3. Contact the development team
4. Check system logs for error details

---

**Last Updated:** March 26, 2026  
**Version:** 1.0.0
