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,154 @@
import { NextRequest, NextResponse } from 'next/server'
import { supabaseAdmin } from '@/lib/supabase/admin'
/**
* @description List and search clients with phonetic search, history, and technical notes
* @param {NextRequest} request - Query params: q (search query), tier (filter by tier), limit (results limit), offset (pagination offset)
* @returns {NextResponse} List of clients with their details
*/
export async function GET(request: NextRequest) {
try {
const searchParams = request.nextUrl.searchParams
const q = searchParams.get('q') || ''
const tier = searchParams.get('tier')
const limit = parseInt(searchParams.get('limit') || '50')
const offset = parseInt(searchParams.get('offset') || '0')
let query = supabaseAdmin
.from('customers')
.select(`
*,
bookings:bookings(
id,
short_id,
service_id,
start_time_utc,
status,
total_price
)
`, { count: 'exact' })
.order('created_at', { ascending: false })
.range(offset, offset + limit - 1)
// Apply tier filter
if (tier) {
query = query.eq('tier', tier)
}
// Apply phonetic search if query provided
if (q) {
const searchTerm = `%${q}%`
query = query.or(`first_name.ilike.${searchTerm},last_name.ilike.${searchTerm},email.ilike.${searchTerm},phone.ilike.${searchTerm}`)
}
const { data: customers, error, count } = await query
if (error) {
console.error('Error fetching clients:', error)
return NextResponse.json(
{ success: false, error: 'Failed to fetch clients' },
{ status: 500 }
)
}
return NextResponse.json({
success: true,
data: customers,
pagination: {
total: count || 0,
limit,
offset,
hasMore: (count || 0) > offset + limit
}
})
} catch (error) {
console.error('Error in /api/aperture/clients:', error)
return NextResponse.json(
{ success: false, error: 'Internal server error' },
{ status: 500 }
)
}
}
/**
* @description Create new client
* @param {NextRequest} request - Body with client details
* @returns {NextResponse} Created client data
*/
export async function POST(request: NextRequest) {
try {
const body = await request.json()
const {
first_name,
last_name,
email,
phone,
tier = 'free',
notes,
preferences,
referral_code
} = body
// Validate required fields
if (!first_name || !last_name) {
return NextResponse.json(
{ success: false, error: 'First name and last name are required' },
{ status: 400 }
)
}
// Generate unique referral code if not provided
let finalReferralCode = referral_code
if (!finalReferralCode) {
finalReferralCode = `${first_name.toLowerCase().replace(/[^a-z]/g, '')}${last_name.toLowerCase().replace(/[^a-z]/g, '')}${Date.now().toString(36)}`
}
// Create customer
const { data: customer, error } = await supabaseAdmin
.from('customers')
.insert({
first_name,
last_name,
email: email || null,
phone: phone || null,
tier,
notes,
preferences: preferences || {},
referral_code: finalReferralCode
})
.select()
.single()
if (error) {
console.error('Error creating client:', error)
return NextResponse.json(
{ success: false, error: error.message },
{ status: 400 }
)
}
// Log to audit
await supabaseAdmin.from('audit_logs').insert({
entity_type: 'customer',
entity_id: customer.id,
action: 'create',
new_values: {
first_name,
last_name,
email,
tier
}
})
return NextResponse.json({
success: true,
data: customer
})
} catch (error) {
console.error('Error in POST /api/aperture/clients:', error)
return NextResponse.json(
{ success: false, error: 'Internal server error' },
{ status: 500 }
)
}
}