# Masar deployment instructions

Last reviewed: **2026-10-25**.

This is the project's maintained deployment guide. Update it in the same change whenever deployment steps, environment settings, dependencies, migrations, seeders, routing, storage, or background services change. Record the change in the release notes at the end. The configuration below is a deployment template; it has not been verified on a production server.

## 1. Deployment layout and URLs

Masar has a React static frontend and a Laravel backend. Keep the root theme file next to the backend: Laravel reads it at runtime, and Vite reads it during builds.

```text
/srv/masar/current/
  style-theme.config.json
  frontend/dist/              # Built static website, including .htaccess
  backend/
    .env                      # Private server configuration
    vendor/
    public/index.php          # Laravel entry point
    storage/                  # Writable, persistent application data
    bootstrap/cache/          # Writable Laravel caches
```

These paths and domains are examples. Substitute the actual deployment path, domains, PHP-FPM socket and service names before running commands.

| URL | Serve with |
| --- | --- |
| `https://masar.example.com/` | React `frontend/dist/index.html` |
| `https://masar.example.com/login` | Frontend staff login |
| `https://masar.example.com/portal/*` | React workspace routes; fallback to frontend `index.html` |
| `https://admin.masar.example.com/api/*` | Laravel public and staff workspace APIs |
| `https://admin.masar.example.com/staff-auth/*` | Laravel staff sessions and CSRF |
| `https://admin.masar.example.com/login` | Laravel super-admin login |
| `https://admin.masar.example.com/admin` | Laravel administration |

Use separate frontend/backend hostnames so the two `/login` pages do not conflict. The frontend calls the backend hostname directly for APIs and staff authentication. Keep session cookies host-only (`SESSION_DOMAIN=null`); the browser sends them to the backend with credentialed requests. Staff and administrator authentication retain separate guards, although both can use the backend's session cookie. Neither the project root nor `backend/` is a public document root.

The current frontend expects deployment at the domain root. Serving it below a path such as `/masar/` needs coordinated router, asset-base and API changes and is not covered by this configuration.

## 2. Requirements

- PHP **8.3** is the tested baseline; use a version supported by the committed Composer lock. Run `composer check-platform-reqs --no-dev` on the deployment PHP runtime.
- PHP extensions required by Laravel plus `pdo_mysql`, `zip` and `xmlreader` for MySQL and XLSX. In particular verify ctype, curl, dom, fileinfo, filter, hash, mbstring, openssl, pcre, PDO, session, tokenizer, xml and libxml. CLI and PHP-FPM/Apache must load compatible extensions.
- Composer 2. Install the locked packages, including OpenSpout; do not run `composer update` during deployment.
- MySQL with InnoDB, strict mode and `utf8mb4`. **MySQL 8.4.6** is the locally verified version. Verify migrations and constraints on the server's actual version.
- Node satisfying the installed Vite engine: **20.19+ in the 20.x line, or 22.12+**. Use the agreed supported build version and `npm ci`. Node is needed for building, not for serving the PHP backend or compiled frontend.
- HTTPS, a web server serving static files and PHP-FPM/Apache PHP, a private MySQL connection, and a backup/restore process.
- A deployment DB account with schema/foreign-key/index/trigger privileges. Main-administrator protections include MySQL triggers and a CHECK constraint. The runtime account should have only the data privileges needed by the application. Coordinate trigger definers and binary-log restrictions with the DBA; do not remove administrator protections to bypass a migration failure.

OpenSpout is already in `backend/composer.lock`. No extra spreadsheet service is required. XLSX imports currently allow 2 MB / 1,000 students. Set the server body limit, PHP `upload_max_filesize`, `post_max_size` (larger than the upload size), timeouts, memory and writable temporary directory to accommodate that bounded workflow. For student imports and form attachments, use for example `upload_max_filesize=12M`, `post_max_size=16M`, and a 16 MB web-server body limit (`client_max_body_size 16m` on Nginx). Application validation still enforces 2 MB for student imports and 10 MB per attachment. Each attachment uses a separate request. Apply settings to the serving PHP SAPI and reload the service; CLI settings alone do not prove HTTP limits.

