# CLAUDE.md — School ERP SaaS

Project rules for anyone (human or AI) working in this repository. The full plan is summarised in
[docs/PLAN.md](docs/PLAN.md); the source documents are `School-ERP-Build-Plan.pdf` and `school_erp_schema.sql`.
Where the plan's main tab and a module tab disagree, **the module tab wins**. Open questions live in
[docs/QUESTIONS.md](docs/QUESTIONS.md): when something is unclear, note it there and pick the safest option.

## Stack

- **Laravel 12**, PHP 8.2+ (XAMPP ships 8.2; `composer.json` pins `config.platform.php` to 8.2 so the lock file installs there).
- **Blade + Bootstrap with Tabler** (loaded from CDN). One admin template, **no SPA**, no Node build required.
- Packages: `nwidart/laravel-modules`, `spatie/laravel-permission` (**teams mode, `team_foreign_key = school_id`**),
  `spatie/laravel-activitylog` (table `activity_logs`, with `school_id`, `branch_id`, `ip_address`, `user_agent`).
- Database: MariaDB 10.4+ (XAMPP) **and** MySQL 8. Migrations must run on both. Tests run on in-memory SQLite,
  so DB-specific SQL (CHECK constraints, prefix indexes) goes through `App\Support\Schema\SchemaHelper`, which skips it on SQLite.

## Tenancy (SaaS, one database)

- Every school-owned table has `school_id`. Every school model **must** use `App\Models\Concerns\BelongsToSchool`
  (global scope `WHERE school_id = current school`, fills `school_id` on create). With no current school the scope
  returns **no rows** (fail closed). `tests/Feature/Architecture/SchoolModelsUseTraitTest` fails the build if a model
  on a `school_id` table does not use the trait.
- The school is found by **subdomain** of `APP_BASE_DOMAIN` (`abc.erp.localhost`). `App\Http\Middleware\IdentifySchool`
  loads it, blocks unknown (404) and suspended/cancelled (403) schools, and calls `setPermissionsTeamId($school->id)`.
- The current school lives in `App\Support\Tenancy\CurrentSchool` (singleton). Never set `school_id` by hand in controllers.
- Branch-owned tables also have `branch_id` and use `App\Models\Concerns\BelongsToBranch`, filtered by the user's role
  **data scope**: `all_branches`, `assigned_branches` (rows in `branch_user`), `own_records` (model defines
  `scopeOwnRecords($query, $user)`; without it the user sees nothing). The widest scope among the user's roles wins.
  `branch_id` is never guessed: it comes from a form request validated against the user's allowed branches.
- `App\Http\Middleware\ResetTenantContext` (global) clears the current school at the start of every request.
- Platform tables (`platform_users`, `plans`, `modules`, `school_modules`, `school_subscriptions`, `academic_templates`)
  are not school-scoped; only the platform panel touches them (except reading `school_modules` for the current school).
- Reserved subdomains (`admin`, `www`, `api`, …) can never be schools. `admin.<base>` is the Platform Owner panel.

## RBAC — always enforced on the server

Five checks on every request; **hiding a button is never the protection**:

1. Route middleware: `auth`, `permission:students.create`.
2. `module:<slug>` (`EnsureModuleEnabled`): the school owns the module, it is active and not expired → else 403.
3. Policies: `$this->authorize('update', $student)` for record-level actions.
4. Global scopes: `school_id` and branch filters on every query (lists, exports, searches, dropdowns).
5. Form requests: never accept `school_id`; accept `branch_id`/`role_id` only from what the user may set.

- Platform Owner (separate `platform` guard, `platform_users` table) and School Super Admin (`users.is_super_admin`)
  skip checks via `Gate::before`. Super admin never crosses schools: the tenant scopes still apply.
- Permission names are `module.action` (`students.create`, `fees.collect`). Core actions are in `config/permissions.php`;
  each module lists its actions in `Modules/<Name>/config/permissions.php`. `php artisan permissions:sync` writes them
  to `permissions` (module_slug, action, label, sort_order). Never create permissions by hand in code.
- Every module route group uses `['tenant', 'auth:web', 'module:<slug>']` (the module RouteServiceProvider adds `web`)
  plus a `permission:` middleware per route. Always name the guard: `auth:web` / `guest:web` on school routes,
  `auth:platform` / `guest:platform` on the platform panel.
