add month year group for graph data

This commit is contained in:
Romulus21
2023-12-25 14:25:05 +01:00
parent 9382119442
commit 56ada87fdf
11 changed files with 248 additions and 63 deletions

View File

@@ -7,9 +7,7 @@ use App\Http\Resources\RainfallCollection;
use App\Http\Resources\RainfallResource;
use App\Models\Rainfall;
use Carbon\Carbon;
use Carbon\CarbonPeriod;
use Illuminate\Http\Request;
use Illuminate\Support\Collection;
class RainfallController extends Controller
{
@@ -88,48 +86,28 @@ class RainfallController extends Controller
$data = $request->validate([
'start' => 'date',
'end' => 'date',
'period' => ['regex:/^day|week|month|year$/'],
]);
$rainfalls = $request->user()
->rainfalls()
->whereBetween('date', [$data['start'], $data['end']])
->orderBy('date')
->get()
->groupBy('date');
->get();
$results = collect();
$index = 0;
foreach ($rainfalls as $date => $rainfall) {
if ($index === 0 && $date !== $data['start']) {
[$results, $index] = $this->addEmptyDays($results, $index, $data['start'], (new Carbon($date))->subDay());
} elseif ($index > 0 && (new Carbon($results->last()['date']))->addDay()->format('Y-m-d') !== $date) {
[$results, $index] = $this->addEmptyDays($results, $index, (new Carbon($results->last()['date']))->addDay(), (new Carbon($date))->subDay());
$results = [];
$currentDate = $data['start'];
while ($currentDate <= $data['end']) {
$key = Rainfall::getDateKey($currentDate, $data['period']);
if (! isset($results[$key])) {
$keyData = Rainfall::getDateKeyData($currentDate, $data);
$results[$key] = [...$keyData, 'value' => 0];
}
$results->push([
'id' => $index++,
'date' => $date,
'value' => $rainfall->sum('value'),
]);
$results[$key]['value'] += $rainfalls->where('date', new Carbon($currentDate))->sum('value');
$currentDate = (new Carbon($currentDate))->addDay()->format('Y-m-d');
}
if ($results->isNotEmpty() && $results->last()['date'] !== $data['end']) {
[$results] = $this->addEmptyDays($results, $index, (new Carbon($results->last()['date']))->addDay(), $data['end']);
}
return response()->json($results);
}
private function addEmptyDays(Collection $results, int $index, Carbon|string $start, Carbon|string $end)
{
foreach (CarbonPeriod::create($start, $end) as $date) {
$results->push([
'id' => $index++,
'date' => $date->format('Y-m-d'),
'value' => 0,
]);
}
return [$results, $index];
return response()->json(array_values($results));
}
}