Ver código fonte

Merge remote-tracking branch 'origin/iao_team' into iao_team_ferrari

ferrari 2 meses atrás
pai
commit
af54f18223

+ 27 - 19
app/Console/Commands/SendSms.php

@@ -31,31 +31,39 @@ class SendSms extends Command
         $expire_date = date("Y-m-d", strtotime("+1 month"));
         $expire_date_it = date("d/m/Y", strtotime("+1 month"));
         $certificates = \App\Models\MemberCertificate::where('expire_date', $expire_date)->get();
-        foreach ($certificates as $certificate) {
-            $phone = $certificate->member->phone;
-            $message = 'Ciao ' . $certificate->member->first_name . ', ci risulta che il tuo certificato medico scade il ' . $expire_date_it . '. Per continuare ad allenarti senza problemi, ricordati di rinnovarlo in tempo. Ti aspettiamo in campo! Centro Sportivo La Madonnella';
-            $params = array(
-                'to'            => '+39' . $phone,
-                'from'          => env('SMS_FROM', 'Test'),
-                'message'       => $message,
-                'format'        => 'json',
-            );
-            sms_send($params);
+        foreach ($certificates as $certificate) {            
+            $new = \App\Models\MemberCertificate::where('expire_date', '>', $expire_date)->count();
+            if ($new == 0)
+            {
+                $phone = $certificate->member->phone;
+                $message = 'Ciao ' . $certificate->member->first_name . ', ci risulta che il tuo certificato medico scade il ' . $expire_date_it . '. Per continuare ad allenarti senza problemi, ricordati di rinnovarlo in tempo. Ti aspettiamo in campo! Centro Sportivo La Madonnella';
+                $params = array(
+                    'to'            => '+39' . $phone,
+                    'from'          => env('SMS_FROM', 'Test'),
+                    'message'       => $message,
+                    'format'        => 'json',
+                );
+                sms_send($params);
+            }
         }
 
         $expire_date = date("Y-m-d", strtotime("+15 days"));
         $expire_date_it = date("d/m/Y", strtotime("+15 days"));
         $certificates = \App\Models\MemberCertificate::where('expire_date', $expire_date)->get();
         foreach ($certificates as $certificate) {
-            $phone = $certificate->member->phone;
-            $message = 'Ciao ' . $certificate->member->first_name . ', ci risulta che il tuo certificato medico scade il ' . $expire_date_it . '. Per continuare ad allenarti senza problemi, ricordati di rinnovarlo in tempo. Ti aspettiamo in campo! Centro Sportivo La Madonnella';
-            $params = array(
-                'to'            => '+39' . $phone,
-                'from'          => env('SMS_FROM', 'Test'),
-                'message'       => $message,
-                'format'        => 'json',
-            );
-            sms_send($params);
+            $new = \App\Models\MemberCertificate::where('expire_date', '>', $expire_date)->count();
+            if ($new == 0)
+            {
+                $phone = $certificate->member->phone;
+                $message = 'Ciao ' . $certificate->member->first_name . ', ci risulta che il tuo certificato medico scade il ' . $expire_date_it . '. Per continuare ad allenarti senza problemi, ricordati di rinnovarlo in tempo. Ti aspettiamo in campo! Centro Sportivo La Madonnella';
+                $params = array(
+                    'to'            => '+39' . $phone,
+                    'from'          => env('SMS_FROM', 'Test'),
+                    'message'       => $message,
+                    'format'        => 'json',
+                );
+                sms_send($params);
+            }
         }
 
         return Command::SUCCESS;

+ 10 - 5
app/Http/Livewire/Bank.php

@@ -6,7 +6,7 @@ use Livewire\Component;
 
 class Bank extends Component
 {
-    public $records, $name, $enabled, $dataId, $update = false, $add = false;
+    public $records, $name, $visibility, $enabled, $dataId, $update = false, $add = false;
 
     protected $rules = [
         'name' => 'required'
@@ -40,6 +40,7 @@ class Bank extends Component
 
     public function resetFields(){
         $this->name = '';
+        $this->visibility = 'IN';
         $this->enabled = true;
         $this->emit('load-data-table');
     }
@@ -47,7 +48,7 @@ class Bank extends Component
     public function render()
     {
         //$this->records = \App\Models\Bank::select('id', 'name', 'enabled')->orderBy($this->sortField, $this->sortAsc ? 'asc' : 'desc')->get();
-        $this->records = \App\Models\Bank::select('id', 'name', 'enabled')->get();
+        $this->records = \App\Models\Bank::select('id', 'name', 'visibility', 'enabled')->get();
         return view('livewire.bank');
     }
 
@@ -64,9 +65,10 @@ class Bank extends Component
         try {
             \App\Models\Bank::create([
                 'name' => $this->name,
+                'visibility' => $this->visibility,
                 'enabled' => $this->enabled
             ]);
-            session()->flash('success','Città creata');
+            session()->flash('success','Banca creata');
             $this->resetFields();
             $this->add = false;
         } catch (\Exception $ex) {
@@ -75,12 +77,14 @@ class Bank extends Component
     }
 
     public function edit($id){
+        $this->resetFields();
         try {
             $bank = \App\Models\Bank::findOrFail($id);
             if( !$bank) {
-                session()->flash('error','Città non trovata');
+                session()->flash('error','Banca non trovata');
             } else {
                 $this->name = $bank->name;
+                $this->visibility = $bank->visibility;
                 $this->enabled = $bank->enabled;
                 $this->dataId = $bank->id;
                 $this->update = true;
@@ -97,9 +101,10 @@ class Bank extends Component
         try {
             \App\Models\Bank::whereId($this->dataId)->update([
                 'name' => $this->name,
+                'visibility' => $this->visibility,
                 'enabled' => $this->enabled
             ]);
-            session()->flash('success','Città aggiornata');
+            session()->flash('success','Banca aggiornata');
             $this->resetFields();
             $this->update = false;
         } catch (\Exception $ex) {

+ 312 - 24
app/Http/Livewire/Record.php

@@ -49,6 +49,8 @@ class Record extends Component
         'exportEmailAddress' => 'required_if:sendViaEmail,true|email',
         'exportEmailSubject' => 'required_if:sendViaEmail,true|string|max:255',
     ];
+    public $total_in = 0;
+    public $total_out = 0;
 
     protected $messages = [
         'exportEmailAddress.required_if' => 'L\'indirizzo email è obbligatorio quando si sceglie di inviare via email.',
@@ -563,19 +565,14 @@ class Record extends Component
         return $ret;
     }
 
-
-
-    public function render()
+    public function loadData($from, $to)
     {
-        $month = 0;
-        $year = 0;
-
-        $this->records = array();
-        $this->totals = array();
-        $this->causalAmounts = array();
 
         $exclude_from_records = \App\Models\Member::where('exclude_from_records', true)->pluck('id')->toArray();
 
+        $f = $from != '' ? $from : $this->appliedFromDate;
+        $t = $to != '' ? $to : $this->appliedToDate;
+
         $datas = \App\Models\Record::with('member', 'supplier', 'payment_method')
             ->select(
                 'records.*',
@@ -586,22 +583,28 @@ class Record extends Component
                 'records_rows.note',
                 'records_rows.when',
                 'records_rows.vat_id',
+                //'causals.name as causal_name',
+                'd.name as destination',
+                'o.name as origin',
             )
             ->join('records_rows', 'records.id', '=', 'records_rows.record_id')
+            ->join('causals', 'records_rows.causal_id', '=', 'causals.id')
+            ->leftJoin('banks as d', 'records.destination_id', '=', 'd.id')
+            ->leftJoin('banks as o', 'records.origin_id', '=', 'o.id')
             //->where('records.deleted', false)
-            ->where(function ($query) {
+            /*->where(function ($query) {
                 $query->where('records.deleted', false)->orWhereNull('records.deleted');
-            })
-            ->whereBetween('date', [$this->appliedFromDate . " 00:00:00", $this->appliedToDate . " 23:59:59"])
+            })*/
+            ->whereBetween('date', [$f . " 00:00:00", $t . " 23:59:59"])
             ->where(function ($query) {
-                $query->where('type', 'OUT')
+                $query->where('records.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')
+                $query->where('records.type', 'OUT')
                     ->orWhere(function ($subquery) use ($exclude_from_records) {
                         $subquery->whereNotIn('member_id', $exclude_from_records);
                     });
@@ -630,12 +633,49 @@ class Record extends Component
             ->orderBy('records_rows.id', 'ASC')
             ->get();
 
-        $groupedData = [];
-        $causalsCount = [];
-        $causalsAmounts = [];
-        $nominativi = [];
+        $ret = array();
+
+        $this->total_in = 0;
+        $this->total_out = 0;
+
+        foreach($datas as $data)
+        {
+            $causal = \App\Models\Causal::findOrFail($data->causal_id);
+            $paymentCheck = $data->payment_method->money;
+            if (!$paymentCheck && ($causal->no_first == null || !$causal->no_first)) 
+            {
+                $data->causal_name = $causal->getTree();
+                $ret[] = $data;
+
+                if ($data->type == 'IN')
+                    $this->total_in += $data->amount;
+                if ($data->type == 'OUT')
+                    $this->total_out += $data->amount;
+
+            }
+        }
+
+        if ($this->total_in > 0 || $this->total_out > 0)        
+        {
+            $ret[] = (object) array("date" => "", "total_in" => $this->total_in, "total_out" => $this->total_out);
+        }
 
-        $values = [];
+        return $ret;
+
+    }
+
+    public function render()
+    {
+        $month = 0;
+        $year = 0;
+
+        $this->records = array();
+        $this->totals = array();
+        $this->causalAmounts = array();
+
+        $this->records = $this->loadData('', '');
+
+        /*
 
         foreach ($datas as $idx => $data) {
 
@@ -739,6 +779,8 @@ class Record extends Component
                 $this->totals[$group['payment_method']][$group['transaction_type']] += $group['amount'];
         }
 
+        */
+
         return view('livewire.records');
     }
 
@@ -857,7 +899,7 @@ class Record extends Component
 
             if ($this->sendViaEmail) {
                 Log::info('Export: Dispatching to background job');
-                $this->dispatchExportJob($exportRecords, $exportTotals);
+                //$this->dispatchExportJob($exportRecords, $exportTotals);
                 Log::info('Export: Job dispatched successfully');
             } else {
                 Log::info('Export: Starting direct download export');
@@ -906,6 +948,85 @@ class Record extends Component
             Log::info('=== EXPORT END ===');
         }
     }
+
+    public function exportData()
+    {
+
+        $this->isExporting = true;
+        $this->emit('$refresh');
+        usleep(100000);
+
+        if ($this->sendViaEmail) {
+            Log::info('Export: Validating email fields');
+            $this->validate([
+                'exportEmailAddress' => 'required|email',
+                'exportEmailSubject' => 'required|string|max:255',
+            ]);
+            Log::info('Export: Email validation passed');
+        }
+
+        $this->isExporting = true;
+
+        try {
+            Log::info('Export: Starting COMBINED data generation phase (NO SEPARATE CALLS)');
+            $startTime = microtime(true);
+
+            $records = $this->loadData($this->exportFromDate, $this->exportToDate);            
+            
+            $dataGenTime = microtime(true) - $startTime;
+            
+
+
+            if ($this->sendViaEmail) {
+                Log::info('Export: Dispatching to background job');
+
+                // Invio mail
+
+                $this->dispatchExportJob($records);
+                Log::info('Export: Job dispatched successfully');
+            } else {
+                Log::info('Export: Starting direct download export');
+                $exportStartTime = microtime(true);
+
+                // Creo excel e scarico
+                $result = $this->exportExcel($records);
+
+                $exportTime = microtime(true) - $exportStartTime;
+
+                return $result;
+            }
+        } catch (\Illuminate\Validation\ValidationException $e) {
+            Log::error('Export: Validation error', [
+                'error' => $e->getMessage(),
+                'errors' => $e->errors()
+            ]);
+            $this->isExporting = false;
+            throw $e;
+        } catch (\Exception $e) {
+            Log::error('Export: General error', [
+                'error' => $e->getMessage(),
+                'trace' => $e->getTraceAsString(),
+                'memory_usage' => memory_get_usage(true),
+                'memory_peak' => memory_get_peak_usage(true),
+                'execution_time' => microtime(true) - ($startTime ?? 0)
+            ]);
+
+            $this->isExporting = false;
+
+            if ($this->sendViaEmail) {
+                $this->emit('export-email-error', 'Errore durante l\'invio dell\'email: ' . $e->getMessage());
+            } else {
+                session()->flash('error', 'Errore durante l\'export: ' . $e->getMessage());
+            }
+        } finally {
+            Log::info('Export: Cleanup phase');
+            $this->isExporting = false;
+            $this->emit('export-complete');
+            $this->emit('hide-export-modal');
+            Log::info('=== EXPORT END ===');
+        }
+    }
+
     private function getEstimatedRecordCount($fromDate, $toDate)
     {
         $exclude_from_records = \App\Models\Member::where('exclude_from_records', true)->pluck('id')->toArray();
@@ -1007,7 +1128,8 @@ class Record extends Component
     /**
      * Dispatch export job to queue
      */
-    private function dispatchExportJob($exportRecords, $exportTotals)
+    //private function dispatchExportJob($exportRecords, $exportTotals)
+    private function dispatchExportJob($records)
     {
         try {
             // Prepare filter descriptions for the job
@@ -1026,8 +1148,9 @@ class Record extends Component
 
             // Dispatch job to background queue
             ExportPrimaNota::dispatch(
-                $exportRecords,
-                $exportTotals,
+                /*$exportRecords,
+                $exportTotals,*/
+                $records,
                 $this->exportEmailAddress,
                 $this->exportEmailSubject,
                 [
@@ -1046,7 +1169,7 @@ class Record extends Component
                 'user_id' => auth()->id(),
                 'email' => $this->exportEmailAddress,
                 'date_range' => [$this->exportFromDate, $this->exportToDate],
-                'total_records' => count($exportRecords)
+                'total_records' => count($this->records)
             ]);
         } catch (\Exception $e) {
             Log::error('Failed to dispatch export job', [
@@ -1522,4 +1645,169 @@ class Record extends Component
     {
         $this->showMonthPicker = !$this->showMonthPicker;
     }
+
+    private function exportExcel($records)
+    {
+        
+        $startTime = microtime(true);
+
+        $spreadsheet = new Spreadsheet();
+        $activeWorksheet = $spreadsheet->getActiveSheet();
+
+        $activeWorksheet->setCellValue('A1', "Data");
+        $activeWorksheet->setCellValue('B1', "Tipologia");
+        $activeWorksheet->setCellValue('C1', "Causale");
+        $activeWorksheet->setCellValue('D1', "Nominativo");
+        $activeWorksheet->setCellValue('E1', "Stato");
+        $activeWorksheet->setCellValue('F1', "Entrata");
+        $activeWorksheet->setCellValue('G1', "Uscita");
+        $activeWorksheet->setCellValue('H1', "Origine");
+        $activeWorksheet->setCellValue('I1', "Destinazione");
+        $activeWorksheet->setCellValue('J1', "Metodo di pagamento");
+
+        $activeWorksheet->getStyle('A1:J1')->getFill()
+            ->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)
+            ->getStartColor()->setARGB('FF0C6197');
+
+        $activeWorksheet->getStyle('A1:J1')->getFont()->getColor()->setARGB('FFFFFFFF');
+
+        $idx = 2;
+        foreach($records as $record)
+        {
+            if ($record->date != '')
+            {
+                $activeWorksheet->setCellValue('A' . $idx, date("d/m/Y", strtotime($record->date)));
+                $activeWorksheet->setCellValue('B' . $idx, $record->commercial ? 'Commerciale' : 'Non commerciale');
+                $activeWorksheet->setCellValue('C' . $idx, $record->causal_name);
+                $activeWorksheet->setCellValue('D' . $idx, $record->type == 'IN' ? ($record->member->first_name . " " . $record->member->last_name) : @$record->supplier->name);
+                $activeWorksheet->setCellValue('E' . $idx, $record->deleted ? 'Annullata' : '');
+                $activeWorksheet->setCellValue('F' . $idx, $record->type == 'IN' ? formatPrice($record->amount) : '');
+                $activeWorksheet->setCellValue('G' . $idx, $record->type == 'OUT' ? formatPrice($record->amount) : '');
+                $activeWorksheet->setCellValue('H' . $idx, $record->type == 'OUT' ? $record->origin : '');
+                $activeWorksheet->setCellValue('I' . $idx, $record->type == 'IN' ? $record->destination : '');
+                $activeWorksheet->setCellValue('J' . $idx, $record->payment_method->name);
+            }
+            else
+            {
+                $activeWorksheet->setCellValue('A' . $idx, "Totali");
+                $activeWorksheet->setCellValue('B' . $idx, "");
+                $activeWorksheet->setCellValue('C' . $idx, "");
+                $activeWorksheet->setCellValue('D' . $idx, "");
+                $activeWorksheet->setCellValue('E' . $idx, "");
+                $activeWorksheet->setCellValue('F' . $idx, formatPrice($record->total_in));
+                $activeWorksheet->setCellValue('G' . $idx, formatPrice($record->total_out));
+                $activeWorksheet->setCellValue('H' . $idx, "");
+                $activeWorksheet->setCellValue('I' . $idx, "");
+                $activeWorksheet->setCellValue('J' . $idx, "");
+            }
+            $idx++;
+        }
+
+        $activeWorksheet->getColumnDimension('A')->setWidth(10);
+        $activeWorksheet->getColumnDimension('B')->setWidth(30);
+        $activeWorksheet->getColumnDimension('C')->setWidth(30);
+        $activeWorksheet->getColumnDimension('D')->setWidth(30);
+        $activeWorksheet->getColumnDimension('E')->setWidth(10);
+        $activeWorksheet->getColumnDimension('F')->setWidth(10);
+        $activeWorksheet->getColumnDimension('G')->setWidth(10);
+        $activeWorksheet->getColumnDimension('H')->setWidth(20);
+        $activeWorksheet->getColumnDimension('I')->setWidth(20);
+        $activeWorksheet->getColumnDimension('J')->setWidth(30);
+
+        $activeWorksheet->getStyle('A' . ($idx - 1) . ':J' . ($idx - 1))->getFont()->setBold(true);
+
+        $filename = 'prima_nota_' . date("YmdHis") . '.xlsx';
+        Log::info('exportWithData: Preparing to save file', [
+            'filename' => $filename,
+            //'total_processing_time' => microtime(true) - $startTime,
+            'memory_before_save' => memory_get_usage(true)
+        ]);
+
+        try {
+            $currentClient = session('currentClient', 'default');
+            $tempPath = sys_get_temp_dir() . '/' . $filename;
+
+            $writer = new Xlsx($spreadsheet);
+
+            $writer->save($tempPath);
+            
+            unset($spreadsheet, $activeWorksheet, $writer);
+            gc_collect_cycles();
+
+            Log::info('exportWithData: Uploading to S3');
+            $disk = Storage::disk('s3');
+            $s3Path = $currentClient . '/prima_nota/' . $filename;
+
+            $primaNotaFolderPath = $currentClient . '/prima_nota/.gitkeep';
+            if (!$disk->exists($primaNotaFolderPath)) {
+                $disk->put($primaNotaFolderPath, '');
+            }
+
+            $uploadStart = microtime(true);
+            $fileContent = file_get_contents($tempPath);
+            $uploaded = $disk->put($s3Path, $fileContent, 'private');
+            $uploadTime = microtime(true) - $uploadStart;
+
+            if (!$uploaded) {
+                throw new \Exception('Failed to upload file to Wasabi S3');
+            }
+
+            Log::info("Export completed successfully", [
+                'client' => $currentClient,
+                'path' => $s3Path,
+                'file_size' => filesize($tempPath),
+                'records_processed' => $recordsProcessed,
+                'upload_time' => $uploadTime,
+                'total_time' => microtime(true) - $startTime,
+                'memory_peak' => memory_get_peak_usage(true)
+            ]);
+
+            if (file_exists($tempPath)) {
+                unlink($tempPath);
+            }
+
+            $downloadUrl = $disk->temporaryUrl($s3Path, now()->addHour());
+            return redirect($downloadUrl);
+        } catch (\Exception $e) {
+            Log::error('Export S3 error - falling back to local', [
+                'error' => $e->getMessage(),
+                'trace' => $e->getTraceAsString(),
+                'client' => session('currentClient', 'unknown'),
+                'filename' => $filename,
+                'records_processed' => $recordsProcessed ?? 0,
+                'time_elapsed' => microtime(true) - $startTime
+            ]);
+
+            // Fallback logic remains the same...
+            $currentClient = session('currentClient', 'default');
+            $clientFolder = storage_path('app/prima_nota/' . $currentClient);
+
+            if (!is_dir($clientFolder)) {
+                mkdir($clientFolder, 0755, true);
+                Log::info("Created local client prima_nota folder: {$clientFolder}");
+            }
+
+            $localPath = $clientFolder . '/' . $filename;
+
+            if (isset($tempPath) && file_exists($tempPath)) {
+                rename($tempPath, $localPath);
+            } else {
+                $writer = new Xlsx($spreadsheet);
+                $writer->save($localPath);
+                unset($spreadsheet, $activeWorksheet, $writer);
+            }
+
+            gc_collect_cycles();
+
+            Log::warning("Export saved locally due to S3 error", [
+                'client' => $currentClient,
+                'local_path' => $localPath,
+                'error' => $e->getMessage()
+            ]);
+
+            session()->flash('warning', 'File salvato localmente a causa di un errore del cloud storage.');
+            return response()->download($localPath)->deleteFileAfterSend();
+        }
+    }
+
 }

+ 7 - 0
app/Http/Livewire/RecordIN.php

@@ -52,6 +52,7 @@ class RecordIN extends Component
     public $records, $dataId, $member_id, $supplier_id,
     $causal_id,
     $payment_method_id,
+    $destination_id,
     $date,
     $month,
     $year,
@@ -97,6 +98,7 @@ class RecordIN extends Component
 
     public $causals = array();
     public $payments = array();
+    public $banks = array();
     public $members = array();
     public $vats = array();
 
@@ -246,6 +248,7 @@ class RecordIN extends Component
         $this->member_id = null;
         $this->supplier_id = null;
         $this->payment_method_id = null;
+        $this->destination_id = null;
         $this->commercial = 0;
         $this->corrispettivo_fiscale = false;
         $this->date = date("Y-m-d");
@@ -361,6 +364,7 @@ class RecordIN extends Component
 
         $this->refreshMembers();
         $this->payments = \App\Models\PaymentMethod::select('id', 'name')->where('enabled', true)->whereIn('type', array('ALL', 'IN'))->orderBy('name')->get();
+        $this->banks = \App\Models\Bank::select('id', 'name')->where('enabled', true)->whereIn('visibility', array('ALL', 'IN'))->orderBy('name')->get();
         $this->vats = \App\Models\Vat::select('id', 'name', 'value')->orderBy('value')->get();
 
         if ($this->first)
@@ -597,6 +601,7 @@ class RecordIN extends Component
                 'member_id' => $this->member_id,
                 'supplier_id' => $this->supplier_id,
                 'payment_method_id' => $this->payment_method_id,
+                'destination_id' => $this->destination_id,
                 'commercial' => $this->commercial,
                 'corrispettivo_fiscale' => $this->corrispettivo_fiscale,
                 'date' => $this->date,
@@ -723,6 +728,7 @@ class RecordIN extends Component
                 $this->member_id = $record->member_id;
                 $this->supplier_id = $record->supplier_id;
                 $this->payment_method_id = $record->payment_method_id;
+                $this->destination_id = $record->destination_id;
                 $this->amount = $record->amount;
                 $this->commercial = $record->commercial;
                 $this->corrispettivo_fiscale = $record->corrispettivo_fiscale;
@@ -774,6 +780,7 @@ class RecordIN extends Component
                 'member_id' => $this->member_id,
                 'supplier_id' => $this->supplier_id,
                 'payment_method_id' => $this->payment_method_id,
+                'destination_id' => $this->destination_id,
                 'commercial' => $this->commercial,
                 'corrispettivo_fiscale' => $this->corrispettivo_fiscale,
                 'date' => date("Y-m-d", strtotime($this->date)),

+ 8 - 0
app/Http/Livewire/RecordOUT.php

@@ -37,6 +37,7 @@ class RecordOUT extends Component
     public $records, $dataId, $member_id, $supplier_id,
     $causal_id,
     $payment_method_id,
+    $origin_id,
     $date,
     $month,
     $year,
@@ -60,6 +61,7 @@ class RecordOUT extends Component
 
     public $causals = array();
     public $payments = array();
+    public $banks = array();
     public $suppliers = array();
 
     public $rows = array();
@@ -105,6 +107,7 @@ class RecordOUT extends Component
         $this->supplier_id = null;
         //$this->causal_id = null;
         $this->payment_method_id = null;
+        $this->origin_id = null;
         $this->date = date("Y-m-d");
         //$this->month = date("n");
         //$this->year = date("Y");
@@ -157,6 +160,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->banks = \App\Models\Bank::select('id', 'name')->where('enabled', true)->whereIn('visibility', array('ALL', 'OUT'))->orderBy('name')->get();
     }
 
     public function getCausal($causal)
@@ -320,6 +324,7 @@ class RecordOUT extends Component
                 'supplier_id' => $this->supplier_id,
                 //'causal_id' => $this->causal_id,
                 'payment_method_id' => $this->payment_method_id,
+                'origin_id' => $this->origin_id,
                 'date' => $this->date,
                 //'month' => $this->month,
                 //'year' => $this->year,
@@ -360,6 +365,7 @@ class RecordOUT extends Component
     }
 
     public function edit($id){
+        $this->resetFields();
         if (!isset($_GET["from"]) && $this->fromPage == '')
             $this->fromPage = 'out';
         $this->emit('setEdit', true);
@@ -375,6 +381,7 @@ class RecordOUT extends Component
                 $this->supplier_id = $record->supplier_id;
                 //$this->causal_id = $record->causal_id;
                 $this->payment_method_id = $record->payment_method_id;
+                $this->origin_id = $record->origin_id;
                 $this->date = date("Y-m-d", strtotime($record->date));
                 //$this->month = $record->month;
                 //$this->year = $record->year;
@@ -409,6 +416,7 @@ class RecordOUT extends Component
                 'supplier_id' => $this->supplier_id,
                 //'causal_id' => $this->causal_id,
                 'payment_method_id' => $this->payment_method_id,
+                'origin_id' => $this->origin_id,
                 'date' => $this->date,
                 //'month' => $this->month,
                 //'year' => $this->year,

+ 1517 - 0
app/Http/Livewire/RecordOld.php

@@ -0,0 +1,1517 @@
+<?php
+
+namespace App\Http\Livewire;
+
+use Livewire\Component;
+use DateInterval;
+use DatePeriod;
+use DateTime;
+
+use PhpOffice\PhpSpreadsheet\Spreadsheet;
+use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
+use Illuminate\Support\Facades\Storage;
+use Illuminate\Support\Facades\Log;
+use Illuminate\Support\Facades\Mail;
+use App\Mail\ExportNotification;
+use App\Jobs\ExportPrimaNota;
+
+class RecordOld 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();
+    public $sendViaEmail = false;
+    public $exportEmailAddress = '';
+    public $exportEmailSubject = 'Prima Nota - Export';
+    private $causalAmounts = [];
+    public $selectedMonth;
+    public $showMonthPicker = false;
+    public $selectedDay;
+    public $showDayPicker = false;
+    public $selectedYear;
+    protected $rules = [
+        'exportEmailAddress' => 'required_if:sendViaEmail,true|email',
+        'exportEmailSubject' => 'required_if:sendViaEmail,true|string|max:255',
+    ];
+
+    protected $messages = [
+        'exportEmailAddress.required_if' => 'L\'indirizzo email è obbligatorio quando si sceglie di inviare via email.',
+        'exportEmailAddress.email' => 'Inserisci un indirizzo email valido.',
+        'exportEmailSubject.required_if' => 'L\'oggetto dell\'email è obbligatorio.',
+        'exportEmailSubject.max' => 'L\'oggetto dell\'email non può superare i 255 caratteri.',
+    ];
+
+    public function hydrate()
+    {
+        $this->emit('load-select');
+    }
+
+    public function mount()
+    {
+        $this->fromDate = date("Y-m-d");
+        $this->toDate = date("Y-m-d");
+
+        $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->exportEmailSubject = 'Prima Nota - Export del ' . date('d/m/Y');
+
+        $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();
+
+        $this->payments = \App\Models\PaymentMethod::select('id', 'name', 'type')->where('enabled', true)->where('money', false)->get();
+
+        $this->selectedMonth = date('Y-m');
+        $this->selectedDay = date('Y-m-d');
+        $this->selectedYear = date('Y');
+    }
+    private function generateExportDataAndTotals($fromDate, $toDate)
+    {
+        Log::info('generateExportDataAndTotals: Start (combined method)', [
+            'from_date' => $fromDate,
+            'to_date' => $toDate,
+            'memory_before' => memory_get_usage(true)
+        ]);
+
+        $exportRecords = array();
+        $exportTotals = array();
+
+        Log::info('generateExportDataAndTotals: Getting excluded members');
+        $exclude_from_records = \App\Models\Member::where('exclude_from_records', true)->pluck('id')->toArray();
+        Log::info('generateExportDataAndTotals: Excluded members retrieved', ['count' => count($exclude_from_records)]);
+
+        Log::info('generateExportDataAndTotals: Building main query');
+        $datas = \App\Models\Record::with('member', 'supplier', 'payment_method')
+            ->select(
+                'records.*',
+                'records_rows.id as row_id',
+                'records_rows.record_id',
+                'records_rows.causal_id',
+                'records_rows.amount',
+                'records_rows.note',
+                'records_rows.when',
+                'records_rows.vat_id',
+                'records_rows.created_at as row_created_at',
+                'records_rows.updated_at as row_updated_at'
+            )
+            ->join('records_rows', 'records.id', '=', 'records_rows.record_id')
+            //->where('records.deleted', false)
+            ->where(function ($query) {
+                $query->where('records.deleted', false)->orWhereNull('records.deleted');
+            })
+            ->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);
+                    });
+            });
+
+        Log::info('generateExportDataAndTotals: Applying causal filters');
+        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);
+            Log::info('generateExportDataAndTotals: Causal filters applied', ['causal_count' => count($causals)]);
+        }
+
+        if ($this->filterMember != null && $this->filterMember > 0) {
+            $datas->where('member_id', $this->filterMember);
+            Log::info('generateExportDataAndTotals: Member filter applied', ['member_id' => $this->filterMember]);
+        }
+
+        Log::info('generateExportDataAndTotals: Executing query');
+        $queryStart = microtime(true);
+
+        $datas = $datas->orderBy('date', 'ASC')
+            ->orderBy('records.created_at', 'ASC')
+            ->orderBy('records_rows.id', 'ASC')
+            ->get();
+
+        $queryTime = microtime(true) - $queryStart;
+        Log::info('generateExportDataAndTotals: Query executed', [
+            'record_count' => $datas->count(),
+            'query_time' => $queryTime,
+            'memory_after_query' => memory_get_usage(true)
+        ]);
+
+        $groupedData = [];
+        $causalsCount = [];
+        $processedCount = 0;
+
+        // Initialize totals array
+        foreach ($this->payments as $p) {
+            $exportTotals[$p->name] = ["IN" => 0, "OUT" => 0];
+        }
+
+        Log::info('generateExportDataAndTotals: Starting combined data processing loop');
+        $loopStart = microtime(true);
+
+        foreach ($datas as $idx => $data) {
+            if ($processedCount % 100 == 0) {
+                Log::info('generateExportDataAndTotals: Processing progress', [
+                    'processed' => $processedCount,
+                    'total' => $datas->count(),
+                    'memory_current' => memory_get_usage(true),
+                    'memory_peak' => memory_get_peak_usage(true)
+                ]);
+            }
+
+            try {
+                $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;
+                    }
+
+                    // CALCULATE TOTALS HERE (in the same loop)
+                    /*if (!$data->deleted) {
+                        $exportTotals[$data->payment_method->name][$data->type] += $amount;
+                    }*/
+
+                    $isCommercial = ($data->commercial == 1 || $data->commercial === '1' || $data->commercial === true);
+                    $typeLabel = $isCommercial ? '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;
+                    }
+                }
+
+                $processedCount++;
+            } catch (\Exception $e) {
+                Log::error('generateExportDataAndTotals: Error processing individual record', [
+                    'record_id' => $data->id ?? 'unknown',
+                    'error' => $e->getMessage(),
+                    'processed_so_far' => $processedCount
+                ]);
+                throw $e;
+            }
+        }
+
+        $loopTime = microtime(true) - $loopStart;
+        Log::info('generateExportDataAndTotals: Combined processing loop completed', [
+            'total_processed' => $processedCount,
+            'grouped_records' => count($groupedData),
+            'loop_time' => $loopTime,
+            'memory_after_loop' => memory_get_usage(true)
+        ]);
+
+        Log::info('generateExportDataAndTotals: Building final export records');
+        $finalStart = microtime(true);
+
+        $tot = 0;
+        $count = 0;
+
+        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 (!$group['deleted'])
+                $exportTotals[$group['payment_method']][$group['transaction_type']] += $group['amount'];
+
+        }
+
+        $finalTime = microtime(true) - $finalStart;
+        Log::info('generateExportDataAndTotals: Final processing completed', [
+            'final_export_records' => count($exportRecords),
+            'final_export_totals' => count($exportTotals),
+            'final_time' => $finalTime,
+            'total_time' => microtime(true) - $loopStart + $queryTime,
+            'memory_final' => memory_get_usage(true),
+            'memory_peak' => memory_get_peak_usage(true)
+        ]);
+
+        // Cleanup
+        unset($datas, $groupedData, $causalsCount);
+        gc_collect_cycles();
+
+        Log::info('generateExportDataAndTotals: Completed with cleanup', [
+            'memory_after_cleanup' => memory_get_usage(true)
+        ]);
+
+        return ['records' => $exportRecords, 'totals' => $exportTotals];
+    }
+
+    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.id as row_id',
+                'records_rows.record_id',
+                'records_rows.causal_id',
+                'records_rows.amount',
+                'records_rows.note',
+                'records_rows.when',
+                'records_rows.vat_id',
+            )
+            ->join('records_rows', 'records.id', '=', 'records_rows.record_id')
+            //->where('records.deleted', false)
+            ->where(function ($query) {
+                $query->where('records.deleted', false)->orWhereNull('records.deleted');
+            })
+            ->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';
+        $this->selectedMonth = date('Y-m');
+        $this->selectedDay = date('Y-m-d');
+        $this->selectedYear = date('Y');
+        $this->showMonthPicker = false;
+        $this->showDayPicker = false;
+        $this->filterCausals = [];
+        $this->filterMember = null;
+
+        $today = date("Y-m-d");
+        $this->fromDate = $today;
+        $this->toDate = $today;
+        $this->appliedFromDate = $today;
+        $this->appliedToDate = $today;
+
+        $this->emit('filters-reset');
+    }
+
+
+    public function applyFilters()
+    {
+        $this->isFiltering = true;
+
+        $this->setPeriodDates();
+
+        $this->appliedFromDate = $this->fromDate;
+        $this->appliedToDate = $this->toDate;
+
+        $this->render();
+
+        $this->isFiltering = false;
+
+        $this->emit('filters-applied');
+    }
+
+    private function setPeriodDates()
+    {
+        $today = now();
+
+        switch ($this->selectedPeriod) {
+            case 'OGGI':
+                $this->fromDate = $today->format('Y-m-d');
+                $this->toDate = $today->format('Y-m-d');
+                break;
+
+            case 'IERI':
+                $yesterday = $today->copy()->subDay();
+                $this->fromDate = $yesterday->format('Y-m-d');
+                $this->toDate = $yesterday->format('Y-m-d');
+                break;
+
+            case 'MESE CORRENTE':
+                $this->fromDate = $today->copy()->startOfMonth()->format('Y-m-d');
+                $this->toDate = $today->copy()->endOfMonth()->format('Y-m-d');
+                break;
+
+            case 'MESE PRECEDENTE':
+                $lastMonth = $today->copy()->subMonth();
+                $this->fromDate = $lastMonth->startOfMonth()->format('Y-m-d');
+                $this->toDate = $lastMonth->endOfMonth()->format('Y-m-d');
+                break;
+
+            case 'MESE_PERSONALIZZATO':
+                if (!empty($this->selectedMonth)) {
+                    $firstDay = date('Y-m-01', strtotime($this->selectedMonth . '-01'));
+                    $lastDay = date('Y-m-t', strtotime($this->selectedMonth . '-01'));
+                    $this->fromDate = $firstDay;
+                    $this->toDate = $lastDay;
+                }
+                break;
+
+            case 'GIORNO_PERSONALIZZATO':
+                if (!empty($this->selectedDay)) {
+                    $this->fromDate = $this->selectedDay;
+                    $this->toDate = $this->selectedDay;
+                }
+                break;
+
+            case 'ULTIMO TRIMESTRE':
+                $this->fromDate = $today->copy()->subMonths(3)->format('Y-m-d');
+                $this->toDate = $today->format('Y-m-d');
+                break;
+
+            case 'ULTIMO QUADRIMESTRE':
+                $this->fromDate = $today->copy()->subMonths(4)->format('Y-m-d');
+                $this->toDate = $today->format('Y-m-d');
+                break;
+        }
+    }
+    public function getCausals($records, $indentation)
+    {
+        foreach ($records as $record) {
+            $this->causals[] = array('id' => $record->id, 'name' => $record->getTree(), 'text' => $record->getTree(), 'level' => $indentation);
+            if (count($record->childs))
+                $this->getCausals($record->childs, $indentation + 1);
+        }
+    }
+
+    public function getMonth($m)
+    {
+        $ret = '';
+        switch ($m) {
+            case 1:
+                $ret = 'Gennaio';
+                break;
+            case 2:
+                $ret = 'Febbraio';
+                break;
+            case 3:
+                $ret = 'Marzo';
+                break;
+            case 4:
+                $ret = 'Aprile';
+                break;
+            case 5:
+                $ret = 'Maggio';
+                break;
+            case 6:
+                $ret = 'Giugno';
+                break;
+            case 7:
+                $ret = 'Luglio';
+                break;
+            case 8:
+                $ret = 'Agosto';
+                break;
+            case 9:
+                $ret = 'Settembre';
+                break;
+            case 10:
+                $ret = 'Ottobre';
+                break;
+            case 11:
+                $ret = 'Novembre';
+                break;
+            case 12:
+                $ret = 'Dicembre';
+                break;
+            default:
+                $ret = '';
+                break;
+        }
+        return $ret;
+    }
+
+
+
+    public function render()
+    {
+        $month = 0;
+        $year = 0;
+
+        $this->records = array();
+        $this->totals = array();
+        $this->causalAmounts = 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.id as row_id',
+                'records_rows.record_id',
+                'records_rows.causal_id',
+                'records_rows.amount',
+                'records_rows.note',
+                'records_rows.when',
+                'records_rows.vat_id',
+            )
+            ->join('records_rows', 'records.id', '=', 'records_rows.record_id')
+            //->where('records.deleted', false)
+            ->where(function ($query) {
+                $query->where('records.deleted', false)->orWhereNull('records.deleted');
+            })
+            ->whereBetween('date', [$this->appliedFromDate . " 00:00:00", $this->appliedToDate . " 23:59:59"])
+            ->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 = [];
+        $causalsAmounts = [];
+        $nominativi = [];
+
+        $values = [];
+
+        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;
+                    if ($data->vat_id > 0)
+                        $amount += getVatValue($amount, $data->vat_id);
+                } else {
+                    $amount = $data->amount;
+                }
+
+                $isCommercial = ($data->commercial == 1 || $data->commercial === '1' || $data->commercial === true);
+                $typeLabel = $isCommercial ? 'Commerciale' : 'Non Commerciale';
+
+                $nominativo = '';
+                if ($data->type == "IN") {
+                    if ($data->member) {
+                        $nominativo = $data->member->last_name . " " . $data->member->first_name;
+                    }
+                    if ($data->payment_method_id == 7)
+                        $values[] = array('id' => $data->record_id, 'amount' => $amount);
+                } 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] = [];
+                    $causalsAmounts[$groupKey] = []; // Initialize causal amounts for this group
+                    $nominativi[$groupKey] = $nominativo;
+                }
+
+                $groupedData[$groupKey]['amount'] += $amount;
+                $causalsCount[$groupKey][$causalCheck->getTree()] = true;
+
+                $causalName = $causalCheck->getTree();
+                if (!isset($causalsAmounts[$groupKey][$causalName])) {
+                    $causalsAmounts[$groupKey][$causalName] = 0;
+                }
+                $causalsAmounts[$groupKey][$causalName] += $amount;
+
+                if (!empty($data->note)) {
+                    $groupedData[$groupKey]['notes'][] = $data->note;
+                }
+                if ($data->deleted) {
+                    $groupedData[$groupKey]['deleted'] = true;
+                }
+            }
+        }
+
+        Log::info('values', [$values]);
+
+        foreach ($groupedData as $groupKey => $group) {
+            $causalsInGroup = array_keys($causalsCount[$groupKey]);
+
+            $causalDisplay = $group['type_label'];
+
+            if (count($causalsInGroup) > 1) {
+                $causalAmountsForJs = [];
+                foreach ($causalsInGroup as $causalName) {
+                    $causalAmountsForJs[] = $causalName . ':::' . formatPrice($causalsAmounts[$groupKey][$causalName]);
+                }
+                $detailDisplay = 'Varie|' . implode('|', $causalAmountsForJs);
+            } else {
+                $detailDisplay = $causalsInGroup[0];
+            }
+
+            $recordKey = $group['date'] . "§" . $causalDisplay . "§" . $group['nominativo'] . "§" . $detailDisplay . "§" . ($group['deleted'] ? 'DELETED' : '') . "§";
+
+            if (!isset($this->records[$recordKey][$group['payment_method']][$group['transaction_type']])) {
+                $this->records[$recordKey][$group['payment_method']][$group['transaction_type']] = 0;
+            }
+
+            $this->records[$recordKey][$group['payment_method']][$group['transaction_type']] += $group['amount'];
+
+            if (!isset($this->totals[$group['payment_method']])) {
+                $this->totals[$group['payment_method']]["IN"] = 0;
+                $this->totals[$group['payment_method']]["OUT"] = 0;
+            }
+
+            if (!$group['deleted'])
+                $this->totals[$group['payment_method']][$group['transaction_type']] += $group['amount'];
+        }
+
+        return view('livewire.records_old');
+    }
+
+    private function getLabels($fromDate, $toDate)
+    {
+        $begin = new DateTime($fromDate);
+        $end = new DateTime($toDate);
+
+        $interval = DateInterval::createFromDateString('1 day');
+        $date_range = new DatePeriod($begin, $interval, $end);
+        foreach ($date_range as $date) {
+            $labels[] = $date->format('d/M');
+        }
+
+        return $labels;
+    }
+
+    private function getRecordData($type, $fromDate, $toDate)
+    {
+        $data = [];
+        $begin = new DateTime($fromDate);
+        $end = new DateTime($toDate);
+
+        $interval = DateInterval::createFromDateString('1 day');
+        $date_range = new DatePeriod($begin, $interval, $end);
+
+        foreach ($date_range as $date) {
+            if ($type == 'IN') {
+                $found = false;
+                foreach ($this->in as $in) {
+                    if (date("Y-m-d", strtotime($in->date)) == $date->format('Y-m-d')) {
+                        $data[] = number_format($in->total, 0, "", "");
+                        $found = true;
+                    }
+                }
+                if (!$found)
+                    $data[] = 0;
+            }
+            if ($type == 'OUT') {
+                $found = false;
+                foreach ($this->out as $out) {
+                    if (date("Y-m-d", strtotime($out->date)) == $date->format('Y-m-d')) {
+                        $data[] = number_format($out->total, 0, "", "");
+                        $found = true;
+                    }
+                }
+                if (!$found)
+                    $data[] = 0;
+            }
+        }
+
+        return $data;
+    }
+
+    public function openExportModal()
+    {
+        $this->exportFromDate = $this->appliedFromDate;
+        $this->exportToDate = $this->appliedToDate;
+
+        // Reset email options
+        $this->sendViaEmail = false;
+        $this->exportEmailAddress = $this->getPreferredEmail();
+        $this->updateEmailSubject();
+
+        $this->emit('show-export-modal');
+    }
+
+    public function exportWithDateRange()
+    {
+
+        Log::info('=== EXPORT START ===', [
+            'user_id' => auth()->id(),
+            'from_date' => $this->exportFromDate,
+            'to_date' => $this->exportToDate,
+            'send_via_email' => $this->sendViaEmail,
+            'memory_usage' => memory_get_usage(true),
+            'memory_peak' => memory_get_peak_usage(true),
+            'time_limit' => ini_get('max_execution_time')
+        ]);
+
+        $this->isExporting = true;
+        $this->emit('$refresh');
+        usleep(100000);
+
+        if ($this->sendViaEmail) {
+            Log::info('Export: Validating email fields');
+            $this->validate([
+                'exportEmailAddress' => 'required|email',
+                'exportEmailSubject' => 'required|string|max:255',
+            ]);
+            Log::info('Export: Email validation passed');
+        }
+
+        $this->isExporting = true;
+
+        try {
+            Log::info('Export: Starting COMBINED data generation phase (NO SEPARATE CALLS)');
+            $startTime = microtime(true);
+
+            // *** THIS IS THE KEY CHANGE - USE ONLY THE COMBINED METHOD ***
+            $result = $this->generateExportDataAndTotals($this->exportFromDate, $this->exportToDate);
+            $exportRecords = $result['records'];
+            $exportTotals = $result['totals'];
+
+            Log::info('TOTALS', [$exportTotals]);
+
+            $dataGenTime = microtime(true) - $startTime;
+            Log::info('Export: COMBINED data generation completed (NO SEPARATE TOTALS CALL)', [
+                'records_count' => count($exportRecords),
+                'totals_count' => count($exportTotals),
+                'generation_time' => $dataGenTime,
+                'memory_usage' => memory_get_usage(true),
+                'memory_peak' => memory_get_peak_usage(true)
+            ]);
+
+
+            if ($this->sendViaEmail) {
+                Log::info('Export: Dispatching to background job');
+                $this->dispatchExportJob($exportRecords, $exportTotals);
+                Log::info('Export: Job dispatched successfully');
+            } else {
+                Log::info('Export: Starting direct download export');
+                $exportStartTime = microtime(true);
+
+                $result = $this->exportWithData($exportRecords, $exportTotals);
+
+                $exportTime = microtime(true) - $exportStartTime;
+                Log::info('Export: Direct export completed', [
+                    'export_time' => $exportTime,
+                    'total_time' => microtime(true) - $startTime,
+                    'memory_usage' => memory_get_usage(true),
+                    'memory_peak' => memory_get_peak_usage(true)
+                ]);
+
+                return $result;
+            }
+        } catch (\Illuminate\Validation\ValidationException $e) {
+            Log::error('Export: Validation error', [
+                'error' => $e->getMessage(),
+                'errors' => $e->errors()
+            ]);
+            $this->isExporting = false;
+            throw $e;
+        } catch (\Exception $e) {
+            Log::error('Export: General error', [
+                'error' => $e->getMessage(),
+                'trace' => $e->getTraceAsString(),
+                'memory_usage' => memory_get_usage(true),
+                'memory_peak' => memory_get_peak_usage(true),
+                'execution_time' => microtime(true) - ($startTime ?? 0)
+            ]);
+
+            $this->isExporting = false;
+
+            if ($this->sendViaEmail) {
+                $this->emit('export-email-error', 'Errore durante l\'invio dell\'email: ' . $e->getMessage());
+            } else {
+                session()->flash('error', 'Errore durante l\'export: ' . $e->getMessage());
+            }
+        } finally {
+            Log::info('Export: Cleanup phase');
+            $this->isExporting = false;
+            $this->emit('export-complete');
+            $this->emit('hide-export-modal');
+            Log::info('=== EXPORT END ===');
+        }
+    }
+    private function getEstimatedRecordCount($fromDate, $toDate)
+    {
+        $exclude_from_records = \App\Models\Member::where('exclude_from_records', true)->pluck('id')->toArray();
+
+        $query = \App\Models\Record::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;
+                    }
+                }
+            }
+            $query->whereIn('causal_id', $causals);
+        }
+
+        if ($this->filterMember != null && $this->filterMember > 0) {
+            $query->where('member_id', $this->filterMember);
+        }
+
+        return $query->count();
+    }
+
+    private function getMemberName($memberId)
+    {
+        $member = \App\Models\Member::find($memberId);
+        return $member ? $member->last_name . ' ' . $member->first_name : 'Sconosciuto';
+    }
+
+    private function getCausalsNames($causalIds)
+    {
+        if (!is_array($causalIds)) {
+            return null;
+        }
+
+        $causals = \App\Models\Causal::whereIn('id', $causalIds)->pluck('name')->toArray();
+        return implode(', ', $causals);
+    }
+
+    public function updatedExportFromDate()
+    {
+        $this->updateEmailSubject();
+    }
+
+    public function updatedExportToDate()
+    {
+        $this->updateEmailSubject();
+    }
+
+    public function updatedSendViaEmail($value)
+    {
+        if ($value && empty($this->exportEmailAddress)) {
+            $this->exportEmailAddress = $this->getPreferredEmail();
+        }
+    }
+
+    public function resetEmailForm()
+    {
+        $this->sendViaEmail = false;
+        $this->exportEmailAddress = $this->getPreferredEmail();
+        $this->updateEmailSubject();
+    }
+
+    private function updateEmailSubject()
+    {
+        if (!empty($this->exportFromDate) && !empty($this->exportToDate)) {
+            $fromFormatted = date('d/m/Y', strtotime($this->exportFromDate));
+            $toFormatted = date('d/m/Y', strtotime($this->exportToDate));
+
+            if ($this->exportFromDate === $this->exportToDate) {
+                $this->exportEmailSubject = "Prima Nota - Export del {$fromFormatted}";
+            } else {
+                $this->exportEmailSubject = "Prima Nota - Export dal {$fromFormatted} al {$toFormatted}";
+            }
+        }
+    }
+
+
+    /**
+     * Dispatch export job to queue
+     */
+    private function dispatchExportJob($exportRecords, $exportTotals)
+    {
+        try {
+            // Prepare filter descriptions for the job
+            $filterDescriptions = [
+                'member' => $this->filterMember ? $this->getMemberName($this->filterMember) : null,
+                'causals' => $this->filterCausals ? $this->getCausalsNames($this->filterCausals) : null,
+            ];
+
+            $paymentsArray = $this->payments->map(function ($payment) {
+                return [
+                    'id' => $payment->id,
+                    'name' => $payment->name,
+                    'type' => $payment->type
+                ];
+            })->toArray();
+
+            // Dispatch job to background queue
+            ExportPrimaNota::dispatch(
+                $exportRecords,
+                $exportTotals,
+                $this->exportEmailAddress,
+                $this->exportEmailSubject,
+                [
+                    'from' => date('d/m/Y', strtotime($this->exportFromDate)),
+                    'to' => date('d/m/Y', strtotime($this->exportToDate))
+                ],
+                auth()->id(),
+                $paymentsArray,
+                $filterDescriptions
+            );
+
+            $this->emit('export-email-queued');
+            session()->flash('success', 'Export in corso! Riceverai l\'email a breve alla casella: ' . $this->exportEmailAddress);
+
+            Log::info('Export job dispatched', [
+                'user_id' => auth()->id(),
+                'email' => $this->exportEmailAddress,
+                'date_range' => [$this->exportFromDate, $this->exportToDate],
+                'total_records' => count($exportRecords)
+            ]);
+        } catch (\Exception $e) {
+            Log::error('Failed to dispatch export job', [
+                'user_id' => auth()->id(),
+                'email' => $this->exportEmailAddress,
+                'error' => $e->getMessage()
+            ]);
+
+            throw new \Exception('Errore nell\'avvio dell\'export: ' . $e->getMessage());
+        }
+    }
+
+
+    function export()
+    {
+        $result = $this->generateExportDataAndTotals($this->exportFromDate, $this->exportToDate);
+        $exportRecords = $result['records'];
+        $exportTotals = $result['totals'];
+
+        return $this->exportWithData($exportRecords, $exportTotals);
+    }
+
+    private function exportWithData($exportRecords, $exportTotals)
+    {
+        Log::info('exportWithData: Starting Excel generation', [
+            'records_count' => count($exportRecords),
+            'totals_count' => count($exportTotals),
+            'memory_before' => memory_get_usage(true)
+        ]);
+
+        $startTime = microtime(true);
+
+        Log::info('exportWithData: Setting memory and GC');
+        ini_set('memory_limit', '512M');
+        gc_enable();
+
+        Log::info('exportWithData: Preparing column letters');
+        $letters = array('F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'AA');
+
+        Log::info('exportWithData: Creating spreadsheet object');
+        $spreadsheet = new Spreadsheet();
+        $activeWorksheet = $spreadsheet->getActiveSheet();
+
+        Log::info('exportWithData: Setting basic headers');
+        $activeWorksheet->setCellValue('A1', "Data");
+        $activeWorksheet->setCellValue('B1', "Tipologia");
+        $activeWorksheet->setCellValue('C1', "Causale");
+        $activeWorksheet->setCellValue('D1', "Nominativo");
+        $activeWorksheet->setCellValue('E1', "Stato");
+
+        $activeWorksheet->getStyle('A1:Q1')->getFill()
+            ->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)
+            ->getStartColor()->setARGB('FF0C6197');
+
+        $activeWorksheet->getStyle('A1:Q1')->getFont()->getColor()->setARGB('FFFFFFFF');
+
+
+        Log::info('exportWithData: Setting payment method headers');
+        $idx = 0;
+        foreach ($this->payments as $p) {
+            if ($idx >= count($letters)) {
+                Log::warning('exportWithData: Reached letter limit', ['payment_index' => $idx]);
+                break;
+            }
+            Log::debug('exportWithData: Setting payment header', [
+                'payment_name' => $p->name,
+                'column_index' => $idx,
+                'column_letter' => $letters[$idx]
+            ]);
+
+            $activeWorksheet->setCellValue($letters[$idx] . '1', $p->name);
+            $idx++;
+            if ($idx >= count($letters)) {
+                break;
+            }
+            $activeWorksheet->mergeCells($letters[$idx] . '1:' . $letters[$idx] . '1');
+            $idx++;
+        }
+
+        Log::info('exportWithData: Setting sub-headers');
+        $idx = 0;
+        $activeWorksheet->setCellValue('A2', "");
+        $activeWorksheet->setCellValue('B2', "");
+        $activeWorksheet->setCellValue('C2', "");
+        $activeWorksheet->setCellValue('D2', "");
+        $activeWorksheet->setCellValue('E2', "");
+
+        foreach ($this->payments as $p) {
+            if ($p->type == 'ALL') {
+                if ($idx >= count($letters)) {
+                    break;
+                }
+                $activeWorksheet->setCellValue($letters[$idx] . '2', "Entrate");
+                $idx++;
+                $activeWorksheet->setCellValue($letters[$idx] . '2', "Uscite");
+                $idx++;
+            } elseif ($p->type == 'IN') {
+                if ($idx >= count($letters)) {
+                    break;
+                }
+                $activeWorksheet->setCellValue($letters[$idx] . '2', "Entrate");
+                $idx++;
+                $activeWorksheet->setCellValue($letters[$idx] . '2', "");
+                $idx++;
+            } elseif ($p->type == 'OUT') {
+                if ($idx >= count($letters)) {
+                    break;
+                }
+                $activeWorksheet->setCellValue($letters[$idx] . '2', "");
+                $idx++;
+                $activeWorksheet->setCellValue($letters[$idx] . '2', "Uscite");
+                $idx++;
+            }
+        }
+
+        Log::info('exportWithData: Applying header styles');
+        $activeWorksheet->getStyle('A1:Q1')->getFont()->setBold(true);
+        $activeWorksheet->getStyle('A2:Q2')->getFont()->setBold(true);
+
+        Log::info('exportWithData: Starting data row processing');
+        $count = 3;
+        $batchSize = 1000;
+        $recordsProcessed = 0;
+
+        $totalRecords = count($exportRecords);
+        Log::info('exportWithData: Processing records in batches', [
+            'total_records' => $totalRecords,
+            'batch_size' => $batchSize
+        ]);
+
+        $recordsArray = array_chunk($exportRecords, $batchSize, true);
+        Log::info('exportWithData: Created batches', ['batch_count' => count($recordsArray)]);
+
+        foreach ($recordsArray as $batchIndex => $recordsBatch) {
+            Log::info('exportWithData: Processing batch', [
+                'batch_index' => $batchIndex,
+                'batch_size' => count($recordsBatch),
+                'memory_current' => memory_get_usage(true),
+                'time_elapsed' => microtime(true) - $startTime
+            ]);
+
+            foreach ($recordsBatch as $causal => $record) {
+                if ($recordsProcessed % 250 == 0) {
+                    Log::info('exportWithData: Record processing progress', [
+                        'processed' => $recordsProcessed,
+                        'total' => $totalRecords,
+                        'current_row' => $count,
+                        'memory_usage' => memory_get_usage(true),
+                        'time_elapsed' => microtime(true) - $startTime
+                    ]);
+                }
+
+                try {
+                    $check = $causal;
+                    $parts = explode("§", $check);
+                    $d = $parts[0] ?? '';
+                    $c = $parts[1] ?? '';
+                    $j = $parts[2] ?? '';
+                    $det = $parts[3] ?? '';
+                    $deleted = $parts[4] ?? '';
+
+                    $detailParts = explode('|', $det);
+                    $exportDetail = count($detailParts) > 1 ? implode(', ', array_slice($detailParts, 1)) : $det;
+
+                    Log::debug('exportWithData: Setting row cells', ['row' => $count]);
+                    $activeWorksheet->setCellValue('A' . $count, !empty($d) ? date("d/m/Y", strtotime($d)) : '');
+                    $activeWorksheet->setCellValue('B' . $count, $c);
+                    $activeWorksheet->setCellValue('C' . $count, $exportDetail);
+                    $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;
+                        }
+
+                        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"]) : "";
+
+                            $activeWorksheet->setCellValue($letters[$idx] . $count, $inValue);
+                            $idx++;
+                            $activeWorksheet->setCellValue($letters[$idx] . $count, $outValue);
+                            $idx++;
+                        } else {
+                            $activeWorksheet->setCellValue($letters[$idx] . $count, "");
+                            $idx++;
+                            $activeWorksheet->setCellValue($letters[$idx] . $count, "");
+                            $idx++;
+                        }
+                    }
+
+                    $count++;
+                    $recordsProcessed++;
+
+                    if ($recordsProcessed % 500 === 0) {
+                        Log::debug('exportWithData: Garbage collection');
+                        gc_collect_cycles();
+                    }
+                } catch (\Exception $e) {
+                    Log::error('exportWithData: Error processing record row', [
+                        'row' => $count,
+                        'causal' => $causal,
+                        'error' => $e->getMessage(),
+                        'processed_so_far' => $recordsProcessed
+                    ]);
+                    throw $e;
+                }
+            }
+
+            Log::info('exportWithData: Batch completed', [
+                'batch_index' => $batchIndex,
+                'records_in_batch' => count($recordsBatch),
+                'total_processed' => $recordsProcessed
+            ]);
+
+            unset($recordsBatch);
+            gc_collect_cycles();
+        }
+
+        Log::info('exportWithData: Adding totals row');
+        $count++;
+        $idx = 0;
+
+        $activeWorksheet->setCellValue('A' . $count, 'Totale');
+        $activeWorksheet->setCellValue('B' . $count, '');
+        $activeWorksheet->setCellValue('C' . $count, '');
+        $activeWorksheet->setCellValue('D' . $count, '');
+        $activeWorksheet->setCellValue('E' . $count, '');
+
+        foreach ($this->payments as $p) {
+            if ($idx >= count($letters) - 1) {
+                break;
+            }
+
+            if (isset($exportTotals[$p->name])) {
+                if ($p->type == 'ALL') {
+                    $activeWorksheet->setCellValue($letters[$idx] . $count, formatPrice($exportTotals[$p->name]["IN"] ?? 0));
+                    $idx++;
+                    $activeWorksheet->setCellValue($letters[$idx] . $count, formatPrice($exportTotals[$p->name]["OUT"] ?? 0));
+                    $idx++;
+                } elseif ($p->type == 'IN') {
+                    $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($exportTotals[$p->name]["OUT"] ?? 0));
+                    $idx++;
+                }
+            } else {
+                if ($p->type == 'ALL') {
+                    $activeWorksheet->setCellValue($letters[$idx] . $count, "0");
+                    $idx++;
+                    $activeWorksheet->setCellValue($letters[$idx] . $count, "0");
+                    $idx++;
+                } elseif ($p->type == 'IN') {
+                    $activeWorksheet->setCellValue($letters[$idx] . $count, "0");
+                    $idx++;
+                    $activeWorksheet->setCellValue($letters[$idx] . $count, "");
+                    $idx++;
+                } elseif ($p->type == 'OUT') {
+                    $activeWorksheet->setCellValue($letters[$idx] . $count, "");
+                    $idx++;
+                    $activeWorksheet->setCellValue($letters[$idx] . $count, "0");
+                    $idx++;
+                }
+            }
+        }
+
+        Log::info('exportWithData: Applying final styles');
+        $activeWorksheet->getStyle('A' . $count . ':Q' . $count)->getFont()->setBold(true);
+
+        Log::info('exportWithData: Setting column dimensions');
+        $activeWorksheet->getColumnDimension('A')->setWidth(20);
+        $activeWorksheet->getColumnDimension('B')->setWidth(40);
+        $activeWorksheet->getColumnDimension('C')->setWidth(40);
+        $activeWorksheet->getColumnDimension('D')->setWidth(40);
+        $activeWorksheet->getColumnDimension('E')->setWidth(20);
+        foreach ($letters as $l) {
+            $activeWorksheet->getColumnDimension($l)->setWidth(20);
+        }
+
+        $filename = 'prima_nota_' . date("YmdHis") . '.xlsx';
+        Log::info('exportWithData: Preparing to save file', [
+            'filename' => $filename,
+            'total_processing_time' => microtime(true) - $startTime,
+            'memory_before_save' => memory_get_usage(true)
+        ]);
+
+        try {
+            $currentClient = session('currentClient', 'default');
+            $tempPath = sys_get_temp_dir() . '/' . $filename;
+
+            Log::info('exportWithData: Creating Excel writer');
+            $writer = new Xlsx($spreadsheet);
+
+            Log::info('exportWithData: Saving to temp path', ['temp_path' => $tempPath]);
+            $writerStart = microtime(true);
+            $writer->save($tempPath);
+            $writerTime = microtime(true) - $writerStart;
+
+            Log::info('exportWithData: File saved to temp', [
+                'writer_time' => $writerTime,
+                'file_size' => file_exists($tempPath) ? filesize($tempPath) : 'unknown',
+                'memory_after_save' => memory_get_usage(true)
+            ]);
+
+            unset($spreadsheet, $activeWorksheet, $writer);
+            gc_collect_cycles();
+
+            Log::info('exportWithData: Uploading to S3');
+            $disk = Storage::disk('s3');
+            $s3Path = $currentClient . '/prima_nota/' . $filename;
+
+            $primaNotaFolderPath = $currentClient . '/prima_nota/.gitkeep';
+            if (!$disk->exists($primaNotaFolderPath)) {
+                $disk->put($primaNotaFolderPath, '');
+                Log::info("Created prima_nota folder for client: {$currentClient}");
+            }
+
+            $uploadStart = microtime(true);
+            $fileContent = file_get_contents($tempPath);
+            $uploaded = $disk->put($s3Path, $fileContent, 'private');
+            $uploadTime = microtime(true) - $uploadStart;
+
+            if (!$uploaded) {
+                throw new \Exception('Failed to upload file to Wasabi S3');
+            }
+
+            Log::info("Export completed successfully", [
+                'client' => $currentClient,
+                'path' => $s3Path,
+                'file_size' => filesize($tempPath),
+                'records_processed' => $recordsProcessed,
+                'upload_time' => $uploadTime,
+                'total_time' => microtime(true) - $startTime,
+                'memory_peak' => memory_get_peak_usage(true)
+            ]);
+
+            if (file_exists($tempPath)) {
+                unlink($tempPath);
+            }
+
+            $downloadUrl = $disk->temporaryUrl($s3Path, now()->addHour());
+            return redirect($downloadUrl);
+        } catch (\Exception $e) {
+            Log::error('Export S3 error - falling back to local', [
+                'error' => $e->getMessage(),
+                'trace' => $e->getTraceAsString(),
+                'client' => session('currentClient', 'unknown'),
+                'filename' => $filename,
+                'records_processed' => $recordsProcessed ?? 0,
+                'time_elapsed' => microtime(true) - $startTime
+            ]);
+
+            // Fallback logic remains the same...
+            $currentClient = session('currentClient', 'default');
+            $clientFolder = storage_path('app/prima_nota/' . $currentClient);
+
+            if (!is_dir($clientFolder)) {
+                mkdir($clientFolder, 0755, true);
+                Log::info("Created local client prima_nota folder: {$clientFolder}");
+            }
+
+            $localPath = $clientFolder . '/' . $filename;
+
+            if (isset($tempPath) && file_exists($tempPath)) {
+                rename($tempPath, $localPath);
+            } else {
+                $writer = new Xlsx($spreadsheet);
+                $writer->save($localPath);
+                unset($spreadsheet, $activeWorksheet, $writer);
+            }
+
+            gc_collect_cycles();
+
+            Log::warning("Export saved locally due to S3 error", [
+                'client' => $currentClient,
+                'local_path' => $localPath,
+                'error' => $e->getMessage()
+            ]);
+
+            session()->flash('warning', 'File salvato localmente a causa di un errore del cloud storage.');
+            return response()->download($localPath)->deleteFileAfterSend();
+        }
+    }
+
+    private function getPreferredEmail()
+    {
+        $email = auth()->user()->email ?? null;
+
+        if (empty($email)) {
+            $email = session('user_email', null);
+        }
+
+        if (empty($email)) {
+            $member = \App\Models\Member::where('user_id', auth()->id())->first();
+            $email = $member ? $member->email : null;
+        }
+
+        if (empty($email)) {
+            $email = config('mail.default_recipient', '');
+        }
+
+        return $email;
+    }
+
+        public function updatedSelectedDay($value)
+    {
+        if (!empty($value)) {
+            $this->selectedPeriod = 'GIORNO_PERSONALIZZATO';
+            $this->fromDate = $value;
+            $this->toDate = $value;
+            $this->applyFilters();
+        }
+    }
+
+    public function selectDay($day)
+    {
+        $this->selectedDay = $day;
+        $this->showDayPicker = false;
+        $this->updatedSelectedDay($day);
+    }
+
+    public function toggleDayPicker()
+    {
+        $this->showDayPicker = !$this->showDayPicker;
+    }
+
+    public function selectToday()
+    {
+        $today = date('Y-m-d');
+        $this->selectDay($today);
+    }
+
+    public function selectYesterday()
+    {
+        $yesterday = date('Y-m-d', strtotime('-1 day'));
+        $this->selectDay($yesterday);
+    }
+
+    // Updated month methods to work with both custom month and day
+    public function updatedSelectedMonth($value)
+    {
+        if (!empty($value)) {
+            $this->selectedPeriod = 'MESE_PERSONALIZZATO';
+            $firstDay = date('Y-m-01', strtotime($value . '-01'));
+            $lastDay = date('Y-m-t', strtotime($value . '-01'));
+            $this->fromDate = $firstDay;
+            $this->toDate = $lastDay;
+            $this->applyFilters();
+        }
+    }
+
+    public function selectMonth($month)
+    {
+        $this->selectedMonth = $month;
+        $this->showMonthPicker = false;
+        $this->updatedSelectedMonth($month);
+    }
+
+    public function toggleMonthPicker()
+    {
+        $this->showMonthPicker = !$this->showMonthPicker;
+    }
+}

