# CLAUDE.md — Paschim Today Backend (Headless CMS + API)

Read this file fully before every task. It is the source of truth for how this
codebase is built. If a prompt conflicts with this file, follow this file and ask.

## 1. Project

Paschim Today (paschimtoday.com) is a Nepali-first news portal based in Dhangadhi,
Kailali, Sudurpaschim Province, Nepal. It covers all 7 provinces, 77 districts and 753
local levels, with the deepest coverage of the Far West.

This repository is the **only backend**. It is a headless CMS and JSON API. It never
renders public HTML. Its clients are:

- the **Next.js public website** (`/api/v1/public/*`)
- the **Next.js newsroom CMS** for reporters, editors and admins (`/api/v1/cms/*`)
- **Flutter reader and reporter apps** (`/api/v1/app/*`)
- **partners and aggregators** (`/api/v1/partner/*`)
- authentication for all of them (`/api/v1/auth/*`)

Core newsroom flow: many reporters submit raw news with any media from anywhere in
Nepal → the System Admin publishes it as-is, edits and publishes, returns, rejects, or
assigns it to an editor → the editor publishes (only if configuration allows) or sends
it back for admin verification. Every step is recorded: who, when, status, and exactly
what changed. Raw news carries a priority (P0 Flash to P4 Low) that controls queue
order, alerts and deadlines.

The full requirements are in the Paschim Today SRS. Build prompts live in
`docs/prompts/`.

## 2. Stack (already installed — do not add or upgrade packages without asking)

| Area | Choice |
| --- | --- |
| Framework | Laravel 12, PHP 8.2 |
| Database | MySQL 8.4 (InnoDB, utf8mb4 / utf8mb4_unicode_ci, strict mode) |
| Cache, sessions, queues, locks, rate limits, counters | Redis 7 (phpredis) |
| Queues dashboard | Laravel Horizon |
| Debugging | Laravel Telescope (local and staging only) |
| Auth | Laravel Sanctum (SPA cookies for the CMS, bearer tokens for apps) |
| Roles and permissions | spatie/laravel-permission ^6.17 |
| Media | spatie/laravel-medialibrary ^11.14 |
| API documentation | dedoc/scramble (OpenAPI at `/docs/api`) |
| Feature flags | Laravel Pennant (behind our ModuleService) |
| Real time | Laravel Reverb |
| Search | Laravel Scout + OpenSearch |
| Other | spatie/laravel-translatable, spatie/laravel-query-builder, pragmarx/google2fa, mews/purifier, pion/laravel-chunk-upload, php-ffmpeg/php-ffmpeg |
| Quality | Pest, Larastan level 8, Laravel Pint |

PHP compatibility: code must run on **PHP 8.2** and also pass on **PHP 8.4**. Do not
use typed class constants, `#[\Override]`, `json_validate()`, property hooks or
asymmetric visibility. PHP 8.2 security support ends on 31 Dec 2026, so the server
will be upgraded later without code changes.

## 3. Architecture: Service + Repository

Request flow:

```
Route → Middleware (auth:sanctum, module:{key}, throttle, 2fa) → FormRequest (validate)
→ Controller (thin) → Policy / AccessService (authorize) → Service (business logic)
→ Repository (data access) → Model → API Resource (response)
```

### Folder layout

```
app/
  Http/Controllers/Api/V1/{Auth,Cms,Public,App,Partner}/
  Http/Requests/{Domain}/
  Http/Resources/{Domain}/
  Http/Middleware/
  Services/{Domain}/              e.g. Services/Auth/AuthService.php
  Repositories/Contracts/         interfaces, e.g. StoryRepositoryInterface.php
  Repositories/Eloquent/          implementations
  Repositories/Cached/            Redis decorators for read-heavy repositories
  DTOs/{Domain}/                  final readonly classes (PHP 8.2)
  Models/
  Policies/
  Enums/
  Events/  Listeners/  Jobs/  Notifications/
  Support/                        Cache, BsCalendar, NepaliDigits, Transliteration, ApiResponse
  Providers/RepositoryServiceProvider.php
```

