feat: implement customer registration flow and business hours system

Major changes:
- Add customer registration with email/phone lookup (app/booking/registro)
- Add customers API endpoint (app/api/customers/route)
- Implement business hours for locations (mon-fri 10-7, sat 10-6, sun closed)
- Fix availability function type casting issues
- Add business hours utilities (lib/utils/business-hours.ts)
- Update Location type to include business_hours JSONB
- Add mock payment component for testing
- Remove Supabase auth from booking flow
- Fix /cita redirect path in booking flow

Database migrations:
- Add category column to services table
- Add business_hours JSONB column to locations table
- Fix availability functions with proper type casting
- Update get_detailed_availability to use business_hours

Features:
- Customer lookup by email or phone
- Auto-redirect to registration if customer not found
- Pre-fill customer data if exists
- Business hours per day of week
- Location-specific opening/closing times
This commit is contained in:
Marco Gallegos
2026-01-17 00:29:49 -06:00
parent fb60178c86
commit 583a25a6f6
56 changed files with 2676 additions and 491 deletions

View File

@@ -1,5 +1,5 @@
import { NextRequest, NextResponse } from 'next/server'
import { supabaseAdmin } from '@/lib/supabase/client'
import { supabaseAdmin } from '@/lib/supabase/admin'
async function validateAdmin(request: NextRequest) {
const authHeader = request.headers.get('authorization')

View File

@@ -1,5 +1,5 @@
import { NextRequest, NextResponse } from 'next/server'
import { supabaseAdmin } from '@/lib/supabase/client'
import { supabaseAdmin } from '@/lib/supabase/admin'
async function validateAdmin(request: NextRequest) {
const authHeader = request.headers.get('authorization')

View File

@@ -1,5 +1,5 @@
import { NextRequest, NextResponse } from 'next/server'
import { supabaseAdmin } from '@/lib/supabase/client'
import { supabaseAdmin } from '@/lib/supabase/admin'
async function validateAdmin(request: NextRequest) {
const authHeader = request.headers.get('authorization')

View File

@@ -1,5 +1,5 @@
import { NextRequest, NextResponse } from 'next/server'
import { supabaseAdmin } from '@/lib/supabase/client'
import { supabaseAdmin } from '@/lib/supabase/admin'
/**
* @description Fetches bookings with filters for dashboard view

View File

@@ -1,5 +1,5 @@
import { NextRequest, NextResponse } from 'next/server'
import { supabaseAdmin } from '@/lib/supabase/client'
import { supabaseAdmin } from '@/lib/supabase/admin'
/**
* @description Fetches recent payments report

View File

@@ -1,5 +1,5 @@
import { NextRequest, NextResponse } from 'next/server'
import { supabaseAdmin } from '@/lib/supabase/client'
import { supabaseAdmin } from '@/lib/supabase/admin'
/**
* @description Fetches payroll report for staff based on recent bookings

View File

@@ -1,5 +1,5 @@
import { NextRequest, NextResponse } from 'next/server'
import { supabaseAdmin } from '@/lib/supabase/client'
import { supabaseAdmin } from '@/lib/supabase/admin'
/**
* @description Fetches sales report including total sales, completed bookings, average service price, and sales by service

View File

@@ -1,5 +1,5 @@
import { NextRequest, NextResponse } from 'next/server'
import { supabaseAdmin } from '@/lib/supabase/client'
import { supabaseAdmin } from '@/lib/supabase/admin'
/**
* @description Retrieves active resources, optionally filtered by location

View File

@@ -1,5 +1,5 @@
import { NextRequest, NextResponse } from 'next/server'
import { supabaseAdmin } from '@/lib/supabase/client'
import { supabaseAdmin } from '@/lib/supabase/admin'
/**
* @description Gets available staff for a location and date

View File

@@ -1,5 +1,5 @@
import { NextRequest, NextResponse } from 'next/server'
import { supabaseAdmin } from '@/lib/supabase/client'
import { supabaseAdmin } from '@/lib/supabase/admin'
/**
* @description Retrieves staff availability schedule with optional filters

View File

@@ -1,5 +1,5 @@
import { NextRequest, NextResponse } from 'next/server'
import { supabaseAdmin } from '@/lib/supabase/client'
import { supabaseAdmin } from '@/lib/supabase/admin'
async function validateAdmin(request: NextRequest) {
const authHeader = request.headers.get('authorization')

View File

@@ -1,5 +1,5 @@
import { NextRequest, NextResponse } from 'next/server'
import { supabaseAdmin } from '@/lib/supabase/client'
import { supabaseAdmin } from '@/lib/supabase/admin'
async function validateAdminOrStaff(request: NextRequest) {
const authHeader = request.headers.get('authorization')

View File

@@ -1,5 +1,5 @@
import { NextRequest, NextResponse } from 'next/server'
import { supabaseAdmin } from '@/lib/supabase/client'
import { supabaseAdmin } from '@/lib/supabase/admin'
/**
* @description Retrieves available staff for a time range

View File

@@ -1,5 +1,5 @@
import { NextRequest, NextResponse } from 'next/server'
import { supabaseAdmin } from '@/lib/supabase/client'
import { supabaseAdmin } from '@/lib/supabase/admin'
/**
* @description Retrieves detailed availability time slots for a date

View File

@@ -1,5 +1,5 @@
import { NextRequest, NextResponse } from 'next/server'
import { supabaseAdmin } from '@/lib/supabase/client'
import { supabaseAdmin } from '@/lib/supabase/admin'
/**
* @description Updates the status of a specific booking

View File

@@ -1,5 +1,5 @@
import { NextRequest, NextResponse } from 'next/server'
import { supabaseAdmin } from '@/lib/supabase/client'
import { supabaseAdmin } from '@/lib/supabase/admin'
import { generateShortId } from '@/lib/utils/short-id'
/**
@@ -9,6 +9,7 @@ export async function POST(request: NextRequest) {
try {
const body = await request.json()
const {
customer_id,
customer_email,
customer_phone,
customer_first_name,
@@ -19,9 +20,16 @@ export async function POST(request: NextRequest) {
notes
} = body
if (!customer_email || !service_id || !location_id || !start_time_utc) {
if (!customer_id && (!customer_email || !customer_first_name || !customer_last_name)) {
return NextResponse.json(
{ error: 'Missing required fields: customer_email, service_id, location_id, start_time_utc' },
{ error: 'Missing required fields: customer_id OR (customer_email, customer_first_name, customer_last_name)' },
{ status: 400 }
)
}
if (!service_id || !location_id || !start_time_utc) {
return NextResponse.json(
{ error: 'Missing required fields: service_id, location_id, start_time_utc' },
{ status: 400 }
)
}
@@ -122,25 +130,39 @@ export async function POST(request: NextRequest) {
const assignedResource = availableResources[0]
// Create or find customer based on email
const { data: customer, error: customerError } = await supabaseAdmin
.from('customers')
.upsert({
email: customer_email,
phone: customer_phone || null,
first_name: customer_first_name || null,
last_name: customer_last_name || null
}, {
onConflict: 'email',
ignoreDuplicates: false
})
.select()
.single()
let customer
let customerError
if (customer_id) {
const result = await supabaseAdmin
.from('customers')
.select('*')
.eq('id', customer_id)
.single()
customer = result.data
customerError = result.error
} else {
const result = await supabaseAdmin
.from('customers')
.upsert({
email: customer_email,
phone: customer_phone || null,
first_name: customer_first_name || null,
last_name: customer_last_name || null
}, {
onConflict: 'email',
ignoreDuplicates: false
})
.select()
.single()
customer = result.data
customerError = result.error
}
if (customerError || !customer) {
console.error('Error creating customer:', customerError)
console.error('Error handling customer:', customerError)
return NextResponse.json(
{ error: 'Failed to create customer' },
{ error: 'Failed to handle customer' },
{ status: 500 }
)
}
@@ -248,8 +270,7 @@ export async function GET(request: NextRequest) {
id,
name,
duration_minutes,
base_price,
category
base_price
),
resource (
id,

View File

@@ -1,6 +1,6 @@
import { NextRequest, NextResponse } from 'next/server'
import Stripe from 'stripe'
import { supabaseAdmin } from '@/lib/supabase/client'
import { supabaseAdmin } from '@/lib/supabase/admin'
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!)

120
app/api/customers/route.ts Normal file
View File

@@ -0,0 +1,120 @@
import { NextRequest, NextResponse } from 'next/server'
import { supabaseAdmin } from '@/lib/supabase/admin'
export async function GET(request: NextRequest) {
try {
const { searchParams } = new URL(request.url)
const email = searchParams.get('email')
const phone = searchParams.get('phone')
if (!email && !phone) {
return NextResponse.json(
{ error: 'Se requiere email o teléfono' },
{ status: 400 }
)
}
let query = supabaseAdmin.from('customers').select('*').eq('is_active', true)
if (email) {
query = query.ilike('email', email)
} else if (phone) {
query = query.ilike('phone', phone)
}
const { data: customers, error } = await query.limit(1)
if (error) {
console.error('Error buscando cliente:', error)
return NextResponse.json(
{ error: 'Error al buscar cliente' },
{ status: 500 }
)
}
return NextResponse.json({
exists: customers && customers.length > 0,
customer: customers && customers.length > 0 ? customers[0] : null
})
} catch (error) {
console.error('Error en GET /api/customers:', error)
return NextResponse.json(
{ error: 'Error interno del servidor' },
{ status: 500 }
)
}
}
export async function POST(request: NextRequest) {
try {
const body = await request.json()
const { email, phone, first_name, last_name, birthday, occupation } = body
if (!email || !phone || !first_name || !last_name) {
return NextResponse.json(
{ error: 'Faltan campos requeridos: email, phone, first_name, last_name' },
{ status: 400 }
)
}
const { data: existingCustomer, error: checkError } = await supabaseAdmin
.from('customers')
.select('*')
.or(`email.ilike.${email},phone.ilike.${phone}`)
.eq('is_active', true)
.limit(1)
.single()
if (checkError && checkError.code !== 'PGRST116') {
console.error('Error verificando cliente existente:', checkError)
return NextResponse.json(
{ error: 'Error al verificar cliente existente' },
{ status: 500 }
)
}
if (existingCustomer) {
return NextResponse.json({
success: false,
message: 'El cliente ya existe',
customer: existingCustomer
})
}
const { data: newCustomer, error: insertError } = await supabaseAdmin
.from('customers')
.insert({
email,
phone,
first_name,
last_name,
tier: 'free',
total_spent: 0,
total_visits: 0,
is_active: true,
notes: birthday || occupation ? JSON.stringify({ birthday, occupation }) : null
})
.select()
.single()
if (insertError) {
console.error('Error creando cliente:', insertError)
return NextResponse.json(
{ error: 'Error al crear cliente' },
{ status: 500 }
)
}
return NextResponse.json({
success: true,
message: 'Cliente registrado exitosamente',
customer: newCustomer
})
} catch (error) {
console.error('Error en POST /api/customers:', error)
return NextResponse.json(
{ error: 'Error interno del servidor' },
{ status: 500 }
)
}
}

View File

@@ -1,5 +1,5 @@
import { NextRequest, NextResponse } from 'next/server'
import { supabaseAdmin } from '@/lib/supabase/client'
import { supabaseAdmin } from '@/lib/supabase/admin'
import { Kiosk } from '@/lib/db/types'
/**

View File

@@ -1,5 +1,5 @@
import { NextRequest, NextResponse } from 'next/server'
import { supabaseAdmin } from '@/lib/supabase/client'
import { supabaseAdmin } from '@/lib/supabase/admin'
async function validateKiosk(request: NextRequest) {
const apiKey = request.headers.get('x-kiosk-api-key')

View File

@@ -1,5 +1,5 @@
import { NextRequest, NextResponse } from 'next/server'
import { supabaseAdmin } from '@/lib/supabase/client'
import { supabaseAdmin } from '@/lib/supabase/admin'
async function validateKiosk(request: NextRequest) {
const apiKey = request.headers.get('x-kiosk-api-key')

View File

@@ -1,5 +1,5 @@
import { NextRequest, NextResponse } from 'next/server'
import { supabaseAdmin } from '@/lib/supabase/client'
import { supabaseAdmin } from '@/lib/supabase/admin'
async function validateKiosk(request: NextRequest) {
const apiKey = request.headers.get('x-kiosk-api-key')

View File

@@ -1,5 +1,5 @@
import { NextRequest, NextResponse } from 'next/server'
import { supabaseAdmin } from '@/lib/supabase/client'
import { supabaseAdmin } from '@/lib/supabase/admin'
/**
* Validates kiosk API key and returns kiosk info if valid

View File

@@ -1,5 +1,5 @@
import { NextRequest, NextResponse } from 'next/server'
import { supabaseAdmin } from '@/lib/supabase/client'
import { supabaseAdmin } from '@/lib/supabase/admin'
/**
* @description Retrieves all active locations

View File

@@ -1,5 +1,5 @@
import { NextRequest, NextResponse } from 'next/server'
import { supabaseAdmin } from '@/lib/supabase/client'
import { supabaseAdmin } from '@/lib/supabase/admin'
/**
* @description Retrieves active services, optionally filtered by location
@@ -11,9 +11,8 @@ export async function GET(request: NextRequest) {
let query = supabaseAdmin
.from('services')
.select('*')
.select('id, name, description, duration_minutes, base_price, requires_dual_artist, premium_fee_enabled, category, is_active, created_at, updated_at')
.eq('is_active', true)
.order('category', { ascending: true })
.order('name', { ascending: true })
if (locationId) {

View File

@@ -1,21 +1,26 @@
'use client'
import { useState, useEffect } from 'react'
import { useRouter } from 'next/navigation'
import { useRouter, useSearchParams } from 'next/navigation'
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { CheckCircle2, Calendar, Clock, MapPin, CreditCard } from 'lucide-react'
import { CardElement, useStripe, useElements } from '@stripe/react-stripe-js'
import { format } from 'date-fns'
import { CheckCircle2, Calendar, Clock, MapPin, Mail, Phone, Search, User } from 'lucide-react'
import { format, parseISO } from 'date-fns'
import { es } from 'date-fns/locale'
import { useAuth } from '@/lib/auth/context'
import MockPaymentForm from '@/components/booking/mock-payment-form'
/** @description Booking confirmation and payment page component for completing appointment reservations. */
export default function CitaPage() {
const { user, loading: authLoading } = useAuth()
const router = useRouter()
const searchParams = useSearchParams()
const [step, setStep] = useState<'search' | 'details' | 'payment' | 'success'>('search')
const [searchValue, setSearchValue] = useState('')
const [searchType, setSearchType] = useState<'email' | 'phone'>('email')
const [customer, setCustomer] = useState<any>(null)
const [searchingCustomer, setSearchingCustomer] = useState(false)
const [formData, setFormData] = useState({
nombre: '',
email: '',
@@ -25,57 +30,57 @@ export default function CitaPage() {
const [bookingDetails, setBookingDetails] = useState<any>(null)
const [pageLoading, setPageLoading] = useState(false)
const [submitted, setSubmitted] = useState(false)
const [paymentIntent, setPaymentIntent] = useState<any>(null)
const [showPayment, setShowPayment] = useState(false)
const stripe = useStripe()
const elements = useElements()
const [depositAmount, setDepositAmount] = useState(0)
const [errors, setErrors] = useState<Record<string, string>>({})
useEffect(() => {
if (!authLoading && !user) {
router.push('/booking/login?redirect=/booking/cita' + window.location.search)
}
}, [user, authLoading, router])
if (authLoading) {
return (
<div className="min-h-screen bg-[var(--bone-white)] pt-24 flex items-center justify-center">
<div className="text-center">
<p>Cargando...</p>
</div>
</div>
)
}
if (!user) {
return null
}
useEffect(() => {
const params = new URLSearchParams(window.location.search)
const service_id = params.get('service_id')
const location_id = params.get('location_id')
const date = params.get('date')
const time = params.get('time')
const service_id = searchParams.get('service_id')
const location_id = searchParams.get('location_id')
const date = searchParams.get('date')
const time = searchParams.get('time')
const customer_id = searchParams.get('customer_id')
if (service_id && location_id && date && time) {
fetchBookingDetails(service_id, location_id, date, time)
}
}, [])
useEffect(() => {
if (user) {
setFormData(prev => ({
...prev,
email: user.email || ''
}))
if (customer_id) {
fetchCustomerById(customer_id)
}
}, [user])
}, [searchParams])
const fetchCustomerById = async (customerId: string) => {
try {
const response = await fetch(`/api/customers?email=${customerId}`)
const data = await response.json()
if (data.exists && data.customer) {
setCustomer(data.customer)
setFormData(prev => ({
...prev,
nombre: `${data.customer.first_name} ${data.customer.last_name}`,
email: data.customer.email,
telefono: data.customer.phone || ''
}))
setStep('details')
}
} catch (error) {
console.error('Error fetching customer:', error)
}
}
const fetchBookingDetails = async (serviceId: string, locationId: string, date: string, time: string) => {
try {
const response = await fetch(`/api/availability/time-slots?location_id=${locationId}&service_id=${serviceId}&date=${date}`)
const data = await response.json()
if (data.availability?.services) {
const service = data.availability.services[0]
const deposit = Math.min(service.base_price * 0.5, 200)
setDepositAmount(deposit)
}
setBookingDetails({
service_id: serviceId,
location_id: locationId,
@@ -85,45 +90,76 @@ export default function CitaPage() {
})
} catch (error) {
console.error('Error fetching booking details:', error)
setErrors({ fetch: 'Error al cargar los detalles de la reserva' })
}
}
const handleSearchCustomer = async (e: React.FormEvent) => {
e.preventDefault()
setSearchingCustomer(true)
setErrors({})
if (!searchValue.trim()) {
setErrors({ search: 'Ingresa un email o teléfono' })
setSearchingCustomer(false)
return
}
try {
const response = await fetch(`/api/customers?${searchType}=${encodeURIComponent(searchValue)}`)
const data = await response.json()
if (data.exists && data.customer) {
setCustomer(data.customer)
setFormData(prev => ({
...prev,
nombre: `${data.customer.first_name} ${data.customer.last_name}`,
email: data.customer.email,
telefono: data.customer.phone || ''
}))
setStep('details')
} else {
const params = new URLSearchParams({
...Object.fromEntries(searchParams.entries()),
[searchType]: searchValue
})
router.push(`/booking/registro?${params.toString()}`)
}
} catch (error) {
console.error('Error searching customer:', error)
setErrors({ search: 'Error al buscar cliente' })
} finally {
setSearchingCustomer(false)
}
}
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault()
setErrors({})
setPageLoading(true)
try {
const response = await fetch('/api/create-payment-intent', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
customer_email: formData.email,
customer_phone: formData.telefono,
customer_first_name: formData.nombre.split(' ')[0] || formData.nombre,
customer_last_name: formData.nombre.split(' ').slice(1).join(' '),
service_id: bookingDetails.service_id,
location_id: bookingDetails.location_id,
start_time_utc: bookingDetails.startTime,
notes: formData.notas
})
})
const validationErrors: Record<string, string> = {}
const data = await response.json()
if (response.ok) {
setPaymentIntent(data)
setShowPayment(true)
} else {
alert('Error al preparar el pago: ' + (data.error || 'Error desconocido'))
}
} catch (error) {
console.error('Error creating payment intent:', error)
alert('Error al preparar el pago')
} finally {
setPageLoading(false)
if (!formData.nombre.trim()) {
validationErrors.nombre = 'Nombre requerido'
}
if (!formData.email.trim() || !formData.email.includes('@')) {
validationErrors.email = 'Email inválido'
}
if (!formData.telefono.trim()) {
validationErrors.telefono = 'Teléfono requerido'
}
if (Object.keys(validationErrors).length > 0) {
setErrors(validationErrors)
setPageLoading(false)
return
}
setShowPayment(true)
setPageLoading(false)
}
const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
@@ -131,80 +167,70 @@ export default function CitaPage() {
...formData,
[e.target.name]: e.target.value
})
setErrors({ ...errors, [e.target.name]: '' })
}
const handlePayment = async () => {
if (!stripe || !elements) return
const handleMockPayment = async (paymentMethod: any) => {
setPageLoading(true)
const { error } = await stripe.confirmCardPayment(paymentIntent.clientSecret, {
payment_method: {
card: elements.getElement(CardElement)!,
}
})
if (error) {
alert('Error en el pago: ' + error.message)
setPageLoading(false)
} else {
// Payment succeeded, create booking
try {
const response = await fetch('/api/bookings', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
customer_email: formData.email,
customer_phone: formData.telefono,
customer_first_name: formData.nombre.split(' ')[0] || formData.nombre,
customer_last_name: formData.nombre.split(' ').slice(1).join(' '),
service_id: bookingDetails.service_id,
location_id: bookingDetails.location_id,
start_time_utc: bookingDetails.startTime,
notes: formData.notas,
payment_intent_id: paymentIntent.id
})
try {
const response = await fetch('/api/bookings', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
customer_id: customer?.id,
customer_email: formData.email,
customer_phone: formData.telefono,
customer_first_name: formData.nombre.split(' ')[0] || formData.nombre,
customer_last_name: formData.nombre.split(' ').slice(1).join(' '),
service_id: bookingDetails.service_id,
location_id: bookingDetails.location_id,
start_time_utc: bookingDetails.startTime,
notes: formData.notas,
payment_method_id: 'mock_' + paymentMethod.cardNumber.slice(-4),
deposit_amount: depositAmount
})
})
const data = await response.json()
const data = await response.json()
if (response.ok && data.success) {
setSubmitted(true)
} else {
alert('Error al crear la reserva: ' + (data.error || 'Error desconocido'))
}
} catch (error) {
console.error('Error creating booking:', error)
alert('Error al crear la reserva')
} finally {
if (response.ok && data.success) {
setSubmitted(true)
} else {
setErrors({ submit: data.error || 'Error al crear la reserva' })
setPageLoading(false)
}
} catch (error) {
console.error('Error creating booking:', error)
setErrors({ submit: 'Error al crear la reserva' })
setPageLoading(false)
}
}
if (submitted) {
return (
<div className="min-h-screen bg-[var(--bone-white)] pt-24 flex items-center justify-center">
<div className="max-w-md w-full px-8">
<Card className="border-none" style={{ background: 'var(--soft-cream)' }}>
<div className="min-h-screen flex items-center justify-center" style={{ background: 'var(--bone-white)' }}>
<div className="max-w-md w-full px-6">
<Card style={{ background: 'var(--soft-cream)', borderColor: 'var(--mocha-taupe)', borderWidth: '1px' }}>
<CardContent className="pt-12 text-center">
<CheckCircle2 className="w-16 h-16 mx-auto mb-6" style={{ color: 'var(--deep-earth)' }} />
<h1 className="text-3xl font-bold mb-4" style={{ color: 'var(--charcoal-brown)' }}>
<h1 className="text-3xl font-bold mb-4 font-serif" style={{ color: 'var(--charcoal-brown)' }}>
¡Reserva Confirmada!
</h1>
<p className="text-lg mb-6" style={{ color: 'var(--charcoal-brown)', opacity: 0.8 }}>
Hemos enviado un correo de confirmación con los detalles de tu cita.
</p>
<div className="space-y-2 text-sm" style={{ color: 'var(--charcoal-brown)', opacity: 0.7 }}>
<div className="space-y-2 text-sm text-left mb-8 p-4 rounded-lg" style={{ background: 'var(--bone-white)', color: 'var(--charcoal-brown)', opacity: 0.7 }}>
<p>Fecha: {format(new Date(bookingDetails.date), 'PPP', { locale: es })}</p>
<p>Hora: {bookingDetails.time}</p>
<p>Puedes agregar esta cita a tu calendario.</p>
<p>Depósito pagado: ${depositAmount.toFixed(2)} USD</p>
</div>
<Button
onClick={() => window.location.href = '/'}
className="w-full"
style={{ background: 'var(--deep-earth)' }}
>
Volver al Inicio
</Button>
@@ -217,188 +243,278 @@ export default function CitaPage() {
if (!bookingDetails) {
return (
<div className="min-h-screen bg-[var(--bone-white)] pt-24 flex items-center justify-center">
<div className="min-h-screen flex items-center justify-center" style={{ background: 'var(--bone-white)' }}>
<div className="text-center">
<p>Cargando detalles de la reserva...</p>
<p style={{ color: 'var(--charcoal-brown)' }}>Cargando detalles de la reserva...</p>
</div>
</div>
)
}
return (
<div className="min-h-screen bg-[var(--bone-white)] pt-24">
<div className="max-w-4xl mx-auto px-8 py-16">
<header className="mb-12">
<div className="min-h-screen" style={{ background: 'var(--bone-white)' }}>
<div className="max-w-4xl mx-auto px-6 py-24">
<header className="mb-8">
<Button
variant="outline"
onClick={() => window.location.href = '/booking/servicios'}
style={{ borderColor: 'var(--mocha-taupe)', color: 'var(--charcoal-brown)' }}
>
Volver
</Button>
</header>
<div className="grid md:grid-cols-2 gap-8">
<Card className="border-none" style={{ background: 'var(--soft-cream)' }}>
<CardHeader>
<CardTitle style={{ color: 'var(--charcoal-brown)' }}>
Resumen de la Cita
</CardTitle>
</CardHeader>
<CardContent>
<div className="space-y-4">
<div className="flex items-start gap-3">
<Calendar className="w-5 h-5 mt-1" style={{ color: 'var(--mocha-taupe)' }} />
{step === 'search' && (
<div className="max-w-md mx-auto">
<Card style={{ background: 'var(--soft-cream)', borderColor: 'var(--mocha-taupe)', borderWidth: '1px' }}>
<CardHeader>
<CardTitle style={{ color: 'var(--charcoal-brown)' }}>
Buscar Cliente
</CardTitle>
<CardDescription>
Ingresa tu email o teléfono para continuar con la reserva
</CardDescription>
</CardHeader>
<CardContent>
<form onSubmit={handleSearchCustomer} className="space-y-6">
<div>
<p className="font-medium" style={{ color: 'var(--charcoal-brown)' }}>Fecha</p>
<p style={{ color: 'var(--charcoal-brown)', opacity: 0.8 }}>
{format(new Date(bookingDetails.date), 'PPP', { locale: es })}
</p>
</div>
</div>
<div className="flex items-start gap-3">
<Clock className="w-5 h-5 mt-1" style={{ color: 'var(--mocha-taupe)' }} />
<div>
<p className="font-medium" style={{ color: 'var(--charcoal-brown)' }}>Hora</p>
<p style={{ color: 'var(--charcoal-brown)', opacity: 0.8 }}>
{bookingDetails.time}
</p>
</div>
</div>
<div className="flex items-start gap-3">
<MapPin className="w-5 h-5 mt-1" style={{ color: 'var(--mocha-taupe)' }} />
<div>
<p className="font-medium" style={{ color: 'var(--charcoal-brown)' }}>Ubicación</p>
<p style={{ color: 'var(--charcoal-brown)', opacity: 0.8 }}>
Anchor:23 - Saltillo
</p>
</div>
</div>
</div>
</CardContent>
</Card>
<Card className="border-none" style={{ background: 'var(--soft-cream)' }}>
<CardHeader>
<CardTitle style={{ color: 'var(--charcoal-brown)' }}>
Tus Datos
</CardTitle>
<CardDescription>
Ingresa tus datos personales para completar la reserva
</CardDescription>
</CardHeader>
<CardContent>
<form onSubmit={handleSubmit} className="space-y-6">
<div>
<Label htmlFor="nombre">Nombre Completo *</Label>
<Input
id="nombre"
name="nombre"
value={formData.nombre}
onChange={handleChange}
required
placeholder="Ej. María García"
className="w-full"
style={{ borderColor: 'var(--mocha-taupe)' }}
/>
</div>
<div>
<Label htmlFor="email">Email *</Label>
<Input
id="email"
name="email"
type="email"
value={formData.email}
onChange={handleChange}
required
placeholder="tu@email.com"
className="w-full"
style={{ borderColor: 'var(--mocha-taupe)' }}
/>
</div>
<div>
<Label htmlFor="telefono">Teléfono *</Label>
<Input
id="telefono"
name="telefono"
type="tel"
value={formData.telefono}
onChange={handleChange}
required
placeholder="+52 844 123 4567"
className="w-full"
style={{ borderColor: 'var(--mocha-taupe)' }}
/>
</div>
<div>
<Label htmlFor="notas">Notas (opcional)</Label>
<textarea
id="notas"
name="notas"
value={formData.notas}
onChange={handleChange}
rows={4}
placeholder="Alguna observación o preferencia..."
className="w-full px-4 py-3 border rounded-lg resize-none"
style={{ borderColor: 'var(--mocha-taupe)' }}
/>
</div>
{showPayment ? (
<div className="space-y-4">
<div className="p-4 rounded-lg" style={{ background: 'var(--bone-white)' }}>
<Label>Información de Pago</Label>
<p className="text-sm opacity-70 mb-4">
Depósito requerido: ${(paymentIntent.amount / 100).toFixed(2)} USD
(50% del servicio o $200 máximo)
</p>
<div className="border rounded-lg p-4" style={{ borderColor: 'var(--mocha-taupe)' }}>
<CardElement
options={{
style: {
base: {
fontSize: '16px',
color: 'var(--charcoal-brown)',
'::placeholder': {
color: 'var(--mocha-taupe)',
},
},
},
}}
/>
</div>
<Label htmlFor="searchType">Buscar por</Label>
<div className="flex gap-2 mt-2">
<Button
type="button"
variant={searchType === 'email' ? 'default' : 'outline'}
onClick={() => setSearchType('email')}
style={searchType === 'email' ? { background: 'var(--deep-earth)' } : { borderColor: 'var(--mocha-taupe)', color: 'var(--charcoal-brown)' }}
>
<Mail className="w-4 h-4 mr-2" />
Email
</Button>
<Button
type="button"
variant={searchType === 'phone' ? 'default' : 'outline'}
onClick={() => setSearchType('phone')}
style={searchType === 'phone' ? { background: 'var(--deep-earth)' } : { borderColor: 'var(--mocha-taupe)', color: 'var(--charcoal-brown)' }}
>
<Phone className="w-4 h-4 mr-2" />
Teléfono
</Button>
</div>
<Button
onClick={handlePayment}
disabled={!stripe || pageLoading}
className="w-full"
>
{pageLoading ? 'Procesando Pago...' : 'Pagar y Confirmar Reserva'}
</Button>
</div>
) : (
<div>
<Label htmlFor="searchValue">{searchType === 'email' ? 'Email' : 'Teléfono'}</Label>
<div className="relative">
<Search className="absolute left-3 top-3 h-4 w-4 opacity-50" style={{ color: 'var(--mocha-taupe)' }} />
<Input
id="searchValue"
type={searchType === 'email' ? 'email' : 'tel'}
value={searchValue}
onChange={(e) => setSearchValue(e.target.value)}
className="pl-10"
style={{ borderColor: errors.search ? '#ef4444' : 'var(--mocha-taupe)' }}
placeholder={searchType === 'email' ? 'tu@email.com' : '+52 844 123 4567'}
/>
</div>
{errors.search && <p className="text-sm mt-1" style={{ color: '#ef4444' }}>{errors.search}</p>}
</div>
<Button
type="submit"
disabled={pageLoading}
disabled={searchingCustomer || !searchValue.trim()}
className="w-full"
style={{ background: 'var(--deep-earth)' }}
>
{pageLoading ? 'Procesando...' : 'Continuar al Pago'}
{searchingCustomer ? 'Buscando...' : 'Buscar Cliente'}
</Button>
)}
</form>
<div className="mt-6 p-4 rounded-lg" style={{ background: 'var(--bone-white)' }}>
<p className="text-sm" style={{ color: 'var(--charcoal-brown)', opacity: 0.7 }}>
* Al confirmar tu reserva, recibirás un correo de confirmación
con los detalles. Se requiere un depósito para confirmar.
</p>
</div>
</CardContent>
</Card>
</div>
{customer && (
<div className="p-4 rounded-lg" style={{ background: 'var(--bone-white)', color: 'var(--charcoal-brown)', opacity: 0.7 }}>
<p className="font-medium mb-1">Cliente encontrado:</p>
<p className="text-sm">{customer.first_name} {customer.last_name}</p>
<p className="text-sm">{customer.email}</p>
</div>
)}
</form>
</CardContent>
</Card>
</div>
)}
{step === 'details' && (
<div className="grid md:grid-cols-2 gap-8">
<div className="space-y-6">
<Card style={{ background: 'var(--soft-cream)', borderColor: 'var(--mocha-taupe)', borderWidth: '1px' }}>
<CardHeader>
<CardTitle style={{ color: 'var(--charcoal-brown)' }}>
Resumen de la Cita
</CardTitle>
</CardHeader>
<CardContent>
<div className="space-y-4">
<div className="flex items-start gap-3">
<Calendar className="w-5 h-5 mt-1" style={{ color: 'var(--mocha-taupe)' }} />
<div>
<p className="font-medium" style={{ color: 'var(--charcoal-brown)' }}>Fecha</p>
<p style={{ color: 'var(--charcoal-brown)', opacity: 0.8 }}>
{format(new Date(bookingDetails.date), 'PPP', { locale: es })}
</p>
</div>
</div>
<div className="flex items-start gap-3">
<Clock className="w-5 h-5 mt-1" style={{ color: 'var(--mocha-taupe)' }} />
<div>
<p className="font-medium" style={{ color: 'var(--charcoal-brown)' }}>Hora</p>
<p style={{ color: 'var(--charcoal-brown)', opacity: 0.8 }}>
{format(parseISO(bookingDetails.time), 'HH:mm', { locale: es })}
</p>
</div>
</div>
<div className="flex items-start gap-3">
<MapPin className="w-5 h-5 mt-1" style={{ color: 'var(--mocha-taupe)' }} />
<div>
<p className="font-medium" style={{ color: 'var(--charcoal-brown)' }}>Ubicación</p>
<p style={{ color: 'var(--charcoal-brown)', opacity: 0.8 }}>
Anchor:23 - Saltillo
</p>
</div>
</div>
{customer && (
<div className="flex items-start gap-3">
<User className="w-5 h-5 mt-1" style={{ color: 'var(--mocha-taupe)' }} />
<div>
<p className="font-medium" style={{ color: 'var(--charcoal-brown)' }}>Cliente</p>
<p style={{ color: 'var(--charcoal-brown)', opacity: 0.8 }}>
{customer.first_name} {customer.last_name}
</p>
</div>
</div>
)}
</div>
</CardContent>
</Card>
{showPayment && (
<Card style={{ background: 'var(--soft-cream)', borderColor: 'var(--mocha-taupe)', borderWidth: '1px' }}>
<CardHeader>
<CardTitle style={{ color: 'var(--charcoal-brown)' }}>
Pago del Depósito
</CardTitle>
</CardHeader>
<CardContent>
<p className="text-sm mb-4" style={{ color: 'var(--charcoal-brown)', opacity: 0.7 }}>
Se requiere un depósito del 50% del servicio (máximo $200) para confirmar tu reserva.
</p>
<MockPaymentForm
amount={depositAmount}
onSubmit={handleMockPayment}
disabled={pageLoading}
/>
</CardContent>
</Card>
)}
</div>
<Card style={{ background: 'var(--soft-cream)', borderColor: 'var(--mocha-taupe)', borderWidth: '1px' }}>
<CardHeader>
<CardTitle style={{ color: 'var(--charcoal-brown)' }}>
Tus Datos
</CardTitle>
<CardDescription style={{ color: 'var(--charcoal-brown)', opacity: 0.7 }}>
{customer ? 'Verifica y confirma tus datos' : 'Ingresa tus datos personales para completar la reserva'}
</CardDescription>
</CardHeader>
<CardContent>
{showPayment ? (
<div className="text-center py-8" style={{ color: 'var(--charcoal-brown)', opacity: 0.7 }}>
Datos completados. Por favor completa el pago para confirmar.
</div>
) : (
<form onSubmit={handleSubmit} className="space-y-6">
<div>
<Label htmlFor="nombre">Nombre Completo *</Label>
<Input
id="nombre"
name="nombre"
value={formData.nombre}
onChange={handleChange}
placeholder="Ej. María García"
className="w-full"
style={{ borderColor: errors.nombre ? '#ef4444' : 'var(--mocha-taupe)' }}
/>
{errors.nombre && <p className="text-sm mt-1" style={{ color: '#ef4444' }}>{errors.nombre}</p>}
</div>
<div>
<Label htmlFor="email">Email *</Label>
<Input
id="email"
name="email"
type="email"
value={formData.email}
onChange={handleChange}
placeholder="tu@email.com"
className="w-full"
style={{ borderColor: errors.email ? '#ef4444' : 'var(--mocha-taupe)' }}
/>
{errors.email && <p className="text-sm mt-1" style={{ color: '#ef4444' }}>{errors.email}</p>}
</div>
<div>
<Label htmlFor="telefono">Teléfono *</Label>
<Input
id="telefono"
name="telefono"
type="tel"
value={formData.telefono}
onChange={handleChange}
placeholder="+52 844 123 4567"
className="w-full"
style={{ borderColor: errors.telefono ? '#ef4444' : 'var(--mocha-taupe)' }}
/>
{errors.telefono && <p className="text-sm mt-1" style={{ color: '#ef4444' }}>{errors.telefono}</p>}
</div>
<div>
<Label htmlFor="notas">Notas (opcional)</Label>
<textarea
id="notas"
name="notas"
value={formData.notas}
onChange={handleChange}
rows={4}
placeholder="Alguna observación o preferencia..."
className="w-full px-4 py-3 border rounded-lg resize-none"
style={{ borderColor: 'var(--mocha-taupe)' }}
/>
</div>
{errors.submit && (
<div className="p-3 rounded-lg text-sm" style={{ background: '#fef2f2', color: '#ef4444' }}>
{errors.submit}
</div>
)}
<Button
type="submit"
disabled={pageLoading}
className="w-full"
style={{ background: 'var(--deep-earth)' }}
>
{pageLoading ? 'Procesando...' : 'Continuar al Pago'}
</Button>
<div className="text-sm" style={{ color: 'var(--charcoal-brown)', opacity: 0.6 }}>
* Al confirmar tu reserva, recibirás un correo de confirmación con los detalles.
</div>
</form>
)}
</CardContent>
</Card>
</div>
)}
</div>
</div>
)

View File

@@ -8,7 +8,12 @@ import { useAuth } from '@/lib/auth/context'
import { loadStripe } from '@stripe/stripe-js'
import { Elements } from '@stripe/react-stripe-js'
const stripePromise = loadStripe(process.env.NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY!)
const STRIPE_ENABLED = process.env.NEXT_PUBLIC_STRIPE_ENABLED === 'true'
const STRIPE_KEY = process.env.NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY
const stripePromise = STRIPE_ENABLED && STRIPE_KEY && !STRIPE_KEY.includes('your_stripe_')
? loadStripe(STRIPE_KEY)
: null
export default function BookingLayout({
children,
@@ -16,8 +21,9 @@ export default function BookingLayout({
children: ReactNode
}) {
const { user, signOut, loading } = useAuth()
return (
<Elements stripe={stripePromise}>
const content = (
<>
<header className="site-header booking-header">
<nav className="nav-primary">
<div className="logo">
@@ -72,6 +78,8 @@ export default function BookingLayout({
<main className="pt-24">
{children}
</main>
</Elements>
</>
)
return stripePromise ? <Elements stripe={stripePromise}>{content}</Elements> : content
}

View File

@@ -0,0 +1,285 @@
'use client'
import { useState } from 'react'
import { useRouter, useSearchParams } from 'next/navigation'
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { User, Mail, Phone, Calendar, Briefcase } from 'lucide-react'
const OCCUPATIONS = [
'Estudiante',
'Profesional',
'Empresario/a',
'Ama de casa',
'Artista',
'Comerciante',
'Profesor/a',
'Ingeniero/a',
'Médico/a',
'Abogado/a',
'Otro'
]
export default function RegisterPage() {
const router = useRouter()
const searchParams = useSearchParams()
const redirect = searchParams.get('redirect') || '/booking/cita'
const emailParam = searchParams.get('email') || ''
const phoneParam = searchParams.get('phone') || ''
const [formData, setFormData] = useState({
email: emailParam,
phone: phoneParam,
first_name: '',
last_name: '',
birthday: '',
occupation: ''
})
const [loading, setLoading] = useState(false)
const [errors, setErrors] = useState<Record<string, string>>({})
const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>) => {
const { name, value } = e.target
setFormData(prev => ({ ...prev, [name]: value }))
setErrors({ ...errors, [name]: '' })
}
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault()
setErrors({})
setLoading(true)
const validationErrors: Record<string, string> = {}
if (!formData.email.trim() || !formData.email.includes('@')) {
validationErrors.email = 'Email inválido'
}
if (!formData.phone.trim()) {
validationErrors.phone = 'Teléfono requerido'
}
if (!formData.first_name.trim()) {
validationErrors.first_name = 'Nombre requerido'
}
if (!formData.last_name.trim()) {
validationErrors.last_name = 'Apellido requerido'
}
if (!formData.birthday) {
validationErrors.birthday = 'Fecha de nacimiento requerida'
}
if (!formData.occupation) {
validationErrors.occupation = 'Ocupación requerida'
}
if (Object.keys(validationErrors).length > 0) {
setErrors(validationErrors)
setLoading(false)
return
}
try {
const response = await fetch('/api/customers', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(formData)
})
const data = await response.json()
if (response.ok && data.success) {
const params = new URLSearchParams({
customer_id: data.customer.id,
...Object.fromEntries(searchParams.entries())
})
router.push(`${redirect}?${params.toString()}`)
} else {
if (data.message === 'El cliente ya existe') {
const params = new URLSearchParams({
customer_id: data.customer.id,
...Object.fromEntries(searchParams.entries())
})
router.push(`${redirect}?${params.toString()}`)
} else {
setErrors({ submit: data.error || 'Error al registrar cliente' })
setLoading(false)
}
}
} catch (error) {
console.error('Error registrando cliente:', error)
setErrors({ submit: 'Error al registrar cliente' })
setLoading(false)
}
}
return (
<div className="min-h-screen bg-[var(--bone-white)] pt-24">
<div className="max-w-md mx-auto px-8 py-16">
<header className="mb-12 text-center">
<h1 className="text-4xl mb-4" style={{ color: 'var(--charcoal-brown)' }}>
Anchor:23
</h1>
<p className="text-lg opacity-80" style={{ color: 'var(--charcoal-brown)' }}>
Completa tu registro
</p>
</header>
<Card className="border-none" style={{ background: 'var(--soft-cream)' }}>
<CardHeader>
<CardTitle style={{ color: 'var(--charcoal-brown)' }}>
Registro de Cliente
</CardTitle>
<CardDescription>
Ingresa tus datos personales para completar tu reserva
</CardDescription>
</CardHeader>
<CardContent>
<form onSubmit={handleSubmit} className="space-y-6">
<div>
<Label htmlFor="email">Email *</Label>
<div className="relative">
<Mail className="absolute left-3 top-3 h-4 w-4 opacity-50" style={{ color: 'var(--mocha-taupe)' }} />
<Input
id="email"
name="email"
type="email"
value={formData.email}
onChange={handleChange}
className="pl-10"
style={{ borderColor: errors.email ? '#ef4444' : 'var(--mocha-taupe)' }}
placeholder="tu@email.com"
/>
</div>
{errors.email && <p className="text-sm mt-1" style={{ color: '#ef4444' }}>{errors.email}</p>}
</div>
<div>
<Label htmlFor="phone">Teléfono *</Label>
<div className="relative">
<Phone className="absolute left-3 top-3 h-4 w-4 opacity-50" style={{ color: 'var(--mocha-taupe)' }} />
<Input
id="phone"
name="phone"
type="tel"
value={formData.phone}
onChange={handleChange}
className="pl-10"
style={{ borderColor: errors.phone ? '#ef4444' : 'var(--mocha-taupe)' }}
placeholder="+52 844 123 4567"
/>
</div>
{errors.phone && <p className="text-sm mt-1" style={{ color: '#ef4444' }}>{errors.phone}</p>}
</div>
<div className="grid grid-cols-2 gap-4">
<div>
<Label htmlFor="first_name">Nombre *</Label>
<div className="relative">
<User className="absolute left-3 top-3 h-4 w-4 opacity-50" style={{ color: 'var(--mocha-taupe)' }} />
<Input
id="first_name"
name="first_name"
value={formData.first_name}
onChange={handleChange}
className="pl-10"
style={{ borderColor: errors.first_name ? '#ef4444' : 'var(--mocha-taupe)' }}
placeholder="María"
/>
</div>
{errors.first_name && <p className="text-sm mt-1" style={{ color: '#ef4444' }}>{errors.first_name}</p>}
</div>
<div>
<Label htmlFor="last_name">Apellido *</Label>
<Input
id="last_name"
name="last_name"
value={formData.last_name}
onChange={handleChange}
style={{ borderColor: errors.last_name ? '#ef4444' : 'var(--mocha-taupe)' }}
placeholder="García"
/>
{errors.last_name && <p className="text-sm mt-1" style={{ color: '#ef4444' }}>{errors.last_name}</p>}
</div>
</div>
<div>
<Label htmlFor="birthday">Fecha de Nacimiento *</Label>
<div className="relative">
<Calendar className="absolute left-3 top-3 h-4 w-4 opacity-50" style={{ color: 'var(--mocha-taupe)' }} />
<Input
id="birthday"
name="birthday"
type="date"
value={formData.birthday}
onChange={handleChange}
className="pl-10"
style={{ borderColor: errors.birthday ? '#ef4444' : 'var(--mocha-taupe)' }}
/>
</div>
{errors.birthday && <p className="text-sm mt-1" style={{ color: '#ef4444' }}>{errors.birthday}</p>}
</div>
<div>
<Label htmlFor="occupation">Ocupación *</Label>
<div className="relative">
<Briefcase className="absolute left-3 top-3 h-4 w-4 opacity-50" style={{ color: 'var(--mocha-taupe)' }} />
<select
id="occupation"
name="occupation"
value={formData.occupation}
onChange={handleChange}
className="w-full pl-10 pr-4 py-3 border rounded-lg appearance-none"
style={{ borderColor: errors.occupation ? '#ef4444' : 'var(--mocha-taupe)', background: 'var(--bone-white)' }}
>
<option value="">Selecciona tu ocupación</option>
{OCCUPATIONS.map(occ => (
<option key={occ} value={occ}>{occ}</option>
))}
</select>
</div>
{errors.occupation && <p className="text-sm mt-1" style={{ color: '#ef4444' }}>{errors.occupation}</p>}
</div>
{errors.submit && (
<div className="p-3 rounded-lg text-sm" style={{ background: '#fef2f2', color: '#ef4444' }}>
{errors.submit}
</div>
)}
<Button
type="submit"
disabled={loading}
className="w-full"
style={{ background: 'var(--deep-earth)' }}
>
{loading ? 'Procesando...' : 'Continuar con la Reserva'}
</Button>
<div className="text-sm" style={{ color: 'var(--charcoal-brown)', opacity: 0.6 }}>
* Al registrarte, aceptas nuestros términos y condiciones.
</div>
</form>
</CardContent>
</Card>
<div className="mt-8 text-center">
<Button
variant="outline"
onClick={() => router.back()}
style={{ borderColor: 'var(--mocha-taupe)', color: 'var(--charcoal-brown)' }}
>
Volver
</Button>
</div>
</div>
</div>
)
}

View File

@@ -5,14 +5,14 @@ import { Button } from '@/components/ui/button'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Label } from '@/components/ui/label'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { Calendar, Clock, User } from 'lucide-react'
import { format } from 'date-fns'
import { Calendar, Clock, User, Check } from 'lucide-react'
import { format, isSameDay, parseISO } from 'date-fns'
import { es } from 'date-fns/locale'
import DatePicker from '@/components/booking/date-picker'
interface Service {
id: string
name: string
category: string
duration_minutes: number
base_price: number
}
@@ -23,15 +23,19 @@ interface Location {
timezone: string
}
type BookingStep = 'service' | 'datetime' | 'confirm' | 'client'
export default function ServiciosPage() {
const [services, setServices] = useState<Service[]>([])
const [locations, setLocations] = useState<Location[]>([])
const [selectedService, setSelectedService] = useState<string>('')
const [selectedLocation, setSelectedLocation] = useState<string>('')
const [selectedDate, setSelectedDate] = useState<string>(format(new Date(), 'yyyy-MM-dd'))
const [selectedDate, setSelectedDate] = useState<Date | null>(new Date())
const [timeSlots, setTimeSlots] = useState<any[]>([])
const [selectedTime, setSelectedTime] = useState<string>('')
const [currentStep, setCurrentStep] = useState<BookingStep>('service')
const [loading, setLoading] = useState(false)
const [errors, setErrors] = useState<Record<string, string>>({})
useEffect(() => {
fetchServices()
@@ -53,6 +57,7 @@ export default function ServiciosPage() {
}
} catch (error) {
console.error('Error fetching services:', error)
setErrors({ ...errors, services: 'Error al cargar servicios' })
}
}
@@ -68,6 +73,7 @@ export default function ServiciosPage() {
}
} catch (error) {
console.error('Error fetching locations:', error)
setErrors({ ...errors, locations: 'Error al cargar ubicaciones' })
}
}
@@ -76,8 +82,9 @@ export default function ServiciosPage() {
setLoading(true)
try {
const formattedDate = format(selectedDate, 'yyyy-MM-dd')
const response = await fetch(
`/api/availability/time-slots?location_id=${selectedLocation}&service_id=${selectedService}&date=${selectedDate}`
`/api/availability/time-slots?location_id=${selectedLocation}&service_id=${selectedService}&date=${formattedDate}`
)
const data = await response.json()
if (data.availability) {
@@ -85,167 +92,281 @@ export default function ServiciosPage() {
}
} catch (error) {
console.error('Error fetching time slots:', error)
setErrors({ ...errors, timeSlots: 'Error al cargar horarios' })
} finally {
setLoading(false)
}
}
const handleContinue = () => {
if (selectedService && selectedLocation && selectedDate && selectedTime) {
const handleDateSelect = (date: Date) => {
setSelectedDate(date)
setSelectedTime('')
}
const canProceedToDateTime = () => {
return selectedService && selectedLocation
}
const canProceedToConfirm = () => {
return selectedService && selectedLocation && selectedDate && selectedTime
}
const handleProceed = () => {
setErrors({})
if (currentStep === 'service') {
if (!selectedService) {
setErrors({ service: 'Selecciona un servicio' })
return
}
if (!selectedLocation) {
setErrors({ location: 'Selecciona una ubicación' })
return
}
setCurrentStep('datetime')
} else if (currentStep === 'datetime') {
if (!selectedDate) {
setErrors({ date: 'Selecciona una fecha' })
return
}
if (!selectedTime) {
setErrors({ time: 'Selecciona un horario' })
return
}
setCurrentStep('confirm')
} else if (currentStep === 'confirm') {
const params = new URLSearchParams({
service_id: selectedService,
location_id: selectedLocation,
date: selectedDate,
date: format(selectedDate!, 'yyyy-MM-dd'),
time: selectedTime
})
window.location.href = `/cita?${params.toString()}`
window.location.href = `/booking/cita?${params.toString()}`
}
}
const handleStepBack = () => {
if (currentStep === 'datetime') {
setCurrentStep('service')
} else if (currentStep === 'confirm') {
setCurrentStep('datetime')
}
}
const selectedServiceData = services.find(s => s.id === selectedService)
const selectedLocationData = locations.find(l => l.id === selectedLocation)
return (
<div className="min-h-screen bg-[var(--bone-white)] pt-24">
<div className="max-w-4xl mx-auto px-8 py-16">
<header className="mb-12">
<h1 className="text-5xl mb-4" style={{ color: 'var(--charcoal-brown)' }}>
<div className="min-h-screen" style={{ background: 'var(--bone-white)' }}>
<div className="max-w-2xl mx-auto px-6 py-24">
<header className="mb-10">
<h1 className="text-4xl mb-3 font-serif" style={{ color: 'var(--charcoal-brown)' }}>
Reservar Cita
</h1>
<p className="text-xl opacity-80" style={{ color: 'var(--charcoal-brown)' }}>
<p className="text-lg" style={{ color: 'var(--charcoal-brown)', opacity: 0.75 }}>
Selecciona el servicio y horario de tu preferencia
</p>
</header>
<div className="space-y-8">
<Card className="border-none" style={{ background: 'var(--soft-cream)' }}>
<CardHeader>
<CardTitle className="flex items-center gap-2" style={{ color: 'var(--charcoal-brown)' }}>
<User className="w-5 h-5" />
Servicios
</CardTitle>
<CardDescription>Selecciona el servicio que deseas reservar</CardDescription>
</CardHeader>
<CardContent>
<div className="space-y-4">
<div>
<Label>Servicio</Label>
<Select onValueChange={setSelectedService} value={selectedService}>
<SelectTrigger className="w-full">
<SelectValue placeholder="Selecciona un servicio" />
</SelectTrigger>
<SelectContent>
{services.map((service) => (
<SelectItem key={service.id} value={service.id}>
{service.name} - ${service.base_price} ({service.duration_minutes} min)
</SelectItem>
))}
</SelectContent>
</Select>
</div>
</div>
</CardContent>
</Card>
<div className="space-y-6">
{currentStep === 'service' && (
<>
<Card style={{ background: 'var(--soft-cream)', borderColor: 'var(--mocha-taupe)', borderWidth: '1px' }}>
<CardHeader>
<CardTitle className="flex items-center gap-2" style={{ color: 'var(--charcoal-brown)' }}>
<User className="w-5 h-5" />
Servicios
</CardTitle>
<CardDescription style={{ color: 'var(--charcoal-brown)', opacity: 0.7 }}>
Selecciona el servicio que deseas reservar
</CardDescription>
</CardHeader>
<CardContent>
<div className="space-y-4">
<div>
<Label className="text-sm font-medium mb-2 block" style={{ color: 'var(--charcoal-brown)' }}>
Servicio
</Label>
<Select onValueChange={setSelectedService} value={selectedService}>
<SelectTrigger className="w-full">
<SelectValue placeholder="Selecciona un servicio" />
</SelectTrigger>
<SelectContent>
{services.map((service) => (
<SelectItem key={service.id} value={service.id}>
{service.name} - ${service.base_price.toFixed(2)} ({service.duration_minutes} min)
</SelectItem>
))}
</SelectContent>
</Select>
{errors.service && <p className="text-sm mt-2" style={{ color: '#ef4444' }}>{errors.service}</p>}
</div>
<Card className="border-none" style={{ background: 'var(--soft-cream)' }}>
<CardHeader>
<CardTitle className="flex items-center gap-2" style={{ color: 'var(--charcoal-brown)' }}>
<Clock className="w-5 h-5" />
Fecha y Hora
</CardTitle>
<CardDescription>Selecciona la fecha y hora disponible</CardDescription>
</CardHeader>
<CardContent>
<div className="space-y-4">
<div>
<Label>Ubicación</Label>
<Select onValueChange={setSelectedLocation} value={selectedLocation}>
<SelectTrigger className="w-full">
<SelectValue placeholder="Selecciona ubicación" />
</SelectTrigger>
<SelectContent>
{locations.map((location) => (
<SelectItem key={location.id} value={location.id}>
{location.name}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div>
<Label>Fecha</Label>
<input
type="date"
value={selectedDate}
onChange={(e) => setSelectedDate(e.target.value)}
min={format(new Date(), 'yyyy-MM-dd')}
className="w-full px-4 py-3 border rounded-lg"
style={{ borderColor: 'var(--mocha-taupe)' }}
/>
</div>
{selectedServiceData && (
<div>
<Label>Duración del servicio: {selectedServiceData.duration_minutes} minutos</Label>
<div>
<Label className="text-sm font-medium mb-2 block" style={{ color: 'var(--charcoal-brown)' }}>
Ubicación
</Label>
<Select onValueChange={setSelectedLocation} value={selectedLocation}>
<SelectTrigger className="w-full">
<SelectValue placeholder="Selecciona ubicación" />
</SelectTrigger>
<SelectContent>
{locations.map((location) => (
<SelectItem key={location.id} value={location.id}>
{location.name}
</SelectItem>
))}
</SelectContent>
</Select>
{errors.location && <p className="text-sm mt-2" style={{ color: '#ef4444' }}>{errors.location}</p>}
</div>
</div>
)}
{loading ? (
<div className="text-center py-4">
Cargando horarios...
</div>
) : (
<div>
<Label>Horarios disponibles</Label>
{timeSlots.length === 0 ? (
<p className="text-sm opacity-70 mt-2">
No hay horarios disponibles para esta fecha. Selecciona otra fecha.
</p>
) : (
<div className="grid grid-cols-3 gap-2 mt-2">
{timeSlots.map((slot, index) => (
<Button
key={index}
variant={selectedTime === slot.start_time ? 'default' : 'outline'}
onClick={() => setSelectedTime(slot.start_time)}
className={selectedTime === slot.start_time ? 'w-full' : ''}
>
{format(new Date(slot.start_time), 'HH:mm', { locale: es })}
</Button>
))}
</div>
)}
</div>
)}
</div>
</CardContent>
</Card>
{selectedServiceData && selectedTime && (
<Card className="border-none" style={{ background: 'var(--deep-earth)' }}>
<CardContent className="pt-6">
<div className="text-white">
<p className="text-lg font-semibold mb-2">Resumen de la reserva</p>
<div className="space-y-1 opacity-90">
<p>Servicio: {selectedServiceData.name}</p>
<p>Fecha: {format(new Date(selectedDate), 'PPP', { locale: es })}</p>
<p>Hora: {format(new Date(selectedTime), 'HH:mm', { locale: es })}</p>
<p>Precio: ${selectedServiceData.base_price.toFixed(2)}</p>
</div>
</div>
</CardContent>
</Card>
</CardContent>
</Card>
</>
)}
<Button
onClick={handleContinue}
disabled={!selectedService || !selectedLocation || !selectedDate || !selectedTime}
className="w-full"
>
Continuar con Datos del Cliente
</Button>
{currentStep === 'datetime' && (
<>
<Card style={{ background: 'var(--soft-cream)', borderColor: 'var(--mocha-taupe)', borderWidth: '1px' }}>
<CardHeader>
<CardTitle className="flex items-center gap-2" style={{ color: 'var(--charcoal-brown)' }}>
<Clock className="w-5 h-5" />
Fecha y Hora
</CardTitle>
<CardDescription style={{ color: 'var(--charcoal-brown)', opacity: 0.7 }}>
Selecciona la fecha y hora disponible
</CardDescription>
</CardHeader>
<CardContent className="space-y-6">
<div>
<Label className="text-sm font-medium mb-2 block" style={{ color: 'var(--charcoal-brown)' }}>
Fecha
</Label>
<DatePicker
selectedDate={selectedDate}
onDateSelect={handleDateSelect}
minDate={new Date()}
/>
{errors.date && <p className="text-sm mt-2" style={{ color: '#ef4444' }}>{errors.date}</p>}
</div>
{loading ? (
<div className="text-center py-8" style={{ color: 'var(--charcoal-brown)', opacity: 0.7 }}>
Cargando horarios...
</div>
) : (
<div>
<Label className="text-sm font-medium mb-2 block" style={{ color: 'var(--charcoal-brown)' }}>
Horarios disponibles
</Label>
{timeSlots.length === 0 ? (
<p className="text-sm" style={{ color: 'var(--charcoal-brown)', opacity: 0.7 }}>
No hay horarios disponibles para esta fecha. Selecciona otra fecha.
</p>
) : (
<div className="grid grid-cols-3 gap-2">
{timeSlots.map((slot, index) => {
const slotTime = new Date(slot.start_time)
return (
<Button
key={index}
variant={selectedTime === slot.start_time ? 'default' : 'outline'}
onClick={() => setSelectedTime(slot.start_time)}
className={selectedTime === slot.start_time ? 'w-full' : ''}
style={selectedTime === slot.start_time ? { background: 'var(--deep-earth)' } : {}}
>
{format(slotTime, 'HH:mm', { locale: es })}
</Button>
)
})}
</div>
)}
{errors.time && <p className="text-sm mt-2" style={{ color: '#ef4444' }}>{errors.time}</p>}
</div>
)}
</CardContent>
</Card>
{selectedServiceData && (
<div className="text-sm p-4 rounded-lg" style={{ background: 'var(--bone-white)', color: 'var(--charcoal-brown)', opacity: 0.7 }}>
Duración del servicio: {selectedServiceData.duration_minutes} minutos
</div>
)}
</>
)}
{currentStep === 'confirm' && selectedServiceData && selectedLocationData && selectedDate && selectedTime && (
<>
<Card style={{ background: 'var(--deep-earth)' }}>
<CardContent className="pt-6">
<div className="text-white space-y-3">
<h3 className="text-lg font-semibold mb-4">Resumen de la reserva</h3>
<div>
<p className="text-sm opacity-75">Servicio</p>
<p className="font-medium">{selectedServiceData.name}</p>
</div>
<div>
<p className="text-sm opacity-75">Ubicación</p>
<p className="font-medium">{selectedLocationData.name}</p>
</div>
<div>
<p className="text-sm opacity-75">Fecha</p>
<p className="font-medium">{format(selectedDate, 'PPP', { locale: es })}</p>
</div>
<div>
<p className="text-sm opacity-75">Hora</p>
<p className="font-medium">{format(parseISO(selectedTime), 'HH:mm', { locale: es })}</p>
</div>
<div>
<p className="text-sm opacity-75">Duración</p>
<p className="font-medium">{selectedServiceData.duration_minutes} minutos</p>
</div>
<div>
<p className="text-sm opacity-75">Precio</p>
<p className="font-medium text-xl">${selectedServiceData.base_price.toFixed(2)} USD</p>
</div>
</div>
</CardContent>
</Card>
</>
)}
{currentStep === 'confirm' && (
<Button
onClick={handleProceed}
className="w-full text-lg py-6"
style={{ background: 'var(--deep-earth)' }}
>
Confirmar cita
</Button>
)}
{currentStep !== 'confirm' && (
<>
<Button
onClick={handleProceed}
disabled={currentStep === 'service' ? !canProceedToDateTime() : !canProceedToConfirm()}
className="w-full text-lg py-6"
style={{ background: 'var(--deep-earth)', opacity: (currentStep === 'service' ? !canProceedToDateTime() : !canProceedToConfirm()) ? 0.5 : 1 }}
>
{currentStep === 'service' ? 'Continuar: Seleccionar fecha y hora' : 'Continuar: Confirmar cita'}
</Button>
{currentStep !== 'service' && (
<Button
variant="outline"
onClick={handleStepBack}
className="w-full"
style={{ borderColor: 'var(--mocha-taupe)', color: 'var(--charcoal-brown)' }}
>
Atrás
</Button>
)}
</>
)}
</div>
</div>
</div>
)
}
}

View File

@@ -272,4 +272,38 @@
color: var(--charcoal-brown);
opacity: 0.8;
}
.select-content {
background: var(--bone-white);
border: 1px solid var(--mocha-taupe);
}
.select-item {
color: var(--charcoal-brown);
transition: background 0.15s;
}
.select-item:hover,
.select-item[data-highlighted] {
background: var(--soft-cream);
}
.select-item[data-state="checked"] {
background: var(--soft-cream);
font-weight: 500;
}
.select-trigger {
background: var(--bone-white);
border: 1px solid var(--mocha-taupe);
color: var(--charcoal-brown);
}
.select-trigger:hover {
border-color: var(--deep-earth);
}
.select-trigger[data-state="open"] {
border-color: var(--deep-earth);
}
}