1
0
forked from poc/pds

Added chart js plugin package and sets static label

This commit is contained in:
dhanabalan
2025-06-27 12:46:29 +05:30
parent fea6573a7a
commit 0fc1852ea2
14 changed files with 6141 additions and 695 deletions

View File

@@ -6,6 +6,7 @@ use App\Models\Line;
use App\Models\ProductionQuantity;
use App\Models\QualityValidation;
use Filament\Widgets\ChartWidget;
use Filament\Support\RawJs;
class CumulativeChart extends ChartWidget
{
@@ -163,6 +164,15 @@ class CumulativeChart extends ChartWidget
}
}
$nonFgData = array_map(function ($value) {
return ($value == 0 || is_null($value)) ? null : $value;
}, $nonFgData);
$fgData = array_map(function ($value) {
return ($value == 0 || is_null($value)) ? null : $value;
}, $fgData);
return [
'labels' => $labels,
'datasets' => array_filter([
@@ -186,8 +196,11 @@ class CumulativeChart extends ChartWidget
'data' => $fgData,
// 'backgroundColor' => '#ef4444', // Red for FG
],
]),
];
}
protected function getType(): string
@@ -208,6 +221,23 @@ class CumulativeChart extends ChartWidget
protected function getOptions(): array
{
return [
// 'plugins' => [
// 'datalabels' => false,
// ],
'plugins' => [
'datalabels' => [
'anchor' => 'start',
'align' => 'start',
'offset' => 4,
'color' => '#000',
'font' => [
'weight' => 'bold',
],
'formatter' => RawJs::make('function(value) {
return value;
}'),
],
],
'scales' => [
'y' => [
'beginAtZero' => true, //Start Y-axis from 0
@@ -219,4 +249,12 @@ class CumulativeChart extends ChartWidget
];
}
// public static function canView(): bool
// {
// return request()->routeIs([
// 'filament.pages.hourly-production',
// 'filament.admin.resources.production-quantities.create',
// ]);
// }
}

View File

@@ -6,6 +6,7 @@ use App\Models\GuardPatrolEntry;
use Carbon\Carbon;
use DB;
use Filament\Widgets\ChartWidget;
use Filament\Support\RawJs;
class GuardPatrolDayChart extends ChartWidget
{
@@ -42,7 +43,6 @@ class GuardPatrolDayChart extends ChartWidget
break;
}
$uniqueGuardNames = GuardPatrolEntry::join('guard_names', 'guard_patrol_entries.guard_name_id', '=', 'guard_names.id')
->where('guard_patrol_entries.plant_id', $selectedPlant)
->select('guard_names.id', 'guard_names.name')
@@ -99,6 +99,10 @@ class GuardPatrolDayChart extends ChartWidget
}
}
$chartData = array_map(function ($value) {
return ($value == 0 || is_null($value)) ? null : $value;
}, $chartData);
return [
'labels' => array_values($uniqueGuardNames),
'datasets' => [
@@ -143,27 +147,21 @@ class GuardPatrolDayChart extends ChartWidget
],
],
],
'plugins' => [
'datalabels' => [
'anchor' => 'start',
'align' => 'start',
'offset' => 4,
'color' => '#000',
'font' => [
'weight' => 'bold',
],
'formatter' => RawJs::make('function(value) {
return value;
}'),
],
],
];
}
// protected function getOptions(): array
// {
// return [
// 'scales' => [
// 'y' => [
// 'beginAtZero' => true, // Start Y-axis from 0
// 'ticks' => [
// 'stepSize' => 5,
// ],
// ],
// ],
// 'plugins' => [
// 'tooltip' => [
// 'callbacks' => [
// 'label' => "function(context) { return context.parsed.y + ' (min)'; }",
// ],
// ],
// ],
// ];
// }
}

View File

