Record.php 73 KB

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