Record.php 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941
  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 $appliedFromDate;
  20. public $appliedToDate;
  21. public $exportFromDate;
  22. public $exportToDate;
  23. public $isExporting = false;
  24. public $selectedPeriod = 'OGGI';
  25. public $filterCausals = null;
  26. public $filterMember = null;
  27. public $isFiltering = false;
  28. public array $recordDatas = [];
  29. public array $labels = [];
  30. public array $causals = [];
  31. public $members = array();
  32. public function hydrate()
  33. {
  34. $this->emit('load-select');
  35. }
  36. public function mount()
  37. {
  38. $this->fromDate = date("Y-m-d");
  39. $this->toDate = date("Y-m-d");
  40. $this->appliedFromDate = date("Y-m-d");
  41. $this->appliedToDate = date("Y-m-d");
  42. $this->exportFromDate = date("Y-m-d");
  43. $this->exportToDate = date("Y-m-d");
  44. $this->getCausals(\App\Models\Causal::select('id', 'name')->where('parent_id', null)->get(), 0);
  45. $this->members = \App\Models\Member::select(['id', 'first_name', 'last_name', 'fiscal_code'])->orderBy('last_name')->orderBy('first_name')->get();
  46. $this->payments = \App\Models\PaymentMethod::select('id', 'name', 'type')->where('enabled', true)->where('money', false)->get();
  47. }
  48. private function generateExportData($fromDate, $toDate)
  49. {
  50. $exportRecords = array();
  51. $exportTotals = array();
  52. $exclude_from_records = \App\Models\Member::where('exclude_from_records', true)->pluck('id')->toArray();
  53. $datas = \App\Models\Record::with('member', 'supplier', 'payment_method')
  54. ->select(
  55. 'records.*',
  56. 'records_rows.id as row_id',
  57. 'records_rows.record_id',
  58. 'records_rows.causal_id',
  59. 'records_rows.amount',
  60. 'records_rows.note',
  61. 'records_rows.when',
  62. 'records_rows.vat_id',
  63. 'records_rows.imponibile',
  64. 'records_rows.aliquota_iva',
  65. 'records_rows.imposta',
  66. 'records_rows.divisa',
  67. 'records_rows.numero_linea',
  68. 'records_rows.prezzo_unitario',
  69. 'records_rows.quantita',
  70. 'records_rows.created_at as row_created_at',
  71. 'records_rows.updated_at as row_updated_at'
  72. )
  73. ->join('records_rows', 'records.id', '=', 'records_rows.record_id')
  74. ->whereBetween('date', [$fromDate, $toDate])
  75. ->where(function ($query) {
  76. $query->where('type', 'OUT')
  77. ->orWhere(function ($query) {
  78. $query->where('records.corrispettivo_fiscale', true)
  79. ->orWhere('records.commercial', false);
  80. });
  81. })
  82. ->where(function ($query) use ($exclude_from_records) {
  83. $query->where('type', 'OUT')
  84. ->orWhere(function ($subquery) use ($exclude_from_records) {
  85. $subquery->whereNotIn('member_id', $exclude_from_records);
  86. });
  87. });
  88. if ($this->filterCausals != null && sizeof($this->filterCausals) > 0) {
  89. $causals = array();
  90. foreach ($this->filterCausals as $z) {
  91. $causals[] = $z;
  92. $childs = \App\Models\Causal::where('parent_id', $z)->get();
  93. foreach ($childs as $c) {
  94. $causals[] = $c->id;
  95. $childsX = \App\Models\Causal::where('parent_id', $c->id)->get();
  96. foreach ($childsX as $cX) {
  97. $causals[] = $cX->id;
  98. }
  99. }
  100. }
  101. $datas->whereIn('causal_id', $causals);
  102. }
  103. if ($this->filterMember != null && $this->filterMember > 0) {
  104. $datas->where('member_id', $this->filterMember);
  105. }
  106. $datas = $datas->orderBy('date', 'ASC')
  107. ->orderBy('records.created_at', 'ASC')
  108. ->orderBy('records_rows.id', 'ASC')
  109. ->get();
  110. $groupedData = [];
  111. $causalsCount = [];
  112. foreach ($datas as $idx => $data) {
  113. $causalCheck = \App\Models\Causal::findOrFail($data->causal_id);
  114. $paymentCheck = $data->payment_method->money;
  115. if (!$paymentCheck && ($causalCheck->no_first == null || !$causalCheck->no_first)) {
  116. if (!$data->deleted) {
  117. $amount = $data->amount;
  118. $amount += getVatValue($amount, $data->vat_id);
  119. } else {
  120. $amount = $data->amount;
  121. }
  122. $isCommercial = ($data->commercial == 1 || $data->commercial === '1' || $data->commercial === true);
  123. $typeLabel = $isCommercial ? 'Commerciale' : 'Non Commerciale';
  124. $nominativo = '';
  125. if ($data->type == "IN") {
  126. if ($data->member) {
  127. $nominativo = $data->member->last_name . " " . $data->member->first_name;
  128. }
  129. } else {
  130. if ($data->supplier) {
  131. $nominativo = $data->supplier->name;
  132. }
  133. }
  134. $groupKey = $data->date . '|' . $typeLabel . '|' . $data->payment_method->name . '|' . $data->type . '|' . $nominativo;
  135. if (!isset($groupedData[$groupKey])) {
  136. $groupedData[$groupKey] = [
  137. 'date' => $data->date,
  138. 'type_label' => $typeLabel,
  139. 'payment_method' => $data->payment_method->name,
  140. 'transaction_type' => $data->type,
  141. 'nominativo' => $nominativo,
  142. 'amount' => 0,
  143. 'deleted' => false,
  144. 'causals' => [],
  145. 'notes' => []
  146. ];
  147. $causalsCount[$groupKey] = [];
  148. }
  149. $groupedData[$groupKey]['amount'] += $amount;
  150. $causalsCount[$groupKey][$causalCheck->getTree()] = true;
  151. if (!empty($data->note)) {
  152. $groupedData[$groupKey]['notes'][] = $data->note;
  153. }
  154. if ($data->deleted) {
  155. $groupedData[$groupKey]['deleted'] = true;
  156. }
  157. }
  158. }
  159. foreach ($groupedData as $groupKey => $group) {
  160. $causalsInGroup = array_keys($causalsCount[$groupKey]);
  161. $causalDisplay = $group['type_label'];
  162. if (count($causalsInGroup) > 1) {
  163. $detailDisplay = 'Varie|' . implode('|', $causalsInGroup);
  164. } else {
  165. $detailDisplay = $causalsInGroup[0];
  166. }
  167. $recordKey = $group['date'] . "§" . $causalDisplay . "§" . $group['nominativo'] . "§" . $detailDisplay . "§" . ($group['deleted'] ? 'DELETED' : '') . "§";
  168. if (!isset($exportRecords[$recordKey][$group['payment_method']][$group['transaction_type']])) {
  169. $exportRecords[$recordKey][$group['payment_method']][$group['transaction_type']] = 0;
  170. }
  171. $exportRecords[$recordKey][$group['payment_method']][$group['transaction_type']] += $group['amount'];
  172. if (!isset($exportTotals[$group['payment_method']])) {
  173. $exportTotals[$group['payment_method']]["IN"] = 0;
  174. $exportTotals[$group['payment_method']]["OUT"] = 0;
  175. }
  176. if (!$group['deleted'])
  177. $exportTotals[$group['payment_method']][$group['transaction_type']] += $group['amount'];
  178. }
  179. return $exportRecords;
  180. }
  181. private function generateExportTotals($fromDate, $toDate)
  182. {
  183. $exportTotals = array();
  184. $exclude_from_records = \App\Models\Member::where('exclude_from_records', true)->pluck('id')->toArray();
  185. $datas = \App\Models\Record::with('member', 'supplier', 'payment_method')
  186. ->select(
  187. 'records.*',
  188. 'records_rows.id as row_id',
  189. 'records_rows.record_id',
  190. 'records_rows.causal_id',
  191. 'records_rows.amount',
  192. 'records_rows.note',
  193. 'records_rows.when',
  194. 'records_rows.vat_id',
  195. 'records_rows.imponibile',
  196. 'records_rows.aliquota_iva',
  197. 'records_rows.imposta'
  198. )
  199. ->join('records_rows', 'records.id', '=', 'records_rows.record_id')
  200. ->whereBetween('date', [$fromDate, $toDate])
  201. ->where(function ($query) {
  202. $query->where('type', 'OUT')
  203. ->orWhere(function ($query) {
  204. $query->where('records.corrispettivo_fiscale', true)
  205. ->orWhere('records.commercial', false);
  206. });
  207. })
  208. ->where(function ($query) use ($exclude_from_records) {
  209. $query->where('type', 'OUT')
  210. ->orWhere(function ($subquery) use ($exclude_from_records) {
  211. $subquery->whereNotIn('member_id', $exclude_from_records);
  212. });
  213. });
  214. if ($this->filterCausals != null && sizeof($this->filterCausals) > 0) {
  215. $causals = array();
  216. foreach ($this->filterCausals as $z) {
  217. $causals[] = $z;
  218. $childs = \App\Models\Causal::where('parent_id', $z)->get();
  219. foreach ($childs as $c) {
  220. $causals[] = $c->id;
  221. $childsX = \App\Models\Causal::where('parent_id', $c->id)->get();
  222. foreach ($childsX as $cX) {
  223. $causals[] = $cX->id;
  224. }
  225. }
  226. }
  227. $datas->whereIn('causal_id', $causals);
  228. }
  229. if ($this->filterMember != null && $this->filterMember > 0) {
  230. $datas->where('member_id', $this->filterMember);
  231. }
  232. $datas = $datas->orderBy('date', 'ASC')
  233. ->orderBy('records.created_at', 'ASC')
  234. ->orderBy('records_rows.id', 'ASC')
  235. ->get();
  236. foreach ($datas as $data) {
  237. $causalCheck = \App\Models\Causal::findOrFail($data->causal_id);
  238. $paymentCheck = $data->payment_method->money;
  239. if (!$paymentCheck && ($causalCheck->no_first == null || !$causalCheck->no_first)) {
  240. if (!$data->deleted) {
  241. $amount = $data->amount;
  242. $amount += getVatValue($amount, $data->vat_id);
  243. } else {
  244. $amount = $data->amount;
  245. }
  246. if (!isset($exportTotals[$data->payment_method->name])) {
  247. $exportTotals[$data->payment_method->name]["IN"] = 0;
  248. $exportTotals[$data->payment_method->name]["OUT"] = 0;
  249. }
  250. if (!$data->deleted)
  251. $exportTotals[$data->payment_method->name][$data->type] += $amount;
  252. }
  253. }
  254. return $exportTotals;
  255. }
  256. public function resetFilters()
  257. {
  258. $this->selectedPeriod = 'OGGI';
  259. $this->filterCausals = [];
  260. $this->filterMember = null;
  261. $today = date("Y-m-d");
  262. $this->fromDate = $today;
  263. $this->toDate = $today;
  264. $this->appliedFromDate = $today;
  265. $this->appliedToDate = $today;
  266. $this->emit('filters-reset');
  267. }
  268. public function applyFilters()
  269. {
  270. $this->isFiltering = true;
  271. $this->setPeriodDates();
  272. $this->appliedFromDate = $this->fromDate;
  273. $this->appliedToDate = $this->toDate;
  274. $this->render();
  275. $this->isFiltering = false;
  276. $this->emit('filters-applied');
  277. }
  278. private function setPeriodDates()
  279. {
  280. $today = now();
  281. switch ($this->selectedPeriod) {
  282. case 'OGGI':
  283. $this->fromDate = $today->format('Y-m-d');
  284. $this->toDate = $today->format('Y-m-d');
  285. break;
  286. case 'IERI':
  287. $yesterday = $today->copy()->subDay();
  288. $this->fromDate = $yesterday->format('Y-m-d');
  289. $this->toDate = $yesterday->format('Y-m-d');
  290. break;
  291. case 'MESE CORRENTE':
  292. $this->fromDate = $today->copy()->startOfMonth()->format('Y-m-d');
  293. $this->toDate = $today->copy()->endOfMonth()->format('Y-m-d');
  294. break;
  295. case 'MESE PRECEDENTE':
  296. $lastMonth = $today->copy()->subMonth();
  297. $this->fromDate = $lastMonth->startOfMonth()->format('Y-m-d');
  298. $this->toDate = $lastMonth->endOfMonth()->format('Y-m-d');
  299. break;
  300. case 'ULTIMO TRIMESTRE':
  301. $this->fromDate = $today->copy()->subMonths(3)->format('Y-m-d');
  302. $this->toDate = $today->format('Y-m-d');
  303. break;
  304. case 'ULTIMO QUADRIMESTRE':
  305. $this->fromDate = $today->copy()->subMonths(4)->format('Y-m-d');
  306. $this->toDate = $today->format('Y-m-d');
  307. break;
  308. }
  309. }
  310. public function getCausals($records, $indentation)
  311. {
  312. foreach ($records as $record) {
  313. $this->causals[] = array('id' => $record->id, 'name' => $record->getTree(), 'text' => $record->getTree(), 'level' => $indentation);
  314. if (count($record->childs))
  315. $this->getCausals($record->childs, $indentation + 1);
  316. }
  317. }
  318. public function getMonth($m)
  319. {
  320. $ret = '';
  321. switch ($m) {
  322. case 1:
  323. $ret = 'Gennaio';
  324. break;
  325. case 2:
  326. $ret = 'Febbraio';
  327. break;
  328. case 3:
  329. $ret = 'Marzo';
  330. break;
  331. case 4:
  332. $ret = 'Aprile';
  333. break;
  334. case 5:
  335. $ret = 'Maggio';
  336. break;
  337. case 6:
  338. $ret = 'Giugno';
  339. break;
  340. case 7:
  341. $ret = 'Luglio';
  342. break;
  343. case 8:
  344. $ret = 'Agosto';
  345. break;
  346. case 9:
  347. $ret = 'Settembre';
  348. break;
  349. case 10:
  350. $ret = 'Ottobre';
  351. break;
  352. case 11:
  353. $ret = 'Novembre';
  354. break;
  355. case 12:
  356. $ret = 'Dicembre';
  357. break;
  358. default:
  359. $ret = '';
  360. break;
  361. }
  362. return $ret;
  363. }
  364. public function render()
  365. {
  366. $month = 0;
  367. $year = 0;
  368. $this->records = array();
  369. $this->totals = array();
  370. $exclude_from_records = \App\Models\Member::where('exclude_from_records', true)->pluck('id')->toArray();
  371. $datas = \App\Models\Record::with('member', 'supplier', 'payment_method')
  372. ->select(
  373. 'records.*',
  374. 'records_rows.id as row_id',
  375. 'records_rows.record_id',
  376. 'records_rows.causal_id',
  377. 'records_rows.amount',
  378. 'records_rows.note',
  379. 'records_rows.when',
  380. 'records_rows.vat_id',
  381. 'records_rows.imponibile',
  382. 'records_rows.aliquota_iva',
  383. 'records_rows.imposta'
  384. )
  385. ->join('records_rows', 'records.id', '=', 'records_rows.record_id')
  386. ->whereBetween('date', [$this->appliedFromDate, $this->appliedToDate])
  387. ->where(function ($query) {
  388. $query->where('type', 'OUT')
  389. ->orWhere(function ($query) {
  390. $query->where('records.corrispettivo_fiscale', true)
  391. ->orWhere('records.commercial', false);
  392. });
  393. })
  394. ->where(function ($query) use ($exclude_from_records) {
  395. $query->where('type', 'OUT')
  396. ->orWhere(function ($subquery) use ($exclude_from_records) {
  397. $subquery->whereNotIn('member_id', $exclude_from_records);
  398. });
  399. });
  400. if ($this->filterCausals != null && sizeof($this->filterCausals) > 0) {
  401. $causals = array();
  402. foreach ($this->filterCausals as $z) {
  403. $causals[] = $z;
  404. $childs = \App\Models\Causal::where('parent_id', $z)->get();
  405. foreach ($childs as $c) {
  406. $causals[] = $c->id;
  407. $childsX = \App\Models\Causal::where('parent_id', $c->id)->get();
  408. foreach ($childsX as $cX) {
  409. $causals[] = $cX->id;
  410. }
  411. }
  412. }
  413. $datas->whereIn('causal_id', $causals);
  414. }
  415. if ($this->filterMember != null && $this->filterMember > 0) {
  416. $datas->where('member_id', $this->filterMember);
  417. }
  418. $datas = $datas->orderBy('date', 'ASC')
  419. ->orderBy('records.created_at', 'ASC')
  420. ->orderBy('records_rows.id', 'ASC')
  421. ->get();
  422. $groupedData = [];
  423. $causalsCount = [];
  424. $nominativi = [];
  425. foreach ($datas as $idx => $data) {
  426. $causalCheck = \App\Models\Causal::findOrFail($data->causal_id);
  427. $paymentCheck = $data->payment_method->money;
  428. if (!$paymentCheck && ($causalCheck->no_first == null || !$causalCheck->no_first)) {
  429. if (!$data->deleted) {
  430. $amount = $data->amount;
  431. $amount += getVatValue($amount, $data->vat_id);
  432. } else {
  433. $amount = $data->amount;
  434. }
  435. $isCommercial = ($data->commercial == 1 || $data->commercial === '1' || $data->commercial === true);
  436. $typeLabel = $isCommercial ? 'Commerciale' : 'Non Commerciale';
  437. $nominativo = '';
  438. if ($data->type == "IN") {
  439. if ($data->member) {
  440. $nominativo = $data->member->last_name . " " . $data->member->first_name;
  441. }
  442. } else {
  443. if ($data->supplier) {
  444. $nominativo = $data->supplier->name;
  445. }
  446. }
  447. $groupKey = $data->date . '|' . $typeLabel . '|' . $data->payment_method->name . '|' . $data->type . '|' . $nominativo;
  448. if (!isset($groupedData[$groupKey])) {
  449. $groupedData[$groupKey] = [
  450. 'date' => $data->date,
  451. 'type_label' => $typeLabel,
  452. 'payment_method' => $data->payment_method->name,
  453. 'transaction_type' => $data->type,
  454. 'nominativo' => $nominativo,
  455. 'amount' => 0,
  456. 'deleted' => false,
  457. 'causals' => [],
  458. 'notes' => []
  459. ];
  460. $causalsCount[$groupKey] = [];
  461. $nominativi[$groupKey] = $nominativo;
  462. }
  463. $groupedData[$groupKey]['amount'] += $amount;
  464. $causalsCount[$groupKey][$causalCheck->getTree()] = true;
  465. if (!empty($data->note)) {
  466. $groupedData[$groupKey]['notes'][] = $data->note;
  467. }
  468. if ($data->deleted) {
  469. $groupedData[$groupKey]['deleted'] = true;
  470. }
  471. }
  472. }
  473. foreach ($groupedData as $groupKey => $group) {
  474. $causalsInGroup = array_keys($causalsCount[$groupKey]);
  475. $causalDisplay = $group['type_label'];
  476. if (count($causalsInGroup) > 1) {
  477. $detailDisplay = 'Varie|' . implode('|', $causalsInGroup);
  478. } else {
  479. $detailDisplay = $causalsInGroup[0];
  480. }
  481. $recordKey = $group['date'] . "§" . $causalDisplay . "§" . $group['nominativo'] . "§" . $detailDisplay . "§" . ($group['deleted'] ? 'DELETED' : '') . "§";
  482. if (!isset($this->records[$recordKey][$group['payment_method']][$group['transaction_type']])) {
  483. $this->records[$recordKey][$group['payment_method']][$group['transaction_type']] = 0;
  484. }
  485. $this->records[$recordKey][$group['payment_method']][$group['transaction_type']] += $group['amount'];
  486. if (!isset($this->totals[$group['payment_method']])) {
  487. $this->totals[$group['payment_method']]["IN"] = 0;
  488. $this->totals[$group['payment_method']]["OUT"] = 0;
  489. }
  490. if (!$group['deleted'])
  491. $this->totals[$group['payment_method']][$group['transaction_type']] += $group['amount'];
  492. }
  493. return view('livewire.records');
  494. }
  495. private function getLabels($fromDate, $toDate)
  496. {
  497. $begin = new DateTime($fromDate);
  498. $end = new DateTime($toDate);
  499. $interval = DateInterval::createFromDateString('1 day');
  500. $date_range = new DatePeriod($begin, $interval, $end);
  501. foreach ($date_range as $date) {
  502. $labels[] = $date->format('d/M');
  503. }
  504. return $labels;
  505. }
  506. private function getRecordData($type, $fromDate, $toDate)
  507. {
  508. $data = [];
  509. $begin = new DateTime($fromDate);
  510. $end = new DateTime($toDate);
  511. $interval = DateInterval::createFromDateString('1 day');
  512. $date_range = new DatePeriod($begin, $interval, $end);
  513. foreach ($date_range as $date) {
  514. if ($type == 'IN') {
  515. $found = false;
  516. foreach ($this->in as $in) {
  517. if (date("Y-m-d", strtotime($in->date)) == $date->format('Y-m-d')) {
  518. $data[] = number_format($in->total, 0, "", "");
  519. $found = true;
  520. }
  521. }
  522. if (!$found)
  523. $data[] = 0;
  524. }
  525. if ($type == 'OUT') {
  526. $found = false;
  527. foreach ($this->out as $out) {
  528. if (date("Y-m-d", strtotime($out->date)) == $date->format('Y-m-d')) {
  529. $data[] = number_format($out->total, 0, "", "");
  530. $found = true;
  531. }
  532. }
  533. if (!$found)
  534. $data[] = 0;
  535. }
  536. }
  537. return $data;
  538. }
  539. public function openExportModal()
  540. {
  541. $this->exportFromDate = $this->appliedFromDate;
  542. $this->exportToDate = $this->appliedToDate;
  543. $this->emit('show-export-modal');
  544. }
  545. public function exportWithDateRange()
  546. {
  547. $this->isExporting = true;
  548. $exportRecords = $this->generateExportData($this->exportFromDate, $this->exportToDate);
  549. $exportTotals = $this->generateExportTotals($this->exportFromDate, $this->exportToDate);
  550. $result = $this->exportWithData($exportRecords, $exportTotals);
  551. $this->isExporting = false;
  552. $this->emit('hide-export-modal');
  553. }
  554. function export()
  555. {
  556. $exportRecords = $this->generateExportData($this->appliedFromDate, $this->appliedToDate);
  557. $exportTotals = $this->generateExportTotals($this->appliedFromDate, $this->appliedToDate);
  558. return $this->exportWithData($exportRecords, $exportTotals);
  559. }
  560. private function exportWithData($exportRecords, $exportTotals)
  561. {
  562. ini_set('memory_limit', '512M');
  563. gc_enable();
  564. $letters = array('F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'AA');
  565. $spreadsheet = new Spreadsheet();
  566. $activeWorksheet = $spreadsheet->getActiveSheet();
  567. $activeWorksheet->setCellValue('A1', "Data");
  568. $activeWorksheet->setCellValue('B1', "Causale");
  569. $activeWorksheet->setCellValue('C1', "Dettaglio");
  570. $activeWorksheet->setCellValue('D1', "Nominativo");
  571. $activeWorksheet->setCellValue('E1', "Stato");
  572. $idx = 0;
  573. foreach ($this->payments as $p) {
  574. if ($idx >= count($letters)) {
  575. break;
  576. }
  577. $activeWorksheet->setCellValue($letters[$idx] . '1', $p->name);
  578. $idx++;
  579. if ($idx >= count($letters)) {
  580. break;
  581. }
  582. $activeWorksheet->mergeCells($letters[$idx] . '1:' . $letters[$idx] . '1');
  583. $idx++;
  584. }
  585. $idx = 0;
  586. $activeWorksheet->setCellValue('A2', "");
  587. $activeWorksheet->setCellValue('B2', "");
  588. $activeWorksheet->setCellValue('C2', "");
  589. $activeWorksheet->setCellValue('D2', "");
  590. $activeWorksheet->setCellValue('E2', "");
  591. foreach ($this->payments as $p) {
  592. if ($p->type == 'ALL') {
  593. if ($idx >= count($letters)) {
  594. break;
  595. }
  596. $activeWorksheet->setCellValue($letters[$idx] . '2', "Entrate");
  597. $idx++;
  598. $activeWorksheet->setCellValue($letters[$idx] . '2', "Uscite");
  599. $idx++;
  600. } elseif ($p->type == 'IN') {
  601. if ($idx >= count($letters)) {
  602. break;
  603. }
  604. $activeWorksheet->setCellValue($letters[$idx] . '2', "Entrate");
  605. $idx++;
  606. $activeWorksheet->setCellValue($letters[$idx] . '2', "");
  607. $idx++;
  608. } elseif ($p->type == 'OUT') {
  609. if ($idx >= count($letters)) {
  610. break;
  611. }
  612. $activeWorksheet->setCellValue($letters[$idx] . '2', "");
  613. $idx++;
  614. $activeWorksheet->setCellValue($letters[$idx] . '2', "Uscite");
  615. $idx++;
  616. }
  617. }
  618. $activeWorksheet->getStyle('A1:Q1')->getFont()->setBold(true);
  619. $activeWorksheet->getStyle('A2:Q2')->getFont()->setBold(true);
  620. $count = 3;
  621. $batchSize = 1000;
  622. $recordsProcessed = 0;
  623. $totalRecords = count($exportRecords);
  624. $recordsArray = array_chunk($exportRecords, $batchSize, true);
  625. foreach ($recordsArray as $recordsBatch) {
  626. foreach ($recordsBatch as $causal => $record) {
  627. $check = $causal;
  628. $parts = explode("§", $check);
  629. $d = $parts[0] ?? '';
  630. $c = $parts[1] ?? '';
  631. $j = $parts[2] ?? '';
  632. $det = $parts[3] ?? '';
  633. $deleted = $parts[4] ?? '';
  634. $detailParts = explode('|', $det);
  635. $exportDetail = count($detailParts) > 1 ? implode(', ', array_slice($detailParts, 1)) : $det;
  636. $activeWorksheet->setCellValue('A' . $count, !empty($d) ? date("d/m/Y", strtotime($d)) : '');
  637. $activeWorksheet->setCellValue('B' . $count, $c);
  638. $activeWorksheet->setCellValue('C' . $count, $exportDetail);
  639. $activeWorksheet->setCellValue('D' . $count, $j);
  640. $stato = ($deleted === 'DELETED') ? 'ANNULLATA' : '';
  641. $activeWorksheet->setCellValue('E' . $count, $stato);
  642. if ($stato === 'ANNULLATA') {
  643. $activeWorksheet->getStyle('E' . $count)->getFont()->getColor()->setARGB('FFFF0000');
  644. }
  645. $idx = 0;
  646. foreach ($this->payments as $p) {
  647. if ($idx >= count($letters) - 1) {
  648. break;
  649. }
  650. if (isset($record[$p->name])) {
  651. $inValue = isset($record[$p->name]["IN"]) ? formatPrice($record[$p->name]["IN"]) : "";
  652. $outValue = isset($record[$p->name]["OUT"]) ? formatPrice($record[$p->name]["OUT"]) : "";
  653. $activeWorksheet->setCellValue($letters[$idx] . $count, $inValue);
  654. $idx++;
  655. $activeWorksheet->setCellValue($letters[$idx] . $count, $outValue);
  656. $idx++;
  657. } else {
  658. $activeWorksheet->setCellValue($letters[$idx] . $count, "");
  659. $idx++;
  660. $activeWorksheet->setCellValue($letters[$idx] . $count, "");
  661. $idx++;
  662. }
  663. }
  664. $count++;
  665. $recordsProcessed++;
  666. if ($recordsProcessed % 500 === 0) {
  667. gc_collect_cycles();
  668. }
  669. }
  670. unset($recordsBatch);
  671. gc_collect_cycles();
  672. }
  673. $count++;
  674. $idx = 0;
  675. $activeWorksheet->setCellValue('A' . $count, 'Totale');
  676. $activeWorksheet->setCellValue('B' . $count, '');
  677. $activeWorksheet->setCellValue('C' . $count, '');
  678. $activeWorksheet->setCellValue('D' . $count, '');
  679. $activeWorksheet->setCellValue('E' . $count, '');
  680. foreach ($this->payments as $p) {
  681. if ($idx >= count($letters) - 1) {
  682. break;
  683. }
  684. if (isset($exportTotals[$p->name])) {
  685. if ($p->type == 'ALL') {
  686. $activeWorksheet->setCellValue($letters[$idx] . $count, formatPrice($exportTotals[$p->name]["IN"] ?? 0));
  687. $idx++;
  688. $activeWorksheet->setCellValue($letters[$idx] . $count, formatPrice($exportTotals[$p->name]["OUT"] ?? 0));
  689. $idx++;
  690. } elseif ($p->type == 'IN') {
  691. $activeWorksheet->setCellValue($letters[$idx] . $count, formatPrice($exportTotals[$p->name]["IN"] ?? 0));
  692. $idx++;
  693. $activeWorksheet->setCellValue($letters[$idx] . $count, "");
  694. $idx++;
  695. } elseif ($p->type == 'OUT') {
  696. $activeWorksheet->setCellValue($letters[$idx] . $count, "");
  697. $idx++;
  698. $activeWorksheet->setCellValue($letters[$idx] . $count, formatPrice($exportTotals[$p->name]["OUT"] ?? 0));
  699. $idx++;
  700. }
  701. } else {
  702. if ($p->type == 'ALL') {
  703. $activeWorksheet->setCellValue($letters[$idx] . $count, "0");
  704. $idx++;
  705. $activeWorksheet->setCellValue($letters[$idx] . $count, "0");
  706. $idx++;
  707. } elseif ($p->type == 'IN') {
  708. $activeWorksheet->setCellValue($letters[$idx] . $count, "0");
  709. $idx++;
  710. $activeWorksheet->setCellValue($letters[$idx] . $count, "");
  711. $idx++;
  712. } elseif ($p->type == 'OUT') {
  713. $activeWorksheet->setCellValue($letters[$idx] . $count, "");
  714. $idx++;
  715. $activeWorksheet->setCellValue($letters[$idx] . $count, "0");
  716. $idx++;
  717. }
  718. }
  719. }
  720. $activeWorksheet->getStyle('A' . $count . ':Q' . $count)->getFont()->setBold(true);
  721. $activeWorksheet->getColumnDimension('A')->setWidth(20);
  722. $activeWorksheet->getColumnDimension('B')->setWidth(40);
  723. $activeWorksheet->getColumnDimension('C')->setWidth(40);
  724. $activeWorksheet->getColumnDimension('D')->setWidth(40);
  725. $activeWorksheet->getColumnDimension('E')->setWidth(20);
  726. foreach ($letters as $l) {
  727. $activeWorksheet->getColumnDimension($l)->setWidth(20);
  728. }
  729. $filename = 'prima_nota_' . date("YmdHis") . '.xlsx';
  730. try {
  731. $currentClient = session('currentClient', 'default');
  732. $tempPath = sys_get_temp_dir() . '/' . $filename;
  733. $writer = new Xlsx($spreadsheet);
  734. $writer->save($tempPath);
  735. unset($spreadsheet, $activeWorksheet, $writer);
  736. gc_collect_cycles();
  737. $disk = Storage::disk('s3');
  738. $s3Path = $currentClient . '/prima_nota/' . $filename;
  739. $primaNotaFolderPath = $currentClient . '/prima_nota/.gitkeep';
  740. if (!$disk->exists($primaNotaFolderPath)) {
  741. $disk->put($primaNotaFolderPath, '');
  742. Log::info("Created prima_nota folder for client: {$currentClient}");
  743. }
  744. $fileContent = file_get_contents($tempPath);
  745. $uploaded = $disk->put($s3Path, $fileContent, 'private');
  746. if (!$uploaded) {
  747. throw new \Exception('Failed to upload file to Wasabi S3');
  748. }
  749. Log::info("Prima Nota exported to Wasabi", [
  750. 'client' => $currentClient,
  751. 'path' => $s3Path,
  752. 'size' => filesize($tempPath),
  753. 'records_processed' => $recordsProcessed
  754. ]);
  755. if (file_exists($tempPath)) {
  756. unlink($tempPath);
  757. }
  758. $downloadUrl = $disk->temporaryUrl($s3Path, now()->addHour());
  759. return redirect($downloadUrl);
  760. } catch (\Exception $e) {
  761. Log::error('Error exporting Prima Nota to Wasabi S3', [
  762. 'error' => $e->getMessage(),
  763. 'client' => session('currentClient', 'unknown'),
  764. 'filename' => $filename,
  765. 'records_processed' => $recordsProcessed ?? 0
  766. ]);
  767. $currentClient = session('currentClient', 'default');
  768. $clientFolder = storage_path('app/prima_nota/' . $currentClient);
  769. if (!is_dir($clientFolder)) {
  770. mkdir($clientFolder, 0755, true);
  771. Log::info("Created local client prima_nota folder: {$clientFolder}");
  772. }
  773. $localPath = $clientFolder . '/' . $filename;
  774. if (isset($tempPath) && file_exists($tempPath)) {
  775. rename($tempPath, $localPath);
  776. } else {
  777. $writer = new Xlsx($spreadsheet);
  778. $writer->save($localPath);
  779. unset($spreadsheet, $activeWorksheet, $writer);
  780. }
  781. gc_collect_cycles();
  782. Log::warning("Prima Nota saved locally due to S3 error", [
  783. 'client' => $currentClient,
  784. 'local_path' => $localPath,
  785. 'error' => $e->getMessage()
  786. ]);
  787. session()->flash('warning', 'File salvato localmente a causa di un errore del cloud storage.');
  788. return response()->download($localPath)->deleteFileAfterSend();
  789. }
  790. }
  791. }