RecordINOUT.php 27 KB

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