adjust dashboard architecture to copy the newest update from dashboard-cpsp

This commit is contained in:
Alberto-Audrix committed 2026-10-21 16:42:03 +07:00
1 parent 0ba2c7ff1b
commit fc7502ba79
23 files changed
+993 -319

No files matched your search

@@ -0,0 +1,16 @@
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('operations', '0013_chickenweight_chicken_area_and_more'),
]
operations = [
migrations.AddField(
model_name='aiinsight',
name='harvest_prediction',
field=models.JSONField(blank=True, null=True),
),
]
+1
View File
@@ -43,6 +43,7 @@ class AIInsight(models.Model):
report_period = models.CharField(max_length=64, blank=True, default="current", db_index=True)
summary = models.TextField(blank=True, default="")
citations = models.TextField(blank=True, default="[]")
harvest_prediction = models.JSONField(null=True, blank=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
+1
View File
@@ -372,6 +372,7 @@ class AIInsightViewSet(CycleScopedViewSet):
"structured_end_cycle": structured_end_cycle,
"alert": row.alert,
"citations": cites,
"harvest_prediction": getattr(row, "harvest_prediction", None),
}
@@ -440,6 +440,9 @@ def _upsert_ai_insights(cycle: Cycle, rows: list[dict[str, Any]]) -> int:
citations_str = raw_citations
else:
citations_str = "[]"
harvest_prediction = raw.get("harvest_prediction")
if not isinstance(harvest_prediction, (dict, list)):
harvest_prediction = None
AIInsight.objects.update_or_create(
cycle=cycle,
@@ -453,6 +456,7 @@ def _upsert_ai_insights(cycle: Cycle, rows: list[dict[str, Any]]) -> int:
"summary": summary,
"alert": alert,
"citations": citations_str,
"harvest_prediction": harvest_prediction,
},
)
count += 1
+20 -12
View File
@@ -226,21 +226,29 @@ CREATE UNIQUE INDEX IF NOT EXISTS uniq_iot_panel_flock_timestamp ON iot_panel (f
-- 9. AI Insight
-- -----------------------------------------------------------------------------
CREATE TABLE IF NOT EXISTS ai_insight (
id BIGSERIAL PRIMARY KEY,
date DATE NOT NULL,
insight_text TEXT NOT NULL,
alert VARCHAR(100) NOT NULL,
section VARCHAR(100) NOT NULL,
session VARCHAR(100) NOT NULL,
created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP,
cycle_id BIGINT NOT NULL REFERENCES cycles (cycle_id) ON DELETE CASCADE
id BIGSERIAL PRIMARY KEY,
date DATE NOT NULL,
insight_text TEXT NOT NULL,
alert VARCHAR(100) NOT NULL DEFAULT '',
cycle_id BIGINT NOT NULL REFERENCES cycles (cycle_id) ON DELETE CASCADE,
kandang_id BIGINT REFERENCES kandang (kandang_id) ON DELETE CASCADE,
topic VARCHAR(64) NOT NULL DEFAULT '',
report_type VARCHAR(32) NOT NULL DEFAULT 'page',
report_period VARCHAR(64) NOT NULL DEFAULT 'current',
summary TEXT NOT NULL DEFAULT '',
citations TEXT NOT NULL DEFAULT '[]',
harvest_prediction JSONB,
created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX IF NOT EXISTS idx_ai_insight_cycle_id ON ai_insight (cycle_id);
CREATE INDEX IF NOT EXISTS idx_ai_insight_date ON ai_insight (date);
CREATE UNIQUE INDEX IF NOT EXISTS uniq_ai_insight_cycle_date_section_session
ON ai_insight (cycle_id, date, section, session);
CREATE INDEX IF NOT EXISTS idx_ai_insight_kandang_id ON ai_insight (kandang_id);
CREATE INDEX IF NOT EXISTS idx_ai_insight_topic ON ai_insight (topic);
CREATE INDEX IF NOT EXISTS idx_ai_insight_report_type ON ai_insight (report_type);
CREATE INDEX IF NOT EXISTS idx_ai_insight_report_period ON ai_insight (report_period);
CREATE UNIQUE INDEX IF NOT EXISTS uniq_ai_insight_cycle_kandang_topic_type_period
ON ai_insight (cycle_id, kandang_id, topic, report_type, report_period);
-- -----------------------------------------------------------------------------
-- 10. Feed Sacks
+343 -212
View File
@@ -9,6 +9,7 @@ import { useFarm } from '../context/FarmContext.tsx';
import { api, errorMessage } from '../services/apiClient.ts';
import type {
EndCycleStructuredInsight,
HarvestPredictionResult,
InsightCitation,
InsightContext,
InsightReportType,
@@ -27,22 +28,19 @@ import { parseAiResult, type AiResult } from '../utils/insightParse.ts';
import { formatRatio } from '../utils/format.ts';
import {
HeroFigure,
InsightStatusBadge,
INSIGHT_STATUS_META,
MutedStatRow,
normalizeInsightStatus,
StatTile,
type InsightStatus,
} from './shared/InsightStatTiles.tsx';
import InsightTrendChart from './shared/InsightTrendChart.tsx';
import HarvestPredictionWidget from './shared/HarvestPredictionWidget.tsx';
const CLIENT_TIMEOUT_MS = 1_200_000; // 20 minutes
const END_CYCLE_JSON_MARKER = '<!--end_cycle_json-->';
const sectionBadgeClasses: Record<InsightStatusLabel, string> = {
ok: 'border-emerald-200 bg-emerald-50 text-emerald-700',
warning: 'border-amber-200 bg-amber-50 text-amber-700',
critical: 'border-red-200 bg-red-50 text-red-700',
unknown: 'border-slate-200 bg-slate-50 text-slate-600',
};
const confidenceBadge: Record<string, string> = {
high: 'border-red-200 bg-red-50 text-red-700',
med: 'border-amber-200 bg-amber-50 text-amber-700',
@@ -261,14 +259,17 @@ export const AiInsightCard: React.FC<AiInsightCardProps> = ({
const [loading, setLoading] = useState(false);
const [lastUpdated, setLastUpdated] = useState<Date | null>(null);
const [error, setError] = useState<string | null>(null);
const [insightAlert, setInsightAlert] = useState<string | null>(null);
const [detailsOpen, setDetailsOpen] = useState(false);
const [reportType, setReportType] = useState<InsightReportType>('daily');
const [dayPeriod, setDayPeriod] = useState<string | null>(null);
const [isCollapsed, setIsCollapsed] = useState(false);
const [harvestPrediction, setHarvestPrediction] = useState<HarvestPredictionResult | null>(null);
const cardRef = useRef<HTMLDivElement>(null);
const insightInFlightRef = useRef(false);
const effectiveKandangId = kandangId ?? selectedKandangId;
const contextDay =
typeof contextProp?.hari_ke === 'number' && Number.isFinite(contextProp.hari_ke)
? contextProp.hari_ke
@@ -297,10 +298,16 @@ export const AiInsightCard: React.FC<AiInsightCardProps> = ({
structuredEndCycle?: EndCycleStructuredInsight | null,
summary?: string | null,
akarMasalah?: string | null,
insightBody?: string | null
insightBody?: string | null,
alert?: string | null,
prediction?: HarvestPredictionResult | null
) => {
const citationsArg = Array.isArray(nextCitations) ? nextCitations : [];
setInsightText(text);
setInsightAlert(alert ?? null);
if (prediction !== undefined) {
setHarvestPrediction(prediction);
}
const endCycle =
structuredEndCycle ??
parseEndCycleFromText(text, summary) ??
@@ -393,6 +400,21 @@ export const AiInsightCard: React.FC<AiInsightCardProps> = ({
contextPayload.target_bw_gram = currentTarget;
}
const curDay = typeof contextPayload.hari_ke === 'number' ? contextPayload.hari_ke : null;
if (curDay != null && curDay > 0) {
const curBw = scopedMetrics.bobot_avg_gram;
const prevWeightRow = [...scopedMetrics.weightSeries]
.reverse()
.find((row) => row.hari < curDay && row.actual != null && row.actual > 0);
if (curBw != null && curBw > 0 && prevWeightRow && prevWeightRow.actual != null) {
const dayDiff = curDay - prevWeightRow.hari;
if (dayDiff > 0) {
contextPayload.adg_actual_gram =
Math.round(((curBw - prevWeightRow.actual) / dayDiff) * 100) / 100;
}
}
}
// EEF series for trend computation (eef, dashboard, end_cycle topics)
if (topic === 'eef' || topic === 'dashboard' || reportType === 'end_cycle') {
contextPayload.eef_seri = scopedMetrics.kpiSeries
@@ -401,6 +423,12 @@ export const AiInsightCard: React.FC<AiInsightCardProps> = ({
}
}
if (topic === 'dashboard') {
if (selectedCycle.start_date) {
contextPayload.cycle_start_date = selectedCycle.start_date;
}
}
if (reportType === 'end_cycle' && scopedMetrics) {
const rollups = buildEndCycleRollups(scopedMetrics, iotDayAggregates);
contextPayload.weekly_summaries = rollups.weekly_summaries;
@@ -434,7 +462,7 @@ export const AiInsightCard: React.FC<AiInsightCardProps> = ({
}
// Manual-generate only: never POST generate on mount / soft refresh.
if (!apiResult) {
applyInsight('', 'cache');
applyInsight('', 'cache', null, null, null, null, null, null);
setLastUpdated(null);
setError(null);
return;
@@ -473,19 +501,21 @@ export const AiInsightCard: React.FC<AiInsightCardProps> = ({
apiResult.structured_end_cycle ?? null,
apiResult.summary,
apiResult.akar_masalah,
apiResult.insight
apiResult.insight,
(apiResult as Record<string, unknown> | null)?.alert as string | undefined,
apiResult.harvest_prediction ?? null
);
setLastUpdated(new Date());
setDetailsOpen(false);
} catch (err) {
console.error('Error generating insight:', err);
if (forceRefresh) {
applyInsight('', 'local_fallback');
applyInsight('', 'local_fallback', null, null, null, null, null, null);
setLastUpdated(null);
setError(errorMessage(err));
setDetailsOpen(false);
} else {
applyInsight('', 'cache');
applyInsight('', 'cache', null, null, null, null, null, null);
setLastUpdated(null);
setError(null);
}
@@ -541,19 +571,11 @@ export const AiInsightCard: React.FC<AiInsightCardProps> = ({
);
};
const renderDetailSection = (
title: string,
section: InsightStructuredSection,
accentClass: string
) => (
const renderDetailSection = (title: string, section: InsightStructuredSection) => (
<section className="rounded-xl border border-gray-100 bg-white p-4 shadow-sm">
<div className="flex items-center justify-between gap-3">
<p className="text-xs font-semibold uppercase tracking-[0.16em] text-gray-500">{title}</p>
<span
className={`rounded-full border px-2.5 py-1 text-xs font-semibold uppercase tracking-wide ${accentClass}`}
>
{section.status}
</span>
<InsightStatusBadge status={section.status} size="xs" />
</div>
<div className="mt-4 grid gap-4 md:grid-cols-3">
<div>
@@ -634,7 +656,78 @@ export const AiInsightCard: React.FC<AiInsightCardProps> = ({
const hasInsight =
Boolean(insightText.trim()) || structuredInsight != null || endCycleInsight != null;
const overallStatus = useMemo((): InsightStatus => {
if (insightAlert) {
const norm = normalizeInsightStatus(insightAlert);
if (norm !== 'unknown') return norm;
}
if (structuredInsight?.detailed) {
const sections = Object.values(structuredInsight.detailed).filter(Boolean);
if (sections.some((s) => s.status === 'critical')) return 'critical';
if (sections.some((s) => s.status === 'warning')) return 'warning';
if (sections.some((s) => s.status === 'ok')) return 'ok';
}
if (endCycleInsight) {
if (endCycleInsight.masalah && endCycleInsight.masalah.length > 0) {
return 'warning';
}
return 'ok';
}
const tileStatuses: InsightStatus[] = [fcrStatus, eefStatus, mortalityStatus, weightStatus];
if (tileStatuses.includes('critical')) return 'critical';
if (tileStatuses.includes('warning')) return 'warning';
if (tileStatuses.includes('ok')) return 'ok';
return 'unknown';
}, [
insightAlert,
structuredInsight,
endCycleInsight,
fcrStatus,
eefStatus,
mortalityStatus,
weightStatus,
]);
const renderVisualBlock = () => {
if (loading) {
if (page !== 'dashboard') return null;
return (
<div className="mb-5 space-y-3 rounded-xl border border-gray-100 bg-white p-4 shadow-sm animate-pulse">
<div className="grid grid-cols-1 gap-3 md:grid-cols-2">
<div className="h-28 bg-gray-50 border border-gray-100 rounded-xl p-4 flex flex-col justify-between">
<div className="h-4 bg-gray-200 rounded w-1/3" />
<div className="h-8 bg-gray-200 rounded w-1/2" />
<div className="h-3 bg-gray-200 rounded w-2/3" />
</div>
<div className="h-28 bg-gray-50 border border-gray-100 rounded-xl p-4 flex flex-col justify-between">
<div className="h-4 bg-gray-200 rounded w-1/3" />
<div className="h-8 bg-gray-200 rounded w-1/2" />
<div className="h-3 bg-gray-200 rounded w-2/3" />
</div>
</div>
<div className="grid grid-cols-2 gap-3 lg:grid-cols-3">
<div className="h-20 bg-gray-50 border border-gray-100 rounded-lg p-3 flex flex-col justify-between">
<div className="h-3 bg-gray-200 rounded w-1/2" />
<div className="h-6 bg-gray-200 rounded w-3/4" />
</div>
<div className="h-20 bg-gray-50 border border-gray-100 rounded-lg p-3 flex flex-col justify-between">
<div className="h-3 bg-gray-200 rounded w-1/2" />
<div className="h-6 bg-gray-200 rounded w-3/4" />
</div>
<div className="h-20 bg-gray-50 border border-gray-100 rounded-lg p-3 flex flex-col justify-between">
<div className="h-3 bg-gray-200 rounded w-1/2" />
<div className="h-6 bg-gray-200 rounded w-3/4" />
</div>
</div>
</div>
);
}
if (!hasInsight || !scopedMetrics || page !== 'dashboard') return null;
const fcrVal = scopedMetrics.fcr;
@@ -802,11 +895,21 @@ export const AiInsightCard: React.FC<AiInsightCardProps> = ({
<h2 className="text-lg font-bold text-gray-900 group-hover:text-red-700 transition-colors">
AI Insight
</h2>
{isCollapsed && hasInsight && (
<span className="text-[11px] font-semibold text-emerald-700 bg-emerald-50 border border-emerald-200 px-2 py-0.5 rounded-full">
Tersedia
{loading ? (
<span className="inline-flex items-center gap-1.5 px-2.5 py-0.5 rounded-full text-xs font-medium bg-amber-50 text-amber-700 border border-amber-200 animate-pulse">
<span className="w-1.5 h-1.5 rounded-full bg-amber-500 animate-ping" />
Memproses...
</span>
)}
) : hasInsight ? (
<InsightStatusBadge
status={overallStatus}
customLabel={
isCollapsed
? `Tersedia (${INSIGHT_STATUS_META[overallStatus].label})`
: undefined
}
/>
) : null}
</div>
<p className="text-xs text-gray-400 truncate">
{selectedKandang?.kandang_name ?? `Kandang ${effectiveKandangId}`}
@@ -870,22 +973,33 @@ export const AiInsightCard: React.FC<AiInsightCardProps> = ({
<>
{effectiveKandangId != null ? renderVisualBlock() : null}
{effectiveKandangId != null &&
(page === 'dashboard' || !page) &&
reportType === 'daily' && (
<HarvestPredictionWidget prediction={harvestPrediction} isLoading={loading} />
)}
<div className="min-h-[120px]">
{effectiveKandangId == null ? (
<div className="bg-amber-50 border border-amber-100 rounded-lg p-4 text-sm text-amber-800">
Pilih satu kandang untuk menghasilkan AI Insight. Generate untuk semua kandang
tidak diizinkan.
</div>
) : loading && !insightText ? (
<div className="flex items-center justify-center py-8">
) : loading ? (
<div className="flex items-center justify-center py-10 rounded-xl border border-gray-100 bg-white shadow-xs">
<div className="flex flex-col items-center gap-3">
<div className="animate-spin rounded-full h-10 w-10 border-b-2 border-red-600" />
<p className="text-sm text-gray-600 text-center max-w-sm">
Menganalisis data peternakan… proses ini bisa memakan waktu beberapa menit.
</p>
<div className="w-10 h-10 rounded-full border-4 border-red-100 border-t-red-600 animate-spin" />
<div className="text-center space-y-1">
<p className="text-sm font-semibold text-gray-800">
Menganalisis data peternakan & menyusun insight…
</p>
<p className="text-xs text-gray-500 max-w-sm">
Proses kalkulasi CP 707 dan AI sedang berjalan. Mohon tunggu beberapa saat.
</p>
</div>
</div>
</div>
) : error && !insightText ? (
) : error ? (
<div className="bg-red-50 border border-red-200 rounded-lg p-4">
<p className="text-red-700 text-sm font-semibold mb-2">Error</p>
<p className="text-red-600 text-sm">{error}</p>
@@ -898,125 +1012,143 @@ export const AiInsightCard: React.FC<AiInsightCardProps> = ({
</div>
) : endCycleInsight ? (
<div className="space-y-4">
<div className="rounded-xl border border-gray-100 bg-white p-5 shadow-sm">
<h4 className="text-sm font-bold text-gray-800 mb-2 flex items-center gap-2">
<i className="fa-solid fa-circle-check text-green-600" /> Kesimpulan
</h4>
<p className="text-sm text-gray-700 bg-gray-50 p-3 rounded-lg border border-gray-100">
{endCycleInsight.kesimpulan}
</p>
</div>
<div className="rounded-xl border border-gray-100 bg-white p-5 shadow-sm">
<h4 className="text-sm font-bold text-gray-800 mb-3 flex items-center gap-2">
<i className="fa-solid fa-triangle-exclamation text-amber-600" /> Masalah
</h4>
{renderBulletList(
endCycleInsight.masalah,
'Tidak ada masalah kritis dari graded facts'
)}
</div>
<div className="rounded-xl border border-gray-100 bg-white p-5 shadow-sm">
<h4 className="text-sm font-bold text-gray-800 mb-3 flex items-center gap-2">
<i className="fa-solid fa-magnifying-glass-chart text-red-600" /> Akar
penyebab
</h4>
{endCycleInsight.akar_penyebab.length === 0 ? (
<p className="text-sm text-gray-500">
Belum ada kandidat akar penyebab berbukti.
<div
className={`rounded-xl border p-5 space-y-4 shadow-xs ${INSIGHT_STATUS_META[overallStatus].containerCls}`}
>
<div>
<div className="flex items-center justify-between mb-2">
<h4 className="text-sm font-bold text-gray-800 flex items-center gap-2">
<i className="fa-solid fa-file-lines text-blue-600" /> Kesimpulan
</h4>
<InsightStatusBadge status={overallStatus} />
</div>
<p className="text-sm text-gray-700 bg-white/85 p-3.5 rounded-lg border border-gray-200/70 shadow-xs leading-relaxed">
{endCycleInsight.kesimpulan}
</p>
) : (
<ul className="space-y-3">
{endCycleInsight.akar_penyebab.map((item, index) => (
<li
key={`${item.id ?? item.hipotesis}-${index}`}
className="rounded-lg border border-gray-100 bg-gray-50 p-3"
>
<div className="flex flex-wrap items-center gap-2">
<p className="text-sm font-semibold text-gray-800">
{item.hipotesis}
</p>
{item.confidence ? (
<span
className={`rounded-full border px-2 py-0.5 text-[10px] font-semibold uppercase tracking-wide ${
confidenceBadge[item.confidence] ?? confidenceBadge.low
}`}
>
{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">
{item.bukti.map((bukti, buktiIdx) => (
<li
key={`${bukti}-${buktiIdx}`}
className="text-xs text-gray-600"
>
— {bukti}
</li>
))}
</ul>
) : null}
</li>
))}
</ul>
)}
</div>
</div>
<div className="rounded-xl border border-gray-100 bg-white p-5 shadow-sm">
<h4 className="text-sm font-bold text-gray-800 mb-3 flex items-center gap-2">
<i className="fa-solid fa-clipboard-check text-blue-600" /> Perbaikan siklus
berikutnya
</h4>
{endCycleInsight.perbaikan_siklus_berikutnya.length === 0 ? (
<p className="text-sm text-gray-500">Belum ada checklist perbaikan.</p>
) : (
<ul className="space-y-3">
{endCycleInsight.perbaikan_siklus_berikutnya.map((item, index) => (
<li
key={`${item.id ?? item.aksi}-${index}`}
className="rounded-lg border border-blue-100 bg-blue-50/40 p-3"
>
<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>
{item.metrik_pantau ? (
<p className="mt-1 text-xs text-gray-500">
Pantau: {item.metrik_pantau}
<div>
<h4 className="text-sm font-bold text-gray-800 mb-2 flex items-center gap-2">
<i className="fa-solid fa-triangle-exclamation text-amber-600" /> Masalah
</h4>
<div className="bg-white/85 p-3.5 rounded-lg border border-gray-200/70 shadow-xs">
{renderBulletList(
endCycleInsight.masalah,
'Tidak ada masalah kritis dari graded facts'
)}
</div>
</div>
<div>
<h4 className="text-sm font-bold text-gray-800 mb-2 flex items-center gap-2">
<i className="fa-solid fa-magnifying-glass-chart text-red-600" /> Akar
penyebab
</h4>
{endCycleInsight.akar_penyebab.length === 0 ? (
<p className="text-sm text-gray-500 bg-white/85 p-3.5 rounded-lg border border-gray-200/70 shadow-xs">
Belum ada kandidat akar penyebab berbukti.
</p>
) : (
<ul className="space-y-3">
{endCycleInsight.akar_penyebab.map((item, index) => (
<li
key={`${item.id ?? item.hipotesis}-${index}`}
className="rounded-lg border border-gray-200/70 bg-white/85 p-3.5 shadow-xs"
>
<div className="flex flex-wrap items-center gap-2">
<p className="text-sm font-semibold text-gray-800">
{item.hipotesis}
</p>
{item.confidence ? (
<span
className={`rounded-full border px-2 py-0.5 text-[10px] font-semibold uppercase tracking-wide ${
confidenceBadge[item.confidence] ?? confidenceBadge.low
}`}
>
{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">
{item.bukti.map((bukti, buktiIdx) => (
<li
key={`${bukti}-${buktiIdx}`}
className="text-xs text-gray-600"
>
— {bukti}
</li>
))}
</ul>
) : null}
</li>
))}
</ul>
)}
</div>
<div>
<h4 className="text-sm font-bold text-gray-800 mb-2 flex items-center gap-2">
<i className="fa-solid fa-clipboard-check text-blue-600" /> Perbaikan siklus
berikutnya
</h4>
{endCycleInsight.perbaikan_siklus_berikutnya.length === 0 ? (
<p className="text-sm text-gray-500 bg-white/85 p-3.5 rounded-lg border border-gray-200/70 shadow-xs">
Belum ada checklist perbaikan.
</p>
) : (
<ul className="space-y-3">
{endCycleInsight.perbaikan_siklus_berikutnya.map((item, index) => (
<li
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>
) : null}
</li>
))}
</ul>
)}
{endCycleInsight.insight ? (
<p className="mt-3 text-sm text-gray-600">{endCycleInsight.insight}</p>
) : null}
<CitationsBlock citations={citations} />
<p className="mt-1 text-sm text-gray-800">{item.aksi}</p>
{item.metrik_pantau ? (
<p className="mt-1 text-xs text-gray-500">
Pantau: {item.metrik_pantau}
</p>
) : null}
</li>
))}
</ul>
)}
{endCycleInsight.insight ? (
<p className="mt-3 text-sm text-gray-600 bg-white/85 p-3.5 rounded-lg border border-gray-200/70 shadow-xs">
{endCycleInsight.insight}
</p>
) : null}
</div>
</div>
<CitationsBlock citations={citations} />
</div>
) : structuredInsight && summary ? (
<div className="space-y-4">
<div className="rounded-xl border border-gray-100 bg-white p-5 shadow-sm">
<h4 className="text-sm font-bold text-gray-800 mb-2 flex items-center gap-2">
<i className="fa-solid fa-circle-check text-green-600" /> Kesimpulan
</h4>
<p className="text-sm text-gray-700 bg-gray-50 p-3 rounded-lg border border-gray-100">
<div
className={`rounded-xl border p-5 shadow-xs ${INSIGHT_STATUS_META[overallStatus].containerCls}`}
>
<div className="flex items-center justify-between mb-2">
<h4 className="text-sm font-bold text-gray-800 flex items-center gap-2">
<i className="fa-solid fa-file-lines text-blue-600" /> Kesimpulan
</h4>
<InsightStatusBadge status={overallStatus} />
</div>
<p className="text-sm text-gray-700 bg-white/85 p-3.5 rounded-lg border border-gray-200/70 shadow-xs leading-relaxed">
{summary.headline}
</p>
<div className="mt-4">
<h4 className="text-sm font-bold text-gray-800 mb-2 flex items-center gap-2">
<i className="fa-solid fa-brain text-red-600" /> AI Insight
</h4>
<div className="text-sm text-gray-700 space-y-2 leading-relaxed">
<div className="text-sm text-gray-700 bg-white/85 p-3.5 rounded-lg border border-gray-200/70 shadow-xs space-y-2 leading-relaxed">
{renderBulletList([
...summary.bullets,
...summary.risks,
@@ -1024,8 +1156,8 @@ export const AiInsightCard: React.FC<AiInsightCardProps> = ({
])}
</div>
</div>
<CitationsBlock citations={citations} />
</div>
<CitationsBlock citations={citations} />
{page === 'dashboard' && detailed && (
<>
@@ -1038,41 +1170,15 @@ export const AiInsightCard: React.FC<AiInsightCardProps> = ({
{detailsOpen && (
<div className="space-y-3">
{detailed.hitung_ayam &&
renderDetailSection(
'Hitung Ayam',
detailed.hitung_ayam,
sectionBadgeClasses[detailed.hitung_ayam.status]
)}
renderDetailSection('Hitung Ayam', detailed.hitung_ayam)}
{detailed.berat_ayam &&
renderDetailSection(
'Berat Ayam',
detailed.berat_ayam,
sectionBadgeClasses[detailed.berat_ayam.status]
)}
{detailed.fcr &&
renderDetailSection(
'FCR',
detailed.fcr,
sectionBadgeClasses[detailed.fcr.status]
)}
{detailed.eef &&
renderDetailSection(
'EEF',
detailed.eef,
sectionBadgeClasses[detailed.eef.status]
)}
renderDetailSection('Berat Ayam', detailed.berat_ayam)}
{detailed.fcr && renderDetailSection('FCR', detailed.fcr)}
{detailed.eef && renderDetailSection('EEF', detailed.eef)}
{detailed.panel_iot &&
renderDetailSection(
'Panel IoT',
detailed.panel_iot,
sectionBadgeClasses[detailed.panel_iot.status]
)}
renderDetailSection('Panel IoT', detailed.panel_iot)}
{detailed.data_quality &&
renderDetailSection(
'Kualitas Data',
detailed.data_quality,
sectionBadgeClasses[detailed.data_quality.status]
)}
renderDetailSection('Kualitas Data', detailed.data_quality)}
</div>
)}
</>
@@ -1080,44 +1186,57 @@ export const AiInsightCard: React.FC<AiInsightCardProps> = ({
</div>
) : dailyInsight ? (
<div className="space-y-4">
<div className="rounded-xl border border-gray-100 bg-white p-5 shadow-sm">
<h4 className="text-sm font-bold text-gray-800 mb-2 flex items-center gap-2">
<i className="fa-solid fa-circle-check text-green-600" /> Kesimpulan
</h4>
<p className="text-sm text-gray-700 bg-gray-50 p-3 rounded-lg border border-gray-100">
{dailyInsight.summary}
</p>
</div>
{dailyInsight.akar_masalah && (
<div className="rounded-xl border border-amber-100/80 bg-amber-50/40 p-5 shadow-sm">
<h4 className="text-sm font-bold text-gray-800 mb-2 flex items-center gap-2">
<i className="fa-solid fa-magnifying-glass-chart text-amber-600" /> Akar
Masalah
</h4>
<p className="text-sm text-gray-700 bg-white/80 p-3 rounded-lg border border-amber-100/80">
{dailyInsight.akar_masalah}
<div
className={`rounded-xl border p-5 space-y-4 shadow-xs ${INSIGHT_STATUS_META[overallStatus].containerCls}`}
>
<div>
<div className="flex items-center justify-between mb-2">
<h4 className="text-sm font-bold text-gray-800 flex items-center gap-2">
<i className="fa-solid fa-file-lines text-blue-600" /> Kesimpulan
</h4>
<InsightStatusBadge status={overallStatus} />
</div>
<p className="text-sm text-gray-700 bg-white/85 p-3.5 rounded-lg border border-gray-200/70 shadow-xs leading-relaxed">
{dailyInsight.summary}
</p>
</div>
)}
<div className="rounded-xl border border-gray-100 bg-white p-5 shadow-sm">
<h4 className="text-sm font-bold text-gray-800 mb-2 flex items-center gap-2">
<i className="fa-solid fa-brain text-red-600" /> AI Insight & Rekomendasi
</h4>
<p className="text-sm text-gray-700 bg-gray-50 p-3 rounded-lg border border-gray-100 whitespace-pre-wrap">
{dailyInsight.insight}
</p>
<CitationsBlock citations={citations} />
{dailyInsight.akar_masalah && (
<div>
<h4 className="text-sm font-bold text-gray-800 mb-2 flex items-center gap-2">
<i className="fa-solid fa-magnifying-glass-chart text-amber-600" /> Akar
Masalah
</h4>
<p className="text-sm text-gray-700 bg-white/85 p-3.5 rounded-lg border border-amber-200/70 shadow-xs leading-relaxed">
{dailyInsight.akar_masalah}
</p>
</div>
)}
<div>
<h4 className="text-sm font-bold text-gray-800 mb-2 flex items-center gap-2">
<i className="fa-solid fa-brain text-red-600" /> AI Insight & Rekomendasi
</h4>
<p className="text-sm text-gray-700 bg-white/85 p-3.5 rounded-lg border border-gray-200/70 shadow-xs whitespace-pre-wrap leading-relaxed">
{dailyInsight.insight}
</p>
</div>
</div>
<CitationsBlock citations={citations} />
</div>
) : insightText ? (
<div className="text-sm text-gray-800 leading-relaxed whitespace-pre-wrap">
{insightText.includes(END_CYCLE_JSON_MARKER)
? insightText.split(END_CYCLE_JSON_MARKER)[0]?.trim()
: insightText.includes('<!--daily_json-->')
? insightText.split('<!--daily_json-->')[0]?.trim()
: insightText}
<div className="space-y-4">
<div
className={`rounded-xl border p-5 shadow-xs ${INSIGHT_STATUS_META[overallStatus].containerCls}`}
>
<div className="text-sm text-gray-800 leading-relaxed whitespace-pre-wrap bg-white/85 p-3.5 rounded-lg border border-gray-200/70 shadow-xs">
{insightText.includes(END_CYCLE_JSON_MARKER)
? insightText.split(END_CYCLE_JSON_MARKER)[0]?.trim()
: insightText.includes('<!--daily_json-->')
? insightText.split('<!--daily_json-->')[0]?.trim()
: insightText}
</div>
</div>
<CitationsBlock citations={citations} />
</div>
) : (
@@ -1125,12 +1244,13 @@ export const AiInsightCard: React.FC<AiInsightCardProps> = ({
<i className="fa-solid fa-brain text-gray-300 text-2xl" />
<p className="text-sm text-gray-500">Belum ada AI Insight untuk periode ini.</p>
<p className="text-xs text-gray-400">
Klik tombol refresh untuk generate insight.
Klik tombol di bawah untuk membuat insight baru.
</p>
<button
type="button"
onClick={() => generateInsight(true)}
className="mt-2 inline-flex items-center gap-2 rounded-lg bg-red-600 px-3 py-1.5 text-xs font-semibold text-white hover:bg-red-700"
disabled={loading}
className="mt-2 inline-flex items-center gap-2 rounded-lg bg-red-600 px-3 py-1.5 text-xs font-semibold text-white hover:bg-red-700 shadow-xs transition-all disabled:opacity-50"
>
<i className="fa-solid fa-wand-magic-sparkles" />
Generate Insight
@@ -1139,7 +1259,20 @@ export const AiInsightCard: React.FC<AiInsightCardProps> = ({
)}
</div>
<div className="mt-6 pt-4 border-t border-gray-100 flex flex-col items-center justify-center gap-1.5">
<div className="mt-6 pt-4 border-t border-gray-100 flex items-center justify-between">
<div className="text-xs text-gray-400">
{loading ? (
<span className="inline-flex items-center gap-1.5 text-amber-600">
<i className="fa-solid fa-spinner fa-spin text-xs" />
<span>Sedang memperbarui analisis AI...</span>
</span>
) : hasInsight ? (
<span className="inline-flex items-center gap-1.5">
<span>Status AI Insight:</span>
<InsightStatusBadge status={overallStatus} size="xs" />
</span>
) : null}
</div>
<button
type="button"
onClick={() => {
@@ -1152,11 +1285,9 @@ export const AiInsightCard: React.FC<AiInsightCardProps> = ({
>
<i className="fa-solid fa-chevron-up text-xs transition-transform group-hover:-translate-y-0.5" />
</button>
{lastUpdated && (
<p className="text-[11px] text-gray-400">
Terakhir diperbarui: {formatLastUpdated()}
</p>
)}
<div className="text-right text-[11px] text-gray-400 min-w-[80px]">
{lastUpdated && <span>Terakhir: {formatLastUpdated()}</span>}
</div>
</div>
</>
)}
+26 -19
View File
@@ -1,5 +1,5 @@
import React, { useEffect, useMemo, useState } from 'react';
import { api, ApiError, errorMessage } from '../services/apiClient.ts';
import { api, errorMessage } from '../services/apiClient.ts';
import type {
ChickenCounting,
ChickenWeight,
@@ -50,7 +50,7 @@ const Dashboard: React.FC<Props> = ({ setView }) => {
const [countings, setCountings] = useState<ChickenCounting[]>([]);
const [manualInputs, setManualInputs] = useState<ManualInput[]>([]);
const [weights, setWeights] = useState<ChickenWeight[]>([]);
const [karung, setKarung] = useState<Karung | null>(null);
const [karungs, setKarungs] = useState<Karung[]>([]);
const [iotDayAggregates, setIotDayAggregates] = useState<EndCycleIotDayAggregate[]>([]);
const [reportOpen, setReportOpen] = useState(false);
const [reportType, setReportType] = useState<DashboardReportType>('daily');
@@ -61,7 +61,7 @@ const Dashboard: React.FC<Props> = ({ setView }) => {
setCountings([]);
setManualInputs([]);
setWeights([]);
setKarung(null);
setKarungs([]);
setIotDayAggregates([]);
return;
}
@@ -71,24 +71,19 @@ const Dashboard: React.FC<Props> = ({ setView }) => {
setLoading(true);
setError(null);
try {
const [kpiRows, countingRows, manualRows, weightRows] = await Promise.all([
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 }),
]);
let latestKarung: Karung | null = null;
try {
latestKarung = await api.karungs.latest({ cycle_id: cycleId });
} catch (err) {
if (!(err instanceof ApiError && err.status === 404)) throw err;
}
if (cancelled) return;
setKpis(kpiRows);
setCountings(countingRows);
setManualInputs(manualRows);
setWeights(weightRows);
setKarung(latestKarung);
setKarungs(karungRows);
// Best-effort IoT aggregates for end-cycle root cause (non-blocking on failure).
try {
@@ -125,6 +120,13 @@ const Dashboard: React.FC<Props> = ({ setView }) => {
};
}, [selectedCycle, selectedKandang]);
const latestKarung = useMemo(() => {
if (karungs.length === 0) return null;
const visibleThrough = selectedCycle?.visible_through_date;
const filtered = throughVisibleDate(karungs, visibleThrough);
return filtered.length > 0 ? filtered[filtered.length - 1] : null;
}, [karungs, selectedCycle?.visible_through_date]);
const insightMetrics = useMemo(() => {
if (selectedKandangId == null) return null;
const visibleThrough = selectedCycle?.visible_through_date;
@@ -140,9 +142,9 @@ const Dashboard: React.FC<Props> = ({ setView }) => {
weights: weightsThroughAnchor,
currentDay: latest?.age ?? selectedCycle?.current_day ?? null,
docInCount: selectedCycle?.doc_in_count ?? null,
pakanKumulatifFallback: karung?.feed_use_total ?? latest?.feed_total ?? null,
pakanKumulatifFallback: latestKarung?.feed_use_total ?? latest?.feed_total ?? null,
});
}, [selectedKandangId, selectedCycle, kpis, weights, karung]);
}, [selectedKandangId, selectedCycle, kpis, weights, latestKarung]);
const insightContext = useMemo(() => {
if (selectedKandangId == null) return null;
@@ -176,8 +178,8 @@ const Dashboard: React.FC<Props> = ({ setView }) => {
? null
: Math.round((100 - latest.chicken_life_percentage) * 100) / 100,
karung_dituang_hari_ini:
latest != null ? latest.feed : (karung?.feed_use_today ?? karung?.out_today ?? null),
pakan_kumulatif_karung: karung?.feed_use_total ?? latest?.feed_total ?? null,
latest != null ? latest.feed : (latestKarung?.feed_use_today ?? latestKarung?.out_today ?? null),
pakan_kumulatif_karung: latestKarung?.feed_use_total ?? latest?.feed_total ?? null,
ayam_hidup_ekor:
latest != null ? Math.max(0, latest.chicken_life - (latest.harvest_total ?? 0)) : null,
persen_hidup: latest?.chicken_life_percentage ?? null,
@@ -188,7 +190,7 @@ const Dashboard: React.FC<Props> = ({ setView }) => {
latest?.harvest_weight_total != null ? latest.harvest_weight_total / 1000 : null,
uniformity_persen: weightOnAnchor?.uniformity ?? null,
});
}, [selectedKandangId, selectedKandang, selectedCycle, kpis, weights, karung]);
}, [selectedKandangId, selectedKandang, selectedCycle, kpis, weights, latestKarung]);
const cards: KpiCardModel[] = useMemo(() => {
// All cards share the latest complete KPI day (not calendar current_day / live IoT).
@@ -320,11 +322,11 @@ const Dashboard: React.FC<Props> = ({ setView }) => {
);
}
const feedTotal = karung?.feed_use_total ?? kpis[0]?.feed_total ?? 0;
const feedTotal = latestKarung?.feed_use_total ?? kpis[0]?.feed_total ?? 0;
const feedWeightKg = feedTotal * 50;
const feedInitialBalance = selectedCycle?.feed_initial_balance ?? 0;
const feedInTotal = (karung?.in_total ?? 0) + feedInitialBalance;
const feedOutTotal = karung?.out_total ?? 0;
const feedInTotal = (latestKarung?.in_total ?? 0) + feedInitialBalance;
const feedOutTotal = latestKarung?.out_total ?? 0;
const feedSaldo = feedInTotal - feedTotal - feedOutTotal;
const feedSaldoColor =
feedSaldo > 0 ? 'text-green-600' : feedSaldo < 0 ? 'text-red-600' : 'text-gray-600';
@@ -423,6 +425,11 @@ const Dashboard: React.FC<Props> = ({ setView }) => {
{formatNumber(feedInitialBalance)}
</p>
<p className="mt-1 text-xs text-gray-400">karung</p>
{selectedCycle?.feed_initial_balance_iot != null && (
<p className="mt-1 text-xs font-semibold text-purple-600">
IoT: {formatNumber(selectedCycle.feed_initial_balance_iot)} karung
</p>
)}
</div>
</div>
-1
View File
@@ -374,7 +374,6 @@ const EefDashboardPage: React.FC<{ onSettings: () => void }> = ({ onSettings })
</div>
<div className="p-6">
<h2 className="text-xl font-bold text-gray-800 mb-4">Grafik Data Pendukung</h2>
<div className="grid grid-cols-1 xl:grid-cols-2 gap-6">
<SupportingMetricChart
title="Persentase Ayam Hidup"
-1
View File
@@ -380,7 +380,6 @@ const FcrDashboardPage: React.FC<{ onSettings: () => void }> = ({ onSettings })
</div>
<div className="p-6">
<h2 className="text-xl font-bold text-gray-800 mb-4">Grafik Data Pendukung</h2>
<div className="grid grid-cols-1 xl:grid-cols-2 gap-6">
<SupportingMetricChart
title="Total Pakan"
+34 -19
View File
@@ -3,7 +3,8 @@ import { api, errorMessage } from '../services/apiClient.ts';
import type { Cycle, Karung, ManualInput } from '../types/api.ts';
import { useFarm } from '../context/FarmContext.tsx';
import { Banner, EmptyFarm, Spinner } from './ui/Feedback.tsx';
import { addDaysIso, cycleDayForDate, formatDateId, resolveCycleStatus, todayIso } from '../utils/format.ts';
import { cycleDayForDate, formatDateId, resolveCycleStatus, todayIso } from '../utils/format.ts';
import { throughVisibleDate } from '../utils/visibility.ts';
import { buildFeedSackInsightContext } from '../utils/insightContextBuilders.ts';
import { PageAiInsight } from './shared/PageAiInsight.tsx';
import FeedStats from './feedSack/FeedStats.tsx';
@@ -48,22 +49,30 @@ const FeedSackCountingPage: React.FC<{ onSettings: () => void }> = ({ onSettings
}, [selectedCycle, reload]);
const sortedRows = useMemo(() => [...rows].sort((a, b) => a.date.localeCompare(b.date)), [rows]);
const latest = sortedRows[sortedRows.length - 1] ?? null;
const sortedManualRows = useMemo(
() => [...manualRows].sort((a, b) => a.date.localeCompare(b.date)),
[manualRows]
);
const visibleThrough = selectedCycle?.visible_through_date;
// Display date follows the latest IoT snapshot; without any snapshot, fall back to today.
// Manual cards only use a same-date row — never fall back to an older day.
const visibleRows = useMemo(
() => throughVisibleDate(sortedRows, visibleThrough),
[sortedRows, visibleThrough]
);
const visibleManualRows = useMemo(
() => throughVisibleDate(sortedManualRows, visibleThrough),
[sortedManualRows, visibleThrough]
);
const latest = visibleRows[visibleRows.length - 1] ?? null;
// Display date follows the latest visible IoT snapshot; without any snapshot, fall back to cutoff date / today.
const displayDate = latest?.date ?? visibleThrough ?? todayIso();
const latestManual = sortedManualRows.find((row) => row.date === displayDate) ?? null;
const latestManual = visibleManualRows.find((row) => row.date === displayDate) ?? null;
const lastRecordedManual = visibleManualRows[visibleManualRows.length - 1] ?? null;
const currentDay = useMemo(() => {
if (!selectedCycle) return 0;
const rawDay = cycleDayForDate(selectedCycle.start_date, displayDate);
return Math.min(rawDay, Math.max(0, (selectedCycle.total_days || 1) - 1));
}, [selectedCycle, displayDate]);
const boundDate = selectedCycle.end_date ?? visibleThrough ?? todayIso();
return cycleDayForDate(selectedCycle.start_date, boundDate);
}, [selectedCycle, visibleThrough]);
const sortedCycles = useMemo(() => {
return [...cycles].sort(
@@ -74,7 +83,12 @@ const FeedSackCountingPage: React.FC<{ onSettings: () => void }> = ({ onSettings
const formatCycleDateRange = (cycle: Cycle) => {
const start = formatDateId(cycle.start_date);
if (cycle.end_date) return `${start} - ${formatDateId(cycle.end_date)}`;
return `${start} - ${formatDateId(addDaysIso(cycle.start_date, cycle.total_days))}`;
if (cycle.proposed_end_date && resolveCycleStatus(cycle) === 'pending_close') {
return `${start} - ${formatDateId(cycle.proposed_end_date)}`;
}
const bound = cycle.visible_through_date || cycle.soft_end_date || todayIso();
const effectiveEnd = bound < cycle.start_date ? cycle.start_date : bound;
return `${start} - ${formatDateId(effectiveEnd)}`;
};
const lastUpdated = useMemo(() => {
@@ -92,8 +106,8 @@ const FeedSackCountingPage: React.FC<{ onSettings: () => void }> = ({ onSettings
const insightContext = useMemo(() => {
if (!selectedKandang || !selectedCycle) return null;
const manualByDate = new Map(sortedManualRows.map((r) => [r.date, r]));
const dailyRows = sortedRows.map((r) => {
const manualByDate = new Map(visibleManualRows.map((r) => [r.date, r]));
const dailyRows = visibleRows.map((r) => {
const manual = manualByDate.get(r.date);
return {
date: r.date,
@@ -115,10 +129,10 @@ const FeedSackCountingPage: React.FC<{ onSettings: () => void }> = ({ onSettings
total_karung_masuk_iot: latest?.in_total ?? null,
total_karung_dituang_iot: latest?.feed_use_total ?? null,
total_karung_keluar_iot: latest?.out_total ?? null,
total_karung_masuk_manual: latestManual?.feed_in_manual_total ?? null,
total_karung_dituang_manual: latestManual?.feed_use_manual_total ?? null,
total_karung_masuk_manual: lastRecordedManual?.feed_in_manual_total ?? null,
total_karung_dituang_manual: lastRecordedManual?.feed_use_manual_total ?? null,
});
}, [selectedKandang, selectedCycle, sortedRows, sortedManualRows, latest, latestManual]);
}, [selectedKandang, selectedCycle, visibleRows, visibleManualRows, latest, lastRecordedManual]);
if (!selectedCycle) return <EmptyFarm onSettings={onSettings} />;
@@ -238,7 +252,7 @@ const FeedSackCountingPage: React.FC<{ onSettings: () => void }> = ({ onSettings
{selectedKandang && insightContext ? (
<PageAiInsight
topic="hitung_karung"
cacheKey={`pakan-k${selectedKandang.id}-c${selectedCycle.id}-day${currentDay}-rows${sortedRows.length}`}
cacheKey={`pakan-k${selectedKandang.id}-c${selectedCycle.id}-day${currentDay}-rows${visibleRows.length}`}
contextData={insightContext}
chartSpec={{
type: 'trend',
@@ -307,6 +321,7 @@ const FeedSackCountingPage: React.FC<{ onSettings: () => void }> = ({ onSettings
<FeedStats
latest={latest}
latestManual={latestManual}
lastRecordedManual={lastRecordedManual}
cycleStartDate={selectedCycle.start_date}
displayDate={displayDate}
/>
@@ -321,15 +336,15 @@ const FeedSackCountingPage: React.FC<{ onSettings: () => void }> = ({ onSettings
{/* Tren harian */}
<FeedTrendChart
rows={sortedRows}
rows={visibleRows}
cycleStartDate={selectedCycle.start_date}
currentDay={currentDay}
/>
{/* Rincian harian */}
<FeedDailySummaryTable
rows={sortedRows}
manualRows={manualRows}
rows={visibleRows}
manualRows={visibleManualRows}
cycleStartDate={selectedCycle.start_date}
currentDay={currentDay}
/>
+1 -1
View File
@@ -26,7 +26,7 @@ const navItems: NavItem[] = [
},
{
view: 'weightStandard',
label: 'Standar Mr. Mike',
label: 'Standar Ross 308',
icon: <i className="fa-solid fa-table-list"></i>,
},
],
+1 -3
View File
@@ -10,9 +10,7 @@ const WeightStandardPage: React.FC = () => {
<i className="fa-solid fa-table-list text-3xl text-red-600 mr-4"></i>
<div>
<h1 className="text-3xl font-bold text-gray-800">Tabel Standar Bobot Ross 308</h1>
<p className="mt-1 text-gray-600">
Driven from pen trial data - so difference may be more
</p>
<p className="mt-1 text-gray-600">Standar bobot Ross 308</p>
</div>
</div>
@@ -0,0 +1,66 @@
import { render, screen } from '@testing-library/react';
import { describe, expect, it } from 'vitest';
import HarvestPredictionWidget from '../shared/HarvestPredictionWidget.tsx';
import type { HarvestPredictionResult } from '../../types/api.ts';
const mockPrediction: HarvestPredictionResult = {
optimal_harvest_day: 24,
optimal_harvest_date: '2026-06-15',
days_remaining: 1,
projected_bw_gram: 1094.2,
projected_fcr: 1.263,
projected_eef: 349.5,
harvest_window_days: [23, 25],
efficiency_status: 'approaching_window',
harvest_type: 'thinning',
recommendation_label: 'Panen Penjarangan / Seleksi Awal',
adg_actual_gram: 74.34,
early_harvest_risk: false,
};
describe('HarvestPredictionWidget', () => {
it('renders title, CP 707 badge, and status pill', () => {
render(<HarvestPredictionWidget prediction={mockPrediction} />);
expect(screen.getByText('Estimasi Waktu Panen Terbaik')).toBeDefined();
expect(screen.getByText('CP 707')).toBeDefined();
expect(screen.getByText(/Mendekati Jendela Panen/i)).toBeDefined();
});
it('renders countdown, projected weight, recommendation label, projected FCR, and projected EEF', () => {
render(<HarvestPredictionWidget prediction={mockPrediction} />);
expect(screen.getByText('Hari ke-24')).toBeDefined();
expect(screen.getByText(/± 1 hari lagi/i)).toBeDefined();
expect(screen.getByText('~1.094 g')).toBeDefined();
expect(screen.getByText('Panen Penjarangan / Seleksi Awal')).toBeDefined();
expect(screen.getByText('1.263')).toBeDefined();
expect(screen.getByText('350')).toBeDefined();
});
it('renders prompt to click Generate Insight when prediction is null', () => {
render(<HarvestPredictionWidget prediction={null} />);
expect(screen.getByText(/Klik tombol/i)).toBeDefined();
expect(screen.getByText(/Siap Generate AI Insight/i)).toBeDefined();
});
it('renders early harvest alert banner when early_harvest_risk is true', () => {
const riskPrediction: HarvestPredictionResult = {
...mockPrediction,
early_harvest_risk: true,
};
render(<HarvestPredictionWidget prediction={riskPrediction} />);
expect(screen.getByText(/Perhatian Panen Dini/i)).toBeDefined();
});
it('renders loading indicators and skeletons when isLoading is true', () => {
render(<HarvestPredictionWidget prediction={mockPrediction} isLoading={true} />);
expect(screen.getByText(/Menghitung Proyeksi…/i)).toBeDefined();
expect(screen.getByTestId('harvest-prediction-loading')).toBeDefined();
expect(screen.queryByText('Hari ke-24')).toBeNull();
});
});
+9 -2
View File
@@ -148,7 +148,7 @@ const DataManagementPage: React.FC<{ onSettings: () => void }> = ({ onSettings }
beratPanen,
stockAkhir,
chickenCount,
persentase: Math.round(persentase * 10) / 10,
persentase,
mortalityTotal: kpi?.mortality_total ?? cumulativeMortality,
harvestTotal: kpi?.harvest_total ?? cumulativeHarvest,
harvestWeightTotal:
@@ -254,9 +254,16 @@ const DataManagementPage: React.FC<{ onSettings: () => void }> = ({ onSettings }
? 'bg-yellow-100 text-yellow-700'
: 'bg-red-100 text-red-700';
const formatted =
persentase >= 100
? '100%'
: persentase.toFixed(2) === '100.00'
? '99.99%'
: `${persentase.toFixed(2)}%`;
return (
<span className={`px-2 py-1 rounded-full text-xs font-medium ${colorClass}`}>
{persentase.toFixed(1)}%
{formatted}
</span>
);
};
+8 -4
View File
@@ -30,6 +30,7 @@ const StatItem: React.FC<{
interface FeedStatsProps {
latest: Karung | null;
latestManual: ManualInput | null;
lastRecordedManual?: ManualInput | null;
cycleStartDate: string;
displayDate: string;
}
@@ -37,6 +38,7 @@ interface FeedStatsProps {
const FeedStats: React.FC<FeedStatsProps> = ({
latest,
latestManual,
lastRecordedManual,
cycleStartDate,
displayDate,
}) => {
@@ -61,6 +63,8 @@ const FeedStats: React.FC<FeedStatsProps> = ({
return `Total (${start} - ${end})`;
}, [cycleStartDate, displayDate]);
const cumulativeManual = lastRecordedManual ?? latestManual;
const columns = useMemo(
() => [
{
@@ -71,7 +75,7 @@ const FeedStats: React.FC<FeedStatsProps> = ({
iotToday: latest?.in_today ?? 0,
iotTotal: latest?.in_total ?? 0,
manualToday: latestManual?.feed_in_manual ?? 0,
manualTotal: latestManual?.feed_in_manual_total ?? 0,
manualTotal: cumulativeManual?.feed_in_manual_total ?? 0,
},
{
key: 'dituang',
@@ -81,7 +85,7 @@ const FeedStats: React.FC<FeedStatsProps> = ({
iotToday: latest?.feed_use_today ?? 0,
iotTotal: latest?.feed_use_total ?? 0,
manualToday: latestManual?.feed_use_manual ?? 0,
manualTotal: latestManual?.feed_use_manual_total ?? 0,
manualTotal: cumulativeManual?.feed_use_manual_total ?? 0,
},
{
key: 'keluar',
@@ -91,10 +95,10 @@ const FeedStats: React.FC<FeedStatsProps> = ({
iotToday: latest?.out_today ?? 0,
iotTotal: latest?.out_total ?? 0,
manualToday: latestManual?.feed_out_manual ?? 0,
manualTotal: latestManual?.feed_out_manual_total ?? 0,
manualTotal: cumulativeManual?.feed_out_manual_total ?? 0,
},
],
[latest, latestManual]
[latest, latestManual, cumulativeManual]
);
return (
@@ -0,0 +1,248 @@
import React from 'react';
import type { HarvestPredictionResult } from '../../types/api.ts';
export interface HarvestPredictionWidgetProps {
prediction: HarvestPredictionResult | null;
isLoading?: boolean;
}
const STATUS_CONFIG: Record<
string,
{ label: string; badgeCls: string; borderCls: string; icon: string }
> = {
growing: {
label: 'Fase Pertumbuhan Aktif',
badgeCls: 'bg-blue-50 text-blue-700 border-blue-200',
borderCls: 'border-blue-100 bg-gradient-to-br from-blue-50/50 via-white to-white',
icon: 'fa-solid fa-seedling text-blue-500',
},
approaching_window: {
label: 'Mendekati Jendela Panen',
badgeCls: 'bg-cyan-50 text-cyan-700 border-cyan-200',
borderCls: 'border-cyan-100 bg-gradient-to-br from-cyan-50/50 via-white to-white',
icon: 'fa-solid fa-clock-rotate-left text-cyan-500',
},
optimal_window: {
label: 'Jendela Panen Terbaik (Puncak EEF)',
badgeCls: 'bg-emerald-50 text-emerald-700 border-emerald-200',
borderCls: 'border-emerald-200 bg-gradient-to-br from-emerald-50/60 via-white to-white',
icon: 'fa-solid fa-trophy text-emerald-600',
},
post_optimal: {
label: 'Melewati Titik Efisien (FCR Meningkat)',
badgeCls: 'bg-amber-50 text-amber-700 border-amber-200',
borderCls: 'border-amber-200 bg-gradient-to-br from-amber-50/50 via-white to-white',
icon: 'fa-solid fa-triangle-exclamation text-amber-500',
},
};
const DEFAULT_STATUS_META = {
label: 'Fase Pertumbuhan Aktif',
badgeCls: 'bg-blue-50 text-blue-700 border-blue-200',
borderCls: 'border-blue-100 bg-gradient-to-br from-blue-50/50 via-white to-white',
icon: 'fa-solid fa-seedling text-blue-500',
};
const WAITING_STATUS_META = {
label: 'Siap Generate AI Insight',
badgeCls: 'bg-blue-50 text-blue-700 border-blue-200',
borderCls: 'border-blue-100 bg-gradient-to-br from-blue-50/40 via-white to-white',
icon: 'fa-solid fa-wand-magic-sparkles text-blue-500',
};
export const HarvestPredictionWidget: React.FC<HarvestPredictionWidgetProps> = ({
prediction,
isLoading = false,
}) => {
const statusMeta = prediction?.efficiency_status
? (STATUS_CONFIG[prediction.efficiency_status] ?? DEFAULT_STATUS_META)
: WAITING_STATUS_META;
const recommendationLabel =
prediction?.recommendation_label ??
(prediction?.harvest_type === 'thinning'
? 'Panen Penjarangan / Seleksi Awal'
: 'Panen Utama / Panen Raya');
return (
<div
className={`rounded-xl border p-4 sm:p-5 shadow-xs mb-4 transition-all ${statusMeta.borderCls}`}
>
{/* Header with Title and Status Phase Badge */}
<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3 pb-3 border-b border-gray-100">
<div className="flex items-center gap-2.5">
<div className="w-8 h-8 rounded-lg bg-emerald-100 flex items-center justify-center shrink-0">
<i className="fa-solid fa-calendar-check text-emerald-700 text-sm" />
</div>
<div>
<h3 className="text-sm font-bold text-gray-900 flex items-center gap-2">
Estimasi Waktu Panen Terbaik
<span className="text-[10px] font-semibold text-emerald-700 bg-emerald-50 px-2 py-0.5 rounded-full border border-emerald-200">
CP 707
</span>
</h3>
<p className="text-xs text-gray-500">
Optimalisasi otomatis berbasis efisiensi pakan (FCR) dan puncak Indeks Performa (EEF)
</p>
</div>
</div>
<div className="flex items-center gap-2">
{isLoading ? (
<span
role="status"
className="inline-flex items-center gap-1.5 px-3 py-1 rounded-full text-xs font-semibold border bg-emerald-50 text-emerald-700 border-emerald-200 animate-pulse"
>
<i className="fa-solid fa-arrows-rotate fa-spin" />
Menghitung Proyeksi…
</span>
) : (
<span
className={`inline-flex items-center gap-1.5 px-3 py-1 rounded-full text-xs font-semibold border ${statusMeta.badgeCls}`}
>
<i className={statusMeta.icon} />
{statusMeta.label}
</span>
)}
</div>
</div>
{/* Main Countdown & Projection Metrics / Status message */}
{isLoading ? (
<div
className="grid grid-cols-2 sm:grid-cols-4 gap-2.5 pt-3"
aria-busy="true"
data-testid="harvest-prediction-loading"
>
{/* Tile 1: Countdown & Target Day Skeleton */}
<div className="bg-white/90 p-3 rounded-lg border border-gray-200/80 shadow-xs flex flex-col justify-between animate-pulse">
<span className="text-[11px] font-medium text-gray-400 uppercase tracking-wide">
Waktu Panen Optimal
</span>
<div className="mt-2 space-y-2">
<div className="h-6 w-24 bg-emerald-100/80 rounded" />
<div className="h-3.5 w-20 bg-gray-200 rounded" />
</div>
</div>
{/* Tile 2: Estimated Harvest Weight Skeleton */}
<div className="bg-white/90 p-3 rounded-lg border border-gray-200/80 shadow-xs flex flex-col justify-between animate-pulse">
<span className="text-[11px] font-medium text-gray-400 uppercase tracking-wide">
Estimasi Bobot Panen
</span>
<div className="mt-2 space-y-2">
<div className="h-6 w-20 bg-emerald-100/80 rounded" />
<div className="h-3.5 w-24 bg-gray-200 rounded" />
</div>
</div>
{/* Tile 3: Projected FCR Skeleton */}
<div className="bg-white/90 p-3 rounded-lg border border-gray-200/80 shadow-xs flex flex-col justify-between animate-pulse">
<span className="text-[11px] font-medium text-gray-400 uppercase tracking-wide">
Proyeksi FCR
</span>
<div className="mt-2 space-y-2">
<div className="h-6 w-16 bg-emerald-100/80 rounded" />
<div className="h-3.5 w-24 bg-gray-200 rounded" />
</div>
</div>
{/* Tile 4: Projected EEF Skeleton */}
<div className="bg-white/90 p-3 rounded-lg border border-gray-200/80 shadow-xs flex flex-col justify-between animate-pulse">
<span className="text-[11px] font-medium text-gray-400 uppercase tracking-wide">
Proyeksi EEF / IP
</span>
<div className="mt-2 space-y-2">
<div className="h-6 w-14 bg-emerald-100/80 rounded" />
<div className="h-3.5 w-24 bg-gray-200 rounded" />
</div>
</div>
</div>
) : prediction ? (
<div className="grid grid-cols-2 sm:grid-cols-4 gap-2.5 pt-3">
{/* Tile 1: Countdown & Target Day */}
<div className="bg-white/90 p-3 rounded-lg border border-gray-200/80 shadow-xs flex flex-col justify-between">
<span className="text-[11px] font-medium text-gray-500 uppercase tracking-wide">
Waktu Panen Optimal
</span>
<div className="mt-1">
<span className="text-xl font-bold text-gray-900">
Hari ke-{prediction.optimal_harvest_day}
</span>
<p className="text-xs font-semibold text-emerald-700 mt-0.5">
{prediction.days_remaining > 0
? `± ${prediction.days_remaining} hari lagi`
: 'Siap Panen Hari Ini'}
{prediction.optimal_harvest_date ? ` (${prediction.optimal_harvest_date})` : ''}
</p>
</div>
</div>
{/* Tile 2: Estimated Harvest Weight */}
<div className="bg-white/90 p-3 rounded-lg border border-gray-200/80 shadow-xs flex flex-col justify-between">
<span className="text-[11px] font-medium text-gray-500 uppercase tracking-wide">
Estimasi Bobot Panen
</span>
<div className="mt-1">
<span className="text-xl font-bold text-gray-900">
~{Math.round(prediction.projected_bw_gram).toLocaleString('id-ID')} g
</span>
<p className="text-xs text-gray-500 mt-0.5">{recommendationLabel}</p>
</div>
</div>
{/* Tile 3: Projected FCR */}
<div className="bg-white/90 p-3 rounded-lg border border-gray-200/80 shadow-xs flex flex-col justify-between">
<span className="text-[11px] font-medium text-gray-500 uppercase tracking-wide">
Proyeksi FCR
</span>
<div className="mt-1">
<span className="text-xl font-bold text-gray-900">
{prediction.projected_fcr.toFixed(3)}
</span>
<p className="text-xs text-gray-500 mt-0.5">
Jendela: Hari {prediction.harvest_window_days[0]}-
{prediction.harvest_window_days[1]}
</p>
</div>
</div>
{/* Tile 4: Projected EEF */}
<div className="bg-white/90 p-3 rounded-lg border border-gray-200/80 shadow-xs flex flex-col justify-between">
<span className="text-[11px] font-medium text-gray-500 uppercase tracking-wide">
Proyeksi EEF / IP
</span>
<div className="mt-1">
<span className="text-xl font-bold text-emerald-700">
{Math.round(prediction.projected_eef)}
</span>
<p className="text-xs text-gray-500 mt-0.5">Puncak Efisiensi Pakan</p>
</div>
</div>
</div>
) : (
<div className="mt-3 py-3.5 px-4 text-center text-xs bg-blue-50/50 rounded-lg border border-blue-100 text-blue-800 flex items-center justify-center gap-2">
<i className="fa-solid fa-wand-magic-sparkles text-blue-600 shrink-0" />
<span>
Klik tombol <strong>Generate Insight</strong> untuk menghitung estimasi waktu panen
terbaik berdasarkan kurva efisiensi pakan (FCR) dan puncak EEF.
</span>
</div>
)}
{/* Early Harvest Risk Banner */}
{!isLoading && prediction?.early_harvest_risk && (
<div className="mt-3 p-3 rounded-lg bg-amber-50 border border-amber-200 text-amber-800 text-xs flex items-center gap-2">
<i className="fa-solid fa-triangle-exclamation text-amber-600 text-sm shrink-0" />
<span>
<strong>Perhatian Panen Dini:</strong> Terdeteksi tren kenaikan mortalitas atau deviasi
lingkungan mendekati panen. Pertimbangkan percepatan panen untuk mitigasi risiko
kerugian pakan dan kematian.
</span>
</div>
)}
</div>
);
};
export default HarvestPredictionWidget;
+80 -6
View File
@@ -7,11 +7,85 @@ import React from 'react';
export type InsightStatus = 'ok' | 'warning' | 'critical' | 'unknown';
const STATUS_CHIP: Record<InsightStatus, { cls: string; glyph: string }> = {
ok: { cls: 'bg-green-50 text-green-800 border-green-200', glyph: '✓' },
warning: { cls: 'bg-amber-50 text-amber-800 border-amber-200', glyph: '!' },
critical: { cls: 'bg-red-50 text-red-800 border-red-200', glyph: '⚠' },
unknown: { cls: 'bg-gray-50 text-gray-500 border-gray-200', glyph: '–' },
export const INSIGHT_STATUS_META: Record<
InsightStatus,
{ cls: string; glyph: string; label: string; bg: string; text: string; containerCls: string }
> = {
ok: {
cls: 'bg-green-50 text-green-800 border-green-200',
glyph: '✓',
label: 'Normal',
bg: 'bg-green-50',
text: 'text-green-800',
containerCls: 'bg-green-50/40 border-green-200',
},
warning: {
cls: 'bg-amber-50 text-amber-800 border-amber-200',
glyph: '!',
label: 'Perhatian',
bg: 'bg-amber-50',
text: 'text-amber-800',
containerCls: 'bg-amber-50/40 border-amber-200',
},
critical: {
cls: 'bg-red-50 text-red-800 border-red-200',
glyph: '⚠',
label: 'Kritis',
bg: 'bg-red-50',
text: 'text-red-800',
containerCls: 'bg-red-50/40 border-red-200',
},
unknown: {
cls: 'bg-gray-50 text-gray-600 border-gray-200',
glyph: '–',
label: 'Belum Dinilai',
bg: 'bg-gray-50',
text: 'text-gray-600',
containerCls: 'bg-gray-50/60 border-gray-200',
},
};
export const normalizeInsightStatus = (status: unknown): InsightStatus => {
if (!status || typeof status !== 'string') return 'unknown';
const lower = status.toLowerCase();
if (lower === 'ok' || lower === 'healthy' || lower === 'normal' || lower === 'aman') return 'ok';
if (lower === 'warning' || lower === 'perhatian' || lower === 'waspada') return 'warning';
if (lower === 'critical' || lower === 'kritis' || lower === 'bahaya') return 'critical';
return 'unknown';
};
export interface InsightStatusBadgeProps {
status: InsightStatus | string;
customLabel?: string;
className?: string;
size?: 'xs' | 'sm' | 'md';
}
export const InsightStatusBadge: React.FC<InsightStatusBadgeProps> = ({
status,
customLabel,
className = '',
size = 'sm',
}) => {
const norm = normalizeInsightStatus(status);
const meta = INSIGHT_STATUS_META[norm];
const sizeClasses =
size === 'xs'
? 'px-2 py-0.5 text-[10px]'
: size === 'md'
? 'px-3 py-1 text-xs'
: 'px-2.5 py-0.5 text-[11px]';
return (
<span
className={`inline-flex items-center gap-1.5 rounded-full border font-semibold tracking-wide ${meta.cls} ${sizeClasses} ${className}`}
>
<span aria-hidden="true" className="font-bold">
{meta.glyph}
</span>
<span>{customLabel || meta.label}</span>
</span>
);
};
interface DeltaChipProps {
@@ -20,7 +94,7 @@ interface DeltaChipProps {
}
export const DeltaChip: React.FC<DeltaChipProps> = ({ status, label }) => {
const chip = STATUS_CHIP[status];
const chip = INSIGHT_STATUS_META[status] ?? INSIGHT_STATUS_META.unknown;
return (
<span
className={`inline-flex items-center gap-1 rounded-full border px-2 py-0.5 text-[11px] font-semibold ${chip.cls}`}
+92 -34
View File
@@ -7,7 +7,7 @@
* the DB row is the source of truth.
* Distinct from `AiInsightCard` (Dashboard report modes).
*/
import React, { useState, useEffect, useRef } from 'react';
import React, { useState, useEffect, useRef, useMemo } from 'react';
import { useFarm } from '../../context/FarmContext.tsx';
import { api, errorMessage } from '../../services/apiClient.ts';
import type {
@@ -29,7 +29,13 @@ import {
} from '../../utils/insightScope.ts';
import InsightTrendChart, { type InsightSeries } from './InsightTrendChart.tsx';
import InsightConditionChart, { type ConditionBar } from './InsightConditionChart.tsx';
import { HeroFigure, type InsightStatus } from './InsightStatTiles.tsx';
import {
HeroFigure,
InsightStatusBadge,
INSIGHT_STATUS_META,
normalizeInsightStatus,
type InsightStatus,
} from './InsightStatTiles.tsx';
import InsightProgressSteps from './InsightProgressSteps.tsx';
const CLIENT_TIMEOUT_MS = 1_200_000; // 20 minutes — NUC LLM can take several minutes
@@ -57,6 +63,8 @@ async function pollInsightJob(
type PageInsightResult = AiResult & {
citations?: InsightCitation[];
alert?: string;
status?: InsightStatus;
};
/** Dedupes concurrent soft DB loads for the same scope (not a content cache). */
@@ -426,13 +434,29 @@ export const PageAiInsight: React.FC<PageAiInsightProps> = ({
manual === null ? null : `Manual dituang: ${manual.toLocaleString('id-ID')} karung`,
perDay === null ? null : `${perDay.toLocaleString('id-ID')} karung/hari`,
].filter(Boolean);
const saldoKarung = masukTotal != null && actual != null ? masukTotal - actual : null;
let karungStatus: InsightStatus = 'ok';
if (saldoKarung !== null && saldoKarung < 0) {
karungStatus = 'critical';
} else if (manual !== null && manual > 0 && Math.abs(actual - manual) / manual > 0.1) {
karungStatus = 'warning';
} else {
karungStatus = 'ok';
}
return {
label: 'Pakan Dituang (IOT)',
value: actual.toLocaleString('id-ID'),
unit: 'karung',
context: parts.length > 0 ? parts.join(' · ') : null,
status: 'unknown' as InsightStatus,
deltaLabel: null,
status: karungStatus,
deltaLabel:
saldoKarung !== null
? `Saldo: ${saldoKarung.toLocaleString('id-ID')} karung`
: manual !== null && manual > 0
? `${Math.round(((actual - manual) / manual) * 100)}% vs manual`
: null,
};
}
@@ -620,11 +644,14 @@ export const PageAiInsight: React.FC<PageAiInsightProps> = ({
throw new Error('Respons AI tidak dapat diproses.');
}
const alertRaw = (apiResult as Record<string, unknown> | null)?.alert as string | undefined;
const wrapped: PageInsightResult = {
summary: parsed.summary,
akar_masalah: parsed.akar_masalah,
insight: parsed.insight,
citations: apiResult.citations,
alert: alertRaw,
status: normalizeInsightStatus(alertRaw),
};
if (!isCurrent()) return wrapped;
@@ -662,6 +689,16 @@ export const PageAiInsight: React.FC<PageAiInsightProps> = ({
generateRef.current = generate;
});
const effectiveStatus: InsightStatus = useMemo(() => {
if (result?.status && result.status !== 'unknown') return result.status;
if (result?.alert) {
const norm = normalizeInsightStatus(result.alert);
if (norm !== 'unknown') return norm;
}
if (heroSpec?.status && heroSpec.status !== 'unknown') return heroSpec.status;
return 'unknown';
}, [result, heroSpec]);
// Day / scope change: clear UI and soft-load from DB (no generate).
useEffect(() => {
if (lastCacheKeyRef.current === scopeKey) return;
@@ -693,10 +730,15 @@ export const PageAiInsight: React.FC<PageAiInsightProps> = ({
<span className="text-sm font-bold text-gray-900 group-hover:text-red-700 transition-colors">
{meta.title}
</span>
{isCollapsed && result && (
<span className="text-[10px] font-semibold text-emerald-700 bg-emerald-50 border border-emerald-200 px-2 py-0.5 rounded-full">
Tersedia
</span>
{result && (
<InsightStatusBadge
status={effectiveStatus}
customLabel={
isCollapsed
? `Tersedia (${INSIGHT_STATUS_META[effectiveStatus].label})`
: undefined
}
/>
)}
</div>
<p className="text-xs text-gray-400 truncate">
@@ -1073,34 +1115,41 @@ export const PageAiInsight: React.FC<PageAiInsightProps> = ({
</div>
)}
<div className="mt-6 pt-4 border-t border-gray-100">
<h4 className="text-sm font-bold text-gray-800 mb-2 flex items-center gap-2">
<i className="fa-solid fa-circle-check text-green-600" /> Kesimpulan
</h4>
<p className="text-sm text-gray-700 bg-gray-50 p-3 rounded-lg border border-gray-100">
{result.summary}
</p>
</div>
{result.akar_masalah && (
<div className="mt-4">
<h4 className="text-sm font-bold text-gray-800 mb-2 flex items-center gap-2">
<i className="fa-solid fa-magnifying-glass-chart text-amber-600" /> Akar
Masalah
</h4>
<p className="text-sm text-gray-700 bg-amber-50/50 p-3 rounded-lg border border-amber-100/80">
{result.akar_masalah}
<div
className={`mt-6 rounded-xl border p-4 sm:p-5 space-y-4 shadow-xs ${INSIGHT_STATUS_META[effectiveStatus].containerCls}`}
>
<div>
<div className="flex items-center justify-between mb-2">
<h4 className="text-sm font-bold text-gray-800 flex items-center gap-2">
<i className="fa-solid fa-file-lines text-blue-600" /> Kesimpulan
</h4>
<InsightStatusBadge status={effectiveStatus} />
</div>
<p className="text-sm text-gray-700 bg-white/85 p-3.5 rounded-lg border border-gray-200/70 shadow-xs leading-relaxed">
{result.summary}
</p>
</div>
)}
<div className="mt-4">
<h4 className="text-sm font-bold text-gray-800 mb-2 flex items-center gap-2">
<i className="fa-solid fa-brain text-red-600" /> AI Insight & Rekomendasi
</h4>
<p className="text-sm text-gray-700 bg-gray-50 p-3 rounded-lg border border-gray-100 whitespace-pre-wrap">
{result.insight}
</p>
{result.akar_masalah && (
<div>
<h4 className="text-sm font-bold text-gray-800 mb-2 flex items-center gap-2">
<i className="fa-solid fa-magnifying-glass-chart text-amber-600" /> Akar
Masalah
</h4>
<p className="text-sm text-gray-700 bg-white/85 p-3.5 rounded-lg border border-amber-200/70 shadow-xs leading-relaxed">
{result.akar_masalah}
</p>
</div>
)}
<div>
<h4 className="text-sm font-bold text-gray-800 mb-2 flex items-center gap-2">
<i className="fa-solid fa-brain text-red-600" /> AI Insight & Rekomendasi
</h4>
<p className="text-sm text-gray-700 bg-white/85 p-3.5 rounded-lg border border-gray-200/70 shadow-xs whitespace-pre-wrap leading-relaxed">
{result.insight}
</p>
</div>
</div>
<CitationsBlock citations={result.citations} />
@@ -1108,7 +1157,15 @@ export const PageAiInsight: React.FC<PageAiInsightProps> = ({
</div>
)}
<div className="mt-5 pt-3 border-t border-gray-100 flex justify-center">
<div className="mt-5 pt-3 border-t border-gray-100 flex items-center justify-between">
<div className="text-xs text-gray-400">
{result && (
<span className="inline-flex items-center gap-1.5">
<span>Status AI Insight:</span>
<InsightStatusBadge status={effectiveStatus} size="xs" />
</span>
)}
</div>
<button
type="button"
onClick={() => {
@@ -1121,6 +1178,7 @@ export const PageAiInsight: React.FC<PageAiInsightProps> = ({
>
<i className="fa-solid fa-chevron-up text-xs transition-transform group-hover:-translate-y-0.5" />
</button>
<div className="w-12" />
</div>
</div>
)}
+3 -1
View File
@@ -42,7 +42,9 @@ describe('apiClient', () => {
it('sends CSRF token on POST', async () => {
document.cookie = 'csrftoken=abc123; path=/';
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ id: 1, user_name: 'admin', display_name: 'admin' }));
const fetchMock = vi
.fn()
.mockResolvedValue(jsonResponse({ id: 1, user_name: 'admin', display_name: 'Admin' }));
vi.stubGlobal('fetch', fetchMock);
await api.auth.login('admin', 'admin123');
+2
View File
@@ -77,6 +77,8 @@ function parseDetail(body: unknown): string {
}
async function ensureCsrf(): Promise<string> {
const fromCookie = getCookie('csrftoken');
if (fromCookie) return fromCookie;
const res = await fetch(`${API_BASE}/auth/csrf/`, { credentials: 'include' });
if (!res.ok) {
throw new ApiError('Gagal mengambil CSRF token', res.status, null);
+21
View File
@@ -285,12 +285,31 @@ export type AIInsight = {
report_period: string;
summary?: string;
citations?: InsightCitation[];
harvest_prediction?: HarvestPredictionResult | null;
section?: string;
session?: string;
created_at: string;
updated_at: string;
};
export type HarvestPredictionResult = {
optimal_harvest_day: number;
optimal_harvest_date: string | null;
days_remaining: number;
projected_bw_gram: number;
projected_fcr: number;
projected_eef: number;
harvest_window_days: [number, number];
efficiency_status: 'growing' | 'approaching_window' | 'optimal_window' | 'post_optimal';
adg_actual_gram: number | null;
harvest_type?: 'thinning' | 'main';
recommendation_label?: string;
min_market_bw_gram?: number;
early_harvest_risk: boolean;
notes?: string;
};
export type InsightReportType = 'page' | 'daily' | 'weekly' | 'end_cycle';
export type InsightTopic =
@@ -421,6 +440,7 @@ export type InsightApiResponse = {
structured?: InsightStructuredReport | null;
structured_end_cycle?: EndCycleStructuredInsight | null;
citations?: InsightCitation[];
harvest_prediction?: HarvestPredictionResult | null;
message?: string;
};
@@ -458,6 +478,7 @@ export type CycleWrite = {
doc_in_count: number;
feed_initial_balance?: number;
feed_initial_balance_date?: string | null;
feed_initial_balance_iot?: number | null;
status?: CycleStatus;
};
+13 -4
View File
@@ -25,8 +25,9 @@ describe('getTargetWeightForAge', () => {
expect(getTargetWeightForAge(7, 60)).toBe(row.values[6]);
});
it('returns null for ages outside 1..35', () => {
expect(getTargetWeightForAge(0, 42)).toBeNull();
it('returns docWeight for age 0 and null for ages outside 0..35', () => {
expect(getTargetWeightForAge(0, 42)).toBe(42);
expect(getTargetWeightForAge(-1, 42)).toBeNull();
expect(getTargetWeightForAge(36, 42)).toBeNull();
});
});
@@ -37,7 +38,15 @@ describe('getTargetGainForAge', () => {
expect(getTargetGainForAge(2, 40)).toBe(row.values[1]! - row.values[0]!);
});
it('returns null for age 1', () => {
expect(getTargetGainForAge(1, 40)).toBeNull();
it('calculates target gain for age 1 relative to docWeight', () => {
const row = rowForDoc(40);
expect(getTargetGainForAge(1, 40)).toBe(row.values[0]! - 40);
});
it('returns null for ages outside 1..35 or invalid docWeight', () => {
expect(getTargetGainForAge(0, 40)).toBeNull();
expect(getTargetGainForAge(36, 40)).toBeNull();
expect(getTargetGainForAge(1, 0)).toBeNull();
expect(getTargetGainForAge(1, -5)).toBeNull();
});
});
+4
View File
@@ -531,6 +531,8 @@ export type BuildDashboardInsightContextArgs = {
panen_kumulatif_ekor?: number | null;
tonase_panen_kg?: number | null;
uniformity_persen?: number | null;
cycle_start_date?: string | null;
adg_actual_gram?: number | null;
};
export function buildDashboardInsightContext(
@@ -559,6 +561,8 @@ export function buildDashboardInsightContext(
panen_kumulatif_ekor: args.panen_kumulatif_ekor ?? null,
tonase_panen_kg: args.tonase_panen_kg ?? null,
uniformity_persen: args.uniformity_persen ?? null,
cycle_start_date: args.cycle_start_date ?? null,
adg_actual_gram: args.adg_actual_gram ?? null,
};
}