# CLASS SCHEDULING SYSTEM — Project Instructions

> This file is the authoritative reference for converting the existing Class
> Scheduling System **prototype** into the **final project**. Read this file
> fully before making any changes to the codebase. Treat it as a living spec:
> follow it exactly, and flag any ambiguity instead of guessing.

---

## 0. How to Work in This Repo (read this first)

- The existing prototype is **approved** and is the baseline. **Do not**
  rebuild it from scratch.
- Existing modules, database structures, layouts, and working features must
  be **retained** unless a section below explicitly says to change them.
- Before touching anything: inspect the current models, migrations,
  controllers, routes, Blade files, CSS, and JS relevant to the area you're
  changing.
- Reuse existing working code whenever possible. Modify only the files
  affected by the revisions below.
- For DB changes, add **new migrations** rather than editing old ones that
  may already have run in an environment.
- Never delete existing records unless deletion is required and explicitly
  approved here.
- Apply revisions **one module/phase at a time** (see Section 12,
  Implementation Sequence) and test each phase before moving to the next.
- Preserve all functionality not addressed by this document.
- Remove prototype-only labels ("Proposal Prototype Version", "Prototype
  Preview", "Prototype Navigation") and replace with final-system wording.
- Prefer asynchronous (AJAX/fetch) operations over full-page reloads where
  it makes sense.
- Keep the interface responsive across desktop, laptop, tablet, and mobile.
- Don't add `form-text`/helper explanatory captions under form fields to
  explain how a field behaves. Labels, placeholders, and validation error
  messages should carry that on their own; a field that needs a paragraph
  to explain itself should be redesigned, not annotated.

---

## 1. Subject Structure: Hours

The system measures subjects in **hours** (the earlier unit-based structure
was reverted; migration `rename_units_to_hours_on_subjects_and_schedules`).

- Subject field: `Weekly Hours` (DB column `weekly_hours`) — the required
  hours scheduled per week.
- Total Hours is **not stored** (column dropped); it is derived as Weekly
  Hours × the weeks in the subject's applicable School Term.
- Each schedule entry stores the hours assigned to that timetable cell
  (`assigned_hours`) and its length in minutes (`duration_minutes`).

**Hours apply everywhere:** subject create/edit, track-subject assignment,
schedule create/edit, teacher load computation, schedule completion
checking, Subject Hour Tracker, reports, dashboard summaries, validation
rules.

**Hour rules:**
1. Weekly Hours = required hours scheduled weekly.
2. Every occupied schedule cell must have an assigned hour value.
3. Assigned hours feed into weekly-scheduled-hours computation.
4. Subject status per section: **Complete / Incomplete / Exceeded**.
5. Hour totals must recompute after add / edit / delete / copy / move / swap.

---

## 2. Scheduling Module

### 2.1 Workspace layout — two panels

**Left panel** (dynamic, changes with scheduling step): available subjects,
subject hour input, available teachers, room selection, current selection
summary, back/cancel.

**Right panel**: grade/section selector, selected section info, weekly
timetable grid (primary workspace), Subject Hour Tracker.

### 2.2 Summary cards (removed)
The Total Sections / Completed Schedules / Incomplete Schedules overview
cards have been **removed from the Scheduling page** per explicit request.
Overall progress is still visible via the Grade/Section selector's red/
yellow status indicators (2.4) and via the Dashboard, which keeps its own
independent overall-completion summary — do not re-add this card to
Scheduling in a future revision without a new explicit request.

### 2.3 Grade/Section selector (replaces plain dropdowns)
Hierarchical: `Grade 11` / `Grade 12`, expand on hover/click to section list
(e.g. `Grade 11 > Section A/B/C`). Selecting a section loads its timetable
immediately, no full reload.
- Selected section stays highlighted until changed.
- Section list = active sections under active School Year only.
- Selector shows status indicators (see 2.4).

### 2.4 Status indicators
- **Red dot** — section has no schedule entries. Bubbles up to Grade Level
  if any section under it is unscheduled.
- **Yellow dot** — section has entries but incomplete. Bubbles up similarly.
- **Priority:** red > yellow at the Grade Level when both exist; individual
  sections keep their own correct color.
- Completed sections need no dot (optional "completed" indicator may come
  later — not required now).
- Indicators refresh after add/edit/delete/copy/move/swap.

### 2.5 Selected section header
Show: School Year, Term, Grade Level, Shift Type, Section — sourced from
the selected section + active academic period. The old separate School
Year/Term dropdown filters on this page can be removed (Admin Settings now
owns active period).

### 2.6 Timetable grid
- Rows = configured time slots (filtered to the section's Shift Type),
  columns = Mon–Fri, break rows per configured break slots.
- Break cells never accept entries.

### 2.7 Cell content (occupied cells), in this order:
`Subject`, `Subject Hours`, `Teacher`, `Room` — compact, readable. Empty
cells must look visually distinct from occupied ones.

### 2.8 Cell selection
Click highlights the cell border (clears any prior highlight), sets the
active day/time slot, updates the left panel accordingly. Clicking a break
cell does nothing. Selection must never resize/shift the grid.

### 2.9 Dynamic left-panel workflow
1. **Default state** — instructions, section summary, legend, completion
   status.
2. **Subject selection** — list subjects filtered by section's Track, Grade
   Level, active Term, active status, active track-subject assignment. Each
   item shows: name, code, Hours/Week, scheduled hours, remaining hours,
   completion status.
3. **Hour input** — required, numeric, reject ≤0, follow DB decimal/whole
   rules, show remaining required hours, warn if it would exceed
   Weekly Hours.
4. **Teacher selection** — active teachers assigned to the subject only;
   show name, current/max/remaining weekly load, availability/conflict for
   the selected day+slot. Check conflicts immediately on pick.
5. **Room selection** — active rooms only; check room conflict, room-type
   requirement, availability.
6. **Save** — on success: update the cell, no full reload, refresh Subject
   Hour Tracker + status indicators + summary cards (if needed), left panel
   returns to subject list/default, show success toast.

### 2.10 Occupied-cell action menu
Hover reveals a three-dot button (top-right, inside the cell, no
resize/shift, keyboard-focusable) → **Edit** / **Delete**. Must not trigger
normal cell selection when clicked.

### 2.11 Edit modal
Editable: Subject, Teacher, Hours, Room only.
Not editable here: School Year, Term, Grade Level, Section, Shift Type,
Day, Time Slot (use move/swap for day/time changes).
Revalidate before save: subject assignment, teacher-subject assignment,
teacher conflict, room conflict, hour allocation, teacher load, Weekly
Hours, specialized room requirement. On success: close modal, update cell,
update tracker + indicators, toast, no full reload.

### 2.12 Delete workflow
Confirm dialog shows Subject/Teacher/Day/Time/Section; Cancel or Confirm.
On delete: cell empties, tracker updates, completion recalculated,
indicators update, summary cards update if needed, no full reload.

### 2.13 Drag: swap / move / copy
Interaction trigger: double-click/double-tap then drag.
- **Swap** (occupied → occupied): exchange Subject, Assigned Hours, Teacher,
  Room between the two cells; day/time stay tied to grid position; validate
  both resulting positions before committing.
- **Move** (occupied → empty): relocate entry, source cell empties,
  destination day/time from target cell; validate before saving.
- **Horizontal copy**: within the same time-slot row, across weekday
  columns; copies Subject, Assigned Hours, Teacher, Room.
- **Vertical copy**: within the same day column, across time-slot rows;
  copies the same fields. Break rows can be dragged across but are never
  a target. The gesture locks to one axis (row or column) - no diagonal
  or L-shaped fills. (Vertical copy was enabled per explicit request,
  replacing the earlier "no copy across time-slot rows" restriction.)
- **Pre-drop validation**: teacher conflict, room conflict, section
  conflict, teacher workload, subject
  hour total, break-cell restriction, shift/time-slot compatibility.
- **Failed drop**: snap back to original cell, no DB writes, show
  conflict/validation toast, no layout shift.

### 2.14 Duplicate subject same day
A section may have the same subject more than once on one day. There is
**no warning and no restriction** for add/copy/move/swap/edit (the earlier
"This subject already exists on this day." Cancel/Continue prompt was
removed per explicit request — do not re-add it without a new request).

### 2.15 Teacher conflict
Same teacher + same Term/Day/Time-slot on another section = conflict.
- Highlight the conflicting cell in red.
- Non-intrusive overlay notification (doesn't push/resize the timetable,
  dismissible) showing teacher, conflicting section, subject, day, time,
  room.
- **Blocking**: unresolved teacher-time conflicts must not save.

### 2.16 Room conflict
Same room + same Term/Day/Time-slot on another section = conflict.
Identify conflicting room/section, block save, show non-intrusive
notification, preserve current scheduling state for correction.

### 2.17 Section conflict
A section can never have overlapping entries in the same day+time-slot
cell — enforce in UI and DB/validation layer. A cell may hold more than one
entry only when their durations fit inside the slot's total minutes (e.g.
the leftover of a slot after a shorter entry); a leftover of 15 minutes or
less is not a usable teaching period.

### 2.18 Teacher–subject validation
Only teachers assigned to the subject are selectable — validate both
client-side and server-side (a hand-crafted request must not bypass this).

### 2.19 Teacher load validation
Compare Max Weekly Load vs Assigned Weekly Hours vs Remaining. Exceeding
max → overload warning showing resulting load. **Current rule: warning +
confirm, not a hard block** (may change in a future revision).

### 2.20 Subject hour validation
When an operation would push scheduled hours past Weekly Hours: warn,
show required vs resulting scheduled hours, allow Cancel/Continue. If
continued, tracker marks subject **Exceeded**.

### 2.21 Subject Hour Tracker
Below the timetable; one row per subject required by the section, showing
Subject, Hours/Week, Scheduled Hours, Remaining Hours, Status
(Complete / Incomplete / Exceeded — see rules in Section 1). Updates after
every schedule mutation, without a full page reload.

### 2.22 Section schedule completion
Complete = every required subject (by Track/Grade/Term) hit its Weekly
Hours. Incomplete = no entries, or any subject under-scheduled. Exceeded
subjects stay visible in the tracker (never hidden/normalized away).

---

## 3. Academic Setup

**Final structure:** Tracks and Subjects · Sections and Rooms · Shift Types
and Time Slots. **Academic Period management is removed from here** (moves
to Admin Settings).

### 3.1 Track-based subject management
Admin can: create/edit/activate/deactivate a Track; view a Track's
subjects; assign/remove a subject to/from a Track; filter subjects by
Track, Grade Level, Term.
- Subjects do **not** auto-belong to every Track.
- A subject can belong to multiple Tracks only via separate assignment.
- Removing a subject from one Track must never delete the subject, remove
  it from other Tracks, or delete unrelated subject records.

### 3.2 Track-subject assignment data
Fields: Track, Subject, Grade Level, School Term, Active Status. Scheduling
module uses this to determine which subjects appear for a section.
Use "Track" consistently in UI/code unless institutional terminology
requires "Pathway" — existing DB naming may stay temporarily if renaming is
risky, but **user-facing labels must use final terminology**.

### 3.3 Subject form updates
Subject form uses Weekly Hours only (Total Hours is derived, not entered).
Keep: Subject Code, Subject Name, Subject Type, Specialized Room
Requirement, Active Status. Subject list shows hour info.

### 3.4 State preservation (Academic Setup page)
Add/Edit/Activate/Deactivate/Assign/Remove/Delete should be async where
possible. After any operation, **preserve**: open tab, expanded panel,
selected Track/Grade Level/Term, search input, active filters, scroll
position, current page of pagination.
- **Partial refresh only** — e.g. adding a subject refreshes just the
  subject list; assigning refreshes just that Track's assignments; editing
  a section refreshes just the section list; updating a time slot refreshes
  just the active Shift Type panel.
- Validation errors: show inline without closing the tab/panel, preserve
  entered values, flag exact invalid fields, no full reload.
- Success: non-intrusive notification, workspace state not reset.
- Disable submit buttons while a request is in flight (no duplicate
  submits).

### 3.5 Academic Period relocation
Remove from Academic Setup: School Year management, School Term
management, active School Year/Term selection. → moved to Admin Settings.

---

## 4. Admin Settings

Add an **Academic Period** section supporting: create/edit School Year
(with start/end dates), activate/deactivate School Year; create/edit
School Terms under a Year (with start/end dates), activate/deactivate
Term.
- Only one School Year active at a time.
- Only one applicable Term (under the active Year) active at a time.
- Activating a new Year/Term must safely deactivate the previous one.
- The active Year/Term drives: Dashboard, Academic Setup, Teachers,
  Scheduling, Reports.

---

## 5. Preserve As-Is (unless a section above changes it)

Administrator authentication · Dashboard · Academic Setup (structure aside)
· Teacher records · Teacher-subject assignment · Teacher load monitoring ·
TEA credit and loan records · Scheduling (behavior aside) · Reports ·
Responsive sidebar/topbar · existing Laravel models/relationships that
still apply · existing DB records · existing routes where still
appropriate.

---

## 6. Out of Scope for This Revision

Do **not** implement these unless they already exist in the prototype —
wait for a separate approved revision:
- Fully automatic schedule generation
- New user roles
- Payroll integration
- Advanced financial accounting
- New notification center
- New analytics modules
- New audit-log module
- Mobile application
- External API integration

---

## 7. Implementation Sequence (do phases in order, test each before next)

1. **Project Audit & Backup** — inspect Laravel/PHP versions, routes,
   controllers, models, migrations, Blade, CSS, JS; commit/backup baseline;
   record existing DB dependencies.
2. **Database & Models** — `weekly_hours` on subjects, `assigned_hours` /
   `duration_minutes` on schedules; preserve existing data; update
   casts/fillable/relationships/validation/computed values.
3. **Admin Settings** — build/extend Academic Period management there;
   wire active Year/Term globally.
4. **Academic Setup** — update Track/Subject management, hour-based subject
   forms, strengthen Track-subject assignments, add async submission,
   preserve tabs/filters/selected Track/scroll state.
5. **Scheduling Data Services** — section-completion queries, subject-hour
   calculations, section-status indicator logic, teacher/room conflict
   validation, filtered subject/teacher queries.
6. **Scheduling Interface** — Grade 11/12 hierarchical selector with red/
   yellow dots, dynamic left panel, timetable header, cell content, Subject
   Hour Tracker.
7. **Scheduling Interactions** — cell selection; subject→hours→teacher→room
   workflow; three-dot menu; Edit modal; Delete confirm; move/copy/swap;
   duplicate-subject warning; conflict overlays.
8. **Reports & Remaining Modules** — hours in reports, teacher load
   calc updates, remove prototype labels, verify unaffected modules still
   work.
9. **Testing** — migrations, data preservation, Track-subject filtering,
   Academic Setup state preservation, schedule create/edit/delete,
   horizontal copy, move, swap, teacher conflict, room conflict, duplicate
   subject warning, hours-exceeded warning, teacher overload warning,
   section completion, red/yellow indicators, responsive layout, report
   hour values.

---

## 8. Guiding Principle

> Inspect first, preserve what works, modify only what the approved
> revisions require, and implement one tested phase at a time.

This is an **improved continuation** of the approved prototype — not a
rewrite.
