Record.php 53 KB

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