# CosmosMobile Backend

Laravel 10 API powering the COSMOS Technician tablet app (Flutter, `../flutter`).

## ⚠️ Shared database — read before running migrations

This app connects to the **same MySQL database** (`cosmos2`) as
`C:\Users\silva\Projects\Cosmos2\backend` — the existing desktop/admin API.
It is a **separate Laravel installation**, not an extension of that codebase
(a deliberate architecture decision — see `PLAN.md` if present, or the
project's plan history, for the trade-offs).

**Rules:**

- **Never run `migrate:fresh`, `migrate:reset`, or `db:wipe`** — they would drop
  tables Cosmos2/backend owns and depends on (delegations, users, clients,
  jobs, work_sheets, service_line_items, equipment_types,
  technician_certifications, complaints, invoices, communication_messages,
  job_technicians, csat_ratings, audit_events, quotations, vehicles, etc.).
- This app's own `database/migrations/` only ever **create new tables it
  owns** (`push_devices`, `notification_preferences`,
  `checklist_item_templates`, `job_checklist_items`, `queue_jobs`) or **add
  columns** to existing shared tables (`work_sheets.technician_signature`,
  `jobs.overdue_notified_at`). Never add a migration that creates a table
  that already exists in Cosmos2/backend's migration set.
- Models in `app/Models/` for shared tables (`Job`, `Client`, `User`,
  `WorkSheet`, `ServiceLineItem`, etc.) are **partial mirrors** of the real
  models in Cosmos2/backend — same table, same enum value strings, but only
  the relations/fields this app needs. If Cosmos2/backend's schema or enums
  change, these must be updated to match by hand (there is no shared package
  yet — see the drift-risk note below).
- Enums in `app/Enums/`, `app/Models/Scopes/DelegationScope.php`, and
  `app/Models/Concerns/BelongsToDelegation.php` are **verbatim copies** from
  Cosmos2/backend. Any change to the real versions must be mirrored here.
- `app/Services/JobTransitionService.php` is a **partial mirror** of
  Cosmos2/backend's `JobStateMachineService` — only the 3 edges a technician
  can trigger (`scheduled→in_progress`, `in_progress→awaiting_documentation`,
  and a system-only `awaiting_documentation→ready_for_billing` auto-approval
  edge unique to the tablet completion flow). See the class docblock.

**Recommended follow-up** (not yet done): extract the enums, `DelegationScope`,
and the mirrored state-machine edges into a shared local Composer package
that both Cosmos2/backend and CosmosMobile/backend require, to eliminate the
hand-copied duplication above. Needs sign-off since it touches Cosmos2/backend too.

## Local setup

```
composer install
cp .env.example .env   # then set DB_DATABASE=cosmos2, DB_USERNAME=root, DB_PASSWORD= (matches Cosmos2/backend's local .env)
php artisan key:generate
php artisan migrate            # only runs THIS app's own migrations (see above)
php artisan db:seed            # checklist item templates + demo jobs for one technician
php artisan serve --port=8001  # Cosmos2/backend typically runs on 8000
```

Queue worker (for push notifications / PDF generation):

```
php artisan queue:work
```

Scheduler (day-before/morning-of/overdue/job-assigned-poll notifications —
see `app/Console/Kernel.php`):

```
php artisan schedule:work
```

## What replaces the missing admin UI

Per the build plan, there is no admin panel in this app. Job creation, Folha
de Obra generation, technician assignment, etc. all happen on the desktop
side (Cosmos2/backend + its own frontend). For local development, use:

- `php artisan db:seed --class="Database\Seeders\DemoTechnicianJobsSeeder"` —
  creates one job per key status/edge-case variant for a technician, so every
  Flutter screen state (overdue, scheduled, in_progress, awaiting
  documentation, on_hold, no-Folha-generated, upcoming) has real data to
  render against.
- `php artisan tinker` for anything more specific.

## Push notifications

`app/Services/PushNotificationService.php` uses the legacy FCM HTTP API
(server-key auth). Set `FCM_SERVER_KEY` in `.env` to actually deliver;
without it, sends are logged to `storage/logs/laravel.log` instead
(`[push:log-only]`) so the rest of the pipeline can be developed without a
configured Firebase project.

## The atomic on-site completion endpoint

`POST /api/v1/jobs/{job}/tablet-completion` — see
`app/Http/Controllers/Api/TabletCompletionController.php`. This is the single
most novel piece of business logic in this app: it replaces, for jobs
completed via the tablet, both of Cosmos2/backend's existing completion paths
(technician WorkSheet upload + PM review, and the separate public
email-link client CSAT/signature flow) with one atomic submission that
captures amendments, checklist, satisfaction score, and both signatures, then
auto-approves the WorkSheet and transitions the job straight to
`ready_for_billing` — bypassing the normal Admin/PM manual review step
(a deliberate product decision, not an oversight).
