mirror of
https://github.com/marcogll/AnchorOS.git
synced 2026-03-15 11:24:26 +00:00
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
174 lines
4.6 KiB
TypeScript
174 lines
4.6 KiB
TypeScript
import { NextRequest, NextResponse } from 'next/server'
|
|
import { supabaseAdmin } from '@/lib/supabase/admin'
|
|
|
|
/**
|
|
* @description Get specific client details with full history
|
|
* @param {NextRequest} request - URL params: clientId in path
|
|
* @returns {NextResponse} Client details with bookings, loyalty, photos
|
|
*/
|
|
export async function GET(
|
|
request: NextRequest,
|
|
{ params }: { params: { clientId: string } }
|
|
) {
|
|
try {
|
|
const { clientId } = params
|
|
|
|
// Get customer basic info
|
|
const { data: customer, error: customerError } = await supabaseAdmin
|
|
.from('customers')
|
|
.select('*')
|
|
.eq('id', clientId)
|
|
.single()
|
|
|
|
if (customerError || !customer) {
|
|
return NextResponse.json(
|
|
{ success: false, error: 'Client not found' },
|
|
{ status: 404 }
|
|
)
|
|
}
|
|
|
|
// Get recent bookings
|
|
const { data: bookings, error: bookingsError } = await supabaseAdmin
|
|
.from('bookings')
|
|
.select(`
|
|
*,
|
|
service:services(name, base_price, duration_minutes),
|
|
location:locations(name),
|
|
staff:staff(id, first_name, last_name)
|
|
`)
|
|
.eq('customer_id', clientId)
|
|
.order('start_time_utc', { ascending: false })
|
|
.limit(20)
|
|
|
|
if (bookingsError) {
|
|
console.error('Error fetching bookings:', bookingsError)
|
|
}
|
|
|
|
// Get loyalty summary
|
|
const { data: loyaltyTransactions, error: loyaltyError } = await supabaseAdmin
|
|
.from('loyalty_transactions')
|
|
.select('*')
|
|
.eq('customer_id', clientId)
|
|
.order('created_at', { ascending: false })
|
|
.limit(10)
|
|
|
|
if (loyaltyError) {
|
|
console.error('Error fetching loyalty transactions:', loyaltyError)
|
|
}
|
|
|
|
// Get photos (if tier allows)
|
|
let photos = []
|
|
const canAccessPhotos = ['gold', 'black', 'VIP'].includes(customer.tier)
|
|
|
|
if (canAccessPhotos) {
|
|
const { data: photosData, error: photosError } = await supabaseAdmin
|
|
.from('customer_photos')
|
|
.select('*')
|
|
.eq('customer_id', clientId)
|
|
.eq('is_active', true)
|
|
.order('taken_at', { ascending: false })
|
|
.limit(20)
|
|
|
|
if (!photosError) {
|
|
photos = photosData
|
|
}
|
|
}
|
|
|
|
// Get subscription (if any)
|
|
const { data: subscription, error: subError } = await supabaseAdmin
|
|
.from('customer_subscriptions')
|
|
.select(`
|
|
*,
|
|
membership_plan:membership_plans(name, tier, benefits)
|
|
`)
|
|
.eq('customer_id', clientId)
|
|
.eq('status', 'active')
|
|
.single()
|
|
|
|
return NextResponse.json({
|
|
success: true,
|
|
data: {
|
|
customer,
|
|
bookings: bookings || [],
|
|
loyalty_transactions: loyaltyTransactions || [],
|
|
photos,
|
|
subscription: subError ? null : subscription
|
|
}
|
|
})
|
|
} catch (error) {
|
|
console.error('Error in GET /api/aperture/clients/[id]:', error)
|
|
return NextResponse.json(
|
|
{ success: false, error: 'Internal server error' },
|
|
{ status: 500 }
|
|
)
|
|
}
|
|
}
|
|
|
|
/**
|
|
* @description Update client information
|
|
* @param {NextRequest} request - Body with updated client data
|
|
* @returns {NextResponse} Updated client data
|
|
*/
|
|
export async function PUT(
|
|
request: NextRequest,
|
|
{ params }: { params: { clientId: string } }
|
|
) {
|
|
try {
|
|
const { clientId } = params
|
|
const body = await request.json()
|
|
|
|
// Get current customer
|
|
const { data: currentCustomer, error: fetchError } = await supabaseAdmin
|
|
.from('customers')
|
|
.select('*')
|
|
.eq('id', clientId)
|
|
.single()
|
|
|
|
if (fetchError || !currentCustomer) {
|
|
return NextResponse.json(
|
|
{ success: false, error: 'Client not found' },
|
|
{ status: 404 }
|
|
)
|
|
}
|
|
|
|
// Update customer
|
|
const { data: updatedCustomer, error: updateError } = await supabaseAdmin
|
|
.from('customers')
|
|
.update({
|
|
...body,
|
|
updated_at: new Date().toISOString()
|
|
})
|
|
.eq('id', clientId)
|
|
.select()
|
|
.single()
|
|
|
|
if (updateError) {
|
|
console.error('Error updating client:', updateError)
|
|
return NextResponse.json(
|
|
{ success: false, error: updateError.message },
|
|
{ status: 400 }
|
|
)
|
|
}
|
|
|
|
// Log to audit
|
|
await supabaseAdmin.from('audit_logs').insert({
|
|
entity_type: 'customer',
|
|
entity_id: clientId,
|
|
action: 'update',
|
|
old_values: currentCustomer,
|
|
new_values: updatedCustomer
|
|
})
|
|
|
|
return NextResponse.json({
|
|
success: true,
|
|
data: updatedCustomer
|
|
})
|
|
} catch (error) {
|
|
console.error('Error in PUT /api/aperture/clients/[id]:', error)
|
|
return NextResponse.json(
|
|
{ success: false, error: 'Internal server error' },
|
|
{ status: 500 }
|
|
)
|
|
}
|
|
}
|