Record.php 56 KB

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