# CLAUDE.md

This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.

## Project

Laravel 13 / PHP 8.3+ API base (`msaber/laravel-base`) — a Clean Architecture foundation serving both an admin dashboard and mobile/web clients, with RBAC, smart caching, feature flags, audit trail, and geo context built in. Local packages `msaber/media`, `msaber/notification`, `msaber/verification` live under `modules/` and are wired via `composer.json` path repositories.

**Source of truth for conventions**: `.kiro/steering/*.md` (`architecture.md`, `code-standards.md`, `crud-conventions.md`, `base-project-style.md`) — all marked `inclusion: always`. `docs/ARCHITECTURE.md` describes a broader/aspirational design (e.g. `ApiResponse` builder, full CQRS Command/Query split) that does not match most of the current code — prefer `.kiro/steering` and the actual code when they disagree. In particular:
- Use the global `json($data, $message, $status, $headerStatus)` helper (`app/Helpers/helpers.php`) for all responses. Do **not** use `ApiResponse::` — it exists but is essentially unused (one call site) and contradicts the mandatory convention in `.kiro/steering/architecture.md`.
- Most CRUD services extend `BaseCRUDService` directly (`app/Services/Admin/{Entity}Service.php`). The `Admin/Commands` and `Admin/Queries` / `Client/Commands` and `Client/Queries` split described in `docs/ARCHITECTURE.md` only exists for a few entities (Notification, Profile, Address, Wallet, General) — it is not the default pattern for new CRUD.

## Commands

```bash
composer install
cp .env.example .env && php artisan key:generate
php artisan migrate
php artisan serve                 # or: composer dev (server + queue:listen + pail + vite, concurrently)

vendor/bin/pint app config database modules routes tests   # format (composer style)
vendor/bin/pint --test ...                                  # check formatting only (composer style:check)

php artisan test                                # full suite
php artisan test --filter=TestName              # single test
php artisan test tests/Feature/SomeTest.php      # single file
vendor/bin/phpunit                              # equivalent direct invocation

php artisan postman:generate                    # regenerate docs/postman-collection.json
php artisan postman:markdown                    # regenerate docs/api/{admin,user,trainer,README}.md from the collection
php artisan postman:frontend-guide              # regenerate the "BRD ↔ API Cycle Mapping" block in docs/api/README.md
```

Run all three, in that order, after any route or FormRequest change — each keeps the next one's input fresh. `postman:frontend-guide` derives its endpoint/field/enum data live from the collection but keeps business-flow ordering (cycle grouping, "when triggered", BRD references) in `app/Console/Commands/Support/FrontendGuideCycles.php`, since that can't be inferred from routes. Both `postman:markdown` and `postman:frontend-guide` splice their output into `docs/api/README.md` between HTML comment markers, so hand-maintained content (the "Coverage Gaps vs BRD" section) survives regeneration.

Tests run against in-memory SQLite (`phpunit.xml`), array cache/session, sync queue — no external services needed.

### Scaffolding a new CRUD entity

```bash
php artisan make:crud Product --context=Admin      # Controller + Request + Service (config-only controller)
php artisan make:query OrderQueryService --context=Admin
php artisan make:command-service OrderCommandService --context=Admin
php artisan make:action Checkout/ApplyCouponAction
php artisan make:value-object Checkout/CartTotal
php artisan make:enum
```
After `make:crud`: register the route, fill in `with`/`load` relations on the controller, add validation rules to the generated Request, and drop `SyncsTranslations` if the model isn't translatable.

### Seeders (dependency order matters)

```bash
php artisan db:seed   # runs all seeders in order; or target one with --class=CountrySeeder etc.
```
Order: Country → Governorate → ShippingZone → Region → Permission → Role → User → Category → FAQ → StaticPage → Slider → AppConfig → FeatureFlag.

## Architecture

### Request flow (mandatory shape — see `.kiro/steering/crud-conventions.md`)

