# Open questions and decisions taken

Each item says what is unclear or conflicting, and the option chosen for now (the safest one). Please confirm or correct.

## Plan / schema

1. **Stack versions.** The plan says PHP 8.3 and MySQL 8; local is XAMPP (PHP 8.2, MariaDB 10.4+).
   *Chosen:* code targets PHP 8.2+ (`config.platform.php = 8.2.12` in composer.json) and migrations run on MariaDB 10.4+ and MySQL 8.

2. **`academic_templates` placement.** The Academic tab calls it a "platform" table, the SQL file puts it in the Academic section.
   *Chosen:* migration lives in `Modules/Academic` (follows the SQL grouping); it has no `school_id` and no tenant scope.

3. **`student_subjects` placement.** Listed in the Academic tab, but in the Students section of the SQL and it references
   `student_enrollments`. *Chosen:* `Modules/Students` (needed for FK order).

4. **`custom_fields` / `custom_field_values` placement.** Introduced in the Students tab but shared by Academic and later Staff;
   the SQL puts them in Core. *Chosen:* core (`database/migrations`).

5. **Expired add-ons.** The main tab says `EnsureModuleEnabled` returns 403 when a module has expired; the `school_modules`
   notes say "expired add-ons turn read-only, data kept". *Chosen:* 403 for every request on an expired or disabled module
   (data is kept in the database). Read-only access can be added later by allowing GET for `expired` status.

6. **Permission lists.** The main tab's standard actions (`view, create, edit, delete, export, print`) and extras
   (`fees.create`, `fees.discount`, `academic.edit`…) differ from the module tabs. *Chosen:* module tabs are used exactly
   (e.g. Fees has no `fees.create`; Academic uses `academic.manage_years` etc.). Core keeps the standard set for
   `branches`, `users`, plus `roles.manage`, `settings.manage`, `activity_logs.view`.

7. **`permissions.module_slug` for `timetable.*`, `portal.*`, `custom_fields.manage`.** These prefixes are not module slugs.
   *Chosen:* `timetable.*` → `academic`; `custom_fields.manage` → `students`; `portal.view_profile` → `students`;
   `portal.view_fees`, `portal.pay_fees` → `fees`; `portal.view_timetable` → `academic`. Core permissions use module_slug `core`.

8. **Schema differences from the PDF tables.** The SQL file was used as-is where it is more specific than the PDF:
   `student_import_rows.sheet_row` (PDF: `row_number`, a reserved word in MySQL 8), `activity_logs.event` and `batch_uuid`
   (needed by spatie/activitylog v4), `settings.branch_key` and `id_formats.branch_key` generated columns, `period_sets.branch_id`
   NOT NULL, `roles.data_scope` default `assigned_branches`.

9. **School Super Admin role row.** The plan says Super Admin is a locked system role, and users also have `is_super_admin`.
   *Chosen:* `is_super_admin` is what `Gate::before` checks; a locked `School Super Admin` role (`is_system`, `all_branches`)
   is also created per school and assigned, so it shows in the role list.

## Phase 0 scope

10. **2FA for platform users.** Required by the plan, but not in the Phase 0 list. *Chosen:* deferred to Phase 1;
    the `two_factor_secret` column exists. Until then the platform panel relies on a strong password.
    **Do not expose the platform panel publicly before 2FA is built.**

11. **Account lock after repeated failures.** The plan asks for a 5/minute rate limit and an account lock. *Chosen:* the
    5/minute rate limit (per login + IP) is in Phase 0; locking (`status = locked`) is deferred to Phase 1 with the Users screens.

12. **Data scope when a user has several roles.** Not stated. *Chosen:* the widest scope wins
    (`all_branches` > `assigned_branches` > `own_records`).

13. **Default data scope for queued jobs / console.** With no logged-in user, `BelongsToBranch` applies no branch filter
    (the school filter still applies, and with no school set nothing is returned). Jobs must set the school explicitly.

