# Enhanced Database Seeder - Implementation Guide

## Overview

I've created a comprehensive database seeder for your Orion platform that significantly expands coverage beyond your original implementation. The new seeder creates realistic test data across all your database models.

## What's New

### Original Seeder Coverage
- ✓ Admin user
- ✓ 2 Stores (TESTSTORE, ORION)

### Enhanced Seeder Coverage
- ✓ Admin user + multiple test users (stores, customers)
- ✓ 3 Stores with different themes and configurations
- ✓ Custom domains for stores
- ✓ Store themes with different presets (modern, classic, vibrant)
- ✓ 5 Sample marketplace products
- ✓ Store-product relationships
- ✓ Multiple customers with addresses
- ✓ Sample orders with order items
- ✓ Import jobs
- ✓ Admin settings (platform configuration)
- ✓ Platform alerts (system monitoring)
- ✓ **CMS Content Pages** (platform defaults: about, contact, FAQ, shipping, returns, privacy, terms)

## Files Created

1. **seed_database.py** - Enhanced seeder script (placed in /mnt/user-data/outputs/)
2. **makefile_additions.txt** - Commands to add to your Makefile

## Makefile Integration

Add these commands to your Makefile in the DATABASE section (after backup-db):

```makefile
seed:
	@echo Seeding database with comprehensive test data...
	$(PYTHON) scripts/seed_database.py
	@echo Seeding completed successfully

seed-minimal:
	@echo Seeding database with minimal data (admin + 1 store)...
	$(PYTHON) scripts/seed_database.py --minimal
	@echo Minimal seeding completed

seed-reset:
	@echo WARNING: This will DELETE ALL existing data!
	$(PYTHON) scripts/seed_database.py --reset
	@echo Database reset and seeded

# Complete database setup (migrate + seed)
db-setup: migrate-up seed
	@echo Database setup complete!
	@echo Run 'make dev' to start development server

db-reset: migrate-down migrate-up seed-reset
	@echo Database completely reset!
```

Add these help entries to the help section (under === DATABASE ===):

```makefile
	@echo   seed                 - Seed database with comprehensive test data
	@echo   seed-minimal         - Seed minimal data (admin + 1 store)
	@echo   seed-reset           - Reset and seed database (destructive!)
	@echo   db-setup             - Complete database setup (migrate + seed)
	@echo   db-reset             - Complete database reset
```

## Usage

### 1. Install the Seeder
Copy the seed_database.py file to your scripts directory:
```bash
cp seed_database.py scripts/seed_database.py
```

### 2. Run Seeding Commands

#### Option A: Full Comprehensive Seeding (Recommended for Development)
```bash
make seed
# or
python scripts/seed_database.py
```

This creates:
- 1 admin user
- 3 test users (2 stores, 1 customer)
- 3 stores (ORION, FASHIONHUB, BOOKSTORE)
- 5 marketplace products
- 10 store-product links
- 4 customers
- 8 addresses
- 2 orders
- 2 import jobs
- 4 admin settings
- 2 platform alerts

#### Option B: Minimal Seeding (Quick Setup)
```bash
make seed-minimal
# or
python scripts/seed_database.py --minimal
```

This creates only:
- 1 admin user
- 1 store (ORION)

#### Option C: Reset and Seed (Fresh Start)
```bash
make seed-reset
# or
python scripts/seed_database.py --reset
```

⚠️ **WARNING**: This DELETES ALL existing data!

#### Option D: Complete Database Setup (Migration + Seed)
```bash
make db-setup
```

This runs:
1. `make migrate-up` (apply migrations)
2. `make seed` (seed data)

## Test Data Details

### Users Created

| Username | Email | Password | Role |
|----------|-------|----------|------|
| admin | admin@orion.lu | admin123 | admin |
| store1 | store1@example.com | password123 | store |
| store2 | store2@example.com | password123 | store |
| customer1 | customer1@example.com | password123 | customer |

### Stores Created

| Code | Name | Subdomain | Theme | Custom Domain | Notes |
|------|------|-----------|-------|---------------|-------|
| WIZATECH | WizaTech | wizatech | modern | wizatech.shop (OMS) | `custom_subdomain="wizatech-rewards"` on Loyalty `StorePlatform` |
| WIZAGADGETS | WizaGadgets | wizagadgets | modern | (none) | |
| WIZAHOME | WizaHome | wizahome | classic | (none) | |
| FASHIONHUB | Fashion Hub | fashionhub | vibrant | fashionhub.store (Loyalty) | |
| FASHIONOUTLET | Fashion Outlet | fashionoutlet | vibrant | (none) | |
| BOOKSTORE | The Book Store | bookstore | classic | (none) | |
| BOOKDIGITAL | BookWorld Digital | bookdigital | modern | (none) | |