+ 117 - 9
app/Jobs/ExportPrimaNota.php

@@ -23,8 +23,9 @@ class ExportPrimaNota implements ShouldQueue
     public $tries = 3;
     public $maxExceptions = 3;
 
-    protected $exportData;
-    protected $exportTotals;
+    //protected $exportData;
+    //protected $exportTotals;
+    protected $records;
     protected $emailAddress;
     protected $emailSubject;
     protected $dateRange;
@@ -35,10 +36,12 @@ class ExportPrimaNota implements ShouldQueue
     /**
      * Create a new job instance.
      */
-    public function __construct($exportData, $exportTotals, $emailAddress, $emailSubject, $dateRange, $userId, $payments, $filters = [])
+    //public function __construct($exportData, $exportTotals, $emailAddress, $emailSubject, $dateRange, $userId, $payments, $filters = [])
+    public function __construct($records, $emailAddress, $emailSubject, $dateRange, $userId, $payments, $filters = [])
     {
-        $this->exportData = $exportData;
-        $this->exportTotals = $exportTotals;
+        //$this->exportData = $exportData;
+        //$this->exportTotals = $exportTotals;
+        $this->records = $records;
         $this->emailAddress = $emailAddress;
         $this->emailSubject = $emailSubject;
         $this->dateRange = $dateRange;
@@ -59,7 +62,7 @@ class ExportPrimaNota implements ShouldQueue
                 'user_id' => $this->userId,
                 'email' => $this->emailAddress,
                 'date_range' => $this->dateRange,
-                'total_records' => count($this->exportData)
+                //'total_records' => count($this->exportData)
             ]);
 
             ini_set('memory_limit', '1024M');
