# Phase 8 Execution Plan: Controller and API Cleanup

## 1. Purpose

Phase 8 cleans up the controller and API layer after the modular core has started taking shape.

The goal is to make controllers thin, predictable, secure, testable, and compatible with the modular platform architecture:

```text
Http Controllers
    ↓
FormRequests / Resources
    ↓
SchoolContext
    ↓
SchoolCore contracts
    ↓
IslamicSundaySchool extension contracts/policies where applicable
```

Controllers should not contain domain behavior. They are delivery adapters. They receive HTTP noise, validate it, authorize it, pass a DTO to an application/domain service, and return a response.

That is the whole job. Controllers trying to calculate balances, record attendance, resolve recipients, generate student IDs, or build reports are not “pragmatic.” They are tiny procedural empires squatting in the web layer.

---

## 2. Scope

Phase 8 applies to:

```text
API controllers
legacy compatibility controllers
FormRequests
API Resources
response envelopes
route definitions
authorization middleware/policies
OpenAPI/API documentation
controller tests
route inventory
legacy duplicate controller cleanup
```

This phase does not rewrite the domain modules. It forces controllers to use the contracts created in earlier phases.

Covered modules:

```text
SchoolContext
Core Contracts
Finance
Attendance
Students
Communication
Reporting
IslamicSundaySchool extension endpoints
```

---

## 3. Required Dependency Direction

Controllers may depend on:

```text
SchoolCore contracts
IslamicSundaySchool extension contracts, only for extension-specific routes
FormRequests
Resources
SchoolContext resolver/store
Authorization policies/gates
```

Controllers must not depend on:

```text
Eloquent models for domain mutation, except simple legacy adapters during migration
raw DB queries
service concrete classes when contract exists
Http\Request directly for validated domain data
auth() calls scattered inside methods
business rule helpers
private domain orchestration methods
provider SDKs
file system paths directly
```

Allowed:

```text
Controller -> Contract -> Service
Controller -> FormRequest -> DTO
Controller -> Resource
Controller -> Policy/Gate
```

Forbidden:

```text
Controller -> DB::table(...)
Controller -> Mail::send(...)
Controller -> WhatsAppProvider
Controller -> Invoice::update(balance)
Controller -> Student::max(id) + 1
Controller -> attendance mutation queries
Controller -> report SQL
```

Yes, controllers can technically do all of that. A shovel can technically be used as a dinner utensil too.

---

## 4. Controller Target Shape

Every controller action should follow this shape:

```php
public function store(CreateStudentRequest $request): StudentResource
{
    $context = $this->schoolContext->current();

    $result = $this->students->createStudent(
        $context,
        $request->toDTO()
    );

    return new StudentResource($result->student);
}
```

Allowed responsibilities:

```text
1. Accept FormRequest.
2. Resolve SchoolContext.
3. Authorize request/resource.
4. Build DTO.
5. Call contract.
6. Return Resource or standardized API response.
```

Forbidden responsibilities:

```text
- domain calculations
- multi-step business transactions
- direct file lookup
- direct provider calls
- duplicate validation logic
- raw request merging
- direct cross-module orchestration
- generating IDs
- applying role logic manually
```

---

## 5. API Response Standard

The project must choose one response envelope and enforce it.

Recommended envelope:

```json
{
  "success": true,
  "data": {},
  "message": null,
  "meta": {},
  "errors": null
}
```

For errors:

```json
{
  "success": false,
  "data": null,
  "message": "Validation failed.",
  "meta": {},
  "errors": {
    "field": ["Error message."]
  }
}
```

Rules:

```text
- Resources own response data shape.
- Controllers do not hand-build inconsistent arrays.
- Paginated responses include consistent pagination metadata.
- Error responses use centralized exception handling.
- Legacy response shapes may be preserved temporarily by adapters.
```

Compatibility warning:

```text
Do not break existing clients casually. If response shape changes, version the API or provide compatibility resources.
```

Breaking mobile/admin clients because the backend suddenly became “clean” is not modernization. It is vandalism with a linter.

---

## 6. API Versioning Strategy

Recommended versioning:

```text
/api/v1/...
/api/v2/...
```

Phase 8 should not force a full v2 unless breaking changes are unavoidable.

Migration strategy:

