# ✅ CANVA Member Card System - Implementation Complete

## 🎉 What Was Implemented

The member card system has been completely redesigned to use **server-side image generation with Pillow**, overlaying user data on your professional CANVA designs.

### Files Created/Modified

#### ✨ New Files
1. **`appauthentication/card_generator.py`**
   - Core Pillow-based card generator
   - Overlays user name, generation code, photo
   - Generates QR codes server-side
   - Creates circular profile photos

2. **`CANVA_CARD_SYSTEM.md`**
   - Complete technical documentation
   - Architecture overview
   - Troubleshooting guide

3. **`QUICK_SETUP_CANVA.md`**
   - Quick start guide
   - Coordinate reference
   - Testing checklist

4. **`setup_canva_cards.sh`**
   - Automated setup script
   - Installs dependencies
   - Runs migrations

#### 🔧 Modified Files
1. **`appauthentication/models.py`**
   - Added `CardTemplate` model (stores CANVA templates + coordinates)
   - Updated `GivingCircle` (added `card_template` foreign key)
   - Simplified `MemberCardConfig` (legacy fields kept for compatibility)

2. **`appauthentication/views.py`**
   - Added `generate_member_card()` - serves card as PNG image
   - Added `download_member_card()` - downloads card as PNG file
   - Added imports for MemberCardGenerator

3. **`appauthentication/urls.py`**
   - Added `/dashboard/card/generate/` endpoint
   - Added `/dashboard/card/download/` endpoint

4. **`appauthentication/admin.py`**
   - Added `CardTemplateAdmin` (manage templates)
   - Updated `GivingCircleAdmin` (show linked template)
   - Simplified `MemberCardConfigAdmin` (only QR URLs needed)

5. **`templates/appauthentication/dashboard.html`**
   - Replaced HTML/CSS card with server-generated image
   - Changed download button to direct link
   - Removed html2canvas and FileSaver.js dependencies

6. **`requirements.txt`**
   - Added `qrcode==8.0` (Pillow already present)

---

## 🚀 Next Steps - Action Required

### Step 1: Run Setup (5 minutes)

```bash
cd /home/cayledsn/Documents/DEVSECOPS/ESM/projectesm
./setup_canva_cards.sh
```

This will:
- ✓ Activate your virtual environment
- ✓ Install qrcode package
- ✓ Create database migrations
- ✓ Apply migrations

### Step 2: Upload CANVA Templates (10 minutes)

You have 4 CANVA designs:
1. `CARTE HERITAGE.png` (gold/brown)
2. `CARTE ROYAUME.png` (beige/cream)
3. `CARTE SOLEIL.png` (dark teal)
4. `CARTE TERANGA.png` (light teal)

**Upload them to Django Admin:**
1. Start server: `python manage.py runserver`
2. Open: `http://localhost:8000/admin/`
3. Go to: **Templates de carte** → **Add Template**
4. For each template:
   - Set name (Heritage, Royaume, Soleil, Teranga)
   - Set slug (heritage, royaume, soleil, teranga)
   - Upload image file
   - Use default coordinates (see QUICK_SETUP_CANVA.md)
   - Check "Active"
   - Save

### Step 3: Link Templates to Giving Circles (2 minutes)

Go to **Cercles de donateurs**, edit each:
- Teranga (€10) → Teranga template
- Soleil (€40) → Soleil template
- Royaume (€160) → Royaume template
- Héritage (€1000) → Heritage template

### Step 4: Configure QR Codes (1 minute)

Go to **Configuration carte membre**:
- QR Code 1 URL: `https://sponsor.enfantsoleilmonde.org/`
- QR Code 2 URL: `https://enfantsoleilmonde.org/`

### Step 5: Test with Sample User (5 minutes)

1. Create or use existing test user
2. In admin, edit their UserProfile:
   - Set `card_active = True`
   - Assign a giving circle
   - Upload a profile photo (optional)
3. Login as that user
4. Go to dashboard
5. Card should display!
6. Click "Télécharger PNG" to test download

### Step 6: Adjust Coordinates (if needed) (10-20 minutes)

If text doesn't align perfectly:
1. Go to **Templates de carte** in admin
2. Edit the template
3. Adjust X/Y coordinates slightly
4. Save
5. Refresh user dashboard to see changes
6. Repeat until perfect

---

## 📋 System Architecture

### Before (HTML/CSS System)
```
Dashboard → member_card.html (HTML/CSS template)
                ↓
         JavaScript (html2canvas)
                ↓
         Download as PNG
```

**Problems:**
- ❌ Limited design flexibility
- ❌ Client-side rendering inconsistencies
- ❌ Hard to maintain complex designs
- ❌ Heavy JavaScript dependencies

### After (CANVA + Pillow System)
```
Dashboard → generate_member_card view
                ↓
         MemberCardGenerator (Pillow)
                ↓
         CANVA Template + User Data
                ↓
         PNG Image (server-side)
                ↓
         Display/Download
```

**Benefits:**
- ✅ Professional CANVA designs
- ✅ Server-side = consistent rendering
- ✅ Easy to update designs (just upload new template)
- ✅ No client JavaScript needed
- ✅ High-quality output

---

## 🔍 How It Works

### User Requests Card

1. User visits `/dashboard/`
2. Dashboard template checks `profile.has_active_card`
3. If true, displays: `<img src="/dashboard/card/generate/">`
4. Browser requests `/dashboard/card/generate/`
5. Django calls `generate_member_card(request)` view

### Server Generates Card

