Saltearse al contenido

Gestión de Activos

1. Descripción General de la Funcionalidad

El sistema de gestión de activos proporciona seguimiento ligero del ciclo de vida del equipo del cliente a través de una “Hoja de Vida” (HV) que captura información esencial del activo (~20 campos) incluyendo número de serial vía IA/OCR desde fotos, marca, modelo, capacidad, ubicación, fotos e historial completo de órdenes. La decisión estratégica de implementar un HV ligero (no integración completa con el sistema heredado de más de 500 campos) habilita trazabilidad práctica de activos sin complejidad abrumadora. El reconocimiento de serial vía foto elimina la necesidad de etiquetas QR físicas, reduciendo costos de logística y fricción operacional mientras mantiene identificación única de activos a través de OCR impulsado por IA con lógica de reintento y mecanismos de respaldo manual.


2. Contexto de Negocio

Los clientes de Algesta necesitaban trazabilidad de activos para rastrear el historial de mantenimiento, estado de garantía y ciclo de vida del equipo sin la complejidad de su sistema ERP heredado (más de 500 campos). El proceso anterior involucraba mantenimiento manual de registros, calidad de datos inconsistente y ninguna vista centralizada del historial de activos. La HV de activos proporciona un punto medio práctico: información esencial capturada automáticamente durante las solicitudes de servicio, accesible para todas las partes interesadas e integrada con el ciclo de vida de la orden de mantenimiento. Esto es crítico para el cumplimiento (registros de inspección de equipos), operaciones (identificación de problemas recurrentes) y valor para el cliente (demostración del historial de mantenimiento para la valoración de activos).


3. Decisión Estratégica: Serial vía Foto (IA/OCR) vs QR

Contexto de la Decisión (Sprint 5-6 Mesa de Trabajo)

Opciones Consideradas:

  1. Etiquetas de Código QR: Etiquetas físicas adheridas a los activos
  2. Serial vía Foto: OCR para leer placas de serial existentes

Decisión: Serial vía Foto con IA/OCR

Justificación:

  • Costo: Sin producción, impresión o distribución de etiquetas físicas
  • Logística: No es necesario coordinar la colocación de etiquetas con técnicos de campo
  • Activos Existentes: La mayoría de los activos ya tienen placas de serial del fabricante
  • Experiencia del Cliente: Sin “calcomanías” visibles en el equipo
  • Viabilidad Operacional: Los técnicos ya fotografían los activos durante el servicio

Compromisos:

  • Precisión: El OCR requiere buena calidad de foto (iluminación, ángulo, enfoque)
  • Lógica de Reintento: Se necesitan múltiples intentos para seriales ilegibles
  • Respaldo: Entrada manual o generación de ID único si el OCR falla
  • Modelo de IA: Requiere datos de entrenamiento y reentrenamiento periódico

Implementación: Sprint 6-7 con integración de servicio OCR y lógica de reintento


4. Ciclo de Vida del Activo

Flujo del Ciclo de Vida

flowchart TD
    A[Order Created] --> B{Asset Identified?}
    B -->|No - New Asset| C[Technician Photographs Serial Plate]
    B -->|Yes - Existing Asset| N[Link Order to Asset]

    C --> D[OCR Processes Photo]
    D --> E{Serial Recognized?}
    E -->|Yes| F[Confirm Serial with Technician]
    E -->|No - Retry 1| G[Request Clearer Photo]
    G --> D
    E -->|No - Retry 2| H[Request Clearer Photo]
    H --> D
    E -->|No - Final Retry| I[Manual Serial Entry or Generate Unique ID]

    F --> J{Serial Unique?}
    J -->|Yes| K[Create Asset HV]
    J -->|No - Duplicate| L[Link to Existing Asset]

    I --> M[Create Asset HV with Generated ID]

    K --> N
    L --> N
    M --> N

    N --> O[Asset HV Updated with Order Info]
    O --> P[Order Execution]
    P --> Q[Add Photos to Asset HV]
    Q --> R[Update Asset State]
    R --> S[Asset History Timeline]
    S --> T{More Orders?}
    T -->|Yes| N
    T -->|No| U[Asset HV Complete]

