Files
dashboard/components/FcrDashboardPage.tsx
T

514 lines
18 KiB
TypeScript

import React, { useCallback, useEffect, useMemo, useState } from 'react';
import {
CartesianGrid,
Line,
LineChart,
ResponsiveContainer,
Tooltip,
XAxis,
YAxis,
} from 'recharts';
import {
formatNumber as formatNumberUtil,
formatDecimal,
formatNullable,
} from '../utils/formatters.ts';
import { PageAiInsight } from './shared/PageAiInsight.tsx';
interface FcrApiKpi {
food_total?: number;
iot_weight?: number;
chicken_life?: number;
harvest_weight_total?: number;
iot_fcr?: number;
}
interface FcrSupportRow {
day: number;
feedTotal: number;
iotWeight: number | null;
chickenLife: number;
harvestWeightTotal: number;
iotFcr: number | null;
}
type FcrApiKpiData = Record<string, FcrApiKpi>;
interface FcrApiResponse {
success?: boolean;
data?: {
kpi?: FcrApiKpiData;
};
}
interface SupportingChartPoint {
day: number;
feedTotal: number;
iotWeight: number | null;
chickenLife: number;
harvestWeightKg: number;
}
interface FcrTrendPoint {
day: number;
iotFcr: number | null;
}
const FCR_CAGE_API_URL =
'https://dashboard.cpsp.id/api/scales/cage/9f556d2a-af5c-41b0-bcd0-6cea0dfa0fed';
const toValidFcr = (value: number | undefined): number | null => {
return value !== undefined && value > 0 ? value : null;
};
// Use centralized formatters
const formatNumber = (value: number, maximumFractionDigits = 0): string => {
return formatNumberUtil(value, { maxDecimals: maximumFractionDigits });
};
const formatFcr = (value: number | null): string => {
return formatNullable(value, (v) => {
const truncatedValue = Math.trunc(v * 1000) / 1000;
return formatNumberUtil(truncatedValue, { minDecimals: 3, maxDecimals: 3 });
});
};
const formatNullableNumber = (value: number | null, maximumFractionDigits = 0): string => {
return formatNullable(value, (v) => formatNumber(v, maximumFractionDigits));
};
const formatHarvestWeightKg = (valueInGrams: number): string => {
return formatDecimal(valueInGrams / 1000, { maxDecimals: 1 });
};
const fetchLiveFcrKpiData = async (): Promise<FcrApiKpiData> => {
const response = await fetch(FCR_CAGE_API_URL);
if (!response.ok) {
throw new Error(`API request failed with status ${response.status}`);
}
const jsonData = (await response.json()) as FcrApiResponse;
if (!jsonData.success || !jsonData.data || !jsonData.data.kpi) {
throw new Error('Invalid data structure from FCR API');
}
return jsonData.data.kpi;
};
const formatTooltipValue = (
value: unknown,
unit: string,
maximumFractionDigits: number
): string => {
return typeof value === 'number' ? `${formatNumber(value, maximumFractionDigits)} ${unit}` : '-';
};
const StatCard: React.FC<{
title: string;
value: string;
unit: string;
}> = ({ title, value, unit }) => (
<div className="bg-white rounded-xl shadow-sm border border-gray-100 p-5">
<p className="text-sm font-semibold text-gray-500">{title}</p>
<div className="mt-2 flex items-baseline gap-2">
<span className="text-2xl font-bold text-gray-800">{value}</span>
<span className="text-sm font-semibold text-gray-500">{unit}</span>
</div>
</div>
);
const FcrTrendChart: React.FC<{ data: FcrTrendPoint[] }> = ({ data }) => (
<div className="bg-white rounded-xl shadow-sm border border-gray-100 p-6">
<h2 className="text-xl font-bold text-gray-800 mb-4">Grafik FCR</h2>
<div className="h-80">
{data.length === 0 ? (
<div className="flex h-full items-center justify-center text-sm text-gray-500">
Tidak ada data FCR tersedia.
</div>
) : (
<ResponsiveContainer width="100%" height="100%">
<LineChart data={data} margin={{ top: 5, right: 20, left: -10, bottom: 5 }}>
<CartesianGrid strokeDasharray="3 3" stroke="#e5e7eb" />
<XAxis dataKey="day" fontSize={12} tick={{ fill: '#6b7280' }} />
<YAxis
fontSize={12}
tick={{ fill: '#6b7280' }}
width={50}
domain={[0, 'dataMax + 0.2']}
label={{ value: 'FCR', angle: -90, position: 'insideLeft' }}
/>
<Tooltip
contentStyle={{
backgroundColor: 'rgba(255, 255, 255, 0.95)',
border: '1px solid #d1d5db',
borderRadius: '8px',
}}
formatter={(value) => [formatFcr(Number(value)), 'IoT FCR']}
labelFormatter={(label) => `Day ${label}`}
/>
<Line
type="monotone"
dataKey="iotFcr"
name="IoT FCR"
stroke="#16a34a"
strokeWidth={2.5}
dot={{ r: 4 }}
activeDot={{ r: 6 }}
connectNulls
/>
</LineChart>
</ResponsiveContainer>
)}
</div>
</div>
);
const SupportingMetricChart: React.FC<{
title: string;
data: SupportingChartPoint[];
dataKey: keyof Omit<SupportingChartPoint, 'day'>;
unit: string;
stroke: string;
maximumFractionDigits?: number;
}> = ({ title, data, dataKey, unit, stroke, maximumFractionDigits = 0 }) => (
<div className="bg-white rounded-xl shadow-sm border border-gray-100 p-5">
<h3 className="text-lg font-bold text-gray-800 mb-4">{title}</h3>
<div className="h-64">
{data.length === 0 ? (
<div className="flex h-full items-center justify-center text-sm text-gray-500">
Tidak ada data tersedia.
</div>
) : (
<ResponsiveContainer width="100%" height="100%">
<LineChart data={data} margin={{ top: 5, right: 20, left: 0, bottom: 5 }}>
<CartesianGrid strokeDasharray="3 3" stroke="#e5e7eb" />
<XAxis dataKey="day" fontSize={12} tick={{ fill: '#6b7280' }} />
<YAxis
fontSize={12}
tick={{ fill: '#6b7280' }}
tickFormatter={(value) => formatNumber(Number(value), maximumFractionDigits)}
width={70}
/>
<Tooltip
contentStyle={{
backgroundColor: 'rgba(255, 255, 255, 0.95)',
border: '1px solid #d1d5db',
borderRadius: '8px',
}}
formatter={(value) => [formatTooltipValue(value, unit, maximumFractionDigits), title]}
labelFormatter={(label) => `Day ${label}`}
/>
<Line
type="monotone"
dataKey={dataKey}
name={title}
stroke={stroke}
strokeWidth={2.5}
dot={{ r: 3 }}
activeDot={{ r: 5 }}
connectNulls
/>
</LineChart>
</ResponsiveContainer>
)}
</div>
</div>
);
const FcrDashboardPage: React.FC = () => {
const [supportRows, setSupportRows] = useState<FcrSupportRow[]>([]);
const [isLoading, setIsLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [lastUpdated, setLastUpdated] = useState<Date | null>(null);
const loadFcrData = useCallback(async () => {
setIsLoading(true);
setError(null);
try {
const apiKpiData = await fetchLiveFcrKpiData();
const rows = Object.entries(apiKpiData)
.map(([dayKey, row]) => ({
day: Number(dayKey),
feedTotal: row.food_total ?? 0,
iotWeight: row.iot_weight ?? null,
chickenLife: row.chicken_life ?? 0,
harvestWeightTotal: row.harvest_weight_total ?? 0,
iotFcr: toValidFcr(row.iot_fcr),
}))
.filter((row) => Number.isFinite(row.day))
.sort((a, b) => a.day - b.day);
setSupportRows(rows);
setLastUpdated(new Date());
} catch (err) {
console.error('Failed to load FCR dashboard data:', err);
setError('Gagal memuat data FCR dari API.');
} finally {
setIsLoading(false);
}
}, []);
useEffect(() => {
loadFcrData();
}, [loadFcrData]);
const fcrTrendData = useMemo<FcrTrendPoint[]>(() => {
return supportRows.map((row) => ({
day: row.day,
iotFcr: row.iotFcr,
}));
}, [supportRows]);
const supportingChartData = useMemo<SupportingChartPoint[]>(() => {
return supportRows.map((row) => ({
day: row.day,
feedTotal: row.feedTotal,
iotWeight: row.iotWeight,
chickenLife: row.chickenLife,
harvestWeightKg: row.harvestWeightTotal / 1000,
}));
}, [supportRows]);
const getLatestValid = <K extends keyof FcrSupportRow>(key: K): FcrSupportRow[K] | null => {
for (let i = supportRows.length - 1; i >= 0; i--) {
// Indexed access can be undefined, and the row's own fields are not
// necessarily strings — compare against the empty string loosely.
const val = supportRows[i]?.[key];
if (val !== null && val !== undefined && val !== 0 && String(val) !== '') {
return val;
}
}
return null;
};
const latestRow = supportRows[supportRows.length - 1];
const latestFcr = getLatestValid('iotFcr');
return (
<main className="px-4 sm:px-6 lg:px-8 pb-8">
<div className="flex items-center justify-between mb-6">
<div className="flex items-center">
<i className="fa-solid fa-chart-line text-3xl text-red-600 mr-4"></i>
<div>
<h1 className="text-3xl font-bold text-gray-800">FCR</h1>
<p className="mt-1 text-gray-600">
Dashboard Feed Conversion Ratio berdasarkan data pakan, bobot IoT, ayam hidup, dan
panen.
</p>
</div>
</div>
<button
onClick={loadFcrData}
disabled={isLoading}
className="flex items-center space-x-2 px-4 py-2 bg-red-600 text-white rounded-lg hover:bg-red-700 disabled:bg-gray-400 disabled:cursor-not-allowed transition-colors"
>
<i className={`fa-solid fa-refresh ${isLoading ? 'fa-spin' : ''}`}></i>
<span>{isLoading ? 'Memuat...' : 'Refresh'}</span>
</button>
</div>
{/* AI Insight FCR — tampil setelah loading selesai */}
{!isLoading && (
<PageAiInsight
topic="fcr"
cacheKey={`fcr-rows${supportRows.length}-fcr${String(latestFcr ?? 'null').replace('.', '_')}`}
chartSpec={{
type: 'trend',
historyKey: 'tren_7_hari_terakhir',
title: 'Tren FCR',
series: [{ field: 'fcr', label: 'FCR aktual', color: '#dc2626' }],
}}
scalarScope={{
historyKey: 'tren_7_hari_terakhir',
derive: {
fcrRataRata_rasio: { field: 'fcr', agg: 'mean', replaces: 'fcr_terakhir' },
// `lastValid`, not `last`: these three carry 0 on every day the
// sensor did not report, and the page beside this card already
// skips those zeros via `getLatestValid`.
pakanTerakhir_karung: {
field: 'pakan',
agg: 'lastValid',
replaces: 'pakan_karung_terakhir',
},
bobotIotTerakhir_kg: {
field: 'bobot_kg',
agg: 'lastValid',
replaces: 'bobot_iot_kg_terakhir',
},
ayamHidupTerakhir_ekor: {
field: 'ayam',
agg: 'lastValid',
replaces: 'ayam_hidup_ekor',
},
},
drop: [
'fcr_terakhir',
'pakan_karung_terakhir',
'bobot_iot_kg_terakhir',
'ayam_hidup_ekor',
],
}}
contextData={
supportRows.length > 0
? {
hari_terakhir: latestRow?.day ?? null,
fcr_terakhir: latestFcr,
pakan_karung_terakhir: getLatestValid('feedTotal') ?? null,
bobot_iot_kg_terakhir: getLatestValid('iotWeight') ?? null,
ayam_hidup_ekor: getLatestValid('chickenLife') ?? null,
beratPanen_kg: getLatestValid('harvestWeightTotal')
? (getLatestValid('harvestWeightTotal') as number) / 1000
: null,
jumlahHariData_hari: supportRows.length,
// Kirim hanya 7 hari terakhir untuk menghindari prompt terlalu panjang
tren_7_hari_terakhir: supportRows.slice(-7).map((r) => ({
hari: r.day,
fcr: r.iotFcr,
pakan: r.feedTotal,
bobot_kg: r.iotWeight,
ayam: r.chickenLife,
})),
}
: { status: 'Tidak ada data FCR dari API.' }
}
/>
)}
<div className="space-y-8">
{error && (
<div className="rounded-xl border border-red-200 bg-red-50 p-4 text-sm font-semibold text-red-700">
{error}
</div>
)}
<div className="grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-5 gap-6">
<StatCard title="FCR" value={formatFcr(latestFcr)} unit="" />
<StatCard
title="Total Pakan"
value={formatNumber((getLatestValid('feedTotal') as number) ?? 0)}
unit="Karung"
/>
<StatCard
title="Bobot IoT"
value={formatNullableNumber(getLatestValid('iotWeight') as number | null, 2)}
unit="g"
/>
<StatCard
title="Ayam Hidup"
value={formatNumber((getLatestValid('chickenLife') as number) ?? 0)}
unit="Ekor"
/>
<StatCard
title="Total Bobot Panen"
value={formatHarvestWeightKg((getLatestValid('harvestWeightTotal') as number) ?? 0)}
unit="kg"
/>
</div>
<FcrTrendChart data={fcrTrendData} />
<div className="bg-white rounded-xl shadow-sm border border-gray-100 overflow-hidden">
<div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-2 px-6 py-4 border-b border-gray-100">
<div>
<h2 className="text-xl font-bold text-gray-800">Data Pendukung FCR</h2>
</div>
{lastUpdated && (
<p className="text-sm text-gray-500">
Update:{' '}
{lastUpdated.toLocaleTimeString('id-ID', { hour: '2-digit', minute: '2-digit' })}
</p>
)}
</div>
<div className="overflow-auto max-h-[420px]">
<table className="min-w-full text-sm">
<thead className="bg-gray-700 text-white sticky top-0 z-10">
<tr>
<th className="p-3 text-left font-semibold">Umur</th>
<th className="p-3 text-right font-semibold">Total Pakan</th>
<th className="p-3 text-right font-semibold">Bobot IoT</th>
<th className="p-3 text-right font-semibold">Ayam Hidup</th>
<th className="p-3 text-right font-semibold">Total Bobot Panen</th>
<th className="p-3 text-right font-semibold">FCR</th>
</tr>
</thead>
<tbody>
{supportRows.map((row) => (
<tr key={row.day} className="even:bg-gray-50 hover:bg-red-50">
<td className="p-3 font-semibold text-gray-800">Day {row.day}</td>
<td className="p-3 text-right text-gray-700">
{formatNumber(row.feedTotal)} karung
</td>
<td className="p-3 text-right text-gray-700">
{formatNullableNumber(row.iotWeight, 2)}
{row.iotWeight !== null ? ' g' : ''}
</td>
<td className="p-3 text-right text-gray-700">
{formatNumber(row.chickenLife)} ekor
</td>
<td className="p-3 text-right text-gray-700">
{formatHarvestWeightKg(row.harvestWeightTotal)} kg
</td>
<td className="p-3 text-right font-mono text-gray-700">
{formatFcr(row.iotFcr)}
</td>
</tr>
))}
{!isLoading && supportRows.length === 0 && (
<tr>
<td colSpan={6} className="p-8 text-center text-gray-500">
Tidak ada data FCR tersedia.
</td>
</tr>
)}
</tbody>
</table>
</div>
<div className="border-t border-gray-100 p-6">
<h2 className="text-xl font-bold text-gray-800 mb-4">Grafik Data Pendukung</h2>
<div className="grid grid-cols-1 xl:grid-cols-2 gap-6">
<SupportingMetricChart
title="Total Pakan"
data={supportingChartData}
dataKey="feedTotal"
unit="karung"
stroke="#dc2626"
/>
<SupportingMetricChart
title="Bobot IoT"
data={supportingChartData}
dataKey="iotWeight"
unit="g"
stroke="#16a34a"
maximumFractionDigits={2}
/>
<SupportingMetricChart
title="Ayam Hidup"
data={supportingChartData}
dataKey="chickenLife"
unit="ekor"
stroke="#2563eb"
/>
<SupportingMetricChart
title="Total Bobot Panen"
data={supportingChartData}
dataKey="harvestWeightKg"
unit="kg"
stroke="#9333ea"
maximumFractionDigits={1}
/>
</div>
</div>
</div>
</div>
</main>
);
};
export default FcrDashboardPage;