```text
v1 routes -> legacy-compatible resources/adapters
v2 routes -> modular standardized resources
```

Rules:

```text
- v1 may preserve old response envelope where required.
- v2 uses standardized envelope.
- New modular endpoints should be v2-ready.
- Deprecated routes must include removal target.
```

---

## 7. Route Inventory

Before cleanup, create a complete route inventory.

Inventory fields:

```text
HTTP method
URI
controller
action
middleware
auth requirement
permission/policy
request class
resource class
domain contract called
response envelope
legacy/canonical status
module
risk level
test coverage status
```

Suggested output:

```text
storage/app/api-route-inventory.json
docs/api-route-inventory.md
```

Each route must be categorized:

```text
canonical
adapter
deprecated
remove
unknown
```

No route should remain `unknown` after Phase 8. Unknown routes are abandoned doors into the app, and abandoned doors are how raccoons and data leaks get in.

---

## 8. Controller Classification

Every controller should be classified.

Categories:

```text
Canonical Controller
Adapter Controller
Deprecated Controller
Remove Candidate
Extension Controller
```

### 8.1 Canonical Controller

Definition:

```text
Current preferred controller for a module/route.
Uses FormRequests, Resources, SchoolContext, contracts, and policies.
```

### 8.2 Adapter Controller

Definition:

```text
Preserves old route/response behavior but delegates to modular contracts.
Contains no domain logic.
```

### 8.3 Deprecated Controller

Definition:

```text
Still reachable but scheduled for replacement/removal.
Must include deprecation comment and target replacement route.
```

### 8.4 Remove Candidate

Definition:

```text
Duplicate, unused, unsafe, or superseded controller.
No active route should point to it.
```

### 8.5 Extension Controller

Definition:

```text
Islamic Sunday School-specific controller.
May depend on IslamicSundaySchool contracts.
Must not be used by SchoolCore routes.
```

---

## 9. Duplicate Controller Cleanup

Known duplicate-ish controller patterns must be resolved.

Examples to review:

```text
BaseApiController variants
RolePermissionController variants
RoleSwitcherController variants
StatsController variants
UserController variants
Finance/payment controllers
Attendance/scanner controllers
Student controllers
Report controllers
Communication/broadcast controllers
```

Resolution process:

```text
1. Find all routes pointing to duplicate controllers.
2. Identify canonical route/controller.
3. Convert old controller to adapter if compatibility is needed.
4. Remove domain logic from adapter.
5. Mark deprecated route with replacement.
6. Add tests proving old and new route behavior.
7. Remove unused controller after deprecation window.
```

Rule:

```text
A shim may contain mapping code. It may not contain business logic.
```

---

## 10. FormRequest Standard

Every route that accepts input must use a FormRequest unless explicitly exempted.

Required methods:

```php
public function authorize(): bool;

public function rules(): array;

public function toDTO(): SomeData;
```

Optional:

```php
public function messages(): array;

protected function prepareForValidation(): void;
```

Rules:

```text
- validation lives in FormRequest
- authorization gate/policy check may begin in FormRequest
- controllers use validated data only
- no raw array merging in controllers
- no Validator::make inside controller except temporary documented adapter
```

Forbidden pattern:

```php
$data = array_merge($request->query->all(), $request->all(), $request->json()->all());
$validator = Validator::make($data, [...]);
```

That pattern is not flexibility. It is a custody battle between query params and JSON.

---

## 11. Resource Standard

Every response returning domain data should use a Resource or ResourceCollection.

Examples:

```text
StudentResource
GuardianResource
InvoiceResource
PaymentResource
AttendanceRecordResource
ScanResultResource
MessageResource
RecipientPreviewResource
ReportResultResource
IslamicSundaySchoolStudentProfileResource
QuranProgressReportResource
```

Rules:

```text
- Resources decide shape.
- Resources respect authorization/field visibility.
- Sensitive fields are hidden unless allowed.
- Extension fields appear only in extension resources or composed views.
- Controllers do not manually build nested response arrays.
```

Resource versioning:

```text
App\Http\Resources\V1\...
App\Http\Resources\V2\...
```

Use versioned resources if compatibility requires it.

---

## 12. Authorization Matrix

Every route needs explicit authorization.

Route authorization matrix fields:

