Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0098b5214c | ||
|
|
4e1e7f2ba3 | ||
|
|
9191899154 | ||
|
|
faa2d34b54 | ||
|
|
d672065186 | ||
|
|
191a02d6c2 | ||
|
|
6ba0bbe7d0 | ||
|
|
c09f6c6ae3 | ||
|
|
0ff27a2038 | ||
|
|
00b59182ac | ||
|
|
7f56fe06d2 | ||
|
|
6fe2b6c9e6 | ||
|
|
6cbc8b53c1 |
No files matched your search
@@ -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).
|
||||
|
||||
|
After Width: | Height: | Size: 100 KiB |
|
After Width: | Height: | Size: 86 KiB |
|
After Width: | Height: | Size: 146 KiB |
|
After Width: | Height: | Size: 61 KiB |
|
After Width: | Height: | Size: 62 KiB |
|
After Width: | Height: | Size: 58 KiB |
|
After Width: | Height: | Size: 87 KiB |
|
After Width: | Height: | Size: 62 KiB |
@@ -1,7 +1,19 @@
|
||||
import type {
|
||||
AdminPrincipal,
|
||||
Booking,
|
||||
BookingCompletePayload,
|
||||
BookingCreatePayload,
|
||||
BookingReschedulePayload,
|
||||
Client,
|
||||
Client360,
|
||||
ClientUpdatePayload,
|
||||
PackageRecord,
|
||||
PaymentAcknowledgmentPayload,
|
||||
PaymentRecord,
|
||||
QuickCheckinPayload,
|
||||
QuickCheckinResponse,
|
||||
RosterSession,
|
||||
Service,
|
||||
} from "./types";
|
||||
|
||||
const API_BASE_URL =
|
||||
@@ -130,3 +142,207 @@ export async function retryCalendarSync(bookingId: string): Promise<Booking> {
|
||||
}
|
||||
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();
|
||||
}
|
||||
@@ -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">×</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">×</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, "&")
|
||||
.replace(/</g, "<")
|
||||
.replace(/>/g, ">")
|
||||
.replace(/"/g, """)
|
||||
.replace(/'/g, "'");
|
||||
}
|
||||
@@ -1,16 +1,40 @@
|
||||
import { fetchAllBookings, retryCalendarSync } from "../api";
|
||||
import {
|
||||
completeBooking,
|
||||
fetchAllBookings,
|
||||
rescheduleBooking,
|
||||
retryCalendarSync,
|
||||
} from "../api";
|
||||
import type { Booking } from "../types";
|
||||
import { calculateInterval, formatCurrency, formatDateTime } from "../utils";
|
||||
import {
|
||||
calculateInterval,
|
||||
checkBufferCollision,
|
||||
formatCurrency,
|
||||
formatDateInput,
|
||||
formatDateTime,
|
||||
formatTimeOnly,
|
||||
isSameDay,
|
||||
isThisWeek,
|
||||
isToday,
|
||||
isTomorrow,
|
||||
} from "../utils";
|
||||
import { showConfirmModal } from "./MicroModal";
|
||||
import {
|
||||
renderBookingStatusBadge,
|
||||
renderCalendarSyncBadge,
|
||||
renderPaymentStatusBadge,
|
||||
} from "./StatusBadge";
|
||||
import { showToast } from "./Toast";
|
||||
|
||||
type AgendaDateFilter = "TODAY" | "TOMORROW" | "THIS_WEEK" | "ALL" | "CUSTOM";
|
||||
|
||||
export function renderDailyAgenda(
|
||||
container: HTMLElement,
|
||||
onStateChange: () => void,
|
||||
): void {
|
||||
let activeFilter: AgendaDateFilter = "TODAY";
|
||||
let customDateStr: string = "";
|
||||
let cachedBookings: Booking[] = [];
|
||||
|
||||
container.innerHTML = `
|
||||
<div class="view-header">
|
||||
<div>
|
||||
@@ -24,6 +48,37 @@ export function renderDailyAgenda(
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Date Navigation & Filter Bar -->
|
||||
<div class="agenda-nav-bar">
|
||||
<div class="date-filter-group" role="tablist" aria-label="Filtro de fecha para la agenda">
|
||||
<button type="button" class="btn btn-filter-pill active" data-filter="TODAY" role="tab" aria-selected="true">
|
||||
Hoy
|
||||
</button>
|
||||
<button type="button" class="btn btn-filter-pill" data-filter="TOMORROW" role="tab" aria-selected="false">
|
||||
Mañana
|
||||
</button>
|
||||
<button type="button" class="btn btn-filter-pill" data-filter="THIS_WEEK" role="tab" aria-selected="false">
|
||||
Esta Semana
|
||||
</button>
|
||||
<button type="button" class="btn btn-filter-pill" data-filter="ALL" role="tab" aria-selected="false">
|
||||
Todas
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div class="custom-date-container">
|
||||
<label for="agenda-custom-date" class="date-picker-label">Día específico:</label>
|
||||
<input
|
||||
type="date"
|
||||
id="agenda-custom-date"
|
||||
class="form-input-date"
|
||||
title="Elegir una fecha específica"
|
||||
aria-label="Seleccionar fecha específica en calendario"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="agenda-filter-indicator" class="filter-indicator-banner"></div>
|
||||
|
||||
<div id="agenda-stats" class="stats-row"></div>
|
||||
|
||||
<div id="agenda-content" class="agenda-timeline">
|
||||
@@ -36,9 +91,17 @@ export function renderDailyAgenda(
|
||||
|
||||
const contentDiv = container.querySelector<HTMLDivElement>("#agenda-content");
|
||||
const statsDiv = container.querySelector<HTMLDivElement>("#agenda-stats");
|
||||
const indicatorDiv = container.querySelector<HTMLDivElement>(
|
||||
"#agenda-filter-indicator",
|
||||
);
|
||||
const refreshBtn = container.querySelector<HTMLButtonElement>(
|
||||
"#refresh-agenda-btn",
|
||||
);
|
||||
const customDateInput = container.querySelector<HTMLInputElement>(
|
||||
"#agenda-custom-date",
|
||||
);
|
||||
const filterButtons =
|
||||
container.querySelectorAll<HTMLButtonElement>(".btn-filter-pill");
|
||||
|
||||
const loadData = async () => {
|
||||
if (!contentDiv) return;
|
||||
@@ -50,8 +113,7 @@ export function renderDailyAgenda(
|
||||
|
||||
try {
|
||||
const bookings = await fetchAllBookings();
|
||||
// Filter active bookings and sort chronologically
|
||||
const activeBookings = bookings
|
||||
cachedBookings = bookings
|
||||
.filter(
|
||||
(b) =>
|
||||
b.booking_status !== "CANCELLED" && b.booking_status !== "RELEASED",
|
||||
@@ -62,8 +124,7 @@ export function renderDailyAgenda(
|
||||
new Date(b.scheduled_at).getTime(),
|
||||
);
|
||||
|
||||
renderStats(activeBookings);
|
||||
renderTimeline(activeBookings);
|
||||
applyFilter();
|
||||
} catch (err: unknown) {
|
||||
if (contentDiv) {
|
||||
contentDiv.innerHTML = `
|
||||
@@ -71,12 +132,76 @@ export function renderDailyAgenda(
|
||||
<div class="error-icon">⚠️</div>
|
||||
<h3 class="error-title">Error al cargar la agenda</h3>
|
||||
<p class="error-desc">${err instanceof Error ? err.message : "Error desconocido"}</p>
|
||||
<button id="retry-agenda-load" class="btn btn-primary btn-sm">Reintentar</button>
|
||||
</div>
|
||||
`;
|
||||
contentDiv
|
||||
.querySelector("#retry-agenda-load")
|
||||
?.addEventListener("click", () => loadData());
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const filterBookings = (): Booking[] => {
|
||||
const now = new Date();
|
||||
|
||||
if (activeFilter === "TODAY") {
|
||||
return cachedBookings.filter((b) =>
|
||||
isToday(new Date(b.scheduled_at), now),
|
||||
);
|
||||
}
|
||||
if (activeFilter === "TOMORROW") {
|
||||
return cachedBookings.filter((b) =>
|
||||
isTomorrow(new Date(b.scheduled_at), now),
|
||||
);
|
||||
}
|
||||
if (activeFilter === "THIS_WEEK") {
|
||||
return cachedBookings.filter((b) =>
|
||||
isThisWeek(new Date(b.scheduled_at), now),
|
||||
);
|
||||
}
|
||||
if (activeFilter === "CUSTOM" && customDateStr) {
|
||||
const [year, month, day] = customDateStr.split("-").map(Number);
|
||||
const targetDate = new Date(year, month - 1, day);
|
||||
return cachedBookings.filter((b) =>
|
||||
isSameDay(new Date(b.scheduled_at), targetDate),
|
||||
);
|
||||
}
|
||||
return cachedBookings;
|
||||
};
|
||||
|
||||
const updateIndicator = (filteredCount: number) => {
|
||||
if (!indicatorDiv) return;
|
||||
let label = "";
|
||||
if (activeFilter === "TODAY") {
|
||||
label = `📅 Mostrando citas para: <strong>Hoy</strong> (${new Intl.DateTimeFormat("es-MX", { dateStyle: "long" }).format(new Date())})`;
|
||||
} else if (activeFilter === "TOMORROW") {
|
||||
const tomorrow = new Date();
|
||||
tomorrow.setDate(tomorrow.getDate() + 1);
|
||||
label = `📅 Mostrando citas para: <strong>Mañana</strong> (${new Intl.DateTimeFormat("es-MX", { dateStyle: "long" }).format(tomorrow)})`;
|
||||
} else if (activeFilter === "THIS_WEEK") {
|
||||
label = `📅 Mostrando citas para: <strong>Esta Semana</strong>`;
|
||||
} else if (activeFilter === "CUSTOM" && customDateStr) {
|
||||
const [year, month, day] = customDateStr.split("-").map(Number);
|
||||
const targetDate = new Date(year, month - 1, day);
|
||||
label = `📅 Mostrando citas para el día: <strong>${new Intl.DateTimeFormat("es-MX", { dateStyle: "long" }).format(targetDate)}</strong>`;
|
||||
} else {
|
||||
label = "📅 Mostrando: <strong>Todas las citas programadas</strong>";
|
||||
}
|
||||
|
||||
indicatorDiv.innerHTML = `
|
||||
<span>${label}</span>
|
||||
<span class="indicator-count">${filteredCount} ${filteredCount === 1 ? "cita activa" : "citas activas"}</span>
|
||||
`;
|
||||
};
|
||||
|
||||
const applyFilter = () => {
|
||||
const filtered = filterBookings();
|
||||
updateIndicator(filtered.length);
|
||||
renderStats(filtered);
|
||||
renderTimeline(filtered);
|
||||
};
|
||||
|
||||
const renderStats = (bookings: Booking[]) => {
|
||||
if (!statsDiv) return;
|
||||
const total = bookings.length;
|
||||
@@ -94,7 +219,7 @@ export function renderDailyAgenda(
|
||||
|
||||
statsDiv.innerHTML = `
|
||||
<div class="stat-card">
|
||||
<span class="stat-label">Citas Programadas</span>
|
||||
<span class="stat-label">Citas en Periodo</span>
|
||||
<span class="stat-number">${total}</span>
|
||||
</div>
|
||||
<div class="stat-card">
|
||||
@@ -119,8 +244,8 @@ export function renderDailyAgenda(
|
||||
contentDiv.innerHTML = `
|
||||
<div class="card empty-state">
|
||||
<div class="empty-icon">📅</div>
|
||||
<h3 class="empty-title">Agenda libre</h3>
|
||||
<p class="empty-desc">No hay citas activas programadas en este momento.</p>
|
||||
<h3 class="empty-title">Agenda libre en este periodo</h3>
|
||||
<p class="empty-desc">No hay citas activas programadas para el filtro seleccionado. Puedes cambiar de fecha o ver "Todas las Citas".</p>
|
||||
</div>
|
||||
`;
|
||||
return;
|
||||
@@ -140,11 +265,45 @@ export function renderDailyAgenda(
|
||||
let collisionNotice = "";
|
||||
if (idx < bookings.length - 1) {
|
||||
const nextBooking = bookings[idx + 1];
|
||||
const nextStart = new Date(nextBooking.scheduled_at);
|
||||
if (nextStart < interval.bufferEnd) {
|
||||
const collision = checkBufferCollision(
|
||||
b.scheduled_at,
|
||||
b.duration_minutes || 60,
|
||||
b.buffer_minutes || 15,
|
||||
nextBooking.scheduled_at,
|
||||
);
|
||||
|
||||
if (collision.hasCollision) {
|
||||
const nextStartStr = formatTimeOnly(nextBooking.scheduled_at);
|
||||
collisionNotice = `
|
||||
<div class="collision-alert">
|
||||
⚠️ ADVERTENCIA: La siguiente cita (${nextBooking.booking_code}) inicia a las ${interval.endStr}, invadiendo el buffer de preparación.
|
||||
<div class="collision-alert ${collision.isDirectCollision ? "collision-critical" : "collision-warning"}" role="alert">
|
||||
<div class="collision-header">
|
||||
<span class="collision-icon">${collision.isDirectCollision ? "🛑" : "⚠️"}</span>
|
||||
<span class="collision-title font-bold">
|
||||
${collision.isDirectCollision ? "Colisión Directa entre Sesiones" : "Conflicto de Buffer Protegido"}
|
||||
</span>
|
||||
<span class="collision-deficit-pill">-${collision.deficitMinutes} min de holgura</span>
|
||||
</div>
|
||||
<div class="collision-markers">
|
||||
<div class="marker-chip">
|
||||
<span class="marker-chip-label">Término cita actual:</span>
|
||||
<span class="marker-chip-time font-mono">${interval.endStr}</span>
|
||||
</div>
|
||||
<div class="marker-chip marker-buffer">
|
||||
<span class="marker-chip-label">Buffer requerido hasta:</span>
|
||||
<span class="marker-chip-time font-mono">${interval.bufferEndStr}</span>
|
||||
</div>
|
||||
<div class="marker-chip marker-conflict">
|
||||
<span class="marker-chip-label">Inicio siguiente (${nextBooking.booking_code}):</span>
|
||||
<span class="marker-chip-time font-mono font-bold">${nextStartStr}</span>
|
||||
</div>
|
||||
</div>
|
||||
<p class="collision-explainer">
|
||||
${
|
||||
collision.isDirectCollision
|
||||
? `La cita <strong>${nextBooking.booking_code}</strong> inicia antes del término de la sesión actual.`
|
||||
: `La cita <strong>${nextBooking.booking_code}</strong> invade el buffer de 15 minutos de descanso y preparación.`
|
||||
}
|
||||
</p>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
@@ -193,6 +352,31 @@ export function renderDailyAgenda(
|
||||
<span class="buffer-hint">Tiempo no agendable protegido por el backend.</span>
|
||||
</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}
|
||||
</div>
|
||||
</div>
|
||||
@@ -202,26 +386,318 @@ export function renderDailyAgenda(
|
||||
</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
|
||||
contentDiv.querySelectorAll(".btn-retry-gcal").forEach((btn) => {
|
||||
btn.addEventListener("click", async () => {
|
||||
const id = btn.getAttribute("data-booking-id");
|
||||
if (!id) return;
|
||||
const origText = btn.textContent;
|
||||
btn.textContent = "⏳...";
|
||||
try {
|
||||
await retryCalendarSync(id);
|
||||
showToast(
|
||||
"✓ Sincronización exitosa con Google Calendar",
|
||||
"success",
|
||||
4000,
|
||||
);
|
||||
loadData();
|
||||
onStateChange();
|
||||
} catch (err: unknown) {
|
||||
alert(
|
||||
err instanceof Error ? err.message : "Error al reintentar sync",
|
||||
showToast(
|
||||
err instanceof Error
|
||||
? err.message
|
||||
: "Error al reintentar sincronización",
|
||||
"error",
|
||||
5000,
|
||||
);
|
||||
btn.textContent = "↻";
|
||||
btn.textContent = origText;
|
||||
}
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
// Event Handlers for Filter Buttons
|
||||
filterButtons.forEach((btn) => {
|
||||
btn.addEventListener("click", () => {
|
||||
const filter = btn.getAttribute("data-filter") as AgendaDateFilter;
|
||||
if (!filter) return;
|
||||
|
||||
activeFilter = filter;
|
||||
if (customDateInput) customDateInput.value = "";
|
||||
customDateStr = "";
|
||||
|
||||
filterButtons.forEach((b) => {
|
||||
const isCurrent = b === btn;
|
||||
b.classList.toggle("active", isCurrent);
|
||||
b.setAttribute("aria-selected", isCurrent ? "true" : "false");
|
||||
});
|
||||
|
||||
applyFilter();
|
||||
});
|
||||
});
|
||||
|
||||
// Event Handler for Custom Date Input
|
||||
customDateInput?.addEventListener("change", () => {
|
||||
if (customDateInput.value) {
|
||||
activeFilter = "CUSTOM";
|
||||
customDateStr = customDateInput.value;
|
||||
|
||||
filterButtons.forEach((b) => {
|
||||
b.classList.remove("active");
|
||||
b.setAttribute("aria-selected", "false");
|
||||
});
|
||||
|
||||
applyFilter();
|
||||
}
|
||||
});
|
||||
|
||||
refreshBtn?.addEventListener("click", () => 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">×</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");
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -9,12 +9,14 @@ import {
|
||||
formatDateTime,
|
||||
getHoursRemainingBadge,
|
||||
} from "../utils";
|
||||
import { showConfirmModal, showPromptModal } from "./MicroModal";
|
||||
import { openPaymentModal } from "./PaymentModal";
|
||||
import {
|
||||
renderBookingStatusBadge,
|
||||
renderCalendarSyncBadge,
|
||||
renderPaymentStatusBadge,
|
||||
} from "./StatusBadge";
|
||||
import { showToast } from "./Toast";
|
||||
|
||||
export function renderFollowUpQueue(
|
||||
container: HTMLElement,
|
||||
@@ -176,20 +178,19 @@ export function renderFollowUpQueue(
|
||||
<div class="secondary-actions">
|
||||
<button
|
||||
type="button"
|
||||
class="btn-text btn-authorize-delay"
|
||||
class="btn btn-action-delay btn-authorize-delay"
|
||||
data-booking-id="${b.id}"
|
||||
title="Permitir que el paciente pague al llegar"
|
||||
>
|
||||
Autorizar prórroga
|
||||
<span>⏳ Prórroga</span>
|
||||
</button>
|
||||
<span class="divider">·</span>
|
||||
<button
|
||||
type="button"
|
||||
class="btn-text text-danger btn-release-slot"
|
||||
class="btn btn-action-release btn-release-slot"
|
||||
data-booking-id="${b.id}"
|
||||
title="Liberar el espacio si no hubo respuesta"
|
||||
>
|
||||
Liberar lugar
|
||||
<span>✕ Liberar</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
@@ -209,7 +210,13 @@ export function renderFollowUpQueue(
|
||||
|
||||
openPaymentModal({
|
||||
booking,
|
||||
onSuccess: () => {
|
||||
onSuccess: (amount: number) => {
|
||||
showToast(
|
||||
`Pago acreditado exitosamente (${formatCurrency(amount)})`,
|
||||
"success",
|
||||
4500,
|
||||
{ folio: booking.booking_code },
|
||||
);
|
||||
loadData();
|
||||
onStateChange();
|
||||
},
|
||||
@@ -219,47 +226,82 @@ export function renderFollowUpQueue(
|
||||
|
||||
// Authorize delayed payment
|
||||
contentDiv.querySelectorAll(".btn-authorize-delay").forEach((btn) => {
|
||||
btn.addEventListener("click", async () => {
|
||||
btn.addEventListener("click", () => {
|
||||
const id = btn.getAttribute("data-booking-id");
|
||||
if (!id) return;
|
||||
const notes = window.prompt(
|
||||
"Motivo o acuerdo de la prórroga de pago:",
|
||||
"Acordado con el paciente para pago en efectivo antes de la sesión",
|
||||
);
|
||||
if (notes === null) return;
|
||||
const booking = bookings.find((b) => b.id === id);
|
||||
if (!id || !booking) return;
|
||||
|
||||
try {
|
||||
showPromptModal({
|
||||
title: "Autorizar Prórroga de Pago",
|
||||
kicker: "Excepción Operativa",
|
||||
subtitle:
|
||||
"Permite al consultante conservar su lugar y liquidar en efectivo o SPEI antes de iniciar su sesión.",
|
||||
bookingContext: {
|
||||
bookingCode: booking.booking_code,
|
||||
clientName: booking.client_name,
|
||||
serviceName: booking.service_name,
|
||||
scheduledAtFormatted: formatDateTime(booking.scheduled_at),
|
||||
},
|
||||
label: "Motivo o acuerdo de la prórroga:",
|
||||
defaultValue:
|
||||
"Acordado con el paciente para pago en efectivo antes de la sesión",
|
||||
placeholder:
|
||||
"Ej. Confirmado por Jasmin para pago presencial el día de la cita",
|
||||
confirmText: "Autorizar Prórroga",
|
||||
cancelText: "Cancelar",
|
||||
onConfirm: async (notes: string) => {
|
||||
await authorizeDelayedPayment(id, notes);
|
||||
showToast(
|
||||
"Prórroga autorizada. Estado actualizado a Prórroga Autorizada.",
|
||||
"warning",
|
||||
4500,
|
||||
{ folio: booking.booking_code },
|
||||
);
|
||||
loadData();
|
||||
onStateChange();
|
||||
} catch (err: unknown) {
|
||||
alert(
|
||||
err instanceof Error ? err.message : "Error al autorizar prórroga",
|
||||
);
|
||||
}
|
||||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
// Release booking
|
||||
contentDiv.querySelectorAll(".btn-release-slot").forEach((btn) => {
|
||||
btn.addEventListener("click", async () => {
|
||||
btn.addEventListener("click", () => {
|
||||
const id = btn.getAttribute("data-booking-id");
|
||||
if (!id) return;
|
||||
const reason = window.prompt(
|
||||
"¿Deseas liberar este horario para otros clientes? Motivo:",
|
||||
"Sin respuesta a recordatorios de pago dentro de las 48h",
|
||||
);
|
||||
if (reason === null) return;
|
||||
const booking = bookings.find((b) => b.id === id);
|
||||
if (!id || !booking) return;
|
||||
|
||||
try {
|
||||
showConfirmModal({
|
||||
title: "¿Liberar este horario?",
|
||||
kicker: "Liberación de Espacio",
|
||||
message: `¿Deseas liberar este horario para otros clientes? Se cancelará la reservación activa y el horario volverá a estar disponible en el calendario público.`,
|
||||
bookingContext: {
|
||||
bookingCode: booking.booking_code,
|
||||
clientName: booking.client_name,
|
||||
serviceName: booking.service_name,
|
||||
scheduledAtFormatted: formatDateTime(booking.scheduled_at),
|
||||
},
|
||||
withReasonInput: true,
|
||||
reasonLabel: "Motivo de la liberación:",
|
||||
defaultReason:
|
||||
"Sin respuesta a recordatorios de pago dentro de las 48h",
|
||||
reasonPlaceholder:
|
||||
"Describe brevemente por qué se libera el horario...",
|
||||
confirmText: "Sí, liberar espacio",
|
||||
cancelText: "Conservar reservación",
|
||||
isDanger: true,
|
||||
onConfirm: async (reason: string) => {
|
||||
await releaseBooking(id, reason);
|
||||
showToast(
|
||||
"Espacio liberado con éxito. Horario nuevamente disponible.",
|
||||
"info",
|
||||
4500,
|
||||
{ folio: booking.booking_code },
|
||||
);
|
||||
loadData();
|
||||
onStateChange();
|
||||
} catch (err: unknown) {
|
||||
alert(
|
||||
err instanceof Error ? err.message : "Error al liberar espacio",
|
||||
);
|
||||
}
|
||||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
@@ -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">×</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">×</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 ? `• 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">×</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, "&")
|
||||
.replace(/</g, "<")
|
||||
.replace(/>/g, ">")
|
||||
.replace(/"/g, """)
|
||||
.replace(/'/g, "'");
|
||||
}
|
||||
@@ -0,0 +1,362 @@
|
||||
export interface BookingSummaryContext {
|
||||
bookingCode: string;
|
||||
clientName?: string | null;
|
||||
serviceName?: string | null;
|
||||
scheduledAtFormatted?: string | null;
|
||||
}
|
||||
|
||||
export interface PromptModalOptions {
|
||||
title: string;
|
||||
kicker?: string;
|
||||
subtitle?: string;
|
||||
bookingContext?: BookingSummaryContext;
|
||||
label: string;
|
||||
defaultValue?: string;
|
||||
placeholder?: string;
|
||||
confirmText?: string;
|
||||
cancelText?: string;
|
||||
onConfirm: (value: string) => Promise<void> | void;
|
||||
onCancel?: () => void;
|
||||
}
|
||||
|
||||
export interface ConfirmModalOptions {
|
||||
title: string;
|
||||
kicker?: string;
|
||||
message: string;
|
||||
bookingContext?: BookingSummaryContext;
|
||||
withReasonInput?: boolean;
|
||||
reasonLabel?: string;
|
||||
defaultReason?: string;
|
||||
reasonPlaceholder?: string;
|
||||
confirmText?: string;
|
||||
cancelText?: string;
|
||||
isDanger?: boolean;
|
||||
onConfirm: (reason: string) => Promise<void> | void;
|
||||
onCancel?: () => void;
|
||||
}
|
||||
|
||||
export function showPromptModal(options: PromptModalOptions): void {
|
||||
const {
|
||||
title,
|
||||
kicker = "Acción Requerida",
|
||||
subtitle,
|
||||
bookingContext,
|
||||
label,
|
||||
defaultValue = "",
|
||||
placeholder = "",
|
||||
confirmText = "Confirmar",
|
||||
cancelText = "Cancelar",
|
||||
onConfirm,
|
||||
onCancel,
|
||||
} = options;
|
||||
|
||||
const existingBackdrop = document.getElementById("micro-modal-backdrop");
|
||||
if (existingBackdrop) existingBackdrop.remove();
|
||||
|
||||
const backdrop = document.createElement("div");
|
||||
backdrop.id = "micro-modal-backdrop";
|
||||
backdrop.className = "modal-backdrop";
|
||||
|
||||
const summaryHtml = bookingContext
|
||||
? `
|
||||
<div class="summary-box">
|
||||
<div class="summary-row">
|
||||
<span class="summary-label">Folio:</span>
|
||||
<span class="summary-value font-mono font-bold">${bookingContext.bookingCode}</span>
|
||||
</div>
|
||||
${
|
||||
bookingContext.clientName
|
||||
? `
|
||||
<div class="summary-row">
|
||||
<span class="summary-label">Paciente:</span>
|
||||
<span class="summary-value">${bookingContext.clientName}</span>
|
||||
</div>`
|
||||
: ""
|
||||
}
|
||||
${
|
||||
bookingContext.serviceName
|
||||
? `
|
||||
<div class="summary-row">
|
||||
<span class="summary-label">Servicio:</span>
|
||||
<span class="summary-value">${bookingContext.serviceName}</span>
|
||||
</div>`
|
||||
: ""
|
||||
}
|
||||
${
|
||||
bookingContext.scheduledAtFormatted
|
||||
? `
|
||||
<div class="summary-row">
|
||||
<span class="summary-label">Horario:</span>
|
||||
<span class="summary-value font-medium">${bookingContext.scheduledAtFormatted}</span>
|
||||
</div>`
|
||||
: ""
|
||||
}
|
||||
</div>
|
||||
`
|
||||
: "";
|
||||
|
||||
backdrop.innerHTML = `
|
||||
<div class="modal-card" role="dialog" aria-modal="true" aria-labelledby="micro-modal-title">
|
||||
<div class="modal-header">
|
||||
<div>
|
||||
<span class="modal-kicker">${kicker}</span>
|
||||
<h3 id="micro-modal-title" class="modal-title">${title}</h3>
|
||||
</div>
|
||||
<button type="button" class="modal-close-btn" id="micro-modal-close" aria-label="Cerrar modal">×</button>
|
||||
</div>
|
||||
|
||||
<div class="modal-body">
|
||||
${subtitle ? `<p class="modal-subtitle-text">${subtitle}</p>` : ""}
|
||||
${summaryHtml}
|
||||
|
||||
<form id="micro-modal-form" class="modal-form-content">
|
||||
<div class="form-group">
|
||||
<label for="prompt-input" class="form-label">${label}</label>
|
||||
<textarea
|
||||
id="prompt-input"
|
||||
name="prompt_value"
|
||||
class="form-textarea"
|
||||
rows="3"
|
||||
placeholder="${placeholder}"
|
||||
required
|
||||
>${defaultValue}</textarea>
|
||||
</div>
|
||||
|
||||
<div id="micro-modal-error" class="modal-error-box hidden"></div>
|
||||
|
||||
<div class="modal-actions">
|
||||
<button type="button" id="micro-modal-cancel" class="btn btn-secondary">
|
||||
${cancelText}
|
||||
</button>
|
||||
<button type="submit" id="micro-modal-submit" class="btn btn-primary">
|
||||
${confirmText}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
|
||||
document.body.appendChild(backdrop);
|
||||
|
||||
const close = () => {
|
||||
backdrop.remove();
|
||||
document.removeEventListener("keydown", handleKeyDown);
|
||||
onCancel?.();
|
||||
};
|
||||
|
||||
const handleKeyDown = (e: KeyboardEvent) => {
|
||||
if (e.key === "Escape") close();
|
||||
};
|
||||
document.addEventListener("keydown", handleKeyDown);
|
||||
|
||||
backdrop
|
||||
.querySelector("#micro-modal-close")
|
||||
?.addEventListener("click", () => close());
|
||||
backdrop
|
||||
.querySelector("#micro-modal-cancel")
|
||||
?.addEventListener("click", () => close());
|
||||
backdrop.addEventListener("click", (e) => {
|
||||
if (e.target === backdrop) close();
|
||||
});
|
||||
|
||||
const form = backdrop.querySelector<HTMLFormElement>("#micro-modal-form");
|
||||
const textarea = backdrop.querySelector<HTMLTextAreaElement>("#prompt-input");
|
||||
const submitBtn = backdrop.querySelector<HTMLButtonElement>(
|
||||
"#micro-modal-submit",
|
||||
);
|
||||
const errorBox = backdrop.querySelector<HTMLDivElement>("#micro-modal-error");
|
||||
|
||||
textarea?.focus();
|
||||
|
||||
form?.addEventListener("submit", async (e) => {
|
||||
e.preventDefault();
|
||||
const val = textarea?.value.trim() ?? "";
|
||||
if (!submitBtn || !errorBox) return;
|
||||
|
||||
submitBtn.disabled = true;
|
||||
submitBtn.textContent = "Procesando...";
|
||||
errorBox.classList.add("hidden");
|
||||
errorBox.textContent = "";
|
||||
|
||||
try {
|
||||
await onConfirm(val);
|
||||
backdrop.remove();
|
||||
document.removeEventListener("keydown", handleKeyDown);
|
||||
} catch (err: unknown) {
|
||||
submitBtn.disabled = false;
|
||||
submitBtn.textContent = confirmText;
|
||||
errorBox.textContent =
|
||||
err instanceof Error ? err.message : "Error al procesar la acción";
|
||||
errorBox.classList.remove("hidden");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
export function showConfirmModal(options: ConfirmModalOptions): void {
|
||||
const {
|
||||
title,
|
||||
kicker = "Confirmación Requerida",
|
||||
message,
|
||||
bookingContext,
|
||||
withReasonInput = false,
|
||||
reasonLabel = "Motivo de la acción:",
|
||||
defaultReason = "",
|
||||
reasonPlaceholder = "Describe el motivo...",
|
||||
confirmText = "Confirmar",
|
||||
cancelText = "Cancelar",
|
||||
isDanger = false,
|
||||
onConfirm,
|
||||
onCancel,
|
||||
} = options;
|
||||
|
||||
const existingBackdrop = document.getElementById("micro-modal-backdrop");
|
||||
if (existingBackdrop) existingBackdrop.remove();
|
||||
|
||||
const backdrop = document.createElement("div");
|
||||
backdrop.id = "micro-modal-backdrop";
|
||||
backdrop.className = "modal-backdrop";
|
||||
|
||||
const summaryHtml = bookingContext
|
||||
? `
|
||||
<div class="summary-box">
|
||||
<div class="summary-row">
|
||||
<span class="summary-label">Folio:</span>
|
||||
<span class="summary-value font-mono font-bold">${bookingContext.bookingCode}</span>
|
||||
</div>
|
||||
${
|
||||
bookingContext.clientName
|
||||
? `
|
||||
<div class="summary-row">
|
||||
<span class="summary-label">Paciente:</span>
|
||||
<span class="summary-value">${bookingContext.clientName}</span>
|
||||
</div>`
|
||||
: ""
|
||||
}
|
||||
${
|
||||
bookingContext.serviceName
|
||||
? `
|
||||
<div class="summary-row">
|
||||
<span class="summary-label">Servicio:</span>
|
||||
<span class="summary-value">${bookingContext.serviceName}</span>
|
||||
</div>`
|
||||
: ""
|
||||
}
|
||||
${
|
||||
bookingContext.scheduledAtFormatted
|
||||
? `
|
||||
<div class="summary-row">
|
||||
<span class="summary-label">Horario:</span>
|
||||
<span class="summary-value font-medium">${bookingContext.scheduledAtFormatted}</span>
|
||||
</div>`
|
||||
: ""
|
||||
}
|
||||
</div>
|
||||
`
|
||||
: "";
|
||||
|
||||
const reasonSectionHtml = withReasonInput
|
||||
? `
|
||||
<div class="form-group" style="margin-top: 12px;">
|
||||
<label for="confirm-reason-input" class="form-label">${reasonLabel}</label>
|
||||
<textarea
|
||||
id="confirm-reason-input"
|
||||
name="reason"
|
||||
class="form-textarea"
|
||||
rows="2"
|
||||
placeholder="${reasonPlaceholder}"
|
||||
required
|
||||
>${defaultReason}</textarea>
|
||||
</div>
|
||||
`
|
||||
: "";
|
||||
|
||||
backdrop.innerHTML = `
|
||||
<div class="modal-card" role="dialog" aria-modal="true" aria-labelledby="confirm-modal-title">
|
||||
<div class="modal-header">
|
||||
<div>
|
||||
<span class="modal-kicker ${isDanger ? "text-danger" : ""}">${kicker}</span>
|
||||
<h3 id="confirm-modal-title" class="modal-title">${title}</h3>
|
||||
</div>
|
||||
<button type="button" class="modal-close-btn" id="confirm-modal-close" aria-label="Cerrar modal">×</button>
|
||||
</div>
|
||||
|
||||
<div class="modal-body">
|
||||
<div class="${isDanger ? "reassuring-warning-box" : "modal-message-box"}">
|
||||
${message}
|
||||
</div>
|
||||
|
||||
${summaryHtml}
|
||||
${reasonSectionHtml}
|
||||
|
||||
<div id="confirm-modal-error" class="modal-error-box hidden"></div>
|
||||
|
||||
<div class="modal-actions">
|
||||
<button type="button" id="confirm-modal-cancel" class="btn btn-secondary">
|
||||
${cancelText}
|
||||
</button>
|
||||
<button type="button" id="confirm-modal-submit" class="btn ${isDanger ? "btn-danger" : "btn-primary"}">
|
||||
${confirmText}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
|
||||
document.body.appendChild(backdrop);
|
||||
|
||||
const close = () => {
|
||||
backdrop.remove();
|
||||
document.removeEventListener("keydown", handleKeyDown);
|
||||
onCancel?.();
|
||||
};
|
||||
|
||||
const handleKeyDown = (e: KeyboardEvent) => {
|
||||
if (e.key === "Escape") close();
|
||||
};
|
||||
document.addEventListener("keydown", handleKeyDown);
|
||||
|
||||
backdrop
|
||||
.querySelector("#confirm-modal-close")
|
||||
?.addEventListener("click", () => close());
|
||||
backdrop
|
||||
.querySelector("#confirm-modal-cancel")
|
||||
?.addEventListener("click", () => close());
|
||||
backdrop.addEventListener("click", (e) => {
|
||||
if (e.target === backdrop) close();
|
||||
});
|
||||
|
||||
const submitBtn = backdrop.querySelector<HTMLButtonElement>(
|
||||
"#confirm-modal-submit",
|
||||
);
|
||||
const errorBox = backdrop.querySelector<HTMLDivElement>(
|
||||
"#confirm-modal-error",
|
||||
);
|
||||
const reasonInput = backdrop.querySelector<HTMLTextAreaElement>(
|
||||
"#confirm-reason-input",
|
||||
);
|
||||
|
||||
submitBtn?.focus();
|
||||
|
||||
submitBtn?.addEventListener("click", async () => {
|
||||
if (!submitBtn || !errorBox) return;
|
||||
const reasonVal = reasonInput ? reasonInput.value.trim() : "";
|
||||
|
||||
submitBtn.disabled = true;
|
||||
submitBtn.textContent = "Procesando...";
|
||||
errorBox.classList.add("hidden");
|
||||
errorBox.textContent = "";
|
||||
|
||||
try {
|
||||
await onConfirm(reasonVal);
|
||||
backdrop.remove();
|
||||
document.removeEventListener("keydown", handleKeyDown);
|
||||
} catch (err: unknown) {
|
||||
submitBtn.disabled = false;
|
||||
submitBtn.textContent = confirmText;
|
||||
errorBox.textContent =
|
||||
err instanceof Error ? err.message : "Error al procesar la acción";
|
||||
errorBox.classList.remove("hidden");
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
import { acknowledgePayment } from "../api";
|
||||
import type { Booking } from "../types";
|
||||
import { formatCurrency } from "../utils";
|
||||
|
||||
@@ -14,7 +15,7 @@ export interface PaymentModalOptions {
|
||||
|
||||
export function openPaymentModal(options: {
|
||||
booking: Booking;
|
||||
onSuccess: () => void;
|
||||
onSuccess: (amount: number) => void;
|
||||
}): void {
|
||||
const { booking, onSuccess } = options;
|
||||
|
||||
@@ -161,7 +162,6 @@ export function openPaymentModal(options: {
|
||||
const notes = notesInput?.value.trim() || undefined;
|
||||
|
||||
try {
|
||||
const { acknowledgePayment } = await import("../api");
|
||||
await acknowledgePayment({
|
||||
booking_id: booking.id,
|
||||
amount_mxn: amount,
|
||||
@@ -169,7 +169,7 @@ export function openPaymentModal(options: {
|
||||
notes,
|
||||
});
|
||||
close();
|
||||
onSuccess();
|
||||
onSuccess(amount);
|
||||
} catch (err: unknown) {
|
||||
submitBtn.disabled = false;
|
||||
submitBtn.textContent = "Confirmar Acreditación";
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
export type ToastType = "success" | "warning" | "error" | "info";
|
||||
|
||||
export interface ToastOptions {
|
||||
message: string;
|
||||
type?: ToastType;
|
||||
durationMs?: number;
|
||||
folio?: string;
|
||||
}
|
||||
|
||||
let toastContainer: HTMLElement | null = null;
|
||||
|
||||
function getToastContainer(): HTMLElement {
|
||||
if (!toastContainer || !document.body.contains(toastContainer)) {
|
||||
toastContainer = document.getElementById("toast-container");
|
||||
if (!toastContainer) {
|
||||
toastContainer = document.createElement("div");
|
||||
toastContainer.id = "toast-container";
|
||||
toastContainer.className = "toast-container";
|
||||
toastContainer.setAttribute("role", "status");
|
||||
toastContainer.setAttribute("aria-live", "polite");
|
||||
document.body.appendChild(toastContainer);
|
||||
}
|
||||
}
|
||||
return toastContainer;
|
||||
}
|
||||
|
||||
export function showToast(
|
||||
message: string,
|
||||
type: ToastType = "info",
|
||||
durationMs = 4000,
|
||||
options?: { folio?: string },
|
||||
): HTMLElement {
|
||||
const container = getToastContainer();
|
||||
|
||||
const toast = document.createElement("div");
|
||||
toast.className = `toast-item toast-${type}`;
|
||||
toast.setAttribute("role", type === "error" ? "alert" : "status");
|
||||
|
||||
const icons: Record<ToastType, string> = {
|
||||
success: "✓",
|
||||
warning: "⏳",
|
||||
error: "⚠️",
|
||||
info: "ℹ️",
|
||||
};
|
||||
|
||||
toast.innerHTML = `
|
||||
<div class="toast-icon" aria-hidden="true">${icons[type]}</div>
|
||||
<div class="toast-content">
|
||||
${options?.folio ? `<span class="toast-folio">${options.folio}</span>` : ""}
|
||||
<span class="toast-message">${message}</span>
|
||||
</div>
|
||||
<button type="button" class="toast-close-btn" aria-label="Cerrar notificación">
|
||||
<span aria-hidden="true">×</span>
|
||||
</button>
|
||||
`;
|
||||
|
||||
const removeToast = () => {
|
||||
toast.classList.add("toast-leaving");
|
||||
setTimeout(() => {
|
||||
toast.remove();
|
||||
}, 250);
|
||||
};
|
||||
|
||||
const closeBtn = toast.querySelector<HTMLButtonElement>(".toast-close-btn");
|
||||
closeBtn?.addEventListener("click", () => removeToast());
|
||||
|
||||
container.appendChild(toast);
|
||||
|
||||
// Trigger entry transition
|
||||
requestAnimationFrame(() => {
|
||||
toast.classList.add("toast-visible");
|
||||
});
|
||||
|
||||
if (durationMs > 0) {
|
||||
setTimeout(() => {
|
||||
if (toast.isConnected) {
|
||||
removeToast();
|
||||
}
|
||||
}, durationMs);
|
||||
}
|
||||
|
||||
return toast;
|
||||
}
|
||||
@@ -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, "&")
|
||||
.replace(/</g, "<")
|
||||
.replace(/>/g, ">")
|
||||
.replace(/"/g, """)
|
||||
.replace(/'/g, "'");
|
||||
}
|
||||
|
||||
/**
|
||||
* Reconcile session state upon out-of-band 409 ALREADY_CHECKED_IN conflict.
|
||||
* Ensures attendance status is COMPLETED / ASISTIÓ, and if the attendee was
|
||||
* previously unrecorded locally, increments attended_count.
|
||||
* Returns true if attended_count was incremented.
|
||||
*/
|
||||
export function reconcileAlreadyCheckedInState(
|
||||
session: RosterSession,
|
||||
attendee: RosterAttendee,
|
||||
): boolean {
|
||||
const wasAttended =
|
||||
attendee.attended || attendee.booking_status === "COMPLETED";
|
||||
attendee.attended = true;
|
||||
attendee.booking_status = "COMPLETED";
|
||||
if (!wasAttended) {
|
||||
session.attended_count += 1;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reconcile local session state with authoritative server sessions.
|
||||
* Matches sessions by service_id and scheduled_at to update counts and attendee records.
|
||||
*/
|
||||
export function reconcileSessionsWithServer(
|
||||
currentSessions: RosterSession[],
|
||||
freshSessions: RosterSession[],
|
||||
): RosterSession[] {
|
||||
if (!freshSessions || freshSessions.length === 0) {
|
||||
return currentSessions;
|
||||
}
|
||||
return freshSessions.map((fresh) => {
|
||||
const existing = currentSessions.find(
|
||||
(curr) =>
|
||||
curr.service_id === fresh.service_id &&
|
||||
curr.scheduled_at === fresh.scheduled_at,
|
||||
);
|
||||
if (!existing) return fresh;
|
||||
return {
|
||||
...existing,
|
||||
...fresh,
|
||||
attendees: fresh.attendees.map((freshAtt) => {
|
||||
const existingAtt = existing.attendees.find(
|
||||
(a) => a.booking_id === freshAtt.booking_id,
|
||||
);
|
||||
return {
|
||||
...existingAtt,
|
||||
...freshAtt,
|
||||
};
|
||||
}),
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Disambiguate HTTP 409 Conflict based on response detail
|
||||
*/
|
||||
export function disambiguate409Error(detail?: string): ConflictType {
|
||||
if (!detail) return "UNKNOWN";
|
||||
const lower = detail.toLowerCase();
|
||||
if (lower.includes("already checked in")) {
|
||||
return "ALREADY_CHECKED_IN";
|
||||
}
|
||||
if (lower.includes("cupo máximo") || lower.includes("cupo maximo")) {
|
||||
return "CAPACITY_EXCEEDED";
|
||||
}
|
||||
return "UNKNOWN";
|
||||
}
|
||||
|
||||
/**
|
||||
* Main component renderer for the Group Workshop Roster view (#rosters)
|
||||
*/
|
||||
export function renderWorkshopRoster(
|
||||
container: HTMLElement,
|
||||
onStateChange?: () => void,
|
||||
): void {
|
||||
let selectedDate = getTodayDateString();
|
||||
let cachedSessions: RosterSession[] = [];
|
||||
|
||||
container.innerHTML = `
|
||||
<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">×</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();
|
||||
}
|
||||
@@ -1,10 +1,14 @@
|
||||
import "./style.css";
|
||||
import { fetchFollowUpQueue } from "./api";
|
||||
import { fetchCurrentAdmin, fetchFollowUpQueue } from "./api";
|
||||
import { renderAllBookings } from "./components/AllBookings";
|
||||
import { renderClientDirectory } from "./components/ClientDirectory";
|
||||
import { renderDailyAgenda } from "./components/DailyAgenda";
|
||||
import { renderFollowUpQueue } from "./components/FollowUpQueue";
|
||||
import { openBookingIntakeModal } from "./components/IntakeModal";
|
||||
import { renderWorkshopRoster } from "./components/WorkshopRoster";
|
||||
import { getRoleBadge } from "./utils";
|
||||
|
||||
type TabId = "queue" | "agenda" | "all";
|
||||
type TabId = "queue" | "agenda" | "clients" | "all" | "rosters";
|
||||
|
||||
class OperatorDashboardApp {
|
||||
private activeTab: TabId = "queue";
|
||||
@@ -22,32 +26,64 @@ class OperatorDashboardApp {
|
||||
private async init(): Promise<void> {
|
||||
this.renderShell();
|
||||
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();
|
||||
const hash = window.location.hash.replace("#", "") as TabId;
|
||||
const initialTab = hash === "agenda" || hash === "all" ? hash : "queue";
|
||||
this.switchTab(this.activeTab);
|
||||
},
|
||||
});
|
||||
} else {
|
||||
const initialTab =
|
||||
hash === "agenda" ||
|
||||
hash === "clients" ||
|
||||
hash === "all" ||
|
||||
hash === "rosters"
|
||||
? hash
|
||||
: "queue";
|
||||
this.switchTab(initialTab);
|
||||
}
|
||||
}
|
||||
|
||||
private renderShell(): void {
|
||||
this.container.innerHTML = `
|
||||
<header class="app-header">
|
||||
<div class="brand-section">
|
||||
<span class="brand-lotus">🪷</span>
|
||||
<span class="brand-lotus" aria-hidden="true">🪷</span>
|
||||
<div>
|
||||
<h1 class="brand-title">Armonía del Ser</h1>
|
||||
<div class="text-xs text-muted">Panel Operativo de Consultas y Agenda</div>
|
||||
</div>
|
||||
<span class="brand-badge">Operador</span>
|
||||
</div>
|
||||
<div class="operator-profile">
|
||||
<div class="operator-badge">
|
||||
<span class="status-dot"></span>
|
||||
<span>Jasmin & Asistente</span>
|
||||
|
||||
<div class="header-actions">
|
||||
<button
|
||||
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>
|
||||
</header>
|
||||
|
||||
<nav class="nav-tabs" role="tablist">
|
||||
<!-- Desktop & Tablet Tabs Header -->
|
||||
<nav class="nav-tabs" role="tablist" aria-label="Navegación principal">
|
||||
<button class="nav-tab active" data-tab="queue" role="tab" aria-selected="true">
|
||||
<span>Cola 48h (Seguimiento)</span>
|
||||
<span id="queue-badge" class="tab-badge hidden">0</span>
|
||||
@@ -55,19 +91,96 @@ class OperatorDashboardApp {
|
||||
<button class="nav-tab" data-tab="agenda" role="tab" aria-selected="false">
|
||||
<span>Agenda del Día (Buffers)</span>
|
||||
</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">
|
||||
<span>Todas las Citas</span>
|
||||
</button>
|
||||
</nav>
|
||||
|
||||
<!-- Main View Container -->
|
||||
<main id="tab-content" class="tab-main-content" role="tabpanel"></main>
|
||||
|
||||
<!-- Sticky Mobile Navigation Bar -->
|
||||
<nav class="mobile-sticky-nav" role="tablist" aria-label="Navegación móvil rápida">
|
||||
<button class="mobile-nav-item active" data-tab="queue" role="tab" aria-selected="true">
|
||||
<span class="mobile-nav-icon" aria-hidden="true">⏱️</span>
|
||||
<span class="mobile-nav-label">Cola 48h</span>
|
||||
<span id="queue-badge-mobile" class="tab-badge tab-badge-mobile hidden">0</span>
|
||||
</button>
|
||||
<button class="mobile-nav-item" data-tab="agenda" role="tab" aria-selected="false">
|
||||
<span class="mobile-nav-icon" aria-hidden="true">📅</span>
|
||||
<span class="mobile-nav-label">Agenda</span>
|
||||
</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">
|
||||
<span class="mobile-nav-icon" aria-hidden="true">📋</span>
|
||||
<span class="mobile-nav-label">Historial</span>
|
||||
</button>
|
||||
</nav>
|
||||
`;
|
||||
}
|
||||
|
||||
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 {
|
||||
const tabButtons =
|
||||
this.container.querySelectorAll<HTMLButtonElement>(".nav-tab");
|
||||
tabButtons.forEach((btn) => {
|
||||
// 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 =
|
||||
this.container.querySelectorAll<HTMLButtonElement>("[data-tab]");
|
||||
allTabButtons.forEach((btn) => {
|
||||
btn.addEventListener("click", () => {
|
||||
const targetTab = btn.getAttribute("data-tab") as TabId;
|
||||
if (targetTab) {
|
||||
@@ -75,15 +188,32 @@ class OperatorDashboardApp {
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// Hash routing
|
||||
window.addEventListener("hashchange", () => {
|
||||
const hash = window.location.hash.replace("#", "") as TabId;
|
||||
if (
|
||||
hash === "queue" ||
|
||||
hash === "agenda" ||
|
||||
hash === "rosters" ||
|
||||
hash === "clients" ||
|
||||
hash === "all"
|
||||
) {
|
||||
if (this.activeTab !== hash) {
|
||||
this.switchTab(hash);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private switchTab(tab: TabId): void {
|
||||
this.activeTab = tab;
|
||||
window.location.hash = tab;
|
||||
|
||||
// Update tab button active states
|
||||
const tabButtons =
|
||||
this.container.querySelectorAll<HTMLButtonElement>(".nav-tab");
|
||||
tabButtons.forEach((btn) => {
|
||||
// Update both desktop and mobile active states
|
||||
const allTabButtons =
|
||||
this.container.querySelectorAll<HTMLButtonElement>("[data-tab]");
|
||||
allTabButtons.forEach((btn) => {
|
||||
const isCurrent = btn.getAttribute("data-tab") === tab;
|
||||
btn.classList.toggle("active", isCurrent);
|
||||
btn.setAttribute("aria-selected", isCurrent ? "true" : "false");
|
||||
@@ -101,6 +231,10 @@ class OperatorDashboardApp {
|
||||
renderFollowUpQueue(contentEl, onStateChange);
|
||||
} else if (tab === "agenda") {
|
||||
renderDailyAgenda(contentEl, onStateChange);
|
||||
} else if (tab === "rosters") {
|
||||
renderWorkshopRoster(contentEl, onStateChange);
|
||||
} else if (tab === "clients") {
|
||||
renderClientDirectory(contentEl, onStateChange);
|
||||
} else if (tab === "all") {
|
||||
renderAllBookings(contentEl);
|
||||
}
|
||||
@@ -109,16 +243,18 @@ class OperatorDashboardApp {
|
||||
private async refreshTabBadge(): Promise<void> {
|
||||
try {
|
||||
const queue = await fetchFollowUpQueue();
|
||||
const badge =
|
||||
this.container.querySelector<HTMLSpanElement>("#queue-badge");
|
||||
if (badge) {
|
||||
if (queue.length > 0) {
|
||||
badge.textContent = String(queue.length);
|
||||
const count = queue.length;
|
||||
const badges = this.container.querySelectorAll<HTMLSpanElement>(
|
||||
"#queue-badge, #queue-badge-mobile",
|
||||
);
|
||||
badges.forEach((badge) => {
|
||||
if (count > 0) {
|
||||
badge.textContent = String(count);
|
||||
badge.classList.remove("hidden");
|
||||
} else {
|
||||
badge.classList.add("hidden");
|
||||
}
|
||||
}
|
||||
});
|
||||
} catch {
|
||||
// Ignore badge background fetch failure
|
||||
}
|
||||
|
||||
@@ -72,3 +72,140 @@ export interface PaymentRecord {
|
||||
notes?: string | null;
|
||||
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;
|
||||
}
|
||||
@@ -83,3 +83,143 @@ export function getHoursRemainingBadge(hours: number): {
|
||||
urgencyClass: "badge-info",
|
||||
};
|
||||
}
|
||||
|
||||
export function isSameDay(d1: Date, d2: Date): boolean {
|
||||
return (
|
||||
d1.getFullYear() === d2.getFullYear() &&
|
||||
d1.getMonth() === d2.getMonth() &&
|
||||
d1.getDate() === d2.getDate()
|
||||
);
|
||||
}
|
||||
|
||||
export function isToday(date: Date, refDate: Date = new Date()): boolean {
|
||||
return isSameDay(date, refDate);
|
||||
}
|
||||
|
||||
export function isTomorrow(date: Date, refDate: Date = new Date()): boolean {
|
||||
const tomorrow = new Date(
|
||||
refDate.getFullYear(),
|
||||
refDate.getMonth(),
|
||||
refDate.getDate() + 1,
|
||||
);
|
||||
return isSameDay(date, tomorrow);
|
||||
}
|
||||
|
||||
export function isThisWeek(date: Date, refDate: Date = new Date()): boolean {
|
||||
const day = refDate.getDay();
|
||||
// Week starts on Monday: (day + 6) % 7 gives 0 for Monday, 6 for Sunday
|
||||
const diffToMonday = (day + 6) % 7;
|
||||
const startOfWeek = new Date(
|
||||
refDate.getFullYear(),
|
||||
refDate.getMonth(),
|
||||
refDate.getDate() - diffToMonday,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
);
|
||||
const endOfWeek = new Date(
|
||||
startOfWeek.getTime() + 7 * 24 * 60 * 60 * 1000 - 1,
|
||||
);
|
||||
return date >= startOfWeek && date <= endOfWeek;
|
||||
}
|
||||
|
||||
export function formatDateInput(date: Date): string {
|
||||
const y = date.getFullYear();
|
||||
const m = String(date.getMonth() + 1).padStart(2, "0");
|
||||
const d = String(date.getDate()).padStart(2, "0");
|
||||
return `${y}-${m}-${d}`;
|
||||
}
|
||||
|
||||
export interface CollisionResult {
|
||||
hasCollision: boolean;
|
||||
isDirectCollision: boolean;
|
||||
isBufferCollision: boolean;
|
||||
deficitMinutes: number;
|
||||
}
|
||||
|
||||
export function checkBufferCollision(
|
||||
currentStartIso: string,
|
||||
currentDurationMinutes: number,
|
||||
currentBufferMinutes: number,
|
||||
nextStartIso: string,
|
||||
): CollisionResult {
|
||||
const currentStart = new Date(currentStartIso);
|
||||
const currentEnd = new Date(
|
||||
currentStart.getTime() + currentDurationMinutes * 60 * 1000,
|
||||
);
|
||||
const currentBufferEnd = new Date(
|
||||
currentEnd.getTime() + currentBufferMinutes * 60 * 1000,
|
||||
);
|
||||
const nextStart = new Date(nextStartIso);
|
||||
|
||||
if (nextStart >= currentBufferEnd) {
|
||||
return {
|
||||
hasCollision: false,
|
||||
isDirectCollision: false,
|
||||
isBufferCollision: false,
|
||||
deficitMinutes: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const isDirectCollision = nextStart < currentEnd;
|
||||
const deficitMs = currentBufferEnd.getTime() - nextStart.getTime();
|
||||
const deficitMinutes = Math.round(deficitMs / (60 * 1000));
|
||||
|
||||
return {
|
||||
hasCollision: true,
|
||||
isDirectCollision,
|
||||
isBufferCollision: !isDirectCollision,
|
||||
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);
|
||||
};
|
||||
}
|
||||
@@ -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(
|
||||
"<script>alert("xss")</script>",
|
||||
);
|
||||
expect(escapeHtml("Tom & Jerry's")).toBe("Tom & Jerry's");
|
||||
expect(escapeHtml('<img src="x" onerror="alert(1)">')).toBe(
|
||||
"<img src="x" onerror="alert(1)">",
|
||||
);
|
||||
});
|
||||
|
||||
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");
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,8 +1,18 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
calculateInterval,
|
||||
checkBufferCollision,
|
||||
debounce,
|
||||
formatCurrency,
|
||||
formatDateInput,
|
||||
formatMexicanPhone,
|
||||
getCleanDigitsPhone,
|
||||
getHoursRemainingBadge,
|
||||
getRoleBadge,
|
||||
isSameDay,
|
||||
isThisWeek,
|
||||
isToday,
|
||||
isTomorrow,
|
||||
} from "../src/utils";
|
||||
|
||||
describe("Frontend Utilities", () => {
|
||||
@@ -32,4 +42,129 @@ describe("Frontend Utilities", () => {
|
||||
expect(getHoursRemainingBadge(36).urgencyClass).toBe("badge-warning");
|
||||
expect(getHoursRemainingBadge(72).urgencyClass).toBe("badge-info");
|
||||
});
|
||||
|
||||
describe("Date Filtering Utilities", () => {
|
||||
const baseDate = new Date("2026-10-20T10:00:00");
|
||||
|
||||
it("correctly identifies same calendar day", () => {
|
||||
const sameDay = new Date("2026-10-20T18:30:00");
|
||||
const diffDay = new Date("2026-10-21T10:00:00");
|
||||
expect(isSameDay(baseDate, sameDay)).toBe(true);
|
||||
expect(isSameDay(baseDate, diffDay)).toBe(false);
|
||||
});
|
||||
|
||||
it("identifies today and tomorrow relative to reference date", () => {
|
||||
const todayAppointment = new Date("2026-10-20T15:00:00");
|
||||
const tomorrowAppointment = new Date("2026-10-21T11:00:00");
|
||||
const nextWeekAppointment = new Date("2026-10-28T11:00:00");
|
||||
|
||||
expect(isToday(todayAppointment, baseDate)).toBe(true);
|
||||
expect(isToday(tomorrowAppointment, baseDate)).toBe(false);
|
||||
|
||||
expect(isTomorrow(tomorrowAppointment, baseDate)).toBe(true);
|
||||
expect(isTomorrow(todayAppointment, baseDate)).toBe(false);
|
||||
|
||||
expect(isThisWeek(todayAppointment, baseDate)).toBe(true);
|
||||
expect(isThisWeek(tomorrowAppointment, baseDate)).toBe(true);
|
||||
expect(isThisWeek(nextWeekAppointment, baseDate)).toBe(false);
|
||||
});
|
||||
|
||||
it("formats date to YYYY-MM-DD input string", () => {
|
||||
const testDate = new Date(2026, 9, 20); // October 20, 2026
|
||||
expect(formatDateInput(testDate)).toBe("2026-10-20");
|
||||
});
|
||||
});
|
||||
|
||||
describe("Collision Detection Utilities", () => {
|
||||
it("detects no collision when next appointment starts after buffer", () => {
|
||||
const startIso = "2026-10-20T10:00:00";
|
||||
const nextStartIso = "2026-10-20T11:15:00"; // Exactly after 60m + 15m buffer
|
||||
const result = checkBufferCollision(startIso, 60, 15, nextStartIso);
|
||||
|
||||
expect(result.hasCollision).toBe(false);
|
||||
expect(result.deficitMinutes).toBe(0);
|
||||
});
|
||||
|
||||
it("detects buffer collision when next appointment invades buffer window", () => {
|
||||
const startIso = "2026-10-20T10:00:00";
|
||||
const nextStartIso = "2026-10-20T11:05:00"; // 5 min into 15m buffer (10 min deficit)
|
||||
const result = checkBufferCollision(startIso, 60, 15, nextStartIso);
|
||||
|
||||
expect(result.hasCollision).toBe(true);
|
||||
expect(result.isBufferCollision).toBe(true);
|
||||
expect(result.isDirectCollision).toBe(false);
|
||||
expect(result.deficitMinutes).toBe(10);
|
||||
});
|
||||
|
||||
it("detects direct collision when next appointment starts before session ends", () => {
|
||||
const startIso = "2026-10-20T10:00:00";
|
||||
const nextStartIso = "2026-10-20T10:45:00"; // 15 min before session ends
|
||||
const result = checkBufferCollision(startIso, 60, 15, nextStartIso);
|
||||
|
||||
expect(result.hasCollision).toBe(true);
|
||||
expect(result.isDirectCollision).toBe(true);
|
||||
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);
|
||||
});
|
||||
});
|
||||
});
|
||||