1. View retrieves user's profile and config
2. Determines which CardTemplate to use (based on giving circle)
3. Instantiates `MemberCardGenerator(profile, config)`
4. Generator:
   - Opens template image (1050x600px)
   - Overlays user name at `(name_x, name_y)`
   - Overlays generation code at `(code_x, code_y)`
   - Crops and pastes user photo at `(photo_x, photo_y)` as circle
   - Generates QR code for donation URL, pastes at `(qr1_x, qr1_y)`
   - Generates QR code for website URL, pastes at `(qr2_x, qr2_y)`
5. Returns PNG image bytes as HTTP response

### User Downloads Card

1. User clicks "Télécharger PNG"
2. Browser requests `/dashboard/card/download/`
3. Same generation process, but response header = `attachment`
4. Browser saves as `carte-membre-{generation_code}.png`

---

## 🎨 Coordinate System Explained

Your CANVA templates are **1050 x 600 pixels**.

Coordinates are measured from **top-left corner**:

```
(0,0) ────────────────────────────────── (1050,0)
  │                                          │
  │    "User Full Name" at (720, 187)        │
  │                                          │
  │    "ESS-KBY-..." at (590, 290)          │
  │                                          │
  │         [QR]           [QR]              │
  │      (620,380)      (892,380)           │
  │                                          │
(0,600) ────────────────────────────────(1050,600)
```

**Example Calculation:**
- Card is 1050px wide
- You want name centered-right (about 70% from left edge)
- 1050 × 0.7 = 735px → Use `name_x = 720`
- You want name about 1/3 down from top
- 600 × 0.31 = 186px → Use `name_y = 187`

**Tip:** Open your CANVA PNG in an image editor (GIMP, Photoshop) and hover over the desired position to see exact coordinates!

---

## 📝 Configuration Summary

### CardTemplate Model (4 instances needed)

| Field | Purpose | Example |
|-------|---------|---------|
| `name` | Display name | "Heritage" |
| `slug` | Identifier | "heritage" |
| `template_image` | CANVA PNG file | Upload file |
| `name_x` | Name X position | 720 |
| `name_y` | Name Y position | 187 |
| `name_font_size` | Font size for name | 32 |
| `name_color` | Name text color | #000000 |
| `code_x` | Code X position | 590 |
| `code_y` | Code Y position | 290 |
| `code_font_size` | Font size for code | 20 |
| `code_color` | Code text color | #0094a0 |
| `photo_x` | Photo X position | 950 |
| `photo_y` | Photo Y position | 275 |
| `photo_size` | Photo diameter | 50 |
| `qr1_x` | QR1 X position | 620 |
| `qr1_y` | QR1 Y position | 380 |
| `qr2_x` | QR2 X position | 892 |
| `qr2_y` | QR2 Y position | 380 |
| `qr_size` | QR code size | 90 |
| `is_active` | Enable template | True |

---

## 🛠️ Maintenance

### Updating a Card Design

1. Export new design from CANVA (1050x600px PNG)
2. In admin, edit CardTemplate
3. Upload new image
4. Adjust coordinates if layout changed
5. Save
6. All users with that template see new design immediately!

### Adding a New Tier/Circle

1. Create new GivingCircle in admin
2. Create new CardTemplate (or reuse existing)
3. Link circle to template
4. Done!

### Changing QR Code Destinations

1. Edit MemberCardConfig
2. Update `qr_code_1_url` or `qr_code_2_url`
3. Save
4. All cards generate with new QR codes

---

## 🐛 Troubleshooting

### "Carte non disponible"
**Cause:** User's card not activated  
**Fix:** Set `UserProfile.card_active = True` in admin

### Error 500 when viewing card
**Cause:** Template file missing or invalid coordinates  
**Fix:** Check server logs, verify template uploaded, check coordinates within bounds

### Text doesn't appear
**Cause:** Wrong coordinates (outside image bounds)  
**Fix:** Reduce X/Y values, ensure X < 1050 and Y < 600

### QR codes missing
**Cause:** QR position outside bounds  
**Fix:** Verify `qr1_x`, `qr1_y`, `qr2_x`, `qr2_y` all < 1050/600

### Photo doesn't show
**Cause:** User has no profile photo uploaded  
**Fix:** Upload photo in UserProfile admin

---

## 📚 Documentation Files

- **`CANVA_CARD_SYSTEM.md`** - Complete technical documentation
- **`QUICK_SETUP_CANVA.md`** - Quick reference guide with coordinates
- **`setup_canva_cards.sh`** - Automated setup script

---

## ✅ Final Checklist

Before going live:

- [ ] Run `./setup_canva_cards.sh`
- [ ] Upload all 4 CANVA templates to admin
- [ ] Configure coordinates for each template
- [ ] Link templates to giving circles
- [ ] Set QR code URLs in config
- [ ] Test with sample user
- [ ] Verify download works
- [ ] Test QR codes scan correctly
- [ ] Adjust coordinates if needed
- [ ] Test on mobile devices
- [ ] Check MEDIA_ROOT permissions

---

## 🎯 Summary

You now have a **professional, maintainable, server-side card generation system** that:

1. ✅ Uses your exact CANVA designs
2. ✅ Generates cards dynamically with user data
3. ✅ Supports multiple card tiers/templates
4. ✅ Produces high-quality PNG downloads
5. ✅ Easy to update designs (just upload new template)
6. ✅ No complex frontend dependencies

**Total time to complete setup: ~30 minutes**

Ready to get started? Run:
```bash
./setup_canva_cards.sh
```

Then follow the steps in **QUICK_SETUP_CANVA.md**!

Good luck! 🚀