@@ -86,7 +89,7 @@ class ExportPrimaNota implements ShouldQueue
                 'subject' => $this->emailSubject,
                 'from_date' => $this->dateRange['from'],
                 'to_date' => $this->dateRange['to'],
-                'total_records' => count($this->exportData),
+                //'total_records' => count($this->exportData),
                 'user_name' => $user ? $user->name : 'Utente',
                 'generated_at' => now()->format('d/m/Y H:i:s'),
                 'filters_applied' => $this->getFiltersDescription(),
@@ -161,11 +164,116 @@ class ExportPrimaNota implements ShouldQueue
     /**
      * Create Excel file with export data
      */
+
     private function createExcelFile($filePath)
+    {
+        $startTime = microtime(true);
+
+        $spreadsheet = new Spreadsheet();
+        $activeWorksheet = $spreadsheet->getActiveSheet();
+
+        $activeWorksheet->setCellValue('A1', "Data");
+        $activeWorksheet->setCellValue('B1', "Tipologia");
+        $activeWorksheet->setCellValue('C1', "Causale");
+        $activeWorksheet->setCellValue('D1', "Nominativo");
+        $activeWorksheet->setCellValue('E1', "Stato");
+        $activeWorksheet->setCellValue('F1', "Entrata");
+        $activeWorksheet->setCellValue('G1', "Uscita");
+        $activeWorksheet->setCellValue('H1', "Origine");
+        $activeWorksheet->setCellValue('I1', "Destinazione");
+        $activeWorksheet->setCellValue('J1', "Metodo di pagamento");
+
+        $activeWorksheet->getStyle('A1:J1')->getFill()
+            ->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)
+            ->getStartColor()->setARGB('FF0C6197');
+
+        $activeWorksheet->getStyle('A1:J1')->getFont()->getColor()->setARGB('FFFFFFFF');
+
+        $idx = 2;
+        foreach($this->records as $record)
+        {
+            if ($record->date != '')
+            {
+                $activeWorksheet->setCellValue('A' . $idx, date("d/m/Y", strtotime($record->date)));
+                $activeWorksheet->setCellValue('B' . $idx, $record->commercial ? 'Commerciale' : 'Non commerciale');
+                $activeWorksheet->setCellValue('C' . $idx, $record->causal_name);
+                $activeWorksheet->setCellValue('D' . $idx, $record->type == 'IN' ? ($record->member->first_name . " " . $record->member->last_name) : @$record->supplier->name);
+                $activeWorksheet->setCellValue('E' . $idx, $record->deleted ? 'Annullata' : '');
+                $activeWorksheet->setCellValue('F' . $idx, $record->type == 'IN' ? formatPrice($record->amount) : '');
+                $activeWorksheet->setCellValue('G' . $idx, $record->type == 'OUT' ? formatPrice($record->amount) : '');
+                $activeWorksheet->setCellValue('H' . $idx, $record->type == 'OUT' ? $record->origin : '');
+                $activeWorksheet->setCellValue('I' . $idx, $record->type == 'IN' ? $record->destination : '');
+                $activeWorksheet->setCellValue('J' . $idx, $record->payment_method->name);
+            }
+            else
+            {
+                $activeWorksheet->setCellValue('A' . $idx, "Totali");
+                $activeWorksheet->setCellValue('B' . $idx, "");
+                $activeWorksheet->setCellValue('C' . $idx, "");
+                $activeWorksheet->setCellValue('D' . $idx, "");
+                $activeWorksheet->setCellValue('E' . $idx, "");
+                $activeWorksheet->setCellValue('F' . $idx, formatPrice($record->total_in));
+                $activeWorksheet->setCellValue('G' . $idx, formatPrice($record->total_out));
+                $activeWorksheet->setCellValue('H' . $idx, "");
+                $activeWorksheet->setCellValue('I' . $idx, "");
+                $activeWorksheet->setCellValue('J' . $idx, "");
+            }
+            $idx++;
+        }
+
+        $activeWorksheet->getColumnDimension('A')->setWidth(10);
+        $activeWorksheet->getColumnDimension('B')->setWidth(30);
+        $activeWorksheet->getColumnDimension('C')->setWidth(30);
+        $activeWorksheet->getColumnDimension('D')->setWidth(30);
+        $activeWorksheet->getColumnDimension('E')->setWidth(10);
+        $activeWorksheet->getColumnDimension('F')->setWidth(10);
+        $activeWorksheet->getColumnDimension('G')->setWidth(10);
+        $activeWorksheet->getColumnDimension('H')->setWidth(20);
+        $activeWorksheet->getColumnDimension('I')->setWidth(20);
+        $activeWorksheet->getColumnDimension('J')->setWidth(30);
+
+        $activeWorksheet->getStyle('A' . ($idx - 1) . ':J' . ($idx - 1))->getFont()->setBold(true);
+
+        try {
+            $writerStart = microtime(true);
+            $writer = new Xlsx($spreadsheet);
+            $writer->save($filePath);
+            $writerTime = microtime(true) - $writerStart;
+
+            Log::info('Job createExcelFile: File saved successfully', [
+                'file_path' => $filePath,
+                'file_exists' => file_exists($filePath),
+                'file_size' => file_exists($filePath) ? filesize($filePath) : 0,
+                'writer_time' => $writerTime,
+                'total_time' => microtime(true) - $startTime,
+                'memory_peak' => memory_get_peak_usage(true)
+            ]);
+        } catch (\Exception $e) {
+            Log::error('Job createExcelFile: Error during file save', [
+                'file_path' => $filePath,
+                'error' => $e->getMessage(),
+                'trace' => $e->getTraceAsString(),
+                'memory_usage' => memory_get_usage(true),
+                'time_elapsed' => microtime(true) - $startTime
+            ]);
+            throw $e;
+        }
+
+        Log::info('Job createExcelFile: Cleaning up memory');
+        unset($spreadsheet, $activeWorksheet, $writer);
+        gc_collect_cycles();
+
+        Log::info('Job createExcelFile: Completed successfully', [
+            'total_time' => microtime(true) - $startTime,
+            'memory_after_cleanup' => memory_get_usage(true)
+        ]);
+    }
+
+    private function createExcelFileOLD($filePath)
     {
         Log::info('Job createExcelFile: Starting Excel file creation', [
             'file_path' => $filePath,
-            'export_data_count' => count($this->exportData),
+            //'export_data_count' => count($this->exportData),
             'payments_count' => count($this->payments),
             'memory_before' => memory_get_usage(true),
             'time_limit' => ini_get('max_execution_time')
@@ -270,7 +378,7 @@ class ExportPrimaNota implements ShouldQueue
             ->getFont()->getColor()->setARGB('FFFFFFFF');
 
         Log::info('Job createExcelFile: Starting data row processing', [
-            'total_export_records' => count($this->exportData),
+            //'total_export_records' => count($this->exportData),
             'time_elapsed_so_far' => microtime(true) - $startTime
         ]);
 

+ 13 - 0
app/Models/Bank.php

@@ -14,6 +14,7 @@ class Bank extends Model
     protected $fillable = [
         'name',
         'enabled',
+        'visibility'
     ];
 
     public function canDelete()
@@ -21,4 +22,16 @@ class Bank extends Model
         return \App\Models\PaymentMethod::where('bank_id', $this->id)->count() == 0;
     }
 
+    public function getVisibility()
+    {
+        $ret = '';
+        if ($this->visibility == 'IN')
+            $ret = "Solo in entrata";
+        if ($this->visibility == 'OUT')
+            $ret = "Solo in uscita";
+        if ($this->visibility == 'ALL')
+            $ret = "Entrambi";
+        return $ret;
+    }
+
 }

+ 2 - 0
app/Models/Record.php

@@ -14,6 +14,8 @@ class Record extends Model
         'supplier_id',
         // 'causal_id',
         'payment_method_id',
+        'destination_id',
+        'origin_id',
         'date',
         //'month',
         //'year',

+ 32 - 0
database/migrations/2025_11_17_100244_add_visibility_to_banks_table.php

@@ -0,0 +1,32 @@
+<?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('banks', function (Blueprint $table) {
+            $table->string('visibility')->nullable();
+        });
+    }
+
+    /**
+     * Reverse the migrations.
+     *
+     * @return void
+     */
+    public function down()
+    {
+        Schema::table('banks', function (Blueprint $table) {
+            $table->dropColumn('visibility');
+        });
+    }
+};

