Record.php 78 KB

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