354 lines
12 KiB
TypeScript
354 lines
12 KiB
TypeScript
import React, { useMemo } from 'react';
|
|
import {
|
|
Area,
|
|
CartesianGrid,
|
|
ComposedChart,
|
|
Legend,
|
|
Line,
|
|
ResponsiveContainer,
|
|
Tooltip,
|
|
XAxis,
|
|
YAxis,
|
|
} from 'recharts';
|
|
import type { DailyWeightPoint } from '../../types.ts';
|
|
import { getCobbStandardForDay } from '../../utils/insightHelpers.ts';
|
|
import { formatWeight } from '../../utils/weightUtils';
|
|
|
|
/**
|
|
* Actual weight vs Cobb standard across the whole cycle, with the gap between
|
|
* the two shaded by direction (surplus above the standard, deficit below).
|
|
*
|
|
* Every number shown here is computed from `data` in this file — nothing comes
|
|
* from the LLM. The chart therefore still renders when the model is offline,
|
|
* and the narrative above it can never disagree with the plotted line.
|
|
*/
|
|
|
|
interface EndCycleWeightVsStandardChartProps {
|
|
data: DailyWeightPoint[];
|
|
startDate?: string | Date | null;
|
|
}
|
|
|
|
type ChartPoint = {
|
|
day: number;
|
|
date: string;
|
|
actual: number;
|
|
target: number;
|
|
deviation: number;
|
|
/** Range band [target, actual] on days the flock beat the standard. */
|
|
surplus: [number, number] | null;
|
|
/** Range band [actual, target] on days the flock fell short. */
|
|
deficit: [number, number] | null;
|
|
};
|
|
|
|
type CycleStats = {
|
|
daysAbove: number;
|
|
daysBelow: number;
|
|
finalDeviation: number;
|
|
finalDeviationPct: number;
|
|
worstDay: ChartPoint | null;
|
|
bestDay: ChartPoint | null;
|
|
avgDeviationPct: number;
|
|
};
|
|
|
|
// Validated for the light chart surface via the dataviz palette checker.
|
|
// The app ships no dark mode (zero `dark:` classes, no darkMode in the Tailwind
|
|
// setup), so a light-only palette is the whole requirement here.
|
|
const COLOR_ACTUAL = '#1d4ed8';
|
|
const COLOR_SURPLUS = '#15803d';
|
|
const COLOR_DEFICIT = '#b45309';
|
|
// The standard is a reference baseline, not a competing series: neutral ink plus
|
|
// a dashed stroke so it never fights the actual line for attention.
|
|
const COLOR_STANDARD = '#94a3b8';
|
|
|
|
const formatSignedWeight = (grams: number) =>
|
|
`${grams >= 0 ? '+' : '-'}${formatWeight(Math.abs(grams))}`;
|
|
|
|
const formatSignedPct = (pct: number) => `${pct >= 0 ? '+' : '-'}${Math.abs(pct).toFixed(1)}%`;
|
|
|
|
export const EndCycleWeightVsStandardChart: React.FC<EndCycleWeightVsStandardChartProps> = ({
|
|
data,
|
|
startDate,
|
|
}) => {
|
|
const chartData = useMemo<ChartPoint[]>(() => {
|
|
if (!data || data.length === 0) return [];
|
|
|
|
return data
|
|
.map((point) => {
|
|
// `target` is already the Cobb figure for most rows; fall back to the
|
|
// lookup so a missing target does not silently drop the day.
|
|
const target = point.target || getCobbStandardForDay(point.day)?.weight || 0;
|
|
const actual = point.actual;
|
|
|
|
if (!actual || !target) return null;
|
|
|
|
const deviation = actual - target;
|
|
|
|
return {
|
|
day: point.day,
|
|
date: point.date,
|
|
actual,
|
|
target,
|
|
deviation,
|
|
surplus: deviation > 0 ? ([target, actual] as [number, number]) : null,
|
|
deficit: deviation < 0 ? ([actual, target] as [number, number]) : null,
|
|
};
|
|
})
|
|
.filter((point): point is ChartPoint => point !== null)
|
|
.sort((a, b) => a.day - b.day);
|
|
}, [data]);
|
|
|
|
const stats = useMemo<CycleStats | null>(() => {
|
|
if (chartData.length === 0) return null;
|
|
|
|
const last = chartData[chartData.length - 1];
|
|
if (!last) return null;
|
|
|
|
const worstDay = chartData.reduce((acc, point) =>
|
|
point.deviation < acc.deviation ? point : acc
|
|
);
|
|
const bestDay = chartData.reduce((acc, point) =>
|
|
point.deviation > acc.deviation ? point : acc
|
|
);
|
|
|
|
const totalPct = chartData.reduce(
|
|
(sum, point) => sum + (point.deviation / point.target) * 100,
|
|
0
|
|
);
|
|
|
|
return {
|
|
daysAbove: chartData.filter((point) => point.deviation > 0).length,
|
|
daysBelow: chartData.filter((point) => point.deviation < 0).length,
|
|
finalDeviation: last.deviation,
|
|
finalDeviationPct: (last.deviation / last.target) * 100,
|
|
worstDay: worstDay.deviation < 0 ? worstDay : null,
|
|
bestDay: bestDay.deviation > 0 ? bestDay : null,
|
|
avgDeviationPct: totalPct / chartData.length,
|
|
};
|
|
}, [chartData]);
|
|
|
|
const formatDateForDay = (point: ChartPoint): string => {
|
|
if (point.date) {
|
|
const parsed = new Date(point.date);
|
|
if (!Number.isNaN(parsed.getTime())) {
|
|
return parsed.toLocaleDateString('id-ID', { day: 'numeric', month: 'short' });
|
|
}
|
|
}
|
|
if (!startDate) return '';
|
|
const date = new Date(startDate);
|
|
if (Number.isNaN(date.getTime())) return '';
|
|
date.setDate(date.getDate() + point.day - 1);
|
|
return date.toLocaleDateString('id-ID', { day: 'numeric', month: 'short' });
|
|
};
|
|
|
|
const CustomTooltip = ({
|
|
active,
|
|
payload,
|
|
}: {
|
|
active?: boolean;
|
|
payload?: Array<{ payload: ChartPoint }>;
|
|
}) => {
|
|
const point = active ? payload?.[0]?.payload : null;
|
|
if (!point) return null;
|
|
|
|
const pct = (point.deviation / point.target) * 100;
|
|
const ahead = point.deviation >= 0;
|
|
|
|
return (
|
|
<div className="rounded-lg border border-gray-200 bg-white p-3 shadow-lg">
|
|
<p className="text-sm font-bold text-gray-900">Hari ke-{point.day}</p>
|
|
{formatDateForDay(point) && (
|
|
<p className="text-xs text-gray-500">{formatDateForDay(point)}</p>
|
|
)}
|
|
<div className="mt-2 space-y-1 text-sm">
|
|
<p className="flex items-center gap-2 text-gray-700">
|
|
<span
|
|
className="inline-block h-2 w-2 shrink-0 rounded-full"
|
|
style={{ backgroundColor: COLOR_ACTUAL }}
|
|
/>
|
|
Berat aktual: <span className="font-semibold">{formatWeight(point.actual)}</span>
|
|
</p>
|
|
<p className="flex items-center gap-2 text-gray-700">
|
|
<span
|
|
className="inline-block h-2 w-2 shrink-0 rounded-full"
|
|
style={{ backgroundColor: COLOR_STANDARD }}
|
|
/>
|
|
Standar Cobb: <span className="font-semibold">{formatWeight(point.target)}</span>
|
|
</p>
|
|
<p className="pt-1 text-gray-700">
|
|
Selisih:{' '}
|
|
<span
|
|
className="font-semibold"
|
|
style={{ color: ahead ? COLOR_SURPLUS : COLOR_DEFICIT }}
|
|
>
|
|
{formatSignedWeight(point.deviation)} ({formatSignedPct(pct)})
|
|
</span>
|
|
</p>
|
|
<p className="text-xs text-gray-500">{ahead ? 'Di atas standar' : 'Di bawah standar'}</p>
|
|
</div>
|
|
</div>
|
|
);
|
|
};
|
|
|
|
if (chartData.length === 0) {
|
|
return (
|
|
<div className="rounded-2xl border border-purple-100 bg-white/90 p-5 shadow-sm">
|
|
<h3 className="text-sm font-bold uppercase tracking-widest text-purple-700">
|
|
Berat Aktual vs Standar Cobb
|
|
</h3>
|
|
<p className="mt-4 text-sm text-gray-500">
|
|
Data berat harian belum tersedia untuk siklus ini, jadi grafik perbandingan terhadap
|
|
standar Cobb belum bisa ditampilkan.
|
|
</p>
|
|
</div>
|
|
);
|
|
}
|
|
|
|
return (
|
|
<div className="rounded-2xl border border-purple-100 bg-white/90 p-5 shadow-sm">
|
|
<div className="mb-1 flex flex-wrap items-baseline justify-between gap-2">
|
|
<h3 className="text-sm font-bold uppercase tracking-widest text-purple-700">
|
|
Berat Aktual vs Standar Cobb
|
|
</h3>
|
|
<span className="text-xs text-gray-500">
|
|
{chartData.length} hari data · dihitung dari data timbangan, bukan dari AI
|
|
</span>
|
|
</div>
|
|
<p className="mb-4 text-sm text-gray-600">
|
|
Area berwarna menunjukkan jarak antara berat aktual dan kurva standar — hijau saat di atas
|
|
standar, oranye saat tertinggal.
|
|
</p>
|
|
|
|
<div className="h-80 w-full">
|
|
<ResponsiveContainer width="100%" height="100%">
|
|
<ComposedChart data={chartData} margin={{ top: 8, right: 16, left: 8, bottom: 8 }}>
|
|
<CartesianGrid stroke="#eef2f7" vertical={false} />
|
|
<XAxis
|
|
dataKey="day"
|
|
tickLine={false}
|
|
axisLine={{ stroke: '#e5e7eb' }}
|
|
tick={{ fill: '#6b7280', fontSize: 12 }}
|
|
tickFormatter={(day) => `H${day}`}
|
|
interval="preserveStartEnd"
|
|
minTickGap={24}
|
|
/>
|
|
<YAxis
|
|
tickLine={false}
|
|
axisLine={false}
|
|
tick={{ fill: '#6b7280', fontSize: 12 }}
|
|
tickFormatter={(value) => `${value}g`}
|
|
width={64}
|
|
/>
|
|
<Tooltip content={<CustomTooltip />} cursor={{ stroke: '#cbd5e1', strokeWidth: 1 }} />
|
|
<Legend
|
|
wrapperStyle={{ paddingTop: 12, fontSize: 12 }}
|
|
iconType="plainline"
|
|
iconSize={18}
|
|
/>
|
|
|
|
<Area
|
|
dataKey="surplus"
|
|
name="Di atas standar"
|
|
stroke="none"
|
|
fill={COLOR_SURPLUS}
|
|
fillOpacity={0.18}
|
|
isAnimationActive={false}
|
|
legendType="rect"
|
|
/>
|
|
<Area
|
|
dataKey="deficit"
|
|
name="Di bawah standar"
|
|
stroke="none"
|
|
fill={COLOR_DEFICIT}
|
|
fillOpacity={0.18}
|
|
isAnimationActive={false}
|
|
legendType="rect"
|
|
/>
|
|
|
|
<Line
|
|
type="monotone"
|
|
dataKey="target"
|
|
name="Standar Cobb"
|
|
stroke={COLOR_STANDARD}
|
|
strokeWidth={2}
|
|
strokeDasharray="6 4"
|
|
dot={false}
|
|
isAnimationActive={false}
|
|
/>
|
|
<Line
|
|
type="monotone"
|
|
dataKey="actual"
|
|
name="Berat aktual"
|
|
stroke={COLOR_ACTUAL}
|
|
strokeWidth={2}
|
|
dot={false}
|
|
activeDot={{ r: 5, strokeWidth: 2, stroke: '#ffffff' }}
|
|
isAnimationActive={false}
|
|
/>
|
|
</ComposedChart>
|
|
</ResponsiveContainer>
|
|
</div>
|
|
|
|
{stats && (
|
|
<div className="mt-5 grid grid-cols-2 gap-3 border-t border-purple-50 pt-4 md:grid-cols-4">
|
|
<div>
|
|
<p className="text-xs font-semibold uppercase tracking-wide text-gray-500">
|
|
Selisih akhir siklus
|
|
</p>
|
|
<p
|
|
className="mt-1 text-lg font-bold"
|
|
style={{ color: stats.finalDeviation >= 0 ? COLOR_SURPLUS : COLOR_DEFICIT }}
|
|
>
|
|
{formatSignedWeight(stats.finalDeviation)}
|
|
</p>
|
|
<p className="text-xs text-gray-500">{formatSignedPct(stats.finalDeviationPct)}</p>
|
|
</div>
|
|
<div>
|
|
<p className="text-xs font-semibold uppercase tracking-wide text-gray-500">
|
|
Hari di atas standar
|
|
</p>
|
|
<p className="mt-1 text-lg font-bold text-gray-900">
|
|
{stats.daysAbove}
|
|
<span className="text-sm font-medium text-gray-500"> / {chartData.length}</span>
|
|
</p>
|
|
<p className="text-xs text-gray-500">{stats.daysBelow} hari tertinggal</p>
|
|
</div>
|
|
<div>
|
|
<p className="text-xs font-semibold uppercase tracking-wide text-gray-500">
|
|
Rata-rata deviasi
|
|
</p>
|
|
<p
|
|
className="mt-1 text-lg font-bold"
|
|
style={{ color: stats.avgDeviationPct >= 0 ? COLOR_SURPLUS : COLOR_DEFICIT }}
|
|
>
|
|
{formatSignedPct(stats.avgDeviationPct)}
|
|
</p>
|
|
<p className="text-xs text-gray-500">sepanjang siklus</p>
|
|
</div>
|
|
<div>
|
|
<p className="text-xs font-semibold uppercase tracking-wide text-gray-500">
|
|
Titik terburuk
|
|
</p>
|
|
{stats.worstDay ? (
|
|
<>
|
|
<p className="mt-1 text-lg font-bold" style={{ color: COLOR_DEFICIT }}>
|
|
{formatSignedWeight(stats.worstDay.deviation)}
|
|
</p>
|
|
<p className="text-xs text-gray-500">pada hari ke-{stats.worstDay.day}</p>
|
|
</>
|
|
) : (
|
|
<>
|
|
<p className="mt-1 text-lg font-bold" style={{ color: COLOR_SURPLUS }}>
|
|
{stats.bestDay ? formatSignedWeight(stats.bestDay.deviation) : '—'}
|
|
</p>
|
|
<p className="text-xs text-gray-500">tidak pernah di bawah standar</p>
|
|
</>
|
|
)}
|
|
</div>
|
|
</div>
|
|
)}
|
|
</div>
|
|
);
|
|
};
|
|
|
|
export default EndCycleWeightVsStandardChart;
|