# Tasks: Base Architecture - Foundation Layers (SP-03)

**Input**: Design documents from `/specs/003-base-architecture/`

**Prerequisites**: plan.md (✅), spec.md (✅), research.md (✅), data-model.md (✅)

**Tests**: Not explicitly requested in feature specification — skipping test tasks

## Format: `[ID] [P?] [Story] Description`

- **[P]**: Can run in parallel (different files, no dependencies)
- **[Story]**: Which user story this task belongs to (e.g., US1, US2, US3)
- Include exact file paths in descriptions

---

## Phase 1: Setup (Shared Infrastructure)

**Purpose**: Verify existing Laravel structure and helpers

- [x] T001 [P] Verify app/Models directory exists (Laravel default User model)
- [x] T002 [P] Verify app/Domains directory structure per Constitution
- [ ] T003 [P] Verify app/Shared/Repositories/ directory structure
- [x] T004 [P] Verify app/Helpers/ApiResponseHelper.php exists (SP-01)
- [x] T005 [P] Verify app/Helpers/CostumErrorResponse.php exists (SP-01)
- [x] T006 [P] Verify config/ExceptionClassToMethod.php exists (existing exception mapping pattern from SP-01)
- [x] T007 [P] Verify config/ directory and base configs

---

## Phase 2: Foundational (Blocking Prerequisites)

**Purpose**: Infrastructure that all user stories depend on

**CRITICAL**: No user story work can begin until this phase is complete

- [x] T008 [P] Create app/Shared/Repositories/Contracts/ directory
- [x] T009 [P] Create app/Shared/Repositories/Eloquent/ directory
- [x] T010 [P] Create app/Shared/Http/Resources/ directory
- [x] T011 [P] Create app/Domains/Auth/Models/ directory
- [x] T012 [P] Create app/Domains/Contract/Models/ directory
- [x] T013 [P] Create app/Domains/Payment/Models/ directory
- [x] T014 [P] Create app/Domains/Agent/Models/ directory
- [x] T015 [P] Create app/Domains/Notification/Models/ directory

**Checkpoint**: Directory structure ready for model creation

---

## Phase 3: User Story 1 - Eloquent Models with Semantic Relationships (Priority: P1) 🎯 MVP

**Goal**: Create 8 Eloquent models with correct relationships and hard immutability for User

**Independent Test**: Instantiate each model and call relationships to verify return types and integrity

**Dependencies**: Phase 2 (Foundational) must be complete before this phase

### Implementation for User Story 1

- [x] T016 [P] [US1] Create User model in app/Models/User.php with contractsAsCustomer(), contractsAsAgent(), sharesLogs() relationships
- [x] T017 [P] [US1] Create Admin model in app/Domains/Auth/Models/Admin.php with HasRoles trait and guard_name = 'admin'
- [x] T018 [P] [US1] Create Contract model in app/Domains/Contract/Models/Contract.php with customer(), agent(), installments() (ordered), payments(), auditLogs() (ordered desc) relationships
- [x] T019 [P] [US1] Create Installment model in app/Domains/Contract/Models/Installment.php with contract() belongsTo relationship
- [x] T020 [P] [US1] Create Payment model in app/Domains/Payment/Models/Payment.php with contract() and auditLogs() relationships
- [x] T021 [P] [US1] Create PaymentAuditLog model in app/Domains/Payment/Models/PaymentAuditLog.php with contract() and payment() relationships
- [x] T022 [P] [US1] Create AgentSharesLog model in app/Domains/Agent/Models/AgentSharesLog.php with agent() relationship
- [x] T023 [P] [US1] Create NotificationTemplate model in app/Domains/Notification/Models/NotificationTemplate.php as standalone (no relationships)
- [x] T024 [US1] Implement hard immutability for User model — override delete() and destroy() to throw RuntimeException with message "Users cannot be deleted" (depends on T016 completion)
- [x] T025 [US1] Add decimal(10,2) casting for all monetary fields in all models per FR-016

**Checkpoint**: All 8 models exist and relationships are correct

---

