# Admin V2 - Master Implementation Plan

## Overview

This plan defines the migration strategy from the current Filament admin (current state = **V1**) to a new operational admin experience (**V2**) focused on day-to-day execution in each place:
- operational daily dashboard (planning, bookings, access, orders)
- cardex-style views for users/families/coaches/employees
- unified order workstation (multi-orderable in one invoice)
- integrated payment actions (wallet, Stripe, crypto, POS/cash where relevant)
- central switchers for active place context and place-level configuration access

The key constraint is that the project currently runs on **Filament v2** (single panel architecture), so V2 must be delivered incrementally without breaking production operations.

This plan includes stakeholder decisions validated on **2026-03-26**.

---

## Product Scope Summary

| Area | Scope |
|---|---|
| **V1 to V2 split** | Move existing Filament code to `app/Filament/V1/*` and initialize `app/Filament/V2/*` |
| **Main dashboard** | Daily planning by place/date (including future), bookings of the day, operational KPIs/charts |
| **Cardex - User** | Identity, bookings history, orders history, access logs, finance snapshot, quick actions |
| **Cardex - Family** | Family members aggregate, shared wallet/finance history, grouped bookings/orders |
| **Cardex - Coach** | Availability management, upcoming bookings, bookings history, revenue/utilization metrics |
| **Cardex - Employee** | Profile, permissions/roles, activity and operational actions |
| **Order workstation** | Add any orderable type in one cart/invoice, then recap + payment options |
| **Payment options** | Stripe and NowPayments link/QR generation + send flow (plus existing wallet/cash/POS where available) |
| **Admin catalogs** | Manage services/products/courses/departments and other commercial entities |
| **Context switchers** | Navbar switch to change active place + place information settings (common/global switch deferred) |

---

## Architecture Decisions

### 1. Filament V2 migration strategy (safe and reversible)

1. Current admin codebase becomes **V1 namespace**:
- `App\Filament\V1\Resources\...`
- `App\Filament\V1\Pages\...`
- `App\Filament\V1\Widgets\...`
- `App\Filament\V1\Components\...`
- `App\Filament\V1\Concerns\...`

2. New admin code starts in **V2 namespace**:
- `App\Filament\V2\Pages\...`
- `App\Filament\V2\Resources\...`
- `App\Filament\V2\Widgets\...`

3. `config/filament.php` discovery points to V1 first for stability.

4. V2 is introduced progressively through explicit registrations (`register` arrays) and route slugs prefixed by `v2/*` to avoid route name/path conflicts.

5. Cutover to V2 can happen feature-by-feature, not as one big-bang release.

### 1.b Access and URL rollout

- V2 is exposed under `/admin/v2/*` during transition.
- V1 remains on `/admin/*` routes until final cutover.
- Initial V2 access is restricted to `super_admin` and `manager`.

### 2. Shared business layer, separate UI composition

V2 must reuse existing domain logic rather than re-implementing it:
- `UpsertOrderAction`, payment actions, invoice generation, booking/services actions
- existing models and relationships (`Order`, `OrderItem`, `Booking`, `PlaceAccessLog`, etc.)

A new `AdminV2` application layer will orchestrate read models and view models for UX screens:
- `app/Actions/AdminV2/*`
- `app/Data/AdminV2/*`

### 3. Context-driven navigation

V2 navigation will be context-first:
- Active place selector (session-backed)
- Place information settings entrypoint for current place
- Context-aware menus and page filters

Common/global switch is explicitly deferred to a later phase.

### 4. Cardex as a first-class pattern

Each entity cardex page uses the same structural pattern:
- Left: identity + key KPIs + quick actions
- Right: tabbed timeline (`Bookings`, `Orders`, `Finance`, `Access`, `Notes`, `Documents`)
- Shared widgets/components to avoid duplication

### 5. Unified order workstation

Single UI flow for employee/admin order creation:
1. choose customer
2. add one or many orderables (products, courses, services, events, manual invoice item, etc.)
3. optional department attribution per line item
4. recap and totals
5. choose payment channel
6. send payment link or process payment directly
7. invoice generation/send

