diff --git a/backend/apps/operations/migrations/0022_aiinsight_harvest_prediction.py b/backend/apps/operations/migrations/0022_aiinsight_harvest_prediction.py new file mode 100644 index 0000000..a3ebbe9 --- /dev/null +++ b/backend/apps/operations/migrations/0022_aiinsight_harvest_prediction.py @@ -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), + ), + ] diff --git a/backend/apps/operations/models.py b/backend/apps/operations/models.py index 4401e3b..e9585e2 100644 --- a/backend/apps/operations/models.py +++ b/backend/apps/operations/models.py @@ -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) diff --git a/backend/apps/operations/services/harvest_projection.py b/backend/apps/operations/services/harvest_projection.py new file mode 100644 index 0000000..4d6880a --- /dev/null +++ b/backend/apps/operations/services/harvest_projection.py @@ -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 diff --git a/backend/apps/operations/services/insight_service.py b/backend/apps/operations/services/insight_service.py index 57d6c4a..16e290c 100644 --- a/backend/apps/operations/services/insight_service.py +++ b/backend/apps/operations/services/insight_service.py @@ -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) diff --git a/backend/apps/operations/tests_harvest_projection.py b/backend/apps/operations/tests_harvest_projection.py new file mode 100644 index 0000000..4c8279f --- /dev/null +++ b/backend/apps/operations/tests_harvest_projection.py @@ -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" diff --git a/backend/apps/operations/tests_insight_quality.py b/backend/apps/operations/tests_insight_quality.py index ab5131e..d04039e 100644 --- a/backend/apps/operations/tests_insight_quality.py +++ b/backend/apps/operations/tests_insight_quality.py @@ -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() \ No newline at end of file diff --git a/backend/database/erd_schema.sql b/backend/database/erd_schema.sql index 41afada..250dc52 100644 --- a/backend/database/erd_schema.sql +++ b/backend/database/erd_schema.sql @@ -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); diff --git a/components/AiInsightCard.tsx b/components/AiInsightCard.tsx index b63186c..e7250f0 100644 --- a/components/AiInsightCard.tsx +++ b/components/AiInsightCard.tsx @@ -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 = ''; @@ -262,10 +264,12 @@ export const AiInsightCard: React.FC = ({ const [reportType, setReportType] = useState('daily'); const [dayPeriod, setDayPeriod] = useState(null); const [isCollapsed, setIsCollapsed] = useState(false); + const [harvestPrediction, setHarvestPrediction] = useState(null); const cardRef = useRef(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 = ({ 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 = ({ 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 = ({ } } + 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 = ({ } // 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 = ({ apiResult.summary, apiResult.akar_masalah, apiResult.insight, - (apiResult as Record | null)?.alert as string | undefined + (apiResult as Record | 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 = ({ <> {effectiveKandangId != null ? renderVisualBlock() : null} + {effectiveKandangId != null && + (page === 'dashboard' || !page) && + reportType === 'daily' && ( + + )} +
{effectiveKandangId == null ? (
@@ -1208,12 +1244,13 @@ export const AiInsightCard: React.FC = ({

Belum ada AI Insight untuk periode ini.

- Klik tombol refresh untuk generate insight. + Klik tombol di bawah untuk membuat insight baru.