ExportPrimaNota.php 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880
  1. <?php
  2. namespace App\Jobs;
  3. use Illuminate\Bus\Queueable;
  4. use Illuminate\Contracts\Queue\ShouldQueue;
  5. use Illuminate\Foundation\Bus\Dispatchable;
  6. use Illuminate\Queue\InteractsWithQueue;
  7. use Illuminate\Queue\SerializesModels;
  8. use Illuminate\Support\Facades\Mail;
  9. use Illuminate\Support\Facades\Log;
  10. use App\Mail\ExportNotification;
  11. use App\Events\ExportCompleted;
  12. use App\Events\ExportFailed;
  13. use PhpOffice\PhpSpreadsheet\Spreadsheet;
  14. use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
  15. class ExportPrimaNota implements ShouldQueue
  16. {
  17. use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
  18. public $timeout = 1200;
  19. public $tries = 3;
  20. public $maxExceptions = 3;
  21. protected $exportData;
  22. protected $exportTotals;
  23. protected $emailAddress;
  24. protected $emailSubject;
  25. protected $dateRange;
  26. protected $userId;
  27. protected $payments;
  28. protected $filters;
  29. /**
  30. * Create a new job instance.
  31. */
  32. public function __construct($exportData, $exportTotals, $emailAddress, $emailSubject, $dateRange, $userId, $payments, $filters = [])
  33. {
  34. $this->exportData = $exportData;
  35. $this->exportTotals = $exportTotals;
  36. $this->emailAddress = $emailAddress;
  37. $this->emailSubject = $emailSubject;
  38. $this->dateRange = $dateRange;
  39. $this->userId = $userId;
  40. $this->payments = $payments;
  41. $this->filters = $filters;
  42. $this->onQueue('exports');
  43. }
  44. /**
  45. * Execute the job.
  46. */
  47. public function handle()
  48. {
  49. try {
  50. Log::info('Starting background export', [
  51. 'user_id' => $this->userId,
  52. 'email' => $this->emailAddress,
  53. 'date_range' => $this->dateRange,
  54. 'total_records' => count($this->exportData)
  55. ]);
  56. ini_set('memory_limit', '1024M');
  57. $filename = 'prima_nota_' . date("Ymd_His") . '_' . $this->userId . '.xlsx';
  58. $tempPath = sys_get_temp_dir() . '/' . $filename;
  59. $this->createExcelFile($tempPath);
  60. if (!file_exists($tempPath) || filesize($tempPath) === 0) {
  61. throw new \Exception('Excel file creation failed');
  62. }
  63. $fileSize = filesize($tempPath);
  64. $maxSize = 25 * 1024 * 1024;
  65. if ($fileSize > $maxSize) {
  66. throw new \Exception('File too large for email attachment (' . round($fileSize / 1024 / 1024, 2) . 'MB > 25MB)');
  67. }
  68. $user = \App\Models\User::find($this->userId);
  69. $emailData = [
  70. 'subject' => $this->emailSubject,
  71. 'from_date' => $this->dateRange['from'],
  72. 'to_date' => $this->dateRange['to'],
  73. 'total_records' => count($this->exportData),
  74. 'user_name' => $user ? $user->name : 'Utente',
  75. 'generated_at' => now()->format('d/m/Y H:i:s'),
  76. 'filters_applied' => $this->getFiltersDescription(),
  77. 'file_size' => round($fileSize / 1024 / 1024, 2) . ' MB'
  78. ];
  79. Mail::to($this->emailAddress)->send(new ExportNotification($emailData, $tempPath, $filename));
  80. if (class_exists(ExportCompleted::class)) {
  81. broadcast(new ExportCompleted($this->userId, $filename, $this->emailAddress));
  82. }
  83. Log::info('Background export completed successfully', [
  84. 'user_id' => $this->userId,
  85. 'email' => $this->emailAddress,
  86. 'filename' => $filename,
  87. 'file_size' => $fileSize,
  88. 'processing_time' => microtime(true) - LARAVEL_START ?? 0
  89. ]);
  90. } catch (\Exception $e) {
  91. Log::error('Background export failed', [
  92. 'user_id' => $this->userId,
  93. 'email' => $this->emailAddress,
  94. 'error' => $e->getMessage(),
  95. 'trace' => $e->getTraceAsString()
  96. ]);
  97. if (class_exists(ExportFailed::class)) {
  98. broadcast(new ExportFailed($this->userId, $e->getMessage()));
  99. }
  100. throw $e;
  101. } finally {
  102. if (isset($tempPath) && file_exists($tempPath)) {
  103. unlink($tempPath);
  104. }
  105. gc_collect_cycles();
  106. }
  107. }
  108. /**
  109. * Handle a job failure.
  110. */
  111. public function failed(\Throwable $exception)
  112. {
  113. Log::error('Export job failed permanently', [
  114. 'user_id' => $this->userId,
  115. 'email' => $this->emailAddress,
  116. 'attempts' => $this->attempts(),
  117. 'error' => $exception->getMessage()
  118. ]);
  119. try {
  120. Mail::raw(
  121. "Il tuo export della Prima Nota non è riuscito dopo {$this->tries} tentativi.\n\n" .
  122. "Errore: {$exception->getMessage()}\n\n" .
  123. "Contatta il supporto tecnico se il problema persiste.",
  124. function ($message) {
  125. $message->to($this->emailAddress)
  126. ->subject('Export Prima Nota - Errore');
  127. }
  128. );
  129. } catch (\Exception $e) {
  130. Log::error('Failed to send failure notification email', [
  131. 'user_id' => $this->userId,
  132. 'error' => $e->getMessage()
  133. ]);
  134. }
  135. }
  136. /**
  137. * Create Excel file with export data
  138. */
  139. private function createExcelFile($filePath)
  140. {
  141. Log::info('Job createExcelFile: Starting Excel file creation', [
  142. 'file_path' => $filePath,
  143. 'export_data_count' => count($this->exportData),
  144. 'payments_count' => count($this->payments),
  145. 'memory_before' => memory_get_usage(true),
  146. 'time_limit' => ini_get('max_execution_time')
  147. ]);
  148. $startTime = microtime(true);
  149. Log::info('Job createExcelFile: Preparing column letters');
  150. $letters = array('F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'AA');
  151. Log::info('Job createExcelFile: Creating Spreadsheet object');
  152. $spreadsheet = new Spreadsheet();
  153. $activeWorksheet = $spreadsheet->getActiveSheet();
  154. $activeWorksheet->setTitle('Prima Nota');
  155. Log::info('Job createExcelFile: Setting document properties');
  156. $spreadsheet->getProperties()
  157. ->setCreator('Prima Nota System')
  158. ->setLastModifiedBy('Sistema')
  159. ->setTitle('Prima Nota Export')
  160. ->setSubject('Export Prima Nota')
  161. ->setDescription('Export dei dati Prima Nota dal ' . $this->dateRange['from'] . ' al ' . $this->dateRange['to']);
  162. Log::info('Job createExcelFile: Setting basic headers');
  163. $activeWorksheet->setCellValue('A1', "Data");
  164. $activeWorksheet->setCellValue('B1', "Tipologia");
  165. $activeWorksheet->setCellValue('C1', "Causale");
  166. $activeWorksheet->setCellValue('D1', "Nominativo");
  167. $activeWorksheet->setCellValue('E1', "Stato");
  168. Log::info('Job createExcelFile: Setting payment method headers and merging cells');
  169. $idx = 0;
  170. foreach ($this->payments as $p) {
  171. if ($idx >= count($letters)) {
  172. Log::warning('Job createExcelFile: Reached letter limit during header setup', [
  173. 'payment_index' => $idx,
  174. 'payment_name' => $p['name']
  175. ]);
  176. break;
  177. }
  178. Log::debug('Job createExcelFile: Setting payment header', [
  179. 'payment_name' => $p['name'],
  180. 'column_index' => $idx,
  181. 'column_letter' => $letters[$idx]
  182. ]);
  183. $activeWorksheet->setCellValue($letters[$idx] . '1', $p['name']);
  184. $activeWorksheet->mergeCells($letters[$idx] . '1:' . $letters[$idx + 1] . '1');
  185. $idx += 2;
  186. }
  187. Log::info('Job createExcelFile: Setting sub-headers (row 2)');
  188. $activeWorksheet->setCellValue('A2', "");
  189. $activeWorksheet->setCellValue('B2', "");
  190. $activeWorksheet->setCellValue('C2', "");
  191. $activeWorksheet->setCellValue('D2', "");
  192. $activeWorksheet->setCellValue('E2', "");
  193. $idx = 0;
  194. foreach ($this->payments as $p) {
  195. if ($idx >= count($letters) - 1) {
  196. Log::warning('Job createExcelFile: Reached letter limit during sub-header setup', [
  197. 'payment_index' => $idx,
  198. 'payment_name' => $p['name']
  199. ]);
  200. break;
  201. }
  202. if ($p['type'] == 'ALL') {
  203. $activeWorksheet->setCellValue($letters[$idx] . '2', "Entrate");
  204. $idx++;
  205. $activeWorksheet->setCellValue($letters[$idx] . '2', "Uscite");
  206. $idx++;
  207. } elseif ($p['type'] == 'IN') {
  208. $activeWorksheet->setCellValue($letters[$idx] . '2', "Entrate");
  209. $idx++;
  210. $activeWorksheet->setCellValue($letters[$idx] . '2', "");
  211. $idx++;
  212. } elseif ($p['type'] == 'OUT') {
  213. $activeWorksheet->setCellValue($letters[$idx] . '2', "");
  214. $idx++;
  215. $activeWorksheet->setCellValue($letters[$idx] . '2', "Uscite");
  216. $idx++;
  217. }
  218. }
  219. Log::info('Job createExcelFile: Applying header styles');
  220. $maxCol = min(count($letters) - 1, count($this->payments) * 2 + 4);
  221. $lastColumnLetter = $letters[$maxCol];
  222. $activeWorksheet->getStyle('A1:' . $lastColumnLetter . '2')
  223. ->getFont()->setBold(true);
  224. $activeWorksheet->getStyle('A1:' . $lastColumnLetter . '1')
  225. ->getFill()
  226. ->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)
  227. ->getStartColor()->setARGB('FF0C6197');
  228. $activeWorksheet->getStyle('A1:' . $lastColumnLetter . '1')
  229. ->getFont()->getColor()->setARGB('FFFFFFFF');
  230. Log::info('Job createExcelFile: Starting data row processing', [
  231. 'total_export_records' => count($this->exportData),
  232. 'time_elapsed_so_far' => microtime(true) - $startTime
  233. ]);
  234. $count = 3;
  235. $batchSize = 500;
  236. $processed = 0;
  237. $batchNumber = 0;
  238. foreach ($this->exportData as $causal => $record) {
  239. if ($processed % 100 == 0) {
  240. Log::info('Job createExcelFile: Processing progress', [
  241. 'processed' => $processed,
  242. 'total' => count($this->exportData),
  243. 'current_row' => $count,
  244. 'memory_usage' => memory_get_usage(true),
  245. 'memory_peak' => memory_get_peak_usage(true),
  246. 'time_elapsed' => microtime(true) - $startTime
  247. ]);
  248. }
  249. try {
  250. $parts = explode("§", $causal);
  251. $d = $parts[0] ?? '';
  252. $c = $parts[1] ?? '';
  253. $j = $parts[2] ?? '';
  254. $det = $parts[3] ?? '';
  255. $deleted = $parts[4] ?? '';
  256. $detailParts = explode('|', $det);
  257. $exportDetail = count($detailParts) > 1 ? implode(', ', array_slice($detailParts, 1)) : $det;
  258. Log::debug('Job createExcelFile: Setting row data', [
  259. 'row' => $count,
  260. 'causal_parts' => count($parts)
  261. ]);
  262. $activeWorksheet->setCellValue('A' . $count, !empty($d) ? date("d/m/Y", strtotime($d)) : '');
  263. $activeWorksheet->setCellValue('B' . $count, $c);
  264. $activeWorksheet->setCellValue('C' . $count, $exportDetail);
  265. $activeWorksheet->setCellValue('D' . $count, $j);
  266. $stato = ($deleted === 'DELETED') ? 'ANNULLATA' : '';
  267. $activeWorksheet->setCellValue('E' . $count, $stato);
  268. if ($stato === 'ANNULLATA') {
  269. $activeWorksheet->getStyle('E' . $count)->getFont()->getColor()->setARGB('FFFF0000');
  270. }
  271. Log::debug('Job createExcelFile: Setting payment data for row', ['row' => $count]);
  272. $idx = 0;
  273. foreach ($this->payments as $p) {
  274. if ($idx >= count($letters) - 1) {
  275. Log::warning('Job createExcelFile: Reached letter limit during payment data', [
  276. 'row' => $count,
  277. 'payment_index' => $idx
  278. ]);
  279. break;
  280. }
  281. if (isset($record[$p['name']])) {
  282. $inValue = isset($record[$p['name']]["IN"]) ? $this->formatPrice($record[$p['name']]["IN"]) : "";
  283. $outValue = isset($record[$p['name']]["OUT"]) ? $this->formatPrice($record[$p['name']]["OUT"]) : "";
  284. $activeWorksheet->setCellValue($letters[$idx] . $count, $inValue);
  285. $idx++;
  286. $activeWorksheet->setCellValue($letters[$idx] . $count, $outValue);
  287. $idx++;
  288. } else {
  289. $activeWorksheet->setCellValue($letters[$idx] . $count, "");
  290. $idx++;
  291. $activeWorksheet->setCellValue($letters[$idx] . $count, "");
  292. $idx++;
  293. }
  294. }
  295. $count++;
  296. $processed++;
  297. if ($processed % $batchSize === 0) {
  298. $batchNumber++;
  299. Log::info('Job createExcelFile: Batch completed, running garbage collection', [
  300. 'batch_number' => $batchNumber,
  301. 'processed' => $processed,
  302. 'memory_before_gc' => memory_get_usage(true)
  303. ]);
  304. gc_collect_cycles();
  305. Log::info('Job createExcelFile: Garbage collection completed', [
  306. 'memory_after_gc' => memory_get_usage(true)
  307. ]);
  308. }
  309. } catch (\Exception $e) {
  310. Log::error('Job createExcelFile: Error processing data row', [
  311. 'row' => $count,
  312. 'processed_so_far' => $processed,
  313. 'causal' => $causal,
  314. 'error' => $e->getMessage(),
  315. 'trace' => $e->getTraceAsString()
  316. ]);
  317. throw $e;
  318. }
  319. }
  320. Log::info('Job createExcelFile: Data processing completed, adding totals row', [
  321. 'total_processed' => $processed,
  322. 'final_row' => $count,
  323. 'processing_time' => microtime(true) - $startTime
  324. ]);
  325. $count++;
  326. $activeWorksheet->setCellValue('A' . $count, 'TOTALE');
  327. $activeWorksheet->setCellValue('B' . $count, '');
  328. $activeWorksheet->setCellValue('C' . $count, '');
  329. $activeWorksheet->setCellValue('D' . $count, '');
  330. $activeWorksheet->setCellValue('E' . $count, '');
  331. Log::info('Job createExcelFile: Setting totals data');
  332. $idx = 0;
  333. foreach ($this->payments as $p) {
  334. if ($idx >= count($letters) - 1) {
  335. break;
  336. }
  337. if (isset($this->exportTotals[$p['name']])) {
  338. if ($p['type'] == 'ALL') {
  339. $activeWorksheet->setCellValue($letters[$idx] . $count, $this->formatPrice($this->exportTotals[$p['name']]["IN"] ?? 0));
  340. $idx++;
  341. $activeWorksheet->setCellValue($letters[$idx] . $count, $this->formatPrice($this->exportTotals[$p['name']]["OUT"] ?? 0));
  342. $idx++;
  343. } elseif ($p['type'] == 'IN') {
  344. $activeWorksheet->setCellValue($letters[$idx] . $count, $this->formatPrice($this->exportTotals[$p['name']]["IN"] ?? 0));
  345. $idx++;
  346. $activeWorksheet->setCellValue($letters[$idx] . $count, "");
  347. $idx++;
  348. } elseif ($p['type'] == 'OUT') {
  349. $activeWorksheet->setCellValue($letters[$idx] . $count, "");
  350. $idx++;
  351. $activeWorksheet->setCellValue($letters[$idx] . $count, $this->formatPrice($this->exportTotals[$p['name']]["OUT"] ?? 0));
  352. $idx++;
  353. }
  354. } else {
  355. $activeWorksheet->setCellValue($letters[$idx] . $count, "0,00");
  356. $idx++;
  357. $activeWorksheet->setCellValue($letters[$idx] . $count, "0,00");
  358. $idx++;
  359. }
  360. }
  361. Log::info('Job createExcelFile: Applying totals row styling');
  362. $activeWorksheet->getStyle('A' . $count . ':' . $lastColumnLetter . $count)
  363. ->getFont()->setBold(true);
  364. $activeWorksheet->getStyle('A' . $count . ':' . $lastColumnLetter . $count)
  365. ->getFill()
  366. ->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)
  367. ->getStartColor()->setARGB('FFF0F0F0');
  368. Log::info('Job createExcelFile: Setting column dimensions');
  369. $activeWorksheet->getColumnDimension('A')->setWidth(15);
  370. $activeWorksheet->getColumnDimension('B')->setWidth(25);
  371. $activeWorksheet->getColumnDimension('C')->setWidth(30);
  372. $activeWorksheet->getColumnDimension('D')->setWidth(25);
  373. $activeWorksheet->getColumnDimension('E')->setWidth(15);
  374. foreach ($letters as $l) {
  375. $activeWorksheet->getColumnDimension($l)->setWidth(15);
  376. }
  377. Log::info('Job createExcelFile: Setting freeze panes');
  378. $activeWorksheet->freezePane('A3');
  379. Log::info('Job createExcelFile: Creating Excel writer and saving file', [
  380. 'file_path' => $filePath,
  381. 'memory_before_save' => memory_get_usage(true)
  382. ]);
  383. try {
  384. $writerStart = microtime(true);
  385. $writer = new Xlsx($spreadsheet);
  386. $writer->save($filePath);
  387. $writerTime = microtime(true) - $writerStart;
  388. Log::info('Job createExcelFile: File saved successfully', [
  389. 'file_path' => $filePath,
  390. 'file_exists' => file_exists($filePath),
  391. 'file_size' => file_exists($filePath) ? filesize($filePath) : 0,
  392. 'writer_time' => $writerTime,
  393. 'total_time' => microtime(true) - $startTime,
  394. 'memory_peak' => memory_get_peak_usage(true)
  395. ]);
  396. } catch (\Exception $e) {
  397. Log::error('Job createExcelFile: Error during file save', [
  398. 'file_path' => $filePath,
  399. 'error' => $e->getMessage(),
  400. 'trace' => $e->getTraceAsString(),
  401. 'memory_usage' => memory_get_usage(true),
  402. 'time_elapsed' => microtime(true) - $startTime
  403. ]);
  404. throw $e;
  405. }
  406. Log::info('Job createExcelFile: Cleaning up memory');
  407. unset($spreadsheet, $activeWorksheet, $writer);
  408. gc_collect_cycles();
  409. Log::info('Job createExcelFile: Completed successfully', [
  410. 'total_time' => microtime(true) - $startTime,
  411. 'memory_after_cleanup' => memory_get_usage(true)
  412. ]);
  413. }
  414. // Generate column letters more efficiently
  415. private function generateColumnLetters($count)
  416. {
  417. $letters = [];
  418. for ($i = 0; $i < $count && $i < 100; $i++) { // Limit to prevent infinite loops
  419. if ($i < 26) {
  420. $letters[] = chr(65 + $i); // A-Z
  421. } else {
  422. $letters[] = 'A' . chr(65 + ($i - 26)); // AA, AB, AC...
  423. }
  424. }
  425. return $letters;
  426. }
  427. // Build headers more efficiently
  428. private function buildHeaders($activeWorksheet, $letters)
  429. {
  430. // Set basic headers
  431. $basicHeaders = [
  432. 'A1' => 'Data',
  433. 'B1' => 'Causale',
  434. 'C1' => 'Dettaglio Causale',
  435. 'D1' => 'Nominativo',
  436. 'E1' => 'Stato'
  437. ];
  438. // Use fromArray for faster header setting
  439. $activeWorksheet->fromArray(array_values($basicHeaders), null, 'A1', true);
  440. // Set payment method headers
  441. $paymentHeaders = [];
  442. $subHeaders = [];
  443. $idx = 5; // Start after basic headers (F column = index 5)
  444. foreach ($this->payments as $p) {
  445. if ($idx >= count($letters)) break;
  446. $paymentHeaders[] = $p['name'];
  447. $activeWorksheet->mergeCells($letters[$idx] . '1:' . $letters[$idx + 1] . '1');
  448. // Sub headers for row 2
  449. if ($p['type'] == 'ALL') {
  450. $subHeaders[$letters[$idx] . '2'] = 'Entrate';
  451. $subHeaders[$letters[$idx + 1] . '2'] = 'Uscite';
  452. } elseif ($p['type'] == 'IN') {
  453. $subHeaders[$letters[$idx] . '2'] = 'Entrate';
  454. $subHeaders[$letters[$idx + 1] . '2'] = '';
  455. } elseif ($p['type'] == 'OUT') {
  456. $subHeaders[$letters[$idx] . '2'] = '';
  457. $subHeaders[$letters[$idx + 1] . '2'] = 'Uscite';
  458. }
  459. $idx += 2;
  460. }
  461. // Set payment headers
  462. $col = 5;
  463. foreach ($paymentHeaders as $header) {
  464. if ($col < count($letters)) {
  465. $activeWorksheet->setCellValue($letters[$col] . '1', $header);
  466. }
  467. $col += 2;
  468. }
  469. // Set sub headers
  470. foreach ($subHeaders as $cell => $value) {
  471. $activeWorksheet->setCellValue($cell, $value);
  472. }
  473. }
  474. // Build data rows with batch processing
  475. private function buildDataRows($activeWorksheet, $letters)
  476. {
  477. $rowNum = 3; // Start after headers
  478. $batchSize = 100; // Process in smaller batches
  479. $batch = [];
  480. $batchCount = 0;
  481. foreach ($this->exportData as $causal => $record) {
  482. $parts = explode("§", $causal);
  483. $d = $parts[0] ?? '';
  484. $c = $parts[1] ?? '';
  485. $j = $parts[2] ?? '';
  486. $det = $parts[3] ?? '';
  487. $deleted = $parts[4] ?? '';
  488. $detailParts = explode('|', $det);
  489. $exportDetail = count($detailParts) > 1 ? implode(', ', array_slice($detailParts, 1)) : $det;
  490. // Prepare row data
  491. $rowData = [
  492. !empty($d) ? date("d/m/Y", strtotime($d)) : '',
  493. $c,
  494. $exportDetail,
  495. $j,
  496. ($deleted === 'DELETED') ? 'ANNULLATA' : ''
  497. ];
  498. // Add payment method values
  499. $idx = 0;
  500. foreach ($this->payments as $p) {
  501. if ($idx >= count($letters) - 6) break; // Leave room for basic columns
  502. if (isset($record[$p['name']])) {
  503. $inValue = isset($record[$p['name']]["IN"]) ? $this->formatPrice($record[$p['name']]["IN"]) : "";
  504. $outValue = isset($record[$p['name']]["OUT"]) ? $this->formatPrice($record[$p['name']]["OUT"]) : "";
  505. $rowData[] = $inValue;
  506. $rowData[] = $outValue;
  507. } else {
  508. $rowData[] = "";
  509. $rowData[] = "";
  510. }
  511. $idx += 2;
  512. }
  513. $batch[] = $rowData;
  514. $batchCount++;
  515. // Process batch when it reaches batch size
  516. if ($batchCount >= $batchSize) {
  517. $this->writeBatchToWorksheet($activeWorksheet, $batch, $rowNum);
  518. $rowNum += $batchCount;
  519. $batch = [];
  520. $batchCount = 0;
  521. gc_collect_cycles(); // Force garbage collection
  522. }
  523. }
  524. // Process remaining batch
  525. if (!empty($batch)) {
  526. $this->writeBatchToWorksheet($activeWorksheet, $batch, $rowNum);
  527. }
  528. }
  529. // Write batch data efficiently
  530. private function writeBatchToWorksheet($activeWorksheet, $batch, $startRow)
  531. {
  532. if (empty($batch)) return;
  533. try {
  534. // Use fromArray for much faster bulk insertion
  535. $activeWorksheet->fromArray($batch, null, 'A' . $startRow, true);
  536. // Apply conditional formatting for deleted records
  537. foreach ($batch as $index => $row) {
  538. $currentRow = $startRow + $index;
  539. if (isset($row[4]) && $row[4] === 'ANNULLATA') {
  540. $activeWorksheet->getStyle('E' . $currentRow)
  541. ->getFont()->getColor()->setARGB('FFFF0000');
  542. }
  543. }
  544. } catch (\Exception $e) {
  545. Log::error('Error writing batch to worksheet', [
  546. 'error' => $e->getMessage(),
  547. 'batch_size' => count($batch),
  548. 'start_row' => $startRow
  549. ]);
  550. // Fallback to individual cell setting
  551. foreach ($batch as $index => $row) {
  552. $currentRow = $startRow + $index;
  553. foreach ($row as $colIndex => $value) {
  554. $col = $this->getColumnLetter($colIndex);
  555. $activeWorksheet->setCellValue($col . $currentRow, $value);
  556. }
  557. }
  558. }
  559. }
  560. // Helper to get column letter by index
  561. private function getColumnLetter($index)
  562. {
  563. if ($index < 26) {
  564. return chr(65 + $index);
  565. } else {
  566. return 'A' . chr(65 + ($index - 26));
  567. }
  568. }
  569. // Build totals row efficiently
  570. private function buildTotalsRow($activeWorksheet, $letters)
  571. {
  572. $totalRows = count($this->exportData) + 3; // +3 for headers and spacing
  573. $totalRow = $totalRows + 1;
  574. $totalsData = ['TOTALE', '', '', '', ''];
  575. $idx = 0;
  576. foreach ($this->payments as $p) {
  577. if ($idx >= count($letters) - 6) break;
  578. if (isset($this->exportTotals[$p['name']])) {
  579. if ($p['type'] == 'ALL') {
  580. $totalsData[] = $this->formatPrice($this->exportTotals[$p['name']]["IN"] ?? 0);
  581. $totalsData[] = $this->formatPrice($this->exportTotals[$p['name']]["OUT"] ?? 0);
  582. } elseif ($p['type'] == 'IN') {
  583. $totalsData[] = $this->formatPrice($this->exportTotals[$p['name']]["IN"] ?? 0);
  584. $totalsData[] = "";
  585. } elseif ($p['type'] == 'OUT') {
  586. $totalsData[] = "";
  587. $totalsData[] = $this->formatPrice($this->exportTotals[$p['name']]["OUT"] ?? 0);
  588. }
  589. } else {
  590. $totalsData[] = "0,00";
  591. $totalsData[] = "0,00";
  592. }
  593. $idx += 2;
  594. }
  595. // Write totals row
  596. $activeWorksheet->fromArray([$totalsData], null, 'A' . $totalRow, true);
  597. }
  598. private function applyStylesEfficiently($activeWorksheet, $letters)
  599. {
  600. $maxCol = min(count($letters) - 1, count($this->payments) * 2 + 4);
  601. $lastCol = $letters[$maxCol];
  602. $totalRows = count($this->exportData) + 4;
  603. $headerRange = 'A1:' . $lastCol . '2';
  604. $activeWorksheet->getStyle($headerRange)->getFont()->setBold(true);
  605. $activeWorksheet->getStyle('A1:' . $lastCol . '1')
  606. ->getFill()
  607. ->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)
  608. ->getStartColor()->setARGB('FF0C6197');
  609. $activeWorksheet->getStyle('A1:' . $lastCol . '1')
  610. ->getFont()->getColor()->setARGB('FFFFFFFF');
  611. $totalsRange = 'A' . $totalRows . ':' . $lastCol . $totalRows;
  612. $activeWorksheet->getStyle($totalsRange)->getFont()->setBold(true);
  613. $activeWorksheet->getStyle($totalsRange)
  614. ->getFill()
  615. ->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)
  616. ->getStartColor()->setARGB('FFF0F0F0');
  617. }
  618. private function setColumnDimensions($activeWorksheet, $letters)
  619. {
  620. $dimensions = [
  621. 'A' => 15,
  622. 'B' => 25,
  623. 'C' => 30,
  624. 'D' => 25,
  625. 'E' => 15
  626. ];
  627. foreach ($dimensions as $col => $width) {
  628. $activeWorksheet->getColumnDimension($col)->setWidth($width);
  629. }
  630. for ($i = 5; $i < count($letters) && $i < 50; $i++) {
  631. $activeWorksheet->getColumnDimension($letters[$i])->setWidth(15);
  632. }
  633. }
  634. /**
  635. * Format price for display
  636. */
  637. private function formatPrice($amount)
  638. {
  639. return number_format($amount, 2, ',', '.');
  640. }
  641. /**
  642. * Get description of applied filters
  643. */
  644. private function getFiltersDescription()
  645. {
  646. $descriptions = [];
  647. if (!empty($this->filters['member'])) {
  648. $descriptions[] = "Utente: {$this->filters['member']}";
  649. }
  650. if (!empty($this->filters['causals'])) {
  651. $descriptions[] = "Causali: " . (is_array($this->filters['causals']) ? implode(', ', $this->filters['causals']) : $this->filters['causals']);
  652. }
  653. return empty($descriptions) ? 'Nessun filtro applicato' : implode(' | ', $descriptions);
  654. }
  655. public function executeWithTimeoutMonitoring($callback, $description = 'Operation')
  656. {
  657. $startTime = microtime(true);
  658. $maxExecutionTime = ini_get('max_execution_time');
  659. Log::info("Starting monitored operation: {$description}", [
  660. 'start_time' => $startTime,
  661. 'max_execution_time' => $maxExecutionTime,
  662. 'memory_start' => memory_get_usage(true)
  663. ]);
  664. try {
  665. $lastCheck = $startTime;
  666. $result = null;
  667. register_tick_function(function () use ($startTime, $maxExecutionTime, $description, &$lastCheck) {
  668. $currentTime = microtime(true);
  669. if ($currentTime - $lastCheck >= 5) {
  670. $elapsed = $currentTime - $startTime;
  671. $remaining = $maxExecutionTime > 0 ? $maxExecutionTime - $elapsed : 'unlimited';
  672. Log::info("Operation progress: {$description}", [
  673. 'elapsed_time' => $elapsed,
  674. 'remaining_time' => $remaining,
  675. 'memory_current' => memory_get_usage(true),
  676. 'memory_peak' => memory_get_peak_usage(true)
  677. ]);
  678. if ($maxExecutionTime > 0 && $elapsed > ($maxExecutionTime * 0.8)) {
  679. Log::warning("Operation approaching timeout: {$description}", [
  680. 'elapsed_time' => $elapsed,
  681. 'max_time' => $maxExecutionTime,
  682. 'percentage_used' => ($elapsed / $maxExecutionTime) * 100
  683. ]);
  684. }
  685. $lastCheck = $currentTime;
  686. }
  687. });
  688. declare(ticks=1000);
  689. $result = $callback();
  690. $totalTime = microtime(true) - $startTime;
  691. Log::info("Operation completed successfully: {$description}", [
  692. 'total_time' => $totalTime,
  693. 'memory_peak' => memory_get_peak_usage(true)
  694. ]);
  695. return $result;
  696. } catch (\Exception $e) {
  697. $totalTime = microtime(true) - $startTime;
  698. Log::error("Operation failed: {$description}", [
  699. 'error' => $e->getMessage(),
  700. 'total_time' => $totalTime,
  701. 'memory_peak' => memory_get_peak_usage(true),
  702. 'trace' => $e->getTraceAsString()
  703. ]);
  704. throw $e;
  705. }
  706. }
  707. private function checkTimeoutRisk($operationName, $startTime = null)
  708. {
  709. if ($startTime === null) {
  710. $startTime = $_SERVER['REQUEST_TIME_FLOAT'] ?? microtime(true);
  711. }
  712. $maxExecutionTime = ini_get('max_execution_time');
  713. if ($maxExecutionTime <= 0) {
  714. return false;
  715. }
  716. $elapsed = microtime(true) - $startTime;
  717. $remaining = $maxExecutionTime - $elapsed;
  718. $percentageUsed = ($elapsed / $maxExecutionTime) * 100;
  719. Log::info("Timeout check: {$operationName}", [
  720. 'elapsed_time' => $elapsed,
  721. 'remaining_time' => $remaining,
  722. 'percentage_used' => $percentageUsed,
  723. 'memory_usage' => memory_get_usage(true)
  724. ]);
  725. if ($percentageUsed > 80) {
  726. Log::warning("High timeout risk detected: {$operationName}", [
  727. 'elapsed_time' => $elapsed,
  728. 'remaining_time' => $remaining,
  729. 'percentage_used' => $percentageUsed
  730. ]);
  731. return true;
  732. }
  733. return false;
  734. }
  735. public function logEnvironmentInfo()
  736. {
  737. Log::info('=== EXPORT ENVIRONMENT INFO ===', [
  738. 'php_version' => PHP_VERSION,
  739. 'memory_limit' => ini_get('memory_limit'),
  740. 'max_execution_time' => ini_get('max_execution_time'),
  741. 'max_input_time' => ini_get('max_input_time'),
  742. 'post_max_size' => ini_get('post_max_size'),
  743. 'upload_max_filesize' => ini_get('upload_max_filesize'),
  744. 'default_socket_timeout' => ini_get('default_socket_timeout'),
  745. 'current_memory_usage' => memory_get_usage(true),
  746. 'current_memory_peak' => memory_get_peak_usage(true),
  747. 'server_time' => date('Y-m-d H:i:s'),
  748. 'timezone' => date_default_timezone_get(),
  749. 'sapi_name' => php_sapi_name(),
  750. 'loaded_extensions' => get_loaded_extensions()
  751. ]);
  752. }
  753. }