RecordINOUT.php 31 KB

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