diff --git a/src/components/DailyAgenda.ts b/src/components/DailyAgenda.ts index 5a5bc3d..e6e67cd 100644 --- a/src/components/DailyAgenda.ts +++ b/src/components/DailyAgenda.ts @@ -1,16 +1,33 @@ import { fetchAllBookings, retryCalendarSync } from "../api"; import type { Booking } from "../types"; -import { calculateInterval, formatCurrency, formatDateTime } from "../utils"; +import { + calculateInterval, + checkBufferCollision, + formatCurrency, + formatDateTime, + formatTimeOnly, + isSameDay, + isThisWeek, + isToday, + isTomorrow, +} from "../utils"; 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 = `
@@ -24,6 +41,37 @@ export function renderDailyAgenda(
+ +
+
+ + + + +
+ +
+ + +
+
+ +
+
@@ -36,9 +84,17 @@ export function renderDailyAgenda( const contentDiv = container.querySelector("#agenda-content"); const statsDiv = container.querySelector("#agenda-stats"); + const indicatorDiv = container.querySelector( + "#agenda-filter-indicator", + ); const refreshBtn = container.querySelector( "#refresh-agenda-btn", ); + const customDateInput = container.querySelector( + "#agenda-custom-date", + ); + const filterButtons = + container.querySelectorAll(".btn-filter-pill"); const loadData = async () => { if (!contentDiv) return; @@ -50,8 +106,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 +117,7 @@ export function renderDailyAgenda( new Date(b.scheduled_at).getTime(), ); - renderStats(activeBookings); - renderTimeline(activeBookings); + applyFilter(); } catch (err: unknown) { if (contentDiv) { contentDiv.innerHTML = ` @@ -71,12 +125,76 @@ export function renderDailyAgenda(
⚠️

Error al cargar la agenda

${err instanceof Error ? err.message : "Error desconocido"}

+
`; + 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: Hoy (${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: Mañana (${new Intl.DateTimeFormat("es-MX", { dateStyle: "long" }).format(tomorrow)})`; + } else if (activeFilter === "THIS_WEEK") { + label = `📅 Mostrando citas para: Esta Semana`; + } 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: ${new Intl.DateTimeFormat("es-MX", { dateStyle: "long" }).format(targetDate)}`; + } else { + label = "📅 Mostrando: Todas las citas programadas"; + } + + indicatorDiv.innerHTML = ` + ${label} + ${filteredCount} ${filteredCount === 1 ? "cita activa" : "citas activas"} + `; + }; + + 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 +212,7 @@ export function renderDailyAgenda( statsDiv.innerHTML = `
- Citas Programadas + Citas en Periodo ${total}
@@ -119,8 +237,8 @@ export function renderDailyAgenda( contentDiv.innerHTML = `
📅
-

Agenda libre

-

No hay citas activas programadas en este momento.

+

Agenda libre en este periodo

+

No hay citas activas programadas para el filtro seleccionado. Puedes cambiar de fecha o ver "Todas las Citas".

`; return; @@ -140,11 +258,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 = ` -
- ⚠️ ADVERTENCIA: La siguiente cita (${nextBooking.booking_code}) inicia a las ${interval.endStr}, invadiendo el buffer de preparación. + `; } @@ -207,21 +359,66 @@ export function renderDailyAgenda( 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(); } diff --git a/src/components/FollowUpQueue.ts b/src/components/FollowUpQueue.ts index 5b4fc18..21be971 100644 --- a/src/components/FollowUpQueue.ts +++ b/src/components/FollowUpQueue.ts @@ -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(
- ·
@@ -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 { - await authorizeDelayedPayment(id, notes); - loadData(); - onStateChange(); - } catch (err: unknown) { - alert( - err instanceof Error ? err.message : "Error al autorizar prórroga", - ); - } + 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(); + }, + }); }); }); // 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 { - await releaseBooking(id, reason); - loadData(); - onStateChange(); - } catch (err: unknown) { - alert( - err instanceof Error ? err.message : "Error al liberar espacio", - ); - } + 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(); + }, + }); }); }); }; diff --git a/src/components/MicroModal.ts b/src/components/MicroModal.ts new file mode 100644 index 0000000..bbe1f5a --- /dev/null +++ b/src/components/MicroModal.ts @@ -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; + 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; + 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 + ? ` +
+
+ Folio: + ${bookingContext.bookingCode} +
+ ${ + bookingContext.clientName + ? ` +
+ Paciente: + ${bookingContext.clientName} +
` + : "" + } + ${ + bookingContext.serviceName + ? ` +
+ Servicio: + ${bookingContext.serviceName} +
` + : "" + } + ${ + bookingContext.scheduledAtFormatted + ? ` +
+ Horario: + ${bookingContext.scheduledAtFormatted} +
` + : "" + } +
+ ` + : ""; + + backdrop.innerHTML = ` + + `; + + 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("#micro-modal-form"); + const textarea = backdrop.querySelector("#prompt-input"); + const submitBtn = backdrop.querySelector( + "#micro-modal-submit", + ); + const errorBox = backdrop.querySelector("#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 + ? ` +
+
+ Folio: + ${bookingContext.bookingCode} +
+ ${ + bookingContext.clientName + ? ` +
+ Paciente: + ${bookingContext.clientName} +
` + : "" + } + ${ + bookingContext.serviceName + ? ` +
+ Servicio: + ${bookingContext.serviceName} +
` + : "" + } + ${ + bookingContext.scheduledAtFormatted + ? ` +
+ Horario: + ${bookingContext.scheduledAtFormatted} +
` + : "" + } +
+ ` + : ""; + + const reasonSectionHtml = withReasonInput + ? ` +
+ + +
+ ` + : ""; + + backdrop.innerHTML = ` + + `; + + 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( + "#confirm-modal-submit", + ); + const errorBox = backdrop.querySelector( + "#confirm-modal-error", + ); + const reasonInput = backdrop.querySelector( + "#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"); + } + }); +} diff --git a/src/components/PaymentModal.ts b/src/components/PaymentModal.ts index d9dd383..0513916 100644 --- a/src/components/PaymentModal.ts +++ b/src/components/PaymentModal.ts @@ -14,7 +14,7 @@ export interface PaymentModalOptions { export function openPaymentModal(options: { booking: Booking; - onSuccess: () => void; + onSuccess: (amount: number) => void; }): void { const { booking, onSuccess } = options; @@ -169,7 +169,7 @@ export function openPaymentModal(options: { notes, }); close(); - onSuccess(); + onSuccess(amount); } catch (err: unknown) { submitBtn.disabled = false; submitBtn.textContent = "Confirmar Acreditación"; diff --git a/src/components/Toast.ts b/src/components/Toast.ts new file mode 100644 index 0000000..5578d60 --- /dev/null +++ b/src/components/Toast.ts @@ -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 = { + success: "✓", + warning: "⏳", + error: "⚠️", + info: "ℹ️", + }; + + toast.innerHTML = ` + +
+ ${options?.folio ? `${options.folio}` : ""} + ${message} +
+ + `; + + const removeToast = () => { + toast.classList.add("toast-leaving"); + setTimeout(() => { + toast.remove(); + }, 250); + }; + + const closeBtn = toast.querySelector(".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; +} diff --git a/src/main.ts b/src/main.ts index 08e316c..033c3f4 100644 --- a/src/main.ts +++ b/src/main.ts @@ -32,7 +32,7 @@ class OperatorDashboardApp { this.container.innerHTML = `
- 🪷 +

Armonía del Ser

Panel Operativo de Consultas y Agenda
@@ -47,7 +47,8 @@ class OperatorDashboardApp {
-