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
This commit is contained in:
Marco Gallegos
2026-01-18 23:05:09 -06:00
parent f6832c1e29
commit bb25d6bde6
21 changed files with 3845 additions and 13 deletions

View File

@@ -0,0 +1,95 @@
import { NextRequest, NextResponse } from 'next/server'
import { supabaseAdmin } from '@/lib/supabase/admin'
/**
* @description CRITICAL: Detect and mark no-show bookings (runs every 2 hours)
* @param {NextRequest} request - Must include Bearer token with CRON_SECRET
* @returns {NextResponse} No-show detection results with count of bookings processed
* @example curl -H "Authorization: Bearer YOUR_CRON_SECRET" /api/cron/detect-no-shows
* @audit BUSINESS RULE: No-show window is 12 hours after booking start time (UTC)
* @audit SECURITY: Requires CRON_SECRET environment variable for authentication
* @audit Validate: Only confirmed/pending bookings without check-in are affected
* @audit AUDIT: Detection action logged in audit_logs with booking details
* @audit PERFORMANCE: Efficient query with date range and status filters
* @audit RELIABILITY: Cron job should run every 2 hours to detect no-shows
*/
export async function GET(request: NextRequest) {
try {
const authHeader = request.headers.get('authorization')
if (!authHeader || !authHeader.startsWith('Bearer ')) {
return NextResponse.json(
{ success: false, error: 'Unauthorized' },
{ status: 401 }
)
}
const cronKey = authHeader.replace('Bearer ', '').trim()
if (cronKey !== process.env.CRON_SECRET) {
return NextResponse.json(
{ success: false, error: 'Invalid cron key' },
{ status: 403 }
)
}
// Calculate no-show window: bookings that started more than 12 hours ago
const windowStart = new Date()
windowStart.setHours(windowStart.getHours() - 12)
// Get eligible bookings (confirmed/pending, no check-in, started > 12h ago)
const { data: bookings, error: bookingsError } = await supabaseAdmin
.from('bookings')
.select('id, start_time_utc, customer_id, service_id, deposit_amount')
.in('status', ['confirmed', 'pending'])
.lt('start_time_utc', windowStart.toISOString())
.is('check_in_time', null)
if (bookingsError) {
console.error('Error fetching bookings for no-show detection:', bookingsError)
return NextResponse.json(
{ success: false, error: 'Failed to fetch bookings' },
{ status: 500 }
)
}
if (!bookings || bookings.length === 0) {
return NextResponse.json({
success: true,
message: 'No bookings to process',
processedCount: 0,
detectedCount: 0
})
}
let detectedCount = 0
// Process each booking
for (const booking of bookings) {
const detected = await supabaseAdmin.rpc('detect_no_show_booking', {
p_booking_id: booking.id
})
if (detected) {
detectedCount++
}
}
console.log(`No-show detection completed: ${detectedCount} bookings detected out of ${bookings.length} processed`)
return NextResponse.json({
success: true,
message: 'No-show detection completed successfully',
processedCount: bookings.length,
detectedCount
})
} catch (error) {
console.error('Error in no-show detection:', error)
return NextResponse.json(
{ success: false, error: 'Internal server error' },
{ status: 500 }
)
}
}