# CLAUDE.md — CMMSchool Upgrade Project

This file provides Claude Code with a comprehensive understanding of the project structure, conventions, and key details for effective assistance without re-exploring the codebase each session.

---

## Project Overview

**Name**: CMMSchool (cmmschoolupgrade)
**Type**: School Management Portal — migration from CodeIgniter 3 → CodeIgniter 4
**Status**: Migration nearly complete; most admin and teacher/parent modules functional. Minor UI fixes remain.
**Base URL (Dev)**: http://cmmschoolupgrade.v1/
**PHP Platform**: 8.4.18 (requires ^8.1)

---

## Technology Stack

| Layer | Technology |
|-------|-----------|
| Framework | CodeIgniter 4 (^4.0) |
| Language | PHP 8.1+ |
| Database | MySQL (MySQLi), utf8mb4 |
| Test DB | SQLite3 in-memory |
| Payment | Stripe PHP SDK ^16.0 |
| Spreadsheet | PhpSpreadsheet ^5.5 |
| Testing | PHPUnit 10.5.16 |
| Frontend | Bootstrap, jQuery 1.11.3, custom JS |
| Email | SMTP via SendGrid |
| Sessions | Filesystem (`writable/session/`) |

---

## Directory Structure

```
cmmschoolupgrade/
├── app/
│   ├── Config/              # 43 config files
│   │   ├── Routes.php       # 517 lines, 200+ explicit routes (no auto-routing)
│   │   ├── App.php          # baseURL, security settings
│   │   ├── Database.php     # MySQL (default) + SQLite3 (tests)
│   │   ├── Stripe.php       # Reads from .env
│   │   ├── Filters.php      # CSRF, honeypot, secureheaders, cors, forcehttps
│   │   ├── Email.php        # SMTP/SendGrid
│   │   ├── Session.php
│   │   └── Constants.php
│   ├── Controllers/
│   │   ├── Home.php         # Redirects to login
│   │   ├── My404.php        # Custom 404
│   │   ├── RegistrationPaperForm.php
│   │   ├── Admin/           # 21 admin module controllers
│   │   ├── Tp/              # 13 teacher/parent portal controllers
│   │   └── Webhook/
│   │       └── StripeWebhook.php
│   ├── Models/              # 142 models (see Database section)
│   ├── Views/
│   │   ├── layouts/
│   │   ├── pages/
│   │   ├── partials/
│   │   ├── admin/
│   │   ├── tp/              # Teacher/parent portal views
│   │   ├── pp/              # Parent portal iframe views
│   │   └── errors/
│   ├── Libraries/
│   │   └── EnrollmentStripeHelper.php
│   ├── Filters/
│   ├── Services/
│   ├── Commands/
│   └── Database/
│       ├── Migrations/      # Currently empty
│       └── Seeds/
├── public/                  # Web root
│   ├── index.php
│   ├── assets/              # Global CSS/JS/images
│   ├── js/                  # Admin JS (jQuery, Bootstrap, custom.js)
│   ├── tp/                  # Teacher/parent portal assets
│   ├── admin/               # Admin-specific assets
│   └── registration_paper_form/
├── tests/
│   ├── feature/             # 9 integration test files
│   ├── unit/                # HealthTest.php
│   ├── session/
│   ├── database/
│   └── _support/            # Test helpers (Http/ directory)
├── docs/                    # 25+ markdown docs
├── writable/                # Logs, sessions, cache, uploads
├── vendor/
├── composer.json
├── phpunit.xml.dist
└── spark                    # CodeIgniter CLI
```

---

## Routing

- **All routes are explicit** — auto-routing is disabled.
- Route file: `app/Config/Routes.php` (517 lines)

### Route Groups

| Prefix | Purpose |
|--------|---------|
| `/` | Public home (redirects to login) |
| `/tp/` | Teacher/parent portal |
| `/admin/` | Admin back-office |
| `/webhook/stripe` | Stripe webhook (POST, no CSRF) |
| `/registration_paper_form/` | Static PDF routes |

---

## Controllers Reference

### Teacher/Parent Portal (`app/Controllers/Tp/`)