@@ -8,7 +8,7 @@ use App\Models\GuardPatrolEntry;
use Carbon\Carbon;
use DB;
use Filament\Widgets\ChartWidget;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Js;
class GuardPatrolHourlyChart extends ChartWidget
{
@@ -19,493 +19,6 @@ class GuardPatrolHourlyChart extends ChartWidget
protected int|string|array $columnSpan = 12;
// protected function getData(): array
// {
// $selectedPlant = session('selected_plant');
// $selectedDate = session('selected_date');
// $selectedGuardName = session('selected_name');
// $selectedTime = session('selected_time');
// $validSessions = session('valid_sessions', []);
// // if (empty($selectedTime) || !isset($validSessions[$selectedTime]) || !$validSessions[$selectedTime]) {
// // return [];
// // }
// if (!$selectedPlant || !$selectedDate || !$selectedGuardName || empty($selectedTime)) {
// return [];
// }
// if (empty($selectedTime) || !isset($validSessions[$selectedTime]) || !$validSessions[$selectedTime])
// {
// return $this->getInvalidSessionChartData();
// }
// $query = GuardPatrolEntry::where('plant_id', $selectedPlant)
// ->where('guard_name_id', $selectedGuardName)
// ->whereDate('patrol_time', $selectedDate);
// if (!empty($selectedTime)) {
// [$startTime, $endTime] = explode(' - ', $selectedTime);
// $startDateTime = Carbon::parse($selectedDate . ' ' . $startTime);
// $endDateTime = Carbon::parse($selectedDate . ' ' . $endTime);
// $query->whereBetween('guard_patrol_entries.patrol_time', [$startDateTime, $endDateTime]);
// }
// // $patrols = $query->orderBy('guard_patrol_entries.patrol_time')->get();
// $patrols = $query->orderBy('patrol_time')->get();
// if ($patrols->count() < 2) {
// return [];
// }
// // Get all CheckPointTime records for the plant
// $cushioningData = CheckPointTime::where('plant_id', $selectedPlant)
// ->orderBy('sequence_number')
// ->get(['sequence_number', 'min_cushioning', 'max_cushioning', 'check_point1_id', 'check_point2_id'])
// ->keyBy('sequence_number');
// // Get all unique checkpoint IDs from CheckPointTime
// $checkPointIds = collect($cushioningData)
// ->flatMap(function ($item) {
// return [$item->check_point1_id, $item->check_point2_id];
// })
// ->unique();
// $checkPointNames = CheckPointName::whereIn('id', $checkPointIds)
// ->pluck('name', 'id');
// $sequenceToName = [];
// //$sequenceNumbers = [];
// foreach ($cushioningData as $sequenceNumber => $data)
// {
// $lastNameId = $data->check_point2_id;
// $name = $checkPointNames[$lastNameId] ?? null;
// if ($name)
// {
// $sequenceToName[$sequenceNumber] = $name;
// //$sequenceNumbers[] = $sequenceNumber;
// }
// }
// $numSequences = count($sequenceToName);
// // Prepare chart data
// $intervals = [];
// $labels = [];
// $colors = [];
// for ($i = 0; $i < $patrols->count() - 1; $i++)
// {
// $current = Carbon::parse($patrols[$i]->patrol_time);
// $next = Carbon::parse($patrols[$i+1]->patrol_time);
// $interval = $next->diffInMinutes($current, true);
// $intervals[] = $interval;
// // if ($next < $current)
// // {
// // $colors[] = '#ff4c4c'; // Red for out-of-order
// // // $intervals[] = $interval;
// // $intervals[] = 0;
// // $labels[] = "Seq " . ($i + 1);
// // continue;
// // }
// $sequenceNumber = ($i % $numSequences) + 1;
// $labels[] = "Seq " . ($i + 1);
// $cushioning = $cushioningData[$sequenceNumber] ?? null;
// if (!$cushioning) {
// $colors[] = '#cccccc';
// continue;
// }
// $min = $cushioning->min_cushioning;
// $max = $cushioning->max_cushioning;
// if ($interval < $min) {
// $colors[] = '#ffd700';
// } elseif ($interval <= $max) {
// $colors[] = '#4caf50';
// } else {
// $colors[] = '#ff4c4c';
// }
// }
// return [
// 'labels' => $labels,
// 'datasets' => [
// [
// 'label' => 'Interval (minutes)',
// 'data' => $intervals,
// 'backgroundColor' => $colors,
// 'borderColor' => '#333',
// 'borderWidth' => 1,
// ],
// ],
// ];
// }
// protected function getData(): array
// {
// $selectedPlant = session('selected_plant');
// $selectedDate = session('selected_date');
// $selectedGuardName = session('selected_name');
// $selectedTime = session('selected_time');
// if (!$selectedPlant || !$selectedDate || !$selectedGuardName || empty($selectedTime)) {
// return [];
// }
// $query = GuardPatrolEntry::where('plant_id', $selectedPlant)
// ->where('guard_name_id', $selectedGuardName)
// ->whereDate('patrol_time', $selectedDate);
// if (!empty($selectedTime)) {
// [$startTime, $endTime] = explode(' - ', $selectedTime);
// $startDateTime = Carbon::parse($selectedDate . ' ' . $startTime);
// $endDateTime = Carbon::parse($selectedDate . ' ' . $endTime);
// $query->whereBetween('guard_patrol_entries.patrol_time', [$startDateTime, $endDateTime]);
// }
// $patrols = $query->orderBy('patrol_time')->get();
// if ($patrols->count() < 2) {
// return [];
// }
// // Get all CheckPointTime records for the plant
// $checkPointTimes = CheckPointTime::where('plant_id', $selectedPlant)
// ->orderBy('sequence_number')
// ->get(['sequence_number', 'min_cushioning', 'max_cushioning', 'check_point1_id', 'check_point2_id']);
// // Build the expected sequence
// $expectedSequence = [];
// foreach ($checkPointTimes as $row) {
// $expectedSequence[] = $row->check_point1_id;
// }
// if ($checkPointTimes->isNotEmpty()) {
// $expectedSequence[] = $checkPointTimes->last()->check_point2_id;
// }
// $intervals = [];
// $labels = [];
// $colors = [];
// $cushioningData = $checkPointTimes->keyBy('sequence_number');
// for ($i = 0; $i < $patrols->count() - 1; $i++) {
// $current = Carbon::parse($patrols[$i]->patrol_time);
// $next = Carbon::parse($patrols[$i+1]->patrol_time);
// $interval = $next->diffInMinutes($current, true);
// $intervals[] = $interval;
// $labels[] = "Seq " . ($i + 1);
// if ($i < count($expectedSequence)) {
// $expectedCheckpoint = $expectedSequence[$i];
// $actualCheckpoint = $patrols[$i]->check_point_name_id;
// if ($expectedCheckpoint != $actualCheckpoint) {
// $colors[] = '#ff4c4c';
// continue;
// }
// } else {
// $colors[] = '#ff4c4c';
// continue;
// }
// $sequenceNumber = ($i % $checkPointTimes->count()) + 1;
// $cushioning = $cushioningData[$sequenceNumber] ?? null;
// if (!$cushioning) {
// $colors[] = '#cccccc';
// continue;
// }
// $min = $cushioning->min_cushioning;
// $max = $cushioning->max_cushioning;
// if ($interval < $min) {
// $colors[] = '#ffd700'; // Yellow for too fast
// } elseif ($interval <= $max) {
// $colors[] = '#4caf50'; // Green for good
// } else {
// $colors[] = '#ff4c4c'; // Red for too slow
// }
// }
// return [
// 'labels' => $labels,
// 'datasets' => [
// [
// 'label' => 'Interval (minutes)',
// 'data' => $intervals,
// 'backgroundColor' => $colors,
// 'borderColor' => '#333',
// 'borderWidth' => 1,
// ],
// ],
// ];
// }
// protected function getData(): array
// {
// $selectedPlant = session('selected_plant'); // Or get from request/argument
// $selectedDate = session('selected_date'); // Or get from request/argument
// $selectedGuardName = session('selected_name'); // Or get from request/argument
// $selectedTime = session('selected_time'); // Or get from request/argument
// // Optional: If you want to avoid sessions entirely, pass these as arguments to the function.
// // For now, we'll keep them as session for minimal change.
// if (!$selectedPlant || !$selectedDate || !$selectedGuardName || empty($selectedTime)) {
// return [];
// }
// $query = GuardPatrolEntry::where('plant_id', $selectedPlant)
// ->where('guard_name_id', $selectedGuardName)
// ->whereDate('patrol_time', $selectedDate);
// if (!empty($selectedTime)) {
// [$startTime, $endTime] = explode(' - ', $selectedTime);
// $startDateTime = Carbon::parse($selectedDate . ' ' . $startTime);
// $endDateTime = Carbon::parse($selectedDate . ' ' . $endTime);
// $query->whereBetween('guard_patrol_entries.patrol_time', [$startDateTime, $endDateTime]);
// }
// $patrols = $query->orderBy('patrol_time')->get();
// if ($patrols->count() < 2) {
// return [];
// }
// // Get all CheckPointTime records for the plant
// $checkPointTimes = CheckPointTime::where('plant_id', $selectedPlant)
// ->orderBy('sequence_number')
// ->get(['sequence_number', 'min_cushioning', 'max_cushioning', 'check_point1_id', 'check_point2_id']);
// // Build the expected sequence
// $expectedSequence = [];
// foreach ($checkPointTimes as $row) {
// $expectedSequence[] = $row->check_point1_id;
// }
// if ($checkPointTimes->isNotEmpty()) {
// $expectedSequence[] = $checkPointTimes->last()->check_point2_id;
// }
// // Prepare chart data
// $intervals = [];
// $labels = [];
// $colors = [];
// // Key cushioning data by sequence_number
// $cushioningData = $checkPointTimes->keyBy('sequence_number');
// // Track if any sequence matches
// $anySequenceMatches = false;
// // For each interval (between patrols)
// for ($i = 0; $i < $patrols->count() - 1; $i++) {
// // Check if the current checkpoint matches the expected sequence
// if ($i < count($expectedSequence)) {
// $expectedCheckpoint = $expectedSequence[$i];
// $actualCheckpoint = $patrols[$i]->check_point_name_id;
// if ($expectedCheckpoint == $actualCheckpoint) {
// $anySequenceMatches = true;
// }
// }
// }
// // If no sequence matches at all, show only "X"
// if (!$anySequenceMatches) {
// return [
// 'labels' => ['X'],
// 'datasets' => [
// [
// 'label' => 'Interval (minutes)',
// 'data' => [0],
// 'backgroundColor' => ['#ff4c4c'],
// 'borderColor' => '#333',
// 'borderWidth' => 1,
// ],
// ],
// ];
// }
// // Otherwise, show the intervals as before
// for ($i = 0; $i < $patrols->count() - 1; $i++) {
// $current = Carbon::parse($patrols[$i]->patrol_time);
// $next = Carbon::parse($patrols[$i+1]->patrol_time);
// $interval = $next->diffInMinutes($current, true);
// $intervals[] = $interval;
// $labels[] = "Seq " . ($i + 1);
// // Check if the current checkpoint matches the expected sequence
// if ($i < count($expectedSequence)) {
// $expectedCheckpoint = $expectedSequence[$i];
// $actualCheckpoint = $patrols[$i]->check_point_name_id;
// if ($expectedCheckpoint != $actualCheckpoint) {
// $colors[] = '#ff4c4c';
// continue;
// }
// } else {
// $colors[] = '#ff4c4c';
// continue;
// }
// // If sequence is correct, apply cushioning logic
// $sequenceNumber = ($i % $checkPointTimes->count()) + 1;
// $cushioning = $cushioningData[$sequenceNumber] ?? null;
// if (!$cushioning) {
// $colors[] = '#cccccc';
// continue;
// }
// $min = $cushioning->min_cushioning;
// $max = $cushioning->max_cushioning;
// if ($interval < $min) {
// $colors[] = '#ffd700';
// } elseif ($interval <= $max) {
// $colors[] = '#4caf50';
// } else {
// $colors[] = '#ff4c4c';
// }
// }
// return [
// 'labels' => $labels,
// 'datasets' => [
// [
// 'label' => 'Interval (minutes)',
// 'data' => $intervals,
// 'backgroundColor' => $colors,
// 'borderColor' => '#333',
// 'borderWidth' => 1,
// ],
// ],
// ];
// }
// protected function getData(): array
// {
// $selectedPlant = session('selected_plant');
// $selectedDate = session('selected_date');
// $selectedGuardName = session('selected_name');
// $selectedTime = session('selected_time');
// if (!$selectedPlant || !$selectedDate || !$selectedGuardName || empty($selectedTime)) {
// return [];
// }
// $query = GuardPatrolEntry::where('plant_id', $selectedPlant)
// ->where('guard_name_id', $selectedGuardName)
// ->whereDate('patrol_time', $selectedDate);
// if (!empty($selectedTime)) {
// [$startTime, $endTime] = explode(' - ', $selectedTime);
// $startDateTime = Carbon::parse($selectedDate . ' ' . $startTime);
// $endDateTime = Carbon::parse($selectedDate . ' ' . $endTime);
// $query->whereBetween('guard_patrol_entries.patrol_time', [$startDateTime, $endDateTime]);
// }
// $patrols = $query->orderBy('patrol_time')->get();
// if ($patrols->count() < 2) {
// return [];
// }
// // Get all CheckPointTime records for the plant
// $checkPointTimes = CheckPointTime::where('plant_id', $selectedPlant)
// ->orderBy('sequence_number')
// ->get(['sequence_number', 'min_cushioning', 'max_cushioning', 'check_point1_id', 'check_point2_id']);
// // Build the expected sequence
// $expectedSequence = [];
// foreach ($checkPointTimes as $row) {
// $expectedSequence[] = $row->check_point1_id;
// }
// if ($checkPointTimes->isNotEmpty()) {
// $expectedSequence[] = $checkPointTimes->last()->check_point2_id;
// }
// // Prepare chart data
// $intervals = [];
// $labels = [];
// $colors = [];
// $cushioningData = $checkPointTimes->keyBy('sequence_number');
// // Track the current position in the expected sequence
// $currentSeqIndex = 0;
// $anySequenceMatches = false;
// for ($i = 0; $i < $patrols->count() - 1; $i++) {
// $current = Carbon::parse($patrols[$i]->patrol_time);
// $next = Carbon::parse($patrols[$i+1]->patrol_time);
// $interval = $next->diffInMinutes($current, true);
// $intervals[] = $interval;
// $labels[] = "Seq " . ($i + 1);
// // Check if current patrol's checkpoint matches the next expected
// if ($currentSeqIndex < count($expectedSequence) && $patrols[$i]->check_point_name_id == $expectedSequence[$currentSeqIndex]) {
// $currentSeqIndex++;
// $anySequenceMatches = true;
// // Apply cushioning logic for valid sequence
// $sequenceNumber = ($currentSeqIndex - 1) % $checkPointTimes->count() + 1;
// $cushioning = $cushioningData[$sequenceNumber] ?? null;
// if (!$cushioning) {
// $colors[] = '#cccccc';
// continue;
// }
// $min = $cushioning->min_cushioning;
// $max = $cushioning->max_cushioning;
// if ($interval < $min) {
// $colors[] = '#ffd700';
// } elseif ($interval <= $max) {
// $colors[] = '#4caf50';
// } else {
// $colors[] = '#ff4c4c';
// }
// } else {
// // Out of order: mark as red
// $colors[] = '#ff4c4c';
// }
// }
// // If no sequence matches at all, show only "X"
// if (!$anySequenceMatches) {
// return [
// 'labels' => ['X'],
// 'datasets' => [
// [
// 'label' => 'Interval (minutes)',
// 'data' => [0],
// 'backgroundColor' => ['#ff4c4c'],
// 'borderColor' => '#333',
// 'borderWidth' => 1,
// ],
// ],
// ];
// }
// return [
// 'labels' => $labels,
// 'datasets' => [
// [
// 'label' => 'Interval (minutes)',
// 'data' => $intervals,
// 'backgroundColor' => $colors,
// 'borderColor' => '#333',
// 'borderWidth' => 1,
// ],
// ],
// ];
// }
protected function getData(): array
{
$selectedPlant = session('selected_plant');
@@ -567,7 +80,9 @@ class GuardPatrolHourlyChart extends ChartWidget
for ($i = 0; $i < $patrols->count() - 1; $i++) {
$current = Carbon::parse($patrols[$i]->patrol_time);
$next = Carbon::parse($patrols[$i+1]->patrol_time);
$interval = $next->diffInMinutes($current, true);
// $interval = $next->diffInMinutes($current, true);
$diffInSeconds = $next->floatDiffInRealSeconds($current, true); // get float seconds
$interval = round($diffInSeconds / 60, 2);
$intervals[] = $interval;
$labels[] = "Seq " . ($i + 1);
@@ -630,6 +145,7 @@ class GuardPatrolHourlyChart extends ChartWidget
protected function getOptions(): array
{
return [
'scales' => [
'y' => [
'beginAtZero' => true, //Start Y-axis from 0
@@ -638,25 +154,46 @@ class GuardPatrolHourlyChart extends ChartWidget
],
],
],
'plugins' => [
'datalabels' => [
'anchor' => 'start',
'align' => 'end',
'color' => '#000',
'font' => [
'weight' => 'bold',
],
//'formatter' => Js::raw('function(value) { return Number(value).toFixed(2) + " min"; }'),
//'formatter' => 'function(value) { return Number(value).toFixed(2) + " min"; }',
'formatter' => Js::from("function(value) { return Number(value).toFixed(2) + ' min'; }"),
//'formatter' => Js::from(new \Illuminate\Support\Stringable('function(value) { return Number(value).toFixed(2) + " min"; }')),
],
],
];
}
// protected function getOptions(): array
// {
// return [
// 'plugins' => [
// 'datalabels' => [
// 'anchor' => 'end',
// 'align' => 'top',
// 'color' => '#000',
// 'font' => [
// 'weight' => 'bold',
// ],
// 'formatter' => \Illuminate\Support\Js::from("function(value) { return value + ' min'; }"),
// ],
// ],
// ];
// }
// protected function getOptions(): array
// {
// return json_decode(json_encode([
// 'plugins' => [
// 'datalabels' => [
// 'anchor' => 'end',
// 'align' => 'start',
// 'offset' => 4,
// 'color' => '#000',
// 'font' => [
// 'weight' => 'bold',
// ],
// 'formatter' => null, // temporarily set null
// ],
// ],
// 'scales' => [
// 'y' => [
// 'beginAtZero' => true,
// ],
// ],
// ]), true);
// }
protected function getType(): string
{

View File

@@ -7,6 +7,7 @@ use App\Models\Line;
use App\Models\Plant;
use DB;
use Filament\Widgets\ChartWidget;
use Illuminate\Support\Js;
class InvoiceChart extends ChartWidget
{
@@ -356,12 +357,43 @@ class InvoiceChart extends ChartWidget
return 'invoice-chart';
}
// protected function getOptions(): array
// {
// return [
// 'scales' => [
// 'y' => [
// 'beginAtZero' => true, //Start Y-axis from 0
// 'ticks' => [
// 'stepSize' => 1,
// ],
// ],
// ],
// ];
// }
protected function getOptions(): array
{
return [
// 'plugins' => [
// 'datalabels' => [
// // 'anchor' => 'start',
// // 'align' => 'start',
// // 'offset' => 1,
// 'anchor' => 'start',
// 'align' => 'start',
// 'offset' => 8,
// 'color' => '#000',
// 'font' => [
// 'weight' => 'bold',
// ],
// 'formatter' => Js::from("function(value) { return Number(value); }"),
// ],
// ],
'plugins' => [
'datalabels' => false, // Disable datalabels plugin properly
],
'scales' => [
'y' => [
'beginAtZero' => true, //Start Y-axis from 0
'beginAtZero' => true,
'ticks' => [
'stepSize' => 1,
],

View File

@@ -14,7 +14,7 @@ class ItemOverview extends ChartWidget
protected int|string|array $columnSpan = '12';
protected static ?string $maxHeight = '350px';
protected static ?string $maxHeight = '400px';
protected $listeners = ['filtersUpdated' => '$refresh'];
@@ -116,6 +116,10 @@ class ItemOverview extends ChartWidget
$labels = array_map(fn ($hour) => date("g A", strtotime("$hour:00")), $shiftedKeys);
}
// $orderedData = array_map(function ($value) {
// return ($value == 0 || is_null($value)) ? null : $value;
// }, $orderedData);
return [
'datasets' => [
[
@@ -126,11 +130,11 @@ class ItemOverview extends ChartWidget
default => $isFgLine ? "Today's FG Count" : "Today's Hourly Production",
},
'data' => $orderedData,
'interaction' => [
'mode' => 'nearest',
'axis' => 'x',
'intersect' => false,
],
// 'interaction' => [
// 'mode' => 'nearest',
// 'axis' => 'x',
// 'intersect' => false,
// ],
'borderColor' => 'rgba(75, 192, 192, 1)',
'backgroundColor' => 'rgba(75, 192, 192, 0.2)',
'fill' => false,
@@ -146,10 +150,34 @@ class ItemOverview extends ChartWidget
return 'line';
}
// protected function getOptions(): array
// {
// return [
// 'scales' => [
// 'y' => [
// 'beginAtZero' => true,
// 'ticks' => [
// 'stepSize' => 0.5,
// ],
// ],
// ],
// ];
// }
protected function getOptions(): array
{
return [
'plugins' => [
'datalabels' => [
'anchor' => 'start',
'color' => '#000',
'font' => [
'weight' => 'bold',
],
'formatter' => 'function(value) { return Number(value); }',
],
],
'scales' => [
'y' => [
'beginAtZero' => true,
@@ -162,6 +190,7 @@ class ItemOverview extends ChartWidget
}
protected function getFilters(): ?array
{
return [

View File

@@ -158,14 +158,17 @@ class ProductionLineStopChart extends ChartWidget
protected function getOptions(): array
{
return [
'responsive' => true,
'plugins' => [
'legend' => [
'position' => 'bottom',
],
'tooltip' => [
'enabled' => true, // Tooltips enabled on hover
],
// 'responsive' => true,
// 'plugins' => [
// 'legend' => [
// 'position' => 'bottom',
// ],
// 'tooltip' => [
// 'enabled' => true, // Tooltips enabled on hover
// ],
// ],
'plugins' => [
'datalabels' => false,
],
'scales' => [
'x' => [

View File

@@ -2,7 +2,11 @@
namespace App\Filament\Widgets;
use App\Models\Line;
use Filament\Widgets\ChartWidget;
use Illuminate\Support\Js;
use Filament\Support\RawJs;
use Illuminate\Support\Stringable;
class ProductionOrderChart extends ChartWidget
{
@@ -10,70 +14,93 @@ class ProductionOrderChart extends ChartWidget
protected int|string|array $columnSpan = 12;
protected static ?string $maxHeight = '330px';
protected $listeners = ['productionOrderChart'];
protected function getData(): array
{
$activeFilter = $this->filter;
$selectedPlant = session('selected_plant');
$selectedLine = session('selected_line');
$productionOrder = session('production_order');
if (!$selectedPlant || !$selectedLine || !$productionOrder)
{
return [
'datasets' => [],
'labels' => [],
];
}
$activeFilter = $this->filter;
if ($activeFilter === 'yesterday') {
$startDate = now()->subDay()->setTime(8, 0, 0); // yesterday 8:00 AM
$endDate = now()->setTime(8, 0, 0); // today 8:00 AM
$groupBy = 'EXTRACT(HOUR FROM production_quantities.created_at)';
}
else if ($activeFilter === 'this_week') {
// Monday 8:00 AM of the current week
$startDate = now()->startOfWeek()->setTime(8, 0, 0);
$selectedPlant = session('selected_plant');
$selectedLine = session('selected_line');
$productionOrder = session('production_order');
// Next Monday 8:00 AM (end of Sunday + 8 hrs)
$endDate = now()->endOfWeek()->addDay()->setTime(8, 0, 0);
if (!$selectedPlant || !$selectedLine || !$productionOrder) {
return [
'datasets' => [],
'labels' => [],
];
}
$groupBy = 'EXTRACT(DOW FROM production_quantities.created_at)'; // Group by day of week
}
// 1. Check line type
$lineType = Line::where('id', $selectedLine)->value('type');
else if ($activeFilter === 'this_month') {
$startDate = now()->startOfMonth();
$endDate = now()->endOfMonth();
$groupBy = "FLOOR((EXTRACT(DAY FROM production_quantities.created_at) - 1) / 7) + 1";
}
else
{
$startDate = now()->setTime(8, 0, 0); // today at 8:00 AM
$endDate = now()->copy()->addDay()->setTime(8, 0, 0); // tomorrow at 8:00 AM
$groupBy = 'EXTRACT(HOUR FROM production_quantities.created_at)';
}
// 2. Set base table and columns depending on line type
if ($lineType == 'FG Line')
{
$table = 'quality_validations';
$dateColumn = 'created_at'; // adjust if your date column is named differently
$plantColumn = 'plant_id';
$lineColumn = 'line_id';
$orderColumn = 'production_order';
}
else
{
$table = 'production_quantities';
$dateColumn = 'created_at';
$plantColumn = 'plant_id';
$lineColumn = 'line_id';
$orderColumn = 'production_order';
}
// 3. Set filter logic as before
if ($activeFilter == 'yesterday')
{
$startDate = now()->subDay()->setTime(8, 0, 0);
$endDate = now()->setTime(8, 0, 0);
$groupBy = "EXTRACT(HOUR FROM $table.$dateColumn)";
}
else if ($activeFilter == 'this_week')
{
$startDate = now()->startOfWeek()->setTime(8, 0, 0);
$endDate = now()->endOfWeek()->addDay()->setTime(8, 0, 0);
$groupBy = "EXTRACT(DOW FROM $table.$dateColumn)";
}
else if ($activeFilter == 'this_month')
{
$startDate = now()->startOfMonth();
$endDate = now()->endOfMonth();
$groupBy = "FLOOR((EXTRACT(DAY FROM $table.$dateColumn) - 1) / 7) + 1";
}
else
{
$startDate = now()->setTime(8, 0, 0);
$endDate = now()->copy()->addDay()->setTime(8, 0, 0);
$groupBy = "EXTRACT(HOUR FROM $table.$dateColumn)";
}
$query = \DB::table('production_quantities')
->join('plants', 'production_quantities.plant_id', '=', 'plants.id')
->join('lines', 'production_quantities.line_id', '=', 'lines.id')
->selectRaw("$groupBy AS time_unit, count(*) AS total_quantity")
->whereBetween('production_quantities.created_at', [$startDate, $endDate])
->where('plants.id', $selectedPlant)
->where('lines.id', $selectedLine)
->when($productionOrder, fn($q) => $q->where('production_quantities.production_order', $productionOrder))
->groupByRaw($groupBy)
->orderByRaw($groupBy)
->pluck('total_quantity', 'time_unit')
->toArray();
if ($activeFilter === 'this_month') {
$weeksCount = ceil($endDate->day / 7); // Calculate total weeks dynamically
$allWeeks = array_fill(1, $weeksCount, 0); // Initialize all weeks with 0
$data = array_replace($allWeeks, $query); // Fill missing weeks with 0
// 4. Build the query dynamically
$query = \DB::table($table)
->join('plants', "$table.$plantColumn", '=', 'plants.id')
->join('lines', "$table.$lineColumn", '=', 'lines.id')
->selectRaw("$groupBy AS time_unit, count(*) AS total_quantity")
->whereBetween("$table.$dateColumn", [$startDate, $endDate])
->where('plants.id', $selectedPlant)
->where('lines.id', $selectedLine)
->when($productionOrder, fn($q) => $q->where("$table.$orderColumn", $productionOrder))
->groupByRaw($groupBy)
->orderByRaw($groupBy)
->pluck('total_quantity', 'time_unit')
->toArray();
if ($activeFilter == 'this_month')
{
$weeksCount = ceil($endDate->day / 7);
$allWeeks = array_fill(1, $weeksCount, 0);
$data = array_replace($allWeeks, $query);
// Generate dynamic week labels
$labels = [];
for ($i = 1; $i <= $weeksCount; $i++) {
$weekStart = $startDate->copy()->addDays(($i - 1) * 7)->format('d M');
@@ -83,19 +110,13 @@ class ProductionOrderChart extends ChartWidget
$orderedData = array_values($data);
}
else if ($activeFilter === 'this_week') {
// Correct week labels: ['Mon', 'Tue', ..., 'Sun']
else if ($activeFilter == 'this_week')
{
$labels = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
// Initialize default data for all 7 days
$data = array_fill(0, 7, 0);
// Fill in data from query results
foreach ($query as $dow => $count) {
$data[$dow] = $count;
}
// Ensure days are ordered from Monday to Sunday
$orderedData = [
$data[1] ?? 0, // Monday
$data[2] ?? 0, // Tuesday
@@ -103,42 +124,55 @@ class ProductionOrderChart extends ChartWidget
$data[4] ?? 0, // Thursday
$data[5] ?? 0, // Friday
$data[6] ?? 0, // Saturday
$data[0] ?? 0, // Sunday (move to last)
$data[0] ?? 0, // Sunday
];
}
else
{
// Hourly data (same as before)
$allHours = array_fill(0, 24, 0);
$data = array_replace($allHours, $query);
$allHours = array_fill(0, 24, 0);
$data = array_replace($allHours, $query);
// Shift hours for proper display (8 AM to 7 AM)
$shiftedKeys = array_merge(range(8, 23), range(0, 8));
$orderedData = array_map(fn($hour) => $data[$hour], $shiftedKeys);
$shiftedKeys = array_merge(range(8, 23), range(0, 8));
$orderedData = array_map(fn($hour) => $data[$hour], $shiftedKeys);
// Labels: ["8 AM", "9 AM", ..., "7 AM"]
$labels = array_map(fn ($hour) => date("g A", strtotime("$hour:00")), $shiftedKeys);
$labels = array_map(fn ($hour) => date("g A", strtotime("$hour:00")), $shiftedKeys);
}
$orderedData = array_map(function ($value) {
return ($value == 0 || is_null($value)) ? null : $value;
}, $orderedData);
return [
'datasets' => [
[
'label' => match ($activeFilter)
{
'this_week' => $lineType == 'FG Line'
? "Daily Fg Production Order Count This Week"
: "Daily Production Order Count This Week",
'this_month' => $lineType == 'FG Line'
? "Weekly Fg Production Order Count This Month"
: "Weekly Production Order Count This Month",
'yesterday' => $lineType == 'FG Line'
? "Yesterday's Hourly Fg Order Count Production"
: "Yesterday's Hourly Order Count Production",
default => $lineType == 'FG Line'
? "Today's Hourly Fg Production Order Count"
: "Today's Hourly Production Order Count",
},
'data' => $orderedData,
'borderColor' => 'rgba(75, 192, 192, 1)',
'backgroundColor' => 'rgba(75, 192, 192, 0.2)',
'fill' => false,
'tension' => 0.3,
],
],
'labels' => $labels,
];
}
return [
'datasets' => [
[
'label' => match ($activeFilter) {
'this_week' => "Daily Production Order Count This Week",
'this_month' => "Weekly Production Order Count This Month", // Updated Label
'yesterday' => "Yesterday's Hourly Order Count Production",
default => "Today's Hourly Production Order Count",
},
'data' => $orderedData,
'borderColor' => 'rgba(75, 192, 192, 1)',
'backgroundColor' => 'rgba(75, 192, 192, 0.2)',
'fill' => false,
'tension' => 0.3,
],
],
'labels' => $labels,
];
}
protected function getType(): string
{
return 'bar';
@@ -147,7 +181,21 @@ class ProductionOrderChart extends ChartWidget
protected function getOptions(): array
{
return [
'plugins' => [
'datalabels' => [
// 'anchor' => 'start',
// 'align' => 'start',
// 'offset' => 1,
'anchor' => 'start',
'align' => 'start',
'offset' => 8,
'color' => '#000',
'font' => [
'weight' => 'bold',
],
'formatter' => Js::from("function(value) { return Number(value); }"),
],
],
'scales' => [
'y' => [
'beginAtZero' => true,

View File

@@ -41,6 +41,9 @@ class AppServiceProvider extends ServiceProvider
// FilamentAsset::register([
// Js::make('chart-js-plugins', Vite::asset('resources/js/filament-chart-js-plugins.js'))->module(),
// ]);
FilamentAsset::register([
Js::make('chart-js-plugins', Vite::asset('resources/js/filament-chart-js-plugins.js'))->module(),
]);
// URL::forceScheme('https');