From 438840622d2b787885371f409d5eca664bb631fd Mon Sep 17 00:00:00 2001 From: Alberto-Audrix Date: Thu, 5 Nov 2026 11:37:20 +0700 Subject: [PATCH] update report fix, live reload, mortality standard, weight use gram instead of kg --- backend/apps/operations/views.py | 6 +- components/AiInsightCard.tsx | 40 +++--- components/Dashboard.tsx | 130 ++++++++++++------ components/EefDashboardPage.tsx | 68 ++++++--- components/FcrDashboardPage.tsx | 74 ++++++---- components/FeedSackCountingPage.tsx | 73 +++++++--- components/Header.tsx | 1 + components/IotPanelPage.tsx | 126 +++++++++++++++-- components/KpiCard.tsx | 6 +- components/WeightMonitoringPage.tsx | 84 +++++++---- components/counting/DataManagementPage.tsx | 77 ++++++++--- components/shared/PageAiInsight.tsx | 14 +- components/weight/DailyWeightGainChart.tsx | 1 + .../weight/DailyWeightProgressionChart.tsx | 1 + services/apiClient.ts | 1 + utils/__tests__/weight.test.ts | 32 ++++- utils/buildInMemoryReport.ts | 16 +-- utils/countingAccuracyWarning.ts | 14 +- utils/cp707EnvStandards.ts | 54 ++++++++ utils/weight.ts | 26 ++-- 20 files changed, 623 insertions(+), 221 deletions(-) diff --git a/backend/apps/operations/views.py b/backend/apps/operations/views.py index b8a7c5d..e0a2f1f 100644 --- a/backend/apps/operations/views.py +++ b/backend/apps/operations/views.py @@ -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) + ), } diff --git a/components/AiInsightCard.tsx b/components/AiInsightCard.tsx index e7250f0..c31acba 100644 --- a/components/AiInsightCard.tsx +++ b/components/AiInsightCard.tsx @@ -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 = ({ 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 = ({ 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)}%` } /> = ({ {item.confidence} ) : null} - {item.fase ? ( - - {item.fase} - - ) : null} {item.bukti.length > 0 ? (
    @@ -1108,10 +1117,7 @@ export const AiInsightCard: React.FC = ({ key={`${item.id ?? item.aksi}-${index}`} className="rounded-lg border border-blue-200/70 bg-white/90 p-3.5 shadow-xs" > -

    - {item.fase} -

    -

    {item.aksi}

    +

    {item.aksi}

    {item.metrik_pantau ? (

    Pantau: {item.metrik_pantau} diff --git a/components/Dashboard.tsx b/components/Dashboard.tsx index 5e5c9ae..54e9881 100644 --- a/components/Dashboard.tsx +++ b/components/Dashboard.tsx @@ -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(rows: T[]): T[] { } const Dashboard: React.FC = ({ setView }) => { - const { selectedCycle, selectedKandang, selectedSite, selectedKandangId } = useFarm(); + const { selectedCycle, selectedKandang, selectedSite, selectedKandangId, updateCycle } = + useFarm(); const [loading, setLoading] = useState(false); const [error, setError] = useState(null); const [kpis, setKpis] = useState([]); @@ -55,30 +57,35 @@ const Dashboard: React.FC = ({ setView }) => { const [reportOpen, setReportOpen] = useState(false); const [reportType, setReportType] = useState('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 = ({ 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( diff --git a/components/EefDashboardPage.tsx b/components/EefDashboardPage.tsx index 238f99b..b594678 100644 --- a/components/EefDashboardPage.tsx +++ b/components/EefDashboardPage.tsx @@ -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([]); const [loading, setLoading] = useState(false); const [error, setError] = useState(null); const [lastUpdated, setLastUpdated] = useState(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( () => diff --git a/components/FcrDashboardPage.tsx b/components/FcrDashboardPage.tsx index c4d6550..8dd7126 100644 --- a/components/FcrDashboardPage.tsx +++ b/components/FcrDashboardPage.tsx @@ -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([]); const [weightRows, setWeightRows] = useState([]); const [loading, setLoading] = useState(false); const [error, setError] = useState(null); const [lastUpdated, setLastUpdated] = useState(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(); diff --git a/components/FeedSackCountingPage.tsx b/components/FeedSackCountingPage.tsx index ce507b3..8425190 100644 --- a/components/FeedSackCountingPage.tsx +++ b/components/FeedSackCountingPage.tsx @@ -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([]); const [manualRows, setManualRows] = useState([]); @@ -22,22 +22,35 @@ const FeedSackCountingPage: React.FC<{ onSettings: () => void }> = ({ onSettings const [error, setError] = useState(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( diff --git a/components/Header.tsx b/components/Header.tsx index 6b507bb..e3579f9 100644 --- a/components/Header.tsx +++ b/components/Header.tsx @@ -94,6 +94,7 @@ const Header: React.FC = ({ 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)); diff --git a/components/IotPanelPage.tsx b/components/IotPanelPage.tsx index bbdd5f7..6569475 100644 --- a/components/IotPanelPage.tsx +++ b/components/IotPanelPage.tsx @@ -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([]); const [selectedFlockId, setSelectedFlockId] = useState(null); const [dates, setDates] = useState([]); @@ -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(() => { 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" /> diff --git a/components/KpiCard.tsx b/components/KpiCard.tsx index 442e353..8401f01 100644 --- a/components/KpiCard.tsx +++ b/components/KpiCard.tsx @@ -61,14 +61,10 @@ const KpiCard: React.FC = ({ 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 (

    void }> = ({ onSettings }) => { - const { selectedCycle, selectedSite, selectedKandang } = useFarm(); + const { selectedCycle, selectedSite, selectedKandang, updateCycle } = useFarm(); const [rows, setRows] = useState([]); const [latest, setLatest] = useState(null); const [loading, setLoading] = useState(false); const [error, setError] = useState(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 diff --git a/components/counting/DataManagementPage.tsx b/components/counting/DataManagementPage.tsx index 0e1627b..102fe08 100644 --- a/components/counting/DataManagementPage.tsx +++ b/components/counting/DataManagementPage.tsx @@ -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([]); const [countings, setCountings] = useState([]); const [manualRows, setManualRows] = useState([]); @@ -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(() => { diff --git a/components/shared/PageAiInsight.tsx b/components/shared/PageAiInsight.tsx index cdf5ccd..96d67d2 100644 --- a/components/shared/PageAiInsight.tsx +++ b/components/shared/PageAiInsight.tsx @@ -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 = ({ 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 })}%`, }; } diff --git a/components/weight/DailyWeightGainChart.tsx b/components/weight/DailyWeightGainChart.tsx index 0b6612a..7a09129 100644 --- a/components/weight/DailyWeightGainChart.tsx +++ b/components/weight/DailyWeightGainChart.tsx @@ -153,6 +153,7 @@ const DailyWeightGainChart: React.FC = ({ rows, docWe formatWeight(value, { stripTrailingZeros: true })} + width={60} /> } /> } /> diff --git a/components/weight/DailyWeightProgressionChart.tsx b/components/weight/DailyWeightProgressionChart.tsx index e132325..79e0d0a 100644 --- a/components/weight/DailyWeightProgressionChart.tsx +++ b/components/weight/DailyWeightProgressionChart.tsx @@ -112,6 +112,7 @@ const DailyWeightProgressionChart: React.FC = formatWeight(value, { stripTrailingZeros: true })} + width={65} /> } /> unwrapList(await get | Cycle[]>('/cycles/', query)), + retrieve: (id: number) => get(`/cycles/${id}/`), create: (body: CycleWrite) => post('/cycles/', body), update: (id: number, body: Partial) => patch(`/cycles/${id}/`, body), remove: (id: number) => del(`/cycles/${id}/`), diff --git a/utils/__tests__/weight.test.ts b/utils/__tests__/weight.test.ts index 1b8c93c..8f1f520 100644 --- a/utils/__tests__/weight.test.ts +++ b/utils/__tests__/weight.test.ts @@ -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'); + }); +}); diff --git a/utils/buildInMemoryReport.ts b/utils/buildInMemoryReport.ts index 8d38390..b6a7cc4 100644 --- a/utils/buildInMemoryReport.ts +++ b/utils/buildInMemoryReport.ts @@ -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, diff --git a/utils/countingAccuracyWarning.ts b/utils/countingAccuracyWarning.ts index 59b8548..f6d8fa7 100644 --- a/utils/countingAccuracyWarning.ts +++ b/utils/countingAccuracyWarning.ts @@ -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(); 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; } diff --git a/utils/cp707EnvStandards.ts b/utils/cp707EnvStandards.ts index ce2c737..0e7b8b9 100644 --- a/utils/cp707EnvStandards.ts +++ b/utils/cp707EnvStandards.ts @@ -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 = { + 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. * diff --git a/utils/weight.ts b/utils/weight.ts index f450a47..cfaaee0 100644 --- a/utils/weight.ts +++ b/utils/weight.ts @@ -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)}`; } /**