# School Management System — Development Conventions Requirements: `Complete_School_Management_System_Requirements.docx` (section numbers below refer to it). ``` backend/ Laravel 12 REST API (Sanctum tokens, Spatie Permission with teams = school_id) frontend/ React 18 + Vite + React Router 6 + Bootstrap 5 + Chart.js (separate SPA) ``` ## Backend ### Multi-tenancy (Section 24, 27.1) - Every tenant-owned table has `school_id` (FK to `schools`, cascade delete) and the model uses `App\Models\Concerns\BelongsToSchool` → global scope on the current school + auto-fill `school_id`. - Also use `App\Models\Concerns\Auditable` on any model whose changes matter (students, marks, attendance, payments, settings...). - Session-specific academic data carries `academic_session_id`. - Validation of foreign ids must be tenant-safe: in a `CrudController` use `$this->existsInSchool('table')` and `$this->uniqueInSchool('table', 'column', $model)`; elsewhere `Rule::exists('table','id')->where('school_id', Tenant::id())`. - Never trust `school_id` from the request. ### Models (`app/Models`) - `protected $guarded = ['id'];` + `casts()`; relationships typed (BelongsTo, HasMany...). - Existing core models (do NOT redefine): School, SubscriptionPlan, SchoolSubscription, Campus, SchoolSetting, AuditLog, LoginHistory, User, AcademicSession (`AcademicSession::current()`), EducationLevel, Department, Designation, Employee (`full_name`, `is_teacher`), Room, SchoolClass (table `classes`, `nextClass()`), Section, Subject, ClassSubject (class/section/subject/teacher per session), Guardian (table `guardians`), Student (`full_name`, `guardians()`, `enrollments()`, `currentEnrollment()`), StudentEnrollment (one row per student per session), StudentDocument, UserNotification. - Laravel serializes relations in snake_case: `schoolClass` → `school_class` in JSON. ### Migrations - Each module owns a timestamp prefix so ordering is deterministic: core `2026_01_01_*` · admissions/students `2026_01_02_*` · courses/learning/homework `2026_01_03_*` · timetable/attendance/calendar `2026_01_04_*` · exams/quizzes `2026_01_05_*` · fees/accounting/HR-payroll `2026_01_06_*` · communication/SMS/portal/student-affairs/visitors `2026_01_07_*` · library/transport/inventory/certificates `2026_01_08_*`. - FKs only to core tables or your own module's tables. To reference another module's table, use a plain nullable `unsignedBigInteger` + index (no FK constraint). - Use `softDeletes()` where records must be recoverable; add indexes for filter columns; scoped unique constraints (e.g. `unique(['school_id','invoice_no'])`). ### Controllers - Simple CRUD: extend `App\Http\Controllers\Api\CrudController` (see its docblock): set `$model`, `$permission`, `$with`, `$searchable`, `$filterable`, `$sortable`, `$defaultSort`, `$fileFields`, implement `rules()`; hooks `indexQuery`, `beforeSave`, `afterSave` (inside the DB transaction), `beforeDelete`, `dateColumn()`. Index supports `?q=`, filters, `?sort=-col`, `?per_page=`, `?all=1` (plain list for dropdowns), `?date_from/date_to`. - Workflow actions (approve, publish, pay, promote...) are extra methods on the controller, wrapped in `DB::transaction`, checking permission with `abort_unless($request->user()->can('x.approve'), 403)`. - Responses: lists = Laravel paginator JSON or `{data: [...]}`; single = `{data: {...}, message?: '...'}`; errors = `abort(422, 'msg')` or validation exceptions (JSON is forced for `api/*`). - Put controllers in a module sub-namespace: `App\Http\Controllers\Api\\...`. - Business logic that is reused goes in `app/Services//...`. ### Routes - Create `routes/api/.php`. It is auto-required INSIDE the `auth:sanctum` + `tenant` group of `routes/api.php` (do not edit `routes/api.php`). Use the `Route::crud('uri', Controller::class)` macro for index/store/show/update/destroy (`{id}` numeric) and add custom routes with explicit `{id}` params. Use kebab-case URIs. - Uploads from the SPA arrive as multipart POST with `_method=PUT` for updates (Laravel method spoofing). ### Permissions (Section 1, 25) - Create `app/Support/Permissions/.php` returning `['group' => 'Label', 'permissions' => ['resource' => ['view','create','update','delete', 'approve'...]], 'roles' => ['Teacher' => ['resource.view', 'other.*']]]`. `School Admin` and `Principal` automatically get everything. Default roles: School Admin, Principal, Vice Principal, Accountant, Admission Officer, Teacher, Class Teacher, Exam Controller, Librarian, Receptionist, Transport Manager, HR Manager, Parent, Student. - Business separation (Section 28): accountants do not get exam/result edit permissions; exam staff do not get payment reversal. - Run `php artisan sms:sync-permissions` after adding permissions (seeding does this too). ### Access rules — `App\Support\Access` - `Access::portalStudentIds($user)` → null for staff, linked children for parents, own id for students. - `Access::scopeStudents($query, $user)`, `Access::ensureStudent($user, $studentId)`. - `Access::isRestrictedTeacher($user)`, `Access::teacherAssignments($user, $sessionId)`, `Access::ensureTeacherCanAccess($user, $classId, $sectionId, $subjectId)`. - Portal endpoints (for parents/students) live under `/portal/...` in your module's route file, require `portal.view` and MUST scope by `Access::portalStudentIds()` (accept `?student_id=` and verify it with `ensureStudent`). ### Settings — `App\Support\Settings` - `Settings::get('grading.bands')`, `Settings::gradeFor($percentage)` → `['grade','gpa','remark']`, `fees.*`, `attendance.*`, `exams.*`, `sms.*`, `notifications.channels`. Add new keys only if essential (edit `Settings::DEFAULTS`). ### Notifications — `App\Services\Notifier` - `Notifier::toUsers($userIds, $title, $body, ['type' => 'homework', 'link' => '/portal/homework'])` - `Notifier::toGuardians($studentIds, $title, $body, ['type' => 'absence'])` (in-app + SMS when enabled) - `Notifier::toStudents($studentIds, ...)` - The SMS module implements `App\Services\Sms\SmsService::sendToGuardians(array $studentIds, string $message, array $meta = []): int`. ### Dashboard - Add `app/Support/Dashboard/.php` returning `fn (Request $request): ?array` (keys merged into `GET /dashboard`). Check permissions inside and return null if not allowed. Honour `academic_session_id`, `campus_id` query params. ### Seeders - Demo data: `database/seeders/Modules/Seeder.php` (namespace `Database\Seeders\Modules`). They run after the core demo data inside the demo school tenant (`Tenant::id()` is set). Make them idempotent (return early if data exists). Keep them small. ## Frontend - Module = `src/modules//index.jsx` default-exporting `{ menu, routes, widgets?, dashboards? }` (see `src/modules/registry.js`). It is auto-discovered — do not edit `App.jsx` or the registry. - Menu group keys & order (Section 30): dashboard 0, platform 5, school 10, users 20, admissions 30, students 40, academics 50, learning 60, timetable 70, attendance 80, examinations 90, fees 100, hr 110, library 120, transport 130, inventory 140, communication 150, sms 155, affairs 160, reports 170, settings 180, portal 1 (parent/student). Re-use a key to add items to an existing group. Menu item: `{ label, path, permission, order, userTypes?: ['parent','student'] }`. - Route: `{ path, element, permission }` (the router guards the permission). - Building blocks in `src/components`: - `ResourcePage` — full CRUD page from config (columns, fields, filters, rowActions, headerActions, exportName...). Read its docblock. - `FormField` / `FormRenderer` — field types incl. async `select` (`endpoint`, `params`, `dependsOn` for cascading class → section). - `DataTable`, `Modal`, `ui.jsx` (`PageHeader`, `Card`, `StatCard`, `StatusBadge`, `Pagination`, `Tabs`, `Loading`, `EmptyState`). - `hooks.js` — `useFetch(url, params)`, `useOptions(endpoint, params)`, `clearOptionsCache()`. - `Toast` — `const toast = useToast(); toast.success('...')`. - `src/api/client.js` — `api` (axios with token/tenant headers), `errorMessage(e)`, `validationErrors(e)`, `toFormData`, `fileUrl(path)`, `download()`. - `src/auth/AuthContext.jsx` — `useAuth()` → `user`, `can('perm')`, `hasRole`, `isParent`, `isStudent`, `currentSession`; ``. - `src/utils/format.js` — `formatDate`, `formatMoney`, `personName`, `titleCase`, `opts`, `exportCsv`, `get`. - Printable documents (report card, admit card, receipt, ID card, certificate): render inside `.print-sheet` and call `window.print()` (print CSS hides the sidebar/topbar/buttons). - Bootstrap 5 classes + bootstrap-icons (`bi-*`). Keep pages responsive. ## Verifying without a database - `php -l` on new PHP files, `php artisan route:list --path=api` must succeed. - Frontend: `npx vite build --outDir ` must succeed (do not write to `frontend/dist` concurrently). ## Dynamic menus (stored in the database) - Table `menus` (per school; `school_id NULL` = Super Admin platform menu): main menus (`parent_id NULL`) → sub menus. - Default menus still come from each module's `menu` export. `npm run export-menus` (frontend) writes `backend/database/data/menus.json`, which seeding and new-school provisioning use (`MenuService::syncFromFile`). When an admin with `menus.manage` opens the app after modules change, the SPA re-syncs automatically (`POST /menus/sync`). - Sync never overwrites admin customisations (label, icon, order, parent, hidden), but always refreshes the permission / user-type rules of built-in items. Admins manage menus at Settings → Menu Manager (custom menus may link to SPA paths or URLs). - `GET /menus` returns only what the signed-in user may see. Permissions may be `a.view|b.view` (any of). ## Appearance - ``. - Use Bootstrap classes and the CSS variables `--sms-primary`, `--sms-primary-rgb`, `--sms-accent`, `--sms-gradient`, `--sms-surface`, `--sms-surface-2`, `--sms-border`, `--sms-muted` — never hard-code brand colours. For charts use `themeColors()`. - Per-user preference: `PUT /auth/preferences`; school default: Settings keys `appearance.*`.