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

67
app/admin/README.md Normal file
View File

@@ -0,0 +1,67 @@
# Admin Enrollment System
Sistema de administración de usuarios y kiosks para SalonOS.
## Descripción
Este sistema permite a los administradores:
- Crear nuevos miembros de staff (admin, manager, staff, artist)
- Crear nuevos kiosks para cada location
- Ver listas de usuarios y kiosks existentes
- Gestionar locations activas
## Acceso
### URL
```
http://localhost:3000/admin/enrollment
```
### Autenticación
El sistema requiere una clave de administración para acceder. Configura esto en `.env.local`:
```env
ADMIN_ENROLLMENT_KEY=tu-clave-segura-aqui
```
## Seguridad
- Autenticación por Bearer token
- Validación de roles (admin, manager, staff, artist)
- API keys de kiosks generadas aleatoriamente (64 caracteres)
- Restricción opcional por IP address para kiosks
## Uso
### Crear Staff Member
1. Ingresa tu `ADMIN_ENROLLMENT_KEY`
2. Selecciona la tab "Staff Members"
3. Completa el formulario:
- Location
- Role (Admin, Manager, Staff, Artist)
- Display Name (público)
- First/Last Name (privado)
- Email (para autenticación)
- Password (contraseña inicial)
- Phone (opcional)
4. Haz clic en "Create Staff Member"
### Crear Kiosk
1. Ingresa tu `ADMIN_ENROLLMENT_KEY`
2. Selecciona la tab "Kiosks"
3. Completa el formulario:
- Location
- Device Name (identificador único)
- Display Name (nombre legible)
- IP Address (opcional, para restricción)
4. Haz clic en "Create Kiosk"
5. ⚠️ **IMPORTANTE**: Guarda el API Key generado de forma segura
## Documentación
- [Guía Completa](../docs/ENROLLMENT_SYSTEM.md)
- [Sistema de Kiosko](../docs/KIOSK_SYSTEM.md)
- [PRD](../PRD.md)

View File