### Rules

- **Controllers are thin**: receive a FormRequest, authorize, call one service method,
  return a Resource. No Eloquent queries, no business rules in controllers.
- **Services hold all business logic.** Inject dependencies through the constructor.
  Services may call other services and repositories. Wrap multi-step writes in
  `DB::transaction()`.
- **Use a Repository** when a model has non-trivial queries, filters, caching, or is
  used by many services: User, Role/Access, Story, Revision, WorkflowConfig, Queue,
  MediaAsset, Category, Location, AuditEvent, Analytics. Simple lookup tables (e.g.
  content types, priority levels) may be read directly through the model inside a
  service.
- Repositories implement an interface in `Repositories/Contracts` and are bound in
  `RepositoryServiceProvider`. Read-heavy repositories get a `Cached*Repository`
  decorator that uses `CacheService` with Redis tags and is invalidated by events.
- **DTOs** carry data from FormRequests into services (`StoryData::fromRequest()`).
  Services never receive raw `Request` objects.
- **Side effects** (notifications, search indexing, cache purge, stats, social posts,
  media processing) run in queued listeners or jobs on the correct Horizon queue.
  Never do slow work inside a request.
- **Enums** for statuses, types and priorities (backed string enums).
- **Module on/off**: every non-core feature belongs to a module key. Its route group
  uses `module:{key}` middleware, and its jobs and listeners check
  `ModuleService::isEnabled()`. A disabled module exposes nothing.
- **Audit**: every state change on content, users, roles, permissions, scopes,
  settings, modules, workflow config and media goes through `AuditService`. The
  `audit_events` table is append-only (DB triggers block UPDATE and DELETE).

## 4. API contract

- Versioned under `/api/v1`.
- Success: `{"data": ..., "meta": {...}, "links": {...}}`
- Error: `{"error": {"code": "snake_case_code", "message": "...", "details": {...},
  "request_id": "..."}}` with the correct HTTP status. Standard codes:
  `validation_failed` 422, `unauthenticated` 401, `forbidden` 403, `not_found` 404,
  `module_disabled` 404, `too_many_requests` 429, `server_error` 500 (no stack traces
  in production).
- Messages translated in `lang/ne` and `lang/en`; locale from `Accept-Language` or
  `?lang=`; default `ne`.
- Public identifiers are ULID `uid` columns. Never expose auto-increment IDs.
- Cursor pagination for feeds and large lists; page pagination for CMS tables.
- Filtering and sorting through spatie/laravel-query-builder with explicit whitelists.
- Translatable text is JSON `{ "ne": "...", "en": "..." }`; `ne` is default and fallback.
- Store times in UTC (`DATETIME`). Responses give ISO 8601 in `Asia/Kathmandu` plus a
  `bs` object `{year, month, day, formatted_ne}` from `BsCalendar`.
- Public GET endpoints send ETag and Cache-Control headers.

## 5. Security (always)

- Every `/api/v1/cms/*` route has permission middleware or a policy check. A test
  fails the build if one does not.
- Authorization = permission (role permissions + direct allows − direct denies) **and**
  scope (category, province, district, local level, desk, content type).
- Validate every input with a FormRequest. Purify rich text with the HTMLPurifier
  allow-list. Embeds only from allow-listed hosts.
- Rate-limit every route group (Redis). Lock accounts after 5 failed logins for 15 min.
- 2FA is required for system-admin, desk-head and editor. Super-admin uses
  password + email OTP when `SUPER_ADMIN_OTP_ENABLED=true` (default); setting it
  to `false` exempts only super-admin from login/enrollment and recent-verification
  requirements, including dangerous CMS/workflow actions. Other roles still follow
  `TWO_FACTOR_METHOD` and role metadata. Dangerous permissions otherwise need 2FA
  confirmed in the last 15 minutes.