+ 36 - 0
database/migrations/2025_11_17_102344_add_more_fields_to_records_rows_table.php

@@ -0,0 +1,36 @@
+<?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('records', function (Blueprint $table) {
+            $table->unsignedBigInteger('destination_id')->nullable();
+            $table->foreign('destination_id')->nullable()->references('id')->on('banks')->onUpdate('cascade')->onDelete('cascade');
+            $table->unsignedBigInteger('origin_id')->nullable();
+            $table->foreign('origin_id')->nullable()->references('id')->on('banks')->onUpdate('cascade')->onDelete('cascade');
+        });
+    }
+
+    /**
+     * Reverse the migrations.
+     *
+     * @return void
+     */
+    public function down()
+    {
+        Schema::table('records', function (Blueprint $table) {
+            $table->dropColumn('destination_id');
+            $table->dropColumn('origin_id');
+        });
+    }
+};

+ 9 - 2
resources/views/layouts/app.blade.php

@@ -162,6 +162,8 @@
                 print "Gestionale";
             if (Request::is('records'))
                 print "Prima nota";
+            if (Request::is('records_old'))
+                print "Prima nota";
             if (Request::is('course_member_one'))
                 print "Corsi";
             if (Request::is('course_member_two'))
@@ -276,11 +278,11 @@
                         </div>
                         <div class="accordion-item">
                             <h2 class="accordion-header linkMenu" id="headingTwo">
-                                <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#collapseTwo" aria-expanded="{{Request::is('in') || Request::is('out') || Request::is('receipts') || Request::is('records_in_out') || Request::is('records') ? 'true' : 'false'}}" aria-controls="collapseTwo">
+                                <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#collapseTwo" aria-expanded="{{Request::is('in') || Request::is('out') || Request::is('receipts') || Request::is('records_in_out') || Request::is('records') || Request::is('records_old') ? 'true' : 'false'}}" aria-controls="collapseTwo">
                                     Contabilità
                                 </button>
                             </h2>
-                            <div id="collapseTwo" class="accordion-collapse collapse {{Request::is('in') || Request::is('out') || Request::is('receipts') || Request::is('records_in_out') || Request::is('records') ? 'show' : ''}}" aria-labelledby="headingTwo" data-bs-parent="#accordionExample">
+                            <div id="collapseTwo" class="accordion-collapse collapse {{Request::is('in') || Request::is('out') || Request::is('receipts') || Request::is('records_in_out') || Request::is('records') || Request::is('records_old') ? 'show' : ''}}" aria-labelledby="headingTwo" data-bs-parent="#accordionExample">
                                 <div class="accordion-body">
                                     <ul class="nav nav-pills flex-column align-items-center align-items-sm-start w-100" id="menu-contabilita" style="margin-top:0px;">
                                         <li class="nav-item" style="{{Request::is('in') ? 'background-color: #c5d9e6;' : ''}}">
@@ -312,6 +314,11 @@
                                                 <span class="ms-3 d-md-inline">Prima Nota</span>
                                             </a>
                                         </li>
+                                        <li class="nav-item" style="{{Request::is('records_old') ? 'background-color: #c5d9e6;' : ''}}">
+                                            <a href="/records_old" class="nav-link d-flex align-items-center linkMenu">
+                                                <span class="ms-3 d-md-inline">Prima Nota (OLD)</span>
+                                            </a>
+                                        </li>
                                     </ul>
                                 </div>
                             </div>

+ 13 - 1
resources/views/livewire/bank.blade.php

@@ -9,7 +9,7 @@
         <header id="title--section" style="display:none !important"  class="d-flex align-items-center justify-content-between">
             <div class="title--section_name d-flex align-items-center justify-content-between">
                 <i class="ico--ui title_section utenti me-2"></i>
-                <h2 class="primary">Banche</h2>
+                <h2 class="primary">Canali finanziari</h2>
             </div>
 
             <div class="title--section_addButton"  wire:click="add()" style="cursor: pointer;">
@@ -46,6 +46,7 @@
                 <thead>
                     <tr>
                         <th scope="col">Nome</th>
+                        <th scope="col">Visibilità</th>
                         <th scope="col">Abilitato</th>
                         <th scope="col">...</th>
                     </tr>
@@ -54,6 +55,7 @@
                     @foreach($records as $record)
                         <tr>
                             <td>{{$record->name}}</td>
+                            <td>{{$record->getVisibility()}}</td>
                             <td> <span class="tablesaw-cell-content"><span class="badge tessera-badge {{$record->enabled ? 'active' : 'suspended'}}">{{$record->enabled ? 'attivo' : 'disattivo'}}</span></span></td>
                             <td>
                                 <button type="button" class="btn" wire:click="edit({{ $record->id }})" data-bs-toggle="popover"  data-bs-trigger="hover focus" data-bs-placement="bottom" data-bs-content="Modifica"><i class="fa-regular fa-pen-to-square"></i></button>
@@ -118,6 +120,16 @@
                                     @enderror
                                 </div>
                             </div>