```text
route
action
resource type
permission
policy/gate
ownership rule
school boundary rule
role allowance
negative tests
```

Minimum negative tests per mutation route:

```text
unauthenticated
wrong school
wrong role
wrong owner/scope
authorized actor
```

High-risk modules requiring immediate authorization review:

```text
finance
payment files
student profile
guardian contact data
attendance override
role/permission mutation
bulk communication
report export
Islamic Sunday School sensitive profile fields
imam/admin notes
scholarship/sadaqah indicators
```

“User is logged in” is not authorization. It is merely proof that someone found the door.

---

## 13. SchoolContext Enforcement

Every controller must resolve or receive `SchoolContext`.

Allowed patterns:

```text
middleware resolves context
controller receives context store
FormRequest validates context-bound inputs
services receive context explicitly
```

Required checks:

```text
school exists
actor belongs to school
academic year belongs to school
term/session belongs to school
resource belongs to school
extension route matches domain profile if applicable
```

Extension route example:

```text
/api/v2/islamic-sunday-school/quran-progress
```

Must verify:

```text
context.domain_profile == islamic_sunday_school
```

Or equivalent extension availability rule.

---

## 14. Module-Specific Controller Cleanup

## 14.1 Finance Controllers

Target contracts:

```text
InvoiceServiceContract
PaymentServiceContract
RefundServiceContract
FinanceFileServiceContract
ReportRunnerContract for finance reports
```

Controllers must not:

```text
calculate invoice balances
edit payments directly
serve files by filename
apply discounts directly
delete financial history silently
```

Required cleanup:

```text
- replace filename-based payment file download with payment-id route
- use PaymentServiceContract for record/edit/reverse
- use RefundServiceContract for refunds
- use FinanceFileServiceContract for downloads
- use Resources for invoices/payments
```

Required tests:

```text
wrong-school finance access fails
payment edit requires permission
payment file download is payment-scoped
finance export requires permission
```

---

## 14.2 Attendance and Scanner Controllers

Target contracts:

```text
ScannerServiceContract
StudentAttendanceServiceContract
StaffAttendanceServiceContract
AttendanceServiceContract
```

Controllers must not:

```text
lookup badges directly
determine late/present status
write attendance records
create scan logs directly
handle duplicate scan logic
```

Required cleanup:

```text
- ScannerController delegates to ScannerServiceContract
- manual override routes use FormRequests
- override reason required
- ScanResultResource standardizes response
```

Required tests:

```text
duplicate scan does not double-count
wrong-school badge fails
manual override requires permission and reason
scanner response remains compatible where needed
```

---

## 14.3 Student Lifecycle Controllers

Target contracts:

```text
StudentServiceContract
GuardianServiceContract
HouseholdServiceContract
EnrollmentServiceContract
AssignmentServiceContract
PromotionServiceContract
```

Controllers must not:

```text
generate student identifiers
link guardians directly
create enrollments directly
assign groups/classes directly
mutate status directly
promote students directly
```

Required cleanup:

```text
- student creation delegates to StudentServiceContract
- guardian linking delegates to GuardianServiceContract
- enrollment routes delegate to EnrollmentServiceContract
- promotion routes delegate to PromotionServiceContract
- Islamic profile routes use IslamicSundaySchool extension contract
```

Required tests:

```text
concurrent student creation safe
wrong-school guardian link fails
status transition invalid path fails
Islamic profile sensitive fields require permission
```

---

## 14.4 Communication Controllers

Target contracts:

```text
RecipientPreviewServiceContract
CommunicationServiceContract
MessageTemplateServiceContract
DeliveryStatusServiceContract
```

Controllers must not:

```text
loop recipients
call Mail directly
call SMS/WhatsApp providers directly
send bulk messages without preview
resolve audience queries directly
```

Required cleanup:

```text
- bulk send requires preview_id and confirmation_token
- recipient preview route added
- send route uses CommunicationServiceContract
- channel provider callbacks use DeliveryStatusServiceContract
```

Required tests:

```text
bulk send without preview fails
duplicate recipients are deduped
opt-outs are enforced
wrong-school recipients excluded
provider callbacks cannot mutate wrong-school message
```

---

## 14.5 Reporting Controllers

Target contracts:

```text
ReportRegistryContract
ReportRunnerContract
ReportExportServiceContract
ReportSnapshotServiceContract
ScheduledReportServiceContract
```

