Record.php 66 KB

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