```
Middleware (auth:api, active, rbac.auto, geo.context, locale)
  → Form Request (extends ApiMasterRequest, validates — 422 on failure)
  → Controller (AdminBaseController subclass, config-only, zero methods)
  → Service (extends BaseCRUDService, or a custom service for non-CRUD logic)
      → Save pipeline: BeforeSave → FillModel → SaveModel → SyncRelations → HandleMedia → AfterSave
        (async/side-effect pipes: AuditChange → InvalidateCache → DispatchEvents)
      → Delete pipeline: BeforeDelete → DetachRelations → CleanupMedia → DeleteModel → AfterDelete
      → Index pipeline: ApplyScopes → ApplyFilters → ApplySearch → ApplySorting → ApplyPagination
  → json() response — {status, message, data}
```

Controllers **must not** contain validation, direct model writes, business `if/else`, `try/catch`, or `Hash::make`/`auth()` calls — all of that belongs in the Form Request or Service. A controller is a `$requirements` config array passed to `AdminBaseController::__construct()` (see `app/Core/Controller/AdminBaseController.php`): `service`, `model`, `with`/`load` (eager-load relations for index/show), `storeRequest`/`updateRequest`, `indexResource`/`showResource`, optional `permissions` map.

### Per-entity file layout

```
app/Http/Controllers/Api/V1/Admin/{Entity}Controller.php     # config-only, extends AdminBaseController
app/Http/Requests/Admin/{Entity}/{Entity}Request.php         # one request for store+update (rule switches on route-model presence)
app/Services/Admin/{Entity}Service.php                       # extends BaseCRUDService, + SyncsTranslations if translatable
app/Http/Resources/Admin/{Entity}/{Entity}Resource.php        # index (lean)
app/Http/Resources/Admin/{Entity}/{Entity}DetailsResource.php # show (rich, extends the list resource)
```
Client-side mirrors this under `Http/Controllers/Api/V1/Client`, `Http/Requests/Client`, `Services/Client`, with leaner resources.

Services override hooks only where behavior deviates from default CRUD: `beforeSave()`, `syncRelations()`, `afterSave()`, `handleMedia()`. Resources are presentation-only (never query the DB), use `whenLoaded()` for relations, and never serialize passwords/tokens/secrets.

### Core building blocks (`app/Core/`)

- `Controller/AdminBaseController.php` — config-driven index/show/store/update/destroy.
- `Service/BaseCRUDService.php`, `BaseQueryService.php`, `BaseCommandService.php` — CRUD + pipeline orchestration; `BaseQueryService`/`BaseCommandService` back the handful of CQRS-split services under `Services/{Admin,Client}/{Commands,Queries}`.
- `Pipeline/Save|Delete|Index/*` — the composable pipes listed above. Override `getSavePipes()`/`getDeletePipes()`/`getIndexPipes()` in a service to add/remove/reorder steps.
- `Repository/BaseRepository.php` — chainable Eloquent query builder (`with()`, `filter()`, `search()`, `filterByDate()`, `sortBy()`, `paginate()` clamped 1–100); resets scope after every terminal call.
- `Traits/HasUuid.php` — gives a model a `uuid` public identifier used for route binding (`show`/`update`/`destroy`) and Resource output, while `id` stays the internal PK/FK. Mandatory for every CRUD entity — see `.kiro/steering/crud-conventions.md`.
- `Exceptions/` — `EntityNotFoundException` (404), `BusinessRuleViolation`/`ValidationFailedException` (422), `InfrastructureException` (503); each carries an `ErrorCode` string.
- `Response/ApiResponse.php` — legacy/unused, do not use (see above).

### Domain layer (`app/Domain/Shared/`)

`Actions/BaseAction` (enforce business `Rules` → execute → dispatch domain `Events`), `ValueObjects/BaseValueObject` (immutable, `equals()`/`toArray()`), `Rules/` + `RuleChain` (evaluates all rules, surfaces every violation at once, not just the first).

### Infrastructure (`app/Infrastructure/`)

