# Implementation Plan

## Validation Checklist

- [x] All specification file paths are correct and exist
- [x] Context priming section is complete
- [x] All implementation phases are defined
- [x] Each phase follows TDD: Prime → Test → Implement → Validate
- [x] Dependencies between phases are clear (no circular dependencies)
- [x] Parallel work is properly tagged with `[parallel: true]`
- [x] Activity hints provided for specialist selection `[activity: type]`
- [x] Every phase references relevant SDD sections
- [x] Every test references PRD acceptance criteria
- [x] Integration & E2E tests defined in final phase
- [x] Project commands match actual project setup
- [x] A developer could follow this plan independently

---

## Specification Compliance Guidelines

### How to Ensure Specification Adherence

1. **Before Each Phase**: Complete the Pre-Implementation Specification Gate
2. **During Implementation**: Reference specific SDD sections in each task
3. **After Each Task**: Run Specification Compliance checks
4. **Phase Completion**: Verify all specification requirements are met

### Deviation Protocol

If implementation cannot follow specification exactly:
1. Document the deviation and reason
2. Get approval before proceeding
3. Update SDD if the deviation is an improvement
4. Never deviate without documentation

## Metadata Reference

- `[parallel: true]` - Tasks that can run concurrently
- `[component: component-name]` - For multi-component features
- `[ref: document/section; lines: 1, 2-3]` - Links to specifications, patterns, or interfaces and (if applicable) line(s)
- `[activity: type]` - Activity hint for specialist agent selection

---

## Context Priming

*GATE: You MUST fully read all files mentioned in this section before starting any implementation.*

**Specification**:

- `docs/specs/009-two-way-sms-chat/product-requirements.md` - Product Requirements
- `docs/specs/009-two-way-sms-chat/solution-design.md` - Solution Design

**Key Design Decisions**:

- **ADR-1**: Separate inbound webhook (`/api/webhooks/chat-inbound`) - don't modify legacy `/api/sms/inbound`
- **ADR-2**: Per-store database tables for chat data (threads, messages, templates) + central DB for usage tracking
- **ADR-3**: Granular opt-out support (STOP = all, STOP MARKETING = marketing only)
- **ADR-4**: Template-only first messages until customer replies (freetext unlock pattern)
- **ADR-5**: Real-time via Ably using existing workbook channel patterns

**Implementation Context**:

- **Commands**:
  - Unit tests: `./test.sh --testsuite unit`
  - Integration tests: `./test.sh --testsuite integration`
  - Coverage: `./test.sh --coverage`
  - Specific test: `./test.sh --filter ChatTest`
  - Dependencies: `cd userfrosting && composer install`

- **Patterns to follow**:
  - Workbook panel registration: `public_html/js/workspace/modules/workbook/layout-manager.js`
  - Ably real-time events: `public_html/js/workspace/modules/workbook/ably-sync.js`
  - SMS service integration: `userfrosting/src/BuyerKiosk/SMS/TextMessageService/TextMessageService.php`
  - Multi-store DB pattern: `userfrosting/models/BaseModel.php` → `dbConnectByName()`

- **Interfaces to implement**:
  - Staff Chat API: `/api/:typeNum/chat/*` (6 endpoints)
  - Admin Chat API: `/admin/:typeNum/chat/*` (6 endpoints)
  - Webhook: `/api/webhooks/chat-inbound` (1 endpoint)

---

## Implementation Phases

---

### T1 Phase 1: Database Foundation & Core Models ✅ COMPLETE

*Establishes the data layer for chat functionality including all tables and entity models.*

*Completed: 2025-12-08 | 144 tests passing, 500 assertions*

- [x] T1.1 Prime Context
    - [x] T1.1.1 Read database schema specifications `[ref: solution-design.md/Data Storage Changes]`
    - [x] T1.1.2 Read entity model specifications `[ref: solution-design.md/Application Data Models]`
    - [x] T1.1.3 Review existing migration patterns `[ref: userfrosting/migrations/input/]`

- [x] T1.2 Write Tests `[activity: test-execution]`
    - [x] T1.2.1 Test ChatThread model creation and state transitions `[ref: product-requirements.md; lines: 143-155]`
    - [x] T1.2.2 Test ChatMessage model with delivery status updates `[ref: product-requirements.md; lines: 185-188]`
    - [x] T1.2.3 Test ChatTemplate model with wildcard validation `[ref: product-requirements.md; lines: 173-180]`
    - [x] T1.2.4 Test freetext unlock logic (staffCanFreetext state machine) `[ref: solution-design.md/Freetext Unlock Logic Example]`
    - [x] T1.2.5 Test segment count calculation for Unicode vs GSM encoding

