RecordINOUT.php 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709
  1. <?php
  2. namespace App\Http\Livewire;
  3. use Livewire\Component;
  4. use PhpOffice\PhpSpreadsheet\Spreadsheet;
  5. use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
  6. use Illuminate\Support\Facades\Log;
  7. use SimpleXMLElement;
  8. use Illuminate\Support\Facades\Auth;
  9. use Illuminate\Support\Facades\Storage;
  10. class RecordINOUT extends Component
  11. {
  12. //public $records_in, $records_out;
  13. public $total_in = 0;
  14. public $total_out = 0;
  15. public $datas = [];
  16. public $month;
  17. public $year;
  18. public $months_1 = [];
  19. public $year_1;
  20. public $months_2 = [];
  21. public $year_2;
  22. public $show_block_2;
  23. //public $borsellino_id = 0;
  24. public $columns = array();
  25. public $rows_in = array();
  26. public $rows_out = array();
  27. public $records_in = array();
  28. public $records_out = array();
  29. public $showData = true;
  30. public $hasFilter = false;
  31. public $total = 0;
  32. public $selectedFilter = '';
  33. public $causalsIn = array();
  34. public $causalsOut = array();
  35. public $payments = array();
  36. public $members = array();
  37. public $filterCausalsIn = null;
  38. public $filterCausalsOut = null;
  39. public $excludeCausals = array();
  40. public function mount()
  41. {
  42. if (Auth::user()->level != env('LEVEL_ADMIN', 0))
  43. return redirect()->to('/dashboard');
  44. $borsellino = \App\Models\Causal::where('money', true)->first();
  45. if ($borsellino)
  46. $this->excludeCausals[] = $borsellino->id;
  47. //$this->borsellino_id = $borsellino->id;
  48. // Aggiungo
  49. $excludes = \App\Models\Causal::where('no_records', true)->get();
  50. foreach ($excludes as $e) {
  51. $this->excludeCausals[] = $e->id;
  52. }
  53. $this->month = date("m");
  54. $this->year = date("Y");
  55. $this->year_1 = date("Y");
  56. $this->year_2 = date("Y");
  57. $this->show_block_2 = false;
  58. $this->getCausale(\App\Models\Causal::select('id', 'name')->where('parent_id', null)->where('type', 'IN')->whereNotIn('id', $this->excludeCausals)->get(), 'IN', 0);
  59. $this->getCausale(\App\Models\Causal::select('id', 'name')->where('parent_id', null)->where('type', 'OUT')->whereNotIn('id', $this->excludeCausals)->get(), 'OUT', 0);
  60. $this->getCausalsIn(\App\Models\Causal::select('id', 'name')->where('parent_id', null)->where('type', 'IN')->get(), 0);
  61. $this->getCausalsOut(\App\Models\Causal::select('id', 'name')->where('parent_id', null)->where('type', 'OUT')->get(), 0);
  62. //$this->causalsIn = \App\Models\Causal::where('parent_id', null)->where('type', 'IN')->whereNotIn('id', $this->excludeCausals)->get();
  63. //$this->causalsOut = \App\Models\Causal::where('parent_id', null)->where('type', 'OUT')->whereNotIn('id', $this->excludeCausals)->get();
  64. }
  65. public function getCausalsIn($records, $indentation)
  66. {
  67. foreach ($records as $record) {
  68. $this->causalsIn[] = array('id' => $record->id, 'name' => $record->getTree(), 'text' => $record->getTree(), 'level' => $indentation);
  69. if (count($record->childs))
  70. $this->getCausalsIn($record->childs, $indentation + 1);
  71. }
  72. }
  73. public function getCausalsOut($records, $indentation)
  74. {
  75. foreach ($records as $record) {
  76. $this->causalsOut[] = array('id' => $record->id, 'name' => $record->getTree(), 'text' => $record->getTree(), 'level' => $indentation);
  77. if (count($record->childs))
  78. $this->getCausalsOut($record->childs, $indentation + 1);
  79. }
  80. }
  81. public function getCausale($records, $type, $indentation)
  82. {
  83. foreach ($records as $record) {
  84. $first_parent_id = null;
  85. if ($record->parent_id != null) {
  86. $first_parent_id = \App\Models\Causal::where('id', $record->parent_id)->first()->parent_id;
  87. }
  88. if ($type == 'IN')
  89. $this->rows_in[] = array('id' => $record->id, 'name' => $record->name, 'level' => $indentation, 'parent_id' => $record->parent_id, 'parent_name' => $this->getCausalName($record->parent_id), 'first_parent_id' => $first_parent_id, 'first_parent_name' => $this->getCausalName($first_parent_id), 'all_childs' => $this->getAllChild($record->id));
  90. if ($type == 'OUT')
  91. $this->rows_out[] = array('id' => $record->id, 'name' => $record->name, 'level' => $indentation, 'parent_id' => $record->parent_id, 'parent_name' => $this->getCausalName($record->parent_id), 'first_parent_id' => $first_parent_id, 'first_parent_name' => $this->getCausalName($first_parent_id), 'all_childs' => $this->getAllChild($record->id));
  92. if (count($record->childs))
  93. $this->getCausale($record->childs, $type, $indentation + 1);
  94. }
  95. }
  96. public function getAllChild($id)
  97. {
  98. $aChilds = array();
  99. $aChilds[] = $id;
  100. $record = \App\Models\Causal::findOrFail($id);
  101. $aChilds[] = $record->parent_id;
  102. if ($record->parent_id != null) {
  103. $first_parent_id = \App\Models\Causal::where('id', $record->parent_id)->first()->parent_id;
  104. $aChilds[] = $first_parent_id;
  105. }
  106. $childs = \App\Models\Causal::where('parent_id', $id)->get();
  107. foreach ($childs as $child) {
  108. $aChilds[] = $child->id;
  109. $childs2 = \App\Models\Causal::where('parent_id', $child->id)->get();
  110. foreach ($childs2 as $child2) {
  111. $aChilds[] = $child2->id;
  112. $childs3 = \App\Models\Causal::where('parent_id', $child2->id)->get();
  113. foreach ($childs3 as $child3) {
  114. $aChilds[] = $child3->id;
  115. }
  116. }
  117. }
  118. return $aChilds;
  119. }
  120. public function getCausalName($id)
  121. {
  122. if ($id > 0)
  123. return \App\Models\Causal::findOrFail($id)->name;
  124. else
  125. return "";
  126. }
  127. public function render()
  128. {
  129. return view('livewire.records_in_out');
  130. }
  131. public function hydrate()
  132. {
  133. $this->emit('load-select');
  134. }
  135. public function show($m, $y)
  136. {
  137. if ($m != "" && $y != "" && !in_array($m . "-" . $y, $this->datas))
  138. $this->datas[] = $m . "-" . $y;
  139. $this->columns = array();
  140. $this->records_in = [];
  141. $this->records_out = [];
  142. $exclude_from_records = \App\Models\Member::where('exclude_from_records', true)->pluck('id')->toArray();
  143. if (sizeof($this->datas) > 0) {
  144. foreach ($this->datas as $filter) {
  145. $this->columns[] = $filter;
  146. $f = $filter;
  147. if ($m == 'x')
  148. $f = str_replace("x-", "", $filter);
  149. $records = \App\Models\Record::where('type', 'IN')
  150. ->join('records_rows', 'records.id', '=', 'records_rows.record_id')
  151. ->whereNotIn('records_rows.causal_id', $this->excludeCausals)
  152. ->where(function ($query) {
  153. $query->where('deleted', false)->orWhere('deleted', null);
  154. })
  155. ->where(function ($query) {
  156. $query->where('financial_movement', false)->orWhere('financial_movement', null);
  157. })
  158. ->whereNotIn('member_id', $exclude_from_records)
  159. ->where('records_rows.when', 'like', '%"' . $f . '"%')
  160. ->get();
  161. //Log::info('Record In' . $records);
  162. foreach ($records as $record) {
  163. $amount = $record->amount;
  164. $amount += getVatValue($amount, $record->vat_id);
  165. $when = sizeof(json_decode($record->when));
  166. if ($when > 1) {
  167. $amount = $amount / $when;
  168. $record->amount = $amount;
  169. }
  170. // Aggiungo/aggiorno i dati
  171. if (isset($this->records_in[$filter][$record->causal_id]))
  172. $this->records_in[$filter][$record->causal_id] += $amount;
  173. else
  174. $this->records_in[$filter][$record->causal_id] = $amount;
  175. // Aggiorno i dati del padre
  176. $this->updateParent("IN", $record->causal_id, $amount, $filter);
  177. }
  178. $records = \App\Models\Record::where('type', 'OUT')
  179. ->join('records_rows', 'records.id', '=', 'records_rows.record_id')
  180. ->whereNotIn('records_rows.causal_id', $this->excludeCausals)
  181. ->where(function ($query) {
  182. $query->where('deleted', false)->orWhere('deleted', null);
  183. })
  184. ->where(function ($query) use ($exclude_from_records) {
  185. $query->whereNull('member_id')
  186. ->orWhereNotIn('member_id', $exclude_from_records);
  187. })
  188. ->where('records_rows.when', 'like', '%"' . $f . '"%')->get();
  189. Log::info('Record Out' . $records);
  190. foreach ($records as $record) {
  191. $amount = $record->amount;
  192. $amount += getVatValue($amount, $record->vat_id);
  193. $when = sizeof(json_decode($record->when));
  194. if ($when > 1) {
  195. $amount = $amount / $when;
  196. $record->amount = $amount;
  197. }
  198. // Aggiungo/aggiorno i dati
  199. if (isset($this->records_out[$filter][$record->causal_id]))
  200. $this->records_out[$filter][$record->causal_id] += $amount;
  201. else
  202. $this->records_out[$filter][$record->causal_id] = $amount;
  203. $this->updateParent("OUT", $record->causal_id, $amount, $filter);
  204. }
  205. }
  206. }
  207. //$this->showData = true;
  208. $this->emit('load-table');
  209. }
  210. public function updateParent($type, $causal_id, $amount, $filter)
  211. {
  212. if ($type == "IN") {
  213. foreach ($this->rows_in as $r) {
  214. if ($r["id"] == $causal_id) {
  215. if (isset($this->records_in[$filter][$r["parent_id"]]))
  216. $this->records_in[$filter][$r["parent_id"]] += $amount;
  217. else
  218. $this->records_in[$filter][$r["parent_id"]] = $amount;
  219. if ($r["parent_id"] > 0)
  220. $this->updateParent("IN", $r["parent_id"], $amount, $filter);
  221. }
  222. }
  223. }
  224. if ($type == "OUT") {
  225. foreach ($this->rows_out as $r) {
  226. if ($r["id"] == $causal_id) {
  227. if (isset($this->records_out[$filter][$r["parent_id"]]))
  228. $this->records_out[$filter][$r["parent_id"]] += $amount;
  229. else
  230. $this->records_out[$filter][$r["parent_id"]] = $amount;
  231. if ($r["parent_id"] > 0)
  232. $this->updateParent("OUT", $r["parent_id"], $amount, $filter);
  233. }
  234. }
  235. }
  236. }
  237. public function updateParentYear($type, $causal_id, $amount, $filter, &$records_in, &$records_out)
  238. {
  239. if ($type == "IN") {
  240. foreach ($this->rows_in as $r) {
  241. if ($r["id"] == $causal_id) {
  242. if (isset($records_in[$filter][$r["parent_id"]]))
  243. $records_in[$filter][$r["parent_id"]] += $amount;
  244. else
  245. $records_in[$filter][$r["parent_id"]] = $amount;
  246. if ($r["parent_id"] > 0)
  247. $this->updateParentYear("IN", $r["parent_id"], $amount, $filter, $records_in, $records_out);
  248. }
  249. }
  250. }
  251. if ($type == "OUT") {
  252. foreach ($this->rows_out as $r) {
  253. if ($r["id"] == $causal_id) {
  254. if (isset($records_out[$filter][$r["parent_id"]]))
  255. $records_out[$filter][$r["parent_id"]] += $amount;
  256. else
  257. $records_out[$filter][$r["parent_id"]] = $amount;
  258. if ($r["parent_id"] > 0)
  259. $this->updateParentYear("OUT", $r["parent_id"], $amount, $filter, $records_in, $records_out);
  260. }
  261. }
  262. }
  263. }
  264. public function getCausal($causal)
  265. {
  266. $ret = '';
  267. if ($causal > 0) {
  268. $ret = \App\Models\Causal::findOrFail($causal)->getTree();
  269. }
  270. return $ret;
  271. }
  272. public function getMonth($str)
  273. {
  274. $ret = '';
  275. list($m, $y) = explode("-", $str);
  276. switch ($m) {
  277. case 'x':
  278. $ret = '';
  279. break;
  280. case '01':
  281. $ret = 'Gennaio ';
  282. break;
  283. case '02':
  284. $ret = 'Febbraio ';
  285. break;
  286. case '03':
  287. $ret = 'Marzo ';
  288. break;
  289. case '04':
  290. $ret = 'Aprile ';
  291. break;
  292. case '05':
  293. $ret = 'Maggio ';
  294. break;
  295. case '06':
  296. $ret = 'Giugno ';
  297. break;
  298. case '07':
  299. $ret = 'Luglio ';
  300. break;
  301. case '08':
  302. $ret = 'Agosto ';
  303. break;
  304. case '09':
  305. $ret = 'Settembre ';
  306. break;
  307. case '10':
  308. $ret = 'Ottobre ';
  309. break;
  310. case '11':
  311. $ret = 'Novembre ';
  312. break;
  313. case '12':
  314. $ret = 'Dicembre ';
  315. break;
  316. default:
  317. $ret = '';
  318. break;
  319. }
  320. $ret .= $y;
  321. return $ret;
  322. }
  323. public function clear()
  324. {
  325. $this->columns = [];
  326. $this->datas = [];
  327. $this->records_out = [];
  328. $this->records_in = [];
  329. $this->emit('load-select');
  330. $this->emit('reset-collapse');
  331. //$this->showData = false;
  332. }
  333. public function remove($idx)
  334. {
  335. if (sizeof($this->datas) > 1)
  336. array_splice($this->datas, $idx, 1);
  337. //unset($this->datas[$idx]);
  338. else
  339. $this->datas = array();
  340. $this->show('', '');
  341. }
  342. public function export()
  343. {
  344. $rows_in = array();
  345. if ($this->filterCausalsIn != null && sizeof($this->filterCausalsIn) > 0) {
  346. foreach ($this->rows_in as $r) {
  347. if (in_array($r["id"], $this->filterCausalsIn) || in_array($r["parent_id"], $this->filterCausalsIn) || in_array($r["first_parent_id"], $this->filterCausalsIn)) {
  348. $rows_in[] = $r;
  349. }
  350. }
  351. } else {
  352. $rows_in = $this->rows_in;
  353. }
  354. $result = $this->generateExcel($this->columns, $rows_in, $this->records_in, $this->rows_out, $this->records_out, false);
  355. if ($result['storage_type'] === 's3') {
  356. try {
  357. $disk = Storage::disk('wasabi');
  358. $downloadUrl = $disk->temporaryUrl($result['path'], now()->addHour());
  359. return redirect($downloadUrl);
  360. } catch (\Exception $e) {
  361. Log::error('Error generating S3 download URL for export', [
  362. 'error' => $e->getMessage(),
  363. 'path' => $result['path']
  364. ]);
  365. session()->flash('error', 'Errore durante la generazione del link di download. Riprova.');
  366. return back();
  367. }
  368. } else {
  369. return response()->download($result['path'])->deleteFileAfterSend();
  370. }
  371. }
  372. public function exportYear($year)
  373. {
  374. $records_in = [];
  375. $records_out = [];
  376. $datas = [];
  377. if (env('FISCAL_YEAR_MONTH_FROM', 1) > 1) {
  378. for ($m = env('FISCAL_YEAR_MONTH_FROM', 1); $m <= 12; $m++) {
  379. $datas[] = $m . "-" . $year;
  380. }
  381. for ($m = 1; $m <= env('FISCAL_YEAR_MONTH_TO', 12); $m++) {
  382. $datas[] = $m . "-" . ($year + 1);
  383. }
  384. } else {
  385. for ($m = 1; $m <= 12; $m++) {
  386. $datas[] = $m . "-" . $year;
  387. }
  388. }
  389. $exclude_from_records = \App\Models\Member::where('exclude_from_records', true)->pluck('id')->toArray();
  390. foreach ($datas as $filter) {
  391. $columns[] = $filter;
  392. $records = \App\Models\Record::where('type', 'IN')
  393. ->join('records_rows', 'records.id', '=', 'records_rows.record_id')
  394. ->whereNotIn('records_rows.causal_id', $this->excludeCausals)
  395. ->where(function ($query) {
  396. $query->where('deleted', false)->orWhere('deleted', null);
  397. })
  398. ->where(function ($query) {
  399. $query->where('financial_movement', false)->orWhere('financial_movement', null);
  400. })
  401. ->whereNotIn('member_id', $exclude_from_records)
  402. ->where('records_rows.when', 'like', '%"' . $filter . '"%')->get();
  403. //$records = $records->orderBy('date', 'DESC')->get();
  404. foreach ($records as $record) {
  405. $amount = $record->amount;
  406. $amount += getVatValue($amount, $record->vat_id);
  407. $when = sizeof(json_decode($record->when));
  408. if ($when > 1) {
  409. $amount = $amount / $when;
  410. $record->amount = $amount;
  411. }
  412. // Aggiungo/aggiorno i dati
  413. if (isset($records_in[$filter][$record->causal_id]))
  414. $records_in[$filter][$record->causal_id] += $amount;
  415. else
  416. $records_in[$filter][$record->causal_id] = $amount;
  417. // Aggiorno i dati del padre
  418. $this->updateParentYear("IN", $record->causal_id, $amount, $filter, $records_in, $records_out);
  419. }
  420. $records = \App\Models\Record::where('type', 'OUT')
  421. ->join('records_rows', 'records.id', '=', 'records_rows.record_id')
  422. ->whereNotIn('records_rows.causal_id', $this->excludeCausals)
  423. ->where(function ($query) {
  424. $query->where('deleted', false)->orWhere('deleted', null);
  425. })
  426. ->where(function ($query) use ($exclude_from_records) {
  427. $query->whereNull('member_id')
  428. ->orWhereNotIn('member_id', $exclude_from_records);
  429. })
  430. ->where('records_rows.when', 'like', '%"' . $filter . '"%')->get();
  431. //$records = $records->orderBy('date', 'DESC')->get();
  432. foreach ($records as $record) {
  433. $amount = $record->amount;
  434. $when = sizeof(json_decode($record->when));
  435. if ($when > 1) {
  436. $amount = $amount / $when;
  437. $record->amount = $amount;
  438. }
  439. // Aggiungo/aggiorno i dati
  440. if (isset($records_out[$filter][$record->causal_id]))
  441. $records_out[$filter][$record->causal_id] += $amount;
  442. else
  443. $records_out[$filter][$record->causal_id] = $amount;
  444. $this->updateParentYear("OUT", $record->causal_id, $amount, $filter, $records_in, $records_out);
  445. }
  446. }
  447. $result = $this->generateExcel($columns, $this->rows_in, $records_in, $this->rows_out, $records_out, true);
  448. if ($result['storage_type'] === 's3') {
  449. $disk = Storage::disk('wasabi');
  450. $downloadUrl = $disk->temporaryUrl($result['path'], now()->addHour());
  451. return redirect($downloadUrl);
  452. } else {
  453. return response()->download($result['path'])->deleteFileAfterSend();
  454. }
  455. }
  456. public function generateExcel($columns, $rows_in, $records_in, $rows_out, $records_out, $isYearExport)
  457. {
  458. $letters = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N');
  459. $spreadsheet = new Spreadsheet();
  460. $activeWorksheet = $spreadsheet->getActiveSheet();
  461. $activeWorksheet->setCellValue('A1', 'Entrate');
  462. foreach ($columns as $idx => $column) {
  463. $activeWorksheet->setCellValue($letters[$idx + 1] . '1', $this->getMonth($column));
  464. }
  465. $activeWorksheet->getStyle('A1:N1')->getFont()->setBold(true);
  466. $activeWorksheet->getStyle('A1:N1')->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('C6E0B4'); // Lighter green
  467. $count = 2;
  468. $totals = [];
  469. foreach ($rows_in as $in) {
  470. $activeWorksheet->setCellValue('A' . $count, str_repeat(" ", $in["level"]) . $in["name"]);
  471. foreach ($columns as $idx => $column) {
  472. if (isset($records_in[$column][$in["id"]])) {
  473. $activeWorksheet->setCellValue($letters[$idx + 1] . $count, formatPrice($records_in[$column][$in["id"]]));
  474. if ($in["level"] == 0) {
  475. if (isset($totals[$idx]))
  476. $totals[$idx] += $records_in[$column][$in["id"]];
  477. else
  478. $totals[$idx] = $records_in[$column][$in["id"]];
  479. }
  480. }
  481. }
  482. if ($in["level"] == 0) {
  483. $activeWorksheet->getStyle('A' . $count . ':N' . $count)->getFont()->setBold(true);
  484. }
  485. $count += 1;
  486. }
  487. $activeWorksheet->setCellValue('A' . $count, 'Totale');
  488. foreach ($totals as $idx => $total) {
  489. $activeWorksheet->setCellValue($letters[$idx + 1] . $count, formatPrice($total));
  490. $activeWorksheet->getStyle('A' . $count . ':N' . $count)->getFont()->setBold(true);
  491. $activeWorksheet->getStyle('A' . $count . ':N' . $count)->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('C6E0B4'); // Lighter green
  492. }
  493. $count += 2;
  494. $activeWorksheet->setCellValue('A' . $count, "Uscite");
  495. foreach ($columns as $idx => $column) {
  496. $activeWorksheet->setCellValue($letters[$idx + 1] . $count, $this->getMonth($column));
  497. }
  498. $activeWorksheet->getStyle('A' . $count . ':N' . $count)->getFont()->setBold(true);
  499. $activeWorksheet->getStyle('A' . $count . ':N' . $count)->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('F8CBAD'); // Lighter red
  500. $count += 1;
  501. $totals = [];
  502. foreach ($rows_out as $out) {
  503. $activeWorksheet->setCellValue('A' . $count, str_repeat(" ", $out["level"]) . $out["name"]);
  504. foreach ($columns as $idx => $column) {
  505. if (isset($records_out[$column][$out["id"]])) {
  506. $activeWorksheet->setCellValue($letters[$idx + 1] . $count, formatPrice($records_out[$column][$out["id"]]));
  507. if ($out["level"] == 0) {
  508. if (isset($totals[$idx]))
  509. $totals[$idx] += $records_out[$column][$out["id"]];
  510. else
  511. $totals[$idx] = $records_out[$column][$out["id"]];
  512. }
  513. }
  514. }
  515. if ($out["level"] == 0) {
  516. $activeWorksheet->getStyle('A' . $count . ':N' . $count)->getFont()->setBold(true);
  517. }
  518. $count += 1;
  519. }
  520. $activeWorksheet->setCellValue('A' . $count, 'Totale');
  521. foreach ($totals as $idx => $total) {
  522. $activeWorksheet->setCellValue($letters[$idx + 1] . $count, formatPrice($total));
  523. $activeWorksheet->getStyle('A' . $count . ':N' . $count)->getFont()->setBold(true);
  524. $activeWorksheet->getStyle('A' . $count . ':N' . $count)->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('F8CBAD'); // Lighter red
  525. }
  526. $activeWorksheet->getColumnDimension('A')->setWidth(35);
  527. for ($i = 1; $i < count($letters); $i++) {
  528. $activeWorksheet->getColumnDimension($letters[$i])->setWidth(20);
  529. }
  530. $fileSuffix = $isYearExport ? 'AnnoFiscale' : 'Selezione';
  531. $filename = date("Ymd") . '_Gestionale_' . $fileSuffix . '.xlsx';
  532. try {
  533. // Get current client for folder organization
  534. $currentClient = session('currentClient', 'default');
  535. // Create temporary file to write Excel data
  536. $tempPath = sys_get_temp_dir() . '/' . $filename;
  537. // Write to temporary file
  538. $writer = new Xlsx($spreadsheet);
  539. $writer->save($tempPath);
  540. // Get Wasabi disk
  541. $disk = Storage::disk('wasabi');
  542. // Create the S3 path (client folder + reports subfolder)
  543. $s3Path = $currentClient . '/reports/' . $filename;
  544. // Ensure the client reports folder exists
  545. $reportsFolderPath = $currentClient . '/reports/.gitkeep';
  546. if (!$disk->exists($reportsFolderPath)) {
  547. $disk->put($reportsFolderPath, '');
  548. Log::info("Created reports folder for client: {$currentClient}");
  549. }
  550. // Upload file to Wasabi S3
  551. $fileContent = file_get_contents($tempPath);
  552. $uploaded = $disk->put($s3Path, $fileContent, 'private');
  553. if (!$uploaded) {
  554. throw new \Exception('Failed to upload file to Wasabi S3');
  555. }
  556. Log::info("Management report uploaded to Wasabi", [
  557. 'client' => $currentClient,
  558. 'path' => $s3Path,
  559. 'size' => filesize($tempPath),
  560. 'type' => $fileSuffix
  561. ]);
  562. // Clean up temporary file
  563. if (file_exists($tempPath)) {
  564. unlink($tempPath);
  565. }
  566. // Return S3 path for further processing or download URL generation
  567. return [
  568. 'success' => true,
  569. 'path' => $s3Path,
  570. 'local_path' => null,
  571. 'storage_type' => 's3'
  572. ];
  573. } catch (\Exception $e) {
  574. Log::error('Error uploading management report to Wasabi S3', [
  575. 'error' => $e->getMessage(),
  576. 'client' => session('currentClient', 'unknown'),
  577. 'filename' => $filename
  578. ]);
  579. // Fallback to local storage if S3 fails
  580. $currentClient = session('currentClient', 'default');
  581. $clientFolder = storage_path('app/reports/' . $currentClient);
  582. // Ensure client folder exists
  583. if (!is_dir($clientFolder)) {
  584. mkdir($clientFolder, 0755, true);
  585. Log::info("Created local client reports folder: {$clientFolder}");
  586. }
  587. $localPath = $clientFolder . '/' . $filename;
  588. $writer = new Xlsx($spreadsheet);
  589. $writer->save($localPath);
  590. Log::warning("Management report saved locally due to S3 error", [
  591. 'client' => $currentClient,
  592. 'local_path' => $localPath,
  593. 'error' => $e->getMessage()
  594. ]);
  595. // Return local path for backward compatibility
  596. return [
  597. 'success' => true,
  598. 'path' => $localPath,
  599. 'local_path' => $localPath,
  600. 'storage_type' => 'local'
  601. ];
  602. }
  603. }
  604. }