Explorar o código

Implementación de controladores

MathewCordourier %!s(int64=2) %!d(string=hai) anos
pai
achega
f09b36ba68

+ 326 - 0
sistema-mantenimiento-back/app/Http/Controllers/DocumentsController.php

@@ -0,0 +1,326 @@
+<?php
+
+/*
+Nombre del programador:         Cordourier Rojas Mathew
+Ultima fecha de modificación:   [ 03 / Marzo / 2023 ]
+Descripción:                    Controlador de ayuda para la nomenclatura e inserciòn de documentos.
+*/
+
+namespace App\Http\Controllers;
+
+use Carbon\Carbon;
+use Illuminate\Support\Facades\DB;
+use Illuminate\Support\Facades\Storage;
+use PhpOffice\PhpSpreadsheet\IOFactory;
+use Throwable;
+
+class DocumentsController extends Controller
+{
+    private $resources_controller;
+    private $response_controller;
+    public function __construct()
+    {
+        $this->resources_controller = new ResourcesController();
+        $this->response_controller = new ResponseController();
+
+    }
+    // Metodo para la creación de un documento y la inserción de la liga en la base de datos
+    public function createDocument($module_code, $document_clasification, $document_name, $id_employee = null, $storage_disk, $line_number = 1, $user_id)
+    {
+        try {
+
+            // Engloba los segmentos de la nomenclatura del nombre del documento
+            $name_document = "";
+            $REGISTER_DATE = Carbon::now()->timezone('America/Mexico_City')->format("ymd");
+            $sequence_number = "000001";
+            $version_number = "01";
+            $line_number = $this->resources_controller->formatSecuence($line_number, 2);
+
+            // Verifica que el nombre de la nomenclatura no se duplique
+            $document_name = $this->deleteCodificationStructureName($document_name, $line_number, $module_code);
+
+            $files_uploaded = Storage::disk($storage_disk)->files();
+
+            // Itera cada archivo guardado en el disco del storage
+            foreach ($files_uploaded as $file) {
+
+                // Si la clasificaciòn es la misma, se recupera el numero de secuencia
+                if (substr($file, 0, 10) == ($line_number . '-' . $module_code . '-' . $document_clasification)) {
+                    $sequence_number = substr($file, 18, 6);
+
+                    // Busca el siguiente numero de versión para el archivo
+                    while (true) {
+                        $name_document = $line_number . '-' . $module_code . '-' . $document_clasification . '-' .
+                            $REGISTER_DATE . '-' . $sequence_number . '=' .
+                            $version_number . '=' . $document_name;
+
+                        // Si el nombre es nuevo, sale del ciclo
+                        if (Storage::disk($storage_disk)->missing($name_document)) {
+                            break;
+                        }
+
+                        $version_number++;
+                        if ($version_number <= 9) {
+                            $version_number = 0 . $version_number;
+                        }
+                    }
+
+                    break;
+                }
+
+                // Encuentra el siguiente numero de secuencia
+                if (substr($file, 18, 6) >= $sequence_number) {
+                    $sequence_number = substr($file, 18, 6);
+                    $sequence_number++;
+                }
+
+            }
+
+            // Si la clasificación es nueva, crea su nuevo nombre
+            if ($name_document == "") {
+                $sequence_number = $this->resources_controller->formatSecuence($sequence_number, 6);
+                $name_document = $line_number . '-' . $module_code . '-' . $document_clasification . '-' .
+                    $REGISTER_DATE . '-' . $sequence_number . '=' .
+                    $version_number . '=' . $document_name;
+            }
+
+            DB::table("S002V01TDOCU_P")
+                ->insert([
+                    "DOCU_NUSE" => $sequence_number,
+                    "DOCU_LIDO" => $name_document,
+                    "DOCU_IDPE" => $id_employee,
+                    "DOCU_NULI" => $line_number,
+                    "DOCU_USRE" => $user_id,
+                    "DOCU_FERE" => $REGISTER_DATE,
+                    "DOCU_FEAR" => DB::raw('CURRENT_TIMESTAMP'),
+                ]);
+
+            return $name_document;
+
+        } catch (Throwable $th) {
+            return $this->response_controller
+                ->makeResponse(TRUE, 'ERR_DOCUMENTO_REG001: Error inesperado guardando el documento', strtoupper($th->getMessage()), 500);
+        }
+
+    }
+
+    // Metodo para eliminar duplicado en la estructura de un mismo nombre
+    public function deleteCodificationStructureName($document_name, $line_number, $module_code)
+    {
+        try {
+
+            // Verifica que la nomenclatura no se duplique
+            if (substr($document_name, 0, 8) == ($line_number . '-' . $module_code . '-') && strlen($document_name) > 28) {
+                $document_name = substr($document_name, 28);
+            }
+            return $document_name;
+
+        } catch (Throwable $th) {
+            return $this->response_controller
+                ->makeResponse(TRUE, 'ERR_DOCUMENTO_REG001: Error inesperado renombrando el documento', strtoupper($th->getMessage()), 500);
+        }
+    }
+
+    // Metodo para buscar el nombre de la ultima versión de un documento
+    public function getDocumentsWithSameName($document_name, $storage_disk)
+    {
+        try {
+
+            $files_uploaded = Storage::disk($storage_disk)->files();
+            $files = [];
+
+            // Itera cada archivo guardado en el disco del storage
+            foreach ($files_uploaded as $file) {
+                if ($document_name == substr($file, 28)) {
+
+                    // Guarda la liga del documento con ese nombre, si es que existe
+                    $files[] = $file;
+                }
+            }
+
+            // Verifica si el arreglo contiene algo
+            if (isset($files[0]) && !empty($files[0])) {
+                return $files;
+            }
+
+            // Si no hay coincidencias, devuelve el codigo de error XXXX
+            return null;
+
+        } catch (Throwable $th) {
+            return $this->response_controller
+                ->makeResponse(TRUE, 'ERR_DOCUMENTO_REG001: Error verificando el nombre del documento', strtoupper($th->getMessage()), 500);
+        }
+    }
+
+    // Metodo para buscar el nombre de la ultima versión de un documento
+    public function getDocumentsWithSameCodificationStructureName($document_name, $storage_disk)
+    {
+        try {
+
+            $files_uploaded = Storage::disk($storage_disk)->files();
+            $files = [];
+
+            // Itera cada archivo guardado en el disco del storage
+            foreach ($files_uploaded as $file) {
+                if ($document_name == $file) {
+
+                    // Guarda la liga del documento con ese nombre, si es que existe
+                    $files[] = $file;
+                }
+            }
+
+            // Verifica si el arreglo contiene algo
+            if (isset($files[0]) && !empty($files[0])) {
+                return $files;
+            }
+
+            // Si no hay, devuelve el codigo de error XXXX
+            return null;
+
+        } catch (Throwable $th) {
+            return $this->response_controller
+                ->makeResponse(TRUE, 'ERR_DOCUMENTO_REG001: Error verificando el nombre del documento', strtoupper($th->getMessage()), 500);
+        }
+    }
+
+    // Metodo para verificar si ya existe el documento pdf
+    public function sameDocumentsPdf($content, $old_documents_name)
+    {
+        try {
+
+            // Se crea temporalmente un documento en el storage
+            Storage::disk('pdf')->put(
+                "TEMPORAL_FILE.pdf",
+                $content
+            );
+
+            $new_file = (Storage::disk('pdf')->size("TEMPORAL_FILE.pdf"));
+
+            // Itera cada archivo guardado en el disco del storage
+            foreach ($old_documents_name as $file) {
+                $old_file = (Storage::disk('pdf')->size($file));
+
+                // Verifica si los documentos son iguales
+                if ($old_file == $new_file) {
+                    Storage::disk('pdf')->delete('TEMPORAL_FILE.pdf');
+                    return $file;
+                }
+
+            }
+
+            Storage::disk('pdf')->delete('TEMPORAL_FILE.pdf');
+            return null;
+
+        } catch (Throwable $th) {
+            return $this->response_controller
+                ->makeResponse(TRUE, 'ERR_DOCUMENTO_REG001: Error verificando autenticidad del documento', strtoupper($th), 500);
+        }
+    }
+
+    // Metodo para eliminar una lista de documentos
+    public function deleteAllDocumentsByName($document_names, $storage_disk)
+    {
+        foreach ($document_names as $document) {
+            Storage::disk($storage_disk)->delete($document);
+        }
+    }
+
+    // Metodo para verificar si ya existe el documento pdf enviando la información del request
+    public function sameDocumentsPdfOnRequest($content, $old_documents_name)
+    {
+        try {
+
+            // Se crea temporalmente un documento en el storage
+            $content->storeAs('public/pdf_documents', "TEMPORAL_FILE.pdf");
+            $new_file = (Storage::disk('pdf')->size("TEMPORAL_FILE.pdf"));
+
+            // Itera cada archivo guardado en el disco del storage
+            foreach ($old_documents_name as $file) {
+                $old_file = (Storage::disk('pdf')->size($file));
+
+                // Verifica si los documentos son iguales
+                if ($old_file == $new_file) {
+                    Storage::disk('pdf')->delete('TEMPORAL_FILE.pdf');
+                    return $file;
+                }
+
+            }
+
+            Storage::disk('pdf')->delete('TEMPORAL_FILE.pdf');
+            return null;
+
+        } catch (Throwable $th) {
+            return $this->response_controller
+                ->makeResponse(TRUE, 'ERR_DOCUMENTO_REG001: Error verificando autenticidad del documento', strtoupper($th->getMessage()), 500);
+        }
+
+    }
+
+
+    // Metodo para verificar si ya existe el documento excel
+    public function sameDocumentsExcel($document, $old_documents_name)
+    {
+        try {
+            $document_repeated = null;
+            $data_new_document = []; # Arreglo donde estarán los datos del nuevo documento
+
+            $document = $document->getActiveSheet();
+
+            $max_row = $document->getHighestRow(); # Fila
+            $max_col = $document->getHighestColumn(); # Columna
+
+            $max_col = \PhpOffice\PhpSpreadsheet\Cell\Coordinate::columnIndexFromString($max_col); # Se convierte la columna en numero
+
+            // Se recorre el documento
+            for ($row = 1; $row <= $max_row; $row++) {
+                for ($col = 1; $col <= $max_col; $col++) {
+
+                    // Se obtiene el valor de esa celda del documento y se introduce en el arreglo
+                    $data_new_document[] = $document->getCellByColumnAndRow($col, $row)->getValue();
+                }
+            }
+
+            foreach ($old_documents_name as $old_document_name) {
+
+                $data_old_document = []; # Arreglo donde estarán los datos del viejo documento
+                $old_document = IOFactory::load(Storage::disk('excel')->path($old_document_name));
+
+                $document = $old_document->getActiveSheet();
+
+                $max_row = $document->getHighestRow(); # Fila
+                $max_col = $document->getHighestColumn(); # Columna
+                $max_col = \PhpOffice\PhpSpreadsheet\Cell\Coordinate::columnIndexFromString($max_col); # Se convierte la columna en numero
+
+                // Se recorre el documento
+                for ($row = 1; $row <= $max_row; $row++) {
+                    for ($col = 1; $col <= $max_col; $col++) {
+
+                        // Se obtiene el valor de esa celda del documento y se introduce en el arreglo
+                        $data_old_document[] = $document->getCellByColumnAndRow($col, $row)->getValue();
+                    }
+                }
+
+                // Se compara dato por dato de cada documento para verificar si contiene lo mismo
+                for ($i = 0; $i < sizeof($data_new_document); $i++) {
+                    if ($data_new_document[$i] != $data_old_document[$i]) {
+                        $document_repeated = null;
+                        break 1;
+                    }
+                    $document_repeated = $old_document_name;
+                }
+
+                if ($document_repeated != null) {
+                    return $document_repeated;
+                }
+            }
+
+            return $document_repeated;
+
+        } catch (Throwable $th) {
+            return $this->response_controller
+                ->makeResponse(TRUE, 'ERR_DOCUMENTO_REG001: Error verificando autenticidad del documento', strtoupper($th->getMessage()), 500);
+        }
+    }
+
+
+}

+ 1200 - 0
sistema-mantenimiento-back/app/Http/Controllers/EmployeeController.php