+                            <div class="col">
+                                <div class="form--item">
+                                    <label for="inputName" class="form-label">Visibilità</label>
+                                    <select class="form-control" id="visibility" wire:model="visibility">
+                                        <option value="IN">Solo in entrata</option>
+                                        <option value="OUT">Solo in uscita</option>
+                                        <option value="ALL">Entrambi</option>
+                                    </select>
+                                </div>
+                            </div>
                             <div class="col">
                                 <div class="form--item">
                                     <label for="enabled" class="form-label">Abilitato</label>

+ 46 - 131
resources/views/livewire/records.blade.php

@@ -333,145 +333,59 @@
             <thead>
                 <tr>
                     <th scope="col">Data</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)
-                        <th colspan="2" scope="col" style="text-align:center; border-left:3px solid white;">{{$p->name}}</th>
-                    @endforeach
+                    <th scope="col">Tipologia</th>
+                    <th scope="col">Causale</th>
+                    <th scope="col">Nominativo</th>
+                    <th scope="col">Stato</th>
+                    <th scope="col">Entrata</th>
+                    <th scope="col">Uscita</th>
+                    <th scope="col">Origine</th>
+                    <th scope="col">Destinazione</th>
+                    <th scope="col">Metodo di pagamento</th>
                 </tr>
                 <tr>
                     <th scope="col"></th>
-                    <th scope="col" style="border-left:3px solid white;"></th>
-                    <th scope="col" style="border-left:3px solid white;"></th>
-                    <th scope="col" style="border-left:3px solid white;"></th>
-                    <th scope="col" style="border-left:3px solid white;"></th>
-                    @foreach($payments as $p)
-                        @if($p->type == 'ALL')
-                            <th scope="col" style="text-align:center; border-left:3px solid white;">Entrate</th>
-                            <th scope="col" style="text-align:center">Uscite</th>
-                        @elseif($p->type == 'IN')
-                            <th scope="col" style="text-align:center; border-left:3px solid white;">Entrate</th>
-                            <th scope="col" style="text-align:center;"></th>
-                        @elseif($p->type == 'OUT')
-                            <th style="border-left:3px solid white;"></th>
-                            <th scope="col" style="text-align:center;">Uscite</th>
-                        @endif
-                    @endforeach
+                    <th scope="col"></th>
+                    <th scope="col"></th>
+                    <th scope="col"></th>
+                    <th scope="col"></th>
+                    <th scope="col"></th>
+                    <th scope="col"></th>
+                    <th scope="col"></th>
+                    <th scope="col"></th>
+                    <th scope="col"></th>
                 </tr>
             </thead>
             <tbody id="checkall-target">
                 @php $count = 0; @endphp
-                @foreach($records as $causal => $record)
-                    <tr>
-                        @php
-                        $parts = explode("§", $causal);
-                        $d = $parts[0] ?? '';
-                        $c = $parts[1] ?? '';
-                        $n = $parts[2] ?? '';
-                        $det = $parts[3] ?? '';
-                        $del = $parts[4] ?? '';
-
-                        $detailParts = explode('|', $det);
-                        $isMultiple = count($detailParts) > 1;
-                        $displayDetail = $isMultiple ? 'Varie' : $det;
-                        @endphp
-                        <td style="background-color:{{$count % 2 == 0 ? 'white' : '#f2f4f7'}}">{{date("d/m/Y", strtotime($d))}}</td>
-                        <td style="border-left:3px solid white !important;background-color:{{$count % 2 == 0 ? 'white' : '#f2f4f7'}}">{{$c}}</td>
-                        <td style="border-left:3px solid white !important;background-color:{{$count % 2 == 0 ? 'white' : '#f2f4f7'}}">
-                            @if($isMultiple)
-                                <span class="varie-link" data-causals="{{implode('|', array_slice($detailParts, 1))}}" style="color: #0C6197; cursor: pointer; text-decoration: underline;">
-                                    {{$displayDetail}}
-                                </span>
-                            @else
-                                {{$displayDetail}}
-                            @endif
-                        </td>
-                        <td style="border-left:3px solid white !important;background-color:{{$count % 2 == 0 ? 'white' : '#f2f4f7'}}">
-                            @if($del == 'DELETED')
-                                <span style='color:red'>Annullata</span>
-                            @endif
-                        </td>
-                        <td style="border-left:3px solid white !important;background-color:{{$count % 2 == 0 ? 'white' : '#f2f4f7'}}">{{$n}}</td>
-                        @foreach($payments as $p)
-                            @if(isset($record[$p->name]))
-                                <td style="text-align:right; border-left:3px solid white !important;background-color:{{$count % 2 == 0 ? 'white' : '#f2f4f7'}}">
-                                    @if(isset($record[$p->name]["IN"]))
-                                        <span class="tablesaw-cell-content " style="color:green">{{formatPrice($record[$p->name]["IN"])}}</span>
-                                    @endif
-                                </td>
-                                <td style="text-align:right;background-color:{{$count % 2 == 0 ? 'white' : '#f2f4f7'}}">
-                                    @if(isset($record[$p->name]["OUT"]))
-                                        <span class="tablesaw-cell-content " style="color:red">{{formatPrice($record[$p->name]["OUT"])}}</span>
-                                    @endif
-                                </td>
-                            @else
-                                <td style="border-left:3px solid white !important;background-color:{{$count % 2 == 0 ? 'white' : '#f2f4f7'}}"></td>
-                                <td style="background-color:{{$count % 2 == 0 ? 'white' : '#f2f4f7'}}"></td>
-                            @endif
-                        @endforeach
-                    </tr>
-                    @php $count++; @endphp
+                @foreach($records as $record)
+                    @if($record->date != '')
+                        <tr>
+                            <td style="background-color:{{$count % 2 == 0 ? 'white' : '#f2f4f7'}}">{{date("d/m/Y", strtotime($record->date))}}</td>
+                            <td style="background-color:{{$count % 2 == 0 ? 'white' : '#f2f4f7'}}">{{$record->commercial ? 'Commerciale' : 'Non commerciale'}}</td>
+                            <td style="background-color:{{$count % 2 == 0 ? 'white' : '#f2f4f7'}}">{{$record->causal_name}}</td>
+                            <td style="background-color:{{$count % 2 == 0 ? 'white' : '#f2f4f7'}}">{{$record->type == 'IN' ? ($record->member->first_name . " " . $record->member->last_name) : @$record->supplier->name}}</td>
+                            <td style="background-color:{{$count % 2 == 0 ? 'white' : '#f2f4f7'}}">{{$record->deleted ? 'Annullata' : ''}}</td>
+                            <td style="background-color:{{$count % 2 == 0 ? 'white' : '#f2f4f7'}};text-align:right;">{{$record->type == 'IN' ? formatPrice($record->amount) : ''}}</td>
+                            <td style="background-color:{{$count % 2 == 0 ? 'white' : '#f2f4f7'}};text-align:right;">{{$record->type == 'OUT' ? formatPrice($record->amount) : ''}}</td>
+                            <td style="background-color:{{$count % 2 == 0 ? 'white' : '#f2f4f7'}}">{{$record->type == 'OUT' ? $record->origin : ''}}</td>
+                            <td style="background-color:{{$count % 2 == 0 ? 'white' : '#f2f4f7'}}">{{$record->type == 'IN' ? $record->destination : ''}}</td>
+                            <td style="background-color:{{$count % 2 == 0 ? 'white' : '#f2f4f7'}}">{{$record->payment_method->name}}</td>
+                        </tr>
+                        @php $count++; @endphp
+                    @endif
                 @endforeach
             </tbody>
-            <tfoot>
-                <tr>
-                    <td></td>
-                    <td></td>
-                    <td></td>
-                    <td></td>
-                    <td><b>Totale</b></td>
-                    @foreach($payments as $p)
-                        @if(isset($totals[$p->name]))
-                            @if($p->type == 'ALL')
-                                <td style="text-align:right"><span class="tablesaw-cell-content primary" style="color:green; font-size:18px;"><b>{{formatPrice(isset($totals[$p->name]) ? $totals[$p->name]["IN"] : 0)}}</b></span></td>
-                                <td style="text-align:right"><span class="tablesaw-cell-content primary" style="color:red; font-size:18px;"><b>{{formatPrice(isset($totals[$p->name]) ? $totals[$p->name]["OUT"] : 0)}}</b></span></td>
-                            @elseif($p->type == 'IN')
-                                <td style="text-align:right"><span class="tablesaw-cell-content primary" style="color:green; font-size:18px;"><b>{{formatPrice(isset($totals[$p->name]) ? $totals[$p->name]["IN"] : 0)}}</b></span></td>
-                                <td style="text-align:right"><span class="tablesaw-cell-content primary" style="color:red; font-size:18px;"><b>&nbsp;</b></span></td>
-
-                            @elseif($p->type == 'OUT')
-                                <td style="text-align:right"><span class="tablesaw-cell-content primary" style="color:green; font-size:18px;"><b>&nbsp;</b></span></td>
-                                <td style="text-align:right"><span class="tablesaw-cell-content primary" style="color:red; font-size:18px;"><b>{{formatPrice(isset($totals[$p->name]) ? $totals[$p->name]["OUT"] : 0)}}</b></span></td>
-                            @endif
-                        @else
-                            @if($p->type == 'ALL')
-
-                                <td style="text-align:right"><span class="tablesaw-cell-content primary" style="color:green; font-size:18px;"><b>{{formatPrice(isset($totals[$p->name]) ? $totals[$p->name]["IN"] : 0)}}</b></span></td>
-                                <td style="text-align:right"><span class="tablesaw-cell-content primary" style="color:red; font-size:18px;"><b>{{formatPrice(isset($totals[$p->name]) ? $totals[$p->name]["OUT"] : 0)}}</b></span></td>
-                            @elseif($p->type == 'IN')
-                                <td style="text-align:right"><span class="tablesaw-cell-content primary" style="color:green; font-size:18px;"><b>{{formatPrice(isset($totals[$p->name]) ? $totals[$p->name]["IN"] : 0)}}</b></span></td>
-                                <td style="text-align:center"><span class="tablesaw-cell-content primary" style="color:red; font-size:18px;"><b>&nbsp;</b></span></td>
-                            @elseif($p->type == 'OUT')
-                                <td style="text-align:right"><span class="tablesaw-cell-content primary" style="color:green; font-size:18px;"><b>&nbsp;</b></span></td>
-                                <td style="text-align:center"><span class="tablesaw-cell-content primary" style="color:red; font-size:18px;"><b>{{formatPrice(isset($totals[$p->name]) ? $totals[$p->name]["OUT"] : 0)}}</b></span></td>
-
-                            @endif
-                        @endif
-                    @endforeach
-                </tr>
-                <tr style="display:none">
-                    <td></td>
-                    <td><b>Differenza</b></td>
-                    @foreach($payments as $p)
-                        @if(isset($totals[$p->name]))
-                            @php
-                            $diff = $totals[$p->name]["IN"] - $totals[$p->name]["OUT"];
-                            @endphp
-                            @if($diff < 0)
-                                <td></td>
-                            @endif
-                            <td style="text-align:right"><span class="tablesaw-cell-content primary" style="color:{{$diff > 0 ? 'green' : 'red'}}; font-size:18px;"><b>{{formatPrice($diff)}}</b></span></td>
-                            @if($diff > 0)
-                                <td></td>
-                            @endif
-                        @else
-                            <td colspan="2" style="text-align:right"><b>{{formatPrice(0)}}</b></td>
-                        @endif
-                    @endforeach
-                </tr>
-            </tfoot>
+            @if($total_in > 0 || $total_out > 0)
+                <tfoot>
+                    <tr>
+                        <td colspan="5"><b>Totale</b></td>
+                        <td style="text-align:right;"><b>{{$total_in > 0 ? formatPrice($total_in) : ''}}</b></td>
+                        <td style="text-align:right;"><b>{{$total_out > 0 ? formatPrice($total_out) : ''}}</b></td>
+                        <td colspan="3"></td>
+                    </tr>
+                </tfoot>
+            @endif
         </table>
         <button type="button" class="btn btn-floating btn-lg" id="btn-back-to-bottom"><i class="fas fa-arrow-down"></i></button>
         <button type="button" class="btn btn-floating btn-lg" id="btn-back-to-top"><i class="fas fa-arrow-up"></i></button>
