RecordOUT.php 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234
  1. <?php
  2. namespace App\Http\Livewire;
  3. use Livewire\Component;
  4. use Illuminate\Support\Facades\Auth;
  5. use Illuminate\Support\Facades\Log;
  6. use SimpleXMLElement;
  7. use Livewire\WithFileUploads;
  8. use Illuminate\Support\Facades\DB;
  9. class RecordOUT extends Component
  10. {
  11. use WithFileUploads;
  12. protected $listeners = ['setCausal' => 'setCausal'];
  13. public $sortField = 'date';
  14. public $sortAsc = false;
  15. public $typeOUT = "OUT";
  16. public $fromPage = '';
  17. public $multiP = false;
  18. public $multiMonthTo = 0;
  19. public $multiYearTo = 0;
  20. public $multiMonthFrom = 0;
  21. public $multiYearFrom = 0;
  22. public function sortBy($field)
  23. {
  24. if ($this->sortField === $field) {
  25. $this->sortAsc = ! $this->sortAsc;
  26. } else {
  27. $this->sortAsc = true;
  28. }
  29. $this->sortField = $field;
  30. }
  31. public $records, $dataId, $member_id, $supplier_id,
  32. $causal_id,
  33. $payment_method_id,
  34. $date,
  35. $month,
  36. $year,
  37. $type,
  38. $amount,
  39. $note,
  40. $commercial, $update = false, $add = false;
  41. public $filterSupplier = 0, $filterPaymentMethod = 0, $filterCausals = [], $filterFrom = '', $filterTo = '', $filterCommercial = 0;
  42. public $hasFilter = false;
  43. public $total = 0;
  44. public $selectedFilter = '';
  45. public $multipleIds = [];
  46. public $multipleAction = '';
  47. public $selectId = 0;
  48. public $causals = array();
  49. public $payments = array();
  50. public $suppliers = array();
  51. public $rows = array();
  52. public $receiptFiles = [];
  53. public $selectedCausal = '';
  54. public $importCausals = array();
  55. protected $rules = [
  56. 'supplier_id' => 'required',
  57. 'payment_method_id' => 'required',
  58. 'rows.*.causal_id' => 'required',
  59. 'rows.*.amount' => 'required'
  60. //'causal_id' => 'required',
  61. //'amount' => 'required'
  62. ];
  63. protected $messages = [
  64. 'supplier_id.required' => 'Il fornitore è obbligatorio',
  65. 'payment_method_id.required' => 'Il metodo di pagamento è obbligatorio',
  66. 'rows.*.amount.required' => 'L\'importo è obbligatorio',
  67. 'rows.*.causal_id.required' => 'La causale è obbligatoria'
  68. ];
  69. public function getSupplierProperty()
  70. {
  71. $ret = null;
  72. if ($this->supplier_id > 0) {
  73. $ret = \App\Models\Supplier::findOrFail($this->supplier_id);
  74. }
  75. return $ret;
  76. }
  77. public function getCausalProperty()
  78. {
  79. $ret = null;
  80. if ($this->causal_id > 0) {
  81. $ret = \App\Models\Causal::findOrFail($this->causal_id);
  82. }
  83. return $ret;
  84. }
  85. public function resetFields()
  86. {
  87. $this->member_id = null;
  88. $this->supplier_id = null;
  89. //$this->causal_id = null;
  90. $this->payment_method_id = null;
  91. $this->date = date("Y-m-d");
  92. //$this->month = date("n");
  93. //$this->year = date("Y");
  94. $this->type = 'OUT';
  95. //$this->note = '';
  96. //$this->amount = null;
  97. $this->commercial = 1;
  98. $this->rows = array();
  99. $this->rows[] = array('causal_id' => null, 'when' => array(array('month' => date("n"), 'year' => date("Y"), 'period' => '')), 'amount' => null, 'note' => '', 'commercial' => 0);
  100. $this->emit('load-data-table');
  101. }
  102. public function getCausale($records, $indentation)
  103. {
  104. foreach ($records as $record) {
  105. $this->causals[] = array('id' => $record->id, 'name' => $record->getTree());
  106. if (count($record->childs))
  107. $this->getCausale($record->childs, $indentation + 1);
  108. }
  109. }
  110. public $isImportModalOpen = false;
  111. public function openImportModal()
  112. {
  113. $this->isImportModalOpen = true;
  114. }
  115. public function closeImportModal()
  116. {
  117. $this->isImportModalOpen = false;
  118. $this->reset(['selectedCausal', 'receiptFiles']);
  119. $this->resetValidation();
  120. }
  121. public function hydrate()
  122. {
  123. $this->emit('load-select');
  124. if (empty($this->importCausals)) {
  125. $this->loadImportCausals();
  126. }
  127. }
  128. public function mount()
  129. {
  130. if (isset($_GET["from"])) {
  131. $this->fromPage = $_GET["from"];
  132. }
  133. if (Auth::user()->level != env('LEVEL_ADMIN', 0))
  134. return redirect()->to('/dashboard');
  135. $this->multiMonthFrom = date("n");
  136. $this->multiYearFrom = date("Y");
  137. $this->multiMonthTo = date("n");
  138. $this->multiYearTo = date("Y");
  139. if (isset($_GET["new"]))
  140. $this->add();
  141. $this->causals = array();
  142. $this->getCausale(\App\Models\Causal::select('id', 'name')->where('parent_id', null)->where('type', 'OUT')->orderBy('name')->get(), 0);
  143. $this->suppliers = \App\Models\Supplier::select('name', 'id')->orderBy('name')->get();
  144. $this->payments = \App\Models\PaymentMethod::select('id', 'name')->whereIn('type', array('ALL', 'OUT'))->where('enabled', true)->orderBy('name')->get();
  145. $this->importCausals = [];
  146. $this->loadImportCausals();
  147. }
  148. public function loadImportCausals()
  149. {
  150. $causals = \App\Models\Causal::select('id', 'name')
  151. ->where('type', 'OUT')
  152. ->orderBy('name')
  153. ->get();
  154. $this->importCausals = [];
  155. foreach ($causals as $causal) {
  156. $this->importCausals[] = [
  157. 'id' => $causal->id,
  158. 'name' => $causal->getTree()
  159. ];
  160. }
  161. }
  162. public function getCausal($causal)
  163. {
  164. $ret = '';
  165. if ($causal > 0) {
  166. $ret = \App\Models\Causal::findOrFail($causal)->getTree();
  167. }
  168. return $ret;
  169. }
  170. public function search()
  171. {
  172. $this->hasFilter = true;
  173. }
  174. public function disableSearch()
  175. {
  176. $this->filterSupplier = 0;
  177. $this->filterPaymentMethod = 0;
  178. $this->filterCausals = [];
  179. $this->filterTo = '';
  180. $this->filterFrom = '';
  181. $this->filterCommercial = 0;
  182. $this->hasFilter = false;
  183. $this->hasFilter = false;
  184. }
  185. public function render()
  186. {
  187. $datas = [];
  188. if (false) {
  189. if ($this->hasFilter) {
  190. $datas = \App\Models\Record::where('type', 'OUT')->with('supplier', 'payment_method');
  191. /*if ($this->filterCommercial > 0)
  192. {
  193. $datas = $datas->where('commercial', $this->filterCommercial == 1 ? true : false);
  194. }*/
  195. if ($this->filterSupplier > 0) {
  196. $datas = $datas->where('supplier_id', $this->filterSupplier);
  197. }
  198. if ($this->filterPaymentMethod > 0) {
  199. $datas = $datas->where('payment_method_id', $this->filterPaymentMethod);
  200. }
  201. /*if (sizeof($this->filterCausals) > 0)
  202. {
  203. $datas = $datas->whereIn('causal_id', $this->filterCausals);
  204. }*/
  205. if ($this->filterFrom != '') {
  206. $datas = $datas->where('date', '>=', $this->filterFrom);
  207. }
  208. if ($this->filterTo != '') {
  209. $datas = $datas->where('date', '<=', $this->filterTo);
  210. }
  211. //$this->records = $datas->orderBy('date', 'DESC')->get();
  212. $this->records = $datas->get();
  213. //$this->total = $this->records->sum('amount');
  214. $this->total = 0;
  215. foreach ($this->records as $r) {
  216. foreach ($r->rows as $rr) {
  217. $this->total += $rr->amount;
  218. }
  219. }
  220. } else {
  221. if ($this->selectedFilter == '') {
  222. $this->records = \App\Models\Record::where('type', 'OUT')->with('supplier', 'payment_method')->limit(20)->orderBy('date', 'DESC')->orderBy('id', 'DESC')->get();
  223. } else {
  224. if ($this->selectedFilter == 0) {
  225. $fromDate = date("Y-m-d");
  226. $toDate = date("Y-m-d");
  227. }
  228. if ($this->selectedFilter == 1) {
  229. $fromDate = date("Y-m-01");
  230. $toDate = date("Y-m-t");
  231. }
  232. if ($this->selectedFilter == 2) {
  233. $fromDate = date("Y-01-01");
  234. $toDate = date("Y-12-31");
  235. }
  236. if ($this->selectedFilter == 3) {
  237. $fromDate = date("2000-01-01");
  238. $toDate = date("Y-12-31");
  239. }
  240. $this->records = \App\Models\Record::where('type', 'OUT')->whereBetween('date', [$fromDate, $toDate])->with('supplier', 'payment_method')->get();
  241. }
  242. }
  243. foreach ($this->records as $r) {
  244. $r->total = $r->getTotal();
  245. $r->supplier = $r->supplier ? $r->supplier->name : '';
  246. $r->payment = $r->payment_method ? $r->payment_method->name : '';
  247. }
  248. }
  249. /*if ($this->sortField != '')
  250. {
  251. if ($this->sortAsc)
  252. $this->records = $this->records->sortBy($this->sortField);
  253. else
  254. $this->records = $this->records->sortByDesc($this->sortField);
  255. }
  256. else
  257. $this->records = $this->records->sortByDesc('id');*/
  258. return view('livewire.records_out');
  259. }
  260. public function executeMultipleAction()
  261. {
  262. if ($this->multipleAction == 'delete')
  263. $this->multipleDelete();
  264. }
  265. public function add()
  266. {
  267. $this->emit('load-select');
  268. //if ($this->hasFilter)
  269. $this->emit('hide-search');
  270. $this->resetFields();
  271. $this->add = true;
  272. $this->update = false;
  273. $this->emit('setEdit', true);
  274. }
  275. public function store()
  276. {
  277. $this->emit('refresh');
  278. $this->validate();
  279. try {
  280. $record = \App\Models\Record::create([
  281. 'member_id' => $this->member_id,
  282. 'supplier_id' => $this->supplier_id,
  283. //'causal_id' => $this->causal_id,
  284. 'payment_method_id' => $this->payment_method_id,
  285. 'date' => $this->date,
  286. //'month' => $this->month,
  287. //'year' => $this->year,
  288. //'note' => $this->note,
  289. 'type' => $this->type,
  290. //'amount' => $this->currencyToDouble($this->amount),
  291. 'commercial' => $this->commercial,
  292. ]);
  293. $this->dataId = $record->id;
  294. $tot = 0;
  295. foreach ($this->rows as $row) {
  296. foreach ($row["when"] as $x => $y) {
  297. $row["when"][$x]['period'] = $row["when"][$x]['month'] . "-" . $row["when"][$x]['year'];
  298. }
  299. \App\Models\RecordRow::create([
  300. 'record_id' => $this->dataId,
  301. 'causal_id' => $row["causal_id"],
  302. 'note' => $row["note"],
  303. 'amount' => $this->currencyToDouble($row["amount"]),
  304. 'commercial' => $row["commercial"],
  305. 'when' => json_encode($row["when"])
  306. ]);
  307. $tot += $this->currencyToDouble($row["amount"]);
  308. }
  309. $record->amount = $tot;
  310. $record->save();
  311. session()->flash('success', 'Movimento creato');
  312. $this->resetFields();
  313. $this->add = false;
  314. $this->emit('setEdit', false);
  315. } catch (\Exception $ex) {
  316. session()->flash('error', 'Errore (' . $ex->getMessage() . ')');
  317. }
  318. }
  319. public function edit($id)
  320. {
  321. if (!isset($_GET["from"]) && $this->fromPage == '')
  322. $this->fromPage = 'out';
  323. $this->emit('setEdit', true);
  324. $this->emit('load-select');
  325. //if ($this->hasFilter)
  326. $this->emit('hide-search');
  327. try {
  328. $record = \App\Models\Record::findOrFail($id);
  329. if (!$record) {
  330. session()->flash('error', 'Movimento non trovato');
  331. } else {
  332. $this->member_id = $record->member_id;
  333. $this->supplier_id = $record->supplier_id;
  334. //$this->causal_id = $record->causal_id;
  335. $this->payment_method_id = $record->payment_method_id;
  336. $this->date = date("Y-m-d", strtotime($record->date));
  337. //$this->month = $record->month;
  338. //$this->year = $record->year;
  339. //$this->note = $record->note;
  340. $this->type = $record->type;
  341. //$this->amount = formatPrice($record->amount);
  342. $this->commercial = $record->commercial;
  343. $this->dataId = $record->id;
  344. $this->update = true;
  345. $this->add = false;
  346. $this->rows = \App\Models\RecordRow::where('record_id', $this->dataId)->select('causal_id', 'note', 'commercial', 'when', 'amount')->get()->toArray();
  347. foreach ($this->rows as $i => $r) {
  348. $this->rows[$i]['amount'] = formatPrice($this->rows[$i]['amount']);
  349. $this->rows[$i]['when'] = json_decode($this->rows[$i]['when']);
  350. }
  351. }
  352. } catch (\Exception $ex) {
  353. session()->flash('error', 'Errore (' . $ex->getMessage() . ')');
  354. }
  355. }
  356. public function update()
  357. {
  358. $this->emit('refresh');
  359. $this->validate();
  360. try {
  361. \App\Models\Record::whereId($this->dataId)->update([
  362. 'member_id' => $this->member_id,
  363. 'supplier_id' => $this->supplier_id,
  364. //'causal_id' => $this->causal_id,
  365. 'payment_method_id' => $this->payment_method_id,
  366. 'date' => $this->date,
  367. //'month' => $this->month,
  368. //'year' => $this->year,
  369. //'note' => $this->note,
  370. 'type' => $this->type,
  371. //'amount' => $this->currencyToDouble($this->amount),
  372. 'commercial' => $this->commercial,
  373. ]);
  374. $tot = 0;
  375. // Elimino le righe
  376. \App\Models\RecordRow::where('record_id', $this->dataId)->delete();
  377. // Inserisco le righe
  378. foreach ($this->rows as $row) {
  379. foreach ($row["when"] as $x => $y) {
  380. $row["when"][$x]['period'] = $row["when"][$x]['month'] . "-" . $row["when"][$x]['year'];
  381. }
  382. \App\Models\RecordRow::create([
  383. 'record_id' => $this->dataId,
  384. 'causal_id' => $row["causal_id"],
  385. 'note' => $row["note"],
  386. 'amount' => $this->currencyToDouble($row["amount"]),
  387. 'commercial' => $row["commercial"],
  388. 'when' => json_encode($row["when"])
  389. ]);
  390. $tot += $this->currencyToDouble($row["amount"]);
  391. }
  392. $rec = \App\Models\Record::findOrFail($this->dataId);
  393. $rec->amount = $tot;
  394. $rec->save();
  395. session()->flash('success', 'Movimento aggiornato');
  396. $this->resetFields();
  397. $this->update = false;
  398. $this->emit('setEdit', false);
  399. } catch (\Exception $ex) {
  400. session()->flash('error', 'Errore (' . $ex->getMessage() . ')');
  401. }
  402. }
  403. public function cancel()
  404. {
  405. $this->add = false;
  406. $this->update = false;
  407. $this->emit('setEdit', false);
  408. $this->resetFields();
  409. }
  410. public function delete($id)
  411. {
  412. try {
  413. \App\Models\Record::find($id)->delete();
  414. session()->flash('success', "Movimento eliminato");
  415. } catch (\Exception $e) {
  416. session()->flash('error', 'Errore (' . $e->getMessage() . ')');
  417. }
  418. }
  419. public function multipleDelete()
  420. {
  421. try {
  422. foreach ($this->multipleIds as $id) {
  423. \App\Models\Record::find($id)->delete();
  424. }
  425. } catch (\Exception $e) {
  426. session()->flash('error', 'Errore (' . $e->getMessage() . ')');
  427. }
  428. $this->multipleAction = '';
  429. }
  430. /*
  431. public function createReceipt()
  432. {
  433. $receipt = \App\Models\Receipt::where('record_id', $this->dataId)->first();
  434. if ($receipt != null)
  435. {
  436. $receipt->update([
  437. 'member_id' => $this->member_id,
  438. 'supplier_id' => $this->supplier_id,
  439. 'causal_id' => $this->causal_id,
  440. 'payment_method_id' => $this->payment_method_id,
  441. 'date' => date("Y-m-d", strtotime($this->date)),
  442. 'month' => $this->month,
  443. 'year' => $this->year,
  444. 'type' => $this->type,
  445. 'amount' => $this->currencyToDouble($this->amount),
  446. 'commercial' => $this->commercial,
  447. 'status' => 1,
  448. ]);
  449. }
  450. else
  451. {
  452. $number = 1;
  453. $exist = \App\Models\Receipt::where('year', $this->year)->orderBy('number', 'DESC')->first();
  454. if ($exist != null)
  455. $number = $exist->number + 1;
  456. $receipt = \App\Models\Receipt::create([
  457. 'record_id' => $this->dataId,
  458. 'member_id' => $this->member_id,
  459. 'supplier_id' => $this->supplier_id,
  460. 'causal_id' => $this->causal_id,
  461. 'payment_method_id' => $this->payment_method_id,
  462. 'number' => $number,
  463. 'date' => $this->date,
  464. 'month' => $this->month,
  465. 'year' => $this->year,
  466. 'type' => $this->type,
  467. 'amount' => $this->currencyToDouble($this->amount),
  468. 'commercial' => $this->commercial,
  469. 'status' => 1,
  470. ]);
  471. }
  472. }
  473. public function removeReceipt()
  474. {
  475. $receipt = \App\Models\Receipt::findOrFail($this->currentReceip->id);
  476. $receipt->status = 99;
  477. $receipt->save();
  478. $this->currentReceip = $receipt;
  479. }
  480. */
  481. function currencyToDouble($val)
  482. {
  483. $x = str_replace("€", "", $val);
  484. $x = str_replace(".", "", $x);
  485. $x = str_replace(",", ".", $x);
  486. return floatval(trim($x));
  487. }
  488. public function addRow()
  489. {
  490. $this->rows[] = array('causal_id' => null, 'when' => array(array('month' => date("n"), 'year' => date("Y"), 'period' => '')), 'amount' => null, 'note' => '', 'commercial' => 0);
  491. $this->emit('load-select');
  492. }
  493. public function delRow($idx)
  494. {
  495. unset($this->rows[$idx]);
  496. // $this->emit('load-select');
  497. }
  498. public function addPeriod($idx)
  499. {
  500. $x = sizeof($this->rows[$idx]['when']) - 1;
  501. $newDate = \Carbon\Carbon::create($this->rows[$idx]['when'][$x]["year"] . "-" . $this->rows[$idx]['when'][$x]["month"] . '-01')->addMonth();
  502. $this->rows[$idx]['when'][] = array('month' => $newDate->format("n"), 'year' => $newDate->format("Y"), 'period' => '');
  503. //$this->rows[$idx]['when'][] = array('month' => date("n"), 'year' => date("Y"), 'period' => '');
  504. }
  505. public function delPeriod($idx, $xxx)
  506. {
  507. array_splice($this->rows[$idx]['when'], $xxx, 1);
  508. // $this->emit('load-select');
  509. }
  510. public function getTotal()
  511. {
  512. $total = 0.00;
  513. foreach ($this->rows as $r) {
  514. $total += $this->currencyToDouble($r["amount"] != null ? $r["amount"] : 0);
  515. }
  516. return formatPrice($total);
  517. // $this->emit('load-select');
  518. }
  519. public function setCausal($id, $idx)
  520. {
  521. $this->rows[$idx]["causal_id"] = $id;
  522. }
  523. public function multiPeriod()
  524. {
  525. $this->multiP = true;
  526. }
  527. public function multiPeriodCreate($idx)
  528. {
  529. $period = \Carbon\CarbonPeriod::create($this->multiYearFrom . '-' . $this->multiMonthFrom . '-01', '1 month', $this->multiYearTo . '-' . $this->multiMonthTo . '-01');
  530. $this->rows[$idx]['when'] = [];
  531. foreach ($period as $dt) {
  532. if (!in_array(array('month' => $dt->format("n"), 'year' => $dt->format("Y"), 'period' => ''), $this->rows[$idx]['when']))
  533. $this->rows[$idx]['when'][] = array('month' => $dt->format("n"), 'year' => $dt->format("Y"), 'period' => '');
  534. }
  535. $this->multiP = false;
  536. }
  537. public function multiPeriodCancel()
  538. {
  539. $this->multiP = false;
  540. }
  541. public function importReceipts()
  542. {
  543. $this->validate([
  544. 'receiptFiles.*' => 'required|mimes:xml|max:2048',
  545. 'selectedCausal' => 'required|exists:causals,id',
  546. ]);
  547. try {
  548. $importCount = 0;
  549. $errorsCount = 0;
  550. $totalFiles = count($this->receiptFiles);
  551. // disabilita select
  552. $this->emit('import-started');
  553. foreach ($this->receiptFiles as $index => $receiptFile) {
  554. try {
  555. // Carica e analizza il file XML
  556. $xmlString = file_get_contents($receiptFile->getRealPath());
  557. $xml = simplexml_load_string($xmlString);
  558. if (!$xml) {
  559. throw new \Exception("Impossibile analizzare il file XML");
  560. }
  561. // Estrai i dati dalla fattura elettronica
  562. $fatturaData = $this->extractFatturaData($xml);
  563. // Trova o crea il fornitore
  564. $supplier = $this->findOrCreateSupplier($fatturaData);
  565. // Trova il metodo di pagamento
  566. $paymentMethodId = $this->findPaymentMethod($fatturaData['modalitaPagamento']);
  567. // Crea il record principale
  568. $record = $this->createRecord($supplier->id, $paymentMethodId, $fatturaData);
  569. // Crea il record row
  570. $this->createRecordRow($record->id, $fatturaData);
  571. // Crea la ricevuta
  572. $receipt = $this->createReceipt($record->id, $supplier->id, $paymentMethodId, $fatturaData);
  573. // Crea le righe della ricevuta
  574. $this->createReceiptRows($receipt->id, $fatturaData);
  575. $importCount++;
  576. Log::info("Fattura importata con successo: {$fatturaData['numeroFattura']}, Fornitore: {$fatturaData['denominazione']}");
  577. } catch (\Exception $e) {
  578. Log::error('Errore durante l\'importazione della fattura: ' . $e->getMessage());
  579. $errorsCount++;
  580. }
  581. $progress = ($index + 1) / $totalFiles * 100;
  582. $this->emit('update-progress', $progress);
  583. }
  584. $this->showResultMessages($importCount, $errorsCount);
  585. } catch (\Exception $e) {
  586. Log::error('Errore durante l\'importazione dei file XML: ' . $e->getMessage());
  587. session()->flash('error', 'Errore durante l\'importazione: ' . $e->getMessage());
  588. } finally {
  589. $this->emit('import-finished');
  590. $this->closeImportModal();
  591. $this->emit('load-data-table');
  592. }
  593. }
  594. /**
  595. * Estrae i dati dalla fattura elettronica XML
  596. */
  597. private function extractFatturaData($xml)
  598. {
  599. $data = [];
  600. try {
  601. // Stampa la struttura XML per debug
  602. Log::info("Nomi dei children dell'elemento radice: " . implode(", ", array_map(function ($node) {
  603. return $node->getName();
  604. }, iterator_to_array($xml->children()))));
  605. $headerNode = $xml->FatturaElettronicaHeader;
  606. $bodyNode = $xml->FatturaElettronicaBody;
  607. if (!$headerNode || !$bodyNode) {
  608. throw new \Exception("Struttura XML non standard, FatturaElettronicaHeader o FatturaElettronicaBody non trovati");
  609. }
  610. // Estrai dati del fornitore (cedente/prestatore)
  611. $cedenteNode = $headerNode->CedentePrestatore;
  612. $datiAnagrafici = $cedenteNode->DatiAnagrafici;
  613. $idFiscaleIVA = $datiAnagrafici->IdFiscaleIVA;
  614. $data['idPaese'] = (string)$idFiscaleIVA->IdPaese;
  615. $data['idCodice'] = (string)$idFiscaleIVA->IdCodice;
  616. $data['partitaIva'] = $data['idPaese'] . $data['idCodice'];
  617. $data['codiceFiscale'] = (string)$datiAnagrafici->CodiceFiscale;
  618. $data['denominazione'] = (string)$datiAnagrafici->Anagrafica->Denominazione;
  619. // Estrai dati della sede
  620. $sede = $cedenteNode->Sede;
  621. $data['indirizzo'] = (string)$sede->Indirizzo;
  622. $data['cap'] = (string)$sede->CAP;
  623. $data['comune'] = (string)$sede->Comune;
  624. $data['provincia'] = (string)$sede->Provincia;
  625. $data['nazione'] = (string)$sede->Nazione ?: 'IT';
  626. // Email, se presente
  627. $data['email'] = '';
  628. if (isset($cedenteNode->Contatti) && isset($cedenteNode->Contatti->Email)) {
  629. $data['email'] = (string)$cedenteNode->Contatti->Email;
  630. }
  631. // Dati generali della fattura
  632. $datiGeneraliDocumento = $bodyNode->DatiGenerali->DatiGeneraliDocumento;
  633. $data['tipoDocumento'] = (string)$datiGeneraliDocumento->TipoDocumento;
  634. $data['divisa'] = (string)$datiGeneraliDocumento->Divisa ?: 'EUR';
  635. $data['dataDocumento'] = (string)$datiGeneraliDocumento->Data;
  636. $data['numeroFattura'] = (string)$datiGeneraliDocumento->Numero;
  637. $data['importoTotale'] = (float)$datiGeneraliDocumento->ImportoTotaleDocumento;
  638. // Dati di pagamento
  639. $data['condizioniPagamento'] = '';
  640. $data['modalitaPagamento'] = '';
  641. $data['dataScadenza'] = '';
  642. $data['iban'] = '';
  643. $data['bic'] = '';
  644. $data['istitutoFinanziario'] = '';
  645. if (isset($bodyNode->DatiPagamento)) {
  646. $datiPagamento = $bodyNode->DatiPagamento;
  647. $data['condizioniPagamento'] = (string)$datiPagamento->CondizioniPagamento;
  648. if (isset($datiPagamento->DettaglioPagamento)) {
  649. $dettaglioPagamento = $datiPagamento->DettaglioPagamento;
  650. $data['modalitaPagamento'] = (string)$dettaglioPagamento->ModalitaPagamento;
  651. $data['dataScadenza'] = (string)$dettaglioPagamento->DataScadenzaPagamento;
  652. $data['iban'] = (string)$dettaglioPagamento->IBAN;
  653. $data['bic'] = (string)$dettaglioPagamento->BIC;
  654. $data['istitutoFinanziario'] = (string)$dettaglioPagamento->IstitutoFinanziario;
  655. }
  656. }
  657. // Estrai le linee di dettaglio
  658. $data['linee'] = [];
  659. if (isset($bodyNode->DatiBeniServizi) && isset($bodyNode->DatiBeniServizi->DettaglioLinee)) {
  660. foreach ($bodyNode->DatiBeniServizi->DettaglioLinee as $index => $linea) {
  661. $lineaData = [
  662. 'numeroLinea' => (int)($linea->NumeroLinea ?? ($index + 1)),
  663. 'descrizione' => (string)($linea->Descrizione ?? ''),
  664. 'quantita' => (float)($linea->Quantita ?? 1),
  665. 'prezzoUnitario' => (float)($linea->PrezzoUnitario ?? 0),
  666. 'prezzoTotale' => (float)($linea->PrezzoTotale ?? 0),
  667. 'aliquotaIva' => (float)($linea->AliquotaIVA ?? 0),
  668. ];
  669. // Calcola il prezzo totale se non presente
  670. if ($lineaData['prezzoTotale'] == 0) {
  671. $lineaData['prezzoTotale'] = $lineaData['quantita'] * $lineaData['prezzoUnitario'];
  672. }
  673. $data['linee'][] = $lineaData;
  674. }
  675. }
  676. $data['riepilogo'] = null;
  677. if (isset($bodyNode->DatiBeniServizi) && isset($bodyNode->DatiBeniServizi->DatiRiepilogo)) {
  678. $riepilogoNode = $bodyNode->DatiBeniServizi->DatiRiepilogo;
  679. if ($riepilogoNode) {
  680. $data['riepilogo'] = [
  681. 'aliquotaIva' => (float)($riepilogoNode->AliquotaIVA ?? 0),
  682. 'imponibile' => (float)($riepilogoNode->ImponibileImporto ?? 0),
  683. 'imposta' => (float)($riepilogoNode->Imposta ?? 0),
  684. ];
  685. }
  686. }
  687. Log::info("Dati estratti dalla fattura: P.IVA={$data['partitaIva']}, Denominazione={$data['denominazione']}, Numero={$data['numeroFattura']}, Importo={$data['importoTotale']}");
  688. return $data;
  689. } catch (\Exception $e) {
  690. Log::error("Errore nell'estrazione dei dati XML: " . $e->getMessage());
  691. throw $e;
  692. }
  693. }
  694. /**
  695. * Trova o crea un fornitore basato sui dati della fattura
  696. */
  697. private function findOrCreateSupplier($fatturaData)
  698. {
  699. $supplier = \App\Models\Supplier::where('vat', $fatturaData['partitaIva'])->first();
  700. if (!$supplier) {
  701. Log::info("Creazione nuovo fornitore con P.IVA: {$fatturaData['partitaIva']} ({$fatturaData['denominazione']})");
  702. $countryId = $this->getCountryId($fatturaData['nazione']);
  703. $provinceId = $this->getProvinceId($fatturaData['provincia']);
  704. $cityId = $this->getCityId($fatturaData['comune']);
  705. $supplier = new \App\Models\Supplier();
  706. $supplier->name = $fatturaData['denominazione'];
  707. $supplier->vat = $fatturaData['partitaIva'];
  708. $supplier->fiscal_code = $fatturaData['codiceFiscale'];
  709. $supplier->address = $fatturaData['indirizzo'];
  710. $supplier->city_id = $cityId;
  711. $supplier->zip_code = $fatturaData['cap'];
  712. $supplier->province_id = $provinceId;
  713. $supplier->nation_id = $countryId;
  714. $supplier->email = $fatturaData['email'];
  715. $supplier->save();
  716. Log::info("Fornitore creato con ID: " . $supplier->id);
  717. }
  718. return $supplier;
  719. }
  720. /**
  721. * Trova l'ID della nazione dal codice
  722. */
  723. private function getCountryId($nationCode)
  724. {
  725. $country = DB::table('nations')->where('code', $nationCode)->first();
  726. return $country ? $country->id : null;
  727. }
  728. /**
  729. * Trova l'ID della provincia dal codice
  730. */
  731. private function getProvinceId($provinceCode)
  732. {
  733. $province = DB::table('provinces')->where('code', $provinceCode)->first();
  734. return $province ? $province->id : null;
  735. }
  736. /**
  737. * Trova l'ID della città dal nome
  738. */
  739. private function getCityId($cityName)
  740. {
  741. if (empty($cityName)) return null;
  742. $city = DB::table('cities')->where('name', $cityName)->first();
  743. return $city ? $city->id : null;
  744. }
  745. /**
  746. * Trova l'ID del metodo di pagamento dal codice
  747. */
  748. private function findPaymentMethod($paymentCode)
  749. {
  750. if (!empty($paymentCode)) {
  751. $paymentMethod = DB::table('payment_methods')->where('code', $paymentCode)->first();
  752. if ($paymentMethod) {
  753. Log::info("Metodo di pagamento trovato: $paymentCode (ID: {$paymentMethod->id})");
  754. return $paymentMethod->id;
  755. }
  756. }
  757. $defaultPaymentMethod = DB::table('payment_methods')->where('default', 1)->first()
  758. ?? DB::table('payment_methods')->first();
  759. if ($defaultPaymentMethod) {
  760. Log::info("Usando metodo di pagamento predefinito ID: {$defaultPaymentMethod->id}");
  761. return $defaultPaymentMethod->id;
  762. }
  763. throw new \Exception("Nessun metodo di pagamento disponibile nel sistema");
  764. }
  765. /**
  766. * Crea un record nella tabella records
  767. */
  768. private function createRecord($supplierId, $paymentMethodId, $fatturaData)
  769. {
  770. $record = new \App\Models\Record();
  771. $record->supplier_id = $supplierId;
  772. $record->payment_method_id = $paymentMethodId;
  773. $record->date = $fatturaData['dataDocumento'];
  774. $record->type = 'OUT';
  775. $record->commercial = 1;
  776. $record->corrispettivo_fiscale = 0;
  777. $record->deleted = 0;
  778. $record->financial_movement = 1;
  779. $record->amount = $fatturaData['importoTotale'];
  780. $record->save();
  781. Log::info("Record creato con ID: " . $record->id);
  782. return $record;
  783. }
  784. /**
  785. * Crea un record row per il record specificato
  786. */
  787. private function createRecordRow($recordId, $fatturaData)
  788. {
  789. Log::info("Inizio creazione RecordRow per Record ID: " . $recordId);
  790. $dataObj = new \DateTime($fatturaData['dataDocumento']);
  791. $month = $dataObj->format('n');
  792. $year = $dataObj->format('Y');
  793. $period = "$month-$year";
  794. $whenData = [[
  795. 'month' => $month,
  796. 'year' => $year,
  797. 'period' => $period
  798. ]];
  799. Log::info("Dati whenData: " . json_encode($whenData));
  800. $recordRow = new \App\Models\RecordRow();
  801. $recordRow->record_id = $recordId;
  802. $recordRow->causal_id = $this->selectedCausal;
  803. $recordRow->when = json_encode($whenData);
  804. $recordRow->amount = $fatturaData['importoTotale'];
  805. $recordRow->commercial = 1;
  806. $noteData = '';
  807. if (isset($fatturaData['linee']) && is_array($fatturaData['linee'])) {
  808. $descriptions = array_map(function ($linea) {
  809. return $linea['descrizione'];
  810. }, $fatturaData['linee']);
  811. $noteData = implode(', ', $descriptions);
  812. }
  813. $recordRow->note = $noteData;
  814. Log::info("Dati RecordRow prima del salvataggio: " . json_encode([
  815. 'record_id' => $recordRow->record_id,
  816. 'causal_id' => $recordRow->causal_id,
  817. 'when' => $recordRow->when,
  818. 'amount' => $recordRow->amount,
  819. 'commercial' => $recordRow->commercial,
  820. 'note' => $recordRow->note
  821. ]));
  822. $recordRow->save();
  823. Log::info("RecordRow creato per il Record ID: " . $recordId);
  824. return $recordRow;
  825. }
  826. /**
  827. * Crea una ricevuta collegata al record
  828. */
  829. private function createReceipt($recordId, $supplierId, $paymentMethodId, $fatturaData)
  830. {
  831. Log::info("Inizio creazione ricevuta per Record ID: " . $recordId);
  832. $receipt = new \App\Models\Receipt();
  833. $receipt->record_id = $recordId;
  834. $receipt->supplier_id = $supplierId;
  835. $receipt->payment_method_id = $paymentMethodId;
  836. $receipt->date = $fatturaData['dataDocumento'];
  837. $receipt->data_documento = $fatturaData['dataDocumento'];
  838. $receipt->numero_fattura = $fatturaData['numeroFattura'];
  839. $receipt->number = preg_replace('/[^0-9]/', '', $fatturaData['numeroFattura']);
  840. $receipt->tipo_documento = $this->mapTipoDocumento($fatturaData['tipoDocumento']);
  841. $receipt->year = date('Y', strtotime($fatturaData['dataDocumento']));
  842. $receipt->type = 'OUT';
  843. $receipt->status = 1;
  844. $receipt->is_ricevuta = true;
  845. if (isset($fatturaData['condizioniPagamento']) && !empty($fatturaData['condizioniPagamento'])) {
  846. $receipt->condizioni_pagamento = $this->mapCondizioniPagamento($fatturaData['condizioniPagamento']);
  847. }
  848. if (isset($fatturaData['iban']) && !empty($fatturaData['iban'])) {
  849. $receipt->IBAN = $fatturaData['iban'];
  850. }
  851. if (isset($fatturaData['bic']) && !empty($fatturaData['bic'])) {
  852. $receipt->BIC = $fatturaData['bic'];
  853. }
  854. if (isset($fatturaData['dataScadenza']) && !empty($fatturaData['dataScadenza'])) {
  855. $receipt->data_scadenza = $fatturaData['dataScadenza'];
  856. }
  857. Log::info("Dati ricevuta prima del salvataggio: " . json_encode([
  858. 'record_id' => $receipt->record_id,
  859. 'supplier_id' => $receipt->supplier_id,
  860. 'payment_method_id' => $receipt->payment_method_id,
  861. 'date' => $receipt->date,
  862. 'number' => $receipt->number,
  863. 'tipo_documento' => $receipt->tipo_documento,
  864. 'year' => $receipt->year,
  865. 'type' => $receipt->type,
  866. 'status' => $receipt->status,
  867. ]));
  868. $receipt->save();
  869. Log::info("Ricevuta creata con ID: " . $receipt->id);
  870. return $receipt;
  871. }
  872. private function createReceiptRows($receiptId, $fatturaData)
  873. {
  874. Log::info("Inizio creazione righe ricevuta per Ricevuta ID: " . $receiptId);
  875. if (!empty($fatturaData['linee'])) {
  876. foreach ($fatturaData['linee'] as $linea) {
  877. $this->createSingleReceiptRow($receiptId, $fatturaData, $linea);
  878. }
  879. } else if ($fatturaData['riepilogo']) {
  880. $this->createReceiptRowFromRiepilogo($receiptId, $fatturaData);
  881. Log::info("Creata una riga di ricevuta dai dati di riepilogo");
  882. } else {
  883. $this->createDefaultReceiptRow($receiptId, $fatturaData);
  884. Log::info("Creata una riga di ricevuta predefinita dall'importo totale");
  885. }
  886. }
  887. private function createSingleReceiptRow($receiptId, $fatturaData, $linea)
  888. {
  889. Log::info("Inizio creazione riga ricevuta singola per Ricevuta ID: " . $receiptId . ", Linea: " . json_encode($linea));
  890. $dataObj = new \DateTime($fatturaData['dataDocumento']);
  891. $month = $dataObj->format('n');
  892. $year = $dataObj->format('Y');
  893. $period = "$month-$year";
  894. $whenData = [[
  895. 'month' => $month,
  896. 'year' => $year,
  897. 'period' => $period
  898. ]];
  899. $receiptRow = new \App\Models\ReceiptRow();
  900. $receiptRow->receip_id = $receiptId;
  901. $receiptRow->causal_id = $this->selectedCausal;
  902. $receiptRow->amount = $linea['prezzoTotale'];
  903. $receiptRow->note = $linea['descrizione'];
  904. $receiptRow->commercial = 1;
  905. $receiptRow->when = json_encode($whenData);
  906. $receiptRow->aliquota_iva = $linea['aliquotaIva'];
  907. $receiptRow->imponibile = $linea['prezzoTotale'];
  908. $receiptRow->imposta = $linea['prezzoTotale'] * ($linea['aliquotaIva'] / 100);
  909. $receiptRow->divisa = $fatturaData['divisa'];
  910. $receiptRow->numero_linea = $linea['numeroLinea'];
  911. $receiptRow->prezzo_unitario = $linea['prezzoUnitario'];
  912. $receiptRow->quantita = $linea['quantita'];
  913. Log::info("Dati riga ricevuta prima del salvataggio: " . json_encode([
  914. 'receip_id' => $receiptRow->receip_id,
  915. 'causal_id' => $receiptRow->causal_id,
  916. 'amount' => $receiptRow->amount,
  917. 'note' => $receiptRow->note,
  918. 'aliquota_iva' => $receiptRow->aliquota_iva,
  919. 'imponibile' => $receiptRow->imponibile,
  920. 'imposta' => $receiptRow->imposta,
  921. 'divisa' => $receiptRow->divisa,
  922. 'numero_linea' => $receiptRow->numero_linea,
  923. 'prezzo_unitario' => $receiptRow->prezzo_unitario,
  924. 'quantita' => $receiptRow->quantita,
  925. ]));
  926. $receiptRow->save();
  927. Log::info("Riga ricevuta creata per linea {$linea['numeroLinea']}: {$linea['descrizione']} (€{$linea['prezzoTotale']})");
  928. }
  929. private function createReceiptRowFromRiepilogo($receiptId, $fatturaData)
  930. {
  931. Log::info("Inizio creazione riga ricevuta da riepilogo per Ricevuta ID: " . $receiptId . ", Riepilogo: " . json_encode($fatturaData['riepilogo']));
  932. $riepilogo = $fatturaData['riepilogo'];
  933. $dataObj = new \DateTime($fatturaData['dataDocumento']);
  934. $month = $dataObj->format('n');
  935. $year = $dataObj->format('Y');
  936. $period = "$month-$year";
  937. $whenData = [[
  938. 'month' => $month,
  939. 'year' => $year,
  940. 'period' => $period
  941. ]];
  942. $receiptRow = new \App\Models\ReceiptRow();
  943. $receiptRow->receip_id = $receiptId;
  944. $receiptRow->causal_id = $this->selectedCausal;
  945. $receiptRow->amount = $riepilogo['imponibile'];
  946. $receiptRow->commercial = 1;
  947. $receiptRow->when = json_encode($whenData);
  948. $receiptRow->aliquota_iva = $riepilogo['aliquotaIva'];
  949. $receiptRow->imponibile = $riepilogo['imponibile'];
  950. $receiptRow->imposta = $riepilogo['imposta'];
  951. $receiptRow->divisa = $fatturaData['divisa'];
  952. $receiptRow->numero_linea = 1;
  953. $receiptRow->quantita = 1;
  954. Log::info("Dati riga ricevuta da riepilogo prima del salvataggio: " . json_encode([
  955. 'receip_id' => $receiptRow->receip_id,
  956. 'causal_id' => $receiptRow->causal_id,
  957. 'amount' => $receiptRow->amount,
  958. 'aliquota_iva' => $receiptRow->aliquota_iva,
  959. 'imponibile' => $receiptRow->imponibile,
  960. 'imposta' => $receiptRow->imposta,
  961. 'divisa' => $receiptRow->divisa,
  962. ]));
  963. $receiptRow->save();
  964. Log::info("Riga ricevuta creata da riepilogo: Imponibile={$riepilogo['imponibile']}, IVA={$riepilogo['aliquotaIva']}%");
  965. }
  966. private function createDefaultReceiptRow($receiptId, $fatturaData)
  967. {
  968. Log::info("Inizio creazione riga ricevuta predefinita per Ricevuta ID: " . $receiptId . ", Importo Totale: " . $fatturaData['importoTotale']);
  969. $dataObj = new \DateTime($fatturaData['dataDocumento']);
  970. $month = $dataObj->format('n');
  971. $year = $dataObj->format('Y');
  972. $period = "$month-$year";
  973. $whenData = [[
  974. 'month' => $month,
  975. 'year' => $year,
  976. 'period' => $period
  977. ]];
  978. $receiptRow = new \App\Models\ReceiptRow();
  979. $receiptRow->receip_id = $receiptId;
  980. $receiptRow->causal_id = $this->selectedCausal;
  981. $receiptRow->amount = $fatturaData['importoTotale'];
  982. $receiptRow->commercial = 1;
  983. $receiptRow->when = json_encode($whenData);
  984. $receiptRow->divisa = $fatturaData['divisa'];
  985. $receiptRow->numero_linea = 1;
  986. $receiptRow->quantita = 1;
  987. Log::info("Dati riga ricevuta predefinita prima del salvataggio: " . json_encode([
  988. 'receip_id' => $receiptRow->receip_id,
  989. 'causal_id' => $receiptRow->causal_id,
  990. 'amount' => $receiptRow->amount,
  991. 'divisa' => $receiptRow->divisa,
  992. ]));
  993. $receiptRow->save();
  994. Log::info("Riga ricevuta predefinita creata con importo totale: {$fatturaData['importoTotale']}");
  995. }
  996. private function mapTipoDocumento($codice)
  997. {
  998. $tipiDocumento = [
  999. 'TD01' => 'Fattura',
  1000. 'TD02' => 'Acconto/Anticipo su fattura',
  1001. 'TD03' => 'Acconto/Anticipo su parcella',
  1002. 'TD04' => 'Nota di credito',
  1003. 'TD05' => 'Nota di debito',
  1004. 'TD06' => 'Parcella',
  1005. 'TD16' => 'Integrazione fattura reverse charge interno',
  1006. 'TD17' => 'Integrazione/autofattura per acquisto servizi dall\'estero',
  1007. 'TD18' => 'Integrazione per acquisto di beni intracomunitari',
  1008. 'TD19' => 'Integrazione/autofattura per acquisto di beni ex art.17 c.2 DPR 633/72',
  1009. 'TD20' => 'Autofattura per regolarizzazione e integrazione delle fatture',
  1010. 'TD21' => 'Autofattura per splafonamento',
  1011. 'TD22' => 'Estrazione beni da Deposito IVA',
  1012. 'TD23' => 'Estrazione beni da Deposito IVA con versamento dell\'IVA',
  1013. 'TD24' => 'Fattura differita di cui all\'art.21, comma 4, lett. a)',
  1014. 'TD25' => 'Fattura differita di cui all\'art.21, comma 4, terzo periodo lett. b)',
  1015. 'TD26' => 'Cessione di beni ammortizzabili e per passaggi interni',
  1016. 'TD27' => 'Fattura per autoconsumo o per cessioni gratuite senza rivalsa'
  1017. ];
  1018. return $tipiDocumento[$codice] ?? $codice;
  1019. }
  1020. private function mapCondizioniPagamento($codice)
  1021. {
  1022. $condizioniPagamento = [
  1023. 'TP01' => 'Pagamento a rate',
  1024. 'TP02' => 'Pagamento completo',
  1025. 'TP03' => 'Anticipo'
  1026. ];
  1027. return $condizioniPagamento[$codice] ?? $codice;
  1028. }
  1029. private function showResultMessages($importCount, $errorsCount)
  1030. {
  1031. if ($importCount > 0) {
  1032. $message = "Importate $importCount fatture con successo.";
  1033. if ($errorsCount > 0) {
  1034. $message .= " $errorsCount fatture non sono state importate.";
  1035. }
  1036. session()->flash('message', $message);
  1037. } else {
  1038. session()->flash('error', 'Nessuna fattura importata. Controlla i file XML e riprova.');
  1039. }
  1040. }
  1041. }