Compare commits

..
11 Commits
Author SHA1 Message Date
kiskaadee 0098b5214c Merge pull request 'feat(roster): Group Workshop Roster Quick Check-in' (#9) from feat/anne/workshop-roster into main 2026-10-29 13:39:28 -05:00
anneux 4e1e7f2ba3 fix(roster): reconcile session state from server on 409 conflict 2026-10-27 07:48:44 -05:00
anneux 9191899154 fix(roster): escape HTML interpolations and sync capacity counter on 409 reconciliation 2026-10-27 07:32:45 -05:00
anneux faa2d34b54 docs(roster): update worktree path reference in self-audit 2026-10-26 21:29:45 -05:00
anneux d672065186 docs(roster): record dual-viewport evidence and freeze anne self-audit 2026-10-26 09:54:02 -05:00
anneux 191a02d6c2 feat(roster): integrate talleres tab in navigation and add responsive styles 2026-10-26 09:49:53 -05:00
anneux 6ba0bbe7d0 feat(roster): implement session cards, attendee list, and check-in workflows 2026-10-26 09:45:48 -05:00
anneux c09f6c6ae3 feat(roster): add status badges, capacity formatting, and unit tests 2026-10-26 09:42:41 -05:00
anneux 0ff27a2038 feat(roster): define API types and client methods for workshop rosters 2026-10-26 09:41:45 -05:00
kiskaadee 00b59182ac Merge pull request 'feat(ui): Dynamic Operator Identity, 'Nueva Cita' Modal, and Client Directory' (#8) from feat/anne/6-intake-and-clients into main 2026-10-19 17:09:36 -05:00
kiskaadee 7f56fe06d2 feat(ui): dynamic operator identity, 'Nueva Cita' modal, and client directory view
- Dynamic identity pill in header querying GET /auth/me with role badge
- Global '+ Nueva Cita' modal with debounced client autocomplete and WhatsApp confirmation
- Agenda card actions for reschedule and completion
- Client Directory tab with search, contact details, and package counters
- Dual-viewport captures for desktop and mobile

Refs: #6, #7
2026-10-19 17:09:16 -05:00
22 changed files with 4120 additions and 13 deletions

No files matched your search

Symlink
+1
View File
@@ -0,0 +1 @@
vp.js
+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: 100 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 86 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 146 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 61 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 62 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 58 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 87 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 62 KiB

+216
View File
@@ -1,7 +1,19 @@
import type { import type {
AdminPrincipal,
Booking, Booking,
BookingCompletePayload,
BookingCreatePayload,
BookingReschedulePayload,
Client,
Client360,
ClientUpdatePayload,
PackageRecord,
PaymentAcknowledgmentPayload, PaymentAcknowledgmentPayload,
PaymentRecord, PaymentRecord,
QuickCheckinPayload,
QuickCheckinResponse,
RosterSession,
Service,
} from "./types"; } from "./types";
const API_BASE_URL = const API_BASE_URL =
@@ -130,3 +142,207 @@ export async function retryCalendarSync(bookingId: string): Promise<Booking> {
} }
return res.json(); return res.json();
} }
export async function fetchCurrentAdmin(): Promise<AdminPrincipal> {
const res = await fetch(`${API_BASE_URL}/auth/me`, {
headers: getAuthHeaders(),
});
if (!res.ok) {
const errData = await res.json().catch(() => ({}));
throw new Error(
errData.detail ||
`Error al consultar identidad de operador: ${res.status} ${res.statusText}`,
);
}
return res.json();
}
export async function fetchServices(activeOnly = true): Promise<Service[]> {
const res = await fetch(
`${API_BASE_URL}/services?active_only=${activeOnly ? "true" : "false"}`,
{
headers: getAuthHeaders(),
},
);
if (!res.ok) {
throw new Error(
`Error al obtener catálogo de servicios: ${res.status} ${res.statusText}`,
);
}
return res.json();
}
export async function searchClients(search?: string): Promise<Client[]> {
const query = search ? `?search=${encodeURIComponent(search.trim())}` : "";
const res = await fetch(`${API_BASE_URL}/clients${query}`, {
headers: getAuthHeaders(),
});
if (!res.ok) {
throw new Error(
`Error al buscar clientes: ${res.status} ${res.statusText}`,
);
}
return res.json();
}
export async function fetchClient360(clientId: string): Promise<Client360> {
const res = await fetch(`${API_BASE_URL}/clients/${clientId}`, {
headers: getAuthHeaders(),
});
if (!res.ok) {
const errData = await res.json().catch(() => ({}));
throw new Error(
errData.detail ||
`Error al obtener perfil de cliente: ${res.status} ${res.statusText}`,
);
}
return res.json();
}
export async function updateClient(
clientId: string,
payload: ClientUpdatePayload,
): Promise<Client> {
const res = await fetch(`${API_BASE_URL}/clients/${clientId}`, {
method: "PATCH",
headers: getAuthHeaders(),
body: JSON.stringify(payload),
});
if (!res.ok) {
const errData = await res.json().catch(() => ({}));
throw new Error(
errData.detail ||
`Error al actualizar datos de cliente: ${res.status} ${res.statusText}`,
);
}
return res.json();
}
export async function createBooking(
payload: BookingCreatePayload,
): Promise<Booking> {
const res = await fetch(`${API_BASE_URL}/bookings`, {
method: "POST",
headers: getAuthHeaders(),
body: JSON.stringify(payload),
});
if (!res.ok) {
const errData = await res.json().catch(() => ({}));
throw new Error(
errData.detail ||
`Error al agendar cita: ${res.status} ${res.statusText}`,
);
}
return res.json();
}
export async function rescheduleBooking(
bookingId: string,
payload: BookingReschedulePayload,
): Promise<Booking> {
const res = await fetch(`${API_BASE_URL}/bookings/${bookingId}/reschedule`, {
method: "POST",
headers: getAuthHeaders(),
body: JSON.stringify(payload),
});
if (!res.ok) {
const errData = await res.json().catch(() => ({}));
throw new Error(
errData.detail ||
`Error al reagendar cita: ${res.status} ${res.statusText}`,
);
}
return res.json();
}
export async function completeBooking(
bookingId: string,
payload?: BookingCompletePayload,
): Promise<Booking> {
const res = await fetch(`${API_BASE_URL}/bookings/${bookingId}/complete`, {
method: "POST",
headers: getAuthHeaders(),
body: JSON.stringify(payload || {}),
});
if (!res.ok) {
const errData = await res.json().catch(() => ({}));
throw new Error(
errData.detail ||
`Error al concluir cita: ${res.status} ${res.statusText}`,
);
}
return res.json();
}
export async function fetchPackages(
clientId?: string,
): Promise<PackageRecord[]> {
const query = clientId ? `?client_id=${encodeURIComponent(clientId)}` : "";
const res = await fetch(`${API_BASE_URL}/packages${query}`, {
headers: getAuthHeaders(),
});
if (!res.ok) {
throw new Error(
`Error al obtener paquetes: ${res.status} ${res.statusText}`,
);
}
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();
}
+483
View File
@@ -0,0 +1,483 @@
import { fetchPackages, searchClients, updateClient } from "../api";
import type { Client, PackageRecord } from "../types";
import { debounce, formatMexicanPhone, getCleanDigitsPhone } from "../utils";
import { showToast } from "./Toast";
export function renderClientDirectory(
container: HTMLElement,
onStateChange?: () => void,
): void {
container.innerHTML = `
<div class="view-header">
<div>
<h2 class="view-title">Directorio de Consultantes</h2>
<p class="view-subtitle">Expedientes de contacto, notas clínicas y seguimiento de paquetes activos.</p>
</div>
<div class="view-actions">
<button id="refresh-clients-btn" class="btn btn-secondary btn-sm" title="Refrescar directorio">
↻ Actualizar
</button>
</div>
</div>
<!-- Search Bar -->
<div class="directory-search-bar">
<div class="search-input-group">
<span class="search-icon" aria-hidden="true">🔍</span>
<input
type="search"
id="client-directory-search"
class="form-input directory-search-input"
placeholder="Buscar consultante por nombre o teléfono WhatsApp..."
aria-label="Buscar consultante por nombre o teléfono"
/>
<button type="button" id="clear-search-btn" class="btn-clear-input hidden" title="Limpiar búsqueda">&times;</button>
</div>
<div id="clients-counter" class="clients-counter-pill text-xs text-muted"></div>
</div>
<!-- Main Container (5 States) -->
<div id="clients-content" class="clients-list-container">
<div class="loading-state">
<div class="skeleton-card"></div>
<div class="skeleton-card"></div>
</div>
</div>
`;
const contentDiv =
container.querySelector<HTMLDivElement>("#clients-content");
const searchInput = container.querySelector<HTMLInputElement>(
"#client-directory-search",
);
const clearSearchBtn =
container.querySelector<HTMLButtonElement>("#clear-search-btn");
const counterDiv =
container.querySelector<HTMLDivElement>("#clients-counter");
const refreshBtn = container.querySelector<HTMLButtonElement>(
"#refresh-clients-btn",
);
let cachedClients: Client[] = [];
let cachedPackages: PackageRecord[] = [];
let currentQuery = "";
const loadData = async (query = "") => {
if (!contentDiv) return;
currentQuery = query;
contentDiv.innerHTML = `
<div class="loading-state">
<div class="skeleton-card"></div>
<div class="skeleton-card"></div>
</div>
`;
try {
// Fetch clients and packages concurrently for resilient state
const [clientsResult, packagesResult] = await Promise.allSettled([
searchClients(query),
fetchPackages(),
]);
if (clientsResult.status === "rejected") {
throw new Error(
clientsResult.reason instanceof Error
? clientsResult.reason.message
: "Error al cargar la lista de consultantes.",
);
}
cachedClients = clientsResult.value;
cachedPackages =
packagesResult.status === "fulfilled" ? packagesResult.value : [];
renderClients(cachedClients, cachedPackages);
} catch (err: unknown) {
renderError(err instanceof Error ? err.message : "Error desconocido");
}
};
const renderError = (msg: string) => {
if (!contentDiv) return;
contentDiv.innerHTML = `
<div class="card error-state">
<div class="error-icon">⚠️</div>
<h3 class="error-title">No se pudo cargar el directorio</h3>
<p class="error-desc">${msg}</p>
<button id="retry-clients-btn" class="btn btn-primary btn-sm">
Intentar de nuevo
</button>
</div>
`;
contentDiv
.querySelector("#retry-clients-btn")
?.addEventListener("click", () => loadData(currentQuery));
};
const renderClients = (clients: Client[], packages: PackageRecord[]) => {
if (!contentDiv) return;
if (counterDiv) {
counterDiv.textContent = `${clients.length} ${clients.length === 1 ? "consultante registrado" : "consultantes registrados"}`;
}
if (clients.length === 0) {
contentDiv.innerHTML = `
<div class="card empty-state">
<div class="empty-icon">👥</div>
<h3 class="empty-title">
${currentQuery ? "Sin coincidencias" : "Directorio vacío"}
</h3>
<p class="empty-desc">
${
currentQuery
? `No se encontraron consultantes para "<strong>${escapeHtml(currentQuery)}</strong>". Puedes registrar una nueva cita desde el botón superior.`
: "Aún no hay consultantes registrados en el sistema."
}
</p>
</div>
`;
return;
}
contentDiv.innerHTML = `
<div class="clients-grid">
${clients
.map((c) => {
const clientPackages = packages.filter(
(p) =>
p.client_id === c.id && p.completed_sessions < p.total_sessions,
);
const cleanDigits = getCleanDigitsPhone(c.phone_whatsapp);
const waLink = `https://wa.me/${cleanDigits}?text=${encodeURIComponent(
`Hola ${c.full_name}, te saludamos de Armonía del Ser.`,
)}`;
const packagesHtml =
clientPackages.length > 0
? clientPackages
.map(
(pkg) => `
<span class="package-pill" title="Sesiones completadas del paquete">
📦 Paquete: ${pkg.completed_sessions} de ${pkg.total_sessions}
${pkg.service_name ? `(${escapeHtml(pkg.service_name)})` : ""}
</span>
`,
)
.join("")
: '<span class="text-xs text-muted">Sin paquetes activos</span>';
return `
<div class="client-card" id="client-card-${c.id}">
<div class="client-card-header">
<div>
<h3 class="client-card-name">${escapeHtml(c.full_name)}</h3>
<span class="client-registered-date text-xs text-muted">
Registrado el ${new Date(c.created_at).toLocaleDateString("es-MX", { day: "numeric", month: "short", year: "numeric" })}
</span>
</div>
<button
type="button"
class="btn btn-secondary btn-sm btn-edit-client"
data-client-id="${c.id}"
title="Editar datos de contacto o notas clínicas"
>
✏️ Editar
</button>
</div>
<div class="client-card-body">
<div class="client-contact-row">
<a
href="${waLink}"
target="_blank"
rel="noopener noreferrer"
class="btn btn-whatsapp btn-xs"
title="Abrir WhatsApp para mensaje directo"
>
<span>💬 ${escapeHtml(c.phone_whatsapp)}</span>
</a>
${
c.email
? `<span class="client-email-badge text-xs">✉️ ${escapeHtml(c.email)}</span>`
: '<span class="text-xs text-muted">Sin correo</span>'
}
</div>
<div class="client-packages-row mt-2">
<span class="detail-label text-xs font-semibold">Estado de Paquetes:</span>
<div class="packages-tags-container mt-1">
${packagesHtml}
</div>
</div>
${
c.notes
? `
<div class="client-notes-box mt-3">
<span class="notes-kicker text-xs font-semibold">Notas Clínicas / Operativas:</span>
<p class="notes-content text-sm mt-1">${escapeHtml(c.notes)}</p>
</div>
`
: `
<div class="client-notes-empty mt-2 text-xs text-muted">
Sin notas adicionales registradas.
</div>
`
}
</div>
</div>
`;
})
.join("")}
</div>
`;
// Attach Edit Handlers
contentDiv.querySelectorAll(".btn-edit-client").forEach((btn) => {
btn.addEventListener("click", () => {
const id = btn.getAttribute("data-client-id");
const client = clients.find((c) => c.id === id);
if (!client) return;
openEditClientModal({
client,
onSuccess: (updated) => {
showToast(
`Datos actualizados para ${updated.full_name}`,
"success",
4500,
);
loadData(currentQuery);
onStateChange?.();
},
});
});
});
};
// Debounced Search Handler
const onSearchInput = debounce((val: string) => {
if (clearSearchBtn) {
clearSearchBtn.classList.toggle("hidden", val.length === 0);
}
loadData(val);
}, 250);
searchInput?.addEventListener("input", () => {
onSearchInput(searchInput.value);
});
clearSearchBtn?.addEventListener("click", () => {
if (searchInput) {
searchInput.value = "";
clearSearchBtn.classList.add("hidden");
loadData("");
searchInput.focus();
}
});
refreshBtn?.addEventListener("click", () => loadData(currentQuery));
// Initial load
loadData("");
}
export interface EditClientModalOptions {
client: Client;
onSuccess: (updated: Client) => void;
}
export function openEditClientModal(options: EditClientModalOptions): void {
const { client, onSuccess } = options;
const existingBackdrop = document.getElementById(
"edit-client-modal-backdrop",
);
if (existingBackdrop) existingBackdrop.remove();
const backdrop = document.createElement("div");
backdrop.id = "edit-client-modal-backdrop";
backdrop.className = "modal-backdrop";
backdrop.innerHTML = `
<div class="modal-card" role="dialog" aria-modal="true" aria-labelledby="edit-client-title">
<div class="modal-header">
<div>
<span class="modal-kicker">Expediente de Consultante</span>
<h3 id="edit-client-title" class="modal-title">Editar Consultante</h3>
</div>
<button type="button" class="modal-close-btn" id="edit-modal-close" aria-label="Cerrar modal">&times;</button>
</div>
<div class="modal-body">
<form id="edit-client-form" class="modal-form-content">
<div class="form-group">
<label for="edit-client-name" class="form-label font-semibold">
Nombre Completo <span class="text-danger">*</span>
</label>
<input
type="text"
id="edit-client-name"
name="full_name"
class="form-input"
value="${escapeHtml(client.full_name)}"
required
minlength="2"
/>
</div>
<div class="form-group">
<label for="edit-client-phone" class="form-label font-semibold">
Teléfono WhatsApp (+52) <span class="text-danger">*</span>
</label>
<input
type="tel"
id="edit-client-phone"
name="phone_whatsapp"
class="form-input"
value="${escapeHtml(formatMexicanPhone(client.phone_whatsapp))}"
required
minlength="10"
/>
</div>
<div class="form-group">
<label for="edit-client-email" class="form-label font-semibold">
Correo Electrónico (opcional)
</label>
<input
type="email"
id="edit-client-email"
name="email"
class="form-input"
value="${escapeHtml(client.email || "")}"
placeholder="correo@ejemplo.com"
/>
</div>
<div class="form-group">
<label for="edit-client-notes" class="form-label font-semibold">
Notas Clínicas u Operativas
</label>
<textarea
id="edit-client-notes"
name="notes"
class="form-textarea"
rows="3"
placeholder="Observaciones de salud, antecedentes, preferencias de horario..."
>${escapeHtml(client.notes || "")}</textarea>
</div>
<div id="edit-client-error" class="modal-error-box hidden" role="alert"></div>
<div class="modal-actions">
<button type="button" id="edit-modal-cancel" class="btn btn-secondary">
Cancelar
</button>
<button type="submit" id="edit-modal-submit" class="btn btn-primary">
Guardar Cambios
</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("#edit-modal-close")
?.addEventListener("click", () => close());
backdrop
.querySelector("#edit-modal-cancel")
?.addEventListener("click", () => close());
backdrop.addEventListener("click", (e) => {
if (e.target === backdrop) close();
});
const form = backdrop.querySelector<HTMLFormElement>("#edit-client-form");
const nameInput =
backdrop.querySelector<HTMLInputElement>("#edit-client-name");
const phoneInput =
backdrop.querySelector<HTMLInputElement>("#edit-client-phone");
const emailInput =
backdrop.querySelector<HTMLInputElement>("#edit-client-email");
const notesInput =
backdrop.querySelector<HTMLTextAreaElement>("#edit-client-notes");
const submitBtn =
backdrop.querySelector<HTMLButtonElement>("#edit-modal-submit");
const errorBox = backdrop.querySelector<HTMLDivElement>("#edit-client-error");
phoneInput?.addEventListener("blur", () => {
if (phoneInput.value) {
phoneInput.value = formatMexicanPhone(phoneInput.value);
}
});
form?.addEventListener("submit", async (e) => {
e.preventDefault();
if (!submitBtn || !errorBox) return;
const full_name = nameInput?.value.trim();
const raw_phone = phoneInput?.value.trim() || "";
const phone_whatsapp = formatMexicanPhone(raw_phone);
const raw_email = emailInput?.value.trim();
const email = raw_email || null;
const raw_notes = notesInput?.value.trim();
const notes = raw_notes || null;
if (!full_name || !phone_whatsapp) {
errorBox.textContent = "El nombre y teléfono son obligatorios.";
errorBox.classList.remove("hidden");
return;
}
submitBtn.disabled = true;
submitBtn.textContent = "Guardando...";
errorBox.classList.add("hidden");
errorBox.textContent = "";
try {
const updated = await updateClient(client.id, {
full_name,
phone_whatsapp,
email,
notes,
});
close();
onSuccess(updated);
} catch (err: unknown) {
submitBtn.disabled = false;
submitBtn.textContent = "Guardar Cambios";
errorBox.textContent =
err instanceof Error
? err.message
: "Error al actualizar datos del cliente.";
errorBox.classList.remove("hidden");
}
});
nameInput?.focus();
}
function escapeHtml(str: string): string {
return str
.replace(/&/g, "&amp;")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;")
.replace(/"/g, "&quot;")
.replace(/'/g, "&#039;");
}
+280 -1
View File
@@ -1,9 +1,15 @@
import { fetchAllBookings, retryCalendarSync } from "../api"; import {
completeBooking,
fetchAllBookings,
rescheduleBooking,
retryCalendarSync,
} from "../api";
import type { Booking } from "../types"; import type { Booking } from "../types";
import { import {
calculateInterval, calculateInterval,
checkBufferCollision, checkBufferCollision,
formatCurrency, formatCurrency,
formatDateInput,
formatDateTime, formatDateTime,
formatTimeOnly, formatTimeOnly,
isSameDay, isSameDay,
@@ -11,6 +17,7 @@ import {
isToday, isToday,
isTomorrow, isTomorrow,
} from "../utils"; } from "../utils";
import { showConfirmModal } from "./MicroModal";
import { import {
renderBookingStatusBadge, renderBookingStatusBadge,
renderCalendarSyncBadge, renderCalendarSyncBadge,
@@ -345,6 +352,31 @@ export function renderDailyAgenda(
<span class="buffer-hint">Tiempo no agendable protegido por el backend.</span> <span class="buffer-hint">Tiempo no agendable protegido por el backend.</span>
</div> </div>
${
b.booking_status === "RESERVED"
? `
<div class="agenda-card-actions">
<button
type="button"
class="btn btn-secondary btn-sm btn-reschedule-booking"
data-booking-id="${b.id}"
title="Mover cita a otro horario o día"
>
<span>🗓️ Mover Cita</span>
</button>
<button
type="button"
class="btn btn-outline-success btn-sm btn-complete-booking"
data-booking-id="${b.id}"
title="Marcar consulta como concluida"
>
<span>✓ Concluir Cita</span>
</button>
</div>
`
: ""
}
${collisionNotice} ${collisionNotice}
</div> </div>
</div> </div>
@@ -354,6 +386,72 @@ export function renderDailyAgenda(
</div> </div>
`; `;
// Attach 'Mover Cita' handlers
contentDiv.querySelectorAll(".btn-reschedule-booking").forEach((btn) => {
btn.addEventListener("click", () => {
const id = btn.getAttribute("data-booking-id");
const booking = bookings.find((b) => b.id === id);
if (!booking) return;
openRescheduleModal({
booking,
onSuccess: (updated) => {
showToast(
`Cita reagendada para ${formatDateTime(updated.scheduled_at)}`,
"success",
5000,
{ folio: updated.booking_code },
);
loadData();
onStateChange();
},
});
});
});
// Attach 'Concluir Cita' handlers
contentDiv.querySelectorAll(".btn-complete-booking").forEach((btn) => {
btn.addEventListener("click", () => {
const id = btn.getAttribute("data-booking-id");
const booking = bookings.find((b) => b.id === id);
if (!booking) return;
showConfirmModal({
title: "¿Concluir consulta?",
kicker: "Finalización de Sesión",
message: `¿Deseas marcar la consulta de <strong>${booking.client_name || "Cliente"}</strong> (${booking.booking_code}) como concluida? Se registrará la asistencia y el estado cambiará a CONCLUIDA.`,
bookingContext: {
bookingCode: booking.booking_code,
clientName: booking.client_name,
serviceName: booking.service_name,
scheduledAtFormatted: formatDateTime(booking.scheduled_at),
},
withReasonInput: true,
reasonLabel:
"Notas clínicas u observaciones de la sesión (opcional):",
defaultReason: "",
reasonPlaceholder:
"Ej. Se completó terapia de sonido; paciente reporta relajación profunda.",
confirmText: "✓ Sí, Concluir Cita",
cancelText: "Volver",
isDanger: false,
onConfirm: async (notes) => {
await completeBooking(booking.id, {
notes: notes || undefined,
});
showToast(
`Cita ${booking.booking_code} marcada como Concluida`,
"success",
5000,
{ folio: booking.booking_code },
);
loadData();
onStateChange();
},
});
});
});
// Attach retry calendar sync buttons // Attach retry calendar sync buttons
contentDiv.querySelectorAll(".btn-retry-gcal").forEach((btn) => { contentDiv.querySelectorAll(".btn-retry-gcal").forEach((btn) => {
btn.addEventListener("click", async () => { btn.addEventListener("click", async () => {
@@ -422,3 +520,184 @@ export function renderDailyAgenda(
refreshBtn?.addEventListener("click", () => loadData()); refreshBtn?.addEventListener("click", () => loadData());
loadData(); loadData();
} }
interface RescheduleModalOptions {
booking: Booking;
onSuccess: (updated: Booking) => void;
}
function openRescheduleModal(options: RescheduleModalOptions): void {
const { booking, onSuccess } = options;
const existing = document.getElementById("reschedule-modal-backdrop");
if (existing) existing.remove();
const backdrop = document.createElement("div");
backdrop.id = "reschedule-modal-backdrop";
backdrop.className = "modal-backdrop";
const currentDt = new Date(booking.scheduled_at);
const defaultDate = formatDateInput(currentDt);
const hours = String(currentDt.getHours()).padStart(2, "0");
const mins = String(currentDt.getMinutes()).padStart(2, "0");
const defaultTime = `${hours}:${mins}`;
backdrop.innerHTML = `
<div class="modal-card" role="dialog" aria-modal="true" aria-labelledby="reschedule-modal-title">
<div class="modal-header">
<div>
<span class="modal-kicker">Reagendación de Consulta</span>
<h3 id="reschedule-modal-title" class="modal-title">Mover Cita</h3>
</div>
<button type="button" class="modal-close-btn" id="reschedule-modal-close" aria-label="Cerrar modal">&times;</button>
</div>
<div class="modal-body">
<div class="summary-box">
<div class="summary-row">
<span class="summary-label">Folio:</span>
<span class="summary-value font-mono font-bold">${booking.booking_code}</span>
</div>
<div class="summary-row">
<span class="summary-label">Paciente:</span>
<span class="summary-value font-semibold">${booking.client_name || "Cliente"}</span>
</div>
<div class="summary-row">
<span class="summary-label">Servicio:</span>
<span class="summary-value">${booking.service_name || "Consulta"}</span>
</div>
<div class="summary-row">
<span class="summary-label">Horario actual:</span>
<span class="summary-value font-medium">${formatDateTime(booking.scheduled_at)}</span>
</div>
</div>
<form id="reschedule-form" class="modal-form-content mt-3">
<div class="form-group">
<label class="form-label font-semibold">Nuevo Horario Propuesto:</label>
<div class="datetime-grid">
<div class="form-subgroup">
<label for="reschedule-date" class="form-sublabel">Nueva Fecha:</label>
<input
type="date"
id="reschedule-date"
class="form-input"
value="${defaultDate}"
required
/>
</div>
<div class="form-subgroup">
<label for="reschedule-time" class="form-sublabel">Nueva Hora:</label>
<input
type="time"
id="reschedule-time"
class="form-input"
value="${defaultTime}"
step="900"
required
/>
</div>
</div>
</div>
<div class="form-group">
<label for="reschedule-notes" class="form-label font-semibold">
Motivo de Reagendación (opcional):
</label>
<textarea
id="reschedule-notes"
class="form-textarea"
rows="2"
placeholder="Ej. Solicitado por el consultante..."
></textarea>
</div>
<div id="reschedule-error" class="modal-error-box hidden" role="alert"></div>
<div class="modal-actions">
<button type="button" id="reschedule-cancel-btn" class="btn btn-secondary">
Cancelar
</button>
<button type="submit" id="reschedule-submit-btn" class="btn btn-primary">
Confirmar Nuevo Horario
</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("#reschedule-modal-close")
?.addEventListener("click", () => close());
backdrop
.querySelector("#reschedule-cancel-btn")
?.addEventListener("click", () => close());
backdrop.addEventListener("click", (e) => {
if (e.target === backdrop) close();
});
const form = backdrop.querySelector<HTMLFormElement>("#reschedule-form");
const dateInput =
backdrop.querySelector<HTMLInputElement>("#reschedule-date");
const timeInput =
backdrop.querySelector<HTMLInputElement>("#reschedule-time");
const notesInput =
backdrop.querySelector<HTMLTextAreaElement>("#reschedule-notes");
const submitBtn = backdrop.querySelector<HTMLButtonElement>(
"#reschedule-submit-btn",
);
const errorBox = backdrop.querySelector<HTMLDivElement>("#reschedule-error");
form?.addEventListener("submit", async (e) => {
e.preventDefault();
if (!submitBtn || !errorBox) return;
const dVal = dateInput?.value;
const tVal = timeInput?.value;
const notes = notesInput?.value.trim() || undefined;
if (!dVal || !tVal) {
errorBox.textContent = "Por favor selecciona la nueva fecha y hora.";
errorBox.classList.remove("hidden");
return;
}
const newDt = new Date(`${dVal}T${tVal}:00`);
if (Number.isNaN(newDt.getTime())) {
errorBox.textContent = "Fecha u hora inválida.";
errorBox.classList.remove("hidden");
return;
}
submitBtn.disabled = true;
submitBtn.textContent = "Reagendando...";
errorBox.classList.add("hidden");
try {
const updated = await rescheduleBooking(booking.id, {
new_scheduled_at: newDt.toISOString(),
notes,
});
close();
onSuccess(updated);
} catch (err: unknown) {
submitBtn.disabled = false;
submitBtn.textContent = "Confirmar Nuevo Horario";
errorBox.textContent =
err instanceof Error ? err.message : "Error al reagendar la consulta.";
errorBox.classList.remove("hidden");
}
});
}
+569
View File
@@ -0,0 +1,569 @@
import { createBooking, fetchServices, searchClients } from "../api";
import type { Booking, Client, Service } from "../types";
import {
debounce,
formatCurrency,
formatDateInput,
formatMexicanPhone,
} from "../utils";
import { showToast } from "./Toast";
export interface IntakeModalOptions {
onSuccess: (booking: Booking) => void;
defaultDate?: Date;
}
export function openBookingIntakeModal(options: IntakeModalOptions): void {
const { onSuccess, defaultDate = new Date() } = options;
const existingBackdrop = document.getElementById("intake-modal-backdrop");
if (existingBackdrop) existingBackdrop.remove();
const backdrop = document.createElement("div");
backdrop.id = "intake-modal-backdrop";
backdrop.className = "modal-backdrop intake-modal-backdrop";
const defaultDateStr = formatDateInput(defaultDate);
// Default time: next hour or 10:00
const currentHour = new Date().getHours();
const nextHour = Math.min(20, Math.max(9, currentHour + 1));
const defaultTimeStr = `${String(nextHour).padStart(2, "0")}:00`;
backdrop.innerHTML = `
<div class="modal-card modal-card-lg" role="dialog" aria-modal="true" aria-labelledby="intake-modal-title">
<div class="modal-header">
<div>
<span class="modal-kicker">Recepción Operativa</span>
<h3 id="intake-modal-title" class="modal-title">+ Nueva Cita</h3>
</div>
<button type="button" class="modal-close-btn" id="intake-modal-close" aria-label="Cerrar ventana">&times;</button>
</div>
<div class="modal-body">
<p class="modal-subtitle-text">
Registra una cita directa. Se aplicará la validación de colisiones y buffer de 15 minutos obligatorio.
</p>
<form id="intake-form" class="modal-form-content">
<!-- 1. Servicio -->
<div class="form-group">
<label for="intake-service" class="form-label font-semibold">
1. Servicio <span class="text-danger">*</span>
</label>
<select id="intake-service" name="service_id" class="form-select" required>
<option value="">Cargando servicios...</option>
</select>
<div id="service-preview-hint" class="service-preview-hint text-xs text-muted mt-1"></div>
</div>
<!-- 2. Cliente Search Combobox -->
<div class="form-group client-combobox-group">
<div class="combobox-label-row">
<label for="client-search-input" class="form-label font-semibold">
2. Paciente / Consultante <span class="text-danger">*</span>
</label>
<span id="client-type-badge" class="client-type-badge badge-new">✦ Nuevo Consultante</span>
</div>
<div class="combobox-wrapper">
<div class="combobox-input-container">
<span class="combobox-icon" aria-hidden="true">🔍</span>
<input
type="text"
id="client-search-input"
class="form-input combobox-input"
placeholder="Buscar por nombre o teléfono, o escribir uno nuevo..."
autocomplete="off"
required
/>
<button type="button" id="clear-client-btn" class="btn-clear-input hidden" title="Limpiar selección">&times;</button>
</div>
<!-- Autocomplete dropdown list -->
<div id="combobox-dropdown" class="combobox-dropdown hidden" role="listbox"></div>
</div>
<div class="client-fields-grid mt-2">
<div class="form-subgroup">
<label for="client-phone-input" class="form-sublabel">Teléfono WhatsApp (+52) <span class="text-danger">*</span></label>
<input
type="tel"
id="client-phone-input"
name="client_phone"
class="form-input"
placeholder="+52 55 1234 5678"
required
/>
</div>
<div class="form-subgroup">
<label for="client-email-input" class="form-sublabel">Correo Electrónico (opcional)</label>
<input
type="email"
id="client-email-input"
name="client_email"
class="form-input"
placeholder="correo@ejemplo.com"
/>
</div>
</div>
</div>
<!-- 3. Fecha y Hora -->
<div class="form-group">
<label class="form-label font-semibold">
3. Fecha y Horario <span class="text-danger">*</span>
</label>
<div class="datetime-grid">
<div class="form-subgroup">
<label for="intake-date" class="form-sublabel">Día de la cita:</label>
<input
type="date"
id="intake-date"
class="form-input"
value="${defaultDateStr}"
required
/>
</div>
<div class="form-subgroup">
<label for="intake-time" class="form-sublabel">Hora de inicio:</label>
<input
type="time"
id="intake-time"
class="form-input"
value="${defaultTimeStr}"
step="900"
required
/>
</div>
</div>
</div>
<!-- 4. Notas u Observaciones -->
<div class="form-group">
<label for="intake-notes" class="form-label font-semibold">
4. Motivo de Consulta u Observaciones (opcional)
</label>
<textarea
id="intake-notes"
name="notes"
class="form-textarea"
rows="2"
placeholder="Ej. Primera vez con dolor lumbar; recomendada por María."
></textarea>
</div>
<!-- Error container -->
<div id="intake-error" class="modal-error-box hidden" role="alert"></div>
<!-- Modal actions -->
<div class="modal-actions">
<button type="button" id="intake-cancel-btn" class="btn btn-secondary">
Cancelar
</button>
<button type="submit" id="intake-submit-btn" class="btn btn-primary btn-submit-intake">
<span>✓ Agendar Cita</span>
</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("#intake-modal-close")
?.addEventListener("click", () => close());
backdrop
.querySelector("#intake-cancel-btn")
?.addEventListener("click", () => close());
backdrop.addEventListener("click", (e) => {
if (e.target === backdrop) close();
});
// Elements
const form = backdrop.querySelector<HTMLFormElement>("#intake-form");
const serviceSelect =
backdrop.querySelector<HTMLSelectElement>("#intake-service");
const serviceHint = backdrop.querySelector<HTMLDivElement>(
"#service-preview-hint",
);
const searchInput = backdrop.querySelector<HTMLInputElement>(
"#client-search-input",
);
const phoneInput = backdrop.querySelector<HTMLInputElement>(
"#client-phone-input",
);
const emailInput = backdrop.querySelector<HTMLInputElement>(
"#client-email-input",
);
const clientBadge =
backdrop.querySelector<HTMLSpanElement>("#client-type-badge");
const clearClientBtn =
backdrop.querySelector<HTMLButtonElement>("#clear-client-btn");
const dropdown = backdrop.querySelector<HTMLDivElement>("#combobox-dropdown");
const dateInput = backdrop.querySelector<HTMLInputElement>("#intake-date");
const timeInput = backdrop.querySelector<HTMLInputElement>("#intake-time");
const notesInput =
backdrop.querySelector<HTMLTextAreaElement>("#intake-notes");
const errorBox = backdrop.querySelector<HTMLDivElement>("#intake-error");
const submitBtn =
backdrop.querySelector<HTMLButtonElement>("#intake-submit-btn");
let availableServices: Service[] = [];
let selectedClient: Client | null = null;
// 1. Load Services
fetchServices(true)
.then((services) => {
availableServices = services;
if (!serviceSelect) return;
if (services.length === 0) {
serviceSelect.innerHTML =
'<option value="">No hay servicios activos</option>';
return;
}
serviceSelect.innerHTML = `
<option value="">-- Selecciona un servicio --</option>
${services
.map(
(s) => `
<option value="${s.id}" data-duration="${s.duration_minutes}" data-buffer="${s.buffer_minutes}" data-price="${s.price_mxn}">
${s.name} (${s.modality === "PRESENCIAL" ? "Presencial" : "En Línea"}) — ${s.duration_minutes} min — ${formatCurrency(s.price_mxn)}
</option>
`,
)
.join("")}
`;
// Auto-select first service if available
if (services.length > 0) {
serviceSelect.value = services[0].id;
updateServiceHint(services[0]);
}
})
.catch((err) => {
if (serviceSelect) {
serviceSelect.innerHTML =
'<option value="">Error al cargar catálogo</option>';
}
if (errorBox) {
errorBox.textContent = `Error al cargar servicios: ${err instanceof Error ? err.message : "Desconocido"}`;
errorBox.classList.remove("hidden");
}
});
const updateServiceHint = (svc?: Service) => {
if (!serviceHint) return;
if (!svc) {
serviceHint.innerHTML = "";
return;
}
serviceHint.innerHTML = `
⏱️ Duración: <strong>${svc.duration_minutes} min</strong> + <strong>${svc.buffer_minutes || 15} min</strong> de colchón obligatorio protegido.
${svc.price_mxn ? `&bull; Tarifa: <strong>${formatCurrency(svc.price_mxn)}</strong>` : ""}
`;
};
serviceSelect?.addEventListener("change", () => {
const sId = serviceSelect.value;
const svc = availableServices.find((s) => s.id === sId);
updateServiceHint(svc);
});
// 2. Client Combobox & Autocomplete
const selectExistingClient = (c: Client) => {
selectedClient = c;
if (searchInput) searchInput.value = c.full_name;
if (phoneInput) phoneInput.value = formatMexicanPhone(c.phone_whatsapp);
if (emailInput) emailInput.value = c.email || "";
if (clientBadge) {
clientBadge.textContent = "✓ Cliente Registrado";
clientBadge.className = "client-type-badge badge-existing";
}
clearClientBtn?.classList.remove("hidden");
hideDropdown();
};
const clearSelectedClient = () => {
selectedClient = null;
if (searchInput) searchInput.value = "";
if (phoneInput) phoneInput.value = "";
if (emailInput) emailInput.value = "";
if (clientBadge) {
clientBadge.textContent = "✦ Nuevo Consultante";
clientBadge.className = "client-type-badge badge-new";
}
clearClientBtn?.classList.add("hidden");
hideDropdown();
searchInput?.focus();
};
clearClientBtn?.addEventListener("click", clearSelectedClient);
const hideDropdown = () => {
if (dropdown) dropdown.classList.add("hidden");
};
const showDropdown = () => {
if (dropdown) dropdown.classList.remove("hidden");
};
const doSearch = debounce(async (query: string) => {
const q = query.trim();
if (!q || !dropdown) {
hideDropdown();
return;
}
try {
const results = await searchClients(q);
if (results.length === 0) {
dropdown.innerHTML = `
<div class="combobox-empty">
No se encontraron pacientes para "<strong>${escapeHtml(q)}</strong>".
<span class="text-xs text-muted block mt-1">Se registrará como nuevo paciente con los datos ingresados.</span>
</div>
`;
showDropdown();
return;
}
dropdown.innerHTML = results
.map(
(c) => `
<div class="combobox-item" role="option" data-id="${c.id}">
<div class="font-medium">${escapeHtml(c.full_name)}</div>
<div class="combobox-meta text-xs text-muted">
<span>📱 ${escapeHtml(c.phone_whatsapp)}</span>
${c.email ? `<span>✉️ ${escapeHtml(c.email)}</span>` : ""}
</div>
</div>
`,
)
.join("");
dropdown.querySelectorAll(".combobox-item").forEach((item) => {
item.addEventListener("click", () => {
const id = item.getAttribute("data-id");
const found = results.find((r) => r.id === id);
if (found) {
selectExistingClient(found);
}
});
});
showDropdown();
} catch {
// Ignore autocomplete failure
}
}, 250);
searchInput?.addEventListener("input", () => {
const val = searchInput.value;
if (selectedClient && val !== selectedClient.full_name) {
selectedClient = null;
if (clientBadge) {
clientBadge.textContent = "✦ Nuevo Consultante";
clientBadge.className = "client-type-badge badge-new";
}
clearClientBtn?.classList.remove("hidden");
}
doSearch(val);
});
// Auto format Mexican phone on blur
phoneInput?.addEventListener("blur", () => {
if (phoneInput.value) {
phoneInput.value = formatMexicanPhone(phoneInput.value);
}
});
// Close dropdown when clicking outside
document.addEventListener("click", (e) => {
if (
dropdown &&
!dropdown.contains(e.target as Node) &&
e.target !== searchInput
) {
hideDropdown();
}
});
// 3. Form Submit
form?.addEventListener("submit", async (e) => {
e.preventDefault();
if (!submitBtn || !errorBox) return;
errorBox.classList.add("hidden");
errorBox.textContent = "";
const serviceId = serviceSelect?.value;
const clientName = searchInput?.value.trim();
let clientPhone = phoneInput?.value.trim();
const clientEmail = emailInput?.value.trim() || undefined;
const dateVal = dateInput?.value;
const timeVal = timeInput?.value;
const notesVal = notesInput?.value.trim() || undefined;
if (!serviceId) {
errorBox.textContent = "Por favor selecciona un servicio.";
errorBox.classList.remove("hidden");
return;
}
if (!clientName || !clientPhone) {
errorBox.textContent =
"El nombre y teléfono de WhatsApp del consultante son obligatorios.";
errorBox.classList.remove("hidden");
return;
}
// Ensure formatted phone
clientPhone = formatMexicanPhone(clientPhone);
if (!dateVal || !timeVal) {
errorBox.textContent = "Por favor define la fecha y hora de la cita.";
errorBox.classList.remove("hidden");
return;
}
// Build scheduled_at in ISO format
const localDateTimeString = `${dateVal}T${timeVal}:00`;
const scheduledDate = new Date(localDateTimeString);
if (Number.isNaN(scheduledDate.getTime())) {
errorBox.textContent = "La fecha u hora seleccionada no es válida.";
errorBox.classList.remove("hidden");
return;
}
submitBtn.disabled = true;
submitBtn.textContent = "Agendando sesión...";
try {
const booking = await createBooking({
service_id: serviceId,
client_name: clientName,
client_phone: clientPhone,
client_email: clientEmail,
scheduled_at: scheduledDate.toISOString(),
notes: notesVal,
});
close();
onSuccess(booking);
// Toast with Folio
showToast(
`Cita agendada para ${booking.client_name || clientName}`,
"success",
6000,
{ folio: booking.booking_code },
);
// 1-Tap WhatsApp confirmation dialog
showBookingCreatedSuccessModal(booking);
} catch (err: unknown) {
submitBtn.disabled = false;
submitBtn.textContent = "✓ Agendar Cita";
errorBox.textContent =
err instanceof Error
? err.message
: "Error inesperado al registrar la cita.";
errorBox.classList.remove("hidden");
}
});
// Focus first input
searchInput?.focus();
}
function showBookingCreatedSuccessModal(booking: Booking): void {
const waUrl =
booking.whatsapp_redirect_url ||
`https://wa.me/${(booking.client_phone || "").replace(/\D/g, "")}?text=${encodeURIComponent(
`Hola ${booking.client_name || ""}, te confirmamos tu cita en Armonía del Ser con folio ${booking.booking_code}. ¡Te esperamos!`,
)}`;
const modal = document.createElement("div");
modal.className = "modal-backdrop";
modal.innerHTML = `
<div class="modal-card" role="dialog" aria-modal="true">
<div class="modal-header">
<div>
<span class="modal-kicker text-success">✓ Cita Confirmada</span>
<h3 class="modal-title">Folio ${booking.booking_code}</h3>
</div>
<button type="button" class="modal-close-btn" id="success-modal-close">&times;</button>
</div>
<div class="modal-body">
<div class="summary-box">
<div class="summary-row">
<span class="summary-label">Paciente:</span>
<span class="summary-value font-semibold">${booking.client_name}</span>
</div>
<div class="summary-row">
<span class="summary-label">Servicio:</span>
<span class="summary-value">${booking.service_name || "Consulta"}</span>
</div>
<div class="summary-row">
<span class="summary-label">Fecha y Hora:</span>
<span class="summary-value font-medium">${new Date(booking.scheduled_at).toLocaleString("es-MX", { dateStyle: "long", timeStyle: "short" })}</span>
</div>
</div>
<p class="modal-subtitle-text mt-3">
La cita ha sido reservada y el buffer protector ha sido bloqueado en el sistema.
</p>
<div class="modal-actions mt-4">
<a
href="${waUrl}"
target="_blank"
rel="noopener noreferrer"
id="btn-send-wa-confirm"
class="btn btn-whatsapp"
>
<span>💬 Enviar Confirmación por WhatsApp</span>
</a>
<button type="button" id="success-modal-dismiss" class="btn btn-secondary">
Listo
</button>
</div>
</div>
</div>
`;
document.body.appendChild(modal);
const closeSuccess = () => modal.remove();
modal
.querySelector("#success-modal-close")
?.addEventListener("click", closeSuccess);
modal
.querySelector("#success-modal-dismiss")
?.addEventListener("click", closeSuccess);
modal.querySelector("#btn-send-wa-confirm")?.addEventListener("click", () => {
setTimeout(closeSuccess, 500);
});
}
function escapeHtml(str: string): string {
return str
.replace(/&/g, "&amp;")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;")
.replace(/"/g, "&quot;")
.replace(/'/g, "&#039;");
}
+1 -1
View File
@@ -1,3 +1,4 @@
import { acknowledgePayment } from "../api";
import type { Booking } from "../types"; import type { Booking } from "../types";
import { formatCurrency } from "../utils"; import { formatCurrency } from "../utils";
@@ -161,7 +162,6 @@ export function openPaymentModal(options: {
const notes = notesInput?.value.trim() || undefined; const notes = notesInput?.value.trim() || undefined;
try { try {
const { acknowledgePayment } = await import("../api");
await acknowledgePayment({ await acknowledgePayment({
booking_id: booking.id, booking_id: booking.id,
amount_mxn: amount, amount_mxn: amount,
+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();
}
+114 -9
View File
@@ -1,10 +1,14 @@
import "./style.css"; import "./style.css";
import { fetchFollowUpQueue } from "./api"; import { fetchCurrentAdmin, fetchFollowUpQueue } from "./api";
import { renderAllBookings } from "./components/AllBookings"; import { renderAllBookings } from "./components/AllBookings";
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 { renderWorkshopRoster } from "./components/WorkshopRoster";
import { getRoleBadge } from "./utils";
type TabId = "queue" | "agenda" | "all"; type TabId = "queue" | "agenda" | "clients" | "all" | "rosters";
class OperatorDashboardApp { class OperatorDashboardApp {
private activeTab: TabId = "queue"; private activeTab: TabId = "queue";
@@ -22,11 +26,30 @@ class OperatorDashboardApp {
private async init(): Promise<void> { private async init(): Promise<void> {
this.renderShell(); this.renderShell();
this.bindEvents(); this.bindEvents();
await Promise.allSettled([
this.loadOperatorIdentity(),
this.refreshTabBadge(),
]);
const hash = window.location.hash.replace("#", "") as TabId | "nueva-cita";
if (hash === "nueva-cita") {
this.switchTab("agenda");
openBookingIntakeModal({
onSuccess: async () => {
await this.refreshTabBadge(); await this.refreshTabBadge();
const hash = window.location.hash.replace("#", "") as TabId; this.switchTab(this.activeTab);
const initialTab = hash === "agenda" || hash === "all" ? hash : "queue"; },
});
} else {
const initialTab =
hash === "agenda" ||
hash === "clients" ||
hash === "all" ||
hash === "rosters"
? hash
: "queue";
this.switchTab(initialTab); this.switchTab(initialTab);
} }
}
private renderShell(): void { private renderShell(): void {
this.container.innerHTML = ` this.container.innerHTML = `
@@ -39,10 +62,22 @@ class OperatorDashboardApp {
</div> </div>
<span class="brand-badge">Operador</span> <span class="brand-badge">Operador</span>
</div> </div>
<div class="operator-profile">
<div class="operator-badge"> <div class="header-actions">
<span class="status-dot"></span> <button
<span>Jasmin & Asistente</span> id="global-new-booking-btn"
class="btn btn-primary btn-new-booking"
type="button"
title="Registrar una nueva reservación de consulta"
>
<span>+ Nueva Cita</span>
</button>
<div id="operator-profile" class="operator-profile" aria-live="polite">
<div class="operator-badge operator-badge-loading">
<span class="status-dot status-dot-pulse"></span>
<span class="operator-name-text">Cargando operador...</span>
</div>
</div> </div>
</div> </div>
</header> </header>
@@ -56,6 +91,12 @@ 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">
<span>Clientes</span>
</button>
<button class="nav-tab" data-tab="all" role="tab" aria-selected="false"> <button class="nav-tab" data-tab="all" role="tab" aria-selected="false">
<span>Todas las Citas</span> <span>Todas las Citas</span>
</button> </button>
@@ -75,6 +116,14 @@ 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">
<span class="mobile-nav-icon" aria-hidden="true">👥</span>
<span class="mobile-nav-label">Clientes</span>
</button>
<button class="mobile-nav-item" data-tab="all" role="tab" aria-selected="false"> <button class="mobile-nav-item" data-tab="all" 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">Historial</span> <span class="mobile-nav-label">Historial</span>
@@ -83,7 +132,52 @@ class OperatorDashboardApp {
`; `;
} }
private async loadOperatorIdentity(): Promise<void> {
const profileEl =
this.container.querySelector<HTMLElement>("#operator-profile");
if (!profileEl) return;
try {
const admin = await fetchCurrentAdmin();
const roleInfo = getRoleBadge(admin.role);
profileEl.innerHTML = `
<div class="operator-badge operator-badge-authenticated" title="Sesión activa: ${admin.email}">
<span class="status-dot status-dot-online"></span>
<span class="operator-name font-medium">${admin.full_name}</span>
<span class="operator-role-pill ${roleInfo.roleClass}">
${roleInfo.label}
</span>
</div>
`;
} catch {
// Graceful fallback if unauthorized or loading error
profileEl.innerHTML = `
<div class="operator-badge operator-badge-fallback" title="Sesión local o sin conexión">
<span class="status-dot status-dot-offline"></span>
<span class="operator-name">Jasmin & Asistente</span>
<span class="operator-role-pill role-fallback">Local</span>
</div>
`;
}
}
private bindEvents(): void { private bindEvents(): void {
// New Booking Button
const newBookingBtn = this.container.querySelector<HTMLButtonElement>(
"#global-new-booking-btn",
);
newBookingBtn?.addEventListener("click", () => {
openBookingIntakeModal({
onSuccess: async () => {
await this.refreshTabBadge();
// Refresh current view
this.switchTab(this.activeTab);
},
});
});
// Tab Switching Buttons
const allTabButtons = const allTabButtons =
this.container.querySelectorAll<HTMLButtonElement>("[data-tab]"); this.container.querySelectorAll<HTMLButtonElement>("[data-tab]");
allTabButtons.forEach((btn) => { allTabButtons.forEach((btn) => {
@@ -95,9 +189,16 @@ class OperatorDashboardApp {
}); });
}); });
// Hash routing
window.addEventListener("hashchange", () => { window.addEventListener("hashchange", () => {
const hash = window.location.hash.replace("#", "") as TabId; const hash = window.location.hash.replace("#", "") as TabId;
if (hash === "queue" || hash === "agenda" || hash === "all") { if (
hash === "queue" ||
hash === "agenda" ||
hash === "rosters" ||
hash === "clients" ||
hash === "all"
) {
if (this.activeTab !== hash) { if (this.activeTab !== hash) {
this.switchTab(hash); this.switchTab(hash);
} }
@@ -130,6 +231,10 @@ 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") {
renderClientDirectory(contentEl, onStateChange);
} else if (tab === "all") { } else if (tab === "all") {
renderAllBookings(contentEl); renderAllBookings(contentEl);
} }
+851 -2
View File
@@ -109,16 +109,96 @@ body {
margin-left: 8px; margin-left: 8px;
} }
.operator-badge { .header-actions {
display: flex;
align-items: center;
gap: 12px;
flex-wrap: wrap;
}
.btn-new-booking {
min-height: 44px;
padding: 8px 16px;
font-weight: 600;
border-radius: var(--radius-md);
display: inline-flex; display: inline-flex;
align-items: center; align-items: center;
gap: 6px; gap: 6px;
box-shadow: var(--shadow-sm);
transition: all 0.15s ease;
}
.btn-new-booking:hover {
transform: translateY(-1px);
box-shadow: var(--shadow-md);
}
.operator-badge {
display: inline-flex;
align-items: center;
gap: 8px;
font-size: 13px; font-size: 13px;
color: var(--color-text-muted); color: var(--color-text-main);
background: var(--color-surface); background: var(--color-surface);
padding: 6px 12px; padding: 6px 12px;
border-radius: var(--radius-md); border-radius: var(--radius-md);
border: 1px solid var(--color-border); border: 1px solid var(--color-border);
min-height: 44px;
}
.operator-badge-loading {
color: var(--color-text-muted);
}
.status-dot-pulse {
animation: pulse-dot 1.5s infinite ease-in-out;
}
@keyframes pulse-dot {
0%,
100% {
opacity: 0.4;
transform: scale(0.9);
}
50% {
opacity: 1;
transform: scale(1.1);
}
}
.status-dot-online {
background-color: var(--color-success);
}
.status-dot-offline {
background-color: var(--color-warning);
}
.operator-role-pill {
font-size: 11px;
font-weight: 700;
text-transform: uppercase;
letter-spacing: 0.04em;
padding: 2px 8px;
border-radius: 999px;
}
.role-owner {
background: var(--color-gold-light);
color: var(--color-gold);
border: 1px solid rgba(184, 134, 11, 0.3);
}
.role-assistant {
background: var(--color-sage-light);
color: var(--color-sage);
border: 1px solid rgba(45, 90, 70, 0.3);
}
.role-fallback {
background: var(--color-surface-soft);
color: var(--color-text-muted);
border: 1px solid var(--color-border);
} }
.status-dot { .status-dot {
@@ -1376,6 +1456,339 @@ body {
margin-top: 2px; margin-top: 2px;
} }
/* ==========================================================================
Intake Modal & Autocomplete Combobox
========================================================================== */
.modal-card-lg {
max-width: 620px;
}
.client-combobox-group {
position: relative;
}
.combobox-label-row {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 6px;
}
.client-type-badge {
font-size: 11px;
font-weight: 700;
padding: 2px 8px;
border-radius: 999px;
text-transform: uppercase;
letter-spacing: 0.04em;
}
.badge-new {
background: var(--color-gold-light);
color: var(--color-gold);
border: 1px solid rgba(184, 134, 11, 0.25);
}
.badge-existing {
background: var(--color-success-light);
color: var(--color-success);
border: 1px solid rgba(30, 126, 78, 0.25);
}
.combobox-wrapper {
position: relative;
}
.combobox-input-container {
position: relative;
display: flex;
align-items: center;
}
.combobox-icon {
position: absolute;
left: 12px;
color: var(--color-text-muted);
pointer-events: none;
font-size: 14px;
}
.combobox-input {
padding-left: 36px;
padding-right: 36px;
}
.btn-clear-input {
position: absolute;
right: 8px;
background: none;
border: none;
font-size: 18px;
color: var(--color-text-muted);
cursor: pointer;
padding: 4px;
display: flex;
align-items: center;
justify-content: center;
min-width: 36px;
min-height: 36px;
border-radius: 50%;
}
.btn-clear-input:hover {
color: var(--color-text-main);
background: var(--color-surface-soft);
}
.combobox-dropdown {
position: absolute;
top: 100%;
left: 0;
right: 0;
margin-top: 4px;
background: var(--color-surface);
border: 1px solid var(--color-border);
border-radius: var(--radius-md);
box-shadow: var(--shadow-lg);
max-height: 220px;
overflow-y: auto;
z-index: 100;
}
.combobox-item {
padding: 10px 14px;
cursor: pointer;
border-bottom: 1px solid var(--color-border);
transition: background 0.15s ease;
}
.combobox-item:last-child {
border-bottom: none;
}
.combobox-item:hover,
.combobox-item:focus {
background: var(--color-sage-light);
}
.combobox-meta {
display: flex;
gap: 12px;
margin-top: 2px;
}
.combobox-empty {
padding: 12px 14px;
font-size: 13px;
color: var(--color-text-muted);
}
.client-fields-grid {
display: grid;
grid-template-columns: 1fr;
gap: 10px;
}
@media (min-width: 580px) {
.client-fields-grid {
grid-template-columns: 1fr 1fr;
}
}
.datetime-grid {
display: grid;
grid-template-columns: 1fr;
gap: 10px;
}
@media (min-width: 580px) {
.datetime-grid {
grid-template-columns: 1fr 1fr;
}
}
.form-subgroup {
display: flex;
flex-direction: column;
gap: 4px;
}
.form-sublabel {
font-size: 12px;
font-weight: 500;
color: var(--color-text-muted);
}
.service-preview-hint {
background: var(--color-sage-light);
color: var(--color-sage-dark);
padding: 6px 10px;
border-radius: var(--radius-sm);
margin-top: 6px;
border: 1px solid rgba(45, 90, 70, 0.15);
line-height: 1.4;
}
/* ==========================================================================
Agenda Card Lifecycle Actions (Mover & Concluir)
========================================================================== */
.agenda-card-actions {
display: flex;
gap: 8px;
margin-top: 12px;
padding-top: 10px;
border-top: 1px dashed var(--color-border);
flex-wrap: wrap;
}
.btn-outline-success {
background: transparent;
color: var(--color-success);
border: 1px solid var(--color-success);
}
.btn-outline-success:hover {
background: var(--color-success-light);
border-color: var(--color-success);
}
/* ==========================================================================
Client Directory View
========================================================================== */
.directory-search-bar {
display: flex;
justify-content: space-between;
align-items: center;
gap: 16px;
margin-bottom: 20px;
flex-wrap: wrap;
}
.search-input-group {
position: relative;
flex: 1;
min-width: 260px;
display: flex;
align-items: center;
}
.directory-search-input {
padding-left: 36px;
padding-right: 36px;
min-height: 44px;
}
.search-icon {
position: absolute;
left: 12px;
font-size: 14px;
color: var(--color-text-muted);
pointer-events: none;
}
.clients-counter-pill {
font-weight: 500;
color: var(--color-text-muted);
}
.clients-grid {
display: grid;
grid-template-columns: 1fr;
gap: 16px;
}
@media (min-width: 768px) {
.clients-grid {
grid-template-columns: 1fr 1fr;
}
}
.client-card {
background: var(--color-surface);
border: 1px solid var(--color-border);
border-radius: var(--radius-md);
padding: 18px;
box-shadow: var(--shadow-sm);
display: flex;
flex-direction: column;
gap: 12px;
}
.client-card-header {
display: flex;
justify-content: space-between;
align-items: flex-start;
gap: 12px;
}
.client-card-name {
font-size: 17px;
font-weight: 600;
color: var(--color-sage-dark);
}
.client-registered-date {
display: block;
margin-top: 2px;
}
.client-card-body {
display: flex;
flex-direction: column;
gap: 10px;
}
.client-contact-row {
display: flex;
align-items: center;
gap: 10px;
flex-wrap: wrap;
}
.client-email-badge {
color: var(--color-text-muted);
}
.packages-tags-container {
display: flex;
flex-wrap: wrap;
gap: 6px;
}
.package-pill {
display: inline-block;
background: var(--color-gold-light);
color: var(--color-gold);
border: 1px solid rgba(184, 134, 11, 0.3);
font-size: 12px;
font-weight: 600;
padding: 3px 8px;
border-radius: var(--radius-sm);
}
.client-notes-box {
background: var(--color-surface-soft);
padding: 8px 12px;
border-radius: var(--radius-sm);
border-left: 3px solid var(--color-sage);
}
.notes-kicker {
color: var(--color-sage-dark);
text-transform: uppercase;
letter-spacing: 0.04em;
display: block;
}
.notes-content {
color: var(--color-text-main);
line-height: 1.4;
}
.client-notes-empty {
font-style: italic;
}
/* ========================================================================== /* ==========================================================================
Sticky Mobile Navigation Bar & Mobile Ergonomics Sticky Mobile Navigation Bar & Mobile Ergonomics
========================================================================== */ ========================================================================== */
@@ -1482,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;
}
}
+137
View File
@@ -72,3 +72,140 @@ export interface PaymentRecord {
notes?: string | null; notes?: string | null;
created_at: string; created_at: string;
} }
export type AdminRole = "OWNER" | "ASSISTANT";
export interface AdminPrincipal {
email: string;
full_name: string;
role: AdminRole;
is_active: boolean;
last_login_at?: string | null;
}
export type ServiceType = "INDIVIDUAL" | "GROUP";
export type ServiceModality = "PRESENCIAL" | "ONLINE";
export interface Service {
id: string;
slug: string;
name: string;
description?: string | null;
service_type: ServiceType;
modality: ServiceModality;
default_schedule?: string | null;
price_mxn: number;
max_capacity: number;
duration_minutes: number;
buffer_minutes: number;
is_active: boolean;
}
export interface Client {
id: string;
full_name: string;
phone_whatsapp: string;
email?: string | null;
notes?: string | null;
created_at: string;
}
export interface ClientUpdatePayload {
full_name?: string;
phone_whatsapp?: string;
email?: string | null;
notes?: string | null;
}
export interface PackageRecord {
id: string;
client_id: string;
client_name?: string | null;
client_phone?: string | null;
service_id: string;
service_name?: string | null;
total_sessions: number;
completed_sessions: number;
remaining_sessions: number;
price_paid_mxn: number;
financial_status: "PAID" | "PARTIAL" | "PENDING";
notes?: string | null;
created_at: string;
updated_at: string;
}
export interface Client360 extends Client {
active_packages: PackageRecord[];
booking_history: Booking[];
recent_bookings: Booking[];
}
export interface BookingCreatePayload {
service_id: string;
client_name: string;
client_phone: string;
client_email?: string | null;
scheduled_at: string;
notes?: string | null;
package_id?: string | null;
}
export interface BookingReschedulePayload {
new_scheduled_at: string;
notes?: string | null;
}
export interface BookingCompletePayload {
package_id?: 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;
}
+50
View File
@@ -173,3 +173,53 @@ export function checkBufferCollision(
deficitMinutes, deficitMinutes,
}; };
} }
export function formatMexicanPhone(input: string): string {
const trimmed = input.trim();
if (!trimmed) return "";
// Strip all non-digit characters
const digits = trimmed.replace(/\D/g, "");
// If 10 digits (Mexican national format, e.g. 5512345678)
if (digits.length === 10) {
return `+52 ${digits.slice(0, 2)} ${digits.slice(2, 6)} ${digits.slice(6)}`;
}
// If 12 digits starting with 52
if (digits.length === 12 && digits.startsWith("52")) {
const national = digits.slice(2);
return `+52 ${national.slice(0, 2)} ${national.slice(2, 6)} ${national.slice(6)}`;
}
// Otherwise return input as-is or cleaned
return trimmed;
}
export function getCleanDigitsPhone(phone: string): string {
const digits = phone.replace(/\D/g, "");
if (digits.length === 10) return `52${digits}`;
return digits;
}
export function getRoleBadge(role: "OWNER" | "ASSISTANT" | string): {
label: string;
roleClass: string;
} {
if (role === "OWNER") {
return { label: "Titular", roleClass: "role-owner" };
}
if (role === "ASSISTANT") {
return { label: "Asistente", roleClass: "role-assistant" };
}
return { label: role || "Operador", roleClass: "role-fallback" };
}
export function debounce<Args extends unknown[]>(
fn: (...args: Args) => void,
delayMs = 250,
): (...args: Args) => void {
let timer: ReturnType<typeof setTimeout> | undefined;
return (...args: Args) => {
if (timer) clearTimeout(timer);
timer = setTimeout(() => {
fn(...args);
}, delayMs);
};
}
+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");
});
});
});
+65
View File
@@ -2,9 +2,13 @@ import { describe, expect, it } from "vitest";
import { import {
calculateInterval, calculateInterval,
checkBufferCollision, checkBufferCollision,
debounce,
formatCurrency, formatCurrency,
formatDateInput, formatDateInput,
formatMexicanPhone,
getCleanDigitsPhone,
getHoursRemainingBadge, getHoursRemainingBadge,
getRoleBadge,
isSameDay, isSameDay,
isThisWeek, isThisWeek,
isToday, isToday,
@@ -102,4 +106,65 @@ describe("Frontend Utilities", () => {
expect(result.deficitMinutes).toBe(30); // 15 min session + 15 min buffer expect(result.deficitMinutes).toBe(30); // 15 min session + 15 min buffer
}); });
}); });
describe("Phone and WhatsApp Utilities", () => {
it("formats 10-digit national number to Mexican international format (+52)", () => {
expect(formatMexicanPhone("5512345678")).toBe("+52 55 1234 5678");
expect(formatMexicanPhone("55-1234-5678")).toBe("+52 55 1234 5678");
expect(formatMexicanPhone("(55) 1234 5678")).toBe("+52 55 1234 5678");
});
it("formats 12-digit number with 52 prefix correctly", () => {
expect(formatMexicanPhone("525512345678")).toBe("+52 55 1234 5678");
expect(formatMexicanPhone("+525512345678")).toBe("+52 55 1234 5678");
});
it("returns empty string on empty input", () => {
expect(formatMexicanPhone("")).toBe("");
expect(formatMexicanPhone(" ")).toBe("");
});
it("cleans phone digits for wa.me links", () => {
expect(getCleanDigitsPhone("5512345678")).toBe("525512345678");
expect(getCleanDigitsPhone("+52 55 1234 5678")).toBe("525512345678");
expect(getCleanDigitsPhone("525512345678")).toBe("525512345678");
});
});
describe("Operator Role Badges", () => {
it("maps OWNER to Titular with role-owner class", () => {
const badge = getRoleBadge("OWNER");
expect(badge.label).toBe("Titular");
expect(badge.roleClass).toBe("role-owner");
});
it("maps ASSISTANT to Asistente with role-assistant class", () => {
const badge = getRoleBadge("ASSISTANT");
expect(badge.label).toBe("Asistente");
expect(badge.roleClass).toBe("role-assistant");
});
it("falls back gracefully for unknown roles", () => {
const badge = getRoleBadge("UNKNOWN");
expect(badge.label).toBe("UNKNOWN");
expect(badge.roleClass).toBe("role-fallback");
});
});
describe("Debounce Utility", () => {
it("debounces calls within timeout", async () => {
let counter = 0;
const fn = debounce(() => {
counter++;
}, 50);
fn();
fn();
fn();
expect(counter).toBe(0);
await new Promise((resolve) => setTimeout(resolve, 80));
expect(counter).toBe(1);
});
});
}); });