- Never log passwords, tokens, OTPs, phone numbers or emails (masked by a log processor).
- Secrets only from `.env` or the secret manager. Never commit `.env`.
- Uploaded files: check real MIME type, size limits, ClamAV scan, random file names,
  originals on a private disk served only by temporary signed URLs.
- Eloquent / query builder bindings only; no raw string SQL with user input. Use
  `$fillable` on every model.

## 6. Redis, queues, Horizon and Telescope

- Redis DBs: 0 default, 1 cache, 2 sessions, 3 queues, 4 locks + rate limits, 5
  counters. Key prefix `pt:{env}:`. Key patterns documented in `docs/redis.md`.
- Use `CacheService` (never raw `Cache::` in services): tagged keys, `Cache::flexible`
  for hot public data, `invalidate(tags)` on events.
- Locks: story edit lock `lock:story:{id}:edit` (5 min + heartbeat), workflow transition
  lock `lock:wf:{story_id}`.
- Horizon queues: `critical` (P0/P1 alerts only), `high`, `default`, `media`,
  `notifications`, `search`, `analytics`, `ai`, `migration`, `low`. Choose the queue
  explicitly on every job.
- Horizon dashboard: `system.horizon` permission. Telescope: local and staging only,
  `system.telescope` permission, sensitive fields hidden, pruned daily.
  `LOCAL_DASHBOARDS_PUBLIC=true` explicitly allows login-free access to both
  dashboards only when `APP_ENV=local`; all other environments keep permission checks.

## 7. Media (Spatie Media Library ^11.14)

- Default storage is the server's own disk: `media_public` (conversions, served by
  nginx via `storage:link`) and `media_private` (originals, EXIF, source documents).
- S3-compatible external storage (AWS S3, Cloudflare R2, DigitalOcean Spaces, Wasabi,
  Backblaze B2, MinIO) is enabled only through env: `MEDIA_DISK`,
  `MEDIA_CONVERSIONS_DISK`, `MEDIA_PRIVATE_DISK`, `MEDIA_S3_*`, `MEDIA_URL_BASE`.
  Never hard-code a disk name in services.
- `MediaAsset` is the central reusable library item (one Spatie media item in
  collection `file`). Stories reference MediaAsset, so one photo can be used in many
  stories.
- Conversions are queued on `media`; public conversions have EXIF/GPS stripped.

## 8. Database conventions

- Table names plural snake_case; foreign keys `{model}_id` with indexes; `uid` ULID
  unique on public models; soft deletes on content tables.
- Add indexes for every filter and sort column. Check `EXPLAIN` for queries over 50 ms.
- Large tables (`audit_events`, `analytics_events`) are RANGE-partitioned by date, with
  the partition column in the primary key and no foreign keys.
- Seeders are idempotent (upsert by natural key) and recorded in `seed_versions`.
  Demo seeders refuse to run in production.

## 9. Testing and done criteria

Every task is done only when:

- migrations, models, factories, seeders, repositories, services, policies, requests,
  resources and routes exist;
- Pest feature tests cover success, 401, 403 (including wrong scope) and 422 cases;
- no N+1 queries (`Model::preventLazyLoading()` outside production + query-count
  assertions);
- Larastan level 8 and Pint pass;
- the endpoints appear correctly in Scramble (`/docs/api`) with request and response
  examples, and `php artisan scramble:export` updates `docs/openapi.json`;
- `docs/<area>.md` is updated (endpoints, permissions, events, settings, seeders).

## 10. Working style

- Work one prompt step at a time and commit after each step:
  `P{n}{step}: short description` (e.g. `P1B: reader registration`).
- If something is unclear or needs client data (registration numbers, stream URL,
  data sources), stop and ask. Use `__CONFIRM_WITH_CLIENT__` placeholders in seeders.
- Prefer small, readable classes. Name things in English; user-facing text in ne + en.
- Never delete or rewrite audit data, migrations already run in shared environments,
  or seed data created by other users.
