ExportPrimaNota.php 39 KB

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