- [x] T1.3 Implement Database Migrations `[activity: data-architecture]`
    - [x] T1.3.1 Create migration: `20251208_001_chat_threads.json` for per-store `chat_threads` table
    - [x] T1.3.2 Create migration: `20251208_002_chat_messages.json` for per-store `chat_messages` table
    - [x] T1.3.3 Create migration: `20251208_003_chat_templates.json` for per-store `chat_templates` table
    - [x] T1.3.4 Create migration: `20251208_004_chat_usage.json` for central `chat_sms_usage` table
    - [x] T1.3.5 Create migration: `20251208_005_chat_optout.json` to add columns to `loyaltyDoNotTextList`

- [x] T1.4 Implement Entity Models `[activity: domain-modeling]`
    - [x] T1.4.1 Create `userfrosting/src/BuyerKiosk/Chat/Models/ChatThread.php` with state behaviors
    - [x] T1.4.2 Create `userfrosting/src/BuyerKiosk/Chat/Models/ChatMessage.php` with delivery tracking
    - [x] T1.4.3 Create `userfrosting/src/BuyerKiosk/Chat/Models/ChatTemplate.php` with validation

- [x] T1.5 Validate
    - [x] T1.5.1 Run unit tests: `./test.sh --filter ChatThread` (39 tests, 149 assertions) `[activity: run-tests]`
    - [x] T1.5.2 Run unit tests: `./test.sh --filter ChatMessage` (58 tests, 210 assertions) `[activity: run-tests]`
    - [x] T1.5.3 Run unit tests: `./test.sh --filter ChatTemplate` (47 tests, 141 assertions) `[activity: run-tests]`
    - [x] T1.5.4 Verify migrations valid JSON format `[activity: run-tests]`
    - [x] T1.5.5 Review models follow existing BuyerKiosk patterns `[activity: review-code]`

---

### T2 Phase 2: Core Services Layer ✅ COMPLETE

*Implements the business logic services that power chat operations.*

**Completed: 2025-12-08** | **Tests: 82 passing, 179 assertions**

**Performance Optimization:** Refactored ChatMatchingService to use `kiosk_buys.systemBuys`
with indexed `phoneNum` column for O(log n) lookup instead of iterating hundreds of store databases.

- [x] T2.1 ChatMatchingService `[component: matching]`

    - [x] T2.1.1 Prime Context
    - [x] T2.1.1.1 Read phone-to-store matching algorithm `[ref: solution-design.md/Example: Phone → Store Matching Logic]`
        - [x] T2.1.1.2 Read inbound routing business rules `[ref: product-requirements.md; lines: 295-308]`
        - [x] T2.1.1.3 Review existing store iteration patterns `[ref: userfrosting/models/BaseModel.php]`

    - [x] T2.1.2 Write Tests `[activity: test-execution]`
        - [x] T2.1.2.1 Test phone normalization (10-digit, +1 prefix, formatting)
        - [x] T2.1.2.2 Test routing to store with most recent buy timestamp
        - [x] T2.1.2.3 Test tiebreaker when same-day buys at multiple stores
        - [x] T2.1.2.4 Test unroutable phone (no customer match)
        - [x] T2.1.2.5 Test opted-out phone detection `[ref: product-requirements.md; lines: 207-214]`

    - [x] T2.1.3 Implement `[activity: domain-modeling]`
        - [x] T2.1.3.1 Create `userfrosting/src/BuyerKiosk/Chat/Services/ChatMatchingService.php`
        - [x] T2.1.3.2 Implement `findStoreByPhone()` using systemBuys indexed lookup
        - [x] T2.1.3.3 Implement `isOptedOut()` with granular opt-out type support

    - [x] T2.1.4 Validate
        - [x] T2.1.4.1 Run unit tests: 21 tests, 41 assertions passing

- [x] T2.2 ChatEligibilityService `[component: eligibility]` `[parallel: true]`

    - [x] T2.2.1 Prime Context
        - [x] T2.2.1.1 Read eligibility rules `[ref: product-requirements.md; lines: 163-170]`
        - [x] T2.2.1.2 Read freetext lock requirements `[ref: product-requirements.md; lines: 147-154]`

    - [x] T2.2.2 Write Tests `[activity: test-execution]`
        - [x] T2.2.2.1 Test same-day buy eligibility (can message)
        - [x] T2.2.2.2 Test previous-day buy with open thread (can message)
        - [x] T2.2.2.3 Test previous-day buy with closed thread (cannot initiate)
        - [x] T2.2.2.4 Test do-not-text customer (cannot message)
        - [x] T2.2.2.5 Test freetext permission check

    - [x] T2.2.3 Implement `[activity: domain-modeling]`
        - [x] T2.2.3.1 Create `userfrosting/src/BuyerKiosk/Chat/Services/ChatEligibilityService.php`
        - [x] T2.2.3.2 Implement `canMessageCustomer()` with eligibility rules
        - [x] T2.2.3.3 Implement `canSendFreetext()` checking thread state
        - [x] T2.2.3.4 Implement `getEligibleCustomers()` for thread list

    - [x] T2.2.4 Validate
        - [x] T2.2.4.1 Run unit tests: 14 tests, 28 assertions passing

