# CC Soccer D11 - Installation Guide

This guide explains how to install and set up the CC Soccer Drupal 11 site for local development.

---

## Table of Contents

1. [Prerequisites](#prerequisites)
2. [Quick Start](#quick-start)
3. [Clean Install (Full Steps)](#clean-install-full-steps)
4. [Seeding Test Data](#seeding-test-data)
5. [Test Accounts](#test-accounts)
6. [Common Commands](#common-commands)
7. [Troubleshooting](#troubleshooting)
8. [Development History](#development-history)

---

## Prerequisites

Before you begin, ensure you have:

- **DDEV** installed ([Installation Guide](https://ddev.readthedocs.io/en/stable/users/install/))
- **Docker Desktop** running
- **Git** installed
- **Composer** (DDEV includes this)

Verify DDEV is working:
```bash
ddev version
```

---

## Quick Start

If you just want to get up and running quickly:

```bash
# Clone the repository
git clone https://github.com/caleb-ccsoccer/ccsoccer-d11.git
cd ccsoccer-d11

# Start DDEV
ddev start

# Install all dependencies (including drush, better_exposed_filters, etc.)
ddev composer install

# Install Drupal
ddev drush site:install standard --site-name="CC Soccer D11" --account-name=admin --account-pass=admin -y

# Fix Site UUID and delete conflicting entities
ddev drush config:set system.site uuid $(grep uuid config/sync/system.site.yml | awk '{print $2}') -y
ddev drush entity:delete shortcut_set default -y

# Import config (this enables ccsoccer and all dependencies)
ddev drush cim -y

# Run database updates
ddev drush updb -y
ddev drush cr

# Seed test data with users
ddev drush ccs-seed --users

# Launch the site
ddev launch
```

**Login:** admin / admin

---

## Clean Install (Full Steps)

Use these steps when you need to completely reset your local environment.

### Step 0: Export Config (If You Have Uncommitted Changes)

**IMPORTANT:** If you have made any configuration changes in the Drupal admin UI that haven't been exported, do this first:

```bash
# Export current config to config/sync/
ddev drush cex -y

# Review what changed
git status
git diff config/sync/

# Commit if needed
git add -A
git commit -m "Export config before clean install"
```

Skip this step if you're certain all config changes are already committed.

### Step 1: Remove Existing Installation

```bash
cd ~/Sites/ccsoccer-d11
ddev delete -O
cd ~/Sites
rm -rf ccsoccer-d11
```

### Step 2: Clone Fresh from GitHub

```bash
git clone https://github.com/caleb-ccsoccer/ccsoccer-d11.git
cd ccsoccer-d11
```

### Step 3: Start DDEV

```bash
ddev start
```

### Step 4: Install Dependencies

```bash
ddev composer install
```

### Step 5: Install Drupal

```bash
ddev drush site:install standard \
  --site-name="CC Soccer D11" \
  --account-name=admin \
  --account-pass=admin \
  -y
```

### Step 6: Fix Site UUID

The fresh install has a different UUID than the exported config. Fix it:

```bash
ddev drush config:set system.site uuid $(grep uuid config/sync/system.site.yml | awk '{print $2}') -y
```

### Step 7: Delete Conflicting Entities

The standard profile creates entities that conflict with config import:

```bash
ddev drush entity:delete shortcut_set default -y
```

### Step 8: Import Configuration

**IMPORTANT:** This must happen BEFORE enabling ccsoccer manually. The config import enables all modules atomically and avoids entity conflicts.

```bash
ddev drush cim -y
```

### Step 9: Run Database Updates

Run any pending updates and clear cache:

```bash
ddev drush updb -y
ddev drush cr
```

### Step 10: Validate Installation

```bash
# Check module is installed
ddev drush pml | grep ccsoccer

# Verify database tables exist
ddev drush sql-query "SHOW TABLES LIKE 'league';"
ddev drush sql-query "SHOW TABLES LIKE 'season';"
ddev drush sql-query "SHOW TABLES LIKE 'tournament';"
ddev drush sql-query "SHOW TABLES LIKE 'team';"
ddev drush sql-query "SHOW TABLES LIKE 'game';"
ddev drush sql-query "SHOW TABLES LIKE 'credits';"
ddev drush sql-query "SHOW TABLES LIKE 'ccsoccer_registration';"

# Verify checkout flow config (credits should be on 'credits' step)
ddev drush cget commerce_checkout.commerce_checkout_flow.ccsoccer configuration.panes.ccsoccer_credits --format=yaml
# Expected: step: credits

ddev drush cget commerce_checkout.commerce_checkout_flow.ccsoccer configuration.panes.payment_process --format=yaml
# Expected: step: payment
```

### Step 11: Seed Test Data

Choose ONE of the seeding options below based on your needs (see [Seeding Test Data](#seeding-test-data)).

### Step 12: Launch

```bash
ddev launch
```

---

## Seeding Test Data

The seed command has different modes for different testing purposes. **Choose the one that fits your needs.**

### Option A: Basic Seed with Test Users

**Use when:** You want basic leagues, seasons, tournaments, and test user accounts for general development.

```bash
ddev drush ccs-seed --users
```

**Creates:**
- 2 Leagues (Coed Tuesday, Men's 35+ Thursday)
- 6 Seasons (Fall 2025, Winter 2026, Spring 2026 for each league)
- 1 Tournament (SLO Friendly 2025)
- Team name taxonomy terms
- Jersey product with all size/style variations
- Test users: `player_test`, `board_test`, `slofriendly_test`, `captain_test`

---

### Option B: Registration Testing Data

**Use when:** You're testing the **registration flow** and need to see all possible registration states (open, closed, full, waitlisted, override offered, already registered, etc.).

```bash
ddev drush ccs-seed --test --force
```

**Creates:**
- All items from basic seed
- 7 test seasons in different states:
  - "TEST: Not Yet Open" - Registration hasn't opened
  - "TEST: Open - Spots Available" - Can register (5/20 spots filled)
  - "TEST: Full" - Season is full (10/10)
  - "TEST: Registration Closed" - Past close date
  - "TEST: On Waitlist" - testuser0 is waitlisted
  - "TEST: Override Offered" - testuser0 has override
  - "TEST: Already Registered" - testuser0 is registered
- 3 test tournaments in different states
- 195 test users (testuser0 through testuser195) with:
  - Gender (~30% female for coed testing)
  - Age (25-55 range)
  - Skill levels (1-5, weighted toward middle)
  - Goalie preferences (~10%)
- Bulk registrations with skill data
- Test groups (5 groups of 2-4 players)

**Note:** This option automatically runs `enhance-test-data` to populate demographics and skills.

**To see all states:** Log in as `testuser0` (password: `password`)

---

### Option C: Roster & Schedule Testing Data

**Use when:** You're testing the **roster builder** or **schedule generator** and need realistic player data with skills, ages, genders, and group assignments.

```bash
ddev drush ccs-seed --force --populate-seasons
```

**Creates:**
- All items from basic seed
- 180 test users with demographics:
  - testuser1-100: Coed only (mixed gender, ages 25-55)
  - testuser101-160: Men's 35+ only (male, ages 35-55)
  - testuser161-180: Both leagues (male, ages 35-55)
- Registrations with randomized:
  - Skill levels (1-5, weighted toward middle)
  - Goalie preferences (~10% prefer goalie)
- Teams auto-created from taxonomy terms
- Ready for roster balancing and schedule generation

---

### Option D: Tournament Testing Data

**Use when:** You're testing **tournament registration**, **team management**, or **tournament brackets** and need tournaments with teams and player registrations.

```bash
ddev drush ccs-seed --force --populate-tournaments
```

**Creates:**
- All items from basic seed
- 3 Tournaments (SLO Friendly 2024, 2025, 2026)
- 4 Teams for the 2025 tournament with:
  - Team captains assigned
  - Player registrations on each team
- Ready for tournament bracket and team management testing

---

### Seed Options Summary

| Option | Command | Purpose |
|--------|---------|---------|
| Basic + Users | `ccs-seed --users` | General development |
| Registration Testing | `ccs-seed --test --force` | Test registration states |
| Roster/Schedule Testing | `ccs-seed --force --populate-seasons` | Test team/schedule building |
| Tournament Testing | `ccs-seed --force --populate-tournaments` | Test tournament teams/brackets |

**Note:** `--test`, `--populate-seasons`, and `--populate-tournaments` are mutually exclusive - use only one of these options.

**The `--force` flag** deletes existing data before seeding. Omit it to skip existing items.

---

## Test Accounts

After seeding with `--users`, these accounts are available:

| Username | Password | Role | Purpose |
|----------|----------|------|---------|
| `admin` | `admin` | Administrator | Full site access |
| `player_test` | `password` | Authenticated | Regular player experience |
| `board_test` | `password` | Board Member | View reports, send notifications, update game status |
| `slofriendly_test` | `password` | Slofriendly | Tournament director (all board perms + tournament management) |
| `captain_test` | `password` | Authenticated | For testing captain flows |
| `testuser0` | `password` | Authenticated | "Me" user for seeing personalized states |
| `testuser1-195` | `password` | Authenticated | Bulk test users |

### Quick Login Links

```bash
# Generate one-time login links
ddev drush uli --name=admin
ddev drush uli --name=board_test
ddev drush uli --name=slofriendly_test
ddev drush uli --name=testuser0
```

### Using Masquerade

Administrators can impersonate any user using the Masquerade block in the footer. This is useful for testing different user experiences without logging out.

---

## Common Commands

### Drush Commands

```bash
# Seed commands
ddev drush ccs-seed                        # Basic seed (skips existing)
ddev drush ccs-seed --users                # Basic + test users
ddev drush ccs-seed --test --force         # Registration testing data
ddev drush ccs-seed --force --populate-seasons  # Roster/schedule testing data
ddev drush ccs-seed --force --populate-tournaments  # Tournament testing data

# Reset all CC Soccer data
ddev drush ccs-reset                       # Prompts for confirmation

# Roster commands
ddev drush ccs-rosters <season_id>         # Preview roster suggestions
ddev drush ccs-rosters <season_id> --apply # Apply roster assignments
ddev drush ccs-roster-state <season_id>    # Show current roster state

# Cache and updates
ddev drush cr                              # Clear all caches
ddev drush updb                            # Run database updates

# User management
ddev drush uli --name=USERNAME             # One-time login link
ddev drush user:password USERNAME PASSWORD # Change password
```

### DDEV Commands

```bash
ddev start              # Start the environment
ddev stop               # Stop the environment
ddev restart            # Restart the environment
ddev launch             # Open site in browser
ddev ssh                # SSH into web container
ddev describe           # Show environment info
ddev delete -O          # Delete environment (keeps files)
```

### Database Commands

```bash
# Access MySQL CLI
ddev drush sql-cli

# Export database
ddev drush sql-dump > backup.sql

# Import database
ddev drush sql-cli < backup.sql

# Quick table check
ddev drush sql-query "SELECT COUNT(*) FROM league;"
```

---

## Troubleshooting

### "No pending updates" but fields don't exist

**Symptom:** `drush updb` says no updates, but entity fields are missing.

**Cause:** Drupal's update tracking thinks updates ran, but the database was reset.

**Solution:**
```bash
# The update_9017 hook will ensure all required fields exist
ddev drush updb -y
ddev drush cr
```

### "'field_league' not found" during seed

**Symptom:** Seed command fails with `'field_league' not found` error.

**Cause:** The team_names taxonomy vocabulary wasn't created.

**Solution:**
```bash
ddev drush updb -y
ddev drush cr
ddev drush ccs-seed --users
```

### Entity tables don't exist

**Symptom:** Queries fail because tables like `league` or `season` don't exist.

**Solution:**
```bash
# Ensure module is enabled
ddev drush en ccsoccer -y

# Run updates to create tables
ddev drush updb -y
ddev drush cr

# If still missing, try reinstalling
ddev drush pmu ccsoccer -y
ddev drush en ccsoccer -y
ddev drush updb -y
```

### Config import fails with UUID mismatch

**Symptom:** `ddev drush cim` fails with "Site UUID in source storage does not match the target storage."

**Cause:** Fresh Drupal install has a different UUID than the exported config.

**Solution:**
```bash
ddev drush config:set system.site uuid $(grep uuid config/sync/system.site.yml | awk '{print $2}') -y
ddev drush cim -y
```

### Config import fails with entity conflicts

**Symptom:** `ddev drush cim` fails with "Entities exist of type Shortcut link" or "Product variation" errors.

**Cause:** You ran `ddev drush en ccsoccer` BEFORE `ddev drush cim`. The module's hook_install() created entities that now conflict with config import.

**Solution:** Start fresh and follow the correct order:
```bash
# Reset and start over
ddev drush site:install standard --site-name="CC Soccer D11" --account-name=admin --account-pass=admin -y

# Fix UUID FIRST
ddev drush config:set system.site uuid $(grep uuid config/sync/system.site.yml | awk '{print $2}') -y

# Delete shortcut conflicts
ddev drush entity:delete shortcut_set default -y

# Import config (this enables ccsoccer properly)
ddev drush cim -y

# Then continue with updb and seed
ddev drush updb -y
ddev drush cr
ddev drush ccs-seed --users
```

**Key Point:** Never run `ddev drush en ccsoccer` manually - let `ddev drush cim` enable it via core.extension.yml.

### Commerce store not found

**Symptom:** Errors about missing Commerce store.

**Solution:** The seed command auto-creates a store if missing. Just run:
```bash
ddev drush ccs-seed --users
```

### Permission denied errors

**Solution:**
```bash
# Fix file permissions
ddev exec chmod -R 777 web/sites/default/files
```

### "Class not found" errors

**Solution:**
```bash
# Clear all caches
ddev drush cr

# If still failing, rebuild Composer autoload
ddev composer dump-autoload
ddev drush cr
```

### Module won't enable

**Solution:**
```bash
# Check for missing dependencies
ddev drush pml | grep ccsoccer

# The ccsoccer module declares all dependencies in ccsoccer.info.yml
# so they should be enabled automatically. If issues persist:
ddev drush cr
ddev drush en ccsoccer -y
```

---

## Development History

### Project Overview

CC Soccer D11 is a Drupal 11 site for managing recreational soccer leagues. It replaces a legacy Drupal 7 site.

### Architecture Approach

The project was built incrementally following this structure:

1. **Phase 1: Core Entities** - League, Season, Tournament, Team, Game, Registration, Credits
2. **Phase 2: Registration Flow** - Commerce integration, checkout panes, payment processing
3. **Phase 3: Team & Schedule** - Roster builder with balancing algorithm, schedule generator
4. **Phase 4: Waitlist & Credits** - Override system, credit management, notifications
5. **Phase 5: Admin & Polish** - Admin UI, content pages, reports

### Current Status (~85% Complete)

**Complete:**
- ✅ All 10 custom entities
- ✅ Registration flow (season + tournament)
- ✅ Group management system
- ✅ Roster builder with drag-drop and balancing algorithm
- ✅ Schedule builder with round-robin generation
- ✅ Notification service (email/SMS)
- ✅ Game status with auto-reset and credits
- ✅ Credits system
- ✅ Season publishing with visibility flags
- ✅ Override system with admin UI
- ✅ Content pages (home, teams, schedule, my-schedule, my-teams, jerseys)
- ✅ Masquerade for testing

**In Progress:**
- ⏳ Schedule cancellation overlay (Andrew)

**Backlog:**
- Reports (City Payment, Insurance, Tournament Team, Jersey)
- Migration scripts from D7
- Mobile testing
- End-to-end testing

### Key Files

| File | Purpose |
|------|---------|
| `web/modules/custom/ccsoccer/` | Main module directory |
| `ccsoccer.install` | Installation hooks and updates |
| `src/Entity/` | All custom entities |
| `src/Service/` | Business logic services |
| `src/Form/` | Admin and user forms |
| `src/Controller/` | Page controllers |
| `src/Drush/Commands/` | Drush commands (seed, roster, etc.) |

### Documentation

| Document | Purpose |
|----------|---------|
| `INSTALLATION_GUIDE.md` | This file - setup instructions |
| `SESSION_HANDOFF.md` | Latest session summary and status |
| `PROJECT_STATUS.md` | Detailed project status |
| `ARCHITECTURE_DECISIONS.md` | Key architecture decisions |
| `REQUIREMENTS_TO_ARCHITECTURE.md` | Original requirements mapping |

---

## Getting Help

1. **Check SESSION_HANDOFF.md** - Latest project state and known issues
2. **Check this guide's Troubleshooting section** - Common problems and solutions
3. **Review the Drush commands** - `ddev drush ccs-seed --help`
4. **Check Drupal logs** - `ddev drush watchdog:show`

---

## Mobile Testing with DDEV

To test the site on a mobile device (iPhone, iPad, Android) on the same local network as your development Mac:

### Setup

1. **Enable bind_all_interfaces** in `.ddev/config.yaml`:
   ```yaml
   bind_all_interfaces: true
   ```

2. **Restart DDEV:**
   ```bash
   ddev restart
   ```

3. **Get your Mac IP address:**
   ```bash
   ipconfig getifaddr en0
   ```
   Example output: `192.168.68.111`

4. **Access from mobile device:**
   - Ensure your phone is on the same WiFi network as your Mac
   - Open Safari/Chrome on your phone
   - Navigate to: `http://192.168.68.111.ddev.site`
   - If you get a certificate warning (HTTPS), tap through to proceed

### Alternative: Direct Port Access

If the `.ddev.site` URL does not work, use direct port access:

```bash
ddev describe
```

Look for the HTTP port (e.g., `59684`), then access:
- `http://192.168.68.111:59684`

### Security Notes

- **Private network only:** The `192.168.x.x` address is only accessible on your local network
- **Router provides NAT firewall:** External internet users cannot access your dev site
- **Disable after testing:** Set `bind_all_interfaces: false` when done to lock down access

### Disable After Testing

1. **Edit `.ddev/config.yaml`:**
   ```yaml
   bind_all_interfaces: false
   ```

2. **Restart DDEV:**
   ```bash
   ddev restart
   ```

---

**Last Updated:** January 22, 2026
