13 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
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
Corey Blais 55353e4d46 Add flock exports, sharing invitations, and improved flock switching
Deploy / deploy-prod (push) Skipped
Deploy / deploy-dev (push) Successful in 3m53s
2026-10-08 11:19:50 -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 ff177dbaed Ghosted memorial birds
Deploy / deploy-prod (push) Skipped
Deploy / deploy-dev (push) Successful in 3m0s
2026-10-07 21:51:25 -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 270652f1a8 Fixed location timeline
Deploy / deploy-prod (push) Skipped
Deploy / deploy-dev (push) Successful in 2m35s
2026-10-07 21:31:07 -04:00
blaisadmin 56d8818581 Pass Mapbox Actions secret to deployment Compose steps
Deploy / deploy-prod (push) Skipped
Deploy / deploy-dev (push) Successful in 1m47s
2026-10-07 20:31:20 -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
32 changed files with 1072 additions and 196 deletions

No files matched your search

+8
View File
@@ -37,12 +37,16 @@ jobs:
docker run --rm -v "$PWD/frontend:/src:ro" -w /tmp/app node:22-alpine sh -lc "cp -a /src/. /tmp/app && npm ci && npm run build" docker run --rm -v "$PWD/frontend:/src:ro" -w /tmp/app node:22-alpine sh -lc "cp -a /src/. /tmp/app && npm ci && npm run build"
- name: Validate dev compose config - name: Validate dev compose config
env:
MAPBOX_ACCESS_TOKEN: ${{ secrets.MAPBOX_ACCESS_TOKEN }}
run: | run: |
set -e set -e
cd /docker/FlockPal-dev cd /docker/FlockPal-dev
docker compose -f docker-compose.dev.yaml config --quiet docker compose -f docker-compose.dev.yaml config --quiet
- name: Deploy dev - name: Deploy dev
env:
MAPBOX_ACCESS_TOKEN: ${{ secrets.MAPBOX_ACCESS_TOKEN }}
run: | run: |
set -e set -e
cd /docker/FlockPal-dev cd /docker/FlockPal-dev
@@ -137,12 +141,16 @@ jobs:
docker run --rm -v "$PWD/frontend:/src:ro" -w /tmp/app node:22-alpine sh -lc "cp -a /src/. /tmp/app && npm ci && npm run build" docker run --rm -v "$PWD/frontend:/src:ro" -w /tmp/app node:22-alpine sh -lc "cp -a /src/. /tmp/app && npm ci && npm run build"
- name: Validate prod compose config - name: Validate prod compose config
env:
MAPBOX_ACCESS_TOKEN: ${{ secrets.MAPBOX_ACCESS_TOKEN }}
run: | run: |
set -e set -e
cd /docker/FlockPal cd /docker/FlockPal
docker compose -f docker-compose.prod.yml config --quiet docker compose -f docker-compose.prod.yml config --quiet
- name: Deploy prod - name: Deploy prod
env:
MAPBOX_ACCESS_TOKEN: ${{ secrets.MAPBOX_ACCESS_TOKEN }}
run: | run: |
set -e set -e
cd /docker/FlockPal cd /docker/FlockPal
+4 -3
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:
@@ -103,7 +104,7 @@ curl -H "Authorization: Bearer <admin-token>" https://your-host/api/metrics
- `FRONTEND_URL` - `FRONTEND_URL`
- `BACKEND_URL` - `BACKEND_URL`
- `VITE_API_BASE_URL` - `VITE_API_BASE_URL`
- `MAPBOX_ACCESS_TOKEN` - `MAPBOX_ACCESS_TOKEN` as a Gitea Actions secret for automated deployments (or in `.env` for manual Compose deployments)
- `REDIS_URL` - `REDIS_URL`
- `IMAGE_STORAGE_PROVIDER` - `IMAGE_STORAGE_PROVIDER`
- `S3_ENDPOINT` - `S3_ENDPOINT`
+85 -37
View File
@@ -1,3 +1,8 @@
import { createReadinessHandler } from './health/readiness.js';
import { photoCacheControl } from './storage/photoCache.js';
import { canUpdateWorkspaceSettings, subscriptionAllowsWrite } from './workspaceAccess.js';
import { buildWorkspaceInviteEmail } from './emails/workspaceInviteEmail.js';
import { exportFlock } from './repositories/flockExportRepository.js';
import { unassignedBirdMatchSchema, claimBirdSchema } from './birdMembershipSchemas.js'; import { unassignedBirdMatchSchema, claimBirdSchema } from './birdMembershipSchemas.js';
import { hasUnassignedBird, removeBirdFromFlock, claimUnassignedBird } from './repositories/birdMembershipRepository.js'; import { hasUnassignedBird, removeBirdFromFlock, claimUnassignedBird } from './repositories/birdMembershipRepository.js';
import { behaviorTypeSchema, behaviorOccurrenceSchema, behaviorRangeSchema } from './behaviorSchemas.js'; import { behaviorTypeSchema, behaviorOccurrenceSchema, behaviorRangeSchema } from './behaviorSchemas.js';
@@ -986,14 +991,6 @@ const normalizeWorkspaceMembershipList = async (userId: string) =>
const isAdminUser = (user: UserRow) => adminEmails.has(normalizeEmail(user.email)); const isAdminUser = (user: UserRow) => adminEmails.has(normalizeEmail(user.email));
const subscriptionAllowsWrite = (workspace: WorkspaceRow) => {
if (workspace.workspace_type === 'rescue') {
return workspace.rescue_verification_status === 'approved';
}
return workspace.subscription_status === 'active' || workspace.subscription_status === 'trialing';
};
const mapStripeSubscriptionStatus = (status: Stripe.Subscription.Status): SubscriptionStatus => { const mapStripeSubscriptionStatus = (status: Stripe.Subscription.Status): SubscriptionStatus => {
if (status === 'active' || status === 'trialing' || status === 'past_due' || status === 'canceled' || status === 'unpaid') { if (status === 'active' || status === 'trialing' || status === 'past_due' || status === 'canceled' || status === 'unpaid') {
return status; return status;
@@ -2214,33 +2211,19 @@ const writeBirdTimelineEvent = async ({
} }
}; };
const isBillingOnlyWorkspaceUpdate = ( const readinessHandler = createReadinessHandler([
workspace: WorkspaceRow, () => db.query('SELECT 1'),
payload: z.infer<typeof workspaceSchema>, () => getBirdMilestoneReminderQueueCounts(),
) => workspace.workspace_type === 'standard' && payload.workspaceType === 'standard' && payload.name === workspace.name; () => getMedicationReminderQueueCounts(),
]);
app.get('/api/health', (_req: Request, res: Response) => { app.get(['/api/health', '/api/health/ready'], readinessHandler);
res.json({ ok: true });
});
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;
@@ -2964,6 +2947,40 @@ app.post('/api/workspaces', requireAuth, requireSessionAuth, async (req: Request
} }
}); });
app.get('/api/workspace/export', requireAuth, requireSessionAuth, async (req: Request, res: Response, next: NextFunction) => {
try {
const parsed = z.object({ birdId: z.string().uuid().optional() }).safeParse(req.query);
if (!parsed.success) {
res.status(400).json({ error: 'Invalid bird selection.' });
return;
}
const { birdId } = parsed.data;
const data = await exportFlock(req.auth!.workspace.id, birdId);
if (birdId && data.birds.length === 0) {
res.status(404).json({ error: 'Bird not found in this flock.' });
return;
}
for (const bird of data.birds) {
if (bird.photo_object_key) {
const config = getS3ImageStorageConfig();
if (!config) throw new Error('Image storage is not configured. Unable to export flock photos.');
const response = await fetch(getSignedS3ObjectUrl({ config, objectKey: bird.photo_object_key, expiresInSeconds: 300 }), {
signal: AbortSignal.timeout(30_000),
});
if (!response.ok) throw new Error('Unable to export a flock photo. Please try again.');
const contentType = bird.photo_content_type || response.headers.get('content-type') || 'application/octet-stream';
bird.photo_data_url = `data:${contentType};base64,${Buffer.from(await response.arrayBuffer()).toString('base64')}`;
}
delete bird.photo_object_key;
}
res.setHeader('Cache-Control', 'no-store');
res.attachment(`flockpal-${birdId ? `bird-${birdId}` : `flock-${req.auth!.workspace.id}`}-${new Date().toISOString().slice(0, 10)}.json`);
res.json(data);
} catch (error) {
next(error);
}
});
app.get('/api/workspace', requireAuth, async (req: Request, res: Response) => { app.get('/api/workspace', requireAuth, async (req: Request, res: Response) => {
res.json({ workspace: normalizeWorkspace(req.auth!.workspace) }); res.json({ workspace: normalizeWorkspace(req.auth!.workspace) });
}); });
@@ -2981,10 +2998,7 @@ app.put('/api/workspace', requireAuth, requireSessionAuth, requireWorkspaceRole(
const billingPlan = resolveBillingPlan(parsed.data.workspaceType, parsed.data.billingPlan ?? currentWorkspace.billing_plan); const billingPlan = resolveBillingPlan(parsed.data.workspaceType, parsed.data.billingPlan ?? currentWorkspace.billing_plan);
const billingInterval = parsed.data.workspaceType === 'rescue' ? 'monthly' : (parsed.data.billingInterval ?? currentWorkspace.billing_interval); const billingInterval = parsed.data.workspaceType === 'rescue' ? 'monthly' : (parsed.data.billingInterval ?? currentWorkspace.billing_interval);
const isConvertingToRescue = currentWorkspace.workspace_type !== 'rescue' && parsed.data.workspaceType === 'rescue'; const isConvertingToRescue = currentWorkspace.workspace_type !== 'rescue' && parsed.data.workspaceType === 'rescue';
const canUpdateWorkspace = const canUpdateWorkspace = canUpdateWorkspaceSettings(currentWorkspace, parsed.data, isAdminUser(req.auth!.user));
isAdminUser(req.auth!.user) ||
subscriptionAllowsWrite(currentWorkspace) ||
isBillingOnlyWorkspaceUpdate(currentWorkspace, parsed.data);
if (!canUpdateWorkspace) { if (!canUpdateWorkspace) {
res.status(402).json({ res.status(402).json({
@@ -3130,6 +3144,37 @@ app.get('/api/workspace/members', requireAuth, async (req: Request, res: Respons
} }
}); });
const sendWorkspaceInvitation = async (auth: AuthContext, member: WorkspaceMemberRow) => {
if (!mailTransport) return { sent: false, message: 'Access is saved, but email delivery is not configured. Share the sign-in instructions directly.' };
try {
const result = await mailTransport.sendMail({
from: smtpFromName ? `"${smtpFromName}" <${smtpFromEmail}>` : smtpFromEmail,
to: member.invite_email,
...await buildWorkspaceInviteEmail({
name: member.name, email: member.invite_email, inviterName: auth.user.name,
flockName: auth.workspace.name, role: member.role, frontendUrl: frontendBaseUrl,
}),
});
if (!result.accepted?.length) throw new Error('Invitation email was not accepted.');
return { sent: true, message: 'Invitation email sent. Access is ready when they sign in with the invited email address.' };
} catch {
return { sent: false, message: 'Access is saved, but the invitation email could not be sent. Use Resend invitation to try again.' };
}
};
app.post('/api/workspace/members/:memberId/invitation', requireAuth, requireSessionAuth, requireWriteAccess, requireWorkspaceRole(['owner', 'assistant']), async (req: Request, res: Response, next: NextFunction) => {
try {
const member = (await listWorkspaceMembers(req.auth!.workspace.id)).find((entry) => entry.id === req.params.memberId);
if (!member) {
res.status(404).json({ error: 'Flock member not found.' });
return;
}
const invitation = await sendWorkspaceInvitation(req.auth!, member);
await writeAuditLog(req.auth!, 'workspace_member.invitation_resent', 'workspace_member', member.id, member.name, { sent: invitation.sent });
res.json({ invitation });
} catch (error) { next(error); }
});
app.post('/api/workspace/members', requireAuth, requireWriteAccess, requireWorkspaceRole(['owner', 'assistant']), async (req: Request, res: Response, next: NextFunction) => { app.post('/api/workspace/members', requireAuth, requireWriteAccess, requireWorkspaceRole(['owner', 'assistant']), async (req: Request, res: Response, next: NextFunction) => {
const parsed = workspaceMemberSchema.safeParse(req.body); const parsed = workspaceMemberSchema.safeParse(req.body);
@@ -3153,7 +3198,8 @@ app.post('/api/workspace/members', requireAuth, requireWriteAccess, requireWorks
inviteEmail: member!.invite_email, inviteEmail: member!.invite_email,
role: member!.role, role: member!.role,
}); });
res.status(201).json({ member: normalizeWorkspaceMember(member!) }); const invitation = await sendWorkspaceInvitation(req.auth!, member!);
res.status(201).json({ member: normalizeWorkspaceMember(member!), invitation });
} catch (error) { } catch (error) {
next(error); next(error);
} }
@@ -3443,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);
@@ -3472,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;
} }
@@ -3490,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) {
@@ -3963,7 +4011,7 @@ app.put('/api/birds/:birdId', requireAuth, requireWriteAccess, requireWorkspaceR
} }
}); });
app.delete('/api/birds/:birdId', requireAuth, requireWriteAccess, requireWorkspaceRole(['owner', 'assistant', 'caregiver']), async (req: Request, res: Response, next: NextFunction) => { app.delete('/api/birds/:birdId', requireAuth, requireWriteAccess, requireWorkspaceRole(['owner', 'assistant']), async (req: Request, res: Response, next: NextFunction) => {
try { try {
const bird = await getBirdById(req.params.birdId, req.auth!.workspace.id); const bird = await getBirdById(req.params.birdId, req.auth!.workspace.id);
+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>;
+17
View File
@@ -115,3 +115,20 @@ test('Swagger UI, initialization, assets and specification are served locally wi
assert.equal(redirect.status, 301); assert.equal(redirect.status, 301);
assert.equal(redirect.headers.get('location'), '/api/docs/'); assert.equal(redirect.headers.get('location'), '/api/docs/');
}); });
test('bird removal is restricted to owners and assistants in the API and its documentation', () => {
const route = ast.statements.find((statement) =>
ts.isExpressionStatement(statement) && ts.isCallExpression(statement.expression) &&
statement.expression.expression.getText(ast) === 'app.delete' &&
statement.expression.arguments[0]?.getText(ast) === "'/api/birds/:birdId'"
);
assert.ok(route && ts.isExpressionStatement(route) && ts.isCallExpression(route.expression));
const guard = route.expression.arguments.find((arg) =>
ts.isCallExpression(arg) && arg.expression.getText(ast) === 'requireWorkspaceRole'
);
assert.ok(guard && ts.isCallExpression(guard));
assert.equal(guard.arguments[0].getText(ast), "['owner', 'assistant']");
const description = customerOpenApi.paths['/birds/{birdId}']!.delete!.description!;
assert.match(description, /Allowed roles: owner, assistant\./);
assert.doesNotMatch(description, /caregiver/);
});
+3 -3
View File
@@ -63,7 +63,7 @@ const one = (name: string, model: z.ZodTypeAny) => z.object({ [name]: model });
const many = (name: string, model: z.ZodTypeAny) => one(name, z.array(model)); const many = (name: string, model: z.ZodTypeAny) => one(name, z.array(model));
endpoint({ method: 'get', path: '/workspace', summary: 'Get the token’s workspace', tag: 'Workspace', response: one('workspace', models.workspaceResponse) }); endpoint({ method: 'get', path: '/workspace', summary: 'Get the token’s workspace', tag: 'Workspace', response: one('workspace', models.workspaceResponse) });
endpoint({ method: 'get', path: '/workspace/members', summary: 'List workspace members', tag: 'Workspace', response: many('members', models.memberResponse) }); endpoint({ method: 'get', path: '/workspace/members', summary: 'List workspace members', tag: 'Workspace', response: many('members', models.memberResponse) });
endpoint({ method: 'post', path: '/workspace/members', summary: 'Add or update a workspace member', tag: 'Workspace', body: registry.register('MemberInput', workspaceMemberSchema), response: one('member', models.memberResponse), roles: ['owner', 'assistant'] }); endpoint({ method: 'post', path: '/workspace/members', summary: 'Add or update a workspace member', tag: 'Workspace', body: registry.register('MemberInput', workspaceMemberSchema), response: z.object({ member: models.memberResponse, invitation: z.object({ sent: z.boolean(), message: z.string() }) }), roles: ['owner', 'assistant'], description: 'Saves access and attempts to send a branded invitation email. Check invitation.sent for email submission status; access remains saved if email delivery fails.' });
endpoint({ method: 'put', path: '/workspace/members/{memberId}', summary: 'Change a member’s role', tag: 'Workspace', body: z.object({ role: workspaceRoleSchema }), response: one('member', models.memberResponse), roles: ['owner', 'assistant'], errors: [404], description: 'Only the billing owner can promote collaborators to owner. Additional protections apply to changing your own or the billing owner’s membership.' }); endpoint({ method: 'put', path: '/workspace/members/{memberId}', summary: 'Change a member’s role', tag: 'Workspace', body: z.object({ role: workspaceRoleSchema }), response: one('member', models.memberResponse), roles: ['owner', 'assistant'], errors: [404], description: 'Only the billing owner can promote collaborators to owner. Additional protections apply to changing your own or the billing owner’s membership.' });
endpoint({ method: 'delete', path: '/workspace/members/{memberId}', summary: 'Remove a workspace member', tag: 'Workspace', roles: ['owner', 'assistant'], errors: [404], description: 'Protected memberships cannot be removed.' }); endpoint({ method: 'delete', path: '/workspace/members/{memberId}', summary: 'Remove a workspace member', tag: 'Workspace', roles: ['owner', 'assistant'], errors: [404], description: 'Protected memberships cannot be removed.' });
endpoint({ method: 'get', path: '/notes', summary: 'List flock notes', tag: 'Notes', response: many('notes', models.noteResponse) }); endpoint({ method: 'get', path: '/notes', summary: 'List flock notes', tag: 'Notes', response: many('notes', models.noteResponse) });
@@ -77,7 +77,7 @@ const birdInput = registry.register('BirdInput', birdSchema);
const birdDescription = 'motivators and demotivators each allow up to three non-empty lines. hatchDay takes precedence over the legacy dateOfBirth field. photoDataUrl accepts an image data URL or HTTP(S) URL; returned photo links may expire.'; const birdDescription = 'motivators and demotivators each allow up to three non-empty lines. hatchDay takes precedence over the legacy dateOfBirth field. photoDataUrl accepts an image data URL or HTTP(S) URL; returned photo links may expire.';
endpoint({ method: 'post', path: '/birds', summary: 'Create a bird', tag: 'Birds', body: birdInput, response: one('bird', models.birdResponse), errors: [409], description: birdDescription, example: { name: 'Yoda', species: 'African grey' } }); endpoint({ method: 'post', path: '/birds', summary: 'Create a bird', tag: 'Birds', body: birdInput, response: one('bird', models.birdResponse), errors: [409], description: birdDescription, example: { name: 'Yoda', species: 'African grey' } });
endpoint({ method: 'put', path: '/birds/{birdId}', summary: 'Update a bird', tag: 'Birds', body: birdInput, response: one('bird', models.birdResponse), errors: [404, 409], description: `Submit the full editable profile: omitted optional fields may be cleared or reset. ${birdDescription}` }); endpoint({ method: 'put', path: '/birds/{birdId}', summary: 'Update a bird', tag: 'Birds', body: birdInput, response: one('bird', models.birdResponse), errors: [404, 409], description: `Submit the full editable profile: omitted optional fields may be cleared or reset. ${birdDescription}` });
endpoint({ method: 'delete', path: '/birds/{birdId}', summary: 'Remove a bird from its flock', tag: 'Birds', errors: [404, 409], description: 'Unassigns the bird without deleting its profile, photo, or care history. Bird-specific notes follow the bird; flock-wide notes and workspace audit logs stay in the old flock. Public sharing is disabled and pending transfers are revoked. An exact band ID match can later bring the bird and its history into a flock.' }); endpoint({ method: 'delete', path: '/birds/{birdId}', summary: 'Remove a bird from its flock', roles: ['owner', 'assistant'], tag: 'Birds', errors: [404, 409], description: 'Unassigns the bird without deleting its profile, photo, or care history. Bird-specific notes follow the bird; flock-wide notes and workspace audit logs stay in the old flock. Public sharing is disabled and pending transfers are revoked. An exact band ID match can later bring the bird and its history into a flock.' });
endpoint({ method: 'get', path: '/birds/{birdId}/timeline', summary: 'List bird timeline events', tag: 'Birds', response: many('events', models.timelineResponse), errors: [404] }); endpoint({ method: 'get', path: '/birds/{birdId}/timeline', summary: 'List bird timeline events', tag: 'Birds', response: many('events', models.timelineResponse), errors: [404] });
for (const resource of [ for (const resource of [
{ path: 'weights', single: 'weight', plural: 'weights', id: 'weightId', tag: 'Weights', input: weightSchema, model: models.weightResponse }, { path: 'weights', single: 'weight', plural: 'weights', id: 'weightId', tag: 'Weights', input: weightSchema, model: models.weightResponse },
@@ -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] });
@@ -0,0 +1,29 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { buildWorkspaceInviteEmail } from './workspaceInviteEmail.js';
const input = { name: '<Pat>', email: 'pat@example.test', inviterName: 'Alex & Sam', flockName: '<Rescue>', role: 'caregiver' as const, frontendUrl: 'https://flockpal.test/' };
test('invitation uses branded layout, escaped copy, and email-specific sign-in instructions', async () => {
const mail = await buildWorkspaceInviteEmail(input);
assert.match(String(mail.html), /&lt;Pat&gt;/);
assert.match(String(mail.html), /Alex &amp; Sam/);
assert.match(String(mail.html), /&lt;Rescue&gt;/);
assert.match(String(mail.html), /cid:flockpal-logo/);
assert.equal(mail.attachments?.length, 1);
assert.match(mail.text, /Sign in to FlockPal using pat@example.test/);
assert.match(mail.text, /cannot remove birds/);
assert.match(mail.text, /flock switcher/);
assert.match(String(mail.html), /href="https:\/\/flockpal.test\/"/);
});
test('invitation describes each assigned role and prevents multiline subjects', async () => {
for (const role of ['viewer', 'caregiver', 'assistant', 'owner'] as const) {
const mail = await buildWorkspaceInviteEmail({ ...input, role, flockName: 'Rescue\r\nFlock' });
assert.doesNotMatch(mail.subject, /[\r\n]/);
assert.ok(mail.text.includes(role.charAt(0).toUpperCase() + role.slice(1)));
if (role === 'viewer') assert.match(mail.text, /cannot edit records/);
if (role === 'assistant') assert.match(mail.text, /remove and transfer birds/);
if (role === 'owner') assert.match(mail.text, /does not change the billing owner/);
}
});
@@ -0,0 +1,26 @@
import { buildEmailLayout, escapeHtml } from './emailLayout.js';
import type { WorkspaceRole } from '../types.js';
const permissions: Record<WorkspaceRole, string> = {
viewer: 'You can view all birds and care histories, and export flock data. You cannot edit records.',
caregiver: 'You can view and export flock data, add and edit birds, log daily care, and delete supported care records. You cannot remove birds or manage sharing, billing, or transfers.',
assistant: 'You can manage birds and care records, remove and transfer birds, manage collaborators, flock settings and billing, and view the audit log.',
owner: 'You have full flock control, including bird removal, transfers, sharing, billing management, memorializing birds, and deleting an empty flock. This does not change the billing owner.',
};
export const buildWorkspaceInviteEmail = async ({ name, email, inviterName, flockName, role, frontendUrl }: {
name: string; email: string; inviterName: string; flockName: string; role: WorkspaceRole; frontendUrl: string;
}) => {
const roleLabel = role.charAt(0).toUpperCase() + role.slice(1);
const instructions = `Sign in to FlockPal using ${email}. If you do not have an account, use that email to get started. After signing in, choose ${flockName} in the flock switcher in the navigation or Settings → Flock profile. If you are already signed in and the flock is missing, sign out and sign back in.`;
return {
subject: `You’re invited to ${flockName.replace(/[\r\n]+/g, ' ')} on FlockPal`,
text: `Hi ${name},\n\n${inviterName} has invited you to ${flockName} as a ${roleLabel}.\n\n${permissions[role]}\n\n${instructions}\n\nOpen FlockPal: ${frontendUrl}\n\nIf you were not expecting this invitation, you can ignore this email.`,
...await buildEmailLayout({
eyebrow: 'Shared flock invitation', headline: `You’re invited to ${flockName}`,
contentHtml: `<p>Hi ${escapeHtml(name)},</p><p>${escapeHtml(inviterName)} has invited you to <strong>${escapeHtml(flockName)}</strong> as a <strong>${roleLabel}</strong>.</p><p>${escapeHtml(permissions[role])}</p><p>${escapeHtml(instructions)}</p>`,
action: { url: frontendUrl, label: 'Open FlockPal' },
footer: 'If you were not expecting this invitation, you can ignore this email.',
}),
};
};
+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);
}
};
@@ -0,0 +1,20 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { createFlockNote, deleteFlockNote } from './auditRepository.js';
import { mockDb } from '../test/mockDb.js';
test('bird notes require a current, non-memorialized bird in the workspace', async () => {
const { calls } = mockDb({ rows: [] });
const result = await createFlockNote({ workspaceId: 1, birdId: 'bird-1', body: 'Note', createdByUserId: 'user-1' });
assert.equal(result, null);
assert.match(calls[0].text, /birds.workspace_id = \$1\s+AND birds.memorialized_at IS NULL/);
assert.deepEqual(calls[0].params, [1, 'bird-1', 'Note', 'Note', 'user-1']);
});
test('deleting bird notes preserves memorialized and transferred bird history', async () => {
const { calls } = mockDb({ rows: [] });
assert.equal(await deleteFlockNote('note-1', 1), null);
assert.match(calls[0].text, /bird_id IS NULL OR EXISTS/);
assert.match(calls[0].text, /birds.id = flock_notes.bird_id/);
assert.match(calls[0].text, /birds.workspace_id = \$2\s+AND birds.memorialized_at IS NULL/);
});
@@ -98,6 +98,7 @@ export const createFlockNote = async ({
FROM birds FROM birds
WHERE birds.id = $2 WHERE birds.id = $2
AND birds.workspace_id = $1 AND birds.workspace_id = $1
AND birds.memorialized_at IS NULL
) )
RETURNING id, workspace_id, bird_id, title, body, created_by_user_id, created_at, updated_at RETURNING id, workspace_id, bird_id, title, body, created_by_user_id, created_at, updated_at
) )
@@ -125,6 +126,12 @@ export const deleteFlockNote = async (noteId: string, workspaceId: number) => {
`DELETE FROM flock_notes `DELETE FROM flock_notes
WHERE id = $1 WHERE id = $1
AND workspace_id = $2 AND workspace_id = $2
AND (bird_id IS NULL OR EXISTS (
SELECT 1 FROM birds
WHERE birds.id = flock_notes.bird_id
AND birds.workspace_id = $2
AND birds.memorialized_at IS NULL
))
RETURNING id, title`, RETURNING id, title`,
[noteId, workspaceId], [noteId, workspaceId],
); );
@@ -0,0 +1,31 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { exportFlock } from './flockExportRepository.js';
import { mockDb } from '../test/mockDb.js';
test('export scopes every history to the selected flock without date or memorial filters', async () => {
const data = { formatVersion: 1, birds: [], workspace: { id: 42, name: 'Flock' } };
const { calls } = mockDb({ rows: [{ data }] });
assert.deepEqual(await exportFlock(42), data);
assert.equal(calls.length, 1);
const { text, params } = calls[0];
assert.deepEqual(params, [42, null]);
assert.match(text, /SELECT \* FROM birds WHERE workspace_id = \$1/);
for (const table of ['weight_records', 'vet_visits', 'medications', 'medication_administrations', 'behavior_occurrences', 'bird_timeline_events']) {
assert.ok(text.includes(`FROM ${table} r JOIN flock_birds b ON b.id = r.bird_id`));
}
assert.match(text, /FROM flock_notes n WHERE n.workspace_id = \$1/);
assert.doesNotMatch(text, /LIMIT|memorialized_at IS NULL|INTERVAL/);
assert.doesNotMatch(text, /auth_sessions|integration_tokens|stripe|magic_link/);
});
test('single member export restricts profiles, notes, and behavior types to the selected bird', async () => {
const birdId = 'd0ab1d12-7859-4a64-a354-dd58bf738b94';
const data = { birds: [{ id: birdId }] };
const { calls } = mockDb({ rows: [{ data }] });
assert.deepEqual(await exportFlock(42, birdId), data);
assert.deepEqual(calls[0].params, [42, birdId]);
assert.ok(calls[0].text.includes('workspace_id = $1 AND ($2::uuid IS NULL OR id = $2)'));
assert.ok(calls[0].text.includes('AND ($2::uuid IS NULL OR n.bird_id IN (SELECT id FROM flock_birds))'));
assert.ok(calls[0].text.includes('WHERE ($2::uuid IS NULL AND (t.is_default OR t.workspace_id = $1)) OR EXISTS'));
});
@@ -0,0 +1,48 @@
import { db } from '../db/client.js';
type ExportBird = Record<string, unknown> & {
photo_object_key?: string | null;
photo_content_type?: string | null;
photo_data_url?: string | null;
};
export type FlockExport = {
formatVersion: number;
exportedAt: string;
workspace: { id: number; name: string };
birds: ExportBird[];
[key: string]: unknown;
};
// A single statement provides a consistent snapshot, including all dates and memorialized birds.
export const exportFlock = async (workspaceId: number, birdId?: string): Promise<FlockExport> => {
const birdTables = {
weights: 'weight_records',
vetVisits: 'vet_visits',
medications: 'medications',
medicationAdministrations: 'medication_administrations',
behaviors: 'behavior_occurrences',
timeline: 'bird_timeline_events',
};
const histories = Object.entries(birdTables).map(([key, table]) =>
`'${key}', (SELECT COALESCE(jsonb_agg(to_jsonb(r) ORDER BY r.id), '[]'::jsonb)
FROM ${table} r JOIN flock_birds b ON b.id = r.bird_id)`
);
const result = await db.query<{ data: FlockExport }>(`
WITH flock_birds AS (SELECT * FROM birds WHERE workspace_id = $1 AND ($2::uuid IS NULL OR id = $2))
SELECT jsonb_build_object(
'formatVersion', 1,
'exportedAt', CURRENT_TIMESTAMP,
'workspace', (SELECT jsonb_build_object('id', id, 'name', name) FROM workspaces WHERE id = $1),
'birds', (SELECT COALESCE(jsonb_agg(to_jsonb(b) ORDER BY b.id), '[]'::jsonb) FROM flock_birds b),
'notes', (SELECT COALESCE(jsonb_agg(to_jsonb(n) ORDER BY n.id), '[]'::jsonb)
FROM flock_notes n WHERE n.workspace_id = $1
AND ($2::uuid IS NULL OR n.bird_id IN (SELECT id FROM flock_birds))),
'behaviorTypes', (SELECT COALESCE(jsonb_agg(to_jsonb(t) - 'workspace_id' ORDER BY t.id), '[]'::jsonb)
FROM behavior_types t WHERE ($2::uuid IS NULL AND (t.is_default OR t.workspace_id = $1)) OR EXISTS (
SELECT 1 FROM behavior_occurrences o JOIN flock_birds b ON b.id = o.bird_id
WHERE o.behavior_type_id = t.id)),
${histories.join(',\n')}
) AS data`, [workspaceId, birdId ?? null]);
return result.rows[0].data;
};
+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);
});
+30
View File
@@ -0,0 +1,30 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { canUpdateWorkspaceSettings, subscriptionAllowsWrite } from '../workspaceAccess.js';
import type { WorkspaceRow } from '../types.js';
type Access = Pick<WorkspaceRow, 'name' | 'workspace_type' | 'subscription_status' | 'rescue_verification_status'>;
const household: Access = { name: 'Our flock', workspace_type: 'standard', subscription_status: 'none', rescue_verification_status: 'not_required' };
test('unsubscribed households can request rescue verification, including a new flock name', () => {
for (const subscription_status of ['none', 'past_due', 'canceled', 'unpaid', 'active', 'trialing'] as const) {
assert.equal(canUpdateWorkspaceSettings({ ...household, subscription_status }, { name: 'Our rescue', workspaceType: 'rescue' }, false), true);
}
});
test('conversion does not make unverified rescues writable, even with an active subscription', () => {
for (const rescue_verification_status of ['pending', 'rejected', 'not_required'] as const) {
const rescue: Access = { ...household, workspace_type: 'rescue', subscription_status: 'active', rescue_verification_status };
assert.equal(subscriptionAllowsWrite(rescue), false);
assert.equal(canUpdateWorkspaceSettings(rescue, { name: rescue.name, workspaceType: 'rescue' }, false), false);
}
assert.equal(subscriptionAllowsWrite({ ...household, workspace_type: 'rescue', rescue_verification_status: 'approved' }), true);
});
test('household edits remain subscription gated while billing recovery and admin access still work', () => {
assert.equal(subscriptionAllowsWrite(household), false);
assert.equal(canUpdateWorkspaceSettings(household, { name: 'Renamed', workspaceType: 'standard' }, false), false);
assert.equal(canUpdateWorkspaceSettings(household, { name: household.name, workspaceType: 'standard' }, false), true);
assert.equal(canUpdateWorkspaceSettings(household, { name: 'Renamed', workspaceType: 'standard' }, true), true);
assert.equal(subscriptionAllowsWrite({ ...household, subscription_status: 'active' }), true);
});
+22
View File
@@ -0,0 +1,22 @@
import type { WorkspaceRow, WorkspaceType } from './types.js';
type WorkspaceAccess = Pick<WorkspaceRow, 'name' | 'workspace_type' | 'subscription_status' | 'rescue_verification_status'>;
export const subscriptionAllowsWrite = (workspace: WorkspaceAccess) => {
if (workspace.workspace_type === 'rescue') {
return workspace.rescue_verification_status === 'approved';
}
return workspace.subscription_status === 'active' || workspace.subscription_status === 'trialing';
};
export const canUpdateWorkspaceSettings = (
workspace: WorkspaceAccess,
payload: { name: string; workspaceType: WorkspaceType },
isAdmin: boolean,
) => {
// Requesting rescue verification must not require buying a household subscription.
// The route still validates onboarding and the repository marks the rescue pending.
const requestingRescue = workspace.workspace_type === 'standard' && payload.workspaceType === 'rescue';
const billingOnly = workspace.workspace_type === 'standard' && payload.workspaceType === 'standard' && payload.name === workspace.name;
return isAdmin || subscriptionAllowsWrite(workspace) || requestingRescue || billingOnly;
};
+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>
+228 -91
View File
@@ -1,3 +1,6 @@
import { usePhotoRefresh } from './usePhotoRefresh';
import { FlockSwitcher } from './FlockSwitcher';
import { combineLocationOwnerMarkers } from './birdTimeline';
import { BehaviorJournal } from './BehaviorJournal'; import { BehaviorJournal } from './BehaviorJournal';
import { useEffect, useMemo, useState, type CSSProperties, type Dispatch, type SetStateAction } from 'react'; import { useEffect, useMemo, useState, type CSSProperties, type Dispatch, type SetStateAction } from 'react';
import birdSilhouette from './assets/bird-silhouette.jpg'; import birdSilhouette from './assets/bird-silhouette.jpg';
@@ -1146,7 +1149,7 @@ const formatBirdTimelineTitle = (event: BirdTimelineEvent) => {
} }
if (event.eventType === 'owner_changed') { if (event.eventType === 'owner_changed') {
return 'Owner record changed'; return 'Adopted';
} }
if (event.eventType === 'manual_note') { if (event.eventType === 'manual_note') {
@@ -1169,7 +1172,7 @@ const formatBirdTimelineDescription = (event: BirdTimelineEvent) => {
} }
if (event.eventType === 'owner_changed') { if (event.eventType === 'owner_changed') {
return event.locationLabel ? `Owner changed at ${event.locationLabel}` : 'Owner changed'; return event.locationLabel ? `Adopted at ${event.locationLabel}` : 'Adopted';
} }
if (event.eventType === 'manual_note') { if (event.eventType === 'manual_note') {
@@ -1191,7 +1194,7 @@ const formatBirdTimelineSecondary = (event: BirdTimelineEvent) => {
} }
if (event.eventType === 'owner_changed') { if (event.eventType === 'owner_changed') {
return 'Owner changed without owner name'; return 'Adoption recorded without owner names';
} }
return ''; return '';
@@ -1246,7 +1249,7 @@ const getBirdTimelineGraphLabel = (event: BirdTimelineEvent) => {
} }
if (event.eventType === 'owner_changed') { if (event.eventType === 'owner_changed') {
return 'Owner changed'; return event.locationLabel ? `${compactTimelineLocationLabel(event.locationLabel)} — Adopted` : 'Adopted';
} }
if (event.eventType === 'transferred') { if (event.eventType === 'transferred') {
@@ -1346,7 +1349,7 @@ const compactTimelineLocationLabel = (label: string) =>
.join(', '); .join(', ');
const getBirdTimelineGraphItems = (bird: Bird, events: BirdTimelineEvent[]): BirdTimelineGraphItem[] => { const getBirdTimelineGraphItems = (bird: Bird, events: BirdTimelineEvent[]): BirdTimelineGraphItem[] => {
const graphEvents: BirdTimelineGraphItem[] = sortBirdTimelineEvents(events) const graphEvents: BirdTimelineGraphItem[] = sortBirdTimelineEvents(combineLocationOwnerMarkers(events, compactTimelineLocationLabel))
.reverse() .reverse()
.filter((event) => event.eventType !== 'profile_created') .filter((event) => event.eventType !== 'profile_created')
.map((event) => ({ .map((event) => ({
@@ -1798,6 +1801,20 @@ const formatRescueVerificationStatus = (status: RescueVerificationStatus) => {
return 'Pending verification'; return 'Pending verification';
}; };
const workspaceRoleDescriptions: Record<WorkspaceRole, string> = {
viewer: 'Can view every bird and their care history, and download flock or individual bird exports. Cannot edit birds or care records.',
caregiver: 'Can view and export, add and edit birds, record daily care, and delete supported care records. Cannot remove birds from the flock or manage sharing, billing, or bird transfers.',
assistant: 'Can do everything a Caregiver can, plus remove birds from the flock, manage collaborators, flock settings and billing, transfer birds, and view the audit log. Cannot memorialize birds or delete the flock.',
owner: 'Can do everything an Assistant can, plus memorialize birds, manage memorial reminders, and delete an empty flock. Owner access does not change the billing owner.',
};
const workspaceRoleLabels: Record<WorkspaceRole, string> = {
viewer: 'Viewer — view and export',
caregiver: 'Caregiver — birds and daily care',
assistant: 'Assistant — flock management',
owner: 'Owner — full flock control',
};
const formatWorkspaceRole = (role: WorkspaceRole) => { const formatWorkspaceRole = (role: WorkspaceRole) => {
if (role === 'owner') { if (role === 'owner') {
return 'Owner'; return 'Owner';
@@ -2171,6 +2188,9 @@ function App() {
const [birdImportPreview, setBirdImportPreview] = useState<BirdImportPreview | null>(null); const [birdImportPreview, setBirdImportPreview] = useState<BirdImportPreview | null>(null);
const [birdImportFileName, setBirdImportFileName] = useState(''); const [birdImportFileName, setBirdImportFileName] = useState('');
const [exportBirdId, setExportBirdId] = useState('');
const [exportingFlock, setExportingFlock] = useState(false);
const [flockExportError, setFlockExportError] = useState('');
const [birdImportNotice, setBirdImportNotice] = useState(''); const [birdImportNotice, setBirdImportNotice] = useState('');
const [importingBirds, setImportingBirds] = useState(false); const [importingBirds, setImportingBirds] = useState(false);
const [memorializeBirdForm, setMemorializeBirdForm] = useState<MemorializeBirdFormState>(emptyMemorializeBirdForm); const [memorializeBirdForm, setMemorializeBirdForm] = useState<MemorializeBirdFormState>(emptyMemorializeBirdForm);
@@ -2182,6 +2202,8 @@ function App() {
const [savingWorkspace, setSavingWorkspace] = useState(false); const [savingWorkspace, setSavingWorkspace] = useState(false);
const [cancelingRescueRequest, setCancelingRescueRequest] = useState(false); const [cancelingRescueRequest, setCancelingRescueRequest] = useState(false);
const [billingRedirecting, setBillingRedirecting] = useState(false); const [billingRedirecting, setBillingRedirecting] = useState(false);
const [invitationNotice, setInvitationNotice] = useState<{ sent: boolean; message: string } | null>(null);
const [resendingInvitationId, setResendingInvitationId] = useState<string | null>(null);
const [savingWorkspaceMember, setSavingWorkspaceMember] = useState(false); const [savingWorkspaceMember, setSavingWorkspaceMember] = useState(false);
const [creatingWorkspace, setCreatingWorkspace] = useState(false); const [creatingWorkspace, setCreatingWorkspace] = useState(false);
const [deletingWorkspace, setDeletingWorkspace] = useState(false); const [deletingWorkspace, setDeletingWorkspace] = useState(false);
@@ -2262,9 +2284,31 @@ function App() {
const [removingWorkspaceMemberId, setRemovingWorkspaceMemberId] = useState(''); const [removingWorkspaceMemberId, setRemovingWorkspaceMemberId] = useState('');
const [expandedSettingsSection, setExpandedSettingsSection] = useState<SettingsSection | null>(null); 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( const selectedBird = useMemo(
() => birds.find((bird) => bird.id === selectedBirdId) ?? null, () => flockBirds.find((bird) => bird.id === selectedBirdId) ?? null,
[birds, selectedBirdId], [flockBirds, selectedBirdId],
); );
const isBillingOwner = Boolean( const isBillingOwner = Boolean(
authSession?.user.email && authSession?.user.email &&
@@ -2981,7 +3025,7 @@ function App() {
setBirds(nextBirds); setBirds(nextBirds);
setMemorializedBirds(data.memorializedBirds ?? []); setMemorializedBirds(data.memorializedBirds ?? []);
setSelectedBirdId((current) => (current && nextBirds.some((bird) => bird.id === current) ? current : '')); setSelectedBirdId((current) => (current && [...nextBirds, ...(data.memorializedBirds ?? [])].some((bird) => bird.id === current) ? current : ''));
if (membersResponse.ok) { if (membersResponse.ok) {
const membersData = (await readJsonSafely<{ members?: WorkspaceMember[] }>(membersResponse)) ?? {}; const membersData = (await readJsonSafely<{ members?: WorkspaceMember[] }>(membersResponse)) ?? {};
@@ -3387,7 +3431,7 @@ function App() {
}; };
const handleWorkspaceSwitch = async (workspaceId: number, nextActivePage: AppPage = 'overview') => { const handleWorkspaceSwitch = async (workspaceId: number, nextActivePage: AppPage = 'overview') => {
if (!authToken || workspaceId === workspace?.id) { if (!authToken || switchingWorkspaceId !== null || workspaceId === workspace?.id) {
return; return;
} }
@@ -3679,6 +3723,7 @@ function App() {
}; };
const startEditBird = (bird: Bird) => { const startEditBird = (bird: Bird) => {
if (bird.memorializedAt) return;
setSelectedBirdId(bird.id); setSelectedBirdId(bird.id);
setEditingBirdId(bird.id); setEditingBirdId(bird.id);
setBirdEditorOpen(true); setBirdEditorOpen(true);
@@ -3838,6 +3883,34 @@ function App() {
} }
}; };
useEffect(() => {
setExportBirdId('');
setFlockExportError('');
setInvitationNotice(null);
}, [workspace?.id]);
const handleFlockExport = async () => {
if (exportingFlock) return;
setExportingFlock(true);
setFlockExportError('');
try {
const response = await apiFetch(`/workspace/export${exportBirdId ? `?birdId=${encodeURIComponent(exportBirdId)}` : ''}`, authToken);
if (!response.ok) throw new Error(await readErrorMessage(response, 'Unable to export flock data.'));
const url = URL.createObjectURL(await response.blob());
const link = document.createElement('a');
link.href = url;
link.download = `flockpal-${exportBirdId ? `bird-${exportBirdId}` : `flock-${workspace?.id ?? 'export'}`}-${new Date().toISOString().slice(0, 10)}.json`;
document.body.appendChild(link);
link.click();
link.remove();
window.setTimeout(() => URL.revokeObjectURL(url), 60_000);
} catch (exportError) {
setFlockExportError(exportError instanceof Error ? exportError.message : 'Unable to export flock data.');
} finally {
setExportingFlock(false);
}
};
const handleBirdImportSubmit = async () => { const handleBirdImportSubmit = async () => {
if (!birdImportPreview || birdImportPreview.errors.length || importingBirds) { if (!birdImportPreview || birdImportPreview.errors.length || importingBirds) {
return; return;
@@ -4591,7 +4664,7 @@ function App() {
}; };
const handleRemoveBird = async () => { const handleRemoveBird = async () => {
if (!selectedBird || deletingBird) { if (!selectedBird || deletingBird || !['owner', 'assistant'].includes(activeMembership?.role ?? '')) {
return; return;
} }
@@ -4659,7 +4732,7 @@ function App() {
} }
const confirmed = window.confirm( const confirmed = window.confirm(
`Memorialize ${selectedBird.name}?\n\nThis cannot be undone by you. ${selectedBird.name} will become read-only, hidden from the standard flock view, and excluded from the subscription bird count.`, `Memorialize ${selectedBird.name}?\n\nThis cannot be undone by you. ${selectedBird.name} will become read-only, shown softly faded in the flock, and excluded from the subscription bird count.`,
); );
if (!confirmed) { if (!confirmed) {
@@ -4688,17 +4761,14 @@ function App() {
const memorializedBird = data.bird; const memorializedBird = data.bird;
setBirds((current) => current.filter((bird) => bird.id !== memorializedBird.id)); setBirds((current) => current.filter((bird) => bird.id !== memorializedBird.id));
setMemorializedBirds((current) => sortBirdsByName([...current.filter((bird) => bird.id !== memorializedBird.id), memorializedBird])); setMemorializedBirds((current) => sortBirdsByName([...current.filter((bird) => bird.id !== memorializedBird.id), memorializedBird]));
setSelectedBirdId(''); setSelectedBirdId(memorializedBird.id);
setBirdEditorOpen(false);
setEditingBirdId(''); setEditingBirdId('');
setBirdForm(emptyBirdForm); setBirdForm(emptyBirdForm);
setBirdPhotoName(''); setBirdPhotoName('');
setPhotoCrop(null); setPhotoCrop(null);
setPhotoDrag(null); setPhotoDrag(null);
setMemorializeBirdForm(emptyMemorializeBirdForm()); setMemorializeBirdForm(emptyMemorializeBirdForm());
setWeights([]);
setVetVisits([]);
setMedications([]);
setMedicationAdministrations([]);
setAllBirdWeights((current) => { setAllBirdWeights((current) => {
const next = { ...current }; const next = { ...current };
delete next[memorializedBird.id]; delete next[memorializedBird.id];
@@ -5506,6 +5576,7 @@ function App() {
const handleWorkspaceMemberSubmit = async (event: React.FormEvent<HTMLFormElement>) => { const handleWorkspaceMemberSubmit = async (event: React.FormEvent<HTMLFormElement>) => {
event.preventDefault(); event.preventDefault();
setError(''); setError('');
setInvitationNotice(null);
setSavingWorkspaceMember(true); setSavingWorkspaceMember(true);
try { try {
@@ -5519,7 +5590,7 @@ function App() {
throw new Error(await readErrorMessage(response, 'Unable to add rescue team member.')); throw new Error(await readErrorMessage(response, 'Unable to add rescue team member.'));
} }
const data = (await readJsonSafely<{ member?: WorkspaceMember }>(response)) ?? {}; const data = (await readJsonSafely<{ member?: WorkspaceMember; invitation?: { sent: boolean; message: string } }>(response)) ?? {};
if (!data.member) { if (!data.member) {
throw new Error('Unable to add rescue team member.'); throw new Error('Unable to add rescue team member.');
@@ -5540,6 +5611,7 @@ function App() {
return current.map((member) => (member.id === nextMember.id ? nextMember : member)); return current.map((member) => (member.id === nextMember.id ? nextMember : member));
}); });
setWorkspaceMemberForm(emptyWorkspaceMemberForm); setWorkspaceMemberForm(emptyWorkspaceMemberForm);
setInvitationNotice(data.invitation ?? null);
} catch (memberError) { } catch (memberError) {
setError(memberError instanceof Error ? memberError.message : 'Unable to add rescue team member.'); setError(memberError instanceof Error ? memberError.message : 'Unable to add rescue team member.');
} finally { } finally {
@@ -5547,6 +5619,21 @@ function App() {
} }
}; };
const handleResendInvitation = async (memberId: string) => {
setResendingInvitationId(memberId);
setInvitationNotice(null);
try {
const response = await apiFetch(`/workspace/members/${memberId}/invitation`, authToken, { method: 'POST' });
if (!response.ok) throw new Error(await readErrorMessage(response, 'Unable to resend invitation.'));
const data = await response.json() as { invitation: { sent: boolean; message: string } };
setInvitationNotice(data.invitation);
} catch (error) {
setInvitationNotice({ sent: false, message: error instanceof Error ? error.message : 'Unable to resend invitation.' });
} finally {
setResendingInvitationId(null);
}
};
const handleUpdateWorkspaceMemberRole = async (memberId: string, role: WorkspaceRole) => { const handleUpdateWorkspaceMemberRole = async (memberId: string, role: WorkspaceRole) => {
setError(''); setError('');
setUpdatingWorkspaceMemberId(memberId); setUpdatingWorkspaceMemberId(memberId);
@@ -5633,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" />
@@ -5830,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>
@@ -5941,12 +6028,21 @@ 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" />
</div> </div>
<aside className="side-nav panel"> <aside className="side-nav panel">
{showWorkspaceSwitcher ? (
<FlockSwitcher
entries={authSession.workspaces}
currentId={workspace?.id}
switching={switchingWorkspaceId !== null}
disabled={switchingWorkspaceId !== null || savingWorkspace || deletingWorkspace}
onSwitch={(id) => { void handleWorkspaceSwitch(id); }}
/>
) : null}
<div className="page-tabs" role="tablist" aria-label="Main navigation"> <div className="page-tabs" role="tablist" aria-label="Main navigation">
<button data-tab="overview" className={`page-tab ${activePage === 'overview' ? 'active' : ''}`} onClick={() => setActivePage('overview')} type="button"> <button data-tab="overview" className={`page-tab ${activePage === 'overview' ? 'active' : ''}`} onClick={() => setActivePage('overview')} type="button">
Overview Overview
@@ -5964,26 +6060,6 @@ function App() {
) : null} ) : null}
</div> </div>
{showWorkspaceSwitcher ? (
<section className="workspace-switcher">
<div className="workspace-switcher-list">
{authSession.workspaces.map((entry) => (
<button
key={`${entry.workspace.id}-${entry.membership.id}`}
className={`workspace-switcher-item ${entry.workspace.id === workspace?.id ? 'active' : ''}`}
onClick={() => handleWorkspaceSwitch(entry.workspace.id)}
type="button"
disabled={switchingWorkspaceId === entry.workspace.id}
>
<span>{entry.workspace.name}</span>
<small>
{formatBillingPlanName(entry.workspace.billingPlan)} • {formatWorkspaceRole(entry.membership.role)}
</small>
</button>
))}
</div>
</section>
) : null}
<button className="secondary-button" onClick={handleLogout} type="button"> <button className="secondary-button" onClick={handleLogout} type="button">
Log out Log out
</button> </button>
@@ -6363,7 +6439,7 @@ function App() {
</div> </div>
</div> </div>
<div className="bird-list"> <div className="bird-list">
{birds.map((bird) => { {flockBirds.map((bird) => {
const weightRangeAlert = outOfRangeBirds.find((alert) => alert.bird.id === bird.id) ?? null; const weightRangeAlert = outOfRangeBirds.find((alert) => alert.bird.id === bird.id) ?? null;
const vetVisitAlertSignature = getVetVisitAlertSignature(bird.id); const vetVisitAlertSignature = getVetVisitAlertSignature(bird.id);
const hasVetVisitAlert = vetVisitDueBirdIds.has(bird.id); const hasVetVisitAlert = vetVisitDueBirdIds.has(bird.id);
@@ -6371,7 +6447,7 @@ function App() {
return ( return (
<article <article
key={bird.id} key={bird.id}
className={`bird-card ${bird.id === selectedBird?.id ? 'active' : ''}`} className={`bird-card ${bird.memorializedAt ? 'memorialized' : ''} ${bird.id === selectedBird?.id ? 'active' : ''}`}
style={bird.id === selectedBird?.id ? { borderColor: bird.chartColor, boxShadow: `0 16px 24px ${bird.chartColor}33` } : undefined} style={bird.id === selectedBird?.id ? { borderColor: bird.chartColor, boxShadow: `0 16px 24px ${bird.chartColor}33` } : undefined}
> >
<button className="bird-card-select" onClick={() => setSelectedBirdId(bird.id)} type="button"> <button className="bird-card-select" onClick={() => setSelectedBirdId(bird.id)} type="button">
@@ -6388,11 +6464,14 @@ function App() {
</span> </span>
</span> </span>
<small>{bird.species}</small> <small>{bird.species}</small>
{bird.memorializedAt ? <small className="memorial-label">In memory · Read-only</small> : null}
</div> </div>
</div> </div>
{!bird.memorializedAt || bird.latestWeightGrams !== null ? (
<strong>{formatWeight(bird.latestWeightGrams)}</strong> <strong>{formatWeight(bird.latestWeightGrams)}</strong>
) : null}
</button> </button>
{weightRangeAlert || hasVetVisitAlert ? ( {!bird.memorializedAt && (weightRangeAlert || hasVetVisitAlert) ? (
<div className="bird-alert-stack"> <div className="bird-alert-stack">
{weightRangeAlert ? ( {weightRangeAlert ? (
<span className="bird-alert-badge"> <span className="bird-alert-badge">
@@ -7012,9 +7091,9 @@ function App() {
</button> </button>
</div> </div>
</form> </form>
<p className="muted">Removing only takes this bird out of your flock. Its profile, photo, notes, and care history are retained and can be brought into a flock later using its exact band ID.</p> <p className="muted">Only Owners and Assistants can remove birds. Removing only takes this bird out of your flock. Its profile, photo, notes, and care history are retained and can be brought into a flock later using its exact band ID.</p>
<div className="button-row"> <div className="button-row">
<button className="danger-button" onClick={handleRemoveBird} type="button" disabled={deletingBird}> <button className="danger-button" onClick={handleRemoveBird} type="button" disabled={deletingBird || !['owner', 'assistant'].includes(activeMembership?.role ?? '')}>
{deletingBird ? 'Removing...' : 'Remove from flock'} {deletingBird ? 'Removing...' : 'Remove from flock'}
</button> </button>
</div> </div>
@@ -7126,7 +7205,7 @@ function App() {
<p className="eyebrow">Flock member</p> <p className="eyebrow">Flock member</p>
</div> </div>
<div className="member-header-actions"> <div className="member-header-actions">
{selectedBirdWeightRangeAlert || selectedBirdWeightDropAlerts.length || selectedBirdHasVetVisitAlert ? ( {!selectedBird.memorializedAt && (selectedBirdWeightRangeAlert || selectedBirdWeightDropAlerts.length || selectedBirdHasVetVisitAlert) ? (
<div className="bird-alert-stack" aria-label={`Critical alerts for ${selectedBird.name}`}> <div className="bird-alert-stack" aria-label={`Critical alerts for ${selectedBird.name}`}>
{selectedBirdWeightRangeAlert ? ( {selectedBirdWeightRangeAlert ? (
<span className="bird-alert-badge"> <span className="bird-alert-badge">
@@ -7179,7 +7258,7 @@ function App() {
</div> </div>
<> <>
<section className="profile-hero"> <section className={`profile-hero ${selectedBird.memorializedAt ? 'memorialized-profile' : ''}`}>
<img className="profile-photo" src={selectedBird.photoDataUrl || defaultBirdPhoto} alt={`${selectedBird.name}`} /> <img className="profile-photo" src={selectedBird.photoDataUrl || defaultBirdPhoto} alt={`${selectedBird.name}`} />
<div className="profile-actions"> <div className="profile-actions">
{selectedBird.publicProfileEnabled && selectedBird.publicProfileCode ? ( {selectedBird.publicProfileEnabled && selectedBird.publicProfileCode ? (
@@ -7189,7 +7268,7 @@ function App() {
</svg> </svg>
</button> </button>
) : null} ) : null}
<button className="profile-icon-button" onClick={() => startEditBird(selectedBird)} type="button" aria-label={`Edit details for ${selectedBird.name}`} title="Edit details"> <button disabled={Boolean(selectedBird.memorializedAt)} className="profile-icon-button" onClick={() => startEditBird(selectedBird)} type="button" aria-label={`Edit details for ${selectedBird.name}`} title="Edit details">
<svg viewBox="0 0 24 24" aria-hidden="true" focusable="false"> <svg viewBox="0 0 24 24" aria-hidden="true" focusable="false">
<path d="M4 20h4l10.5-10.5-4-4L4 16v4Z" /> <path d="M4 20h4l10.5-10.5-4-4L4 16v4Z" />
<path d="m13.5 6.5 4 4" /> <path d="m13.5 6.5 4 4" />
@@ -7216,6 +7295,7 @@ function App() {
</div> </div>
</section> </section>
{selectedBird.memorializedAt ? <p className="memorial-banner" role="status">In memory of {selectedBird.name}{selectedBird.memorializedOn ? ` · ${formatDate(selectedBird.memorializedOn)}` : ''}. This profile and its care history are read-only.</p> : null}
<div className="bird-detail-tab-panel"> <div className="bird-detail-tab-panel">
{selectedBirdTab === 'info' ? ( {selectedBirdTab === 'info' ? (
<div className="flock-member-sections" role="tabpanel"> <div className="flock-member-sections" role="tabpanel">
@@ -7266,14 +7346,14 @@ function App() {
<h2>Medication schedule</h2> <h2>Medication schedule</h2>
</div> </div>
</div> </div>
<div className="recent-list">{renderMedicationList({ showAdministrationControls: true })}</div> <div className="recent-list">{renderMedicationList({ showAdministrationControls: !selectedBird.memorializedAt })}</div>
</section> </section>
) : null} ) : null}
</div> </div>
) : 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' ? (
@@ -7433,7 +7513,7 @@ function App() {
</div> </div>
</div> </div>
<form className="form-panel inline-form" onSubmit={handleWeightSubmit}> {!selectedBird.memorializedAt ? (<form className="form-panel inline-form" onSubmit={handleWeightSubmit}>
<label> <label>
Weight in grams Weight in grams
<input <input
@@ -7464,16 +7544,16 @@ function App() {
/> />
</label> </label>
<div className="button-row care-form-actions"> <div className="button-row care-form-actions">
<button className="primary-button" type="submit"> <button className="primary-button" disabled={Boolean(selectedBird.memorializedAt)} type="submit">
{editingWeightId ? 'Save weight changes' : 'Save weight'} {editingWeightId ? 'Save weight changes' : 'Save weight'}
</button> </button>
{editingWeightId ? ( {editingWeightId ? (
<button className="secondary-button" onClick={handleCancelWeightEdit} type="button"> <button className="secondary-button" onClick={handleCancelWeightEdit} disabled={Boolean(selectedBird.memorializedAt)} type="button">
Cancel edit Cancel edit
</button> </button>
) : null} ) : null}
</div> </div>
</form> </form>) : null}
<div className="recent-list"> <div className="recent-list">
{editableWeights {editableWeights
.map((weight) => ( .map((weight) => (
@@ -7482,7 +7562,7 @@ function App() {
<span>{formatDate(weight.recordedOn)}</span> <span>{formatDate(weight.recordedOn)}</span>
<small>{weight.notes || 'No notes recorded.'}</small> <small>{weight.notes || 'No notes recorded.'}</small>
<div className="button-row"> <div className="button-row">
<button className="secondary-button" onClick={() => handleEditWeight(weight)} type="button"> <button className="secondary-button" onClick={() => handleEditWeight(weight)} disabled={Boolean(selectedBird.memorializedAt)} type="button">
Edit Edit
</button> </button>
</div> </div>
@@ -7509,7 +7589,7 @@ function App() {
setVeterinaryInfoForm(toVeterinaryInfoForm(selectedBird)); setVeterinaryInfoForm(toVeterinaryInfoForm(selectedBird));
setEditingVeterinaryInfo(true); setEditingVeterinaryInfo(true);
}} }}
type="button" disabled={Boolean(selectedBird.memorializedAt)} type="button"
aria-label={`Edit veterinary info for ${selectedBird.name}`} aria-label={`Edit veterinary info for ${selectedBird.name}`}
title="Edit veterinary info" title="Edit veterinary info"
> >
@@ -7521,7 +7601,7 @@ function App() {
</button> </button>
) : null} ) : null}
</div> </div>
{editingVeterinaryInfo ? ( {editingVeterinaryInfo && !selectedBird.memorializedAt ? (
<form className="form-panel inline-form care-entry-form" onSubmit={handleVeterinaryInfoSubmit}> <form className="form-panel inline-form care-entry-form" onSubmit={handleVeterinaryInfoSubmit}>
<label> <label>
Clinic name Clinic name
@@ -7557,7 +7637,7 @@ function App() {
/> />
</label> </label>
<div className="button-row care-form-actions"> <div className="button-row care-form-actions">
<button className="primary-button" type="submit" disabled={savingVeterinaryInfo}> <button className="primary-button" type="submit" disabled={Boolean(selectedBird.memorializedAt) || (savingVeterinaryInfo)}>
{savingVeterinaryInfo ? 'Saving veterinary info...' : 'Save veterinary info'} {savingVeterinaryInfo ? 'Saving veterinary info...' : 'Save veterinary info'}
</button> </button>
<button <button
@@ -7567,7 +7647,7 @@ function App() {
setEditingVeterinaryInfo(false); setEditingVeterinaryInfo(false);
}} }}
type="button" type="button"
disabled={savingVeterinaryInfo} disabled={Boolean(selectedBird.memorializedAt) || (savingVeterinaryInfo)}
> >
Cancel Cancel
</button> </button>
@@ -7603,7 +7683,7 @@ function App() {
</div> </div>
</div> </div>
<form className="form-panel inline-form care-entry-form" onSubmit={handleVetVisitSubmit}> {!selectedBird.memorializedAt ? (<form className="form-panel inline-form care-entry-form" onSubmit={handleVetVisitSubmit}>
<label> <label>
Visit date Visit date
<input <input
@@ -7639,16 +7719,16 @@ function App() {
/> />
</label> </label>
<div className="button-row care-form-actions"> <div className="button-row care-form-actions">
<button className="primary-button" type="submit"> <button className="primary-button" disabled={Boolean(selectedBird.memorializedAt)} type="submit">
{editingVetVisitId ? 'Save vet visit changes' : 'Save vet visit'} {editingVetVisitId ? 'Save vet visit changes' : 'Save vet visit'}
</button> </button>
{editingVetVisitId ? ( {editingVetVisitId ? (
<button className="secondary-button" onClick={handleCancelVetVisitEdit} type="button"> <button className="secondary-button" onClick={handleCancelVetVisitEdit} disabled={Boolean(selectedBird.memorializedAt)} type="button">
Cancel edit Cancel edit
</button> </button>
) : null} ) : null}
</div> </div>
</form> </form>) : null}
<div className="recent-list"> <div className="recent-list">
{vetVisits.length ? ( {vetVisits.length ? (
@@ -7660,7 +7740,7 @@ function App() {
</span> </span>
<small>{visit.notes || 'No notes recorded.'}</small> <small>{visit.notes || 'No notes recorded.'}</small>
<div className="button-row"> <div className="button-row">
<button className="secondary-button" onClick={() => handleEditVetVisit(visit)} type="button"> <button className="secondary-button" onClick={() => handleEditVetVisit(visit)} disabled={Boolean(selectedBird.memorializedAt)} type="button">
Edit Edit
</button> </button>
{editingVetVisitId === visit.id ? ( {editingVetVisitId === visit.id ? (
@@ -7668,7 +7748,7 @@ function App() {
className="secondary-button" className="secondary-button"
onClick={() => handleDeleteVetVisit(visit.id)} onClick={() => handleDeleteVetVisit(visit.id)}
type="button" type="button"
disabled={deletingVetVisitId === visit.id} disabled={Boolean(selectedBird.memorializedAt) || (deletingVetVisitId === visit.id)}
> >
{deletingVetVisitId === visit.id ? 'Deleting...' : 'Delete'} {deletingVetVisitId === visit.id ? 'Deleting...' : 'Delete'}
</button> </button>
@@ -7697,7 +7777,7 @@ function App() {
</div> </div>
<p className="muted">{selectedBirdNotes.length} total</p> <p className="muted">{selectedBirdNotes.length} total</p>
</div> </div>
<form className="form-panel care-entry-form" onSubmit={handleFlockNoteSubmit}> {!selectedBird.memorializedAt ? (<form className="form-panel care-entry-form" onSubmit={handleFlockNoteSubmit}>
<label className="wide-field"> <label className="wide-field">
Note Note
<textarea <textarea
@@ -7708,10 +7788,10 @@ function App() {
required required
/> />
</label> </label>
<button className="primary-button" type="submit" disabled={savingFlockNote}> <button className="primary-button" type="submit" disabled={Boolean(selectedBird.memorializedAt) || (savingFlockNote)}>
{savingFlockNote ? 'Saving...' : 'Save note'} {savingFlockNote ? 'Saving...' : 'Save note'}
</button> </button>
</form> </form>) : null}
<div className="recent-list note-list"> <div className="recent-list note-list">
{selectedBirdNotes.length ? ( {selectedBirdNotes.length ? (
selectedBirdNotes.map((note) => ( selectedBirdNotes.map((note) => (
@@ -7726,7 +7806,7 @@ function App() {
className="secondary-button" className="secondary-button"
type="button" type="button"
onClick={() => handleDeleteFlockNote(note.id)} onClick={() => handleDeleteFlockNote(note.id)}
disabled={deletingFlockNoteId === note.id} disabled={Boolean(selectedBird.memorializedAt) || (deletingFlockNoteId === note.id)}
> >
{deletingFlockNoteId === note.id ? 'Deleting...' : 'Delete'} {deletingFlockNoteId === note.id ? 'Deleting...' : 'Delete'}
</button> </button>
@@ -7764,10 +7844,10 @@ function App() {
</article> </article>
</div> </div>
<div className="button-row"> <div className="button-row">
<button className="primary-button" onClick={() => handleOpenAdoptionReport(false)} type="button" disabled={creatingAdoptionReportCode}> <button className="primary-button" onClick={() => handleOpenAdoptionReport(false)} type="button" disabled={Boolean(selectedBird.memorializedAt) || (creatingAdoptionReportCode)}>
{creatingAdoptionReportCode ? 'Preparing report...' : 'Open adoption report'} {creatingAdoptionReportCode ? 'Preparing report...' : 'Open adoption report'}
</button> </button>
<button className="secondary-button" onClick={() => handleOpenAdoptionReport(true)} type="button" disabled={creatingAdoptionReportCode}> <button className="secondary-button" onClick={() => handleOpenAdoptionReport(true)} type="button" disabled={Boolean(selectedBird.memorializedAt) || (creatingAdoptionReportCode)}>
Print-friendly report Print-friendly report
</button> </button>
</div> </div>
@@ -7851,7 +7931,7 @@ function App() {
</div> </div>
) : null; ) : null;
})()} })()}
<form className="form-panel inline-form care-entry-form bird-timeline-form" onSubmit={handleBirdTimelineEventSubmit}> {!selectedBird.memorializedAt ? (<form className="form-panel inline-form care-entry-form bird-timeline-form" onSubmit={handleBirdTimelineEventSubmit}>
<label> <label>
Type Type
<select <select
@@ -7872,7 +7952,7 @@ function App() {
}} }}
> >
<option value="location_updated">Location note</option> <option value="location_updated">Location note</option>
<option value="owner_changed">Owner</option> <option value="owner_changed">Adoption</option>
<option value="manual_note">General note</option> <option value="manual_note">General note</option>
</select> </select>
</label> </label>
@@ -7922,8 +8002,8 @@ function App() {
} }
/> />
<span> <span>
<strong>Owner changed</strong> <strong>Adopted</strong>
<small>Records a change without owner names.</small> <small>Records an adoption without owner names.</small>
</span> </span>
</label> </label>
) : null} ) : null}
@@ -7940,7 +8020,7 @@ function App() {
} }
/> />
</label> </label>
<button className="primary-button" type="submit" disabled={savingBirdTimelineEvent}> <button className="primary-button" type="submit" disabled={Boolean(selectedBird.memorializedAt) || (savingBirdTimelineEvent)}>
{savingBirdTimelineEvent ? 'Adding...' : 'Add timeline item'} {savingBirdTimelineEvent ? 'Adding...' : 'Add timeline item'}
</button> </button>
{birdTimelineNotice ? ( {birdTimelineNotice ? (
@@ -7948,7 +8028,7 @@ function App() {
{birdTimelineNotice.message} {birdTimelineNotice.message}
</p> </p>
) : null} ) : null}
</form> </form>) : null}
<div className="recent-list bird-timeline-list"> <div className="recent-list bird-timeline-list">
{birdTimelineEvents.length ? ( {birdTimelineEvents.length ? (
birdTimelineEvents.map((event) => ( birdTimelineEvents.map((event) => (
@@ -7967,7 +8047,7 @@ function App() {
) : ( ) : (
<article className="empty-card"> <article className="empty-card">
<strong>No timeline events yet</strong> <strong>No timeline events yet</strong>
<small>New location and owner changes for {selectedBird.name} will appear here.</small> <small>New location changes and adoptions for {selectedBird.name} will appear here.</small>
</article> </article>
)} )}
</div> </div>
@@ -8508,9 +8588,26 @@ function App() {
{expandedSettingsSection === 'collaborators' ? ( {expandedSettingsSection === 'collaborators' ? (
<> <>
<p className="muted"> <p className="muted">
Invite other people to help manage this flock. Rescue flocks support teams, and household flocks can also support Give someone access to this flock using their email address. Their role applies to every bird in this flock,
co-caregivers without changing who owns the billing. including memorialized birds. Every role can download flock data. Sharing access does not change the billing owner.
</p> </p>
<details className="summary-card">
<summary>Compare shared flock roles</summary>
<div className="recent-list">
{(['viewer', 'caregiver', 'assistant', 'owner'] as const).map((role) => (
<div key={role}>
<strong>{workspaceRoleLabels[role]}</strong>
<p>{workspaceRoleDescriptions[role]}</p>
</div>
))}
</div>
<p className="muted">
Memorialized bird records remain read-only. Editing also depends on the flock’s subscription or rescue verification status.
</p>
</details>
{invitationNotice ? (
<p className={invitationNotice.sent ? 'success-banner' : 'error-banner'} role="status">{invitationNotice.message}</p>
) : null}
<form className="form-panel" onSubmit={handleWorkspaceMemberSubmit}> <form className="form-panel" onSubmit={handleWorkspaceMemberSubmit}>
<label> <label>
Team member name Team member name
@@ -8533,6 +8630,7 @@ function App() {
Role Role
<select <select
value={workspaceMemberForm.role} value={workspaceMemberForm.role}
aria-describedby="invite-role-description"
onChange={(event) => onChange={(event) =>
setWorkspaceMemberForm({ setWorkspaceMemberForm({
...workspaceMemberForm, ...workspaceMemberForm,
@@ -8540,14 +8638,17 @@ function App() {
}) })
} }
> >
{isBillingOwner ? <option value="owner">Owner</option> : null} {isBillingOwner ? <option value="owner">{workspaceRoleLabels.owner}</option> : null}
<option value="assistant">Assistant</option> <option value="assistant">{workspaceRoleLabels.assistant}</option>
<option value="caregiver">Caregiver</option> <option value="caregiver">{workspaceRoleLabels.caregiver}</option>
<option value="viewer">Viewer</option> <option value="viewer">{workspaceRoleLabels.viewer}</option>
</select> </select>
</label> </label>
<p id="invite-role-description" className="muted" aria-live="polite">
{workspaceRoleDescriptions[workspaceMemberForm.role]}
</p>
<button className="primary-button" type="submit" disabled={savingWorkspaceMember}> <button className="primary-button" type="submit" disabled={savingWorkspaceMember}>
{savingWorkspaceMember ? 'Adding member...' : 'Add collaborator'} {savingWorkspaceMember ? 'Sending invitation...' : 'Add collaborator and send invitation'}
</button> </button>
</form> </form>
@@ -8579,6 +8680,7 @@ function App() {
Role Role
<select <select
value={member.role} value={member.role}
aria-describedby={`member-role-description-${member.id}`}
onChange={(event) => handleUpdateWorkspaceMemberRole(member.id, event.target.value as WorkspaceRole)} onChange={(event) => handleUpdateWorkspaceMemberRole(member.id, event.target.value as WorkspaceRole)}
disabled={ disabled={
(member.role === 'owner' && !canChangeOwnerRole) || (member.role === 'owner' && !canChangeOwnerRole) ||
@@ -8586,12 +8688,21 @@ function App() {
removingWorkspaceMemberId === member.id removingWorkspaceMemberId === member.id
} }
> >
{member.role === 'owner' || canPromoteToOwner ? <option value="owner">Owner</option> : null} {member.role === 'owner' || canPromoteToOwner ? <option value="owner">{workspaceRoleLabels.owner}</option> : null}
<option value="assistant">Assistant</option> <option value="assistant">{workspaceRoleLabels.assistant}</option>
<option value="caregiver">Caregiver</option> <option value="caregiver">{workspaceRoleLabels.caregiver}</option>
<option value="viewer">Viewer</option> <option value="viewer">{workspaceRoleLabels.viewer}</option>
</select> </select>
</label> </label>
<p id={`member-role-description-${member.id}`} className="muted" aria-live="polite">
{workspaceRoleDescriptions[member.role]}
</p>
{['owner', 'assistant'].includes(activeMembership?.role ?? '') ? (
<button className="secondary-button" type="button" onClick={() => handleResendInvitation(member.id)}
disabled={resendingInvitationId !== null || removingWorkspaceMemberId === member.id}>
{resendingInvitationId === member.id ? 'Sending...' : 'Resend invitation'}
</button>
) : null}
<button <button
className="danger-button" className="danger-button"
onClick={() => handleRemoveWorkspaceMember(member.id)} onClick={() => handleRemoveWorkspaceMember(member.id)}
@@ -8731,8 +8842,8 @@ function App() {
<article className="panel form-panel settings-card-bird-import"> <article className="panel form-panel settings-card-bird-import">
<div className="panel-header"> <div className="panel-header">
<div> <div>
<p className="eyebrow">Import</p> <p className="eyebrow">Flock data</p>
<h2>Bulk Import</h2> <h2>Bulk actions</h2>
</div> </div>
<button <button
className="secondary-button" className="secondary-button"
@@ -8747,6 +8858,32 @@ function App() {
</div> </div>
{expandedSettingsSection === 'bird-import' ? ( {expandedSettingsSection === 'bird-import' ? (
<> <>
<h3>Bulk export</h3>
<p className="muted">
Download all information for {workspace?.name ?? 'this flock'}, including active and memorialized bird profiles,
photos, all weights, vet visits, medications and doses, behaviors, timeline history, and flock notes.
Choose a single flock member to export only their profile and records, including their bird-specific notes.
The JSON file preserves your complete records. Export each flock separately if you have multiple flocks.
JSON exports cannot be uploaded through the Excel import below.
</p>
<label>
Export scope
<select value={exportBirdId} onChange={(event) => setExportBirdId(event.target.value)} disabled={exportingFlock}>
<option value="">All flock members</option>
{flockBirds.map((bird) => (
<option key={bird.id} value={bird.id}>
{bird.name}{bird.tagId ? ` — ${bird.tagId}` : ''}{bird.memorializedAt ? ' (In memory)' : ''}
</option>
))}
</select>
</label>
<div className="button-row">
<button className="primary-button" type="button" onClick={handleFlockExport} disabled={exportingFlock}>
{exportingFlock ? 'Exporting...' : exportBirdId ? 'Export selected flock member' : 'Export all flock data'}
</button>
</div>
{flockExportError ? <p className="error-banner" role="alert">{flockExportError}</p> : null}
<h3>Bulk import</h3>
<p className="muted"> <p className="muted">
Import the first worksheet from an Excel file. Use one row per weight entry and repeat the Bird Name for rows that belong to the Import the first worksheet from an Excel file. Use one row per weight entry and repeat the Bird Name for rows that belong to the
same profile. same profile.
+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>;
} }
+68
View File
@@ -0,0 +1,68 @@
import { useEffect, useRef, useState } from 'react';
type FlockEntry = { workspace: { id: number; name: string }; membership: { role: string } };
const roleName = (role: string) => role.charAt(0).toUpperCase() + role.slice(1);
export function FlockSwitcher({ entries, currentId, switching, disabled, onSwitch }: {
entries: FlockEntry[]; currentId?: number; switching: boolean; disabled: boolean; onSwitch: (id: number) => void;
}) {
const [open, setOpen] = useState(false);
const container = useRef<HTMLElement>(null);
const trigger = useRef<HTMLButtonElement>(null);
const current = entries.find((entry) => entry.workspace.id === currentId);
useEffect(() => { setOpen(false); }, [currentId, disabled]);
useEffect(() => {
if (!open) return;
const closeOutside = (event: PointerEvent) => {
if (!container.current?.contains(event.target as Node)) setOpen(false);
};
document.addEventListener('pointerdown', closeOutside);
return () => document.removeEventListener('pointerdown', closeOutside);
}, [open]);
return (
<section className="workspace-switcher" aria-label="Flock selection" ref={container}
onBlur={(event) => { if (!event.currentTarget.contains(event.relatedTarget)) setOpen(false); }}
onKeyDown={(event) => {
if (event.key === 'Escape' && open) {
event.preventDefault();
setOpen(false);
trigger.current?.focus();
}
}}>
<span className="workspace-switcher-label">Current flock</span>
<button className="flock-switcher-trigger" ref={trigger} type="button" disabled={disabled}
aria-expanded={open} aria-controls="flock-switcher-options" onClick={() => setOpen(!open)}>
<span className="flock-switcher-avatar" aria-hidden="true">{current?.workspace.name.trim().charAt(0).toUpperCase() || 'F'}</span>
<span className="flock-switcher-copy">
<strong>{current?.workspace.name ?? 'Choose a flock'}</strong>
<small>{current ? roleName(current.membership.role) : 'Switch flocks'}</small>
</span>
<svg className={`flock-switcher-chevron ${open ? 'is-open' : ''}`} width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" aria-hidden="true"><path d="m6 9 6 6 6-6" /></svg>
</button>
<span className="flock-switcher-status" role="status">{switching ? 'Switching flocks…' : ''}</span>
{open ? (
<div id="flock-switcher-options" className="flock-switcher-options">
<p className="flock-switcher-heading">Switch flock</p>
{[
{ label: 'My flocks', items: entries.filter((entry) => entry.membership.role === 'owner') },
{ label: 'Shared with me', items: entries.filter((entry) => entry.membership.role !== 'owner') },
].filter((group) => group.items.length).map((group) => (
<div className="flock-switcher-group" key={group.label} role="group" aria-label={group.label}>
<p>{group.label}</p>
{group.items.map((entry) => (
<button className="flock-switcher-option" key={entry.workspace.id} type="button"
aria-current={entry.workspace.id === currentId ? 'true' : undefined}
onClick={() => { setOpen(false); trigger.current?.focus(); onSwitch(entry.workspace.id); }}>
<span className="flock-switcher-copy"><strong>{entry.workspace.name}</strong><small>{roleName(entry.membership.role)}</small></span>
{entry.workspace.id === currentId ? <span className="flock-switcher-check" aria-label="Current flock">✓</span> : null}
</button>
))}
</div>
))}
</div>
) : null}
</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; } }
+26
View File
@@ -0,0 +1,26 @@
type LocationEvent = {
eventType: string;
eventDate: string;
createdAt: string;
locationLabel: string | null;
toWorkspaceId: number | null;
};
// Keep the owner marker when it already represents the same dated location.
// The original event list remains unchanged so notes and audit history are retained.
export const combineLocationOwnerMarkers = <T extends LocationEvent>(
events: T[],
normalizeLocation: (location: string) => string,
): T[] => {
const key = (event: T) => JSON.stringify([
event.eventDate || event.createdAt.slice(0, 10),
normalizeLocation(event.locationLabel || '').trim().toLowerCase(),
event.toWorkspaceId,
]);
const ownerLocations = new Set(events
.filter((event) => event.eventType === 'owner_changed' && event.locationLabel?.trim())
.map(key));
return events.filter((event) =>
event.eventType !== 'location_updated' || !event.locationLabel?.trim() || !ownerLocations.has(key(event)),
);
};
+85 -41
View File
@@ -216,6 +216,7 @@ textarea {
} }
.side-rail { .side-rail {
z-index: 30;
position: sticky; position: sticky;
top: 2rem; top: 2rem;
display: grid; display: grid;
@@ -856,33 +857,77 @@ textarea {
.workspace-switcher { .workspace-switcher {
display: grid; display: grid;
gap: 0.9rem; gap: 0.45rem;
min-width: 0;
padding-bottom: 1rem;
border-bottom: 1px solid rgba(39, 105, 179, 0.16);
} }
.workspace-switcher-item small { .workspace-switcher-label {
color: var(--muted); color: var(--muted);
font-size: 0.78rem;
font-weight: 700;
letter-spacing: 0.06em;
text-transform: uppercase;
} }
.workspace-switcher-list { .workspace-switcher { position: relative; }
display: grid;
gap: 0.75rem;
}
.workspace-switcher-item { .flock-switcher-trigger {
display: flex;
align-items: center;
gap: 0.7rem;
width: 100%; width: 100%;
min-width: 0;
padding: 0.8rem;
color: var(--ink);
text-align: left; text-align: left;
border: 1px solid rgba(39, 105, 179, 0.12); background: rgba(255, 255, 255, 0.65);
border-radius: 18px; border: 1px solid var(--panel-border);
padding: 0.85rem 0.95rem; border-radius: 16px;
background: rgba(255, 255, 255, 0.58); box-shadow: 0 3px 10px rgba(53, 90, 66, 0.05);
display: grid;
gap: 0.2rem;
} }
.workspace-switcher-item.active { .flock-switcher-trigger:hover:not(:disabled) { background: #fffaf0; border-color: var(--accent-green); }
background: linear-gradient(135deg, rgba(203, 58, 53, 0.16), rgba(39, 105, 179, 0.18)); .flock-switcher-trigger:focus-visible, .flock-switcher-option:focus-visible { outline: 2px solid var(--accent-green); outline-offset: 3px; }
border-color: rgba(39, 105, 179, 0.24); .flock-switcher-avatar {
display: grid;
place-items: center;
flex: 0 0 36px;
height: 36px;
border-radius: 11px;
background: #e1eee2;
color: #276b48;
font-weight: 800;
} }
.flock-switcher-copy { display: grid; gap: 0.15rem; min-width: 0; flex: 1; }
.flock-switcher-copy strong { font-size: 0.95rem; line-height: 1.35; overflow-wrap: anywhere; }
.flock-switcher-copy small { color: var(--muted); font-size: 0.76rem; font-weight: 400; }
.flock-switcher-chevron { flex-shrink: 0; color: var(--muted); }
.flock-switcher-chevron.is-open { transform: rotate(180deg); }
.flock-switcher-status:empty { display: none; }
.flock-switcher-status { color: var(--muted); font-size: 0.78rem; }
.flock-switcher-options {
position: absolute;
top: calc(100% - 0.5rem);
left: 0;
z-index: 50;
width: max(100%, 280px);
max-width: calc(100vw - 3rem);
max-height: min(420px, 60dvh);
overflow-y: auto;
padding: 0.65rem;
border: 1px solid var(--panel-border);
border-radius: 18px;
background: #fffaf1;
box-shadow: 0 18px 45px rgba(35, 65, 45, 0.2);
}
.flock-switcher-heading { margin: 0; padding: 0.35rem 0.5rem 0.6rem; font-size: 0.9rem; font-weight: 700; }
.flock-switcher-group + .flock-switcher-group { border-top: 1px solid var(--panel-border); margin-top: 0.5rem; padding-top: 0.35rem; }
.flock-switcher-group > p { margin: 0; padding: 0.4rem 0.5rem; color: var(--muted); font-size: 0.72rem; font-weight: 700; letter-spacing: 0.05em; text-transform: uppercase; }
.flock-switcher-option { display: flex; align-items: center; gap: 0.7rem; width: 100%; min-height: 54px; padding: 0.65rem; border: 0; border-radius: 11px; background: transparent; color: var(--ink); text-align: left; }
.flock-switcher-option:hover, .flock-switcher-option[aria-current="true"] { background: #e8f1e7; }
.flock-switcher-check { color: #276b48; font-weight: 800; }
.integration-token-secret { .integration-token-secret {
gap: 0.75rem; gap: 0.75rem;
@@ -2623,25 +2668,12 @@ label {
.workspace-switcher { .workspace-switcher {
grid-column: 1 / -1; grid-column: 1 / -1;
gap: 0.5rem; gap: 0.4rem;
padding-bottom: 0.65rem;
} }
.workspace-switcher-list {
display: flex;
gap: 0.45rem;
overflow-x: auto;
padding-bottom: 0.1rem;
}
.workspace-switcher-item {
min-width: 160px;
padding: 0.55rem 0.7rem;
border-radius: 14px;
}
.workspace-switcher-item small {
display: none;
}
} }
@media (max-width: 720px) { @media (max-width: 720px) {
@@ -2787,17 +2819,7 @@ label {
gap: 0.4rem; gap: 0.4rem;
} }
.workspace-switcher-list {
margin: 0 -0.2rem;
padding: 0 0.2rem 0.2rem;
}
.workspace-switcher-item {
min-width: min(180px, 78vw);
padding: 0.5rem 0.65rem;
border-radius: 999px;
font-size: 0.86rem;
}
.top-alert-notification { .top-alert-notification {
gap: 0.65rem; gap: 0.65rem;
@@ -3096,3 +3118,25 @@ label {
padding: 0.5rem; padding: 0.5rem;
} }
} }
/* Memorial profiles stay discoverable while remaining visually subdued. */
.bird-card.memorialized {
background: #f5f3f0;
border-style: dashed;
}
.bird-card.memorialized .bird-avatar,
.memorialized-profile .profile-photo {
opacity: 0.6;
filter: saturate(0.35);
}
.bird-card.memorialized .bird-card-copy,
.bird-card.memorialized .bird-card-select > strong {
opacity: 0.72;
}
.memorial-label { font-style: italic; }
.memorial-banner {
padding: 0.85rem 1rem;
border-radius: 12px;
background: #f5f3f0;
color: var(--muted);
}
+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);
});
+23
View File
@@ -0,0 +1,23 @@
import assert from 'node:assert/strict';
import { test } from 'node:test';
import { combineLocationOwnerMarkers } from '../src/birdTimeline.ts';
const location = { id: 'location', eventType: 'location_updated', eventDate: '2023-04-07', createdAt: '2026-10-07T12:00:00Z', locationLabel: 'Warwick, RI, US', toWorkspaceId: 1 };
const owner = { ...location, id: 'owner', eventType: 'owner_changed' };
const normalize = (value: string) => value.replace('United States', 'US');
test('combines a same-date location and owner change without modifying saved events', () => {
const events = [location, { ...owner, locationLabel: 'Warwick, RI, United States' }];
assert.deepEqual(combineLocationOwnerMarkers(events, normalize).map(event => event.id), ['owner']);
assert.equal(events.length, 2);
});
test('preserves different dates, locations, flocks, and standalone location changes', () => {
for (const other of [
{ ...owner, eventDate: '2023-04-08' },
{ ...owner, locationLabel: 'Providence, RI, US' },
{ ...owner, toWorkspaceId: 2 },
{ ...owner, locationLabel: null },
]) assert.equal(combineLocationOwnerMarkers([location, other], normalize).length, 2);
assert.deepEqual(combineLocationOwnerMarkers([location], normalize), [location]);
});