## Phase 4: User Story 2 - Repository Pattern Infrastructure (Priority: P1)

**Goal**: Create BaseRepositoryInterface and BaseEloquentRepository for sole database gateway

**Independent Test**: Instantiate base repository and verify it implements interface contract

**Dependencies**: Phase 2 (Foundational) must be complete before this phase

### Implementation for User Story 2

- [x] T026 [P] [US2] Create BaseRepositoryInterface in app/Shared/Repositories/Contracts/BaseRepositoryInterface.php defining CRUD methods: all(), find(), findOrFail(), create(), update(), delete(), paginate(), AND cursorPaginate() per Constitution pagination rules (Section 4.3)
- [x] T027 [P] [US2] Create BaseEloquentRepository in app/Shared/Repositories/Eloquent/BaseEloquentRepository.php implementing BaseRepositoryInterface using Laravel Eloquent
- [x] T028 [US2] Register repository binding in app/Providers/AppServiceProvider.php: $this->app->bind(BaseRepositoryInterface::class, BaseEloquentRepository::class)

**Checkpoint**: Repository pattern infrastructure is bound and ready for use

---

## Phase 5: User Story 3 - Unified API Response Infrastructure (Priority: P1)

**Goal**: Create BaseResource class ensuring consistent response format with success, message, data fields

**Independent Test**: Create dummy resource extending BaseResource and verify JSON structure

**Dependencies**: Phase 2 (Foundational) must be complete before this phase

### Implementation for User Story 3

- [x] T029 [P] [US3] Create BaseResource in app/Shared/Http/Resources/BaseResource.php extending JsonResource with toArray() wrapping response in success, message, data structure

**Checkpoint**: BaseResource ready for all API resources to extend

---

## Phase 6: User Story 4 - Exception Handler Integration (Priority: P1)

**Goal**: Map Laravel exceptions to appropriate API responses via config/ExceptionClassToMethod.php

**Independent Test**: Trigger exceptions and verify correct HTTP status codes and JSON structure

**Dependencies**: Phase 2 (Foundational) must be complete before this phase

**IMPORTANT**: Use EXISTING config/ExceptionClassToMethod.php pattern — do NOT use withExceptions() in bootstrap/app.php

### Implementation for User Story 4

- [x] T030 [P] [US4] Verify existing config/ExceptionClassToMethod.php structure and existing exception mappings
- [x] T031 [P] [US4] If not already present, add ModelNotFoundException → modelNotFoundResponse() mapping to config/ExceptionClassToMethod.php
- [x] T032 [P] [US4] If not already present, add ValidationException → unprocessableResponse() mapping to config/ExceptionClassToMethod.php
- [x] T033 [P] [US4] If not already present, add AuthorizationException → forbiddenResponse() mapping to config/ExceptionClassToMethod.php
- [x] T034 [US4] Add RuntimeException (User deletion) → immutabilityViolationResponse() mapping to config/ExceptionClassToMethod.php for FR-009 hard immutability
- [x] T035 [US4] Add EntityNotFoundException → notFoundResponse() mapping to config/ExceptionClassToMethod.php for relationship edge case

**Checkpoint**: Exception handler returns unified API responses for all mapped exceptions via ExceptionClassToMethod.php

---

## Phase 7: User Story 5 - Queue Infrastructure (Priority: P1)

**Goal**: Configure queue system to use database driver for async job processing

**Independent Test**: Dispatch test job and verify it appears in jobs table

**Dependencies**: Phase 2 (Foundational) must be complete before this phase

### Implementation for User Story 5

- [x] T036 [P] [US5] Verify create_jobs_table.php migration exists in database/migrations/
- [ ] T037 [P] [US5] Verify create_failed_jobs_table.php migration exists in database/migrations/
- [x] T038 [P] [US5] Verify notification_templates table migration exists in database/migrations/ (created in SP-02)
- [x] T039 [US5] Update .env to set QUEUE_CONNECTION=database
- [x] T040 [US5] Verify config/queue.php is configured for database driver

**Checkpoint**: Queue configured and ready for SP-04 async exports

---

