# Constitution Index — Supreme Build Authority

**STATUS:** SUPREME AUTHORITY
**SCOPE:** This file defines the documentation authority hierarchy and consolidates cross-cutting mandates that do not belong to a single constitution file.

---

## 1. Authority Hierarchy

```
┌───────────────────────────────────────────────────────────┐
│  Level 1: Master Constitution                             │
│  Path: .specify/memory/constitution.md                    │
│  Any conflict with any other document → Constitution wins │
├───────────────────────────────────────────────────────────┤
│  Level 2: Constitution Files (this folder)                │
│  Path: CONSTITUTIONS/*.md                                 │
│  The EXCLUSIVE authority for "HOW to build"               │
│  Any conflict with any other document → wins here         │
├───────────────────────────────────────────────────────────┤
│  Level 3: Specifications (SPECIFICATIONS/)                │
│  Path: SPECIFICATIONS/**/*.md                             │
│  Defines "WHAT to build" — no implementation HOW          │
│  Any mention of HOW is a pointer, not a definition        │
├───────────────────────────────────────────────────────────┤
│  Level 4: This Index                                      │
│  Entry point and navigation only — defines no rules       │
└───────────────────────────────────────────────────────────┘
```

### Conflict Resolution Rule

When a conflict exists between any two documents:
1. If one side is `constitution.md` → it wins immediately
2. If one side is a file from `CONSTITUTIONS/` → it wins
3. If the conflict is between two files in `SPECIFICATIONS/` → consult the relevant constitution to resolve
4. If the constitution does not resolve it → consult `constitution.md`

---

## 2. Cross-Cutting Mandates

### 2.1 Testing Mandates (Non-Negotiable)

| Rule | Detail |
|:---|:---|
| Test-First | Tests are written before implementation. |
| PHPUnit Coverage | Unit tests — pure, no database |
| Feature Coverage | One test for every API endpoint |
| Payment Engine Tests | Must cover: happy path + all error scenarios + boundary conditions |
| Minimum Coverage | **80%** minimum |
| Deleting Failing Tests | Prohibited — must fix or get explicit approval |

### 2.2 Test Structure

```
tests/
├── Unit/
│   ├── Services/
│   ├── Models/
│   └── Traits/
└── Feature/
    ├── Auth/
    ├── Customer/
    ├── Agent/
    ├── Contract/
    ├── Payment/
    ├── Shares/
    ├── Investor/
    ├── Analytics/
    └── Notification/
```

### 2.3 Factory Standards

- Every domain MUST have a Factory
- Use `fake('ar_SA')` for realistic Arabic data
- Syrian phone format: `09XXXXXXXX`
- Factories MUST support role flags via state methods

### 2.4 Seeder Standards

- All seeders MUST be idempotent — `firstOrCreate` only.
- Use `fake('ar_SA')`. No "Lorem ipsum".

### 2.5 Security Mandates

| Rule | Detail |
|:---|:---|
| Authentication | Laravel Sanctum — Bearer token |
| Authorization | Spatie Laravel Permission — `guard_name = 'admin'` |
| Route Protection | Every route requires `auth:admin` (Exception: `/api/v1/auth/login`) |
| Input Protection | All inputs validated via FormRequest |
| Mass Assignment | Explicit `$fillable` — No `guarded = ['*']` |
| Rate Limit — Login | 5 attempts/minute per IP |
| Rate Limit — Authenticated | Per admin user: Read 120 req/min, Write 60 req/min |
| Error Messages | All via `__()` — No hardcoded strings |

### 2.6 Project Structure