Controllers must not:

```text
build report SQL
export directly
bypass report authorization
show extension reports outside domain profile
```

Required cleanup:

```text
- report listing uses ReportRegistryContract
- run report uses ReportRunnerContract
- export uses ReportExportServiceContract
- snapshots use ReportSnapshotServiceContract
```

Required tests:

```text
wrong-school report access fails
view-only user cannot export
Islamic reports hidden outside islamic_sunday_school profile
sensitive columns filtered
```

---

## 14.6 Islamic Sunday School Extension Controllers

Allowed extension route examples:

```text
/api/v2/islamic-sunday-school/students/{student}/profile
/api/v2/islamic-sunday-school/quran-progress
/api/v2/islamic-sunday-school/arabic-levels
/api/v2/islamic-sunday-school/halaqa-attendance
/api/v2/islamic-sunday-school/masjid-family-summary
```

Rules:

```text
- extension routes depend on IslamicSundaySchool contracts
- extension routes require islamic_sunday_school domain profile or installed extension
- extension controllers may compose core resources and extension resources
- extension controllers must not mutate core tables directly
```

Forbidden:

```text
SchoolCore controllers importing IslamicSundaySchool classes
Core student resource always exposing Qur'an/Arabic/halaqa fields
Core attendance controller hardcoding halaqa/session behavior
```

---

## 15. Exception Handling

Centralize API exceptions.

Map exceptions:

```text
ValidationException -> 422
AuthenticationException -> 401
AuthorizationException -> 403
ModelNotFoundException / domain not found -> 404
DomainConflictException -> 409
IdempotencyConflictException -> 409
RateLimitException -> 429
Unhandled exception -> 500
```

Domain exceptions from prior phases:

```text
FinanceException
AttendanceException
StudentException
CommunicationException
ReportingException
UnauthorizedFinanceAccessException
UnauthorizedAttendanceAccessException
UnauthorizedStudentAccessException
UnauthorizedCommunicationAccessException
UnauthorizedReportAccessException
```

Rules:

```text
- exception messages must be safe for clients
- internal details logged server-side
- response envelope is consistent
- no stack traces in API output
```

---

## 16. OpenAPI Documentation

Phase 8 should produce or update OpenAPI docs.

Required for each endpoint:

```text
method
path
summary
tags
auth requirements
permissions
request schema
response schema
error responses
pagination metadata, if any
deprecation status
```

OpenAPI grouping:

```text
Auth
School Context
Students
Guardians
Enrollment
Attendance
Finance
Communication
Reporting
Islamic Sunday School
System/Admin
```

Rules:

```text
- docs generated from route inventory where possible
- deprecated endpoints marked
- v1/v2 differences documented
- sensitive fields documented by permission
```

---

## 17. Compatibility Strategy

Not all controllers should be broken at once. Apparently users dislike when APIs evaporate for architectural purity. Strange but documented.

Compatibility options:

```text
adapter controller
legacy resource
v1 route preservation
feature flag
deprecation header
API changelog
```

Deprecation headers:

```text
Deprecation: true
Sunset: 2027-01-01
Link: </api/v2/replacement-route>; rel="successor-version"
```

Each deprecated endpoint must document:

```text
replacement route
behavior differences
removal target
migration notes
```

---

## 18. Route Naming Standard

Use consistent route names.

Examples:

```text
api.v2.students.index
api.v2.students.store
api.v2.students.show
api.v2.students.update
api.v2.finance.payments.store
api.v2.finance.payments.update
api.v2.finance.payments.file
api.v2.attendance.scans.store
api.v2.communication.recipient-previews.store
api.v2.communication.bulk-sends.store
api.v2.reporting.reports.run
api.v2.islamic-sunday-school.quran-progress.index
```

Rules:

```text
- names are stable
- extension routes are clearly namespaced
- route names map to OpenAPI operation IDs
```

---

## 19. Middleware Standard

Recommended middleware layers:

```text
auth:sanctum or equivalent
resolve.school.context
ensure.school.membership
ensure.domain.profile, for extension routes
permission or policy middleware
request.id
rate.limit
audit.context
```

High-risk routes require stricter middleware:

