# Domain Boundaries Phase 2 Implementation Plan

> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.

**Goal:** Enforce the first modular-monolith boundary slice by extracting high-risk Livewire workflows into Actions, adding public contracts/data/events, and introducing architecture checks with strict high-risk rules plus legacy reporting.

**Architecture:** Keep Laravel models and existing routes intact while moving write ownership out of touched UI workflows into `app/Domain/*/Actions`. Use DTOs for validated command data, events as stable after-commit-ready facts, and an Artisan architecture-check command that distinguishes blocking violations from report-only findings.

**Tech Stack:** Laravel 12, Livewire 3, Eloquent, PHPUnit, Artisan commands, PostgreSQL/MySQL-compatible Eloquent code with sqlite test runs.

---

## File Map

Create:

- `app/Console/Commands/ArchitectureCheckCommand.php`
- `app/Domain/Common/Contracts/*.php`
- `app/Domain/Common/Data/*.php`
- `app/Domain/Corporate/B2B/Actions/ConvertB2bLeadToOrganizationAction.php`
- `app/Domain/WhatsApp/Actions/CreateB2bLeadFromConversationAction.php`
- `app/Domain/WhatsApp/Actions/SendWhatsAppReplyAction.php`
- `app/Domain/Scheduling/Actions/{Create,Update,Cancel,Reopen}AttendanceSessionAction.php`
- `app/Domain/*/Events/*.php` for the Phase 2 event contracts
- `app/Domain/*/Queries/*.php` for the requested initial Query surface
- `config/architecture-check.php`
- `tests/Feature/Architecture/DomainBoundaryTest.php`
- `tests/Feature/Architecture/WorkflowActionTest.php`
- `docs/domain_boundaries.md`

Modify:

- `app/Livewire/Admin/B2B/B2BLeadDetailPage.php`
- `app/Livewire/Admin/WhatsApp/ConversationPage.php`
- `app/Livewire/Admin/Cohorts/AdminCohortSessionsPage.php`
- `routes/console.php` only if command registration is needed by repository conventions

## Task 1: Lock Boundary Expectations With Tests

**Files:**
- Create: `tests/Feature/Architecture/DomainBoundaryTest.php`
- Create: `tests/Feature/Architecture/WorkflowActionTest.php`

- [ ] **Step 1: Write failing boundary tests**

Cover existence of Common contracts, required Actions, event classes, forbidden runtime legacy strings, and architecture command registration.

- [ ] **Step 2: Run red boundary tests**

Run:

```powershell
$env:DB_CONNECTION='sqlite'; $env:DB_DATABASE=':memory:'; php artisan test tests\Feature\Architecture\DomainBoundaryTest.php --stop-on-failure
```

Expected: fail because contracts/actions/command do not exist yet.

- [ ] **Step 3: Write failing workflow tests**

Cover:

- `ConvertB2bLeadToOrganizationAction` converts lead and creates or links organization.
- `CreateB2bLeadFromConversationAction` links contact/conversation to the B2B lead.
- `SendWhatsAppReplyAction` creates outbound message and outbox path for outbox mode.
- Manual attendance create/cancel/reopen action lifecycle.

- [ ] **Step 4: Run red workflow tests**

Run:

```powershell
$env:DB_CONNECTION='sqlite'; $env:DB_DATABASE=':memory:'; php artisan test tests\Feature\Architecture\WorkflowActionTest.php --stop-on-failure
```

Expected: fail because Actions/data classes do not exist yet.

## Task 2: Add Common Contracts, DTOs, And Event Contracts

**Files:**
- Create: `app/Domain/Common/Contracts/CreatesEnrollments.php`
- Create: `app/Domain/Common/Contracts/SendsMessages.php`
- Create: `app/Domain/Common/Contracts/AllocatesPayments.php`
- Create: `app/Domain/Common/Contracts/GeneratesSchedules.php`
- Create: `app/Domain/Common/Contracts/DispatchesTrackingEvents.php`
- Create: `app/Domain/Common/Data/*.php`
- Create: requested event classes under module folders

- [ ] **Step 1: Add minimal contracts**

Keep signatures capability-oriented and do not bind them to Livewire state arrays.

- [ ] **Step 2: Add command DTOs**

Create immutable constructors/factories for conversion, WhatsApp reply/B2B creation, and attendance session writes.

- [ ] **Step 3: Add safe event classes**

Events store model IDs and safe scalars only, with after-commit-friendly dispatch usage in touched Actions.

- [ ] **Step 4: Run boundary tests**

Expected: class existence checks move green while workflow behavior remains red until Actions exist.

## Task 3: Extract Corporate Lead Conversion

**Files:**
- Create: `app/Domain/Corporate/B2B/Actions/ConvertB2bLeadToOrganizationAction.php`
- Modify: `app/Livewire/Admin/B2B/B2BLeadDetailPage.php`

- [ ] **Step 1: Move conversion transaction into Action**

The Action must match/create Organization, update lead, record lead activity, write Org audit, and emit `B2bLeadConverted` after success.