```
tamkeen/
├── app/
│   ├── Domains/
│   │   ├── Auth/
│   │   │   ├── Models/
│   │   │   │   └── Scopes/
│   │   │   ├── Queries/
│   │   │   ├── DTOs/
│   │   │   ├── Services/
│   │   │   ├── Actions/                 ← Orchestrators (See 10_ACTION_SERVICE...)
│   │   │   ├── Validation/              ← Domain Validators (See 08_FORM_REQUESTS...)
│   │   │   ├── Enums/
│   │   │   │   └── Display/
│   │   │   ├── Http/
│   │   │   │   ├── Controllers/
│   │   │   │   ├── Requests/
│   │   │   │   └── Resources/
│   │   │   ├── Jobs/
│   │   │   └── Routes/v1/api.php
│   │   ├── ... (Other Domains)
│   │   └── Shared/
│   │       ├── Models/                  ← Foundational Entities (e.g., Client.php)
│   │       ├── ValueObjects/            ← Money, etc.
│   │       ├── Traits/                  ← HasReferenceNumber, PreventsDeletion
│   │       ├── Filters/                 ← DateRangeFilter, SearchFilter
│   │       └── Validation/
│   │           └── Rules/               ← Reusable Custom Rules
│   ├── Exceptions/
│   │   ├── ExceptionMappings.php
│   │   └── Business/                    ← Specialized Domain Exceptions
│   ├── Http/
│   │   ├── Controllers/
│   │   │   └── Controller.php           ← Base Controller (HasApiResponse Trait)
│   │   └── Resources/
│   │       └── CursorMeta.php           ← Pagination Meta Resource
│   ├── Services/
│   │   └── ApiResponseFormatter.php
│   ├── Facades/
│   │   ├── ApiResponse.php
│   │   └── FileService.php
│   └── ...
├── routes/
│   └── api.php                          ← Central dynamic loader
└── tests/
```

### 2.7 Naming Conventions

| Item | Convention | Example |
|:---|:---|:---|
| Models | Singular, PascalCase | `Client`, `Contract` |
| Actions | `{Purpose}Action` | `CreateContractAction` |
| Domain Validators | `Validate{Purpose}` | `ValidateShareWithdrawal` |
| Shared Rules | Descriptive | `UniqueExceptCurrentPhone` |
| Read DTOs | `{Description}DTO` | `CustomerFinancialSummaryDTO` (No double DTO suffix) |

### 2.8 Git Workflow

#### Branch Structure
```
main          ← production-ready only
  └── develop ← integration branch
        └── feat/SP-{N}-{slug}
        └── fix/{slug}
```

#### Commit Format (Conventional Commits)
```
feat(SP-07): add contract creation with auto-installment generation
fix(SP-08): correct LIFO payment deletion validation
```

---

## 3. Constitution File Index

| File | Topic | Question It Answers |
| :--- | :--- | :--- |
| `01_EVENTS_OBSERVERS.md` | Events, Listeners & Observers | When do I use Event/Listener/Observer? |
| `02_ERROR_BOUNDARIES.md` | Exceptions & Error Boundaries | How do I build/map an Exception? |
| `03_ENUMS.md` | Enums | What is allowed inside an Enum? |
| `04_DATABASE_COMMUNICATION.md` | Database Communication | Scope vs Query vs Builder? |
| `05_ROUTING_PROVIDERS.md` | Routing & Service Providers | How are routes loaded? When do I create a ServiceProvider? |
| `06_SHARED_DOMAIN.md` | The Shared Domain | What is allowed in Shared? |
| `07_BOUNDARY_LAYERS.md` | Boundary Layers | Rules for Resource, Job, Controller, Response? |
| `08_FORM_REQUESTS.md` | FormRequests & Validation | Custom Rules vs Domain Validators? |
| `09_DTOS.md` | Data Transfer Objects | What are the three DTO types? |
| `10_ACTION_SERVICE_ORCHESTRATION.md` | Actions & Services | When do I create an Action vs calling Service directly? |

---

## 4. Quick Decision Trees

### 4.1 "Where do I look for a build rule?"

```
Is the question about HOW to build something specific?
├─ Event/Listener/Observer → CONSTITUTIONS/01_EVENTS_OBSERVERS.md
├─ Exception or error handling → CONSTITUTIONS/02_ERROR_BOUNDARIES.md
├─ Enum or Display Class → CONSTITUTIONS/03_ENUMS.md
├─ Database query or DTO or Transaction → CONSTITUTIONS/04_DATABASE_COMMUNICATION.md
├─ Route or ServiceProvider → CONSTITUTIONS/05_ROUTING_PROVIDERS.md
├─ Something in the Shared folder → CONSTITUTIONS/06_SHARED_DOMAIN.md
├─ Resource, Job, Filter, Controller, Response → CONSTITUTIONS/07_BOUNDARY_LAYERS.md
├─ FormRequest, Custom Rule, Domain Validator → CONSTITUTIONS/08_FORM_REQUESTS.md
├─ DTO (type, construction, when to use) → CONSTITUTIONS/09_DTOS.md
└─ Action vs Service orchestration → CONSTITUTIONS/10_ACTION_SERVICE_ORCHESTRATION.md
```

