14 Commits

Author SHA1 Message Date
Marco Gallegos
d27354fd5a feat: Add kiosk management, artist selection, and schedule management
- Add KiosksManagement component with full CRUD for kiosks
- Add ScheduleManagement for staff schedules with break reminders
- Update booking flow to allow artist selection by customers
- Add staff_services API for assigning services to artists
- Update staff management UI with service assignment dialog
- Add auto-break reminder when schedule >= 8 hours
- Update availability API to filter artists by service
- Add kiosk management to Aperture dashboard
- Clean up ralphy artifacts and logs
2026-01-21 13:02:06 -06:00
Marco Gallegos
1e93188783 fix: Correct business hours showing only 22:00-23:00 slots
- Created migration to fix ALL locations with incorrect business hours
- Added debug endpoint to check business hours
- Migration updates locations with 22:00/23:00 times to correct 10:00-19:00

This resolves the booking availability showing wrong time slots.
2026-01-19 00:47:52 -06:00
Marco Gallegos
35d5cd058c fix: Correct calendar offset and fix business hours showing only 22:00-23:00
FIX 1 - Calendar Day Offset (already fixed in previous commit):
- Corrected DatePicker component to calculate proper day offset
- Added padding cells for correct weekday alignment
- January 1, 2026 now correctly shows as Thursday instead of Monday

FIX 2 - Business Hours Only Showing 22:00-23:00:
PROBLEM:
- Time slots API only returned 22:00 and 23:00 as available hours
- Incorrect business hours in database (likely 22:00-23:00 instead of 10:00-19:00)
- Poor timezone conversion in get_detailed_availability function

ROOT CAUSES:
1. Location business_hours stored incorrect hours (22:00-23:00)
2. get_detailed_availability had timezone concatenation issues
   - Used string concatenation for timestamp construction
   - Didn't properly handle timezone conversion
3. Fallback to defaults was using wrong values

SOLUTIONS:
1. Migration 20260118080000_fix_business_hours_default.sql:
   - Update default business hours to normal salon hours
   - Mon-Fri: 10:00-19:00
   - Saturday: 10:00-18:00
   - Sunday: Closed

2. Migration 20260118090000_fix_get_detailed_availability_timezone.sql:
   - Rewrite get_detailed_availability function
   - Use make_timestamp() instead of string concatenation
   - Proper timezone handling with AT TIME ZONE
   - Better NULL handling for business_hours
   - Fix is_available_for_booking COALESCE to default true

CHANGES:
- components/booking/date-picker.tsx: Added day offset calculation
- supabase/migrations/20260118080000.sql: Fix default business hours
- supabase/migrations/20260118090000.sql: Fix timezone in availability function
2026-01-18 23:17:41 -06:00
Marco Gallegos
bb25d6bde6 feat: Implement FASE 5 (Clients & Loyalty) and FASE 6 (Payments & Financial)
FASE 5 - Clientes y Fidelización:
- Client Management (CRM) con búsqueda fonética
- Galería de fotos restringida por tier (VIP/Black/Gold)
- Sistema de Lealtad con puntos y expiración (6 meses)
- Membresías (Gold, Black, VIP) con beneficios configurables
- Notas técnicas con timestamp

APIs Implementadas:
- GET/POST /api/aperture/clients - CRUD completo de clientes
- GET /api/aperture/clients/[id] - Detalles con historial de reservas
- POST /api/aperture/clients/[id]/notes - Notas técnicas
- GET/POST /api/aperture/clients/[id]/photos - Galería de fotos
- GET /api/aperture/loyalty - Resumen de lealtad
- GET/POST /api/aperture/loyalty/[customerId] - Historial y puntos

FASE 6 - Pagos y Protección:
- Stripe Webhooks (payment_intent.succeeded, payment_failed, charge.refunded)
- No-Show Logic con detección automática (ventana 12h)
- Check-in de clientes para prevenir no-shows
- Override Admin para waivar penalizaciones
- Finanzas y Reportes (expenses, daily closing, staff performance)

APIs Implementadas:
- POST /api/webhooks/stripe - Handler de webhooks Stripe
- GET /api/cron/detect-no-shows - Detectar no-shows (cron job)
- POST /api/aperture/bookings/no-show - Aplicar penalización
- POST /api/aperture/bookings/check-in - Registrar check-in
- GET /api/aperture/finance - Resumen financiero
- POST/GET /api/aperture/finance/daily-closing - Reportes diarios
- GET/POST /api/aperture/finance/expenses - Gestión de gastos
- GET /api/aperture/finance/staff-performance - Performance de staff

Documentación:
- docs/APERATURE_SPECS.md - Especificaciones técnicas completas
- docs/APERTURE_SQUARE_UI.md - Ejemplos de Radix UI con Square UI
- docs/API.md - Actualizado con nuevas rutas

Migraciones SQL:
- 20260118050000_clients_loyalty_system.sql - Clientes, fotos, lealtad, membresías
- 20260118060000_stripe_webhooks_noshow_logic.sql - Webhooks, no-shows, check-ins
- 20260118070000_financial_reporting_expenses.sql - Gastos, reportes financieros
2026-01-18 23:05:09 -06:00
Marco Gallegos
93366fc596 Add detailed logging to API endpoints for debugging 500 errors 2026-01-18 08:49:16 -06:00
Marco Gallegos
7f8a54f249 🎯 FASE 4 CONTINÚA: Sistema de Nómina Implementado
 SISTEMA DE NÓMINA COMPLETO:
- API  con cálculos automáticos de sueldo
- Cálculo de comisiones (10% de revenue de servicios completados)
- Cálculo de propinas (5% estimado de revenue)
- Cálculo de horas trabajadas desde bookings completados
- Sueldo base configurable por staff

 COMPONENTE PayrollManagement:
- Interfaz completa para gestión de nóminas
- Cálculo por períodos mensuales
- Tabla de resultados con exportación CSV
- Diálogo de cálculo detallado

 APIs CRUD STAFF FUNCIONALES:
- GET/POST/PUT/DELETE  y
- Gestión de roles y ubicaciones
- Auditoría completa de cambios

 APIs CRUD RESOURCES FUNCIONALES:
- GET/POST  con disponibilidad en tiempo real
- Estado de ocupación por recurso
- Capacidades y tipos de recursos

 MIGRACIÓN PAYROLL PREPARADA:
- Tablas: staff_salaries, commission_rates, tip_records, payroll_records
- Funciones PostgreSQL para cálculos complejos
- RLS policies configuradas

Próximo: POS completo con múltiples métodos de pago
2026-01-17 15:38:35 -06:00
Marco Gallegos
0f3de32899 🚀 FASE 4 COMPLETADO: Comentarios auditables + Calendario funcional + Gestión staff/recursos
 COMENTARIOS AUDITABLES IMPLEMENTADOS:
- 80+ archivos con JSDoc completo para auditoría manual
- APIs críticas con validaciones business/security/performance
- Componentes con reglas de negocio documentadas
- Funciones core con edge cases y validaciones

 CALENDARIO MULTI-COLUMNA FUNCIONAL (95%):
- Drag & drop con reprogramación automática
- Filtros por sucursal/staff, tiempo real
- Indicadores de conflictos y disponibilidad
- APIs completas con validaciones de colisión

 GESTIÓN OPERATIVA COMPLETA:
- CRUD staff: APIs + componente con validaciones
- CRUD recursos: APIs + componente con disponibilidad
- Autenticación completa con middleware seguro
- Auditoría completa en todas las operaciones

 DOCUMENTACIÓN ACTUALIZADA:
- TASKS.md: FASE 4 95% completado
- README.md: Estado actual y funcionalidades
- API.md: 40+ endpoints documentados

 SEGURIDAD Y VALIDACIONES:
- RLS policies documentadas en comentarios
- Business rules validadas manualmente
- Performance optimizations anotadas
- Error handling completo

Próximos: Nómina/POS/CRM avanzado (FASE 4 final)
2026-01-17 15:31:13 -06:00
Marco Gallegos
583a25a6f6 feat: implement customer registration flow and business hours system
Major changes:
- Add customer registration with email/phone lookup (app/booking/registro)
- Add customers API endpoint (app/api/customers/route)
- Implement business hours for locations (mon-fri 10-7, sat 10-6, sun closed)
- Fix availability function type casting issues
- Add business hours utilities (lib/utils/business-hours.ts)
- Update Location type to include business_hours JSONB
- Add mock payment component for testing
- Remove Supabase auth from booking flow
- Fix /cita redirect path in booking flow

Database migrations:
- Add category column to services table
- Add business_hours JSONB column to locations table
- Fix availability functions with proper type casting
- Update get_detailed_availability to use business_hours

Features:
- Customer lookup by email or phone
- Auto-redirect to registration if customer not found
- Pre-fill customer data if exists
- Business hours per day of week
- Location-specific opening/closing times
2026-01-17 00:29:49 -06:00
Marco Gallegos
9bb0caaecf feat: Add kiosk setup and API testing scripts, alongside database function fixes for API key generation and short IDs. 2026-01-16 16:23:43 -06:00
Marco Gallegos
392621e2cc feat: Agregar migración completa de sistema de disponibilidad
- Crear tablas booking_blocks y staff_availability
- Crear funciones RPC: check_staff_work_hours, check_staff_availability, get_available_staff, get_detailed_availability
- Agregar campos de horario a staff (work_hours_start, work_hours_end, work_days, is_available_for_booking)
2026-01-16 15:15:04 -06:00
Marco Gallegos
accf0e81e1 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
2026-01-16 15:12:57 -06:00
Marco Gallegos
631e60376c fix: Corregir error SQL en migración de Telegram
- Corregir uso de INTO en SELECT con múltiples columnas
- La migración de Telegram se ejecutó correctamente
- Campos de scoring agregados: performance_score, total_bookings_completed, etc.
- Funciones de scoring implementadas: update_staff_performance_score(), get_top_performers()
- Triggers automáticos para notificaciones de Telegram
2026-01-16 11:01:46 -06:00
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
Marco Gallegos
18071cfb63 refactor: migrate from old db/ to supabase CLI structure
- Migrated database schema from db/migrations to supabase/migrations
- Added Supabase CLI configuration (config.toml, .gitignore)
- Added kiosk role and amenities tables for touch kiosks
- Added notification system for artist alerts
- Added seed data with test locations and staff
- Removed old migration scripts and documentation
- Updated tasks_mg.md with current setup

Features:
- 2 locations: ANCHOR:23 - Via KLAVA and TEST
- Kiosk role for touch screen check-in/booking
- Amenities: coffee, cocktails, mocktails for clients
- Notifications when client arrives
- 1 staff + 4 artists + 1 kiosk per location
- Services: hair, nails, makeup, lashes
2026-01-16 00:01:32 -06:00