# Task Execution Template

Copy this file for every task. Fill it top to bottom. Do not write production code before
the **Targeted Discovery** and **Implementation Plan** sections are complete.

Reference: `AGENTS.md` · `docs/PROJECT_ARCHITECTURE.md` · `docs/DOMAIN_MODELING_GUIDE.md` ·
`docs/API_WORKFLOW.md` · `docs/SWAGGER_GUIDE.md`

> This is a **base codebase**. Existing files define *how* to build; the analysis defines
> *what* to build. If a needed model does not exist, design it — do not reuse an unrelated
> old-domain model.

---

## Task Name

<!-- One line. e.g. "Client Signup + Provider Signup" -->

---

## Task Type

<!-- Tick one. It determines which standard and which checklists apply. -->

- [ ] **New Business Module** — model does not exist yet · `DOMAIN_MODELING_GUIDE.md` · `API_WORKFLOW.md` § 2b → §§ 3–13
- [ ] **API** — existing new-domain module · `AGENTS.md` § API Implementation Standard · `API_WORKFLOW.md` §§ 3–13
- [ ] **Dashboard** — `AGENTS.md` § Dashboard Implementation Standard · `API_WORKFLOW.md` § 14
- [ ] **Socket / Cron** — `AGENTS.md` § Socket & Cron Standard · `API_WORKFLOW.md` § 15
- [ ] **Bug fix** — no new surface; smallest possible diff; add a regression test
- [ ] **Docs only** — no code changes

---

## Pre-Flight: Does It Already Exist?

<!--
Run before planning anything. Paste the real output.

grep -rn "<endpoint-path>" src/routes/
grep -rn "<functionName>"  src/helpers/api/ src/controllers/
ls src/models | grep -i <entity>
-->

| Check | Command run | Result |
|---|---|---|
| Endpoint already registered? |  |  |
| Logic already implemented? |  |  |
| Model already exists? |  |  |
| If it exists — **base/old domain** or **new domain**? |  |  |

**Verdict:**
☐ New business module (model must be designed)
☐ Modification of an existing **new-domain** module
☐ Name collides with an **old-domain** model → raise with the human before proceeding
☐ Already fully implemented → stop and report

---

## Feature Scope

<!--
In / out of scope, in plain terms.
IN:  …
OUT: …
Surface: API (/api) | Dashboard (/dashboard) | Webview (/web) | Socket | Cron
Actors: client | provider (store/haraj) | admin | guest
-->

---

## What Should Be Implemented

<!--
Numbered list of concrete deliverables.
1. POST /api/… — …
2. …
-->

---

## What Must Not Be Changed

<!--
Default list — extend as needed:
- The stack (no new packages, no framework swap)
- src/routes/index/index.js structure (AppInitializer)
- ApiResponse / ApiError / errorHandler contracts
- Unrelated domains, controllers, models, or views
- .env, .htaccess, .gitlab-cd.yml, certificate paths
- Password hashing scheme (userModel pre('save'))
- Anything listed as "Known Issues" in PROJECT_ARCHITECTURE.md unless this task IS that fix
-->

---

## Domain Design

> Required for any task that creates or changes a business model.
> Complete and get this reviewed **before** writing a schema file.
> Guide: `docs/DOMAIN_MODELING_GUIDE.md`.

### New Models Needed

| Model | Purpose | Faces (client / provider / admin / shared) | Source of the design |
|---|---|---|---|
|  |  |  | *(analysis doc / epic / human)* |

### Existing Models Reused

| Model | New domain or base/old? | Why it is legitimately reused |
|---|---|---|
|  |  |  |

<!-- If a base/old model appears here, justify it explicitly. Default answer is "do not reuse". -->

### Relationships

| From | Field | To | Cardinality | Indexed? | Populated where? |
|---|---|---|---|---|---|
|  |  |  | 1:1 / 1:N / N:M |  | *(service layer — NOT pre(/^find/))* |

### Status Flow

