# ECOLE ECOIN Refactoring Roadmap

Date: 2026-05-21

Goal: sequence improvements after the architecture audit without breaking live platform behavior.

## Roadmap Principles

- No rewrite.
- Security and money safety first.
- Refactor by bounded workflow slices.
- Keep tests green before moving the next workflow.
- New features follow `docs/architecture_standards.md` immediately even before older code is migrated.

## Priority 1: Security, Permissions, Files, IDOR

| File or area | Problem | Risk | Recommended fix | Estimated impact | Tests needed |
| --- | --- | --- | --- | --- | --- |
| `routes/web.php` admin route groups | Multiple protection styles; some routes use only `auth` or `EnsureUserIsAdmin` while others declare `can:*`. | Permission regression during new admin features. | Standardize explicit permission/policy middleware for sensitive admin pages and document rare exceptions. | Medium. Route edits and targeted RBAC tests. | Admin route permission tests, support/admin/super-admin matrix. |
| `routes/instructor.php`, `app/Livewire/Teacher`, `app/Livewire/Instructor` | Teacher and instructor surfaces coexist with duplicate route prefixes. | Divergent authorization and duplicate fixes. | Choose canonical teacher console namespace; keep redirects/compatibility aliases until migration completes. | Medium. | Teacher route smoke tests and unassigned cohort/session IDOR tests. |
| Org Livewire pages and Org queries | Some pages rely mostly on portal/tenancy middleware and do not show page-level authorization calls. | Tenant and action review remains implicit. | Add page/action authorization inventory and query objects for org-scoped lists. | Medium. | Org member cross-organization IDOR tests. |
| Sensitive download flows | New Corporate flows are strong; older UI paths include direct download patterns to review. | Public or under-audited file delivery. | Inventory all downloads, move sensitive new/legacy downloads behind controllers plus policies. | Medium. | File privacy tests and foreign-ID download tests. |
| `app/Support/Rbac/PermissionCatalog.php` | Large catalog grows with every module. | Permission naming drift and accidental omission. | Keep catalog but split grouping/reporting checks or add generated validation per domain. | Medium. | Permission catalog parity tests and route permission checks. |

## Priority 2: Move Workflow Logic Out Of Livewire

| File or area | Problem | Risk | Recommended fix | Estimated impact | Tests needed |
| --- | --- | --- | --- | --- | --- |
| `app/Livewire/Admin/B2B/B2BLeadDetailPage.php` | Lead conversion transaction lives in UI. | Future API/automation duplicates conversion rules. | Extract `ConvertB2bLeadToOrganizationAction`. | Low-medium. | Lead conversion feature/unit tests, duplicate match tests, audit test. |
| `app/Livewire/Admin/WhatsApp/ConversationPage.php` | Reply provider fallback and B2B creation live in UI. | Provider logic divergence and incomplete audit/idempotency. | Extract send reply and create-B2B Actions; keep Livewire validation/UI only. | Medium. | Hybrid outbox fallback tests, conversation event/audit tests. |
| `app/Livewire/Admin/Cohorts/AdminCohortSessionsPage.php` | Manual session create/edit/cancel/reopen workflow lives in component. | Scheduling conflict rules diverge from generator and future API. | Extract manual session Actions and conflict Query/validator. | High. | Scheduling overlap, room conflict, attendance lock, earnings-trigger regression tests. |
| `app/Livewire/Admin/Registrations/AdminRegistrationCreatePage.php` | Large registration creation surface. | Public/admin/WhatsApp registration paths diverge. | Split into command DTO plus admin registration Action and read Queries. | High. | Admin registration lifecycle and deposit-policy tests. |
| `app/Livewire/Student/Payments.php` | Payment submission and receipt behavior exist in UI. | Payment workflow forks from finance rules. | Route through payment submission Action and controller downloads. | Medium. | Student payment submission/file tests. |

## Priority 3: Consolidate Duplicate Services And Names