```text
finance mutations
file downloads
bulk communication sends
report exports
role/permission mutations
sensitive Islamic Sunday School profile fields
```

---

## 20. Testing Strategy

### 20.1 Controller feature tests

Every canonical controller action must test:

```text
success path
validation failure
unauthenticated
unauthorized role
wrong school
wrong owner/scope
resource not found
standard response envelope
```

### 20.2 Adapter tests

Every adapter route must test:

```text
legacy route still works
response shape remains compatible
adapter delegates to contract
no domain logic in adapter
deprecation header if applicable
```

### 20.3 Architecture tests

Required assertions:

```text
controllers do not call DB directly for domain mutations
controllers do not call Mail/SMS/WhatsApp provider directly
controllers do not calculate invoice balance
controllers do not generate student identifiers
controllers do not write attendance records directly
controllers do not build report SQL
controllers use FormRequests for mutable endpoints
controllers return Resources or standardized response helpers
SchoolCore controllers do not import IslamicSundaySchool
extension controllers are under IslamicSundaySchool namespace or extension route group
```

---

## 21. Static Analysis Rules

Add static checks where practical:

```text
No DB::table in Http\Controllers
No Validator::make in canonical controllers
No Mail:: in Http\Controllers
No response()->download for payment files outside FinanceFileService
No max('id') identifier generation in controllers
No private methods over a set complexity threshold in controllers
No controller over a line-count threshold without review
```

Suggested thresholds:

```text
controller class max 250 lines
controller action max 40 lines
private methods in controllers discouraged
```

These are not moral laws. They are smoke alarms. When they go off, investigate before the kitchen is structural ash.

---

## 22. Migration Strategy

### 22.1 Recommended order

```text
1. Route inventory
2. Controller classification
3. Response envelope standard
4. Exception handler standard
5. FormRequest standard
6. Resource standard
7. Finance controller cleanup
8. Attendance/scanner controller cleanup
9. Student lifecycle controller cleanup
10. Communication controller cleanup
11. Reporting controller cleanup
12. Islamic Sunday School extension controller cleanup
13. OpenAPI docs
14. Static/architecture tests
15. Deprecation cleanup
```

Why this order:

```text
- inventory prevents blind refactor
- classification prevents duplicate chaos
- response/exception standards stabilize API contract
- high-risk module controllers are cleaned before cosmetic ones
- documentation follows actual route decisions
- architecture tests prevent regression
```

---

## 23. First Implementation Slice: Route Inventory

### Objective

Create a complete inventory of active API routes.

### Tasks

```text
API-001. Generate route list from framework.
API-002. Parse method, URI, controller, action, middleware.
API-003. Add manual fields: module, risk, canonical status.
API-004. Identify duplicate controller/action mappings.
API-005. Export inventory to JSON and Markdown.
```

### Required tests/checks

```text
- inventory generation succeeds in CI
- every route has controller/action
- every route has module classification
- every mutation route has auth middleware or documented exception
```

### Done when

```text
- route inventory exists
- unknown routes are visible
- duplicate routes/controllers are listed
```

---

## 24. Second Implementation Slice: Controller Classification

### Objective

Mark every controller as canonical, adapter, deprecated, remove, or extension.

### Tasks

```text
API-006. Create controller classification document.
API-007. Add docblocks or config map for classification.
API-008. Identify canonical controller per module.
API-009. Identify adapter/deprecated duplicates.
API-010. Create removal tickets for unused controllers.
```

### Required checks

```text
- every controller is classified
- every duplicate has canonical target
- no route points to remove candidate
```

### Done when

```text
- controller ownership is explicit
- duplicate cleanup has a queue
```

---

## 25. Third Implementation Slice: Response and Exception Standard

### Objective

Standardize API success/error responses.

### Tasks

```text
API-011. Create ApiResponse helper or base resource response.
API-012. Update exception handler mapping.
API-013. Add validation error envelope.
API-014. Add authorization error envelope.
API-015. Add not-found/conflict envelope.
API-016. Add response snapshot tests.
```

### Required tests

```text
- validation error returns 422 envelope
- unauthorized returns 403 envelope
- not found returns 404 envelope
- conflict returns 409 envelope
- success response uses standard shape
```

### Done when

```text
- new canonical endpoints use consistent envelope
- legacy exceptions are safely mapped
```

---

