Files
dashboard/components/counting/ChickenCountingAiInsight.tsx
Alberto-Audrix 01b3178bc6
CI / lint-and-test (push) Canceled after 0s
fix ai insight
2026-08-28 14:22:33 +07:00

932 lines
41 KiB
TypeScript

import React, { useState, useCallback, useEffect, useRef } from 'react';
import { Sparkles, RefreshCw, AlertTriangle, CheckCircle, Download } from 'lucide-react';
import { apiClient } from '../../services/apiService.ts';
import { parseAiResult, type AiResult } from '../../utils/insightParse.ts';
import { getDiagnostikBundle, scopeDiagnostikToDay } from '../../utils/insightEvidence.ts';
import { DATA_UPDATE_NOTICE, DATA_UPDATE_NOTICE_DETAIL } from '../../utils/insightDataSchedule.ts';
import { useAppContext } from '../../context/AppContext.tsx';
import InsightTrendChart from '../shared/InsightTrendChart.tsx';
import { exportCardToPdf } from '../../utils/pdfExport.ts';
import { HeroFigure, type InsightStatus } from '../shared/InsightStatTiles.tsx';
import PdfReportHeader, {
buildPdfFilename,
describeDataDates,
describeKandangScope,
describeTimeframePeriod,
isoDataDates,
parseDayRangeLabel,
} from '../shared/PdfReportHeader.tsx';
interface KandangInsight {
name: string;
docIn: number;
currentPopulation: number;
mortalityTotal: number;
mortalityRate: number;
/** Harvested alive. Absent from this row is why the per-coop line read as if
* the whole population drop were deaths. */
panen?: number;
}
/** One day's mortality/harvest row from `/api/mortality/:cycleId`. */
interface MortalityDayRow {
day?: number | null;
mortalityCount?: number | null;
afkir?: number | null;
panen?: number | null;
beratPanen?: number | null;
}
/**
* The rows belonging to the selected period.
*
* Deaths and culls are flows: "Jumlah Kematian" under a Mingguan heading must
* mean the deaths of that week, not the cycle total. The window is matched on
* each row's own `day` so a day with no record drops out instead of sliding it.
*/
const sliceRowsByTimeframe = (
rows: MortalityDayRow[],
timeframe: 'harian' | 'mingguan',
selectedDay: number | null = null
) => {
const dayOf = (row: MortalityDayRow) =>
typeof row.day === 'number' && Number.isFinite(row.day) ? row.day : null;
const days = rows.map(dayOf).filter((day): day is number => day !== null);
if (days.length === 0) return { window: rows, label: 'seluruh data' };
const lastDay = Math.max(...days);
if (timeframe === 'harian') {
// Picking a day means "the cycle so far, up to that day" — day 0 through
// day N. Deaths and culls are then the running total, which is what the
// cumulative mortality headline above the card already reports.
if (selectedDay !== null) {
const window = rows.filter((row) => (dayOf(row) ?? Infinity) <= selectedDay);
const windowDays = window.map(dayOf).filter((d): d is number => d !== null);
return {
window,
label:
windowDays.length === 0
? `hari ke-${selectedDay}`
: `hari ke-${Math.min(...windowDays)} s/d ke-${selectedDay}`,
};
}
return {
window: rows.filter((row) => dayOf(row) === lastDay),
label: `hari ke-${lastDay}`,
};
}
const firstDay = Math.max(Math.min(...days), lastDay - 6);
return {
window: rows.filter((row) => {
const day = dayOf(row);
return day !== null && day >= firstDay && day <= lastDay;
}),
label: `hari ke-${firstDay} s/d ke-${lastDay}`,
};
};
/**
* Real departures, split by cause.
*
* `populasi awal - populasi kini` was being reported as "kematian+afkir". That
* counts every harvested bird as dead: this coop shipped 22.523 birds and the
* insight announced "mortalitas 100%, seluruh populasi mati". Deaths, culls and
* harvest each have their own column — read them instead of inferring.
*/
const summariseDepartures = (rows: MortalityDayRow[], docIn: number) => {
const sum = (f: keyof MortalityDayRow) =>
rows.reduce((t, r) => {
const v = r[f];
return t + (typeof v === 'number' && Number.isFinite(v) ? v : 0);
}, 0);
const mati = sum('mortalityCount');
const afkir = sum('afkir');
const panen = sum('panen');
const beratPanen = sum('beratPanen');
const mortalityTotal = mati + afkir;
return {
mati,
afkir,
panen,
beratPanen,
mortalityTotal,
// A rate needs a denominator; without one it is unknown, not zero.
mortalityRate: docIn > 0 ? (mortalityTotal / docIn) * 100 : null,
saldo: Math.max(0, docIn - mortalityTotal - panen),
adaData: rows.length > 0,
};
};
interface PopulationPoint {
date: string;
population: number;
}
export interface ChickenCountingInsightProps {
cycleId: string;
currentDay: number;
totalDays: number;
totalInitialPopulation: number;
populationTrend: PopulationPoint[];
kandangInsights: KandangInsight[];
/**
* Which coop the figures are scoped to; null means all coops combined.
* The mortality ledger must be read for the same scope as
* `totalInitialPopulation`, or the rate is computed against the wrong
* denominator.
*/
kandangId?: number | null;
}
const CC_FOCUSES = [
'Tren mortalitas harian dan dampaknya terhadap populasi akhir',
'Distribusi ayam di berbagai area/kamera (penumpukan)',
'Perbandingan populasi aktual dengan target DOC In',
'Deteksi dini potensi wabah penyakit dari lonjakan mortalitas',
'Evaluasi efektivitas afkir selektif vs kematian alami',
'Proyeksi sisa populasi layak panen',
'Evaluasi tingkat kepadatan (density) vs kapasitas kandang',
];
/**
* @param periodDeparture Flows (deaths, culls, harvest) INSIDE the selected
* window. These are what "Harian" and "Mingguan" are supposed to change.
* @param departures The same flows for the whole cycle. Kept separate because
* the cumulative mortality rate and the saldo are stocks — they must count
* every departure since day 1, and grading a week's own deaths against the
* CP 707 *cumulative* standard would understate the flock's real condition.
*
* Both blocks go into the prompt under explicit headings. Previously only the
* cycle-wide figures were sent, under a line claiming the data was already
* limited to the selected range — so "Harian" reported the entire cycle's
* deaths and harvest as if they had happened today.
*/
const buildPrompt = (
props: ChickenCountingInsightProps,
timeframe: 'harian' | 'mingguan',
departures: ReturnType<typeof summariseDepartures>,
periodDeparture: ReturnType<typeof summariseDepartures>,
periodRangeLabel: string
): string => {
const { currentDay, totalDays, totalInitialPopulation, populationTrend, kandangInsights } = props;
const selectedFocus = CC_FOCUSES[Math.floor(Math.random() * CC_FOCUSES.length)];
const latestPop =
populationTrend[populationTrend.length - 1]?.population ?? totalInitialPopulation;
// Harian looks at today only; Mingguan at the 7-day window ending today.
// Previously both modes were handed the same 7-day trend, so the toggle
// barely changed the answer.
//
// The window is matched on each point's own DATE, not its array position: a
// missing day would otherwise slide the window silently, so "7 hari terakhir"
// could quietly cover days 35-48. A day with no record must drop out of the
// window, not shift it.
const dated = populationTrend
.map((p) => ({ ...p, ts: new Date(p.date).setHours(0, 0, 0, 0) }))
.filter((p) => Number.isFinite(p.ts))
.sort((a, b) => a.ts - b.ts);
const latestTs = dated[dated.length - 1]?.ts ?? null;
const spanDays = timeframe === 'harian' ? 1 : 7;
const scopedPops =
latestTs === null
? []
: dated.filter((p) => p.ts > latestTs - spanDays * 86400000 && p.ts <= latestTs);
const recentPops = scopedPops.map((p) => p.population);
const trendLabel =
timeframe === 'harian' ? 'Populasi hari ini' : 'Trend populasi (7 hari terakhir)';
const trendStr = recentPops.length > 0 ? recentPops.join(' → ') : 'belum ada data trend';
// `periodRangeLabel` already names the sliced window ("hari ke-20"), so it is
// the authority here. Hardcoding `currentDay` made a report for a past day
// announce itself as "HARI INI", which the model then repeated as fact.
const periodLabel =
timeframe === 'harian'
? periodRangeLabel.includes(`ke-${currentDay}`)
? `HARI INI SAJA (${periodRangeLabel})`
: `${periodRangeLabel.toUpperCase()} SAJA — BUKAN hari ini (hari ini hari ke-${currentDay})`
: `7 HARI TERAKHIR (hari ke-${Math.max(1, currentDay - 6)} sampai hari ke-${currentDay})`;
const kandangStr =
kandangInsights.length > 0
? kandangInsights
.map(
(k) =>
`- ${k.name}: DOC=${k.docIn.toLocaleString()}, populasi_kini=${k.currentPopulation.toLocaleString()}, mati+afkir=${k.mortalityTotal.toLocaleString()}, mortalitas=${k.mortalityRate.toFixed(2)}%, dipanen=${
typeof k.panen === 'number'
? k.panen.toLocaleString() + ' ekor'
: 'data tidak tersedia'
}`
)
.join('\n')
: '- Data per kandang belum tersedia (backend offline). Gunakan data total untuk analisis.';
return `Anda adalah dokter hewan dan manajer peternakan ayam broiler berpengalaman.
Analisis data hitung ayam berikut dan buat AI Insight yang MUDAH DIPAHAMI, PROFESIONAL, dan ACTIONABLE bagi peternak.
Jika ada data yang belum tersedia, tetap berikan insight dan rekomendasi berdasarkan data yang ada.
IDENTITAS SIKLUS:
- Hari ke: ${currentDay} dari total ${totalDays} hari
- Populasi awal (DOC in): ${totalInitialPopulation.toLocaleString()} ekor
A. DATA PERIODE YANG DIANALISIS (${periodRangeLabel}) — angka DI DALAM rentang ini saja:
- Kematian (mati) pada periode ini: ${periodDeparture.adaData ? periodDeparture.mati.toLocaleString() + ' ekor' : 'data tidak tersedia'}
- Afkir pada periode ini: ${periodDeparture.adaData ? periodDeparture.afkir.toLocaleString() + ' ekor' : 'data tidak tersedia'}
- Kematian+afkir pada periode ini: ${periodDeparture.adaData ? periodDeparture.mortalityTotal.toLocaleString() + ' ekor' : 'data tidak tersedia'}
- Dipanen pada periode ini: ${periodDeparture.adaData ? periodDeparture.panen.toLocaleString() + ' ekor' : 'data tidak tersedia'}
- Bobot panen pada periode ini: ${periodDeparture.adaData && periodDeparture.beratPanen > 0 ? periodDeparture.beratPanen.toLocaleString() + ' kg' : 'data tidak tersedia'}
B. DATA KUMULATIF SEJAK HARI KE-1 — konteks, BUKAN angka periode ini:
- Total kematian+afkir kumulatif: ${departures.adaData ? departures.mortalityTotal.toLocaleString() + ' ekor' : 'data tidak tersedia'}
- Tingkat mortalitas kumulatif: ${departures.mortalityRate === null ? 'data tidak tersedia' : departures.mortalityRate.toFixed(2) + '%'}
- Total sudah dipanen: ${departures.adaData ? departures.panen.toLocaleString() + ' ekor' : 'data tidak tersedia'}
- Total bobot panen: ${departures.adaData && departures.beratPanen > 0 ? departures.beratPanen.toLocaleString() + ' kg' : 'data tidak tersedia'}
- Saldo ayam di kandang: ${departures.adaData ? departures.saldo.toLocaleString() + ' ekor' : 'data tidak tersedia'}
- ${trendLabel}: ${trendStr}
PENTING — jangan tertukar antara blok A dan blok B:
Kalau Anda menyebut kematian, afkir, atau panen "pada ${periodRangeLabel}", ambil dari
blok A. Angka blok B adalah total sejak hari ke-1 — hanya boleh disebut dengan kata
"kumulatif" atau "sejak awal siklus". DILARANG menyebut angka blok B seolah terjadi
pada periode ini.
DILARANG memakai kata "total", "keseluruhan", atau "sepanjang siklus" untuk angka blok A —
itu angka SATU periode. Setiap angka blok A wajib Anda tulis bersama keterangan
periodenya, contoh: "dipanen 822 ekor pada ${periodRangeLabel}". Sebaliknya, setiap angka
blok B wajib ditulis dengan kata "kumulatif".
PENTING — jangan salah membaca penurunan populasi:
Populasi turun karena DUA sebab yang berbeda: kematian/afkir DAN panen. Ayam yang
dipanen TIDAK mati. Populasi yang tinggal ${latestPop.toLocaleString()} ekor bukan berarti
sisanya mati — pakai angka "Total kematian+afkir kumulatif" dan "Tingkat mortalitas
kumulatif" apa adanya, dan JANGAN menghitung mortalitas dari selisih populasi.
Satuan: ekor untuk jumlah, kg untuk bobot, persen untuk tingkat mortalitas. Jangan menukarnya.
ATURAN ANGKA (WAJIB DIPATUHI):
Setiap angka yang Anda tulis HARUS disalin apa adanya dari blok A, blok B, atau DATA PER
KANDANG di atas. DILARANG menghitung sendiri: jangan membagi bobot panen dengan jumlah
ekor, jangan menjumlahkan atau mengurangkan antar baris, jangan mengubah total menjadi
rata-rata per hari, dan jangan menurunkan persentase yang tidak tertulis di atas.
Kalau sebuah angka tidak ada di data, tulis "data tidak tersedia".
DATA PER KANDANG (angka KUMULATIF sejak hari ke-1, bukan periode ini):
${kandangStr}
PEDOMAN MORTALITAS:
Nilai statusnya memakai "Tingkat mortalitas kumulatif" dari blok B (bukan angka periode
di blok A), karena standar CP 707 di bawah ini juga kumulatif.
Gunakan angka "Mortalitas kumulatif standar" pada blok STANDAR CP 707 di atas sebagai
pembanding — standar itu berbeda tiap umur, jadi DILARANG memakai ambang tetap.
- Di bawah standar hari ini: NORMAL (ok)
- Sampai 1,5x standar hari ini: PERLU PERHATIAN (warning)
- Di atas 1,5x standar hari ini: KRITIS, perlu tindakan segera (critical)
Konteks & Aturan Variasi:
Fokus utama analisis Anda hari ini adalah: "${selectedFocus}".
RENTANG WAKTU ANALISIS: ${periodLabel}.
Blok A sudah dibatasi pada rentang tersebut; blok B dan DATA PER KANDANG sengaja kumulatif sebagai konteks. Jadikan blok A sebagai pokok analisis, jangan menyimpulkan tren di luar rentang tersebut, dan jangan mengarang angka dari hari lain.
Jadikan ini sebagai sudut pandang utama analisis. Jangan sebutkan nama fokus secara eksplisit di hasil akhir. Dilarang keras berhalusinasi atau menambahkan angka fiktif.
TUGAS UTAMA — JELASKAN SEBABNYA:
Menyebut "mortalitas 9,1% di atas standar" saja TIDAK diterima. Anda WAJIB menjelaskan
KENAPA angkanya bisa setinggi itu, dengan menunjuk hari, angka, dan metrik lain yang
bergerak lebih dulu. Gunakan blok TEMUAN TERUKUR DARI DATA (jika ada di bawah) sebagai
sumber bukti — angka di blok itu sudah dihitung sistem dan boleh dikutip apa adanya.
Ikuti aturan analisis sebab-akibat pada system prompt: setiap sebab diberi label
[Terbukti dari data] atau [Dugaan — perlu dicek: ...], dan sebutkan terus terang metrik
yang datanya tidak tersedia.
INSTRUKSI OUTPUT:
Kembalikan HANYA satu objek JSON valid tanpa markdown, tanpa komentar, tanpa teks tambahan di luar JSON.
Format JSON yang harus dikembalikan:
{
"kesimpulan": "2-4 kalimat: metrik utama + angkanya + standar CP 707 pembandingnya + seberapa jauh menyimpang + sebab utamanya.",
"insight": "Ikuti format PENYEBAB / BELUM DAPAT DIPASTIKAN / TINDAKAN, pisahkan baris dengan baris baru."
}`;
};
export const ChickenCountingAiInsight: React.FC<ChickenCountingInsightProps> = (props) => {
const appContext = useAppContext();
const { cycleData } = appContext;
// Read the mortality ledger directly. Callers pass different prop subsets
// (one omits cycleId and kandangInsights entirely), so deriving the figures
// here keeps them correct regardless of which page mounts this card.
const [mortalityRows, setMortalityRows] = useState<MortalityDayRow[]>([]);
const activeCycleId = props.cycleId || cycleData?.id;
useEffect(() => {
let cancelled = false;
if (!activeCycleId) {
setMortalityRows([]);
return;
}
apiClient
.getMortalityRecords(activeCycleId, props.kandangId ?? undefined)
.then((rows: unknown) => {
if (!cancelled) setMortalityRows(Array.isArray(rows) ? (rows as MortalityDayRow[]) : []);
})
.catch((err: unknown) => {
console.error('❌ Gagal memuat catatan mortalitas untuk insight hitung ayam:', err);
if (!cancelled) setMortalityRows([]);
});
return () => {
cancelled = true;
};
}, [activeCycleId, props.kandangId]);
const [result, setResult] = useState<AiResult | null>(null);
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
/**
* The weekly view was removed: the day picker covers the same ground and more,
* since picking a day already reports the cycle cumulatively up to it. Kept as
* a typed constant so the slicing helper and the PDF labels keep their shape.
*/
const timeframe: 'harian' | 'mingguan' = 'harian';
// Which cycle day the daily view describes; null = the newest day in the data,
// which is how this card behaved before the picker existed.
const [selectedDay, setSelectedDay] = useState<number | null>(null);
/**
* Days the mortality history actually contains. Offering a day with no record
* would slice the window to nothing and report "no data" for a day the user
* had no reason to think was empty.
*/
const availableDays = React.useMemo(() => {
const days = new Set<number>();
for (const row of mortalityRows) {
if (typeof row.day === 'number' && Number.isFinite(row.day)) days.add(row.day);
}
return [...days].sort((a, b) => a - b);
}, [mortalityRows]);
const activeDay =
timeframe === 'harian' && selectedDay !== null && availableDays.includes(selectedDay)
? selectedDay
: null;
const inFlightRef = useRef(false);
const hasGeneratedRef = useRef(false);
/**
* Hasil yang sedang tampil, di ref supaya `generate` bisa membacanya tanpa
* ikut jadi dependensi useCallback. Dikirim ke backend saat operator menekan
* generate lagi, sebagai penanda bahwa ini permintaan ULANG: datanya sama,
* yang diminta sudut pandang dan tindakan yang berbeda.
*/
const lastResultRef = useRef<AiResult | null>(null);
const lastCacheKeyRef = useRef<string | null>(null);
const pdfRef = useRef<HTMLDivElement>(null);
useEffect(() => {
lastResultRef.current = result;
}, [result]);
// The day belongs in the key: without it day 5 and day 12 share a cache entry
// and switching days shows the previous day's report.
const cacheKey = `cc-insight-${props.cycleId}-${props.currentDay}-${timeframe}${
activeDay === null ? '' : `-h${activeDay}`
}`;
// The scope the user is currently asking for, so a request dropped because
// another was in flight can be re-run once that one finishes.
// Flow figures for the selected period. `departures` stays cycle-wide because
// the saldo is a stock: it must count every departure up to now, not just the
// ones inside the window.
/**
* Cycle-to-date figures, capped at the day being reported on.
*
* Mortality rate and saldo are stocks, so they count every departure since
* day 1 — but "since day 1" must end at the day the report describes. Left
* uncapped, a "Hari 20" card headlined the day-48 cumulative rate (9,91%)
* beside its own day-20 rows, which is the contradiction the day picker was
* meant to remove.
*/
const cumulativeRows = React.useMemo(
() =>
activeDay === null
? mortalityRows
: mortalityRows.filter(
(row) => typeof row.day === 'number' && Number.isFinite(row.day) && row.day <= activeDay
),
[mortalityRows, activeDay]
);
const departures = summariseDepartures(cumulativeRows, props.totalInitialPopulation);
const period = React.useMemo(
() => sliceRowsByTimeframe(mortalityRows, timeframe, activeDay),
[mortalityRows, timeframe, activeDay]
);
const periodDepartures = summariseDepartures(period.window, props.totalInitialPopulation);
/**
* The one figure this card is judged on, matching the hero the topic cards
* carry. Cumulative mortality rather than the balance, because it is the
* figure with a CP 707 standard to compare against — a hero without a
* comparison is just a big number.
*/
const heroSpec = React.useMemo(() => {
const rate = departures.mortalityRate;
if (rate === null) return null;
const status: InsightStatus = rate < 5 ? 'ok' : rate <= 7 ? 'warning' : 'critical';
return {
value: rate.toFixed(2),
status,
context: `${departures.mortalityTotal.toLocaleString('id-ID')} ekor dari ${props.totalInitialPopulation.toLocaleString('id-ID')} ekor DOC`,
};
}, [departures.mortalityRate, departures.mortalityTotal, props.totalInitialPopulation]);
// InsightTrendChart plots against cycle day, but `point.date` is a localised
// display label ("22 Mei"), not a parseable date — and it parses
// INCONSISTENTLY: "Mei" fails while "07 Jul" silently becomes July 2001,
// which put half the points at day -9084. So index the points instead, and
// anchor the last one to `currentDay` so the shaded window lines up with the
// day the insight text actually discusses.
const chartRows = React.useMemo(() => {
const points = props.populationTrend ?? [];
const all = points.map((point, index) => ({
hari: props.currentDay - (points.length - 1 - index),
populasi: point.population,
}));
// Cut the line at the chosen day: plotting past it would show days the
// figures below deliberately exclude.
return activeDay === null ? all : all.filter((row) => row.hari <= activeDay);
}, [props.populationTrend, props.currentDay, activeDay]);
// The insight text covers one day (harian) or the trailing week (mingguan);
// shade exactly that span so the reader sees which part the words describe.
const chartHighlight = React.useMemo(() => {
if (chartRows.length === 0) return null;
const days = chartRows.map((row) => row.hari);
// The band covers the whole analysed window, which for a picked day runs
// from the start of the cycle to that day.
const lastDay = timeframe === 'harian' && activeDay !== null ? activeDay : Math.max(...days);
const firstDay =
timeframe === 'harian'
? activeDay !== null
? Math.min(...days)
: lastDay
: Math.max(Math.min(...days), lastDay - 6);
return { firstDay, lastDay };
}, [chartRows, timeframe, activeDay]);
const downloadPdf = async () => {
if (!result || !pdfRef.current) return;
try {
// Coop and period included: two coops on the same day used to produce
// one identical filename and overwrite each other.
const { fromDay, toDay } = parseDayRangeLabel(period.label);
const filename = buildPdfFilename({
reportName: 'Hitung-Ayam',
area: appContext.selectedArea || 'Sukawarna',
kandangLabel: describeKandangScope(appContext.kandangs, props.kandangId ?? null),
// One file per day instead of every day overwriting "…-Harian.pdf".
periodSlug:
timeframe === 'harian'
? activeDay === null
? 'Harian'
: `Harian-Hari-${activeDay}`
: 'Mingguan',
isoDates: isoDataDates(cycleData?.startDate, fromDay, toDay),
});
await exportCardToPdf(pdfRef.current, filename);
} catch (error) {
console.error('Failed to generate PDF:', error);
}
};
const generate = useCallback(
async (force = false) => {
if (inFlightRef.current) return;
// Minimal data check
if (!props.cycleId) return;
lastCacheKeyRef.current = cacheKey;
if (!force) {
try {
const cached = sessionStorage.getItem(cacheKey);
if (cached) {
const parsed = parseAiResult(cached);
if (parsed) {
setResult(parsed);
hasGeneratedRef.current = true;
return;
}
}
} catch {
// sessionStorage might be unavailable
}
}
inFlightRef.current = true;
setLoading(true);
setError(null);
try {
const prompt = buildPrompt(props, timeframe, departures, periodDepartures, period.label);
const system_prompt =
'Anda adalah manajer peternakan ayam broiler CP 707. Analisis HANYA berdasarkan standar buku CP 707. Tugas utama Anda adalah MENJELASKAN PENYEBAB dari setiap angka yang menyimpang dari standar, bukan sekadar melaporkan angkanya. Kembalikan HANYA objek JSON valid. Dilarang memberikan teks di luar JSON.';
// Race antara LM Studio dan timeout 20 menit (sama dengan backend)
// contextData carries the cycle day so the backend can inject the CP 707
// standard for THIS day; without it the prompt has no book figure to
// compare against and the model falls back to guessing one.
// Why the mortality is what it is cannot be answered from the counting
// ledger alone. The bundle adds the other domains' daily series — suhu,
// pakan, bobot — so the backend can point at the days that explain the
// deaths instead of only restating the rate. Cached per cycle-day and
// shared with every other insight card in the session.
const cageUuid =
props.kandangId === null || props.kandangId === undefined
? null
: ((appContext.kandangs ?? []).find((item: any) => item?.id === props.kandangId)
?.cageUuid ?? null);
const diagnostik = scopeDiagnostikToDay(
await getDiagnostikBundle({
cycleId: props.cycleId,
cageUuid,
kandangId: props.kandangId ?? null,
startDate: cycleData?.startDate,
currentDay: props.currentDay,
totalDays: props.totalDays,
populasiAwal: props.totalInitialPopulation || null,
keseragaman: appContext.weightStats?.uniformity?.value ?? null,
apiMode: appContext.apiMode,
// This page holds the authoritative ledger — deaths, culls and
// harvest in separate columns — so it passes it rather than letting
// the bundle fall back to the KPI feed's deaths-only figure.
mortalityRows,
}),
activeDay ?? props.currentDay
);
const fetchCall = apiClient.proxyLmStudio(
prompt,
system_prompt,
0.2,
'hitung_ayam',
'',
{
// The day the report is ABOUT, not the day the cycle has reached.
//
// The backend builds its "STANDAR CP 707 UNTUK HARI INI" block from
// this field (routes/aiInsights.js → buildCp707StandardBlock), so
// sending currentDay while the picker was on an earlier day handed
// the model day-48 book figures — bobot standar 2.500 g — to judge
// day-20 data against. The evidence block beside it was already
// scoped to the picked day, so the two halves of the same prompt
// disagreed about which day was being reported on.
hari_ke: activeDay ?? props.currentDay,
...(diagnostik ? { diagnostik } : {}),
},
// Hanya saat operator menekan tombol lagi padahal sudah ada hasil di
// layar — itulah penanda permintaan ULANG. Pemuatan biasa (`force`
// false) tidak boleh ikut meminta variasi.
force && lastResultRef.current
? `${lastResultRef.current.kesimpulan}\n\n${lastResultRef.current.insight}`
: null
);
const timeout = new Promise<never>((_, reject) =>
setTimeout(() => reject(new Error('LM Studio timeout setelah 20 menit.')), 1200000)
);
const json = await Promise.race([fetchCall, timeout]);
const text = json.response ?? '';
const parsed = parseAiResult(text);
if (!parsed) throw new Error('Format respons LM Studio tidak valid. Coba lagi.');
if (result && JSON.stringify(parsed) === JSON.stringify(result)) {
// Dulu pesan ini berbunyi "Data belum diperbarui", padahal penyebab
// sebenarnya adalah sampling: tanpa seed acak dan pada temperature
// 0.1, prompt yang sama selalu menghasilkan teks yang sama. Keduanya
// sudah diperbaiki, jadi kalau ini masih terjadi penyebabnya memang
// di model — bukan di datanya.
throw new Error(
'Model mengembalikan analisis yang sama persis dengan sebelumnya. Coba tekan sekali lagi.'
);
}
setResult(parsed);
hasGeneratedRef.current = true;
try {
sessionStorage.setItem(cacheKey, text);
} catch {
// ignore
}
} catch (err) {
const msg = err instanceof Error ? err.message : 'Terjadi kesalahan tidak diketahui.';
console.error('❌ Generate AI Insight hitung ayam gagal:', err);
setError(msg);
} finally {
setLoading(false);
inFlightRef.current = false;
// A day switch made while this was in flight is NOT re-run for the new
// scope: generation costs minutes of model time and now only ever
// starts from a click. The effect above shows the stored answer for the
// scope the user landed on, or the button if there is none.
}
},
// eslint-disable-next-line react-hooks/exhaustive-deps
[
props.cycleId,
props.currentDay,
props.totalInitialPopulation,
props.kandangInsights.length,
props.populationTrend.length,
timeframe,
cacheKey,
result,
]
);
// Scope changed: show the answer stored for it, and generate NOTHING.
//
// Generation runs only when the user presses the button. The stored result
// still has to reappear here, or leaving the page and coming back would look
// like the card had never been run.
//
// Deliberately NOT dependent on `generate`: it is rebuilt whenever `result` or
// any watched prop changes, which would make this effect re-run constantly.
useEffect(() => {
if (!props.cycleId) return;
if (lastCacheKeyRef.current === cacheKey) return;
try {
const cached = sessionStorage.getItem(cacheKey);
if (cached) {
const parsed = parseAiResult(cached);
if (parsed) {
setResult(parsed);
setError(null);
hasGeneratedRef.current = true;
lastCacheKeyRef.current = cacheKey;
return;
}
sessionStorage.removeItem(cacheKey);
}
} catch {
// sessionStorage might be unavailable
}
// Nothing stored for this scope — clear the previous one's answer so it is
// never left on screen under a different heading, and wait for the click.
setResult(null);
setError(null);
}, [props.cycleId, cacheKey]);
return (
<div
ref={pdfRef}
className="rounded-2xl border border-purple-100 bg-gradient-to-br from-purple-50 via-white to-blue-50 shadow-lg overflow-hidden"
>
<div className="px-5 pt-4">
<PdfReportHeader
title="AI Insight — Hitung Ayam"
area={appContext.selectedArea || 'Sukawarna'}
kandangLabel={describeKandangScope(appContext.kandangs, props.kandangId ?? null)}
periodLabel={describeTimeframePeriod(timeframe, period.label)}
cycleId={props.cycleId}
dataDateLabel={(() => {
const { fromDay, toDay } = parseDayRangeLabel(period.label);
return describeDataDates(cycleData?.startDate, fromDay, toDay);
})()}
/>
</div>
{/* Header */}
<div className="flex items-center justify-between px-5 py-4 border-b border-purple-100 bg-white/60 backdrop-blur-sm">
<div className="flex items-center gap-2">
<div className="p-1.5 bg-purple-100 rounded-lg">
<Sparkles className="w-5 h-5 text-purple-600" />
</div>
<div>
<h2 className="text-base font-bold text-gray-900">AI Insight — Hitung Ayam</h2>
<p className="text-xs text-gray-500">
Analisis populasi &amp; mortalitas berbasis kecerdasan buatan
</p>
<p className="text-[11px] text-gray-400" title={DATA_UPDATE_NOTICE_DETAIL}>
{DATA_UPDATE_NOTICE}
</p>
</div>
</div>
<div className="flex items-center gap-2" data-html2canvas-ignore="true">
{/* DAY PICKER — same role as the dashboard's: the daily view describes
one cycle day, and without this it could only ever be the newest. */}
{timeframe === 'harian' && availableDays.length > 1 && (
<select
value={activeDay ?? availableDays[availableDays.length - 1]}
onChange={(e) => setSelectedDay(parseInt(e.target.value, 10))}
className="text-[11px] font-semibold border border-purple-100 bg-white text-purple-700 rounded-lg px-2 py-1 shadow-sm focus:border-purple-400 focus:ring-purple-400"
title="Pilih hari siklus"
>
{availableDays.map((d) => (
<option key={d} value={d}>
Hari {d}
</option>
))}
</select>
)}
{result && (
<button
onClick={downloadPdf}
disabled={loading}
title="Unduh PDF"
className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg border border-slate-800 bg-slate-900 text-white hover:bg-slate-800 active:scale-95 disabled:opacity-50 disabled:cursor-not-allowed transition-all text-xs font-semibold shadow-sm"
>
<Download className="w-3.5 h-3.5" />
<span>Unduh PDF</span>
</button>
)}
<button
onClick={() => generate(true)}
disabled={loading}
className={`p-1.5 rounded-lg transition-all border ${
loading
? 'bg-gray-100 border-gray-200 cursor-not-allowed'
: 'bg-white border-purple-200 hover:bg-purple-50 hover:border-purple-300 active:scale-95 shadow-sm'
}`}
title="Refresh insight"
>
<RefreshCw className={`w-3.5 h-3.5 text-purple-600 ${loading ? 'animate-spin' : ''}`} />
</button>
</div>
</div>
{/* Body */}
<div className="p-5">
{/* Loading */}
{loading && !result && (
<div className="flex flex-col items-center justify-center py-10 gap-3">
<div className="relative">
<div className="w-12 h-12 rounded-full border-4 border-purple-100 border-t-purple-600 animate-spin" />
<Sparkles className="w-5 h-5 text-purple-500 absolute inset-0 m-auto animate-pulse" />
</div>
<p className="text-sm text-gray-500 animate-pulse">
Menganalisis data populasi ayam...
</p>
</div>
)}
{/* Error.
Deliberately NOT gated on `!result`. A regeneration that fails —
an unparseable reply, or a reply identical to the one on screen —
leaves the previous answer standing, and hiding the message there
was the worst case of all: the operator waits minutes for the model,
nothing on the card changes, and nothing says why. */}
{error && (
<div className="flex items-start gap-3 bg-red-50 border border-red-200 rounded-xl p-4">
<AlertTriangle className="w-5 h-5 text-red-500 shrink-0 mt-0.5" />
<div>
<p className="text-sm font-semibold text-red-700">
{result ? 'Generate ulang gagal' : 'Gagal memuat insight'}
</p>
<p className="text-sm text-red-600 mt-1">{error}</p>
{result && (
<p className="text-xs text-red-500 mt-1">
Analisis di bawah masih hasil sebelumnya, belum diperbarui.
</p>
)}
<button
onClick={() => generate(true)}
className="mt-2 text-xs text-red-700 underline hover:no-underline"
>
Coba lagi
</button>
</div>
</div>
)}
{/* Nothing generated for this scope yet.
This used to be a spinner reading "Memuat insight AI...", from when
the card generated on mount. Generation is click-only now, so that
spinner turned forever on a card that was not loading anything.
Same wording and same call to action as every other insight card. */}
{!loading && !error && !result && (
<div className="flex flex-col items-center justify-center gap-3 py-8 text-center">
<p className="text-sm text-gray-500">
Belum ada AI Insight untuk periode ini. Klik tombol di bawah untuk membuatnya.
</p>
<button
onClick={() => generate(true)}
className="flex items-center gap-2 px-4 py-2 rounded-lg border border-purple-200 bg-white hover:bg-purple-50 hover:border-purple-300 text-purple-700 text-xs font-semibold shadow-sm active:scale-95 transition-all"
>
<Sparkles className="w-4 h-4" />
<span>Buat AI Insight</span>
</button>
</div>
)}
{/* Result */}
{result && (
<div className={`space-y-4${error ? ' mt-4' : ''}`}>
{heroSpec && (
<HeroFigure
label="Mortalitas Kumulatif"
value={heroSpec.value}
unit="%"
context={heroSpec.context}
status={heroSpec.status}
deltaLabel="standar CP 707 <5%"
/>
)}
<div
className="bg-white rounded-xl border border-gray-100 shadow-sm p-5"
data-pdf-block
>
<div className="grid grid-cols-1 md:grid-cols-2 gap-y-3 gap-x-6">
{/* Data Points */}
<div className="flex justify-between items-center py-1 border-b border-gray-50">
<span className="text-sm text-gray-600 font-medium">
Jumlah Populasi (Jumlah DOC)
</span>
<span className="text-sm font-bold text-gray-900">
{props.totalInitialPopulation.toLocaleString()}
</span>
</div>
<div className="flex justify-between items-center py-1 border-b border-gray-50">
<span className="text-sm text-gray-600 font-medium">
Jumlah Kematian (Kematian + Afkir){' '}
<span className="text-xs font-normal text-gray-400">— {period.label}</span>
</span>
<span className="text-sm font-bold text-gray-900">
{periodDepartures.adaData
? periodDepartures.mortalityTotal.toLocaleString('id-ID')
: '-'}
</span>
</div>
<div className="flex justify-between items-center py-1 border-b border-gray-50">
<span className="text-sm text-gray-600 font-medium">
Jumlah terpanen{' '}
<span className="text-xs font-normal text-gray-400">— {period.label}</span>
</span>
<span className="text-sm font-bold text-gray-900">
{periodDepartures.adaData
? periodDepartures.panen.toLocaleString('id-ID')
: '-'}
</span>
</div>
<div className="flex justify-between items-center py-1 border-b border-gray-50">
<span className="text-sm text-gray-600 font-medium">
Jumlah tonase panen{' '}
<span className="text-xs font-normal text-gray-400">— {period.label}</span>
</span>
<span className="text-sm font-bold text-gray-900">
{periodDepartures.adaData && periodDepartures.beratPanen > 0
? `${periodDepartures.beratPanen.toLocaleString('id-ID')} kg`
: '-'}
</span>
</div>
<div className="flex justify-between items-center py-1 border-b border-gray-50">
<span className="text-sm text-gray-600 font-medium">
Saldo Akhir Ayam{' '}
<span className="text-xs font-normal text-gray-400">— seluruh siklus</span>
</span>
<span className="text-sm font-bold text-gray-900">
{departures.adaData ? departures.saldo.toLocaleString('id-ID') : '-'}
</span>
</div>
</div>
{/* GRAFIK — konteks visual untuk teks di bawahnya.
`data-pdf-block` keeps a page break from landing inside it. */}
<div className="mt-6 pt-4 border-t border-purple-100" data-pdf-block>
<InsightTrendChart
rows={chartRows}
series={[{ field: 'populasi', label: 'Populasi', color: '#7c3aed' }]}
unit="ekor"
title="Tren Populasi Ayam"
highlight={chartHighlight}
emptyLabel="Belum ada data tren populasi untuk digambarkan."
/>
</div>
<div className="mt-6 pt-4 border-t border-purple-100" data-pdf-block>
<h4 className="text-sm font-bold text-purple-700 mb-2 flex items-center gap-2">
<CheckCircle className="w-4 h-4" /> Kesimpulan
</h4>
<p className="text-sm text-gray-700 bg-purple-50/50 p-3 rounded-lg border border-purple-100">
{result.kesimpulan}
</p>
</div>
<div className="mt-4">
<h4 className="text-sm font-bold text-purple-700 mb-2 flex items-center gap-2">
<Sparkles className="w-4 h-4" /> AI Insight
</h4>
<p className="text-sm text-gray-700 bg-blue-50/50 p-3 rounded-lg border border-blue-100 whitespace-pre-line">
{result.insight}
</p>
</div>
</div>
</div>
)}
</div>
</div>
);
};
export default ChickenCountingAiInsight;