- Roles are **not** globally scoped (Spatie's shared permission cache); list them with `Role::forCurrentSchool()`.

## Data rules

- Money is **`DECIMAL(12,2)`** (`decimal(..., 12, 2)` in migrations, `decimal:2` casts). Never float.
- Receipts and refunds are **never deleted**, only cancelled with a reason (no soft delete either).
- Custom IDs come from `id_formats`, read with `lockForUpdate()` **inside a DB transaction**.
- Status columns are `VARCHAR(20)`; allowed values are constants on the model.
- Aadhaar and 2FA secrets use the `encrypted` cast.
- Unique keys always include `school_id`; nullable `stream_id`/`branch_id` in unique keys go through a stored
  generated `*_key = IFNULL(col, 0)` column.
- Timestamps stored in UTC; displayed in the school's timezone.

## Code layout

- `app/` — core: tenancy, auth (school `web` guard + `platform` guard), platform panel, RBAC, settings, IDs.
- `Modules/Academic`, `Modules/Students`, `Modules/Fees` (nwidart). Each has `config/permissions.php`, `config/menu.php`,
  `database/migrations`, `routes/web.php`, `app/Http/Controllers`, `resources/views`.
- Migrations: platform + core in `database/migrations` (`2026_01_01_*`); Academic `2026_01_02_*`; Students `2026_01_03_*`;
  Fees `2026_01_04_*`. Laravel sorts all migration files by name, so these prefixes keep foreign keys in order.
- Layouts: `layouts.app` (school admin: sidebar shows only enabled modules the user may view), `layouts.platform`.

## Testing

- **Every feature ships with feature tests**, including *"a user of school A gets 404 for school B's records"*,
  permission (403 without permission), module (disabled → 403) and data-scope tests.
- Run `php artisan test` after every change; fix failures before moving on.
- Helpers in `tests/TestCase.php`: `seedPlatform()`, `createSchool()`, `createSchoolUser($school, $permissions, $scope, $branchIds)`,
  `superAdminOf()`, `mainBranchOf()`, `platformOwner()`, `schoolUrl()`, `platformUrl()`, `baseUrl()`.
- Tests run on in-memory SQLite; run them on MariaDB too before merging schema changes
  (`DB_CONNECTION=mariadb DB_DATABASE=school_erp_test php artisan test`).
- `vendor/bin/pint` before committing.

## Local environment (Windows + XAMPP)

- XAMPP Apache + MariaDB 10.4+. No Herd, Valet or Docker. `DB_CONNECTION=mariadb`, database `school_erp`.
- `APP_BASE_DOMAIN=erp.localhost`; platform panel at `admin.erp.localhost`; schools at `<subdomain>.erp.localhost`
  (demo `abc.erp.localhost`). See [docs/LOCAL_SETUP.md](docs/LOCAL_SETUP.md).
- **Local-only fallback**: when `APP_ENV=local` and no school subdomain matches, `?school=abc` picks the school and keeps it
  in the session. Never enabled in any other environment (guarded in `IdentifySchool`, covered by tests).
- File (or database) sessions, cache and queues. **No Redis.**

## Core services (Phase 1)

- `App\Support\Tenancy\CurrentBranch` — branch picked in the top bar (null = all the user may see); `BranchScope` narrows to it.
- `User::allowedBranchIds()` / `dataScope()` — use these for every branch check; never trust a branch id from input without them.
- `App\Support\Settings\Settings` — `get($key, $branchId)`, `set()`, `forget()`; fields are declared in `config/settings.php`.
- `App\Support\Ids\IdGenerator::next($entity, $branchId)` — the only way to issue student/admission/staff/receipt/refund numbers.
  Call it inside the transaction that saves the record.
- `App\Support\Permissions\PermissionGrid` / `AssignableRoles` — what a user may grant (never more than they hold).
- `App\Support\Auth\TwoFactor` — TOTP; required for platform users, optional for school users.
- Models with `LogsCoreActivity` write created/updated/deleted to `activity_logs`; `TracksAuthors` fills created_by/updated_by.
- Rules that hold for everyone (main branch, system roles, super admin accounts, own account) are checked in the controller,
  not only in policies, because `Gate::before` lets super admins skip policies.
- School routes add `password.changed` after `auth:web` (forces the change-password page when `must_change_password`).

## Academic module (Phase 2)

- Models in `Modules/Academic/app/Models` (`SchoolClass` is the `classes` table). Branch-owned: classes, sections, period sets,
  elective groups, class subjects; their `scopeOwnRecords` lets teachers see what they teach.
- `AcademicYear::ensureEditable()` (403) before any change to data of a year: closed years are read-only everywhere.
- `Modules\Academic\Support\AcademicContext::year()` (the ?year= picker) and `::teachers($branchId)` (active teaching staff).
- `TimetableService` holds the timetable checks (teacher clash by clock time, breaks, room and over-target warnings).
- `CopySetup` copies a year's setup (preview = same code rolled back).
- Core `App\Support\Users\DeactivationChecks`: modules register what a user still holds before deactivation.
- Module routes: `Modules/<Name>/routes/web.php`; add new groups above the `// @routes-end` line.
- Test helpers for Academic data: `tests/Concerns/BuildsAcademic.php`.

## Students module (Phase 3)

- Models in `Modules/Students/app/Models`; `Student` is branch-owned, `scopeOwnRecords` covers teachers (their sections),
  parents (their children) and students (themselves). Record actions go through `StudentPolicy`.
- `AdmissionService::admit()` is the only way to create a student (one transaction: ids, guardians, enrollment, files, logins).
- Status changes go through `StudentStatus` (fires `StudentStatusChanged`); promotion through `Promotion` (batches, undo).
- Parent/Student logins: `PortalLogins`; portal users (`User::isPortalUser()`) only reach `/portal` (`portal` middleware).
- Files (photos, documents) on the private `local` disk under `schools/{school}/students/{id}`, served by permission-checked routes.
- Custom fields: `App\Support\CustomFields\CustomFields` (students, guardians, classes, sections, subjects).
- Imports: `StudentImporter` (queue over 300 rows) and Academic `AcademicImporter`; both preview first and give an error file.
- Test helpers for students: `tests/Concerns/BuildsStudents.php`.

## Fees module (Phase 4)

- Money arithmetic in PHP is in whole paise: `Modules\Fees\Support\Money` (`paise()`, `format()`, `display()`). Never float.
- `StructureBuilder` (grid, split, copy), `DuesService` (all due lines; enrollment hooks in `FeesServiceProvider`),
  `ConcessionCalculator`, `FineCalculator`, `CollectionService` (the only way to make or cancel a receipt), `CreditLedger`
  (append-only, student row locked), `OnlinePaymentService` + `RazorpayClient`, `RefundService`, `CarryForward`, `Reminders`, `FeeReports`.
- `student_fees.balance` is a generated column: after changing amounts in PHP use `duePaise()`; lists load
  `withSum('paidItems as fine_paid', 'fine_amount')` for the fee/fine split.
- Compare `due_date` with `whereDate()` (SQLite stores dates with a time part).
- Fees tests travel in time **before** creating the school (`$this->travelTo(...)` first), or the school's modules have not started yet.
- Counter receipts take staff-chosen `allocations` [line_id => amount]; online payments and automatic credit allocate oldest first.
- Fee accounts (`FeeAccount`, own receipt series `receipt_<id>`) and `DepositAccount` (cash/bank): `CollectionService::collect()`
  makes one receipt per fee account (same `receipt_group`) and returns the first.
- DCR (Day Challan Receipt), per branch: `FeeDay::businessDate($branchId)` (after the DCR time or once the branch's DCR is
  closed, receipts get the next day), `isClosed($date, $branchId)`, `close()` (DCR number from ID format `dcr`).
  `fees:close-days` closes every branch at the Super Admin's DCR time; `fees.close_day` lets branch accounts close earlier.
- Dashboard widgets: a module's `config/dashboard.php` names a class with `render(User): ?string` (`Modules\Fees\Support\DashboardWidget`).
- Test helpers: `tests/Concerns/BuildsFees.php` (`makeHead`, `makeStructure`).

## Operations (Phase 5)

- `SecurityHeaders` (global), HTTPS forced when `APP_SCHEME=https`, `TRUSTED_PROXIES` for a TLS proxy.
- `backup:database` / `backup:files` (`App\Support\Backups\BackupStore`, `config/backup.php`), scheduled in `routes/console.php`.
- Shared hosting (cPanel, [docs/SHARED_HOSTING.md](docs/SHARED_HOSTING.md)): `QUEUE_VIA_SCHEDULER=true` (cron runs the queue),
  `BACKUP_METHOD=php` (`App\Support\Backups\PhpDumper`, no mysqldump). Never rely on exec/proc_open or long-running processes.
  No Terminal: the release zip (vendor included, built by `.github/workflows/release.yml`) and `php artisan erp:install`
  (idempotent install/update, run from a cron job). Keep `erp:install` safe to run repeatedly.
- `php artisan erp:preflight` must pass on a server before real schools use it; see [docs/DEPLOY.md](docs/DEPLOY.md).
- `tests/Feature/Architecture/RouteProtectionTest`: a new logged-in route without `permission:` fails the build unless it is
  listed there with the reason it is safe.

## Working rules

- Small steps, one commit each, clear message. `php artisan test` green before committing.
- Don't build a later phase early. Phase status is tracked in docs/PLAN.md §11.
