Record.php 19 KB

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