@@ -1852,7 +1766,8 @@
         function handleExportClick() {
             showExportLoading();
 
-            @this.call('exportWithDateRange');
+            @this.call('exportData');
+            //@this.call('exportWithDateRange');
         }
 
         function showExportLoading() {

+ 19 - 1
resources/views/livewire/records_in.blade.php

@@ -317,10 +317,11 @@
                         @else
 
                             <div class="row gx-2 mt-3">
-                                <span class="title-form d-block w-100">Metodo di pagamento</span>
+                                
 
                                 <div class="col-md-6" >
 
+                                    <span class="title-form d-block w-100">Metodo di pagamento</span>
                                     <select name="payment_method_id" class="form-select paymentClass @error('payment_method_id') is-invalid @enderror" aria-label="Seleziona un metodo di pagamento" wire:model="payment_method_id" style="width:100%"  {{$this->dataId > 0 && $deleted ? 'disabled' : ''}}>
                                         <option value="">--Seleziona--
                                         @foreach($payments as $payment)
@@ -330,6 +331,23 @@
                                     @error('payment_method_id')
                                         <div class="invalid-feedback">{{ $message }}</div>
                                     @enderror
+                                    
+                                </div>
+                            
+                                <div class="col-md-6" >
+
+                                    <span class="title-form d-block w-100">Destinazione</span>
+
+                                    <select name="destination_id" class="form-select  @error('destination_id') is-invalid @enderror" aria-label="Seleziona una destinazione" wire:model="destination_id" style="width:100%"  {{$this->dataId > 0 && $deleted ? 'disabled' : ''}}>
+                                        <option value="">--Seleziona--
+                                        @foreach($banks as $bank)
+                                            <option value="{{$bank->id}}">{{$bank->name}}
+                                        @endforeach
+                                    </select>
+                                    @error('destination_id')
+                                        <div class="invalid-feedback">{{ $message }}</div>
+                                    @enderror
+                                    
                                 </div>
                             </div>
 

+ 1974 - 0
resources/views/livewire/records_old.blade.php

@@ -0,0 +1,1974 @@
+
+<div class="col card--ui" id="card--dashboard">
+
+     <header id="title--section" style="display:none !important"  class="d-flex align-items-center justify-content-between">
+        <div class="title--section_name d-flex align-items-center justify-content-between">
+            <i class="ico--ui title_section utenti me-2"></i>
+            <h2 class="primary">Prima nota</h2>
+        </div>
+
+    </header>
+    <section id="subheader" class="">
+        <div class="row g-3">
+            <div class="col-md-3">
+                Utente
+                <select name="search_member_id" class="form-select filterMember" wire:model="filterMember">
+                    <option value="">--Seleziona--
+                    @foreach($members as $member)
+                        <option value="{{$member->id}}">{{$member->last_name}} {{$member->first_name}}
+                    @endforeach
+                </select>
+            </div>
+            <div class="col-md-4">
+                Causale
+                <select name="search_causal_id[]" class="form-select filterCausals me-2" multiple="multiple" wire:model="filterCausals">
+                    @foreach($causals as $causal)
+                        <option value="{{$causal["id"]}}">{!!$causal["name"]!!}
+                    @endforeach
+                </select>
+            </div>
+            <div class="col-md-3">
+                Periodo
+                <div class="col-12 mb-3">
+                    <select wire:model="selectedPeriod" class="form-select" @if($isFiltering) disabled @endif style="height: 43px!important;">
+                        <option value="OGGI">Oggi</option>
+                        <option value="IERI">Ieri</option>
+                        <option value="GIORNO_PERSONALIZZATO">Giorno Personalizzato</option>
+                        <option value="MESE CORRENTE">Mese Corrente</option>
+                        <option value="MESE PRECEDENTE">Mese Precedente</option>
+                        <option value="MESE_PERSONALIZZATO">Mese Personalizzato</option>
+                        <option value="ULTIMO TRIMESTRE">Ultimo Trimestre</option>
+                        <option value="ULTIMO QUADRIMESTRE">Ultimo Quadrimestre</option>
+                    </select>
+                </div>
+
+                @if($selectedPeriod === 'GIORNO_PERSONALIZZATO')
+                <div class="col-12 mb-2" wire:transition>
+                    <div class="day-picker-container position-relative">
+                        <div class="input-group">
+                            <input type="date"
+                                wire:model="selectedDay"
+                                class="form-control"
+                                style="height: 43px!important;"
+                                @if($isFiltering) disabled @endif>
+                        </div>
+
+                        @if($showDayPicker)
+                        <div class="day-picker-dropdown position-absolute bg-white border rounded shadow-lg p-3 mt-1"
+                            style="z-index: 1060; width: 100%; max-width: 350px;">
+                            <div class="d-flex justify-content-between align-items-center mb-3">
+                                <h6 class="mb-0 text-primary">
+                                    <i class="fa-regular fa-calendar me-2"></i>
+                                    Seleziona Giorno
+                                </h6>
+                                <button type="button"
+                                        class="btn-close btn-sm"
+                                        wire:click="toggleDayPicker"></button>
+                            </div>
+
+                            <div class="row g-2 mb-3">
+                                <div class="col-6">
+                                    <button type="button"
+                                            class="btn btn-sm btn-outline-primary w-100"
+                                            wire:click="selectToday">
+                                        <i class="fas fa-calendar-day me-1"></i>
+                                        Oggi
+                                    </button>
+                                </div>
+                                <div class="col-6">
+                                    <button type="button"
+                                            class="btn btn-sm btn-outline-secondary w-100"
+                                            wire:click="selectYesterday">
+                                        <i class="fas fa-step-backward me-1"></i>
+                                        Ieri
+                                    </button>
+                                </div>
+                            </div>
+
+                            <div class="mb-3">
+                                <label class="form-label small">Anno</label>
+                                <select wire:model="selectedYear" class="form-select form-select-sm">
+                                    @php
+                                        $currentYear = date('Y');
+                                        $selectedDayYear = $selectedDay ? substr($selectedDay, 0, 4) : $currentYear;
+                                    @endphp
+                                    @for($year = $currentYear - 3; $year <= $currentYear + 1; $year++)
+                                        <option value="{{ $year }}" {{ $year == $selectedDayYear ? 'selected' : '' }}>
+                                            {{ $year }}
+                                        </option>
+                                    @endfor
+                                </select>
+                            </div>
+
+                            <div class="mb-3">
+                                <label class="form-label small">Mese</label>
+                                <div class="row g-1">
+                                    @php
+                                        $months = [
+                                            '01' => 'Gen', '02' => 'Feb', '03' => 'Mar', '04' => 'Apr',
+                                            '05' => 'Mag', '06' => 'Giu', '07' => 'Lug', '08' => 'Ago',
+                                            '09' => 'Set', '10' => 'Ott', '11' => 'Nov', '12' => 'Dic'
+                                        ];
+                                        $currentMonth = $selectedDay ? substr($selectedDay, 5, 2) : date('m');
+                                        $currentYear = $selectedDay ? substr($selectedDay, 0, 4) : date('Y');
+                                    @endphp
+
+                                    @foreach($months as $monthNum => $monthName)
+                                        <div class="col-3">
+                                            <button type="button"
+                                                    class="btn btn-sm w-100 month-selector {{ $monthNum === $currentMonth ? 'btn-primary' : 'btn-outline-secondary' }}"
+                                                    data-month="{{ $monthNum }}">
+                                                {{ $monthName }}
+                                            </button>
+                                        </div>
+                                    @endforeach
+                                </div>
+                            </div>
+
+                            <div class="mb-3">
+                                <label class="form-label small">Giorno</label>
+                                <div class="day-grid" id="dayGrid">
+                                </div>
+                            </div>
+
+                            <div class="row g-2">
+                                <div class="col-6">
+                                    <button type="button"
+                                            class="btn btn-sm btn-success w-100"
+                                            id="confirmDaySelection">
+                                        <i class="fas fa-check me-1"></i>
+                                        Conferma
+                                    </button>
+                                </div>
+                                <div class="col-6">
+                                    <button type="button"
+                                            class="btn btn-sm btn-outline-secondary w-100"
+                                            wire:click="toggleDayPicker">
+                                        <i class="fas fa-times me-1"></i>
+                                        Annulla
+                                    </button>
+                                </div>
+                            </div>
+                        </div>
+                        @endif
+                    </div>
+                </div>
+
+                @if($selectedDay && $selectedPeriod === 'GIORNO_PERSONALIZZATO')
+                <div class="col-12 mb-2">
+                    <div class="alert alert-info py-2 px-3 mb-0" style="font-size: 0.875rem;">
+                        <i class="fas fa-info-circle me-1"></i>
+                        <strong>Giorno selezionato:</strong><br>
+                        {{ \Carbon\Carbon::createFromFormat('Y-m-d', $selectedDay)->locale('it')->isoFormat('dddd, D MMMM YYYY') }}
+                    </div>
+                </div>
+                @endif
+                @endif
+
+                @if($selectedPeriod === 'MESE_PERSONALIZZATO')
+                <div class="col-12 mb-2" wire:transition>
+                    <div class="month-picker-container position-relative">
+                        <div class="input-group">
+                            <input type="month"
+                                wire:model="selectedMonth"
+                                class="form-control"
+                                style="height: 43px!important;"
+                                @if($isFiltering) disabled @endif>
+                        </div>
+
+                        @if($showMonthPicker)
+                        <div class="month-picker-dropdown position-absolute bg-white border rounded shadow-lg p-3 mt-1"
+                            style="z-index: 1060; width: 100%; max-width: 300px;">
+                            <div class="d-flex justify-content-between align-items-center mb-3">
+                                <h6 class="mb-0 text-primary">
+                                    <i class="fa-regular fa-calendar me-2"></i>
+                                    Seleziona Mese
+                                </h6>
+                                <button type="button"
+                                        class="btn-close btn-sm"
+                                        wire:click="toggleMonthPicker"></button>
+                            </div>
+
+                            <div class="mb-3">
+                                <label class="form-label small">Anno</label>
+                                <select wire:model="selectedYear" class="form-select form-select-sm">
+                                    @php
+                                        $currentYear = date('Y');
+                                        $selectedYear = $selectedMonth ? substr($selectedMonth, 0, 4) : $currentYear;
+                                    @endphp
+                                    @for($year = $currentYear - 3; $year <= $currentYear + 1; $year++)
+                                        <option value="{{ $year }}" {{ $year == $selectedYear ? 'selected' : '' }}>
+                                            {{ $year }}
+                                        </option>
+                                    @endfor
+                                </select>
+                            </div>
+
+                            <div class="row g-1 mb-3">
+                                @php
+                                    $months = [
+                                        '01' => 'Gen', '02' => 'Feb', '03' => 'Mar', '04' => 'Apr',
+                                        '05' => 'Mag', '06' => 'Giu', '07' => 'Lug', '08' => 'Ago',
+                                        '09' => 'Set', '10' => 'Ott', '11' => 'Nov', '12' => 'Dic'
+                                    ];
+                                    $currentMonth = $selectedMonth ?: date('Y-m');
+                                @endphp
+
+                                @foreach($months as $monthNum => $monthName)
+                                    <div class="col-3">
+                                        <button type="button"
+                                                class="btn btn-sm w-100 {{ ($selectedYear . '-' . $monthNum) === $currentMonth ? 'btn-primary' : 'btn-outline-secondary' }}"
+                                                wire:click="selectMonth('{{ $selectedYear }}-{{ $monthNum }}')">
+                                            {{ $monthName }}
+                                        </button>
+                                    </div>
+                                @endforeach
+                            </div>
+
+                            <div class="row g-1">
+                                <div class="col-6">
+                                    <button type="button"
+                                            class="btn btn-sm btn-outline-primary w-100"
+                                            wire:click="selectMonth('{{ date('Y-m') }}')">
+                                        <i class="fas fa-calendar-day me-1"></i>
+                                        Questo Mese
+                                    </button>
+                                </div>
+                                <div class="col-6">
+                                    <button type="button"
+                                            class="btn btn-sm btn-outline-secondary w-100"
+                                            wire:click="selectMonth('{{ date('Y-m', strtotime('-1 month')) }}')">
+                                        <i class="fas fa-step-backward me-1"></i>
+                                        Mese Scorso
+                                    </button>
+                                </div>
+                            </div>
+                        </div>
+                        @endif
+                    </div>
+                </div>
+
+                @if($selectedMonth && $selectedPeriod === 'MESE_PERSONALIZZATO')
+                <div class="col-12 mb-2">
+                    <div class="alert alert-info py-2 px-3 mb-0" style="font-size: 0.875rem;">
+                        <i class="fas fa-info-circle me-1"></i>
+                        <strong>Periodo selezionato:</strong><br>
+                        {{ \Carbon\Carbon::createFromFormat('Y-m', $selectedMonth)->locale('it')->isoFormat('MMMM YYYY') }}
+                    </div>
+                </div>
+                @endif
+                @endif
+            </div>
+            <div class="col-md-2">
+                <div class="prima--nota_buttons ms-auto" style="float:right; margin-top:25px;">
+                    <button class="btn--ui primary" wire:click="applyFilters" style="margin-right:5px;" @if($isFiltering) disabled @endif>
+                        @if($isFiltering)
+                            <i class="fas fa-spinner fa-spin"></i> CARICAMENTO...
+                        @else
+                            FILTRA
+                        @endif
+                    </button>
+                    <button class="btn--ui lightGrey reset reset" style="margin-left:5px;color:#10172A;" wire:click="resetFilters" @if($isFiltering) disabled @endif>RESET</button>
+                </div>
+            </div>
+        </div>
+        {{-- Custom loader --}}
+        <div wire:loading>
+            <div class="custom_loader">
+                <i class="fas fa-spinner fa-spin"></i>
+            </div>
+        </div>
+
+        <style>
+            .custom_loader {
+                position: fixed;
+                top: 0;
+                left: 0;
+                right: 0;
+                bottom: 0;
+                display: flex;
+                flex-direction: column;
+                flex-wrap: nowrap;
+                align-content: center;
+                justify-content: center;
+                align-items: center;
+                padding: 10px;
+                background: #ffffff80;
+                z-index: 1000;
+            }
+            
+            .custom_loader i {
+                font-size: 50px;
+                color: #0c6197;
+            }
+        </style>
+        {{-- END Custom loader --}}
+        
+        <div style="float:left; margin-top:10px; margin-bottom:10px;">
+            <div class="dropdown">
+            <button class="btn--ui_outline light dropdown-toggle" type="button" id="exportDropdown" data-bs-toggle="dropdown" aria-expanded="false"
+            style="color:#10172A;" @if($isFiltering) disabled @endif>
+                ESPORTA
+            </button>
+            <ul class="dropdown-menu" aria-labelledby="exportDropdown">
+                <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>
+        </div>
+    </section>
+
+    <section id="resume-table" class="scrollTable records-table" style="position: relative;">
+
+        @if($isFiltering)
+            <div class="loading-overlay">
+                <div class="loading-content">
+                    <i class="fas fa-spinner fa-spin fa-3x"></i>
+                    <p>Caricamento dati in corso...</p>
+                </div>
+            </div>
+        @endif
+
+        <table class="table tablesaw tableHead tablesaw-stack" id="tablesaw-350" width="100%">
+            <thead>
+                <tr>
+                    <th scope="col">Data</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)
+                        <th colspan="2" scope="col" style="text-align:center; border-left:3px solid white;">{{$p->name}}</th>
+                    @endforeach
+                </tr>
+                <tr>
+                    <th scope="col"></th>
+                    <th scope="col" style="border-left:3px solid white;"></th>
+                    <th scope="col" style="border-left:3px solid white;"></th>
+                    <th scope="col" style="border-left:3px solid white;"></th>
+                    <th scope="col" style="border-left:3px solid white;"></th>
+                    @foreach($payments as $p)
+                        @if($p->type == 'ALL')
+                            <th scope="col" style="text-align:center; border-left:3px solid white;">Entrate</th>
+                            <th scope="col" style="text-align:center">Uscite</th>
+                        @elseif($p->type == 'IN')
+                            <th scope="col" style="text-align:center; border-left:3px solid white;">Entrate</th>
+                            <th scope="col" style="text-align:center;"></th>
+                        @elseif($p->type == 'OUT')
+                            <th style="border-left:3px solid white;"></th>
+                            <th scope="col" style="text-align:center;">Uscite</th>
+                        @endif
+                    @endforeach
+                </tr>
+            </thead>
+            <tbody id="checkall-target">
+                @php $count = 0; @endphp
+                @foreach($records as $causal => $record)
+                    <tr>
+                        @php
+                        $parts = explode("§", $causal);
+                        $d = $parts[0] ?? '';
+                        $c = $parts[1] ?? '';
+                        $n = $parts[2] ?? '';
+                        $det = $parts[3] ?? '';
+                        $del = $parts[4] ?? '';
+
+                        $detailParts = explode('|', $det);
+                        $isMultiple = count($detailParts) > 1;
+                        $displayDetail = $isMultiple ? 'Varie' : $det;
+                        @endphp
+                        <td style="background-color:{{$count % 2 == 0 ? 'white' : '#f2f4f7'}}">{{date("d/m/Y", strtotime($d))}}</td>
+                        <td style="border-left:3px solid white !important;background-color:{{$count % 2 == 0 ? 'white' : '#f2f4f7'}}">{{$c}}</td>
+                        <td style="border-left:3px solid white !important;background-color:{{$count % 2 == 0 ? 'white' : '#f2f4f7'}}">
+                            @if($isMultiple)
+                                <span class="varie-link" data-causals="{{implode('|', array_slice($detailParts, 1))}}" style="color: #0C6197; cursor: pointer; text-decoration: underline;">
+                                    {{$displayDetail}}
+                                </span>
+                            @else
+                                {{$displayDetail}}
+                            @endif
+                        </td>
+                        <td style="border-left:3px solid white !important;background-color:{{$count % 2 == 0 ? 'white' : '#f2f4f7'}}">
+                            @if($del == 'DELETED')
+                                <span style='color:red'>Annullata</span>
+                            @endif
+                        </td>
+                        <td style="border-left:3px solid white !important;background-color:{{$count % 2 == 0 ? 'white' : '#f2f4f7'}}">{{$n}}</td>
+                        @foreach($payments as $p)
+                            @if(isset($record[$p->name]))
+                                <td style="text-align:right; border-left:3px solid white !important;background-color:{{$count % 2 == 0 ? 'white' : '#f2f4f7'}}">
+                                    @if(isset($record[$p->name]["IN"]))
+                                        <span class="tablesaw-cell-content " style="color:green">{{formatPrice($record[$p->name]["IN"])}}</span>
+                                    @endif
+                                </td>
+                                <td style="text-align:right;background-color:{{$count % 2 == 0 ? 'white' : '#f2f4f7'}}">
+                                    @if(isset($record[$p->name]["OUT"]))
+                                        <span class="tablesaw-cell-content " style="color:red">{{formatPrice($record[$p->name]["OUT"])}}</span>
+                                    @endif
+                                </td>
+                            @else
+                                <td style="border-left:3px solid white !important;background-color:{{$count % 2 == 0 ? 'white' : '#f2f4f7'}}"></td>
+                                <td style="background-color:{{$count % 2 == 0 ? 'white' : '#f2f4f7'}}"></td>
+                            @endif
+                        @endforeach
+                    </tr>
+                    @php $count++; @endphp
+                @endforeach
+            </tbody>
+            <tfoot>
+                <tr>
+                    <td></td>
+                    <td></td>
+                    <td></td>
+                    <td></td>
+                    <td><b>Totale</b></td>
+                    @foreach($payments as $p)
+                        @if(isset($totals[$p->name]))
+                            @if($p->type == 'ALL')
+                                <td style="text-align:right"><span class="tablesaw-cell-content primary" style="color:green; font-size:18px;"><b>{{formatPrice(isset($totals[$p->name]) ? $totals[$p->name]["IN"] : 0)}}</b></span></td>
+                                <td style="text-align:right"><span class="tablesaw-cell-content primary" style="color:red; font-size:18px;"><b>{{formatPrice(isset($totals[$p->name]) ? $totals[$p->name]["OUT"] : 0)}}</b></span></td>
+                            @elseif($p->type == 'IN')
+                                <td style="text-align:right"><span class="tablesaw-cell-content primary" style="color:green; font-size:18px;"><b>{{formatPrice(isset($totals[$p->name]) ? $totals[$p->name]["IN"] : 0)}}</b></span></td>
+                                <td style="text-align:right"><span class="tablesaw-cell-content primary" style="color:red; font-size:18px;"><b>&nbsp;</b></span></td>
+
+                            @elseif($p->type == 'OUT')
+                                <td style="text-align:right"><span class="tablesaw-cell-content primary" style="color:green; font-size:18px;"><b>&nbsp;</b></span></td>
+                                <td style="text-align:right"><span class="tablesaw-cell-content primary" style="color:red; font-size:18px;"><b>{{formatPrice(isset($totals[$p->name]) ? $totals[$p->name]["OUT"] : 0)}}</b></span></td>
+                            @endif
+                        @else
+                            @if($p->type == 'ALL')
+
+                                <td style="text-align:right"><span class="tablesaw-cell-content primary" style="color:green; font-size:18px;"><b>{{formatPrice(isset($totals[$p->name]) ? $totals[$p->name]["IN"] : 0)}}</b></span></td>
+                                <td style="text-align:right"><span class="tablesaw-cell-content primary" style="color:red; font-size:18px;"><b>{{formatPrice(isset($totals[$p->name]) ? $totals[$p->name]["OUT"] : 0)}}</b></span></td>
+                            @elseif($p->type == 'IN')
+                                <td style="text-align:right"><span class="tablesaw-cell-content primary" style="color:green; font-size:18px;"><b>{{formatPrice(isset($totals[$p->name]) ? $totals[$p->name]["IN"] : 0)}}</b></span></td>
+                                <td style="text-align:center"><span class="tablesaw-cell-content primary" style="color:red; font-size:18px;"><b>&nbsp;</b></span></td>
+                            @elseif($p->type == 'OUT')
+                                <td style="text-align:right"><span class="tablesaw-cell-content primary" style="color:green; font-size:18px;"><b>&nbsp;</b></span></td>
+                                <td style="text-align:center"><span class="tablesaw-cell-content primary" style="color:red; font-size:18px;"><b>{{formatPrice(isset($totals[$p->name]) ? $totals[$p->name]["OUT"] : 0)}}</b></span></td>
+
+                            @endif
+                        @endif
+                    @endforeach
+                </tr>
+                <tr style="display:none">
+                    <td></td>
+                    <td><b>Differenza</b></td>
+                    @foreach($payments as $p)
+                        @if(isset($totals[$p->name]))
+                            @php
+                            $diff = $totals[$p->name]["IN"] - $totals[$p->name]["OUT"];
+                            @endphp
+                            @if($diff < 0)
+                                <td></td>
+                            @endif
+                            <td style="text-align:right"><span class="tablesaw-cell-content primary" style="color:{{$diff > 0 ? 'green' : 'red'}}; font-size:18px;"><b>{{formatPrice($diff)}}</b></span></td>
+                            @if($diff > 0)
+                                <td></td>
+                            @endif
+                        @else
+                            <td colspan="2" style="text-align:right"><b>{{formatPrice(0)}}</b></td>
+                        @endif
+                    @endforeach
+                </tr>
+            </tfoot>
+        </table>
+        <button type="button" class="btn btn-floating btn-lg" id="btn-back-to-bottom"><i class="fas fa-arrow-down"></i></button>
+        <button type="button" class="btn btn-floating btn-lg" id="btn-back-to-top"><i class="fas fa-arrow-up"></i></button>
+    </section>
+
+    <div class="modal fade" id="causalsModal" tabindex="-1" aria-labelledby="causalsModalLabel" aria-hidden="true">
+        <div class="modal-dialog modal-lg">
+            <div class="modal-content">
+                <div class="modal-header" style="background-color: #0C6197!important;">
+                    <h5 class="modal-title" id="causalsModalLabel">
+                        <i class="me-2"></i>
+                        Dettaglio Causali
+                    </h5>
+                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="CHIUDI"></button>
+                </div>
+                <div class="modal-body">
+                    <div class="row">
+                        <div class="col-12">
+                            <div class="d-flex justify-content-between align-items-center mb-3">
+                                <h6 class="mb-0">
+                                    <i class="me-2 text-primary"></i>
+                                    Causali incluse:
+                                </h6>
+                            </div>
+                            <div class="border rounded" style="max-height: 400px; overflow-y: auto;">
+                                <ul id="causalsList" class="list-group list-group-flush mb-0">
+                                    <!-- Causals will be populated here by JavaScript -->
+                                </ul>
+                            </div>
+                        </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">
+                        <i class="fas fa-times me-1"></i>
+                        CHIUDI
+                    </button>
+                </div>
+            </div>
+        </div>
+    </div>
+
+    <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>
+
+                @if(false)
+                    <div class="row mt-4">
+                        <div class="col-12">
+                            <div class="form-check export-method-check">
+                                <input class="form-check-input" type="checkbox" id="sendViaEmail" wire:model.defer="sendViaEmail">
+                                <label class="form-check-label" for="sendViaEmail">
+                                    <i class="fas fa-envelope me-2"></i>Invia via Email
+                                    <small class="d-block text-muted mt-1">L'export verrà elaborato in background e inviato alla tua email</small>
+                                </label>
+                            </div>
+                        </div>
+                    </div>
+                @endif
+
+                <div class="row mt-3" style="display: none;" id="emailAddressRow">
+                    <div class="col-12">
+                        <label for="exportEmailAddress" class="form-label">
+                            <i class="fas fa-envelope me-1"></i>Indirizzo Email
+                        </label>
+                        <input type="email" class="form-control" id="exportEmailAddress"
+                               wire:model.defer="exportEmailAddress"
+                               placeholder="inserisci@email.com">
+                        <div class="invalid-feedback" id="emailValidationFeedback">
+                            Inserisci un indirizzo email valido
+                        </div>
+                        <small class="form-text text-muted">
+                            Il file Excel verrà inviato a questo indirizzo
+                        </small>
+                    </div>
+                </div>
+
+                <div class="row mt-3" style="display: none;" id="emailSubjectRow">
+                    <div class="col-12">
+                        <label for="exportEmailSubject" class="form-label">
+                            <i class="fas fa-tag me-1"></i>Oggetto Email
+                        </label>
+                        <input type="text" class="form-control" id="exportEmailSubject"
+                               wire:model.defer="exportEmailSubject"
+                               placeholder="Prima Nota - Export">
+                        <small class="form-text text-muted">
+                            Personalizza l'oggetto dell'email
+                        </small>
+                    </div>
+                </div>
+
+                <div class="row mt-3">
+                    <div class="col-12">
+                        <div class="alert alert-info d-flex align-items-start">
+                            <i class="fas fa-info-circle me-2 mt-1"></i>
+                            <div>
+                                <strong>Informazioni Export:</strong>
+                                <ul class="mb-0 mt-1">
+                                    <li>L'export includerà tutti i record nel periodo selezionato</li>
+                                    <li>Verranno applicati i filtri attualmente attivi</li>
+                                    <li id="emailProcessingInfo" style="display: none;">L'elaborazione avverrà in background, potrai continuare a usare l'applicazione</li>
+                                </ul>
+                            </div>
+                        </div>
+                    </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" onclick="handleExportClick()" id="exportButton">
+                    <span id="loadingState" style="display: none;">
+                        <div class="spinner-border spinner-border-sm me-2" role="status">
+                            <span class="visually-hidden">Loading...</span>
+                        </div>
+                        ELABORAZIONE...
+                    </span>
+                    <span id="normalState">
+                        <i class="fas fa-download me-1"></i>
+                        ESPORTA
+                    </span>
+                </button>
+            </div>
+        </div>
+    </div>
+</div>
+
+<div class="toast-container position-fixed top-0 end-0 p-3" style="z-index: 11000;">
+    <!-- Toasts will be dynamically added here -->
+</div>
+</div>
+
+@push('scripts')
+    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
+@endpush
+
+@push('scripts')
+    <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
+    <style>
+        .loading-overlay {
+            position: absolute;
+            top: 0;
+            left: 0;
+            right: 0;
+            bottom: 0;
+            background-color: rgba(255, 255, 255, 0.9);
+            display: flex;
+            justify-content: center;
+            align-items: center;
+            z-index: 1000;
+            border-radius: 4px;
+        }
+
+        .loading-content {
+            text-align: center;
+            color: #0C6197;
+        }
+
+        .loading-content i {
+            margin-bottom: 15px;
+            color: #0C6197;
+        }
+
+        .loading-content p {
+            margin: 0;
+            font-size: 16px;
+            font-weight: 500;
+            color: #10172A;
+        }
+
+        .modal {
+            z-index: 9999 !important;
+        }
+
+        .modal-backdrop {
+            z-index: 9998 !important;
+            background-color: rgba(0, 0, 0, 0.6) !important;
+        }
+
+        .modal-content {
+            border-radius: 8px;
+            border: none;
+            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
+            z-index: 10000 !important;
+        }
+
+        .modal-header {
+            color: white;
+            border-bottom: none;
+            border-radius: 8px 8px 0 0;
+        }
+
+        .modal-header .btn-close {
+            filter: invert(1);
+        }
+
+        .modal-title {
+            font-weight: 600;
+        }
+
+        .varie-link:hover {
+            color: #084c6b !important;
+            text-decoration: underline !important;
+        }
+
+        #btn-back-to-top {
+            background-color: #0C6197;
+            color: white;
+            position: fixed;
+            display: none;
+        }
+
+        #btn-back-to-bottom {
+            background-color: #0C6197;
+            color: white;
+            position: fixed;
+            z-index: 9999;
+            display: none;
+        }
+
+        button[disabled] {
+            opacity: 0.7;
+            cursor: not-allowed;
+        }
+
+        .btn--ui .fa-spinner {
+            margin-right: 5px;
+        }
+
+        .scrollTable {
+            margin-left: 0px;
+            margin-right: 0px;
+            padding: 15px;
+            overflow-x: auto;
+            overflow-y: auto;
+            white-space: nowrap;
+            border: 1px solid #ddd;
+        }
+
+        ::-webkit-scrollbar-thumb {
+            background: #e4e4e4;
+            border-radius: 10px;
+        }
+
+        table thead {
+            position: sticky;
+            z-index: 100;
+            top: 0;
+        }
+
+        .select2-container--default .select2-selection--single {
+            background-color: #E9F0F5;
+            border: 0.0625rem solid #DFE5EB;
+            font-size: 0.75rem;
+            height: 38px !important;
+        }
+
+        .select2-selection__rendered {
+            padding-top: 3px;
+        }
+
+        .select2 {
+            width: 100% !important;
+        }
+
+        .select2-selection--multiple {
+            overflow: hidden !important;
+            height: auto !important;
+        }
+
+        .select2-container {
+            box-sizing: border-box;
+            display: inline-block;
+            margin: 0;
+            position: relative;
+            vertical-align: middle;
+            z-index: 999 !important;
+        }
+
+        .select2-dropdown {
+            z-index: 999 !important;
+        }
+
+        .select2-container .select2-selection--single {
+            box-sizing: border-box;
+            cursor: pointer;
+            display: block;
+            height: 38px;
+            user-select: none;
+            -webkit-user-select: none;
+        }
+
+        .select2-container .select2-selection--single .select2-selection__rendered {
+            display: block;
+            padding-left: 8px;
+            padding-right: 20px;
+            overflow: hidden;
+            text-overflow: ellipsis;
+            white-space: nowrap;
+        }
+
+        button#exportDropdown.btn--ui_outline.light {
+            font-weight: normal !important;
+        }
+
+        .btn--ui_outline.light.dropdown-toggle:active,
+        .btn--ui_outline.light.dropdown-toggle:focus,
+        .btn--ui_outline.light.dropdown-toggle.show {
+            background-color: transparent !important;
+            color: #10172A !important;
+            box-shadow: none !important;
+        }
+
+        .btn--ui_outline.light.dropdown-toggle:hover {
+            background-color: transparent !important;
+            color: #10172A !important;
+        }
+
+        .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;
+        }
+
+        .modal-dialog {
+            z-index: 10001 !important;
+            margin: 1.75rem auto;
+        }
+
+        .list-group-item {
+            border-left: none;
+            border-right: none;
+            border-top: 1px solid #dee2e6;
+            padding: 12px 15px;
+        }
+
+        .list-group-item:first-child {
+            border-top: none;
+        }
+
+        .list-group-item:last-child {
+            border-bottom: none;
+        }
+
+        @media (max-width: 768px) {
+            .col-md-2, .col-md-3, .col-md-4 {
+                margin-bottom: 10px;
+            }
+
+            .prima--nota_buttons {
+                float: none !important;
+                margin-top: 10px !important;
+                text-align: center;
+            }
+        }
+
+        .export-method-check {
+            padding: 16px 16px 16px 50px;
+            background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
+            border-radius: 8px;
+            border: 2px solid #e9ecef;
+            transition: all 0.3s ease;
+            cursor: pointer;
+            position: relative;
+        }
+
+        .export-method-check:hover {
+            border-color: #0C6197;
+            background: linear-gradient(135deg, #e8f4f8 0%, #d1ecf1 100%);
+        }
+
+        .export-method-check .form-check-input {
+            position: absolute;
+            left: 16px;
+            top: 50%;
+            transform: translateY(-50%);
+            margin: 0;
+            width: 20px;
+            height: 20px;
+            background-color: #fff;
+            border: 2px solid #dee2e6;
+            border-radius: 4px;
+            cursor: pointer;
+        }
+
+        .export-method-check .form-check-input:checked {
+            background-color: #0C6197;
+            border-color: #0C6197;
+        }
+
+        .export-method-check .form-check-input:checked ~ .form-check-label {
+            color: #0C6197;
+            font-weight: 600;
+        }
+
+        .export-method-check .form-check-label {
+            font-weight: 500;
+            color: #495057;
+            cursor: pointer;
+            margin-left: 0;
+            display: block;
+        }
+
+        .form-check-input:focus {
+            border-color: #0C6197;
+            outline: 0;
+            box-shadow: 0 0 0 0.2rem rgba(12, 97, 151, 0.25);
+        }
+        #emailAddressRow.show, #emailSubjectRow.show {
+            display: block !important;
+            animation: slideDown 0.3s ease-out;
+        }
+
+        @keyframes slideDown {
+            from {
+                opacity: 0;
+                transform: translateY(-10px);
+            }
+            to {
+                opacity: 1;
+                transform: translateY(0);
+            }
+        }
+
+        .invalid-feedback {
+            display: none;
+        }
+
+        .is-invalid ~ .invalid-feedback {
+            display: block;
+        }
+
+        .alert-info {
+            background-color: rgba(12, 97, 151, 0.1);
+            border-color: rgba(12, 97, 151, 0.2);
+            color: #0C6197;
+        }
+
+        .spinner-border-sm {
+            width: 1rem;
+            height: 1rem;
+        }
+
+        .toast {
+            min-width: 300px;
+        }
+
+        .toast-body {
+            font-weight: 500;
+        }
+
+        .btn--ui:disabled {
+            opacity: 0.7;
+            cursor: not-allowed;
+        }
+
+        .list-group-item {
+            border-left: none;
+            border-right: none;
+            border-top: 1px solid #dee2e6;
+            padding: 12px 15px;
+        }
+
+        .list-group-item:first-child {
+            border-top: none;
+        }
+
+        .list-group-item:last-child {
+            border-bottom: none;
+        }
+
+        .list-group-item.d-flex {
+            display: flex !important;
+            justify-content: space-between !important;
+            align-items: center !important;
+        }
+
+        .list-group-item .badge {
+            font-size: 0.875rem;
+            font-weight: 600;
+        }
+
+        .list-group-item:hover {
+            background-color: rgba(12, 97, 151, 0.05);
+            transition: background-color 0.2s ease;
+        }
+
+        #causalsModal .modal-body {
+            padding: 1rem 0;
+        }
+
+         .loading-overlay {
+            position: absolute;
+            top: 0;
+            left: 0;
+            right: 0;
+            bottom: 0;
+            background-color: rgba(255, 255, 255, 0.9);
+            display: flex;
+            justify-content: center;
+            align-items: center;
+            z-index: 1000;
+            border-radius: 4px;
+        }
+
+        /* New styles for Custom Day Picker */
+        .day-picker-container {
+            position: relative;
+        }
+
+        .day-picker-dropdown {
+            max-height: 600px;
+            overflow-y: auto;
+            border: 1px solid #dee2e6;
+            background: white;
+            border-radius: 8px;
+            box-shadow: 0 0.5rem 1rem rgba(0, 0, 0, 0.15);
+            z-index: 1060;
+            animation: slideDown 0.2s ease-out;
+            transform-origin: top;
+        }
+
+        .day-grid {
+            display: grid;
+            grid-template-columns: repeat(7, 1fr);
+            gap: 2px;
+            margin-bottom: 1rem;
+        }
+
+        .day-grid .day-header {
+            text-align: center;
+            font-weight: bold;
+            font-size: 0.75rem;
+            padding: 0.25rem;
+            background-color: #f8f9fa;
+            border-radius: 3px;
+            color: #6c757d;
+        }
+
+        .day-grid .day-button {
+            padding: 0.375rem 0.25rem;
+            font-size: 0.75rem;
+            border: 1px solid #dee2e6;
+            background: white;
+            border-radius: 4px;
+            cursor: pointer;
+            transition: all 0.15s ease-in-out;
+            text-align: center;
+            min-height: 32px;
+            display: flex;
+            align-items: center;
+            justify-content: center;
+        }
+
+        .day-grid .day-button:hover:not(.disabled) {
+            background-color: #e9ecef;
+            border-color: #0C6197;
+        }
+
+        .day-grid .day-button.selected {
+            background-color: #0C6197;
+            border-color: #0C6197;
+            color: white;
+        }
+
+        .day-grid .day-button.today {
+            border-color: #28a745;
+            font-weight: bold;
+        }
+
+        .day-grid .day-button.disabled {
+            color: #6c757d;
+            background-color: #f8f9fa;
+            cursor: not-allowed;
+            opacity: 0.5;
+        }
+
+        .day-grid .day-button.other-month {
+            color: #adb5bd;
+            background-color: #f8f9fa;
+        }
+
+        .month-selector.btn-primary {
+            background-color: #0C6197;
+            border-color: #0C6197;
+        }
+
+        .month-selector.btn-outline-secondary:hover {
+            background-color: #6c757d;
+            border-color: #6c757d;
+            color: white;
+        }
+
+        input[type="date"] {
+            background-color: #E9F0F5;
+            border: 0.0625rem solid #DFE5EB;
+            font-size: 0.75rem;
+        }
+
+        input[type="date"]:focus {
+            border-color: #0C6197;
+            box-shadow: 0 0 0 0.2rem rgba(12, 97, 151, 0.25);
+        }
+
+        input[type="date"]::-webkit-calendar-picker-indicator {
+            cursor: pointer;
+            opacity: 0.7;
+            transition: opacity 0.15s ease-in-out;
+        }
+
+        input[type="date"]::-webkit-calendar-picker-indicator:hover {
+            opacity: 1;
+        }
+
+        @media (max-width: 768px) {
+            .day-picker-dropdown {
+                width: 100% !important;
+                max-width: none !important;
+            }
+
+            .day-grid .day-button {
+                font-size: 0.7rem;
+                padding: 0.25rem;
+                min-height: 28px;
+            }
+        }
+
+        .month-picker-container {
+            position: relative;
+        }
+
+        .month-picker-dropdown {
+            max-height: 500px;
+            overflow-y: auto;
+            border: 1px solid #dee2e6;
+            background: white;
+            border-radius: 8px;
+            box-shadow: 0 0.5rem 1rem rgba(0, 0, 0, 0.15);
+            z-index: 1060;
+        }
+
+        .month-picker-dropdown .btn {
+            font-size: 0.75rem;
+            padding: 0.375rem 0.5rem;
+            border-radius: 4px;
+            transition: all 0.15s ease-in-out;
+        }
+
+        .month-picker-dropdown .btn-sm {
+            font-size: 0.875rem;
+            padding: 0.25rem 0.5rem;
+        }
+
+        .month-picker-dropdown .btn-close {
+            padding: 0.25rem;
+            font-size: 0.75rem;
+        }
+
+        .month-picker-dropdown .btn-primary {
+            background-color: #0C6197;
+            border-color: #0C6197;
+        }
+
+        .month-picker-dropdown .btn-outline-primary {
+            color: #0C6197;
+            border-color: #0C6197;
+        }
+
+        .month-picker-dropdown .btn-outline-primary:hover {
+            background-color: #0C6197;
+            border-color: #0C6197;
+        }
+
+        .month-picker-dropdown .btn-outline-secondary:hover {
+            background-color: #6c757d;
+            border-color: #6c757d;
+        }
+
+        input[type="month"] {
+            background-color: #E9F0F5;
+            border: 0.0625rem solid #DFE5EB;
+            font-size: 0.75rem;
+        }
+
+        input[type="month"]:focus {
+            border-color: #0C6197;
+            box-shadow: 0 0 0 0.2rem rgba(12, 97, 151, 0.25);
+        }
+
+        input[type="month"]::-webkit-calendar-picker-indicator {
+            cursor: pointer;
+            opacity: 0.7;
+            transition: opacity 0.15s ease-in-out;
+        }
+
+        input[type="month"]::-webkit-calendar-picker-indicator:hover {
+            opacity: 1;
+        }
+
+        .alert-info {
+            background-color: rgba(12, 97, 151, 0.1);
+            border-color: rgba(12, 97, 151, 0.2);
+            color: #0C6197;
+            border-radius: 6px;
+        }
+
+        .month-picker-dropdown {
+            animation: slideDown 0.2s ease-out;
+            transform-origin: top;
+        }
+
+        @keyframes slideDown {
+            from {
+                opacity: 0;
+                transform: translateY(-10px) scaleY(0.8);
+            }
+            to {
+                opacity: 1;
+                transform: translateY(0) scaleY(1);
+            }
+        }
+
+        @media (max-width: 768px) {
+            .month-picker-dropdown {
+                width: 100% !important;
+                max-width: none !important;
+            }
+
+            .month-picker-dropdown .row.g-1 .col-3 {
+                flex: 0 0 25%;
+                max-width: 25%;
+            }
+        }
+
+        [wire\:transition] {
+            transition: all 0.3s ease-in-out;
+        }
+
+        .select2-container {
+            z-index: 999 !important;
+        }
+
+        .select2-dropdown {
+            z-index: 999 !important;
+        }
+
+        .month-picker-dropdown {
+            z-index: 1060 !important;
+        }
+
+        .month-picker-dropdown .btn-group-sm .btn {
+            padding: 0.25rem 0.5rem;
+            font-size: 0.75rem;
+        }
+
+        .month-picker-container .form-label {
+            font-weight: 600;
+            color: #10172A;
+            margin-bottom: 0.5rem;
+        }
+
+        .month-picker-container .input-group .btn {
+            border-left: 0;
+            background-color: #f8f9fa;
+            border-color: #DFE5EB;
+            color: #6c757d;
+        }
+
+        .month-picker-container .input-group .btn:hover {
+            background-color: #e9ecef;
+            color: #0C6197;
+        }
+
+    </style>
+    <script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>
+    <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
+    <script src="/assets/js/aCollapTable.js"></script>
+@endpush
+
+@push('scripts')
+    <script>
+         let selectedDayValue = '';
+        let currentDisplayMonth = '';
+        let currentDisplayYear = '';
+
+        function initializeDayPicker() {
+            const today = new Date();
+            const selectedDay = @this.get('selectedDay');
+
+            if (selectedDay) {
+                selectedDayValue = selectedDay;
+                const selectedDate = new Date(selectedDay);
+                currentDisplayMonth = String(selectedDate.getMonth() + 1).padStart(2, '0');
+                currentDisplayYear = String(selectedDate.getFullYear());
+            } else {
+                currentDisplayMonth = String(today.getMonth() + 1).padStart(2, '0');
+                currentDisplayYear = String(today.getFullYear());
+            }
+
+            updateDayGrid();
+        }
+
+        function updateDayGrid() {
+            const dayGrid = document.getElementById('dayGrid');
+            if (!dayGrid) return;
+
+            const year = parseInt(currentDisplayYear);
+            const month = parseInt(currentDisplayMonth);
+            const today = new Date();
+            const selectedDate = selectedDayValue ? new Date(selectedDayValue) : null;
+
+            dayGrid.innerHTML = '';
+
+            const dayHeaders = ['Dom', 'Lun', 'Mar', 'Mer', 'Gio', 'Ven', 'Sab'];
+            dayHeaders.forEach(header => {
+                const headerDiv = document.createElement('div');
+                headerDiv.className = 'day-header';
+                headerDiv.textContent = header;
+                dayGrid.appendChild(headerDiv);
+            });
+
+            const firstDay = new Date(year, month - 1, 1);
+            const lastDay = new Date(year, month, 0);
+            const startDate = new Date(firstDay);
+            startDate.setDate(startDate.getDate() - firstDay.getDay());
+
+            for (let i = 0; i < 42; i++) {
+                const currentDate = new Date(startDate);
+                currentDate.setDate(startDate.getDate() + i);
+
+                const dayButton = document.createElement('button');
+                dayButton.type = 'button';
+                dayButton.className = 'day-button';
+                dayButton.textContent = currentDate.getDate();
+
+                const isCurrentMonth = currentDate.getMonth() === month - 1;
+                const isToday = currentDate.toDateString() === today.toDateString();
+                const isSelected = selectedDate && currentDate.toDateString() === selectedDate.toDateString();
+
+                if (!isCurrentMonth) {
+                    dayButton.classList.add('other-month');
+                }
+
+                if (isToday) {
+                    dayButton.classList.add('today');
+                }
+
+                if (isSelected) {
+                    dayButton.classList.add('selected');
+                }
+
+                const dateString = currentDate.getFullYear() + '-' +
+                                 String(currentDate.getMonth() + 1).padStart(2, '0') + '-' +
+                                 String(currentDate.getDate()).padStart(2, '0');
+
+                dayButton.addEventListener('click', function() {
+                    document.querySelectorAll('.day-button.selected').forEach(btn => {
+                        btn.classList.remove('selected');
+                    });
+
+                    this.classList.add('selected');
+                    selectedDayValue = dateString;
+                });
+
+                dayGrid.appendChild(dayButton);
+            }
+        }
+
+        document.addEventListener('click', function(event) {
+            if (event.target.classList.contains('month-selector')) {
+                const month = event.target.getAttribute('data-month');
+                currentDisplayMonth = month;
+
+                document.querySelectorAll('.month-selector').forEach(btn => {
+                    btn.classList.remove('btn-primary');
+                    btn.classList.add('btn-outline-secondary');
+                });
+                event.target.classList.remove('btn-outline-secondary');
+                event.target.classList.add('btn-primary');
+
+                updateDayGrid();
+            }
+        });
+
+        document.addEventListener('click', function(event) {
+            if (event.target.id === 'confirmDaySelection') {
+                if (selectedDayValue) {
+                    @this.call('selectDay', selectedDayValue);
+                }
+            }
+        });
+
+        document.addEventListener('click', function(event) {
+            const dayPicker = document.querySelector('.day-picker-dropdown');
+            const dayPickerContainer = document.querySelector('.day-picker-container');
+
+            if (dayPicker && dayPickerContainer && !dayPickerContainer.contains(event.target)) {
+                @this.set('showDayPicker', false);
+            }
+        });
+
+        document.addEventListener('livewire:updated', function() {
+            const dayPicker = document.querySelector('.day-picker-dropdown');
+            if (dayPicker) {
+                initializeDayPicker();
+            }
+        });
+
+        function closeSelect2Dropdowns() {
+            $('.filterCausals').each(function() {
+                if ($(this).hasClass('select2-hidden-accessible')) {
+                    $(this).select2('close');
+                }
+            });
+            $('.filterMember').each(function() {
+                if ($(this).hasClass('select2-hidden-accessible')) {
+                    $(this).select2('close');
+                }
+            });
+        }
+
+        function load() {
+            $(document).ready(function(){
+                $(document).on("keypress", $('.filterCausals'), function (e) {
+                    setTimeout(() => {
+                        $(".select2-results__option").each(function(){
+                            var txt = $(this).html();
+                            var count = (txt.match(/-/g) || []).length;
+                            $(this).addClass('paddingLeftSelect' + count);
+                        });
+                    }, 100);
+                });
+
+                if (!$('.filterCausals').hasClass('select2-hidden-accessible')) {
+                    $('.filterCausals').select2({
+                        "language": {"noResults": function(){return "Nessun risultato";}},
+                        "dropdownParent": $('body'),
+                        "width": "100%"
+                    });
+                }
+
+                $('.filterCausals').off('change.customHandler').on('change.customHandler', function (e) {
+                    var data = $('.filterCausals').select2("val");
+                    @this.set('filterCausals', data);
+                });
+
+                $('.filterCausals').off('select2:open.customHandler').on('select2:open.customHandler', function (e) {
+                    if ($('#causalsModal').hasClass('show')) {
+                        $('#causalsModal').modal('hide');
+                    }
+
+                    setTimeout(() => {
+                        $(".select2-results__option").each(function(){
+                            var txt = $(this).html();
+                            var count = (txt.match(/-/g) || []).length;
+                            $(this).addClass('paddingLeftSelect' + count);
+                        });
+                    }, 100);
+                });
+
+                if (!$('.filterMember').hasClass('select2-hidden-accessible')) {
+                    $('.filterMember').select2({
+                        "language": {"noResults": function(){return "Nessun risultato";}},
+                        "dropdownParent": $('body'),
+                        "width": "100%"
+                    });
+                }
+
+                $('.filterMember').off('change.customHandler').on('change.customHandler', function (e) {
+                    var data = $('.filterMember').select2("val");
+                    @this.set('filterMember', data);
+                });
+
+                $('.filterMember').off('select2:open.customHandler').on('select2:open.customHandler', function (e) {
+                    if ($('#causalsModal').hasClass('show')) {
+                        $('#causalsModal').modal('hide');
+                    }
+                });
+            });
+        }
+
+        function printData() {
+            var divToPrint = document.getElementById("tablesaw-350");
+            newWin = window.open("");
+            var htmlToPrint = '' +
+                '<style type="text/css">' +
+                'table th, table td {' +
+                'border:1px solid #000;' +
+                'padding:0.5em;' +
+                '}' +
+                '</style>';
+            htmlToPrint += divToPrint.outerHTML;
+            newWin.document.write(htmlToPrint);
+            newWin.document.close();
+            newWin.print();
+            newWin.close();
+        }
+
+        function scrollFunction() {
+            const element = document.getElementById('resume-table');
+            const mybuttonBottom = document.getElementById("btn-back-to-bottom");
+            const mybutton = document.getElementById("btn-back-to-top");
+
+            if (element.scrollTop > 20) {
+                mybutton.style.display = "block";
+                mybuttonBottom.style.display = "block";
+            } else {
+                mybutton.style.display = "none";
+                mybuttonBottom.style.display = "none";
+            }
+        }
+
+        function backToTop() {
+            $('#resume-table').scrollTop(0);
+        }
+
+        function backToBottom() {
+            $('#resume-table').scrollTop($('#resume-table')[0].scrollHeight);
+        }
+
+        $(document).ready(function() {
+            load();
+
+            document.querySelector("#print").addEventListener("click", function(){
+                printData();
+            });
+
+            const element = document.getElementById('resume-table');
+            element.onscroll = scrollFunction;
+
+            const mybuttonBottom = document.getElementById("btn-back-to-bottom");
+            const mybutton = document.getElementById("btn-back-to-top");
+
+            mybutton.addEventListener("click", backToTop);
+            mybuttonBottom.addEventListener("click", backToBottom);
+
+            $(document).on('click', '.varie-link', function(e) {
+                e.preventDefault();
+                e.stopPropagation();
+
+                closeSelect2Dropdowns();
+
+                const causalsData = $(this).data('causals');
+
+                if (causalsData) {
+                    const causals = causalsData.split('|');
+
+                    $('#causalsList').empty();
+
+                    causals.forEach(function(causal) {
+                        if (causal.trim()) {
+                            if (causal.includes(':::')) {
+                                const parts = causal.split(':::');
+                                const causalName = parts[0].trim();
+                                const amount = parts[1].trim();
+
+                                $('#causalsList').append(
+                                    '<li class="list-group-item d-flex justify-content-between align-items-center">' +
+                                    '<div>' +
+                                    '<i class="fas fa-tags me-2" style="color: #0C6197;"></i>' +
+                                    causalName +
+                                    '</div>' +
+                                    '<span class="badge bg-primary rounded-pill" style="background-color: #0C6197 !important;">' +
+                                    amount +
+                                    '</span>' +
+                                    '</li>'
+                                );
+                            } else {
+                                $('#causalsList').append(
+                                    '<li class="list-group-item">' +
+                                    '<i class="fas fa-tags me-2" style="color: #0C6197;"></i>' +
+                                    causal.trim() +
+                                    '</li>'
+                                );
+                            }
+                        }
+                    });
+
+                    $('#causalsModal').modal('show');
+
+                    $('#causalsModal').on('shown.bs.modal', function () {
+                        $(this).find('.btn-close').focus();
+                    });
+                }
+            });
+        });
+        Livewire.on('load-table', () => {
+            load();
+        });
+
+        Livewire.on('load-select', () => {
+            load();
+        });
+
+        Livewire.on('filters-reset', () => {
+            $('.filterMember').val('').trigger('change');
+            $('.filterCausals').val('').trigger('change');
+            load();
+        });
+
+        Livewire.on('show-export-modal', () => {
+            $('#exportModal').modal('show');
+        });
+
+        Livewire.on('hide-export-modal', () => {
+            $('#exportModal').modal('hide');
+        });
+
+        function showToast(type, message, duration = 5000) {
+            const toastContainer = document.querySelector('.toast-container');
+            if (!toastContainer) {
+                console.error('Toast container not found');
+                return;
+            }
+
+            const toastId = 'toast-' + Date.now();
+
+            const toastColors = {
+                success: 'bg-success',
+                error: 'bg-danger',
+                warning: 'bg-warning',
+                info: 'bg-info'
+            };
+
+            const toastIcons = {
+                success: 'fa-check-circle',
+                error: 'fa-exclamation-circle',
+                warning: 'fa-exclamation-triangle',
+                info: 'fa-info-circle'
+            };
+
+            const toast = document.createElement('div');
+            toast.id = toastId;
+            toast.className = `toast align-items-center text-white ${toastColors[type]} border-0`;
+            toast.setAttribute('role', 'alert');
+            toast.innerHTML = `
+                <div class="d-flex">
+                    <div class="toast-body">
+                        <i class="fas ${toastIcons[type]} me-2"></i>
+                        ${message}
+                    </div>
+                    <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast"></button>
+                </div>
+            `;
+
+            toastContainer.appendChild(toast);
+
+            if (typeof bootstrap !== 'undefined') {
+                const bsToast = new bootstrap.Toast(toast, { delay: duration });
+                bsToast.show();
+
+                toast.addEventListener('hidden.bs.toast', function() {
+                    if (toastContainer.contains(toast)) {
+                        toastContainer.removeChild(toast);
+                    }
+                });
+
+                return bsToast;
+            } else {
+                toast.style.display = 'block';
+                setTimeout(() => {
+                    if (toastContainer.contains(toast)) {
+                        toastContainer.removeChild(toast);
+                    }
+                }, duration);
+            }
+        }
+
+        document.addEventListener('DOMContentLoaded', function() {
+            const sendViaEmailCheckbox = document.getElementById('sendViaEmail');
+            const emailAddressRow = document.getElementById('emailAddressRow');
+            const emailSubjectRow = document.getElementById('emailSubjectRow');
+            const emailProcessingInfo = document.getElementById('emailProcessingInfo');
+            const exportIcon = document.getElementById('exportIcon');
+            const exportButtonText = document.getElementById('exportButtonText');
+            const emailInput = document.getElementById('exportEmailAddress');
+
+            function toggleEmailFields() {
+                if (sendViaEmailCheckbox && sendViaEmailCheckbox.checked) {
+                    if (emailAddressRow) {
+                        emailAddressRow.style.display = 'block';
+                        emailAddressRow.classList.add('show');
+                    }
+                    if (emailSubjectRow) {
+                        emailSubjectRow.style.display = 'block';
+                        emailSubjectRow.classList.add('show');
+                    }
+                    if (emailProcessingInfo) {
+                        emailProcessingInfo.style.display = 'list-item';
+                    }
+
+                    if (exportIcon) exportIcon.className = 'fas fa-paper-plane me-1';
+                    if (exportButtonText) exportButtonText.textContent = 'INVIA EMAIL';
+                } else {
+                    if (emailAddressRow) {
+                        emailAddressRow.style.display = 'none';
+                        emailAddressRow.classList.remove('show');
+                    }
+                    if (emailSubjectRow) {
+                        emailSubjectRow.style.display = 'none';
+                        emailSubjectRow.classList.remove('show');
+                    }
+                    if (emailProcessingInfo) {
+                        emailProcessingInfo.style.display = 'none';
+                    }
+
+                    if (exportIcon) exportIcon.className = 'fas fa-download me-1';
+                    if (exportButtonText) exportButtonText.textContent = 'ESPORTA';
+                }
+            }
+
+            function validateEmail(email) {
+                const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
+                return emailRegex.test(email);
+            }
+
+            if (sendViaEmailCheckbox) {
+                sendViaEmailCheckbox.addEventListener('change', toggleEmailFields);
+            }
+
+            if (emailInput) {
+                emailInput.addEventListener('blur', function() {
+                    if (sendViaEmailCheckbox && sendViaEmailCheckbox.checked && this.value) {
+                        if (validateEmail(this.value)) {
+                            this.classList.remove('is-invalid');
+                            this.classList.add('is-valid');
+                        } else {
+                            this.classList.remove('is-valid');
+                            this.classList.add('is-invalid');
+                        }
+                    }
+                });
+
+                emailInput.addEventListener('input', function() {
+                    this.classList.remove('is-invalid', 'is-valid');
+                });
+            }
+
+            if (typeof $ !== 'undefined') {
+                $('#exportModal').on('shown.bs.modal', function() {
+                    toggleEmailFields();
+                });
+            }
+        });
+
+        document.addEventListener('livewire:load', function () {
+            console.log('Livewire loaded, setting up export event listeners');
+
+            Livewire.on('export-email-queued', function() {
+                console.log('Export email queued event received');
+                showToast('info',
+                    '<strong>Export avviato!</strong><br>' +
+                    'L\'elaborazione è in corso in background. Riceverai l\'email a breve.',
+                    8000
+                );
+            });
+
+            Livewire.on('export-email-sent', function() {
+                console.log('Export email sent event received');
+                showToast('success',
+                    '<strong>Email inviata!</strong><br>' +
+                    'L\'export è stato completato e inviato alla tua email.',
+                    6000
+                );
+            });
+
+            Livewire.on('export-email-error', function(message) {
+                console.log('Export email error event received:', message);
+                showToast('error',
+                    '<strong>Errore nell\'export:</strong><br>' +
+                    (message || 'Si è verificato un errore durante l\'elaborazione.'),
+                    10000
+                );
+            });
+
+            Livewire.on('show-export-modal', function() {
+                console.log('Show export modal event received');
+                if (typeof $ !== 'undefined') {
+                    $('#exportModal').modal('show');
+                }
+            });
+
+            Livewire.on('hide-export-modal', function() {
+                console.log('Hide export modal event received');
+                if (typeof $ !== 'undefined') {
+                    $('#exportModal').modal('hide');
+                }
+            });
+        });
+
+        if (typeof Livewire !== 'undefined') {
+            document.addEventListener('livewire:initialized', function () {
+                console.log('Livewire initialized, setting up export event listeners');
+
+                Livewire.on('export-email-queued', function() {
+                    showToast('info',
+                        '<strong>Export avviato!</strong><br>' +
+                        'L\'elaborazione è in corso in background. Riceverai l\'email a breve.',
+                        8000
+                    );
+                });
+
+                Livewire.on('export-email-sent', function() {
+                    showToast('success',
+                        '<strong>Email inviata!</strong><br>' +
+                        'L\'export è stato completato e inviato alla tua email.',
+                        6000
+                    );
+                });
+
+                Livewire.on('export-email-error', function(message) {
+                    showToast('error',
+                        '<strong>Errore nell\'export:</strong><br>' +
+                        (message || 'Si è verificato un errore durante l\'elaborazione.'),
+                        10000
+                    );
+                });
+
+                Livewire.on('show-export-modal', function() {
+                    if (typeof $ !== 'undefined') {
+                        $('#exportModal').modal('show');
+                    }
+                });
+
+                Livewire.on('hide-export-modal', function() {
+                    if (typeof $ !== 'undefined') {
+                        $('#exportModal').modal('hide');
+                    }
+                });
+            });
+        }
+
+        window.addEventListener('load', function() {
+            if (typeof showToast === 'function') {
+                console.log('showToast function is available globally');
+            } else {
+                console.error('showToast function is not available globally');
+            }
+        });
+
+
+        function handleExportClick() {
+            showExportLoading();
+
+            @this.call('exportWithDateRange');
+        }
+
+        function showExportLoading() {
+            document.getElementById('normalState').style.display = 'none';
+            document.getElementById('loadingState').style.display = 'inline-flex';
+            document.getElementById('exportButton').disabled = true;
+        }
+
+        function hideExportLoading() {
+            document.getElementById('normalState').style.display = 'inline-flex';
+            document.getElementById('loadingState').style.display = 'none';
+            document.getElementById('exportButton').disabled = false;
+        }
+
+        Livewire.on('export-complete', function() {
+            hideExportLoading();
+        });
+
+        Livewire.on('hide-export-modal', function() {
+            hideExportLoading();
+        });
+
+        function setupSimpleExportListeners() {
+            if (typeof Livewire !== 'undefined') {
+                Livewire.on('export-email-queued', function() {
+                    setTimeout(() => {
+                        hideExportLoading();
+                        $('#exportModal').modal('hide');
+
+                        showToast('success',
+                            '<i class="fas fa-paper-plane me-2"></i>' +
+                            '<strong>Export avviato!</strong><br>' +
+                            'Riceverai l\'email a breve.',
+                            6000
+                        );
+                    }, 1500);
+                });
+
+                Livewire.on('export-complete', function() {
+                    hideExportLoading();
+                });
+
+                Livewire.on('hide-export-modal', function() {
+                    hideExportLoading();
+                    $('#exportModal').modal('hide');
+                });
+            }
+        }
+        document.addEventListener('DOMContentLoaded', function() {
+            document.addEventListener('click', function(event) {
+                const monthPicker = document.querySelector('.month-picker-dropdown');
+                const monthPickerContainer = document.querySelector('.month-picker-container');
+
+                if (monthPicker && monthPickerContainer && !monthPickerContainer.contains(event.target)) {
+                    if (typeof @this !== 'undefined') {
+                        @this.set('showMonthPicker', false);
+                    }
+                }
+            });
+
+            document.addEventListener('keydown', function(event) {
+                if (event.key === 'Escape') {
+                    if (typeof @this !== 'undefined') {
+                        @this.set('showMonthPicker', false);
+                    }
+                }
+            });
+
+            document.addEventListener('click', function(event) {
+                const monthPickerDropdown = event.target.closest('.month-picker-dropdown');
+                if (monthPickerDropdown) {
+                    event.stopPropagation();
+                }
+            });
+        });
+
+        function resetFiltersWithMonthPicker() {
+            $('.filterMember').val('').trigger('change');
+            $('.filterCausals').val('').trigger('change');
+
+            if (typeof @this !== 'undefined') {
+                @this.call('resetFilters');
+            }
+
+            load();
+        }
+
+        if (typeof Livewire !== 'undefined') {
+            Livewire.on('filters-applied', function() {
+                console.log('Filters applied with month picker');
+            });
+
+            Livewire.on('filters-reset', function() {
+                console.log('Filters reset including month picker');
+                load();
+            });
+        }
+
+        function initializeMonthPicker() {
+            const monthPickerDropdown = document.querySelector('.month-picker-dropdown');
+            if (monthPickerDropdown) {
+                monthPickerDropdown.style.opacity = '0';
+                monthPickerDropdown.style.transform = 'translateY(-10px)';
+
+                setTimeout(() => {
+                    monthPickerDropdown.style.transition = 'all 0.2s ease-out';
+                    monthPickerDropdown.style.opacity = '1';
+                    monthPickerDropdown.style.transform = 'translateY(0)';
+                }, 10);
+            }
+        }
+
+        document.addEventListener('livewire:updated', function() {
+            initializeMonthPicker();
+        });
+    </script>
+@endpush

