# FASE 2: Análisis Detallado - ERP Clínicas **Proyecto:** erp-clinicas **Fecha:** 2026-01-04 **Estado:** Completado **Base:** FASE-1-ANALISIS-INICIAL.md --- ## 1. Análisis de Dependencias ### 1.1 Dependencias de ERP-Core | Schema | Tabla | Requerida | Uso | |--------|-------|-----------|-----| | core | tenants | ✅ | Multi-tenant | | core | partners | ✅ | Pacientes/proveedores | | core | users | ✅ | Usuarios sistema | | hr | employees | ✅ | Personal médico | | hr | departments | ✅ | Áreas de clínica | | financial | accounts | ⚠️ | Contabilidad | | financial | journals | ⚠️ | Diarios contables | | financial | payment_terms | ✅ | Términos de pago | | inventory | products | ⚠️ | Medicamentos/insumos | | inventory | warehouses | ⚠️ | Farmacia/bodega | ### 1.2 Dependencias Internas ``` clinica.specialties └── clinica.doctors (specialty_id) └── clinica.appointment_slots (doctor_id) └── clinica.appointments (slot_id) clinica.patients ├── clinica.patient_contacts (patient_id) ├── clinica.patient_insurance (patient_id) ├── clinica.appointments (patient_id) └── clinica.medical_records (patient_id) └── clinica.consultations (record_id) ├── clinica.vital_signs (consultation_id) ├── clinica.diagnoses (consultation_id) └── clinica.prescriptions (consultation_id) └── clinica.prescription_items (prescription_id) ``` --- ## 2. Detalle de Correcciones por Módulo ### 2.1 Financial - Extensiones #### COR-035: payment_term_lines ```sql CREATE TABLE financial.payment_term_lines ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), tenant_id UUID NOT NULL, payment_term_id UUID REFERENCES financial.payment_terms(id), value_type VARCHAR(20) NOT NULL, -- 'percent', 'balance', 'fixed' value NUMERIC(10,2) DEFAULT 0, days INTEGER DEFAULT 0, day_of_month INTEGER, applies_to VARCHAR(50), -- 'consulta', 'procedimiento', 'laboratorio' sequence INTEGER DEFAULT 10, created_at TIMESTAMPTZ DEFAULT NOW() ); ``` #### COR-037: payment_methods ```sql CREATE TABLE financial.payment_methods ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), tenant_id UUID NOT NULL, name VARCHAR(100) NOT NULL, code VARCHAR(20) NOT NULL, payment_type financial.payment_method_type NOT NULL, -- Extensiones clínica aplica_seguro BOOLEAN DEFAULT false, requiere_factura BOOLEAN DEFAULT false, porcentaje_seguro NUMERIC(5,2) DEFAULT 0, active BOOLEAN DEFAULT true, created_at TIMESTAMPTZ DEFAULT NOW(), UNIQUE(tenant_id, code) ); ``` ### 2.2 Inventory - Extensiones #### COR-042: storage_categories (Clínica) ```sql CREATE TABLE inventory.storage_categories ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), tenant_id UUID NOT NULL, name VARCHAR(100) NOT NULL, max_weight NUMERIC(10,2), allow_new_product VARCHAR(20) DEFAULT 'mixed', -- Extensiones clínica requiere_refrigeracion BOOLEAN DEFAULT false, temperatura_min NUMERIC(5,2), temperatura_max NUMERIC(5,2), es_controlado BOOLEAN DEFAULT false, requiere_receta BOOLEAN DEFAULT false, created_at TIMESTAMPTZ DEFAULT NOW() ); ``` #### COR-040: packages (Medicamentos) ```sql CREATE TABLE inventory.packages ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), tenant_id UUID NOT NULL, package_type_id UUID REFERENCES inventory.package_types(id), name VARCHAR(100), -- Extensiones clínica lote VARCHAR(50), fecha_fabricacion DATE, fecha_caducidad DATE, laboratorio VARCHAR(100), registro_sanitario VARCHAR(50), created_at TIMESTAMPTZ DEFAULT NOW() ); ``` ### 2.3 HR - Extensiones #### COR-062: work_locations (Consultorios) ```sql CREATE TABLE hr.work_locations ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), tenant_id UUID NOT NULL, name VARCHAR(100) NOT NULL, address_id UUID, -- Extensiones clínica tipo_consultorio VARCHAR(50), -- 'general', 'especialidad', 'urgencias', 'quirofano' capacidad INTEGER DEFAULT 1, equipamiento TEXT[], horario_apertura TIME, horario_cierre TIME, active BOOLEAN DEFAULT true, created_at TIMESTAMPTZ DEFAULT NOW() ); ``` #### COR-063: skills (Especialidades Médicas) ```sql -- Tipos de habilidad para clínicas CREATE TABLE hr.skill_types ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), tenant_id UUID NOT NULL, name VARCHAR(100) NOT NULL, -- 'Especialidad', 'Certificación', 'Curso', 'Idioma' created_at TIMESTAMPTZ DEFAULT NOW() ); -- Skills específicos CREATE TABLE hr.skills ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), tenant_id UUID NOT NULL, skill_type_id UUID REFERENCES hr.skill_types(id), name VARCHAR(100) NOT NULL, -- Extensiones clínica codigo_ssa VARCHAR(20), -- Código SSA de especialidad requiere_cedula BOOLEAN DEFAULT false, created_at TIMESTAMPTZ DEFAULT NOW() ); ``` ### 2.4 Projects - Adaptaciones #### COR-056: collaborators → personal_clinica ```sql CREATE TABLE clinica.personal_clinica ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), tenant_id UUID NOT NULL, employee_id UUID NOT NULL, consultorio_id UUID REFERENCES hr.work_locations(id), rol VARCHAR(50) NOT NULL, -- 'medico', 'enfermera', 'recepcion', 'auxiliar' vigencia_desde DATE, vigencia_hasta DATE, es_titular BOOLEAN DEFAULT false, horario JSONB, created_at TIMESTAMPTZ DEFAULT NOW() ); ``` #### COR-059: ratings (Satisfacción) ```sql CREATE TABLE clinica.ratings ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), tenant_id UUID NOT NULL, consultation_id UUID REFERENCES clinica.consultations(id), patient_id UUID REFERENCES clinica.patients(id), doctor_id UUID REFERENCES clinica.doctors(id), rating INTEGER CHECK (rating BETWEEN 1 AND 5), feedback TEXT, rated_at TIMESTAMPTZ DEFAULT NOW(), created_at TIMESTAMPTZ DEFAULT NOW() ); ``` --- ## 3. ENUMs Requeridos ### 3.1 Nuevos ENUMs ```sql -- Financial CREATE TYPE financial.payment_method_type AS ENUM ('inbound', 'outbound'); CREATE TYPE financial.reconcile_model_type AS ENUM ('writeoff_button', 'writeoff_suggestion', 'invoice_matching'); -- HR CREATE TYPE hr.expense_status AS ENUM ('draft', 'submitted', 'approved', 'posted', 'paid', 'rejected'); CREATE TYPE hr.resume_line_type AS ENUM ('experience', 'education', 'certification', 'internal'); CREATE TYPE hr.payslip_status AS ENUM ('draft', 'verify', 'done', 'cancel'); -- Clínica (existentes) -- appointment_status, patient_gender, blood_type, consultation_status ``` --- ## 4. Tablas a Crear ### 4.1 Resumen por Schema | Schema | Tablas Nuevas | Extensiones | |--------|---------------|-------------| | financial | 4 | 0 | | inventory | 5 | 2 campos | | purchase | 1 | 0 | | hr | 11 | 2 campos | | clinica | 2 | 0 | | **Total** | **23** | **4 campos** | ### 4.2 Lista de Tablas **Financial (4):** 1. payment_term_lines 2. payment_methods 3. reconcile_models 4. reconcile_model_lines **Inventory (5):** 1. package_types 2. packages 3. storage_categories 4. putaway_rules 5. removal_strategies **Purchase (1):** 1. product_supplierinfo **HR (11):** 1. work_locations 2. skill_types 3. skills 4. skill_levels 5. employee_skills 6. expense_sheets 7. expenses 8. employee_resume_lines 9. payslip_structures 10. payslips 11. payslip_lines **Clínica (2):** 1. personal_clinica 2. ratings --- ## 5. Índices Requeridos ### 5.1 Por Tabla Principal | Tabla | Índices | |-------|---------| | payment_methods | tenant_id, code | | storage_categories | tenant_id, es_controlado | | packages | tenant_id, lote, fecha_caducidad | | work_locations | tenant_id, tipo_consultorio | | skills | tenant_id, skill_type_id, codigo_ssa | | expenses | tenant_id, employee_id, status | | personal_clinica | tenant_id, employee_id, consultorio_id | | ratings | tenant_id, consultation_id, doctor_id | --- ## 6. Validaciones NOM-024-SSA3-2012 ### 6.1 Requisitos de Expediente Clínico Electrónico | Requisito | Implementación | |-----------|----------------| | Identificación única | patient.id (UUID) | | Datos de identificación | patients tabla | | Historial clínico | medical_records | | Notas médicas | consultations | | Signos vitales | vital_signs | | Diagnósticos CIE-10 | diagnoses.cie10_code | | Prescripciones | prescriptions | | Trazabilidad | created_at, updated_at | | Firma electrónica | Por implementar | | Confidencialidad | RLS + encriptación | --- ## 7. Próximos Pasos 1. ✅ Análisis detallado completado 2. ⏳ FASE 3: Plan de implementación 3. ⏳ FASE 4: Validación del plan 4. ⏳ FASE 5-8: Implementación --- **Estado:** FASE 2 COMPLETADA **Siguiente:** FASE 3 - Plan de Implementación **Fecha:** 2026-01-04