## 3. Prepare a release before changing live traffic

1. Choose an exact reviewed Git commit/tag and record its ID. Use a clean checkout or isolated release directory. Do not overwrite the live directory with an unreviewed pull or discard local server changes.
2. Configure `frontend/.env` with the backend URL described below, then install dependencies and build the frontend in the release/build workspace:

```sh
# From repository root
npm --prefix frontend ci
npm run build

cd backend
composer install --no-dev --prefer-dist --no-interaction --optimize-autoloader
composer check-platform-reqs --no-dev
```

3. Verify `frontend/dist/index.html`, assets and **`frontend/dist/.htaccess`** exist. Vite automatically copies `frontend/public/.htaccess` on every build. Upload/copy hidden files too. Keep `style-theme.config.json` beside `backend/`.
4. Run code tests in CI/staging with development dependencies and the isolated test database, not on the production runtime. The backend suite resets only its guarded local `127.0.0.1 / masar_auth_test` MySQL database. Do not change that safety check or point PHPUnit at application data.
5. Keep `.env`, the existing `APP_KEY`, storage, database, credentials and backups outside source artifacts. Do not deploy local test reports, upload fixtures, `node_modules`, or demo database dumps as public files.

Before building, create `frontend/.env` from `.env.example` and set the Laravel base URL, without `/api/v1`:

```dotenv
VITE_BACKEND_URL=https://admin.masar.example.com
```

All API, staff-auth, workspace and XLSX requests use this base URL. The value is public and embedded at build time: rebuild and redeploy `dist/` after changing it (restart Vite during development). Replace the old `VITE_API_BASE_URL` setting with `VITE_BACKEND_URL`. Do not put secrets in frontend environment variables. Set the backend's allowed frontend origin as shown below; no frontend API proxy is required. An empty `VITE_BACKEND_URL` optionally retains same-origin routing; `API_PROXY_TARGET` configures only Vite's development proxy.

## 4. First installation

### Local session-expired troubleshooting

For Vite development, leave `VITE_BACKEND_URL=` empty in `frontend/.env` and set `API_PROXY_TARGET=http://127.0.0.1:8000`. Requests to `/api/*` and `/staff-auth/*` then go through Vite on the browser's current origin. This supports both `http://localhost:5173` and `http://127.0.0.1:5173` without cross-site session cookies. These hosts have separate cookies; sign in on the address you use. Restart Vite after environment changes and refresh the page to fetch a current CSRF token.

A direct `127.0.0.1:8000` backend URL combined with a `localhost:5173` frontend is cross-site. The default SameSite=Lax session cookie cannot support that cross-site fetch login; Laravel may return 419 and the UI shows “انتهت الجلسة”. Do not disable CSRF or change local HTTP cookies to SameSite=None to bypass it. Use the local proxy or matching browser/backend hostnames. Production still uses the configured direct HTTPS backend URL and the CORS/cookie settings below; Vite's proxy is development-only.

### Configure private environment

Create `backend/.env` from `backend/.env.example` once, then replace placeholders securely. Do not replace an existing installation's `.env` with the example.

```dotenv
APP_NAME=Masar
APP_ENV=production
APP_DEBUG=false
APP_URL=https://admin.masar.example.com
CORS_ALLOWED_ORIGINS=https://masar.example.com
APP_LOCALE=ar
APP_FALLBACK_LOCALE=en

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=masar
DB_USERNAME=masar_runtime
DB_PASSWORD="REPLACE_SECURELY"

SESSION_DRIVER=file
SESSION_PATH=/
SESSION_DOMAIN=null
SESSION_SECURE_COOKIE=true
SESSION_HTTP_ONLY=true
SESSION_SAME_SITE=lax
CACHE_STORE=file
QUEUE_CONNECTION=sync
LOG_LEVEL=warning
```

