56 Commits
Author SHA1 Message Date
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
Corey Blais 1706a906f0 Merge remote-tracking branch 'origin/dev'
Deploy / deploy-dev (push) Skipped
Deploy / deploy-prod (push) Successful in 4m2s
2026-10-08 16:10:03 -04:00
blaisadmin dc07026a88 Merge remote-tracking branch 'origin/dev'
Deploy / deploy-dev (push) Skipped
Deploy / deploy-prod (push) Successful in 3m15s
2026-10-07 21:55:38 -04:00
blaisadmin 0e2aa9366f Merge remote-tracking branch 'origin/dev'
Deploy / deploy-dev (push) Skipped
Deploy / deploy-prod (push) Successful in 2m35s
2026-10-07 21:38:14 -04:00
blaisadmin f676b94e36 Pass Mapbox Actions secret to deployment Compose steps
Deploy / deploy-dev (push) Skipped
Deploy / deploy-prod (push) Successful in 2m14s
2026-10-07 20:31:16 -04:00
blaisadmin cf8dceb014 Merge remote-tracking branch 'origin/dev'
Deploy / deploy-dev (push) Skipped
Deploy / deploy-prod (push) Successful in 3m14s
2026-10-07 20:19:30 -04:00
blaisadmin 802544e452 fixed main build notification
Deploy / deploy-dev (push) Skipped
Deploy / deploy-prod (push) Successful in 1m57s
2026-10-07 19:49:17 -04:00
blaisadmin 8205fee420 Merge branch 'dev'
Deploy / deploy-dev (push) Skipped
Deploy / deploy-prod (push) Successful in 3m4s
2026-10-07 19:40:24 -04:00
Corey Blais fc541f024d Merge dev into production release without education
Deploy / deploy-dev (push) Skipped
Deploy / deploy-prod (push) Successful in 3m58s
2026-10-05 18:18:10 -04:00
Corey Blais c1ca4891fc Notify Discord after deploy workflows
Deploy / deploy-dev (push) Skipped
Deploy / deploy-prod (push) Successful in 1m25s
2026-07-22 20:39:35 -04:00
Corey Blais 7406d00687 Fixing mobile views
Deploy / deploy-dev (push) Skipped
Deploy / deploy-prod (push) Successful in 1m56s
2026-07-22 20:30:03 -04:00
blaisadmin ecad447d60 Add deploy-ready health checks
Deploy / deploy-dev (push) Skipped
Deploy / deploy-prod (push) Successful in 1m57s
2026-07-21 22:46:16 -04:00
blaisadmin 3ba6410972 Merge branch 'dev'
Deploy / deploy-dev (push) Skipped
Deploy / deploy-prod (push) Successful in 3m3s
# Conflicts:
#	backend/src/app.ts
#	backend/src/db/schema.ts
#	backend/src/queues/adoptionReportQueue.ts
#	backend/src/reports/adoptionReport.ts
#	backend/src/reports/adoptionReportJob.ts
#	backend/src/repositories/birdRepository.ts
#	backend/src/types.ts
#	frontend/src/App.tsx
#	frontend/src/index.css
2026-07-21 22:25:29 -04:00
blaisadmin 4a43a450f3 Additional Genders
Deploy / deploy-dev (push) Has been skipped
Deploy / deploy-prod (push) Successful in 2m43s
2026-06-17 22:04:42 -04:00
Corey Blais 46605d8717 Limit editable weight entries to three
Deploy / deploy-dev (push) Has been skipped
Deploy / deploy-prod (push) Successful in 1m30s
2026-06-17 10:08:24 -04:00
Corey Blais 8f1144de1a Allow four editable weight entries
Deploy / deploy-dev (push) Has been skipped
Deploy / deploy-prod (push) Successful in 3m2s
2026-06-17 09:57:23 -04:00
Corey Blais 53b75588a2 weight edit fixes
Deploy / deploy-dev (push) Has been skipped
Deploy / deploy-prod (push) Successful in 2m36s
2026-06-16 18:13:54 -04:00
Corey Blais 1849ecd73b Updated weight edit 2026-06-16 18:13:54 -04:00
Corey Blais 53b7d34520 trimmed weight edit 2026-06-16 18:13:54 -04:00
Corey Blais f65a4bed24 adding weight edits 2026-06-16 18:13:54 -04:00
blaisadmin cc4a2382c6 Add production health checks
Deploy / deploy-dev (push) Has been skipped
Deploy / deploy-prod (push) Successful in 1m46s
2026-06-05 22:28:48 -04:00
blaisadmin 5735bb7735 Adding promoting to owner
Deploy / deploy-dev (push) Has been skipped
Deploy / deploy-prod (push) Successful in 2m23s
2026-06-05 21:45:58 -04:00
blaisadmin 88ff06237e Adjusting role actions 2026-06-05 21:45:58 -04:00
Corey Blais fbb13561b0 Medication reminder and pdr worker 2026-06-05 21:45:58 -04:00
Corey Blais b15861c856 Use fixed screen size for adoption report sheet 2026-06-05 21:42:20 -04:00
Corey Blais 2aeaa119f7 Wrap adoption report in letter sheet 2026-06-05 21:42:20 -04:00
Corey Blais 36690c0174 Tighten adoption report page scale 2026-06-05 21:42:20 -04:00
Corey Blais b76ad35c07 Size adoption report for letter paper 2026-06-05 21:42:20 -04:00
Corey Blais 6918b55a58 Stabilize adoption report layout 2026-06-05 21:42:20 -04:00
blaisadmin 49f1713e26 Add flock member notes and audit tabs 2026-06-05 21:42:20 -04:00
Corey Blais c9fa7e4246 Cover consumed adoption transfer codes
Deploy / deploy-dev (push) Has been skipped
Deploy / deploy-prod (push) Successful in 1m45s
2026-06-03 14:12:10 -04:00
Corey Blais 0411ec5175 Keep adoption transfer codes stable
Deploy / deploy-dev (push) Has been skipped
Deploy / deploy-prod (push) Successful in 2m17s
2026-06-03 12:10:27 -04:00
Corey Blais 7b7171c109 Prevent report card text overlap
Deploy / deploy-dev (push) Has been skipped
Deploy / deploy-prod (push) Successful in 1m47s
2026-06-03 11:54:44 -04:00
Corey Blais c02bb4d6d8 Convert report photos for PDF embedding
Deploy / deploy-dev (push) Has been skipped
Deploy / deploy-prod (push) Successful in 2m37s
2026-06-03 11:20:52 -04:00
Corey Blais 603b4eee4d Render adoption reports in worker
Deploy / deploy-dev (push) Has been skipped
Deploy / deploy-prod (push) Successful in 1m43s
2026-06-03 10:55:09 -04:00
Corey Blais 52008f5b43 Fix adoption report photos and section order
Deploy / deploy-dev (push) Has been skipped
Deploy / deploy-prod (push) Successful in 2m23s
2026-06-03 10:05:48 -04:00
Corey Blais 5b57cdd6bf Fix adoption report QR and chart layout 2026-06-03 10:05:48 -04:00
Corey Blais 60eadf0847 Refine adoption report header layout 2026-06-03 10:05:48 -04:00
Corey Blais 682ccfd41f Generate adoption reports as PDFs 2026-06-03 10:05:48 -04:00
Corey Blais 59c6b19ad6 fixing analytics icon pt2
Deploy / deploy-dev (push) Has been skipped
Deploy / deploy-prod (push) Successful in 2m15s
2026-06-02 12:55:35 -04:00
Corey Blais aa1a4cf6ff fixing analytics icon 2026-06-02 12:55:35 -04:00
Corey Blais 5f0fad3cbb Updated adoption report 2026-06-02 12:55:35 -04:00
Corey Blais 545fae59b2 Added adoption report and transfer code 2026-06-02 12:55:35 -04:00
Corey Blais d748d2db21 Added vet info
Deploy / deploy-dev (push) Has been skipped
Deploy / deploy-prod (push) Successful in 2m14s
2026-06-01 15:20:47 -04:00
blaisadmin 095c91e56d Merge branch 'release/flock-member-notes-audit'
Deploy / deploy-dev (push) Has been skipped
Deploy / deploy-prod (push) Successful in 2m16s
2026-05-30 22:50:54 -04:00
blaisadmin f2017068d5 Auto deploy production on main merge 2026-05-30 22:47:11 -04:00
blaisadmin c9702495a3 Add flock member notes and audit tabs 2026-05-30 22:46:31 -04:00
blaisadmin e965cb55ef Revert education feature from main 2026-05-30 15:50:23 -04:00
blaisadmin 505a9b8496 Added backend limits 2026-05-30 15:43:38 -04:00
blaisadmin c6dc5b22b8 Merge dev into main 2026-05-30 15:29:48 -04:00
blaisadmin f16e88e2f0 Validate builds before deploy 2026-05-24 21:48:42 -04:00
blaisadmin 016bc187d4 Run deploy compose from host repo paths 2026-05-24 11:33:58 -04:00
blaisadmin 104f01f75d Use local mounts for production deploy workflow 2026-05-23 18:38:49 -04:00
blaisadmin 568aee3e70 Adding gitea action 2026-05-23 16:32:59 -04:00
30 changed files with 457 additions and 1140 deletions

No files matched your search