| Status value | Enum file | Entered from | Entered by | Terminal? |
|---|---|---|---|---|
|  | `src/helpers/enums/<x>.enum.js` |  |  |  |

<!-- Draw the allowed transitions. Invalid source states must be rejected, not silently accepted. -->

```
draft → pending → active → …
```

### Fields

| Field | Type | Required | Default | Unique | select:false | Notes |
|---|---|---|---|---|---|---|
|  |  |  |  |  |  |  |

### Indexes

| Index | Type | Which query/endpoint needs it |
|---|---|---|
|  | single / compound / partial-unique / 2dsphere |  |

<!-- Every index must name the query that justifies it. The base declares indexes in only
     8 of 67 models — do not inherit that. -->

### Soft Delete & Timestamps

- Soft delete convention applied: <!-- status enum + deletedAt, per DOMAIN_MODELING_GUIDE -->
- `{ timestamps: true, versionKey: false }`: ☐ yes
- Partial unique index needed for any unique field? ☐ yes ☐ n/a

### Security Notes

- Sensitive fields and how they are protected (`select: false` **and** omitted from the DTO):
- Fields deliberately **not** exposed in the DTO (and why):
- Ownership rule (who may read / write a row):
- File/image fields — stored as filenames, URLs built in `@returnObj`: ☐ yes ☐ n/a
- Audit/history required? ☐ separate `<Entity>StatusHistory` collection ☐ not needed

### Design Confirmations

- [ ] No `pre(/^find/)` auto-populate on the new model
- [ ] No old-domain model extended to host new behaviour
- [ ] Every status value comes from a frozen enum
- [ ] Naming matches `DOMAIN_MODELING_GUIDE.md` § Naming
- [ ] Design reviewed by the human before implementation

---

## Targeted Discovery

### Files To Inspect

| File | Why |
|---|---|
|  |  |

### Existing Patterns

<!--
What conventions did you find that this task must copy?
- Route class shape / auth bucket
- Validator + getValidationChain wiring
- Thin controller → helpers/api/<Domain>.js
- @returnObj DTO shape for the entities involved
- Enums / status transitions already defined
- i18n namespaces already in use
-->

### Routes

<!-- Existing routes in scope + where new ones will be registered (which class, which bucket) -->

### Controllers

<!-- Which controller files, which methods -->

### Validations

<!-- Which validator class, which static methods, which shared building blocks are reusable -->

### Services