Mixed pricing/tax lines are supported in one invoice (taxable and tax-exempt together).

### 6. UX and performance constraints

- Filters and date pickers must be place-timezone aware for display.
- Dashboard and cardex timelines require optimized queries and pagination.
- Heavy KPI blocks should support short caching windows.

---

## Domain Boundaries For V2

| Module | Responsibilities | Reuses Existing |
|---|---|---|
| `V2\Dashboard` | Daily cockpit, charts, occupancy/load indicators | Schedule/booking/order/access actions |
| `V2\Cardex\User` | Customer profile and complete history | Customer + Booking + Order + Wallet domains |
| `V2\Cardex\Family` | Grouped family operations and finance | Family + Wallet + Orders |
| `V2\Cardex\Coach` | Availability + bookings + utilization | Coach + Booking + schedule logic |
| `V2\Cardex\Employee` | Staff profile and role-specific operations | Employee + activity logs |
| `V2\OrderDesk` | Multi-orderable invoice composition + payment options | UpsertOrder + payment/invoice services |
| `V2\CatalogAdmin` | Commercial primitives management | Existing resources/entities |

---

## Development Phases

| Phase | Name | Scope |
|---|---|---|
| **1** | V1/V2 Namespace Migration Foundation | Move current Filament code to `V1`, initialize `V2`, keep production stable |
| **2** | V2 Shell and Navigation | New layout shell, context switchers, V2 entrypoint pages |
| **3** | Dashboard Day Cockpit | Daily planning, bookings today, key charts, date switching |
| **4** | Cardex Core Components | Shared cardex layout, reusable timeline/KPI/action blocks |
| **5** | User & Family Cardex | Full profile and financial/booking/order views for users and families |
| **6** | Coach & Employee Cardex | Coach availability/bookings/history + employee operational views |
| **7** | Order Workstation | Add any orderable to one invoice, recap and validation flow |
| **8** | Payments and Invoice Actions | Wallet/Stripe/crypto/Cash/POS flows, link+QR flows, send actions, invoice send/regenerate |
| **9** | Admin Catalog Surface | Services/products/courses/departments management in V2 UX |
| **10** | Hardening and Rollout | Permissions parity, performance, tests, progressive cutover |

---

## Dependency Graph

```
Phase 1 (V1/V2 migration)
   |
   +--> Phase 2 (V2 shell/navigation)
   |       |
   |       +--> Phase 3 (Dashboard)
   |       |
   |       +--> Phase 4 (Cardex core)
   |               |
   |               +--> Phase 5 (User/Family cardex)
   |               |
   |               +--> Phase 6 (Coach/Employee cardex)
   |
   +--> Phase 7 (Order workstation)
   |       |
   |       +--> Phase 8 (Payments + invoices)
   |
   +--> Phase 9 (Catalog admin)
   |
   +--> Phase 10 (Hardening/rollout)
```

Recommended execution order:
1. Phase 1 + Phase 2
2. Phase 3 + Phase 4 in parallel
3. Phase 5 + Phase 6 in parallel
4. Phase 7
5. Phase 8 + Phase 9
6. Phase 10

---

## Phase Details

### Phase 1 - V1/V2 Namespace Migration Foundation

**Objective:** isolate current admin as V1 and make room for V2 development without production disruption.

**Tasks:**
- Move namespaces and directories from `App\Filament\*` to `App\Filament\V1\*`.
- Update imports in all moved files.
- Update `config/filament.php` discovery paths to V1.
- Keep login/auth compatibility.
- Add `app/Filament/V2/{Pages,Resources,Widgets}` skeleton.
- Add initial V2 landing page route (`/admin/v2`).

**Acceptance criteria:**
- Existing admin behavior unchanged.
- No route regression on V1 resources/pages.
- V2 placeholder page is reachable.

### Phase 2 - V2 Shell and Navigation

**Objective:** define the UX skeleton for all V2 screens.

