Record.php 78 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044
  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->deleted != true)
  635. if ($data->type == 'IN')
  636. $this->total_in += $data->amount;
  637. if ($data->type == 'OUT')
  638. $this->total_out += $data->amount;
  639. }
  640. }
  641. foreach ($financial_movements as $m) {
  642. // USCITA
  643. $ret[] = (object) [
  644. 'id' => 'fm_out_' . $m->id,
  645. 'date' => $m->date,
  646. 'type' => 'MOVE_OUT',
  647. 'commercial' => false,
  648. 'causal_name' => $m->causal_name,
  649. 'amount' => $m->amount,
  650. 'origin' => $m->origin,
  651. 'destination' => null,
  652. 'deleted' => $m->deleted,
  653. ];
  654. if (!$m->deleted)
  655. $this->total_out += $m->amount;
  656. // ENTRATA
  657. $ret[] = (object) [
  658. 'id' => 'fm_in_' . $m->id,
  659. 'date' => $m->date,
  660. 'type' => 'MOVE_IN',
  661. 'commercial' => false,
  662. 'causal_name' => $m->causal_name,
  663. 'amount' => $m->amount,
  664. 'origin' => null,
  665. 'destination' => $m->destination,
  666. 'deleted' => $m->deleted,
  667. ];
  668. if (!$m->deleted)
  669. $this->total_in += $m->amount;
  670. }
  671. usort($ret, function ($a, $b) {
  672. $da = $a->date ? strtotime((string)$a->date) : 0;
  673. $db = $b->date ? strtotime((string)$b->date) : 0;
  674. if ($da !== $db) return $da <=> $db;
  675. $ca = isset($a->created_at) && $a->created_at ? strtotime((string)$a->created_at) : 0;
  676. $cb = isset($b->created_at) && $b->created_at ? strtotime((string)$b->created_at) : 0;
  677. if ($ca !== $cb) return $ca <=> $cb;
  678. return ((int)($a->id ?? 0)) <=> ((int)($b->id ?? 0));
  679. });
  680. if ($this->total_in > 0 || $this->total_out > 0)
  681. {
  682. $ret[] = (object) array("date" => "", "total_in" => $this->total_in, "total_out" => $this->total_out);
  683. }
  684. return $ret;
  685. }
  686. public function render()
  687. {
  688. $month = 0;
  689. $year = 0;
  690. $this->records = array();
  691. $this->totals = array();
  692. $this->causalAmounts = array();
  693. $this->records = $this->loadData('', '');
  694. /*
  695. foreach ($datas as $idx => $data) {
  696. $causalCheck = \App\Models\Causal::findOrFail($data->causal_id);
  697. $paymentCheck = $data->payment_method->money;
  698. if (!$paymentCheck && ($causalCheck->no_first == null || !$causalCheck->no_first)) {
  699. if (!$data->deleted) {
  700. $amount = $data->amount;
  701. if ($data->vat_id > 0)
  702. $amount += getVatValue($amount, $data->vat_id);
  703. } else {
  704. $amount = $data->amount;
  705. }
  706. $isCommercial = ($data->commercial == 1 || $data->commercial === '1' || $data->commercial === true);
  707. $typeLabel = $isCommercial ? 'Commerciale' : 'Non Commerciale';
  708. $nominativo = '';
  709. if ($data->type == "IN") {
  710. if ($data->member) {
  711. $nominativo = $data->member->last_name . " " . $data->member->first_name;
  712. }
  713. if ($data->payment_method_id == 7)
  714. $values[] = array('id' => $data->record_id, 'amount' => $amount);
  715. } else {
  716. if ($data->supplier) {
  717. $nominativo = $data->supplier->name;
  718. }
  719. }
  720. $groupKey = $data->date . '|' . $typeLabel . '|' . $data->payment_method->name . '|' . $data->type . '|' . $nominativo;
  721. if (!isset($groupedData[$groupKey])) {
  722. $groupedData[$groupKey] = [
  723. 'date' => $data->date,
  724. 'type_label' => $typeLabel,
  725. 'payment_method' => $data->payment_method->name,
  726. 'transaction_type' => $data->type,
  727. 'nominativo' => $nominativo,
  728. 'amount' => 0,
  729. 'deleted' => false,
  730. 'causals' => [],
  731. 'notes' => []
  732. ];
  733. $causalsCount[$groupKey] = [];
  734. $causalsAmounts[$groupKey] = []; // Initialize causal amounts for this group
  735. $nominativi[$groupKey] = $nominativo;
  736. }
  737. $groupedData[$groupKey]['amount'] += $amount;
  738. $causalsCount[$groupKey][$causalCheck->getTree()] = true;
  739. $causalName = $causalCheck->getTree();
  740. if (!isset($causalsAmounts[$groupKey][$causalName])) {
  741. $causalsAmounts[$groupKey][$causalName] = 0;
  742. }
  743. $causalsAmounts[$groupKey][$causalName] += $amount;
  744. if (!empty($data->note)) {
  745. $groupedData[$groupKey]['notes'][] = $data->note;
  746. }
  747. if ($data->deleted) {
  748. $groupedData[$groupKey]['deleted'] = true;
  749. }
  750. }
  751. }
  752. Log::info('values', [$values]);
  753. foreach ($groupedData as $groupKey => $group) {
  754. $causalsInGroup = array_keys($causalsCount[$groupKey]);
  755. $causalDisplay = $group['type_label'];
  756. if (count($causalsInGroup) > 1) {
  757. $causalAmountsForJs = [];
  758. foreach ($causalsInGroup as $causalName) {
  759. $causalAmountsForJs[] = $causalName . ':::' . formatPrice($causalsAmounts[$groupKey][$causalName]);
  760. }
  761. $detailDisplay = 'Varie|' . implode('|', $causalAmountsForJs);
  762. } else {
  763. $detailDisplay = $causalsInGroup[0];
  764. }
  765. $recordKey = $group['date'] . "§" . $causalDisplay . "§" . $group['nominativo'] . "§" . $detailDisplay . "§" . ($group['deleted'] ? 'DELETED' : '') . "§";
  766. if (!isset($this->records[$recordKey][$group['payment_method']][$group['transaction_type']])) {
  767. $this->records[$recordKey][$group['payment_method']][$group['transaction_type']] = 0;
  768. }
  769. $this->records[$recordKey][$group['payment_method']][$group['transaction_type']] += $group['amount'];
  770. if (!isset($this->totals[$group['payment_method']])) {
  771. $this->totals[$group['payment_method']]["IN"] = 0;
  772. $this->totals[$group['payment_method']]["OUT"] = 0;
  773. }
  774. if (!$group['deleted'])
  775. $this->totals[$group['payment_method']][$group['transaction_type']] += $group['amount'];
  776. }
  777. */
  778. return view('livewire.records');
  779. }
  780. private function getLabels($fromDate, $toDate)
  781. {
  782. $begin = new DateTime($fromDate);
  783. $end = new DateTime($toDate);
  784. $interval = DateInterval::createFromDateString('1 day');
  785. $date_range = new DatePeriod($begin, $interval, $end);
  786. foreach ($date_range as $date) {
  787. $labels[] = $date->format('d/M');
  788. }
  789. return $labels;
  790. }
  791. private function getRecordData($type, $fromDate, $toDate)
  792. {
  793. $data = [];
  794. $begin = new DateTime($fromDate);
  795. $end = new DateTime($toDate);
  796. $interval = DateInterval::createFromDateString('1 day');
  797. $date_range = new DatePeriod($begin, $interval, $end);
  798. foreach ($date_range as $date) {
  799. if ($type == 'IN') {
  800. $found = false;
  801. foreach ($this->in as $in) {
  802. if (date("Y-m-d", strtotime($in->date)) == $date->format('Y-m-d')) {
  803. $data[] = number_format($in->total, 0, "", "");
  804. $found = true;
  805. }
  806. }
  807. if (!$found)
  808. $data[] = 0;
  809. }
  810. if ($type == 'OUT') {
  811. $found = false;
  812. foreach ($this->out as $out) {
  813. if (date("Y-m-d", strtotime($out->date)) == $date->format('Y-m-d')) {
  814. $data[] = number_format($out->total, 0, "", "");
  815. $found = true;
  816. }
  817. }
  818. if (!$found)
  819. $data[] = 0;
  820. }
  821. }
  822. return $data;
  823. }
  824. public function openExportModal()
  825. {
  826. $this->exportFromDate = $this->appliedFromDate;
  827. $this->exportToDate = $this->appliedToDate;
  828. // Reset email options
  829. $this->sendViaEmail = false;
  830. $this->exportEmailAddress = $this->getPreferredEmail();
  831. $this->updateEmailSubject();
  832. $this->emit('show-export-modal');
  833. }
  834. public function exportWithDateRange()
  835. {
  836. Log::info('=== EXPORT START ===', [
  837. 'user_id' => auth()->id(),
  838. 'from_date' => $this->exportFromDate,
  839. 'to_date' => $this->exportToDate,
  840. 'send_via_email' => $this->sendViaEmail,
  841. 'memory_usage' => memory_get_usage(true),
  842. 'memory_peak' => memory_get_peak_usage(true),
  843. 'time_limit' => ini_get('max_execution_time')
  844. ]);
  845. $this->isExporting = true;
  846. $this->emit('$refresh');
  847. usleep(100000);
  848. if ($this->sendViaEmail) {
  849. Log::info('Export: Validating email fields');
  850. $this->validate([
  851. 'exportEmailAddress' => 'required|email',
  852. 'exportEmailSubject' => 'required|string|max:255',
  853. ]);
  854. Log::info('Export: Email validation passed');
  855. }
  856. $this->isExporting = true;
  857. try {
  858. Log::info('Export: Starting COMBINED data generation phase (NO SEPARATE CALLS)');
  859. $startTime = microtime(true);
  860. // *** THIS IS THE KEY CHANGE - USE ONLY THE COMBINED METHOD ***
  861. $result = $this->generateExportDataAndTotals($this->exportFromDate, $this->exportToDate);
  862. $exportRecords = $result['records'];
  863. $exportTotals = $result['totals'];
  864. Log::info('TOTALS', [$exportTotals]);
  865. $dataGenTime = microtime(true) - $startTime;
  866. Log::info('Export: COMBINED data generation completed (NO SEPARATE TOTALS CALL)', [
  867. 'records_count' => count($exportRecords),
  868. 'totals_count' => count($exportTotals),
  869. 'generation_time' => $dataGenTime,
  870. 'memory_usage' => memory_get_usage(true),
  871. 'memory_peak' => memory_get_peak_usage(true)
  872. ]);
  873. if ($this->sendViaEmail) {
  874. Log::info('Export: Dispatching to background job');
  875. //$this->dispatchExportJob($exportRecords, $exportTotals);
  876. Log::info('Export: Job dispatched successfully');
  877. } else {
  878. Log::info('Export: Starting direct download export');
  879. $exportStartTime = microtime(true);
  880. $result = $this->exportWithData($exportRecords, $exportTotals);
  881. $exportTime = microtime(true) - $exportStartTime;
  882. Log::info('Export: Direct export completed', [
  883. 'export_time' => $exportTime,
  884. 'total_time' => microtime(true) - $startTime,
  885. 'memory_usage' => memory_get_usage(true),
  886. 'memory_peak' => memory_get_peak_usage(true)
  887. ]);
  888. return $result;
  889. }
  890. } catch (\Illuminate\Validation\ValidationException $e) {
  891. Log::error('Export: Validation error', [
  892. 'error' => $e->getMessage(),
  893. 'errors' => $e->errors()
  894. ]);
  895. $this->isExporting = false;
  896. throw $e;
  897. } catch (\Exception $e) {
  898. Log::error('Export: General error', [
  899. 'error' => $e->getMessage(),
  900. 'trace' => $e->getTraceAsString(),
  901. 'memory_usage' => memory_get_usage(true),
  902. 'memory_peak' => memory_get_peak_usage(true),
  903. 'execution_time' => microtime(true) - ($startTime ?? 0)
  904. ]);
  905. $this->isExporting = false;
  906. if ($this->sendViaEmail) {
  907. $this->emit('export-email-error', 'Errore durante l\'invio dell\'email: ' . $e->getMessage());
  908. } else {
  909. session()->flash('error', 'Errore durante l\'export: ' . $e->getMessage());
  910. }
  911. } finally {
  912. Log::info('Export: Cleanup phase');
  913. $this->isExporting = false;
  914. $this->emit('export-complete');
  915. $this->emit('hide-export-modal');
  916. Log::info('=== EXPORT END ===');
  917. }
  918. }
  919. public function exportData()
  920. {
  921. $this->isExporting = true;
  922. $this->emit('$refresh');
  923. usleep(100000);
  924. if ($this->sendViaEmail) {
  925. Log::info('Export: Validating email fields');
  926. $this->validate([
  927. 'exportEmailAddress' => 'required|email',
  928. 'exportEmailSubject' => 'required|string|max:255',
  929. ]);
  930. Log::info('Export: Email validation passed');
  931. }
  932. $this->isExporting = true;
  933. try {
  934. Log::info('Export: Starting COMBINED data generation phase (NO SEPARATE CALLS)');
  935. $startTime = microtime(true);
  936. $records = $this->loadData($this->exportFromDate, $this->exportToDate);
  937. $dataGenTime = microtime(true) - $startTime;
  938. if ($this->sendViaEmail) {
  939. Log::info('Export: Dispatching to background job');
  940. // Invio mail
  941. $this->dispatchExportJob($records);
  942. Log::info('Export: Job dispatched successfully');
  943. } else {
  944. Log::info('Export: Starting direct download export');
  945. $exportStartTime = microtime(true);
  946. // Creo excel e scarico
  947. $result = $this->exportExcel($records);
  948. $exportTime = microtime(true) - $exportStartTime;
  949. return $result;
  950. }
  951. } catch (\Illuminate\Validation\ValidationException $e) {
  952. Log::error('Export: Validation error', [
  953. 'error' => $e->getMessage(),
  954. 'errors' => $e->errors()
  955. ]);
  956. $this->isExporting = false;
  957. throw $e;
  958. } catch (\Exception $e) {
  959. Log::error('Export: General error', [
  960. 'error' => $e->getMessage(),
  961. 'trace' => $e->getTraceAsString(),
  962. 'memory_usage' => memory_get_usage(true),
  963. 'memory_peak' => memory_get_peak_usage(true),
  964. 'execution_time' => microtime(true) - ($startTime ?? 0)
  965. ]);
  966. $this->isExporting = false;
  967. if ($this->sendViaEmail) {
  968. $this->emit('export-email-error', 'Errore durante l\'invio dell\'email: ' . $e->getMessage());
  969. } else {
  970. session()->flash('error', 'Errore durante l\'export: ' . $e->getMessage());
  971. }
  972. } finally {
  973. Log::info('Export: Cleanup phase');
  974. $this->isExporting = false;
  975. $this->emit('export-complete');
  976. $this->emit('hide-export-modal');
  977. Log::info('=== EXPORT END ===');
  978. }
  979. }
  980. private function getEstimatedRecordCount($fromDate, $toDate)
  981. {
  982. $exclude_from_records = \App\Models\Member::where('exclude_from_records', true)->pluck('id')->toArray();
  983. $query = \App\Models\Record::join('records_rows', 'records.id', '=', 'records_rows.record_id')
  984. ->whereBetween('date', [$fromDate, $toDate])
  985. ->where(function ($query) {
  986. $query->where('type', 'OUT')
  987. ->orWhere(function ($query) {
  988. $query->where('records.corrispettivo_fiscale', true)
  989. ->orWhere('records.commercial', false);
  990. });
  991. })
  992. ->where(function ($query) use ($exclude_from_records) {
  993. $query->where('type', 'OUT')
  994. ->orWhere(function ($subquery) use ($exclude_from_records) {
  995. $subquery->whereNotIn('member_id', $exclude_from_records);
  996. });
  997. });
  998. if ($this->filterCausals != null && sizeof($this->filterCausals) > 0) {
  999. $causals = array();
  1000. foreach ($this->filterCausals as $z) {
  1001. $causals[] = $z;
  1002. $childs = \App\Models\Causal::where('parent_id', $z)->get();
  1003. foreach ($childs as $c) {
  1004. $causals[] = $c->id;
  1005. $childsX = \App\Models\Causal::where('parent_id', $c->id)->get();
  1006. foreach ($childsX as $cX) {
  1007. $causals[] = $cX->id;
  1008. }
  1009. }
  1010. }
  1011. $query->whereIn('causal_id', $causals);
  1012. }
  1013. if ($this->filterPaymentMethods != null && sizeof($this->filterPaymentMethods) > 0) {
  1014. $query->whereIn('payment_method_id', $this->filterPaymentMethods);
  1015. }
  1016. if ($this->filterOrigins != null && sizeof($this->filterOrigins) > 0) {
  1017. $query->whereIn('origin_id', $this->filterOrigins);
  1018. }
  1019. if ($this->filterDestinations != null && sizeof($this->filterDestinations) > 0) {
  1020. $query->whereIn('destination_id', $this->filterDestinations);
  1021. }
  1022. if ($this->filterMember != null && $this->filterMember > 0) {
  1023. $query->where('member_id', $this->filterMember);
  1024. }
  1025. if ($this->filterSupplier != null && $this->filterSupplier > 0) {
  1026. $query->where('supplier_id', $this->filterSupplier);
  1027. }
  1028. return $query->count();
  1029. }
  1030. private function getMemberName($memberId)
  1031. {
  1032. $member = \App\Models\Member::find($memberId);
  1033. return $member ? $member->last_name . ' ' . $member->first_name : 'Sconosciuto';
  1034. }
  1035. private function getSupplierName($supplierId)
  1036. {
  1037. $supplier = \App\Models\Supplier::find($supplierId);
  1038. return $supplier ? $supplier->name : 'Sconosciuto';
  1039. }
  1040. private function getCausalsNames($causalIds)
  1041. {
  1042. if (!is_array($causalIds)) {
  1043. return null;
  1044. }
  1045. $causals = \App\Models\Causal::whereIn('id', $causalIds)->pluck('name')->toArray();
  1046. return implode(', ', $causals);
  1047. }
  1048. private function getPaymentMethodsNames($paymentMethodIds)
  1049. {
  1050. if (!is_array($paymentMethodIds)) {
  1051. return null;
  1052. }
  1053. $payment_methods = \App\Models\PaymentMethod::whereIn('id', $paymentMethodIds)->pluck('name')->toArray();
  1054. return implode(', ', $payment_methods);
  1055. }
  1056. private function getOriginsNames($originIds)
  1057. {
  1058. if (!is_array($originIds)) {
  1059. return null;
  1060. }
  1061. $origins = \App\Models\Bank::whereIn('id', $originIds)->pluck('name')->toArray();
  1062. return implode(', ', $origins);
  1063. }
  1064. private function getDestinationsNames($destinationIds)
  1065. {
  1066. if (!is_array($destinationIds)) {
  1067. return null;
  1068. }
  1069. $destinations = \App\Models\Bank::whereIn('id', $destinationIds)->pluck('name')->toArray();
  1070. return implode(', ', $destinations);
  1071. }
  1072. public function updatedExportFromDate()
  1073. {
  1074. $this->updateEmailSubject();
  1075. }
  1076. public function updatedExportToDate()
  1077. {
  1078. $this->updateEmailSubject();
  1079. }
  1080. public function updatedSendViaEmail($value)
  1081. {
  1082. if ($value && empty($this->exportEmailAddress)) {
  1083. $this->exportEmailAddress = $this->getPreferredEmail();
  1084. }
  1085. }
  1086. public function resetEmailForm()
  1087. {
  1088. $this->sendViaEmail = false;
  1089. $this->exportEmailAddress = $this->getPreferredEmail();
  1090. $this->updateEmailSubject();
  1091. }
  1092. private function updateEmailSubject()
  1093. {
  1094. if (!empty($this->exportFromDate) && !empty($this->exportToDate)) {
  1095. $fromFormatted = date('d/m/Y', strtotime($this->exportFromDate));
  1096. $toFormatted = date('d/m/Y', strtotime($this->exportToDate));
  1097. if ($this->exportFromDate === $this->exportToDate) {
  1098. $this->exportEmailSubject = "Prima Nota - Export del {$fromFormatted}";
  1099. } else {
  1100. $this->exportEmailSubject = "Prima Nota - Export dal {$fromFormatted} al {$toFormatted}";
  1101. }
  1102. }
  1103. }
  1104. /**
  1105. * Dispatch export job to queue
  1106. */
  1107. //private function dispatchExportJob($exportRecords, $exportTotals)
  1108. private function dispatchExportJob($records)
  1109. {
  1110. try {
  1111. // Prepare filter descriptions for the job
  1112. $filterDescriptions = [
  1113. 'member' => $this->filterMember ? $this->getMemberName($this->filterMember) : null,
  1114. 'supplier' => $this->filterSupplier ? $this->getSupplierName($this->filterSupplier) : null,
  1115. 'causals' => $this->filterCausals ? $this->getCausalsNames($this->filterCausals) : null,
  1116. 'payment_methods' => $this->filterPaymentMethods ? $this->getPaymentMethodsNames($this->filterPaymentMethods) : null,
  1117. 'origins' => $this->filterOrigins ? $this->getOriginsNames($this->filterOrigins) : null,
  1118. 'destinations' => $this->filterDestinations ? $this->getDestinationsNames($this->filterDestinations) : null,
  1119. ];
  1120. $paymentsArray = $this->payments->map(function ($payment) {
  1121. return [
  1122. 'id' => $payment->id,
  1123. 'name' => $payment->name,
  1124. 'type' => $payment->type
  1125. ];
  1126. })->toArray();
  1127. // Dispatch job to background queue
  1128. ExportPrimaNota::dispatch(
  1129. /*$exportRecords,
  1130. $exportTotals,*/
  1131. $records,
  1132. $this->exportEmailAddress,
  1133. $this->exportEmailSubject,
  1134. [
  1135. 'from' => date('d/m/Y', strtotime($this->exportFromDate)),
  1136. 'to' => date('d/m/Y', strtotime($this->exportToDate))
  1137. ],
  1138. auth()->id(),
  1139. $paymentsArray,
  1140. $filterDescriptions
  1141. );
  1142. $this->emit('export-email-queued');
  1143. session()->flash('success', 'Export in corso! Riceverai l\'email a breve alla casella: ' . $this->exportEmailAddress);
  1144. Log::info('Export job dispatched', [
  1145. 'user_id' => auth()->id(),
  1146. 'email' => $this->exportEmailAddress,
  1147. 'date_range' => [$this->exportFromDate, $this->exportToDate],
  1148. 'total_records' => count($this->records)
  1149. ]);
  1150. } catch (\Exception $e) {
  1151. Log::error('Failed to dispatch export job', [
  1152. 'user_id' => auth()->id(),
  1153. 'email' => $this->exportEmailAddress,
  1154. 'error' => $e->getMessage()
  1155. ]);
  1156. throw new \Exception('Errore nell\'avvio dell\'export: ' . $e->getMessage());
  1157. }
  1158. }
  1159. function export()
  1160. {
  1161. $result = $this->generateExportDataAndTotals($this->exportFromDate, $this->exportToDate);
  1162. $exportRecords = $result['records'];
  1163. $exportTotals = $result['totals'];
  1164. return $this->exportWithData($exportRecords, $exportTotals);
  1165. }
  1166. private function exportWithData($exportRecords, $exportTotals)
  1167. {
  1168. Log::info('exportWithData: Starting Excel generation', [
  1169. 'records_count' => count($exportRecords),
  1170. 'totals_count' => count($exportTotals),
  1171. 'memory_before' => memory_get_usage(true)
  1172. ]);
  1173. $startTime = microtime(true);
  1174. Log::info('exportWithData: Setting memory and GC');
  1175. ini_set('memory_limit', '512M');
  1176. gc_enable();
  1177. Log::info('exportWithData: Preparing column letters');
  1178. $letters = array('F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'AA');
  1179. Log::info('exportWithData: Creating spreadsheet object');
  1180. $spreadsheet = new Spreadsheet();
  1181. $activeWorksheet = $spreadsheet->getActiveSheet();
  1182. Log::info('exportWithData: Setting basic headers');
  1183. $activeWorksheet->setCellValue('A1', "Data");
  1184. $activeWorksheet->setCellValue('B1', "Tipologia");
  1185. $activeWorksheet->setCellValue('C1', "Causale");
  1186. $activeWorksheet->setCellValue('D1', "Nominativo");
  1187. $activeWorksheet->setCellValue('E1', "Stato");
  1188. $activeWorksheet->getStyle('A1:Q1')->getFill()
  1189. ->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)
  1190. ->getStartColor()->setARGB('FF0C6197');
  1191. $activeWorksheet->getStyle('A1:Q1')->getFont()->getColor()->setARGB('FFFFFFFF');
  1192. Log::info('exportWithData: Setting payment method headers');
  1193. $idx = 0;
  1194. foreach ($this->payments as $p) {
  1195. if ($idx >= count($letters)) {
  1196. Log::warning('exportWithData: Reached letter limit', ['payment_index' => $idx]);
  1197. break;
  1198. }
  1199. Log::debug('exportWithData: Setting payment header', [
  1200. 'payment_name' => $p->name,
  1201. 'column_index' => $idx,
  1202. 'column_letter' => $letters[$idx]
  1203. ]);
  1204. $activeWorksheet->setCellValue($letters[$idx] . '1', $p->name);
  1205. $idx++;
  1206. if ($idx >= count($letters)) {
  1207. break;
  1208. }
  1209. $activeWorksheet->mergeCells($letters[$idx] . '1:' . $letters[$idx] . '1');
  1210. $idx++;
  1211. }
  1212. Log::info('exportWithData: Setting sub-headers');
  1213. $idx = 0;
  1214. $activeWorksheet->setCellValue('A2', "");
  1215. $activeWorksheet->setCellValue('B2', "");
  1216. $activeWorksheet->setCellValue('C2', "");
  1217. $activeWorksheet->setCellValue('D2', "");
  1218. $activeWorksheet->setCellValue('E2', "");
  1219. foreach ($this->payments as $p) {
  1220. if ($p->type == 'ALL') {
  1221. if ($idx >= count($letters)) {
  1222. break;
  1223. }
  1224. $activeWorksheet->setCellValue($letters[$idx] . '2', "Entrate");
  1225. $idx++;
  1226. $activeWorksheet->setCellValue($letters[$idx] . '2', "Uscite");
  1227. $idx++;
  1228. } elseif ($p->type == 'IN') {
  1229. if ($idx >= count($letters)) {
  1230. break;
  1231. }
  1232. $activeWorksheet->setCellValue($letters[$idx] . '2', "Entrate");
  1233. $idx++;
  1234. $activeWorksheet->setCellValue($letters[$idx] . '2', "");
  1235. $idx++;
  1236. } elseif ($p->type == 'OUT') {
  1237. if ($idx >= count($letters)) {
  1238. break;
  1239. }
  1240. $activeWorksheet->setCellValue($letters[$idx] . '2', "");
  1241. $idx++;
  1242. $activeWorksheet->setCellValue($letters[$idx] . '2', "Uscite");
  1243. $idx++;
  1244. }
  1245. }
  1246. Log::info('exportWithData: Applying header styles');
  1247. $activeWorksheet->getStyle('A1:Q1')->getFont()->setBold(true);
  1248. $activeWorksheet->getStyle('A2:Q2')->getFont()->setBold(true);
  1249. Log::info('exportWithData: Starting data row processing');
  1250. $count = 3;
  1251. $batchSize = 1000;
  1252. $recordsProcessed = 0;
  1253. $totalRecords = count($exportRecords);
  1254. Log::info('exportWithData: Processing records in batches', [
  1255. 'total_records' => $totalRecords,
  1256. 'batch_size' => $batchSize
  1257. ]);
  1258. $recordsArray = array_chunk($exportRecords, $batchSize, true);
  1259. Log::info('exportWithData: Created batches', ['batch_count' => count($recordsArray)]);
  1260. foreach ($recordsArray as $batchIndex => $recordsBatch) {
  1261. Log::info('exportWithData: Processing batch', [
  1262. 'batch_index' => $batchIndex,
  1263. 'batch_size' => count($recordsBatch),
  1264. 'memory_current' => memory_get_usage(true),
  1265. 'time_elapsed' => microtime(true) - $startTime
  1266. ]);
  1267. foreach ($recordsBatch as $causal => $record) {
  1268. if ($recordsProcessed % 250 == 0) {
  1269. Log::info('exportWithData: Record processing progress', [
  1270. 'processed' => $recordsProcessed,
  1271. 'total' => $totalRecords,
  1272. 'current_row' => $count,
  1273. 'memory_usage' => memory_get_usage(true),
  1274. 'time_elapsed' => microtime(true) - $startTime
  1275. ]);
  1276. }
  1277. try {
  1278. $check = $causal;
  1279. $parts = explode("§", $check);
  1280. $d = $parts[0] ?? '';
  1281. $c = $parts[1] ?? '';
  1282. $j = $parts[2] ?? '';
  1283. $det = $parts[3] ?? '';
  1284. $deleted = $parts[4] ?? '';
  1285. $detailParts = explode('|', $det);
  1286. $exportDetail = count($detailParts) > 1 ? implode(', ', array_slice($detailParts, 1)) : $det;
  1287. Log::debug('exportWithData: Setting row cells', ['row' => $count]);
  1288. $activeWorksheet->setCellValue('A' . $count, !empty($d) ? date("d/m/Y", strtotime($d)) : '');
  1289. $activeWorksheet->setCellValue('B' . $count, $c);
  1290. $activeWorksheet->setCellValue('C' . $count, $exportDetail);
  1291. $activeWorksheet->setCellValue('D' . $count, $j);
  1292. $stato = ($deleted === 'DELETED') ? 'ANNULLATA' : '';
  1293. $activeWorksheet->setCellValue('E' . $count, $stato);
  1294. if ($stato === 'ANNULLATA') {
  1295. $activeWorksheet->getStyle('E' . $count)->getFont()->getColor()->setARGB('FFFF0000');
  1296. }
  1297. $idx = 0;
  1298. foreach ($this->payments as $p) {
  1299. if ($idx >= count($letters) - 1) {
  1300. break;
  1301. }
  1302. if (isset($record[$p->name])) {
  1303. $inValue = isset($record[$p->name]["IN"]) ? formatPrice($record[$p->name]["IN"]) : "";
  1304. $outValue = isset($record[$p->name]["OUT"]) ? formatPrice($record[$p->name]["OUT"]) : "";
  1305. $activeWorksheet->setCellValue($letters[$idx] . $count, $inValue);
  1306. $idx++;
  1307. $activeWorksheet->setCellValue($letters[$idx] . $count, $outValue);
  1308. $idx++;
  1309. } else {
  1310. $activeWorksheet->setCellValue($letters[$idx] . $count, "");
  1311. $idx++;
  1312. $activeWorksheet->setCellValue($letters[$idx] . $count, "");
  1313. $idx++;
  1314. }
  1315. }
  1316. $count++;
  1317. $recordsProcessed++;
  1318. if ($recordsProcessed % 500 === 0) {
  1319. Log::debug('exportWithData: Garbage collection');
  1320. gc_collect_cycles();
  1321. }
  1322. } catch (\Exception $e) {
  1323. Log::error('exportWithData: Error processing record row', [
  1324. 'row' => $count,
  1325. 'causal' => $causal,
  1326. 'error' => $e->getMessage(),
  1327. 'processed_so_far' => $recordsProcessed
  1328. ]);
  1329. throw $e;
  1330. }
  1331. }
  1332. Log::info('exportWithData: Batch completed', [
  1333. 'batch_index' => $batchIndex,
  1334. 'records_in_batch' => count($recordsBatch),
  1335. 'total_processed' => $recordsProcessed
  1336. ]);
  1337. unset($recordsBatch);
  1338. gc_collect_cycles();
  1339. }
  1340. Log::info('exportWithData: Adding totals row');
  1341. $count++;
  1342. $idx = 0;
  1343. $activeWorksheet->setCellValue('A' . $count, 'Totale');
  1344. $activeWorksheet->setCellValue('B' . $count, '');
  1345. $activeWorksheet->setCellValue('C' . $count, '');
  1346. $activeWorksheet->setCellValue('D' . $count, '');
  1347. $activeWorksheet->setCellValue('E' . $count, '');
  1348. foreach ($this->payments as $p) {
  1349. if ($idx >= count($letters) - 1) {
  1350. break;
  1351. }
  1352. if (isset($exportTotals[$p->name])) {
  1353. if ($p->type == 'ALL') {
  1354. $activeWorksheet->setCellValue($letters[$idx] . $count, formatPrice($exportTotals[$p->name]["IN"] ?? 0));
  1355. $idx++;
  1356. $activeWorksheet->setCellValue($letters[$idx] . $count, formatPrice($exportTotals[$p->name]["OUT"] ?? 0));
  1357. $idx++;
  1358. } elseif ($p->type == 'IN') {
  1359. $activeWorksheet->setCellValue($letters[$idx] . $count, formatPrice($exportTotals[$p->name]["IN"] ?? 0));
  1360. $idx++;
  1361. $activeWorksheet->setCellValue($letters[$idx] . $count, "");
  1362. $idx++;
  1363. } elseif ($p->type == 'OUT') {
  1364. $activeWorksheet->setCellValue($letters[$idx] . $count, "");
  1365. $idx++;
  1366. $activeWorksheet->setCellValue($letters[$idx] . $count, formatPrice($exportTotals[$p->name]["OUT"] ?? 0));
  1367. $idx++;
  1368. }
  1369. } else {
  1370. if ($p->type == 'ALL') {
  1371. $activeWorksheet->setCellValue($letters[$idx] . $count, "0");
  1372. $idx++;
  1373. $activeWorksheet->setCellValue($letters[$idx] . $count, "0");
  1374. $idx++;
  1375. } elseif ($p->type == 'IN') {
  1376. $activeWorksheet->setCellValue($letters[$idx] . $count, "0");
  1377. $idx++;
  1378. $activeWorksheet->setCellValue($letters[$idx] . $count, "");
  1379. $idx++;
  1380. } elseif ($p->type == 'OUT') {
  1381. $activeWorksheet->setCellValue($letters[$idx] . $count, "");
  1382. $idx++;
  1383. $activeWorksheet->setCellValue($letters[$idx] . $count, "0");
  1384. $idx++;
  1385. }
  1386. }
  1387. }
  1388. Log::info('exportWithData: Applying final styles');
  1389. $activeWorksheet->getStyle('A' . $count . ':Q' . $count)->getFont()->setBold(true);
  1390. Log::info('exportWithData: Setting column dimensions');
  1391. $activeWorksheet->getColumnDimension('A')->setWidth(20);
  1392. $activeWorksheet->getColumnDimension('B')->setWidth(40);
  1393. $activeWorksheet->getColumnDimension('C')->setWidth(40);
  1394. $activeWorksheet->getColumnDimension('D')->setWidth(40);
  1395. $activeWorksheet->getColumnDimension('E')->setWidth(20);
  1396. foreach ($letters as $l) {
  1397. $activeWorksheet->getColumnDimension($l)->setWidth(20);
  1398. }
  1399. $filename = 'prima_nota_' . date("YmdHis") . '.xlsx';
  1400. Log::info('exportWithData: Preparing to save file', [
  1401. 'filename' => $filename,
  1402. 'total_processing_time' => microtime(true) - $startTime,
  1403. 'memory_before_save' => memory_get_usage(true)
  1404. ]);
  1405. try {
  1406. $currentClient = session('currentClient', 'default');
  1407. $tempPath = sys_get_temp_dir() . '/' . $filename;
  1408. Log::info('exportWithData: Creating Excel writer');
  1409. $writer = new Xlsx($spreadsheet);
  1410. Log::info('exportWithData: Saving to temp path', ['temp_path' => $tempPath]);
  1411. $writerStart = microtime(true);
  1412. $writer->save($tempPath);
  1413. $writerTime = microtime(true) - $writerStart;
  1414. Log::info('exportWithData: File saved to temp', [
  1415. 'writer_time' => $writerTime,
  1416. 'file_size' => file_exists($tempPath) ? filesize($tempPath) : 'unknown',
  1417. 'memory_after_save' => memory_get_usage(true)
  1418. ]);
  1419. unset($spreadsheet, $activeWorksheet, $writer);
  1420. gc_collect_cycles();
  1421. Log::info('exportWithData: Uploading to S3');
  1422. $disk = Storage::disk('s3');
  1423. $s3Path = $currentClient . '/prima_nota/' . $filename;
  1424. $primaNotaFolderPath = $currentClient . '/prima_nota/.gitkeep';
  1425. if (!$disk->exists($primaNotaFolderPath)) {
  1426. $disk->put($primaNotaFolderPath, '');
  1427. Log::info("Created prima_nota folder for client: {$currentClient}");
  1428. }
  1429. $uploadStart = microtime(true);
  1430. $fileContent = file_get_contents($tempPath);
  1431. $uploaded = $disk->put($s3Path, $fileContent, 'private');
  1432. $uploadTime = microtime(true) - $uploadStart;
  1433. if (!$uploaded) {
  1434. throw new \Exception('Failed to upload file to Wasabi S3');
  1435. }
  1436. Log::info("Export completed successfully", [
  1437. 'client' => $currentClient,
  1438. 'path' => $s3Path,
  1439. 'file_size' => filesize($tempPath),
  1440. 'records_processed' => $recordsProcessed,
  1441. 'upload_time' => $uploadTime,
  1442. 'total_time' => microtime(true) - $startTime,
  1443. 'memory_peak' => memory_get_peak_usage(true)
  1444. ]);
  1445. if (file_exists($tempPath)) {
  1446. unlink($tempPath);
  1447. }
  1448. $downloadUrl = $disk->temporaryUrl($s3Path, now()->addHour());
  1449. return redirect($downloadUrl);
  1450. } catch (\Exception $e) {
  1451. Log::error('Export S3 error - falling back to local', [
  1452. 'error' => $e->getMessage(),
  1453. 'trace' => $e->getTraceAsString(),
  1454. 'client' => session('currentClient', 'unknown'),
  1455. 'filename' => $filename,
  1456. 'records_processed' => $recordsProcessed ?? 0,
  1457. 'time_elapsed' => microtime(true) - $startTime
  1458. ]);
  1459. // Fallback logic remains the same...
  1460. $currentClient = session('currentClient', 'default');
  1461. $clientFolder = storage_path('app/prima_nota/' . $currentClient);
  1462. if (!is_dir($clientFolder)) {
  1463. mkdir($clientFolder, 0755, true);
  1464. Log::info("Created local client prima_nota folder: {$clientFolder}");
  1465. }
  1466. $localPath = $clientFolder . '/' . $filename;
  1467. if (isset($tempPath) && file_exists($tempPath)) {
  1468. rename($tempPath, $localPath);
  1469. } else {
  1470. $writer = new Xlsx($spreadsheet);
  1471. $writer->save($localPath);
  1472. unset($spreadsheet, $activeWorksheet, $writer);
  1473. }
  1474. gc_collect_cycles();
  1475. Log::warning("Export saved locally due to S3 error", [
  1476. 'client' => $currentClient,
  1477. 'local_path' => $localPath,
  1478. 'error' => $e->getMessage()
  1479. ]);
  1480. session()->flash('warning', 'File salvato localmente a causa di un errore del cloud storage.');
  1481. return response()->download($localPath)->deleteFileAfterSend();
  1482. }
  1483. }
  1484. private function getPreferredEmail()
  1485. {
  1486. $email = auth()->user()->email ?? null;
  1487. if (empty($email)) {
  1488. $email = session('user_email', null);
  1489. }
  1490. if (empty($email)) {
  1491. $member = \App\Models\Member::where('user_id', auth()->id())->first();
  1492. $email = $member ? $member->email : null;
  1493. }
  1494. if (empty($email)) {
  1495. $email = config('mail.default_recipient', '');
  1496. }
  1497. return $email;
  1498. }
  1499. public function updatedSelectedPeriod($value) {
  1500. $this->setPeriodDates();
  1501. // $this->applyFilters();
  1502. }
  1503. public function updatedSelectedDay($value)
  1504. {
  1505. if (!empty($value)) {
  1506. $this->selectedPeriod = 'GIORNO_PERSONALIZZATO';
  1507. $this->fromDate = $value;
  1508. $this->toDate = $value;
  1509. // $this->applyFilters();
  1510. }
  1511. }
  1512. public function selectDay($day)
  1513. {
  1514. $this->selectedDay = $day;
  1515. $this->showDayPicker = false;
  1516. $this->updatedSelectedDay($day);
  1517. }
  1518. public function toggleDayPicker()
  1519. {
  1520. $this->showDayPicker = !$this->showDayPicker;
  1521. }
  1522. public function selectToday()
  1523. {
  1524. $today = date('Y-m-d');
  1525. $this->selectDay($today);
  1526. }
  1527. public function selectYesterday()
  1528. {
  1529. $yesterday = date('Y-m-d', strtotime('-1 day'));
  1530. $this->selectDay($yesterday);
  1531. }
  1532. // Updated month methods to work with both custom month and day
  1533. public function updatedSelectedMonth($value)
  1534. {
  1535. if (!empty($value)) {
  1536. $this->selectedPeriod = 'MESE_PERSONALIZZATO';
  1537. $firstDay = date('Y-m-01', strtotime($value . '-01'));
  1538. $lastDay = date('Y-m-t', strtotime($value . '-01'));
  1539. $this->fromDate = $firstDay;
  1540. $this->toDate = $lastDay;
  1541. // $this->applyFilters();
  1542. }
  1543. }
  1544. public function selectMonth($month)
  1545. {
  1546. $this->selectedMonth = $month;
  1547. $this->showMonthPicker = false;
  1548. $this->updatedSelectedMonth($month);
  1549. }
  1550. public function toggleMonthPicker()
  1551. {
  1552. $this->showMonthPicker = !$this->showMonthPicker;
  1553. }
  1554. private function exportExcel($records)
  1555. {
  1556. $startTime = microtime(true);
  1557. $spreadsheet = new Spreadsheet();
  1558. $activeWorksheet = $spreadsheet->getActiveSheet();
  1559. $activeWorksheet->setCellValue('A1', "Data");
  1560. $activeWorksheet->setCellValue('B1', "Tipologia");
  1561. $activeWorksheet->setCellValue('C1', "Causale");
  1562. $activeWorksheet->setCellValue('D1', "Nominativo");
  1563. $activeWorksheet->setCellValue('E1', "Stato");
  1564. $activeWorksheet->setCellValue('F1', "Entrata");
  1565. $activeWorksheet->setCellValue('G1', "Uscita");
  1566. $activeWorksheet->setCellValue('H1', "Origine");
  1567. $activeWorksheet->setCellValue('I1', "Destinazione");
  1568. $activeWorksheet->setCellValue('J1', "Metodo di pagamento");
  1569. $activeWorksheet->getStyle('A1:J1')->getFill()
  1570. ->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)
  1571. ->getStartColor()->setARGB('FF0C6197');
  1572. $activeWorksheet->getStyle('A1:J1')->getFont()->getColor()->setARGB('FFFFFFFF');
  1573. $idx = 2;
  1574. foreach ($records as $record) {
  1575. if ($record->date != '') {
  1576. $isMoveIn = $record->type === 'MOVE_IN';
  1577. $isMoveOut = $record->type === 'MOVE_OUT';
  1578. $isIn = $record->type === 'IN';
  1579. $isOut = $record->type === 'OUT';
  1580. $activeWorksheet->setCellValue('A' . $idx, date("d/m/Y", strtotime($record->date)));
  1581. // Tipologia
  1582. $activeWorksheet->setCellValue(
  1583. 'B' . $idx,
  1584. ($isMoveIn || $isMoveOut) ? '' : ($record->commercial ? 'Commerciale' : 'Non commerciale')
  1585. );
  1586. // Causale
  1587. $activeWorksheet->setCellValue('C' . $idx, $record->causal_name);
  1588. // Nominativo
  1589. if (isset($record->member)) {
  1590. $nominativo = $record->member->first_name . ' ' . $record->member->last_name;
  1591. } elseif (isset($record->supplier)) {
  1592. $nominativo = $record->supplier->name;
  1593. } else {
  1594. $nominativo = '';
  1595. }
  1596. $activeWorksheet->setCellValue('D' . $idx, $nominativo);
  1597. // Stato
  1598. $activeWorksheet->setCellValue('E' . $idx, $record->deleted ? 'Annullata' : '');
  1599. // Entrata
  1600. $activeWorksheet->setCellValue(
  1601. 'F' . $idx,
  1602. ($isIn || $isMoveIn) ? formatPrice($record->amount) : ''
  1603. );
  1604. // Uscita
  1605. $activeWorksheet->setCellValue(
  1606. 'G' . $idx,
  1607. ($isOut || $isMoveOut) ? formatPrice($record->amount) : ''
  1608. );
  1609. // Origine
  1610. $activeWorksheet->setCellValue(
  1611. 'H' . $idx,
  1612. ($isOut || $isMoveOut) ? ($record->origin ?? '') : ''
  1613. );
  1614. // Destinazione
  1615. $activeWorksheet->setCellValue(
  1616. 'I' . $idx,
  1617. ($isIn || $isMoveIn) ? ($record->destination ?? '') : ''
  1618. );
  1619. // Metodo di pagamento
  1620. $activeWorksheet->setCellValue(
  1621. 'J' . $idx,
  1622. ($isMoveIn || $isMoveOut) ? '' : ($record->payment_method->name ?? '')
  1623. );
  1624. } else {
  1625. // RIGA TOTALI
  1626. $activeWorksheet->setCellValue('A' . $idx, "Totali");
  1627. $activeWorksheet->setCellValue('F' . $idx, formatPrice($record->total_in));
  1628. $activeWorksheet->setCellValue('G' . $idx, formatPrice($record->total_out));
  1629. }
  1630. $idx++;
  1631. }
  1632. $activeWorksheet->getColumnDimension('A')->setWidth(10);
  1633. $activeWorksheet->getColumnDimension('B')->setWidth(30);
  1634. $activeWorksheet->getColumnDimension('C')->setWidth(30);
  1635. $activeWorksheet->getColumnDimension('D')->setWidth(30);
  1636. $activeWorksheet->getColumnDimension('E')->setWidth(10);
  1637. $activeWorksheet->getColumnDimension('F')->setWidth(10);
  1638. $activeWorksheet->getColumnDimension('G')->setWidth(10);
  1639. $activeWorksheet->getColumnDimension('H')->setWidth(20);
  1640. $activeWorksheet->getColumnDimension('I')->setWidth(20);
  1641. $activeWorksheet->getColumnDimension('J')->setWidth(30);
  1642. $activeWorksheet->getStyle('A' . ($idx - 1) . ':J' . ($idx - 1))->getFont()->setBold(true);
  1643. $filename = 'prima_nota_' . date("YmdHis") . '.xlsx';
  1644. Log::info('exportWithData: Preparing to save file', [
  1645. 'filename' => $filename,
  1646. //'total_processing_time' => microtime(true) - $startTime,
  1647. 'memory_before_save' => memory_get_usage(true)
  1648. ]);
  1649. try {
  1650. $currentClient = session('currentClient', 'default');
  1651. $tempPath = sys_get_temp_dir() . '/' . $filename;
  1652. $writer = new Xlsx($spreadsheet);
  1653. $writer->save($tempPath);
  1654. unset($spreadsheet, $activeWorksheet, $writer);
  1655. gc_collect_cycles();
  1656. Log::info('exportWithData: Uploading to S3');
  1657. $disk = Storage::disk('s3');
  1658. $s3Path = $currentClient . '/prima_nota/' . $filename;
  1659. $primaNotaFolderPath = $currentClient . '/prima_nota/.gitkeep';
  1660. if (!$disk->exists($primaNotaFolderPath)) {
  1661. $disk->put($primaNotaFolderPath, '');
  1662. }
  1663. $uploadStart = microtime(true);
  1664. $fileContent = file_get_contents($tempPath);
  1665. $uploaded = $disk->put($s3Path, $fileContent, 'private');
  1666. $uploadTime = microtime(true) - $uploadStart;
  1667. if (!$uploaded) {
  1668. throw new \Exception('Failed to upload file to Wasabi S3');
  1669. }
  1670. Log::info("Export completed successfully", [
  1671. 'client' => $currentClient,
  1672. 'path' => $s3Path,
  1673. 'file_size' => filesize($tempPath),
  1674. 'records_processed' => $recordsProcessed,
  1675. 'upload_time' => $uploadTime,
  1676. 'total_time' => microtime(true) - $startTime,
  1677. 'memory_peak' => memory_get_peak_usage(true)
  1678. ]);
  1679. if (file_exists($tempPath)) {
  1680. unlink($tempPath);
  1681. }
  1682. $downloadUrl = $disk->temporaryUrl($s3Path, now()->addHour());
  1683. return redirect($downloadUrl);
  1684. } catch (\Exception $e) {
  1685. Log::error('Export S3 error - falling back to local', [
  1686. 'error' => $e->getMessage(),
  1687. 'trace' => $e->getTraceAsString(),
  1688. 'client' => session('currentClient', 'unknown'),
  1689. 'filename' => $filename,
  1690. 'records_processed' => $recordsProcessed ?? 0,
  1691. 'time_elapsed' => microtime(true) - $startTime
  1692. ]);
  1693. // Fallback logic remains the same...
  1694. $currentClient = session('currentClient', 'default');
  1695. $clientFolder = storage_path('app/prima_nota/' . $currentClient);
  1696. if (!is_dir($clientFolder)) {
  1697. mkdir($clientFolder, 0755, true);
  1698. Log::info("Created local client prima_nota folder: {$clientFolder}");
  1699. }
  1700. $localPath = $clientFolder . '/' . $filename;
  1701. if (isset($tempPath) && file_exists($tempPath)) {
  1702. rename($tempPath, $localPath);
  1703. } else {
  1704. $writer = new Xlsx($spreadsheet);
  1705. $writer->save($localPath);
  1706. unset($spreadsheet, $activeWorksheet, $writer);
  1707. }
  1708. gc_collect_cycles();
  1709. Log::warning("Export saved locally due to S3 error", [
  1710. 'client' => $currentClient,
  1711. 'local_path' => $localPath,
  1712. 'error' => $e->getMessage()
  1713. ]);
  1714. session()->flash('warning', 'File salvato localmente a causa di un errore del cloud storage.');
  1715. return response()->download($localPath)->deleteFileAfterSend();
  1716. }
  1717. }
  1718. }