# Masar / مسار

Arabic RTL educational counseling platform. Stage 1 establishes a React + TypeScript frontend and a separate Laravel API.

Start with [Stage 1: foundation](docs/STAGE_1_FOUNDATION.md) for setup, architecture, scope, and verified checks. See [the documentation index](docs/README.md) for design and responsive requirements.

For server installation and updates, follow the maintained [deployment instructions](docs/DEPLOYMENT.md).

After installing dependencies and preparing `backend/.env` as documented:

```powershell
npm run dev
```

- Frontend: <http://127.0.0.1:5173>
- API health: <http://127.0.0.1:8000/api/v1/health>
- Central visual configuration: [`style-theme.config.json`](style-theme.config.json).

```powershell
npm run build
npm test
```

The Laravel backend includes Arabic/English administration for directorates, schools, staff users, fixed user types, and counselor assignments. The React frontend opens to a bilingual public landing page with news, articles, and separate staff login. Directorate heads now manage their schools and staff from the frontend. Public registration remains disabled; counseling workflows are later work.

## Public frontend and staff portal

- `/` explains Masar, its roles, available features, and planned counseling workflows, using a public navbar/footer.
- `/news` and `/articles` list public content; `/read/:slug` opens full details. The homepage previews three items per section. Three news items and three articles are seeded in Arabic/English and labeled as sample content. Publishing/editing screens are not included.
- Frontend `/login` accepts active directorate heads, supervisors, and counselors through Laravel's separate `staff` session guard. Super admins use the backend login on port 8000. `/portal` redirects directorate heads to `/portal/directorate`, supervisors to `/portal/supervisor`, and counselors to `/portal/counselor` (then `/profile`). Students and school managers do not receive accounts.
- The super admin manages staff passwords through Users. Demo accounts retain their random passwords; use their Edit dialog to set a password when access is needed. No existing passwords were reset.
- Display settings contain language and Light/Dark/Auto toggles. Frontend preferences persist locally (`masar-public-locale`, `masar-theme`); backend preferences remain separate, without cross-origin synchronization. Earlier Stage 1 previews remain at `/dashboard`, `/registers`, and `/cases`, without private staff/student data.

Set `VITE_BACKEND_URL` in `frontend/.env` to the Laravel base URL (without `/api/v1`), for example `https://admin.masar.example.com`. All public API, staff login, workspace and XLSX requests use this URL directly. Set `CORS_ALLOWED_ORIGINS` in `backend/.env` to the exact frontend origin. Rebuild the frontend after URL changes. Staff sessions use credentialed Laravel cookies and in-memory CSRF tokens. See [deployment instructions](docs/DEPLOYMENT.md) for HTTPS and same-site/cross-site cookie settings. Leaving `VITE_BACKEND_URL` empty retains relative requests and the optional development proxy.

For local Vite development, the example leaves `VITE_BACKEND_URL=` empty and uses `API_PROXY_TARGET=http://127.0.0.1:8000`. This supports both `localhost:5173` and `127.0.0.1:5173` through same-origin browser requests. Do not combine a localhost frontend with a direct 127.0.0.1 backend URL: the different sites can block login cookies and produce a session-expired/419 message. Refresh and sign in on your chosen address after changing the environment. Set the direct HTTPS backend URL before production builds.

The tracked `frontend/public/.htaccess` is copied automatically to `frontend/dist/.htaccess` by every frontend build (`npm run build`). Deploy the entire `dist/` directory, including this hidden file. On Apache, enable `mod_rewrite` and allow `FileInfo Options Indexes` overrides for the frontend directory (or use `AllowOverride All`). The file serves existing assets normally and sends frontend routes to `index.html`, so direct links and page refreshes work. It excludes `/api` and `/staff-auth` from the SPA fallback. With a direct backend URL, these endpoints are served on the backend hostname and need no frontend proxy.

After verifying the database target and backing up existing data, run from `backend/`:

```powershell
& C:/laragon/bin/php/php8.3/php.exe artisan migrate --no-interaction
& C:/laragon/bin/php/php8.3/php.exe artisan db:seed --class=PublicationSeeder --no-interaction
```

`PublicationSeeder` is local/testing-only, inserts missing slugs, and preserves edits. It is included in `DatabaseSeeder`. Public API: `GET /api/v1/publications?type=news|article&locale=ar|en&page=1` (six per page) and `GET /api/v1/publications/{slug}?locale=ar|en`. Draft/future items are excluded; bodies are detail-only and rendered as plain text.

## Directorate-head workspace

Directorate-head workspace: sign in through the frontend with an active `directorate_head` account assigned to an active directorate. It provides scoped overview counts, school/user lists and details, searchable filters, paginated tables, Create/Edit dialogs, activation/deactivation, and counselor school/supervisor assignments. Only supervisors/counselors can be managed; heads cannot change their own role, manage other heads/super admins, or access another directorate. Manager contacts remain school fields, and Students stays reserved. Use the backend Users/Edit dialog to set an existing demo head's password if needed; this implementation does not reset passwords or seed additional live data.

Authenticated JSON endpoints are under `/api/v1/directorate`: `overview`, `options`, `schools`, `schools/{id}`, `users`, and `users/{id}`. Lists use GET, creation POST, and editing PUT; deletion is unavailable. They use Laravel's web/session/CSRF middleware and the staff/head checks, while preserving the API version. Lists paginate at 25, lookups return at most 100, and write payloads inherit the directorate on the server rather than accepting a directorate selector. Existing schema is sufficient; no new migration or seed run is required for this workspace.

## Backend administrator

Open <http://127.0.0.1:8000/> to reach the login page. Only active super administrators can sign in to this backend area. After signing in, `/admin` shows module counts and navigation to directorates, schools, users, and user types. See [the Stage 2 implementation record](docs/STAGE_2_MANAGEMENT.md#local-implementation-and-verification).

