diff --git a/docs/pilot/COLLABORATION-PLAN.md b/docs/pilot/COLLABORATION-PLAN.md new file mode 100644 index 0000000..85c1d80 --- /dev/null +++ b/docs/pilot/COLLABORATION-PLAN.md @@ -0,0 +1,104 @@ +--- +type: plan +status: ratified +project: armonia-dashboard +pilot: group-workshop-roster +date: 2026-10-26 +tags: [collaboration-plan, pilot, governance, anne-droid, qa] +--- + +# Project Collaboration Plan: Group Workshop Roster Pilot + +> **Status:** Ratified Operating Contract (Gates 1 & 2 Approved) +> **Target System:** `armonia-dashboard` +> **Pilot Simplification Note:** For this pilot, the Orchestrator synthesizes both the requirements and the UX proposal. This is a deliberate pilot simplification to test the workflow without premature agent proliferation; it does **not** demonstrate that Requirements Engineering and UX Design are interchangeable in the permanent agency architecture. + +--- + +## 1. Active Role Roster & Authority Boundaries + +```mermaid +sequenceDiagram + autonumber + actor PO as Project Owner + participant ORCH as Orchestrator + participant ANNE as Anne Droid (Frontend) + participant QA as Independent QA + + PO->>ORCH: 1. Approve Collaboration Plan & Spec Contract + ORCH->>ANNE: 2. Delegate approved spec + API contract + Note over ANNE: Worktree: ../armonia-dashboard-anne-roster
Implements views, styles, unit tests
Documents contract friction if blocked + ANNE->>ORCH: 3. Open Draft PR & Freeze Anne Self-Audit + Note over ORCH,QA: Information Barrier: QA has ZERO access
to Anne's code diff, PR text, or self-audit + ORCH->>QA: 4. Dispatch Running URL + Verification Packet ONLY + Note over QA: Executes Scenarios 1 to 8
Verifies UI, persistence (F5), a11y, mobile + QA->>ORCH: 5. Submit QA Evidence Scorecard (Pass/Fail per AC) + ORCH->>PO: 6. Present PR Diff + Anne Audit + QA Scorecard + alt All Criteria Pass & Evidence Verified + PO->>ANNE: 7a. Authorize PR Merge into main + else Defects / Gaps Detected + PO->>ORCH: 7b. Issue Revision Directive (routed per Escalation Protocol) + end +``` + +| Role | Operational Scope for This Pilot | Autonomous Authority | Strict Boundary / Prohibited | +| :---------------------------- | :------------------------------------------------------------------------------------------------------------ | :-------------------------------------------------------------------------- | :----------------------------------------------------------------------------------------------- | +| **Project Owner** | Final business authority, requirement sign-off, risk acceptance, conflict adjudication, and release approval. | All consequential product and architectural decisions. | N/A | +| **Orchestrator** | Synthesizes specification; monitors handoffs; verifies precondition gates; routes escalation friction. | Workflow sequencing, contract packaging, QA test dispatching. | **Cannot** modify acceptance criteria, relax invariants, waive QA defects, or approve PR merges. | +| **Anne Droid (Frontend)** | Implements frontend views, styles, and component tests against the approved contract. | Component modularity, state architecture, styling tokens, local unit tests, implementation decomposition, and commit sequencing. | **Cannot** commit to `main`, modify business logic, silently mock API endpoints, merge PRs, or **modify/refactor existing working features outside the assigned scope**. | +| **Independent QA Specialist** | Validates running application against acceptance criteria using the Verification Packet. | Pass/Fail/Blocked verdicts per criterion backed by browser evidence. | **Cannot** waive acceptance criteria, inspect Anne's code/self-audit, or make release decisions. | + +### 1.1 Scope Containment & Non-Regression Invariant +When tasked with implementing a new feature (Feature C, e.g. Workshop Roster): +1. **Preserve Existing Capabilities**: Existing views and features (Features A and B: Follow-up Queue, Daily Agenda, Client Directory, Nueva Cita modal) must continue to function without behavioral, visual, or test regressions. All existing test suites (`pnpm exec vp test`) must pass 100%. +2. **Beyond Automated Tests (Targeted Workflow Checks)**: Because existing automated tests may not cover every edge in Queue or Agenda, Anne's self-audit must execute targeted smoke checks of those existing workflows (e.g. verifying that the 48h queue loads and the Nueva Cita modal still opens without errors). +3. **Additive Isolation & Justified Integration**: Feature C must reside in dedicated, isolated files (e.g., `src/components/WorkshopRoster.ts`). Edits to shared integration points (`main.ts`, `api.ts`, `types.ts`, `style.css`) should be strictly additive by default. If an unavoidable non-additive integration edit is required, Anne must document and justify it in her frozen self-audit. +4. **No Opportunistic Refactoring**: Anne is strictly prohibited from rewriting, reorganizing, or reformatting existing working components unless explicitly instructed by the Specification Contract. +5. **Self-Audit Regression Gate**: Anne's frozen self-audit must explicitly prove that existing tabs still render correctly and that the git diff is tightly bounded to the assigned feature. + +### 1.2 Incremental Implementation & Commit Discipline +Anne Droid owns the decomposition of the approved feature specification into coherent implementation increments. The Project Owner defines the required outcomes and acceptance criteria; the Orchestrator does not prescribe the implementation task sequence unless a specific dependency, risk, or contract constraint requires intervention. + +1. **Engineer-Owned Decomposition**: Before writing code, Anne identifies a practical sequence of implementation increments based on the approved contract and existing architecture. The sequence is an engineering breakdown, not a source of new product requirements. Missing requirements or consequential scope changes must be escalated rather than resolved through implementation planning alone. +2. **Coherent Incremental Commits**: Anne commits completed increments as work progresses. Each commit must have a clear purpose, a reviewable diff, and a Conventional Commit message describing the change (e.g., `feat(roster): add API client and roster types`, `feat(roster): implement session card and capacity indicators`). Commits must reflect genuine progress rather than arbitrary file boundaries or retrospective subdivision of a completed feature. +3. **Intermediate Integrity**: Each commit should leave the branch in a coherent state and pass the checks relevant to its changes (`pnpm exec biome check .`, `vp check`). The completed feature must pass the full required test suite. Any temporary intermediate limitation must be intentional, documented in commit notes, and resolved before the PR is submitted for review. +4. **Scope and Regression Boundaries**: Incremental commits do not authorize opportunistic refactoring or unrelated behavior changes. Changes to existing features and shared integration points remain subject to the Scope Containment & Non-Regression Invariant. +5. **Traceability and Review**: Anne's frozen self-audit must summarize the implementation increments, map commits to acceptance criteria, explain any justified deviations from the initial breakdown, and document any known limitations. The Orchestrator may flag incoherent commits, excessive unrelated changes, or gaps in traceability, but may not dictate implementation details solely to enforce a preferred task sequence. +6. **Integrated Verification**: Commit-level checks do not replace feature-level acceptance testing or independent QA. The complete pull request remains subject to the approved Specification Contract, Verification Packet, regression requirements, and Project Owner's release decision. + +### 1.3 Clarification on QA Failure Routing & Final Acceptance +- **QA owns its findings and supporting evidence**, not the release decision. +- If QA reports a failure on an acceptance criterion, the Orchestrator routes the defect back to Anne (for an implementation bug) or to the relevant specialist (for an API or requirement flaw). +- **The Orchestrator cannot waive a failure or convert a failed acceptance criterion into a pass.** Only the Project Owner has the authority to relax a requirement, accept a known risk, or authorize a PR merge. + +--- + +## 2. Phase-by-Phase Handoff Matrix + +| Phase | Acting Role | Required Input | Produced Output | Approval Gatekeeper | +| :------------------------------------ | :----------------------------------------- | :------------------------------------------- | :----------------------------------------------------------- | :------------------------------------------------ | +| **Phase 1: Operating Model** | Orchestrator | Pre-experiment baseline snapshot | `COLLABORATION-PLAN.md` | **Project Owner** (Signs off on roles) | +| **Phase 2: Contract Formulation** | Orchestrator (Requirements + UX synthesis) | API schema, M4 roadmap scope | `SPEC-WORKSHOP-ROSTER.md` + `VERIFICATION-PACKET-ROSTER.md` | **Project Owner** (Approves criteria & test data) | +| **Phase 3: Implementation** | Anne Droid | Approved spec + running API | `feat/anne/workshop-roster` PR + frozen `anne-self-audit.md` | **Anne Droid** (Freezes self-audit prior to QA) | +| **Phase 4: Independent Verification** | QA Specialist | Running build URL + Verification Packet ONLY | `qa-evidence-scorecard.md` | **QA Specialist** (Signs off on test evidence) | +| **Phase 5: Release & Post-Mortem** | Project Owner | PR diff + Anne Audit + QA Scorecard | Merge decision + Pilot evaluation log | **Project Owner** (Decides merge / rework) | + +--- + +## 3. Explicit Change & Escalation Protocol + +If any specialist encounters a blocking condition or contradiction, work halts at that boundary and routes strictly according to problem type: + +```mermaid +flowchart LR + BLOCK["Friction Encountered"] --> CAT{Classify Problem} + CAT -->|"Contradictory / Missing Business Rule"| REQ["Orchestrator / Requirements"] + CAT -->|"Unworkable Interaction Flow"| UX["Orchestrator / UX"] + CAT -->|"API Schema Defect / Backend 500"| BE["Backend Owner / Issue Tracker"] + CAT -->|"Implementation Bug"| ANNE["Anne Droid (Worktree)"] + CAT -->|"Ambiguous / Broken Test Criterion"| QA["Requirements + QA Specialist"] + CAT -->|"Scope Trade-off or Scope Relaxation"| PO["Project Owner (Human Decision)"] +``` + +1. **API Friction Rule**: Anne must record a structured **Contract Friction Notice** on the PR rather than silently creating synthetic mock data or changing expected response shapes. +2. **Owner Escalation Rule**: Any trade-off affecting user workflows (e.g. omitting walk-in check-ins due to API constraints) requires an explicit choice from the Project Owner. diff --git a/docs/pilot/SPEC-WORKSHOP-ROSTER.md b/docs/pilot/SPEC-WORKSHOP-ROSTER.md new file mode 100644 index 0000000..4638642 --- /dev/null +++ b/docs/pilot/SPEC-WORKSHOP-ROSTER.md @@ -0,0 +1,193 @@ +--- +type: plan +role: specification-contract +status: approved +project: armonia-dashboard +feature: workshop-roster-checkin +milestone: M4 +date: 2026-10-26 +tags: [spec, frontend, requirements, ux, armonia-dashboard] +--- + +# Specification Contract: Group Workshop Roster Quick Check-in + +> **Status:** Ratified Implementation Contract (Gate 2 Approved) +> **Contract Authority:** Binding implementation contract for `armonia-dashboard`. +> **Engineering Boundary:** This specification defines *what* the operator must accomplish and *how* states behave. The component breakdown, DOM composition, and styling implementation belong to Anne Droid's engineering judgment. Implementation must be strictly additive and isolated; existing features (Follow-up Queue, Daily Agenda, Client Directory, Nueva Cita) must remain undisturbed and 100% passing. + +--- + +## 1. Domain Context & User Goals + +In Armonía del Ser, group services (e.g., *Círculo de Cacao Presencial*, *Meditación con Cuencos*) take place with multiple attendees (up to 12–25 capacity). + +**The Operator's Goal:** +On the day of the workshop, Jasmin or her assistant stands at reception. As participants arrive, the operator needs a mobile-first, high-density view to: +1. Confirm which group workshop session is active today and review capacity metrics. +2. Rapidly record digital attendance (1-tap check-in marking attendance and completing the booking). +3. Identify payment state at a glance: identify who is pre-paid (`PAGADO` via SPEI) versus who must pay on arrival (`PENDIENTE`). +4. Collect cash on-site and acknowledge payment in the same 1-tap check-in action. +5. Register and check in unexpected walk-in attendees without disrupting the session flow. + +--- + +## 2. Precise Semantic Definitions & Status Mapping + +### 2.1 The Two Workshop Counters + +``` +┌────────────────────────────────────────────────────────────────────────┐ +│ Workshop Counter Semantics │ +├─────────────────────┬──────────────────────────────────────────────────┤ +│ Metric │ Business Meaning & Mutation Rules │ +├─────────────────────┼──────────────────────────────────────────────────┤ +│ occupied_count │ Total participants holding an active spot │ +│ │ (status: RESERVED, COMPLETED, NO_SHOW). │ +│ │ • Advance booking created: count increments. │ +│ │ • Existing attendee checks in: count UNCHANGED. │ +│ │ • Walk-in attendee registers: count increments. │ +├─────────────────────┼──────────────────────────────────────────────────┤ +│ attended_count │ Participants physically present & verified │ +│ │ (booking_status: COMPLETED, attended: true). │ +│ │ • Existing attendee checks in: count increments. │ +│ │ • Walk-in attendee registers: count increments. │ +└─────────────────────┴──────────────────────────────────────────────────┘ +``` + +- **Capacity Display**: Formatted as `Ocupación: {occupied_count} / {max_capacity} ({attended_count} presentes)`. +- **409 Conflict Disambiguation & Reconciliation Contract**: + The backend issues `HTTP 409 Conflict` in two distinct business scenarios, verified against pinned backend commit `d9c86e27d926` in `armonia-api/app/routers/rosters.py`. The client must inspect `response.detail` (or error payload): + 1. *Already Checked-In Conflict (`detail: "This attendee has already checked in."`)* (`app/routers/rosters.py#L196`): Indicates an idempotent duplicate submission. The client must reconcile by updating the attendee row to `ASISTIÓ`, disabling the check-in button, and showing an informative status toast (*"El asistente ya contaba con asistencia registrada"*). The client must never crash or treat this as a failed/unregistered state. + 2. *Capacity Exceeded Conflict (`detail: "El taller ha alcanzado su cupo máximo ({max_cap}) para esta sesión."`)* (`app/routers/rosters.py#L332`): Occurs during walk-in registration when `occupied_count >= max_capacity`. The client must detect the capacity message (e.g. matching `cupo máximo`), display an explicit capacity error alert (*"El taller ha alcanzado su cupo máximo (15) para esta sesión"*), keep the modal form state intact for operator decision, and **never** optimistically increment attendance or report success. +- **Ordinary Network / 500 Failure**: Preserve the current UI state, do not change attendee status, and allow the operator to retry. +- **Technical Debt & Future Contract Note**: String matching on `response.detail` is a pilot accommodation to preserve backend immutability on `armonia-api`. A future M5 ADR will introduce structured machine-readable error codes (e.g. `{"error_code": "ATTENDEE_ALREADY_CHECKED_IN"}`). + +### 2.2 Status Terminology Mapping Table + +To prevent ambiguity between UI labels and backend persistence, all badge renderings must adhere to this mapping: + +| UI Badge / Label | Visual Styling | Backend Entity | Persisted Status Field & Value | +| :--- | :--- | :--- | :--- | +| **`REGISTRADO`** | Slate/Neutral Pill | `Booking` | `booking_status: "RESERVED"`, `attended: false` | +| **`ASISTIÓ`** | Emerald/Green Pill | `Booking` | `booking_status: "COMPLETED"`, `attended: true` | +| **`PAGADO`** | Emerald/Green Pill | `Booking` & `Payment` | `payment_status: "ACKNOWLEDGED"` | +| **`PENDIENTE`** | Amber/Orange Pill | `Booking` | `payment_status: "AWAITING_ACKNOWLEDGMENT"` | + +--- + +## 3. Resilient Error-Recovery Contract (The 5 States) + +Every interactive view in this feature must explicitly handle the 5 states: + +```mermaid +stateDiagram + [*] --> Loading: Switch to #rosters tab + Loading --> Empty: GET /rosters returns [] + Loading --> Error_Roster: GET /rosters fails (Network/500) + Loading --> Roster_Ready: GET /rosters returns sessions + + Error_Roster --> Loading: Tap "Reintentar" + Empty --> Loading: Change date picker + + Roster_Ready --> Action_In_Flight: Tap Check-in or Submit Walk-in + Action_In_Flight --> Action_Error: POST fails (Timeout/Network) + Action_In_Flight --> Roster_Ready: POST succeeds (HTTP 200) -> Toast + Action_Error --> Roster_Ready: Toast error; row stays uncommitted +``` + +1. **Loading State**: Render skeleton placeholder cards for workshop sessions and attendee rows. Layout shift (CLS) must remain $\le 0.05$. +2. **Empty State**: If no group sessions exist for the selected date, display: + > *"No hay talleres grupales programados para esta fecha."* + The date selector remains interactive so the operator can navigate to adjacent days. +3. **Failed Roster Retrieval (Error with Retry)**: If `GET /rosters` fails (network down or server error), display an inline error banner: + > *"No se pudieron cargar los talleres. Verifica tu conexión."* + Accompanied by an explicit `` that re-triggers the fetch without a full page reload. +4. **Action Failure & Conflict Recovery**: + - *Already-Checked-In Conflict (409)*: If the server reports the attendee is already checked in, the client reconciles state by updating the row to `ASISTIÓ`, disabling check-in, and displaying an informative notice (*"El asistente ya contaba con asistencia registrada"*). + - *Capacity Reached Conflict (409)*: If a walk-in is rejected because the session is full, the client reports the capacity limit (*"El taller ha alcanzado su cupo máximo"*), leaves the form open for operator decision, and does not record attendance. + - *Network / Server Error (5xx / Timeout)*: The client displays an accessible error toast, preserves the uncommitted attendee row state (no optimistic toggle), and keeps the action button enabled for immediate retry. +5. **Success Feedback State**: Upon successful check-in or walk-in: + - Immediate visual feedback on the row (`ASISTIÓ` badge). + - Display an accessible toast container equipped with `role="status"` and `aria-live="polite"` announcing: *"Asistencia registrada con éxito."* + +--- + +## 4. Explicit Acceptance Criteria (AC) + +### `AC-1`: Workshop Session Selection & Capacity Overview +- **Given** the operator navigates to the "Talleres" tab (URL hash `#rosters`), +- **When** the view loads for the selected date (default: today), +- **Then** it queries `GET /rosters?date_from=YYYY-MM-DD&date_to=YYYY-MM-DD`. +- **And** it displays the group session title, scheduled time, and a capacity counter formatted as `Ocupación: {occupied_count} / {max_capacity} ({attended_count} presentes)`. + +### `AC-2`: Attendee Roster Display & Status Indicators +- **Given** an active workshop session with registered attendees, +- **When** the session roster renders, +- **Then** each attendee row displays: Client Name, Phone, Booking Code (`ADS-XXXX`), Attendance Status (`REGISTRADO` vs. `ASISTIÓ`), and Payment Status (`PAGADO` vs. `PENDIENTE`). +- **And** includes a 1-tap `wa.me` link pre-populated with the attendee's phone. + +### `AC-3`: Existing Booking Check-in (Pre-paid) +- **Given** an attendee with `booking_status: "RESERVED"` and `payment_status: "ACKNOWLEDGED"`, +- **When** the operator taps the "Registrar Asistencia" button, +- **Then** the client sends `POST /rosters/quick-checkin` with payload `{"booking_id": "", "paid_cash": false}`. +- **And** upon HTTP 200, the row immediately updates to `ASISTIÓ`, the check-in button disables, and `attended_count` increments by 1. + +### `AC-4`: Existing Booking Check-in with Cash Payment Acknowledgment +- **Given** an attendee with `payment_status: "AWAITING_ACKNOWLEDGMENT"`, +- **When** the operator taps check-in with "Cobro en efectivo recibido" checked, +- **Then** the client sends `POST /rosters/quick-checkin` with payload `{"booking_id": "", "paid_cash": true, "notes": "Cobro en puerta"}`. +- **And** upon HTTP 200, the row reflects both `ASISTIÓ` and `PAGADO` (`ACKNOWLEDGED`), and `attended_count` increments by 1 without full page reload. + +### `AC-5`: Walk-in Attendee Quick Registration & Check-in +- **Given** an unregistered participant arrives at the workshop, +- **When** the operator taps "+ Registrar Asistente Sin Cita", +- **Then** a modal opens requesting: Full Name, Phone (WhatsApp), and Cash Payment toggle (defaults to `true` / checked, because walk-in reception is predominantly cash). +- **When** submitted, the client sends `POST /rosters/quick-checkin` with Mode 2 payload: + `{"service_id": "", "scheduled_at": "", "client_name": "...", "client_phone": "...", "paid_cash": true}`. +- **And** upon HTTP 200, the modal closes, the attendee appears in the list as `ASISTIÓ` and `PAGADO`, and both `occupied_count` and `attended_count` increment by 1. +- **And** the modal submit button disables while in flight to prevent accidental double-click duplicate registrations. + +### `AC-6`: Resilient Error Handling & Retry +- **Given** an error state (failed roster fetch or interrupted check-in), +- **Then** the UI exposes an actionable retry path without clearing existing form data or falsely marking attendees present. + +### `AC-7`: Mobile Ergonomics & Keyboard Accessibility +- All interactive controls (Check-in buttons, Cash toggles, Walk-in trigger, Modal inputs) must have touch targets of at least **44x44px**. +- Roster rows must render cleanly at **375px** viewport width without horizontal scroll overflow. +- All interactive controls must support sequential keyboard focus (`Tab` / `Shift+Tab`) with visible `:focus-visible` outlines. +- Toast feedback must announce to assistive technology via `role="status"` and `aria-live="polite"`. + +--- +## 5. Navigation & Architectural Conventions + +1. **Tab Identifier**: `rosters` +2. **URL Hash**: `#rosters` +3. **Navigation Label**: "Talleres" +4. **Header Integration**: Integrated into `OperatorDashboardApp.renderShell()` in `src/main.ts` alongside `#queue`, `#agenda`, `#clients`, and `#all`. +5. **Cash Toggle Default**: In the walk-in modal, the "Cobro en efectivo recibido" toggle defaults to **checked (`true`)**. *Rationale:* In-person workshop walk-ins overwhelmingly settle entrance fees in cash at reception. Operators may uncheck if the client provides immediate SPEI transfer verification. + +--- + +## 6. API Contract Reference + +The view interacts strictly with existing endpoints defined in `armonia-api`: + +- **Endpoint 1:** `GET /rosters?date_from={YYYY-MM-DD}&date_to={YYYY-MM-DD}&service_id={optional}` + - *Response Shape:* `list[RosterSessionRead]` (see `app/schemas/roster.py`). +- **Endpoint 2:** `POST /rosters/quick-checkin` + - *Mode 1 (Existing Booking):* + ```json + { "booking_id": "uuid-str", "paid_cash": true, "notes": "Opcional" } + ``` + - *Mode 2 (Walk-In):* + ```json + { + "service_id": "uuid-str", + "scheduled_at": "2026-10-25T18:00:00Z", + "client_name": "Nombre Cliente", + "client_phone": "525512345678", + "paid_cash": true + } + ``` + - *Response:* `QuickCheckinResponse` (`walk_in: bool`, `attendee: RosterAttendeeRead`). + - *Conflict Behavior:* HTTP 409 Conflict if attendee already completed or session at max capacity. diff --git a/docs/pilot/VERIFICATION-PACKET-ROSTER.md b/docs/pilot/VERIFICATION-PACKET-ROSTER.md new file mode 100644 index 0000000..5317424 --- /dev/null +++ b/docs/pilot/VERIFICATION-PACKET-ROSTER.md @@ -0,0 +1,238 @@ +--- +type: plan +role: verification-packet +status: approved +project: armonia-dashboard +feature: workshop-roster-checkin +date: 2026-10-26 +tags: [qa, verification-packet, test-data, blind-testing] +--- + +# Verification Packet: Group Workshop Roster Quick Check-in + +> **Status:** Ratified Verification Contract (Gate 2 Approved) +> **Notice to Independent QA Reviewer:** This packet contains **all** instructions, test personas, and expected observable criteria needed to verify the feature. You must evaluate the running application *without* inspecting the pull request discussion, implementation source code, or the implementer's self-audit. + +--- + +## 1. Frozen Environment & Runtime Configuration + +Prior to executing test scenarios, verify that both services are running on the specified commits: + +| Component | Target Directory | Verified Commit Hash | Start Command | Active Port | +| :--- | :--- | :--- | :--- | :--- | +| **Backend API** | `armonia/armonia-api` | `d9c86e27d926bab3287857ccc9b53ec4fbcec91b` | `DATABASE_URL=file:test_armonia.db uv run python -m uvicorn app.main:app --port 8000` | `http://localhost:8000` | +| **Frontend UI** | `armonia/armonia-dashboard` | PR Branch (`feat/anne/workshop-roster`) | `pnpm exec vp dev --port 5173` | `http://localhost:5173` | + +--- + +## 2. Tested & Verified Test Database Seed Script with Preflight Assertions + +Run this command inside `armonia-api` using `uv run python`. It creates a clean disposable SQLite database (`test_armonia.db`), initializes default services, seeds the exact test records required for today's date, and **formally asserts all four preflight conditions** before completing: + +```bash +cd /home/kiskaadee/Projects/active/armonia/armonia-api && uv run python -c " +import os, asyncio +from datetime import datetime, UTC +from zoneinfo import ZoneInfo +from pathlib import Path + +# Deterministic absolute path anchoring +abs_db_path = (Path.cwd() / 'test_armonia.db').resolve() +assert abs_db_path.name.startswith('test_') and abs_db_path.name != 'local.db', 'Safety failure: refusal to touch non-test database' +if abs_db_path.exists(): + abs_db_path.unlink() + +os.environ['DATABASE_URL'] = f'file:{abs_db_path}' + +from app.core.config import settings +settings.database_url = f'file:{db_filename}' +from app.db.init_db import init_schema_and_seed +from app.db.database import get_db +from fastapi.testclient import TestClient +from app.main import app +from app.core.auth import create_session_token + +async def seed_and_verify(): + # 1. Initialize schema and default services + await init_schema_and_seed() + + async with get_db() as client: + # Preflight 1: Assert service exists with expected capacity of 15 + res = await client.execute('SELECT id, name, price_mxn, max_capacity FROM services WHERE slug = \"circulo-cacao-presencial\" LIMIT 1;') + assert res.rows, 'Preflight 1 Failed: circulo-cacao-presencial service not found!' + cacao_id, cacao_name, price_mxn, max_capacity = res.rows[0] + assert max_capacity == 15, f'Preflight 1 Failed: Expected capacity 15, got {max_capacity}' + + # Preflight 2: Calculate today's session instant at 18:00 + tz = ZoneInfo(settings.business_timezone) + today = datetime.now(tz).date() + today_str = today.isoformat() + session_dt = datetime(today.year, today.month, today.day, 18, 0, 0, tzinfo=tz).astimezone(UTC).isoformat() + now = datetime.now(UTC).isoformat() + + # Insert Elena Gómez (Prepaid SPEI: RESERVED + ACKNOWLEDGED) + client_elena = 'c1111111-1111-1111-1111-111111111111' + booking_elena = 'b1111111-1111-1111-1111-111111111111' + await client.execute('INSERT OR REPLACE INTO clients (id, full_name, phone_whatsapp, email) VALUES (?, ?, ?, ?);', + [client_elena, 'Elena Gómez', '525511112222', 'elena@example.com']) + await client.execute(''' + INSERT OR REPLACE INTO bookings ( + id, booking_code, service_id, client_id, scheduled_at, duration_minutes, buffer_minutes, + booking_status, payment_arrangement, payment_status, amount_mxn, created_at + ) VALUES (?, ?, ?, ?, ?, 120, 0, 'RESERVED', 'PREPAID_DEFAULT', 'ACKNOWLEDGED', ?, ?); + ''', [booking_elena, 'ADS-1001', cacao_id, client_elena, session_dt, price_mxn, now]) + + # Insert Carlos Méndez (Unpaid: RESERVED + AWAITING_ACKNOWLEDGMENT) + client_carlos = 'c2222222-2222-2222-2222-222222222222' + booking_carlos = 'b2222222-2222-2222-2222-222222222222' + await client.execute('INSERT OR REPLACE INTO clients (id, full_name, phone_whatsapp, email) VALUES (?, ?, ?, ?);', + [client_carlos, 'Carlos Méndez', '525533334444', 'carlos@example.com']) + await client.execute(''' + INSERT OR REPLACE INTO bookings ( + id, booking_code, service_id, client_id, scheduled_at, duration_minutes, buffer_minutes, + booking_status, payment_arrangement, payment_status, amount_mxn, created_at + ) VALUES (?, ?, ?, ?, ?, 120, 0, 'RESERVED', 'PREPAID_DEFAULT', 'AWAITING_ACKNOWLEDGMENT', ?, ?); + ''', [booking_carlos, 'ADS-1002', cacao_id, client_carlos, session_dt, price_mxn, now]) + + # Preflight 3: Endpoint level validation (assert endpoint returns exact expected session & attendees) + tc = TestClient(app) + headers = {'Authorization': f'Bearer {create_session_token(\"asistente@armoniadelser.mx\")}'} + r = tc.get(f'/rosters?date_from={today_str}&date_to={today_str}', headers=headers) + assert r.status_code == 200, f'Preflight 3 Failed: GET /rosters returned {r.status_code}' + data = r.json() + assert len(data) == 1, f'Preflight 3 Failed: Expected 1 session, got {len(data)}' + sess = data[0] + assert sess['occupied_count'] == 2 and sess['attended_count'] == 0, 'Preflight 3 Failed: Initial counts mismatch' + codes = {att['booking_code'] for att in sess['attendees']} + assert codes == {'ADS-1001', 'ADS-1002'}, f'Preflight 3 Failed: Missing expected codes {codes}' + + # Preflight 4: File existence & non-empty database target + assert abs_db_path.exists() and abs_db_path.stat().st_size > 0, 'Preflight 4 Failed: Database file missing or empty' + + print('✅ Preflight assertions passed: 100% verified test database ready at', abs_db_path) + +asyncio.run(seed_and_verify()) +" +``` + +--- + +## 3. Pre-Configured Test Attendee Personas + +| Attendee Persona | Initial Persisted State | Expected Initial UI Rendering | Expected Post-Action State | +| :--- | :--- | :--- | :--- | +| **Elena Gómez** (`ADS-1001`) | `booking_status: "RESERVED"`, `payment_status: "ACKNOWLEDGED"`, `attended: false` | Badge: `REGISTRADO`
Badge: `PAGADO` (Green)
Action: "Registrar Asistencia" | After check-in: Badge updates to `ASISTIÓ`. Counter increments to `1 presente`. | +| **Carlos Méndez** (`ADS-1002`) | `booking_status: "RESERVED"`, `payment_status: "AWAITING_ACKNOWLEDGMENT"`, `attended: false` | Badge: `REGISTRADO`
Badge: `PENDIENTE` (Amber)
Action: Check-in + "Cobro efectivo" | After cash check-in: Badge updates to `ASISTIÓ` AND `PAGADO`. Counter increments. | +| **Walk-in: Lucía Vega** | Not in database initially | Not present in list | After registration: Appears in list as `ASISTIÓ` and `PAGADO`. Occupancy becomes `3 / 15`. | + +--- + +## 4. Test Execution Scenarios & Concrete Pass/Fail Criteria + +### Scenario 1: Navigation, Tab Hash & Capacity Overview (`AC-1`) +1. Open `http://localhost:5173` in a desktop browser. +2. Click the "Talleres" navigation button in the top navigation bar. +3. **Pass Criteria:** + - [ ] URL updates to `http://localhost:5173/#rosters`. + - [ ] "Talleres" tab button reflects active state (`aria-selected="true"`). + - [ ] Session card for "Círculo de Cacao (Presencial)" renders with time 18:00. + - [ ] Capacity counter displays exactly: `Ocupación: 2 / 15 (0 presentes)`. + +### Scenario 2: Attendee Roster Display & Status Badges (`AC-2`) +1. Inspect the attendee table/list for the active workshop. +2. **Pass Criteria:** + - [ ] Elena Gómez is listed with booking code `ADS-1001`, status `REGISTRADO`, and payment pill `PAGADO`. + - [ ] Carlos Méndez is listed with booking code `ADS-1002`, status `REGISTRADO`, and payment pill `PENDIENTE`. + - [ ] Both rows display a clickable WhatsApp link (`wa.me/525511112222` and `wa.me/525533334444`). + +### Scenario 3: Pre-paid Attendee Check-in & Persistence Verification (`AC-3`) +1. On Elena Gómez's row (`ADS-1001`), tap "Registrar Asistencia". +2. **Pass Criteria (UI & Persistence):** + - [ ] Network inspector shows `POST /rosters/quick-checkin` returned HTTP 200 with payload `{"booking_id": "...", "paid_cash": false}`. + - [ ] Elena's status badge updates from `REGISTRADO` to `ASISTIÓ`. + - [ ] Capacity summary updates to `Ocupación: 2 / 15 (1 presentes)`. + - [ ] An accessible toast announces: *"Asistencia registrada con éxito."* + - [ ] **Persistence Proof:** Refresh the browser page (`F5`). Upon reload, Elena still renders as `ASISTIÓ` and capacity remains `1 presente`. + +### Scenario 4: Cash Check-in & Payment Status Transition (`AC-4`) +1. On Carlos Méndez's row (`ADS-1002`), trigger check-in with the "Cobro en efectivo recibido" checkbox checked. +2. **Pass Criteria (UI & Persistence):** + - [ ] Network inspector shows `POST /rosters/quick-checkin` returned HTTP 200 with `paid_cash: true`. + - [ ] Carlos's status badge updates to `ASISTIÓ`. + - [ ] Carlos's payment pill transitions from `PENDIENTE` to `PAGADO`. + - [ ] Capacity summary updates to `Ocupación: 2 / 15 (2 presentes)`. + - [ ] **Persistence Proof:** Refresh the browser page (`F5`). Carlos renders with both `ASISTIÓ` and `PAGADO`. + +### Scenario 5: Walk-In Registration & Double-Submission Prevention (`AC-5`) +1. Click the "+ Registrar Asistente Sin Cita" button. +2. In the modal: + - Full Name: `Lucía Vega` + - Phone: `525598765432` + - Cash toggle: confirm it defaults to **checked (`true`)**. +3. **Double-Submission Test**: Rapidly click "Registrar y Marcar Asistencia" twice in succession. +4. **Pass Criteria:** + - [ ] Submit button disables immediately while the request is in flight. + - [ ] Exactly **one** walk-in record is created (network inspector shows only one successful registration; second click is ignored or blocked). + - [ ] Modal closes upon HTTP 200. + - [ ] Lucía Vega appears in the active attendee list with `ASISTIÓ` and `PAGADO`. + - [ ] Capacity counter updates to exactly `Ocupación: 3 / 15 (3 presentes)` (NOT `4 / 15`). + - [ ] **Persistence Proof:** Refresh the browser (`F5`). Exactly one Lucía Vega record remains persisted in the roster. + +### Scenario 6: 409 Conflict Disambiguation & Reconciliation +1. **Case 6A (Already-Checked-In Idempotency)**: Trigger a duplicate check-in request via network replay or rapid re-tap for an already checked-in attendee (`ADS-1001`). + - **Pass Criteria:** + - [ ] Backend returns `HTTP 409 Conflict` (`"This attendee has already checked in."`). + - [ ] UI catches the 409, reconciles state, displays informative feedback (*"El asistente ya contaba con asistencia registrada"*), and ensures row reflects `ASISTIÓ` without unhandled application crash. +2. **Case 6B (Capacity Reached Conflict)**: When submitting a walk-in to a session at max capacity: + - **Pass Criteria:** + - [ ] Backend returns `HTTP 409 Conflict` (`"El taller ha alcanzado su cupo máximo"`). + - [ ] UI displays explicit capacity error alert; modal form data is preserved; row is **not** added to list. + +### Scenario 7: Failed Roster Fetch & Actionable Retry (`AC-6`) +1. Temporarily stop the backend API process (`Ctrl+C` on uvicorn). +2. Switch dates or refresh the `#rosters` view. +3. **Pass Criteria:** + - [ ] Error banner renders: *"No se pudieron cargar los talleres. Verifica tu conexión."* + - [ ] A visible "Reintentar" button is displayed. +4. Restart the backend API process. +5. Click "Reintentar". +6. **Pass Criteria:** + - [ ] Roster reloads successfully without needing a browser reload. + +### Scenario 8: Mobile Ergonomics & Accessibility Tree (`AC-7`) +1. Switch browser DevTools to Mobile Emulation: **375 x 812 px** (iPhone SE/X). +2. **Pass Criteria:** + - [ ] Zero horizontal scroll overflow on the table/cards. + - [ ] All check-in buttons, toggles, and modal inputs have minimum touch bounding boxes of **44 x 44 px**. +3. Navigate the view using only the keyboard (`Tab` and `Shift+Tab`). +4. **Pass Criteria:** + - [ ] Focus indicator is visibly highlighted on every active button and input. + - [ ] Toast notification container possesses `role="status"` and `aria-live="polite"`. + +--- + +## 5. Evidence Capture & Scorecard Deliverable + +The QA Specialist must produce `qa-evidence-scorecard.md` containing: +1. Formal table checking every criterion (`AC-1` to `AC-7`, Scenarios 1 to 8) with verdict: `PASS`, `FAIL`, or `BLOCKED`. +2. Captured screenshots attached: + - Desktop initial roster view. + - Mobile 375px view showing touch targets. + - Post-check-in state showing updated counter. + - Walk-in modal open state. +3. Browser console log confirming zero uncaught JavaScript exceptions. +4. If any test fails, record: Exact visual element, HTTP status, and response JSON payload. + +--- + +## 6. Reset & Cleanup Procedure + +To restore the test environment between verification passes: +```bash +# 1. Stop backend API (Ctrl+C) +# 2. Delete test database file +rm -f /home/kiskaadee/Projects/active/armonia/armonia-api/test_armonia.db +# 3. Re-run the seed script from Section 2 +# 4. Restart backend API +```