## 26. Fourth Implementation Slice: FormRequest and Resource Standard

### Objective

Force input/output boundaries.

### Tasks

```text
API-017. Create request/resource naming standard.
API-018. Add DTO conversion convention.
API-019. Replace manual validation in high-risk controllers.
API-020. Add Resources for high-risk module responses.
API-021. Add architecture tests requiring FormRequest for mutations.
```

### Required tests

```text
- mutable routes use FormRequest
- invalid input fails before service call
- resource hides sensitive fields without permission
```

### Done when

```text
- finance, attendance, student, communication, and reporting mutations use FormRequests
- responses use Resources or standard response helper
```

---

## 27. Fifth Implementation Slice: Finance Controller Cleanup

### Objective

Make finance controllers thin and safe.

### Tasks

```text
API-022. Replace payment file filename route with payment-id route.
API-023. Update payment record/edit routes to use PaymentServiceContract.
API-024. Update refund/reversal routes to use RefundServiceContract.
API-025. Add finance Resources.
API-026. Add finance controller feature tests.
```

### Required tests

```text
- payment file wrong-school access fails
- payment edit unauthorized fails
- payment file route uses payment ID
- controller does not calculate balance
```

### Done when

```text
- finance controllers delegate only
- unsafe payment file route is deprecated or removed
```

---

## 28. Sixth Implementation Slice: Attendance Controller Cleanup

### Objective

Make scanner and attendance controllers thin.

### Tasks

```text
API-027. Update ScannerController to use ScannerServiceContract.
API-028. Move badge lookup out of controller.
API-029. Move late/status logic out of controller.
API-030. Update manual override routes to require reason.
API-031. Add ScanResultResource and AttendanceRecordResource.
```

### Required tests

```text
- duplicate scan behavior preserved/fixed
- scanner controller has no domain private methods
- manual override requires reason
- wrong-school scan fails
```

### Done when

```text
- scanner is HTTP adapter only
- attendance mutation belongs to services
```

---

## 29. Seventh Implementation Slice: Student Controller Cleanup

### Objective

Make student lifecycle controllers delegate to services.

### Tasks

```text
API-032. Update StudentController create/update to use StudentServiceContract.
API-033. Remove identifier generation from controller.
API-034. Update guardian routes to use GuardianServiceContract.
API-035. Update enrollment/assignment routes to use contracts.
API-036. Update promotion routes to use PromotionServiceContract.
API-037. Add student/guardian/enrollment Resources.
```

### Required tests

```text
- no controller path uses max(id) + 1
- student creation delegates to service
- wrong-school guardian link fails
- promotion unauthorized fails
```

### Done when

```text
- student lifecycle is no longer controller-orchestrated
```

---

## 30. Eighth Implementation Slice: Communication Controller Cleanup

### Objective

Make communication controllers safe and preview-driven.

### Tasks

```text
API-038. Add recipient preview endpoint.
API-039. Update bulk send endpoint to require preview_id.
API-040. Remove direct send loops from controllers.
API-041. Move Mail/SMS/WhatsApp calls behind channels.
API-042. Add communication Resources.
```

### Required tests

```text
- bulk send without preview fails
- controller does not call Mail directly
- wrong-school recipients excluded
- opt-outs enforced
```

### Done when

```text
- communication controllers cannot fire blind bulk sends
```

---

## 31. Ninth Implementation Slice: Reporting Controller Cleanup

### Objective

Make reporting controllers consume reporting contracts.

### Tasks

```text
API-043. Add report list endpoint via ReportRegistryContract.
API-044. Add run report endpoint via ReportRunnerContract.
API-045. Add export endpoint via ReportExportServiceContract.
API-046. Add snapshot endpoint via ReportSnapshotServiceContract.
API-047. Add scheduled report endpoints through ScheduledReportServiceContract.
```

### Required tests

```text
- view-only user cannot export
- Islamic reports hidden outside islamic_sunday_school profile
- export audit is written
- report controller does not build SQL
```

### Done when

```text
- reporting controllers delegate only
```

---

## 32. Tenth Implementation Slice: Islamic Sunday School Extension Routes

### Objective

Make extension endpoints explicit and isolated.

### Tasks

