TemplatesManagementController.php 70 KB

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