Files
AnchorOS/db/migrations/003_audit_triggers.sql
Marco Gallegos 4707ddbd5a feat(salonos): implementar Fase 1.1 y 1.2 - Infraestructura y Esquema de Base de Datos
Implementación completa de la Fase 1.1 y 1.2 del proyecto SalonOS:

## Cambios en Reglas de Negocio (PRD.md, AGENTS.md, TASKS.md)
- Actualizado reset de invitaciones de mensual a semanal (Lunes 00:00 UTC)
- Jerarquía de roles actualizada: Admin > Manager > Staff > Artist > Customer
- Artistas (antes colaboradoras) ahora tienen rol 'artist'
- Staff/Manager/Admin pueden ver PII de customers
- Artist solo ve nombre y notas de customers (restricción de privacidad)

## Estructura del Proyecto (Next.js 14)
- app/boutique/: Frontend de cliente
- app/hq/: Dashboard administrativo
- app/api/: API routes
- components/: Componentes UI reutilizables (boutique, hq, shared)
- lib/: Lógica de negocio (supabase, db, utils)
- db/: Esquemas, migraciones y seeds
- integrations/: Stripe, Google Calendar, WhatsApp
- scripts/: Scripts de utilidad y automatización
- docs/: Documentación del proyecto

## Esquema de Base de Datos (Supabase PostgreSQL)
8 tablas creadas:
- locations: Ubicaciones con timezone
- resources: Recursos físicos (estaciones, habitaciones, equipos)
- staff: Personal con roles jerárquicos
- services: Catálogo de servicios
- customers: Información de clientes con tier (free/gold)
- invitations: Sistema de invitaciones semanales
- bookings: Sistema de reservas con short_id (6 caracteres)
- audit_logs: Registro de auditoría automática

14 funciones creadas:
- generate_short_id(): Generador de Short ID (6 chars, collision-safe)
- generate_invitation_code(): Generador de códigos de invitación (10 chars)
- reset_weekly_invitations_for_customer(): Reset individual de invitaciones
- reset_all_weekly_invitations(): Reset masivo de invitaciones
- validate_secondary_artist_role(): Validación de secondary_artist
- log_audit(): Trigger de auditoría automática
- get_current_user_role(): Obtener rol del usuario actual
- is_staff_or_higher(): Verificar si es admin/manager/staff
- is_artist(): Verificar si es artist
- is_customer(): Verificar si es customer
- is_admin(): Verificar si es admin
- update_updated_at(): Actualizar timestamps
- generate_booking_short_id(): Generar Short ID automáticamente
- get_week_start(): Obtener inicio de semana

17+ triggers activos:
- Auditores automáticos en tablas críticas
- Timestamps updated_at en todas las tablas
- Validación de secondary_artist (trigger en lugar de constraint)

20+ políticas RLS configuradas:
- Restricción crítica: Artist no ve email/phone de customers
- Jerarquía de roles: Admin > Manager > Staff > Artist > Customer
- Políticas granulares por tipo de operación y rol

6 tipos ENUM:
- user_role: admin, manager, staff, artist, customer
- customer_tier: free, gold
- booking_status: pending, confirmed, cancelled, completed, no_show
- invitation_status: pending, used, expired
- resource_type: station, room, equipment
- audit_action: create, update, delete, reset_invitations, payment, status_change

## Scripts de Utilidad
- check-connection.sh: Verificar conexión a Supabase
- simple-verify.sh: Verificar migraciones instaladas
- simple-seed.sh: Crear datos de prueba
- create-auth-users.js: Crear usuarios de Auth en Supabase
- verify-migration.sql: Script de verificación SQL completo
- seed-data.sql: Script de seed de datos SQL completo

## Documentación
- docs/STEP_BY_STEP_VERIFICATION.md: Guía paso a paso de verificación
- docs/STEP_BY_STEP_AUTH_CONFIG.md: Guía paso a paso de configuración Auth
- docs/POST_MIGRATION_SUCCESS.md: Guía post-migración
- docs/MIGRATION_CORRECTION.md: Detalle de correcciones aplicadas
- docs/QUICK_START_POST_MIGRATION.md: Guía rápida de referencia
- docs/SUPABASE_DASHBOARD_MIGRATION.md: Guía de ejecución en Dashboard
- docs/00_FULL_MIGRATION_FINAL_README.md: Guía de migración final
- SIMPLE_GUIDE.md: Guía simple de inicio
- FASE_1_STATUS.md: Estado de la Fase 1

## Configuración
- package.json: Dependencias y scripts de npm
- tsconfig.json: Configuración TypeScript con paths aliases
- next.config.js: Configuración Next.js
- tailwind.config.ts: Tema personalizado con colores primary, secondary, gold
- postcss.config.js: Configuración PostCSS
- .gitignore: Archivos excluidos de git
- .env.example: Template de variables de entorno

## Correcciones Aplicadas
1. Constraint de subquery en CHECK reemplazado por trigger de validación
   - PostgreSQL no permite subqueries en CHECK constraints
   - validate_secondary_artist_role() ahora es un trigger

