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,84 @@
import { NextRequest, NextResponse } from 'next/server'
import { supabaseAdmin } from '@/lib/supabase/admin'
/**
* @description Add technical note to client
* @param {NextRequest} request - Body with note content
* @returns {NextResponse} Updated customer with notes
*/
export async function POST(
request: NextRequest,
{ params }: { params: { clientId: string } }
) {
try {
const { clientId } = params
const { note } = await request.json()
if (!note) {
return NextResponse.json(
{ success: false, error: 'Note content is required' },
{ status: 400 }
)
}
// Get current customer
const { data: customer, error: fetchError } = await supabaseAdmin
.from('customers')
.select('notes, technical_notes')
.eq('id', clientId)
.single()
if (fetchError || !customer) {
return NextResponse.json(
{ success: false, error: 'Client not found' },
{ status: 404 }
)
}
// Append new technical note
const existingNotes = customer.technical_notes || ''
const timestamp = new Date().toISOString()
const newNoteEntry = `[${timestamp}] ${note}`
const updatedNotes = existingNotes
? `${existingNotes}\n${newNoteEntry}`
: newNoteEntry
// Update customer
const { data: updatedCustomer, error: updateError } = await supabaseAdmin
.from('customers')
.update({
technical_notes: updatedNotes,
updated_at: new Date().toISOString()
})
.eq('id', clientId)
.select()
.single()
if (updateError) {
console.error('Error adding technical note:', 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: 'technical_note_added',
new_values: { note }
})
return NextResponse.json({
success: true,
data: updatedCustomer
})
} catch (error) {
console.error('Error in POST /api/aperture/clients/[id]/notes:', error)
return NextResponse.json(
{ success: false, error: 'Internal server error' },
{ status: 500 }
)
}
}

View File

@@ -0,0 +1,152 @@
import { NextRequest, NextResponse } from 'next/server'
import { supabaseAdmin } from '@/lib/supabase/admin'
/**
* @description Get client photo gallery (VIP/Black/Gold only)
* @param {NextRequest} request - URL params: clientId in path
* @returns {NextResponse} Client photos with metadata
*/
export async function GET(
request: NextRequest,
{ params }: { params: { clientId: string } }
) {
try {
const { clientId } = params
// Check if customer tier allows photo access
const { data: customer, error: customerError } = await supabaseAdmin
.from('customers')
.select('tier')
.eq('id', clientId)
.single()
if (customerError || !customer) {
return NextResponse.json(
{ success: false, error: 'Client not found' },
{ status: 404 }
)
}
// Check tier access
const canAccess = ['gold', 'black', 'VIP'].includes(customer.tier)
if (!canAccess) {
return NextResponse.json(
{ success: false, error: 'Photo gallery not available for this tier' },
{ status: 403 }
)
}
// Get photos
const { data: photos, error: photosError } = await supabaseAdmin
.from('customer_photos')
.select(`
*,
creator:auth.users(id, email)
`)
.eq('customer_id', clientId)
.eq('is_active', true)
.order('taken_at', { ascending: false })
if (photosError) {
console.error('Error fetching photos:', photosError)
return NextResponse.json(
{ success: false, error: 'Failed to fetch photos' },
{ status: 500 }
)
}
return NextResponse.json({
success: true,
data: photos || []
})
} catch (error) {
console.error('Error in GET /api/aperture/clients/[id]/photos:', error)
return NextResponse.json(
{ success: false, error: 'Internal server error' },
{ status: 500 }
)
}
}
/**
* @description Upload photo to client gallery (VIP/Black/Gold only)
* @param {NextRequest} request - Body with photo data
* @returns {NextResponse} Uploaded photo metadata
*/
export async function POST(
request: NextRequest,
{ params }: { params: { clientId: string } }
) {
try {
const { clientId } = params
const { storage_path, description } = await request.json()
if (!storage_path) {
return NextResponse.json(
{ success: false, error: 'Storage path is required' },
{ status: 400 }
)
}
// Check if customer tier allows photo gallery
const { data: customer, error: customerError } = await supabaseAdmin
.from('customers')
.select('tier')
.eq('id', clientId)
.single()
if (customerError || !customer) {
return NextResponse.json(
{ success: false, error: 'Client not found' },
{ status: 404 }
)
}
const canAccess = ['gold', 'black', 'VIP'].includes(customer.tier)
if (!canAccess) {
return NextResponse.json(
{ success: false, error: 'Photo gallery not available for this tier' },
{ status: 403 }
)
}
// Create photo record
const { data: photo, error: photoError } = await supabaseAdmin
.from('customer_photos')
.insert({
customer_id: clientId,
storage_path,
description,
created_by: (await supabaseAdmin.auth.getUser()).data.user?.id
})
.select()
.single()
if (photoError) {
console.error('Error uploading photo:', photoError)
return NextResponse.json(
{ success: false, error: photoError.message },
{ status: 400 }
)
}
// Log to audit
await supabaseAdmin.from('audit_logs').insert({
entity_type: 'customer_photo',
entity_id: photo.id,
action: 'upload',
new_values: { customer_id: clientId, storage_path }
})
return NextResponse.json({
success: true,
data: photo
})
} catch (error) {
console.error('Error in POST /api/aperture/clients/[id]/photos:', error)
return NextResponse.json(
{ success: false, error: 'Internal server error' },
{ status: 500 }
)
}
}

View File

@@ -0,0 +1,173 @@
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 }
)
}
}