Jelajahi Sumber

Actualización de los controladores del módulo de gestión de personal de mantenimiento

Jose Brito 2 tahun lalu
induk
melakukan
0d534bbc92

+ 1126 - 1492
sistema-mantenimiento-back/app/Http/Controllers/EmployeeController.php

@@ -1,9 +1,4 @@
 <?php
-/*
-Nombre del programador:         Cordourier Rojas Mathew
-Ultima fecha de modificación:   [ 24 / Abril / 2023 ]
-Descripción:                    Controlador del submodulo Personal. Perteneciente al Módulo 13 - Gestion del Personal de Mantenimiento
-*/
 
 namespace App\Http\Controllers;
 
@@ -13,1632 +8,1271 @@ use Illuminate\Support\Facades\DB;
 use Illuminate\Support\Facades\Storage;
 use Illuminate\Support\Facades\Validator;
 use PhpOffice\PhpSpreadsheet\IOFactory;
+use Illuminate\Database\Query\Builder;
 use PhpOffice\PhpSpreadsheet\Spreadsheet;
 use stdClass;
 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();
-
+class EmployeeController extends Controller{
+    private $responseController;
+    private $encryptionController;
+    private $documentManagementController;
+    private $functionsController;
+
+    public function __construct(){
+        $this->responseController = new ResponseController();
+        $this->encryptionController = new EncryptionController();
+        $this->documentManagementController = new DocumentManagementController();
+        $this->functionsController = new FunctionsController();
     }
 
-    // Metodo para obtener datos del personal
-    public function getConsultOfEmployees($line_number)
-    {
-        try {
-            $employees = DB::table('S002V01TPERS')
-                ->select(
-                    'S002V01TPERS.PERS_IDPE as ID_EMPLOYEE',
-                    DB::raw('TRIM(CONCAT(S002V01TUSUA.USUA_NOMB, " " , S002V01TUSUA.USUA_APPA, " ", COALESCE(S002V01TUSUA.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',
-                    'S002V01TPERS.PERS_ESTA as STATUS'
-                )
-                // ->where('S002V01TPERS.PERS_ESTA', '=', 'Activo')
-                ->where('S002V01TPERS.PERS_NULI', '=', $line_number)
-                ->where('S002V01TUSUA.USUA_NULI', '=', $line_number)
-                ->join('S002V01TUSUA', 'S002V01TPERS.PERS_IDUS', '=', 'S002V01TUSUA.USUA_IDUS')
-                ->get();
-
-            $users = DB::table('S002V01TUSUA')
-                ->select('USUA_IDUS as ID', DB::raw('TRIM(CONCAT(USUA_NOMB, " " , USUA_APPA, " ", COALESCE(USUA_APMA,""))) as NAME'))
-                ->where('USUA_NULI', '=', $line_number)
-                ->get();
-
-            $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();
-
-            foreach ($employees as $employee) {
-
-                // Introduce los equipos de trabajo a los que pertenece
-                foreach ($workteams as $workteam) {
-                    if ($employee->ID_EMPLOYEE == $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;
-                        }
-                    }
-                }
-
-                // 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");
-                }
-            }
-
-            return $this->response_controller
-                ->makeResponse(FALSE, "Consulta exitosa", $employees);
+    public function getConsultOfEmployees($idUser, $line) {
+        DB::enableQueryLog();
 
-
-        } catch (Throwable $th) {
-            return $this->response_controller
-                ->makeResponse(TRUE, 'ERR_PERSONAL_REG001: Error inesperado', strtoupper($th->getMessage()), 500);
+        $idUser = $this->encryptionController->decrypt($idUser);
+        if(!$idUser){
+            return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente', [], 400);
         }
-    }
 
-    // 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();
-
-            // Encripta la liga de cada documento
-            foreach ($documents_by_employee as $doc) {
-
-                $doc->DOCUMENT_NAME = $doc->DOCUMENT_LINK;
-                $doc->DOCUMENT_LINK = Storage::disk('pdf')->url($doc->DOCUMENT_LINK);
-                $doc->DOCUMENT_LINK = $this->encrypt_controller->encrypt($doc->DOCUMENT_LINK);
-            }
-
-            return $this->response_controller
-                ->makeResponse(FALSE, "Consulta exitosa", $documents_by_employee);
+        $usr = DB::table('S002V01TUSUA')->where([
+            ['USUA_NULI', '=', $line],
+            ['USUA_IDUS', '=', $idUser],
+        ])->first();
 
-
-        } catch (Throwable $th) {
-            return $this->response_controller
-                ->makeResponse(TRUE, 'ERR_PERSONAL_REG002: Error inesperado', strtoupper($th->getMessage()), 500);
+        if(is_null($usr)){
+            return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado', [], 404);
         }
-    }
-
-    public function getLastDocumentsByEmployee($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', 'DOCU_NUSE as SEQUENCE')
-                ->where('DOCU_IDPE', '=', $id_employee)
-                ->where('DOCU_NULI', '=', $line_number)
-                ->get();
-
-            // Busca los numeros de secuencia
-            $documents_sequence = DB::table('S002V01TDOCU_P')
-                ->select('DOCU_NUSE as SEQUENCE')
-                ->where('DOCU_IDPE', '=', $id_employee)
-                ->where('DOCU_NULI', '=', $line_number)
-                ->groupBy('DOCU_NUSE')
-                ->get();
-
-            $test = [];
-
-            for ($i = 0; $i < sizeof($documents_sequence); $i++) {
-                foreach ($documents_by_employee as $doc) {
-                    if ($doc->SEQUENCE == $documents_sequence[$i]->SEQUENCE) {
-                        if (isset($test[$i]) && !empty($test[$i])) {
-                            if (substr($doc->DOCUMENT_LINK, 25, 2) > substr($test[$i], 25, 2)) {
-                                $test[$i] = $doc->DOCUMENT_LINK;
-                            }
-                        } else {
-                            $test[$i] = $doc->DOCUMENT_LINK;
-                        }
-                    }
-                }
-            }
-
-            return $this->response_controller
-                ->makeResponse(FALSE, "Consulta exitosa", $test);
-
 
-        } catch (Throwable $th) {
-            return $this->response_controller
-                ->makeResponse(TRUE, 'ERR_PERSONAL_REG003: Error inesperado', strtoupper($th->getMessage()), 500);
-        }
+        $employees = DB::table('S002V01TPERS')->select([
+            'PERS_IDPE AS ID_EMPLOYEE',
+            DB::raw('TRIM(CONCAT(USUA_NOMB, " " , USUA_APPA, " ", COALESCE(USUA_APMA,""))) as NAME'),
+            'PERS_TICO AS CONTRACT_TYPE',
+            'PERS_ESPE AS SPECIALITY',
+            'PERS_EQTR AS TEAM_ID',
+            'EQMA_NOMB AS TEAM_NAME',
+            'PERS_FERE AS REGISTER_DATE',
+            'PERS_USRE AS REGISTERED_BY_USER',
+            'PERS_FEMO AS UPDATE_DATE',
+            'PERS_USMO AS UPDATED_BY_USER',
+            'PERS_ESTA AS STATUS'
+        ])->join('S002V01TUSUA', 'PERS_IDUS', '=', 'USUA_IDUS')
+        ->leftJoin('S002V01TEQMA', 'PERS_EQTR', '=', 'EQMA_IDEQ')
+        ->where('USUA_NULI', '=', $line)->get()->all();
+
+        $now = $this->functionsController->now();
+        $nowStr = $now->toDateTimeString();
+        $actions = DB::getQueryLog();
+        $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
+        
+        $idac = $this->functionsController->registerActivity(
+            $line,
+            'S002V01M11GPRS',
+            'S002V01F01GEPE',
+            'S002V01P01COEM',
+            'Consulta',
+            "El usuario $name (" . $usr->USUA_IDUS . ") consultó los empleados registrados.",
+            $idUser,
+            $nowStr,
+            'S002V01S02GEPE'
+        );
+
+        $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
+        return $this->responseController->makeResponse(false, 'EXITO', $employees);
     }
 
