Files
AnchorOS/app/api/aperture/loyalty/[customerId]/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

135 lines
3.9 KiB
TypeScript

import { NextRequest, NextResponse } from 'next/server'
import { supabaseAdmin } from '@/lib/supabase/admin'
/**
* @description Get loyalty history for specific customer
* @param {NextRequest} request - URL params: customerId in path
* @returns {NextResponse} Customer loyalty transactions and history
*/
export async function GET(
request: NextRequest,
{ params }: { params: { customerId: string } }
) {
try {
const { customerId } = params
// Get loyalty summary
const { data: summary, error: summaryError } = await supabaseAdmin
.rpc('get_customer_loyalty_summary', { p_customer_id: customerId })
if (summaryError) {
console.error('Error fetching loyalty summary:', summaryError)
return NextResponse.json(
{ success: false, error: 'Failed to fetch loyalty summary' },
{ status: 500 }
)
}
// Get loyalty transactions with pagination
const searchParams = request.nextUrl.searchParams
const limit = parseInt(searchParams.get('limit') || '50')
const offset = parseInt(searchParams.get('offset') || '0')
const { data: transactions, error: transactionsError, count } = await supabaseAdmin
.from('loyalty_transactions')
.select('*', { count: 'exact' })
.eq('customer_id', customerId)
.order('created_at', { ascending: false })
.range(offset, offset + limit - 1)
if (transactionsError) {
console.error('Error fetching loyalty transactions:', transactionsError)
return NextResponse.json(
{ success: false, error: 'Failed to fetch loyalty transactions' },
{ status: 500 }
)
}
return NextResponse.json({
success: true,
data: {
summary,
transactions: transactions || [],
pagination: {
total: count || 0,
limit,
offset,
hasMore: (count || 0) > offset + limit
}
}
})
} catch (error) {
console.error('Error in GET /api/aperture/loyalty/[customerId]:', error)
return NextResponse.json(
{ success: false, error: 'Internal server error' },
{ status: 500 }
)
}
}
/**
* @description Add or remove loyalty points for customer
* @param {NextRequest} request - Body with points, transaction_type, description, reference_type, reference_id
* @returns {NextResponse} Transaction result and updated summary
*/
export async function POST(
request: NextRequest,
{ params }: { params: { customerId: string } }
) {
try {
const { customerId } = params
const body = await request.json()
const {
points,
transaction_type = 'admin_adjustment',
description,
reference_type,
reference_id
} = body
if (!points || typeof points !== 'number') {
return NextResponse.json(
{ success: false, error: 'Points amount is required and must be a number' },
{ status: 400 }
)
}
// Add loyalty points
const { data: transactionId, error: error } = await supabaseAdmin
.rpc('add_loyalty_points', {
p_customer_id: customerId,
p_points: points,
p_transaction_type: transaction_type,
p_description: description,
p_reference_type: reference_type,
p_reference_id: reference_id
})
if (error) {
console.error('Error adding loyalty points:', error)
return NextResponse.json(
{ success: false, error: error.message },
{ status: 400 }
)
}
// Get updated summary
const { data: summary } = await supabaseAdmin
.rpc('get_customer_loyalty_summary', { p_customer_id: customerId })
return NextResponse.json({
success: true,
data: {
transaction_id: transactionId,
summary
}
})
} catch (error) {
console.error('Error in POST /api/aperture/loyalty/[customerId]/points:', error)
return NextResponse.json(
{ success: false, error: 'Internal server error' },
{ status: 500 }
)
}
}