ソースを参照

adaptación de componentes para usarlos para las ordenes de visita tecnica no programada. Selección de operarios, aceptacion o rechazo por parte de los operarios, visualización de firma y de comentarios.

EmilianoOrtiz 1 週間 前
コミット
8827926ee6

+ 237 - 93
src/app/components/corrective-maintenance/operations-management/staff-selection/staff-selection.component.ts

@@ -1,22 +1,32 @@
-
 import { Component, Inject, OnInit, DOCUMENT } from '@angular/core';
 import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';
 import { ResourcesService } from '../../../../services/resources.service';
-import { CorrectiveWorkOrderDetailsResponse, WorkOrderStatusHistoryListItem } from '../../../../interfaces/corrective-maintenance.interface';
+import {
+  CorrectiveWorkOrderDetailsResponse,
+  WorkOrderStatusHistoryListItem,
+} from '../../../../interfaces/corrective-maintenance.interface';
+import { PreventiveVisitDetailsResponse } from '../../../../interfaces/preventive-maintenance.interface';
 import { lastValueFrom } from 'rxjs';
 import { CorrectiveMaintenanceService } from '../../../../services/corrective-maintenance.service';
+import { PreventiveMaintenanceService } from '../../../../services/preventive-maintenance.service';
 import { FormControl, FormGroup, Validators } from '@angular/forms';
 import { EncService } from '../../../../services/enc.service';
 import { EmployeeService } from '../../../../services/personal-management/employee.service';
-import { EmployeesListItem, EmployeesListResponse } from '../../../../interfaces/personal-managment/employee.interface';
+import {
+  EmployeesListItem,
+  EmployeesListResponse,
+} from '../../../../interfaces/personal-managment/employee.interface';
 import { SubcontratistService } from '../../../../services/personal-management/subcontratist.service';