-    // 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();
-
-            return $this->response_controller
-                ->makeResponse(FALSE, "Consulta exitosa", $employee_interventions);
-
-        } catch (Throwable $th) {
-            return $this->response_controller
-                ->makeResponse(TRUE, 'ERR_PERSONAL_REG002: Error inesperado', strtoupper($th->getMessage()), 500);
+    public function storeEmployee(Request $request) {
+        DB::enableQueryLog();
+
+        $request['RFC'] = $this->encryptionController->decrypt($request->RFC) ? $this->encryptionController->decrypt($request->RFC) : 'ENC_ERR';
+        $request['TAX'] = $this->encryptionController->decrypt($request->TAX) ? $this->encryptionController->decrypt($request->TAX) : 'ENC_ERR';
+        $request['CONTACT_NAME'] = $this->encryptionController->decrypt($request->CONTACT_NAME) ? $this->encryptionController->decrypt($request->CONTACT_NAME) : 'ENC_ERR';
+        $request['CONTACT_TELEPHONE'] = $this->encryptionController->decrypt($request->CONTACT_TELEPHONE) ? $this->encryptionController->decrypt($request->CONTACT_TELEPHONE) : 'ENC_ERR';
+        $request['CONTACT_LADA'] = $this->encryptionController->decrypt($request->CONTACT_LADA) ? $this->encryptionController->decrypt($request->CONTACT_LADA) : 'ENC_ERR';
+        $request['CONTACT_ADDRESS'] = $this->encryptionController->decrypt($request->CONTACT_ADDRESS) ? $this->encryptionController->decrypt($request->CONTACT_ADDRESS) : 'ENC_ERR';
+
+        $validator = Validator::make($request->all(), [
+            'id_user' => 'required|string',
+            'linea' => 'required|integer',
+            'USER_ID' => 'required|string',
+            'WORKTEAM_ID' => 'required|string',
+            'CONTRACT_TYPE' => 'required|string|in:Subcontratista,Interno',
+            'SUBCONTRATIST_ID' => 'required_if:CONTRACT_TYPE,=,Subcontratista|string',
+            'SPECIALITY' => 'required|string|max:75',
+            'FOREIGNER' => 'required|string|in:Si,No',
+            'RFC' => 'required_if:FOREIGNER,=,No|string|max:13',
+            'TAX' => 'required_if:FOREIGNER,=,Si|string|max:13',
+            'COUNTRY' => 'required|string|max:75',
+            'FEDERAL_ENTITY' => 'required|string|max:75',
+            'CITY' => 'string|max:75',
+            'TOWN' => 'string|max:75',
+            'SUBURB' => 'required|string|max:75',
+            'POSTAL_CODE' => 'required|string|max:5',
+            'STREET' => 'required|string|max:150',
+            'EXTERIOR_NUMBER' => 'required|integer',
+            'INTERIOR_NUMBER' => 'integer',
+            'CONTACT_NAME' => 'required|string|max:150',
+            'CONTACT_LADA' => 'required|string|max:10',
+            'CONTACT_TELEPHONE' => 'required|string|max:11',
+            'CONTACT_ADDRESS' => 'required|string|max:250',
+            'ATTACHED' => 'required|json',
+        ]);
+
+        if($validator->fails()){
+            return $this->responseController->makeResponse(
+                TRUE,
+                'ERR_PERSONAL_REG001: Uno o más errores encontrados',
+                $this->responseController->makeErrors($validator->errors()->messages()),
+                400
+            );
         }
-    }
-
-    // Metodo para la eliminación logica de un empleado
-    public function updateToInactiveStatus(Request $request, $id_employee)
-    {
-        try {
-            $request['SAVED_BY_USER'] = $this->encrypt_controller->decrypt($request->SAVED_BY_USER);
-            $validator = Validator::make($request->all(), [
-                "SAVED_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')
-                ->select('USUA_IDUS as ID_USER')
-                ->where('USUA_IDUS', '=', $request->SAVED_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);
+        $form = $request->all();
+        foreach($form as $k=>$v){
+            if($k == 'INTERIOR_NUMBER' && $v == '0'){
+                unset($form[$k]);
+            }else if($v == '-'){
+                unset($form[$k]);
             }
+        }
 
-            // 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" => "Eliminado",
-                        "PERS_USMO" => trim($request->SAVED_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);
-                }
+        $idUser = $this->encryptionController->decrypt($form['id_user']);
+        if(!$idUser){
+            return $this->responseController->makeResponse(true, 'El ID de usuario no fue encriptado correctamente.', [], 400);
+        }
 
-                $delete_employee = DB::table('S002V01TPEEM')
-                    ->where('PEEM_IDPE', $id_employee)
-                    ->where('PEEM_NULI', '=', $request->LINE_NUMBER)
-                    ->update([
-                        "PEEM_ESTA" => "Eliminado",
-                        "PEEM_USMO" => trim($request->SAVED_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");
+        $usr = DB::table('S002V01TUSUA')->where([
+            ['USUA_NULI', '=', $form['linea']],
+            ['USUA_IDUS', '=', $idUser]
+        ])->first();
+        
+        if(is_null($usr)){
+            return $this->responseController->makeResponse(true, 'El usuario que realizó la petición no existe.', [], 404);
+        }
 
-        } catch (Throwable $th) {
-            return $this->response_controller
-                ->makeResponse(TRUE, 'ERR_PERSONAL_REG007: Error inesperado', strtoupper($th->getMessage()), 500);
+        $idUserReg = $this->encryptionController->decrypt($form['USER_ID']);
+        if(!$idUserReg){
+            return $this->responseController->makeResponse(true, 'El ID del usuario seleccionado no fue encriptado correctamente.', [], 400);
+        }else if($idUser == $idUserReg){
+            return $this->responseController->makeResponse(true, 'El usuario no puede registrarse a sí mismo.', [], 400);
+        }
+        
+        $usrReg = DB::table('S002V01TUSUA')->where([
+            ['USUA_NULI', '=', $form['linea']],
+            ['USUA_IDUS', '=', $idUserReg]
+        ])->first();
+        
+        if(is_null($usrReg)){
+            return $this->responseController->makeResponse(true, 'El usuario seleccionado no existe.', [], 404);
         }
-    }
 
-    // Metodo para la activación logica de un empleado
-    public function updateToActiveStatus(Request $request, $id_employee)
-    {
-        try {
-            $request['SAVED_BY_USER'] = $this->encrypt_controller->decrypt($request->SAVED_BY_USER);
-            $validator = Validator::make($request->all(), [
-                "SAVED_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
-                );
+        $idTeam = null;
+        if(isset($form['WORKTEAM_ID'])){
+            $idTeam = $this->encryptionController->decrypt($form['WORKTEAM_ID']);
+            if(!$idTeam){
+                return $this->responseController->makeResponse(true, 'El ID del equipo seleccionado encriptado correctamente.', [], 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);
+            $team = DB::table('S002V01TEQMA')->where([
+                ['EQMA_IDEQ', '=', $idTeam],
+                ['EQMA_NULI', '=', $form['linea']],
+            ])->first();
+        
+            if(is_null($team)){
+                return $this->responseController->makeResponse(true, 'El equipo seleccionado no existe.', [], 404);
+            }else if($team->EQMA_ESTA == 'Eliminado'){
+                return $this->responseController->makeResponse(true, 'El equipo seleccionado está eliminado.', [], 404);
             }
+        }
 
-            $user_register = DB::table('S002V01TUSUA')
-                ->select('USUA_IDUS as ID_USER')
-                ->where('USUA_IDUS', '=', $request->SAVED_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 activar empleados", [], 500);
+        $idSubcontratist = null;
+        if(isset($form['SUBCONTRATIST_ID'])){
+            $idSubcontratist = $this->encryptionController->decrypt($form['SUBCONTRATIST_ID']);
+            if(!$idSubcontratist){
+                return $this->responseController->makeResponse(true, 'El ID del subcontratista seleccionado no fue encriptado correctamente.', [], 400);
             }
 
-            $check_workteam = DB::table("S002V01TEQMA")
-                ->select("S002V01TEQMA.EQMA_ESTA as STATUS")
-                ->where("S002V01TPEEM.PEEM_IDPE", '=', $id_employee)
-                ->join('S002V01TPEEM', 'S002V01TEQMA.EQMA_IDEQ', '=', 'S002V01TPEEM.PEEM_IDEM')
-                ->first();
-
-            if ($check_workteam->STATUS == "Eliminado") {
-                return $this->response_controller
-                    ->makeResponse(TRUE, "ERR_EQUIPO_TRABAJO_REG004: El equipo de trabajo no esta activo", [], 500);
+            $subcontratist = DB::table('S002V01TPESU')->where([
+                ['PESU_IDPS', '=', $idSubcontratist],
+                ['PESU_NULI', '=', $form['linea']],
+            ])->first();
+        
+            if(is_null($subcontratist)){
+                return $this->responseController->makeResponse(true, 'El subcontratista seleccionado no existe.', [], 404);
             }
+        }
 
-            DB::beginTransaction(); # Para impedir que las actualizaciones queden incompletas
-
-            $UPDATE_DATE = Carbon::now()->timezone('America/Mexico_City')->toDateTimeString();
-
-            $activate_employee = DB::table('S002V01TPERS')
-                ->where('PERS_IDPE', $id_employee)
-                ->where('PERS_NULI', '=', $request->LINE_NUMBER)
-                ->update([
-                    "PERS_ESTA" => "Activo",
-                    "PERS_USMO" => trim($request->SAVED_BY_USER),
-                    "PERS_FEMO" => $UPDATE_DATE,
-                    "PERS_FEAR" => DB::raw('CURRENT_TIMESTAMP')
-                ]);
+        $rfcx = null;
+        if(isset($form['RFC']) && $form['FOREIGNER'] == 'No' && $form['RFC'] == 'ENC_ERR'){
+            return $this->responseController->makeResponse(true, 'El RFC no fue encriptado correctamente.', [], 400);
+        }else if(isset($form['RFC']) && $form['RFC'] != 'ENC_ERR'){
+            $rfcx = $form['RFC'];
+        }
 
-            // Verifica que la actualización fuera exitosa
-            if ($activate_employee < 1) {
-                return $this->response_controller
-                    ->makeResponse(TRUE, 'ERR_PERSONAL_REG005: Algo salió mal, error activando al empleado', [], 500);
-            }
+        $taid = null;
+        if(isset($form['TAX']) && $form['FOREIGNER'] == 'Si' && $form['TAX'] == 'ENC_ERR'){
+            return $this->responseController->makeResponse(true, 'El TAX ID no fue encriptado correctamente.', [], 400);
+        }else if(isset($form['TAX']) && $form['TAX'] != 'ENC_ERR'){
+            $taid =  $form['TAX'];
+        }
+        
+        $country = DB::table('S002V01TPAIS')->where([
+            ['PAIS_NULI', '=', $form['linea']],
+            ['PAIS_IDPA', '=', $form['COUNTRY']],
+        ])->first();
+        
+        if(is_null($country)){
+            return $this->responseController->makeResponse(true, 'El país seleccionado no existe.', [], 404);
+        }
 
-            $activate_employee = DB::table('S002V01TPEEM')
-                ->where('PEEM_IDPE', $id_employee)
-                ->where('PEEM_NULI', '=', $request->LINE_NUMBER)
-                ->update([
-                    "PEEM_ESTA" => "Activo",
-                    "PEEM_USMO" => trim($request->SAVED_BY_USER),
-                    "PEEM_FEMO" => $UPDATE_DATE,
-                    "PEEM_FEAR" => DB::raw('CURRENT_TIMESTAMP')
-                ]);
-
-            // Verifica que la actualización fuera exitosa
-            if ($activate_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 activando al empleado del equipo', [], 500);
+        $colo = null;
+        $ciud = null;
+        $loca = null;
+        if($form['COUNTRY'] == 'MEX' || $form['COUNTRY'] == 'USA' || $form['COUNTRY'] == 'CAN'){
+            $state = DB::table('S002V01TESTA')->where([
+                ['ESTA_NULI', '=', $form['linea']],
+                ['ESTA_COES', '=', $form['FEDERAL_ENTITY']],
+                ['ESTA_COPA', '=', $form['COUNTRY']],
+            ])->first();
+        
+            if(is_null($state)){
+                return $this->responseController->makeResponse(true, 'El estado seleccionado no existe.', [], 404);
             }
 
-            DB::commit(); # Para guardar los cambios en la base de datos
-            return $this->response_controller->makeResponse(FALSE, "Activación exitosa");
-
-        } catch (Throwable $th) {
-            return $this->response_controller->
-                makeResponse(TRUE, 'ERR_PERSONAL_REG007: Error inesperado', strtoupper($th->getMessage()), 500);
-        }
-    }
+            if($form['COUNTRY'] == 'MEX'){
+                if(isset($form['CITY'])){
+                    $city = DB::table('S002V01TMUNI')->where([
+                        ['MUNI_NULI', '=', $form['linea']],
+                        ['MUNI_COMU', '=', $form['CITY']],
+                        ['MUNI_COES', '=', $form['FEDERAL_ENTITY']],
+                    ])->first();
+            
+                    if(is_null($city)){
+                        return $this->responseController->makeResponse(true, 'El municipio seleccionado no existe.', [], 404);
+                    }else{
+                        $ciud = $form['CITY'];
+                    }
+                }
 
-    // Metodo para obtener a los usuarios que no son empleados y el enviado por path
-    public function getAvaibleUsers($id_employee, $line_number)
-    {
-
-        try {
-
-            // Busca en la base si existe otro empleado con ese usuario
-            $users = DB::table('S002V01TUSUA')
-                ->select(
-                    DB::raw('TRIM(CONCAT(USUA_NOMB, " " , USUA_APPA, " ", COALESCE(USUA_APMA,""))) as NAME'),
-                    "USUA_IDUS as ID_USER"
-                )
-                ->orderBy('NAME', 'asc')
-                ->where('USUA_NULI', '=', $line_number)
-                ->where('USUA_ESTA', '=', "Activo")
-                ->get();
-
-            $employees = DB::table('S002V01TPERS')
-                ->select("PERS_IDUS as ID_USER")
-                ->where('PERS_NULI', '=', $line_number)
-                ->get();
-
-            $avaibleUsers = [];
-
-            foreach ($users as $user) {
-                foreach ($employees as $employee) {
-                    if ($user->ID_USER == $employee->ID_USER) {
-                        $user->ID_USER = "XXXX";
+                if(isset($form['TOWN'])){
+                    $town = DB::table('S002V01TLOCA')->where([
+                        ['LOCA_NULI', '=', $form['linea']],
+                        ['LOCA_COLO', '=', $form['TOWN']],
+                        ['LOCA_COES', '=', $form['FEDERAL_ENTITY']],
+                    ])->first();
+            
+                    if(is_null($town)){
+                        return $this->responseController->makeResponse(true, 'La localidad seleccionada no existe.', [], 404);
+                    }else{
+                        $loca = $form['TOWN'];
                     }
                 }
-                if ($user->ID_USER != "XXXX") {
-                    $avaibleUsers[] = $user;
+                
+                $setting = DB::table('S002V01TCOLO')->where([
+                    ['COLO_NULI', '=', $form['linea']],
+                    ['COLO_COCO', '=', $form['SUBURB']],
+                    ['COLO_COPO', '=', $form['POSTAL_CODE']],
+                ])->first();
+            
+                if(is_null($setting)){
+                    return $this->responseController->makeResponse(true, 'La colonia seleccionada no existe.', [], 404);
+                }else{
+                    $colo = $form['SUBURB'];
                 }
+                
+                $zipCode = DB::table('S002V01TCOPO')->where([
+                    ['COPO_NULI', '=', $form['linea']],
+                    ['COPO_COPO', '=', $form['POSTAL_CODE']],
+                    ['COPO_COES', '=', $form['FEDERAL_ENTITY']],
+                ])->first();
+            
+                if(is_null($zipCode)){
+                    return $this->responseController->makeResponse(true, 'El código postal seleccionado no existe.', [], 404);
+                }
+            }else{
+                $colo = $form['SUBURB'];
+                $ciud = $form['CITY'];
+                $loca = isset($form['TOWN']) ? $form['TOWN'] : null;
             }
-
-            // Busca en la base el empleado requerido
-            if ($id_employee != "0") {
-                $employeSelected = DB::table('S002V01TPERS')
-                    ->select(
-                        DB::raw('TRIM(CONCAT(S002V01TUSUA.USUA_NOMB, " " , S002V01TUSUA.USUA_APPA, " ", COALESCE(S002V01TUSUA.USUA_APMA,""))) as NAME'),
-                        "S002V01TUSUA.USUA_IDUS as ID_USER"
-                    )
-                    ->where('S002V01TUSUA.USUA_NULI', '=', $line_number)
-                    ->where('S002V01TPERS.PERS_NULI', '=', $line_number)
-                    ->where('S002V01TPERS.PERS_IDPE', '=', $id_employee)
-                    ->join('S002V01TUSUA', 'S002V01TPERS.PERS_IDUS', '=', 'S002V01TUSUA.USUA_IDUS')
-                    ->first();
-
-                $avaibleUsers[] = $employeSelected;
-            }
-
-            return $this->response_controller->makeResponse(FALSE, 'Usuarios obtenidos', $avaibleUsers, 200);
-
-        } catch (Throwable $th) {
-            return $this->response_controller
-                ->makeResponse(TRUE, 'ERR_PERSONAL_REG001: Error inesperado', strtoupper($th), 500);
+        }else{
+            $colo = $form['SUBURB'];
+            $ciud = $form['CITY'];
+            $loca = isset($form['TOWN']) ? $form['TOWN'] : null;
         }
-    }
-
-    // Metodo para guardar un nuevo empleado
-    public function storeEmployee(Request $request)
-    {
-
-        try {
-            $REGISTER_DATE = Carbon::now()->timezone('America/Mexico_City')->toDateTimeString();
-            $request['SAVED_BY_USER'] = $this->encrypt_controller->decrypt($request->SAVED_BY_USER);
-            $request['CONTACT_NAME'] = $this->encrypt_controller->decrypt($request->CONTACT_NAME);
-            $request['CONTACT_TELEPHONE'] = $this->encrypt_controller->decrypt($request->CONTACT_TELEPHONE);
-            $request['CONTACT_LADA'] = $this->encrypt_controller->decrypt($request->CONTACT_LADA);
-            $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_LADA" => ['required', 'max:5'],
-                "CONTACT_ADDRESS" => ['required', 'max:100'],
-                "CONTRACT_TYPE" => ['required'],
-                "SPECIALITY" => ['required', 'max:75'],
-                "SUBCONTRATIST_ID" => ['max:10'],
-                "SAVED_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', '=', $request->LINE_NUMBER)
-                ->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')
-                ->select("USUA_IDUS")
-                ->where('USUA_IDUS', '=', $request->USER_ID)
-                ->where('USUA_NULI', '=', $request->LINE_NUMBER)
-                ->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', '=', $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_REG004: No se encontró al equipo de trabajo', [], 500);
-            }
-
-            $user_register = DB::table('S002V01TUSUA')
-                ->select('USUA_IDUS as ID_USER')
-                ->where('USUA_IDUS', '=', $request->SAVED_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_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_LATC" => $request->CONTACT_LADA,
-                    "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->SAVED_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', '=', $request->LINE_NUMBER)
-                ->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->SAVED_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_AUTHO) && !empty($request->DOCUMENTS_AUTHO)) {
-                $doc = $request->DOCUMENTS_AUTHO;
-
-
-                // Se obtiene el nombre del archivo con su extensión
-                $completeFileName = $doc->getClientOriginalName();
-                // Se obtiene únicamente el nombre
-                $fileNameOnly = pathinfo($completeFileName, PATHINFO_FILENAME) . '-' . $employee_id;
-
-                // Se obtiene la extensión del archivo
-                $extension = $doc->getClientOriginalExtension();
-                if ($extension != "pdf") {
-                    return $this->response_controller
-                        ->makeResponse(TRUE, 'ERR_DOCUMENTO_REG007: Solo se permiten archivos PDF', [], 500);
-                }
-
-                // Se quitan los espacios y se concatena datos para ser guardado
-                $final_part_name_document = str_replace(' ', '_', $fileNameOnly) . '.' . $extension;
-
-                $name_document = $this->documents_controller->createDocument(
-                    "GPRS",
-                    "IN",
-                    $final_part_name_document,
-                    $employee_id,
-                    'pdf',
-                    $request->LINE_NUMBER,
-                    $request->SAVED_BY_USER
-                );
-
-                // El documento es guardado en el storage
-                $doc->storeAs('public/pdf_documents', $name_document);
+        $subArr = DB::table('S002V01TPERS')->where('PERS_NULI', '=', $form['linea'])->where(function(Builder $query) use ($form, $idUserReg) {
+            $query->where('PERS_IDUS', '=', $idUserReg)
+            ->orWhere('PERS_XRFC', '=', $form['RFC']);
+        })->where('PERS_ESTA', '=', 'Activo')->get()->all();
 
+        if(count($subArr) > 0){
+            return $this->responseController->makeResponse(true, 'La razón social, el RFC o el correo electrónico ya fueron registrados.', [], 401);
+        }
 
+        $ladasValues = [];
+        $ladas = DB::table('S002V01TPAIS')->select([
+            'PAIS_LADA AS LADA'
+        ])->where('PAIS_NULI', '=', $form['linea'])->get()->all();
 
+        foreach($ladas as $lada){
+            if($lada->LADA != '' && $lada->LADA != '0'){
+                $ladasValues[] = $lada->LADA;
             }
+        }
 
-            // Verifica si el objeto esta vacio
-            if (isset($request->DOCUMENTS_AUTHO2) && !empty($request->DOCUMENTS_AUTHO2)) {
-                $doc = $request->DOCUMENTS_AUTHO2;
-
-                // Se obtiene el nombre del archivo con su extensión
-                $completeFileName = $doc->getClientOriginalName();
-                // Se obtiene únicamente el nombre
-                $fileNameOnly = pathinfo($completeFileName, PATHINFO_FILENAME) . '-' . $employee_id;
+        if($form['CONTACT_LADA'] == 'ENC_ERR'){
+            return $this->responseController->makeResponse(true, "La lada del contacto de emergencia no fue encriptada correctamente.", [], 400);
+        }else if(!in_array($form['CONTACT_LADA'], $ladasValues)){
+            return $this->responseController->makeResponse(true, "La lada $form[CONTACT_LADA] no está relacionada a ningún país.", [], 400);
+        }else if($form['CONTACT_TELEPHONE'] == 'ENC_ERR'){
+            return $this->responseController->makeResponse(true, 'El número telefónico del contacto de emergencia no fue encriptado correctamente.', [], 400);
+        }
 
-                // Se obtiene la extensión del archivo
-                $extension = $doc->getClientOriginalExtension();
-                if ($extension != "pdf") {
-                    return $this->response_controller
-                        ->makeResponse(TRUE, 'ERR_DOCUMENTO_REG008: Solo se permiten archivos PDF', [], 500);
-                }
+        if($form['CONTACT_ADDRESS'] == 'ENC_ERR'){
+            return $this->responseController->makeResponse(true, "La dirección del contacto de emergencia no fue encriptada correctamente.", [], 400);
+        }
 
-                // Se quitan los espacios y se concatena datos para ser guardado
-                $final_part_name_document = str_replace(' ', '_', $fileNameOnly) . '.' . $extension;
+        if($form['CONTACT_NAME'] == 'ENC_ERR'){
+            return $this->responseController->makeResponse(true, "El nombre del contacto de emergencia no fue encriptada correctamente.", [], 400);
+        }
 
-                $name_document = $this->documents_controller->createDocument(
-                    "GPRS",
-                    "IN",
-                    $final_part_name_document,
-                    $employee_id,
-                    'pdf',
-                    $request->LINE_NUMBER,
-                    $request->SAVED_BY_USER
-                );
+        $docsArr = json_decode($form['ATTACHED'], true);
+        if(count($docsArr) == 0){
+            return $this->responseController->makeResponse(true, "El arreglo de archivos adjuntos está vacío.", [], 400);
+        }
 
-                // El documento es guardado en el storage
-                $doc->storeAs('public/pdf_documents', $name_document);
+        $authCont = 0;
+        foreach($docsArr as $doc){
+            if($doc['type'] == 'AU') $authCont++;
+        }
 
+        if($authCont < 1){
+            return $this->responseController->makeResponse(true, "El arreglo de archivos adjuntos debe contener al menos un documento de autorización.", [], 400);
+        }
 
+        $finalDocsArr = [];
+        foreach($docsArr as $doc){
+            $idFileDec = $this->encryptionController->decrypt($doc['id']);
+            $tempFile = DB::table('S002V01TARTE')->where([
+                ['ARTE_NULI', '=', $form['linea']],
+                ['ARTE_IDAR', '=', $idFileDec],
+            ])->first();
 
+            if(is_null($tempFile)){
+                return $this->responseController->makeResponse(true, "El archivo $doc[name] no está registrado.", [], 404);
             }
 
-            // Verifica si el objeto esta vacio
-            if (isset($request->DOCUMENTS_CERT) && !empty($request->DOCUMENTS_CERT)) {
-                $doc = $request->DOCUMENTS_CERT;
-
-                // Se obtiene el nombre del archivo con su extensión
-                $completeFileName = $doc->getClientOriginalName();
-                // Se obtiene únicamente el nombre
-                $fileNameOnly = pathinfo($completeFileName, PATHINFO_FILENAME) . '-' . $employee_id;
-
-                // Se obtiene la extensión del archivo
-                $extension = $doc->getClientOriginalExtension();
-                if ($extension != "pdf") {
-                    return $this->response_controller
-                        ->makeResponse(TRUE, 'ERR_DOCUMENTO_REG009: Solo se permiten archivos PDF', [], 500);
-                }
-
-                // Se quitan los espacios y se concatena datos para ser guardado
-                $final_part_name_document = str_replace(' ', '_', $fileNameOnly) . '.' . $extension;
-
-                $name_document = $this->documents_controller->createDocument(
-                    "GPRS",
-                    "CE",
-                    $final_part_name_document,
-                    $employee_id,
-                    'pdf',
-                    $request->LINE_NUMBER,
-                    $request->SAVED_BY_USER
-                );
-
-                // El documento es guardado en el storage
-                $doc->storeAs('public/pdf_documents', $name_document);
-
-
-
+            $classifications = ["AU" => "IN", "OF" => "CO", "CE" => "CE"];
+            $cldo = $classifications[$doc['type']];
+            $finalFile = $this->documentManagementController->moveFinalFile($form['linea'], "GPRS", $cldo, $tempFile, $idUser);
+
+            if(!$finalFile[0]){
+                return $this->responseController->makeResponse(true, $finalFile[1], [], 400);
+            }else{
+                $finalDocsArr[] = [
+                    'CODE' => $finalFile[1],
+                    'TYPE' => $doc['type']
+                ];
             }
+        }
 
-            // Verifica si el objeto esta vacio
-            if (isset($request->DOCUMENTS_CERT2) && !empty($request->DOCUMENTS_CERT2)) {
-                $doc = $request->DOCUMENTS_CERT2;
-
-                // Se obtiene el nombre del archivo con su extensión
-                $completeFileName = $doc->getClientOriginalName();
-                // Se obtiene únicamente el nombre
-                $fileNameOnly = pathinfo($completeFileName, PATHINFO_FILENAME) . '-' . $employee_id;
-
-                // Se obtiene la extensión del archivo
-                $extension = $doc->getClientOriginalExtension();
-                if ($extension != "pdf") {
-                    return $this->response_controller
-                        ->makeResponse(TRUE, 'ERR_DOCUMENTO_REG010: Solo se permiten archivos PDF', [], 500);
-                }
-
-                // Se quitan los espacios y se concatena datos para ser guardado
-                $final_part_name_document = str_replace(' ', '_', $fileNameOnly) . '.' . $extension;
-
-                $name_document = $this->documents_controller->createDocument(
-                    "GPRS",
-                    "CE",
-                    $final_part_name_document,
-                    $employee_id,
-                    'pdf',
-                    $request->LINE_NUMBER,
-                    $request->SAVED_BY_USER
-                );
-
-                // El documento es guardado en el storage
-                $doc->storeAs('public/pdf_documents', $name_document);
-
-
-
-            }
+        $now = $this->functionsController->now();
+        $nowStr = $now->toDateTimeString();
+        $doas = json_encode($finalDocsArr);
+        $nuin = isset($form['INTERIOR_NUMBER']) ? $form['INTERIOR_NUMBER'] : null;
+        $employeeID = DB::table('S002V01TPERS')->insertGetId([
+            'PERS_NULI' => $form['linea'],
+            'PERS_IDUS' => $idUserReg,
+            'PERS_EQTR' => $idTeam,
+            'PERS_TICO' => $form['CONTRACT_TYPE'],
+            'PERS_IDPS' => $idSubcontratist,
+            'PERS_ESPE' => $form['SPECIALITY'],
+            'PERS_EXTR' => $form['FOREIGNER'],
+            'PERS_XRFC' => $rfcx,
+            'PERS_TAID' => $taid,
+            'PERS_IDPA' => $form['COUNTRY'],
+            'PERS_ENFE' => $form['FEDERAL_ENTITY'],
+            'PERS_CIUD' => $ciud,
+            'PERS_LOCA' => $loca,
+            'PERS_COLO' => $colo,
+            'PERS_COPO' => $form['POSTAL_CODE'],
+            'PERS_CALL' => $form['STREET'],
+            'PERS_NUEX' => $form['EXTERIOR_NUMBER'],
+            'PERS_NUIN' => $nuin,
+            'PERS_NOCE' => $form['CONTACT_NAME'],
+            'PERS_LCEM' => $form['CONTACT_LADA'],
+            'PERS_NUTC' => $form['CONTACT_TELEPHONE'],
+            'PERS_DCEM' => $form['CONTACT_ADDRESS'],
+            'PERS_DOAS' => $doas,
+            'PERS_USRE' => $idUser,
+            'PERS_FERE' => $nowStr,
+        ]);
+
+        $actions = DB::getQueryLog();
+        $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
+        $nameEmp = $this->functionsController->joinName($usrReg->USUA_NOMB, $usrReg->USUA_APPA, $usrReg->USUA_APMA);
+        
+        $idac = $this->functionsController->registerActivity(
+            $form['linea'],
+            'S002V01M11GPRS',
+            'S002V01F01GEPE',
+            'S002V01P02REEM',
+            'Registro',
+            "El usuario $name (" . $usr->USUA_IDUS . ") registró al empleado " . $nameEmp . "($employeeID).",
+            $idUser,
+            $nowStr,
+            'S002V01S02GEPE'
+        );
+
+        $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']);
+        return $this->responseController->makeResponse(false, 'EXITO');
+    }
 
-            // Verifica si el objeto esta vacio
-            if (isset($request->DOCUMENT_OFFICE) && !empty($request->DOCUMENT_OFFICE)) {
-                $doc = $request->DOCUMENT_OFFICE;
+    public function getEmployeeById($idEmployee, $idUser, $line) {
+        DB::enableQueryLog();
 
-                // Se obtiene el nombre del archivo con su extensión
-                $completeFileName = $doc->getClientOriginalName();
-                // Se obtiene únicamente el nombre
-                $fileNameOnly = pathinfo($completeFileName, PATHINFO_FILENAME) . '-' . $employee_id;
+        $idUser = $this->encryptionController->decrypt($idUser);
+        if(!$idUser){
+            return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente', [], 400);
+        }
 
-                // Se obtiene la extensión del archivo
-                $extension = $doc->getClientOriginalExtension();
-                if ($extension != "pdf") {
-                    return $this->response_controller
-                        ->makeResponse(TRUE, 'ERR_DOCUMENTO_REG011: Solo se permiten archivos PDF', [], 500);
-                }
+        $usr = DB::table('S002V01TUSUA')->where([
+            ['USUA_NULI', '=', $line],
+            ['USUA_IDUS', '=', $idUser],
+        ])->first();
 
-                // Se quitan los espacios y se concatena datos para ser guardado
-                $final_part_name_document = str_replace(' ', '_', $fileNameOnly) . '.' . $extension;
+        if(is_null($usr)){
+            return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado', [], 404);
+        }
 
-                $name_document = $this->documents_controller->createDocument(
-                    "GPRS",
-                    "CO",
-                    $final_part_name_document,
-                    $employee_id,
-                    'pdf',
-                    $request->LINE_NUMBER,
-                    $request->SAVED_BY_USER
-                );
+        $idEmployee = $this->encryptionController->decrypt($idEmployee);
+        if(!$idEmployee){
+            return $this->responseController->makeResponse(true, 'El ID del empleado solicitado no está encriptado correctamente', [], 400);
+        }
 
-                // El documento es guardado en el storage
-                $doc->storeAs('public/pdf_documents', $name_document);
+        $employee = DB::table('S002V01TPERS')->select([
+            'PERS_IDPE AS ID_EMPLOYEE',
+            DB::raw('TRIM(CONCAT(USUA_NOMB, " " , USUA_APPA, " ", COALESCE(USUA_APMA,""))) as EMPLOYEE_NAME'),
+            'PERS_IDUS AS USER_ID',
+            'EQMA_IDEQ AS WORKTEAM_ID',
+            'EQMA_NOMB AS WORKTEAM_NAME',
+            'PERS_TICO AS CONTRACT_TYPE',
+            'PERS_IDPS AS SUBCONTRATIST_ID',
+            'PESU_RASO AS SUBCONTRATIST_NAME',
+            'PESU_REFI AS TAX_REGIME',
+            'REFI_DRFI AS TAX_REGIME_DESCRIPTION',
+            'PERS_ESPE AS SPECIALITY',
+            'PERS_EXTR AS FOREIGNER',
+            'PERS_XRFC AS RFC',
+            'PERS_TAID AS TAX_ID',
+            'PERS_IDPA AS COUNTRY',
+            'PERS_ENFE AS STATE',
+            'PERS_CIUD AS CITY',
+            'PERS_LOCA AS TOWN',
+            'PERS_COLO AS SETTING',
+            'PERS_COPO AS ZIP_CODE',
+            'PERS_CALL AS STREET',
+            'PERS_NUEX AS EXTERIOR_NUMBER',
+            'PERS_NUIN AS INTERIOR_NUMBER',
+            'PERS_NOCE AS CONTACT_NAME',
+            'PERS_LCEM AS CONTACT_LADA',
+            'PERS_NUTC AS CONTACT_TELEPHONE',
+            'PERS_DCEM AS CONTACT_ADDRESS',
+            'PERS_DOAS AS DOCUMENTS',
+            'PERS_ESTA AS STATUS',
+            'PERS_USRE AS USRREG',
+            'PERS_USMO AS USRMOD',
+            'PERS_FERE AS FECREG',
+            'PERS_FEMO AS FECMOD',
+        ])->leftJoin('S002V01TEQMA', 'EQMA_IDEQ', '=', 'PERS_EQTR')
+        ->leftJoin('S002V01TPESU', 'PESU_IDPS', '=', 'PERS_IDPS')
+        ->leftJoin('S002V01TREFI', 'REFI_CRFI', '=', 'PESU_REFI')
+        ->join('S002V01TUSUA', 'PERS_IDUS', '=', 'USUA_IDUS')->where([
+            ['PERS_NULI', '=', $line],
+            ['PERS_IDPE', '=', $idEmployee],
+        ])->first();
+
+        $attached = [];
+        $docsArr = json_decode($employee->DOCUMENTS, true);
+        foreach($docsArr as $doc){
+            $docArr = explode('=', $doc['CODE']);
+            $codeArr = explode('-', $docArr[0]);
+
+            $document = DB::table('S002V01TAFAL')->select([
+                'AFAL_NOAR AS FILE_NAME',
+                'AFAL_EXTE AS FILE_EXTENSION',
+                'AFAL_TAMA AS FILE_SIZE',
+                'AFAL_ESTA AS FILE_STATUS'
+            ])->where([
+                ['AFAL_NULI', '=', $line],
+                ['AFAL_COMO', '=', $codeArr[1]],
+                ['AFAL_CLDO', '=', $codeArr[2]],
+                ['AFAL_FECR', '=', $codeArr[3]],
+                ['AFAL_NUSE', '=', $codeArr[4]],
+                ['AFAL_NUVE', '=', $docArr[1]],
+            ])->first();
+
+            $document->FILE_ID = $this->encryptionController->encrypt($doc['CODE']);
+            $document->FILE_TYPE = $doc['TYPE'];
+            $attached[] = $document;
+        }
 
-            }
+        $employee->DOCUMENTS = json_encode($attached);
+        $country = DB::table('S002V01TPAIS')->where([
+            ['PAIS_NULI', '=', $line],
+            ['PAIS_IDPA', '=', $employee->COUNTRY]
+        ])->first();
+
+        $state = DB::table('S002V01TESTA')->where([
+            ['ESTA_NULI', '=', $line],
+            ['ESTA_COES', '=', $employee->STATE],
+            ['ESTA_COPA', '=', $employee->COUNTRY]
+        ])->first();
+
+        $city = DB::table('S002V01TMUNI')->where([
+            ['MUNI_NULI', '=', $line],
+            ['MUNI_COMU', '=', $employee->CITY],
+            ['MUNI_COES', '=', $employee->STATE],
+        ])->first();
+
+        $town = DB::table('S002V01TLOCA')->where([
+            ['LOCA_NULI', '=', $line],
+            ['LOCA_COLO', '=', $employee->TOWN],
+            ['LOCA_COES', '=', $employee->STATE],
+        ])->first();
+
+        $setting = DB::table('S002V01TCOLO')->where([
+            ['COLO_NULI', '=', $line],
+            ['COLO_COCO', '=', $employee->SETTING],
+            ['COLO_COPO', '=', $employee->ZIP_CODE],
+        ])->first();
+
+        $employee->COUNTRY = $country->PAIS_NOMB . " (" . $employee->COUNTRY . ")";
+        $employee->STATE = is_null($state) ? $employee->STATE : $state->ESTA_NOES . " (" . $employee->STATE . ")";
+        $employee->CITY = is_null($city) ? $employee->CITY : $city->MUNI_NOMU . " (" . $employee->CITY . ")";
+        $employee->TOWN = is_null($town) ? $employee->TOWN : $town->LOCA_NOLO . " (" . $employee->TOWN . ")";
+        $employee->SETTING = is_null($setting) ? $employee->SETTING : $setting->COLO_NOCO . " (" . $employee->SETTING . ")";
+
+        $usrReg = DB::table('S002V01TUSUA')->where([
+            ['USUA_NULI', '=', $line],
+            ['USUA_IDUS', '=', $employee->USRREG]
+        ])->first();
+
+        $nameReg = $this->functionsController->joinName($usrReg->USUA_NOMB, $usrReg->USUA_APPA, $usrReg->USUA_APMA);
+        $employee->USRREG = "$nameReg (" . $employee->USRREG . ")";
+
+        if(!is_null($employee->USRMOD)){
+            $usrMod = DB::table('S002V01TUSUA')->where([
+                ['USUA_NULI', '=', $line],
+                ['USUA_IDUS', '=', $employee->USRMOD]
+            ])->first();
+
+            $nameMod = $this->functionsController->joinName($usrMod->USUA_NOMB, $usrMod->USUA_APPA, $usrMod->USUA_APMA);
+            $employee->USRMOD = "$nameMod (" . $employee->USRMOD . ")";
+        }
 
-            DB::commit(); # Para guardar los cambios en la base de datos
-            return $this->response_controller->makeResponse(FALSE, 'Creación exitosa', 200);
+        $now = $this->functionsController->now();
+        $nowStr = $now->toDateTimeString();
+        $actions = DB::getQueryLog();
+        $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
+        
+        $idac = $this->functionsController->registerActivity(
+            $line,
+            'S002V01M11GPRS',
+            'S002V01F01GEPE',
+            'S002V01P03DEEM',
+            'Consulta',
+            "El usuario $name (" . $usr->USUA_IDUS . ") consultó al empleado " . $employee->EMPLOYEE_NAME . " ($idEmployee).",
+            $idUser,
+            $nowStr,
+            'S002V01S02GEPE'
+        );
+
+        $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
+        return $this->responseController->makeResponse(false, 'EXITO', $employee);
+    }
 
-        } catch (Throwable $th) {
-            return $this->response_controller
-                ->makeResponse(TRUE, 'ERR_PERSONAL_REG012: Error inesperado', strtoupper($th), 500);
+    public function updateEmployee(Request $request) {
+        DB::enableQueryLog();
+
+        $request['RFC'] = $this->encryptionController->decrypt($request->RFC) ? $this->encryptionController->decrypt($request->RFC) : 'ENC_ERR';
+        $request['TAX'] = $this->encryptionController->decrypt($request->TAX) ? $this->encryptionController->decrypt($request->TAX) : 'ENC_ERR';
+        $request['CONTACT_NAME'] = $this->encryptionController->decrypt($request->CONTACT_NAME) ? $this->encryptionController->decrypt($request->CONTACT_NAME) : 'ENC_ERR';
+        $request['CONTACT_TELEPHONE'] = $this->encryptionController->decrypt($request->CONTACT_TELEPHONE) ? $this->encryptionController->decrypt($request->CONTACT_TELEPHONE) : 'ENC_ERR';
+        $request['CONTACT_LADA'] = $this->encryptionController->decrypt($request->CONTACT_LADA) ? $this->encryptionController->decrypt($request->CONTACT_LADA) : 'ENC_ERR';
+        $request['CONTACT_ADDRESS'] = $this->encryptionController->decrypt($request->CONTACT_ADDRESS) ? $this->encryptionController->decrypt($request->CONTACT_ADDRESS) : 'ENC_ERR';
+
+        $validator = Validator::make($request->all(), [
+            'id_user' => 'required|string',
+            'linea' => 'required|integer',
+            'id_employee' => 'required|string',
+            'USER_ID' => 'required|string',
+            'WORKTEAM_ID' => 'required|string',
+            'CONTRACT_TYPE' => 'required|string|in:Subcontratista,Interno',
+            'SUBCONTRATIST_ID' => 'required_if:CONTRACT_TYPE,=,Subcontratista|string',
+            'SPECIALITY' => 'required|string|max:75',
+            'FOREIGNER' => 'required|string|in:Si,No',
+            'RFC' => 'required_if:FOREIGNER,=,No|string|max:13',
+            'TAX' => 'required_if:FOREIGNER,=,Si|string|max:13',
+            'COUNTRY' => 'required|string|max:75',
+            'FEDERAL_ENTITY' => 'required|string|max:75',
+            'CITY' => 'string|max:75',
+            'TOWN' => 'string|max:75',
+            'SUBURB' => 'required|string|max:75',
+            'POSTAL_CODE' => 'required|string|max:5',
+            'STREET' => 'required|string|max:150',
+            'EXTERIOR_NUMBER' => 'required|integer',
+            'INTERIOR_NUMBER' => 'integer',
+            'CONTACT_NAME' => 'required|string|max:150',
+            'CONTACT_LADA' => 'required|string|max:10',
+            'CONTACT_TELEPHONE' => 'required|string|max:11',
+            'CONTACT_ADDRESS' => 'required|string|max:250',
+            'ATTACHED' => 'required|json',
+        ]);
+
+        if($validator->fails()){
+            return $this->responseController->makeResponse(
+                TRUE,
+                'ERR_PERSONAL_REG001: Uno o más errores encontrados',
+                $this->responseController->makeErrors($validator->errors()->messages()),
+                400
+            );
         }
-    }
 
-    // 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 ID_EMPLOYEE',
-                    'S002V01TPERS.PERS_IDUS as USER_ID',
-                    'S002V01TEQMA.EQMA_IDEQ as WORKTEAM_ID',
-                    'S002V01TPERS.PERS_IDPS as SUBCONTRATIST_ID',
-                    'S002V01TEQMA.EQMA_NOMB as WORKTEAM_NAME',
-                    'S002V01TPERS.PERS_NOCE as CONTACT_NAME',
-                    'S002V01TPERS.PERS_NUTC as CONTACT_TELEPHONE',
-                    'S002V01TPERS.PERS_LATC as CONTACT_LADA',
-                    '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('TRIM(CONCAT(S002V01TUSUA.USUA_NOMB, " " , S002V01TUSUA.USUA_APPA, " ", COALESCE(S002V01TUSUA.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.USUA_NULI', '=', $line_number)
-                ->join('S002V01TPEEM', 'S002V01TPERS.PERS_IDPE', '=', 'S002V01TPEEM.PEEM_IDPE')
-                ->join('S002V01TEQMA', 'S002V01TPEEM.PEEM_IDEM', '=', 'S002V01TEQMA.EQMA_IDEQ')
-                ->join('S002V01TUSUA', 'S002V01TPERS.PERS_IDUS', '=', 'S002V01TUSUA.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);
+        $form = $request->all();
+        foreach($form as $k=>$v){
+            if($k == 'INTERIOR_NUMBER' && $v == '0'){
+                unset($form[$k]);
+            }else if($v == '-'){
+                unset($form[$k]);
             }
+        }
 
-            $employee->CONTACT_NAME = $this->encrypt_controller->encrypt($employee->CONTACT_NAME);
-            $employee->CONTACT_TELEPHONE = $this->encrypt_controller->encrypt($employee->CONTACT_TELEPHONE);
-            $employee->CONTACT_LADA = $this->encrypt_controller->encrypt($employee->CONTACT_LADA);
-            $employee->CONTACT_ADDRESS = $this->encrypt_controller->encrypt($employee->CONTACT_ADDRESS);
-
-            $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();
+        $idUser = $this->encryptionController->decrypt($form['id_user']);
+        if(!$idUser){
+            return $this->responseController->makeResponse(true, 'El ID de usuario no fue encriptado correctamente.', [], 400);
+        }
 
-            // 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);
-                }
-            }
+        $usr = DB::table('S002V01TUSUA')->where([
+            ['USUA_NULI', '=', $form['linea']],
+            ['USUA_IDUS', '=', $idUser]
+        ])->first();
+        
+        if(is_null($usr)){
+            return $this->responseController->makeResponse(true, 'El usuario que realizó la petición no existe.', [], 404);
+        }
 
-            return $this->response_controller
-                ->makeResponse(FALSE, "Consulta exitosa", $employee);
+        $idEmployee = $this->encryptionController->decrypt($form['id_employee']);
+        if(!$idEmployee){
+            return $this->responseController->makeResponse(true, 'El ID del empleado que desea actualizar no fue encriptado correctamente.', [], 400);
+        }
 
+        $employee = DB::table('S002V01TPERS')->where([
+            ['PERS_NULI', '=', $form['linea']],
+            ['PERS_IDPE', '=', $idEmployee]
+        ])->first();
+        
+        if(is_null($employee)){
+            return $this->responseController->makeResponse(true, 'El empleado que desea actualizar no existe.', [], 404);
+        }
 
-        } catch (Throwable $th) {
-            return $this->response_controller
-                ->makeResponse(TRUE, 'ERR_PERSONAL_REG002: Error inesperado', strtoupper($th->getMessage()), 500);
+        $idUserReg = $this->encryptionController->decrypt($form['USER_ID']);
+        if(!$idUserReg){
+            return $this->responseController->makeResponse(true, 'El ID del usuario seleccionado no fue encriptado correctamente.', [], 400);
+        }else if($idUser == $idUserReg){
+            return $this->responseController->makeResponse(true, 'El usuario no puede registrarse a sí mismo.', [], 400);
+        }
+        
+        $usrReg = DB::table('S002V01TUSUA')->where([
+            ['USUA_NULI', '=', $form['linea']],
+            ['USUA_IDUS', '=', $idUserReg]
+        ])->first();
+        
+        if(is_null($usrReg)){
+            return $this->responseController->makeResponse(true, 'El usuario seleccionado no existe.', [], 404);
         }
-    }
 
-    // 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_LATC as CONTACT_LADA',
-                    '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();
-
-            foreach ($employees as $employee) {
-                $employee->CONTACT_NAME = $this->encrypt_controller->encrypt($employee->CONTACT_NAME);
-                $employee->CONTACT_TELEPHONE = $this->encrypt_controller->encrypt($employee->CONTACT_TELEPHONE);
-                $employee->CONTACT_LADA = $this->encrypt_controller->encrypt($employee->CONTACT_LADA);
-                $employee->CONTACT_ADDRESS = $this->encrypt_controller->encrypt($employee->CONTACT_ADDRESS);
-                $employee->DOCUMENTS = [];
+        $idTeam = null;
+        if(isset($form['WORKTEAM_ID'])){
+            $idTeam = $this->encryptionController->decrypt($form['WORKTEAM_ID']);
+            if(!$idTeam){
+                return $this->responseController->makeResponse(true, 'El ID del equipo seleccionado encriptado correctamente.', [], 400);
             }
 
-            // 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) {
-                    foreach ($documents_of_employees as $doc) {
-                        if ($employee->EMPLOYEE_ID == $doc->EMPLOYEE_ID) {
-                            $employee->DOCUMENTS[] = $this->encrypt_controller->encrypt($doc->DOCUMENT);
-                        }
-                    }
-                }
+            $team = DB::table('S002V01TEQMA')->where([
+                ['EQMA_IDEQ', '=', $idTeam],
+                ['EQMA_NULI', '=', $form['linea']],
+            ])->first();
+        
+            if(is_null($team)){
+                return $this->responseController->makeResponse(true, 'El equipo seleccionado no existe.', [], 404);
+            }else if($team->EQMA_ESTA == 'Eliminado'){
+                return $this->responseController->makeResponse(true, 'El equipo seleccionado está eliminado.', [], 404);
             }
-
-            return $this->response_controller
-                ->makeResponse(FALSE, "Consulta exitosa", $employees);
-
-        } catch (Throwable $th) {
-            return $this->response_controller
-                ->makeResponse(TRUE, 'ERR_PERSONAL_REG001: Error inesperado', strtoupper($th->getMessage()), 500);
         }
-    }
-
-    // Metodo para actualizar un empleado
-    public function updateEmployee(Request $request, $id_employee)
-    {
-
-        try {
-            $save_option = $request->UPLOAD_NEW_DOCUMENTS != "N";
-            $request['SAVED_BY_USER'] = $this->encrypt_controller->decrypt($request->SAVED_BY_USER);
-            $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_LADA'] = $this->encrypt_controller->decrypt($request->CONTACT_LADA);
-            $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_LADA" => ['required', 'max:5'],
-                "CONTACT_ADDRESS" => ['required', 'max:100'],
-                "CONTRACT_TYPE" => ['required'],
-                "SPECIALITY" => ['required', 'max:75'],
-                "SUBCONTRATIST_ID" => ['max:10'],
-                "SAVED_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);
+        $idSubcontratist = null;
+        if(isset($form['SUBCONTRATIST_ID'])){
+            $idSubcontratist = $this->encryptionController->decrypt($form['SUBCONTRATIST_ID']);
+            if(!$idSubcontratist){
+                return $this->responseController->makeResponse(true, 'El ID del subcontratista seleccionado no fue encriptado correctamente.', [], 400);
             }
 
-            // 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);
+            $subcontratist = DB::table('S002V01TPESU')->where([
+                ['PESU_IDPS', '=', $idSubcontratist],
+                ['PESU_NULI', '=', $form['linea']],
+            ])->first();
+        
+            if(is_null($subcontratist)){
+                return $this->responseController->makeResponse(true, 'El subcontratista seleccionado no existe.', [], 404);
             }
+        }
 
-            $user_register = DB::table('S002V01TUSUA')
-                ->select('USUA_IDUS as ID_USER')
-                ->where('USUA_IDUS', '=', $request->SAVED_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);
-            }
+        $rfcx = null;
+        if(isset($form['RFC']) && $form['FOREIGNER'] == 'No' && $form['RFC'] == 'ENC_ERR'){
+            return $this->responseController->makeResponse(true, 'El RFC no fue encriptado correctamente.', [], 400);
+        }else if(isset($form['RFC']) && $form['RFC'] != 'ENC_ERR'){
+            $rfcx = $form['RFC'];
+        }
 
-            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_LATC" => $request->CONTACT_LADA,
-                    "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->SAVED_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);
-            }
+        $taid = null;
+        if(isset($form['TAX']) && $form['FOREIGNER'] == 'Si' && $form['TAX'] == 'ENC_ERR'){
+            return $this->responseController->makeResponse(true, 'El TAX ID no fue encriptado correctamente.', [], 400);
+        }else if(isset($form['TAX']) && $form['TAX'] != 'ENC_ERR'){
+            $taid =  $form['TAX'];
+        }
+        
+        $country = DB::table('S002V01TPAIS')->where([
+            ['PAIS_NULI', '=', $form['linea']],
+            ['PAIS_IDPA', '=', $form['COUNTRY']],
+        ])->first();
+        
+        if(is_null($country)){
+            return $this->responseController->makeResponse(true, 'El país seleccionado no existe.', [], 404);
+        }
 
-            $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->SAVED_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);
+        $colo = null;
+        $ciud = null;
+        $loca = null;
+        if($form['COUNTRY'] == 'MEX' || $form['COUNTRY'] == 'USA' || $form['COUNTRY'] == 'CAN'){
+            $state = DB::table('S002V01TESTA')->where([
+                ['ESTA_NULI', '=', $form['linea']],
+                ['ESTA_COES', '=', $form['FEDERAL_ENTITY']],
+                ['ESTA_COPA', '=', $form['COUNTRY']],
+            ])->first();
+        
+            if(is_null($state)){
+                return $this->responseController->makeResponse(true, 'El estado seleccionado no existe.', [], 404);
             }
 
-            // Verifica si el objeto esta vacio
-            if (isset($request->DOCUMENTS_AUTHO) && !empty($request->DOCUMENTS_AUTHO)) {
-                $doc = $request->DOCUMENTS_AUTHO;
-
-                // Se obtiene el nombre del archivo con su extensión
-                $completeFileName = $doc->getClientOriginalName();
-                // Se obtiene únicamente el nombre
-                $fileNameOnly = pathinfo($completeFileName, PATHINFO_FILENAME) . '-' . $id_employee;
-
-                // Se obtiene la extensión del archivo
-                $extension = $doc->getClientOriginalExtension();
-                if ($extension != "pdf") {
-                    return $this->response_controller
-                        ->makeResponse(TRUE, 'ERR_DOCUMENTO_REG007: Solo se permiten archivos PDF', [], 500);
+            if($form['COUNTRY'] == 'MEX'){
+                if(isset($form['CITY'])){
+                    $city = DB::table('S002V01TMUNI')->where([
+                        ['MUNI_NULI', '=', $form['linea']],
+                        ['MUNI_COMU', '=', $form['CITY']],
+                        ['MUNI_COES', '=', $form['FEDERAL_ENTITY']],
+                    ])->first();
+            
+                    if(is_null($city)){
+                        return $this->responseController->makeResponse(true, 'El municipio seleccionado no existe.', [], 404);
+                    }else{
+                        $ciud = $form['CITY'];
+                    }
                 }
 
-                // 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");
-
-                $name_document = $this->documents_controller->createDocument(
-                    "GPRS",
-                    "IN",
-                    $final_part_name_document,
-                    $id_employee,
-                    'pdf',
-                    $request->LINE_NUMBER,
-                    $request->SAVED_BY_USER,
-                    $request->DOCUMENTS_AUTHO_UPDATE
-                );
-
-                // El documento es guardado en el storage
-                $doc->storeAs('public/pdf_documents', $name_document);
-
-
-            }
-
-            // Verifica si el objeto esta vacio
-            if (isset($request->DOCUMENTS_AUTHO2) && !empty($request->DOCUMENTS_AUTHO2)) {
-                $doc = $request->DOCUMENTS_AUTHO2;
-
-                // Se obtiene el nombre del archivo con su extensión
-                $completeFileName = $doc->getClientOriginalName();
-                // Se obtiene únicamente el nombre
-                $fileNameOnly = pathinfo($completeFileName, PATHINFO_FILENAME) . '-' . $id_employee;
-
-                // Se obtiene la extensión del archivo
-                $extension = $doc->getClientOriginalExtension();
-                if ($extension != "pdf") {
-                    return $this->response_controller
-                        ->makeResponse(TRUE, 'ERR_DOCUMENTO_REG008: Solo se permiten archivos PDF', [], 500);
+                if(isset($form['TOWN'])){
+                    $town = DB::table('S002V01TLOCA')->where([
+                        ['LOCA_NULI', '=', $form['linea']],
+                        ['LOCA_COLO', '=', $form['TOWN']],
+                        ['LOCA_COES', '=', $form['FEDERAL_ENTITY']],
+                    ])->first();
+            
+                    if(is_null($town)){
+                        return $this->responseController->makeResponse(true, 'La localidad seleccionada no existe.', [], 404);
+                    }else{
+                        $loca = $form['TOWN'];
+                    }
                 }
-
-                // 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");
-
-                $name_document = $this->documents_controller->createDocument(
-                    "GPRS",
-                    "IN",
-                    $final_part_name_document,
-                    $id_employee,
-                    'pdf',
-                    $request->LINE_NUMBER,
-                    $request->SAVED_BY_USER,
-                    $request->DOCUMENTS_AUTHO2_UPDATE
-                );
-
-                // El documento es guardado en el storage
-                $doc->storeAs('public/pdf_documents', $name_document);
-
-
-            }
-
-            // Verifica si el objeto esta vacio
-            if (isset($request->DOCUMENTS_CERT) && !empty($request->DOCUMENTS_CERT)) {
-                $doc = $request->DOCUMENTS_CERT;
-
-                // Se obtiene el nombre del archivo con su extensión
-                $completeFileName = $doc->getClientOriginalName();
-                // Se obtiene únicamente el nombre
-                $fileNameOnly = pathinfo($completeFileName, PATHINFO_FILENAME) . '-' . $id_employee;
-
-                // Se obtiene la extensión del archivo
-                $extension = $doc->getClientOriginalExtension();
-                if ($extension != "pdf") {
-                    return $this->response_controller
-                        ->makeResponse(TRUE, 'ERR_DOCUMENTO_REG009: Solo se permiten archivos PDF', [], 500);
+                
+                $setting = DB::table('S002V01TCOLO')->where([
+                    ['COLO_NULI', '=', $form['linea']],
+                    ['COLO_COCO', '=', $form['SUBURB']],
+                    ['COLO_COPO', '=', $form['POSTAL_CODE']],
+                ])->first();
+            
+                if(is_null($setting)){
+                    return $this->responseController->makeResponse(true, 'La colonia seleccionada no existe.', [], 404);
+                }else{
+                    $colo = $form['SUBURB'];
                 }
-
-                // 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");
-
-                $name_document = $this->documents_controller->createDocument(
-                    "GPRS",
-                    "CE",
-                    $final_part_name_document,
-                    $id_employee,
-                    'pdf',
-                    $request->LINE_NUMBER,
-                    $request->SAVED_BY_USER,
-                    $request->DOCUMENTS_CERT_UPDATE
-                );
-
-                // El documento es guardado en el storage
-                $doc->storeAs('public/pdf_documents', $name_document);
-
-            }
-
-            // Verifica si el objeto esta vacio
-            if (isset($request->DOCUMENTS_CERT2) && !empty($request->DOCUMENTS_CERT2)) {
-                $doc = $request->DOCUMENTS_CERT2;
-
-                // Se obtiene el nombre del archivo con su extensión
-                $completeFileName = $doc->getClientOriginalName();
-                // Se obtiene únicamente el nombre
-                $fileNameOnly = pathinfo($completeFileName, PATHINFO_FILENAME) . '-' . $id_employee;
-
-                // Se obtiene la extensión del archivo
-                $extension = $doc->getClientOriginalExtension();
-                if ($extension != "pdf") {
-                    return $this->response_controller
-                        ->makeResponse(TRUE, 'ERR_DOCUMENTO_REG010: Solo se permiten archivos PDF', [], 500);
+                
+                $zipCode = DB::table('S002V01TCOPO')->where([
+                    ['COPO_NULI', '=', $form['linea']],
+                    ['COPO_COPO', '=', $form['POSTAL_CODE']],
+                    ['COPO_COES', '=', $form['FEDERAL_ENTITY']],
+                ])->first();
+            
+                if(is_null($zipCode)){
+                    return $this->responseController->makeResponse(true, 'El código postal seleccionado no existe.', [], 404);
                 }
-
-                // 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");
-
-                $name_document = $this->documents_controller->createDocument(
-                    "GPRS",
-                    "CE",
-                    $final_part_name_document,
-                    $id_employee,
-                    'pdf',
-                    $request->LINE_NUMBER,
-                    $request->SAVED_BY_USER,
-                    $request->DOCUMENTS_CERT2_UPDATE
-                );
-
-                // El documento es guardado en el storage
-                $doc->storeAs('public/pdf_documents', $name_document);
-
-
-
-
+            }else{
+                $colo = $form['SUBURB'];
+                $ciud = $form['CITY'];
+                $loca = isset($form['TOWN']) ? $form['TOWN'] : null;
             }
+        }else{
+            $colo = $form['SUBURB'];
+            $ciud = $form['CITY'];
+            $loca = isset($form['TOWN']) ? $form['TOWN'] : null;
+        }
 
-            // Verifica si el objeto esta vacio
-            if (isset($request->DOCUMENT_OFFICE) && !empty($request->DOCUMENT_OFFICE)) {
-                $doc = $request->DOCUMENT_OFFICE;
-
-                // Se obtiene el nombre del archivo con su extensión
-                $completeFileName = $doc->getClientOriginalName();
-                // Se obtiene únicamente el nombre
-                $fileNameOnly = pathinfo($completeFileName, PATHINFO_FILENAME) . '-' . $id_employee;
+        $subArr = DB::table('S002V01TPERS')->where('PERS_NULI', '=', $form['linea'])->where(function(Builder $query) use ($form, $idUserReg) {
+            $query->where('PERS_IDUS', '=', $idUserReg)
+            ->orWhere('PERS_XRFC', '=', $form['RFC']);
+        })->where([
+            ['PERS_ESTA', '=', 'Activo'],
+            ['PERS_IDPE', '!=', $idEmployee],
+        ])->get()->all();
 
-                // Se obtiene la extensión del archivo
-                $extension = $doc->getClientOriginalExtension();
-                if ($extension != "pdf") {
-                    return $this->response_controller
-                        ->makeResponse(TRUE, 'ERR_DOCUMENTO_REG011: Solo se permiten archivos PDF', [], 500);
-                }
+        if(count($subArr) > 0){
+            return $this->responseController->makeResponse(true, 'La razón social, el RFC o el correo electrónico ya fueron registrados.', [], 401);
+        }
 
-                // Se quitan los espacios y se concatena datos para ser guardado
-                $final_part_name_document = str_replace(' ', '_', $fileNameOnly) . '.' . $extension;
+        $ladasValues = [];
+        $ladas = DB::table('S002V01TPAIS')->select([
+            'PAIS_LADA AS LADA'
+        ])->where('PAIS_NULI', '=', $form['linea'])->get()->all();
 
-                $final_part_name_document = $this->documents_controller->deleteCodificationStructureName($final_part_name_document, "01", "GPRS");
+        foreach($ladas as $lada){
+            if($lada->LADA != '' && $lada->LADA != '0'){
+                $ladasValues[] = $lada->LADA;
+            }
+        }
 
-                $name_document = $this->documents_controller->createDocument(
-                    "GPRS",
-                    "CO",
-                    $final_part_name_document,
-                    $id_employee,
-                    'pdf',
-                    $request->LINE_NUMBER,
-                    $request->SAVED_BY_USER,
-                    $request->DOCUMENT_OFFICE_UPDATE
-                );
+        if($form['CONTACT_LADA'] == 'ENC_ERR'){
+            return $this->responseController->makeResponse(true, "La lada del contacto de emergencia no fue encriptada correctamente.", [], 400);
+        }else if(!in_array($form['CONTACT_LADA'], $ladasValues)){
+            return $this->responseController->makeResponse(true, "La lada $form[CONTACT_LADA] no está relacionada a ningún país.", [], 400);
+        }else if($form['CONTACT_TELEPHONE'] == 'ENC_ERR'){
+            return $this->responseController->makeResponse(true, 'El número telefónico del contacto de emergencia no fue encriptado correctamente.', [], 400);
+        }
 
-                // El documento es guardado en el storage
-                $doc->storeAs('public/pdf_documents', $name_document);
+        if($form['CONTACT_ADDRESS'] == 'ENC_ERR'){
+            return $this->responseController->makeResponse(true, "La dirección del contacto de emergencia no fue encriptada correctamente.", [], 400);
+        }
 
-            }
+        if($form['CONTACT_NAME'] == 'ENC_ERR'){
+            return $this->responseController->makeResponse(true, "El nombre del contacto de emergencia no fue encriptada correctamente.", [], 400);
+        }
 
-            DB::commit(); # Para guardar los cambios en la base de datos
-            return $this->response_controller->makeResponse(FALSE, 'Actualización exitosa', 200);
+        $docsArr = json_decode($form['ATTACHED'], true);
+        if(count($docsArr) == 0){
+            return $this->responseController->makeResponse(true, "El arreglo de archivos adjuntos está vacío.", [], 400);
+        }
 
-        } catch (Throwable $th) {
-            return $this->response_controller
-                ->makeResponse(TRUE, 'ERR_PERSONAL_REG012: Error inesperado', strtoupper($th), 500);
+        $authCont = 0;
+        foreach($docsArr as $doc){
+            if($doc['type'] == 'AU') $authCont++;
         }
-    }
 
-    // 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('TRIM(CONCAT(S002V01TUSUA.USUA_NOMB, " " , S002V01TUSUA.USUA_APPA, " ", COALESCE(S002V01TUSUA.USUA_APMA,""))) AS NAME'),
-                    DB::raw(
-                        'COUNT(S002V01TPECO.PECO_IDPE) AS CONTRACTS_COUNT',
-                    )
-                )
-                ->where('S002V01TPERS.PERS_NULI', '=', $line_number)
-                ->where('S002V01TUSUA.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', 'S002V01TPERS.PERS_IDUS', '=', 'S002V01TUSUA.USUA_IDUS')
-                ->join('S002V01TPECO', 'S002V01TPERS.PERS_IDPE', '=', 'S002V01TPECO.PECO_IDPE')
-                ->join('S002V01TCONT', 'S002V01TPECO.PECO_IDCO', '=', 'S002V01TCONT.CONT_IDCO')
-                ->get();
-
-            return $this->response_controller
-                ->makeResponse(FALSE, "Consulta exitosa", $contracts_by_employee);
-
-        } catch (Throwable $th) {
-            return $this->response_controller
-                ->makeResponse(TRUE, 'ERR_PERSONAL_REG001: Error inesperado', strtoupper($th->getMessage()), 500);
+        if($authCont < 1){
+            return $this->responseController->makeResponse(true, "El arreglo de archivos adjuntos debe contener al menos un documento de autorización.", [], 400);
         }
-    }
 
-    // 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);
+        $finalDocsArr = [];
+        foreach($docsArr as $doc){
+            if(!array_key_exists('isFinalFile', $doc)){
+                return $this->responseController->makeResponse(true, "La información del archivo $doc[name] no tiene un formato correcto.", [], 400);
             }
 
-            //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', 'S002V01TCONT.CONT_NOMB as CONTRACT_NAME')
-                ->join('S002V01TPECO', 'S002V01TPERS.PERS_IDPE', '=', 'S002V01TPECO.PECO_IDPE')
-                ->join('S002V01TCONT', 'S002V01TPECO.PECO_IDCO', '=', 'S002V01TCONT.CONT_IDCO')
-                ->get();
-
-            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);
+            if($doc['isFinalFile']){
+                $finalDocsArr[] = [
+                    'CODE' => $doc['name'],
+                    'TYPE' => $doc['type']
+                ];
+            }else{
+                $idFileDec = $this->encryptionController->decrypt($doc['id']);
+                $tempFile = DB::table('S002V01TARTE')->where([
+                    ['ARTE_NULI', '=', $form['linea']],
+                    ['ARTE_IDAR', '=', $idFileDec],
+                ])->first();
+    
+                if(is_null($tempFile)){
+                    return $this->responseController->makeResponse(true, "El archivo $doc[name] no está registrado.", [], 404);
+                }
+    
+                $classifications = ["AU" => "IN", "OF" => "CO", "CE" => "CE"];
+                $cldo = $classifications[$doc['type']];
+                $finalFile = $this->documentManagementController->moveFinalFile($form['linea'], "GPRS", $cldo, $tempFile, $idUser);
+    
+                if(!$finalFile[0]){
+                    return $this->responseController->makeResponse(true, $finalFile[1], [], 400);
+                }else{
+                    $finalDocsArr[] = [
+                        'CODE' => $finalFile[1],
+                        'TYPE' => $doc['type']
+                    ];
+                }
             }
-
-            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 la descarga de archivo excel con los detalles del empleado
-    public function downoloadEmployeeInfoOnExcel(Request $request)
-    {
 
-        try {
-            $request['SAVED_BY_USER'] = $this->encrypt_controller->decrypt($request->SAVED_BY_USER);
-            $employee_id = $request->EMPLOYEE['ID_EMPLOYEE'];
+        $doas = json_encode($finalDocsArr);
+        $nuin = isset($form['INTERIOR_NUMBER']) ? $form['INTERIOR_NUMBER'] : null;
+
+        $now = $this->functionsController->now();
+        $nowStr = $now->toDateTimeString();
+        DB::table('S002V01TPERS')->where([
+            ['PERS_NULI', '=', $form['linea']],
+            ['PERS_IDPE', '=', $idEmployee]
+        ])->update([
+            'PERS_EQTR' => $idTeam,
+            'PERS_TICO' => $form['CONTRACT_TYPE'],
+            'PERS_IDPS' => $idSubcontratist,
+            'PERS_ESPE' => $form['SPECIALITY'],
+            'PERS_EXTR' => $form['FOREIGNER'],
+            'PERS_XRFC' => $rfcx,
+            'PERS_TAID' => $taid,
+            'PERS_IDPA' => $form['COUNTRY'],
+            'PERS_ENFE' => $form['FEDERAL_ENTITY'],
+            'PERS_CIUD' => $ciud,
+            'PERS_LOCA' => $loca,
+            'PERS_COLO' => $colo,
+            'PERS_COPO' => $form['POSTAL_CODE'],
+            'PERS_CALL' => $form['STREET'],
+            'PERS_NUEX' => $form['EXTERIOR_NUMBER'],
+            'PERS_NUIN' => $nuin,
+            'PERS_NOCE' => $form['CONTACT_NAME'],
+            'PERS_LCEM' => $form['CONTACT_LADA'],
+            'PERS_NUTC' => $form['CONTACT_TELEPHONE'],
+            'PERS_DCEM' => $form['CONTACT_ADDRESS'],
+            'PERS_DOAS' => $doas,
+            'PERS_USMO' => $idUser,
+            'PERS_FEMO' => $nowStr,
+        ]);
+
+        $actions = DB::getQueryLog();
+        $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
+        $nameEmp = $this->functionsController->joinName($usrReg->USUA_NOMB, $usrReg->USUA_APPA, $usrReg->USUA_APMA);
+        
+        $idac = $this->functionsController->registerActivity(
+            $form['linea'],
+            'S002V01M11GPRS',
+            'S002V01F01GEPE',
+            'S002V01P02REEM',
+            'Actualización',
+            "El usuario $name (" . $usr->USUA_IDUS . ") actualizó al empleado " . $nameEmp . "($idEmployee).",
+            $idUser,
+            $nowStr,
+            'S002V01S02GEPE'
+        );
+
+        $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']);
+        return $this->responseController->makeResponse(false, 'EXITO');
+    }
 
-            $final_part_name_document = "Details_Of_Employee_" . $employee_id . ".xlsx";
+    public function updateToInactiveStatus(Request $request) {
+        DB::enableQueryLog();
+
+        $validator = Validator::make($request->all(), [
+            'id_user' => 'required|string',
+            'linea' => 'required|integer',
+            'id_employee' => 'required|string',
+        ]);
+
+        if($validator->fails()){
+            return $this->responseController->makeResponse(
+                true,
+                "Se encontraron uno o más errores.",
+                $this->responseController->makeErrors(
+                    $validator->errors()->messages()
+                ),
+                401
+            );
+        }
 
-            // Crea el documento con los datos del request
-            $document = $this->createDocument($request);
+        $form = $request->all();
+        $idUser = $this->encryptionController->decrypt($form['id_user']);
+        if(!$idUser){
+            return $this->responseController->makeResponse(true, 'El ID de usuario no fue encriptado correctamente.', [], 400);
+        }
 
-            // Busca la ultima versión del documento que se haya insertado
-            $old_document_name = $this->documents_controller->getDocumentsWithSameName($final_part_name_document, 'excel');
+        $usr = DB::table('S002V01TUSUA')->where([
+            ['USUA_NULI', '=', $form['linea']],
+            ['USUA_IDUS', '=', $idUser]
+        ])->first();
+        
+        if(is_null($usr)){
+            return $this->responseController->makeResponse(true, 'El usuario que realizó la petición no existe.', [], 404);
+        }
 
-            if ($old_document_name != null) {
+        $idEmployee = $this->encryptionController->decrypt($form['id_employee']);
+        if(!$idEmployee){
+            return $this->responseController->makeResponse(true, 'El ID del empleado que desea actualizar no fue encriptado correctamente.', [], 400);
+        }
 
-                // Obtiene el nombre del documento que tiene el mismo contenido
-                $old_document_name = $this->documents_controller->sameDocumentsExcel($document, $old_document_name);
+        $employee = DB::table('S002V01TPERS')->where([
+            ['PERS_NULI', '=', $form['linea']],
+            ['PERS_IDPE', '=', $idEmployee]
+        ])->first();
+        
+        if(is_null($employee)){
+            return $this->responseController->makeResponse(true, 'El empleado que desea actualizar no existe.', [], 404);
+        }
+        
+        if($idUser == $employee->PERS_IDUS){
+            return $this->responseController->makeResponse(true, 'El usuario no puede eliminarse a sí mismo.', [], 400);
+        }
 
-                // Si no hay ningun cambio en el documento, se descarga la ultima versión
-                if ($old_document_name != null) {
-                    return $this->response_controller
-                        ->makeResponse(False, 'Éxito', Storage::disk('excel')->url($old_document_name), 200);
-                }
-            }
+        $now = $this->functionsController->now();
+        $nowStr = $now->toDateTimeString();
+        DB::table('S002V01TPERS')->where([
+            ['PERS_NULI', '=', $form['linea']],
+            ['PERS_IDPE', '=', $idEmployee]
+        ])->update([
+            'PERS_ESTA' => 'Eliminado',
+            'PERS_USMO' => $idUser,
+            'PERS_FEMO' => $nowStr,
+        ]);
+
+        $actions = DB::getQueryLog();
+        $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
+        $idac = $this->functionsController->registerActivity(
+            $form['linea'],
+            'S002V01M11GPRS',
+            'S002V01F01GEPE',
+            'S002V01P02REEM',
+            'Eliminación',
+            "El usuario $name (" . $usr->USUA_IDUS . ") eliminó al empleado $idEmployee.",
+            $idUser,
+            $nowStr,
+            'S002V01S02GEPE'
+        );
+
+        $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']);
+        return $this->responseController->makeResponse(false, 'EXITO');
+    }
 
-            // Guarda el documento creado en la variable
-            $writer = IOFactory::createWriter($document, 'Xlsx');
-            $content = tmpfile();
-            $writer->save($content);
+    public function getContractsOfEveryEmployee($idUser, $line) {
+        DB::enableQueryLog();
 
-            // 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->SAVED_BY_USER);
+        $idUser = $this->encryptionController->decrypt($idUser);
+        if(!$idUser){
+            return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente', [], 400);
+        }
 
-            Storage::disk('excel')->put(
-                $name_document,
-                $content
-            );
+        $usr = DB::table('S002V01TUSUA')->where([
+            ['USUA_NULI', '=', $line],
+            ['USUA_IDUS', '=', $idUser],
+        ])->first();
 
-            return $this->response_controller
-                ->makeResponse(False, 'Éxito', Storage::disk('excel')->url($name_document), 200);
+        if(is_null($usr)){
+            return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado', [], 404);
+        }
 
-        } catch (Throwable $th) {
-            return $this->response_controller
-                ->makeResponse(TRUE, 'ERR_EXCEL_REG001: Error inesperado', strtoupper($th), 500);
+        $contractsByEmployees = DB::table('S002V01TPERS')->select([
+            DB::raw("
+                TRIM(CONCAT(
+                    USUA_NOMB, 
+                    ' ', 
+                    USUA_APPA,
+                    IF(ISNULL(USUA_APMA), '', CONCAT(' ', USUA_APMA)),
+                    ' <(',
+                    PERS_IDPE,
+                    ')> (',
+                    PERS_IDUS,
+                    ')'
+                )) AS EMPLOYEE
+            "),
+            DB::raw("COUNT(CONT_IDCO) AS CONTRACTS")
+        ])->leftJoin('S002V01TCONT', 'CONT_IDEM', '=', 'PERS_IDPE')
+        ->join('S002V01TUSUA', 'USUA_IDUS', '=', 'PERS_IDUS')
+        ->groupBy('EMPLOYEE')->where([
+            ['PERS_NULI', '=', $line],
+            ['PERS_TICO', '=', 'Interno'],
+        ])->get()->all();
+
+        foreach($contractsByEmployees as $key=>$val){
+            $employeeArr = explode('<', $val->EMPLOYEE);
+            $employeeName = $employeeArr[0];
+            $employeeArr = array_reverse($employeeArr);
+            $employeeArr = explode('>', $employeeArr[0]);
+
+            $employeeID = str_replace('(', '', $employeeArr[0]);
+            $employeeID = str_replace(')', '', $employeeID);
+
+            $val->ID_EMPLOYEE = $this->encryptionController->encrypt($employeeID);
+            $val->EMPLOYEE = $employeeName . join('', $employeeArr);
+
+            $contractsByEmployees[$key] = $val;
         }
+
+        $now = $this->functionsController->now();
+        $nowStr = $now->toDateTimeString();
+        $actions = DB::getQueryLog();
+        $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
+        
+        $idac = $this->functionsController->registerActivity(
+            $line,
+            'S002V01M11GPRS',
+            'S002V01F02ACEM',
+            'S002V01P01HCEM',
+            'Consulta',
+            "El usuario $name (" . $usr->USUA_IDUS . ") consultó los contratos por empleados.",
+            $idUser,
+            $nowStr,
+            'S002V01S02GEPE'
+        );
+
+        $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
+        return $this->responseController->makeResponse(false, 'EXITO', $contractsByEmployees);
     }
 
-    // Metodo para la descarga de archivo pdf con los detalles del empleado
-    public function downoloadEmployeeInfoOnPdf(Request $request)
-    {
+    public function getDetailsOfContractsByEmployee($idEmployee, $idUser, $line) {
+        DB::enableQueryLog();
 
-        try {
-            $request['SAVED_BY_USER'] = $this->encrypt_controller->decrypt($request->SAVED_BY_USER);
-            $employee_id = $request->EMPLOYEE['ID_EMPLOYEE'];
+        $idUser = $this->encryptionController->decrypt($idUser);
+        if(!$idUser){
+            return $this->responseController->makeResponse(true, 'El ID de usuario no fue encriptado correctamente.', [], 400);
+        }
 
-            $final_part_name_document = "Details_Of_Employee_" . $employee_id . ".pdf";
+        $usr = DB::table('S002V01TUSUA')->where([
+            ['USUA_NULI', '=', $line],
+            ['USUA_IDUS', '=', $idUser]
+        ])->first();
+        
+        if(is_null($usr)){
+            return $this->responseController->makeResponse(true, 'El usuario que realizó la petición no existe.', [], 404);
+        }
 
-            // Crea el documento
-            $document = $this->createDocument($request);
-            $writer = IOFactory::createWriter($document, 'Mpdf');
-            $content = tmpfile();
+        $idEmployee = $this->encryptionController->decrypt($idEmployee);
+        if(!$idEmployee){
+            return $this->responseController->makeResponse(true, 'El ID del empleado no fue encriptado correctamente.', [], 400);
+        }
 
-            // Busca la ultima versión del documento que se haya insertado
-            $old_document_name = $this->documents_controller->getDocumentsWithSameName($final_part_name_document, 'pdf');
+        $sub = DB::table('S002V01TPERS')->where([
+            ['PERS_NULI', '=', $line],
+            ['PERS_IDPE', '=', $idEmployee],
+            ['PERS_TICO', '=', 'Interno'],
+        ])->first();
+        
+        if(is_null($sub)){
+            return $this->responseController->makeResponse(true, 'El empleado solicitado no existe.', [], 404);
+        }
 
-            $writer->save($content);
-            if ($old_document_name != null) {
+        $contracts = DB::table('S002V01TCONT')->select([
+            'CONT_NOCO AS CONTRACT_NAME',
+            'CONT_FEIN AS START_DATE',
+            'CONT_FEFI AS END_DATE',
+            'CONT_COST AS COST',
+        ])->where([
+            ['CONT_NULI', '=', $line],
+            ['CONT_IDEM', '=', $idEmployee],
+            ['CONT_TIPO', '=', 'Interno'],
+        ])->get()->all();
+
+        $now = $this->functionsController->now();
+        $nowStr = $now->toDateTimeString();
+        $actions = DB::getQueryLog();
+        $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
+        
+        $idac = $this->functionsController->registerActivity(
+            $line,
+            'S002V01M11GPRS',
+            'S002V01F02ACEM',
+            'S002V01P01HCEM',
+            'Consulta',
+            "El usuario $name (" . $usr->USUA_IDUS . ") consultó los contratos del empleado #$idEmployee.",
+            $idUser,
+            $nowStr,
+            'S002V01S02GEPE'
+        );
+
+        $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
+        return $this->responseController->makeResponse(false, 'EXITO', $contracts);
+    }
 
-                // Obtiene el nombre del documento que tiene el mismo contenido
-                $old_document_name = $this->documents_controller->sameDocumentsPdf($content, $old_document_name);
+    public function getInterventionsByEmployee($idEmployee, $idUser, $line) {
+        DB::enableQueryLog();
 
-                // Si no hay ningun cambio en el documento, se descarga la ultima versión
-                if ($old_document_name != null) {
-                    return $this->response_controller
-                        ->makeResponse(False, 'Éxito', Storage::disk('pdf')->url($old_document_name), 200);
-                }
-            }
+        $idUser = $this->encryptionController->decrypt($idUser);
+        if(!$idUser){
+            return $this->responseController->makeResponse(true, 'El ID de usuario no fue encriptado correctamente.', [], 400);
+        }
 
-            // 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->SAVED_BY_USER);
-            Storage::disk('pdf')->put(
-                $name_document,
-                $content
-            );
-            return $this->response_controller
-                ->makeResponse(False, 'Éxito', Storage::disk('pdf')->url($name_document), 200);
+        $usr = DB::table('S002V01TUSUA')->where([
+            ['USUA_NULI', '=', $line],
+            ['USUA_IDUS', '=', $idUser]
+        ])->first();
+        
+        if(is_null($usr)){
+            return $this->responseController->makeResponse(true, 'El usuario que realizó la petición no existe.', [], 404);
+        }
 
-        } catch (Throwable $th) {
-            return $this->response_controller
-                ->makeResponse(TRUE, 'ERR_PDF_REG001: Error inesperado', strtoupper($th), 500);
+        $idEmployee = $this->encryptionController->decrypt($idEmployee);
+        if(!$idEmployee){
+            return $this->responseController->makeResponse(true, 'El ID del empleado no fue encriptado correctamente.', [], 400);
         }
-    }
 
-    // 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");
-            // Cambia la hoja a horizontal par que se observen mejor los datos
-            $document->getActiveSheet()->getPageSetup()->setOrientation("landscape");
-
-            // 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, '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['ID_EMPLOYEE']);
-            $col++;
-
-            $document->getActiveSheet()->setCellValue($col . $row, $employee['EMPLOYEE_NAME']);
-            $col++;
-
-            $document->getActiveSheet()->setCellValue($col . $row, $employee['WORKTEAM_NAME']);
-            $col++;
-
-            $document->getActiveSheet()->setCellValue($col . $row, $this->encrypt_controller->decrypt($employee['CONTACT_NAME']));
-            $col++;
-
-            $document->getActiveSheet()->setCellValue($col . $row, $this->encrypt_controller->decrypt($employee['CONTACT_LADA']) . $this->encrypt_controller->decrypt($employee['CONTACT_TELEPHONE']));
-            $col++;
-
-            $document->getActiveSheet()->setCellValue($col . $row, $this->encrypt_controller->decrypt($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++;
-            }
+        $employee = DB::table('S002V01TPERS')->where([
+            ['PERS_NULI', '=', $line],
+            ['PERS_IDPE', '=', $idEmployee],
+        ])->first();
+        
+        if(is_null($employee)){
+            return $this->responseController->makeResponse(true, 'El empleado solicitado no existe.', [], 404);
+        }
 
-            //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++;
+        $preventiveOrders = DB::select("
+        SELECT 
+            DISTINCT(S002V01TOTPR.OTPR_IDOT) AS IDORDEN, 
+            S002V01TOTPR.OTPR_DEIN AS DESCRIPCION,
+            'Preventivo' AS TIPOORDEN
+        FROM 
+            S002V01TOTPR, 
+            JSON_TABLE(OTPR_OPPR, '$[*]' COLUMNS(
+                OTPR_OPPR_ID INT PATH '$.ID', 
+                OTPR_OPPR_TYPE VARCHAR(100) PATH '$.TYPE'
+            )) OPPR 
+        WHERE 
+            (OTPR_OPPR_ID = :emp_id AND OTPR_OPPR_TYPE = 'EM')
+            OR (OTPR_OPPR_ID = :sub_id AND OTPR_OPPR_TYPE = 'SU')
+            OR (OTPR_OPPR_ID = :team_id AND OTPR_OPPR_TYPE = 'EQ')
+        ", [
+            'emp_id' => $employee->PERS_IDPE,
+            'sub_id' => $employee->PERS_IDPS,
+            'team_id' => $employee->PERS_EQTR
+        ]);
+
+        //PENDIENTE MANTENIMIENTO CORRECTIVO
+
+        $ordersFN = [];
+        $relatedOrders = [];
+        foreach($preventiveOrders as $order){
+            if(!in_array($order->IDORDEN, $relatedOrders)){
+                $relatedOrders[] = $order->IDORDEN;
+
+                $order->IDORDEN = $this->encryptionController->encrypt($order->IDORDEN);
+                $ordersFN[] = $order;
             }
-
-            $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);
         }
-    }
 
-}
+        $now = $this->functionsController->now();
+        $nowStr = $now->toDateTimeString();
+        $actions = DB::getQueryLog();
+        $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
+        
+        $idac = $this->functionsController->registerActivity(
+            $line,
+            'S002V01M11GPRS',
+            'S002V01F01GEPE',
+            'S002V01P03DEEM',
+            'Consulta',
+            "El usuario $name (" . $usr->USUA_IDUS . ") consultó las órdenes de trabajo relacionadas al empleado #$idEmployee.",
+            $idUser,
+            $nowStr,
+            'S002V01S02GEPE'
+        );
+
+        $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
+        return $this->responseController->makeResponse(false, 'EXITO', $ordersFN);
+    }
+}

+ 350 - 505
sistema-mantenimiento-back/app/Http/Controllers/InterventionController.php

@@ -1,9 +1,4 @@
 <?php
-/*
-Nombre del programador:         Cordourier Rojas Mathew
-Ultima fecha de modificación:   [ 24 / Abril / 2023 ]
-Descripción:                    Controlador del submodulo Intervenciones. Perteneciente al Módulo 13 - Gestion del Personal de Mantenimiento
-*/
 
 namespace App\Http\Controllers;
 
@@ -15,552 +10,402 @@ use Illuminate\Support\Facades\Validator;
 use stdClass;
 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();
+class InterventionController extends Controller{
+    private $responseController;
+    private $encryptionController;
+    private $documentManagementController;
+    private $functionsController;
+
+    public function __construct(){
+        $this->responseController = new ResponseController();
+        $this->encryptionController = new EncryptionController();
+        $this->documentManagementController = new DocumentManagementController();
+        $this->functionsController = new FunctionsController();
     }
 
-    // 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();
-
-            // Obtiene los datos de la tabla intermediaria entre intervenciones y equipos de mantenimiento
-            $equipment_by_intervention = DB::table('S002V01TINMA')
-                ->select(
-                    'S002V01TINMA.INMA_IDMA as EQUIPMENT_ID',
-                    'S002V01TMATE_P.MATE_NOMB as EQUIPMENT_NAME',
-                    'S002V01TINMA.INMA_IDIN as INTERVENTION_ID'
-                )
-                ->where('INMA_NULI', '=', $line_number)
-                ->join('S002V01TMATE_P', 'S002V01TINMA.INMA_IDMA', '=', 'S002V01TMATE_P.MATE_IDMA')
-                ->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");
-                $intervention->EQUIPMENT = new stdClass();
-                foreach ($equipment_by_intervention as $equipment) {
-                    if ($equipment->INTERVENTION_ID == $intervention->INTERVENTION_ID) {
-                        $intervention->EQUIPMENT->ID = $equipment->EQUIPMENT_ID;
-                        $intervention->EQUIPMENT->NAME = $equipment->EQUIPMENT_NAME;
-                    }
-                }
-
-                // Verifica si el objeto esta vacio
-                if (!isset($intervention->EQUIPMENT->ID) && empty($intervention->EQUIPMENT->ID)) {
-                    $intervention->EQUIPMENT = null;
-                }
-            }
-
-            return $this->response_controller
-                ->makeResponse(FALSE, 'Consulta exitosa', $interventions);
-
-        } catch (Throwable $th) {
-            return $this->response_controller
-                ->makeResponse(TRUE, 'ERR_INTERVENCIÓN_GET000: Error inesperado', strtoupper($th->getMessage()), 500);
+    public function storeContract(Request $request) {
+        DB::enableQueryLog();
+
+        $request['CONTRACT_COST'] = $this->encryptionController->decrypt($request->CONTRACT_COST) ? $this->encryptionController->decrypt($request->CONTRACT_COST) : 'ENC_ERR';
+        $request['CONTRACT_COST'] = floatval($request->CONTRACT_COST);
+
+        $validator = Validator::make($request->all(), [
+            'id_user' => 'required|string',
+            'linea' => 'required|integer',
+            'CONTRACT_NAME' => 'required|string|max:100',
+            'WORK_ORDER' => 'required|string',
+            'CONTRACT_TYPE' => 'required|string|in:Subcontratista,Interno',
+            'DENOMINATION' => 'required|string',
+            'START_DATE' => 'required|date',
+            'END_DATE' => 'required|date',
+            'CONTRACT_COST' => 'required|numeric',
+            'DOCUMENT' => 'required|json',
+        ]);
+
+        if ($validator->fails()) {
+            return $this->responseController->makeResponse(
+                TRUE,
+                'ERR_CONTRATO_REG001: Uno o más errores encontrados',
+                $this->responseController->makeErrors($validator->errors()->messages()),
+                400
+            );
         }
-    }
-
-    // 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_GET000: 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();
-
-            // Obtiene a los empleados con su nombre
-            $employees_workteam = DB::table('S002V01TPEEM')
-                ->select(
-                    DB::raw('TRIM(CONCAT(S002V01TUSUA.USUA_NOMB, " " , S002V01TUSUA.USUA_APPA, " ", COALESCE(S002V01TUSUA.USUA_APMA,""))) as NAME'),
-                    'S002V01TPEEM.PEEM_IDEM as WORKTEAM_ID'
-                )
-                ->where('S002V01TPEEM.PEEM_NULI', '=', $line_number)
-                ->where('S002V01TPERS.PERS_NULI', '=', $line_number)
-                ->where('S002V01TUSUA.USUA_NULI', '=', $line_number)
-                ->join('S002V01TPERS', 'S002V01TPEEM.PEEM_IDPE', '=', 'S002V01TPERS.PERS_IDPE')
-                ->join('S002V01TUSUA', 'S002V01TPERS.PERS_IDUS', '=', 'S002V01TUSUA.USUA_IDUS')
-                ->get();
-
-            // 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;
-                    }
-                }
+        $form = $request->all();
+        foreach($form as $k=>$v){
+            if($k == 'CONTRACT_COST' && $v == '0'){
+                unset($form[$k]);
+            }else if($v == '-'){
+                unset($form[$k]);
             }
+        }
 
-            $intervention_details->WORKTEAMS = $workteams_on_intervention;
+        $idUser = $this->encryptionController->decrypt($form['id_user']);
+        if(!$idUser){
+            return $this->responseController->makeResponse(true, 'El ID de usuario no fue encriptado correctamente.', [], 400);
+        }
 
-            // 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;
-                }
-            }
+        $usr = DB::table('S002V01TUSUA')->where([
+            ['USUA_NULI', '=', $form['linea']],
+            ['USUA_IDUS', '=', $idUser]
+        ])->first();
+        
+        if(is_null($usr)){
+            return $this->responseController->makeResponse(true, 'El usuario que realizó la petición no existe.', [], 404);
+        }
 
-            // 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;
-                }
-            }
+        $idOrderArr = explode('-', $form['WORK_ORDER']);
+        $idOrder = $this->encryptionController->decrypt($idOrderArr[0]);
+        if(!$idOrder){
+            return $this->responseController->makeResponse(true, 'El ID de la orden seleccionada no está encriptado correctamente.', [], 400);
+        }
 
-            $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");
+        $order = null;
+        if($idOrderArr[1] == 'prev'){
+            $order = DB::table('S002V01TOTPR')->where([
+                ['OTPR_NULI', '=', $form['linea']],
+                ['OTPR_IDOT', '=', $idOrder],
+            ])->first();
+        }else{
+            //PENDIENTE MANTENIMIENTO CORRECTIVO
+        }
 
-            return $this->response_controller
-                ->makeResponse(FALSE, 'Consulta exitosa', $intervention_details);
+        if(is_null($order)){
+            return $this->responseController->makeResponse(true, 'La orden seleccionada no existe.', [], 404);
+        }
 
-        } catch (Throwable $th) {
-            return $this->response_controller
-                ->makeResponse(TRUE, 'ERR_INTERVENCIÓN_GET001: Error inesperado', strtoupper($th->getMessage()), 500);
+        $workersStr = "[]";
+        if($idOrderArr[1] == 'prev'){
+            $workersStr = $order->OTPR_OPPR;
+        }else{
+            //PENDIENTE MANTENIMIENTO PREVENTIVO
         }
-    }
 
-    // Metodo para obtener datos de los contratos
-    public function getConsultOfContracts($line_number)
-    {
-        try {
-
-            $contracts = DB::table('S002V01TCONT')
-                ->select(
-                    'CONT_IDCO as CONTRACT_ID',
-                    'CONT_NOMB as CONTRACT_NAME',
-                    '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',
-                    'CONT_LIDO as DOCUMENT'
-                )
-                ->where('CONT_NULI', '=', $line_number)
-                ->get();
-
-            $users = DB::table('S002V01TUSUA')
-                ->select(
-                    'USUA_IDUS as USER_ID',
-                    DB::raw('TRIM(CONCAT(USUA_NOMB, " " , USUA_APPA, " ", COALESCE(USUA_APMA,""))) as NAME')
-                )
-                ->where('USUA_NULI', '=', $line_number)
-                ->get();
-
-            $employees = DB::table('S002V01TPERS')
-                ->select(
-                    DB::raw('TRIM(CONCAT(S002V01TUSUA.USUA_NOMB, " " , S002V01TUSUA.USUA_APPA, " ", COALESCE(S002V01TUSUA.USUA_APMA,""))) as EMPLOYEE'),
-                    'S002V01TPERS.PERS_IDPS as TYPE_EMPLOYEE',
-                    'S002V01TPECO.PECO_IDCO as CONTRACT_ID',
-                    'S002V01TPESU.PESU_RASO AS SUBCONTRATIST',
-                )
-                ->where('S002V01TPERS.PERS_NULI', '=', $line_number)
-                ->where('S002V01TUSUA.USUA_NULI', '=', $line_number)
-                ->where('S002V01TPECO.PECO_NULI', '=', $line_number)
-                ->orWhere('S002V01TPESU.PESU_NULI', '=', $line_number)
-                ->join('S002V01TUSUA', 'S002V01TPERS.PERS_IDUS', '=', 'S002V01TUSUA.USUA_IDUS')
-                ->leftJoin('S002V01TPESU', 'S002V01TPERS.PERS_IDPS', '=', 'S002V01TPESU.PESU_IDPS')
-                ->join('S002V01TPECO', 'S002V01TPERS.PERS_IDPE', '=', 'S002V01TPECO.PECO_IDPE')
-                ->get();
-
-            $todays_date = Carbon::now();
-            // Itera los contratos para agregar a los dueños de los mismos y su duración
-            foreach ($contracts as $contract) {
-                $contract->DENOMINATION = [];
-                // Verifica el estado del contrato, si ya paso su fecha de fin
-                $contract->STATUS = $todays_date->greaterThan(Carbon::create($contract->END_DATE)) ? "Expirado" : "Activo";
-                $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);
-                $contract->DOCUMENT = $this->encrypt_controller->encrypt(Storage::disk('pdf')->url($contract->DOCUMENT));
-
-                // 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;
+        $workersArr = json_decode($workersStr, true);
+        $staff = [];
+        foreach($workersArr as $worker){
+            $type = $worker['TYPE'];
+            switch($type){
+                case "EM":
+                    if(!in_array(intval($worker['ID']), $staff)){
+                        $staff[] = intval($worker['ID']);
                     }
-                }
-
-                // 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;
+                break;
+                case "EQ": 
+                    $employees = DB::table('S002V01TPERS')->where([
+                        ['PERS_NULI', '=', $form['linea']],
+                        ['PERS_EQTR', '=', $worker['ID']],
+                    ])->get()->all();
+
+                    foreach($employees as $employee){
+                        if(!in_array(intval($employee->PERS_IDPE), $staff)){
+                            $staff[] = intval($employee->PERS_IDPE);
                         }
                     }
-                }
-
+                break;
+                case "SU":
+                    $employees = DB::table('S002V01TPERS')->where([
+                        ['PERS_NULI', '=', $form['linea']],
+                        ['PERS_IDPS', '=', $worker['ID']],
+                    ])->get()->all();
+
+                    foreach($employees as $employee){
+                        if(!in_array(intval($employee->PERS_IDPE), $staff)){
+                            $staff[] = intval($employee->PERS_IDPE);
+                        }
+                    }
+                break;
             }
-
-            return $this->response_controller
-                ->makeResponse(FALSE, 'Consulta exitosa', $contracts);
-
-        } catch (Throwable $th) {
-            return $this->response_controller
-                ->makeResponse(TRUE, 'ERR_INTERVENCIÓN_GET000: 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_NOMB as CONTRACT_NAME',
-                    '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);
-            }
+        $idEmployee = $this->encryptionController->decrypt($form['DENOMINATION']);
+        if(!$idEmployee){
+            return $this->responseController->makeResponse(true, 'El ID del empleado seleccionado no está encriptado correctamente.', [], 400);
+        }else if(!in_array(intval($idEmployee), $staff)){
+            return $this->responseController->makeResponse(true, 'El empleado seleccionado no está ligado a la orden de trabajo seleccionada.', [], 400);
+        }
 
-            $employee = DB::table('S002V01TPECO')
-                ->select("PECO_IDPE as DENOMINATION")
-                ->where('PECO_IDCO', '=', $id_contract)
-                ->where('PECO_NULI', '=', $line_number)
-                ->first();
-
-            $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);
-            $contract->DENOMINATION = $employee->DENOMINATION;
-
-            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);
+        $employee = DB::table('S002V01TPERS')->where([
+            ['PERS_NULI', '=', $form['linea']],
+            ['PERS_IDPE', '=', $idEmployee]
+        ])->first();
+        
+        if(is_null($employee)){
+            return $this->responseController->makeResponse(true, 'El empleado seleccionado no existe.', [], 404);
         }
-    }
 
-    // Metodo para guardar un contrato
-    public function storeContract(Request $request)
-    {
-        try {
-            $REGISTER_DATE = Carbon::now()->timezone('America/Mexico_City')->toDateTimeString();
-            $request['SAVED_BY_USER'] = $this->encrypt_controller->decrypt($request->SAVED_BY_USER);
-            $request['CONTRACT_COST'] = $this->encrypt_controller->decrypt($request->CONTRACT_COST);
-
-            $validator = Validator::make($request->all(), [
-                "CONTRACT_NAME" => ['required'],
-                "CONTRACT_TYPE" => ['required'],
-                "DENOMINATION" => ['required', 'size:10'],
-                "START_DATE" => ['required', 'date'],
-                "END_DATE" => ['required', 'date'],
-                "CONTRACT_COST" => ['required'],
-                "DOCUMENT" => ['required'],
-                "SAVED_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
-                );
-            }
+        $orderType = $idOrderArr[1] == 'prev' ? 'Preventivo' : 'Correctivo';
+        $contract = DB::table('S002V01TCONT')->where([
+            ['CONT_NULI', '=', $form['linea']],
+            ['CONT_IDEM', '=', $idEmployee],
+            ['CONT_IDOT', '=', $idOrder],
+            ['CONT_TOTR', '=', $orderType],
+        ])->first();
 
-            $user_register = DB::table('S002V01TUSUA')
-                ->select('USUA_IDUS as ID_USER')
-                ->where('USUA_IDUS', '=', $request->SAVED_BY_USER)
-                ->where('USUA_NULI', '=', $request->LINE_NUMBER)
-                ->first();
+        if(!is_null($contract)){
+            return $this->responseController->makeResponse(true, "El empleado #$idEmployee ya tiene un contrato relacionado a la orden de trabajo $orderType #$idOrder", [], 404);
+        }
 
-            // 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);
+        
+        $docsArr = json_decode($form['DOCUMENT'], true);
+        $finalDocsArr = [];
+        foreach($docsArr as $doc){
+            $idFileDec = $this->encryptionController->decrypt($doc['id']);
+            $tempFile = DB::table('S002V01TARTE')->where([
+                ['ARTE_NULI', '=', $form['linea']],
+                ['ARTE_IDAR', '=', $idFileDec],
+            ])->first();
+    
+            if(is_null($tempFile)){
+                return $this->responseController->makeResponse(true, "El archivo $doc[name] no está registrado.", [], 404);
             }
 
-            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', '=', $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_REG003: No se encontró al empleado', [], 500);
+            $cldo = "CO";
+            $finalFile = $this->documentManagementController->moveFinalFile($form['linea'], "GPRS", $cldo, $tempFile, $idUser);
+    
+            if(!$finalFile[0]){
+                return $this->responseController->makeResponse(true, $finalFile[1], [], 400);
+            }else{
+                $finalDocsArr[] = $finalFile[1];
             }
+        }
 
-            // Para la creación del contrato y guardar su enlace
-            $doc = $request->DOCUMENT;
-
-            // Se obtiene el nombre del archivo con su extensión
-            $completeFileName = $doc->getClientOriginalName();
+        if(!isset($form['CONTRACT_COST'])){
+            return $this->responseController->makeResponse(true, 'El costo del contrato no fue encriptado correctamente.', [], 400);
+        }
+        
+        $lido = json_encode($finalDocsArr);
+        $now = $this->functionsController->now();
+        $nowStr = $now->toDateTimeString();
+        $idContract = DB::table('S002V01TCONT')->insertGetId([
+            'CONT_NULI' => $form['linea'],
+            'CONT_NOCO' => $form['CONTRACT_NAME'],
+            'CONT_IDEM' => $idEmployee,
+            'CONT_IDOT' => $idOrder,
+            'CONT_TOTR' => $orderType,
+            'CONT_TIPO' => $form['CONTRACT_TYPE'],
+            'CONT_FEIN' => $form['START_DATE'],
+            'CONT_FEFI' => $form['END_DATE'],
+            'CONT_COST' => $form['CONTRACT_COST'],
+            'CONT_LIDO' => $lido,
+            'CONT_USRE' => $idUser,
+            'CONT_FERE' => $nowStr,
+        ]);
+
+        $actions = DB::getQueryLog();
+        $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
+        
+        $idac = $this->functionsController->registerActivity(
+            $form['linea'],
+            'S002V01M11GPRS',
+            'S002V01F02ADCN',
+            'S002V01P02RECO',
+            'Registro',
+            "El usuario $name (" . $usr->USUA_IDUS . ") registró el contrato #$idContract.",
+            $idUser,
+            $nowStr,
+            'S002V01S03GEIN'
+        );
+
+        $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']);
+        return $this->responseController->makeResponse(false, 'EXITO');
+    }
 
-            // Se obtiene únicamente el nombre
-            $fileNameOnly = pathinfo($completeFileName, PATHINFO_FILENAME);
+    public function getConsultOfContracts($idUser, $line) {
+        DB::enableQueryLog();
 
-            // Se obtiene la extensión del archivo
-            $extension = $doc->getClientOriginalExtension();
+        $idUser = $this->encryptionController->decrypt($idUser);
+        if(!$idUser){
+            return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente', [], 400);
+        }
 
-            // Se quitan los espacios y se concatena datos para ser guardado
-            $final_part_name_document = str_replace(' ', '_', $fileNameOnly) . '.' . $extension;
+        $usr = DB::table('S002V01TUSUA')->where([
+            ['USUA_NULI', '=', $line],
+            ['USUA_IDUS', '=', $idUser],
+        ])->first();
 
-            // Se agrega la fecha actual con el formato de la nomenclatura de documentos
-            $DATE_TO_DOCUMENT = Carbon::now()->timezone('America/Mexico_City')->format("ymd");
+        if(is_null($usr)){
+            return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado', [], 404);
+        }
 
-            // 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);
+        $contracts = DB::table('S002V01TCONT')->select([
+            'CONT_IDCO AS CONTRACT_ID',
+            'CONT_NOCO AS CONTRACT_NAME',
+            'CONT_IDEM AS DENOMINATION',
+            'CONT_IDOT AS WORK_ORDER_ID',
+            'CONT_TOTR AS WORK_ORDER_TYPE',
+            'CONT_TIPO AS CONTRACT_TYPE',
+            'CONT_FEIN AS START_DATE',
+            'CONT_FEFI AS END_DATE',
+            'CONT_COST AS CONTRACT_COST',
+            'CONT_LIDO AS DOCUMENT',
+            'CONT_USRE AS REGISTERED_BY',
+            'CONT_FERE AS REGISTER_DATE',
+            'CONT_USMO AS MODIFIED_BY',
+            'CONT_FEMO AS MODIFICATION_DATE',
+        ])->where('CONT_NULI', '=', $line)->get()->all();
+
+        $now = $this->functionsController->now();
+        $nowStr = $now->toDateTimeString();
+        foreach($contracts as $key=>$contract){
+            $contract->CONTRACT_ID = $this->encryptionController->encrypt($contract->CONTRACT_ID);
+            $contract->CONTRACT_COST = $this->encryptionController->encrypt($contract->CONTRACT_COST);
+            $docsArr = json_decode($contract->DOCUMENT);
+
+            $docsFN = [];
+            foreach($docsArr as $keyDoc=>$doc){
+                $docIDArr = explode('=', $doc);
+                $codeArr = explode('-', $docIDArr[0]);
+
+                $file = DB::table('S002V01TAFAL')->where([
+                    ['AFAL_NULI', '=', $line],
+                    ['AFAL_COMO', '=', $codeArr[1]],
+                    ['AFAL_CLDO', '=', $codeArr[2]],
+                    ['AFAL_FECR', '=', $codeArr[3]],
+                    ['AFAL_NUSE', '=', $codeArr[4]],
+                    ['AFAL_NUVE', '=', $docIDArr[1]],
+                ])->first();
+
+                $docsFN[] = [
+                    'id' => $this->encryptionController->encrypt($doc),
+                    'name' => $doc,
+                    'size' => $file->AFAL_TAMA
+                ];
             }
 
-            $contracts = DB::table("S002V01TCONT")
-                ->select("CONT_LIDO as SEQUENCE")
-                ->get();
-
-            $sequence_number = "000001";
-
-            // Itera cada archivo guardado en el la base
-            foreach ($contracts as $contract) {
-
-                // Encuentra el siguiente numero de secuencia
-                if (substr($contract->SEQUENCE, 18, 6) >= $sequence_number) {
-                    $sequence_number = substr($contract->SEQUENCE, 18, 6);
-                    $sequence_number++;
-                }
-
+            $contract->DOCUMENT = json_encode($docsFN);
+            $usrReg = DB::table('S002V01TUSUA')->where([
+                ['USUA_NULI', '=', $line],
+                ['USUA_IDUS', '=', $contract->REGISTERED_BY],
+            ])->first();
+
+            $contract->REGISTERED_BY = $this->functionsController->joinName(
+                $usrReg->USUA_NOMB, $usrReg->USUA_APPA, $usrReg->USUA_APMA
+            ) . " (" . $contract->REGISTERED_BY . ")";
+
+            if(!is_null($contract->MODIFIED_BY)){
+                $usrMod = DB::table('S002V01TUSUA')->where([
+                    ['USUA_NULI', '=', $line],
+                    ['USUA_IDUS', '=', $contract->MODIFIED_BY],
+                ])->first();
+    
+                $contract->MODIFIED_BY = $this->functionsController->joinName(
+                    $usrMod->USUA_NOMB, $usrMod->USUA_APPA, $usrMod->USUA_APMA
+                ) . " (" . $contract->MODIFIED_BY . ")";
             }
 
-            // Se crea el nombre del documento
-            $name_document = '01-GPRS-CO-' . $DATE_TO_DOCUMENT . '-' . $this->resources_controller->formatSecuence($sequence_number, 6) . '=01=' . $final_part_name_document;
-
-            // Verifica si el nombre de documento no existe aún
-            $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: El nombre de contrato ya ha sido ocupado el dia de hoy', [], 500);
-                    }
-                }
-            }
+            $employee = DB::table('S002V01TPERS')->join('S002V01TUSUA', 'USUA_IDUS', '=', 'PERS_IDUS')->where([
+                ['PERS_NULI', '=', $line],
+                ['PERS_IDPE', '=', $contract->DENOMINATION],
+            ])->first();
 
-            // El contrato es guardado en el storage
-            $doc->storeAs('public/pdf_documents', $name_document);
-
-            $insert_contract = DB::table('S002V01TCONT')
-                ->insert([
-                    "CONT_NOMB" => $request->CONTRACT_NAME,
-                    "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->SAVED_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);
-            }
+            $contract->DENOMINATION = $this->functionsController->joinName(
+                $employee->USUA_NOMB, $employee->USUA_APPA, $employee->USUA_APMA
+            ) . ' (' . $employee->PERS_IDPE . ') (' . $employee->PERS_IDUS . ')';
 
-            // Busca el id del contrato insertado
-            $contract_id = DB::table('S002V01TCONT')
-                ->select("CONT_IDCO as CONTRACT_ID")
-                ->where("CONT_NAME", '=', $request->CONTRACT_NAME)
-                ->where("CONT_TIPO", '=', $request->CONTRACT_TYPE)
-                ->where("CONT_FERE", '=', $REGISTER_DATE)
-                ->where("CONT_COST", '=', $request->CONTRACT_COST)
-                ->where("CONT_USRE", '=', $request->SAVED_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);
-            }
+            $contract->DURATION = $this->functionsController->getDatesDifference($contract->START_DATE, $contract->END_DATE);
+            $contracts[$key] = $contract;
 
-            $insert_contract_with_employee = DB::table('S002V01TPECO')
-                ->insert([
-                    "PECO_IDPE" => $request->DENOMINATION,
-                    "PECO_IDCO" => $contract_id,
-                    "PECO_USRE" => $request->SAVED_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);
-            }
+            $endDate = new Carbon($contract->END_DATE);
+            $status = $now->gt($endDate) ? 'Expirado' : 'Activo';
+            $contract->STATUS = $status;
+        }
 
-            DB::commit(); # Para guardar los cambios en la base de datos
-            return $this->response_controller->makeResponse(FALSE, 'Registro exitoso', 200);
+        $actions = DB::getQueryLog();
+        $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
+        
+        $idac = $this->functionsController->registerActivity(
+            $line,
+            'S002V01M11GPRS',
+            'S002V01F02ADCN',
+            'S002V01P01COCO',
+            'Consulta',
+            "El usuario $name (" . $usr->USUA_IDUS . ") consultó los contratos registrados.",
+            $idUser,
+            $nowStr,
+            'S002V01S03GEIN'
+        );
+
+        $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
+        return $this->responseController->makeResponse(false, 'EXITO', $contracts);
+    }
 
+    public function getConsultOfInterventions($idUser, $line) {
+        DB::enableQueryLog();
 
-        } catch (Throwable $th) {
-            return $this->response_controller
-                ->makeResponse(TRUE, 'ERR_CONTRATO_REG009: Error inesperado', strtoupper($th->getMessage()), 500);
+        $idUser = $this->encryptionController->decrypt($idUser);
+        if(!$idUser){
+            return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente', [], 400);
         }
-    }
 
-    // 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_NOMB as CONTRACT_NANE',
-                    '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();
-
-            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);
-            }
+        $usr = DB::table('S002V01TUSUA')->where([
+            ['USUA_NULI', '=', $line],
+            ['USUA_IDUS', '=', $idUser],
+        ])->first();
 
-            return $this->response_controller
-                ->makeResponse(FALSE, 'Consulta exitosa', $contracts);
+        if(is_null($usr)){
+            return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado', [], 404);
+        }
 
-        } catch (Throwable $th) {
-            return $this->response_controller
-                ->makeResponse(TRUE, 'ERR_INTERVENCIÓN_REG002: Error inesperado', strtoupper($th->getMessage()), 500);
+        //PENDIENTE LIGAR CON EQUIPAMIENTOS
+        $preventiveInterventions = DB::table('S002V01TBEOT')->select([
+            DB::raw('CONCAT(BEOT_IDRE, "|", BEOT_FEPR) AS IDREG'),
+            'OTPR_IDOT AS IDORDER',
+            'OTPR_EQIN AS EQUIPMENT',
+            'BEOT_TIOR AS ORDER_TYPE',
+            'BEOT_TIAC AS ACTION_TYPE',
+            'BEOT_FEEJ AS START_DATE',
+            'BEOT_FEFI AS END_DATE',
+        ])->join('S002V01TOTPR', 'OTPR_IDOT', '=', 'BEOT_IDOT')->where([
+            ['BEOT_NULI', '=', $line],
+            ['BEOT_TIOR', '=', 'Preventivo'],
+        ])->get()->all();
+
+        foreach($preventiveInterventions as $key=>$val){
+            $val->IDREG = $this->encryptionController->encrypt($val->IDREG);
+            $preventiveInterventions[$key] = $val;
         }
-    }
 
-}
+        //PENDIENTE MANTENIMIENTO CORRECTIVO
+
+        $now = $this->functionsController->now();
+        $nowStr = $now->toDateTimeString();
+        $actions = DB::getQueryLog();
+        $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
+        
+        $idac = $this->functionsController->registerActivity(
+            $line,
+            'S002V01M11GPRS',
+            'S002V01F01ADIN',
+            '-',
+            'Consulta',
+            "El usuario $name (" . $usr->USUA_IDUS . ") consultó las intervenciones registradas.",
+            $idUser,
+            $nowStr,
+            'S002V01S03GEIN'
+        );
+
+        $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
+        return $this->responseController->makeResponse(false, 'EXITO', $preventiveInterventions);
+    }
+}