| Controller | Purpose |
|-----------|---------|
| `Te.php` | Teacher authentication (login, logout, forgotPassword, newPassword) |
| `Pa.php` | Parent authentication |
| `Ur.php` | Unified role dashboard, chooseSchool, signin_out |
| `Pp.php` | Parent portal (iframe mode) |
| `Rosters.php` | Check-in/out, notes, student details |
| `InternalMessage.php` | Inbox (compose, sent_items, reply) |
| `Quests.php` | Montessori lesson planning, behavior tracking |
| `StudentEnrollment.php` | Registration flow, ajaxData |
| `Payment.php` | Stripe Checkout (createCheckoutSession, process, success, cancel) |
| `Reports.php` | Daily reports, comments, attachments |
| `TeacherMessage.php` | Teacher↔parent messages, bulk messaging |
| `St.php` | Student assessment (stAssessment, baseLineAssessment, readinessAssessment) |
| `Incoming.php` | Incoming requests |

### Admin Panel (`app/Controllers/Admin/`)

| Controller | Purpose |
|-----------|---------|
| `Home.php` | Admin login, logout, dashboard, changePassword |
| `Schools.php` | School management |
| `Users.php` | User management (admins, staff) |
| `Teachers.php` | Teacher management, class assignments |
| `Students.php` | Student management, attendance view |
| `ClassRooms.php` | Classroom setup |
| `Enrollment.php` | Registration/enrollment management |
| `Prospects.php` | Lead management, bulk email |
| `Withdraws.php` | Student withdrawal management |
| `StudentParent.php` | Student-parent linking |
| `ParentConcerns.php` | Parent issue tracking |
| `Activities.php` | Activity management |
| `Requests.php` | Request management |
| `InternalMessage.php` | Admin inbox |
| `TeacherMessage.php` | Message monitoring |
| `Portals.php` | Announcements, newsletters, documents, notifications |
| `Events.php` | Event calendar, Google sync |
| `EmailTemplate.php` | Email template management |
| `Classroster.php` | Class attendance reports |
| `AdminController.php` | Base controller for admin modules |

---

## Key Libraries

### `app/Libraries/EnrollmentStripeHelper.php`
- `computeFeeAmounts()` — Calculates Stripe processing fees (legacy-compatible formulas)
- `clearPaymentSessionKeys()` — Cleans up session after payment
- `finalizeFromCheckoutSession()` — Processes successful payment, updates DB (idempotent)

---

## Database

- **Driver**: MySQLi
- **DB Name (dev)**: `cmmschoolupgrade`
- **Charset**: utf8mb4 / utf8mb4_general_ci
- **Test DB**: SQLite3 `:memory:` (configured in `app/Config/Database.php` under `tests` group)
- **Legacy schema**: Shared with original CI3 system — schema was not changed during migration

### Model Categories (142 total)

| Category | Key Models |
|---------|-----------|
| Users | User, UserRole, UserAccessLevel, UserAddress, UserMedia, UserLoginDetail, UserOwner |
| Students | Student, StudentClass, StudentEnrollment, StudentDailyInOut, StudentBehavior, StudentWithdraw, StudentMedication, StudentSchedule |
| Teachers | Teacher, TeacherClass, TeacherSchedule, TeacherMessage, TeacherMessageAttachment |
| Schools | School, SchoolCategory, SchoolStaff, Program, ClassRoom, ClassRoomActivity, ClassRoomProgram |
| Parents | Parent, ParentConcern, Family, FamilyAgreement, RelationWithChild |
| Enrollment | Enrollment, EnrollmentStatus, StripePayment |
| Quests/Lessons | Quest, LessonStatus, LessonPlan, MonthlyLessonPlan, Concept, Material, Area |
| Assessment | Assessment, BaStudent, BaArea, BaAreaQuestion, BaStudentAnswer |
| Activities | Activity, ActivityProgram, ActivitySchedule, ActivityStudent, ActivityType |
| Portals | AdminAnnouncement, Newsletter, Document, Notification, Portal |
| Events | Event, EventSync |
| Messages | InternalMessage, InternalMessageAttachment |
| Prospects | Prospect, ProspectStatus, ProspectSource, ProspectRequest |
| Reports | DailyReport (Dr), DrItem, StudentDrItem |
| Utilities | Common, Utility, Timezone, Country, State, Category |

---

## Configuration

### Environment (`.env`)
- `CI_ENVIRONMENT=development`
- `app.baseURL=http://cmmschoolupgrade.v1/`
- `database.default.*` — MySQL, localhost, root:redhat, db: cmmschoolupgrade
- `encryption.key=1` (CI3-compatible)
- `email.protocol=smtp` (SendGrid)
- `stripe.testMode=true` (test credentials)

