RecordINOUT.php.bak 31 KB

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