Kaynağa Gözat

nuovo export prima nota

FabioFratini 7 ay önce
ebeveyn
işleme
b3439e64af

+ 253 - 27
app/Http/Livewire/Record.php

@@ -16,28 +16,22 @@ use Illuminate\Support\Facades\Log;
 class Record extends Component
 {
     public $records, $dataId, $totals;
-
     public $in;
     public $out;
-
     public $payments = [];
-
     public $fromDate;
     public $toDate;
-
     public $appliedFromDate;
     public $appliedToDate;
-
+    public $exportFromDate;
+    public $exportToDate;
+    public $isExporting = false;
     public $selectedPeriod = 'OGGI';
-
     public $filterCausals = null;
     public $filterMember = null;
-
     public $isFiltering = false;
-
     public array $recordDatas = [];
     public array $labels = [];
-
     public array $causals = [];
     public $members = array();
 
@@ -54,6 +48,9 @@ class Record extends Component
         $this->appliedFromDate = date("Y-m-d");
         $this->appliedToDate = date("Y-m-d");
 
+        $this->exportFromDate = date("Y-m-d");
+        $this->exportToDate = date("Y-m-d");
+
         $this->getCausals(\App\Models\Causal::select('id', 'name')->where('parent_id', null)->get(), 0);
 
         $this->members = \App\Models\Member::select(['id', 'first_name', 'last_name', 'fiscal_code'])->orderBy('last_name')->orderBy('first_name')->get();
@@ -61,6 +58,214 @@ class Record extends Component
         $this->payments = \App\Models\PaymentMethod::select('id', 'name', 'type')->where('enabled', true)->where('money', false)->get();
     }
 
