TemplatesManagementController.php 79 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068
  1. <?php
  2. namespace App\Http\Controllers;
  3. use Illuminate\Http\Request;
  4. use Illuminate\Support\Facades\DB;
  5. use Illuminate\Support\Facades\Validator;
  6. use Illuminate\Support\Carbon;
  7. use PhpOffice\PhpSpreadsheet\Spreadsheet;
  8. use PhpOffice\PhpSpreadsheet\IOFactory;
  9. use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
  10. class TemplatesManagementController extends Controller {
  11. private $responseController;
  12. private $encryptionController;
  13. private $functionsController;
  14. private $resourcesController;
  15. private $documentManagementController;
  16. private $templatesUbic;
  17. public function __construct(){
  18. $this->responseController = new ResponseController();
  19. $this->encryptionController = new EncryptionController();
  20. $this->functionsController = new FunctionsController();
  21. $this->resourcesController = new ResourcesController();
  22. $this->documentManagementController = new DocumentManagementController();
  23. $this->templatesUbic = app_path('Http/Controllers');
  24. }
  25. /**
  26. * Validar y procesar plantilla Excel de equipamientos
  27. * Recibe el ID del archivo temporal ya cargado
  28. */
  29. public function validateAndProcessExcelTemplate(Request $request) {
  30. DB::enableQueryLog();
  31. $validator = Validator::make($request->all(), [
  32. 'id_user' => 'required|string',
  33. 'id_file' => 'required|string',
  34. 'linea' => 'required|integer',
  35. ]);
  36. if($validator->fails()){
  37. return $this->responseController->makeResponse(
  38. true,
  39. "Se encontraron uno o más errores.",
  40. $this->responseController->makeErrors($validator->errors()->messages()),
  41. 401
  42. );
  43. }
  44. $form = $request->all();
  45. $idUser = '0000000001';
  46. if(!$idUser){
  47. return $this->responseController->makeResponse(true, "El id del usuario no fue desencriptado correctamente", [], 400);
  48. }
  49. $usr = DB::table('S002V01TUSUA')->where([
  50. ['USUA_IDUS', '=', $idUser],
  51. ['USUA_NULI', '=', $form['linea']]
  52. ])->first();
  53. if(is_null($usr)){
  54. return $this->responseController->makeResponse(true, 'El usuario no está registrado', [], 404);
  55. }
  56. // Obtener archivo temporal
  57. $fileIdDecrypted = $this->encryptionController->decrypt($form['id_file']);
  58. $tempFile = DB::table('S002V01TARTE')->where([
  59. ['ARTE_IDAR', '=', $fileIdDecrypted],
  60. ['ARTE_NULI', '=', $form['linea']]
  61. ])->first();
  62. if(is_null($tempFile)){
  63. return $this->responseController->makeResponse(true, 'El archivo temporal no fue encontrado', [], 404);
  64. }
  65. try {
  66. // Validar estructura del Excel
  67. $structureValidation = $this->validateExcelStructure($tempFile->ARTE_UBTE);
  68. if(!$structureValidation['valid']) {
  69. return $this->responseController->makeResponse(true, $structureValidation['message'], [], 400);
  70. }
  71. // Procesar contenido del Excel
  72. $spreadsheet = IOFactory::load($tempFile->ARTE_UBTE);
  73. $config = ExcelTemplateConfig::getTemplateConfigs()['TPCEQ'];
  74. $acronymMappings = $this->extractAcronymMappings($spreadsheet);
  75. $cargaMap = $acronymMappings['carga'];
  76. $lruMap = $acronymMappings['lru'];
  77. $sheetsToProcess = [
  78. 'CASO 1', 'CASO 2', 'CASO 3',
  79. 'CASO 4', 'CASO 5', 'CASO 6'
  80. ];
  81. $processedData = [];
  82. $errors = [];
  83. $successCount = 0;
  84. DB::beginTransaction();
  85. foreach($sheetsToProcess as $sheetName) {
  86. // Verificar si la hoja existe en el documento
  87. if(!in_array($sheetName, $spreadsheet->getSheetNames())) {
  88. $errors[] = "Hoja requerida no encontrada: $sheetName";
  89. continue;
  90. }
  91. // Obtener configuración de la hoja
  92. $sheetConfig = $config['worksheets'][$sheetName] ?? null;
  93. if(!$sheetConfig) {
  94. $errors[] = "Configuración no encontrada para hoja: $sheetName";
  95. continue;
  96. }
  97. $worksheet = $spreadsheet->getSheetByName($sheetName);
  98. $result = $this->processWorksheet(
  99. $worksheet,
  100. $sheetConfig,
  101. $sheetName,
  102. $form['linea'],
  103. $idUser,
  104. $cargaMap, // Nuevo parámetro
  105. $lruMap // Nuevo parámetro
  106. );
  107. $worksheet = $spreadsheet->getSheetByName($sheetName);
  108. $result = $this->processWorksheet($worksheet, $sheetConfig, $sheetName, $form['linea'], $idUser, $cargaMap, $lruMap);
  109. $processedData = array_merge($processedData, $result['data']);
  110. $errors = array_merge($errors, $result['errors']);
  111. $successCount += $result['count'];
  112. }
  113. if(!empty($errors) && empty($processedData)) {
  114. DB::rollBack();
  115. return $this->responseController->makeResponse(true, "Errores en el procesamiento: " . implode('; ', array_slice($errors, 0, 5)), [], 400);
  116. }
  117. // Insertar datos procesados en la tabla temporal de equipamientos
  118. foreach($processedData as $data) {
  119. DB::table('S002V01TPCEQ')->insert($data);
  120. }
  121. DB::commit();
  122. // Registrar actividad
  123. $nowStr = Carbon::now('America/Mexico_city')->toDateTimeString();
  124. $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
  125. $actions = DB::getQueryLog();
  126. $idac = $this->functionsController->registerActivity(
  127. $form['linea'],
  128. 'S002V01M07GEEQ',
  129. 'S002V01F01ADEQ',
  130. 'S002V01P11REEQ',
  131. 'Procesamiento',
  132. "El usuario $name (" . $usr->USUA_IDUS . ") procesó $successCount equipos desde el archivo {$tempFile->ARTE_NOAR}.",
  133. $idUser,
  134. $nowStr,
  135. );
  136. $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']);
  137. $responseData = [
  138. 'equipos_procesados' => $successCount,
  139. 'archivo' => $tempFile->ARTE_NOAR,
  140. 'id_archivo' => $form['id_file']
  141. ];
  142. if(!empty($errors)) {
  143. $responseData['advertencias'] = array_slice($errors, 0, 10);
  144. }
  145. return $this->responseController->makeResponse(false, "Procesamiento exitoso", $responseData);
  146. } catch(Exception $e) {
  147. DB::rollBack();
  148. return $this->responseController->makeResponse(true, "Error al procesar el archivo: " . $e->getMessage(), [], 500);
  149. }
  150. }
  151. private function extractAcronymMappings($spreadsheet) {
  152. $mappings = [
  153. 'carga' => [
  154. 'equipos' => [],
  155. 'modelos' => []
  156. ],
  157. 'lru' => [
  158. 'equipos' => [],
  159. 'modelos' => []
  160. ]
  161. ];
  162. // Normalizar nombres de hojas
  163. $sheetNames = array_map('strtolower', $spreadsheet->getSheetNames());
  164. // 1. Encontrar hoja CARGA DE EQUIPOS (case-insensitive)
  165. $cargaSheet = null;
  166. foreach ($spreadsheet->getAllSheets() as $sheet) {
  167. if (strtolower(trim($sheet->getTitle())) === 'equipamiento') {
  168. $cargaSheet = $sheet;
  169. break;
  170. }
  171. }
  172. // 2. Procesar hoja CARGA DE EQUIPOS si existe
  173. if ($cargaSheet) {
  174. $highestRow = $cargaSheet->getHighestRow();
  175. \Log::debug("Procesando CARGA DE EQUIPOS. Filas: $highestRow");
  176. for ($row = 9; $row <= $highestRow; $row++) {
  177. // Mapeo de equipos
  178. $acronym = $this->getCellValue($cargaSheet, 'D', $row);
  179. $type = $this->getCellValue($cargaSheet, 'C', $row);
  180. if (!empty($acronym) && !empty($type)) {
  181. $mappings['carga']['equipos'][$acronym] = $type;
  182. }
  183. // Mapeo de modelos
  184. $modelAcronym = $this->getCellValue($cargaSheet, 'F', $row);
  185. $modelFull = $this->getCellValue($cargaSheet, 'E', $row);
  186. if (!empty($modelAcronym) && !empty($modelFull)) {
  187. $mappings['carga']['modelos'][$modelAcronym] = $modelFull;
  188. }
  189. }
  190. \Log::debug('Mapeos CARGA modelos: ' . json_encode($mappings['carga']['modelos']));
  191. } else {
  192. \Log::warning('Hoja CARGA DE EQUIPOS no encontrada en el archivo');
  193. }
  194. // 3. Procesar hoja LRU (usando el mismo método robusto)
  195. $lruSheet = null;
  196. foreach ($spreadsheet->getAllSheets() as $sheet) {
  197. if (strtolower(trim($sheet->getTitle())) === 'lru') {
  198. $lruSheet = $sheet;
  199. break;
  200. }
  201. }
  202. if ($lruSheet) {
  203. $highestRow = $lruSheet->getHighestRow();
  204. for ($row = 9; $row <= $highestRow; $row++) {
  205. // Mapeo de equipos
  206. $acronym = $this->getCellValue($lruSheet, 'D', $row);
  207. $type = $this->getCellValue($lruSheet, 'C', $row);
  208. if (!empty($acronym) && !empty($type)) {
  209. $mappings['lru']['equipos'][$acronym] = $type;
  210. }
  211. // Mapeo de modelos
  212. $modelAcronym = $this->getCellValue($lruSheet, 'F', $row);
  213. $modelFull = $this->getCellValue($lruSheet, 'E', $row);
  214. if (!empty($modelAcronym) && !empty($modelFull)) {
  215. $mappings['lru']['modelos'][$modelAcronym] = $modelFull;
  216. }
  217. }
  218. }
  219. return $mappings;
  220. }
  221. // Nueva función para obtener valores de celda robusta
  222. private function getCellValue($worksheet, $column, $row) {
  223. try {
  224. $cell = $worksheet->getCell($column . $row);
  225. // Manejar cualquier tipo de dato
  226. return trim($cell->getFormattedValue());
  227. } catch (\Exception $e) {
  228. \Log::error("Error leyendo celda $column$row: " . $e->getMessage());
  229. return '';
  230. }
  231. }
  232. /**
  233. * Validar solo la estructura del Excel (sin procesar datos)
  234. */
  235. public function validateExcelStructureOnly(Request $request) {
  236. $validator = Validator::make($request->all(), [
  237. 'id_user' => 'required|string',
  238. 'id_file' => 'required|string',
  239. 'linea' => 'required|integer',
  240. ]);
  241. if($validator->fails()){
  242. return $this->responseController->makeResponse(
  243. true,
  244. "Se encontraron uno o más errores.",
  245. $this->responseController->makeErrors($validator->errors()->messages()),
  246. 401
  247. );
  248. }
  249. $form = $request->all();
  250. $idUser = $this->encryptionController->decrypt($form['id_user']);
  251. if(!$idUser){
  252. return $this->responseController->makeResponse(true, "El id del usuario no fue desencriptado correctamente", [], 400);
  253. }
  254. // Obtener archivo temporal
  255. $fileIdDecrypted = $this->encryptionController->decrypt($form['id_file']);
  256. $tempFile = DB::table('S002V01TARTE')->where([
  257. ['ARTE_IDAR', '=', $fileIdDecrypted],
  258. ['ARTE_NULI', '=', $form['linea']]
  259. ])->first();
  260. if(is_null($tempFile)){
  261. return $this->responseController->makeResponse(true, 'El archivo temporal no fue encontrado', [], 404);
  262. }
  263. // Validar solo la estructura
  264. $structureValidation = $this->validateExcelStructure($tempFile->ARTE_UBTE);
  265. if(!$structureValidation['valid']) {
  266. return $this->responseController->makeResponse(true, $structureValidation['message'], [], 400);
  267. }
  268. return $this->responseController->makeResponse(false, "Estructura del archivo válida", [
  269. 'archivo' => $tempFile->ARTE_NOAR,
  270. 'validado' => true
  271. ]);
  272. }
  273. private function validateExcelStructure($filePath) {
  274. try {
  275. $spreadsheet = IOFactory::load($filePath);
  276. $config = ExcelTemplateConfig::getTemplateConfigs()['TPCEQ'];
  277. $requiredSheets = array_keys($config['worksheets']);
  278. $existingSheets = $spreadsheet->getSheetNames();
  279. // Verificar que existan las hojas requeridas
  280. $missingSheets = array_diff($requiredSheets, $existingSheets);
  281. if(!empty($missingSheets)) {
  282. return [
  283. 'valid' => false,
  284. 'message' => 'Tu documento no cumple con las hojas requeridas de la plantilla'
  285. ];
  286. }
  287. // Validar headers de cada hoja
  288. foreach($config['worksheets'] as $sheetName => $sheetConfig) {
  289. if(!in_array($sheetName, $existingSheets)) continue;
  290. $worksheet = $spreadsheet->getSheetByName($sheetName);
  291. $headerValidation = $this->validateSheetHeaders($worksheet, $sheetConfig, $sheetName);
  292. if(!$headerValidation['valid']) {
  293. return [
  294. 'valid' => false,
  295. 'message' => 'Tu documento tiene error en los Headers, revísalos e intentalo de nuevo'
  296. ];
  297. }
  298. // Validar que tenga datos (solo para CARGA DE EQUIPOS)
  299. if($sheetName === 'CARGA DE EQUIPOS') {
  300. $dataValidation = $this->validateSheetHasData($worksheet, $sheetName, $sheetConfig);
  301. if(!$dataValidation['valid']) {
  302. return $dataValidation;
  303. }
  304. }
  305. }
  306. return ['valid' => true, 'message' => 'Estructura válida'];
  307. } catch(Exception $e) {
  308. return [
  309. 'valid' => false,
  310. 'message' => 'Error al validar la estructura del archivo: ' . $e->getMessage()
  311. ];
  312. }
  313. }
  314. private function validateSheetHeaders($worksheet, $sheetConfig, $sheetName) {
  315. // Para CATÁLOGOS usar validación especial
  316. if($sheetName === 'CATÁLOGOS') {
  317. return $this->validateCatalogosSheet($worksheet);
  318. }
  319. $headerRow = $sheetConfig['header_row'] ?? 4;
  320. $fieldMapping = $sheetConfig['field_mapping'];
  321. // Definir headers esperados según la configuración de Angular
  322. $expectedHeaders = $this->getExpectedHeaders($sheetName);
  323. if(empty($expectedHeaders)) {
  324. return ['valid' => true, 'message' => "No hay headers específicos para validar en $sheetName"];
  325. }
  326. foreach($expectedHeaders as $column => $expectedHeader) {
  327. $cellValue = $worksheet->getCell($column . $headerRow)->getCalculatedValue();
  328. $actualHeader = $cellValue ? trim((string)$cellValue) : '';
  329. if($actualHeader !== $expectedHeader) {
  330. return [
  331. 'valid' => false,
  332. 'message' => "Error en header de $sheetName, columna $column: esperado '$expectedHeader', encontrado '$actualHeader'"
  333. ];
  334. }
  335. }
  336. return ['valid' => true, 'message' => "Headers válidos para $sheetName"];
  337. }
  338. private function validateCatalogosSheet($worksheet) {
  339. $expectedHeaders = [
  340. 'B' => 'FAMILIA',
  341. 'C' => 'ACRÓNIMO',
  342. 'E' => 'SUBFAMILIA',
  343. 'F' => 'ACRÓNIMO',
  344. 'G' => 'SUBFAMILY',
  345. 'I' => 'UBICACIONES (FRENTES)',
  346. 'J' => 'CÓDIGO',
  347. 'L' => 'RMS',
  348. 'M' => 'ELEMENTO',
  349. 'N' => 'CÓDIGO',
  350. 'P' => 'OCUPACIÓN',
  351. 'Q' => 'CÓDIGO',
  352. 'S' => 'ESTADO',
  353. 'T' => 'ACRÓNIMO'
  354. ];
  355. foreach($expectedHeaders as $column => $expectedHeader) {
  356. $cellValue = $worksheet->getCell($column . '5')->getCalculatedValue();
  357. $actualHeader = $cellValue ? trim((string)$cellValue) : '';
  358. if($actualHeader !== $expectedHeader) {
  359. return [
  360. 'valid' => false,
  361. 'message' => "Error en CATÁLOGOS, fila 5, columna $column: esperado '$expectedHeader', encontrado '$actualHeader'"
  362. ];
  363. }
  364. }
  365. return ['valid' => true, 'message' => 'Headers válidos para CATÁLOGOS'];
  366. }
  367. private function validateSheetHasData($worksheet, $sheetName, $sheetConfig) {
  368. try {
  369. $range = $worksheet->calculateWorksheetDimension();
  370. $highestRow = $worksheet->getHighestRow();
  371. $dataStartRow = $sheetConfig['date_start_row'] ?? 9;
  372. if($highestRow < $dataStartRow) {
  373. return [
  374. 'valid' => false,
  375. 'message' => "La hoja '$sheetName' no contiene datos. Se requiere al menos un registro con información."
  376. ];
  377. }
  378. // Verificar que hay al menos una fila con datos
  379. $hasData = false;
  380. $mainColumns = ['B', 'D', 'F', 'G']; // Columnas principales para verificar
  381. for($row = $dataStartRow; $row <= $highestRow; $row++) {
  382. foreach($mainColumns as $col) {
  383. $cellValue = $worksheet->getCell($col . $row)->getCalculatedValue();
  384. if($cellValue !== null && $cellValue !== '' && trim((string)$cellValue) !== '') {
  385. $hasData = true;
  386. break 2;
  387. }
  388. }
  389. }
  390. if(!$hasData) {
  391. return [
  392. 'valid' => false,
  393. 'message' => "La hoja '$sheetName' no contiene datos. Se requiere al menos un registro con información."
  394. ];
  395. }
  396. return ['valid' => true, 'message' => 'Datos encontrados'];
  397. } catch(Exception $e) {
  398. return [
  399. 'valid' => false,
  400. 'message' => "Error al validar datos en '$sheetName': " . $e->getMessage()
  401. ];
  402. }
  403. }
  404. private function getExpectedHeaders($sheetName) {
  405. $headers = [
  406. 'CARGA DE EQUIPOS' => [
  407. 'B' => 'CÓDIGO EQUIVALENTE',
  408. 'C' => 'TIPO / DESCRIPCIÓN',
  409. 'D' => 'ACRÓNIMO DEL EQUIPO',
  410. 'E' => 'MODELO COMPLETO',
  411. 'F' => 'ACRÓNIMO DEL MODELO',
  412. 'G' => 'ID',
  413. 'H' => 'NO.SERIE',
  414. 'I' => 'NO. CÓDIGO DE BARRAS',
  415. 'J' => 'CARÁCTER',
  416. 'K' => 'FECHA DE VENCIMIENTO DEL ARTÍCULO',
  417. 'L' => 'ETIQUETA FINAL DEL EQUIPO',
  418. ],
  419. 'LRU' => [
  420. 'B' => 'CÓDIGO EQUIVALENTE',
  421. 'C' => 'TIPO / DESCRIPCIÓN',
  422. 'D' => 'ACRÓNIMO DEL EQUIPO',
  423. 'E' => 'MODELO COMPLETO',
  424. 'F' => 'ACRÓNIMO DEL MODELO',
  425. 'G' => 'ID',
  426. 'H' => 'NO.SERIE',
  427. 'I' => 'NO. CÓDIGO DE BARRAS',
  428. 'J' => 'CARÁCTER',
  429. 'K' => 'FECHA DE VENCIMIENTO DEL ARTÍCULO',
  430. 'L' => 'ETIQUETA FINAL DEL EQUIPO'
  431. ],
  432. 'CASO 1'=> [
  433. 'B'=> 'LÍNEA',
  434. 'D'=> 'UBICACIÓN',
  435. 'F'=> 'NIVEL',
  436. 'H'=> 'OCUPACIÓN',
  437. 'J'=> 'ELEMENTO',
  438. 'L'=> 'COORDENADAS PLANO GENERAL',
  439. 'M'=> 'COORDENADAS DETALLE',
  440. 'N'=> 'COORDENADAS DE POSICIÓN',
  441. 'P'=> 'FAMILIA',
  442. 'R'=> 'SUBFAMILIA',
  443. 'T'=> 'ESTADO',
  444. 'V'=> 'TIPO',
  445. 'X'=> 'MODELO',
  446. 'Z'=> 'ID',
  447. 'AB'=> 'TIPO',
  448. 'AD'=> 'MODELO',
  449. 'AF'=> 'ID',
  450. 'AH'=> 'CÓDIGO COMPLETO SAM',
  451. 'AI'=> 'CÓDIGO EQUIVALENTE',
  452. ],
  453. 'CASO 2'=> [
  454. 'B'=> 'LÍNEA',
  455. 'D'=> 'UBICACIÓN',
  456. 'F'=> 'NIVEL',
  457. 'H'=> 'OCUPACIÓN',
  458. 'J'=> 'ELEMENTO',
  459. 'L'=> 'COORDENADAS PLANO GENERAL',
  460. 'M'=> 'COORDENADAS DE POSICIÓN',
  461. 'N'=> 'POSICIÓN EN RACK',
  462. 'P'=> 'FAMILIA',
  463. 'R'=> 'SUBFAMILIA',
  464. 'T'=> 'ESTADO',
  465. 'V'=> 'TIPO',
  466. 'X'=> 'MODELO',
  467. 'Z'=> 'ID',
  468. 'AB'=> 'TIPO',
  469. 'AD'=> 'MODELO',
  470. 'AF'=> 'ID',
  471. 'AH'=> 'CÓDIGO COMPLETO',
  472. 'AI'=> 'CÓDIGO EQUIVALENTE',
  473. ],
  474. 'CASO 3'=> [
  475. 'B'=> 'LÍNEA',
  476. 'D'=> 'UBICACIÓN ORIGEN',
  477. 'F'=> 'NIVEL ORIGEN',
  478. 'H'=> 'OCUPACIÓN ORIGEN',
  479. 'J'=> 'ELEMENTO ORIGEN',
  480. 'L'=> 'PK ORIGEN',
  481. 'N'=> 'UBICACIÓN DESTINO',
  482. 'P'=> 'NIVEL DESTINO',
  483. 'R'=> 'OCUPACIÓN DESTINO',
  484. 'T'=> 'ELEMENTO DESTINO',
  485. 'V'=> 'PK DESTINO',
  486. 'X'=> 'FAMILIA',
  487. 'Z'=> 'SUBFAMILIA',
  488. 'AB'=> 'ESTADO',
  489. 'AD'=> 'TIPO',
  490. 'AF'=> 'MODELO',
  491. 'AH'=> 'ID',
  492. 'AJ'=> 'TIPO',
  493. 'AL'=> 'MODELO',
  494. 'AN'=> 'ID',
  495. 'AP'=> 'CÓDIGO COMPLETO',
  496. 'AQ'=> 'CÓDIGO EQUIVALENTE'
  497. ],
  498. 'CASO 4'=> [
  499. 'B'=> 'LÍNEA',
  500. 'D'=> 'UBICACIÓN ORIGEN',
  501. 'F'=> 'NIVEL ORIGEN',
  502. 'H'=> 'OCUPACIÓN ORIGEN',
  503. 'J'=> 'ELEMENTO ORIGEN',
  504. 'L'=> 'SECUENCIAL ORIGEN',
  505. 'N'=> 'COORDENADAS PLANO',
  506. 'O'=> 'COORDENADAS DETALLE',
  507. 'P'=> 'COORDENADAS DE POSICIÓN',
  508. 'R'=> 'UBICACIÓN DESTINO',
  509. 'T'=> 'NIVEL DESTINO',
  510. 'V'=> 'OCUPACIÓN DESTINO',
  511. 'X'=> 'ELEMENTO DESTINO',
  512. 'Z'=> 'SECUENCIAL DESTINO',
  513. 'AB'=> 'COORDENADAS PLANO',
  514. 'AC'=> 'COORDENADAS DETALLE',
  515. 'AD'=> 'COORDENADAS DE POSICIÓN',
  516. 'AF'=> 'FAMILIA',
  517. 'AH'=> 'SUBFAMILIA',
  518. 'AJ'=> 'ESTADO',
  519. 'AL'=> 'TIPO',
  520. 'AN'=> 'MODELO',
  521. 'AP'=> 'ID',
  522. 'AR'=> 'TIPO',
  523. 'AT'=> 'MODELO',
  524. 'AV'=> 'ID',
  525. 'AX'=> 'CÓDIGO COMPLETO',
  526. 'AY'=> 'CÓDIGO EQUIVALENTE',
  527. ],
  528. 'CASO 5'=> [
  529. 'B'=> 'LÍNEA',
  530. 'D'=> 'UBICACIÓN',
  531. 'F'=> 'NIVEL',
  532. 'H'=> 'OCUPACIÓN',
  533. 'J'=> 'ÁREA',
  534. 'L'=> 'ELEMENTO',
  535. 'N'=> 'FAMILIA',
  536. 'P'=> 'SUBFAMILIA',
  537. 'R'=> 'ESTADO',
  538. 'T'=> 'TIPO',
  539. 'V'=> 'MODELO',
  540. 'X'=> 'ID',
  541. 'Z'=> 'TIPO',
  542. 'AB'=> 'MODELO',
  543. 'AD'=> 'ID',
  544. 'AF'=> 'CÓDIGO COMPLETO',
  545. 'AG'=> 'CÓDIGO EQUIVALENTE',
  546. ],
  547. 'CASO 6' => [
  548. 'B'=> 'LÍNEA',
  549. 'D'=> 'UBICACIÓN',
  550. 'F'=> 'NIVEL',
  551. 'H'=> 'OCUPACIÓN',
  552. 'J'=> 'ELEMENTO',
  553. 'L'=> 'POSICIÓN',
  554. 'N'=> 'FAMILIA',
  555. 'P'=> 'SUBFAMILIA',
  556. 'R'=> 'ESTADO',
  557. 'T'=> 'TIPO',
  558. 'V'=> 'MODELO',
  559. 'X'=> 'ID',
  560. 'Z'=> 'TIPO',
  561. 'AB'=> 'MODELO',
  562. 'AD'=> 'ID',
  563. 'AF'=> 'CÓDIGO COMPLETO',
  564. 'AG'=> 'CÓDIGO EQUIVALENTE'
  565. ]
  566. ];
  567. return $headers[$sheetName] ?? [];
  568. }
  569. private function extractRowData($worksheet, $row, $fieldMapping, $sheetName) {
  570. $rowData = [];
  571. foreach($fieldMapping as $column => $field) {
  572. $cellValue = $worksheet->getCell($column . $row)->getCalculatedValue();
  573. // Manejar concatenaciones especiales para coordenadas
  574. if($sheetName === 'CASO 1' || $sheetName === 'CASO 2') {
  575. if($column === 'L' && isset($fieldMapping['M']) && isset($fieldMapping['N'])) {
  576. $coordL = $worksheet->getCell('L' . $row)->getCalculatedValue();
  577. $coordM = $worksheet->getCell('M' . $row)->getCalculatedValue();
  578. $coordN = $worksheet->getCell('N' . $row)->getCalculatedValue();
  579. $rowData['PCEQ_COOR'] = $coordL . $coordM . $coordN;
  580. }
  581. }
  582. if($sheetName === 'CASO 4') {
  583. if($column === 'N' && isset($fieldMapping['O']) && isset($fieldMapping['P'])) {
  584. $coordN = $worksheet->getCell('N' . $row)->getCalculatedValue();
  585. $coordO = $worksheet->getCell('O' . $row)->getCalculatedValue();
  586. $coordP = $worksheet->getCell('P' . $row)->getCalculatedValue();
  587. $rowData['PCEQ_COOR_ORIGEN'] = $coordN . $coordO . $coordP;
  588. }
  589. if($column === 'AB' && isset($fieldMapping['AC']) && isset($fieldMapping['AD'])) {
  590. $coordAB = $worksheet->getCell('AB' . $row)->getCalculatedValue();
  591. $coordAC = $worksheet->getCell('AC' . $row)->getCalculatedValue();
  592. $coordAD = $worksheet->getCell('AD' . $row)->getCalculatedValue();
  593. $rowData['PCEQ_COOR_DESTINO'] = $coordAB . $coordAC . $coordAD;
  594. }
  595. }
  596. if(!empty($field) && !in_array($field, ['.', '-', '_', '+', ':', ';'])) {
  597. $rowData[$field] = $cellValue;
  598. }
  599. }
  600. return $rowData;
  601. }
  602. private function isEmptyRow($rowData) {
  603. $requiredFields = ['PCEQ_TIEQ', 'PCEQ_MOEQ']; // Campos mínimos
  604. foreach($requiredFields as $field) {
  605. if(isset($rowData[$field]) && !empty(trim((string)$rowData[$field]))) {
  606. return false;
  607. }
  608. }
  609. return true;
  610. }
  611. private function validateRowData($rowData, $sheetName, $row) {
  612. $errors = [];
  613. $valid = true;
  614. // Para hojas de casos 1-6
  615. if (in_array($sheetName, ['CASO 1', 'CASO 2', 'CASO 3', 'CASO 4', 'CASO 5', 'CASO 6'])) {
  616. $tienePrimerConjunto =
  617. !empty(trim($rowData['PCEQ_TIEQ'] ?? '')) &&
  618. !empty(trim($rowData['PCEQ_MOEQ'] ?? ''));
  619. $tieneSegundoConjunto =
  620. !empty(trim($rowData['PCEQ_TIEQ_HIJO'] ?? '')) &&
  621. !empty(trim($rowData['PCEQ_MOEQ_HIJO'] ?? ''));
  622. if (!$tienePrimerConjunto && !$tieneSegundoConjunto) {
  623. $errors[] = 'Se requiere al menos un conjunto completo de datos (Tipo/Modelo)';
  624. $valid = false;
  625. }
  626. } else {
  627. // Validación original para otras hojas
  628. if(empty($rowData['PCEQ_TIEQ'] ?? '')) {
  629. $errors[] = 'Tipo de equipo requerido';
  630. $valid = false;
  631. }
  632. if(empty($rowData['PCEQ_MOEQ'] ?? '')) {
  633. $errors[] = 'Modelo requerido';
  634. $valid = false;
  635. }
  636. }
  637. // Validar fechas si existen
  638. $dateFields = ['PCEQ_FEAD', 'PCEQ_FIGA', 'PCEQ_FTGA'];
  639. foreach($dateFields as $dateField) {
  640. if(isset($rowData[$dateField]) && !empty($rowData[$dateField])) {
  641. try {
  642. Carbon::parse($rowData[$dateField]);
  643. } catch(Exception $e) {
  644. $errors[] = "Fecha inválida en campo $dateField";
  645. $valid = false;
  646. }
  647. }
  648. }
  649. return ['valid' => $valid, 'errors' => $errors];
  650. }
  651. private function noDate($value)
  652. {
  653. if (empty($value) ||
  654. strtoupper(trim($value)) === 'NA' ||
  655. trim($value) === '.' ||
  656. trim($value) === '-') {
  657. return now()->format('Y-m-d');
  658. }
  659. if (is_numeric($value)) {
  660. try {
  661. return \PhpOffice\PhpSpreadsheet\Shared\Date::excelToDateTimeObject($value)->format('Y-m-d');
  662. } catch (Exception $e) {
  663. return null;
  664. }
  665. }
  666. if (is_string($value)) {
  667. try {
  668. $date = new \DateTime($value);
  669. return $date->format('Y-m-d');
  670. } catch (Exception $e) {
  671. return null;
  672. }
  673. }
  674. return null;
  675. }
  676. private function prepareEquipmentData($rowData, $linea, $idUser, $sheetName) {
  677. $nowStr = Carbon::now('America/Mexico_city')->toDateTimeString();
  678. // si se llegan a meter columnas de fechas a la hoja ests variables formatean la fecha de la columna, nada más habría que formatear
  679. // queda así
  680. //'PCEQ_FIGA' => $fechaInicioGarantia 'PCEQ_FEAD' => $fechaAdquisicion 'PCEQ_FTGA' => $fechaFinGarantia
  681. $caracter = $this->normalizeCaracter($rowData['PCEQ_CARA'] ?? null);
  682. $fechaInicioGarantia = $this->parseDate($rowData['PCEQ_FIGA'] ?? null);
  683. $fechaFinGarantia = $this->parseDate($rowData['PCEQ_FTGA'] ?? null);
  684. $fechaAdquisicion = $this->parseDate($rowData['PCEQ_FEAD'] ?? null);
  685. $fechaVencimiento = $this->noDate($rowData['PCEQ_FVAR'] ?? null);
  686. $equipmentData = [
  687. 'PCEQ_FIGA' => now()->format('Y-m-d'),
  688. 'PCEQ_FEAD' => now()->format('Y-m-d'),
  689. 'PCEQ_FTGA' => now()->format('Y-m-d'),
  690. 'PCEQ_OTCO' => '[]',
  691. 'PCEQ_NULI' => $linea,
  692. 'PCEQ_UBOR' => $rowData['PCEQ_UBOR'] ?? '',
  693. 'PCEQ_NIOR' => $rowData['PCEQ_NIOR'] ?? '',
  694. 'PCEQ_OCOR' => $rowData['PCEQ_OCOR'] ?? '',
  695. 'PCEQ_ELOR' => $rowData['PCEQ_ELOR'] ?? '',
  696. 'PCEQ_COOR' => $rowData['PCEQ_COOR'] ?? '',
  697. 'PCEQ_FAMI' => $rowData['PCEQ_FAMI'] ?? '',
  698. 'PCEQ_SUBF' => $rowData['PCEQ_SUBF'] ?? '',
  699. 'PCEQ_ESEQ' => $rowData['PCEQ_ESEQ'] ?? 'A',
  700. 'PCEQ_TIEQ' => $rowData['PCEQ_TIEQ'] ?? '',
  701. 'PCEQ_MOEQ' => $rowData['PCEQ_MOEQ'] ?? '',
  702. 'PCEQ_CPGE' => $rowData['PCEQ_CPGE'] ?? '',
  703. 'PCEQ_TICO' => $this->getCodeTypeFromSheet($sheetName),
  704. 'PCEQ_JERA' => 'Padre',
  705. 'PCEQ_EQPA' => null,
  706. 'PCEQ_NUSE' => $rowData['PCEQ_NUSE'] ?? '',
  707. 'PCEQ_COBA' => $rowData['PCEQ_COBA'] ?? '',
  708. 'PCEQ_CARA' => $caracter,
  709. 'PCEQ_PREQ' => $rowData['PCEQ_PREQ'] ?? 0,
  710. 'PCEQ_FVAR' => $fechaVencimiento,
  711. 'PCEQ_GAIM' => json_encode([]),
  712. 'PCEQ_DORE' => json_encode([]),
  713. 'PCEQ_ESRE' => 'Revisión',
  714. 'PCEQ_USRE' => $idUser,
  715. 'PCEQ_FERE' => $nowStr,
  716. 'PCEQ_IDPR' => $this->generateNumericUniqueId($linea)
  717. ];
  718. $this->handleHierarchy($equipmentData, $rowData, $sheetName);
  719. // Lógica de jerarquía (Padre/Hijo) para casos 1-6
  720. if (in_array($sheetName, ['CASO 1', 'CASO 2', 'CASO 3', 'CASO 4', 'CASO 5', 'CASO 6'])) {
  721. // Verificar si los campos del segundo conjunto (AB y AD) tienen datos
  722. $tieneSegundoConjunto =
  723. !empty(trim($rowData['PCEQ_TIEQ_HIJO'] ?? '')) &&
  724. !empty(trim($rowData['PCEQ_MOEQ_HIJO'] ?? ''));
  725. if ($tieneSegundoConjunto) {
  726. // Usar valores del segundo conjunto (Hijo)
  727. $equipmentData['PCEQ_TIEQ'] = $rowData['PCEQ_TIEQ_HIJO'];
  728. $equipmentData['PCEQ_MOEQ'] = $rowData['PCEQ_MOEQ_HIJO'];
  729. $equipmentData['PCEQ_JERA'] = 'Hijo';
  730. } else {
  731. // Usar valores del primer conjunto (Padre)
  732. $equipmentData['PCEQ_TIEQ'] = $rowData['PCEQ_TIEQ'] ?? '';
  733. $equipmentData['PCEQ_MOEQ'] = $rowData['PCEQ_MOEQ'] ?? '';
  734. $equipmentData['PCEQ_JERA'] = 'Padre';
  735. }
  736. } else {
  737. // Para otras hojas (CARGA DE EQUIPOS, LRU) usar valores normales
  738. $equipmentData['PCEQ_TIEQ'] = $rowData['PCEQ_TIEQ'] ?? '';
  739. $equipmentData['PCEQ_MOEQ'] = $rowData['PCEQ_MOEQ'] ?? '';
  740. }
  741. // Agregar campos específicos según el tipo de hoja
  742. $this->addSheetSpecificFields($equipmentData, $rowData, $sheetName);
  743. // Manejar fechas
  744. if(isset($rowData['PCEQ_FEAD'])) {
  745. $equipmentData['PCEQ_FEAD'] = $this->noDate($rowData['PCEQ_FEAD']) ?? now()->format('Y-m-d');
  746. }
  747. if(isset($rowData['PCEQ_FIGA'])) {
  748. $equipmentData['PCEQ_FIGA'] = $this->noDate($rowData['PCEQ_FIGA']) ?? now()->format('Y-m-d');
  749. }
  750. if(isset($rowData['PCEQ_FTGA'])) {
  751. $equipmentData['PCEQ_FTGA'] = $this->noDate($rowData['PCEQ_FTGA']) ?? now()->format('Y-m-d');
  752. }
  753. if(isset($rowData['PCEQ_FVAR'])) {
  754. $equipmentData['PCEQ_FVAR'] = $this->noDate($rowData['PCEQ_FVAR']) ?? now()->format('Y-m-d');
  755. }
  756. // GENERAR PCEQ_IDPR: Solo un ID numérico único simple
  757. $equipmentData['PCEQ_IDPR'] = $this->generateNumericUniqueId($linea);
  758. // GENERAR PCEQ_CPGE: El código concatenado completo (solo para CASOS 1-6)
  759. if(in_array($sheetName, ['CASO 1', 'CASO 2', 'CASO 3', 'CASO 4', 'CASO 5', 'CASO 6'])) {
  760. $equipmentData['PCEQ_CPGE'] = $this->generateConcatenatedCode($equipmentData, $sheetName);
  761. } else {
  762. // Para CARGA DE EQUIPOS y LRU, usar valor por defecto o del Excel
  763. $equipmentData['PCEQ_CPGE'] = $rowData['PCEQ_CPGE'] ?? 'DEFAULT_CODE_' . $equipmentData['PCEQ_IDPR'];
  764. }
  765. return $equipmentData;
  766. }
  767. private function parseDate($value) {
  768. if (!$value) return null;
  769. try {
  770. // Intentar como fecha de Excel
  771. if (is_numeric($value)) {
  772. return \PhpOffice\PhpSpreadsheet\Shared\Date::excelToDateTimeObject($value)
  773. ->format('Y-m-d');
  774. }
  775. // Intentar como cadena de fecha
  776. return Carbon::createFromFormat('d/m/Y', $value)->format('Y-m-d');
  777. } catch (\Exception $e) {
  778. return null;
  779. }
  780. }
  781. // Función para manejar jerarquía
  782. private function handleHierarchy(&$equipmentData, $rowData, $sheetName) {
  783. if (!in_array($sheetName, ['CASO 1','CASO 2','CASO 3','CASO 4','CASO 5','CASO 6'])) {
  784. return;
  785. }
  786. // Determinar si es hijo
  787. $isHijo = !empty($rowData['PCEQ_TIEQ_HIJO']) || !empty($rowData['PCEQ_MOEQ_HIJO']);
  788. if ($isHijo) {
  789. $equipmentData['PCEQ_JERA'] = 'Hijo';
  790. $equipmentData['PCEQ_TIEQ'] = $rowData['PCEQ_TIEQ_HIJO'] ?? '';
  791. $equipmentData['PCEQ_MOEQ'] = $rowData['PCEQ_MOEQ_HIJO'] ?? '';
  792. }
  793. }
  794. private function normalizeCaracter($value) {
  795. if (!$value) return null;
  796. $value = strtoupper(trim($value));
  797. $mapping = [
  798. 'REPARABLE' => 'REPARABLE',
  799. 'REP' => 'REPARABLE',
  800. 'R' => 'REPARABLE',
  801. 'CONSUMIBLE' => 'CONSUMIBLE',
  802. 'CONSUM' => 'CONSUMIBLE',
  803. 'CONS' => 'CONSUMIBLE',
  804. 'C' => 'CONSUMIBLE',
  805. 'DESECHABLE' => 'CONSUMIBLE'
  806. ];
  807. return $mapping[$value] ?? null;
  808. }
  809. // MÉTODO PARA GENERAR PCEQ_IDPR: Solo ID numérico único
  810. private function generateNumericUniqueId($linea) {
  811. // Obtener el máximo ID existente para esta línea
  812. $maxId = DB::table('S002V01TPCEQ')
  813. ->where('PCEQ_NULI', $linea)
  814. ->max('PCEQ_IDPR');
  815. // Generar el siguiente ID secuencial
  816. $nextId = $maxId ? $maxId + 1 : 1;
  817. // Verificar que el ID no exista (por seguridad)
  818. while(DB::table('S002V01TPCEQ')
  819. ->where('PCEQ_NULI', $linea)
  820. ->where('PCEQ_IDPR', $nextId)
  821. ->exists()) {
  822. $nextId++;
  823. }
  824. return $nextId;
  825. }
  826. // MÉTODO PARA GENERAR PCEQ_CPGE: El código concatenado complejo (solo CASOS 1-6)
  827. private function generateConcatenatedCode($equipmentData, $sheetName) {
  828. // Solo generar concatenación para CASOS 1-6
  829. switch($sheetName) {
  830. case 'CASO 1':
  831. case 'CASO 2':
  832. return $this->generateCodeCaso1y2($equipmentData);
  833. case 'CASO 3':
  834. return $this->generateCodeCaso3($equipmentData);
  835. case 'CASO 4':
  836. return $this->generateCodeCaso4($equipmentData);
  837. case 'CASO 5':
  838. case 'CASO 6':
  839. return $this->generateCodeCaso5y6($equipmentData);
  840. default:
  841. return 'DEFAULT_CODE_' . $equipmentData['PCEQ_IDPR'];
  842. }
  843. }
  844. private function generateCodeCaso1y2($data) {
  845. // Patrón: LINEA.UBICACION.NIVEL.OCUPACION.ELEMENTO+COORDENADAS_FAMILIA.SUBFAMILIA.ESTADO.TIPO-MODELO-ID.TIPO-MODELO-ID-CODIGO_SAM
  846. $parts = [
  847. str_pad($data['PCEQ_NULI'], 2, '0', STR_PAD_LEFT), // Línea con padding
  848. $data['PCEQ_UBOR'] ?? '', // Ubicación
  849. $data['PCEQ_NIOR'] ?? '', // Nivel
  850. $data['PCEQ_OCOR'] ?? '', // Ocupación
  851. $data['PCEQ_ELOR'] ?? '', // Elemento
  852. $data['PCEQ_COOR'] ?? '', // Coordenadas
  853. $data['PCEQ_FAMI'] ?? '', // Familia
  854. '',
  855. $data['PCEQ_SUBF'] ?? '', // Subfamilia
  856. $data['PCEQ_ESEQ'] ?? 'A', // Estado
  857. $data['PCEQ_TIEQ'] ?? '', // Tipo
  858. $data['PCEQ_MOEQ'] ?? '', // Modelo
  859. $data['PCEQ_IDPR'], // ID numérico
  860. ];
  861. return implode('.', array_filter($parts));
  862. }
  863. private function generateCodeCaso3($data) {
  864. // Patrón para CASO 3: LINEA.UBICACION_ORIGEN.NIVEL_ORIGEN.OCUPACION_ORIGEN.ELEMENTO_ORIGEN:UBICACION_DESTINO.NIVEL_DESTINO.OCUPACION_DESTINO.ELEMENTO_DESTINO-FAMILIA-SUBFAMILIA.ESTADO-TIPO-MODELO-ID
  865. $parts = [
  866. str_pad($data['PCEQ_NULI'], 2, '0', STR_PAD_LEFT),
  867. $data['PCEQ_UBOR'] ?? '', // Ubicación origen
  868. $data['PCEQ_NIDE'] ?? '', // Nivel origen
  869. $data['PCEQ_OCDE'] ?? '', // Ocupación origen
  870. $data['PCEQ_ELDE'] ?? '', // Elemento origen
  871. $data['PCEQ_UBDE'] ?? '', // Ubicación destino
  872. $data['PCEQ_FAMI'] ?? '', // Familia
  873. $data['PCEQ_SUBF'] ?? '', // Subfamilia
  874. $data['PCEQ_ESEQ'] ?? 'A', // Estado
  875. $data['PCEQ_TIEQ'] ?? '', // Tipo
  876. $data['PCEQ_MOEQ'] ?? '', // Modelo
  877. $data['PCEQ_IDPR'], // ID numérico
  878. ];
  879. return implode('.', array_filter($parts));
  880. }
  881. private function generateCodeCaso4($data) {
  882. // Patrón para CASO 4: Similar a CASO 3 pero con secuenciales y coordenadas adicionales
  883. $parts = [
  884. str_pad($data['PCEQ_NULI'], 2, '0', STR_PAD_LEFT),
  885. $data['PCEQ_UBOR'] ?? '', // Ubicación origen
  886. $data['PCEQ_SEOR'] ?? '0', // Secuencial origen
  887. $data['PCEQ_COOR'] ?? '', // Coordenadas origen
  888. $data['PCEQ_UBDE'] ?? '', // Ubicación destino
  889. $data['PCEQ_SEDE'] ?? '0', // Secuencial destino
  890. $data['PCEQ_CODE'] ?? '', // Coordenadas destino
  891. $data['PCEQ_FAMI'] ?? '', // Familia
  892. $data['PCEQ_SUBF'] ?? '', // Subfamilia
  893. $data['PCEQ_ESEQ'] ?? 'A', // Estado
  894. $data['PCEQ_TIEQ'] ?? '', // Tipo
  895. $data['PCEQ_MOEQ'] ?? '', // Modelo
  896. $data['PCEQ_IDPR'], // ID numérico
  897. ];
  898. return implode('.', array_filter($parts));
  899. }
  900. private function generateCodeCaso5y6($data) {
  901. // Patrón para CASO 5 y 6: LINEA.UBICACION.NIVEL.OCUPACION.AREA.ELEMENTO_FAMILIA.SUBFAMILIA.ESTADO.TIPO-MODELO-ID.TIPO-MODELO-ID-CODIGO
  902. $parts = [
  903. str_pad($data['PCEQ_NULI'], 2, '0', STR_PAD_LEFT),
  904. $data['PCEQ_UBOR'] ?? '', // Ubicación
  905. $data['PCEQ_NIOR'] ?? '', // Nivel
  906. $data['PCEQ_OCOR'] ?? '', // Ocupación
  907. $data['PCEQ_ARTR'] ?? '', // Área
  908. $data['PCEQ_ELOR'] ?? '', // Elemento
  909. $data['PCEQ_FAMI'] ?? '', // Familia
  910. $data['PCEQ_SUBF'] ?? '', // Subfamilia
  911. $data['PCEQ_ESEQ'] ?? 'A', // Estado
  912. $data['PCEQ_TIEQ'] ?? '', // Tipo
  913. $data['PCEQ_MOEQ'] ?? '', // Modelo
  914. $data['PCEQ_IDPR'], // ID numérico
  915. ];
  916. return implode('.', array_filter($parts));
  917. }
  918. // MÉTODO ALTERNATIVO: Usar timestamp + hash para garantizar unicidad (para CARGA DE EQUIPOS y LRU)
  919. private function generateUniqueHashId($linea) {
  920. // Crear ID único basado en timestamp + random para CARGA DE EQUIPOS y LRU
  921. return $linea . '_' . date('YmdHis') . '_' . uniqid();
  922. }
  923. // MÉTODO DE RESPALDO: Si falla todo, usar este ID de emergencia
  924. private function generateFallbackId($linea) {
  925. return 'FALLBACK_' . $linea . '_' . microtime(true) . '_' . rand(10000, 99999);
  926. }
  927. // SOLUCIÓN MEJORADA: Verificar duplicados de PCEQ_IDPR antes de insertar
  928. private function insertEquipmentWithDuplicateHandling($equipmentData) {
  929. $maxAttempts = 5;
  930. $attempt = 0;
  931. while($attempt < $maxAttempts) {
  932. try {
  933. // Verificar si ya existe este PCEQ_IDPR para esta línea
  934. $exists = DB::table('S002V01TPCEQ')
  935. ->where('PCEQ_NULI', $equipmentData['PCEQ_NULI'])
  936. ->where('PCEQ_IDPR', $equipmentData['PCEQ_IDPR'])
  937. ->exists();
  938. if($exists) {
  939. // Regenerar PCEQ_IDPR numérico único
  940. $equipmentData['PCEQ_IDPR'] = $this->generateNumericUniqueId($equipmentData['PCEQ_NULI']);
  941. // Si es un CASO 1-6, regenerar también el PCEQ_CPGE con el nuevo IDPR
  942. if(isset($equipmentData['PCEQ_CPGE']) && strpos($equipmentData['PCEQ_CPGE'], '.') !== false) {
  943. $sheetName = $this->getSheetNameFromCodeType($equipmentData['PCEQ_TICO']);
  944. if($sheetName) {
  945. $equipmentData['PCEQ_CPGE'] = $this->generateConcatenatedCode($equipmentData, $sheetName);
  946. }
  947. }
  948. $attempt++;
  949. continue;
  950. }
  951. // Intentar insertar
  952. return DB::table('S002V01TPCEQ')->insert($equipmentData);
  953. } catch(\Illuminate\Database\QueryException $e) {
  954. // Si es error de clave duplicada, regenerar ID
  955. if($e->getCode() == 23000 || strpos($e->getMessage(), 'Duplicate entry') !== false) {
  956. $equipmentData['PCEQ_IDPR'] = $this->generateNumericUniqueId($equipmentData['PCEQ_NULI']);
  957. $attempt++;
  958. continue;
  959. }
  960. // Si es otro tipo de error, re-lanzar
  961. throw $e;
  962. }
  963. }
  964. throw new Exception("No se pudo insertar el registro después de $maxAttempts intentos");
  965. }
  966. // MÉTODO AUXILIAR: Obtener nombre de hoja basado en tipo de código
  967. private function getSheetNameFromCodeType($codeType) {
  968. $codeTypes = [
  969. '1' => 'CASO 1',
  970. '2' => 'CASO 2',
  971. '3' => 'CASO 3',
  972. '4' => 'CASO 4',
  973. '5' => 'CASO 5',
  974. '6' => 'CASO 6'
  975. ];
  976. return $codeTypes[$codeType] ?? null;
  977. }
  978. // SOLUCIÓN 3: Usar upsert (insertar o actualizar)
  979. private function upsertEquipmentData($equipmentData) {
  980. return DB::table('S002V01TPCEQ')->updateOrInsert(
  981. [
  982. 'PCEQ_NULI' => $equipmentData['PCEQ_NULI'],
  983. 'PCEQ_TICO' => $equipmentData['PCEQ_TICO'],
  984. 'PCEQ_IDPR' => $equipmentData['PCEQ_IDPR']
  985. ],
  986. $equipmentData
  987. );
  988. }
  989. // MÉTODO MODIFICADO PARA PROCESAR WORKSHEET CON MANEJO DE DUPLICADOS
  990. private function processWorksheet($worksheet, $sheetConfig, $sheetName, $linea, $idUser, $cargaMap, $lruMap) {
  991. $processedData = [];
  992. $errors = [];
  993. $count = 0;
  994. $highestRow = $worksheet->getHighestRow();
  995. $startRow = $sheetConfig['date_start_row'];
  996. $fieldMapping = $sheetConfig['field_mapping'];
  997. // Obtener todos los equipos de CARGA y LRU para búsqueda
  998. $cargaEquipments = $this->getAllCargaEquipments($worksheet->getParent());
  999. $lruEquipments = $this->getAllLruEquipments($worksheet->getParent());
  1000. for($row = $startRow; $row <= $highestRow; $row++) {
  1001. $rowData = $this->extractRowData($worksheet, $row, $fieldMapping, $sheetName);
  1002. if($this->isEmptyRow($rowData)) {
  1003. continue;
  1004. }
  1005. $this->replaceAcronyms($rowData, $sheetName, $cargaMap, $lruMap);
  1006. $validation = $this->validateRowData($rowData, $sheetName, $row);
  1007. if(!$validation['valid']) {
  1008. $errors[] = "Hoja: $sheetName, Fila: $row - " . implode(', ', $validation['errors']);
  1009. continue;
  1010. }
  1011. // Determinar si es equipo padre o hijo
  1012. $isHijo = !empty($rowData['PCEQ_TIEQ_HIJO']) || !empty($rowData['PCEQ_MOEQ_HIJO']);
  1013. // Buscar equipo completo en CARGA o LRU
  1014. $fullEquipment = null;
  1015. if($isHijo) {
  1016. // Buscar en LRU por tipo y modelo hijo
  1017. $fullEquipment = $this->findEquipment(
  1018. $lruEquipments,
  1019. $rowData['PCEQ_TIEQ_HIJO'] ?? '',
  1020. $rowData['PCEQ_MOEQ_HIJO'] ?? ''
  1021. );
  1022. } else {
  1023. // Buscar en CARGA por tipo y modelo padre
  1024. $fullEquipment = $this->findEquipment(
  1025. $cargaEquipments,
  1026. $rowData['PCEQ_TIEQ'] ?? '',
  1027. $rowData['PCEQ_MOEQ'] ?? ''
  1028. );
  1029. }
  1030. // Combinar datos del caso con datos del equipo completo
  1031. if($fullEquipment) {
  1032. $rowData = array_merge($rowData, $fullEquipment);
  1033. }
  1034. $equipmentData = $this->prepareEquipmentData($rowData, $linea, $idUser, $sheetName);
  1035. $processedData[] = $equipmentData;
  1036. $count++;
  1037. }
  1038. return [
  1039. 'data' => $processedData,
  1040. 'errors' => $errors,
  1041. 'count' => $count
  1042. ];
  1043. }
  1044. // Obtener todos los equipos de CARGA DE EQUIPOS
  1045. private function getAllCargaEquipments($spreadsheet) {
  1046. $equipments = [];
  1047. $sheet = $spreadsheet->getSheetByName('CARGA DE EQUIPOS');
  1048. if(!$sheet) return $equipments;
  1049. $highestRow = $sheet->getHighestRow();
  1050. $config = ExcelTemplateConfig::getTemplateConfigs()['TPCEQ']['worksheets']['CARGA DE EQUIPOS'];
  1051. $startRow = $config['date_start_row'];
  1052. for($row = $startRow; $row <= $highestRow; $row++) {
  1053. $equipment = $this->extractRowData($sheet, $row, $config['field_mapping'], 'CARGA DE EQUIPOS');
  1054. if(!$this->isEmptyRow($equipment)) {
  1055. $equipments[] = $equipment;
  1056. }
  1057. }
  1058. return $equipments;
  1059. }
  1060. // Obtener todos los equipos de LRU
  1061. private function getAllLruEquipments($spreadsheet) {
  1062. $equipments = [];
  1063. $sheet = $spreadsheet->getSheetByName('LRU');
  1064. if(!$sheet) return $equipments;
  1065. $highestRow = $sheet->getHighestRow();
  1066. $config = ExcelTemplateConfig::getTemplateConfigs()['TPCEQ']['worksheets']['LRU'];
  1067. $startRow = $config['date_start_row'];
  1068. for($row = $startRow; $row <= $highestRow; $row++) {
  1069. $equipment = $this->extractRowData($sheet, $row, $config['field_mapping'], 'LRU');
  1070. if(!$this->isEmptyRow($equipment)) {
  1071. $equipments[] = $equipment;
  1072. }
  1073. }
  1074. return $equipments;
  1075. }
  1076. // Buscar equipo por tipo y modelo
  1077. private function findEquipment($equipments, $tipo, $modelo) {
  1078. $normalize = function($value) {
  1079. return trim(strtoupper($value));
  1080. };
  1081. $tipo = $normalize($tipo);
  1082. $modelo = $normalize($modelo);
  1083. foreach($equipments as $equipment) {
  1084. $eqTipo = $normalize($equipment['PCEQ_TIEQ'] ?? '');
  1085. $eqModelo = $normalize($equipment['PCEQ_MOEQ'] ?? '');
  1086. if($eqTipo === $tipo && $eqModelo === $modelo) {
  1087. return $equipment;
  1088. }
  1089. }
  1090. return null;
  1091. }
  1092. private function replaceAcronyms(&$rowData, $sheetName, $cargaMap, $lruMap) {
  1093. // Solo aplica para hojas de casos
  1094. if (!in_array($sheetName, ['CASO 1','CASO 2','CASO 3','CASO 4','CASO 5','CASO 6'])) {
  1095. return;
  1096. }
  1097. // Reemplazar acrónimo padre (de CARGA DE EQUIPOS)
  1098. if (isset($rowData['PCEQ_TIEQ'])) {
  1099. $acronym = trim($rowData['PCEQ_TIEQ']);
  1100. if (isset($cargaMap['equipos'][$acronym])) {
  1101. $rowData['PCEQ_TIEQ'] = $cargaMap['equipos'][$acronym];
  1102. }
  1103. }
  1104. // Reemplazar acrónimo hijo (de LRU)
  1105. if (isset($rowData['PCEQ_TIEQ_HIJO'])) {
  1106. $acronym = trim($rowData['PCEQ_TIEQ_HIJO']);
  1107. if (isset($lruMap['equipos'][$acronym])) {
  1108. $rowData['PCEQ_TIEQ_HIJO'] = $lruMap['equipos'][$acronym];
  1109. }
  1110. }
  1111. if (isset($rowData['PCEQ_MOEQ'])) {
  1112. $acronym = trim($rowData['PCEQ_MOEQ']);
  1113. if (isset($cargaMap['modelos'][$acronym])) {
  1114. $rowData['PCEQ_MOEQ'] = $cargaMap['modelos'][$acronym];
  1115. }
  1116. }
  1117. // NUEVO: Reemplazar acrónimo de modelo hijo (de LRU)
  1118. if (isset($rowData['PCEQ_MOEQ_HIJO'])) {
  1119. $acronym = trim($rowData['PCEQ_MOEQ_HIJO']);
  1120. if (isset($lruMap['modelos'][$acronym])) {
  1121. $rowData['PCEQ_MOEQ_HIJO'] = $lruMap['modelos'][$acronym];
  1122. }
  1123. }
  1124. }
  1125. // MÉTODO ALTERNATIVO: Limpiar datos duplicados antes del procesamiento
  1126. public function cleanDuplicateRecords(Request $request) {
  1127. $validator = Validator::make($request->all(), [
  1128. 'id_user' => 'required|string',
  1129. 'linea' => 'required|integer',
  1130. ]);
  1131. if($validator->fails()) {
  1132. return $this->responseController->makeResponse(
  1133. true,
  1134. "Se encontraron uno o más errores.",
  1135. $this->responseController->makeErrors($validator->errors()->messages()),
  1136. 401
  1137. );
  1138. }
  1139. $form = $request->all();
  1140. $idUser = $this->encryptionController->decrypt($form['id_user']);
  1141. if(!$idUser) {
  1142. return $this->responseController->makeResponse(true, "El id del usuario no fue desencriptado correctamente", [], 400);
  1143. }
  1144. try {
  1145. DB::beginTransaction();
  1146. // Eliminar registros duplicados manteniendo solo el más reciente
  1147. $duplicatesDeleted = DB::statement("
  1148. DELETE p1 FROM S002V01TPCEQ p1
  1149. INNER JOIN S002V01TPCEQ p2
  1150. WHERE p1.PCEQ_NULI = p2.PCEQ_NULI
  1151. AND p1.PCEQ_TICO = p2.PCEQ_TICO
  1152. AND p1.PCEQ_IDPR = p2.PCEQ_IDPR
  1153. AND p1.PCEQ_FERE < p2.PCEQ_FERE
  1154. AND p1.PCEQ_NULI = ?
  1155. ", [$form['linea']]);
  1156. DB::commit();
  1157. return $this->responseController->makeResponse(false, "Duplicados eliminados exitosamente", [
  1158. 'linea' => $form['linea'],
  1159. 'duplicados_eliminados' => $duplicatesDeleted
  1160. ]);
  1161. } catch(Exception $e) {
  1162. DB::rollBack();
  1163. return $this->responseController->makeResponse(true, "Error al limpiar duplicados: " . $e->getMessage(), [], 500);
  1164. }
  1165. }
  1166. private function getCodeTypeFromSheet($sheetName) {
  1167. $codeTypes = [
  1168. 'CASO 1' => '1',
  1169. 'CASO 2' => '2',
  1170. 'CASO 3' => '3',
  1171. 'CASO 4' => '4',
  1172. 'CASO 5' => '5',
  1173. 'CASO 6' => '6',
  1174. ];
  1175. return $codeTypes[$sheetName] ?? '1';
  1176. }
  1177. private function addSheetSpecificFields(&$equipmentData, $rowData, $sheetName) {
  1178. switch($sheetName) {
  1179. case 'CASO 1':
  1180. case 'CASO 2':
  1181. $equipmentData['PCEQ_UBOR'] = $rowData['PCEQ_UBOR'] ?? '';
  1182. $equipmentData['PCEQ_NIOR'] = $rowData['PCEQ_NIOR'] ?? '';
  1183. $equipmentData['PCEQ_OCOR'] = $rowData['PCEQ_OCOR'] ?? '';
  1184. $equipmentData['PCEQ_ELOR'] = $rowData['PCEQ_ELOR'] ?? '';
  1185. $equipmentData['PCEQ_COOR'] = $rowData['PCEQ_COOR'] ?? '';
  1186. $equipmentData['PCEQ_FAMI'] = $rowData['PCEQ_FAMI'] ?? '';
  1187. $equipmentData['PCEQ_SUBF'] = $rowData['PCEQ_SUBF'] ?? '';
  1188. if(isset($rowData['PCEQ_CPGE'])) {
  1189. $equipmentData['PCEQ_CPGE'] = $rowData['PCEQ_CPGE'];
  1190. }
  1191. break;
  1192. case 'CASO 3':
  1193. $equipmentData['PCEQ_UBOR'] = $rowData['PCEQ_UBOR'] ?? '';
  1194. $equipmentData['PCEQ_UBDE'] = $rowData['PCEQ_UBDE'] ?? '';
  1195. if(isset($rowData['PCEQ_IDPR'])) {
  1196. $equipmentData['PCEQ_IDPR'] = $rowData['PCEQ_IDPR'];
  1197. }
  1198. if(isset($rowData['PCEQ_CPGE'])) {
  1199. $equipmentData['PCEQ_CPGE'] = $rowData['PCEQ_CPGE'];
  1200. }
  1201. break;
  1202. case 'CASO 4':
  1203. $equipmentData['PCEQ_UBOR'] = $rowData['PCEQ_UBOR'] ?? '';
  1204. $equipmentData['PCEQ_UBDE'] = $rowData['PCEQ_UBDE'] ?? '';
  1205. $equipmentData['PCEQ_SEOR'] = $rowData['PCEQ_SEOR'] ?? 0;
  1206. $equipmentData['PCEQ_SEDE'] = $rowData['PCEQ_SEDE'] ?? 0;
  1207. $equipmentData['PCEQ_COOR'] = $rowData['PCEQ_COOR_ORIGEN'] ?? '';
  1208. $equipmentData['PCEQ_CODE'] = $rowData['PCEQ_COOR_DESTINO'] ?? '';
  1209. if(isset($rowData['PCEQ_IDPR'])) {
  1210. $equipmentData['PCEQ_IDPR'] = $rowData['PCEQ_IDPR'];
  1211. }
  1212. if(isset($rowData['PCEQ_CPGE'])) {
  1213. $equipmentData['PCEQ_CPGE'] = $rowData['PCEQ_CPGE'];
  1214. }
  1215. break;
  1216. case 'CASO 5':
  1217. case 'CASO 6':
  1218. $equipmentData['PCEQ_UBOR'] = $rowData['PCEQ_UBOR'] ?? '';
  1219. $equipmentData['PCEQ_NIOR'] = $rowData['PCEQ_NIOR'] ?? '';
  1220. $equipmentData['PCEQ_OCOR'] = $rowData['PCEQ_OCOR'] ?? '';
  1221. $equipmentData['PCEQ_ARTR'] = $rowData['PCEQ_ARTR'] ?? '';
  1222. $equipmentData['PCEQ_ELOR'] = $rowData['PCEQ_ELOR'] ?? '';
  1223. if(isset($rowData['PCEQ_IDPR'])) {
  1224. $equipmentData['PCEQ_IDPR'] = $rowData['PCEQ_IDPR'];
  1225. }
  1226. if(isset($rowData['PCEQ_CPGE'])) {
  1227. $equipmentData['PCEQ_CPGE'] = $rowData['PCEQ_CPGE'];
  1228. }
  1229. break;
  1230. }
  1231. }
  1232. // Método para obtener equipos en revisión
  1233. public function getPendingEquipments(Request $request) {
  1234. $validator = Validator::make($request->all(), [
  1235. 'id_user' => 'required|string',
  1236. 'linea' => 'required|integer',
  1237. ]);
  1238. if($validator->fails()) {
  1239. return $this->responseController->makeResponse(
  1240. true,
  1241. "Se encontraron uno o más errores.",
  1242. $this->responseController->makeErrors($validator->errors()->messages()),
  1243. 401
  1244. );
  1245. }
  1246. $form = $request->all();
  1247. $idUser = $this->encryptionController->decrypt($form['id_user']);
  1248. if(!$idUser) {
  1249. return $this->responseController->makeResponse(true, "El id del usuario no fue desencriptado correctamente", [], 400);
  1250. }
  1251. $pendingEquipments = DB::table('S002V01TPCEQ')
  1252. ->where('PCEQ_NULI', $form['linea'])
  1253. ->where('PCEQ_ESRE', 'Revisión')
  1254. ->orderBy('PCEQ_FERE', 'desc')
  1255. ->get();
  1256. $equipmentsArray = [];
  1257. foreach($pendingEquipments as $equipment) {
  1258. $equipmentsArray[] = [
  1259. 'id' => $this->encryptionController->encrypt($equipment->PCEQ_IDPR),
  1260. 'codigo' => $equipment->PCEQ_CPGE,
  1261. 'tipo' => $equipment->PCEQ_TIEQ,
  1262. 'modelo' => $equipment->PCEQ_MOEQ,
  1263. 'familia' => $equipment->PCEQ_FAMI,
  1264. 'subfamilia' => $equipment->PCEQ_SUBF,
  1265. 'estado' => $equipment->PCEQ_ESEQ,
  1266. 'fecha_registro' => $equipment->PCEQ_FERE,
  1267. 'estado_revision' => $equipment->PCEQ_ESRE
  1268. ];
  1269. }
  1270. return $this->responseController->makeResponse(false, 'EXITO.', $equipmentsArray);
  1271. }
  1272. /**
  1273. * Método para aprobar equipamientos desde la tabla temporal hacia la tabla final
  1274. */
  1275. public function approveEquipments(Request $request) {
  1276. DB::enableQueryLog();
  1277. $validator = Validator::make($request->all(), [
  1278. 'id_user' => 'required|string',
  1279. 'linea' => 'required|integer',
  1280. 'equipment_ids' => 'required|array',
  1281. 'equipment_ids.*' => 'required|string'
  1282. ]);
  1283. if($validator->fails()) {
  1284. return $this->responseController->makeResponse(
  1285. true,
  1286. "Se encontraron uno o más errores.",
  1287. $this->responseController->makeErrors($validator->errors()->messages()),
  1288. 401
  1289. );
  1290. }
  1291. $form = $request->all();
  1292. $idUser = $this->encryptionController->decrypt($form['id_user']);
  1293. if(!$idUser) {
  1294. return $this->responseController->makeResponse(true, "El id del usuario no fue desencriptado correctamente", [], 400);
  1295. }
  1296. $usr = DB::table('S002V01TUSUA')->where([
  1297. ['USUA_IDUS', '=', $idUser],
  1298. ['USUA_NULI', '=', $form['linea']]
  1299. ])->first();
  1300. if(is_null($usr)) {
  1301. return $this->responseController->makeResponse(true, 'El usuario no está registrado', [], 404);
  1302. }
  1303. try {
  1304. DB::beginTransaction();
  1305. $approvedCount = 0;
  1306. $errors = [];
  1307. foreach($form['equipment_ids'] as $encryptedId) {
  1308. $equipmentId = $this->encryptionController->decrypt($encryptedId);
  1309. if(!$equipmentId) {
  1310. $errors[] = "ID de equipamiento inválido: $encryptedId";
  1311. continue;
  1312. }
  1313. // Obtener equipamiento temporal
  1314. $tempEquipment = DB::table('S002V01TPCEQ')
  1315. ->where('PCEQ_IDPR', $equipmentId)
  1316. ->where('PCEQ_NULI', $form['linea'])
  1317. ->where('PCEQ_ESRE', 'Revisión')
  1318. ->first();
  1319. if(!$tempEquipment) {
  1320. $errors[] = "Equipamiento no encontrado o ya procesado: $equipmentId";
  1321. continue;
  1322. }
  1323. // Mover a tabla final de equipamientos
  1324. $finalEquipmentData = $this->prepareFinalEquipmentData($tempEquipment, $idUser);
  1325. $finalEquipmentId = DB::table('S002V01TEQUI')->insertGetId($finalEquipmentData);
  1326. // Actualizar estado en tabla temporal
  1327. DB::table('S002V01TPCEQ')
  1328. ->where('PCEQ_IDPR', $equipmentId)
  1329. ->update([
  1330. 'PCEQ_ESRE' => 'Aprobado',
  1331. 'PCEQ_USAP' => $idUser,
  1332. 'PCEQ_FEAP' => Carbon::now('America/Mexico_city')->toDateTimeString()
  1333. ]);
  1334. $approvedCount++;
  1335. }
  1336. if($approvedCount === 0) {
  1337. DB::rollBack();
  1338. return $this->responseController->makeResponse(true, "No se pudo aprobar ningún equipamiento: " . implode('; ', $errors), [], 400);
  1339. }
  1340. DB::commit();
  1341. // Registrar actividad
  1342. $nowStr = Carbon::now('America/Mexico_city')->toDateTimeString();
  1343. $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
  1344. $actions = DB::getQueryLog();
  1345. $idac = $this->functionsController->registerActivity(
  1346. $form['linea'],
  1347. 'S002V01M07GEEQ',
  1348. 'S002V01F01ADEQ',
  1349. 'S002V01P11REEQ',
  1350. 'Aprobación',
  1351. "El usuario $name (" . $usr->USUA_IDUS . ") aprobó $approvedCount equipamientos.",
  1352. $idUser,
  1353. $nowStr,
  1354. );
  1355. $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']);
  1356. $responseData = [
  1357. 'equipos_aprobados' => $approvedCount,
  1358. 'total_procesados' => count($form['equipment_ids'])
  1359. ];
  1360. if(!empty($errors)) {
  1361. $responseData['errores'] = $errors;
  1362. }
  1363. return $this->responseController->makeResponse(false, "Aprobación exitosa", $responseData);
  1364. } catch(Exception $e) {
  1365. DB::rollBack();
  1366. return $this->responseController->makeResponse(true, "Error al aprobar equipamientos: " . $e->getMessage(), [], 500);
  1367. }
  1368. }
  1369. private function prepareFinalEquipmentData($tempEquipment, $approvingUserId) {
  1370. $nowStr = Carbon::now('America/Mexico_city')->toDateTimeString();
  1371. return [
  1372. 'EQUI_NULI' => $tempEquipment->PCEQ_NULI,
  1373. 'EQUI_COEQ' => $tempEquipment->PCEQ_CPGE,
  1374. 'EQUI_JERA' => $tempEquipment->PCEQ_JERA,
  1375. 'EQUI_EQPA' => $tempEquipment->PCEQ_EQPA,
  1376. 'EQUI_TICO' => $tempEquipment->PCEQ_TICO,
  1377. 'EQUI_UBOR' => $tempEquipment->PCEQ_UBOR,
  1378. 'EQUI_NIOR' => $tempEquipment->PCEQ_NIOR,
  1379. 'EQUI_OCOR' => $tempEquipment->PCEQ_OCOR,
  1380. 'EQUI_ELOR' => $tempEquipment->PCEQ_ELOR,
  1381. 'EQUI_FAMI' => $tempEquipment->PCEQ_FAMI,
  1382. 'EQUI_SUBF' => $tempEquipment->PCEQ_SUBF,
  1383. 'EQUI_ESEQ' => $tempEquipment->PCEQ_ESEQ,
  1384. 'EQUI_TIEQ' => $tempEquipment->PCEQ_TIEQ,
  1385. 'EQUI_MOEQ' => $tempEquipment->PCEQ_MOEQ,
  1386. 'EQUI_FEAD' => $tempEquipment->PCEQ_FEAD,
  1387. 'EQUI_FIGA' => $tempEquipment->PCEQ_FIGA,
  1388. 'EQUI_FTGA' => $tempEquipment->PCEQ_FTGA,
  1389. 'EQUI_PREQ' => $tempEquipment->PCEQ_PREQ,
  1390. 'EQUI_NUSE' => $tempEquipment->PCEQ_NUSE,
  1391. 'EQUI_GAIM' => $tempEquipment->PCEQ_GAIM,
  1392. 'EQUI_DORE' => $tempEquipment->PCEQ_DORE,
  1393. 'EQUI_USRE' => $approvingUserId,
  1394. 'EQUI_FERE' => $nowStr,
  1395. // Campos adicionales según el tipo de equipamiento
  1396. 'EQUI_UBDE' => $tempEquipment->PCEQ_UBDE ?? null,
  1397. 'EQUI_NIDE' => $tempEquipment->PCEQ_NIDE ?? null,
  1398. 'EQUI_OCDE' => $tempEquipment->PCEQ_OCDE ?? null,
  1399. 'EQUI_ELDE' => $tempEquipment->PCEQ_ELDE ?? null,
  1400. 'EQUI_COOR' => $tempEquipment->PCEQ_COOR ?? null,
  1401. 'EQUI_SEOR' => $tempEquipment->PCEQ_SEOR ?? null,
  1402. 'EQUI_SEDE' => $tempEquipment->PCEQ_SEDE ?? null,
  1403. 'EQUI_ARTR' => $tempEquipment->PCEQ_ARTR ?? null,
  1404. ];
  1405. }
  1406. /**
  1407. * Método para rechazar equipamientos
  1408. */
  1409. public function rejectEquipments(Request $request) {
  1410. $validator = Validator::make($request->all(), [
  1411. 'id_user' => 'required|string',
  1412. 'linea' => 'required|integer',
  1413. 'equipment_ids' => 'required|array',
  1414. 'equipment_ids.*' => 'required|string',
  1415. 'rejection_reason' => 'required|string'
  1416. ]);
  1417. if($validator->fails()) {
  1418. return $this->responseController->makeResponse(
  1419. true,
  1420. "Se encontraron uno o más errores.",
  1421. $this->responseController->makeErrors($validator->errors()->messages()),
  1422. 401
  1423. );
  1424. }
  1425. $form = $request->all();
  1426. $idUser = $this->encryptionController->decrypt($form['id_user']);
  1427. if(!$idUser) {
  1428. return $this->responseController->makeResponse(true, "El id del usuario no fue desencriptado correctamente", [], 400);
  1429. }
  1430. try {
  1431. DB::beginTransaction();
  1432. $rejectedCount = 0;
  1433. foreach($form['equipment_ids'] as $encryptedId) {
  1434. $equipmentId = $this->encryptionController->decrypt($encryptedId);
  1435. if($equipmentId) {
  1436. DB::table('S002V01TPCEQ')
  1437. ->where('PCEQ_IDPR', $equipmentId)
  1438. ->where('PCEQ_NULI', $form['linea'])
  1439. ->update([
  1440. 'PCEQ_ESRE' => 'Rechazado',
  1441. 'PCEQ_MORE' => $form['rejection_reason'],
  1442. 'PCEQ_USRE' => $idUser,
  1443. 'PCEQ_FERE' => Carbon::now('America/Mexico_city')->toDateTimeString()
  1444. ]);
  1445. $rejectedCount++;
  1446. }
  1447. }
  1448. DB::commit();
  1449. return $this->responseController->makeResponse(false, "Equipamientos rechazados exitosamente", [
  1450. 'equipos_rechazados' => $rejectedCount
  1451. ]);
  1452. } catch(Exception $e) {
  1453. DB::rollBack();
  1454. return $this->responseController->makeResponse(true, "Error al rechazar equipamientos: " . $e->getMessage(), [], 500);
  1455. }
  1456. }
  1457. }
  1458. class ExcelTemplateConfig {
  1459. public static function getTemplateConfigs() {
  1460. return [
  1461. 'TPCEQ' => [
  1462. 'model' => 'S002V01TPCEQ',
  1463. 'worksheets' => [
  1464. 'EQUIPAMIENTO' => [
  1465. 'table_start' => 'B9',
  1466. 'table_end' => 'P9',
  1467. 'header_row' => 7,
  1468. 'date_start_row' => 9,
  1469. 'field_mapping' => [
  1470. 'A' => '',
  1471. 'B' => 'PCEQ_OTCO', // Código Equivalente
  1472. 'C' => 'PCEQ_TIEQ', // Tipo / Descripción
  1473. 'D' => '', // Acrónimo del equipo
  1474. 'E' => 'PCEQ_MOEQ', // Acrónimo del modelo
  1475. 'F' => '', // Acrónimo del modelo
  1476. 'G' => '', // Id
  1477. 'H' => 'PCEQ_NUSE', // No. código de barras
  1478. 'I' => 'PCEQ_COBA', // Carácter
  1479. 'J' => 'PCEQ_CARA', // Proveedor del equipamiento
  1480. 'K' => 'PCEQ_FVAR', // Fecha inicio de garantía
  1481. 'L' => '', // Fecha de vencimiento del artículo
  1482. ]
  1483. ],
  1484. 'LRU' => [
  1485. 'table_start' => 'B9',
  1486. 'table_end' => 'L9',
  1487. 'header_row' => 7,
  1488. 'date_start_row' => 9,
  1489. 'field_mapping' => [
  1490. 'A' => '',
  1491. 'B' => 'PCEQ_TIEQ', // Tipo / Descripción
  1492. 'C' => '', // Acrónimo del equipo
  1493. 'D' => 'PCEQ_MOEQ', // Modelo completo
  1494. 'E' => '', // Acrónimo del modelo
  1495. 'F' => '', // Id
  1496. 'G' => 'PCEQ_NUSE', // No. serie
  1497. 'H' => 'PCEQ_COBA', // No. código de barras
  1498. 'I' => 'PCEQ_CARA', // Carácter
  1499. 'J' => 'PCEQ_FTGA', // Fecha de vencimiento del artículo
  1500. 'K' => '', // Etiqueta final del equipo
  1501. 'L' => '', // Código equivalente
  1502. ]
  1503. ],
  1504. 'CASO 1' => [
  1505. 'table_start' => 'B8',
  1506. 'table_end' => 'AI8',
  1507. 'header_row' => 7,
  1508. 'date_start_row' => 8,
  1509. 'field_mapping' => [
  1510. 'A' => '',
  1511. 'B' => 'PCEQ_NULI', // Línea
  1512. 'C' => '.', // .
  1513. 'D' => 'PCEQ_UBOR', // Ubicación
  1514. 'E' => '.', // .
  1515. 'F' => 'PCEQ_NIOR', // Nivel
  1516. 'G' => '.', // .
  1517. 'H' => 'PCEQ_OCOR', // Ocupación
  1518. 'I' => '.', // .
  1519. 'J' => 'PCEQ_ELOR', // Elemento
  1520. 'K' => '+', // +
  1521. 'L' => '', // Coordenadas plano
  1522. 'M' => '', // Coordenadas detalle
  1523. 'N' => '', // Coordenadas de posición
  1524. 'O' => '_', // _
  1525. 'P' => 'PCEQ_FAMI', // Familia
  1526. 'Q' => '.', // .
  1527. 'R' => 'PCEQ_SUBF', // Subfamilia
  1528. 'S' => '.', // .
  1529. 'T' => 'PCEQ_ESEQ', // Estado
  1530. 'U' => '.', // .
  1531. 'V' => 'PCEQ_TIEQ', // Tipo
  1532. 'W' => '-', // -
  1533. 'X' => 'PCEQ_MOEQ', // Modelo
  1534. 'Y' => '-', // -
  1535. 'Z' => '', // ID
  1536. 'AA' => '.', // .
  1537. 'AB' => 'PCEQ_TIEQ_HIJO', // Tipo
  1538. 'AC' => '-', // -
  1539. 'AD' => 'PCEQ_MOEQ_HIJO', // Modelo
  1540. 'AE' => '-', // -
  1541. 'AF' => '', // ID
  1542. 'AG' => '', // Vacío
  1543. 'AH' => 'PCEQ_CPGE', // Código completo SAM
  1544. 'AI' => 'PCEQ_OTCO', // Código equivalente
  1545. ]
  1546. ],
  1547. 'CASO 2' => [
  1548. 'table_start' => 'B8',
  1549. 'table_end' => 'AI8',
  1550. 'header_row' => 7,
  1551. 'date_start_row' => 8,
  1552. 'field_mapping' => [
  1553. 'A' => '',
  1554. 'B' => 'PCEQ_NULI', // Línea
  1555. 'C' => '.', // .
  1556. 'D' => 'PCEQ_UBOR', // Ubicación
  1557. 'E' => '.', // .
  1558. 'F' => 'PCEQ_NIOR', // Nivel
  1559. 'G' => '.', // .
  1560. 'H' => 'PCEQ_OCOR', // Ocupación
  1561. 'I' => '.', // .
  1562. 'J' => 'PCEQ_ELOR', // Elemento
  1563. 'K' => '+', // +
  1564. 'L' => '', // Coordenadas plano
  1565. 'M' => '', // Coordenadas detalle
  1566. 'N' => '', // Coordenadas de posición
  1567. 'O' => '_', // _
  1568. 'P' => 'PCEQ_FAMI', // Familia
  1569. 'Q' => '.', // .
  1570. 'R' => 'PCEQ_SUBF', // Subfamilia
  1571. 'S' => '.', // .
  1572. 'T' => 'PCEQ_ESEQ', // Estado
  1573. 'U' => '.', // .
  1574. 'V' => 'PCEQ_TIEQ', // Tipo
  1575. 'W' => '-', // -
  1576. 'X' => 'PCEQ_MOEQ', // Modelo
  1577. 'Y' => '-', // -
  1578. 'Z' => '', // ID
  1579. 'AA' => '.', // .
  1580. 'AB' => 'PCEQ_TIEQ_HIJO', // Tipo
  1581. 'AC' => '-', // -
  1582. 'AD' => 'PCEQ_MOEQ_HIJO', // Modelo
  1583. 'AE' => '-', // -
  1584. 'AF' => '', // ID
  1585. 'AG' => '', // Vacío
  1586. 'AH' => 'PCEQ_CPGE', // Código completo SAM
  1587. 'AI' => 'PCEQ_OTCO', // Código equivalente
  1588. ]
  1589. ],
  1590. 'CASO 3' => [
  1591. 'table_start' => 'B8',
  1592. 'table_end' => 'AQ8',
  1593. 'header_row' => 7,
  1594. 'date_start_row' => 8,
  1595. 'field_mapping' => [
  1596. 'A' => '',
  1597. 'B' => 'PCEQ_NULI', // Línea
  1598. 'C' => '.', // .
  1599. 'D' => 'PCEQ_UBOR', // Ubicación origen
  1600. 'E' => '.', // .
  1601. 'F' => 'PCEQ_NIOR', // Nivel origen
  1602. 'G' => '.', // .
  1603. 'H' => 'PCEQ_OCOR', // Ocupación origen
  1604. 'I' => '.', // .
  1605. 'J' => 'PCEQ_ELOR', // Elemento origen
  1606. 'K' => '.', // .
  1607. 'L' => 'PCEQ_KIOR', // PK origen
  1608. 'M' => ':', // :
  1609. 'N' => 'PCEQ_UBDE', // Ubicación destino
  1610. 'O' => '.', // .
  1611. 'P' => 'PCEQ_NIDE', // Nivel destino
  1612. 'Q' => '.', // .
  1613. 'R' => 'PCEQ_OCDE', // Ocupación destino
  1614. 'S' => '.', // .
  1615. 'T' => 'PCEQ_ELDE', // Elemento destino
  1616. 'U' => '.', // .
  1617. 'V' => 'PCEQ_KIDE', // PK destino
  1618. 'W' => '-', // -
  1619. 'X' => 'PCEQ_FAMI', // Familia
  1620. 'Y' => '-', // -
  1621. 'Z' => 'PCEQ_SUBF', // Subfamilia
  1622. 'AA' => '.', // .
  1623. 'AB' => 'PCEQ_ESEQ', // Estado
  1624. 'AC' => '-', // -
  1625. 'AD' => 'PCEQ_TIEQ', // Tipo
  1626. 'AE' => '-', // -
  1627. 'AF' => 'PCEQ_MOEQ', // Modelo
  1628. 'AG' => '-', // -
  1629. 'AH' => '', // ID
  1630. 'AI' => '.', // .
  1631. 'AJ' => 'PCEQ_TIEQ_HIJO', // Tipo
  1632. 'AK' => '-', // -
  1633. 'AL' => 'PCEQ_MOEQ_HIJO', // Modelo
  1634. 'AM' => '-', // -
  1635. 'AN' => 'PCEQ_IDPR', // ID
  1636. 'AO' => '-', // -
  1637. 'AP' => 'PCEQ_CPGE', // Código completo
  1638. 'AQ' => 'PCEQ_OTCO', // Código equivalente
  1639. ]
  1640. ],
  1641. 'CASO 4' => [
  1642. 'table_start' => 'B8',
  1643. 'table_end' => 'AY8',
  1644. 'header_row' => 7,
  1645. 'date_start_row' => 8,
  1646. 'field_mapping' => [
  1647. 'A' => '',
  1648. 'B' => 'PCEQ_NULI', // Línea
  1649. 'C' => '.', // .
  1650. 'D' => 'PCEQ_UBOR', // Ubicación origen
  1651. 'E' => '.', // .
  1652. 'F' => 'PCEQ_NIOR', // Nivel origen
  1653. 'G' => '.', // .
  1654. 'H' => 'PCEQ_OCOR', // Ocupación origen
  1655. 'I' => '.', // .
  1656. 'J' => 'PCEQ_ELOR', // Elemento origen
  1657. 'K' => '.', // .
  1658. 'L' => 'PCEQ_SEOR', // Secuencial origen
  1659. 'M' => '.', // .
  1660. 'N' => '', // Coordenadas plano (concatenar con O,P)
  1661. 'O' => '', // Coordenadas detalle
  1662. 'P' => '', // Coordenadas de posición
  1663. 'Q' => ':', // :
  1664. 'R' => 'PCEQ_UBDE', // Ubicación destino
  1665. 'S' => '.', // .
  1666. 'T' => 'PCEQ_NIDE', // Nivel destino
  1667. 'U' => '.', // .
  1668. 'V' => 'PCEQ_OCDE', // Ocupación destino
  1669. 'W' => '.', // .
  1670. 'X' => 'PCEQ_ELDE', // Elemento destino
  1671. 'Y' => '.', // .
  1672. 'Z' => 'PCEQ_SEDE', // Secuencial destino
  1673. 'AA' => '+', // +
  1674. 'AB' => '', // Coordenadas plano (concatenar con AC,AD)
  1675. 'AC' => '', // Coordenadas detalle
  1676. 'AD' => '', // Coordenadas de posición
  1677. 'AE' => '_', // _
  1678. 'AF' => 'PCEQ_FAMI', // Familia
  1679. 'AG' => '.', // .
  1680. 'AH' => 'PCEQ_SUBF', // Subfamilia
  1681. 'AI' => '.', // .
  1682. 'AJ' => 'PCEQ_ESEQ', // Estado
  1683. 'AK' => '.', // .
  1684. 'AL' => 'PCEQ_TIEQ', // Tipo
  1685. 'AM' => '-', // -
  1686. 'AN' => 'PCEQ_MOEQ', // Modelo
  1687. 'AO' => '-', // -
  1688. 'AP' => '', // ID
  1689. 'AQ' => '.', // .
  1690. 'AR' => 'PCEQ_TIEQ_HIJO', // Tipo
  1691. 'AS' => '-', // -
  1692. 'AT' => 'PCEQ_MOEQ_HIJO', // Modelo
  1693. 'AU' => '-', // -
  1694. 'AV' => '', // ID
  1695. 'AW' => '', // Vacío
  1696. 'AX' => 'PCEQ_CPGE', // Código completo
  1697. 'AY' => 'PCEQ_OTCO', // Código equivalente
  1698. ]
  1699. ],
  1700. 'CASO 5' => [
  1701. 'table_start' => 'B8',
  1702. 'table_end' => 'AG8',
  1703. 'header_row' => 7,
  1704. 'date_start_row' => 8,
  1705. 'field_mapping' => [
  1706. 'A' => '',
  1707. 'B' => 'PCEQ_NULI', // Línea
  1708. 'C' => '.', // .
  1709. 'D' => 'PCEQ_UBOR', // Ubicación
  1710. 'E' => '.', // .
  1711. 'F' => 'PCEQ_NIOR', // Nivel
  1712. 'G' => '.', // .
  1713. 'H' => 'PCEQ_OCOR', // Ocupación
  1714. 'I' => '.', // .
  1715. 'J' => 'PCEQ_ARTR', // Área
  1716. 'K' => '.', // .
  1717. 'L' => 'PCEQ_ELOR', // Elemento
  1718. 'M' => '_', // _
  1719. 'N' => 'PCEQ_FAMI', // Familia
  1720. 'O' => '.', // .
  1721. 'P' => 'PCEQ_SUBF', // Subfamilia
  1722. 'Q' => '.', // .
  1723. 'R' => 'PCEQ_ESEQ', // Estado
  1724. 'S' => '.', // .
  1725. 'T' => 'PCEQ_TIEQ', // Tipo
  1726. 'U' => '-', // -
  1727. 'V' => 'PCEQ_MOEQ', // Modelo
  1728. 'W' => '-', // -
  1729. 'X' => '', // ID
  1730. 'Y' => '.', // .
  1731. 'Z' => 'PCEQ_TIEQ_HIJO', // Tipo LRU
  1732. 'AA' => '-', // -
  1733. 'AB' => 'PCEQ_MOEQ_HIJO', // Modelo LRU
  1734. 'AC' => '-', // -
  1735. 'AD' => '', // ID LRU
  1736. 'AE' => '', // Vacío
  1737. 'AF' => 'PCEQ_CPGE', // Código completo
  1738. 'AG' => 'PCEQ_OTCO', // Código equivalente
  1739. ]
  1740. ],
  1741. 'CASO 6' => [
  1742. 'table_start' => '',
  1743. 'table_end' => '',
  1744. 'header_row' => 7,
  1745. 'date_start_row' => 8,
  1746. 'field_mapping' => [
  1747. 'A' => '', // Vacío
  1748. 'B' => 'PCEQ_NULI', // Linea
  1749. 'C' => '.', // .
  1750. 'D' => 'PCEQ_UBOR', // Ubicación
  1751. 'E' => '.', // .
  1752. 'F' => 'PCEQ_NIOR', // Nivel
  1753. 'G' => '.', // .
  1754. 'H' => 'PCEQ_OCOR', // Ocupación
  1755. 'I' => '.', // .
  1756. 'J' => 'PCEQ_ELOR', // Elemento
  1757. 'K' => '.', // .
  1758. 'L' => 'PCEQ_COOR', // Posición
  1759. 'M' => '_', // _
  1760. 'N' => 'PCEQ_FAMI', // Familia
  1761. 'O' => '.', // .
  1762. 'P' => 'PCEQ_SUBF', // Subfamilia
  1763. 'Q' => '.', // .
  1764. 'R' => 'PCEQ_ESEQ', // Estado
  1765. 'S' => '.', // .
  1766. 'T' => 'PCEQ_TIEQ', // Tipo
  1767. 'U' => '-', // -
  1768. 'V' => 'PCEQ_MOEQ', // Modelo
  1769. 'W' => '-', // -
  1770. 'X' => 'PCEQ_IDPR', // ID
  1771. 'Y' => '.', // .
  1772. 'Z' => 'PCEQ_TIEQ_HIJO', // Tipo
  1773. 'AA' => '-', // -
  1774. 'AB' => 'PCEQ_MOEQ_HIJO', // Modelo
  1775. 'AC' => '-', // -
  1776. 'AD' => 'PCEQ_LRID', // ID
  1777. 'AE' => '', // Vacío
  1778. 'AF' => 'PCEQ_CPGE', // Código completo
  1779. 'AG' => 'PCEQ_OTCO', // Código equivalente
  1780. ]
  1781. ]
  1782. ]
  1783. ],
  1784. ];
  1785. }
  1786. };