@@ -0,0 +1,1200 @@
+<?php
+/*
+Nombre del programador:         Cordourier Rojas Mathew
+Ultima fecha de modificación:   [ 03 / Marzo / 2023 ]
+Descripción:                    Controlador del submodulo Personal. Perteneciente al Módulo 13 - Gestion del Personal de Mantenimiento
+*/
+
+namespace App\Http\Controllers;
+
+use Carbon\Carbon;
+use Illuminate\Http\Request;
+use Illuminate\Support\Facades\DB;
+use Illuminate\Support\Facades\Storage;
+use Illuminate\Support\Facades\Validator;
+use PhpOffice\PhpSpreadsheet\IOFactory;
+use PhpOffice\PhpSpreadsheet\Spreadsheet;
+use Throwable;
+
+class EmployeeController extends Controller
+{
+
+    private $response_controller;
+    private $encrypt_controller;
+    private $documents_controller;
+
+    public function __construct()
+    {
+        $this->response_controller = new ResponseController();
+        $this->encrypt_controller = new EncryptionController();
+        $this->documents_controller = new DocumentsController();
+
+    }
+
+    // Metodo para obtener datos del personal
+    public function getConsultOfEmployees($line_number)
+    {
+        try {
+            $employees = DB::table('S002V01TPERS')
+                ->select(
+                    'S002V01TPERS.PERS_IDPE as ID',
+                    DB::raw('CONCAT(S002V01TUSUA_P.USUA_NOMB, " " , S002V01TUSUA_P.USUA_APPA, " ",  S002V01TUSUA_P.USUA_APMA) as NAME'),
+                    'S002V01TPERS.PERS_TICO as CONTRACT_TYPE',
+                    'S002V01TPERS.PERS_ESPE as SPECIALITY',
+                    'S002V01TPERS.PERS_FERE as REGISTER_DATE',
+                    'S002V01TPERS.PERS_USRE as REGISTERED_BY_USER',
+                    'S002V01TPERS.PERS_FEMO as UPDATE_DATE',
+                    'S002V01TPERS.PERS_USMO as UPDATED_BY_USER'
+                )
+                ->where('S002V01TPERS.PERS_ESTA', '=', 'Activo')
+                ->where('S002V01TPERS.PERS_NULI', '=', $line_number)
+                ->where('S002V01TUSUA_P.USUA_NULI', '=', $line_number)
+                ->join('S002V01TUSUA_P', 'S002V01TPERS.PERS_IDUS', '=', 'S002V01TUSUA_P.USUA_IDUS')
+                ->get();
+
+            // Verifica si el objeto esta vacio
+            if (!isset($employees[0]) && empty($employees[0])) {
+                return $this->response_controller
+                    ->makeResponse(TRUE, 'ERR_PERSONAL_REG001: No se encontraron datos', $employees, 500);
+            }
+
+            $users = DB::table('S002V01TUSUA_P')
+                ->select('USUA_IDUS as ID', DB::raw('CONCAT(USUA_NOMB, " " , USUA_APPA, " ",  USUA_APMA) as NAME'))
+                ->where('USUA_NULI', '=', $line_number)
+                ->get();
+
+            // Verifica si el objeto esta vacio
+            if (!isset($users[0]) && empty($users[0])) {
+                return $this->response_controller
+                    ->makeResponse(TRUE, 'ERR_USUARIO_REG002: No se encontraron datos', $users, 500);
+            }
+
+            $workteams = DB::table('S002V01TEQMA')
+                ->select('S002V01TEQMA.EQMA_NOMB as NAME', 'S002V01TPEEM.PEEM_IDPE as ID_EMPLOYEE')
+                ->where('S002V01TEQMA.EQMA_NULI', '=', $line_number)
+                ->where('S002V01TPEEM.PEEM_NULI', '=', $line_number)
+                ->join('S002V01TPEEM', 'S002V01TEQMA.EQMA_IDEQ', '=', 'S002V01TPEEM.PEEM_IDEM')
+                ->get();
+
+            // Verifica si el objeto esta vacio
+            if (!isset($workteams[0]) && empty($workteams[0])) {
+                return $this->response_controller
+                    ->makeResponse(TRUE, 'ERR_EQUIPO_TRABAJO_REG003: No se encontraron datos', $workteams, 500);
+            }
+
+            foreach ($employees as $employee) {
+
+                // Introduce los equipos de trabajo a los que pertenece
+                foreach ($workteams as $workteam) {
+                    if ($employee->ID == $workteam->ID_EMPLOYEE) {
+                        $employee->WORKTEAMS[] = $workteam->NAME;
+                    }
+                }
+
+                // Introduce la persona que lo registro
+                foreach ($users as $user) {
+                    if ($employee->REGISTERED_BY_USER == $user->ID) {
+                        $employee->REGISTERED_BY_USER = $user->NAME;
+                    }
+
+                    // Si hubo actualización, introduce a la persona que lo actualizo
+                    if ($employee->UPDATED_BY_USER != null) {
+                        if ($employee->UPDATED_BY_USER == $user->ID) {
+                            $employee->UPDATED_BY_USER = $user->NAME;
+                        }
+                    } else {
+                        $employee->UPDATED_BY_USER = "-";
+                    }
+                }
+
+                // Introduce la fecha en que se registro y actualizo al empleado (si hubo actualización)
+                $employee->REGISTER_DATE = Carbon::create($employee->REGISTER_DATE)->format("d-m-Y h:i:s A");
+                if ($employee->UPDATE_DATE != null) {
+                    $employee->UPDATE_DATE = Carbon::create($employee->UPDATE_DATE)->format("d-m-Y h:i:s A");
+                } else {
+                    $employee->UPDATE_DATE = "-";
+                }
+            }
+
+            return $this->response_controller
+                ->makeResponse(FALSE, "Consulta exitosa", $employees);
+
+
+        } catch (Throwable $th) {
+            return $this->response_controller
+                ->makeResponse(TRUE, 'ERR_PERSONAL_REG004: Error inesperado', strtoupper($th->getMessage()), 500);
+        }
+    }
+
+    // Metodo para ver el listado de documentos de un empleado
+    public function getDocumentsByEmployee($id_employee, $line_number)
+    {
+        try {
+
+            // Busca si existe el empleado
+            $employee_found = DB::table('S002V01TPERS')
+                ->select('PERS_IDPE')
+                ->where('PERS_IDPE', '=', $id_employee)
+                ->where('PERS_NULI', '=', $line_number)
+                ->first();
+
+            // Verifica si el objeto esta vacio
+            if (!isset($employee_found) && empty($employee_found)) {
+                return $this->response_controller
+                    ->makeResponse(TRUE, 'ERR_PERSONAL_REG001: No se encontró al empleado', [], 500);
+            }
+
+            // Busca si el empleado tiene documentos
+            $documents_by_employee = DB::table('S002V01TDOCU_P')
+                ->select('DOCU_LIDO as DOCUMENT_LINK')
+                ->where('DOCU_IDPE', '=', $id_employee)
+                ->where('DOCU_NULI', '=', $line_number)
+                ->get();
+
+            // Verifica si el objeto esta vacio
+            if (!isset($documents_by_employee[0]) && empty($documents_by_employee[0])) {
+                return $this->response_controller
+                    ->makeResponse(TRUE, 'ERR_DOCUMENTO_REG002: El empleado no tiene documentos', [], 500);
+            }
+
+            // Encripta la liga de cada documento
+            foreach ($documents_by_employee as $doc) {
+                $doc->DOCUMENT_LINK = $this->encrypt_controller->encrypt($doc->DOCUMENT_LINK);
+            }
+
+            return $this->response_controller
+                ->makeResponse(FALSE, "Consulta exitosa", $documents_by_employee);
+
+
+        } catch (Throwable $th) {
+            return $this->response_controller
+                ->makeResponse(TRUE, 'ERR_PERSONAL_REG003: Error inesperado', strtoupper($th->getMessage()), 500);
+        }
+    }
+
+    // Metodo para obtener todas las intervenciones relacionadas a un empleado
+    public function getInterventionsByEmployee($id_employee, $line_number)
+    {
+        try {
+
+            // Verifica si el empleado existe
+            $employee_exist = DB::table('S002V01TPERS')
+                ->select('PERS_IDPE')
+                ->where('PERS_IDPE', '=', $id_employee)
+                ->where('PERS_NULI', '=', $line_number)
+                ->first();
+
+            // Verifica si el objeto esta vacio
+            if (!isset($employee_exist) && empty($employee_exist)) {
+                return $this->response_controller
+                    ->makeResponse(TRUE, 'ERR_PERSONAL_REG001: No se encontró al empleado', [], 500);
+            }
+
+            // Obtiene las intervenciones del empleado
+            $employee_interventions = DB::table('S002V01TPERS')
+                ->select(
+                    'S002V01TEQMA.EQMA_NOMB as WORKTEAM_NAME',
+                    'S002V01TINTE_P.INTE_NOMB as INTERVENTION_NAME',
+                    'S002V01TEQMA.EQMA_NOMB as WORKTEAM_NAME',
+                    'S002V01TINTE_P.INTE_IDIN as INTERVENTION_ID',
+                    'S002V01TINTE_P.INTE_DESC as INTERVENTION_DESCRIPTION',
+                )
+                ->where('S002V01TPERS.PERS_IDPE', '=', $id_employee)
+                ->where('S002V01TPERS.PERS_NULI', '=', $line_number)
+                ->where('S002V01TPEEM.PEEM_NULI', '=', $line_number)
+                ->where('S002V01TEQMA.EQMA_NULI', '=', $line_number)
+                ->where('S002V01TEMIN.EMIN_NULI', '=', $line_number)
+                ->where('S002V01TINTE_P.INTE_NULI', '=', $line_number)
+                ->join('S002V01TPEEM', 'S002V01TPERS.PERS_IDPE', '=', 'S002V01TPEEM.PEEM_IDPE')
+                ->join('S002V01TEQMA', 'S002V01TPEEM.PEEM_IDEM', '=', 'S002V01TEQMA.EQMA_IDEQ')
+                ->join('S002V01TEMIN', 'S002V01TEQMA.EQMA_IDEQ', '=', 'S002V01TEMIN.EMIN_IDEM')
+                ->join('S002V01TINTE_P', 'S002V01TEMIN.EMIN_IDIN', '=', 'S002V01TINTE_P.INTE_IDIN')
+                ->get();
+
+            // Verifica si el objeto esta vacio
+            if (!isset($employee_interventions[0]) && empty($employee_interventions[0])) {
+                return $this->response_controller
+                    ->makeResponse(TRUE, 'ERR_PERSONAL_REG002: El empleado no tiene intervenciones', [], 500);
+            }
+
+            return $this->response_controller
+                ->makeResponse(FALSE, "Consulta exitosa", $employee_interventions);
+
+        } catch (Throwable $th) {
+            return $this->response_controller
+                ->makeResponse(TRUE, 'ERR_PERSONAL_REG003: Error inesperado', strtoupper($th->getMessage()), 500);
+        }
+    }
+
+    // Metodo para la eliminación logica de un empleado
+    public function updateToInactiveStatus(Request $request, $id_employee)
+    {
+        try {
+
+            $validator = Validator::make($request->all(), [
+                "UPDATED_BY_USER" => ['required', 'digits:10']
+            ]);
+
+            if ($validator->fails()) {
+                return $this->response_controller->makeResponse(
+                    TRUE,
+                    'ERR_PERSONAL_REG001: Uno o más errores encontrados',
+                    $this->response_controller->makeErrors($validator->errors()->messages()),
+                    400
+                );
+            }
+
+            // Busca si el empleado existe
+            $search_employee = DB::table("S002V01TPERS")
+                ->select("PERS_IDPE")
+                ->where("PERS_IDPE", "=", $id_employee)
+                ->where('PERS_NULI', '=', $request->LINE_NUMBER)
+                ->first();
+
+            // Verifica si el objeto esta vacio
+            if (!isset($search_employee) && empty($search_employee)) {
+                return $this->response_controller
+                    ->makeResponse(TRUE, "ERR_PERSONAL_REG002: No se encontró al empleado", $search_employee, 500);
+            }
+
+            $user_register = DB::table('S002V01TUSUA_P')
+                ->select('USUA_IDUS as ID_USER')
+                ->where('USUA_IDUS', '=', $request->UPDATED_BY_USER)
+                ->where('USUA_NULI', '=', $request->LINE_NUMBER)
+                ->first();
+
+            // Verifica si el objeto esta vacio
+            if (!isset($user_register) && empty($user_register)) {
+                return $this->response_controller
+                    ->makeResponse(TRUE, "ERR_USUARIO_REG003: Tu usuario no es válido para eliminar empleados", [], 500);
+            }
+
+            // Busca si el empleado tiene intervenciones activas
+            $search_employee = DB::table("S002V01TPERS")
+                ->select("S002V01TINTE_P.INTE_NOMB")
+                ->where("S002V01TPERS.PERS_IDPE", "=", $id_employee)
+                ->where("S002V01TINTE_P.INTE_ESTA", "=", "Activo")
+                ->where("S002V01TEMIN.EMIN_ESTA", "=", "Activo")
+                ->where("S002V01TPERS.PERS_NULI", "=", $request->LINE_NUMBER)
+                ->where('S002V01TPEEM.PEEM_NULI', '=', $request->LINE_NUMBER)
+                ->where('S002V01TEQMA.EQMA_NULI', '=', $request->LINE_NUMBER)
+                ->where('S002V01TEMIN.EMIN_NULI', '=', $request->LINE_NUMBER)
+                ->where('S002V01TINTE_P.INTE_NULI', '=', $request->LINE_NUMBER)
+                ->groupBy('S002V01TINTE_P.INTE_NOMB')
+                ->join("S002V01TPEEM", "S002V01TPERS.PERS_IDPE", "=", "S002V01TPEEM.PEEM_IDPE")
+                ->join("S002V01TEQMA", "S002V01TPEEM.PEEM_IDEM", "=", "S002V01TEQMA.EQMA_IDEQ")
+                ->join("S002V01TEMIN", "S002V01TEQMA.EQMA_IDEQ", "=", "S002V01TEMIN.EMIN_IDEM")
+                ->join("S002V01TINTE_P", "S002V01TEMIN.EMIN_IDIN", "=", "S002V01TINTE_P.INTE_IDIN")
+                ->get();
+
+
+            // Verifica si el objeto contiene algo
+            if (isset($search_employee[0]) && !empty($search_employee[0])) {
+                return $this->response_controller
+                    ->makeResponse(TRUE, "ERR_PERSONAL_REG004: Empleado ocupado con intervenciones", $search_employee, 500);
+            } else {
+
+                DB::beginTransaction(); # Para impedir que las actualizaciones queden incompletas
+
+                $UPDATE_DATE = Carbon::now()->timezone('America/Mexico_City')->toDateTimeString();
+
+                $delete_employee = DB::table('S002V01TPERS')
+                    ->where('PERS_IDPE', $id_employee)
+                    ->where('PERS_NULI', '=', $request->LINE_NUMBER)
+                    ->update([
+                        "PERS_ESTA" => "Inactivo",
+                        "PERS_USMO" => trim($request->UPDATED_BY_USER),
+                        "PERS_FEMO" => $UPDATE_DATE,
+                        "PERS_FEAR" => DB::raw('CURRENT_TIMESTAMP')
+                    ]);
+
+                // Verifica que la actualización fuera exitosa
+                if ($delete_employee < 1) {
+                    return $this->response_controller
+                        ->makeResponse(TRUE, 'ERR_PERSONAL_REG005: Algo salió mal, error eliminando al empleado', [], 500);
+                }
+
+                $delete_employee = DB::table('S002V01TPEEM')
+                    ->where('PEEM_IDPE', $id_employee)
+                    ->where('PEEM_NULI', '=', $request->LINE_NUMBER)
+                    ->update([
+                        "PEEM_ESTA" => "Inactivo",
+                        "PEEM_USMO" => trim($request->UPDATED_BY_USER),
+                        "PEEM_FEMO" => $UPDATE_DATE,
+                        "PEEM_FEAR" => DB::raw('CURRENT_TIMESTAMP')
+                    ]);
+
+                // Verifica que la actualización fuera exitosa
+                if ($delete_employee < 1) {
+                    DB::rollBack(); # Si no se logra eliminar al empleado en el equipo, se revierten los cambios previos
+                    return $this->response_controller
+                        ->makeResponse(TRUE, 'ERR_PERSONAL_REG006: Algo salió mal, error eliminando al empleado del equipo', [], 500);
+                }
+            }
+            DB::commit(); # Para guardar los cambios en la base de datos
+            return $this->response_controller->makeResponse(FALSE, "Eliminado exitoso");
+
+        } catch (Throwable $th) {
+            return $this->response_controller
+                ->makeResponse(TRUE, 'ERR_PERSONAL_REG007: Error inesperado', strtoupper($th->getMessage()), 500);
+        }
+    }
+
+    // Metodo para guardar un nuevo empleado
+    public function storeEmployee(Request $request)
+    {
+
+        try {
+            $REGISTER_DATE = Carbon::now()->timezone('America/Mexico_City')->toDateTimeString();
+            $request['CONTACT_NAME'] = $this->encrypt_controller->decrypt($request->CONTACT_NAME);
+            $request['CONTACT_TELEPHONE'] = $this->encrypt_controller->decrypt($request->CONTACT_TELEPHONE);
+            $request['CONTACT_ADDRESS'] = $this->encrypt_controller->decrypt($request->CONTACT_ADDRESS);
+
+            $validator = Validator::make($request->all(), [
+                "USER_ID" => ['required', 'digits:10'],
+                "WORKTEAM_ID" => ['required', 'digits:10'],
+                "CONTACT_NAME" => ['required', 'max:150'],
+                "CONTACT_TELEPHONE" => ['required', 'max:11'],
+                "CONTACT_ADDRESS" => ['required', 'max:100'],
+                "CONTRACT_TYPE" => ['required'],
+                "SPECIALITY" => ['required', 'max:75'],
+                "SUBCONTRATIST_ID" => ['max:10'],
+                "REGISTERED_BY_USER" => ['required', 'digits:10'],
+                "LINE_NUMBER" => ['required', 'digits:1']
+            ]);
+
+
+            if ($validator->fails()) {
+                return $this->response_controller->makeResponse(
+                    TRUE,
+                    'ERR_PERSONAL_REG001: Uno o más errores encontrados',
+                    $this->response_controller->makeErrors($validator->errors()->messages()),
+                    400
+                );
+            }
+
+            // Busca en la base si existe otro empleado con ese usuario
+            $uniq_user = DB::table('S002V01TPERS')
+                ->select("PERS_IDPE")
+                ->where('PERS_IDUS', '=', $request->USER_ID)
+                    // ->where('PERS_NULI', '=', '01')
+                ->first();
+
+            // Verifica si el objeto contiene algo
+            if (isset($uniq_user) && !empty($uniq_user)) {
+                return $this->response_controller
+                    ->makeResponse(TRUE, 'ERR_PERSONAL_REG002: El usuario ya está registrado como empleado', [], 500);
+            }
+
+            // Busca si el usuario existe
+            $user_exist = DB::table('S002V01TUSUA_P')
+                ->select("USUA_IDUS")
+                ->where('USUA_IDUS', '=', $request->USER_ID)
+                    // ->where('USUA_NULI', '=', '01')
+                ->first();
+
+            // Verifica si el objeto esta vacio
+            if (!isset($user_exist) && empty($user_exist)) {
+                return $this->response_controller
+                    ->makeResponse(TRUE, 'ERR_PERSONAL_REG003: No se encontró al usuario', [], 500);
+            }
+
+            // Busca si el equipo de trabajo existe
+            $team_found = DB::table('S002V01TEQMA')
+                ->select('EQMA_NOMB')
+                ->where('EQMA_IDEQ', '=', $request->WORKTEAM_ID)
+                    // ->where('EQMA_NULI', '=', '01')
+                ->first();
+
+            // Verifica si el objeto esta vacio
+            if (!isset($team_found) && empty($team_found)) {
+                return $this->response_controller
+                    ->makeResponse(TRUE, 'ERR_EQUIPO_TRABAJO_REG004: No se encontró al equipo de trabajo', [], 500);
+            }
+
+            $user_register = DB::table('S002V01TUSUA_P')
+                ->select('USUA_IDUS as ID_USER')
+                ->where('USUA_IDUS', '=', $request->REGISTERED_BY_USER)
+                ->first();
+
+            // Verifica si el objeto esta vacio
+            if (!isset($user_register) && empty($user_register)) {
+                return $this->response_controller
+                    ->makeResponse(TRUE, "ERR_USUARIO_REG005: Tu usuario no es válido para registrar empleados", [], 500);
+            }
+
+            DB::beginTransaction(); # Para impedir que las actualizaciones queden a incompletas
+
+            $insert_employee = DB::table('S002V01TPERS')
+                ->insert([
+                    "PERS_IDUS" => $request->USER_ID,
+                    "PERS_NOCE" => trim($request->CONTACT_NAME),
+                    "PERS_NUTC" => $request->CONTACT_TELEPHONE,
+                    "PERS_DICE" => trim($request->CONTACT_ADDRESS),
+                    "PERS_TICO" => trim($request->CONTRACT_TYPE),
+                    "PERS_ESPE" => trim($request->SPECIALITY),
+                    "PERS_IDPS" => $request->SUBCONTRATIST_ID,
+                    "PERS_NULI" => $request->LINE_NUMBER,
+                    "PERS_ESTA" => "Activo",
+                    "PERS_USRE" => $request->REGISTERED_BY_USER,
+                    "PERS_FERE" => $REGISTER_DATE,
+                    "PERS_FEAR" => DB::raw('CURRENT_TIMESTAMP')
+                ]);
+
+            // Verifica que la inserción del empleado se haya hecho correctamente
+            if (!$insert_employee) {
+                return $this->response_controller
+                    ->makeResponse(TRUE, 'ERR_PERSONAL_REG006: Algo salió mal, error registrando al empleado', [], 500);
+            }
+
+            // Obtiene el ID del empleado registrado
+            $employee_id = DB::table('S002V01TPERS')
+                ->select('PERS_IDPE as EMPLOYEE_ID')
+                ->where('PERS_IDUS', '=', $request->USER_ID)
+                    // ->where('PERS_NULI', '=', '01')
+                ->first();
+
+            // Saca el ID del objeto
+            $employee_id = $employee_id->EMPLOYEE_ID;
+
+            $insert_employee_on_workteam = DB::table('S002V01TPEEM')
+                ->insert([
+                    "PEEM_IDPE" => $employee_id,
+                    "PEEM_IDEM" => $request->WORKTEAM_ID,
+                    "PEEM_NULI" => $request->LINE_NUMBER,
+                    "PEEM_ESTA" => "Activo",
+                    "PEEM_USRE" => $request->REGISTERED_BY_USER,
+                    "PEEM_FERE" => $REGISTER_DATE,
+                    "PEEM_FEAR" => DB::raw('CURRENT_TIMESTAMP'),
+                ]);
+
+            // Verifica que la inserción del empleado en el equipo de trabajo se haya hecho correctamente
+            if (!$insert_employee_on_workteam) {
+                DB::rollBack(); # Si no se logra insertar al equipo, se revierten los cambios previos
+                return $this->response_controller
+                    ->makeResponse(TRUE, 'ERR_EQUIPO_TRABAJO_REG007: Algo salió mal, error registrando al empleado en el equipo', [], 500);
+            }
+
+            // Verifica si el objeto esta vacio
+            if (isset($request->DOCUMENTS[0]) && !empty($request->DOCUMENTS[0])) {
+                foreach ($request->DOCUMENTS as $doc) {
+
+                    //$doc = $this->encrypt_controller->decrypt($doc); #Para cuando este en producción, desencriptar el archivo
+                    // Se obtiene el nombre del archivo con su extensión
+                    $completeFileName = $doc->getClientOriginalName();
+
+                    // Se obtiene únicamente el nombre
+                    $fileNameOnly = pathinfo($completeFileName, PATHINFO_FILENAME);
+
+                    // Se obtiene la extensión del archivo
+                    $extension = $doc->getClientOriginalExtension();
+
+                    // Se quitan los espacios y se concatena datos para ser guardado
+                    $final_part_name_document = str_replace(' ', '_', $fileNameOnly) . '.' . $extension;
+
+                    // Crea el nombre del documento y lo almacena en la base de datos
+                    $name_document = $this->documents_controller->createDocument(
+                        "GPRS",
+                        "CO",
+                        $final_part_name_document,
+                        $employee_id,
+                        'pdf',
+                        $request->LINE_NUMBER,
+                        $request->REGISTERED_BY_USER
+                    );
+
+                    // El documento es guardado e el storage
+                    $doc->storeAs('public/pdf_documents', $name_document);
+
+                }
+
+            }
+
+            DB::commit(); # Para guardar los cambios en la base de datos
+            return $this->response_controller->makeResponse(FALSE, 'Creación exitosa', 200);
+
+        } catch (Throwable $th) {
+            return $this->response_controller
+                ->makeResponse(TRUE, 'ERR_PERSONAL_REG008: Error inesperado', strtoupper($th), 500);
+        }
+    }
+
+    // Metodo para obtener un empleado por id con sus documentos (Pensado: 1 empleado solo tiene un equipo de trabajo)
+    public function getEmployeeById($id_employee, $line_number)
+    {
+        try {
+
+            $employee = DB::table('S002V01TPERS')
+                ->select(
+                    'S002V01TPERS.PERS_IDPE as EMPLOYEE_ID',
+                    'S002V01TPERS.PERS_IDUS as USER_ID',
+                    'S002V01TEQMA.EQMA_IDEQ as WORKTEAM_ID',
+                    'S002V01TEQMA.EQMA_NOMB as WORKTEAM_NAME',
+                    'S002V01TPERS.PERS_NOCE as CONTACT_NAME',
+                    'S002V01TPERS.PERS_NUTC as CONTACT_TELEPHONE',
+                    'S002V01TPERS.PERS_DICE as CONTACT_ADDRESS',
+                    'S002V01TPERS.PERS_TICO as CONTRACT_TYPE',
+                    'S002V01TPERS.PERS_ESPE as SPECIALITY',
+                    'S002V01TPERS.PERS_NULI as LINE_NUMBER',
+                    DB::raw('CONCAT(S002V01TUSUA_P.USUA_NOMB, " " , S002V01TUSUA_P.USUA_APPA, " ",  S002V01TUSUA_P.USUA_APMA) as EMPLOYEE_NAME')
+                )
+                ->where('S002V01TPERS.PERS_IDPE', '=', $id_employee)
+                ->where('S002V01TPERS.PERS_NULI', '=', $line_number)
+                ->where('s002v01TPEEM.PEEM_NULI', '=', $line_number)
+                ->where('s002v01TEQMA.EQMA_NULI', '=', $line_number)
+                ->where('s002v01TUSUA_P.USUA_NULI', '=', $line_number)
+                ->join('S002V01TPEEM', 'S002V01TPERS.PERS_IDPE', '=', 'S002V01TPEEM.PEEM_IDPE')
+                ->join('S002V01TEQMA', 'S002V01TPEEM.PEEM_IDEM', '=', 'S002V01TEQMA.EQMA_IDEQ')
+                ->join('S002V01TUSUA_P', 'S002V01TPERS.PERS_IDUS', '=', 'S002V01TUSUA_P.USUA_IDUS')
+                ->first();
+
+            // Verifica si el objeto esta vacio
+            if (!isset($employee) && empty($employee)) {
+                return $this->response_controller
+                    ->makeResponse(TRUE, 'ERR_PERSONAL_REG001: No se encontró al empleado', [], 500);
+            }
+
+            $employee->DOCUMENTS = [];
+
+            // Obtiene los documentos de un empleado
+            $documents_of_employee = DB::table('S002V01TDOCU_P')
+                ->select('DOCU_LIDO as DOCUMENT')
+                ->where('DOCU_IDPE', '=', $id_employee)
+                ->where('DOCU_NULI', '=', $line_number)
+                ->get();
+
+            // Verifica si el objeto contiene algo
+            if (isset($documents_of_employee[0]) && !empty($documents_of_employee[0])) {
+                foreach ($documents_of_employee as $doc) {
+                    $employee->DOCUMENTS[] = $this->encrypt_controller->encrypt($doc->DOCUMENT);
+                }
+            }
+
+            return $this->response_controller
+                ->makeResponse(FALSE, "Consulta exitosa", $employee);
+
+
+        } catch (Throwable $th) {
+            return $this->response_controller
+                ->makeResponse(TRUE, 'ERR_PERSONAL_REG002: Error inesperado', strtoupper($th->getMessage()), 500);
+        }
+    }
+
+    // Metodo para obtener todos los empleados con sus documentos (Pensado: 1 empleado solo tiene un equipo de trabajo)
+    public function getAllEmployees($line_number)
+    {
+        try {
+
+            $employees = DB::table('S002V01TPERS')
+                ->select(
+                    'S002V01TPERS.PERS_IDPE as EMPLOYEE_ID',
+                    'S002V01TPERS.PERS_IDUS as USER_ID',
+                    'S002V01TEQMA.EQMA_IDEQ as WORKTEAM_ID',
+                    'S002V01TPERS.PERS_NOCE as CONTACT_NAME',
+                    'S002V01TPERS.PERS_NUTC as CONTACT_TELEPHONE',
+                    'S002V01TPERS.PERS_DICE as CONTACT_ADDRESS',
+                    'S002V01TPERS.PERS_TICO as CONTRACT_TYPE',
+                    'S002V01TPERS.PERS_ESPE as SPECIALITY',
+                )
+                ->where('S002V01TPERS.PERS_NULI', '=', $line_number)
+                ->where('S002V01TPEEM.PEEM_NULI', '=', $line_number)
+                ->where('S002V01TEQMA.EQMA_NULI', '=', $line_number)
+                ->join('S002V01TPEEM', 'S002V01TPERS.PERS_IDPE', '=', 'S002V01TPEEM.PEEM_IDPE')
+                ->join('S002V01TEQMA', 'S002V01TPEEM.PEEM_IDEM', '=', 'S002V01TEQMA.EQMA_IDEQ')
+                ->get();
+
+            // Verifica si el objeto esta vacio
+            if (!isset($employees[0]) && empty($employees[0])) {
+                return $this->response_controller
+                    ->makeResponse(TRUE, 'ERR_PERSONAL_REG001: No se encontraron datos', [], 500);
+            }
+
+            // Obtiene los documentos
+            $documents_of_employees = DB::table('S002V01TDOCU_P')
+                ->select('DOCU_LIDO as DOCUMENT', 'DOCU_IDPE as EMPLOYEE_ID')
+                ->where('DOCU_NULI', '=', $line_number)
+                ->get();
+
+            // Verifica si el objeto esta vacio
+            if (isset($documents_of_employees[0]) && !empty($documents_of_employees[0])) {
+
+                // Asigna al empleado los documentos que le pertenezcan
+                foreach ($employees as $employee) {
+                    $employee->DOCUMENTS = [];
+                    foreach ($documents_of_employees as $doc) {
+                        if ($employee->EMPLOYEE_ID == $doc->EMPLOYEE_ID) {
+                            $employee->DOCUMENTS[] = $this->encrypt_controller->encrypt($doc->DOCUMENT);
+                        }
+                    }
+                }
+            }
+
+            return $this->response_controller
+                ->makeResponse(FALSE, "Consulta exitosa", $employees);
+
+        } catch (Throwable $th) {
+            return $this->response_controller
+                ->makeResponse(TRUE, 'ERR_PERSONAL_REG002: Error inesperado', strtoupper($th->getMessage()), 500);
+        }
+    }
+
+    // Metodo para actualizar un empleado
+    public function updateEmployee(Request $request, $id_employee)
+    {
+
+        try {
+            $UPDATE_DATE = Carbon::now()->timezone('America/Mexico_City')->toDateTimeString();
+            $request['CONTACT_NAME'] = $this->encrypt_controller->decrypt($request->CONTACT_NAME);
+            $request['CONTACT_TELEPHONE'] = $this->encrypt_controller->decrypt($request->CONTACT_TELEPHONE);
+            $request['CONTACT_ADDRESS'] = $this->encrypt_controller->decrypt($request->CONTACT_ADDRESS);
+
+            $validator = Validator::make($request->all(), [
+                "USER_ID" => ['required', 'digits:10'],
+                "WORKTEAM_ID" => ['required', 'digits:10'],
+                "CONTACT_NAME" => ['required', 'max:150'],
+                "CONTACT_TELEPHONE" => ['required', 'max:11'],
+                "CONTACT_ADDRESS" => ['required', 'max:100'],
+                "CONTRACT_TYPE" => ['required'],
+                "SPECIALITY" => ['required', 'max:75'],
+                "SUBCONTRATIST_ID" => ['max:10'],
+                "UPDATED_BY_USER" => ['required', 'digits:10'],
+                "LINE_NUMBER" => ['required', 'digits:1']
+            ]);
+
+            if ($validator->fails()) {
+                return $this->response_controller->makeResponse(
+                    true,
+                    'ERR_PERSONAL_REG001: Uno o más errores encontrados',
+                    $this->response_controller->makeErrors($validator->errors()->messages()),
+                    400
+                );
+            }
+
+            // Busca al empleado si existe
+            $employee_exist = DB::table('S002V01TPERS')
+                ->select('PERS_IDPE')
+                ->where('PERS_IDPE', '=', $id_employee)
+                ->where('PERS_NULI', '=', $request->LINE_NUMBER)
+                ->first();
+
+            // Verifica si el objeto esta vacio
+            if (!isset($employee_exist) && empty($employee_exist)) {
+                return $this->response_controller
+                    ->makeResponse(TRUE, 'ERR_PERSONAL_REG002: No se encontró al empleado', [], 500);
+            }
+
+            // Busca al equipo de trabajo si existe
+            $team_found = DB::table('S002V01TEQMA')
+                ->select('EQMA_NOMB')
+                ->where('EQMA_IDEQ', '=', $request->WORKTEAM_ID)
+                ->where('EQMA_NULI', '=', $request->LINE_NUMBER)
+                ->first();
+
+            // Verifica si el objeto esta vacio
+            if (!isset($team_found) && empty($team_found)) {
+                return $this->response_controller
+                    ->makeResponse(TRUE, 'ERR_EQUIPO_TRABAJO_REG003: No se encontró al equipo de trabajo', [], 500);
+            }
+
+            $user_register = DB::table('S002V01TUSUA_P')
+                ->select('USUA_IDUS as ID_USER')
+                ->where('USUA_IDUS', '=', $request->UPDATED_BY_USER)
+                ->where('USUA_NULI', '=', $request->LINE_NUMBER)
+                ->first();
+
+            // Verifica si el objeto esta vacio
+            if (!isset($user_register) && empty($user_register)) {
+                return $this->response_controller
+                    ->makeResponse(TRUE, "ERR_USUARIO_REG004: Tu usuario no es válido para actualizar empleados", [], 500);
+            }
+
+            DB::beginTransaction(); # Para impedir que las actualizaciones queden incompletas
+
+            $update_employee = DB::table('S002V01TPERS')
+                ->where('PERS_IDPE', '=', $id_employee)
+                ->where('PERS_NULI', '=', $request->LINE_NUMBER)
+                ->update([
+                    "PERS_IDUS" => $request->USER_ID,
+                    "PERS_NOCE" => trim($request->CONTACT_NAME),
+                    "PERS_NUTC" => $request->CONTACT_TELEPHONE,
+                    "PERS_DICE" => trim($request->CONTACT_ADDRESS),
+                    "PERS_TICO" => trim($request->CONTRACT_TYPE),
+                    "PERS_ESPE" => trim($request->SPECIALITY),
+                    "PERS_IDPS" => $request->SUBCONTRATIST_ID,
+                    "PERS_ESTA" => "Activo",
+                    "PERS_USMO" => $request->UPDATED_BY_USER,
+                    "PERS_FEMO" => $UPDATE_DATE,
+                    "PERS_FEAR" => DB::raw('CURRENT_TIMESTAMP')
+                ]);
+
+            // Verifica que la actualización del empleado haya sido satisfactoria
+            if ($update_employee < 1) {
+                return $this->response_controller
+                    ->makeResponse(TRUE, 'ERR_PERSONAL_REG005: Algo salió mal, error actualizando al empleado', [], 500);
+            }
+
+            $update_employee_on_workteam = DB::table('S002V01TPEEM')
+                ->where('PEEM_IDPE', '=', $id_employee)
+                ->where('PEEM_NULI', '=', $request->LINE_NUMBER)
+                ->update([
+                    "PEEM_IDEM" => $request->WORKTEAM_ID,
+                    "PEEM_ESTA" => "Activo",
+                    "PEEM_USRE" => $request->UPDATED_BY_USER,
+                    "PEEM_FERE" => $UPDATE_DATE,
+                    "PEEM_FEAR" => DB::raw('CURRENT_TIMESTAMP'),
+                ]);
+
+            // Verifica que la actualización del cambio de equipo del empleado haya sido satisfactoria
+            if ($update_employee_on_workteam < 1) {
+                DB::rollBack(); # Si no se logra actualizar el equipo, se revierten los cambios previos
+                return $this->response_controller
+                    ->makeResponse(TRUE, 'ERR_EQUIPO_TRABAJO_REG006: Algo salió mal, error cambiando al empleado de equipo', [], 500);
+            }
+
+            // Verifica si el objeto esta vacio
+            if (isset($request->DOCUMENTS[0]) && !empty($request->DOCUMENTS[0])) {
+                $documents_saved = [];
+                foreach ($request->DOCUMENTS as $doc) {
+
+                    //$doc = $this->encrypt_controller->decrypt($doc); #Para cuando este en producción, desencriptar
+                    // Se obtiene el nombre del archivo con su extensión
+                    $completeFileName = $doc->getClientOriginalName();
+
+                    // Se obtiene únicamente el nombre
+                    $fileNameOnly = pathinfo($completeFileName, PATHINFO_FILENAME);
+
+                    // Se obtiene la extensión del archivo
+                    $extension = $doc->getClientOriginalExtension();
+
+                    // Se quitan los espacios y se concatena datos para ser guardado
+                    $final_part_name_document = str_replace(' ', '_', $fileNameOnly) . '.' . $extension;
+
+                    $final_part_name_document = $this->documents_controller->deleteCodificationStructureName($final_part_name_document, "01", "GPRS");
+                    $old_documents_name = $this->documents_controller->getDocumentsWithSameName($final_part_name_document, "pdf");
+                    if ($old_documents_name != null) {
+
+                        // Si no hay ningun cambio en el documento, se descarga la ultima versión
+                        $old_documents_name = $this->documents_controller->sameDocumentsPdfOnRequest($doc, $old_documents_name);
+                        if ($old_documents_name == null) {
+
+                            // Crea el nombre del documento y lo almacena en la base de datos
+                            $name_document = $this->documents_controller->createDocument(
+                                "GPRS",
+                                "CO",
+                                $final_part_name_document,
+                                $id_employee,
+                                'pdf',
+                                $request->LINE_NUMBER,
+                                $request->UPDATED_BY_USER
+                            );
+                            $documents_saved[] = $name_document;
+
+                            // El documento es guardado en el storage
+                            $doc->storeAs('public/pdf_documents', $name_document);
+                        } else {
+
+                            // Si algun documento esta duplicado, se revierten los cambios previos
+                            DB::rollBack();
+                            $this->documents_controller->deleteAllDocumentsByName($documents_saved, 'pdf');
+                            return $this->response_controller
+                                ->makeResponse(TRUE, 'ERR_DOCUMENTO_REG006: Documento ya insertado anteriormente', $old_documents_name, 500);
+                        }
+                    } else {
+                        $name_document = $this->documents_controller->createDocument(
+                            "GPRS",
+                            "CO",
+                            $final_part_name_document,
+                            $id_employee,
+                            'pdf',
+                            $request->LINE_NUMBER,
+                            $request->UPDATED_BY_USER
+                        );
+                        $documents_saved[] = $name_document;
+
+                        // El documento es guardado en el storage
+                        $doc->storeAs('public/pdf_documents', $name_document);
+                    }
+
+
+                }
+
+            }
+
+
+            DB::commit(); # Para guardar los cambios en la base de datos
+            return $this->response_controller->makeResponse(FALSE, 'Actualización exitosa', 200);
+
+        } catch (Throwable $th) {
+            return $this->response_controller
+                ->makeResponse(TRUE, 'ERR_PERSONAL_REG007: Error inesperado', strtoupper($th), 500);
+        }
+    }
+
+    // Metodo para obtener la cantidad de contratos otorgados a cada empleado
+    public function getContractsOfEveryEmployee($line_number)
+    {
+        try {
+
+            // Obtiene la cantidad de contratos que tiene cada empleado
+            $contracts_by_employee = DB::table('S002V01TPERS')
+                ->select(
+                    'S002V01TPERS.PERS_IDPE as ID_EMPLOYEE',
+                    DB::raw('CONCAT(S002V01TUSUA_P.USUA_NOMB, " " , S002V01TUSUA_P.USUA_APPA, " ", S002V01TUSUA_P.USUA_APMA) AS NAME'),
+                    DB::raw(
+                        'COUNT(S002V01TPECO.PECO_IDPE) AS CONTRACTS_COUNT',
+                    )
+                )
+                ->where('S002V01TPERS.PERS_NULI', '=', $line_number)
+                ->where('S002V01TUSUA_P.USUA_NULI', '=', $line_number)
+                ->where('S002V01TPECO.PECO_NULI', '=', $line_number)
+                ->where('S002V01TCONT.CONT_NULI', '=', $line_number)
+                ->groupBy('S002V01TPERS.PERS_IDPE', 'NAME', 'S002V01TPECO.PECO_IDPE')
+                ->join('S002V01TUSUA_P', 'S002V01TPERS.PERS_IDUS', '=', 'S002V01TUSUA_P.USUA_IDUS')
+                ->join('S002V01TPECO', 'S002V01TPERS.PERS_IDPE', '=', 'S002V01TPECO.PECO_IDPE')
+                ->join('S002V01TCONT', 'S002V01TPECO.PECO_IDCO', '=', 'S002V01TCONT.CONT_IDCO')
+                ->get();
+
+            // Verifica si el objeto esta vacio
+            if (!isset($contracts_by_employee[0]) && empty($contracts_by_employee[0])) {
+                return $this->response_controller
+                    ->makeResponse(TRUE, 'ERR_PERSONAL_CONTRATO_REG001: No se encontraron datos', [], 500);
+            }
+
+            return $this->response_controller
+                ->makeResponse(FALSE, "Consulta exitosa", $contracts_by_employee);
+
+        } catch (Throwable $th) {
+            return $this->response_controller
+                ->makeResponse(TRUE, 'ERR_PERSONAL_REG002: Error inesperado', strtoupper($th->getMessage()), 500);
+        }
+    }
+
+    // Metodo para obtener detalles acerca de los contratos otorgados al empleado
+    public function getDetailsOfContractsByEmployee($id_employee, $line_number)
+    {
+        try {
+
+            // Busca al empleado si existe
+            $employee_exist = DB::table('S002V01TPERS')
+                ->select('PERS_IDPE')
+                ->where('PERS_IDPE', '=', $id_employee)
+                ->where('PERS_NULI', '=', $line_number)
+                ->first();
+
+            // Verifica si el objeto esta vacio
+            if (!isset($employee_exist) && empty($employee_exist)) {
+                return $this->response_controller
+                    ->makeResponse(TRUE, 'ERR_PERSONAL_REG001: No se encontró al empleado', [], 500);
+            }
+
+            //Obtiene los contratos pertenecientes al subcontratista deseado
+            $contracts_by_employee = DB::table('S002V01TPERS')
+                ->orderBy("S002V01TCONT.CONT_FEIN", 'desc')
+                ->where('S002V01TPERS.PERS_IDPE', '=', $id_employee)
+                ->where('S002V01TPERS.PERS_NULI', '=', $line_number)
+                ->where('S002V01TPECO.PECO_NULI', '=', $line_number)
+                ->where('S002V01TCONT.CONT_NULI', '=', $line_number)
+                ->select('S002V01TCONT.CONT_FEIN as START_DATE', 'S002V01TCONT.CONT_FEFI as END_DATE', 'S002V01TCONT.CONT_COST as CONTRACT_COST')
+                ->join('S002V01TPECO', 'S002V01TPERS.PERS_IDPE', '=', 'S002V01TPECO.PECO_IDPE')
+                ->join('S002V01TCONT', 'S002V01TPECO.PECO_IDCO', '=', 'S002V01TCONT.CONT_IDCO')
+                ->get();
+
+            // Verifica si el objeto esta vacio
+            if (!isset($contracts_by_employee[0]) && empty($contracts_by_employee[0])) {
+                return $this->response_controller
+                    ->makeResponse(TRUE, 'ERR_PERSONAL_CONTRATO_REG002: Empleado sin contratos', $contracts_by_employee, 500);
+            }
+
+            foreach ($contracts_by_employee as $contract) {
+                $contract->START_DATE = Carbon::create($contract->START_DATE)->format("d-m-Y h:i:s A");
+                $contract->END_DATE = Carbon::create($contract->END_DATE)->format("d-m-Y h:i:s A");
+                $contract->CONTRACT_COST = $this->encrypt_controller->encrypt($contract->CONTRACT_COST);
+            }
+
+            return $this->response_controller
+                ->makeResponse(FALSE, "Consulta exitosa", $contracts_by_employee);
+
+        } catch (Throwable $th) {
+            return $this->response_controller
+                ->makeResponse(TRUE, 'ERR_PERSONAL_REG003: Error inesperado', strtoupper($th->getMessage()), 500);
+        }
+    }
+
+    // Metodo para la descarga de archivo excel con los detalles del empleado
+    public function downoloadEmployeeInfoOnExcel(Request $request)
+    {
+
+        try {
+
+            $employee_id = $request->employee['EMPLOYEE_ID'];
+
+            $final_part_name_document = "Details_Of_Employee_" . $employee_id . ".xlsx";
+
+            // Crea el documento con los datos del request
+            $document = $this->createDocument($request);
+
+            // Busca la ultima versión del documento que se haya insertado
+            $old_document_name = $this->documents_controller->getDocumentsWithSameName($final_part_name_document, 'excel');
+
+            if ($old_document_name != null) {
+
+                // Obtiene el nombre del documento que tiene el mismo contenido
+                $old_document_name = $this->documents_controller->sameDocumentsExcel($document, $old_document_name);
+
+                // Si no hay ningun cambio en el documento, se descarga la ultima versión
+                if ($old_document_name != null) {
+                    return Storage::disk('excel')->download($old_document_name);
+                }
+            }
+
+            // Guarda el documento creado en la variable
+            $writer = IOFactory::createWriter($document, 'Xlsx');
+            $content = tmpfile();
+            $writer->save($content);
+
+            // Inserta la nueva version del documento en la base de datos y en el storage            
+            $name_document = $this->documents_controller->createDocument("GPRS", "IN", $final_part_name_document, $employee_id, "excel", $request->employee['LINE_NUMBER'], $request->REGISTERED_BY_USER);
+
+            Storage::disk('excel')->put(
+                $name_document,
+                $content
+            );
+
+            return Storage::disk('excel')->download($name_document);
+
+        } catch (Throwable $th) {
+            return $this->response_controller
+                ->makeResponse(TRUE, 'ERR_EXCEL_REG001: Error inesperado', strtoupper($th), 500);
+        }
+    }
+
+    // Metodo para la descarga de archivo pdf con los detalles del empleado
+    public function downoloadEmployeeInfoOnPdf(Request $request)
+    {
+
+        try {
+
+            $employee_id = $request->employee['EMPLOYEE_ID'];
+
+            $final_part_name_document = "Details_Of_Employee_" . $employee_id . ".pdf";
+
+            // Crea el documento
+            $document = $this->createDocument($request);
+            $writer = IOFactory::createWriter($document, 'Mpdf');
+            $content = tmpfile();
+
+            // Busca la ultima versión del documento que se haya insertado
+            $old_document_name = $this->documents_controller->getDocumentsWithSameName($final_part_name_document, 'pdf');
+
+            $writer->save($content);
+            if ($old_document_name != null) {
+
+                // Obtiene el nombre del documento que tiene el mismo contenido
+                $old_document_name = $this->documents_controller->sameDocumentsPdf($content, $old_document_name);
+
+                // Si no hay ningun cambio en el documento, se descarga la ultima versión
+                if ($old_document_name != null) {
+                    return Storage::disk('pdf')->download($old_document_name);
+                }
+            }
+
+            // Inserta la nueva version del documento en la base de datos y en el storage
+            $name_document = $this->documents_controller->createDocument("GPRS", "IN", $final_part_name_document, $employee_id, "pdf", $request->employee['LINE_NUMBER'], $request->REGISTERED_BY_USER);
+            Storage::disk('pdf')->put(
+                $name_document,
+                $content
+            );
+
+            return Storage::disk('pdf')->download($name_document);
+
+        } catch (Throwable $th) {
+            return $this->response_controller
+                ->makeResponse(TRUE, 'ERR_PDF_REG001: Error inesperado', strtoupper($th), 500);
+        }
+    }
+
+    // Metodo para la creación de archivo
+    public function createDocument(Request $request)
+    {
+        try {
+            $employee = $request->employee;
+            $document = new Spreadsheet();
+
+            // Propiedades del documento
+            $document->getProperties()
+                ->setCreator("ITTEC")
+                ->setTitle("Detalles del empleado")
+                ->setDescription("Detalles de solo un empleado.")
+                ->setKeywords("Empleado Detalles")
+                ->setCategory("Empleado Detalles Pdf");
+
+            // Hace la escritura dentro del archivo
+            $start_row = 2; # Indica desde que fila inicia la tabla
+            $start_col = "B"; # Indica desde que columna inicia la tabla
+
+            $col = $start_col;
+            $row = $start_row;
+            $col++;
+            $second_col = $col;
+            $col++;
+            $third_col = $col;
+            $col++;
+            $fourth_col = $col;
+            $col++;
+            $fifth_col = $col;
+            $col++;
+            $sixth_col = $col;
+            $col++;
+            $seventh_col = $col;
+            $col++;
+            $eight_col = $col;
+            $col = $start_col;
+            $final_col = "";
+
+            for ($i = 0; $i < 9; $i++) {
+                $final_col = $col;
+                $col++;
+            }
+            $col = $start_col;
+
+            // Titulo del documento
+            $document->getActiveSheet()->mergeCells($start_col . $row . ":" . $final_col . $row);
+            $document->getActiveSheet()->setCellValue($start_col . $row, 'DETALLES DEL EMPLEADO')->getStyle($start_col . $row)->getFill()
+                ->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)
+                ->getStartColor()->setRGB('FFCC88');
+            $document->getActiveSheet()->getStyle($start_col . $row)->getFont()->setBold(true);
+            $row++;
+
+            //Cuerpo del documento
+            $document->getActiveSheet()->setCellValue($col . $row, 'ID EMPLEADO')->getStyle($col . $row)->getFill()
+                ->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)
+                ->getStartColor()->setRGB('38D9CE');
+            $col++;
+
+            $document->getActiveSheet()->setCellValue($col . $row, 'NOMBRE EMPLEADO')->getStyle($col . $row)->getFill()
+                ->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)
+                ->getStartColor()->setRGB('38D9CE');
+            $col++;
+
+            $document->getActiveSheet()->setCellValue($col . $row, 'NOMBRE EQUIPO')->getStyle($col . $row)->getFill()
+                ->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)
+                ->getStartColor()->setRGB('38D9CE');
+            $col++;
+
+            $document->getActiveSheet()->setCellValue($col . $row, 'NOMBRE CONTACTO DE EMERGENCIA')->getStyle($col . $row)->getFill()
+                ->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)
+                ->getStartColor()->setRGB('38D9CE');
+            $col++;
+
+            $document->getActiveSheet()->setCellValue($col . $row, 'TELEFONO CONTACTO DE EMERGENCIA')->getStyle($col . $row)->getFill()
+                ->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)
+                ->getStartColor()->setRGB('38D9CE');
+            $col++;
+
+            $document->getActiveSheet()->setCellValue($col . $row, 'DIRECCIÓN CONTACTO DE EMERGENCIA')->getStyle($col . $row)->getFill()
+                ->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)
+                ->getStartColor()->setRGB('38D9CE');
+            $col++;
+
+            $document->getActiveSheet()->setCellValue($col . $row, 'TIPO DE CONTRATO')->getStyle($col . $row)->getFill()
+                ->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)
+                ->getStartColor()->setRGB('38D9CE');
+            $col++;
+
+            $document->getActiveSheet()->setCellValue($col . $row, 'ESPECIALIDAD DEL EMPLEADO')->getStyle($col . $row)->getFill()
+                ->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)
+                ->getStartColor()->setRGB('38D9CE');
+            $col++;
+
+            $document->getActiveSheet()->setCellValue($col . $row, 'LIGA DE DOCUMENTOS')->getStyle($col . $row)->getFill()
+                ->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)
+                ->getStartColor()->setRGB('38D9CE');
+
+            $row++;
+            $col = $start_col;
+
+            $document->getActiveSheet()->setCellValue($col . $row, "#" . $employee['EMPLOYEE_ID']);
+            $col++;
+
+            $document->getActiveSheet()->setCellValue($col . $row, $employee['EMPLOYEE_NAME']);
+            $col++;
+
+            $document->getActiveSheet()->setCellValue($col . $row, $employee['WORKTEAM_NAME']);
+            $col++;
+
+            $document->getActiveSheet()->setCellValue($col . $row, $employee['CONTACT_NAME']);
+            $col++;
+
+            $document->getActiveSheet()->setCellValue($col . $row, $employee['CONTACT_TELEPHONE']);
+            $col++;
+
+            $document->getActiveSheet()->setCellValue($col . $row, $employee['CONTACT_ADDRESS']);
+            $col++;
+
+            $document->getActiveSheet()->setCellValue($col . $row, $employee['CONTRACT_TYPE']);
+            $col++;
+
+            $document->getActiveSheet()->setCellValue($col . $row, $employee['SPECIALITY']);
+            $col++;
+
+            // Verifica si el empleado tiene documentos
+            if (isset($employee['DOCUMENTS'][0]) && !empty($employee['DOCUMENTS'][0])) {
+                foreach ($employee['DOCUMENTS'] as $doc) {
+                    $document->getActiveSheet()->setCellValue($col . $row, $this->encrypt_controller->decrypt($doc));
+                    $row++;
+                }
+            } else {
+                $document->getActiveSheet()->setCellValue($col . $row, 'SIN DOCUMENTOS...');
+                $document->getActiveSheet()->getStyle($col . $row)->getFont()->setBold(true);
+                $row++;
+            }
+
+            //Ajusta las celdas a su contenido y da estilo
+            $document->getActiveSheet()->mergeCells($start_col . $start_row + 2 . ":" . $start_col . $row - 1);
+            $document->getActiveSheet()->mergeCells($second_col . $start_row + 2 . ":" . $second_col . $row - 1);
+            $document->getActiveSheet()->mergeCells($third_col . $start_row + 2 . ":" . $third_col . $row - 1);
+            $document->getActiveSheet()->mergeCells($fourth_col . $start_row + 2 . ":" . $fourth_col . $row - 1);
+            $document->getActiveSheet()->mergeCells($fifth_col . $start_row + 2 . ":" . $fifth_col . $row - 1);
+            $document->getActiveSheet()->mergeCells($sixth_col . $start_row + 2 . ":" . $sixth_col . $row - 1);
+            $document->getActiveSheet()->mergeCells($seventh_col . $start_row + 2 . ":" . $seventh_col . $row - 1);
+            $document->getActiveSheet()->mergeCells($eight_col . $start_row + 2 . ":" . $eight_col . $row - 1);
+
+            $col = $start_col;
+            for ($i = 0; $i < 9; $i++) {
+                $document->getActiveSheet()->getColumnDimension($col)->setAutoSize(true);
+                $col++;
+            }
+
+            $document->getActiveSheet()->getStyle($start_col . $start_row . ':' . $final_col . $row)->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER);
+            $document->getActiveSheet()->getStyle($start_col . $start_row . ':' . $final_col . $row)->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);
+            $document->getActiveSheet()->getStyle($start_col . $start_row . ':' . $final_col . $row - 1)->getBorders()->getAllBorders()->setBorderStyle(\PhpOffice\PhpSpreadsheet\Style\Border::BORDER_MEDIUM);
+
+            return $document;
+
+        } catch (Throwable $th) {
+            return $this->response_controller
+                ->makeResponse(TRUE, 'ERR_CREACIÓN_DOCUMENTO_REG001: Error inesperado', strtoupper($th->getMessage()), 500);
+        }
+    }
+
+}
+
+/*
+PENDIENTES:
+3.1.2.1
+VER TASA HORARIA (Otro modulo)
+3.1.2.4 
+TASA HORARIA (Otro modulo)
+*/
+
+/*
+DATOS OBLIGATORIOS
+$REGISTER_DATE = Carbon::now()->timezone('America/Mexico_City')->toDateTimeString();
+$UPDATE_DATE = Carbon::now()->timezone('America/Mexico_City')->toDateTimeString();
+"_ESTA" => $request->STATUS,
+"_USRE" => $request->REGISTER_USER,
+"_USMO" => $request->MODIFIED_USER,
+"_FERE" => $REGISTER_DATE,
+"_FEMO" => $UPDATE_DATE,
+"_FEAR" => DB::raw('CURRENT_TIMESTAMP')
+*/

