updated behavior journal

This commit is contained in:
blaisadmin committed 2026-10-09 23:41:41 -04:00
1 parent dc07026a88
commit 7397b85e69
8 files changed
+69 -21

No files matched your search

+1 -1
View File
@@ -7277,7 +7277,7 @@ function App() {
) : null}
{selectedBirdTab === 'behavior' && authToken ? <BehaviorJournal
key={`${workspace?.id}-${selectedBird.id}`} bird={selectedBird} birds={birds} onSelectBird={setSelectedBirdId} token={authToken} apiFetch={apiFetch}
key={`${workspace?.id}-${selectedBird.id}`} bird={selectedBird} token={authToken} apiFetch={apiFetch}
writable={!selectedBird.memorializedAt && ['owner', 'assistant', 'caregiver'].includes(activeMembership?.role ?? '') && Boolean(authSession?.isAdmin || (workspace?.workspaceType === 'rescue' ? workspace.rescueVerificationStatus === 'approved' : workspace && subscriptionAllowsFlockWrites(workspace.subscriptionStatus)))}
/> : null}
{selectedBirdTab === 'weight' ? (
+23 -11
View File
@@ -7,16 +7,18 @@ type Occurrence = {
durationSeconds: number | null; severity: number | null; notes: string | null; createdAt: string; updatedAt: string;
};
type Props = {
bird: { id: string; name: string }; birds: { id: string; name: string }[]; onSelectBird: (id: string) => void; token: string; writable: boolean;
bird: { id: string; name: string }; token: string; writable: boolean;
apiFetch: (path: string, token?: string, init?: RequestInit) => Promise<Response>;
};
const localDate = (date: Date) => `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
const localTime = (date: Date) => `${localDate(date)}T${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}:${String(date.getSeconds()).padStart(2, '0')}`;
const emptyForm = () => ({ behaviorTypeId: '', occurredAt: localTime(new Date()), duration: '', severity: '', notes: '' });
export function BehaviorJournal({ bird, birds, onSelectBird, token, writable, apiFetch }: Props) {
export function BehaviorJournal({ bird, token, writable, apiFetch }: Props) {
const [month, setMonth] = useState(() => new Date(new Date().getFullYear(), new Date().getMonth(), 1));
const [day, setDay] = useState(() => localDate(new Date()));
const [view, setView] = useState<'month' | 'range'>('month');
const [range, setRange] = useState(() => ({ start: localDate(new Date(new Date().getFullYear(), new Date().getMonth(), 1)), end: localDate(new Date()) }));
const [filter, setFilter] = useState('');
const [types, setTypes] = useState<BehaviorType[]>([]);
const [entries, setEntries] = useState<Occurrence[]>([]);
@@ -42,14 +44,22 @@ export function BehaviorJournal({ bird, birds, onSelectBird, token, writable, ap
useEffect(() => {
let active = true;
setLoading(true); setError(''); setEntries([]);
const query = new URLSearchParams({ from: month.toISOString(), to: new Date(month.getFullYear(), month.getMonth() + 1, 1).toISOString() });
const from = view === 'range' ? new Date(`${range.start}T00:00:00`) : month;
const to = view === 'range' ? new Date(`${range.end}T00:00:00`) : new Date(month.getFullYear(), month.getMonth() + 1, 1);
if (view === 'range') to.setDate(to.getDate() + 1);
if (!Number.isFinite(from.getTime()) || !Number.isFinite(to.getTime()) || to <= from || to.getTime() - from.getTime() > 366 * 86400000) {
setError('Choose a start and end date, with the end on or after the start and a range of up to 366 days.');
setLoading(false);
return;
}
const query = new URLSearchParams({ from: from.toISOString(), to: to.toISOString() });
if (filter) query.set('behaviorTypeId', filter);
Promise.all([request(`${base}/behavior-types`), request(`${base}/behaviors?${query}`)])
.then(([typeData, occurrenceData]) => { if (active) { setTypes(typeData.behaviorTypes); setEntries(occurrenceData.occurrences); } })
.catch((e) => { if (active) setError(e instanceof Error ? e.message : 'Unable to load journal.'); })
.finally(() => { if (active) setLoading(false); });
return () => { active = false; };
}, [bird.id, token, month, filter, revision]);
}, [bird.id, token, month, view, range, filter, revision]);
const byDay = useMemo(() => {
const result = new Map<string, Occurrence[]>();
@@ -79,6 +89,7 @@ export function BehaviorJournal({ bird, birds, onSelectBird, token, writable, ap
await request(`${base}/behaviors${editing ? `/${editing.id}` : ''}`, { method: editing ? 'PUT' : 'POST', body: JSON.stringify({ behaviorTypeId: typeId, occurredAt, durationSeconds: form.duration === '' ? null : Number(form.duration), severity: form.severity === '' ? null : Number(form.severity), notes: form.notes || null }) });
const savedDate = new Date(occurredAt);
setMonth(new Date(savedDate.getFullYear(), savedDate.getMonth(), 1)); setDay(localDate(savedDate));
if (view === 'range' && (localDate(savedDate) < range.start || localDate(savedDate) > range.end)) setRange({ start: localDate(savedDate), end: localDate(savedDate) });
setFilter(''); setShowForm(false); setEditing(null); setRevision((value) => value + 1); setNotice('Occurrence saved.');
} catch (e) { setError(e instanceof Error ? e.message : 'Unable to save occurrence.'); }
finally { setSaving(false); }
@@ -113,11 +124,12 @@ export function BehaviorJournal({ bird, birds, onSelectBird, token, writable, ap
<div className="behavior-actions"><button className="primary-button" type="submit">{saving ? 'Saving…' : 'Save occurrence'}</button><button className="secondary-button" type="button" onClick={() => { setShowForm(false); setEditing(null); }}>Cancel</button></div>
</fieldset>
</form>}
<label>Bird<select aria-label="Bird" value={bird.id} disabled={saving} onChange={(e) => onSelectBird(e.target.value)}>{birds.map((item) => <option key={item.id} value={item.id}>{item.name}</option>)}</select></label>
<label>Show behavior<select aria-label="Show behavior" value={filter} disabled={saving} onChange={(e) => setFilter(e.target.value)}><option value="">All behaviors</option>{types.map((type) => <option key={type.id} value={type.id}>{type.name}</option>)}</select></label>
<div className="behavior-month"><button className="secondary-button" type="button" aria-label="Previous month" onClick={() => navigate(-1)}>‹</button><h3 aria-live="polite">{month.toLocaleDateString(undefined, { month: 'long', year: 'numeric' })}</h3><button className="secondary-button" type="button" aria-label="Next month" onClick={() => navigate(1)}>›</button></div>
<p aria-live="polite">{loading ? 'Loading occurrences…' : `${entries.length} occurrence${entries.length === 1 ? '' : 's'} this month`}</p>
<div className="behavior-calendar" aria-label="Monthly behavior occurrences" aria-busy={loading}>
<label>View<select aria-label="Journal view" value={view} disabled={saving} onChange={(e) => setView(e.target.value as 'month' | 'range')}><option value="month">Monthly calendar</option><option value="range">Date range</option></select></label>
{view === 'range' && <div className="behavior-range"><label>Start date<input type="date" required value={range.start} disabled={saving} onChange={(e) => setRange({ ...range, start: e.target.value })} /></label><label>End date<input type="date" required min={range.start} value={range.end} disabled={saving} onChange={(e) => setRange({ ...range, end: e.target.value })} /></label><p className="muted">Includes both dates, up to 366 days. Entries are shown newest first.</p></div>}
{view === 'month' && <div className="behavior-month"><button className="secondary-button" type="button" aria-label="Previous month" onClick={() => navigate(-1)}>‹</button><h3 aria-live="polite">{month.toLocaleDateString(undefined, { month: 'long', year: 'numeric' })}</h3><button className="secondary-button" type="button" aria-label="Next month" onClick={() => navigate(1)}>›</button></div>}
<p aria-live="polite">{loading ? 'Loading occurrences…' : `${entries.length} occurrence${entries.length === 1 ? '' : 's'} ${view === 'month' ? 'this month' : 'in this date range'}`}</p>
{view === 'month' && <><div className="behavior-calendar" aria-label="Monthly behavior occurrences" aria-busy={loading}>
{['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'].map((label) => <span className="behavior-weekday" key={label}>{label}</span>)}
{Array.from({ length: month.getDay() }, (_, index) => <span key={`blank-${index}`} />)}
{Array.from({ length: days }, (_, index) => {
@@ -125,8 +137,8 @@ export function BehaviorJournal({ bird, birds, onSelectBird, token, writable, ap
return <button type="button" key={key} className={`behavior-day ${count ? 'has-occurrences' : ''}`} aria-pressed={key === day} aria-current={key === localDate(new Date()) ? 'date' : undefined} aria-label={`${date.toLocaleDateString()}: ${count} occurrences`} onClick={() => setDay(key)}><span>{index + 1}</span>{count > 0 && <><span className="behavior-dots" aria-hidden="true">{'●'.repeat(Math.min(count, 3))}{count > 3 ? '+' : ''}</span><small>{count}</small></>}</button>;
})}
</div>
<h3>{new Date(`${day}T12:00:00`).toLocaleDateString(undefined, { dateStyle: 'long' })}</h3>
{!loading && !(byDay.get(day)?.length) && <p className="muted">No occurrences recorded for this day{filter ? ' for the selected behavior' : ''}.</p>}
{(byDay.get(day) || []).map((entry) => <details key={entry.id} className="behavior-entry"><summary><strong>{entry.behaviorName}</strong><span>{new Date(entry.occurredAt).toLocaleString()}</span>{entry.durationSeconds !== null && <span>Duration: {entry.durationSeconds} seconds</span>}{entry.severity !== null && <span>Intensity: {entry.severity}/5</span>}{entry.notes && <span className="behavior-note-preview">{entry.notes}</span>}</summary><div>{entry.notes && <p className="behavior-notes">{entry.notes}</p>}<p className="muted">Created: {new Date(entry.createdAt).toLocaleString()}<br />Updated: {new Date(entry.updatedAt).toLocaleString()}</p>{writable && <div className="behavior-actions"><button className="secondary-button" type="button" disabled={saving} onClick={() => edit(entry)}>Edit</button><button className="danger-button" type="button" disabled={saving} onClick={() => void remove(entry)}>Delete</button></div>}</div></details>)}
<h3>{new Date(`${day}T12:00:00`).toLocaleDateString(undefined, { dateStyle: 'long' })}</h3></>}
{!loading && !error && !(view === 'range' ? entries.length : byDay.get(day)?.length) && <p className="muted">No occurrences recorded for {view === 'range' ? 'this date range' : 'this day'}{filter ? ' for the selected behavior' : ''}.</p>}
{(view === 'range' ? entries : byDay.get(day) || []).map((entry) => <details key={entry.id} className="behavior-entry"><summary><strong>{entry.behaviorName}</strong><span>{new Date(entry.occurredAt).toLocaleString()}</span>{entry.durationSeconds !== null && <span>Duration: {entry.durationSeconds} seconds</span>}{entry.severity !== null && <span>Intensity: {entry.severity}/5</span>}{entry.notes && <span className="behavior-note-preview">{entry.notes}</span>}</summary><div>{entry.notes && <p className="behavior-notes">{entry.notes}</p>}<p className="muted">Created: {new Date(entry.createdAt).toLocaleString()}<br />Updated: {new Date(entry.updatedAt).toLocaleString()}</p>{writable && <div className="behavior-actions"><button className="secondary-button" type="button" disabled={saving} onClick={() => edit(entry)}>Edit</button><button className="danger-button" type="button" disabled={saving} onClick={() => void remove(entry)}>Delete</button></div>}</div></details>)}
</section>;
}
+5
View File
@@ -22,3 +22,8 @@
.behavior-note-preview { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.behavior-notes { white-space: pre-wrap; overflow-wrap: anywhere; }
@media (max-width: 540px) { .behavior-form fieldset { grid-template-columns: 1fr; } .behavior-day { min-height: 64px; padding: .2rem; } .behavior-calendar { gap: .15rem; } .behavior-weekday { font-size: .7rem; } }
.behavior-range { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: .75rem; margin-top: .75rem; }
.behavior-range input { min-width: 0; width: 100%; box-sizing: border-box; }
.behavior-range p { grid-column: 1 / -1; margin: 0; }
@media (max-width: 540px) { .behavior-range { grid-template-columns: 1fr; } }
+12 -3
View File
@@ -49,6 +49,15 @@ try {
await page.getByRole('tab', { name: 'Behavior Journal' }).click();
const journal = page.getByRole('tabpanel', { name: 'Behavior Journal' });
await journal.getByText('1 occurrence this month', { exact: true }).waitFor();
await journal.getByLabel('Journal view').selectOption('range');
await journal.getByLabel('Start date', { exact: true }).fill('2026-09-30');
await journal.getByLabel('End date', { exact: true }).fill('2026-11-01');
await journal.getByText('4 occurrences in this date range', { exact: true }).waitFor();
assert.equal(await journal.locator('details').count(), 4);
await journal.getByLabel('Start date', { exact: true }).fill('2026-11-01');
await journal.getByText('2 occurrences in this date range', { exact: true }).waitFor(); // Both repeated hours on the inclusive end date.
await journal.getByLabel('Journal view').selectOption('month');
await journal.getByText('1 occurrence this month', { exact: true }).waitFor();
await journal.getByRole('button', { name: 'Record behavior' }).click();
assert.match(await journal.getByLabel('Date and time', { exact: true }).inputValue(), /^2026-10-05T12:00(:00)?$/);
await journal.getByLabel('Behavior', { exact: true }).selectOption('custom');
@@ -104,9 +113,9 @@ try {
await editedEntry.getByRole('button', { name: 'Delete', exact: true }).click();
await journal.getByText('Occurrence deleted.', { exact: true }).waitFor();
await journal.getByRole('button', { name: '10/5/2026: 1 occurrences', exact: true }).waitFor();
await journal.getByLabel('Bird', { exact: true }).selectOption(secondBird);
await page.locator('.bird-card-select').filter({ hasText: 'Willow' }).click();
await journal.getByText('0 occurrences this month', { exact: true }).waitFor();
await journal.getByLabel('Bird', { exact: true }).selectOption(bird);
await page.locator('.bird-card-select').filter({ hasText: 'Piper' }).click();
await journal.getByText('2 occurrences this month', { exact: true }).waitFor();
await page.setViewportSize({ width: 1280, height: 1000 });
await journal.scrollIntoViewIfNeeded();
@@ -124,7 +133,7 @@ try {
await utcJournal.getByRole('button', { name: '10/1/2026: 2 occurrences', exact: true }).waitFor();
await utcContext.close();
assert.deepEqual(errors, []);
console.log('PASS: browser create/custom type/edit/delete, bird/behavior filters, month navigation, multiple events/day, local midnight and DST, and mobile layout.');
console.log('PASS: browser create/custom type/edit/delete, member journals and behavior filters, month navigation, multiple events/day, local midnight and DST, and mobile layout.');
} catch (error) {
if (page) {
console.error(await page.locator('.behavior-journal').innerText().catch(() => 'Journal unavailable'));