+ 1288 - 1045
sistema-mantenimiento-back/app/Http/Controllers/SubcontractController.php

@@ -1,1190 +1,1433 @@
 <?php
-/*
-Nombre del programador:         Cordourier Rojas Mathew
-Ultima fecha de modificación:   [ 24 / Abril / 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\Database\Query\Builder;
 use Illuminate\Http\Request;
 use Illuminate\Support\Facades\DB;
 use Illuminate\Support\Facades\Storage;
 use Illuminate\Support\Facades\Validator;
+use Illuminate\Http\File;
+
 use PhpOffice\PhpSpreadsheet\IOFactory;
 use PhpOffice\PhpSpreadsheet\Spreadsheet;
+use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
+use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
+use PhpOffice\PhpSpreadsheet\Style\Fill;
+use PhpOffice\PhpSpreadsheet\Style\Alignment;
+use PhpOffice\PhpSpreadsheet\Style\NumberFormat;
+use PhpOffice\PhpSpreadsheet\Style\Border;
+
 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();
+class SubcontractController extends Controller{
+    private $responseController;
+    private $encryptionController;
+    private $documentManagementController;
+    private $functionsController;
+
+    public function __construct(){
+        $this->responseController = new ResponseController();
+        $this->encryptionController = new EncryptionController();
+        $this->documentManagementController = new DocumentManagementController();
+        $this->functionsController = new FunctionsController();
     }
 
-    // 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_FEMO AS UPDATE_DATE',
-                    'PESU_USRE AS REGISTERED_BY_USER',
-                    'PESU_USMO AS UPDATED_BY_USER',
-                    'PESU_ESTA AS STATUS'
-                )
-                ->where('PESU_NULI', '=', $line_number)
-                ->get();
-
-
-            $users_register_name = DB::table('S002V01TUSUA')
-                ->select('USUA_IDUS AS USERID', DB::raw('TRIM(CONCAT(USUA_NOMB, " " , USUA_APPA, " ", COALESCE(USUA_APMA,""))) AS NAME'))
-                ->where('USUA_NULI', '=', $line_number)
-                ->get();
-
-            $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();
-
-            // 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->UPDATE_DATE != null ? $subcontratist->UPDATE_DATE = Carbon::create($subcontratist->UPDATE_DATE)->format("d-m-Y h:i:s A") : null;
-
-                $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;
-                    }
+    public function getConsultOfSubcontratists($idUser, $line) {
+        DB::enableQueryLog();
 
-                    if ($subcontratist->UPDATED_BY_USER == $user_register->USERID) {
-                        $subcontratist->UPDATED_BY_USER = $user_register->NAME;
-                    }
+        $idUser = $this->encryptionController->decrypt($idUser);
+        if(!$idUser){
+            return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente', [], 400);
+        }
 
-                }
+        $usr = DB::table('S002V01TUSUA')->where([
+            ['USUA_NULI', '=', $line],
+            ['USUA_IDUS', '=', $idUser],
+        ])->first();
 
-                // 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;
+        if(is_null($usr)){
+            return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado', [], 404);
+        }
 
+        $subcontratists = DB::table('S002V01TPESU')->select([
+            'PESU_IDPS as ID_SUBCONTRATIST',
+            DB::raw('CONCAT(PESU_RASO, " (" , COALESCE(PESU_REFI, ""), ")") AS NAME'),
+            'PESU_EXTR AS TIPO',
+            'PESU_ESPE AS SPECIALTY',
+            'PESU_FERE AS REGISTER_DATE',
+            'PESU_FEMO AS UPDATE_DATE',
+            'PESU_USRE AS REGISTERED_BY_USER',
+            'PESU_USMO AS UPDATED_BY_USER',
+            'PESU_ESTA AS STATUS'
+        ])->where('PESU_NULI', '=', $line)->get()->all();
+
+        foreach($subcontratists as $subcontratist){
+            $regUsr = DB::table('S002V01TUSUA')->where([
+                ['USUA_NULI', '=', $line],
+                ['USUA_IDUS', '=', $subcontratist->REGISTERED_BY_USER],
+            ])->first();
+
+            if(!is_null($regUsr)){
+                $subcontratist->REGISTERED_BY_USER = $this->functionsController->joinName($regUsr->USUA_NOMB, $regUsr->USUA_APPA, $regUsr->USUA_APMA) . " (" . $subcontratist->REGISTERED_BY_USER . ")";
+            }else{
+                $subcontratist->REGISTERED_BY_USER = "DESCONOCIDO (" . $subcontratist->REGISTERED_BY_USER . ")";
+            }
+            
+            if(!is_null($subcontratist->UPDATED_BY_USER)){
+                $modUsr = DB::table('S002V01TUSUA')->where([
+                    ['USUA_NULI', '=', $line],
+                    ['USUA_IDUS', '=', $subcontratist->UPDATED_BY_USER],
+                ])->first();
+    
+                if(!is_null($modUsr)){
+                    $subcontratist->UPDATED_BY_USER = $this->functionsController->joinName($modUsr->USUA_NOMB, $modUsr->USUA_APPA, $modUsr->USUA_APMA) . " (" . $subcontratist->UPDATED_BY_USER . ")";
+                }else{
+                    $subcontratist->UPDATED_BY_USER = "DESCONOCIDO (" . $subcontratist->UPDATED_BY_USER . ")";
+                }
             }
 
-            return $this->response_controller->makeResponse(FALSE, 'Consulta exitosa', $subcontratists);
-
-        } catch (Throwable $e) {
-            return $this->response_controller
-                ->makeResponse(TRUE, 'ERR_SUBCONTRATISTA_REG001: Error inesperado', strtoupper($e->getMessage()), 500);
-        }
-    }
-
-    // Metodo para la eliminación lógica de un subcontratista
-    public function updateToInactiveStatus(Request $request, $id_subcontratist)
-    {
-        try {
-
-            $request['SAVED_BY_USER'] = $this->encrypt_controller->decrypt($request->SAVED_BY_USER);
-            $validator = Validator::make($request->all(), [
-                "SAVED_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
-                );
+            if($subcontratist->TIPO == 'No'){
+                $subcontratist->TIPO = 'Nacional';
+            }else{
+                $subcontratist->TIPO = 'Extranjero';
             }
 
-            $user_register = DB::table('S002V01TUSUA')
-                ->select('USUA_IDUS as ID_USER')
-                ->where('USUA_IDUS', '=', $request->SAVED_BY_USER)
-                ->where('USUA_NULI', '=', $request->LINE_NUMBER)
-                ->first();
+            $preventiveInterventions = DB::select("
+            SELECT 
+                DISTINCT(S002V01TOTPR.OTPR_IDOT), 
+                OPPR.*
+            FROM 
+                S002V01TOTPR, 
+                JSON_TABLE(OTPR_OPPR, '$[*]' COLUMNS(
+                    OTPR_OPPR_ID INT PATH '$.ID', 
+                    OTPR_OPPR_TYPE VARCHAR(100) PATH '$.TYPE'
+                )) OPPR 
+            WHERE 
+                OPPR.OTPR_OPPR_TYPE = :emp_type
+                AND OPPR.OTPR_OPPR_ID = :emp_id
+            ", ['emp_type' => 'SU', 'emp_id' => $subcontratist->ID_SUBCONTRATIST]);
+            //PENDIENTE IMPLEMENTAR INTERVENCIONES DE MANTENIMIENTO CORRECTIVO
+            $subcontratist->INTERVENTIONS_COUNT = count($preventiveInterventions);
+        }
 
-            // 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);
-            }
+        $now = $this->functionsController->now();
+        $nowStr = $now->toDateTimeString();
+        $actions = DB::getQueryLog();
+        $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
+        
+        $idac = $this->functionsController->registerActivity(
+            $line,
+            'S002V01M11GPRS',
+            'S002V01F01GESU',
+            'S002V01P01COSU',
+            'Consulta',
+            "El usuario $name (" . $usr->USUA_IDUS . ") consultó los subcontratistas registrados.",
+            $idUser,
+            $nowStr,
+            'S002V01S01GESU'
+        );
+
+        $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
+        return $this->responseController->makeResponse(false, 'EXITO', $subcontratists);
+    }
 
-            // 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);
-            }
+    public function storeSubcontratist(Request $request) {
+        DB::enableQueryLog();
+
+        $request['TELEPHONE1'] = $this->encryptionController->decrypt($request->TELEPHONE1) ? $this->encryptionController->decrypt($request->TELEPHONE1) : 'ENC_ERR';
+        $request['TELEPHONE2'] = $this->encryptionController->decrypt($request->TELEPHONE2) ? $this->encryptionController->decrypt($request->TELEPHONE2) : 'ENC_ERR';
+        $request['EMAIL'] = $this->encryptionController->decrypt($request->EMAIL) ? $this->encryptionController->decrypt($request->EMAIL) : 'ENC_ERR';
+        $request['RFC'] = $this->encryptionController->decrypt($request->RFC) ? $this->encryptionController->decrypt($request->RFC) : 'ENC_ERR';
+        $request['TAX'] = $this->encryptionController->decrypt($request->TAX) ? $this->encryptionController->decrypt($request->TAX) : 'ENC_ERR';
+
+        $validator = Validator::make($request->all(), [
+            'id_user' => 'required|string',
+            'linea' => 'required|integer',
+            'SOCIAL_REASON' => 'required|string|max:150',
+            'TAX_REFERENCE' => 'required|string|max:15',
+            'CONTRACT_TYPE' => 'required|string|in:Persona moral,Persona física',
+            'FOREIGNER' => 'required|string|in:Si,No',
+            'RFC' => 'required_if:FOREIGNER,=,No|string|max:13',
+            'TAX' => 'required_if:FOREIGNER,=,Si|string|max:13',
+            'EMAIL' => 'required|string|max:150',
+            'COUNTRY' => 'required|string|max:75',
+            'FEDERAL_ENTITY' => 'required|string|max:75',
+            'CITY' => 'string|max:75',
+            'TOWN' => 'string|max:75',
+            'SUBURB' => 'required|string|max:75',
+            'POSTAL_CODE' => 'required|string|max:5',
+            'STREET' => 'required|string|max:150',
+            'EXTERIOR_NUMBER' => 'required|integer',
+            'INTERIOR_NUMBER' => 'integer',
+            'LADA1' => 'required|string|max:15',
+            'TELEPHONE1' => 'required|string|min:7|max:11',
+            'LADA2' => 'string|max:15',
+            'TELEPHONE2' => 'string|min:7|max:11',
+            'SPECIALTY' => 'required|string|max:100'
+        ]);
+
+        if($validator->fails()){
+            return $this->responseController->makeResponse(
+                true,
+                "Se encontraron uno o más errores.",
+                $this->responseController->makeErrors(
+                    $validator->errors()->messages()
+                ),
+                401
+            );
+        }
 
-            // 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_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_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" => "Eliminado",
-                        "PESU_USMO" => trim($request->SAVED_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);
-                }
+        $form = $request->all();
+        foreach($form as $k=>$v){
+            if($k == 'INTERIOR_NUMBER' && $v == '0'){
+                unset($form[$k]);
+            }else if($v == '-'){
+                unset($form[$k]);
             }
+        }
 
-            return $response;
+        $idUser = $this->encryptionController->decrypt($form['id_user']);
+        if(!$idUser){
+            return $this->responseController->makeResponse(true, 'El ID de usuario no fue encriptado correctamente.', [], 400);
+        }
 
-        } catch (Throwable $th) {
-            return $this->response_controller
-                ->makeResponse(TRUE, 'ERR_SUBCONTRATISTA_REG006: Error inesperado', strtoupper($th->getMessage()), 500);
+        $usr = DB::table('S002V01TUSUA')->where([
+            ['USUA_NULI', '=', $form['linea']],
+            ['USUA_IDUS', '=', $idUser]
+        ])->first();
+        
+        if(is_null($usr)){
+            return $this->responseController->makeResponse(true, 'El usuario que realizó la petición no existe.', [], 404);
         }
-    }
 
-    // Metodo para la activación lógica de un subcontratista
-    public function updateToActiveStatus(Request $request, $id_subcontratist)
-    {
-        try {
-
-            $request['SAVED_BY_USER'] = $this->encrypt_controller->decrypt($request->SAVED_BY_USER);
-            $validator = Validator::make($request->all(), [
-                "SAVED_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
-                );
+        $ladasValues = [];
+        $ladas = DB::table('S002V01TPAIS')->select([
+            'PAIS_LADA AS LADA'
+        ])->where('PAIS_NULI', '=', $form['linea'])->get()->all();
+
+        foreach($ladas as $lada){
+            if($lada->LADA != '' && $lada->LADA != '0'){
+                $ladasValues[] = $lada->LADA;
             }
+        }
 
-            $user_register = DB::table('S002V01TUSUA')
-                ->select('USUA_IDUS as ID_USER')
-                ->where('USUA_IDUS', '=', $request->SAVED_BY_USER)
-                ->where('USUA_NULI', '=', $request->LINE_NUMBER)
-                ->first();
+        if(!in_array($form['LADA1'], $ladasValues)){
+            return $this->responseController->makeResponse(true, "La lada $form[LADA1] no está relacionada a ningún país.", [], 400);
+        }else if($form['TELEPHONE1'] == 'ENC_ERR'){
+            return $this->responseController->makeResponse(true, 'El número telefónico 1 no fue encriptado correctamente.', [], 400);
+        }
 
-            // 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 activar subcontratistas", [], 500);
+        $lada2 = null;
+        $phone2 = null;
+        if(isset($form['LADA2'])){
+            if(!in_array($form['LADA2'], $ladasValues)){
+                return $this->responseController->makeResponse(true, "La lada $form[LADA2] no está relacionada a ningún país.", [], 400);
+            }else if($form['TELEPHONE2'] == 'ENC_ERR'){
+                return $this->responseController->makeResponse(true, 'El número telefónico 2 no fue encriptado correctamente.', [], 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 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);
-            }
+            $lada2 = $form['LADA2'];
+            $phone2 = $form['TELEPHONE2'];
+        }
 
-                $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" => "Activo",
-                        "PESU_USMO" => trim($request->SAVED_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, "Activación exitosa");
-                } else {
-                    $response = $this->response_controller
-                        ->makeResponse(TRUE, 'ERR_SUBCONTRATISTA_REG005: Algo salió mal, error activando al subcontratista', [], 500);
-                }
+        if($form['EMAIL'] == 'ENC_ERR'){
+            return $this->responseController->makeResponse(true, 'El email no fue encriptado correctamente.', [], 400);
+        }
 
-            return $response;
+        $rfcx = null;
+        if(isset($form['RFC']) && $form['FOREIGNER'] == 'No' && $form['RFC'] == 'ENC_ERR'){
+            return $this->responseController->makeResponse(true, 'El RFC no fue encriptado correctamente.', [], 400);
+        }else if(isset($form['RFC']) && $form['RFC'] != 'ENC_ERR'){
+            $rfcx = $form['RFC'];
+        }
 
-        } catch (Throwable $th) {
-            return $this->response_controller
-                ->makeResponse(TRUE, 'ERR_SUBCONTRATISTA_REG006: Error inesperado', strtoupper($th->getMessage()), 500);
+        $taid = null;
+        if(isset($form['TAX']) && $form['FOREIGNER'] == 'Si' && $form['TAX'] == 'ENC_ERR'){
+            return $this->responseController->makeResponse(true, 'El TAX ID no fue encriptado correctamente.', [], 400);
+        }else if(isset($form['TAX']) && $form['TAX'] != 'ENC_ERR'){
+            $taid =  $form['TAX'];
+        }
+        
+        $country = DB::table('S002V01TPAIS')->where([
+            ['PAIS_NULI', '=', $form['linea']],
+            ['PAIS_IDPA', '=', $form['COUNTRY']],
+        ])->first();
+        
+        if(is_null($country)){
+            return $this->responseController->makeResponse(true, 'El país seleccionado no existe.', [], 404);
+        }
+        
+        $taxRegime = DB::table('S002V01TREFI')->where([
+            ['REFI_NULI', '=', $form['linea']],
+            ['REFI_CRFI', '=', $form['TAX_REFERENCE']],
+        ])->first();
+        
+        if(is_null($taxRegime)){
+            return $this->responseController->makeResponse(true, 'El régimen fiscal seleccionado no existe.', [], 404);
         }
-    }
 
-    // Metodo para guardar un nuevo subcontratista
-    public function storeSubcontratist(Request $request)
-    {
-
-        $REGISTER_DATE = Carbon::now()->timezone('America/Mexico_City')->toDateTimeString();
-        $request['SAVED_BY_USER'] = $this->encrypt_controller->decrypt($request->SAVED_BY_USER);
-        $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);
-        $request['TAX'] = $this->encrypt_controller->decrypt($request->TAX);
-
-        try {
-
-            $validator = Validator::make($request->all(), [
-                "RFC" => ['max:13'],
-                "SOCIAL_REASON" => ['required', 'max:150'],
-                "TAX_REFERENCE" => ['max:45'],
-                "CONTRACT_TYPE" => ['required'],
-                "EMAIL" => ['required', 'email', 'max:150'],
-                "FOREIGNER" => ['required'],
-                "TAX" => ['max:13'],
-                "STREET" => ['required', 'max:50'],
-                "EXTERIOR_NUMBER" => ['required','string'],
-                "SUBURB" => ['required', 'max:50'],
-                "CITY" => ['required', 'max:50'],
-                "POSTAL_CODE" => ['required', 'digits:5'],
-                "FEDERAL_ENTITY" => ['required', 'max:50'],
-                "COUNTRY" => ['required'],
-                "TELEPHONE1" => ['required', 'digits_between:7,11'],
-                "LADA1" => ['required', 'max:5'],
-                "SAVED_BY_USER" => ['required', 'digits:10'],
-                "TELEPHONE2" => ['digits_between:7,11'],
-                "LADA2" => ['max:5'],
-                "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
-                );
+        $colo = null;
+        $ciud = null;
+        $loca = null;
+        if($form['COUNTRY'] == 'MEX' || $form['COUNTRY'] == 'USA' || $form['COUNTRY'] == 'CAN'){
+            $state = DB::table('S002V01TESTA')->where([
+                ['ESTA_NULI', '=', $form['linea']],
+                ['ESTA_COES', '=', $form['FEDERAL_ENTITY']],
+                ['ESTA_COPA', '=', $form['COUNTRY']],
+            ])->first();
+        
+            if(is_null($state)){
+                return $this->responseController->makeResponse(true, 'El estado seleccionado no existe.', [], 404);
             }
 
-            // 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($form['COUNTRY'] == 'MEX'){
+                if(isset($form['CITY'])){
+                    $city = DB::table('S002V01TMUNI')->where([
+                        ['MUNI_NULI', '=', $form['linea']],
+                        ['MUNI_COMU', '=', $form['CITY']],
+                        ['MUNI_COES', '=', $form['FEDERAL_ENTITY']],
+                    ])->first();
+            
+                    if(is_null($city)){
+                        return $this->responseController->makeResponse(true, 'El municipio seleccionado no existe.', [], 404);
+                    }else{
+                        $ciud = $form['CITY'];
                     }
+                }
 
-                    if ($subcontratist->EMAIL == $request->EMAIL) {
-                        $duplicated_data[] = "Email: " . $subcontratist->EMAIL;
+                if(isset($form['TOWN'])){
+                    $town = DB::table('S002V01TLOCA')->where([
+                        ['LOCA_NULI', '=', $form['linea']],
+                        ['LOCA_COLO', '=', $form['TOWN']],
+                        ['LOCA_COES', '=', $form['FEDERAL_ENTITY']],
+                    ])->first();
+            
+                    if(is_null($town)){
+                        return $this->responseController->makeResponse(true, 'La localidad seleccionada no existe.', [], 404);
+                    }else{
+                        $loca = $form['TOWN'];
                     }
                 }
-
-                if (isset($duplicated_data[0]) && !empty($duplicated_data[0])) {
-                    return $this->response_controller->makeResponse(TRUE, 'ERR_SUBCONTRATISTA_REG002: Datos duplicados', $duplicated_data, 500);
+                
+                $setting = DB::table('S002V01TCOLO')->where([
+                    ['COLO_NULI', '=', $form['linea']],
+                    ['COLO_COCO', '=', $form['SUBURB']],
+                    ['COLO_COPO', '=', $form['POSTAL_CODE']],
+                ])->first();
+            
+                if(is_null($setting)){
+                    return $this->responseController->makeResponse(true, 'La colonia seleccionada no existe.', [], 404);
+                }else{
+                    $colo = $form['SUBURB'];
+                }
+                
+                $zipCode = DB::table('S002V01TCOPO')->where([
+                    ['COPO_NULI', '=', $form['linea']],
+                    ['COPO_COPO', '=', $form['POSTAL_CODE']],
+                    ['COPO_COES', '=', $form['FEDERAL_ENTITY']],
+                ])->first();
+            
+                if(is_null($zipCode)){
+                    return $this->responseController->makeResponse(true, 'El código postal seleccionado no existe.', [], 404);
                 }
+            }else{
+                $colo = $form['SUBURB'];
+                $ciud = $form['CITY'];
+                $loca = isset($form['TOWN']) ? $form['TOWN'] : null;
             }
+        }else{
+            $colo = $form['SUBURB'];
+            $ciud = $form['CITY'];
+            $loca = isset($form['TOWN']) ? $form['TOWN'] : null;
+        }
 
-            $user_register = DB::table('S002V01TUSUA')
-                ->select('USUA_IDUS as ID_USER')
-                ->where('USUA_IDUS', '=', $request->SAVED_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);
-            }
+        $subArr = DB::table('S002V01TPESU')->where('PESU_NULI', '=', $form['linea'])->where(function(Builder $query) use ($form) {
+            $query->where('PESU_RASO', '=', $form['SOCIAL_REASON'])
+            ->orWhere('PESU_XRFC', '=', $form['RFC'])
+            ->orWhere('PESU_CORR', '=', $form['EMAIL']);
+        })->where('PESU_ESTA', '=', 'Activo')->get()->all();
 
-            $insert_subcontratist = DB::table('S002V01TPESU')->insert([
-                "PESU_NULI" => $request->LINE_NUMBER,
-                "PESU_RASO" => $request->SOCIAL_REASON != null ? trim($request->SOCIAL_REASON) : null,
-                "PESU_REFI" => $request->TAX_REFERENCE != null ? trim($request->TAX_REFERENCE) : null,
-                "PESU_XRFC" => $request->RFC != null ? trim($request->RFC) : null,
-                "PESU_TIPO" => $request->CONTRACT_TYPE != null ? trim($request->CONTRACT_TYPE) : null,
-                "PESU_CORR" => $request->EMAIL != null ? trim($request->EMAIL) : null,
-                "PESU_EXTR" => $request->FOREIGNER != null ? trim($request->FOREIGNER) : null,
-                "PESU_TAID" => $request->TAX != null ? trim($request->TAX) : null,
-                "PESU_CALL" => $request->STREET != null ? trim($request->STREET) : null,
-                "PESU_NOEX" => $request->EXTERIOR_NUMBER != null ? trim($request->EXTERIOR_NUMBER) : null,
-                "PESU_COLO" => $request->SUBURB != null ? trim($request->SUBURB) : null,
-                "PESU_CIUD" => $request->CITY != null ? trim($request->CITY) : null,
-                "PESU_COPO" => $request->POSTAL_CODE != null ? trim($request->POSTAL_CODE) : null,
-                "PESU_ENFE" => $request->FEDERAL_ENTITY != null ? trim($request->FEDERAL_ENTITY) : null,
-                "PESU_IDPA" => $request->COUNTRY != null ? trim($request->COUNTRY) : null,
-                "PESU_TEL1" => $request->TELEPHONE1 != null ? trim($request->TELEPHONE1) : null,
-                "PESU_LAT1" => $request->LADA1 != null ? trim($request->LADA1) : null,
-                "PESU_TEL2" => $request->TELEPHONE2 != null ? trim($request->TELEPHONE2) : null,
-                "PESU_LAT2" => $request->LADA2 != null ? trim($request->LADA2) : null,
-                "PESU_USRE" => $request->SAVED_BY_USER != null ? trim($request->SAVED_BY_USER) : null,
-                "PESU_NOIN" => $request->INTERIOR_NUMBER == '' ? null : trim($request->INTERIOR_NUMBER),
-                "PESU_ESTA" => "Activo",
-                "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);
-            }
+        if(count($subArr) > 0){
+            return $this->responseController->makeResponse(true, 'La razón social, el RFC o el correo electrónico ya fueron registrados.', [], 401);
+        }
 
-            return $response;
+        $nuin = isset($form['INTERIOR_NUMBER']) ? $form['INTERIOR_NUMBER'] : null;
+        $now = $this->functionsController->now();
+        $nowStr = $now->toDateTimeString();
+        $subcontratistID = DB::table('S002V01TPESU')->insertGetId([
+            'PESU_NULI' => $form['linea'],
+            'PESU_RASO' => $form['SOCIAL_REASON'],
+            'PESU_REFI' => $form['TAX_REFERENCE'],
+            'PESU_XRFC' => $rfcx,
+            'PESU_TIPO' => $form['CONTRACT_TYPE'],
+            'PESU_CORR' => $form['EMAIL'],
+            'PESU_EXTR' => $form['FOREIGNER'],
+            'PESU_TAID' => $taid,
+            'PESU_CALL' => $form['STREET'],
+            'PESU_NUEX' => $form['EXTERIOR_NUMBER'],
+            'PESU_NUIN' => $nuin,
+            'PESU_COLO' => $colo,
+            'PESU_CIUD' => $ciud,
+            'PESU_LOCA' => $loca,
+            'PESU_COPO' => $form['POSTAL_CODE'],
+            'PESU_ENFE' => $form['FEDERAL_ENTITY'],
+            'PESU_IDPA' => $form['COUNTRY'],
+            'PESU_TEL1' => $form['TELEPHONE1'],
+            'PESU_LAT1' => $form['LADA1'],
+            'PESU_TEL2' => $phone2,
+            'PESU_LAT2' => $lada2,
+            'PESU_ESPE' => $form['SPECIALTY'],
+            'PESU_USRE' => $idUser,
+            'PESU_FERE' => $nowStr,
+        ]);
+
+        $actions = DB::getQueryLog();
+        $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
+        
+        $idac = $this->functionsController->registerActivity(
+            $form['linea'],
+            'S002V01M11GPRS',
+            'S002V01F01GESU',
+            'S002V01P02RESU',
+            'Registro',
+            "El usuario $name (" . $usr->USUA_IDUS . ") registró al subcontratista $form[SOCIAL_REASON] ($subcontratistID).",
+            $idUser,
+            $nowStr,
+            'S002V01S01GESU'
+        );
+
+        $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']);
+        return $this->responseController->makeResponse(false, 'EXITO');
+    }
 
+    public function getSubcontratistById($idSub, $idUser, $line) {
+        DB::enableQueryLog();
 
-        } catch (Throwable $th) {
-            return $this->response_controller
-                ->makeResponse(TRUE, 'ERR_SUBCONTRATISTA_REG005: Error inesperado', strtoupper($th->getMessage()), 500);
+        $idUser = $this->encryptionController->decrypt($idUser);
+        if(!$idUser){
+            return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la consulta no está encriptado correctamente.', [], 400);
         }
 
-    }
-
-    // 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 SUBURB',
-                    'S002V01TPESU.PESU_CIUD as CITY',
-                    'S002V01TPESU.PESU_COPO as POSTAL_CODE',
-                    'S002V01TPESU.PESU_ENFE as FEDERAL_ENTITY',
-                    'S002V01TPESU.PESU_IDPA 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);
-            }
+        $usr = DB::table('S002V01TUSUA')->where([
+            ['USUA_IDUS', '=', $idUser],
+            ['USUA_NULI', '=', $line]
+        ])->first();
 
-            $subcontratists_info->RFC != null ? $subcontratists_info->RFC = $this->encrypt_controller->encrypt($subcontratists_info->RFC) : null;
-            $subcontratists_info->TAX != null ? $subcontratists_info->TAX = $this->encrypt_controller->encrypt($subcontratists_info->TAX) : null;
-            $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);
+        if(is_null($usr)){
+            return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado', [], 404);
+        }
+        
+        $idSub = $this->encryptionController->decrypt($idSub);
+        if(!$idSub){
+            return $this->responseController->makeResponse(true, 'El ID del subcontratista consultado no está encriptado correctamente.', [], 400);
+        }
 
-            return $this->response_controller->makeResponse(FALSE, 'Consulta exitosa', $subcontratists_info);
+        $subcontratists_info = DB::table('S002V01TPESU')->select([
+            'PESU_IDPS as ID_SUBCONTRATIST',
+            'PESU_RASO as SOCIAL_REASON',
+            'PESU_REFI as TAX_REFERENCE',
+            'PESU_XRFC as RFC',
+            'PESU_TIPO as CONTRACT_TYPE',
+            'PESU_CORR as EMAIL',
+            'PESU_EXTR as FOREIGNER',
+            'PESU_TAID as TAX',
+            'PESU_CALL as STREET',
+            'PESU_NUEX as EXTERIOR_NUMBER',
+            'PESU_NUIN as INTERIOR_NUMBER',
+            'PESU_COLO as SUBURB',
+            'PESU_CIUD as CITY',
+            'PESU_LOCA as TOWN',
+            'PESU_COPO as POSTAL_CODE',
+            'PESU_ENFE as FEDERAL_ENTITY',
+            'PESU_IDPA as COUNTRY',
+            'PESU_TEL1 as TELEPHONE1',
+            'PESU_LAT1 as LADA1',
+            'PESU_TEL2 as TELEPHONE2',
+            'PESU_LAT2 as LADA2',
+            'PESU_ESPE as SPECIALTY',
+            'PESU_ESTA as STATUS'
+        ])->where([
+            ['PESU_NULI', '=', $line],
+            ['PESU_IDPS', '=', $idSub],
+        ])->first();
+
+        $taxRegime = DB::table('S002V01TREFI')->where([
+            ['REFI_NULI', '=', $line],
+            ['REFI_CRFI', '=', $subcontratists_info->TAX_REFERENCE],
+        ])->first();
+        $subcontratists_info->TAX_REFERENCE = $taxRegime->REFI_DRFI . " (" . $subcontratists_info->TAX_REFERENCE . ")";
+
+        $country = DB::table('S002V01TPAIS')->where([
+            ['PAIS_NULI', '=', $line],
+            ['PAIS_IDPA', '=', $subcontratists_info->COUNTRY],
+        ])->first();
+
+        $state = DB::table('S002V01TESTA')->where([
+            ['ESTA_NULI', '=', $line],
+            ['ESTA_COES', '=', $subcontratists_info->FEDERAL_ENTITY],
+            ['ESTA_COPA', '=', $subcontratists_info->COUNTRY],
+        ])->first();
+
+        $city = DB::table('S002V01TMUNI')->where([
+            ['MUNI_NULI', '=', $line],
+            ['MUNI_COMU', '=', $subcontratists_info->CITY],
+            ['MUNI_COES', '=', $subcontratists_info->FEDERAL_ENTITY],
+        ])->first();
+
+        $town = DB::table('S002V01TLOCA')->where([
+            ['LOCA_NULI', '=', $line],
+            ['LOCA_COLO', '=', $subcontratists_info->TOWN],
+            ['LOCA_COES', '=', $subcontratists_info->FEDERAL_ENTITY],
+        ])->first();
+
+        $setting = DB::table('S002V01TCOLO')->where([
+            ['COLO_NULI', '=', $line],
+            ['COLO_COCO', '=', $subcontratists_info->SUBURB],
+            ['COLO_COPO', '=', $subcontratists_info->POSTAL_CODE],
+        ])->first();
+
+        if(!is_null($country)){
+            $subcontratists_info->COUNTRY = trim($country->PAIS_NOMB) . " (" . $subcontratists_info->COUNTRY . ")";
+        }
 
-        } catch (Throwable $e) {
-            return $this->response_controller
-                ->makeResponse(TRUE, 'ERR_SUBCONTRATISTA_REG002: Error inesperado', strtoupper($e->getMessage()), 500);
+        if(!is_null($state)){
+            $subcontratists_info->FEDERAL_ENTITY = trim($state->ESTA_NOES) . " (" . $subcontratists_info->FEDERAL_ENTITY . ")";
         }
-    }
 
-    // Metodo para actualizar un subcontratista
-    public function updateSubcontratist(Request $request, $id_subcontratist)
-    {
-        $UPDATE_DATE = Carbon::now()->timezone('America/Mexico_City')->toDateTimeString();
-        $request['SAVED_BY_USER'] = $this->encrypt_controller->decrypt($request->SAVED_BY_USER);
-        $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'] != null ? $request['RFC'] = $this->encrypt_controller->decrypt($request->RFC) : null;
-        $request['TAX'] != null ? $request['TAX'] = $this->encrypt_controller->decrypt($request->TAX) : null;
-
-        try {
-            $validator = Validator::make($request->all(), [
-                "RFC" => ['max:13'],
-                "SOCIAL_REASON" => ['required', 'max:150'],
-                "TAX_REFERENCE" => ['max:45'],
-                "CONTRACT_TYPE" => ['required'],
-                "EMAIL" => ['required', 'email', 'max:150'],
-                "FOREIGNER" => ['required'],
-                "TAX" => ['max:13'],
-                "STREET" => ['required', 'max:50'],
-                "EXTERIOR_NUMBER" => ['required', 'string'],
-                "SUBURB" => ['required', 'max:50'],
-                "CITY" => ['required', 'max:50'],
-                "POSTAL_CODE" => ['required', 'digits:5'],
-                "FEDERAL_ENTITY" => ['required', 'max:50'],
-                "COUNTRY" => ['required'],
-                "TELEPHONE1" => ['required', 'digits_between:7,11'],
-                "LADA1" => ['required', 'max:5'],
-                "SAVED_BY_USER" => ['required', 'digits:10'],
-                "TELEPHONE2" => ['digits_between:7,11'],
-                "LADA2" => ['max:5'],
-                "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
-                );
-            }
+        if(!is_null($city)){
+            $subcontratists_info->CITY = trim($city->MUNI_NOMU) . " (" . $subcontratists_info->CITY . ")";
+        }
 
-            // 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);
-            }
+        if(!is_null($town)){
+            $subcontratists_info->TOWN = trim($town->LOCA_NOLO) . " (" . $subcontratists_info->TOWN . ")";
+        }
 
-            // 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 ($request->RFC != null && $subcontratist->RFC == $request->RFC) {
-                            $duplicated_data[] = "RFC: " . $subcontratist->RFC;
-                        }
-
-                        if ($subcontratist->EMAIL == $request->EMAIL) {
-                            $duplicated_data[] = "Email: " . $subcontratist->EMAIL;
-                        }
-                    }
+        if(!is_null($setting)){
+            $subcontratists_info->SUBURB = trim($setting->COLO_NOCO) . " (" . $subcontratists_info->SUBURB . ")";
+        }
 
-                    if (isset($duplicated_data[0]) && !empty($duplicated_data[0])) {
-                        return $this->response_controller->makeResponse(TRUE, 'ERR_SUBCONTRATISTA_REG003: Datos duplicados', $duplicated_data, 500);
-                    }
-                }
-            }
+        $now = $this->functionsController->now();
+        $nowStr = $now->toDateTimeString();
+        $actions = DB::getQueryLog();
+        $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
+        
+        $idac = $this->functionsController->registerActivity(
+            $line,
+            'S002V01M11GPRS',
+            'S002V01F01GESU',
+            'S002V01P03DESU',
+            'Consulta',
+            "El usuario $name (" . $usr->USUA_IDUS . ") consultó al subcontratista " . $subcontratists_info->SOCIAL_REASON . " ($idSub).",
+            $idUser,
+            $nowStr,
+            'S002V01S01GESU'
+        );
+
+        $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
+        return $this->responseController->makeResponse(false, 'EXITO', $subcontratists_info);
+    }
 
-            $user_register = DB::table('S002V01TUSUA')
-                ->select('USUA_IDUS as ID_USER')
-                ->where('USUA_IDUS', '=', $request->SAVED_BY_USER)
-                ->where('USUA_NULI', '=', $request->LINE_NUMBER)
-                ->first();
+    public function updateSubcontratist(Request $request) {
+        DB::enableQueryLog();
+
+        $request['TELEPHONE1'] = $this->encryptionController->decrypt($request->TELEPHONE1) ? $this->encryptionController->decrypt($request->TELEPHONE1) : 'ENC_ERR';
+        $request['TELEPHONE2'] = $this->encryptionController->decrypt($request->TELEPHONE2) ? $this->encryptionController->decrypt($request->TELEPHONE2) : 'ENC_ERR';
+        $request['EMAIL'] = $this->encryptionController->decrypt($request->EMAIL) ? $this->encryptionController->decrypt($request->EMAIL) : 'ENC_ERR';
+        $request['RFC'] = $this->encryptionController->decrypt($request->RFC) ? $this->encryptionController->decrypt($request->RFC) : 'ENC_ERR';
+        $request['TAX'] = $this->encryptionController->decrypt($request->TAX) ? $this->encryptionController->decrypt($request->TAX) : 'ENC_ERR';
+
+        $validator = Validator::make($request->all(), [
+            'id_user' => 'required|string',
+            'linea' => 'required|integer',
+            'id_subcontratist' => 'required|string',
+            'SOCIAL_REASON' => 'required|string|max:150',
+            'TAX_REFERENCE' => 'required|string|max:15',
+            'CONTRACT_TYPE' => 'required|string|in:Persona moral,Persona física',
+            'FOREIGNER' => 'required|string|in:Si,No',
+            'RFC' => 'required_if:FOREIGNER,=,No|string|max:13',
+            'TAX' => 'required_if:FOREIGNER,=,Si|string|max:13',
+            'EMAIL' => 'required|string|max:150',
+            'COUNTRY' => 'required|string|max:75',
+            'FEDERAL_ENTITY' => 'required|string|max:75',
+            'CITY' => 'string|max:75',
+            'TOWN' => 'string|max:75',
+            'SUBURB' => 'required|string|max:75',
+            'POSTAL_CODE' => 'required|string|max:5',
+            'STREET' => 'required|string|max:150',
+            'EXTERIOR_NUMBER' => 'required|integer',
+            'INTERIOR_NUMBER' => 'integer',
+            'LADA1' => 'required|string|max:15',
+            'TELEPHONE1' => 'required|string|min:7|max:11',
+            'LADA2' => 'string|max:15',
+            'TELEPHONE2' => 'string|min:7|max:11',
+            'SPECIALTY' => 'required|string|max:100'
+        ]);
+
+        if($validator->fails()){
+            return $this->responseController->makeResponse(
+                true,
+                "Se encontraron uno o más errores.",
+                $this->responseController->makeErrors(
+                    $validator->errors()->messages()
+                ),
+                401
+            );
+        }
 
-            // 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);
+        $form = $request->all();
+        foreach($form as $k=>$v){
+            if($k == 'INTERIOR_NUMBER' && $v == '0'){
+                unset($form[$k]);
+            }else if($v == '-'){
+                unset($form[$k]);
             }
+        }
 
-            $update_sql = DB::table('S002V01TPESU')
-                ->where('PESU_IDPS', $id_subcontratist)
-                ->where('PESU_NULI', '=', $request->LINE_NUMBER)
-                ->update([
-                    "PESU_NULI" => $request->LINE_NUMBER,
-                    "PESU_RASO" => $request->SOCIAL_REASON != null ? trim($request->SOCIAL_REASON) : null,
-                    "PESU_REFI" => $request->TAX_REFERENCE != null ? trim($request->TAX_REFERENCE) : null,
-                    "PESU_XRFC" => $request->RFC != null ? trim($request->RFC) : null,
-                    "PESU_TIPO" => $request->CONTRACT_TYPE != null ? trim($request->CONTRACT_TYPE) : null,
-                    "PESU_CORR" => $request->EMAIL != null ? trim($request->EMAIL) : null,
-                    "PESU_EXTR" => $request->FOREIGNER != null ? trim($request->FOREIGNER) : null,
-                    "PESU_TAID" => $request->TAX != null ? trim($request->TAX) : null,
-                    "PESU_CALL" => $request->STREET != null ? trim($request->STREET) : null,
-                    "PESU_NOEX" => $request->EXTERIOR_NUMBER != null ? trim($request->EXTERIOR_NUMBER) : null,
-                    "PESU_COLO" => $request->SUBURB != null ? trim($request->SUBURB) : null,
-                    "PESU_CIUD" => $request->CITY != null ? trim($request->CITY) : null,
-                    "PESU_COPO" => $request->POSTAL_CODE != null ? trim($request->POSTAL_CODE) : null,
-                    "PESU_ENFE" => $request->FEDERAL_ENTITY != null ? trim($request->FEDERAL_ENTITY) : null,
-                    "PESU_IDPA" => $request->COUNTRY != null ? trim($request->COUNTRY) : null,
-                    "PESU_TEL1" => $request->TELEPHONE1 != null ? trim($request->TELEPHONE1) : null,
-                    "PESU_LAT1" => $request->LADA1 != null ? trim($request->LADA1) : null,
-                    "PESU_TEL2" => $request->TELEPHONE2 != null ? trim($request->TELEPHONE2) : null,
-                    "PESU_LAT2" => $request->LADA2 != null ? trim($request->LADA2) : null,
-                    "PESU_USMO" => $request->SAVED_BY_USER != null ? trim($request->SAVED_BY_USER) : null,
-                    "PESU_NOIN" => $request->INTERIOR_NUMBER == '' ? null : trim($request->INTERIOR_NUMBER),
-                    "PESU_ESTA" => "Activo",
-                    "PESU_FEMO" => $UPDATE_DATE,
-                    "PESU_FEAR" => DB::raw('CURRENT_TIMESTAMP')
-                ]);
-
-            // Verifica que la actualización se haya realizado exitosamente
-            if ($update_sql > 0) {
-                $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);
-            }
+        $idUser = $this->encryptionController->decrypt($form['id_user']);
+        if(!$idUser){
+            return $this->responseController->makeResponse(true, 'El ID de usuario no fue encriptado correctamente.', [], 400);
+        }
 
-            return $response;
+        $usr = DB::table('S002V01TUSUA')->where([
+            ['USUA_NULI', '=', $form['linea']],
+            ['USUA_IDUS', '=', $idUser]
+        ])->first();
+        
+        if(is_null($usr)){
+            return $this->responseController->makeResponse(true, 'El usuario que realizó la petición no existe.', [], 404);
+        }
 
+        $idSub = $this->encryptionController->decrypt($form['id_subcontratist']);
+        if(!$idSub){
+            return $this->responseController->makeResponse(true, 'El ID del subcontratista no fue encriptado correctamente.', [], 400);
+        }
 
-        } catch (Throwable $th) {
-            return $this->response_controller
-                ->makeResponse(TRUE, 'ERR_SUBCONTRATISTA_REG006: Error inesperado', strtoupper($th->getMessage()), 500);
+        $sub = DB::table('S002V01TPESU')->where([
+            ['PESU_NULI', '=', $form['linea']],
+            ['PESU_IDPS', '=', $idSub],
+        ])->first();
+        
+        if(is_null($sub)){
+            return $this->responseController->makeResponse(true, 'El subcontratista solicitado no existe.', [], 404);
         }
 
-    }
+        $ladasValues = [];
+        $ladas = DB::table('S002V01TPAIS')->select([
+            'PAIS_LADA AS LADA'
+        ])->where('PAIS_NULI', '=', $form['linea'])->get()->all();
 
-    // 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();
-
-            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);
+        foreach($ladas as $lada){
+            if($lada->LADA != '' && $lada->LADA != '0'){
+                $ladasValues[] = $lada->LADA;
             }
+        }
 
-            return $this->response_controller->makeResponse(FALSE, 'Consulta exitosa', $subcontratists_info);
-
-        } catch (Throwable $e) {
-            return $this->response_controller
-                ->makeResponse(TRUE, 'ERR_SUBCONTRATISTA_REG001: Error inesperado', strtoupper($e->getMessage()), 500);
+        if(!in_array($form['LADA1'], $ladasValues)){
+            return $this->responseController->makeResponse(true, "La lada $form[LADA1] no está relacionada a ningún país.", [], 400);
+        }else if($form['TELEPHONE1'] == 'ENC_ERR'){
+            return $this->responseController->makeResponse(true, 'El número telefónico 1 no fue encriptado correctamente.', [], 400);
         }
-    }
 
-    // Metodo para obtener datos de los subcontratistas
-    public function getActiveSubcontratists($line_number)
-    {
-        try {
-
-            $subcontratists_info = DB::table('S002V01TPESU')
-                ->select(
-                    DB::raw('CONCAT(PESU_RASO, " " , COALESCE(PESU_REFI, "")) AS NAME'),
-                    'PESU_IDPS as ID_SUBCONTRATIST',
-                )
-                ->orderBy('NAME', 'asc')
-                ->where('PESU_NULI', '=', $line_number)
-                ->where('PESU_ESTA', '=', "Activo")
-                ->get();
-
-            foreach ($subcontratists_info as $subcontratist) {
-                $subcontratist->NAME = trim($subcontratist->NAME);
+        $lada2 = null;
+        $phone2 = null;
+        if(isset($form['LADA2'])){
+            if(!in_array($form['LADA2'], $ladasValues)){
+                return $this->responseController->makeResponse(true, "La lada $form[LADA2] no está relacionada a ningún país.", [], 400);
+            }else if($form['TELEPHONE2'] == 'ENC_ERR'){
+                return $this->responseController->makeResponse(true, 'El número telefónico 2 no fue encriptado correctamente.', [], 400);
             }
 
-            return $this->response_controller->makeResponse(FALSE, 'Consulta exitosa', $subcontratists_info);
+            $lada2 = $form['LADA2'];
+            $phone2 = $form['TELEPHONE2'];
+        }
 
-        } catch (Throwable $e) {
-            return $this->response_controller
-                ->makeResponse(TRUE, 'ERR_SUBCONTRATISTA_REG001: Error inesperado', strtoupper($e->getMessage()), 500);
+        if($form['EMAIL'] == 'ENC_ERR'){
+            return $this->responseController->makeResponse(true, 'El email no fue encriptado correctamente.', [], 400);
+        }
+
+        $rfcx = null;
+        if(isset($form['RFC']) && $form['FOREIGNER'] == 'No' && $form['RFC'] == 'ENC_ERR'){
+            return $this->responseController->makeResponse(true, 'El RFC no fue encriptado correctamente.', [], 400);
+        }else if(isset($form['RFC']) && $form['RFC'] != 'ENC_ERR'){
+            $rfcx = $form['RFC'];
+        }
+
+        $taid = null;
+        if(isset($form['TAX']) && $form['FOREIGNER'] == 'Si' && $form['TAX'] == 'ENC_ERR'){
+            return $this->responseController->makeResponse(true, 'El TAX ID no fue encriptado correctamente.', [], 400);
+        }else if(isset($form['TAX']) && $form['TAX'] != 'ENC_ERR'){
+            $taid =  $form['TAX'];
+        }
+        
+        $country = DB::table('S002V01TPAIS')->where([
+            ['PAIS_NULI', '=', $form['linea']],
+            ['PAIS_IDPA', '=', $form['COUNTRY']],
+        ])->first();
+        
+        if(is_null($country)){
+            return $this->responseController->makeResponse(true, 'El país seleccionado no existe.', [], 404);
+        }
+        
+        $taxRegime = DB::table('S002V01TREFI')->where([
+            ['REFI_NULI', '=', $form['linea']],
+            ['REFI_CRFI', '=', $form['TAX_REFERENCE']],
+        ])->first();
+        
+        if(is_null($taxRegime)){
+            return $this->responseController->makeResponse(true, 'El régimen fiscal seleccionado no existe.', [], 404);
         }
-    }
 
-    // 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();
-
-            $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";
-                        }
+        $colo = null;
+        $ciud = null;
+        $loca = null;
+        if($form['COUNTRY'] == 'MEX' || $form['COUNTRY'] == 'USA' || $form['COUNTRY'] == 'CAN'){
+            $state = DB::table('S002V01TESTA')->where([
+                ['ESTA_NULI', '=', $form['linea']],
+                ['ESTA_COES', '=', $form['FEDERAL_ENTITY']],
+                ['ESTA_COPA', '=', $form['COUNTRY']],
+            ])->first();
+        
+            if(is_null($state)){
+                return $this->responseController->makeResponse(true, 'El estado seleccionado no existe.', [], 404);
+            }
+
+            if($form['COUNTRY'] == 'MEX'){
+                if(isset($form['CITY'])){
+                    $city = DB::table('S002V01TMUNI')->where([
+                        ['MUNI_NULI', '=', $form['linea']],
+                        ['MUNI_COMU', '=', $form['CITY']],
+                        ['MUNI_COES', '=', $form['FEDERAL_ENTITY']],
+                    ])->first();
+            
+                    if(is_null($city)){
+                        return $this->responseController->makeResponse(true, 'El municipio seleccionado no existe.', [], 404);
+                    }else{
+                        $ciud = $form['CITY'];
                     }
                 }
 
-                // 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];
+                if(isset($form['TOWN'])){
+                    $town = DB::table('S002V01TLOCA')->where([
+                        ['LOCA_NULI', '=', $form['linea']],
+                        ['LOCA_COLO', '=', $form['TOWN']],
+                        ['LOCA_COES', '=', $form['FEDERAL_ENTITY']],
+                    ])->first();
+            
+                    if(is_null($town)){
+                        return $this->responseController->makeResponse(true, 'La localidad seleccionada no existe.', [], 404);
+                    }else{
+                        $loca = $form['TOWN'];
+                    }
                 }
+                
+                $setting = DB::table('S002V01TCOLO')->where([
+                    ['COLO_NULI', '=', $form['linea']],
+                    ['COLO_COCO', '=', $form['SUBURB']],
+                    ['COLO_COPO', '=', $form['POSTAL_CODE']],
+                ])->first();
+            
+                if(is_null($setting)){
+                    return $this->responseController->makeResponse(true, 'La colonia seleccionada no existe.', [], 404);
+                }else{
+                    $colo = $form['SUBURB'];
+                }
+                
+                $zipCode = DB::table('S002V01TCOPO')->where([
+                    ['COPO_NULI', '=', $form['linea']],
+                    ['COPO_COPO', '=', $form['POSTAL_CODE']],
+                    ['COPO_COES', '=', $form['FEDERAL_ENTITY']],
+                ])->first();
+            
+                if(is_null($zipCode)){
+                    return $this->responseController->makeResponse(true, 'El código postal seleccionado no existe.', [], 404);
+                }
+            }else{
+                $colo = $form['SUBURB'];
+                $ciud = $form['CITY'];
+                $loca = isset($form['TOWN']) ? $form['TOWN'] : null;
             }
+        }else{
+            $colo = $form['SUBURB'];
+            $ciud = $form['CITY'];
+            $loca = isset($form['TOWN']) ? $form['TOWN'] : null;
+        }
 
-            return $this->response_controller->makeResponse(FALSE, "Consulta exitosa", $contracts_by_subcontratist);
-
-        } catch (Throwable $th) {
-            return $this->response_controller
-                ->makeResponse(TRUE, 'ERR_SUBCONTRATISTA_REG001: Error inesperado', strtoupper($th->getMessage()), 500);
+        $subArr = DB::table('S002V01TPESU')->where('PESU_NULI', '=', $form['linea'])->where(function(Builder $query) use ($form) {
+            $query->where('PESU_RASO', '=', $form['SOCIAL_REASON'])
+            ->orWhere('PESU_XRFC', '=', $form['RFC'])
+            ->orWhere('PESU_CORR', '=', $form['EMAIL']);
+        })->where([
+            ['PESU_IDPS', '!=', $idSub],
+            ['PESU_ESTA', '=', 'Activo'],
+        ])->get()->all();
+
+        if(count($subArr) > 0){
+            return $this->responseController->makeResponse(true, 'La razón social, el RFC o el correo electrónico ya fueron registrados.', [], 401);
         }
 
+        $nuin = isset($form['INTERIOR_NUMBER']) ? $form['INTERIOR_NUMBER'] : null;
+        $now = $this->functionsController->now();
+        $nowStr = $now->toDateTimeString();
+        DB::table('S002V01TPESU')->where([
+            ['PESU_NULI', '=', $form['linea']],
+            ['PESU_IDPS', '=', $idSub],
+        ])->update([
+            'PESU_RASO' => $form['SOCIAL_REASON'],
+            'PESU_REFI' => $form['TAX_REFERENCE'],
+            'PESU_XRFC' => $rfcx,
+            'PESU_TIPO' => $form['CONTRACT_TYPE'],
+            'PESU_CORR' => $form['EMAIL'],
+            'PESU_EXTR' => $form['FOREIGNER'],
+            'PESU_TAID' => $taid,
+            'PESU_CALL' => $form['STREET'],
+            'PESU_NUEX' => $form['EXTERIOR_NUMBER'],
+            'PESU_NUIN' => $nuin,
+            'PESU_COLO' => $colo,
+            'PESU_CIUD' => $ciud,
+            'PESU_LOCA' => $loca,
+            'PESU_COPO' => $form['POSTAL_CODE'],
+            'PESU_ENFE' => $form['FEDERAL_ENTITY'],
+            'PESU_IDPA' => $form['COUNTRY'],
+            'PESU_TEL1' => $form['TELEPHONE1'],
+            'PESU_LAT1' => $form['LADA1'],
+            'PESU_TEL2' => $phone2,
+            'PESU_LAT2' => $lada2,
+            'PESU_ESPE' => $form['SPECIALTY'],
+            'PESU_USMO' => $idUser,
+            'PESU_FEMO' => $nowStr,
+        ]);
+
+        $actions = DB::getQueryLog();
+        $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
+        
+        $idac = $this->functionsController->registerActivity(
+            $form['linea'],
+            'S002V01M11GPRS',
+            'S002V01F01GESU',
+            'S002V01P02RESU',
+            'Actualización',
+            "El usuario $name (" . $usr->USUA_IDUS . ") actualizó al subcontratista $idSub.",
+            $idUser,
+            $nowStr,
+            'S002V01S01GESU'
+        );
+
+        $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']);
+        return $this->responseController->makeResponse(false, 'EXITO');
     }
 
-    // Metodo para obtener el historico de los contratos de un subcontratista (Comprueba si existe el subcontratista)
-    public function getContractsBySubcontratist($id_subcontratist, $line_number)
-    {
+    public  function updateToInactiveStatus(Request $request) {
+        DB::enableQueryLog();
+
+        $validator = Validator::make($request->all(), [
+            'id_user' => 'required|string',
+            'linea' => 'required|integer',
+            'id_subcontratist' => 'required|string',
+        ]);
+
+        if($validator->fails()){
+            return $this->responseController->makeResponse(
+                true,
+                "Se encontraron uno o más errores.",
+                $this->responseController->makeErrors(
+                    $validator->errors()->messages()
+                ),
+                401
+            );
+        }
 
-        try {
+        $form = $request->all();
+        $idUser = $this->encryptionController->decrypt($form['id_user']);
+        if(!$idUser){
+            return $this->responseController->makeResponse(true, 'El ID de usuario no fue encriptado correctamente.', [], 400);
+        }
 
-            // 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();
+        $usr = DB::table('S002V01TUSUA')->where([
+            ['USUA_NULI', '=', $form['linea']],
+            ['USUA_IDUS', '=', $idUser]
+        ])->first();
+        
+        if(is_null($usr)){
+            return $this->responseController->makeResponse(true, 'El usuario que realizó la petición no existe.', [], 404);
+        }
 
-            // 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);
-            }
+        $idSub = $this->encryptionController->decrypt($form['id_subcontratist']);
+        if(!$idSub){
+            return $this->responseController->makeResponse(true, 'El ID del subcontratista no fue encriptado correctamente.', [], 400);
+        }
 
-            // 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', 'S002V01TCONT.CONT_COST', 'S002V01TCONT.CONT_NOMB')
-                ->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_NOMB as CONTRACT_NAME',
-                    'S002V01TCONT.CONT_FEFI as END_DATE',
-                    'S002V01TCONT.CONT_IDCO as ID_CONTRACT',
-                    'S002V01TCONT.CONT_COST as COST',
-                    'S002V01TPERS.PERS_IDPS as ID_SUBCONTRATIST',
-                )
-                ->join('S002V01TPECO', 'S002V01TPERS.PERS_IDPE', '=', 'S002V01TPECO.PECO_IDPE')
-                ->join('S002V01TCONT', 'S002V01TPECO.PECO_IDCO', '=', 'S002V01TCONT.CONT_IDCO')
-                ->get();
-
-            // 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('TRIM(CONCAT(S002V01TUSUA.USUA_NOMB, " " , S002V01TUSUA.USUA_APPA, " ", COALESCE(S002V01TUSUA.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.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', 'S002V01TPERS.PERS_IDUS', '=', 'S002V01TUSUA.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();
-
-            // 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");
-                $contract->COST = $this->encrypt_controller->encrypt($contract->COST);
-                $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";
-                        }
+        $sub = DB::table('S002V01TPESU')->where([
+            ['PESU_NULI', '=', $form['linea']],
+            ['PESU_IDPS', '=', $idSub],
+        ])->first();
+        
+        if(is_null($sub)){
+            return $this->responseController->makeResponse(true, 'El subcontratista solicitado no existe.', [], 404);
+        }
 
-                    }
+        $users = DB::table('S002V01TPERS')->where([
+            ['PERS_NULI', '=', $form['linea']],
+            ['PERS_ESTA', '=', 'Activo'],
+        ])->join('S002V01TPESU', 'PERS_IDPS', '=', 'PESU_IDPS')->get()->all();
 
-                    // 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++;
-                    }
+        if(count($users) > 0){
+            return $this->responseController->makeResponse(true, 'El subcontratista que desea eliminar tiene usuarios relacionados.', [], 401);
+        }
 
-                }
-                $contract->INTERVENTIONS_COUNTER = $interventions_counter;
-            }
+        $now = $this->functionsController->now();
+        $nowStr = $now->toDateTimeString();
+        DB::table('S002V01TPESU')->where([
+            ['PESU_NULI', '=', $form['linea']],
+            ['PESU_IDPS', '=', $idSub],
+        ])->update([
+            'PESU_ESTA' => 'Eliminado',
+            'PESU_USMO' => $idUser,
+            'PESU_FEMO' => $nowStr
+        ]);
+
+        $actions = DB::getQueryLog();
+        $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
+        
+        $idac = $this->functionsController->registerActivity(
+            $form['linea'],
+            'S002V01M11GPRS',
+            'S002V01F01GESU',
+            'S002V01P02RESU',
+            'Eliminación',
+            "El usuario $name (" . $usr->USUA_IDUS . ") eliminó al subcontratista $idSub.",
+            $idUser,
+            $nowStr,
+            'S002V01S01GESU'
+        );
+
+        $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']);
+        return $this->responseController->makeResponse(false, 'EXITO');
+    }
 
-            // Verifica si el objeto esta vacio
-            if (!isset($contracts[0]) && empty($contracts[0])) {
-                return $this->response_controller
-                    ->makeResponse(TRUE, 'ERR_CONTRATO_REG002: 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);
+    public function getContractsOfEverySubcontratist($idUser, $line) {
+        DB::enableQueryLog();
 
-        } catch (Throwable $th) {
-            return $this->response_controller
-                ->makeResponse(TRUE, 'ERR_SUBCONTRATISTA_REG003: Error inesperado', strtoupper($th->getMessage()), 500);
+        $idUser = $this->encryptionController->decrypt($idUser);
+        if(!$idUser){
+            return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente', [], 400);
         }
-    }
 
-    // Metodo para obtener los paises
-    public function getCountries($line_number)
-    {
-        try {
-
-            // Busca si el subcontratista existe
-            $countries = DB::table("S002V01TPAIS")
-                ->select(
-                    "PAIS_IDPA as COUNTRY_ID",
-                    "PAIS_NOMB as NAME",
-                    "PAIS_LADA as LADA",
-                    "PAIS_NOME AS NOMECLARUTA_ISO2",
-                    "PAIS_NOM2 AS NOMECLARUTA_ISO3"
-                    )
-                ->where('PAIS_NULI', '=', $line_number)
-                ->get();
-
-            // Verifica si el objeto esta vacio
-            if (!isset($countries[0]) && empty($countries[0])) {
-                return $this->response_controller
-                    ->makeResponse(TRUE, "ERR_SUBCONTRATISTA_REG001: No se encontró al subcontratista", $countries, 500);
-            }
+        $usr = DB::table('S002V01TUSUA')->where([
+            ['USUA_NULI', '=', $line],
+            ['USUA_IDUS', '=', $idUser],
+        ])->first();
 
-            return $this->response_controller->makeResponse(FALSE, 'Consulta exitosa', $countries);
+        if(is_null($usr)){
+            return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado', [], 404);
+        }
 
-        } catch (Throwable $th) {
-            return $this->response_controller
-                ->makeResponse(TRUE, 'ERR_SUBCONTRATISTA_REG005: Error inesperado', strtoupper($th->getMessage()), 500);
+        $contractsBySubcontratists = DB::table('S002V01TPERS')->select([
+            DB::raw("
+                TRIM(CONCAT(
+                    USUA_NOMB, 
+                    ' ', 
+                    USUA_APPA,
+                    IF(ISNULL(USUA_APMA), '', CONCAT(' ', USUA_APMA)),
+                    ' <(',
+                    PERS_IDPE,
+                    ')> (',
+                    PERS_IDUS,
+                    ')'
+                )) AS EMPLOYEE
+            "),
+            DB::raw("COUNT(CONT_IDCO) AS CONTRACTS")
+        ])->leftJoin('S002V01TCONT', 'CONT_IDEM', '=', 'PERS_IDPE')
+        ->join('S002V01TUSUA', 'USUA_IDUS', '=', 'PERS_IDUS')
+        ->groupBy('EMPLOYEE')->where([
+            ['PERS_NULI', '=', $line],
+            ['PERS_TICO', '=', 'Subcontratista'],
+        ])->get()->all();
+
+        foreach($contractsBySubcontratists as $key=>$val){
+            $employeeArr = explode('<', $val->EMPLOYEE);
+            $employeeName = $employeeArr[0];
+            $employeeArr = array_reverse($employeeArr);
+            $employeeArr = explode('>', $employeeArr[0]);
+
+            $employeeID = str_replace('(', '', $employeeArr[0]);
+            $employeeID = str_replace(')', '', $employeeID);
+
+            $val->ID_EMPLOYEE = $this->encryptionController->encrypt($employeeID);
+            $val->EMPLOYEE = $employeeName . join('', $employeeArr);
+
+            $contractsBySubcontratists[$key] = $val;
         }
+
+        $now = $this->functionsController->now();
+        $nowStr = $now->toDateTimeString();
+        $actions = DB::getQueryLog();
+        $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
+        
+        $idac = $this->functionsController->registerActivity(
+            $line,
+            'S002V01M11GPRS',
+            'S002V01F02ADCO',
+            'S002V01P01HCSU',
+            'Consulta',
+            "El usuario $name (" . $usr->USUA_IDUS . ") consultó los contratos por subcontratista.",
+            $idUser,
+            $nowStr,
+            'S002V01S01GESU'
+        );
+
+        $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
+        return $this->responseController->makeResponse(false, 'EXITO', $contractsBySubcontratists);
     }
 
-    // Metodo para la descarga en archivo excel del historial de contratos por subcontratista
-    public function downoloadSubcontractInfoOnExcel(Request $request)
-    {
+    public function getContractsBySubcontratist($idSubcontratist, $idUser, $line) {
+        DB::enableQueryLog();
 
-        try {
-            $request['SAVED_BY_USER'] = $this->encrypt_controller->decrypt($request->SAVED_BY_USER);
-            $id_subcontratist = $request->CONTRACTS[0]['ID_SUBCONTRATIST'];
+        $idUser = $this->encryptionController->decrypt($idUser);
+        if(!$idUser){
+            return $this->responseController->makeResponse(true, 'El ID de usuario no fue encriptado correctamente.', [], 400);
+        }
 
-            $final_part_name_document = "Contracts_History_By_Subcontratist_" . $id_subcontratist . ".xlsx";
+        $usr = DB::table('S002V01TUSUA')->where([
+            ['USUA_NULI', '=', $line],
+            ['USUA_IDUS', '=', $idUser]
+        ])->first();
+        
+        if(is_null($usr)){
+            return $this->responseController->makeResponse(true, 'El usuario que realizó la petición no existe.', [], 404);
+        }
 
-            // Crea el documento con los datos del request
-            $document = $this->createDocument($request);
+        $idSubcontratist = $this->encryptionController->decrypt($idSubcontratist);
+        if(!$idSubcontratist){
+            return $this->responseController->makeResponse(true, 'El ID del subcontratista no fue encriptado correctamente.', [], 400);
+        }
 
-            // Busca la ultima versión del documento que se haya insertado
-            $old_document_name = $this->documents_controller->getDocumentsWithSameName($final_part_name_document, 'excel');
+        $sub = DB::table('S002V01TPERS')->where([
+            ['PERS_NULI', '=', $line],
+            ['PERS_IDPE', '=', $idSubcontratist],
+            ['PERS_TICO', '=', 'Subcontratista'],
+        ])->first();
+        
+        if(is_null($sub)){
+            return $this->responseController->makeResponse(true, 'El subcontratista solicitado no existe.', [], 404);
+        }
 
-            if ($old_document_name != null) {
+        $contracts = DB::table('S002V01TCONT')->select([
+            'CONT_NOCO AS CONTRACT_NAME',
+            'CONT_FEIN AS START_DATE',
+            'CONT_FEFI AS END_DATE',
+            'CONT_COST AS COST',
+        ])->where([
+            ['CONT_NULI', '=', $line],
+            ['CONT_IDEM', '=', $idSubcontratist],
+            ['CONT_TIPO', '=', 'Subcontratista'],
+        ])->get()->all();
+
+        $now = $this->functionsController->now();
+        $nowStr = $now->toDateTimeString();
+        $actions = DB::getQueryLog();
+        $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
+        
+        $idac = $this->functionsController->registerActivity(
+            $line,
+            'S002V01M11GPRS',
+            'S002V01F02ADCO',
+            'S002V01P01HCSU',
+            'Consulta',
+            "El usuario $name (" . $usr->USUA_IDUS . ") consultó los contratos del subcontratista #$idSubcontratist.",
+            $idUser,
+            $nowStr,
+            'S002V01S01GESU'
+        );
+
+        $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
+        return $this->responseController->makeResponse(false, 'EXITO', $contracts);
+    }
 
-                // Obtiene el nombre del documento que tiene el mismo contenido
-                $old_document_name = $this->documents_controller->sameDocumentsExcel($document, $old_document_name);
+    public function downloadSubcontractInfoOnExcel($idSubcontratist, $idUser, $line){
+        DB::enableQueryLog();
 
-                // Si no hay ningun cambio en el documento, se descarga la ultima versión
-                if ($old_document_name != null) {
-                    return $this->response_controller
-                        ->makeResponse(False, 'Éxito', Storage::disk('excel')->url($old_document_name), 200);
-                }
-            }
+        $idUser = $this->encryptionController->decrypt($idUser);
+        if(!$idUser){
+            return $this->responseController->makeResponse(true, 'El ID de usuario no fue encriptado correctamente.', [], 400);
+        }
 
-            $writer = IOFactory::createWriter($document, 'Xlsx');
-            $content = tmpfile();
-            $writer->save($content);
+        $usr = DB::table('S002V01TUSUA')->where([
+            ['USUA_NULI', '=', $line],
+            ['USUA_IDUS', '=', $idUser]
+        ])->first();
+        
+        if(is_null($usr)){
+            return $this->responseController->makeResponse(true, 'El usuario que realizó la petición no existe.', [], 404);
+        }
 
-            // 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->SAVED_BY_USER);
-            Storage::disk('excel')->put(
-                $name_document,
-                $content
-            );
-            return $this->response_controller
-                ->makeResponse(False, 'Éxito', Storage::disk('excel')->url($name_document), 200);
+        $idSubcontratist = $this->encryptionController->decrypt($idSubcontratist);
+        if(!$idSubcontratist){
+            return $this->responseController->makeResponse(true, 'El ID del subcontratista no fue encriptado correctamente.', [], 400);
+        }
 
-        } catch (Throwable $th) {
-            return $this->response_controller
-                ->makeResponse(TRUE, 'ERR_EXCEL_REG001: Error inesperado', strtoupper($th), 500);
+        $sub = DB::table('S002V01TPERS')->where([
+            ['PERS_NULI', '=', $line],
+            ['PERS_IDPE', '=', $idSubcontratist],
+            ['PERS_TICO', '=', 'Subcontratista'],
+        ])->first();
+        
+        if(is_null($sub)){
+            return $this->responseController->makeResponse(true, 'El subcontratista solicitado no existe.', [], 404);
         }
-    }
 
-    // Metodo para la descarga en archivo pdf del historial de contratos por subcontratista
-    public function downoloadSubcontractInfoOnPdf(Request $request)
-    {
+        $contracts = DB::table('S002V01TCONT')->select([
+            'CONT_IDCO AS IDCONTRATO',
+            'CONT_NOCO AS NOMBRECONTRATO',
+            'CONT_IDOT AS IDORDEN',
+            'CONT_TOTR AS TIPOORDEN',
+            'PERS_ESPE AS ESPECIALIDAD',
+            'CONT_FEIN AS FECHAINICIO',
+            'CONT_FEFI AS FECHAFIN',
+            'CONT_COST AS COSTO',
+        ])->join('S002V01TPERS', 'PERS_IDPE', '=', 'CONT_IDEM')->where([
+            ['CONT_NULI', '=', $line],
+            ['CONT_IDEM', '=', $idSubcontratist],
+            ['CONT_TIPO', '=', 'Subcontratista'],
+        ])->get()->all();
+
+        $document = $this->generateDocument($contracts);
+
+        $now = $this->functionsController->now();
+        $nowStr = $now->toDateTimeString();
+        
+        $dateTimeArr = explode(" ", $nowStr);
+        $dateArr = explode("-", $dateTimeArr[0]);
+        $year = substr($dateArr[0], 2);
+        $como = 'GPRS';
+        $cldo = 'IN';
+        $fecr = $year . $dateArr[1] . $dateArr[2];
+
+        $sec = DB::table('S002V01TAFAL')->where([
+            ['AFAL_NULI', '=', $line],
+            ['AFAL_COMO', '=', $como],
+            ['AFAL_CLDO', '=', $cldo],
+        ])->orderBy('AFAL_NUSE', 'desc')->first();
+
+        $nuse = "";
+        if(is_null($sec)){
+            $nuse = '000001';
+        }else{
+            $secu = "" . intval($sec->AFAL_NUSE) + 1 . "";
+            $nuse = "";
+
+            for($i = strlen($secu); $i < 6; $i++){
+                $nuse .= "0";
+            }
 
-        try {
-            $request['SAVED_BY_USER'] = $this->encrypt_controller->decrypt($request->SAVED_BY_USER);
-            $id_subcontratist = $request->CONTRACTS[0]['ID_SUBCONTRATIST'];
+            $nuse = $nuse . $secu;
+        }
 
-            $final_part_name_document = "Contracts_History_By_Subcontratist_" . $id_subcontratist . ".pdf";
+        $noar = "ficha_de_subcontratacion_del_subcontratista_$idSubcontratist";
+        $exte = "xlsx";
+
+        $ver = DB::table('S002V01TAFAL')->where([
+            ['AFAL_NULI', '=', $line],
+            ['AFAL_COMO', '=', $como],
+            ['AFAL_CLDO', '=', $cldo],
+            ['AFAL_NOAR', '=', $noar],
+            ['AFAL_EXTE', '=', $exte],
+        ])->orderBy('AFAL_NUVE', 'desc')->first();
+
+        $nuve = "";
+        if(is_null($ver)){
+            $nuve = "01";
+        }else{
+            $vers = intval($ver->AFAL_NUVE) + 1;
+            $nuve = $vers < 10 ? "0$vers" : "$vers";
+        }
+
+        $line = $line < 10 ? "0$line" : "$line";
+        $filePath = 'C:\inetpub\wwwroot\sam\public_files\\';
+        $fileName = "$line-$como-$cldo-$fecr-$nuse=$nuve=$noar.$exte";
+        
+        $tempFile = $filePath . $fileName;
+        if(file_exists($tempFile)){
+            unlink($tempFile);
+        }
 
-            //Crea el documento con los datos del request
+        $writer = IOFactory::createWriter($document, 'Xlsx');
+        $writer->save($tempFile);
+        $ubic = Storage::putFile('files', new File($tempFile));
+        $ubic = str_replace("/", "\\", $ubic);
+        $ubic = "C:\inetpub\wwwroot\sam\storage\app\\" . $ubic;
+        $tama = filesize($ubic);
+        $usac = json_encode([$idUser]);
+        unlink($tempFile);
+
+        DB::table('S002V01TAFAL')->insert([
+            'AFAL_NULI' => $line,
+            'AFAL_COMO' => $como,
+            'AFAL_CLDO' => $cldo,
+            'AFAL_FECR' => $fecr,
+            'AFAL_NUSE' => $nuse,
+            'AFAL_NUVE' => $nuve,
+            'AFAL_NOAR' => $noar,
+            'AFAL_EXTE' => $exte,
+            'AFAL_TAMA' => $tama,
+            'AFAL_UBIC' => $ubic,
+            'AFAL_USAC' => $usac,
+            'AFAL_USRE' => $idUser,
+            'AFAL_FERE' => $nowStr,
+        ]);
+
+        $actions = DB::getQueryLog();
+        $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
+        
+        $idac = $this->functionsController->registerActivity(
+            $line,
+            'S002V01M11GPRS',
+            'S002V01F02ADCO',
+            'S002V01P02FISU',
+            'Registro',
+            "El usuario $name (" . $usr->USUA_IDUS . ") generó la ficha de subcontratación del subcontratista #$idSubcontratist para Excel.",
+            $idUser,
+            $nowStr,
+            'S002V01S01GESU'
+        );
+
+        $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
+        return $this->responseController->makeResponse(false, 'EXITO.', ['fileID' => $fileName]);
+    }
 
-            $document = $this->createDocument($request);
+    public function downloadSubcontractInfoOnPdf($idSubcontratist, $idUser, $line) {
+        DB::enableQueryLog();
 
-            $writer = IOFactory::createWriter($document, 'Mpdf');
-            $content = tmpfile();
+        $idUser = $this->encryptionController->decrypt($idUser);
+        if(!$idUser){
+            return $this->responseController->makeResponse(true, 'El ID de usuario no fue encriptado correctamente.', [], 400);
+        }
 
-            // Busca la ultima versión del documento que se haya insertado
-            $old_document_name = $this->documents_controller->getDocumentsWithSameName($final_part_name_document, 'pdf');
+        $usr = DB::table('S002V01TUSUA')->where([
+            ['USUA_NULI', '=', $line],
+            ['USUA_IDUS', '=', $idUser]
+        ])->first();
+        
+        if(is_null($usr)){
+            return $this->responseController->makeResponse(true, 'El usuario que realizó la petición no existe.', [], 404);
+        }
 
-            $writer->save($content);
-            if ($old_document_name != null) {
+        $idSubcontratist = $this->encryptionController->decrypt($idSubcontratist);
+        if(!$idSubcontratist){
+            return $this->responseController->makeResponse(true, 'El ID del subcontratista no fue encriptado correctamente.', [], 400);
+        }
 
-                // Obtiene el nombre del documento que tiene el mismo contenido
-                $old_document_name = $this->documents_controller->sameDocumentsPdf($content, $old_document_name);
+        $sub = DB::table('S002V01TPERS')->where([
+            ['PERS_NULI', '=', $line],
+            ['PERS_IDPE', '=', $idSubcontratist],
+            ['PERS_TICO', '=', 'Subcontratista'],
+        ])->first();
+        
+        if(is_null($sub)){
+            return $this->responseController->makeResponse(true, 'El subcontratista solicitado no existe.', [], 404);
+        }
 
-                // Si no hay ningun cambio en el documento, se descarga la ultima versión
-                if ($old_document_name != null) {
-                    return $this->response_controller
-                        ->makeResponse(False, 'Éxito', Storage::disk('pdf')->url($old_document_name), 200);
-                }
+        $contracts = DB::table('S002V01TCONT')->select([
+            'CONT_IDCO AS IDCONTRATO',
+            'CONT_NOCO AS NOMBRECONTRATO',
+            'CONT_IDOT AS IDORDEN',
+            'CONT_TOTR AS TIPOORDEN',
+            'PERS_ESPE AS ESPECIALIDAD',
+            'CONT_FEIN AS FECHAINICIO',
+            'CONT_FEFI AS FECHAFIN',
+            'CONT_COST AS COSTO',
+        ])->join('S002V01TPERS', 'PERS_IDPE', '=', 'CONT_IDEM')->where([
+            ['CONT_NULI', '=', $line],
+            ['CONT_IDEM', '=', $idSubcontratist],
+            ['CONT_TIPO', '=', 'Subcontratista'],
+        ])->get()->all();
+
+        $document = $this->generateDocument($contracts);
+
+        $now = $this->functionsController->now();
+        $nowStr = $now->toDateTimeString();
+        
+        $dateTimeArr = explode(" ", $nowStr);
+        $dateArr = explode("-", $dateTimeArr[0]);
+        $year = substr($dateArr[0], 2);
+        $como = 'GPRS';
+        $cldo = 'IN';
+        $fecr = $year . $dateArr[1] . $dateArr[2];
+
+        $sec = DB::table('S002V01TAFAL')->where([
+            ['AFAL_NULI', '=', $line],
+            ['AFAL_COMO', '=', $como],
+            ['AFAL_CLDO', '=', $cldo],
+        ])->orderBy('AFAL_NUSE', 'desc')->first();
+
+        $nuse = "";
+        if(is_null($sec)){
+            $nuse = '000001';
+        }else{
+            $secu = "" . intval($sec->AFAL_NUSE) + 1 . "";
+            $nuse = "";
+
+            for($i = strlen($secu); $i < 6; $i++){
+                $nuse .= "0";
             }
 
-            // 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->SAVED_BY_USER);
-
-            Storage::disk('pdf')->put(
-                $name_document,
-                $content
-            );
+            $nuse = $nuse . $secu;
+        }
 
-            return $this->response_controller
-                ->makeResponse(False, 'Éxito', Storage::disk('pdf')->url($name_document), 200);
+        $noar = "ficha_de_subcontratacion_del_subcontratista_$idSubcontratist";
+        $exte = "pdf";
+
+        $ver = DB::table('S002V01TAFAL')->where([
+            ['AFAL_NULI', '=', $line],
+            ['AFAL_COMO', '=', $como],
+            ['AFAL_CLDO', '=', $cldo],
+            ['AFAL_NOAR', '=', $noar],
+            ['AFAL_EXTE', '=', $exte],
+        ])->orderBy('AFAL_NUVE', 'desc')->first();
+
+        $nuve = "";
+        if(is_null($ver)){
+            $nuve = "01";
+        }else{
+            $vers = intval($ver->AFAL_NUVE) + 1;
+            $nuve = $vers < 10 ? "0$vers" : "$vers";
+        }
 
-        } catch (Throwable $th) {
-            return $this->response_controller
-                ->makeResponse(TRUE, 'ERR_PDF_REG001: Error inesperado', strtoupper($th), 500);
+        $line = $line < 10 ? "0$line" : "$line";
+        $filePath = 'C:\inetpub\wwwroot\sam\public_files\\';
+        $fileName = "$line-$como-$cldo-$fecr-$nuse=$nuve=$noar.$exte";
+        
+        $tempFile = $filePath . $fileName;
+        if(file_exists($tempFile)){
+            unlink($tempFile);
         }
+
+        $writer = IOFactory::createWriter($document, 'Mpdf');
+        $writer->save($tempFile);
+        $ubic = Storage::putFile('files', new File($tempFile));
+        $ubic = str_replace("/", "\\", $ubic);
+        $ubic = "C:\inetpub\wwwroot\sam\storage\app\\" . $ubic;
+        $tama = filesize($ubic);
+        $usac = json_encode([$idUser]);
+        unlink($tempFile);
+
+        DB::table('S002V01TAFAL')->insert([
+            'AFAL_NULI' => $line,
+            'AFAL_COMO' => $como,
+            'AFAL_CLDO' => $cldo,
+            'AFAL_FECR' => $fecr,
+            'AFAL_NUSE' => $nuse,
+            'AFAL_NUVE' => $nuve,
+            'AFAL_NOAR' => $noar,
+            'AFAL_EXTE' => $exte,
+            'AFAL_TAMA' => $tama,
+            'AFAL_UBIC' => $ubic,
+            'AFAL_USAC' => $usac,
+            'AFAL_USRE' => $idUser,
+            'AFAL_FERE' => $nowStr,
+        ]);
+
+        $actions = DB::getQueryLog();
+        $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
+        
+        $idac = $this->functionsController->registerActivity(
+            $line,
+            'S002V01M11GPRS',
+            'S002V01F02ADCO',
+            'S002V01P02FISU',
+            'Registro',
+            "El usuario $name (" . $usr->USUA_IDUS . ") generó la ficha de subcontratación del subcontratista #$idSubcontratist para Excel.",
+            $idUser,
+            $nowStr,
+            'S002V01S01GESU'
+        );
+
+        $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
+        return $this->responseController->makeResponse(false, 'EXITO.', ['fileID' => $fileName]);
     }
 
-    // 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++;
+    private function generateDocument($contracts) : Spreadsheet {
+        $spreadsheet = new Spreadsheet;
+        $spreadsheet->getProperties()
+            ->setCreator('STC')
+            ->setTitle('Historial de contratos por subcontratista.')
+            ->setSubject('Historial documento')
+            ->setKeywords('Subcontratista Contratos Historial')
+            ->setCategory('Historial archivo');
+        
+        $worksheet = $spreadsheet->getActiveSheet();
+        $worksheet->setTitle('HISTORIAL DE CONTRATOS');
+
+        $columns = ['# DE CONTRATO', 'NOMBRE DEL CONTRATO', 'ORDEN DE TRABAJO', 'TIPO DE ORDEN', 'ESPECIALIDAD', 'FECHA DE INICIO', 'FECHA DE TÉRMINO', 'COSTO'];
+        $startRow = 2;
+        $startCol = 2;
+        $maxRow = $startRow + count($contracts) + 1;
+        $maxCol = $startCol + 7;
+
+        for($row = $startRow; $row <= $maxRow; $row++){
+            $startColStr = Coordinate::stringFromColumnIndex($startCol);
+            $maxColStr = Coordinate::stringFromColumnIndex($maxCol);
+
+            if($row == 2){
+                $worksheet->mergeCells($startColStr . $row . ':' . $maxColStr . $row);
+                $worksheet->setCellValue($startColStr . $row, 'FICHA DE SUBCONTRATACIÓN')->getStyle($startColStr . $row)->getFill()
+                    ->setFillType(Fill::FILL_SOLID)
+                    ->getStartColor()->setRGB('B7BCC4');
+                $worksheet->getStyle($startColStr . $row)->getFont()->setBold(true);
+                $worksheet->getStyle($startColStr . $row)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
+            }else if($row == 3){
+                for($col = $startCol; $col <= $maxCol; $col++){
+                    $colStr = Coordinate::stringFromColumnIndex($col);
+                    $colInd = $col - 2;
+
+                    $column = $columns[$colInd]; 
+                    $worksheet->setCellValue($colStr . $row, $column);
+                    $worksheet->getColumnDimension($colStr)->setAutoSize(true);
+                    $worksheet->getStyle($colStr . $row)->getFont()->setBold(true);
+                    $worksheet->getStyle($colStr . $row)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
                 }
-
-                // 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 TÉRMINO')->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);
+            }else if($row > 3){
+                $rowInd = $row - 4;
+                $contract = (array) $contracts[$rowInd];
+                $keys = array_keys($contract);
+
+                for($col = $startCol; $col <= $maxCol; $col++){
+                    $colInd = $col - 2;
+                    $key = $keys[$colInd];
+                    $value = $contract[$key];
+                    $colStr = Coordinate::stringFromColumnIndex($col);
+
+                    if($key == 'IDORDEN'){
+                        $value = "Orden #$value";
+                    }else if($key == 'FECHAINICIO' || $key == 'FECHAFIN'){
+                        $value = $this->functionsController->formatDateTime($value);
+                    }else if($key == 'COSTO'){
+                        $worksheet->getStyle($colStr . $row)->getNumberFormat()->setFormatCode(NumberFormat::FORMAT_CURRENCY_USD);
                     }
 
-                    // 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);
+                    $worksheet->setCellValue($colStr . $row, $value);
                 }
-
-                $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);
         }
-    }
 
-}
+        if(count($contracts) == 0){
+            $startColStr = Coordinate::stringFromColumnIndex($startCol);
+            $maxColStr = Coordinate::stringFromColumnIndex($maxCol);
+            $maxRow++;
+
+            $worksheet->mergeCells($startColStr . $maxRow . ':' . $maxColStr . $maxRow);
+            $worksheet->setCellValue($startColStr . $maxRow, 'Aún no se han asociado contratos al subcontratista.');
+            $worksheet->getStyle($startColStr . $maxRow)->getFont()->setBold(true);
+            $worksheet->getStyle($startColStr . $maxRow)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
+        }
+
+        $worksheet->getStyle($startColStr . $startRow . ':' . $maxColStr . $maxRow)
+            ->getBorders()
+            ->getAllBorders()
+            ->setBorderStyle(Border::BORDER_MEDIUM);
+
+        return $spreadsheet;
+    }
+}

+ 407 - 450
sistema-mantenimiento-back/app/Http/Controllers/WorkTeamController.php

@@ -1,9 +1,4 @@
 <?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;
 
@@ -13,472 +8,434 @@ 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();
+class WorkTeamController extends Controller{
+    private $responseController;
+    private $encryptionController;
+    private $documentManagementController;
+    private $functionsController;
+
+    public function __construct(){
+        $this->responseController = new ResponseController();
+        $this->encryptionController = new EncryptionController();
+        $this->documentManagementController = new DocumentManagementController();
+        $this->functionsController = new FunctionsController();
     }
 
-    // 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_NULI', '=', $line_number)
-                ->get();
-
-            return $this->response_controller->makeResponse(FALSE, 'Consulta exitosa', $workteams, 200);
-        } catch (Throwable $th) {
-            return $this->response_controller
-                ->makeResponse(TRUE, 'ERR_EQUIPO_TRABAJO_REG001: Error inesperado', strtoupper($th->getMessage()), 500);
+    public function storeWorkteam(Request $request) {
+        DB::enableQueryLog();
+
+        $validator = Validator::make($request->all(), [
+            'id_user' => 'required|string',
+            'linea' => 'required|integer',
+            'NAME' => 'required|string|max:100',
+            'SPECIALITY' => 'required|string|max:100',
+        ]);
+
+        if($validator->fails()){
+            return $this->responseController->makeResponse(
+                TRUE,
+                'ERR_PERSONAL_REG001: Uno o más errores encontrados',
+                $this->responseController->makeErrors($validator->errors()->messages()),
+                400
+            );
         }
-    }
 
-    // Metodo para la consulta de equipos de trabajo
-    public function getActiveWorkteams($line_number)
-    {
-        try {
-            $workteams = DB::table('S002V01TEQMA')
-                ->select(
-                    'EQMA_IDEQ as WORKTEAM_ID',
-                    'EQMA_NOMB as NAME',
-                )
-                ->orderBy('NAME', 'asc')
-                ->where('EQMA_ESTA', '=', 'Activo')
-                ->where('EQMA_NULI', '=', $line_number)
-                ->get();
-
-            return $this->response_controller->makeResponse(FALSE, 'Consulta exitosa', $workteams, 200);
-        } catch (Throwable $th) {
-            return $this->response_controller
-                ->makeResponse(TRUE, 'ERR_EQUIPO_TRABAJO_REG001: Error inesperado', strtoupper($th->getMessage()), 500);
+        $form = $request->all();
+        $idUser = $this->encryptionController->decrypt($form['id_user']);
+        if(!$idUser){
+            return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente', [], 400);
         }
-    }
 
-    // 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);
+        $usr = DB::table('S002V01TUSUA')->where([
+            ['USUA_NULI', '=', $form['linea']],
+            ['USUA_IDUS', '=', $idUser],
+        ])->first();
+
+        if(is_null($usr)){
+            return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado', [], 404);
         }
-    }
 
-    // Metodo para obtener los integrantes de un equipo
-    public function getMembersOfWorkteamById($id_workteam, $line_number)
-    {
-        try {
-            // Obtiene las intervenciones del empleado
-            $workteam_members = DB::table('S002V01TPERS')
-                ->select(
-                    DB::raw('TRIM(CONCAT(S002V01TUSUA.USUA_NOMB, " " , S002V01TUSUA.USUA_APPA, " ", COALESCE(S002V01TUSUA.USUA_APMA,""))) as NAME')
-                )
-                ->where('S002V01TPEEM.PEEM_IDEM', '=', $id_workteam)
-                ->where('S002V01TPERS.PERS_NULI', '=', $line_number)
-                ->where('S002V01TPEEM.PEEM_NULI', '=', $line_number)
-                ->join('S002V01TPEEM', 'S002V01TPERS.PERS_IDPE', '=', 'S002V01TPEEM.PEEM_IDPE')
-                ->join('S002V01TUSUA', 'S002V01TPERS.PERS_IDUS', '=', 'S002V01TUSUA.USUA_IDUS')
-                ->get();
-
-            return $this->response_controller->makeResponse(FALSE, 'Consulta exitosa', $workteam_members, 200);
-
-        } catch (Throwable $th) {
-            return $this->response_controller
-                ->makeResponse(TRUE, 'ERR_EQUIPO_TRABAJO_REG002: Error inesperado', strtoupper($th->getMessage()), 500);
+        $team = DB::table('S002V01TEQMA')->where([
+            ['EQMA_NOMB', '=', $form['NAME']],
+            ['EQMA_NULI', '=', $form['linea']],
+            ['EQMA_ESTA', '=', 'Activo'],
+        ])->get()->all();
+
+        if(count($team) > 0){
+            return $this->responseController->makeResponse(true, "El nombre $form[NAME] ya fue tomado", [], 401);
         }
+
+        $now = $this->functionsController->now();
+        $nowStr = $now->toDateTimeString();
+        DB::table('S002V01TEQMA')->insert([
+            "EQMA_NULI" => $form['linea'],
+            "EQMA_NOMB" => $form['NAME'],
+            "EQMA_ESPE" => $form['SPECIALITY'],
+            "EQMA_USRE" => $idUser,
+            "EQMA_FERE" => $nowStr,
+        ]);
+
+        $actions = DB::getQueryLog();
+        $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
+        
+        $idac = $this->functionsController->registerActivity(
+            $form['linea'],
+            'S002V01M11GPRS',
+            'S002V01F01AETR',
+            'S002V01P02REET',
+            'Registro',
+            "El usuario $name (" . $usr->USUA_IDUS . ") registró el equipo de trabajo $form[NAME].",
+            $idUser,
+            $nowStr,
+            'S002V01S04GETR'
+        );
+
+        $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']);
+        return $this->responseController->makeResponse(false, 'EXITO.');
     }
 
-    // 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", '=', $line_number)
-                ->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")
-                ->select("USUA_IDUS as ID", DB::raw('TRIM(CONCAT(USUA_NOMB, " " , USUA_APPA, " ", COALESCE(USUA_APMA,""))) AS NAME'))
-                ->where('USUA_NULI', '=', $line_number)
-                ->get();
-
-            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);
+    public function getConsultOfWorkteams($idUser, $line) {
+        DB::enableQueryLog();
+
+        $idUser = $this->encryptionController->decrypt($idUser);
+        if(!$idUser){
+            return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente', [], 400);
         }
-    }
 
-    // Metodo para la eliminación lógica de un equipo de trabajo
-    public function updateToInactiveStatus(Request $request, $id_workteam)
-    {
-        try {
-
-            $request['SAVED_BY_USER'] = $this->encrypt_controller->decrypt($request->SAVED_BY_USER);
-            $validator = Validator::make($request->all(), [
-                "SAVED_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')
-                ->select('USUA_IDUS as ID_USER')
-                ->where('USUA_IDUS', '=', $request->SAVED_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" => "Eliminado",
-                    "EQMA_USMO" => trim($request->SAVED_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);
+        $usr = DB::table('S002V01TUSUA')->where([
+            ['USUA_NULI', '=', $line],
+            ['USUA_IDUS', '=', $idUser],
+        ])->first();
+
+        if(is_null($usr)){
+            return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado', [], 404);
         }
+
+        $workteams = DB::table('S002V01TEQMA')->select([
+            'EQMA_IDEQ as WORKTEAM_ID',
+            'EQMA_NOMB as NAME',
+            'EQMA_ESPE as SPECIALITY',
+            'EQMA_ESTA as STATUS'
+        ])->where('EQMA_NULI', '=', $line)->get()->all();
+
+        $now = $this->functionsController->now();
+        $nowStr = $now->toDateTimeString();
+        $actions = DB::getQueryLog();
+        $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
+        
+        $idac = $this->functionsController->registerActivity(
+            $line,
+            'S002V01M11GPRS',
+            'S002V01F01AETR',
+            'S002V01P01CETR',
+            'Consulta',
+            "El usuario $name (" . $usr->USUA_IDUS . ") consultó los equipos de trabajo registrados.",
+            $idUser,
+            $nowStr,
+            'S002V01S04GETR'
+        );
+
+        $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
+        return $this->responseController->makeResponse(false, 'EXITO.', $workteams);
     }
-    // Metodo para la activación lógica de un equipo de trabajo
-    public function updateToActiveStatus(Request $request, $id_workteam)
-    {
-        try {
-
-            $request['SAVED_BY_USER'] = $this->encrypt_controller->decrypt($request->SAVED_BY_USER);
-            $validator = Validator::make($request->all(), [
-                "SAVED_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);
-            }
-
-            $user_register = DB::table('S002V01TUSUA')
-                ->select('USUA_IDUS as ID_USER')
-                ->where('USUA_IDUS', '=', $request->SAVED_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_REG003: Tu usuario no es válido para activar equipos de trabajo", [], 500);
-            }
-
-            $UPDATE_DATE = Carbon::now()->timezone('America/Mexico_City')->toDateTimeString();
-
-            $activate_workteam = DB::table('S002V01TEQMA')
-                ->where("EQMA_IDEQ", '=', $id_workteam)
-                ->where('EQMA_NULI', '=', $request->LINE_NUMBER)
-                ->update([
-                    "EQMA_ESTA" => "Activo",
-                    "EQMA_USMO" => trim($request->SAVED_BY_USER),
-                    "EQMA_FEMO" => $UPDATE_DATE,
-                    "EQMA_FEAR" => DB::raw('CURRENT_TIMESTAMP')
-                ]);
-
-            if (!$activate_workteam) {
-                return $this->response_controller
-                    ->makeResponse(TRUE, 'ERR_EQUIPO_TRABAJO_REG004: Algo salió mal, error activando al equipo de trabajo', [], 500);
-            }
-
-            return $this->response_controller
-                ->makeResponse(FALSE, 'Activación exitosa');
-
-        } catch (Throwable $th) {
-            return $this->response_controller
-                ->makeResponse(TRUE, 'ERR_EQUIPO_TRABAJO_REG005: Error inesperado', strtoupper($th->getMessage()), 500);
+    
+    public function getWorkteamById($workteam, $idUser, $line) {
+        DB::enableQueryLog();
+
+        $idUser = $this->encryptionController->decrypt($idUser);
+        if(!$idUser){
+            return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente', [], 400);
+        }
+
+        $usr = DB::table('S002V01TUSUA')->where([
+            ['USUA_NULI', '=', $line],
+            ['USUA_IDUS', '=', $idUser],
+        ])->first();
+
+        if(is_null($usr)){
+            return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado', [], 404);
+        }
+
+        $workteam = $this->encryptionController->decrypt($workteam);
+        if(!$workteam){
+            return $this->responseController->makeResponse(true, 'El ID equipo de trabajo solicitado no está encriptado correctamente', [], 400);
         }
+
+        $team = DB::table('S002V01TEQMA')->select([
+            'EQMA_IDEQ as WORKTEAM_ID',
+            'EQMA_NOMB as NAME',
+            'EQMA_ESPE as SPECIALITY',
+            'EQMA_ESTA as STATUS'
+        ])->where([
+            ['EQMA_IDEQ', '=', $workteam],
+            ['EQMA_NULI', '=', $line],
+        ])->first();
+
+        if(is_null($team)){
+            return $this->responseController->makeResponse(true, 'El equipo de trabajo consultado no está registrado', [], 404);
+        }
+
+        $now = $this->functionsController->now();
+        $nowStr = $now->toDateTimeString();
+        $actions = DB::getQueryLog();
+        $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
+        
+        $idac = $this->functionsController->registerActivity(
+            $line,
+            'S002V01M11GPRS',
+            'S002V01F01AETR',
+            'S002V01P03DETR',
+            'Consulta',
+            "El usuario $name (" . $usr->USUA_IDUS . ") consultó los detalles del equipo de trabajo " . $team->NAME . ".",
+            $idUser,
+            $nowStr,
+            'S002V01S04GETR'
+        );
+
+        $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
+        return $this->responseController->makeResponse(false, 'EXITO.', $team);
     }
 
-    // Metodo para guardar un equipo de trabajo
-    public function storeWorkteam(Request $request)
-    {
-        try {
-            $REGISTER_DATE = Carbon::now()->timezone('America/Mexico_City')->toDateTimeString();
-            $request['SAVED_BY_USER'] = $this->encrypt_controller->decrypt($request->SAVED_BY_USER);
-            $validator = Validator::make($request->all(), [
-                "NAME" => ['required', 'max:100'],
-                "SPECIALITY" => ['required', 'max:100'],
-                "SAVED_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', '=', $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_REG002: El nombre ya fue tomado', [], 500);
-            }
-
-            $user_register = DB::table('S002V01TUSUA')
-                ->select('USUA_IDUS as ID_USER')
-                ->where('USUA_IDUS', '=', $request->SAVED_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 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->SAVED_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);
+    public function getMembersOfWorkteamById($workteam, $idUser, $line) {
+        DB::enableQueryLog();
+
+        $idUser = $this->encryptionController->decrypt($idUser);
+        if(!$idUser){
+            return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente', [], 400);
+        }
+
+        $usr = DB::table('S002V01TUSUA')->where([
+            ['USUA_NULI', '=', $line],
+            ['USUA_IDUS', '=', $idUser],
+        ])->first();
+
+        if(is_null($usr)){
+            return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado', [], 404);
+        }
+
+        $workteam = $this->encryptionController->decrypt($workteam);
+        if(!$workteam){
+            return $this->responseController->makeResponse(true, 'El ID equipo de trabajo solicitado no está encriptado correctamente', [], 400);
+        }
+
+        $team = DB::table('S002V01TEQMA')->where([
+            ['EQMA_IDEQ', '=', $workteam],
+            ['EQMA_NULI', '=', $line],
+        ])->first();
+
+        if(is_null($team)){
+            return $this->responseController->makeResponse(true, 'El equipo de trabajo consultado no está registrado', [], 404);
         }
+
+        $members = DB::table('S002V01TPERS')->select([
+            DB::raw('TRIM(CONCAT(USUA_NOMB, " " , USUA_APPA, " ", COALESCE(USUA_APMA,""))) as NAME'),
+            'PERS_IDPE AS IDEMPLEADO',
+            'PERS_IDUS AS IDUSUARIO'
+        ])->where([
+            ['EQMA_IDEQ', '=', $workteam],
+            ['EQMA_NULI', '=', $line],
+            ['PERS_ESTA', '=', 'Activo'],
+        ])->join(
+            'S002V01TUSUA', 'PERS_IDUS', '=', 'USUA_IDUS'
+        )->join(
+            'S002V01TEQMA', 'PERS_EQTR', '=', 'EQMA_IDEQ'
+        )->get()->all();
+
+        $now = $this->functionsController->now();
+        $nowStr = $now->toDateTimeString();
+        $actions = DB::getQueryLog();
+        $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
+        
+        $idac = $this->functionsController->registerActivity(
+            $line,
+            'S002V01M11GPRS',
+            'S002V01F01AETR',
+            'S002V01P03DETR',
+            'Consulta',
+            "El usuario $name (" . $usr->USUA_IDUS . ") consultó los integrantes del equipo de trabajo " . $team->EQMA_NOMB . ".",
+            $idUser,
+            $nowStr,
+            'S002V01S04GETR'
+        );
+
+        $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
+        return $this->responseController->makeResponse(false, 'EXITO.', $members);
     }
 
-    // Metodo para actualizar un equipo de trabajo
-    public function updateWorkteam(Request $request, $id_workteam)
-    {
-        try {
-            $UPDATE_DATE = Carbon::now()->timezone('America/Mexico_City')->toDateTimeString();
-            $request['SAVED_BY_USER'] = $this->encrypt_controller->decrypt($request->SAVED_BY_USER);
-            $validator = Validator::make($request->all(), [
-                "NAME" => ['required', 'max:100'],
-                "SPECIALITY" => ['required', 'max:100'],
-                "SAVED_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')
-                ->select('USUA_IDUS as ID_USER')
-                ->where('USUA_IDUS', '=', $request->SAVED_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->SAVED_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);
+    public function updateWorkteam(Request $request) {
+        DB::enableQueryLog();
+
+        $validator = Validator::make($request->all(), [
+            'id_user' => 'required|string',
+            'linea' => 'required|integer',
+            'WORKTEAM_ID' =>'required|string',
+            'NAME' => 'required|string|max:100',
+            'SPECIALITY' => 'required|string|max:100',
+        ]);
+
+        if($validator->fails()) {
+            return $this->responseController->makeResponse(
+                TRUE,
+                'ERR_EQUIPO_TRABAJO_REG001: Uno o más errores encontrados',
+                $this->responseController->makeErrors($validator->errors()->messages()),
+                400
+            );
+        }
+
+        $form = $request->all();
+        $idUser = $this->encryptionController->decrypt($form['id_user']);
+        if(!$idUser){
+            return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente', [], 400);
+        }
+
+        $usr = DB::table('S002V01TUSUA')->where([
+            ['USUA_NULI', '=', $form['linea']],
+            ['USUA_IDUS', '=', $idUser],
+        ])->first();
+
+        if(is_null($usr)){
+            return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado', [], 404);
         }
+
+        $workteam = $this->encryptionController->decrypt($form['WORKTEAM_ID']);
+        if(!$workteam){
+            return $this->responseController->makeResponse(true, 'El ID equipo de trabajo solicitado no está encriptado correctamente', [], 400);
+        }
+
+        $team = DB::table('S002V01TEQMA')->where([
+            ['EQMA_IDEQ', '=', $workteam],
+            ['EQMA_NULI', '=', $form['linea']],
+        ])->first();
+
+        if(is_null($team)){
+            return $this->responseController->makeResponse(true, 'El equipo de trabajo consultado no está registrado', [], 404);
+        }
+
+        $now = $this->functionsController->now();
+        $nowStr = $now->toDateTimeString();
+
+        DB::table('S002V01TEQMA')->where([
+            ["EQMA_IDEQ", '=', $workteam],
+            ['EQMA_NULI', '=', $form['linea']]
+        ])->update([
+            "EQMA_NOMB" => $form['NAME'],
+            "EQMA_ESPE" => $form['SPECIALITY'],
+            "EQMA_USMO" => $idUser,
+            "EQMA_FEMO" => $nowStr,
+        ]);
+
+        $actions = DB::getQueryLog();
+        $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
+        
+        $idac = $this->functionsController->registerActivity(
+            $form['linea'],
+            'S002V01M11GPRS',
+            'S002V01F01AETR',
+            'S002V01P02REET',
+            'Actualización',
+            "El usuario $name (" . $usr->USUA_IDUS . ") actualizó el equipo de trabajo #$workteam.",
+            $idUser,
+            $nowStr,
+            'S002V01S04GETR'
+        );
+
+        $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']);
+        return $this->responseController->makeResponse(false, 'EXITO.');
     }
 
-}
+    public function updateToInactiveStatus(Request $request) {
+        DB::enableQueryLog();
+
+        $validator = Validator::make($request->all(), [
+            'id_user' => 'required|string',
+            'linea' => 'required|integer',
+            'WORKTEAM_ID' =>'required|string',
+        ]);
+
+        if($validator->fails()) {
+            return $this->responseController->makeResponse(
+                TRUE,
+                'ERR_EQUIPO_TRABAJO_REG001: Uno o más errores encontrados',
+                $this->responseController->makeErrors($validator->errors()->messages()),
+                400
+            );
+        }
+
+        $form = $request->all();
+        $idUser = $this->encryptionController->decrypt($form['id_user']);
+        if(!$idUser){
+            return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente', [], 400);
+        }
+
+        $usr = DB::table('S002V01TUSUA')->where([
+            ['USUA_NULI', '=', $form['linea']],
+            ['USUA_IDUS', '=', $idUser],
+        ])->first();
+
+        if(is_null($usr)){
+            return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado', [], 404);
+        }
+
+        $workteam = $this->encryptionController->decrypt($form['WORKTEAM_ID']);
+        if(!$workteam){
+            return $this->responseController->makeResponse(true, 'El ID equipo de trabajo solicitado no está encriptado correctamente', [], 400);
+        }
+
+        $team = DB::table('S002V01TEQMA')->where([
+            ['EQMA_IDEQ', '=', $workteam],
+            ['EQMA_NULI', '=', $form['linea']],
+        ])->first();
+
+        if(is_null($team)){
+            return $this->responseController->makeResponse(true, 'El equipo de trabajo consultado no está registrado', [], 404);
+        }
+
+        $members = DB::table('S002V01TPERS')->select([
+            DB::raw('TRIM(CONCAT(USUA_NOMB, " " , USUA_APPA, " ", COALESCE(USUA_APMA,""))) as NAME'),
+            'PERS_IDPE AS IDEMPLEADO',
+            'PERS_IDUS AS IDUSUARIO'
+        ])->where([
+            ['EQMA_IDEQ', '=', $workteam],
+            ['EQMA_NULI', '=', $form['linea']],
+            ['PERS_ESTA', '=', 'Activo'],
+        ])->join(
+            'S002V01TUSUA', 'PERS_IDUS', '=', 'USUA_IDUS'
+        )->join(
+            'S002V01TEQMA', 'PERS_EQTR', '=', 'EQMA_IDEQ'
+        )->get()->all();
+
+        if(count($members) > 0){
+            return $this->responseController->makeResponse(true, 'El equipo de trabajo que desea eliminar tiene usuarios relacionados.', [], 401);
+        }
+
+        $now = $this->functionsController->now();
+        $nowStr = $now->toDateTimeString();
+
+        DB::table('S002V01TEQMA')->where([
+            ["EQMA_IDEQ", '=', $workteam],
+            ['EQMA_NULI', '=', $form['linea']]
+        ])->update([
+            "EQMA_ESTA" => 'Eliminado',
+            "EQMA_USMO" => $idUser,
+            "EQMA_FEMO" => $nowStr,
+        ]);
+
+        $actions = DB::getQueryLog();
+        $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
+        
+        $idac = $this->functionsController->registerActivity(
+            $form['linea'],
+            'S002V01M11GPRS',
+            'S002V01F01AETR',
+            'S002V01P01CETR',
+            'Eliminación',
+            "El usuario $name (" . $usr->USUA_IDUS . ") eliminó el equipo de trabajo #$workteam.",
+            $idUser,
+            $nowStr,
+            'S002V01S04GETR'
+        );
+
+        $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']);
+        return $this->responseController->makeResponse(false, 'EXITO.');
+    }
+}

+ 31 - 4
sistema-mantenimiento-back/routes/api.php

@@ -211,6 +211,33 @@ Route::middleware(['jwt.auth'])->group(function(){
     Route::get("/get-activators-by-type/{type}/{idUser}/{line}", "App\Http\Controllers\CountersActivatorsController@getActivatorsByType");
     Route::get("/get-activator/{idActi}/{idUser}/{line}", "App\Http\Controllers\CountersActivatorsController@getActivator");
     Route::post("/register-activator", "App\Http\Controllers\CountersActivatorsController@registerActivator");
+    //Módulo gestión del personal de mantenimiento
+    Route::get("/employee/consult/{idUser}/{line}", "App\Http\Controllers\EmployeeController@getConsultOfEmployees");
+    Route::get("/employee/only/{idEmployee}/{idUser}/{line}", "App\Http\Controllers\EmployeeController@getEmployeeById");
+    Route::get("/employee/contracts/employees/{idUser}/{line}", "App\Http\Controllers\EmployeeController@getContractsOfEveryEmployee");
+    Route::get("/employee/contracts/history/{idEmployee}/{idUser}/{line}", "App\Http\Controllers\EmployeeController@getDetailsOfContractsByEmployee");
+    Route::get("/employee/orders/{idEmployee}/{idUser}/{line}", "App\Http\Controllers\EmployeeController@getInterventionsByEmployee");
+    Route::get("/subcontract/consult/{idUser}/{line}", "App\Http\Controllers\SubcontractController@getConsultOfSubcontratists");
+    Route::get("/subcontract/only/{idSub}/{idUser}/{line}", "App\Http\Controllers\SubcontractController@getSubcontratistById");
+    Route::get("/subcontract/contracts/subcontratists/{idUser}/{line}", "App\Http\Controllers\SubcontractController@getContractsOfEverySubcontratist");
+    Route::get("/subcontract/contracts/history/{idSubcontratist}/{idUser}/{line}", "App\Http\Controllers\SubcontractController@getContractsBySubcontratist");
+    Route::get("/subcontract/download-info-excel/{idSubcontratist}/{idUser}/{line}", "App\Http\Controllers\SubcontractController@downloadSubcontractInfoOnExcel");
+    Route::get("/subcontract/download-info-pdf/{idSubcontratist}/{idUser}/{line}", "App\Http\Controllers\SubcontractController@downloadSubcontractInfoOnPdf");
+    Route::get("/workteam/consult/{idUser}/{line}", "App\Http\Controllers\WorkTeamController@getConsultOfWorkteams");
+    Route::get("/workteam/only/{workteam}/{idUser}/{line}", "App\Http\Controllers\WorkTeamController@getWorkteamById");
+    Route::get("/workteam/members/{workteam}/{idUser}/{line}", "App\Http\Controllers\WorkTeamController@getMembersOfWorkteamById");
+    Route::get("/intervention/contract/consult/{idUser}/{line}", "App\Http\Controllers\InterventionController@getConsultOfContracts");
+    Route::get("/intervention/consult/{idUser}/{line}", "App\Http\Controllers\InterventionController@getConsultOfInterventions");
+    Route::post("/employee/register", "App\Http\Controllers\EmployeeController@storeEmployee");
+    Route::post("/employee/update", "App\Http\Controllers\EmployeeController@updateEmployee");
+    Route::post("/employee/delete", "App\Http\Controllers\EmployeeController@updateToInactiveStatus");
+    Route::post("/subcontract/register", "App\Http\Controllers\SubcontractController@storeSubcontratist");
+    Route::post("/subcontract/update", "App\Http\Controllers\SubcontractController@updateSubcontratist");
+    Route::post("/subcontract/delete", "App\Http\Controllers\SubcontractController@updateToInactiveStatus");
+    Route::post("/workteam/register", "App\Http\Controllers\WorkTeamController@storeWorkteam");
+    Route::post("/workteam/update", "App\Http\Controllers\WorkTeamController@updateWorkteam");
+    Route::post("/workteam/delete", "App\Http\Controllers\WorkTeamController@updateToInactiveStatus");
+    Route::post("/intervention/contract/register", "App\Http\Controllers\InterventionController@storeContract");
 });
 
 // Module (FUNCIONALES)
@@ -320,7 +347,7 @@ Route::middleware(['jwt.auth'])->group(function(){
     Route::post('failure-analysis/delete-symptom',                                                                  [SymptomController::class,         'deleteSymptom']);
     
     // Module: GPRS
-    Route::get ('subcontract/consult/{line_number}',                                [SubcontractController::class,      'getConsultOfSubcontratists']);
+    /*Route::get ('subcontract/consult/{line_number}',                                [SubcontractController::class,      'getConsultOfSubcontratists']);
     Route::put ('subcontract/inactive-subcontratist/{id_subcontratist}',            [SubcontractController::class,      'updateToInactiveStatus']);
     Route::put ('subcontract/active-subcontratist/{id_subcontratist}',              [SubcontractController::class,      'updateToActiveStatus']);
     Route::get ('subcontract/subcontratists/{line_number}',                         [SubcontractController::class,      'getAllSubcontratists']);
@@ -330,8 +357,8 @@ Route::middleware(['jwt.auth'])->group(function(){
     Route::put ('subcontract/{id_subcontratist}',                                   [SubcontractController::class,      'updateSubcontratist']);
     Route::get ('subcontract/contracts/subcontratists/{line_number}',               [SubcontractController::class,      'getContractsOfEverySubcontratist']);
     Route::get ('subcontract/contracts/history/{id_subcontratist}/{line_number}',   [SubcontractController::class,      'getContractsBySubcontratist']);
-    Route::post('subcontract/downoload-info-excel',                                 [SubcontractController::class,      'downoloadSubcontractInfoOnExcel']);
-    Route::post('subcontract/downoload-info-pdf',                                   [SubcontractController::class,      'downoloadSubcontractInfoOnPdf']);
+    Route::post('subcontract/downoload-info-excel',                                 [SubcontractController::class,      'downloadSubcontractInfoOnExcel']);
+    Route::post('subcontract/downoload-info-pdf',                                   [SubcontractController::class,      'downloadSubcontractInfoOnPdf']);
     Route::post('employee/consult/{line_number}',                                   [EmployeeController::class,         'getConsultOfEmployees']);
     Route::get ('employee/user-avaible/{id_employee}/{line_number}',                [EmployeeController::class,         'getAvaibleUsers']);
     Route::get ('employee/last-documents/{id_employee}/{line_number}',              [EmployeeController::class,         'getLastDocumentsByEmployee']);
@@ -361,7 +388,7 @@ Route::middleware(['jwt.auth'])->group(function(){
     Route::put ('workteam/inactive-workteam/{id_workteam}',                         [WorkTeamController::class,         'updateToInactiveStatus']);
     Route::put ('workteam/active-workteam/{id_workteam}',                           [WorkTeamController::class,         'updateToActiveStatus']);
     Route::post('workteam/',                                                        [WorkTeamController::class,         'storeWorkteam']);
-    Route::put ('workteam/{id_workteam}',                                           [WorkTeamController::class,         'updateWorkteam']);
+    Route::put ('workteam/{id_workteam}',                                           [WorkTeamController::class,         'updateWorkteam']);*/
 
     Route::get ('locate/postal-code-data/{postal_code}/{line_number}',             [LocateController::class,        'getDataByPostalCode']);
     Route::get ('locate/countries/{line_number}',                                  [LocateController::class,        'getCountries']);