```text
API-048. Create Islamic Sunday School route group.
API-049. Add ensure.domain.profile middleware.
API-050. Add extension FormRequests/Resources.
API-051. Move Qur'an/Arabic/halaqa/masjid-family endpoints under extension namespace.
API-052. Add extension route tests.
```

### Required tests

```text
- extension route fails for non-islamic_sunday_school profile
- Qur'an profile fields require permission
- halaqa attendance uses extension controller/resource
- SchoolCore controllers do not import IslamicSundaySchool
```

### Done when

```text
- Islamic Sunday School endpoints are explicitly extension-owned
```

---

## 33. Eleventh Implementation Slice: OpenAPI and Deprecation

### Objective

Document the cleaned API and migration path.

### Tasks

```text
API-053. Generate OpenAPI baseline.
API-054. Add operation IDs from route names.
API-055. Mark deprecated endpoints.
API-056. Add successor route links.
API-057. Create API changelog.
API-058. Add docs test to ensure route docs coverage.
```

### Required checks

```text
- every canonical route appears in OpenAPI
- every deprecated route has replacement
- high-risk routes document permissions
```

### Done when

```text
- API consumers can migrate without guessing
```

---

## 34. Twelfth Implementation Slice: Architecture Enforcement

### Objective

Prevent controller bloat from returning.

### Tasks

```text
API-059. Add controller architecture tests.
API-060. Add static analysis rules.
API-061. Add CI route inventory diff.
API-062. Add CI check for undocumented routes.
API-063. Add controller complexity/line threshold warnings.
```

### Required checks

```text
- controller DB mutation rule enforced
- no provider SDK calls in controllers
- no SchoolCore -> IslamicSundaySchool imports
- mutation routes use FormRequests
- canonical routes use Resources/standard responses
```

### Done when

```text
- bad controller patterns fail CI or produce review blockers
```

---

## 35. Database and Schema Requirements

Phase 8 should avoid schema changes unless required for API support.

Possible supporting tables:

```text
api_route_inventory_snapshots
api_deprecation_notices
api_client_usage_logs, optional
```

More likely, store documentation artifacts in:

```text
docs/
storage/app/generated/
```

Do not create database tables just to feel productive. Databases are not filing cabinets for indecision.

---

## 36. Implementation Tickets

## API-001: Generate route inventory

### Description

Generate complete API route inventory with controller/action/middleware/module classification.

### Acceptance Criteria

```text
- Inventory exists in JSON and Markdown.
- Every route has method, URI, controller, action, middleware.
- Mutation routes missing auth are flagged.
- Duplicate controller usage is listed.
```

---

## API-002: Classify controllers

### Description

Mark each controller as canonical, adapter, deprecated, remove, or extension.

### Acceptance Criteria

```text
- Every controller is classified.
- Every duplicate has canonical target.
- No active route points to remove candidate.
```

---

## API-003: Standardize API responses and exceptions

### Description

Create response envelope and exception mapping.

### Acceptance Criteria

```text
- Success, validation, auth, not-found, and conflict responses are standardized.
- Legacy compatibility exceptions documented.
- Snapshot tests exist.
```

---

## API-004: Enforce FormRequest and Resource standard

### Description

Require FormRequests and Resources for canonical endpoints.

### Acceptance Criteria

```text
- Mutable canonical endpoints use FormRequests.
- Domain data responses use Resources.
- Sensitive fields hidden unless authorized.
```

---

## API-005: Clean finance controllers

### Description

Move finance controllers to contract delegation and remove unsafe file/balance behavior.

### Acceptance Criteria

```text
- Payment file route uses payment ID.
- Payment mutations use finance contracts.
- Controllers do not calculate balances.
- Finance authorization tests pass.
```

---

## API-006: Clean attendance/scanner controllers

### Description

Move scanner and attendance controllers to contract delegation.

### Acceptance Criteria

```text
- ScannerController delegates to ScannerServiceContract.
- Badge lookup/status/idempotency outside controller.
- Manual override requires reason.
```

---

## API-007: Clean student lifecycle controllers

### Description

Move student, guardian, enrollment, assignment, and promotion controllers to contracts.

### Acceptance Criteria

```text
- No controller generates student identifiers.
- Student creation delegates to StudentServiceContract.
- Guardian/enrollment/promotion routes use contracts.
```

---

## API-008: Clean communication controllers

