# CC Soccer D11 - Session Handoff

**Status:** Schedule Builder UI implemented with drag-drop grid and week navigation

**Last Updated:** December 31, 2024

---

## **Current State - WORKING ✅**

### **Environment:**
- DDEV running Drupal 11
- Database: MySQL
- Git repo: Active, pushed to GitHub
- Site URL: http://ccsoccer-d11.ddev.site/
- Mailhog: http://ccsoccer-d11.ddev.site:8026

### **Core Systems Complete:**
- ✅ All 7 custom entities implemented and working
- ✅ Registration entity (custom, not contrib)
- ✅ Waitlist entity with override system
- ✅ Invitation entity for group/team invitations
- ✅ Commerce integration (products auto-created for seasons/tournaments)
- ✅ Notification system (email via Symfony Mailer, SMS via Clickatell)
- ✅ Complete checkout flow with custom panes
- ✅ Group management for seasons
- ✅ Team management for tournaments
- ✅ Order completion subscriber creating registrations
- ✅ Roles & permissions system with access control
- ✅ Captain access control for tournament teams
- ✅ **Schedule Builder with drag-drop UI**

### **User-Facing Pages Working:**
- `/register` - Main registration page with state-based cards
- `/my-registrations` - User's active registrations
- `/my-group/{registration}` - Group/team management
- `/tournament/{tournament}/team/{team}/manage` - Captain team management (UI TODO)
- `/admin/ccsoccer/schedule/{season}` - **Schedule Builder (NEW)**

### **Test Data System:**
```bash
# Seed comprehensive test data (7 seasons + 3 tournaments)
ddev drush ccs-seed --test --force

# Seed with test users (board_test, slofriendly_test, etc)
ddev drush ccs-seed --users

# Test user credentials:
Username: testuser0 (or board_test, slofriendly_test, etc)
Password: password
```

---

## **Major Accomplishment This Session**

### **Implemented Schedule Builder UI**

**Goal:** Create an interactive schedule builder allowing admins to generate, view, and manually adjust game schedules with drag-and-drop functionality.

**Implementation:**

#### **1. Schedule Builder Form (`ScheduleBuilderForm.php`)**

**Features:**
- Configuration panel (collapsible) with:
  - Start/End date pickers
  - Day of week selector
  - Time slots with configurable field counts
  - Add/Remove time slot buttons
  - Dynamic capacity calculator ("7 games/week = 14 teams needed")
  - Bye week date pickers with day-of-week validation
  - Add bye week button

- Visual schedule grid:
  - Table layout with dates as columns, time slots as rows
  - Each cell shows home team (pink) and away team (white)
  - Bye weeks shown as gray "No games" columns
  - Future weeks (2 months past season end) shown as lighter gray

- Action buttons:
  - Generate New Schedule
  - Fill Empty Slots
  - Publish Schedule
  - Unpublish
  - Clear All Games

**File:** `src/Form/ScheduleBuilderForm.php`

#### **2. Schedule Generator Service (`ScheduleGeneratorService.php`)**

**Algorithm:**
- Round-robin matchup generation (all teams play each other)
- Matchup prioritization (least-played matchups first)
- Time slot balancing (teams distributed across early/late games)
- Bye week handling
- Game entity creation with proper field assignments

**Key Methods:**
- `generateSchedule()` - Main entry point
- `selectMatchupsForWeek()` - Picks non-repeating matchups
- `assignToTimeSlots()` - Balances time slots
- `getScheduleState()` - Returns current schedule for display
- `validateMove()` - Validates drag-drop moves
- `moveTeam()` - Executes team swaps

**File:** `src/Service/ScheduleGeneratorService.php`

#### **3. JavaScript Drag-Drop & Navigation (`schedule-builder.js`)**

**Features:**
- Prev/Next navigation buttons to scroll through weeks
- Auto-scroll to current week on page load
- Responsive week count (3-10 weeks visible based on viewport)
- Drag-and-drop team placement
- Workbench for temporarily holding teams
- Toast notifications for feedback
- Capacity calculator real-time updates
- Bye week day-of-week validation warnings

**File:** `js/schedule-builder.js`

#### **4. Styling (`schedule-builder.css`)**

**Visual Design:**
- Clean grid layout with colored headers
- Time slot labels in green
- Home team cells in pink, away team in white
- Bye weeks in medium gray
- Future weeks in lighter gray
- Blue navigation buttons
- Workbench with dashed border
- Toast notifications (success/error/info)

**File:** `css/schedule-builder.css`

#### **5. Routes & Controller**

