ExportPrimaNota.php 38 KB

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