+ 574 - 0
sistema-mantenimiento-back/app/Http/Controllers/InterventionController.php

@@ -0,0 +1,574 @@
+<?php
+/*
+Nombre del programador:         Cordourier Rojas Mathew
+Ultima fecha de modificación:   [ 03 / Marzo / 2023 ]
+Descripción:                    Controlador del submodulo Intervenciones. Perteneciente al Módulo 13 - Gestion del Personal de Mantenimiento
+*/
+
+namespace App\Http\Controllers;
+
+use Carbon\Carbon;
+use Illuminate\Support\Facades\DB;
+use Illuminate\Http\Request;
+use Illuminate\Support\Facades\Validator;
+use Throwable;
+
+class InterventionController extends Controller
+{
+
+    private $response_controller;
+    private $encrypt_controller;
+    private $resources_controller;
+    private $documents_controller;
+    public function __construct()
+    {
+        $this->response_controller = new ResponseController();
+        $this->encrypt_controller = new EncryptionController();
+        $this->resources_controller = new ResourcesController();
+        $this->documents_controller = new DocumentsController();
+    }
+
+    // Metodo para consultar de las intervenciones
+    public function getConsultOfInterventions($line_number)
+    {
+        try {
+            $interventions = DB::table('S002V01TINTE_P')
+                ->select(
+                    'INTE_IDIN as INTERVENTION_ID',
+                    'INTE_FECS as START_DATE',
+                    'INTE_FESD as END_DATE'
+                )
+                ->where('INTE_ESTA', '=', 'Activo')
+                ->where('INTE_NULI', '=', $line_number)
+                ->get();
+
+            // Verifica si el objeto esta vacio
+            if (!isset($interventions[0]) && empty($interventions[0])) {
+                return $this->response_controller
+                    ->makeResponse(TRUE, 'ERR_INTERVENCIÓN_REG001: No se encontraron datos', $interventions, 500);
+            }
+
+            // Obtiene los datos de la tabla intermediaria entre intervenciones y equipos de mantenimiento
+            $equipment_by_intervention = DB::table('S002V01TINMA')
+                ->select(
+                    'INMA_IDMA as EQUIPMENT_ID',
+                    'INMA_IDIN as INTERVENTION_ID'
+                )
+                ->where('INMA_NULI', '=', $line_number)
+                ->get();
+
+            // Cambia el formato de las fechas y el equipamiento que se utilizó por intervención
+            foreach ($interventions as $intervention) {
+                $intervention->START_DATE = Carbon::create($intervention->START_DATE)->format("d-m-Y h:i:s A");
+                $intervention->END_DATE = Carbon::create($intervention->END_DATE)->format("d-m-Y h:i:s A");
+                foreach ($equipment_by_intervention as $equipment) {
+                    if ($equipment->INTERVENTION_ID == $intervention->INTERVENTION_ID) {
+                        $intervention->EQUIPMENTS_ID[] = $equipment->EQUIPMENT_ID;
+                    }
+                }
+            }
+
+            return $this->response_controller
+                ->makeResponse(FALSE, 'Consulta exitosa', $interventions);
+
+        } catch (Throwable $th) {
+            return $this->response_controller
+                ->makeResponse(TRUE, 'ERR_INTERVENCIÓN_REG002: Error inesperado', strtoupper($th->getMessage()), 500);
+        }
+    }
+
+    // Metodo para obtener los detalles de una intervención
+    public function getDetailsOfInterventionsById($id_intervention, $line_number)
+    {
+        try {
+
+            $intervention_details = DB::table('S002V01TINTE_P')
+                ->select(
+                    'INTE_IDIN as INTERVENTION_ID',
+                    'INTE_FECS as START_DATE',
+                    'INTE_FESD as END_DATE',
+                    'INTE_DEFA as FAILURES_INTERVENTION',
+                    'INTE_DEAC as ACTIVITIES_INTERVENTION'
+                )
+                ->where('INTE_IDIN', '=', $id_intervention)
+                ->where('INTE_NULI', '=', $line_number)
+                ->first();
+
+            // Verifica si el objeto esta vacio
+            if (!isset($intervention_details) && empty($intervention_details)) {
+                return $this->response_controller
+                    ->makeResponse(TRUE, 'ERR_INTERVENCIÓN_REG001: No se encontró la intervención', $intervention_details, 500);
+            }
+
+            $images_failures = DB::table('S002V01TIMAG_P')
+                ->select(
+                    'IMAG_LIIM as FAILURES_IMAGE_INTERVENTION'
+                )
+                ->where('IMAG_IDIN', '=', $id_intervention)
+                ->where('IMAG_TIIM', '=', 'Falla')
+                ->where('IMAG_ESTA', '=', 'Activo')
+                ->where('IMAG_NULI', '=', $line_number)
+                ->get();
+
+            $images_activities = DB::table('S002V01TIMAG_P')
+                ->select(
+                    'IMAG_LIIM as ACTIVITIES_IMAGE_INTERVENTION'
+                )
+                ->where('IMAG_IDIN', '=', $id_intervention)
+                ->where('IMAG_TIIM', '=', 'Actividad')
+                ->where('IMAG_ESTA', '=', 'Activo')
+                ->where('IMAG_NULI', '=', $line_number)
+                ->get();
+
+            // Obtiene los equipos que estuvieron presentes en la intervención
+            $workteams_on_intervention = DB::table('S002V01TEQMA')
+                ->select('S002V01TEQMA.EQMA_NOMB as WORKTEAM_NAME', 'S002V01TEQMA.EQMA_IDEQ as WORKTEAM_ID')
+                ->where('S002V01TEMIN.EMIN_IDIN', '=', $id_intervention)
+                ->where('S002V01TEMIN.EMIN_NULI', '=', $line_number)
+                ->join('S002V01TEMIN', 'S002V01TEQMA.EQMA_IDEQ', '=', 'S002V01TEMIN.EMIN_IDEM')
+                ->get();
+
+            // Obtiene los equipamientos que se utilizaron para la intervención
+            $equipment_on_intervention = DB::table('S002V01TMATE_P')
+                ->select('S002V01TMATE_P.MATE_NOMB as NAME', 'S002V01TMATE_P.MATE_LIIM as IMAGE')
+                ->where('S002V01TINMA.INMA_IDIN', '=', $id_intervention)
+                ->where('S002V01TINMA.INMA_NULI', '=', $line_number)
+                ->join('S002V01TINMA', 'S002V01TMATE_P.MATE_IDMA', '=', 'S002V01TINMA.INMA_IDMA')
+                ->get();
+
+            // Verifica si el objeto esta vacio
+            if (!isset($workteams_on_intervention[0]) && empty($workteams_on_intervention[0])) {
+                return $this->response_controller
+                    ->makeResponse(TRUE, 'ERR_EQUIPO_INTERVENCIÓN_REG002: No se encontraron datos', $intervention_details, 500);
+            }
+
+            // Obtiene a los empleados con su nombre
+            $employees_workteam = DB::table('S002V01TPEEM')
+                ->select(
+                    DB::raw('CONCAT(S002V01TUSUA_P.USUA_NOMB, " " , S002V01TUSUA_P.USUA_APPA, " ",  S002V01TUSUA_P.USUA_APMA) as NAME'),
+                    'S002V01TPEEM.PEEM_IDEM as WORKTEAM_ID'
+                )
+                ->where('S002V01TPEEM.PEEM_NULI', '=', $line_number)
+                ->where('S002V01TPERS.PERS_NULI', '=', $line_number)
+                ->where('S002V01TUSUA_P.USUA_NULI', '=', $line_number)
+                ->join('S002V01TPERS', 'S002V01TPEEM.PEEM_IDPE', '=', 'S002V01TPERS.PERS_IDPE')
+                ->join('S002V01TUSUA_P', 'S002V01TPERS.PERS_IDUS', '=', 'S002V01TUSUA_P.USUA_IDUS')
+                ->get();
+
+            // Verifica si el objeto esta vacio
+            if (!isset($employees_workteam[0]) && empty($employees_workteam[0])) {
+                return $this->response_controller
+                    ->makeResponse(TRUE, 'ERR_PERSONAL_EQUIPO_REG003: No se encontraron datos', $intervention_details, 500);
+            }
+
+            // Introduce el equipamiento utilizado, si es que hubo
+            if (!isset($equipment_on_intervention[0]) && empty($equipment_on_intervention[0])) {
+                $intervention_details->EQUIPMENT = "-";
+            } else {
+                $intervention_details->EQUIPMENT = $equipment_on_intervention;
+            }
+
+            // Introduce los empleados en su equipo de trabajo 
+            foreach ($workteams_on_intervention as $workteam) {
+                foreach ($employees_workteam as $employee) {
+                    if ($workteam->WORKTEAM_ID == $employee->WORKTEAM_ID) {
+                        $workteam->MEMBERS[] = $employee->NAME;
+                    }
+                }
+            }
+
+            $intervention_details->WORKTEAMS = $workteams_on_intervention;
+
+            // Verifica si el objeto esta vacio
+            if (!isset($images_activities[0]) && empty($images_activities[0])) {
+                $intervention_details->ACTIVITIES_IMAGE_INTERVENTION = "-";
+            } else {
+                foreach ($images_activities as $image) {
+                    $intervention_details->ACTIVITIES_IMAGE_INTERVENTION[] = $image->ACTIVITIES_IMAGE_INTERVENTION;
+                }
+            }
+
+            // Verifica si el objeto esta vacio
+            if (!isset($images_failures[0]) && empty($images_failures[0])) {
+                $intervention_details->FAILURES_IMAGE_INTERVENTION = "-";
+            } else {
+                foreach ($images_failures as $image) {
+                    $intervention_details->FAILURES_IMAGE_INTERVENTION[] = $image->FAILURES_IMAGE_INTERVENTION;
+                }
+            }
+
+            $intervention_details->START_DATE = Carbon::create($intervention_details->START_DATE)->format("d-m-Y h:i:s A");
+            $intervention_details->END_DATE = Carbon::create($intervention_details->END_DATE)->format("d-m-Y h:i:s A");
+
+            return $this->response_controller
+                ->makeResponse(FALSE, 'Consulta exitosa', $intervention_details);
+
+        } catch (Throwable $th) {
+            return $this->response_controller
+                ->makeResponse(TRUE, 'ERR_INTERVENCIÓN_REG004: Error inesperado', strtoupper($th->getMessage()), 500);
+        }
+    }
+
+    // Metodo para obtener datos de los contratos
+    public function getConsultOfContracts($line_number)
+    {
+        try {
+
+            $contracts = DB::table('S002V01TCONT')
+                ->select(
+                    'CONT_IDCO as CONTRACT_ID',
+                    'CONT_TIPO as CONTRACT_TYPE',
+                    'CONT_FEIN as START_DATE',
+                    'CONT_FEFI as END_DATE',
+                    'CONT_COST as CONTRACT_COST',
+                    'CONT_FERE as REGISTER_DATE',
+                    'CONT_USRE as REGISTERED_BY'
+                )
+                ->where('CONT_NULI', '=', $line_number)
+                ->get();
+
+            // Verifica si el objeto esta vacio
+            if (!isset($contracts[0]) && empty($contracts[0])) {
+                return $this->response_controller
+                    ->makeResponse(TRUE, 'ERR_CONTRATO_REG001: No se encontraron datos', $contracts, 500);
+            }
+
+            $users = DB::table('S002V01TUSUA_P')
+                ->select(
+                    'USUA_IDUS as USER_ID',
+                    DB::raw('CONCAT(USUA_NOMB, " " , USUA_APPA, " ",  USUA_APMA) as NAME')
+                )
+                ->where('USUA_NULI', '=', $line_number)
+                ->get();
+
+            // Verifica si el objeto esta vacio
+            if (!isset($users[0]) && empty($users[0])) {
+                return $this->response_controller
+                    ->makeResponse(TRUE, 'ERR_USUARIO_REG002: No se encontraron datos', $users, 500);
+            }
+
+            $employees = DB::table('S002V01TPERS')
+                ->select(
+                    'S002V01TPESU.PESU_RASO AS SUBCONTRATIST',
+                    DB::raw('CONCAT(S002V01TUSUA_P.USUA_NOMB, " " , S002V01TUSUA_P.USUA_APPA, " ",  S002V01TUSUA_P.USUA_APMA) as EMPLOYEE'),
+                    'S002V01TPERS.PERS_IDPS as TYPE_EMPLOYEE',
+                    'S002V01TPECO.PECO_IDCO as CONTRACT_ID'
+                )
+                ->where('S002V01TPERS.PERS_NULI', '=', $line_number)
+                ->where('S002V01TPESU.PESU_NULI', '=', $line_number)
+                ->where('S002V01TUSUA_P.USUA_NULI', '=', $line_number)
+                ->where('S002V01TPECO.PECO_NULI', '=', $line_number)
+                ->leftJoin('S002V01TPESU', 'S002V01TPERS.PERS_IDPS', '=', 'S002V01TPESU.PESU_IDPS')
+                ->join('S002V01TUSUA_P', 'S002V01TPERS.PERS_IDUS', '=', 'S002V01TUSUA_P.USUA_IDUS')
+                ->join('S002V01TPECO', 'S002V01TPERS.PERS_IDPE', '=', 'S002V01TPECO.PECO_IDPE')
+                ->get();
+
+            // Verifica si el objeto esta vacio
+            if (!isset($employees[0]) && empty($employees[0])) {
+                return $this->response_controller
+                    ->makeResponse(TRUE, 'ERR_PERSONAL_REG003: No se encontraron datos', $employees, 500);
+            }
+
+            // Itera los contratos para agregar a los dueños de los mismos y su duración
+            foreach ($contracts as $contract) {
+                $contract->DENOMINATION = [];
+                $contract->START_DATE = Carbon::create($contract->START_DATE)->format("d-m-Y");
+                $contract->END_DATE = Carbon::create($contract->END_DATE)->format("d-m-Y");
+                $contract->CONTRACT_COST = $this->encrypt_controller->encrypt($contract->CONTRACT_COST);
+
+                // Para establecer la duracion del contrato
+                $duration = Carbon::create($contract->START_DATE)->diff($contract->END_DATE);
+                $contract->DURATION = $this->resources_controller->durationDate($duration);
+
+                $contract->REGISTER_DATE = Carbon::create($contract->REGISTER_DATE)->format("d-m-Y h:i:s A");
+
+                foreach ($users as $user) {
+                    if ($contract->REGISTERED_BY == $user->USER_ID) {
+                        $contract->REGISTERED_BY = $user->NAME;
+                    }
+                }
+
+                // Ingresa el nombre del propietario del contrato, si fue por medio de un subcontratista, se coloca el nombre de este
+                foreach ($employees as $employee) {
+                    if ($employee->CONTRACT_ID == $contract->CONTRACT_ID) {
+                        if ($contract->CONTRACT_TYPE == "Subcontratista") {
+
+                            // Evita duplicados de subcontratista
+                            if (!in_array(trim($employee->SUBCONTRATIST), $contract->DENOMINATION)) {
+                                $contract->DENOMINATION[] = trim($employee->SUBCONTRATIST);
+                            }
+                        } else {
+                            $contract->DENOMINATION[] = $employee->EMPLOYEE;
+                        }
+                    }
+                }
+
+            }
+
+            return $this->response_controller
+                ->makeResponse(FALSE, 'Consulta exitosa', $contracts);
+
+        } catch (Throwable $th) {
+            return $this->response_controller
+                ->makeResponse(TRUE, 'ERR_INTERVENCIÓN_REG004: Error inesperado', strtoupper($th->getMessage()), 500);
+        }
+    }
+
+    // Metodo para obtener un contrato por el ID
+    public function getContractById($id_contract, $line_number)
+    {
+        try {
+            $contract = DB::table('S002V01TCONT')
+                ->select(
+                    'CONT_IDCO as CONTRACT_ID',
+                    'CONT_TIPO as CONTRACT_TYPE',
+                    'CONT_FEIN as START_DATE',
+                    'CONT_FEFI as END_DATE',
+                    'CONT_COST as CONTRACT_COST',
+                    'CONT_LIDO as CONTRACT_DOCUMENT',
+                    'CONT_FERE as REGISTER_DATE',
+                    'CONT_USRE as REGISTERED_BY'
+                )
+                ->where('CONT_IDCO', '=', $id_contract)
+                ->where('CONT_NULI', '=', $line_number)
+                ->first();
+
+            // Verifica si el objeto esta vacio
+            if (!isset($contract) && empty($contract)) {
+                return $this->response_controller
+                    ->makeResponse(TRUE, 'ERR_CONTRATO_REG001: No se encontró el contrato', $contract, 500);
+            }
+
+            $contract->START_DATE = Carbon::create($contract->START_DATE)->format("d-m-Y h:i:s A");
+            $contract->END_DATE = Carbon::create($contract->END_DATE)->format("d-m-Y h:i:s A");
+            $contract->REGISTER_DATE = Carbon::create($contract->REGISTER_DATE)->format("d-m-Y h:i:s A");
+            $contract->CONTRACT_COST = $this->encrypt_controller->encrypt($contract->CONTRACT_COST);
+            $contract->CONTRACT_DOCUMENT = $this->encrypt_controller->encrypt($contract->CONTRACT_DOCUMENT);
+
+            return $this->response_controller
+                ->makeResponse(FALSE, 'Consulta exitosa', $contract);
+
+        } catch (Throwable $th) {
+            return $this->response_controller
+                ->makeResponse(TRUE, 'ERR_INTERVENCIÓN_REG002: Error inesperado', strtoupper($th->getMessage()), 500);
+        }
+    }
+
+    // Metodo para guardar un contrato
+    public function storeContract(Request $request)
+    {
+        try {
+            $REGISTER_DATE = Carbon::now()->timezone('America/Mexico_City')->toDateTimeString();
+            $request['CONTRACT_COST'] = $this->encrypt_controller->decrypt($request->CONTRACT_COST);
+
+            $validator = Validator::make($request->all(), [
+                "CONTRACT_TYPE" => ['required'],
+                "DENOMINATION" => ['required', 'size:10'],
+                "START_DATE" => ['required', 'date'],
+                "END_DATE" => ['required', 'date'],
+                "CONTRACT_COST" => ['required'],
+                "DOCUMENT" => ['required'],
+                "REGISTERED_BY_USER" => ['required', 'digits:10'],
+                "LINE_NUMBER" => ['required', 'digits:1']
+            ]);
+
+            if ($validator->fails()) {
+                return $this->response_controller->makeResponse(
+                    TRUE,
+                    'ERR_CONTRATO_REG001: Uno o más errores encontrados',
+                    $this->response_controller->makeErrors($validator->errors()->messages()),
+                    400
+                );
+            }
+
+            $user_register = DB::table('S002V01TUSUA_P')
+                ->select('USUA_IDUS as ID_USER')
+                ->where('USUA_IDUS', '=', $request->REGISTERED_BY_USER)
+                    // ->where('USUA_NULI', '=', '01')
+                ->first();
+
+            // Verifica si el objeto esta vacio
+            if (!isset($user_register) && empty($user_register)) {
+                return $this->response_controller
+                    ->makeResponse(TRUE, "ERR_USUARIO_REG002: Tu usuario no es válido para registrar contratos", [], 500);
+            }
+
+            DB::beginTransaction(); # Para impedir que las actualizaciones queden a incompletas
+
+            // Busca si el empleado existe en la base de datos
+            $employee_exist = DB::table('S002V01TPERS')
+                ->select("PERS_IDPE")
+                ->where('PERS_IDPE', '=', $request->DENOMINATION)
+                    // ->where('PERS_NULI', '=', '01')
+                ->first();
+
+            // Verifica si el objeto esta vacio
+            if (!isset($employee_exist) && empty($employee_exist)) {
+                return $this->response_controller
+                    ->makeResponse(TRUE, 'ERR_PERSONAL_REG003: No se encontró al empleado', [], 500);
+            }
+
+            // Para la creación del contrato y guardar su enlace
+            $doc = $request->DOCUMENT;
+
+            //$doc = $this->encrypt_controller->decrypt($request->DOCUMENT); #Para cuando este en producción, desencriptar
+            // Se obtiene el nombre del archivo con su extensión
+            $completeFileName = $doc->getClientOriginalName();
+
+            // Se obtiene únicamente el nombre
+            $fileNameOnly = pathinfo($completeFileName, PATHINFO_FILENAME);
+
+            // Se obtiene la extensión del archivo
+            $extension = $doc->getClientOriginalExtension();
+
+            // Se quitan los espacios y se concatena datos para ser guardado
+            $final_part_name_document = str_replace(' ', '_', $fileNameOnly) . '.' . $extension;
+
+            // Se agrega la fecha actual con el formato de la nomenclatura de documentos
+            $DATE_TO_DOCUMENT = Carbon::now()->timezone('America/Mexico_City')->format("ymd");
+
+            // Verifica que el nombre del documento no sea el mismo de la generada automaticamente
+            if (substr($final_part_name_document, 0, 8) == ('01-GPRS-') && strlen($final_part_name_document) > 28) {
+                $final_part_name_document = substr($final_part_name_document, 28);
+            }
+
+            // Se crea el nombre del documento
+            $name_document = '01-GPRS-CO-' . $DATE_TO_DOCUMENT . '-000001' . '=01=' . $final_part_name_document;
+
+            // Verifica si el nombre de documento no existe aun
+            $repeated_names = $this->documents_controller->getDocumentsWithSameCodificationStructureName($name_document, 'pdf');
+            if ($repeated_names != null) {
+                if ($this->documents_controller->sameDocumentsPdfOnRequest($doc, $repeated_names) != null) {
+                    return $this->response_controller
+                        ->makeResponse(TRUE, 'ERR_CONTRATO_REG004: Este contrato ya ha sido registrado', [], 500);
+                }
+
+                foreach ($repeated_names as $name) {
+                    if ($name == $name_document) {
+                        return $this->response_controller
+                            ->makeResponse(TRUE, 'ERR_CONTRATO_REG005: Este nombre ya ha sido ocupado el dia de hoy', [], 500);
+                    }
+                }
+            }
+
+            // El contrato es guardado en el storage
+            $doc->storeAs('public/pdf_documents', $name_document);
+
+            $insert_contract = DB::table('S002V01TCONT')
+                ->insert([
+                    "CONT_TIPO" => $request->CONTRACT_TYPE,
+                    "CONT_FEIN" => Carbon::create($request->START_DATE)->format('Y-m-d H:i:s'),
+                    "CONT_FEFI" => Carbon::create($request->END_DATE)->format('Y-m-d H:i:s'),
+                    "CONT_COST" => $request->CONTRACT_COST,
+                    "CONT_NULI" => $request->LINE_NUMBER,
+                    "CONT_LIDO" => $name_document,
+                    "CONT_USRE" => $request->REGISTERED_BY_USER,
+                    "CONT_FERE" => $REGISTER_DATE,
+                    "CONT_FEAR" => DB::raw('CURRENT_TIMESTAMP')
+                ]);
+
+
+            if (!$insert_contract) {
+                return $this->response_controller
+                    ->makeResponse(TRUE, 'ERR_CONTRATO_REG006: Algo salió mal, error registrando el contrato', [], 500);
+            }
+
+            // Busca el id del contrato insertado
+            $contract_id = DB::table('S002V01TCONT')
+                ->select("CONT_IDCO as CONTRACT_ID")
+                ->where("CONT_TIPO", '=', $request->CONTRACT_TYPE)
+                ->where("CONT_FERE", '=', $REGISTER_DATE)
+                ->where("CONT_COST", '=', $request->CONTRACT_COST)
+                ->where("CONT_USRE", '=', $request->REGISTERED_BY_USER)
+                ->where("CONT_LIDO", '=', $name_document)
+                ->where('CONT_NULI', '=', $request->LINE_NUMBER)
+                ->first();
+            $contract_id = $contract_id->CONTRACT_ID;
+
+            // Verifica si el objeto esta vacio
+            if (!isset($contract_id) && empty($contract_id)) {
+                DB::rollBack(); # Si no se logra insertar el contrato con empleado, se revierten los cambios previos
+                return $this->response_controller
+                    ->makeResponse(TRUE, 'ERR_CONTRATO_REG007: Algo salió mal, error buscando el contrato registrado', [], 500);
+            }
+
+            $insert_contract_with_employee = DB::table('S002V01TPECO')
+                ->insert([
+                    "PECO_IDPE" => $request->DENOMINATION,
+                    "PECO_IDCO" => $contract_id,
+                    "PECO_USRE" => $request->REGISTERED_BY_USER,
+                    "PECO_NULI" => $request->LINE_NUMBER,
+                    "PECO_FERE" => $REGISTER_DATE,
+                    "PECO_FEAR" => DB::raw('CURRENT_TIMESTAMP')
+                ]);
+
+            if (!$insert_contract_with_employee) {
+                DB::rollBack(); # Si no se logra insertar el contrato con empleado, se revierten los cambios previos
+                return $this->response_controller
+                    ->makeResponse(TRUE, 'ERR_CONTRATO_PERSONAL_REG008: Algo salió mal, error registrando el contrato con el empleado', [], 500);
+            }
+
+            DB::commit(); # Para guardar los cambios en la base de datos
+            return $this->response_controller->makeResponse(FALSE, 'Registro exitoso', 200);
+
+
+        } catch (Throwable $th) {
+            return $this->response_controller
+                ->makeResponse(TRUE, 'ERR_CONTRATO_REG009: Error inesperado', strtoupper($th->getMessage()), 500);
+        }
+    }
+
+    // Metodo para obtener un contrato por el ID
+    public function getAllContracts($line_number)
+    {
+        try {
+            $contracts = DB::table('S002V01TCONT')
+                ->select(
+                    'CONT_IDCO as CONTRACT_ID',
+                    'CONT_TIPO as CONTRACT_TYPE',
+                    'CONT_FEIN as START_DATE',
+                    'CONT_FEFI as END_DATE',
+                    'CONT_COST as CONTRACT_COST',
+                    'CONT_LIDO as CONTRACT_DOCUMENT',
+                    'CONT_FERE as REGISTER_DATE',
+                    'CONT_USRE as REGISTERED_BY'
+                )
+                ->where('CONT_NULI', '=', $line_number)
+                ->get();
+
+            // Verifica si el objeto esta vacio
+            if (!isset($contracts[0]) && empty($contracts[0])) {
+                return $this->response_controller
+                    ->makeResponse(TRUE, 'ERR_CONTRATO_REG001: No se encontró el contrato', $contracts, 500);
+            }
+
+            foreach ($contracts as $contract) {
+                $contract->START_DATE = Carbon::create($contract->START_DATE)->format("d-m-Y h:i:s A");
+                $contract->END_DATE = Carbon::create($contract->END_DATE)->format("d-m-Y h:i:s A");
+                $contract->REGISTER_DATE = Carbon::create($contract->REGISTER_DATE)->format("d-m-Y h:i:s A");
+                $contract->CONTRACT_COST = $this->encrypt_controller->encrypt($contract->CONTRACT_COST);
+                $contract->CONTRACT_DOCUMENT = $this->encrypt_controller->encrypt($contract->CONTRACT_DOCUMENT);
+            }
+
+            return $this->response_controller
+                ->makeResponse(FALSE, 'Consulta exitosa', $contracts);
+
+        } catch (Throwable $th) {
+            return $this->response_controller
+                ->makeResponse(TRUE, 'ERR_INTERVENCIÓN_REG002: Error inesperado', strtoupper($th->getMessage()), 500);
+        }
+    }
+
+}
+
+/*
+DATOS OBLIGATORIOS
+$REGISTER_DATE = Carbon::now()->timezone('America/Mexico_City')->toDateTimeString();
+$UPDATE_DATE = Carbon::now()->timezone('America/Mexico_City')->toDateTimeString();
+"_ESTA" => $request->STATUS,
+"_USRE" => $request->REGISTER_USER,
+"_USMO" => $request->MODIFIED_USER,
+"_FERE" => $REGISTER_DATE,
+"_FEMO" => $UPDATE_DATE,
+"_FEAR" => DB::raw('CURRENT_TIMESTAMP')
+*/

