fix: day modal bar chart shows experiment-wide session stats per subject

Shows Total / Success / Failure bars across ALL sessions for each animal
that has at least one valid (non-empty) value for the chosen field.
Animals with zero valid field entries are excluded from the chart.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
Experiments DB Dev
2026-04-23 12:21:52 -04:00
parent 9b51250d8e
commit 7439a1a101
2 changed files with 32 additions and 21 deletions
+23 -15
View File
@@ -53,25 +53,29 @@ function DayPanel({ date, animals, allStatuses, template, experimentId, selected
const fieldLabel = fieldOptions.find((f) => f.value === selectedField)?.label; const fieldLabel = fieldOptions.find((f) => f.value === selectedField)?.label;
// Bar chart: this day's field value per subject (numeric fields only) // Bar chart: session stats across ALL days, for animals with at least one valid field value
const barData = useMemo(() => { const barData = useMemo(() => {
if (!selectedField) return []; if (!selectedField) return [];
const isBuiltin = BUILTIN_KEYS_SET.has(selectedField); const isBuiltin = BUILTIN_KEYS_SET.has(selectedField);
return animalsWithData return animals
.map((animal) => { .map((animal) => {
const status = statusByAnimal[animal.id]; const statuses = allStatuses.filter((s) => s.animal_id === animal.id);
if (!status) return null; const total = statuses.length;
const raw = isBuiltin ? status[selectedField] : status.custom_fields?.[selectedField]; if (total === 0) return null;
if (raw === null || raw === undefined || String(raw).trim() === '') return null; const success = statuses.filter((s) => {
const num = parseFloat(raw); const val = isBuiltin ? s[selectedField] : s.custom_fields?.[selectedField];
if (isNaN(num)) return null; return val !== null && val !== undefined && String(val).trim() !== '';
}).length;
if (success === 0) return null; // skip animals with no valid field data
return { return {
name: animal.animal_name || animal.animal_id_string || animal.id.slice(0, 8), name: animal.animal_name || animal.animal_id_string || animal.id.slice(0, 8),
value: num, total,
success,
failure: total - success,
}; };
}) })
.filter(Boolean); .filter(Boolean);
}, [animalsWithData, statusByAnimal, selectedField]); }, [animals, allStatuses, selectedField]);
return ( return (
<div className="space-y-3 max-h-[80vh] overflow-y-auto pr-1"> <div className="space-y-3 max-h-[80vh] overflow-y-auto pr-1">
@@ -120,16 +124,20 @@ function DayPanel({ date, animals, allStatuses, template, experimentId, selected
{/* Bar chart: overall per-subject completeness */} {/* Bar chart: overall per-subject completeness */}
{barData.length > 0 && ( {barData.length > 0 && (
<div className="mt-4 pt-4 border-t border-gray-100"> <div className="mt-4 pt-4 border-t border-gray-100">
<h4 className="text-sm font-semibold text-gray-700 mb-3"> <h4 className="text-sm font-semibold text-gray-700 mb-1">
{fieldLabel ?? 'Field'} by subject Session statistics {fieldLabel ?? 'selected field'}
</h4> </h4>
<p className="text-xs text-gray-400 mb-3">All sessions across the experiment</p>
<ResponsiveContainer width="100%" height={200}> <ResponsiveContainer width="100%" height={200}>
<BarChart data={barData} margin={{ top: 4, right: 16, left: 0, bottom: 4 }}> <BarChart data={barData} margin={{ top: 4, right: 16, left: 0, bottom: 4 }}>
<CartesianGrid strokeDasharray="3 3" stroke="#f0f0f0" /> <CartesianGrid strokeDasharray="3 3" stroke="#f0f0f0" />
<XAxis dataKey="name" tick={{ fontSize: 11 }} /> <XAxis dataKey="name" tick={{ fontSize: 11 }} />
<YAxis tick={{ fontSize: 11 }} /> <YAxis tick={{ fontSize: 11 }} allowDecimals={false} />
<Tooltip formatter={(v) => [v, fieldLabel ?? 'Value']} /> <Tooltip />
<Bar dataKey="value" name={fieldLabel ?? 'Value'} fill="#6366f1" radius={[3, 3, 0, 0]} /> <Legend wrapperStyle={{ fontSize: 11 }} />
<Bar dataKey="total" name="Total" fill="#94a3b8" />
<Bar dataKey="success" name="Success" fill="#22c55e" />
<Bar dataKey="failure" name="Failure" fill="#f87171" minPointSize={2} />
</BarChart> </BarChart>
</ResponsiveContainer> </ResponsiveContainer>
</div> </div>
+9 -6
View File
@@ -248,7 +248,7 @@ describe('day click modal', () => {
// ── Bar chart (inside day modal) ────────────────────────────────────────────── // ── Bar chart (inside day modal) ──────────────────────────────────────────────
describe('bar chart inside day modal', () => { describe('bar chart inside day modal', () => {
it('renders bar chart for numeric field values on that day', async () => { it('renders session stats bar chart when animals have valid field data', async () => {
const dateStr = todayStr(); const dateStr = todayStr();
const statuses = [ const statuses = [
makeStatus('a1000000-0000-0000-0000-000000000001', dateStr, { 'ww000000-0000-0000-0000-000000000099': '325' }), makeStatus('a1000000-0000-0000-0000-000000000001', dateStr, { 'ww000000-0000-0000-0000-000000000099': '325' }),
@@ -263,16 +263,19 @@ describe('bar chart inside day modal', () => {
}); });
}); });
it('does not render bar chart when selected field is non-numeric', async () => { it('excludes animals with no valid field data from bar chart', async () => {
const dateStr = todayStr(); const dateStr = todayStr();
// vitals is a text field — not numeric, so no bar chart // Rat A has weight data; Rat B has only empty custom_fieldsshould be excluded from chart
const statuses = [makeStatus('a1000000-0000-0000-0000-000000000001', dateStr, {}, 'HR 72')]; const statuses = [
makeStatus('a1000000-0000-0000-0000-000000000001', dateStr, { 'ww000000-0000-0000-0000-000000000099': '325' }),
makeStatus('a2000000-0000-0000-0000-000000000002', dateStr, {}),
];
render( render(
<ExperimentCalendar experimentId={EXP_ID} template={TEMPLATE} allStatuses={statuses} animals={ANIMALS} />, <ExperimentCalendar experimentId={EXP_ID} template={TEMPLATE} allStatuses={statuses} animals={ANIMALS} />,
); );
fireEvent.change(screen.getByTestId('field-select'), { target: { value: 'vitals' } });
fireEvent.click(screen.getByTestId(`day-${dateStr}`)); fireEvent.click(screen.getByTestId(`day-${dateStr}`));
await waitFor(() => screen.getByRole('dialog')); await waitFor(() => screen.getByRole('dialog'));
expect(screen.queryByTestId('bar-chart')).not.toBeInTheDocument(); // Both animals are in the day view (both have records), but bar chart only has Rat A
expect(screen.getByTestId('bar-chart')).toBeInTheDocument();
}); });
}); });