5. Historias de Usuario por Sprint

Sprint 6: Reconocimiento de Serial y Creación de HV

US-S6-022: Reconocimiento de Serial vía Foto

  • Descripción: Como técnico, quiero fotografiar la placa de serial de un activo y que el sistema la reconozca automáticamente
  • Criterios de Aceptación:
    • Carga de foto durante la creación o ejecución de la orden
    • El servicio OCR procesa la foto
    • Número de serial extraído y mostrado
    • El técnico puede confirmar o corregir el serial
    • Si el OCR falla, solicitar foto más clara (hasta 3 intentos)
    • Si aún falla, entrada manual de serial o generación de ID único
    • HV de activo creada con el serial
  • Estado: 🟡 En Progreso
  • Implementación:
    • algesta-ms-orders-nestjs/src/shared/services/ocr.service.ts - OCR integration
    • algesta-ms-orders-nestjs/src/shared/services/ocr-label-extractor.service.ts - Label extraction
    • algesta-ms-orders-nestjs/src/application/handlers/commands/recognize-serial.handler.ts - Serial recognition command
  • Pruebas: Sprint 6-7 Pruebas notes - serial recognition tested with sample photos
  • API:
    • POST /api/assets/recognize-serial - OCR serial from photo
    • POST /api/assets/create - Create asset with serial

US-S6-023: Creación Manual de HV

  • Descripción: Como agente, quiero crear manualmente una HV de activo cuando el serial es ilegible o no está disponible
  • Criterios de Aceptación:
    • Formulario con campos esenciales: tipo de activo, marca, modelo, capacidad, ubicación, propietario, fotos
    • Generar ID único de activo si no hay serial
    • HV de activo creada y visible en el panel
    • Vincular a la orden
  • Estado: ✅ Completo
  • Implementación:
    • algesta-ms-orders-nestjs/src/application/handlers/commands/create-asset.handler.ts - Create asset command
  • API: POST /api/assets - Create asset manually

Sprint 7: Gestión Automatizada de HV

US-S7-027: Creación Automatizada de HV desde Orden

  • Descripción: Como sistema, quiero crear o actualizar automáticamente la HV de activo cuando se ejecuta una orden
  • Criterios de Aceptación:
    • Cuando la orden alcanza el estado “TrabajoIniciado”, verificar si existe el activo
    • Si no existe, activar reconocimiento de serial desde fotos de la orden
    • Crear o actualizar HV de activo con información de la orden
    • Agregar orden a la línea de tiempo del historial del activo
    • Actualizar estado del activo según resultado de la orden (funcional, requiere mantenimiento, retirado)
  • Estado: 🟡 En Progreso
  • Implementación:
    • algesta-ms-orders-nestjs/src/application/handlers/commands/create-or-update-asset.handler.ts - Asset HV automation
  • Pruebas: Sprint 7 Pruebas notes - Historia 16016
  • API: POST /api/assets/from-order - Create asset from order

US-S7-028: Seguimiento de Estado del Activo

  • Descripción: Como agente, quiero rastrear el estado operacional del activo a lo largo del tiempo
  • Criterios de Aceptación:
    • Estados de activo: OPERATIONAL, REQUIRES_MAINTENANCE, UNDER_REPAIR, OUT_OF_SERVICE, RETIRED
    • Estado actualizado según resultados de órdenes
    • Historial de estados rastreado con marcas de tiempo
    • Indicadores visuales en el panel (estados codificados por color)
  • Estado: 🟡 En Progreso
  • Implementación:
    • algesta-ms-orders-nestjs/src/domain/entities/asset.entity.ts - Asset entity with state
    • Asset state machine in entity logic

Sprint 8: Acceso y Historial de HV