+ 73 - 0
sistema-mantenimiento-back/app/Http/Controllers/ResourcesController.php

@@ -0,0 +1,73 @@
+<?php
+
+namespace App\Http\Controllers;
+
+use Illuminate\Http\Request;
+
+class ResourcesController extends Controller
+{
+    public function formatSecuence($cont, $length)
+    {
+        $longigud = strlen($cont);
+        $aumentar = $length - $longigud;
+        $contador = '';
+        for ($i = 0; $i < $aumentar; $i++) {
+            $contador .= '0';
+        }
+        $contador .= $cont === 0 ? 1 : $cont;
+        return $contador;
+    }
+
+    // Establece la duracion entre dos fechas
+    public function durationDate($date)
+    {
+        if ($date->y > 0 && $date->m > 0 && $date->d > 0) {
+
+            if ($date->y > 1) {
+                $duration = $date->y . " años, ";
+            } else {
+                $duration = $date->y . " año, ";
+            }
+
+            if ($date->m > 1) {
+                $duration .= $date->m . " meses, ";
+            } else {
+                $duration .= $date->m . " mes, ";
+            }
+
+            if ($date->d > 1) {
+                $duration .= $date->d . " dias";
+            } else {
+                $duration .= $date->d . " dia";
+            }
+
+        } else if ($date->m > 0 && $date->d > 0) {
+
+            if ($date->m > 1) {
+                $duration = $date->m . " meses, ";
+            } else {
+                $duration = $date->m . " mes, ";
+            }
+
+            if ($date->d > 1) {
+                $duration .= $date->d . " dias";
+            } else {
+                $duration .= $date->d . " dia";
+            }
+
+        } else if ($date->d > 0) {
+
+            if ($date->d > 1) {
+                $duration = $date->d . " dias";
+            } else {
+                $duration = $date->d . " dia";
+            }
+
+        } else {
+            $duration = "Menos de 1 dia";
+        }
+
+        return $duration;
+    }
+
+}