**Tasks:**
- Implement V2 layout shell (header/navbar/left nav/content zones).
- Add active place switcher and place information settings entrypoint.
- Introduce V2 nav groups (Dashboard, Cardex, Orders, Catalog, Settings).
- Add shared filters state management (place/date).

**Acceptance criteria:**
- Context switch updates all widgets/pages consistently.
- Navigation remains role-aware.

### Phase 3 - Dashboard Day Cockpit

**Objective:** operational home page per place and date.

**Tasks:**
- Build a daily timeline/planning widget.
- Add cards for bookings today, pending check-ins, access count, sales snapshot.
- Add charts for bookings distribution and revenue split.
- Support date picker for future days.
- Add the selected KPI pack (see dedicated section).

**Acceptance criteria:**
- Data reflects selected place/date.
- Query performance acceptable for production volumes.

### Phase 4 - Cardex Core Components

**Objective:** provide reusable building blocks for all cardex pages.

**Tasks:**
- Build generic cardex page class.
- Implement reusable components: identity block, KPI strip, timeline table, quick action rail.
- Create shared transformers for timeline entries.

**Acceptance criteria:**
- Components reused by all 4 cardex types.
- Consistent UI/interaction patterns.

### Phase 5 - User and Family Cardex

**Objective:** full operational 360 for customers/families.

**Tasks:**
- User cardex: bookings history, orders, wallet/financial summary, access history.
- Family cardex: aggregate members data + shared finance + grouped history.
- Add quick actions: create order, send invoice, open payment link flow.

**Acceptance criteria:**
- A staff member can open one profile and execute common workflows end-to-end.

### Phase 6 - Coach and Employee Cardex

**Objective:** staff-oriented cardex views.

**Tasks:**
- Coach cardex: availability calendar, assigned bookings, historical utilization.
- Coach cardex: recurring availability management (weekly patterns + exceptions).
- Employee cardex: role/permissions summary, operational activity timeline.
- Quick actions for scheduling and assignment.

**Acceptance criteria:**
- Availability and booking assignment workflows are operable without leaving V2.

### Phase 7 - Unified Order Workstation

**Objective:** one invoicing workstation for all orderable types.

**Tasks:**
- Customer selection/search.
- Item picker by orderable type (all current orderables are in scope from day 1).
- Metadata capture per type (date/time/coach/department/quantity/custom amount).
- Recap page with VAT, totals, and payment options.

**Acceptance criteria:**
- One invoice can contain heterogeneous line items.
- One invoice can mix taxable and tax-exempt lines without manual technical workaround.
- Existing order constraints still enforced.

### Phase 8 - Payments and Invoice Actions

**Objective:** finalize checkout operations from V2.

**Tasks:**
- Buttons/actions for wallet, Stripe, crypto, cash, and POS payment flows.
- Display payment links and QR codes.
- Send links to customer by email from V2.
- Trigger invoice generation/send and invoice regeneration action.

**Acceptance criteria:**
- Payment orchestration works with existing webhook completion flows.
- Invoice artifacts remain consistent and downloadable.
- Cash and POS are available in the same checkout workflow as online methods.

### Phase 9 - Admin Catalog Surface

**Objective:** V2 screens to manage sellable entities and operational settings.

**Tasks:**
- Services/products/courses/departments management entrypoints.
- Role-gated CRUD access in V2 navigation.
- Place-scoped settings screens aligned with active place switcher.

**Acceptance criteria:**
- Core commercial catalog operations can be performed in V2.

### Phase 10 - Hardening and Rollout

**Objective:** production-safe rollout.

**Tasks:**
- Permission parity verification vs V1.
- Performance profiling and caching on heavy dashboards.
- E2E smoke scenarios and regression checks.
- Progressive enablement with feature flags.

**Acceptance criteria:**
- V2 is stable under production traffic.
- Rollback to V1 remains possible at any point.

---

## Technical File Impact (Estimated)

### New files