The admin area uses a sidebar, navbar, avatar/account menu, table-based modules, and modal Create/Edit actions. Linked school/user/directorate names open record details. School details include manager name/phone/email as contact information without a manager user account, plus a reserved Students section. Student management is available in the counselor workspace; this admin section remains reserved, and students have no login accounts. See [the admin UX requirements](docs/PROJECT_INSTRUCTIONS.md#administration-ui-and-ux).

MySQL is the application database. This workspace was switched to the new local `masar` database on MySQL 8.4.6 and the migrations were applied. No existing SQLite database was present. On another installation, configure the `DB_*` values from `backend/.env.example`, provision the empty MySQL database with `utf8mb4`, verify the resolved target, then run:

```powershell
node scripts/backend.mjs config:clear --no-interaction
node scripts/backend.mjs migrate --no-interaction
```

Create the main administrator from the `backend` directory using PHP directly:

```powershell
& C:/laragon/bin/php/php8.3/php.exe artisan masar:create-main-admin
```

The command asks for the name, email, password, and password confirmation. Password entry is hidden. Use at least 12 characters with uppercase/lowercase letters and a number. There is no default administrator or password. The command creates only one main administrator and refuses to replace or promote an existing account. A unique database slot prevents concurrent creation of two main administrators. Passwords are hashed; credentials are not printed.

For automation, supply `--name`, `--email`, and `--no-interaction`, with the password in the temporary process environment variable `MASAR_ADMIN_PASSWORD`. Clear it after use; do not put passwords in command arguments, source files, or committed environment files.

The main administrator cannot be deleted, demoted, stripped of protection, or deactivated through the application or ordinary MySQL DELETE/UPDATE statements. MySQL triggers and constraints enforce these protections, including bulk operations. A privileged DBA can still remove tables/triggers or truncate data; the production runtime database account must not have those schema privileges. Run migrations with an appropriately privileged deployment account.

Login uses Laravel's session guard, CSRF protection, session regeneration, generic credential errors, per-IP/account rate limits, and POST-only logout. Backend pages use the root `style-theme.config.json` directly, including light/dark/system appearance and responsive widths. Keep that root configuration available beside `backend/` in deployment; this Blade area requires no frontend build.

## Demo seed data

To give all 13 existing seeded staff accounts one chosen password, run `php artisan masar:reset-demo-passwords` from `backend/` to preview, then add `--apply` and enter/confirm the password privately. It supports local/testing/staging MySQL, excludes every super admin and unrelated account, and refuses production. See [demo password instructions](docs/DEPLOYMENT.md#set-one-password-for-existing-demo-staff). Seeders continue to generate random passwords for new accounts and preserve existing passwords on reruns.

From `C:/laragon/www/masar/backend`, preview the resolved environment, host, database, and missing records:

```powershell
& C:/laragon/bin/php/php8.3/php.exe artisan masar:seed-demo
```

After checking that target and backing up any existing data, insert the missing demo records:

```powershell
& C:/laragon/bin/php/php8.3/php.exe artisan masar:seed-demo --apply
```

The seeder uses the root HTML prototype's 11 school/counselor pairs and supervisor, with their assignments. It adds one directorate and a fictional directorate head, manager contacts, stable demo codes, and reserved `.test` email addresses. Stages/gender follow the prototype names/flags where available; unspecified stages and shifts are demo defaults, not verified official school data. No students or manager user accounts are created.

Create the protected main administrator first. Demo seeding is restricted to `local`/`testing` MySQL environments. It creates 13 staff accounts and never creates or replaces the main administrator. Staff passwords are random and hashed, never printed; these staff types still cannot sign in to the admin area. Reruns insert missing records and preserve existing edits, credentials, and assignments. Conflicts roll back the transaction. The conventional `php artisan db:seed` also calls this seeder and writes immediately; use `masar:seed-demo` for a preview first.

## Backend verification

The backend test suite now requires a separate local MySQL database named `masar_auth_test`. **This database is disposable:** authentication tests check the resolved host/database before resetting its tables. Never put real data in it. `backend/phpunit.xml` pins its host, database, and connection; test credentials can be supplied through the process environment. The normal application uses `masar`.

```powershell
npm run test:api
```

Stage 1 authentication checks and Stage 2 management/localization checks are recorded in [the Stage 2 verification section](docs/STAGE_2_MANAGEMENT.md#local-implementation-and-verification). Phone landscape, real-device keyboard behavior, 200% zoom, printing, a full accessibility audit, backup restoration, production deployment, and load testing remain pending.

This workspace already has a main administrator; Stage 2 preserved its credentials and protection. Do not recreate or replace it. Counseling records, supervisor review, production deployment, and capacity/load testing remain later work. Use HTTPS and secure session cookies in production, and provision shared session/cache storage before running multiple application instances.


Supervisor workspace: active supervisors sign in through the frontend staff login and are routed to `/portal/supervisor`. Schools and Counselors are read-only tabs with search, filters, pagination, and details. Access follows current supervision and school assignments within the same directorate; sharing a school never grants access to an unrelated counselor. School details include a reserved Students tab. Supervisor student access and evaluation workflows are not implemented. Student records are managed separately by counselors. The backend super-admin Users/Edit dialog can set a demo supervisor password when needed; this feature does not reset existing credentials.


Counselor workspace: `/portal/counselor` has separate My account and information (`/profile`) and My supervisor (`/supervisor`) pages. The read-only self-profile API derives identity from the staff session; it cannot select another counselor by ID. It exposes the counselor's own account/directorate and only the current active supervisor's name/email/mobile in the same directorate. An empty state appears when no valid current assignment exists. Counselors cannot use the supervisor/directorate management APIs or backend administration. Demo passwords remain unchanged; the super admin can set them through Users/Edit when needed.


Counselor students: open **Students**, choose an assigned school, and use **Add student**, **Download Excel template**, or **Import Excel**. Required fields are student number, full name, grade and section; optional fields are birth date, gender and guardian contacts. `.xlsx` imports support up to 1,000 students / 2 MB, show a preview before confirmation, and reject invalid rows/duplicates without partial saves or overwrites. Students have no user account or login. Student viewing/creation/import are counselor-only in this increment; other role tabs remain reserved. The additive migration is `2026_10_24_172633_create_students_table`; install Composer dependencies before applying it on another checkout. The local `masar` database has been migrated. Student samples are seeded separately through the opt-in command below; existing records are preserved.


### Fictional student samples

From `backend/`, after the demo schools and counselors exist:

```sh
php artisan masar:seed-demo-students
php artisan masar:seed-demo-students --apply
```

The first command previews without writing. `--apply` adds ten clearly labeled fictional students per active demo school with a current active counselor assignment. It only targets the eleven known prototype demo-school codes under `DEMO-IRBID`, refuses production/non-MySQL environments, and preserves existing students, edited fields, accounts, and assignments. Repeating it inserts only missing sample numbers. Inactive/unassigned schools are reported as skipped. Student samples remain opt-in and are not added by the normal `DatabaseSeeder`.

Local execution on 2026-10-24 created **110 students across 11 schools**. A second run inserted zero duplicates. The counselor `c1@demo.masar.test` can view ten students after selecting their assigned school in **Students**. All sample names/guardian details are explicitly fictional; phone values use a non-dialable `000-TEST-` prefix.

## Counselor interviews

Counselors can open **Student interviews and consultations** from their workspace sidebar (`/portal/counselor/interviews`). Select an assigned school, create a record for an existing student, and view/edit/delete your own records. The table supports student search, month/type/follow-up filters, pagination, and related student links. Arabic/English dialogs retain drafts across language changes and reject stale edits. Saving records the interview directly as Pending review. Current authorized supervisors can view it, add a note, and mark it Reviewed or Approved from their Counselor forms page. Content edits require a new review; the remaining form types are later work. See [the form specification](docs/COUNSELOR_FORMS.md#first-implemented-form--2026-10-24). Run the normal additive migrations before using this module.

## Supervisor form review

Open `/portal/supervisor/interviews` as an assigned supervisor. The table lists currently authorized counselors' interviews with search, month/status filters, and links to counselor/school/form details. Read the form, then use Review form to save an optional note and Reviewed/Approved status. The counselor sees the latest decision and note. Changing answers resets the form to Pending review while retaining the earlier review. Supervisors cannot edit answers or delete interviews. Run the normal migrations to add review status/content versions and the dedicated review history; see [the review rules](docs/COUNSELOR_FORMS.md#supervisor-review--2026-10-24).


## Vocational guidance

Vocational guidance is available to counselors at `/portal/counselor/vocational-guidance` and supervisors at `/portal/supervisor/vocational-guidance`. Record school/class activities with topic/date, optional class/counts/activity notes/evaluation, and the established scoped Reviewed/Approved workflow. Apply the `2026_10_25_064232_create_vocational_guidance_records_table` migration after checking/backing up the target. Demo examples are available through `masar:seed-demo-forms` (see below). See [the form fields and limits](docs/COUNSELOR_FORMS.md#vocational-guidance--2026-10-25).

## Bulletins register

Counselors manage private counseling bulletins at `/portal/counselor/bulletins`; supervisors review them at `/portal/supervisor/bulletins`. Fields are name, date, target audience, optional copy count and objectives. Supports scoped tables/filters, modal create/edit/delete and Reviewed/Approved notes with conflict protection. These records do not publish public news/articles. Apply `2026_10_25_065723_create_counselor_bulletins_table` after verifying/backing up the target. Demo examples are available through `masar:seed-demo-forms` (see below). See [the form contract](docs/COUNSELOR_FORMS.md#bulletins-register--2026-10-25).

## Studies register

Counselors manage private school studies at `/portal/counselor/studies`; supervisors review them at `/portal/supervisor/studies`. Required title/date, optional sample description/purpose/results, scoped paginated tables and modal saves follow the established review/version workflow. Apply `2026_10_25_071703_create_counselor_studies_table` after verifying/backing up the target. Demo examples are available through `masar:seed-demo-forms` (see below). See [fields and access rules](docs/COUNSELOR_FORMS.md#studies-register--2026-10-25).

## Counseling committee register

Counselors manage committee activities at `/portal/counselor/committee-activities`; supervisors review them at `/portal/supervisor/committee-activities`. Fields: activity/date, optional participant/teacher counts and objectives, plus counselor evaluation. Supervisor Reviewed/Approved remains a separate decision. Apply `2026_10_25_073811_create_committee_activities_table` after verifying/backing up the target. Demo examples are available through `masar:seed-demo-forms` (see below). See [the form contract](docs/COUNSELOR_FORMS.md#counseling-committee-register--2026-10-25).

## Home visits register

Counselors manage home visits at `/portal/counselor/home-visits`; supervisors review them at `/portal/supervisor/home-visits`. Select an assigned-school student and visit date, choose visit type/follow-up and enter optional combined visit/action notes. Grade/section come from the student record. Scoped Reviewed/Approved notes, draft/version protection and confirmed soft deletion follow existing registers. Apply `2026_10_25_074331_create_home_visits_table` after verifying/backing up the target. Demo examples are available through `masar:seed-demo-forms` (see below). See [the form contract](docs/COUNSELOR_FORMS.md#home-visits-register--2026-10-25).

## Case studies

Counselors manage 12-section case studies at `/portal/counselor/case-studies`; supervisors review them at `/portal/supervisor/case-studies`. Cases link to an assigned-school student, support partial first saves, autosave on reopened cases, ordered goals/sessions and independent case-progress/review states. Health/family narratives are excluded from summary lists. Apply `2026_10_25_074748_create_case_studies_table` after verifying/backing up the target. Demo examples are available through `masar:seed-demo-forms` (see below). See [the full field/save/review contract](docs/COUNSELOR_FORMS.md#case-study-implementation--2026-10-25).

## Demo data for newer forms

From `backend/`, after completing migrations and seeding management and students:

```sh
php artisan masar:seed-demo-forms
php artisan masar:seed-demo-forms --apply
```

This optional local/testing MySQL command covers parent meetings, vocational guidance, bulletins, studies, committee activities, home visits and case studies. It refuses staging/production. Use `--form=case-studies` (or another form key shown in the preview) to select one register. It is not part of `DatabaseSeeder`; interview examples still use their existing command below.

With all 11 known demo assignments eligible, it creates six examples per school per form: 66 per form, 462 overall, with 22 Pending, 22 Reviewed and 22 Approved per form and 308 review entries overall. Case studies include fictional family/health narratives, goals and sessions: 22 New, 22 In follow-up and 22 Closed cases, with 132 goals and 66 sessions. All narratives are labeled fictional.

Preview shows missing/existing/skipped slots and planned insert statuses. Missing students or invalid assignments are skipped; review examples also require the current canonical demo supervisor. Reruns preserve edits, review history and deleted samples, along with accounts, passwords, students and assignments. Back up valued local data first. See [deployment instructions](docs/DEPLOYMENT.md#8-seeders-local-demo-only).

## Demo interview data

Run from `backend/` after seeding demo schools/staff and students:

```powershell
# Read-only preview: inspect environment, host, database, missing records and statuses.
& C:/laragon/bin/php/php8.3/php.exe artisan masar:seed-demo-interviews

# Insert missing fictional examples after verifying/backing up the target.
& C:/laragon/bin/php/php8.3/php.exe artisan masar:seed-demo-interviews --apply
```

This opt-in seeder is restricted to local/testing MySQL. It adds six fictional interviews per eligible known demo school/counselor pair: two Pending, two Reviewed and two Approved. Examples use existing `DEMO-cN-001` through `006` students, varied interview/referral/follow-up choices, September/October 2026 dates, clearly labeled Arabic sample narratives, and sample supervisor notes. The current demo supervisor must still actively supervise the counselor for Reviewed/Approved samples; otherwise those slots are skipped. Missing students and inactive/unassigned/mismatched schools/counselors are also skipped and counted. Run `masar:seed-demo --apply` and `masar:seed-demo-students --apply` first if prerequisites are absent.

Creation/review uses the normal scoped transactional services. Stable UUIDs identify each of the 66 possible demo slots, so reruns preserve edited answers, review decisions/notes, and soft deletions. They do not modify accounts, passwords, assignments or students, and do not republish deleted samples. `DatabaseSeeder` is unchanged: normal database seeding does not automatically add these interviews. The CLI status counts describe new records to insert, not the current totals.

After the local run on 2026-10-24: **66 active demo interviews / 11 schools / 44 review notes**, with **22 Pending, 22 Reviewed, 22 Approved**. A second apply inserted zero records. The sample counselor sees six records at `/portal/counselor/interviews`; the sample supervisor sees 66 at `/portal/supervisor/interviews`. Select an assigned school in the counselor workspace. All 110 existing students remain unchanged.

## Parent meetings

Counselors can use **Parent meetings / مقابلات أولياء الأمور** in the sidebar (`/portal/counselor/parent-meetings`) to record an existing student's parent meeting: date, meeting type, reason, counseling action and follow-up. Supervisors review these separately under the Parent meetings tab (`/portal/supervisor/parent-meetings`), with the same Reviewed/Approved notes and Pending reset on content edits. School/ownership scope, version conflicts, duplicate-create protection, bilingual dialogs and soft deletion match interviews. Run `php artisan migrate --no-interaction` from `backend/` before use. No demo parent meetings are seeded automatically. See [the form specification](docs/COUNSELOR_FORMS.md#parent-meetings--2026-10-24).


## Directorate-head counselor forms

Heads can view all eight counselor form types in their own directorate at `/portal/directorate/interviews` and the corresponding form pages. Filter lists, open saved answers and read the latest supervisor notes/status. Viewing is read-only, including case sections/goals/sessions; heads retain existing school/staff management. Historical forms remain visible after assignments end, provided both school and counselor still belong to the head's directorate. No new migration or seed command is needed. See [form access rules](docs/COUNSELOR_FORMS.md#directorate-head-viewing--2026-10-25).


## Student form history

Open a student in the counselor workspace to view their interviews, parent meetings, home visits and case studies by type, with review-status filtering and pagination. Create opens the normal form modal with the current student fixed. Students and counselors can have many independent records of the same or different types, including the same date; retrying one save still creates only one record. The four school-level forms remain available in their own registers. No migration or reseeding is required.


## Form attachments

Studies, bulletins, vocational guidance and committee activities support optional private files. Save the form, open its details, and use the drop zone or Choose files, then Upload files. Supported: PDF, DOCX, XLSX, JPG/JPEG and PNG; up to five files per form and 10 MB per file. Authorized supervisors and heads can download files to open/preview them. Only the owning counselor uploads/removes, and either change returns the form to Pending review.

Apply `2026_10_25_120104_create_form_attachments_table` through normal migrations and preserve `backend/storage/app/private/form-attachments` across releases. No new dependency is needed. See [storage, server limits and cleanup](docs/DEPLOYMENT.md#form-attachment-storage) and [the reusable drop-zone instructions](docs/PROJECT_INSTRUCTIONS.md#attachment-uploads-and-downloads).