### Description

Move communication controllers to preview-driven communication contracts.

### Acceptance Criteria

```text
- Bulk send requires preview_id.
- Controllers do not call Mail/SMS/WhatsApp providers.
- Recipient dedupe/preferences enforced.
```

---

## API-009: Clean reporting controllers

### Description

Move reporting controllers to report contracts.

### Acceptance Criteria

```text
- Report list uses registry.
- Report run uses runner.
- Export uses export service.
- No report SQL in controller.
```

---

## API-010: Add Islamic Sunday School extension routes

### Description

Create explicit extension route group and controllers.

### Acceptance Criteria

```text
- Extension routes require islamic_sunday_school profile.
- Extension controllers use IslamicSundaySchool contracts.
- SchoolCore controllers do not import extension classes.
```

---

## API-011: Generate OpenAPI documentation

### Description

Generate or update OpenAPI docs from cleaned route inventory.

### Acceptance Criteria

```text
- Canonical routes documented.
- Deprecated routes marked.
- Permissions documented.
- Request/response schemas documented.
```

---

## API-012: Add controller architecture tests

### Description

Enforce controller boundary rules in CI.

### Acceptance Criteria

```text
- Controllers cannot perform domain DB mutations.
- Controllers cannot call provider SDKs.
- Mutation routes require FormRequests.
- Canonical routes use Resources/standard response.
- CI fails on boundary violation.
```

---

## 37. Definition of Done for Phase 8

Phase 8 is done when:

```text
- Complete route inventory exists.
- Every controller is classified.
- Duplicate controllers have canonical targets or removal tickets.
- API response envelope is standardized for canonical endpoints.
- Exception handling is centralized.
- Mutable canonical endpoints use FormRequests.
- Domain data responses use Resources.
- Finance controllers delegate to finance contracts.
- Scanner/attendance controllers delegate to attendance contracts.
- Student lifecycle controllers delegate to student contracts.
- Communication controllers require preview for bulk sends.
- Reporting controllers delegate to reporting contracts.
- Islamic Sunday School extension routes are explicit and profile-gated.
- OpenAPI docs cover canonical routes.
- Deprecated routes have replacement paths and removal targets.
- Controller architecture tests exist.
- Legacy controller methods are labeled canonical, adapter, deprecated, or remove.
```

---

## 38. Non-Goals

Do not include in Phase 8:

```text
- full frontend migration
- complete API v2 rewrite unless required
- new business features
- new reporting calculations
- payment gateway implementation
- scanner hardware integration
- full permissions redesign
- public developer portal
```

Phase 8 is about making the HTTP layer boring. Boring APIs are underrated. Exciting APIs usually mean someone is debugging production at night.

---

## 39. Main Risks

### Risk: breaking existing clients

Mitigation:

```text
- v1 adapters
- response snapshot tests
- deprecation headers
- OpenAPI changelog
```

### Risk: controller logic moves sideways, not downward

Mitigation:

```text
- architecture tests
- contract delegation checks
- controller size thresholds
```

### Risk: duplicate controllers remain active

Mitigation:

```text
- route inventory
- controller classification
- canonical target mapping
```

### Risk: authorization gaps

Mitigation:

```text
- route authorization matrix
- negative tests
- school context middleware
```

### Risk: Islamic Sunday School concepts leak into core routes

Mitigation:

```text
- extension route group
- domain profile middleware
- import boundary tests
```

### Risk: documentation lies

Mitigation:

```text
- docs generated from route inventory
- docs coverage check
- deprecated route metadata
```

---

## 40. Immediate Next Work Queue

Start here:

```text
1. API-001 Generate route inventory
2. API-002 Classify controllers
3. API-003 Standardize API responses and exceptions
4. API-004 Enforce FormRequest and Resource standard
5. API-005 Clean finance controllers
6. API-006 Clean attendance/scanner controllers
7. API-007 Clean student lifecycle controllers
8. API-008 Clean communication controllers
9. API-009 Clean reporting controllers
10. API-010 Add Islamic Sunday School extension routes
11. API-011 Generate OpenAPI documentation
12. API-012 Add controller architecture tests
```

Do not begin by renaming files into prettier folders. Start with the route inventory. The routes are the actual public contract. Everything else is backstage clutter wearing a namespace.