Set `APP_URL` to the admin origin for CLI-generated backend URLs. Web requests still use their own host. For the initial single application server, file session/cache drivers match current project setup. If deploying multiple nodes, configure supported shared session/cache storage, a shared `APP_KEY`, and persistent storage before adding nodes; per-node file sessions are insufficient.

`CORS_ALLOWED_ORIGINS` is a comma-separated list of exact frontend origins (scheme, host and optional port, no path or trailing slash). Use trusted origins only, never `*`. Laravel allows credentialed CORS on `/api/*` and `/staff-auth/*`; staff writes still require their session's CSRF token. Allow preflight `OPTIONS` through the web server. After backend environment changes run `php artisan config:clear` locally or rebuild `config:cache` during deployment.

HTTPS subdomains such as `masar.example.com` and `admin.masar.example.com` are cross-origin but same-site; keep `SESSION_SAME_SITE=lax`. If frontend and backend are on different sites (for example `masar.example.com` and `api.other-domain.com`), use **`SESSION_SAME_SITE=none` and `SESSION_SECURE_COOKIE=true`**, with HTTPS on both. Browser third-party-cookie restrictions may still block these cross-site sessions; verify login in target browsers and prefer same-site subdomains for reliable cookie authentication. Do not disable CSRF to solve cookie failures. For local HTTP development, use the same hostname on both sides, e.g. frontend `http://127.0.0.1:5173`, backend `http://127.0.0.1:8000`; do not mix `localhost` with `127.0.0.1`.

A separate reverse proxy/load balancer requires an explicit trusted-proxy configuration and forwarded HTTPS/host validation. The current application does not configure deployment-specific trusted proxies. Test secure cookies and HTTPS redirects rather than trusting arbitrary forwarded headers.

From `backend/`:

```sh
# First installation only: creates APP_KEY in the private .env.
php artisan key:generate --force
php artisan config:clear
```

Never regenerate `APP_KEY` on an existing installation. Preserve it with the environment backup.

### Provision and verify MySQL

Have the DBA create the intended database with `utf8mb4` and provision deployment/runtime accounts. Inspect the resolved driver, host and database without printing the password. If `DB_URL` is set, account for its override of individual `DB_*` settings. A configured name or successful liveness route alone does not verify the connection target.

Using a securely configured MySQL client, verify the actual connection:

```sql
SELECT DATABASE(), VERSION(), @@character_set_database, @@collation_database;
```

Resolve any unexpected target before migrations. Review the pending migration list; an empty new database may not yet have a migrations table.

```sh
php artisan migrate:status --no-interaction
php artisan migrate --force --no-interaction
```

Run migrations under the approved deployment DB account. Restore the least-privilege runtime connection afterward and rebuild configuration caches. Do not leave a separate migration password in shell history or source files.

### Create the protected main administrator once

```sh
php artisan masar:create-main-admin
```

The command asks for name/email and a hidden password plus confirmation. Password requirements are at least 12 characters with uppercase, lowercase and a number (maximum 72 bytes). It refuses to replace an existing main administrator. There is no default production administrator password.

For automation, use `--name`, `--email`, `--no-interaction` and a temporary `MASAR_ADMIN_PASSWORD` process variable supplied through the deployment secret mechanism. Clear it afterward. Never place the password in command arguments or committed files.

After login, create real directorates, schools and staff through administration. Students and school-manager contacts do not have login accounts. Public self-registration remains disabled.

## 5. Web-server routing

Use HTTPS on both hostnames. Serve PHP through a production PHP runtime, not `php artisan serve`. Serve the built frontend, not Vite dev/preview.

### Apache