14. **Module menu placeholders.** Each Basic module gets an index route (`/students`, `/academic`, `/fees`) that shows a
    "coming in Phase N" page, so the sidebar, module middleware and permission middleware can be tested. No module screens are built.

## Migrations

15. **`fee_reminders.sent_at` default.** On MariaDB < 10.10 (XAMPP) and on MySQL with `explicit_defaults_for_timestamp=OFF`,
    the first `TIMESTAMP NOT NULL` column without a default silently becomes `DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP`,
    so updating a reminder would overwrite when it was sent. *Chosen:* the migration declares `sent_at ... DEFAULT CURRENT_TIMESTAMP`
    (no `ON UPDATE`). This is the only difference from `school_erp_schema.sql`; everything else (columns and order, types, defaults,
    generated columns, indexes, foreign keys with names and delete rules, CHECK constraints, engine and collation) was verified
    identical on MariaDB 10.11 by comparing `information_schema` of both databases.

16. **Password resets are not tenant-aware.** Laravel's `password_reset_tokens` is keyed by email only, but emails are unique per school,
    not globally. *Chosen:* left as Laravel's default table for now (forgot-password is Phase 1); it must gain `school_id` (or use
    `users.id`) before the reset screen is built.

## Phase 0 implementation choices

17. **Roles are not tenant-scoped by a global scope.** Spatie caches all roles and permissions of every school together; a
    `school_id` global scope on `Role` would make that cache depend on whichever school filled it. Spatie's teams mode already
    limits a user's roles to the current school (`model_has_roles.school_id`). *Chosen:* `Role` is exempt from `BelongsToSchool`
    (listed with the reason in the architecture test); role screens in Phase 1 must use `Role::forCurrentSchool()` and policies.

18. **Trial schools after `trial_ends_at`.** The plan does not say what happens. *Chosen:* nothing automatic yet; a trial school
    keeps working until the Platform Owner suspends it. A scheduled expiry job can come with billing.

19. **Current branch.** `BelongsToBranch` filters but does not fill `branch_id`, because the branch switcher (Phase 1) does not
    exist yet. *Chosen:* `branch_id` always comes from validated input.

20. **Tabler assets from a CDN** (`cdn.jsdelivr.net`, pinned versions). No Node build is needed, but pages are unstyled offline.
    Can be copied into `public/vendor` later if schools need offline use.

21. **Tests run on SQLite in memory** (fast, no setup). CHECK constraints are not created there, so the suite was also run on
    MariaDB 10.11 (all green). Run both before changing the schema.

22. **Default demo passwords** (`password`) are for local use only. Production seeding should not run `DemoSchoolSeeder`,
    and the platform owner's password must be changed (2FA comes in Phase 1).

## Phase 1 implementation choices

23. **Branch switcher narrows every branch-owned list.** Picking a branch in the top bar filters `BelongsToBranch` queries to it;
    "All branches" is offered only to users who can see more than one. The value is re-checked against the user's allowed
    branches on every request.

24. **Fees settings.** The core screen list says Settings (general, academic, fees, notifications) needs `settings.manage`; the Fees
    tab says Fee Settings needs `fees.settings`. *Chosen (module tab wins):* one Settings screen; the Fees group needs `fees.settings`
    and the Fees module, the other groups need `settings.manage`. The Academic group (student admission options) shows when Students is on.

25. **Account lock.** ✅ *Decided (owner): School Super Admins are never locked out.* 10 wrong passwords in a row within a day lock the account (`status = locked`); a user with `users.edit` sets it back
    to active. School Super Admins are never locked (the 5/minute rate limit still applies), so a school can't lock itself out.
    The counter lives in the cache: no schema change.

