Explorar el Código

fatture import funzionante v1

FabioFratini hace 9 meses
padre
commit
2eb7d6d4ae

+ 0 - 38
app/Http/Livewire/RecordINOUT.php

@@ -85,7 +85,6 @@ class RecordINOUT extends Component
 
         //$this->causalsIn = \App\Models\Causal::where('parent_id', null)->where('type', 'IN')->whereNotIn('id', $this->excludeCausals)->get();
         //$this->causalsOut = \App\Models\Causal::where('parent_id', null)->where('type', 'OUT')->whereNotIn('id', $this->excludeCausals)->get();
-
     }
 
     public function getCausalsIn($records, $indentation)
@@ -686,41 +685,4 @@ class RecordINOUT extends Component
         return $path;
 
     }
-
-    public function importReceipts()
-    {
-        $this->validate([
-            'receiptFile' => 'required|mimes:xml|max:2048',
-        ]);
-
-        try {
-            $xmlString = file_get_contents($this->receiptFile->getRealPath());
-            $xml = new SimpleXMLElement($xmlString);
-            Log::info('XML Data: ' . print_r($xml, true));
-
-            // Extract data from XML and create receipts
-            foreach ($xml->receipt as $receiptData) {
-                Log::info('Receipt Data: ' . print_r($receiptData, true));
-                $member = Member::where('fiscal_code', (string)$receiptData->fiscal_code)->first();
-
-                if ($member) {
-                    $receipt = new \App\Models\Receipt();
-                    $receipt->member_id = $member->id;
-                    $receipt->date = (string)$receiptData->date;
-                    $receipt->amount = (float)$receiptData->amount;
-                    $receipt->number = (string)$receiptData->number;
-                    $receipt->year = (int)$receiptData->year;
-                    $receipt->save();
-                }
-            }
-
-            session()->flash('message', 'Ricevute importate con successo.');
-        } catch (\Exception $e) {
-            session()->flash('error', 'Errore durante l\'importazione del file XML: ' . $e->getMessage());
-        }
-
-        $this->reset('receiptFile');
-        $this->emit('load-data-table');
-    }
-
 }

+ 703 - 97
app/Http/Livewire/RecordOUT.php

@@ -1,14 +1,22 @@
 <?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;
