# Stage 1 — Project foundation

Date: 2026-10-22.

This is the historical Stage 1 record. Backend authentication and MySQL were added on 2026-10-23; see [the current backend setup](../README.md#backend-administrator) for the delivered scope. Database and authentication limitations below describe Stage 1 at its original completion.

## Goal and delivered scope

Establish an extensible application with a React frontend and Laravel backend API. Pages compose reusable components; domain behavior belongs to feature folders; shared infrastructure stays separate from page content.

The foundation includes:

1. React 19 with TypeScript, Vite, and lazy-loaded React Router pages.
2. Laravel 13 on PHP 8.3+, with versioned API routes and JSON API error rendering.
3. A responsive Arabic RTL application shell, desktop sidebar, accessible mobile navigation drawer, and page structure.
4. Reusable buttons, cards, page headers, empty states, and application error handling.
5. Dashboard, register catalog, case-study placeholder, and not-found page. These establish composition patterns without simulated student records or working CRUD controls.
6. The root `style-theme.config.json`, consumed by the frontend build for CSS variables and media queries. Light/dark/system themes share one root theme state.
7. A shared HTTP client, validated response contract, and a feature component using TanStack Query for connection state, cancellation, and retry.
8. A working `GET /api/v1/health` connection through the frontend development proxy.
9. Dependency lockfiles, environment examples, local startup scripts, and automated foundation checks.
10. Prettier/editor formatting conventions and Laravel Boost development guidelines. Laravel's unused frontend build and welcome-page files were removed so the React app owns frontend rendering.

## Structure

```text
masar/
├── docs/                         Project guidance and stage records
├── style-theme.config.json       Single editable visual configuration
├── package.json                  Root run/build/test commands
├── scripts/                      Backend runner and combined local launcher
├── frontend/
│   ├── scripts/                  Theme validation/generation and its tests
│   ├── src/
│   │   ├── app/                  Root providers and routing
│   │   ├── pages/                Route-level composition
│   │   ├── features/
│   │   │   ├── registers/        Register catalog data and presentation
│   │   │   └── service-status/   API contract and connection component
│   │   ├── shared/
│   │   │   ├── api/              Shared HTTP transport and error type
│   │   │   ├── layout/           Shell, sidebar, navigation
│   │   │   ├── theme/            Theme preference/provider
│   │   │   └── ui/               Reusable presentation primitives
│   │   ├── styles/               Global rules consuming central tokens
│   │   └── test/                 Component-test setup
│   ├── .env.example
│   └── package-lock.json
└── backend/
    ├── app/Http/Controllers/Api/V1/
    ├── routes/api.php            Versioned API route registration
    ├── tests/Feature/            API contract checks
    ├── .env.example
    └── composer.lock
```

## Code organization rules

- `pages` assemble sections and feature components. Avoid putting fetch calls, large forms, and domain rules directly into a page.
- `features/<name>` owns its domain components, hooks, API functions, schemas, and types. Add subfolders when the feature grows; do not create empty layers preemptively.
- `shared/ui` contains generic presentation components. It must not import a domain feature.
- `shared/layout` owns navigation and page framing. Reuse the same sidebar content for desktop and mobile.
- `shared/api` owns HTTP transport. Feature API modules validate their own payloads; components consume those modules through query hooks.
- Keep local interaction state local. Use context for shared app preferences and TanStack Query for server state. Add a global store only when a concrete cross-page requirement needs one.
- Place tests beside the behavior they verify. Add backend feature tests for route contracts and meaningful component tests for asynchronous states.
- Backend controllers live under `Api/V1`. As domain features arrive, use Form Requests for validation, policies for authorization, API Resources for public representations, and focused actions/services for multi-step business rules. Keep ordinary Eloquent operations simple.
- New pages must be registered in `app/router.tsx`; add visible destinations to `shared/layout/navigation.ts` when appropriate.

## One theme configuration

Edit only root `style-theme.config.json` for shared colors, typography, spacing, radii, border widths, layout dimensions, breakpoints, sizing, motion, stacking, and print tokens.

The Vite theme plugin in `frontend/scripts/theme.mjs` validates the configuration, generates the virtual `masar-theme.css` import, and expands `@media (--tablet)` / `@media (--desktop)` to configured widths. CSS references to undefined central tokens fail the build. Configuration edits restart the development server; builds always read the current file. There is no manually maintained generated theme file.

Examples: palette `brand` becomes `--brand`; `layout.sidebar` becomes `--layout-sidebar`; `spacing.lg` becomes `--spacing-lg`. Components must use these values rather than introducing a second palette or spacing scale.

The initial dark primary-button text uses the source's dark-hover ink (`#06201C`) in normal and hover states to improve contrast against the dark palette's lighter green. This is a deliberate application refinement; `DESIGN_REFERENCE.md` preserves the exact original values.

Fonts load from the URL in central configuration; browser fallbacks remain available when Google Fonts cannot be reached. Hosting fonts locally can be added later without changing component typography.

## Local prerequisites

- PHP 8.3+ with Laravel's required extensions, and Composer.
- Node compatible with the installed Vite release. This stage was built using Node `26.5.1` and npm `11.17.0`.
- The local PHP 8.3 executable is `C:/laragon/bin/php/php8.3/php.exe`. The shell's default PHP is 8.2, so the root backend runner automatically selects the installed Laragon PHP 8.3 path on Windows. Set `PHP_BIN` to override it; other environments fall back to `php`.

Current framework references: [Laravel release requirements](https://laravel.com/docs/13.x/releases), [Vite setup](https://vite.dev/guide/), and [React Router installation](https://reactrouter.com/start/declarative/installation). Installed versions are pinned by the two dependency lockfiles.

## Install from this workspace

Run from `C:/laragon/www/masar` in PowerShell:

```powershell
npm --prefix frontend ci
& C:/laragon/bin/php/php8.3/php.exe C:/ProgramData/ComposerSetup/bin/composer.phar install --working-dir=backend
```

Prepare environment files only if they do not exist. Never overwrite an existing `.env` or regenerate an existing application key during routine setup:

```powershell
if (-not (Test-Path -LiteralPath backend/.env)) {
    Copy-Item -LiteralPath backend/.env.example -Destination backend/.env
    node scripts/backend.mjs key:generate
}
if (-not (Test-Path -LiteralPath frontend/.env)) {
    Copy-Item -LiteralPath frontend/.env.example -Destination frontend/.env
}
```

The local backend environment and application key were already prepared during Stage 1. Secrets stay in ignored environment files.

No database creation, migration, reset, or seed was run. The API health route needs no database. The default Laravel migrations are retained for later review, and file-based session/cache plus synchronous queue settings avoid database dependencies during this stage. SQLite is the example connection placeholder; configure and verify the intended database and driver before running any migrations. The selected local PHP does not currently load `pdo_sqlite`.

## Run

From the project root:

```powershell
npm run dev
```

This starts the Laravel server on `127.0.0.1:8000` and Vite on `127.0.0.1:5173`. Stop the launcher with Ctrl+C. To run in separate terminals, use `npm run dev:api` and `npm run dev:frontend`.

The frontend requests `/api/v1/health` on the backend configured through `VITE_BACKEND_URL` in `frontend/.env` (Laravel base URL, without `/api/v1`). Staff authentication, workspace requests and XLSX transfers use the same base. Configure `CORS_ALLOWED_ORIGINS` in the backend for the exact frontend origin. Leaving the URL empty retains relative requests and Vite's optional `API_PROXY_TARGET` proxy. Restart Vite after environment changes and rebuild for production. Do not put secrets in `VITE_*` variables because they are public client configuration.

For local development, the environment example leaves `VITE_BACKEND_URL=` empty and uses `API_PROXY_TARGET=http://127.0.0.1:8000`. Browser requests remain on the current frontend origin, supporting both localhost and 127.0.0.1 without mixing cookie sites. Refresh and sign in again after changing environment/hostname. For production, serve `frontend/dist` with SPA fallback and set the direct HTTPS Laravel base URL before building. Vite's development proxy is not included in the build. Use the exact CORS origins and secure cookie configuration in [the deployment guide](DEPLOYMENT.md).

## API contract

`GET /api/v1/health` returns:

```json
{
  "data": {
    "status": "ok",
    "service": "masar-api",
    "version": "v1"
  }
}
```

This is application liveness only. It does not verify database, queue, email, storage, or production readiness. No authenticated or student-data endpoints are exposed.

## Verification

```powershell
npm run build
npm test
npm --prefix frontend run format:check
```

Completed locally:

| Check                                    | Result                                                                                                                                     |
| ---------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ |
| TypeScript and production frontend build | Passed; lazy page bundles and generated theme CSS emitted                                                                                  |
| Central theme tests                      | 3 passed: configuration validation, token coverage, and propagation of color/breakpoint edits                                              |
| React component tests                    | 4 passed: API success, failure/retry, invalid response handling, and theme preference persistence                                          |
| Laravel tests                            | 5 passed, including 3 health/API contract checks; no database required                                                                     |
| Composer manifest and lock consistency   | Passed                                                                                                                                     |
| PHP formatting                           | Passed for changed PHP files using Pint; explicit file scope used because `--dirty` requires a Git repository                              |
| Frontend formatting                      | Passed                                                                                                                                     |
| Live API and Vite proxy                  | Both returned the expected `/api/v1/health` payload; dashboard displayed connected state                                                   |
| Dashboard widths                         | No page-wide overflow at 320, 375, 640, 768, 1024, and 1440px in light and dark appearance                                                 |
| Register catalog widths                  | No page-wide overflow at the same six widths in both themes                                                                                |
| Mobile navigation                        | Right-side drawer, initial focus, keyboard focus cycling, Escape, focus restoration, scroll locking, and navigation to the catalog checked |
| Page navigation                          | Dashboard, register catalog, and case placeholder checked in the browser                                                                   |
| Browser console                          | No warning/error entries in the final dashboard check                                                                                      |
| Documentation links                      | Local Markdown document links verified                                                                                                     |

Not yet verified: browser zoom at 200%, phone landscape, real-device/on-screen keyboard behavior, print rendering, reduced-motion emulation, and a complete accessibility/contrast audit. Login, data-entry tables/forms, case editing, supervisor review, and report workflows do not exist in Stage 1 and therefore were not tested. Full responsive workflow acceptance in `RESPONSIVE_REQUIREMENTS.md` remains required as those features are implemented.

## Later stages

Authentication and server-enforced roles, database/domain schema, counselor record CRUD, case-study forms, autosave, supervisor review, statistics, and real report printing remain outside Stage 1. The register catalog and case page label those workflows as forthcoming; frontend navigation does not implement authorization.