+10 -3
View File
@@ -3,13 +3,14 @@ name: Deploy
on:
push:
branches:
- main
- dev
- develop
workflow_dispatch:
jobs:
deploy-dev:
if: ${{ github.event_name == 'push' }}
if: ${{ github.event_name == 'push' && (github.ref_name == 'dev' || github.ref_name == 'develop') }}
runs-on: ubuntu-latest
container:
volumes:
@@ -113,7 +114,7 @@ jobs:
"$DISCORD_WEBHOOK_URL" || echo "Discord notification failed."
deploy-prod:
if: ${{ github.event_name == 'workflow_dispatch' }}
if: ${{ github.event_name == 'workflow_dispatch' || (github.event_name == 'push' && github.ref_name == 'main') }}
runs-on: ubuntu-latest
container:
volumes:
@@ -153,7 +154,13 @@ jobs:
run: |
set -e
cd /docker/FlockPal
docker compose -f docker-compose.prod.yml up -d --build
docker compose -f docker-compose.prod.yml up -d --build --wait --wait-timeout 180
- name: Verify production API readiness
run: |
set -e
cd /docker/FlockPal
docker compose -f docker-compose.prod.yml exec -T backend node dist/healthcheck.js api-ready
- name: Notify Discord
if: always()
+17
View File
@@ -47,6 +47,23 @@ The default `docker-compose.yml` is development-only. It mounts source files, in
## Operations
### Health checks
Monitor these production checks:
- Frontend: `GET https://your-host/healthz`
- Verifies Nginx is serving the frontend container.
- Backend liveness: `GET https://your-host/api/health/live`
- Verifies the API process is running.
- Backend readiness: `GET https://your-host/api/health/ready`
- Verifies the API can reach Postgres and Redis. Returns `503` if either dependency is unavailable.
- Backend metrics: `GET https://your-host/api/metrics`
- Admin-authenticated process, request, and queue metrics.
- Postgres and Redis:
- Use the Docker health checks in `docker-compose.prod.yml`.
- Worker:
- Use the Docker health check in `docker-compose.prod.yml`; it validates worker dependencies. The worker does not expose HTTP.
### Backups
Create a compressed Postgres backup from the Docker Compose Postgres service:
+24 -200
View File
@@ -1,3 +1,4 @@
import { photoCacheControl } from './storage/photoCache.js';
import { canUpdateWorkspaceSettings, subscriptionAllowsWrite } from './workspaceAccess.js';
import { buildWorkspaceInviteEmail } from './emails/workspaceInviteEmail.js';
import { exportFlock } from './repositories/flockExportRepository.js';
@@ -58,6 +59,7 @@ import nodemailer from 'nodemailer';
import Stripe from 'stripe';
import { z } from 'zod';
import { db } from './db/client.js';
import { ensureSchema } from './db/schema.js';
import { adoptionReportQueueEvents, enqueueAdoptionReportJob } from './queues/adoptionReportQueue.js';
import { enqueueBirdMilestoneReminderJob, getBirdMilestoneReminderQueueCounts } from './queues/birdMilestoneReminderQueue.js';
@@ -123,19 +125,6 @@ import {
listAuditLogEntries,
listFlockNotes,
} from './repositories/auditRepository.js';
import {
deleteDailyEducation,
deleteEducationQuestion,
createEducationQuestion,
getDailyEducationForDate,
getEducationOptOut,
listDailyEducationForAdmin,
listDailyEducationQuestions,
listEducationQuestionsForAdmin,
updateEducationOptOut,
updateEducationQuestion,
upsertDailyEducation,
} from './repositories/educationRepository.js';
import {
buildBirdPhotoObjectKey,
getImageExtensionFromContentType,
@@ -175,8 +164,6 @@ import type {
AuditLogEntryRow,
BillingInterval,
BillingPlan,
DailyEducationRow,
EducationQuestionRow,
BirdGender,
BirdMilestoneReminderCandidateRow,
BirdRow,
@@ -374,27 +361,6 @@ const integrationTokenCreateSchema = z.object({
expiresInDays: z.coerce.number().int().min(1).max(3650).optional(),
});
const educationQuestionSchema = z
.object({
prompt: z.string().trim().min(1).max(500),
options: z.array(z.string().trim().min(1).max(240)).min(2).max(4),
correctAnswerIndex: z.coerce.number().int().min(0).max(3),
explanation: z.string().trim().max(800).optional().or(z.literal('')),
})
.refine((value) => value.correctAnswerIndex < value.options.length, {
message: 'Correct answer must match one of the quiz options.',
path: ['correctAnswerIndex'],
});
const dailyEducationSchema = z.object({
publishDate: dateStringSchema,
fact: z.string().trim().min(1).max(2000),
});
const educationPreferenceSchema = z.object({
educationOptOut: z.boolean(),
});
const emptyToNull = (value?: string) => {
const trimmed = value?.trim() ?? '';
return trimmed ? trimmed : null;
@@ -589,25 +555,6 @@ const normalizeWorkspaceMember = (row: WorkspaceMemberRow) => ({
createdAt: row.created_at,
});
const normalizeEducationQuestion = (row: EducationQuestionRow) => ({
id: row.id,
prompt: row.prompt,
options: row.options,
correctAnswerIndex: Number(row.correct_answer_index),
explanation: row.explanation ?? null,
createdAt: row.created_at,
updatedAt: row.updated_at,
});
const normalizeDailyEducation = (row: DailyEducationRow, questions: EducationQuestionRow[] = []) => ({
id: row.id,
publishDate: row.publish_date,
fact: row.fact,
quizQuestions: questions.map(normalizeEducationQuestion),
createdAt: row.created_at,
updatedAt: row.updated_at,
});
const signBirdPhotoAccessToken = (row: BirdRow) => {
if (!row.photo_object_key) {
return '';
@@ -2267,6 +2214,24 @@ app.get('/api/health', (_req: Request, res: Response) => {
res.json({ ok: true });
});
app.get('/api/health/live', (_req: Request, res: Response) => {
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) => {
const memoryUsage = process.memoryUsage();
const averageDurationMs = requestMetrics.totalRequests > 0 ? requestMetrics.totalDurationMs / requestMetrics.totalRequests : 0;
@@ -2712,149 +2677,6 @@ app.get('/api/admin/rescue-workspaces', requireAuth, requireSessionAuth, require
}
});
app.get('/api/admin/daily-education', requireAuth, requireSessionAuth, requireAdmin, async (_req: Request, res: Response, next: NextFunction) => {
try {
const education = await listDailyEducationForAdmin();
res.json({ education: education.map((entry) => normalizeDailyEducation(entry)) });
} catch (error) {
next(error);
}
});
app.get('/api/admin/education-questions', requireAuth, requireSessionAuth, requireAdmin, async (_req: Request, res: Response, next: NextFunction) => {
try {
const questions = await listEducationQuestionsForAdmin();
res.json({ questions: questions.map(normalizeEducationQuestion) });
} catch (error) {
next(error);
}
});
app.put('/api/admin/daily-education', requireAuth, requireSessionAuth, requireAdmin, async (req: Request, res: Response, next: NextFunction) => {
const parsed = dailyEducationSchema.safeParse(req.body);
if (!parsed.success) {
res.status(400).json({ error: 'Invalid daily education payload', details: parsed.error.flatten() });
return;
}
try {
const education = await upsertDailyEducation({
publishDate: parsed.data.publishDate,
fact: parsed.data.fact,
createdByUserId: req.auth!.user.id,
});
res.json({ education: normalizeDailyEducation(education) });
} catch (error) {
next(error);
}
});
app.post('/api/admin/education-questions', requireAuth, requireSessionAuth, requireAdmin, async (req: Request, res: Response, next: NextFunction) => {
const parsed = educationQuestionSchema.safeParse(req.body);
if (!parsed.success) {
res.status(400).json({ error: 'Invalid education question payload', details: parsed.error.flatten() });
return;
}
try {
const question = await createEducationQuestion({
question: { ...parsed.data, explanation: emptyToNull(parsed.data.explanation) },
createdByUserId: req.auth!.user.id,
});
res.status(201).json({ question: normalizeEducationQuestion(question) });
} catch (error) {
next(error);
}
});
app.put('/api/admin/education-questions/:questionId', requireAuth, requireSessionAuth, requireAdmin, async (req: Request, res: Response, next: NextFunction) => {
const parsed = educationQuestionSchema.safeParse(req.body);
if (!parsed.success) {
res.status(400).json({ error: 'Invalid education question payload', details: parsed.error.flatten() });
return;
}
try {
const question = await updateEducationQuestion(req.params.questionId, {
...parsed.data,
explanation: emptyToNull(parsed.data.explanation),
});
if (!question) {
res.status(404).json({ error: 'Education question not found.' });
return;
}
res.json({ question: normalizeEducationQuestion(question) });
} catch (error) {
next(error);
}
});
app.delete('/api/admin/education-questions/:questionId', requireAuth, requireSessionAuth, requireAdmin, async (req: Request, res: Response, next: NextFunction) => {
try {
const deleted = await deleteEducationQuestion(req.params.questionId);
if (!deleted) {
res.status(404).json({ error: 'Education question not found.' });
return;
}
res.status(204).send();
} catch (error) {
next(error);
}
});
app.delete('/api/admin/daily-education/:educationId', requireAuth, requireSessionAuth, requireAdmin, async (req: Request, res: Response, next: NextFunction) => {
try {
const deleted = await deleteDailyEducation(req.params.educationId);
if (!deleted) {
res.status(404).json({ error: 'Daily education item not found.' });
return;
}
res.status(204).send();
} catch (error) {
next(error);
}
});
app.get('/api/education/today', requireAuth, requireSessionAuth, async (req: Request, res: Response, next: NextFunction) => {
try {
const educationOptOut = await getEducationOptOut(req.auth!.user.id);
const education = educationOptOut ? null : await getDailyEducationForDate();
const questions = education ? await listDailyEducationQuestions(education.publish_date) : [];
res.json({
educationOptOut,
education: education ? normalizeDailyEducation(education, questions) : null,
});
} catch (error) {
next(error);
}
});
app.patch('/api/education/preferences', requireAuth, requireSessionAuth, async (req: Request, res: Response, next: NextFunction) => {
const parsed = educationPreferenceSchema.safeParse(req.body);
if (!parsed.success) {
res.status(400).json({ error: 'Invalid education preference payload', details: parsed.error.flatten() });
return;
}
try {
const educationOptOut = await updateEducationOptOut(req.auth!.user.id, parsed.data.educationOptOut);
res.json({ educationOptOut });
} catch (error) {
next(error);
}
});
app.patch('/api/admin/rescue-workspaces/:workspaceId', requireAuth, requireAdmin, requireWriteAccess, async (req: Request, res: Response, next: NextFunction) => {
const parsed = z.object({ rescueVerificationStatus: rescueVerificationStatusSchema }).safeParse(req.body);
@@ -3675,6 +3497,8 @@ app.post(
);
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 {
const token = typeof req.query.token === 'string' ? req.query.token : '';
const photoAccess = verifyBirdPhotoAccessToken(token);
@@ -3704,9 +3528,8 @@ app.get('/api/birds/:birdId/photo', async (req: Request, res: Response, next: Ne
expiresInSeconds: 5 * 60,
});
res.setHeader('Cache-Control', 'private, max-age=900');
if (photoDeliveryMode === 'redirect') {
res.setHeader('Cache-Control', photoCacheControl('redirect', photoAccess.expiresAt));
res.redirect(302, signedUrl);
return;
}
@@ -3722,6 +3545,7 @@ app.get('/api/birds/:birdId/photo', async (req: Request, res: Response, next: Ne
const contentLength = imageResponse.headers.get('content-length');
const imageBuffer = Buffer.from(await imageResponse.arrayBuffer());
res.setHeader('Cache-Control', photoCacheControl('proxy', photoAccess.expiresAt));
res.setHeader('Content-Type', contentType);
if (contentLength) {
+2 -2
View File
@@ -15,8 +15,8 @@ export const behaviorRangeSchema = z.object({
from: z.string().datetime({ offset: true }),
to: z.string().datetime({ offset: true }),
behaviorTypeId: z.string().uuid().optional(),
}).refine(({ from, to }) => Date.parse(to) > Date.parse(from) && Date.parse(to) - Date.parse(from) <= 32 * 86400000, {
message: 'Choose a date range of up to 32 days, with to after from.',
}).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 366 days, with to after from.',
});
export type BehaviorInput = z.infer<typeof behaviorOccurrenceSchema>;
-34
View File
@@ -30,9 +30,6 @@ export const ensureSchema = async (database: DatabaseClient = db) => {
ALTER TABLE workspaces
DROP CONSTRAINT IF EXISTS workspaces_id_check;
ALTER TABLE users
ADD COLUMN IF NOT EXISTS education_opt_out BOOLEAN NOT NULL DEFAULT FALSE;
ALTER TABLE workspaces
ADD COLUMN IF NOT EXISTS billing_email VARCHAR(255),
ADD COLUMN IF NOT EXISTS billing_plan VARCHAR(32) NOT NULL DEFAULT 'household_basic',
@@ -142,37 +139,6 @@ export const ensureSchema = async (database: DatabaseClient = db) => {
CREATE INDEX IF NOT EXISTS idx_auth_sessions_created_user
ON auth_sessions (created_at DESC, user_id);
CREATE TABLE IF NOT EXISTS daily_education (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
publish_date DATE NOT NULL UNIQUE,
fact TEXT NOT NULL,
quiz_questions JSONB NOT NULL DEFAULT '[]'::jsonb,
created_by_user_id UUID REFERENCES users(id) ON DELETE SET NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
);
ALTER TABLE daily_education
ALTER COLUMN quiz_questions SET DEFAULT '[]'::jsonb;
CREATE INDEX IF NOT EXISTS idx_daily_education_publish_date
ON daily_education (publish_date DESC);
CREATE TABLE IF NOT EXISTS education_question_bank (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
prompt VARCHAR(500) NOT NULL,
options JSONB NOT NULL,
correct_answer_index INTEGER NOT NULL,
explanation VARCHAR(800),
created_by_user_id UUID REFERENCES users(id) ON DELETE SET NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
CHECK (correct_answer_index >= 0 AND correct_answer_index <= 3)
);
CREATE INDEX IF NOT EXISTS idx_education_question_bank_created
ON education_question_bank (created_at DESC);
CREATE TABLE IF NOT EXISTS integration_tokens (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
+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: '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: '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] });
-1
View File
@@ -26,4 +26,3 @@ export const loadWeightReminderPortrait = async (bird: Pick<WeightReminder, 'bir
}
return thumbnail(await readFile(asset('yoda-default.png')));
};
+54
View File
@@ -0,0 +1,54 @@
import { db } from './db/client.js';
import { closeBirdMilestoneReminderQueue, getBirdMilestoneReminderQueueCounts } from './queues/birdMilestoneReminderQueue.js';
const timeoutMs = Number(process.env.HEALTHCHECK_TIMEOUT_MS ?? 5_000);
const withTimeout = async <T>(operation: Promise<T>, label: string): Promise<T> => {
let timeout: NodeJS.Timeout | undefined;
try {
return await Promise.race([
operation,
new Promise<never>((_resolve, reject) => {
timeout = setTimeout(() => reject(new Error(`${label} timed out`)), timeoutMs);
}),
]);
} finally {
if (timeout) {
clearTimeout(timeout);
}
}
};
const checkHttp = async (path: string) => {
const port = process.env.PORT ?? '5000';
const response = await withTimeout(fetch(`http://127.0.0.1:${port}${path}`), path);
if (!response.ok) {
throw new Error(`${path} returned ${response.status}`);
}
};
const checkWorkerDependencies = async () => {
await withTimeout(db.query('SELECT 1'), 'postgres');
await withTimeout(getBirdMilestoneReminderQueueCounts(), 'redis');
};
const mode = process.argv[2] ?? 'api-ready';
try {
if (mode === 'api-live') {
await checkHttp('/api/health/live');
} else if (mode === 'api-ready') {
await checkHttp('/api/health/ready');
} else if (mode === 'worker') {
await checkWorkerDependencies();
} else {
throw new Error(`Unknown healthcheck mode: ${mode}`);
}
} catch (error) {
console.error(error instanceof Error ? error.message : error);
process.exitCode = 1;
} finally {
await Promise.allSettled([closeBirdMilestoneReminderQueue(), db.close()]);
}
@@ -6,7 +6,9 @@ import {
createBird,
createPendingBirdTransfer,
getBirdById,
getOpenBirdTransferCode,
listWeightsForBird,
markBirdTransferCodeCompleted,
transferBirdToWorkspace,
} from './birdRepository.js';
import { mockDb } from '../test/mockDb.js';
@@ -253,3 +255,25 @@ test('completePendingBirdTransfersForOwner moves pending birds and marks complet
null,
]);
});
test('getOpenBirdTransferCode only returns unconsumed codes', async () => {
const { calls } = mockDb({ rowCount: 0, rows: [] });
const transferCode = await getOpenBirdTransferCode('ADOPT-123');
assert.equal(transferCode, null);
assert.deepEqual(calls[0].params, ['ADOPT-123']);
assert.match(calls[0].text, /bird_transfer_codes\.completed_at IS NULL/);
assert.match(calls[0].text, /bird_transfer_codes\.revoked_at IS NULL/);
assert.match(calls[0].text, /birds\.workspace_id = bird_transfer_codes\.source_workspace_id/);
});
test('markBirdTransferCodeCompleted consumes a code for the receiving workspace', async () => {
const { calls } = mockDb({ rowCount: 1, rows: [] });
await markBirdTransferCodeCompleted('code-1', 22);
assert.deepEqual(calls[0].params, ['code-1', 22]);
assert.match(calls[0].text, /SET completed_at = CURRENT_TIMESTAMP/);
assert.match(calls[0].text, /completed_workspace_id = \$2/);
});
@@ -1,153 +0,0 @@
import { db } from '../db/client.js';
import type { DailyEducationQuestion, DailyEducationRow, EducationQuestionRow } from '../types.js';
export const getEducationOptOut = async (userId: string) => {
const result = await db.query<{ education_opt_out: boolean }>(
`SELECT education_opt_out
FROM users
WHERE id = $1`,
[userId],
);
return result.rows[0]?.education_opt_out ?? false;
};
export const updateEducationOptOut = async (userId: string, educationOptOut: boolean) => {
const result = await db.query<{ education_opt_out: boolean }>(
`UPDATE users
SET education_opt_out = $2
WHERE id = $1
RETURNING education_opt_out`,
[userId, educationOptOut],
);
return result.rows[0]?.education_opt_out ?? educationOptOut;
};
export const getDailyEducationForDate = async (publishDate?: string) => {
const result = publishDate
? await db.query<DailyEducationRow>(
`SELECT id, publish_date::text, fact, quiz_questions, created_by_user_id, created_at, updated_at
FROM daily_education
WHERE publish_date = $1`,
[publishDate],
)
: await db.query<DailyEducationRow>(
`SELECT id, publish_date::text, fact, quiz_questions, created_by_user_id, created_at, updated_at
FROM daily_education
WHERE publish_date = CURRENT_DATE`,
);
return result.rows[0] ?? null;
};
export const listDailyEducationForAdmin = async () => {
const result = await db.query<DailyEducationRow>(
`SELECT id, publish_date::text, fact, quiz_questions, created_by_user_id, created_at, updated_at
FROM daily_education
ORDER BY publish_date DESC
LIMIT 120`,
);
return result.rows;
};
export const upsertDailyEducation = async ({
publishDate,
fact,
createdByUserId,
}: {
publishDate: string;
fact: string;
createdByUserId: string;
}) => {
const result = await db.query<DailyEducationRow>(
`INSERT INTO daily_education (publish_date, fact, created_by_user_id)
VALUES ($1, $2, $3)
ON CONFLICT (publish_date) DO UPDATE
SET fact = EXCLUDED.fact,
updated_at = CURRENT_TIMESTAMP
RETURNING id, publish_date::text, fact, quiz_questions, created_by_user_id, created_at, updated_at`,
[publishDate, fact, createdByUserId],
);
return result.rows[0];
};
export const listEducationQuestionsForAdmin = async () => {
const result = await db.query<EducationQuestionRow>(
`SELECT id, prompt, options, correct_answer_index, explanation, created_by_user_id, created_at, updated_at
FROM education_question_bank
ORDER BY updated_at DESC, created_at DESC
LIMIT 400`,
);
return result.rows;
};
export const listDailyEducationQuestions = async (seedDate?: string) => {
const result = await db.query<EducationQuestionRow>(
`SELECT id, prompt, options, correct_answer_index, explanation, created_by_user_id, created_at, updated_at
FROM education_question_bank
ORDER BY md5(COALESCE($1::text, CURRENT_DATE::text) || id::text)
LIMIT 4`,
[seedDate ?? null],
);
return result.rows;
};
export const createEducationQuestion = async ({
question,
createdByUserId,
}: {
question: DailyEducationQuestion;
createdByUserId: string;
}) => {
const result = await db.query<EducationQuestionRow>(
`INSERT INTO education_question_bank (prompt, options, correct_answer_index, explanation, created_by_user_id)
VALUES ($1, $2::jsonb, $3, $4, $5)
RETURNING id, prompt, options, correct_answer_index, explanation, created_by_user_id, created_at, updated_at`,
[question.prompt, JSON.stringify(question.options), question.correctAnswerIndex, question.explanation, createdByUserId],
);
return result.rows[0];
};
export const updateEducationQuestion = async (questionId: string, question: DailyEducationQuestion) => {
const result = await db.query<EducationQuestionRow>(
`UPDATE education_question_bank
SET prompt = $2,
options = $3::jsonb,
correct_answer_index = $4,
explanation = $5,
updated_at = CURRENT_TIMESTAMP
WHERE id = $1
RETURNING id, prompt, options, correct_answer_index, explanation, created_by_user_id, created_at, updated_at`,
[questionId, question.prompt, JSON.stringify(question.options), question.correctAnswerIndex, question.explanation],
);
return result.rows[0] ?? null;
};
export const deleteEducationQuestion = async (questionId: string) => {
const result = await db.query<{ id: string }>(
`DELETE FROM education_question_bank
WHERE id = $1
RETURNING id`,
[questionId],
);
return Boolean(result.rowCount);
};
export const deleteDailyEducation = async (educationId: string) => {
const result = await db.query<{ id: string }>(
`DELETE FROM daily_education
WHERE id = $1
RETURNING id`,
[educationId],
);
return Boolean(result.rowCount);
};
-1
View File
@@ -208,4 +208,3 @@ export const flockNoteSchema = z.object({
birdId: z.string().uuid().optional().nullable().or(z.literal('')),
body: z.string().trim().min(1).max(5000),
});
+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);
});
-29
View File
@@ -13,38 +13,9 @@ export type UserRow = {
email: string;
password_hash: string | null;
name: string;
education_opt_out?: boolean;
created_at: string;
};
export type DailyEducationQuestion = {
prompt: string;
options: string[];
correctAnswerIndex: number;
explanation: string | null;
};
export type DailyEducationRow = {
id: string;
publish_date: string;
fact: string;
quiz_questions: DailyEducationQuestion[];
created_by_user_id: string | null;
created_at: string;
updated_at: string;
};
export type EducationQuestionRow = {
id: string;
prompt: string;
options: string[];
correct_answer_index: number;
explanation: string | null;
created_by_user_id: string | null;
created_at: string;
updated_at: string;
};
export type WorkspaceRow = {
id: number;
name: string;
+1 -1
View File
@@ -22,7 +22,7 @@ try {
for (let i = 0; i < 3; 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, `Membership test ${i}`]);
await db.query(`INSERT INTO users (id, email, name, education_opt_out) VALUES ($1, $2, 'Tester', TRUE)`, [user, email]);
await db.query(`INSERT INTO users (id, email, name) VALUES ($1, $2, 'Tester')`, [user, email]);
await db.query(`INSERT INTO workspace_members (workspace_id, user_id, invite_email, name, role, accepted_at) VALUES ($1, $2, $3, '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, user, token });
+18
View File
@@ -98,6 +98,12 @@ services:
condition: service_healthy
redis:
condition: service_healthy
healthcheck:
test: ["CMD", "node", "dist/healthcheck.js", "api-ready"]
interval: 30s
timeout: 10s
retries: 3
start_period: 30s
labels:
- traefik.enable=true
- traefik.docker.network=traefik
@@ -158,6 +164,12 @@ services:
condition: service_healthy
redis:
condition: service_healthy
healthcheck:
test: ["CMD", "node", "dist/healthcheck.js", "worker"]
interval: 30s
timeout: 10s
retries: 3
start_period: 30s
restart: unless-stopped
frontend:
@@ -169,6 +181,12 @@ services:
container_name: flockpal-frontend
depends_on:
- backend
healthcheck:
test: ["CMD-SHELL", "wget -q -O /dev/null http://127.0.0.1/healthz"]
interval: 30s
timeout: 5s
retries: 3
start_period: 10s
labels:
- traefik.enable=true
- traefik.docker.network=traefik
+7
View File
@@ -96,6 +96,12 @@ services:
condition: service_healthy
redis:
condition: service_healthy
healthcheck:
test: ["CMD-SHELL", "node -e \"fetch('http://127.0.0.1:5000/api/health/ready').then(r => { if (!r.ok) process.exit(1) }).catch(() => process.exit(1))\""]
interval: 30s
timeout: 10s
retries: 3
start_period: 30s
ports:
- "5000:5000"
command: >
@@ -104,6 +110,7 @@ services:
volumes:
- ./backend:/app
- /app/node_modules
restart: unless-stopped
worker:
build:
+35 -2
View File
@@ -344,14 +344,47 @@ Validation failures return `400` with this shape:
#### `GET /api/health`
Public health check.
Public readiness-compatible health check. Verifies backend dependencies.
Response `200`:
```json
{ "ok": true }
{
"ok": true,
"service": "flockpal-backend",
"status": "ready",
"checkedAt": "2026-06-06T00:00:00.000Z",
"dependencies": {
"postgres": { "ok": true, "latencyMs": 3 },
"redis": { "ok": true, "latencyMs": 4 }
}
}
```
Response `503` when Postgres or Redis is unavailable.
#### `GET /api/health/live`
Public liveness check. Verifies the backend process is running without checking dependencies.
Response `200`:
```json
{
"ok": true,
"service": "flockpal-backend",
"status": "live",
"uptimeSeconds": 120,
"checkedAt": "2026-06-06T00:00:00.000Z"
}
```
#### `GET /api/health/ready`
Public readiness check. Verifies the backend can reach Postgres and Redis.
Response `200` uses the same shape as `GET /api/health`; response `503` means at least one dependency failed.
### Metrics
#### `GET /api/metrics`
+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.
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
@@ -24,7 +26,7 @@ The interactive API reference includes these endpoints:
| --- | --- | --- |
| 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`) |
| 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 |
| PUT | `/api/birds/:birdId/behaviors/:occurrenceId` | Replace the editable fields |
| DELETE | `/api/birds/:birdId/behaviors/:occurrenceId` | Delete an occurrence |
@@ -59,7 +61,7 @@ npx playwright install chromium
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:
+6
View File
@@ -12,6 +12,12 @@ server {
add_header X-Frame-Options "SAMEORIGIN" always;
add_header Permissions-Policy "camera=(), microphone=(), geolocation=()" always;
location = /healthz {
access_log off;
add_header Content-Type text/plain;
return 200 "ok\n";
}
location / {
try_files $uri $uri/ /index.html;
}
+28 -571
View File
@@ -1,3 +1,4 @@
import { usePhotoRefresh } from './usePhotoRefresh';
import { FlockSwitcher } from './FlockSwitcher';
import { combineLocationOwnerMarkers } from './birdTimeline';
import { BehaviorJournal } from './BehaviorJournal';
@@ -195,23 +196,6 @@ type AdminRescueWorkspace = {
memberCount: number;
};
type DailyEducationQuestion = {
id: string;
prompt: string;
options: string[];
correctAnswerIndex: number;
explanation: string | null;
};
type DailyEducation = {
id: string;
publishDate: string;
fact: string;
quizQuestions: DailyEducationQuestion[];
createdAt: string;
updatedAt: string;
};
type IntegrationTokenSummary = {
id: string;
userId: string;
@@ -411,18 +395,6 @@ type BillingNotice = {
message: string;
};
type DailyEducationQuestionFormState = {
prompt: string;
options: [string, string, string, string];
correctAnswerIndex: number;
explanation: string;
};
type DailyEducationFormState = {
publishDate: string;
fact: string;
};
type BulkWeightRowState = {
weightGrams: string;
};
@@ -945,18 +917,6 @@ const emptyFlockNoteForm: FlockNoteFormState = {
body: '',
};
const emptyDailyEducationQuestion = (): DailyEducationQuestionFormState => ({
prompt: '',
options: ['', '', '', ''],
correctAnswerIndex: 0,
explanation: '',
});
const emptyDailyEducationForm = (): DailyEducationFormState => ({
publishDate: new Date().toISOString().slice(0, 10),
fact: '',
});
const defaultAuthProviders: AuthProvider[] = [
{ providerKey: 'google', displayName: 'Google', enabled: false },
{ providerKey: 'microsoft', displayName: 'Microsoft', enabled: false },
@@ -2199,20 +2159,6 @@ function App() {
const [birdTimelineEventForm, setBirdTimelineEventForm] = useState<BirdTimelineEventFormState>(emptyBirdTimelineEventForm);
const [adminSummary, setAdminSummary] = useState<AdminSummary | null>(null);
const [adminRescueWorkspaces, setAdminRescueWorkspaces] = useState<AdminRescueWorkspace[]>([]);
const [adminDailyEducation, setAdminDailyEducation] = useState<DailyEducation[]>([]);
const [adminEducationQuestions, setAdminEducationQuestions] = useState<DailyEducationQuestion[]>([]);
const [dailyEducationForm, setDailyEducationForm] = useState<DailyEducationFormState>(emptyDailyEducationForm);
const [educationQuestionForm, setEducationQuestionForm] = useState<DailyEducationQuestionFormState>(emptyDailyEducationQuestion);
const [editingEducationQuestionId, setEditingEducationQuestionId] = useState('');
const [savingDailyEducation, setSavingDailyEducation] = useState(false);
const [savingEducationQuestion, setSavingEducationQuestion] = useState(false);
const [deletingDailyEducationId, setDeletingDailyEducationId] = useState('');
const [deletingEducationQuestionId, setDeletingEducationQuestionId] = useState('');
const [todayEducation, setTodayEducation] = useState<DailyEducation | null>(null);
const [educationOptOut, setEducationOptOut] = useState(false);
const [savingEducationPreference, setSavingEducationPreference] = useState(false);
const [educationAnswers, setEducationAnswers] = useState<Record<number, number>>({});
const [dailyEducationOpen, setDailyEducationOpen] = useState(false);
const [birds, setBirds] = useState<Bird[]>([]);
const [memorializedBirds, setMemorializedBirds] = useState<Bird[]>([]);
const [selectedBirdId, setSelectedBirdId] = useState<string>('');
@@ -2339,6 +2285,27 @@ function App() {
const [expandedSettingsSection, setExpandedSettingsSection] = useState<SettingsSection | null>(null);
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(
() => flockBirds.find((bird) => bird.id === selectedBirdId) ?? null,
[flockBirds, selectedBirdId],
@@ -2856,15 +2823,6 @@ function App() {
setAuditLogEntries([]);
setAdminSummary(null);
setAdminRescueWorkspaces([]);
setAdminDailyEducation([]);
setAdminEducationQuestions([]);
setDailyEducationForm(emptyDailyEducationForm());
setEducationQuestionForm(emptyDailyEducationQuestion());
setEditingEducationQuestionId('');
setTodayEducation(null);
setEducationOptOut(false);
setEducationAnswers({});
setDailyEducationOpen(false);
setBirds([]);
setMemorializedBirds([]);
setWeights([]);
@@ -3164,27 +3122,20 @@ function App() {
const loadAdminDashboard = async () => {
try {
const [summaryResponse, rescuesResponse, educationResponse, educationQuestionsResponse] = await Promise.all([
const [summaryResponse, rescuesResponse] = await Promise.all([
apiFetch('/admin/summary', authToken),
apiFetch('/admin/rescue-workspaces', authToken),
apiFetch('/admin/daily-education', authToken),
apiFetch('/admin/education-questions', authToken),
]);
if (!summaryResponse.ok || !rescuesResponse.ok || !educationResponse.ok || !educationQuestionsResponse.ok) {
if (!summaryResponse.ok || !rescuesResponse.ok) {
throw new Error('Unable to load admin dashboard.');
}
const summaryData = (await readJsonSafely<{ summary?: AdminSummary }>(summaryResponse)) ?? {};
const rescuesData = (await readJsonSafely<{ rescueWorkspaces?: AdminRescueWorkspace[] }>(rescuesResponse)) ?? {};
const educationData = (await readJsonSafely<{ education?: DailyEducation[] }>(educationResponse)) ?? {};
const educationQuestionsData =
(await readJsonSafely<{ questions?: DailyEducationQuestion[] }>(educationQuestionsResponse)) ?? {};
setAdminSummary(summaryData.summary ?? null);
setAdminRescueWorkspaces(rescuesData.rescueWorkspaces ?? []);
setAdminDailyEducation(educationData.education ?? []);
setAdminEducationQuestions(educationQuestionsData.questions ?? []);
} catch (adminError) {
setError(adminError instanceof Error ? adminError.message : 'Unable to load admin dashboard.');
}
@@ -3193,34 +3144,6 @@ function App() {
void loadAdminDashboard();
}, [activePage, authSession?.isAdmin, authToken]);
useEffect(() => {
if (!authToken || !authSession) {
return;
}
const loadTodayEducation = async () => {
try {
const response = await apiFetch('/education/today', authToken);
if (!response.ok) {
throw new Error(await readErrorMessage(response, 'Unable to load daily education.'));
}
const data =
(await readJsonSafely<{ education?: DailyEducation | null; educationOptOut?: boolean }>(response)) ?? {};
setEducationOptOut(Boolean(data.educationOptOut));
setTodayEducation(data.education ?? null);
setEducationAnswers({});
setDailyEducationOpen(false);
} catch (educationError) {
setError(educationError instanceof Error ? educationError.message : 'Unable to load daily education.');
}
};
void loadTodayEducation();
}, [authSession, authToken]);
useEffect(() => {
if (!selectedBird?.id) {
setWeights([]);
@@ -3741,221 +3664,6 @@ function App() {
}
};
const loadDailyEducationIntoForm = (education: DailyEducation) => {
setDailyEducationForm({
publishDate: education.publishDate,
fact: education.fact,
});
};
const loadEducationQuestionIntoForm = (question: DailyEducationQuestion) => {
setEditingEducationQuestionId(question.id);
setEducationQuestionForm({
prompt: question.prompt,
options: [
question.options[0] ?? '',
question.options[1] ?? '',
question.options[2] ?? '',
question.options[3] ?? '',
],
correctAnswerIndex: question.correctAnswerIndex,
explanation: question.explanation ?? '',
});
};
const resetEducationQuestionForm = () => {
setEditingEducationQuestionId('');
setEducationQuestionForm(emptyDailyEducationQuestion());
};
const handleDailyEducationSubmit = async (event: React.FormEvent<HTMLFormElement>) => {
event.preventDefault();
if (!authToken) {
return;
}
setError('');
setSavingDailyEducation(true);
try {
const response = await apiFetch('/admin/daily-education', authToken, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
publishDate: dailyEducationForm.publishDate,
fact: dailyEducationForm.fact.trim(),
}),
});
if (!response.ok) {
throw new Error(await readErrorMessage(response, 'Unable to save daily education.'));
}
const data = (await readJsonSafely<{ education?: DailyEducation }>(response)) ?? {};
if (!data.education) {
throw new Error('Unable to save daily education.');
}
setAdminDailyEducation((current) =>
[data.education!, ...current.filter((education) => education.id !== data.education!.id && education.publishDate !== data.education!.publishDate)]
.sort((left, right) => right.publishDate.localeCompare(left.publishDate)),
);
if (data.education.publishDate === new Date().toISOString().slice(0, 10) && !educationOptOut) {
const todayResponse = await apiFetch('/education/today', authToken);
const todayData = todayResponse.ok
? await readJsonSafely<{ education?: DailyEducation | null }>(todayResponse)
: null;
setTodayEducation(todayData?.education ?? null);
setEducationAnswers({});
}
setDailyEducationForm(emptyDailyEducationForm());
} catch (educationError) {
setError(educationError instanceof Error ? educationError.message : 'Unable to save daily education.');
} finally {
setSavingDailyEducation(false);
}
};
const handleEducationQuestionSubmit = async (event: React.FormEvent<HTMLFormElement>) => {
event.preventDefault();
if (!authToken) {
return;
}
setError('');
setSavingEducationQuestion(true);
try {
const response = await apiFetch(
editingEducationQuestionId ? `/admin/education-questions/${editingEducationQuestionId}` : '/admin/education-questions',
authToken,
{
method: editingEducationQuestionId ? 'PUT' : 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
prompt: educationQuestionForm.prompt.trim(),
options: educationQuestionForm.options.map((option) => option.trim()),
correctAnswerIndex: educationQuestionForm.correctAnswerIndex,
explanation: educationQuestionForm.explanation.trim(),
}),
},
);
if (!response.ok) {
throw new Error(await readErrorMessage(response, 'Unable to save education question.'));
}
const data = (await readJsonSafely<{ question?: DailyEducationQuestion }>(response)) ?? {};
if (!data.question) {
throw new Error('Unable to save education question.');
}
setAdminEducationQuestions((current) => [
data.question!,
...current.filter((question) => question.id !== data.question!.id),
]);
resetEducationQuestionForm();
} catch (educationError) {
setError(educationError instanceof Error ? educationError.message : 'Unable to save education question.');
} finally {
setSavingEducationQuestion(false);
}
};
const handleDeleteEducationQuestion = async (questionId: string) => {
if (!authToken) {
return;
}
setError('');
setDeletingEducationQuestionId(questionId);
try {
const response = await apiFetch(`/admin/education-questions/${questionId}`, authToken, { method: 'DELETE' });
if (!response.ok) {
throw new Error(await readErrorMessage(response, 'Unable to delete education question.'));
}
setAdminEducationQuestions((current) => current.filter((question) => question.id !== questionId));
if (editingEducationQuestionId === questionId) {
resetEducationQuestionForm();
}
} catch (educationError) {
setError(educationError instanceof Error ? educationError.message : 'Unable to delete education question.');
} finally {
setDeletingEducationQuestionId('');
}
};
const handleDeleteDailyEducation = async (educationId: string) => {
if (!authToken) {
return;
}
setError('');
setDeletingDailyEducationId(educationId);
try {
const response = await apiFetch(`/admin/daily-education/${educationId}`, authToken, { method: 'DELETE' });
if (!response.ok) {
throw new Error(await readErrorMessage(response, 'Unable to delete daily education.'));
}
setAdminDailyEducation((current) => current.filter((education) => education.id !== educationId));
if (todayEducation?.id === educationId) {
setTodayEducation(null);
}
} catch (educationError) {
setError(educationError instanceof Error ? educationError.message : 'Unable to delete daily education.');
} finally {
setDeletingDailyEducationId('');
}
};
const handleEducationPreferenceChange = async (nextEducationOptOut: boolean) => {
if (!authToken) {
return;
}
setError('');
setSavingEducationPreference(true);
try {
const response = await apiFetch('/education/preferences', authToken, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ educationOptOut: nextEducationOptOut }),
});
if (!response.ok) {
throw new Error(await readErrorMessage(response, 'Unable to save education preference.'));
}
setEducationOptOut(nextEducationOptOut);
if (nextEducationOptOut) {
setTodayEducation(null);
setDailyEducationOpen(false);
} else {
const todayResponse = await apiFetch('/education/today', authToken);
const data = todayResponse.ok
? await readJsonSafely<{ education?: DailyEducation | null }>(todayResponse)
: null;
setTodayEducation(data?.education ?? null);
}
setEducationAnswers({});
} catch (educationError) {
setError(educationError instanceof Error ? educationError.message : 'Unable to save education preference.');
} finally {
setSavingEducationPreference(false);
}
};
const handleCreateWorkspace = async (event: React.FormEvent<HTMLFormElement>) => {
event.preventDefault();
@@ -6012,7 +5720,7 @@ function App() {
if (shouldShowPublicProfilePage) {
return (
<main className="auth-shell public-profile-shell">
<main className="auth-shell public-profile-shell" onErrorCapture={handlePhotoError}>
<section className="panel public-profile-card">
<a className="public-profile-logo-link" href="/" aria-label="Go to FlockPal sign in">
<img className="public-profile-logo" src={flockPalLandingArt} alt="FlockPal" />
@@ -6209,7 +5917,7 @@ function App() {
if (loading) {
return (
<main className="app-shell">
<main className="app-shell" onErrorCapture={handlePhotoError}>
<section className="hero-card">
<p>Loading flock data...</p>
</section>
@@ -6320,7 +6028,7 @@ function App() {
);
return (
<main className="app-shell">
<main className="app-shell" onErrorCapture={handlePhotoError}>
<div className="side-rail">
<div className="brand-lockup">
<img className="side-nav-logo" src={flockPalLandingArt} alt="FlockPal" />
@@ -6553,74 +6261,6 @@ function App() {
</div>
</section>
{todayEducation ? (
<article className={dailyEducationOpen ? 'panel daily-education-panel open' : 'panel daily-education-panel condensed'}>
<div className="panel-header">
<div>
<p className="eyebrow">Fid fact of the day</p>
<h2>{dailyEducationOpen ? formatDate(todayEducation.publishDate) : 'Daily learning'}</h2>
</div>
<button className="secondary-button" onClick={() => setDailyEducationOpen((current) => !current)} type="button">
{dailyEducationOpen ? 'Close' : 'Open'}
</button>
</div>
{dailyEducationOpen ? (
<>
<p className="daily-fact">{todayEducation.fact}</p>
<section className="daily-quiz" aria-label="Daily education quiz">
{todayEducation.quizQuestions.map((question, questionIndex) => {
const selectedAnswer = educationAnswers[questionIndex];
const hasAnswer = selectedAnswer !== undefined;
return (
<fieldset key={`${todayEducation.id}-${question.id}`} className="quiz-question">
<legend>{question.prompt}</legend>
<div className="quiz-options">
{question.options.map((option, optionIndex) => (
<label
key={`${question.id}-${optionIndex}`}
className={
hasAnswer && optionIndex === question.correctAnswerIndex
? 'quiz-option correct'
: hasAnswer && optionIndex === selectedAnswer
? 'quiz-option incorrect'
: 'quiz-option'
}
>
<input
type="radio"
name={`daily-question-${question.id}`}
checked={selectedAnswer === optionIndex}
onChange={() =>
setEducationAnswers((current) => ({
...current,
[questionIndex]: optionIndex,
}))
}
/>
<span>{option}</span>
</label>
))}
</div>
{hasAnswer ? (
<p className={selectedAnswer === question.correctAnswerIndex ? 'quiz-feedback correct' : 'quiz-feedback'}>
{selectedAnswer === question.correctAnswerIndex ? 'Correct.' : 'Correct answer shown.'}{' '}
{question.explanation}
</p>
) : null}
</fieldset>
);
})}
</section>
</>
) : (
<p className="muted daily-education-teaser">
Open today&apos;s fact and {todayEducation.quizQuestions.length || 'the'} quiz questions.
</p>
)}
</article>
) : null}
<section className="forms-grid">
<article className="panel form-panel pulse-panel">
<div className="panel-header">
@@ -6777,168 +6417,6 @@ function App() {
)}
</div>
</article>
<article className="panel admin-education-panel">
<div className="panel-header">
<div>
<p className="eyebrow">Education</p>
<h2>Fid facts</h2>
</div>
<button className="secondary-button" onClick={() => setDailyEducationForm(emptyDailyEducationForm())} type="button">
New date
</button>
</div>
<form className="form-panel" onSubmit={handleDailyEducationSubmit}>
<div className="education-admin-basics">
<label>
Publish date
<input
type="date"
value={dailyEducationForm.publishDate}
onChange={(event) => setDailyEducationForm({ ...dailyEducationForm, publishDate: event.target.value })}
required
/>
</label>
<label>
Fid fact
<textarea
value={dailyEducationForm.fact}
onChange={(event) => setDailyEducationForm({ ...dailyEducationForm, fact: event.target.value })}
rows={3}
required
/>
</label>
</div>
<button className="primary-button" type="submit" disabled={savingDailyEducation}>
{savingDailyEducation ? 'Saving...' : 'Save fact'}
</button>
</form>
<div className="recent-list education-admin-list">
{adminDailyEducation.length ? (
adminDailyEducation.map((education) => (
<article key={education.id} className="vet-visit-card">
<strong>{formatDate(education.publishDate)}</strong>
<span>{education.fact}</span>
<div className="button-row">
<button className="secondary-button" type="button" onClick={() => loadDailyEducationIntoForm(education)}>
Edit
</button>
<button
className="secondary-button"
type="button"
onClick={() => handleDeleteDailyEducation(education.id)}
disabled={deletingDailyEducationId === education.id}
>
{deletingDailyEducationId === education.id ? 'Deleting...' : 'Delete'}
</button>
</div>
</article>
))
) : (
<article className="vet-visit-card empty-card">
<strong>No scheduled facts yet</strong>
<small>Add a dated Fid fact for the overview page.</small>
</article>
)}
</div>
</article>
<article className="panel admin-education-panel">
<div className="panel-header">
<div>
<p className="eyebrow">Education</p>
<h2>Quiz question bank</h2>
</div>
<button className="secondary-button" onClick={resetEducationQuestionForm} type="button">
New question
</button>
</div>
<p className="muted">Each day the quiz uses a stable random selection of four saved questions.</p>
<form className="form-panel" onSubmit={handleEducationQuestionSubmit}>
<fieldset className="settings-nested-card quiz-editor-question">
<legend>{editingEducationQuestionId ? 'Edit question' : 'Add question'}</legend>
<label>
Prompt
<input
value={educationQuestionForm.prompt}
onChange={(event) => setEducationQuestionForm({ ...educationQuestionForm, prompt: event.target.value })}
required
/>
</label>
<div className="quiz-editor-options">
{educationQuestionForm.options.map((option, optionIndex) => (
<label key={`bank-option-${optionIndex}`}>
Option {optionIndex + 1}
<input
value={option}
onChange={(event) => {
const options = [...educationQuestionForm.options] as DailyEducationQuestionFormState['options'];
options[optionIndex] = event.target.value;
setEducationQuestionForm({ ...educationQuestionForm, options });
}}
required
/>
</label>
))}
</div>
<label>
Correct option
<select
value={educationQuestionForm.correctAnswerIndex}
onChange={(event) =>
setEducationQuestionForm({ ...educationQuestionForm, correctAnswerIndex: Number(event.target.value) })
}
>
{educationQuestionForm.options.map((_, optionIndex) => (
<option key={`bank-correct-${optionIndex}`} value={optionIndex}>
Option {optionIndex + 1}
</option>
))}
</select>
</label>
<label>
Explanation
<textarea
value={educationQuestionForm.explanation}
onChange={(event) => setEducationQuestionForm({ ...educationQuestionForm, explanation: event.target.value })}
rows={2}
/>
</label>
</fieldset>
<button className="primary-button" type="submit" disabled={savingEducationQuestion}>
{savingEducationQuestion ? 'Saving...' : editingEducationQuestionId ? 'Save question changes' : 'Add question'}
</button>
</form>
<div className="recent-list education-admin-list">
{adminEducationQuestions.length ? (
adminEducationQuestions.map((question) => (
<article key={question.id} className="vet-visit-card">
<strong>{question.prompt}</strong>
<span>Answer: {question.options[question.correctAnswerIndex]}</span>
<small>{question.options.length} options</small>
<div className="button-row">
<button className="secondary-button" type="button" onClick={() => loadEducationQuestionIntoForm(question)}>
Edit
</button>
<button
className="secondary-button"
type="button"
onClick={() => handleDeleteEducationQuestion(question.id)}
disabled={deletingEducationQuestionId === question.id}
>
{deletingEducationQuestionId === question.id ? 'Deleting...' : 'Delete'}
</button>
</div>
</article>
))
) : (
<article className="vet-visit-card empty-card">
<strong>No quiz questions yet</strong>
<small>Add at least four questions before the daily quiz can use a full set.</small>
</article>
)}
</div>
</article>
</section>
) : null}
@@ -7875,7 +7353,7 @@ function App() {
) : null}
{selectedBirdTab === 'behavior' && authToken ? <BehaviorJournal
key={`${workspace?.id}-${selectedBird.id}`} bird={selectedBird} birds={birds} onSelectBird={setSelectedBirdId} token={authToken} apiFetch={apiFetch}
key={`${workspace?.id}-${selectedBird.id}`} bird={selectedBird} token={authToken} apiFetch={apiFetch}
writable={!selectedBird.memorializedAt && ['owner', 'assistant', 'caregiver'].includes(activeMembership?.role ?? '') && Boolean(authSession?.isAdmin || (workspace?.workspaceType === 'rescue' ? workspace.rescueVerificationStatus === 'approved' : workspace && subscriptionAllowsFlockWrites(workspace.subscriptionStatus)))}
/> : null}
{selectedBirdTab === 'weight' ? (
@@ -9090,27 +8568,6 @@ function App() {
</div>
<div className="settings-column settings-column-right">
<article className="panel form-panel">
<div className="panel-header">
<div>
<p className="eyebrow">Education</p>
<h2>Daily learning</h2>
</div>
</div>
<label className="toggle-card">
<input
type="checkbox"
checked={!educationOptOut}
onChange={(event) => handleEducationPreferenceChange(!event.target.checked)}
disabled={savingEducationPreference}
/>
<span>
<strong>Show daily education</strong>
<small>Display the Fid fact of the day and four-question quiz on Overview.</small>
</span>
</label>
</article>
<article className="panel form-panel settings-card-collaborators">
<div className="panel-header">
<div>
+23 -11
View File
@@ -7,16 +7,18 @@ type Occurrence = {
durationSeconds: number | null; severity: number | null; notes: string | null; createdAt: string; updatedAt: string;
};
type Props = {
bird: { id: string; name: string }; birds: { id: string; name: string }[]; onSelectBird: (id: string) => void; token: string; writable: boolean;
bird: { id: string; name: string }; token: string; writable: boolean;
apiFetch: (path: string, token?: string, init?: RequestInit) => Promise<Response>;
};
const localDate = (date: Date) => `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
const localTime = (date: Date) => `${localDate(date)}T${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}:${String(date.getSeconds()).padStart(2, '0')}`;
const emptyForm = () => ({ behaviorTypeId: '', occurredAt: localTime(new Date()), duration: '', severity: '', notes: '' });
export function BehaviorJournal({ bird, birds, onSelectBird, token, writable, apiFetch }: Props) {
export function BehaviorJournal({ bird, token, writable, apiFetch }: Props) {
const [month, setMonth] = useState(() => new Date(new Date().getFullYear(), new Date().getMonth(), 1));
const [day, setDay] = useState(() => localDate(new Date()));
const [view, setView] = useState<'month' | 'range'>('month');
const [range, setRange] = useState(() => ({ start: localDate(new Date(new Date().getFullYear(), new Date().getMonth(), 1)), end: localDate(new Date()) }));
const [filter, setFilter] = useState('');
const [types, setTypes] = useState<BehaviorType[]>([]);
const [entries, setEntries] = useState<Occurrence[]>([]);
@@ -42,14 +44,22 @@ export function BehaviorJournal({ bird, birds, onSelectBird, token, writable, ap
useEffect(() => {
let active = true;
setLoading(true); setError(''); setEntries([]);
const query = new URLSearchParams({ from: month.toISOString(), to: new Date(month.getFullYear(), month.getMonth() + 1, 1).toISOString() });
const from = view === 'range' ? new Date(`${range.start}T00:00:00`) : month;
const to = view === 'range' ? new Date(`${range.end}T00:00:00`) : new Date(month.getFullYear(), month.getMonth() + 1, 1);
if (view === 'range') to.setDate(to.getDate() + 1);
if (!Number.isFinite(from.getTime()) || !Number.isFinite(to.getTime()) || to <= from || to.getTime() - from.getTime() > 366 * 86400000) {
setError('Choose a start and end date, with the end on or after the start and a range of up to 366 days.');
setLoading(false);
return;
}
const query = new URLSearchParams({ from: from.toISOString(), to: to.toISOString() });
if (filter) query.set('behaviorTypeId', filter);
Promise.all([request(`${base}/behavior-types`), request(`${base}/behaviors?${query}`)])
.then(([typeData, occurrenceData]) => { if (active) { setTypes(typeData.behaviorTypes); setEntries(occurrenceData.occurrences); } })
.catch((e) => { if (active) setError(e instanceof Error ? e.message : 'Unable to load journal.'); })
.finally(() => { if (active) setLoading(false); });
return () => { active = false; };
}, [bird.id, token, month, filter, revision]);
}, [bird.id, token, month, view, range, filter, revision]);
const byDay = useMemo(() => {
const result = new Map<string, Occurrence[]>();
@@ -79,6 +89,7 @@ export function BehaviorJournal({ bird, birds, onSelectBird, token, writable, ap
await request(`${base}/behaviors${editing ? `/${editing.id}` : ''}`, { method: editing ? 'PUT' : 'POST', body: JSON.stringify({ behaviorTypeId: typeId, occurredAt, durationSeconds: form.duration === '' ? null : Number(form.duration), severity: form.severity === '' ? null : Number(form.severity), notes: form.notes || null }) });
const savedDate = new Date(occurredAt);
setMonth(new Date(savedDate.getFullYear(), savedDate.getMonth(), 1)); setDay(localDate(savedDate));
if (view === 'range' && (localDate(savedDate) < range.start || localDate(savedDate) > range.end)) setRange({ start: localDate(savedDate), end: localDate(savedDate) });
setFilter(''); setShowForm(false); setEditing(null); setRevision((value) => value + 1); setNotice('Occurrence saved.');
} catch (e) { setError(e instanceof Error ? e.message : 'Unable to save occurrence.'); }
finally { setSaving(false); }
@@ -113,11 +124,12 @@ export function BehaviorJournal({ bird, birds, onSelectBird, token, writable, ap
<div className="behavior-actions"><button className="primary-button" type="submit">{saving ? 'Saving…' : 'Save occurrence'}</button><button className="secondary-button" type="button" onClick={() => { setShowForm(false); setEditing(null); }}>Cancel</button></div>
</fieldset>
</form>}
<label>Bird<select aria-label="Bird" value={bird.id} disabled={saving} onChange={(e) => onSelectBird(e.target.value)}>{birds.map((item) => <option key={item.id} value={item.id}>{item.name}</option>)}</select></label>
<label>Show behavior<select aria-label="Show behavior" value={filter} disabled={saving} onChange={(e) => setFilter(e.target.value)}><option value="">All behaviors</option>{types.map((type) => <option key={type.id} value={type.id}>{type.name}</option>)}</select></label>
<div className="behavior-month"><button className="secondary-button" type="button" aria-label="Previous month" onClick={() => navigate(-1)}>‹</button><h3 aria-live="polite">{month.toLocaleDateString(undefined, { month: 'long', year: 'numeric' })}</h3><button className="secondary-button" type="button" aria-label="Next month" onClick={() => navigate(1)}>›</button></div>
<p aria-live="polite">{loading ? 'Loading occurrences…' : `${entries.length} occurrence${entries.length === 1 ? '' : 's'} this month`}</p>
<div className="behavior-calendar" aria-label="Monthly behavior occurrences" aria-busy={loading}>
<label>View<select aria-label="Journal view" value={view} disabled={saving} onChange={(e) => setView(e.target.value as 'month' | 'range')}><option value="month">Monthly calendar</option><option value="range">Date range</option></select></label>
{view === 'range' && <div className="behavior-range"><label>Start date<input type="date" required value={range.start} disabled={saving} onChange={(e) => setRange({ ...range, start: e.target.value })} /></label><label>End date<input type="date" required min={range.start} value={range.end} disabled={saving} onChange={(e) => setRange({ ...range, end: e.target.value })} /></label><p className="muted">Includes both dates, up to 366 days. Entries are shown newest first.</p></div>}
{view === 'month' && <div className="behavior-month"><button className="secondary-button" type="button" aria-label="Previous month" onClick={() => navigate(-1)}>‹</button><h3 aria-live="polite">{month.toLocaleDateString(undefined, { month: 'long', year: 'numeric' })}</h3><button className="secondary-button" type="button" aria-label="Next month" onClick={() => navigate(1)}>›</button></div>}
<p aria-live="polite">{loading ? 'Loading occurrences…' : `${entries.length} occurrence${entries.length === 1 ? '' : 's'} ${view === 'month' ? 'this month' : 'in this date range'}`}</p>
{view === 'month' && <><div className="behavior-calendar" aria-label="Monthly behavior occurrences" aria-busy={loading}>
{['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'].map((label) => <span className="behavior-weekday" key={label}>{label}</span>)}
{Array.from({ length: month.getDay() }, (_, index) => <span key={`blank-${index}`} />)}
{Array.from({ length: days }, (_, index) => {
@@ -125,8 +137,8 @@ export function BehaviorJournal({ bird, birds, onSelectBird, token, writable, ap
return <button type="button" key={key} className={`behavior-day ${count ? 'has-occurrences' : ''}`} aria-pressed={key === day} aria-current={key === localDate(new Date()) ? 'date' : undefined} aria-label={`${date.toLocaleDateString()}: ${count} occurrences`} onClick={() => setDay(key)}><span>{index + 1}</span>{count > 0 && <><span className="behavior-dots" aria-hidden="true">{'●'.repeat(Math.min(count, 3))}{count > 3 ? '+' : ''}</span><small>{count}</small></>}</button>;
})}
</div>
<h3>{new Date(`${day}T12:00:00`).toLocaleDateString(undefined, { dateStyle: 'long' })}</h3>
{!loading && !(byDay.get(day)?.length) && <p className="muted">No occurrences recorded for this day{filter ? ' for the selected behavior' : ''}.</p>}
{(byDay.get(day) || []).map((entry) => <details key={entry.id} className="behavior-entry"><summary><strong>{entry.behaviorName}</strong><span>{new Date(entry.occurredAt).toLocaleString()}</span>{entry.durationSeconds !== null && <span>Duration: {entry.durationSeconds} seconds</span>}{entry.severity !== null && <span>Intensity: {entry.severity}/5</span>}{entry.notes && <span className="behavior-note-preview">{entry.notes}</span>}</summary><div>{entry.notes && <p className="behavior-notes">{entry.notes}</p>}<p className="muted">Created: {new Date(entry.createdAt).toLocaleString()}<br />Updated: {new Date(entry.updatedAt).toLocaleString()}</p>{writable && <div className="behavior-actions"><button className="secondary-button" type="button" disabled={saving} onClick={() => edit(entry)}>Edit</button><button className="danger-button" type="button" disabled={saving} onClick={() => void remove(entry)}>Delete</button></div>}</div></details>)}
<h3>{new Date(`${day}T12:00:00`).toLocaleDateString(undefined, { dateStyle: 'long' })}</h3></>}
{!loading && !error && !(view === 'range' ? entries.length : byDay.get(day)?.length) && <p className="muted">No occurrences recorded for {view === 'range' ? 'this date range' : 'this day'}{filter ? ' for the selected behavior' : ''}.</p>}
{(view === 'range' ? entries : byDay.get(day) || []).map((entry) => <details key={entry.id} className="behavior-entry"><summary><strong>{entry.behaviorName}</strong><span>{new Date(entry.occurredAt).toLocaleString()}</span>{entry.durationSeconds !== null && <span>Duration: {entry.durationSeconds} seconds</span>}{entry.severity !== null && <span>Intensity: {entry.severity}/5</span>}{entry.notes && <span className="behavior-note-preview">{entry.notes}</span>}</summary><div>{entry.notes && <p className="behavior-notes">{entry.notes}</p>}<p className="muted">Created: {new Date(entry.createdAt).toLocaleString()}<br />Updated: {new Date(entry.updatedAt).toLocaleString()}</p>{writable && <div className="behavior-actions"><button className="secondary-button" type="button" disabled={saving} onClick={() => edit(entry)}>Edit</button><button className="danger-button" type="button" disabled={saving} onClick={() => void remove(entry)}>Delete</button></div>}</div></details>)}
</section>;
}
+5
View File
@@ -22,3 +22,8 @@
.behavior-note-preview { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.behavior-notes { white-space: pre-wrap; overflow-wrap: anywhere; }
@media (max-width: 540px) { .behavior-form fieldset { grid-template-columns: 1fr; } .behavior-day { min-height: 64px; padding: .2rem; } .behavior-calendar { gap: .15rem; } .behavior-weekday { font-size: .7rem; } }
.behavior-range { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: .75rem; margin-top: .75rem; }
.behavior-range input { min-width: 0; width: 100%; box-sizing: border-box; }
.behavior-range p { grid-column: 1 / -1; margin: 0; }
@media (max-width: 540px) { .behavior-range { grid-template-columns: 1fr; } }
-123
View File
@@ -793,123 +793,6 @@ textarea {
align-content: start;
}
.daily-education-panel,
.daily-quiz,
.quiz-options,
.education-question-editor {
display: grid;
gap: 1rem;
}
.daily-education-panel.condensed {
gap: 0.35rem;
padding-block: 1rem;
}
.daily-education-panel.condensed .panel-header {
margin-bottom: 0;
}
.daily-education-teaser {
margin: 0;
}
.daily-fact {
margin: 0;
padding: 1rem;
border-left: 4px solid var(--accent-gold);
border-radius: 0 8px 8px 0;
background: rgba(255, 254, 250, 0.7);
font-size: 1.08rem;
}
.daily-quiz {
grid-template-columns: repeat(auto-fit, minmax(min(290px, 100%), 1fr));
}
.quiz-question,
.quiz-editor-question {
min-width: 0;
margin: 0;
border: 1px solid var(--button-border);
}
.quiz-question {
display: grid;
gap: 0.85rem;
padding: 1rem;
border-radius: 8px;
background: rgba(255, 254, 250, 0.64);
}
.quiz-question legend,
.quiz-editor-question legend {
padding: 0 0.35rem;
font-weight: 700;
}
.quiz-option {
display: grid;
grid-template-columns: auto minmax(0, 1fr);
align-items: start;
gap: 0.65rem;
min-width: 0;
padding: 0.7rem;
border: 1px solid rgba(39, 105, 179, 0.12);
border-radius: 8px;
background: rgba(255, 255, 255, 0.58);
}
.quiz-option.correct {
border-color: rgba(35, 138, 90, 0.42);
background: rgba(223, 247, 229, 0.82);
}
.quiz-option.incorrect {
border-color: rgba(203, 58, 53, 0.36);
background: rgba(255, 236, 232, 0.82);
}
.quiz-option input {
width: auto;
margin: 0.25rem 0 0;
}
.quiz-feedback {
margin: 0;
color: var(--accent-red);
}
.quiz-feedback.correct {
color: var(--accent-green);
}
.admin-education-panel,
.education-admin-basics,
.quiz-editor-question,
.education-admin-list {
display: grid;
gap: 1rem;
}
.education-admin-basics {
grid-template-columns: minmax(180px, 0.35fr) minmax(0, 1fr);
}
.quiz-editor-question {
padding: 1rem;
}
.quiz-editor-options {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 0.8rem;
}
.education-admin-list span {
overflow-wrap: anywhere;
}
.button-row {
display: flex;
gap: 0.75rem;
@@ -2667,11 +2550,6 @@ label {
}
@media (max-width: 980px) {
.education-admin-basics,
.quiz-editor-options {
grid-template-columns: 1fr;
}
.app-shell,
.auth-panel,
.hero-card,
@@ -3066,7 +2944,6 @@ label {
.inline-form,
.settings-nested-grid,
.education-admin-basics,
.quiz-editor-options,
.dose-schedule-row,
.verified-location-search-row,
+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?.();
};
}
+13 -4
View File
@@ -27,7 +27,7 @@ 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, education_opt_out) VALUES ($1, $2, 'Browser tester', TRUE)`, [user, `${user}@example.test`]);
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]);
@@ -49,6 +49,15 @@ try {
await page.getByRole('tab', { name: 'Behavior Journal' }).click();
const journal = page.getByRole('tabpanel', { name: 'Behavior Journal' });
await journal.getByText('1 occurrence this month', { exact: true }).waitFor();
await journal.getByLabel('Journal view').selectOption('range');
await journal.getByLabel('Start date', { exact: true }).fill('2026-09-30');
await journal.getByLabel('End date', { exact: true }).fill('2026-11-01');
await journal.getByText('4 occurrences in this date range', { exact: true }).waitFor();
assert.equal(await journal.locator('details').count(), 4);
await journal.getByLabel('Start date', { exact: true }).fill('2026-11-01');
await journal.getByText('2 occurrences in this date range', { exact: true }).waitFor(); // Both repeated hours on the inclusive end date.
await journal.getByLabel('Journal view').selectOption('month');
await journal.getByText('1 occurrence this month', { exact: true }).waitFor();
await journal.getByRole('button', { name: 'Record behavior' }).click();
assert.match(await journal.getByLabel('Date and time', { exact: true }).inputValue(), /^2026-10-05T12:00(:00)?$/);
await journal.getByLabel('Behavior', { exact: true }).selectOption('custom');
@@ -104,9 +113,9 @@ try {
await editedEntry.getByRole('button', { name: 'Delete', exact: true }).click();
await journal.getByText('Occurrence deleted.', { exact: true }).waitFor();
await journal.getByRole('button', { name: '10/5/2026: 1 occurrences', exact: true }).waitFor();
await journal.getByLabel('Bird', { exact: true }).selectOption(secondBird);
await page.locator('.bird-card-select').filter({ hasText: 'Willow' }).click();
await journal.getByText('0 occurrences this month', { exact: true }).waitFor();
await journal.getByLabel('Bird', { exact: true }).selectOption(bird);
await page.locator('.bird-card-select').filter({ hasText: 'Piper' }).click();
await journal.getByText('2 occurrences this month', { exact: true }).waitFor();
await page.setViewportSize({ width: 1280, height: 1000 });
await journal.scrollIntoViewIfNeeded();
@@ -124,7 +133,7 @@ try {
await utcJournal.getByRole('button', { name: '10/1/2026: 2 occurrences', exact: true }).waitFor();
await utcContext.close();
assert.deepEqual(errors, []);
console.log('PASS: browser create/custom type/edit/delete, bird/behavior filters, month navigation, multiple events/day, local midnight and DST, and mobile layout.');
console.log('PASS: browser create/custom type/edit/delete, member journals and behavior filters, month navigation, multiple events/day, local midnight and DST, and mobile layout.');
} catch (error) {
if (page) {
console.error(await page.locator('.behavior-journal').innerText().catch(() => 'Journal unavailable'));
+1 -1
View File
@@ -28,7 +28,7 @@ try {
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, education_opt_out) VALUES ($1, $2, 'Browser tester', TRUE)`, [user, email]);
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 });
+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);
});