# CANVA-Based Member Card System

## Overview

The new member card system uses **server-side image generation with Pillow** to overlay user data on professionally designed CANVA templates. This replaces the previous HTML/CSS-based card rendering system.

## Architecture

### Components

1. **CardTemplate Model** (`appauthentication/models.py`)
   - Stores CANVA template images (1050x600px)
   - Configurable positioning for all dynamic elements (name, code, photo, QR codes)
   - Each template has customizable font sizes and colors

2. **MemberCardGenerator** (`appauthentication/card_generator.py`)
   - Pillow-based image manipulation
   - Overlays user data on template images
   - Generates QR codes server-side
   - Creates circular cropped profile photos

3. **Views** (`appauthentication/views.py`)
   - `generate_member_card`: Serves card as inline PNG image
   - `download_member_card`: Serves card as downloadable PNG

4. **Models Integration**
   - `GivingCircle` → `CardTemplate`: Each giving circle can have its own template
   - `UserProfile.has_active_card`: Determines if user can see their card
   - `MemberCardConfig`: Singleton for QR code URLs

## Card Templates

### Available Templates (from CANVA)

1. **Heritage** (`heritage`) - Gold/brown gradient - Premium tier
2. **Royaume** (`royaume`) - Beige/cream gradient - High tier
3. **Soleil** (`soleil`) - Dark teal/gray - Mid tier
4. **Teranga** (`teranga`) - Light teal/gray - Entry tier

### Template Specifications

- **Image Size**: 1050x600 pixels
- **Format**: PNG or JPG
- **Elements to include**:
  - Logo areas (already in design)
  - Blank space for user name
  - Blank space for generation code
  - Space for profile photo (if desired)
  - Two QR code placeholder areas
  - Contact information (already in design)

### Coordinate System

The positioning system uses **pixel coordinates** from the top-left corner (0,0):

```
(0,0)
  ┌──────────────────────────────────────┐
  │                                      │
  │  User Name at (name_x, name_y)      │
  │                                      │
  │  Generation Code at (code_x, code_y) │
  │                                      │
  │  [Photo]  [QR1]  [QR2]              │
  │                                      │
  └──────────────────────────────────────┘
                                    (1050, 600)
```

## Setup Instructions

### 1. Install Dependencies

```bash
pip install -r requirements.txt
```

Dependencies added:
- `pillow==12.2.0` (already installed)
- `qrcode==8.0` (new)

### 2. Run Migrations

```bash
python manage.py makemigrations
python manage.py migrate
```

### 3. Upload CANVA Templates to Django Admin

1. Go to Django Admin → **Templates de carte**
2. Click **Add Template**
3. Fill in:
   - **Name**: Display name (e.g., "Heritage")
   - **Slug**: Identifier (e.g., "heritage")
   - **Template Image**: Upload your exported CANVA PNG (1050x600px)
   - **Position coordinates**: See "Finding Coordinates" below
   - **Font sizes**: Adjust based on your design
   - **Colors**: Hex codes for text colors
4. Set **Active** = True
5. Save

### 4. Link Templates to Giving Circles

1. Go to **Cercles de donateurs**
2. Edit each circle
3. Select appropriate **Template de carte**
4. Save

Example mapping:
- Teranga (€10/month) → Teranga template
- Soleil (€40/month) → Soleil template
- Royaume (€160/month) → Royaume template
- Héritage (€1000/month) → Heritage template

### 5. Configure QR Code URLs

1. Go to **Configuration carte membre**
2. Set:
   - **QR Code 1 URL**: Donation page (e.g., `https://sponsor.enfantsoleilmonde.org/`)
   - **QR Code 2 URL**: Main website (e.g., `https://enfantsoleilmonde.org/`)
3. Save

## Finding Coordinates for Templates

### Method 1: Using GIMP/Photoshop

1. Open your CANVA template in GIMP or Photoshop
2. Use the **Info** panel or move cursor to desired position
3. Note X and Y coordinates (use top-left corner of text/element)
4. Enter these values in Django admin

### Method 2: Trial and Error

1. Start with estimated coordinates
2. Generate a test card from admin
3. Adjust coordinates in admin
4. Regenerate until positioned correctly

### Recommended Coordinates (for reference)

Based on your CANVA designs:

```python
# User Name (Large bold text)
name_x = 720
name_y = 187
name_font_size = 32

# Generation Code (Smaller monospace)
code_x = 590
code_y = 290
code_font_size = 20

# Profile Photo (circular, top-right)
photo_x = 950
photo_y = 275
photo_size = 50  # diameter

# QR Codes (90x90px each)
qr1_x = 620   # Left QR (DON)
qr1_y = 380
qr2_x = 892   # Right QR (Website)
qr2_y = 380
qr_size = 90
```

## Customization

### Adjusting Text Style

Edit in `card_generator.py`:

```python
def _get_font_path(self, font_name):
    # Add custom font paths here
    font_paths = [
        '/path/to/custom/font.ttf',
        # ...existing paths
    ]
```

### Changing Colors

Colors are configured per CardTemplate in Django admin using hex codes:
- `name_color`: Color for user's name
- `code_color`: Color for generation code

### Photo Styling

The photo is automatically:
- Cropped to circular shape
- Resized to `photo_size` diameter
- Centered at `(photo_x, photo_y)`

## Usage

### For End Users

1. User logs into dashboard
2. If `card_active = True` and they have a giving circle, card displays
3. Card is dynamically generated on each page load
4. Click "Télécharger PNG" to download high-quality version

### For Administrators

1. **Activate a card**: Set `UserProfile.card_active = True` in admin
2. **Change template**: Assign different template to user's giving circle
3. **Update design**: Upload new template image (coordinates remain same)

## Troubleshooting

### Card not displaying

- Check `UserProfile.card_active` is `True`
- Check user has a `giving_circle` assigned
- Check giving circle has a `card_template` assigned
- Check template `is_active = True`

### Text positioning is off

- Adjust `name_x`, `name_y`, `code_x`, `code_y` in CardTemplate admin
- Coordinates are from **top-left** corner
- Try small increments (±10-20 pixels)

### QR codes not appearing

- Check `MemberCardConfig` has valid URLs
- Ensure QR position coordinates are within image bounds (0-1050, 0-600)

### Font not loading

- Default system fonts are used automatically
- For custom fonts, add path to `_get_font_path()` in `card_generator.py`

### Photo not circular

- Check photo file exists and is accessible
- Verify `photo_size` is reasonable (30-100 pixels)

## Migration from Old System

The old HTML/CSS card system is **no longer used**. Legacy fields in `MemberCardConfig` are kept for backward compatibility but collapsed in admin.

To complete migration:
1. Upload all 4 CANVA templates
2. Configure coordinates for each
3. Link templates to giving circles
4. Test with sample user accounts

## Performance Notes

- Cards are generated **on-demand** (not pre-cached)
- Generation time: ~100-300ms per card
- Consider caching generated cards if load becomes high
- Image served directly from memory (no disk writes)

## Future Enhancements

Possible improvements:
- Cache generated cards with Redis/Memcached
- Pre-generate cards on profile update
- Add card version/revision tracking
- Support multiple card sizes/formats
- Batch card generation for printing

## Support

For questions or issues with the CANVA card system:
- Check server logs for Python errors
- Verify Pillow and qrcode are installed correctly
- Ensure MEDIA_ROOT is writable for template uploads
- Test coordinate positioning with sample accounts
