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
This commit is contained in:
Marco Gallegos
2026-01-16 10:51:12 -06:00
parent c770d4ebf9
commit fed5cb6850
33 changed files with 6152 additions and 80 deletions

View File

@@ -0,0 +1,145 @@
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 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 isActive = searchParams.get('is_active')
let query = supabaseAdmin
.from('kiosks')
.select(`
id,
location_id,
device_name,
display_name,
ip_address,
is_active,
created_at,
updated_at,
location (
id,
name,
timezone
)
`)
if (locationId) {
query = query.eq('location_id', locationId)
}
if (isActive !== null) {
query = query.eq('is_active', isActive === 'true')
}
const { data: kiosks, error: kiosksError } = await query.order('created_at', { ascending: false })
if (kiosksError) {
return NextResponse.json(
{ error: kiosksError.message },
{ status: 400 }
)
}
return NextResponse.json({ kiosks })
} catch (error) {
console.error('Admin kiosks GET error:', error)
return NextResponse.json(
{ error: 'Internal server error' },
{ status: 500 }
)
}
}
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,
device_name,
display_name,
ip_address
} = body
if (!location_id || !device_name || !display_name) {
return NextResponse.json(
{ error: 'Missing required fields: location_id, device_name, display_name' },
{ status: 400 }
)
}
const { data: existingKiosk } = await supabaseAdmin
.from('kiosks')
.select('id')
.eq('device_name', device_name)
.single()
if (existingKiosk) {
return NextResponse.json(
{ error: 'A kiosk with this device_name already exists' },
{ status: 400 }
)
}
const { data: kiosk, error: kioskError } = await supabaseAdmin.rpc('create_kiosk', {
p_location_id: location_id,
p_device_name: device_name,
p_display_name: display_name,
p_ip_address: ip_address
})
if (kioskError || !kiosk) {
return NextResponse.json(
{ error: kioskError?.message || 'Failed to create kiosk' },
{ status: 400 }
)
}
return NextResponse.json({
success: true,
kiosk,
message: 'Kiosk created successfully. Save the API key securely.'
}, { status: 201 })
} catch (error) {
console.error('Admin kiosks POST error:', error)
return NextResponse.json(
{ error: 'Internal server error' },
{ status: 500 }
)
}
}

View File

@@ -0,0 +1,51 @@
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 GET(request: NextRequest) {
try {
const isAdmin = await validateAdmin(request)
if (!isAdmin) {
return NextResponse.json(
{ error: 'Unauthorized' },
{ status: 401 }
)
}
const { data: locations, error } = await supabaseAdmin
.from('locations')
.select('*')
.order('name', { ascending: true })
if (error) {
return NextResponse.json(
{ error: error.message },
{ status: 400 }
)
}
return NextResponse.json({ locations })
} catch (error) {
console.error('Admin locations GET error:', error)
return NextResponse.json(
{ error: 'Internal server error' },
{ status: 500 }
)
}
}

View File

@@ -0,0 +1,179 @@
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 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 role = searchParams.get('role')
let query = supabaseAdmin
.from('staff')
.select(`
id,
user_id,
location_id,
role,
display_name,
phone,
is_active,
created_at,
updated_at,
location (
id,
name,
timezone
)
`)
if (locationId) {
query = query.eq('location_id', locationId)
}
if (role) {
query = query.eq('role', role)
}
const { data: staff, error: staffError } = await query.order('created_at', { ascending: false })
if (staffError) {
return NextResponse.json(
{ error: staffError.message },
{ status: 400 }
)
}
return NextResponse.json({ staff })
} catch (error) {
console.error('Admin users GET error:', error)
return NextResponse.json(
{ error: 'Internal server error' },
{ status: 500 }
)
}
}
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,
role,
display_name,
phone,
email,
password,
first_name,
last_name
} = body
if (!location_id || !role || !display_name) {
return NextResponse.json(
{ error: 'Missing required fields: location_id, role, display_name' },
{ status: 400 }
)
}
if (!['admin', 'manager', 'staff', 'artist'].includes(role)) {
return NextResponse.json(
{ error: 'Invalid role. Must be: admin, manager, staff, or artist' },
{ status: 400 }
)
}
if (!email || !password) {
return NextResponse.json(
{ error: 'Email and password are required to create auth user' },
{ status: 400 }
)
}
const { data: authUser, error: authError } = await supabaseAdmin.auth.admin.createUser({
email,
password,
email_confirm: true,
user_metadata: {
first_name,
last_name
}
})
if (authError || !authUser) {
return NextResponse.json(
{ error: authError?.message || 'Failed to create auth user' },
{ status: 400 }
)
}
const { data: staff, error: staffError } = await supabaseAdmin
.from('staff')
.insert({
user_id: authUser.user.id,
location_id,
role,
display_name,
phone,
is_active: true
})
.select()
.single()
if (staffError || !staff) {
return NextResponse.json(
{ error: staffError?.message || 'Failed to create staff record' },
{ status: 400 }
)
}
return NextResponse.json({
success: true,
staff: {
...staff,
email: authUser.user.email,
first_name: authUser.user.user_metadata?.first_name,
last_name: authUser.user.user_metadata?.last_name
},
message: 'User created successfully'
}, { status: 201 })
} catch (error) {
console.error('Admin users POST error:', error)
return NextResponse.json(
{ error: 'Internal server error' },
{ status: 500 }
)
}
}