# Estandar de Nomenclatura de Schemas - ERP Suite **Version:** 1.0.0 **Fecha:** 2025-12-08 **Autor:** Architecture Analyst Agent **Estado:** APROBADO --- ## 1. Proposito Este documento define la convencion de nomenclatura para schemas de base de datos en todo el ecosistema ERP-Suite, asegurando consistencia entre erp-core y todas las verticales. --- ## 2. Convencion General ### 2.1 Formato de Nombres ``` {prefijo}_{dominio} ``` | Componente | Descripcion | Ejemplo | |------------|-------------|---------| | prefijo | Identificador del proyecto (3 letras) | `erp`, `con`, `mec` | | dominio | Area funcional | `auth`, `inventory`, `sales` | ### 2.2 Prefijos por Proyecto | Proyecto | Prefijo | Descripcion | |----------|---------|-------------| | **erp-core** | `erp_` | Schemas del core compartido | | **construccion** | `con_` | Vertical de construccion | | **mecanicas-diesel** | `mec_` | Vertical de mecanicas | | **clinicas** | `cli_` | Vertical de clinicas | | **retail** | `ret_` | Vertical de retail/POS | | **vidrio-templado** | `vit_` | Vertical de vidrio templado | --- ## 3. Schemas del ERP-Core ### 3.1 Schemas Base (Compartidos) | Schema Actual | Schema Estandar | Descripcion | |---------------|-----------------|-------------| | `auth` | `erp_auth` | Autenticacion, sesiones | | `core` | `erp_core` | Catalogos base, configuracion | | `financial` | `erp_financial` | Contabilidad, diarios | | `inventory` | `erp_inventory` | Productos, almacenes | | `purchase` | `erp_purchase` | Ordenes de compra | | `sales` | `erp_sales` | Cotizaciones, pedidos | | `projects` | `erp_projects` | Proyectos, tareas | | `system` | `erp_system` | Notificaciones, logs | | `billing` | `erp_billing` | SaaS subscripciones | | `crm` | `erp_crm` | Leads, oportunidades | | `hr` | `erp_hr` | Recursos humanos | | `analytics` | `erp_analytics` | Contabilidad analitica | --- ## 4. Schemas por Vertical ### 4.1 Construccion (`con_*`) | Schema | Descripcion | Tablas Estimadas | |--------|-------------|------------------| | `con_projects` | Proyectos, fraccionamientos, fases | 8 | | `con_budgets` | Presupuestos, partidas, costos | 10 | | `con_estimates` | Estimaciones, avances | 6 | | `con_infonavit` | Integracion INFONAVIT | 6 | | `con_quality` | Calidad, inspecciones | 5 | | `con_contracts` | Contratos, subcontratos | 5 | | `con_hse` | Seguridad, higiene | 8 | ### 4.2 Mecanicas Diesel (`mec_*`) | Schema | Descripcion | Tablas | |--------|-------------|--------| | `mec_workshop` | Configuracion de taller | 9 | | `mec_service` | Ordenes de servicio, diagnosticos | 14 | | `mec_parts` | Refacciones, inventario | 12 | | `mec_vehicles` | Vehiculos, flotas | 8 | ### 4.3 Clinicas (`cli_*`) | Schema | Descripcion | Tablas Estimadas | |--------|-------------|------------------| | `cli_patients` | Pacientes, expedientes | 8 | | `cli_appointments` | Citas, agenda | 5 | | `cli_medical` | Consultas, recetas | 10 | | `cli_lab` | Laboratorio, resultados | 6 | | `cli_pharmacy` | Farmacia, medicamentos | 5 | | `cli_imaging` | Imagenologia, DICOM | 4 | ### 4.4 Retail (`ret_*`) | Schema | Descripcion | Tablas Estimadas | |--------|-------------|------------------| | `ret_pos` | Punto de venta, cajas | 8 | | `ret_store` | Tiendas, sucursales | 5 | | `ret_loyalty` | Fidelizacion, puntos | 6 | | `ret_ecommerce` | Tienda online | 8 | ### 4.5 Vidrio Templado (`vit_*`) | Schema | Descripcion | Tablas Estimadas | |--------|-------------|------------------| | `vit_production` | Produccion, ordenes | 8 | | `vit_cutting` | Corte, nesting | 5 | | `vit_tempering` | Templado, hornos | 5 | | `vit_quality` | Calidad, fragmentacion | 6 | | `vit_dispatch` | Despacho, entregas | 4 | --- ## 5. Convencion de Tablas ### 5.1 Formato de Nombres ```sql -- Tablas en plural, snake_case {schema}.{nombre_tabla_plural} -- Ejemplos erp_auth.users erp_inventory.products con_projects.developments mec_service.work_orders ``` ### 5.2 Columnas Obligatorias Todas las tablas transaccionales DEBEN incluir: ```sql -- Identificador id UUID PRIMARY KEY DEFAULT gen_random_uuid() -- Multi-tenancy tenant_id UUID NOT NULL -- Auditoria created_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP created_by UUID updated_at TIMESTAMPTZ updated_by UUID -- Soft delete is_active BOOLEAN DEFAULT true deleted_at TIMESTAMPTZ deleted_by UUID ``` ### 5.3 Indices ```sql -- Formato: idx_{tabla}_{columnas} CREATE INDEX idx_users_tenant_id ON erp_auth.users(tenant_id); CREATE INDEX idx_users_email ON erp_auth.users(email); -- Unique con soft delete CREATE UNIQUE INDEX idx_users_email_active ON erp_auth.users(email) WHERE deleted_at IS NULL; ``` ### 5.4 Foreign Keys ```sql -- Formato: fk_{origen}_to_{destino} ALTER TABLE mec_service.work_orders ADD CONSTRAINT fk_work_orders_to_vehicles FOREIGN KEY (vehicle_id) REFERENCES mec_vehicles.vehicles(id); ``` ### 5.5 Triggers ```sql -- Formato: trg_{tabla}_{accion} CREATE TRIGGER trg_users_updated_at BEFORE UPDATE ON erp_auth.users FOR EACH ROW EXECUTE FUNCTION update_updated_at(); ``` --- ## 6. RLS (Row-Level Security) ### 6.1 Patron Estandar ```sql -- Habilitar RLS ALTER TABLE {schema}.{tabla} ENABLE ROW LEVEL SECURITY; -- Policy de aislamiento por tenant CREATE POLICY tenant_isolation ON {schema}.{tabla} USING (tenant_id = current_setting('app.current_tenant_id')::uuid); ``` ### 6.2 Variable de Contexto por Vertical | Vertical | Variable de Contexto | |----------|---------------------| | erp-core | `app.current_tenant_id` | | construccion | `app.current_tenant_id` | | mecanicas | `app.current_taller_id` | | clinicas | `app.current_clinica_id` | | retail | `app.current_tienda_id` | | vidrio | `app.current_planta_id` | --- ## 7. Migracion de Schemas Existentes ### 7.1 Plan de Migracion Para proyectos con schemas existentes, seguir este proceso: 1. **Crear nuevo schema** con prefijo correcto 2. **Copiar estructura** de tablas 3. **Migrar datos** con INSERT...SELECT 4. **Actualizar referencias** en codigo 5. **Deprecar schema antiguo** 6. **Eliminar schema antiguo** (siguiente version) ### 7.2 Mapeo de Schemas Existentes #### erp-core (ya implementado) ```sql -- Actual → Estandar (pendiente migracion) auth → erp_auth core → erp_core financial → erp_financial inventory → erp_inventory purchase → erp_purchase sales → erp_sales projects → erp_projects system → erp_system billing → erp_billing crm → erp_crm hr → erp_hr analytics → erp_analytics ``` #### construccion ```sql -- Actual → Estandar construction → con_projects hr → con_hr (o mover a erp_hr) hse → con_hse ``` #### mecanicas-diesel ```sql -- Actual → Estandar workshop_core → mec_workshop service_management → mec_service parts_management → mec_parts vehicle_management → mec_vehicles ``` --- ## 8. Validacion ### 8.1 Checklist de Validacion ```yaml validacion_schema: - [ ] Prefijo correcto segun proyecto - [ ] Nombre en snake_case - [ ] Tablas en plural - [ ] Columnas obligatorias presentes - [ ] RLS habilitado - [ ] Indices de tenant_id - [ ] Triggers de auditoria ``` ### 8.2 Script de Validacion ```sql -- Verificar schemas con prefijo correcto SELECT schema_name FROM information_schema.schemata WHERE schema_name LIKE 'erp_%' OR schema_name LIKE 'con_%' OR schema_name LIKE 'mec_%' OR schema_name LIKE 'cli_%' OR schema_name LIKE 'ret_%' OR schema_name LIKE 'vit_%'; -- Verificar RLS habilitado SELECT schemaname, tablename, rowsecurity FROM pg_tables WHERE schemaname LIKE '%_%' AND rowsecurity = false; ``` --- ## 9. Excepciones ### 9.1 Schemas de Sistema Los siguientes schemas NO requieren prefijo: - `public` - Extensiones PostgreSQL - `pg_catalog` - Sistema PostgreSQL - `information_schema` - Metadatos ### 9.2 Schemas de Migracion Durante la migracion, pueden coexistir schemas antiguos y nuevos: ```sql -- Temporal durante migracion auth -- Antiguo (deprecado) erp_auth -- Nuevo (activo) ``` --- ## 10. Referencias | Documento | Ubicacion | |-----------|-----------| | ADR-007 Database Design | `erp-core/docs/97-adr/ADR-007-database-design.md` | | DDL erp-core | `erp-core/database/ddl/` | | DDL mecanicas | `mecanicas-diesel/database/ddl/` | | DDL construccion | `construccion/database/ddl/` | --- ## 11. Historial de Cambios | Version | Fecha | Cambios | |---------|-------|---------| | 1.0.0 | 2025-12-08 | Version inicial | --- *Documento de arquitectura - ERP Suite* *Sistema NEXUS - Fabrica de Software con Agentes IA*