Record.php 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634
  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. class Record extends Component
  12. {
  13. public $records, $dataId, $totals;
  14. public $in;
  15. public $out;
  16. public $payments = [];
  17. public $fromDate;
  18. public $toDate;
  19. // Add these properties for the actual filtering
  20. public $appliedFromDate;
  21. public $appliedToDate;
  22. public $filterCausals = null;
  23. public $filterMember = null;
  24. // Add this property to track filtering state
  25. public $isFiltering = false;
  26. public array $recordDatas = [];
  27. public array $labels = [];
  28. public array $causals = [];
  29. public $members = array();
  30. public function hydrate()
  31. {
  32. $this->emit('load-select');
  33. }
  34. public function mount()
  35. {
  36. $this->fromDate = date("Y-m-d");
  37. $this->toDate = date("Y-m-d");
  38. // Initialize applied dates to current date
  39. $this->appliedFromDate = date("Y-m-d");
  40. $this->appliedToDate = date("Y-m-d");
  41. $this->getCausals(\App\Models\Causal::select('id', 'name')->where('parent_id', null)->get(), 0);
  42. $this->members = \App\Models\Member::select(['id', 'first_name', 'last_name', 'fiscal_code'])->orderBy('last_name')->orderBy('first_name')->get();
  43. $this->payments = \App\Models\PaymentMethod::select('id', 'name', 'type')->where('enabled', true)->where('money', false)->get();
  44. }
  45. // Add this method to handle manual filtering
  46. public function applyFilters()
  47. {
  48. // Set filtering state to true
  49. $this->isFiltering = true;
  50. $this->appliedFromDate = $this->fromDate;
  51. $this->appliedToDate = $this->toDate;
  52. // Process the data
  53. $this->render();
  54. // Reset filtering state
  55. $this->isFiltering = false;
  56. // Emit event to update any JavaScript components if needed
  57. $this->emit('filters-applied');
  58. }
  59. public function getCausals($records, $indentation)
  60. {
  61. foreach ($records as $record) {
  62. $this->causals[] = array('id' => $record->id, 'name' => $record->getTree(), 'text' => $record->getTree(), 'level' => $indentation);
  63. if (count($record->childs))
  64. $this->getCausals($record->childs, $indentation + 1);
  65. }
  66. }
  67. public function getMonth($m)
  68. {
  69. $ret = '';
  70. switch ($m) {
  71. case 1:
  72. $ret = 'Gennaio';
  73. break;
  74. case 2:
  75. $ret = 'Febbraio';
  76. break;
  77. case 3:
  78. $ret = 'Marzo';
  79. break;
  80. case 4:
  81. $ret = 'Aprile';
  82. break;
  83. case 5:
  84. $ret = 'Maggio';
  85. break;
  86. case 6:
  87. $ret = 'Giugno';
  88. break;
  89. case 7:
  90. $ret = 'Luglio';
  91. break;
  92. case 8:
  93. $ret = 'Agosto';
  94. break;
  95. case 9:
  96. $ret = 'Settembre';
  97. break;
  98. case 10:
  99. $ret = 'Ottobre';
  100. break;
  101. case 11:
  102. $ret = 'Novembre';
  103. break;
  104. case 12:
  105. $ret = 'Dicembre';
  106. break;
  107. default:
  108. $ret = '';
  109. break;
  110. }
  111. return $ret;
  112. }
  113. public function render()
  114. {
  115. $month = 0;
  116. $year = 0;
  117. $this->records = array();
  118. $this->totals = array();
  119. $exclude_from_records = \App\Models\Member::where('exclude_from_records', true)->pluck('id')->toArray();
  120. // Use applied dates instead of current dates for filtering
  121. $datas = \App\Models\Record::with('member', 'supplier', 'payment_method')
  122. ->select('records.*', 'records_rows.*') // Ensure all columns are selected
  123. ->join('records_rows', 'records.id', '=', 'records_rows.record_id')
  124. ->whereBetween('date', [$this->appliedFromDate, $this->appliedToDate])
  125. ->where(function ($query) {
  126. $query->where('type', 'OUT')
  127. ->orWhere(function ($query) {
  128. $query->where('records.corrispettivo_fiscale', true)
  129. ->orWhere('records.commercial', false);
  130. });
  131. })
  132. ->where(function ($query) use ($exclude_from_records) {
  133. $query->where('type', 'OUT')
  134. ->orWhere(function ($subquery) use ($exclude_from_records) {
  135. $subquery->whereNotIn('member_id', $exclude_from_records);
  136. });
  137. });
  138. if ($this->filterCausals != null && sizeof($this->filterCausals) > 0) {
  139. $causals = array();
  140. foreach ($this->filterCausals as $z) {
  141. $causals[] = $z;
  142. $childs = \App\Models\Causal::where('parent_id', $z)->get();
  143. foreach ($childs as $c) {
  144. $causals[] = $c->id;
  145. $childsX = \App\Models\Causal::where('parent_id', $c->id)->get();
  146. foreach ($childsX as $cX) {
  147. $causals[] = $cX->id;
  148. }
  149. }
  150. }
  151. $datas->whereIn('causal_id', $causals);
  152. }
  153. if ($this->filterMember != null && $this->filterMember > 0) {
  154. $datas->where('member_id', $this->filterMember);
  155. }
  156. $datas = $datas->orderBy('date', 'ASC')
  157. ->orderBy('records.created_at', 'ASC')
  158. ->orderBy('records_rows.id', 'ASC') // Important to maintain row order
  159. ->get();
  160. // Group data by date, type (commercial/non-commercial), payment method, and type (IN/OUT)
  161. $groupedData = [];
  162. $causalsCount = []; // Track how many different causals per group
  163. $nominativi = []; // Track nominativi for each group
  164. foreach ($datas as $idx => $data) {
  165. $causalCheck = \App\Models\Causal::findOrFail($data->causal_id);
  166. $paymentCheck = $data->payment_method->money;
  167. if (!$paymentCheck && ($causalCheck->no_first == null || !$causalCheck->no_first)) {
  168. if (!$data->deleted) {
  169. $amount = $data->amount;
  170. $amount += getVatValue($amount, $data->vat_id);
  171. } else {
  172. $amount = $data->amount;
  173. }
  174. // Determine the type (commercial or non-commercial)
  175. $typeLabel = $data->commercial ? 'Commerciale' : 'Non Commerciale';
  176. // Get nominativo
  177. $nominativo = '';
  178. if ($data->type == "IN") {
  179. if ($data->member) {
  180. $nominativo = $data->member->last_name . " " . $data->member->first_name;
  181. }
  182. } else {
  183. if ($data->supplier) {
  184. $nominativo = $data->supplier->name;
  185. }
  186. }
  187. // Create grouping key: date + type + payment_method + IN/OUT + nominativo
  188. $groupKey = $data->date . '|' . $typeLabel . '|' . $data->payment_method->name . '|' . $data->type . '|' . $nominativo;
  189. // Initialize group if not exists
  190. if (!isset($groupedData[$groupKey])) {
  191. $groupedData[$groupKey] = [
  192. 'date' => $data->date,
  193. 'type_label' => $typeLabel,
  194. 'payment_method' => $data->payment_method->name,
  195. 'transaction_type' => $data->type,
  196. 'nominativo' => $nominativo,
  197. 'amount' => 0,
  198. 'deleted' => false,
  199. 'causals' => [],
  200. 'notes' => []
  201. ];
  202. $causalsCount[$groupKey] = [];
  203. $nominativi[$groupKey] = $nominativo;
  204. }
  205. // Add amount to group
  206. $groupedData[$groupKey]['amount'] += $amount;
  207. // Track causals for this group
  208. $causalsCount[$groupKey][$causalCheck->getTree()] = true;
  209. // Collect notes
  210. if (!empty($data->note)) {
  211. $groupedData[$groupKey]['notes'][] = $data->note;
  212. }
  213. // Track if any record in this group is deleted
  214. if ($data->deleted) {
  215. $groupedData[$groupKey]['deleted'] = true;
  216. }
  217. }
  218. }
  219. // Convert grouped data to records format
  220. foreach ($groupedData as $groupKey => $group) {
  221. $causalsInGroup = array_keys($causalsCount[$groupKey]);
  222. // Always show type in causale column
  223. $causalDisplay = $group['type_label']; // Always Commerciale or Non Commerciale
  224. // Determine detail display
  225. if (count($causalsInGroup) > 1) {
  226. $detailDisplay = 'Varie|' . implode('|', $causalsInGroup); // Store causals for popup
  227. } else {
  228. $detailDisplay = $causalsInGroup[0]; // Show single causal
  229. }
  230. // Create record key with nominativo
  231. $recordKey = $group['date'] . "§" . $causalDisplay . "§" . $group['nominativo'] . "§" . $detailDisplay . "§" . ($group['deleted'] ? 'DELETED' : '') . "§";
  232. // Initialize records structure
  233. if (!isset($this->records[$recordKey][$group['payment_method']][$group['transaction_type']])) {
  234. $this->records[$recordKey][$group['payment_method']][$group['transaction_type']] = 0;
  235. }
  236. // Add amount to records
  237. $this->records[$recordKey][$group['payment_method']][$group['transaction_type']] += $group['amount'];
  238. // Initialize totals if needed
  239. if (!isset($this->totals[$group['payment_method']])) {
  240. $this->totals[$group['payment_method']]["IN"] = 0;
  241. $this->totals[$group['payment_method']]["OUT"] = 0;
  242. }
  243. // Update totals if not deleted
  244. if (!$group['deleted'])
  245. $this->totals[$group['payment_method']][$group['transaction_type']] += $group['amount'];
  246. }
  247. return view('livewire.records');
  248. }
  249. private function getLabels($fromDate, $toDate)
  250. {
  251. $begin = new DateTime($fromDate);
  252. $end = new DateTime($toDate);
  253. $interval = DateInterval::createFromDateString('1 day');
  254. $date_range = new DatePeriod($begin, $interval, $end);
  255. foreach ($date_range as $date) {
  256. $labels[] = $date->format('d/M');
  257. }
  258. return $labels;
  259. }
  260. private function getRecordData($type, $fromDate, $toDate)
  261. {
  262. $data = [];
  263. $begin = new DateTime($fromDate);
  264. $end = new DateTime($toDate);
  265. $interval = DateInterval::createFromDateString('1 day');
  266. $date_range = new DatePeriod($begin, $interval, $end);
  267. foreach ($date_range as $date) {
  268. if ($type == 'IN') {
  269. $found = false;
  270. foreach ($this->in as $in) {
  271. if (date("Y-m-d", strtotime($in->date)) == $date->format('Y-m-d')) {
  272. $data[] = number_format($in->total, 0, "", "");
  273. $found = true;
  274. }
  275. }
  276. if (!$found)
  277. $data[] = 0;
  278. }
  279. if ($type == 'OUT') {
  280. $found = false;
  281. foreach ($this->out as $out) {
  282. if (date("Y-m-d", strtotime($out->date)) == $date->format('Y-m-d')) {
  283. $data[] = number_format($out->total, 0, "", "");
  284. $found = true;
  285. }
  286. }
  287. if (!$found)
  288. $data[] = 0;
  289. }
  290. }
  291. return $data;
  292. }
  293. public function export()
  294. {
  295. ini_set('memory_limit', '512M');
  296. gc_enable();
  297. $letters = array('F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'AA');
  298. $spreadsheet = new Spreadsheet();
  299. $activeWorksheet = $spreadsheet->getActiveSheet();
  300. $activeWorksheet->setCellValue('A1', "Data");
  301. $activeWorksheet->setCellValue('B1', "Causale");
  302. $activeWorksheet->setCellValue('C1', "Dettaglio");
  303. $activeWorksheet->setCellValue('D1', "Nominativo");
  304. $activeWorksheet->setCellValue('E1', "Stato");
  305. $idx = 0;
  306. foreach ($this->payments as $p) {
  307. if ($idx >= count($letters)) {
  308. break;
  309. }
  310. $activeWorksheet->setCellValue($letters[$idx] . '1', $p->name);
  311. $idx++;
  312. if ($idx >= count($letters)) {
  313. break;
  314. }
  315. $activeWorksheet->mergeCells($letters[$idx] . '1:' . $letters[$idx] . '1');
  316. $idx++;
  317. }
  318. $idx = 0;
  319. $activeWorksheet->setCellValue('A2', "");
  320. $activeWorksheet->setCellValue('B2', "");
  321. $activeWorksheet->setCellValue('C2', "");
  322. $activeWorksheet->setCellValue('D2', "");
  323. $activeWorksheet->setCellValue('E2', "");
  324. foreach ($this->payments as $p) {
  325. if ($p->type == 'ALL') {
  326. if ($idx >= count($letters)) {
  327. break;
  328. }
  329. $activeWorksheet->setCellValue($letters[$idx] . '2', "Entrate");
  330. $idx++;
  331. $activeWorksheet->setCellValue($letters[$idx] . '2', "Uscite");
  332. $idx++;
  333. } elseif ($p->type == 'IN') {
  334. if ($idx >= count($letters)) {
  335. break;
  336. }
  337. $activeWorksheet->setCellValue($letters[$idx] . '2', "Entrate");
  338. $idx++;
  339. $activeWorksheet->setCellValue($letters[$idx] . '2', "");
  340. $idx++;
  341. } elseif ($p->type == 'OUT') {
  342. if ($idx >= count($letters)) {
  343. break;
  344. }
  345. $activeWorksheet->setCellValue($letters[$idx] . '2', "");
  346. $idx++;
  347. $activeWorksheet->setCellValue($letters[$idx] . '2', "Uscite");
  348. $idx++;
  349. }
  350. }
  351. $activeWorksheet->getStyle('A1:Q1')->getFont()->setBold(true);
  352. $activeWorksheet->getStyle('A2:Q2')->getFont()->setBold(true);
  353. $count = 3;
  354. $batchSize = 1000;
  355. $recordsProcessed = 0;
  356. $totalRecords = count($this->records);
  357. $recordsArray = array_chunk($this->records, $batchSize, true);
  358. foreach ($recordsArray as $recordsBatch) {
  359. foreach ($recordsBatch as $causal => $record) {
  360. $check = $causal; // No need to handle prefix anymore
  361. $parts = explode("§", $check);
  362. $d = $parts[0] ?? '';
  363. $c = $parts[1] ?? '';
  364. $j = $parts[2] ?? ''; // Nominativo
  365. $det = $parts[3] ?? '';
  366. $deleted = $parts[4] ?? '';
  367. // Handle "Varie" case for export - show actual causals instead of "Varie"
  368. $detailParts = explode('|', $det);
  369. $exportDetail = count($detailParts) > 1 ? implode(', ', array_slice($detailParts, 1)) : $det;
  370. $activeWorksheet->setCellValue('A' . $count, !empty($d) ? date("d/m/Y", strtotime($d)) : '');
  371. $activeWorksheet->setCellValue('B' . $count, $c);
  372. $activeWorksheet->setCellValue('C' . $count, $exportDetail); // Show all causals in export
  373. $activeWorksheet->setCellValue('D' . $count, $j); // Nominativo
  374. $stato = ($deleted === 'DELETED') ? 'ANNULLATA' : '';
  375. $activeWorksheet->setCellValue('E' . $count, $stato);
  376. if ($stato === 'ANNULLATA') {
  377. $activeWorksheet->getStyle('E' . $count)->getFont()->getColor()->setARGB('FFFF0000');
  378. }
  379. $idx = 0;
  380. foreach ($this->payments as $p) {
  381. if ($idx >= count($letters) - 1) {
  382. break;
  383. }
  384. if (isset($record[$p->name])) {
  385. $inValue = isset($record[$p->name]["IN"]) ? formatPrice($record[$p->name]["IN"]) : "";
  386. $outValue = isset($record[$p->name]["OUT"]) ? formatPrice($record[$p->name]["OUT"]) : "";
  387. $activeWorksheet->setCellValue($letters[$idx] . $count, $inValue);
  388. $idx++;
  389. $activeWorksheet->setCellValue($letters[$idx] . $count, $outValue);
  390. $idx++;
  391. } else {
  392. $activeWorksheet->setCellValue($letters[$idx] . $count, "");
  393. $idx++;
  394. $activeWorksheet->setCellValue($letters[$idx] . $count, "");
  395. $idx++;
  396. }
  397. }
  398. $count++;
  399. $recordsProcessed++;
  400. if ($recordsProcessed % 500 === 0) {
  401. gc_collect_cycles();
  402. }
  403. }
  404. unset($recordsBatch);
  405. gc_collect_cycles();
  406. }
  407. $count++;
  408. $idx = 0;
  409. $activeWorksheet->setCellValue('A' . $count, 'Totale');
  410. $activeWorksheet->setCellValue('B' . $count, '');
  411. $activeWorksheet->setCellValue('C' . $count, '');
  412. $activeWorksheet->setCellValue('D' . $count, '');
  413. $activeWorksheet->setCellValue('E' . $count, '');
  414. foreach ($this->payments as $p) {
  415. if ($idx >= count($letters) - 1) {
  416. break;
  417. }
  418. if (isset($this->totals[$p->name])) {
  419. if ($p->type == 'ALL') {
  420. $activeWorksheet->setCellValue($letters[$idx] . $count, formatPrice($this->totals[$p->name]["IN"] ?? 0));
  421. $idx++;
  422. $activeWorksheet->setCellValue($letters[$idx] . $count, formatPrice($this->totals[$p->name]["OUT"] ?? 0));
  423. $idx++;
  424. } elseif ($p->type == 'IN') {
  425. $activeWorksheet->setCellValue($letters[$idx] . $count, formatPrice($this->totals[$p->name]["IN"] ?? 0));
  426. $idx++;
  427. $activeWorksheet->setCellValue($letters[$idx] . $count, "");
  428. $idx++;
  429. } elseif ($p->type == 'OUT') {
  430. $activeWorksheet->setCellValue($letters[$idx] . $count, "");
  431. $idx++;
  432. $activeWorksheet->setCellValue($letters[$idx] . $count, formatPrice($this->totals[$p->name]["OUT"] ?? 0));
  433. $idx++;
  434. }
  435. } else {
  436. if ($p->type == 'ALL') {
  437. $activeWorksheet->setCellValue($letters[$idx] . $count, "0");
  438. $idx++;
  439. $activeWorksheet->setCellValue($letters[$idx] . $count, "0");
  440. $idx++;
  441. } elseif ($p->type == 'IN') {
  442. $activeWorksheet->setCellValue($letters[$idx] . $count, "0");
  443. $idx++;
  444. $activeWorksheet->setCellValue($letters[$idx] . $count, "");
  445. $idx++;
  446. } elseif ($p->type == 'OUT') {
  447. $activeWorksheet->setCellValue($letters[$idx] . $count, "");
  448. $idx++;
  449. $activeWorksheet->setCellValue($letters[$idx] . $count, "0");
  450. $idx++;
  451. }
  452. }
  453. }
  454. $activeWorksheet->getStyle('A' . $count . ':Q' . $count)->getFont()->setBold(true);
  455. $activeWorksheet->getColumnDimension('A')->setWidth(20);
  456. $activeWorksheet->getColumnDimension('B')->setWidth(40);
  457. $activeWorksheet->getColumnDimension('C')->setWidth(40);
  458. $activeWorksheet->getColumnDimension('D')->setWidth(40);
  459. $activeWorksheet->getColumnDimension('E')->setWidth(20);
  460. foreach ($letters as $l) {
  461. $activeWorksheet->getColumnDimension($l)->setWidth(20);
  462. }
  463. $filename = 'prima_nota_' . date("YmdHis") . '.xlsx';
  464. try {
  465. $currentClient = session('currentClient', 'default');
  466. $tempPath = sys_get_temp_dir() . '/' . $filename;
  467. $writer = new Xlsx($spreadsheet);
  468. $writer->save($tempPath);
  469. unset($spreadsheet, $activeWorksheet, $writer);
  470. gc_collect_cycles();
  471. $disk = Storage::disk('s3');
  472. $s3Path = $currentClient . '/prima_nota/' . $filename;
  473. $primaNotaFolderPath = $currentClient . '/prima_nota/.gitkeep';
  474. if (!$disk->exists($primaNotaFolderPath)) {
  475. $disk->put($primaNotaFolderPath, '');
  476. Log::info("Created prima_nota folder for client: {$currentClient}");
  477. }
  478. $fileContent = file_get_contents($tempPath);
  479. $uploaded = $disk->put($s3Path, $fileContent, 'private');
  480. if (!$uploaded) {
  481. throw new \Exception('Failed to upload file to Wasabi S3');
  482. }
  483. Log::info("Prima Nota exported to Wasabi", [
  484. 'client' => $currentClient,
  485. 'path' => $s3Path,
  486. 'size' => filesize($tempPath),
  487. 'records_processed' => $recordsProcessed
  488. ]);
  489. if (file_exists($tempPath)) {
  490. unlink($tempPath);
  491. }
  492. $downloadUrl = $disk->temporaryUrl($s3Path, now()->addHour());
  493. return redirect($downloadUrl);
  494. } catch (\Exception $e) {
  495. Log::error('Error exporting Prima Nota to Wasabi S3', [
  496. 'error' => $e->getMessage(),
  497. 'client' => session('currentClient', 'unknown'),
  498. 'filename' => $filename,
  499. 'records_processed' => $recordsProcessed ?? 0
  500. ]);
  501. $currentClient = session('currentClient', 'default');
  502. $clientFolder = storage_path('app/prima_nota/' . $currentClient);
  503. if (!is_dir($clientFolder)) {
  504. mkdir($clientFolder, 0755, true);
  505. Log::info("Created local client prima_nota folder: {$clientFolder}");
  506. }
  507. $localPath = $clientFolder . '/' . $filename;
  508. if (isset($tempPath) && file_exists($tempPath)) {
  509. rename($tempPath, $localPath);
  510. } else {
  511. $writer = new Xlsx($spreadsheet);
  512. $writer->save($localPath);
  513. unset($spreadsheet, $activeWorksheet, $writer);
  514. }
  515. gc_collect_cycles();
  516. Log::warning("Prima Nota saved locally due to S3 error", [
  517. 'client' => $currentClient,
  518. 'local_path' => $localPath,
  519. 'error' => $e->getMessage()
  520. ]);
  521. session()->flash('warning', 'File salvato localmente a causa di un errore del cloud storage.');
  522. return response()->download($localPath)->deleteFileAfterSend();
  523. }
  524. }
  525. }