ExportPrimaNota.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  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 = 600;
  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. $letters = array('F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'AA');
  142. $spreadsheet = new Spreadsheet();
  143. $activeWorksheet = $spreadsheet->getActiveSheet();
  144. $activeWorksheet->setTitle('Prima Nota');
  145. $spreadsheet->getProperties()
  146. ->setCreator('Prima Nota System')
  147. ->setLastModifiedBy('Sistema')
  148. ->setTitle('Prima Nota Export')
  149. ->setSubject('Export Prima Nota')
  150. ->setDescription('Export dei dati Prima Nota dal ' . $this->dateRange['from'] . ' al ' . $this->dateRange['to']);
  151. $activeWorksheet->setCellValue('A1', "Data");
  152. $activeWorksheet->setCellValue('B1', "Causale");
  153. $activeWorksheet->setCellValue('C1', "Dettaglio Causale");
  154. $activeWorksheet->setCellValue('D1', "Nominativo");
  155. $activeWorksheet->setCellValue('E1', "Stato");
  156. $idx = 0;
  157. foreach ($this->payments as $p) {
  158. if ($idx >= count($letters)) break;
  159. $activeWorksheet->setCellValue($letters[$idx] . '1', $p['name']);
  160. $activeWorksheet->mergeCells($letters[$idx] . '1:' . $letters[$idx + 1] . '1');
  161. $idx += 2;
  162. }
  163. $activeWorksheet->setCellValue('A2', "");
  164. $activeWorksheet->setCellValue('B2', "");
  165. $activeWorksheet->setCellValue('C2', "");
  166. $activeWorksheet->setCellValue('D2', "");
  167. $activeWorksheet->setCellValue('E2', "");
  168. $idx = 0;
  169. foreach ($this->payments as $p) {
  170. if ($idx >= count($letters) - 1) break;
  171. if ($p['type'] == 'ALL') {
  172. $activeWorksheet->setCellValue($letters[$idx] . '2', "Entrate");
  173. $idx++;
  174. $activeWorksheet->setCellValue($letters[$idx] . '2', "Uscite");
  175. $idx++;
  176. } elseif ($p['type'] == 'IN') {
  177. $activeWorksheet->setCellValue($letters[$idx] . '2', "Entrate");
  178. $idx++;
  179. $activeWorksheet->setCellValue($letters[$idx] . '2', "");
  180. $idx++;
  181. } elseif ($p['type'] == 'OUT') {
  182. $activeWorksheet->setCellValue($letters[$idx] . '2', "");
  183. $idx++;
  184. $activeWorksheet->setCellValue($letters[$idx] . '2', "Uscite");
  185. $idx++;
  186. }
  187. }
  188. $activeWorksheet->getStyle('A1:' . $letters[min(count($letters) - 1, count($this->payments) * 2 + 4)] . '2')
  189. ->getFont()->setBold(true);
  190. $activeWorksheet->getStyle('A1:' . $letters[min(count($letters) - 1, count($this->payments) * 2 + 4)] . '1')
  191. ->getFill()
  192. ->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)
  193. ->getStartColor()->setARGB('FF0C6197');
  194. $activeWorksheet->getStyle('A1:' . $letters[min(count($letters) - 1, count($this->payments) * 2 + 4)] . '1')
  195. ->getFont()->getColor()->setARGB('FFFFFFFF');
  196. $count = 3;
  197. $batchSize = 500;
  198. $processed = 0;
  199. foreach ($this->exportData as $causal => $record) {
  200. $parts = explode("§", $causal);
  201. $d = $parts[0] ?? '';
  202. $c = $parts[1] ?? '';
  203. $j = $parts[2] ?? '';
  204. $det = $parts[3] ?? '';
  205. $deleted = $parts[4] ?? '';
  206. $detailParts = explode('|', $det);
  207. $exportDetail = count($detailParts) > 1 ? implode(', ', array_slice($detailParts, 1)) : $det;
  208. $activeWorksheet->setCellValue('A' . $count, !empty($d) ? date("d/m/Y", strtotime($d)) : '');
  209. $activeWorksheet->setCellValue('B' . $count, $c);
  210. $activeWorksheet->setCellValue('C' . $count, $exportDetail);
  211. $activeWorksheet->setCellValue('D' . $count, $j);
  212. $stato = ($deleted === 'DELETED') ? 'ANNULLATA' : '';
  213. $activeWorksheet->setCellValue('E' . $count, $stato);
  214. if ($stato === 'ANNULLATA') {
  215. $activeWorksheet->getStyle('E' . $count)->getFont()->getColor()->setARGB('FFFF0000');
  216. }
  217. $idx = 0;
  218. foreach ($this->payments as $p) {
  219. if ($idx >= count($letters) - 1) break;
  220. if (isset($record[$p['name']])) {
  221. $inValue = isset($record[$p['name']]["IN"]) ? $this->formatPrice($record[$p['name']]["IN"]) : "";
  222. $outValue = isset($record[$p['name']]["OUT"]) ? $this->formatPrice($record[$p['name']]["OUT"]) : "";
  223. $activeWorksheet->setCellValue($letters[$idx] . $count, $inValue);
  224. $idx++;
  225. $activeWorksheet->setCellValue($letters[$idx] . $count, $outValue);
  226. $idx++;
  227. } else {
  228. $activeWorksheet->setCellValue($letters[$idx] . $count, "");
  229. $idx++;
  230. $activeWorksheet->setCellValue($letters[$idx] . $count, "");
  231. $idx++;
  232. }
  233. }
  234. $count++;
  235. $processed++;
  236. if ($processed % $batchSize === 0) {
  237. gc_collect_cycles();
  238. }
  239. }
  240. $count++;
  241. $activeWorksheet->setCellValue('A' . $count, 'TOTALE');
  242. $activeWorksheet->setCellValue('B' . $count, '');
  243. $activeWorksheet->setCellValue('C' . $count, '');
  244. $activeWorksheet->setCellValue('D' . $count, '');
  245. $activeWorksheet->setCellValue('E' . $count, '');
  246. $idx = 0;
  247. foreach ($this->payments as $p) {
  248. if ($idx >= count($letters) - 1) break;
  249. if (isset($this->exportTotals[$p['name']])) {
  250. if ($p['type'] == 'ALL') {
  251. $activeWorksheet->setCellValue($letters[$idx] . $count, $this->formatPrice($this->exportTotals[$p['name']]["IN"] ?? 0));
  252. $idx++;
  253. $activeWorksheet->setCellValue($letters[$idx] . $count, $this->formatPrice($this->exportTotals[$p['name']]["OUT"] ?? 0));
  254. $idx++;
  255. } elseif ($p['type'] == 'IN') {
  256. $activeWorksheet->setCellValue($letters[$idx] . $count, $this->formatPrice($this->exportTotals[$p['name']]["IN"] ?? 0));
  257. $idx++;
  258. $activeWorksheet->setCellValue($letters[$idx] . $count, "");
  259. $idx++;
  260. } elseif ($p['type'] == 'OUT') {
  261. $activeWorksheet->setCellValue($letters[$idx] . $count, "");
  262. $idx++;
  263. $activeWorksheet->setCellValue($letters[$idx] . $count, $this->formatPrice($this->exportTotals[$p['name']]["OUT"] ?? 0));
  264. $idx++;
  265. }
  266. } else {
  267. $activeWorksheet->setCellValue($letters[$idx] . $count, "0,00");
  268. $idx++;
  269. $activeWorksheet->setCellValue($letters[$idx] . $count, "0,00");
  270. $idx++;
  271. }
  272. }
  273. $activeWorksheet->getStyle('A' . $count . ':' . $letters[min(count($letters) - 1, count($this->payments) * 2 + 4)] . $count)
  274. ->getFont()->setBold(true);
  275. $activeWorksheet->getStyle('A' . $count . ':' . $letters[min(count($letters) - 1, count($this->payments) * 2 + 4)] . $count)
  276. ->getFill()
  277. ->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)
  278. ->getStartColor()->setARGB('FFF0F0F0');
  279. $activeWorksheet->getColumnDimension('A')->setWidth(15);
  280. $activeWorksheet->getColumnDimension('B')->setWidth(25);
  281. $activeWorksheet->getColumnDimension('C')->setWidth(30);
  282. $activeWorksheet->getColumnDimension('D')->setWidth(25);
  283. $activeWorksheet->getColumnDimension('E')->setWidth(15);
  284. foreach ($letters as $l) {
  285. $activeWorksheet->getColumnDimension($l)->setWidth(15);
  286. }
  287. $activeWorksheet->freezePane('A3');
  288. $writer = new Xlsx($spreadsheet);
  289. $writer->save($filePath);
  290. unset($spreadsheet, $activeWorksheet, $writer);
  291. gc_collect_cycles();
  292. }
  293. /**
  294. * Format price for display
  295. */
  296. private function formatPrice($amount)
  297. {
  298. return number_format($amount, 2, ',', '.');
  299. }
  300. /**
  301. * Get description of applied filters
  302. */
  303. private function getFiltersDescription()
  304. {
  305. $descriptions = [];
  306. if (!empty($this->filters['member'])) {
  307. $descriptions[] = "Utente: {$this->filters['member']}";
  308. }
  309. if (!empty($this->filters['causals'])) {
  310. $descriptions[] = "Causali: " . (is_array($this->filters['causals']) ? implode(', ', $this->filters['causals']) : $this->filters['causals']);
  311. }
  312. return empty($descriptions) ? 'Nessun filtro applicato' : implode(' | ', $descriptions);
  313. }
  314. }