26. **2FA recovery codes.** ✅ *Decided (owner): add them.* 8 one-time codes (`xxxxx-xxxxx`) per account, shown once when 2FA is
    turned on, regenerated from My profile / the platform account page (current password needed), removed when 2FA is turned off
    or reset. Stored as HMAC hashes in a new table `two_factor_recovery_codes` (not one of the 56 plan tables; the plan schema has
    no column for them). Admin reset (school) and `php artisan platform:reset-2fa` stay for users who lose both.

27. **Yearly ID reset.** ✅ *Decided (owner): restart with the academic year.* Yearly formats restart when the academic year starts
    (Settings > General > "Academic year starts in", default June) and `{YYYY}`/`{YY}` show the year the session starts
    (2026 for 2026-27). Phase 2 can read the start date from `academic_years` instead of the setting.

28. **ID "next number" can only go up**, so numbers already given out never repeat. School code and subdomain cannot be changed after
    creation (IDs, links and bookmarks use them).

29. **Deleted users keep their username.** Users are soft-deleted and `UNIQUE(school_id, username)` includes deleted rows, so a
    username cannot be reused. Same for branch codes.

30. ⏸ *Decide later (owner).* **Platform screens still missing**: plans and module prices, subscriptions and payments, "login as" a school super admin, platform users.
    They are in the plan's first-release screen list but not in the Phase 1 (Core) line of the build phases. Not scheduled yet.

31. **`password_reset_tokens` now has `school_id`** (migration `2026_01_01_002100`). It is Laravel's table, not one of the 56.

## Phase 2 (Academic) implementation choices

32. ✅ *Built in Phase 3.* **Elective choices per student (`student_subjects`) were not built in Phase 2.** They are stored per student enrollment, and enrollments
    come with the Students module (Phase 3). *Chosen:* build the "Elective Choices" screen in Phase 3; its sub-menu entry and
    `academic.manage_electives` permission are already in place.

33. **Excel import of classes, sections and subjects** ✅ built in Phase 3 (Academic > Import): same upload → preview → error file →
    import flow as student import. Existing names are reported as errors, never overwritten.

34. ✅ *Built in Phase 3.* **Custom fields on classes, sections and subjects** use the custom-fields system that arrives with Students (Phase 3).

35. **Inline editing and drag-to-reorder.** Lists use small forms per row and an order number instead of drag-and-drop
    (no JavaScript build). Can be added later.

36. **Print and PDF of timetables** use the browser's print (Print → Save as PDF); no PDF library on the server.

37. ✅ *Built in Phase 3.* **Portal timetable** (`portal.view_timetable`) comes with the parent/student portal in Phase 3.

38. **Board templates are generic starting points** (class names, wings, common subjects per stage), not official board syllabi;
    the wizard says so and everything is editable. The Platform Owner can maintain them in `academic_templates` (screen later).

39. **Timetable teacher clash** compares real clock times, so sections on different bell schedules, and teachers working in
    several branches of the same school, are checked too. Elective-group slots check every subject teacher of the group.

40. **Deactivating a teacher** who still holds class-teacher posts, subject assignments or timetable periods in open years is
    stopped with the list; ticking "Deactivate anyway" goes ahead (the plan: "lists their assignments so they can be reassigned first").

41. **Yearly ID reset** still reads the "Academic year starts in" setting (item 27). Now that academic years exist, it could use the
    current year's start date instead; kept on the setting so IDs keep working if a school switches the Academic module off.

## Phase 3 (Students) implementation choices

42. **Aadhaar uniqueness.** Aadhaar is stored encrypted (random IV), so the database cannot index it. *Chosen:* the duplicate check
    decrypts only the school's students whose stored last-4 digits match, inside the admission transaction. Fine for school sizes;
    a keyed hash column could be added later if a school has very many students.

43. **Promotion batches** are recorded with `activity_logs.batch_uuid` (no extra table). "Undo" reverts a batch once, and only
    until fee dues exist for those students in the new year.

44. **Student list column picker** is remembered per browser (localStorage), not per user on the server.

45. **Imports over 300 rows run on the queue**: a worker must be running (`php artisan queue:work`, see LOCAL_SETUP §8).
    Up to 300 rows are imported straight away.

