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,106 @@
import { NextRequest, NextResponse } from 'next/server'
import { supabaseAdmin } from '@/lib/supabase/admin'
import Stripe from 'stripe'
/**
* @description Handle Stripe webhooks for payment intents and refunds
* @param {NextRequest} request - Raw Stripe webhook payload with signature
* @returns {NextResponse} Webhook processing result
*/
export async function POST(request: NextRequest) {
try {
const stripeSecretKey = process.env.STRIPE_SECRET_KEY
const stripeWebhookSecret = process.env.STRIPE_WEBHOOK_SECRET
if (!stripeSecretKey || !stripeWebhookSecret) {
return NextResponse.json(
{ error: 'Stripe not configured' },
{ status: 500 }
)
}
const stripe = new Stripe(stripeSecretKey)
const body = await request.text()
const signature = request.headers.get('stripe-signature')
if (!signature) {
return NextResponse.json(
{ error: 'Missing Stripe signature' },
{ status: 400 }
)
}
// Verify webhook signature
let event
try {
event = stripe.webhooks.constructEvent(
body,
signature,
stripeWebhookSecret
)
} catch (err) {
console.error('Webhook signature verification failed:', err)
return NextResponse.json(
{ error: 'Invalid signature' },
{ status: 400 }
)
}
const eventId = event.id
// Check if event already processed
const { data: existingLog } = await supabaseAdmin
.from('webhook_logs')
.select('*')
.eq('event_id', eventId)
.single()
if (existingLog) {
console.log(`Event ${eventId} already processed, skipping`)
return NextResponse.json({ received: true, already_processed: true })
}
// Log webhook event
await supabaseAdmin.from('webhook_logs').insert({
event_type: event.type,
event_id: eventId,
payload: event.data as any
})
// Process based on event type
switch (event.type) {
case 'payment_intent.succeeded':
await supabaseAdmin.rpc('process_payment_intent_succeeded', {
p_event_id: eventId,
p_payload: event.data as any
})
break
case 'payment_intent.payment_failed':
await supabaseAdmin.rpc('process_payment_intent_failed', {
p_event_id: eventId,
p_payload: event.data as any
})
break
case 'charge.refunded':
await supabaseAdmin.rpc('process_charge_refunded', {
p_event_id: eventId,
p_payload: event.data as any
})
break
default:
console.log(`Unhandled event type: ${event.type}`)
}
return NextResponse.json({ received: true })
} catch (error) {
console.error('Error processing Stripe webhook:', error)
return NextResponse.json(
{ error: 'Webhook processing failed' },
{ status: 500 }
)
}
}