## Phase 8: Polish & Cross-Cutting Concerns

**Purpose**: Validation and consistency across all user stories

- [x] T041 [P] Verify all models have correct $fillable for mass assignment protection
- [x] T042 [P] Verify all monetary fields use decimal(10,2) casting
- [x] T043 Verify AppServiceProvider has all repository bindings
- [x] T044 Run php artisan about to verify Laravel installation
- [x] T045 Run quickstart.md verification commands

---

## Dependencies & Execution Order

### Phase Dependencies

- **Setup (Phase 1)**: No dependencies — can start immediately
- **Foundational (Phase 2)**: Depends on Setup completion — BLOCKS all user stories
- **User Stories (Phase 3-7)**: All depend on Foundational phase completion
- **Polish (Phase 8)**: Depends on all user stories being complete

### User Story Dependencies

- **User Story 1 (P1)**: Can start after Foundational (Phase 2) — creates all 8 models
- **User Story 2 (P1)**: Can start after Foundational (Phase 2) — creates repository infrastructure
- **User Story 3 (P1)**: Can start after Foundational (Phase 2) — creates BaseResource
- **User Story 4 (P1)**: Can start after Foundational (Phase 2) — configures exception mapping via ExceptionClassToMethod.php
- **User Story 5 (P1)**: Can start after Foundational (Phase 2) — configures queue

All user stories (Phase 3-7) can proceed in parallel after Foundational completes since they create different infrastructure components.

### Within User Story 1 Task Dependencies

- **T024 depends on T016**: Hard immutability implementation (delete/destroy override) requires User model to be created first

---

## Parallel Opportunities

### Within User Story 1
- T016-T023: All 8 models can be created in parallel (different files)
- T024: Must follow T016 (User model must exist first)

### Within User Story 2
- T026-T027: Interface and Implementation can be created in parallel
- T028: Depends on T026 and T027 (binding needs both)

### Within User Story 4
- T030-T033: Exception mapping verification and additions can be done in parallel (existing config modifications)
- T034-T035: Additional exception mappings can be parallel with T030-T033

### Within User Story 5
- T036-T038: Migration verifications can be parallel
- T039-T040: Config updates can be parallel

### Between User Stories
All 5 user stories can be implemented in parallel after Phase 2 completes.

---

## Implementation Strategy

### MVP First (User Story 1 only for MVP delivery)

1. Complete Phase 1: Setup
2. Complete Phase 2: Foundational (CRITICAL — blocks all stories)
3. Complete Phase 3: User Story 1 (8 models with relationships)
4. **STOP and VALIDATE**: Test User Story 1 independently
5. Deploy/demo if foundation is sufficient

### Incremental Delivery

1. Complete Setup + Foundational → Foundation ready
2. Add User Story 1 → Test independently → Deploy/Demo (MVP!)
3. Add User Story 2 → Test independently → Deploy/Demo
4. Add User Story 3 → Test independently → Deploy/Demo
5. Add User Story 4 → Test independently → Deploy/Demo
6. Add User Story 5 → Test independently → Deploy/Demo
7. Polish phase → Final validation

### Parallel Team Strategy

With multiple developers:

1. Team completes Setup + Foundational together
2. Once Foundational is done:
   - Developer A: User Story 1 (8 models)
   - Developer B: User Story 2 (repositories) + User Story 3 (BaseResource)
   - Developer C: User Story 4 (Exception Handler via ExceptionClassToMethod.php) + User Story 5 (Queue)
3. Stories complete and integrate independently

---

## Notes

- [P] tasks = different files, no dependencies
- [Story] label maps task to specific user story for traceability
- All monetary fields MUST use decimal(10,2) casting per Constitution
- User model hard immutability is non-negotiable per FR-009
- Repository is sole database gateway per Constitution Clean Architecture rule
- Queue must be ready before SP-04 (async exports)
- Exception handling MUST use config/ExceptionClassToMethod.php pattern (do NOT use withExceptions() in bootstrap/app.php)
- cursorPaginate() is mandatory per Constitution Section 4.3 (Cursor-based pagination)