- [ ] **Step 2: Keep Livewire UI state in component**

The component remains responsible for authorization, duplicate confirmation state, and refresh/flash behavior.

- [ ] **Step 3: Run conversion workflow test**

Run the focused test filter for B2B conversion.

## Task 4: Extract WhatsApp Conversation Mutations

**Files:**
- Create: `app/Domain/WhatsApp/Actions/CreateB2bLeadFromConversationAction.php`
- Create: `app/Domain/WhatsApp/Actions/SendWhatsAppReplyAction.php`
- Modify: `app/Livewire/Admin/WhatsApp/ConversationPage.php`

- [ ] **Step 1: Move B2B lead creation/linkage into Action**

Use a DTO carrying conversation and optional source metadata.

- [ ] **Step 2: Move outbound reply provider/outbox workflow into Action**

Action writes message row, handles provider result/fallback, and updates contact/conversation timestamps.

- [ ] **Step 3: Keep permission checks in Livewire**

Gate checks remain near the UI action methods.

- [ ] **Step 4: Run WhatsApp focused workflow tests**

Verify lead link and outbox reply tests pass.

## Task 5: Extract Manual Attendance Session Lifecycle

**Files:**
- Create: `app/Domain/Scheduling/Actions/CreateAttendanceSessionAction.php`
- Create: `app/Domain/Scheduling/Actions/UpdateAttendanceSessionAction.php`
- Create: `app/Domain/Scheduling/Actions/CancelAttendanceSessionAction.php`
- Create: `app/Domain/Scheduling/Actions/ReopenAttendanceSessionAction.php`
- Modify: `app/Livewire/Admin/Cohorts/AdminCohortSessionsPage.php`

- [ ] **Step 1: Create attendance session write DTO**

Carry persisted attendance session values only.

- [ ] **Step 2: Move create/update persistence and audit writes**

Leave current UI validation/conflict preparation in the component for this slice, then pass final command data to Actions.

- [ ] **Step 3: Move cancel and reopen status transitions**

Action owns transaction and audit behavior.

- [ ] **Step 4: Dispatch `AttendanceSessionCreated` from create Action**

Payload contains session/cohort/actor IDs only.

- [ ] **Step 5: Run scheduling lifecycle focused tests**

Verify create/cancel/reopen Action behavior.

## Task 6: Add Initial Query Surface

**Files:**
- Create query classes requested by Phase 2.
- Modify touched Livewire callers only when query extraction is direct and low-risk.

- [ ] **Step 1: Create Query classes**

Add:

- `OrganizationInvoicesQuery`
- `InstructorScheduleQuery`
- `EnrollmentPaymentsQuery`
- `CorporateReceivablesQuery`
- `WhatsAppConversationListQuery`

- [ ] **Step 2: Keep methods small and scoped**

Each query exposes a reusable builder or page method with clear caller input.

- [ ] **Step 3: Move touched inbox/list reads where safe**

Do not rewrite unrelated dashboards in this phase.

## Task 7: Add Architecture Check Command And Baseline

**Files:**
- Create: `app/Console/Commands/ArchitectureCheckCommand.php`
- Create: `config/architecture-check.php`

- [ ] **Step 1: Add config for scan roots, allow lists, and report patterns**

Allow legacy migration/docs paths while keeping runtime app paths strict.

- [ ] **Step 2: Implement grouped check output**

Output strict errors and warnings for:

- legacy forbidden strings.
- WhatsApp direct Enrollment/Payment create/update writes.
- write-heavy Livewire authorization inventory.
- admin route permission inventory.
- sensitive download route inventory.
- hardcoded admin/corporate navigation URLs.

- [ ] **Step 3: Return non-zero only on strict errors**

Warnings remain visible in report mode.

- [ ] **Step 4: Run command directly**

Run:

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

Expected: exit success when only configured warnings remain.

## Task 8: Document Domain Boundaries

**Files:**
- Create: `docs/domain_boundaries.md`

- [ ] **Step 1: Write ownership matrix**

Use the approved module ownership from the user requirement.

- [ ] **Step 2: Document allowed/forbidden dependencies**

Include Actions, Queries, DTOs, transactions, events, listener rules, and architecture-check baseline behavior.

- [ ] **Step 3: Verify docs have no placeholders**

Search for placeholder markers before final closeout.

## Task 9: Verification

- [ ] **Step 1: Run new architecture tests**

```powershell
$env:DB_CONNECTION='sqlite'; $env:DB_DATABASE=':memory:'; php artisan test tests\Feature\Architecture\DomainBoundaryTest.php tests\Feature\Architecture\WorkflowActionTest.php --stop-on-failure
```

- [ ] **Step 2: Run touched feature suites**

Run focused B2B, WhatsApp, and Cohort sessions feature tests that cover the touched Livewire surfaces.

- [ ] **Step 3: Run architecture command**

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

- [ ] **Step 4: Run view compilation only if touched Blade changes occur**

No Blade changes are required by default.
