mirror of
https://github.com/marcogll/AnchorOS.git
synced 2026-03-15 11:24:26 +00:00
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)
This commit is contained in:
178
lib/db/types.ts
Normal file
178
lib/db/types.ts
Normal file
@@ -0,0 +1,178 @@
|
||||
// Types based on SalonOS database schema
|
||||
|
||||
export type UserRole = 'admin' | 'manager' | 'staff' | 'artist' | 'customer'
|
||||
export type CustomerTier = 'free' | 'gold'
|
||||
export type BookingStatus = 'pending' | 'confirmed' | 'cancelled' | 'completed' | 'no_show'
|
||||
export type InvitationStatus = 'pending' | 'used' | 'expired'
|
||||
export type ResourceType = 'station' | 'room' | 'equipment'
|
||||
export type AuditAction = 'create' | 'update' | 'delete' | 'reset_invitations' | 'payment' | 'status_change'
|
||||
|
||||
export interface Location {
|
||||
id: string
|
||||
name: string
|
||||
timezone: string
|
||||
address?: string
|
||||
phone?: string
|
||||
is_active: boolean
|
||||
created_at: string
|
||||
updated_at: string
|
||||
}
|
||||
|
||||
export interface Resource {
|
||||
id: string
|
||||
location_id: string
|
||||
name: string
|
||||
type: ResourceType
|
||||
capacity: number
|
||||
is_active: boolean
|
||||
created_at: string
|
||||
updated_at: string
|
||||
location?: Location
|
||||
}
|
||||
|
||||
export interface Staff {
|
||||
id: string
|
||||
user_id: string
|
||||
location_id: string
|
||||
role: UserRole
|
||||
display_name: string
|
||||
phone?: string
|
||||
is_active: boolean
|
||||
created_at: string
|
||||
updated_at: string
|
||||
location?: Location
|
||||
}
|
||||
|
||||
export interface Service {
|
||||
id: string
|
||||
name: string
|
||||
description?: string
|
||||
duration_minutes: number
|
||||
base_price: number
|
||||
requires_dual_artist: boolean
|
||||
premium_fee_enabled: boolean
|
||||
is_active: boolean
|
||||
created_at: string
|
||||
updated_at: string
|
||||
}
|
||||
|
||||
export interface Customer {
|
||||
id: string
|
||||
user_id?: string
|
||||
first_name: string
|
||||
last_name: string
|
||||
email: string
|
||||
phone?: string
|
||||
tier: CustomerTier
|
||||
notes?: string
|
||||
total_spent: number
|
||||
total_visits: number
|
||||
last_visit_date?: string
|
||||
is_active: boolean
|
||||
created_at: string
|
||||
updated_at: string
|
||||
}
|
||||
|
||||
export interface Invitation {
|
||||
id: string
|
||||
inviter_id: string
|
||||
code: string
|
||||
email?: string
|
||||
status: InvitationStatus
|
||||
week_start_date: string
|
||||
expiry_date: string
|
||||
used_at?: string
|
||||
created_at: string
|
||||
updated_at: string
|
||||
inviter?: Customer
|
||||
}
|
||||
|
||||
export interface Booking {
|
||||
id: string
|
||||
short_id: string
|
||||
customer_id: string
|
||||
staff_id: string
|
||||
secondary_artist_id?: string
|
||||
location_id: string
|
||||
resource_id: string
|
||||
service_id: string
|
||||
start_time_utc: string
|
||||
end_time_utc: string
|
||||
status: BookingStatus
|
||||
deposit_amount: number
|
||||
total_amount: number
|
||||
is_paid: boolean
|
||||
payment_reference?: string
|
||||
notes?: string
|
||||
created_at: string
|
||||
updated_at: string
|
||||
customer?: Customer
|
||||
staff?: Staff
|
||||
secondary_artist?: Staff
|
||||
location?: Location
|
||||
resource?: Resource
|
||||
service?: Service
|
||||
}
|
||||
|
||||
export interface AuditLog {
|
||||
id: string
|
||||
entity_type: string
|
||||
entity_id: string
|
||||
action: AuditAction
|
||||
old_values?: Record<string, unknown>
|
||||
new_values?: Record<string, unknown>
|
||||
performed_by?: string
|
||||
performed_by_role?: UserRole
|
||||
ip_address?: string
|
||||
user_agent?: string
|
||||
metadata?: Record<string, unknown>
|
||||
created_at: string
|
||||
}
|
||||
|
||||
// Database response types
|
||||
export type Database = {
|
||||
public: {
|
||||
Tables: {
|
||||
locations: {
|
||||
Row: Location
|
||||
Insert: Omit<Location, 'id' | 'created_at' | 'updated_at'>
|
||||
Update: Partial<Omit<Location, 'id' | 'created_at'>>
|
||||
}
|
||||
resources: {
|
||||
Row: Resource
|
||||
Insert: Omit<Resource, 'id' | 'created_at' | 'updated_at'>
|
||||
Update: Partial<Omit<Resource, 'id' | 'created_at'>>
|
||||
}
|
||||
staff: {
|
||||
Row: Staff
|
||||
Insert: Omit<Staff, 'id' | 'created_at' | 'updated_at'>
|
||||
Update: Partial<Omit<Staff, 'id' | 'created_at'>>
|
||||
}
|
||||
services: {
|
||||
Row: Service
|
||||
Insert: Omit<Service, 'id' | 'created_at' | 'updated_at'>
|
||||
Update: Partial<Omit<Service, 'id' | 'created_at'>>
|
||||
}
|
||||
customers: {
|
||||
Row: Customer
|
||||
Insert: Omit<Customer, 'id' | 'created_at' | 'updated_at'>
|
||||
Update: Partial<Omit<Customer, 'id' | 'created_at'>>
|
||||
}
|
||||
invitations: {
|
||||
Row: Invitation
|
||||
Insert: Omit<Invitation, 'id' | 'created_at' | 'updated_at'>
|
||||
Update: Partial<Omit<Invitation, 'id' | 'created_at'>>
|
||||
}
|
||||
bookings: {
|
||||
Row: Booking
|
||||
Insert: Omit<Booking, 'id' | 'created_at' | 'updated_at'>
|
||||
Update: Partial<Omit<Booking, 'id' | 'created_at'>>
|
||||
}
|
||||
audit_logs: {
|
||||
Row: AuditLog
|
||||
Insert: Omit<AuditLog, 'id' | 'created_at'>
|
||||
Update: Partial<AuditLog>
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
19
lib/supabase/client.ts
Normal file
19
lib/supabase/client.ts
Normal file
@@ -0,0 +1,19 @@
|
||||
import { createClient } from '@supabase/supabase-js'
|
||||
|
||||
const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL!
|
||||
const supabaseAnonKey = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!
|
||||
|
||||
export const supabase = createClient(supabaseUrl, supabaseAnonKey)
|
||||
|
||||
export const supabaseAdmin = createClient(
|
||||
supabaseUrl,
|
||||
process.env.SUPABASE_SERVICE_ROLE_KEY!,
|
||||
{
|
||||
auth: {
|
||||
autoRefreshToken: false,
|
||||
persistSession: false
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
export default supabase
|
||||
Reference in New Issue
Block a user