Record.php 67 KB

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