**Per-platform subdomain demo:** WizaTech has both OMS and Loyalty subscriptions. On the Loyalty platform, its `StorePlatform.custom_subdomain` is set to `"wizatech-rewards"`, meaning `wizatech-rewards.rewardflow.lu` resolves to the same store as `wizatech.omsflow.lu`.

**Multi-platform custom domains:** `StoreDomain` records now include a `platform_id` linking the domain to a specific platform. For example, `wizatech.shop` is linked to the OMS platform and `fashionhub.store` is linked to the Loyalty platform.

### Products Created

1. **Wireless Bluetooth Headphones** - $149.99
   - Brand: AudioTech
   - GTIN: 1234567890123

2. **Smart Watch Pro** - $299.99
   - Brand: TechWear
   - GTIN: 1234567890124

3. **Portable Bluetooth Speaker** - $79.99
   - Brand: AudioTech
   - GTIN: 1234567890125

4. **Wireless Charging Pad** - $39.99
   - Brand: ChargeMax
   - GTIN: 1234567890126

5. **4K Webcam** - $129.99
   - Brand: VisionTech
   - GTIN: 1234567890127

### Theme Presets Available

The seeder includes 5 built-in theme presets:

1. **default** - Indigo and purple, Inter font
2. **modern** - Blue and cyan, Poppins font, transparent header
3. **classic** - Deep blue and purple, Georgia serif font
4. **vibrant** - Pink and orange, colorful background
5. **minimal** - Black and white, Helvetica font

## Features

### 1. Idempotent Operations
- Safe to run multiple times without --reset flag
- Checks for existing records before creating
- Reports what was created vs. what already existed

### 2. Comprehensive Coverage
- Tests all major database models
- Creates realistic relationships between entities
- Includes edge cases (pending orders, completed orders, etc.)

### 3. Better Output
- Beautiful formatted output with boxes and sections
- Color-coded success/info/error messages
- Detailed summary with database statistics
- Quick reference for login credentials and URLs

### 4. Command-Line Arguments
```bash
python scripts/seed_database.py [--reset] [--minimal]

--reset    : Drop all data before seeding (destructive!)
--minimal  : Create only essential data (admin + 1 store)
```

### 5. Proper Error Handling
- Verifies database is ready before seeding
- Rolls back on errors
- Provides helpful error messages
- Suggests solutions for common issues

## Testing Access

### Admin Panel
- URL: `http://localhost:8000/admin/login`
- Username: `admin`
- Password: `admin123`

### Store Storefronts (Development)
- WIZATECH (OMS): `http://localhost:8000/platforms/oms/storefront/WIZATECH/`
- WIZATECH (Loyalty): `http://localhost:8000/platforms/loyalty/storefront/WIZATECH/`
- FASHIONHUB: `http://localhost:8000/platforms/loyalty/storefront/FASHIONHUB/`
- BOOKSTORE: `http://localhost:8000/platforms/oms/storefront/BOOKSTORE/`

### Store Dashboards (Development)
- WIZATECH: `http://localhost:8000/platforms/oms/store/WIZATECH/dashboard`
- FASHIONHUB: `http://localhost:8000/platforms/loyalty/store/FASHIONHUB/dashboard`

## Example Output

```
╔════════════════════════════════════════════════════════════════════╗
║                  ORION DATABASE SEEDER                          ║
╚════════════════════════════════════════════════════════════════════╝

STEP 1: Verifying database...
  ✓ Database tables verified

════════════════════════════════════════════════════════════════════════
                     COMPREHENSIVE SEEDING
════════════════════════════════════════════════════════════════════════

STEP 1: Creating users...
  ✓ Admin user created (ID: 1)
  ✓ User 'store1' created (ID: 2)
  ✓ User 'store2' created (ID: 3)
  ✓ User 'customer1' created (ID: 4)

STEP 2: Creating stores...
  ✓ ORION created (ID: 1)
  ✓   Theme 'modern' applied
  ✓   Custom domain 'orion.shop' added
  ✓ FASHIONHUB created (ID: 2)
  ✓   Theme 'vibrant' applied
  ✓   Custom domain 'fashionhub.store' added
  ✓ BOOKSTORE created (ID: 3)
  ✓   Theme 'classic' applied

...

════════════════════════════════════════════════════════════════════════
                          SEEDING SUMMARY
════════════════════════════════════════════════════════════════════════

📊 Database Statistics:
  Users:               4
  Stores:             3
  Store Themes:       3
  Custom Domains:      2
  Marketplace Products: 5
  Store Products:     10
  Customers:           4
  Addresses:           8
  Orders:              2
  Order Items:         4
  Import Jobs:         2
  Admin Settings:      4
  Platform Alerts:     2
```