<!-- helpers/api/<Domain>.js methods; any src/services/* integration (SMS, push, OTO, Agora, cron) -->

### Models

<!-- Models read/written; fields added; hooks or indexes affected; does userModel change ripple to Client/Provider/ProviderMeta? -->

### Swagger

<!-- Which endpoints will be documented; which docs/openapi/paths/*.yaml and which Postman collection -->

---

## Files To Create

| Path | Purpose |
|---|---|
|  |  |

---

## Files To Modify

| Path | Change |
|---|---|
|  |  |

---

## Implementation Plan

<!--
Ordered steps, bottom-up:
1. Model / enum changes
2. Validator methods
3. Route registration (correct auth bucket)
4. Thin controller delegates
5. Business logic in helpers/api/<Domain>.js
6. @returnObj DTO
7. i18n keys (ar + en)
8. API docs (touched endpoints only)
9. Tests
-->

---

## Blast Radius & Rollback

**Shared files touched** (each one affects other features — list who else depends on them):

| Shared file | Also used by | Risk |
|---|---|---|
| `src/models/userModel.js` | Client + Provider + ProviderMeta | a field change ripples to all three |
| `src/helpers/returnObject/returnObject.js` | every API response | a DTO change is visible to the mobile app |
| `src/routes/api/indexRoute/indexRoute.js` | all API routing | ordering vs `requireAuth` matters |
| `src/routes/dashboard/adminRoute/adminRoute.js` | whole dashboard | route-order regressions are easy |
| `src/locales/{ar,en}/*.json` | all surfaces | catalogue is loaded statically at boot |
|  |  |  |

**Breaking-change check:**

- [ ] No existing response field was removed or renamed (mobile clients read them)
- [ ] No existing `key` value changed for an existing endpoint
- [ ] No existing route path or method changed
- [ ] No enum value removed (only added)
- [ ] No required-field added to an existing request without a migration story

**Rollback:** <!-- Which commits/files to revert, and whether any DB write is irreversible. -->

---

## Validation Rules

| Field | Type | Required | Rule | Error i18n key |
|---|---|---|---|---|
|  |  |  |  |  |

<!-- Every field the handler reads must appear here — matchedData drops undeclared fields. -->

---

## Security Rules

- [ ] Every consumed field is declared in a validator
- [ ] Ownership enforced via `req.user._id` in the query (not trusted from the body)
- [ ] Response contains no `password`, `activationCode`/OTP, secret, or `.env` value
- [ ] No credential-bearing `console.log`
- [ ] IDs validated with `isMongoId()` before querying
- [ ] Uploads validated by magic bytes (`GlobalValidator.validateImageFile`), path built via `makeDir`
- [ ] Money/balance changes guarded by `checkBalance` and recorded in `BalanceHistory` / `FinancialTransaction`
- [ ] Status transitions use enums and reject invalid source states
- [ ] Public endpoints leak nothing that requires auth
- [ ] Dashboard route (if touched): `csrfProtection` present; `uploadsFiles()` before it on multipart
- [ ] No new package added

---

## Swagger Updates

| Endpoint | Tag | File | Change |
|---|---|---|---|
|  |  |  |  |

- [ ] Only touched endpoints documented
- [ ] `security: []` for public endpoints, `bearerAuth` otherwise
- [ ] `lang` header parameter present
- [ ] Every documented field exists in the real DTO
- [ ] No secrets, OTPs, tokens, or real customer data in examples
- [ ] Matching Postman request updated

---

## Manual QA

| # | Step | Expected `key` / `status` | Result |
|---|---|---|---|
| 1 | Happy path |  |  |
| 2 | Each validation failure |  |  |
| 3 | `lang: ar` and `lang: en` |  |  |
| 4 | Unauthenticated call to protected route | `unauthorized` / 419 |  |
| 5 | Wrong-owner call | `fail` or `unauthorized` |  |
| 6 | Pagination (`page`, `limit`) if listing |  |  |

Run with: `npm run start:dev`

---

## Automated Tests

| Test file | Covers | Result |
|---|---|---|
|  |  |  |

```
# paste real `npm test` output here, including failures
```

---

## Final Report

1. **Files inspected** —
2. **Files created** —
3. **Files modified** —
4. **Endpoints added/changed** — (method + path + auth bucket)
5. **Validation rules** —
6. **Documentation updates** —
7. **Security checks performed** —
8. **Manual QA** —
9. **Automated test results** —
10. **Not implemented / deferred, and why** —

---

## Definition of Done

- [ ] Pre-Flight run; base/old vs new-domain classification recorded
- [ ] Domain Design completed and reviewed **before** any schema was written (new models)
- [ ] New model follows `DOMAIN_MODELING_GUIDE.md`: declared indexes · enum-backed status ·
      `select: false` on sensitive fields · no `pre(/^find/)` auto-populate · timestamps
- [ ] No old-domain model reused or extended to host new-product behaviour
- [ ] Module ships as a complete vertical slice: model · validation · route · controller ·
      service · swagger · tests where applicable
- [ ] Targeted Discovery was done and reported before coding
- [ ] Code follows existing patterns (route class → thin controller → `helpers/api` logic)
- [ ] No unrelated files modified
- [ ] Validation exists for every new input field
- [ ] Responses built from `@returnObj` + `ApiResponse`; no sensitive fields
- [ ] Errors go through `errorHandler` with the correct `statusName`
- [ ] i18n keys added to both `ar` and `en`
- [ ] API documentation updated for touched endpoints only
- [ ] Tests and/or manual QA documented with real results
- [ ] No secrets leaked, no credentials logged
- [ ] No packages added, stack unchanged