46. **Not built yet:** the age-for-class warning on admission, and cropping the photo in the browser (photos are only checked for
    type and size). Both need decisions on rules/JS and can come later.

47. **Portal fees** (`portal.view_fees`, `portal.pay_fees`) come with Fees (Phase 4). `StudentStatusChanged` is fired on leave,
    suspend, reactivate and pass-out so Fees can stop future installments.

48. **Parent logins** use the primary guardian's mobile number as username (one login per family, sees all their children);
    student logins use the student code. Both get an 8-character password shown once (and a WhatsApp share link) and must change it.

49. **Demo data.** The demo school is seeded empty (no years, classes or students). Use the setup wizard (Academic > Setup) and
    the import templates to fill it.

## Phase 4 (Fees) implementation choices

50. ✅ *Confirmed (owner): several concession types, percent or amount.* **Fixed-amount concessions** are a yearly amount spread over the student's lines of the covered heads in proportion to
    their amounts (percent concessions apply to each line). Several concessions add up; a line's concession never exceeds its
    amount. Only lines with nothing paid change when a concession is approved, revoked or edited.

51. ✅ *Confirmed (owner).* **Which fine rule applies.** When several active rules match a line (head and class), the oldest rule wins. Fines are
    recalculated nightly (`fees:fines`); a waiver or a paid fine is never taken back by a later recalculation.

52. ✅ *Decided (owner): at the counter, staff decide.* Staff type (or tick in full) how much each due line gets; money above
    what they apply becomes credit, and an amount with nothing applied while dues are open must be ticked as an advance. A
    "spread oldest first" button only fills the boxes. Online payments and automatic credit use oldest due first, then head
    priority. Inside a line the fine is paid before the fee.

53. **Stream structures.** A student gets their stream's structure when one is published, else the class-wide one
    ("all streams"). Moving to a section of another stream replaces unpaid future lines; paid and past lines stay.

54. **Mid-year admission**: installments due before the admission are skipped except the current one (the last one already due);
    one-time heads are always charged, due on the admission date. "Charge installments already due" in Fee Settings charges all.

55. **Credit is applied automatically** to new dues (structure, admission, manual charges) as a receipt with mode `credit`
    (Fee Settings can turn it off).

56. **Cancelling a receipt that added credit** needs that credit to still be there; if it was used since, cancel the later receipt first.

57. **Refunds**: a refundable head keeps its line as paid (the refund is noted on it and in `fee_refunds`); a credit refund debits the
    credit ledger; an online refund of the whole receipt cancels it (its lines are due again) and a part refund comes out of the
    student's credit. The requester can never approve their own refund, super admins included. Paying out an approved refund is
    allowed to `fees.refund` or `fees.approve_refund`.

58. ✅ *Decided (owner): both.* **Carry forward** runs from Fees > Carry Forward and automatically when a promotion (or detention)
    creates the student's next-year enrollment; undoing the promotion cancels the carried line and the old lines are due again. Students with no enrollment in the new
    year keep their dues in the old year ("Former students with dues"). Carrying into a year needs that year open; the old
    year may be closed.

59. **Razorpay**: each school enters its key id, key secret and webhook secret (Fee Settings) and sets the webhook URL
    `https://<school>.<domain>/fees/razorpay/webhook` (events `payment.captured`, `payment.failed`) in its Razorpay dashboard.
    The convenience fee is a percentage chosen in Fee Settings and is kept on the order, not on receipts.
    **Test with Razorpay test keys before a school goes live.**

60. **Scheduler**: `fees:fines` (nightly), `fees:reconcile-online` (every 15 minutes), `fees:remind` (daily, only when email
    reminders are on). Locally run `php artisan schedule:work`; servers need the usual `schedule:run` cron.

61. **Reports** are on screen with Excel export; PDF is the browser's Print → Save as PDF (no PDF library on the server).