+ 27 - 12
resources/views/livewire/records_out.blade.php

@@ -234,18 +234,33 @@
                         </div>
 
                         <div class="row gx-2 mt-5">
-                            <span class="title-form d-block w-100">Metodo di pagamento</span>
-
-                            <div class="col-md-12">
-                                <select name="payment_method_id" class="form-select paymentClass @error('payment_method_id') is-invalid @enderror" aria-label="Seleziona un metodo di pagamento" wire:model="payment_method_id">
-                                    <option value="">--Seleziona--
-                                    @foreach($payments as $payment)
-                                        <option value="{{$payment->id}}">{{$payment->name}}
-                                    @endforeach
-                                </select>
-                                @error('payment_method_id')
-                                    <div class="invalid-feedback">{{ $message }}</div>
-                                @enderror
+                            <div class="col-6">
+                                <span class="title-form d-block w-100">Metodo di pagamento</span>
+                                <div class="col-md-12">
+                                    <select name="payment_method_id" class="form-select paymentClass @error('payment_method_id') is-invalid @enderror" aria-label="Seleziona un metodo di pagamento" wire:model="payment_method_id">
+                                        <option value="">--Seleziona--
+                                        @foreach($payments as $payment)
+                                            <option value="{{$payment->id}}">{{$payment->name}}
+                                        @endforeach
+                                    </select>
+                                    @error('payment_method_id')
+                                        <div class="invalid-feedback">{{ $message }}</div>
+                                    @enderror
+                                </div>
+                            </div>
+                            <div class="col-6">
+                                <span class="title-form d-block w-100">Origine</span>
+                                <div class="col-md-12">
+                                    <select name="origin_id" class="form-select" aria-label="Seleziona un origine" wire:model="origin_id">
+                                        <option value="">--Seleziona--
+                                        @foreach($banks as $bank)
+                                            <option value="{{$bank->id}}">{{$bank->name}}
+                                        @endforeach
+                                    </select>
+                                    @error('origin_id')
+                                        <div class="invalid-feedback">{{ $message }}</div>
+                                    @enderror
+                                </div>
                             </div>
                         </div>
 

