| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399 |
- <?php
- namespace App\Http\Livewire;
- use Livewire\Component;
- use Illuminate\Support\Facades\Auth;
- use Illuminate\Support\Facades\Log;
- use SimpleXMLElement;
- use Livewire\WithFileUploads;
- use Illuminate\Support\Facades\DB;
- use Illuminate\Support\Facades\Schema;
- class RecordOUT extends Component
- {
- use WithFileUploads;
- protected $listeners = [
- 'setCausal' => 'setCausal',
- 'closeImportModal' => 'closeImportModal',
- ];
- public $sortField = 'date';
- public $sortAsc = false;
- public $typeOUT = "OUT";
- public $fromPage = '';
- public $multiP = false;
- public $multiMonthTo = 0;
- public $multiYearTo = 0;
- public $multiMonthFrom = 0;
- public $multiYearFrom = 0;
- public function sortBy($field)
- {
- if ($this->sortField === $field) {
- $this->sortAsc = ! $this->sortAsc;
- } else {
- $this->sortAsc = true;
- }
- $this->sortField = $field;
- }
- public $records, $dataId, $member_id, $supplier_id,
- $causal_id,
- $payment_method_id,
- $date,
- $data_pagamento,
- $month,
- $year,
- $type,
- $amount,
- $note,
- $commercial, $update = false, $add = false;
- public $attachment;
- public $filterSupplier = 0, $filterPaymentMethod = 0, $filterCausals = [], $filterFrom = '', $filterTo = '', $filterCommercial = 0;
- public $hasFilter = false;
- public $total = 0;
- public $selectedFilter = '';
- public $multipleIds = [];
- public $multipleAction = '';
- public $selectId = 0;
- public $causals = array();
- public $payments = array();
- public $suppliers = array();
- public $rows = array();
- public $receiptFiles = [];
- public $selectedCausal = '';
- public $importCausals = array();
- protected $rules = [
- 'supplier_id' => 'required',
- 'payment_method_id' => 'required',
- 'rows.*.causal_id' => 'required',
- 'rows.*.amount' => 'required'
- //'causal_id' => 'required',
- //'amount' => 'required'
- ];
- protected $messages = [
- 'supplier_id.required' => 'Il fornitore è obbligatorio',
- 'payment_method_id.required' => 'Il metodo di pagamento è obbligatorio',
- 'rows.*.amount.required' => 'L\'importo è obbligatorio',
- 'rows.*.causal_id.required' => 'La causale è obbligatoria'
- ];
- public function getSupplierProperty()
- {
- $ret = null;
- if ($this->supplier_id > 0) {
- $ret = \App\Models\Supplier::findOrFail($this->supplier_id);
- }
- return $ret;
- }
- public function getCausalProperty()
- {
- $ret = null;
- if ($this->causal_id > 0) {
- $ret = \App\Models\Causal::findOrFail($this->causal_id);
- }
- return $ret;
- }
- public function resetFields()
- {
- $this->member_id = null;
- $this->supplier_id = null;
- //$this->causal_id = null;
- $this->payment_method_id = null;
- $this->date = date("Y-m-d");
- $this->data_pagamento = date("Y-m-d");
- //$this->month = date("n");
- //$this->year = date("Y");
- $this->type = 'OUT';
- //$this->note = '';
- //$this->amount = null;
- $this->commercial = 1;
- $this->rows = array();
- $this->rows[] = array(
- 'causal_id' => null,
- 'when' => array(array('month' => date("n"), 'year' => date("Y"), 'period' => '')),
- 'amount' => null,
- 'imponibile' => null,
- 'aliquota_iva' => null,
- 'note' => '',
- 'commercial' => 0
- );
- $this->emit('load-data-table');
- }
- public function getCausale($records, $indentation)
- {
- foreach ($records as $record) {
- $this->causals[] = array('id' => $record->id, 'name' => $record->getTree());
- if (count($record->childs))
- $this->getCausale($record->childs, $indentation + 1);
- }
- }
- public $isImportModalOpen = false;
- public function openImportModal()
- {
- $this->isImportModalOpen = true;
- }
- public function closeImportModal()
- {
- $this->isImportModalOpen = false;
- $this->reset(['selectedCausal', 'receiptFiles']);
- $this->resetValidation();
- $this->dispatchBrowserEvent('closeModal');
- }
- public function hydrate()
- {
- $this->emit('load-select');
- if (empty($this->importCausals)) {
- $this->loadImportCausals();
- }
- }
- public function mount()
- {
- if (isset($_GET["from"])) {
- $this->fromPage = $_GET["from"];
- }
- if (Auth::user()->level != env('LEVEL_ADMIN', 0))
- return redirect()->to('/dashboard');
- $this->multiMonthFrom = date("n");
- $this->multiYearFrom = date("Y");
- $this->multiMonthTo = date("n");
- $this->multiYearTo = date("Y");
- if (isset($_GET["new"]))
- $this->add();
- $this->causals = array();
- $this->getCausale(\App\Models\Causal::select('id', 'name')->where('parent_id', null)->where('type', 'OUT')->orderBy('name')->get(), 0);
- $this->suppliers = \App\Models\Supplier::select('name', 'id')->orderBy('name')->get();
- $this->payments = \App\Models\PaymentMethod::select('id', 'name')->whereIn('type', array('ALL', 'OUT'))->where('enabled', true)->orderBy('name')->get();
- $this->importCausals = [];
- $this->loadImportCausals();
- }
- public function loadImportCausals()
- {
- $causals = \App\Models\Causal::select('id', 'name', 'parent_id')
- ->where('type', 'OUT')
- ->orderBy('name')
- ->get();
- $this->importCausals = [];
- $this->buildCausalTree($causals);
- }
- private function buildCausalTree($causals, $parentId = null, $level = 0)
- {
- foreach ($causals as $causal) {
- if ($causal->parent_id == $parentId) {
- $dotString = str_repeat('● ', $level);
- $this->importCausals[] = [
- 'id' => $causal->id,
- 'name' => $dotString . $causal->name
- ];
- $this->buildCausalTree($causals, $causal->id, $level + 1);
- }
- }
- }
- private function getCausalLevel($causal, $level = 0)
- {
- if ($causal->parent_id == null) {
- return $level;
- }
- $parent = \App\Models\Causal::find($causal->parent_id);
- if (!$parent) {
- return $level;
- }
- return $this->getCausalLevel($parent, $level + 1);
- }
- public function getCausal($causal)
- {
- $ret = '';
- if ($causal > 0) {
- $ret = \App\Models\Causal::findOrFail($causal)->getTree();
- }
- return $ret;
- }
- public function search()
- {
- $this->hasFilter = true;
- }
- public function disableSearch()
- {
- $this->filterSupplier = 0;
- $this->filterPaymentMethod = 0;
- $this->filterCausals = [];
- $this->filterTo = '';
- $this->filterFrom = '';
- $this->filterCommercial = 0;
- $this->hasFilter = false;
- $this->hasFilter = false;
- }
- public function render()
- {
- $datas = [];
- if (false) {
- if ($this->hasFilter) {
- $datas = \App\Models\Record::where('type', 'OUT')->with('supplier', 'payment_method');
- /*if ($this->filterCommercial > 0)
- {
- $datas = $datas->where('commercial', $this->filterCommercial == 1 ? true : false);
- }*/
- if ($this->filterSupplier > 0) {
- $datas = $datas->where('supplier_id', $this->filterSupplier);
- }
- if ($this->filterPaymentMethod > 0) {
- $datas = $datas->where('payment_method_id', $this->filterPaymentMethod);
- }
- /*if (sizeof($this->filterCausals) > 0)
- {
- $datas = $datas->whereIn('causal_id', $this->filterCausals);
- }*/
- if ($this->filterFrom != '') {
- $datas = $datas->where('date', '>=', $this->filterFrom);
- }
- if ($this->filterTo != '') {
- $datas = $datas->where('date', '<=', $this->filterTo);
- }
- //$this->records = $datas->orderBy('date', 'DESC')->get();
- $this->records = $datas->get();
- //$this->total = $this->records->sum('amount');
- $this->total = 0;
- foreach ($this->records as $r) {
- foreach ($r->rows as $rr) {
- $this->total += $rr->amount;
- }
- }
- } else {
- if ($this->selectedFilter == '') {
- $this->records = \App\Models\Record::where('type', 'OUT')->with('supplier', 'payment_method')->limit(20)->orderBy('date', 'DESC')->orderBy('id', 'DESC')->get();
- } else {
- if ($this->selectedFilter == 0) {
- $fromDate = date("Y-m-d");
- $toDate = date("Y-m-d");
- }
- if ($this->selectedFilter == 1) {
- $fromDate = date("Y-m-01");
- $toDate = date("Y-m-t");
- }
- if ($this->selectedFilter == 2) {
- $fromDate = date("Y-01-01");
- $toDate = date("Y-12-31");
- }
- if ($this->selectedFilter == 3) {
- $fromDate = date("2000-01-01");
- $toDate = date("Y-12-31");
- }
- $this->records = \App\Models\Record::where('type', 'OUT')->whereBetween('date', [$fromDate, $toDate])->with('supplier', 'payment_method')->get();
- }
- }
- foreach ($this->records as $r) {
- $r->total = $r->getTotal();
- $r->supplier = $r->supplier ? $r->supplier->name : '';
- $r->payment = $r->payment_method ? $r->payment_method->name : '';
- }
- }
- /*if ($this->sortField != '')
- {
- if ($this->sortAsc)
- $this->records = $this->records->sortBy($this->sortField);
- else
- $this->records = $this->records->sortByDesc($this->sortField);
- }
- else
- $this->records = $this->records->sortByDesc('id');*/
- return view('livewire.records_out');
- }
- public function executeMultipleAction()
- {
- if ($this->multipleAction == 'delete')
- $this->multipleDelete();
- }
- public function add()
- {
- $this->emit('load-select');
- //if ($this->hasFilter)
- $this->emit('hide-search');
- $this->resetFields();
- $this->add = true;
- $this->update = false;
- $this->emit('setEdit', true);
- }
- public function store()
- {
- $this->emit('refresh');
- $this->validate();
- try {
- $record = \App\Models\Record::create([
- 'member_id' => $this->member_id,
- 'supplier_id' => $this->supplier_id,
- //'causal_id' => $this->causal_id,
- 'payment_method_id' => $this->payment_method_id,
- 'date' => $this->date,
- 'data_pagamento' => $this->data_pagamento,
- //'month' => $this->month,
- //'year' => $this->year,
- //'note' => $this->note,
- 'type' => $this->type,
- //'amount' => $this->currencyToDouble($this->amount),
- 'commercial' => $this->commercial,
- ]);
- $this->dataId = $record->id;
- $tot = 0;
- foreach ($this->rows as $row) {
- foreach ($row["when"] as $x => $y) {
- $row["when"][$x]['period'] = $row["when"][$x]['month'] . "-" . $row["when"][$x]['year'];
- }
- $imponibile = isset($row["imponibile"]) ? $this->currencyToDouble($row["imponibile"]) : null;
- Log::info("Imponibile store: " . $imponibile);
- $aliquota_iva = isset($row["aliquota_iva"]) ? floatval(str_replace('%', '', $row["aliquota_iva"])) : null;
- Log::info("Aliquota IVA store: " . $aliquota_iva);
- \App\Models\RecordRow::create([
- 'record_id' => $this->dataId,
- 'causal_id' => $row["causal_id"],
- 'note' => $row["note"],
- 'amount' => $this->currencyToDouble($row["amount"]),
- 'imponibile' => $imponibile,
- 'aliquota_iva' => $aliquota_iva,
- 'commercial' => $row["commercial"],
- 'when' => json_encode($row["when"])
- ]);
- $tot += $this->currencyToDouble($row["amount"]);
- }
- $record->amount = $tot;
- $record->save();
- session()->flash('success', 'Movimento creato');
- $this->resetFields();
- $this->add = false;
- $this->emit('setEdit', false);
- } catch (\Exception $ex) {
- $this->emit('flash-error', 'Errore (' . $ex->getMessage() . ')');
- }
- }
- public function edit($id)
- {
- if (!isset($_GET["from"]) && $this->fromPage == '')
- $this->fromPage = 'out';
- $this->emit('setEdit', true);
- $this->emit('load-select');
- //if ($this->hasFilter)
- $this->emit('hide-search');
- try {
- $record = \App\Models\Record::findOrFail($id);
- if (!$record) {
- $this->emit('flash-error', 'Movimento non trovato');
- } else {
- $this->member_id = $record->member_id;
- $this->supplier_id = $record->supplier_id;
- //$this->causal_id = $record->causal_id;
- $this->payment_method_id = $record->payment_method_id;
- $this->date = date("Y-m-d", strtotime($record->date));
- $this->data_pagamento = date("Y-m-d", strtotime($record->data_pagamento));
- //$this->month = $record->month;
- //$this->year = $record->year;
- //$this->note = $record->note;
- $this->type = $record->type;
- //$this->amount = formatPrice($record->amount);
- $this->commercial = $record->commercial;
- $this->dataId = $record->id;
- $this->update = true;
- $this->add = false;
- $this->rows = [];
- $recordRows = \App\Models\RecordRow::where('record_id', $this->dataId)->get();
- foreach ($recordRows as $recordRow) {
- $rowData = [
- 'causal_id' => $recordRow->causal_id,
- 'note' => $recordRow->note,
- 'commercial' => $recordRow->commercial,
- 'when' => json_decode($recordRow->when),
- 'amount' => formatPrice($recordRow->amount)
- ];
- // Add imponibile field if available in the database
- if (isset($recordRow->imponibile)) {
- $rowData['imponibile'] = formatPrice($recordRow->imponibile);
- }
- // Add aliquota_iva field if available in the database
- if (isset($recordRow->aliquota_iva)) {
- $rowData['aliquota_iva'] = $recordRow->aliquota_iva . '%';
- }
- $this->rows[] = $rowData;
- }
- }
- } catch (\Exception $ex) {
- $this->emit('flash-error', 'Errore (' . $ex->getMessage() . ')');
- }
- }
- public function update()
- {
- $this->emit('refresh');
- $this->validate();
- Log::info("Rows: pipo");
- try {
- \App\Models\Record::whereId($this->dataId)->update([
- 'member_id' => $this->member_id,
- 'supplier_id' => $this->supplier_id,
- 'payment_method_id' => $this->payment_method_id,
- 'date' => $this->date,
- 'data_pagamento' => $this->data_pagamento,
- 'type' => $this->type,
- 'commercial' => $this->commercial,
- ]);
- $tot = 0;
- $existingRows = \App\Models\RecordRow::where('record_id', $this->dataId)
- ->select('id', 'quantita', 'numero_linea')
- ->get()
- ->keyBy('id')
- ->toArray();
- \App\Models\RecordRow::where('record_id', $this->dataId)->delete();
- foreach ($this->rows as $row) {
- foreach ($row["when"] as $x => $y) {
- $row["when"][$x]['period'] = $row["when"][$x]['month'] . "-" . $row["when"][$x]['year'];
- }
- $imponibile = null;
- if (isset($row["imponibile"]) && $row["imponibile"] !== null && $row["imponibile"] !== '') {
- $imponibile = $this->currencyToDouble($row["imponibile"]);
- Log::info("Imponibile: " . $imponibile);
- }
- $aliquota_iva = null;
- if (isset($row["aliquota_iva"]) && $row["aliquota_iva"] !== null && $row["aliquota_iva"] !== '') {
- $aliquota_iva = floatval(str_replace('%', '', $row["aliquota_iva"]));
- Log::info("Aliquota IVA: " . $aliquota_iva);
- }
- $amount = $this->currencyToDouble($row["amount"]);
- $imposta = null;
- if ($imponibile !== null) {
- $imposta = $amount - $imponibile;
- Log::info("Imposta calculated: " . $imposta);
- }
- $recordRowData = [
- 'record_id' => $this->dataId,
- 'causal_id' => $row["causal_id"],
- 'note' => $row["note"],
- 'amount' => $this->currencyToDouble($row["amount"]),
- 'commercial' => $row["commercial"],
- 'when' => json_encode($row["when"]),
- 'imponibile' => $imponibile,
- 'aliquota_iva' => $aliquota_iva,
- 'imposta' => $imposta,
- 'divisa' => 'EUR',
- ];
- if (isset($row["id"]) && isset($existingRows[$row["id"]])) {
- $existingRow = $existingRows[$row["id"]];
- $recordRowData['quantita'] = $existingRow['quantita'];
- $recordRowData['numero_linea'] = $existingRow['numero_linea'];
- }
- Log::info("RecordRowData: " . json_encode($recordRowData));
- \App\Models\RecordRow::create($recordRowData);
- $tot += $this->currencyToDouble($row["amount"]);
- }
- $rec = \App\Models\Record::findOrFail($this->dataId);
- $rec->amount = $tot;
- $rec->save();
- session()->flash('success', 'Movimento aggiornato');
- $this->resetFields();
- $this->update = false;
- $this->emit('setEdit', false);
- } catch (\Exception $ex) {
- $this->emit('flash-error', 'Errore (' . $ex->getMessage() . ')');
- }
- }
- public function cancel()
- {
- $this->add = false;
- $this->update = false;
- $this->emit('setEdit', false);
- $this->resetFields();
- }
- public function delete($id)
- {
- try {
- \App\Models\Record::find($id)->delete();
- session()->flash('success', "Movimento eliminato");
- } catch (\Exception $e) {
- $this->emit('flash-error', 'Errore (' . $e->getMessage() . ')');
- }
- }
- public function multipleDelete()
- {
- try {
- foreach ($this->multipleIds as $id) {
- \App\Models\Record::find($id)->delete();
- }
- } catch (\Exception $e) {
- $this->emit('flash-error', 'Errore (' . $e->getMessage() . ')');
- }
- $this->multipleAction = '';
- }
- /*
- public function createReceipt()
- {
- $receipt = \App\Models\Receipt::where('record_id', $this->dataId)->first();
- if ($receipt != null)
- {
- $receipt->update([
- 'member_id' => $this->member_id,
- 'supplier_id' => $this->supplier_id,
- 'causal_id' => $this->causal_id,
- 'payment_method_id' => $this->payment_method_id,
- 'date' => date("Y-m-d", strtotime($this->date)),
- 'month' => $this->month,
- 'year' => $this->year,
- 'type' => $this->type,
- 'amount' => $this->currencyToDouble($this->amount),
- 'commercial' => $this->commercial,
- 'status' => 1,
- ]);
- }
- else
- {
- $number = 1;
- $exist = \App\Models\Receipt::where('year', $this->year)->orderBy('number', 'DESC')->first();
- if ($exist != null)
- $number = $exist->number + 1;
- $receipt = \App\Models\Receipt::create([
- 'record_id' => $this->dataId,
- 'member_id' => $this->member_id,
- 'supplier_id' => $this->supplier_id,
- 'causal_id' => $this->causal_id,
- 'payment_method_id' => $this->payment_method_id,
- 'number' => $number,
- 'date' => $this->date,
- 'month' => $this->month,
- 'year' => $this->year,
- 'type' => $this->type,
- 'amount' => $this->currencyToDouble($this->amount),
- 'commercial' => $this->commercial,
- 'status' => 1,
- ]);
- }
- }
- public function removeReceipt()
- {
- $receipt = \App\Models\Receipt::findOrFail($this->currentReceip->id);
- $receipt->status = 99;
- $receipt->save();
- $this->currentReceip = $receipt;
- }
- */
- function currencyToDouble($val)
- {
- $x = str_replace("€", "", $val);
- $x = str_replace(".", "", $x);
- $x = str_replace(",", ".", $x);
- return floatval(trim($x));
- }
- public function addRow()
- {
- $this->rows[] = array(
- 'causal_id' => null,
- 'when' => array(array('month' => date("n"), 'year' => date("Y"), 'period' => '')),
- 'amount' => null,
- 'imponibile' => null,
- 'aliquota_iva' => null,
- 'note' => '',
- 'commercial' => 0
- );
- $this->emit('load-select');
- }
- public function delRow($idx)
- {
- unset($this->rows[$idx]);
- // $this->emit('load-select');
- }
- public function addPeriod($idx)
- {
- $x = sizeof($this->rows[$idx]['when']) - 1;
- $newDate = \Carbon\Carbon::create($this->rows[$idx]['when'][$x]["year"] . "-" . $this->rows[$idx]['when'][$x]["month"] . '-01')->addMonth();
- $this->rows[$idx]['when'][] = array('month' => $newDate->format("n"), 'year' => $newDate->format("Y"), 'period' => '');
- //$this->rows[$idx]['when'][] = array('month' => date("n"), 'year' => date("Y"), 'period' => '');
- }
- public function delPeriod($idx, $xxx)
- {
- array_splice($this->rows[$idx]['when'], $xxx, 1);
- // $this->emit('load-select');
- }
- public function getTotal()
- {
- $total = 0.00;
- foreach ($this->rows as $r) {
- $total += $this->currencyToDouble($r["amount"] != null ? $r["amount"] : 0);
- }
- return formatPrice($total);
- // $this->emit('load-select');
- }
- public function setCausal($id, $idx)
- {
- $this->rows[$idx]["causal_id"] = $id;
- }
- public function multiPeriod()
- {
- $this->multiP = true;
- }
- public function multiPeriodCreate($idx)
- {
- $period = \Carbon\CarbonPeriod::create($this->multiYearFrom . '-' . $this->multiMonthFrom . '-01', '1 month', $this->multiYearTo . '-' . $this->multiMonthTo . '-01');
- $this->rows[$idx]['when'] = [];
- foreach ($period as $dt) {
- if (!in_array(array('month' => $dt->format("n"), 'year' => $dt->format("Y"), 'period' => ''), $this->rows[$idx]['when']))
- $this->rows[$idx]['when'][] = array('month' => $dt->format("n"), 'year' => $dt->format("Y"), 'period' => '');
- }
- $this->multiP = false;
- }
- public function multiPeriodCancel()
- {
- $this->multiP = false;
- }
- public function importReceipts()
- {
- $this->validate([
- //'receiptFiles.*' => 'required|mimes:xml|max:2048',
- 'selectedCausal' => 'required|exists:causals,id',
- ]);
- Log::info("Importazione ricevute: " . json_encode($this->receiptFiles));
- try {
- $importCount = 0;
- $updateCount = 0;
- $errorsCount = 0;
- $errorMessages = [];
- $totalFiles = count($this->receiptFiles);
- // disabilita select
- $this->emit('import-started');
- Log::info("Import iniziato");
- foreach ($this->receiptFiles as $index => $receiptFile) {
- try {
- $fileName = $receiptFile->getClientOriginalName();
- Log::info("Elaborazione file: " . $fileName);
- // Carica e analizza il file XML
- $xmlString = file_get_contents($receiptFile->getRealPath());
- $xml = simplexml_load_string($xmlString);
- if (!$xml) {
- throw new \Exception("Impossibile analizzare il file XML");
- }
- // Estrai i dati dalla fattura elettronica
- $fatturaData = $this->extractFatturaData($xml);
- // Trova o crea il fornitorez
- $supplier = $this->findOrCreateSupplier($fatturaData);
- // Trova il metodo di pagamento
- $paymentMethodId = $this->findPaymentMethod($fatturaData['modalitaPagamento']);
- // Crea il record principale
- $isUpdate = false;
- $existingRecord = \App\Models\Record::where('supplier_id', $supplier->id)
- ->where('numero_fattura', $fatturaData['numeroFattura'])
- ->first();
- if ($existingRecord) {
- $record = $this->updateRecord($existingRecord, $paymentMethodId, $fatturaData);
- $isUpdate = true;
- $updateCount++;
- Log::info("Fattura aggiornata con successo: {$fatturaData['numeroFattura']}, Fornitore: {$supplier->name}");
- } else {
- // Crea un nuovo record
- $record = $this->createRecord($supplier->id, $paymentMethodId, $fatturaData);
- $importCount++;
- Log::info("Fattura importata con successo: {$fatturaData['numeroFattura']}, Fornitore: {$supplier->name}");
- }
- // Crea il record row
- $this->createRecordRow($record->id, $fatturaData);
- //$importCount++;
- Log::info("Fattura importata con successo: {$fatturaData['numeroFattura']}, Fornitore: {$fatturaData['denominazione']} OR {$fatturaData['cognome']}, {$fatturaData['nome']}");
- } catch (\Exception $e) {
- $errorMsg = 'Errore durante l\'importazione della fattura';
- if (isset($fileName)) {
- $errorMsg .= " ($fileName)";
- }
- $errorMsg .= ': ' . $e->getMessage();
- Log::error($errorMsg);
- $errorMessages[] = $errorMsg;
- $errorsCount++;
- }
- $progress = ($index + 1) / $totalFiles * 100;
- $this->emit('update-progress', $progress);
- }
- $this->showResultMessages($importCount, $updateCount, $errorsCount);
- } catch (\Exception $e) {
- $errorMsg = 'Errore durante l\'importazione dei file XML: ' . $e->getMessage();
- Log::error($errorMsg);
- $this->emit('show-import-result', [
- 'message' => $errorMsg,
- 'type' => 'error'
- ]);
- } finally {
- $this->emit('load-data-table');
- // Non chiamiamo più closeImportModal() qui, perché la chiusura è gestita dal JavaScript
- }
- }
- /**
- * Estrae i dati dalla fattura elettronica XML
- */
- private function extractFatturaData($xml)
- {
- $data = [];
- try {
- // Stampa la struttura XML per debug
- Log::info("Nomi dei children dell'elemento radice: " . implode(", ", array_map(function ($node) {
- return $node->getName();
- }, iterator_to_array($xml->children()))));
- $headerNode = $xml->FatturaElettronicaHeader;
- $bodyNode = $xml->FatturaElettronicaBody;
- if (!$headerNode || !$bodyNode) {
- throw new \Exception("Struttura XML non standard, FatturaElettronicaHeader o FatturaElettronicaBody non trovati");
- }
- // Estrai dati del fornitore (cedente/prestatore)
- $cedenteNode = $headerNode->CedentePrestatore;
- $datiAnagrafici = $cedenteNode->DatiAnagrafici;
- $idFiscaleIVA = $datiAnagrafici->IdFiscaleIVA;
- $data['idPaese'] = (string)$idFiscaleIVA->IdPaese;
- $data['idCodice'] = (string)$idFiscaleIVA->IdCodice;
- $data['partitaIva'] = $data['idPaese'] . $data['idCodice'];
- $data['codiceFiscale'] = (string)$datiAnagrafici->CodiceFiscale;
- $data['denominazione'] = (string)$datiAnagrafici->Anagrafica->Denominazione;
- $data['cognome'] = (string)$datiAnagrafici->Anagrafica->Cognome;
- $data['nome'] = (string)$datiAnagrafici->Anagrafica->Nome;
- // Estrai dati della sede
- $sede = $cedenteNode->Sede;
- $data['indirizzo'] = (string)$sede->Indirizzo;
- $data['cap'] = (string)$sede->CAP;
- $data['comune'] = (string)$sede->Comune;
- $data['provincia'] = (string)$sede->Provincia;
- $data['nazione'] = (string)$sede->Nazione ?: 'IT';
- // Email, se presente
- $data['email'] = '';
- if (isset($cedenteNode->Contatti) && isset($cedenteNode->Contatti->Email)) {
- $data['email'] = (string)$cedenteNode->Contatti->Email;
- }
- // Dati generali della fattura
- $datiGeneraliDocumento = $bodyNode->DatiGenerali->DatiGeneraliDocumento;
- $data['tipoDocumento'] = (string)$datiGeneraliDocumento->TipoDocumento;
- $data['divisa'] = (string)$datiGeneraliDocumento->Divisa ?: 'EUR';
- $data['dataDocumento'] = (string)$datiGeneraliDocumento->Data;
- $data['numeroFattura'] = (string)$datiGeneraliDocumento->Numero;
- $data['importoTotale'] = (float)$datiGeneraliDocumento->ImportoTotaleDocumento;
- // Dati di pagamento
- $data['condizioniPagamento'] = '';
- $data['modalitaPagamento'] = '';
- $data['dataScadenza'] = '';
- $data['iban'] = '';
- $data['bic'] = '';
- $data['istitutoFinanziario'] = '';
- if (isset($bodyNode->DatiPagamento)) {
- $datiPagamento = $bodyNode->DatiPagamento;
- $data['condizioniPagamento'] = (string)$datiPagamento->CondizioniPagamento;
- if (isset($datiPagamento->DettaglioPagamento)) {
- $dettaglioPagamento = $datiPagamento->DettaglioPagamento;
- $data['modalitaPagamento'] = (string)$dettaglioPagamento->ModalitaPagamento;
- $data['dataScadenza'] = (string)$dettaglioPagamento->DataScadenzaPagamento;
- $data['iban'] = (string)$dettaglioPagamento->IBAN;
- $data['bic'] = (string)$dettaglioPagamento->BIC;
- $data['istitutoFinanziario'] = (string)$dettaglioPagamento->IstitutoFinanziario;
- }
- }
- // Estrai le linee di dettaglio
- $data['linee'] = [];
- if (isset($bodyNode->DatiBeniServizi) && isset($bodyNode->DatiBeniServizi->DettaglioLinee)) {
- foreach ($bodyNode->DatiBeniServizi->DettaglioLinee as $index => $linea) {
- if(isset($linea->Quantita)) {
- $lineaData = [
- 'numeroLinea' => (int)($linea->NumeroLinea ?? ($index + 1)),
- 'descrizione' => (string)($linea->Descrizione ?? ''),
- 'quantita' => (float)($linea->Quantita ?? 1),
- 'prezzoUnitario' => (float)($linea->PrezzoUnitario ?? 0),
- 'prezzoTotale' => (float)($linea->PrezzoTotale ?? 0),
- 'aliquotaIva' => (float)($linea->AliquotaIVA ?? 0),
- ];
- // Calcola il prezzo totale se non presente
- if ($lineaData['prezzoTotale'] == 0) {
- $lineaData['prezzoTotale'] = $lineaData['quantita'] * $lineaData['prezzoUnitario'];
- }
- $data['linee'][] = $lineaData;
- } else {
- // Se la linea ha un campo Quantita, non la consideriamo
- Log::info("Linea con Quantita non considerata: " . json_encode($linea));
- }
- }
- }
- $data['riepilogo'] = null;
- if (isset($bodyNode->DatiBeniServizi) && isset($bodyNode->DatiBeniServizi->DatiRiepilogo)) {
- $riepilogoNode = $bodyNode->DatiBeniServizi->DatiRiepilogo;
- if ($riepilogoNode) {
- $data['riepilogo'] = [
- 'aliquotaIva' => (float)($riepilogoNode->AliquotaIVA ?? 0),
- 'imponibile' => (float)($riepilogoNode->ImponibileImporto ?? 0),
- 'imposta' => (float)($riepilogoNode->Imposta ?? 0),
- ];
- }
- }
- Log::info("Dati estratti dalla fattura: P.IVA={$data['partitaIva']}, Denominazione={$data['denominazione']},Nome={$data['nome']},Cognome={$data['cognome']} , Numero={$data['numeroFattura']}, Importo={$data['importoTotale']}");
- return $data;
- } catch (\Exception $e) {
- Log::error("Errore nell'estrazione dei dati XML: " . $e->getMessage());
- throw $e;
- }
- }
- /**
- * Trova o crea un fornitore basato sui dati della fattura
- */
- private function findOrCreateSupplier($fatturaData)
- {
- $supplier = \App\Models\Supplier::where('vat', $fatturaData['partitaIva'])->first();
- if (!$supplier) {
- Log::info("Creazione nuovo fornitore con P.IVA: {$fatturaData['partitaIva']} ({$fatturaData['denominazione']}) OR ({$fatturaData['nome']}), ({$fatturaData['cognome']})");
- $countryId = $this->getCountryId($fatturaData['nazione']);
- $provinceId = $this->getProvinceId($fatturaData['provincia']);
- $cityId = $this->getCityId($fatturaData['comune']);
- $supplier = new \App\Models\Supplier();
- $supplier->name = $fatturaData['denominazione'] ?: $fatturaData['cognome'] . ' ' . $fatturaData['nome'];
- Log::info("Nome fornitore: " . $supplier->name);
- $supplier->vat = $fatturaData['partitaIva'];
- $supplier->fiscal_code = $fatturaData['codiceFiscale'];
- $supplier->address = $fatturaData['indirizzo'];
- $supplier->city_id = $cityId;
- $supplier->zip_code = $fatturaData['cap'];
- $supplier->province_id = $provinceId;
- $supplier->nation_id = $countryId;
- $supplier->email = $fatturaData['email'];
- $supplier->save();
- Log::info("Fornitore creato con ID: " . $supplier->id);
- }
- return $supplier;
- }
- /**
- * Trova l'ID della nazione dal codice
- */
- private function getCountryId($nationCode)
- {
- $country = DB::table('nations')->where('code', $nationCode)->first();
- return $country ? $country->id : null;
- }
- /**
- * Trova l'ID della provincia dal codice
- */
- private function getProvinceId($provinceCode)
- {
- $province = DB::table('provinces')->where('code', $provinceCode)->first();
- return $province ? $province->id : null;
- }
- /**
- * Trova l'ID della città dal nome
- */
- private function getCityId($cityName)
- {
- if (empty($cityName)) return null;
- $city = DB::table('cities')->where('name', $cityName)->first();
- return $city ? $city->id : null;
- }
- /**
- * Trova l'ID del metodo di pagamento dal codice
- */
- private function findPaymentMethod($paymentCode)
- {
- if (!empty($paymentCode)) {
- $paymentMethod = DB::table('payment_methods')->where('code', $paymentCode)->first();
- if ($paymentMethod) {
- Log::info("Metodo di pagamento trovato: $paymentCode (ID: {$paymentMethod->id})");
- return $paymentMethod->id;
- }
- }
- // Cerca il metodo di pagamento predefinito - corretto per evitare l'errore della colonna 'default'
- // Verifica se esiste una colonna 'is_default' o simile
- $possibleDefaultColumns = ['is_default', 'is_default_method', 'default_method', 'primary'];
- $defaultPaymentMethod = null;
- foreach ($possibleDefaultColumns as $column) {
- if (Schema::hasColumn('payment_methods', $column)) {
- $defaultPaymentMethod = DB::table('payment_methods')->where($column, 1)->first();
- if ($defaultPaymentMethod) {
- Log::info("Usando metodo di pagamento predefinito (colonna $column) ID: {$defaultPaymentMethod->id}");
- break;
- }
- }
- }
- // Se non è stato trovato un metodo predefinito, prendi il primo disponibile
- if (!$defaultPaymentMethod) {
- $defaultPaymentMethod = DB::table('payment_methods')->first();
- if ($defaultPaymentMethod) {
- Log::info("Usando il primo metodo di pagamento disponibile ID: {$defaultPaymentMethod->id}");
- }
- }
- if ($defaultPaymentMethod) {
- return $defaultPaymentMethod->id;
- }
- throw new \Exception("Nessun metodo di pagamento disponibile nel sistema");
- }
- /**
- * Crea un record nella tabella records
- */
- private function createRecord($supplierId, $paymentMethodId, $fatturaData)
- {
- $record = new \App\Models\Record();
- $record->supplier_id = $supplierId;
- $record->payment_method_id = $paymentMethodId;
- $record->date = $fatturaData['dataDocumento'];
- $record->data_pagamento = $fatturaData['dataDocumento'];
- $record->numero_fattura = $fatturaData['numeroFattura'];
- $record->type = 'OUT';
- $record->commercial = 1;
- $record->corrispettivo_fiscale = 0;
- $record->deleted = 0;
- $record->financial_movement = 1;
- $record->amount = $fatturaData['importoTotale'];
- $record->tipo_documento = $this->mapTipoDocumento($fatturaData['tipoDocumento']);
- $record->is_ricevuta = true;
- if (isset($fatturaData['condizioniPagamento']) && !empty($fatturaData['condizioniPagamento'])) {
- $record->condizioni_pagamento = $this->mapCondizioniPagamento($fatturaData['condizioniPagamento']);
- }
- if (isset($fatturaData['iban']) && !empty($fatturaData['iban'])) {
- $record->IBAN = $fatturaData['iban'];
- }
- if (isset($fatturaData['bic']) && !empty($fatturaData['bic'])) {
- $record->BIC = $fatturaData['bic'];
- }
- if (isset($fatturaData['dataScadenza']) && !empty($fatturaData['dataScadenza'])) {
- $record->data_scadenza = $fatturaData['dataScadenza'];
- }
- $record->save();
- Log::info("Nuovo record creato con ID: " . $record->id);
- return $record;
- }
- /**
- * Aggiorna un record esistente nella tabella records
- */
- private function updateRecord($record, $paymentMethodId, $fatturaData)
- {
- $record->payment_method_id = $paymentMethodId;
- $record->date = $fatturaData['dataDocumento'];
- $record->data_pagamento = $fatturaData['dataDocumento'];
- $record->type = 'OUT';
- $record->commercial = 1;
- $record->corrispettivo_fiscale = 0;
- $record->deleted = 0;
- $record->financial_movement = 1;
- $record->amount = $fatturaData['importoTotale'];
- $record->tipo_documento = $this->mapTipoDocumento($fatturaData['tipoDocumento']);
- $record->is_ricevuta = true;
- if (isset($fatturaData['condizioniPagamento']) && !empty($fatturaData['condizioniPagamento'])) {
- $record->condizioni_pagamento = $this->mapCondizioniPagamento($fatturaData['condizioniPagamento']);
- }
- if (isset($fatturaData['iban']) && !empty($fatturaData['iban'])) {
- $record->IBAN = $fatturaData['iban'];
- }
- if (isset($fatturaData['bic']) && !empty($fatturaData['bic'])) {
- $record->BIC = $fatturaData['bic'];
- }
- if (isset($fatturaData['dataScadenza']) && !empty($fatturaData['dataScadenza'])) {
- $record->data_scadenza = $fatturaData['dataScadenza'];
- }
- $record->save();
- Log::info("Record esistente aggiornato con ID: " . $record->id);
- return $record;
- }
- /**
- * Crea un record row per il record specificato
- */
- private function createRecordRow($recordId, $fatturaData)
- {
- Log::info("Inizio creazione RecordRow per Record ID: " . $recordId);
- $existingRows = \App\Models\RecordRow::where('record_id', $recordId)->get();
- // Delete existing rows if they exist
- if ($existingRows->count() > 0) {
- Log::info("Eliminazione di " . $existingRows->count() . " righe record esistenti per Record ID: " . $recordId);
- foreach ($existingRows as $row) {
- $row->delete();
- }
- }
- if (!empty($fatturaData['linee'])) {
- foreach ($fatturaData['linee'] as $linea) {
- $this->createSingleRecordRow($recordId, $fatturaData, $linea);
- }
- } else if ($fatturaData['riepilogo']) {
- $this->createRecordRowFromRiepilogo($recordId, $fatturaData);
- Log::info("Creata una riga di record dai dati di riepilogo");
- } else {
- $this->createDefaultRecordRow($recordId, $fatturaData);
- Log::info("Creata una riga di record predefinita dall'importo totale");
- }
- }
- private function createSingleRecordRow($recordId, $fatturaData, $linea)
- {
- Log::info("Inizio creazione riga record singola per Record ID: " . $recordId . ", Linea: " . json_encode($linea));
- $dataObj = new \DateTime($fatturaData['dataDocumento']);
- $month = $dataObj->format('n');
- $year = $dataObj->format('Y');
- $period = "$month-$year";
- $whenData = [[
- 'month' => $month,
- 'year' => $year,
- 'period' => $period
- ]];
- $recordRow = new \App\Models\RecordRow();
- $recordRow->record_id = $recordId;
- $recordRow->causal_id = $this->selectedCausal;
- $recordRow->amount = $linea['prezzoTotale'] + $linea['prezzoTotale'] * ($linea['aliquotaIva'] / 100);
- $recordRow->note = $linea['descrizione'];
- $recordRow->commercial = 1;
- $recordRow->when = json_encode($whenData);
- $recordRow->aliquota_iva = $linea['aliquotaIva'];
- $recordRow->imponibile = $linea['prezzoTotale'];
- $recordRow->imposta = $linea['prezzoTotale'] * ($linea['aliquotaIva'] / 100);
- $recordRow->divisa = $fatturaData['divisa'];
- $recordRow->numero_linea = $linea['numeroLinea'];
- $recordRow->prezzo_unitario = $linea['prezzoUnitario'];
- $recordRow->quantita = $linea['quantita'];
- Log::info("Dati riga record prima del salvataggio: " . json_encode([
- 'record_id' => $recordRow->record_id,
- 'causal_id' => $recordRow->causal_id,
- 'amount' => $recordRow->amount,
- 'note' => $recordRow->note,
- 'aliquota_iva' => $recordRow->aliquota_iva,
- 'imponibile' => $recordRow->imponibile,
- 'imposta' => $recordRow->imposta,
- 'divisa' => $recordRow->divisa,
- 'numero_linea' => $recordRow->numero_linea,
- 'prezzo_unitario' => $recordRow->prezzo_unitario,
- 'quantita' => $recordRow->quantita,
- ]));
- $recordRow->save();
- Log::info("Riga record creata per linea {$linea['numeroLinea']}: {$linea['descrizione']} (€{$linea['prezzoTotale']})");
- }
- private function createRecordRowFromRiepilogo($recordId, $fatturaData)
- {
- Log::info("Inizio creazione riga record da riepilogo per Record ID: " . $recordId . ", Riepilogo: " . json_encode($fatturaData['riepilogo']));
- $riepilogo = $fatturaData['riepilogo'];
- $dataObj = new \DateTime($fatturaData['dataDocumento']);
- $month = $dataObj->format('n');
- $year = $dataObj->format('Y');
- $period = "$month-$year";
- $whenData = [[
- 'month' => $month,
- 'year' => $year,
- 'period' => $period
- ]];
- $total_amount = $riepilogo['imponibile'] + $riepilogo['imposta'];
- $recordRow = new \App\Models\RecordRow();
- $recordRow->record_id = $recordId;
- $recordRow->causal_id = $this->selectedCausal;
- $recordRow->amount = $total_amount;
- $recordRow->commercial = 1;
- $recordRow->when = json_encode($whenData);
- $recordRow->aliquota_iva = $riepilogo['aliquotaIva'];
- $recordRow->imponibile = $riepilogo['imponibile'];
- $recordRow->imposta = $riepilogo['imposta'];
- $recordRow->divisa = $fatturaData['divisa'];
- $recordRow->numero_linea = 1;
- $recordRow->quantita = 1;
- Log::info("Dati riga record da riepilogo prima del salvataggio: " . json_encode([
- 'record_id' => $recordRow->record_id,
- 'causal_id' => $recordRow->causal_id,
- 'amount' => $recordRow->amount,
- 'aliquota_iva' => $recordRow->aliquota_iva,
- 'imponibile' => $recordRow->imponibile,
- 'imposta' => $recordRow->imposta,
- 'divisa' => $recordRow->divisa,
- ]));
- $recordRow->save();
- Log::info("Riga record creata da riepilogo: Imponibile={$riepilogo['imponibile']}, IVA={$riepilogo['aliquotaIva']}%");
- }
- private function createDefaultRecordRow($recordId, $fatturaData)
- {
- Log::info("Inizio creazione riga record predefinita per Record ID: " . $recordId . ", Importo Totale: " . $fatturaData['importoTotale']);
- $dataObj = new \DateTime($fatturaData['dataDocumento']);
- $month = $dataObj->format('n');
- $year = $dataObj->format('Y');
- $period = "$month-$year";
- $whenData = [[
- 'month' => $month,
- 'year' => $year,
- 'period' => $period
- ]];
- $recordRow = new \App\Models\RecordRow();
- $recordRow->record_id = $recordId;
- $recordRow->causal_id = $this->selectedCausal;
- $recordRow->amount = $fatturaData['importoTotale'];
- $recordRow->commercial = 1;
- $recordRow->when = json_encode($whenData);
- $recordRow->divisa = $fatturaData['divisa'];
- $recordRow->numero_linea = 1;
- $recordRow->quantita = 1;
- Log::info("Dati riga record predefinita prima del salvataggio: " . json_encode([
- 'record_id' => $recordRow->record_id,
- 'causal_id' => $recordRow->causal_id,
- 'amount' => $recordRow->amount,
- 'divisa' => $recordRow->divisa,
- ]));
- $recordRow->save();
- Log::info("Riga record predefinita creata con importo totale: {$fatturaData['importoTotale']}");
- }
- private function mapTipoDocumento($codice)
- {
- $tipiDocumento = [
- 'TD01' => 'Fattura',
- 'TD02' => 'Acconto/Anticipo su fattura',
- 'TD03' => 'Acconto/Anticipo su parcella',
- 'TD04' => 'Nota di credito',
- 'TD05' => 'Nota di debito',
- 'TD06' => 'Parcella',
- 'TD16' => 'Integrazione fattura reverse charge interno',
- 'TD17' => 'Integrazione/autofattura per acquisto servizi dall\'estero',
- 'TD18' => 'Integrazione per acquisto di beni intracomunitari',
- 'TD19' => 'Integrazione/autofattura per acquisto di beni ex art.17 c.2 DPR 633/72',
- 'TD20' => 'Autofattura per regolarizzazione e integrazione delle fatture',
- 'TD21' => 'Autofattura per splafonamento',
- 'TD22' => 'Estrazione beni da Deposito IVA',
- 'TD23' => 'Estrazione beni da Deposito IVA con versamento dell\'IVA',
- 'TD24' => 'Fattura differita di cui all\'art.21, comma 4, lett. a)',
- 'TD25' => 'Fattura differita di cui all\'art.21, comma 4, terzo periodo lett. b)',
- 'TD26' => 'Cessione di beni ammortizzabili e per passaggi interni',
- 'TD27' => 'Fattura per autoconsumo o per cessioni gratuite senza rivalsa'
- ];
- return $tipiDocumento[$codice] ?? $codice;
- }
- private function mapCondizioniPagamento($codice)
- {
- $condizioniPagamento = [
- 'TP01' => 'Pagamento a rate',
- 'TP02' => 'Pagamento completo',
- 'TP03' => 'Anticipo'
- ];
- return $condizioniPagamento[$codice] ?? $codice;
- }
- private function showResultMessages($importCount, $updateCount, $errorsCount)
- {
- $message = "";
- $messageType = "success";
- if ($importCount > 0) {
- $message .= "Importate $importCount nuove fatture.<br>";
- }
- if ($updateCount > 0) {
- $message .= "Aggiornate $updateCount fatture esistenti.<br>";
- }
- if ($errorsCount > 0) {
- $message .= "$errorsCount fatture non sono state importate a causa di errori.<br>";
- // Aggiungi i dettagli degli errori se disponibili
- if (!empty($errorMessages)) {
- $message .= "<details><summary>Dettagli errori (clicca per espandere)</summary><ul>";
- foreach ($errorMessages as $errorMsg) {
- $message .= "<li>" . htmlspecialchars($errorMsg) . "</li>";
- }
- $message .= "</ul></details>";
- }
- if ($importCount == 0 && $updateCount == 0) {
- $messageType = "error";
- } else {
- $messageType = "warning";
- }
- }
- if ($importCount > 0 || $updateCount > 0) {
- $this->emit('show-import-result', [
- 'message' => $message,
- 'type' => $messageType
- ]);
- } else {
- $this->emit('show-import-result', [
- 'message' => 'Nessuna fattura importata. Controlla i file XML e riprova.',
- 'type' => 'error'
- ]);
- }
- // Resetta i campi del form dopo l'importazione
- $this->reset(['receiptFiles']);
- }
- }
|