forked from audrix/dashboard-cpsp
update ai insight feature for harvest prediction
This commit is contained in:
1 parent
535a34266b
commit
76a74fee0a
13 files changed
+999
-22
No files matched your search
@@ -0,0 +1,18 @@
|
||||
# Generated by Django 5.2.17 on 2026-10-15 03:06
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('operations', '0021_chickenweight_chicken_area_and_more'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
model_name='aiinsight',
|
||||
name='harvest_prediction',
|
||||
field=models.JSONField(blank=True, null=True),
|
||||
),
|
||||
]
|
||||
@@ -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)
|
||||
|
||||
|
||||
@@ -0,0 +1,289 @@
|
||||
"""
|
||||
Deterministic Forward Projection Engine for Broiler Harvest Time.
|
||||
Based on PT Charoen Pokphand Indonesia CP 707 Management Guide (July 2023).
|
||||
|
||||
Principles:
|
||||
- Code grades numbers, LLM only narrates.
|
||||
- Blended growth scaling [0.75, 1.15] combining cumulative BW ratio (65%) and recent ADG ratio (35%).
|
||||
- Purely data-driven optimization: Peak EEF curve starting from commercial harvest threshold (>= 1000g)
|
||||
without requiring manual minimum weight input from the user.
|
||||
- Resilient to missing or incomplete weighing data.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date, datetime, timedelta
|
||||
from typing import Any
|
||||
|
||||
from apps.operations.services.cp707_knowledge import PERFORMANCE_STANDARD_DAILY
|
||||
from apps.operations.services.kpi_formulas import compute_eef
|
||||
|
||||
|
||||
DAILY_STANDARDS_BY_DAY = {row["day"]: row for row in PERFORMANCE_STANDARD_DAILY}
|
||||
COMMERCIAL_MIN_BW_G = 1000.0
|
||||
MAX_THINNING_DAY = 27
|
||||
|
||||
|
||||
def calculate_growth_scale(
|
||||
current_age: int,
|
||||
current_bw_g: float | None = None,
|
||||
adg_actual: float | None = None,
|
||||
) -> float:
|
||||
"""
|
||||
Calculate the actual growth rate ratio scaled against CP 707 standard.
|
||||
Uses a blended ratio (65% cumulative BW vs standard + 35% actual ADG vs standard)
|
||||
clamped strictly between 0.75 and 1.15 to prevent single-day ADG spikes from distorting projections.
|
||||
"""
|
||||
if current_age < 1 or current_age > 45:
|
||||
return 1.0
|
||||
|
||||
std_row = DAILY_STANDARDS_BY_DAY.get(current_age)
|
||||
if not std_row:
|
||||
std_row = DAILY_STANDARDS_BY_DAY.get(37, {"adg_g": 95, "bw_g": 2380})
|
||||
|
||||
std_adg = float(std_row.get("adg_g") or 95.0)
|
||||
std_bw = float(std_row.get("bw_g") or 2380.0)
|
||||
|
||||
has_bw = current_bw_g is not None and float(current_bw_g) > 0 and std_bw > 0
|
||||
has_adg = adg_actual is not None and float(adg_actual) > 0 and std_adg > 0
|
||||
|
||||
if has_bw and has_adg:
|
||||
ratio_bw = float(current_bw_g) / std_bw
|
||||
ratio_adg = float(adg_actual) / std_adg
|
||||
blended = (0.65 * ratio_bw) + (0.35 * ratio_adg)
|
||||
return max(0.75, min(1.15, blended))
|
||||
|
||||
if has_bw:
|
||||
ratio_bw = float(current_bw_g) / std_bw
|
||||
return max(0.75, min(1.15, ratio_bw))
|
||||
|
||||
if has_adg:
|
||||
ratio_adg = float(adg_actual) / std_adg
|
||||
return max(0.75, min(1.15, ratio_adg))
|
||||
|
||||
return 1.0
|
||||
|
||||
|
||||
def project_daily_curve(
|
||||
current_age: int,
|
||||
current_bw_g: float,
|
||||
current_feed_cum_g: float,
|
||||
current_mort_pct: float,
|
||||
scale: float = 1.0,
|
||||
max_day: int = 38,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""
|
||||
Project daily weight, cumulative feed, FCR, cumulative mortality, and EEF
|
||||
from current_age + 1 up to max_day.
|
||||
"""
|
||||
curve: list[dict[str, Any]] = []
|
||||
|
||||
last_bw = float(current_bw_g)
|
||||
last_feed = float(current_feed_cum_g)
|
||||
last_mort = float(current_mort_pct)
|
||||
|
||||
start_day = max(1, current_age + 1)
|
||||
|
||||
for day in range(start_day, max_day + 1):
|
||||
if day <= 37 and day in DAILY_STANDARDS_BY_DAY:
|
||||
std_row = DAILY_STANDARDS_BY_DAY[day]
|
||||
adg_std = float(std_row["adg_g"])
|
||||
daily_feed = float(std_row["feedDaily_g"])
|
||||
prev_std = DAILY_STANDARDS_BY_DAY.get(day - 1)
|
||||
if prev_std:
|
||||
mort_delta = max(0.0, float(std_row["mortalityCum_pct"]) - float(prev_std["mortalityCum_pct"]))
|
||||
else:
|
||||
mort_delta = 0.10
|
||||
else:
|
||||
extra_days = day - 37
|
||||
adg_std = max(60.0, 95.0 - extra_days * 5.0)
|
||||
daily_feed = 195.0 + extra_days * 5.0
|
||||
mort_delta = 0.12
|
||||
|
||||
proj_bw = last_bw + (adg_std * scale)
|
||||
proj_feed = last_feed + daily_feed
|
||||
proj_mort = last_mort + mort_delta
|
||||
|
||||
proj_fcr = proj_feed / proj_bw if proj_bw > 0 else 0.0
|
||||
life_pct = max(0.0, 100.0 - proj_mort)
|
||||
proj_eef = compute_eef(life_pct, proj_bw, float(day), proj_fcr)
|
||||
|
||||
curve.append({
|
||||
"day": day,
|
||||
"projected_bw_g": round(proj_bw, 1),
|
||||
"projected_feed_cum_g": round(proj_feed, 1),
|
||||
"projected_fcr": round(proj_fcr, 3),
|
||||
"projected_mortality_pct": round(proj_mort, 2),
|
||||
"projected_eef": round(proj_eef, 1),
|
||||
})
|
||||
|
||||
last_bw = proj_bw
|
||||
last_feed = proj_feed
|
||||
last_mort = proj_mort
|
||||
|
||||
return curve
|
||||
|
||||
|
||||
def _parse_cycle_start_date(start_date: str | date | None) -> date | None:
|
||||
if not start_date:
|
||||
return None
|
||||
if isinstance(start_date, date):
|
||||
return start_date
|
||||
if isinstance(start_date, str):
|
||||
try:
|
||||
return datetime.strptime(start_date.split("T")[0], "%Y-%m-%d").date()
|
||||
except Exception:
|
||||
return None
|
||||
return None
|
||||
|
||||
|
||||
def find_optimal_harvest_window(
|
||||
current_age: int,
|
||||
projection_curve: list[dict[str, Any]],
|
||||
cycle_start_date: str | date | None = None,
|
||||
current_mortality_pct: float = 0.0,
|
||||
uniformity_pct: float | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
Select optimal harvest day automatically based on:
|
||||
1. Commercial minimum harvestable weight (>= 1000g)
|
||||
2. Peak projected EEF (European Efficiency Factor)
|
||||
3. Classification into Thinning (Panen Penjarangan/Seleksi) vs Main Harvest (Panen Utama)
|
||||
"""
|
||||
if not projection_curve:
|
||||
return {
|
||||
"optimal_harvest_day": max(33, current_age),
|
||||
"optimal_harvest_date": None,
|
||||
"days_remaining": max(0, 33 - current_age),
|
||||
"projected_bw_gram": 1950.0,
|
||||
"projected_fcr": 1.52,
|
||||
"projected_eef": 375.0,
|
||||
"harvest_window_days": [32, 34],
|
||||
"efficiency_status": "growing",
|
||||
"harvest_type": "main",
|
||||
"recommendation_label": "Panen Utama / Panen Raya",
|
||||
"adg_actual_gram": None,
|
||||
"early_harvest_risk": False,
|
||||
"notes": "Fallback default window",
|
||||
}
|
||||
|
||||
candidates = [
|
||||
pt for pt in projection_curve
|
||||
if pt["projected_bw_g"] >= COMMERCIAL_MIN_BW_G
|
||||
]
|
||||
|
||||
if candidates:
|
||||
best = max(candidates, key=lambda pt: pt["projected_eef"])
|
||||
else:
|
||||
best = projection_curve[-1]
|
||||
|
||||
optimal_day = int(best["day"])
|
||||
window_start = max(1, optimal_day - 1)
|
||||
window_end = optimal_day + 1
|
||||
|
||||
# Calendar date calculation (Day 0 = cycle_start_date)
|
||||
parsed_start = _parse_cycle_start_date(cycle_start_date)
|
||||
optimal_date_str = None
|
||||
if parsed_start:
|
||||
target_dt = parsed_start + timedelta(days=optimal_day)
|
||||
optimal_date_str = target_dt.strftime("%Y-%m-%d")
|
||||
|
||||
# Determine efficiency status phase
|
||||
if current_age < optimal_day - 3:
|
||||
status = "growing"
|
||||
elif optimal_day - 3 <= current_age <= optimal_day - 1:
|
||||
status = "approaching_window"
|
||||
elif optimal_day <= current_age <= optimal_day + 1:
|
||||
status = "optimal_window"
|
||||
else:
|
||||
status = "post_optimal"
|
||||
|
||||
# Classify harvest type: Thinning (Penjarangan/Seleksi) only up to MAX_THINNING_DAY (day 27)
|
||||
proj_bw = float(best["projected_bw_g"])
|
||||
is_low_uniformity = uniformity_pct is not None and 0 < float(uniformity_pct) < 60.0
|
||||
if optimal_day <= MAX_THINNING_DAY and (proj_bw < 1450.0 or is_low_uniformity):
|
||||
harvest_type = "thinning"
|
||||
recommendation_label = "Panen Penjarangan / Seleksi Awal"
|
||||
else:
|
||||
harvest_type = "main"
|
||||
recommendation_label = "Panen Utama / Panen Raya"
|
||||
|
||||
# High mortality or health risk near harvest
|
||||
early_risk = False
|
||||
if current_mortality_pct >= 6.0 and current_age >= 25:
|
||||
early_risk = True
|
||||
|
||||
return {
|
||||
"optimal_harvest_day": optimal_day,
|
||||
"optimal_harvest_date": optimal_date_str,
|
||||
"days_remaining": max(0, optimal_day - current_age),
|
||||
"projected_bw_gram": best["projected_bw_g"],
|
||||
"projected_fcr": best["projected_fcr"],
|
||||
"projected_eef": best["projected_eef"],
|
||||
"harvest_window_days": [window_start, window_end],
|
||||
"efficiency_status": status,
|
||||
"harvest_type": harvest_type,
|
||||
"recommendation_label": recommendation_label,
|
||||
"adg_actual_gram": None,
|
||||
"early_harvest_risk": early_risk,
|
||||
"notes": (
|
||||
f"Peak EEF {best['projected_eef']} at day {optimal_day} "
|
||||
f"with projected BW {best['projected_bw_g']}g ({recommendation_label})"
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
def evaluate_harvest_prediction(context: dict[str, Any]) -> dict[str, Any]:
|
||||
"""
|
||||
Main entry point for harvest prediction from dashboard insight context.
|
||||
"""
|
||||
current_age = int(context.get("hari_ke") or context.get("age") or 0)
|
||||
current_bw = context.get("bobot_avg_gram") or context.get("bobot_iot_gram") or context.get("bw_gram")
|
||||
adg_actual = context.get("adg_actual_gram") or context.get("adg_g") or context.get("adg")
|
||||
fcr_actual = context.get("fcr_terakhir") or context.get("fcr")
|
||||
uniformity_pct = context.get("uniformity_persen") or context.get("uniformity")
|
||||
mort_pct = context.get("mortalitas_kumulatif_persen")
|
||||
if mort_pct is None and context.get("persen_hidup") is not None:
|
||||
mort_pct = max(0.0, 100.0 - float(context["persen_hidup"]))
|
||||
mort_pct = float(mort_pct or 0.0)
|
||||
|
||||
cycle_start = context.get("cycle_start_date") or context.get("start_date")
|
||||
|
||||
# Resilient Fallbacks
|
||||
std_row = DAILY_STANDARDS_BY_DAY.get(current_age)
|
||||
if not std_row:
|
||||
std_row = DAILY_STANDARDS_BY_DAY.get(min(37, max(1, current_age))) or {
|
||||
"bw_g": 1284, "feedCum_g": 1726.5, "mortalityCum_pct": 2.88, "fcr": 1.345
|
||||
}
|
||||
|
||||
if current_bw is None or float(current_bw) <= 0:
|
||||
current_bw = float(std_row.get("bw_g", 1284.0))
|
||||
else:
|
||||
current_bw = float(current_bw)
|
||||
|
||||
if fcr_actual is not None and float(fcr_actual) > 0:
|
||||
current_feed_cum = current_bw * float(fcr_actual)
|
||||
else:
|
||||
current_feed_cum = float(std_row.get("feedCum_g", current_bw * 1.35))
|
||||
|
||||
scale = calculate_growth_scale(current_age, current_bw, adg_actual)
|
||||
|
||||
max_proj_day = max(38, current_age + 2)
|
||||
curve = project_daily_curve(
|
||||
current_age=current_age,
|
||||
current_bw_g=current_bw,
|
||||
current_feed_cum_g=current_feed_cum,
|
||||
current_mort_pct=mort_pct,
|
||||
scale=scale,
|
||||
max_day=max_proj_day,
|
||||
)
|
||||
|
||||
result = find_optimal_harvest_window(
|
||||
current_age=current_age,
|
||||
projection_curve=curve,
|
||||
cycle_start_date=cycle_start,
|
||||
current_mortality_pct=mort_pct,
|
||||
uniformity_pct=float(uniformity_pct) if uniformity_pct is not None else None,
|
||||
)
|
||||
result["adg_actual_gram"] = float(adg_actual) if adg_actual is not None else None
|
||||
return result
|
||||
@@ -241,6 +241,31 @@ def build_insight_user_prompt(
|
||||
"bobot ayam, atau FCR karena metrik tersebut bukan bagian dari topik Hitung Karung."
|
||||
)
|
||||
|
||||
if topic == "dashboard" and graded and graded.get("harvest_prediction"):
|
||||
hp = graded["harvest_prediction"]
|
||||
opt_day = hp.get("optimal_harvest_day")
|
||||
opt_date = hp.get("optimal_harvest_date") or "-"
|
||||
proj_bw = hp.get("projected_bw_gram")
|
||||
proj_fcr = hp.get("projected_fcr")
|
||||
proj_eef = hp.get("projected_eef")
|
||||
rec_label = hp.get("recommendation_label") or "Panen Optimal"
|
||||
status_fase = hp.get("efficiency_status")
|
||||
early_risk = hp.get("early_harvest_risk")
|
||||
|
||||
lines.append(
|
||||
"\n[PROYEKSI WAKTU PANEN TERBAIK (DETERMINISTIK CP 707)]\n"
|
||||
f"- Jenis Rekomendasi Panen: {rec_label}\n"
|
||||
f"- Hari Panen Optimal: Hari ke-{opt_day} (Estimasi Tanggal: {opt_date})\n"
|
||||
f"- Proyeksi Bobot saat Panen: ~{proj_bw} gram\n"
|
||||
f"- Proyeksi FCR: {proj_fcr}\n"
|
||||
f"- Proyeksi EEF (Indeks Performa): {proj_eef}\n"
|
||||
f"- Status Fase: {status_fase}\n"
|
||||
f"- Peringatan Panen Dini: {'YA (Perlu mitigasi risiko mortalitas)' if early_risk else 'Tidak'}\n"
|
||||
"INSTRUKSI PANEN UNTUK LLM: Masukkan ulasan proyeksi panen ini ke dalam narasi insight. "
|
||||
"Jelaskan alasan teknis penentuan hari panen optimal tersebut berdasarkan puncak kurva EEF, tren FCR, dan keseragaman/kepadatan kandang, serta rekomendasikan SOP pra-panen "
|
||||
"(puasa pakan 8-12 jam sebelum tangkap, pencahayaan redup saat tangkap, sirkulasi udara maksimal)."
|
||||
)
|
||||
|
||||
# 4. Root Cause / ANALISIS AKAR MASALAH (end_cycle only)
|
||||
if is_end_cycle and hypotheses:
|
||||
lines.append("\n[ANALISIS AKAR MASALAH]")
|
||||
@@ -615,6 +640,9 @@ def grade_context(context: dict[str, Any], topic: str | None = None) -> dict[str
|
||||
block["direction"] = "di_atas_standar" if dev > 0 else "di_bawah_standar"
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
if topic == "dashboard":
|
||||
from apps.operations.services.harvest_projection import evaluate_harvest_prediction
|
||||
graded["harvest_prediction"] = evaluate_harvest_prediction(context)
|
||||
return graded
|
||||
|
||||
|
||||
@@ -1046,6 +1074,7 @@ def serialize_insight(row: AIInsight) -> dict[str, Any]:
|
||||
"structured_end_cycle": structured,
|
||||
"alert": row.alert or ALERT_UNKNOWN,
|
||||
"citations": norm_citations,
|
||||
"harvest_prediction": getattr(row, "harvest_prediction", None),
|
||||
"date": row.date.isoformat() if row.date else None,
|
||||
"created_at": row.created_at.isoformat() if row.created_at else None,
|
||||
"updated_at": row.updated_at.isoformat() if row.updated_at else None,
|
||||
@@ -1353,6 +1382,7 @@ def generate_insight(
|
||||
"summary": summary,
|
||||
"alert": alert,
|
||||
"citations": encode_citations(citations),
|
||||
"harvest_prediction": graded.get("harvest_prediction") if graded else None,
|
||||
},
|
||||
)
|
||||
return serialize_insight(row)
|
||||
@@ -0,0 +1,171 @@
|
||||
"""
|
||||
Unit tests for deterministic harvest projection engine (automatic EEF peak & thinning detection).
|
||||
"""
|
||||
|
||||
import pytest
|
||||
|
||||
from apps.operations.services.harvest_projection import (
|
||||
calculate_growth_scale,
|
||||
project_daily_curve,
|
||||
find_optimal_harvest_window,
|
||||
evaluate_harvest_prediction,
|
||||
)
|
||||
|
||||
|
||||
def test_calculate_growth_scale_clamped():
|
||||
# Standard at day 25: BW=1284g, ADG=84g. If actual matches standard, scale is 1.0
|
||||
scale = calculate_growth_scale(current_age=25, current_bw_g=1284, adg_actual=84)
|
||||
assert pytest.approx(scale, rel=1e-2) == 1.0
|
||||
|
||||
# High actual BW and ADG -> clamped to max 1.15
|
||||
scale_high = calculate_growth_scale(current_age=25, current_bw_g=1600, adg_actual=120)
|
||||
assert scale_high == 1.15
|
||||
|
||||
# Low actual BW and ADG -> clamped to min 0.75
|
||||
scale_low = calculate_growth_scale(current_age=25, current_bw_g=850, adg_actual=50)
|
||||
assert scale_low == 0.75
|
||||
|
||||
|
||||
def test_calculate_growth_scale_fallback_to_bw():
|
||||
# If adg_actual is None, derive from current_bw / std_bw
|
||||
scale = calculate_growth_scale(current_age=25, current_bw_g=1284, adg_actual=None)
|
||||
assert pytest.approx(scale, rel=1e-2) == 1.0
|
||||
|
||||
|
||||
def test_project_daily_curve_structure():
|
||||
curve = project_daily_curve(
|
||||
current_age=25,
|
||||
current_bw_g=1280.0,
|
||||
current_feed_cum_g=1720.0,
|
||||
current_mort_pct=2.88,
|
||||
scale=1.0,
|
||||
max_day=38,
|
||||
)
|
||||
assert len(curve) == 13 # days 26 to 38 inclusive
|
||||
assert curve[0]["day"] == 26
|
||||
assert curve[-1]["day"] == 38
|
||||
|
||||
for i in range(len(curve) - 1):
|
||||
assert curve[i + 1]["projected_bw_g"] > curve[i]["projected_bw_g"]
|
||||
assert curve[i + 1]["projected_feed_cum_g"] > curve[i]["projected_feed_cum_g"]
|
||||
assert curve[i]["projected_eef"] > 0
|
||||
assert curve[i]["projected_fcr"] > 0
|
||||
|
||||
|
||||
def test_find_optimal_harvest_window_standard():
|
||||
curve = project_daily_curve(
|
||||
current_age=25,
|
||||
current_bw_g=1284.0,
|
||||
current_feed_cum_g=1726.5,
|
||||
current_mort_pct=2.88,
|
||||
scale=1.0,
|
||||
max_day=38,
|
||||
)
|
||||
res = find_optimal_harvest_window(
|
||||
current_age=25,
|
||||
projection_curve=curve,
|
||||
cycle_start_date="2026-09-01",
|
||||
)
|
||||
assert res["optimal_harvest_day"] >= 26
|
||||
assert res["projected_bw_gram"] >= 1000
|
||||
assert res["harvest_window_days"][0] <= res["optimal_harvest_day"] <= res["harvest_window_days"][1]
|
||||
assert res["days_remaining"] == res["optimal_harvest_day"] - 25
|
||||
assert res["efficiency_status"] in ["growing", "approaching_window", "optimal_window"]
|
||||
assert res["optimal_harvest_date"] is not None
|
||||
assert res["harvest_type"] in ["thinning", "main"]
|
||||
assert res["recommendation_label"] in [
|
||||
"Panen Penjarangan / Seleksi Awal",
|
||||
"Panen Utama / Panen Raya",
|
||||
]
|
||||
|
||||
|
||||
def test_sukawarna_day_23_predicts_day_24_thinning_harvest():
|
||||
"""
|
||||
Validate against actual Sukawarna Kandang Atas dataset at Day 23 (2026-06-14):
|
||||
- start_date: 2026-05-22 (Day 0)
|
||||
- Day 23 actual: BW=1014.73g, ADG_3d=(1014.73-756.45)/3 = 86.09g (or daily ADG=74.34g),
|
||||
FCR=1.2245, Live%=96.896, Uniformity=35.1%
|
||||
Must predict Day 24 (2026-06-15) as optimal thinning harvest!
|
||||
"""
|
||||
context = {
|
||||
"hari_ke": 23,
|
||||
"bobot_avg_gram": 1014.73,
|
||||
"adg_actual_gram": 74.34,
|
||||
"fcr_terakhir": 1.2245,
|
||||
"persen_hidup": 96.896,
|
||||
"uniformity_persen": 35.1,
|
||||
"cycle_start_date": "2026-05-22",
|
||||
}
|
||||
pred = evaluate_harvest_prediction(context)
|
||||
assert pred["optimal_harvest_day"] == 24
|
||||
assert pred["optimal_harvest_date"] == "2026-06-15"
|
||||
assert pred["days_remaining"] == 1
|
||||
assert pred["harvest_window_days"] == [23, 25]
|
||||
assert pred["harvest_type"] == "thinning"
|
||||
assert pred["recommendation_label"] == "Panen Penjarangan / Seleksi Awal"
|
||||
assert pred["efficiency_status"] == "approaching_window"
|
||||
|
||||
|
||||
def test_day_28_or_later_never_classified_as_thinning():
|
||||
"""
|
||||
At age >= 28 (e.g. Day 30 with low uniformity 42.2%), optimal harvest day is >= 28
|
||||
and must be classified as 'main' (Panen Utama / Panen Raya), never 'thinning'.
|
||||
"""
|
||||
context = {
|
||||
"hari_ke": 30,
|
||||
"bobot_avg_gram": 1480.51,
|
||||
"adg_actual_gram": 41.65,
|
||||
"fcr_terakhir": 1.4314,
|
||||
"persen_hidup": 96.232,
|
||||
"uniformity_persen": 42.2,
|
||||
"cycle_start_date": "2026-05-22",
|
||||
}
|
||||
pred = evaluate_harvest_prediction(context)
|
||||
assert pred["optimal_harvest_day"] >= 28
|
||||
assert pred["harvest_type"] == "main"
|
||||
assert pred["recommendation_label"] == "Panen Utama / Panen Raya"
|
||||
|
||||
|
||||
def test_efficiency_status_transitions():
|
||||
curve = project_daily_curve(
|
||||
current_age=30,
|
||||
current_bw_g=1725.0,
|
||||
current_feed_cum_g=2548.0,
|
||||
current_mort_pct=3.52,
|
||||
scale=1.0,
|
||||
max_day=38,
|
||||
)
|
||||
res_opt = find_optimal_harvest_window(current_age=34, projection_curve=curve)
|
||||
if res_opt["optimal_harvest_day"] == 34:
|
||||
assert res_opt["efficiency_status"] == "optimal_window"
|
||||
|
||||
res_post = find_optimal_harvest_window(current_age=39, projection_curve=curve)
|
||||
assert res_post["efficiency_status"] == "post_optimal"
|
||||
|
||||
|
||||
def test_evaluate_harvest_prediction_context_integration():
|
||||
context = {
|
||||
"hari_ke": 27,
|
||||
"bobot_avg_gram": 1450.0,
|
||||
"adg_actual_gram": 86.0,
|
||||
"fcr_terakhir": 1.40,
|
||||
"mortalitas_kumulatif_persen": 3.12,
|
||||
"cycle_start_date": "2026-09-15",
|
||||
}
|
||||
pred = evaluate_harvest_prediction(context)
|
||||
assert pred is not None
|
||||
assert pred["projected_bw_gram"] >= 1000
|
||||
assert pred["optimal_harvest_day"] >= 28
|
||||
assert "optimal_harvest_date" in pred
|
||||
assert pred["efficiency_status"] in ["growing", "approaching_window", "optimal_window", "post_optimal"]
|
||||
|
||||
|
||||
def test_evaluate_harvest_prediction_graceful_fallback():
|
||||
context_young = {"hari_ke": 3, "bobot_avg_gram": 90}
|
||||
pred_young = evaluate_harvest_prediction(context_young)
|
||||
assert pred_young["efficiency_status"] == "growing"
|
||||
assert pred_young["optimal_harvest_day"] >= 30
|
||||
|
||||
pred_empty = evaluate_harvest_prediction({})
|
||||
assert pred_empty is not None
|
||||
assert pred_empty["efficiency_status"] == "growing"
|
||||
@@ -770,6 +770,81 @@ class TraceLintTests(TestCase):
|
||||
self.assertGreater(200, 60)
|
||||
|
||||
|
||||
class HarvestPredictionIntegrationTests(TestCase):
|
||||
"""Test harvest prediction integration in insight_service pipeline."""
|
||||
|
||||
def test_grade_context_includes_harvest_prediction_for_dashboard(self):
|
||||
ctx = {
|
||||
"kandangName": "Kandang 4",
|
||||
"hari_ke": 28,
|
||||
"bobot_avg_gram": 1540.0,
|
||||
"adg_actual_gram": 88.0,
|
||||
"fcr_terakhir": 1.42,
|
||||
"mortalitas_kumulatif_persen": 3.25,
|
||||
"cycle_start_date": "2026-09-17",
|
||||
}
|
||||
graded = insight_service.grade_context(ctx, topic="dashboard")
|
||||
self.assertIn("harvest_prediction", graded)
|
||||
hp = graded["harvest_prediction"]
|
||||
self.assertGreaterEqual(hp["projected_bw_gram"], 1000)
|
||||
self.assertGreaterEqual(hp["optimal_harvest_day"], 28)
|
||||
self.assertIn(hp["efficiency_status"], ["growing", "approaching_window", "optimal_window"])
|
||||
self.assertIn(hp["harvest_type"], ["thinning", "main"])
|
||||
|
||||
def test_build_user_prompt_includes_harvest_prediction(self):
|
||||
ctx = {
|
||||
"kandangName": "Kandang 4",
|
||||
"hari_ke": 28,
|
||||
"bobot_avg_gram": 1540.0,
|
||||
}
|
||||
graded = insight_service.grade_context(ctx, topic="dashboard")
|
||||
prompt = insight_service.build_insight_user_prompt(
|
||||
topic="dashboard",
|
||||
kandang_name="Kandang 4",
|
||||
report_type="page",
|
||||
report_period="current",
|
||||
context=ctx,
|
||||
graded=graded,
|
||||
)
|
||||
self.assertIn("[PROYEKSI WAKTU PANEN TERBAIK (DETERMINISTIK CP 707)]", prompt)
|
||||
self.assertIn("Jenis Rekomendasi Panen:", prompt)
|
||||
self.assertIn("INSTRUKSI PANEN UNTUK LLM", prompt)
|
||||
|
||||
def test_serialize_insight_includes_harvest_prediction_field(self):
|
||||
from apps.accounts.models import User
|
||||
from apps.farms.models import Cycle, Kandang, Site
|
||||
from apps.operations.models import AIInsight
|
||||
from django.utils import timezone
|
||||
|
||||
user = User.objects.create_user(user_name="harvest_tester", password="password")
|
||||
site = Site.objects.create(site_name="Harvest Site", user=user)
|
||||
kandang = Kandang.objects.create(site=site, kandang_name="Kandang 1")
|
||||
cycle = Cycle.objects.create(
|
||||
kandang=kandang, doc_in_count=25000, doc_in_weight=45, start_date=timezone.localdate()
|
||||
)
|
||||
|
||||
ai_row = AIInsight.objects.create(
|
||||
cycle=cycle,
|
||||
kandang=kandang,
|
||||
topic="dashboard",
|
||||
report_type="page",
|
||||
report_period="current",
|
||||
date=timezone.localdate(),
|
||||
insight_text="Test insight",
|
||||
summary="Test summary",
|
||||
harvest_prediction={
|
||||
"optimal_harvest_day": 33,
|
||||
"projected_bw_gram": 1950.0,
|
||||
"min_market_bw_gram": 1700,
|
||||
},
|
||||
)
|
||||
serialized = insight_service.serialize_insight(ai_row)
|
||||
self.assertIn("harvest_prediction", serialized)
|
||||
self.assertIsNotNone(serialized["harvest_prediction"])
|
||||
self.assertEqual(serialized["harvest_prediction"]["optimal_harvest_day"], 33)
|
||||
self.assertEqual(serialized["harvest_prediction"]["projected_bw_gram"], 1950.0)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
import unittest
|
||||
unittest.main()
|
||||
@@ -18,7 +18,7 @@
|
||||
-- kandang → flock → iot_panel
|
||||
-- cycles → ai_insight (scoped by kandang/topic/report), feed_sacks,
|
||||
-- chicken_counting, chicken_weight, manual_input, kpi
|
||||
-- kandang.feed_in_button_urls: JSON map of feed-in button URLs per slot
|
||||
-- kandang.feed_in_button_urls: JSON list of feed-in button URLs ({label, url})
|
||||
-- kpi → chicken_counting, chicken_weight, feed_sacks, manual_input
|
||||
-- =============================================================================
|
||||
|
||||
@@ -103,7 +103,7 @@ CREATE TABLE IF NOT EXISTS kandang (
|
||||
kandang_id SERIAL PRIMARY KEY,
|
||||
kandang_name VARCHAR(30) NOT NULL,
|
||||
site_id VARCHAR(64) NOT NULL REFERENCES sites (site_id) ON DELETE CASCADE,
|
||||
feed_in_button_urls JSONB NOT NULL DEFAULT '{}'::jsonb,
|
||||
feed_in_button_urls JSONB NOT NULL DEFAULT '[]'::jsonb,
|
||||
created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
@@ -189,19 +189,20 @@ CREATE UNIQUE INDEX IF NOT EXISTS uniq_iot_panel_flock_timestamp ON iot_panel (f
|
||||
-- alert: condition from graded CP707 facts (healthy|warning|critical|unknown).
|
||||
-- -----------------------------------------------------------------------------
|
||||
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 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 '[]', -- JSON array string of RAG citations
|
||||
created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
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 '[]', -- JSON array string of RAG citations
|
||||
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);
|
||||
|
||||
@@ -9,6 +9,7 @@ import { useFarm } from '../context/FarmContext.tsx';
|
||||
import { api, errorMessage } from '../services/apiClient.ts';
|
||||
import type {
|
||||
EndCycleStructuredInsight,
|
||||
HarvestPredictionResult,
|
||||
InsightCitation,
|
||||
InsightContext,
|
||||
InsightReportType,
|
||||
@@ -35,6 +36,7 @@ import {
|
||||
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-->';
|
||||
@@ -262,10 +264,12 @@ export const AiInsightCard: React.FC<AiInsightCardProps> = ({
|
||||
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
|
||||
@@ -295,11 +299,15 @@ export const AiInsightCard: React.FC<AiInsightCardProps> = ({
|
||||
summary?: string | null,
|
||||
akarMasalah?: string | null,
|
||||
insightBody?: string | null,
|
||||
alert?: 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) ??
|
||||
@@ -392,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
|
||||
@@ -400,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;
|
||||
@@ -433,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 +502,20 @@ export const AiInsightCard: React.FC<AiInsightCardProps> = ({
|
||||
apiResult.summary,
|
||||
apiResult.akar_masalah,
|
||||
apiResult.insight,
|
||||
(apiResult as Record<string, unknown> | null)?.alert as string | undefined
|
||||
(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);
|
||||
}
|
||||
@@ -943,6 +973,12 @@ 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">
|
||||
@@ -1208,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
|
||||
|
||||
@@ -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();
|
||||
});
|
||||
});
|
||||
@@ -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;
|
||||
@@ -224,10 +224,28 @@ export type AIInsight = {
|
||||
report_period: string;
|
||||
summary?: string;
|
||||
citations?: InsightCitation[];
|
||||
harvest_prediction?: HarvestPredictionResult | null;
|
||||
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 =
|
||||
@@ -345,6 +363,7 @@ export type InsightApiResponse = {
|
||||
structured?: InsightStructuredReport | null;
|
||||
structured_end_cycle?: EndCycleStructuredInsight | null;
|
||||
citations?: InsightCitation[];
|
||||
harvest_prediction?: HarvestPredictionResult | null;
|
||||
message?: string;
|
||||
};
|
||||
|
||||
|
||||
@@ -143,3 +143,21 @@ describe('scopeDashboardInsightMetrics', () => {
|
||||
expect(scoped.weightSeries.map((row) => row.hari)).toEqual([7, 14, 21]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('buildDashboardInsightContext', () => {
|
||||
it('includes cycle_start_date and adg_actual_gram in return payload', async () => {
|
||||
const { buildDashboardInsightContext } = await import('../insightContextBuilders.ts');
|
||||
const ctx = buildDashboardInsightContext({
|
||||
kandangId: 4,
|
||||
kandangName: 'Kandang 4',
|
||||
hari_ke: 25,
|
||||
bobot_avg_gram: 1280,
|
||||
cycle_start_date: '2026-09-17',
|
||||
adg_actual_gram: 84.5,
|
||||
});
|
||||
|
||||
expect(ctx.kandangId).toBe(4);
|
||||
expect(ctx.cycle_start_date).toBe('2026-09-17');
|
||||
expect(ctx.adg_actual_gram).toBe(84.5);
|
||||
});
|
||||
});
|
||||
@@ -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,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user