소스 검색

iva uscite

FabioFratini 8 달 전
부모
커밋
3b3773a6dc
3개의 변경된 파일143개의 추가작업 그리고 30개의 파일을 삭제
  1. 2 2
      app/Http/Livewire/RecordIN.php
  2. 100 4
      app/Http/Livewire/RecordOUT.php
  3. 41 24
      resources/views/livewire/records_out.blade.php

+ 2 - 2
app/Http/Livewire/RecordIN.php

@@ -874,7 +874,7 @@ class RecordIN extends Component
                 \App\Models\Record::find($this->dataId)->delete();
                 session()->flash('success',"Movimento eliminato");
             }catch(\Exception $e){
-                session()->flash('error','Errore (' . $ex->getMessage() . ')');
+                session()->flash('error','Errore (' . $e->getMessage() . ')');
             }
         }
         $this->isDuplicate = false;
@@ -943,7 +943,7 @@ class RecordIN extends Component
                 \App\Models\Record::find($id)->delete();
             }
         }catch(\Exception $e){
-            session()->flash('error','Errore (' . $ex->getMessage() . ')');
+            session()->flash('error','Errore (' . $e->getMessage() . ')');
         }
         $this->multipleAction = '';
     }

+ 100 - 4
app/Http/Livewire/RecordOUT.php

@@ -86,6 +86,8 @@ class RecordOUT extends Component
     public $selectedCausal = '';
     public $importCausals = array();
 
+    public $vats = array();
+
 
     protected $rules = [
         'supplier_id' => 'required',
@@ -135,7 +137,7 @@ class RecordOUT extends Component
             'when' => array(array('month' => date("n"), 'year' => date("Y"), 'period' => '')),
             'amount' => null,
             'imponibile' => null,
-            'aliquota_iva' => null,
+            'aliquota_iva' => '',
             'note' => '',
             'commercial' => 0
         );
@@ -173,6 +175,9 @@ class RecordOUT extends Component
         if (empty($this->importCausals)) {
             $this->loadImportCausals();
         }
+
+        $this->vats = \App\Models\Vat::select('id', 'name', 'value')->orderBy('value')->get();
+
     }
 
     public function mount()
@@ -199,6 +204,7 @@ class RecordOUT extends Component
 
         $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->vats = \App\Models\Vat::select('id', 'name', 'value')->orderBy('value')->get();
 
         $this->importCausals = [];
         $this->loadImportCausals();
@@ -483,16 +489,40 @@ class RecordOUT extends Component
                         '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
+                    $vatLookup = [];
+                    foreach ($this->vats as $vat) {
+                        $vatLookup[(string)$vat->value] = $vat->value;
+                    }
+
                     if (isset($recordRow->aliquota_iva)) {
-                        $rowData['aliquota_iva'] = $recordRow->aliquota_iva . '%';
+                        $dbVatValue = (string)$recordRow->aliquota_iva;
+                        if (isset($vatLookup[$dbVatValue])) {
+                            $rowData['aliquota_iva'] = (string)$vatLookup[$dbVatValue];
+                        } else {
+                            $dbVatValueFloat = floatval($dbVatValue);
+                            $closestMatch = null;
+                            $minDiff = PHP_FLOAT_MAX;
+
+                            foreach ($vatLookup as $vatValue) {
+                                $diff = abs($dbVatValueFloat - floatval($vatValue));
+                                if ($diff < $minDiff && $diff < 0.1) {
+                                    $minDiff = $diff;
+                                    $closestMatch = $vatValue;
+                                }
+                            }
+                            if ($closestMatch !== null) {
+                                $rowData['aliquota_iva'] = (string)$closestMatch;
+                            } else {
+                                $rowData['aliquota_iva'] = $dbVatValue;
+                            }
+                        }
                     }
 
+
                     $this->rows[] = $rowData;
                 }
             }
@@ -1173,6 +1203,12 @@ class RecordOUT extends Component
             'period' => $period
         ]];
 
+        $vatId = null;
+        if (isset($linea['aliquotaIva']) && $linea['aliquotaIva'] > 0) {
+            $vatId = $this->findOrCreateVat($linea['aliquotaIva']);
+            Log::info("Using VAT ID: $vatId for rate: {$linea['aliquotaIva']}%");
+        }
+
         $recordRow = new \App\Models\RecordRow();
         $recordRow->record_id = $recordId;
         $recordRow->causal_id = $this->selectedCausal;
@@ -1224,6 +1260,12 @@ class RecordOUT extends Component
             'year' => $year,
             'period' => $period
         ]];
+
+        $vatId = null;
+        if (isset($riepilogo['aliquotaIva']) && $riepilogo['aliquotaIva'] > 0) {
+            $vatId = $this->findOrCreateVat($riepilogo['aliquotaIva']);
+            Log::info("Using VAT ID: $vatId for rate: {$riepilogo['aliquotaIva']}%");
+        }
         $total_amount = $riepilogo['imponibile'] + $riepilogo['imposta'];
         $recordRow = new \App\Models\RecordRow();
         $recordRow->record_id = $recordId;
@@ -1417,4 +1459,58 @@ class RecordOUT extends Component
         // Per altri errori, conserva il messaggio originale ma semplificalo
         return $errorMessage;
     }