US-S8-035: Ver HV e Historial de Activo

  • Descripción: Como cliente o agente, quiero ver la HV completa del activo y su historial de mantenimiento
  • Criterios de Aceptación:
    • La página de detalle del activo muestra: serial, marca, modelo, capacidad, ubicación, propietario, fotos, estado actual
    • Línea de tiempo de todas las órdenes asociadas con el activo (cronológico)
    • Para cada orden: fecha, tipo de servicio, proveedor, estado, fotos antes/después
    • Filtrar historial por rango de fechas, tipo de servicio
    • Exportar HV a PDF
  • Estado: 🟡 En Progreso
  • Implementación:
    • algesta-dashboard-react/src/Funcionalidades/assets/Componentes/AssetDetail.tsx - Asset detail UI
    • algesta-ms-orders-nestjs/src/application/handlers/queries/get-asset-history.handler.ts - Asset history query
    • algesta-ms-orders-nestjs/src/shared/services/asset-cv-template.service.ts - PDF export
  • Pruebas: Sprint 8 Pruebas notes - Historia 17988
  • API:
    • GET /api/assets/:id - Get asset details
    • GET /api/assets/:id/history - Get asset order history
    • GET /api/assets/:id/pdf - Export HV to PDF

US-S8-036: Búsqueda y Filtros de Activos

  • Descripción: Como agente, quiero buscar y filtrar activos por varios criterios
  • Criterios de Aceptación:
    • Buscar por: serial, marca, modelo, propietario, ubicación
    • Filtrar por: tipo de activo, estado, fecha del último mantenimiento
    • Ordenar por: serial, fecha de creación, último mantenimiento
    • Paginación para conjuntos de datos grandes
  • Estado: 🟡 En Progreso
  • Implementación:
    • algesta-dashboard-react/src/Funcionalidades/assets/Componentes/AssetList.tsx - Asset list UI
    • algesta-ms-orders-nestjs/src/application/handlers/queries/get-all-assets.handler.ts - List assets query
  • API: GET /api/assets?search=X&state=Y&type=Z - List assets with filters

6. Modelo de Datos del Activo

Entidad de Activo

Referencia: algesta-ms-orders-nestjs/src/domain/entities/asset.entity.ts

CampoTipoDescripciónRequerido
_idObjectIdIdentificador único
assetNumberStringIdentificador único del activo (serial o ID generado)
serialNumberStringSerial del fabricante (si está disponible)No
serialRecognitionMétodoEnumOCR, MANUAL, GENERATED
assetTypeEnumAIR_CONDITIONER, BOILER, ELECTRICAL_PANEL, PUMP, etc.
brandStringMarca del fabricanteNo
modelStringNúmero de modeloNo
capacityStringCapacidad (ej., 12000 BTU, 500L)No
locationObjectUbicación física (edificio, piso, habitación, dirección)
ownerIdObjectIdReferencia al cliente
photosArrayURLs de Azure BlobNo
stateEnumOPERATIONAL, REQUIRES_MAINTENANCE, UNDER_REPAIR, OUT_OF_SERVICE, RETIRED
installationDateDateFecha de instalaciónNo
warrantyExpirationDateDateFecha de vencimiento de garantíaNo
lastMaintenanceDateDateFecha del último servicioNo
nextMaintenanceDateDatePróximo servicio programadoNo
ordersArrayReferencias a órdenesNo
createdAtDateFecha de creación de HV
updatedAtDateÚltima actualización
createdByObjectIdUsuario que creó la HV
notesStringNotas adicionalesNo

Nota: ~20 campos vs. 500+ en el sistema heredado (diseño de HV ligero)


7. Serial Recognition Process

OCR Workflow

