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

102 lines
3.0 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';
private array $spiceIds = [];
protected function getOptions(): array
{
$spices = Spice::all();
$data = [];
$labels = [];
foreach ($spices as $spice) {
$this->spiceIds[] = $spice->id;
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 = collect($this->spiceIds)
->map(fn ($id) => url('/dashboard/rohstoffe/' . $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) {
return val + '' + opt.w.globals.labels[opt.dataPointIndex].match(/\((.*?)\)/)[1];
},
dropShadow: { enabled: true }
}
}
JS);
}
}