Record.php 56 KB

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