+ 1 - 1
resources/views/livewire/settings.blade.php

@@ -115,7 +115,7 @@
             <div id="contabilita">
                 <a href="/banks">
                     <div class="row">
-                        <div class="col-md-11 p-2"><h5>Banche</h5></div>
+                        <div class="col-md-11 p-2"><h5>Canali finanziari</h5></div>
                         <div class="col-md-1 p-2"><i class="fa-solid fa-chevron-right"></i></div>
                     </div>
                 </a>

+ 33 - 24
routes/web.php

@@ -81,6 +81,7 @@ Route::group(['middleware' => 'auth'], function () {
     Route::get('/suppliers', \App\Http\Livewire\Supplier::class);
     Route::get('/sponsors', \App\Http\Livewire\Sponsor::class);
     Route::get('/records', \App\Http\Livewire\Record::class);
+    Route::get('/records_old', \App\Http\Livewire\RecordOld::class);
     Route::get('/reminders', \App\Http\Livewire\Reminder::class);
     Route::get('/in', \App\Http\Livewire\RecordIN::class);
     Route::get('/out', \App\Http\Livewire\RecordOUT::class);
@@ -1759,36 +1760,44 @@ Route::get('/send_sms', function () {
     $expire_date_it = date("d/m/Y", strtotime("+1 month"));
     $certificates = \App\Models\MemberCertificate::where('expire_date', $expire_date)->get();
     foreach ($certificates as $certificate) {
-        $phone = $certificate->member->phone;
-        $message = 'Ciao ' . $certificate->member->first_name . ', ci risulta che il tuo certificato medico scade il ' . $expire_date_it . '. Per continuare ad allenarti senza problemi, ricordati di rinnovarlo in tempo. Ti aspettiamo in campo! Centro Sportivo La Madonnella';
-        $params = array(
-            'to'            => '+39' . $phone,
-            'from'          => env('SMS_FROM', 'Test'),
-            'message'       => $message,
-            'format'        => 'json',
-        );
-        $r = sms_send($params);
-        Log::info("SMS");
-        Log::info($r);
-        sleep(1);
+        $new = \App\Models\MemberCertificate::where('expire_date', '>', $expire_date)->count();
+        if ($new == 0)
+        {
+            $phone = $certificate->member->phone;
+            $message = 'Ciao ' . $certificate->member->first_name . ', ci risulta che il tuo certificato medico scade il ' . $expire_date_it . '. Per continuare ad allenarti senza problemi, ricordati di rinnovarlo in tempo. Ti aspettiamo in campo! Centro Sportivo La Madonnella';
+            $params = array(
+                'to'            => '+39' . $phone,
+                'from'          => env('SMS_FROM', 'Test'),
+                'message'       => $message,
+                'format'        => 'json',
+            );
+            $r = sms_send($params);
+            Log::info("SMS");
+            Log::info($r);
+            sleep(1);
+        }
     }
 
     $expire_date = date("Y-m-d", strtotime("+15 days"));
     $expire_date_it = date("d/m/Y", strtotime("+15 days"));
     $certificates = \App\Models\MemberCertificate::where('expire_date', $expire_date)->get();
     foreach ($certificates as $certificate) {
-        $phone = $certificate->member->phone;
-        $message = 'Ciao ' . $certificate->member->first_name . ', ci risulta che il tuo certificato medico scade il ' . $expire_date_it . '. Per continuare ad allenarti senza problemi, ricordati di rinnovarlo in tempo. Ti aspettiamo in campo! Centro Sportivo La Madonnella';
-        $params = array(
-            'to'            => '+39' . $phone,
-            'from'          => env('SMS_FROM', 'Test'),
-            'message'       => $message,
-            'format'        => 'json',
-        );
-        $r = sms_send($params);
-        Log::info("SMS");
-        Log::info($r);
-        sleep(1);
+        $new = \App\Models\MemberCertificate::where('expire_date', '>', $expire_date)->count();
+        if ($new == 0)
+        {
+            $phone = $certificate->member->phone;
+            $message = 'Ciao ' . $certificate->member->first_name . ', ci risulta che il tuo certificato medico scade il ' . $expire_date_it . '. Per continuare ad allenarti senza problemi, ricordati di rinnovarlo in tempo. Ti aspettiamo in campo! Centro Sportivo La Madonnella';
+            $params = array(
+                'to'            => '+39' . $phone,
+                'from'          => env('SMS_FROM', 'Test'),
+                'message'       => $message,
+                'format'        => 'json',
+            );
+            $r = sms_send($params);
+            Log::info("SMS");
+            Log::info($r);
+            sleep(1);
+        }
     }
 
 });