Record.php 76 KB

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