diff --git a/docs/evidence/anne-self-audit.md b/docs/evidence/anne-self-audit.md new file mode 100644 index 0000000..ef0d88c --- /dev/null +++ b/docs/evidence/anne-self-audit.md @@ -0,0 +1,144 @@ +# Frontend Implementation Self-Audit: Group Workshop Roster Quick Check-in + +> **Author:** Anne Droid +> **Role:** Senior Frontend Engineer & UX Specialist +> **Worktree:** `/home/kiskaadee/Projects/active/armonia/.worktrees/armonia-dashboard-anne-roster` +> **Branch:** `feat/anne/workshop-roster` +> **Date:** 2026-10-26 +> **Target Specification:** `docs/pilot/SPEC-WORKSHOP-ROSTER.md` +> **Collaboration Plan:** `docs/pilot/COLLABORATION-PLAN.md` + +--- + +## 1. Executive Summary + +The **Group Workshop Roster Quick Check-in** feature (`#rosters`, "Talleres") has been fully implemented, styled, verified, and frozen. + +The implementation strictly respects the Scope Containment Invariant: +1. Feature logic is isolated in `src/components/WorkshopRoster.ts` and tests in `tests/roster.test.ts`. +2. Edits to shared entry points (`src/main.ts`, `src/types.ts`, `src/api.ts`, and `src/style.css`) are strictly additive. +3. Zero regressions on existing views: `#queue` (48h follow-up queue), `#agenda` (daily agenda with buffers), `#clients` (directory), and the "Nueva Cita" intake modal remain 100% operational. +4. All 17 existing tests in `tests/utils.test.ts` pass alongside 12 new unit tests in `tests/roster.test.ts` (total: 29 tests passing). + +--- + +## 2. Commit Decomposition & Traceability Matrix + +| Commit | Scope & Summary | Addressed Acceptance Criteria | +| :--- | :--- | :--- | +| `0ff27a2` | `feat(roster): define API types and client methods for workshop rosters` | `AC-1`, `AC-3`, `AC-4`, `AC-5`, `AC-6` | +| `c09f6c6` | `feat(roster): add status badges, capacity formatting, and unit tests` | `AC-1`, `AC-2`, `AC-6` | +| `6ba0bbe` | `feat(roster): implement session cards, attendee list, and check-in workflows` | `AC-1`, `AC-2`, `AC-3`, `AC-4`, `AC-5`, `AC-6`, `AC-7` | +| `191a02d` | `feat(roster): integrate talleres tab in navigation and add responsive styles` | `AC-1`, `AC-7` | + +### Acceptance Criteria Verification Breakdown + +- **`AC-1`: Workshop Session Selection & Capacity Overview** + - Integrated tab `#rosters` ("Talleres") into desktop and sticky mobile navigation. + - Fetches `GET /rosters?date_from=YYYY-MM-DD&date_to=YYYY-MM-DD` defaulting to today (Mexico City timezone). + - Displays session title, scheduled time (e.g. `18:00 hrs`), and counter formatted exactly as: + `Ocupación: {occupied_count} / {max_capacity} ({attended_count} presentes)`. +- **`AC-2`: Attendee Roster Display & Status Indicators** + - Displays attendee client name, contact phone, booking code (`ADS-XXXX`). + - Attendance badge matches Section 2.2: `REGISTRADO` (slate pill) vs `ASISTIÓ` (emerald pill). + - Payment badge matches Section 2.2: `PAGADO` (emerald pill) vs `PENDIENTE` (amber pill). + - Clickable 1-tap WhatsApp link (`wa.me/52...`) pre-populated with cleaned attendee digits. +- **`AC-3`: Existing Booking Check-in (Pre-paid)** + - Tapping "Registrar Asistencia" sends `POST /rosters/quick-checkin` with payload `{"booking_id": "", "paid_cash": false}`. + - Upon HTTP 200, row immediately transitions to `ASISTIÓ`, check-in button disables, `attended_count` increments by 1, and accessible toast announces: *"Asistencia registrada con éxito."*. +- **`AC-4`: Existing Booking Check-in with Cash Payment Acknowledgment** + - When "Cobro en efectivo recibido" is checked, sends payload `{"booking_id": "", "paid_cash": true, "notes": "Cobro en puerta"}`. + - Upon HTTP 200, status badge transitions to `ASISTIÓ`, payment status transitions to `PAGADO`, and `attended_count` increments without full reload. +- **`AC-5`: Walk-in Attendee Quick Registration & Check-in** + - "+ Registrar Asistente Sin Cita" opens a dedicated modal with Full Name, Phone, Email, and Cash Payment toggle. + - Cash toggle defaults to **checked (`true`)** per section 5.5. + - Modal submit button disables immediately in flight (`disabled = true`, "Registrando...") to prevent duplicate submissions on double-click. + - Sends Mode 2 payload `{"service_id": "...", "scheduled_at": "...", "client_name": "...", "client_phone": "...", "paid_cash": true}`. + - Upon HTTP 200, closes modal, attendee appears in list as `ASISTIÓ` and `PAGADO`, and both `occupied_count` and `attended_count` increment by 1. +- **`AC-6`: Resilient Error Handling & Retry (409 Conflict Disambiguation)** + - *Case 6A (Already Checked-in 409)*: `detail` matching "already checked in" reconciles row to `ASISTIÓ`, disables button, and displays informative toast: *"El asistente ya contaba con asistencia registrada"*. + - *Case 6B (Capacity Exceeded 409)*: `detail` matching "cupo máximo" renders an explicit capacity error alert, preserves walk-in form inputs, and does NOT increment counts or report false success. + - *Failed Roster Fetch*: Displays inline error banner *"No se pudieron cargar los talleres. Verifica tu conexión."* with an explicit `Reintentar` button that re-triggers fetch. +- **`AC-7`: Mobile Ergonomics & Keyboard Accessibility** + - Minimum touch targets $\ge 44 \times 44\text{px}$ across check-in buttons, modal inputs, toggles, and nav pills. + - 375px viewport (iPhone SE/X) renders without horizontal scroll overflow. + - Visible `:focus-visible` outlines (`outline: 2px solid var(--color-sage)`). + - Toast notifications dispatched inside container equipped with `role="status"` and `aria-live="polite"`. + +--- + +## 3. Explicit Handling of the 5 Component States + +1. **Loading State**: + - Implemented via `.roster-skeleton-wrapper` rendering skeleton session cards and rows with subtle pulse animation, guaranteeing CLS $\le 0.05$. +2. **Empty State**: + - When `sessions.length === 0`, renders: + > *"No hay talleres grupales programados para esta fecha."* + - Date picker and quick filter pills ("Hoy", "Mañana") remain fully interactive. +3. **Error State with Actionable Retry**: + - If `GET /rosters` fails, renders inline error banner: + > *"No se pudieron cargar los talleres. Verifica tu conexión."* + - Includes `` allowing recovery without page reload. +4. **Partial / Conflict State (HTTP 409)**: + - Disambiguates duplicate attendance vs. capacity limit via `disambiguate409Error`. + - Preserves state and form inputs without crashing or corrupting client-side counters. +5. **Success State**: + - Immediate row update to `ASISTIÓ` (and `PAGADO` when cash collected). + - Capacity counter updates seamlessly. + - Screen-reader accessible toast announcement. + +--- + +## 4. Verification Evidence & Non-Regression Invariant + +### 4.1 Automated Toolchain Checks +- **Vitest Unit & Component Tests**: 29 passed (17 existing + 12 roster) + ``` + Test Files 2 passed (2) + Tests 29 passed (29) + ``` +- **TypeScript Typecheck**: + ``` + $ tsc --noEmit + Exit code: 0 + ``` +- **Biome Linter & Formatter**: + ``` + $ biome check . + Checked 23 files in 28ms. No fixes applied. + Exit code: 0 + ``` + +### 4.2 Non-Regression Smoke Verification +- `#queue` (Cola 48h): Loads and displays urgent follow-up badges and queue counters. +- `#agenda` (Agenda del Día): Visualizes chronologically with 15-minute buffer enforcement, stat pills, and rescheduling modal triggers. +- `#clients` (Directorio de Clientes): Search and client history intact. +- `+ Nueva Cita` Modal: Opens and captures intake fields cleanly. + +### 4.3 Captured Screenshots +- Desktop View (1280x800): `docs/screenshots/roster-desktop.png` +- Mobile View (375x812): `docs/screenshots/roster-mobile.png` + +--- + +## 5. Contract Friction Notices + +- **Notice 1 (String Matching on HTTP 409 detail)**: + As anticipated in Section 2.1 of `SPEC-WORKSHOP-ROSTER.md`, disambiguating between duplicate check-in (`"This attendee has already checked in."`) and session capacity (`"El taller ha alcanzado su cupo máximo..."`) relies on substring matching on `response.detail`. This is preserved as an accepted pilot accommodation to maintain backend immutability on `armonia-api`. An M5 ticket will introduce machine-readable error codes (`error_code`). + +--- + +## 6. Addendum: Post-Review Revision & Multi-Attendee 409 Server Reconciliation + +Following Project Owner review and QA verification of PR #9, targeted enhancements were implemented: +1. **Finding A: HTML Sanitization (`escapeHtml`)**: + - Introduced and exported `escapeHtml(str: string): string` in `src/components/WorkshopRoster.ts` (matching the pattern in `ClientDirectory.ts` and `IntakeModal.ts`). + - Sanitized all dynamic string interpolations (`attendee.client_name`, `attendee.client_phone`, `attendee.booking_code`, `session.service_name`, date strings, etc.) across visible text nodes and attribute values (`aria-label`, `title`, `href`, `data-booking-id`). +2. **Finding B & Case 2B: Authoritative Server Reconciliation on 409 Conflict**: + - Implemented `reconcileSessionsWithServer()` in `src/components/WorkshopRoster.ts`. + - When an `ALREADY_CHECKED_IN` 409 conflict occurs, the client now performs an authoritative refresh from `fetchRosters({ date_from, date_to })`, reconciling all sessions and attendees against server state and re-rendering the view. + - This ensures that if multiple attendees were checked in out-of-band across devices (Case 2B), the capacity counter immediately reflects the exact server count (e.g. `2 presentes`) and all checked-in attendees render with `ASISTIÓ`. If the refresh fetch fails, it gracefully falls back to local row reconciliation via `reconcileAlreadyCheckedInState()`. +3. **Verification**: + - Added unit test suites in `tests/roster.test.ts` validating HTML escaping (XSS vectors, attributes, plain strings), local state reconciliation, and authoritative multi-attendee out-of-band reconciliation (Case 2B). + - Test suite passes 100%: 34/34 tests passing (17 utils + 17 roster). + diff --git a/docs/screenshots/roster-desktop.png b/docs/screenshots/roster-desktop.png new file mode 100644 index 0000000..94ba1dd Binary files /dev/null and b/docs/screenshots/roster-desktop.png differ diff --git a/docs/screenshots/roster-mobile.png b/docs/screenshots/roster-mobile.png new file mode 100644 index 0000000..d5e1fe9 Binary files /dev/null and b/docs/screenshots/roster-mobile.png differ diff --git a/src/api.ts b/src/api.ts index 85c7c86..35f203a 100644 --- a/src/api.ts +++ b/src/api.ts @@ -10,6 +10,9 @@ import type { PackageRecord, PaymentAcknowledgmentPayload, PaymentRecord, + QuickCheckinPayload, + QuickCheckinResponse, + RosterSession, Service, } from "./types"; @@ -285,3 +288,61 @@ export async function fetchPackages( } return res.json(); } + +export class ApiError extends Error { + public status: number; + public detail?: string; + + constructor(status: number, message: string, detail?: string) { + super(message); + this.name = "ApiError"; + this.status = status; + this.detail = detail; + } +} + +export async function fetchRosters(params: { + date_from: string; + date_to: string; + service_id?: string; +}): Promise { + const query = new URLSearchParams(); + query.set("date_from", params.date_from); + query.set("date_to", params.date_to); + if (params.service_id) query.set("service_id", params.service_id); + + const url = `${API_BASE_URL}/rosters?${query.toString()}`; + const res = await fetch(url, { + headers: getAuthHeaders(), + }); + if (!res.ok) { + const errData = await res.json().catch(() => ({})); + const detail = errData.detail || `${res.status} ${res.statusText}`; + throw new ApiError( + res.status, + `Error al obtener talleres: ${detail}`, + errData.detail, + ); + } + return res.json(); +} + +export async function quickCheckin( + payload: QuickCheckinPayload, +): Promise { + const res = await fetch(`${API_BASE_URL}/rosters/quick-checkin`, { + method: "POST", + headers: getAuthHeaders(), + body: JSON.stringify(payload), + }); + if (!res.ok) { + const errData = await res.json().catch(() => ({})); + const detail = errData.detail || `${res.status} ${res.statusText}`; + throw new ApiError( + res.status, + `Error al registrar asistencia: ${detail}`, + errData.detail, + ); + } + return res.json(); +} diff --git a/src/components/WorkshopRoster.ts b/src/components/WorkshopRoster.ts new file mode 100644 index 0000000..8f46a14 --- /dev/null +++ b/src/components/WorkshopRoster.ts @@ -0,0 +1,941 @@ +import { ApiError, fetchRosters, quickCheckin } from "../api"; +import type { + QuickCheckinBookingPayload, + QuickCheckinWalkInPayload, + RosterAttendee, + RosterSession, +} from "../types"; +import { formatMexicanPhone, getCleanDigitsPhone } from "../utils"; +import { showToast } from "./Toast"; + +/** + * Format workshop session capacity label according to spec AC-1: + * "Ocupación: {occupied_count} / {max_capacity} ({attended_count} presentes)" + */ +export function formatRosterCapacity( + occupiedCount: number, + maxCapacity: number, + attendedCount: number, +): string { + return `Ocupación: ${occupiedCount} / ${maxCapacity} (${attendedCount} presentes)`; +} + +/** + * Render attendance status pill according to section 2.2: + * REGISTRADO (Slate/Neutral) vs ASISTIÓ (Emerald/Green) + */ +export function renderAttendanceStatusBadge( + attended: boolean, + bookingStatus?: string, +): string { + if (attended || bookingStatus === "COMPLETED") { + return 'ASISTIÓ'; + } + return 'REGISTRADO'; +} + +/** + * Render payment status pill according to section 2.2: + * PAGADO (Emerald/Green) vs PENDIENTE (Amber/Orange) + */ +export function renderPaymentStatusPill(paymentStatus: string): string { + if (paymentStatus === "ACKNOWLEDGED") { + return 'PAGADO'; + } + return 'PENDIENTE'; +} + +/** + * Build 1-tap WhatsApp click-to-chat URL + */ +export function buildWhatsAppUrl(phone: string): string { + const clean = getCleanDigitsPhone(phone); + return `https://wa.me/${clean}`; +} + +/** + * Format ISO datetime to 24-hour time in Mexico City timezone (e.g. 18:00) + */ +export function formatRosterSessionTime(isoStr: string): string { + try { + const dt = new Date(isoStr); + if (Number.isNaN(dt.getTime())) return isoStr; + return new Intl.DateTimeFormat("es-MX", { + timeZone: "America/Mexico_City", + hour: "2-digit", + minute: "2-digit", + hour12: false, + }).format(dt); + } catch { + return isoStr; + } +} + +/** + * Helper to get today's date formatted as YYYY-MM-DD in Mexico City timezone + */ +export function getTodayDateString(): string { + try { + const formatter = new Intl.DateTimeFormat("en-CA", { + timeZone: "America/Mexico_City", + year: "numeric", + month: "2-digit", + day: "2-digit", + }); + return formatter.format(new Date()); + } catch { + const d = new Date(); + const y = d.getFullYear(); + const m = String(d.getMonth() + 1).padStart(2, "0"); + const day = String(d.getDate()).padStart(2, "0"); + return `${y}-${m}-${day}`; + } +} + +export type ConflictType = + | "ALREADY_CHECKED_IN" + | "CAPACITY_EXCEEDED" + | "UNKNOWN"; + +/** + * Escape HTML characters to prevent XSS in template string interpolations + */ +export function escapeHtml(str: string): string { + return str + .replace(/&/g, "&") + .replace(//g, ">") + .replace(/"/g, """) + .replace(/'/g, "'"); +} + +/** + * Reconcile session state upon out-of-band 409 ALREADY_CHECKED_IN conflict. + * Ensures attendance status is COMPLETED / ASISTIÓ, and if the attendee was + * previously unrecorded locally, increments attended_count. + * Returns true if attended_count was incremented. + */ +export function reconcileAlreadyCheckedInState( + session: RosterSession, + attendee: RosterAttendee, +): boolean { + const wasAttended = + attendee.attended || attendee.booking_status === "COMPLETED"; + attendee.attended = true; + attendee.booking_status = "COMPLETED"; + if (!wasAttended) { + session.attended_count += 1; + return true; + } + return false; +} + +/** + * Reconcile local session state with authoritative server sessions. + * Matches sessions by service_id and scheduled_at to update counts and attendee records. + */ +export function reconcileSessionsWithServer( + currentSessions: RosterSession[], + freshSessions: RosterSession[], +): RosterSession[] { + if (!freshSessions || freshSessions.length === 0) { + return currentSessions; + } + return freshSessions.map((fresh) => { + const existing = currentSessions.find( + (curr) => + curr.service_id === fresh.service_id && + curr.scheduled_at === fresh.scheduled_at, + ); + if (!existing) return fresh; + return { + ...existing, + ...fresh, + attendees: fresh.attendees.map((freshAtt) => { + const existingAtt = existing.attendees.find( + (a) => a.booking_id === freshAtt.booking_id, + ); + return { + ...existingAtt, + ...freshAtt, + }; + }), + }; + }); +} + +/** + * Disambiguate HTTP 409 Conflict based on response detail + */ +export function disambiguate409Error(detail?: string): ConflictType { + if (!detail) return "UNKNOWN"; + const lower = detail.toLowerCase(); + if (lower.includes("already checked in")) { + return "ALREADY_CHECKED_IN"; + } + if (lower.includes("cupo máximo") || lower.includes("cupo maximo")) { + return "CAPACITY_EXCEEDED"; + } + return "UNKNOWN"; +} + +/** + * Main component renderer for the Group Workshop Roster view (#rosters) + */ +export function renderWorkshopRoster( + container: HTMLElement, + onStateChange?: () => void, +): void { + let selectedDate = getTodayDateString(); + let cachedSessions: RosterSession[] = []; + + container.innerHTML = ` +
+
+