| File or area | Problem | Risk | Recommended fix | Estimated impact | Tests needed |
| --- | --- | --- | --- | --- | --- |
| `app/Services/InstructorConflictDetector.php`, `app/Services/TeacherConflictDetector.php` | Two overlap/conflict services with different interfaces. | Schedule availability bugs and naming drift. | Define one Scheduling availability/conflict service; migrate callers gradually. | Medium. | Conflict matrix tests. |
| `app/Application`, `app/Domain`, `app/Services`, `app/UseCases` | Multiple business-layer homes. | New work lands arbitrarily. | New work uses `app/Domain/{Module}`; migrate existing global services only when touched. | Cross-cutting. | Domain boundary tests. |
| Finance UI namespaces | `Finance`, `Admin/Finance`, `FinanceReports` split. | Permission and report ownership confusion. | Document canonical finance UI entry points and make compatibility redirects explicit. | Medium. | Finance route/access smoke tests. |
| `Session`, `Cohort`, `AttendanceSession` vocabulary | Core domain terms overlap. | Incorrect table/model assumptions. | Publish glossary and rename only with migration plan. | High if renamed; low for docs. | Model/relation regression tests. |

## Priority 4: Event And Automation Readiness

| Area | Problem | Risk | Recommended fix | Estimated impact | Tests needed |
| --- | --- | --- | --- | --- | --- |
| Enrollment lifecycle | Not every major transition is a formal event. | CRM/automation hooks attach to UI instead of facts. | Emit `EnrollmentCreated`, `DepositPaid`, and attendance lifecycle events after commit. | Medium. | Event dispatch and listener idempotency tests. |
| Corporate workflow | Proposal/agreement/invoice facts are mostly service/activity driven. | Marketing/operations automation couples to Corporate UI. | Add domain events for accepted proposal, activated agreement, issued invoice, allocated payment. | Medium. | Workflow event tests. |
| WhatsApp lead lifecycle | Journey service exists but broader automation contracts need stable events. | AI/CRM work duplicates WhatsApp internals. | Add `WhatsAppLeadCreated` and conversation stage events with safe payloads. | Medium. | Payload privacy and queue idempotency tests. |
| Jobs/listeners layout | Root and domain-specific job folders coexist. | Ownership unclear. | Place new jobs/listeners under module ownership and document provider retry/idempotency. | Low-medium. | Queue retry/idempotency tests. |

## Priority 5: UI, i18n, Documentation Cleanup

| Area | Problem | Risk | Recommended fix | Estimated impact | Tests needed |
| --- | --- | --- | --- | --- | --- |
| `docs/i18n_coverage_report.md` hotspots | 678 potential hardcoded strings remain. | AR/FR experience drift. | Triage production/admin/PDF strings by user impact. | Medium. | i18n raw-key and view smoke tests. |
| Admin/portal UI conventions | Layouts and sidebars have improved but page patterns vary. | Inconsistent UX. | Standardize cards, actions, badges, empty states, and responsive tables by design system. | Medium. | UI smoke and no-horizontal-scroll checks where available. |
| Documentation ownership | Many phase docs exist; standards were implicit. | Future feature work ignores prior decisions. | Require docs update for module boundary, security, events, and operational workflow changes. | Low. | Review checklist rather than runtime tests. |

## Proposed Refactor Order

1. Add architecture/security checks before touching large workflows.
2. Normalize route permission inventory for admin, org, teacher, files.
3. Extract B2B conversion Action as the smallest high-value workflow example.
4. Extract WhatsApp reply/send flow and B2B lead creation Actions.
5. Extract manual cohort session create/edit/cancel workflow.
6. Revisit registration creation and student payment submission.
7. Introduce lifecycle domain events for automation.

## Automated Guardrails To Add

Recommended command:

```bash
php artisan app:architecture-check
```

Recommended checks:

- Reject forbidden legacy references in new app/runtime code:
  - `companies`
  - `users.company_id`
  - `agreement_path`
- Inventory admin routes missing explicit permission/policy middleware.
- Inventory sensitive download routes not using controller plus policy.
- Inventory Livewire components with write patterns but no authorization markers.
- Inventory raw translation-key output and hardcoded high-risk UI strings.

Recommended tests:

- `tests/Feature/Architecture/ArchitectureTest.php`
- `tests/Feature/Architecture/SecurityRouteTest.php`
- `tests/Feature/Architecture/DomainBoundaryTest.php`

These guardrails are proposed here rather than implemented in this audit-only phase.