+ 1078 - 0
sistema-mantenimiento-back/app/Http/Controllers/SubcontractController.php

@@ -0,0 +1,1078 @@
+<?php
+/*
+Nombre del programador:         Cordourier Rojas Mathew
+Ultima fecha de modificación:   [ 03 / Marzo / 2023 ]
+Descripción:                    Controlador del submodulo Subcontrataciones. Perteneciente al Módulo 13 - Gestion del Personal de Mantenimiento
+*/
+
+namespace App\Http\Controllers;
+
+use Carbon\Carbon;
+use Illuminate\Http\Request;
+use Illuminate\Support\Facades\DB;
+use Illuminate\Support\Facades\Storage;
+use Illuminate\Support\Facades\Validator;
+use PhpOffice\PhpSpreadsheet\IOFactory;
+use PhpOffice\PhpSpreadsheet\Spreadsheet;
+use stdClass;
+use Throwable;
+
+class SubcontractController extends Controller
+{
+    private $response_controller;
+    private $encrypt_controller;
+    private $documents_controller;
+    public function __construct()
+    {
+        $this->response_controller = new ResponseController();
+        $this->encrypt_controller = new EncryptionController();
+        $this->documents_controller = new DocumentsController();
+    }
+
+    // Metodo de consulta de datos especificos por subcontratistas
+    public function getConsultOfSubcontratists($line_number)
+    {
+        try {
+
+            $subcontratists = DB::table('S002V01TPESU')
+                ->select('PESU_IDPS as ID_SUBCONTRATIST', DB::raw('CONCAT(PESU_RASO, " " , COALESCE(PESU_REFI, "")) AS NAME'), 'PESU_FERE AS REGISTER_DATE', 'PESU_USRE AS REGISTERED_BY_USER')
+                ->where('PESU_NULI', '=', $line_number)
+                ->get();
+
+            // Verifica que el objeto no este vacio
+            if (!isset($subcontratists[0]) && empty($subcontratists[0])) {
+                return $this->response_controller
+                    ->makeResponse(TRUE, 'ERR_SUBCONTRATISTA_REG001: No se encontraron datos', $subcontratists, 500);
+            }
+
+            $users_register_name = DB::table('S002V01TUSUA_P')
+                ->select('USUA_IDUS AS USERID', DB::raw('CONCAT(USUA_NOMB, " " , USUA_APPA, " ", USUA_APMA) AS NAME'))
+                ->where('USUA_NULI', '=', $line_number)
+                ->get();
+
+            // Verifica si el objeto esta vacio
+            if (!isset($users_register_name[0]) && empty($users_register_name[0])) {
+                return $this->response_controller
+                    ->makeResponse(TRUE, 'ERR_USUARIO_REG002: No se encontraron datos', $users_register_name, 500);
+            }
+
+            $interventions = DB::table('S002V01TPESU')
+                ->select('S002V01TPERS.PERS_IDPS as SUBCONTRATIST_ID', 'S002V01TINTE_P.INTE_IDIN as INTERVENTION_ID')
+                ->where('S002V01TPESU.PESU_NULI', '=', $line_number)
+                ->where('S002V01TPERS.PERS_NULI', '=', $line_number)
+                ->where('S002V01TPEEM.PEEM_NULI', '=', $line_number)
+                ->where('S002V01TEQMA.EQMA_NULI', '=', $line_number)
+                ->where('S002V01TEMIN.EMIN_NULI', '=', $line_number)
+                ->where('S002V01TINTE_P.INTE_NULI', '=', $line_number)
+                ->groupBy('S002V01TPESU.PESU_IDPS', 'S002V01TINTE_P.INTE_IDIN')
+                ->join('S002V01TPERS', 'S002V01TPESU.PESU_IDPS', '=', 'S002V01TPERS.PERS_IDPS')
+                ->join('S002V01TPEEM', 'S002V01TPERS.PERS_IDPE', '=', 'S002V01TPEEM.PEEM_IDPE')
+                ->join('S002V01TEQMA', 'S002V01TPEEM.PEEM_IDEM', '=', 'S002V01TEQMA.EQMA_IDEQ')
+                ->join('S002V01TEMIN', 'S002V01TEQMA.EQMA_IDEQ', '=', 'S002V01TEMIN.EMIN_IDEM')
+                ->join('S002V01TINTE_P', 'S002V01TEMIN.EMIN_IDIN', '=', 'S002V01TINTE_P.INTE_IDIN')
+                ->get();
+
+            // Verifica si el objeto esta vacio
+            if (!isset($interventions[0]) && empty($interventions[0])) {
+                return $this->response_controller
+                    ->makeResponse(TRUE, 'ERR_EQUIPO_INTERVENCIÓN_REG003: No se encontraron datos', $interventions, 500);
+            }
+
+            // Se iteran los subcontratistas encontrados
+            foreach ($subcontratists as $subcontratist) {
+                $subcontratist->REGISTER_DATE = Carbon::create($subcontratist->REGISTER_DATE)->format("d-m-Y h:i:s A");
+
+                $subcontratist->NAME = trim($subcontratist->NAME);
+
+                // Se adjunta el nombre completo del usuario que lo registro
+                foreach ($users_register_name as $user_register) {
+                    if ($subcontratist->REGISTERED_BY_USER == $user_register->USERID) {
+                        $subcontratist->REGISTERED_BY_USER = $user_register->NAME;
+                    }
+                }
+
+                // Se adjunta el numero de intervenciones en las que participo el subcontratista
+                $interventions_count = 0;
+                foreach ($interventions as $intervention) {
+                    if ($subcontratist->ID_SUBCONTRATIST == $intervention->SUBCONTRATIST_ID) {
+                        $interventions_count++;
+                    }
+                }
+                $subcontratist->INTERVENTIONS_COUNT = $interventions_count;
+
+            }
+
+            return $this->response_controller->makeResponse(FALSE, 'Consulta exitosa', $subcontratists);
+
+        } catch (Throwable $e) {
+            return $this->response_controller
+                ->makeResponse(TRUE, 'ERR_SUBCONTRATISTA_REG004: Error inesperado', strtoupper($e->getMessage()), 500);
+        }
+    }
+
+    // Metodo para la eliminación lógica de un subcontratista
+    public function updateToInactiveStatus(Request $request, $id_subcontratist)
+    {
+        try {
+
+            $validator = Validator::make($request->all(), [
+                "UPDATED_BY_USER" => ['required', 'digits:10']
+            ]);
+
+            if ($validator->fails()) {
+                return $this->response_controller->makeResponse(
+                    TRUE,
+                    'ERR_SUBCONTRATISTA_REG001: Uno o más errores encontrados',
+                    $this->response_controller->makeErrors($validator->errors()->messages()),
+                    400
+                );
+            }
+
+            $user_register = DB::table('S002V01TUSUA_P')
+                ->select('USUA_IDUS as ID_USER')
+                ->where('USUA_IDUS', '=', $request->UPDATED_BY_USER)
+                ->where('USUA_NULI', '=', $request->LINE_NUMBER)
+                ->first();
+
+            // Verifica si el objeto está vacio
+            if (!isset($user_register) && empty($user_register)) {
+                return $this->response_controller
+                    ->makeResponse(TRUE, "ERR_USUARIO_REG002: Tu usuario no es válido para eliminar subcontratistas", [], 500);
+            }
+
+            // Busca si el subcontratista existe
+            $search_subcontratist = DB::table("S002V01TPESU")
+                ->select("PESU_IDPS")
+                ->where("PESU_IDPS", "=", $id_subcontratist)
+                ->where('PESU_NULI', '=', $request->LINE_NUMBER)
+                ->first();
+
+            // Verifica si el objeto está vacio
+            if (!isset($search_subcontratist) && empty($search_subcontratist)) {
+                return $this->response_controller
+                    ->makeResponse(TRUE, "ERR_SUBCONTRATISTA_REG003: No se encontró al subcontratista", $search_subcontratist, 500);
+            }
+
+            // Obtiene las intervenciones en las que está ocupado el subcontratista, si hay alguna
+            $search_subcontratist = DB::table("S002V01TPERS")
+                ->select("S002V01TINTE_P.INTE_NOMB")
+                ->where("S002V01TPERS.PERS_IDPS", "=", $id_subcontratist)
+                ->where("S002V01TINTE_P.INTE_ESTA", "=", "Activo")
+                ->where("S002V01TEMIN.EMIN_ESTA", "=", "Activo")
+                ->where('S002V01TPERS.PERS_NULI', '=', $request->LINE_NUMBER)
+                ->where("S002V01TPEEM.PEEM_ESTA", "=", $request->LINE_NUMBER)
+                ->where("S002V01TEQMA.EQMA_ESTA", "=", $request->LINE_NUMBER)
+                ->where("S002V01TEMIN.EMIN_ESTA", "=", $request->LINE_NUMBER)
+                ->where("S002V01TINTE_P.INTE_ESTA", "=", $request->LINE_NUMBER)
+                ->groupBy('S002V01TINTE_P.INTE_NOMB')
+                ->join("S002V01TPEEM", "S002V01TPERS.PERS_IDPE", "=", "S002V01TPEEM.PEEM_IDPE")
+                ->join("S002V01TEQMA", "S002V01TPEEM.PEEM_IDEM", "=", "S002V01TEQMA.EQMA_IDEQ")
+                ->join("S002V01TEMIN", "S002V01TEQMA.EQMA_IDEQ", "=", "S002V01TEMIN.EMIN_IDEM")
+                ->join("S002V01TINTE_P", "S002V01TEMIN.EMIN_IDIN", "=", "S002V01TINTE_P.INTE_IDIN")
+                ->get();
+
+            // Verifica si el objeto contiene algo
+            if (isset($search_subcontratist[0]) && !empty($search_subcontratist[0])) {
+                return $this->response_controller
+                    ->makeResponse(TRUE, "ERR_SUBCONTRATISTA_REG004: Subcontratista ocupado con intervenciones", $search_subcontratist, 500);
+            } else {
+
+                $UPDATE_DATE = Carbon::now()->timezone('America/Mexico_City')->toDateTimeString();
+
+                $delete_subcontratist = DB::table('S002V01TPESU')
+                    ->where('PESU_IDPS', $id_subcontratist)
+                    ->where('PESU_NULI', '=', $request->LINE_NUMBER)
+                    ->update([
+                        "PESU_ESTA" => "Inactivo",
+                        "PESU_USMO" => trim($request->UPDATED_BY_USER),
+                        "PESU_FEMO" => $UPDATE_DATE,
+                        "PESU_FEAR" => DB::raw('CURRENT_TIMESTAMP')
+                    ]);
+
+                // Verifica si el subcontratista se inhabilitó correctamente
+                if ($delete_subcontratist) {
+                    $response = $this->response_controller->makeResponse(FALSE, "Eliminación exitosa");
+                } else {
+                    $response = $this->response_controller
+                        ->makeResponse(TRUE, 'ERR_SUBCONTRATISTA_REG005: Algo salió mal, error eliminando al subcontratista', [], 500);
+                }
+            }
+
+            return $response;
+
+        } catch (Throwable $th) {
+            return $this->response_controller
+                ->makeResponse(TRUE, 'ERR_SUBCONTRATISTA_REG006: Error inesperado', strtoupper($th->getMessage()), 500);
+        }
+    }
+
+    // Metodo para guardar un nuevo subcontratista
+    public function storeSubcontratist(Request $request)
+    {
+
+        $REGISTER_DATE = Carbon::now()->timezone('America/Mexico_City')->toDateTimeString();
+        $request['TELEPHONE1'] = $this->encrypt_controller->decrypt($request->TELEPHONE1);
+        $request['TELEPHONE2'] = $this->encrypt_controller->decrypt($request->TELEPHONE2);
+        $request['EMAIL'] = $this->encrypt_controller->decrypt($request->EMAIL);
+        $request['RFC'] = $this->encrypt_controller->decrypt($request->RFC);
+
+        try {
+
+            $validator = Validator::make($request->all(), [
+                "RFC" => ['required', 'max:13'],
+                "SOCIAL_REASON" => ['required', 'max:150'],
+                "TAX_REFERENCE" => ['max:15'],
+                "CONTRACT_TYPE" => ['required'],
+                "EMAIL" => ['required', 'email', 'max:150'],
+                "FOREIGNER" => ['required'],
+                "TAX" => ['required', 'max:13'],
+                "STREET" => ['required', 'max:50'],
+                "EXTERIOR_NUMBER" => ['required', 'digits_between:1,10'],
+                "COLONIA" => ['required', 'max:50'],
+                "CITY" => ['required', 'max:50'],
+                "POSTAL_CODE" => ['required', 'digits:5'],
+                "FEDERAL_ENTITY" => ['required', 'max:50'],
+                "COUNTRY_ID" => ['required'],
+                "TELEPHONE1" => ['required', 'digits_between:7,11'],
+                "LADA1" => ['required', 'digits_between:1,3'],
+                "REGISTERED_BY_USER" => ['required', 'digits:10'],
+                "INTERIOR_NUMBER" => ['digits_between:1,10'],
+                "TELEPHONE2" => ['digits_between:7,11'],
+                "LADA2" => ['digits_between:1,3'],
+                "LINE_NUMBER" => ['required', 'digits:1']
+            ]);
+
+            if ($validator->fails()) {
+                return $this->response_controller->makeResponse(
+                    TRUE,
+                    'ERR_SUBCONTRATISTA_REG001: Uno o más errores encontrados',
+                    $this->response_controller->makeErrors($validator->errors()->messages()),
+                    400
+                );
+            }
+
+            // Busca si hay duplicados con los subcontratistas ya guardados
+            $subcontratists = DB::table('S002V01TPESU')
+                ->select("PESU_RASO as SOCIAL_REASON", "PESU_XRFC as RFC", "PESU_CORR as EMAIL")
+                ->where('PESU_RASO', '=', $request->SOCIAL_REASON)
+                ->orWhere('PESU_XRFC', '=', $request->RFC)
+                ->orWhere('PESU_CORR', '=', $request->EMAIL)
+                ->get();
+
+            // Valida que los campos no esten repetidos con los que ya se encuentran en la base de datos
+            if (isset($subcontratists[0]) && !empty($subcontratists[0])) {
+                $duplicated_data = [];
+                foreach ($subcontratists as $subcontratist) {
+                    if ($subcontratist->SOCIAL_REASON == $request->SOCIAL_REASON) {
+                        $duplicated_data[] = "Razon Social: " . $subcontratist->SOCIAL_REASON;
+                    }
+
+                    if ($subcontratist->RFC == $request->RFC) {
+                        $duplicated_data[] = "RFC: " . $subcontratist->RFC;
+                    }
+
+                    if ($subcontratist->EMAIL == $request->EMAIL) {
+                        $duplicated_data[] = "Email: " . $subcontratist->EMAIL;
+                    }
+                }
+
+                if (isset($duplicated_data[0]) && !empty($duplicated_data[0])) {
+                    return $this->response_controller->makeResponse(TRUE, 'ERR_SUBCONTRATISTA_REG002: Datos duplicados', $duplicated_data, 500);
+                }
+            }
+
+            $user_register = DB::table('S002V01TUSUA_P')
+                ->select('USUA_IDUS as ID_USER')
+                ->where('USUA_IDUS', '=', $request->REGISTERED_BY_USER)
+                ->where('USUA_NULI', '=', $request->LINE_NUMBER)
+                ->first();
+
+            // Verifica si el objeto esta vacio
+            if (!isset($user_register) && empty($user_register)) {
+                return $this->response_controller
+                    ->makeResponse(TRUE, "ERR_USUARIO_REG003: Tu usuario no es válido para registrar subcontratistas", [], 500);
+            }
+
+            $insert_subcontratist = DB::table('S002V01TPESU')->insert([
+                "PESU_NULI" => $request->LINE_NUMBER,
+                "PESU_RASO" => trim($request->SOCIAL_REASON),
+                "PESU_REFI" => trim($request->TAX_REFERENCE),
+                "PESU_XRFC" => trim($request->RFC),
+                "PESU_TIPO" => trim($request->CONTRACT_TYPE),
+                "PESU_CORR" => trim($request->EMAIL),
+                "PESU_EXTR" => trim($request->FOREIGNER),
+                "PESU_TAID" => trim($request->TAX),
+                "PESU_CALL" => trim($request->STREET),
+                "PESU_NOEX" => trim($request->EXTERIOR_NUMBER),
+                "PESU_NOIN" => trim($request->INTERIOR_NUMBER),
+                "PESU_COLO" => trim($request->COLONIA),
+                "PESU_CIUD" => trim($request->CITY),
+                "PESU_COPO" => trim($request->POSTAL_CODE),
+                "PESU_ENFE" => trim($request->FEDERAL_ENTITY),
+                "PESU_IDPA" => trim($request->COUNTRY_ID),
+                "PESU_TEL1" => trim($request->TELEPHONE1),
+                "PESU_LAT1" => trim($request->LADA1),
+                "PESU_TEL2" => trim($request->TELEPHONE2),
+                "PESU_LAT2" => trim($request->LADA2),
+                "PESU_ESTA" => "Activo",
+                "PESU_USRE" => trim($request->REGISTERED_BY_USER),
+                "PESU_FERE" => $REGISTER_DATE,
+                "PESU_FEAR" => DB::raw('CURRENT_TIMESTAMP')
+            ]);
+
+            // Verifica que se haya insertado correctamente al subcontratista
+            if ($insert_subcontratist) {
+                $response = $this->response_controller->makeResponse(FALSE, 'Guardado exitoso');
+            } else {
+                $response = $this->response_controller->makeResponse(TRUE, 'ERR_SUBCONTRATISTA_REG004: Algo salió mal, error registrando al subcontratista', [], 500);
+            }
+
+            return $response;
+
+
+        } catch (Throwable $th) {
+            return $this->response_controller
+                ->makeResponse(TRUE, 'ERR_SUBCONTRATISTA_REG005: Error inesperado', strtoupper($th->getMessage()), 500);
+        }
+
+    }
+
+    // Metodo para obtener datos de un subcontratista
+    public function getSubcontratistById($id_subcontratist, $line_number)
+    {
+        try {
+
+            $subcontratists_info = DB::table('S002V01TPESU')
+                ->select(
+                    'PESU_IDPS as ID_SUBCONTRATIST',
+                    'S002V01TPESU.PESU_RASO as SOCIAL_REASON',
+                    'S002V01TPESU.PESU_REFI as TAX_REFERENCE',
+                    'S002V01TPESU.PESU_XRFC as RFC',
+                    'S002V01TPESU.PESU_TIPO as CONTRACT_TYPE',
+                    'S002V01TPESU.PESU_CORR as EMAIL',
+                    'S002V01TPESU.PESU_EXTR as FOREIGNER',
+                    'S002V01TPESU.PESU_TAID as TAX',
+                    'S002V01TPESU.PESU_CALL as STREET',
+                    'S002V01TPESU.PESU_NOEX as EXTERIOR_NUMBER',
+                    'S002V01TPESU.PESU_NOIN as INTERIOR_NUMBER',
+                    'S002V01TPESU.PESU_COLO as COLONIA',
+                    'S002V01TPESU.PESU_CIUD as CITY',
+                    'S002V01TPESU.PESU_COPO as POSTAL_CODE',
+                    'S002V01TPESU.PESU_ENFE as FEDERAL_ENTITY',
+                    'S002V01TPAIS.PAIS_NOMB as COUNTRY',
+                    'S002V01TPESU.PESU_TEL1 as TELEPHONE1',
+                    'S002V01TPESU.PESU_LAT1 as LADA1',
+                    'S002V01TPESU.PESU_TEL2 as TELEPHONE2',
+                    'S002V01TPESU.PESU_LAT2 as LADA2',
+                    'S002V01TPESU.PESU_ESTA as STATUS'
+                )
+                ->where('S002V01TPESU.PESU_IDPS', '=', $id_subcontratist)
+                ->where('S002V01TPESU.PESU_NULI', '=', $line_number)
+                ->join('S002V01TPAIS', 'S002V01TPESU.PESU_IDPA', '=', 'S002V01TPAIS.PAIS_IDPA')
+                ->first();
+
+            // Verifica si el objeto esta vacio
+            if (!isset($subcontratists_info) && empty($subcontratists_info)) {
+                return $this->response_controller
+                    ->makeResponse(TRUE, 'ERR_SUBCONTRATISTA_REG001: No se encontró al subcontratista', $subcontratists_info, 500);
+            }
+
+            $subcontratists_info->RFC = $this->encrypt_controller->encrypt($subcontratists_info->RFC);
+            $subcontratists_info->TELEPHONE1 = $this->encrypt_controller->encrypt($subcontratists_info->TELEPHONE1);
+            $subcontratists_info->TELEPHONE2 = $this->encrypt_controller->encrypt($subcontratists_info->TELEPHONE2);
+            $subcontratists_info->EMAIL = $this->encrypt_controller->encrypt($subcontratists_info->EMAIL);
+
+            return $this->response_controller->makeResponse(FALSE, 'Consulta exitosa', $subcontratists_info);
+
+        } catch (Throwable $e) {
+            return $this->response_controller
+                ->makeResponse(TRUE, 'ERR_SUBCONTRATISTA_REG002: Error inesperado', strtoupper($e->getMessage()), 500);
+        }
+    }
+
+    // Metodo para actualizar un subcontratista
+    public function updateSubcontratist(Request $request, $id_subcontratist)
+    {
+        $UPDATE_DATE = Carbon::now()->timezone('America/Mexico_City')->toDateTimeString();
+        $request['TELEPHONE1'] = $this->encrypt_controller->decrypt($request->TELEPHONE1);
+        $request['TELEPHONE2'] = $this->encrypt_controller->decrypt($request->TELEPHONE2);
+        $request['EMAIL'] = $this->encrypt_controller->decrypt($request->EMAIL);
+        $request['RFC'] = $this->encrypt_controller->decrypt($request->RFC);
+
+        try {
+            $validator = Validator::make($request->all(), [
+                "RFC" => ['required', 'max:13'],
+                "SOCIAL_REASON" => ['required', 'max:150'],
+                "TAX_REFERENCE" => ['max:15'],
+                "CONTRACT_TYPE" => ['required'],
+                "EMAIL" => ['required', 'email', 'max:150'],
+                "FOREIGNER" => ['required'],
+                "TAX" => ['required', 'max:13'],
+                "STREET" => ['required', 'max:50'],
+                "EXTERIOR_NUMBER" => ['required', 'digits_between:1,10'],
+                "COLONIA" => ['required', 'max:50'],
+                "CITY" => ['required', 'max:50'],
+                "POSTAL_CODE" => ['required', 'digits:5'],
+                "FEDERAL_ENTITY" => ['required', 'max:50'],
+                "COUNTRY_ID" => ['required'],
+                "TELEPHONE1" => ['required', 'digits_between:7,11'],
+                "LADA1" => ['required', 'digits_between:1,3'],
+                "UPDATED_BY_USER" => ['required', 'digits:10'],
+                "INTERIOR_NUMBER" => ['digits_between:1,10'],
+                "TELEPHONE2" => ['digits_between:7,11'],
+                "LADA2" => ['digits_between:1,3'],
+                "LINE_NUMBER" => ['required', 'digits:1']
+            ]);
+
+            if ($validator->fails()) {
+                return $this->response_controller->makeResponse(
+                    TRUE,
+                    'ERR_SUBCONTRATISTA_REG001: Uno o más errores encontrados',
+                    $this->response_controller->makeErrors($validator->errors()->messages()),
+                    400
+                );
+            }
+
+            // Busca si el subcontratista existe
+            $search_subcontratist = DB::table("S002V01TPESU")
+                ->select("PESU_IDPS")
+                ->where("PESU_IDPS", "=", $id_subcontratist)
+                ->where('PESU_NULI', '=', $request->LINE_NUMBER)
+                ->first();
+
+            // Verifica si el objeto esta vacio
+            if (!isset($search_subcontratist) && empty($search_subcontratist)) {
+                return $this->response_controller
+                    ->makeResponse(TRUE, "ERR_SUBCONTRATISTA_REG002: No se encontró al subcontratista", $search_subcontratist, 500);
+            }
+
+            // Busca los subcontratistas que tengan datos iguales a los ingresados
+            $subcontratists = DB::table('S002V01TPESU')
+                ->select("PESU_RASO as SOCIAL_REASON", "PESU_XRFC as RFC", "PESU_CORR as EMAIL")
+                ->where('PESU_IDPS', '<>', $id_subcontratist)
+                ->where('PESU_NULI', '=', $request->LINE_NUMBER)
+                ->get();
+
+            // Valida que los campos no sean repetidos con los que ya se encuentran en la base de datos
+            foreach ($subcontratists as $subcontratist) {
+                if (isset($subcontratists[0]) && !empty($subcontratists[0])) {
+                    $duplicated_data = [];
+                    foreach ($subcontratists as $subcontratist) {
+                        if ($subcontratist->SOCIAL_REASON == $request->SOCIAL_REASON) {
+                            $duplicated_data[] = "Razon Social: " . $subcontratist->SOCIAL_REASON;
+                        }
+
+                        if ($subcontratist->RFC == $request->RFC) {
+                            $duplicated_data[] = "RFC: " . $subcontratist->RFC;
+                        }
+
+                        if ($subcontratist->EMAIL == $request->EMAIL) {
+                            $duplicated_data[] = "Email: " . $subcontratist->EMAIL;
+                        }
+                    }
+
+                    if (isset($duplicated_data[0]) && !empty($duplicated_data[0])) {
+                        return $this->response_controller->makeResponse(TRUE, 'ERR_SUBCONTRATISTA_REG003: Datos duplicados', $duplicated_data, 500);
+                    }
+                }
+            }
+
+            $user_register = DB::table('S002V01TUSUA_P')
+                ->select('USUA_IDUS as ID_USER')
+                ->where('USUA_IDUS', '=', $request->UPDATED_BY_USER)
+                ->where('USUA_NULI', '=', $request->LINE_NUMBER)
+                ->first();
+
+            // Verifica si el objeto esta vacio
+            if (!isset($user_register) && empty($user_register)) {
+                return $this->response_controller
+                    ->makeResponse(TRUE, "ERR_SUBCONTRATISTA_REG004: Tu usuario no es válido para actualizar subcontratistas", [], 500);
+            }
+
+            $update_sql = DB::table('S002V01TPESU')
+                ->where('PESU_IDPS', $id_subcontratist)
+                ->where('PESU_NULI', '=', $request->LINE_NUMBER)
+                ->update([
+                    "PESU_RASO" => trim($request->SOCIAL_REASON),
+                    "PESU_REFI" => trim($request->TAX_REFERENCE),
+                    "PESU_XRFC" => trim($request->RFC),
+                    "PESU_TIPO" => trim($request->CONTRACT_TYPE),
+                    "PESU_CORR" => trim($request->EMAIL),
+                    "PESU_EXTR" => trim($request->FOREIGNER),
+                    "PESU_TAID" => trim($request->TAX),
+                    "PESU_CALL" => trim($request->STREET),
+                    "PESU_NOEX" => trim($request->EXTERIOR_NUMBER),
+                    "PESU_NOIN" => trim($request->INTERIOR_NUMBER),
+                    "PESU_COLO" => trim($request->COLONIA),
+                    "PESU_CIUD" => trim($request->CITY),
+                    "PESU_COPO" => trim($request->POSTAL_CODE),
+                    "PESU_ENFE" => trim($request->FEDERAL_ENTITY),
+                    "PESU_IDPA" => trim($request->COUNTRY_ID),
+                    "PESU_TEL1" => trim($request->TELEPHONE1),
+                    "PESU_LAT1" => trim($request->LADA1),
+                    "PESU_TEL2" => trim($request->TELEPHONE2),
+                    "PESU_LAT2" => trim($request->LADA2),
+                    "PESU_ESTA" => "Activo",
+                    "PESU_USMO" => trim($request->UPDATED_BY_USER),
+                    "PESU_FEMO" => $UPDATE_DATE,
+                    "PESU_FEAR" => DB::raw('CURRENT_TIMESTAMP')
+                ]);
+
+            // Verifica que la actualización se haya realizado exitosamente
+            if ($update_sql) {
+                $response = $this->response_controller->makeResponse(FALSE, 'Actualización exitosa');
+            } else {
+                $response = $this->response_controller->makeResponse(TRUE, 'ERR_SUBCONTRATISTA_REG005: Algo salió mal, error al actualizar al subcontratista', [], 500);
+            }
+
+            return $response;
+
+
+        } catch (Throwable $th) {
+            return $this->response_controller
+                ->makeResponse(TRUE, 'ERR_SUBCONTRATISTA_REG006: Error inesperado', strtoupper($th->getMessage()), 500);
+        }
+
+    }
+
+    // Metodo para obtener datos de los subcontratistas
+    public function getAllSubcontratists($line_number)
+    {
+        try {
+
+            $subcontratists_info = DB::table('S002V01TPESU')
+                ->select(
+                    'S002V01TPESU.PESU_IDPS as ID_SUBCONTRATIST',
+                    'S002V01TPESU.PESU_RASO as SOCIAL_REASON',
+                    'S002V01TPESU.PESU_REFI as TAX_REFERENCE',
+                    'S002V01TPESU.PESU_XRFC as RFC',
+                    'S002V01TPESU.PESU_TIPO as CONTRACT_TYPE',
+                    'S002V01TPESU.PESU_CORR as EMAIL',
+                    'S002V01TPESU.PESU_EXTR as FOREIGNER',
+                    'S002V01TPESU.PESU_TAID as TAX',
+                    'S002V01TPESU.PESU_CALL as STREET',
+                    'S002V01TPESU.PESU_NOEX as EXTERIOR_NUMBER',
+                    'S002V01TPESU.PESU_NOIN as INTERIOR_NUMBER',
+                    'S002V01TPESU.PESU_COLO as COLONIA',
+                    'S002V01TPESU.PESU_CIUD as CITY',
+                    'S002V01TPESU.PESU_COPO as POSTAL_CODE',
+                    'S002V01TPESU.PESU_ENFE as FEDERAL_ENTITY',
+                    'S002V01TPAIS.PAIS_NOMB as COUNTRY',
+                    'S002V01TPESU.PESU_TEL1 as TELEPHONE1',
+                    'S002V01TPESU.PESU_LAT1 as LADA1',
+                    'S002V01TPESU.PESU_TEL2 as TELEPHONE2',
+                    'S002V01TPESU.PESU_LAT2 as LADA2',
+                    'S002V01TPESU.PESU_ESTA as STATUS'
+                )
+                ->where('S002V01TPESU.PESU_NULI', '=', $line_number)
+                ->join('S002V01TPAIS', 'S002V01TPESU.PESU_IDPA', '=', 'S002V01TPAIS.PAIS_IDPA')
+                ->get();
+
+            // Verifica si el objeto esta vacio
+            if (!isset($subcontratists_info[0]) && empty($subcontratists_info[0])) {
+                return $this->response_controller
+                    ->makeResponse(TRUE, 'ERR_SUBCONTRATISTA_REG001: No se encontraron datos', $subcontratists_info, 500);
+            }
+
+            foreach ($subcontratists_info as $subcontratist) {
+                $subcontratist->RFC = $this->encrypt_controller->encrypt($subcontratist->RFC);
+                $subcontratist->TELEPHONE1 = $this->encrypt_controller->encrypt($subcontratist->TELEPHONE1);
+                $subcontratist->TELEPHONE2 = $this->encrypt_controller->encrypt($subcontratist->TELEPHONE2);
+                $subcontratist->EMAIL = $this->encrypt_controller->encrypt($subcontratist->EMAIL);
+            }
+
+            return $this->response_controller->makeResponse(FALSE, 'Consulta exitosa', $subcontratists_info);
+
+        } catch (Throwable $e) {
+            return $this->response_controller
+                ->makeResponse(TRUE, 'ERR_SUBCONTRATISTA_REG002: Error inesperado', strtoupper($e->getMessage()), 500);
+        }
+    }
+
+    // Metodo para obtener los subcontratistas y el numero de contratos que tienen
+    public function getContractsOfEverySubcontratist($line_number)
+    {
+        try {
+            $subcontratists = DB::table('S002V01TPESU')
+                ->select(
+                    'S002V01TPESU.PESU_IDPS as ID_SUBCONTRATIST',
+                    DB::raw('CONCAT(S002V01TPESU.PESU_RASO, " " , COALESCE(S002V01TPESU.PESU_REFI, "")) AS NAME'),
+                    DB::raw('COUNT(S002V01TPECO.PECO_IDPE) AS CONTRACTS_COUNT')
+                )
+                ->where('S002V01TPESU.PESU_NULI', '=', $line_number)
+                ->where('S002V01TPERS.PERS_NULI', '=', $line_number)
+                ->where('S002V01TPECO.PECO_NULI', '=', $line_number)
+                ->where('S002V01TCONT.CONT_NULI', '=', $line_number)
+                ->groupBy('S002V01TPESU.PESU_IDPS', 'S002V01TPESU.PESU_RASO', 'S002V01TPECO.PECO_IDPE')
+                ->join('S002V01TPERS', 'S002V01TPESU.PESU_IDPS', '=', 'S002V01TPERS.PERS_IDPS')
+                ->join('S002V01TPECO', 'S002V01TPERS.PERS_IDPE', '=', 'S002V01TPECO.PECO_IDPE')
+                ->join('S002V01TCONT', 'S002V01TPECO.PECO_IDCO', '=', 'S002V01TCONT.CONT_IDCO')
+                ->get();
+
+            // Verifica si el objeto esta vacio
+            if (!isset($subcontratists[0]) && empty($subcontratists[0])) {
+                return $this->response_controller
+                    ->makeResponse(TRUE, 'ERR_SUBCONTRATISTA_REG001: No se encontraron datos', $subcontratists, 500);
+            }
+
+            $contracts_by_subcontratist = [];
+
+            // Ciclo para impedir que un subcontratista cuente el contrato de cada empleado, solo contará los contratos unicos
+            for ($i = 0; $i < sizeof($subcontratists); $i++) {
+                for ($o = $i + 1; $o < sizeof($subcontratists); $o++) {
+                    if ($subcontratists[$i]->NAME == $subcontratists[$o]->NAME) {
+
+                        // Verifica que registro tiene el numero mayor, que sera el conteo real de los contratos sin repeticiones
+                        // El registro que sea el menor (repetido), cambiara el nombre para indicar que esta repetido
+                        if ($subcontratists[$i]->CONTRACTS_COUNT > $subcontratists[$o]->CONTRACTS_COUNT) {
+                            $subcontratists[$o]->NAME = "XXXX";
+                        } else {
+                            $subcontratists[$i]->NAME = "XXXX";
+                        }
+                    }
+                }
+
+                // Si el registro tiene un nombre unico, se coloca en el arreglo a enviar
+                if ($subcontratists[$i]->NAME != "XXXX") {
+                    $subcontratists[$i]->NAME = trim($subcontratists[$i]->NAME);
+                    $contracts_by_subcontratist[] = $subcontratists[$i];
+                }
+            }
+
+            return $this->response_controller
+                ->makeResponse(FALSE, "Consulta exitosa", $contracts_by_subcontratist);
+
+        } catch (Throwable $th) {
+            return $this->response_controller
+                ->makeResponse(TRUE, 'ERR_SUBCONTRATISTA_REG002: Error inesperado', strtoupper($th->getMessage()), 500);
+        }
+
+    }
+
+    // Metodo para obtener el historico de los contratos de un subcontratista (Comprueba si existe el subcontratista)
+    public function getContractsBySubcontratist($id_subcontratist, $line_number)
+    {
+
+        try {
+
+            // Busca si el subcontratista existe
+            $search_subcontratist = DB::table("S002V01TPESU")
+                ->select("PESU_NULI as LINE_NUMBER")
+                ->where("PESU_IDPS", "=", $id_subcontratist)
+                ->where('PESU_NULI', '=', $line_number)
+                ->first();
+
+            // Verifica si el objeto esta vacio
+            if (!isset($search_subcontratist) && empty($search_subcontratist)) {
+                return $this->response_controller
+                    ->makeResponse(TRUE, "ERR_SUBCONTRATISTA_REG001: No se encontró al subcontratista", $search_subcontratist, 500);
+            }
+
+            // Obtiene los contratos pertenecientes al subcontratista deseado
+            $contracts = DB::table('S002V01TPERS')
+                ->groupBy('S002V01TPERS.PERS_IDPS', 'S002V01TCONT.CONT_IDCO', 'S002V01TCONT.CONT_FEIN', 'S002V01TCONT.CONT_FEFI', 'S002V01TPERS.PERS_NULI')
+                ->orderBy("S002V01TCONT.CONT_FEIN", 'desc')
+                ->where('S002V01TPERS.PERS_IDPS', '=', $id_subcontratist)
+                ->where('S002V01TPERS.PERS_NULI', '=', $line_number)
+                ->where('S002V01TPECO.PECO_NULI', '=', $line_number)
+                ->where('S002V01TCONT.CONT_NULI', '=', $line_number)
+                ->select(
+                    'S002V01TCONT.CONT_FEIN as START_DATE',
+                    'S002V01TCONT.CONT_FEFI as END_DATE',
+                    'S002V01TCONT.CONT_IDCO as ID_CONTRACT',
+                    'S002V01TPERS.PERS_IDPS as ID_SUBCONTRATIST',
+                )
+                ->join('S002V01TPECO', 'S002V01TPERS.PERS_IDPE', '=', 'S002V01TPECO.PECO_IDPE')
+                ->join('S002V01TCONT', 'S002V01TPECO.PECO_IDCO', '=', 'S002V01TCONT.CONT_IDCO')
+                ->get();
+
+            // Verifica si el objeto esta vacio
+            if (!isset($contracts[0]) && empty($contracts[0])) {
+                return $this->response_controller
+                    ->makeResponse(TRUE, 'ERR_CONTRATO_REG002: El subcontratista no tiene contratos', $contracts, 500);
+            }
+
+
+            // Obtiene las intervenciones con el id del contrato del personal que realizo el trabajo
+            $interventions = DB::table('S002V01TCONT')
+                ->select(
+                    'S002V01TCONT.CONT_IDCO as ID_CONTRACT',
+                    DB::raw('CONCAT(S002V01TPESU.PESU_RASO, " " , COALESCE(S002V01TPESU.PESU_REFI, "")) AS SUBCONTRACT_NAME'),
+                    DB::raw('CONCAT(S002V01TUSUA_P.USUA_NOMB, " " , S002V01TUSUA_P.USUA_APPA, " ", S002V01TUSUA_P.USUA_APMA) AS NAME'),
+                    'S002V01TPERS.PERS_ESPE',
+                    'S002V01TINTE_P.INTE_IDIN as INTERVENTION_ID',
+                    'S002V01TINTE_P.INTE_NOMB as INTERVENTION_NAME',
+                    'S002V01TINTE_P.INTE_ESRE as SPECIALTY_REQUIRED',
+                    'S002V01TPERS.PERS_IDPE as ID_SUBCONTRACT',
+                    'S002V01TINTE_P.INTE_FECS as INTERVENTION_DATE',
+                )
+                ->where('S002V01TPERS.PERS_IDPS', '=', $id_subcontratist)
+                ->where('S002V01TPERS.PERS_NULI', '=', $line_number)
+                ->where('S002V01TCONT.CONT_NULI', '=', $line_number)
+                ->where('S002V01TPECO.PECO_NULI', '=', $line_number)
+                ->where('S002V01TUSUA_P.USUA_NULI', '=', $line_number)
+                ->where('S002V01TPESU.PESU_NULI', '=', $line_number)
+                ->where('S002V01TPEEM.PEEM_NULI', '=', $line_number)
+                ->where('S002V01TEQMA.EQMA_NULI', '=', $line_number)
+                ->where('S002V01TEMIN.EMIN_NULI', '=', $line_number)
+                ->where('S002V01TINTE_P.INTE_NULI', '=', $line_number)
+                ->join('S002V01TPECO', 'S002V01TCONT.CONT_IDCO', '=', 'S002V01TPECO.PECO_IDCO')
+                ->join('S002V01TPERS', 'S002V01TPECO.PECO_IDPE', '=', 'S002V01TPERS.PERS_IDPE')
+                ->join('S002V01TUSUA_P', 'S002V01TPERS.PERS_IDUS', '=', 'S002V01TUSUA_P.USUA_IDUS')
+                ->join('S002V01TPESU', 'S002V01TPERS.PERS_IDPS', '=', 'S002V01TPESU.PESU_IDPS')
+                ->join('S002V01TPEEM', 'S002V01TPERS.PERS_IDPE', '=', 'S002V01TPEEM.PEEM_IDPE')
+                ->join('S002V01TEQMA', 'S002V01TPEEM.PEEM_IDEM', '=', 'S002V01TEQMA.EQMA_IDEQ')
+                ->join('S002V01TEMIN', 'S002V01TEQMA.EQMA_IDEQ', '=', 'S002V01TEMIN.EMIN_IDEM')
+                ->join('S002V01TINTE_P', 'S002V01TEMIN.EMIN_IDIN', '=', 'S002V01TINTE_P.INTE_IDIN')
+                ->get();
+
+            // Verifica si el objeto esta vacio
+            if (!isset($interventions[0]) && empty($interventions[0])) {
+                return $this->response_controller
+                    ->makeResponse(TRUE, 'ERR_INTERVENCIÓN_REG003: No se encontraron datos', $interventions, 500);
+            }
+
+            // Itera los contratos para colocarles las intervenciones y miembros correspondientes
+            foreach ($contracts as $contract) {
+
+                // Para indicar la hora en la que fue creado el contrato con el formato deseado
+                $contract->START_DATE = Carbon::create($contract->START_DATE)->format("d-m-Y h:i:s A");
+                $contract->END_DATE = Carbon::create($contract->END_DATE)->format("d-m-Y h:i:s A");
+
+                $interventions_counter = 0;
+                for ($i = 0; $i < sizeof($interventions); $i++) {
+                    $temporal_intervention = new stdClass();
+                    $temporal_members = [];
+                    for ($o = $i + 1; $o < sizeof($interventions); $o++) {
+
+                        // Verifica que no se repitan las intervenciones ni los nombres de integrantes en la misma intervencion
+                        if ($interventions[$i]->INTERVENTION_ID == $interventions[$o]->INTERVENTION_ID && $interventions[$i]->SUBCONTRACT_NAME == $interventions[$o]->SUBCONTRACT_NAME) {
+                            if ($interventions[$i]->NAME <> $interventions[$o]->NAME) {
+                                $temporal_members[] = $interventions[$o]->NAME;
+                            }
+
+                            // Para que no lo tome nuevamente, eliminamos el ID del contrato
+                            $interventions[$o]->INTERVENTION_ID = "XXXX";
+                        }
+
+                    }
+
+                    // Introduce sus datos de la intervencion correspondiente
+                    if ($interventions[$i]->INTERVENTION_ID != "XXXX" && Carbon::create($interventions[$i]->INTERVENTION_DATE)->between($contract->START_DATE, $contract->END_DATE)) {
+                        $temporal_members[] = $interventions[$i]->NAME;
+                        $temporal_intervention->INTERVENTION_NAME = $interventions[$i]->INTERVENTION_NAME;
+                        $temporal_intervention->INTERVENTION_ID = $interventions[$i]->INTERVENTION_ID;
+                        $temporal_intervention->SPECIALTY_REQUIRED = $interventions[$i]->SPECIALTY_REQUIRED;
+                        $temporal_intervention->SUBCONTRACT_NAME = trim($interventions[$i]->SUBCONTRACT_NAME);
+                        $temporal_intervention->MEMBERS = $temporal_members;
+                        $contract->INTERVENTIONS[] = $temporal_intervention;
+                        $interventions_counter++;
+                    }
+
+                }
+                $contract->INTERVENTIONS_COUNTER = $interventions_counter;
+            }
+
+            // Verifica si el objeto esta vacio
+            if (!isset($contracts[0]) && empty($contracts[0])) {
+                return $this->response_controller
+                    ->makeResponse(TRUE, 'ERR_CONTRATO_REG004: Error al asignar contrato con intervención', $contracts, 500);
+            }
+            $response = new stdClass();
+            $response->LINE_NUMBER = $search_subcontratist->LINE_NUMBER;
+            $response->contracts = $contracts;
+            return $this->response_controller->makeResponse(FALSE, 'Consulta exitosa', $response);
+
+        } catch (Throwable $th) {
+            return $this->response_controller
+                ->makeResponse(TRUE, 'ERR_SUBCONTRATISTA_REG005: Error inesperado', strtoupper($th->getMessage()), 500);
+        }
+    }
+
+    // Metodo para la descarga en archivo excel del historial de contratos por subcontratista
+    public function downoloadSubcontractInfoOnExcel(Request $request)
+    {
+
+        try {
+
+            $id_subcontratist = $request->contracts[0]['ID_SUBCONTRATIST'];
+
+            $final_part_name_document = "Contracts_History_By_Subcontratist_" . $id_subcontratist . ".xlsx";
+
+            // Crea el documento con los datos del request
+            $document = $this->createDocument($request);
+
+            // Busca la ultima versión del documento que se haya insertado
+            $old_document_name = $this->documents_controller->getDocumentsWithSameName($final_part_name_document, 'excel');
+
+            if ($old_document_name != null) {
+
+                // Obtiene el nombre del documento que tiene el mismo contenido
+                $old_document_name = $this->documents_controller->sameDocumentsExcel($document, $old_document_name);
+
+                // Si no hay ningun cambio en el documento, se descarga la ultima versión
+                if ($old_document_name != null) {
+                    return Storage::disk('excel')->download($old_document_name);
+                }
+            }
+
+            $writer = IOFactory::createWriter($document, 'Xlsx');
+            $content = tmpfile();
+            $writer->save($content);
+            // Inserta la nueva versión del documento en la base de datos y luego en el storage
+            $name_document = $this->documents_controller->createDocument("GPRS", "IN", $final_part_name_document, null, 'excel', $request->LINE_NUMBER, $request->REGISTERED_BY_USER);
+            Storage::disk('excel')->put(
+                $name_document,
+                $content
+            );
+
+            return Storage::disk('excel')->download($name_document);
+
+        } catch (Throwable $th) {
+            return $this->response_controller
+                ->makeResponse(TRUE, 'ERR_EXCEL_REG001: Error inesperado', strtoupper($th), 500);
+        }
+    }
+
+    // Metodo para la descarga en archivo pdf del historial de contratos por subcontratista
+    public function downoloadSubcontractInfoOnPdf(Request $request)
+    {
+
+        try {
+
+            $id_subcontratist = $request->contracts[0]['ID_SUBCONTRATIST'];
+
+            $final_part_name_document = "Contracts_History_By_Subcontratist_" . $id_subcontratist . ".pdf";
+
+            //Crea el documento con los datos del request
+
+            $document = $this->createDocument($request);
+
+            $writer = IOFactory::createWriter($document, 'Mpdf');
+            $content = tmpfile();
+
+            // Busca la ultima versión del documento que se haya insertado
+            $old_document_name = $this->documents_controller->getDocumentsWithSameName($final_part_name_document, 'pdf');
+
+            $writer->save($content);
+            if ($old_document_name != null) {
+
+                // Obtiene el nombre del documento que tiene el mismo contenido
+                $old_document_name = $this->documents_controller->sameDocumentsPdf($content, $old_document_name);
+
+                // Si no hay ningun cambio en el documento, se descarga la ultima versión
+                if ($old_document_name != null) {
+                    return Storage::disk('pdf')->download($old_document_name);
+                }
+            }
+
+            // Inserta la nueva version del documento en la base de datos y luego en el storage
+            $name_document = $this->documents_controller->createDocument("GPRS", "IN", $final_part_name_document, null, 'pdf', $request->LINE_NUMBER, $request->REGISTERED_BY_USER);
+
+            Storage::disk('pdf')->put(
+                $name_document,
+                $content
+            );
+
+            return Storage::disk('pdf')->download($name_document);
+
+        } catch (Throwable $th) {
+            return $this->response_controller
+                ->makeResponse(TRUE, 'ERR_PDF_REG001: Error inesperado', strtoupper($th), 500);
+        }
+    }
+
+    // Metodo para la creación de documento
+    public function createDocument(Request $request)
+    {
+        try {
+
+            $contracts = $request->contracts;
+            $document = new Spreadsheet();
+
+            // Propiedades del documento 
+            $document->getProperties()
+                ->setCreator("ITTEC")
+                ->setTitle("Historial de Contratos por Subcontratista")
+                ->setSubject("Historial Documento")
+                ->setKeywords("Subcontratista Contratos Historial")
+                ->setCategory("Historial archivo");
+
+            // Hace la escritura dentro del archivo 
+            $start_row = 2; # Indica desde que fila inicia la tabla
+            $start_col = "B"; # Indica desde que columna inicia la tabla
+
+            $row = $start_row;
+            foreach ($contracts as $contract) {
+                // Lleva el control de las celdas de forma automatica
+                $first_row = $row;
+                $col = $start_col;
+                $col++;
+                $second_col = $col;
+                $col++;
+                $third_col = $col;
+                $col++;
+                $semi_final_col = $col;
+                $col++;
+                $final_col = $col;
+                $col = $start_col;
+
+                // Titulo del documento
+                if ($first_row == $start_row) {
+                    $document->getActiveSheet()->mergeCells($start_col . $row . ":" . $final_col . $row);
+                    $document->getActiveSheet()->setCellValue($start_col . $row, 'FICHA DE SUBCONTRATACIÓN')->getStyle($start_col . $row)->getFill()
+                        ->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)
+                        ->getStartColor()->setRGB('FFCC88');
+                    $document->getActiveSheet()->getStyle($start_col . $row)->getFont()->setBold(true);
+                    $row++;
+                }
+
+                // Cuerpo del documento
+                // Si el contrato tiene intervenciones...
+                if ($contract['INTERVENTIONS_COUNTER'] > 0) {
+
+                    // Une las 4 primeras celdas para el titulo y datos de las fechas
+                    $document->getActiveSheet()->mergeCells($col . $row . ":" . $semi_final_col . $row);
+                    $document->getActiveSheet()->mergeCells($col . $row + 1 . ":" . $semi_final_col . $row + 1);
+
+                    $document->getActiveSheet()->setCellValue($col . $row, 'FECHA INICIO - FECHA FIN')->getStyle($col . $row)->getFill()
+                        ->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)
+                        ->getStartColor()->setRGB('FFCC88');
+                    $col++;
+                    $col++;
+                    $col++;
+                    $col++;
+
+                    $document->getActiveSheet()->setCellValue($col . $row, 'ID CONTRATO')->getStyle($col . $row)->getFill()
+                        ->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)
+                        ->getStartColor()->setRGB('FFCC88');
+                    $row++;
+
+                    $col = $start_col;
+                    $document->getActiveSheet()->setCellValue($col . $row, $contract['START_DATE'] . " - " . $contract['END_DATE']);
+
+                    $col++;
+                    $col++;
+                    $col++;
+                    $col++;
+                    $document->getActiveSheet()->setCellValue($col . $row, "#" . $contract['ID_CONTRACT']);
+
+                    $row++;
+                    foreach ($contract['INTERVENTIONS'] as $intervention) {
+                        $col = $start_col;
+                        $document->getActiveSheet()->setCellValue($col . $row, 'ID INTERVENCIÓN')->getStyle($col . $row)->getFill()
+                            ->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)
+                            ->getStartColor()->setRGB('38D9CE');
+                        $col++;
+                        $document->getActiveSheet()->setCellValue($col . $row, 'NOMBRE INTERVENCIÓN')->getStyle($col . $row)->getFill()
+                            ->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)
+                            ->getStartColor()->setRGB('38D9CE');
+
+                        $col++;
+                        $document->getActiveSheet()->setCellValue($col . $row, 'ESPECIALIDAD REQUERIDA')->getStyle($col . $row)->getFill()
+                            ->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)
+                            ->getStartColor()->setRGB('38D9CE');
+
+                        $col++;
+                        $document->getActiveSheet()->setCellValue($col . $row, 'NOMBRE SUBCONTRATISTA')->getStyle($col . $row)->getFill()
+                            ->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)
+                            ->getStartColor()->setRGB('38D9CE');
+
+                        $col++;
+                        $document->getActiveSheet()->setCellValue($col . $row, 'MIEMBROS DE INTERVENCIÓN')->getStyle($col . $row)->getFill()
+                            ->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)
+                            ->getStartColor()->setRGB('38D9CE');
+
+                        $col = $start_col;
+                        $row++;
+                        $document->getActiveSheet()->setCellValue($col . $row, "#" . $intervention['INTERVENTION_ID']);
+                        $col++;
+                        $document->getActiveSheet()->setCellValue($col . $row, $intervention['INTERVENTION_NAME']);
+                        $col++;
+                        $document->getActiveSheet()->setCellValue($col . $row, $intervention['SPECIALTY_REQUIRED']);
+                        $col++;
+                        $document->getActiveSheet()->setCellValue($col . $row, $intervention['SUBCONTRACT_NAME']);
+                        $col++;
+
+                        $temporal_pointer_row = $row; # Indica la primera fila donde se introducieron miembros de la intervencion
+
+                        // Ingresa fila por fila a los miembros de una intervencion
+                        foreach ($intervention['MEMBERS'] as $member) {
+                            $document->getActiveSheet()->setCellValue($col . $row, $member);
+                            $row++;
+                        }
+
+                        // Une las celdas sobrantes de los campos de intervencion
+                        $document->getActiveSheet()->mergeCells($start_col . $temporal_pointer_row . ":" . $start_col . $row - 1);
+                        $document->getActiveSheet()->mergeCells($second_col . $temporal_pointer_row . ":" . $second_col . $row - 1);
+                        $document->getActiveSheet()->mergeCells($third_col . $temporal_pointer_row . ":" . $third_col . $row - 1);
+                        $document->getActiveSheet()->mergeCells($semi_final_col . $temporal_pointer_row . ":" . $semi_final_col . $row - 1);
+                        $document->getActiveSheet()->getStyle($start_col . $first_row . ':' . $col . $row - 1)->getBorders()->getAllBorders()->setBorderStyle(\PhpOffice\PhpSpreadsheet\Style\Border::BORDER_MEDIUM);
+                    }
+
+                    // Si el contrato no tiene intervenciones...
+                } else {
+                    $document->getActiveSheet()->mergeCells($col . $row . ":" . $semi_final_col . $row);
+                    $document->getActiveSheet()->mergeCells($col . $row + 1 . ":" . $semi_final_col . $row + 1);
+
+                    $document->getActiveSheet()->setCellValue($col . $row, 'FECHA INICIO - FECHA FIN')->getStyle($col . $row)->getFill()
+                        ->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)
+                        ->getStartColor()->setRGB('FFCC88');
+                    $col++;
+                    $col++;
+                    $col++;
+                    $col++;
+
+                    $document->getActiveSheet()->setCellValue($col . $row, 'ID CONTRATO')->getStyle($col . $row)->getFill()
+                        ->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)
+                        ->getStartColor()->setRGB('FFCC88');
+                    $row++;
+
+                    $col = $start_col;
+                    $document->getActiveSheet()->setCellValue($col . $row, $contract['START_DATE'] . " - " . $contract['END_DATE']);
+
+                    $col++;
+                    $col++;
+                    $col++;
+                    $col++;
+                    $document->getActiveSheet()->setCellValue($col . $row, "#" . $contract['ID_CONTRACT']);
+
+                    $row++;
+
+                    $document->getActiveSheet()->mergeCells($start_col . $row . ":" . $final_col . $row);
+                    $document->getActiveSheet()->setCellValue($start_col . $row, 'CONTRATO SIN INTERVENCIONES...')->getStyle($start_col . $row)->getFill()
+                        ->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)
+                        ->getStartColor()->setRGB('38D9CE');
+                    $document->getActiveSheet()->getStyle($start_col . $row)->getFont()->setBold(true);
+
+                    $row++;
+                    $document->getActiveSheet()->getStyle($start_col . $first_row . ':' . $col . $row - 1)->getBorders()->getAllBorders()->setBorderStyle(\PhpOffice\PhpSpreadsheet\Style\Border::BORDER_MEDIUM);
+                }
+
+                $row++;
+                $document->getActiveSheet()->getStyle($start_col . $row - 1 . ':' . $final_col . $row - 1)->getFill()
+                    ->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)
+                    ->getStartColor()->setRGB('D9386C');
+                $document->getActiveSheet()->getRowDimension($row - 1)->setRowHeight(25);
+                $document->getActiveSheet()->getStyle($start_col . $first_row . ':' . $final_col . $row)->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER);
+                $document->getActiveSheet()->getStyle($start_col . $first_row . ':' . $final_col . $row)->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);
+            }
+            $document->getActiveSheet()->getColumnDimension($start_col)->setAutoSize(true);
+            $start_col++;
+            $document->getActiveSheet()->getColumnDimension($start_col)->setAutoSize(true);
+            $start_col++;
+            $document->getActiveSheet()->getColumnDimension($start_col)->setAutoSize(true);
+            $start_col++;
+            $document->getActiveSheet()->getColumnDimension($start_col)->setAutoSize(true);
+            $start_col++;
+            $document->getActiveSheet()->getColumnDimension($start_col)->setAutoSize(true);
+
+            return $document;
+
+        } catch (Throwable $th) {
+            return $this->response_controller
+                ->makeResponse(TRUE, 'ERR_CREACIÓN_DOCUMENTO_REG001: Error inesperado', strtoupper($th->getMessage()), 500);
+        }
+    }
+
+}

