# System Workflows

This document describes the major business workflows from end to end, including actors, triggers, steps, business rules, and outcomes.

---

## 1. Program Registration & Approval Workflow

**Actors:** Visitor (Program Admin), System Admin (super-admin)
**Preconditions:** None
**Trigger:** Visitor accesses program registration page

### Steps
1. Visitor navigates to `/program/register-a-program-email` or `/program/register-a-program-phone`
2. Fills in program details (name, description, admin name, email/phone)
3. System creates new `Program` with `is_active=false` (pending)
4. System creates admin `User` with `is_active=false` (pending)
5. Program automatically subscribed to initial `ProgramPlan`
6. Admin user automatically subscribed to initial `TeacherPlan`
7. Notification dispatched: `program.created`, `user.account.created`
8. System admin receives notification about new program
9. System admin reviews program in Admin panel → `ProgramResource`
10. Admin approves program via `Program.approve()` method:
    - Sets `is_active=true`, `approved_at=now()`
    - Dispatches `program.approved`, `program.enabled`
11. Program admin is notified of approval
12. Program admin can now log in and manage the program

**Business Rules:**
- Both email AND phone verification supported (at least one required)
- Program must be approved before users can access the panel
- Initial plan provides base feature limits

**Exception:** Program rejected → Program is deleted or marked inactive. Users cannot access.

---

## 2. Teacher Registration Workflow

**Actors:** Visitor (Teacher), Program Admin
**Preconditions:** Program must be active and have available `no_of_teachers` capacity
**Trigger:** Teacher clicks registration link from program admin

### Steps
1. Program admin shares teacher registration link: `/program/{program_id}/register-teacher-to-program-email`
2. Teacher fills in registration details
3. System creates `User` with `teacher_id=null`, `program_id={program_id}`, role `portal-teacher`
4. Teacher auto-subscribed to initial `TeacherPlan`
5. Teacher account is `is_active=false` (pending approval by program admin)
6. Notification dispatched: `user.account.created`
7. Program admin approves teacher in Admin panel
8. Teacher can now access Program panel and create content

**Business Rules:**
- `no_of_teachers` feature consumption checked on User creation (program subscription)
- Teacher must verify email or phone before accessing panel
- Teacher account marked inactive until program admin approves

---

## 3. Student Registration Workflow

**Actors:** Visitor (Student/Parent), Teacher
**Preconditions:** Teacher is active, has available capacity
**Trigger:** Student clicks registration link from their teacher

### Steps
1. Teacher shares student registration link: `/program/{teacher_id}/register-to-program-email`
2. Student fills in registration details
3. System creates `User` with `teacher_id={teacher_id}`, `program_id={teacher_program}`, role `portal-student`
4. Student auto-subscribed to initial `StudentPlan`
5. Notification dispatched: `user.account.created`
6. Teacher approves student account
7. Student can now access assessments and self-training

**Business Rules:**
- Teacher capacity for students checked via feature limits
- Students are linked to exactly one teacher
- Students can be in multiple teams (groups)
- Student verification required before access

---

## 4. Assessment Lifecycle Workflow

**Actors:** Teacher, Students
**Preconditions:** Teacher has active subscription with assessment feature enabled
**Trigger:** Teacher creates a new assessment

### Steps
1. Teacher creates Assessment (type: exam/competition/training/etc.)
2. `SubscriptionUsageObserver` checks feature limit and consumes usage
3. Teacher adds problems via `AssessmentProblems`
4. Teacher configures: timing, scoring, visibility, enrollment mode
5. If competition: configure scope (system/program/teacher), payment, eligibility
6. For timed assessments: use `MentalMathTimer` for real-time problem display
7. Students access assessment (if non-locked and within time window)
8. Students submit attempts via `AssessmentAttempt` + `AssessmentAttemptAnswer`
9. System records score, updates `update_count` if problems edited
10. Results displayed based on `show_result` setting
11. For competitions: rankings computed via `RankingService`

**Assessment Types & Behavior:**
- **Exams:** Teacher-scoped, formal evaluation
- **Competitions:** Program or system-scoped, uses participation system
- **Marathon-Competitions:** Child of a Marathon event
- **Trainings:** Practice before competitions
- **Self-Training:** Student-initiated practice (consumes student subscription)
- **Group-*:** Team-scoped assignments/homework/exams

**Business Rules:**
- `is_locked` controls whether assessment is accessible
- `scope` + `level_classification` synced automatically to child assessments
- Problem edits tracked via `update_count` (limited by `no_of_edits_*` features)
- Assessment timing: `timing=assessment` (full test) vs `timing=problems` (per-problem timing)

---

## 5. Marathon Lifecycle Workflow

**Actors:** Program Admin/Teacher, Participants (Teachers), Students
**Preconditions:** Program has `no_of_marathons` capacity
**Trigger:** Admin creates a new Marathon

### Steps
1. Admin creates Marathon with scope (system/program/teacher)
2. Feature consumption: `no_of_marathons` (program subscription)
3. Admin adds competitions to marathon (Assessments with `marathon_id` set)
4. Per-marathon competition limit checked: `no_of_competition_per_marathon`
5. Marathon starts at `starts_at` (scheduled via `events:open-scheduled` cron)
6. Teachers participate via participation system
7. Students take competitions
8. Marathon ends at `ends_at`
9. Scheduler (`marathons:complete-expired` cron) auto-completes marathon
10. Rankings computed for all competitions within marathon
11. Marathon leaderboard displayed via `MarathonLeaderboardWidget`

