12 Commits 9d9db7fa37 ... 8986c14724

Tác giả SHA1 Thông báo Ngày
  Luca Parisio 8986c14724 Aggiunta versione ol prima nota 2 tháng trước cách đây
  Luca Parisio d5748c054d Merge remote-tracking branch 'origin/iao_team_ferrari' into iao_team 2 tháng trước cách đây
  ferrari 51793db7b0 members - visualizzazione corretta mesi corsi 2 tháng trước cách đây
  ferrari d5f2d7b125 reports - ottimizzazione aggiornamento grafici 2 tháng trước cách đây
  ferrari aaee20a9f9 reports - ottimizzazione aggiornamento grafici 2 tháng trước cách đây
  ferrari 3761b93fbb reports - ottimizzazione aggiornamento grafici 2 tháng trước cách đây
  ferrari ee29aa9992 reports - ottimizzazione aggiornamento grafici 2 tháng trước cách đây
  ferrari 06a960f2a9 modifiche calcolo totali reports e gestionale 2 tháng trước cách đây
  ferrari 7e8fc6a36b modifiche calcolo totali reports e gestionale 2 tháng trước cách đây
  ferrari 65aab6ee5d modifiche calcolo totali reports e gestionale 2 tháng trước cách đây
  ferrari 6df941599c record - eliminazione record all'eliminazione della ricevuta 2 tháng trước cách đây
  ferrari 6c00e3703a modificati filtri entrate/uscite 2 tháng trước cách đây

+ 17 - 1
app/Http/Livewire/Member.php

@@ -684,7 +684,23 @@ class Member extends Component
     public function loadMemberCourses()
     {
         $this->member_courses = \App\Models\MemberCourse::where('member_id', $this->dataId)->get();
-        // return view('livewire.member');
+
+        if ($this->dataId) {
+            $order = [9,10,11,12,1,2,3,4,5,6,7,8];
+
+            $this->member_courses = $this->member_courses->map(function($course) use ($order) {
+                $months = json_decode($course->months, true);
+
+                usort($months, function($a, $b) use ($order) {
+                    $posA = array_search($a['m'], $order);
+                    $posB = array_search($b['m'], $order);
+                    return $posA <=> $posB;
+                });
+
+                $course->months = json_encode($months);
+                return $course;
+            });
+        }
     }
 
     public function loadMemberCategories()

+ 60 - 13
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.',
@@ -573,7 +575,7 @@ class Record extends Component
                 'records_rows.note',
                 'records_rows.when',
                 'records_rows.vat_id',
-                'causals.name as causal_name',
+                //'causals.name as causal_name',
                 'd.name as destination',
                 'o.name as origin',
             )
@@ -622,8 +624,35 @@ class Record extends Component
             ->orderBy('records.created_at', 'ASC')
             ->orderBy('records_rows.id', 'ASC')
             ->get();
-        
-        return $datas;
+
+        $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);
+        }
+
+        return $ret;
 
     }
 
@@ -1637,16 +1666,32 @@ class Record extends Component
         $idx = 2;
         foreach($records as $record)
         {
-            $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);
+            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++;
         }
 
@@ -1661,6 +1706,8 @@ class Record extends Component
         $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,

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

@@ -1076,6 +1076,35 @@ class RecordIN extends Component
         $receipt = \App\Models\Receipt::findOrFail($this->currentReceip->id);
         $receipt->status = 99;
         $receipt->save();
+        
+        // cancellazione record associato
+        try{
+
+            $record = \App\Models\Record::find($receipt->record_id);
+
+            if ($record->member_course_id > 0)
+            {
+                $months = json_decode($record->months);
+                $c = \App\Models\MemberCourse::findOrFail($record->member_course_id);
+                $xxx = json_decode($c->months);
+                foreach($xxx as $idx => $mm)
+                {
+                    if (in_array($mm->m, $months))
+                    {
+                        $xxx[$idx]->status = "";
+                    }
+                }
+                $c->months = json_encode($xxx);
+                $c->save();
+            }
+
+            $record->deleted = true;
+            $record->save();
+
+        } catch(\Exception $ex) {
+            session()->flash('error','Errore (' . $ex->getMessage() . ')');
+        }
+
         sendReceiptDeleteEmail($receipt);
         $this->currentReceip = $receipt;
 

+ 132 - 292
app/Http/Livewire/RecordINOUT.php

@@ -1,6 +1,8 @@
 <?php
 
 namespace App\Http\Livewire;
+
+use Illuminate\Support\Carbon;
 use Livewire\Component;
 
 use PhpOffice\PhpSpreadsheet\Spreadsheet;
