Record.php 69 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813
  1. <?php
  2. namespace App\Http\Livewire;
  3. use Livewire\Component;
  4. use DateInterval;
  5. use DatePeriod;
  6. use DateTime;
  7. use PhpOffice\PhpSpreadsheet\Spreadsheet;
  8. use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
  9. use Illuminate\Support\Facades\Storage;
  10. use Illuminate\Support\Facades\Log;
  11. use Illuminate\Support\Facades\Mail;
  12. use App\Mail\ExportNotification;
  13. use App\Jobs\ExportPrimaNota;
  14. class Record extends Component
  15. {
  16. public $records, $dataId, $totals;
  17. public $in;
  18. public $out;
  19. public $payments = [];
  20. public $fromDate;
  21. public $toDate;
  22. public $appliedFromDate;
  23. public $appliedToDate;
  24. public $exportFromDate;
  25. public $exportToDate;
  26. public $isExporting = false;
  27. public $selectedPeriod = 'OGGI';
  28. public $filterCausals = null;
  29. public $filterMember = null;
  30. public $isFiltering = false;
  31. public array $recordDatas = [];
  32. public array $labels = [];
  33. public array $causals = [];
  34. public $members = array();
  35. public $sendViaEmail = false;
  36. public $exportEmailAddress = '';
  37. public $exportEmailSubject = 'Prima Nota - Export';
  38. private $causalAmounts = [];
  39. public $selectedMonth;
  40. public $showMonthPicker = false;
  41. public $selectedDay;
  42. public $showDayPicker = false;
  43. public $selectedYear;
  44. protected $rules = [
  45. 'exportEmailAddress' => 'required_if:sendViaEmail,true|email',
  46. 'exportEmailSubject' => 'required_if:sendViaEmail,true|string|max:255',
  47. ];
  48. public $total_in = 0;
  49. public $total_out = 0;
  50. protected $messages = [
  51. 'exportEmailAddress.required_if' => 'L\'indirizzo email è obbligatorio quando si sceglie di inviare via email.',
  52. 'exportEmailAddress.email' => 'Inserisci un indirizzo email valido.',
  53. 'exportEmailSubject.required_if' => 'L\'oggetto dell\'email è obbligatorio.',
  54. 'exportEmailSubject.max' => 'L\'oggetto dell\'email non può superare i 255 caratteri.',
  55. ];
  56. public function hydrate()
  57. {
  58. $this->emit('load-select');
  59. }
  60. public function mount()
  61. {
  62. $this->fromDate = date("Y-m-d");
  63. $this->toDate = date("Y-m-d");
  64. $this->appliedFromDate = date("Y-m-d");
  65. $this->appliedToDate = date("Y-m-d");
  66. $this->exportFromDate = date("Y-m-d");
  67. $this->exportToDate = date("Y-m-d");
  68. $this->exportEmailSubject = 'Prima Nota - Export del ' . date('d/m/Y');
  69. $this->getCausals(\App\Models\Causal::select('id', 'name')->where('parent_id', null)->get(), 0);
  70. $this->members = \App\Models\Member::select(['id', 'first_name', 'last_name', 'fiscal_code'])
  71. ->where(function($query) {
  72. $query->where('is_archived', false)
  73. ->orWhereNull('is_archived');
  74. })
  75. ->where(function($query) {
  76. $query->where('is_deleted', false)
  77. ->orWhereNull('is_deleted');
  78. })->orderBy('last_name')->orderBy('first_name')->get();
  79. $this->payments = \App\Models\PaymentMethod::select('id', 'name', 'type')->where('enabled', true)->where('money', false)->get();
  80. $this->selectedMonth = date('Y-m');
  81. $this->selectedDay = date('Y-m-d');
  82. $this->selectedYear = date('Y');
  83. }
  84. private function generateExportDataAndTotals($fromDate, $toDate)
  85. {
  86. Log::info('generateExportDataAndTotals: Start (combined method)', [
  87. 'from_date' => $fromDate,
  88. 'to_date' => $toDate,
  89. 'memory_before' => memory_get_usage(true)
  90. ]);
  91. $exportRecords = array();
  92. $exportTotals = array();
  93. Log::info('generateExportDataAndTotals: Getting excluded members');
  94. $exclude_from_records = \App\Models\Member::where('exclude_from_records', true)->pluck('id')->toArray();
  95. Log::info('generateExportDataAndTotals: Excluded members retrieved', ['count' => count($exclude_from_records)]);
  96. Log::info('generateExportDataAndTotals: Building main query');
  97. $datas = \App\Models\Record::with('member', 'supplier', 'payment_method')
  98. ->select(
  99. 'records.*',
  100. 'records_rows.id as row_id',
  101. 'records_rows.record_id',
  102. 'records_rows.causal_id',
  103. 'records_rows.amount',
  104. 'records_rows.note',
  105. 'records_rows.when',
  106. 'records_rows.vat_id',
  107. 'records_rows.created_at as row_created_at',
  108. 'records_rows.updated_at as row_updated_at'
  109. )
  110. ->join('records_rows', 'records.id', '=', 'records_rows.record_id')
  111. //->where('records.deleted', false)
  112. ->where(function ($query) {
  113. $query->where('records.deleted', false)->orWhereNull('records.deleted');
  114. })
  115. ->whereBetween('date', [$fromDate, $toDate])
  116. ->where(function ($query) {
  117. $query->where('type', 'OUT')
  118. ->orWhere(function ($query) {
  119. $query->where('records.corrispettivo_fiscale', true)
  120. ->orWhere('records.commercial', false);
  121. });
  122. })
  123. ->where(function ($query) use ($exclude_from_records) {
  124. $query->where('type', 'OUT')
  125. ->orWhere(function ($subquery) use ($exclude_from_records) {
  126. $subquery->whereNotIn('member_id', $exclude_from_records);
  127. });
  128. });
  129. Log::info('generateExportDataAndTotals: Applying causal filters');
  130. if ($this->filterCausals != null && sizeof($this->filterCausals) > 0) {
  131. $causals = array();
  132. foreach ($this->filterCausals as $z) {
  133. $causals[] = $z;
  134. $childs = \App\Models\Causal::where('parent_id', $z)->get();
  135. foreach ($childs as $c) {
  136. $causals[] = $c->id;
  137. $childsX = \App\Models\Causal::where('parent_id', $c->id)->get();
  138. foreach ($childsX as $cX) {
  139. $causals[] = $cX->id;
  140. }
  141. }
  142. }
  143. $datas->whereIn('causal_id', $causals);
  144. Log::info('generateExportDataAndTotals: Causal filters applied', ['causal_count' => count($causals)]);
  145. }
  146. if ($this->filterMember != null && $this->filterMember > 0) {
  147. $datas->where('member_id', $this->filterMember);
  148. Log::info('generateExportDataAndTotals: Member filter applied', ['member_id' => $this->filterMember]);
  149. }
  150. Log::info('generateExportDataAndTotals: Executing query');
  151. $queryStart = microtime(true);
  152. $datas = $datas->orderBy('date', 'ASC')
  153. ->orderBy('records.created_at', 'ASC')
  154. ->orderBy('records_rows.id', 'ASC')
  155. ->get();
  156. $queryTime = microtime(true) - $queryStart;
  157. Log::info('generateExportDataAndTotals: Query executed', [
  158. 'record_count' => $datas->count(),
  159. 'query_time' => $queryTime,
  160. 'memory_after_query' => memory_get_usage(true)
  161. ]);
  162. $groupedData = [];
  163. $causalsCount = [];
  164. $processedCount = 0;
  165. // Initialize totals array
  166. foreach ($this->payments as $p) {
  167. $exportTotals[$p->name] = ["IN" => 0, "OUT" => 0];
  168. }
  169. Log::info('generateExportDataAndTotals: Starting combined data processing loop');
  170. $loopStart = microtime(true);
  171. foreach ($datas as $idx => $data) {
  172. if ($processedCount % 100 == 0) {
  173. Log::info('generateExportDataAndTotals: Processing progress', [
  174. 'processed' => $processedCount,
  175. 'total' => $datas->count(),
  176. 'memory_current' => memory_get_usage(true),
  177. 'memory_peak' => memory_get_peak_usage(true)
  178. ]);
  179. }
  180. try {
  181. $causalCheck = \App\Models\Causal::findOrFail($data->causal_id);
  182. $paymentCheck = $data->payment_method->money;
  183. if (!$paymentCheck && ($causalCheck->no_first == null || !$causalCheck->no_first)) {
  184. if (!$data->deleted) {
  185. $amount = $data->amount;
  186. $amount += getVatValue($amount, $data->vat_id);
  187. } else {
  188. $amount = $data->amount;
  189. }
  190. // CALCULATE TOTALS HERE (in the same loop)
  191. /*if (!$data->deleted) {
  192. $exportTotals[$data->payment_method->name][$data->type] += $amount;
  193. }*/
  194. $isCommercial = ($data->commercial == 1 || $data->commercial === '1' || $data->commercial === true);
  195. $typeLabel = $isCommercial ? 'Commerciale' : 'Non Commerciale';
  196. $nominativo = '';
  197. if ($data->type == "IN") {
  198. if ($data->member) {
  199. $nominativo = $data->member->last_name . " " . $data->member->first_name;
  200. }
  201. } else {
  202. if ($data->supplier) {
  203. $nominativo = $data->supplier->name;
  204. }
  205. }
  206. $groupKey = $data->date . '|' . $typeLabel . '|' . $data->payment_method->name . '|' . $data->type . '|' . $nominativo;
  207. if (!isset($groupedData[$groupKey])) {
  208. $groupedData[$groupKey] = [
  209. 'date' => $data->date,
  210. 'type_label' => $typeLabel,
  211. 'payment_method' => $data->payment_method->name,
  212. 'transaction_type' => $data->type,
  213. 'nominativo' => $nominativo,
  214. 'amount' => 0,
  215. 'deleted' => false,
  216. 'causals' => [],
  217. 'notes' => []
  218. ];
  219. $causalsCount[$groupKey] = [];
  220. }
  221. $groupedData[$groupKey]['amount'] += $amount;
  222. $causalsCount[$groupKey][$causalCheck->getTree()] = true;
  223. if (!empty($data->note)) {
  224. $groupedData[$groupKey]['notes'][] = $data->note;
  225. }
  226. if ($data->deleted) {
  227. $groupedData[$groupKey]['deleted'] = true;
  228. }
  229. }
  230. $processedCount++;
  231. } catch (\Exception $e) {
  232. Log::error('generateExportDataAndTotals: Error processing individual record', [
  233. 'record_id' => $data->id ?? 'unknown',
  234. 'error' => $e->getMessage(),
  235. 'processed_so_far' => $processedCount
  236. ]);
  237. throw $e;
  238. }
  239. }
  240. $loopTime = microtime(true) - $loopStart;
  241. Log::info('generateExportDataAndTotals: Combined processing loop completed', [
  242. 'total_processed' => $processedCount,
  243. 'grouped_records' => count($groupedData),
  244. 'loop_time' => $loopTime,
  245. 'memory_after_loop' => memory_get_usage(true)
  246. ]);
  247. Log::info('generateExportDataAndTotals: Building final export records');
  248. $finalStart = microtime(true);
  249. $tot = 0;
  250. $count = 0;
  251. foreach ($groupedData as $groupKey => $group) {
  252. $causalsInGroup = array_keys($causalsCount[$groupKey]);
  253. $causalDisplay = $group['type_label'];
  254. if (count($causalsInGroup) > 1) {
  255. $detailDisplay = 'Varie|' . implode('|', $causalsInGroup);
  256. } else {
  257. $detailDisplay = $causalsInGroup[0];
  258. }
  259. $recordKey = $group['date'] . "§" . $causalDisplay . "§" . $group['nominativo'] . "§" . $detailDisplay . "§" . ($group['deleted'] ? 'DELETED' : '') . "§";
  260. if (!isset($exportRecords[$recordKey][$group['payment_method']][$group['transaction_type']])) {
  261. $exportRecords[$recordKey][$group['payment_method']][$group['transaction_type']] = 0;
  262. }
  263. $exportRecords[$recordKey][$group['payment_method']][$group['transaction_type']] += $group['amount'];
  264. if (!$group['deleted'])
  265. $exportTotals[$group['payment_method']][$group['transaction_type']] += $group['amount'];
  266. }
  267. $finalTime = microtime(true) - $finalStart;
  268. Log::info('generateExportDataAndTotals: Final processing completed', [
  269. 'final_export_records' => count($exportRecords),
  270. 'final_export_totals' => count($exportTotals),
  271. 'final_time' => $finalTime,
  272. 'total_time' => microtime(true) - $loopStart + $queryTime,
  273. 'memory_final' => memory_get_usage(true),
  274. 'memory_peak' => memory_get_peak_usage(true)
  275. ]);
  276. // Cleanup
  277. unset($datas, $groupedData, $causalsCount);
  278. gc_collect_cycles();
  279. Log::info('generateExportDataAndTotals: Completed with cleanup', [
  280. 'memory_after_cleanup' => memory_get_usage(true)
  281. ]);
  282. return ['records' => $exportRecords, 'totals' => $exportTotals];
  283. }
  284. private function generateExportTotals($fromDate, $toDate)
  285. {
  286. $exportTotals = array();
  287. $exclude_from_records = \App\Models\Member::where('exclude_from_records', true)->pluck('id')->toArray();
  288. $datas = \App\Models\Record::with('member', 'supplier', 'payment_method')
  289. ->select(
  290. 'records.*',
  291. 'records_rows.id as row_id',
  292. 'records_rows.record_id',
  293. 'records_rows.causal_id',
  294. 'records_rows.amount',
  295. 'records_rows.note',
  296. 'records_rows.when',
  297. 'records_rows.vat_id',
  298. )
  299. ->join('records_rows', 'records.id', '=', 'records_rows.record_id')
  300. //->where('records.deleted', false)
  301. ->where(function ($query) {
  302. $query->where('records.deleted', false)->orWhereNull('records.deleted');
  303. })
  304. ->whereBetween('date', [$fromDate, $toDate])
  305. ->where(function ($query) {
  306. $query->where('type', 'OUT')
  307. ->orWhere(function ($query) {
  308. $query->where('records.corrispettivo_fiscale', true)
  309. ->orWhere('records.commercial', false);
  310. });
  311. })
  312. ->where(function ($query) use ($exclude_from_records) {
  313. $query->where('type', 'OUT')
  314. ->orWhere(function ($subquery) use ($exclude_from_records) {
  315. $subquery->whereNotIn('member_id', $exclude_from_records);
  316. });
  317. });
  318. if ($this->filterCausals != null && sizeof($this->filterCausals) > 0) {
  319. $causals = array();
  320. foreach ($this->filterCausals as $z) {
  321. $causals[] = $z;
  322. $childs = \App\Models\Causal::where('parent_id', $z)->get();
  323. foreach ($childs as $c) {
  324. $causals[] = $c->id;
  325. $childsX = \App\Models\Causal::where('parent_id', $c->id)->get();
  326. foreach ($childsX as $cX) {
  327. $causals[] = $cX->id;
  328. }
  329. }
  330. }
  331. $datas->whereIn('causal_id', $causals);
  332. }
  333. if ($this->filterMember != null && $this->filterMember > 0) {
  334. $datas->where('member_id', $this->filterMember);
  335. }
  336. $datas = $datas->orderBy('date', 'ASC')
  337. ->orderBy('records.created_at', 'ASC')
  338. ->orderBy('records_rows.id', 'ASC')
  339. ->get();
  340. foreach ($datas as $data) {
  341. $causalCheck = \App\Models\Causal::findOrFail($data->causal_id);
  342. $paymentCheck = $data->payment_method->money;
  343. if (!$paymentCheck && ($causalCheck->no_first == null || !$causalCheck->no_first)) {
  344. if (!$data->deleted) {
  345. $amount = $data->amount;
  346. $amount += getVatValue($amount, $data->vat_id);
  347. } else {
  348. $amount = $data->amount;
  349. }
  350. if (!isset($exportTotals[$data->payment_method->name])) {
  351. $exportTotals[$data->payment_method->name]["IN"] = 0;
  352. $exportTotals[$data->payment_method->name]["OUT"] = 0;
  353. }
  354. if (!$data->deleted)
  355. $exportTotals[$data->payment_method->name][$data->type] += $amount;
  356. }
  357. }
  358. return $exportTotals;
  359. }
  360. public function resetFilters()
  361. {
  362. $this->selectedPeriod = 'OGGI';
  363. $this->selectedMonth = date('Y-m');
  364. $this->selectedDay = date('Y-m-d');
  365. $this->selectedYear = date('Y');
  366. $this->showMonthPicker = false;
  367. $this->showDayPicker = false;
  368. $this->filterCausals = [];
  369. $this->filterMember = null;
  370. $today = date("Y-m-d");
  371. $this->fromDate = $today;
  372. $this->toDate = $today;
  373. $this->appliedFromDate = $today;
  374. $this->appliedToDate = $today;
  375. $this->emit('filters-reset');
  376. }
  377. public function applyFilters()
  378. {
  379. $this->isFiltering = true;
  380. $this->setPeriodDates();
  381. $this->appliedFromDate = $this->fromDate;
  382. $this->appliedToDate = $this->toDate;
  383. $this->render();
  384. $this->isFiltering = false;
  385. $this->emit('filters-applied');
  386. }
  387. private function setPeriodDates()
  388. {
  389. $today = now();
  390. switch ($this->selectedPeriod) {
  391. case 'OGGI':
  392. $this->fromDate = $today->format('Y-m-d');
  393. $this->toDate = $today->format('Y-m-d');
  394. break;
  395. case 'IERI':
  396. $yesterday = $today->copy()->subDay();
  397. $this->fromDate = $yesterday->format('Y-m-d');
  398. $this->toDate = $yesterday->format('Y-m-d');
  399. break;
  400. case 'MESE CORRENTE':
  401. $this->fromDate = $today->copy()->startOfMonth()->format('Y-m-d');
  402. $this->toDate = $today->copy()->endOfMonth()->format('Y-m-d');
  403. break;
  404. case 'MESE PRECEDENTE':
  405. $lastMonth = $today->copy()->subMonth();
  406. $this->fromDate = $lastMonth->startOfMonth()->format('Y-m-d');
  407. $this->toDate = $lastMonth->endOfMonth()->format('Y-m-d');
  408. break;
  409. case 'MESE_PERSONALIZZATO':
  410. if (!empty($this->selectedMonth)) {
  411. $firstDay = date('Y-m-01', strtotime($this->selectedMonth . '-01'));
  412. $lastDay = date('Y-m-t', strtotime($this->selectedMonth . '-01'));
  413. $this->fromDate = $firstDay;
  414. $this->toDate = $lastDay;
  415. }
  416. break;
  417. case 'GIORNO_PERSONALIZZATO':
  418. if (!empty($this->selectedDay)) {
  419. $this->fromDate = $this->selectedDay;
  420. $this->toDate = $this->selectedDay;
  421. }
  422. break;
  423. case 'ULTIMO TRIMESTRE':
  424. $this->fromDate = $today->copy()->subMonths(3)->format('Y-m-d');
  425. $this->toDate = $today->format('Y-m-d');
  426. break;
  427. case 'ULTIMO QUADRIMESTRE':
  428. $this->fromDate = $today->copy()->subMonths(4)->format('Y-m-d');
  429. $this->toDate = $today->format('Y-m-d');
  430. break;
  431. }
  432. }
  433. public function getCausals($records, $indentation)
  434. {
  435. foreach ($records as $record) {
  436. $this->causals[] = array('id' => $record->id, 'name' => $record->getTree(), 'text' => $record->getTree(), 'level' => $indentation);
  437. if (count($record->childs))
  438. $this->getCausals($record->childs, $indentation + 1);
  439. }
  440. }
  441. public function getMonth($m)
  442. {
  443. $ret = '';
  444. switch ($m) {
  445. case 1:
  446. $ret = 'Gennaio';
  447. break;
  448. case 2:
  449. $ret = 'Febbraio';
  450. break;
  451. case 3:
  452. $ret = 'Marzo';
  453. break;
  454. case 4:
  455. $ret = 'Aprile';
  456. break;
  457. case 5:
  458. $ret = 'Maggio';
  459. break;
  460. case 6:
  461. $ret = 'Giugno';
  462. break;
  463. case 7:
  464. $ret = 'Luglio';
  465. break;
  466. case 8:
  467. $ret = 'Agosto';
  468. break;
  469. case 9:
  470. $ret = 'Settembre';
  471. break;
  472. case 10:
  473. $ret = 'Ottobre';
  474. break;
  475. case 11:
  476. $ret = 'Novembre';
  477. break;
  478. case 12:
  479. $ret = 'Dicembre';
  480. break;
  481. default:
  482. $ret = '';
  483. break;
  484. }
  485. return $ret;
  486. }
  487. public function loadData($from, $to)
  488. {
  489. $exclude_from_records = \App\Models\Member::where('exclude_from_records', true)->pluck('id')->toArray();
  490. $f = $from != '' ? $from : $this->appliedFromDate;
  491. $t = $to != '' ? $to : $this->appliedToDate;
  492. $datas = \App\Models\Record::with('member', 'supplier', 'payment_method')
  493. ->select(
  494. 'records.*',
  495. 'records_rows.id as row_id',
  496. 'records_rows.record_id',
  497. 'records_rows.causal_id',
  498. 'records_rows.amount',
  499. 'records_rows.note',
  500. 'records_rows.when',
  501. 'records_rows.vat_id',
  502. //'causals.name as causal_name',
  503. 'd.name as destination',
  504. 'o.name as origin',
  505. )
  506. ->join('records_rows', 'records.id', '=', 'records_rows.record_id')
  507. ->join('causals', 'records_rows.causal_id', '=', 'causals.id')
  508. ->leftJoin('banks as d', 'records.destination_id', '=', 'd.id')
  509. ->leftJoin('banks as o', 'records.origin_id', '=', 'o.id')
  510. //->where('records.deleted', false)
  511. /*->where(function ($query) {
  512. $query->where('records.deleted', false)->orWhereNull('records.deleted');
  513. })*/
  514. ->whereBetween('date', [$f . " 00:00:00", $t . " 23:59:59"])
  515. ->where(function ($query) {
  516. $query->where('records.type', 'OUT')
  517. ->orWhere(function ($query) {
  518. $query->where('records.corrispettivo_fiscale', true)
  519. ->orWhere('records.commercial', false);
  520. });
  521. })
  522. ->where(function ($query) use ($exclude_from_records) {
  523. $query->where('records.type', 'OUT')
  524. ->orWhere(function ($subquery) use ($exclude_from_records) {
  525. $subquery->whereNotIn('member_id', $exclude_from_records);
  526. });
  527. });
  528. if ($this->filterCausals != null && sizeof($this->filterCausals) > 0) {
  529. $causals = array();
  530. foreach ($this->filterCausals as $z) {
  531. $causals[] = $z;
  532. $childs = \App\Models\Causal::where('parent_id', $z)->get();
  533. foreach ($childs as $c) {
  534. $causals[] = $c->id;
  535. $childsX = \App\Models\Causal::where('parent_id', $c->id)->get();
  536. foreach ($childsX as $cX) {
  537. $causals[] = $cX->id;
  538. }
  539. }
  540. }
  541. $datas->whereIn('causal_id', $causals);
  542. }
  543. if ($this->filterMember != null && $this->filterMember > 0) {
  544. $datas->where('member_id', $this->filterMember);
  545. }
  546. $datas = $datas->orderBy('date', 'ASC')
  547. ->orderBy('records.created_at', 'ASC')
  548. ->orderBy('records_rows.id', 'ASC')
  549. ->get();
  550. $ret = array();
  551. $this->total_in = 0;
  552. $this->total_out = 0;
  553. foreach($datas as $data)
  554. {
  555. $causal = \App\Models\Causal::findOrFail($data->causal_id);
  556. $paymentCheck = $data->payment_method->money;
  557. if (!$paymentCheck && ($causal->no_first == null || !$causal->no_first))
  558. {
  559. $data->causal_name = $causal->getTree();
  560. $ret[] = $data;
  561. if ($data->type == 'IN')
  562. $this->total_in += $data->amount;
  563. if ($data->type == 'OUT')
  564. $this->total_out += $data->amount;
  565. }
  566. }
  567. if ($this->total_in > 0 || $this->total_out > 0)
  568. {
  569. $ret[] = (object) array("date" => "", "total_in" => $this->total_in, "total_out" => $this->total_out);
  570. }
  571. return $ret;
  572. }
  573. public function render()
  574. {
  575. $month = 0;
  576. $year = 0;
  577. $this->records = array();
  578. $this->totals = array();
  579. $this->causalAmounts = array();
  580. $this->records = $this->loadData('', '');
  581. /*
  582. foreach ($datas as $idx => $data) {
  583. $causalCheck = \App\Models\Causal::findOrFail($data->causal_id);
  584. $paymentCheck = $data->payment_method->money;
  585. if (!$paymentCheck && ($causalCheck->no_first == null || !$causalCheck->no_first)) {
  586. if (!$data->deleted) {
  587. $amount = $data->amount;
  588. if ($data->vat_id > 0)
  589. $amount += getVatValue($amount, $data->vat_id);
  590. } else {
  591. $amount = $data->amount;
  592. }
  593. $isCommercial = ($data->commercial == 1 || $data->commercial === '1' || $data->commercial === true);
  594. $typeLabel = $isCommercial ? 'Commerciale' : 'Non Commerciale';
  595. $nominativo = '';
  596. if ($data->type == "IN") {
  597. if ($data->member) {
  598. $nominativo = $data->member->last_name . " " . $data->member->first_name;
  599. }
  600. if ($data->payment_method_id == 7)
  601. $values[] = array('id' => $data->record_id, 'amount' => $amount);
  602. } else {
  603. if ($data->supplier) {
  604. $nominativo = $data->supplier->name;
  605. }
  606. }
  607. $groupKey = $data->date . '|' . $typeLabel . '|' . $data->payment_method->name . '|' . $data->type . '|' . $nominativo;
  608. if (!isset($groupedData[$groupKey])) {
  609. $groupedData[$groupKey] = [
  610. 'date' => $data->date,
  611. 'type_label' => $typeLabel,
  612. 'payment_method' => $data->payment_method->name,
  613. 'transaction_type' => $data->type,
  614. 'nominativo' => $nominativo,
  615. 'amount' => 0,
  616. 'deleted' => false,
  617. 'causals' => [],
  618. 'notes' => []
  619. ];
  620. $causalsCount[$groupKey] = [];
  621. $causalsAmounts[$groupKey] = []; // Initialize causal amounts for this group
  622. $nominativi[$groupKey] = $nominativo;
  623. }
  624. $groupedData[$groupKey]['amount'] += $amount;
  625. $causalsCount[$groupKey][$causalCheck->getTree()] = true;
  626. $causalName = $causalCheck->getTree();
  627. if (!isset($causalsAmounts[$groupKey][$causalName])) {
  628. $causalsAmounts[$groupKey][$causalName] = 0;
  629. }
  630. $causalsAmounts[$groupKey][$causalName] += $amount;
  631. if (!empty($data->note)) {
  632. $groupedData[$groupKey]['notes'][] = $data->note;
  633. }
  634. if ($data->deleted) {
  635. $groupedData[$groupKey]['deleted'] = true;
  636. }
  637. }
  638. }
  639. Log::info('values', [$values]);
  640. foreach ($groupedData as $groupKey => $group) {
  641. $causalsInGroup = array_keys($causalsCount[$groupKey]);
  642. $causalDisplay = $group['type_label'];
  643. if (count($causalsInGroup) > 1) {
  644. $causalAmountsForJs = [];
  645. foreach ($causalsInGroup as $causalName) {
  646. $causalAmountsForJs[] = $causalName . ':::' . formatPrice($causalsAmounts[$groupKey][$causalName]);
  647. }
  648. $detailDisplay = 'Varie|' . implode('|', $causalAmountsForJs);
  649. } else {
  650. $detailDisplay = $causalsInGroup[0];
  651. }
  652. $recordKey = $group['date'] . "§" . $causalDisplay . "§" . $group['nominativo'] . "§" . $detailDisplay . "§" . ($group['deleted'] ? 'DELETED' : '') . "§";
  653. if (!isset($this->records[$recordKey][$group['payment_method']][$group['transaction_type']])) {
  654. $this->records[$recordKey][$group['payment_method']][$group['transaction_type']] = 0;
  655. }
  656. $this->records[$recordKey][$group['payment_method']][$group['transaction_type']] += $group['amount'];
  657. if (!isset($this->totals[$group['payment_method']])) {
  658. $this->totals[$group['payment_method']]["IN"] = 0;
  659. $this->totals[$group['payment_method']]["OUT"] = 0;
  660. }
  661. if (!$group['deleted'])
  662. $this->totals[$group['payment_method']][$group['transaction_type']] += $group['amount'];
  663. }
  664. */
  665. return view('livewire.records');
  666. }
  667. private function getLabels($fromDate, $toDate)
  668. {
  669. $begin = new DateTime($fromDate);
  670. $end = new DateTime($toDate);
  671. $interval = DateInterval::createFromDateString('1 day');
  672. $date_range = new DatePeriod($begin, $interval, $end);
  673. foreach ($date_range as $date) {
  674. $labels[] = $date->format('d/M');
  675. }
  676. return $labels;
  677. }
  678. private function getRecordData($type, $fromDate, $toDate)
  679. {
  680. $data = [];
  681. $begin = new DateTime($fromDate);
  682. $end = new DateTime($toDate);
  683. $interval = DateInterval::createFromDateString('1 day');
  684. $date_range = new DatePeriod($begin, $interval, $end);
  685. foreach ($date_range as $date) {
  686. if ($type == 'IN') {
  687. $found = false;
  688. foreach ($this->in as $in) {
  689. if (date("Y-m-d", strtotime($in->date)) == $date->format('Y-m-d')) {
  690. $data[] = number_format($in->total, 0, "", "");
  691. $found = true;
  692. }
  693. }
  694. if (!$found)
  695. $data[] = 0;
  696. }
  697. if ($type == 'OUT') {
  698. $found = false;
  699. foreach ($this->out as $out) {
  700. if (date("Y-m-d", strtotime($out->date)) == $date->format('Y-m-d')) {
  701. $data[] = number_format($out->total, 0, "", "");
  702. $found = true;
  703. }
  704. }
  705. if (!$found)
  706. $data[] = 0;
  707. }
  708. }
  709. return $data;
  710. }
  711. public function openExportModal()
  712. {
  713. $this->exportFromDate = $this->appliedFromDate;
  714. $this->exportToDate = $this->appliedToDate;
  715. // Reset email options
  716. $this->sendViaEmail = false;
  717. $this->exportEmailAddress = $this->getPreferredEmail();
  718. $this->updateEmailSubject();
  719. $this->emit('show-export-modal');
  720. }
  721. public function exportWithDateRange()
  722. {
  723. Log::info('=== EXPORT START ===', [
  724. 'user_id' => auth()->id(),
  725. 'from_date' => $this->exportFromDate,
  726. 'to_date' => $this->exportToDate,
  727. 'send_via_email' => $this->sendViaEmail,
  728. 'memory_usage' => memory_get_usage(true),
  729. 'memory_peak' => memory_get_peak_usage(true),
  730. 'time_limit' => ini_get('max_execution_time')
  731. ]);
  732. $this->isExporting = true;
  733. $this->emit('$refresh');
  734. usleep(100000);
  735. if ($this->sendViaEmail) {
  736. Log::info('Export: Validating email fields');
  737. $this->validate([
  738. 'exportEmailAddress' => 'required|email',
  739. 'exportEmailSubject' => 'required|string|max:255',
  740. ]);
  741. Log::info('Export: Email validation passed');
  742. }
  743. $this->isExporting = true;
  744. try {
  745. Log::info('Export: Starting COMBINED data generation phase (NO SEPARATE CALLS)');
  746. $startTime = microtime(true);
  747. // *** THIS IS THE KEY CHANGE - USE ONLY THE COMBINED METHOD ***
  748. $result = $this->generateExportDataAndTotals($this->exportFromDate, $this->exportToDate);
  749. $exportRecords = $result['records'];
  750. $exportTotals = $result['totals'];
  751. Log::info('TOTALS', [$exportTotals]);
  752. $dataGenTime = microtime(true) - $startTime;
  753. Log::info('Export: COMBINED data generation completed (NO SEPARATE TOTALS CALL)', [
  754. 'records_count' => count($exportRecords),
  755. 'totals_count' => count($exportTotals),
  756. 'generation_time' => $dataGenTime,
  757. 'memory_usage' => memory_get_usage(true),
  758. 'memory_peak' => memory_get_peak_usage(true)
  759. ]);
  760. if ($this->sendViaEmail) {
  761. Log::info('Export: Dispatching to background job');
  762. //$this->dispatchExportJob($exportRecords, $exportTotals);
  763. Log::info('Export: Job dispatched successfully');
  764. } else {
  765. Log::info('Export: Starting direct download export');
  766. $exportStartTime = microtime(true);
  767. $result = $this->exportWithData($exportRecords, $exportTotals);
  768. $exportTime = microtime(true) - $exportStartTime;
  769. Log::info('Export: Direct export completed', [
  770. 'export_time' => $exportTime,
  771. 'total_time' => microtime(true) - $startTime,
  772. 'memory_usage' => memory_get_usage(true),
  773. 'memory_peak' => memory_get_peak_usage(true)
  774. ]);
  775. return $result;
  776. }
  777. } catch (\Illuminate\Validation\ValidationException $e) {
  778. Log::error('Export: Validation error', [
  779. 'error' => $e->getMessage(),
  780. 'errors' => $e->errors()
  781. ]);
  782. $this->isExporting = false;
  783. throw $e;
  784. } catch (\Exception $e) {
  785. Log::error('Export: General error', [
  786. 'error' => $e->getMessage(),
  787. 'trace' => $e->getTraceAsString(),
  788. 'memory_usage' => memory_get_usage(true),
  789. 'memory_peak' => memory_get_peak_usage(true),
  790. 'execution_time' => microtime(true) - ($startTime ?? 0)
  791. ]);
  792. $this->isExporting = false;
  793. if ($this->sendViaEmail) {
  794. $this->emit('export-email-error', 'Errore durante l\'invio dell\'email: ' . $e->getMessage());
  795. } else {
  796. session()->flash('error', 'Errore durante l\'export: ' . $e->getMessage());
  797. }
  798. } finally {
  799. Log::info('Export: Cleanup phase');
  800. $this->isExporting = false;
  801. $this->emit('export-complete');
  802. $this->emit('hide-export-modal');
  803. Log::info('=== EXPORT END ===');
  804. }
  805. }
  806. public function exportData()
  807. {
  808. $this->isExporting = true;
  809. $this->emit('$refresh');
  810. usleep(100000);
  811. if ($this->sendViaEmail) {
  812. Log::info('Export: Validating email fields');
  813. $this->validate([
  814. 'exportEmailAddress' => 'required|email',
  815. 'exportEmailSubject' => 'required|string|max:255',
  816. ]);
  817. Log::info('Export: Email validation passed');
  818. }
  819. $this->isExporting = true;
  820. try {
  821. Log::info('Export: Starting COMBINED data generation phase (NO SEPARATE CALLS)');
  822. $startTime = microtime(true);
  823. $records = $this->loadData($this->exportFromDate, $this->exportToDate);
  824. $dataGenTime = microtime(true) - $startTime;
  825. if ($this->sendViaEmail) {
  826. Log::info('Export: Dispatching to background job');
  827. // Invio mail
  828. $this->dispatchExportJob($records);
  829. Log::info('Export: Job dispatched successfully');
  830. } else {
  831. Log::info('Export: Starting direct download export');
  832. $exportStartTime = microtime(true);
  833. // Creo excel e scarico
  834. $result = $this->exportExcel($records);
  835. $exportTime = microtime(true) - $exportStartTime;
  836. return $result;
  837. }
  838. } catch (\Illuminate\Validation\ValidationException $e) {
  839. Log::error('Export: Validation error', [
  840. 'error' => $e->getMessage(),
  841. 'errors' => $e->errors()
  842. ]);
  843. $this->isExporting = false;
  844. throw $e;
  845. } catch (\Exception $e) {
  846. Log::error('Export: General error', [
  847. 'error' => $e->getMessage(),
  848. 'trace' => $e->getTraceAsString(),
  849. 'memory_usage' => memory_get_usage(true),
  850. 'memory_peak' => memory_get_peak_usage(true),
  851. 'execution_time' => microtime(true) - ($startTime ?? 0)
  852. ]);
  853. $this->isExporting = false;
  854. if ($this->sendViaEmail) {
  855. $this->emit('export-email-error', 'Errore durante l\'invio dell\'email: ' . $e->getMessage());
  856. } else {
  857. session()->flash('error', 'Errore durante l\'export: ' . $e->getMessage());
  858. }
  859. } finally {
  860. Log::info('Export: Cleanup phase');
  861. $this->isExporting = false;
  862. $this->emit('export-complete');
  863. $this->emit('hide-export-modal');
  864. Log::info('=== EXPORT END ===');
  865. }
  866. }
  867. private function getEstimatedRecordCount($fromDate, $toDate)
  868. {
  869. $exclude_from_records = \App\Models\Member::where('exclude_from_records', true)->pluck('id')->toArray();
  870. $query = \App\Models\Record::join('records_rows', 'records.id', '=', 'records_rows.record_id')
  871. ->whereBetween('date', [$fromDate, $toDate])
  872. ->where(function ($query) {
  873. $query->where('type', 'OUT')
  874. ->orWhere(function ($query) {
  875. $query->where('records.corrispettivo_fiscale', true)
  876. ->orWhere('records.commercial', false);
  877. });
  878. })
  879. ->where(function ($query) use ($exclude_from_records) {
  880. $query->where('type', 'OUT')
  881. ->orWhere(function ($subquery) use ($exclude_from_records) {
  882. $subquery->whereNotIn('member_id', $exclude_from_records);
  883. });
  884. });
  885. if ($this->filterCausals != null && sizeof($this->filterCausals) > 0) {
  886. $causals = array();
  887. foreach ($this->filterCausals as $z) {
  888. $causals[] = $z;
  889. $childs = \App\Models\Causal::where('parent_id', $z)->get();
  890. foreach ($childs as $c) {
  891. $causals[] = $c->id;
  892. $childsX = \App\Models\Causal::where('parent_id', $c->id)->get();
  893. foreach ($childsX as $cX) {
  894. $causals[] = $cX->id;
  895. }
  896. }
  897. }
  898. $query->whereIn('causal_id', $causals);
  899. }
  900. if ($this->filterMember != null && $this->filterMember > 0) {
  901. $query->where('member_id', $this->filterMember);
  902. }
  903. return $query->count();
  904. }
  905. private function getMemberName($memberId)
  906. {
  907. $member = \App\Models\Member::find($memberId);
  908. return $member ? $member->last_name . ' ' . $member->first_name : 'Sconosciuto';
  909. }
  910. private function getCausalsNames($causalIds)
  911. {
  912. if (!is_array($causalIds)) {
  913. return null;
  914. }
  915. $causals = \App\Models\Causal::whereIn('id', $causalIds)->pluck('name')->toArray();
  916. return implode(', ', $causals);
  917. }
  918. public function updatedExportFromDate()
  919. {
  920. $this->updateEmailSubject();
  921. }
  922. public function updatedExportToDate()
  923. {
  924. $this->updateEmailSubject();
  925. }
  926. public function updatedSendViaEmail($value)
  927. {
  928. if ($value && empty($this->exportEmailAddress)) {
  929. $this->exportEmailAddress = $this->getPreferredEmail();
  930. }
  931. }
  932. public function resetEmailForm()
  933. {
  934. $this->sendViaEmail = false;
  935. $this->exportEmailAddress = $this->getPreferredEmail();
  936. $this->updateEmailSubject();
  937. }
  938. private function updateEmailSubject()
  939. {
  940. if (!empty($this->exportFromDate) && !empty($this->exportToDate)) {
  941. $fromFormatted = date('d/m/Y', strtotime($this->exportFromDate));
  942. $toFormatted = date('d/m/Y', strtotime($this->exportToDate));
  943. if ($this->exportFromDate === $this->exportToDate) {
  944. $this->exportEmailSubject = "Prima Nota - Export del {$fromFormatted}";
  945. } else {
  946. $this->exportEmailSubject = "Prima Nota - Export dal {$fromFormatted} al {$toFormatted}";
  947. }
  948. }
  949. }
  950. /**
  951. * Dispatch export job to queue
  952. */
  953. //private function dispatchExportJob($exportRecords, $exportTotals)
  954. private function dispatchExportJob($records)
  955. {
  956. try {
  957. // Prepare filter descriptions for the job
  958. $filterDescriptions = [
  959. 'member' => $this->filterMember ? $this->getMemberName($this->filterMember) : null,
  960. 'causals' => $this->filterCausals ? $this->getCausalsNames($this->filterCausals) : null,
  961. ];
  962. $paymentsArray = $this->payments->map(function ($payment) {
  963. return [
  964. 'id' => $payment->id,
  965. 'name' => $payment->name,
  966. 'type' => $payment->type
  967. ];
  968. })->toArray();
  969. // Dispatch job to background queue
  970. ExportPrimaNota::dispatch(
  971. /*$exportRecords,
  972. $exportTotals,*/
  973. $records,
  974. $this->exportEmailAddress,
  975. $this->exportEmailSubject,
  976. [
  977. 'from' => date('d/m/Y', strtotime($this->exportFromDate)),
  978. 'to' => date('d/m/Y', strtotime($this->exportToDate))
  979. ],
  980. auth()->id(),
  981. $paymentsArray,
  982. $filterDescriptions
  983. );
  984. $this->emit('export-email-queued');
  985. session()->flash('success', 'Export in corso! Riceverai l\'email a breve alla casella: ' . $this->exportEmailAddress);
  986. Log::info('Export job dispatched', [
  987. 'user_id' => auth()->id(),
  988. 'email' => $this->exportEmailAddress,
  989. 'date_range' => [$this->exportFromDate, $this->exportToDate],
  990. 'total_records' => count($this->records)
  991. ]);
  992. } catch (\Exception $e) {
  993. Log::error('Failed to dispatch export job', [
  994. 'user_id' => auth()->id(),
  995. 'email' => $this->exportEmailAddress,
  996. 'error' => $e->getMessage()
  997. ]);
  998. throw new \Exception('Errore nell\'avvio dell\'export: ' . $e->getMessage());
  999. }
  1000. }
  1001. function export()
  1002. {
  1003. $result = $this->generateExportDataAndTotals($this->exportFromDate, $this->exportToDate);
  1004. $exportRecords = $result['records'];
  1005. $exportTotals = $result['totals'];
  1006. return $this->exportWithData($exportRecords, $exportTotals);
  1007. }
  1008. private function exportWithData($exportRecords, $exportTotals)
  1009. {
  1010. Log::info('exportWithData: Starting Excel generation', [
  1011. 'records_count' => count($exportRecords),
  1012. 'totals_count' => count($exportTotals),
  1013. 'memory_before' => memory_get_usage(true)
  1014. ]);
  1015. $startTime = microtime(true);
  1016. Log::info('exportWithData: Setting memory and GC');
  1017. ini_set('memory_limit', '512M');
  1018. gc_enable();
  1019. Log::info('exportWithData: Preparing column letters');
  1020. $letters = array('F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'AA');
  1021. Log::info('exportWithData: Creating spreadsheet object');
  1022. $spreadsheet = new Spreadsheet();
  1023. $activeWorksheet = $spreadsheet->getActiveSheet();
  1024. Log::info('exportWithData: Setting basic headers');
  1025. $activeWorksheet->setCellValue('A1', "Data");
  1026. $activeWorksheet->setCellValue('B1', "Tipologia");
  1027. $activeWorksheet->setCellValue('C1', "Causale");
  1028. $activeWorksheet->setCellValue('D1', "Nominativo");
  1029. $activeWorksheet->setCellValue('E1', "Stato");
  1030. $activeWorksheet->getStyle('A1:Q1')->getFill()
  1031. ->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)
  1032. ->getStartColor()->setARGB('FF0C6197');
  1033. $activeWorksheet->getStyle('A1:Q1')->getFont()->getColor()->setARGB('FFFFFFFF');
  1034. Log::info('exportWithData: Setting payment method headers');
  1035. $idx = 0;
  1036. foreach ($this->payments as $p) {
  1037. if ($idx >= count($letters)) {
  1038. Log::warning('exportWithData: Reached letter limit', ['payment_index' => $idx]);
  1039. break;
  1040. }
  1041. Log::debug('exportWithData: Setting payment header', [
  1042. 'payment_name' => $p->name,
  1043. 'column_index' => $idx,
  1044. 'column_letter' => $letters[$idx]
  1045. ]);
  1046. $activeWorksheet->setCellValue($letters[$idx] . '1', $p->name);
  1047. $idx++;
  1048. if ($idx >= count($letters)) {
  1049. break;
  1050. }
  1051. $activeWorksheet->mergeCells($letters[$idx] . '1:' . $letters[$idx] . '1');
  1052. $idx++;
  1053. }
  1054. Log::info('exportWithData: Setting sub-headers');
  1055. $idx = 0;
  1056. $activeWorksheet->setCellValue('A2', "");
  1057. $activeWorksheet->setCellValue('B2', "");
  1058. $activeWorksheet->setCellValue('C2', "");
  1059. $activeWorksheet->setCellValue('D2', "");
  1060. $activeWorksheet->setCellValue('E2', "");
  1061. foreach ($this->payments as $p) {
  1062. if ($p->type == 'ALL') {
  1063. if ($idx >= count($letters)) {
  1064. break;
  1065. }
  1066. $activeWorksheet->setCellValue($letters[$idx] . '2', "Entrate");
  1067. $idx++;
  1068. $activeWorksheet->setCellValue($letters[$idx] . '2', "Uscite");
  1069. $idx++;
  1070. } elseif ($p->type == 'IN') {
  1071. if ($idx >= count($letters)) {
  1072. break;
  1073. }
  1074. $activeWorksheet->setCellValue($letters[$idx] . '2', "Entrate");
  1075. $idx++;
  1076. $activeWorksheet->setCellValue($letters[$idx] . '2', "");
  1077. $idx++;
  1078. } elseif ($p->type == 'OUT') {
  1079. if ($idx >= count($letters)) {
  1080. break;
  1081. }
  1082. $activeWorksheet->setCellValue($letters[$idx] . '2', "");
  1083. $idx++;
  1084. $activeWorksheet->setCellValue($letters[$idx] . '2', "Uscite");
  1085. $idx++;
  1086. }
  1087. }
  1088. Log::info('exportWithData: Applying header styles');
  1089. $activeWorksheet->getStyle('A1:Q1')->getFont()->setBold(true);
  1090. $activeWorksheet->getStyle('A2:Q2')->getFont()->setBold(true);
  1091. Log::info('exportWithData: Starting data row processing');
  1092. $count = 3;
  1093. $batchSize = 1000;
  1094. $recordsProcessed = 0;
  1095. $totalRecords = count($exportRecords);
  1096. Log::info('exportWithData: Processing records in batches', [
  1097. 'total_records' => $totalRecords,
  1098. 'batch_size' => $batchSize
  1099. ]);
  1100. $recordsArray = array_chunk($exportRecords, $batchSize, true);
  1101. Log::info('exportWithData: Created batches', ['batch_count' => count($recordsArray)]);
  1102. foreach ($recordsArray as $batchIndex => $recordsBatch) {
  1103. Log::info('exportWithData: Processing batch', [
  1104. 'batch_index' => $batchIndex,
  1105. 'batch_size' => count($recordsBatch),
  1106. 'memory_current' => memory_get_usage(true),
  1107. 'time_elapsed' => microtime(true) - $startTime
  1108. ]);
  1109. foreach ($recordsBatch as $causal => $record) {
  1110. if ($recordsProcessed % 250 == 0) {
  1111. Log::info('exportWithData: Record processing progress', [
  1112. 'processed' => $recordsProcessed,
  1113. 'total' => $totalRecords,
  1114. 'current_row' => $count,
  1115. 'memory_usage' => memory_get_usage(true),
  1116. 'time_elapsed' => microtime(true) - $startTime
  1117. ]);
  1118. }
  1119. try {
  1120. $check = $causal;
  1121. $parts = explode("§", $check);
  1122. $d = $parts[0] ?? '';
  1123. $c = $parts[1] ?? '';
  1124. $j = $parts[2] ?? '';
  1125. $det = $parts[3] ?? '';
  1126. $deleted = $parts[4] ?? '';
  1127. $detailParts = explode('|', $det);
  1128. $exportDetail = count($detailParts) > 1 ? implode(', ', array_slice($detailParts, 1)) : $det;
  1129. Log::debug('exportWithData: Setting row cells', ['row' => $count]);
  1130. $activeWorksheet->setCellValue('A' . $count, !empty($d) ? date("d/m/Y", strtotime($d)) : '');
  1131. $activeWorksheet->setCellValue('B' . $count, $c);
  1132. $activeWorksheet->setCellValue('C' . $count, $exportDetail);
  1133. $activeWorksheet->setCellValue('D' . $count, $j);
  1134. $stato = ($deleted === 'DELETED') ? 'ANNULLATA' : '';
  1135. $activeWorksheet->setCellValue('E' . $count, $stato);
  1136. if ($stato === 'ANNULLATA') {
  1137. $activeWorksheet->getStyle('E' . $count)->getFont()->getColor()->setARGB('FFFF0000');
  1138. }
  1139. $idx = 0;
  1140. foreach ($this->payments as $p) {
  1141. if ($idx >= count($letters) - 1) {
  1142. break;
  1143. }
  1144. if (isset($record[$p->name])) {
  1145. $inValue = isset($record[$p->name]["IN"]) ? formatPrice($record[$p->name]["IN"]) : "";
  1146. $outValue = isset($record[$p->name]["OUT"]) ? formatPrice($record[$p->name]["OUT"]) : "";
  1147. $activeWorksheet->setCellValue($letters[$idx] . $count, $inValue);
  1148. $idx++;
  1149. $activeWorksheet->setCellValue($letters[$idx] . $count, $outValue);
  1150. $idx++;
  1151. } else {
  1152. $activeWorksheet->setCellValue($letters[$idx] . $count, "");
  1153. $idx++;
  1154. $activeWorksheet->setCellValue($letters[$idx] . $count, "");
  1155. $idx++;
  1156. }
  1157. }
  1158. $count++;
  1159. $recordsProcessed++;
  1160. if ($recordsProcessed % 500 === 0) {
  1161. Log::debug('exportWithData: Garbage collection');
  1162. gc_collect_cycles();
  1163. }
  1164. } catch (\Exception $e) {
  1165. Log::error('exportWithData: Error processing record row', [
  1166. 'row' => $count,
  1167. 'causal' => $causal,
  1168. 'error' => $e->getMessage(),
  1169. 'processed_so_far' => $recordsProcessed
  1170. ]);
  1171. throw $e;
  1172. }
  1173. }
  1174. Log::info('exportWithData: Batch completed', [
  1175. 'batch_index' => $batchIndex,
  1176. 'records_in_batch' => count($recordsBatch),
  1177. 'total_processed' => $recordsProcessed
  1178. ]);
  1179. unset($recordsBatch);
  1180. gc_collect_cycles();
  1181. }
  1182. Log::info('exportWithData: Adding totals row');
  1183. $count++;
  1184. $idx = 0;
  1185. $activeWorksheet->setCellValue('A' . $count, 'Totale');
  1186. $activeWorksheet->setCellValue('B' . $count, '');
  1187. $activeWorksheet->setCellValue('C' . $count, '');
  1188. $activeWorksheet->setCellValue('D' . $count, '');
  1189. $activeWorksheet->setCellValue('E' . $count, '');
  1190. foreach ($this->payments as $p) {
  1191. if ($idx >= count($letters) - 1) {
  1192. break;
  1193. }
  1194. if (isset($exportTotals[$p->name])) {
  1195. if ($p->type == 'ALL') {
  1196. $activeWorksheet->setCellValue($letters[$idx] . $count, formatPrice($exportTotals[$p->name]["IN"] ?? 0));
  1197. $idx++;
  1198. $activeWorksheet->setCellValue($letters[$idx] . $count, formatPrice($exportTotals[$p->name]["OUT"] ?? 0));
  1199. $idx++;
  1200. } elseif ($p->type == 'IN') {
  1201. $activeWorksheet->setCellValue($letters[$idx] . $count, formatPrice($exportTotals[$p->name]["IN"] ?? 0));
  1202. $idx++;
  1203. $activeWorksheet->setCellValue($letters[$idx] . $count, "");
  1204. $idx++;
  1205. } elseif ($p->type == 'OUT') {
  1206. $activeWorksheet->setCellValue($letters[$idx] . $count, "");
  1207. $idx++;
  1208. $activeWorksheet->setCellValue($letters[$idx] . $count, formatPrice($exportTotals[$p->name]["OUT"] ?? 0));
  1209. $idx++;
  1210. }
  1211. } else {
  1212. if ($p->type == 'ALL') {
  1213. $activeWorksheet->setCellValue($letters[$idx] . $count, "0");
  1214. $idx++;
  1215. $activeWorksheet->setCellValue($letters[$idx] . $count, "0");
  1216. $idx++;
  1217. } elseif ($p->type == 'IN') {
  1218. $activeWorksheet->setCellValue($letters[$idx] . $count, "0");
  1219. $idx++;
  1220. $activeWorksheet->setCellValue($letters[$idx] . $count, "");
  1221. $idx++;
  1222. } elseif ($p->type == 'OUT') {
  1223. $activeWorksheet->setCellValue($letters[$idx] . $count, "");
  1224. $idx++;
  1225. $activeWorksheet->setCellValue($letters[$idx] . $count, "0");
  1226. $idx++;
  1227. }
  1228. }
  1229. }
  1230. Log::info('exportWithData: Applying final styles');
  1231. $activeWorksheet->getStyle('A' . $count . ':Q' . $count)->getFont()->setBold(true);
  1232. Log::info('exportWithData: Setting column dimensions');
  1233. $activeWorksheet->getColumnDimension('A')->setWidth(20);
  1234. $activeWorksheet->getColumnDimension('B')->setWidth(40);
  1235. $activeWorksheet->getColumnDimension('C')->setWidth(40);
  1236. $activeWorksheet->getColumnDimension('D')->setWidth(40);
  1237. $activeWorksheet->getColumnDimension('E')->setWidth(20);
  1238. foreach ($letters as $l) {
  1239. $activeWorksheet->getColumnDimension($l)->setWidth(20);
  1240. }
  1241. $filename = 'prima_nota_' . date("YmdHis") . '.xlsx';
  1242. Log::info('exportWithData: Preparing to save file', [
  1243. 'filename' => $filename,
  1244. 'total_processing_time' => microtime(true) - $startTime,
  1245. 'memory_before_save' => memory_get_usage(true)
  1246. ]);
  1247. try {
  1248. $currentClient = session('currentClient', 'default');
  1249. $tempPath = sys_get_temp_dir() . '/' . $filename;
  1250. Log::info('exportWithData: Creating Excel writer');
  1251. $writer = new Xlsx($spreadsheet);
  1252. Log::info('exportWithData: Saving to temp path', ['temp_path' => $tempPath]);
  1253. $writerStart = microtime(true);
  1254. $writer->save($tempPath);
  1255. $writerTime = microtime(true) - $writerStart;
  1256. Log::info('exportWithData: File saved to temp', [
  1257. 'writer_time' => $writerTime,
  1258. 'file_size' => file_exists($tempPath) ? filesize($tempPath) : 'unknown',
  1259. 'memory_after_save' => memory_get_usage(true)
  1260. ]);
  1261. unset($spreadsheet, $activeWorksheet, $writer);
  1262. gc_collect_cycles();
  1263. Log::info('exportWithData: Uploading to S3');
  1264. $disk = Storage::disk('s3');
  1265. $s3Path = $currentClient . '/prima_nota/' . $filename;
  1266. $primaNotaFolderPath = $currentClient . '/prima_nota/.gitkeep';
  1267. if (!$disk->exists($primaNotaFolderPath)) {
  1268. $disk->put($primaNotaFolderPath, '');
  1269. Log::info("Created prima_nota folder for client: {$currentClient}");
  1270. }
  1271. $uploadStart = microtime(true);
  1272. $fileContent = file_get_contents($tempPath);
  1273. $uploaded = $disk->put($s3Path, $fileContent, 'private');
  1274. $uploadTime = microtime(true) - $uploadStart;
  1275. if (!$uploaded) {
  1276. throw new \Exception('Failed to upload file to Wasabi S3');
  1277. }
  1278. Log::info("Export completed successfully", [
  1279. 'client' => $currentClient,
  1280. 'path' => $s3Path,
  1281. 'file_size' => filesize($tempPath),
  1282. 'records_processed' => $recordsProcessed,
  1283. 'upload_time' => $uploadTime,
  1284. 'total_time' => microtime(true) - $startTime,
  1285. 'memory_peak' => memory_get_peak_usage(true)
  1286. ]);
  1287. if (file_exists($tempPath)) {
  1288. unlink($tempPath);
  1289. }
  1290. $downloadUrl = $disk->temporaryUrl($s3Path, now()->addHour());
  1291. return redirect($downloadUrl);
  1292. } catch (\Exception $e) {
  1293. Log::error('Export S3 error - falling back to local', [
  1294. 'error' => $e->getMessage(),
  1295. 'trace' => $e->getTraceAsString(),
  1296. 'client' => session('currentClient', 'unknown'),
  1297. 'filename' => $filename,
  1298. 'records_processed' => $recordsProcessed ?? 0,
  1299. 'time_elapsed' => microtime(true) - $startTime
  1300. ]);
  1301. // Fallback logic remains the same...
  1302. $currentClient = session('currentClient', 'default');
  1303. $clientFolder = storage_path('app/prima_nota/' . $currentClient);
  1304. if (!is_dir($clientFolder)) {
  1305. mkdir($clientFolder, 0755, true);
  1306. Log::info("Created local client prima_nota folder: {$clientFolder}");
  1307. }
  1308. $localPath = $clientFolder . '/' . $filename;
  1309. if (isset($tempPath) && file_exists($tempPath)) {
  1310. rename($tempPath, $localPath);
  1311. } else {
  1312. $writer = new Xlsx($spreadsheet);
  1313. $writer->save($localPath);
  1314. unset($spreadsheet, $activeWorksheet, $writer);
  1315. }
  1316. gc_collect_cycles();
  1317. Log::warning("Export saved locally due to S3 error", [
  1318. 'client' => $currentClient,
  1319. 'local_path' => $localPath,
  1320. 'error' => $e->getMessage()
  1321. ]);
  1322. session()->flash('warning', 'File salvato localmente a causa di un errore del cloud storage.');
  1323. return response()->download($localPath)->deleteFileAfterSend();
  1324. }
  1325. }
  1326. private function getPreferredEmail()
  1327. {
  1328. $email = auth()->user()->email ?? null;
  1329. if (empty($email)) {
  1330. $email = session('user_email', null);
  1331. }
  1332. if (empty($email)) {
  1333. $member = \App\Models\Member::where('user_id', auth()->id())->first();
  1334. $email = $member ? $member->email : null;
  1335. }
  1336. if (empty($email)) {
  1337. $email = config('mail.default_recipient', '');
  1338. }
  1339. return $email;
  1340. }
  1341. public function updatedSelectedDay($value)
  1342. {
  1343. if (!empty($value)) {
  1344. $this->selectedPeriod = 'GIORNO_PERSONALIZZATO';
  1345. $this->fromDate = $value;
  1346. $this->toDate = $value;
  1347. $this->applyFilters();
  1348. }
  1349. }
  1350. public function selectDay($day)
  1351. {
  1352. $this->selectedDay = $day;
  1353. $this->showDayPicker = false;
  1354. $this->updatedSelectedDay($day);
  1355. }
  1356. public function toggleDayPicker()
  1357. {
  1358. $this->showDayPicker = !$this->showDayPicker;
  1359. }
  1360. public function selectToday()
  1361. {
  1362. $today = date('Y-m-d');
  1363. $this->selectDay($today);
  1364. }
  1365. public function selectYesterday()
  1366. {
  1367. $yesterday = date('Y-m-d', strtotime('-1 day'));
  1368. $this->selectDay($yesterday);
  1369. }
  1370. // Updated month methods to work with both custom month and day
  1371. public function updatedSelectedMonth($value)
  1372. {
  1373. if (!empty($value)) {
  1374. $this->selectedPeriod = 'MESE_PERSONALIZZATO';
  1375. $firstDay = date('Y-m-01', strtotime($value . '-01'));
  1376. $lastDay = date('Y-m-t', strtotime($value . '-01'));
  1377. $this->fromDate = $firstDay;
  1378. $this->toDate = $lastDay;
  1379. $this->applyFilters();
  1380. }
  1381. }
  1382. public function selectMonth($month)
  1383. {
  1384. $this->selectedMonth = $month;
  1385. $this->showMonthPicker = false;
  1386. $this->updatedSelectedMonth($month);
  1387. }
  1388. public function toggleMonthPicker()
  1389. {
  1390. $this->showMonthPicker = !$this->showMonthPicker;
  1391. }
  1392. private function exportExcel($records)
  1393. {
  1394. $startTime = microtime(true);
  1395. $spreadsheet = new Spreadsheet();
  1396. $activeWorksheet = $spreadsheet->getActiveSheet();
  1397. $activeWorksheet->setCellValue('A1', "Data");
  1398. $activeWorksheet->setCellValue('B1', "Tipologia");
  1399. $activeWorksheet->setCellValue('C1', "Causale");
  1400. $activeWorksheet->setCellValue('D1', "Nominativo");
  1401. $activeWorksheet->setCellValue('E1', "Stato");
  1402. $activeWorksheet->setCellValue('F1', "Entrata");
  1403. $activeWorksheet->setCellValue('G1', "Uscita");
  1404. $activeWorksheet->setCellValue('H1', "Origine");
  1405. $activeWorksheet->setCellValue('I1', "Destinazione");
  1406. $activeWorksheet->setCellValue('J1', "Metodo di pagamento");
  1407. $activeWorksheet->getStyle('A1:J1')->getFill()
  1408. ->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)
  1409. ->getStartColor()->setARGB('FF0C6197');
  1410. $activeWorksheet->getStyle('A1:J1')->getFont()->getColor()->setARGB('FFFFFFFF');
  1411. $idx = 2;
  1412. foreach($records as $record)
  1413. {
  1414. if ($record->date != '')
  1415. {
  1416. $activeWorksheet->setCellValue('A' . $idx, date("d/m/Y", strtotime($record->date)));
  1417. $activeWorksheet->setCellValue('B' . $idx, $record->commercial ? 'Commerciale' : 'Non commerciale');
  1418. $activeWorksheet->setCellValue('C' . $idx, $record->causal_name);
  1419. $activeWorksheet->setCellValue('D' . $idx, $record->type == 'IN' ? ($record->member->first_name . " " . $record->member->last_name) : @$record->supplier->name);
  1420. $activeWorksheet->setCellValue('E' . $idx, $record->deleted ? 'Annullata' : '');
  1421. $activeWorksheet->setCellValue('F' . $idx, $record->type == 'IN' ? formatPrice($record->amount) : '');
  1422. $activeWorksheet->setCellValue('G' . $idx, $record->type == 'OUT' ? formatPrice($record->amount) : '');
  1423. $activeWorksheet->setCellValue('H' . $idx, $record->type == 'OUT' ? $record->origin : '');
  1424. $activeWorksheet->setCellValue('I' . $idx, $record->type == 'IN' ? $record->destination : '');
  1425. $activeWorksheet->setCellValue('J' . $idx, $record->payment_method->name);
  1426. }
  1427. else
  1428. {
  1429. $activeWorksheet->setCellValue('A' . $idx, "Totali");
  1430. $activeWorksheet->setCellValue('B' . $idx, "");
  1431. $activeWorksheet->setCellValue('C' . $idx, "");
  1432. $activeWorksheet->setCellValue('D' . $idx, "");
  1433. $activeWorksheet->setCellValue('E' . $idx, "");
  1434. $activeWorksheet->setCellValue('F' . $idx, formatPrice($record->total_in));
  1435. $activeWorksheet->setCellValue('G' . $idx, formatPrice($record->total_out));
  1436. $activeWorksheet->setCellValue('H' . $idx, "");
  1437. $activeWorksheet->setCellValue('I' . $idx, "");
  1438. $activeWorksheet->setCellValue('J' . $idx, "");
  1439. }
  1440. $idx++;
  1441. }
  1442. $activeWorksheet->getColumnDimension('A')->setWidth(10);
  1443. $activeWorksheet->getColumnDimension('B')->setWidth(30);
  1444. $activeWorksheet->getColumnDimension('C')->setWidth(30);
  1445. $activeWorksheet->getColumnDimension('D')->setWidth(30);
  1446. $activeWorksheet->getColumnDimension('E')->setWidth(10);
  1447. $activeWorksheet->getColumnDimension('F')->setWidth(10);
  1448. $activeWorksheet->getColumnDimension('G')->setWidth(10);
  1449. $activeWorksheet->getColumnDimension('H')->setWidth(20);
  1450. $activeWorksheet->getColumnDimension('I')->setWidth(20);
  1451. $activeWorksheet->getColumnDimension('J')->setWidth(30);
  1452. $activeWorksheet->getStyle('A' . ($idx - 1) . ':J' . ($idx - 1))->getFont()->setBold(true);
  1453. $filename = 'prima_nota_' . date("YmdHis") . '.xlsx';
  1454. Log::info('exportWithData: Preparing to save file', [
  1455. 'filename' => $filename,
  1456. //'total_processing_time' => microtime(true) - $startTime,
  1457. 'memory_before_save' => memory_get_usage(true)
  1458. ]);
  1459. try {
  1460. $currentClient = session('currentClient', 'default');
  1461. $tempPath = sys_get_temp_dir() . '/' . $filename;
  1462. $writer = new Xlsx($spreadsheet);
  1463. $writer->save($tempPath);
  1464. unset($spreadsheet, $activeWorksheet, $writer);
  1465. gc_collect_cycles();
  1466. Log::info('exportWithData: Uploading to S3');
  1467. $disk = Storage::disk('s3');
  1468. $s3Path = $currentClient . '/prima_nota/' . $filename;
  1469. $primaNotaFolderPath = $currentClient . '/prima_nota/.gitkeep';
  1470. if (!$disk->exists($primaNotaFolderPath)) {
  1471. $disk->put($primaNotaFolderPath, '');
  1472. }
  1473. $uploadStart = microtime(true);
  1474. $fileContent = file_get_contents($tempPath);
  1475. $uploaded = $disk->put($s3Path, $fileContent, 'private');
  1476. $uploadTime = microtime(true) - $uploadStart;
  1477. if (!$uploaded) {
  1478. throw new \Exception('Failed to upload file to Wasabi S3');
  1479. }
  1480. Log::info("Export completed successfully", [
  1481. 'client' => $currentClient,
  1482. 'path' => $s3Path,
  1483. 'file_size' => filesize($tempPath),
  1484. 'records_processed' => $recordsProcessed,
  1485. 'upload_time' => $uploadTime,
  1486. 'total_time' => microtime(true) - $startTime,
  1487. 'memory_peak' => memory_get_peak_usage(true)
  1488. ]);
  1489. if (file_exists($tempPath)) {
  1490. unlink($tempPath);
  1491. }
  1492. $downloadUrl = $disk->temporaryUrl($s3Path, now()->addHour());
  1493. return redirect($downloadUrl);
  1494. } catch (\Exception $e) {
  1495. Log::error('Export S3 error - falling back to local', [
  1496. 'error' => $e->getMessage(),
  1497. 'trace' => $e->getTraceAsString(),
  1498. 'client' => session('currentClient', 'unknown'),
  1499. 'filename' => $filename,
  1500. 'records_processed' => $recordsProcessed ?? 0,
  1501. 'time_elapsed' => microtime(true) - $startTime
  1502. ]);
  1503. // Fallback logic remains the same...
  1504. $currentClient = session('currentClient', 'default');
  1505. $clientFolder = storage_path('app/prima_nota/' . $currentClient);
  1506. if (!is_dir($clientFolder)) {
  1507. mkdir($clientFolder, 0755, true);
  1508. Log::info("Created local client prima_nota folder: {$clientFolder}");
  1509. }
  1510. $localPath = $clientFolder . '/' . $filename;
  1511. if (isset($tempPath) && file_exists($tempPath)) {
  1512. rename($tempPath, $localPath);
  1513. } else {
  1514. $writer = new Xlsx($spreadsheet);
  1515. $writer->save($localPath);
  1516. unset($spreadsheet, $activeWorksheet, $writer);
  1517. }
  1518. gc_collect_cycles();
  1519. Log::warning("Export saved locally due to S3 error", [
  1520. 'client' => $currentClient,
  1521. 'local_path' => $localPath,
  1522. 'error' => $e->getMessage()
  1523. ]);
  1524. session()->flash('warning', 'File salvato localmente a causa di un errore del cloud storage.');
  1525. return response()->download($localPath)->deleteFileAfterSend();
  1526. }
  1527. }
  1528. }