Record.php 57 KB

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