@@ -0,0 +1,537 @@
'use client'
import { useState, useEffect } from 'react'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
import { Label } from '@/components/ui/label'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
export default function EnrollmentPage() {
const [adminKey, setAdminKey] = useState('')
const [isAuthenticated, setIsAuthenticated] = useState(false)
const [activeTab, setActiveTab] = useState<'staff' | 'kiosks'>('staff')
const [locations, setLocations] = useState<any[]>([])
const [loading, setLoading] = useState(false)
const [message, setMessage] = useState<{ type: 'success' | 'error', text: string } | null>(null)
const [staffForm, setStaffForm] = useState({
location_id: '',
role: 'staff',
display_name: '',
email: '',
password: '',
first_name: '',
last_name: '',
phone: ''
})
const [kioskForm, setKioskForm] = useState({
location_id: '',
device_name: '',
display_name: '',
ip_address: ''
})
const [staffList, setStaffList] = useState<any[]>([])
const [kioskList, setKioskList] = useState<any[]>([])
useEffect(() => {
const savedKey = localStorage.getItem('admin_enrollment_key')
if (savedKey) {
setAdminKey(savedKey)
setIsAuthenticated(true)
fetchLocations(savedKey)
}
}, [])
const authenticate = async () => {
if (!adminKey) {
setMessage({ type: 'error', text: 'Please enter the admin enrollment key' })
return
}
setLoading(true)
setMessage(null)
try {
const response = await fetch('/api/admin/locations', {
headers: {
'Authorization': `Bearer ${adminKey}`
}
})
if (response.ok) {
localStorage.setItem('admin_enrollment_key', adminKey)
setIsAuthenticated(true)
const data = await response.json()
setLocations(data.locations)
setMessage({ type: 'success', text: 'Authenticated successfully!' })
} else {
setMessage({ type: 'error', text: 'Invalid admin enrollment key' })
}
} catch (error) {
setMessage({ type: 'error', text: 'Authentication failed' })
} finally {
setLoading(false)
}
}
const fetchLocations = async (key: string) => {
try {
const response = await fetch('/api/admin/locations', {
headers: {
'Authorization': `Bearer ${key}`
}
})
const data = await response.json()
setLocations(data.locations)
} catch (error) {
console.error('Failed to fetch locations:', error)
}
}
const createStaff = async () => {
setLoading(true)
setMessage(null)
try {
const response = await fetch('/api/admin/users', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${adminKey}`
},
body: JSON.stringify(staffForm)
})
const data = await response.json()
if (response.ok) {
setMessage({ type: 'success', text: data.message || 'Staff member created successfully!' })
fetchStaff()
setStaffForm({
location_id: '',
role: 'staff',
display_name: '',
email: '',
password: '',
first_name: '',
last_name: '',
phone: ''
})
} else {
setMessage({ type: 'error', text: data.error || 'Failed to create staff member' })
}
} catch (error) {
setMessage({ type: 'error', text: 'Failed to create staff member' })
} finally {
setLoading(false)
}
}
const createKiosk = async () => {
setLoading(true)
setMessage(null)
try {
const response = await fetch('/api/admin/kiosks', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${adminKey}`
},
body: JSON.stringify(kioskForm)
})
const data = await response.json()
if (response.ok) {
setMessage({ type: 'success', text: data.message || 'Kiosk created successfully!' })
fetchKiosks()
setKioskForm({
location_id: '',
device_name: '',
display_name: '',
ip_address: ''
})
} else {
setMessage({ type: 'error', text: data.error || 'Failed to create kiosk' })
}
} catch (error) {
setMessage({ type: 'error', text: 'Failed to create kiosk' })
} finally {
setLoading(false)
}
}
const fetchStaff = async () => {
try {
const response = await fetch('/api/admin/users', {
headers: {
'Authorization': `Bearer ${adminKey}`
}
})
const data = await response.json()
setStaffList(data.staff || [])
} catch (error) {
console.error('Failed to fetch staff:', error)
}
}
const fetchKiosks = async () => {
try {
const response = await fetch('/api/admin/kiosks', {
headers: {
'Authorization': `Bearer ${adminKey}`
}
})
const data = await response.json()
setKioskList(data.kiosks || [])
} catch (error) {
console.error('Failed to fetch kiosks:', error)
}
}
useEffect(() => {
if (isAuthenticated) {
fetchStaff()
fetchKiosks()
}
}, [isAuthenticated])
if (!isAuthenticated) {
return (
<div className="min-h-screen bg-gradient-to-br from-purple-50 to-pink-50 flex items-center justify-center p-4">
<Card className="w-full max-w-md">
<CardHeader>
<CardTitle>Admin Enrollment</CardTitle>
<CardDescription>
Enter your admin enrollment key to access the user management system
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<div className="space-y-2">
<Label htmlFor="adminKey">Admin Enrollment Key</Label>
<Input
id="adminKey"
type="password"
placeholder="Enter your admin key"
value={adminKey}
onChange={(e) => setAdminKey(e.target.value)}
/>
</div>
{message && (
<div className={`p-3 rounded-md ${message.type === 'success' ? 'bg-green-50 text-green-700 border border-green-200' : 'bg-red-50 text-red-700 border border-red-200'}`}>
{message.text}
</div>
)}
<Button onClick={authenticate} disabled={loading} className="w-full">
{loading ? 'Authenticating...' : 'Access Enrollment System'}
</Button>
</CardContent>
</Card>
</div>
)
}
return (
<div className="min-h-screen bg-gradient-to-br from-purple-50 to-pink-50 p-4">
<div className="max-w-6xl mx-auto">
<header className="mb-8">
<h1 className="text-4xl font-bold text-gray-900 mb-2">
User Enrollment System
</h1>
<p className="text-gray-600">
Create staff members and kiosks for your salon locations
</p>
<Button
variant="outline"
onClick={() => {
localStorage.removeItem('admin_enrollment_key')
setIsAuthenticated(false)
}}
className="mt-4"
>
Logout
</Button>
</header>
{message && (
<div className={`p-4 rounded-md mb-6 ${message.type === 'success' ? 'bg-green-50 text-green-700 border border-green-200' : 'bg-red-50 text-red-700 border border-red-200'}`}>
{message.text}
</div>
)}
<Tabs value={activeTab} onValueChange={(v) => setActiveTab(v as 'staff' | 'kiosks')} className="mb-8">
<TabsList className="grid w-full grid-cols-2">
<TabsTrigger value="staff">Staff Members</TabsTrigger>
<TabsTrigger value="kiosks">Kiosks</TabsTrigger>
</TabsList>
<TabsContent value="staff" className="space-y-6">
<Card>
<CardHeader>
<CardTitle>Create Staff Member</CardTitle>
<CardDescription>
Add a new staff member to a location
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<div className="grid grid-cols-2 gap-4">
<div className="space-y-2">
<Label htmlFor="location">Location *</Label>
<Select onValueChange={(v) => setStaffForm({ ...staffForm, location_id: v })}>
<SelectTrigger>
<SelectValue placeholder="Select location" />
</SelectTrigger>
<SelectContent>
{locations.map((loc) => (
<SelectItem key={loc.id} value={loc.id}>
{loc.name}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div className="space-y-2">
<Label htmlFor="role">Role *</Label>
<Select onValueChange={(v) => setStaffForm({ ...staffForm, role: v })}>
<SelectTrigger>
<SelectValue placeholder="Select role" />
</SelectTrigger>
<SelectContent>
<SelectItem value="admin">Admin</SelectItem>
<SelectItem value="manager">Manager</SelectItem>
<SelectItem value="staff">Staff</SelectItem>
<SelectItem value="artist">Artist</SelectItem>
</SelectContent>
</Select>
</div>
</div>
<div className="space-y-2">
<Label htmlFor="displayName">Display Name *</Label>
<Input
id="displayName"
placeholder="e.g., María García"
value={staffForm.display_name}
onChange={(e) => setStaffForm({ ...staffForm, display_name: e.target.value })}
/>
</div>
<div className="grid grid-cols-2 gap-4">
<div className="space-y-2">
<Label htmlFor="firstName">First Name *</Label>
<Input
id="firstName"
placeholder="e.g., María"
value={staffForm.first_name}
onChange={(e) => setStaffForm({ ...staffForm, first_name: e.target.value })}
/>
</div>
<div className="space-y-2">
<Label htmlFor="lastName">Last Name *</Label>
<Input
id="lastName"
placeholder="e.g., García"
value={staffForm.last_name}
onChange={(e) => setStaffForm({ ...staffForm, last_name: e.target.value })}
/>
</div>
</div>
<div className="grid grid-cols-2 gap-4">
<div className="space-y-2">
<Label htmlFor="email">Email *</Label>
<Input
id="email"
type="email"
placeholder="e.g., maria@salon.com"
value={staffForm.email}
onChange={(e) => setStaffForm({ ...staffForm, email: e.target.value })}
/>
</div>
<div className="space-y-2">
<Label htmlFor="phone">Phone</Label>
<Input
id="phone"
type="tel"
placeholder="e.g., +52 55 1234 5678"
value={staffForm.phone}
onChange={(e) => setStaffForm({ ...staffForm, phone: e.target.value })}
/>
</div>
</div>
<div className="space-y-2">
<Label htmlFor="password">Password *</Label>
<Input
id="password"
type="password"
placeholder="Enter password"
value={staffForm.password}
onChange={(e) => setStaffForm({ ...staffForm, password: e.target.value })}
/>
</div>
<Button onClick={createStaff} disabled={loading} className="w-full">
{loading ? 'Creating Staff Member...' : 'Create Staff Member'}
</Button>
</CardContent>
</Card>
{staffList.length > 0 && (
<Card>
<CardHeader>
<CardTitle>Existing Staff Members</CardTitle>
<CardDescription>
{staffList.length} staff members found
</CardDescription>
</CardHeader>
<CardContent>
<div className="space-y-3">
{staffList.map((staff) => (
<div key={staff.id} className="p-3 bg-gray-50 rounded-lg flex justify-between items-center">
<div>
<p className="font-semibold">{staff.display_name}</p>
<p className="text-sm text-gray-600">
{staff.role} {staff.location?.name}
</p>
<p className="text-xs text-gray-500">
{staff.is_active ? 'Active' : 'Inactive'}
</p>
</div>
<div className="text-right">
<p className="text-xs text-gray-500">
{new Date(staff.created_at).toLocaleDateString()}
</p>
</div>
</div>
))}
</div>
</CardContent>
</Card>
)}
</TabsContent>
<TabsContent value="kiosks" className="space-y-6">
<Card>
<CardHeader>
<CardTitle>Create Kiosk</CardTitle>
<CardDescription>
Add a new kiosk to a location
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<div className="space-y-2">
<Label htmlFor="kioskLocation">Location *</Label>
<Select onValueChange={(v) => setKioskForm({ ...kioskForm, location_id: v })}>
<SelectTrigger>
<SelectValue placeholder="Select location" />
</SelectTrigger>
<SelectContent>
{locations.map((loc) => (
<SelectItem key={loc.id} value={loc.id}>
{loc.name}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div className="space-y-2">
<Label htmlFor="deviceName">Device Name *</Label>
<Input
id="deviceName"
placeholder="e.g., kiosk-entrance-1"
value={kioskForm.device_name}
onChange={(e) => setKioskForm({ ...kioskForm, device_name: e.target.value })}
/>
</div>
<div className="space-y-2">
<Label htmlFor="kioskDisplayName">Display Name *</Label>
<Input
id="kioskDisplayName"
placeholder="e.g., Kiosk Entrada Principal"
value={kioskForm.display_name}
onChange={(e) => setKioskForm({ ...kioskForm, display_name: e.target.value })}
/>
</div>
<div className="space-y-2">
<Label htmlFor="ipAddress">IP Address (Optional)</Label>
<Input
id="ipAddress"
type="text"
placeholder="e.g., 192.168.1.100"
value={kioskForm.ip_address}
onChange={(e) => setKioskForm({ ...kioskForm, ip_address: e.target.value })}
/>
</div>
<Button onClick={createKiosk} disabled={loading} className="w-full">
{loading ? 'Creating Kiosk...' : 'Create Kiosk'}
</Button>
{message?.type === 'success' && message.text.includes('API key') && (
<div className="p-4 bg-yellow-50 border border-yellow-200 rounded-md">
<p className="font-semibold text-yellow-900 mb-2">
Important: Save your API Key
</p>
<p className="text-sm text-yellow-800">
The API key will only be shown once. Make sure to save it securely and add it to your environment variables.
</p>
</div>
)}
</CardContent>
</Card>
{kioskList.length > 0 && (
<Card>
<CardHeader>
<CardTitle>Existing Kiosks</CardTitle>
<CardDescription>
{kioskList.length} kiosks found
</CardDescription>
</CardHeader>
<CardContent>
<div className="space-y-3">
{kioskList.map((kiosk) => (
<div key={kiosk.id} className="p-3 bg-gray-50 rounded-lg flex justify-between items-center">
<div>
<p className="font-semibold">{kiosk.display_name}</p>
<p className="text-sm text-gray-600">
{kiosk.device_name} {kiosk.location?.name}
</p>
<p className="text-xs text-gray-500">
{kiosk.ip_address || 'No IP restriction'}
</p>
<p className="text-xs text-gray-500">
{kiosk.is_active ? 'Active' : 'Inactive'}
</p>
</div>
<div className="text-right">
<p className="text-xs text-gray-500">
{new Date(kiosk.created_at).toLocaleDateString()}
</p>
</div>
</div>
))}
</div>
</CardContent>
</Card>
)}
</TabsContent>
</Tabs>
</div>
</div>
)
}

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 }
)
}
}

View File

@@ -0,0 +1,59 @@
import { NextRequest, NextResponse } from 'next/server'
import { supabase } from '@/lib/supabase/client'
import { Kiosk } from '@/lib/db/types'
export async function POST(request: NextRequest) {
try {
const { api_key } = await request.json()
if (!api_key || typeof api_key !== 'string') {
return NextResponse.json(
{ error: 'API key is required' },
{ status: 400 }
)
}
const { data: kiosk, error } = await supabase
.from('kiosks')
.select(`
id,
location_id,
device_name,
display_name,
is_active,
location (
id,
name,
timezone
)
`)
.eq('api_key', api_key)
.eq('is_active', true)
.single()
if (error || !kiosk) {
return NextResponse.json(
{ error: 'Invalid API key or kiosk not active' },
{ status: 401 }
)
}
return NextResponse.json({
success: true,
kiosk: {
id: kiosk.id,
location_id: kiosk.location_id,
device_name: kiosk.device_name,
display_name: kiosk.display_name,
is_active: kiosk.is_active,
location: kiosk.location
}
})
} catch (error) {
console.error('Kiosk authentication error:', error)
return NextResponse.json(
{ error: 'Internal server error' },
{ status: 500 }
)
}
}

View File

@@ -0,0 +1,109 @@
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,
{ params }: { params: { shortId: string } }
) {
try {
const kiosk = await validateKiosk(request)
if (!kiosk) {
return NextResponse.json(
{ error: 'Unauthorized' },
{ status: 401 }
)
}
const shortId = params.shortId
const { data: booking, error: fetchError } = await supabase
.from('bookings')
.select('id, status, location_id')
.eq('short_id', shortId)
.single()
if (fetchError || !booking) {
return NextResponse.json(
{ error: 'Booking not found' },
{ status: 404 }
)
}
if (booking.location_id !== kiosk.location_id) {
return NextResponse.json(
{ error: 'Booking not found in kiosk location' },
{ status: 404 }
)
}
if (booking.status !== 'pending') {
return NextResponse.json(
{ error: 'Booking is not in pending status' },
{ status: 400 }
)
}
const { data: updatedBooking, error: updateError } = await supabase
.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
)
`)
.single()
if (updateError || !updatedBooking) {
return NextResponse.json(
{ error: updateError?.message || 'Failed to confirm booking' },
{ status: 400 }
)
}
return NextResponse.json({
success: true,
booking: updatedBooking
})
} catch (error) {
console.error('Kiosk booking confirm error:', error)
return NextResponse.json(
{ error: 'Internal server error' },
{ status: 500 }
)
}
}

View File

@@ -0,0 +1,240 @@
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 GET(request: NextRequest) {
try {
const kiosk = await validateKiosk(request)
if (!kiosk) {
return NextResponse.json(
{ error: 'Unauthorized' },
{ status: 401 }
)
}
const { searchParams } = new URL(request.url)
const short_id = searchParams.get('short_id')
const date = searchParams.get('date')
let query = supabase
.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
)
`)
.eq('location_id', kiosk.location_id)
.in('status', ['pending', 'confirmed'])
if (short_id) {
query = query.eq('short_id', short_id)
}
if (date) {
const startDate = new Date(date)
const endDate = new Date(startDate)
endDate.setDate(endDate.getDate() + 1)
query = query
.gte('start_time_utc', startDate.toISOString())
.lt('start_time_utc', endDate.toISOString())
}
const { data: bookings, error } = await query.order('start_time_utc', { ascending: true })
if (error) {
return NextResponse.json(
{ error: error.message },
{ status: 400 }
)
}
return NextResponse.json({ bookings })
} catch (error) {
console.error('Kiosk bookings GET error:', error)
return NextResponse.json(
{ error: 'Internal server error' },
{ status: 500 }
)
}
}
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,
staff_id,
start_time_utc,
notes
} = body
if (!customer_email || !service_id || !staff_id || !start_time_utc) {
return NextResponse.json(
{ error: 'Missing required fields: customer_email, service_id, staff_id, start_time_utc' },
{ 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 startTime = new Date(start_time_utc)
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 the selected time' },
{ 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(' ') || 'Kiosko',
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,
location_id: kiosk.location_id,
resource_id: assignedResource.resource_id,
service_id,
start_time_utc: startTime.toISOString(),
end_time_utc: endTime.toISOString(),
status: 'pending',
deposit_amount: 0,
total_amount: service.base_price,
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
)
`)
.single()
if (bookingError || !booking) {
return NextResponse.json(
{ error: bookingError?.message || 'Failed to create booking' },
{ status: 400 }
)
}
return NextResponse.json({
success: true,
booking: {
...booking,
resource_name: assignedResource.resource_name,
resource_type: assignedResource.resource_type
}
}, { status: 201 })
} catch (error) {
console.error('Kiosk bookings POST error:', error)
return NextResponse.json(
{ error: 'Internal server error' },
{ status: 500 }
)
}
}

View File

@@ -0,0 +1,98 @@
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 GET(request: NextRequest) {
try {
const kiosk = await validateKiosk(request)
if (!kiosk) {
return NextResponse.json(
{ error: 'Unauthorized' },
{ status: 401 }
)
}
const { searchParams } = new URL(request.url)
const start_time = searchParams.get('start_time')
const end_time = searchParams.get('end_time')
const service_id = searchParams.get('service_id')
if (!start_time || !end_time) {
return NextResponse.json(
{ error: 'start_time and end_time are required' },
{ status: 400 }
)
}
const startTime = new Date(start_time)
const endTime = new Date(end_time)
if (isNaN(startTime.getTime()) || isNaN(endTime.getTime())) {
return NextResponse.json(
{ error: 'Invalid date format' },
{ status: 400 }
)
}
let resourceQuery = supabase
.rpc('get_available_resources_with_priority', {
p_location_id: kiosk.location_id,
p_start_time: startTime.toISOString(),
p_end_time: endTime.toISOString()
})
const { data: resources, error } = await resourceQuery
if (error) {
return NextResponse.json(
{ error: error.message },
{ status: 400 }
)
}
let availableResources = resources || []
if (service_id) {
const { data: service } = await supabase
.from('services')
.select('requires_dual_artist')
.eq('id', service_id)
.single()
if (service?.requires_dual_artist) {
availableResources = availableResources.filter(r => r.resource_type === 'room')
}
}
return NextResponse.json({
location_id: kiosk.location_id,
start_time: startTime.toISOString(),
end_time: endTime.toISOString(),
resources: availableResources,
total_available: availableResources.length
})
} catch (error) {
console.error('Kiosk resources available error:', error)
return NextResponse.json(
{ error: 'Internal server error' },
{ status: 500 }
)
}
}

View File

@@ -0,0 +1,182 @@
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 }
)
}
}

View File

@@ -0,0 +1,242 @@
'use client'
import { useState, useEffect } from 'react'
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { BookingConfirmation } from '@/components/kiosk/BookingConfirmation'
import { WalkInFlow } from '@/components/kiosk/WalkInFlow'
import { Calendar, UserPlus, MapPin, Clock } from 'lucide-react'
export default function KioskPage({ params }: { params: { locationId: string } }) {
const [apiKey, setApiKey] = useState<string | null>(null)
const [location, setLocation] = useState<any>(null)
const [currentView, setCurrentView] = useState<'home' | 'confirm' | 'walkin'>('home')
const [loading, setLoading] = useState(true)
const [error, setError] = useState<string | null>(null)
const [currentTime, setCurrentTime] = useState<Date>(new Date())
useEffect(() => {
const timer = setInterval(() => {
setCurrentTime(new Date())
}, 1000)
return () => clearInterval(timer)
}, [])
useEffect(() => {
const authenticateKiosk = async () => {
setLoading(true)
setError(null)
try {
const response = await fetch('/api/kiosk/authenticate', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
api_key: process.env.NEXT_PUBLIC_KIOSK_API_KEY || 'demo-api-key-64-characters-long-enough'
})
})
const data = await response.json()
if (!response.ok) {
throw new Error(data.error || 'Authentication failed')
}
setApiKey(data.kiosk.device_name)
setLocation(data.kiosk.location)
} catch (err) {
setError(err instanceof Error ? err.message : 'Error de autenticación del kiosko')
} finally {
setLoading(false)
}
}
authenticateKiosk()
}, [])
const formatDateTime = (date: Date) => {
return new Intl.DateTimeFormat('es-MX', {
dateStyle: 'full',
timeStyle: 'short',
timeZone: location?.timezone || 'America/Monterrey'
}).format(date)
}
if (loading) {
return (
<div className="min-h-screen flex items-center justify-center bg-gradient-to-br from-purple-50 to-pink-50">
<Card className="w-full max-w-md">
<CardContent className="pt-6">
<div className="text-center py-8">
<div className="animate-spin rounded-full h-12 w-12 border-b-2 border-purple-600 mx-auto mb-4"></div>
<p className="text-muted-foreground">Iniciando kiosko...</p>
</div>
</CardContent>
</Card>
</div>
)
}
if (error) {
return (
<div className="min-h-screen flex items-center justify-center bg-gradient-to-br from-red-50 to-orange-50">
<Card className="w-full max-w-md">
<CardHeader>
<CardTitle className="text-red-600">Error de Conexión</CardTitle>
</CardHeader>
<CardContent>
<div className="p-4 bg-red-50 border border-red-200 rounded-md mb-4">
{error}
</div>
<Button onClick={() => window.location.reload()} className="w-full">
Reintentar
</Button>
</CardContent>
</Card>
</div>
)
}
if (currentView === 'confirm') {
return (
<div className="min-h-screen flex items-center justify-center bg-gradient-to-br from-purple-50 to-pink-50 p-4">
<BookingConfirmation
apiKey={apiKey || ''}
onConfirm={(booking) => {
setCurrentView('home')
}}
onCancel={() => setCurrentView('home')}
/>
</div>
)
}
if (currentView === 'walkin') {
return (
<div className="min-h-screen flex items-center justify-center bg-gradient-to-br from-purple-50 to-pink-50 p-4">
<WalkInFlow
apiKey={apiKey || ''}
onComplete={(booking) => {
setCurrentView('home')
}}
onCancel={() => setCurrentView('home')}
/>
</div>
)
}
return (
<div className="min-h-screen bg-gradient-to-br from-purple-50 to-pink-50 p-4">
<div className="max-w-6xl mx-auto">
<header className="mb-8">
<div className="flex justify-between items-start">
<div>
<h1 className="text-4xl font-bold text-gray-900 mb-2">
{location?.name || 'Kiosko'}
</h1>
<div className="flex items-center gap-4 text-muted-foreground">
<div className="flex items-center gap-2">
<MapPin className="w-5 h-5" />
<span>Kiosko Principal</span>
</div>
<div className="flex items-center gap-2">
<Clock className="w-5 h-5" />
<span>{formatDateTime(currentTime)}</span>
</div>
</div>
</div>
<div className="text-right">
<p className="text-sm text-muted-foreground">ID del Kiosko</p>
<p className="font-mono text-lg">{apiKey || 'N/A'}</p>
</div>
</div>
</header>
<div className="grid md:grid-cols-2 gap-6 mb-8">
<Card
className="cursor-pointer hover:shadow-lg transition-shadow border-2 hover:border-purple-400"
onClick={() => setCurrentView('confirm')}
>
<CardHeader>
<div className="w-16 h-16 bg-purple-100 rounded-full flex items-center justify-center mb-4">
<Calendar className="w-8 h-8 text-purple-600" />
</div>
<CardTitle className="text-2xl">Confirmar Cita</CardTitle>
<CardDescription>
Confirma tu llegada ingresando el código de tu cita
</CardDescription>
</CardHeader>
<CardContent>
<Button className="w-full" size="lg">
Confirmar Cita
</Button>
</CardContent>
</Card>
<Card
className="cursor-pointer hover:shadow-lg transition-shadow border-2 hover:border-pink-400"
onClick={() => setCurrentView('walkin')}
>
<CardHeader>
<div className="w-16 h-16 bg-pink-100 rounded-full flex items-center justify-center mb-4">
<UserPlus className="w-8 h-8 text-pink-600" />
</div>
<CardTitle className="text-2xl">Reserva Inmediata</CardTitle>
<CardDescription>
Crea una reserva sin cita previa (Walk-in)
</CardDescription>
</CardHeader>
<CardContent>
<Button className="w-full" size="lg" variant="outline">
Crear Reserva
</Button>
</CardContent>
</Card>
</div>
<Card>
<CardHeader>
<CardTitle>Instrucciones</CardTitle>
</CardHeader>
<CardContent>
<div className="grid md:grid-cols-2 gap-6">
<div>
<h3 className="font-semibold mb-2 flex items-center gap-2">
<Calendar className="w-5 h-5 text-purple-600" />
Confirmar Cita
</h3>
<ol className="list-decimal list-inside space-y-2 text-sm text-muted-foreground">
<li>Selecciona "Confirmar Cita"</li>
<li>Ingresa el código de 6 caracteres de tu reserva</li>
<li>Verifica los detalles de tu cita</li>
<li>Confirma tu llegada</li>
</ol>
</div>
<div>
<h3 className="font-semibold mb-2 flex items-center gap-2">
<UserPlus className="w-5 h-5 text-pink-600" />
Reserva Inmediata
</h3>
<ol className="list-decimal list-inside space-y-2 text-sm text-muted-foreground">
<li>Selecciona "Reserva Inmediata"</li>
<li>Elige el servicio que deseas</li>
<li>Ingresa tus datos personales</li>
<li>Confirma la reserva</li>
</ol>
</div>
</div>
</CardContent>
</Card>
<footer className="mt-8 text-center text-sm text-muted-foreground">
<p>SalonOS Kiosk v1.0</p>
<p className="mt-1">Necesitas ayuda? Contacta al personal del salón</p>
</footer>
</div>
</div>
)
}