diff --git a/bin/vp b/bin/vp new file mode 120000 index 0000000..d896557 --- /dev/null +++ b/bin/vp @@ -0,0 +1 @@ +vp.js \ No newline at end of file diff --git a/docs/screenshots/desktop-agenda.png b/docs/screenshots/desktop-agenda.png new file mode 100644 index 0000000..96b70be Binary files /dev/null and b/docs/screenshots/desktop-agenda.png differ diff --git a/docs/screenshots/desktop-clients.png b/docs/screenshots/desktop-clients.png new file mode 100644 index 0000000..2406591 Binary files /dev/null and b/docs/screenshots/desktop-clients.png differ diff --git a/docs/screenshots/desktop-intake-modal.png b/docs/screenshots/desktop-intake-modal.png new file mode 100644 index 0000000..93988e2 Binary files /dev/null and b/docs/screenshots/desktop-intake-modal.png differ diff --git a/docs/screenshots/mobile-agenda.png b/docs/screenshots/mobile-agenda.png new file mode 100644 index 0000000..ab748e0 Binary files /dev/null and b/docs/screenshots/mobile-agenda.png differ diff --git a/docs/screenshots/mobile-clients.png b/docs/screenshots/mobile-clients.png new file mode 100644 index 0000000..fb65562 Binary files /dev/null and b/docs/screenshots/mobile-clients.png differ diff --git a/docs/screenshots/mobile-intake-modal.png b/docs/screenshots/mobile-intake-modal.png new file mode 100644 index 0000000..3ab2628 Binary files /dev/null and b/docs/screenshots/mobile-intake-modal.png differ diff --git a/src/api.ts b/src/api.ts index 2e1d6f1..85c7c86 100644 --- a/src/api.ts +++ b/src/api.ts @@ -1,7 +1,16 @@ import type { + AdminPrincipal, Booking, + BookingCompletePayload, + BookingCreatePayload, + BookingReschedulePayload, + Client, + Client360, + ClientUpdatePayload, + PackageRecord, PaymentAcknowledgmentPayload, PaymentRecord, + Service, } from "./types"; const API_BASE_URL = @@ -130,3 +139,149 @@ export async function retryCalendarSync(bookingId: string): Promise { } return res.json(); } + +export async function fetchCurrentAdmin(): Promise { + 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 { + 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 { + 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 { + 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 { + 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 { + 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 { + 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 { + 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 { + 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(); +} diff --git a/src/components/ClientDirectory.ts b/src/components/ClientDirectory.ts new file mode 100644 index 0000000..be1afd4 --- /dev/null +++ b/src/components/ClientDirectory.ts @@ -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 = ` +
+
+

Directorio de Consultantes

+

Expedientes de contacto, notas clínicas y seguimiento de paquetes activos.

+
+
+ +
+
+ + + + + +
+
+
+
+
+
+ `; + + const contentDiv = + container.querySelector("#clients-content"); + const searchInput = container.querySelector( + "#client-directory-search", + ); + const clearSearchBtn = + container.querySelector("#clear-search-btn"); + const counterDiv = + container.querySelector("#clients-counter"); + const refreshBtn = container.querySelector( + "#refresh-clients-btn", + ); + + let cachedClients: Client[] = []; + let cachedPackages: PackageRecord[] = []; + let currentQuery = ""; + + const loadData = async (query = "") => { + if (!contentDiv) return; + currentQuery = query; + + contentDiv.innerHTML = ` +
+
+
+
+ `; + + 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 = ` +
+
⚠️
+

No se pudo cargar el directorio

+

${msg}

+ +
+ `; + 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 = ` +
+
👥
+

+ ${currentQuery ? "Sin coincidencias" : "Directorio vacío"} +

+

+ ${ + currentQuery + ? `No se encontraron consultantes para "${escapeHtml(currentQuery)}". Puedes registrar una nueva cita desde el botón superior.` + : "Aún no hay consultantes registrados en el sistema." + } +

+
+ `; + return; + } + + contentDiv.innerHTML = ` +
+ ${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) => ` + + 📦 Paquete: ${pkg.completed_sessions} de ${pkg.total_sessions} + ${pkg.service_name ? `(${escapeHtml(pkg.service_name)})` : ""} + + `, + ) + .join("") + : 'Sin paquetes activos'; + + return ` +
+
+
+

${escapeHtml(c.full_name)}

+ + Registrado el ${new Date(c.created_at).toLocaleDateString("es-MX", { day: "numeric", month: "short", year: "numeric" })} + +
+ +
+ +
+
+ + 💬 ${escapeHtml(c.phone_whatsapp)} + + ${ + c.email + ? `✉️ ${escapeHtml(c.email)}` + : 'Sin correo' + } +
+ +
+ Estado de Paquetes: +
+ ${packagesHtml} +
+
+ + ${ + c.notes + ? ` +
+ Notas Clínicas / Operativas: +

${escapeHtml(c.notes)}

+
+ ` + : ` +
+ Sin notas adicionales registradas. +
+ ` + } +
+
+ `; + }) + .join("")} +
+ `; + + // 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 = ` + + `; + + 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("#edit-client-form"); + const nameInput = + backdrop.querySelector("#edit-client-name"); + const phoneInput = + backdrop.querySelector("#edit-client-phone"); + const emailInput = + backdrop.querySelector("#edit-client-email"); + const notesInput = + backdrop.querySelector("#edit-client-notes"); + const submitBtn = + backdrop.querySelector("#edit-modal-submit"); + const errorBox = backdrop.querySelector("#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, "'"); +} diff --git a/src/components/DailyAgenda.ts b/src/components/DailyAgenda.ts index e6e67cd..18af1a5 100644 --- a/src/components/DailyAgenda.ts +++ b/src/components/DailyAgenda.ts @@ -1,9 +1,15 @@ -import { fetchAllBookings, retryCalendarSync } from "../api"; +import { + completeBooking, + fetchAllBookings, + rescheduleBooking, + retryCalendarSync, +} from "../api"; import type { Booking } from "../types"; import { calculateInterval, checkBufferCollision, formatCurrency, + formatDateInput, formatDateTime, formatTimeOnly, isSameDay, @@ -11,6 +17,7 @@ import { isToday, isTomorrow, } from "../utils"; +import { showConfirmModal } from "./MicroModal"; import { renderBookingStatusBadge, renderCalendarSyncBadge, @@ -345,6 +352,31 @@ export function renderDailyAgenda( Tiempo no agendable protegido por el backend. + ${ + b.booking_status === "RESERVED" + ? ` +
+ + +
+ ` + : "" + } + ${collisionNotice} @@ -354,6 +386,72 @@ export function renderDailyAgenda( `; + // 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 ${booking.client_name || "Cliente"} (${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 () => { @@ -422,3 +520,184 @@ export function renderDailyAgenda( 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 = ` + + `; + + 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("#reschedule-form"); + const dateInput = + backdrop.querySelector("#reschedule-date"); + const timeInput = + backdrop.querySelector("#reschedule-time"); + const notesInput = + backdrop.querySelector("#reschedule-notes"); + const submitBtn = backdrop.querySelector( + "#reschedule-submit-btn", + ); + const errorBox = backdrop.querySelector("#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"); + } + }); +} diff --git a/src/components/IntakeModal.ts b/src/components/IntakeModal.ts new file mode 100644 index 0000000..af4df9b --- /dev/null +++ b/src/components/IntakeModal.ts @@ -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 = ` + + `; + + 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("#intake-form"); + const serviceSelect = + backdrop.querySelector("#intake-service"); + const serviceHint = backdrop.querySelector( + "#service-preview-hint", + ); + const searchInput = backdrop.querySelector( + "#client-search-input", + ); + const phoneInput = backdrop.querySelector( + "#client-phone-input", + ); + const emailInput = backdrop.querySelector( + "#client-email-input", + ); + const clientBadge = + backdrop.querySelector("#client-type-badge"); + const clearClientBtn = + backdrop.querySelector("#clear-client-btn"); + const dropdown = backdrop.querySelector("#combobox-dropdown"); + const dateInput = backdrop.querySelector("#intake-date"); + const timeInput = backdrop.querySelector("#intake-time"); + const notesInput = + backdrop.querySelector("#intake-notes"); + const errorBox = backdrop.querySelector("#intake-error"); + const submitBtn = + backdrop.querySelector("#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 = + ''; + return; + } + + serviceSelect.innerHTML = ` + + ${services + .map( + (s) => ` + + `, + ) + .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 = + ''; + } + 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: ${svc.duration_minutes} min + ${svc.buffer_minutes || 15} min de colchón obligatorio protegido. + ${svc.price_mxn ? `• Tarifa: ${formatCurrency(svc.price_mxn)}` : ""} + `; + }; + + 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 = ` +
+ No se encontraron pacientes para "${escapeHtml(q)}". + Se registrará como nuevo paciente con los datos ingresados. +
+ `; + showDropdown(); + return; + } + + dropdown.innerHTML = results + .map( + (c) => ` +
+
${escapeHtml(c.full_name)}
+
+ 📱 ${escapeHtml(c.phone_whatsapp)} + ${c.email ? `✉️ ${escapeHtml(c.email)}` : ""} +
+
+ `, + ) + .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 = ` + + `; + + 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, "'"); +} diff --git a/src/components/PaymentModal.ts b/src/components/PaymentModal.ts index 0513916..d0b8909 100644 --- a/src/components/PaymentModal.ts +++ b/src/components/PaymentModal.ts @@ -1,3 +1,4 @@ +import { acknowledgePayment } from "../api"; import type { Booking } from "../types"; import { formatCurrency } from "../utils"; @@ -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, diff --git a/src/main.ts b/src/main.ts index 033c3f4..9bff54d 100644 --- a/src/main.ts +++ b/src/main.ts @@ -1,10 +1,13 @@ 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 { getRoleBadge } from "./utils"; -type TabId = "queue" | "agenda" | "all"; +type TabId = "queue" | "agenda" | "clients" | "all"; class OperatorDashboardApp { private activeTab: TabId = "queue"; @@ -22,10 +25,26 @@ class OperatorDashboardApp { private async init(): Promise { this.renderShell(); this.bindEvents(); - await this.refreshTabBadge(); - const hash = window.location.hash.replace("#", "") as TabId; - const initialTab = hash === "agenda" || hash === "all" ? hash : "queue"; - this.switchTab(initialTab); + 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(); + this.switchTab(this.activeTab); + }, + }); + } else { + const initialTab = + hash === "agenda" || hash === "clients" || hash === "all" + ? hash + : "queue"; + this.switchTab(initialTab); + } } private renderShell(): void { @@ -39,10 +58,22 @@ class OperatorDashboardApp { Operador -
-
- - Jasmin & Asistente + +
+ + +
+
+ + Cargando operador... +
@@ -56,6 +87,9 @@ class OperatorDashboardApp { + @@ -75,6 +109,10 @@ class OperatorDashboardApp { Agenda +