Record.php 57 KB

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