- **RBAC** (`Auth/`) — `RbacAutoCheck` middleware strips the `admin.` prefix from the route name (e.g. `admin.orders.update` → `orders.update`) and checks it against the user's permissions (direct or `resource.*`); roles form a parent/child hierarchy with inherited permissions; resolved permissions cached 1h, invalidated globally on role/permission change.
- **Smart caching** (`Cache/`) — `SmartCacheInterface::remember($key, $tables, $callback, $ttl)` keys entries by a hash of per-table version counters; any save through the pipeline bumps the relevant table's counter via `InvalidateCache`, so cache reads never go stale and nothing calls `Cache::forget()` manually.
- **Feature flags** (`FeatureFlags/`) — `feature('flag_key')` helper, zero-DB read (cached), supports country/version/percentage targeting rules; admin CRUD + toggle at `/api/v1/admin/feature-flags`.
- **Geo** (`Geo/`) — `GeoContextMiddleware` resolves country/currency/coordinates once per request via header → user profile → IP → config-default chain; access via `GeoContext::current()`. Hierarchy is Country → Governorate → Region → Shipping Zone. Spatial queries via `HasCoordinates` trait (`nearby()`, `orderByDistance()`).
- **EventBus** (`EventBus/`) — Redis pub/sub, whitelisted event types, per-user rate limiting, channel routing.
- **Resilience** (`Resilience/`) — `IdempotencyMiddleware` (client writes, `Idempotency-Key` header, 24h TTL, 409 on concurrent duplicate) and `CircuitBreaker` (closed → open after 5 failures → half-open probe after 30s).
- **Payments** (`Payments/`) — `IntegrationRegistryInterface::resolve($method, ['country' => ..., 'platform' => ...])` returns a swappable gateway; integrations stored in DB with encrypted credentials and priority ordering.
- **Audit** (`Audit/`) — automatic via the `AuditChange` save pipe; sensitive fields excluded per `config/audit.php`; prune via `php artisan audit:prune`.

Everything above is accessed through an interface in `app/Contracts/`, so implementations can be swapped in a service provider (`$this->app->singleton(SmartCacheInterface::class, MyImpl::class)`) without touching call sites.

### Routing

```
routes/api/v1/admin.php    # auth:api + active + rbac.auto
routes/api/v1/client.php   # auth:api + active
routes/api/v1/guest.php    # no auth
routes/api/v1/shared.php   # cross-role (notifications, health, bootstrap)
```
V2 would live in a new `routes/api/v2/` registered in `bootstrap/app.php`, leaving v1 untouched.

### Translations

Translatable models use `astrotomic/laravel-translatable` plus the `SyncsTranslations` service trait. Requests use **flat locale keys**, not `translations.{locale}`:
```json
{"is_active": true, "en": {"name": "..."}, "ar": {"name": "..."}}
```
Index responses expose only the current-locale fields; show/detail responses add all-locale blocks for admin editing.

### Pagination / filtering (index endpoints)

Always paginated by default (`?paginate=false` to disable); `?per_page=` (max 100), `?sort[field]=asc|desc`, `?search=term`, `?filters[field]=value`.

### Code style conventions (`.kiro/steering/code-standards.md`)

- `declare(strict_types=1);` in every file; alphabetized, role-grouped imports.
- Class-level PHPDoc with summary + `@package` (architectural layer) + `@see`; public/protected methods documented with `@param`/`@return`/`@throws`.
- `# ── Section ──` comment separators grouping: Constants → Properties → Constructor → Public API → Protected/hooks → Internal — and methods are physically ordered the same way.
- Inline `#` comments explain WHY, not WHAT.
- Naming: `*Interface` for contracts, `Base*` for abstract classes, verb+noun for Actions (`ApplyCouponAction`), past-tense for Events (`OrderPlaced`), `*Exception` for exceptions, `{Entity}Resource`/`{Entity}DetailsResource` for resources.

This is a stricter/more heavily-documented style than typical Laravel apps — match it in new files rather than the terser style you might default to.

===

<laravel-boost-guidelines>
=== foundation rules ===

# Laravel Boost Guidelines

The Laravel Boost guidelines are specifically curated by Laravel maintainers for this application. These guidelines should be followed closely to ensure the best experience when building Laravel applications.

## Foundational Context

This application is a Laravel application running on PHP 8.4. You are an expert with the Laravel ecosystem. Always use the APIs that match the installed major version of each package — do not assume a version.

Before relying on a package's API, confirm its installed version:
- PHP packages: run `composer show --direct` to list direct dependencies with versions, or `composer show <vendor/package>` for a single package.
- JS packages: check `package.json` for the installed versions.

## Skills Activation