**Routes Added:**
- `ccsoccer.schedule_builder` - Main builder page
- `ccsoccer.schedule_builder_move` - AJAX move endpoint
- `ccsoccer.schedule_builder_validate` - AJAX validation endpoint
- `ccsoccer.schedule_builder_state` - AJAX state endpoint
- `ccsoccer.schedule_builder_distribution` - Time slot analysis
- `ccsoccer.my_schedule` - Player's personal schedule view

**File:** `src/Controller/ScheduleController.php`

#### **6. Library Registration**

```yaml
# ccsoccer.libraries.yml
schedule-builder:
  css:
    theme:
      css/schedule-builder.css: {}
  js:
    js/schedule-builder.js: {}
  dependencies:
    - core/drupal
    - core/jquery
    - core/drupalSettings
```

---

## **Schedule Builder UI Details**

### **Navigation Header**
- Shows season name (e.g., "Coed Winter 2026")
- Prev/Next buttons scroll one week at a time
- Buttons disabled at start/end of range
- Auto-scrolls to current week on load

### **Grid Display**
- Columns: Game dates (Mon Jan 6, Mon Jan 13, etc.)
- Rows: Time slots × Fields (6:00 PM Field 1, 6:00 PM Field 2, etc.)
- Gray spacer bars separate time slot groups

### **Week Types**
| Type | Header Color | Cell Color | Shows |
|------|--------------|------------|-------|
| Regular | Dark gray | White/Pink | Team names |
| Bye Week | Medium gray | Light gray | "No games" |
| Future | Lighter gray | Lighter gray | "No games" |

### **Drag and Drop**
- Drag team name to swap positions
- Drop on workbench to temporarily hold
- Workbench teams can be dragged to game slots
- Validation prevents team from playing twice in same week
- AJAX saves changes immediately

### **Calendar Extension**
- Extends 2 months past season end date
- Ensures end-of-season view has games on left, future on right
- Supports proper scrolling behavior throughout season

---

## **Files Created/Modified This Session**

### **New Files:**
- `src/Form/ScheduleBuilderForm.php` - Main form with grid building
- `src/Service/ScheduleGeneratorService.php` - Schedule generation algorithm
- `src/Controller/ScheduleController.php` - AJAX endpoints and display
- `js/schedule-builder.js` - Drag-drop and navigation
- `css/schedule-builder.css` - Grid and UI styling

### **Modified Files:**
- `ccsoccer.routing.yml` - Added 6 schedule routes
- `ccsoccer.services.yml` - Registered ScheduleGeneratorService
- `ccsoccer.libraries.yml` - Added schedule-builder library

---

## **Architecture Decisions**

### **Custom Registration Entity (Not Contrib)**
**Decision:** Built completely custom Registration entity instead of extending contrib Registration module.

**Rationale:**
- Contrib Registration designed for "host entity" pattern
- Our use case: Direct entity references (player → season, player → tournament)
- Full control over complex field requirements

### **Captain as Entity Relationship (Not Role)**
**Decision:** Captain is a field on Team entity, not a Drupal role.

**Rationale:**
- Captains are per-team, not global
- Same user can be captain of multiple teams
- Custom access checker handles programmatic access control

### **Schedule State from Game Entities**
**Decision:** Schedule displayed by querying Game entities, not stored separately.

**Rationale:**
- Single source of truth (Game entity)
- No sync issues between schedule and games
- Drag-drop directly updates Game entities

### **Calendar Extension for End-of-Season**
**Decision:** Display extends 2 months past season end with "No games" weeks.

**Rationale:**
- Allows current week to always appear on left
- End of season doesn't result in sparse display
- Natural scrolling behavior throughout season

---

## **Next Session Priorities**

### **1. Fix Repeat Games Issue**
Current algorithm may create repeat matchups (same teams playing twice). Need to:
- Add stronger constraints to prevent any repeats when possible
- Add randomization to prevent deterministic patterns
- Consider implementing true round-robin algorithm

### **2. Build Captain Team Management UI**
Controller stubs exist, need actual implementation:
- Team roster display with member details
- Invitation form and handler
- Remove player confirmation and logic
- Team notification form functionality

### **3. Schedule Validation**
- Verify no team plays twice in same week
- Check for orphaned games
- Add schedule completeness report

### **4. Public Schedule Display**
- Create template for public schedule view
- Add to season page
- Implement "My Schedule" for logged-in players

---

## **Testing Schedule Builder**

### **Access the Builder:**
```bash
# Get admin login link
ddev drush uli

# Navigate to: /admin/ccsoccer/schedule/{season_id}
# Example: /admin/ccsoccer/schedule/1
```

