Bladeren bron

Merge branch 'master' of http://host.webmagistri.biz:3000/parisio/iao_team

Luca Parisio 8 maanden geleden
bovenliggende
commit
170b4072b3

+ 71 - 63
app/Http/Livewire/Record.php

@@ -259,12 +259,15 @@ class Record extends Component
     }
     public function export()
     {
+        ini_set('memory_limit', '512M');
+
+        gc_enable();
+
         $letters = array('F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'AA');
 
         $spreadsheet = new Spreadsheet();
         $activeWorksheet = $spreadsheet->getActiveSheet();
 
-        //$activeWorksheet->setCellValue('A1', 'PrimaNota');
         $activeWorksheet->setCellValue('A1', "Data");
         $activeWorksheet->setCellValue('B1', "Causale");
         $activeWorksheet->setCellValue('C1', "Dettaglio");
@@ -297,7 +300,6 @@ class Record extends Component
                 if ($idx >= count($letters)) {
                     break;
                 }
-
                 $activeWorksheet->setCellValue($letters[$idx] . '2', "Entrate");
                 $idx++;
                 $activeWorksheet->setCellValue($letters[$idx] . '2', "Uscite");
@@ -306,7 +308,6 @@ class Record extends Component
                 if ($idx >= count($letters)) {
                     break;
                 }
-
                 $activeWorksheet->setCellValue($letters[$idx] . '2', "Entrate");
                 $idx++;
                 $activeWorksheet->setCellValue($letters[$idx] . '2', "");
@@ -315,7 +316,6 @@ class Record extends Component
                 if ($idx >= count($letters)) {
                     break;
                 }
-
                 $activeWorksheet->setCellValue($letters[$idx] . '2', "");
                 $idx++;
                 $activeWorksheet->setCellValue($letters[$idx] . '2', "Uscite");
@@ -325,62 +325,73 @@ class Record extends Component
 
         $activeWorksheet->getStyle('A1:Q1')->getFont()->setBold(true);
         $activeWorksheet->getStyle('A2:Q2')->getFont()->setBold(true);
-        // $activeWorksheet->getStyle('A1:N1')->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('00ff00');
 
         $count = 3;
+        $batchSize = 1000;
+        $recordsProcessed = 0;
+
+        $totalRecords = count($this->records);
+        $recordsArray = array_chunk($this->records, $batchSize, true);
+
+        foreach ($recordsArray as $recordsBatch) {
+            foreach ($recordsBatch as $causal => $record) {
+                $check = strpos($causal, "$") ? explode("$", $causal)[1] : $causal;
+
+                $parts = explode("§", $check);
+                $d = $parts[0] ?? '';
+                $c = $parts[1] ?? '';
+                $j = $parts[2] ?? '';
+                $k = $parts[3] ?? '';
+                $deleted = $parts[4] ?? '';
+                $numeroLinea = $parts[5] ?? '';
+
+                $activeWorksheet->setCellValue('A' . $count, !empty($d) ? date("d/m/Y", strtotime($d)) : '');
+                $activeWorksheet->setCellValue('B' . $count, $c);
+                $activeWorksheet->setCellValue('C' . $count, $k);
+                $activeWorksheet->setCellValue('D' . $count, $j);
+
+                $stato = ($deleted === 'DELETED') ? 'ANNULLATA' : '';
+                $activeWorksheet->setCellValue('E' . $count, $stato);
+
+                if ($stato === 'ANNULLATA') {
+                    $activeWorksheet->getStyle('E' . $count)->getFont()->getColor()->setARGB('FFFF0000');
+                }
 
-        $totals = [];
-
-        foreach ($this->records as $causal => $record) {
-
-            $check = strpos($causal, "$") ? explode("$", $causal)[1] : $causal;
-            list($d, $c, $j, $k, $deleted, $numeroLinea) = explode("§", $check);
-
-            $activeWorksheet->setCellValue('A' . $count, date("d/m/Y", strtotime($d)));
-            $activeWorksheet->setCellValue('B' . $count, $c);
-            $activeWorksheet->setCellValue('C' . $count, $k);
-            $activeWorksheet->setCellValue('D' . $count, $j);
-
-            $stato = ($deleted === 'DELETED') ? 'ANNULLATA' : '';
-            $activeWorksheet->setCellValue('E' . $count, $stato);
-
-            if ($stato === 'ANNULLATA') {
-                $activeWorksheet->getStyle('E' . $count)->getFont()->getColor()->setARGB('FFFF0000');
-            }
+                $idx = 0;
+                foreach ($this->payments as $p) {
+                    if ($idx >= count($letters) - 1) {
+                        break;
+                    }
 
-            $idx = 0;
-            foreach ($this->payments as $p) {
-                if (isset($record[$p->name])) {
+                    if (isset($record[$p->name])) {
+                        $inValue = isset($record[$p->name]["IN"]) ? formatPrice($record[$p->name]["IN"]) : "";
+                        $outValue = isset($record[$p->name]["OUT"]) ? formatPrice($record[$p->name]["OUT"]) : "";
 
-                    if (isset($record[$p->name]["IN"])) {
-                        $activeWorksheet->setCellValue($letters[$idx] . $count, formatPrice($record[$p->name]["IN"]));
+                        $activeWorksheet->setCellValue($letters[$idx] . $count, $inValue);
+                        $idx++;
+                        $activeWorksheet->setCellValue($letters[$idx] . $count, $outValue);
+                        $idx++;
                     } else {
                         $activeWorksheet->setCellValue($letters[$idx] . $count, "");
-                    }
-                    $idx++;
-                    if (isset($record[$p->name]["OUT"])) {
-                        $activeWorksheet->setCellValue($letters[$idx] . $count, formatPrice($record[$p->name]["OUT"]));
-                    } else {
+                        $idx++;
                         $activeWorksheet->setCellValue($letters[$idx] . $count, "");
+                        $idx++;
                     }
-                    $idx++;
-                } else {
-                    if ($idx >= count($letters)) {
-                        break;
-                    }
+                }
 
-                    $activeWorksheet->setCellValue($letters[$idx] . $count, "");
-                    $idx++;
-                    $activeWorksheet->setCellValue($letters[$idx] . $count, "");
-                    $idx++;
+                $count++;
+                $recordsProcessed++;
+
+                if ($recordsProcessed % 500 === 0) {
+                    gc_collect_cycles();
                 }
             }
 
-            $count += 1;
+            unset($recordsBatch);
+            gc_collect_cycles();
         }
 
-        $count += 1;
-
+        $count++;
         $idx = 0;
 
         $activeWorksheet->setCellValue('A' . $count, 'Totale');
@@ -390,47 +401,39 @@ class Record extends Component
         $activeWorksheet->setCellValue('E' . $count, '');
 
         foreach ($this->payments as $p) {
+            if ($idx >= count($letters) - 1) {
+                break;
+            }
+
             if (isset($this->totals[$p->name])) {
                 if ($p->type == 'ALL') {
-                    $activeWorksheet->setCellValue($letters[$idx] . $count, formatPrice($this->totals[$p->name]["IN"]));
+                    $activeWorksheet->setCellValue($letters[$idx] . $count, formatPrice($this->totals[$p->name]["IN"] ?? 0));
                     $idx++;
-                    $activeWorksheet->setCellValue($letters[$idx] . $count, formatPrice($this->totals[$p->name]["OUT"]));
+                    $activeWorksheet->setCellValue($letters[$idx] . $count, formatPrice($this->totals[$p->name]["OUT"] ?? 0));
                     $idx++;
                 } elseif ($p->type == 'IN') {
-                    $activeWorksheet->setCellValue($letters[$idx] . $count, formatPrice($this->totals[$p->name]["IN"]));
+                    $activeWorksheet->setCellValue($letters[$idx] . $count, formatPrice($this->totals[$p->name]["IN"] ?? 0));
                     $idx++;
                     $activeWorksheet->setCellValue($letters[$idx] . $count, "");
                     $idx++;
                 } elseif ($p->type == 'OUT') {
                     $activeWorksheet->setCellValue($letters[$idx] . $count, "");
                     $idx++;
-                    $activeWorksheet->setCellValue($letters[$idx] . $count, formatPrice($this->totals[$p->name]["OUT"]));
+                    $activeWorksheet->setCellValue($letters[$idx] . $count, formatPrice($this->totals[$p->name]["OUT"] ?? 0));
                     $idx++;
                 }
             } else {
                 if ($p->type == 'ALL') {
-                    if ($idx >= count($letters)) {
-                        break;
-                    }
-
                     $activeWorksheet->setCellValue($letters[$idx] . $count, "0");
                     $idx++;
                     $activeWorksheet->setCellValue($letters[$idx] . $count, "0");
                     $idx++;
                 } elseif ($p->type == 'IN') {
-                    if ($idx >= count($letters)) {
-                        break;
-                    }
-
                     $activeWorksheet->setCellValue($letters[$idx] . $count, "0");
                     $idx++;
                     $activeWorksheet->setCellValue($letters[$idx] . $count, "");
                     $idx++;
                 } elseif ($p->type == 'OUT') {
-                    if ($idx >= count($letters)) {
-                        break;
-                    }
-
                     $activeWorksheet->setCellValue($letters[$idx] . $count, "");
                     $idx++;
                     $activeWorksheet->setCellValue($letters[$idx] . $count, "0");
@@ -446,11 +449,16 @@ class Record extends Component
         $activeWorksheet->getColumnDimension('C')->setWidth(40);
         $activeWorksheet->getColumnDimension('D')->setWidth(40);
         $activeWorksheet->getColumnDimension('E')->setWidth(20);
-        foreach ($letters as $l)
+        foreach ($letters as $l) {
             $activeWorksheet->getColumnDimension($l)->setWidth(20);
+        }
 
         $writer = new Xlsx($spreadsheet);
-        $writer->save($path = storage_path('prima_nota_' . date("YmdHis") . '.xlsx'));
+        $path = storage_path('prima_nota_' . date("YmdHis") . '.xlsx');
+        $writer->save($path);
+
+        unset($spreadsheet, $activeWorksheet, $writer);
+        gc_collect_cycles();
 
         return response()->download($path)->deleteFileAfterSend();
     }

+ 23 - 9
app/Http/Livewire/RecordIN.php

@@ -611,8 +611,7 @@ class RecordIN extends Component
                     $no_receipt_causal = true;
 
                 if ($cau->money) {
-                    if ($rowNet >= env('MIN_MONEY', 100))
-                    {
+                    if ($rowNet >= env('MIN_MONEY', 100)) {
                         $money = new \App\Models\Money();
                         $money->member_id = $this->member_id;
                         $money->record_id = $this->dataId;
@@ -1004,6 +1003,18 @@ class RecordIN extends Component
                 if ($exist != null)
                     $number = $exist->number + 1;
 
+                // Calculate totals for the receipt
+                $totalGross = 0;
+                $totalNet = 0;
+                foreach ($this->rows as $row) {
+                    $rowAmount = $this->currencyToDouble($row["amount"]);
+                    $rowSconto = isset($row['sconto']) ? $this->currencyToDouble($row['sconto']) : 0;
+                    $rowNet = max(0, $rowAmount - $rowSconto);
+
+                    $totalGross += $rowAmount;
+                    $totalNet += $rowNet;
+                }
+
                 $receipt = \App\Models\Receipt::create([
                     'record_id' => $this->dataId,
                     'member_id' => $this->member_id,
@@ -1016,14 +1027,22 @@ class RecordIN extends Component
                     'parent' => $this->parent,
                     'status' => 1,
                 ]);
+
                 foreach ($this->rows as $row) {
-                    Log::info("Row - Gross: " . $row["amount"] . ", Sconto: " . $row["sconto"] . ", Net: " . $row["amount"]);
+                    $rowAmount = $this->currencyToDouble($row["amount"]);
+                    $rowSconto = isset($row['sconto']) ? $this->currencyToDouble($row['sconto']) : 0;
+                    $rowNet = max(0, $rowAmount - $rowSconto);
+
+                    Log::info("Receipt Row - Gross: " . $rowAmount . ", Sconto: " . $rowSconto . ", Net: " . $rowNet);
+
                     \App\Models\ReceiptRow::create([
                         'receip_id' => $receipt->id,
                         'causal_id' => $row["causal_id"],
                         'note' => $row["note"],
                         'vat_id' => $row["vat_id"],
-                        'amount' => $this->currencyToDouble($row["amount"]) - $this->currencyToDouble($row["sconto"]),
+                        'amount' => $rowNet,
+                        'prediscount_amount' => $rowAmount,
+                        'sconto' => $rowSconto,
                         'commercial' => $row["commercial"],
                         'when' => json_encode($row["when"])
                     ]);
@@ -1033,10 +1052,8 @@ class RecordIN extends Component
 
                 sendReceiptEmail($receipt);
 
-
                 session()->flash('receipt', "Ricevuta " . $number . "/" . date("Y") . " creata correttamente");
 
-                // Apro la ricevuta
                 $this->emit('showReceipt', $this->currentReceip->id);
             }
         }
@@ -1091,15 +1108,12 @@ class RecordIN extends Component
 
         foreach ($this->rows as $r) {
             if ($r["amount"] != null && $r["amount"] != "") {
-                // Get the amount after discount
                 $rowAmount = $this->currencyToDouble($r["amount"]);
                 $rowSconto = isset($r['sconto']) ? $this->currencyToDouble($r['sconto']) : 0;
                 $netAmount = max(0, $rowAmount - $rowSconto);
 
-                // Add net amount to total
                 $total += $netAmount;
 
-                // Add VAT if applicable (calculated on net amount)
                 if ($r["vat_id"] > 0)
                     $total += getVatValue($netAmount, $r["vat_id"]);
             }

+ 1 - 1
app/Http/Livewire/RecordOUT.php

@@ -1090,7 +1090,7 @@ class RecordOUT extends Component
         $record->supplier_id = $supplierId;
         $record->payment_method_id = $paymentMethodId;
         $record->date = $fatturaData['dataDocumento'];
-        $record->data_pagamento = $fatturaData['dataDocumento'];
+        //$record->data_pagamento = $fatturaData['dataDocumento'];
         $record->numero_fattura = $fatturaData['numeroFattura'];
         $record->type = 'OUT';
         $record->commercial = 1;

+ 3 - 1
app/Models/ReceiptRow.php

@@ -24,7 +24,9 @@ class ReceiptRow extends Model
         'divisa',
         'numero_linea',
         'prezzo_unitario',
-        'quantita'
+        'quantita',
+        'prediscount_amount',
+        'sconto',
     ];
 
     protected $casts = [

+ 42 - 0
database/migrations/2025_05_23_000000_add_field_sconti_to_receipts_rows_table.php

@@ -0,0 +1,42 @@
+<?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) {
+            if (!Schema::hasColumn('receipts_rows', 'prediscount_amount')) {
+                $table->decimal('prediscount_amount', 10, 2)->nullable()->after('amount');
+            }
+            if (!Schema::hasColumn('receipts_rows', 'sconto')) {
+                $table->decimal('sconto', 10, 2)->default(0)->after('prediscount_amount');
+            }
+        });
+    }
+
+    /**
+     * Reverse the migrations.
+     *
+     * @return void
+     */
+    public function down()
+    {
+        Schema::table('receipts', function (Blueprint $table) {
+            $table->dropColumn('prediscount_amount');
+        });
+
+        Schema::table('receipt_rows', function (Blueprint $table) {
+            $table->dropColumn(['prediscount_amount', 'sconto']);
+        });
+    }
+};

+ 4 - 7
resources/views/livewire/records_in.blade.php

@@ -498,17 +498,14 @@
                                                             @php
                                                                 $rowAmount = $this->currencyToDouble($rows[$idx]["amount"]);
                                                                 $rowSconto = isset($rows[$idx]["sconto"]) ? $this->currencyToDouble($rows[$idx]["sconto"]) : 0;
-                                                                $totalValue = $rowAmount; // Use original amount for display
 
-                                                                // Add VAT if applicable
+                                                                $totalValue = max(0, $rowAmount - $rowSconto);
+
                                                                 if ($rows[$idx]["vat_id"] > 0) {
-                                                                    // Use amount after sconto for VAT calculation
-                                                                    $netAmount = max(0, $rowAmount - $rowSconto);
-                                                                    $vatAmount = getVatValue($netAmount, $rows[$idx]["vat_id"]);
-                                                                    $totalValue = $rowAmount + $vatAmount;
+                                                                    $vatAmount = getVatValue($totalValue, $rows[$idx]["vat_id"]);
+                                                                    $totalValue = $totalValue + $vatAmount;
                                                                 }
 
-                                                                // Calculate per period
                                                                 $valuePerPeriod = sizeof($rows[$idx]["when"]) > 0 ? $totalValue / sizeof($rows[$idx]["when"]) : 0;
                                                             @endphp
                                                             {{ $rowAmount > 0 ? formatPrice($valuePerPeriod) : "" }}

+ 36 - 14
resources/views/receipt.blade.php

@@ -72,22 +72,44 @@
     @endif
     <hr><br>
 
-    @php
+   @php
     $total = 0;
-    @endphp
-    @foreach($receipt->rows as $row)
-        <b>Causale</b>: {{@$row->causal->getTree()}}<br><br>
-        <b>Dettaglio causale</b>: {{$row->note != '' ? $row->note : ''}}<br><br>
-        <b>Importo</b>: {{formatPrice($row->amount)}}<br><br>
-        @php
+    $totalSconto = 0;
+    $totalPrediscount = 0;
+    $hasDiscount = false;
+@endphp
+
+@foreach($receipt->rows as $row)
+    <b>Causale</b>: {{@$row->causal->getTree()}}<br><br>
+    <b>Dettaglio causale</b>: {{$row->note != '' ? $row->note : ''}}<br><br>
+
+    @if($row->sconto > 0)
+        @php $hasDiscount = true; @endphp
+        <b>Importo</b>: {{formatPrice($row->prediscount_amount)}}<br><br>
+        <b>Sconto</b>: {{formatPrice($row->sconto)}}<br><br>
+    @endif
+
+    <b>{{$row->sconto > 0 ? 'Importo finale' : 'Importo'}}</b>: {{formatPrice($row->amount)}}<br><br>
+    <hr><br>
+    @php
+        $totalSconto += $row->sconto;
+        $totalPrediscount += $row->prediscount_amount;
         $total += $row->amount;
-        @endphp
-    @endforeach
-    <br><br>
-    <b>Totale</b>: {{formatPrice($total)}}
-    <footer>
-        <small>{{env('LOCALITA', '')}} ({{env('PROVINCIA', '')}}) li {{date("d/m/Y", strtotime($receipt->created_at))}}</small>
-    </footer>
+    @endphp
+@endforeach
+
+<br><br>
+
+@if($hasDiscount)
+    <b>Totale prescontato</b>: {{formatPrice($totalPrediscount)}}<br><br>
+    <b>Sconto totale</b>: {{formatPrice($totalSconto)}}<br><br>
+@endif
+
+<b>Totale</b>: {{formatPrice($total)}}<br><br>
+
+<footer>
+    <small>{{env('LOCALITA', '')}} ({{env('PROVINCIA', '')}}) li {{date("d/m/Y", strtotime($receipt->created_at))}}</small>
+</footer>
 
 </body>
 </html>