update report fix, live reload, mortality standard, weight use gram instead of kg
This commit is contained in:
1 parent
ec55063ffe
commit
438840622d
20 files changed
+623
-221
No files matched your search
@@ -372,7 +372,11 @@ class AIInsightViewSet(CycleScopedViewSet):
|
||||
"structured_end_cycle": structured_end_cycle,
|
||||
"alert": row.alert,
|
||||
"citations": cites,
|
||||
"harvest_prediction": getattr(row, "harvest_prediction", None),
|
||||
"harvest_prediction": (
|
||||
None
|
||||
if getattr(row, "report_type", None) == "end_cycle"
|
||||
else getattr(row, "harvest_prediction", None)
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -24,6 +24,7 @@ import {
|
||||
scopeDashboardInsightMetrics,
|
||||
} from '../utils/insightContextBuilders.ts';
|
||||
import { getCobbStandardForDay } from '../utils/insightHelpers.ts';
|
||||
import { getMortalityCumStandardByDay } from '../utils/cp707EnvStandards.ts';
|
||||
import { parseAiResult, type AiResult } from '../utils/insightParse.ts';
|
||||
import { formatRatio } from '../utils/format.ts';
|
||||
import {
|
||||
@@ -619,12 +620,19 @@ export const AiInsightCard: React.FC<AiInsightCardProps> = ({
|
||||
return 'critical';
|
||||
})();
|
||||
|
||||
const mortalityStandard =
|
||||
reportType === 'end_cycle' ? null : getMortalityCumStandardByDay(gradeDay);
|
||||
|
||||
const mortalityStatus = ((): InsightStatus => {
|
||||
const pct = scopedMetrics?.mortalitas_kumulatif_persen ?? null;
|
||||
if (pct === null) return 'unknown';
|
||||
if (pct < 5) return 'ok';
|
||||
if (pct <= 7) return 'warning';
|
||||
return 'critical';
|
||||
if (reportType === 'end_cycle') {
|
||||
if (pct < 5) return 'ok';
|
||||
if (pct <= 7) return 'warning';
|
||||
return 'critical';
|
||||
}
|
||||
if (mortalityStandard === null) return 'unknown';
|
||||
return pct <= mortalityStandard ? 'ok' : 'warning';
|
||||
})();
|
||||
|
||||
const weightTarget =
|
||||
@@ -787,11 +795,17 @@ export const AiInsightCard: React.FC<AiInsightCardProps> = ({
|
||||
deltaLabel={
|
||||
mortVal == null
|
||||
? null
|
||||
: mortalityStatus === 'ok'
|
||||
? '✓ normal <5%'
|
||||
: mortalityStatus === 'warning'
|
||||
? '↑ melebihi standar <5%'
|
||||
: '↑ tinggi, standar <5%'
|
||||
: reportType === 'end_cycle'
|
||||
? mortalityStatus === 'ok'
|
||||
? '✓ normal <5%'
|
||||
: mortalityStatus === 'warning'
|
||||
? '↑ melebihi standar <5%'
|
||||
: '↑ tinggi, standar <5%'
|
||||
: mortalityStandard == null
|
||||
? null
|
||||
: mortalityStatus === 'ok'
|
||||
? `✓ sesuai standar ≤${mortalityStandard.toFixed(2)}%`
|
||||
: `↑ melebihi standar ${mortalityStandard.toFixed(2)}%`
|
||||
}
|
||||
/>
|
||||
<StatTile
|
||||
@@ -1068,11 +1082,6 @@ export const AiInsightCard: React.FC<AiInsightCardProps> = ({
|
||||
{item.confidence}
|
||||
</span>
|
||||
) : null}
|
||||
{item.fase ? (
|
||||
<span className="text-[10px] uppercase tracking-wide text-gray-500">
|
||||
{item.fase}
|
||||
</span>
|
||||
) : null}
|
||||
</div>
|
||||
{item.bukti.length > 0 ? (
|
||||
<ul className="mt-2 space-y-1">
|
||||
@@ -1108,10 +1117,7 @@ export const AiInsightCard: React.FC<AiInsightCardProps> = ({
|
||||
key={`${item.id ?? item.aksi}-${index}`}
|
||||
className="rounded-lg border border-blue-200/70 bg-white/90 p-3.5 shadow-xs"
|
||||
>
|
||||
<p className="text-[10px] font-semibold uppercase tracking-wide text-blue-700">
|
||||
{item.fase}
|
||||
</p>
|
||||
<p className="mt-1 text-sm text-gray-800">{item.aksi}</p>
|
||||
<p className="text-sm text-gray-800">{item.aksi}</p>
|
||||
{item.metrik_pantau ? (
|
||||
<p className="mt-1 text-xs text-gray-500">
|
||||
Pantau: {item.metrik_pantau}
|
||||
|
||||
+87
-43
@@ -1,4 +1,4 @@
|
||||
import React, { useEffect, useMemo, useState } from 'react';
|
||||
import React, { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import { api, errorMessage } from '../services/apiClient.ts';
|
||||
import type {
|
||||
ChickenCounting,
|
||||
@@ -6,6 +6,7 @@ import type {
|
||||
Karung,
|
||||
KPI,
|
||||
ManualInput,
|
||||
PanelIoT,
|
||||
} from '../types/api.ts';
|
||||
import type { View } from '../types/common.ts';
|
||||
import { useFarm } from '../context/FarmContext.tsx';
|
||||
@@ -43,7 +44,8 @@ function chronological<T>(rows: T[]): T[] {
|
||||
}
|
||||
|
||||
const Dashboard: React.FC<Props> = ({ setView }) => {
|
||||
const { selectedCycle, selectedKandang, selectedSite, selectedKandangId } = useFarm();
|
||||
const { selectedCycle, selectedKandang, selectedSite, selectedKandangId, updateCycle } =
|
||||
useFarm();
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [kpis, setKpis] = useState<KPI[]>([]);
|
||||
@@ -55,30 +57,35 @@ const Dashboard: React.FC<Props> = ({ setView }) => {
|
||||
const [reportOpen, setReportOpen] = useState(false);
|
||||
const [reportType, setReportType] = useState<DashboardReportType>('daily');
|
||||
|
||||
useEffect(() => {
|
||||
if (!selectedCycle) {
|
||||
setKpis([]);
|
||||
setCountings([]);
|
||||
setManualInputs([]);
|
||||
setWeights([]);
|
||||
setKarungs([]);
|
||||
setIotDayAggregates([]);
|
||||
return;
|
||||
}
|
||||
const cycleId = selectedCycle.id;
|
||||
let cancelled = false;
|
||||
(async () => {
|
||||
setLoading(true);
|
||||
const fetchDashboardData = useCallback(
|
||||
async (isBackground = false) => {
|
||||
if (!selectedCycle) {
|
||||
setKpis([]);
|
||||
setCountings([]);
|
||||
setManualInputs([]);
|
||||
setWeights([]);
|
||||
setKarungs([]);
|
||||
setIotDayAggregates([]);
|
||||
return;
|
||||
}
|
||||
const cycleId = selectedCycle.id;
|
||||
if (!isBackground) {
|
||||
setLoading(true);
|
||||
}
|
||||
setError(null);
|
||||
try {
|
||||
const [kpiRows, countingRows, manualRows, weightRows, karungRows] = await Promise.all([
|
||||
api.kpis.list({ cycle_id: cycleId }),
|
||||
api.countings.list({ cycle_id: cycleId }),
|
||||
api.manualInputs.list({ cycle_id: cycleId }),
|
||||
api.weights.list({ cycle_id: cycleId }),
|
||||
api.karungs.list({ cycle_id: cycleId }),
|
||||
]);
|
||||
if (cancelled) return;
|
||||
const [kpiRows, countingRows, manualRows, weightRows, karungRows, freshCycle] =
|
||||
await Promise.all([
|
||||
api.kpis.list({ cycle_id: cycleId }),
|
||||
api.countings.list({ cycle_id: cycleId }),
|
||||
api.manualInputs.list({ cycle_id: cycleId }),
|
||||
api.weights.list({ cycle_id: cycleId }),
|
||||
api.karungs.list({ cycle_id: cycleId }).catch(() => []),
|
||||
api.cycles?.retrieve?.(cycleId)?.catch(() => null) ?? Promise.resolve(null),
|
||||
]);
|
||||
if (freshCycle) {
|
||||
updateCycle(cycleId, freshCycle);
|
||||
}
|
||||
setKpis(kpiRows);
|
||||
setCountings(countingRows);
|
||||
setManualInputs(manualRows);
|
||||
@@ -92,33 +99,70 @@ const Dashboard: React.FC<Props> = ({ setView }) => {
|
||||
(selectedKandang
|
||||
? (await api.flocks.list({ kandang_id: selectedKandang.id }))[0]?.id
|
||||
: null);
|
||||
if (flockId != null) {
|
||||
const panels = await api.panelIot.list({ flock_id: flockId });
|
||||
if (!cancelled) {
|
||||
setIotDayAggregates(
|
||||
buildIotDayAggregates({
|
||||
rows: panels,
|
||||
cycleStartDate: selectedCycle.start_date,
|
||||
getTempTarget: getTempStandardByDay,
|
||||
})
|
||||
);
|
||||
}
|
||||
if (flockId == null) {
|
||||
setIotDayAggregates([]);
|
||||
} else {
|
||||
if (!cancelled) setIotDayAggregates([]);
|
||||
let iotRows: PanelIoT[] = [];
|
||||
try {
|
||||
iotRows = await api.panelIot.list({ cycle_id: cycleId, flock_id: flockId });
|
||||
} catch {
|
||||
const dates = await api.panelIot.dates({ cycle_id: cycleId, flock_id: flockId });
|
||||
const sample = [...dates].sort().slice(-14);
|
||||
const batches = await Promise.all(
|
||||
sample.map((date) =>
|
||||
api.panelIot.list({ cycle_id: cycleId, flock_id: flockId, date }).catch(() => [])
|
||||
)
|
||||
);
|
||||
iotRows = batches.flat();
|
||||
}
|
||||
setIotDayAggregates(
|
||||
buildIotDayAggregates({
|
||||
rows: iotRows,
|
||||
cycleStartDate: selectedCycle.start_date,
|
||||
getTempTarget: getTempStandardByDay,
|
||||
})
|
||||
);
|
||||
}
|
||||
} catch {
|
||||
if (!cancelled) setIotDayAggregates([]);
|
||||
setIotDayAggregates([]);
|
||||
}
|
||||
} catch (err) {
|
||||
if (!cancelled) setError(errorMessage(err));
|
||||
if (!isBackground) {
|
||||
setError(errorMessage(err));
|
||||
}
|
||||
} finally {
|
||||
if (!cancelled) setLoading(false);
|
||||
if (!isBackground) {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
},
|
||||
[selectedCycle?.id, selectedCycle?.start_date, selectedKandang, updateCycle]
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
void fetchDashboardData(false);
|
||||
|
||||
const interval = setInterval(() => {
|
||||
if (document.visibilityState === 'visible') {
|
||||
void fetchDashboardData(true);
|
||||
}
|
||||
}, 60000);
|
||||
|
||||
const handleFocusOrVisibility = () => {
|
||||
if (document.visibilityState === 'visible') {
|
||||
void fetchDashboardData(true);
|
||||
}
|
||||
})();
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [selectedCycle, selectedKandang]);
|
||||
|
||||
document.addEventListener('visibilitychange', handleFocusOrVisibility);
|
||||
window.addEventListener('focus', handleFocusOrVisibility);
|
||||
|
||||
return () => {
|
||||
clearInterval(interval);
|
||||
document.removeEventListener('visibilitychange', handleFocusOrVisibility);
|
||||
window.removeEventListener('focus', handleFocusOrVisibility);
|
||||
};
|
||||
}, [fetchDashboardData]);
|
||||
|
||||
const visibleThrough = selectedCycle?.visible_through_date;
|
||||
const visibleKpis = useMemo(
|
||||
|
||||
@@ -166,23 +166,36 @@ const SupportingMetricChart: React.FC<{
|
||||
);
|
||||
|
||||
const EefDashboardPage: React.FC<{ onSettings: () => void }> = ({ onSettings }) => {
|
||||
const { selectedCycle, selectedKandang } = useFarm();
|
||||
const { selectedCycle, selectedKandang, updateCycle } = useFarm();
|
||||
const [rows, setRows] = useState<KPI[]>([]);
|
||||
const [loading, setLoading] = 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 = await api.kpis.list({ cycle_id: selectedCycle.id });
|
||||
setRows(kpiRows);
|
||||
setLastUpdated(new Date());
|
||||
} catch (err) {
|
||||
setError(errorMessage(err));
|
||||
}
|
||||
}, [selectedCycle]);
|
||||
const loadData = useCallback(
|
||||
async (isBackground = false) => {
|
||||
if (!selectedCycle) return;
|
||||
if (!isBackground) {
|
||||
setError(null);
|
||||
}
|
||||
try {
|
||||
const [kpiRows, freshCycle] = await Promise.all([
|
||||
api.kpis.list({ cycle_id: selectedCycle.id }),
|
||||
api.cycles?.retrieve?.(selectedCycle.id)?.catch(() => null) ?? Promise.resolve(null),
|
||||
]);
|
||||
if (freshCycle) {
|
||||
updateCycle(selectedCycle.id, freshCycle);
|
||||
}
|
||||
setRows(kpiRows);
|
||||
setLastUpdated(new Date());
|
||||
} catch (err) {
|
||||
if (!isBackground) {
|
||||
setError(errorMessage(err));
|
||||
}
|
||||
}
|
||||
},
|
||||
[selectedCycle?.id, updateCycle]
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (!selectedCycle) {
|
||||
@@ -190,19 +203,36 @@ const EefDashboardPage: React.FC<{ onSettings: () => void }> = ({ onSettings })
|
||||
setLastUpdated(null);
|
||||
return;
|
||||
}
|
||||
let cancelled = false;
|
||||
(async () => {
|
||||
void (async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
await loadData();
|
||||
await loadData(false);
|
||||
} finally {
|
||||
if (!cancelled) setLoading(false);
|
||||
setLoading(false);
|
||||
}
|
||||
})();
|
||||
return () => {
|
||||
cancelled = true;
|
||||
|
||||
const interval = setInterval(() => {
|
||||
if (document.visibilityState === 'visible') {
|
||||
void loadData(true);
|
||||
}
|
||||
}, 60000);
|
||||
|
||||
const handleFocusOrVisibility = () => {
|
||||
if (document.visibilityState === 'visible') {
|
||||
void loadData(true);
|
||||
}
|
||||
};
|
||||
}, [selectedCycle, loadData]);
|
||||
|
||||
document.addEventListener('visibilitychange', handleFocusOrVisibility);
|
||||
window.addEventListener('focus', handleFocusOrVisibility);
|
||||
|
||||
return () => {
|
||||
clearInterval(interval);
|
||||
document.removeEventListener('visibilitychange', handleFocusOrVisibility);
|
||||
window.removeEventListener('focus', handleFocusOrVisibility);
|
||||
};
|
||||
}, [selectedCycle?.id, loadData]);
|
||||
|
||||
const eefRows = useMemo<EefRow[]>(
|
||||
() =>
|
||||
|
||||
@@ -157,28 +157,39 @@ const SupportingMetricChart: React.FC<{
|
||||
);
|
||||
|
||||
const FcrDashboardPage: React.FC<{ onSettings: () => void }> = ({ onSettings }) => {
|
||||
const { selectedCycle, selectedKandang } = useFarm();
|
||||
const { selectedCycle, selectedKandang, updateCycle } = useFarm();
|
||||
const [rows, setRows] = useState<KPI[]>([]);
|
||||
const [weightRows, setWeightRows] = useState<ChickenWeight[]>([]);
|
||||
const [loading, setLoading] = 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, weightList] = await Promise.all([
|
||||
api.kpis.list({ cycle_id: selectedCycle.id }),
|
||||
api.weights.list({ cycle_id: selectedCycle.id }),
|
||||
]);
|
||||
setRows(kpiRows);
|
||||
setWeightRows(weightList);
|
||||
setLastUpdated(new Date());
|
||||
} catch (err) {
|
||||
setError(errorMessage(err));
|
||||
}
|
||||
}, [selectedCycle]);
|
||||
const loadData = useCallback(
|
||||
async (isBackground = false) => {
|
||||
if (!selectedCycle) return;
|
||||
if (!isBackground) {
|
||||
setError(null);
|
||||
}
|
||||
try {
|
||||
const [kpiRows, weightList, freshCycle] = await Promise.all([
|
||||
api.kpis.list({ cycle_id: selectedCycle.id }),
|
||||
api.weights.list({ cycle_id: selectedCycle.id }),
|
||||
api.cycles?.retrieve?.(selectedCycle.id)?.catch(() => null) ?? Promise.resolve(null),
|
||||
]);
|
||||
if (freshCycle) {
|
||||
updateCycle(selectedCycle.id, freshCycle);
|
||||
}
|
||||
setRows(kpiRows);
|
||||
setWeightRows(weightList);
|
||||
setLastUpdated(new Date());
|
||||
} catch (err) {
|
||||
if (!isBackground) {
|
||||
setError(errorMessage(err));
|
||||
}
|
||||
}
|
||||
},
|
||||
[selectedCycle?.id, updateCycle]
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (!selectedCycle) {
|
||||
@@ -187,19 +198,36 @@ const FcrDashboardPage: React.FC<{ onSettings: () => void }> = ({ onSettings })
|
||||
setLastUpdated(null);
|
||||
return;
|
||||
}
|
||||
let cancelled = false;
|
||||
(async () => {
|
||||
void (async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
await loadData();
|
||||
await loadData(false);
|
||||
} finally {
|
||||
if (!cancelled) setLoading(false);
|
||||
setLoading(false);
|
||||
}
|
||||
})();
|
||||
return () => {
|
||||
cancelled = true;
|
||||
|
||||
const interval = setInterval(() => {
|
||||
if (document.visibilityState === 'visible') {
|
||||
void loadData(true);
|
||||
}
|
||||
}, 60000);
|
||||
|
||||
const handleFocusOrVisibility = () => {
|
||||
if (document.visibilityState === 'visible') {
|
||||
void loadData(true);
|
||||
}
|
||||
};
|
||||
}, [selectedCycle, loadData]);
|
||||
|
||||
document.addEventListener('visibilitychange', handleFocusOrVisibility);
|
||||
window.addEventListener('focus', handleFocusOrVisibility);
|
||||
|
||||
return () => {
|
||||
clearInterval(interval);
|
||||
document.removeEventListener('visibilitychange', handleFocusOrVisibility);
|
||||
window.removeEventListener('focus', handleFocusOrVisibility);
|
||||
};
|
||||
}, [selectedCycle?.id, loadData]);
|
||||
|
||||
const weightByAge = useMemo(() => {
|
||||
const map = new Map<number, number>();
|
||||
|
||||
@@ -14,7 +14,7 @@ import FeedDailySummaryTable from './feedSack/FeedDailySummaryTable.tsx';
|
||||
import InitialBalanceCard from './feedSack/InitialBalanceCard.tsx';
|
||||
|
||||
const FeedSackCountingPage: React.FC<{ onSettings: () => void }> = ({ onSettings }) => {
|
||||
const { selectedCycle, selectedKandang, selectedSite, cycles, setSelectedCycleId } =
|
||||
const { selectedCycle, selectedKandang, selectedSite, cycles, setSelectedCycleId, updateCycle } =
|
||||
useFarm();
|
||||
const [rows, setRows] = useState<Karung[]>([]);
|
||||
const [manualRows, setManualRows] = useState<ManualInput[]>([]);
|
||||
@@ -22,22 +22,35 @@ const FeedSackCountingPage: React.FC<{ onSettings: () => void }> = ({ onSettings
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [showCyclePicker, setShowCyclePicker] = useState(false);
|
||||
|
||||
const reload = useCallback(async (cycleId: number) => {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
const [karungRows, manualList] = await Promise.all([
|
||||
api.karungs.list({ cycle_id: cycleId }),
|
||||
api.manualInputs.list({ cycle_id: cycleId }),
|
||||
]);
|
||||
setRows(karungRows);
|
||||
setManualRows(manualList);
|
||||
} catch (err) {
|
||||
setError(errorMessage(err));
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, []);
|
||||
const reload = useCallback(
|
||||
async (cycleId: number, isBackground = false) => {
|
||||
if (!isBackground) {
|
||||
setLoading(true);
|
||||
}
|
||||
setError(null);
|
||||
try {
|
||||
const [karungRows, manualList, freshCycle] = await Promise.all([
|
||||
api.karungs.list({ cycle_id: cycleId }),
|
||||
api.manualInputs.list({ cycle_id: cycleId }),
|
||||
api.cycles?.retrieve?.(cycleId)?.catch(() => null) ?? Promise.resolve(null),
|
||||
]);
|
||||
if (freshCycle) {
|
||||
updateCycle(cycleId, freshCycle);
|
||||
}
|
||||
setRows(karungRows);
|
||||
setManualRows(manualList);
|
||||
} catch (err) {
|
||||
if (!isBackground) {
|
||||
setError(errorMessage(err));
|
||||
}
|
||||
} finally {
|
||||
if (!isBackground) {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
},
|
||||
[updateCycle]
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (!selectedCycle) {
|
||||
@@ -45,8 +58,30 @@ const FeedSackCountingPage: React.FC<{ onSettings: () => void }> = ({ onSettings
|
||||
setManualRows([]);
|
||||
return;
|
||||
}
|
||||
void reload(selectedCycle.id);
|
||||
}, [selectedCycle, reload]);
|
||||
const cycleId = selectedCycle.id;
|
||||
void reload(cycleId, false);
|
||||
|
||||
const interval = setInterval(() => {
|
||||
if (document.visibilityState === 'visible') {
|
||||
void reload(cycleId, true);
|
||||
}
|
||||
}, 60000);
|
||||
|
||||
const handleFocusOrVisibility = () => {
|
||||
if (document.visibilityState === 'visible') {
|
||||
void reload(cycleId, true);
|
||||
}
|
||||
};
|
||||
|
||||
document.addEventListener('visibilitychange', handleFocusOrVisibility);
|
||||
window.addEventListener('focus', handleFocusOrVisibility);
|
||||
|
||||
return () => {
|
||||
clearInterval(interval);
|
||||
document.removeEventListener('visibilitychange', handleFocusOrVisibility);
|
||||
window.removeEventListener('focus', handleFocusOrVisibility);
|
||||
};
|
||||
}, [selectedCycle?.id, reload]);
|
||||
|
||||
const sortedRows = useMemo(() => [...rows].sort((a, b) => a.date.localeCompare(b.date)), [rows]);
|
||||
const sortedManualRows = useMemo(
|
||||
|
||||
@@ -94,6 +94,7 @@ const Header: React.FC<HeaderProps> = ({
|
||||
try {
|
||||
await api.activeSites.syncAll();
|
||||
await reloadFarm();
|
||||
window.dispatchEvent(new Event('focus'));
|
||||
} catch (err) {
|
||||
// Keep sync failures visible in the browser console; UI stays quiet.
|
||||
console.error(errorMessage(err));
|
||||
|
||||
+113
-13
@@ -1,4 +1,4 @@
|
||||
import React, { useEffect, useMemo, useState } from 'react';
|
||||
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import {
|
||||
CartesianGrid,
|
||||
Line,
|
||||
@@ -17,7 +17,6 @@ import {
|
||||
formatDateId,
|
||||
formatDateRange,
|
||||
formatNumber,
|
||||
resolveCycleBoundDate,
|
||||
todayIso,
|
||||
} from '../utils/format.ts';
|
||||
import {
|
||||
@@ -69,7 +68,7 @@ type DaySummary = {
|
||||
};
|
||||
|
||||
const IotPanelPage: React.FC<{ onSettings: () => void }> = ({ onSettings }) => {
|
||||
const { selectedCycle, selectedKandang, selectedSite } = useFarm();
|
||||
const { selectedCycle, selectedKandang, selectedSite, updateCycle } = useFarm();
|
||||
const [flocks, setFlocks] = useState<Flock[]>([]);
|
||||
const [selectedFlockId, setSelectedFlockId] = useState<number | null>(null);
|
||||
const [dates, setDates] = useState<string[]>([]);
|
||||
@@ -80,6 +79,7 @@ const IotPanelPage: React.FC<{ onSettings: () => void }> = ({ onSettings }) => {
|
||||
const [selectedChartKey, setSelectedChartKey] = useState<'humidity' | 'wind' | 'water' | null>(
|
||||
null
|
||||
);
|
||||
const userPickedDateRef = useRef(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (!selectedChartKey) return;
|
||||
@@ -91,6 +91,7 @@ const IotPanelPage: React.FC<{ onSettings: () => void }> = ({ onSettings }) => {
|
||||
}, [selectedChartKey]);
|
||||
|
||||
useEffect(() => {
|
||||
userPickedDateRef.current = false;
|
||||
if (!selectedKandang) {
|
||||
setFlocks([]);
|
||||
setSelectedFlockId(null);
|
||||
@@ -100,6 +101,10 @@ const IotPanelPage: React.FC<{ onSettings: () => void }> = ({ onSettings }) => {
|
||||
return;
|
||||
}
|
||||
let cancelled = false;
|
||||
setSelectedFlockId(null);
|
||||
setDates([]);
|
||||
setSelectedDate('');
|
||||
setDayRows([]);
|
||||
(async () => {
|
||||
setError(null);
|
||||
try {
|
||||
@@ -116,10 +121,76 @@ const IotPanelPage: React.FC<{ onSettings: () => void }> = ({ onSettings }) => {
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [selectedKandang]);
|
||||
}, [selectedKandang?.id]);
|
||||
|
||||
const cycleId = selectedCycle?.id ?? null;
|
||||
const cycleStartDate = selectedCycle?.start_date ?? '';
|
||||
const cycleEndDate = selectedCycle?.end_date ?? null;
|
||||
|
||||
const reload = useCallback(
|
||||
async (isBackground = false) => {
|
||||
if (cycleId == null || selectedFlockId == null) {
|
||||
return;
|
||||
}
|
||||
if (!isBackground) {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
}
|
||||
try {
|
||||
const [dateList, freshCycle] = await Promise.all([
|
||||
api.panelIot.dates({
|
||||
cycle_id: cycleId,
|
||||
flock_id: selectedFlockId,
|
||||
}),
|
||||
api.cycles?.retrieve?.(cycleId)?.catch(() => null) ?? Promise.resolve(null),
|
||||
]);
|
||||
if (freshCycle) {
|
||||
updateCycle(cycleId, freshCycle);
|
||||
}
|
||||
const sortedDates = [...dateList].sort();
|
||||
setDates(sortedDates);
|
||||
const cycleMin = cycleStartDate;
|
||||
const cycleMax = cycleEndDate ?? todayIso();
|
||||
const fallbackDate =
|
||||
todayIso() > cycleMax ? cycleMax : todayIso() < cycleMin ? cycleMin : todayIso();
|
||||
const newestAvailableDate =
|
||||
sortedDates.length > 0
|
||||
? (sortedDates[sortedDates.length - 1] ?? fallbackDate)
|
||||
: fallbackDate;
|
||||
|
||||
let dateToFetch = selectedDate;
|
||||
if (!dateToFetch || (!userPickedDateRef.current && dateToFetch !== newestAvailableDate)) {
|
||||
dateToFetch = newestAvailableDate;
|
||||
setSelectedDate(dateToFetch);
|
||||
}
|
||||
|
||||
if (dateToFetch) {
|
||||
const data = await api.panelIot.list({
|
||||
cycle_id: cycleId,
|
||||
flock_id: selectedFlockId,
|
||||
date: dateToFetch,
|
||||
});
|
||||
const sorted = [...data].sort((a, b) =>
|
||||
(a.timestamp ?? a.date).localeCompare(b.timestamp ?? b.date)
|
||||
);
|
||||
setDayRows(sorted);
|
||||
}
|
||||
} catch (err) {
|
||||
if (!isBackground) {
|
||||
setError(errorMessage(err));
|
||||
}
|
||||
} finally {
|
||||
if (!isBackground) {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
},
|
||||
[cycleId, cycleStartDate, cycleEndDate, selectedFlockId, selectedDate, updateCycle]
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (!selectedCycle || selectedFlockId == null) {
|
||||
userPickedDateRef.current = false;
|
||||
if (cycleId == null || selectedFlockId == null) {
|
||||
setDates([]);
|
||||
setSelectedDate('');
|
||||
setDayRows([]);
|
||||
@@ -131,14 +202,14 @@ const IotPanelPage: React.FC<{ onSettings: () => void }> = ({ onSettings }) => {
|
||||
setError(null);
|
||||
try {
|
||||
const dateList = await api.panelIot.dates({
|
||||
cycle_id: selectedCycle.id,
|
||||
cycle_id: cycleId,
|
||||
flock_id: selectedFlockId,
|
||||
});
|
||||
if (cancelled) return;
|
||||
const sortedDates = [...dateList].sort();
|
||||
setDates(sortedDates);
|
||||
const cycleMin = selectedCycle.start_date;
|
||||
const cycleMax = resolveCycleBoundDate(selectedCycle);
|
||||
const cycleMin = cycleStartDate;
|
||||
const cycleMax = cycleEndDate ?? todayIso();
|
||||
const fallbackDate =
|
||||
todayIso() > cycleMax ? cycleMax : todayIso() < cycleMin ? cycleMin : todayIso();
|
||||
setSelectedDate((previous) => {
|
||||
@@ -159,10 +230,10 @@ const IotPanelPage: React.FC<{ onSettings: () => void }> = ({ onSettings }) => {
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [selectedCycle, selectedFlockId]);
|
||||
}, [cycleId, cycleStartDate, cycleEndDate, selectedFlockId]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!selectedCycle || selectedFlockId == null || !selectedDate) {
|
||||
if (cycleId == null || selectedFlockId == null || !selectedDate) {
|
||||
setDayRows([]);
|
||||
return;
|
||||
}
|
||||
@@ -172,7 +243,7 @@ const IotPanelPage: React.FC<{ onSettings: () => void }> = ({ onSettings }) => {
|
||||
setError(null);
|
||||
try {
|
||||
const data = await api.panelIot.list({
|
||||
cycle_id: selectedCycle.id,
|
||||
cycle_id: cycleId,
|
||||
flock_id: selectedFlockId,
|
||||
date: selectedDate,
|
||||
});
|
||||
@@ -191,7 +262,33 @@ const IotPanelPage: React.FC<{ onSettings: () => void }> = ({ onSettings }) => {
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [selectedCycle, selectedFlockId, selectedDate]);
|
||||
}, [cycleId, selectedFlockId, selectedDate]);
|
||||
|
||||
useEffect(() => {
|
||||
if (cycleId == null || selectedFlockId == null) {
|
||||
return;
|
||||
}
|
||||
const interval = setInterval(() => {
|
||||
if (document.visibilityState === 'visible') {
|
||||
void reload(true);
|
||||
}
|
||||
}, 60000);
|
||||
|
||||
const handleFocusOrVisibility = () => {
|
||||
if (document.visibilityState === 'visible') {
|
||||
void reload(true);
|
||||
}
|
||||
};
|
||||
|
||||
document.addEventListener('visibilitychange', handleFocusOrVisibility);
|
||||
window.addEventListener('focus', handleFocusOrVisibility);
|
||||
|
||||
return () => {
|
||||
clearInterval(interval);
|
||||
document.removeEventListener('visibilitychange', handleFocusOrVisibility);
|
||||
window.removeEventListener('focus', handleFocusOrVisibility);
|
||||
};
|
||||
}, [cycleId, selectedFlockId, reload]);
|
||||
|
||||
const summary = useMemo<DaySummary | null>(() => {
|
||||
if (dayRows.length === 0) return null;
|
||||
@@ -328,7 +425,10 @@ const IotPanelPage: React.FC<{ onSettings: () => void }> = ({ onSettings }) => {
|
||||
value={selectedDate}
|
||||
min={datePickerMin}
|
||||
max={datePickerMax}
|
||||
onChange={(event) => setSelectedDate(event.target.value)}
|
||||
onChange={(event) => {
|
||||
userPickedDateRef.current = true;
|
||||
setSelectedDate(event.target.value);
|
||||
}}
|
||||
className="rounded-lg border border-slate-300 bg-white px-2 py-1.5 text-sm text-slate-700 focus:ring-2 focus:ring-red-500 focus:border-red-500"
|
||||
/>
|
||||
</span>
|
||||
|
||||
@@ -61,14 +61,10 @@ const KpiCard: React.FC<Props> = ({
|
||||
if (title.toUpperCase().includes('FCR') || title.toUpperCase().includes('EEF')) {
|
||||
return formatRatio(value, 3);
|
||||
}
|
||||
if (unit === 'gram' && value > 999) return formatNumber(value / 1000, 2);
|
||||
return formatNumber(value, 2);
|
||||
};
|
||||
|
||||
const displayUnit = () => {
|
||||
if (value !== null && unit === 'gram' && value > 999) return 'kg';
|
||||
return unit;
|
||||
};
|
||||
const displayUnit = () => unit;
|
||||
|
||||
return (
|
||||
<div
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import React, { useEffect, useMemo, useState } from 'react';
|
||||
import React, { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import { api, ApiError, errorMessage } from '../services/apiClient.ts';
|
||||
import type { ChickenWeight, LatestAvg } from '../types/api.ts';
|
||||
import { useFarm } from '../context/FarmContext.tsx';
|
||||
@@ -17,28 +17,46 @@ import DailyWeightGainChart from './weight/DailyWeightGainChart.tsx';
|
||||
import DailyDetailPanel from './weight/DailyDetailPanel.tsx';
|
||||
|
||||
const WeightMonitoringPage: React.FC<{ onSettings: () => void }> = ({ onSettings }) => {
|
||||
const { selectedCycle, selectedSite, selectedKandang } = useFarm();
|
||||
const { selectedCycle, selectedSite, selectedKandang, updateCycle } = useFarm();
|
||||
const [rows, setRows] = useState<ChickenWeight[]>([]);
|
||||
const [latest, setLatest] = useState<LatestAvg | null>(null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [selectedDate, setSelectedDate] = useState('');
|
||||
|
||||
const reload = async (cycleId: number) => {
|
||||
setError(null);
|
||||
try {
|
||||
const list = await api.weights.list({ cycle_id: cycleId });
|
||||
setRows(list);
|
||||
try {
|
||||
setLatest(await api.weights.latestAvg({ cycle_id: cycleId }));
|
||||
} catch (err) {
|
||||
if (err instanceof ApiError && err.status === 404) setLatest(null);
|
||||
else throw err;
|
||||
const reload = useCallback(
|
||||
async (cycleId: number, isBackground = false) => {
|
||||
if (!isBackground) {
|
||||
setLoading(true);
|
||||
}
|
||||
} catch (err) {
|
||||
setError(errorMessage(err));
|
||||
}
|
||||
};
|
||||
setError(null);
|
||||
try {
|
||||
const [list, freshCycle] = await Promise.all([
|
||||
api.weights.list({ cycle_id: cycleId }),
|
||||
api.cycles?.retrieve?.(cycleId)?.catch(() => null) ?? Promise.resolve(null),
|
||||
]);
|
||||
if (freshCycle) {
|
||||
updateCycle(cycleId, freshCycle);
|
||||
}
|
||||
setRows(list);
|
||||
try {
|
||||
setLatest(await api.weights.latestAvg({ cycle_id: cycleId }));
|
||||
} catch (err) {
|
||||
if (err instanceof ApiError && err.status === 404) setLatest(null);
|
||||
else throw err;
|
||||
}
|
||||
} catch (err) {
|
||||
if (!isBackground) {
|
||||
setError(errorMessage(err));
|
||||
}
|
||||
} finally {
|
||||
if (!isBackground) {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
},
|
||||
[updateCycle]
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (!selectedCycle) {
|
||||
@@ -47,20 +65,30 @@ const WeightMonitoringPage: React.FC<{ onSettings: () => void }> = ({ onSettings
|
||||
setSelectedDate('');
|
||||
return;
|
||||
}
|
||||
let cancelled = false;
|
||||
(async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
await reload(selectedCycle.id);
|
||||
} finally {
|
||||
if (!cancelled) setLoading(false);
|
||||
const cycleId = selectedCycle.id;
|
||||
void reload(cycleId, false);
|
||||
|
||||
const interval = setInterval(() => {
|
||||
if (document.visibilityState === 'visible') {
|
||||
void reload(cycleId, true);
|
||||
}
|
||||
}, 60000);
|
||||
|
||||
const handleFocusOrVisibility = () => {
|
||||
if (document.visibilityState === 'visible') {
|
||||
void reload(cycleId, true);
|
||||
}
|
||||
})();
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [selectedCycle]);
|
||||
|
||||
document.addEventListener('visibilitychange', handleFocusOrVisibility);
|
||||
window.addEventListener('focus', handleFocusOrVisibility);
|
||||
|
||||
return () => {
|
||||
clearInterval(interval);
|
||||
document.removeEventListener('visibilitychange', handleFocusOrVisibility);
|
||||
window.removeEventListener('focus', handleFocusOrVisibility);
|
||||
};
|
||||
}, [selectedCycle?.id, reload]);
|
||||
|
||||
// Days without a weighing are stored as 0 g. Charts skip those days so the
|
||||
// line does not drop to zero at the end of a cycle, mirroring the old
|
||||
|
||||
@@ -48,7 +48,7 @@ function mortalityAccuracy(manual: number, iot: number): number {
|
||||
}
|
||||
|
||||
const DataManagementPage: React.FC<{ onSettings: () => void }> = ({ onSettings }) => {
|
||||
const { selectedCycle, selectedKandang, selectedSite } = useFarm();
|
||||
const { selectedCycle, selectedKandang, selectedSite, updateCycle } = useFarm();
|
||||
const [kpis, setKpis] = useState<KPI[]>([]);
|
||||
const [countings, setCountings] = useState<ChickenCounting[]>([]);
|
||||
const [manualRows, setManualRows] = useState<ManualInput[]>([]);
|
||||
@@ -59,24 +59,37 @@ const DataManagementPage: React.FC<{ onSettings: () => void }> = ({ onSettings }
|
||||
|
||||
const isClosedCycle = !selectedCycle || resolveCycleStatus(selectedCycle) !== 'active';
|
||||
|
||||
const loadData = useCallback(async (cycleId: number) => {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
const [k, c, m] = await Promise.all([
|
||||
api.kpis.list({ cycle_id: cycleId }),
|
||||
api.countings.list({ cycle_id: cycleId }),
|
||||
api.manualInputs.list({ cycle_id: cycleId }),
|
||||
]);
|
||||
setKpis(k);
|
||||
setCountings(c);
|
||||
setManualRows(m);
|
||||
} catch (err) {
|
||||
setError(errorMessage(err));
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, []);
|
||||
const loadData = useCallback(
|
||||
async (cycleId: number, isBackground = false) => {
|
||||
if (!isBackground) {
|
||||
setLoading(true);
|
||||
}
|
||||
setError(null);
|
||||
try {
|
||||
const [k, c, m, freshCycle] = await Promise.all([
|
||||
api.kpis.list({ cycle_id: cycleId }),
|
||||
api.countings.list({ cycle_id: cycleId }),
|
||||
api.manualInputs.list({ cycle_id: cycleId }),
|
||||
api.cycles?.retrieve?.(cycleId)?.catch(() => null) ?? Promise.resolve(null),
|
||||
]);
|
||||
if (freshCycle) {
|
||||
updateCycle(cycleId, freshCycle);
|
||||
}
|
||||
setKpis(k);
|
||||
setCountings(c);
|
||||
setManualRows(m);
|
||||
} catch (err) {
|
||||
if (!isBackground) {
|
||||
setError(errorMessage(err));
|
||||
}
|
||||
} finally {
|
||||
if (!isBackground) {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
},
|
||||
[updateCycle]
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (!selectedCycle) {
|
||||
@@ -85,8 +98,30 @@ const DataManagementPage: React.FC<{ onSettings: () => void }> = ({ onSettings }
|
||||
setManualRows([]);
|
||||
return;
|
||||
}
|
||||
void loadData(selectedCycle.id);
|
||||
}, [selectedCycle, loadData]);
|
||||
const cycleId = selectedCycle.id;
|
||||
void loadData(cycleId, false);
|
||||
|
||||
const interval = setInterval(() => {
|
||||
if (document.visibilityState === 'visible') {
|
||||
void loadData(cycleId, true);
|
||||
}
|
||||
}, 60000);
|
||||
|
||||
const handleFocusOrVisibility = () => {
|
||||
if (document.visibilityState === 'visible') {
|
||||
void loadData(cycleId, true);
|
||||
}
|
||||
};
|
||||
|
||||
document.addEventListener('visibilitychange', handleFocusOrVisibility);
|
||||
window.addEventListener('focus', handleFocusOrVisibility);
|
||||
|
||||
return () => {
|
||||
clearInterval(interval);
|
||||
document.removeEventListener('visibilitychange', handleFocusOrVisibility);
|
||||
window.removeEventListener('focus', handleFocusOrVisibility);
|
||||
};
|
||||
}, [selectedCycle?.id, loadData]);
|
||||
|
||||
// Build daily rows through calendar today (not publish-gated current_day).
|
||||
const rows = useMemo<Row[]>(() => {
|
||||
|
||||
@@ -19,6 +19,7 @@ import type {
|
||||
} from '../../types/api.ts';
|
||||
import { formatNumber, formatRatio } from '../../utils/format.ts';
|
||||
import { getCobbStandardForDay } from '../../utils/insightHelpers.ts';
|
||||
import { getMortalityCumStandardByDay } from '../../utils/cp707EnvStandards.ts';
|
||||
import { parseAiResult, type AiResult } from '../../utils/insightParse.ts';
|
||||
import {
|
||||
scopeContextToTimeframe,
|
||||
@@ -465,23 +466,24 @@ export const PageAiInsight: React.FC<PageAiInsightProps> = ({
|
||||
if (actual === null) return null;
|
||||
const awal = n(displayContext.populasi_awal_ekor);
|
||||
const mortPct = n(displayContext.mortalitas_persen);
|
||||
const mortStd = getMortalityCumStandardByDay(effectiveDay ?? currentDay);
|
||||
return {
|
||||
label: 'Populasi Kini',
|
||||
value: Math.round(actual).toLocaleString('id-ID'),
|
||||
unit: 'ekor',
|
||||
context:
|
||||
awal === null ? null : `Populasi awal: ${Math.round(awal).toLocaleString('id-ID')} ekor`,
|
||||
status: (mortPct === null
|
||||
status: (mortPct === null || mortStd === null
|
||||
? 'unknown'
|
||||
: mortPct < 5
|
||||
: mortPct <= mortStd
|
||||
? 'ok'
|
||||
: mortPct <= 7
|
||||
? 'warning'
|
||||
: 'critical') as InsightStatus,
|
||||
: 'warning') as InsightStatus,
|
||||
deltaLabel:
|
||||
mortPct === null
|
||||
? null
|
||||
: `Mortalitas ${mortPct.toLocaleString('id-ID', { maximumFractionDigits: 2 })}%`,
|
||||
: mortStd !== null
|
||||
? `Mortalitas ${mortPct.toLocaleString('id-ID', { maximumFractionDigits: 2 })}% (std ${mortStd.toLocaleString('id-ID', { maximumFractionDigits: 2 })}%)`
|
||||
: `Mortalitas ${mortPct.toLocaleString('id-ID', { maximumFractionDigits: 2 })}%`,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -153,6 +153,7 @@ const DailyWeightGainChart: React.FC<DailyWeightGainChartProps> = ({ rows, docWe
|
||||
<YAxis
|
||||
tick={{ fill: '#6b7280', fontSize: 12 }}
|
||||
tickFormatter={(value) => formatWeight(value, { stripTrailingZeros: true })}
|
||||
width={60}
|
||||
/>
|
||||
<Legend content={<CustomLegend />} />
|
||||
<Tooltip content={<CustomTooltip />} />
|
||||
|
||||
@@ -112,6 +112,7 @@ const DailyWeightProgressionChart: React.FC<DailyWeightProgressionChartProps> =
|
||||
<YAxis
|
||||
tick={{ fill: '#6b7280', fontSize: 12 }}
|
||||
tickFormatter={(value) => formatWeight(value, { stripTrailingZeros: true })}
|
||||
width={65}
|
||||
/>
|
||||
<Tooltip content={<CustomTooltip />} />
|
||||
<Line
|
||||
|
||||
@@ -220,6 +220,7 @@ export const api = {
|
||||
cycles: {
|
||||
list: async (query?: CycleFilter) =>
|
||||
unwrapList(await get<Paginated<Cycle> | Cycle[]>('/cycles/', query)),
|
||||
retrieve: (id: number) => get<Cycle>(`/cycles/${id}/`),
|
||||
create: (body: CycleWrite) => post<Cycle>('/cycles/', body),
|
||||
update: (id: number, body: Partial<CycleWrite>) => patch<Cycle>(`/cycles/${id}/`, body),
|
||||
remove: (id: number) => del(`/cycles/${id}/`),
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { weightStandardData } from '../../mockData/weightStandardData.ts';
|
||||
import { getTargetGainForAge, getTargetWeightForAge } from '../weight.ts';
|
||||
import { formatWeight, getTargetGainForAge, getTargetWeightForAge } from '../weight.ts';
|
||||
|
||||
function rowForDoc(docWeight: number) {
|
||||
return weightStandardData.data.find((row) => row.day === docWeight)!;
|
||||
@@ -50,3 +50,33 @@ describe('getTargetGainForAge', () => {
|
||||
expect(getTargetGainForAge(1, -5)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('formatWeight', () => {
|
||||
it('formats small weights in grams', () => {
|
||||
expect(formatWeight(42, { decimals: 0 })).toBe('42 g');
|
||||
expect(formatWeight(500, { stripTrailingZeros: true })).toBe('500 g');
|
||||
});
|
||||
|
||||
it('formats large weights in grams instead of kg', () => {
|
||||
expect(formatWeight(1000, { stripTrailingZeros: true })).toBe('1.000 g');
|
||||
expect(formatWeight(1450, { stripTrailingZeros: true })).toBe('1.450 g');
|
||||
expect(formatWeight(2500, { stripTrailingZeros: true })).toBe('2.500 g');
|
||||
});
|
||||
|
||||
it('handles null and undefined', () => {
|
||||
expect(formatWeight(null, { stripTrailingZeros: true })).toBe('0 g');
|
||||
expect(formatWeight(undefined, { stripTrailingZeros: true })).toBe('0 g');
|
||||
expect(formatWeight(null)).toBe('0,0000 g');
|
||||
});
|
||||
|
||||
it('handles negative values with minus sign', () => {
|
||||
expect(formatWeight(-150, { stripTrailingZeros: true })).toBe('-150 g');
|
||||
});
|
||||
|
||||
it('supports custom suffix and unit options', () => {
|
||||
expect(formatWeight(52.34, { suffix: '/hari', decimals: 2, truncate: true })).toBe(
|
||||
'52,34 g/hari'
|
||||
);
|
||||
expect(formatWeight(1500, { stripTrailingZeros: true, unit: 'gram' })).toBe('1.500 gram');
|
||||
});
|
||||
});
|
||||
@@ -7,7 +7,7 @@ import type {
|
||||
ManualInput,
|
||||
} from '../types/api.ts';
|
||||
import type { DashboardReportPayload, DashboardReportType } from '../types/dashboardReport.ts';
|
||||
import { cycleDayForDate } from './format.ts';
|
||||
import { cycleDayForDate, cycleLastDayIndex, resolveCycleBoundDate } from './format.ts';
|
||||
|
||||
export type BuildInMemoryReportInput = {
|
||||
cycle: Cycle;
|
||||
@@ -48,11 +48,8 @@ function feedAccuracy(iot: number | null, manual: number | null): number | null
|
||||
export function buildInMemoryReport(input: BuildInMemoryReportInput): DashboardReportPayload {
|
||||
const { cycle } = input;
|
||||
// Day numbering stays 0-based (day 0 = start_date), but the report must never
|
||||
// run past the cycle end date. lastDay = start_date → end_date in days, which
|
||||
// is total_days - 1 for a contiguous cycle.
|
||||
const lastDay = cycle.end_date
|
||||
? cycleDayForDate(cycle.start_date, cycle.end_date)
|
||||
: Math.max(0, (cycle.total_days || 1) - 1);
|
||||
// run past the approved end (or soft bound while open).
|
||||
const lastDay = cycleLastDayIndex(cycle);
|
||||
const endCycleUpTo = Math.min(cycle.total_days, lastDay);
|
||||
const defaultUpTo =
|
||||
input.reportType === 'end_cycle'
|
||||
@@ -108,7 +105,10 @@ export function buildInMemoryReport(input: BuildInMemoryReportInput): DashboardR
|
||||
const mati = mortality ?? 0;
|
||||
const panen = harvest ?? 0;
|
||||
const countBefore = day === 0 ? cycle.doc_in_count || 0 : (previousStockAkhir ?? 0);
|
||||
const countAfter = kpi?.chicken_life ?? Math.max(0, countBefore - mati - panen);
|
||||
const countAfter =
|
||||
kpi != null
|
||||
? Math.max(0, kpi.chicken_life - (kpi.harvest_total ?? 0))
|
||||
: Math.max(0, countBefore - mati - panen);
|
||||
previousStockAkhir = countAfter;
|
||||
|
||||
return {
|
||||
@@ -204,7 +204,7 @@ export function buildInMemoryReport(input: BuildInMemoryReportInput): DashboardR
|
||||
return {
|
||||
cycleId: String(cycle.id),
|
||||
cycleStart: cycle.start_date,
|
||||
cycleEnd: cycle.end_date ?? '',
|
||||
cycleEnd: cycle.end_date ?? resolveCycleBoundDate(cycle),
|
||||
kandangId: input.kandangId,
|
||||
kandangName: input.kandangName,
|
||||
area: input.area,
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import type { ChickenCounting, Cycle, KPI, ManualInput } from '../types/api.ts';
|
||||
import { addDaysIso, cycleDayForDate } from './format.ts';
|
||||
import { addDaysIso, cycleDayForDate, todayIso } from './format.ts';
|
||||
import { stockAkhirFromKpi } from './kpiStock.ts';
|
||||
|
||||
export const COUNTING_ACCURACY_WARNING_THRESHOLD = 95;
|
||||
|
||||
@@ -37,11 +38,10 @@ function stockAkhirByDate(
|
||||
const kpiByDate = new Map(kpis.map((k) => [k.date, k]));
|
||||
const manualByDate = new Map(manualInputs.map((m) => [m.date, m]));
|
||||
|
||||
const lastCycleDay = Math.max(0, (cycle.total_days || 1) - 1);
|
||||
const endDay = cycle.end_date
|
||||
? cycleDayForDate(cycle.start_date, cycle.end_date)
|
||||
: lastCycleDay;
|
||||
const maxDay = Math.min(lastCycleDay, endDay);
|
||||
const calendarDay = cycleDayForDate(cycle.start_date, todayIso());
|
||||
const maxDay = cycle.end_date
|
||||
? Math.min(calendarDay, cycleDayForDate(cycle.start_date, cycle.end_date))
|
||||
: calendarDay;
|
||||
|
||||
const result = new Map<string, number>();
|
||||
let previousStockAkhir = 0;
|
||||
@@ -53,7 +53,7 @@ function stockAkhirByDate(
|
||||
const stockAwal = day === 0 ? cycle.doc_in_count || 0 : previousStockAkhir;
|
||||
const mati = manual?.mortality_manual ?? kpi?.mortality ?? 0;
|
||||
const panen = manual?.harvest_manual ?? kpi?.harvest ?? 0;
|
||||
const stockAkhir = kpi?.chicken_life ?? Math.max(0, stockAwal - mati - panen);
|
||||
const stockAkhir = stockAkhirFromKpi(kpi) ?? Math.max(0, stockAwal - mati - panen);
|
||||
result.set(date, stockAkhir);
|
||||
previousStockAkhir = stockAkhir;
|
||||
}
|
||||
|
||||
@@ -67,6 +67,60 @@ export const getTempStandardByDay = (dayAge: number | null | undefined): number
|
||||
return row ? row.temp_C : null;
|
||||
};
|
||||
|
||||
/** Standar mortalitas kumulatif harian CP 707 (Lampiran 2) — hari 1..37. */
|
||||
const MORTALITY_CUM_STANDARD_BY_DAY: Record<number, number> = {
|
||||
1: 0.4,
|
||||
2: 0.5,
|
||||
3: 0.6,
|
||||
4: 0.7,
|
||||
5: 0.8,
|
||||
6: 0.9,
|
||||
7: 1.0,
|
||||
8: 1.1,
|
||||
9: 1.2,
|
||||
10: 1.3,
|
||||
11: 1.4,
|
||||
12: 1.5,
|
||||
13: 1.6,
|
||||
14: 1.7,
|
||||
15: 1.8,
|
||||
16: 1.9,
|
||||
17: 2.0,
|
||||
18: 2.1,
|
||||
19: 2.2,
|
||||
20: 2.3,
|
||||
21: 2.4,
|
||||
22: 2.52,
|
||||
23: 2.64,
|
||||
24: 2.76,
|
||||
25: 2.88,
|
||||
26: 3.0,
|
||||
27: 3.12,
|
||||
28: 3.25,
|
||||
29: 3.38,
|
||||
30: 3.52,
|
||||
31: 3.66,
|
||||
32: 3.8,
|
||||
33: 3.95,
|
||||
34: 4.1,
|
||||
35: 4.25,
|
||||
36: 4.45,
|
||||
37: 4.65,
|
||||
};
|
||||
|
||||
/**
|
||||
* Standar mortalitas kumulatif (%) untuk umur hari tertentu (sinkron dengan
|
||||
* `get_mortality_cum_std_by_day` di `cp707_knowledge.py`).
|
||||
*/
|
||||
export const getMortalityCumStandardByDay = (dayAge: number | null | undefined): number | null => {
|
||||
if (typeof dayAge !== 'number' || !Number.isFinite(dayAge) || dayAge < 0) return null;
|
||||
const day = Math.trunc(dayAge);
|
||||
if (day === 0) return 0.4;
|
||||
if (day in MORTALITY_CUM_STANDARD_BY_DAY) return MORTALITY_CUM_STANDARD_BY_DAY[day]!;
|
||||
if (day > 37) return Math.round((4.65 + (day - 37) * 0.1) * 100) / 100;
|
||||
return null;
|
||||
};
|
||||
|
||||
/**
|
||||
* Number out of a display-formatted reading.
|
||||
*
|
||||
|
||||
+16
-10
@@ -1,25 +1,33 @@
|
||||
import { weightStandardData } from '../mockData/weightStandardData.ts';
|
||||
|
||||
/**
|
||||
* Formats a weight value in grams into a locale-aware string. Values at or
|
||||
* below 999 g stay in grams; larger values are shown in kg. Negative values
|
||||
* (e.g. ADG during close-out) are shown with a minus sign.
|
||||
* Formats a weight value in grams into a locale-aware string. Values are always
|
||||
* shown in grams (g). Negative values (e.g. ADG during close-out) are shown
|
||||
* with a minus sign.
|
||||
*
|
||||
* By default every value is shown with 4 decimal places (never rounded).
|
||||
* Callers may override with options:
|
||||
* - `decimals` decimal places to show (default 4)
|
||||
* - `stripTrailingZeros` drop trailing zeros so the exact value is shown
|
||||
* - `truncate` truncate instead of round (default false)
|
||||
* - `unit` unit to append (default 'g')
|
||||
*/
|
||||
export function formatWeight(
|
||||
grams: number | null | undefined,
|
||||
options?: { suffix?: string; decimals?: number; stripTrailingZeros?: boolean; truncate?: boolean }
|
||||
options?: {
|
||||
suffix?: string;
|
||||
decimals?: number;
|
||||
stripTrailingZeros?: boolean;
|
||||
truncate?: boolean;
|
||||
unit?: string;
|
||||
}
|
||||
): string {
|
||||
const suffix = options?.suffix ?? '';
|
||||
const decimals = options?.decimals ?? 4;
|
||||
const minDecimals = options?.stripTrailingZeros ? 0 : decimals;
|
||||
const unit = options?.unit ?? 'g';
|
||||
|
||||
const format = (value: number, unit: string): string => {
|
||||
const format = (value: number, u: string): string => {
|
||||
let display = value;
|
||||
if (options?.truncate) {
|
||||
const factor = 10 ** decimals;
|
||||
@@ -29,15 +37,13 @@ export function formatWeight(
|
||||
minimumFractionDigits: minDecimals,
|
||||
maximumFractionDigits: decimals,
|
||||
});
|
||||
return `${formatted} ${unit}${suffix}`;
|
||||
return `${formatted} ${u}${suffix}`;
|
||||
};
|
||||
|
||||
if (grams == null) return format(0, 'g');
|
||||
if (grams == null) return format(0, unit);
|
||||
const sign = grams < 0 ? '-' : '';
|
||||
const abs = Math.abs(grams);
|
||||
const unit = abs <= 999 ? 'g' : 'kg';
|
||||
const display = abs <= 999 ? abs : abs / 1000;
|
||||
return `${sign}${format(display, unit)}`;
|
||||
return `${sign}${format(abs, unit)}`;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
Reference in new issue
Block a user