### 4.2 "Where do I look for a specification or business rule?"

```
Is the question about WHAT, not HOW?
├─ Business constraint → SPECIFICATIONS/01_BUSINESS_CONTEXT/03_BUSINESS_RULES.md
├─ What must the system do? → SPECIFICATIONS/02_REQUIREMENTS/01_FUNCTIONAL.md
├─ API endpoint specification → SPECIFICATIONS/06_API/{relevant file}.md
├─ Database table shape → SPECIFICATIONS/04_DATABASE/01_TABLES.md
├─ Specific algorithm → SPECIFICATIONS/05_ALGORITHMS/{relevant file}.md
├─ Why was this decision made? → SPECIFICATIONS/03_ARCHITECTURE/04_DECISION_RECORDS.md
└─ Entity state → SPECIFICATIONS/03_ARCHITECTURE/02_STATE_MACHINES.md
```

---

## 5. Rejected Patterns Catalog (Quick Reference)

### Prohibited Under All Circumstances

| Prohibited | Referenced Constitution |
|:---|:---|
| Business logic inside Controller or Model | `constitution.md` → Principle I |
| `float` or `double` in financial calculations | `SPECIFICATIONS/.../03_BUSINESS_RULES.md` → BR-006-2 |
| Modifying a payment amount | `SPECIFICATIONS/.../03_BUSINESS_RULES.md` → BR-004-4 |
| Modifying a contract after signing | `SPECIFICATIONS/.../03_BUSINESS_RULES.md` → BR-002-4 |
| `__()` or HTTP Status inside Domain Exception | `02_ERROR_BOUNDARIES.md` → Prohibitions |
| `try-catch` to convert Exception to JSON | `02_ERROR_BOUNDARIES.md` → Catch Rules |
| Generic Exception for multiple contexts (e.g., `DataIntegrityException`) | `02_ERROR_BOUNDARIES.md` → Single Context Rule |
| `str_contains` on log messages in ExceptionMappings | `02_ERROR_BOUNDARIES.md` → Prohibitions |
| `fromRequest()` inside DTO | `09_DTOS.md` → Prohibitions |
| DI, Color, or Translation inside Enum | `03_ENUMS.md` → Prohibitions |
| State Machine maps inside Enum | `03_ENUMS.md` → Prohibitions |
| Database query inside Resource | `07_BOUNDARY_LAYERS.md` → Resource Prohibitions |
| `Resource::collection($paginator)` | `07_BOUNDARY_LAYERS.md` → make() vs collection() |
| `$request->validated()` in Controller | `07_BOUNDARY_LAYERS.md` → Input Extraction Rules |
| Global helpers (like `success()`, `cursorMeta()`) | `07_BOUNDARY_LAYERS.md` → Response Construction |
| Creating Action for single Service call | `10_ACTION_SERVICE_ORCHESTRATION.md` → Prohibitions |
| Returning Eloquent Models from Actions | `10_ACTION_SERVICE_ORCHESTRATION.md` → Return Types |
| Financial Audit Log inside Listener | `01_EVENTS_OBSERVERS.md` → Prohibitions |
| Domain-specific Models in Shared (only Foundational) | `06_SHARED_DOMAIN.md` → Allowed List |
| ServiceProvider created only to load routes | `05_ROUTING_PROVIDERS.md` → Prohibitions |
| Omitting `->whereNumber()` for numeric IDs | `05_ROUTING_PROVIDERS.md` → Parameter Constraints |
| Eloquent or Query Builder inside `withValidator` | `08_FORM_REQUESTS.md` → Prohibitions |
| `required` rule in Update FormRequests | `08_FORM_REQUESTS.md` → Update Requests |
| Repository as default pattern | `04_DATABASE_COMMUNICATION.md` → Prohibitions |
| Raw arrays crossing layer boundaries | `04_DATABASE_COMMUNICATION.md` → Prohibitions |
| `guarded = ['*']` in any Model | This file → Security Mandates |
| Using `float` or `double` for monetary values (Violates BR-006-1) | `06_SHARED_DOMAIN.md` → Value Objects |
| Passing raw numeric strings to `Money::of()` without ensuring they originate from safe sources (HTTP or DB) | `06_SHARED_DOMAIN.md` → Money Constructor |
| Using `$money->formatted()` in database writes or Service calculations | `06_SHARED_DOMAIN.md` → Money Methods |