ValidateLoadArchivesController.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497
  1. <?php
  2. namespace App\Http\Controllers;
  3. use Illuminate\Http\Request;
  4. use Illuminate\Support\Facades\Validator;
  5. use Illuminate\Support\Facades\Log;
  6. use Illuminate\Support\Facades\DB;
  7. use PhpOffice\PhpSpreadsheet\IOFactory;
  8. use ZipArchive;
  9. /**
  10. * Controller for validating Excel and ZIP files for equipment documentation loading
  11. * Validates Excel headers structure and compares file listings with ZIP contents
  12. */
  13. class ValidateLoadArchivesController extends Controller
  14. {
  15. private $responseController;
  16. private $encryptionController;
  17. private $documentManagementController;
  18. // Expected headers in row 7 of Excel file with their corresponding column letters
  19. private $expectedHeaders = [
  20. ['letter' => 'D', 'category' => 'CÓDIGO DE EQUIPO'],
  21. ['letter' => 'H', 'category' => 'FICHA DE SEGURIDAD DE PRODUCTOS QUÍMICOS'],
  22. ['letter' => 'J', 'category' => 'FICHA TÉCNICA'],
  23. ['letter' => 'L', 'category' => 'FOTOGRAFÍAS - DIAGRAMAS'],
  24. ['letter' => 'N', 'category' => 'DATOS DEL PROVEEDOR'],
  25. ['letter' => 'P', 'category' => 'MANUALES DE OPERACIÓN'],
  26. ['letter' => 'R', 'category' => 'MANUALES DE MANTENIMIENTO PREVENTIVO'],
  27. ['letter' => 'T', 'category' => 'MANUALES DE MANTENIMIENTO CORRECTIVO'],
  28. ['letter' => 'V', 'category' => 'DOCUMENTOS ADICIONALES']
  29. ];
  30. // Mapping of file extensions to their types for validation
  31. private $extensionTypes = [
  32. // Archivos de almacenamiento
  33. 'zip' => 'STORAGE', 'rar' => 'STORAGE', 'tar' => 'STORAGE', '7z' => 'STORAGE',
  34. // Formatos de audio
  35. 'mp3' => 'AUDIO', 'mpeg' => 'AUDIO', 'wav' => 'AUDIO', 'ogg' => 'AUDIO', 'opus' => 'AUDIO',
  36. // Archivos de imagen
  37. 'jpeg' => 'IMG', 'jpg' => 'IMG', 'png' => 'IMG', 'gif' => 'IMG', 'bmp' => 'IMG', 'tiff' => 'IMG', 'svg' => 'IMG',
  38. // Archivos de texto
  39. 'txt' => 'TEXT',
  40. // Archivos de video
  41. 'webm' => 'VIDEO', 'mpeg4' => 'VIDEO', 'mp4' => 'VIDEO', '3gpp' => 'VIDEO', 'mov' => 'VIDEO', 'avi' => 'VIDEO', 'wmv' => 'VIDEO', 'flv' => 'VIDEO',
  42. // Planos de Auto CAD
  43. 'dwg' => 'CAD', 'dxf' => 'CAD',
  44. // Modelos de 3D Studio
  45. '3ds' => '3D',
  46. // Dibujos de Illustrator
  47. 'ai' => 'ILLUSTRATOR',
  48. // Imágenes de Photoshop
  49. 'psd' => 'PHOTOSHOP',
  50. // Formato de documento portátil
  51. 'pdf' => 'PDF',
  52. // Hoja de cálculo en Excel
  53. 'xls' => 'EXCEL', 'xlsx' => 'EXCEL',
  54. // Presentaciones de PowerPoint
  55. 'ppt' => 'POWERPOINT', 'pptx' => 'POWERPOINT',
  56. // Documentos de texto de Word
  57. 'doc' => 'WORD', 'docx' => 'WORD',
  58. // Dibujos de Visio
  59. 'vsd' => 'VISIO', 'vsdx' => 'VISIO'
  60. ];
  61. // File size limits in MB by extension
  62. private $fileSizeLimits = [
  63. // 50MB limit
  64. 'pdf' => 50, 'doc' => 50, 'docx' => 50, 'vsd' => 50, 'vsdx' => 50,
  65. // 75MB limit
  66. 'xls' => 75, 'xlsx' => 75,
  67. // 100MB limit
  68. 'ppt' => 100, 'pptx' => 100,
  69. // 250MB limit (default for all others)
  70. 'zip' => 250, 'rar' => 250, 'tar' => 250, '7z' => 250,
  71. 'mp3' => 250, 'mpeg' => 250, 'wav' => 250, 'ogg' => 250, 'opus' => 250,
  72. 'jpeg' => 250, 'jpg' => 250, 'png' => 250, 'gif' => 250, 'bmp' => 250, 'tiff' => 250, 'svg' => 250,
  73. 'txt' => 250, 'webm' => 250, 'mpeg4' => 250, 'mp4' => 250, '3gpp' => 250, 'mov' => 250, 'avi' => 250, 'wmv' => 250, 'flv' => 250,
  74. 'dwg' => 250, 'dxf' => 250, '3ds' => 250, 'ai' => 250, 'psd' => 250
  75. ];
  76. public function __construct()
  77. {
  78. $this->responseController = new ResponseController();
  79. $this->encryptionController = new EncryptionController();
  80. $this->documentManagementController = new DocumentManagementController();
  81. }
  82. /**
  83. * Main validation endpoint that validates both Excel and ZIP files
  84. * Checks Excel headers, ZIP integrity, file listings, and compares them
  85. */
  86. public function validateFiles(Request $request)
  87. {
  88. Log::info('=== INICIANDO VALIDACIÓN DE ARCHIVOS ===');
  89. // Validate request inputs
  90. Log::info('Paso 1: Validando tipos de archivo');
  91. $validator = Validator::make($request->all(), [
  92. 'id_user' => 'required|string',
  93. 'linea' => 'required|integer',
  94. 'excel_file' => 'required|file|mimes:xlsx,xls',
  95. 'zip_file' => 'required|file|mimes:zip'
  96. ]);
  97. if ($validator->fails()) {
  98. Log::error('Error en validación de tipos de archivo', $validator->errors()->toArray());
  99. return $this->responseController->makeResponse(
  100. true,
  101. 'Se encontraron uno o más errores.',
  102. $this->responseController->makeErrors($validator->errors()->messages()),
  103. 400
  104. );
  105. }
  106. Log::info('✓ Tipos de archivo válidos');
  107. // Validate Excel file headers structure
  108. Log::info('Paso 2: Validando encabezados de Excel');
  109. $excelValidation = $this->validateExcelHeaders($request->file('excel_file'));
  110. if ($excelValidation['error']) {
  111. Log::error('Error en encabezados Excel: ' . $excelValidation['message']);
  112. return $this->responseController->makeResponse(true, $excelValidation['message'], [], 400);
  113. }
  114. Log::info('✓ Encabezados de Excel válidos');
  115. // Extract and validate file listings from Excel
  116. Log::info('Paso 3: Extrayendo listado de archivos del Excel');
  117. $filesValidation = $this->extractAndValidateFiles($request->file('excel_file'));
  118. if ($filesValidation['error']) {
  119. Log::error('Error extrayendo archivos Excel: ' . $filesValidation['message']);
  120. return $this->responseController->makeResponse(true, $filesValidation['message'], [], 400);
  121. }
  122. Log::info('✓ Archivos extraídos: ' . count($filesValidation['files']) . ' archivos encontrados');
  123. // Validate ZIP file integrity
  124. Log::info('Paso 4: Validando integridad del archivo ZIP');
  125. $zipValidation = $this->validateZipFile($request->file('zip_file'));
  126. if ($zipValidation['error']) {
  127. Log::error('Error validando ZIP: ' . $zipValidation['message']);
  128. return $this->responseController->makeResponse(true, $zipValidation['message'], [], 400);
  129. }
  130. Log::info('✓ Archivo ZIP válido');
  131. // Compare Excel file listings with ZIP contents
  132. Log::info('Paso 5: Comparando listados Excel vs ZIP y validando tamaños');
  133. $comparison = $this->compareExcelWithZip($filesValidation['files'], $request->file('zip_file'));
  134. // Check for file size validation errors
  135. if (isset($comparison['error'])) {
  136. Log::error('Error en validación de tamaños: ' . $comparison['error']);
  137. return $this->responseController->makeResponse(true, $comparison['error'], [], 400);
  138. }
  139. Log::info('✓ Comparación completada', [
  140. 'valid' => $comparison['valid'],
  141. 'missing_in_zip' => count($comparison['missing_in_zip'] ?? []),
  142. 'extra_in_zip' => count($comparison['extra_in_zip'] ?? [])
  143. ]);
  144. // Upload temp files if validation is successful
  145. if ($comparison['valid']) {
  146. Log::info('Paso 6: Subiendo archivos temporales');
  147. $tempFiles = $this->uploadTempFiles($request);
  148. if ($tempFiles['error']) {
  149. Log::error('Error subiendo archivos temporales: ' . $tempFiles['message']);
  150. return $this->responseController->makeResponse(true, $tempFiles['message'], [], 400);
  151. }
  152. Log::info('✓ Archivos temporales subidos');
  153. $comparison['temp_files'] = $tempFiles['files'];
  154. }
  155. Log::info('=== VALIDACIÓN COMPLETADA EXITOSAMENTE ===');
  156. return $this->responseController->makeResponse(false, 'Validación completada.', $comparison);
  157. }
  158. /**
  159. * Validates that Excel file has the correct headers in row 7
  160. * Each column must match the expected category name exactly
  161. */
  162. private function validateExcelHeaders($file)
  163. {
  164. try {
  165. Log::info(' - Cargando archivo Excel: ' . $file->getClientOriginalName());
  166. $spreadsheet = IOFactory::load($file->getPathname());
  167. $worksheet = $spreadsheet->getActiveSheet();
  168. Log::info(' - Excel cargado, validando encabezados en fila 7');
  169. // Check each expected header in row 7
  170. foreach ($this->expectedHeaders as $header) {
  171. $cellValue = $worksheet->getCell($header['letter'] . '7')->getValue();
  172. if (trim($cellValue) !== $header['category']) {
  173. return [
  174. 'error' => true,
  175. 'message' => "El encabezado en la columna {$header['letter']} no coincide. Se esperaba: '{$header['category']}', se encontró: '{$cellValue}'"
  176. ];
  177. }
  178. }
  179. return ['error' => false];
  180. } catch (\Exception $e) {
  181. return ['error' => true, 'message' => 'Error al procesar el archivo Excel: ' . $e->getMessage()];
  182. }
  183. }
  184. /**
  185. * Validates ZIP file integrity and ensures it's not empty
  186. */
  187. private function validateZipFile($file)
  188. {
  189. Log::info(' - Abriendo archivo ZIP: ' . $file->getClientOriginalName());
  190. $zip = new ZipArchive();
  191. $result = $zip->open($file->getPathname());
  192. if ($result !== TRUE) {
  193. return ['error' => true, 'message' => 'No se pudo abrir el archivo ZIP.'];
  194. }
  195. if ($zip->numFiles === 0) {
  196. $zip->close();
  197. return ['error' => true, 'message' => 'El archivo ZIP está vacío.'];
  198. }
  199. Log::info(' - ZIP contiene ' . $zip->numFiles . ' archivos');
  200. $zip->close();
  201. return ['error' => false];
  202. }
  203. /**
  204. * Extracts file listings from Excel starting from row 8
  205. * Validates file extensions and creates structured file list
  206. * Only processes rows with equipment code (column D)
  207. */
  208. private function extractAndValidateFiles($file)
  209. {
  210. try {
  211. $spreadsheet = IOFactory::load($file->getPathname());
  212. $worksheet = $spreadsheet->getActiveSheet();
  213. $highestRow = $worksheet->getHighestRow();
  214. Log::info(' - Procesando ' . ($highestRow - 7) . ' filas de datos (filas 8-' . $highestRow . ')');
  215. $files = [];
  216. // Process each row starting from row 8 (data rows)
  217. for ($row = 8; $row <= $highestRow; $row++) {
  218. $equipmentCode = trim($worksheet->getCell('D' . $row)->getValue());
  219. if (empty($equipmentCode)) continue; // Skip rows without equipment code
  220. $hasFiles = false;
  221. $rowFiles = [];
  222. // Check each file category column (excluding equipment code column D)
  223. foreach ($this->expectedHeaders as $header) {
  224. if ($header['letter'] === 'D') continue;
  225. $cellValue = trim($worksheet->getCell($header['letter'] . $row)->getValue());
  226. if (empty($cellValue)) continue;
  227. // Handle multiple files separated by commas
  228. $fileNames = explode(',', $cellValue);
  229. foreach ($fileNames as $fileName) {
  230. $fileName = trim($fileName);
  231. if (empty($fileName)) continue;
  232. // Validate file extension
  233. $extension = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));
  234. if (!isset($this->extensionTypes[$extension])) {
  235. return [
  236. 'error' => true,
  237. 'message' => "Extensión inválida '{$extension}' en archivo '{$fileName}' para equipo '{$equipmentCode}'"
  238. ];
  239. }
  240. $rowFiles[] = [
  241. 'equipment_code' => $equipmentCode,
  242. 'category' => $header['category'],
  243. 'file_name' => $fileName,
  244. 'type' => $this->extensionTypes[$extension]
  245. ];
  246. $hasFiles = true;
  247. }
  248. }
  249. if ($hasFiles) {
  250. $files = array_merge($files, $rowFiles);
  251. }
  252. }
  253. return ['error' => false, 'files' => $files];
  254. } catch (\Exception $e) {
  255. return ['error' => true, 'message' => 'Error al extraer archivos del Excel: ' . $e->getMessage()];
  256. }
  257. }
  258. /**
  259. * Compares file listings from Excel with actual files in ZIP
  260. * Returns validation status and lists of missing/extra files
  261. */
  262. private function compareExcelWithZip($excelFiles, $zipFile)
  263. {
  264. $zip = new ZipArchive();
  265. $zip->open($zipFile->getPathname());
  266. // Extract all file names and sizes from ZIP
  267. Log::info(' - Extrayendo nombres de archivos del ZIP');
  268. $zipFiles = [];
  269. $zipFileSizes = [];
  270. for ($i = 0; $i < $zip->numFiles; $i++) {
  271. $fullPath = $zip->getNameIndex($i);
  272. // Skip directories (entries ending with /)
  273. if (substr($fullPath, -1) === '/') {
  274. continue;
  275. }
  276. // Extract filename and size
  277. $fileName = basename($fullPath);
  278. if (!empty($fileName)) {
  279. $zipFiles[] = $fileName;
  280. $zipFileSizes[$fileName] = $zip->statIndex($i)['size'];
  281. }
  282. }
  283. $zip->close();
  284. Log::info(' - ZIP contiene ' . count($zipFiles) . ' archivos (excluyendo directorios)');
  285. // Validate file sizes
  286. Log::info(' - Validando tamaños de archivos');
  287. foreach ($zipFileSizes as $fileName => $size) {
  288. $extension = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));
  289. if (isset($this->fileSizeLimits[$extension])) {
  290. $limitMB = $this->fileSizeLimits[$extension];
  291. $limitBytes = $limitMB * 1024 * 1024;
  292. if ($size > $limitBytes) {
  293. $sizeMB = round($size / (1024 * 1024), 2);
  294. return [
  295. 'valid' => false,
  296. 'error' => "El archivo '{$fileName}' excede el límite de tamaño. Tamaño: {$sizeMB}MB, Límite: {$limitMB}MB"
  297. ];
  298. }
  299. }
  300. }
  301. // Get file names from Excel listings
  302. $excelFileNames = array_column($excelFiles, 'file_name');
  303. Log::info(' - Excel lista ' . count($excelFileNames) . ' archivos');
  304. // Find discrepancies between Excel and ZIP
  305. $missingInZip = array_diff($excelFileNames, $zipFiles);
  306. $extraInZip = array_diff($zipFiles, $excelFileNames);
  307. Log::info(' - Archivos faltantes en ZIP: ' . count($missingInZip));
  308. Log::info(' - Archivos extra en ZIP: ' . count($extraInZip));
  309. return [
  310. 'valid' => empty($missingInZip) && empty($extraInZip),
  311. 'missing_in_zip' => array_values($missingInZip),
  312. 'extra_in_zip' => array_values($extraInZip)
  313. ];
  314. }
  315. /**
  316. * Uploads Excel and ZIP files as temporary files using DocumentManagementController
  317. */
  318. private function uploadTempFiles(Request $request)
  319. {
  320. try {
  321. $tempFiles = [];
  322. // Upload Excel file
  323. $excelRequest = new Request();
  324. $excelRequest->files->set('file', $request->file('excel_file'));
  325. $excelRequest->merge([
  326. 'id_user' => $request->input('id_user'),
  327. 'linea' => $request->input('linea')
  328. ]);
  329. $excelResponse = $this->documentManagementController->uploadTempFile($excelRequest);
  330. $excelData = json_decode($excelResponse->getContent());
  331. Log::info('Excel upload response:', ['data' => $excelData]);
  332. if ($excelData->error) {
  333. $errorMsg = isset($excelData->message) ? $excelData->message : 'Error desconocido subiendo Excel';
  334. return ['error' => true, 'message' => 'Error subiendo Excel: ' . $errorMsg];
  335. }
  336. $tempFiles['excel'] = $excelData->response->idArchivo;
  337. // Upload ZIP file
  338. $zipRequest = new Request();
  339. $zipRequest->files->set('file', $request->file('zip_file'));
  340. $zipRequest->merge([
  341. 'id_user' => $request->input('id_user'),
  342. 'linea' => $request->input('linea')
  343. ]);
  344. $zipResponse = $this->documentManagementController->uploadTempFile($zipRequest);
  345. $zipData = json_decode($zipResponse->getContent());
  346. Log::info('ZIP upload response:', ['data' => $zipData]);
  347. if ($zipData->error) {
  348. $errorMsg = isset($zipData->message) ? $zipData->message : 'Error desconocido subiendo ZIP';
  349. return ['error' => true, 'message' => 'Error subiendo ZIP: ' . $errorMsg];
  350. }
  351. $tempFiles['zip'] = $zipData->response->idArchivo;
  352. return ['error' => false, 'files' => $tempFiles];
  353. } catch (\Exception $e) {
  354. return ['error' => true, 'message' => 'Error en uploadTempFiles: ' . $e->getMessage()];
  355. }
  356. }
  357. /**
  358. * Process endpoint that moves temp files to final storage
  359. */
  360. public function processLoadArchives(Request $request)
  361. {
  362. Log::info('=== INICIANDO PROCESAMIENTO DE ARCHIVOS ===');
  363. $validator = Validator::make($request->all(), [
  364. 'id_user' => 'required|string',
  365. 'linea' => 'required|integer',
  366. 'temp_files' => 'required|array',
  367. 'temp_files.excel' => 'required|string',
  368. 'temp_files.zip' => 'required|string'
  369. ]);
  370. if ($validator->fails()) {
  371. return $this->responseController->makeResponse(
  372. true,
  373. 'Se encontraron uno o más errores.',
  374. $this->responseController->makeErrors($validator->errors()->messages()),
  375. 400
  376. );
  377. }
  378. $form = $request->all();
  379. // $idUser = $this->encryptionController->decrypt($form['id_user']);
  380. $idUser = "0000000001";
  381. if (!$idUser) {
  382. return $this->responseController->makeResponse(true, 'ID de usuario inválido.', [], 400);
  383. }
  384. $finalFiles = [];
  385. try {
  386. // Move Excel to final
  387. Log::info('Moviendo Excel a almacenamiento final');
  388. $excelFinal = $this->moveToFinal($form['temp_files']['excel'], $form['linea'], $idUser);
  389. if (!$excelFinal) {
  390. return $this->responseController->makeResponse(true, 'Error procesando Excel', [], 400);
  391. }
  392. $finalFiles['excel'] = $excelFinal;
  393. // Move ZIP to final
  394. Log::info('Moviendo ZIP a almacenamiento final');
  395. $zipFinal = $this->moveToFinal($form['temp_files']['zip'], $form['linea'], $idUser);
  396. if (!$zipFinal) {
  397. return $this->responseController->makeResponse(true, 'Error procesando ZIP', [], 400);
  398. }
  399. $finalFiles['zip'] = $zipFinal;
  400. Log::info('=== PROCESAMIENTO COMPLETADO EXITOSAMENTE ===');
  401. return $this->responseController->makeResponse(false, 'Archivos procesados exitosamente.', $finalFiles);
  402. } catch (\Exception $e) {
  403. Log::error('Error en procesamiento: ' . $e->getMessage());
  404. return $this->responseController->makeResponse(true, 'Error interno: ' . $e->getMessage(), [], 500);
  405. }
  406. }
  407. /**
  408. * Moves a temporary file to final storage using DocumentManagementController
  409. */
  410. private function moveToFinal($tempId, $line, $idUser)
  411. {
  412. try {
  413. $tempIdDec = $this->encryptionController->decrypt($tempId);
  414. if (!$tempIdDec) {
  415. return false;
  416. }
  417. $tempFile = DB::table('S002V01TARTE')->where('ARTE_IDAR', $tempIdDec)->first();
  418. if (!$tempFile) {
  419. return false;
  420. }
  421. $result = $this->documentManagementController->moveFinalFile($line, 'GDEL', 'CA', $tempFile, $idUser);
  422. return $result[0] ? $result[1] : false;
  423. } catch (\Exception $e) {
  424. Log::error('Error en moveToFinal: ' . $e->getMessage());
  425. return false;
  426. }
  427. }
  428. }