Talleres Grupales & Control de Asistencia

+

Pase de lista digital, cobro en puerta y registro de asistentes sin cita.

+
+
+ +
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+ `; + + const contentEl = container.querySelector("#roster-content"); + const dateInput = + container.querySelector("#roster-date-input"); + const btnToday = + container.querySelector("#roster-btn-today"); + const btnTomorrow = container.querySelector( + "#roster-btn-tomorrow", + ); + const btnRefresh = container.querySelector( + "#refresh-roster-btn", + ); + + function updateDateFilterPills(dateStr: string) { + const today = getTodayDateString(); + const tomorrow = (() => { + const d = new Date(`${today}T12:00:00`); + d.setDate(d.getDate() + 1); + return d.toISOString().slice(0, 10); + })(); + + const isTodayActive = dateStr === today; + const isTomorrowActive = dateStr === tomorrow; + + btnToday?.classList.toggle("active", isTodayActive); + btnToday?.setAttribute("aria-selected", isTodayActive ? "true" : "false"); + + btnTomorrow?.classList.toggle("active", isTomorrowActive); + btnTomorrow?.setAttribute( + "aria-selected", + isTomorrowActive ? "true" : "false", + ); + + if (dateInput) { + dateInput.value = dateStr; + } + } + + async function loadSessions(): Promise { + if (!contentEl) return; + + // 1. Loading State: Skeleton cards preventing layout shift + renderLoadingSkeleton(contentEl); + + try { + const sessions = await fetchRosters({ + date_from: selectedDate, + date_to: selectedDate, + }); + cachedSessions = sessions; + + // 2. Empty State + if (sessions.length === 0) { + renderEmptyState(contentEl, selectedDate); + return; + } + + // 3. Success / Ready State + renderSessions(contentEl, cachedSessions); + } catch (err: unknown) { + // 4. Failed Roster Retrieval State with Actionable Retry + renderErrorState(contentEl, err); + } + } + + function renderLoadingSkeleton(target: HTMLElement): void { + target.innerHTML = ` +
+
+
+
+
+
+
+
+
+
+
+ `; + } + + function renderEmptyState(target: HTMLElement, dateStr: string): void { + target.innerHTML = ` +
+ +