| Type | Estimate |
|---|---|
| V2 pages/resources/widgets | 25-40 |
| AdminV2 actions/data classes | 20-30 |
| Shared UI components/views | 10-20 |
| Tests (feature + filament) | 30-50 |
| Docs (phase-level plans + logs) | 10+ |

### Modified files

| Area | Examples |
|---|---|
| Filament config | `config/filament.php` |
| Filament provider/navigation | `app/Providers/FilamentServiceProvider.php` |
| Existing Filament classes | namespace updates to `App\Filament\V1\...` |
| Views/theme assets | `resources/views/filament/*`, `resources/filament/*` |

---

## Testing Strategy

- Migration safety tests for V1 routes and page accessibility.
- Feature tests for each V2 module (dashboard/cardex/order/payment).
- Snapshot/structure tests for critical JSON payloads used by V2 read models.
- Payment/invoice workflow tests (including link generation and send actions).
- Performance smoke checks on high-volume pages.

---

## Rollout Strategy

1. Deploy Phase 1 with no UX change for users.
2. Release V2 behind feature flag (`config('features.admin_v2')`).
3. Enable V2 for `super_admin` and `manager`.
4. Iterate module by module.
5. Make V2 default once parity is confirmed.
6. Keep V1 available during a stabilization window.

---

## Risks and Mitigations

| Risk | Impact | Mitigation |
|---|---|---|
| Namespace migration breakage | High | Automated namespace refactor + route smoke tests |
| Filament v2 panel limitation | High | Progressive V2 registration and slug namespacing |
| Query performance on cardex/dashboard | High | dedicated read actions, indexes, short-lived caching |
| Permission drift V1 vs V2 | Medium | explicit permission matrix and tests |
| UX inconsistency across modules | Medium | shared V2 shell and component system |

---

## Product Decisions Locked (2026-03-26)

1. Namespace migration is confirmed: current Filament becomes `V1`; new work is under `V2`.
2. Transition URL is confirmed: V2 runs under `/admin/v2/*`.
3. Initial V2 access roles are `super_admin` and `manager`.
4. Common/global switch is deferred; selected place information settings are in scope now.
5. Order workstation includes all currently supported orderable types.
6. Payment methods in scope are `wallet`, `stripe`, `nowpayments`, `cash`, and `pos`.
7. Mixed invoices are confirmed: one invoice can include heterogeneous lines.
8. Coach availability must support recurring schedules from first V2 delivery.
9. Family wallet model is confirmed: family wallet is the active wallet; member wallet remains historical (pre-family join context).
10. Cardex navigation order follows business priority: User -> Family -> Coach -> Employee.
11. Dashboard KPIs are selected by product/engineering and listed below.

---

## Dashboard KPI Pack (Selected)

1. **Planned Sessions Today**
- Total sessions/bookings for selected place/date with split by orderable/session type.

2. **Occupancy Rate by Time Block**
- Ratio of booked slots to available capacity per hour block to detect peaks and gaps.

3. **Coach Utilization**
- Booked coaching minutes vs available coaching minutes (global and per-coach drilldown).

4. **Attendance Gap**
- Checked-in attendees vs expected attendees (bookings) to monitor no-show pressure.

5. **Pending Customer Actions**
- Requests requiring staff action: confirmations/cancellations/rebookings and unpaid payment-link follow-ups.

6. **Commercial Pulse (Today)**
- Paid revenue today + unpaid orders count, with payment-method split (wallet/stripe/crypto/cash/pos).

---

## Next Documentation Artifacts

Generated artifacts:
- `01-PHASE-FOUNDATION.md`
- `02-PHASE-V2-SHELL.md`
- `03-PHASE-DASHBOARD.md`
- `04-PHASE-CARDEX-CORE.md`
- `05-PHASE-USER-FAMILY.md`
- `06-PHASE-COACH-EMPLOYEE.md`
- `07-PHASE-ORDER-WORKSTATION.md`
- `08-PHASE-PAYMENT-INVOICE.md`
- `09-PHASE-CATALOG-ADMIN.md`
- `10-PHASE-HARDENING.md`
- `TESTS.md`
- `AGENT_INIT.md`
