Files
AnchorOS/app/api/kiosk/walkin/route.ts
Marco Gallegos fed5cb6850 feat: Implementar sistema de kiosko, enrollment e integración Telegram
## Sistema de Kiosko 
- Nuevo rol 'kiosk' en enum user_role
- Tabla kiosks con autenticación por API key (64 caracteres)
- Funciones SQL: generate_kiosk_api_key(), is_kiosk(), get_available_resources_with_priority()
- API Routes: authenticate, bookings (GET/POST), confirm, resources/available, walkin
- Componentes UI: BookingConfirmation, WalkInFlow, ResourceAssignment
- Página kiosko: /kiosk/[locationId]/page.tsx

## Sistema de Enrollment 
- API routes para administración: /api/admin/users, /api/admin/kiosks, /api/admin/locations
- Frontend enrollment: /admin/enrollment con autenticación por ADMIN_KEY
- Creación de staff (admin, manager, staff, artist) con Supabase Auth
- Creación de kiosks con generación automática de API key
- Componentes UI: card, button, input, label, select, tabs

## Actualización de Recursos 
- Reemplazo de recursos con códigos estándarizados
- Estructura por location: 3 mkup, 1 lshs, 4 pedi, 4 mani
- Migración de limpieza: elimina duplicados
- Total: 12 recursos por location

## Integración Telegram y Scoring 
- Campos agregados a staff: telegram_id, email, gmail, google_account, telegram_chat_id
- Sistema de scoring: performance_score, total_bookings_completed, total_guarantees_count
- Tablas: telegram_notifications, telegram_groups, telegram_bots
- Funciones: update_staff_performance_score(), get_top_performers(), get_performance_summary()
- Triggers automáticos: notificaciones al crear/confirmar/completar booking
- Cálculo de score: base 50 +10 por booking +5 por garantía +1 por $100

## Actualización de Tipos 
- UserRole: agregado 'kiosk'
- CustomerTier: agregado 'black', 'VIP'
- Nuevas interfaces: Kiosk

## Documentación 
- KIOSK_SYSTEM.md: Documentación completa del sistema
- KIOSK_IMPLEMENTATION.md: Guía rápida
- ENROLLMENT_SYSTEM.md: Sistema de enrollment
- RESOURCES_UPDATE.md: Actualización de recursos
- PROJECT_UPDATE_JAN_2026.md: Resumen de proyecto

## Componentes UI (7)
- button.tsx, card.tsx, input.tsx, label.tsx, select.tsx, tabs.tsx

## Migraciones SQL (4)
- 20260116000000_add_kiosk_system.sql
- 20260116010000_update_resources.sql
- 20260116020000_cleanup_and_fix_resources.sql
- 20260116030000_telegram_integration.sql

## Métricas
- ~7,500 líneas de código
- 32 archivos creados/modificados
- 7 componentes UI
- 10 API routes
- 4 migraciones SQL
2026-01-16 10:51:12 -06:00

183 lines
4.6 KiB
TypeScript

import { NextRequest, NextResponse } from 'next/server'
import { supabase } 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
.from('kiosks')
.select('id, location_id, is_active')
.eq('api_key', apiKey)
.eq('is_active', true)
.single()
return kiosk
}
export async function POST(request: NextRequest) {
try {
const kiosk = await validateKiosk(request)
if (!kiosk) {
return NextResponse.json(
{ error: 'Unauthorized' },
{ status: 401 }
)
}
const body = await request.json()
const {
customer_email,
customer_phone,
customer_name,
service_id,
notes
} = body
if (!customer_email || !service_id) {
return NextResponse.json(
{ error: 'Missing required fields: customer_email, service_id' },
{ status: 400 }
)
}
const { data: service, error: serviceError } = await supabase
.from('services')
.select('*')
.eq('id', service_id)
.eq('is_active', true)
.single()
if (serviceError || !service) {
return NextResponse.json(
{ error: 'Invalid service_id' },
{ status: 400 }
)
}
const { data: availableStaff } = await supabase
.from('staff')
.select('id, display_name, role')
.eq('location_id', kiosk.location_id)
.eq('is_active', true)
.in('role', ['artist', 'staff', 'manager'])
if (!availableStaff || availableStaff.length === 0) {
return NextResponse.json(
{ error: 'No staff available' },
{ status: 400 }
)
}
const assignedStaff = availableStaff[0]
const startTime = new Date()
const endTime = new Date(startTime)
endTime.setMinutes(endTime.getMinutes() + service.duration_minutes)
const { data: availableResources } = await supabase
.rpc('get_available_resources_with_priority', {
p_location_id: kiosk.location_id,
p_start_time: startTime.toISOString(),
p_end_time: endTime.toISOString()
})
if (!availableResources || availableResources.length === 0) {
return NextResponse.json(
{ error: 'No resources available for immediate booking' },
{ status: 400 }
)
}
const assignedResource = availableResources[0]
const { data: customer, error: customerError } = await supabase
.from('customers')
.upsert({
email: customer_email,
first_name: customer_name?.split(' ')[0] || 'Cliente',
last_name: customer_name?.split(' ').slice(1).join(' ') || 'Walk-in',
phone: customer_phone,
tier: 'free',
is_active: true
})
.select()
.single()
if (customerError || !customer) {
return NextResponse.json(
{ error: 'Failed to create/find customer' },
{ status: 400 }
)
}
const { data: booking, error: bookingError } = await supabase
.from('bookings')
.insert({
customer_id: customer.id,
staff_id: assignedStaff.id,
location_id: kiosk.location_id,
resource_id: assignedResource.resource_id,
service_id,
start_time_utc: startTime.toISOString(),
end_time_utc: endTime.toISOString(),
status: 'confirmed',
deposit_amount: 0,
total_amount: service.base_price,
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
)
`)
.single()
if (bookingError || !booking) {
return NextResponse.json(
{ error: bookingError?.message || 'Failed to create walk-in booking' },
{ status: 400 }
)
}
return NextResponse.json({
success: true,
booking: {
...booking,
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) {
console.error('Kiosk walk-in error:', error)
return NextResponse.json(
{ error: 'Internal server error' },
{ status: 500 }
)
}
}