- [x] T2.3 ChatTemplateService `[component: templates]` `[parallel: true]`

    - [x] T2.3.1 Prime Context
        - [x] T2.3.1.1 Read wildcard processing example `[ref: solution-design.md; lines: 939-989]`
        - [x] T2.3.1.2 Read template management requirements `[ref: product-requirements.md; lines: 173-180]`

    - [x] T2.3.2 Write Tests `[activity: test-execution]`
        - [x] T2.3.2.1 Test wildcard replacement (customer_name, store_phone, buy_number)
        - [x] T2.3.2.2 Test missing data fallbacks (e.g., no first name → "Customer")
        - [x] T2.3.2.3 Test character count calculation after wildcard expansion
        - [x] T2.3.2.4 Test SMS segment calculation (GSM vs Unicode)
        - [x] T2.3.2.5 Test template validation (320 char limit)

    - [x] T2.3.3 Implement `[activity: domain-modeling]`
        - [x] T2.3.3.1 Create `userfrosting/src/BuyerKiosk/Chat/Services/ChatTemplateService.php`
        - [x] T2.3.3.2 Implement `render()` with wildcard substitution
        - [x] T2.3.3.3 Implement `getAvailableWildcards()` for UI documentation
        - [x] T2.3.3.4 Implement `calculateSegmentCount()` with encoding detection

    - [x] T2.3.4 Validate
        - [x] T2.3.4.1 Run unit tests: 32 tests, 62 assertions passing

- [x] T2.4 ChatBillingService `[component: billing]` `[parallel: true]`

    - [x] T2.4.1 Prime Context
        - [x] T2.4.1.1 Read usage tracking requirements `[ref: product-requirements.md; lines: 197-205]`
        - [x] T2.4.1.2 Read central database schema for usage `[ref: solution-design.md; lines: 497-519]`

    - [x] T2.4.2 Write Tests `[activity: test-execution]`
        - [x] T2.4.2.1 Test transactional message (not billable)
        - [x] T2.4.2.2 Test interactive message (billable)
        - [x] T2.4.2.3 Test segment count tracking
        - [x] T2.4.2.4 Test usage aggregation by billing period

    - [x] T2.4.3 Implement `[activity: domain-modeling]`
        - [x] T2.4.3.1 Create `userfrosting/src/BuyerKiosk/Chat/Services/ChatBillingService.php`
        - [x] T2.4.3.2 Implement `trackUsage()` writing to central database
        - [x] T2.4.3.3 Implement `getUsageReport()` for admin dashboard

    - [x] T2.4.4 Validate
        - [x] T2.4.4.1 Run unit tests: 13 tests, 46 assertions passing

- [x] T2.5 Phase 2 Validation
    - [x] T2.5.1 Run all service tests: 82 tests, 179 assertions - ALL PASSING
    - [x] T2.5.2 Review service layer follows existing patterns - CONFIRMED

**Additional Infrastructure:**
- [x] Added `{{buys}}` placeholder support to migration system (`globalMigration.php`)
- [x] Created migration for `phoneNum` index on `systemBuys` table

---

### T3 Phase 3: Inbound Webhook & Real-time Events ✅ COMPLETE

*Handles customer replies and pushes real-time notifications to the Workbook.*

**Completed: 2025-12-08** | **Tests: 59 passing (45 ChatWebhookController + 14 ChatAblyPublisher)**

- [x] T3.1 Prime Context
    - [x] T3.1.1 Read webhook controller flow `[ref: solution-design.md; lines: 1036-1072]`
    - [x] T3.1.2 Read opt-out processing algorithm `[ref: solution-design.md; lines: 1084-1115]`
    - [x] T3.1.3 Read Ably event patterns `[ref: solution-design.md; lines: 773-814]`
    - [x] T3.1.4 Review existing SMS inbound handling `[ref: userfrosting/routes/groups/sms.php]`
    - [x] T3.1.5 Review existing Ably publishing patterns `[ref: public_html/js/workspace/modules/workbook/ably-sync.js]`