+    private function generateExportData($fromDate, $toDate)
+    {
+        $exportRecords = array();
+        $exportTotals = array();
+
+        $exclude_from_records = \App\Models\Member::where('exclude_from_records', true)->pluck('id')->toArray();
+
+        $datas = \App\Models\Record::with('member', 'supplier', 'payment_method')
+            ->select('records.*', 'records_rows.*')
+            ->join('records_rows', 'records.id', '=', 'records_rows.record_id')
+            ->whereBetween('date', [$fromDate, $toDate])
+            ->where(function ($query) {
+                $query->where('type', 'OUT')
+                    ->orWhere(function ($query) {
+                        $query->where('records.corrispettivo_fiscale', true)
+                            ->orWhere('records.commercial', false);
+                    });
+            })
+            ->where(function ($query) use ($exclude_from_records) {
+                $query->where('type', 'OUT')
+                    ->orWhere(function ($subquery) use ($exclude_from_records) {
+                        $subquery->whereNotIn('member_id', $exclude_from_records);
+                    });
+            });
+
+        if ($this->filterCausals != null && sizeof($this->filterCausals) > 0) {
+            $causals = array();
+            foreach ($this->filterCausals as $z) {
+                $causals[] = $z;
+                $childs = \App\Models\Causal::where('parent_id', $z)->get();
+                foreach ($childs as $c) {
+                    $causals[] = $c->id;
+                    $childsX = \App\Models\Causal::where('parent_id', $c->id)->get();
+                    foreach ($childsX as $cX) {
+                        $causals[] = $cX->id;
+                    }
+                }
+            }
+            $datas->whereIn('causal_id', $causals);
+        }
+        if ($this->filterMember != null && $this->filterMember > 0) {
+            $datas->where('member_id', $this->filterMember);
+        }
+        $datas = $datas->orderBy('date', 'ASC')
+            ->orderBy('records.created_at', 'ASC')
+            ->orderBy('records_rows.id', 'ASC')
+            ->get();
+
+        $groupedData = [];
+        $causalsCount = [];
+
+        foreach ($datas as $idx => $data) {
+            $causalCheck = \App\Models\Causal::findOrFail($data->causal_id);
+            $paymentCheck = $data->payment_method->money;
+
+            if (!$paymentCheck && ($causalCheck->no_first == null || !$causalCheck->no_first)) {
+                if (!$data->deleted) {
+                    $amount = $data->amount;
+                    $amount += getVatValue($amount, $data->vat_id);
+                } else {
+                    $amount = $data->amount;
+                }
+
+                $typeLabel = $data->commercial ? 'Commerciale' : 'Non Commerciale';
+
+                $nominativo = '';
+                if ($data->type == "IN") {
+                    if ($data->member) {
+                        $nominativo = $data->member->last_name . " " . $data->member->first_name;
+                    }
+                } else {
+                    if ($data->supplier) {
+                        $nominativo = $data->supplier->name;
+                    }
+                }
+
+                $groupKey = $data->date . '|' . $typeLabel . '|' . $data->payment_method->name . '|' . $data->type . '|' . $nominativo;
+
+                if (!isset($groupedData[$groupKey])) {
+                    $groupedData[$groupKey] = [
+                        'date' => $data->date,
+                        'type_label' => $typeLabel,
+                        'payment_method' => $data->payment_method->name,
+                        'transaction_type' => $data->type,
+                        'nominativo' => $nominativo,
+                        'amount' => 0,
+                        'deleted' => false,
+                        'causals' => [],
+                        'notes' => []
+                    ];
+                    $causalsCount[$groupKey] = [];
+                }
+
+                $groupedData[$groupKey]['amount'] += $amount;
+                $causalsCount[$groupKey][$causalCheck->getTree()] = true;
+
+                if (!empty($data->note)) {
+                    $groupedData[$groupKey]['notes'][] = $data->note;
+                }
+
+                if ($data->deleted) {
+                    $groupedData[$groupKey]['deleted'] = true;
+                }
+            }
+        }
+
+        foreach ($groupedData as $groupKey => $group) {
+            $causalsInGroup = array_keys($causalsCount[$groupKey]);
+
+            $causalDisplay = $group['type_label'];
+
+            if (count($causalsInGroup) > 1) {
+                $detailDisplay = 'Varie|' . implode('|', $causalsInGroup);
+            } else {
+                $detailDisplay = $causalsInGroup[0];
+            }
+
+            $recordKey = $group['date'] . "§" . $causalDisplay . "§" . $group['nominativo'] . "§" . $detailDisplay . "§" . ($group['deleted'] ? 'DELETED' : '') . "§";
+
+            if (!isset($exportRecords[$recordKey][$group['payment_method']][$group['transaction_type']])) {
+                $exportRecords[$recordKey][$group['payment_method']][$group['transaction_type']] = 0;
+            }
+
+            $exportRecords[$recordKey][$group['payment_method']][$group['transaction_type']] += $group['amount'];
+
+            if (!isset($exportTotals[$group['payment_method']])) {
+                $exportTotals[$group['payment_method']]["IN"] = 0;
+                $exportTotals[$group['payment_method']]["OUT"] = 0;
+            }
+
+            if (!$group['deleted'])
+                $exportTotals[$group['payment_method']][$group['transaction_type']] += $group['amount'];
+        }
+
+        return $exportRecords;
+    }
+
+    private function generateExportTotals($fromDate, $toDate)
+    {
+        $exportTotals = array();
+
+        $exclude_from_records = \App\Models\Member::where('exclude_from_records', true)->pluck('id')->toArray();
+
+        $datas = \App\Models\Record::with('member', 'supplier', 'payment_method')
+            ->select('records.*', 'records_rows.*')
+            ->join('records_rows', 'records.id', '=', 'records_rows.record_id')
+            ->whereBetween('date', [$fromDate, $toDate])
+            ->where(function ($query) {
+                $query->where('type', 'OUT')
+                    ->orWhere(function ($query) {
+                        $query->where('records.corrispettivo_fiscale', true)
+                            ->orWhere('records.commercial', false);
+                    });
+            })
+            ->where(function ($query) use ($exclude_from_records) {
+                $query->where('type', 'OUT')
+                    ->orWhere(function ($subquery) use ($exclude_from_records) {
+                        $subquery->whereNotIn('member_id', $exclude_from_records);
+                    });
+            });
+
+        if ($this->filterCausals != null && sizeof($this->filterCausals) > 0) {
+            $causals = array();
+            foreach ($this->filterCausals as $z) {
+                $causals[] = $z;
+                $childs = \App\Models\Causal::where('parent_id', $z)->get();
+                foreach ($childs as $c) {
+                    $causals[] = $c->id;
+                    $childsX = \App\Models\Causal::where('parent_id', $c->id)->get();
+                    foreach ($childsX as $cX) {
+                        $causals[] = $cX->id;
+                    }
+                }
+            }
+            $datas->whereIn('causal_id', $causals);
+        }
+        if ($this->filterMember != null && $this->filterMember > 0) {
+            $datas->where('member_id', $this->filterMember);
+        }
+        $datas = $datas->orderBy('date', 'ASC')
+            ->orderBy('records.created_at', 'ASC')
+            ->orderBy('records_rows.id', 'ASC')
+            ->get();
+
+        foreach ($datas as $data) {
+            $causalCheck = \App\Models\Causal::findOrFail($data->causal_id);
+            $paymentCheck = $data->payment_method->money;
+
+            if (!$paymentCheck && ($causalCheck->no_first == null || !$causalCheck->no_first)) {
+                if (!$data->deleted) {
+                    $amount = $data->amount;
+                    $amount += getVatValue($amount, $data->vat_id);
+                } else {
+                    $amount = $data->amount;
+                }
+
+                if (!isset($exportTotals[$data->payment_method->name])) {
+                    $exportTotals[$data->payment_method->name]["IN"] = 0;
+                    $exportTotals[$data->payment_method->name]["OUT"] = 0;
+                }
+
+                if (!$data->deleted)
+                    $exportTotals[$data->payment_method->name][$data->type] += $amount;
+            }
+        }
+
+        return $exportTotals;
+    }
     public function resetFilters()
     {
         $this->selectedPeriod = 'OGGI';
@@ -256,10 +461,8 @@ class Record extends Component
                     $amount = $data->amount;
                 }
 