62. **Not built in v1** (as planned): automatic SMS/WhatsApp through a paid provider, Tally export, GST invoices, payment links for
    non-portal parents, transport fee by route.
    ✅ *Built (owner asked):* fee tiles on the dashboard (my collection today, collected today, overdue, due in 7 days,
    online payments to check, concessions and refunds waiting for approval), each shown only with its permission.

63. **Bug fixed in core**: the branch scope could lose its user filter when first applied inside `withSum`/`withCount`/`whereHas`
    (Laravel switches relation constraints off there). `BranchScope` now enforces constraints; a regression test covers it.

## Phase 5 (Pilot) — readiness

64. **Scope chosen by the owner: pilot readiness only.** Built: HTTPS and security headers, backups, the go-live check
    (`erp:preflight`), route-protection tests, production seeding and [DEPLOY.md](DEPLOY.md). Not built (still open):
    school onboarding checklist and demo data, "log in as" for support, and billing (plans and prices, subscriptions,
    payments, platform users — item 30).

65. **No Content-Security-Policy yet.** Pages load Tabler from a CDN and use small inline scripts; a strict CSP needs the
    assets copied into `public/` and the scripts moved to files. The other headers (nosniff, frame, referrer, HSTS) are on.

66. **Backup copy to another provider** needs a disk for it (S3-compatible or SFTP, one composer package); the plan asks for a
    different provider, so `erp:preflight` fails until `BACKUP_COPY_DISK` is set.

67. **Production seeding** creates no demo school, and the first Platform Owner gets `PLATFORM_OWNER_PASSWORD` or a random
    password printed once (never `password`).

## Fees additions (owner request after Phase 5)

68. **New tables, not in the 56 of the plan:** `deposit_accounts` (bank accounts and cash boxes), `fee_accounts` (groups of heads
    with their own receipts) and `fee_day_closes`; `fee_heads.fee_account_id` and `fee_payments.fee_account_id`,
    `deposit_account_id`, `receipt_group`. Migration `2026_01_04_001600`.

69. ✅ *Decided (owner): fee accounts and bank/cash accounts, both.* Heads belong to a fee account (none = the default "School
    fees" account). One payment makes one receipt per fee account, each with its own ID-format series (`receipt_<id>`, editable
    under ID formats; the default account keeps the school's receipt series). Money above the dues (credit) goes on the first
    receipt; credit used is spread over the receipts in order. Cash goes to the account's cash box, every other mode to its bank
    account; online payments use the bank account. Cancelling one receipt of a group leaves the others.

70. ✅ *Decided (owner): DCR (Day Challan Receipt).* Each **branch** has its own DCR. It closes automatically at the DCR time the
    School Super Admin sets (all branches), or earlier when a user with the new permission `fees.close_day` (branch accounts)
    closes their own branch. Each closed DCR gets a number from ID formats (entity `dcr`, `{PREFIX}-DCR{YY}-{SEQ}`) and a
    printable DCR (receipts, totals by mode, collector and deposit account, refunds, signature lines). After a branch's DCR
    is closed, its receipts are dated the next day; other branches keep their own day.
    *Earlier decision (owner): after the closing time, receipts go to the next day.* The School Super Admin sets the time (Settings >
    "Fees: daily closing"; only super admins see it). The counter shows the date receipts will get and no longer lets staff pick a
    date. **A closed day's receipts cannot be cancelled** (a cheque can still bounce; it is recorded when it happens). Without a
    closing time a day closes at midnight, so cancelling now works only on the same day — this is new for all schools.
    The Super Admin can also close the day early.

71. **No holiday calendar yet**: after the closing time receipts go to the next calendar day even if it is a Sunday or holiday.

72. Receipts made before fee accounts existed have no account; reports show them under "School fees".

73. `fee_day_closes` was rebuilt per branch with a DCR number (migration `2026_01_04_001700`); it only holds closing summaries,
    which `fees:close-days` re-creates.