### Stripe (`app/Config/Stripe.php`)
- All keys read from `.env`: `testMode`, `secretKey`, `publishableKey`, `webhookSecret`
- Webhook verification is required — raw body must be preserved for `POST /webhook/stripe`
- CSRF filter is excluded for the webhook route

### Filters (`app/Config/Filters.php`)
- Defined aliases: `csrf`, `toolbar`, `honeypot`, `invalidchars`, `secureheaders`, `cors`, `forcehttps`, `pagecache`
- Global filters disabled by default — apply per-route as needed

---

## Testing

```bash
composer test                         # Run all tests
./vendor/bin/phpunit tests/feature/   # Feature tests only
./vendor/bin/phpunit tests/unit/      # Unit tests only
```

**Configuration**: `phpunit.xml.dist`
- Bootstrap: `vendor/codeigniter4/framework/system/Test/bootstrap.php`
- Coverage output: `build/logs/` (HTML, Clover, PHP)
- Server variable override: `app.baseURL = http://example.com/`
- Test database: SQLite3 in-memory

### Test Files

| File | Covers |
|------|--------|
| `feature/TpGuestFeatureTest.php` | Teacher portal guest access |
| `feature/TpPaymentGuestFeatureTest.php` | Stripe payment flow |
| `feature/AdminHomeFeatureTest.php` | Admin login/dashboard |
| `feature/AdminModulesGuestFeatureTest.php` | Admin modules (guest) |
| `feature/TpLoginValidationFeatureTest.php` | Login form validation |
| `feature/NotFoundFeatureTest.php` | 404 handling |
| `feature/RegistrationPaperFormFeatureTest.php` | PDF routes |
| `feature/RouteInventoryGuestTest.php` | Route coverage inventory |
| `unit/HealthTest.php` | Basic health checks |

---

## Key Conventions

1. **No auto-routing** — all routes are explicitly defined in `app/Config/Routes.php`
2. **No Helpers directory** — logic is in Models, Libraries, or Controllers
3. **Legacy schema** — do not change table/column names; they match the CI3 system
4. **AJAX responses** — controllers return JSON for datatables and dynamic UI
5. **Role separation** — Admin, Teacher, Parent roles have separate login flows and session keys
6. **Stripe idempotency** — `finalizeFromCheckoutSession()` is designed to be called multiple times safely
7. **CSRF** — disabled globally; applied selectively; excluded on webhook route
8. **Session storage** — filesystem at `writable/session/`
9. **Frontend assets** — served from `public/assets/` (global), `public/tp/` (portal), `public/admin/` (admin)

---

## Documentation (`docs/`)

| File | Topic |
|------|-------|
| `README.md` | Project hub, quick start |
| `ARCHITECTURE.md` | System diagram, folder layout |
| `ENVIRONMENT.md` | `.env` variable reference |
| `DATABASE.md` | Schema reference, table columns |
| `DEPLOYMENT.md` | Dev/staging/production setup |
| `TESTING.md` | PHPUnit guide |
| `SECURITY.md` | CSRF, Stripe, XSS, validation checklist |
| `payment-gateway.md` | Stripe Checkout, webhooks, enrollment fees |
| `email-sending.md` | SMTP/SendGrid, troubleshooting |
| `MIGRATION.md` | CI3→CI4 migration summary |

---

## Git History (Notable Commits)

```
96a2feb  Payment gateway configuration completed
33780ab  Project almost completed, ready for development
2ac8301  Fix validation, UI issues, form handling in School Owner module
b386c85  Every module completed, only minor UI fixes needed
48f932d  Implement School Owner and Admin modules
```

---

## Current Work in Progress (as of last session)

- Modified files: `app/Config/App.php`, `app/Controllers/Tp/Payment.php`, `app/Libraries/EnrollmentStripeHelper.php`, `app/Views/tp/stripe_payment.php`
- New feature test files added: `tests/feature/` (8 new files)
- New support files: `tests/_support/Http/`
- Docs updated: `docs/README.md`, `docs/TESTING.md`, `docs/UNIT-TESTING.md`
- New case study docs: `docs/CASE-STUDY*.md`, `docs/PROJECT-SHORT.md`