Sin talleres programados

+

No hay talleres grupales programados para esta fecha.

+

Fecha seleccionada: ${escapeHtml(dateStr)}. Navega a otra fecha para consultar talleres.

+
+ `; + } + + function renderErrorState(target: HTMLElement, _error: unknown): void { + target.innerHTML = ` + + `; + + const retryBtn = + target.querySelector("#roster-retry-btn"); + retryBtn?.addEventListener("click", () => { + loadSessions(); + }); + } + + function renderSessions( + target: HTMLElement, + sessions: RosterSession[], + ): void { + target.innerHTML = ""; + + sessions.forEach((session, sessionIdx) => { + const card = document.createElement("div"); + card.className = "roster-session-card"; + card.setAttribute("data-session-idx", String(sessionIdx)); + + const timeStr = formatRosterSessionTime(session.scheduled_at); + const capacityText = formatRosterCapacity( + session.occupied_count, + session.max_capacity, + session.attended_count, + ); + + card.innerHTML = ` +
+
+ ⏰ ${escapeHtml(timeStr)} hrs +

${escapeHtml(session.service_name)}

+
+
+ + ${capacityText} + + +
+
+ +
+ ${renderAttendeesList(session, sessionIdx)} +
+ `; + + target.appendChild(card); + }); + + bindSessionCardEvents(target); + } + + function renderAttendeesList( + session: RosterSession, + sessionIdx: number, + ): string { + if (session.attendees.length === 0) { + return ` +
+

