From 85cdc234c3807841c688a5f3a11ff0c553781b48 Mon Sep 17 00:00:00 2001 From: Alberto-Audrix Date: Tue, 27 Oct 2026 13:47:38 +0700 Subject: [PATCH] adjust ai insight mortality standard for end cycle and daily standard. Remove harvest prediction on end cycle ai insight --- .../operations/services/cp707_knowledge.py | 147 +++++++++++------- .../operations/services/insight_service.py | 30 ++-- .../apps/operations/services/root_cause.py | 5 +- .../apps/operations/tests_insight_grading.py | 16 +- .../apps/operations/tests_insight_quality.py | 23 +++ components/AiInsightCard.tsx | 40 +++-- components/shared/PageAiInsight.tsx | 14 +- utils/cp707EnvStandards.ts | 54 +++++++ 8 files changed, 237 insertions(+), 92 deletions(-) diff --git a/backend/apps/operations/services/cp707_knowledge.py b/backend/apps/operations/services/cp707_knowledge.py index c21b58d..ecd9983 100644 --- a/backend/apps/operations/services/cp707_knowledge.py +++ b/backend/apps/operations/services/cp707_knowledge.py @@ -470,7 +470,12 @@ def analyze_bw(actual_bw_g: Any, day_age: Any, target_bw_g: Any = None) -> dict[ } -def analyze_mortality(mortality_rate_pct: Any, day_age: Any) -> dict[str, Any]: +def analyze_mortality( + mortality_rate_pct: Any, + day_age: Any, + *, + is_end_cycle: bool = False, +) -> dict[str, Any]: rate = _as_float(mortality_rate_pct) std_mortality = get_mortality_cum_std_by_day(day_age) @@ -485,51 +490,62 @@ def analyze_mortality(mortality_rate_pct: Any, day_age: Any) -> dict[str, Any]: "message": "Data mortalitas tidak tersedia.", } - if rate > MORTALITY_THRESHOLDS["critical_pct"]: - status = "critical" - direction = "di_atas_standar" - severity_label = "SANGAT TINGGI" - dilarang = ["rendah", "normal", "baik", "aman", "terkendali", "sedikit"] - message = ( - f"Mortalitas kumulatif {rate:.2f}% adalah SANGAT TINGGI — melebihi batas kritis " - f"CP 707 (>7%)." - ) - elif rate >= MORTALITY_THRESHOLDS["warning_pct"]: - status = "warning" - direction = "di_atas_standar" - severity_label = "TINGGI" - dilarang = ["rendah", "normal", "baik", "aman", "terkendali", "sedikit"] - message = ( - f"Mortalitas kumulatif {rate:.2f}% adalah TINGGI (warning). " - "Standar CP 707 <5%." - ) - elif rate >= MORTALITY_THRESHOLDS["normal_pct"]: - # 5% inclusive through just under warning threshold — still not "rendah" - status = "warning" - direction = "di_atas_standar" - severity_label = "TINGGI" - dilarang = ["rendah", "normal", "baik", "aman", "terkendali", "sedikit"] - message = ( - f"Mortalitas kumulatif {rate:.2f}% adalah TINGGI. " - "Standar CP 707 <5%." - ) - elif std_mortality is not None and rate > std_mortality * 1.5: - status = "warning" - direction = "di_atas_standar" - severity_label = "TINGGI" - dilarang = ["rendah", "normal", "baik", "aman", "terkendali"] - message = ( - f"Mortalitas kumulatif {rate:.2f}% adalah TINGGI relatif standar harian CP 707 " - f"({std_mortality:.2f}%) pada hari ke-{day_age}." - ) + if is_end_cycle: + if rate > MORTALITY_THRESHOLDS["critical_pct"]: + status = "critical" + direction = "di_atas_standar" + severity_label = "SANGAT TINGGI" + dilarang = ["rendah", "normal", "baik", "aman", "terkendali", "sedikit"] + message = ( + f"Mortalitas kumulatif {rate:.2f}% adalah SANGAT TINGGI — melebihi batas kritis " + f"akhir siklus CP 707 (>7%)." + ) + elif rate >= MORTALITY_THRESHOLDS["normal_pct"]: + status = "warning" + direction = "di_atas_standar" + severity_label = "TINGGI" + dilarang = ["rendah", "normal", "baik", "aman", "terkendali", "sedikit"] + message = ( + f"Mortalitas kumulatif {rate:.2f}% adalah TINGGI (5-7%). " + "Standar akhir siklus CP 707 <5%." + ) + else: + status = "ok" + direction = "sesuai_standar" + severity_label = "normal/rendah" + dilarang = ["SANGAT TINGGI", "kritis"] + message = ( + f"Mortalitas kumulatif {rate:.2f}% normal/rendah — dalam batas akhir siklus CP 707 (<5%)." + ) else: - status = "ok" - direction = "sesuai_standar" if (std_mortality is None or rate <= std_mortality) else "di_atas_standar" - severity_label = "normal/rendah" - dilarang = ["SANGAT TINGGI", "kritis"] - message = ( - f"Mortalitas kumulatif {rate:.2f}% normal/rendah — dalam batas CP 707 (<5%)." - ) + if std_mortality is None: + return { + "status": "unknown", + "direction": "unknown", + "severity_label": None, + "actual_pct": rate, + "dilarang_kata": [], + "stdMortality": None, + "message": "Umur tidak tersedia untuk grading mortalitas harian CP 707.", + } + if rate > std_mortality: + status = "warning" + direction = "di_atas_standar" + severity_label = "TINGGI" + dilarang = ["rendah", "normal", "baik", "aman", "terkendali", "sedikit"] + message = ( + f"Mortalitas kumulatif {rate:.2f}% adalah TINGGI — melebihi standar harian CP 707 " + f"({std_mortality:.2f}%) pada hari ke-{day_age}." + ) + else: + status = "ok" + direction = "sesuai_standar" + severity_label = "normal/rendah" + dilarang = ["SANGAT TINGGI", "kritis"] + message = ( + f"Mortalitas kumulatif {rate:.2f}% normal/rendah — sesuai standar harian CP 707 " + f"({std_mortality:.2f}%) pada hari ke-{day_age}." + ) return { "status": status, @@ -1039,7 +1055,7 @@ def analyze_feed_balance( } -def build_book_reference_context(day_age: Any) -> str: +def build_book_reference_context(day_age: Any, *, is_end_cycle: bool = False) -> str: std_bw = get_bw_standard_by_day(day_age) std_fcr = get_fcr_standard_by_day(day_age) std_mortality = get_mortality_cum_std_by_day(day_age) @@ -1051,13 +1067,17 @@ def build_book_reference_context(day_age: Any) -> str: if day_age == 0 else (f"{std_bw} gram" if std_bw is not None else "N/A") ) + mortality_line = ( + "- Target mortalitas kumulatif akhir siklus: <5% normal, 5-7% tinggi (warning), >7% kritis (standar CP 707)" + if is_end_cycle + else f"- Target mortalitas kumulatif standar hari ke-{day_age}: {str(std_mortality) + '%' if std_mortality is not None else 'N/A'}" + ) return f""" === REFERENSI STANDAR BUKU CP 707 (SUMBER TUNGGAL - PT CHAROEN POKPHAND INDONESIA) === Umur ayam hari ke-{day_age}: - Target bobot badan: {bw_target_str} - Target FCR: {std_fcr if std_fcr is not None else 'N/A'} -- Target mortalitas kumulatif normal: <5% (standar CP 707) -- Target mortalitas kumulatif standar hari ke-{day_age}: {str(std_mortality) + '%' if std_mortality is not None else 'N/A'} +{mortality_line} - Target suhu kandang: {temp_std['temp_C']}°C - Target kelembapan: {temp_std['humidity_pct_min']}%-{temp_std['humidity_pct_max']}% - Target Efektif Temperatur (TET): {tet}°C @@ -1091,6 +1111,7 @@ def build_cp707_standard_block(context_data: dict[str, Any] | None) -> str: return "" day = int(day_f) + is_end_cycle = str(context_data.get("report_type") or "").strip().lower() == "end_cycle" ip = get_ip_standard_by_day(day) ip_range = get_ip_standard_range() target_bw_ctx = _resolve_target_bw(context_data, day) @@ -1107,16 +1128,24 @@ def build_cp707_standard_block(context_data: dict[str, Any] | None) -> str: lines = [ bw_line, f"- FCR standar hari ke-{day}: {str(fcr) + ' (rasio, tanpa satuan)' if fcr is not None else 'tidak tercantum di buku'}", - f"- Mortalitas kumulatif standar hari ke-{day}: {str(mort) + ' %' if mort is not None else 'tidak tercantum di buku'}", ] - if mort is not None: - hidup = round((100 - mort) * 100) / 100 + if is_end_cycle: lines.append( - f"- Persen hidup standar hari ke-{day}: {hidup} % " - "(turunan langsung dari mortalitas standar di atas — pakai angka ini, jangan menghitung sendiri)" + "- Mortalitas kumulatif standar akhir siklus CP 707: <5% normal, 5-7% tinggi (warning), >7% sangat tinggi (critical)" ) + lines.append("- Persen hidup standar akhir siklus CP 707: >95% normal") else: - lines.append(f"- Persen hidup standar hari ke-{day}: tidak tersedia") + lines.append( + f"- Mortalitas kumulatif standar hari ke-{day}: {str(mort) + ' %' if mort is not None else 'tidak tercantum di buku'}" + ) + if mort is not None: + hidup = round((100 - mort) * 100) / 100 + lines.append( + f"- Persen hidup standar hari ke-{day}: {hidup} % " + "(turunan langsung dari mortalitas standar di atas — pakai angka ini, jangan menghitung sendiri)" + ) + else: + lines.append(f"- Persen hidup standar hari ke-{day}: tidak tersedia") if ip is not None: lines.append(f"- IP/EEF standar hari ke-{day}: {ip} (indeks, TANPA satuan)") @@ -1340,7 +1369,15 @@ def analyze_with_cp707_standards(context_pack: dict[str, Any] | None, topic: str # Cumulative mortality grading if "mortality" in metrics_to_grade: mortality_rate = _resolve_mortality(pack) - result["analyses"]["mortality"] = analyze_mortality(mortality_rate, day_age) + is_end_cycle = ( + topic == "end_cycle" + or str(pack.get("report_type") or "").strip().lower() == "end_cycle" + ) + result["analyses"]["mortality"] = analyze_mortality( + mortality_rate, + day_age, + is_end_cycle=is_end_cycle, + ) # ADG grading (berat_ayam, dashboard, end_cycle) if "adg" in metrics_to_grade: diff --git a/backend/apps/operations/services/insight_service.py b/backend/apps/operations/services/insight_service.py index 16e290c..9043ac8 100644 --- a/backend/apps/operations/services/insight_service.py +++ b/backend/apps/operations/services/insight_service.py @@ -100,8 +100,8 @@ ATURAN MORTALITAS (WAJIB DIPATUHI — TIDAK BOLEH DILANGGAR): 1) mortalitas_hari_ini_ekor = jumlah EKOR mati hari ini (bukan persen). Jika nilainya 0, tulis mortalitas hari ini 0 ekor — JANGAN sebut "5%" atau "TINGGI". 2) mortalitas kumulatif % = hanya dari field *_persen / persen_hidup / [GRADED FACTS]. -- Ambang CP 707 untuk mortalitas KUMULATIF %: <5% normal; 5–7% TINGGI; >7% SANGAT TINGGI. - Ambang ini BUKAN untuk mortalitas hari ini. +- Untuk insight HARIAN / BERJALAN, bandingkan mortalitas kumulatif % HANYA terhadap standar harian CP 707 pada umur hari tersebut (lihat blok STANDAR CP 707 / [GRADED FACTS]). +- Ambang akhir siklus CP 707 (<5% normal; 5–7% TINGGI; >7% SANGAT TINGGI) HANYA digunakan pada laporan akhir siklus (end_cycle), BUKAN untuk insight harian dan BUKAN untuk mortalitas hari ini. - WAJIB: untuk mortalitas kumulatif, sebutkan severity_label dari [GRADED FACTS] PERSIS (contoh: "SANGAT TINGGI"). Jangan mengganti dengan sinonim lain. - DILARANG memakai kata di dilarang_kata pada blok mortality (mis. "rendah", "normal", @@ -241,7 +241,7 @@ 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"): + if topic == "dashboard" and not is_end_cycle 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 "-" @@ -640,7 +640,11 @@ 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": + is_end_cycle = ( + topic == "end_cycle" + or str(context.get("report_type") or "").strip().lower() == "end_cycle" + ) + if topic == "dashboard" and not is_end_cycle: from apps.operations.services.harvest_projection import evaluate_harvest_prediction graded["harvest_prediction"] = evaluate_harvest_prediction(context) return graded @@ -1074,7 +1078,11 @@ 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), + "harvest_prediction": ( + None + if getattr(row, "report_type", None) == "end_cycle" + else 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, @@ -1183,6 +1191,7 @@ def generate_insight( _notify(stage_cb, "retrieving") day = graded.get("hari_ke") day_display = day if day is not None else '?' + is_end_cycle = report_type == "end_cycle" if topic == "hitung_karung": standard_block = ( "=== STANDAR MANAJEMEN PAKAN DAN SALDO KARUNG (CP 707) ===\n" @@ -1194,9 +1203,10 @@ def generate_insight( "=== END STANDAR PAKAN ===" ) else: - standard_block = cp707.build_cp707_standard_block(ctx) or cp707.build_book_reference_context(day if day is not None else 1) - - is_end_cycle = report_type == "end_cycle" + standard_block = cp707.build_cp707_standard_block(ctx) or cp707.build_book_reference_context( + day if day is not None else 1, + is_end_cycle=is_end_cycle, + ) hypotheses: list[dict[str, Any]] = [] next_actions: list[dict[str, Any]] = [] masalah: list[str] = [] @@ -1382,7 +1392,9 @@ def generate_insight( "summary": summary, "alert": alert, "citations": encode_citations(citations), - "harvest_prediction": graded.get("harvest_prediction") if graded else None, + "harvest_prediction": ( + None if is_end_cycle else (graded.get("harvest_prediction") if graded else None) + ), }, ) return serialize_insight(row) diff --git a/backend/apps/operations/services/root_cause.py b/backend/apps/operations/services/root_cause.py index af926b8..ec2e0cd 100644 --- a/backend/apps/operations/services/root_cause.py +++ b/backend/apps/operations/services/root_cause.py @@ -351,7 +351,7 @@ _ACTION_TEMPLATES: dict[str, dict[str, str]] = { "litter_ventilasi": { "fase": PHASE_FINISHER, "aksi": ( - "Perbaiki manajemen litter dan ventilasi finisher; " + "Perbaiki manajemen litter dan ventilasi kandang; " "jaga kelembapan 50–70% dan amonia rendah." ), "metrik_pantau": "jumlah pembacaan RH/amonia out-of-range; mortalitas minggu 4+", @@ -558,10 +558,9 @@ def format_end_cycle_insight_text(payload: dict[str, Any]) -> str: for item in perbaikan: if not isinstance(item, dict): continue - fase = item.get("fase") or "" aksi = item.get("aksi") or "" metrik = item.get("metrik_pantau") or "" - lines.append(f"• [{fase}] {aksi}") + lines.append(f"• {aksi}") if metrik: lines.append(f" Pantau: {metrik}") lines.append("") diff --git a/backend/apps/operations/tests_insight_grading.py b/backend/apps/operations/tests_insight_grading.py index e8e717a..1af6882 100644 --- a/backend/apps/operations/tests_insight_grading.py +++ b/backend/apps/operations/tests_insight_grading.py @@ -136,16 +136,28 @@ class DuplicateKandangNameTests(SimpleTestCase): class MortalityWordingConsistencyTests(SimpleTestCase): def test_critical_mortality_has_explicit_severity_label(self): - result = cp707.analyze_mortality(9.49, 48) + result = cp707.analyze_mortality(9.49, 48, is_end_cycle=True) self.assertEqual(result["status"], "critical") self.assertEqual(result["severity_label"], "SANGAT TINGGI") self.assertEqual(result["actual_pct"], 9.49) self.assertIn("rendah", result["dilarang_kata"]) + def test_daily_mortality_grades_against_day_standard_without_50pct_tolerance(self): + ok_day25 = cp707.analyze_mortality(2.88, 25, is_end_cycle=False) + self.assertEqual(ok_day25["status"], "ok") + self.assertIn("2.88%", ok_day25["message"]) + self.assertNotIn("<5%", ok_day25["message"]) + + warn_day25 = cp707.analyze_mortality(3.00, 25, is_end_cycle=False) + self.assertEqual(warn_day25["status"], "warning") + self.assertEqual(warn_day25["severity_label"], "TINGGI") + self.assertIn("2.88%", warn_day25["message"]) + self.assertNotIn("<5%", warn_day25["message"]) + def test_enforce_rewrites_rendah_when_mortality_is_critical(self): graded = { "analyses": { - "mortality": cp707.analyze_mortality(9.49, 48), + "mortality": cp707.analyze_mortality(9.49, 48, is_end_cycle=True), } } parsed = { diff --git a/backend/apps/operations/tests_insight_quality.py b/backend/apps/operations/tests_insight_quality.py index d04039e..281d66d 100644 --- a/backend/apps/operations/tests_insight_quality.py +++ b/backend/apps/operations/tests_insight_quality.py @@ -844,6 +844,29 @@ class HarvestPredictionIntegrationTests(TestCase): self.assertEqual(serialized["harvest_prediction"]["optimal_harvest_day"], 33) self.assertEqual(serialized["harvest_prediction"]["projected_bw_gram"], 1950.0) + def test_end_cycle_excludes_harvest_prediction(self): + ctx = { + "kandangName": "Kandang 4", + "hari_ke": 48, + "report_type": "end_cycle", + "bobot_avg_gram": 2100.0, + "fcr_terakhir": 1.65, + } + graded = insight_service.grade_context(ctx, topic="dashboard") + self.assertNotIn("harvest_prediction", graded) + + prompt = insight_service.build_insight_user_prompt( + topic="dashboard", + kandang_name="Kandang 4", + report_type="end_cycle", + report_period="end", + context=ctx, + graded={"analyses": {}, "harvest_prediction": {"optimal_harvest_day": 33}}, + is_end_cycle=True, + ) + self.assertNotIn("[PROYEKSI WAKTU PANEN TERBAIK (DETERMINISTIK CP 707)]", prompt) + self.assertNotIn("INSTRUKSI PANEN UNTUK LLM", prompt) + if __name__ == "__main__": import unittest diff --git a/components/AiInsightCard.tsx b/components/AiInsightCard.tsx index e7250f0..c31acba 100644 --- a/components/AiInsightCard.tsx +++ b/components/AiInsightCard.tsx @@ -24,6 +24,7 @@ import { scopeDashboardInsightMetrics, } from '../utils/insightContextBuilders.ts'; import { getCobbStandardForDay } from '../utils/insightHelpers.ts'; +import { getMortalityCumStandardByDay } from '../utils/cp707EnvStandards.ts'; import { parseAiResult, type AiResult } from '../utils/insightParse.ts'; import { formatRatio } from '../utils/format.ts'; import { @@ -619,12 +620,19 @@ export const AiInsightCard: React.FC = ({ return 'critical'; })(); + const mortalityStandard = + reportType === 'end_cycle' ? null : getMortalityCumStandardByDay(gradeDay); + const mortalityStatus = ((): InsightStatus => { const pct = scopedMetrics?.mortalitas_kumulatif_persen ?? null; if (pct === null) return 'unknown'; - if (pct < 5) return 'ok'; - if (pct <= 7) return 'warning'; - return 'critical'; + if (reportType === 'end_cycle') { + if (pct < 5) return 'ok'; + if (pct <= 7) return 'warning'; + return 'critical'; + } + if (mortalityStandard === null) return 'unknown'; + return pct <= mortalityStandard ? 'ok' : 'warning'; })(); const weightTarget = @@ -787,11 +795,17 @@ export const AiInsightCard: React.FC = ({ deltaLabel={ mortVal == null ? null - : mortalityStatus === 'ok' - ? '✓ normal <5%' - : mortalityStatus === 'warning' - ? '↑ melebihi standar <5%' - : '↑ tinggi, standar <5%' + : reportType === 'end_cycle' + ? mortalityStatus === 'ok' + ? '✓ normal <5%' + : mortalityStatus === 'warning' + ? '↑ melebihi standar <5%' + : '↑ tinggi, standar <5%' + : mortalityStandard == null + ? null + : mortalityStatus === 'ok' + ? `✓ sesuai standar ≤${mortalityStandard.toFixed(2)}%` + : `↑ melebihi standar ${mortalityStandard.toFixed(2)}%` } /> = ({ {item.confidence} ) : null} - {item.fase ? ( - - {item.fase} - - ) : null} {item.bukti.length > 0 ? (
    @@ -1108,10 +1117,7 @@ export const AiInsightCard: React.FC = ({ key={`${item.id ?? item.aksi}-${index}`} className="rounded-lg border border-blue-200/70 bg-white/90 p-3.5 shadow-xs" > -

    - {item.fase} -

    -

    {item.aksi}

    +

    {item.aksi}

    {item.metrik_pantau ? (

    Pantau: {item.metrik_pantau} diff --git a/components/shared/PageAiInsight.tsx b/components/shared/PageAiInsight.tsx index cdf5ccd..96d67d2 100644 --- a/components/shared/PageAiInsight.tsx +++ b/components/shared/PageAiInsight.tsx @@ -19,6 +19,7 @@ import type { } from '../../types/api.ts'; import { formatNumber, formatRatio } from '../../utils/format.ts'; import { getCobbStandardForDay } from '../../utils/insightHelpers.ts'; +import { getMortalityCumStandardByDay } from '../../utils/cp707EnvStandards.ts'; import { parseAiResult, type AiResult } from '../../utils/insightParse.ts'; import { scopeContextToTimeframe, @@ -465,23 +466,24 @@ export const PageAiInsight: React.FC = ({ if (actual === null) return null; const awal = n(displayContext.populasi_awal_ekor); const mortPct = n(displayContext.mortalitas_persen); + const mortStd = getMortalityCumStandardByDay(effectiveDay ?? currentDay); return { label: 'Populasi Kini', value: Math.round(actual).toLocaleString('id-ID'), unit: 'ekor', context: awal === null ? null : `Populasi awal: ${Math.round(awal).toLocaleString('id-ID')} ekor`, - status: (mortPct === null + status: (mortPct === null || mortStd === null ? 'unknown' - : mortPct < 5 + : mortPct <= mortStd ? 'ok' - : mortPct <= 7 - ? 'warning' - : 'critical') as InsightStatus, + : 'warning') as InsightStatus, deltaLabel: mortPct === null ? null - : `Mortalitas ${mortPct.toLocaleString('id-ID', { maximumFractionDigits: 2 })}%`, + : mortStd !== null + ? `Mortalitas ${mortPct.toLocaleString('id-ID', { maximumFractionDigits: 2 })}% (std ${mortStd.toLocaleString('id-ID', { maximumFractionDigits: 2 })}%)` + : `Mortalitas ${mortPct.toLocaleString('id-ID', { maximumFractionDigits: 2 })}%`, }; } diff --git a/utils/cp707EnvStandards.ts b/utils/cp707EnvStandards.ts index ce2c737..0e7b8b9 100644 --- a/utils/cp707EnvStandards.ts +++ b/utils/cp707EnvStandards.ts @@ -67,6 +67,60 @@ export const getTempStandardByDay = (dayAge: number | null | undefined): number return row ? row.temp_C : null; }; +/** Standar mortalitas kumulatif harian CP 707 (Lampiran 2) — hari 1..37. */ +const MORTALITY_CUM_STANDARD_BY_DAY: Record = { + 1: 0.4, + 2: 0.5, + 3: 0.6, + 4: 0.7, + 5: 0.8, + 6: 0.9, + 7: 1.0, + 8: 1.1, + 9: 1.2, + 10: 1.3, + 11: 1.4, + 12: 1.5, + 13: 1.6, + 14: 1.7, + 15: 1.8, + 16: 1.9, + 17: 2.0, + 18: 2.1, + 19: 2.2, + 20: 2.3, + 21: 2.4, + 22: 2.52, + 23: 2.64, + 24: 2.76, + 25: 2.88, + 26: 3.0, + 27: 3.12, + 28: 3.25, + 29: 3.38, + 30: 3.52, + 31: 3.66, + 32: 3.8, + 33: 3.95, + 34: 4.1, + 35: 4.25, + 36: 4.45, + 37: 4.65, +}; + +/** + * Standar mortalitas kumulatif (%) untuk umur hari tertentu (sinkron dengan + * `get_mortality_cum_std_by_day` di `cp707_knowledge.py`). + */ +export const getMortalityCumStandardByDay = (dayAge: number | null | undefined): number | null => { + if (typeof dayAge !== 'number' || !Number.isFinite(dayAge) || dayAge < 0) return null; + const day = Math.trunc(dayAge); + if (day === 0) return 0.4; + if (day in MORTALITY_CUM_STANDARD_BY_DAY) return MORTALITY_CUM_STANDARD_BY_DAY[day]!; + if (day > 37) return Math.round((4.65 + (day - 37) * 0.1) * 100) / 100; + return null; +}; + /** * Number out of a display-formatted reading. *