Record.php 56 KB

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