Aún no hay asistentes registrados para esta sesión.

+
+ `; + } + + const rowsHtml = session.attendees + .map((attendee, attIdx) => { + const isAttended = + attendee.attended || attendee.booking_status === "COMPLETED"; + const waUrl = buildWhatsAppUrl(attendee.client_phone); + const formattedPhone = formatMexicanPhone(attendee.client_phone); + const cleanPhoneDigits = getCleanDigitsPhone(attendee.client_phone); + + const attendanceBadge = renderAttendanceStatusBadge( + isAttended, + attendee.booking_status, + ); + const paymentBadge = renderPaymentStatusPill(attendee.payment_status); + + let actionHtml = ""; + if (isAttended) { + actionHtml = ` + + `; + } else if (attendee.payment_status === "AWAITING_ACKNOWLEDGMENT") { + actionHtml = ` +
+ + +
+ `; + } else { + // Pre-paid attendee (ACKNOWLEDGED) + actionHtml = ` +
+ +
+ `; + } + + return ` +
+
+ ${escapeHtml(attendee.client_name)} + ${escapeHtml(attendee.booking_code)} +
+ +
+ ${escapeHtml(formattedPhone)} + + + + +
+ +
+
${attendanceBadge}
+
${paymentBadge}
+
+ +
+ ${actionHtml} +
+
+ `; + }) + .join(""); + + return `
${rowsHtml}
`; + } + + function bindSessionCardEvents(target: HTMLElement): void { + // 1. Walk-in registration trigger + const walkinButtons = + target.querySelectorAll(".btn-walkin"); + walkinButtons.forEach((btn) => { + btn.addEventListener("click", () => { + const sessionIdx = Number(btn.getAttribute("data-session-idx")); + const session = cachedSessions[sessionIdx]; + if (session) { + openWalkInModal(session, sessionIdx); + } + }); + }); + + // 2. Quick Check-in trigger for existing attendees + const checkinButtons = target.querySelectorAll( + ".btn-checkin:not([disabled])", + ); + checkinButtons.forEach((btn) => { + btn.addEventListener("click", async () => { + const sessionIdx = Number(btn.getAttribute("data-session-idx")); + const attIdx = Number(btn.getAttribute("data-att-idx")); + const bookingId = btn.getAttribute("data-booking-id"); + if (!bookingId) return; + + const session = cachedSessions[sessionIdx]; + const attendee = session?.attendees[attIdx]; + if (!session || !attendee) return; + + // Determine if cash was checked + const rowEl = btn.closest(".roster-attendee-row"); + const cashCheckbox = + rowEl?.querySelector(".cash-checkbox"); + const isCashChecked = cashCheckbox?.checked ?? false; + + await handleExistingCheckin({ + button: btn, + rowEl: rowEl as HTMLElement, + session, + sessionIdx, + attendee, + paidCash: isCashChecked, + }); + }); + }); + } + + async function handleExistingCheckin(params: { + button: HTMLButtonElement; + rowEl: HTMLElement | null; + session: RosterSession; + sessionIdx: number; + attendee: RosterAttendee; + paidCash: boolean; + }): Promise { + const { button, rowEl, session, sessionIdx, attendee, paidCash } = params; + + // Disable button during in-flight action + button.disabled = true; + const originalText = button.textContent; + button.textContent = "Registrando..."; + + const payload: QuickCheckinBookingPayload = { + booking_id: attendee.booking_id, + paid_cash: paidCash, + notes: paidCash ? "Cobro en puerta" : undefined, + }; + + try { + await quickCheckin(payload); + + // Mutate local state + attendee.attended = true; + attendee.booking_status = "COMPLETED"; + if (paidCash) { + attendee.payment_status = "ACKNOWLEDGED"; + } + session.attended_count += 1; + + // Update UI + updateRowAttendanceState(rowEl, attendee); + updateCapacityDisplay(session, sessionIdx); + + showToast("Asistencia registrada con éxito.", "success"); + onStateChange?.(); + } catch (err: unknown) { + const apiError = err instanceof ApiError ? err : null; + const detail = + apiError?.detail || (err instanceof Error ? err.message : ""); + const conflictType = disambiguate409Error(detail); + + if (conflictType === "ALREADY_CHECKED_IN") { + // 409 Case A: Authoritative server state reconciliation + try { + const freshSessions = await fetchRosters({ + date_from: selectedDate, + date_to: selectedDate, + }); + cachedSessions = reconcileSessionsWithServer( + cachedSessions, + freshSessions, + ); + if (contentEl) { + renderSessions(contentEl, cachedSessions); + } + } catch { + // Fallback to local row reconciliation if refresh fetch fails + const incremented = reconcileAlreadyCheckedInState(session, attendee); + if (incremented) { + updateCapacityDisplay(session, sessionIdx); + } + updateRowAttendanceState(rowEl, attendee); + } + + showToast("El asistente ya contaba con asistencia registrada", "info"); + onStateChange?.(); + } else { + // Ordinary failure / timeout + button.disabled = false; + button.textContent = originalText; + showToast( + apiError?.detail || + "Error al registrar asistencia. Intenta nuevamente.", + "error", + ); + } + } + } + + function updateRowAttendanceState( + rowEl: HTMLElement | null, + attendee: RosterAttendee, + ): void { + if (!rowEl) return; + rowEl.classList.add("row-attended"); + + const attBadgeSlot = rowEl.querySelector(".badge-slot-attendance"); + if (attBadgeSlot) { + attBadgeSlot.innerHTML = renderAttendanceStatusBadge(true, "COMPLETED"); + } + + if (attendee.payment_status === "ACKNOWLEDGED") { + const pBadgeSlot = rowEl.querySelector(".badge-slot-payment"); + if (pBadgeSlot) { + pBadgeSlot.innerHTML = renderPaymentStatusPill("ACKNOWLEDGED"); + } + } + + const actionCol = rowEl.querySelector(".attendee-col-actions"); + if (actionCol) { + actionCol.innerHTML = ` + + `; + } + } + + function updateCapacityDisplay( + session: RosterSession, + sessionIdx: number, + ): void { + const counterEl = container.querySelector( + `#capacity-counter-${sessionIdx}`, + ); + if (counterEl) { + counterEl.textContent = formatRosterCapacity( + session.occupied_count, + session.max_capacity, + session.attended_count, + ); + } + } + + function openWalkInModal(session: RosterSession, sessionIdx: number): void { + const existingBackdrop = document.getElementById("walkin-modal-backdrop"); + if (existingBackdrop) existingBackdrop.remove(); + + const timeStr = formatRosterSessionTime(session.scheduled_at); + const backdrop = document.createElement("div"); + backdrop.id = "walkin-modal-backdrop"; + backdrop.className = "modal-backdrop"; + + backdrop.innerHTML = ` + + `; + + document.body.appendChild(backdrop); + + const close = () => { + backdrop.remove(); + document.removeEventListener("keydown", handleKeyDown); + }; + + const handleKeyDown = (e: KeyboardEvent) => { + if (e.key === "Escape") close(); + }; + document.addEventListener("keydown", handleKeyDown); + + backdrop + .querySelector("#walkin-modal-close") + ?.addEventListener("click", () => close()); + backdrop + .querySelector("#walkin-modal-cancel") + ?.addEventListener("click", () => close()); + backdrop.addEventListener("click", (e) => { + if (e.target === backdrop) close(); + }); + + const form = backdrop.querySelector("#walkin-modal-form"); + const nameInput = backdrop.querySelector("#walkin-name"); + const phoneInput = + backdrop.querySelector("#walkin-phone"); + const emailInput = + backdrop.querySelector("#walkin-email"); + const cashCheckbox = + backdrop.querySelector("#walkin-cash"); + const submitBtn = backdrop.querySelector( + "#walkin-modal-submit", + ); + const errorBox = backdrop.querySelector( + "#walkin-modal-error", + ); + + nameInput?.focus(); + + form?.addEventListener("submit", async (e) => { + e.preventDefault(); + if (!submitBtn || !errorBox) return; + + // Double-submission prevention: Immediately disable button while in-flight + submitBtn.disabled = true; + submitBtn.textContent = "Registrando..."; + errorBox.classList.add("hidden"); + errorBox.textContent = ""; + + const clientName = nameInput?.value.trim() ?? ""; + const clientPhone = phoneInput?.value.trim() ?? ""; + const clientEmail = emailInput?.value.trim() || undefined; + const paidCash = cashCheckbox?.checked ?? true; + + const payload: QuickCheckinWalkInPayload = { + service_id: session.service_id, + scheduled_at: session.scheduled_at, + client_name: clientName, + client_phone: clientPhone, + client_email: clientEmail, + paid_cash: paidCash, + notes: paidCash ? "Cobro en puerta (Walk-in)" : undefined, + }; + + try { + const response = await quickCheckin(payload); + + // Mutation on local model + session.occupied_count += 1; + session.attended_count += 1; + session.attendees.push(response.attendee); + + // Re-render session capacity counter and attendees list + updateCapacityDisplay(session, sessionIdx); + const containerEl = container.querySelector( + `#attendees-container-${sessionIdx}`, + ); + if (containerEl) { + containerEl.innerHTML = renderAttendeesList(session, sessionIdx); + bindSessionCardEvents(container); + } + + close(); + showToast("Asistencia registrada con éxito.", "success"); + onStateChange?.(); + } catch (err: unknown) { + const apiError = err instanceof ApiError ? err : null; + const detail = + apiError?.detail || (err instanceof Error ? err.message : ""); + const conflictType = disambiguate409Error(detail); + + submitBtn.disabled = false; + submitBtn.textContent = "Registrar y Marcar Asistencia"; + + if (conflictType === "CAPACITY_EXCEEDED") { + // 409 Case B: Capacity reached. Preserve form inputs, show error + errorBox.textContent = + apiError?.detail || + "El taller ha alcanzado su cupo máximo para esta sesión."; + errorBox.classList.remove("hidden"); + } else { + errorBox.textContent = + apiError?.detail || + (err instanceof Error + ? err.message + : "Error al registrar asistente sin cita"); + errorBox.classList.remove("hidden"); + } + } + }); + } + + // Navigation bindings + btnToday?.addEventListener("click", () => { + const today = getTodayDateString(); + if (selectedDate !== today) { + selectedDate = today; + updateDateFilterPills(selectedDate); + loadSessions(); + } + }); + + btnTomorrow?.addEventListener("click", () => { + const today = getTodayDateString(); + const d = new Date(`${today}T12:00:00`); + d.setDate(d.getDate() + 1); + const tomorrow = d.toISOString().slice(0, 10); + if (selectedDate !== tomorrow) { + selectedDate = tomorrow; + updateDateFilterPills(selectedDate); + loadSessions(); + } + }); + + dateInput?.addEventListener("change", () => { + if (dateInput.value && dateInput.value !== selectedDate) { + selectedDate = dateInput.value; + updateDateFilterPills(selectedDate); + loadSessions(); + } + }); + + btnRefresh?.addEventListener("click", () => { + loadSessions(); + }); + + // Initial load + updateDateFilterPills(selectedDate); + loadSessions(); +} diff --git a/src/main.ts b/src/main.ts index 9bff54d..ca25e4b 100644 --- a/src/main.ts +++ b/src/main.ts @@ -5,9 +5,10 @@ import { renderClientDirectory } from "./components/ClientDirectory"; import { renderDailyAgenda } from "./components/DailyAgenda"; import { renderFollowUpQueue } from "./components/FollowUpQueue"; import { openBookingIntakeModal } from "./components/IntakeModal"; +import { renderWorkshopRoster } from "./components/WorkshopRoster"; import { getRoleBadge } from "./utils"; -type TabId = "queue" | "agenda" | "clients" | "all"; +type TabId = "queue" | "agenda" | "clients" | "all" | "rosters"; class OperatorDashboardApp { private activeTab: TabId = "queue"; @@ -40,7 +41,10 @@ class OperatorDashboardApp { }); } else { const initialTab = - hash === "agenda" || hash === "clients" || hash === "all" + hash === "agenda" || + hash === "clients" || + hash === "all" || + hash === "rosters" ? hash : "queue"; this.switchTab(initialTab); @@ -87,6 +91,9 @@ class OperatorDashboardApp { + @@ -109,6 +116,10 @@ class OperatorDashboardApp { Agenda +