- [x] T3.2 Write Tests `[activity: test-execution]`
    - [x] T3.2.1 Test Vonage webhook payload parsing (msisdn, text, message-timestamp)
    - [x] T3.2.2 Test Twilio webhook payload parsing (From, Body, MessageSid)
    - [x] T3.2.3 Test STOP command detection and opt-out processing `[ref: product-requirements.md; lines: 207-214]`
    - [x] T3.2.4 Test STOP MARKETING granular opt-out
    - [x] T3.2.5 Test phone routing to correct store
    - [x] T3.2.6 Test thread creation for new customer
    - [x] T3.2.7 Test thread update for existing customer
    - [x] T3.2.8 Test freetext unlock when customer replies
    - [x] T3.2.9 Test unroutable phone logging
    - [x] T3.2.10 Test Ably event publishing format

- [x] T3.3 Implement ChatWebhookController `[activity: api-development]`
    - [x] T3.3.1 Create `userfrosting/src/BuyerKiosk/Chat/Controllers/ChatWebhookController.php`
    - [x] T3.3.2 Implement `handleInbound()` with provider detection (Vonage vs Twilio)
    - [x] T3.3.3 Implement phone normalization and opt-out detection
    - [x] T3.3.4 Implement store routing via ChatMatchingService
    - [x] T3.3.5 Implement thread find-or-create logic
    - [x] T3.3.6 Implement freetext unlock on customer reply

- [x] T3.4 Implement ChatAblyPublisher `[activity: api-development]`
    - [x] T3.4.1 Create `userfrosting/src/BuyerKiosk/Chat/Events/ChatAblyPublisher.php`
    - [x] T3.4.2 Implement `publishNewMessage()` for `workbook:chat:message` event
    - [x] T3.4.3 Implement `publishNewThread()` for `workbook:chat:thread:new` event
    - [x] T3.4.4 Implement `publishDeliveryUpdate()` for `workbook:chat:delivered` event

- [x] T3.5 Implement Webhook Route `[activity: api-development]`
    - [x] T3.5.1 Create `userfrosting/routes/chat/webhooks.php`
    - [x] T3.5.2 Register POST `/api/webhooks/chat-inbound` route
    - [x] T3.5.3 Add route to main router in `public_html/index.php`

- [x] T3.6 Validate
    - [x] T3.6.1 Run unit tests: 45 ChatWebhookController tests passing
    - [x] T3.6.2 Run unit tests: 14 ChatAblyPublisher tests passing
    - [x] T3.6.3 Test webhook endpoint responds 200 OK
    - [x] T3.6.4 Total: 1881 unit tests, 6559 assertions

---

### T4 Phase 4: Staff Chat API ✅ COMPLETE

*Provides the backend API for staff to send messages and manage threads.*

**Completed: 2025-12-08** | **Tests: 54 passing, 104 assertions**

- [x] T4.1 Prime Context
    - [x] T4.1.1 Read Staff API specifications `[ref: solution-design.md; lines: 529-610]`
    - [x] T4.1.2 Read primary flow sequence diagram `[ref: solution-design.md; lines: 996-1032]`
    - [x] T4.1.3 Review existing API patterns `[ref: userfrosting/routes/api.php]`

- [x] T4.2 Write Tests `[activity: test-execution]`
    - [x] T4.2.1 Test GET `/api/:typeNum/chat/threads` returns active threads `[ref: product-requirements.md; lines: 131-137]`
    - [x] T4.2.2 Test GET `/api/:typeNum/chat/threads/:threadId` returns messages
    - [x] T4.2.3 Test POST `/api/:typeNum/chat/threads/:threadId/messages` with template `[ref: product-requirements.md; lines: 147-154]`
    - [x] T4.2.4 Test POST `/api/:typeNum/chat/threads/:threadId/messages` with freetext (when unlocked)
    - [x] T4.2.5 Test POST `/api/:typeNum/chat/threads/:threadId/messages` freetext blocked (when locked)
    - [x] T4.2.6 Test GET `/api/:typeNum/chat/eligible` returns today's customers `[ref: product-requirements.md; lines: 163-170]`
    - [x] T4.2.7 Test POST `/api/:typeNum/chat/threads` creates new thread
    - [x] T4.2.8 Test POST `/api/:typeNum/chat/threads/:threadId/close` closes thread `[ref: product-requirements.md; lines: 218-224]`
    - [x] T4.2.9 Test GET `/api/:typeNum/chat/templates` returns active templates
    - [x] T4.2.10 Test permission checks (session + CSRF + store access)
    - [x] T4.2.11 Test character limit enforcement (320 max)

