Record.php 68 KB

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