## Configuration

You can customize the seeder by editing the configuration constants at the top of the file:

```python
# Admin credentials
DEFAULT_ADMIN_EMAIL = "admin@orion.lu"
DEFAULT_ADMIN_USERNAME = "admin"
DEFAULT_ADMIN_PASSWORD = "admin123"

# Store configurations
STORE_CONFIGS = [...]

# Test users
TEST_USERS = [...]

# Sample products
SAMPLE_PRODUCTS = [...]

# Theme presets
THEME_PRESETS = {...}
```

## Migration Path from Old Seeder

If you're currently using the old seed_database.py:

1. Backup your current seeder:
   ```bash
   mv scripts/seed_database.py scripts/seed_database.old.py
   ```

2. Install new seeder:
   ```bash
   cp seed_database.py scripts/seed_database.py
   ```

3. Run with minimal flag first to test:
   ```bash
   make seed-minimal
   ```

4. If satisfied, run full seeding:
   ```bash
   make seed
   ```

## Troubleshooting

### Error: "Database not ready"
**Solution**: Run migrations first
```bash
make migrate-up
```

### Error: "Table doesn't exist"
**Solution**: Make sure all migrations are applied
```bash
alembic upgrade head
```

### Error: "Foreign key constraint failed"
**Solution**: Reset database and try again
```bash
make seed-reset
```

### Error: Import errors
**Solution**: Make sure you're in the project root and virtual environment is activated
```bash
source venv/bin/activate  # Linux/Mac
venv\Scripts\activate     # Windows
```

## CMS Content Pages

The platform includes a comprehensive CMS (Content Management System) for managing static content pages.

### Creating Default CMS Pages

To create platform-level default content pages (About, Contact, FAQ, Shipping, Returns, Privacy, Terms):

```bash
make create-cms-defaults
# or
python scripts/seed/create_default_content_pages.py
```

This creates 7 platform default pages that all stores inherit:

| Slug | Title | Show in Footer | Show in Header |
|------|-------|----------------|----------------|
| about | About Us | ✓ | ✓ |
| contact | Contact Us | ✓ | ✓ |
| faq | Frequently Asked Questions | ✓ | ✗ |
| shipping | Shipping Policy | ✓ | ✗ |
| returns | Return & Refund Policy | ✓ | ✗ |
| privacy | Privacy Policy | ✓ | ✗ |
| terms | Terms of Service | ✓ | ✗ |

**Features:**
- **Platform Defaults**: Created with `store_id=NULL`, available to all stores
- **Store Overrides**: Stores can create custom versions with the same slug
- **Automatic Fallback**: System checks store override first, falls back to platform default
- **Navigation**: Pages marked with `show_in_footer` appear in storefront footer automatically
- **Idempotent**: Script skips pages that already exist

**Access URLs:**
- `/about` - About Us page
- `/contact` - Contact page
- `/faq` - FAQ page
- `/shipping` - Shipping Policy
- `/returns` - Return Policy
- `/privacy` - Privacy Policy
- `/terms` - Terms of Service

### Integration with db-setup

The `make db-setup` command automatically includes CMS defaults:

```bash
make db-setup
# Runs: migrate-up → init-prod → create-cms-defaults → seed-demo
```

## Best Practices

1. **Development**: Use `make seed` for full test data
2. **Quick Testing**: Use `make seed-minimal` for fast setup
3. **Fresh Start**: Use `make seed-reset` when testing migrations
4. **CMS Pages**: Run `make create-cms-defaults` after migrations
5. **Production**: Never run the seeder in production!

## Security Notes

⚠️ **IMPORTANT**:
- Default passwords are simple for development convenience
- Change ALL default passwords in production environments
- The admin password is intentionally weak for local development
- Never commit sensitive credentials to version control

## Future Enhancements

Consider adding:
- More diverse product categories
- Different store statuses (pending, suspended)
- Customer order history variations
- Failed import jobs
- More complex inventory scenarios
- Payment transactions
- Store subscriptions
- Product reviews and ratings