This project has domain-specific skills available in `**/skills/**`. You MUST activate the relevant skill whenever you work in that domain—don't wait until you're stuck.

## Conventions

- You must follow all existing code conventions used in this application. When creating or editing a file, check sibling files for the correct structure, approach, and naming.
- Use descriptive names for variables and methods. For example, `isRegisteredForDiscounts`, not `discount()`.
- Check for existing components to reuse before writing a new one.

## Verification Scripts

- Do not create verification scripts or tinker when tests cover that functionality and prove they work. Unit and feature tests are more important.

## Application Structure & Architecture

- Stick to existing directory structure; don't create new base folders without approval.
- Do not change the application's dependencies without approval.

## Frontend Bundling

- If the user doesn't see a frontend change reflected in the UI, it could mean they need to run `npm run build`, `npm run dev`, or `composer run dev`. Ask them.

## Documentation Files

- You must only create documentation files if explicitly requested by the user.

## Replies

- Be concise in your explanations - focus on what's important rather than explaining obvious details.

=== boost rules ===

# Laravel Boost

## Tools

- Laravel Boost is an MCP server with tools designed specifically for this application. Prefer Boost tools over manual alternatives like shell commands or file reads.
- Use `database-query` to run read-only queries against the database instead of writing raw SQL in tinker.
- Use `database-schema` to inspect table structure before writing migrations or models.
- Use `get-absolute-url` to resolve the correct scheme, domain, and port for project URLs. Always use this before sharing a URL with the user.
- Use `browser-logs` to read browser logs, errors, and exceptions. Only recent logs are useful, ignore old entries.

## Searching Documentation (IMPORTANT)

- Use `search-docs` before changes that depend on Laravel ecosystem APIs, behavior, configuration, or version-specific syntax. Skip it for copy-only edits and other changes where package documentation is irrelevant. Reuse sufficient results already in context instead of searching again.
- Pass a `packages` array to scope results when you know which packages are relevant.
- Use multiple broad, topic-based queries: `['rate limiting', 'routing rate limiting', 'routing']`. Expect the most relevant results first.
- Do not add package names to queries because package info is already shared. Use `test resource table`, not `filament 4 test resource table`.

### Search Syntax

1. Use words for auto-stemmed AND logic: `rate limit` matches both "rate" AND "limit".
2. Use `"quoted phrases"` for exact position matching: `"infinite scroll"` requires adjacent words in order.
3. Combine words and phrases for mixed queries: `middleware "rate limit"`.
4. Use multiple queries for OR logic: `queries=["authentication", "middleware"]`.

## Project Rules

- This project contains committed, area-grouped rules in `.ai/rules` when that directory exists (settled decisions, non-obvious traps, standing constraints). Framework and package guidelines that only apply to specific paths (testing, frontend, components) also live there, under `.ai/rules/boost` — this is not just recorded decisions, it is load-bearing guidance you have not seen inline. Before you enter plan mode or create/edit any file, you MUST first: open @.ai/rules/index.md (it maps file globs to rule files), read every rule file whose globs cover the path(s) in scope, and run `grep -rin 'keyword' .ai/rules` to catch what a path match alone misses. Do not write code until you have read and are following every matching rule. If `.ai/rules` does not exist, continue without it.
- Record a rule with `record-rule` only when the user explicitly asks for one. Instructions for the work at hand are not rules, no matter how emphatic: "remove this typo", "use X here" are work to do, not rules to record. Never record a rule on your own initiative, as a byproduct of a change, or to summarize what you just did. When the user does ask, pass a `glob` (e.g. `app/Http/Controllers/**`), a short `title`, and a few-line `note`. Use `record-rule` rather than your native memory or notes tool, because native memory is personal and session-scoped, while only `.ai/rules` is shared with the team and persists in the repo.

## Artisan

- Run Artisan commands directly via the command line (e.g., `php artisan route:list`). Use `php artisan list` to discover available commands and `php artisan [command] --help` to check parameters.
- Inspect routes with `php artisan route:list`. Filter with: `--method=GET`, `--name=users`, `--path=api`, `--except-vendor`, `--only-vendor`.
- Read configuration values using dot notation: `php artisan config:show app.name`, `php artisan config:show database.default`. Or read config files directly from the `config/` directory.

