Record.php 70 KB

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