sequenceDiagram
    participant Technician
    participant Dashboard
    participant Gateway
    participant OrdersMS
    participant OCRService
    participant AzureBlob

    Technician->>Dashboard: Upload serial plate photo
    Dashboard->>Gateway: POST /api/assets/recognize-serial
    Gateway->>OrdersMS: RecognizeSerialCommand
    OrdersMS->>AzureBlob: Upload photo
    AzureBlob-->>OrdersMS: Photo URL

    OrdersMS->>OCRService: Extract text from photo
    OCRService->>OCRService: Process image (OCR)
    alt Serial recognized
        OCRService-->>OrdersMS: Extracted serial: "ABC123456"
        OrdersMS->>OrdersMS: Validate serial format
        OrdersMS-->>Dashboard: Serial: ABC123456 (confidence: 95%)
        Dashboard->>Technician: Confirm serial?
        Technician->>Dashboard: Confirm
        Dashboard->>Gateway: POST /api/assets/create
        Gateway->>OrdersMS: CreateAssetCommand
        OrdersMS->>OrdersMS: Create Asset HV
    else Serial not recognized (retry 1)
        OCRService-->>OrdersMS: No serial found
        OrdersMS-->>Dashboard: Please retake photo (clearer, better lighting)
        Dashboard->>Technician: Retake photo
        Technician->>Dashboard: Upload new photo
        Dashboard->>Gateway: POST /api/assets/recognize-serial
        Note over OrdersMS,OCRService: Retry logic (up to 3 attempts)
    else Serial still not recognized (final retry)
        OCRService-->>OrdersMS: No serial found
        OrdersMS-->>Dashboard: Manual entry or generate ID?
        Dashboard->>Technician: Choose option
        alt Manual entry
            Technician->>Dashboard: Enter serial manually
        else Generate ID
            Dashboard->>Gateway: POST /api/assets/generate-id
            Gateway->>OrdersMS: GenerateAssetIdCommand
            OrdersMS->>OrdersMS: Generate unique ID: AST-2025-001
            OrdersMS-->>Dashboard: Generated ID: AST-2025-001
        end
    end

OCR Retry Logic

async function recognizeSerial(
photoUrl: string,
attempt: number = 1
): Promise<string> {
const maxAttempts = 3;
try {
const ocrResult = await ocrService.extractText(photoUrl);
const serial = extractSerialFromText(ocrResult.text);
if (serial && validateSerialFormat(serial)) {
return serial;
} else if (attempt < maxAttempts) {
// Retry with different OCR parameters or request new photo
throw new OCRRetryException(
`Serial not found, attempt ${attempt}/${maxAttempts}`
);
} else {
// Final retry failed
throw new OCRFailedException(
"Serial recognition failed after 3 attempts"
);
}
} catch (error) {
if (attempt < maxAttempts) {
// Prompt for clearer photo
throw new OCRRetryException(
`OCR failed, attempt ${attempt}/${maxAttempts}`
);
} else {
// Offer manual entry or ID generation
throw new OCRFailedException("OCR failed, manual intervention required");
}
}
}

Implementación: algesta-ms-orders-nestjs/src/shared/services/ocr.service.ts


8. Asset History and Transactional State

Order Association

All orders associated with an asset are tracked chronologically, forming the asset’s Completo maintenance history.

AssetHistory Entity

Reference: algesta-ms-orders-nestjs/src/domain/entities/asset-history.entity.ts

FieldTypeDescription
_idObjectIdUnique identifier
assetIdObjectIdReference to asset
orderIdObjectIdReference to order
eventTypeEnumCREATED, MAINTENANCE, REPAIR, INSPECTION, STATE_CHANGE, RETIRED
previousStateEnumPrevious asset state
newStateEnumNew asset state
timestampDateWhen event occurred
performedByObjectIdProvider or agent
notesStringEvent Descripción
photosArrayBefore/after photos

History Timeline

gantt
    title Asset HV Timeline Example
    dateFormat YYYY-MM-DD
    section Installation
    Asset Created (Serial: ABC123)        :done, 2023-01-15, 1d
    section Maintenance
    Preventive Maintenance (Provider A)   :done, 2023-03-20, 2d
    Corrective Repair (Provider B)        :done, 2023-06-10, 3d
    Inspection (In-house)                 :done, 2023-09-05, 1d
    section State Changes
    Operational → Requires Maintenance    :done, 2023-12-01, 1d
    Under Repair → Operational            :done, 2023-12-15, 1d

9. HV PDF Export

PDF Template

Generated PDF includes:

  1. Header: Algesta logo, asset number, generation date
  2. Asset Information: Serial, type, brand, model, capacity, location, owner, photos
  3. Current State: Operational Estado with color indicator
  4. Maintenance History: Table of all orders (date, service type, provider, outcome)
  5. Before/After Photos: For each order (if available)
  6. QR Code: Link to online HV (optional)
  7. Footer: Page numbers, confidentiality notice

Implementación: algesta-ms-orders-nestjs/src/shared/services/asset-cv-template.service.ts

