# Smart Clinic Laravel Backend

API-first Laravel backend implementing the Smart Clinic specification: multi-role authentication, multi-location doctor schedules, assistant permissions, patients, appointments, editable/automatic tokens, live queue, transaction-backed billing, notifications, audit logs, reports and production deployment structure.

## Stack

- PHP 8.3+
- Laravel 13.x
- Laravel Sanctum bearer tokens
- MySQL 8.0+ / MariaDB 10.6+
- Redis recommended for cache, locks and queues (database drivers are supported for smaller deployments)
- Timezone: Asia/Karachi; appointment timestamps are stored as UTC
- REST prefix: `/api/v1`

## Quick start

```bash
composer install
cp .env.example .env
php artisan key:generate
# Configure DB_* in .env
php artisan migrate
php artisan db:seed
php artisan serve
```

For local/demo data, keep `APP_ENV=local` and run `php artisan db:seed`. The demo seeder creates an admin, two doctors, two assistants, multiple locations, schedules, patients and the queue regression fixture with tokens 04/05/06. Demo password is `password` and is never seeded automatically in production.

For production, use the safe bootstrap path:

```bash
php artisan migrate --force
php artisan db:seed --class=EssentialSeeder --force
php artisan clinic:create-admin admin@example.com "Clinic Admin" --organization=smart-clinic
```

## Authentication

Send `Authorization: Bearer <token>` for protected routes. Staff login uses email/password. The login response contains a Sanctum token and bootstrap context (user, role, organization, permissions, assignments and settings). Current-token and all-device logout are supported. Staff password reset and signed email verification endpoints are included.

## Core route groups

- `/api/v1/auth/*` – login, logout, logout-all, reset password, email verification
- `/api/v1/me`, `/api/v1/bootstrap`, `/api/v1/dashboard`
- `/api/v1/locations`, `/api/v1/doctors`, doctor locations and server-calculated availability
- `/api/v1/patients/*` – search, create, detail, edit, archive and appointment history
- `/api/v1/appointments/*` – booking, update, atomic reschedule, cancel and workflow status
- `/api/v1/queue/*` – active queue, check-in, automatic token, editable token, status and call-next
- `/api/v1/transactions`, appointment payments/waivers and refunds
- `/api/v1/notifications`, preferences and `/devices`
- `/api/v1/admin/*` – users/roles, doctors, assistants, locations, assignments, schedules, settings, audit logs, operational metrics and full reports

See `docs/openapi.yaml` and `routes/api.php` for the complete route contract.

## Important domain guarantees

### Appointment booking

Appointment slots are derived on the server from doctor-location working hours, exceptions and existing active appointments. Booking/rescheduling locks the doctor-location assignment inside a DB transaction before checking overlap, which serializes competing bookings for that practice context. Fees are taken from the doctor-location assignment rather than trusted from the client.

### Token and queue

Token allocation and token serving are separate. Queue tokens are unique by organization + configurable queue scope + queue date + token. Allocation/edit happens transactionally with a locked queue counter. Manual collisions return `TOKEN_ALREADY_IN_USE` with HTTP 409. `call-next` selects the smallest eligible waiting token greater than the current served token; the seeded regression verifies 04 -> 05 rather than skipping to 06.

### Billing

`transactions` is the financial source of truth. Payments are idempotent using a client `idempotency_key` or provider reference, partial payments are supported, waivers require a reason, refunds are separate negative transactions referencing the original payment, and appointment payment status is recalculated from the ledger. Payment methods are organization-configurable.

### Authorization

Record access is always scoped by organization and role. Assistant operations additionally require an active doctor/location assignment and the relevant permission flag (`can_create_patient`, `can_book_appointment`, `can_check_in`, `can_reschedule`, `can_cancel`, `can_edit_patient`, `can_collect_payment`).

## Queue worker and scheduler

```bash
php artisan queue:work --tries=4 --timeout=120
php artisan schedule:run
```

Production should run the queue worker continuously with Supervisor/systemd (or hosting equivalent) and invoke `php artisan schedule:run` every minute. Appointment reminders are discovered every five minutes and dispatched idempotently.

## Testing and quality

```bash
php artisan test
vendor/bin/pint --test
vendor/bin/phpstan analyse --memory-limit=1G
php artisan clinic:check-openapi
```

The default suite uses SQLite in-memory and covers authentication, role/patient isolation, patient/WhatsApp rules, appointment conflicts, payment lifecycle/idempotency, notification idempotency/retry behavior, admin/report endpoints, token collisions and the 04 -> 05 -> 06 regression. True row-lock races run separately against MySQL:

```bash
vendor/bin/phpunit -c phpunit.mysql.xml
```

See `docs/TESTING.md`; `.github/workflows/ci.yml` runs the release quality gates.

## Documentation

- `docs/openapi.yaml` – OpenAPI 3 contract
- `docs/ERD.md` – database/entity map
- `docs/DEPLOYMENT.md` – production deployment and rollback
- `docs/PROVIDERS.md` – Expo/FCM/APNs/WhatsApp/email setup
- `docs/TESTING.md` – feature, static-analysis and MySQL concurrency gates
- `docs/BACKUP_RESTORE.md` – backup/restore procedure
- `docs/DATA_RETENTION_PRIVACY.md` – production privacy/retention decisions
- `docs/MOBILE_INTEGRATION.md` – Expo API replacement map
- `docs/ERROR_CODES.md` – domain error reference
- `docs/IMPLEMENTATION_MATRIX.md` – specification-to-code mapping

## Production warning

Do not use demo credentials or `APP_DEBUG=true` in production. Configure HTTPS, backups, queue worker, scheduler, provider secrets and monitoring before handling real patient data. Provider and data-retention requirements must be reviewed for the jurisdiction where the clinic operates.
