mirror of
https://github.com/marcogll/AnchorOS.git
synced 2026-03-15 13:24:27 +00:00
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:
75
STRIPE_SETUP.md
Normal file
75
STRIPE_SETUP.md
Normal file
@@ -0,0 +1,75 @@
|
||||
# Stripe Payment Integration
|
||||
|
||||
## Current Status
|
||||
Stripe is currently **DISABLED** using mock payment mode for testing.
|
||||
|
||||
## To Enable Real Stripe Payments
|
||||
|
||||
### 1. Update Environment Variables
|
||||
|
||||
In `.env.local`:
|
||||
|
||||
```bash
|
||||
NEXT_PUBLIC_STRIPE_ENABLED=true
|
||||
STRIPE_SECRET_KEY=sk_test_your_real_stripe_secret_key
|
||||
STRIPE_PUBLISHABLE_KEY=pk_test_your_real_stripe_publishable_key
|
||||
STRIPE_WEBHOOK_SECRET=whsec_your_real_webhook_secret
|
||||
```
|
||||
|
||||
### 2. Replace Mock Payment with Real Stripe
|
||||
|
||||
In `app/booking/cita/page.tsx`:
|
||||
|
||||
Replace the `MockPaymentForm` component usage with real Stripe integration:
|
||||
|
||||
```tsx
|
||||
import { useStripe, useElements, CardElement } from '@stripe/react-stripe-js'
|
||||
|
||||
// Replace the mock payment section with:
|
||||
<CardElement
|
||||
options={{
|
||||
style: {
|
||||
base: {
|
||||
fontSize: '16px',
|
||||
color: 'var(--charcoal-brown)',
|
||||
'::placeholder': {
|
||||
color: 'var(--mocha-taupe)',
|
||||
},
|
||||
},
|
||||
},
|
||||
}}
|
||||
/>
|
||||
```
|
||||
|
||||
### 3. Update Payment Handling
|
||||
|
||||
Replace the `handleMockPayment` function with real Stripe confirmation:
|
||||
|
||||
```tsx
|
||||
const handlePayment = async () => {
|
||||
if (!stripe || !elements) return
|
||||
|
||||
const { error, paymentIntent } = await stripe.confirmCardPayment(
|
||||
paymentIntent.clientSecret,
|
||||
{
|
||||
payment_method: {
|
||||
card: elements.getElement(CardElement)!,
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
if (error) {
|
||||
// Handle error
|
||||
} else {
|
||||
// Payment succeeded, create booking
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 4. Update Create Payment Intent API
|
||||
|
||||
Ensure `/api/create-payment-intent` uses your real Stripe secret key.
|
||||
|
||||
## Mock Payment Mode
|
||||
|
||||
Currently using `components/booking/mock-payment-form.tsx` for testing without real payments. This validates card formatting and simulates payment flow.
|
||||
@@ -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')
|
||||
|
||||
@@ -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')
|
||||
|
||||
@@ -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')
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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')
|
||||
|
||||
@@ -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')
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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
120
app/api/customers/route.ts
Normal 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 }
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -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'
|
||||
|
||||
/**
|
||||
|
||||
@@ -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')
|
||||
|
||||
@@ -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')
|
||||
|
||||
@@ -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')
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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>
|
||||
)
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
285
app/booking/registro/page.tsx
Normal file
285
app/booking/registro/page.tsx
Normal 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>
|
||||
)
|
||||
}
|
||||
@@ -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,165 +92,279 @@ 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>
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
105
components/booking/date-picker.tsx
Normal file
105
components/booking/date-picker.tsx
Normal file
@@ -0,0 +1,105 @@
|
||||
import { useState } from 'react'
|
||||
import { format, startOfMonth, endOfMonth, eachDayOfInterval, isSameMonth, isSameDay, isToday, addMonths, subMonths } from 'date-fns'
|
||||
import { es } from 'date-fns/locale'
|
||||
import { ChevronLeft, ChevronRight } from 'lucide-react'
|
||||
|
||||
interface DatePickerProps {
|
||||
selectedDate: Date | null
|
||||
onDateSelect: (date: Date) => void
|
||||
minDate?: Date
|
||||
disabled?: boolean
|
||||
}
|
||||
|
||||
export default function DatePicker({ selectedDate, onDateSelect, minDate, disabled }: DatePickerProps) {
|
||||
const [currentMonth, setCurrentMonth] = useState(selectedDate ? new Date(selectedDate) : new Date())
|
||||
|
||||
const days = eachDayOfInterval({
|
||||
start: startOfMonth(currentMonth),
|
||||
end: endOfMonth(currentMonth)
|
||||
})
|
||||
|
||||
const previousMonth = () => setCurrentMonth(subMonths(currentMonth, 1))
|
||||
const nextMonth = () => setCurrentMonth(addMonths(currentMonth, 1))
|
||||
|
||||
const isDateDisabled = (date: Date) => {
|
||||
if (minDate) {
|
||||
return date < minDate
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
const isDateSelected = (date: Date) => {
|
||||
return selectedDate && isSameDay(date, selectedDate)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="w-full">
|
||||
<div className="flex items-center justify-between mb-4">
|
||||
<button
|
||||
type="button"
|
||||
onClick={previousMonth}
|
||||
disabled={disabled}
|
||||
className="p-2 hover:bg-[var(--mocha-taupe)]/10 rounded-md transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
|
||||
>
|
||||
<ChevronLeft className="w-5 h-5" style={{ color: 'var(--charcoal-brown)' }} />
|
||||
</button>
|
||||
<h3 className="text-lg font-medium" style={{ color: 'var(--charcoal-brown)' }}>
|
||||
{format(currentMonth, 'MMMM yyyy', { locale: es })}
|
||||
</h3>
|
||||
<button
|
||||
type="button"
|
||||
onClick={nextMonth}
|
||||
disabled={disabled}
|
||||
className="p-2 hover:bg-[var(--mocha-taupe)]/10 rounded-md transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
|
||||
>
|
||||
<ChevronRight className="w-5 h-5" style={{ color: 'var(--charcoal-brown)' }} />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-7 gap-1 mb-2">
|
||||
{['L', 'M', 'X', 'J', 'V', 'S', 'D'].map((day, index) => (
|
||||
<div
|
||||
key={index}
|
||||
className="text-center text-sm font-medium py-2"
|
||||
style={{ color: 'var(--mocha-taupe)' }}
|
||||
>
|
||||
{day}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-7 gap-1">
|
||||
{days.map((date, index) => {
|
||||
const disabled = isDateDisabled(date)
|
||||
const selected = isDateSelected(date)
|
||||
const today = isToday(date)
|
||||
const notCurrentMonth = !isSameMonth(date, currentMonth)
|
||||
|
||||
return (
|
||||
<button
|
||||
key={index}
|
||||
type="button"
|
||||
onClick={() => !disabled && !notCurrentMonth && onDateSelect(date)}
|
||||
disabled={disabled || notCurrentMonth}
|
||||
className={`
|
||||
relative p-2 text-sm font-medium rounded-md transition-all
|
||||
${disabled || notCurrentMonth ? 'opacity-30 cursor-not-allowed' : 'cursor-pointer hover:bg-[var(--mocha-taupe)]/10'}
|
||||
${selected ? 'text-white' : ''}
|
||||
${today && !selected ? 'font-bold' : ''}
|
||||
`}
|
||||
style={selected ? { background: 'var(--deep-earth)' } : { color: 'var(--charcoal-brown)' }}
|
||||
>
|
||||
{format(date, 'd')}
|
||||
{today && !selected && (
|
||||
<span
|
||||
className="absolute bottom-1 left-1/2 transform -translate-x-1/2 w-1 h-1 rounded-full"
|
||||
style={{ background: 'var(--deep-earth)' }}
|
||||
/>
|
||||
)}
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
210
components/booking/mock-payment-form.tsx
Normal file
210
components/booking/mock-payment-form.tsx
Normal file
@@ -0,0 +1,210 @@
|
||||
import { useState } from 'react'
|
||||
import { CreditCard, Lock } from 'lucide-react'
|
||||
|
||||
interface MockPaymentFormProps {
|
||||
amount: number
|
||||
onSubmit: (paymentMethod: any) => Promise<void>
|
||||
disabled?: boolean
|
||||
}
|
||||
|
||||
export default function MockPaymentForm({ amount, onSubmit, disabled }: MockPaymentFormProps) {
|
||||
const [cardNumber, setCardNumber] = useState('')
|
||||
const [expiry, setExpiry] = useState('')
|
||||
const [cvc, setCvc] = useState('')
|
||||
const [name, setName] = useState('')
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [errors, setErrors] = useState<Record<string, string>>({})
|
||||
|
||||
const formatCardNumber = (value: string) => {
|
||||
const v = value.replace(/\s+/g, '').replace(/[^0-9]/gi, '')
|
||||
const matches = v.match(/\d{4,16}/g)
|
||||
const match = (matches && matches[0]) || ''
|
||||
const parts = []
|
||||
|
||||
for (let i = 0, len = match.length; i < len; i += 4) {
|
||||
parts.push(match.substring(i, i + 4))
|
||||
}
|
||||
|
||||
if (parts.length) {
|
||||
return parts.join(' ')
|
||||
} else {
|
||||
return v
|
||||
}
|
||||
}
|
||||
|
||||
const formatExpiry = (value: string) => {
|
||||
const v = value.replace(/\s+/g, '').replace(/[^0-9]/gi, '')
|
||||
if (v.length >= 2) {
|
||||
return v.substring(0, 2) + '/' + v.substring(2, 4)
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
const validate = () => {
|
||||
const newErrors: Record<string, string> = {}
|
||||
|
||||
if (cardNumber.length < 19) {
|
||||
newErrors.cardNumber = 'Número de tarjeta inválido'
|
||||
}
|
||||
|
||||
if (expiry.length < 5) {
|
||||
newErrors.expiry = 'Fecha de expiración inválida'
|
||||
}
|
||||
|
||||
if (cvc.length < 3) {
|
||||
newErrors.cvc = 'CVC inválido'
|
||||
}
|
||||
|
||||
if (!name.trim()) {
|
||||
newErrors.name = 'Nombre requerido'
|
||||
}
|
||||
|
||||
setErrors(newErrors)
|
||||
return Object.keys(newErrors).length === 0
|
||||
}
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault()
|
||||
|
||||
if (!validate()) return
|
||||
|
||||
setLoading(true)
|
||||
try {
|
||||
await onSubmit({
|
||||
cardNumber: cardNumber.replace(/\s/g, ''),
|
||||
expiry,
|
||||
cvc,
|
||||
name,
|
||||
type: 'card'
|
||||
})
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleCardNumberChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const formatted = formatCardNumber(e.target.value)
|
||||
if (formatted.length <= 19) {
|
||||
setCardNumber(formatted)
|
||||
}
|
||||
}
|
||||
|
||||
const handleExpiryChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const formatted = formatExpiry(e.target.value)
|
||||
if (formatted.length <= 5) {
|
||||
setExpiry(formatted)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="p-6 rounded-xl" style={{ background: 'var(--bone-white)' }}>
|
||||
<div className="flex items-center gap-2 mb-4">
|
||||
<Lock className="w-4 h-4" style={{ color: 'var(--mocha-taupe)' }} />
|
||||
<span className="text-sm font-medium" style={{ color: 'var(--charcoal-brown)' }}>
|
||||
Pago Seguro (Demo Mode)
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
<div>
|
||||
<label className="block text-sm font-medium mb-2" style={{ color: 'var(--charcoal-brown)' }}>
|
||||
Número de Tarjeta
|
||||
</label>
|
||||
<div className="relative">
|
||||
<input
|
||||
type="text"
|
||||
value={cardNumber}
|
||||
onChange={handleCardNumberChange}
|
||||
placeholder="1234 5678 9012 3456"
|
||||
disabled={disabled || loading}
|
||||
className="w-full px-4 py-3 border rounded-lg pr-12"
|
||||
style={{ borderColor: errors.cardNumber ? '#ef4444' : 'var(--mocha-taupe)' }}
|
||||
/>
|
||||
<CreditCard className="absolute right-3 top-1/2 transform -translate-y-1/2 w-5 h-5" style={{ color: 'var(--mocha-taupe)' }} />
|
||||
</div>
|
||||
{errors.cardNumber && <p className="text-sm mt-1" style={{ color: '#ef4444' }}>{errors.cardNumber}</p>}
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div>
|
||||
<label className="block text-sm font-medium mb-2" style={{ color: 'var(--charcoal-brown)' }}>
|
||||
Expiración (MM/AA)
|
||||
</label>
|
||||
<input
|
||||
type="text"
|
||||
value={expiry}
|
||||
onChange={handleExpiryChange}
|
||||
placeholder="12/28"
|
||||
disabled={disabled || loading}
|
||||
className="w-full px-4 py-3 border rounded-lg"
|
||||
style={{ borderColor: errors.expiry ? '#ef4444' : 'var(--mocha-taupe)' }}
|
||||
/>
|
||||
{errors.expiry && <p className="text-sm mt-1" style={{ color: '#ef4444' }}>{errors.expiry}</p>}
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="block text-sm font-medium mb-2" style={{ color: 'var(--charcoal-brown)' }}>
|
||||
CVC
|
||||
</label>
|
||||
<input
|
||||
type="text"
|
||||
value={cvc}
|
||||
onChange={(e) => setCvc(e.target.value.replace(/[^0-9]/g, ''))}
|
||||
placeholder="123"
|
||||
disabled={disabled || loading}
|
||||
className="w-full px-4 py-3 border rounded-lg"
|
||||
style={{ borderColor: errors.cvc ? '#ef4444' : 'var(--mocha-taupe)' }}
|
||||
/>
|
||||
{errors.cvc && <p className="text-sm mt-1" style={{ color: '#ef4444' }}>{errors.cvc}</p>}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="block text-sm font-medium mb-2" style={{ color: 'var(--charcoal-brown)' }}>
|
||||
Nombre en la tarjeta
|
||||
</label>
|
||||
<input
|
||||
type="text"
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
placeholder="MARÍA GARCÍA"
|
||||
disabled={disabled || loading}
|
||||
className="w-full px-4 py-3 border rounded-lg uppercase"
|
||||
style={{ borderColor: errors.name ? '#ef4444' : 'var(--mocha-taupe)' }}
|
||||
/>
|
||||
{errors.name && <p className="text-sm mt-1" style={{ color: '#ef4444' }}>{errors.name}</p>}
|
||||
</div>
|
||||
|
||||
<div className="pt-2">
|
||||
<div className="flex items-center justify-between mb-4">
|
||||
<span className="text-sm" style={{ color: 'var(--charcoal-brown)', opacity: 0.7 }}>
|
||||
Total a pagar
|
||||
</span>
|
||||
<span className="text-2xl font-semibold" style={{ color: 'var(--charcoal-brown)' }}>
|
||||
${amount.toFixed(2)} USD
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<button
|
||||
type="submit"
|
||||
disabled={disabled || loading}
|
||||
className="w-full px-6 py-4 rounded-lg font-medium text-white transition-all disabled:opacity-50 disabled:cursor-not-allowed"
|
||||
style={{ background: 'var(--deep-earth)' }}
|
||||
>
|
||||
{loading ? 'Procesando...' : 'Pagar y Confirmar Reserva'}
|
||||
</button>
|
||||
|
||||
<div className="mt-4 p-3 rounded-lg" style={{ background: 'rgba(111, 94, 79, 0.1)', border: '1px solid var(--mocha-taupe)' }}>
|
||||
<p className="text-xs text-center" style={{ color: 'var(--charcoal-brown)', opacity: 0.8 }}>
|
||||
<Lock className="inline w-3 h-3 mr-1" />
|
||||
<span className="font-medium">Modo de prueba:</span> Este es un formulario de demostración. No se procesará ningún pago real.
|
||||
</p>
|
||||
<p className="text-xs text-center mt-1" style={{ color: 'var(--charcoal-brown)', opacity: 0.6 }}>
|
||||
Consulta STRIPE_SETUP.md para activar pagos reales
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -20,14 +20,14 @@ const SelectTrigger = React.forwardRef<
|
||||
<SelectPrimitive.Trigger
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"flex h-10 w-full items-center justify-between rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1",
|
||||
"select-trigger flex h-10 w-full items-center justify-between rounded-md border px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
<SelectPrimitive.Icon asChild>
|
||||
<ChevronDown className="h-4 w-4 opacity-50" />
|
||||
<ChevronDown className="h-4 w-4 opacity-50" style={{ color: 'var(--charcoal-brown)' }} />
|
||||
</SelectPrimitive.Icon>
|
||||
</SelectPrimitive.Trigger>
|
||||
))
|
||||
@@ -46,6 +46,7 @@ const SelectScrollUpButton = React.forwardRef<
|
||||
"flex cursor-default items-center justify-center py-1",
|
||||
className
|
||||
)}
|
||||
style={{ color: 'var(--charcoal-brown)' }}
|
||||
{...props}
|
||||
>
|
||||
<ChevronUp className="h-4 w-4" />
|
||||
@@ -66,6 +67,7 @@ const SelectScrollDownButton = React.forwardRef<
|
||||
"flex cursor-default items-center justify-center py-1",
|
||||
className
|
||||
)}
|
||||
style={{ color: 'var(--charcoal-brown)' }}
|
||||
{...props}
|
||||
>
|
||||
<ChevronDown className="h-4 w-4" />
|
||||
@@ -84,7 +86,7 @@ const SelectContent = React.forwardRef<
|
||||
<SelectPrimitive.Content
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
|
||||
"select-content relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-md shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
|
||||
position === "popper" &&
|
||||
"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",
|
||||
className
|
||||
@@ -133,14 +135,14 @@ const SelectItem = React.forwardRef<
|
||||
<SelectPrimitive.Item
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
|
||||
"select-item relative flex w-full cursor-default select-none items-center rounded-sm py-2 pl-8 pr-2 text-sm outline-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
|
||||
<SelectPrimitive.ItemIndicator>
|
||||
<Check className="h-4 w-4" />
|
||||
<Check className="h-4 w-4" style={{ color: 'var(--deep-earth)' }} />
|
||||
</SelectPrimitive.ItemIndicator>
|
||||
</span>
|
||||
|
||||
@@ -158,7 +160,8 @@ const SelectSeparator = React.forwardRef<
|
||||
>(({ className, ...props }, ref) => (
|
||||
<SelectPrimitive.Separator
|
||||
ref={ref}
|
||||
className={cn("-mx-1 my-1 h-px bg-muted", className)}
|
||||
className={cn("-mx-1 my-1 h-px", className)}
|
||||
style={{ background: 'var(--mocha-taupe)', opacity: 0.3 }}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
|
||||
@@ -8,6 +8,22 @@ export type InvitationStatus = 'pending' | 'used' | 'expired'
|
||||
export type ResourceType = 'station' | 'room' | 'equipment'
|
||||
export type AuditAction = 'create' | 'update' | 'delete' | 'reset_invitations' | 'payment' | 'status_change'
|
||||
|
||||
export interface DayHours {
|
||||
open: string
|
||||
close: string
|
||||
is_closed: boolean
|
||||
}
|
||||
|
||||
export interface BusinessHours {
|
||||
monday: DayHours
|
||||
tuesday: DayHours
|
||||
wednesday: DayHours
|
||||
thursday: DayHours
|
||||
friday: DayHours
|
||||
saturday: DayHours
|
||||
sunday: DayHours
|
||||
}
|
||||
|
||||
/** Represents a salon location with timezone and contact info */
|
||||
export interface Location {
|
||||
id: string
|
||||
@@ -16,6 +32,7 @@ export interface Location {
|
||||
address?: string
|
||||
phone?: string
|
||||
is_active: boolean
|
||||
business_hours?: BusinessHours
|
||||
created_at: string
|
||||
updated_at: string
|
||||
}
|
||||
@@ -151,8 +168,8 @@ export type Database = {
|
||||
Tables: {
|
||||
locations: {
|
||||
Row: Location
|
||||
Insert: Omit<Location, 'id' | 'created_at' | 'updated_at'>
|
||||
Update: Partial<Omit<Location, 'id' | 'created_at'>>
|
||||
Insert: Omit<Location, 'id' | 'created_at' | 'updated_at'> & { business_hours?: BusinessHours }
|
||||
Update: Partial<Omit<Location, 'id' | 'created_at'> & { business_hours?: BusinessHours }>
|
||||
}
|
||||
resources: {
|
||||
Row: Resource
|
||||
|
||||
16
lib/supabase/admin.ts
Normal file
16
lib/supabase/admin.ts
Normal file
@@ -0,0 +1,16 @@
|
||||
import { createClient } from '@supabase/supabase-js'
|
||||
|
||||
const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL!
|
||||
const supabaseServiceRoleKey = process.env.SUPABASE_SERVICE_ROLE_KEY!
|
||||
|
||||
// Admin Supabase client for server-side operations with service role
|
||||
export const supabaseAdmin = createClient(
|
||||
supabaseUrl,
|
||||
supabaseServiceRoleKey,
|
||||
{
|
||||
auth: {
|
||||
autoRefreshToken: false,
|
||||
persistSession: false
|
||||
}
|
||||
}
|
||||
)
|
||||
@@ -6,16 +6,4 @@ const supabaseAnonKey = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!
|
||||
// Public Supabase client for client-side operations
|
||||
export const supabase = createClient(supabaseUrl, supabaseAnonKey)
|
||||
|
||||
// Admin Supabase client for server-side operations with service role
|
||||
export const supabaseAdmin = createClient(
|
||||
supabaseUrl,
|
||||
process.env.SUPABASE_SERVICE_ROLE_KEY!,
|
||||
{
|
||||
auth: {
|
||||
autoRefreshToken: false,
|
||||
persistSession: false
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
export default supabase
|
||||
|
||||
84
lib/utils/business-hours.ts
Normal file
84
lib/utils/business-hours.ts
Normal file
@@ -0,0 +1,84 @@
|
||||
import type { BusinessHours, DayHours } from '@/lib/db/types'
|
||||
|
||||
const DAYS = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday'] as const
|
||||
type DayOfWeek = typeof DAYS[number]
|
||||
|
||||
export function getDayOfWeek(date: Date): DayOfWeek {
|
||||
return DAYS[date.getDay()]
|
||||
}
|
||||
|
||||
export function isOpenNow(businessHours: BusinessHours, date = new Date): boolean {
|
||||
const day = getDayOfWeek(date)
|
||||
const hours = businessHours[day]
|
||||
|
||||
if (!hours || hours.is_closed) {
|
||||
return false
|
||||
}
|
||||
|
||||
const now = date
|
||||
const [openHour, openMinute] = hours.open.split(':').map(Number)
|
||||
const [closeHour, closeMinute] = hours.close.split(':').map(Number)
|
||||
|
||||
const openTime = new Date(now)
|
||||
openTime.setHours(openHour, openMinute, 0, 0)
|
||||
|
||||
const closeTime = new Date(now)
|
||||
closeTime.setHours(closeHour, closeMinute, 0, 0)
|
||||
|
||||
return now >= openTime && now < closeTime
|
||||
}
|
||||
|
||||
export function getNextOpenTime(businessHours: BusinessHours, from = new Date): Date | null {
|
||||
const checkDate = new Date(from)
|
||||
|
||||
for (let i = 0; i < 7; i++) {
|
||||
const day = getDayOfWeek(checkDate)
|
||||
const hours = businessHours[day]
|
||||
|
||||
if (hours && !hours.is_closed) {
|
||||
const [openHour, openMinute] = hours.open.split(':').map(Number)
|
||||
|
||||
const openTime = new Date(checkDate)
|
||||
openTime.setHours(openHour, openMinute, 0, 0)
|
||||
|
||||
if (openTime > from) {
|
||||
return openTime
|
||||
}
|
||||
|
||||
openTime.setDate(openTime.getDate() + 1)
|
||||
return openTime
|
||||
}
|
||||
|
||||
checkDate.setDate(checkDate.getDate() + 1)
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
export function isTimeWithinHours(time: string, dayHours: DayHours): boolean {
|
||||
if (dayHours.is_closed) {
|
||||
return false
|
||||
}
|
||||
|
||||
const [hour, minute] = time.split(':').map(Number)
|
||||
const checkMinutes = hour * 60 + minute
|
||||
|
||||
const [openHour, openMinute] = dayHours.open.split(':').map(Number)
|
||||
const [closeHour, closeMinute] = dayHours.close.split(':').map(Number)
|
||||
const openMinutes = openHour * 60 + openMinute
|
||||
const closeMinutes = closeHour * 60 + closeMinute
|
||||
|
||||
return checkMinutes >= openMinutes && checkMinutes < closeMinutes
|
||||
}
|
||||
|
||||
export function getBusinessHoursString(dayHours: DayHours): string {
|
||||
if (dayHours.is_closed) {
|
||||
return 'Cerrado'
|
||||
}
|
||||
return `${dayHours.open} - ${dayHours.close}`
|
||||
}
|
||||
|
||||
export function getTodayHours(businessHours: BusinessHours): string {
|
||||
const day = getDayOfWeek(new Date())
|
||||
return getBusinessHoursString(businessHours[day])
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import { supabaseAdmin } from '@/lib/supabase/client'
|
||||
import { supabaseAdmin } from '@/lib/supabase/admin'
|
||||
|
||||
/**
|
||||
* generateShortId function that generates a unique short ID using Supabase RPC.
|
||||
|
||||
33
scripts/add_business_hours.sql
Normal file
33
scripts/add_business_hours.sql
Normal file
@@ -0,0 +1,33 @@
|
||||
-- Ejecutar este SQL en Supabase Dashboard: Database > SQL Editor
|
||||
-- Agrega horarios de atención a la tabla locations
|
||||
|
||||
-- Agregar columna business_hours
|
||||
ALTER TABLE locations
|
||||
ADD COLUMN IF NOT EXISTS business_hours JSONB DEFAULT '{
|
||||
"monday": {"open": "10:00", "close": "19:00", "is_closed": false},
|
||||
"tuesday": {"open": "10:00", "close": "19:00", "is_closed": false},
|
||||
"wednesday": {"open": "10:00", "close": "19:00", "is_closed": false},
|
||||
"thursday": {"open": "10:00", "close": "19:00", "is_closed": false},
|
||||
"friday": {"open": "10:00", "close": "19:00", "is_closed": false},
|
||||
"saturday": {"open": "10:00", "close": "18:00", "is_closed": false},
|
||||
"sunday": {"is_closed": true}
|
||||
}'::jsonb;
|
||||
|
||||
-- Agregar comentario
|
||||
COMMENT ON COLUMN locations.business_hours IS 'Horarios de atención por día. Formato JSONB con claves: monday-sunday, cada una con open/close en formato HH:MM e is_closed boolean';
|
||||
|
||||
-- Actualizar locations existentes con horarios por defecto
|
||||
UPDATE locations
|
||||
SET business_hours = '{
|
||||
"monday": {"open": "10:00", "close": "19:00", "is_closed": false},
|
||||
"tuesday": {"open": "10:00", "close": "19:00", "is_closed": false},
|
||||
"wednesday": {"open": "10:00", "close": "19:00", "is_closed": false},
|
||||
"thursday": {"open": "10:00", "close": "19:00", "is_closed": false},
|
||||
"friday": {"open": "10:00", "close": "19:00", "is_closed": false},
|
||||
"saturday": {"open": "10:00", "close": "18:00", "is_closed": false},
|
||||
"sunday": {"is_closed": true}
|
||||
}'::jsonb
|
||||
WHERE business_hours IS NULL OR business_hours = '{}'::jsonb;
|
||||
|
||||
-- Verificar resultados
|
||||
SELECT id, name, business_hours FROM locations;
|
||||
41
scripts/debug_business_hours.sql
Normal file
41
scripts/debug_business_hours.sql
Normal file
@@ -0,0 +1,41 @@
|
||||
-- Debug and fix business_hours JSONB extraction
|
||||
-- Execute in Supabase Dashboard: Database > SQL Editor
|
||||
|
||||
-- First, check what's actually stored in business_hours
|
||||
SELECT
|
||||
id,
|
||||
name,
|
||||
business_hours,
|
||||
business_hours->>'monday' as monday_raw,
|
||||
business_hours->'monday' as monday_object
|
||||
FROM locations
|
||||
LIMIT 1;
|
||||
|
||||
-- Test extraction logic
|
||||
SELECT
|
||||
'2026-01-20'::DATE as test_date,
|
||||
EXTRACT(DOW FROM '2026-01-20'::DATE) as day_of_week_number,
|
||||
ARRAY['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday'][EXTRACT(DOW FROM '2026-01-20'::DATE) + 1] as day_name;
|
||||
|
||||
-- Fix: Ensure business_hours is properly formatted
|
||||
UPDATE locations
|
||||
SET business_hours = '{
|
||||
"monday": {"open": "10:00", "close": "19:00", "is_closed": false},
|
||||
"tuesday": {"open": "10:00", "close": "19:00", "is_closed": false},
|
||||
"wednesday": {"open": "10:00", "close": "19:00", "is_closed": false},
|
||||
"thursday": {"open": "10:00", "close": "19:00", "is_closed": false},
|
||||
"friday": {"open": "10:00", "close": "19:00", "is_closed": false},
|
||||
"saturday": {"open": "10:00", "close": "18:00", "is_closed": false},
|
||||
"sunday": {"is_closed": true}
|
||||
}'::jsonb
|
||||
WHERE business_hours IS NULL OR business_hours = '{}'::jsonb;
|
||||
|
||||
-- Verify the update
|
||||
SELECT
|
||||
id,
|
||||
name,
|
||||
business_hours->>'monday' as monday,
|
||||
(business_hours->'monday'->>'open')::TIME as monday_open,
|
||||
(business_hours->'monday'->>'close')::TIME as monday_close
|
||||
FROM locations
|
||||
LIMIT 1;
|
||||
81
scripts/seed_booking_data.sql
Normal file
81
scripts/seed_booking_data.sql
Normal file
@@ -0,0 +1,81 @@
|
||||
-- Seed data for testing booking flow
|
||||
-- Execute in Supabase Dashboard: Database > SQL Editor
|
||||
|
||||
-- Get active locations
|
||||
DO $$
|
||||
DECLARE
|
||||
v_location_id UUID;
|
||||
v_staff_id UUID;
|
||||
v_resource_id UUID;
|
||||
v_service_id UUID;
|
||||
BEGIN
|
||||
-- Get first active location
|
||||
SELECT id INTO v_location_id FROM locations WHERE is_active = true LIMIT 1;
|
||||
|
||||
IF v_location_id IS NULL THEN
|
||||
RAISE NOTICE 'No active locations found';
|
||||
RETURN;
|
||||
END IF;
|
||||
|
||||
RAISE NOTICE 'Using location: %', v_location_id;
|
||||
|
||||
-- Insert sample staff if none exists
|
||||
INSERT INTO staff (user_id, location_id, role, display_name, phone, is_active, is_available_for_booking, work_hours_start, work_hours_end, work_days)
|
||||
SELECT
|
||||
gen_random_uuid(),
|
||||
v_location_id,
|
||||
'artist',
|
||||
'Artista Demo',
|
||||
'+52 844 123 4567',
|
||||
true,
|
||||
true,
|
||||
'10:00'::TIME,
|
||||
'19:00'::TIME,
|
||||
'MON,TUE,WED,THU,FRI,SAT'
|
||||
WHERE NOT EXISTS (SELECT 1 FROM staff WHERE display_name = 'Artista Demo' AND location_id = v_location_id)
|
||||
RETURNING id INTO v_staff_id;
|
||||
|
||||
IF v_staff_id IS NOT NULL THEN
|
||||
RAISE NOTICE 'Created staff: %', v_staff_id;
|
||||
ELSE
|
||||
SELECT id INTO v_staff_id FROM staff WHERE display_name = 'Artista Demo' AND location_id = v_location_id;
|
||||
RAISE NOTICE 'Using existing staff: %', v_staff_id;
|
||||
END IF;
|
||||
|
||||
-- Insert sample resources if none exists
|
||||
INSERT INTO resources (location_id, name, type, capacity, is_active)
|
||||
SELECT
|
||||
v_location_id,
|
||||
'Estación Demo',
|
||||
'station',
|
||||
1,
|
||||
true
|
||||
WHERE NOT EXISTS (SELECT 1 FROM resources WHERE name = 'Estación Demo' AND location_id = v_location_id)
|
||||
RETURNING id INTO v_resource_id;
|
||||
|
||||
IF v_resource_id IS NOT NULL THEN
|
||||
RAISE NOTICE 'Created resource: %', v_resource_id;
|
||||
ELSE
|
||||
SELECT id INTO v_resource_id FROM resources WHERE name = 'Estación Demo' AND location_id = v_location_id;
|
||||
RAISE NOTICE 'Using existing resource: %', v_resource_id;
|
||||
END IF;
|
||||
|
||||
-- Check if we have services
|
||||
SELECT id INTO v_service_id FROM services WHERE is_active = true LIMIT 1;
|
||||
|
||||
IF v_service_id IS NOT NULL THEN
|
||||
RAISE NOTICE 'Using service: %', v_service_id;
|
||||
END IF;
|
||||
|
||||
RAISE NOTICE 'Seed data completed';
|
||||
END $$;
|
||||
|
||||
-- Verify results
|
||||
SELECT
|
||||
'Locations' as type, COUNT(*)::text as count FROM locations WHERE is_active = true
|
||||
UNION ALL
|
||||
SELECT 'Staff', COUNT(*)::text FROM staff WHERE is_active = true
|
||||
UNION ALL
|
||||
SELECT 'Resources', COUNT(*)::text FROM resources WHERE is_active = true
|
||||
UNION ALL
|
||||
SELECT 'Services', COUNT(*)::text FROM services WHERE is_active = true;
|
||||
46
scripts/seed_test_data.sql
Normal file
46
scripts/seed_test_data.sql
Normal file
@@ -0,0 +1,46 @@
|
||||
-- Seed data for testing availability
|
||||
-- Execute in Supabase Dashboard: Database > SQL Editor
|
||||
|
||||
-- Insert sample staff if none exists
|
||||
INSERT INTO staff (user_id, location_id, role, display_name, phone, is_active, is_available_for_booking, work_hours_start, work_hours_end, work_days)
|
||||
SELECT
|
||||
gen_random_uuid() as user_id,
|
||||
id as location_id,
|
||||
'artist' as role,
|
||||
'Artista Demo' as display_name,
|
||||
'+52 844 123 4567' as phone,
|
||||
true as is_active,
|
||||
true as is_available_for_booking,
|
||||
'10:00'::TIME as work_hours_start,
|
||||
'19:00'::TIME as work_hours_end,
|
||||
'MON,TUE,WED,THU,FRI,SAT' as work_days
|
||||
FROM locations
|
||||
WHERE is_active = true
|
||||
AND NOT EXISTS (SELECT 1 FROM staff WHERE location_id = locations.id AND display_name = 'Artista Demo')
|
||||
LIMIT 1;
|
||||
|
||||
-- Insert sample resources if none exists
|
||||
INSERT INTO resources (location_id, name, type, capacity, is_active)
|
||||
SELECT
|
||||
id as location_id,
|
||||
'Estación Demo' as name,
|
||||
'station' as type,
|
||||
1 as capacity,
|
||||
true as is_active
|
||||
FROM locations
|
||||
WHERE is_active = true
|
||||
AND NOT EXISTS (SELECT 1 FROM resources WHERE location_id = locations.id AND name = 'Estación Demo')
|
||||
LIMIT 1;
|
||||
|
||||
-- Verify results
|
||||
SELECT
|
||||
'Staff added' as info,
|
||||
COUNT(*)::text as count
|
||||
FROM staff
|
||||
WHERE display_name = 'Artista Demo'
|
||||
UNION ALL
|
||||
SELECT
|
||||
'Resources added',
|
||||
COUNT(*)::text
|
||||
FROM resources
|
||||
WHERE name = 'Estación Demo';
|
||||
24
scripts/test_availability_functions.sql
Normal file
24
scripts/test_availability_functions.sql
Normal file
@@ -0,0 +1,24 @@
|
||||
-- Test the availability functions
|
||||
-- Execute in Supabase Dashboard: Database > SQL Editor
|
||||
|
||||
-- Test check_staff_availability with fixed type casting
|
||||
SELECT
|
||||
check_staff_availability(
|
||||
(SELECT id FROM staff LIMIT 1),
|
||||
NOW() + INTERVAL '1 hour',
|
||||
NOW() + INTERVAL '2 hours'
|
||||
) as is_available;
|
||||
|
||||
-- Test get_detailed_availability with business hours
|
||||
SELECT * FROM get_detailed_availability(
|
||||
(SELECT id FROM locations LIMIT 1),
|
||||
(SELECT id FROM services LIMIT 1),
|
||||
CURRENT_DATE + INTERVAL '1 day',
|
||||
60
|
||||
);
|
||||
|
||||
-- Check business hours structure
|
||||
SELECT name, business_hours FROM locations LIMIT 1;
|
||||
|
||||
-- Check services with category
|
||||
SELECT id, name, category, is_active FROM services LIMIT 5;
|
||||
20
scripts/test_data_check.sql
Normal file
20
scripts/test_data_check.sql
Normal file
@@ -0,0 +1,20 @@
|
||||
-- Test script to check database data
|
||||
-- Execute in Supabase Dashboard: Database > SQL Editor
|
||||
|
||||
-- Check counts
|
||||
SELECT
|
||||
'Locations' as table_name, COUNT(*)::text as count FROM locations
|
||||
UNION ALL
|
||||
SELECT 'Services', COUNT(*)::text FROM services
|
||||
UNION ALL
|
||||
SELECT 'Staff', COUNT(*)::text FROM staff
|
||||
UNION ALL
|
||||
SELECT 'Resources', COUNT(*)::text FROM resources
|
||||
UNION ALL
|
||||
SELECT 'Bookings', COUNT(*)::text FROM bookings;
|
||||
|
||||
-- Show sample data
|
||||
SELECT id, name, timezone, is_active FROM locations LIMIT 5;
|
||||
SELECT id, name, duration_minutes, base_price, is_active FROM services LIMIT 5;
|
||||
SELECT id, display_name, role, is_active, is_available_for_booking FROM staff LIMIT 5;
|
||||
SELECT id, name, type, capacity, is_active FROM resources LIMIT 5;
|
||||
102
scripts/update_availability_function.sql
Normal file
102
scripts/update_availability_function.sql
Normal file
@@ -0,0 +1,102 @@
|
||||
-- Update get_detailed_availability to use business_hours from locations table
|
||||
-- Execute in Supabase Dashboard: Database > SQL Editor
|
||||
|
||||
DROP FUNCTION IF EXISTS get_detailed_availability(p_location_id UUID, p_service_id UUID, p_date DATE, p_time_slot_duration_minutes INTEGER) CASCADE;
|
||||
|
||||
CREATE OR REPLACE FUNCTION get_detailed_availability(
|
||||
p_location_id UUID,
|
||||
p_service_id UUID,
|
||||
p_date DATE,
|
||||
p_time_slot_duration_minutes INTEGER DEFAULT 60
|
||||
)
|
||||
RETURNS JSONB AS $$
|
||||
DECLARE
|
||||
v_service_duration INTEGER;
|
||||
v_location_timezone TEXT;
|
||||
v_business_hours JSONB;
|
||||
v_day_of_week TEXT;
|
||||
v_day_hours JSONB;
|
||||
v_start_time TIME := '09:00'::TIME;
|
||||
v_end_time TIME := '21:00'::TIME;
|
||||
v_time_slots JSONB := '[]'::JSONB;
|
||||
v_slot_start TIMESTAMPTZ;
|
||||
v_slot_end TIMESTAMPTZ;
|
||||
v_available_staff_count INTEGER;
|
||||
v_day_names TEXT[] := ARRAY['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday'];
|
||||
BEGIN
|
||||
-- Obtener duración del servicio
|
||||
SELECT duration_minutes INTO v_service_duration
|
||||
FROM services
|
||||
WHERE id = p_service_id;
|
||||
|
||||
IF v_service_duration IS NULL THEN
|
||||
RETURN '[]'::JSONB;
|
||||
END IF;
|
||||
|
||||
-- Obtener zona horaria y horarios de la ubicación
|
||||
SELECT
|
||||
timezone,
|
||||
business_hours
|
||||
INTO
|
||||
v_location_timezone,
|
||||
v_business_hours
|
||||
FROM locations
|
||||
WHERE id = p_location_id;
|
||||
|
||||
IF v_location_timezone IS NULL THEN
|
||||
RETURN '[]'::JSONB;
|
||||
END IF;
|
||||
|
||||
-- Obtener día de la semana (0 = Domingo, 1 = Lunes, etc.)
|
||||
v_day_of_week := v_day_names[EXTRACT(DOW FROM p_date) + 1];
|
||||
|
||||
-- Obtener horarios para este día
|
||||
v_day_hours := v_business_hours -> v_day_of_week;
|
||||
|
||||
-- Verificar si el lugar está cerrado este día
|
||||
IF v_day_hours->>'is_closed' = 'true' THEN
|
||||
RETURN '[]'::JSONB;
|
||||
END IF;
|
||||
|
||||
-- Extraer horas de apertura y cierre
|
||||
v_start_time := (v_day_hours->>'open')::TIME;
|
||||
v_end_time := (v_day_hours->>'close')::TIME;
|
||||
|
||||
-- Generar slots de tiempo para el día
|
||||
v_slot_start := (p_date || ' ' || v_start_time::TEXT)::TIMESTAMPTZ
|
||||
AT TIME ZONE v_location_timezone;
|
||||
|
||||
v_slot_end := (p_date || ' ' || v_end_time::TEXT)::TIMESTAMPTZ
|
||||
AT TIME ZONE v_location_timezone;
|
||||
|
||||
-- Iterar por cada slot
|
||||
WHILE v_slot_start < v_slot_end LOOP
|
||||
-- Verificar staff disponible para este slot
|
||||
SELECT COUNT(*) INTO v_available_staff_count
|
||||
FROM (
|
||||
SELECT 1
|
||||
FROM staff s
|
||||
WHERE s.location_id = p_location_id
|
||||
AND s.is_active = true
|
||||
AND s.is_available_for_booking = true
|
||||
AND s.role IN ('artist', 'staff', 'manager')
|
||||
AND check_staff_availability(s.id, v_slot_start, v_slot_start + (v_service_duration || ' minutes')::INTERVAL)
|
||||
) AS available_staff;
|
||||
|
||||
-- Agregar slot al resultado
|
||||
IF v_available_staff_count > 0 THEN
|
||||
v_time_slots := v_time_slots || jsonb_build_object(
|
||||
'start_time', v_slot_start::TEXT,
|
||||
'end_time', (v_slot_start + (p_time_slot_duration_minutes || ' minutes')::INTERVAL)::TEXT,
|
||||
'available', true,
|
||||
'available_staff_count', v_available_staff_count
|
||||
);
|
||||
END IF;
|
||||
|
||||
-- Avanzar al siguiente slot
|
||||
v_slot_start := v_slot_start + (p_time_slot_duration_minutes || ' minutes')::INTERVAL;
|
||||
END LOOP;
|
||||
|
||||
RETURN v_time_slots;
|
||||
END;
|
||||
$$ LANGUAGE plpgsql SECURITY DEFINER;
|
||||
63
scripts/update_business_hours.sql
Normal file
63
scripts/update_business_hours.sql
Normal file
@@ -0,0 +1,63 @@
|
||||
-- Update business_hours with correct structure and values
|
||||
-- Execute in Supabase Dashboard: Database > SQL Editor
|
||||
|
||||
-- First, check current state
|
||||
SELECT
|
||||
id,
|
||||
name,
|
||||
business_hours->>'monday' as monday_check,
|
||||
(business_hours->'monday'->>'open') as monday_open_check,
|
||||
(business_hours->'monday'->>'close') as monday_close_check
|
||||
FROM locations
|
||||
LIMIT 1;
|
||||
|
||||
-- Update with correct structure - Monday to Friday 10-7, Saturday 10-6, Sunday closed
|
||||
UPDATE locations
|
||||
SET business_hours = '{
|
||||
"monday": {"open": "10:00", "close": "19:00", "is_closed": false},
|
||||
"tuesday": {"open": "10:00", "close": "19:00", "is_closed": false},
|
||||
"wednesday": {"open": "10:00", "close": "19:00", "is_closed": false},
|
||||
"thursday": {"open": "10:00", "close": "19:00", "is_closed": false},
|
||||
"friday": {"open": "10:00", "close": "19:00", "is_closed": false},
|
||||
"saturday": {"open": "10:00", "close": "18:00", "is_closed": false},
|
||||
"sunday": {"is_closed": true}
|
||||
}'::jsonb;
|
||||
|
||||
-- Verify the update
|
||||
SELECT
|
||||
id,
|
||||
name,
|
||||
timezone,
|
||||
business_hours
|
||||
FROM locations
|
||||
LIMIT 1;
|
||||
|
||||
-- Test extraction for different days
|
||||
SELECT
|
||||
'Monday' as day,
|
||||
(business_hours->'monday'->>'open')::TIME as open_time,
|
||||
(business_hours->'monday'->>'close')::TIME as close_time,
|
||||
business_hours->'monday'->>'is_closed' as is_closed
|
||||
FROM locations
|
||||
UNION ALL
|
||||
SELECT
|
||||
'Saturday' as day,
|
||||
(business_hours->'saturday'->>'open')::TIME as open_time,
|
||||
(business_hours->'saturday'->>'close')::TIME as close_time,
|
||||
business_hours->'saturday'->>'is_closed' as is_closed
|
||||
FROM locations
|
||||
UNION ALL
|
||||
SELECT
|
||||
'Sunday' as day,
|
||||
(business_hours->'sunday'->>'open')::TIME as open_time,
|
||||
(business_hours->'sunday'->>'close')::TIME as close_time,
|
||||
business_hours->'sunday'->>'is_closed' as is_closed
|
||||
FROM locations;
|
||||
|
||||
-- Test the get_detailed_availability function
|
||||
SELECT * FROM get_detailed_availability(
|
||||
(SELECT id FROM locations LIMIT 1),
|
||||
(SELECT id FROM services WHERE is_active = true LIMIT 1),
|
||||
CURRENT_DATE,
|
||||
60
|
||||
);
|
||||
25
scripts/update_business_hours_final.sql
Normal file
25
scripts/update_business_hours_final.sql
Normal file
@@ -0,0 +1,25 @@
|
||||
-- Update business_hours with correct structure and values
|
||||
-- Execute in Supabase Dashboard: Database > SQL Editor
|
||||
|
||||
-- Update with correct structure - Monday to Friday 10-7, Saturday 10-6, Sunday closed
|
||||
UPDATE locations
|
||||
SET business_hours = '{
|
||||
"monday": {"open": "10:00", "close": "19:00", "is_closed": false},
|
||||
"tuesday": {"open": "10:00", "close": "19:00", "is_closed": false},
|
||||
"wednesday": {"open": "10:00", "close": "19:00", "is_closed": false},
|
||||
"thursday": {"open": "10:00", "close": "19:00", "is_closed": false},
|
||||
"friday": {"open": "10:00", "close": "19:00", "is_closed": false},
|
||||
"saturday": {"open": "10:00", "close": "18:00", "is_closed": false},
|
||||
"sunday": {"is_closed": true}
|
||||
}'::jsonb
|
||||
WHERE business_hours IS NULL OR business_hours = '{}'::jsonb;
|
||||
|
||||
-- Verify update
|
||||
SELECT
|
||||
id,
|
||||
name,
|
||||
business_hours->>'monday' as monday_check,
|
||||
(business_hours->'monday'->>'open')::TIME as monday_open,
|
||||
(business_hours->'monday'->>'close')::TIME as monday_close
|
||||
FROM locations
|
||||
LIMIT 1;
|
||||
@@ -43,7 +43,7 @@ CREATE TABLE IF NOT EXISTS booking_blocks (
|
||||
end_time_utc TIMESTAMPTZ NOT NULL,
|
||||
reason TEXT,
|
||||
created_at TIMESTAMPTZ DEFAULT NOW(),
|
||||
created_by UUID REFERENCES users(id) ON DELETE SET NULL,
|
||||
created_by UUID REFERENCES staff(id) ON DELETE SET NULL,
|
||||
CONSTRAINT booking_blocks_time_check CHECK (end_time_utc > start_time_utc)
|
||||
);
|
||||
|
||||
@@ -193,6 +193,8 @@ $$ LANGUAGE plpgsql SECURITY DEFINER;
|
||||
-- Obtiene staff disponible para un rango de tiempo
|
||||
-- ============================================
|
||||
|
||||
DROP FUNCTION IF EXISTS get_available_staff(p_location_id UUID, p_start_time_utc TIMESTAMPTZ, p_end_time_utc TIMESTAMPTZ) CASCADE;
|
||||
|
||||
CREATE OR REPLACE FUNCTION get_available_staff(
|
||||
p_location_id UUID,
|
||||
p_start_time_utc TIMESTAMPTZ,
|
||||
@@ -237,6 +239,8 @@ $$ LANGUAGE plpgsql SECURITY DEFINER;
|
||||
-- Obtiene slots de tiempo disponibles
|
||||
-- ============================================
|
||||
|
||||
DROP FUNCTION IF EXISTS get_detailed_availability(p_location_id UUID, p_service_id UUID, p_date DATE, p_time_slot_duration_minutes INTEGER) CASCADE;
|
||||
|
||||
CREATE OR REPLACE FUNCTION get_detailed_availability(
|
||||
p_location_id UUID,
|
||||
p_service_id UUID,
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
-- Add category column to services table
|
||||
ALTER TABLE services ADD COLUMN IF NOT EXISTS category VARCHAR(50) DEFAULT 'General';
|
||||
@@ -0,0 +1,13 @@
|
||||
-- Add business hours to locations table
|
||||
-- Format: JSONB with daily opening/closing times
|
||||
|
||||
ALTER TABLE locations
|
||||
ADD COLUMN IF NOT EXISTS business_hours JSONB DEFAULT '{"monday":{"open":"10:00","close":"19:00","is_closed":false},"tuesday":{"open":"10:00","close":"19:00","is_closed":false},"wednesday":{"open":"10:00","close":"19:00","is_closed":false},"thursday":{"open":"10:00","close":"19:00","is_closed":false},"friday":{"open":"10:00","close":"19:00","is_closed":false},"saturday":{"open":"10:00","close":"18:00","is_closed":false},"sunday":{"is_closed":true}}';
|
||||
|
||||
-- Add comments
|
||||
COMMENT ON COLUMN locations.business_hours IS 'Business hours for each day of the week in JSONB format. Keys: monday-sunday with open/close times in HH:MM format and is_closed boolean';
|
||||
|
||||
-- Update existing locations with default hours
|
||||
UPDATE locations
|
||||
SET business_hours = '{"monday":{"open":"10:00","close":"19:00","is_closed":false},"tuesday":{"open":"10:00","close":"19:00","is_closed":false},"wednesday":{"open":"10:00","close":"19:00","is_closed":false},"thursday":{"open":"10:00","close":"19:00","is_closed":false},"friday":{"open":"10:00","close":"19:00","is_closed":false},"saturday":{"open":"10:00","close":"18:00","is_closed":false},"sunday":{"is_closed":true}}'
|
||||
WHERE business_hours IS NULL OR business_hours = '{}'::jsonb;
|
||||
@@ -0,0 +1,101 @@
|
||||
-- Update get_detailed_availability to use business_hours from locations table
|
||||
|
||||
DROP FUNCTION IF EXISTS get_detailed_availability(p_location_id UUID, p_service_id UUID, p_date DATE, p_time_slot_duration_minutes INTEGER) CASCADE;
|
||||
|
||||
CREATE OR REPLACE FUNCTION get_detailed_availability(
|
||||
p_location_id UUID,
|
||||
p_service_id UUID,
|
||||
p_date DATE,
|
||||
p_time_slot_duration_minutes INTEGER DEFAULT 60
|
||||
)
|
||||
RETURNS JSONB AS $$
|
||||
DECLARE
|
||||
v_service_duration INTEGER;
|
||||
v_location_timezone TEXT;
|
||||
v_business_hours JSONB;
|
||||
v_day_of_week TEXT;
|
||||
v_day_hours JSONB;
|
||||
v_start_time TIME := '09:00'::TIME;
|
||||
v_end_time TIME := '21:00'::TIME;
|
||||
v_time_slots JSONB := '[]'::JSONB;
|
||||
v_slot_start TIMESTAMPTZ;
|
||||
v_slot_end TIMESTAMPTZ;
|
||||
v_available_staff_count INTEGER;
|
||||
v_day_names TEXT[] := ARRAY['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday'];
|
||||
BEGIN
|
||||
-- Obtener duración del servicio
|
||||
SELECT duration_minutes INTO v_service_duration
|
||||
FROM services
|
||||
WHERE id = p_service_id;
|
||||
|
||||
IF v_service_duration IS NULL THEN
|
||||
RETURN '[]'::JSONB;
|
||||
END IF;
|
||||
|
||||
-- Obtener zona horaria y horarios de la ubicación
|
||||
SELECT
|
||||
timezone,
|
||||
business_hours
|
||||
INTO
|
||||
v_location_timezone,
|
||||
v_business_hours
|
||||
FROM locations
|
||||
WHERE id = p_location_id;
|
||||
|
||||
IF v_location_timezone IS NULL THEN
|
||||
RETURN '[]'::JSONB;
|
||||
END IF;
|
||||
|
||||
-- Obtener día de la semana (0 = Domingo, 1 = Lunes, etc.)
|
||||
v_day_of_week := v_day_names[EXTRACT(DOW FROM p_date) + 1];
|
||||
|
||||
-- Obtener horarios para este día
|
||||
v_day_hours := v_business_hours -> v_day_of_week;
|
||||
|
||||
-- Verificar si el lugar está cerrado este día
|
||||
IF v_day_hours->>'is_closed' = 'true' THEN
|
||||
RETURN '[]'::JSONB;
|
||||
END IF;
|
||||
|
||||
-- Extraer horas de apertura y cierre
|
||||
v_start_time := (v_day_hours->>'open')::TIME;
|
||||
v_end_time := (v_day_hours->>'close')::TIME;
|
||||
|
||||
-- Generar slots de tiempo para el día
|
||||
v_slot_start := (p_date || ' ' || v_start_time::TEXT)::TIMESTAMPTZ
|
||||
AT TIME ZONE v_location_timezone;
|
||||
|
||||
v_slot_end := (p_date || ' ' || v_end_time::TEXT)::TIMESTAMPTZ
|
||||
AT TIME ZONE v_location_timezone;
|
||||
|
||||
-- Iterar por cada slot
|
||||
WHILE v_slot_start < v_slot_end LOOP
|
||||
-- Verificar staff disponible para este slot
|
||||
SELECT COUNT(*) INTO v_available_staff_count
|
||||
FROM (
|
||||
SELECT 1
|
||||
FROM staff s
|
||||
WHERE s.location_id = p_location_id
|
||||
AND s.is_active = true
|
||||
AND s.is_available_for_booking = true
|
||||
AND s.role IN ('artist', 'staff', 'manager')
|
||||
AND check_staff_availability(s.id, v_slot_start, v_slot_start + (v_service_duration || ' minutes')::INTERVAL)
|
||||
) AS available_staff;
|
||||
|
||||
-- Agregar slot al resultado
|
||||
IF v_available_staff_count > 0 THEN
|
||||
v_time_slots := v_time_slots || jsonb_build_object(
|
||||
'start_time', v_slot_start::TEXT,
|
||||
'end_time', (v_slot_start + (p_time_slot_duration_minutes || 'minutes')::INTERVAL)::TEXT,
|
||||
'available', true,
|
||||
'available_staff_count', v_available_staff_count
|
||||
);
|
||||
END IF;
|
||||
|
||||
-- Avanzar al siguiente slot
|
||||
v_slot_start := v_slot_start + (p_time_slot_duration_minutes || 'minutes')::INTERVAL;
|
||||
END LOOP;
|
||||
|
||||
RETURN v_time_slots;
|
||||
END;
|
||||
$$ LANGUAGE plpgsql SECURITY DEFINER;
|
||||
@@ -0,0 +1,72 @@
|
||||
-- Fix: Remove category references from services and fix type casting in availability functions
|
||||
|
||||
-- Check if category column exists and remove it from queries if needed
|
||||
-- The services table doesn't have a category column, so we need to remove it from any queries
|
||||
|
||||
-- Fix type casting in check_staff_availability function
|
||||
DROP FUNCTION IF EXISTS check_staff_availability(p_staff_id UUID, p_start_time_utc TIMESTAMPTZ, p_end_time_utc TIMESTAMPTZ, p_exclude_booking_id UUID) CASCADE;
|
||||
|
||||
CREATE OR REPLACE FUNCTION check_staff_availability(
|
||||
p_staff_id UUID,
|
||||
p_start_time_utc TIMESTAMPTZ,
|
||||
p_end_time_utc TIMESTAMPTZ,
|
||||
p_exclude_booking_id UUID DEFAULT NULL
|
||||
)
|
||||
RETURNS BOOLEAN AS $$
|
||||
DECLARE
|
||||
v_is_work_hours BOOLEAN;
|
||||
v_has_booking_conflict BOOLEAN;
|
||||
v_has_manual_block BOOLEAN;
|
||||
v_location_timezone TEXT;
|
||||
v_start_time_local TIME;
|
||||
v_end_time_local TIME;
|
||||
v_block_start_local TIME;
|
||||
v_block_end_local TIME;
|
||||
BEGIN
|
||||
-- Obtener zona horaria de la ubicación del staff
|
||||
SELECT timezone INTO v_location_timezone
|
||||
FROM locations
|
||||
WHERE id = (SELECT location_id FROM staff WHERE id = p_staff_id);
|
||||
|
||||
-- Verificar horario laboral
|
||||
v_is_work_hours := check_staff_work_hours(p_staff_id, p_start_time_utc, p_end_time_utc, v_location_timezone);
|
||||
|
||||
IF NOT v_is_work_hours THEN
|
||||
RETURN false;
|
||||
END IF;
|
||||
|
||||
-- Verificar conflictos con otras reservas
|
||||
SELECT EXISTS(
|
||||
SELECT 1
|
||||
FROM bookings
|
||||
WHERE staff_id = p_staff_id
|
||||
AND status NOT IN ('cancelled', 'no_show')
|
||||
AND (p_exclude_booking_id IS NULL OR id != p_exclude_booking_id)
|
||||
AND NOT (p_end_time_utc <= start_time_utc OR p_start_time_utc >= end_time_utc)
|
||||
) INTO v_has_booking_conflict;
|
||||
|
||||
IF v_has_booking_conflict THEN
|
||||
RETURN false;
|
||||
END IF;
|
||||
|
||||
-- Convert times to local TIME for comparison
|
||||
v_start_time_local := (p_start_time_utc AT TIME ZONE v_location_timezone)::TIME;
|
||||
v_end_time_local := (p_end_time_utc AT TIME ZONE v_location_timezone)::TIME;
|
||||
|
||||
-- Verificar bloques manuales de disponibilidad
|
||||
SELECT EXISTS(
|
||||
SELECT 1
|
||||
FROM staff_availability
|
||||
WHERE staff_id = p_staff_id
|
||||
AND date = (p_start_time_utc AT TIME ZONE v_location_timezone)::DATE
|
||||
AND is_available = false
|
||||
AND NOT (v_end_time_local <= start_time OR v_start_time_local >= end_time)
|
||||
) INTO v_has_manual_block;
|
||||
|
||||
IF v_has_manual_block THEN
|
||||
RETURN false;
|
||||
END IF;
|
||||
|
||||
RETURN true;
|
||||
END;
|
||||
$$ LANGUAGE plpgsql SECURITY DEFINER;
|
||||
234
supabase/migrations/20260117040000_complete_availability_fix.sql
Normal file
234
supabase/migrations/20260117040000_complete_availability_fix.sql
Normal file
@@ -0,0 +1,234 @@
|
||||
-- Complete fix for all availability functions with proper type casting
|
||||
-- This replaces all functions to fix type comparison issues
|
||||
|
||||
-- Drop all functions first
|
||||
DROP FUNCTION IF EXISTS check_staff_work_hours(p_staff_id UUID, p_start_time_utc TIMESTAMPTZ, p_end_time_utc TIMESTAMPTZ, p_location_timezone TEXT) CASCADE;
|
||||
DROP FUNCTION IF EXISTS check_staff_availability(p_staff_id UUID, p_start_time_utc TIMESTAMPTZ, p_end_time_utc TIMESTAMPTZ, p_exclude_booking_id UUID) CASCADE;
|
||||
DROP FUNCTION IF EXISTS get_detailed_availability(p_location_id UUID, p_service_id UUID, p_date DATE, p_time_slot_duration_minutes INTEGER) CASCADE;
|
||||
|
||||
-- ============================================
|
||||
-- FUNCIÓN: check_staff_work_hours
|
||||
-- Verifica si el staff está en horario laboral
|
||||
-- ============================================
|
||||
|
||||
CREATE OR REPLACE FUNCTION check_staff_work_hours(
|
||||
p_staff_id UUID,
|
||||
p_start_time_utc TIMESTAMPTZ,
|
||||
p_end_time_utc TIMESTAMPTZ,
|
||||
p_location_timezone TEXT
|
||||
)
|
||||
RETURNS BOOLEAN AS $$
|
||||
DECLARE
|
||||
v_work_hours_start TIME;
|
||||
v_work_hours_end TIME;
|
||||
v_work_days TEXT;
|
||||
v_day_of_week TEXT;
|
||||
v_local_start TIME;
|
||||
v_local_end TIME;
|
||||
BEGIN
|
||||
-- Obtener horario del staff
|
||||
SELECT
|
||||
work_hours_start,
|
||||
work_hours_end,
|
||||
work_days
|
||||
INTO
|
||||
v_work_hours_start,
|
||||
v_work_hours_end,
|
||||
v_work_days
|
||||
FROM staff
|
||||
WHERE id = p_staff_id;
|
||||
|
||||
-- Si no tiene horario definido, asumir disponible 24/7
|
||||
IF v_work_hours_start IS NULL OR v_work_hours_end IS NULL THEN
|
||||
RETURN true;
|
||||
END IF;
|
||||
|
||||
-- Obtener día de la semana en zona horaria local
|
||||
v_day_of_week := TO_CHAR(p_start_time_utc AT TIME ZONE p_location_timezone, 'DY');
|
||||
|
||||
-- Verificar si trabaja ese día
|
||||
IF v_work_days IS NULL OR NOT (',' || v_work_days || ',') LIKE ('%,' || v_day_of_week || ',%') THEN
|
||||
RETURN false;
|
||||
END IF;
|
||||
|
||||
-- Convertir horas UTC a horario local
|
||||
v_local_start := (p_start_time_utc AT TIME ZONE p_location_timezone)::TIME;
|
||||
v_local_end := (p_end_time_utc AT TIME ZONE p_location_timezone)::TIME;
|
||||
|
||||
-- Verificar si está dentro del horario laboral
|
||||
RETURN v_local_start >= v_work_hours_start AND v_local_end <= v_work_hours_end;
|
||||
END;
|
||||
$$ LANGUAGE plpgsql SECURITY DEFINER;
|
||||
|
||||
-- ============================================
|
||||
-- FUNCIÓN: check_staff_availability
|
||||
-- Verifica disponibilidad completa del staff
|
||||
-- ============================================
|
||||
|
||||
CREATE OR REPLACE FUNCTION check_staff_availability(
|
||||
p_staff_id UUID,
|
||||
p_start_time_utc TIMESTAMPTZ,
|
||||
p_end_time_utc TIMESTAMPTZ,
|
||||
p_exclude_booking_id UUID DEFAULT NULL
|
||||
)
|
||||
RETURNS BOOLEAN AS $$
|
||||
DECLARE
|
||||
v_is_work_hours BOOLEAN;
|
||||
v_has_booking_conflict BOOLEAN;
|
||||
v_has_manual_block BOOLEAN;
|
||||
v_location_timezone TEXT;
|
||||
v_start_time_local TIME;
|
||||
v_end_time_local TIME;
|
||||
v_block_start_local TIME;
|
||||
v_block_end_local TIME;
|
||||
BEGIN
|
||||
-- Obtener zona horaria de la ubicación del staff
|
||||
SELECT timezone INTO v_location_timezone
|
||||
FROM locations
|
||||
WHERE id = (SELECT location_id FROM staff WHERE id = p_staff_id);
|
||||
|
||||
-- Verificar horario laboral
|
||||
v_is_work_hours := check_staff_work_hours(p_staff_id, p_start_time_utc, p_end_time_utc, v_location_timezone);
|
||||
|
||||
IF NOT v_is_work_hours THEN
|
||||
RETURN false;
|
||||
END IF;
|
||||
|
||||
-- Verificar conflictos con otras reservas
|
||||
SELECT EXISTS(
|
||||
SELECT 1
|
||||
FROM bookings
|
||||
WHERE staff_id = p_staff_id
|
||||
AND status NOT IN ('cancelled', 'no_show')
|
||||
AND (p_exclude_booking_id IS NULL OR id != p_exclude_booking_id)
|
||||
AND NOT (p_end_time_utc <= start_time_utc OR p_start_time_utc >= end_time_utc)
|
||||
) INTO v_has_booking_conflict;
|
||||
|
||||
IF v_has_booking_conflict THEN
|
||||
RETURN false;
|
||||
END IF;
|
||||
|
||||
-- Convertir a TIME local para comparación
|
||||
v_start_time_local := (p_start_time_utc AT TIME ZONE v_location_timezone)::TIME;
|
||||
v_end_time_local := (p_end_time_utc AT TIME ZONE v_location_timezone)::TIME;
|
||||
|
||||
-- Verificar bloques manuales de disponibilidad
|
||||
SELECT EXISTS(
|
||||
SELECT 1
|
||||
FROM staff_availability
|
||||
WHERE staff_id = p_staff_id
|
||||
AND date = (p_start_time_utc AT TIME ZONE v_location_timezone)::DATE
|
||||
AND is_available = false
|
||||
AND NOT (v_end_time_local <= end_time OR v_start_time_local >= start_time)
|
||||
) INTO v_has_manual_block;
|
||||
|
||||
IF v_has_manual_block THEN
|
||||
RETURN false;
|
||||
END IF;
|
||||
|
||||
RETURN true;
|
||||
END;
|
||||
$$ LANGUAGE plpgsql SECURITY DEFINER;
|
||||
|
||||
-- ============================================
|
||||
-- FUNCIÓN: get_detailed_availability
|
||||
-- Obtiene slots de tiempo disponibles
|
||||
-- ============================================
|
||||
|
||||
CREATE OR REPLACE FUNCTION get_detailed_availability(
|
||||
p_location_id UUID,
|
||||
p_service_id UUID,
|
||||
p_date DATE,
|
||||
p_time_slot_duration_minutes INTEGER DEFAULT 60
|
||||
)
|
||||
RETURNS JSONB AS $$
|
||||
DECLARE
|
||||
v_service_duration INTEGER;
|
||||
v_location_timezone TEXT;
|
||||
v_business_hours JSONB;
|
||||
v_day_of_week TEXT;
|
||||
v_day_hours JSONB;
|
||||
v_start_time TIME := '09:00'::TIME;
|
||||
v_end_time TIME := '21:00'::TIME;
|
||||
v_time_slots JSONB := '[]'::JSONB;
|
||||
v_slot_start TIMESTAMPTZ;
|
||||
v_slot_end TIMESTAMPTZ;
|
||||
v_available_staff_count INTEGER;
|
||||
v_day_names TEXT[] := ARRAY['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday'];
|
||||
BEGIN
|
||||
-- Obtener duración del servicio
|
||||
SELECT duration_minutes INTO v_service_duration
|
||||
FROM services
|
||||
WHERE id = p_service_id;
|
||||
|
||||
IF v_service_duration IS NULL THEN
|
||||
RETURN '[]'::JSONB;
|
||||
END IF;
|
||||
|
||||
-- Obtener zona horaria y horarios de la ubicación
|
||||
SELECT
|
||||
timezone,
|
||||
business_hours
|
||||
INTO
|
||||
v_location_timezone,
|
||||
v_business_hours
|
||||
FROM locations
|
||||
WHERE id = p_location_id;
|
||||
|
||||
IF v_location_timezone IS NULL THEN
|
||||
RETURN '[]'::JSONB;
|
||||
END IF;
|
||||
|
||||
-- Obtener día de la semana (0 = Domingo, 1 = Lunes, etc.)
|
||||
v_day_of_week := v_day_names[EXTRACT(DOW FROM p_date) + 1];
|
||||
|
||||
-- Obtener horarios para este día
|
||||
v_day_hours := v_business_hours -> v_day_of_week;
|
||||
|
||||
-- Verificar si el lugar está cerrado este día
|
||||
IF v_day_hours->>'is_closed' = 'true' THEN
|
||||
RETURN '[]'::JSONB;
|
||||
END IF;
|
||||
|
||||
-- Extraer horas de apertura y cierre
|
||||
v_start_time := (v_day_hours->>'open')::TIME;
|
||||
v_end_time := (v_day_hours->>'close')::TIME;
|
||||
|
||||
-- Generar slots de tiempo para el día
|
||||
v_slot_start := (p_date || ' ' || v_start_time::TEXT)::TIMESTAMPTZ
|
||||
AT TIME ZONE v_location_timezone;
|
||||
|
||||
v_slot_end := (p_date || ' ' || v_end_time::TEXT)::TIMESTAMPTZ
|
||||
AT TIME ZONE v_location_timezone;
|
||||
|
||||
-- Iterar por cada slot
|
||||
WHILE v_slot_start < v_slot_end LOOP
|
||||
-- Verificar staff disponible para este slot
|
||||
SELECT COUNT(*) INTO v_available_staff_count
|
||||
FROM (
|
||||
SELECT 1
|
||||
FROM staff s
|
||||
WHERE s.location_id = p_location_id
|
||||
AND s.is_active = true
|
||||
AND s.is_available_for_booking = true
|
||||
AND s.role IN ('artist', 'staff', 'manager')
|
||||
AND check_staff_availability(s.id, v_slot_start, v_slot_start + (v_service_duration || ' minutes')::INTERVAL)
|
||||
) AS available_staff;
|
||||
|
||||
-- Agregar slot al resultado
|
||||
IF v_available_staff_count > 0 THEN
|
||||
v_time_slots := v_time_slots || jsonb_build_object(
|
||||
'start_time', v_slot_start::TEXT,
|
||||
'end_time', (v_slot_start + (p_time_slot_duration_minutes || ' minutes')::INTERVAL)::TEXT,
|
||||
'available', true,
|
||||
'available_staff_count', v_available_staff_count
|
||||
);
|
||||
END IF;
|
||||
|
||||
-- Avanzar al siguiente slot
|
||||
v_slot_start := v_slot_start + (p_time_slot_duration_minutes || ' minutes')::INTERVAL;
|
||||
END LOOP;
|
||||
|
||||
RETURN v_time_slots;
|
||||
END;
|
||||
$$ LANGUAGE plpgsql SECURITY DEFINER;
|
||||
107
supabase/migrations/20260117050000_fix_business_hours_json.sql
Normal file
107
supabase/migrations/20260117050000_fix_business_hours_json.sql
Normal file
@@ -0,0 +1,107 @@
|
||||
-- Improved get_detailed_availability with better JSONB handling and debugging
|
||||
|
||||
DROP FUNCTION IF EXISTS get_detailed_availability(p_location_id UUID, p_service_id UUID, p_date DATE, p_time_slot_duration_minutes INTEGER) CASCADE;
|
||||
|
||||
CREATE OR REPLACE FUNCTION get_detailed_availability(
|
||||
p_location_id UUID,
|
||||
p_service_id UUID,
|
||||
p_date DATE,
|
||||
p_time_slot_duration_minutes INTEGER DEFAULT 60
|
||||
)
|
||||
RETURNS JSONB AS $$
|
||||
DECLARE
|
||||
v_service_duration INTEGER;
|
||||
v_location_timezone TEXT;
|
||||
v_business_hours JSONB;
|
||||
v_day_of_week TEXT;
|
||||
v_day_hours JSONB;
|
||||
v_open_time_text TEXT;
|
||||
v_close_time_text TEXT;
|
||||
v_start_time TIME;
|
||||
v_end_time TIME;
|
||||
v_time_slots JSONB := '[]'::JSONB;
|
||||
v_slot_start TIMESTAMPTZ;
|
||||
v_slot_end TIMESTAMPTZ;
|
||||
v_available_staff_count INTEGER;
|
||||
v_day_names TEXT[] := ARRAY['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday'];
|
||||
BEGIN
|
||||
-- Obtener duración del servicio
|
||||
SELECT duration_minutes INTO v_service_duration
|
||||
FROM services
|
||||
WHERE id = p_service_id;
|
||||
|
||||
IF v_service_duration IS NULL THEN
|
||||
RETURN '[]'::JSONB;
|
||||
END IF;
|
||||
|
||||
-- Obtener zona horaria y horarios de la ubicación
|
||||
SELECT
|
||||
timezone,
|
||||
COALESCE(business_hours, '{}'::jsonb)
|
||||
INTO
|
||||
v_location_timezone,
|
||||
v_business_hours
|
||||
FROM locations
|
||||
WHERE id = p_location_id;
|
||||
|
||||
IF v_location_timezone IS NULL THEN
|
||||
RETURN '[]'::JSONB;
|
||||
END IF;
|
||||
|
||||
-- Obtener día de la semana (0 = Domingo, 1 = Lunes, etc.)
|
||||
v_day_of_week := v_day_names[EXTRACT(DOW FROM p_date) + 1];
|
||||
|
||||
-- Obtener horarios para este día desde JSONB
|
||||
v_day_hours := v_business_hours -> v_day_of_week;
|
||||
|
||||
-- Verificar si el lugar está cerrado este día
|
||||
IF v_day_hours IS NULL OR v_day_hours->>'is_closed' = 'true' THEN
|
||||
RETURN '[]'::JSONB;
|
||||
END IF;
|
||||
|
||||
-- Extraer horas de apertura y cierre como TEXT primero
|
||||
v_open_time_text := v_day_hours->>'open';
|
||||
v_close_time_text := v_day_hours->>'close';
|
||||
|
||||
-- Convertir a TIME, usar defaults si están NULL
|
||||
v_start_time := COALESCE(v_open_time_text::TIME, '10:00'::TIME);
|
||||
v_end_time := COALESCE(v_close_time_text::TIME, '19:00'::TIME);
|
||||
|
||||
-- Generar slots de tiempo para el día
|
||||
v_slot_start := (p_date || ' ' || v_start_time::TEXT)::TIMESTAMPTZ
|
||||
AT TIME ZONE v_location_timezone;
|
||||
|
||||
v_slot_end := (p_date || ' ' || v_end_time::TEXT)::TIMESTAMPTZ
|
||||
AT TIME ZONE v_location_timezone;
|
||||
|
||||
-- Iterar por cada slot
|
||||
WHILE v_slot_start < v_slot_end LOOP
|
||||
-- Verificar staff disponible para este slot
|
||||
SELECT COUNT(*) INTO v_available_staff_count
|
||||
FROM (
|
||||
SELECT 1
|
||||
FROM staff s
|
||||
WHERE s.location_id = p_location_id
|
||||
AND s.is_active = true
|
||||
AND s.is_available_for_booking = true
|
||||
AND s.role IN ('artist', 'staff', 'manager')
|
||||
AND check_staff_availability(s.id, v_slot_start, v_slot_start + (v_service_duration || ' minutes')::INTERVAL)
|
||||
) AS available_staff;
|
||||
|
||||
-- Agregar slot al resultado
|
||||
IF v_available_staff_count > 0 THEN
|
||||
v_time_slots := v_time_slots || jsonb_build_object(
|
||||
'start_time', v_slot_start::TEXT,
|
||||
'end_time', (v_slot_start + (p_time_slot_duration_minutes || ' minutes')::INTERVAL)::TEXT,
|
||||
'available', true,
|
||||
'available_staff_count', v_available_staff_count
|
||||
);
|
||||
END IF;
|
||||
|
||||
-- Avanzar al siguiente slot
|
||||
v_slot_start := v_slot_start + (p_time_slot_duration_minutes || ' minutes')::INTERVAL;
|
||||
END LOOP;
|
||||
|
||||
RETURN v_time_slots;
|
||||
END;
|
||||
$$ LANGUAGE plpgsql SECURITY DEFINER;
|
||||
@@ -0,0 +1,15 @@
|
||||
-- Update business_hours with correct structure and values
|
||||
-- Execute: This migration updates business_hours for all locations
|
||||
|
||||
-- Update with correct structure - Monday to Friday 10-7, Saturday 10-6, Sunday closed
|
||||
UPDATE locations
|
||||
SET business_hours = '{
|
||||
"monday": {"open": "10:00", "close": "19:00", "is_closed": false},
|
||||
"tuesday": {"open": "10:00", "close": "19:00", "is_closed": false},
|
||||
"wednesday": {"open": "10:00", "close": "19:00", "is_closed": false},
|
||||
"thursday": {"open": "10:00", "close": "19:00", "is_closed": false},
|
||||
"friday": {"open": "10:00", "close": "19:00", "is_closed": false},
|
||||
"saturday": {"open": "10:00", "close": "18:00", "is_closed": false},
|
||||
"sunday": {"is_closed": true}
|
||||
}'::jsonb
|
||||
WHERE business_hours IS NULL OR business_hours = '{}'::jsonb;
|
||||
Reference in New Issue
Block a user