- [x] T4.3 Implement ChatApiController `[activity: api-development]`
    - [x] T4.3.1 Create `userfrosting/src/BuyerKiosk/Chat/Controllers/ChatApiController.php`
    - [x] T4.3.2 Implement `getThreads()` with status filtering
    - [x] T4.3.3 Implement `getThread()` with messages and customer context
    - [x] T4.3.4 Implement `sendMessage()` with template/freetext logic
    - [x] T4.3.5 Implement `getEligibleCustomers()` for today's buys
    - [x] T4.3.6 Implement `createThread()` for new conversations
    - [x] T4.3.7 Implement `closeThread()` with employee tracking
    - [x] T4.3.8 Implement `getTemplates()` for template picker

- [x] T4.4 Integrate with SMS Sending `[activity: api-development]`
    - [x] T4.4.1 Integrate with existing `TextMessageService` for outbound SMS
    - [x] T4.4.2 Implement delivery status webhook handling for chat messages
    - [x] T4.4.3 Track usage via ChatBillingService after send

- [x] T4.5 Implement API Routes `[activity: api-development]`
    - [x] T4.5.1 Create `userfrosting/routes/chat/api.php`
    - [x] T4.5.2 Register all staff API endpoints
    - [x] T4.5.3 Add route to main router

- [x] T4.6 Validate
    - [x] T4.6.1 Run unit tests: 54 tests, 104 assertions - ALL PASSING
    - [x] T4.6.2 Test API endpoints respond correctly - CONFIRMED
    - [x] T4.6.3 Verify permission checks work - CONFIRMED
    - [x] T4.6.4 Review API follows existing patterns - CONFIRMED

**Files Created:**
- `userfrosting/src/BuyerKiosk/Chat/Controllers/ChatApiController.php` (987 lines)
- `userfrosting/routes/chat/api.php` (147 lines)
- `userfrosting/tests/Unit/Chat/Controllers/ChatApiControllerTest.php` (54 tests)

---

### T5 Phase 5: Frontend Chat Panel ✅ COMPLETE

*Builds the user interface for staff to interact with chat in the Workbook.*

**Completed: 2025-12-08** | **9 JavaScript modules, 1 Twig template, CSS styles**

- [x] T5.1 Prime Context
    - [x] T5.1.1 Read UI specifications `[ref: solution-design.md/UI Specifications]`
    - [x] T5.1.2 Read component structure pattern `[ref: solution-design.md/Building Block View]`
    - [x] T5.1.3 Review Workbook panel registration `[ref: public_html/js/workspace/modules/workbook/layout-manager.js]`
    - [x] T5.1.4 Review existing Ably sync patterns `[ref: public_html/js/workspace/modules/workbook/ably-sync.js]`
    - [x] T5.1.5 Review Handlebars template usage `[ref: userfrosting/templates/themes/default/workspace/workspace.html]`

- [x] T5.2 Implement Chat Overlay Container `[activity: component-development]`
    - [x] T5.2.1 Create `public_html/js/workspace/modules/chat/chat-overlay.js`
    - [x] T5.2.2 Implement floating overlay with drag/resize capability
    - [x] T5.2.3 Implement minimize to KPI footer
    - [x] T5.2.4 Implement expand from footer icon
    - [x] T5.2.5 Persist panel position/size in localStorage

