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,68 @@
import { NextRequest, NextResponse } from 'next/server'
import { supabaseAdmin } from '@/lib/supabase/admin'
/**
* @description Get daily closing reports
* @param {NextRequest} request - Query params: location_id, start_date, end_date, status
* @returns {NextResponse} List of daily closing reports
*/
export async function GET(request: NextRequest) {
try {
const searchParams = request.nextUrl.searchParams
const location_id = searchParams.get('location_id')
const start_date = searchParams.get('start_date')
const end_date = searchParams.get('end_date')
const status = searchParams.get('status')
const limit = parseInt(searchParams.get('limit') || '50')
const offset = parseInt(searchParams.get('offset') || '0')
let query = supabaseAdmin
.from('daily_closing_reports')
.select('*', { count: 'exact' })
.order('report_date', { ascending: false })
.range(offset, offset + limit - 1)
if (location_id) {
query = query.eq('location_id', location_id)
}
if (status) {
query = query.eq('status', status)
}
if (start_date) {
query = query.gte('report_date', start_date)
}
if (end_date) {
query = query.lte('report_date', end_date)
}
const { data: reports, error, count } = await query
if (error) {
console.error('Error fetching daily closing reports:', error)
return NextResponse.json(
{ success: false, error: 'Failed to fetch daily closing reports' },
{ status: 500 }
)
}
return NextResponse.json({
success: true,
data: reports || [],
pagination: {
total: count || 0,
limit,
offset,
hasMore: (count || 0) > offset + limit
}
})
} catch (error) {
console.error('Error in GET /api/aperture/finance/daily-closing:', error)
return NextResponse.json(
{ success: false, error: 'Internal server error' },
{ status: 500 }
)
}
}

View File

@@ -0,0 +1,143 @@
import { NextRequest, NextResponse } from 'next/server'
import { supabaseAdmin } from '@/lib/supabase/admin'
/**
* @description Create expense record
* @param {NextRequest} request - Body with expense details
* @returns {NextResponse} Created expense
*/
export async function POST(request: NextRequest) {
try {
const body = await request.json()
const {
location_id,
category,
description,
amount,
expense_date,
payment_method,
receipt_url,
notes
} = body
if (!category || !description || !amount || !expense_date) {
return NextResponse.json(
{ success: false, error: 'category, description, amount, and expense_date are required' },
{ status: 400 }
)
}
const { data: expense, error } = await supabaseAdmin
.from('expenses')
.insert({
location_id,
category,
description,
amount,
expense_date,
payment_method,
receipt_url,
notes,
created_by: (await supabaseAdmin.auth.getUser()).data.user?.id
})
.select()
.single()
if (error) {
console.error('Error creating expense:', error)
return NextResponse.json(
{ success: false, error: error.message },
{ status: 400 }
)
}
// Log to audit
await supabaseAdmin.from('audit_logs').insert({
entity_type: 'expense',
entity_id: expense.id,
action: 'create',
new_values: {
category,
description,
amount
}
})
return NextResponse.json({
success: true,
data: expense
})
} catch (error) {
console.error('Error in POST /api/aperture/finance/expenses:', error)
return NextResponse.json(
{ success: false, error: 'Internal server error' },
{ status: 500 }
)
}
}
/**
* @description Get expenses with filters
* @param {NextRequest} request - Query params: location_id, category, start_date, end_date
* @returns {NextResponse} List of expenses
*/
export async function GET(request: NextRequest) {
try {
const searchParams = request.nextUrl.searchParams
const location_id = searchParams.get('location_id')
const category = searchParams.get('category')
const start_date = searchParams.get('start_date')
const end_date = searchParams.get('end_date')
const limit = parseInt(searchParams.get('limit') || '50')
const offset = parseInt(searchParams.get('offset') || '0')
let query = supabaseAdmin
.from('expenses')
.select('*', { count: 'exact' })
.order('expense_date', { ascending: false })
.range(offset, offset + limit - 1)
if (location_id) {
query = query.eq('location_id', location_id)
}
if (category) {
query = query.eq('category', category)
}
if (start_date) {
query = query.gte('expense_date', start_date)
}
if (end_date) {
query = query.lte('expense_date', end_date)
}
const { data: expenses, error, count } = await query
if (error) {
console.error('Error fetching expenses:', error)
return NextResponse.json(
{ success: false, error: 'Failed to fetch expenses' },
{ status: 500 }
)
}
return NextResponse.json({
success: true,
data: expenses || [],
pagination: {
total: count || 0,
limit,
offset,
hasMore: (count || 0) > offset + limit
}
})
} catch (error) {
console.error('Error in GET /api/aperture/finance/expenses:', error)
return NextResponse.json(
{ success: false, error: 'Internal server error' },
{ status: 500 }
)
}
}

View File

@@ -0,0 +1,49 @@
import { NextRequest, NextResponse } from 'next/server'
import { supabaseAdmin } from '@/lib/supabase/admin'
/**
* @description Get financial summary for date range and location
* @param {NextRequest} request - Query params: location_id, start_date, end_date
* @returns {NextResponse} Financial summary with revenue, expenses, and profit
*/
export async function GET(request: NextRequest) {
try {
const searchParams = request.nextUrl.searchParams
const location_id = searchParams.get('location_id')
const start_date = searchParams.get('start_date')
const end_date = searchParams.get('end_date')
if (!start_date || !end_date) {
return NextResponse.json(
{ success: false, error: 'start_date and end_date are required' },
{ status: 400 }
)
}
// Get financial summary
const { data: summary, error } = await supabaseAdmin.rpc('get_financial_summary', {
p_location_id: location_id || null,
p_start_date: start_date,
p_end_date: end_date
})
if (error) {
console.error('Error fetching financial summary:', error)
return NextResponse.json(
{ success: false, error: 'Failed to fetch financial summary' },
{ status: 500 }
)
}
return NextResponse.json({
success: true,
data: summary
})
} catch (error) {
console.error('Error in GET /api/aperture/finance:', error)
return NextResponse.json(
{ success: false, error: 'Internal server error' },
{ status: 500 }
)
}
}

View File

@@ -0,0 +1,49 @@
import { NextRequest, NextResponse } from 'next/server'
import { supabaseAdmin } from '@/lib/supabase/admin'
/**
* @description Get staff performance report for date range
* @param {NextRequest} request - Query params: location_id, start_date, end_date
* @returns {NextResponse} Staff performance metrics per staff member
*/
export async function GET(request: NextRequest) {
try {
const searchParams = request.nextUrl.searchParams
const location_id = searchParams.get('location_id')
const start_date = searchParams.get('start_date')
const end_date = searchParams.get('end_date')
if (!location_id || !start_date || !end_date) {
return NextResponse.json(
{ success: false, error: 'location_id, start_date, and end_date are required' },
{ status: 400 }
)
}
// Get staff performance report
const { data: report, error } = await supabaseAdmin.rpc('get_staff_performance_report', {
p_location_id: location_id,
p_start_date: start_date,
p_end_date: end_date
})
if (error) {
console.error('Error fetching staff performance report:', error)
return NextResponse.json(
{ success: false, error: 'Failed to fetch staff performance report' },
{ status: 500 }
)
}
return NextResponse.json({
success: true,
data: report
})
} catch (error) {
console.error('Error in GET /api/aperture/finance/staff-performance:', error)
return NextResponse.json(
{ success: false, error: 'Internal server error' },
{ status: 500 }
)
}
}