Explorar o código

modifiche calcolo totali reports e gestionale

ferrari hai 2 meses
pai
achega
65aab6ee5d
Modificáronse 2 ficheiros con 345 adicións e 377 borrados
  1. 124 292
      app/Http/Livewire/RecordINOUT.php
  2. 221 85
      app/Http/Livewire/Reports.php

+ 124 - 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;
 
@@ -192,40 +180,27 @@ class RecordINOUT extends Component
 
         $exclude_from_records = \App\Models\Member::where('exclude_from_records', true)->pluck('id')->toArray();
 
-        if (sizeof($this->datas) > 0)
-        {
-            foreach($this->datas as $filter)
-            {
-                // $filter = $m . "-" . $this->year;
-
+        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 +209,34 @@ 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;
-                    }
+                    $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 +245,34 @@ 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;
-                    }
+                    $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 +282,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 +298,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 +314,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 +326,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 +343,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 +398,7 @@ class RecordINOUT extends Component
                 break;
         }
         if ($m == 'x') {
-            $nextY = $y+1;
+            $nextY = $y + 1;
             $ret = "{$y}/{$nextY}";
         } else {
             $ret .= $y;
@@ -545,7 +422,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 +435,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 +465,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 +516,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 +545,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 +561,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 +572,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 +587,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 +605,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 +616,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 +631,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 +648,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 +656,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;
-
     }
-
 }

+ 221 - 85
app/Http/Livewire/Reports.php

@@ -165,9 +165,19 @@ class Reports extends Component
 
         $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 +186,37 @@ 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;
+            $amount += getVatValue($amount, $record->vat_id);
+
+            foreach ($matches[0] as $match) {
+                $m = explode("-", $match)[0];
 
-        $expenseRecords = DB::table('records')
+                $monthIndex = array_search($m, $monthOrder);
+                if ($monthIndex !== false) {
+                    $incomeData[$monthIndex] += $amount / $total_months;
+                }
+            }
+        }
+
+        $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 +225,33 @@ 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();
-
-        foreach ($incomeRecords as $record) {
-            $monthIndex = array_search($record->month_num, $monthOrder);
-            if ($monthIndex !== false) {
-                $incomeData[$monthIndex] = $record->total;
-            }
-        }
+            ->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) {
-            $monthIndex = array_search($record->month_num, $monthOrder);
-            if ($monthIndex !== false) {
-                $expenseData[$monthIndex] = $record->total;
+            $total_months = count(json_decode($record->when, true));
+            $matches = [];
+            if (!preg_match_all("/$pairs/", $record->when, $matches)) continue;
+
+            $amount = $record->amount;
+            $amount += getVatValue($amount, $record->vat_id);
+
+            foreach ($matches[0] as $match) {
+                $m = explode("-", $match)[0];
+
+                $monthIndex = array_search($m, $monthOrder);
+                if ($monthIndex !== false) {
+                    $expenseData[$monthIndex] += $amount / $total_months;
+                }
             }
         }
 
@@ -235,66 +279,101 @@ 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();
+        $incomeData = [];
+        $expenseData = [];
 
-        // Mappa anno/totale
-        $incomeByYear = $incomeRecords->pluck('total', 'year_num');
-        $expenseByYear = $expenseRecords->pluck('total', 'year_num');
+        $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;
 
-        // Unione di tutti gli anni presenti ordinati
-        $allYears = $incomeByYear->keys()
-            ->merge($expenseByYear->keys())
-            ->unique()
-            ->sort()
-            ->values();
+            $next_year = $year + 1;
 
-        // 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();
+            $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;
+                $amount += getVatValue($amount, $record->vat_id);
+                $amount *= ($matching_months / $total_months);
+                
+                $incomeData[$index] += $amount;
+            }
 
+            $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;
+                $amount += getVatValue($amount, $record->vat_id);
+                $amount *= ($matching_months / $total_months);
+                
+                $expenseData[$index] += $amount;
+            }
+        }
 
         return [
-            'labels' => $allYears->toArray(),
+            'labels' => $years_label,
             'datasets' => [
                 [
                     'label' => 'Entrate',
@@ -313,8 +392,23 @@ class Reports extends Component
     public function getYearlySummary()
     {
         $dateRange = $this->getSeasonDateRange($this->seasonFilter);
+        Log::info('=== getyearlyTotals called ===');
+
+        $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();
 
-        $totalIncome = 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);
+
+        $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 +417,32 @@ 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();
 
-        $totalExpenses = DB::table('records')
+        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;
+            $amount += getVatValue($amount, $record->vat_id);
+            $amount *= ($matching_months / $total_months);
+                
+            $totalIncome += $amount;
+        }
+
+        $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 +451,30 @@ 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;
+            $amount += getVatValue($amount, $record->vat_id);
+            $amount *= ($matching_months / $total_months);
+                
+            $totalExpenses += $amount;
+        }
 
         $delta = $totalIncome - $totalExpenses;
 
@@ -725,7 +861,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;