-import { SubcontratistItem, SubcontratistsResponse } from '../../../../interfaces/personal-managment/subcontratists.interface';
+import {
+  SubcontratistItem,
+  SubcontratistsResponse,
+} from '../../../../interfaces/personal-managment/subcontratists.interface';
 
 @Component({
   selector: 'app-staff-selection',
   standalone: false,
   templateUrl: './staff-selection.component.html',
-  styleUrl: './staff-selection.component.css'
+  styleUrl: './staff-selection.component.css',
 })
 export class StaffSelectionComponent implements OnInit {
   isLoading: boolean;
@@ -27,6 +37,7 @@ export class StaffSelectionComponent implements OnInit {
   employees: EmployeesListItem[];
   subcontratists: EmployeesListItem[];
   excludedUsers: string[];
+  orderType: 'Correctivo' | 'Preventivo';
 
   formGroup: FormGroup;
 
@@ -36,113 +47,209 @@ export class StaffSelectionComponent implements OnInit {
     private _resourcesService: ResourcesService,
     private _dialogRef: MatDialogRef<StaffSelectionComponent>,
     private _correctiveMaintenanceService: CorrectiveMaintenanceService,
+    private _preventiveMaintenanceService: PreventiveMaintenanceService,
     private _encService: EncService,
     private _employeeService: EmployeeService,
-    private _subcontratistService: SubcontratistService,
+    private _subcontratistService: SubcontratistService
   ) {
     this.isLoading = true;
     this.hasError = true;
-    this.errorStr = "";
+    this.errorStr = '';
     this.staffSpecialtiesMap = new Map();
     this.staffOperariesMap = new Map();
     this.employees = [];
     this.subcontratists = [];
     this.excludedUsers = [];
+    this.orderType = 'Correctivo'; // default
 
     this.formGroup = new FormGroup({});
   }
 
   ngOnInit(): void {
-    if(this._data.idOrder != null && this._data.idOrder != undefined){
+    if (this._data.idOrder != null && this._data.idOrder != undefined) {
+      // Set orderType from data, default to 'corrective' if not provided
+      this.orderType = this._data.orderType || 'Correctivo';
       this.getOrderDetails();
-    }else{
-      this._resourcesService.openSnackBar('No se envió el ID de la orden de mantenimiento.');
+    } else {
+      this._resourcesService.openSnackBar(
+        'No se envió el ID de la orden de mantenimiento.'
+      );
       this._dialogRef.close();
     }
   }
 
-  private async getOrderDetails(){
-    try{
+  private async getOrderDetails() {
+    try {
       let idUser = localStorage.getItem('idusuario')!;
-      let order: CorrectiveWorkOrderDetailsResponse = await lastValueFrom(this._correctiveMaintenanceService.getWorkOrder(
-        this._data.idOrder,
-        idUser,
-        1
-      ));
+      let personalData: string = '';
+      let historialEstatus: string = '';
+
+      console.log('🔍 Staff Selection - Order Type:', this.orderType);
+      console.log('🔍 Staff Selection - Order ID:', this._data.idOrder);
+
+      // Fetch order details based on orderType
+      if (this.orderType === 'Correctivo') {
+        let order: CorrectiveWorkOrderDetailsResponse = await lastValueFrom(
+          this._correctiveMaintenanceService.getWorkOrder(
+            this._data.idOrder,
+            idUser,
+            1
+          )
+        );
+
+        console.log('✅ Corrective Order Response:', order);
+
+        this.hasError = order.error;
+        this.errorStr = order.msg;
+
+        if (this.hasError) {
+          console.error('❌ Error getting corrective order:', this.errorStr);
+          this.isLoading = false;
+          return;
+        }
 
-      this.hasError = order.error;
-      this.errorStr = order.msg;
+        personalData = order.response.PERSONAL;
+        historialEstatus = order.response.HISTORIAL_ESTATUS;
+        console.log('📋 PERSONAL data (raw):', personalData);
+      } else {
+        // Preventive maintenance
+        let order: PreventiveVisitDetailsResponse = await lastValueFrom(
+          this._preventiveMaintenanceService.getVisit(
+            this._data.idOrder,
+            idUser,
+            1
+          )
+        );
+
+        console.log('✅ Preventive Order Response:', order);
+
+        this.hasError = order.error;
+        this.errorStr = order.msg;
+
+        if (this.hasError) {
+          console.error('❌ Error getting preventive order:', this.errorStr);
+          this.isLoading = false;
+          return;
+        }
 
-      if(this.hasError){
-        this.isLoading = false;
-      }else{
-        let statusHistory: WorkOrderStatusHistoryListItem[] = JSON.parse(order.response.HISTORIAL_ESTATUS);
-        let validatedStatus = statusHistory.filter(item => item.ESTADO == 'VA');
+        personalData = order.response.PERSONAL || '';
+        // Preventive visits might not have HISTORIAL_ESTATUS in the same format
+        // We'll handle this case by using an empty string
+        historialEstatus = '';
+        console.log('📋 PERSONAL data (raw):', personalData);
+      }
 
-        if(validatedStatus.length > 0){
+      // Process excluded users from status history (only for corrective orders)
+      if (this.orderType === 'Correctivo' && historialEstatus) {
+        let statusHistory: WorkOrderStatusHistoryListItem[] =
+          JSON.parse(historialEstatus);
+        let validatedStatus = statusHistory.filter(
+          (item) => item.ESTADO == 'VA'
+        );
+
+        if (validatedStatus.length > 0 && validatedStatus[0].ATENCION) {
           let excludedUsersArr: string[] = [];
-          for(const item of validatedStatus[0].ATENCION!){
-            if(item.RESPUESTA == 'R') excludedUsersArr.push(item.ID);
+          for (const item of validatedStatus[0].ATENCION!) {
+            if (item.RESPUESTA == 'R') excludedUsersArr.push(item.ID);
           }
 
           this.excludedUsers = excludedUsersArr;
         }
+      }
 
-        let staffArr = JSON.parse(order.response.PERSONAL);
-        for(const specialty of staffArr){
+      // Process staff requirements (same for both types)
+      if (personalData) {
+        let staffArr = JSON.parse(personalData);
+        console.log('👥 Staff Array (parsed):', staffArr);
+
+        for (const specialty of staffArr) {
           let idDec = await this._encService.decrypt(specialty.ID);
+          console.log(`🔓 Specialty ID decrypted: ${specialty.ID} -> ${idDec}`);
+          console.log(
+            `📛 Specialty Name: ${specialty.NAME}, Cantidad: ${specialty.CANT}`
+          );
+
           this.staffSpecialtiesMap.set(idDec, specialty.NAME);
 
-          let operaries: string[] = this.staffOperariesMap.get(idDec) === undefined ? [] : this.staffOperariesMap.get(idDec)!;
-          for(let i = 0; i < specialty.CANT; i++){
+          let operaries: string[] =
+            this.staffOperariesMap.get(idDec) === undefined
+              ? []
+              : this.staffOperariesMap.get(idDec)!;
+          for (let i = 0; i < specialty.CANT; i++) {
             let index = `${idDec}${i}Control`;
-            this.formGroup.addControl(index, new FormControl('', Validators.required));
-            
+            console.log(`➕ Adding form control: ${index}`);
+            this.formGroup.addControl(
+              index,
+              new FormControl('', Validators.required)
+            );
+
             operaries.push(index);
           }
 
           this.staffOperariesMap.set(idDec, operaries);
         }
 
-        this.getEmployees();
+        console.log('🗺️ staffSpecialtiesMap:', this.staffSpecialtiesMap);
+        console.log('🗺️ staffOperariesMap:', this.staffOperariesMap);
+      } else {
+        console.warn('⚠️ No PERSONAL data found in response');
       }
-    }catch(error: any){
-      if(error.error == undefined){
-        this.errorStr = "Ocurrió un error inesperado.";
-      }else if(error.error.msg == undefined){
-        this.errorStr = "Ocurrió un error inesperado.";
-      }else{
+
+      this.getEmployees();
+    } catch (error: any) {
+      if (error.error == undefined) {
+        this.errorStr = 'Ocurrió un error inesperado.';
+      } else if (error.error.msg == undefined) {
+        this.errorStr = 'Ocurrió un error inesperado.';
+      } else {
         this.errorStr = error.error.msg;
       }
+      this.hasError = true;
+      this.isLoading = false;
     }
   }
 
-  private async getEmployees(){
-    try{
+  private async getEmployees() {
+    try {
       let idUser = localStorage.getItem('idusuario')!;
-      let employees: EmployeesListResponse = await lastValueFrom(this._employeeService.getConsultOfEmployees(idUser, 1));
+      let employees: EmployeesListResponse = await lastValueFrom(
+        this._employeeService.getConsultOfEmployees(idUser, 1)
+      );
+
+      console.log('👷 Employees Response:', employees);
 
       this.hasError = employees.error;
       this.errorStr = employees.msg;
 
-      if(this.hasError){
+      if (this.hasError) {
+        console.error('❌ Error getting employees:', this.errorStr);
         this.isLoading = false;
-      }else{
+      } else {
         let employeesArr: EmployeesListItem[] = [];
         let subcontratistsEmployees: EmployeesListItem[] = [];
-        
-        for(const employee of employees.response){
+        console.log(
+          `📊 Total employees received: ${employees.response.length}`
+        );
+
+        for (const employee of employees.response) {
           let idEmployee = await this._encService.decrypt(employee.ID_EMPLOYEE);
           employee.NAME = `${employee.NAME} (${idEmployee})`;
 
-          if(employee.CONTRACT_TYPE == 'Interno' && employee.STATUS == 'Activo'){
+          if (
+            employee.CONTRACT_TYPE == 'Interno' &&
+            employee.STATUS == 'Activo'
+          ) {
             let specialtiesArr = JSON.parse(employee.SPECIALITY);
             let specialtiesStrArr: string[] = [];
 
-            for(const specialtyStr of specialtiesArr){
-              let specialtyEnc = await this._encService.isEncrypted(specialtyStr);
-              let specialtyDec = specialtyEnc ? await this._encService.decrypt(specialtyStr) : specialtyStr;
-              let specialtyArr = specialtyDec.split(" - ");
+            for (const specialtyStr of specialtiesArr) {
+              let specialtyEnc = await this._encService.isEncrypted(
+                specialtyStr
+              );
+              let specialtyDec = specialtyEnc
+                ? await this._encService.decrypt(specialtyStr)
+                : specialtyStr;
+              let specialtyArr = specialtyDec.split(' - ');
               let specialtyInd = specialtyArr[0];
 
               specialtiesStrArr.push(specialtyInd);
@@ -150,97 +257,133 @@ export class StaffSelectionComponent implements OnInit {
 
             employee.SPECIALITY_ARR = specialtiesStrArr;
             let idUser = await this._encService.decrypt(employee.ID_USUARIO);
-            let userExceptionFilt = this.excludedUsers.filter(item => item == idUser);
+            let userExceptionFilt = this.excludedUsers.filter(
+              (item) => item == idUser
+            );
 
-            if(userExceptionFilt.length <= 0){
+            if (userExceptionFilt.length <= 0) {
               employeesArr.push(employee);
             }
-          }else if(employee.CONTRACT_TYPE == 'Subcontratista'){
+          } else if (employee.CONTRACT_TYPE == 'Subcontratista') {
             subcontratistsEmployees.push(employee);
           }
         }
 
         this.employees = employeesArr;
+        console.log(`✅ Internal employees filtered: ${employeesArr.length}`);
+        console.log(
+          `🏢 Subcontractor employees to process: ${subcontratistsEmployees.length}`
+        );
         this.getSubcontratists(subcontratistsEmployees);
       }
-    }catch(error: any){
-      if(error.error == undefined){
-        this.errorStr = "Ocurrió un error inesperado.";
-      }else if(error.error.msg == undefined){
-        this.errorStr = "Ocurrió un error inesperado.";
-      }else{
+    } catch (error: any) {
+      if (error.error == undefined) {
+        this.errorStr = 'Ocurrió un error inesperado.';
+      } else if (error.error.msg == undefined) {
+        this.errorStr = 'Ocurrió un error inesperado.';
+      } else {
         this.errorStr = error.error.msg;
       }
     }
   }
 
-  private async getSubcontratists(subcontratistsEmployees: EmployeesListItem[]){
-    try{
+  private async getSubcontratists(
+    subcontratistsEmployees: EmployeesListItem[]
+  ) {
+    try {
       let idUser = localStorage.getItem('idusuario')!;
-      let subcontratists: SubcontratistsResponse = await lastValueFrom(this._subcontratistService.getConsultOfSubcontratists(idUser, 1));
+      let subcontratists: SubcontratistsResponse = await lastValueFrom(
+        this._subcontratistService.getConsultOfSubcontratists(idUser, 1)
+      );
 
       this.hasError = subcontratists.error;
       this.errorStr = subcontratists.msg;
 
-      if(!this.hasError){
+      if (!this.hasError) {
         let subcontratistsArr: SubcontratistItem[] = [];
-        for(const subcontratist of subcontratists.response){
-          subcontratist.ID_SUBCONTRATIST = await this._encService.decrypt(subcontratist.ID_SUBCONTRATIST);
+        for (const subcontratist of subcontratists.response) {
+          subcontratist.ID_SUBCONTRATIST = await this._encService.decrypt(
+            subcontratist.ID_SUBCONTRATIST
+          );
           subcontratistsArr.push(subcontratist);
         }
 
         let subcontratistEmployeesArr: EmployeesListItem[] = [];
-        for(const employee of subcontratistsEmployees){
-          let idSubcontratistDec = await this._encService.decrypt(employee.ID_SUBCONTRATISTA!);
-          let subcontratistFilt = subcontratistsArr.filter(item => item.ID_SUBCONTRATIST == idSubcontratistDec);
-
-          if(subcontratistFilt.length > 0){
+        for (const employee of subcontratistsEmployees) {
+          let idSubcontratistDec = await this._encService.decrypt(
+            employee.ID_SUBCONTRATISTA!
+          );
+          let subcontratistFilt = subcontratistsArr.filter(
+            (item) => item.ID_SUBCONTRATIST == idSubcontratistDec
+          );
+
+          if (subcontratistFilt.length > 0) {
             let specialtiesArr = JSON.parse(employee.SPECIALITY);
             let specialtiesStrArr: string[] = [];
 
-            for(const specialtyStr of specialtiesArr){
-              let specialtyEnc = await this._encService.isEncrypted(specialtyStr);
-              let specialtyDec = specialtyEnc ? await this._encService.decrypt(specialtyStr) : specialtyStr;
-              let specialtyArr = specialtyDec.split(" - ");
+            for (const specialtyStr of specialtiesArr) {
+              let specialtyEnc = await this._encService.isEncrypted(
+                specialtyStr
+              );
+              let specialtyDec = specialtyEnc
+                ? await this._encService.decrypt(specialtyStr)
+                : specialtyStr;
+              let specialtyArr = specialtyDec.split(' - ');
               let specialtyInd = specialtyArr[0];
 
               specialtiesStrArr.push(specialtyInd);
             }
-            
+
             employee.SPECIALITY_ARR = specialtiesStrArr;
             employee.NAME = `${subcontratistFilt[0].NAME} - ${employee.NAME}`;
             let idUser = await this._encService.decrypt(employee.ID_USUARIO);
-            let userExceptionFilt = this.excludedUsers.filter(item => item == idUser);
+            let userExceptionFilt = this.excludedUsers.filter(
+              (item) => item == idUser
+            );
 
-            if(userExceptionFilt.length <= 0){
+            if (userExceptionFilt.length <= 0) {
               subcontratistEmployeesArr.push(employee);
             }
           }
         }
 
         this.subcontratists = subcontratistEmployeesArr;
+        console.log(
+          `✅ Final subcontractor employees: ${subcontratistEmployeesArr.length}`
+        );
       }
 
+      console.log('🎯 Final data loaded:');
+      console.log('  - Employees:', this.employees.length);
+      console.log('  - Subcontratists:', this.subcontratists.length);
+      console.log('  - Specialties Map:', this.staffSpecialtiesMap);
+      console.log('  - Operaries Map:', this.staffOperariesMap);
+
       this.isLoading = false;
-    }catch(error: any){
-      if(error.error == undefined){
-        this.errorStr = "Ocurrió un error inesperado.";
-      }else if(error.error.msg == undefined){
-        this.errorStr = "Ocurrió un error inesperado.";
-      }else{
+    } catch (error: any) {
+      if (error.error == undefined) {
+        this.errorStr = 'Ocurrió un error inesperado.';
+      } else if (error.error.msg == undefined) {
+        this.errorStr = 'Ocurrió un error inesperado.';
+      } else {
         this.errorStr = error.error.msg;
       }
     }
   }
 
-  isSelected(value: string): boolean{
+  isSelected(value: string): boolean {
     let isSelected = false;
 
-    for(const key in this.formGroup.controls){
+    for (const key in this.formGroup.controls) {
       let control = this.formGroup.controls[key];
       let selection = control.value;
 
-      if(selection != null && selection != undefined && selection != '' && selection == value){
+      if (
+        selection != null &&
+        selection != undefined &&
+        selection != '' &&
+        selection == value
+      ) {
         isSelected = true;
       }
     }
@@ -248,17 +391,17 @@ export class StaffSelectionComponent implements OnInit {
     return isSelected;
   }
 
-  async saveConfig(){
+  async saveConfig() {
     let config = [];
-    for(const key of this.staffOperariesMap.keys()){
+    for (const key of this.staffOperariesMap.keys()) {
       let operaries = this.staffOperariesMap.get(key)!;
       let operariesConfig = [];
 
-      for(const control of operaries){
+      for (const control of operaries) {
         let controlValue = this.formGroup.controls[control].value;
         let valueArr = controlValue.split('|');
 
-        if(valueArr.length > 1){
+        if (valueArr.length > 1) {
           let operaryConfig = {
             ID: valueArr[0],
             TYPE: valueArr[1],
@@ -270,13 +413,14 @@ export class StaffSelectionComponent implements OnInit {
 
       let specialtyConfig = {
         SPECIALTY: await this._encService.encrypt(key),
-        STAFF: operariesConfig
+        STAFF: operariesConfig,
       };
 
       config.push(specialtyConfig);
     }
 
     let configStr = JSON.stringify(config);
+    console.log('Staff Selection Request:', configStr);
     this._dialogRef.close(configStr);
   }
 }

+ 70 - 30
src/app/components/template/notification-dialog/comments-view/comments-view.component.ts

@@ -1,6 +1,7 @@
 import { Component, Inject, OnInit } from '@angular/core';
 import { MAT_DIALOG_DATA } from '@angular/material/dialog';
 import { CorrectiveMaintenanceService } from '../../../../services/corrective-maintenance.service';
+import { PreventiveMaintenanceService } from '../../../../services/preventive-maintenance.service';
 import { EncService } from '../../../../services/enc.service';
 import { lastValueFrom } from 'rxjs';
 import { WorkOrderStatusHistoryListResponse } from '../../../../interfaces/corrective-maintenance.interface';
@@ -9,72 +10,111 @@ import { WorkOrderStatusHistoryListResponse } from '../../../../interfaces/corre
   selector: 'app-comments-view',
   standalone: false,
   templateUrl: './comments-view.component.html',
-  styleUrl: './comments-view.component.css'
+  styleUrl: './comments-view.component.css',
 })
 export class CommentsViewComponent implements OnInit {
   isLoading: boolean;
   hasError: boolean;
   errorStr: string;
   comments: string;
+  orderType: 'Correctivo' | 'Preventivo';
 
   constructor(
     @Inject(MAT_DIALOG_DATA) private _data: any,
     private _correctiveMaintenanceService: CorrectiveMaintenanceService,
-    private _encService: EncService,
+    private _preventiveMaintenanceService: PreventiveMaintenanceService,
+    private _encService: EncService
   ) {
     this.isLoading = true;
     this.hasError = false;
-    this.errorStr = "";
-    this.comments = "";
+    this.errorStr = '';
+    this.comments = '';
+    this.orderType = 'Correctivo'; // default
   }
 
   ngOnInit(): void {
-    this.getCorrectiveWorkOrder();
+    // Set orderType from data, default to 'Correctivo' if not provided
+    this.orderType = this._data.orderType || 'Correctivo';
+    this.getWorkOrderStatusHistory();
   }
 
-  private async getCorrectiveWorkOrder(){
-    try{
+  private async getWorkOrderStatusHistory() {
+    try {
       let idUser = localStorage.getItem('idusuario')!;
-      let order: WorkOrderStatusHistoryListResponse = await lastValueFrom(this._correctiveMaintenanceService.getWorkOrderStatusHistory(
-        this._data.idOrder, 
-        idUser, 
-        1
-      ));
+      let order: WorkOrderStatusHistoryListResponse;
+
+      // Call appropriate service based on orderType
+      if (this.orderType === 'Correctivo') {
+        order = await lastValueFrom(
+          this._correctiveMaintenanceService.getWorkOrderStatusHistory(
+            this._data.idOrder,
+            idUser,
+            1
+          )
+        );
+      } else {
+        order = await lastValueFrom(
+          this._preventiveMaintenanceService.getVisitStatusHistory(
+            this._data.idOrder,
+            idUser,
+            1
+          )
+        );
+      }
 
       this.hasError = order.error;
       this.errorStr = order.msg;
 
-      if(!this.hasError){
-        let validatedStatusFilt = order.response.filter(item => item.ESTADO == 'Validado');
-        if(validatedStatusFilt.length > 0){
-          let idUserActionDec = await this._encService.decrypt(this._data.idUserAction);
-          let userStaffValidation = validatedStatusFilt[0].PERSONAL!.filter(item => item == idUserActionDec);
+      if (!this.hasError) {
+        let validatedStatusFilt = order.response.filter(
+          (item) => item.ESTADO == 'Validado'
+        );
+        if (validatedStatusFilt.length > 0) {
+          let idUserActionDec = await this._encService.decrypt(
+            this._data.idUserAction
+          );
+          let userStaffValidation = validatedStatusFilt[0].PERSONAL!.filter(
+            (item) => item == idUserActionDec
+          );
 
-          if(userStaffValidation.length > 0){
-            let userAttendanceValidation = validatedStatusFilt[0].ATENCION!.filter(item => item.ID == idUserActionDec);
-            if(userAttendanceValidation.length > 0){
+          if (userStaffValidation.length > 0) {
+            let userAttendanceValidation =
+              validatedStatusFilt[0].ATENCION!.filter(
+                (item) => item.ID == idUserActionDec
+              );
+            if (userAttendanceValidation.length > 0) {
               this.comments = userAttendanceValidation[0].COMENTARIOS!;
-            }else{
+            } else {
               this.hasError = true;
-              this.errorStr = 'El usuario asociado aún no ha respondido a la orden de mantenimiento consultada.';
+              this.errorStr = `El usuario asociado aún no ha respondido a la ${
+                this.orderType === 'Correctivo'
+                  ? 'orden de mantenimiento'
+                  : 'visita preventiva'
+              } consultada.`;
             }
-          }else{
+          } else {
             this.hasError = true;
-            this.errorStr = 'El usuario asociado no está asignado a la orden de mantenimiento consultada.';
+            this.errorStr = `El usuario asociado no está asignado a la ${
+              this.orderType === 'Correctivo'
+                ? 'orden de mantenimiento'
+                : 'visita preventiva'
+            } consultada.`;
           }
-        }else{
+        } else {
           this.hasError = true;
-          this.errorStr = 'La orden consultada no ha sido validada.';
+          this.errorStr = `La ${
+            this.orderType === 'Correctivo' ? 'orden' : 'visita'
+          } consultada no ha sido validada.`;
         }
       }
 
       this.isLoading = false;
-    }catch(error: any){
-      if(error.error == undefined){
+    } catch (error: any) {
+      if (error.error == undefined) {
         this.errorStr = 'Ocurrió un error inesperado.';
-      }else if(error.error.msg == undefined){
+      } else if (error.error.msg == undefined) {
         this.errorStr = 'Ocurrió un error inesperado.';
-      }else{
+      } else {
         this.errorStr = error.error.msg;
       }
 

+ 206 - 0
src/app/components/template/notification-dialog/notification-dialog.component.ts

@@ -13,6 +13,7 @@ import { EncService } from '../../../services/enc.service';
 import { NotificationsService } from '../../../services/notifications.service';
 import { ResourcesService } from '../../../services/resources.service';
 import { CorrectiveMaintenanceService } from '../../../services/corrective-maintenance.service';
+import { PreventiveMaintenanceService } from '../../../services/preventive-maintenance.service';
 import { GdelService } from '../../../services/gdel.service';
 import { ProcessManagementService } from '../../../services/process-management/process-management.service';
 import { lastValueFrom } from 'rxjs';
@@ -47,6 +48,7 @@ export class NotificationDialogComponent implements OnInit {
     private _dialog: MatDialog,
     private _resourcesService: ResourcesService,
     private _correctiveMaintenanceService: CorrectiveMaintenanceService,
+    private _preventiveMaintenanceService: PreventiveMaintenanceService,
     private _processManagementService: ProcessManagementService,
     private _dialogRef: MatDialogRef<NotificationDialogComponent>,
     private _gdelService: GdelService
@@ -156,6 +158,19 @@ export class NotificationDialogComponent implements OnInit {
         this.openPreventiveWorkOrderDetails(paramsArr[0]);
         break;
       case 'validatePreventiveWorkOrder':
+        this.validatePreventiveWorkOrder(paramsArr[0]);
+        break;
+      case 'revalidatePreventiveWorkOrder':
+        this.revalidatePreventiveWorkOrder(paramsArr[0]);
+        break;
+      case 'attendPreventiveWorkOrder':
+        this.attendPreventiveWorkOrder(paramsArr[0]);
+        break;
+      case 'reviewCommentsInPreventiveVisit':
+        this.reviewCommentsInPreventiveWorkOrder(paramsArr[0], paramsArr[1]);
+        break;
+      case 'reviewSignatureInPreventiveVisit':
+        this.reviewSignatureInPreventiveVisit(paramsArr[0], paramsArr[1]);
         break;
       default:
         this._resourcesService.openSnackBar(
@@ -277,6 +292,7 @@ export class NotificationDialogComponent implements OnInit {
       maxWidth: '540px',
       data: {
         idOrder: idOrder,
+        orderType: 'Correctivo',
       },
     });
 
@@ -294,6 +310,7 @@ export class NotificationDialogComponent implements OnInit {
       maxWidth: '540px',
       data: {
         idOrder: idOrder,
+        orderType: 'Correctivo',
       },
     });
 
@@ -429,6 +446,7 @@ export class NotificationDialogComponent implements OnInit {
       data: {
         idOrder: idOrder,
         idUserAction: idUserAction,
+        orderType: 'Correctivo',
       },
     });
   }
@@ -443,7 +461,195 @@ export class NotificationDialogComponent implements OnInit {
       data: {
         idOrder: idOrder,
         idUserAction: idUserAction,
+        orderType: 'Correctivo',
+      },
+    });
+  }
+
+  // PREVENTIVE MAINTENANCE FUNCTIONS
+  private reviewCommentsInPreventiveWorkOrder(
+    idOrder: string,
+    idUserAction: string
+  ) {
+    this._dialog.open(CommentsViewComponent, {
+      width: '420px',
+      maxWidth: '420px',
+      data: {
+        idOrder: idOrder,
+        idUserAction: idUserAction,
+        orderType: 'Preventivo',
+      },
+    });
+  }
+
+  private reviewSignatureInPreventiveVisit(
+    idOrder: string,
+    idUserAction: string
+  ) {
+    this._dialog.open(SignatureViewComponent, {
+      width: '420px',
+      maxWidth: '420px',
+      data: {
+        idOrder: idOrder,
+        idUserAction: idUserAction,
+        orderType: 'Preventivo',
+      },
+    });
+  }
+  attendPreventiveWorkOrder(idOrder: string) {
+    let dialogRef = this._dialog.open(AgreeOrderComponent, {
+      disableClose: true,
+      width: '560px',
+      maxWidth: '560px',
+      data: {
+        idOrder: idOrder,
+      },
+    });
+
+    dialogRef.afterClosed().subscribe((res) => {
+      if (res != null && res != undefined && res != '') {
+        this.saveAttendancePreventiveOrder(idOrder, res);
+      }
+    });
+  }
+
+  private async saveAttendancePreventiveOrder(
+    idOrder: string,
+    dataEnc: string
+  ) {
+    try {
+      let idUser = localStorage.getItem('idusuario')!;
+      let dataDec = await this._encService.decrypt(dataEnc);
+      let dataArr = JSON.parse(dataDec);
+      let formData = new FormData();
+
+      formData.append('id_user', idUser);
+      formData.append('linea', '1');
+      formData.append('id_order', idOrder);
+      formData.append('attendance', dataArr[0]);
+      formData.append('data', dataArr[1]);
+
+      await lastValueFrom(
+        this._preventiveMaintenanceService.setVisitAttendance(formData)
+      );
+      this._resourcesService.openSnackBar(
+        'La atención a la visita preventiva se registró correctamente.'
+      );
+      this._dialogRef.close();
+    } catch (error: any) {
+      if (error.error == undefined) {
+        this._resourcesService.openSnackBar('Ocurrió un error inesperado.');
+      } else if (error.error.msg == undefined) {
+        this._resourcesService.openSnackBar('Ocurrió un error inesperado.');
+      } else {
+        this._resourcesService.openSnackBar(error.error.msg);
+      }
+    }
+  }
+  private validatePreventiveWorkOrder(idOrder: string) {
+    let dialogRef = this._dialog.open(StaffSelectionComponent, {
+      disableClose: true,
+      width: '540px',
+      maxWidth: '540px',
+      data: {
+        idOrder: idOrder,
+        orderType: 'Preventivo',
       },
     });
+
+    dialogRef.afterClosed().subscribe((res) => {
+      if (res != null && res != undefined && res != '') {
+        this.approvePreventiveWorkOrder(idOrder, res);
+      }
+    });
+  }
+
+  private revalidatePreventiveWorkOrder(idOrder: string) {
+    let dialogRef = this._dialog.open(StaffSelectionComponent, {
+      disableClose: true,
+      width: '540px',
+      maxWidth: '540px',
+      data: {
+        idOrder: idOrder,
+        orderType: 'Preventivo',
+      },
+    });
+
+    dialogRef.afterClosed().subscribe((res) => {
+      if (res != null && res != undefined && res != '') {
+        this.updateApprovedPreventiveWorkOrder(idOrder, res);
+      }
+    });
+  }
+
+  private async approvePreventiveWorkOrder(idOrder: string, config: string) {
+    try {
+      let idUser = localStorage.getItem('idusuario')!;
+      let formData = new FormData();
+
+      formData.append('id_user', idUser);
+      formData.append('linea', '1');
+      formData.append('id_order', idOrder);
+      formData.append('config', config);
+
+      await lastValueFrom(
+        this._preventiveMaintenanceService.assignOperariosToPreventiveVisit(
+          formData
+        )
+      );
+      this._resourcesService.openSnackBar(
+        'La orden de trabajo preventivo se aprobó correctamente.'
+      );
+      this._dialogRef.close();
+    } catch (error: any) {
+      if (error.error == undefined) {
+        this._resourcesService.openSnackBar(
+          'Ocurrió un error inesperado (14).'
+        );
+      } else if (error.error.msg == undefined) {
+        this._resourcesService.openSnackBar(
+          'Ocurrió un error inesperado (15).'
+        );
+      } else {
+        this._resourcesService.openSnackBar(error.error.msg);
+      }
+    }
+  }
+
+  private async updateApprovedPreventiveWorkOrder(
+    idOrder: string,
+    config: string
+  ) {
+    try {
+      let idUser = localStorage.getItem('idusuario')!;
+      let formData = new FormData();
+
+      formData.append('id_user', idUser);
+      formData.append('linea', '1');
+      formData.append('id_order', idOrder);
+      formData.append('config', config);
+
+      await lastValueFrom(
+        this._preventiveMaintenanceService.assignOperariosToPreventiveVisit(
+          formData
+        )
+      );
+      this._resourcesService.openSnackBar(
+        'La orden de trabajo preventivo se actualizó correctamente.'
+      );
+      this._dialogRef.close();
+    } catch (error: any) {
+      if (error.error == undefined) {
+        this._resourcesService.openSnackBar(
+          'Ocurrió un error inesperado (14).'
+        );
+      } else if (error.error.msg == undefined) {
+        this._resourcesService.openSnackBar(
+          'Ocurrió un error inesperado (15).'
+        );
+      } else {
+        this._resourcesService.openSnackBar(error.error.msg);
+      }
+    }
   }
 }

+ 81 - 43
src/app/components/template/notification-dialog/signature-view/signature-view.component.ts

@@ -2,6 +2,7 @@ import { Component, Inject, OnInit } from '@angular/core';
 import { MAT_DIALOG_DATA } from '@angular/material/dialog';
 import { lastValueFrom } from 'rxjs';
 import { CorrectiveMaintenanceService } from '../../../../services/corrective-maintenance.service';
+import { PreventiveMaintenanceService } from '../../../../services/preventive-maintenance.service';
 import { WorkOrderStatusHistoryListResponse } from '../../../../interfaces/corrective-maintenance.interface';
 import { EncService } from '../../../../services/enc.service';
 import { GdelService } from '../../../../services/gdel.service';
@@ -10,76 +11,115 @@ import { GdelService } from '../../../../services/gdel.service';
   selector: 'app-signature-view',
   standalone: false,
   templateUrl: './signature-view.component.html',
-  styleUrl: './signature-view.component.css'
+  styleUrl: './signature-view.component.css',
 })
 export class SignatureViewComponent implements OnInit {
   isLoading: boolean;
   hasError: boolean;
   errorStr: string;
   signatureFileURI: string;
+  orderType: 'Correctivo' | 'Preventivo';
 
   constructor(
     @Inject(MAT_DIALOG_DATA) private _data: any,
     private _correctiveMaintenanceService: CorrectiveMaintenanceService,
+    private _preventiveMaintenanceService: PreventiveMaintenanceService,
     private _encService: EncService,
-    private _gdelService: GdelService,
+    private _gdelService: GdelService
   ) {
     this.isLoading = true;
     this.hasError = false;
-    this.errorStr = "";
-    this.signatureFileURI = "";
+    this.errorStr = '';
+    this.signatureFileURI = '';
+    this.orderType = 'Correctivo'; // default
   }
 
   ngOnInit(): void {
-    this.getCorrectiveWorkOrder();
+    // Set orderType from data, default to 'Correctivo' if not provided
+    this.orderType = this._data.orderType || 'Correctivo';
+    this.getWorkOrderStatusHistory();
   }
 
-  private async getCorrectiveWorkOrder(){
-    try{
+  private async getWorkOrderStatusHistory() {
+    try {
       let idUser = localStorage.getItem('idusuario')!;
-      let order: WorkOrderStatusHistoryListResponse = await lastValueFrom(this._correctiveMaintenanceService.getWorkOrderStatusHistory(
-        this._data.idOrder, 
-        idUser, 
-        1
-      ));
+      let order: WorkOrderStatusHistoryListResponse;
+
+      // Call appropriate service based on orderType
+      if (this.orderType === 'Correctivo') {
+        order = await lastValueFrom(
+          this._correctiveMaintenanceService.getWorkOrderStatusHistory(
+            this._data.idOrder,
+            idUser,
+            1
+          )
+        );
+      } else {
+        order = await lastValueFrom(
+          this._preventiveMaintenanceService.getVisitStatusHistory(
+            this._data.idOrder,
+            idUser,
+            1
+          )
+        );
+      }
 
       this.hasError = order.error;
       this.errorStr = order.msg;
 
-      if(this.hasError){
+      if (this.hasError) {
         this.isLoading = false;
-      }else{
-        let validatedStatusFilt = order.response.filter(item => item.ESTADO == 'Validado');
-        if(validatedStatusFilt.length > 0){
-          let idUserActionDec = await this._encService.decrypt(this._data.idUserAction);
-          let userStaffValidation = validatedStatusFilt[0].PERSONAL!.filter(item => item == idUserActionDec);
+      } else {
+        let validatedStatusFilt = order.response.filter(
+          (item) => item.ESTADO == 'Validado'
+        );
+        if (validatedStatusFilt.length > 0) {
+          let idUserActionDec = await this._encService.decrypt(
+            this._data.idUserAction
+          );
+          let userStaffValidation = validatedStatusFilt[0].PERSONAL!.filter(
+            (item) => item == idUserActionDec
+          );
 
-          if(userStaffValidation.length > 0){
-            let userAttendanceValidation = validatedStatusFilt[0].ATENCION!.filter(item => item.ID == idUserActionDec);
-            if(userAttendanceValidation.length > 0){
+          if (userStaffValidation.length > 0) {
+            let userAttendanceValidation =
+              validatedStatusFilt[0].ATENCION!.filter(
+                (item) => item.ID == idUserActionDec
+              );
+            if (userAttendanceValidation.length > 0) {
               this.getSignatureFile(userAttendanceValidation[0].FIRMA!);
-            }else{
+            } else {
               this.isLoading = false;
               this.hasError = true;
-              this.errorStr = 'El usuario asociado aún no ha respondido a la orden de mantenimiento consultada.';
+              this.errorStr = `El usuario asociado aún no ha respondido a la ${
+                this.orderType === 'Correctivo'
+                  ? 'orden de mantenimiento'
+                  : 'visita preventiva'
+              } consultada.`;
             }
-          }else{
+          } else {
             this.isLoading = false;
             this.hasError = true;
-            this.errorStr = 'El usuario asociado no está asignado a la orden de mantenimiento consultada.';
+            this.errorStr = `El usuario asociado no está asignado a la ${
+              this.orderType === 'Correctivo'
+                ? 'orden de mantenimiento'
+                : 'visita preventiva'
+            } consultada.`;
           }
-        }else{
+        } else {
           this.isLoading = false;
           this.hasError = true;
-          this.errorStr = 'La orden consultada no ha sido validada.';
+          this.errorStr = `La ${
+            this.orderType === 'Correctivo' ? 'orden' : 'visita'
+          } consultada no ha sido validada.`;
         }
       }
-    }catch(error: any){
-      if(error.error == undefined){
+    } catch (error: any) {
+      if (error.error == undefined) {
         this.errorStr = 'Ocurrió un error inesperado.';
-      }else if(error.error.msg == undefined){
+      } else if (error.error.msg == undefined) {
         this.errorStr = 'Ocurrió un error inesperado.';
-      }else{
+      } else {
         this.errorStr = error.error.msg;
       }
 
@@ -88,30 +128,28 @@ export class SignatureViewComponent implements OnInit {
     }
   }
 
-  private async getSignatureFile(signatureCode: string){
-    try{
+  private async getSignatureFile(signatureCode: string) {
+    try {
       let idUser = localStorage.getItem('idusuario')!;
       let signatureCodeEnc = await this._encService.encrypt(signatureCode);
-      let signatureFile = await lastValueFrom(this._gdelService.getPublicDocumentUrl(
-        signatureCodeEnc, 
-        idUser, 
-        1
-      ));
+      let signatureFile = await lastValueFrom(
+        this._gdelService.getPublicDocumentUrl(signatureCodeEnc, idUser, 1)
+      );
 
       this.hasError = signatureFile.error;
       this.errorStr = signatureFile.msg;
 
-      if(!this.hasError){
+      if (!this.hasError) {
         this.signatureFileURI = signatureFile.response.public_uri;
       }
 
       this.isLoading = false;
-    }catch(error: any){
-      if(error.error == undefined){
+    } catch (error: any) {
+      if (error.error == undefined) {
         this.errorStr = 'Ocurrió un error inesperado.';
-      }else if(error.error.msg == undefined){
+      } else if (error.error.msg == undefined) {
         this.errorStr = 'Ocurrió un error inesperado.';
-      }else{
+      } else {
         this.errorStr = error.error.msg;
       }
 

+ 180 - 80
src/app/services/preventive-maintenance.service.ts

@@ -4,170 +4,270 @@ import { map } from 'rxjs';
 import { apiTemp } from '../../environments/environment.prod';
 
 @Injectable({
-  providedIn: 'root'
+  providedIn: 'root',
 })
 export class PreventiveMaintenanceService {
+  constructor(private _http: HttpClient) {}
 
-  constructor(private _http: HttpClient) { }
+  getWorkOrdersByDay(
+    day: number,
+    month: number,
+    year: number,
+    idUser: string,
+    line: number
+  ) {
+    return this.getQuery(
+      `get-work-orders-by-day/${day}/${month}/${year}/${idUser}/${line}`
+    ).pipe(map((data: any) => data));
+  }
+
+  getWorkOrder(id: string, idUser: string, line: number) {
+    return this.getQuery(`get-work-order/${id}/${idUser}/${line}`).pipe(
+      map((data: any) => data)
+    );
+  }
 
-  getWorkOrdersByDay(day: number, month: number, year: number, idUser: string, line: number){
-    return this.getQuery(`get-work-orders-by-day/${day}/${month}/${year}/${idUser}/${line}`).pipe(map((data: any) => data))
+  getStartedWorkOrders(idUser: string, line: number) {
+    return this.getQuery(`get-started-work-orders/${idUser}/${line}`).pipe(
+      map((data: any) => data)
+    );
   }
 
-  getWorkOrder(id: string, idUser: string, line: number){
-    return this.getQuery(`get-work-order/${id}/${idUser}/${line}`).pipe(map((data: any) => data))
+  getExecRegister(date: string, idOrder: string, idUser: string, line: number) {
+    return this.getQuery(
+      `get-exec-register/${date}/${idOrder}/${idUser}/${line}`
+    ).pipe(map((data: any) => data));
   }
 
-  getStartedWorkOrders(idUser: string, line: number){
-    return this.getQuery(`get-started-work-orders/${idUser}/${line}`).pipe(map((data: any) => data))
+  getWorkOrders(idUser: string, line: number) {
+    return this.getQuery(`get-work-orders/${idUser}/${line}`).pipe(
+      map((data: any) => data)
+    );
   }
 
-  getExecRegister(date: string, idOrder: string, idUser: string, line: number){
-    return this.getQuery(`get-exec-register/${date}/${idOrder}/${idUser}/${line}`).pipe(map((data: any) => data))
+  getActiveWorkOrders(idUser: string, line: number) {
+    return this.getQuery(`get-active-orders/${idUser}/${line}`).pipe(
+      map((data: any) => data)
+    );
   }
 
-  getWorkOrders(idUser: string, line: number){
-    return this.getQuery(`get-work-orders/${idUser}/${line}`).pipe(map((data: any) => data))
+  getPreventiveCalendar(
+    fecIni: string,
+    fecFin: string,
+    idUser: string,
+    line: number
+  ) {
+    return this.getQuery(
+      `get-preventive-calendar/${fecIni}/${fecFin}/${idUser}/${line}`
+    ).pipe(map((data: any) => data));
   }
 
-  getActiveWorkOrders(idUser: string, line: number){
-    return this.getQuery(`get-active-orders/${idUser}/${line}`).pipe(map((data: any) => data))
+  getUnprogrammedVisits(idUser: string, line: number) {
+    return this.getQuery(`get-unprogrammed-visits/${idUser}/${line}`).pipe(
+      map((data: any) => data)
+    );
   }
 
-  getPreventiveCalendar(fecIni: string, fecFin: string, idUser: string, line: number){
-    return this.getQuery(`get-preventive-calendar/${fecIni}/${fecFin}/${idUser}/${line}`).pipe(map((data: any) => data))
+  getUnprogrammedVisit(idVisit: string, idUser: string, line: number) {
+    return this.getQuery(
+      `get-unprogrammed-visit/${idVisit}/${idUser}/${line}`
+    ).pipe(map((data: any) => data));
   }
 
-  getUnprogrammedVisits(idUser: string, line: number){
-    return this.getQuery(`get-unprogrammed-visits/${idUser}/${line}`).pipe(map((data: any) => data))
+  getMaintenanceSimulation(idOrder: string, idUser: string, line: number) {
+    return this.getQuery(
+      `get-maintenance-simulation/${idOrder}/${idUser}/${line}`
+    ).pipe(map((data: any) => data));
   }
 
-  getUnprogrammedVisit(idVisit: string, idUser: string, line: number){
-    return this.getQuery(`get-unprogrammed-visit/${idVisit}/${idUser}/${line}`).pipe(map((data: any) => data))
+  getOrderWithActivator(idOrder: string, idUser: string, line: number) {
+    return this.getQuery(
+      `get-order-with-activator/${idOrder}/${idUser}/${line}`
+    ).pipe(map((data: any) => data));
   }
 
-  getMaintenanceSimulation(idOrder: string, idUser: string, line: number){
-    return this.getQuery(`get-maintenance-simulation/${idOrder}/${idUser}/${line}`).pipe(map((data: any) => data))
+  printOrderSimulation(idOrder: string, idUser: string, line: number) {
+    return this.getQuery(
+      `print-order-simulation/${idOrder}/${idUser}/${line}`
+    ).pipe(map((data: any) => data));
   }
 
-  getOrderWithActivator(idOrder: string, idUser: string, line: number){
-    return this.getQuery(`get-order-with-activator/${idOrder}/${idUser}/${line}`).pipe(map((data: any) => data))
+  printOrderDetails(idOrder: string, idUser: string, line: number) {
+    return this.getQuery(
+      `print-order-details/${idOrder}/${idUser}/${line}`
+    ).pipe(map((data: any) => data));
   }
 
-  printOrderSimulation(idOrder: string, idUser: string, line: number){
-    return this.getQuery(`print-order-simulation/${idOrder}/${idUser}/${line}`).pipe(map((data: any) => data))
+  extractMaintenancePlan(idOrder: string, idUser: string, line: number) {
+    return this.getQuery(
+      `extract-maintenance-plan/${idOrder}/${idUser}/${line}`
+    ).pipe(map((data: any) => data));
   }
 
-  printOrderDetails(idOrder: string, idUser: string, line: number){
-    return this.getQuery(`print-order-details/${idOrder}/${idUser}/${line}`).pipe(map((data: any) => data))
+  getMaintenancePlanAnalysis(idFile: string, idUser: string, line: number) {
+    return this.getQuery(
+      `get-maintenance-plan-analysis/${idFile}/${idUser}/${line}`
+    ).pipe(map((data: any) => data));
   }
 
-  extractMaintenancePlan(idOrder: string, idUser: string, line: number){
-    return this.getQuery(`extract-maintenance-plan/${idOrder}/${idUser}/${line}`).pipe(map((data: any) => data))
+  getFileToMSProject(idOrder: string, idUser: string, line: number) {
+    return this.getQuery(
+      `get-file-to-ms-project/${idOrder}/${idUser}/${line}`
+    ).pipe(map((data: any) => data));
   }
 
-  getMaintenancePlanAnalysis(idFile: string, idUser: string, line: number){
-    return this.getQuery(`get-maintenance-plan-analysis/${idFile}/${idUser}/${line}`).pipe(map((data: any) => data))
+  getOrderStaff(idOrder: string, idUser: string, line: number) {
+    return this.getQuery(`get-order-staff/${idOrder}/${idUser}/${line}`).pipe(
+      map((data: any) => data)
+    );
   }
 
-  getFileToMSProject(idOrder: string, idUser: string, line: number){
-    return this.getQuery(`get-file-to-ms-project/${idOrder}/${idUser}/${line}`).pipe(map((data: any) => data))
+  getOrderExecutionDetails(idExecution: string, idUser: string, line: number) {
+    return this.getQuery(
+      `get-order-execution-details/${idExecution}/${idUser}/${line}`
+    ).pipe(map((data: any) => data));
   }
 
-  getOrderStaff(idOrder: string, idUser: string, line: number){
-    return this.getQuery(`get-order-staff/${idOrder}/${idUser}/${line}`).pipe(map((data: any) => data))
+  getWorkOrdersByEquipment(
+    equipmentCode: string,
+    idUser: string,
+    line: number
+  ) {
+    return this.getQuery(
+      `get-work-orders-by-equipment/${equipmentCode}/${idUser}/${line}`
+    ).pipe(map((data: any) => data));
   }
 
-  getOrderExecutionDetails(idExecution: string, idUser: string, line: number){
-    return this.getQuery(`get-order-execution-details/${idExecution}/${idUser}/${line}`).pipe(map((data: any) => data))
+  getVisit(id: string, idUser: string, line: number) {
+    return this.getQuery(`get-visit/${id}/${idUser}/${line}`).pipe(
+      map((data: any) => data)
+    );
   }
 
-  getWorkOrdersByEquipment(equipmentCode: string, idUser: string, line: number){
-    return this.getQuery(`get-work-orders-by-equipment/${equipmentCode}/${idUser}/${line}`).pipe(map((data: any) => data))
+  getVisitStatusHistory(idOrder: string, idUser: string, line: number) {
+    return this.getQuery(
+      `get-visit-status-history/${idOrder}/${idUser}/${line}`
+    ).pipe(map((data: any) => data));
   }
 
-  getVisit(id: string, idUser: string, line: number){
-    return this.getQuery(`get-visit/${id}/${idUser}/${line}`).pipe(map((data: any) => data))
+  assignOperariosToPreventiveVisit(body: any) {
+    return this.postQuery('assign-operarios-to-visit', body).pipe(
+      map((data: any) => data)
+    );
   }
 
-  registerWorkOrder(body: any){
-    return this.postQuery("register-work-order", body).pipe(map((data: any) => data))
+  setVisitAttendance(body: any) {
+    return this.postQuery('attend-preventive-visit', body).pipe(
+      map((data: any) => data)
+    );
   }
 
-  executePreventiveWorkOrder(body: any){
-    return this.postQuery("execute-preventive-work-order", body).pipe(map((data: any) => data))
+  registerWorkOrder(body: any) {
+    return this.postQuery('register-work-order', body).pipe(
+      map((data: any) => data)
+    );
   }
 
-  cancelWorkOrder(body: any){
-    return this.postQuery("cancel-work-order", body).pipe(map((data: any) => data))
+  executePreventiveWorkOrder(body: any) {
+    return this.postQuery('execute-preventive-work-order', body).pipe(
+      map((data: any) => data)
+    );
   }
 
-  deleteWorkOrder(body: any){
-    return this.postQuery("delete-work-order", body).pipe(map((data: any) => data))
+  cancelWorkOrder(body: any) {
+    return this.postQuery('cancel-work-order', body).pipe(
+      map((data: any) => data)
+    );
   }
 
-  updateWorkOrder(body: any){
-    return this.postQuery("update-work-order", body).pipe(map((data: any) => data))
+  deleteWorkOrder(body: any) {
+    return this.postQuery('delete-work-order', body).pipe(
+      map((data: any) => data)
+    );
   }
 
-  endOrderExecution(body: any){
-    return this.postQuery("end-order-execution", body).pipe(map((data: any) => data))
+  updateWorkOrder(body: any) {
+    return this.postQuery('update-work-order', body).pipe(
+      map((data: any) => data)
+    );
   }
 
-  copyWorkOrder(body: any){
-    return this.postQuery("copy-work-order", body).pipe(map((data: any) => data))
+  endOrderExecution(body: any) {
+    return this.postQuery('end-order-execution', body).pipe(
+      map((data: any) => data)
+    );
   }
 
-  savePresetWorkOrder(body: any){
-    return this.postQuery("save-preset-work-order", body).pipe(map((data: any) => data))
+  copyWorkOrder(body: any) {
+    return this.postQuery('copy-work-order', body).pipe(
+      map((data: any) => data)
+    );
   }
 
-  newUnprogrammedOrder(body: any){
-    return this.postQuery("new-unprogrammed-order", body).pipe(map((data: any) => data))
+  savePresetWorkOrder(body: any) {
+    return this.postQuery('save-preset-work-order', body).pipe(
+      map((data: any) => data)
+    );
   }
 
-  updateVisitStatus(body: any){
-    return this.postQuery("update-visit-status", body).pipe(map((data: any) => data))
+  newUnprogrammedOrder(body: any) {
+    return this.postQuery('new-unprogrammed-order', body).pipe(
+      map((data: any) => data)
+    );
   }
 
-  updateOrderStatus(body: any){
-    return this.postQuery("update-order-status", body).pipe(map((data: any) => data))
+  updateVisitStatus(body: any) {
+    return this.postQuery('update-visit-status', body).pipe(
+      map((data: any) => data)
+    );
   }
 
-  setBudgetAnalysis(body: any){
-    return this.postQuery("set-budget-analysis", body).pipe(map((data: any) => data))
+  updateOrderStatus(body: any) {
+    return this.postQuery('update-order-status', body).pipe(
+      map((data: any) => data)
+    );
   }
 
-  updateOrderWithActivator(body: any){
-    return this.postQuery("update-order-with-activator", body).pipe(map((data: any) => data))
+  setBudgetAnalysis(body: any) {
+    return this.postQuery('set-budget-analysis', body).pipe(
+      map((data: any) => data)
+    );
   }
 
-  saveOrderSimulation(body: any){
-    return this.postQuery("save-order-simulation", body).pipe(map((data: any) => data))
+  updateOrderWithActivator(body: any) {
+    return this.postQuery('update-order-with-activator', body).pipe(
+      map((data: any) => data)
+    );
   }
-  
-  getQuery(query: string, tk?: string){
+
+  saveOrderSimulation(body: any) {
+    return this.postQuery('save-order-simulation', body).pipe(
+      map((data: any) => data)
+    );
+  }
+
+  getQuery(query: string, tk?: string) {
     const URL = `${apiTemp}${query}`;
-    let token = "";
-    if(tk == undefined || tk == null || tk == ""){
+    let token = '';
+    if (tk == undefined || tk == null || tk == '') {
       token = `Bearer ${localStorage.getItem('token')!}`;
-    }else{
+    } else {
       token = `Bearer ${tk!}`;
     }
     return this._http.get(URL, {
       headers: new HttpHeaders({
         Authorization: token,
-      })
-    })
+      }),
+    });
   }
 
-  postQuery(query: string, body: any){
+  postQuery(query: string, body: any) {
     const JWT = `Bearer ${localStorage.getItem('token')}`;
     const URL = `${apiTemp}${query}`;
     return this._http.post(URL, body, {
       headers: new HttpHeaders({
-        Authorization: JWT!
-      })
+        Authorization: JWT!,
+      }),
     });
   }
 }