Compare commits
48
Commits
dev
..
802544e452
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
802544e452 | ||
|
|
8205fee420 | ||
|
|
fc541f024d | ||
|
|
c1ca4891fc | ||
|
|
7406d00687 | ||
|
|
ecad447d60 | ||
|
|
3ba6410972 | ||
|
|
4a43a450f3 | ||
|
|
46605d8717 | ||
|
|
8f1144de1a | ||
|
|
53b75588a2 | ||
|
|
1849ecd73b | ||
|
|
53b7d34520 | ||
|
|
f65a4bed24 | ||
|
|
cc4a2382c6 | ||
|
|
5735bb7735 | ||
|
|
88ff06237e | ||
|
|
fbb13561b0 | ||
|
|
b15861c856 | ||
|
|
2aeaa119f7 | ||
|
|
36690c0174 | ||
|
|
b76ad35c07 | ||
|
|
6918b55a58 | ||
|
|
49f1713e26 | ||
|
|
c9fa7e4246 | ||
|
|
0411ec5175 | ||
|
|
7b7171c109 | ||
|
|
c02bb4d6d8 | ||
|
|
603b4eee4d | ||
|
|
52008f5b43 | ||
|
|
5b57cdd6bf | ||
|
|
60eadf0847 | ||
|
|
682ccfd41f | ||
|
|
59c6b19ad6 | ||
|
|
aa1a4cf6ff | ||
|
|
5f0fad3cbb | ||
|
|
545fae59b2 | ||
|
|
d748d2db21 | ||
|
|
095c91e56d | ||
|
|
f2017068d5 | ||
|
|
c9702495a3 | ||
|
|
e965cb55ef | ||
|
|
505a9b8496 | ||
|
|
c6dc5b22b8 | ||
|
|
f16e88e2f0 | ||
|
|
016bc187d4 | ||
|
|
104f01f75d | ||
|
|
568aee3e70 |
No files matched your search
+10
-11
@@ -3,13 +3,14 @@ name: Deploy
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
- dev
|
||||
- develop
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
deploy-dev:
|
||||
if: ${{ github.event_name == 'push' }}
|
||||
if: ${{ github.event_name == 'push' && (github.ref_name == 'dev' || github.ref_name == 'develop') }}
|
||||
runs-on: ubuntu-latest
|
||||
container:
|
||||
volumes:
|
||||
@@ -36,16 +37,12 @@ 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"
|
||||
|
||||
- name: Validate dev compose config
|
||||
env:
|
||||
MAPBOX_ACCESS_TOKEN: ${{ secrets.MAPBOX_ACCESS_TOKEN }}
|
||||
run: |
|
||||
set -e
|
||||
cd /docker/FlockPal-dev
|
||||
docker compose -f docker-compose.dev.yaml config --quiet
|
||||
|
||||
- name: Deploy dev
|
||||
env:
|
||||
MAPBOX_ACCESS_TOKEN: ${{ secrets.MAPBOX_ACCESS_TOKEN }}
|
||||
run: |
|
||||
set -e
|
||||
cd /docker/FlockPal-dev
|
||||
@@ -113,7 +110,7 @@ jobs:
|
||||
"$DISCORD_WEBHOOK_URL" || echo "Discord notification failed."
|
||||
|
||||
deploy-prod:
|
||||
if: ${{ github.event_name == 'workflow_dispatch' }}
|
||||
if: ${{ github.event_name == 'workflow_dispatch' || (github.event_name == 'push' && github.ref_name == 'main') }}
|
||||
runs-on: ubuntu-latest
|
||||
container:
|
||||
volumes:
|
||||
@@ -140,20 +137,22 @@ 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"
|
||||
|
||||
- name: Validate prod compose config
|
||||
env:
|
||||
MAPBOX_ACCESS_TOKEN: ${{ secrets.MAPBOX_ACCESS_TOKEN }}
|
||||
run: |
|
||||
set -e
|
||||
cd /docker/FlockPal
|
||||
docker compose -f docker-compose.prod.yml config --quiet
|
||||
|
||||
- name: Deploy prod
|
||||
env:
|
||||
MAPBOX_ACCESS_TOKEN: ${{ secrets.MAPBOX_ACCESS_TOKEN }}
|
||||
run: |
|
||||
set -e
|
||||
cd /docker/FlockPal
|
||||
docker compose -f docker-compose.prod.yml up -d --build
|
||||
docker compose -f docker-compose.prod.yml up -d --build --wait --wait-timeout 180
|
||||
|
||||
- name: Verify production API readiness
|
||||
run: |
|
||||
set -e
|
||||
cd /docker/FlockPal
|
||||
docker compose -f docker-compose.prod.yml exec -T backend node dist/healthcheck.js api-ready
|
||||
|
||||
- name: Notify Discord
|
||||
if: always()
|
||||
|
||||
@@ -47,6 +47,23 @@ The default `docker-compose.yml` is development-only. It mounts source files, in
|
||||
|
||||
## Operations
|
||||
|
||||
### Health checks
|
||||
|
||||
Monitor these production checks:
|
||||
|
||||
- Frontend: `GET https://your-host/healthz`
|
||||
- Verifies Nginx is serving the frontend container.
|
||||
- Backend liveness: `GET https://your-host/api/health/live`
|
||||
- Verifies the API process is running.
|
||||
- Backend readiness: `GET https://your-host/api/health/ready`
|
||||
- Verifies the API can reach Postgres and Redis. Returns `503` if either dependency is unavailable.
|
||||
- Backend metrics: `GET https://your-host/api/metrics`
|
||||
- Admin-authenticated process, request, and queue metrics.
|
||||
- Postgres and Redis:
|
||||
- Use the Docker health checks in `docker-compose.prod.yml`.
|
||||
- Worker:
|
||||
- Use the Docker health check in `docker-compose.prod.yml`; it validates worker dependencies. The worker does not expose HTTP.
|
||||
|
||||
### Backups
|
||||
|
||||
Create a compressed Postgres backup from the Docker Compose Postgres service:
|
||||
@@ -86,7 +103,7 @@ curl -H "Authorization: Bearer <admin-token>" https://your-host/api/metrics
|
||||
- `FRONTEND_URL`
|
||||
- `BACKEND_URL`
|
||||
- `VITE_API_BASE_URL`
|
||||
- `MAPBOX_ACCESS_TOKEN` as a Gitea Actions secret for automated deployments (or in `.env` for manual Compose deployments)
|
||||
- `MAPBOX_ACCESS_TOKEN`
|
||||
- `REDIS_URL`
|
||||
- `IMAGE_STORAGE_PROVIDER`
|
||||
- `S3_ENDPOINT`
|
||||
|
||||
+38
-272
@@ -1,6 +1,3 @@
|
||||
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 { hasUnassignedBird, removeBirdFromFlock, claimUnassignedBird } from './repositories/birdMembershipRepository.js';
|
||||
import { behaviorTypeSchema, behaviorOccurrenceSchema, behaviorRangeSchema } from './behaviorSchemas.js';
|
||||
@@ -58,6 +55,7 @@ import nodemailer from 'nodemailer';
|
||||
import Stripe from 'stripe';
|
||||
import { z } from 'zod';
|
||||
|
||||
import { db } from './db/client.js';
|
||||
import { ensureSchema } from './db/schema.js';
|
||||
import { adoptionReportQueueEvents, enqueueAdoptionReportJob } from './queues/adoptionReportQueue.js';
|
||||
import { enqueueBirdMilestoneReminderJob, getBirdMilestoneReminderQueueCounts } from './queues/birdMilestoneReminderQueue.js';
|
||||
@@ -123,19 +121,6 @@ import {
|
||||
listAuditLogEntries,
|
||||
listFlockNotes,
|
||||
} from './repositories/auditRepository.js';
|
||||
import {
|
||||
deleteDailyEducation,
|
||||
deleteEducationQuestion,
|
||||
createEducationQuestion,
|
||||
getDailyEducationForDate,
|
||||
getEducationOptOut,
|
||||
listDailyEducationForAdmin,
|
||||
listDailyEducationQuestions,
|
||||
listEducationQuestionsForAdmin,
|
||||
updateEducationOptOut,
|
||||
updateEducationQuestion,
|
||||
upsertDailyEducation,
|
||||
} from './repositories/educationRepository.js';
|
||||
import {
|
||||
buildBirdPhotoObjectKey,
|
||||
getImageExtensionFromContentType,
|
||||
@@ -175,8 +160,6 @@ import type {
|
||||
AuditLogEntryRow,
|
||||
BillingInterval,
|
||||
BillingPlan,
|
||||
DailyEducationRow,
|
||||
EducationQuestionRow,
|
||||
BirdGender,
|
||||
BirdMilestoneReminderCandidateRow,
|
||||
BirdRow,
|
||||
@@ -374,27 +357,6 @@ const integrationTokenCreateSchema = z.object({
|
||||
expiresInDays: z.coerce.number().int().min(1).max(3650).optional(),
|
||||
});
|
||||
|
||||
const educationQuestionSchema = z
|
||||
.object({
|
||||
prompt: z.string().trim().min(1).max(500),
|
||||
options: z.array(z.string().trim().min(1).max(240)).min(2).max(4),
|
||||
correctAnswerIndex: z.coerce.number().int().min(0).max(3),
|
||||
explanation: z.string().trim().max(800).optional().or(z.literal('')),
|
||||
})
|
||||
.refine((value) => value.correctAnswerIndex < value.options.length, {
|
||||
message: 'Correct answer must match one of the quiz options.',
|
||||
path: ['correctAnswerIndex'],
|
||||
});
|
||||
|
||||
const dailyEducationSchema = z.object({
|
||||
publishDate: dateStringSchema,
|
||||
fact: z.string().trim().min(1).max(2000),
|
||||
});
|
||||
|
||||
const educationPreferenceSchema = z.object({
|
||||
educationOptOut: z.boolean(),
|
||||
});
|
||||
|
||||
const emptyToNull = (value?: string) => {
|
||||
const trimmed = value?.trim() ?? '';
|
||||
return trimmed ? trimmed : null;
|
||||
@@ -589,25 +551,6 @@ const normalizeWorkspaceMember = (row: WorkspaceMemberRow) => ({
|
||||
createdAt: row.created_at,
|
||||
});
|
||||
|
||||
const normalizeEducationQuestion = (row: EducationQuestionRow) => ({
|
||||
id: row.id,
|
||||
prompt: row.prompt,
|
||||
options: row.options,
|
||||
correctAnswerIndex: Number(row.correct_answer_index),
|
||||
explanation: row.explanation ?? null,
|
||||
createdAt: row.created_at,
|
||||
updatedAt: row.updated_at,
|
||||
});
|
||||
|
||||
const normalizeDailyEducation = (row: DailyEducationRow, questions: EducationQuestionRow[] = []) => ({
|
||||
id: row.id,
|
||||
publishDate: row.publish_date,
|
||||
fact: row.fact,
|
||||
quizQuestions: questions.map(normalizeEducationQuestion),
|
||||
createdAt: row.created_at,
|
||||
updatedAt: row.updated_at,
|
||||
});
|
||||
|
||||
const signBirdPhotoAccessToken = (row: BirdRow) => {
|
||||
if (!row.photo_object_key) {
|
||||
return '';
|
||||
@@ -1043,6 +986,14 @@ const normalizeWorkspaceMembershipList = async (userId: string) =>
|
||||
|
||||
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 => {
|
||||
if (status === 'active' || status === 'trialing' || status === 'past_due' || status === 'canceled' || status === 'unpaid') {
|
||||
return status;
|
||||
@@ -2263,10 +2214,33 @@ const writeBirdTimelineEvent = async ({
|
||||
}
|
||||
};
|
||||
|
||||
const isBillingOnlyWorkspaceUpdate = (
|
||||
workspace: WorkspaceRow,
|
||||
payload: z.infer<typeof workspaceSchema>,
|
||||
) => workspace.workspace_type === 'standard' && payload.workspaceType === 'standard' && payload.name === workspace.name;
|
||||
|
||||
app.get('/api/health', (_req: Request, res: Response) => {
|
||||
res.json({ ok: true });
|
||||
});
|
||||
|
||||
app.get('/api/health/live', (_req: Request, res: Response) => {
|
||||
res.json({ ok: true, status: 'live' });
|
||||
});
|
||||
|
||||
app.get('/api/health/ready', async (_req: Request, res: Response) => {
|
||||
try {
|
||||
await Promise.all([
|
||||
db.query('SELECT 1'),
|
||||
getBirdMilestoneReminderQueueCounts(),
|
||||
getMedicationReminderQueueCounts(),
|
||||
]);
|
||||
res.json({ ok: true, status: 'ready' });
|
||||
} catch (error) {
|
||||
console.error('Readiness check failed', error);
|
||||
res.status(503).json({ ok: false, status: 'not_ready' });
|
||||
}
|
||||
});
|
||||
|
||||
app.get('/api/metrics', requireAuth, requireAdmin, async (_req: Request, res: Response, next: NextFunction) => {
|
||||
const memoryUsage = process.memoryUsage();
|
||||
const averageDurationMs = requestMetrics.totalRequests > 0 ? requestMetrics.totalDurationMs / requestMetrics.totalRequests : 0;
|
||||
@@ -2712,149 +2686,6 @@ app.get('/api/admin/rescue-workspaces', requireAuth, requireSessionAuth, require
|
||||
}
|
||||
});
|
||||
|
||||
app.get('/api/admin/daily-education', requireAuth, requireSessionAuth, requireAdmin, async (_req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const education = await listDailyEducationForAdmin();
|
||||
res.json({ education: education.map((entry) => normalizeDailyEducation(entry)) });
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
});
|
||||
|
||||
app.get('/api/admin/education-questions', requireAuth, requireSessionAuth, requireAdmin, async (_req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const questions = await listEducationQuestionsForAdmin();
|
||||
res.json({ questions: questions.map(normalizeEducationQuestion) });
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
});
|
||||
|
||||
app.put('/api/admin/daily-education', requireAuth, requireSessionAuth, requireAdmin, async (req: Request, res: Response, next: NextFunction) => {
|
||||
const parsed = dailyEducationSchema.safeParse(req.body);
|
||||
|
||||
if (!parsed.success) {
|
||||
res.status(400).json({ error: 'Invalid daily education payload', details: parsed.error.flatten() });
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const education = await upsertDailyEducation({
|
||||
publishDate: parsed.data.publishDate,
|
||||
fact: parsed.data.fact,
|
||||
createdByUserId: req.auth!.user.id,
|
||||
});
|
||||
res.json({ education: normalizeDailyEducation(education) });
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
});
|
||||
|
||||
app.post('/api/admin/education-questions', requireAuth, requireSessionAuth, requireAdmin, async (req: Request, res: Response, next: NextFunction) => {
|
||||
const parsed = educationQuestionSchema.safeParse(req.body);
|
||||
|
||||
if (!parsed.success) {
|
||||
res.status(400).json({ error: 'Invalid education question payload', details: parsed.error.flatten() });
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const question = await createEducationQuestion({
|
||||
question: { ...parsed.data, explanation: emptyToNull(parsed.data.explanation) },
|
||||
createdByUserId: req.auth!.user.id,
|
||||
});
|
||||
res.status(201).json({ question: normalizeEducationQuestion(question) });
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
});
|
||||
|
||||
app.put('/api/admin/education-questions/:questionId', requireAuth, requireSessionAuth, requireAdmin, async (req: Request, res: Response, next: NextFunction) => {
|
||||
const parsed = educationQuestionSchema.safeParse(req.body);
|
||||
|
||||
if (!parsed.success) {
|
||||
res.status(400).json({ error: 'Invalid education question payload', details: parsed.error.flatten() });
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const question = await updateEducationQuestion(req.params.questionId, {
|
||||
...parsed.data,
|
||||
explanation: emptyToNull(parsed.data.explanation),
|
||||
});
|
||||
|
||||
if (!question) {
|
||||
res.status(404).json({ error: 'Education question not found.' });
|
||||
return;
|
||||
}
|
||||
|
||||
res.json({ question: normalizeEducationQuestion(question) });
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
});
|
||||
|
||||
app.delete('/api/admin/education-questions/:questionId', requireAuth, requireSessionAuth, requireAdmin, async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const deleted = await deleteEducationQuestion(req.params.questionId);
|
||||
|
||||
if (!deleted) {
|
||||
res.status(404).json({ error: 'Education question not found.' });
|
||||
return;
|
||||
}
|
||||
|
||||
res.status(204).send();
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
});
|
||||
|
||||
app.delete('/api/admin/daily-education/:educationId', requireAuth, requireSessionAuth, requireAdmin, async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const deleted = await deleteDailyEducation(req.params.educationId);
|
||||
|
||||
if (!deleted) {
|
||||
res.status(404).json({ error: 'Daily education item not found.' });
|
||||
return;
|
||||
}
|
||||
|
||||
res.status(204).send();
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
});
|
||||
|
||||
app.get('/api/education/today', requireAuth, requireSessionAuth, async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const educationOptOut = await getEducationOptOut(req.auth!.user.id);
|
||||
const education = educationOptOut ? null : await getDailyEducationForDate();
|
||||
const questions = education ? await listDailyEducationQuestions(education.publish_date) : [];
|
||||
|
||||
res.json({
|
||||
educationOptOut,
|
||||
education: education ? normalizeDailyEducation(education, questions) : null,
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
});
|
||||
|
||||
app.patch('/api/education/preferences', requireAuth, requireSessionAuth, async (req: Request, res: Response, next: NextFunction) => {
|
||||
const parsed = educationPreferenceSchema.safeParse(req.body);
|
||||
|
||||
if (!parsed.success) {
|
||||
res.status(400).json({ error: 'Invalid education preference payload', details: parsed.error.flatten() });
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const educationOptOut = await updateEducationOptOut(req.auth!.user.id, parsed.data.educationOptOut);
|
||||
res.json({ educationOptOut });
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
});
|
||||
|
||||
app.patch('/api/admin/rescue-workspaces/:workspaceId', requireAuth, requireAdmin, requireWriteAccess, async (req: Request, res: Response, next: NextFunction) => {
|
||||
const parsed = z.object({ rescueVerificationStatus: rescueVerificationStatusSchema }).safeParse(req.body);
|
||||
|
||||
@@ -3133,40 +2964,6 @@ 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) => {
|
||||
res.json({ workspace: normalizeWorkspace(req.auth!.workspace) });
|
||||
});
|
||||
@@ -3184,7 +2981,10 @@ app.put('/api/workspace', requireAuth, requireSessionAuth, requireWorkspaceRole(
|
||||
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 isConvertingToRescue = currentWorkspace.workspace_type !== 'rescue' && parsed.data.workspaceType === 'rescue';
|
||||
const canUpdateWorkspace = canUpdateWorkspaceSettings(currentWorkspace, parsed.data, isAdminUser(req.auth!.user));
|
||||
const canUpdateWorkspace =
|
||||
isAdminUser(req.auth!.user) ||
|
||||
subscriptionAllowsWrite(currentWorkspace) ||
|
||||
isBillingOnlyWorkspaceUpdate(currentWorkspace, parsed.data);
|
||||
|
||||
if (!canUpdateWorkspace) {
|
||||
res.status(402).json({
|
||||
@@ -3330,37 +3130,6 @@ 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) => {
|
||||
const parsed = workspaceMemberSchema.safeParse(req.body);
|
||||
|
||||
@@ -3384,8 +3153,7 @@ app.post('/api/workspace/members', requireAuth, requireWriteAccess, requireWorks
|
||||
inviteEmail: member!.invite_email,
|
||||
role: member!.role,
|
||||
});
|
||||
const invitation = await sendWorkspaceInvitation(req.auth!, member!);
|
||||
res.status(201).json({ member: normalizeWorkspaceMember(member!), invitation });
|
||||
res.status(201).json({ member: normalizeWorkspaceMember(member!) });
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
@@ -3798,7 +3566,6 @@ app.post('/api/birds', requireAuth, requireWriteAccess, requireWorkspaceRole(['o
|
||||
toWorkspaceId: req.auth!.workspace.id,
|
||||
locationLabel: bird!.location_label,
|
||||
locationDetails: bird!.location_details,
|
||||
eventDate: emptyToNull(parsed.data.locationDate),
|
||||
createdByUserId: req.auth!.user.id,
|
||||
});
|
||||
res.status(201).json({ bird: normalizeBird(bird!) });
|
||||
@@ -4178,7 +3945,6 @@ app.put('/api/birds/:birdId', requireAuth, requireWriteAccess, requireWorkspaceR
|
||||
toWorkspaceId: req.auth!.workspace.id,
|
||||
locationLabel: bird.location_label,
|
||||
locationDetails: bird.location_details,
|
||||
eventDate: emptyToNull(parsed.data.locationDate),
|
||||
createdByUserId: req.auth!.user.id,
|
||||
});
|
||||
}
|
||||
@@ -4195,7 +3961,7 @@ app.put('/api/birds/:birdId', requireAuth, requireWriteAccess, requireWorkspaceR
|
||||
}
|
||||
});
|
||||
|
||||
app.delete('/api/birds/:birdId', requireAuth, requireWriteAccess, requireWorkspaceRole(['owner', 'assistant']), async (req: Request, res: Response, next: NextFunction) => {
|
||||
app.delete('/api/birds/:birdId', requireAuth, requireWriteAccess, requireWorkspaceRole(['owner', 'assistant', 'caregiver']), async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const bird = await getBirdById(req.params.birdId, req.auth!.workspace.id);
|
||||
|
||||
|
||||
@@ -30,9 +30,6 @@ export const ensureSchema = async (database: DatabaseClient = db) => {
|
||||
ALTER TABLE workspaces
|
||||
DROP CONSTRAINT IF EXISTS workspaces_id_check;
|
||||
|
||||
ALTER TABLE users
|
||||
ADD COLUMN IF NOT EXISTS education_opt_out BOOLEAN NOT NULL DEFAULT FALSE;
|
||||
|
||||
ALTER TABLE workspaces
|
||||
ADD COLUMN IF NOT EXISTS billing_email VARCHAR(255),
|
||||
ADD COLUMN IF NOT EXISTS billing_plan VARCHAR(32) NOT NULL DEFAULT 'household_basic',
|
||||
@@ -142,37 +139,6 @@ export const ensureSchema = async (database: DatabaseClient = db) => {
|
||||
CREATE INDEX IF NOT EXISTS idx_auth_sessions_created_user
|
||||
ON auth_sessions (created_at DESC, user_id);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS daily_education (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
publish_date DATE NOT NULL UNIQUE,
|
||||
fact TEXT NOT NULL,
|
||||
quiz_questions JSONB NOT NULL DEFAULT '[]'::jsonb,
|
||||
created_by_user_id UUID REFERENCES users(id) ON DELETE SET NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
|
||||
ALTER TABLE daily_education
|
||||
ALTER COLUMN quiz_questions SET DEFAULT '[]'::jsonb;
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_daily_education_publish_date
|
||||
ON daily_education (publish_date DESC);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS education_question_bank (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
prompt VARCHAR(500) NOT NULL,
|
||||
options JSONB NOT NULL,
|
||||
correct_answer_index INTEGER NOT NULL,
|
||||
explanation VARCHAR(800),
|
||||
created_by_user_id UUID REFERENCES users(id) ON DELETE SET NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
CHECK (correct_answer_index >= 0 AND correct_answer_index <= 3)
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_education_question_bank_created
|
||||
ON education_question_bank (created_at DESC);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS integration_tokens (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
|
||||
@@ -115,20 +115,3 @@ test('Swagger UI, initialization, assets and specification are served locally wi
|
||||
assert.equal(redirect.status, 301);
|
||||
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/);
|
||||
});
|
||||
@@ -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));
|
||||
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: '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: '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: '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: '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.';
|
||||
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: '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: '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: 'get', path: '/birds/{birdId}/timeline', summary: 'List bird timeline events', tag: 'Birds', response: many('events', models.timelineResponse), errors: [404] });
|
||||
for (const resource of [
|
||||
{ path: 'weights', single: 'weight', plural: 'weights', id: 'weightId', tag: 'Weights', input: weightSchema, model: models.weightResponse },
|
||||
|
||||
@@ -26,4 +26,3 @@ export const loadWeightReminderPortrait = async (bird: Pick<WeightReminder, 'bir
|
||||
}
|
||||
return thumbnail(await readFile(asset('yoda-default.png')));
|
||||
};
|
||||
|
||||
@@ -1,29 +0,0 @@
|
||||
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), /<Pat>/);
|
||||
assert.match(String(mail.html), /Alex & Sam/);
|
||||
assert.match(String(mail.html), /<Rescue>/);
|
||||
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/);
|
||||
}
|
||||
});
|
||||
@@ -1,26 +0,0 @@
|
||||
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.',
|
||||
}),
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,54 @@
|
||||
import { db } from './db/client.js';
|
||||
import { closeBirdMilestoneReminderQueue, getBirdMilestoneReminderQueueCounts } from './queues/birdMilestoneReminderQueue.js';
|
||||
|
||||
const timeoutMs = Number(process.env.HEALTHCHECK_TIMEOUT_MS ?? 5_000);
|
||||
|
||||
const withTimeout = async <T>(operation: Promise<T>, label: string): Promise<T> => {
|
||||
let timeout: NodeJS.Timeout | undefined;
|
||||
|
||||
try {
|
||||
return await Promise.race([
|
||||
operation,
|
||||
new Promise<never>((_resolve, reject) => {
|
||||
timeout = setTimeout(() => reject(new Error(`${label} timed out`)), timeoutMs);
|
||||
}),
|
||||
]);
|
||||
} finally {
|
||||
if (timeout) {
|
||||
clearTimeout(timeout);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const checkHttp = async (path: string) => {
|
||||
const port = process.env.PORT ?? '5000';
|
||||
const response = await withTimeout(fetch(`http://127.0.0.1:${port}${path}`), path);
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`${path} returned ${response.status}`);
|
||||
}
|
||||
};
|
||||
|
||||
const checkWorkerDependencies = async () => {
|
||||
await withTimeout(db.query('SELECT 1'), 'postgres');
|
||||
await withTimeout(getBirdMilestoneReminderQueueCounts(), 'redis');
|
||||
};
|
||||
|
||||
const mode = process.argv[2] ?? 'api-ready';
|
||||
|
||||
try {
|
||||
if (mode === 'api-live') {
|
||||
await checkHttp('/api/health/live');
|
||||
} else if (mode === 'api-ready') {
|
||||
await checkHttp('/api/health/ready');
|
||||
} else if (mode === 'worker') {
|
||||
await checkWorkerDependencies();
|
||||
} else {
|
||||
throw new Error(`Unknown healthcheck mode: ${mode}`);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(error instanceof Error ? error.message : error);
|
||||
process.exitCode = 1;
|
||||
} finally {
|
||||
await Promise.allSettled([closeBirdMilestoneReminderQueue(), db.close()]);
|
||||
}
|
||||
@@ -1,20 +0,0 @@
|
||||
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,7 +98,6 @@ export const createFlockNote = async ({
|
||||
FROM birds
|
||||
WHERE birds.id = $2
|
||||
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
|
||||
)
|
||||
@@ -126,12 +125,6 @@ export const deleteFlockNote = async (noteId: string, workspaceId: number) => {
|
||||
`DELETE FROM flock_notes
|
||||
WHERE id = $1
|
||||
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`,
|
||||
[noteId, workspaceId],
|
||||
);
|
||||
|
||||
@@ -6,7 +6,9 @@ import {
|
||||
createBird,
|
||||
createPendingBirdTransfer,
|
||||
getBirdById,
|
||||
getOpenBirdTransferCode,
|
||||
listWeightsForBird,
|
||||
markBirdTransferCodeCompleted,
|
||||
transferBirdToWorkspace,
|
||||
} from './birdRepository.js';
|
||||
import { mockDb } from '../test/mockDb.js';
|
||||
@@ -253,3 +255,25 @@ test('completePendingBirdTransfersForOwner moves pending birds and marks complet
|
||||
null,
|
||||
]);
|
||||
});
|
||||
|
||||
test('getOpenBirdTransferCode only returns unconsumed codes', async () => {
|
||||
const { calls } = mockDb({ rowCount: 0, rows: [] });
|
||||
|
||||
const transferCode = await getOpenBirdTransferCode('ADOPT-123');
|
||||
|
||||
assert.equal(transferCode, null);
|
||||
assert.deepEqual(calls[0].params, ['ADOPT-123']);
|
||||
assert.match(calls[0].text, /bird_transfer_codes\.completed_at IS NULL/);
|
||||
assert.match(calls[0].text, /bird_transfer_codes\.revoked_at IS NULL/);
|
||||
assert.match(calls[0].text, /birds\.workspace_id = bird_transfer_codes\.source_workspace_id/);
|
||||
});
|
||||
|
||||
test('markBirdTransferCodeCompleted consumes a code for the receiving workspace', async () => {
|
||||
const { calls } = mockDb({ rowCount: 1, rows: [] });
|
||||
|
||||
await markBirdTransferCodeCompleted('code-1', 22);
|
||||
|
||||
assert.deepEqual(calls[0].params, ['code-1', 22]);
|
||||
assert.match(calls[0].text, /SET completed_at = CURRENT_TIMESTAMP/);
|
||||
assert.match(calls[0].text, /completed_workspace_id = \$2/);
|
||||
});
|
||||
@@ -1,153 +0,0 @@
|
||||
import { db } from '../db/client.js';
|
||||
import type { DailyEducationQuestion, DailyEducationRow, EducationQuestionRow } from '../types.js';
|
||||
|
||||
export const getEducationOptOut = async (userId: string) => {
|
||||
const result = await db.query<{ education_opt_out: boolean }>(
|
||||
`SELECT education_opt_out
|
||||
FROM users
|
||||
WHERE id = $1`,
|
||||
[userId],
|
||||
);
|
||||
|
||||
return result.rows[0]?.education_opt_out ?? false;
|
||||
};
|
||||
|
||||
export const updateEducationOptOut = async (userId: string, educationOptOut: boolean) => {
|
||||
const result = await db.query<{ education_opt_out: boolean }>(
|
||||
`UPDATE users
|
||||
SET education_opt_out = $2
|
||||
WHERE id = $1
|
||||
RETURNING education_opt_out`,
|
||||
[userId, educationOptOut],
|
||||
);
|
||||
|
||||
return result.rows[0]?.education_opt_out ?? educationOptOut;
|
||||
};
|
||||
|
||||
export const getDailyEducationForDate = async (publishDate?: string) => {
|
||||
const result = publishDate
|
||||
? await db.query<DailyEducationRow>(
|
||||
`SELECT id, publish_date::text, fact, quiz_questions, created_by_user_id, created_at, updated_at
|
||||
FROM daily_education
|
||||
WHERE publish_date = $1`,
|
||||
[publishDate],
|
||||
)
|
||||
: await db.query<DailyEducationRow>(
|
||||
`SELECT id, publish_date::text, fact, quiz_questions, created_by_user_id, created_at, updated_at
|
||||
FROM daily_education
|
||||
WHERE publish_date = CURRENT_DATE`,
|
||||
);
|
||||
|
||||
return result.rows[0] ?? null;
|
||||
};
|
||||
|
||||
export const listDailyEducationForAdmin = async () => {
|
||||
const result = await db.query<DailyEducationRow>(
|
||||
`SELECT id, publish_date::text, fact, quiz_questions, created_by_user_id, created_at, updated_at
|
||||
FROM daily_education
|
||||
ORDER BY publish_date DESC
|
||||
LIMIT 120`,
|
||||
);
|
||||
|
||||
return result.rows;
|
||||
};
|
||||
|
||||
export const upsertDailyEducation = async ({
|
||||
publishDate,
|
||||
fact,
|
||||
createdByUserId,
|
||||
}: {
|
||||
publishDate: string;
|
||||
fact: string;
|
||||
createdByUserId: string;
|
||||
}) => {
|
||||
const result = await db.query<DailyEducationRow>(
|
||||
`INSERT INTO daily_education (publish_date, fact, created_by_user_id)
|
||||
VALUES ($1, $2, $3)
|
||||
ON CONFLICT (publish_date) DO UPDATE
|
||||
SET fact = EXCLUDED.fact,
|
||||
updated_at = CURRENT_TIMESTAMP
|
||||
RETURNING id, publish_date::text, fact, quiz_questions, created_by_user_id, created_at, updated_at`,
|
||||
[publishDate, fact, createdByUserId],
|
||||
);
|
||||
|
||||
return result.rows[0];
|
||||
};
|
||||
|
||||
export const listEducationQuestionsForAdmin = async () => {
|
||||
const result = await db.query<EducationQuestionRow>(
|
||||
`SELECT id, prompt, options, correct_answer_index, explanation, created_by_user_id, created_at, updated_at
|
||||
FROM education_question_bank
|
||||
ORDER BY updated_at DESC, created_at DESC
|
||||
LIMIT 400`,
|
||||
);
|
||||
|
||||
return result.rows;
|
||||
};
|
||||
|
||||
export const listDailyEducationQuestions = async (seedDate?: string) => {
|
||||
const result = await db.query<EducationQuestionRow>(
|
||||
`SELECT id, prompt, options, correct_answer_index, explanation, created_by_user_id, created_at, updated_at
|
||||
FROM education_question_bank
|
||||
ORDER BY md5(COALESCE($1::text, CURRENT_DATE::text) || id::text)
|
||||
LIMIT 4`,
|
||||
[seedDate ?? null],
|
||||
);
|
||||
|
||||
return result.rows;
|
||||
};
|
||||
|
||||
export const createEducationQuestion = async ({
|
||||
question,
|
||||
createdByUserId,
|
||||
}: {
|
||||
question: DailyEducationQuestion;
|
||||
createdByUserId: string;
|
||||
}) => {
|
||||
const result = await db.query<EducationQuestionRow>(
|
||||
`INSERT INTO education_question_bank (prompt, options, correct_answer_index, explanation, created_by_user_id)
|
||||
VALUES ($1, $2::jsonb, $3, $4, $5)
|
||||
RETURNING id, prompt, options, correct_answer_index, explanation, created_by_user_id, created_at, updated_at`,
|
||||
[question.prompt, JSON.stringify(question.options), question.correctAnswerIndex, question.explanation, createdByUserId],
|
||||
);
|
||||
|
||||
return result.rows[0];
|
||||
};
|
||||
|
||||
export const updateEducationQuestion = async (questionId: string, question: DailyEducationQuestion) => {
|
||||
const result = await db.query<EducationQuestionRow>(
|
||||
`UPDATE education_question_bank
|
||||
SET prompt = $2,
|
||||
options = $3::jsonb,
|
||||
correct_answer_index = $4,
|
||||
explanation = $5,
|
||||
updated_at = CURRENT_TIMESTAMP
|
||||
WHERE id = $1
|
||||
RETURNING id, prompt, options, correct_answer_index, explanation, created_by_user_id, created_at, updated_at`,
|
||||
[questionId, question.prompt, JSON.stringify(question.options), question.correctAnswerIndex, question.explanation],
|
||||
);
|
||||
|
||||
return result.rows[0] ?? null;
|
||||
};
|
||||
|
||||
export const deleteEducationQuestion = async (questionId: string) => {
|
||||
const result = await db.query<{ id: string }>(
|
||||
`DELETE FROM education_question_bank
|
||||
WHERE id = $1
|
||||
RETURNING id`,
|
||||
[questionId],
|
||||
);
|
||||
|
||||
return Boolean(result.rowCount);
|
||||
};
|
||||
|
||||
export const deleteDailyEducation = async (educationId: string) => {
|
||||
const result = await db.query<{ id: string }>(
|
||||
`DELETE FROM daily_education
|
||||
WHERE id = $1
|
||||
RETURNING id`,
|
||||
[educationId],
|
||||
);
|
||||
|
||||
return Boolean(result.rowCount);
|
||||
};
|
||||
@@ -1,31 +0,0 @@
|
||||
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'));
|
||||
});
|
||||
@@ -1,48 +0,0 @@
|
||||
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;
|
||||
};
|
||||
@@ -104,7 +104,6 @@ export const locationSearchSchema = z.object({
|
||||
});
|
||||
|
||||
export const birdSchema = z.object({
|
||||
locationDate: dateStringSchema.optional().or(z.literal('')),
|
||||
name: z.string().trim().min(1).max(120),
|
||||
tagId: z.string().trim().max(80).optional().or(z.literal('')),
|
||||
species: z.string().trim().min(1).max(120),
|
||||
@@ -208,4 +207,3 @@ export const flockNoteSchema = z.object({
|
||||
birdId: z.string().uuid().optional().nullable().or(z.literal('')),
|
||||
body: z.string().trim().min(1).max(5000),
|
||||
});
|
||||
|
||||
@@ -1,30 +0,0 @@
|
||||
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);
|
||||
});
|
||||
@@ -13,38 +13,9 @@ export type UserRow = {
|
||||
email: string;
|
||||
password_hash: string | null;
|
||||
name: string;
|
||||
education_opt_out?: boolean;
|
||||
created_at: string;
|
||||
};
|
||||
|
||||
export type DailyEducationQuestion = {
|
||||
prompt: string;
|
||||
options: string[];
|
||||
correctAnswerIndex: number;
|
||||
explanation: string | null;
|
||||
};
|
||||
|
||||
export type DailyEducationRow = {
|
||||
id: string;
|
||||
publish_date: string;
|
||||
fact: string;
|
||||
quiz_questions: DailyEducationQuestion[];
|
||||
created_by_user_id: string | null;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
};
|
||||
|
||||
export type EducationQuestionRow = {
|
||||
id: string;
|
||||
prompt: string;
|
||||
options: string[];
|
||||
correct_answer_index: number;
|
||||
explanation: string | null;
|
||||
created_by_user_id: string | null;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
};
|
||||
|
||||
export type WorkspaceRow = {
|
||||
id: number;
|
||||
name: string;
|
||||
|
||||
@@ -1,22 +0,0 @@
|
||||
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;
|
||||
};
|
||||
@@ -22,7 +22,7 @@ try {
|
||||
for (let i = 0; i < 3; i++) {
|
||||
const workspace = baseId + i, user = randomUUID(), token = randomUUID(), email = `${user}@example.test`;
|
||||
await db.query(`INSERT INTO workspaces (id, name, workspace_type, rescue_verification_status) VALUES ($1, $2, 'rescue', 'approved')`, [workspace, `Membership test ${i}`]);
|
||||
await db.query(`INSERT INTO users (id, email, name, education_opt_out) VALUES ($1, $2, 'Tester', TRUE)`, [user, email]);
|
||||
await db.query(`INSERT INTO users (id, email, name) VALUES ($1, $2, 'Tester')`, [user, email]);
|
||||
await db.query(`INSERT INTO workspace_members (workspace_id, user_id, invite_email, name, role, accepted_at) VALUES ($1, $2, $3, 'Tester', 'owner', NOW())`, [workspace, user, email]);
|
||||
await db.query(`INSERT INTO auth_sessions (user_id, active_workspace_id, token_hash, expires_at) VALUES ($1, $2, $3, NOW() + INTERVAL '1 hour')`, [user, workspace, createHash('sha256').update(token).digest('hex')]);
|
||||
accounts.push({ workspace, user, token });
|
||||
|
||||
@@ -98,6 +98,12 @@ services:
|
||||
condition: service_healthy
|
||||
redis:
|
||||
condition: service_healthy
|
||||
healthcheck:
|
||||
test: ["CMD", "node", "dist/healthcheck.js", "api-ready"]
|
||||
interval: 30s
|
||||
timeout: 10s
|
||||
retries: 3
|
||||
start_period: 30s
|
||||
labels:
|
||||
- traefik.enable=true
|
||||
- traefik.docker.network=traefik
|
||||
@@ -158,6 +164,12 @@ services:
|
||||
condition: service_healthy
|
||||
redis:
|
||||
condition: service_healthy
|
||||
healthcheck:
|
||||
test: ["CMD", "node", "dist/healthcheck.js", "worker"]
|
||||
interval: 30s
|
||||
timeout: 10s
|
||||
retries: 3
|
||||
start_period: 30s
|
||||
restart: unless-stopped
|
||||
|
||||
frontend:
|
||||
@@ -169,6 +181,12 @@ services:
|
||||
container_name: flockpal-frontend
|
||||
depends_on:
|
||||
- backend
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "wget -q -O /dev/null http://127.0.0.1/healthz"]
|
||||
interval: 30s
|
||||
timeout: 5s
|
||||
retries: 3
|
||||
start_period: 10s
|
||||
labels:
|
||||
- traefik.enable=true
|
||||
- traefik.docker.network=traefik
|
||||
|
||||
@@ -96,6 +96,12 @@ services:
|
||||
condition: service_healthy
|
||||
redis:
|
||||
condition: service_healthy
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "node -e \"fetch('http://127.0.0.1:5000/api/health/ready').then(r => { if (!r.ok) process.exit(1) }).catch(() => process.exit(1))\""]
|
||||
interval: 30s
|
||||
timeout: 10s
|
||||
retries: 3
|
||||
start_period: 30s
|
||||
ports:
|
||||
- "5000:5000"
|
||||
command: >
|
||||
@@ -104,6 +110,7 @@ services:
|
||||
volumes:
|
||||
- ./backend:/app
|
||||
- /app/node_modules
|
||||
restart: unless-stopped
|
||||
|
||||
worker:
|
||||
build:
|
||||
|
||||
+35
-2
@@ -344,14 +344,47 @@ Validation failures return `400` with this shape:
|
||||
|
||||
#### `GET /api/health`
|
||||
|
||||
Public health check.
|
||||
Public readiness-compatible health check. Verifies backend dependencies.
|
||||
|
||||
Response `200`:
|
||||
|
||||
```json
|
||||
{ "ok": true }
|
||||
{
|
||||
"ok": true,
|
||||
"service": "flockpal-backend",
|
||||
"status": "ready",
|
||||
"checkedAt": "2026-06-06T00:00:00.000Z",
|
||||
"dependencies": {
|
||||
"postgres": { "ok": true, "latencyMs": 3 },
|
||||
"redis": { "ok": true, "latencyMs": 4 }
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Response `503` when Postgres or Redis is unavailable.
|
||||
|
||||
#### `GET /api/health/live`
|
||||
|
||||
Public liveness check. Verifies the backend process is running without checking dependencies.
|
||||
|
||||
Response `200`:
|
||||
|
||||
```json
|
||||
{
|
||||
"ok": true,
|
||||
"service": "flockpal-backend",
|
||||
"status": "live",
|
||||
"uptimeSeconds": 120,
|
||||
"checkedAt": "2026-06-06T00:00:00.000Z"
|
||||
}
|
||||
```
|
||||
|
||||
#### `GET /api/health/ready`
|
||||
|
||||
Public readiness check. Verifies the backend can reach Postgres and Redis.
|
||||
|
||||
Response `200` uses the same shape as `GET /api/health`; response `503` means at least one dependency failed.
|
||||
|
||||
### Metrics
|
||||
|
||||
#### `GET /api/metrics`
|
||||
|
||||
@@ -12,6 +12,12 @@ server {
|
||||
add_header X-Frame-Options "SAMEORIGIN" always;
|
||||
add_header Permissions-Policy "camera=(), microphone=(), geolocation=()" always;
|
||||
|
||||
location = /healthz {
|
||||
access_log off;
|
||||
add_header Content-Type text/plain;
|
||||
return 200 "ok\n";
|
||||
}
|
||||
|
||||
location / {
|
||||
try_files $uri $uri/ /index.html;
|
||||
}
|
||||
|
||||
+111
-804
File diff suppressed because it is too large.
Load diff
@@ -1,68 +0,0 @@
|
||||
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>
|
||||
);
|
||||
}
|
||||
@@ -1,26 +0,0 @@
|
||||
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)),
|
||||
);
|
||||
};
|
||||
+43
-210
@@ -216,7 +216,6 @@ textarea {
|
||||
}
|
||||
|
||||
.side-rail {
|
||||
z-index: 30;
|
||||
position: sticky;
|
||||
top: 2rem;
|
||||
display: grid;
|
||||
@@ -793,123 +792,6 @@ textarea {
|
||||
align-content: start;
|
||||
}
|
||||
|
||||
.daily-education-panel,
|
||||
.daily-quiz,
|
||||
.quiz-options,
|
||||
.education-question-editor {
|
||||
display: grid;
|
||||
gap: 1rem;
|
||||
}
|
||||
|
||||
.daily-education-panel.condensed {
|
||||
gap: 0.35rem;
|
||||
padding-block: 1rem;
|
||||
}
|
||||
|
||||
.daily-education-panel.condensed .panel-header {
|
||||
margin-bottom: 0;
|
||||
}
|
||||
|
||||
.daily-education-teaser {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.daily-fact {
|
||||
margin: 0;
|
||||
padding: 1rem;
|
||||
border-left: 4px solid var(--accent-gold);
|
||||
border-radius: 0 8px 8px 0;
|
||||
background: rgba(255, 254, 250, 0.7);
|
||||
font-size: 1.08rem;
|
||||
}
|
||||
|
||||
.daily-quiz {
|
||||
grid-template-columns: repeat(auto-fit, minmax(min(290px, 100%), 1fr));
|
||||
}
|
||||
|
||||
.quiz-question,
|
||||
.quiz-editor-question {
|
||||
min-width: 0;
|
||||
margin: 0;
|
||||
border: 1px solid var(--button-border);
|
||||
}
|
||||
|
||||
.quiz-question {
|
||||
display: grid;
|
||||
gap: 0.85rem;
|
||||
padding: 1rem;
|
||||
border-radius: 8px;
|
||||
background: rgba(255, 254, 250, 0.64);
|
||||
}
|
||||
|
||||
.quiz-question legend,
|
||||
.quiz-editor-question legend {
|
||||
padding: 0 0.35rem;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.quiz-option {
|
||||
display: grid;
|
||||
grid-template-columns: auto minmax(0, 1fr);
|
||||
align-items: start;
|
||||
gap: 0.65rem;
|
||||
min-width: 0;
|
||||
padding: 0.7rem;
|
||||
border: 1px solid rgba(39, 105, 179, 0.12);
|
||||
border-radius: 8px;
|
||||
background: rgba(255, 255, 255, 0.58);
|
||||
}
|
||||
|
||||
.quiz-option.correct {
|
||||
border-color: rgba(35, 138, 90, 0.42);
|
||||
background: rgba(223, 247, 229, 0.82);
|
||||
}
|
||||
|
||||
.quiz-option.incorrect {
|
||||
border-color: rgba(203, 58, 53, 0.36);
|
||||
background: rgba(255, 236, 232, 0.82);
|
||||
}
|
||||
|
||||
.quiz-option input {
|
||||
width: auto;
|
||||
margin: 0.25rem 0 0;
|
||||
}
|
||||
|
||||
.quiz-feedback {
|
||||
margin: 0;
|
||||
color: var(--accent-red);
|
||||
}
|
||||
|
||||
.quiz-feedback.correct {
|
||||
color: var(--accent-green);
|
||||
}
|
||||
|
||||
.admin-education-panel,
|
||||
.education-admin-basics,
|
||||
.quiz-editor-question,
|
||||
.education-admin-list {
|
||||
display: grid;
|
||||
gap: 1rem;
|
||||
}
|
||||
|
||||
.education-admin-basics {
|
||||
grid-template-columns: minmax(180px, 0.35fr) minmax(0, 1fr);
|
||||
}
|
||||
|
||||
.quiz-editor-question {
|
||||
padding: 1rem;
|
||||
}
|
||||
|
||||
.quiz-editor-options {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
gap: 0.8rem;
|
||||
}
|
||||
|
||||
.education-admin-list span {
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.button-row {
|
||||
display: flex;
|
||||
gap: 0.75rem;
|
||||
@@ -974,77 +856,33 @@ textarea {
|
||||
|
||||
.workspace-switcher {
|
||||
display: grid;
|
||||
gap: 0.45rem;
|
||||
min-width: 0;
|
||||
padding-bottom: 1rem;
|
||||
border-bottom: 1px solid rgba(39, 105, 179, 0.16);
|
||||
gap: 0.9rem;
|
||||
}
|
||||
|
||||
.workspace-switcher-label {
|
||||
.workspace-switcher-item small {
|
||||
color: var(--muted);
|
||||
font-size: 0.78rem;
|
||||
font-weight: 700;
|
||||
letter-spacing: 0.06em;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
|
||||
.workspace-switcher { position: relative; }
|
||||
|
||||
.flock-switcher-trigger {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.7rem;
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
padding: 0.8rem;
|
||||
color: var(--ink);
|
||||
text-align: left;
|
||||
background: rgba(255, 255, 255, 0.65);
|
||||
border: 1px solid var(--panel-border);
|
||||
border-radius: 16px;
|
||||
box-shadow: 0 3px 10px rgba(53, 90, 66, 0.05);
|
||||
}
|
||||
|
||||
.flock-switcher-trigger:hover:not(:disabled) { background: #fffaf0; border-color: var(--accent-green); }
|
||||
.flock-switcher-trigger:focus-visible, .flock-switcher-option:focus-visible { outline: 2px solid var(--accent-green); outline-offset: 3px; }
|
||||
.flock-switcher-avatar {
|
||||
.workspace-switcher-list {
|
||||
display: grid;
|
||||
place-items: center;
|
||||
flex: 0 0 36px;
|
||||
height: 36px;
|
||||
border-radius: 11px;
|
||||
background: #e1eee2;
|
||||
color: #276b48;
|
||||
font-weight: 800;
|
||||
gap: 0.75rem;
|
||||
}
|
||||
.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);
|
||||
|
||||
.workspace-switcher-item {
|
||||
width: 100%;
|
||||
text-align: left;
|
||||
border: 1px solid rgba(39, 105, 179, 0.12);
|
||||
border-radius: 18px;
|
||||
background: #fffaf1;
|
||||
box-shadow: 0 18px 45px rgba(35, 65, 45, 0.2);
|
||||
padding: 0.85rem 0.95rem;
|
||||
background: rgba(255, 255, 255, 0.58);
|
||||
display: grid;
|
||||
gap: 0.2rem;
|
||||
}
|
||||
|
||||
.workspace-switcher-item.active {
|
||||
background: linear-gradient(135deg, rgba(203, 58, 53, 0.16), rgba(39, 105, 179, 0.18));
|
||||
border-color: rgba(39, 105, 179, 0.24);
|
||||
}
|
||||
.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 {
|
||||
gap: 0.75rem;
|
||||
@@ -2667,11 +2505,6 @@ label {
|
||||
}
|
||||
|
||||
@media (max-width: 980px) {
|
||||
.education-admin-basics,
|
||||
.quiz-editor-options {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
|
||||
.app-shell,
|
||||
.auth-panel,
|
||||
.hero-card,
|
||||
@@ -2790,12 +2623,25 @@ label {
|
||||
|
||||
.workspace-switcher {
|
||||
grid-column: 1 / -1;
|
||||
gap: 0.4rem;
|
||||
padding-bottom: 0.65rem;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.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) {
|
||||
@@ -2941,7 +2787,17 @@ label {
|
||||
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 {
|
||||
gap: 0.65rem;
|
||||
@@ -3066,7 +2922,6 @@ label {
|
||||
|
||||
.inline-form,
|
||||
.settings-nested-grid,
|
||||
.education-admin-basics,
|
||||
.quiz-editor-options,
|
||||
.dose-schedule-row,
|
||||
.verified-location-search-row,
|
||||
@@ -3241,25 +3096,3 @@ label {
|
||||
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);
|
||||
}
|
||||
@@ -27,7 +27,7 @@ try {
|
||||
const workspace = 100000 + Math.floor(Math.random() * 1000000000);
|
||||
const user = randomUUID(), bird = randomUUID(), secondBird = randomUUID(), token = randomUUID();
|
||||
await db.query(`INSERT INTO workspaces (id, name, workspace_type, rescue_verification_status) VALUES ($1, 'Browser test', 'rescue', 'approved')`, [workspace]);
|
||||
await db.query(`INSERT INTO users (id, email, name, education_opt_out) VALUES ($1, $2, 'Browser tester', TRUE)`, [user, `${user}@example.test`]);
|
||||
await db.query(`INSERT INTO users (id, email, name) VALUES ($1, $2, 'Browser tester')`, [user, `${user}@example.test`]);
|
||||
await db.query(`INSERT INTO workspace_members (workspace_id, user_id, invite_email, name, role, accepted_at) VALUES ($1, $2, $3, 'Browser tester', 'owner', NOW())`, [workspace, user, `${user}@example.test`]);
|
||||
await db.query(`INSERT INTO auth_sessions (user_id, active_workspace_id, token_hash, expires_at) VALUES ($1, $2, $3, NOW() + INTERVAL '1 hour')`, [user, workspace, createHash('sha256').update(token).digest('hex')]);
|
||||
await db.query(`INSERT INTO birds (id, workspace_id, name, species) VALUES ($1, $2, 'Piper', 'Parrot'), ($3, $2, 'Willow', 'Parrot')`, [bird, workspace, secondBird]);
|
||||
|
||||
@@ -28,7 +28,7 @@ try {
|
||||
for (let i = 0; i < 2; i++) {
|
||||
const workspace = baseId + i, user = randomUUID(), token = randomUUID(), email = `${user}@example.test`;
|
||||
await db.query(`INSERT INTO workspaces (id, name, workspace_type, rescue_verification_status) VALUES ($1, $2, 'rescue', 'approved')`, [workspace, `Browser membership ${i}`]);
|
||||
await db.query(`INSERT INTO users (id, email, name, education_opt_out) VALUES ($1, $2, 'Browser tester', TRUE)`, [user, email]);
|
||||
await db.query(`INSERT INTO users (id, email, name) VALUES ($1, $2, 'Browser tester')`, [user, email]);
|
||||
await db.query(`INSERT INTO workspace_members (workspace_id, user_id, invite_email, name, role, accepted_at) VALUES ($1, $2, $3, 'Browser tester', 'owner', NOW())`, [workspace, user, email]);
|
||||
await db.query(`INSERT INTO auth_sessions (user_id, active_workspace_id, token_hash, expires_at) VALUES ($1, $2, $3, NOW() + INTERVAL '1 hour')`, [user, workspace, createHash('sha256').update(token).digest('hex')]);
|
||||
accounts.push({ workspace, token });
|
||||
|
||||
@@ -1,23 +0,0 @@
|
||||
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]);
|
||||
});
|
||||
Reference in new issue
Block a user