+
-
-
-
-
-
- Servicios
-
- Selecciona el servicio que deseas reservar
-
-
-
-
- Servicio
-
-
-
-
-
- {services.map((service) => (
-
- {service.name} - ${service.base_price} ({service.duration_minutes} min)
-
- ))}
-
-
-
-
-
-
+
+ {currentStep === 'service' && (
+ <>
+
+
+
+
+ Servicios
+
+
+ Selecciona el servicio que deseas reservar
+
+
+
+
+
+
+ Servicio
+
+
+
+
+
+
+ {services.map((service) => (
+
+ {service.name} - ${service.base_price.toFixed(2)} ({service.duration_minutes} min)
+
+ ))}
+
+
+ {errors.service &&
{errors.service}
}
+
-
-
-
-
- Fecha y Hora
-
- Selecciona la fecha y hora disponible
-
-
-
-
- Ubicación
-
-
-
-
-
- {locations.map((location) => (
-
- {location.name}
-
- ))}
-
-
-
-
-
- Fecha
- 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)' }}
- />
-
-
- {selectedServiceData && (
-
-
Duración del servicio: {selectedServiceData.duration_minutes} minutos
+
+
+ Ubicación
+
+
+
+
+
+
+ {locations.map((location) => (
+
+ {location.name}
+
+ ))}
+
+
+ {errors.location &&
{errors.location}
}
+
- )}
-
- {loading ? (
-
- Cargando horarios...
-
- ) : (
-
-
Horarios disponibles
- {timeSlots.length === 0 ? (
-
- No hay horarios disponibles para esta fecha. Selecciona otra fecha.
-
- ) : (
-
- {timeSlots.map((slot, index) => (
- setSelectedTime(slot.start_time)}
- className={selectedTime === slot.start_time ? 'w-full' : ''}
- >
- {format(new Date(slot.start_time), 'HH:mm', { locale: es })}
-
- ))}
-
- )}
-
- )}
-
-
-
-
- {selectedServiceData && selectedTime && (
-
-
-
-
Resumen de la reserva
-
-
Servicio: {selectedServiceData.name}
-
Fecha: {format(new Date(selectedDate), 'PPP', { locale: es })}
-
Hora: {format(new Date(selectedTime), 'HH:mm', { locale: es })}
-
Precio: ${selectedServiceData.base_price.toFixed(2)}
-
-
-
-
+
+
+ >
)}
-
- Continuar con Datos del Cliente
-
+ {currentStep === 'datetime' && (
+ <>
+
+
+
+
+ Fecha y Hora
+
+
+ Selecciona la fecha y hora disponible
+
+
+
+
+
+ Fecha
+
+
+ {errors.date &&
{errors.date}
}
+
+
+ {loading ? (
+
+ Cargando horarios...
+
+ ) : (
+
+
+ Horarios disponibles
+
+ {timeSlots.length === 0 ? (
+
+ No hay horarios disponibles para esta fecha. Selecciona otra fecha.
+
+ ) : (
+
+ {timeSlots.map((slot, index) => {
+ const slotTime = new Date(slot.start_time)
+ return (
+ 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 })}
+
+ )
+ })}
+
+ )}
+ {errors.time &&
{errors.time}
}
+
+ )}
+
+
+
+ {selectedServiceData && (
+
+ Duración del servicio: {selectedServiceData.duration_minutes} minutos
+
+ )}
+ >
+ )}
+
+ {currentStep === 'confirm' && selectedServiceData && selectedLocationData && selectedDate && selectedTime && (
+ <>
+
+
+
+
Resumen de la reserva
+
+
Servicio
+
{selectedServiceData.name}
+
+
+
Ubicación
+
{selectedLocationData.name}
+
+
+
Fecha
+
{format(selectedDate, 'PPP', { locale: es })}
+
+
+
Hora
+
{format(parseISO(selectedTime), 'HH:mm', { locale: es })}
+
+
+
Duración
+
{selectedServiceData.duration_minutes} minutos
+
+
+
Precio
+
${selectedServiceData.base_price.toFixed(2)} USD
+
+
+
+
+ >
+ )}
+
+ {currentStep === 'confirm' && (
+
+ Confirmar cita
+
+ )}
+
+ {currentStep !== 'confirm' && (
+ <>
+
+ {currentStep === 'service' ? 'Continuar: Seleccionar fecha y hora' : 'Continuar: Confirmar cita'}
+
+
+ {currentStep !== 'service' && (
+
+ Atrás
+
+ )}
+ >
+ )}
)
-}
+}
\ No newline at end of file
diff --git a/app/globals.css b/app/globals.css
index a287f30..e564daf 100644
--- a/app/globals.css
+++ b/app/globals.css
@@ -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);
+ }
}
diff --git a/components/booking/date-picker.tsx b/components/booking/date-picker.tsx
new file mode 100644
index 0000000..1b91e4c
--- /dev/null
+++ b/components/booking/date-picker.tsx
@@ -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 (
+
+
+
+
+
+
+ {format(currentMonth, 'MMMM yyyy', { locale: es })}
+
+
+
+
+
+
+
+ {['L', 'M', 'X', 'J', 'V', 'S', 'D'].map((day, index) => (
+
+ {day}
+
+ ))}
+
+
+
+ {days.map((date, index) => {
+ const disabled = isDateDisabled(date)
+ const selected = isDateSelected(date)
+ const today = isToday(date)
+ const notCurrentMonth = !isSameMonth(date, currentMonth)
+
+ return (
+ !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 && (
+
+ )}
+
+ )
+ })}
+
+
+ )
+}
\ No newline at end of file
diff --git a/components/booking/mock-payment-form.tsx b/components/booking/mock-payment-form.tsx
new file mode 100644
index 0000000..146a9ba
--- /dev/null
+++ b/components/booking/mock-payment-form.tsx
@@ -0,0 +1,210 @@
+import { useState } from 'react'
+import { CreditCard, Lock } from 'lucide-react'
+
+interface MockPaymentFormProps {
+ amount: number
+ onSubmit: (paymentMethod: any) => Promise
+ 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>({})
+
+ 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 = {}
+
+ 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) => {
+ const formatted = formatCardNumber(e.target.value)
+ if (formatted.length <= 19) {
+ setCardNumber(formatted)
+ }
+ }
+
+ const handleExpiryChange = (e: React.ChangeEvent) => {
+ const formatted = formatExpiry(e.target.value)
+ if (formatted.length <= 5) {
+ setExpiry(formatted)
+ }
+ }
+
+ return (
+
+
+
+
+ Pago Seguro (Demo Mode)
+
+
+
+
+
+ )
+}
\ No newline at end of file
diff --git a/components/ui/select.tsx b/components/ui/select.tsx
index 21b39cf..4e62f8b 100644
--- a/components/ui/select.tsx
+++ b/components/ui/select.tsx
@@ -20,14 +20,14 @@ const SelectTrigger = React.forwardRef<
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}
-
+
))
@@ -46,6 +46,7 @@ const SelectScrollUpButton = React.forwardRef<
"flex cursor-default items-center justify-center py-1",
className
)}
+ style={{ color: 'var(--charcoal-brown)' }}
{...props}
>
@@ -66,6 +67,7 @@ const SelectScrollDownButton = React.forwardRef<
"flex cursor-default items-center justify-center py-1",
className
)}
+ style={{ color: 'var(--charcoal-brown)' }}
{...props}
>
@@ -84,7 +86,7 @@ const SelectContent = React.forwardRef<
-
+
@@ -158,7 +160,8 @@ const SelectSeparator = React.forwardRef<
>(({ className, ...props }, ref) => (
))
diff --git a/lib/db/types.ts b/lib/db/types.ts
index f299d8d..bc4dde2 100644
--- a/lib/db/types.ts
+++ b/lib/db/types.ts
@@ -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
- Update: Partial>
+ Insert: Omit & { business_hours?: BusinessHours }
+ Update: Partial & { business_hours?: BusinessHours }>
}
resources: {
Row: Resource
diff --git a/lib/supabase/admin.ts b/lib/supabase/admin.ts
new file mode 100644
index 0000000..7e49386
--- /dev/null
+++ b/lib/supabase/admin.ts
@@ -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
+ }
+ }
+)
\ No newline at end of file
diff --git a/lib/supabase/client.ts b/lib/supabase/client.ts
index a0cff46..efd40ef 100644
--- a/lib/supabase/client.ts
+++ b/lib/supabase/client.ts
@@ -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
diff --git a/lib/utils/business-hours.ts b/lib/utils/business-hours.ts
new file mode 100644
index 0000000..a2614a6
--- /dev/null
+++ b/lib/utils/business-hours.ts
@@ -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])
+}
diff --git a/lib/utils/short-id.ts b/lib/utils/short-id.ts
index 62e4b8f..198f403 100644
--- a/lib/utils/short-id.ts
+++ b/lib/utils/short-id.ts
@@ -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.
diff --git a/scripts/add_business_hours.sql b/scripts/add_business_hours.sql
new file mode 100644
index 0000000..09519c0
--- /dev/null
+++ b/scripts/add_business_hours.sql
@@ -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;
diff --git a/scripts/debug_business_hours.sql b/scripts/debug_business_hours.sql
new file mode 100644
index 0000000..babf43a
--- /dev/null
+++ b/scripts/debug_business_hours.sql
@@ -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;
diff --git a/scripts/seed_booking_data.sql b/scripts/seed_booking_data.sql
new file mode 100644
index 0000000..a662c6e
--- /dev/null
+++ b/scripts/seed_booking_data.sql
@@ -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;
diff --git a/scripts/seed_test_data.sql b/scripts/seed_test_data.sql
new file mode 100644
index 0000000..5d7bef2
--- /dev/null
+++ b/scripts/seed_test_data.sql
@@ -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';
diff --git a/scripts/test_availability_functions.sql b/scripts/test_availability_functions.sql
new file mode 100644
index 0000000..c13ac83
--- /dev/null
+++ b/scripts/test_availability_functions.sql
@@ -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;
diff --git a/scripts/test_data_check.sql b/scripts/test_data_check.sql
new file mode 100644
index 0000000..2e72a5b
--- /dev/null
+++ b/scripts/test_data_check.sql
@@ -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;
diff --git a/scripts/update_availability_function.sql b/scripts/update_availability_function.sql
new file mode 100644
index 0000000..d97b1e1
--- /dev/null
+++ b/scripts/update_availability_function.sql
@@ -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;
diff --git a/scripts/update_business_hours.sql b/scripts/update_business_hours.sql
new file mode 100644
index 0000000..fd18175
--- /dev/null
+++ b/scripts/update_business_hours.sql
@@ -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
+);
diff --git a/scripts/update_business_hours_final.sql b/scripts/update_business_hours_final.sql
new file mode 100644
index 0000000..f118e73
--- /dev/null
+++ b/scripts/update_business_hours_final.sql
@@ -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;
diff --git a/supabase/migrations/20260116100000_create_availability_tables.sql b/supabase/migrations/20260116100000_create_availability_tables.sql
index 89ed842..79fa6c3 100644
--- a/supabase/migrations/20260116100000_create_availability_tables.sql
+++ b/supabase/migrations/20260116100000_create_availability_tables.sql
@@ -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,
diff --git a/supabase/migrations/20260117000000_add_services_category.sql b/supabase/migrations/20260117000000_add_services_category.sql
new file mode 100644
index 0000000..67eb87e
--- /dev/null
+++ b/supabase/migrations/20260117000000_add_services_category.sql
@@ -0,0 +1,2 @@
+-- Add category column to services table
+ALTER TABLE services ADD COLUMN IF NOT EXISTS category VARCHAR(50) DEFAULT 'General';
\ No newline at end of file
diff --git a/supabase/migrations/20260117010000_add_location_business_hours.sql b/supabase/migrations/20260117010000_add_location_business_hours.sql
new file mode 100644
index 0000000..6ffb454
--- /dev/null
+++ b/supabase/migrations/20260117010000_add_location_business_hours.sql
@@ -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;
diff --git a/supabase/migrations/20260117020000_update_availability_function.sql b/supabase/migrations/20260117020000_update_availability_function.sql
new file mode 100644
index 0000000..95f9cdb
--- /dev/null
+++ b/supabase/migrations/20260117020000_update_availability_function.sql
@@ -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;
diff --git a/supabase/migrations/20260117030000_fix_availability_type_casting.sql b/supabase/migrations/20260117030000_fix_availability_type_casting.sql
new file mode 100644
index 0000000..4a4f7e1
--- /dev/null
+++ b/supabase/migrations/20260117030000_fix_availability_type_casting.sql
@@ -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;
diff --git a/supabase/migrations/20260117040000_complete_availability_fix.sql b/supabase/migrations/20260117040000_complete_availability_fix.sql
new file mode 100644
index 0000000..06bfb6f
--- /dev/null
+++ b/supabase/migrations/20260117040000_complete_availability_fix.sql
@@ -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;
diff --git a/supabase/migrations/20260117050000_fix_business_hours_json.sql b/supabase/migrations/20260117050000_fix_business_hours_json.sql
new file mode 100644
index 0000000..769309a
--- /dev/null
+++ b/supabase/migrations/20260117050000_fix_business_hours_json.sql
@@ -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;
diff --git a/supabase/migrations/20260117060000_update_business_hours_data.sql b/supabase/migrations/20260117060000_update_business_hours_data.sql
new file mode 100644
index 0000000..df939e9
--- /dev/null
+++ b/supabase/migrations/20260117060000_update_business_hours_data.sql
@@ -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;