| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860 |
- <?php
- namespace App\Http\Controllers;
- use Illuminate\Http\Request;
- use Illuminate\Support\Facades\DB;
- use Illuminate\Support\Facades\Validator;
- use Illuminate\Support\Carbon;
- use Exception;
- use Illuminate\Support\Facades\Log;
- use PhpOffice\PhpSpreadsheet\Spreadsheet;
- use PhpOffice\PhpSpreadsheet\IOFactory;
- use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
- class TemplatesManagementController extends Controller {
- private $responseController;
- private $encryptionController;
- private $functionsController;
- private $resourcesController;
- private $documentManagementController;
- private $templatesUbic;
- public function __construct(){
- $this->responseController = new ResponseController();
- $this->encryptionController = new EncryptionController();
- $this->functionsController = new FunctionsController();
- $this->resourcesController = new ResourcesController();
- $this->documentManagementController = new DocumentManagementController();
- $this->templatesUbic = app_path('Http/Controllers');
- }
- /**
- * Validar y procesar plantilla Excel de equipamientos
- * Recibe el ID del archivo temporal ya cargado
- */
- public function validateAndProcessExcelTemplate(Request $request) {
- DB::enableQueryLog();
-
- $validator = Validator::make($request->all(), [
- 'id_user' => 'required|string',
- 'id_file' => 'required|string',
- 'linea' => 'required|integer',
- ]);
- if($validator->fails()){
- return $this->responseController->makeResponse(
- true,
- "Se encontraron uno o más errores.",
- $this->responseController->makeErrors($validator->errors()->messages()),
- 401
- );
- }
- $form = $request->all();
- $idUser = '0000000001';
-
- if(!$idUser){
- return $this->responseController->makeResponse(true, "El id del usuario no fue desencriptado correctamente", [], 400);
- }
- $usr = DB::table('S002V01TUSUA')->where([
- ['USUA_IDUS', '=', $idUser],
- ['USUA_NULI', '=', $form['linea']]
- ])->first();
- if(is_null($usr)){
- return $this->responseController->makeResponse(true, 'El usuario no está registrado', [], 404);
- }
- // Obtener archivo temporal
- $fileIdDecrypted = $this->encryptionController->decrypt($form['id_file']);
- $tempFile = DB::table('S002V01TARTE')->where([
- ['ARTE_IDAR', '=', $fileIdDecrypted],
- ['ARTE_NULI', '=', $form['linea']]
- ])->first();
-
- if(is_null($tempFile)){
- return $this->responseController->makeResponse(true, 'El archivo temporal no fue encontrado', [], 404);
- }
- try {
- // Validar estructura del Excel
- $structureValidation = $this->validateExcelStructure($tempFile->ARTE_UBTE);
- if(!$structureValidation['valid']) {
- return $this->responseController->makeResponse(true, $structureValidation['message'], [], 400);
- }
- // Procesar contenido del Excel
- $spreadsheet = IOFactory::load($tempFile->ARTE_UBTE);
- $config = ExcelTemplateConfig::getTemplateConfigs()['TPCEQ'];
- $acronymMappings = $this->extractAcronymMappings($spreadsheet);
- $cargaMap = $acronymMappings['carga'];
- $lruMap = $acronymMappings['lru'];
- $sheetsToProcess = [
- 'CASO 1', 'CASO 2', 'CASO 3',
- 'CASO 4', 'CASO 5', 'CASO 6'
- ];
- $processedData = [];
- $errors = [];
- $successCount = 0;
-
- DB::beginTransaction();
-
- foreach($sheetsToProcess as $sheetName) {
- // Verificar si la hoja existe en el documento
- if(!in_array($sheetName, $spreadsheet->getSheetNames())) {
- $errors[] = "Hoja requerida no encontrada: $sheetName";
- continue;
- }
-
- // Obtener configuración de la hoja
- $sheetConfig = $config['worksheets'][$sheetName] ?? null;
- if(!$sheetConfig) {
- $errors[] = "Configuración no encontrada para hoja: $sheetName";
- continue;
- }
- $worksheet = $spreadsheet->getSheetByName($sheetName);
- $result = $this->processWorksheet(
- $worksheet,
- $sheetConfig,
- $sheetName,
- $form['linea'],
- $idUser,
- $cargaMap,
- $lruMap
- );
-
- $processedData = array_merge($processedData, $result['data']);
- $errors = array_merge($errors, $result['errors']);
- $successCount += $result['count'];
- }
-
- if(!empty($errors) && empty($processedData)) {
- DB::rollBack();
- return $this->responseController->makeResponse(true, "Errores en el procesamiento: " . implode('; ', array_slice($errors, 0, 5)), [], 400);
- }
-
- // Insertar datos procesados en la tabla temporal de equipamientos
- foreach($processedData as $data) {
- DB::table('S002V01TPCEQ')->insert($data);
- }
-
- DB::commit();
-
- // Registrar actividad
- $nowStr = Carbon::now('America/Mexico_city')->toDateTimeString();
- $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
-
- $actions = DB::getQueryLog();
- $idac = $this->functionsController->registerActivity(
- $form['linea'],
- 'S002V01M07GEEQ',
- 'S002V01F01ADEQ',
- 'S002V01P11REEQ',
- 'Procesamiento',
- "El usuario $name (" . $usr->USUA_IDUS . ") procesó $successCount equipos desde el archivo {$tempFile->ARTE_NOAR}.",
- $idUser,
- $nowStr,
- );
-
- $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']);
-
- $responseData = [
- 'equipos_procesados' => $successCount,
- 'archivo' => $tempFile->ARTE_NOAR,
- 'id_archivo' => $form['id_file']
- ];
-
- if(!empty($errors)) {
- $responseData['advertencias'] = array_slice($errors, 0, 10);
- }
-
- return $this->responseController->makeResponse(false, "Procesamiento exitoso", $responseData);
-
- } catch(Exception $e) {
- DB::rollBack();
- return $this->responseController->makeResponse(true, "Error al procesar el archivo: " . $e->getMessage(), [], 500);
- }
- }
- private function extractAcronymMappings($spreadsheet) {
- $mappings = [
- 'carga' => [
- 'equipos' => [], // [acronimo_equipo][acronimo_modelo] = tipo_completo
- 'modelos' => [] // [acronimo_modelo] = modelo_completo
- ],
- 'lru' => [
- 'equipos' => [],
- 'modelos' => []
- ]
- ];
-
- // Normalizar nombres de hojas
- $sheetNames = array_map('strtolower', $spreadsheet->getSheetNames());
-
- // 1. Encontrar hoja CARGA DE EQUIPOS (case-insensitive)
- $cargaSheet = null;
- foreach ($spreadsheet->getAllSheets() as $sheet) {
- if (strtolower(trim($sheet->getTitle())) === 'equipamiento') {
- $cargaSheet = $sheet;
- break;
- }
- }
- // 2. Procesar hoja CARGA DE EQUIPOS si existe
- if ($cargaSheet) {
- $highestRow = $cargaSheet->getHighestRow();
- for ($row = 9; $row <= $highestRow; $row++) {
- $acronimoEquipo = $this->getCellValue($cargaSheet, 'D', $row);
- $tipoCompleto = $this->getCellValue($cargaSheet, 'C', $row);
- $modeloCompleto = $this->getCellValue($cargaSheet, 'E', $row);
- $acronimoModelo = $this->getCellValue($cargaSheet, 'F', $row);
-
- if (!empty($acronimoEquipo) && !empty($acronimoModelo)) {
- // Almacenar combinación equipo+modelo
- if (!isset($mappings['carga']['equipos'][$acronimoEquipo])) {
- $mappings['carga']['equipos'][$acronimoEquipo] = [];
- }
- $mappings['carga']['equipos'][$acronimoEquipo][$acronimoModelo] = $tipoCompleto;
- }
-
- if (!empty($acronimoModelo) && !empty($modeloCompleto)) {
- $mappings['carga']['modelos'][$acronimoModelo] = $modeloCompleto;
- }
- }
- }
- // 3. Procesar hoja LRU (usando el mismo método robusto)
- $lruSheet = null;
- foreach ($spreadsheet->getAllSheets() as $sheet) {
- if (strtolower(trim($sheet->getTitle())) === 'lru') {
- $lruSheet = $sheet;
- break;
- }
- }
- if ($lruSheet) {
- $highestRow = $lruSheet->getHighestRow();
- for ($row = 9; $row <= $highestRow; $row++) {
- $acronimoEquipo = $this->getCellValue($lruSheet, 'D', $row);
- $tipoCompleto = $this->getCellValue($lruSheet, 'C', $row);
- $modeloCompleto = $this->getCellValue($lruSheet, 'E', $row);
- $acronimoModelo = $this->getCellValue($lruSheet, 'F', $row);
-
- if (!empty($acronimoEquipo) && !empty($acronimoModelo)) {
- if (!isset($mappings['lru']['equipos'][$acronimoEquipo])) {
- $mappings['lru']['equipos'][$acronimoEquipo] = [];
- }
- $mappings['lru']['equipos'][$acronimoEquipo][$acronimoModelo] = $tipoCompleto;
- }
-
- if (!empty($acronimoModelo) && !empty($modeloCompleto)) {
- $mappings['lru']['modelos'][$acronimoModelo] = $modeloCompleto;
- }
- }
- }
- return $mappings;
- }
- // Nueva función para obtener valores de celda robusta
- private function getCellValue($worksheet, $column, $row) {
- try {
- $cell = $worksheet->getCell($column . $row);
- return trim($cell->getFormattedValue());
- } catch (\Exception $e) {
- // \Log::error("Error leyendo celda $column$row: " . $e->getMessage());
- return '';
- }
- }
- /**
- * Validar solo la estructura del Excel (sin procesar datos)
- */
- public function validateExcelStructureOnly(Request $request) {
- $validator = Validator::make($request->all(), [
- 'id_user' => 'required|string',
- 'id_file' => 'required|string',
- 'linea' => 'required|integer',
- ]);
- if($validator->fails()){
- return $this->responseController->makeResponse(
- true,
- "Se encontraron uno o más errores.",
- $this->responseController->makeErrors($validator->errors()->messages()),
- 401
- );
- }
- $form = $request->all();
- $idUser = $this->encryptionController->decrypt($form['id_user']);
-
- if(!$idUser){
- return $this->responseController->makeResponse(true, "El id del usuario no fue desencriptado correctamente", [], 400);
- }
- // Obtener archivo temporal
- $fileIdDecrypted = $this->encryptionController->decrypt($form['id_file']);
- $tempFile = DB::table('S002V01TARTE')->where([
- ['ARTE_IDAR', '=', $fileIdDecrypted],
- ['ARTE_NULI', '=', $form['linea']]
- ])->first();
-
- if(is_null($tempFile)){
- return $this->responseController->makeResponse(true, 'El archivo temporal no fue encontrado', [], 404);
- }
- // Validar solo la estructura
- $structureValidation = $this->validateExcelStructure($tempFile->ARTE_UBTE);
- if(!$structureValidation['valid']) {
- return $this->responseController->makeResponse(true, $structureValidation['message'], [], 400);
- }
- return $this->responseController->makeResponse(false, "Estructura del archivo válida", [
- 'archivo' => $tempFile->ARTE_NOAR,
- 'validado' => true
- ]);
- }
- private function validateExcelStructure($filePath) {
- try {
- $spreadsheet = IOFactory::load($filePath);
- $config = ExcelTemplateConfig::getTemplateConfigs()['TPCEQ'];
-
- $requiredSheets = array_keys($config['worksheets']);
- $existingSheets = $spreadsheet->getSheetNames();
-
- // Verificar que existan las hojas requeridas
- $missingSheets = array_diff($requiredSheets, $existingSheets);
- if(!empty($missingSheets)) {
- return [
- 'valid' => false,
- 'message' => 'Tu documento no cumple con las hojas requeridas de la plantilla'
- ];
- }
- // Validar headers de cada hoja
- foreach($config['worksheets'] as $sheetName => $sheetConfig) {
- if(!in_array($sheetName, $existingSheets)) continue;
-
- $worksheet = $spreadsheet->getSheetByName($sheetName);
- $headerValidation = $this->validateSheetHeaders($worksheet, $sheetConfig, $sheetName);
-
- if(!$headerValidation['valid']) {
- return [
- 'valid' => false,
- 'message' => 'Tu documento tiene error en los Headers, revísalos e intentalo de nuevo'
- ];
- }
- // Validar que tenga datos (solo para CARGA DE EQUIPOS)
- if($sheetName === 'CARGA DE EQUIPOS') {
- $dataValidation = $this->validateSheetHasData($worksheet, $sheetName, $sheetConfig);
- if(!$dataValidation['valid']) {
- return $dataValidation;
- }
- }
- }
- return ['valid' => true, 'message' => 'Estructura válida'];
-
- } catch(Exception $e) {
- return [
- 'valid' => false,
- 'message' => 'Error al validar la estructura del archivo: ' . $e->getMessage()
- ];
- }
- }
- private function validateSheetHeaders($worksheet, $sheetConfig, $sheetName) {
- // Para CATÁLOGOS usar validación especial
- if($sheetName === 'CATÁLOGOS') {
- return $this->validateCatalogosSheet($worksheet);
- }
-
- $headerRow = $sheetConfig['header_row'] ?? 4;
- $fieldMapping = $sheetConfig['field_mapping'];
-
- // Definir headers esperados según la configuración de Angular
- $expectedHeaders = $this->getExpectedHeaders($sheetName);
-
- if(empty($expectedHeaders)) {
- return ['valid' => true, 'message' => "No hay headers específicos para validar en $sheetName"];
- }
- foreach($expectedHeaders as $column => $expectedHeader) {
- $cellValue = $worksheet->getCell($column . $headerRow)->getCalculatedValue();
- $actualHeader = $cellValue ? trim((string)$cellValue) : '';
-
- if($actualHeader !== $expectedHeader) {
- return [
- 'valid' => false,
- 'message' => "Error en header de $sheetName, columna $column: esperado '$expectedHeader', encontrado '$actualHeader'"
- ];
- }
- }
-
- return ['valid' => true, 'message' => "Headers válidos para $sheetName"];
- }
- private function validateCatalogosSheet($worksheet) {
- $expectedHeaders = [
- 'B' => 'FAMILIA',
- 'C' => 'ACRÓNIMO',
- 'E' => 'SUBFAMILIA',
- 'F' => 'ACRÓNIMO',
- 'G' => 'SUBFAMILY',
- 'I' => 'UBICACIONES (FRENTES)',
- 'J' => 'CÓDIGO',
- 'L' => 'RMS',
- 'M' => 'ELEMENTO',
- 'N' => 'CÓDIGO',
- 'P' => 'OCUPACIÓN',
- 'Q' => 'CÓDIGO',
- 'S' => 'ESTADO',
- 'T' => 'ACRÓNIMO'
- ];
- foreach($expectedHeaders as $column => $expectedHeader) {
- $cellValue = $worksheet->getCell($column . '5')->getCalculatedValue();
- $actualHeader = $cellValue ? trim((string)$cellValue) : '';
-
- if($actualHeader !== $expectedHeader) {
- return [
- 'valid' => false,
- 'message' => "Error en CATÁLOGOS, fila 5, columna $column: esperado '$expectedHeader', encontrado '$actualHeader'"
- ];
- }
- }
- return ['valid' => true, 'message' => 'Headers válidos para CATÁLOGOS'];
- }
- private function validateSheetHasData($worksheet, $sheetName, $sheetConfig) {
- try {
- $range = $worksheet->calculateWorksheetDimension();
- $highestRow = $worksheet->getHighestRow();
-
- $dataStartRow = $sheetConfig['date_start_row'] ?? 9;
-
- if($highestRow < $dataStartRow) {
- return [
- 'valid' => false,
- 'message' => "La hoja '$sheetName' no contiene datos. Se requiere al menos un registro con información."
- ];
- }
- // Verificar que hay al menos una fila con datos
- $hasData = false;
- $mainColumns = ['B', 'D', 'F', 'G']; // Columnas principales para verificar
-
- for($row = $dataStartRow; $row <= $highestRow; $row++) {
- foreach($mainColumns as $col) {
- $cellValue = $worksheet->getCell($col . $row)->getCalculatedValue();
-
- if($cellValue !== null && $cellValue !== '' && trim((string)$cellValue) !== '') {
- $hasData = true;
- break 2;
- }
- }
- }
-
- if(!$hasData) {
- return [
- 'valid' => false,
- 'message' => "La hoja '$sheetName' no contiene datos. Se requiere al menos un registro con información."
- ];
- }
-
- return ['valid' => true, 'message' => 'Datos encontrados'];
-
- } catch(Exception $e) {
- return [
- 'valid' => false,
- 'message' => "Error al validar datos en '$sheetName': " . $e->getMessage()
- ];
- }
- }
- private function getExpectedHeaders($sheetName) {
- $headers = [
- 'CARGA DE EQUIPOS' => [
- 'B' => 'CÓDIGO EQUIVALENTE',
- 'C' => 'TIPO / DESCRIPCIÓN',
- 'D' => 'ACRÓNIMO DEL EQUIPO',
- 'E' => 'MODELO COMPLETO',
- 'F' => 'ACRÓNIMO DEL MODELO',
- 'G' => 'ID',
- 'H' => 'NO.SERIE',
- 'I' => 'NO. CÓDIGO DE BARRAS',
- 'J' => 'CARÁCTER',
- 'K' => 'FECHA DE VENCIMIENTO DEL ARTÍCULO',
- 'L' => 'ETIQUETA FINAL DEL EQUIPO',
- ],
- 'LRU' => [
- 'B' => 'CÓDIGO EQUIVALENTE',
- 'C' => 'TIPO / DESCRIPCIÓN',
- 'D' => 'ACRÓNIMO DEL EQUIPO',
- 'E' => 'MODELO COMPLETO',
- 'F' => 'ACRÓNIMO DEL MODELO',
- 'G' => 'ID',
- 'H' => 'NO.SERIE',
- 'I' => 'NO. CÓDIGO DE BARRAS',
- 'J' => 'CARÁCTER',
- 'K' => 'FECHA DE VENCIMIENTO DEL ARTÍCULO',
- 'L' => 'ETIQUETA FINAL DEL EQUIPO'
- ],
- 'CASO 1'=> [
- 'B'=> 'LÍNEA',
- 'D'=> 'UBICACIÓN',
- 'F'=> 'NIVEL',
- 'H'=> 'OCUPACIÓN',
- 'J'=> 'ELEMENTO',
- 'L'=> 'COORDENADAS PLANO GENERAL',
- 'M'=> 'COORDENADAS DETALLE',
- 'N'=> 'COORDENADAS DE POSICIÓN',
- 'P'=> 'FAMILIA',
- 'R'=> 'SUBFAMILIA',
- 'T'=> 'ESTADO',
- 'V'=> 'TIPO',
- 'X'=> 'MODELO',
- 'Z'=> 'ID',
- 'AB'=> 'TIPO',
- 'AD'=> 'MODELO',
- 'AF'=> 'ID',
- 'AH'=> 'CÓDIGO COMPLETO SAM',
- 'AI'=> 'CÓDIGO EQUIVALENTE',
- ],
- 'CASO 2'=> [
- 'B'=> 'LÍNEA',
- 'D'=> 'UBICACIÓN',
- 'F'=> 'NIVEL',
- 'H'=> 'OCUPACIÓN',
- 'J'=> 'ELEMENTO',
- 'L'=> 'COORDENADAS PLANO GENERAL',
- 'M'=> 'COORDENADAS DE POSICIÓN',
- 'N'=> 'POSICIÓN EN RACK',
- 'P'=> 'FAMILIA',
- 'R'=> 'SUBFAMILIA',
- 'T'=> 'ESTADO',
- 'V'=> 'TIPO',
- 'X'=> 'MODELO',
- 'Z'=> 'ID',
- 'AB'=> 'TIPO',
- 'AD'=> 'MODELO',
- 'AF'=> 'ID',
- 'AH'=> 'CÓDIGO COMPLETO',
- 'AI'=> 'CÓDIGO EQUIVALENTE',
- ],
- 'CASO 3'=> [
- 'B'=> 'LÍNEA',
- 'D'=> 'UBICACIÓN ORIGEN',
- 'F'=> 'NIVEL ORIGEN',
- 'H'=> 'OCUPACIÓN ORIGEN',
- 'J'=> 'ELEMENTO ORIGEN',
- 'L'=> 'PK ORIGEN',
- 'N'=> 'UBICACIÓN DESTINO',
- 'P'=> 'NIVEL DESTINO',
- 'R'=> 'OCUPACIÓN DESTINO',
- 'T'=> 'ELEMENTO DESTINO',
- 'V'=> 'PK DESTINO',
- 'X'=> 'FAMILIA',
- 'Z'=> 'SUBFAMILIA',
- 'AB'=> 'ESTADO',
- 'AD'=> 'TIPO',
- 'AF'=> 'MODELO',
- 'AH'=> 'ID',
- 'AJ'=> 'TIPO',
- 'AL'=> 'MODELO',
- 'AN'=> 'ID',
- 'AP'=> 'CÓDIGO COMPLETO',
- 'AQ'=> 'CÓDIGO EQUIVALENTE'
- ],
- 'CASO 4'=> [
- 'B'=> 'LÍNEA',
- 'D'=> 'UBICACIÓN ORIGEN',
- 'F'=> 'NIVEL ORIGEN',
- 'H'=> 'OCUPACIÓN ORIGEN',
- 'J'=> 'ELEMENTO ORIGEN',
- 'L'=> 'SECUENCIAL ORIGEN',
- 'N'=> 'COORDENADAS PLANO',
- 'O'=> 'COORDENADAS DETALLE',
- 'P'=> 'COORDENADAS DE POSICIÓN',
- 'R'=> 'UBICACIÓN DESTINO',
- 'T'=> 'NIVEL DESTINO',
- 'V'=> 'OCUPACIÓN DESTINO',
- 'X'=> 'ELEMENTO DESTINO',
- 'Z'=> 'SECUENCIAL DESTINO',
- 'AB'=> 'COORDENADAS PLANO',
- 'AC'=> 'COORDENADAS DETALLE',
- 'AD'=> 'COORDENADAS DE POSICIÓN',
- 'AF'=> 'FAMILIA',
- 'AH'=> 'SUBFAMILIA',
- 'AJ'=> 'ESTADO',
- 'AL'=> 'TIPO',
- 'AN'=> 'MODELO',
- 'AP'=> 'ID',
- 'AR'=> 'TIPO',
- 'AT'=> 'MODELO',
- 'AV'=> 'ID',
- 'AX'=> 'CÓDIGO COMPLETO',
- 'AY'=> 'CÓDIGO EQUIVALENTE',
- ],
- 'CASO 5'=> [
- 'B'=> 'LÍNEA',
- 'D'=> 'UBICACIÓN',
- 'F'=> 'NIVEL',
- 'H'=> 'OCUPACIÓN',
- 'J'=> 'ÁREA',
- 'L'=> 'ELEMENTO',
- 'N'=> 'FAMILIA',
- 'P'=> 'SUBFAMILIA',
- 'R'=> 'ESTADO',
- 'T'=> 'TIPO',
- 'V'=> 'MODELO',
- 'X'=> 'ID',
- 'Z'=> 'TIPO',
- 'AB'=> 'MODELO',
- 'AD'=> 'ID',
- 'AF'=> 'CÓDIGO COMPLETO',
- 'AG'=> 'CÓDIGO EQUIVALENTE',
- ],
- 'CASO 6' => [
- 'B'=> 'LÍNEA',
- 'D'=> 'UBICACIÓN',
- 'F'=> 'NIVEL',
- 'H'=> 'OCUPACIÓN',
- 'J'=> 'ELEMENTO',
- 'L'=> 'POSICIÓN',
- 'N'=> 'FAMILIA',
- 'P'=> 'SUBFAMILIA',
- 'R'=> 'ESTADO',
- 'T'=> 'TIPO',
- 'V'=> 'MODELO',
- 'X'=> 'ID',
- 'Z'=> 'TIPO',
- 'AB'=> 'MODELO',
- 'AD'=> 'ID',
- 'AF'=> 'CÓDIGO COMPLETO',
- 'AG'=> 'CÓDIGO EQUIVALENTE'
- ]
- ];
- return $headers[$sheetName] ?? [];
- }
- private function extractRowData($worksheet, $row, $fieldMapping, $sheetName) {
- $rowData = [];
-
- foreach($fieldMapping as $column => $field) {
- if (!empty($field) && $field !== '.' && $field !== '-' && $field !== '_' && $field !== '+') {
- $cellValue = $worksheet->getCell($column . $row)->getCalculatedValue();
- $rowData[$field] = $cellValue;
- }
- }
- // **CAMBIO CLAVE 5: Capturar el código completo generado por el frontend**
- if (in_array($sheetName, ['CASO 1', 'CASO 2'])) {
- // Para CASO 1 y 2, el código está en columna AH
- $frontendCode = $worksheet->getCell('AH' . $row)->getCalculatedValue();
- if (!empty($frontendCode)) {
- $rowData['PCEQ_CPGE'] = trim($frontendCode);
- }
-
- // Manejar concatenaciones especiales para coordenadas
- $coordL = $this->getCellValue($worksheet, 'L', $row);
- $coordM = $this->getCellValue($worksheet, 'M', $row);
- $coordN = $this->getCellValue($worksheet, 'N', $row);
- $rowData['PCEQ_COOR'] = $coordL . $coordM . $coordN;
- }
- elseif ($sheetName === 'CASO 3') {
- // Para CASO 3, el código está en columna AP
- $frontendCode = $worksheet->getCell('AP' . $row)->getCalculatedValue();
- if (!empty($frontendCode)) {
- $rowData['PCEQ_CPGE'] = trim($frontendCode);
- }
- }
- elseif ($sheetName === 'CASO 4') {
- // Para CASO 4, el código está en columna AX
- $frontendCode = $worksheet->getCell('AX' . $row)->getCalculatedValue();
- if (!empty($frontendCode)) {
- $rowData['PCEQ_CPGE'] = trim($frontendCode);
- }
-
- // Concatenar coordenadas para CASO 4 (origen y destino)
- $coordN = $this->getCellValue($worksheet, 'N', $row);
- $coordO = $this->getCellValue($worksheet, 'O', $row);
- $coordP = $this->getCellValue($worksheet, 'P', $row);
- $rowData['PCEQ_COOR_ORIGEN'] = $coordN . $coordO . $coordP;
-
- $coordAB = $this->getCellValue($worksheet, 'AB', $row);
- $coordAC = $this->getCellValue($worksheet, 'AC', $row);
- $coordAD = $this->getCellValue($worksheet, 'AD', $row);
- $rowData['PCEQ_COOR_DESTINO'] = $coordAB . $coordAC . $coordAD;
- }
- elseif (in_array($sheetName, ['CASO 5', 'CASO 6'])) {
- // Para CASO 5 y 6, el código está en columna AF
- $frontendCode = $worksheet->getCell('AF' . $row)->getCalculatedValue();
- if (!empty($frontendCode)) {
- $rowData['PCEQ_CPGE'] = trim($frontendCode);
- }
- }
-
- $rowData['PCEQ_TIEQ_ACRONIMO'] = '';
- $rowData['PCEQ_MOEQ_ACRONIMO'] = '';
- $rowData['PCEQ_TIEQ_HIJO_ACRONIMO'] = '';
- $rowData['PCEQ_MOEQ_HIJO_ACRONIMO'] = '';
- return $rowData;
- }
- private function logCodeComparison($frontendCode, $backendCode, $sheetName, $row) {
- if ($frontendCode !== $backendCode) {
- // \Log::info("Comparación de códigos en $sheetName fila $row:");
- // \Log::info("Frontend: $frontendCode");
- // \Log::info("Backend: $backendCode");
-
- // Analizar diferencias
- $frontParts = explode('.', $frontendCode);
- $backParts = explode('.', $backendCode);
-
- for ($i = 0; $i < max(count($frontParts), count($backParts)); $i++) {
- $front = $frontParts[$i] ?? '[MISSING]';
- $back = $backParts[$i] ?? '[MISSING]';
- if ($front !== $back) {
- // \Log::info("Diferencia en parte $i: Frontend='$front' vs Backend='$back'");
- }
- }
- }
- }
- private function isEmptyRow($rowData) {
- $requiredFields = ['PCEQ_TIEQ', 'PCEQ_MOEQ']; // Campos mínimos
-
- foreach($requiredFields as $field) {
- if(isset($rowData[$field]) && !empty(trim((string)$rowData[$field]))) {
- return false;
- }
- }
- return true;
- }
- private function validateRowData($rowData, $sheetName, $row) {
- $errors = [];
- $valid = true;
-
- // Para hojas de casos 1-6
- if (in_array($sheetName, ['CASO 1', 'CASO 2', 'CASO 3', 'CASO 4', 'CASO 5', 'CASO 6'])) {
- $tienePrimerConjunto =
- !empty(trim($rowData['PCEQ_TIEQ'] ?? '')) &&
- !empty(trim($rowData['PCEQ_MOEQ'] ?? ''));
-
- $tieneSegundoConjunto =
- !empty(trim($rowData['PCEQ_TIEQ_HIJO'] ?? '')) &&
- !empty(trim($rowData['PCEQ_MOEQ_HIJO'] ?? ''));
-
- if (!$tienePrimerConjunto && !$tieneSegundoConjunto) {
- $errors[] = 'Se requiere al menos un conjunto completo de datos (Tipo/Modelo)';
- $valid = false;
- }
- } else {
- if(empty($rowData['PCEQ_TIEQ'] ?? '')) {
- $errors[] = 'Tipo de equipo requerido';
- $valid = false;
- }
-
- if(empty($rowData['PCEQ_MOEQ'] ?? '')) {
- $errors[] = 'Modelo requerido';
- $valid = false;
- }
- }
-
- // Validar fechas si existen
- $dateFields = ['PCEQ_FEAD', 'PCEQ_FIGA', 'PCEQ_FTGA'];
- foreach($dateFields as $dateField) {
- if(isset($rowData[$dateField]) && !empty($rowData[$dateField])) {
- try {
- Carbon::parse($rowData[$dateField]);
- } catch(Exception $e) {
- $errors[] = "Fecha inválida en campo $dateField";
- $valid = false;
- }
- }
- }
-
- return ['valid' => $valid, 'errors' => $errors];
- }
- private function noDate($value)
- {
- if (empty($value) ||
- strtoupper(trim($value)) === 'NA' ||
- trim($value) === '.' ||
- trim($value) === '-') {
- return now()->format('Y-m-d');
- }
-
- if (is_numeric($value)) {
- try {
- return \PhpOffice\PhpSpreadsheet\Shared\Date::excelToDateTimeObject($value)->format('Y-m-d');
- } catch (Exception $e) {
- return null;
- }
- }
-
- if (is_string($value)) {
- try {
- $date = new \DateTime($value);
- return $date->format('Y-m-d');
- } catch (Exception $e) {
- return null;
- }
- }
-
- return null;
- }
- private function prepareEquipmentData($rowData, $linea, $idUser, $sheetName) {
- $nowStr = Carbon::now('America/Mexico_city')->toDateTimeString();
-
- $caracter = $this->normalizeCaracter($rowData['PCEQ_CARA'] ?? null);
- $fechaInicioGarantia = $this->parseDate($rowData['PCEQ_FIGA'] ?? null);
- $fechaFinGarantia = $this->parseDate($rowData['PCEQ_FTGA'] ?? null);
- $fechaAdquisicion = $this->parseDate($rowData['PCEQ_FEAD'] ?? null);
- $fechaVencimiento = $this->noDate($rowData['PCEQ_FVAR'] ?? null);
-
- $equipmentData = [
- 'PCEQ_FIGA' => $fechaInicioGarantia ?? now()->format('Y-m-d'),
- 'PCEQ_FEAD' => $fechaAdquisicion ?? now()->format('Y-m-d'),
- 'PCEQ_FTGA' => $fechaFinGarantia ?? now()->format('Y-m-d'),
- 'PCEQ_OTCO' => '[]',
- 'PCEQ_NULI' => $linea,
- 'PCEQ_UBOR' => $rowData['PCEQ_UBOR'] ?? '',
- 'PCEQ_NIOR' => $rowData['PCEQ_NIOR'] ?? '',
- 'PCEQ_OCOR' => $rowData['PCEQ_OCOR'] ?? '',
- 'PCEQ_ELOR' => $rowData['PCEQ_ELOR'] ?? '',
- 'PCEQ_COOR' => $rowData['PCEQ_COOR'] ?? '',
- 'PCEQ_FAMI' => $rowData['PCEQ_FAMI'] ?? '',
- 'PCEQ_SUBF' => $rowData['PCEQ_SUBF'] ?? '',
- 'PCEQ_ESEQ' => $rowData['PCEQ_ESEQ'] ?? 'A',
- 'PCEQ_TICO' => $this->getCodeTypeFromSheet($sheetName),
- 'PCEQ_JERA' => 'Padre',
- 'PCEQ_EQPA' => null,
- 'PCEQ_NUSE' => $rowData['PCEQ_NUSE'] ?? '',
- 'PCEQ_COBA' => $rowData['PCEQ_COBA'] ?? '',
- 'PCEQ_CARA' => $caracter,
- 'PCEQ_PREQ' => $rowData['PCEQ_PREQ'] ?? 0,
- 'PCEQ_FVAR' => $fechaVencimiento ?? now()->format('Y-m-d'),
- 'PCEQ_GAIM' => json_encode([]),
- 'PCEQ_DORE' => json_encode([]),
- 'PCEQ_ESRE' => 'Revisión',
- 'PCEQ_USRE' => $idUser,
- 'PCEQ_FERE' => $nowStr,
- 'PCEQ_IDPR' => $this->generateNumericUniqueId($linea)
- ];
- // ==================== CAMBIO PRINCIPAL ====================
- // Lógica de jerarquía (Padre/Hijo) para casos 1-6
- if (in_array($sheetName, ['CASO 1', 'CASO 2', 'CASO 3', 'CASO 4', 'CASO 5', 'CASO 6'])) {
- $tieneSegundoConjunto =
- !empty(trim($rowData['PCEQ_TIEQ_HIJO'] ?? '')) &&
- !empty(trim($rowData['PCEQ_MOEQ_HIJO'] ?? ''));
-
- if ($tieneSegundoConjunto) {
- // Para HIJO: Guardar nombres COMPLETOS en BD
- $equipmentData['PCEQ_TIEQ'] = $rowData['PCEQ_TIEQ_HIJO_COMPLETO'] ?? $rowData['PCEQ_TIEQ_HIJO'] ?? '';
- $equipmentData['PCEQ_MOEQ'] = $rowData['PCEQ_MOEQ_HIJO_COMPLETO'] ?? $rowData['PCEQ_MOEQ_HIJO'] ?? '';
- $equipmentData['PCEQ_JERA'] = 'Hijo';
- } else {
- // Para PADRE: Guardar nombres COMPLETOS en BD
- $equipmentData['PCEQ_TIEQ'] = $rowData['PCEQ_TIEQ_COMPLETO'] ?? $rowData['PCEQ_TIEQ'] ?? '';
- $equipmentData['PCEQ_MOEQ'] = $rowData['PCEQ_MOEQ_COMPLETO'] ?? $rowData['PCEQ_MOEQ'] ?? '';
- $equipmentData['PCEQ_JERA'] = 'Padre';
- }
- } else {
- // Para CARGA DE EQUIPOS y LRU: También usar nombres completos si están disponibles
- $equipmentData['PCEQ_TIEQ'] = $rowData['PCEQ_TIEQ_COMPLETO'] ?? $rowData['PCEQ_TIEQ'] ?? '';
- $equipmentData['PCEQ_MOEQ'] = $rowData['PCEQ_MOEQ_COMPLETO'] ?? $rowData['PCEQ_MOEQ'] ?? '';
- }
- // ==================== FIN CAMBIO PRINCIPAL ====================
-
- // Agregar campos específicos según el tipo de hoja
- $this->addSheetSpecificFields($equipmentData, $rowData, $sheetName);
-
- return $equipmentData;
- }
- private function parseDate($value) {
- if (!$value) return null;
-
- try {
- // Intentar como fecha de Excel
- if (is_numeric($value)) {
- return \PhpOffice\PhpSpreadsheet\Shared\Date::excelToDateTimeObject($value)
- ->format('Y-m-d');
- }
-
- // Intentar como cadena de fecha
- return Carbon::createFromFormat('d/m/Y', $value)->format('Y-m-d');
- } catch (\Exception $e) {
- return null;
- }
- }
- // Función para manejar jerarquía
- private function handleHierarchy(&$equipmentData, $rowData, $sheetName) {
- if (!in_array($sheetName, ['CASO 1','CASO 2','CASO 3','CASO 4','CASO 5','CASO 6'])) {
- return;
- }
- // Determinar si es hijo
- $isHijo = !empty($rowData['PCEQ_TIEQ_HIJO']) || !empty($rowData['PCEQ_MOEQ_HIJO']);
-
- if ($isHijo) {
- $equipmentData['PCEQ_JERA'] = 'Hijo';
- $equipmentData['PCEQ_TIEQ'] = $rowData['PCEQ_TIEQ_HIJO'] ?? '';
- $equipmentData['PCEQ_MOEQ'] = $rowData['PCEQ_MOEQ_HIJO'] ?? '';
- }
- }
- private function normalizeCaracter($value) {
- if (!$value) return null;
-
- $value = strtoupper(trim($value));
- $mapping = [
- 'REPARABLE' => 'REPARABLE',
- 'REP' => 'REPARABLE',
- 'R' => 'REPARABLE',
- 'CONSUMIBLE' => 'CONSUMIBLE',
- 'CONSUM' => 'CONSUMIBLE',
- 'CONS' => 'CONSUMIBLE',
- 'C' => 'CONSUMIBLE',
- 'DESECHABLE' => 'CONSUMIBLE'
- ];
-
- return $mapping[$value] ?? null;
- }
- // MÉTODO PARA GENERAR PCEQ_IDPR: Solo ID numérico único
- private function generateNumericUniqueId($linea, $increment = true) {
- static $lastId = [];
- static $initialized = [];
-
- // Solo inicializar una vez por línea
- if (!isset($initialized[$linea])) {
- // Obtener el máximo ID existente en la base de datos
- $maxId = DB::table('S002V01TPCEQ')
- ->where('PCEQ_NULI', $linea)
- ->max('PCEQ_IDPR');
-
- if ($maxId) {
- // Si hay registros, convertir a entero (removiendo padding)
- $lastId[$linea] = (int)ltrim($maxId, '0');
- } else {
- // Si NO hay registros, empezar desde 0
- $lastId[$linea] = 0;
- }
-
- $initialized[$linea] = true;
-
- // Log para debug
- // \Log::info("Línea $linea - Max ID en BD: " . ($maxId ?? 'NULL') . ", Contador inicializado en: " . $lastId[$linea]);
- }
-
- // Solo incrementar si se solicita (por defecto true)
- if ($increment) {
- $lastId[$linea]++;
- }
-
- // FORMATEAR A 6 DÍGITOS
- return str_pad($lastId[$linea], 6, '0', STR_PAD_LEFT);
- }
- // MÉTODO PARA GENERAR PCEQ_CPGE: El código concatenado complejo (solo CASOS 1-6)
- private function generateConcatenatedCode($equipmentData, $sheetName) {
- // Validar campos mínimos requeridos
- $requiredFields = ['PCEQ_NULI', 'PCEQ_IDPR'];
- foreach ($requiredFields as $field) {
- if (empty($equipmentData[$field])) {
- return 'CODIGO_INCOMPLETO_' . uniqid();
- }
- }
-
- switch($sheetName) {
- case 'CASO 1':
- case 'CASO 2':
- return $this->generateCodeCaso1y2($equipmentData);
- case 'CASO 3':
- return $this->generateCodeCaso3($equipmentData);
- case 'CASO 4':
- return $this->generateCodeCaso4($equipmentData);
- case 'CASO 5':
- case 'CASO 6':
- return $this->generateCodeCaso5y6($equipmentData);
- default:
- return 'DEFAULT_CODE_' . $equipmentData['PCEQ_IDPR'];
- }
- }
- private function generateCodeCaso1y2($data) {
- $parts = [
- str_pad($data['PCEQ_NULI'], 2, '0', STR_PAD_LEFT),
- $data['PCEQ_UBOR'] ?? '',
- $data['PCEQ_NIOR'] ?? '',
- $data['PCEQ_OCOR'] ?? '',
- $data['PCEQ_ELOR'] ?? '',
- $data['PCEQ_COOR'] ?? '',
- $data['PCEQ_FAMI'] ?? '',
- $data['PCEQ_SUBF'] ?? '',
- $data['PCEQ_ESEQ'] ?? 'A',
- // USAR ACRÓNIMOS para la generación del código
- $this->getAcronymForCode($data, 'TIEQ'),
- $this->getAcronymForCode($data, 'MOEQ'),
- $data['PCEQ_IDPR']
- ];
- return implode('.', array_filter($parts));
- }
- private function generateCodeCaso3($data) {
- $parts = [
- str_pad($data['PCEQ_NULI'], 2, '0', STR_PAD_LEFT),
- $data['PCEQ_UBOR'] ?? '',
- $data['PCEQ_NIDE'] ?? '',
- $data['PCEQ_OCDE'] ?? '',
- $data['PCEQ_ELDE'] ?? '',
- $data['PCEQ_UBDE'] ?? '',
- $data['PCEQ_FAMI'] ?? '',
- $data['PCEQ_SUBF'] ?? '',
- $data['PCEQ_ESEQ'] ?? 'A',
- // USAR ACRÓNIMOS para la generación del código
- $this->getAcronymForCode($data, 'TIEQ'),
- $this->getAcronymForCode($data, 'MOEQ'),
- $data['PCEQ_IDPR']
- ];
-
- return implode('.', array_filter($parts));
- }
- private function generateCodeCaso4($data) {
- $parts = [
- str_pad($data['PCEQ_NULI'], 2, '0', STR_PAD_LEFT),
- $data['PCEQ_UBOR'] ?? '',
- $data['PCEQ_SEOR'] ?? '0',
- $data['PCEQ_COOR'] ?? '',
- $data['PCEQ_UBDE'] ?? '',
- $data['PCEQ_SEDE'] ?? '0',
- $data['PCEQ_CODE'] ?? '',
- $data['PCEQ_FAMI'] ?? '',
- $data['PCEQ_SUBF'] ?? '',
- $data['PCEQ_ESEQ'] ?? 'A',
- // USAR ACRÓNIMOS para la generación del código
- $this->getAcronymForCode($data, 'TIEQ'),
- $this->getAcronymForCode($data, 'MOEQ'),
- $data['PCEQ_IDPR']
- ];
-
- return implode('.', array_filter($parts));
- }
- private function generateCodeCaso5y6($data) {
- $parts = [
- str_pad($data['PCEQ_NULI'], 2, '0', STR_PAD_LEFT),
- $data['PCEQ_UBOR'] ?? '',
- $data['PCEQ_NIOR'] ?? '',
- $data['PCEQ_OCOR'] ?? '',
- $data['PCEQ_ARTR'] ?? '',
- $data['PCEQ_ELOR'] ?? '',
- $data['PCEQ_FAMI'] ?? '',
- $data['PCEQ_SUBF'] ?? '',
- $data['PCEQ_ESEQ'] ?? 'A',
- // USAR ACRÓNIMOS para la generación del código
- $this->getAcronymForCode($data, 'TIEQ'),
- $this->getAcronymForCode($data, 'MOEQ'),
- $data['PCEQ_IDPR']
- ];
-
- return implode('.', array_filter($parts));
- }
- private function getAcronymForCode($data, $type) {
- // Determinar si usar padre o hijo según PCEQ_JERA
- $isHijo = ($data['PCEQ_JERA'] ?? 'Padre') === 'Hijo';
-
- if ($type === 'TIEQ') {
- if ($isHijo) {
- return $data['PCEQ_TIEQ_HIJO_ACRONIMO'] ?? $data['PCEQ_TIEQ_ACRONIMO'] ?? '';
- } else {
- return $data['PCEQ_TIEQ_ACRONIMO'] ?? '';
- }
- } elseif ($type === 'MOEQ') {
- if ($isHijo) {
- return $data['PCEQ_MOEQ_HIJO_ACRONIMO'] ?? $data['PCEQ_MOEQ_ACRONIMO'] ?? '';
- } else {
- return $data['PCEQ_MOEQ_ACRONIMO'] ?? '';
- }
- }
-
- return '';
- }
- // MÉTODO ALTERNATIVO: Usar timestamp + hash para garantizar unicidad (para CARGA DE EQUIPOS y LRU)
- private function generateUniqueHashId($linea) {
- // Crear ID único basado en timestamp + random para CARGA DE EQUIPOS y LRU
- return $linea . '_' . date('YmdHis') . '_' . uniqid();
- }
- // MÉTODO DE RESPALDO: Si falla todo, usar este ID de emergencia
- private function generateFallbackId($linea) {
- return 'FALLBACK_' . $linea . '_' . microtime(true) . '_' . rand(10000, 99999);
- }
- // SOLUCIÓN MEJORADA: Verificar duplicados de PCEQ_IDPR antes de insertar
- private function insertEquipmentWithDuplicateHandling($equipmentData) {
- $maxAttempts = 5;
- $attempt = 0;
-
- while($attempt < $maxAttempts) {
- try {
- // Verificar si ya existe este PCEQ_IDPR para esta línea
- $exists = DB::table('S002V01TPCEQ')
- ->where('PCEQ_NULI', $equipmentData['PCEQ_NULI'])
- ->where('PCEQ_IDPR', $equipmentData['PCEQ_IDPR'])
- ->exists();
-
- if($exists) {
- // Regenerar PCEQ_IDPR numérico único
- $equipmentData['PCEQ_IDPR'] = $this->generateNumericUniqueId($equipmentData['PCEQ_NULI']);
-
- // Si es un CASO 1-6, regenerar también el PCEQ_CPGE con el nuevo IDPR
- if(isset($equipmentData['PCEQ_CPGE']) && strpos($equipmentData['PCEQ_CPGE'], '.') !== false) {
- $sheetName = $this->getSheetNameFromCodeType($equipmentData['PCEQ_TICO']);
- if($sheetName) {
- $equipmentData['PCEQ_CPGE'] = $this->generateConcatenatedCode($equipmentData, $sheetName);
- }
- }
-
- $attempt++;
- continue;
- }
-
- // Intentar insertar
- return DB::table('S002V01TPCEQ')->insert($equipmentData);
-
- } catch(\Illuminate\Database\QueryException $e) {
- // Si es error de clave duplicada, regenerar ID
- if($e->getCode() == 23000 || strpos($e->getMessage(), 'Duplicate entry') !== false) {
- $equipmentData['PCEQ_IDPR'] = $this->generateNumericUniqueId($equipmentData['PCEQ_NULI']);
- $attempt++;
- continue;
- }
-
- // Si es otro tipo de error, re-lanzar
- throw $e;
- }
- }
-
- throw new Exception("No se pudo insertar el registro después de $maxAttempts intentos");
- }
- // MÉTODO AUXILIAR: Obtener nombre de hoja basado en tipo de código
- private function getSheetNameFromCodeType($codeType) {
- $codeTypes = [
- '1' => 'CASO 1',
- '2' => 'CASO 2',
- '3' => 'CASO 3',
- '4' => 'CASO 4',
- '5' => 'CASO 5',
- '6' => 'CASO 6'
- ];
-
- return $codeTypes[$codeType] ?? null;
- }
- // SOLUCIÓN 3: Usar upsert (insertar o actualizar)
- private function upsertEquipmentData($equipmentData) {
- return DB::table('S002V01TPCEQ')->updateOrInsert(
- [
- 'PCEQ_NULI' => $equipmentData['PCEQ_NULI'],
- 'PCEQ_TICO' => $equipmentData['PCEQ_TICO'],
- 'PCEQ_IDPR' => $equipmentData['PCEQ_IDPR']
- ],
- $equipmentData
- );
- }
- // MÉTODO MODIFICADO PARA PROCESAR WORKSHEET CON MANEJO DE DUPLICADOS
- private function processWorksheet($worksheet, $sheetConfig, $sheetName, $linea, $idUser, $cargaMap, $lruMap) {
- $processedData = [];
- $errors = [];
- $count = 0;
-
- $highestRow = $worksheet->getHighestRow();
- $startRow = $sheetConfig['date_start_row'];
- $fieldMapping = $sheetConfig['field_mapping'];
-
- // Obtener todos los equipos de CARGA y LRU para búsqueda
- $cargaEquipments = $this->getAllCargaEquipments($worksheet->getParent());
- $lruEquipments = $this->getAllLruEquipments($worksheet->getParent());
-
- for($row = $startRow; $row <= $highestRow; $row++) {
- $rowData = $this->extractRowData($worksheet, $row, $fieldMapping, $sheetName);
-
- if($this->isEmptyRow($rowData)) {
- continue;
- }
-
- // PASO 1: Resolver nombres completos y acrónimos
- $this->resolveEquipmentNames($rowData, $sheetName, $cargaMap, $lruMap);
- $validation = $this->validateRowData($rowData, $sheetName, $row);
-
- if(!$validation['valid']) {
- $errors[] = "Hoja: $sheetName, Fila: $row - " . implode(', ', $validation['errors']);
- continue;
- }
-
- // PASO 2: Preparar datos del equipo (con nombres COMPLETOS para BD)
- $equipmentData = $this->prepareEquipmentData($rowData, $linea, $idUser, $sheetName);
-
- // PASO 3: Crear array especial para generación de código (con ACRÓNIMOS)
- $codeData = array_merge($equipmentData, [
- 'PCEQ_TIEQ_ACRONIMO' => $rowData['PCEQ_TIEQ_ACRONIMO'] ?? '',
- 'PCEQ_MOEQ_ACRONIMO' => $rowData['PCEQ_MOEQ_ACRONIMO'] ?? '',
- 'PCEQ_TIEQ_HIJO_ACRONIMO' => $rowData['PCEQ_TIEQ_HIJO_ACRONIMO'] ?? '',
- 'PCEQ_MOEQ_HIJO_ACRONIMO' => $rowData['PCEQ_MOEQ_HIJO_ACRONIMO'] ?? ''
- ]);
-
- // PASO 4: Generar código usando acrónimos
- $equipmentData['PCEQ_CPGE'] = $this->generateConcatenatedCode($codeData, $sheetName);
-
- $processedData[] = $equipmentData;
- $count++;
- }
-
- return [
- 'data' => $processedData,
- 'errors' => $errors,
- 'count' => $count
- ];
- }
- // Obtener todos los equipos de CARGA DE EQUIPOS
- private function getAllCargaEquipments($spreadsheet) {
- $equipments = [];
- $sheet = $spreadsheet->getSheetByName('EQUIPAMIENTO');
-
- if(!$sheet) return $equipments;
-
- $highestRow = $sheet->getHighestRow();
- $config = ExcelTemplateConfig::getTemplateConfigs()['TPCEQ']['worksheets']['EQUIPAMIENTO'];
- $startRow = $config['date_start_row'];
-
- for($row = $startRow; $row <= $highestRow; $row++) {
- $equipment = $this->extractRowData($sheet, $row, $config['field_mapping'], 'EQUIPAMIENTO');
-
- if(!$this->isEmptyRow($equipment)) {
- $equipments[] = $equipment;
- }
- }
-
- return $equipments;
- }
- // Obtener todos los equipos de LRU
- private function getAllLruEquipments($spreadsheet) {
- $equipments = [];
- $sheet = $spreadsheet->getSheetByName('LRU');
-
- if(!$sheet) return $equipments;
-
- $highestRow = $sheet->getHighestRow();
- $config = ExcelTemplateConfig::getTemplateConfigs()['TPCEQ']['worksheets']['LRU'];
- $startRow = $config['date_start_row'];
-
- for($row = $startRow; $row <= $highestRow; $row++) {
- $equipment = $this->extractRowData($sheet, $row, $config['field_mapping'], 'LRU');
-
- if(!$this->isEmptyRow($equipment)) {
- $equipments[] = $equipment;
- }
- }
-
- return $equipments;
- }
- // Buscar equipo por tipo y modelo
- private function findEquipment($equipments, $tipo, $modelo) {
- $normalize = function($value) {
- return trim(strtoupper($value));
- };
-
- $tipoNorm = $normalize($tipo);
- $modeloNorm = $normalize($modelo);
-
- foreach($equipments as $equipment) {
- $eqTipo = $normalize($equipment['PCEQ_TIEQ'] ?? '');
- $eqModelo = $normalize($equipment['PCEQ_MOEQ'] ?? '');
-
- // Buscar coincidencia exacta en tipo y modelo
- if($eqTipo === $tipoNorm && $eqModelo === $modeloNorm) {
- return $equipment;
- }
- }
-
- return null;
- }
- private function resolveEquipmentNames(&$rowData, $sheetName, $cargaMap, $lruMap) {
- if (!in_array($sheetName, ['CASO 1','CASO 2','CASO 3','CASO 4','CASO 5','CASO 6'])) {
- return;
- }
- // Resolver nombres completos para equipo principal
- $acronimoTipo = $rowData['PCEQ_TIEQ'] ?? '';
- $acronimoModelo = $rowData['PCEQ_MOEQ'] ?? '';
-
- if ($acronimoTipo && $acronimoModelo) {
- // Obtener nombre completo desde los mapas
- $tipoCompleto = $cargaMap['equipos'][$acronimoTipo][$acronimoModelo] ?? $acronimoTipo;
- $modeloCompleto = $cargaMap['modelos'][$acronimoModelo] ?? $acronimoModelo;
-
- // Preservar ambos valores
- $rowData['PCEQ_TIEQ_COMPLETO'] = $tipoCompleto; // Nombre completo para BD
- $rowData['PCEQ_MOEQ_COMPLETO'] = $modeloCompleto; // Nombre completo para BD
- $rowData['PCEQ_TIEQ_ACRONIMO'] = $acronimoTipo; // Acrónimo para generación de código
- $rowData['PCEQ_MOEQ_ACRONIMO'] = $acronimoModelo; // Acrónimo para generación de código
- }
- // Resolver nombres completos para equipo hijo
- $acronimoTipoHijo = $rowData['PCEQ_TIEQ_HIJO'] ?? '';
- $acronimoModeloHijo = $rowData['PCEQ_MOEQ_HIJO'] ?? '';
-
- if ($acronimoTipoHijo && $acronimoModeloHijo) {
- $tipoHijoCompleto = $lruMap['equipos'][$acronimoTipoHijo][$acronimoModeloHijo] ?? $acronimoTipoHijo;
- $modeloHijoCompleto = $lruMap['modelos'][$acronimoModeloHijo] ?? $acronimoModeloHijo;
-
- $rowData['PCEQ_TIEQ_HIJO_COMPLETO'] = $tipoHijoCompleto;
- $rowData['PCEQ_MOEQ_HIJO_COMPLETO'] = $modeloHijoCompleto;
- $rowData['PCEQ_TIEQ_HIJO_ACRONIMO'] = $acronimoTipoHijo;
- $rowData['PCEQ_MOEQ_HIJO_ACRONIMO'] = $acronimoModeloHijo;
- }
- }
- // // MÉTODO ALTERNATIVO: Limpiar datos duplicados antes del procesamiento
- // public function cleanDuplicateRecords(Request $request) {
- // $validator = Validator::make($request->all(), [
- // 'id_user' => 'required|string',
- // 'linea' => 'required|integer',
- // ]);
- // if($validator->fails()) {
- // return $this->responseController->makeResponse(
- // true,
- // "Se encontraron uno o más errores.",
- // $this->responseController->makeErrors($validator->errors()->messages()),
- // 401
- // );
- // }
- // $form = $request->all();
- // $idUser = $this->encryptionController->decrypt($form['id_user']);
-
- // if(!$idUser) {
- // return $this->responseController->makeResponse(true, "El id del usuario no fue desencriptado correctamente", [], 400);
- // }
- // try {
- // DB::beginTransaction();
-
- // // Eliminar registros duplicados manteniendo solo el más reciente
- // $duplicatesDeleted = DB::statement("
- // DELETE p1 FROM S002V01TPCEQ p1
- // INNER JOIN S002V01TPCEQ p2
- // WHERE p1.PCEQ_NULI = p2.PCEQ_NULI
- // AND p1.PCEQ_TICO = p2.PCEQ_TICO
- // AND p1.PCEQ_IDPR = p2.PCEQ_IDPR
- // AND p1.PCEQ_FERE < p2.PCEQ_FERE
- // AND p1.PCEQ_NULI = ?
- // ", [$form['linea']]);
-
- // DB::commit();
-
- // return $this->responseController->makeResponse(false, "Duplicados eliminados exitosamente", [
- // 'linea' => $form['linea'],
- // 'duplicados_eliminados' => $duplicatesDeleted
- // ]);
-
- // } catch(Exception $e) {
- // DB::rollBack();
- // return $this->responseController->makeResponse(true, "Error al limpiar duplicados: " . $e->getMessage(), [], 500);
- // }
- // }
- private function getCodeTypeFromSheet($sheetName) {
- $codeTypes = [
- 'CASO 1' => '1',
- 'CASO 2' => '2',
- 'CASO 3' => '3',
- 'CASO 4' => '4',
- 'CASO 5' => '5',
- 'CASO 6' => '6',
- ];
-
- return $codeTypes[$sheetName] ?? '1';
- }
- private function addSheetSpecificFields(&$equipmentData, $rowData, $sheetName) {
- switch($sheetName) {
- case 'CASO 1':
- case 'CASO 2':
- $equipmentData['PCEQ_UBOR'] = $rowData['PCEQ_UBOR'] ?? '';
- $equipmentData['PCEQ_NIOR'] = $rowData['PCEQ_NIOR'] ?? '';
- $equipmentData['PCEQ_OCOR'] = $rowData['PCEQ_OCOR'] ?? '';
- $equipmentData['PCEQ_ELOR'] = $rowData['PCEQ_ELOR'] ?? '';
- $equipmentData['PCEQ_COOR'] = $rowData['PCEQ_COOR'] ?? '';
- $equipmentData['PCEQ_FAMI'] = $rowData['PCEQ_FAMI'] ?? '';
- $equipmentData['PCEQ_SUBF'] = $rowData['PCEQ_SUBF'] ?? '';
- break;
-
- case 'CASO 3':
- $equipmentData['PCEQ_UBOR'] = $rowData['PCEQ_UBOR'] ?? '';
- $equipmentData['PCEQ_UBDE'] = $rowData['PCEQ_UBDE'] ?? '';
- break;
-
- case 'CASO 4':
- $equipmentData['PCEQ_UBOR'] = $rowData['PCEQ_UBOR'] ?? '';
- $equipmentData['PCEQ_UBDE'] = $rowData['PCEQ_UBDE'] ?? '';
- $equipmentData['PCEQ_SEOR'] = $rowData['PCEQ_SEOR'] ?? 0;
- $equipmentData['PCEQ_SEDE'] = $rowData['PCEQ_SEDE'] ?? 0;
- $equipmentData['PCEQ_COOR'] = $rowData['PCEQ_COOR_ORIGEN'] ?? '';
- $equipmentData['PCEQ_CODE'] = $rowData['PCEQ_COOR_DESTINO'] ?? '';
- break;
-
- case 'CASO 5':
- case 'CASO 6':
- $equipmentData['PCEQ_UBOR'] = $rowData['PCEQ_UBOR'] ?? '';
- $equipmentData['PCEQ_NIOR'] = $rowData['PCEQ_NIOR'] ?? '';
- $equipmentData['PCEQ_OCOR'] = $rowData['PCEQ_OCOR'] ?? '';
- $equipmentData['PCEQ_ARTR'] = $rowData['PCEQ_ARTR'] ?? '';
- $equipmentData['PCEQ_ELOR'] = $rowData['PCEQ_ELOR'] ?? '';
- break;
- }
- }
- // Método para obtener equipos en revisión
- public function getPendingEquipments(Request $request) {
- $validator = Validator::make($request->all(), [
- 'id_user' => 'required|string',
- 'linea' => 'required|integer',
- ]);
- if($validator->fails()) {
- return $this->responseController->makeResponse(
- true,
- "Se encontraron uno o más errores.",
- $this->responseController->makeErrors($validator->errors()->messages()),
- 401
- );
- }
- $form = $request->all();
- $idUser = $this->encryptionController->decrypt($form['id_user']);
-
- if(!$idUser) {
- return $this->responseController->makeResponse(true, "El id del usuario no fue desencriptado correctamente", [], 400);
- }
- $pendingEquipments = DB::table('S002V01TPCEQ')
- ->where('PCEQ_NULI', $form['linea'])
- ->where('PCEQ_ESRE', 'Revisión')
- ->orderBy('PCEQ_FERE', 'desc')
- ->get();
- $equipmentsArray = [];
- foreach($pendingEquipments as $equipment) {
- $equipmentsArray[] = [
- 'id' => $this->encryptionController->encrypt($equipment->PCEQ_IDPR),
- 'codigo' => $equipment->PCEQ_CPGE,
- 'tipo' => $equipment->PCEQ_TIEQ,
- 'modelo' => $equipment->PCEQ_MOEQ,
- 'familia' => $equipment->PCEQ_FAMI,
- 'subfamilia' => $equipment->PCEQ_SUBF,
- 'estado' => $equipment->PCEQ_ESEQ,
- 'fecha_registro' => $equipment->PCEQ_FERE,
- 'estado_revision' => $equipment->PCEQ_ESRE
- ];
- }
- return $this->responseController->makeResponse(false, 'EXITO.', $equipmentsArray);
- }
- /**
- * Método para aprobar equipamientos desde la tabla temporal hacia la tabla final
- */
-
- }
- class ExcelTemplateConfig {
- public static function getTemplateConfigs() {
- return [
- 'TPCEQ' => [
- 'model' => 'S002V01TPCEQ',
- 'worksheets' => [
- 'EQUIPAMIENTO' => [
- 'table_start' => 'B9',
- 'table_end' => 'P9',
- 'header_row' => 7,
- 'date_start_row' => 9,
- 'field_mapping' => [
- 'A' => '',
- 'B' => 'PCEQ_OTCO', // Código Equivalente
- 'C' => 'PCEQ_TIEQ', // Tipo / Descripción
- 'D' => '', // Acrónimo del equipo
- 'E' => 'PCEQ_MOEQ', // Acrónimo del modelo
- 'F' => '', // Acrónimo del modelo
- 'G' => '', // Id
- 'H' => 'PCEQ_NUSE', // No. serie
- 'I' => 'PCEQ_COBA', // No. código de barras
- 'J' => 'PCEQ_CARA', // Carácter
- 'K' => 'PCEQ_FVAR', // Fecha inicio de garantía
- 'L' => '', // Fecha de vencimiento del artículo
- ]
- ],
- 'LRU' => [
- 'table_start' => 'B9',
- 'table_end' => 'L9',
- 'header_row' => 7,
- 'date_start_row' => 9,
- 'field_mapping' => [
- 'A' => '',
- 'B' => 'PCEQ_TIEQ', // Tipo / Descripción
- 'C' => '', // Acrónimo del equipo
- 'D' => 'PCEQ_MOEQ', // Modelo completo
- 'E' => '', // Acrónimo del modelo
- 'F' => '', // Id
- 'G' => '', // (ID) - no se usa
- 'H' => 'PCEQ_NUSE', // No. serie
- 'I' => 'PCEQ_COBA', // No. código de barras
- 'J' => 'PCEQ_CARA', // Carácter
- 'K' => 'PCEQ_FTGA', // Fecha de vencimiento del artículo
- 'L' => '', // Etiqueta final del equipo
- ]
- ],
- 'CASO 1' => [
- 'table_start' => 'B8',
- 'table_end' => 'AI8',
- 'header_row' => 7,
- 'date_start_row' => 8,
- 'field_mapping' => [
- 'A' => '',
- 'B' => 'PCEQ_NULI', // Línea
- 'C' => '.', // .
- 'D' => 'PCEQ_UBOR', // Ubicación
- 'E' => '.', // .
- 'F' => 'PCEQ_NIOR', // Nivel
- 'G' => '.', // .
- 'H' => 'PCEQ_OCOR', // Ocupación
- 'I' => '.', // .
- 'J' => 'PCEQ_ELOR', // Elemento
- 'K' => '+', // +
- 'L' => '', // Coordenadas plano
- 'M' => '', // Coordenadas detalle
- 'N' => '', // Coordenadas de posición
- 'O' => '_', // _
- 'P' => 'PCEQ_FAMI', // Familia
- 'Q' => '.', // .
- 'R' => 'PCEQ_SUBF', // Subfamilia
- 'S' => '.', // .
- 'T' => 'PCEQ_ESEQ', // Estado
- 'U' => '.', // .
- 'V' => 'PCEQ_TIEQ', // Tipo
- 'W' => '-', // -
- 'X' => 'PCEQ_MOEQ', // Modelo
- 'Y' => '-', // -
- 'Z' => '', // ID
- 'AA' => '.', // .
- 'AB' => 'PCEQ_TIEQ_HIJO', // Tipo
- 'AC' => '-', // -
- 'AD' => 'PCEQ_MOEQ_HIJO', // Modelo
- 'AE' => '-', // -
- 'AF' => '', // ID
- 'AG' => '', // Vacío
- 'AH' => 'PCEQ_CPGE', // Código completo SAM
- 'AI' => 'PCEQ_OTCO', // Código equivalente
- ]
- ],
- 'CASO 2' => [
- 'table_start' => 'B8',
- 'table_end' => 'AI8',
- 'header_row' => 7,
- 'date_start_row' => 8,
- 'field_mapping' => [
- 'A' => '',
- 'B' => 'PCEQ_NULI', // Línea
- 'C' => '.', // .
- 'D' => 'PCEQ_UBOR', // Ubicación
- 'E' => '.', // .
- 'F' => 'PCEQ_NIOR', // Nivel
- 'G' => '.', // .
- 'H' => 'PCEQ_OCOR', // Ocupación
- 'I' => '.', // .
- 'J' => 'PCEQ_ELOR', // Elemento
- 'K' => '+', // +
- 'L' => '', // Coordenadas plano
- 'M' => '', // Coordenadas detalle
- 'N' => '', // Coordenadas de posición
- 'O' => '_', // _
- 'P' => 'PCEQ_FAMI', // Familia
- 'Q' => '.', // .
- 'R' => 'PCEQ_SUBF', // Subfamilia
- 'S' => '.', // .
- 'T' => 'PCEQ_ESEQ', // Estado
- 'U' => '.', // .
- 'V' => 'PCEQ_TIEQ', // Tipo
- 'W' => '-', // -
- 'X' => 'PCEQ_MOEQ', // Modelo
- 'Y' => '-', // -
- 'Z' => '', // ID
- 'AA' => '.', // .
- 'AB' => 'PCEQ_TIEQ_HIJO', // Tipo
- 'AC' => '-', // -
- 'AD' => 'PCEQ_MOEQ_HIJO', // Modelo
- 'AE' => '-', // -
- 'AF' => '', // ID
- 'AG' => '', // Vacío
- 'AH' => 'PCEQ_CPGE', // Código completo SAM
- 'AI' => 'PCEQ_OTCO', // Código equivalente
- ]
- ],
- 'CASO 3' => [
- 'table_start' => 'B8',
- 'table_end' => 'AQ8',
- 'header_row' => 7,
- 'date_start_row' => 8,
- 'field_mapping' => [
- 'A' => '',
- 'B' => 'PCEQ_NULI', // Línea
- 'C' => '.', // .
- 'D' => 'PCEQ_UBOR', // Ubicación origen
- 'E' => '.', // .
- 'F' => 'PCEQ_NIOR', // Nivel origen
- 'G' => '.', // .
- 'H' => 'PCEQ_OCOR', // Ocupación origen
- 'I' => '.', // .
- 'J' => 'PCEQ_ELOR', // Elemento origen
- 'K' => '.', // .
- 'L' => 'PCEQ_KIOR', // PK origen
- 'M' => ':', // :
- 'N' => 'PCEQ_UBDE', // Ubicación destino
- 'O' => '.', // .
- 'P' => 'PCEQ_NIDE', // Nivel destino
- 'Q' => '.', // .
- 'R' => 'PCEQ_OCDE', // Ocupación destino
- 'S' => '.', // .
- 'T' => 'PCEQ_ELDE', // Elemento destino
- 'U' => '.', // .
- 'V' => 'PCEQ_KIDE', // PK destino
- 'W' => '-', // -
- 'X' => 'PCEQ_FAMI', // Familia
- 'Y' => '-', // -
- 'Z' => 'PCEQ_SUBF', // Subfamilia
- 'AA' => '.', // .
- 'AB' => 'PCEQ_ESEQ', // Estado
- 'AC' => '-', // -
- 'AD' => 'PCEQ_TIEQ', // Tipo
- 'AE' => '-', // -
- 'AF' => 'PCEQ_MOEQ', // Modelo
- 'AG' => '-', // -
- 'AH' => '', // ID
- 'AI' => '.', // .
- 'AJ' => 'PCEQ_TIEQ_HIJO', // Tipo
- 'AK' => '-', // -
- 'AL' => 'PCEQ_MOEQ_HIJO', // Modelo
- 'AM' => '-', // -
- 'AN' => 'PCEQ_IDPR', // ID
- 'AO' => '-', // -
- 'AP' => 'PCEQ_CPGE', // Código completo
- 'AQ' => 'PCEQ_OTCO', // Código equivalente
- ]
- ],
- 'CASO 4' => [
- 'table_start' => 'B8',
- 'table_end' => 'AY8',
- 'header_row' => 7,
- 'date_start_row' => 8,
- 'field_mapping' => [
- 'A' => '',
- 'B' => 'PCEQ_NULI', // Línea
- 'C' => '.', // .
- 'D' => 'PCEQ_UBOR', // Ubicación origen
- 'E' => '.', // .
- 'F' => 'PCEQ_NIOR', // Nivel origen
- 'G' => '.', // .
- 'H' => 'PCEQ_OCOR', // Ocupación origen
- 'I' => '.', // .
- 'J' => 'PCEQ_ELOR', // Elemento origen
- 'K' => '.', // .
- 'L' => 'PCEQ_SEOR', // Secuencial origen
- 'M' => '.', // .
- 'N' => '', // Coordenadas plano (concatenar con O,P)
- 'O' => '', // Coordenadas detalle
- 'P' => '', // Coordenadas de posición
- 'Q' => ':', // :
- 'R' => 'PCEQ_UBDE', // Ubicación destino
- 'S' => '.', // .
- 'T' => 'PCEQ_NIDE', // Nivel destino
- 'U' => '.', // .
- 'V' => 'PCEQ_OCDE', // Ocupación destino
- 'W' => '.', // .
- 'X' => 'PCEQ_ELDE', // Elemento destino
- 'Y' => '.', // .
- 'Z' => 'PCEQ_SEDE', // Secuencial destino
- 'AA' => '+', // +
- 'AB' => '', // Coordenadas plano (concatenar con AC,AD)
- 'AC' => '', // Coordenadas detalle
- 'AD' => '', // Coordenadas de posición
- 'AE' => '_', // _
- 'AF' => 'PCEQ_FAMI', // Familia
- 'AG' => '.', // .
- 'AH' => 'PCEQ_SUBF', // Subfamilia
- 'AI' => '.', // .
- 'AJ' => 'PCEQ_ESEQ', // Estado
- 'AK' => '.', // .
- 'AL' => 'PCEQ_TIEQ', // Tipo
- 'AM' => '-', // -
- 'AN' => 'PCEQ_MOEQ', // Modelo
- 'AO' => '-', // -
- 'AP' => '', // ID
- 'AQ' => '.', // .
- 'AR' => 'PCEQ_TIEQ_HIJO', // Tipo
- 'AS' => '-', // -
- 'AT' => 'PCEQ_MOEQ_HIJO', // Modelo
- 'AU' => '-', // -
- 'AV' => '', // ID
- 'AW' => '', // Vacío
- 'AX' => 'PCEQ_CPGE', // Código completo
- 'AY' => 'PCEQ_OTCO', // Código equivalente
- ]
- ],
- 'CASO 5' => [
- 'table_start' => 'B8',
- 'table_end' => 'AG8',
- 'header_row' => 7,
- 'date_start_row' => 8,
- 'field_mapping' => [
- 'A' => '',
- 'B' => 'PCEQ_NULI', // Línea
- 'C' => '.', // .
- 'D' => 'PCEQ_UBOR', // Ubicación
- 'E' => '.', // .
- 'F' => 'PCEQ_NIOR', // Nivel
- 'G' => '.', // .
- 'H' => 'PCEQ_OCOR', // Ocupación
- 'I' => '.', // .
- 'J' => 'PCEQ_ARTR', // Área
- 'K' => '.', // .
- 'L' => 'PCEQ_ELOR', // Elemento
- 'M' => '_', // _
- 'N' => 'PCEQ_FAMI', // Familia
- 'O' => '.', // .
- 'P' => 'PCEQ_SUBF', // Subfamilia
- 'Q' => '.', // .
- 'R' => 'PCEQ_ESEQ', // Estado
- 'S' => '.', // .
- 'T' => 'PCEQ_TIEQ', // Tipo
- 'U' => '-', // -
- 'V' => 'PCEQ_MOEQ', // Modelo
- 'W' => '-', // -
- 'X' => '', // ID
- 'Y' => '.', // .
- 'Z' => 'PCEQ_TIEQ_HIJO', // Tipo LRU
- 'AA' => '-', // -
- 'AB' => 'PCEQ_MOEQ_HIJO', // Modelo LRU
- 'AC' => '-', // -
- 'AD' => '', // ID LRU
- 'AE' => '', // Vacío
- 'AF' => 'PCEQ_CPGE', // Código completo
- 'AG' => 'PCEQ_OTCO', // Código equivalente
- ]
- ],
- 'CASO 6' => [
- 'table_start' => '',
- 'table_end' => '',
- 'header_row' => 7,
- 'date_start_row' => 8,
- 'field_mapping' => [
- 'A' => '', // Vacío
- 'B' => 'PCEQ_NULI', // Linea
- 'C' => '.', // .
- 'D' => 'PCEQ_UBOR', // Ubicación
- 'E' => '.', // .
- 'F' => 'PCEQ_NIOR', // Nivel
- 'G' => '.', // .
- 'H' => 'PCEQ_OCOR', // Ocupación
- 'I' => '.', // .
- 'J' => 'PCEQ_ELOR', // Elemento
- 'K' => '.', // .
- 'L' => 'PCEQ_COOR', // Posición
- 'M' => '_', // _
- 'N' => 'PCEQ_FAMI', // Familia
- 'O' => '.', // .
- 'P' => 'PCEQ_SUBF', // Subfamilia
- 'Q' => '.', // .
- 'R' => 'PCEQ_ESEQ', // Estado
- 'S' => '.', // .
- 'T' => 'PCEQ_TIEQ', // Tipo
- 'U' => '-', // -
- 'V' => 'PCEQ_MOEQ', // Modelo
- 'W' => '-', // -
- 'X' => 'PCEQ_IDPR', // ID
- 'Y' => '.', // .
- 'Z' => 'PCEQ_TIEQ_HIJO', // Tipo
- 'AA' => '-', // -
- 'AB' => 'PCEQ_MOEQ_HIJO', // Modelo
- 'AC' => '-', // -
- 'AD' => 'PCEQ_LRID', // ID
- 'AE' => '', // Vacío
- 'AF' => 'PCEQ_CPGE', // Código completo
- 'AG' => 'PCEQ_OTCO', // Código equivalente
- ]
- ]
- ]
- ],
- ];
- }
- };
|