TemplatesManagementController.php 93 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373
  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. 'auto_transfer' => 'boolean' // Nuevo parámetro opcional
  38. ]);
  39. if($validator->fails()){
  40. return $this->responseController->makeResponse(
  41. true,
  42. "Se encontraron uno o más errores.",
  43. $this->responseController->makeErrors($validator->errors()->messages()),
  44. 401
  45. );
  46. }
  47. $form = $request->all();
  48. $idUser = '0000000001'; // Usar ID fijo por ahora
  49. $autoTransfer = $form['auto_transfer'] ?? false; // Por defecto false
  50. if(!$idUser){
  51. return $this->responseController->makeResponse(true, "El id del usuario no fue desencriptado correctamente", [], 400);
  52. }
  53. $usr = DB::table('S002V01TUSUA')->where([
  54. ['USUA_IDUS', '=', $idUser],
  55. ['USUA_NULI', '=', $form['linea']]
  56. ])->first();
  57. if(is_null($usr)){
  58. return $this->responseController->makeResponse(true, 'El usuario no está registrado', [], 404);
  59. }
  60. // Obtener archivo temporal
  61. $fileIdDecrypted = $this->encryptionController->decrypt($form['id_file']);
  62. $tempFile = DB::table('S002V01TARTE')->where([
  63. ['ARTE_IDAR', '=', $fileIdDecrypted],
  64. ['ARTE_NULI', '=', $form['linea']]
  65. ])->first();
  66. if(is_null($tempFile)){
  67. return $this->responseController->makeResponse(true, 'El archivo temporal no fue encontrado', [], 404);
  68. }
  69. try {
  70. // **NUEVA VALIDACIÓN: Verificar que el frontend haya generado los códigos**
  71. error_log("🔍 [Validation] Verificando códigos generados por frontend...");
  72. $codeValidation = $this->validateFrontendCodes($tempFile->ARTE_UBTE);
  73. if(!$codeValidation['valid']) {
  74. error_log(" [Validation] Códigos del frontend faltantes: " . $codeValidation['message']);
  75. return $this->responseController->makeResponse(
  76. true,
  77. $codeValidation['message'],
  78. ['details' => $codeValidation['details']],
  79. 400
  80. );
  81. }
  82. error_log(" [Validation] Códigos del frontend validados correctamente");
  83. // Validar estructura del Excel
  84. $structureValidation = $this->validateExcelStructure($tempFile->ARTE_UBTE);
  85. if(!$structureValidation['valid']) {
  86. return $this->responseController->makeResponse(true, $structureValidation['message'], [], 400);
  87. }
  88. // Procesar contenido del Excel (AHORA usa códigos del frontend)
  89. $spreadsheet = IOFactory::load($tempFile->ARTE_UBTE);
  90. $config = ExcelTemplateConfig::getTemplateConfigs()['TPCEQ'];
  91. $acronymMappings = $this->extractAcronymMappings($spreadsheet);
  92. $cargaMap = $acronymMappings['carga'];
  93. $lruMap = $acronymMappings['lru'];
  94. $sheetsToProcess = [
  95. 'CASO 1', 'CASO 2', 'CASO 3',
  96. 'CASO 4', 'CASO 5', 'CASO 6'
  97. ];
  98. $processedData = [];
  99. $errors = [];
  100. $successCount = 0;
  101. DB::beginTransaction();
  102. foreach($sheetsToProcess as $sheetName) {
  103. if(!in_array($sheetName, $spreadsheet->getSheetNames())) {
  104. $errors[] = "Hoja requerida no encontrada: $sheetName";
  105. continue;
  106. }
  107. $sheetConfig = $config['worksheets'][$sheetName] ?? null;
  108. if(!$sheetConfig) {
  109. $errors[] = "Configuración no encontrada para hoja: $sheetName";
  110. continue;
  111. }
  112. $worksheet = $spreadsheet->getSheetByName($sheetName);
  113. $result = $this->processWorksheet(
  114. $worksheet,
  115. $sheetConfig,
  116. $sheetName,
  117. $form['linea'],
  118. $idUser,
  119. $cargaMap,
  120. $lruMap
  121. );
  122. $processedData = array_merge($processedData, $result['data']);
  123. $errors = array_merge($errors, $result['errors']);
  124. $successCount += $result['count'];
  125. }
  126. if(!empty($errors) && empty($processedData)) {
  127. DB::rollBack();
  128. return $this->responseController->makeResponse(true, "Errores en el procesamiento: " . implode('; ', array_slice($errors, 0, 5)), [], 400);
  129. }
  130. // **LOG FINAL: Verificar qué códigos se van a insertar**
  131. error_log("[Final Insert] Resumen de códigos a insertar:");
  132. foreach($processedData as $index => $data) {
  133. error_log(" [{$index}] PCEQ_CPGE: '" . $data['PCEQ_CPGE'] . "'");
  134. if($index >= 4) { // Mostrar solo los primeros 5
  135. error_log(" ... y " . (count($processedData) - 5) . " más");
  136. break;
  137. }
  138. }
  139. // Insertar datos procesados en la tabla temporal de equipamientos
  140. foreach($processedData as $data) {
  141. DB::table('S002V01TPCEQ')->insert($data);
  142. }
  143. // **NUEVA FUNCIONALIDAD: Transferencia automática a tabla final**
  144. $transferResult = null;
  145. if ($autoTransfer) {
  146. error_log(" [Auto Transfer] Iniciando transferencia automática a tabla final...");
  147. $transferResult = $this->transferEquipmentsToFinal($form['linea'], $idUser);
  148. if (!$transferResult['success']) {
  149. // Si falla la transferencia, hacer rollback completo
  150. DB::rollBack();
  151. return $this->responseController->makeResponse(
  152. true,
  153. "Error en transferencia automática: " . $transferResult['message'],
  154. [],
  155. 500
  156. );
  157. }
  158. error_log(" [Auto Transfer] Transferencia automática completada: {$transferResult['transferred_count']} equipos transferidos");
  159. }
  160. DB::commit();
  161. // Registrar actividad
  162. $nowStr = Carbon::now('America/Mexico_city')->toDateTimeString();
  163. $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
  164. $actions = DB::getQueryLog();
  165. $activityMessage = "El usuario $name (" . $usr->USUA_IDUS . ") procesó $successCount equipos desde el archivo {$tempFile->ARTE_NOAR} usando códigos generados por frontend.";
  166. if ($autoTransfer && $transferResult) {
  167. $activityMessage .= " Se transfirieron automáticamente {$transferResult['transferred_count']} equipos a la tabla final.";
  168. }
  169. $idac = $this->functionsController->registerActivity(
  170. $form['linea'],
  171. 'S002V01M07GEEQ',
  172. 'S002V01F01ADEQ',
  173. 'S002V01P11REEQ',
  174. 'Registro',
  175. $activityMessage,
  176. $idUser,
  177. $nowStr,
  178. );
  179. $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']);
  180. $responseData = [
  181. 'equipos_procesados' => $successCount,
  182. 'archivo' => $tempFile->ARTE_NOAR,
  183. 'id_archivo' => $form['id_file'],
  184. 'codigos_frontend_validados' => true
  185. ];
  186. // Agregar información de transferencia si se realizó
  187. if ($autoTransfer && $transferResult) {
  188. $responseData['transferencia_automatica'] = [
  189. 'realizada' => true,
  190. 'equipos_transferidos' => $transferResult['transferred_count'],
  191. 'total_equipos_temporales' => $transferResult['total_temp_equipments']
  192. ];
  193. if (!empty($transferResult['errors'])) {
  194. $responseData['transferencia_automatica']['errores'] = $transferResult['errors'];
  195. }
  196. }
  197. if(!empty($errors)) {
  198. $responseData['advertencias'] = array_slice($errors, 0, 10);
  199. }
  200. $successMessage = "Procesamiento exitoso usando códigos del frontend";
  201. if ($autoTransfer && $transferResult) {
  202. $successMessage .= " y transferencia automática completada";
  203. }
  204. error_log(" [Validation Complete] $successMessage");
  205. return $this->responseController->makeResponse(false, $successMessage, $responseData);
  206. } catch(Exception $e) {
  207. DB::rollBack();
  208. error_log(" [Validation Error] " . $e->getMessage());
  209. return $this->responseController->makeResponse(true, "Error al procesar el archivo: " . $e->getMessage(), [], 500);
  210. }
  211. }
  212. private function extractAcronymMappings($spreadsheet) {
  213. $mappings = [
  214. 'carga' => [
  215. 'equipos' => [], // [acronimo_equipo][acronimo_modelo] = tipo_completo
  216. 'modelos' => [], // [acronimo_modelo] = modelo_completo
  217. 'details' => [] // **NUEVO: [acronimo_equipo][acronimo_modelo] = [CARA, COBA, etc.]
  218. ],
  219. 'lru' => [
  220. 'equipos' => [],
  221. 'modelos' => [],
  222. 'details' => [] // **NUEVO: [acronimo_equipo][acronimo_modelo] = [CARA, COBA, etc.]
  223. ]
  224. ];
  225. // 1. Encontrar hoja EQUIPAMIENTO (case-insensitive)
  226. $cargaSheet = null;
  227. foreach ($spreadsheet->getAllSheets() as $sheet) {
  228. if (strtolower(trim($sheet->getTitle())) === 'equipamiento') {
  229. $cargaSheet = $sheet;
  230. break;
  231. }
  232. }
  233. // 2. Procesar hoja EQUIPAMIENTO si existe
  234. if ($cargaSheet) {
  235. $highestRow = $cargaSheet->getHighestRow();
  236. for ($row = 9; $row <= $highestRow; $row++) {
  237. $acronimoEquipo = $this->getCellValue($cargaSheet, 'D', $row);
  238. $tipoCompleto = $this->getCellValue($cargaSheet, 'C', $row);
  239. $modeloCompleto = $this->getCellValue($cargaSheet, 'E', $row);
  240. $acronimoModelo = $this->getCellValue($cargaSheet, 'F', $row);
  241. // **NUEVO: Extraer campos adicionales según el field_mapping**
  242. $codigoEquivalente = $this->getCellValue($cargaSheet, 'B', $row); // PCEQ_OTCO
  243. $numeroSerie = $this->getCellValue($cargaSheet, 'H', $row); // PCEQ_NUSE
  244. $codigoBarras = $this->getCellValue($cargaSheet, 'I', $row); // PCEQ_COBA
  245. $caracter = $this->getCellValue($cargaSheet, 'J', $row); // PCEQ_CARA
  246. $fechaVencimiento = $this->getCellValue($cargaSheet, 'K', $row); // PCEQ_FVAR
  247. if (!empty($acronimoEquipo) && !empty($acronimoModelo)) {
  248. // Almacenar combinación equipo+modelo para tipos completos
  249. if (!isset($mappings['carga']['equipos'][$acronimoEquipo])) {
  250. $mappings['carga']['equipos'][$acronimoEquipo] = [];
  251. }
  252. $mappings['carga']['equipos'][$acronimoEquipo][$acronimoModelo] = $tipoCompleto;
  253. // **NUEVO: Almacenar detalles del equipo**
  254. if (!isset($mappings['carga']['details'][$acronimoEquipo])) {
  255. $mappings['carga']['details'][$acronimoEquipo] = [];
  256. }
  257. $mappings['carga']['details'][$acronimoEquipo][$acronimoModelo] = [
  258. 'PCEQ_OTCO' => $codigoEquivalente,
  259. 'PCEQ_NUSE' => $numeroSerie,
  260. 'PCEQ_COBA' => $codigoBarras,
  261. 'PCEQ_CARA' => $caracter,
  262. 'PCEQ_FVAR' => $fechaVencimiento
  263. ];
  264. error_log("[EQUIPAMIENTO] {$acronimoEquipo}/{$acronimoModelo}: CARA='{$caracter}', COBA='{$codigoBarras}'");
  265. }
  266. if (!empty($acronimoModelo) && !empty($modeloCompleto)) {
  267. $mappings['carga']['modelos'][$acronimoModelo] = $modeloCompleto;
  268. }
  269. }
  270. }
  271. // 3. Procesar hoja LRU
  272. $lruSheet = null;
  273. foreach ($spreadsheet->getAllSheets() as $sheet) {
  274. if (strtolower(trim($sheet->getTitle())) === 'lru') {
  275. $lruSheet = $sheet;
  276. break;
  277. }
  278. }
  279. if ($lruSheet) {
  280. $highestRow = $lruSheet->getHighestRow();
  281. for ($row = 9; $row <= $highestRow; $row++) {
  282. $acronimoEquipo = $this->getCellValue($lruSheet, 'D', $row);
  283. $tipoCompleto = $this->getCellValue($lruSheet, 'C', $row);
  284. $modeloCompleto = $this->getCellValue($lruSheet, 'E', $row);
  285. $acronimoModelo = $this->getCellValue($lruSheet, 'F', $row);
  286. // **NUEVO: Extraer campos adicionales para LRU según field_mapping**
  287. $codigoEquivalente = $this->getCellValue($lruSheet, 'B', $row); // PCEQ_OTCO
  288. $numeroSerie = $this->getCellValue($lruSheet, 'H', $row); // PCEQ_NUSE
  289. $codigoBarras = $this->getCellValue($lruSheet, 'I', $row); // PCEQ_COBA
  290. $caracter = $this->getCellValue($lruSheet, 'J', $row); // PCEQ_CARA
  291. $fechaVencimiento = $this->getCellValue($lruSheet, 'K', $row); // PCEQ_FTGA (en LRU es diferente)
  292. if (!empty($acronimoEquipo) && !empty($acronimoModelo)) {
  293. if (!isset($mappings['lru']['equipos'][$acronimoEquipo])) {
  294. $mappings['lru']['equipos'][$acronimoEquipo] = [];
  295. }
  296. $mappings['lru']['equipos'][$acronimoEquipo][$acronimoModelo] = $tipoCompleto;
  297. // **NUEVO: Almacenar detalles del LRU**
  298. if (!isset($mappings['lru']['details'][$acronimoEquipo])) {
  299. $mappings['lru']['details'][$acronimoEquipo] = [];
  300. }
  301. $mappings['lru']['details'][$acronimoEquipo][$acronimoModelo] = [
  302. 'PCEQ_OTCO' => $codigoEquivalente,
  303. 'PCEQ_NUSE' => $numeroSerie,
  304. 'PCEQ_COBA' => $codigoBarras,
  305. 'PCEQ_CARA' => $caracter,
  306. 'PCEQ_FVAR' => $fechaVencimiento
  307. ];
  308. error_log("[LRU] {$acronimoEquipo}/{$acronimoModelo}: CARA='{$caracter}', COBA='{$codigoBarras}'");
  309. }
  310. if (!empty($acronimoModelo) && !empty($modeloCompleto)) {
  311. $mappings['lru']['modelos'][$acronimoModelo] = $modeloCompleto;
  312. }
  313. }
  314. }
  315. return $mappings;
  316. }
  317. // Nueva función para obtener valores de celda robusta
  318. private function getCellValue($worksheet, $column, $row) {
  319. try {
  320. $cell = $worksheet->getCell($column . $row);
  321. return trim($cell->getFormattedValue());
  322. } catch (\Exception $e) {
  323. // \Log::error("Error leyendo celda $column$row: " . $e->getMessage());
  324. return '';
  325. }
  326. }
  327. /**
  328. * Validar solo la estructura del Excel (sin procesar datos)
  329. */
  330. public function validateExcelStructureOnly(Request $request) {
  331. $validator = Validator::make($request->all(), [
  332. 'id_user' => 'required|string',
  333. 'id_file' => 'required|string',
  334. 'linea' => 'required|integer',
  335. ]);
  336. if($validator->fails()){
  337. return $this->responseController->makeResponse(
  338. true,
  339. "Se encontraron uno o más errores.",
  340. $this->responseController->makeErrors($validator->errors()->messages()),
  341. 401
  342. );
  343. }
  344. $form = $request->all();
  345. $idUser = $this->encryptionController->decrypt($form['id_user']);
  346. if(!$idUser){
  347. return $this->responseController->makeResponse(true, "El id del usuario no fue desencriptado correctamente", [], 400);
  348. }
  349. // Obtener archivo temporal
  350. $fileIdDecrypted = $this->encryptionController->decrypt($form['id_file']);
  351. $tempFile = DB::table('S002V01TARTE')->where([
  352. ['ARTE_IDAR', '=', $fileIdDecrypted],
  353. ['ARTE_NULI', '=', $form['linea']]
  354. ])->first();
  355. if(is_null($tempFile)){
  356. return $this->responseController->makeResponse(true, 'El archivo temporal no fue encontrado', [], 404);
  357. }
  358. // Validar solo la estructura
  359. $structureValidation = $this->validateExcelStructure($tempFile->ARTE_UBTE);
  360. if(!$structureValidation['valid']) {
  361. return $this->responseController->makeResponse(true, $structureValidation['message'], [], 400);
  362. }
  363. return $this->responseController->makeResponse(false, "Estructura del archivo válida", [
  364. 'archivo' => $tempFile->ARTE_NOAR,
  365. 'validado' => true
  366. ]);
  367. }
  368. private function validateExcelStructure($filePath) {
  369. try {
  370. $spreadsheet = IOFactory::load($filePath);
  371. $config = ExcelTemplateConfig::getTemplateConfigs()['TPCEQ'];
  372. $requiredSheets = array_keys($config['worksheets']);
  373. $existingSheets = $spreadsheet->getSheetNames();
  374. // Verificar que existan las hojas requeridas
  375. $missingSheets = array_diff($requiredSheets, $existingSheets);
  376. if(!empty($missingSheets)) {
  377. return [
  378. 'valid' => false,
  379. 'message' => 'Tu documento no cumple con las hojas requeridas de la plantilla'
  380. ];
  381. }
  382. // Validar headers de cada hoja
  383. foreach($config['worksheets'] as $sheetName => $sheetConfig) {
  384. if(!in_array($sheetName, $existingSheets)) continue;
  385. $worksheet = $spreadsheet->getSheetByName($sheetName);
  386. $headerValidation = $this->validateSheetHeaders($worksheet, $sheetConfig, $sheetName);
  387. if(!$headerValidation['valid']) {
  388. return [
  389. 'valid' => false,
  390. 'message' => 'Tu documento tiene error en los Headers, revísalos e intentalo de nuevo'
  391. ];
  392. }
  393. // Validar que tenga datos (solo para CARGA DE EQUIPOS)
  394. if($sheetName === 'EQUIPAMIENTO') {
  395. $dataValidation = $this->validateSheetHasData($worksheet, $sheetName, $sheetConfig);
  396. if(!$dataValidation['valid']) {
  397. return $dataValidation;
  398. }
  399. }
  400. }
  401. return ['valid' => true, 'message' => 'Estructura válida'];
  402. } catch(Exception $e) {
  403. return [
  404. 'valid' => false,
  405. 'message' => 'Error al validar la estructura del archivo: ' . $e->getMessage()
  406. ];
  407. }
  408. }
  409. private function validateSheetHeaders($worksheet, $sheetConfig, $sheetName) {
  410. // Para CATÁLOGOS usar validación especial
  411. if($sheetName === 'CATÁLOGOS') {
  412. return $this->validateCatalogosSheet($worksheet);
  413. }
  414. $headerRow = $sheetConfig['header_row'] ?? 4;
  415. $fieldMapping = $sheetConfig['field_mapping'];
  416. // Definir headers esperados según la configuración de Angular
  417. $expectedHeaders = $this->getExpectedHeaders($sheetName);
  418. if(empty($expectedHeaders)) {
  419. return ['valid' => true, 'message' => "No hay headers específicos para validar en $sheetName"];
  420. }
  421. foreach($expectedHeaders as $column => $expectedHeader) {
  422. $cellValue = $worksheet->getCell($column . $headerRow)->getCalculatedValue();
  423. $actualHeader = $cellValue ? trim((string)$cellValue) : '';
  424. if($actualHeader !== $expectedHeader) {
  425. return [
  426. 'valid' => false,
  427. 'message' => "Error en header de $sheetName, columna $column: esperado '$expectedHeader', encontrado '$actualHeader'"
  428. ];
  429. }
  430. }
  431. return ['valid' => true, 'message' => "Headers válidos para $sheetName"];
  432. }
  433. private function validateCatalogosSheet($worksheet) {
  434. $expectedHeaders = [
  435. 'B' => 'FAMILIA',
  436. 'C' => 'ACRÓNIMO',
  437. 'E' => 'SUBFAMILIA',
  438. 'F' => 'ACRÓNIMO',
  439. 'G' => 'SUBFAMILY',
  440. 'I' => 'UBICACIONES (FRENTES)',
  441. 'J' => 'CÓDIGO',
  442. 'L' => 'RMS',
  443. 'M' => 'ELEMENTO',
  444. 'N' => 'CÓDIGO',
  445. 'P' => 'OCUPACIÓN',
  446. 'Q' => 'CÓDIGO',
  447. 'S' => 'ESTADO',
  448. 'T' => 'ACRÓNIMO'
  449. ];
  450. foreach($expectedHeaders as $column => $expectedHeader) {
  451. $cellValue = $worksheet->getCell($column . '5')->getCalculatedValue();
  452. $actualHeader = $cellValue ? trim((string)$cellValue) : '';
  453. if($actualHeader !== $expectedHeader) {
  454. return [
  455. 'valid' => false,
  456. 'message' => "Error en CATÁLOGOS, fila 5, columna $column: esperado '$expectedHeader', encontrado '$actualHeader'"
  457. ];
  458. }
  459. }
  460. return ['valid' => true, 'message' => 'Headers válidos para CATÁLOGOS'];
  461. }
  462. private function validateSheetHasData($worksheet, $sheetName, $sheetConfig) {
  463. try {
  464. $range = $worksheet->calculateWorksheetDimension();
  465. $highestRow = $worksheet->getHighestRow();
  466. $dataStartRow = $sheetConfig['date_start_row'] ?? 9;
  467. if($highestRow < $dataStartRow) {
  468. return [
  469. 'valid' => false,
  470. 'message' => "La hoja '$sheetName' no contiene datos. Se requiere al menos un registro con información."
  471. ];
  472. }
  473. // Verificar que hay al menos una fila con datos
  474. $hasData = false;
  475. $mainColumns = ['B', 'D', 'F', 'G']; // Columnas principales para verificar
  476. for($row = $dataStartRow; $row <= $highestRow; $row++) {
  477. foreach($mainColumns as $col) {
  478. $cellValue = $worksheet->getCell($col . $row)->getCalculatedValue();
  479. if($cellValue !== null && $cellValue !== '' && trim((string)$cellValue) !== '') {
  480. $hasData = true;
  481. break 2;
  482. }
  483. }
  484. }
  485. if(!$hasData) {
  486. return [
  487. 'valid' => false,
  488. 'message' => "La hoja '$sheetName' no contiene datos. Se requiere al menos un registro con información."
  489. ];
  490. }
  491. return ['valid' => true, 'message' => 'Datos encontrados'];
  492. } catch(Exception $e) {
  493. return [
  494. 'valid' => false,
  495. 'message' => "Error al validar datos en '$sheetName': " . $e->getMessage()
  496. ];
  497. }
  498. }
  499. private function getExpectedHeaders($sheetName) {
  500. $headers = [
  501. 'EQUIPAMIENTO' => [
  502. 'B' => 'CÓDIGO EQUIVALENTE',
  503. 'C' => 'TIPO / DESCRIPCIÓN',
  504. 'D' => 'ACRÓNIMO DEL EQUIPO',
  505. 'E' => 'MODELO COMPLETO',
  506. 'F' => 'ACRÓNIMO DEL MODELO',
  507. 'G' => 'ID',
  508. 'H' => 'NO.SERIE',
  509. 'I' => 'NO. CÓDIGO DE BARRAS',
  510. 'J' => 'CARÁCTER',
  511. 'K' => 'FECHA DE VENCIMIENTO DEL ARTÍCULO',
  512. 'L' => 'ETIQUETA FINAL DEL EQUIPO',
  513. ],
  514. 'LRU' => [
  515. 'B' => 'CÓDIGO EQUIVALENTE',
  516. 'C' => 'TIPO / DESCRIPCIÓN',
  517. 'D' => 'ACRÓNIMO DEL EQUIPO',
  518. 'E' => 'MODELO COMPLETO',
  519. 'F' => 'ACRÓNIMO DEL MODELO',
  520. 'G' => 'ID',
  521. 'H' => 'NO.SERIE',
  522. 'I' => 'NO. CÓDIGO DE BARRAS',
  523. 'J' => 'CARÁCTER',
  524. 'K' => 'FECHA DE VENCIMIENTO DEL ARTÍCULO',
  525. 'L' => 'ETIQUETA FINAL DEL EQUIPO'
  526. ],
  527. 'CASO 1'=> [
  528. 'B'=> 'LÍNEA',
  529. 'D'=> 'UBICACIÓN',
  530. 'F'=> 'NIVEL',
  531. 'H'=> 'OCUPACIÓN',
  532. 'J'=> 'ELEMENTO',
  533. 'L'=> 'COORDENADAS PLANO GENERAL',
  534. 'M'=> 'COORDENADAS DETALLE',
  535. 'N'=> 'COORDENADAS DE POSICIÓN',
  536. 'P'=> 'FAMILIA',
  537. 'R'=> 'SUBFAMILIA',
  538. 'T'=> 'ESTADO',
  539. 'V'=> 'TIPO',
  540. 'X'=> 'MODELO',
  541. 'Z'=> 'ID',
  542. 'AB'=> 'TIPO',
  543. 'AD'=> 'MODELO',
  544. 'AF'=> 'ID',
  545. 'AH'=> 'CÓDIGO COMPLETO SAM',
  546. 'AI'=> 'CÓDIGO EQUIVALENTE',
  547. ],
  548. 'CASO 2'=> [
  549. 'B'=> 'LÍNEA',
  550. 'D'=> 'UBICACIÓN',
  551. 'F'=> 'NIVEL',
  552. 'H'=> 'OCUPACIÓN',
  553. 'J'=> 'ELEMENTO',
  554. 'L'=> 'COORDENADAS PLANO GENERAL',
  555. 'M'=> 'COORDENADAS DE POSICIÓN',
  556. 'N'=> 'POSICIÓN EN RACK',
  557. 'P'=> 'FAMILIA',
  558. 'R'=> 'SUBFAMILIA',
  559. 'T'=> 'ESTADO',
  560. 'V'=> 'TIPO',
  561. 'X'=> 'MODELO',
  562. 'Z'=> 'ID',
  563. 'AB'=> 'TIPO',
  564. 'AD'=> 'MODELO',
  565. 'AF'=> 'ID',
  566. 'AH'=> 'CÓDIGO COMPLETO',
  567. 'AI'=> 'CÓDIGO EQUIVALENTE',
  568. ],
  569. 'CASO 3'=> [
  570. 'B'=> 'LÍNEA',
  571. 'D'=> 'UBICACIÓN ORIGEN',
  572. 'F'=> 'NIVEL ORIGEN',
  573. 'H'=> 'OCUPACIÓN ORIGEN',
  574. 'J'=> 'ELEMENTO ORIGEN',
  575. 'L'=> 'PK ORIGEN',
  576. 'N'=> 'UBICACIÓN DESTINO',
  577. 'P'=> 'NIVEL DESTINO',
  578. 'R'=> 'OCUPACIÓN DESTINO',
  579. 'T'=> 'ELEMENTO DESTINO',
  580. 'V'=> 'PK DESTINO',
  581. 'X'=> 'FAMILIA',
  582. 'Z'=> 'SUBFAMILIA',
  583. 'AB'=> 'ESTADO',
  584. 'AD'=> 'TIPO',
  585. 'AF'=> 'MODELO',
  586. 'AH'=> 'ID',
  587. 'AJ'=> 'TIPO',
  588. 'AL'=> 'MODELO',
  589. 'AN'=> 'ID',
  590. 'AP'=> 'CÓDIGO COMPLETO',
  591. 'AQ'=> 'CÓDIGO EQUIVALENTE'
  592. ],
  593. 'CASO 4'=> [
  594. 'B'=> 'LÍNEA',
  595. 'D'=> 'UBICACIÓN ORIGEN',
  596. 'F'=> 'NIVEL ORIGEN',
  597. 'H'=> 'OCUPACIÓN ORIGEN',
  598. 'J'=> 'ELEMENTO ORIGEN',
  599. 'L'=> 'SECUENCIAL ORIGEN',
  600. 'N'=> 'COORDENADAS PLANO',
  601. 'O'=> 'COORDENADAS DETALLE',
  602. 'P'=> 'COORDENADAS DE POSICIÓN',
  603. 'R'=> 'UBICACIÓN DESTINO',
  604. 'T'=> 'NIVEL DESTINO',
  605. 'V'=> 'OCUPACIÓN DESTINO',
  606. 'X'=> 'ELEMENTO DESTINO',
  607. 'Z'=> 'SECUENCIAL DESTINO',
  608. 'AB'=> 'COORDENADAS PLANO',
  609. 'AC'=> 'COORDENADAS DETALLE',
  610. 'AD'=> 'COORDENADAS DE POSICIÓN',
  611. 'AF'=> 'FAMILIA',
  612. 'AH'=> 'SUBFAMILIA',
  613. 'AJ'=> 'ESTADO',
  614. 'AL'=> 'TIPO',
  615. 'AN'=> 'MODELO',
  616. 'AP'=> 'ID',
  617. 'AR'=> 'TIPO',
  618. 'AT'=> 'MODELO',
  619. 'AV'=> 'ID',
  620. 'AX'=> 'CÓDIGO COMPLETO',
  621. 'AY'=> 'CÓDIGO EQUIVALENTE',
  622. ],
  623. 'CASO 5'=> [
  624. 'B'=> 'LÍNEA',
  625. 'D'=> 'UBICACIÓN',
  626. 'F'=> 'NIVEL',
  627. 'H'=> 'OCUPACIÓN',
  628. 'J'=> 'ÁREA',
  629. 'L'=> 'ELEMENTO',
  630. 'N'=> 'FAMILIA',
  631. 'P'=> 'SUBFAMILIA',
  632. 'R'=> 'ESTADO',
  633. 'T'=> 'TIPO',
  634. 'V'=> 'MODELO',
  635. 'X'=> 'ID',
  636. 'Z'=> 'TIPO',
  637. 'AB'=> 'MODELO',
  638. 'AD'=> 'ID',
  639. 'AF'=> 'CÓDIGO COMPLETO',
  640. 'AG'=> 'CÓDIGO EQUIVALENTE',
  641. ],
  642. 'CASO 6' => [
  643. 'B'=> 'LÍNEA',
  644. 'D'=> 'UBICACIÓN',
  645. 'F'=> 'NIVEL',
  646. 'H'=> 'OCUPACIÓN',
  647. 'J'=> 'ELEMENTO',
  648. 'L'=> 'POSICIÓN',
  649. 'N'=> 'FAMILIA',
  650. 'P'=> 'SUBFAMILIA',
  651. 'R'=> 'ESTADO',
  652. 'T'=> 'TIPO',
  653. 'V'=> 'MODELO',
  654. 'X'=> 'ID',
  655. 'Z'=> 'TIPO',
  656. 'AB'=> 'MODELO',
  657. 'AD'=> 'ID',
  658. 'AF'=> 'CÓDIGO COMPLETO',
  659. 'AG'=> 'CÓDIGO EQUIVALENTE'
  660. ]
  661. ];
  662. return $headers[$sheetName] ?? [];
  663. }
  664. private function extractRowData($worksheet, $row, $fieldMapping, $sheetName) {
  665. $rowData = [];
  666. foreach($fieldMapping as $column => $field) {
  667. if (!empty($field) && $field !== '.' && $field !== '-' && $field !== '_' && $field !== '+') {
  668. $cellValue = $worksheet->getCell($column . $row)->getCalculatedValue();
  669. $rowData[$field] = $cellValue;
  670. }
  671. }
  672. // **CAMBIO PRINCIPAL: Usar SIEMPRE el código generado por el frontend**
  673. $frontendCode = $this->extractFrontendGeneratedCode($worksheet, $row, $sheetName);
  674. if (!empty($frontendCode)) {
  675. $rowData['PCEQ_CPGE'] = trim($frontendCode);
  676. // Log para debug
  677. error_log("[Frontend Code] {$sheetName} Fila {$row}: Usando código del frontend: '{$frontendCode}'");
  678. } else {
  679. error_log("[Frontend Code] {$sheetName} Fila {$row}: No se encontró código generado por frontend");
  680. // Como fallback, generar código básico pero con advertencia
  681. $rowData['PCEQ_CPGE'] = $this->generateFallbackCode($rowData, $sheetName, $row);
  682. }
  683. // Manejar concatenaciones especiales para coordenadas si es necesario
  684. $this->handleCoordinateConcatenation($rowData, $worksheet, $row, $sheetName);
  685. // Inicializar campos de acrónimos (para compatibilidad)
  686. $rowData['PCEQ_TIEQ_ACRONIMO'] = '';
  687. $rowData['PCEQ_MOEQ_ACRONIMO'] = '';
  688. $rowData['PCEQ_TIEQ_HIJO_ACRONIMO'] = '';
  689. $rowData['PCEQ_MOEQ_HIJO_ACRONIMO'] = '';
  690. return $rowData;
  691. }
  692. private function generateFallbackCode($rowData, $sheetName, $row) {
  693. error_log(" [Fallback Code] Generando código de respaldo para {$sheetName} Fila {$row}");
  694. // Para hojas de casos, usar un formato básico
  695. if (in_array($sheetName, ['CASO 1', 'CASO 2', 'CASO 3', 'CASO 4', 'CASO 5', 'CASO 6'])) {
  696. $linea = $rowData['PCEQ_NULI'] ?? '';
  697. $tipo = $rowData['PCEQ_TIEQ'] ?? '';
  698. $modelo = $rowData['PCEQ_MOEQ'] ?? '';
  699. $timestamp = date('YmdHis');
  700. return "FALLBACK_{$linea}_{$tipo}_{$modelo}_{$timestamp}_{$row}";
  701. }
  702. // Para EQUIPAMIENTO y LRU, usar ID simple
  703. return $this->generateUniqueHashId($rowData['PCEQ_NULI'] ?? '1');
  704. }
  705. private function extractFrontendGeneratedCode($worksheet, $row, $sheetName) {
  706. $codeColumns = [
  707. 'CASO 1' => 'AH', // Columna AH para CASO 1
  708. 'CASO 2' => 'AH', // Columna AH para CASO 2
  709. 'CASO 3' => 'AP', // Columna AP para CASO 3
  710. 'CASO 4' => 'AX', // Columna AX para CASO 4
  711. 'CASO 5' => 'AF', // Columna AF para CASO 5
  712. 'CASO 6' => 'AF', // Columna AF para CASO 6
  713. // Para CARGA DE EQUIPOS y LRU, no hay código complejo generado
  714. 'EQUIPAMIENTO' => null,
  715. 'LRU' => null
  716. ];
  717. $columnLetter = $codeColumns[$sheetName] ?? null;
  718. if ($columnLetter) {
  719. try {
  720. $cellValue = $worksheet->getCell($columnLetter . $row)->getCalculatedValue();
  721. $code = $cellValue ? trim((string)$cellValue) : '';
  722. // Validar que el código no esté vacío y tenga formato esperado
  723. if (!empty($code) && strlen($code) > 5) { // Códigos válidos suelen ser largos
  724. error_log(" [Code Extract] {$sheetName} Fila {$row}: Código encontrado en {$columnLetter}: '{$code}'");
  725. return $code;
  726. } else {
  727. error_log("⚠️ [Code Extract] {$sheetName} Fila {$row}: Código en {$columnLetter} está vacío o muy corto: '{$code}'");
  728. }
  729. } catch (\Exception $e) {
  730. error_log(" [Code Extract] {$sheetName} Fila {$row}: Error leyendo {$columnLetter}: " . $e->getMessage());
  731. }
  732. }
  733. return null;
  734. }
  735. private function handleCoordinateConcatenation(&$rowData, $worksheet, $row, $sheetName) {
  736. switch($sheetName) {
  737. case 'CASO 1':
  738. case 'CASO 2':
  739. $coordL = $this->getCellValue($worksheet, 'L', $row);
  740. $coordM = $this->getCellValue($worksheet, 'M', $row);
  741. $coordN = $this->getCellValue($worksheet, 'N', $row);
  742. $rowData['PCEQ_COOR'] = $coordL . $coordM . $coordN;
  743. break;
  744. case 'CASO 4':
  745. // Coordenadas origen
  746. $coordN = $this->getCellValue($worksheet, 'N', $row);
  747. $coordO = $this->getCellValue($worksheet, 'O', $row);
  748. $coordP = $this->getCellValue($worksheet, 'P', $row);
  749. $rowData['PCEQ_COOR_ORIGEN'] = $coordN . $coordO . $coordP;
  750. // Coordenadas destino
  751. $coordAB = $this->getCellValue($worksheet, 'AB', $row);
  752. $coordAC = $this->getCellValue($worksheet, 'AC', $row);
  753. $coordAD = $this->getCellValue($worksheet, 'AD', $row);
  754. $rowData['PCEQ_COOR_DESTINO'] = $coordAB . $coordAC . $coordAD;
  755. break;
  756. }
  757. }
  758. private function logCodeComparison($frontendCode, $backendCode, $sheetName, $row) {
  759. if ($frontendCode !== $backendCode) {
  760. // \Log::info("Comparación de códigos en $sheetName fila $row:");
  761. // \Log::info("Frontend: $frontendCode");
  762. // \Log::info("Backend: $backendCode");
  763. // Analizar diferencias
  764. $frontParts = explode('.', $frontendCode);
  765. $backParts = explode('.', $backendCode);
  766. for ($i = 0; $i < max(count($frontParts), count($backParts)); $i++) {
  767. $front = $frontParts[$i] ?? '[MISSING]';
  768. $back = $backParts[$i] ?? '[MISSING]';
  769. if ($front !== $back) {
  770. // \Log::info("Diferencia en parte $i: Frontend='$front' vs Backend='$back'");
  771. }
  772. }
  773. }
  774. }
  775. private function isEmptyRow($rowData) {
  776. $requiredFields = ['PCEQ_TIEQ', 'PCEQ_MOEQ']; // Campos mínimos
  777. foreach($requiredFields as $field) {
  778. if(isset($rowData[$field]) && !empty(trim((string)$rowData[$field]))) {
  779. return false;
  780. }
  781. }
  782. return true;
  783. }
  784. private function validateRowData($rowData, $sheetName, $row) {
  785. $errors = [];
  786. $valid = true;
  787. // Para hojas de casos 1-6
  788. if (in_array($sheetName, ['CASO 1', 'CASO 2', 'CASO 3', 'CASO 4', 'CASO 5', 'CASO 6'])) {
  789. $tienePrimerConjunto =
  790. !empty(trim($rowData['PCEQ_TIEQ'] ?? '')) &&
  791. !empty(trim($rowData['PCEQ_MOEQ'] ?? ''));
  792. $tieneSegundoConjunto =
  793. !empty(trim($rowData['PCEQ_TIEQ_HIJO'] ?? '')) &&
  794. !empty(trim($rowData['PCEQ_MOEQ_HIJO'] ?? ''));
  795. if (!$tienePrimerConjunto && !$tieneSegundoConjunto) {
  796. $errors[] = 'Se requiere al menos un conjunto completo de datos (Tipo/Modelo)';
  797. $valid = false;
  798. }
  799. } else {
  800. if(empty($rowData['PCEQ_TIEQ'] ?? '')) {
  801. $errors[] = 'Tipo de equipo requerido';
  802. $valid = false;
  803. }
  804. if(empty($rowData['PCEQ_MOEQ'] ?? '')) {
  805. $errors[] = 'Modelo requerido';
  806. $valid = false;
  807. }
  808. }
  809. // Validar fechas si existen
  810. $dateFields = ['PCEQ_FEAD', 'PCEQ_FIGA', 'PCEQ_FTGA'];
  811. foreach($dateFields as $dateField) {
  812. if(isset($rowData[$dateField]) && !empty($rowData[$dateField])) {
  813. try {
  814. Carbon::parse($rowData[$dateField]);
  815. } catch(Exception $e) {
  816. $errors[] = "Fecha inválida en campo $dateField";
  817. $valid = false;
  818. }
  819. }
  820. }
  821. return ['valid' => $valid, 'errors' => $errors];
  822. }
  823. private function noDate($value)
  824. {
  825. if (empty($value) ||
  826. strtoupper(trim($value)) === 'NA' ||
  827. trim($value) === '.' ||
  828. trim($value) === '-') {
  829. return now()->format('Y-m-d');
  830. }
  831. if (is_numeric($value)) {
  832. try {
  833. return \PhpOffice\PhpSpreadsheet\Shared\Date::excelToDateTimeObject($value)->format('Y-m-d');
  834. } catch (Exception $e) {
  835. return null;
  836. }
  837. }
  838. if (is_string($value)) {
  839. try {
  840. $date = new \DateTime($value);
  841. return $date->format('Y-m-d');
  842. } catch (Exception $e) {
  843. return null;
  844. }
  845. }
  846. return null;
  847. }
  848. private function prepareEquipmentData($rowData, $linea, $idUser, $sheetName) {
  849. $nowStr = Carbon::now('America/Mexico_city')->toDateTimeString();
  850. // **MODIFICADO: Determinar si es hijo ANTES de procesar los campos**
  851. $tieneSegundoConjunto =
  852. !empty(trim($rowData['PCEQ_TIEQ_HIJO'] ?? '')) &&
  853. !empty(trim($rowData['PCEQ_MOEQ_HIJO'] ?? ''));
  854. $isHijo = $tieneSegundoConjunto;
  855. // **NUEVO: Obtener PCEQ_CARA y PCEQ_COBA según jerarquía**
  856. if ($isHijo) {
  857. // Para HIJO: usar los campos con sufijo _HIJO
  858. $caracter = $this->normalizeCaracter($rowData['PCEQ_CARA_HIJO'] ?? null);
  859. $codigoBarras = $rowData['PCEQ_COBA_HIJO'] ?? '';
  860. $numeroSerie = $rowData['PCEQ_NUSE_HIJO'] ?? '';
  861. $codigoEquivalente = $rowData['PCEQ_OTCO_HIJO'] ?? '';
  862. $fechaVencimiento = $this->noDate($rowData['PCEQ_FVAR_HIJO'] ?? null);
  863. error_log("[Equipment Data] HIJO - Usando: CARA='{$caracter}', COBA='{$codigoBarras}'");
  864. } else {
  865. // Para PADRE: usar los campos normales
  866. $caracter = $this->normalizeCaracter($rowData['PCEQ_CARA'] ?? null);
  867. $codigoBarras = $rowData['PCEQ_COBA'] ?? '';
  868. $numeroSerie = $rowData['PCEQ_NUSE'] ?? '';
  869. $codigoEquivalente = $rowData['PCEQ_OTCO'] ?? '';
  870. $fechaVencimiento = $this->noDate($rowData['PCEQ_FVAR'] ?? null);
  871. error_log("[Equipment Data] PADRE - Usando: CARA='{$caracter}', COBA='{$codigoBarras}'");
  872. }
  873. // Procesar otras fechas
  874. $fechaInicioGarantia = $this->parseDate($rowData['PCEQ_FIGA'] ?? null);
  875. $fechaFinGarantia = $this->parseDate($rowData['PCEQ_FTGA'] ?? null);
  876. $fechaAdquisicion = $this->parseDate($rowData['PCEQ_FEAD'] ?? null);
  877. // Procesar OTCO
  878. $otcoArray = [];
  879. if (!empty(trim($codigoEquivalente))) {
  880. if (is_string($codigoEquivalente) && json_decode($codigoEquivalente) !== null) {
  881. $otcoArray = json_decode($codigoEquivalente, true);
  882. } else {
  883. $otcoArray = [$codigoEquivalente];
  884. }
  885. }
  886. $equipmentData = [
  887. 'PCEQ_FIGA' => $fechaInicioGarantia ?? now()->format('Y-m-d'),
  888. 'PCEQ_FEAD' => $fechaAdquisicion ?? now()->format('Y-m-d'),
  889. 'PCEQ_FTGA' => $fechaFinGarantia ?? now()->format('Y-m-d'),
  890. 'PCEQ_NULI' => $linea,
  891. 'PCEQ_UBOR' => $rowData['PCEQ_UBOR'] ?? '',
  892. 'PCEQ_NIOR' => $rowData['PCEQ_NIOR'] ?? '',
  893. 'PCEQ_OCOR' => $rowData['PCEQ_OCOR'] ?? '',
  894. 'PCEQ_ELOR' => $rowData['PCEQ_ELOR'] ?? '',
  895. 'PCEQ_COOR' => $rowData['PCEQ_COOR'] ?? '',
  896. 'PCEQ_FAMI' => $rowData['PCEQ_FAMI'] ?? '',
  897. 'PCEQ_SUBF' => $rowData['PCEQ_SUBF'] ?? '',
  898. 'PCEQ_ESEQ' => $rowData['PCEQ_ESEQ'] ?? 'A',
  899. 'PCEQ_TICO' => $this->getCodeTypeFromSheet($sheetName),
  900. 'PCEQ_JERA' => $isHijo ? 'Hijo' : 'Padre',
  901. 'PCEQ_EQPA' => null,
  902. // **CAMPOS OBTENIDOS SEGÚN JERARQUÍA**
  903. 'PCEQ_NUSE' => $numeroSerie,
  904. 'PCEQ_COBA' => $codigoBarras,
  905. 'PCEQ_CARA' => $caracter,
  906. 'PCEQ_FVAR' => $fechaVencimiento ?? now()->format('Y-m-d'),
  907. 'PCEQ_OTCO' => json_encode($otcoArray),
  908. // Campos fijos
  909. 'PCEQ_PREQ' => $rowData['PCEQ_PREQ'] ?? 0,
  910. 'PCEQ_GAIM' => json_encode([]),
  911. 'PCEQ_DORE' => json_encode([]),
  912. 'PCEQ_ESRE' => 'Revisión',
  913. 'PCEQ_USRE' => $idUser,
  914. 'PCEQ_FERE' => $nowStr,
  915. 'PCEQ_IDPR' => $this->generateNumericUniqueId($linea),
  916. 'PCEQ_KIOR' => $rowData['PCEQ_KIOR'] ?? '',
  917. 'PCEQ_ELDE' => $rowData['PCEQ_ELDE'] ?? '',
  918. // **CÓDIGO DEL FRONTEND (SIN CAMBIOS)**
  919. 'PCEQ_CPGE' => $rowData['PCEQ_CPGE'] ?? '',
  920. 'PCEQ_EQPA' => ''
  921. ];
  922. // Manejo de jerarquía para código padre
  923. if ($equipmentData['PCEQ_JERA'] === 'Hijo') {
  924. $fullCode = $equipmentData['PCEQ_CPGE'] ?? '';
  925. // Extraer el código padre eliminando el último segmento
  926. $parts = explode('.', $fullCode);
  927. if (count($parts) > 1) {
  928. array_pop($parts); // Eliminar segmento hijo
  929. $equipmentData['PCEQ_EQPA'] = implode('.', $parts);
  930. error_log("👨‍👦 [Hierarchy] {$sheetName} - Código padre extraído: " . $equipmentData['PCEQ_EQPA']);
  931. }
  932. }
  933. // Validación final del código
  934. if (empty($equipmentData['PCEQ_CPGE'])) {
  935. error_log("[Equipment Data] ADVERTENCIA: PCEQ_CPGE está vacío para fila de {$sheetName}");
  936. $equipmentData['PCEQ_CPGE'] = $this->generateFallbackCode($rowData, $sheetName, 0);
  937. error_log("[Equipment Data] Usando código de respaldo: " . $equipmentData['PCEQ_CPGE']);
  938. }
  939. // Lógica de nombres según jerarquía
  940. if (in_array($sheetName, ['CASO 1', 'CASO 2', 'CASO 3', 'CASO 4', 'CASO 5', 'CASO 6'])) {
  941. if ($isHijo) {
  942. // Para HIJO: Usar nombres completos
  943. $equipmentData['PCEQ_TIEQ'] = $rowData['PCEQ_TIEQ_HIJO_COMPLETO'] ?? $rowData['PCEQ_TIEQ_HIJO'] ?? '';
  944. $equipmentData['PCEQ_MOEQ'] = $rowData['PCEQ_MOEQ_HIJO_COMPLETO'] ?? $rowData['PCEQ_MOEQ_HIJO'] ?? '';
  945. } else {
  946. // Para PADRE: Usar nombres completos
  947. $equipmentData['PCEQ_TIEQ'] = $rowData['PCEQ_TIEQ_COMPLETO'] ?? $rowData['PCEQ_TIEQ'] ?? '';
  948. $equipmentData['PCEQ_MOEQ'] = $rowData['PCEQ_MOEQ_COMPLETO'] ?? $rowData['PCEQ_MOEQ'] ?? '';
  949. }
  950. } else {
  951. // Para EQUIPAMIENTO y LRU: También usar nombres completos si están disponibles
  952. $equipmentData['PCEQ_TIEQ'] = $rowData['PCEQ_TIEQ_COMPLETO'] ?? $rowData['PCEQ_TIEQ'] ?? '';
  953. $equipmentData['PCEQ_MOEQ'] = $rowData['PCEQ_MOEQ_COMPLETO'] ?? $rowData['PCEQ_MOEQ'] ?? '';
  954. }
  955. // Agregar campos específicos según el tipo de hoja
  956. $this->addSheetSpecificFields($equipmentData, $rowData, $sheetName);
  957. return $equipmentData;
  958. }
  959. private function parseDate($value) {
  960. if (!$value) return null;
  961. try {
  962. // Intentar como fecha de Excel
  963. if (is_numeric($value)) {
  964. return \PhpOffice\PhpSpreadsheet\Shared\Date::excelToDateTimeObject($value)
  965. ->format('Y-m-d');
  966. }
  967. // Intentar como cadena de fecha
  968. return Carbon::createFromFormat('d/m/Y', $value)->format('Y-m-d');
  969. } catch (\Exception $e) {
  970. return null;
  971. }
  972. }
  973. // Función para manejar jerarquía
  974. private function handleHierarchy(&$equipmentData, $rowData, $sheetName) {
  975. if (!in_array($sheetName, ['CASO 1','CASO 2','CASO 3','CASO 4','CASO 5','CASO 6'])) {
  976. return;
  977. }
  978. // Determinar si es hijo
  979. $isHijo = !empty($rowData['PCEQ_TIEQ_HIJO']) || !empty($rowData['PCEQ_MOEQ_HIJO']);
  980. if ($isHijo) {
  981. $equipmentData['PCEQ_JERA'] = 'Hijo';
  982. $equipmentData['PCEQ_TIEQ'] = $rowData['PCEQ_TIEQ_HIJO'] ?? '';
  983. $equipmentData['PCEQ_MOEQ'] = $rowData['PCEQ_MOEQ_HIJO'] ?? '';
  984. }
  985. }
  986. private function normalizeCaracter($value) {
  987. if (!$value) return null;
  988. $value = strtoupper(trim($value));
  989. $mapping = [
  990. 'REPARABLE' => 'REPARABLE',
  991. 'REP' => 'REPARABLE',
  992. 'R' => 'REPARABLE',
  993. 'CONSUMIBLE' => 'CONSUMIBLE',
  994. 'CONSUM' => 'CONSUMIBLE',
  995. 'CONS' => 'CONSUMIBLE',
  996. 'C' => 'CONSUMIBLE',
  997. 'DESECHABLE' => 'CONSUMIBLE'
  998. ];
  999. return $mapping[$value] ?? null;
  1000. }
  1001. // MÉTODO PARA GENERAR PCEQ_IDPR: Solo ID numérico único
  1002. private function generateNumericUniqueId($linea, $increment = true) {
  1003. static $lastId = [];
  1004. static $initialized = [];
  1005. // Solo inicializar una vez por línea
  1006. if (!isset($initialized[$linea])) {
  1007. // Obtener el máximo ID existente en la base de datos
  1008. $maxId = DB::table('S002V01TPCEQ')
  1009. ->where('PCEQ_NULI', $linea)
  1010. ->max('PCEQ_IDPR');
  1011. if ($maxId) {
  1012. // Si hay registros, convertir a entero (removiendo padding)
  1013. $lastId[$linea] = (int)ltrim($maxId, '0');
  1014. } else {
  1015. // Si NO hay registros, empezar desde 0
  1016. $lastId[$linea] = 0;
  1017. }
  1018. $initialized[$linea] = true;
  1019. // Log para debug
  1020. }
  1021. // Solo incrementar si se solicita (por defecto true)
  1022. if ($increment) {
  1023. $lastId[$linea]++;
  1024. }
  1025. // FORMATEAR A 6 DÍGITOS
  1026. return str_pad($lastId[$linea], 6, '0', STR_PAD_LEFT);
  1027. }
  1028. // MÉTODO PARA GENERAR PCEQ_CPGE: El código concatenado complejo (solo CASOS 1-6)
  1029. private function getAcronymForCode($data, $type) {
  1030. // Determinar si usar padre o hijo según PCEQ_JERA
  1031. $isHijo = ($data['PCEQ_JERA'] ?? 'Padre') === 'Hijo';
  1032. if ($type === 'TIEQ') {
  1033. if ($isHijo) {
  1034. return $data['PCEQ_TIEQ_HIJO_ACRONIMO'] ?? $data['PCEQ_TIEQ_ACRONIMO'] ?? '';
  1035. } else {
  1036. return $data['PCEQ_TIEQ_ACRONIMO'] ?? '';
  1037. }
  1038. } elseif ($type === 'MOEQ') {
  1039. if ($isHijo) {
  1040. return $data['PCEQ_MOEQ_HIJO_ACRONIMO'] ?? $data['PCEQ_MOEQ_ACRONIMO'] ?? '';
  1041. } else {
  1042. return $data['PCEQ_MOEQ_ACRONIMO'] ?? '';
  1043. }
  1044. }
  1045. return '';
  1046. }
  1047. // MÉTODO ALTERNATIVO: Usar timestamp + hash para garantizar unicidad (para CARGA DE EQUIPOS y LRU)
  1048. private function generateUniqueHashId($linea) {
  1049. // Crear ID único basado en timestamp + random para CARGA DE EQUIPOS y LRU
  1050. return $linea . '_' . date('YmdHis') . '_' . uniqid();
  1051. }
  1052. // MÉTODO DE RESPALDO: Si falla todo, usar este ID de emergencia
  1053. private function generateFallbackId($linea) {
  1054. return 'FALLBACK_' . $linea . '_' . microtime(true) . '_' . rand(10000, 99999);
  1055. }
  1056. // SOLUCIÓN MEJORADA: Verificar duplicados de PCEQ_IDPR antes de insertar
  1057. private function insertEquipmentWithDuplicateHandling($equipmentData) {
  1058. $maxAttempts = 5;
  1059. $attempt = 0;
  1060. while($attempt < $maxAttempts) {
  1061. try {
  1062. // Verificar si ya existe este PCEQ_IDPR para esta línea
  1063. $exists = DB::table('S002V01TPCEQ')
  1064. ->where('PCEQ_NULI', $equipmentData['PCEQ_NULI'])
  1065. ->where('PCEQ_IDPR', $equipmentData['PCEQ_IDPR'])
  1066. ->exists();
  1067. if($exists) {
  1068. // Regenerar PCEQ_IDPR numérico único
  1069. $equipmentData['PCEQ_IDPR'] = $this->generateNumericUniqueId($equipmentData['PCEQ_NULI']);
  1070. // Si es un CASO 1-6, regenerar también el PCEQ_CPGE con el nuevo IDPR
  1071. if(isset($equipmentData['PCEQ_CPGE']) && strpos($equipmentData['PCEQ_CPGE'], '.') !== false) {
  1072. $sheetName = $this->getSheetNameFromCodeType($equipmentData['PCEQ_TICO']);
  1073. if($sheetName) {
  1074. $equipmentData['PCEQ_CPGE'] = $this->generateConcatenatedCode($equipmentData, $sheetName);
  1075. }
  1076. }
  1077. $attempt++;
  1078. continue;
  1079. }
  1080. // Intentar insertar
  1081. return DB::table('S002V01TPCEQ')->insert($equipmentData);
  1082. } catch(\Illuminate\Database\QueryException $e) {
  1083. // Si es error de clave duplicada, regenerar ID
  1084. if($e->getCode() == 23000 || strpos($e->getMessage(), 'Duplicate entry') !== false) {
  1085. $equipmentData['PCEQ_IDPR'] = $this->generateNumericUniqueId($equipmentData['PCEQ_NULI']);
  1086. $attempt++;
  1087. continue;
  1088. }
  1089. // Si es otro tipo de error, re-lanzar
  1090. throw $e;
  1091. }
  1092. }
  1093. throw new Exception("No se pudo insertar el registro después de $maxAttempts intentos");
  1094. }
  1095. // MÉTODO AUXILIAR: Obtener nombre de hoja basado en tipo de código
  1096. private function getSheetNameFromCodeType($codeType) {
  1097. $codeTypes = [
  1098. '1' => 'CASO 1',
  1099. '2' => 'CASO 2',
  1100. '3' => 'CASO 3',
  1101. '4' => 'CASO 4',
  1102. '5' => 'CASO 5',
  1103. '6' => 'CASO 6'
  1104. ];
  1105. return $codeTypes[$codeType] ?? null;
  1106. }
  1107. // SOLUCIÓN 3: Usar upsert (insertar o actualizar)
  1108. private function upsertEquipmentData($equipmentData) {
  1109. return DB::table('S002V01TPCEQ')->updateOrInsert(
  1110. [
  1111. 'PCEQ_NULI' => $equipmentData['PCEQ_NULI'],
  1112. 'PCEQ_TICO' => $equipmentData['PCEQ_TICO'],
  1113. 'PCEQ_IDPR' => $equipmentData['PCEQ_IDPR']
  1114. ],
  1115. $equipmentData
  1116. );
  1117. }
  1118. // MÉTODO MODIFICADO PARA PROCESAR WORKSHEET CON MANEJO DE DUPLICADOS
  1119. private function processWorksheet($worksheet, $sheetConfig, $sheetName, $linea, $idUser, $cargaMap, $lruMap) {
  1120. $processedData = [];
  1121. $errors = [];
  1122. $count = 0;
  1123. $highestRow = $worksheet->getHighestRow();
  1124. $startRow = $sheetConfig['date_start_row'];
  1125. $fieldMapping = $sheetConfig['field_mapping'];
  1126. error_log(" [Process Worksheet] Procesando {$sheetName}: Filas {$startRow}-{$highestRow}");
  1127. for($row = $startRow; $row <= $highestRow; $row++) {
  1128. $rowData = $this->extractRowData($worksheet, $row, $fieldMapping, $sheetName);
  1129. if($this->isEmptyRow($rowData)) {
  1130. continue;
  1131. }
  1132. // **VALIDACIÓN CRÍTICA: Verificar que el código del frontend esté presente**
  1133. if (empty($rowData['PCEQ_CPGE']) || strlen(trim($rowData['PCEQ_CPGE'])) < 3) {
  1134. error_log("[Process Worksheet] {$sheetName} Fila {$row}: Código PCEQ_CPGE inválido: '" . ($rowData['PCEQ_CPGE'] ?? 'NULL') . "'");
  1135. // Continuar procesamiento pero con advertencia
  1136. } else {
  1137. error_log(" [Process Worksheet] {$sheetName} Fila {$row}: Código PCEQ_CPGE válido: '" . $rowData['PCEQ_CPGE'] . "'");
  1138. }
  1139. // Resolver nombres completos y acrónimos
  1140. $this->resolveEquipmentNames($rowData, $sheetName, $cargaMap, $lruMap);
  1141. $validation = $this->validateRowData($rowData, $sheetName, $row);
  1142. if(!$validation['valid']) {
  1143. $errors[] = "Hoja: $sheetName, Fila: $row - " . implode(', ', $validation['errors']);
  1144. continue;
  1145. }
  1146. // Preparar datos del equipo (AHORA usa el código del frontend)
  1147. $equipmentData = $this->prepareEquipmentData($rowData, $linea, $idUser, $sheetName);
  1148. // **LOG FINAL: Confirmar qué código se va a insertar**
  1149. error_log("[Final Data] {$sheetName} Fila {$row}: PCEQ_CPGE final = '" . $equipmentData['PCEQ_CPGE'] . "'");
  1150. $processedData[] = $equipmentData;
  1151. $count++;
  1152. }
  1153. error_log(" [Process Worksheet] {$sheetName} completado: {$count} equipos procesados, " . count($errors) . " errores");
  1154. return [
  1155. 'data' => $processedData,
  1156. 'errors' => $errors,
  1157. 'count' => $count
  1158. ];
  1159. }
  1160. public function validateFrontendCodes($filePath) {
  1161. try {
  1162. $spreadsheet = IOFactory::load($filePath);
  1163. $config = ExcelTemplateConfig::getTemplateConfigs()['TPCEQ'];
  1164. $codeValidation = [
  1165. 'valid' => true,
  1166. 'message' => '',
  1167. 'details' => []
  1168. ];
  1169. $sheetsToValidate = ['CASO 1', 'CASO 2', 'CASO 3', 'CASO 4', 'CASO 5', 'CASO 6'];
  1170. foreach($sheetsToValidate as $sheetName) {
  1171. if(!in_array($sheetName, $spreadsheet->getSheetNames())) {
  1172. continue;
  1173. }
  1174. $worksheet = $spreadsheet->getSheetByName($sheetName);
  1175. $sheetConfig = $config['worksheets'][$sheetName] ?? null;
  1176. if(!$sheetConfig) continue;
  1177. $highestRow = $worksheet->getHighestRow();
  1178. $startRow = $sheetConfig['date_start_row'];
  1179. $emptyCodeCount = 0;
  1180. $totalRows = 0;
  1181. for($row = $startRow; $row <= $highestRow; $row++) {
  1182. // Verificar si la fila tiene datos
  1183. $hasData = false;
  1184. foreach(['B', 'D', 'F', 'H'] as $col) {
  1185. $cellValue = $worksheet->getCell($col . $row)->getCalculatedValue();
  1186. if(!empty($cellValue)) {
  1187. $hasData = true;
  1188. break;
  1189. }
  1190. }
  1191. if(!$hasData) continue;
  1192. $totalRows++;
  1193. // Verificar código generado por frontend
  1194. $frontendCode = $this->extractFrontendGeneratedCode($worksheet, $row, $sheetName);
  1195. if(empty($frontendCode)) {
  1196. $emptyCodeCount++;
  1197. $codeValidation['details'][] = "Hoja {$sheetName}, Fila {$row}: Código faltante";
  1198. }
  1199. }
  1200. if($emptyCodeCount > 0) {
  1201. $codeValidation['valid'] = false;
  1202. $percentage = round(($emptyCodeCount / $totalRows) * 100, 1);
  1203. $codeValidation['details'][] = "Hoja {$sheetName}: {$emptyCodeCount} de {$totalRows} filas sin código ({$percentage}%)";
  1204. }
  1205. }
  1206. if(!$codeValidation['valid']) {
  1207. $codeValidation['message'] = 'Faltan códigos generados por el frontend. Asegúrate de procesar el archivo en el preview antes de validar.';
  1208. } else {
  1209. $codeValidation['message'] = 'Todos los códigos del frontend están presentes';
  1210. }
  1211. return $codeValidation;
  1212. } catch(Exception $e) {
  1213. return [
  1214. 'valid' => false,
  1215. 'message' => 'Error al validar códigos del frontend: ' . $e->getMessage(),
  1216. 'details' => []
  1217. ];
  1218. }
  1219. }
  1220. // Obtener todos los equipos de CARGA DE EQUIPOS
  1221. private function getAllCargaEquipments($spreadsheet) {
  1222. $equipments = [];
  1223. $sheet = $spreadsheet->getSheetByName('EQUIPAMIENTO');
  1224. if(!$sheet) return $equipments;
  1225. $highestRow = $sheet->getHighestRow();
  1226. $config = ExcelTemplateConfig::getTemplateConfigs()['TPCEQ']['worksheets']['EQUIPAMIENTO'];
  1227. $startRow = $config['date_start_row'];
  1228. for($row = $startRow; $row <= $highestRow; $row++) {
  1229. $equipment = $this->extractRowData($sheet, $row, $config['field_mapping'], 'EQUIPAMIENTO');
  1230. if(!$this->isEmptyRow($equipment)) {
  1231. $equipments[] = $equipment;
  1232. }
  1233. }
  1234. return $equipments;
  1235. }
  1236. // Obtener todos los equipos de LRU
  1237. private function getAllLruEquipments($spreadsheet) {
  1238. $equipments = [];
  1239. $sheet = $spreadsheet->getSheetByName('LRU');
  1240. if(!$sheet) return $equipments;
  1241. $highestRow = $sheet->getHighestRow();
  1242. $config = ExcelTemplateConfig::getTemplateConfigs()['TPCEQ']['worksheets']['LRU'];
  1243. $startRow = $config['date_start_row'];
  1244. for($row = $startRow; $row <= $highestRow; $row++) {
  1245. $equipment = $this->extractRowData($sheet, $row, $config['field_mapping'], 'LRU');
  1246. if(!$this->isEmptyRow($equipment)) {
  1247. $equipments[] = $equipment;
  1248. }
  1249. }
  1250. return $equipments;
  1251. }
  1252. // Buscar equipo por tipo y modelo
  1253. private function findEquipment($equipments, $tipo, $modelo) {
  1254. $normalize = function($value) {
  1255. return trim(strtoupper($value));
  1256. };
  1257. $tipoNorm = $normalize($tipo);
  1258. $modeloNorm = $normalize($modelo);
  1259. foreach($equipments as $equipment) {
  1260. $eqTipo = $normalize($equipment['PCEQ_TIEQ'] ?? '');
  1261. $eqModelo = $normalize($equipment['PCEQ_MOEQ'] ?? '');
  1262. // Buscar coincidencia exacta en tipo y modelo
  1263. if($eqTipo === $tipoNorm && $eqModelo === $modeloNorm) {
  1264. return $equipment;
  1265. }
  1266. }
  1267. return null;
  1268. }
  1269. private function resolveEquipmentNames(&$rowData, $sheetName, $cargaMap, $lruMap) {
  1270. if (!in_array($sheetName, ['CASO 1','CASO 2','CASO 3','CASO 4','CASO 5','CASO 6'])) {
  1271. return;
  1272. }
  1273. // Resolver nombres completos y campos adicionales para equipo principal
  1274. $acronimoTipo = $rowData['PCEQ_TIEQ'] ?? '';
  1275. $acronimoModelo = $rowData['PCEQ_MOEQ'] ?? '';
  1276. if ($acronimoTipo && $acronimoModelo) {
  1277. // Obtener nombre completo desde los mapas
  1278. $tipoCompleto = $cargaMap['equipos'][$acronimoTipo][$acronimoModelo] ?? $acronimoTipo;
  1279. $modeloCompleto = $cargaMap['modelos'][$acronimoModelo] ?? $acronimoModelo;
  1280. // Preservar ambos valores
  1281. $rowData['PCEQ_TIEQ_COMPLETO'] = $tipoCompleto; // Nombre completo para BD
  1282. $rowData['PCEQ_MOEQ_COMPLETO'] = $modeloCompleto; // Nombre completo para BD
  1283. $rowData['PCEQ_TIEQ_ACRONIMO'] = $acronimoTipo; // Acrónimo para generación de código
  1284. $rowData['PCEQ_MOEQ_ACRONIMO'] = $acronimoModelo; // Acrónimo para generación de código
  1285. // **NUEVO: Obtener PCEQ_CARA y PCEQ_COBA desde EQUIPAMIENTO**
  1286. $equipmentDetails = $this->findEquipmentDetailsByCodes($cargaMap, $acronimoTipo, $acronimoModelo);
  1287. if ($equipmentDetails) {
  1288. $rowData['PCEQ_CARA'] = $equipmentDetails['PCEQ_CARA'] ?? '';
  1289. $rowData['PCEQ_COBA'] = $equipmentDetails['PCEQ_COBA'] ?? '';
  1290. $rowData['PCEQ_NUSE'] = $equipmentDetails['PCEQ_NUSE'] ?? '';
  1291. $rowData['PCEQ_FVAR'] = $equipmentDetails['PCEQ_FVAR'] ?? '';
  1292. $rowData['PCEQ_OTCO'] = $equipmentDetails['PCEQ_OTCO'] ?? '';
  1293. } else {
  1294. error_log("[Equipment Details] No se encontraron detalles para Padre - {$acronimoTipo}/{$acronimoModelo}");
  1295. }
  1296. }
  1297. // Resolver nombres completos y campos adicionales para equipo hijo
  1298. $acronimoTipoHijo = $rowData['PCEQ_TIEQ_HIJO'] ?? '';
  1299. $acronimoModeloHijo = $rowData['PCEQ_MOEQ_HIJO'] ?? '';
  1300. if ($acronimoTipoHijo && $acronimoModeloHijo) {
  1301. $tipoHijoCompleto = $lruMap['equipos'][$acronimoTipoHijo][$acronimoModeloHijo] ?? $acronimoTipoHijo;
  1302. $modeloHijoCompleto = $lruMap['modelos'][$acronimoModeloHijo] ?? $acronimoModeloHijo;
  1303. $rowData['PCEQ_TIEQ_HIJO_COMPLETO'] = $tipoHijoCompleto;
  1304. $rowData['PCEQ_MOEQ_HIJO_COMPLETO'] = $modeloHijoCompleto;
  1305. $rowData['PCEQ_TIEQ_HIJO_ACRONIMO'] = $acronimoTipoHijo;
  1306. $rowData['PCEQ_MOEQ_HIJO_ACRONIMO'] = $acronimoModeloHijo;
  1307. // **NUEVO: Obtener PCEQ_CARA y PCEQ_COBA desde LRU para equipo hijo**
  1308. $equipmentDetailsHijo = $this->findEquipmentDetailsByCodes($lruMap, $acronimoTipoHijo, $acronimoModeloHijo);
  1309. if ($equipmentDetailsHijo) {
  1310. // Para equipos hijo, usar sufijo _HIJO para evitar sobreescribir los del padre
  1311. $rowData['PCEQ_CARA_HIJO'] = $equipmentDetailsHijo['PCEQ_CARA'] ?? '';
  1312. $rowData['PCEQ_COBA_HIJO'] = $equipmentDetailsHijo['PCEQ_COBA'] ?? '';
  1313. $rowData['PCEQ_NUSE_HIJO'] = $equipmentDetailsHijo['PCEQ_NUSE'] ?? '';
  1314. $rowData['PCEQ_FVAR_HIJO'] = $equipmentDetailsHijo['PCEQ_FVAR'] ?? '';
  1315. $rowData['PCEQ_OTCO_HIJO'] = $equipmentDetailsHijo['PCEQ_OTCO'] ?? '';
  1316. error_log(" [Equipment Details] Hijo - {$acronimoTipoHijo}/{$acronimoModeloHijo}: CARA='{$equipmentDetailsHijo['PCEQ_CARA']}', COBA='{$equipmentDetailsHijo['PCEQ_COBA']}'");
  1317. } else {
  1318. error_log("[Equipment Details] No se encontraron detalles para Hijo - {$acronimoTipoHijo}/{$acronimoModeloHijo}");
  1319. }
  1320. }
  1321. }
  1322. /**
  1323. * Nueva función para encontrar detalles del equipo basado en códigos
  1324. */
  1325. private function findEquipmentDetailsByCodes($equipmentMap, $acronimoTipo, $acronimoModelo) {
  1326. // Buscar en los datos crudos que se extrajeron originalmente
  1327. if (isset($equipmentMap['details'][$acronimoTipo][$acronimoModelo])) {
  1328. return $equipmentMap['details'][$acronimoTipo][$acronimoModelo];
  1329. }
  1330. return null;
  1331. }
  1332. // // MÉTODO ALTERNATIVO: Limpiar datos duplicados antes del procesamiento
  1333. // public function cleanDuplicateRecords(Request $request) {
  1334. // $validator = Validator::make($request->all(), [
  1335. // 'id_user' => 'required|string',
  1336. // 'linea' => 'required|integer',
  1337. // ]);
  1338. // if($validator->fails()) {
  1339. // return $this->responseController->makeResponse(
  1340. // true,
  1341. // "Se encontraron uno o más errores.",
  1342. // $this->responseController->makeErrors($validator->errors()->messages()),
  1343. // 401
  1344. // );
  1345. // }
  1346. // $form = $request->all();
  1347. // $idUser = $this->encryptionController->decrypt($form['id_user']);
  1348. // if(!$idUser) {
  1349. // return $this->responseController->makeResponse(true, "El id del usuario no fue desencriptado correctamente", [], 400);
  1350. // }
  1351. // try {
  1352. // DB::beginTransaction();
  1353. // // Eliminar registros duplicados manteniendo solo el más reciente
  1354. // $duplicatesDeleted = DB::statement("
  1355. // DELETE p1 FROM S002V01TPCEQ p1
  1356. // INNER JOIN S002V01TPCEQ p2
  1357. // WHERE p1.PCEQ_NULI = p2.PCEQ_NULI
  1358. // AND p1.PCEQ_TICO = p2.PCEQ_TICO
  1359. // AND p1.PCEQ_IDPR = p2.PCEQ_IDPR
  1360. // AND p1.PCEQ_FERE < p2.PCEQ_FERE
  1361. // AND p1.PCEQ_NULI = ?
  1362. // ", [$form['linea']]);
  1363. // DB::commit();
  1364. // return $this->responseController->makeResponse(false, "Duplicados eliminados exitosamente", [
  1365. // 'linea' => $form['linea'],
  1366. // 'duplicados_eliminados' => $duplicatesDeleted
  1367. // ]);
  1368. // } catch(Exception $e) {
  1369. // DB::rollBack();
  1370. // return $this->responseController->makeResponse(true, "Error al limpiar duplicados: " . $e->getMessage(), [], 500);
  1371. // }
  1372. // }
  1373. private function getCodeTypeFromSheet($sheetName) {
  1374. $codeTypes = [
  1375. 'CASO 1' => '1',
  1376. 'CASO 2' => '2',
  1377. 'CASO 3' => '3',
  1378. 'CASO 4' => '4',
  1379. 'CASO 5' => '5',
  1380. 'CASO 6' => '6',
  1381. ];
  1382. return $codeTypes[$sheetName] ?? '1';
  1383. }
  1384. private function addSheetSpecificFields(&$equipmentData, $rowData, $sheetName) {
  1385. switch($sheetName) {
  1386. case 'CASO 1':
  1387. case 'CASO 2':
  1388. $equipmentData['PCEQ_UBOR'] = $rowData['PCEQ_UBOR'] ?? '';
  1389. $equipmentData['PCEQ_NIOR'] = $rowData['PCEQ_NIOR'] ?? '';
  1390. $equipmentData['PCEQ_OCOR'] = $rowData['PCEQ_OCOR'] ?? '';
  1391. $equipmentData['PCEQ_ELOR'] = $rowData['PCEQ_ELOR'] ?? '';
  1392. $equipmentData['PCEQ_COOR'] = $rowData['PCEQ_COOR'] ?? '';
  1393. $equipmentData['PCEQ_FAMI'] = $rowData['PCEQ_FAMI'] ?? '';
  1394. $equipmentData['PCEQ_SUBF'] = $rowData['PCEQ_SUBF'] ?? '';
  1395. break;
  1396. case 'CASO 3':
  1397. $equipmentData['PCEQ_UBOR'] = $rowData['PCEQ_UBOR'] ?? '';
  1398. $equipmentData['PCEQ_UBDE'] = $rowData['PCEQ_UBDE'] ?? '';
  1399. $equipmentData['PCEQ_KIOR'] = $rowData['PCEQ_KIOR'] ?? ''; // PK Origen
  1400. $equipmentData['PCEQ_KIDE'] = $rowData['PCEQ_KIDE'] ?? '';
  1401. break;
  1402. case 'CASO 4':
  1403. $equipmentData['PCEQ_UBOR'] = $rowData['PCEQ_UBOR'] ?? '';
  1404. $equipmentData['PCEQ_UBDE'] = $rowData['PCEQ_UBDE'] ?? '';
  1405. $equipmentData['PCEQ_SEOR'] = $rowData['PCEQ_SEOR'] ?? 0;
  1406. $equipmentData['PCEQ_SEDE'] = $rowData['PCEQ_SEDE'] ?? 0;
  1407. $equipmentData['PCEQ_COOR'] = $rowData['PCEQ_COOR_ORIGEN'] ?? '';
  1408. $equipmentData['PCEQ_CODE'] = $rowData['PCEQ_COOR_DESTINO'] ?? '';
  1409. break;
  1410. case 'CASO 5':
  1411. case 'CASO 6':
  1412. $equipmentData['PCEQ_UBOR'] = $rowData['PCEQ_UBOR'] ?? '';
  1413. $equipmentData['PCEQ_NIOR'] = $rowData['PCEQ_NIOR'] ?? '';
  1414. $equipmentData['PCEQ_OCOR'] = $rowData['PCEQ_OCOR'] ?? '';
  1415. $equipmentData['PCEQ_ARTR'] = $rowData['PCEQ_ARTR'] ?? '';
  1416. $equipmentData['PCEQ_ELOR'] = $rowData['PCEQ_ELOR'] ?? '';
  1417. break;
  1418. }
  1419. }
  1420. // Método para obtener equipos en revisión
  1421. public function getPendingEquipments(Request $request) {
  1422. $validator = Validator::make($request->all(), [
  1423. 'id_user' => 'required|string',
  1424. 'linea' => 'required|integer',
  1425. ]);
  1426. if($validator->fails()) {
  1427. return $this->responseController->makeResponse(
  1428. true,
  1429. "Se encontraron uno o más errores.",
  1430. $this->responseController->makeErrors($validator->errors()->messages()),
  1431. 401
  1432. );
  1433. }
  1434. $form = $request->all();
  1435. $idUser = $this->encryptionController->decrypt($form['id_user']);
  1436. if(!$idUser) {
  1437. return $this->responseController->makeResponse(true, "El id del usuario no fue desencriptado correctamente", [], 400);
  1438. }
  1439. $pendingEquipments = DB::table('S002V01TPCEQ')
  1440. ->where('PCEQ_NULI', $form['linea'])
  1441. ->where('PCEQ_ESRE', 'Revisión')
  1442. ->orderBy('PCEQ_FERE', 'desc')
  1443. ->get();
  1444. $equipmentsArray = [];
  1445. foreach($pendingEquipments as $equipment) {
  1446. $equipmentsArray[] = [
  1447. 'id' => $this->encryptionController->encrypt($equipment->PCEQ_IDPR),
  1448. 'codigo' => $equipment->PCEQ_CPGE,
  1449. 'tipo' => $equipment->PCEQ_TIEQ,
  1450. 'modelo' => $equipment->PCEQ_MOEQ,
  1451. 'familia' => $equipment->PCEQ_FAMI,
  1452. 'subfamilia' => $equipment->PCEQ_SUBF,
  1453. 'estado' => $equipment->PCEQ_ESEQ,
  1454. 'fecha_registro' => $equipment->PCEQ_FERE,
  1455. 'estado_revision' => $equipment->PCEQ_ESRE
  1456. ];
  1457. }
  1458. return $this->responseController->makeResponse(false, 'EXITO.', $equipmentsArray);
  1459. }
  1460. //Métodos para mover a final ----------------------------------------------------------------------------------------------------------------------------------------------------------------------
  1461. public function transferEquipmentsToFinal($linea, $idUser) {
  1462. try {
  1463. DB::beginTransaction();
  1464. // Obtener equipos en estado "Revisión" desde la tabla temporal
  1465. $tempEquipments = DB::table('S002V01TPCEQ')
  1466. ->where('PCEQ_NULI', $linea)
  1467. ->where('PCEQ_ESRE', 'Revisión')
  1468. ->get();
  1469. if ($tempEquipments->isEmpty()) {
  1470. return [
  1471. 'success' => false,
  1472. 'message' => 'No se encontraron equipos para transferir',
  1473. 'transferred_count' => 0
  1474. ];
  1475. }
  1476. $transferredCount = 0;
  1477. $errors = [];
  1478. foreach ($tempEquipments as $tempEquip) {
  1479. try {
  1480. // Generar nuevo EQUI_IDEQ secuencial
  1481. $newEquiId = $this->generateNewEquiId($linea);
  1482. // Preparar datos para la tabla final
  1483. $finalEquipmentData = [
  1484. 'EQUI_NULI' => $tempEquip->PCEQ_NULI,
  1485. 'EQUI_FAMI' => $tempEquip->PCEQ_FAMI,
  1486. 'EQUI_SUBF' => $tempEquip->PCEQ_SUBF,
  1487. 'EQUI_TIPO' => $tempEquip->PCEQ_TIEQ,
  1488. 'EQUI_MODE' => $tempEquip->PCEQ_MOEQ,
  1489. 'EQUI_IDEQ' => $newEquiId,
  1490. 'EQUI_ESEQ' => $tempEquip->PCEQ_ESEQ,
  1491. 'EQUI_COEQ' => $tempEquip->PCEQ_CPGE, // Era el problema principal del CASO 3
  1492. 'EQUI_JERA' => $tempEquip->PCEQ_JERA,
  1493. 'EQUI_EQPA' => $tempEquip->PCEQ_EQPA,
  1494. 'EQUI_TICO' => $tempEquip->PCEQ_TICO,
  1495. // Campos de ubicación origen
  1496. 'EQUI_UBOR' => $tempEquip->PCEQ_UBOR,
  1497. 'EQUI_NIOR' => $tempEquip->PCEQ_NIOR,
  1498. 'EQUI_OCOR' => $tempEquip->PCEQ_OCOR,
  1499. 'EQUI_ELOR' => $tempEquip->PCEQ_ELOR,
  1500. 'EQUI_COOR' => $tempEquip->PCEQ_COOR,
  1501. 'EQUI_PCOR' => $tempEquip->PCEQ_PCOR ?? null,
  1502. // Campos de almacén (CASO 7) - verificar si existen
  1503. 'EQUI_ALMA' => $tempEquip->PCEQ_ALMA ?? null,
  1504. 'EQUI_AREA' => $tempEquip->PCEQ_AREA ?? null,
  1505. 'EQUI_NIVE' => $tempEquip->PCEQ_NIVE ?? null,
  1506. 'EQUI_ZONA' => $tempEquip->PCEQ_ZONA ?? null,
  1507. // Campos PCC - verificar si existen
  1508. 'EQUI_IPCC' => $tempEquip->PCEQ_IPCC ?? null,
  1509. 'EQUI_PPCC' => $tempEquip->PCEQ_PPCC ?? null,
  1510. 'EQUI_KIOR' => $this->parseVarcharValue($tempEquip->PCEQ_KIOR),
  1511. 'EQUI_SEOR' => $tempEquip->PCEQ_SEOR ?? null,
  1512. 'EQUI_ARTR' => $tempEquip->PCEQ_ARTR ?? null,
  1513. 'EQUI_TCOR' => $tempEquip->PCEQ_TCOR ?? null,
  1514. 'EQUI_CEOR' => $tempEquip->PCEQ_CEOR ?? null,
  1515. // Campos de ubicación destino
  1516. 'EQUI_UBDE' => $tempEquip->PCEQ_UBDE ?? null,
  1517. 'EQUI_NIDE' => $tempEquip->PCEQ_NIDE ?? null,
  1518. 'EQUI_OCDE' => $tempEquip->PCEQ_OCDE ?? null,
  1519. 'EQUI_ELDE' => $tempEquip->PCEQ_ELDE ?? null,
  1520. 'EQUI_CODE' => $tempEquip->PCEQ_CODE ?? null,
  1521. 'EQUI_PCDE' => $tempEquip->PCEQ_PCDE ?? null,
  1522. 'EQUI_KIDE' => $this->parseVarcharValue($tempEquip->PCEQ_KIDE),
  1523. 'EQUI_SEDE' => $tempEquip->PCEQ_SEDE ?? null,
  1524. 'EQUI_TCDE' => $tempEquip->PCEQ_TCDE ?? null,
  1525. 'EQUI_CEDE' => $tempEquip->PCEQ_CEDE ?? null,
  1526. // Campos de fechas y proveedor
  1527. 'EQUI_CRSE' => $tempEquip->PCEQ_CRSE ?? null,
  1528. 'EQUI_FEAD' => $tempEquip->PCEQ_FEAD,
  1529. 'EQUI_FIGA' => $tempEquip->PCEQ_FIGA,
  1530. 'EQUI_FTGA' => $tempEquip->PCEQ_FTGA,
  1531. 'EQUI_PREQ' => $tempEquip->PCEQ_PREQ ?? null,
  1532. 'EQUI_NUSE' => $tempEquip->PCEQ_NUSE ?? null,
  1533. // 'EQUI_COBA' => $tempEquip->PCEQ_COBA ?? null, // Código de barras
  1534. // 'EQUI_CARA' => $tempEquip->PCEQ_CARA ?? null, // Carácter
  1535. // 'EQUI_FVAR' => $tempEquip->PCEQ_FVAR ?? null, // Fecha vencimiento
  1536. // Campos de software
  1537. 'EQUI_DESO' => $tempEquip->PCEQ_DESO ?? null,
  1538. 'EQUI_VESO' => $tempEquip->PCEQ_VESO ?? null,
  1539. // Campos JSON
  1540. 'EQUI_HICO' => json_encode([]), // Historial de códigos (nuevo campo)
  1541. 'EQUI_GAIM' => $tempEquip->PCEQ_GAIM ?? json_encode([]),
  1542. 'EQUI_DORE' => $tempEquip->PCEQ_DORE ?? json_encode([]),
  1543. 'EQUI_OTCO' => $tempEquip->PCEQ_OTCO ?? json_encode([]),
  1544. // Estados y usuarios
  1545. 'EQUI_ESFU' => 'EF', // Estado funcionamiento por defecto
  1546. 'EQUI_USRE' => $tempEquip->PCEQ_USRE,
  1547. 'EQUI_FERE' => $tempEquip->PCEQ_FERE,
  1548. 'EQUI_USMO' => null,
  1549. 'EQUI_FEMO' => null
  1550. ];
  1551. // Debug para verificar campos críticos
  1552. error_log(" [Transfer Debug] PCEQ_IDPR: {$tempEquip->PCEQ_IDPR}");
  1553. error_log(" - PCEQ_CPGE: '{$tempEquip->PCEQ_CPGE}' -> EQUI_COEQ");
  1554. error_log(" - PCEQ_KIOR: '{$tempEquip->PCEQ_KIOR}' -> EQUI_KIOR: " . ($finalEquipmentData['EQUI_KIOR'] ?? 'NULL'));
  1555. error_log(" - PCEQ_KIDE: '{$tempEquip->PCEQ_KIDE}' -> EQUI_KIDE: " . ($finalEquipmentData['EQUI_KIDE'] ?? 'NULL'));
  1556. // Insertar en tabla final
  1557. DB::table('S002V01TEQUI')->insert($finalEquipmentData);
  1558. // Marcar como aprobado en tabla temporal
  1559. DB::table('S002V01TPCEQ')
  1560. ->where('PCEQ_IDPR', $tempEquip->PCEQ_IDPR)
  1561. ->where('PCEQ_NULI', $linea)
  1562. ->update([
  1563. 'PCEQ_ESRE' => 'Aprobado',
  1564. 'PCEQ_USMO' => $idUser,
  1565. 'PCEQ_FEMO' => now()->format('Y-m-d H:i:s')
  1566. ]);
  1567. $transferredCount++;
  1568. error_log("[Transfer] Equipo transferido: PCEQ_IDPR={$tempEquip->PCEQ_IDPR} -> EQUI_IDEQ={$newEquiId}");
  1569. } catch (Exception $e) {
  1570. $errors[] = "Error transfiriendo equipo PCEQ_IDPR {$tempEquip->PCEQ_IDPR}: " . $e->getMessage();
  1571. error_log(" [Transfer Error] PCEQ_IDPR={$tempEquip->PCEQ_IDPR}: " . $e->getMessage());
  1572. continue;
  1573. }
  1574. }
  1575. DB::commit();
  1576. return [
  1577. 'success' => true,
  1578. 'message' => "Equipos transferidos exitosamente",
  1579. 'transferred_count' => $transferredCount,
  1580. 'total_temp_equipments' => count($tempEquipments),
  1581. 'errors' => $errors
  1582. ];
  1583. } catch (Exception $e) {
  1584. DB::rollBack();
  1585. error_log(" [Transfer Error] Error general: " . $e->getMessage());
  1586. return [
  1587. 'success' => false,
  1588. 'message' => 'Error al transferir equipos: ' . $e->getMessage(),
  1589. 'transferred_count' => 0
  1590. ];
  1591. }
  1592. }
  1593. private function parseVarcharValue($value) {
  1594. if ($value === null || $value === '') {
  1595. return null;
  1596. }
  1597. return trim((string)$value);
  1598. }
  1599. private function parseNumericValue($value) {
  1600. if ($value === null || $value === '') {
  1601. return null;
  1602. }
  1603. // Si es string que representa un número
  1604. if (is_string($value) && is_numeric($value)) {
  1605. return (float)$value;
  1606. }
  1607. // Si ya es numérico
  1608. if (is_numeric($value)) {
  1609. return (float)$value;
  1610. }
  1611. return null;
  1612. }
  1613. private function generateNewEquiId($linea) {
  1614. $maxId = DB::table('S002V01TEQUI')
  1615. ->where('EQUI_NULI', $linea)
  1616. ->max('EQUI_IDEQ');
  1617. return $maxId ? ($maxId + 1) : 1;
  1618. }
  1619. public function transferEquipmentsToFinalTable(Request $request) {
  1620. $validator = Validator::make($request->all(), [
  1621. 'id_user' => 'required|string',
  1622. 'linea' => 'required|integer',
  1623. ]);
  1624. if($validator->fails()) {
  1625. return $this->responseController->makeResponse(
  1626. true,
  1627. "Se encontraron uno o más errores.",
  1628. $this->responseController->makeErrors($validator->errors()->messages()),
  1629. 401
  1630. );
  1631. }
  1632. $form = $request->all();
  1633. $idUser = $this->encryptionController->decrypt($form['id_user']);
  1634. if(!$idUser) {
  1635. return $this->responseController->makeResponse(true, "El id del usuario no fue desencriptado correctamente", [], 400);
  1636. }
  1637. // Verificar que el usuario existe
  1638. $usr = DB::table('S002V01TUSUA')->where([
  1639. ['USUA_IDUS', '=', $idUser],
  1640. ['USUA_NULI', '=', $form['linea']]
  1641. ])->first();
  1642. if(is_null($usr)) {
  1643. return $this->responseController->makeResponse(true, 'El usuario no está registrado', [], 404);
  1644. }
  1645. try {
  1646. $transferResult = $this->transferEquipmentsToFinal($form['linea'], $idUser);
  1647. if (!$transferResult['success']) {
  1648. return $this->responseController->makeResponse(true, $transferResult['message'], [], 500);
  1649. }
  1650. // Registrar actividad
  1651. $nowStr = Carbon::now('America/Mexico_city')->toDateTimeString();
  1652. $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
  1653. $this->functionsController->registerActivity(
  1654. $form['linea'],
  1655. 'S002V01M07GEEQ',
  1656. 'S002V01F01ADEQ',
  1657. 'S002V01P11REEQ',
  1658. 'Registro',
  1659. "El usuario $name (" . $usr->USUA_IDUS . ") transfirió {$transferResult['transferred_count']} equipos desde la tabla temporal a la tabla final.",
  1660. $idUser,
  1661. $nowStr
  1662. );
  1663. return $this->responseController->makeResponse(false, "Equipos transferidos exitosamente", [
  1664. 'equipos_transferidos' => $transferResult['transferred_count'],
  1665. 'total_equipos_temporales' => $transferResult['total_temp_equipments'],
  1666. 'errores' => $transferResult['errors'] ?? []
  1667. ]);
  1668. } catch (Exception $e) {
  1669. error_log(" [Manual Transfer Error] " . $e->getMessage());
  1670. return $this->responseController->makeResponse(true, "Error al transferir equipos: " . $e->getMessage(), [], 500);
  1671. }
  1672. }
  1673. }
  1674. class ExcelTemplateConfig {
  1675. public static function getTemplateConfigs() {
  1676. return [
  1677. 'TPCEQ' => [
  1678. 'model' => 'S002V01TPCEQ',
  1679. 'worksheets' => [
  1680. 'EQUIPAMIENTO' => [
  1681. 'table_start' => 'B9',
  1682. 'table_end' => 'P9',
  1683. 'header_row' => 7,
  1684. 'date_start_row' => 9,
  1685. 'field_mapping' => [
  1686. 'A' => '',
  1687. 'B' => 'PCEQ_OTCO', // Código Equivalente
  1688. 'C' => 'PCEQ_TIEQ', // Tipo / Descripción
  1689. 'D' => '', // Acrónimo del equipo
  1690. 'E' => 'PCEQ_MOEQ', // Acrónimo del modelo
  1691. 'F' => '', // Acrónimo del modelo
  1692. 'G' => '', // Id
  1693. 'H' => 'PCEQ_NUSE', // No. serie
  1694. 'I' => 'PCEQ_COBA', // No. código de barras
  1695. 'J' => 'PCEQ_CARA', // Carácter
  1696. 'K' => 'PCEQ_FVAR', // Fecha inicio de garantía
  1697. 'L' => '', // Fecha de vencimiento del artículo
  1698. ]
  1699. ],
  1700. 'LRU' => [
  1701. 'table_start' => 'B9',
  1702. 'table_end' => 'L9',
  1703. 'header_row' => 7,
  1704. 'date_start_row' => 9,
  1705. 'field_mapping' => [
  1706. 'A' => '',
  1707. 'B' => 'PCEQ_OTCO', // Tipo / Descripción
  1708. 'C' => 'PCEQ_TIEQ', // Acrónimo del equipo
  1709. 'D' => '', // Modelo completo
  1710. 'E' => 'PCEQ_MOEQ', // Acrónimo del modelo
  1711. 'F' => '', // Id
  1712. 'G' => '', // (ID) - no se usa
  1713. 'H' => 'PCEQ_NUSE', // No. serie
  1714. 'I' => 'PCEQ_COBA', // No. código de barras
  1715. 'J' => 'PCEQ_CARA', // Carácter
  1716. 'K' => 'PCEQ_FTGA', // Fecha de vencimiento del artículo
  1717. 'L' => '', // Etiqueta final del equipo
  1718. ]
  1719. ],
  1720. 'CASO 1' => [
  1721. 'table_start' => 'B8',
  1722. 'table_end' => 'AI8',
  1723. 'header_row' => 7,
  1724. 'date_start_row' => 8,
  1725. 'field_mapping' => [
  1726. 'A' => '',
  1727. 'B' => 'PCEQ_NULI', // Línea
  1728. 'C' => '.', // .
  1729. 'D' => 'PCEQ_UBOR', // Ubicación
  1730. 'E' => '.', // .
  1731. 'F' => 'PCEQ_NIOR', // Nivel
  1732. 'G' => '.', // .
  1733. 'H' => 'PCEQ_OCOR', // Ocupación
  1734. 'I' => '.', // .
  1735. 'J' => 'PCEQ_ELOR', // Elemento
  1736. 'K' => '+', // +
  1737. 'L' => '', // Coordenadas plano
  1738. 'M' => '', // Coordenadas detalle
  1739. 'N' => '', // Coordenadas de posición
  1740. 'O' => '_', // _
  1741. 'P' => 'PCEQ_FAMI', // Familia
  1742. 'Q' => '.', // .
  1743. 'R' => 'PCEQ_SUBF', // Subfamilia
  1744. 'S' => '.', // .
  1745. 'T' => 'PCEQ_ESEQ', // Estado
  1746. 'U' => '.', // .
  1747. 'V' => 'PCEQ_TIEQ', // Tipo
  1748. 'W' => '-', // -
  1749. 'X' => 'PCEQ_MOEQ', // Modelo
  1750. 'Y' => '-', // -
  1751. 'Z' => '', // ID
  1752. 'AA' => '.', // .
  1753. 'AB' => 'PCEQ_TIEQ_HIJO', // Tipo
  1754. 'AC' => '-', // -
  1755. 'AD' => 'PCEQ_MOEQ_HIJO', // Modelo
  1756. 'AE' => '-', // -
  1757. 'AF' => '', // ID
  1758. 'AG' => '', // Vacío
  1759. 'AH' => 'PCEQ_CPGE', // Código completo SAM
  1760. 'AI' => 'PCEQ_OTCO', // Código equivalente
  1761. ]
  1762. ],
  1763. 'CASO 2' => [
  1764. 'table_start' => 'B8',
  1765. 'table_end' => 'AI8',
  1766. 'header_row' => 7,
  1767. 'date_start_row' => 8,
  1768. 'field_mapping' => [
  1769. 'A' => '',
  1770. 'B' => 'PCEQ_NULI', // Línea
  1771. 'C' => '.', // .
  1772. 'D' => 'PCEQ_UBOR', // Ubicación
  1773. 'E' => '.', // .
  1774. 'F' => 'PCEQ_NIOR', // Nivel
  1775. 'G' => '.', // .
  1776. 'H' => 'PCEQ_OCOR', // Ocupación
  1777. 'I' => '.', // .
  1778. 'J' => 'PCEQ_ELOR', // Elemento
  1779. 'K' => '+', // +
  1780. 'L' => '', // Coordenadas plano
  1781. 'M' => '', // Coordenadas detalle
  1782. 'N' => '', // Coordenadas de posición
  1783. 'O' => '_', // _
  1784. 'P' => 'PCEQ_FAMI', // Familia
  1785. 'Q' => '.', // .
  1786. 'R' => 'PCEQ_SUBF', // Subfamilia
  1787. 'S' => '.', // .
  1788. 'T' => 'PCEQ_ESEQ', // Estado
  1789. 'U' => '.', // .
  1790. 'V' => 'PCEQ_TIEQ', // Tipo
  1791. 'W' => '-', // -
  1792. 'X' => 'PCEQ_MOEQ', // Modelo
  1793. 'Y' => '-', // -
  1794. 'Z' => '', // ID
  1795. 'AA' => '.', // .
  1796. 'AB' => 'PCEQ_TIEQ_HIJO', // Tipo
  1797. 'AC' => '-', // -
  1798. 'AD' => 'PCEQ_MOEQ_HIJO', // Modelo
  1799. 'AE' => '-', // -
  1800. 'AF' => '', // ID
  1801. 'AG' => '', // Vacío
  1802. 'AH' => 'PCEQ_CPGE', // Código completo SAM
  1803. 'AI' => 'PCEQ_OTCO', // Código equivalente
  1804. ]
  1805. ],
  1806. 'CASO 3' => [
  1807. 'table_start' => 'B8',
  1808. 'table_end' => 'AQ8',
  1809. 'header_row' => 7,
  1810. 'date_start_row' => 8,
  1811. 'field_mapping' => [
  1812. 'A' => '',
  1813. 'B' => 'PCEQ_NULI', // Línea
  1814. 'C' => '.', // .
  1815. 'D' => 'PCEQ_UBOR', // Ubicación origen
  1816. 'E' => '.', // .
  1817. 'F' => 'PCEQ_NIOR', // Nivel origen
  1818. 'G' => '.', // .
  1819. 'H' => 'PCEQ_OCOR', // Ocupación origen
  1820. 'I' => '.', // .
  1821. 'J' => 'PCEQ_ELOR', // Elemento origen
  1822. 'K' => '.', // .
  1823. 'L' => 'PCEQ_KIOR', // PK origen
  1824. 'M' => ':', // :
  1825. 'N' => 'PCEQ_UBDE', // Ubicación destino
  1826. 'O' => '.', // .
  1827. 'P' => 'PCEQ_NIDE', // Nivel destino
  1828. 'Q' => '.', // .
  1829. 'R' => 'PCEQ_OCDE', // Ocupación destino
  1830. 'S' => '.', // .
  1831. 'T' => 'PCEQ_ELDE', // Elemento destino
  1832. 'U' => '.', // .
  1833. 'V' => 'PCEQ_KIDE', // PK destino
  1834. 'W' => '-', // -
  1835. 'X' => 'PCEQ_FAMI', // Familia
  1836. 'Y' => '-', // -
  1837. 'Z' => 'PCEQ_SUBF', // Subfamilia
  1838. 'AA' => '.', // .
  1839. 'AB' => 'PCEQ_ESEQ', // Estado
  1840. 'AC' => '-', // -
  1841. 'AD' => 'PCEQ_TIEQ', // Tipo
  1842. 'AE' => '-', // -
  1843. 'AF' => 'PCEQ_MOEQ', // Modelo
  1844. 'AG' => '-', // -
  1845. 'AH' => '', // ID
  1846. 'AI' => '.', // .
  1847. 'AJ' => 'PCEQ_TIEQ_HIJO', // Tipo
  1848. 'AK' => '-', // -
  1849. 'AL' => 'PCEQ_MOEQ_HIJO', // Modelo
  1850. 'AM' => '-', // -
  1851. 'AN' => 'PCEQ_IDPR', // ID
  1852. 'AO' => '-', // -
  1853. 'AP' => 'PCEQ_CPGE', // Código completo
  1854. 'AQ' => 'PCEQ_OTCO', // Código equivalente
  1855. ]
  1856. ],
  1857. 'CASO 4' => [
  1858. 'table_start' => 'B8',
  1859. 'table_end' => 'AY8',
  1860. 'header_row' => 7,
  1861. 'date_start_row' => 8,
  1862. 'field_mapping' => [
  1863. 'A' => '',
  1864. 'B' => 'PCEQ_NULI', // Línea
  1865. 'C' => '.', // .
  1866. 'D' => 'PCEQ_UBOR', // Ubicación origen
  1867. 'E' => '.', // .
  1868. 'F' => 'PCEQ_NIOR', // Nivel origen
  1869. 'G' => '.', // .
  1870. 'H' => 'PCEQ_OCOR', // Ocupación origen
  1871. 'I' => '.', // .
  1872. 'J' => 'PCEQ_ELOR', // Elemento origen
  1873. 'K' => '.', // .
  1874. 'L' => 'PCEQ_SEOR', // Secuencial origen
  1875. 'M' => '.', // .
  1876. 'N' => '', // Coordenadas plano (concatenar con O,P)
  1877. 'O' => '', // Coordenadas detalle
  1878. 'P' => '', // Coordenadas de posición
  1879. 'Q' => ':', // :
  1880. 'R' => 'PCEQ_UBDE', // Ubicación destino
  1881. 'S' => '.', // .
  1882. 'T' => 'PCEQ_NIDE', // Nivel destino
  1883. 'U' => '.', // .
  1884. 'V' => 'PCEQ_OCDE', // Ocupación destino
  1885. 'W' => '.', // .
  1886. 'X' => 'PCEQ_ELDE', // Elemento destino
  1887. 'Y' => '.', // .
  1888. 'Z' => 'PCEQ_SEDE', // Secuencial destino
  1889. 'AA' => '+', // +
  1890. 'AB' => '', // Coordenadas plano (concatenar con AC,AD)
  1891. 'AC' => '', // Coordenadas detalle
  1892. 'AD' => '', // Coordenadas de posición
  1893. 'AE' => '_', // _
  1894. 'AF' => 'PCEQ_FAMI', // Familia
  1895. 'AG' => '.', // .
  1896. 'AH' => 'PCEQ_SUBF', // Subfamilia
  1897. 'AI' => '.', // .
  1898. 'AJ' => 'PCEQ_ESEQ', // Estado
  1899. 'AK' => '.', // .
  1900. 'AL' => 'PCEQ_TIEQ', // Tipo
  1901. 'AM' => '-', // -
  1902. 'AN' => 'PCEQ_MOEQ', // Modelo
  1903. 'AO' => '-', // -
  1904. 'AP' => '', // ID
  1905. 'AQ' => '.', // .
  1906. 'AR' => 'PCEQ_TIEQ_HIJO', // Tipo
  1907. 'AS' => '-', // -
  1908. 'AT' => 'PCEQ_MOEQ_HIJO', // Modelo
  1909. 'AU' => '-', // -
  1910. 'AV' => '', // ID
  1911. 'AW' => '', // Vacío
  1912. 'AX' => 'PCEQ_CPGE', // Código completo
  1913. 'AY' => 'PCEQ_OTCO', // Código equivalente
  1914. ]
  1915. ],
  1916. 'CASO 5' => [
  1917. 'table_start' => 'B8',
  1918. 'table_end' => 'AG8',
  1919. 'header_row' => 7,
  1920. 'date_start_row' => 8,
  1921. 'field_mapping' => [
  1922. 'A' => '',
  1923. 'B' => 'PCEQ_NULI', // Línea
  1924. 'C' => '.', // .
  1925. 'D' => 'PCEQ_UBOR', // Ubicación
  1926. 'E' => '.', // .
  1927. 'F' => 'PCEQ_NIOR', // Nivel
  1928. 'G' => '.', // .
  1929. 'H' => 'PCEQ_OCOR', // Ocupación
  1930. 'I' => '.', // .
  1931. 'J' => 'PCEQ_ARTR', // Área
  1932. 'K' => '.', // .
  1933. 'L' => 'PCEQ_ELOR', // Elemento
  1934. 'M' => '_', // _
  1935. 'N' => 'PCEQ_FAMI', // Familia
  1936. 'O' => '.', // .
  1937. 'P' => 'PCEQ_SUBF', // Subfamilia
  1938. 'Q' => '.', // .
  1939. 'R' => 'PCEQ_ESEQ', // Estado
  1940. 'S' => '.', // .
  1941. 'T' => 'PCEQ_TIEQ', // Tipo
  1942. 'U' => '-', // -
  1943. 'V' => 'PCEQ_MOEQ', // Modelo
  1944. 'W' => '-', // -
  1945. 'X' => '', // ID
  1946. 'Y' => '.', // .
  1947. 'Z' => 'PCEQ_TIEQ_HIJO', // Tipo LRU
  1948. 'AA' => '-', // -
  1949. 'AB' => 'PCEQ_MOEQ_HIJO', // Modelo LRU
  1950. 'AC' => '-', // -
  1951. 'AD' => '', // ID LRU
  1952. 'AE' => '', // Vacío
  1953. 'AF' => 'PCEQ_CPGE', // Código completo
  1954. 'AG' => 'PCEQ_OTCO', // Código equivalente
  1955. ]
  1956. ],
  1957. 'CASO 6' => [
  1958. 'table_start' => '',
  1959. 'table_end' => '',
  1960. 'header_row' => 7,
  1961. 'date_start_row' => 8,
  1962. 'field_mapping' => [
  1963. 'A' => '', // Vacío
  1964. 'B' => 'PCEQ_NULI', // Linea
  1965. 'C' => '.', // .
  1966. 'D' => 'PCEQ_UBOR', // Ubicación
  1967. 'E' => '.', // .
  1968. 'F' => 'PCEQ_NIOR', // Nivel
  1969. 'G' => '.', // .
  1970. 'H' => 'PCEQ_OCOR', // Ocupación
  1971. 'I' => '.', // .
  1972. 'J' => 'PCEQ_ELOR', // Elemento
  1973. 'K' => '.', // .
  1974. 'L' => 'PCEQ_COOR', // Posición
  1975. 'M' => '_', // _
  1976. 'N' => 'PCEQ_FAMI', // Familia
  1977. 'O' => '.', // .
  1978. 'P' => 'PCEQ_SUBF', // Subfamilia
  1979. 'Q' => '.', // .
  1980. 'R' => 'PCEQ_ESEQ', // Estado
  1981. 'S' => '.', // .
  1982. 'T' => 'PCEQ_TIEQ', // Tipo
  1983. 'U' => '-', // -
  1984. 'V' => 'PCEQ_MOEQ', // Modelo
  1985. 'W' => '-', // -
  1986. 'X' => 'PCEQ_IDPR', // ID
  1987. 'Y' => '.', // .
  1988. 'Z' => 'PCEQ_TIEQ_HIJO', // Tipo
  1989. 'AA' => '-', // -
  1990. 'AB' => 'PCEQ_MOEQ_HIJO', // Modelo
  1991. 'AC' => '-', // -
  1992. 'AD' => 'PCEQ_LRID', // ID
  1993. 'AE' => '', // Vacío
  1994. 'AF' => 'PCEQ_CPGE', // Código completo
  1995. 'AG' => 'PCEQ_OTCO', // Código equivalente
  1996. ]
  1997. ]
  1998. ]
  1999. ],
  2000. ];
  2001. }
  2002. };