- Public vhost document root: `/srv/masar/current/frontend/dist`.
- Admin vhost document root: `/srv/masar/current/backend/public`.
- Enable `mod_rewrite`; allow the frontend `.htaccess` directives using `AllowOverride FileInfo Options Indexes` (or a reviewed equivalent server-level configuration). Configure Laravel's public `.htaccess` support too.
- The frontend `.htaccess` handles SPA refreshes and existing assets. It **excludes** `/api` and `/staff-auth` from fallback; it does not route them to Laravel by itself.
- With `VITE_BACKEND_URL` configured, the public vhost serves only the frontend; no API proxy is needed. The backend vhost serves `/api/*` and `/staff-auth/*` through Laravel's front controller, including preflight `OPTIONS`, cookies, CSRF headers, uploads and binary downloads. Do not add conflicting wildcard CORS headers at the web server.
- Keep PHP execution confined to the Laravel public entry point and do not expose application source, `.env`, backups or storage internals.

### Nginx + PHP-FPM reference fragments

These snippets belong **inside the matching HTTPS server blocks** after configuring certificates, server names, logs and the real PHP-FPM socket. They are templates, not an installed server configuration. The direct Nginx→PHP-FPM arrangement avoids an extra HTTP proxy hop.

Public host (`masar.example.com`):

```nginx
root /srv/masar/current/frontend/dist;
index index.html;
client_max_body_size 8m;

location ~ /\. {
    deny all;
}

location / {
    try_files $uri $uri/ /index.html;
}
```

Admin host (`admin.masar.example.com`):

```nginx
root /srv/masar/current/backend/public;
index index.php;
client_max_body_size 8m;

location ~ /\. {
    deny all;
}

location / {
    try_files $uri $uri/ /index.php?$query_string;
}

location = /index.php {
    include fastcgi_params;
    fastcgi_param SCRIPT_FILENAME /srv/masar/current/backend/public/index.php;
    fastcgi_param DOCUMENT_ROOT /srv/masar/current/backend/public;
    fastcgi_pass unix:/run/php/php8.3-fpm.sock;
}

location ~ \.php$ {
    return 404;
}
```

