first commit

This commit is contained in:
Alberto-Audrix committed 2026-08-26 13:46:05 +07:00
commit 367533c02b
171 files changed
+101175

No files matched your search

+473
View File
@@ -0,0 +1,473 @@
import React, { useCallback, useEffect, useMemo, useState } from 'react';
import {
CartesianGrid,
Line,
LineChart,
ResponsiveContainer,
Tooltip,
XAxis,
YAxis,
} from 'recharts';
import { api, errorMessage } from '../services/apiClient.ts';
import type { AIInsight, ChickenWeight, KPI } from '../types/api.ts';
import { useFarm } from '../context/FarmContext.tsx';
import { Banner, EmptyFarm, PageHeader, Spinner } from './ui/Feedback.tsx';
import { formatNumber, formatRatio } from '../utils/format.ts';
type FcrRow = {
day: number;
feedTotal: number;
iotWeight: number | null;
chickenLife: number;
harvestWeightKg: number;
fcr: number | null;
};
type TrendPoint = { day: number; fcr: number | null };
type SupportPoint = {
day: number;
feedTotal: number;
iotWeight: number | null;
chickenLife: number;
harvestWeightKg: number;
};
const formatFcr = (value: number | null): string => (value == null ? 'N/A' : formatRatio(value, 3));
const formatNum = (value: number | null | undefined, maxDecimals = 0): string =>
value == null || !Number.isFinite(Number(value))
? 'N/A'
: formatNumber(Number(value), maxDecimals, 0, true);
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: TrendPoint[] }> = ({ 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)), 'FCR']}
labelFormatter={(label) => `Hari ${label}`}
/>
<Line
type="monotone"
dataKey="fcr"
name="FCR"
stroke="#16a34a"
strokeWidth={2.5}
dot={{ r: 4 }}
activeDot={{ r: 6 }}
connectNulls
/>
</LineChart>
</ResponsiveContainer>
)}
</div>
</div>
);
const SupportingMetricChart: React.FC<{
title: string;
data: SupportPoint[];
dataKey: keyof Omit<SupportPoint, '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) => formatNum(Number(value), maximumFractionDigits)}
width={70}
/>
<Tooltip
contentStyle={{
backgroundColor: 'rgba(255, 255, 255, 0.95)',
border: '1px solid #d1d5db',
borderRadius: '8px',
}}
formatter={(value) => [
`${formatNum(Number(value), maximumFractionDigits)} ${unit}`,
title,
]}
labelFormatter={(label) => `Hari ${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<{ onSettings: () => void }> = ({ onSettings }) => {
const { selectedCycle } = useFarm();
const [rows, setRows] = useState<KPI[]>([]);
const [weightRows, setWeightRows] = useState<ChickenWeight[]>([]);
const [insights, setInsights] = useState<AIInsight[]>([]);
const [loading, setLoading] = useState(false);
const [refreshing, setRefreshing] = useState(false);
const [error, setError] = useState<string | null>(null);
const [lastUpdated, setLastUpdated] = useState<Date | null>(null);
const loadData = useCallback(async () => {
if (!selectedCycle) return;
setError(null);
try {
const [kpiRows, insightRows, weightList] = await Promise.all([
api.kpis.list({ cycle_id: selectedCycle.id }),
api.insights.list({ cycle_id: selectedCycle.id }),
api.weights.list({ cycle_id: selectedCycle.id }),
]);
setRows(kpiRows);
setInsights(insightRows);
setWeightRows(weightList);
setLastUpdated(new Date());
} catch (err) {
setError(errorMessage(err));
}
}, [selectedCycle]);
useEffect(() => {
if (!selectedCycle) {
setRows([]);
setWeightRows([]);
setInsights([]);
setLastUpdated(null);
return;
}
let cancelled = false;
(async () => {
setLoading(true);
try {
await loadData();
} finally {
if (!cancelled) setLoading(false);
}
})();
return () => {
cancelled = true;
};
}, [selectedCycle, loadData]);
const handleRefresh = async () => {
setRefreshing(true);
try {
await loadData();
} finally {
setRefreshing(false);
}
};
const weightByAge = useMemo(() => {
const map = new Map<number, number>();
for (const weight of weightRows) {
if (weight.average_weight > 0 && !map.has(weight.age)) {
map.set(weight.age, weight.average_weight);
}
}
return map;
}, [weightRows]);
const fcrRows = useMemo<FcrRow[]>(
() =>
[...rows]
.sort((a, b) => a.age - b.age || a.date.localeCompare(b.date))
.map((row) => ({
day: row.age,
feedTotal: row.feed_total,
iotWeight: weightByAge.get(row.age) ?? null,
chickenLife: row.chicken_life,
harvestWeightKg: row.harvest_weight_total / 1000,
fcr: row.fcr > 0 ? row.fcr : null,
})),
[rows, weightByAge]
);
const trendData = useMemo<TrendPoint[]>(
() => fcrRows.map((row) => ({ day: row.day, fcr: row.fcr })),
[fcrRows]
);
const supportData = useMemo<SupportPoint[]>(
() =>
fcrRows.map((row) => ({
day: row.day,
feedTotal: row.feedTotal,
iotWeight: row.iotWeight,
chickenLife: row.chickenLife,
harvestWeightKg: row.harvestWeightKg,
})),
[fcrRows]
);
const getLatestValid = <K extends keyof FcrRow>(key: K): FcrRow[K] | null => {
for (let i = fcrRows.length - 1; i >= 0; i--) {
const val = fcrRows[i]?.[key];
if (val !== null && val !== undefined && val !== 0 && String(val) !== '') {
return val;
}
}
return null;
};
const latestFcr = getLatestValid('fcr');
const latestIotWeight = getLatestValid('iotWeight');
const fcrInsights = useMemo(() => {
const matched = insights.filter((item) => {
const text =
`${item.section ?? ''} ${item.alert ?? ''} ${item.insight_text ?? ''}`.toLowerCase();
return (
text.includes('fcr') ||
text.includes('pakan') ||
text.includes('feed') ||
text.includes('konversi') ||
text.includes('panen')
);
});
return (matched.length > 0 ? matched : insights).slice(0, 4);
}, [insights]);
if (!selectedCycle) return <EmptyFarm onSettings={onSettings} />;
return (
<main className="mx-auto max-w-[1240px] space-y-6">
<div className="flex flex-col gap-4 lg:flex-row lg:items-start lg:justify-between">
<PageHeader
title="FCR"
subtitle="Dashboard Feed Conversion Ratio berdasarkan data pakan, bobot IoT, ayam hidup, dan panen."
icon={<i className="fa-solid fa-chart-line" />}
/>
<button
onClick={handleRefresh}
disabled={refreshing || loading}
className="inline-flex shrink-0 items-center gap-2 rounded-lg bg-red-600 px-4 py-2 text-sm font-semibold text-white transition-colors hover:bg-red-700 disabled:cursor-not-allowed disabled:bg-gray-400"
>
<i className={`fa-solid fa-rotate-right ${refreshing || loading ? 'fa-spin' : ''}`} />
<span>{refreshing || loading ? 'Memuat...' : 'Refresh'}</span>
</button>
</div>
{error && (
<div>
<Banner kind="error">{error}</Banner>
</div>
)}
<section>
<h2 className="text-lg font-bold text-gray-800 mb-3">
<i className="fa-solid fa-brain text-red-600 mr-2" />
AI Insight FCR
</h2>
{loading ? (
<Spinner />
) : fcrInsights.length === 0 ? (
<Banner>Belum ada insight untuk siklus ini.</Banner>
) : (
<div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
{fcrInsights.map((item) => (
<article
key={item.id}
className="bg-white rounded-xl shadow-sm p-5 border border-gray-100"
>
<div className="flex items-start justify-between gap-3">
<div>
<p className="text-xs uppercase tracking-wide text-gray-400">{item.section}</p>
<h3 className="font-semibold text-gray-800 mt-1">{item.alert || 'Insight'}</h3>
</div>
<span className="text-xs text-gray-400">{item.session}</span>
</div>
<p className="text-sm text-gray-600 mt-3 whitespace-pre-wrap">
{item.insight_text}
</p>
</article>
))}
</div>
)}
</section>
{loading ? (
<Spinner />
) : (
<div className="space-y-8">
<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={formatNum(getLatestValid('feedTotal') ?? 0)}
unit="Karung"
/>
<StatCard title="Bobot IoT" value={formatNum(latestIotWeight, 2)} unit="g" />
<StatCard
title="Ayam Hidup"
value={formatNum(getLatestValid('chickenLife') ?? 0)}
unit="Ekor"
/>
<StatCard
title="Total Bobot Panen"
value={formatNum(getLatestValid('harvestWeightKg') ?? 0, 1)}
unit="kg"
/>
</div>
<FcrTrendChart data={trendData} />
<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">
<h2 className="text-xl font-bold text-gray-800">Data Pendukung FCR</h2>
{lastUpdated && (
<p className="text-sm text-gray-500">
Update:{' '}
{lastUpdated.toLocaleTimeString('id-ID', { hour: '2-digit', minute: '2-digit' })}
</p>
)}
</div>
<div className="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={supportData}
dataKey="feedTotal"
unit="karung"
stroke="#dc2626"
/>
<SupportingMetricChart
title="Bobot IoT"
data={supportData}
dataKey="iotWeight"
unit="g"
stroke="#16a34a"
maximumFractionDigits={2}
/>
<SupportingMetricChart
title="Ayam Hidup"
data={supportData}
dataKey="chickenLife"
unit="ekor"
stroke="#2563eb"
/>
<SupportingMetricChart
title="Total Bobot Panen"
data={supportData}
dataKey="harvestWeightKg"
unit="kg"
stroke="#9333ea"
maximumFractionDigits={1}
/>
</div>
</div>
<div className="border-t border-gray-100">
<div className="px-6 py-4">
<h2 className="text-xl font-bold text-gray-800">Tabel Data Pendukung FCR</h2>
</div>
<div className="overflow-auto max-h-[420px] border-t border-gray-100">
<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>
{fcrRows.map((row) => (
<tr key={row.day} className="even:bg-gray-50 hover:bg-red-50">
<td className="p-3 font-semibold text-gray-800">Hari {row.day}</td>
<td className="p-3 text-right text-gray-700">
{formatNum(row.feedTotal)} karung
</td>
<td className="p-3 text-right text-gray-700">
{formatNum(row.iotWeight, 2)}
{row.iotWeight != null ? ' g' : ''}
</td>
<td className="p-3 text-right text-gray-700">
{formatNum(row.chickenLife)} ekor
</td>
<td className="p-3 text-right text-gray-700">
{formatNum(row.harvestWeightKg, 1)} kg
</td>
<td className="p-3 text-right font-mono text-gray-700">
{formatFcr(row.fcr)}
</td>
</tr>
))}
{fcrRows.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>
</div>
</div>
)}
</main>
);
};
export default FcrDashboardPage;