Files
AnchorOS/app/api/aperture/loyalty/route.ts
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

93 lines
2.7 KiB
TypeScript

import { NextRequest, NextResponse } from 'next/server'
import { supabaseAdmin } from '@/lib/supabase/admin'
/**
* @description Get loyalty points and rewards for current customer
* @param {NextRequest} request - Query params: customerId (optional, defaults to authenticated user)
* @returns {NextResponse} Loyalty summary with points, transactions, and rewards
*/
export async function GET(request: NextRequest) {
try {
const searchParams = request.nextUrl.searchParams
const customerId = searchParams.get('customerId')
// Get customer ID from auth or query param
let targetCustomerId = customerId
// If no customerId provided, get from authenticated user
if (!targetCustomerId) {
const { data: { user } } = await supabaseAdmin.auth.getUser()
if (!user) {
return NextResponse.json(
{ success: false, error: 'Authentication required' },
{ status: 401 }
)
}
const { data: customer } = await supabaseAdmin
.from('customers')
.select('id')
.eq('user_id', user.id)
.single()
if (!customer) {
return NextResponse.json(
{ success: false, error: 'Customer not found' },
{ status: 404 }
)
}
targetCustomerId = customer.id
}
// Get loyalty summary
const { data: summary, error: summaryError } = await supabaseAdmin
.rpc('get_customer_loyalty_summary', { p_customer_id: targetCustomerId })
if (summaryError) {
console.error('Error fetching loyalty summary:', summaryError)
return NextResponse.json(
{ success: false, error: 'Failed to fetch loyalty summary' },
{ status: 500 }
)
}
// Get recent transactions
const { data: transactions, error: transactionsError } = await supabaseAdmin
.from('loyalty_transactions')
.select('*')
.eq('customer_id', targetCustomerId)
.order('created_at', { ascending: false })
.limit(50)
if (transactionsError) {
console.error('Error fetching loyalty transactions:', transactionsError)
}
// Get available rewards based on points
const { data: membershipPlans, error: plansError } = await supabaseAdmin
.from('membership_plans')
.select('*')
.eq('is_active', true)
if (plansError) {
console.error('Error fetching membership plans:', plansError)
}
return NextResponse.json({
success: true,
data: {
summary,
transactions: transactions || [],
available_rewards: membershipPlans || []
}
})
} catch (error) {
console.error('Error in GET /api/aperture/loyalty:', error)
return NextResponse.json(
{ success: false, error: 'Internal server error' },
{ status: 500 }
)
}
}