+
 
 class RecordOUT extends Component
 {
+    use WithFileUploads;
 
     protected $listeners = ['setCausal' => 'setCausal'];
 
-    public $sortField ='date';
+    public $sortField = 'date';
     public $sortAsc = false;
 
     public $typeOUT = "OUT";
@@ -24,8 +32,7 @@ class RecordOUT extends Component
 
     public function sortBy($field)
     {
-        if($this->sortField === $field)
-        {
+        if ($this->sortField === $field) {
             $this->sortAsc = ! $this->sortAsc;
         } else {
             $this->sortAsc = true;
@@ -35,15 +42,15 @@ class RecordOUT extends Component
     }
 
     public $records, $dataId, $member_id, $supplier_id,
-    $causal_id,
-    $payment_method_id,
-    $date,
-    $month,
-    $year,
-    $type,
-    $amount,
-    $note,
-    $commercial, $update = false, $add = false;
+        $causal_id,
+        $payment_method_id,
+        $date,
+        $month,
+        $year,
+        $type,
+        $amount,
+        $note,
+        $commercial, $update = false, $add = false;
 
     public $filterSupplier = 0, $filterPaymentMethod = 0, $filterCausals = [], $filterFrom = '', $filterTo = '', $filterCommercial = 0;
 
@@ -63,6 +70,10 @@ class RecordOUT extends Component
     public $suppliers = array();
 
     public $rows = array();
+    public $receiptFiles = [];
+    public $selectedCausal = '';
+    public $importCausals = array();
+
 
     protected $rules = [
         'supplier_id' => 'required',
@@ -83,8 +94,7 @@ class RecordOUT extends Component
     public function getSupplierProperty()
     {
         $ret = null;
-        if ($this->supplier_id > 0)
-        {
+        if ($this->supplier_id > 0) {
             $ret = \App\Models\Supplier::findOrFail($this->supplier_id);
         }
         return $ret;
@@ -93,14 +103,14 @@ class RecordOUT extends Component
     public function getCausalProperty()
     {
         $ret = null;
-        if ($this->causal_id > 0)
-        {
+        if ($this->causal_id > 0) {
             $ret = \App\Models\Causal::findOrFail($this->causal_id);
         }
         return $ret;
     }
 
-    public function resetFields(){
+    public function resetFields()
+    {
         $this->member_id = null;
         $this->supplier_id = null;
         //$this->causal_id = null;
@@ -119,28 +129,44 @@ class RecordOUT extends Component
 
     public function getCausale($records, $indentation)
     {
-        foreach($records as $record)
-        {
+        foreach ($records as $record) {
             $this->causals[] = array('id' => $record->id, 'name' => $record->getTree());
-            if(count($record->childs))
+            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();
+    }
+
     public function hydrate()
     {
         $this->emit('load-select');
+
+        if (empty($this->importCausals)) {
+            $this->loadImportCausals();
+        }
     }
 
     public function mount()
     {
 
-        if (isset($_GET["from"]))
-        {
+        if (isset($_GET["from"])) {
             $this->fromPage = $_GET["from"];
         }
 
-        if(\Auth::user()->level != env('LEVEL_ADMIN', 0))
+        if (Auth::user()->level != env('LEVEL_ADMIN', 0))
             return redirect()->to('/dashboard');
 
         $this->multiMonthFrom = date("n");
@@ -155,15 +181,32 @@ class RecordOUT extends Component
 
         $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->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')
+            ->orderBy('name')
+            ->get();
+
+        $this->importCausals = [];
+        foreach ($causals as $causal) {
+            $this->importCausals[] = [
+                'id' => $causal->id,
+                'name' => $causal->getTree()
+            ];
+        }
     }
 
     public function getCausal($causal)
     {
         $ret = '';
-        if ($causal > 0)
-        {
+        if ($causal > 0) {
             $ret = \App\Models\Causal::findOrFail($causal)->getTree();
         }
         return $ret;
@@ -184,41 +227,34 @@ class RecordOUT extends Component
         $this->filterCommercial = 0;
         $this->hasFilter = false;
         $this->hasFilter = false;
-
     }
 
     public function render()
     {
         $datas = [];
 
-        if (false)
-        {
-            if ($this->hasFilter)
-            {
+        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)
-                {
+                if ($this->filterSupplier > 0) {
                     $datas = $datas->where('supplier_id', $this->filterSupplier);
                 }
-                if ($this->filterPaymentMethod > 0)
-                {
+                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 != '')
-                {
+                if ($this->filterFrom != '') {
                     $datas = $datas->where('date', '>=', $this->filterFrom);
                 }
-                if ($this->filterTo != '')
-                {
+                if ($this->filterTo != '') {
                     $datas = $datas->where('date', '<=', $this->filterTo);
                 }
                 //$this->records = $datas->orderBy('date', 'DESC')->get();
@@ -228,40 +264,28 @@ class RecordOUT extends Component
                 //$this->total = $this->records->sum('amount');
 
                 $this->total = 0;
-                foreach($this->records as $r)
-                {
-                    foreach($r->rows as $rr)
-                    {
+                foreach ($this->records as $r) {
+                    foreach ($r->rows as $rr) {
                         $this->total += $rr->amount;
                     }
                 }
-
-            }
-            else
-            {
-                if ($this->selectedFilter == '')
-                {
+            } 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)
-                    {
+                } else {
+                    if ($this->selectedFilter == 0) {
                         $fromDate = date("Y-m-d");
                         $toDate = date("Y-m-d");
                     }
-                    if ($this->selectedFilter == 1)
-                    {
+                    if ($this->selectedFilter == 1) {
                         $fromDate = date("Y-m-01");
                         $toDate = date("Y-m-t");
                     }
-                    if ($this->selectedFilter == 2)
-                    {
+                    if ($this->selectedFilter == 2) {
                         $fromDate = date("Y-01-01");
                         $toDate = date("Y-12-31");
                     }
-                    if ($this->selectedFilter == 3)
-                    {
+                    if ($this->selectedFilter == 3) {
                         $fromDate = date("2000-01-01");
                         $toDate = date("Y-12-31");
                     }
@@ -269,8 +293,7 @@ class RecordOUT extends Component
                 }
             }
 
-            foreach($this->records as $r)
-            {
+            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 : '';
@@ -290,11 +313,11 @@ class RecordOUT extends Component
         return view('livewire.records_out');
     }
 
-    public function executeMultipleAction(){
+    public function executeMultipleAction()
+    {
 
         if ($this->multipleAction == 'delete')
             $this->multipleDelete();
-
     }
 
     public function add()
@@ -302,7 +325,7 @@ class RecordOUT extends Component
 
         $this->emit('load-select');
         //if ($this->hasFilter)
-            $this->emit('hide-search');
+        $this->emit('hide-search');
         $this->resetFields();
         $this->add = true;
         $this->update = false;
@@ -331,10 +354,8 @@ class RecordOUT extends Component
 
             $this->dataId = $record->id;
             $tot = 0;
-            foreach($this->rows as $row)
-            {
-                foreach($row["when"] as $x => $y)
-                {
+            foreach ($this->rows as $row) {
+                foreach ($row["when"] as $x => $y) {
                     $row["when"][$x]['period'] = $row["when"][$x]['month'] . "-" . $row["when"][$x]['year'];
                 }
                 \App\Models\RecordRow::create([
@@ -350,26 +371,27 @@ class RecordOUT extends Component
             $record->amount = $tot;
             $record->save();
 
-            session()->flash('success','Movimento creato');
+            session()->flash('success', 'Movimento creato');
             $this->resetFields();
             $this->add = false;
             $this->emit('setEdit', false);
         } catch (\Exception $ex) {
-            session()->flash('error','Errore (' . $ex->getMessage() . ')');
+            session()->flash('error', 'Errore (' . $ex->getMessage() . ')');
         }
     }
 
-    public function edit($id){
+    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');
+        $this->emit('hide-search');
         try {
             $record = \App\Models\Record::findOrFail($id);
-            if( !$record) {
-                session()->flash('error','Movimento non trovato');
+            if (!$record) {
+                session()->flash('error', 'Movimento non trovato');
             } else {
                 $this->member_id = $record->member_id;
                 $this->supplier_id = $record->supplier_id;
@@ -387,15 +409,13 @@ class RecordOUT extends Component
                 $this->add = false;
 
                 $this->rows = \App\Models\RecordRow::where('record_id', $this->dataId)->select('causal_id', 'note', 'commercial', 'when', 'amount')->get()->toArray();
-                foreach($this->rows as $i => $r)
-                {
+                foreach ($this->rows as $i => $r) {
                     $this->rows[$i]['amount'] = formatPrice($this->rows[$i]['amount']);
                     $this->rows[$i]['when'] = json_decode($this->rows[$i]['when']);
                 }
-
             }
         } catch (\Exception $ex) {
-            session()->flash('error','Errore (' . $ex->getMessage() . ')');
+            session()->flash('error', 'Errore (' . $ex->getMessage() . ')');
         }
     }
 
@@ -423,10 +443,8 @@ class RecordOUT extends Component
             // Elimino le righe
             \App\Models\RecordRow::where('record_id', $this->dataId)->delete();
             // Inserisco le righe
-            foreach($this->rows as $row)
-            {
-                foreach($row["when"] as $x => $y)
-                {
+            foreach ($this->rows as $row) {
+                foreach ($row["when"] as $x => $y) {
                     $row["when"][$x]['period'] = $row["when"][$x]['month'] . "-" . $row["when"][$x]['year'];
                 }
                 \App\Models\RecordRow::create([
@@ -444,12 +462,12 @@ class RecordOUT extends Component
             $rec->amount = $tot;
             $rec->save();
 
-            session()->flash('success','Movimento aggiornato');
+            session()->flash('success', 'Movimento aggiornato');
             $this->resetFields();
             $this->update = false;
             $this->emit('setEdit', false);
         } catch (\Exception $ex) {
-            session()->flash('error','Errore (' . $ex->getMessage() . ')');
+            session()->flash('error', 'Errore (' . $ex->getMessage() . ')');
         }
     }
 
@@ -463,23 +481,22 @@ class RecordOUT extends Component
 
     public function delete($id)
     {
-        try{
+        try {
             \App\Models\Record::find($id)->delete();
-            session()->flash('success',"Movimento eliminato");
-        }catch(\Exception $e){
-            session()->flash('error','Errore (' . $ex->getMessage() . ')');
+            session()->flash('success', "Movimento eliminato");
+        } catch (\Exception $e) {
+            session()->flash('error', 'Errore (' . $e->getMessage() . ')');
         }
     }
 
     public function multipleDelete()
     {
-        try{
-            foreach($this->multipleIds as $id)
-            {
+        try {
+            foreach ($this->multipleIds as $id) {
                 \App\Models\Record::find($id)->delete();
             }
-        }catch(\Exception $e){
-            session()->flash('error','Errore (' . $ex->getMessage() . ')');
+        } catch (\Exception $e) {
+            session()->flash('error', 'Errore (' . $e->getMessage() . ')');
         }
         $this->multipleAction = '';
     }
@@ -580,8 +597,7 @@ class RecordOUT extends Component
     public function getTotal()
     {
         $total = 0.00;
-        foreach($this->rows as $r)
-        {
+        foreach ($this->rows as $r) {
             $total += $this->currencyToDouble($r["amount"] != null ? $r["amount"] : 0);
         }
         return formatPrice($total);
@@ -609,7 +625,6 @@ class RecordOUT extends Component
         }
 
         $this->multiP = false;
-
     }
 
     public function multiPeriodCancel()
@@ -617,4 +632,595 @@ class RecordOUT extends Component
         $this->multiP = false;
     }
 
+
+
+    public function importReceipts()
+    {
+        $this->validate([
+            'receiptFiles.*' => 'required|mimes:xml|max:2048',
+            'selectedCausal' => 'required|exists:causals,id',
+        ]);
+
+        try {
+            $importCount = 0;
+            $errorsCount = 0;
+
+            foreach ($this->receiptFiles as $receiptFile) {
+                try {
+                    // 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 fornitore
+                    $supplier = $this->findOrCreateSupplier($fatturaData);
+
+                    // Trova il metodo di pagamento
+                    $paymentMethodId = $this->findPaymentMethod($fatturaData['modalitaPagamento']);
+
+                    // Crea il record principale
+                    $record = $this->createRecord($supplier->id, $paymentMethodId, $fatturaData);
+
+                    // Crea il record row
+                    $this->createRecordRow($record->id, $fatturaData);
+
+                    // Crea la ricevuta
+                    $receipt = $this->createReceipt($record->id, $supplier->id, $paymentMethodId, $fatturaData);
+
+                    // Crea le righe della ricevuta
+                    $this->createReceiptRows($receipt->id, $fatturaData);
+
+                    $importCount++;
+                    Log::info("Fattura importata con successo: {$fatturaData['numeroFattura']}, Fornitore: {$fatturaData['denominazione']}");
+                } catch (\Exception $e) {
+                    Log::error('Errore durante l\'importazione della fattura: ' . $e->getMessage());
+                    $errorsCount++;
+                }
+            }
+
+            // Mostra messaggi appropriati
+            $this->showResultMessages($importCount, $errorsCount);
+        } catch (\Exception $e) {
+            Log::error('Errore durante l\'importazione dei file XML: ' . $e->getMessage());
+            session()->flash('error', 'Errore durante l\'importazione: ' . $e->getMessage());
+        }
+
+        $this->reset(['receiptFiles', 'selectedCausal']);
+        $this->emit('load-data-table');
+    }
+
+    /**
+     * 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;
+
+            // 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) {
+                    $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;
+                }
+            }
+
+            $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']}, 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']})");
+
+            $countryId = $this->getCountryId($fatturaData['nazione']);
+            $provinceId = $this->getProvinceId($fatturaData['provincia']);
+            $cityId = $this->getCityId($fatturaData['comune']);
+
+            $supplier = new \App\Models\Supplier();
+            $supplier->name = $fatturaData['denominazione'];
+            $supplier->vat = $fatturaData['partitaIva'];
+            $supplier->fiscal_code = $fatturaData['codiceFiscale'];
+            $supplier->address = $fatturaData['indirizzo'];
+            $supplier->city_id = $cityId;
+            $supplier->cap = $fatturaData['cap'];
+            $supplier->province_id = $provinceId;
+            $supplier->country_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;
+            }
+        }
+
+        $defaultPaymentMethod = DB::table('payment_methods')->where('default', 1)->first()
+            ?? DB::table('payment_methods')->first();
+
+        if ($defaultPaymentMethod) {
+            Log::info("Usando metodo di pagamento predefinito ID: {$defaultPaymentMethod->id}");
+            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->type = 'OUT';
+        $record->commercial = 0;
+        $record->corrispettivo_fiscale = 0;
+        $record->deleted = 0;
+        $record->financial_movement = 1;
+        $record->amount = $fatturaData['importoTotale'];
+        $record->save();
+
+        Log::info("Record creato 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);
+
+        $dataObj = new \DateTime($fatturaData['dataDocumento']);
+        $month = $dataObj->format('n');
+        $year = $dataObj->format('Y');
+
+        $period = "$month-$year";
+
+        $whenData = [[
+            'month' => $month,
+            'year' => $year,
+            'period' => $period
+        ]];
+        Log::info("Dati whenData: " . json_encode($whenData));
+
+        $recordRow = new \App\Models\RecordRow();
+        $recordRow->record_id = $recordId;
+        $recordRow->causal_id = $this->selectedCausal;
+        $recordRow->when = json_encode($whenData);
+        $recordRow->amount = $fatturaData['importoTotale'];
+        $recordRow->commercial = 0;
+
+        $noteData = '';
+        if (isset($fatturaData['linee']) && is_array($fatturaData['linee'])) {
+            $descriptions = array_map(function ($linea) {
+                return $linea['descrizione'];
+            }, $fatturaData['linee']);
+            $noteData = implode(', ', $descriptions);
+        }
+
+        $recordRow->note = $noteData;
+
+        Log::info("Dati RecordRow prima del salvataggio: " . json_encode([
+            'record_id' => $recordRow->record_id,
+            'causal_id' => $recordRow->causal_id,
+            'when' => $recordRow->when,
+            'amount' => $recordRow->amount,
+            'commercial' => $recordRow->commercial,
+            'note' => $recordRow->note
+        ]));
+
+        $recordRow->save();
+
+        Log::info("RecordRow creato per il Record ID: " . $recordId);
+
+        return $recordRow;
+    }
+
+    /**
+     * Crea una ricevuta collegata al record
+     */
+    private function createReceipt($recordId, $supplierId, $paymentMethodId, $fatturaData)
+    {
+        Log::info("Inizio creazione ricevuta per Record ID: " . $recordId);
+
+        $receipt = new \App\Models\Receipt();
+        $receipt->record_id = $recordId;
+        $receipt->supplier_id = $supplierId;
+        $receipt->payment_method_id = $paymentMethodId;
+        $receipt->date = $fatturaData['dataDocumento'];
+        $receipt->data_documento = $fatturaData['dataDocumento'];
+        $receipt->numero_fattura =  $fatturaData['numeroFattura'];
+        $receipt->number = preg_replace('/[^0-9]/', '', $fatturaData['numeroFattura']);
+        $receipt->tipo_documento = $this->mapTipoDocumento($fatturaData['tipoDocumento']);
+        $receipt->year = date('Y', strtotime($fatturaData['dataDocumento']));
+        $receipt->type = 'OUT';
+        $receipt->status = 1;
+        $receipt->is_ricevuta = true;
+        if (isset($fatturaData['condizioniPagamento']) && !empty($fatturaData['condizioniPagamento'])) {
+            $receipt->condizioni_pagamento = $this->mapCondizioniPagamento($fatturaData['condizioniPagamento']);
+        }
+        if (isset($fatturaData['iban']) && !empty($fatturaData['iban'])) {
+            $receipt->IBAN = $fatturaData['iban'];
+        }
+        if (isset($fatturaData['bic']) && !empty($fatturaData['bic'])) {
+            $receipt->BIC = $fatturaData['bic'];
+        }
+        if (isset($fatturaData['dataScadenza']) && !empty($fatturaData['dataScadenza'])) {
+            $receipt->data_scadenza = $fatturaData['dataScadenza'];
+        }
+
+        Log::info("Dati ricevuta prima del salvataggio: " . json_encode([
+            'record_id' => $receipt->record_id,
+            'supplier_id' => $receipt->supplier_id,
+            'payment_method_id' => $receipt->payment_method_id,
+            'date' => $receipt->date,
+            'number' => $receipt->number,
+            'tipo_documento' => $receipt->tipo_documento,
+            'year' => $receipt->year,
+            'type' => $receipt->type,
+            'status' => $receipt->status,
+        ]));
+
+        $receipt->save();
+
+        Log::info("Ricevuta creata con ID: " . $receipt->id);
+
+        return $receipt;
+    }
+
+    private function createReceiptRows($receiptId, $fatturaData)
+    {
+        Log::info("Inizio creazione righe ricevuta per Ricevuta ID: " . $receiptId);
+
+        if (!empty($fatturaData['linee'])) {
+            foreach ($fatturaData['linee'] as $linea) {
+                $this->createSingleReceiptRow($receiptId, $fatturaData, $linea);
+            }
+        } else if ($fatturaData['riepilogo']) {
+            $this->createReceiptRowFromRiepilogo($receiptId, $fatturaData);
+            Log::info("Creata una riga di ricevuta dai dati di riepilogo");
+        } else {
+            $this->createDefaultReceiptRow($receiptId, $fatturaData);
+            Log::info("Creata una riga di ricevuta predefinita dall'importo totale");
+        }
+    }
+
+    private function createSingleReceiptRow($receiptId, $fatturaData, $linea)
+    {
+        Log::info("Inizio creazione riga ricevuta singola per Ricevuta ID: " . $receiptId . ", 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
+        ]];
+
+        $receiptRow = new \App\Models\ReceiptRow();
+        $receiptRow->receip_id = $receiptId;
+        $receiptRow->causal_id = $this->selectedCausal;
+        $receiptRow->amount = $linea['prezzoTotale'];
+        $receiptRow->note = $linea['descrizione'];
+        $receiptRow->commercial = true;
+
+        $receiptRow->when = json_encode($whenData);
+        $receiptRow->aliquota_iva = $linea['aliquotaIva'];
+        $receiptRow->imponibile = $linea['prezzoTotale'];
+        $receiptRow->imposta = $linea['prezzoTotale'] * ($linea['aliquotaIva'] / 100);
+        $receiptRow->divisa = $fatturaData['divisa'];
+        $receiptRow->numero_linea = $linea['numeroLinea'];
+        $receiptRow->prezzo_unitario = $linea['prezzoUnitario'];
+        $receiptRow->quantita = $linea['quantita'];
+
+        Log::info("Dati riga ricevuta prima del salvataggio: " . json_encode([
+            'receip_id' => $receiptRow->receip_id,
+            'causal_id' => $receiptRow->causal_id,
+            'amount' => $receiptRow->amount,
+            'note' => $receiptRow->note,
+            'aliquota_iva' => $receiptRow->aliquota_iva,
+            'imponibile' => $receiptRow->imponibile,
+            'imposta' => $receiptRow->imposta,
+            'divisa' => $receiptRow->divisa,
+            'numero_linea' => $receiptRow->numero_linea,
+            'prezzo_unitario' => $receiptRow->prezzo_unitario,
+            'quantita' => $receiptRow->quantita,
+        ]));
+
+        $receiptRow->save();
+
+        Log::info("Riga ricevuta creata per linea {$linea['numeroLinea']}: {$linea['descrizione']} (€{$linea['prezzoTotale']})");
+    }
+
+    private function createReceiptRowFromRiepilogo($receiptId, $fatturaData)
+    {
+        Log::info("Inizio creazione riga ricevuta da riepilogo per Ricevuta ID: " . $receiptId . ", 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
+        ]];
+        $receiptRow = new \App\Models\ReceiptRow();
+        $receiptRow->receip_id = $receiptId;
+        $receiptRow->causal_id = $this->selectedCausal;
+        $receiptRow->amount = $riepilogo['imponibile'];
+        $receiptRow->commercial = true;
+
+        $receiptRow->when = json_encode($whenData);
+        $receiptRow->aliquota_iva = $riepilogo['aliquotaIva'];
+        $receiptRow->imponibile = $riepilogo['imponibile'];
+        $receiptRow->imposta = $riepilogo['imposta'];
+        $receiptRow->divisa = $fatturaData['divisa'];
+        $receiptRow->numero_linea = 1;
+        $receiptRow->quantita = 1;
+
+        Log::info("Dati riga ricevuta da riepilogo prima del salvataggio: " . json_encode([
+            'receip_id' => $receiptRow->receip_id,
+            'causal_id' => $receiptRow->causal_id,
+            'amount' => $receiptRow->amount,
+            'aliquota_iva' => $receiptRow->aliquota_iva,
+            'imponibile' => $receiptRow->imponibile,
+            'imposta' => $receiptRow->imposta,
+            'divisa' => $receiptRow->divisa,
+        ]));
+
+        $receiptRow->save();
+
+        Log::info("Riga ricevuta creata da riepilogo: Imponibile={$riepilogo['imponibile']}, IVA={$riepilogo['aliquotaIva']}%");
+    }
+
+    private function createDefaultReceiptRow($receiptId, $fatturaData)
+    {
+        Log::info("Inizio creazione riga ricevuta predefinita per Ricevuta ID: " . $receiptId . ", 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
+        ]];
+        $receiptRow = new \App\Models\ReceiptRow();
+        $receiptRow->receip_id = $receiptId;
+        $receiptRow->causal_id = $this->selectedCausal;
+        $receiptRow->amount = $fatturaData['importoTotale'];
+        $receiptRow->commercial = true;
+
+        $receiptRow->when = json_encode($whenData);
+        $receiptRow->divisa = $fatturaData['divisa'];
+        $receiptRow->numero_linea = 1;
+        $receiptRow->quantita = 1;
+
+        Log::info("Dati riga ricevuta predefinita prima del salvataggio: " . json_encode([
+            'receip_id' => $receiptRow->receip_id,
+            'causal_id' => $receiptRow->causal_id,
+            'amount' => $receiptRow->amount,
+            'divisa' => $receiptRow->divisa,
+        ]));
+
+        $receiptRow->save();
+
+        Log::info("Riga ricevuta 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, $errorsCount)
+    {
+        if ($importCount > 0) {
+            $message = "Importate $importCount fatture con successo.";
+            if ($errorsCount > 0) {
+                $message .= " $errorsCount fatture non sono state importate.";
+            }
+            session()->flash('message', $message);
+        } else {
+            session()->flash('error', 'Nessuna fattura importata. Controlla i file XML e riprova.');
+        }
+    }
 }

+ 20 - 1
app/Models/ReceiptRow.php

@@ -18,6 +18,22 @@ class ReceiptRow extends Model
         'amount',
         'note',
         'commercial',
+        'aliquota_iva',
+        'imponibile',
+        'imposta',
+        'divisa',
+        'numero_linea',
+        'prezzo_unitario',
+        'quantita'
+    ];
+
+    protected $casts = [
+        'when' => 'json',
+        'aliquota_iva' => 'decimal:2',
+        'imponibile' => 'decimal:2',
+        'imposta' => 'decimal:2',
+        'prezzo_unitario' => 'decimal:2',
+        'quantita' => 'decimal:2',
     ];
 
     public function causal()
@@ -25,5 +41,8 @@ class ReceiptRow extends Model
         return $this->belongsTo(Causal::class);
     }
 
+    public function receipt()
+    {
+        return $this->belongsTo(Receipt::class, 'receip_id', 'id');
+    }
 }
-

+ 0 - 1
database/migrations/2025_04_07_132625_add_code_to_payment_methods_and_insert_data.php

@@ -237,7 +237,6 @@ class AddCodeToPaymentMethodsAndInsertData extends Migration
                     ->where('code', $method['code'])
                     ->update($method);
             } else {
-                // Insert new payment method
                 DB::table('payment_methods')->insert($method);
             }
         }

+ 46 - 0
database/migrations/2025_04_08_000000_add_fields_to_receipts_rows_table.php

@@ -0,0 +1,46 @@
+<?php
+
+use Illuminate\Database\Migrations\Migration;
+use Illuminate\Database\Schema\Blueprint;
+use Illuminate\Support\Facades\Schema;
+
+return new class extends Migration
+{
+    /**
+     * Run the migrations.
+     *
+     * @return void
+     */
+    public function up()
+    {
+        Schema::table('receipts_rows', function (Blueprint $table) {
+            $table->decimal('aliquota_iva', 8, 2)->nullable()->after('amount');
+            $table->decimal('imponibile', 8, 2)->nullable()->after('aliquota_iva');
+            $table->decimal('imposta', 8, 2)->nullable()->after('imponibile');
+            $table->string('divisa', 10)->nullable()->after('imposta');
+            $table->integer('numero_linea')->nullable()->after('divisa');
+            $table->decimal('prezzo_unitario', 10, 2)->nullable()->after('numero_linea');
+            $table->decimal('quantita', 10, 2)->nullable()->after('prezzo_unitario');
+        });
+    }
+
+    /**
+     * Reverse the migrations.
+     *
+     * @return void
+     */
+    public function down()
+    {
+        Schema::table('receipts_rows', function (Blueprint $table) {
+            $table->dropColumn([
+                'aliquota_iva',
+                'imponibile',
+                'imposta',
+                'divisa',
+                'numero_linea',
+                'prezzo_unitario',
+                'quantita'
+            ]);
+        });
+    }
+};

+ 55 - 0
database/migrations/2025_04_08_000001_add_fields_and_foreign_key_to_receipts_table.php

@@ -0,0 +1,55 @@
+<?php
+
+use Illuminate\Database\Migrations\Migration;
+use Illuminate\Database\Schema\Blueprint;
+use Illuminate\Support\Facades\Schema;
+
+return new class extends Migration{
+    /**
+     * Run the migrations.
+     *
+     * @return void
+     */
+    public function up()
+    {
+        Schema::table('receipts', function (Blueprint $table) {
+            $table->date('data_documento')->nullable()->after('date');
+            $table->string('numero_fattura')->nullable()->after('number');
+            $table->string('tipo_documento')->nullable()->after('type');
+            $table->string('BIC')->nullable()->after('tipo_documento');
+            $table->string('IBAN')->nullable()->after('BIC');
+            $table->date('data_scadenza')->nullable()->after('IBAN');
+            $table->unsignedBigInteger('bank_id')->nullable()->after('data_scadenza');
+            $table->string('condizioni_pagamento')->nullable()->after('bank_id');
+            $table->boolean('is_ricevuta')->default(false)->after('parent');
+            $table->foreign('bank_id')
+                  ->references('id')
+                  ->on('banks')
+                  ->onDelete('set null')
+                  ->onUpdate('cascade');
+        });
+    }
+
+    /**
+     * Reverse the migrations.
+     *
+     * @return void
+     */
+    public function down()
+    {
+        Schema::table('receipts', function (Blueprint $table) {
+            $table->dropForeign(['bank_id']);
+
+            $table->dropColumn([
+                'data_documento',
+                'numero_fattura',
+                'tipo_documento',
+                'BIC',
+                'IBAN',
+                'data_scadenza',
+                'bank_id',
+                'condizioni_pagamento'
+            ]);
+        });
+    }
+};

+ 106 - 7
resources/views/livewire/records_out.blade.php

@@ -20,26 +20,42 @@
 
     @if(!$add && !$update)
 
-    <div class="title--section_addButton">
-        <button type="button" class="btn--ui entrata d-flex justify-items-between" data-bs-toggle="modal" data-bs-target="#importModal">
+    <div class="title--section_addButton d-flex justify-content-end">
+        <button type="button" class="btn--ui entrata"
+                wire:click="openImportModal" onclick="openImportModal()">
             Importa
         </button>
     </div>
-    <div class="modal fade" id="importModal" tabindex="-1" aria-labelledby="importModalLabel" aria-hidden="true">
+
+        <div class="modal fade" id="importModal" tabindex="-1" aria-labelledby="importModalLabel" aria-hidden="true"
+     wire:ignore.self>
         <div class="modal-dialog">
             <div class="modal-content">
                 <div class="modal-header">
                     <h5 class="modal-title" id="importModalLabel">Importa Ricevute</h5>
-                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
+                    <button type="button" class="btn-close" onclick="closeImportModal()" aria-label="Close"></button>
                 </div>
                 <div class="modal-body">
                     <form wire:submit.prevent="importReceipts">
+                        <div class="mb-3" wire:ignore>
+                            <label for="selectedCausal" class="form-label">Seleziona Causale di Uscita</label>
+                            <select class="form-select import-causal-select" id="selectedCausal" wire:model.defer="selectedCausal">
+                                <option value="">Seleziona una causale</option>
+                                @forelse($importCausals as $causal)
+                                    <option value="{{ $causal['id'] }}">{{ $causal['name'] }}</option>
+                                @empty
+                                    <option value="" disabled>Nessuna causale disponibile</option>
+                                @endforelse
+                            </select>
+                            @error('selectedCausal') <span class="text-danger">{{ $message }}</span> @enderror
+                        </div>
                         <div class="mb-3">
-                            <label for="receiptFile" class="form-label">Seleziona File</label>
-                            <input type="file" class="form-control" id="receiptFile" wire:model="receiptFile">
-                            @error('receiptFile') <span class="text-danger">{{ $message }}</span> @enderror
+                            <label for="receiptFiles" class="form-label">Seleziona Files</label>
+                            <input type="file" class="form-control" id="receiptFiles" wire:model="receiptFiles" multiple>
+                            @error('receiptFiles.*') <span class="text-danger">{{ $message }}</span> @enderror
                         </div>
                         <button type="submit" class="btn--ui">Importa</button>
+                        <button type="button" class="btn--ui lightGrey" onclick="closeImportModal()">Annulla</button>
                     </form>
                 </div>
             </div>
@@ -962,6 +978,89 @@
 
         };
 
+        document.addEventListener('livewire:initialized', () => {
+            let importModalOpen = false;
+            const importModal = document.getElementById('importModal');
+
+            importModal.addEventListener('shown.bs.modal', function () {
+                importModalOpen = true;
+            });
+
+            importModal.addEventListener('hidden.bs.modal', function () {
+                importModalOpen = false;
+            });
+
+            document.addEventListener('livewire:update', function() {
+                if (importModalOpen) {
+                    const modalInstance = bootstrap.Modal.getInstance(importModal);
+                    if (!modalInstance) {
+                        const newModal = new bootstrap.Modal(importModal);
+                        newModal.show();
+                    } else if (!importModal.classList.contains('show')) {
+                        modalInstance.show();
+                    }
+                }
+            });
+
+            document.querySelectorAll('.select2-container').forEach(select => {
+                select.addEventListener('click', function(e) {
+                    e.stopPropagation();
+                });
+            });
+        });
+
+        function initImportCausalSelect() {
+            $('.import-causal-select').select2({
+                dropdownParent: $('#importModal'),
+                language: {
+                    noResults: function() {
+                        return "Nessun risultato";
+                    }
+                }
+            });
+
+            $('.import-causal-select').on('change', function() {
+                let selectedValue = $(this).val();
+                Livewire.first().set('selectedCausal', selectedValue);
+            });
+        }
+
+    // Function to open the modal
+    function openImportModal() {
+        const importModal = new bootstrap.Modal(document.getElementById('importModal'));
+        importModal.show();
+
+        setTimeout(function() {
+            initImportCausalSelect();
+        }, 200);
+    }
+
+    document.addEventListener('DOMContentLoaded', function() {
+        if (document.getElementById('importModal')) {
+            initImportCausalSelect();
+        }
+
+
+        Livewire.on('load-select', function() {
+            if (document.getElementById('importModal') &&
+                document.getElementById('importModal').classList.contains('show')) {
+                initImportCausalSelect();
+            }
+        });
+    });
+
+    function closeImportModal() {
+        const importModal = bootstrap.Modal.getInstance(document.getElementById('importModal'));
+        if (importModal) {
+            importModal.hide();
+        }
+        Livewire.first().call('closeImportModal');
+
+        setTimeout(function() {
+            window.location.reload();
+        }, 100);
+    }
+
     </script>
 
 @endpush