## Tinker

- Execute PHP in app context for debugging and testing code. Do not create models without user approval, prefer tests with factories instead. Prefer existing Artisan commands over custom tinker code.
- Always use single quotes to prevent shell expansion: `php artisan tinker --execute 'Your::code();'`
  - Double quotes for PHP strings inside: `php artisan tinker --execute 'User::where("active", true)->count();'`

=== php rules ===

# PHP

- Always use curly braces for control structures, even for single-line bodies.
- Use PHP 8 constructor property promotion: `public function __construct(public GitHub $github) { }`. Do not leave empty zero-parameter `__construct()` methods unless the constructor is private.
- Use explicit return type declarations and type hints for all method parameters: `function isAccessible(User $user, ?string $path = null): bool`
- Follow existing application Enum naming conventions.
- Prefer PHPDoc blocks over inline comments. Only add inline comments for exceptionally complex logic.
- Use array shape type definitions in PHPDoc blocks.

=== deployments rules ===

# Deployment

- Laravel can be deployed using [Laravel Cloud](https://cloud.laravel.com/), which is the fastest way to deploy and scale production Laravel applications.
- Activate the `deploying-to-cloud` skill whenever deploying to Laravel Cloud, configuring Cloud environments or resources, using the Cloud CLI, or troubleshooting Cloud deployments.

=== tests rules ===

# Test Enforcement

- Add or update tests for behavior and logic changes when a test provides meaningful regression coverage.
- Pure copy, styling, and layout-only changes do not require new or updated tests.
- When test coverage applies, run the affected tests and ensure they pass.
- Test the changed behavior and its important failure modes, but do not add tests beyond them.
- Read the `testing-best-practices` skill before writing tests.

=== laravel/core rules ===

# Do Things the Laravel Way

- Use `php artisan make:` commands to create new files (i.e. migrations, controllers, models, etc.). You can list available Artisan commands using `php artisan list` and check their parameters with `php artisan [command] --help`.
- If you're creating a generic PHP class, use `php artisan make:class`.
- Pass `--no-interaction` to all Artisan commands to ensure they work without user input. You should also pass the correct `--options` to ensure correct behavior.

### Model Creation

- When creating new models, create useful factories and seeders for them too. Ask the user if they need any other things, using `php artisan make:model --help` to check the available options.

## APIs & Eloquent Resources

- For APIs, default to using Eloquent API Resources and API versioning unless existing API routes do not, then you should follow existing application convention.

## URL Generation

- When generating links to other pages, prefer named routes and the `route()` function.

## Testing

- When creating models for tests, use the factories for the models. Check if the factory has custom states that can be used before manually setting up the model.
- Faker: Use methods such as `$this->faker->word()` or `fake()->randomDigit()`. Follow existing conventions whether to use `$this->faker` or `fake()`.
- When creating tests, make use of `php artisan make:test [options] {name}` to create a feature test, and pass `--unit` to create a unit test. Most tests should be feature tests.

## Vite Error

- If you receive an "Illuminate\Foundation\ViteException: Unable to locate file in Vite manifest" error, you can run `npm run build` or ask the user to run `npm run dev` or `composer run dev`.

=== pint/core rules ===

# Laravel Pint Code Formatter

- If you have modified any PHP files, you must run `vendor/bin/pint --dirty --format agent` before finalizing changes to ensure your code matches the project's expected style.
- Do not run `vendor/bin/pint --test --format agent`, simply run `vendor/bin/pint --format agent` to fix any formatting issues.

=== phpunit/core rules ===

# PHPUnit

- This project uses PHPUnit. Create tests with `php artisan make:test --phpunit {name}`.
- Do not include the test suite directory in `{name}`. Use `SomeFeatureTest`, not `Feature/SomeFeatureTest`.
- Read the `testing-best-practices` skill for guidance on coverage, naming, structure, dependency isolation, and review.

## Running Tests

- Run the narrowest set of tests that covers the change. Pass a file path or `--filter=testName` to `php artisan test --compact`.
- Rerun a test after each change to it.
- Run `vendor/bin/phpunit` to call the test runner directly. It accepts the same file path and `--filter=testName` arguments.

</laravel-boost-guidelines>