2. Variable no declarada en loop
   - customer_record RECORD; añadido en bloque DECLARE

## Principios Implementados
- UTC-first: Todos los timestamps se almacenan en UTC
- Sistema Doble Capa: Validación Staff/Artist + Recurso físico
- Reset semanal: Invitaciones se resetean cada Lunes 00:00 UTC
- Idempotencia: Procesos de reset son idempotentes y auditados
- Privacidad: Artist solo ve nombre y notas de customers
- Auditoría: Todas las acciones críticas se registran automáticamente
- Short ID: 6 caracteres alfanuméricos como referencia humana
- UUID: Identificador primario interno

## Próximos Pasos
- Ejecutar scripts de verificación y seed
- Configurar Auth en Supabase Dashboard
- Implementar Tarea 1.3: Short ID & Invitaciones (backend)
- Implementar Tarea 1.4: CRM Base (endpoints CRUD)
2026-01-15 14:58:28 -06:00

309 lines
9.1 KiB
PL/PgSQL

-- Migración 003: Funciones auxiliares y triggers de auditoría
-- Version: 003
-- Fecha: 2026-01-15
-- Descripción: Generador de Short ID, funciones de reset semanal de invitaciones y triggers de auditoría
-- ============================================
-- SHORT ID GENERATOR
-- ============================================
CREATE OR REPLACE FUNCTION generate_short_id()
RETURNS VARCHAR(6) AS $$
DECLARE
chars VARCHAR(36) := '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
short_id VARCHAR(6);
attempts INT := 0;
max_attempts INT := 10;
BEGIN
LOOP
short_id := '';
FOR i IN 1..6 LOOP
short_id := short_id || substr(chars, floor(random() * 36 + 1)::INT, 1);
END LOOP;
IF NOT EXISTS (SELECT 1 FROM bookings WHERE short_id = short_id) THEN
RETURN short_id;
END IF;
attempts := attempts + 1;
IF attempts >= max_attempts THEN
RAISE EXCEPTION 'Failed to generate unique short_id after % attempts', max_attempts;
END IF;
END LOOP;
END;
$$ LANGUAGE plpgsql SECURITY DEFINER;
-- ============================================
-- INVITATION CODE GENERATOR
-- ============================================
CREATE OR REPLACE FUNCTION generate_invitation_code()
RETURNS VARCHAR(10) AS $$
DECLARE
chars VARCHAR(36) := '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
code VARCHAR(10);
attempts INT := 0;
max_attempts INT := 10;
BEGIN
LOOP
code := '';
FOR i IN 1..10 LOOP
code := code || substr(chars, floor(random() * 36 + 1)::INT, 1);
END LOOP;
IF NOT EXISTS (SELECT 1 FROM invitations WHERE code = code) THEN
RETURN code;
END IF;
attempts := attempts + 1;
IF attempts >= max_attempts THEN
RAISE EXCEPTION 'Failed to generate unique invitation code after % attempts', max_attempts;
END IF;
END LOOP;
END;
$$ LANGUAGE plpgsql SECURITY DEFINER;
-- ============================================
-- WEEKLY INVITATION RESET
-- ============================================
CREATE OR REPLACE FUNCTION get_week_start(date_param DATE DEFAULT CURRENT_DATE)
RETURNS DATE AS $$
BEGIN
RETURN date_param - (EXTRACT(ISODOW FROM date_param)::INT - 1);
END;
$$ LANGUAGE plpgsql IMMUTABLE;
CREATE OR REPLACE FUNCTION reset_weekly_invitations_for_customer(customer_uuid UUID)
RETURNS INTEGER AS $$
DECLARE
week_start DATE;
invitations_remaining INTEGER := 5;
invitations_created INTEGER := 0;
BEGIN
week_start := get_week_start(CURRENT_DATE);
-- Verificar si ya existen invitaciones para esta semana
SELECT COUNT(*) INTO invitations_created
FROM invitations
WHERE inviter_id = customer_uuid
AND week_start_date = week_start;
-- Si no hay invitaciones para esta semana, crear las 5 nuevas
IF invitations_created = 0 THEN
INSERT INTO invitations (inviter_id, code, week_start_date, expiry_date, status)
SELECT
customer_uuid,
generate_invitation_code(),
week_start,
week_start + INTERVAL '6 days',
'pending'
FROM generate_series(1, 5);
invitations_created := 5;
-- Registrar en audit_logs
INSERT INTO audit_logs (
entity_type,
entity_id,
action,
old_values,
new_values,
performed_by,
performed_by_role,
metadata
)
VALUES (
'invitations',
customer_uuid,
'reset_invitations',
'{"week_start": null}'::JSONB,
'{"week_start": "' || week_start || '", "count": 5}'::JSONB,
NULL,
'system',
'{"reset_type": "weekly", "invitations_created": 5}'::JSONB
);
END IF;
RETURN invitations_created;
END;
$$ LANGUAGE plpgsql SECURITY DEFINER;
CREATE OR REPLACE FUNCTION reset_all_weekly_invitations()
RETURNS JSONB AS $$
DECLARE
customers_count INTEGER := 0;
invitations_created INTEGER := 0;
result JSONB;
customer_record RECORD;
BEGIN
-- Resetear invitaciones solo para clientes Gold
FOR customer_record IN
SELECT id FROM customers WHERE tier = 'gold' AND is_active = true
LOOP
invitations_created := invitations_created + reset_weekly_invitations_for_customer(customer_record.id);
customers_count := customers_count + 1;
END LOOP;
result := jsonb_build_object(
'customers_processed', customers_count,
'invitations_created', invitations_created,
'executed_at', NOW()::TEXT
);
-- Registrar ejecución masiva
INSERT INTO audit_logs (
entity_type,
entity_id,
action,
old_values,
new_values,
performed_by,
performed_by_role,
metadata
)
VALUES (
'invitations',
uuid_generate_v4(),
'reset_invitations',
'{}'::JSONB,
result,
NULL,
'system',
'{"reset_type": "weekly_batch"}'::JSONB
);
RETURN result;
END;
$$ LANGUAGE plpgsql SECURITY DEFINER;
-- ============================================
-- AUDIT LOG TRIGGER FUNCTION
-- ============================================
CREATE OR REPLACE FUNCTION log_audit()
RETURNS TRIGGER AS $$
DECLARE
current_user_role_val user_role;
BEGIN
-- Obtener rol del usuario actual
current_user_role_val := get_current_user_role();
-- Solo auditar tablas críticas
IF TG_TABLE_NAME IN ('bookings', 'customers', 'invitations', 'staff', 'services') THEN
IF TG_OP = 'INSERT' THEN
INSERT INTO audit_logs (
entity_type,
entity_id,
action,
old_values,
new_values,
performed_by,
performed_by_role,
metadata
)
VALUES (
TG_TABLE_NAME,
NEW.id,
'create',
NULL,
row_to_json(NEW)::JSONB,
auth.uid(),
current_user_role_val,
jsonb_build_object('operation', TG_OP, 'table_name', TG_TABLE_NAME)
);
ELSIF TG_OP = 'UPDATE' THEN
-- Solo auditar si hubo cambios relevantes
IF NEW IS DISTINCT FROM OLD THEN
INSERT INTO audit_logs (
entity_type,
entity_id,
action,
old_values,
new_values,
performed_by,
performed_by_role,
metadata
)
VALUES (
TG_TABLE_NAME,
NEW.id,
'update',
row_to_json(OLD)::JSONB,
row_to_json(NEW)::JSONB,
auth.uid(),
current_user_role_val,
jsonb_build_object('operation', TG_OP, 'table_name', TG_TABLE_NAME)
);
END IF;
ELSIF TG_OP = 'DELETE' THEN
INSERT INTO audit_logs (
entity_type,
entity_id,
action,
old_values,
new_values,
performed_by,
performed_by_role,
metadata
)
VALUES (
TG_TABLE_NAME,
OLD.id,
'delete',
row_to_json(OLD)::JSONB,
NULL,
auth.uid(),
current_user_role_val,
jsonb_build_object('operation', TG_OP, 'table_name', TG_TABLE_NAME)
);
END IF;
END IF;
IF TG_OP = 'DELETE' THEN
RETURN OLD;
ELSE
RETURN NEW;
END IF;
END;
$$ LANGUAGE plpgsql SECURITY DEFINER;
-- ============================================
-- APPLY AUDIT LOG TRIGGERS
-- ============================================
CREATE TRIGGER audit_bookings AFTER INSERT OR UPDATE OR DELETE ON bookings
FOR EACH ROW EXECUTE FUNCTION log_audit();
CREATE TRIGGER audit_customers AFTER INSERT OR UPDATE OR DELETE ON customers
FOR EACH ROW EXECUTE FUNCTION log_audit();
CREATE TRIGGER audit_invitations AFTER INSERT OR UPDATE OR DELETE ON invitations
FOR EACH ROW EXECUTE FUNCTION log_audit();
CREATE TRIGGER audit_staff AFTER INSERT OR UPDATE OR DELETE ON staff
FOR EACH ROW EXECUTE FUNCTION log_audit();
CREATE TRIGGER audit_services AFTER INSERT OR UPDATE OR DELETE ON services
FOR EACH ROW EXECUTE FUNCTION log_audit();
-- ============================================
-- AUTOMATIC SHORT ID GENERATION FOR BOOKINGS
-- ============================================
CREATE OR REPLACE FUNCTION generate_booking_short_id()
RETURNS TRIGGER AS $$
BEGIN
IF NEW.short_id IS NULL OR NEW.short_id = '' THEN
NEW.short_id := generate_short_id();
END IF;
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
CREATE TRIGGER booking_generate_short_id BEFORE INSERT ON bookings
FOR EACH ROW EXECUTE FUNCTION generate_booking_short_id();
-- ============================================
-- END OF MIGRATION 003
-- ============================================