+ 405 - 0
sistema-mantenimiento-back/app/Http/Controllers/WorkTeamController.php

@@ -0,0 +1,405 @@
+<?php
+/*
+Nombre del programador:         Cordourier Rojas Mathew
+Ultima fecha de modificación:   [ 03 / Marzo / 2023 ]
+Descripción:                    Controlador del submodulo Equipos de Trabajo. Perteneciente al Módulo 13 - Gestion del Personal de Mantenimiento
+*/
+
+namespace App\Http\Controllers;
+
+use Illuminate\Http\Request;
+use Carbon\Carbon;
+use Illuminate\Support\Facades\DB;
+use Illuminate\Support\Facades\Validator;
+use Throwable;
+
+class WorkTeamController extends Controller
+{
+
+    private $response_controller;
+    private $encrypt_controller;
+    public function __construct()
+    {
+        $this->response_controller = new ResponseController();
+        $this->encrypt_controller = new EncryptionController();
+    }
+
+    // Metodo para la consulta de equipos de trabajo
+    public function getConsultOfWorkteams($line_number)
+    {
+        try {
+            $workteams = DB::table('S002V01TEQMA')
+                ->select(
+                    'EQMA_IDEQ as WORKTEAM_ID',
+                    'EQMA_NOMB as NAME',
+                    'EQMA_ESPE as SPECIALITY',
+                    'EQMA_ESTA as STATUS'
+                )
+                ->where('EQMA_ESTA', '=', 'Activo')
+                ->where('EQMA_NULI', '=', $line_number)
+                ->get();
+
+            // Verifica si el objeto esta vacio
+            if (!isset($workteams[0]) && empty($workteams[0])) {
+                return $this->response_controller
+                    ->makeResponse(TRUE, 'ERR_EQUIPO_TRABAJO_REG001: No se encontraron datos', $workteams, 500);
+            }
+
+            return $this->response_controller->makeResponse(FALSE, 'Consulta exitosa', $workteams, 200);
+        } catch (Throwable $th) {
+            return $this->response_controller
+                ->makeResponse(TRUE, 'ERR_EQUIPO_TRABAJO_REG002: Error inesperado', strtoupper($th->getMessage()), 500);
+        }
+    }
+
+    // Metodo para la consulta de un equipo de trabajo por medio de su id
+    public function getWorkteamById($id_workteam, $line_number)
+    {
+        try {
+            $workteams = DB::table('S002V01TEQMA')
+                ->select(
+                    'EQMA_IDEQ as WORKTEAM_ID',
+                    'EQMA_NOMB as NAME',
+                    'EQMA_ESPE as SPECIALITY',
+                    'EQMA_ESTA as STATUS'
+                )
+                ->where('EQMA_IDEQ', '=', $id_workteam)
+                ->where('EQMA_NULI', '=', $line_number)
+                ->first();
+
+            // Verifica si el objeto esta vacio
+            if (!isset($workteams) && empty($workteams)) {
+                return $this->response_controller
+                    ->makeResponse(TRUE, 'ERR_EQUIPO_TRABAJO_REG001: No se encontró al equipo de trabajo', $workteams, 500);
+            }
+
+            return $this->response_controller->makeResponse(FALSE, 'Consulta exitosa', $workteams, 200);
+        } catch (Throwable $th) {
+            return $this->response_controller
+                ->makeResponse(TRUE, 'ERR_EQUIPO_TRABAJO_REG002: Error inesperado', strtoupper($th->getMessage()), 500);
+        }
+    }
+
+    // Metodo para obtener los detalles de un equipo de trabajo por el id
+    public function getDetailsOfWorkteamById($id_workteam, $line_number)
+    {
+        try {
+            $workteam = DB::table("S002V01TEQMA")
+                ->select(
+                    'EQMA_IDEQ as WORKTEAM_ID',
+                    'EQMA_NOMB as NAME',
+                    'EQMA_ESPE as SPECIALITY',
+                    "EQMA_FERE as REGISTER_DATE",
+                    "EQMA_USRE as REGISTERED_BY",
+                    "EQMA_FEMO as UPDATE_DATE",
+                    "EQMA_USMO as UPDATED_BY"
+                )
+                ->where("EQMA_IDEQ", '=', $id_workteam)
+                ->where("EQMA_NULI", '=', '01')
+                ->first();
+
+            // Verifica si el objeto esta vacio
+            if (!isset($workteam) && empty($workteam)) {
+                return $this->response_controller
+                    ->makeResponse(TRUE, 'ERR_EQUIPO_TRABAJO_REG001: No se encontró al equipo de trabajo', [], 500);
+            }
+
+            $users = DB::table("S002V01TUSUA_P")
+                ->select("USUA_IDUS as ID", DB::raw('CONCAT(USUA_NOMB, " " , USUA_APPA, " ", USUA_APMA) AS NAME'))
+                ->where('USUA_NULI', '=', $line_number)
+                ->get();
+
+            // Verifica si el objeto esta vacio
+            if (!isset($users[0]) && empty($users[0])) {
+                return $this->response_controller
+                    ->makeResponse(TRUE, 'ERR_USUARIO_REG002: No se encontraron datos', [], 500);
+            }
+
+            foreach ($users as $user) {
+
+                // Inserta el nombre del usuario que lo registro y actualizó si hubo alguno.
+                if ($workteam->REGISTERED_BY == $user->ID) {
+                    $workteam->REGISTERED_BY = $user->NAME;
+                }
+
+                if ($workteam->UPDATED_BY == $user->ID) {
+                    $workteam->UPDATED_BY = $user->NAME;
+                }
+            }
+
+            // Inserta la fecha de registro y actualización si hubo alguna.
+            $workteam->REGISTER_DATE = Carbon::create($workteam->REGISTER_DATE)->format("d-m-Y h:i:s A");
+            if ($workteam->UPDATE_DATE != null) {
+                $workteam->UPDATE_DATE = Carbon::create($workteam->UPDATE_DATE)->format("d-m-Y h:i:s A");
+            } else {
+                $workteam->UPDATE_DATE = "-";
+            }
+
+            if ($workteam->UPDATED_BY == null) {
+                $workteam->UPDATED_BY = "-";
+            }
+
+            return $this->response_controller->makeResponse(FALSE, 'Consulta exitosa', $workteam, 200);
+
+        } catch (Throwable $th) {
+            return $this->response_controller
+                ->makeResponse(TRUE, 'ERR_EQUIPO_TRABAJO_REG003: Error inesperado', strtoupper($th->getMessage()), 500);
+        }
+    }
+
+    // Metodo para la eliminación lógica de un equipo de trabajo
+    public function updateToInactiveStatus(Request $request, $id_workteam)
+    {
+        try {
+
+            $validator = Validator::make($request->all(), [
+                "UPDATED_BY_USER" => ['required', 'digits:10']
+            ]);
+
+            if ($validator->fails()) {
+                return $this->response_controller->makeResponse(
+                    TRUE,
+                    'ERR_EQUIPO_TRABAJO_REG001: Uno o más errores encontrados',
+                    $this->response_controller->makeErrors($validator->errors()->messages()),
+                    400
+                );
+            }
+
+            $workteam = DB::table('S002V01TEQMA')
+                ->select("EQMA_IDEQ")
+                ->where("EQMA_IDEQ", '=', $id_workteam)
+                ->first();
+
+            // Verifica si el objeto esta vacio
+            if (!isset($workteam) && empty($workteam)) {
+                return $this->response_controller
+                    ->makeResponse(TRUE, 'ERR_EQUIPO_TRABAJO_REG002: No se encontró al equipo de trabajo', [], 500);
+            }
+
+            $workteam_has_employees = DB::table("S002V01TPEEM")
+                ->select(DB::raw("COUNT(PEEM_IDEM) as MEMBERS_QUANTITY"))
+                ->where("PEEM_IDEM", '=', $id_workteam)
+                ->where("PEEM_ESTA", '=', 'Activo')
+                ->where('PEEM_NULI', '=', $request->LINE_NUMBER)
+                ->first();
+
+            // Verifica que el equipo no tenga empleados activos
+            if ($workteam_has_employees->MEMBERS_QUANTITY > 0) {
+                return $this->response_controller
+                    ->makeResponse(TRUE, 'ERR_EQUIPO_PERSONAL_REG003: El equipo de trabajo tiene miembros activos', $workteam_has_employees, 500);
+            }
+
+            $user_register = DB::table('S002V01TUSUA_P')
+                ->select('USUA_IDUS as ID_USER')
+                ->where('USUA_IDUS', '=', $request->UPDATED_BY_USER)
+                ->where('USUA_NULI', '=', $request->LINE_NUMBER)
+                ->first();
+
+            // Verifica si el objeto esta vacio
+            if (!isset($user_register) && empty($user_register)) {
+                return $this->response_controller
+                    ->makeResponse(TRUE, "ERR_EQUIPO_TRABAJO_REG004: Tu usuario no es válido para eliminar equipos de trabajo", [], 500);
+            }
+
+            $UPDATE_DATE = Carbon::now()->timezone('America/Mexico_City')->toDateTimeString();
+
+            $delete_workteam = DB::table('S002V01TEQMA')
+                ->where("EQMA_IDEQ", '=', $id_workteam)
+                ->where('EQMA_NULI', '=', $request->LINE_NUMBER)
+                ->update([
+                    "EQMA_ESTA" => "Inactivo",
+                    "EQMA_USMO" => trim($request->UPDATED_BY_USER),
+                    "EQMA_FEMO" => $UPDATE_DATE,
+                    "EQMA_FEAR" => DB::raw('CURRENT_TIMESTAMP')
+                ]);
+
+            if (!$delete_workteam) {
+                return $this->response_controller
+                    ->makeResponse(TRUE, 'ERR_EQUIPO_TRABAJO_REG005: Algo salió mal, error eliminando al equipo de trabajo', [], 500);
+            }
+
+            return $this->response_controller
+                ->makeResponse(FALSE, 'Eliminación exitosa');
+
+        } catch (Throwable $th) {
+            return $this->response_controller
+                ->makeResponse(TRUE, 'ERR_EQUIPO_TRABAJO_REG006: Error inesperado', strtoupper($th->getMessage()), 500);
+        }
+    }
+
+    // Metodo para guardar un equipo de trabajo
+    public function storeWorkteam(Request $request)
+    {
+        try {
+            $REGISTER_DATE = Carbon::now()->timezone('America/Mexico_City')->toDateTimeString();
+
+            $validator = Validator::make($request->all(), [
+                "NAME" => ['required', 'max:100'],
+                "SPECIALITY" => ['required', 'max:100'],
+                "REGISTERED_BY_USER" => ['required', 'digits:10'],
+                "LINE_NUMBER" => ['required', 'digits:1']
+            ]);
+
+            if ($validator->fails()) {
+                return $this->response_controller->makeResponse(
+                    TRUE,
+                    'ERR_EQUIPO_TRABAJO_REG001: Uno o más errores encontrados',
+                    $this->response_controller->makeErrors($validator->errors()->messages()),
+                    400
+                );
+            }
+
+            $search_workteam_name = DB::table('S002V01TEQMA')
+                ->select("EQMA_NOMB")
+                ->where("EQMA_NOMB", '=', $request->NAME)
+                    // ->where('EQMA_NULI', '=', '01')
+                ->first();
+
+            // Verifica si el objeto tiene algo
+            if (isset($search_workteam_name) && !empty($search_workteam_name)) {
+                return $this->response_controller
+                    ->makeResponse(TRUE, 'ERR_EQUIPO_TRABAJO_REG002: El nombre ya fue tomado', [], 500);
+            }
+
+            $user_register = DB::table('S002V01TUSUA_P')
+                ->select('USUA_IDUS as ID_USER')
+                ->where('USUA_IDUS', '=', $request->REGISTERED_BY_USER)
+                    // ->where('USUA_NULI', '=', '01')
+                ->first();
+
+            // Verifica si el objeto esta vacio
+            if (!isset($user_register) && empty($user_register)) {
+                return $this->response_controller
+                    ->makeResponse(TRUE, "ERR_USUARIO_REG003: Tu usuario no es válido para registrar equipos de trabajo", [], 500);
+            }
+
+            $insert_workteam = DB::table('S002V01TEQMA')
+                ->insert([
+                    "EQMA_NOMB" => $request->NAME,
+                    "EQMA_ESPE" => $request->SPECIALITY,
+                    "EQMA_NULI" => $request->LINE_NUMBER,
+                    "EQMA_ESTA" => "Activo",
+                    "EQMA_USRE" => $request->REGISTERED_BY_USER,
+                    "EQMA_FERE" => $REGISTER_DATE,
+                    "EQMA_FEAR" => DB::raw('CURRENT_TIMESTAMP')
+                ]);
+
+            if (!$insert_workteam) {
+                return $this->response_controller
+                    ->makeResponse(TRUE, 'ERR_EQUIPO_TRABAJO_REG004: Algo salió mal, error registrando al equipo de trabajo', [], 500);
+            }
+
+            return $this->response_controller
+                ->makeResponse(FALSE, 'CREACIÓN EXITOSA');
+
+        } catch (Throwable $th) {
+            return $this->response_controller
+                ->makeResponse(TRUE, 'ERR_EQUIPO_TRABAJO_REG005: Error inesperado', strtoupper($th->getMessage()), 500);
+        }
+    }
+
+    // Metodo para actualizar un equipo de trabajo
+    public function updateWorkteam(Request $request, $id_workteam)
+    {
+        try {
+            $UPDATE_DATE = Carbon::now()->timezone('America/Mexico_City')->toDateTimeString();
+            $validator = Validator::make($request->all(), [
+                "NAME" => ['required', 'max:100'],
+                "SPECIALITY" => ['required', 'max:100'],
+                "UPDATED_BY_USER" => ['required', 'digits:10'],
+                "LINE_NUMBER" => ['required', 'digits:1']
+            ]);
+
+            if ($validator->fails()) {
+                return $this->response_controller->makeResponse(
+                    TRUE,
+                    'ERR_EQUIPO_TRABAJO_REG001: Uno o más errores encontrados',
+                    $this->response_controller->makeErrors($validator->errors()->messages()),
+                    400
+                );
+            }
+
+            $search_workteam = DB::table('S002V01TEQMA')
+                ->select("EQMA_IDEQ")
+                ->where("EQMA_IDEQ", '=', $id_workteam)
+                ->where('EQMA_NULI', '=', $request->LINE_NUMBER)
+                ->first();
+
+            // Verifica si el objeto esta vacio
+            if (!isset($search_workteam) && empty($search_workteam)) {
+                return $this->response_controller
+                    ->makeResponse(TRUE, 'ERR_EQUIPO_TRABAJO_REG002: No se encontró al equipo de trabajo', [], 500);
+            }
+
+            $search_workteam_name = DB::table('S002V01TEQMA')
+                ->select("EQMA_NOMB")
+                ->where("EQMA_NOMB", '=', $request->NAME)
+                ->where("EQMA_IDEQ", '<>', $id_workteam)
+                ->where('EQMA_NULI', '=', $request->LINE_NUMBER)
+                ->first();
+
+            // Verifica si el objeto tiene algo
+            if (isset($search_workteam_name) && !empty($search_workteam_name)) {
+                return $this->response_controller
+                    ->makeResponse(TRUE, 'ERR_EQUIPO_TRABAJO_REG003: El nombre ya fue tomado', [], 500);
+            }
+
+            $user_register = DB::table('S002V01TUSUA_P')
+                ->select('USUA_IDUS as ID_USER')
+                ->where('USUA_IDUS', '=', $request->UPDATED_BY_USER)
+                ->where('USUA_NULI', '=', $request->LINE_NUMBER)
+                ->first();
+
+            // Verifica si el objeto esta vacio
+            if (!isset($user_register) && empty($user_register)) {
+                return $this->response_controller
+                    ->makeResponse(TRUE, "ERR_USUARIO_REG004: Tu usuario no es válido para actualizar equipos de trabajo", [], 500);
+            }
+
+            $update_workteam = DB::table('S002V01TEQMA')
+                ->where("EQMA_IDEQ", '=', $id_workteam)
+                ->where('EQMA_NULI', '=', $request->LINE_NUMBER)
+                ->update([
+                    "EQMA_NOMB" => $request->NAME,
+                    "EQMA_ESPE" => $request->SPECIALITY,
+                    "EQMA_ESTA" => "Activo",
+                    "EQMA_USMO" => $request->UPDATED_BY_USER,
+                    "EQMA_FEMO" => $UPDATE_DATE,
+                    "EQMA_FEAR" => DB::raw('CURRENT_TIMESTAMP')
+                ]);
+
+            if (!$update_workteam) {
+                return $this->response_controller
+                    ->makeResponse(TRUE, 'ERR_EQUIPO_TRABAJO_REG005: Algo salió mal, error actualizando al equipo de trabajo', [], 500);
+            }
+
+            return $this->response_controller
+                ->makeResponse(FALSE, 'Actualización exitosa');
+
+        } catch (Throwable $th) {
+            return $this->response_controller
+                ->makeResponse(TRUE, 'ERR_EQUIPO_TRABAJO_REG006: Error inesperado', strtoupper($th->getMessage()), 500);
+        }
+    }
+
+}
+
+/*
+try{
+} catch (Throwable $th) {
+return $this->response_controller
+->makeResponse(TRUE, 'ERR_INTERVEN_REG002: UNEXPECTED ERROR', strtoupper($th->getMessage()), 500);
+}
+*/
+
+/*
+DATOS OBLIGATORIOS
+$REGISTER_DATE = Carbon::now()->timezone('America/Mexico_City')->toDateTimeString();
+$UPDATE_DATE = Carbon::now()->timezone('America/Mexico_City')->toDateTimeString();
+"_ESTA" => $request->STATUS,
+"_USRE" => $request->REGISTER_USER,
+"_USMO" => $request->MODIFIED_USER,
+"_FERE" => $REGISTER_DATE,
+"_FEMO" => $UPDATE_DATE,
+"_FEAR" => DB::raw('CURRENT_TIMESTAMP')
+*/

