5 Commits
Author SHA1 Message Date
Corey Blais 138ea78ec7 Return dependency readiness from the public API health endpoint
Deploy / deploy-dev (push) Skipped
Deploy / deploy-prod (push) Successful in 2m43s
2026-10-22 09:31:25 -04:00
blaisadmin 474b54e6ec SEO improvements
Deploy / deploy-dev (push) Skipped
Deploy / deploy-prod (push) Successful in 3m18s
2026-10-11 19:54:37 -04:00
blaisadmin c8eb9bc862 Merge remote-tracking branch 'origin/main'
Deploy / deploy-dev (push) Skipped
Deploy / deploy-prod (push) Successful in 4m3s
2026-10-09 23:42:16 -04:00
blaisadmin 7397b85e69 updated behavior journal 2026-10-09 23:41:41 -04:00
Corey Blais 693a30f437 Invites and fixed image caching
Deploy / deploy-dev (push) Skipped
Deploy / deploy-prod (push) Successful in 3m57s
2026-10-09 20:16:22 -04:00
18 changed files with 356 additions and 47 deletions

No files matched your search

+3 -2
View File
@@ -55,8 +55,9 @@ Monitor these production checks:
- Verifies Nginx is serving the frontend container. - Verifies Nginx is serving the frontend container.
- Backend liveness: `GET https://your-host/api/health/live` - Backend liveness: `GET https://your-host/api/health/live`
- Verifies the API process is running. - Verifies the API process is running.
- Backend readiness: `GET https://your-host/api/health/ready` - Application health: `GET https://your-host/api/health` (alias: `/api/health/ready`)
- Verifies the API can reach Postgres and Redis. Returns `503` if either dependency is unavailable. - Use this endpoint for application availability monitoring. Verifies Postgres and Redis, returning HTTP `503` if a check fails or exceeds four seconds, and HTTP `200` only when all checks pass. Responses are not cacheable.
- Connection failures and timeouts also mean unavailable: during a startup database failure, the API may not be listening at all.
- Backend metrics: `GET https://your-host/api/metrics` - Backend metrics: `GET https://your-host/api/metrics`
- Admin-authenticated process, request, and queue metrics. - Admin-authenticated process, request, and queue metrics.
- Postgres and Redis: - Postgres and Redis:
+14 -19
View File
@@ -1,3 +1,5 @@
import { createReadinessHandler } from './health/readiness.js';
import { photoCacheControl } from './storage/photoCache.js';
import { canUpdateWorkspaceSettings, subscriptionAllowsWrite } from './workspaceAccess.js'; import { canUpdateWorkspaceSettings, subscriptionAllowsWrite } from './workspaceAccess.js';
import { buildWorkspaceInviteEmail } from './emails/workspaceInviteEmail.js'; import { buildWorkspaceInviteEmail } from './emails/workspaceInviteEmail.js';
import { exportFlock } from './repositories/flockExportRepository.js'; import { exportFlock } from './repositories/flockExportRepository.js';
@@ -2209,28 +2211,19 @@ const writeBirdTimelineEvent = async ({
} }
}; };
app.get('/api/health', (_req: Request, res: Response) => { const readinessHandler = createReadinessHandler([
res.json({ ok: true }); () => db.query('SELECT 1'),
}); () => getBirdMilestoneReminderQueueCounts(),
() => getMedicationReminderQueueCounts(),
]);
app.get(['/api/health', '/api/health/ready'], readinessHandler);
app.get('/api/health/live', (_req: Request, res: Response) => { app.get('/api/health/live', (_req: Request, res: Response) => {
res.set('Cache-Control', 'no-store');
res.json({ ok: true, status: 'live' }); res.json({ ok: true, status: 'live' });
}); });
app.get('/api/health/ready', async (_req: Request, res: Response) => {
try {
await Promise.all([
db.query('SELECT 1'),
getBirdMilestoneReminderQueueCounts(),
getMedicationReminderQueueCounts(),
]);
res.json({ ok: true, status: 'ready' });
} catch (error) {
console.error('Readiness check failed', error);
res.status(503).json({ ok: false, status: 'not_ready' });
}
});
app.get('/api/metrics', requireAuth, requireAdmin, async (_req: Request, res: Response, next: NextFunction) => { app.get('/api/metrics', requireAuth, requireAdmin, async (_req: Request, res: Response, next: NextFunction) => {
const memoryUsage = process.memoryUsage(); const memoryUsage = process.memoryUsage();
const averageDurationMs = requestMetrics.totalRequests > 0 ? requestMetrics.totalDurationMs / requestMetrics.totalRequests : 0; const averageDurationMs = requestMetrics.totalRequests > 0 ? requestMetrics.totalDurationMs / requestMetrics.totalRequests : 0;
@@ -3496,6 +3489,8 @@ app.post(
); );
app.get('/api/birds/:birdId/photo', async (req: Request, res: Response, next: NextFunction) => { app.get('/api/birds/:birdId/photo', async (req: Request, res: Response, next: NextFunction) => {
// Invalid tokens, missing photos and upstream failures must never be cached.
res.setHeader('Cache-Control', 'no-store');
try { try {
const token = typeof req.query.token === 'string' ? req.query.token : ''; const token = typeof req.query.token === 'string' ? req.query.token : '';
const photoAccess = verifyBirdPhotoAccessToken(token); const photoAccess = verifyBirdPhotoAccessToken(token);
@@ -3525,9 +3520,8 @@ app.get('/api/birds/:birdId/photo', async (req: Request, res: Response, next: Ne
expiresInSeconds: 5 * 60, expiresInSeconds: 5 * 60,
}); });
res.setHeader('Cache-Control', 'private, max-age=900');
if (photoDeliveryMode === 'redirect') { if (photoDeliveryMode === 'redirect') {
res.setHeader('Cache-Control', photoCacheControl('redirect', photoAccess.expiresAt));
res.redirect(302, signedUrl); res.redirect(302, signedUrl);
return; return;
} }
@@ -3543,6 +3537,7 @@ app.get('/api/birds/:birdId/photo', async (req: Request, res: Response, next: Ne
const contentLength = imageResponse.headers.get('content-length'); const contentLength = imageResponse.headers.get('content-length');
const imageBuffer = Buffer.from(await imageResponse.arrayBuffer()); const imageBuffer = Buffer.from(await imageResponse.arrayBuffer());
res.setHeader('Cache-Control', photoCacheControl('proxy', photoAccess.expiresAt));
res.setHeader('Content-Type', contentType); res.setHeader('Content-Type', contentType);
if (contentLength) { if (contentLength) {
+2 -2
View File
@@ -15,8 +15,8 @@ export const behaviorRangeSchema = z.object({
from: z.string().datetime({ offset: true }), from: z.string().datetime({ offset: true }),
to: z.string().datetime({ offset: true }), to: z.string().datetime({ offset: true }),
behaviorTypeId: z.string().uuid().optional(), behaviorTypeId: z.string().uuid().optional(),
}).refine(({ from, to }) => Date.parse(to) > Date.parse(from) && Date.parse(to) - Date.parse(from) <= 32 * 86400000, { }).refine(({ from, to }) => Date.parse(to) > Date.parse(from) && Date.parse(to) - Date.parse(from) <= 366 * 86400000, {
message: 'Choose a date range of up to 32 days, with to after from.', message: 'Choose a date range of up to 366 days, with to after from.',
}); });
export type BehaviorInput = z.infer<typeof behaviorOccurrenceSchema>; export type BehaviorInput = z.infer<typeof behaviorOccurrenceSchema>;
+1 -1
View File
@@ -108,7 +108,7 @@ const behaviorResponse = registry.register('BehaviorOccurrence', z.object({
})); }));
endpoint({ method: 'get', path: '/birds/{birdId}/behavior-types', summary: 'List available behavior types', tag: 'Behavior Journal', response: many('behaviorTypes', behaviorTypeResponse), errors: [400, 404], description: 'Includes common behaviors, flock custom behaviors, and behaviors in this bird’s transferred history.' }); endpoint({ method: 'get', path: '/birds/{birdId}/behavior-types', summary: 'List available behavior types', tag: 'Behavior Journal', response: many('behaviorTypes', behaviorTypeResponse), errors: [400, 404], description: 'Includes common behaviors, flock custom behaviors, and behaviors in this bird’s transferred history.' });
endpoint({ method: 'post', path: '/birds/{birdId}/behavior-types', summary: 'Create a reusable flock behavior type', tag: 'Behavior Journal', body: behaviorTypeSchema, response: one('behaviorType', behaviorTypeResponse), errors: [404, 409], description: 'Names are unique within the flock, ignoring case. An existing type is returned for a duplicate name.' }); endpoint({ method: 'post', path: '/birds/{birdId}/behavior-types', summary: 'Create a reusable flock behavior type', tag: 'Behavior Journal', body: behaviorTypeSchema, response: one('behaviorType', behaviorTypeResponse), errors: [404, 409], description: 'Names are unique within the flock, ignoring case. An existing type is returned for a duplicate name.' });
endpoint({ method: 'get', path: '/birds/{birdId}/behaviors', summary: 'List behavior occurrences in a date range', tag: 'Behavior Journal', response: many('occurrences', behaviorResponse), query: z.object({ from: z.string().datetime({ offset: true }), to: z.string().datetime({ offset: true }), behaviorTypeId: z.string().uuid().optional() }), errors: [404], description: 'From is inclusive; to is exclusive. The range must be positive and at most 32 days. Send local month boundaries with their UTC offsets or converted to UTC. Results are newest first; individual events are never aggregated.' }); endpoint({ method: 'get', path: '/birds/{birdId}/behaviors', summary: 'List behavior occurrences in a date range', tag: 'Behavior Journal', response: many('occurrences', behaviorResponse), query: z.object({ from: z.string().datetime({ offset: true }), to: z.string().datetime({ offset: true }), behaviorTypeId: z.string().uuid().optional() }), errors: [404], description: 'From is inclusive; to is exclusive. The range must be positive and at most 366 days. Send local date boundaries with their UTC offsets or converted to UTC. Results are newest first; individual events are never aggregated.' });
endpoint({ method: 'post', path: '/birds/{birdId}/behaviors', summary: 'Record a behavior occurrence', tag: 'Behavior Journal', body: behaviorOccurrenceSchema, response: one('occurrence', behaviorResponse), errors: [404, 409], description: 'Duration is optional and measured in seconds. Intensity is optional, from 1 to 5. Occurrence timestamps require a time zone offset.' }); endpoint({ method: 'post', path: '/birds/{birdId}/behaviors', summary: 'Record a behavior occurrence', tag: 'Behavior Journal', body: behaviorOccurrenceSchema, response: one('occurrence', behaviorResponse), errors: [404, 409], description: 'Duration is optional and measured in seconds. Intensity is optional, from 1 to 5. Occurrence timestamps require a time zone offset.' });
endpoint({ method: 'put', path: '/birds/{birdId}/behaviors/{occurrenceId}', summary: 'Edit a behavior occurrence', tag: 'Behavior Journal', body: behaviorOccurrenceSchema, response: one('occurrence', behaviorResponse), errors: [404, 409] }); endpoint({ method: 'put', path: '/birds/{birdId}/behaviors/{occurrenceId}', summary: 'Edit a behavior occurrence', tag: 'Behavior Journal', body: behaviorOccurrenceSchema, response: one('occurrence', behaviorResponse), errors: [404, 409] });
endpoint({ method: 'delete', path: '/birds/{birdId}/behaviors/{occurrenceId}', summary: 'Delete a behavior occurrence', tag: 'Behavior Journal', errors: [400, 404, 409] }); endpoint({ method: 'delete', path: '/birds/{birdId}/behaviors/{occurrenceId}', summary: 'Delete a behavior occurrence', tag: 'Behavior Journal', errors: [400, 404, 409] });
+38
View File
@@ -0,0 +1,38 @@
import assert from 'node:assert/strict';
import { test } from 'node:test';
import type { Request, Response } from 'express';
import { createReadinessHandler } from './readiness.js';
async function probe(checks: Array<() => Promise<unknown>>) {
const result = { code: 0, cache: '', body: {} };
const response = {
set(_name: string, value: string) { result.cache = value; return this; },
status(code: number) { result.code = code; return this; },
json(body: unknown) { result.body = body as object; return this; },
} as unknown as Response;
await createReadinessHandler(checks, 20, () => {} )({} as Request, response);
return result;
}
test('healthy dependencies return uncached HTTP 200', async () => {
const result = await probe([async () => 1, async () => ({})]);
assert.equal(result.code, 200);
assert.equal(result.cache, 'no-store');
assert.deepEqual(result.body, { ok: true, status: 'ready' });
});
for (const dependency of ['postgres', 'redis']) {
test(`${dependency} failure returns HTTP 503`, async () => {
const checks = [async () => 1, async () => 1];
checks[dependency === 'postgres' ? 0 : 1] = async () => { throw new Error('unavailable'); };
const result = await probe(checks);
assert.equal(result.code, 503);
assert.equal(result.cache, 'no-store');
assert.deepEqual(result.body, { ok: false, status: 'not_ready' });
});
}
test('unresponsive dependencies return HTTP 503 within the deadline', async () => {
const result = await probe([() => new Promise(() => {})]);
assert.equal(result.code, 503);
});
+25
View File
@@ -0,0 +1,25 @@
import type { Request, Response } from 'express';
/** Dependency readiness shared by the public health and readiness endpoints. */
export const createReadinessHandler = (
checks: Array<() => Promise<unknown>>,
timeoutMs = 4000,
reportError: (error: unknown) => void = (error) => console.error('Readiness check failed', error),
) => async (_req: Request, res: Response) => {
res.set('Cache-Control', 'no-store');
let timer: ReturnType<typeof setTimeout> | undefined;
try {
await Promise.race([
Promise.all(checks.map((check) => Promise.resolve().then(check))),
new Promise<never>((_resolve, reject) => {
timer = setTimeout(() => reject(new Error('Readiness dependencies timed out')), timeoutMs);
}),
]);
res.status(200).json({ ok: true, status: 'ready' });
} catch (error) {
reportError(error);
res.status(503).json({ ok: false, status: 'not_ready' });
} finally {
clearTimeout(timer);
}
};
+13
View File
@@ -0,0 +1,13 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { photoCacheControl } from './photoCache.js';
test('storage redirects cannot be cached beyond the signed destination lifetime', () => {
assert.equal(photoCacheControl('redirect', 1900, 1000), 'no-store');
});
test('proxy caching is bounded by the remaining app token lifetime', () => {
assert.equal(photoCacheControl('proxy', 1900, 1000), 'private, max-age=900, must-revalidate');
assert.equal(photoCacheControl('proxy', 1050, 1000), 'private, max-age=50, must-revalidate');
assert.equal(photoCacheControl('proxy', 999, 1000), 'private, max-age=0, must-revalidate');
});
+4
View File
@@ -0,0 +1,4 @@
// Never cache a redirect to a signed storage URL: its lifetime is independent of
// the app token. Successful proxy responses cannot outlive the app token.
export const photoCacheControl = (mode: 'proxy' | 'redirect', expiresAt: number, now = Math.floor(Date.now() / 1000)) =>
mode === 'redirect' ? 'no-store' : `private, max-age=${Math.max(0, Math.min(900, expiresAt - now))}, must-revalidate`;
+20
View File
@@ -0,0 +1,20 @@
import assert from 'node:assert/strict';
import { test } from 'node:test';
import { behaviorRangeSchema } from '../behaviorSchemas.js';
test('behavior ranges span months and include a full leap year', () => {
for (const range of [
{ from: '2026-09-30T00:00:00-04:00', to: '2026-11-02T00:00:00-05:00' },
{ from: '2024-01-01T00:00:00Z', to: '2025-01-01T00:00:00Z' },
{ from: '2026-11-01T00:00:00-04:00', to: '2026-11-02T00:00:00-05:00' },
]) assert.equal(behaviorRangeSchema.safeParse(range).success, true);
});
test('behavior ranges reject invalid, reversed, empty, and oversized intervals', () => {
for (const range of [
{ from: 'invalid', to: 'invalid' },
{ from: '2026-10-02T00:00:00Z', to: '2026-10-01T00:00:00Z' },
{ from: '2026-10-01T00:00:00Z', to: '2026-10-01T00:00:00Z' },
{ from: '2024-01-01T00:00:00Z', to: '2025-01-01T00:00:01Z' },
]) assert.equal(behaviorRangeSchema.safeParse(range).success, false);
});
+5 -3
View File
@@ -2,7 +2,9 @@
Open **Flock → select a bird → Behavior Journal** (calendar tab). Select a behavior or create a custom one, confirm the current date/time, and save. Duration in seconds, intensity from 1–5, and notes are optional. Open a day's occurrence to see its details, edit it, or delete it with confirmation. Open **Flock → select a bird → Behavior Journal** (calendar tab). Select a behavior or create a custom one, confirm the current date/time, and save. Duration in seconds, intensity from 1–5, and notes are optional. Open a day's occurrence to see its details, edit it, or delete it with confirmation.
The bird and behavior selectors filter the journal. The calendar displays one month at a time, daily counts and up to three dots (plus a `+` for additional events). Select a day to review its individual events. The count above the calendar reflects the selected behavior and displayed month. Each flock member has their own journal, which automatically uses the bird whose profile is open. The behavior selector filters that member’s entries. The calendar displays one month at a time, daily counts and up to three dots (plus a `+` for additional events). Select a day to review its individual events. The count above the calendar reflects the selected behavior and displayed month.
Choose **Date range** in the View selector to review entries across months. Start and end dates are inclusive in your local time zone, with ranges up to 366 days. Matching entries appear newest first and still support behavior filtering, editing, and deletion. Switch back to **Monthly calendar** for daily counts. Saving an entry outside the selected range moves the range to its date so the saved entry is visible.
## Storage and access ## Storage and access
@@ -24,7 +26,7 @@ The interactive API reference includes these endpoints:
| --- | --- | --- | | --- | --- | --- |
| GET | `/api/birds/:birdId/behavior-types` | Available default, flock, and transferred-history types | | GET | `/api/birds/:birdId/behavior-types` | Available default, flock, and transferred-history types |
| POST | `/api/birds/:birdId/behavior-types` | Create/reuse a custom type (`name`, optional `description`) | | POST | `/api/birds/:birdId/behavior-types` | Create/reuse a custom type (`name`, optional `description`) |
| GET | `/api/birds/:birdId/behaviors?from=…&to=…&behaviorTypeId=…` | Events in a positive range of at most 32 days; optional type filter | | GET | `/api/birds/:birdId/behaviors?from=…&to=…&behaviorTypeId=…` | Events in a positive range of at most 366 days; optional type filter |
| POST | `/api/birds/:birdId/behaviors` | Create an occurrence | | POST | `/api/birds/:birdId/behaviors` | Create an occurrence |
| PUT | `/api/birds/:birdId/behaviors/:occurrenceId` | Replace the editable fields | | PUT | `/api/birds/:birdId/behaviors/:occurrenceId` | Replace the editable fields |
| DELETE | `/api/birds/:birdId/behaviors/:occurrenceId` | Delete an occurrence | | DELETE | `/api/birds/:birdId/behaviors/:occurrenceId` | Delete an occurrence |
@@ -59,7 +61,7 @@ npx playwright install chromium
node test-integration/behaviorJournal.mjs node test-integration/behaviorJournal.mjs
``` ```
The browser check starts and stops its own API and Vite server (port 55441). It covers the complete entry/custom behavior/edit/delete workflow, bird and behavior filters, day selection and daily counts, month navigation, local midnight and daylight-saving boundaries, and a 390px mobile layout. It writes screenshots to `/tmp/flockpal-behavior-mobile.png` and `/tmp/flockpal-behavior-desktop.png`. The browser check starts and stops its own API and Vite server (port 55441). It covers the complete entry/custom behavior/edit/delete workflow, switching between member journals, behavior filters, day selection and daily counts, month navigation, local midnight and daylight-saving boundaries, and a 390px mobile layout. It writes screenshots to `/tmp/flockpal-behavior-mobile.png` and `/tmp/flockpal-behavior-desktop.png`.
After verification, stop only the disposable database: After verification, stop only the disposable database:
+19 -2
View File
@@ -8,10 +8,27 @@
type="image/svg+xml" type="image/svg+xml"
href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 64 64'%3E%3Cdefs%3E%3ClinearGradient id='featherFill' x1='0%25' y1='0%25' x2='100%25' y2='100%25'%3E%3Cstop offset='0%25' stop-color='%23cb3a35'/%3E%3Cstop offset='30%25' stop-color='%23f0b63f'/%3E%3Cstop offset='58%25' stop-color='%23238a5a'/%3E%3Cstop offset='100%25' stop-color='%232769b3'/%3E%3C/linearGradient%3E%3C/defs%3E%3Cpath d='M50.8 10.4C37.9 10.3 27 18.5 22.7 31.1c-3.1 9.1-2.1 18.5-8.6 24.8c-1.5 1.5-0.2 4 1.9 3.6c8.4-1.5 14.6-6.7 18.6-13.7c1 0.5 2.2 0.8 3.4 0.8c3.5 0 6.5-2.3 7.5-5.4c1.9-0.4 3.7-1.3 5.1-2.7c2-2 3-4.6 3.1-7.2c3.3-5.8 4.9-12.9 1.4-20.2c-0.7-1.3-2-0.7-4.3-0.7Z' fill='url(%23featherFill)'/%3E%3Cpath d='M18 56c8.5-3.4 14.2-9.8 18.1-17.8M26.9 48.9c6.9-7.2 13.5-14.8 20.3-22.1M31.8 41.2c6.4-1.3 12.1-4.6 16.5-9.4M36.8 33.8c4.9-0.9 9.2-3.4 12.6-7.1' fill='none' stroke='%23fff8ef' stroke-linecap='round' stroke-width='2.6'/%3E%3Cpath d='M18 56c8.5-3.4 14.2-9.8 18.1-17.8' fill='none' stroke='%2363562d' stroke-linecap='round' stroke-width='2.2'/%3E%3C/svg%3E" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 64 64'%3E%3Cdefs%3E%3ClinearGradient id='featherFill' x1='0%25' y1='0%25' x2='100%25' y2='100%25'%3E%3Cstop offset='0%25' stop-color='%23cb3a35'/%3E%3Cstop offset='30%25' stop-color='%23f0b63f'/%3E%3Cstop offset='58%25' stop-color='%23238a5a'/%3E%3Cstop offset='100%25' stop-color='%232769b3'/%3E%3C/linearGradient%3E%3C/defs%3E%3Cpath d='M50.8 10.4C37.9 10.3 27 18.5 22.7 31.1c-3.1 9.1-2.1 18.5-8.6 24.8c-1.5 1.5-0.2 4 1.9 3.6c8.4-1.5 14.6-6.7 18.6-13.7c1 0.5 2.2 0.8 3.4 0.8c3.5 0 6.5-2.3 7.5-5.4c1.9-0.4 3.7-1.3 5.1-2.7c2-2 3-4.6 3.1-7.2c3.3-5.8 4.9-12.9 1.4-20.2c-0.7-1.3-2-0.7-4.3-0.7Z' fill='url(%23featherFill)'/%3E%3Cpath d='M18 56c8.5-3.4 14.2-9.8 18.1-17.8M26.9 48.9c6.9-7.2 13.5-14.8 20.3-22.1M31.8 41.2c6.4-1.3 12.1-4.6 16.5-9.4M36.8 33.8c4.9-0.9 9.2-3.4 12.6-7.1' fill='none' stroke='%23fff8ef' stroke-linecap='round' stroke-width='2.6'/%3E%3Cpath d='M18 56c8.5-3.4 14.2-9.8 18.1-17.8' fill='none' stroke='%2363562d' stroke-linecap='round' stroke-width='2.2'/%3E%3C/svg%3E"
/> />
<title>FlockPal</title> <title>FlockPal | Bird Care, Health Records &amp; Flock Management</title>
<meta
name="description"
content="Manage your flock with FlockPal. Track bird weights, health records, medications, and care routines in one shared workspace for bird households and rescues."
/>
</head> </head>
<body> <body>
<div id="root"></div> <div id="root">
<!-- React replaces this initial content when the app loads. -->
<main class="auth-shell">
<section class="panel auth-panel">
<div class="auth-copy">
<h1>Organized care for companion birds and rescue flocks</h1>
<p class="muted">
Keep every bird's care story in one place; your flock's health, history, and routines together and easier to visualize.
</p>
<noscript>Enable JavaScript to sign in and manage your flock.</noscript>
</div>
</section>
</main>
</div>
<script type="module" src="/src/main.tsx"></script> <script type="module" src="/src/main.tsx"></script>
</body> </body>
</html> </html>
+26 -4
View File
@@ -1,3 +1,4 @@
import { usePhotoRefresh } from './usePhotoRefresh';
import { FlockSwitcher } from './FlockSwitcher'; import { FlockSwitcher } from './FlockSwitcher';
import { combineLocationOwnerMarkers } from './birdTimeline'; import { combineLocationOwnerMarkers } from './birdTimeline';
import { BehaviorJournal } from './BehaviorJournal'; import { BehaviorJournal } from './BehaviorJournal';
@@ -2284,6 +2285,27 @@ function App() {
const [expandedSettingsSection, setExpandedSettingsSection] = useState<SettingsSection | null>(null); const [expandedSettingsSection, setExpandedSettingsSection] = useState<SettingsSection | null>(null);
const flockBirds = useMemo(() => sortBirdsByName([...birds, ...memorializedBirds]), [birds, memorializedBirds]); const flockBirds = useMemo(() => sortBirdsByName([...birds, ...memorializedBirds]), [birds, memorializedBirds]);
const handlePhotoError = usePhotoRefresh({
apiBaseUrl, token: authToken, workspaceId: workspace?.id, publicProfileCode,
fallback: defaultBirdPhoto,
onPhotos: (photos) => {
const urls = new Map(photos.map((photo) => [photo.id, photo.photoDataUrl]));
const update = (current: Bird[]) => current.map((bird) => urls.has(bird.id)
? { ...bird, photoDataUrl: urls.get(bird.id) ?? null } : bird);
setBirds(update);
setMemorializedBirds(update);
setPublicProfile((current) => current && urls.has(current.id)
? { ...current, photoDataUrl: urls.get(current.id) ?? null } : current);
// Renew the editor preview only if it still matches the saved photo.
// Never replace an uploaded/cropped photo or a deliberate removal.
const editingBird = [...birds, ...memorializedBirds].find((bird) => bird.id === editingBirdId);
if (editingBird && urls.has(editingBirdId)) {
setBirdForm((current) => current.photoDataUrl === editingBird.photoDataUrl
? { ...current, photoDataUrl: urls.get(editingBirdId) ?? '' } : current);
}
},
});
const selectedBird = useMemo( const selectedBird = useMemo(
() => flockBirds.find((bird) => bird.id === selectedBirdId) ?? null, () => flockBirds.find((bird) => bird.id === selectedBirdId) ?? null,
[flockBirds, selectedBirdId], [flockBirds, selectedBirdId],
@@ -5698,7 +5720,7 @@ function App() {
if (shouldShowPublicProfilePage) { if (shouldShowPublicProfilePage) {
return ( return (
<main className="auth-shell public-profile-shell"> <main className="auth-shell public-profile-shell" onErrorCapture={handlePhotoError}>
<section className="panel public-profile-card"> <section className="panel public-profile-card">
<a className="public-profile-logo-link" href="/" aria-label="Go to FlockPal sign in"> <a className="public-profile-logo-link" href="/" aria-label="Go to FlockPal sign in">
<img className="public-profile-logo" src={flockPalLandingArt} alt="FlockPal" /> <img className="public-profile-logo" src={flockPalLandingArt} alt="FlockPal" />
@@ -5895,7 +5917,7 @@ function App() {
if (loading) { if (loading) {
return ( return (
<main className="app-shell"> <main className="app-shell" onErrorCapture={handlePhotoError}>
<section className="hero-card"> <section className="hero-card">
<p>Loading flock data...</p> <p>Loading flock data...</p>
</section> </section>
@@ -6006,7 +6028,7 @@ function App() {
); );
return ( return (
<main className="app-shell"> <main className="app-shell" onErrorCapture={handlePhotoError}>
<div className="side-rail"> <div className="side-rail">
<div className="brand-lockup"> <div className="brand-lockup">
<img className="side-nav-logo" src={flockPalLandingArt} alt="FlockPal" /> <img className="side-nav-logo" src={flockPalLandingArt} alt="FlockPal" />
@@ -7331,7 +7353,7 @@ function App() {
) : null} ) : null}
{selectedBirdTab === 'behavior' && authToken ? <BehaviorJournal {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)))} writable={!selectedBird.memorializedAt && ['owner', 'assistant', 'caregiver'].includes(activeMembership?.role ?? '') && Boolean(authSession?.isAdmin || (workspace?.workspaceType === 'rescue' ? workspace.rescueVerificationStatus === 'approved' : workspace && subscriptionAllowsFlockWrites(workspace.subscriptionStatus)))}
/> : null} /> : null}
{selectedBirdTab === 'weight' ? ( {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; durationSeconds: number | null; severity: number | null; notes: string | null; createdAt: string; updatedAt: string;
}; };
type Props = { 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>; 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 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 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: '' }); 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 [month, setMonth] = useState(() => new Date(new Date().getFullYear(), new Date().getMonth(), 1));
const [day, setDay] = useState(() => localDate(new Date())); 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 [filter, setFilter] = useState('');
const [types, setTypes] = useState<BehaviorType[]>([]); const [types, setTypes] = useState<BehaviorType[]>([]);
const [entries, setEntries] = useState<Occurrence[]>([]); const [entries, setEntries] = useState<Occurrence[]>([]);
@@ -42,14 +44,22 @@ export function BehaviorJournal({ bird, birds, onSelectBird, token, writable, ap
useEffect(() => { useEffect(() => {
let active = true; let active = true;
setLoading(true); setError(''); setEntries([]); 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); if (filter) query.set('behaviorTypeId', filter);
Promise.all([request(`${base}/behavior-types`), request(`${base}/behaviors?${query}`)]) Promise.all([request(`${base}/behavior-types`), request(`${base}/behaviors?${query}`)])
.then(([typeData, occurrenceData]) => { if (active) { setTypes(typeData.behaviorTypes); setEntries(occurrenceData.occurrences); } }) .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.'); }) .catch((e) => { if (active) setError(e instanceof Error ? e.message : 'Unable to load journal.'); })
.finally(() => { if (active) setLoading(false); }); .finally(() => { if (active) setLoading(false); });
return () => { active = false; }; return () => { active = false; };
}, [bird.id, token, month, filter, revision]); }, [bird.id, token, month, view, range, filter, revision]);
const byDay = useMemo(() => { const byDay = useMemo(() => {
const result = new Map<string, Occurrence[]>(); 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 }) }); 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); const savedDate = new Date(occurredAt);
setMonth(new Date(savedDate.getFullYear(), savedDate.getMonth(), 1)); setDay(localDate(savedDate)); 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.'); setFilter(''); setShowForm(false); setEditing(null); setRevision((value) => value + 1); setNotice('Occurrence saved.');
} catch (e) { setError(e instanceof Error ? e.message : 'Unable to save occurrence.'); } } catch (e) { setError(e instanceof Error ? e.message : 'Unable to save occurrence.'); }
finally { setSaving(false); } 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> <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> </fieldset>
</form>} </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> <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> <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>
<p aria-live="polite">{loading ? 'Loading occurrences…' : `${entries.length} occurrence${entries.length === 1 ? '' : 's'} this month`}</p> {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>}
<div className="behavior-calendar" aria-label="Monthly behavior occurrences" aria-busy={loading}> {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>)} {['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: month.getDay() }, (_, index) => <span key={`blank-${index}`} />)}
{Array.from({ length: days }, (_, 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>; 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> </div>
<h3>{new Date(`${day}T12:00:00`).toLocaleDateString(undefined, { dateStyle: 'long' })}</h3> <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>} {!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>}
{(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>)} {(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>; </section>;
} }
+5
View File
@@ -22,3 +22,8 @@
.behavior-note-preview { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .behavior-note-preview { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.behavior-notes { white-space: pre-wrap; overflow-wrap: anywhere; } .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; } } @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; } }
+36
View File
@@ -0,0 +1,36 @@
export type PhotoRecord = { id: string; photoDataUrl: string | null };
export const PHOTO_REFRESH_INTERVAL_MS = 5 * 60_000;
// One request for all mounted photos; throttle failures without blocking later recovery.
export function createPhotoRefresher({ load, apply, now = Date.now }: {
load: (signal: AbortSignal) => Promise<PhotoRecord[]>;
apply: (photos: PhotoRecord[]) => void;
now?: () => number;
}) {
const controller = new AbortController();
let inFlight = false;
let lastAttempt = -Infinity;
return {
async refresh() {
if (controller.signal.aborted || inFlight || now() - lastAttempt < 30_000) return;
inFlight = true;
lastAttempt = now();
try {
const photos = await load(controller.signal);
if (!controller.signal.aborted) apply(photos);
} catch {
// Keep existing photos on transient failures; retry on the next focus/timer/error.
} finally {
inFlight = false;
}
},
dispose() { controller.abort(); },
};
}
export function isExpiringPhotoUrl(src: string) {
try {
const url = new URL(src, window.location.href);
return /\/birds\/[^/]+\/photo$/.test(url.pathname) && url.searchParams.has('token');
} catch { return false; }
}
+50
View File
@@ -0,0 +1,50 @@
import { useEffect, useRef, type SyntheticEvent } from 'react';
import { createPhotoRefresher, isExpiringPhotoUrl, PHOTO_REFRESH_INTERVAL_MS, type PhotoRecord } from './photoRefresh';
export function usePhotoRefresh({ apiBaseUrl, token, workspaceId, publicProfileCode, onPhotos, fallback }: {
apiBaseUrl: string; token: string; workspaceId?: number; publicProfileCode: string;
onPhotos: (photos: PhotoRecord[]) => void; fallback: string;
}) {
const apply = useRef(onPhotos);
apply.current = onPhotos;
const refresh = useRef<(() => Promise<void>) | null>(null);
useEffect(() => {
if (!publicProfileCode && (!token || !workspaceId)) return;
const refresher = createPhotoRefresher({
load: async (signal) => {
const path = publicProfileCode ? `/public/birds/${encodeURIComponent(publicProfileCode)}` : '/birds';
const response = await fetch(`${apiBaseUrl}${path}`, {
signal, cache: 'no-store',
headers: publicProfileCode ? {} : { Authorization: `Bearer ${token}` },
});
if (!response.ok) throw new Error('Unable to refresh photos.');
const data = await response.json();
return publicProfileCode ? (data.bird ? [data.bird] : []) : [...(data.birds ?? []), ...(data.memorializedBirds ?? [])];
},
apply: (photos) => apply.current(photos),
});
refresh.current = refresher.refresh;
const onResume = () => { if (document.visibilityState === 'visible') void refresher.refresh(); };
const timer = window.setInterval(onResume, PHOTO_REFRESH_INTERVAL_MS);
window.addEventListener('focus', onResume);
window.addEventListener('online', onResume);
document.addEventListener('visibilitychange', onResume);
return () => {
refresher.dispose();
refresh.current = null;
window.clearInterval(timer);
window.removeEventListener('focus', onResume);
window.removeEventListener('online', onResume);
document.removeEventListener('visibilitychange', onResume);
};
}, [apiBaseUrl, token, workspaceId, publicProfileCode]);
return (event: SyntheticEvent) => {
const image = event.target;
if (!(image instanceof Element)) return;
const attribute = image.localName === 'img' ? 'src' : image.localName === 'image' ? 'href' : null;
if (!attribute || !isExpiringPhotoUrl(image.getAttribute(attribute) ?? '')) return;
image.setAttribute(attribute, fallback);
void refresh.current?.();
};
}
+12 -3
View File
@@ -49,6 +49,15 @@ try {
await page.getByRole('tab', { name: 'Behavior Journal' }).click(); await page.getByRole('tab', { name: 'Behavior Journal' }).click();
const journal = page.getByRole('tabpanel', { name: 'Behavior Journal' }); const journal = page.getByRole('tabpanel', { name: 'Behavior Journal' });
await journal.getByText('1 occurrence this month', { exact: true }).waitFor(); 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(); await journal.getByRole('button', { name: 'Record behavior' }).click();
assert.match(await journal.getByLabel('Date and time', { exact: true }).inputValue(), /^2026-10-05T12:00(:00)?$/); 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('Behavior', { exact: true }).selectOption('custom');
@@ -104,9 +113,9 @@ try {
await editedEntry.getByRole('button', { name: 'Delete', exact: true }).click(); await editedEntry.getByRole('button', { name: 'Delete', exact: true }).click();
await journal.getByText('Occurrence deleted.', { exact: true }).waitFor(); await journal.getByText('Occurrence deleted.', { exact: true }).waitFor();
await journal.getByRole('button', { name: '10/5/2026: 1 occurrences', 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.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 journal.getByText('2 occurrences this month', { exact: true }).waitFor();
await page.setViewportSize({ width: 1280, height: 1000 }); await page.setViewportSize({ width: 1280, height: 1000 });
await journal.scrollIntoViewIfNeeded(); await journal.scrollIntoViewIfNeeded();
@@ -124,7 +133,7 @@ try {
await utcJournal.getByRole('button', { name: '10/1/2026: 2 occurrences', exact: true }).waitFor(); await utcJournal.getByRole('button', { name: '10/1/2026: 2 occurrences', exact: true }).waitFor();
await utcContext.close(); await utcContext.close();
assert.deepEqual(errors, []); 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) { } catch (error) {
if (page) { if (page) {
console.error(await page.locator('.behavior-journal').innerText().catch(() => 'Journal unavailable')); console.error(await page.locator('.behavior-journal').innerText().catch(() => 'Journal unavailable'));
+60
View File
@@ -0,0 +1,60 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { createPhotoRefresher } from '../src/photoRefresh.ts';
test('simultaneous image errors share a refresh, then can renew again after cooldown', async () => {
let now = 0;
let calls = 0;
let finish!: (photos: { id: string; photoDataUrl: string }[]) => void;
const applied: unknown[] = [];
const refresher = createPhotoRefresher({
now: () => now,
load: async () => { calls++; return new Promise((resolve) => { finish = resolve; }); },
apply: (photos) => applied.push(photos),
});
const first = refresher.refresh();
await refresher.refresh();
assert.equal(calls, 1);
finish([{ id: 'bird', photoDataUrl: 'renewed' }]);
await first;
assert.equal(applied.length, 1);
await refresher.refresh();
assert.equal(calls, 1);
now = 30_000;
const next = refresher.refresh();
finish([]);
await next;
assert.equal(calls, 2);
});
test('logout or flock switching aborts requests and discards stale photo responses', async () => {
let finish!: (photos: { id: string; photoDataUrl: string }[]) => void;
let signal!: AbortSignal;
let applied = false;
const refresher = createPhotoRefresher({
load: async (requestSignal) => { signal = requestSignal; return new Promise((resolve) => { finish = resolve; }); },
apply: () => { applied = true; },
});
const pending = refresher.refresh();
refresher.dispose();
finish([{ id: 'old-flock-bird', photoDataUrl: 'stale' }]);
await pending;
assert.equal(signal.aborted, true);
assert.equal(applied, false);
});
test('a failed refresh can recover on a later timer, focus, or reconnect', async () => {
let now = 0;
let attempts = 0;
let applied = false;
const refresher = createPhotoRefresher({
now: () => now,
load: async () => { if (++attempts === 1) throw new Error('offline'); return []; },
apply: () => { applied = true; },
});
await refresher.refresh();
assert.equal(applied, false);
now = 30_000;
await refresher.refresh();
assert.equal(applied, true);
});