API: GET /api/assets/:id/pdf - Export HV to PDF


10. API Endpoints Resumen

EndpointMétodoDescriptionActorSprint
/api/assetsGETList all assets with filtersAgentS8
/api/assets/:idGETGet asset detailsAgent/ClientS8
/api/assetsPOSTCreate asset manuallyAgentS6
/api/assets/from-orderPOSTCreate asset from orderSystemS7
/api/assets/recognize-serialPOSTOCR serial from photoTechnicianS6
/api/assets/generate-idPOSTGenerate unique asset IDSystemS6
/api/assets/:idPUTUpdate asset infoAgentS7
/api/assets/:id/historyGETGet asset order historyAgent/ClientS8
/api/assets/:id/pdfGETExport HV to PDFAgent/ClientS8
/api/assets/:id/photosPOSTAdd photos to assetTechnicianS7
/api/assets/:id/statePUTUpdate asset stateAgentS7

Reference: algesta-ms-orders-nestjs/src/infrastructure/controllers/assets.controller.ts


11. Integration Points

Internal Service Integration

  1. Orders Service:

    • Asset created or updated during order execution
    • Order linked to asset in HV
    • Asset state updated based on order outcome
  2. Notifications Service:

    • Notify client when HV created
    • Notify client of asset state changes

External Integration

  1. Azure Blob Storage: Photo and Documento storage
  2. OCR Service: Serial recognition from photos (Azure Computer Vision or custom)
  3. WhatsApp (Jelou): Photo capture from technicians in field

12. Key Workflows with Sequence Diagrams

Asset Creation from Order with OCR

sequenceDiagram
    participant Technician
    participant WhatsApp
    participant Gateway
    participant OrdersMS
    participant OCRService
    participant AzureBlob

    Note over Technician,AzureBlob: Order Execution Phase

    Technician->>WhatsApp: Send message "Starting work on order ORD-2025-001"
    Technician->>WhatsApp: Attach photo of asset serial plate
    WhatsApp->>Gateway: POST /api/orders/:id/start-work (with photo)
    Gateway->>OrdersMS: StartWorkCommand
    OrdersMS->>OrdersMS: Update order state to TrabajoIniciado
    OrdersMS->>OrdersMS: Check if asset exists
    alt Asset not found
        OrdersMS->>AzureBlob: Upload serial photo
        AzureBlob-->>OrdersMS: Photo URL
        OrdersMS->>OCRService: Extract text from photo
        OCRService-->>OrdersMS: Extracted serial: "XYZ789"
        OrdersMS->>OrdersMS: Check if serial unique
        alt Serial unique
            OrdersMS->>OrdersMS: Create Asset HV
            OrdersMS->>OrdersMS: Link order to asset
            OrdersMS->>OrdersMS: Create AssetHistory record
            OrdersMS-->>Gateway: Work started, asset HV created
        else Serial exists
            OrdersMS->>OrdersMS: Link order to existing asset
            OrdersMS->>OrdersMS: Update AssetHistory
            OrdersMS-->>Gateway: Work started, asset linked
        end
    else Asset exists
        OrdersMS->>OrdersMS: Link order to asset
        OrdersMS->>OrdersMS: Update AssetHistory
        OrdersMS-->>Gateway: Work started
    end
    Gateway-->>WhatsApp: Confirmation
    WhatsApp->>Technician: "Work started, asset HV updated"

Asset History Retrieval

sequenceDiagram
    participant Client
    participant Dashboard
    participant Gateway
    participant OrdersMS

    Client->>Dashboard: Navigate to Assets section
    Dashboard->>Gateway: GET /api/assets?ownerId=:clientId
    Gateway->>OrdersMS: GetAllAssetsQuery
    OrdersMS-->>Dashboard: List of client's assets

    Client->>Dashboard: Click asset to view details
    Dashboard->>Gateway: GET /api/assets/:id
    Gateway->>OrdersMS: GetAssetByIdQuery
    OrdersMS->>OrdersMS: Retrieve asset with full history
    OrdersMS->>OrdersMS: Get all orders associated with asset
    OrdersMS->>OrdersMS: Build timeline
    OrdersMS-->>Dashboard: Asset details + order history timeline

    Dashboard->>Client: Display asset HV with timeline

    Client->>Dashboard: Click "Export to PDF"
    Dashboard->>Gateway: GET /api/assets/:id/pdf
    Gateway->>OrdersMS: GenerateAssetPDFQuery
    OrdersMS->>OrdersMS: Generate PDF from template
    OrdersMS-->>Dashboard: PDF file
    Dashboard->>Client: Download PDF

