Files
SpiceManagementSystem/app/Filament/User/Resources/SpiceResource/Widgets/SpiceChart.php
T
2026-09-13 00:33:05 +02:00

101 lines
3.1 KiB
PHP

<?php
namespace App\Filament\User\Resources\SpiceResource\Widgets;
use Leandrocfe\FilamentApexCharts\Widgets\ApexChartWidget;
use Filament\Support\RawJs;
use App\Models\Spice;
class SpiceChart extends ApexChartWidget
{
protected static ?string $chartId = 'spiceChart';
protected static ?string $heading = 'Rohstoffmengen im Lager';
protected function getOptions(): array
{
$spices = Spice::orderBy('id')->get();
$data = [];
$labels = [];
foreach ($spices as $spice) {
if ($spice->unit === 'grams') {
$data[] = round($spice->quantity / 1000, 2);
$labels[] = $spice->name . ' (kg)';
} elseif ($spice->unit === 'pieces') {
$data[] = $spice->quantity;
$labels[] = $spice->name . ' (Stück)';
} elseif ($spice->unit === 'liter') {
$data[] = $spice->quantity;
$labels[] = $spice->name . ' (Liter)';
} else {
$data[] = $spice->quantity;
$labels[] = $spice->name . ' (' . ucfirst($spice->unit) . ')';
}
}
return [
'chart' => [
'type' => 'bar',
'height' => 300,
],
'series' => [
[
'name' => 'Bestand',
'data' => $data,
],
],
'xaxis' => [
'categories' => $labels,
'labels' => ['style' => ['fontFamily' => 'inherit']],
],
'yaxis' => [
'labels' => ['style' => ['fontFamily' => 'inherit']],
],
'colors' => ['#f59e0b'],
'plotOptions' => [
'bar' => ['borderRadius' => 3, 'horizontal' => false],
],
];
}
protected function extraJsOptions(): ?RawJs
{
$urls = Spice::orderBy('id')
->get()
->map(fn ($spice) => url('/dashboard/rohstoffe/' . $spice->id . '/edit'))
->values()
->toJson();
return RawJs::make(<<<JS
{
chart: {
events: {
dataPointSelection: function(event, chartContext, config) {
var urls = {$urls};
var url = urls[config.dataPointIndex];
if (url) window.location.href = url;
}
}
},
xaxis: {
labels: {
formatter: function (val) {
return val.replace('( ', '(');
}
}
},
dataLabels: {
enabled: true,
formatter: function (val, opt) {
var label = opt.w.globals.labels[opt.dataPointIndex];
var match = label ? label.match(/\((.*?)\)/) : null;
return val + (match ? match[1] : '');
},
dropShadow: { enabled: true }
}
}
JS);
}
}