A diferenza do arquivo foi suprimida porque é demasiado grande
+ 291 - 175
sistema-mantenimiento-back/composer.lock


+ 50 - 0
sistema-mantenimiento-back/routes/api.php

@@ -1,5 +1,9 @@
 <?php
 
+use App\Http\Controllers\EmployeeController;
+use App\Http\Controllers\InterventionController;
+use App\Http\Controllers\SubcontractController;
+use App\Http\Controllers\WorkTeamController;
 use Illuminate\Http\Request;
 use Illuminate\Support\Facades\Route;
 
@@ -117,3 +121,49 @@ Route::middleware(['jwt.auth'])->group(function(){
     Route::get("/get-file-info/{id}/{idUser}/{line}", "App\Http\Controllers\DocumentManagementController@getFileInfo");                   //Obtiene la información de un archivo en específico
     Route::get("/get-download-token/{idFile}/{idUser}/{line}", "App\Http\Controllers\DocumentManagementController@getDownloadToken");     //Permite generar un token para descargar un archivo
 });
+
+Route::controller(SubcontractController::class)->prefix('/subcontract')->group(function () {
+    Route::get('/consult/{line_number}',                                'getConsultOfSubcontratists');
+    Route::put('/inactive-subcontratist/{id_subcontratist}',            'updateToInactiveStatus');
+    Route::post('/',                                                    'storeSubcontratist');
+    Route::get('/subcontratist/{id_subcontratist}/{line_number}',       'getSubcontratistById');
+    Route::put('/{id_subcontratist}',                                   'updateSubcontratist');
+    Route::get('/subcontratist/{line_number}',                          'getAllSubcontratists');
+    Route::get('/contracts/subcontratists/{line_number}',               'getContractsOfEverySubcontratist');
+    Route::get('/contracts/history/{id_subcontratist}/{line_number}',   'getContractsBySubcontratist');
+    Route::post('/downoload-subcontract-info-Excel',                    'downoloadSubcontractInfoOnExcel');
+    Route::post('/downoload-subcontract-info-pdf',                      'downoloadSubcontractInfoOnPdf');
+});
+
+Route::controller(EmployeeController::class)->prefix('/employee')->group(function () {
+    Route::get('/consult/{line_number}',                                'getConsultOfEmployees');
+    Route::get('/documents/{id_employee}/{line_number}',                'getDocumentsByEmployee');
+    Route::get('/orders/{id_employee}/{line_number}',                   'getInterventionsByEmployee');
+    Route::put('/inactive-employee/{id_employee}',                      'updateToInactiveStatus');
+    Route::post('/',                                                    'storeEmployee');
+    Route::get('/{id_employee}/{line_number}',                          'getEmployeeById');
+    Route::get('/{line_number}',                                        'getAllEmployees');
+    Route::get('/contracts/employees/{line_number}',                    'getContractsOfEveryEmployee');
+    Route::get('/contracts/history/{id_employee}/{line_number}',        'getDetailsOfContractsByEmployee');
+    Route::post('/downoload-details-excel',                             'downoloadEmployeeInfoOnExcel');
+    Route::post('/downoload-details-pdf',                               'downoloadEmployeeInfoOnPdf');
+    Route::post('/{id_employee}',                                       'updateEmployee'); # Se cambia el metodo PUT a POST por problema en form-data con archivos
+});
+
+Route::controller(InterventionController::class)->prefix('/intervention')->group(function () {
+    Route::get('/consult/{line_number}',                                  'getConsultOfInterventions');
+    Route::get('/detail/{id_intervention}/{line_number}',                 'getDetailsOfInterventionsById');
+    Route::get('/contract/consult/{line_number}',                         'getConsultOfContracts');
+    Route::get('/contract/{id_intervention}/{line_number}',               'getContractById');
+    Route::post('/contract',                                              'storeContract');
+    Route::get('/contract/{line_number}',                                 'getAllContracts');
+});
+
+Route::controller(WorkTeamController::class)->prefix('/workteam')->group(function () {
+    Route::get('/{line_number}',                                          'getConsultOfWorkteams');
+    Route::get('/{id_workteam}/{line_number}',                            'getWorkteamById');
+    Route::get('/details/{id_workteam}/{line_number}',                    'getDetailsOfWorkteamById');
+    Route::put('/inactive-workteam/{id_workteam}',                        'updateToInactiveStatus');
+    Route::post('/',                                                      'storeWorkteam');
+    Route::put('/{id_workteam}',                                          'updateWorkteam');
+});

Algúns arquivos non se mostraron porque demasiados arquivos cambiaron neste cambio