13. Pruebas Evidence

From unified_Pruebas_notes.md:

Sprint 7 - Historia 16016: Asset HV Automation

Pre-requisites:

  • Orders in “TrabajoIniciado” state
  • Photos available for OCR
  • OCR service configured

Scenarios Tested:

  1. Serial Recognition Success:

    • Action: Upload clear serial plate photo
    • Expected: Serial extracted, asset HV created
    • Result: ✅ Validated
  2. Serial Recognition Failure (Retry):

    • Action: Upload blurry photo
    • Expected: Prompt for clearer photo, retry OCR
    • Result: ✅ Validated
  3. Manual Serial Entry:

    • Action: OCR fails after 3 attempts, enter serial manually
    • Expected: Asset HV created with manual serial
    • Result: ✅ Validated
  4. Unique ID Generation:

    • Action: No serial available, generate unique ID
    • Expected: Asset HV created with generated ID (AST-2025-XXX)
    • Result: ✅ Validated

Sprint 8 - Historia 17988: Asset HV Access

Scenarios Tested:

  1. Asset List with Filters:

    • Action: View assets, filter by state, search by serial
    • Expected: Correct assets displayed
    • Result: ✅ Validated
  2. Asset Detail View:

    • Action: View asset details with history timeline
    • Expected: All information displayed, timeline chronological
    • Result: ✅ Validated
  3. PDF Export:

    • Action: Export asset HV to PDF
    • Expected: PDF generated with all data and photos
    • Result: 🟡 Partial - PDF generation works, formatting needs refinement

Known Issues:

  • HV field persistence issues (some fields not saving correctly)
  • PDF export formatting inconsistencies
  • Completo history consolidation Pendiente (orders not fully linked)

14. Known Issues and Future Enhancements

From Completo_backlog_analysis.md:

🟧 Critical Issues

  • WhatsApp Business Integration Impediment: Photo capture from WhatsApp unreliable, affecting serial recognition workflow ✅ Resolved
  • HV Field Persistence: Some asset fields not saving correctly (brand, model, capacity)
  • Completo History Consolidation: Not all orders properly linked to assets in history timeline

🟨 Essential MVP Improvements

  • Completo HV History: Ensure all orders linked and visible in timeline
  • HV PDF Export Refinement: Improve formatting, add QR code, ensure all photos included
  • Serial Format Validation: Add validation rules for different serial formats by asset type
  • Asset State Automation: Automatically update state based on order outcomes

🟩 Post-MVP Operaciones

  • AI Model Retraining: Collect more serial photos to improve OCR accuracy
  • Integration with Legacy System: Sync in-house asset data with legacy ERP
  • Preventive Maintenance Automation: Trigger preventive orders based on asset’s next maintenance date
  • Asset Valuation Tracking: Track asset depreciation and market Valor

🟦 Future Backlog

  • IoT Integration: Connect sensors for real-time asset monitoring (temperature, pressure, etc.)
  • Predictive Maintenance: ML model to predict asset failures based on history
  • Asset Geolocation: GPS tracking for mobile assets
  • Mobile App for Technicians: Dedicated app for photo capture and serial recognition
  • Asset QR Codes (Optional): Generate QR codes for assets after creation for easier lookup

15. Referencias Cruzadas

Arquitectura Documentoation

Data Flows

Sprint Documentoation

Sprint 6-8 Documentoation (see docs/Sprint_6.md through Sprint_8.md in project Repositorio)

Pruebas

Unified Pruebas Notes (Sprint 7 - Historia 16016, Sprint 8 - Historia 17988) (see test/unified_Pruebas_notes.md in project Repositorio)


Last Updated: 2025-11-20 | Next Review: End of Guarantee Phase