Merge pull request 'feat(roster): Group Workshop Roster Quick Check-in' (#9) from feat/anne/workshop-roster into main

This commit was merged in pull request #9.
This commit is contained in:
kiskaadee committed 2026-10-29 13:39:28 -05:00
commit 0098b5214c
9 files changed
+1916 -2

No files matched your search

+144
View File
@@ -0,0 +1,144 @@
# Frontend Implementation Self-Audit: Group Workshop Roster Quick Check-in
> **Author:** Anne Droid <anne-droid@roadtotech.me>
> **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": "<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": "<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 `<button class="btn btn-secondary" id="roster-retry-btn">Reintentar</button>` 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).
Binary file not shown.

After

Width:  |  Height:  |  Size: 87 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 62 KiB

+61
View File
@@ -10,6 +10,9 @@ import type {
PackageRecord, PackageRecord,
PaymentAcknowledgmentPayload, PaymentAcknowledgmentPayload,
PaymentRecord, PaymentRecord,
QuickCheckinPayload,
QuickCheckinResponse,
RosterSession,
Service, Service,
} from "./types"; } from "./types";
@@ -285,3 +288,61 @@ export async function fetchPackages(
} }
return res.json(); 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<RosterSession[]> {
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<QuickCheckinResponse> {
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();
}
+941
View File
@@ -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 '<span class="status-pill status-roster-attended">ASISTIÓ</span>';
}
return '<span class="status-pill status-roster-registered">REGISTRADO</span>';
}
/**
* 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 '<span class="status-pill status-roster-paid">PAGADO</span>';
}
return '<span class="status-pill status-roster-pending">PENDIENTE</span>';
}
/**
* 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, "&amp;")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;")
.replace(/"/g, "&quot;")
.replace(/'/g, "&#039;");
}
/**
* 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 = `
<div class="view-header">
<div>
<h2 class="view-title">Talleres Grupales & Control de Asistencia</h2>
<p class="view-subtitle">Pase de lista digital, cobro en puerta y registro de asistentes sin cita.</p>
</div>
<div class="view-actions">
<button id="refresh-roster-btn" class="btn btn-secondary btn-sm" title="Refrescar lista de talleres" type="button">
↻ Actualizar
</button>
</div>
</div>
<!-- Date Navigation & Filter Bar -->
<div class="roster-nav-bar">
<div class="date-filter-group" role="tablist" aria-label="Filtro rápido de fecha">
<button type="button" class="btn btn-filter-pill active" id="roster-btn-today" role="tab" aria-selected="true">
Hoy
</button>
<button type="button" class="btn btn-filter-pill" id="roster-btn-tomorrow" role="tab" aria-selected="false">
Mañana
</button>
</div>
<div class="custom-date-container">
<label for="roster-date-input" class="text-xs text-muted font-medium">Fecha:</label>
<input
type="date"
id="roster-date-input"
class="form-input-date"
value="${escapeHtml(selectedDate)}"
aria-label="Seleccionar fecha de talleres"
/>
</div>
</div>
<!-- Main Dynamic Content Container -->
<div id="roster-content" class="roster-content-area" aria-live="polite"></div>
`;
const contentEl = container.querySelector<HTMLElement>("#roster-content");
const dateInput =
container.querySelector<HTMLInputElement>("#roster-date-input");
const btnToday =
container.querySelector<HTMLButtonElement>("#roster-btn-today");
const btnTomorrow = container.querySelector<HTMLButtonElement>(
"#roster-btn-tomorrow",
);
const btnRefresh = container.querySelector<HTMLButtonElement>(
"#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<void> {
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 = `
<div class="roster-skeleton-wrapper" aria-busy="true" aria-label="Cargando talleres...">
<div class="roster-session-card skeleton-card">
<div class="skeleton-line skeleton-title"></div>
<div class="skeleton-line skeleton-meta"></div>
<div class="skeleton-table">
<div class="skeleton-line skeleton-row"></div>
<div class="skeleton-line skeleton-row"></div>
<div class="skeleton-line skeleton-row"></div>
</div>
</div>
</div>
`;
}
function renderEmptyState(target: HTMLElement, dateStr: string): void {
target.innerHTML = `
<div class="empty-state roster-empty-state">
<div class="empty-icon" aria-hidden="true">🪷</div>
<h3 class="empty-title">Sin talleres programados</h3>
<p class="empty-message">No hay talleres grupales programados para esta fecha.</p>
<p class="text-xs text-muted mt-2">Fecha seleccionada: ${escapeHtml(dateStr)}. Navega a otra fecha para consultar talleres.</p>
</div>
`;
}
function renderErrorState(target: HTMLElement, _error: unknown): void {
target.innerHTML = `
<div class="error-state roster-error-state" role="alert">
<div class="error-box-card">
<div class="error-icon" aria-hidden="true">⚠️</div>
<div class="error-content">
<h3 class="font-bold text-base">Error al consultar los talleres</h3>
<p class="error-banner-message">No se pudieron cargar los talleres. Verifica tu conexión.</p>
</div>
<button type="button" id="roster-retry-btn" class="btn btn-secondary">
Reintentar
</button>
</div>
</div>
`;
const retryBtn =
target.querySelector<HTMLButtonElement>("#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 = `
<div class="session-card-header">
<div class="session-title-block">
<span class="session-time-pill" title="Horario del taller">⏰ ${escapeHtml(timeStr)} hrs</span>
<h3 class="session-title">${escapeHtml(session.service_name)}</h3>
</div>
<div class="session-header-actions">
<span class="session-capacity-counter font-mono font-medium" id="capacity-counter-${sessionIdx}">
${capacityText}
</span>
<button
type="button"
class="btn btn-primary btn-sm btn-walkin"
data-session-idx="${sessionIdx}"
title="Registrar participante sin reservación previa"
>
+ Registrar Asistente Sin Cita
</button>
</div>
</div>
<div class="session-attendees-container" id="attendees-container-${sessionIdx}">
${renderAttendeesList(session, sessionIdx)}
</div>
`;
target.appendChild(card);
});
bindSessionCardEvents(target);
}
function renderAttendeesList(
session: RosterSession,
sessionIdx: number,
): string {
if (session.attendees.length === 0) {
return `
<div class="attendees-empty-notice">
<p class="text-sm text-muted">Aún no hay asistentes registrados para esta sesión.</p>
</div>
`;
}
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 = `
<button type="button" class="btn btn-secondary btn-sm btn-checkin" disabled aria-disabled="true">
✓ Asistió
</button>
`;
} else if (attendee.payment_status === "AWAITING_ACKNOWLEDGMENT") {
actionHtml = `
<div class="checkin-action-group">
<label class="cash-toggle-label" for="cash-check-${sessionIdx}-${attIdx}">
<input
type="checkbox"
id="cash-check-${sessionIdx}-${attIdx}"
class="cash-checkbox"
data-booking-id="${escapeHtml(attendee.booking_id)}"
/>
<span class="text-xs">Cobro en efectivo recibido</span>
</label>
<button
type="button"
class="btn btn-primary btn-sm btn-checkin"
data-session-idx="${sessionIdx}"
data-att-idx="${attIdx}"
data-booking-id="${escapeHtml(attendee.booking_id)}"
>
Registrar Asistencia
</button>
</div>
`;
} else {
// Pre-paid attendee (ACKNOWLEDGED)
actionHtml = `
<div class="checkin-action-group">
<button
type="button"
class="btn btn-primary btn-sm btn-checkin"
data-session-idx="${sessionIdx}"
data-att-idx="${attIdx}"
data-booking-id="${escapeHtml(attendee.booking_id)}"
>
Registrar Asistencia
</button>
</div>
`;
}
return `
<div class="roster-attendee-row ${isAttended ? "row-attended" : ""}" data-booking-id="${escapeHtml(attendee.booking_id)}">
<div class="attendee-col-client">
<span class="attendee-name font-medium">${escapeHtml(attendee.client_name)}</span>
<span class="attendee-code font-mono">${escapeHtml(attendee.booking_code)}</span>
</div>
<div class="attendee-col-phone">
<span class="attendee-phone-text">${escapeHtml(formattedPhone)}</span>
<a
href="${escapeHtml(waUrl)}"
target="_blank"
rel="noopener noreferrer"
class="btn-wa-link"
title="Abrir chat en WhatsApp"
aria-label="Contactar a ${escapeHtml(attendee.client_name)} por WhatsApp"
>
<span class="wa-icon" aria-hidden="true">💬</span>
<span class="wa-label font-mono text-xs">wa.me/${escapeHtml(cleanPhoneDigits)}</span>
</a>
</div>
<div class="attendee-col-badges">
<div class="badge-slot-attendance">${attendanceBadge}</div>
<div class="badge-slot-payment">${paymentBadge}</div>
</div>
<div class="attendee-col-actions">
${actionHtml}
</div>
</div>
`;
})
.join("");
return `<div class="roster-attendees-table">${rowsHtml}</div>`;
}
function bindSessionCardEvents(target: HTMLElement): void {
// 1. Walk-in registration trigger
const walkinButtons =
target.querySelectorAll<HTMLButtonElement>(".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<HTMLButtonElement>(
".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<HTMLInputElement>(".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<void> {
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 = `
<button type="button" class="btn btn-secondary btn-sm btn-checkin" disabled aria-disabled="true">
✓ Asistió
</button>
`;
}
}
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 = `
<div class="modal-card" role="dialog" aria-modal="true" aria-labelledby="walkin-modal-title">
<div class="modal-header">
<div>
<span class="modal-kicker">Asistencia Inmediata</span>
<h3 id="walkin-modal-title" class="modal-title">Registrar Asistente Sin Cita</h3>
</div>
<button type="button" class="modal-close-btn" id="walkin-modal-close" aria-label="Cerrar ventana">&times;</button>
</div>
<div class="modal-body">
<div class="summary-box">
<div class="summary-row">
<span class="summary-label">Taller:</span>
<span class="summary-value font-medium">${escapeHtml(session.service_name)}</span>
</div>
<div class="summary-row">
<span class="summary-label">Horario:</span>
<span class="summary-value font-mono font-bold">${escapeHtml(timeStr)} hrs</span>
</div>
<div class="summary-row">
<span class="summary-label">Capacidad Actual:</span>
<span class="summary-value">${session.occupied_count} / ${session.max_capacity}</span>
</div>
</div>
<form id="walkin-modal-form" class="modal-form-content">
<div class="form-group">
<label for="walkin-name" class="form-label">
Nombre Completo <span class="text-danger">*</span>
</label>
<input
type="text"
id="walkin-name"
name="client_name"
class="form-input"
placeholder="Ej. Lucía Vega"
required
autocomplete="name"
/>
</div>
<div class="form-group">
<label for="walkin-phone" class="form-label">
Teléfono WhatsApp (10 o 12 dígitos) <span class="text-danger">*</span>
</label>
<input
type="tel"
id="walkin-phone"
name="client_phone"
class="form-input"
placeholder="Ej. 525598765432 o 5598765432"
required
autocomplete="tel"
/>
</div>
<div class="form-group">
<label for="walkin-email" class="form-label">
Correo Electrónico (Opcional)
</label>
<input
type="email"
id="walkin-email"
name="client_email"
class="form-input"
placeholder="cliente@ejemplo.com"
autocomplete="email"
/>
</div>
<!-- Section 5.5: Cash Toggle defaults to TRUE (checked) -->
<div class="form-group mt-3">
<label class="form-checkbox-label" for="walkin-cash">
<input
type="checkbox"
id="walkin-cash"
name="paid_cash"
class="form-checkbox"
checked
/>
<span class="font-medium text-sm">Cobro en efectivo recibido</span>
</label>
<p class="text-xs text-muted mt-1" style="margin-left: 28px;">
Registra el cobro en efectivo en puerta y acredita el pago automáticamente.
</p>
</div>
<div id="walkin-modal-error" class="modal-error-box hidden" role="alert"></div>
<div class="modal-actions">
<button type="button" id="walkin-modal-cancel" class="btn btn-secondary">
Cancelar
</button>
<button type="submit" id="walkin-modal-submit" class="btn btn-primary">
Registrar y Marcar Asistencia
</button>
</div>
</form>
</div>
</div>
`;
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<HTMLFormElement>("#walkin-modal-form");
const nameInput = backdrop.querySelector<HTMLInputElement>("#walkin-name");
const phoneInput =
backdrop.querySelector<HTMLInputElement>("#walkin-phone");
const emailInput =
backdrop.querySelector<HTMLInputElement>("#walkin-email");
const cashCheckbox =
backdrop.querySelector<HTMLInputElement>("#walkin-cash");
const submitBtn = backdrop.querySelector<HTMLButtonElement>(
"#walkin-modal-submit",
);
const errorBox = backdrop.querySelector<HTMLDivElement>(
"#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();
}
+16 -2
View File
@@ -5,9 +5,10 @@ import { renderClientDirectory } from "./components/ClientDirectory";
import { renderDailyAgenda } from "./components/DailyAgenda"; import { renderDailyAgenda } from "./components/DailyAgenda";
import { renderFollowUpQueue } from "./components/FollowUpQueue"; import { renderFollowUpQueue } from "./components/FollowUpQueue";
import { openBookingIntakeModal } from "./components/IntakeModal"; import { openBookingIntakeModal } from "./components/IntakeModal";
import { renderWorkshopRoster } from "./components/WorkshopRoster";
import { getRoleBadge } from "./utils"; import { getRoleBadge } from "./utils";
type TabId = "queue" | "agenda" | "clients" | "all"; type TabId = "queue" | "agenda" | "clients" | "all" | "rosters";
class OperatorDashboardApp { class OperatorDashboardApp {
private activeTab: TabId = "queue"; private activeTab: TabId = "queue";
@@ -40,7 +41,10 @@ class OperatorDashboardApp {
}); });
} else { } else {
const initialTab = const initialTab =
hash === "agenda" || hash === "clients" || hash === "all" hash === "agenda" ||
hash === "clients" ||
hash === "all" ||
hash === "rosters"
? hash ? hash
: "queue"; : "queue";
this.switchTab(initialTab); this.switchTab(initialTab);
@@ -87,6 +91,9 @@ class OperatorDashboardApp {
<button class="nav-tab" data-tab="agenda" role="tab" aria-selected="false"> <button class="nav-tab" data-tab="agenda" role="tab" aria-selected="false">
<span>Agenda del Día (Buffers)</span> <span>Agenda del Día (Buffers)</span>
</button> </button>
<button class="nav-tab" data-tab="rosters" role="tab" aria-selected="false">
<span>Talleres</span>
</button>
<button class="nav-tab" data-tab="clients" role="tab" aria-selected="false"> <button class="nav-tab" data-tab="clients" role="tab" aria-selected="false">
<span>Clientes</span> <span>Clientes</span>
</button> </button>
@@ -109,6 +116,10 @@ class OperatorDashboardApp {
<span class="mobile-nav-icon" aria-hidden="true">📅</span> <span class="mobile-nav-icon" aria-hidden="true">📅</span>
<span class="mobile-nav-label">Agenda</span> <span class="mobile-nav-label">Agenda</span>
</button> </button>
<button class="mobile-nav-item" data-tab="rosters" role="tab" aria-selected="false">
<span class="mobile-nav-icon" aria-hidden="true">🪷</span>
<span class="mobile-nav-label">Talleres</span>
</button>
<button class="mobile-nav-item" data-tab="clients" role="tab" aria-selected="false"> <button class="mobile-nav-item" data-tab="clients" role="tab" aria-selected="false">
<span class="mobile-nav-icon" aria-hidden="true">👥</span> <span class="mobile-nav-icon" aria-hidden="true">👥</span>
<span class="mobile-nav-label">Clientes</span> <span class="mobile-nav-label">Clientes</span>
@@ -184,6 +195,7 @@ class OperatorDashboardApp {
if ( if (
hash === "queue" || hash === "queue" ||
hash === "agenda" || hash === "agenda" ||
hash === "rosters" ||
hash === "clients" || hash === "clients" ||
hash === "all" hash === "all"
) { ) {
@@ -219,6 +231,8 @@ class OperatorDashboardApp {
renderFollowUpQueue(contentEl, onStateChange); renderFollowUpQueue(contentEl, onStateChange);
} else if (tab === "agenda") { } else if (tab === "agenda") {
renderDailyAgenda(contentEl, onStateChange); renderDailyAgenda(contentEl, onStateChange);
} else if (tab === "rosters") {
renderWorkshopRoster(contentEl, onStateChange);
} else if (tab === "clients") { } else if (tab === "clients") {
renderClientDirectory(contentEl, onStateChange); renderClientDirectory(contentEl, onStateChange);
} else if (tab === "all") { } else if (tab === "all") {
+436
View File
@@ -1895,3 +1895,439 @@ body {
grid-template-columns: repeat(2, 1fr); grid-template-columns: repeat(2, 1fr);
} }
} }
/* ==========================================================================
Workshop Roster Quick Check-in (#rosters)
========================================================================== */
.roster-nav-bar {
display: flex;
flex-wrap: wrap;
gap: 12px;
justify-content: space-between;
align-items: center;
margin-bottom: 20px;
}
.roster-content-area {
display: flex;
flex-direction: column;
gap: 24px;
}
/* Skeleton Loading State */
.roster-skeleton-wrapper {
display: flex;
flex-direction: column;
gap: 16px;
}
.skeleton-card {
background: var(--color-surface);
border: 1px solid var(--color-border);
border-radius: var(--radius-md);
padding: 20px;
display: flex;
flex-direction: column;
gap: 14px;
}
.skeleton-line {
background: linear-gradient(
90deg,
var(--color-surface-soft) 25%,
#ebe7df 50%,
var(--color-surface-soft) 75%
);
background-size: 200% 100%;
animation: skeleton-pulse 1.5s ease-in-out infinite;
border-radius: var(--radius-sm);
}
@keyframes skeleton-pulse {
0% {
background-position: 200% 0;
}
100% {
background-position: -200% 0;
}
}
.skeleton-title {
width: 45%;
height: 24px;
}
.skeleton-meta {
width: 25%;
height: 18px;
}
.skeleton-table {
display: flex;
flex-direction: column;
gap: 12px;
margin-top: 8px;
}
.skeleton-row {
width: 100%;
height: 48px;
}
/* Empty & Error States */
.roster-empty-state {
background: var(--color-surface);
border: 1px dashed var(--color-border);
border-radius: var(--radius-md);
padding: 48px 24px;
text-align: center;
}
.roster-error-state {
background: var(--color-surface);
border: 1px solid var(--color-danger-light);
border-radius: var(--radius-md);
padding: 24px;
}
.error-box-card {
display: flex;
align-items: center;
gap: 16px;
flex-wrap: wrap;
}
.error-icon {
font-size: 28px;
}
.error-content {
flex: 1;
min-width: 220px;
}
.error-banner-message {
color: var(--color-danger);
font-size: 14px;
margin-top: 4px;
}
/* Session Card */
.roster-session-card {
background: var(--color-surface);
border: 1px solid var(--color-border);
border-radius: var(--radius-md);
box-shadow: var(--shadow-sm);
overflow: hidden;
transition: box-shadow 0.2s ease;
}
.roster-session-card:hover {
box-shadow: var(--shadow-md);
}
.session-card-header {
display: flex;
flex-wrap: wrap;
justify-content: space-between;
align-items: center;
padding: 16px 20px;
background: var(--color-surface);
border-bottom: 1px solid var(--color-border);
gap: 12px;
}
.session-title-block {
display: flex;
align-items: center;
gap: 12px;
flex-wrap: wrap;
}
.session-time-pill {
display: inline-flex;
align-items: center;
gap: 4px;
font-size: 13px;
font-weight: 700;
padding: 4px 10px;
background: var(--color-sage-light);
color: var(--color-sage-dark);
border-radius: 9999px;
border: 1px solid rgba(45, 90, 70, 0.2);
}
.session-title {
font-family: var(--font-serif);
font-size: 19px;
font-weight: 600;
color: var(--color-text-main);
}
.session-header-actions {
display: flex;
align-items: center;
gap: 14px;
flex-wrap: wrap;
}
.session-capacity-counter {
font-size: 13px;
padding: 6px 12px;
background: var(--color-surface-soft);
color: var(--color-text-main);
border: 1px solid var(--color-border);
border-radius: var(--radius-sm);
}
/* Attendees Table / Rows */
.session-attendees-container {
padding: 0;
}
.attendees-empty-notice {
padding: 32px 20px;
text-align: center;
}
.roster-attendees-table {
display: flex;
flex-direction: column;
}
.roster-attendee-row {
display: grid;
grid-template-columns: 2fr 2fr 1.6fr 2.4fr;
align-items: center;
padding: 14px 20px;
border-bottom: 1px solid var(--color-border);
gap: 16px;
transition: background-color 0.15s ease;
}
.roster-attendee-row:last-child {
border-bottom: none;
}
.roster-attendee-row:hover {
background-color: #faf9f6;
}
.roster-attendee-row.row-attended {
background-color: rgba(30, 126, 78, 0.04);
}
.attendee-col-client {
display: flex;
flex-direction: column;
gap: 2px;
}
.attendee-name {
font-size: 14px;
font-weight: 600;
color: var(--color-text-main);
}
.attendee-code {
font-size: 11px;
color: var(--color-text-muted);
}
.attendee-col-phone {
display: flex;
flex-direction: column;
gap: 4px;
}
.attendee-phone-text {
font-size: 13px;
color: var(--color-text-main);
}
.btn-wa-link {
display: inline-flex;
align-items: center;
gap: 4px;
color: #128c7e;
text-decoration: none;
font-size: 11px;
font-weight: 500;
min-height: 24px;
}
.btn-wa-link:hover {
text-decoration: underline;
}
.attendee-col-badges {
display: flex;
flex-wrap: wrap;
gap: 6px;
}
.attendee-col-actions {
display: flex;
justify-content: flex-end;
align-items: center;
}
.checkin-action-group {
display: flex;
align-items: center;
gap: 12px;
flex-wrap: wrap;
justify-content: flex-end;
}
.cash-toggle-label {
display: inline-flex;
align-items: center;
gap: 6px;
cursor: pointer;
user-select: none;
padding: 4px 0;
color: var(--color-text-main);
}
.cash-checkbox {
width: 18px;
height: 18px;
accent-color: var(--color-sage);
cursor: pointer;
}
/* Status Badges Mapping per Section 2.2 */
.status-roster-registered {
background: #f1f5f9;
color: #475569;
border: 1px solid #cbd5e1;
font-size: 11px;
font-weight: 600;
letter-spacing: 0.03em;
}
.status-roster-attended {
background: var(--color-success-light);
color: var(--color-success);
border: 1px solid rgba(30, 126, 78, 0.25);
font-size: 11px;
font-weight: 600;
letter-spacing: 0.03em;
}
.status-roster-paid {
background: var(--color-success-light);
color: var(--color-success);
border: 1px solid rgba(30, 126, 78, 0.25);
font-size: 11px;
font-weight: 600;
letter-spacing: 0.03em;
}
.status-roster-pending {
background: var(--color-warning-light);
color: var(--color-warning);
border: 1px solid rgba(217, 119, 6, 0.3);
font-size: 11px;
font-weight: 600;
letter-spacing: 0.03em;
}
/* Touch Targets & Keyboard Accessibility */
.btn-checkin,
.btn-walkin,
.btn-filter-pill,
.toast-close-btn {
min-height: 44px;
min-width: 44px;
}
.cash-toggle-label,
.form-checkbox-label {
min-height: 44px;
}
button:focus-visible,
input:focus-visible,
a:focus-visible {
outline: 2px solid var(--color-sage);
outline-offset: 2px;
}
/* Responsive Overrides (Mobile 375px) */
@media (max-width: 768px) {
.roster-nav-bar {
flex-direction: column;
align-items: stretch;
}
.session-card-header {
flex-direction: column;
align-items: stretch;
gap: 12px;
padding: 14px;
}
.session-header-actions {
flex-direction: column;
align-items: stretch;
gap: 8px;
}
.session-capacity-counter {
text-align: center;
}
.btn-walkin {
width: 100%;
justify-content: center;
}
.roster-attendee-row {
display: flex;
flex-direction: column;
align-items: stretch;
gap: 10px;
padding: 14px;
}
.attendee-col-client {
flex-direction: row;
justify-content: space-between;
align-items: center;
}
.attendee-col-phone {
flex-direction: row;
justify-content: space-between;
align-items: center;
}
.attendee-col-badges {
justify-content: flex-start;
gap: 8px;
}
.attendee-col-actions {
width: 100%;
margin-top: 4px;
}
.checkin-action-group {
width: 100%;
flex-direction: column;
align-items: stretch;
gap: 8px;
}
.cash-toggle-label {
justify-content: flex-start;
}
.btn-checkin {
width: 100%;
justify-content: center;
}
}
+50
View File
@@ -159,3 +159,53 @@ export interface BookingCompletePayload {
package_id?: string | null; package_id?: string | null;
notes?: string | null; notes?: string | null;
} }
export interface RosterAttendee {
booking_id: string;
booking_code: string;
client_id: string;
client_name: string;
client_phone: string;
client_email?: string | null;
booking_status: BookingStatus | string;
payment_arrangement: PaymentArrangement | string;
payment_status: PaymentStatus | string;
amount_mxn: number;
attended: boolean;
}
export interface RosterSession {
service_id: string;
service_name: string;
scheduled_at: string;
max_capacity: number;
occupied_count: number;
attended_count: number;
attendees: RosterAttendee[];
}
export interface QuickCheckinBookingPayload {
booking_id: string;
paid_cash?: boolean;
notes?: string | null;
}
export interface QuickCheckinWalkInPayload {
service_id: string;
scheduled_at: string;
client_name: string;
client_phone: string;
client_email?: string | null;
paid_cash?: boolean;
notes?: string | null;
}
export type QuickCheckinPayload =
| QuickCheckinBookingPayload
| QuickCheckinWalkInPayload;
export interface QuickCheckinResponse {
walk_in: boolean;
attendee: RosterAttendee;
payment_id?: string | null;
}
+268
View File
@@ -0,0 +1,268 @@
import { describe, expect, it } from "vitest";
import {
buildWhatsAppUrl,
disambiguate409Error,
escapeHtml,
formatRosterCapacity,
reconcileAlreadyCheckedInState,
reconcileSessionsWithServer,
renderAttendanceStatusBadge,
renderPaymentStatusPill,
} from "../src/components/WorkshopRoster";
import type { RosterAttendee, RosterSession } from "../src/types";
describe("Workshop Roster Utilities", () => {
describe("Capacity Formatting", () => {
it("formats capacity counter accurately per spec", () => {
expect(formatRosterCapacity(2, 15, 0)).toBe(
"Ocupación: 2 / 15 (0 presentes)",
);
expect(formatRosterCapacity(2, 15, 1)).toBe(
"Ocupación: 2 / 15 (1 presentes)",
);
expect(formatRosterCapacity(3, 15, 3)).toBe(
"Ocupación: 3 / 15 (3 presentes)",
);
});
});
describe("Status Badges Rendering", () => {
it("renders REGISTRADO when attended is false", () => {
const badge = renderAttendanceStatusBadge(false, "RESERVED");
expect(badge).toContain("REGISTRADO");
expect(badge).toContain("status-roster-registered");
});
it("renders ASISTIÓ when attended is true or status is COMPLETED", () => {
const badge1 = renderAttendanceStatusBadge(true, "COMPLETED");
expect(badge1).toContain("ASISTIÓ");
expect(badge1).toContain("status-roster-attended");
const badge2 = renderAttendanceStatusBadge(false, "COMPLETED");
expect(badge2).toContain("ASISTIÓ");
});
it("renders PAGADO when payment_status is ACKNOWLEDGED", () => {
const badge = renderPaymentStatusPill("ACKNOWLEDGED");
expect(badge).toContain("PAGADO");
expect(badge).toContain("status-roster-paid");
});
it("renders PENDIENTE when payment_status is AWAITING_ACKNOWLEDGMENT", () => {
const badge = renderPaymentStatusPill("AWAITING_ACKNOWLEDGMENT");
expect(badge).toContain("PENDIENTE");
expect(badge).toContain("status-roster-pending");
});
});
describe("WhatsApp URL Generation", () => {
it("generates 1-tap wa.me link with 10-digit number", () => {
expect(buildWhatsAppUrl("5511112222")).toBe("https://wa.me/525511112222");
});
it("generates wa.me link with already prefixed 12-digit number", () => {
expect(buildWhatsAppUrl("525533334444")).toBe(
"https://wa.me/525533334444",
);
});
it("cleans formatting characters in phone number", () => {
expect(buildWhatsAppUrl("+52 55 9876 5432")).toBe(
"https://wa.me/525598765432",
);
});
});
describe("409 Conflict Disambiguation", () => {
it("identifies already checked in conflict", () => {
expect(
disambiguate409Error("This attendee has already checked in."),
).toBe("ALREADY_CHECKED_IN");
});
it("identifies capacity reached conflict", () => {
expect(
disambiguate409Error(
"El taller ha alcanzado su cupo máximo (15) para esta sesión.",
),
).toBe("CAPACITY_EXCEEDED");
});
it("identifies capacity reached without accent if encountered", () => {
expect(
disambiguate409Error(
"El taller ha alcanzado su cupo maximo para esta sesión.",
),
).toBe("CAPACITY_EXCEEDED");
});
it("falls back to UNKNOWN for other 409 or empty messages", () => {
expect(disambiguate409Error("Some generic conflict")).toBe("UNKNOWN");
expect(disambiguate409Error(undefined)).toBe("UNKNOWN");
});
});
describe("HTML Sanitization (escapeHtml)", () => {
it("escapes dangerous HTML characters to prevent XSS", () => {
expect(escapeHtml('<script>alert("xss")</script>')).toBe(
"&lt;script&gt;alert(&quot;xss&quot;)&lt;/script&gt;",
);
expect(escapeHtml("Tom & Jerry's")).toBe("Tom &amp; Jerry&#039;s");
expect(escapeHtml('<img src="x" onerror="alert(1)">')).toBe(
"&lt;img src=&quot;x&quot; onerror=&quot;alert(1)&quot;&gt;",
);
});
it("leaves strings without special characters untouched", () => {
expect(escapeHtml("Elena Gómez")).toBe("Elena Gómez");
expect(escapeHtml("ADS-1001")).toBe("ADS-1001");
expect(escapeHtml("+52 55 1111 2222")).toBe("+52 55 1111 2222");
});
});
describe("409 Out-of-Band Counter Reconciliation", () => {
function createMockSession(occupied = 2, attended = 0): RosterSession {
return {
service_id: "srv-123",
service_name: "Círculo de Cacao",
scheduled_at: "2026-10-26T18:00:00Z",
max_capacity: 15,
occupied_count: occupied,
attended_count: attended,
attendees: [],
};
}
function createMockAttendee(attended = false): RosterAttendee {
return {
booking_id: "bk-123",
booking_code: "ADS-1001",
client_id: "cl-123",
client_name: "Elena Gómez",
client_phone: "525511112222",
booking_status: attended ? "COMPLETED" : "RESERVED",
payment_arrangement: "PREPAID_DEFAULT",
payment_status: "ACKNOWLEDGED",
amount_mxn: 350,
attended,
};
}
it("increments attended_count and reconciles attendee when locally unrecorded", () => {
const session = createMockSession(2, 0);
const attendee = createMockAttendee(false);
const incremented = reconcileAlreadyCheckedInState(session, attendee);
expect(incremented).toBe(true);
expect(session.attended_count).toBe(1);
expect(attendee.attended).toBe(true);
expect(attendee.booking_status).toBe("COMPLETED");
});
it("does not increment attended_count if attendee was already marked attended locally", () => {
const session = createMockSession(2, 1);
const attendee = createMockAttendee(true);
const incremented = reconcileAlreadyCheckedInState(session, attendee);
expect(incremented).toBe(false);
expect(session.attended_count).toBe(1); // Unchanged
expect(attendee.attended).toBe(true);
});
it("reconciles multiple out-of-band check-ins authoritatively from server response (Case 2B)", () => {
const staleLocalSession: RosterSession = {
service_id: "srv-123",
service_name: "Círculo de Cacao",
scheduled_at: "2026-10-26T18:00:00Z",
max_capacity: 15,
occupied_count: 2,
attended_count: 0,
attendees: [
{
booking_id: "bk-1001",
booking_code: "ADS-1001",
client_id: "cl-1",
client_name: "Elena Gómez",
client_phone: "525511112222",
booking_status: "RESERVED",
payment_arrangement: "PREPAID_DEFAULT",
payment_status: "ACKNOWLEDGED",
amount_mxn: 350,
attended: false,
},
{
booking_id: "bk-1002",
booking_code: "ADS-1002",
client_id: "cl-2",
client_name: "Carlos Méndez",
client_phone: "525533334444",
booking_status: "RESERVED",
payment_arrangement: "PREPAID_DEFAULT",
payment_status: "AWAITING_ACKNOWLEDGMENT",
amount_mxn: 350,
attended: false,
},
],
};
const authoritativeServerSession: RosterSession = {
service_id: "srv-123",
service_name: "Círculo de Cacao",
scheduled_at: "2026-10-26T18:00:00Z",
max_capacity: 15,
occupied_count: 2,
attended_count: 2,
attendees: [
{
booking_id: "bk-1001",
booking_code: "ADS-1001",
client_id: "cl-1",
client_name: "Elena Gómez",
client_phone: "525511112222",
booking_status: "COMPLETED",
payment_arrangement: "PREPAID_DEFAULT",
payment_status: "ACKNOWLEDGED",
amount_mxn: 350,
attended: true,
},
{
booking_id: "bk-1002",
booking_code: "ADS-1002",
client_id: "cl-2",
client_name: "Carlos Méndez",
client_phone: "525533334444",
booking_status: "COMPLETED",
payment_arrangement: "PREPAID_DEFAULT",
payment_status: "ACKNOWLEDGED",
amount_mxn: 350,
attended: true,
},
],
};
const reconciled = reconcileSessionsWithServer(
[staleLocalSession],
[authoritativeServerSession],
);
expect(reconciled).toHaveLength(1);
expect(reconciled[0].occupied_count).toBe(2);
expect(reconciled[0].attended_count).toBe(2);
const elena = reconciled[0].attendees.find(
(a) => a.booking_code === "ADS-1001",
);
const carlos = reconciled[0].attendees.find(
(a) => a.booking_code === "ADS-1002",
);
expect(elena?.attended).toBe(true);
expect(elena?.booking_status).toBe("COMPLETED");
expect(carlos?.attended).toBe(true);
expect(carlos?.booking_status).toBe("COMPLETED");
});
});
});