@@ -53,18 +55,17 @@ class RecordINOUT extends Component
     public function mount()
     {
 
-        if(Auth::user()->level != env('LEVEL_ADMIN', 0))
+        if (Auth::user()->level != env('LEVEL_ADMIN', 0))
             return redirect()->to('/dashboard');
 
         $borsellino = \App\Models\Causal::where('money', true)->first();
         if ($borsellino)
             $this->excludeCausals[] = $borsellino->id;
-            //$this->borsellino_id = $borsellino->id;
+        //$this->borsellino_id = $borsellino->id;
 
         // Aggiungo
         $excludes = \App\Models\Causal::where('no_records', true)->get();
-        foreach($excludes as $e)
-        {
+        foreach ($excludes as $e) {
             $this->excludeCausals[] = $e->id;
         }
 
@@ -89,38 +90,34 @@ class RecordINOUT extends Component
 
     public function getCausalsIn($records, $indentation)
     {
-        foreach($records as $record)
-        {
+        foreach ($records as $record) {
             $this->causalsIn[] = array('id' => $record->id, 'name' => $record->getTree(), 'text' => $record->getTree(), 'level' => $indentation);
-            if(count($record->childs))
+            if (count($record->childs))
                 $this->getCausalsIn($record->childs, $indentation + 1);
         }
     }
 
     public function getCausalsOut($records, $indentation)
     {
-        foreach($records as $record)
-        {
+        foreach ($records as $record) {
             $this->causalsOut[] = array('id' => $record->id, 'name' => $record->getTree(), 'text' => $record->getTree(), 'level' => $indentation);
-            if(count($record->childs))
+            if (count($record->childs))
                 $this->getCausalsOut($record->childs, $indentation + 1);
         }
     }
 
     public function getCausale($records, $type, $indentation)
     {
-        foreach($records as $record)
-        {
+        foreach ($records as $record) {
             $first_parent_id = null;
-            if ($record->parent_id != null)
-            {
+            if ($record->parent_id != null) {
                 $first_parent_id = \App\Models\Causal::where('id', $record->parent_id)->first()->parent_id;
             }
             if ($type == 'IN')
                 $this->rows_in[] = array('id' => $record->id, 'name' => $record->name, 'level' => $indentation, 'parent_id' => $record->parent_id, 'parent_name' => $this->getCausalName($record->parent_id), 'first_parent_id' => $first_parent_id, 'first_parent_name' => $this->getCausalName($first_parent_id), 'all_childs' => $this->getAllChild($record->id));
             if ($type == 'OUT')
                 $this->rows_out[] = array('id' => $record->id, 'name' => $record->name, 'level' => $indentation, 'parent_id' => $record->parent_id, 'parent_name' => $this->getCausalName($record->parent_id), 'first_parent_id' => $first_parent_id, 'first_parent_name' => $this->getCausalName($first_parent_id), 'all_childs' => $this->getAllChild($record->id));
-            if(count($record->childs))
+            if (count($record->childs))
                 $this->getCausale($record->childs, $type, $indentation + 1);
         }
     }
@@ -133,30 +130,24 @@ class RecordINOUT extends Component
 
         $record = \App\Models\Causal::findOrFail($id);
         $aChilds[] = $record->parent_id;
-        if ($record->parent_id != null)
-        {
+        if ($record->parent_id != null) {
             $first_parent_id = \App\Models\Causal::where('id', $record->parent_id)->first()->parent_id;
             $aChilds[] = $first_parent_id;
         }
 
         $childs = \App\Models\Causal::where('parent_id', $id)->get();
-        foreach($childs as $child)
-        {
+        foreach ($childs as $child) {
             $aChilds[] = $child->id;
             $childs2 = \App\Models\Causal::where('parent_id', $child->id)->get();
-            foreach($childs2 as $child2)
-            {
+            foreach ($childs2 as $child2) {
                 $aChilds[] = $child2->id;
                 $childs3 = \App\Models\Causal::where('parent_id', $child2->id)->get();
-                foreach($childs3 as $child3)
-                {
+                foreach ($childs3 as $child3) {
                     $aChilds[] = $child3->id;
-
                 }
             }
         }
         return $aChilds;
-
     }
 
 
@@ -179,10 +170,7 @@ class RecordINOUT extends Component
     }
 
     public function show($m, $y)
-    //public function show($dt)
     {
-        //list($m, $y) = explode("_", $dt);
-
         if ($m != "" && $y != "" && !in_array($m . "-" . $y, $this->datas))
             $this->datas[] = $m . "-" . $y;
 
@@ -190,42 +178,31 @@ class RecordINOUT extends Component
         $this->records_in = [];
         $this->records_out = [];
 
-        $exclude_from_records = \App\Models\Member::where('exclude_from_records', true)->pluck('id')->toArray();
+        $vats = getVatMap();
 
-        if (sizeof($this->datas) > 0)
-        {
-            foreach($this->datas as $filter)
-            {
-                // $filter = $m . "-" . $this->year;
+        $exclude_from_records = \App\Models\Member::where('exclude_from_records', true)->pluck('id')->toArray();
 
+        if (sizeof($this->datas) > 0) {
+            foreach ($this->datas as $filter) {
                 $this->columns[] = $filter;
 
                 list($m, $y) = explode("-", $filter);
 
-                // $f = $filter;
-                // if ($m == 'x')
-                //     $f = str_replace("x-", "", $filter);
-
-                //$dt = $y . "-0" . $m;
-
-                // $records = \App\Models\Record::where('type', 'IN')
-                //     ->join('records_rows', 'records.id', '=', 'records_rows.record_id')
-                //     ->whereNotIn('records_rows.causal_id', $this->excludeCausals)
-                //     ->where(function ($query)  {
-                //         $query->where('deleted', false)->orWhere('deleted', null);
-                //     })
-                //     ->where(function ($query)  {
-                //         $query->where('financial_movement', false)->orWhere('financial_movement', null);
-                //     })
-                //     ->whereNotIn('member_id', $exclude_from_records)
-                //     /*->where(function ($query) use ($f, $dt)  {
-                //         $query->where('records.date', 'like', '%' . $dt . '%')->orWhere('records_rows.when', 'like', '%' . $f . '%');
-                //     })*/
-                //     ->where('records_rows.when', 'like', '%"' . $f . '"%')
-                //     ->get();
-                // //$records = $records->orderBy('date', 'DESC')->get();
-
-                $recordsQuery = \App\Models\Record::where('records.type', 'IN')
+                $pairs = [];
+                if ($m == 'x') {
+                    $year = $y;
+                    $next_year = $y + 1;
+                    $start = Carbon::createFromFormat("Y-m-d", "$year-09-01")->startOfMonth();
+                    $end = Carbon::createFromFormat("Y-m-d", "$next_year-08-31")->startOfMonth();
+                    foreach (\Carbon\CarbonPeriod::create($start, '1 month', $end) as $d) {
+                        $pairs[] = '"' . (string)$d->month . "-" . (string)$d->year . '"';
+                    }
+                    $pairs = implode("|", $pairs);
+                } else {
+                    $pairs = '"' . $filter . '"';
+                }
+
+                $incomeQuery = \App\Models\Record::where('records.type', 'IN')
                     ->join('records_rows', 'records.id', '=', 'records_rows.record_id')
                     ->whereNotIn('records_rows.causal_id', $this->excludeCausals)
                     ->where(function ($query) {
@@ -234,92 +211,37 @@ class RecordINOUT extends Component
                     ->where(function ($query) {
                         $query->where('financial_movement', false)->orWhere('financial_movement', null);
                     })
-                    ->whereNotIn('member_id', $exclude_from_records);
-
-                if ($m === 'x') {
-                    // Anno fiscale da settembre $y a agosto $y+1
-                    $months = array_merge(range(9, 12), range(1, 8));
-                    $years = [
-                        9 => $y, 10 => $y, 11 => $y, 12 => $y,
-                        1 => $y+1, 2 => $y+1, 3 => $y+1, 4 => $y+1,
-                        5 => $y+1, 6 => $y+1, 7 => $y+1, 8 => $y+1
-                    ];
-
-                    $recordsQuery->where(function ($q) use ($months, $years) {
-                        foreach ($months as $month) {
-                            $year = $years[$month];
-                            // variante entrambi numeri stringhe
-                            $q->orWhereRaw("JSON_CONTAINS(`records_rows`.`when`, '{\"month\":\"{$month}\",\"year\":\"{$year}\"}')");
-                            // variante month stringa e year int
-                            $q->orWhereRaw("JSON_CONTAINS(`records_rows`.`when`, '{\"month\":\"{$month}\",\"year\":{$year}}')");
-                            // variante month int e year stringa
-                            $q->orWhereRaw("JSON_CONTAINS(`records_rows`.`when`, '{\"month\":{$month},\"year\":\"{$year}\"}')");
-                            // variante entrambi numeri int
-                            $q->orWhereRaw("JSON_CONTAINS(`records_rows`.`when`, '{\"month\":{$month},\"year\":{$year}}')");
-                        }
-                    });
+                    ->whereNotIn('member_id', $exclude_from_records)
+                    ->whereRaw('records_rows.when REGEXP ?', [$pairs]);
+                $incomeRecords = $incomeQuery->get();
 
-                } else {
-                    $recordsQuery->where(function ($q) use ($m, $y) {
-                        // variante entrambi numeri stringhe
-                        $q->orWhereRaw("JSON_CONTAINS(`records_rows`.`when`, '{\"month\":\"{$m}\",\"year\":\"{$y}\"}')");
-                        // variante month stringa e year int
-                        $q->orWhereRaw("JSON_CONTAINS(`records_rows`.`when`, '{\"month\":\"{$m}\",\"year\":{$y}}')");
-                        // variante month int e year stringa
-                        $q->orWhereRaw("JSON_CONTAINS(`records_rows`.`when`, '{\"month\":{$m},\"year\":\"{$y}\"}')");
-                        // variante entrambi numeri int
-                        $q->orWhereRaw("JSON_CONTAINS(`records_rows`.`when`, '{\"month\":{$m},\"year\":{$y}}')");
-                    });
-                }
-                $records = $recordsQuery->get();
+                foreach ($incomeRecords as $record) {
+                    $total_months = count(json_decode($record->when, true));
+                    $matching_months = 0;
+                    $matches = [];
+                    if (!preg_match_all("/$pairs/", $record->when, $matches)) continue;
 
-                $ccc = 0;
-                $ids = '';
+                    $matching_months = count($matches[0]);
 
-                foreach($records as $record)
-                {
                     $amount = $record->amount;
-                    $amount += getVatValue($amount, $record->vat_id);
-                    $when = sizeof(json_decode($record->when));
-                    if ($when > 1)
-                    {
-                        $amount = $amount / $when;
-                        $record->amount = $amount;
+                    if (isset($vats[$record->vat_id]) && $vats[$record->vat_id] > 0) {
+                        $vat = $vats[$record->vat_id];
+                        $amount += $amount * $vat;
                     }
+                    $amount *= ($matching_months / $total_months);
+
                     // Aggiungo/aggiorno i dati
-                    if (isset($this->records_in[$filter][$record->causal_id]))
+                    if (isset($this->records_in[$filter][$record->causal_id])) {
                         $this->records_in[$filter][$record->causal_id] += $amount;
-                    else
+                    } else {
                         $this->records_in[$filter][$record->causal_id] = $amount;
-
-                    //if ($record->causal_id == 158)
-                    //    print "ID = " . $record->id . "<br>";
+                    }
 
                     // Aggiorno i dati del padre
                     $this->updateParent("IN", $record->causal_id, $amount, $filter);
-
-                    if ($record->causal_id == 159 && $filter == '11-2025')
-                    {
-                        $ccc += 1;
-                        $ids .= $record->id . ",";
-                    }
                 }
-                //die;
-
-                // $records = \App\Models\Record::where('type', 'OUT')
-                //     ->join('records_rows', 'records.id', '=', 'records_rows.record_id')
-                //     ->whereNotIn('records_rows.causal_id', $this->excludeCausals)
-                //     ->where(function ($query)  {
-                //         $query->where('deleted', false)->orWhere('deleted', null);
-                //     })
-                //     ->where(function ($query)  {
-                //         $query->where('financial_movement', false)->orWhere('financial_movement', null);
-                //     })
-                //     ->whereNotIn('member_id', $exclude_from_records)
-                //     ->where('records_rows.when', 'like', '%"' . $f . '"%')->get();
-                //$records = $records->orderBy('date', 'DESC')->get();
-
-                $recordsQuery = \App\Models\Record::where('records.type', 'OUT')
+
+                $expenseQuery = \App\Models\Record::where('records.type', 'OUT')
                     ->join('records_rows', 'records.id', '=', 'records_rows.record_id')
                     ->whereNotIn('records_rows.causal_id', $this->excludeCausals)
                     ->where(function ($query) {
@@ -328,60 +250,37 @@ class RecordINOUT extends Component
                     ->where(function ($query) {
                         $query->where('financial_movement', false)->orWhere('financial_movement', null);
                     })
-                    ->whereNotIn('member_id', $exclude_from_records);
-
-                if ($m === 'x') {
-                    // Anno fiscale da settembre $y a agosto $y+1
-                    $months = array_merge(range(9, 12), range(1, 8));
-                    $years = [
-                        9 => $y, 10 => $y, 11 => $y, 12 => $y,
-                        1 => $y+1, 2 => $y+1, 3 => $y+1, 4 => $y+1,
-                        5 => $y+1, 6 => $y+1, 7 => $y+1, 8 => $y+1
-                    ];
-
-                    $recordsQuery->where(function ($q) use ($months, $years) {
-                        foreach ($months as $month) {
-                            $year = $years[$month];
-                            // variante entrambi numeri stringhe
-                            $q->orWhereRaw("JSON_CONTAINS(`records_rows`.`when`, '{\"month\":\"{$month}\",\"year\":\"{$year}\"}')");
-                            // variante month stringa e year int
-                            $q->orWhereRaw("JSON_CONTAINS(`records_rows`.`when`, '{\"month\":\"{$month}\",\"year\":{$year}}')");
-                            // variante month int e year stringa
-                            $q->orWhereRaw("JSON_CONTAINS(`records_rows`.`when`, '{\"month\":{$month},\"year\":\"{$year}\"}')");
-                            // variante entrambi numeri int
-                            $q->orWhereRaw("JSON_CONTAINS(`records_rows`.`when`, '{\"month\":{$month},\"year\":{$year}}')");
-                        }
-                    });
+                    ->whereNotIn('member_id', $exclude_from_records)
+                    ->whereRaw('records_rows.when REGEXP ?', [$pairs]);
+                $expenseRecords = $expenseQuery->get();
 
-                } else {
-                    $recordsQuery->where(function ($q) use ($m, $y) {
-                        // variante entrambi numeri stringhe
-                        $q->orWhereRaw("JSON_CONTAINS(`records_rows`.`when`, '{\"month\":\"{$m}\",\"year\":\"{$y}\"}')");
-                        // variante month stringa e year int
-                        $q->orWhereRaw("JSON_CONTAINS(`records_rows`.`when`, '{\"month\":\"{$m}\",\"year\":{$y}}')");
-                        // variante month int e year stringa
-                        $q->orWhereRaw("JSON_CONTAINS(`records_rows`.`when`, '{\"month\":{$m},\"year\":\"{$y}\"}')");
-                        // variante entrambi numeri int
-                        $q->orWhereRaw("JSON_CONTAINS(`records_rows`.`when`, '{\"month\":{$m},\"year\":{$y}}')");
-                    });
-                }
-                $records = $recordsQuery->get();
+                foreach ($expenseRecords as $record) {
+                    $when_array = json_decode($record->when, true);
+                    if (!is_array($when_array) || empty($when_array) || count($when_array) <= 0) continue;
+
+                    $total_months = count($when_array);
+
+                    $matching_months = 0;
+                    $matches = [];
+                    if (!preg_match_all("/$pairs/", $record->when, $matches)) continue;
+
+                    $matching_months = count($matches[0]);
 
-                foreach($records as $record)
-                {
                     $amount = $record->amount;
-                    $amount += getVatValue($amount, $record->vat_id);
-                    $when = sizeof(json_decode($record->when));
-                    if ($when > 1)
-                    {
-                        $amount = $amount / $when;
-                        $record->amount = $amount;
+                    if (isset($vats[$record->vat_id]) && $vats[$record->vat_id] > 0) {
+                        $vat = $vats[$record->vat_id];
+                        $amount += $amount * $vat;
                     }
+                    $amount *= ($matching_months / $total_months);
+
                     // Aggiungo/aggiorno i dati
-                    if (isset($this->records_out[$filter][$record->causal_id]))
+                    if (isset($this->records_out[$filter][$record->causal_id])) {
                         $this->records_out[$filter][$record->causal_id] += $amount;
-                    else
+                    } else {
                         $this->records_out[$filter][$record->causal_id] = $amount;
+                    }
+
+                    // Aggiorno i dati del padre
                     $this->updateParent("OUT", $record->causal_id, $amount, $filter);
                 }
             }
@@ -391,17 +290,13 @@ class RecordINOUT extends Component
         //print $ids;
         //$this->showData = true;
         $this->emit('load-table');
-
     }
 
     public function updateParent($type, $causal_id, $amount, $filter)
     {
-        if ($type == "IN")
-        {
-            foreach($this->rows_in as $r)
-            {
-                if ($r["id"] == $causal_id)
-                {
+        if ($type == "IN") {
+            foreach ($this->rows_in as $r) {
+                if ($r["id"] == $causal_id) {
                     if (isset($this->records_in[$filter][$r["parent_id"]]))
                         $this->records_in[$filter][$r["parent_id"]] += $amount;
                     else
@@ -411,12 +306,9 @@ class RecordINOUT extends Component
                 }
             }
         }
-        if ($type == "OUT")
-        {
-            foreach($this->rows_out as $r)
-            {
-                if ($r["id"] == $causal_id)
-                {
+        if ($type == "OUT") {
+            foreach ($this->rows_out as $r) {
+                if ($r["id"] == $causal_id) {
                     if (isset($this->records_out[$filter][$r["parent_id"]]))
                         $this->records_out[$filter][$r["parent_id"]] += $amount;
                     else
@@ -430,12 +322,9 @@ class RecordINOUT extends Component
 
     public function updateParentYear($type, $causal_id, $amount, $filter, &$records_in, &$records_out)
     {
-        if ($type == "IN")
-        {
-            foreach($this->rows_in as $r)
-            {
-                if ($r["id"] == $causal_id)
-                {
+        if ($type == "IN") {
+            foreach ($this->rows_in as $r) {
+                if ($r["id"] == $causal_id) {
                     if (isset($records_in[$filter][$r["parent_id"]]))
                         $records_in[$filter][$r["parent_id"]] += $amount;
                     else
@@ -445,12 +334,9 @@ class RecordINOUT extends Component
                 }
             }
         }
-        if ($type == "OUT")
-        {
-            foreach($this->rows_out as $r)
-            {
-                if ($r["id"] == $causal_id)
-                {
+        if ($type == "OUT") {
+            foreach ($this->rows_out as $r) {
+                if ($r["id"] == $causal_id) {
                     if (isset($records_out[$filter][$r["parent_id"]]))
                         $records_out[$filter][$r["parent_id"]] += $amount;
                     else
@@ -465,8 +351,7 @@ class RecordINOUT extends Component
     public function getCausal($causal)
     {
         $ret = '';
-        if ($causal > 0)
-        {
+        if ($causal > 0) {
             $ret = \App\Models\Causal::findOrFail($causal)->getTree();
         }
         return $ret;
@@ -521,7 +406,7 @@ class RecordINOUT extends Component
                 break;
         }
         if ($m == 'x') {
-            $nextY = $y+1;
+            $nextY = $y + 1;
             $ret = "{$y}/{$nextY}";
         } else {
             $ret .= $y;
@@ -545,7 +430,7 @@ class RecordINOUT extends Component
 
         if (sizeof($this->datas) > 1)
             array_splice($this->datas, $idx, 1);
-            //unset($this->datas[$idx]);
+        //unset($this->datas[$idx]);
         else
             $this->datas = array();
 
@@ -558,40 +443,29 @@ class RecordINOUT extends Component
         $rows_in = array();
         $rows_out = array();
 
-        if ($this->filterCausalsIn != null && sizeof($this->filterCausalsIn) > 0)
-        {
-            foreach($this->rows_in as $r)
-            {
-                if (in_array($r["id"], $this->filterCausalsIn) || in_array($r["parent_id"], $this->filterCausalsIn) || in_array($r["first_parent_id"], $this->filterCausalsIn))
-                {
+        if ($this->filterCausalsIn != null && sizeof($this->filterCausalsIn) > 0) {
+            foreach ($this->rows_in as $r) {
+                if (in_array($r["id"], $this->filterCausalsIn) || in_array($r["parent_id"], $this->filterCausalsIn) || in_array($r["first_parent_id"], $this->filterCausalsIn)) {
                     $rows_in[] = $r;
                 }
             }
-        }
-        else
-        {
+        } else {
             $rows_in = $this->rows_in;
         }
 
-        if ($this->filterCausalsOut != null && sizeof($this->filterCausalsOut) > 0)
-        {
-            foreach($this->rows_out as $r)
-            {
-                if (in_array($r["id"], $this->filterCausalsOut) || in_array($r["parent_id"], $this->filterCausalsOut) || in_array($r["first_parent_id"], $this->filterCausalsOut))
-                {
+        if ($this->filterCausalsOut != null && sizeof($this->filterCausalsOut) > 0) {
+            foreach ($this->rows_out as $r) {
+                if (in_array($r["id"], $this->filterCausalsOut) || in_array($r["parent_id"], $this->filterCausalsOut) || in_array($r["first_parent_id"], $this->filterCausalsOut)) {
                     $rows_out[] = $r;
                 }
             }
-        }
-        else
-        {
+        } else {
             $rows_out = $this->rows_out;
         }
 
-        $path = $this->generateExcel($this->columns, $rows_in, $this->records_in, $rows_out, $this->records_out,false);
+        $path = $this->generateExcel($this->columns, $rows_in, $this->records_in, $rows_out, $this->records_out, false);
 
         return response()->download($path)->deleteFileAfterSend();
-
     }
 
     public function exportYear($year)
@@ -599,56 +473,47 @@ class RecordINOUT extends Component
         $records_in = [];
         $records_out = [];
         $datas = [];
-        if (env('FISCAL_YEAR_MONTH_FROM', 1) > 1)
-        {
+        if (env('FISCAL_YEAR_MONTH_FROM', 1) > 1) {
 
             if (date("m") < env('FISCAL_YEAR_MONTH_FROM', 1))
                 $year -= 1;
 
-            for($m=env('FISCAL_YEAR_MONTH_FROM', 1);$m<=12;$m++)
-            {
+            for ($m = env('FISCAL_YEAR_MONTH_FROM', 1); $m <= 12; $m++) {
                 $datas[] = $m . "-" . $year;
             }
-            for($m=1;$m<=env('FISCAL_YEAR_MONTH_TO', 12);$m++)
-            {
+            for ($m = 1; $m <= env('FISCAL_YEAR_MONTH_TO', 12); $m++) {
                 $datas[] = $m . "-" . ($year + 1);
             }
-        }
-        else
-        {
-            for($m=1;$m<=12;$m++)
-            {
+        } else {
+            for ($m = 1; $m <= 12; $m++) {
                 $datas[] = $m . "-" . $year;
             }
         }
 
         $exclude_from_records = \App\Models\Member::where('exclude_from_records', true)->pluck('id')->toArray();
 
-        foreach($datas as $filter)
-        {
+        foreach ($datas as $filter) {
 
             $columns[] = $filter;
 
             $records = \App\Models\Record::where('type', 'IN')
                 ->join('records_rows', 'records.id', '=', 'records_rows.record_id')
                 ->whereNotIn('records_rows.causal_id', $this->excludeCausals)
-                ->where(function ($query)  {
+                ->where(function ($query) {
                     $query->where('deleted', false)->orWhere('deleted', null);
                 })
-                ->where(function ($query)  {
+                ->where(function ($query) {
                     $query->where('financial_movement', false)->orWhere('financial_movement', null);
                 })
                 ->whereNotIn('member_id', $exclude_from_records)
                 ->where('records_rows.when', 'like', '%"' . $filter . '"%')->get();
             //$records = $records->orderBy('date', 'DESC')->get();
 
-            foreach($records as $record)
-            {
+            foreach ($records as $record) {
                 $amount = $record->amount;
                 $amount += getVatValue($amount, $record->vat_id);
                 $when = sizeof(json_decode($record->when));
-                if ($when > 1)
-                {
+                if ($when > 1) {
                     $amount = $amount / $when;
                     //$record->amount = $amount;
                 }
@@ -659,30 +524,25 @@ class RecordINOUT extends Component
                     $records_in[$filter][$record->causal_id] = $amount;
                 // Aggiorno i dati del padre
                 $this->updateParentYear("IN", $record->causal_id, $amount, $filter, $records_in, $records_out);
-
-                
-
             }
 
             $records = \App\Models\Record::where('type', 'OUT')
                 ->join('records_rows', 'records.id', '=', 'records_rows.record_id')
                 ->whereNotIn('records_rows.causal_id', $this->excludeCausals)
-                ->where(function ($query)  {
+                ->where(function ($query) {
                     $query->where('deleted', false)->orWhere('deleted', null);
                 })
-                ->where(function ($query)  {
+                ->where(function ($query) {
                     $query->where('financial_movement', false)->orWhere('financial_movement', null);
                 })
                 ->whereNotIn('member_id', $exclude_from_records)
                 ->where('records_rows.when', 'like', '%"' . $filter . '"%')->get();
             //$records = $records->orderBy('date', 'DESC')->get();
 
-            foreach($records as $record)
-            {
+            foreach ($records as $record) {
                 $amount = $record->amount;
                 $when = sizeof(json_decode($record->when));
-                if ($when > 1)
-                {
+                if ($when > 1) {
                     $amount = $amount / $when;
                     $record->amount = $amount;
                 }
@@ -693,14 +553,12 @@ class RecordINOUT extends Component
                     $records_out[$filter][$record->causal_id] = $amount;
                 $this->updateParentYear("OUT", $record->causal_id, $amount, $filter, $records_in, $records_out);
             }
-
         }
 
 
 
         $path = $this->generateExcel($columns, $this->rows_in, $records_in, $this->rows_out, $records_out, true);
         return response()->download($path)->deleteFileAfterSend();
-
     }
 
     public function generateExcel($columns, $rows_in, $records_in, $rows_out, $records_out, $isYearExport)
@@ -711,8 +569,7 @@ class RecordINOUT extends Component
         $activeWorksheet = $spreadsheet->getActiveSheet();
 
         $activeWorksheet->setCellValue('A1', 'Entrate');
-        foreach($columns as $idx => $column)
-        {
+        foreach ($columns as $idx => $column) {
             $activeWorksheet->setCellValue($letters[$idx + 1] . '1', $this->getMonth($column));
         }
 
@@ -723,17 +580,13 @@ class RecordINOUT extends Component
 
         $totals = [];
 
-        foreach($rows_in as $in)
-        {
+        foreach ($rows_in as $in) {
             $activeWorksheet->setCellValue('A' . $count, str_repeat("  ", $in["level"]) . $in["name"]);
 
-            foreach($columns as $idx => $column)
-            {
-                if(isset($records_in[$column][$in["id"]]))
-                {
+            foreach ($columns as $idx => $column) {
+                if (isset($records_in[$column][$in["id"]])) {
                     $activeWorksheet->setCellValue($letters[$idx + 1] . $count, formatPrice($records_in[$column][$in["id"]]));
-                    if ($in["level"] == 0)
-                    {
+                    if ($in["level"] == 0) {
                         if (isset($totals[$idx]))
                             $totals[$idx] += $records_in[$column][$in["id"]];
                         else
@@ -742,19 +595,16 @@ class RecordINOUT extends Component
                 }
             }
 
-            if ($in["level"] == 0)
-            {
+            if ($in["level"] == 0) {
                 $activeWorksheet->getStyle('A' . $count . ':N' . $count)->getFont()->setBold(true);
                 //$activeWorksheet->getStyle('A' . $count . ':N' . $count)->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('b1ed5c');
             }
 
             $count += 1;
-
         }
 
         $activeWorksheet->setCellValue('A' . $count, 'Totale');
-        foreach($totals as $idx => $total)
-        {
+        foreach ($totals as $idx => $total) {
             $activeWorksheet->setCellValue($letters[$idx + 1] . $count, formatPrice($total));
             $activeWorksheet->getStyle('A' . $count . ':N' . $count)->getFont()->setBold(true);
             $activeWorksheet->getStyle('A' . $count . ':N' . $count)->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('C6E0B4'); // Lighter green
@@ -763,8 +613,7 @@ class RecordINOUT extends Component
 
         $count += 2;
         $activeWorksheet->setCellValue('A' . $count, "Uscite");
-        foreach($columns as $idx => $column)
-        {
+        foreach ($columns as $idx => $column) {
             $activeWorksheet->setCellValue($letters[$idx + 1] . $count, $this->getMonth($column));
         }
 
@@ -775,17 +624,13 @@ class RecordINOUT extends Component
 
         $totals = [];
 
-        foreach($rows_out as $out)
-        {
+        foreach ($rows_out as $out) {
             $activeWorksheet->setCellValue('A' . $count, str_repeat("  ", $out["level"]) . $out["name"]);
 
-            foreach($columns as $idx => $column)
-            {
-                if(isset($records_out[$column][$out["id"]]))
-                {
+            foreach ($columns as $idx => $column) {
+                if (isset($records_out[$column][$out["id"]])) {
                     $activeWorksheet->setCellValue($letters[$idx + 1] . $count, formatPrice($records_out[$column][$out["id"]]));
-                    if ($out["level"] == 0)
-                    {
+                    if ($out["level"] == 0) {
                         if (isset($totals[$idx]))
                             $totals[$idx] += $records_out[$column][$out["id"]];
                         else
@@ -794,19 +639,16 @@ class RecordINOUT extends Component
                 }
             }
 
-            if ($out["level"] == 0)
-            {
+            if ($out["level"] == 0) {
                 $activeWorksheet->getStyle('A' . $count . ':N' . $count)->getFont()->setBold(true);
                 //$activeWorksheet->getStyle('A' . $count . ':N' . $count)->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('ed6d61');
             }
 
             $count += 1;
-
         }
 
         $activeWorksheet->setCellValue('A' . $count, 'Totale');
-        foreach($totals as $idx => $total)
-        {
+        foreach ($totals as $idx => $total) {
             $activeWorksheet->setCellValue($letters[$idx + 1] . $count, formatPrice($total));
             $activeWorksheet->getStyle('A' . $count . ':N' . $count)->getFont()->setBold(true);
             $activeWorksheet->getStyle('A' . $count . ':N' . $count)->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('F8CBAD'); // Lighter red
@@ -814,7 +656,7 @@ class RecordINOUT extends Component
 
         $activeWorksheet->getColumnDimension('A')->setWidth(35);
 
-        for($i = 1; $i < count($letters); $i++) {
+        for ($i = 1; $i < count($letters); $i++) {
             $activeWorksheet->getColumnDimension($letters[$i])->setWidth(20);
         }
 
@@ -822,10 +664,8 @@ class RecordINOUT extends Component
         $fileSuffix = $isYearExport ? 'AnnoFiscale' : 'Selezione';
 
         $writer = new Xlsx($spreadsheet);
-        $writer->save($path = storage_path(date("Ymd") .'_Gestionale_' . $fileSuffix .  '.xlsx'));
+        $writer->save($path = storage_path(date("Ymd") . '_Gestionale_' . $fileSuffix .  '.xlsx'));
 
         return $path;
-
     }
-
 }

+ 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;
+    }
+}

+ 248 - 87
app/Http/Livewire/Reports.php

@@ -113,20 +113,20 @@ class Reports extends Component
     {
         $this->courses = $this->getCoursesForSelect();
         $this->emit('chartsUpdated');
-        $this->dispatchBrowserEvent('chartsUpdated');
+        // $this->dispatchBrowserEvent('chartsUpdated');
     }
 
     public function updateCourseChart()
     {
         $this->emit('chartsUpdated');
-        $this->dispatchBrowserEvent('chartsUpdated');
+        // $this->dispatchBrowserEvent('chartsUpdated');
     }
 
     public function updatedSeasonFilter()
     {
         $this->courses = $this->getCoursesForSelect();
         $this->emit('chartsUpdated');
-        $this->dispatchBrowserEvent('chartsUpdated');
+        // $this->dispatchBrowserEvent('chartsUpdated');
     }
 
     public function setSeasonFilter($season)
@@ -161,13 +161,26 @@ class Reports extends Component
         Log::info('Date range start: ' . $dateRange['start']);
         Log::info('Date range end: ' . $dateRange['end']);
         $monthOrder = [9, 10, 11, 12, 1, 2, 3, 4, 5, 6, 7, 8];
+        $monthIndex = [9 => 0, 10 => 1, 11 => 2, 12 => 3, 1 => 4, 2 => 5, 3 => 6, 4 => 7, 5 => 8, 6 => 9, 7 => 10, 8 => 11];
         $monthNames = ['Set', 'Ott', 'Nov', 'Dic', 'Gen', 'Feb', 'Mar', 'Apr', 'Mag', 'Giu', 'Lug', 'Ago'];
 
+        $vats = getVatMap();
+
         $incomeData = array_fill(0, 12, 0);
         $expenseData = array_fill(0, 12, 0);
-        //$this->setupTenantConnection();
 
-        $incomeRecords = DB::table('records')
+        $pairs = [];
+        $start = $dateRange['start']->copy()->startOfMonth();
+        $end = $dateRange['end']->copy()->startOfMonth();
+        foreach (\Carbon\CarbonPeriod::create($start, '1 month', $end) as $d) {
+            $pairs[] = '"' . (string)$d->month . "-" . (string)$d->year . '"';
+        }
+        $pairs = implode("|", $pairs);
+
+        $excluded_causals = \App\Models\Causal::where('no_records', true)->orWhere('money', true)->pluck('id')->toArray();
+        $excluded_members = \App\Models\Member::where('exclude_from_records', true)->pluck('id')->toArray();
+
+        $incomeQuery = DB::table('records')
             ->join('records_rows', 'records.id', '=', 'records_rows.record_id')
             ->join('causals', function ($join) {
                 $join->on('causals.id', '=', 'records_rows.causal_id')
@@ -176,13 +189,40 @@ class Reports extends Component
                             ->orWhereNull('causals.no_reports');
                     });
             })
-            ->whereBetween('records.date', [$dateRange['start'], $dateRange['end']])
-            ->where('records.type', 'IN')
-            ->select(DB::raw('MONTH(records.date) as month_num'), DB::raw('SUM(records_rows.amount) as total'))
-            ->groupBy('month_num')
-            ->get();
+            ->whereRaw('records_rows.when REGEXP ?', [$pairs])
+            ->whereNotIn('records_rows.causal_id', $excluded_causals)
+            ->whereNotIn('member_id', $excluded_members)
+            ->where(function ($query) {
+                $query->where('deleted', false)->orWhere('deleted', null);
+            })
+            ->where(function ($query) {
+                $query->where('financial_movement', false)->orWhere('financial_movement', null);
+            })
+            ->where('records.type', 'IN');
+        $incomeRecords = $incomeQuery->get();
+
+        foreach ($incomeRecords as $record) {
+            $total_months = count(json_decode($record->when, true));
+            $matches = [];
+            if (!preg_match_all("/$pairs/", $record->when, $matches)) continue;
+
+            $amount = $record->amount;
+            if (isset($vats[$record->vat_id]) && $vats[$record->vat_id] > 0) {
+                $vat = $vats[$record->vat_id];
+                $amount += $amount * $vat;
+            }
+
+            foreach ($matches[0] as $match) {
+                $m = explode("-", trim($match, '"'))[0];
+
+                // $monthIndex = array_search($m, $monthOrder);
+                if (isset($monthIndex[$m])) {
+                    $incomeData[$monthIndex[$m]] += $amount / $total_months;
+                }
+            }
+        }
 
-        $expenseRecords = DB::table('records')
+        $expenseQuery = DB::table('records')
             ->join('records_rows', 'records.id', '=', 'records_rows.record_id')
             ->join('causals', function ($join) {
                 $join->on('causals.id', '=', 'records_rows.causal_id')
@@ -191,23 +231,36 @@ class Reports extends Component
                             ->orWhereNull('causals.no_reports');
                     });
             })
-            ->whereBetween('records.date', [$dateRange['start'], $dateRange['end']])
-            ->where('records.type', 'OUT')
-            ->select(DB::raw('MONTH(records.date) as month_num'), DB::raw('SUM(records_rows.amount) as total'))
-            ->groupBy('month_num')
-            ->get();
+            ->whereRaw('records_rows.when REGEXP ?', [$pairs])
+            ->whereNotIn('records_rows.causal_id', $excluded_causals)
+            ->whereNotIn('member_id', $excluded_members)
+            ->where(function ($query) {
+                $query->where('deleted', false)->orWhere('deleted', null);
+            })
+            ->where(function ($query) {
+                $query->where('financial_movement', false)->orWhere('financial_movement', null);
+            })
+            ->where('records.type', 'OUT');
+        $expenseRecords = $expenseQuery->get();
 
-        foreach ($incomeRecords as $record) {
-            $monthIndex = array_search($record->month_num, $monthOrder);
-            if ($monthIndex !== false) {
-                $incomeData[$monthIndex] = $record->total;
+        foreach ($expenseRecords as $record) {
+            $total_months = count(json_decode($record->when, true));
+            $matches = [];
+            if (!preg_match_all("/$pairs/", $record->when, $matches)) continue;
+
+            $amount = $record->amount;
+            if (isset($vats[$record->vat_id]) && $vats[$record->vat_id] > 0) {
+                $vat = $vats[$record->vat_id];
+                $amount += $amount * $vat;
             }
-        }
 
-        foreach ($expenseRecords as $record) {
-            $monthIndex = array_search($record->month_num, $monthOrder);
-            if ($monthIndex !== false) {
-                $expenseData[$monthIndex] = $record->total;
+            foreach ($matches[0] as $match) {
+                $m = explode("-", trim($match, '"'))[0];
+
+                // $monthIndex = array_search($m, $monthOrder);
+                if (isset($monthIndex[$m])) {
+                    $expenseData[$monthIndex[$m]] += $amount / $total_months;
+                }
             }
         }
 
@@ -235,66 +288,109 @@ class Reports extends Component
     {
         Log::info('=== getyearlyTotals called ===');
 
-        $incomeRecords = DB::table('records')
-            ->join('records_rows', 'records.id', '=', 'records_rows.record_id')
-            ->join('causals', function ($join) {
-                $join->on('causals.id', '=', 'records_rows.causal_id')
-                    ->where(function ($query) {
-                        $query->where('causals.no_reports', 0)
-                            ->orWhereNull('causals.no_reports');
-                    });
-            })
-            ->where('records.type', 'IN')
-            ->selectRaw("
-                CASE
-                    WHEN MONTH(records.date) >= 9
-                        THEN CONCAT(YEAR(records.date), '/', YEAR(records.date) + 1)
-                    ELSE CONCAT(YEAR(records.date) - 1, '/', YEAR(records.date))
-                END AS year_num,
-                SUM(records_rows.amount) AS total
-            ")
-            ->groupBy('year_num')
-            ->get();
+        $excluded_causals = \App\Models\Causal::where('no_records', true)->orWhere('money', true)->pluck('id')->toArray();
+        $excluded_members = \App\Models\Member::where('exclude_from_records', true)->pluck('id')->toArray();
 
-        $expenseRecords = DB::table('records')
-            ->join('records_rows', 'records.id', '=', 'records_rows.record_id')
-            ->join('causals', function ($join) {
-                $join->on('causals.id', '=', 'records_rows.causal_id')
-                    ->where(function ($query) {
-                        $query->where('causals.no_reports', 0)
-                            ->orWhereNull('causals.no_reports');
-                    });
-            })
-            ->where('records.type', 'OUT')
-            ->selectRaw("
-                CASE
-                    WHEN MONTH(records.date) >= 9
-                        THEN CONCAT(YEAR(records.date), '/', YEAR(records.date) + 1)
-                    ELSE CONCAT(YEAR(records.date) - 1, '/', YEAR(records.date))
-                END AS year_num,
-                SUM(records_rows.amount) AS total
-            ")
-            ->groupBy('year_num')
-            ->get();
+        $vats = getVatMap();
+
+        $incomeData = [];
+        $expenseData = [];
+
+        $years = range(2023, now()->year);
+        $years_label = array_map(function ($year) {
+            return $year . "/" . ($year + 1);
+        }, $years);
+        foreach ($years as $index => $year) {
+            $incomeData[$index] = 0;
+            $expenseData[$index] = 0;
+
+            $next_year = $year + 1;
 
-        // Mappa anno/totale
-        $incomeByYear = $incomeRecords->pluck('total', 'year_num');
-        $expenseByYear = $expenseRecords->pluck('total', 'year_num');
+            $pairs = [];
+            $start = Carbon::createFromFormat("Y-m-d", "$year-09-01")->startOfMonth();
+            $end = Carbon::createFromFormat("Y-m-d", "$next_year-08-31")->startOfMonth();
+            foreach (\Carbon\CarbonPeriod::create($start, '1 month', $end) as $d) {
+                $pairs[] = '"' . (string)$d->month . "-" . (string)$d->year . '"';
+            }
+            $pairs = implode("|", $pairs);
+
+            $incomeQuery = DB::table('records')
+                ->join('records_rows', 'records.id', '=', 'records_rows.record_id')
+                ->join('causals', function ($join) {
+                    $join->on('causals.id', '=', 'records_rows.causal_id')
+                        ->where(function ($query) {
+                            $query->where('causals.no_reports', 0)
+                                ->orWhereNull('causals.no_reports');
+                        });
+                })
+                ->whereRaw('records_rows.when REGEXP ?', [$pairs])
+                ->whereNotIn('records_rows.causal_id', $excluded_causals)
+                ->whereNotIn('member_id', $excluded_members)
+                ->where(function ($query) {
+                    $query->where('deleted', false)->orWhere('deleted', null);
+                })
+                ->where(function ($query) {
+                    $query->where('financial_movement', false)->orWhere('financial_movement', null);
+                })
+                ->where('records.type', 'IN');
+            $incomeRecords = $incomeQuery->get();
+
+            foreach ($incomeRecords as $record) {
+                $total_months = count(json_decode($record->when, true));
+                $matches = [];
+                if (!preg_match_all("/$pairs/", $record->when, $matches)) continue;
+
+                $matching_months = count($matches[0]);
+                $amount = $record->amount;
+                if (isset($vats[$record->vat_id]) && $vats[$record->vat_id] > 0) {
+                    $vat = $vats[$record->vat_id];
+                    $amount += $amount * $vat;
+                }
+                $amount *= ($matching_months / $total_months);
 
-        // Unione di tutti gli anni presenti ordinati
-        $allYears = $incomeByYear->keys()
-            ->merge($expenseByYear->keys())
-            ->unique()
-            ->sort()
-            ->values();
+                $incomeData[$index] += $amount;
+            }
 
-        // Allineo i dati dei due array, se non presente l'anno: default 0
-        $incomeData  = $allYears->map(fn($y) => (float) ($incomeByYear[$y]  ?? 0))->toArray();
-        $expenseData = $allYears->map(fn($y) => (float) ($expenseByYear[$y] ?? 0))->toArray();
+            $expenseQuery = DB::table('records')
+                ->join('records_rows', 'records.id', '=', 'records_rows.record_id')
+                ->join('causals', function ($join) {
+                    $join->on('causals.id', '=', 'records_rows.causal_id')
+                        ->where(function ($query) {
+                            $query->where('causals.no_reports', 0)
+                                ->orWhereNull('causals.no_reports');
+                        });
+                })
+                ->whereRaw('records_rows.when REGEXP ?', [$pairs])
+                ->whereNotIn('records_rows.causal_id', $excluded_causals)
+                ->whereNotIn('member_id', $excluded_members)
+                ->where(function ($query) {
+                    $query->where('deleted', false)->orWhere('deleted', null);
+                })
+                ->where(function ($query) {
+                    $query->where('financial_movement', false)->orWhere('financial_movement', null);
+                })
+                ->where('records.type', 'OUT');
+            $expenseRecords = $expenseQuery->get();
+
+            foreach ($expenseRecords as $record) {
+                $total_months = count(json_decode($record->when, true));
+                $matches = [];
+                if (!preg_match_all("/$pairs/", $record->when, $matches)) continue;
+
+                $matching_months = count($matches[0]);
+                $amount = $record->amount;
+                if (isset($vats[$record->vat_id]) && $vats[$record->vat_id] > 0) {
+                    $vat = $vats[$record->vat_id];
+                    $amount += $amount * $vat;
+                }
+                $amount *= ($matching_months / $total_months);
 
+                $expenseData[$index] += $amount;
+            }
+        }
 
         return [
-            'labels' => $allYears->toArray(),
+            'labels' => $years_label,
             'datasets' => [
                 [
                     'label' => 'Entrate',
@@ -313,8 +409,25 @@ class Reports extends Component
     public function getYearlySummary()
     {
         $dateRange = $this->getSeasonDateRange($this->seasonFilter);
+        Log::info('=== getYearlySummary called ===');
+
+        $vats = getVatMap();
+
+        $excluded_causals = \App\Models\Causal::where('no_records', true)->orWhere('money', true)->pluck('id')->toArray();
+        $excluded_members = \App\Models\Member::where('exclude_from_records', true)->pluck('id')->toArray();
+
+        $pairs = [];
+        $start = $dateRange['start']->copy()->startOfMonth();
+        $end = $dateRange['end']->copy()->startOfMonth();
+        foreach (\Carbon\CarbonPeriod::create($start, '1 month', $end) as $d) {
+            $pairs[] = '"' . (string)$d->month . "-" . (string)$d->year . '"';
+        }
+        $pairs = implode("|", $pairs);
 
-        $totalIncome = DB::table('records')
+        $totalIncome = 0;
+        $totalExpenses = 0;
+
+        $incomeQuery = DB::table('records')
             ->join('records_rows', 'records.id', '=', 'records_rows.record_id')
             ->join('causals', function ($join) {
                 $join->on('causals.id', '=', 'records_rows.causal_id')
@@ -323,11 +436,35 @@ class Reports extends Component
                             ->orWhereNull('causals.no_reports');
                     });
             })
-            ->whereBetween('records.date', [$dateRange['start'], $dateRange['end']])
-            ->where('records.type', 'IN')
-            ->sum('records_rows.amount');
+            ->whereRaw('records_rows.when REGEXP ?', [$pairs])
+            ->whereNotIn('records_rows.causal_id', $excluded_causals)
+            ->whereNotIn('member_id', $excluded_members)
+            ->where(function ($query) {
+                $query->where('deleted', false)->orWhere('deleted', null);
+            })
+            ->where(function ($query) {
+                $query->where('financial_movement', false)->orWhere('financial_movement', null);
+            })
+            ->where('records.type', 'IN');
+        $incomeRecords = $incomeQuery->get();
+
+        foreach ($incomeRecords as $record) {
+            $total_months = count(json_decode($record->when, true));
+            $matches = [];
+            if (!preg_match_all("/$pairs/", $record->when, $matches)) continue;
+
+            $matching_months = count($matches[0]);
+            $amount = $record->amount;
+            if (isset($vats[$record->vat_id]) && $vats[$record->vat_id] > 0) {
+                $vat = $vats[$record->vat_id];
+                $amount += $amount * $vat;
+            }
+            $amount *= ($matching_months / $total_months);
+
+            $totalIncome += $amount;
+        }
 
-        $totalExpenses = DB::table('records')
+        $expenseQuery = DB::table('records')
             ->join('records_rows', 'records.id', '=', 'records_rows.record_id')
             ->join('causals', function ($join) {
                 $join->on('causals.id', '=', 'records_rows.causal_id')
@@ -336,9 +473,33 @@ class Reports extends Component
                             ->orWhereNull('causals.no_reports');
                     });
             })
-            ->whereBetween('records.date', [$dateRange['start'], $dateRange['end']])
-            ->where('records.type', 'OUT')
-            ->sum('records_rows.amount');
+            ->whereRaw('records_rows.when REGEXP ?', [$pairs])
+            ->whereNotIn('records_rows.causal_id', $excluded_causals)
+            ->whereNotIn('member_id', $excluded_members)
+            ->where(function ($query) {
+                $query->where('deleted', false)->orWhere('deleted', null);
+            })
+            ->where(function ($query) {
+                $query->where('financial_movement', false)->orWhere('financial_movement', null);
+            })
+            ->where('records.type', 'OUT');
+        $expenseRecords = $expenseQuery->get();
+
+        foreach ($expenseRecords as $record) {
+            $total_months = count(json_decode($record->when, true));
+            $matches = [];
+            if (!preg_match_all("/$pairs/", $record->when, $matches)) continue;
+
+            $matching_months = count($matches[0]);
+            $amount = $record->amount;
+            if (isset($vats[$record->vat_id]) && $vats[$record->vat_id] > 0) {
+                $vat = $vats[$record->vat_id];
+                $amount += $amount * $vat;
+            }
+            $amount *= ($matching_months / $total_months);
+
+            $totalExpenses += $amount;
+        }
 
         $delta = $totalIncome - $totalExpenses;
 
@@ -725,7 +886,7 @@ class Reports extends Component
             ->get();
 
         $cardTypes = $memberCards->pluck('card.name')->unique()->filter()->sort()->values()->toArray();
-        usort($cardTypes, function($a, $b) {
+        usort($cardTypes, function ($a, $b) {
             if ($a == $b) return 0;
             if ($a == "UISP") return 1;
             if ($b == "UISP") return 1;

+ 28 - 10
app/Jobs/ExportPrimaNota.php

@@ -192,16 +192,32 @@ class ExportPrimaNota implements ShouldQueue
         $idx = 2;
         foreach($this->records as $record)
         {
-            $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);
+            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++;
         }
 
@@ -216,6 +232,8 @@ class ExportPrimaNota implements ShouldQueue
         $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);

+ 17 - 0
app/helpers.php

@@ -44,6 +44,23 @@ function getVatValue($v, $i)
     return $vat;
 }
 
+function getVatMap()
+{
+    static $map = null;
+
+    if ($map === null) {
+        $map = [];
+
+        $vats = \App\Models\Vat::select('id', 'value')->get();
+        foreach ($vats as $vat) {
+            $rate = (float)$vat->value;
+            $map[$vat->id] = $rate > 0 ? 1.0 + ($rate / 100.0) : 1.0;
+        }
+    }
+
+    return $map;
+}
+
 function mysqlToDate($dt)
 {
     list($date, $hour) = explode(" ", $dt);

+ 13 - 4
resources/views/layouts/app.blade.php

@@ -160,6 +160,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'))
@@ -269,11 +271,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;' : ''}}">
@@ -305,6 +307,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>
@@ -438,8 +445,10 @@
         }
         $(document).ready(function() {
             $(document).on("click",`[data-bs-trigger='hover focus']`,function() {
-                $(".bs-popover-auto").css('display','none')
-                $(this).popover('hide');
+                $(".bs-popover-auto").css('display','none');
+                if (typeof $(this).popover !== "undefined") { 
+                    $(this).popover('hide');
+                }
             });
         });
         function newexportaction(e, dt, button, config) {

+ 25 - 13
resources/views/livewire/records.blade.php

@@ -359,21 +359,33 @@
             <tbody id="checkall-target">
                 @php $count = 0; @endphp
                 @foreach($records as $record)
-                    <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'}}">{{$record->type == 'IN' ? formatPrice($record->amount) : ''}}</td>
-                        <td style="background-color:{{$count % 2 == 0 ? 'white' : '#f2f4f7'}}">{{$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
+                    @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>
+            @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>

+ 11 - 9
resources/views/livewire/records_old.blade.php

@@ -533,17 +533,19 @@
                     </div>
                 </div>
 
-                <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>
+                @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>
-                </div>
+                @endif
 
                 <div class="row mt-3" style="display: none;" id="emailAddressRow">
                     <div class="col-12">

+ 6 - 6
resources/views/livewire/reports.blade.php

@@ -27,7 +27,7 @@
         <div class="controls-section">
             <div class="control-group">
                 <label for="season-filter">Stagione di Riferimento:</label>
-                <select class="form-select" wire:model="seasonFilter" wire:change="updateCharts">
+                <select class="form-select" wire:model="seasonFilter" {{--wire:change="updateCharts"--}}>
                     @foreach($this->getAvailableSeasons() as $season)
                     <option value="{{ $season }}">{{ $season }}</option>
                     @endforeach
@@ -203,11 +203,6 @@
                     this.updateMonthlyTable(monthlyData);
                 });
 
-                @this.call('getYearlyTotals').then(yearlyData => {
-                    console.log('Got yearly data:', yearlyData);
-                    this.updateYearlyTable(yearlyData);
-                });
-
                 @this.call('getTopCausalsByAmount').then(causalsData => {
                     console.log('Got causals data:', causalsData);
                     this.createCausalsChart(originalSeasonKey, causalsData);
@@ -1279,6 +1274,11 @@
         document.addEventListener('DOMContentLoaded', function () {
             setTimeout(() => {
                 window.ReportsChartManager.updateMainCharts();
+                
+                @this.call('getYearlyTotals').then(yearlyData => {
+                    console.log('Got yearly data:', yearlyData);
+                    window.ReportsChartManager.updateYearlyTable(yearlyData);
+                });
             }, 100);
         });
 

+ 15 - 5
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);
@@ -484,7 +485,7 @@ Route::get('/get_record_in', function () {
                 ->leftJoin('receipts', 'records.id', '=', 'receipts.record_id')
                 ->where('records.type', 'IN');
 
-        $y = \App\Models\Record::select('records_rows.record_id', 'records_rows.amount', 'records.member_id', 'records.corrispettivo_fiscale', 'records.commercial', 'records.deleted', 'records.financial_movement', 'records_rows.causal_id', DB::raw('members.first_name as first_name'), DB::raw('members.last_name as last_name')) // , \DB::raw('SUM(records.id) As total'))
+        $y = \App\Models\Record::select('records_rows.record_id', 'records_rows.amount', 'records.member_id', 'records.corrispettivo_fiscale', 'records.commercial', 'records.deleted', 'records.financial_movement', 'records_rows.causal_id', 'records.payment_method_id', DB::raw('members.first_name as first_name'), DB::raw('members.last_name as last_name')) // , \DB::raw('SUM(records.id) As total'))
         ->leftJoin('members', 'records.member_id', '=', 'members.id')
         ->leftJoin('records_rows', 'records.id', '=', 'records_rows.record_id')
         //->leftJoin('receipts', 'records.id', '=', 'receipts.record_id')
@@ -589,6 +590,8 @@ Route::get('/get_record_in', function () {
     }
 
     $excludeCausals = [];
+    $causale_movimento_finanziario = \App\Models\Causal::where('name', "MOVIMENTO FINANZIARIO ENTRATA")->where('type', "IN")->pluck('id')->toArray();
+    $excludeCausals = $causale_movimento_finanziario;
     /*$borsellino = \App\Models\Causal::where('money', true)->first();
         if ($borsellino)
             $excludeCausals[] = $borsellino->id;*/
@@ -607,7 +610,8 @@ Route::get('/get_record_in', function () {
     $moneys = \App\Models\PaymentMethod::where('money', true)->pluck('id')->toArray();
 
     // Causale money
-    $moneysCausal = \App\Models\Causal::where('money', true)->pluck('id')->toArray();
+    // $moneysCausal = \App\Models\Causal::where('money', true)->pluck('id')->toArray();
+    $moneysCausal = [];
 
     $total = 0;
 
@@ -768,12 +772,18 @@ Route::get('/get_record_out', function () {
         $hasFilter = true;
     }
 
+    $excludeCausals = [];
+    $causale_movimento_finanziario = \App\Models\Causal::where('name', "MOVIMENTO FINANZIARIO USCITA")->where('type', "OUT")->pluck('id')->toArray();
+    $excludeCausals = $causale_movimento_finanziario;
+
     $total = 0;
     foreach ($x->get() as $r) {
         foreach ($r->rows as $rr) {
-            $total += $rr->amount;
-            if ($rr->vat_id > 0)
-                $total += getVatValue($rr->amount, $rr->vat_id);
+            if (!in_array($rr->causal_id, $excludeCausals)) {
+                $total += $rr->amount;
+                if ($rr->vat_id > 0)
+                    $total += getVatValue($rr->amount, $rr->vat_id);
+            }
         }
     }