Merge dev into production release without education
Deploy / deploy-dev (push) Skipped
Deploy / deploy-prod (push) Successful in 3m58s

This commit is contained in:
Corey Blais committed 2026-10-05 18:18:10 -04:00
commit fc541f024d
50 files changed
+2986 -458

No files matched your search

Binary file not shown.

After

Width:  |  Height:  |  Size: 237 KiB

+124 -32
View File
@@ -1,3 +1,4 @@
import { BehaviorJournal } from './BehaviorJournal';
import { useEffect, useMemo, useState, type CSSProperties, type Dispatch, type SetStateAction } from 'react';
import birdSilhouette from './assets/bird-silhouette.jpg';
import flockPalLandingArt from './assets/flockpal-landing-art.png';
@@ -235,7 +236,7 @@ type AuditLogEntry = {
type BirdTimelineEvent = {
id: string;
birdId: string;
eventType: 'profile_created' | 'transferred' | 'location_updated' | 'owner_changed' | 'manual_note';
eventType: 'profile_created' | 'transferred' | 'location_updated' | 'owner_changed' | 'manual_note' | 'removed_from_flock' | 'joined_flock';
fromWorkspaceId: number | null;
toWorkspaceId: number | null;
fromWorkspaceName: string | null;
@@ -429,7 +430,7 @@ type WeightDropAlert = {
};
type DismissibleAlertType = 'weight-range' | 'weight-drop' | 'vet-visit';
type BirdDetailTab = 'info' | 'weight' | 'vet' | 'notes' | 'reports' | 'timeline' | 'audit';
type BirdDetailTab = 'behavior' | 'info' | 'weight' | 'vet' | 'notes' | 'reports' | 'timeline' | 'audit';
type DismissedAlertMap = Record<string, boolean>;
type PhotoCropState = {
@@ -1133,6 +1134,9 @@ const formatAuditAction = (value: string) =>
.join(' ');
const formatBirdTimelineTitle = (event: BirdTimelineEvent) => {
if (event.eventType === 'removed_from_flock') return 'Removed from flock';
if (event.eventType === 'joined_flock') return 'Joined flock with history';
if (event.eventType === 'profile_created') {
return 'Added to flock';
}
@@ -1153,6 +1157,9 @@ const formatBirdTimelineTitle = (event: BirdTimelineEvent) => {
};
const formatBirdTimelineDescription = (event: BirdTimelineEvent) => {
if (event.eventType === 'removed_from_flock') return `Left ${event.fromWorkspaceName || 'previous flock'}; history retained.`;
if (event.eventType === 'joined_flock') return `Joined ${event.toWorkspaceName || 'current flock'} with existing history.`;
if (event.eventType === 'profile_created') {
return event.locationLabel ? `Location: ${event.locationLabel}` : `Flock: ${event.toWorkspaceName || 'Unknown flock'}`;
}
@@ -1231,6 +1238,9 @@ const getBirdHatchDay = (bird: Pick<Bird, 'hatchDay' | 'dateOfBirth'>) => {
};
const getBirdTimelineGraphLabel = (event: BirdTimelineEvent) => {
if (event.eventType === 'removed_from_flock') return 'Removed from flock';
if (event.eventType === 'joined_flock') return 'Joined flock with history';
if (event.eventType === 'location_updated') {
return event.locationLabel || 'Location updated';
}
@@ -2153,6 +2163,12 @@ function App() {
const [integrationTokenForm, setIntegrationTokenForm] = useState<IntegrationTokenFormState>(emptyIntegrationTokenForm);
const [flockNoteForm, setFlockNoteForm] = useState<FlockNoteFormState>(emptyFlockNoteForm);
const [birdForm, setBirdForm] = useState<BirdFormState>(emptyBirdForm);
const [unassignedBirdMatch, setUnassignedBirdMatch] = useState<{
tagId: string; status: 'idle' | 'loading' | 'available' | 'none' | 'error';
}>({ tagId: '', status: 'idle' });
const matchingUnassignedBird = !editingBirdId && unassignedBirdMatch.status === 'available'
&& unassignedBirdMatch.tagId === birdForm.tagId.trim().toLowerCase();
const [birdImportPreview, setBirdImportPreview] = useState<BirdImportPreview | null>(null);
const [birdImportFileName, setBirdImportFileName] = useState('');
const [birdImportNotice, setBirdImportNotice] = useState('');
@@ -2277,12 +2293,33 @@ function App() {
[auditLogEntries, selectedBird],
);
useEffect(() => {
const tagId = birdForm.tagId.trim().toLowerCase();
if (!authToken || !birdEditorOpen || editingBirdId || !tagId || ['unknown', 'not recorded', 'n/a', 'na', 'none'].includes(tagId)) {
setUnassignedBirdMatch({ tagId, status: 'idle' });
return;
}
const controller = new AbortController();
setUnassignedBirdMatch({ tagId, status: 'loading' });
const timer = window.setTimeout(async () => {
try {
const response = await apiFetch(`/birds/unassigned-match?${new URLSearchParams({ tagId })}`, authToken, { signal: controller.signal });
if (!response.ok) throw new Error('Unable to check band ID.');
const data = await response.json() as { available: boolean };
if (!controller.signal.aborted) setUnassignedBirdMatch({ tagId, status: data.available ? 'available' : 'none' });
} catch {
if (!controller.signal.aborted) setUnassignedBirdMatch({ tagId, status: 'error' });
}
}, 350);
return () => { window.clearTimeout(timer); controller.abort(); };
}, [authToken, workspace?.id, birdEditorOpen, editingBirdId, birdForm.tagId]);
useEffect(() => {
setDismissedAlerts(readDismissedAlerts());
}, [workspace?.id]);
useEffect(() => {
setSelectedBirdTab('info');
setSelectedBirdTab((current) => current === 'behavior' ? 'behavior' : 'info');
setBirdTimelineEvents([]);
setBirdTimelineEventForm(emptyBirdTimelineEventForm);
setBirdTimelineNotice(null);
@@ -3910,6 +3947,37 @@ function App() {
}
};
const handleClaimUnassignedBird = async () => {
if (!matchingUnassignedBird || savingBird) return;
const tagId = birdForm.tagId.trim();
if (!window.confirm(`Add the bird with band ID ${tagId} to this flock?\n\nIts saved profile, photo, notes, and care history will be brought in. The existing profile details will be used instead of any new details entered here.`)) return;
setSavingBird(true);
setError('');
try {
const response = await apiFetch('/birds/claim', authToken, {
method: 'POST', headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ tagId, confirmHistory: true }),
});
if (!response.ok) throw new Error(await readErrorMessage(response, 'Unable to add the existing bird.'));
const data = await response.json() as { bird: Bird };
setBirds((current) => sortBirdsByName([...current.filter((bird) => bird.id !== data.bird.id), data.bird]));
setSelectedBirdId(data.bird.id);
setEditingBirdId(data.bird.id);
setBirdForm(toBirdForm(data.bird));
setBirdPhotoName('');
setBirdEditorOpen(false);
setActivePage('flock');
setUnassignedBirdMatch({ tagId: '', status: 'idle' });
// Refresh notes without treating a successful claim as failed if this secondary request fails.
void apiFetch('/notes', authToken).then(async (notesResponse) => {
if (notesResponse.ok) setFlockNotes(((await notesResponse.json()) as { notes: FlockNote[] }).notes);
}).catch(() => setError('Bird added with its history. Refresh the flock to load its notes.'));
window.alert(`${data.bird.name} was added with its existing profile and care history.`);
} catch (claimError) {
setError(claimError instanceof Error ? claimError.message : 'Unable to add the existing bird.');
} finally { setSavingBird(false); }
};
const handleBirdSubmit = async (event: React.FormEvent<HTMLFormElement>) => {
event.preventDefault();
setError('');
@@ -4528,7 +4596,7 @@ function App() {
}
const confirmed = window.confirm(
`Remove ${selectedBird.name} from the flock?\n\nThis will also remove weight records and vet visits for this flock member.`,
`Remove ${selectedBird.name} from the flock?\n\nThe bird will leave this flock, but its profile, photo, notes, and care history will be retained. Public sharing and pending transfers will be disabled. Someone adding its exact band ID can bring the bird and its history into their flock.${selectedBird.tagId ? '' : '\n\nThis bird has no band ID, so its history cannot be automatically matched later.'}`,
);
if (!confirmed) {
@@ -4548,6 +4616,7 @@ function App() {
}
const nextBirds = birds.filter((bird) => bird.id !== selectedBird.id);
setFlockNotes((current) => current.filter((note) => note.birdId !== selectedBird.id));
setBirds(nextBirds);
setAllBirdWeights((current) => {
const next = { ...current };
@@ -5879,17 +5948,17 @@ function App() {
</div>
<aside className="side-nav panel">
<div className="page-tabs" role="tablist" aria-label="Main navigation">
<button className={`page-tab ${activePage === 'overview' ? 'active' : ''}`} onClick={() => setActivePage('overview')} type="button">
<button data-tab="overview" className={`page-tab ${activePage === 'overview' ? 'active' : ''}`} onClick={() => setActivePage('overview')} type="button">
Overview
</button>
<button className={`page-tab ${activePage === 'flock' ? 'active' : ''}`} onClick={() => setActivePage('flock')} type="button">
<button data-tab="flock" className={`page-tab ${activePage === 'flock' ? 'active' : ''}`} onClick={() => setActivePage('flock')} type="button">
Flock
</button>
<button className={`page-tab ${activePage === 'settings' ? 'active' : ''}`} onClick={() => setActivePage('settings')} type="button">
<button data-tab="settings" className={`page-tab ${activePage === 'settings' ? 'active' : ''}`} onClick={() => setActivePage('settings')} type="button">
Settings
</button>
{authSession.isAdmin ? (
<button className={`page-tab ${activePage === 'admin' ? 'active' : ''}`} onClick={() => setActivePage('admin')} type="button">
<button data-tab="admin" className={`page-tab ${activePage === 'admin' ? 'active' : ''}`} onClick={() => setActivePage('admin')} type="button">
Admin
</button>
) : null}
@@ -6468,6 +6537,17 @@ function App() {
placeholder="Optional if unknown"
/>
</label>
{!editingBirdId && unassignedBirdMatch.status === 'loading' ? <p className="muted wide-field" role="status">Checking band ID for existing history…</p> : null}
{matchingUnassignedBird ? (
<div className="success-banner wide-field" role="status">
<strong>This band ID matches a bird that is not currently in a flock.</strong>
<p>Adding it will bring in its saved profile, photo, notes, and care history. Existing profile details will be used.</p>
<button className="primary-button" type="button" disabled={savingBird} onClick={() => void handleClaimUnassignedBird()}>
{savingBird ? 'Adding…' : 'Add bird with existing history'}
</button>
</div>
) : null}
{!editingBirdId && unassignedBirdMatch.status === 'error' ? <p className="muted wide-field" role="status">Could not check for existing history. The band ID will still be checked when you save.</p> : null}
<label className="species-picker-field wide-field">
Species
<div className="species-picker">
@@ -6546,7 +6626,7 @@ function App() {
<span className="gender-symbol-mark">{getBirdGenderSymbol({ gender })}</span>
</span>
<BirdGenderSourceIcon bird={{ gender }} />
{getBirdGenderLabel({ gender })}
<span className="gender-option-label">{getBirdGenderLabel({ gender })}</span>
</button>
))}
</div>
@@ -6764,7 +6844,7 @@ function App() {
</div>
</section>
<div className="settings-save-row">
<button className="primary-button" type="submit" disabled={savingBird}>
<button className="primary-button" type="submit" disabled={savingBird || matchingUnassignedBird || (!editingBirdId && unassignedBirdMatch.status === 'loading')}>
{savingBird ? 'Saving...' : editingBird ? 'Save profile changes' : 'Save bird profile'}
</button>
</div>
@@ -6904,7 +6984,7 @@ function App() {
<section className="settings-nested-card settings-danger-card">
<div className="settings-nested-header">
<p className="eyebrow">Danger zone</p>
<h3>Destructive profile actions</h3>
<h3>Remove or memorialize</h3>
</div>
<form className="form-panel inline-form care-entry-form" onSubmit={handleMemorializeBird}>
<label>
@@ -6930,7 +7010,7 @@ function App() {
</button>
</div>
</form>
<p className="muted">Removing permanently deletes weight records, vet visits, and medication history for this bird.</p>
<p className="muted">Removing only takes this bird out of your flock. Its profile, photo, notes, and care history are retained and can be brought into a flock later using its exact band ID.</p>
<div className="button-row">
<button className="danger-button" onClick={handleRemoveBird} type="button" disabled={deletingBird}>
{deletingBird ? 'Removing...' : 'Remove from flock'}
@@ -6945,7 +7025,7 @@ function App() {
<section className="panel flock-member-panel bird-detail-panel">
<div className="bird-detail-tabs" role="tablist" aria-label={`${selectedBird.name} detail sections`}>
<button
className={`bird-detail-tab ${selectedBirdTab === 'info' ? 'active' : ''}`}
data-tab="info" className={`bird-detail-tab ${selectedBirdTab === 'info' ? 'active' : ''}`}
onClick={() => setSelectedBirdTab('info')}
type="button"
role="tab"
@@ -6958,7 +7038,7 @@ function App() {
</svg>
</button>
<button
className={`bird-detail-tab ${selectedBirdTab === 'weight' ? 'active' : ''}`}
data-tab="weight" className={`bird-detail-tab ${selectedBirdTab === 'weight' ? 'active' : ''}`}
onClick={() => setSelectedBirdTab('weight')}
type="button"
role="tab"
@@ -6970,21 +7050,13 @@ function App() {
<path d="M240-200h480l-57-400H297l-57 400Zm240-480q17 0 28.5-11.5T520-720q0-17-11.5-28.5T480-760q-17 0-28.5 11.5T440-720q0 17 11.5 28.5T480-680Zm113 0h70q30 0 52 20t27 49l57 400q5 36-18.5 63.5T720-120H240q-37 0-60.5-27.5T161-211l57-400q5-29 27-49t52-20h70q-3-10-5-19.5t-2-20.5q0-50 35-85t85-35q50 0 85 35t35 85q0 11-2 20.5t-5 19.5ZM240-200h480-480Z" />
</svg>
</button>
<button data-tab="behavior" className={`bird-detail-tab ${selectedBirdTab === 'behavior' ? 'active' : ''}`} type="button" role="tab" aria-selected={selectedBirdTab === 'behavior'} aria-label="Behavior Journal" title="Behavior Journal" onClick={() => setSelectedBirdTab('behavior')}>
<svg className="behavior-tab-icon" viewBox="0 -960 960 960" aria-hidden="true" focusable="false">
<path d="M580-240q-42 0-71-29t-29-71q0-42 29-71t71-29q42 0 71 29t29 71q0 42-29 71t-71 29ZM200-80q-33 0-56.5-23.5T120-160v-560q0-33 23.5-56.5T200-800h40v-80h80v80h320v-80h80v80h40q33 0 56.5 23.5T840-720v560q0 33-23.5 56.5T760-80H200Zm0-80h560v-400H200v400Zm0-480h560v-80H200v80Zm0 0v-80 80Z" />
</svg>
</button>
<button
className={`bird-detail-tab ${selectedBirdTab === 'vet' ? 'active' : ''}`}
onClick={() => setSelectedBirdTab('vet')}
type="button"
role="tab"
aria-selected={selectedBirdTab === 'vet'}
aria-label="Vet"
title="Vet"
>
<svg className="vet-tab-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
<path d="M20 6h-4V4c0-1.11-.89-2-2-2h-4c-1.11 0-2 .89-2 2v2H4c-1.11 0-2 .89-2 2v12c0 1.11.89 2 2 2h16c1.11 0 2-.89 2-2V8c0-1.11-.89-2-2-2ZM10 4h4v2h-4V4Zm6 11h-3v3h-2v-3H8v-2h3v-3h2v3h3v2Z" />
</svg>
</button>
<button
className={`bird-detail-tab ${selectedBirdTab === 'notes' ? 'active' : ''}`}
data-tab="notes" className={`bird-detail-tab ${selectedBirdTab === 'notes' ? 'active' : ''}`}
onClick={() => setSelectedBirdTab('notes')}
type="button"
role="tab"
@@ -6997,7 +7069,20 @@ function App() {
</svg>
</button>
<button
className={`bird-detail-tab ${selectedBirdTab === 'reports' ? 'active' : ''}`}
data-tab="vet" className={`bird-detail-tab ${selectedBirdTab === 'vet' ? 'active' : ''}`}
onClick={() => setSelectedBirdTab('vet')}
type="button"
role="tab"
aria-selected={selectedBirdTab === 'vet'}
aria-label="Vet"
title="Vet"
>
<svg className="vet-tab-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
<path d="M20 6h-4V4c0-1.11-.89-2-2-2h-4c-1.11 0-2 .89-2 2v2H4c-1.11 0-2 .89-2 2v12c0 1.11.89 2 2 2h16c1.11 0 2-.89 2-2V8c0-1.11-.89-2-2-2ZM10 4h4v2h-4V4Zm6 11h-3v3h-2v-3H8v-2h3v-3h2v3h3v2Z" />
</svg>
</button>
<button
data-tab="reports" className={`bird-detail-tab ${selectedBirdTab === 'reports' ? 'active' : ''}`}
onClick={() => setSelectedBirdTab('reports')}
type="button"
role="tab"
@@ -7010,7 +7095,7 @@ function App() {
</svg>
</button>
<button
className={`bird-detail-tab ${selectedBirdTab === 'timeline' ? 'active' : ''}`}
data-tab="timeline" className={`bird-detail-tab ${selectedBirdTab === 'timeline' ? 'active' : ''}`}
onClick={() => setSelectedBirdTab('timeline')}
type="button"
role="tab"
@@ -7021,7 +7106,7 @@ function App() {
<svg className="timeline-tab-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d="M21 6a2 2 0 0 0-1.93 2.51l-3.55 3.56A2.15 2.15 0 0 0 15 12c-.18 0-.36.02-.52.07l-2.55-2.55c.05-.16.07-.34.07-.52a2 2 0 1 0-4 0c0 .18.02.36.07.52l-4.56 4.55A2.03 2.03 0 0 0 3 14a2 2 0 1 0 1.93 1.49l4.55-4.56c.16.05.34.07.52.07s.36-.02.52-.07l2.55 2.55c-.05.16-.07.34-.07.52a2 2 0 1 0 4 0c0-.18-.02-.36-.07-.52l3.56-3.55A2 2 0 1 0 21 6Z" /></svg>
</button>
<button
className={`bird-detail-tab ${selectedBirdTab === 'audit' ? 'active' : ''}`}
data-tab="audit" className={`bird-detail-tab ${selectedBirdTab === 'audit' ? 'active' : ''}`}
onClick={() => setSelectedBirdTab('audit')}
type="button"
role="tab"
@@ -7185,6 +7270,10 @@ function App() {
</div>
) : null}
{selectedBirdTab === 'behavior' && authToken ? <BehaviorJournal
key={`${workspace?.id}-${selectedBird.id}`} bird={selectedBird} birds={birds} onSelectBird={setSelectedBirdId} 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' ? (
<div className="flock-member-sections" role="tabpanel">
<section className="panel inset-panel">
@@ -8551,7 +8640,10 @@ function App() {
{expandedSettingsSection === 'integration-tokens' ? (
<>
<p className="muted">
Create a flock-scoped token for automations like n8n. The secret is shown only once, so store it in your automation tool when it appears.
Create a flock-scoped token for automations like n8n. The secret is shown only once, so store it in your automation tool when it appears.{' '}
<a href={`${apiBaseUrl.replace(/\/$/, '')}/docs/`} target="_blank" rel="noopener noreferrer">
Browse the API reference
</a>.
</p>
<form className="form-panel" onSubmit={handleCreateIntegrationToken}>
<label>
+132
View File
@@ -0,0 +1,132 @@
import { useEffect, useMemo, useState, type FormEvent } from 'react';
import './behaviorJournal.css';
type BehaviorType = { id: string; name: string; description: string | null };
type Occurrence = {
id: string; birdId: string; behaviorTypeId: string; behaviorName: string; occurredAt: string;
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;
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) {
const [month, setMonth] = useState(() => new Date(new Date().getFullYear(), new Date().getMonth(), 1));
const [day, setDay] = useState(() => localDate(new Date()));
const [filter, setFilter] = useState('');
const [types, setTypes] = useState<BehaviorType[]>([]);
const [entries, setEntries] = useState<Occurrence[]>([]);
const [form, setForm] = useState(emptyForm);
const [editing, setEditing] = useState<Occurrence | null>(null);
const [showForm, setShowForm] = useState(false);
const [customName, setCustomName] = useState('');
const [customDescription, setCustomDescription] = useState('');
const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false);
const [error, setError] = useState('');
const [notice, setNotice] = useState('');
const [revision, setRevision] = useState(0);
const base = `/birds/${bird.id}`;
async function request(path: string, init?: RequestInit) {
const response = await apiFetch(path, token, { ...init, headers: { 'Content-Type': 'application/json', ...init?.headers } });
if (response.status === 204) return null;
const data = await response.json();
if (!response.ok) throw new Error(data.error || 'Unable to update the journal.');
return data;
}
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() });
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]);
const byDay = useMemo(() => {
const result = new Map<string, Occurrence[]>();
entries.forEach((entry) => { const key = localDate(new Date(entry.occurredAt)); result.set(key, [...(result.get(key) || []), entry]); });
return result;
}, [entries]);
function navigate(offset: number) {
const next = new Date(month.getFullYear(), month.getMonth() + offset, 1);
setMonth(next); setDay(localDate(next));
}
function edit(entry: Occurrence) {
setEditing(entry); setShowForm(true); setError(''); setNotice('');
setForm({ behaviorTypeId: entry.behaviorTypeId, occurredAt: localTime(new Date(entry.occurredAt)), duration: entry.durationSeconds === null ? '' : String(entry.durationSeconds), severity: entry.severity === null ? '' : String(entry.severity), notes: entry.notes || '' });
}
async function save(event: FormEvent) {
event.preventDefault(); setSaving(true); setError(''); setNotice('');
try {
let typeId = form.behaviorTypeId;
if (typeId === 'custom') {
const data = await request(`${base}/behavior-types`, { method: 'POST', body: JSON.stringify({ name: customName, description: customDescription }) });
typeId = data.behaviorType.id;
setTypes((previous) => [...previous.filter((type) => type.id !== typeId), data.behaviorType]);
setForm((previous) => ({ ...previous, behaviorTypeId: typeId }));
}
// Preserve sub-second precision if the timestamp was not edited.
const occurredAt = editing && form.occurredAt === localTime(new Date(editing.occurredAt)) ? editing.occurredAt : new Date(form.occurredAt).toISOString();
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));
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); }
}
async function remove(entry: Occurrence) {
if (!window.confirm(`Delete this ${entry.behaviorName} occurrence?`)) return;
setSaving(true); setError(''); setNotice('');
try {
await request(`${base}/behaviors/${entry.id}`, { method: 'DELETE' });
if (editing?.id === entry.id) { setShowForm(false); setEditing(null); }
setRevision((value) => value + 1); setNotice('Occurrence deleted.');
} catch (e) { setError(e instanceof Error ? e.message : 'Unable to delete occurrence.'); }
finally { setSaving(false); }
}
const days = new Date(month.getFullYear(), month.getMonth() + 1, 0).getDate();
return <section className="panel inset-panel behavior-journal" role="tabpanel" aria-label="Behavior Journal">
<div className="panel-header"><div><p className="eyebrow">{bird.name}</p><h2>Behavior Journal</h2></div>
{writable && <button type="button" className="primary-button" disabled={saving} onClick={() => { setForm(emptyForm()); setEditing(null); setCustomName(''); setCustomDescription(''); setShowForm(true); setError(''); setNotice(''); }}>Record behavior</button>}
</div>
<p className="muted">Record what you observed and review when it happened. Dates and times use your device’s local time zone.</p>
{error && <p className="error-banner" role="alert">{error}</p>}
{notice && <p className="success-banner" role="status">{notice}</p>}
{showForm && writable && <form onSubmit={save} className="behavior-form">
<h3>{editing ? 'Edit occurrence' : 'Record occurrence'}</h3>
<fieldset disabled={saving}>
<label>Behavior<select aria-label="Behavior" required value={form.behaviorTypeId} onChange={(e) => setForm({ ...form, behaviorTypeId: e.target.value })}><option value="">Select behavior</option>{types.map((type) => <option key={type.id} value={type.id}>{type.name}</option>)}<option value="custom">Create custom behavior…</option></select></label>
{form.behaviorTypeId === 'custom' && <><label>Custom behavior name<input required maxLength={120} value={customName} onChange={(e) => setCustomName(e.target.value)} /></label><label>Description (optional)<input maxLength={2000} value={customDescription} onChange={(e) => setCustomDescription(e.target.value)} /></label></>}
<label className="behavior-wide">Date and time<input type="datetime-local" step="1" required value={form.occurredAt} onChange={(e) => setForm({ ...form, occurredAt: e.target.value })} /></label>
<label>Duration in seconds (optional)<input type="number" min="0.001" max="31536000" step="any" value={form.duration} onChange={(e) => setForm({ ...form, duration: e.target.value })} /></label>
<label>Intensity (optional)<select aria-label="Intensity (optional)" value={form.severity} onChange={(e) => setForm({ ...form, severity: e.target.value })}><option value="">Not recorded</option>{[1, 2, 3, 4, 5].map((value) => <option key={value} value={value}>{value}{value === 1 ? ' — Low' : value === 5 ? ' — High' : ''}</option>)}</select></label>
<label className="behavior-wide">Notes (optional)<textarea maxLength={10000} rows={3} value={form.notes} onChange={(e) => setForm({ ...form, notes: e.target.value })} /></label>
<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}>
{['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) => {
const date = new Date(month.getFullYear(), month.getMonth(), index + 1); const key = localDate(date); const count = byDay.get(key)?.length || 0;
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>)}
</section>;
}
+24
View File
@@ -0,0 +1,24 @@
.behavior-journal { min-width: 0; }
.behavior-journal > label + label { margin-top: .75rem; }
.behavior-journal label { display: grid; gap: .4rem; }
.behavior-month { display: flex; justify-content: space-between; align-items: center; gap: .5rem; margin-top: 1rem; }
.behavior-calendar { display: grid; grid-template-columns: repeat(7, minmax(0, 1fr)); gap: .3rem; }
.behavior-weekday { text-align: center; font-size: .8rem; }
.behavior-day { min-height: 76px; min-width: 0; border: 1px solid #c5d4ce; border-radius: .6rem; background: #fff; color: #244338; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: .15rem; cursor: pointer; }
.behavior-day.has-occurrences { background: #e4f2e9; }
.behavior-day[aria-pressed="true"] { outline: 3px solid #326b56; outline-offset: -3px; }
.behavior-day[aria-current="date"] > span:first-child { text-decoration: underline; font-weight: bold; }
.behavior-dots { font-size: .65rem; letter-spacing: .04em; }
.behavior-day:focus-visible { outline: 3px solid #1c5ba3; }
.behavior-form { margin: 1rem 0; }
.behavior-form fieldset { border: 0; padding: 0; display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 1rem; }
.behavior-wide { grid-column: 1 / -1; }
.behavior-form input, .behavior-form select, .behavior-form textarea { min-width: 0; width: 100%; box-sizing: border-box; }
.behavior-form .behavior-actions { grid-column: 1 / -1; }
.behavior-actions { display: flex; flex-wrap: wrap; gap: .5rem; }
.behavior-entry { padding: 1rem; margin: .75rem 0; border: 1px solid #c5d4ce; border-radius: .6rem; }
.behavior-entry summary { cursor: pointer; }
.behavior-entry summary > span { display: block; margin-top: .3rem; }
.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; } }
+75 -11
View File
@@ -44,6 +44,30 @@ body,
width: 100%;
}
/* Keep the page width steady when switching between short and long tabs. */
html {
overflow-y: scroll;
background-color: #e9ddba;
scrollbar-color: #898b93 transparent;
}
/* Keep native scrollbar tracks from painting a white strip over the page. */
html::-webkit-scrollbar {
width: 14px;
background: transparent;
}
html::-webkit-scrollbar-track {
background: transparent;
}
html::-webkit-scrollbar-thumb {
background-color: #898b93;
border: 3px solid transparent;
background-clip: padding-box;
border-radius: 999px;
}
body {
min-height: 100vh;
color: var(--ink);
@@ -510,11 +534,26 @@ textarea {
text-align: left;
}
/* Background X colors and their lighter tones give every tab a distinct active fill. */
.page-tab[data-tab="overview"] { --tab-active-color: #5bb3b7; }
.page-tab[data-tab="flock"] { --tab-active-color: #7eb773; }
.page-tab[data-tab="settings"] { --tab-active-color: #f3a24a; }
.page-tab[data-tab="admin"] { --tab-active-color: #9698a0; }
.bird-detail-tab[data-tab="info"] { --tab-active-color: #9ed2d4; }
.bird-detail-tab[data-tab="weight"] { --tab-active-color: #b9c945; }
.bird-detail-tab[data-tab="behavior"] { --tab-active-color: #f7c27d; }
.bird-detail-tab[data-tab="notes"] { --tab-active-color: #b4d5ad; }
.bird-detail-tab[data-tab="vet"] { --tab-active-color: #71ad80; }
.bird-detail-tab[data-tab="reports"] { --tab-active-color: #b9bac0; }
.bird-detail-tab[data-tab="timeline"] { --tab-active-color: #d4ba64; }
.bird-detail-tab[data-tab="audit"] { --tab-active-color: #78a8ad; }
.page-tab.active {
background: linear-gradient(135deg, #d89a2f, #3c8f65 58%, #2f8f98);
color: #fffdf9;
border-color: transparent;
background: var(--tab-active-color);
color: var(--ink);
border-color: rgba(31, 42, 42, 0.32);
box-shadow: 0 14px 26px rgba(88, 110, 62, 0.2);
font-weight: 700;
}
.page-tab:hover {
@@ -1562,6 +1601,14 @@ textarea {
transition: border-color 0.2s ease, box-shadow 0.2s ease, color 0.2s ease, transform 0.2s ease;
}
/* Material Symbols Outlined "event", bundled as SVG for the self-only CSP. */
.bird-detail-tab .behavior-tab-icon {
width: 24px;
height: 24px;
fill: currentColor;
stroke: none;
}
.bird-detail-tab svg {
width: 20px;
height: 20px;
@@ -1598,9 +1645,9 @@ textarea {
}
.bird-detail-tab.active {
border-color: rgba(35, 138, 90, 0.42);
background: rgba(240, 248, 244, 0.95);
color: var(--accent-green);
border-color: rgba(31, 42, 42, 0.32);
background: var(--tab-active-color);
color: var(--ink);
box-shadow: 10px 10px 20px rgba(39, 105, 179, 0.1);
}
@@ -1676,11 +1723,12 @@ textarea {
.segmented-control {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(8.5rem, 1fr));
grid-template-columns: repeat(auto-fit, minmax(min(13rem, 100%), 1fr));
gap: 0.55rem;
}
.segmented-option {
min-width: 0;
display: inline-flex;
align-items: center;
justify-content: center;
@@ -1693,6 +1741,17 @@ textarea {
transition: border-color 0.2s ease, box-shadow 0.2s ease, transform 0.2s ease;
}
.segmented-option .gender-symbol,
.segmented-option .gender-source-icon {
flex-shrink: 0;
}
.gender-option-label {
min-width: 0;
white-space: normal;
overflow-wrap: anywhere;
}
.segmented-option.active {
border-color: rgba(35, 138, 90, 0.4);
box-shadow: 0 10px 20px rgba(39, 105, 179, 0.1);
@@ -2761,8 +2820,14 @@ label {
min-width: 520px;
}
.overview-chart-card {
min-height: 230px;
.chart-card.overview-chart-card {
min-height: 0;
overflow: hidden;
}
.overview-chart-card .weight-chart {
min-width: 0;
min-height: 0;
}
.chart-footer {
@@ -2857,7 +2922,6 @@ label {
.inline-form,
.settings-nested-grid,
.education-admin-basics,
.quiz-editor-options,
.dose-schedule-row,
.verified-location-search-row,
@@ -2882,7 +2946,7 @@ label {
}
.segmented-control {
grid-template-columns: repeat(auto-fit, minmax(min(8rem, 100%), 1fr));
grid-template-columns: repeat(auto-fit, minmax(min(13rem, 100%), 1fr));
}
.segmented-option {
@@ -0,0 +1,138 @@
// Optional browser check. Requires Playwright in a disposable frontend install; see docs/BEHAVIOR_JOURNAL.md.
import assert from 'node:assert/strict';
import { randomUUID, createHash } from 'node:crypto';
import { spawn } from 'node:child_process';
import { once } from 'node:events';
import { fileURLToPath } from 'node:url';
import { chromium } from 'playwright';
Object.assign(process.env, {
POSTGRES_HOST: '127.0.0.1', POSTGRES_PORT: '55439', POSTGRES_DB: 'behavior_test', POSTGRES_USER: 'postgres',
POSTGRES_PASSWORD: 'behavior_test_only', PORT: '55440', FRONTEND_URL: 'http://127.0.0.1:55441',
VITE_API_BASE_URL: 'http://127.0.0.1:55440/api',
MILESTONE_REMINDERS_ENABLED: 'false', MEDICATION_REMINDERS_ENABLED: 'false', WEIGHT_REMINDERS_ENABLED: 'false',
});
const { db } = await import('../../backend/dist/db/client.js');
const children = [];
let browser;
let page;
async function start(path, args, marker) {
let output = '';
const child = spawn(process.execPath, [fileURLToPath(path), ...args], { cwd: fileURLToPath(new URL('../', import.meta.url)), env: process.env, stdio: ['ignore', 'pipe', 'pipe'] });
children.push(child);
child.stdout.on('data', (data) => { output += data; }); child.stderr.on('data', (data) => { output += data; });
for (let i = 0; i < 100 && !output.includes(marker); i++) await new Promise((resolve) => setTimeout(resolve, 100));
assert.ok(output.includes(marker), output);
}
try {
const workspace = 100000 + Math.floor(Math.random() * 1000000000);
const user = randomUUID(), bird = randomUUID(), secondBird = randomUUID(), token = randomUUID();
await db.query(`INSERT INTO workspaces (id, name, workspace_type, rescue_verification_status) VALUES ($1, 'Browser test', 'rescue', 'approved')`, [workspace]);
await db.query(`INSERT INTO users (id, email, name) VALUES ($1, $2, 'Browser tester')`, [user, `${user}@example.test`]);
await db.query(`INSERT INTO workspace_members (workspace_id, user_id, invite_email, name, role, accepted_at) VALUES ($1, $2, $3, 'Browser tester', 'owner', NOW())`, [workspace, user, `${user}@example.test`]);
await db.query(`INSERT INTO auth_sessions (user_id, active_workspace_id, token_hash, expires_at) VALUES ($1, $2, $3, NOW() + INTERVAL '1 hour')`, [user, workspace, createHash('sha256').update(token).digest('hex')]);
await db.query(`INSERT INTO birds (id, workspace_id, name, species) VALUES ($1, $2, 'Piper', 'Parrot'), ($3, $2, 'Willow', 'Parrot')`, [bird, workspace, secondBird]);
const type = (await db.query(`SELECT id FROM behavior_types WHERE is_default ORDER BY name LIMIT 1`)).rows[0].id;
for (const timestamp of ['2026-10-01T03:59:59Z', '2026-10-01T04:00:00Z', '2026-11-01T05:30:00Z', '2026-11-01T06:30:00Z']) {
await db.query(`INSERT INTO behavior_occurrences (bird_id, behavior_type_id, occurred_at) VALUES ($1, $2, $3)`, [bird, type, timestamp]);
}
await start(new URL('../../backend/dist/app.js', import.meta.url), [], 'listening');
await start(new URL('../node_modules/vite/bin/vite.js', import.meta.url), ['--host', '127.0.0.1', '--port', '55441'], 'Local:');
browser = await chromium.launch({ headless: true });
const context = await browser.newContext({ timezoneId: 'America/New_York', viewport: { width: 1280, height: 1000 } });
page = await context.newPage();
const errors = []; page.on('pageerror', (e) => errors.push(e.message));
await page.addInitScript((value) => localStorage.setItem('flockpal_auth_token', value), token);
await page.clock.setFixedTime(new Date('2026-10-05T16:00:00Z'));
await page.goto('http://127.0.0.1:55441');
await page.getByRole('button', { name: 'Flock', exact: true }).click();
await page.locator('.bird-card-select').filter({ hasText: 'Piper' }).click();
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.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');
await journal.getByLabel('Custom behavior name').fill('Wing stretching');
await journal.getByLabel('Description (optional)').fill('Wings extended');
await journal.getByLabel('Date and time', { exact: true }).fill('2026-10-05T23:30:12');
await journal.getByLabel('Duration in seconds (optional)').fill('90');
await journal.getByLabel('Intensity (optional)').selectOption('3');
await journal.getByLabel('Notes (optional)').fill('Observed after play');
await journal.getByRole('button', { name: 'Save occurrence' }).click();
await journal.getByText('Occurrence saved.', { exact: true }).waitFor();
await journal.getByRole('button', { name: 'Record behavior' }).click();
await journal.getByLabel('Behavior', { exact: true }).selectOption({ label: 'Wing stretching' });
await journal.getByLabel('Date and time', { exact: true }).fill('2026-10-05T22:00');
await journal.getByRole('button', { name: 'Save occurrence' }).click();
await journal.getByText('3 occurrences this month', { exact: true }).waitFor();
const day = journal.getByRole('button', { name: '10/5/2026: 2 occurrences', exact: true });
await day.click(); assert.equal(await journal.locator('details').count(), 2);
const entry = journal.locator('details').filter({ hasText: 'Observed after play' });
await entry.locator('summary').click();
await entry.getByRole('button', { name: 'Edit', exact: true }).click();
await journal.getByLabel('Notes (optional)').fill('Edited observation');
await journal.getByRole('button', { name: 'Save occurrence' }).click();
await journal.getByText('Edited observation', { exact: true }).first().waitFor();
await journal.getByLabel('Show behavior', { exact: true }).selectOption({ label: 'Wing stretching' });
await journal.getByText('2 occurrences this month', { exact: true }).waitFor();
await journal.getByRole('button', { name: 'Next month' }).click();
await journal.getByText('0 occurrences this month', { exact: true }).waitFor();
await journal.getByLabel('Show behavior', { exact: true }).selectOption('');
await journal.getByText('2 occurrences this month', { exact: true }).waitFor();
await journal.getByRole('button', { name: '11/1/2026: 2 occurrences', exact: true }).click();
assert.equal(await journal.locator('details').count(), 2); // Both sides of fall-back belong to Nov 1.
await journal.locator('details').first().locator('summary').click();
await journal.locator('details').first().getByRole('button', { name: 'Edit', exact: true }).click();
await journal.getByLabel('Notes (optional)').fill('Later repeated hour retained');
await journal.getByRole('button', { name: 'Save occurrence' }).click();
await journal.getByText('Occurrence saved.', { exact: true }).waitFor();
const repeated = (await db.query(`SELECT occurred_at FROM behavior_occurrences WHERE bird_id = $1 AND notes = 'Later repeated hour retained'`, [bird])).rows[0];
assert.equal(repeated.occurred_at.toISOString(), '2026-11-01T06:30:00.000Z');
await journal.getByRole('button', { name: 'Previous month' }).click();
await journal.getByRole('button', { name: 'Previous month' }).click();
await journal.getByText('1 occurrence this month', { exact: true }).waitFor(); // UTC Oct 1 before local midnight.
await journal.getByRole('button', { name: 'Next month' }).click();
await journal.getByRole('button', { name: '10/5/2026: 2 occurrences', exact: true }).click();
await page.setViewportSize({ width: 390, height: 844 });
await journal.scrollIntoViewIfNeeded();
await page.screenshot({ path: '/tmp/flockpal-behavior-mobile.png', fullPage: true });
assert.equal(await journal.evaluate((element) => element.scrollWidth <= element.clientWidth + 1), true, 'Journal must fit mobile width');
const editedEntry = journal.locator('details').filter({ hasText: 'Edited observation' });
await editedEntry.locator('summary').click();
page.once('dialog', (dialog) => dialog.accept());
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 journal.getByText('0 occurrences this month', { exact: true }).waitFor();
await journal.getByLabel('Bird', { exact: true }).selectOption(bird);
await journal.getByText('2 occurrences this month', { exact: true }).waitFor();
await page.setViewportSize({ width: 1280, height: 1000 });
await journal.scrollIntoViewIfNeeded();
await page.screenshot({ path: '/tmp/flockpal-behavior-desktop.png', fullPage: true });
const utcContext = await browser.newContext({ timezoneId: 'UTC', viewport: { width: 1280, height: 1000 } });
const utcPage = await utcContext.newPage();
await utcPage.addInitScript((value) => localStorage.setItem('flockpal_auth_token', value), token);
await utcPage.clock.setFixedTime(new Date('2026-10-05T16:00:00Z'));
await utcPage.goto('http://127.0.0.1:55441');
await utcPage.getByRole('button', { name: 'Flock', exact: true }).click();
await utcPage.locator('.bird-card-select').filter({ hasText: 'Piper' }).click();
await utcPage.getByRole('tab', { name: 'Behavior Journal' }).click();
const utcJournal = utcPage.getByRole('tabpanel', { name: 'Behavior Journal' });
await utcJournal.getByText('3 occurrences this month', { exact: true }).waitFor();
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.');
} catch (error) {
if (page) {
console.error(await page.locator('.behavior-journal').innerText().catch(() => 'Journal unavailable'));
await page.screenshot({ path: '/tmp/flockpal-behavior-failure.png', fullPage: true });
}
throw error;
} finally {
if (browser) await browser.close();
for (const child of children.reverse()) if (child.exitCode === null) { const done = once(child, 'exit'); child.kill('SIGTERM'); await done; }
await db.close();
}
@@ -0,0 +1,91 @@
// Optional browser integration check; use the disposable setup in docs/BIRD_MEMBERSHIP.md.
import assert from 'node:assert/strict';
import { randomUUID, createHash } from 'node:crypto';
import { spawn } from 'node:child_process';
import { once } from 'node:events';
import { fileURLToPath } from 'node:url';
import { chromium } from 'playwright';
Object.assign(process.env, {
POSTGRES_HOST: '127.0.0.1', POSTGRES_PORT: '55439', POSTGRES_DB: 'behavior_test', POSTGRES_USER: 'postgres',
POSTGRES_PASSWORD: 'behavior_test_only', PORT: '55440', FRONTEND_URL: 'http://127.0.0.1:55441',
VITE_API_BASE_URL: 'http://127.0.0.1:55440/api',
MILESTONE_REMINDERS_ENABLED: 'false', MEDICATION_REMINDERS_ENABLED: 'false', WEIGHT_REMINDERS_ENABLED: 'false',
});
const { db } = await import('../../backend/dist/db/client.js');
const children = [];
let browser;
async function start(path, args, marker) {
let output = '';
const child = spawn(process.execPath, [fileURLToPath(path), ...args], { cwd: fileURLToPath(new URL('../', import.meta.url)), env: process.env, stdio: ['ignore', 'pipe', 'pipe'] });
children.push(child);
child.stdout.on('data', (data) => { output += data; }); child.stderr.on('data', (data) => { output += data; });
for (let i = 0; i < 100 && !output.includes(marker); i++) await new Promise((resolve) => setTimeout(resolve, 100));
assert.ok(output.includes(marker), output);
}
try {
const accounts = [];
const baseId = 100000 + Math.floor(Math.random() * 1000000000);
for (let i = 0; i < 2; i++) {
const workspace = baseId + i, user = randomUUID(), token = randomUUID(), email = `${user}@example.test`;
await db.query(`INSERT INTO workspaces (id, name, workspace_type, rescue_verification_status) VALUES ($1, $2, 'rescue', 'approved')`, [workspace, `Browser membership ${i}`]);
await db.query(`INSERT INTO users (id, email, name) VALUES ($1, $2, 'Browser tester')`, [user, email]);
await db.query(`INSERT INTO workspace_members (workspace_id, user_id, invite_email, name, role, accepted_at) VALUES ($1, $2, $3, 'Browser tester', 'owner', NOW())`, [workspace, user, email]);
await db.query(`INSERT INTO auth_sessions (user_id, active_workspace_id, token_hash, expires_at) VALUES ($1, $2, $3, NOW() + INTERVAL '1 hour')`, [user, workspace, createHash('sha256').update(token).digest('hex')]);
accounts.push({ workspace, token });
}
const [source, destination] = accounts;
const bird = randomUUID(), tagId = `FP-${randomUUID()}`;
await db.query(`INSERT INTO birds (id, workspace_id, name, tag_id, species) VALUES ($1, $2, 'Piper', $3, 'Parrot')`, [bird, source.workspace, tagId]);
await db.query(`INSERT INTO weight_records (bird_id, weight_grams, recorded_on) VALUES ($1, 120, CURRENT_DATE)`, [bird]);
await db.query(`INSERT INTO flock_notes (workspace_id, bird_id, title, body) VALUES ($1, $2, 'Existing note', 'Enjoys morning play')`, [source.workspace, bird]);
await start(new URL('../../backend/dist/app.js', import.meta.url), [], 'listening');
await start(new URL('../node_modules/vite/bin/vite.js', import.meta.url), ['--host', '127.0.0.1', '--port', '55441'], 'Local:');
browser = await chromium.launch({ headless: true });
const sourcePage = await browser.newPage({ viewport: { width: 1280, height: 1000 } });
await sourcePage.addInitScript((value) => localStorage.setItem('flockpal_auth_token', value), source.token);
await sourcePage.goto('http://127.0.0.1:55441', { waitUntil: 'domcontentloaded' });
await sourcePage.getByRole('button', { name: 'Flock', exact: true }).click();
await sourcePage.locator('.bird-card-select').filter({ hasText: 'Piper' }).click();
await sourcePage.getByRole('button', { name: 'Edit details for Piper' }).click();
sourcePage.once('dialog', async (dialog) => { assert.match(dialog.message(), /history will be retained/); await dialog.accept(); });
await sourcePage.getByRole('button', { name: 'Remove from flock', exact: true }).click();
await sourcePage.locator('.bird-card-select').filter({ hasText: 'Piper' }).waitFor({ state: 'detached' });
assert.equal((await db.query(`SELECT workspace_id FROM birds WHERE id = $1`, [bird])).rows[0].workspace_id, null);
const page = await browser.newPage({ viewport: { width: 390, height: 844 } });
const pageErrors = []; page.on('pageerror', (error) => pageErrors.push(error.message));
await page.addInitScript((value) => localStorage.setItem('flockpal_auth_token', value), destination.token);
await page.goto('http://127.0.0.1:55441', { waitUntil: 'domcontentloaded' });
await page.getByRole('button', { name: 'Flock', exact: true }).click();
await page.getByRole('button', { name: 'Add bird', exact: true }).click();
const bandInput = page.getByLabel('Band ID, if known', { exact: true });
await bandInput.fill(tagId.slice(0, -1));
await page.getByText('Checking band ID for existing history…').waitFor({ state: 'hidden' });
assert.equal(await page.getByRole('button', { name: 'Add bird with existing history' }).count(), 0);
await bandInput.fill(` ${tagId.toLowerCase()} `);
const claimButton = page.getByRole('button', { name: 'Add bird with existing history' });
await claimButton.waitFor();
assert.equal(await page.getByRole('button', { name: 'Save bird profile', exact: true }).isDisabled(), true);
const notice = page.getByRole('status').filter({ hasText: 'This band ID matches' });
assert.equal(await notice.evaluate((element) => element.scrollWidth <= element.clientWidth), true);
await notice.screenshot({ path: '/tmp/flockpal-existing-history-notice.png' });
page.once('dialog', async (dialog) => { assert.match(dialog.message(), /history will be brought in/); await dialog.dismiss(); });
await claimButton.click();
assert.equal((await db.query(`SELECT workspace_id FROM birds WHERE id = $1`, [bird])).rows[0].workspace_id, null);
// Only a band ID is needed: no replacement name or species should be required to claim history.
assert.equal(await page.getByLabel('Bird name', { exact: true }).inputValue(), '');
page.on('dialog', (dialog) => dialog.accept());
await claimButton.click();
await page.getByRole('tab', { name: 'Weight', exact: true }).waitFor();
assert.equal((await db.query(`SELECT workspace_id FROM birds WHERE id = $1`, [bird])).rows[0].workspace_id, destination.workspace);
assert.equal((await db.query(`SELECT COUNT(*)::int AS count FROM birds WHERE LOWER(tag_id) = LOWER($1)`, [tagId])).rows[0].count, 1);
await page.getByRole('tab', { name: 'Notes', exact: true }).click();
await page.getByText('Enjoys morning play', { exact: true }).waitFor();
await page.getByRole('tab', { name: 'Timeline', exact: true }).click();
await page.getByText('Joined flock with history', { exact: true }).first().waitFor();
assert.deepEqual(pageErrors, []);
console.log('PASS: desktop removal retains history; mobile exact band match notice, cancellation, confirmation, claim without replacement fields, and restored notes/timeline.');
} finally {
if (browser) await browser.close();
for (const child of children.reverse()) if (child.exitCode === null) { const done = once(child, 'exit'); child.kill('SIGTERM'); await done; }
await db.close();
}