diff --git a/src/components/WorkshopRoster.ts b/src/components/WorkshopRoster.ts index 576b31d..2ffff38 100644 --- a/src/components/WorkshopRoster.ts +++ b/src/components/WorkshopRoster.ts @@ -1,4 +1,12 @@ -import { getCleanDigitsPhone } from "../utils"; +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: @@ -45,6 +53,45 @@ export function buildWhatsAppUrl(phone: string): string { 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" @@ -64,3 +111,744 @@ export function disambiguate409Error(detail?: string): ConflictType { } return "UNKNOWN"; } + +/** + * Main component renderer for the Group Workshop Roster view (#rosters) + */ +export function renderWorkshopRoster( + container: HTMLElement, + onStateChange?: () => void, +): void { + let selectedDate = getTodayDateString(); + let cachedSessions: RosterSession[] = []; + + container.innerHTML = ` +
+
+

Talleres Grupales & Control de Asistencia

+

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

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

Sin talleres programados

+

No hay talleres grupales programados para esta fecha.

+

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

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

${session.service_name}

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

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

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