+
+    public function getVats()
+    {
+        $vats = array();
+        foreach($this->rows as $r)
+        {
+            if ($r["amount"] != null && $r["amount"] != "" && $r["vat_id"] > 0)
+            {
+                $vat = getVatValue($this->currencyToDouble($r["amount"]), $r["vat_id"]);
+                $vatName = "";
+                foreach($this->vats as $v)
+                {
+                    if ($v->id == $r["vat_id"])
+                        $vatName = $v->name;
+                }
+                if (isset($vats[$vatName]))
+                    $vats[$vatName] += $vat;
+                else
+                    $vats[$vatName] = $vat;
+            }
+        }
+        return $vats;
+    }
+
+    private function findOrCreateVat($vatRate)
+    {
+        $vatRate = (float)$vatRate;
+        Log::info("Searching for VAT rate: $vatRate%");
+
+        $existingVat = \App\Models\Vat::where(function ($query) use ($vatRate) {
+            $query->whereRaw('ABS(value - ?) < 0.01', [$vatRate]);
+        })->first();
+
+        if ($existingVat) {
+            Log::info("Found existing VAT rate: ID={$existingVat->id}, Name={$existingVat->name}, Value={$existingVat->value}");
+            return $existingVat->id;
+        }
+
+        Log::info("Creating new VAT rate: $vatRate%");
+
+        $vatName = "IVA $vatRate%";
+
+        $newVat = new \App\Models\Vat();
+        $newVat->name = $vatName;
+        $newVat->value = $vatRate;
+        $newVat->enabled = 1;
+        $newVat->save();
+
+        Log::info("Created new VAT rate: ID={$newVat->id}, Name={$newVat->name}, Value={$newVat->value}");
+
+        $this->vats = \App\Models\Vat::select('id', 'name', 'value')->orderBy('value')->get();
+
+        return $newVat->id;
+    }
 }

+ 41 - 24
resources/views/livewire/records_out.blade.php

@@ -325,29 +325,28 @@
                                     @enderror
                                 </div>
                             </div>
-
-                            <div class="row gx-2 mt-5 align-items-center">
-                                <div class="col-md-6">
-                                    <span class="total primary">Aliquota IVA (%)</span>
-                                </div>
-                                <div class="col-md-6">
-                                    @if($add)
-                                        <input type="text" class="form-control text-end @error('rows.{{$idx}}.aliquota_iva') is-invalid @enderror"
-                                            id="rows.{{$idx}}.aliquota_iva" wire:model="rows.{{$idx}}.aliquota_iva"
-                                            wire:keydown.enter="store(false)" onkeyup="onlyNumberPercent(this)" placeholder="0%">
-                                    @endif
-                                    @if($update)
-                                        <input type="text" class="form-control text-end @error('rows.{{$idx}}.aliquota_iva') is-invalid @enderror"
-                                            id="rows.{{$idx}}.aliquota_iva" placeholder="0%" wire:model="rows.{{$idx}}.aliquota_iva"
-                                            onkeyup="onlyNumberPercent(this)" wire:keydown.enter="update(false)">
-                                    @endif
-                                    @error('rows.'. $idx . '.aliquota_iva')
-                                        <span style="margin-top: 0.25rem; font-size: 0.875em; color: var(--bs-form-invalid-color);">{{ $message }}</span>
-                                    @enderror
+                            @if($commercial)
+                                <div class="row gx-2 mt-5 align-items-center">
+                                    <div class="col-md-6">
+                                        <span class="total primary">Aliquota IVA</span>
+                                    </div>
+                                    <div class="col-md-2 ms-auto">
+                                        @if($add || $update )
+                                            <select class="form-select text-end @error('rows.'.$idx.'.aliquota_iva') is-invalid @enderror"
+                                                id="rows.{{$idx}}.aliquota_iva"
+                                                wire:model="rows.{{$idx}}.aliquota_iva">
+                                                <option value="">--Seleziona--</option>
+                                                @foreach($vats as $vat)
+                                                    <option value="{{$vat->value}}">{{$vat->name}}</option>
+                                                @endforeach
+                                            </select>
+                                            @error('rows.'. $idx . '.aliquota_iva')
+                                                <span style="margin-top: 0.25rem; font-size: 0.875em; color: var(--bs-form-invalid-color);">{{ $message }}</span>
+                                            @enderror
+                                        @endif
+                                    </div>
                                 </div>
-                            </div>
-
-
+                            @endif
                             <div class="row gx-2 mt-5 align-items-center">
                                 <div class="col-md-6">
                                     <span class="total primary">Importo</span>
@@ -1233,8 +1232,7 @@
                 let imponibile = imponibileField.value.replace('€', '').replace(/\./g, '').replace(',', '.').trim();
                 imponibile = parseFloat(imponibile) || 0;
 
-                let aliquota = aliquotaField.value.replace('%', '').trim();
-                aliquota = parseFloat(aliquota) || 0;
+                let aliquota = parseFloat(aliquotaField.value) || 0;
 
                 const imposta = imponibile * (aliquota / 100);
                 const totalAmount = imponibile + imposta;
@@ -1271,9 +1269,28 @@
         });
 
         Livewire.on('load-select', function() {
+            $('select[id^="rows."][id$=".aliquota_iva"]').each(function(i, obj) {
+            $(obj).select2({
+                "language": {"noResults": function(){return "Nessun risultato";}}
+            });
+            $(obj).on('change', function (e) {
+                const data = $(obj).select2("val");
+                const name = $(obj).attr("id");
+                const rowIndex = name.match(/rows\.(\d+)\./)[1];
+
+                const component = Livewire.find(document.querySelector('[wire\\:id]').getAttribute('wire:id'));
+                if (component) {
+                    component.set(name, data);
+                }
+
+                calculateAmount(rowIndex);
+            });
+            });
             setTimeout(setupCalculationListeners, 300);
         });
     });
+
+
     </script>
 
 @endpush