-                // Determine the type (commercial or non-commercial)
                 $typeLabel = $data->commercial ? 'Commerciale' : 'Non Commerciale';
 
-                // Get nominativo
                 $nominativo = '';
                 if ($data->type == "IN") {
                     if ($data->member) {
@@ -271,10 +474,8 @@ class Record extends Component
                     }
                 }
 
-                // Create grouping key: date + type + payment_method + IN/OUT + nominativo
                 $groupKey = $data->date . '|' . $typeLabel . '|' . $data->payment_method->name . '|' . $data->type . '|' . $nominativo;
 
-                // Initialize group if not exists
                 if (!isset($groupedData[$groupKey])) {
                     $groupedData[$groupKey] = [
                         'date' => $data->date,
@@ -292,13 +493,10 @@ class Record extends Component
                 }
 
                 $groupedData[$groupKey]['amount'] += $amount;
-
                 $causalsCount[$groupKey][$causalCheck->getTree()] = true;
-
                 if (!empty($data->note)) {
                     $groupedData[$groupKey]['notes'][] = $data->note;
                 }
-
                 if ($data->deleted) {
                     $groupedData[$groupKey]['deleted'] = true;
                 }
@@ -387,7 +585,36 @@ class Record extends Component
         return $data;
     }
 
-    public function export()
+    public function openExportModal()
+    {
+        $this->exportFromDate = $this->appliedFromDate;
+        $this->exportToDate = $this->appliedToDate;
+
+        $this->emit('show-export-modal');
+    }
+
+    public function exportWithDateRange()
+    {
+        $this->isExporting = true;
+
+        $exportRecords = $this->generateExportData($this->exportFromDate, $this->exportToDate);
+        $exportTotals = $this->generateExportTotals($this->exportFromDate, $this->exportToDate);
+
+        $result = $this->exportWithData($exportRecords, $exportTotals);
+
+        $this->isExporting = false;
+
+        $this->emit('hide-export-modal');
+    }
+    function export()
+    {
+        $exportRecords = $this->generateExportData($this->appliedFromDate, $this->appliedToDate);
+        $exportTotals = $this->generateExportTotals($this->appliedFromDate, $this->appliedToDate);
+
+        return $this->exportWithData($exportRecords, $exportTotals);
+    }
+
+    private function exportWithData($exportRecords, $exportTotals)
     {
         ini_set('memory_limit', '512M');
         gc_enable();
@@ -398,8 +625,8 @@ class Record extends Component
         $activeWorksheet = $spreadsheet->getActiveSheet();
 
         $activeWorksheet->setCellValue('A1', "Data");
-        $activeWorksheet->setCellValue('B1', "Tipo");
-        $activeWorksheet->setCellValue('C1', "Causale");
+        $activeWorksheet->setCellValue('B1', "Causale");
+        $activeWorksheet->setCellValue('C1', "Dettaglio");
         $activeWorksheet->setCellValue('D1', "Nominativo");
         $activeWorksheet->setCellValue('E1', "Stato");
 
@@ -459,13 +686,12 @@ class Record extends Component
         $batchSize = 1000;
         $recordsProcessed = 0;
 
-        $totalRecords = count($this->records);
-        $recordsArray = array_chunk($this->records, $batchSize, true);
+        $totalRecords = count($exportRecords);
+        $recordsArray = array_chunk($exportRecords, $batchSize, true);
 
         foreach ($recordsArray as $recordsBatch) {
             foreach ($recordsBatch as $causal => $record) {
                 $check = $causal;
-
                 $parts = explode("§", $check);
                 $d = $parts[0] ?? '';
                 $c = $parts[1] ?? '';
@@ -536,21 +762,21 @@ class Record extends Component
                 break;
             }
 
-            if (isset($this->totals[$p->name])) {
+            if (isset($exportTotals[$p->name])) {
                 if ($p->type == 'ALL') {
-                    $activeWorksheet->setCellValue($letters[$idx] . $count, formatPrice($this->totals[$p->name]["IN"] ?? 0));
+                    $activeWorksheet->setCellValue($letters[$idx] . $count, formatPrice($exportTotals[$p->name]["IN"] ?? 0));
                     $idx++;
-                    $activeWorksheet->setCellValue($letters[$idx] . $count, formatPrice($this->totals[$p->name]["OUT"] ?? 0));
+                    $activeWorksheet->setCellValue($letters[$idx] . $count, formatPrice($exportTotals[$p->name]["OUT"] ?? 0));
                     $idx++;
                 } elseif ($p->type == 'IN') {
-                    $activeWorksheet->setCellValue($letters[$idx] . $count, formatPrice($this->totals[$p->name]["IN"] ?? 0));
+                    $activeWorksheet->setCellValue($letters[$idx] . $count, formatPrice($exportTotals[$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"] ?? 0));
+                    $activeWorksheet->setCellValue($letters[$idx] . $count, formatPrice($exportTotals[$p->name]["OUT"] ?? 0));
                     $idx++;
                 }
             } else {

+ 75 - 2
resources/views/livewire/records.blade.php

@@ -57,7 +57,7 @@
                 ESPORTA
             </button>
             <ul class="dropdown-menu" aria-labelledby="exportDropdown">
-                <li><a class="dropdown-item" href="#" wire:click="export()">Excel</a></li>
+                <li><a class="dropdown-item" href="#" wire:click="openExportModal">Excel</a></li>
                 <li><a class="dropdown-item" href="#" id="print">Stampa</a></li>
             </ul>
             </div>
@@ -79,8 +79,8 @@
             <thead>
                 <tr>
                     <th scope="col">Data</th>
-                    <th scope="col" style="border-left:3px solid white;">Tipo</th>
                     <th scope="col" style="border-left:3px solid white;">Causale</th>
+                    <th scope="col" style="border-left:3px solid white;">Dettaglio Causale</th>
                     <th scope="col" style="border-left:3px solid white;">Stato</th>
                     <th scope="col" style="border-left:3px solid white;">Nominativo</th>
                     @foreach($payments as $p)
@@ -245,6 +245,48 @@
             </div>
         </div>
     </div>
+
+    <!-- Modal for Export Date Range -->
+    <div class="modal fade" id="exportModal" tabindex="-1" aria-labelledby="exportModalLabel" aria-hidden="true">
+        <div class="modal-dialog">
+            <div class="modal-content">
+                <div class="modal-header" style="background-color: #0C6197!important;">
+                    <h5 class="modal-title" id="exportModalLabel">Seleziona Periodo per Export</h5>
+                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="CHIUDI"></button>
+                </div>
+                <div class="modal-body">
+                    <div class="row g-3">
+                        <div class="col-md-6">
+                            <label for="exportFromDate" class="form-label">Data Inizio</label>
+                            <input type="date" class="form-control" id="exportFromDate" wire:model.defer="exportFromDate">
+                        </div>
+                        <div class="col-md-6">
+                            <label for="exportToDate" class="form-label">Data Fine</label>
+                            <input type="date" class="form-control" id="exportToDate" wire:model.defer="exportToDate">
+                        </div>
+                    </div>
+                    <div class="row mt-3">
+                        <div class="col-12">
+                            <small class="text-muted">
+                                <i class="fas fa-info-circle me-1"></i>
+                                L'export includerà tutti i record nel periodo selezionato con i filtri attualmente applicati.
+                            </small>
+                        </div>
+                    </div>
+                </div>
+                <div class="modal-footer" style="background-color: #FFF!important;">
+                    <button type="button" class="btn--ui lightGrey me-2" data-bs-dismiss="modal">ANNULLA</button>
+                    <button type="button" class="btn--ui primary" wire:click="exportWithDateRange" @if($isExporting) disabled @endif>
+                        @if($isExporting)
+                            <i class="fas fa-spinner fa-spin me-1"></i> ESPORTANDO...
+                        @else
+                            <i class="fas fa-download me-1"></i> ESPORTA
+                        @endif
+                    </button>
+                </div>
+            </div>
+        </div>
+    </div>
 </div>
 
 @push('scripts')
@@ -434,9 +476,31 @@
         }
 
         .form-select {
+            height: 38px !important;
+        }
+
+        .form-control {
             height: 43px !important;
         }
 
+        #exportModal .modal-body {
+            padding: 1.5rem;
+        }
+
+        #exportModal .form-label {
+            font-weight: 600;
+            color: #10172A;
+            margin-bottom: 0.5rem;
+        }
+
+        #exportModal .text-muted {
+            font-size: 0.875rem;
+        }
+
+        .btn--ui[disabled] .fa-spinner {
+            margin-right: 0.5rem;
+        }
+
         body.modal-open {
             overflow: hidden;
         }
@@ -594,6 +658,7 @@
 
         $(document).ready(function() {
             load();
+
             document.querySelector("#print").addEventListener("click", function(){
                 printData();
             });
@@ -662,5 +727,13 @@
             $('.filterCausals').val('').trigger('change');
             load();
         });
+
+        Livewire.on('show-export-modal', () => {
+            $('#exportModal').modal('show');
+        });
+
+        Livewire.on('hide-export-modal', () => {
+            $('#exportModal').modal('hide');
+        });
     </script>
 @endpush