Preserve `REQUEST_URI`, query strings, method/body and HTTPS through the standard FastCGI parameters. Ensure `fastcgi_params` supplies the correct HTTPS state for TLS requests. Validate syntax (`nginx -t` or the platform's Apache config test), then reload only after it passes. Verify routes and cookies with the acceptance checklist below. Nginx does not read `.htaccess`.

Do not add blanket caching to `/api`, `/staff-auth` or admin responses. Session/private responses use no-store. Hashed frontend assets can be cached by the server; HTML should revalidate so clients receive the new build.

## 6. Filesystem and runtime preparation

- PHP must be able to write `backend/storage` and `backend/bootstrap/cache`. Assign ownership/permissions to the actual runtime user/group; do not use world-writable `777` permissions.
- Preserve `storage` across release swaps, especially sessions/logs. Set up log rotation and protect backup access. This increment does not require public `storage:link`; XLSX templates are generated temporarily and downloads remove their temporary files.
- Rebuild caches only after the final environment and dependencies are in place:

```sh
# From backend/
php artisan config:cache
php artisan route:cache
php artisan view:cache
```

- Reload the deployment's PHP-FPM/Apache service as required to pick up release/OPcache changes. Service names depend on the host.
- Current work uses `QUEUE_CONNECTION=sync`; no new worker or scheduler service is required for the implemented forms. Document and provision workers/scheduling before introducing queued or scheduled features.
- Mail currently defaults to logging in the example environment. Do not claim email delivery until a real mail transport and its behavior are configured and verified.

## 7. Updating an existing installation

1. Record the current commit, environment configuration, MySQL version and deployed migration state. Prepare the new release/build as in section 3.
2. Take a protected, consistent database backup and a backup of `.env`/`APP_KEY` and persistent data. Backups must include the MySQL trigger definitions; verify restoration on an isolated database. Record backup location and restore owner without storing secrets here.
3. Review the release's migration list and compatibility with the old application. For an incompatible schema change, use a planned maintenance window and block writes at the web server/load balancer for both hosts and public staff API paths. Laravel maintenance mode alone does not stop the separately served static frontend.
4. Configure the release with the preserved environment/storage. Run `composer install` from the committed lock and verify platform requirements. Clear stale configuration for the new migration environment, verify the actual DB target, then apply only pending migrations:

```sh
# From backend/ in the release being deployed
php artisan config:clear
php artisan migrate:status --no-interaction
php artisan migrate --force --no-interaction
```

5. Restore the runtime DB credentials and build the caches in section 6. Publish/switch the frontend and backend as one compatible release, reload the runtime, and invalidate stale HTML at any CDN.
6. Run the acceptance checks before reopening writes. Remove maintenance routing; if `artisan down` was used as well, run `php artisan up`.
7. Record deployed commit/date, migration results, backup reference, checks and operator in the deployment log. Do not run main-admin creation or demo seeders as part of every update.

Never use `migrate:fresh`, `migrate:refresh`, `db:wipe`, an application-DB PHPUnit run, or a copied demo dump to update a real installation.

### Form attachment storage

Apply `2026_10_25_120104_create_form_attachments_table` through normal migrations after verifying/backing up the target; rebuild frontend and Laravel route/config caches. No new Composer/npm dependency is required. Existing demo form seeders do not create binary attachments.

The dedicated private `form_attachments` disk stores files under `backend/storage/app/private/form-attachments`. Keep this directory writable by PHP, persistent across releases, and inaccessible to the web server's static handlers. Do not run `storage:link` for these files. The authenticated Laravel download route streams files as binary attachments. Preserve session/cookie/CORS support for multipart uploads and binary downloads on the direct backend origin. The frontend uses the filename supplied by authenticated metadata, so no additional exposed CORS header is required.

Back up this private directory together with MySQL; a DB-only backup cannot restore file bytes. When scaling to multiple backend instances, configure this named disk on shared private storage before accepting uploads across nodes. Uploaded and removed files are retained privately; establish a reviewed retention/purge policy separately. The current validation checks content types and Office package structure; it does not provide antivirus scanning.

Recover abandoned pending uploads (never ready/retained files) from `backend/`:

```sh
php artisan masar:prune-pending-attachments
php artisan masar:prune-pending-attachments --apply
```

The first command previews pending rows older than 24 hours. The second rechecks state under a lock, removes their private bytes and metadata, and reports failure if disk removal fails. It processes bounded chunks. Run manually or through an operational daily schedule with the application's environment/DB/storage configuration. No scheduler entry is installed automatically. Do not delete ready files manually.

After deployment, verify a counselor can upload/download/remove a sample file on an authorized study, and that its review status returns to Pending. Verify supervisor/head downloads, denied cross-directorate/other-parent URLs, rejected unsupported/oversized files, and retained storage across a release swap. Confirm serving PHP/web-server limits from section 2. Verify backups can restore both metadata and bytes.

## 8. Seeders: local demo only

Current demo/publication seeders reject production. Do not change `APP_ENV` on a production installation to bypass that protection. There is no mandatory production data seeder in this release, and plain `db:seed` is not a production deployment step.

For a separate local/demo installation with an existing main administrator and completed migrations, preview/apply in this order from `backend/`:

```sh
php artisan masar:seed-demo
php artisan masar:seed-demo --apply
php artisan masar:seed-demo-students
php artisan masar:seed-demo-students --apply
php artisan masar:seed-demo-interviews
php artisan masar:seed-demo-interviews --apply
php artisan masar:seed-demo-forms
php artisan masar:seed-demo-forms --apply
php artisan db:seed --class=PublicationSeeder --no-interaction
```

The four Masar commands preview by default and require `--apply` to write. PublicationSeeder has no preview CLI and inserts missing labeled sample news/articles directly in local/testing. Existing content/edits are preserved. A fresh production landing page may show empty news/articles: no production publication editor/import workflow is provided yet.

Current demo scope: 11 prototype schools/counselors, a supervisor/head, 110 sample students, and 66 sample interviews with 44 reviews when all prerequisites remain eligible. Demo passwords are not part of deployment instructions. The seven newer forms each receive 66 examples and 44 reviews (462 records and 308 reviews in total). Case studies include 132 goals and 66 sessions. Each form has 22 Pending, 22 Reviewed and 22 Approved examples. Existing interviews remain unchanged.

`masar:seed-demo-forms` is opt-in, previews by default, and requires local/testing MySQL. It refuses staging and production; do not change the environment to bypass this guard. Complete migrations and seed management/students first. All seven forms are selected by default; select one with `--form=parent-meetings`, `vocational-guidance`, `bulletins`, `studies`, `committee-activities`, `home-visits` or `case-studies` (add `--apply` to write). Preview shows the actual target, existing/missing/skipped slots and planned statuses. These status counts describe new inserts, not totals already stored.

Examples use known active demo assignments and existing demo students. Reviewed/Approved slots also require the current canonical demo supervisor. Missing prerequisites are skipped and counted, or fail when no eligible assignment remains. Stable UUIDs preserve edits, reviews and soft-deleted samples on rerun. Accounts, passwords, students and assignments remain unchanged. The command reuses normal transactional save/review services and adds audit events. It is not called by `DatabaseSeeder` and adds no dependency or migration. Back up before applying to any valued local database.

### Set one password for existing demo staff

From `backend/`, preview the environment, actual database and eligible accounts:

```sh
php artisan masar:reset-demo-passwords
```

After verifying the target and backing up the existing credentials/database, apply:

```sh
php artisan masar:reset-demo-passwords --apply
```

Enter and confirm the shared password using the hidden prompt. Require at least 12 characters with uppercase/lowercase and a number, at most 72 bytes. The command never prints the password. For automation, pass it in a temporary `MASAR_DEMO_PASSWORD` process variable and use `--apply --no-interaction`; remove that variable afterward. Do not put the password in source, command arguments, deployment logs, or committed environment files.

This command accepts `APP_ENV=local`, `testing`, or `staging` with MySQL, and refuses production. It changes only the 13 known seeded staff accounts under `DEMO-IRBID`, matching their email, employee marker and expected role. All super admins and unrelated users are excluded. Passwords are hashed, remember-me tokens cleared, record versions advanced and credential-reset audit events recorded without password values. This command does not create missing accounts, change assignments, or enable demo **seeding** in staging; the existing seeders still accept only local/testing. It does not revoke existing browser sessions. Regular seeder reruns preserve the chosen passwords.

## 9. Acceptance checks after installation or update

- [ ] Public landing page and built assets load over HTTPS. Refresh a deep URL such as `/portal/counselor/parent-meetings`; it returns the React page, not a server 404.
- [ ] `GET https://admin.masar.example.com/api/v1/health` returns JSON, not frontend HTML. It verifies application liveness only; independently verify database connectivity and migrations.
- [ ] The frontend calls the configured backend URL directly. Preflight and actual responses allow the exact frontend origin and credentials. No wildcard origin is configured.
- [ ] `GET /staff-auth/session` on the backend returns JSON and a CSRF token with the expected secure, HTTP-only, host-only session cookie. It is not cached. Do not save CSRF/session values in the deployment log.
- [ ] Staff sign-in, authenticated reloads, writes, Excel imports/downloads and sign-out work from the frontend with the actual browser cookie settings. Super admins use only the admin login; other user types cannot enter backend administration. No public registration is available.
- [ ] Admin login, school/user lists, modal writes and language/theme controls work. A missing root theme file is a deployment failure.
- [ ] Head school/user management remains scoped to its directorate. Supervisor school/counselor management remains read-only.
- [ ] Counselor student list, manual add, actual XLSX template download and preview/confirm import work under the web runtime's PHP limits and extensions. Use fictional acceptance data.
- [ ] Counselor interview and parent-meeting create/edit/details/filter pages work. Supervisors can review assigned counselors' forms with notes and Reviewed/Approved; changed answers return to Pending review. Inaccessible records cannot be reached by guessing IDs.
- [ ] Vocational guidance works for an assigned school even without students: create/edit/delete, topic/month/status filters, optional class/counts, and supervisor review. Empty counts remain empty and zero beneficiaries remain zero.
- [ ] Bulletins work in both role workspaces, with name/month/audience/status filters and supervisor notes/Reviewed/Approved. Blank copies remain empty and zero copies remain zero. Private bulletins do not appear in public news/articles.
- [ ] Studies work in both role workspaces: required title/date, optional sample/purpose/results, title/month/status filters, counselor CRUD and supervisor notes/Reviewed/Approved. Private studies do not appear in public articles.
- [ ] Counseling committee activities work in both role workspaces: activity/date, optional participant counts/objectives, counselor evaluation and separate supervisor review. Empty counts remain empty; zeros remain zero. Verify activity/month/evaluation/status filters and scoped access.
- [ ] Home visits support assigned-school student selection, derived class display, three visit types, follow-up and a combined visit/action narrative. Verify counselor CRUD/filters, supervisor notes/Reviewed/Approved, and denial of cross-school students or unrelated counselors.
- [ ] Case studies: select a student, save a partial case, reopen and edit all 12 sections. Confirm Saved only after an acknowledged response, queued autosaves, network/validation/conflict draft retention, and goal/session add/remove. Verify progress separately from supervisor review, immutable student identity, date rules, scoped details, and no case narratives in list/public responses. Recheck target browsers/mobile before acceptance; automated tests alone do not prove visual behavior.
- [ ] Arabic/English, RTL/LTR, light/dark/auto and mobile dialogs work; saving does not lose a draft on validation or version conflict.
- [ ] Private API/admin responses remain no-store, production errors hide stack traces (`APP_DEBUG=false`), and logs contain no credentials or counseling/student payloads.
- [ ] `.env`, root/source files, SQL backups and storage internals are inaccessible over HTTP. Confirm backup restoration and monitoring ownership before declaring production ready.

Local automated/browser checks recorded in [Stage 2](STAGE_2_MANAGEMENT.md) are not evidence of production readiness, capacity or a verified server deployment.

## 10. Rollback and recovery

Keep the previous release and its configuration available. If the new application fails and the schema is backward-compatible, switch back to the previous application/frontend together and rebuild its caches/reload the runtime. If schema/data changes are incompatible, keep writes blocked and use the reviewed recovery plan.

Do not blindly run `migrate:rollback`: these migrations can drop student/forms/review tables and lose data. A database restore can also remove writes made since the backup; coordinate that recovery explicitly with the responsible operator and record the affected time range. Restore trigger definitions, `.env`/`APP_KEY` and persistent data as required, then re-run acceptance checks. Reopening traffic is a separate verified step.

## 11. Deployment-impacting change log

Update this table whenever an important change affects installation or updating. Add a dated row with exact commands/settings and any migration, compatibility or recovery notes. Keep detailed feature descriptions in the stage/form documents.

| Date | Change | Deployment action |
| --- | --- | --- |
| 2026-10-25 | Private form attachments | Apply `2026_10_25_120104_create_form_attachments_table`; preserve private attachment storage and rebuild frontend/route/config caches. Set upload/body limits for 10 MB files. Verify role-scoped downloads and review invalidation; use pending-upload cleanup preview/`--apply` as needed. No dependency added. |
| 2026-10-25 | Student form history and repeated records | Deploy the four counselor `student_id` list filters and rebuild frontend. Open a student to view/add multiple interviews, parent meetings, home visits and case studies. No migration, dependency or seeding needed; existing ownership and retry protection remain. |
| 2026-10-25 | Directorate-head form viewing | Deploy read-only form policy/routes and rebuild frontend/route caches. Verify own-directorate lists/details and supervisor notes with a head account; cross-directorate forms and all form writes remain denied. No migration, dependency or seeding required. |
| 2026-10-25 | Local cookie/CSRF hostname mismatch | Local `frontend/.env` now leaves `VITE_BACKEND_URL` empty and uses `API_PROXY_TARGET`, supporting localhost and 127.0.0.1 through Vite. Restart Vite and sign in again after a hostname change. Production still needs its direct HTTPS backend URL. No backend security/session settings changed. |
| 2026-10-25 | 12-section case study and autosave | Apply `2026_10_25_074748_create_case_studies_table` (case, goals, sessions, reviews), rebuild frontend/route caches and verify counselor/supervisor flows. Existing students required. Keep request limits sufficient for bounded long drafts (8 MB example). No dependency or automatic seeding change. |
| 2026-10-25 | Home visits register | Apply `2026_10_25_074331_create_home_visits_table` (records + reviews), rebuild frontend and route caches, and verify both role workspaces. Existing student records are prerequisites. No dependency or automatic seeding change. |
| 2026-10-25 | Counseling committee register | Apply `2026_10_25_073811_create_committee_activities_table` (records + reviews), rebuild frontend and route caches, verify both workspaces. No dependency or automatic seeding change. |
| 2026-10-25 | Studies register and supervisor review | Apply `2026_10_25_071703_create_counselor_studies_table` (records + reviews), rebuild frontend and route caches, and verify both role workspaces. No dependency or automatic seeding change. |
| 2026-10-25 | Bulletins register and supervisor review | Apply `2026_10_25_065723_create_counselor_bulletins_table` (records + reviews), rebuild frontend and route caches, and verify counselor/supervisor flows. No dependency, public publication or automatic seeding change. |
| 2026-10-25 | Vocational guidance register and supervisor review | Apply `2026_10_25_064232_create_vocational_guidance_records_table` (records + reviews), rebuild frontend and route caches, and verify both role workspaces. No dependency or automatic seeding change. |
| 2026-10-25 | Shared demo staff password command | Deploy `masar:reset-demo-passwords`; preview target/accounts, then `--apply` with hidden password entry. Optional local/testing/staging operation only. No migration/dependency changes; super admins excluded. |
| 2026-10-24 | Frontend Apache SPA fallback | Build and upload `frontend/dist/.htaccess`; configure `/api` and `/staff-auth` routing separately. |
| 2026-10-24 | Direct backend URL and credentialed CORS | Set frontend `VITE_BACKEND_URL` and backend `CORS_ALLOWED_ORIGINS`; rebuild frontend and Laravel configuration cache. Configure secure/SameSite cookies for the domain layout. No migration or dependency change. |
| 2026-10-24 | Counselor students and XLSX | Install locked Composer dependencies/OpenSpout and PHP ZIP/XMLReader extensions; apply `2026_10_24_172633_create_students_table`. Verify upload limits and downloads/imports. |
| 2026-10-24 | Student interviews | Apply `2026_10_24_175454_create_counselor_interviews_table`; release frontend/backend together. |
| 2026-10-24 | Supervisor review | Apply `2026_10_24_180922_add_supervisor_review_to_counselor_interviews`; verify review-history storage, versions and supervisor routes. |
| 2026-10-24 | Parent meetings | Apply `2026_10_24_190259_create_parent_meetings_table` (records + review tables); verify both role workspaces. No new dependency or automatic seeding. |
| 2026-10-25 | New form demo data | Optional `masar:seed-demo-forms` preview/`--apply` for all seven newer forms, with optional `--form`; local/testing MySQL only. Seed management/students first; preserve existing edits/deletions and credentials. No migration or dependency added. |
| 2026-10-24 | Demo commands | Optional local/testing-only student/interview seeders; do not run on production or during every update. |

All earlier base/users/management/contact/publication migrations must also run on a fresh installation through the normal `migrate` command. The table highlights recent changes; it does not replace Laravel's migration tracking.

## References

- [Laravel 13 deployment](https://laravel.com/docs/13.x/deployment)
- [Apache URL mapping and aliases](https://httpd.apache.org/docs/2.4/mod/mod_alias.html)
- [Credentialed CORS and browser cookie restrictions](https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/CORS)
- [Cookie Secure and SameSite settings](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Set-Cookie)
- [Backend requirements](BACKEND_INSTRUCTIONS.md)
- [Counselor forms and review rules](COUNSELOR_FORMS.md)