- [x] T5.3 Implement Thread List `[activity: component-development]`
    - [x] T5.3.1 Create `public_html/js/workspace/modules/chat/chat-thread-list.js`
    - [x] T5.3.2 Implement Active/Closed tab switching
    - [x] T5.3.3 Implement thread item rendering (customer name, buy#, preview, timestamp)
    - [x] T5.3.4 Implement unread badge display
    - [x] T5.3.5 Implement thread selection and highlighting

- [x] T5.4 Implement Conversation View `[activity: component-development]`
    - [x] T5.4.1 Create `public_html/js/workspace/modules/chat/chat-conversation.js`
    - [x] T5.4.2 Implement message history display (inbound/outbound styling)
    - [x] T5.4.3 Implement delivery status indicators (Sending → Sent → Delivered/Failed)
    - [x] T5.4.4 Implement customer/buy context header
    - [x] T5.4.5 Implement auto-scroll to latest message

- [x] T5.5 Implement Message Composer `[activity: component-development]`
    - [x] T5.5.1 Create `public_html/js/workspace/modules/chat/chat-composer.js`
    - [x] T5.5.2 Implement freetext input with locked/unlocked states `[ref: solution-design.md/Message Composer]`
    - [x] T5.5.3 Implement character counter with color states (normal/warning/danger) `[ref: solution-design.md/Character Counter]`
    - [x] T5.5.4 Implement send button with disabled states
    - [x] T5.5.5 Implement keyboard shortcut (Enter to send)

- [x] T5.6 Implement Template Picker `[activity: component-development]`
    - [x] T5.6.1 Create `public_html/js/workspace/modules/chat/chat-templates.js`
    - [x] T5.6.2 Implement dropdown with categorized templates
    - [x] T5.6.3 Implement preview with wildcards filled
    - [x] T5.6.4 Implement one-click insert to composer

- [x] T5.7 Implement Real-time Updates `[activity: component-development]`
    - [x] T5.7.1 Create `public_html/js/workspace/modules/chat/chat-ably-sync.js`
    - [x] T5.7.2 Subscribe to `workbook:chat:message` events
    - [x] T5.7.3 Subscribe to `workbook:chat:thread:new` events
    - [x] T5.7.4 Subscribe to `workbook:chat:delivered` events
    - [x] T5.7.5 Update UI on event receipt

- [x] T5.8 Implement Notifications `[activity: component-development]`
    - [x] T5.8.1 Create `public_html/js/workspace/modules/chat/chat-notifications.js`
    - [x] T5.8.2 Implement toast notification for inbound messages
    - [x] T5.8.3 Implement footer icon badge with unread count
    - [x] T5.8.4 Implement audio notification chime for inbound messages

- [x] T5.9 Implement Buy Queue Badge `[activity: component-development]`
    - [x] T5.9.1 Create `public_html/js/workspace/modules/chat/chat-buyqueue-badge.js`
    - [x] T5.9.2 Add chat icon to buy queue rows
    - [x] T5.9.3 Show unread count badge on rows with active chats
    - [x] T5.9.4 Open chat overlay to specific thread on badge click

- [x] T5.10 Implement Twig Template + Chat Manager `[activity: component-development]`
    - [x] T5.10.1 Create `userfrosting/templates/themes/default/workspace/partials/chat-panel-content.html`
    - [x] T5.10.2 Add Handlebars templates wrapped in `{% raw %}`
    - [x] T5.10.3 Inject server-side data (templates, csrf token, employee info)
    - [x] T5.10.4 Create `public_html/js/workspace/modules/chat/chat-manager.js` orchestrator

- [x] T5.11 Validate
    - [x] T5.11.1 All 9 JavaScript files pass syntax validation (node --check)
    - [x] T5.11.2 Scripts added to workspace-foot.html
    - [x] T5.11.3 CSS added to workspace-head.html
    - [x] T5.11.4 Twig template included in workspace-foot.html
    - [x] T5.11.5 337 Chat unit tests passing, 941 assertions

**Files Created:**
- `public_html/js/workspace/modules/chat/chat-overlay.js` - Floating overlay container
- `public_html/js/workspace/modules/chat/chat-thread-list.js` - Thread list with tabs
- `public_html/js/workspace/modules/chat/chat-conversation.js` - Message history view
- `public_html/js/workspace/modules/chat/chat-composer.js` - Message input/send
- `public_html/js/workspace/modules/chat/chat-templates.js` - Template picker
- `public_html/js/workspace/modules/chat/chat-ably-sync.js` - Real-time updates
- `public_html/js/workspace/modules/chat/chat-notifications.js` - Toast/badge/sound
- `public_html/js/workspace/modules/chat/chat-buyqueue-badge.js` - Buy queue icons
- `public_html/js/workspace/modules/chat/chat-manager.js` - Main orchestrator
- `userfrosting/templates/themes/default/workspace/partials/chat-panel-content.html`
- `public_html/css/admin/modules/chat.css` - All chat styles

---

### T6 Phase 6: Admin Template Management ✅ COMPLETE

*Provides the admin interface for managing canned templates and viewing usage.*

**Completed: 2025-12-08** | **Tests: 37 passing, 167 assertions**

- [x] T6.1 Prime Context
    - [x] T6.1.1 Read Admin API specifications `[ref: solution-design.md; lines: 612-690]`
    - [x] T6.1.2 Read template management requirements `[ref: product-requirements.md; lines: 173-180]`
    - [x] T6.1.3 Read usage dashboard requirements `[ref: product-requirements.md; lines: 233-238]`
    - [x] T6.1.4 Review existing admin page patterns

- [x] T6.2 Write Tests `[activity: test-execution]`
    - [x] T6.2.1 Test GET `/admin/:typeNum/chat/templates` lists all templates
    - [x] T6.2.2 Test POST `/admin/:typeNum/chat/templates` creates template
    - [x] T6.2.3 Test PUT `/admin/:typeNum/chat/templates/:id` updates template
    - [x] T6.2.4 Test DELETE `/admin/:typeNum/chat/templates/:id` (non-system templates only)
    - [x] T6.2.5 Test system templates cannot be deleted
    - [x] T6.2.6 Test GET `/admin/:typeNum/chat/customers/:id/history` returns chat history `[ref: product-requirements.md; lines: 190-196]`
    - [x] T6.2.7 Test GET `/admin/:typeNum/chat/usage` returns usage report

- [x] T6.3 Implement ChatAdminController `[activity: api-development]`
    - [x] T6.3.1 Create `userfrosting/src/BuyerKiosk/Chat/Controllers/ChatAdminController.php`
    - [x] T6.3.2 Implement `listTemplates()` with all templates
    - [x] T6.3.3 Implement `createTemplate()` with validation
    - [x] T6.3.4 Implement `updateTemplate()` with character/segment recalculation
    - [x] T6.3.5 Implement `deleteTemplate()` with system template protection
    - [x] T6.3.6 Implement `getCustomerHistory()` for chat history lookup
    - [x] T6.3.7 Implement `getUsageReport()` with date filtering

- [x] T6.4 Implement Admin Routes `[activity: api-development]`
    - [x] T6.4.1 Create `userfrosting/routes/chat/admin.php`
    - [x] T6.4.2 Register all admin API endpoints
    - [x] T6.4.3 Add permission checks for `uri_store_settings`

- [x] T6.5 Implement Admin Frontend `[activity: component-development]`
    - [x] T6.5.1 Create `public_html/js/admin/chat/template-manager.js`
    - [x] T6.5.2 Implement template list with CRUD actions
    - [x] T6.5.3 Implement template editor with wildcard insertion
    - [x] T6.5.4 Implement character/segment counter in editor
    - [x] T6.5.5 Create `public_html/js/admin/chat/usage-dashboard.js`
    - [x] T6.5.6 Implement usage report with date filtering
    - [x] T6.5.7 Implement usage chart (optional)

- [x] T6.6 Implement Admin Templates `[activity: component-development]`
    - [x] T6.6.1 Create `userfrosting/templates/themes/default/admin/chat/templates.html`
    - [x] T6.6.2 Create `userfrosting/templates/themes/default/admin/chat/usage.html`

- [x] T6.7 Seed Default Templates `[activity: data-architecture]`
    - [x] T6.7.1 Create migration to insert default transactional templates:
        - "Buy Ready" - "Hi {{customer_name}}, your buy {{buy_number}} is ready for pickup!"
        - "Pickup Reminder" - "Hi {{customer_name}}, reminder: your buy {{buy_number}} is ready at {{store_name}}."
        - "Store Hours" - "We're open today until {{store_hours}}. See you soon!"

- [x] T6.8 Validate
    - [x] T6.8.1 Run unit tests: 37 tests, 167 assertions - ALL PASSING
    - [x] T6.8.2 Test template CRUD operations - CONFIRMED
    - [x] T6.8.3 Test usage report displays correctly - CONFIRMED
    - [x] T6.8.4 Test permission enforcement - CONFIRMED
    - [x] T6.8.5 Review admin pages follow existing patterns - CONFIRMED

**Files Created:**
- `userfrosting/src/BuyerKiosk/Chat/Controllers/ChatAdminController.php` (26KB)
- `userfrosting/routes/chat/admin.php` (10KB)
- `userfrosting/tests/Unit/Chat/Controllers/ChatAdminControllerTest.php` (68KB)
- `public_html/js/admin/chat/template-manager.js` (30KB)
- `public_html/js/admin/chat/usage-dashboard.js` (24KB)
- `userfrosting/templates/themes/default/admin/chat/templates.html` (24KB)
- `userfrosting/templates/themes/default/admin/chat/usage.html` (26KB)
- `userfrosting/migrations/input/20251208_007_chat_default_templates.json`

---

### T7 Phase 7: Integration & End-to-End Validation

*Validates the complete feature works end-to-end and meets all quality requirements.*

- [ ] T7.1 Integration Tests `[activity: test-execution]`
    - [ ] T7.1.1 Test complete outbound flow: Staff sends template → SMS sent → Delivery webhook updates status
    - [ ] T7.1.2 Test complete inbound flow: Customer replies → Webhook routes → Thread updates → Ably notifies → UI updates
    - [ ] T7.1.3 Test freetext unlock flow: Staff sends template → Customer replies → Freetext unlocks → Staff sends freetext
    - [ ] T7.1.4 Test opt-out flow: Customer sends STOP → Opt-out recorded → Confirmation sent → Thread closed
    - [ ] T7.1.5 Test multi-store routing: Same customer, different stores, correct routing

- [ ] T7.2 End-to-End Tests `[activity: test-execution]`
    - [ ] T7.2.1 Scenario: Staff initiates conversation with today's customer `[ref: product-requirements.md; lines: 100-107]`
    - [ ] T7.2.2 Scenario: Customer replies and staff responds with freetext `[ref: product-requirements.md; lines: 92-98]`
    - [ ] T7.2.3 Scenario: Owner manages templates `[ref: product-requirements.md; lines: 117-125]`
    - [ ] T7.2.4 Scenario: Opt-out processed correctly `[ref: solution-design.md; lines: 1336-1343]`
    - [ ] T7.2.5 Scenario: Inbound routes to correct store `[ref: solution-design.md; lines: 1354-1360]`

- [ ] T7.3 Performance Validation `[activity: performance-testing]` `[ref: solution-design.md; lines: 1265-1270]`
    - [ ] T7.3.1 Test webhook response time: <5 seconds (target <1 second)
    - [ ] T7.3.2 Test thread list load: <2 seconds for 50 threads
    - [ ] T7.3.3 Test message send: <3 seconds end-to-end
    - [ ] T7.3.4 Test Ably notification latency: <5 seconds

- [ ] T7.4 Security Validation `[activity: quality-review]` `[ref: solution-design.md; lines: 1276-1280]`
    - [ ] T7.4.1 Verify all staff endpoints require session + CSRF
    - [ ] T7.4.2 Verify admin endpoints require `uri_store_settings` permission
    - [ ] T7.4.3 Verify opt-out processed before message handling
    - [ ] T7.4.4 Verify no PII in error logs
    - [ ] T7.4.5 Verify cross-store data isolation

- [ ] T7.5 PRD Acceptance Criteria Verification
    - [ ] T7.5.1 Feature 1: Chat Panel in Workbook `[ref: product-requirements.md; lines: 131-137]`
    - [ ] T7.5.2 Feature 2: Inbound Message Routing `[ref: product-requirements.md; lines: 139-145]`
    - [ ] T7.5.3 Feature 3: Canned Message Requirement `[ref: product-requirements.md; lines: 147-154]`
    - [ ] T7.5.4 Feature 4: Freetext Response After Reply `[ref: product-requirements.md; lines: 156-161]`
    - [ ] T7.5.5 Feature 5: Eligibility Rules `[ref: product-requirements.md; lines: 163-170]`
    - [ ] T7.5.6 Feature 6: Template Management `[ref: product-requirements.md; lines: 173-180]`
    - [ ] T7.5.7 Feature 7: Delivery Status Tracking `[ref: product-requirements.md; lines: 185-188]`
    - [ ] T7.5.8 Feature 8: Chat History `[ref: product-requirements.md; lines: 190-196]`
    - [ ] T7.5.9 Feature 9: SMS Usage Tracking `[ref: product-requirements.md; lines: 197-205]`
    - [ ] T7.5.10 Feature 10: TCPA Opt-Out Handling `[ref: product-requirements.md; lines: 207-214]`

- [ ] T7.6 Test Coverage Report `[activity: run-tests]`
    - [ ] T7.6.1 Run coverage: `./test.sh --coverage`
    - [ ] T7.6.2 Verify Chat module coverage ≥80%
    - [ ] T7.6.3 Document any coverage gaps with justification

- [ ] T7.7 Documentation
    - [ ] T7.7.1 Update API documentation for new endpoints
    - [ ] T7.7.2 Add chat feature to user-facing documentation
    - [ ] T7.7.3 Document webhook configuration for SMS providers

- [ ] T7.8 Deployment Preparation
    - [ ] T7.8.1 Verify migrations run successfully
    - [ ] T7.8.2 Prepare feature flag: `chat_enabled` in store settings
    - [ ] T7.8.3 Document rollout plan (start with 1-2 stores)
    - [ ] T7.8.4 Prepare webhook URLs for Vonage/Twilio dashboard configuration

- [ ] T7.9 Final Sign-off
    - [ ] T7.9.1 All unit tests passing: `./test.sh --testsuite unit`
    - [ ] T7.9.2 All integration tests passing: `./test.sh --testsuite integration`
    - [ ] T7.9.3 All PRD requirements implemented
    - [ ] T7.9.4 Implementation follows SDD design
    - [ ] T7.9.5 Feature ready for staged rollout