**Scheduled Jobs:**
- `events:open-scheduled` — Every 15 min, unlocks scheduled competitions
- `events:close-expired` — Hourly, locks expired competitions
- `marathons:complete-expired` — Hourly, completes past marathons
- `notifications:marathon-upcoming` — Daily 8AM, notifies about starting/ending marathons

---

## 6. Participation Workflow (Shared)

**Actors:** Teacher (Participant), Authority (Admin/Manager), Students
**Preconditions:** Event (Marathon/Competition) exists and is open
**Trigger:** Teacher requests to participate in an event

### Steps
1. Teacher submits participation request via `ParticipationRequestService`
2. `EligibilityService` checks eligibility criteria against event config
3. Notification: `participation.submitted` sent to approval authority
4. Authority reviews and approves/rejects via `ParticipationRequestManagementPage`
5. On approval: `SeatAllocationService` allocates seats (if applicable)
6. Notification: `participation.approved` / `participation.rejected`
7. Teacher enrolls students via `StudentEnrollmentService`
8. Enrollments approved/rejected by teacher
9. If payment required: student submits payment via `PaymentSubmission`
10. Authority verifies payment via `PaymentVerificationPage`
11. Audit trail recorded via `ParticipationAuditService` at each step

**Scope-Specific Rules:**
| Scope | Approval Authority | Participant Type | Seat Allocation |
|-------|-------------------|------------------|----------------|
| System | super-admin/manager | Teacher | Yes |
| Program | portal-admin/manager | Teacher | Yes |
| Teacher | portal-teacher | Student | No |

**Notifications:** `participation.*`, `enrollment.*`, `payment.*`, `seat.*`

---

## 7. Subscription Lifecycle Workflow

**Actors:** Subscriber (Program/Teacher/Student), System
**Preconditions:** Subscriber exists with an active plan
**Trigger:** Subscription creation (auto on registration)

### Steps
1. Subscription created with `status=pending`, `is_active=false`
2. On activation: `starts_at` set, `status=active`, `is_active=true`
3. Feature limits from plan snapshot recorded
4. Feature usage tracked via `SubscriptionUsageObserver`
5. As `ends_at` approaches:
   - `notifications:plan-expiring` (Daily 6AM) — notifies at 7 days and 1 day
   - `notifications:feature-limit` (Daily 12PM) — warns if usage >80%
6. On `ends_at`:
   - If grace period configured → enters grace period (`status=grace_period`)
   - `subscriptions:process-grace-period` (Daily 2AM) handles grace end
   - `subscriptions:auto-suspend` (Daily 12AM) suspends past-grace subscriptions
   - After 30 days suspended → expired permanently
7. On renewal: new subscription created or existing extended
8. Default plan assigned if no active subscription

**Status Transitions:**
```
pending → active → grace_period → suspended (30d) → expired
         → expired (no grace period)
         → cancelled (manual)
```

---

## 8. Feature Usage Tracking Workflow

**Actors:** System (automatic)
**Preconditions:** Resource model is registered in `config/subscription-resources.php`
**Trigger:** Resource creation or deletion

### Steps
1. User creates a countable resource (e.g., Course, Video, Team)
2. `SubscriptionUsageObserver@created` fires
3. Observer reads `config/subscription-resources.php` mapping:
   - Resolves feature key (may be type-dependent, e.g., Assessment)
   - Resolves subscriber (teacher/program/student)
   - Resolves amount (static 1, or storage MB for videos)
4. Observer calls `FeatureGate::consume(subscriber, feature, amount)`
5. FeatureGate checks current usage + requested amount against limit
6. If within limit → usage counter incremented
7. If exceeds limit → `FeatureLimitExceededException` thrown → creation rolled back
8. On resource deletion → `FeatureGate::release()` decrements usage (if configured)

**Daily Snapshot:**
- `usage:snapshot` (Daily 23:55) — Records usage snapshots in `usage_histories` for analytics

---

## 9. Course → Lesson → Classroom Workflow

**Actors:** Teacher, Students
**Preconditions:** Teacher has `no_of_courses` and `no_of_lessons` capacity
**Trigger:** Teacher creates a course

### Steps
1. Teacher creates Course → consumes `no_of_courses`
2. Teacher adds Lessons within course → consumes `no_of_lessons`
3. Each lesson has a `mode`: physical, video, or meeting
4. Teacher can create Teams (groups) and assign students
5. Teacher creates ClassroomInstance linked to a team + lesson
6. Students attend classroom session → attendance tracked via QR code
7. Teacher can add learning path steps (`TeamPathStep`) linked to assessments

---

## 10. User Login & Session Workflow

**Actors:** Any user
**Preconditions:** User account exists and is active
**Trigger:** User accesses login page

### Steps
1. User chooses email or phone authentication
2. System validates credentials
3. On successful login:
   - `LoginHistory` record created (user_id, login_at, ip, user_agent)
   - `ExpireSubscriptionsOnLogin` listener fires → expires past-due subscriptions
   - `user.login.detected` notification dispatched
4. User activity tracked via `RecordUserActivity` and `UpdateLastActivity` middleware
5. On logout → `login_history.logout_at` updated
6. Session timezone detected via JavaScript and stored in session
