feat: Implementar sistema de disponibilidad y corregir errores de kiosko

- Agregar API routes de disponibilidad (blocks, staff, time-slots, staff-unavailable)
- Corregir autenticación en availability routes (reemplazar get_current_user_role con validación Bearer)
- Corregir DELETE en blocks/route.ts para usar query parameters
- Corregir errores de tipos en kiosk routes (supabase → supabaseAdmin)
- Agregar layout raíz de Next.js y estilos globales
- Agregar componente Badge UI
- Corregir tipos TypeScript en WalkInFlow
- Instalar dependencias necesarias (@radix-ui/*, class-variance-authority, etc)
- Agregar migraciones de disponibilidad
This commit is contained in:
Marco Gallegos
2026-01-16 15:12:57 -06:00
parent 631e60376c
commit accf0e81e1
23 changed files with 8263 additions and 152 deletions

View File

@@ -0,0 +1,200 @@
import { NextRequest, NextResponse } from 'next/server'
import { supabaseAdmin } from '@/lib/supabase/client'
async function validateAdmin(request: NextRequest) {
const authHeader = request.headers.get('authorization')
if (!authHeader) {
return null
}
const token = authHeader.replace('Bearer ', '')
if (token !== process.env.ADMIN_ENROLLMENT_KEY) {
return null
}
return true
}
export async function POST(request: NextRequest) {
try {
const isAdmin = await validateAdmin(request)
if (!isAdmin) {
return NextResponse.json(
{ error: 'Unauthorized' },
{ status: 401 }
)
}
const body = await request.json()
const {
location_id,
resource_id,
start_time_utc,
end_time_utc,
reason
} = body
if (!location_id || !resource_id || !start_time_utc || !end_time_utc) {
return NextResponse.json(
{ error: 'Missing required fields: location_id, resource_id, start_time_utc, end_time_utc' },
{ status: 400 }
)
}
const { data: block, error: blockError } = await supabaseAdmin
.from('booking_blocks')
.insert({
location_id,
resource_id,
start_time_utc,
end_time_utc,
reason
})
.select()
.single()
if (blockError || !block) {
return NextResponse.json(
{ error: blockError?.message || 'Failed to create booking block' },
{ status: 400 }
)
}
return NextResponse.json({
success: true,
block
})
} catch (error) {
console.error('Booking blocks POST error:', error)
return NextResponse.json(
{ error: 'Internal server error' },
{ status: 500 }
)
}
}
export async function GET(request: NextRequest) {
try {
const isAdmin = await validateAdmin(request)
if (!isAdmin) {
return NextResponse.json(
{ error: 'Unauthorized' },
{ status: 401 }
)
}
const { searchParams } = new URL(request.url)
const locationId = searchParams.get('location_id')
const startDate = searchParams.get('start_date')
const endDate = searchParams.get('end_date')
let query = supabaseAdmin
.from('booking_blocks')
.select(`
id,
location_id,
resource_id,
start_time_utc,
end_time_utc,
reason,
created_at,
location (
id,
name
),
resource (
id,
name,
type
),
created_by (
id,
display_name
)
`)
if (locationId) {
query = query.eq('location_id', locationId)
}
if (startDate) {
query = query.gte('start_time_utc', startDate)
}
if (endDate) {
query = query.lte('end_time_utc', endDate)
}
const { data: blocks, error } = await query.order('start_time_utc', { ascending: true })
if (error) {
return NextResponse.json(
{ error: error.message },
{ status: 400 }
)
}
return NextResponse.json({
blocks: blocks || [],
total: blocks?.length || 0
})
} catch (error) {
console.error('Booking blocks GET error:', error)
return NextResponse.json(
{ error: 'Internal server error' },
{ status: 500 }
)
}
}
export async function DELETE(request: NextRequest) {
try {
const isAdmin = await validateAdmin(request)
if (!isAdmin) {
return NextResponse.json(
{ error: 'Unauthorized' },
{ status: 401 }
)
}
const { searchParams } = new URL(request.url)
const blockId = searchParams.get('id')
if (!blockId) {
return NextResponse.json(
{ error: 'Missing required parameter: id' },
{ status: 400 }
)
}
const { data: block, error: blockError } = await supabaseAdmin
.from('booking_blocks')
.delete()
.eq('id', blockId)
.select()
.single()
if (blockError) {
return NextResponse.json(
{ error: blockError?.message || 'Block not found' },
{ status: 404 }
)
}
return NextResponse.json({
success: true,
message: 'Booking block deleted successfully'
})
} catch (error) {
console.error('Booking blocks DELETE error:', error)
return NextResponse.json(
{ error: 'Internal server error' },
{ status: 500 }
)
}
}

View File

@@ -0,0 +1,178 @@
import { NextRequest, NextResponse } from 'next/server'
import { supabaseAdmin } from '@/lib/supabase/client'
async function validateAdminOrStaff(request: NextRequest) {
const authHeader = request.headers.get('authorization')
if (!authHeader) {
return null
}
const token = authHeader.replace('Bearer ', '')
if (token !== process.env.ADMIN_ENROLLMENT_KEY) {
return null
}
return true
}
export async function POST(request: NextRequest) {
try {
const hasAccess = await validateAdminOrStaff(request)
if (!hasAccess) {
return NextResponse.json(
{ error: 'Unauthorized' },
{ status: 401 }
)
}
const body = await request.json()
const {
staff_id,
date,
start_time,
end_time,
reason,
location_id
} = body
if (!staff_id || !date || !start_time || !end_time) {
return NextResponse.json(
{ error: 'Missing required fields: staff_id, date, start_time, end_time' },
{ status: 400 }
)
}
const { data: staff, error: staffError } = await supabaseAdmin
.from('staff')
.select('id, location_id')
.eq('id', staff_id)
.single()
if (staffError || !staff) {
return NextResponse.json(
{ error: staffError?.message || 'Staff not found' },
{ status: 400 }
)
}
const { data: availability, error: availabilityError } = await supabaseAdmin.rpc('check_staff_availability', {
p_staff_id: staff_id,
p_start_time_utc: `${date}T${start_time}Z`,
p_end_time_utc: `${date}T${end_time}Z`
})
if (availabilityError) {
return NextResponse.json(
{ error: availabilityError.message },
{ status: 400 }
)
}
const { data: existingAvailability } = await supabaseAdmin
.from('staff_availability')
.select('*')
.eq('staff_id', staff_id)
.eq('date', date)
.single()
if (existingAvailability) {
return NextResponse.json(
{ error: 'Availability already exists for this staff and date' },
{ status: 400 }
)
}
const { data: newAvailability, error: createError } = await supabaseAdmin
.from('staff_availability')
.insert({
staff_id,
date,
start_time,
end_time,
is_available: false,
reason,
created_by: staff_id
})
.select()
.single()
if (createError) {
return NextResponse.json(
{ error: createError.message },
{ status: 400 }
)
}
return NextResponse.json({
success: true,
availability: newAvailability
})
} catch (error) {
console.error('Staff unavailable POST error:', error)
return NextResponse.json(
{ error: 'Internal server error' },
{ status: 500 }
)
}
}
export async function GET(request: NextRequest) {
try {
const hasAccess = await validateAdminOrStaff(request)
if (!hasAccess) {
return NextResponse.json(
{ error: 'Unauthorized' },
{ status: 401 }
)
}
const { searchParams } = new URL(request.url)
const staffId = searchParams.get('staff_id')
const startDate = searchParams.get('start_date')
const endDate = searchParams.get('end_date')
if (!staffId) {
return NextResponse.json(
{ error: 'Missing required parameter: staff_id' },
{ status: 400 }
)
}
let query = supabaseAdmin
.from('staff_availability')
.select('*')
.eq('staff_id', staffId)
if (startDate) {
query = query.gte('date', startDate)
}
if (endDate) {
query = query.lte('date', endDate)
}
const { data: availabilityList, error } = await query.order('date', { ascending: true })
if (error) {
return NextResponse.json(
{ error: error.message },
{ status: 400 }
)
}
return NextResponse.json({
success: true,
availability: availabilityList || []
})
} catch (error) {
console.error('Staff unavailable GET error:', error)
return NextResponse.json(
{ error: 'Internal server error' },
{ status: 500 }
)
}
}

View File

@@ -0,0 +1,46 @@
import { NextRequest, NextResponse } from 'next/server'
import { supabaseAdmin } from '@/lib/supabase/client'
export async function GET(request: NextRequest) {
try {
const { searchParams } = new URL(request.url)
const locationId = searchParams.get('location_id')
const startTime = searchParams.get('start_time_utc')
const endTime = searchParams.get('end_time_utc')
if (!locationId || !startTime || !endTime) {
return NextResponse.json(
{ error: 'Missing required parameters: location_id, start_time_utc, end_time_utc' },
{ status: 400 }
)
}
const { data: staff, error: staffError } = await supabaseAdmin.rpc('get_available_staff', {
p_location_id: locationId,
p_start_time_utc: startTime,
p_end_time_utc: endTime
})
if (staffError) {
return NextResponse.json(
{ error: staffError.message },
{ status: 400 }
)
}
return NextResponse.json({
success: true,
staff: staff || [],
location_id: locationId,
start_time_utc: startTime,
end_time_utc: endTime,
available_count: staff?.length || 0
})
} catch (error) {
console.error('Available staff GET error:', error)
return NextResponse.json(
{ error: 'Internal server error' },
{ status: 500 }
)
}
}

View File

@@ -0,0 +1,46 @@
import { NextRequest, NextResponse } from 'next/server'
import { supabaseAdmin } from '@/lib/supabase/client'
export async function GET(request: NextRequest) {
try {
const { searchParams } = new URL(request.url)
const locationId = searchParams.get('location_id')
const serviceId = searchParams.get('service_id')
const date = searchParams.get('date')
if (!locationId || !date) {
return NextResponse.json(
{ error: 'Missing required parameters: location_id, date' },
{ status: 400 }
)
}
const timeSlotDuration = parseInt(searchParams.get('time_slot_duration_minutes') || '60', 10);
const { data: availability, error } = await supabaseAdmin.rpc('get_detailed_availability', {
p_location_id: locationId,
p_service_id: serviceId,
p_date: date,
p_time_slot_duration_minutes: timeSlotDuration
})
if (error) {
console.error('RPC error:', error);
return NextResponse.json(
{ error: error.message },
{ status: 400 }
)
}
return NextResponse.json({
success: true,
availability
})
} catch (error) {
console.error('Time slots GET error:', error)
return NextResponse.json(
{ error: 'Internal server error' },
{ status: 500 }
)
}
}

View File

@@ -1,10 +1,12 @@
import { NextRequest, NextResponse } from 'next/server'
import { supabase } from '@/lib/supabase/client'
import { supabaseAdmin } from '@/lib/supabase/client'
import { Kiosk } from '@/lib/db/types'
export async function POST(request: NextRequest) {
try {
const { api_key } = await request.json()
const body = await request.json()
console.log('Auth request body:', body)
const { api_key } = body
if (!api_key || typeof api_key !== 'string') {
return NextResponse.json(
@@ -13,7 +15,8 @@ export async function POST(request: NextRequest) {
)
}
const { data: kiosk, error } = await supabase
console.log('Querying kiosk with api_key:', api_key)
const { data: kiosk, error } = await supabaseAdmin
.from('kiosks')
.select(`
id,
@@ -21,7 +24,7 @@ export async function POST(request: NextRequest) {
device_name,
display_name,
is_active,
location (
locations (
id,
name,
timezone
@@ -31,7 +34,10 @@ export async function POST(request: NextRequest) {
.eq('is_active', true)
.single()
console.log('Kiosk query result:', { error, kiosk })
if (error || !kiosk) {
console.log('Authentication failed:', error || 'Kiosk not found')
return NextResponse.json(
{ error: 'Invalid API key or kiosk not active' },
{ status: 401 }
@@ -46,7 +52,7 @@ export async function POST(request: NextRequest) {
device_name: kiosk.device_name,
display_name: kiosk.display_name,
is_active: kiosk.is_active,
location: kiosk.location
location: kiosk.locations
}
})
} catch (error) {

View File

@@ -1,14 +1,14 @@
import { NextRequest, NextResponse } from 'next/server'
import { supabase } from '@/lib/supabase/client'
import { supabaseAdmin } from '@/lib/supabase/client'
async function validateKiosk(request: NextRequest) {
const apiKey = request.headers.get('x-kiosk-api-key')
if (!apiKey) {
return null
}
const { data: kiosk } = await supabase
const { data: kiosk } = await supabaseAdmin
.from('kiosks')
.select('id, location_id, is_active')
.eq('api_key', apiKey)
@@ -34,7 +34,7 @@ export async function POST(
const shortId = params.shortId
const { data: booking, error: fetchError } = await supabase
const { data: booking, error: fetchError } = await supabaseAdmin
.from('bookings')
.select('id, status, location_id')
.eq('short_id', shortId)
@@ -61,31 +61,11 @@ export async function POST(
)
}
const { data: updatedBooking, error: updateError } = await supabase
const { data: updatedBooking, error: updateError } = await supabaseAdmin
.from('bookings')
.update({ status: 'confirmed' })
.eq('id', booking.id)
.select(`
id,
short_id,
status,
start_time_utc,
end_time_utc,
service (
id,
name,
duration_minutes
),
resource (
id,
name,
type
),
staff (
id,
display_name
)
`)
.select('id, short_id, status, start_time_utc, end_time_utc')
.single()
if (updateError || !updatedBooking) {

View File

@@ -1,14 +1,14 @@
import { NextRequest, NextResponse } from 'next/server'
import { supabase } from '@/lib/supabase/client'
import { supabaseAdmin } from '@/lib/supabase/client'
async function validateKiosk(request: NextRequest) {
const apiKey = request.headers.get('x-kiosk-api-key')
if (!apiKey) {
return null
}
const { data: kiosk } = await supabase
const { data: kiosk } = await supabaseAdmin
.from('kiosks')
.select('id, location_id, is_active')
.eq('api_key', apiKey)
@@ -33,29 +33,9 @@ export async function GET(request: NextRequest) {
const short_id = searchParams.get('short_id')
const date = searchParams.get('date')
let query = supabase
let query = supabaseAdmin
.from('bookings')
.select(`
id,
short_id,
status,
start_time_utc,
end_time_utc,
service (
id,
name,
duration_minutes
),
resource (
id,
name,
type
),
staff (
id,
display_name
)
`)
.select()
.eq('location_id', kiosk.location_id)
.in('status', ['pending', 'confirmed'])
@@ -121,7 +101,7 @@ export async function POST(request: NextRequest) {
)
}
const { data: service, error: serviceError } = await supabase
const { data: service, error: serviceError } = await supabaseAdmin
.from('services')
.select('*')
.eq('id', service_id)
@@ -139,7 +119,7 @@ export async function POST(request: NextRequest) {
const endTime = new Date(startTime)
endTime.setMinutes(endTime.getMinutes() + service.duration_minutes)
const { data: availableResources } = await supabase
const { data: availableResources } = await supabaseAdmin
.rpc('get_available_resources_with_priority', {
p_location_id: kiosk.location_id,
p_start_time: startTime.toISOString(),
@@ -155,7 +135,7 @@ export async function POST(request: NextRequest) {
const assignedResource = availableResources[0]
const { data: customer, error: customerError } = await supabase
const { data: customer, error: customerError } = await supabaseAdmin
.from('customers')
.upsert({
email: customer_email,
@@ -175,7 +155,7 @@ export async function POST(request: NextRequest) {
)
}
const { data: booking, error: bookingError } = await supabase
const { data: booking, error: bookingError } = await supabaseAdmin
.from('bookings')
.insert({
customer_id: customer.id,
@@ -191,28 +171,7 @@ export async function POST(request: NextRequest) {
is_paid: false,
notes
})
.select(`
id,
short_id,
status,
start_time_utc,
end_time_utc,
service (
id,
name,
duration_minutes,
base_price
),
resource (
id,
name,
type
),
staff (
id,
display_name
)
`)
.select('id, short_id, status, start_time_utc, end_time_utc')
.single()
if (bookingError || !booking) {
@@ -224,11 +183,10 @@ export async function POST(request: NextRequest) {
return NextResponse.json({
success: true,
booking: {
...booking,
resource_name: assignedResource.resource_name,
resource_type: assignedResource.resource_type
}
booking,
service_name: service.name,
resource_name: assignedResource.resource_name,
resource_type: assignedResource.resource_type
}, { status: 201 })
} catch (error) {
console.error('Kiosk bookings POST error:', error)

View File

@@ -1,5 +1,5 @@
import { NextRequest, NextResponse } from 'next/server'
import { supabase } from '@/lib/supabase/client'
import { supabaseAdmin } from '@/lib/supabase/client'
async function validateKiosk(request: NextRequest) {
const apiKey = request.headers.get('x-kiosk-api-key')
@@ -8,7 +8,7 @@ async function validateKiosk(request: NextRequest) {
return null
}
const { data: kiosk } = await supabase
const { data: kiosk } = await supabaseAdmin
.from('kiosks')
.select('id, location_id, is_active')
.eq('api_key', apiKey)
@@ -51,7 +51,7 @@ export async function GET(request: NextRequest) {
)
}
let resourceQuery = supabase
let resourceQuery = supabaseAdmin
.rpc('get_available_resources_with_priority', {
p_location_id: kiosk.location_id,
p_start_time: startTime.toISOString(),
@@ -70,14 +70,14 @@ export async function GET(request: NextRequest) {
let availableResources = resources || []
if (service_id) {
const { data: service } = await supabase
const { data: service } = await supabaseAdmin
.from('services')
.select('requires_dual_artist')
.eq('id', service_id)
.single()
if (service?.requires_dual_artist) {
availableResources = availableResources.filter(r => r.resource_type === 'room')
availableResources = availableResources.filter((r: any) => r.resource_type === 'room')
}
}

View File

@@ -1,5 +1,5 @@
import { NextRequest, NextResponse } from 'next/server'
import { supabase } from '@/lib/supabase/client'
import { supabaseAdmin } from '@/lib/supabase/client'
async function validateKiosk(request: NextRequest) {
const apiKey = request.headers.get('x-kiosk-api-key')
@@ -8,7 +8,7 @@ async function validateKiosk(request: NextRequest) {
return null
}
const { data: kiosk } = await supabase
const { data: kiosk } = await supabaseAdmin
.from('kiosks')
.select('id, location_id, is_active')
.eq('api_key', apiKey)
@@ -45,7 +45,7 @@ export async function POST(request: NextRequest) {
)
}
const { data: service, error: serviceError } = await supabase
const { data: service, error: serviceError } = await supabaseAdmin
.from('services')
.select('*')
.eq('id', service_id)
@@ -59,7 +59,7 @@ export async function POST(request: NextRequest) {
)
}
const { data: availableStaff } = await supabase
const { data: availableStaff } = await supabaseAdmin
.from('staff')
.select('id, display_name, role')
.eq('location_id', kiosk.location_id)
@@ -79,7 +79,7 @@ export async function POST(request: NextRequest) {
const endTime = new Date(startTime)
endTime.setMinutes(endTime.getMinutes() + service.duration_minutes)
const { data: availableResources } = await supabase
const { data: availableResources } = await supabaseAdmin
.rpc('get_available_resources_with_priority', {
p_location_id: kiosk.location_id,
p_start_time: startTime.toISOString(),
@@ -95,7 +95,7 @@ export async function POST(request: NextRequest) {
const assignedResource = availableResources[0]
const { data: customer, error: customerError } = await supabase
const { data: customer, error: customerError } = await supabaseAdmin
.from('customers')
.upsert({
email: customer_email,
@@ -115,7 +115,7 @@ export async function POST(request: NextRequest) {
)
}
const { data: booking, error: bookingError } = await supabase
const { data: booking, error: bookingError } = await supabaseAdmin
.from('bookings')
.insert({
customer_id: customer.id,
@@ -131,28 +131,7 @@ export async function POST(request: NextRequest) {
is_paid: false,
notes: notes ? `${notes} [Walk-in]` : '[Walk-in]'
})
.select(`
id,
short_id,
status,
start_time_utc,
end_time_utc,
service (
id,
name,
duration_minutes,
base_price
),
resource (
id,
name,
type
),
staff (
id,
display_name
)
`)
.select('id, status, start_time_utc, end_time_utc, total_amount, is_paid')
.single()
if (bookingError || !booking) {
@@ -164,12 +143,11 @@ export async function POST(request: NextRequest) {
return NextResponse.json({
success: true,
booking: {
...booking,
resource_name: assignedResource.resource_name,
resource_type: assignedResource.resource_type,
staff_name: assignedStaff.display_name
},
booking,
service_name: service.name,
resource_name: assignedResource.resource_name,
resource_type: assignedResource.resource_type,
staff_name: assignedStaff.display_name,
message: 'Walk-in booking created successfully'
}, { status: 201 })
} catch (error) {