### **Generate a Schedule:**
1. Open Schedule Configuration panel
2. Set start/end dates
3. Configure time slots and fields
4. Add any bye weeks
5. Click "Generate New Schedule"

### **Test Navigation:**
1. Click Next/Prev buttons
2. Verify weeks scroll correctly
3. Verify current week appears on left on page load

### **Test Drag-Drop:**
1. Drag a team name
2. Drop on another team slot
3. Verify swap occurs
4. Check workbench functionality

---

## **Known Issues / TODO**

### **Repeat Games**
**Status:** Algorithm may create repeat matchups
**Impact:** Same teams could play multiple times in a season
**Fix:** Strengthen matchup selection constraints

### **Captain UI - Not Yet Built**
**Status:** Access control complete, controller methods are stubs
**Files with TODO:**
- `src/Controller/TournamentController.php`
- `src/Form/TournamentTeamNotificationForm.php`

### **Role Import for Collaborators**
When pulling from git, run:
```bash
ddev drush config:import --partial --source=modules/custom/ccsoccer/config/install -y
ddev drush cr
```

---

## **Commands to Remember**

### **Daily Development:**
```bash
# Start DDEV
ddev start

# Clear cache (do often!)
ddev drush cr

# Fresh test data with users
ddev drush ccs-seed --test --users --force

# Check Mailhog for emails
open http://ccsoccer-d11.ddev.site:8026

# Git workflow
git pull
git status
git add .
git commit -m "message"
git push origin main
```

### **Schedule Builder:**
```bash
# Access schedule builder for season 1
# URL: /admin/ccsoccer/schedule/1

# Check games for a season
ddev drush sqlq "SELECT id, home_team, away_team, game_date, week_number FROM game WHERE season = 1 ORDER BY game_date, game_time"

# Clear games for fresh generation
ddev drush sqlq "DELETE FROM game WHERE season = 1"
ddev drush cr
```

### **Role & Permission Testing:**
```bash
# Create test users with roles
ddev drush ccsoccer:seed-users

# Log in as specific user
ddev drush uli --name=board_test
ddev drush uli --name=slofriendly_test
```

---

## **Collaboration Notes**

**Team:**
- Caleb - Lead developer
- Andrew (abmeade@hotmail.com) - Roster building and schedule generation

**Git Workflow:**
- **ALWAYS** `git pull` before `git push`
- Commit working states frequently
- Clear commit messages

**After Pulling Changes:**
```bash
ddev drush config:import --partial --source=modules/custom/ccsoccer/config/install -y
ddev drush cr
```

---

## **Test User Quick Reference**

| Username | Password | Role | Can Access |
|----------|----------|------|------------|
| `admin` | (existing) | Administrator | Everything |
| `testuser0` | `password` | Player | Register, own data, manage groups |
| `board_test` | `password` | Board Member | View reports, send notifications, update game status |
| `slofriendly_test` | `password` | Slofriendly | Board Member perms + manage tournaments |
| `captain_test` | `password` | Player | Becomes captain when assigned to Team.captain field |

---

## **Success Metrics**

**This Session:**
- ✅ Schedule Builder form with configuration panel
- ✅ Visual schedule grid with time slots and weeks
- ✅ Drag-and-drop team placement
- ✅ Workbench for temporary team holding
- ✅ Prev/Next week navigation
- ✅ Auto-scroll to current week
- ✅ Calendar extends 2 months past season end
- ✅ Bye weeks and future weeks displayed
- ✅ Dynamic capacity calculator
- ✅ Bye week day-of-week validation
- ✅ AJAX move endpoint with validation
- ✅ Responsive design (3-10 weeks based on viewport)

**Next Session Goal:**
- Fix repeat games in schedule generation
- Build captain team management UI
- Add schedule validation/reports
- Create public schedule display

---

## **Important Reminders**

- **Schedule is generated from Game entities** - no separate schedule storage
- **Navigation shows season name** - not week numbers
- **Calendar extends 2 months** - for proper end-of-season display
- **Drag-drop saves immediately** - AJAX calls on drop
- **Workbench is temporary** - teams must be placed back in games
- **Captain is NOT a role** - it's a Team.captain field relationship
- **Board Member can VIEW but not EDIT** - read-only access to admin areas

---

**End of Handoff - Schedule Builder Complete**

Current State: Schedule Builder UI fully implemented with drag-drop and navigation
Next Priority: Fix repeat games, build captain UI
Breaking Point: Clean - schedule builder working, improvements identified
