34 Commits
Author SHA1 Message Date
blaisadmin cc4a2382c6 Add production health checks
Deploy / deploy-dev (push) Has been skipped
Deploy / deploy-prod (push) Successful in 1m46s
2026-06-05 22:28:48 -04:00
blaisadmin 5735bb7735 Adding promoting to owner
Deploy / deploy-dev (push) Has been skipped
Deploy / deploy-prod (push) Successful in 2m23s
2026-06-05 21:45:58 -04:00
blaisadmin 88ff06237e Adjusting role actions 2026-06-05 21:45:58 -04:00
Corey Blais fbb13561b0 Medication reminder and pdr worker 2026-06-05 21:45:58 -04:00
Corey Blais b15861c856 Use fixed screen size for adoption report sheet 2026-06-05 21:42:20 -04:00
Corey Blais 2aeaa119f7 Wrap adoption report in letter sheet 2026-06-05 21:42:20 -04:00
Corey Blais 36690c0174 Tighten adoption report page scale 2026-06-05 21:42:20 -04:00
Corey Blais b76ad35c07 Size adoption report for letter paper 2026-06-05 21:42:20 -04:00
Corey Blais 6918b55a58 Stabilize adoption report layout 2026-06-05 21:42:20 -04:00
blaisadmin 49f1713e26 Add flock member notes and audit tabs 2026-06-05 21:42:20 -04:00
Corey Blais c9fa7e4246 Cover consumed adoption transfer codes
Deploy / deploy-dev (push) Has been skipped
Deploy / deploy-prod (push) Successful in 1m45s
2026-06-03 14:12:10 -04:00
Corey Blais 0411ec5175 Keep adoption transfer codes stable
Deploy / deploy-dev (push) Has been skipped
Deploy / deploy-prod (push) Successful in 2m17s
2026-06-03 12:10:27 -04:00
Corey Blais 7b7171c109 Prevent report card text overlap
Deploy / deploy-dev (push) Has been skipped
Deploy / deploy-prod (push) Successful in 1m47s
2026-06-03 11:54:44 -04:00
Corey Blais c02bb4d6d8 Convert report photos for PDF embedding
Deploy / deploy-dev (push) Has been skipped
Deploy / deploy-prod (push) Successful in 2m37s
2026-06-03 11:20:52 -04:00
Corey Blais 603b4eee4d Render adoption reports in worker
Deploy / deploy-dev (push) Has been skipped
Deploy / deploy-prod (push) Successful in 1m43s
2026-06-03 10:55:09 -04:00
Corey Blais 52008f5b43 Fix adoption report photos and section order
Deploy / deploy-dev (push) Has been skipped
Deploy / deploy-prod (push) Successful in 2m23s
2026-06-03 10:05:48 -04:00
Corey Blais 5b57cdd6bf Fix adoption report QR and chart layout 2026-06-03 10:05:48 -04:00
Corey Blais 60eadf0847 Refine adoption report header layout 2026-06-03 10:05:48 -04:00
Corey Blais 682ccfd41f Generate adoption reports as PDFs 2026-06-03 10:05:48 -04:00
Corey Blais 59c6b19ad6 fixing analytics icon pt2
Deploy / deploy-dev (push) Has been skipped
Deploy / deploy-prod (push) Successful in 2m15s
2026-06-02 12:55:35 -04:00
Corey Blais aa1a4cf6ff fixing analytics icon 2026-06-02 12:55:35 -04:00
Corey Blais 5f0fad3cbb Updated adoption report 2026-06-02 12:55:35 -04:00
Corey Blais 545fae59b2 Added adoption report and transfer code 2026-06-02 12:55:35 -04:00
Corey Blais d748d2db21 Added vet info
Deploy / deploy-dev (push) Has been skipped
Deploy / deploy-prod (push) Successful in 2m14s
2026-06-01 15:20:47 -04:00
blaisadmin 095c91e56d Merge branch 'release/flock-member-notes-audit'
Deploy / deploy-dev (push) Has been skipped
Deploy / deploy-prod (push) Successful in 2m16s
2026-05-30 22:50:54 -04:00
blaisadmin f2017068d5 Auto deploy production on main merge 2026-05-30 22:47:11 -04:00
blaisadmin c9702495a3 Add flock member notes and audit tabs 2026-05-30 22:46:31 -04:00
blaisadmin e965cb55ef Revert education feature from main 2026-05-30 15:50:23 -04:00
blaisadmin 505a9b8496 Added backend limits 2026-05-30 15:43:38 -04:00
blaisadmin c6dc5b22b8 Merge dev into main 2026-05-30 15:29:48 -04:00
blaisadmin f16e88e2f0 Validate builds before deploy 2026-05-24 21:48:42 -04:00
blaisadmin 016bc187d4 Run deploy compose from host repo paths 2026-05-24 11:33:58 -04:00
blaisadmin 104f01f75d Use local mounts for production deploy workflow 2026-05-23 18:38:49 -04:00
blaisadmin 568aee3e70 Adding gitea action 2026-05-23 16:32:59 -04:00
41 changed files with 1388 additions and 5079 deletions
-8
View File
@@ -14,7 +14,6 @@ PHOTO_DELIVERY_MODE=proxy
FRONTEND_URL=http://localhost:3000
BACKEND_URL=http://localhost:5000
VITE_API_BASE_URL=http://localhost:5000/api
MAPBOX_ACCESS_TOKEN=
NODE_ENV=development
TRUST_PROXY=
ADMIN_EMAILS=corey@blaishome.online
@@ -39,10 +38,3 @@ STRIPE_PRICE_HOUSEHOLD_HYACINTH_MACAW_YEARLY=
STRIPE_CHECKOUT_SUCCESS_URL=http://localhost:3000/?billing=success
STRIPE_CHECKOUT_CANCEL_URL=http://localhost:3000/?billing=cancelled
STRIPE_PORTAL_RETURN_URL=http://localhost:3000/?billing=portal
# Daily email for birds without a new weight entry in 48 hours; uses the milestone time zone.
WEIGHT_REMINDERS_ENABLED=true
# Optional absolute HTTPS image URL; defaults to FRONTEND_URL/email-background.png.
# Deploy frontend/public/email-background.png before sending the updated email templates.
EMAIL_BACKGROUND_URL=
+3 -124
View File
@@ -3,13 +3,14 @@ name: Deploy
on:
push:
branches:
- main
- dev
- develop
workflow_dispatch:
jobs:
deploy-dev:
if: ${{ github.event_name == 'push' }}
if: ${{ github.event_name == 'push' && (github.ref_name == 'dev' || github.ref_name == 'develop') }}
runs-on: ubuntu-latest
container:
volumes:
@@ -47,69 +48,8 @@ jobs:
cd /docker/FlockPal-dev
docker compose -f docker-compose.dev.yaml up -d --build
- name: Notify Discord
if: always()
env:
DISCORD_WEBHOOK_URL: ${{ secrets.DISCORD_WEBHOOK_URL }}
JOB_STATUS: ${{ job.status }}
run: |
if [ -z "$DISCORD_WEBHOOK_URL" ]; then
echo "DISCORD_WEBHOOK_URL is not configured; skipping Discord notification."
exit 0
fi
if [ "$JOB_STATUS" = "success" ]; then
STATUS_TITLE="Deploy succeeded"
COLOR=65280
else
STATUS_TITLE="Deploy failed"
COLOR=16711680
fi
RUN_URL="${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}"
AVATAR_URL="${{ vars.DISCORD_AVATAR_URL }}"
AVATAR_URL="${AVATAR_URL:-https://www.flockpal.app/FlockPal-Paint.png}"
COMMIT_MESSAGE="$(git -C /docker/FlockPal-dev log -1 --pretty=%s 2>/dev/null || printf '%s' '${{ github.sha }}')"
json_escape() {
printf '%s' "$1" | sed 's/\\/\\\\/g; s/"/\\"/g'
}
BRANCH="$(json_escape '${{ github.ref_name }}')"
MESSAGE="$(json_escape "$COMMIT_MESSAGE")"
AVATAR_URL="$(json_escape "$AVATAR_URL")"
cat > /tmp/discord-payload.json <<EOF
{
"username": "FlockPal Build",
"avatar_url": "${AVATAR_URL}",
"embeds": [
{
"title": "${STATUS_TITLE}",
"url": "${RUN_URL}",
"description": "FlockPal dev deploy",
"color": ${COLOR},
"fields": [
{
"name": "Branch",
"value": "${BRANCH}",
"inline": true
},
{
"name": "Message",
"value": "${MESSAGE}",
"inline": false
}
]
}
]
}
EOF
curl --fail --show-error --silent \
-H "Content-Type: application/json" \
-d @/tmp/discord-payload.json \
"$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:
@@ -146,64 +86,3 @@ jobs:
set -e
cd /docker/FlockPal
docker compose -f docker-compose.prod.yml up -d --build
- name: Notify Discord
if: always()
env:
DISCORD_WEBHOOK_URL: ${{ secrets.DISCORD_WEBHOOK_URL }}
JOB_STATUS: ${{ job.status }}
run: |
if [ -z "$DISCORD_WEBHOOK_URL" ]; then
echo "DISCORD_WEBHOOK_URL is not configured; skipping Discord notification."
exit 0
fi
if [ "$JOB_STATUS" = "success" ]; then
STATUS_TITLE="Deploy succeeded"
COLOR=65280
else
STATUS_TITLE="Deploy failed"
COLOR=16711680
fi
RUN_URL="${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}"
AVATAR_URL="${{ vars.DISCORD_AVATAR_URL }}"
AVATAR_URL="${AVATAR_URL:-https://www.flockpal.app/FlockPal-Paint.png}"
COMMIT_MESSAGE="$(git -C /docker/FlockPal log -1 --pretty=%s 2>/dev/null || printf '%s' '${{ github.sha }}')"
json_escape() {
printf '%s' "$1" | sed 's/\\/\\\\/g; s/"/\\"/g'
}
BRANCH="$(json_escape '${{ github.ref_name }}')"
MESSAGE="$(json_escape "$COMMIT_MESSAGE")"
AVATAR_URL="$(json_escape "$AVATAR_URL")"
cat > /tmp/discord-payload.json <<EOF
{
"username": "FlockPal Build",
"avatar_url": "${AVATAR_URL}",
"embeds": [
{
"title": "${STATUS_TITLE}",
"url": "${RUN_URL}",
"description": "FlockPal production deploy",
"color": ${COLOR},
"fields": [
{
"name": "Branch",
"value": "${BRANCH}",
"inline": true
},
{
"name": "Message",
"value": "${MESSAGE}",
"inline": false
}
]
}
]
}
EOF
curl --fail --show-error --silent \
-H "Content-Type: application/json" \
-d @/tmp/discord-payload.json \
"$DISCORD_WEBHOOK_URL" || echo "Discord notification failed."
+17 -31
View File
@@ -47,6 +47,23 @@ The default `docker-compose.yml` is development-only. It mounts source files, in
## Operations
### Health checks
Monitor these production checks:
- Frontend: `GET https://your-host/healthz`
- Verifies Nginx is serving the frontend container.
- Backend liveness: `GET https://your-host/api/health/live`
- Verifies the API process is running.
- Backend readiness: `GET https://your-host/api/health/ready`
- Verifies the API can reach Postgres and Redis. Returns `503` if either dependency is unavailable.
- Backend metrics: `GET https://your-host/api/metrics`
- Admin-authenticated process, request, and queue metrics.
- Postgres and Redis:
- Use the Docker health checks in `docker-compose.prod.yml`.
- Worker:
- Use the Docker health check in `docker-compose.prod.yml`; it validates worker dependencies. The worker does not expose HTTP.
### Backups
Create a compressed Postgres backup from the Docker Compose Postgres service:
@@ -86,7 +103,6 @@ curl -H "Authorization: Bearer <admin-token>" https://your-host/api/metrics
- `FRONTEND_URL`
- `BACKEND_URL`
- `VITE_API_BASE_URL`
- `MAPBOX_ACCESS_TOKEN`
- `REDIS_URL`
- `IMAGE_STORAGE_PROVIDER`
- `S3_ENDPOINT`
@@ -95,8 +111,6 @@ curl -H "Authorization: Bearer <admin-token>" https://your-host/api/metrics
- `S3_ACCESS_KEY_ID`
- `S3_SECRET_ACCESS_KEY`
- `RESCUE_ONBOARDING_WEBHOOK_URL`
- `DISCORD_WEBHOOK_URL` as a Gitea Actions secret for deploy notifications
- `DISCORD_AVATAR_URL` as an optional Gitea Actions variable for the deploy notification icon
2. Build and start the production stack:
```bash
@@ -161,34 +175,6 @@ npm run build
npm run worker
```
### Overdue weight emails
The worker checks once per calendar day for living birds with no new weight entry in
48 hours. Each accepted owner, assistant, or caregiver receives one email per flock
listing all birds due for a reminder. The branded email embeds the FlockPal logo
and each bird's portrait (including private S3 photos), with the default portrait
used when a photo is missing or unavailable. Pending invitees and viewers are excluded.
Reminders repeat daily while overdue; adding a new weight restarts the
48-hour clock. Birds without weights use their profile creation time.
Scheduling matches hatch-day reminders: a check 15 seconds after worker startup,
then hourly, with one queued job per local date. There is no fixed morning send
time. Both use `MILESTONE_REMINDER_TIME_ZONE` (default `America/New_York`).
Delivery tracking uses local calendar dates, including daylight-saving changes.
Deploying this change removes the old five-minute Redis schedule.
The clock uses the weight entry's creation timestamp, since the measurement date
has no time of day. Editing an existing entry does not restart the clock; entering
a historical weight does. Memorialized birds are excluded.
`WEIGHT_REMINDERS_ENABLED` defaults to `true` in both Compose stacks. Set it to
`false` to disable delivery. The worker, Redis, Postgres, and existing SMTP settings
must be available. The schema initializer creates the delivery tracking table.
Missing SMTP configuration or failed sends leave reminders eligible for retry.
Delivery tracking prevents ordinary repeat sends and concurrent claims; as with
other SMTP delivery, a crash after acceptance but before saving delivery can cause
a duplicate on retry.
## Auth and flock notes
- One user can belong to multiple flocks.
Binary file not shown.

Before

Width:  |  Height:  |  Size: 237 KiB

@@ -1,13 +0,0 @@
// Rebuild the email-safe PNG from the app's SVG tracks and background palette.
// Run from backend: node scripts/generate-email-background.mjs
import { readFile, writeFile } from 'node:fs/promises';
import sharp from 'sharp';
const css = await readFile(new URL('../../frontend/src/index.css', import.meta.url), 'utf8');
const encoded = css.match(/background-image: url\("data:image\/svg\+xml,([^"\n]+)"\)/)?.[1];
if (!encoded) throw new Error('App bird-track background was not found');
const tracks = decodeURIComponent(encoded);
const gradients = `<defs><linearGradient id="wash" x2="0" y2="1"><stop stop-color="#fef5e7"/><stop offset=".46" stop-color="#e9ddba"/><stop offset="1" stop-color="#d9eadf"/></linearGradient>${[[14,10,22,'#de7c3a',.28],[82,12,20,'#35886e',.26],[24,84,22,'#ddb34e',.2],[86,78,24,'#2b765c',.24],[62,54,16,'#3072a0',.14]].map(([x,y,r,color,opacity],i)=>`<radialGradient id="glow${i}" cx="${x}%" cy="${y}%" r="${r}%"><stop stop-color="${color}" stop-opacity="${opacity}"/><stop offset="1" stop-color="${color}" stop-opacity="0"/></radialGradient>`).join('')}</defs>`;
const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="800" height="1100" viewBox="0 0 1600 2200">${gradients}<rect width="1600" height="2200" fill="url(#wash)"/>${[0,1,2,3,4].map(i=>`<rect width="1600" height="2200" fill="url(#glow${i})"/>`).join('')}<g opacity=".42">${tracks.replace(/^<svg[^>]*>/,'').replace(/<\/svg>$/,'')}</g></svg>`;
await writeFile(new URL('../assets/email-background.png', import.meta.url), await sharp(Buffer.from(svg)).png().toBuffer());
await writeFile(new URL('../../frontend/public/email-background.png', import.meta.url), await readFile(new URL('../assets/email-background.png', import.meta.url)));
+367 -785
View File
File diff suppressed because it is too large Load Diff
-75
View File
@@ -30,9 +30,6 @@ export const ensureSchema = async (database: DatabaseClient = db) => {
ALTER TABLE workspaces
DROP CONSTRAINT IF EXISTS workspaces_id_check;
ALTER TABLE users
ADD COLUMN IF NOT EXISTS education_opt_out BOOLEAN NOT NULL DEFAULT FALSE;
ALTER TABLE workspaces
ADD COLUMN IF NOT EXISTS billing_email VARCHAR(255),
ADD COLUMN IF NOT EXISTS billing_plan VARCHAR(32) NOT NULL DEFAULT 'household_basic',
@@ -142,37 +139,6 @@ export const ensureSchema = async (database: DatabaseClient = db) => {
CREATE INDEX IF NOT EXISTS idx_auth_sessions_created_user
ON auth_sessions (created_at DESC, user_id);
CREATE TABLE IF NOT EXISTS daily_education (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
publish_date DATE NOT NULL UNIQUE,
fact TEXT NOT NULL,
quiz_questions JSONB NOT NULL DEFAULT '[]'::jsonb,
created_by_user_id UUID REFERENCES users(id) ON DELETE SET NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
);
ALTER TABLE daily_education
ALTER COLUMN quiz_questions SET DEFAULT '[]'::jsonb;
CREATE INDEX IF NOT EXISTS idx_daily_education_publish_date
ON daily_education (publish_date DESC);
CREATE TABLE IF NOT EXISTS education_question_bank (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
prompt VARCHAR(500) NOT NULL,
options JSONB NOT NULL,
correct_answer_index INTEGER NOT NULL,
explanation VARCHAR(800),
created_by_user_id UUID REFERENCES users(id) ON DELETE SET NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
CHECK (correct_answer_index >= 0 AND correct_answer_index <= 3)
);
CREATE INDEX IF NOT EXISTS idx_education_question_bank_created
ON education_question_bank (created_at DESC);
CREATE TABLE IF NOT EXISTS integration_tokens (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
@@ -249,8 +215,6 @@ export const ensureSchema = async (database: DatabaseClient = db) => {
motivators VARCHAR(1000),
demotivators VARCHAR(1000),
favorite_snack VARCHAR(160),
location_label VARCHAR(160),
location_details JSONB,
vet_clinic_name VARCHAR(160),
vet_clinic_address VARCHAR(500),
vet_account_number VARCHAR(120),
@@ -279,8 +243,6 @@ export const ensureSchema = async (database: DatabaseClient = db) => {
ADD COLUMN IF NOT EXISTS motivators VARCHAR(1000),
ADD COLUMN IF NOT EXISTS demotivators VARCHAR(1000),
ADD COLUMN IF NOT EXISTS favorite_snack VARCHAR(160),
ADD COLUMN IF NOT EXISTS location_label VARCHAR(160),
ADD COLUMN IF NOT EXISTS location_details JSONB,
ADD COLUMN IF NOT EXISTS vet_clinic_name VARCHAR(160),
ADD COLUMN IF NOT EXISTS vet_clinic_address VARCHAR(500),
ADD COLUMN IF NOT EXISTS vet_account_number VARCHAR(120),
@@ -406,32 +368,6 @@ export const ensureSchema = async (database: DatabaseClient = db) => {
WHERE completed_at IS NULL
AND revoked_at IS NULL;
CREATE TABLE IF NOT EXISTS bird_timeline_events (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
bird_id UUID NOT NULL REFERENCES birds(id) ON DELETE CASCADE,
event_type VARCHAR(40) NOT NULL,
from_workspace_id INTEGER REFERENCES workspaces(id) ON DELETE SET NULL,
to_workspace_id INTEGER REFERENCES workspaces(id) ON DELETE SET NULL,
from_workspace_name VARCHAR(160),
to_workspace_name VARCHAR(160),
from_owner_email VARCHAR(255),
to_owner_email VARCHAR(255),
location_label VARCHAR(160),
location_details JSONB,
note TEXT,
event_date DATE NOT NULL DEFAULT CURRENT_DATE,
created_by_user_id UUID REFERENCES users(id) ON DELETE SET NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
);
ALTER TABLE bird_timeline_events
ADD COLUMN IF NOT EXISTS note TEXT,
ADD COLUMN IF NOT EXISTS location_details JSONB,
ADD COLUMN IF NOT EXISTS event_date DATE NOT NULL DEFAULT CURRENT_DATE;
CREATE INDEX IF NOT EXISTS idx_bird_timeline_events_bird_created
ON bird_timeline_events (bird_id, event_date DESC, created_at DESC);
CREATE TABLE IF NOT EXISTS flock_notes (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
workspace_id INTEGER NOT NULL REFERENCES workspaces(id) ON DELETE CASCADE,
@@ -480,17 +416,6 @@ export const ensureSchema = async (database: DatabaseClient = db) => {
UNIQUE (bird_id, recorded_on)
);
CREATE TABLE IF NOT EXISTS weight_reminder_deliveries (
bird_id UUID NOT NULL REFERENCES birds(id) ON DELETE CASCADE,
workspace_id INTEGER NOT NULL REFERENCES workspaces(id) ON DELETE CASCADE,
activity_at TIMESTAMPTZ NOT NULL,
recipient TEXT NOT NULL,
claim_token UUID NOT NULL,
claimed_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
delivered_at TIMESTAMPTZ,
PRIMARY KEY (bird_id, workspace_id, activity_at, recipient)
);
CREATE TABLE IF NOT EXISTS vet_visits (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
bird_id UUID NOT NULL REFERENCES birds(id) ON DELETE CASCADE,
-29
View File
@@ -1,29 +0,0 @@
import { readFile } from 'node:fs/promises';
import sharp from 'sharp';
import type { WeightReminder } from '../reminders/weightReminders.js';
import { getS3ImageStorageConfig } from '../storage/imageStorageConfig.js';
import { getSignedS3ObjectUrl } from '../storage/s3Client.js';
const asset = (name: string) => new URL(`../../assets/${name}`, import.meta.url);
const thumbnail = (content: Buffer) => sharp(content).rotate().resize(192, 192, { fit: 'cover' }).jpeg({ quality: 80 }).toBuffer();
export const loadWeightReminderPortrait = async (bird: Pick<WeightReminder, 'bird_id' | 'photo_object_key' | 'photo_data_url'>): Promise<Buffer> => {
try {
if (bird.photo_object_key) {
const config = getS3ImageStorageConfig();
if (config) {
const response = await fetch(getSignedS3ObjectUrl({ config, objectKey: bird.photo_object_key, expiresInSeconds: 300 }), {
signal: AbortSignal.timeout(10_000),
});
if (!response.ok) throw new Error(`Photo storage returned ${response.status}`);
return await thumbnail(Buffer.from(await response.arrayBuffer()));
}
}
const match = bird.photo_data_url?.match(/^data:image\/(?:png|jpe?g|webp|gif);base64,(.+)$/);
if (match) return await thumbnail(Buffer.from(match[1], 'base64'));
} catch {
console.warn(`Unable to load weight reminder portrait for bird ${bird.bird_id}; using default portrait.`);
}
return thumbnail(await readFile(asset('yoda-default.png')));
};
-36
View File
@@ -1,36 +0,0 @@
import assert from 'node:assert/strict';
import { test } from 'node:test';
import { buildEmailLayout } from './emailLayout.js';
test('shared layout escapes copy and embeds the app background and bird portrait', async () => {
const mail = await buildEmailLayout({
backgroundUrl: 'https://flockpal.test/email-background.png',
eyebrow: 'Medication <reminder>', headline: 'Medication time for Kiwi & Peep',
contentHtml: '<p>Morning at 8:00 AM</p>',
action: { url: 'https://flockpal.test/?a=1&b=2', label: 'Open <FlockPal>' },
bird: { id: 'bird-1', name: 'Kiwi & Peep', photo_data_url: null, photo_object_key: null },
});
const html = String(mail.html);
assert.match(html, /Medication &lt;reminder&gt;/);
assert.match(html, /Medication time for Kiwi &amp; Peep/);
assert.match(html, /a=1&amp;b=2/);
assert.match(html, /Open &lt;FlockPal&gt;/);
assert.match(html, /Morning at 8:00 AM/);
assert.match(html, /background="https:\/\/flockpal.test\/email-background.png"/);
assert.match(html, /background-image:url\('https:\/\/flockpal.test\/email-background.png'\)/);
assert.doesNotMatch(html, /flockpal-pattern|cid:flockpal-background/);
assert.doesNotMatch(html, /48-hour|weights are overdue|data:image/);
for (const attachment of mail.attachments ?? []) {
assert.ok(html.includes(`cid:${attachment.cid}`));
assert.equal(attachment.contentDisposition, 'inline');
assert.ok(Buffer.isBuffer(attachment.content));
}
assert.equal((html.match(/<table\b/g) ?? []).length, (html.match(/<\/table>/g) ?? []).length);
assert.equal((html.match(/<td\b/g) ?? []).length, (html.match(/<\/td>/g) ?? []).length);
});
test('transactional layout omits optional portrait, action and reminder footer', async () => {
const mail = await buildEmailLayout({ eyebrow: 'Rescue status', headline: 'Flock update', contentHtml: '<p>Status changed</p>' });
assert.equal(mail.attachments?.length, 1);
assert.doesNotMatch(String(mail.html), /bird-portrait|<a |48-hour/);
});
-48
View File
@@ -1,48 +0,0 @@
import { readFile } from 'node:fs/promises';
import type { SendMailOptions } from 'nodemailer';
import sharp from 'sharp';
import { loadWeightReminderPortrait } from './birdPortrait.js';
export const escapeHtml = (value: string) => value.replace(/[&<>"']/g, char => ({
'&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;',
})[char]!);
const asset = (name: string) => new URL(`../../assets/${name}`, import.meta.url);
export const buildEmailLayout = async ({ eyebrow, headline, preheader = headline, contentHtml, action, footer, bird, backgroundUrl = process.env.EMAIL_BACKGROUND_URL || new URL('/email-background.png', process.env.FRONTEND_URL || 'http://localhost:3000').href }: {
eyebrow: string;
headline: string;
preheader?: string;
/** Trusted markup; escape all dynamic values before passing them. */
contentHtml: string;
action?: { url: string; label: string };
footer?: string;
backgroundUrl?: string;
bird?: { id: string; name: string; photo_data_url: string | null; photo_object_key: string | null };
}): Promise<Pick<SendMailOptions, 'html' | 'attachments'>> => ({
attachments: [
{ filename: 'flockpal-logo.png', cid: 'flockpal-logo', contentType: 'image/png', contentDisposition: 'inline', content: await sharp(await readFile(asset('flockpal-logo.png'))).resize({ width: 480 }).png().toBuffer() },
...(bird ? [{ filename: 'bird-portrait.jpg', cid: 'bird-portrait', contentType: 'image/jpeg', contentDisposition: 'inline' as const, content: await loadWeightReminderPortrait({ bird_id: bird.id, photo_data_url: bird.photo_data_url, photo_object_key: bird.photo_object_key }) }] : []),
],
html: `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"></head>
<body style="margin:0;padding:0;background-color:#fef5e7;">
<div style="display:none;max-height:0;overflow:hidden;mso-hide:all;">${escapeHtml(preheader)}</div>
<table role="presentation" width="100%" cellspacing="0" cellpadding="0" style="width:100%;background-color:#fef5e7;font-family:Arial,sans-serif;color:#1f2a2a;line-height:1.5;">
<tr><td align="center" background="${escapeHtml(backgroundUrl)}" style="padding:24px 12px;background-color:#fef5e7;background-image:url('${escapeHtml(backgroundUrl)}');background-position:center top;background-repeat:repeat;background-size:100% auto;">
<table role="presentation" width="100%" cellspacing="0" cellpadding="0" style="max-width:600px;background-color:#edf8ef;border:1px solid #d3e5d8;border-radius:24px;">
<tr><td align="center" style="padding:24px;border-bottom:1px solid #d3e5d8;">
<img src="cid:flockpal-logo" width="220" alt="FlockPal" style="display:block;width:220px;max-width:100%;height:auto;border:0;" />
</td></tr>
<tr><td style="padding:24px;">
<p style="margin:0 0 8px;font-size:12px;font-weight:bold;letter-spacing:1.5px;color:#238a5a;text-transform:uppercase;">${escapeHtml(eyebrow)}</p>
<h1 style="margin:0 0 12px;font-size:26px;line-height:1.2;word-break:break-word;">${escapeHtml(headline)}</h1>
${bird ? `<img src="cid:bird-portrait" width="76" height="76" alt="${escapeHtml(bird.name)}" style="display:block;border:0;border-radius:16px;margin:0 0 16px;" />` : ''}
${contentHtml}
${action ? `<table role="presentation" cellspacing="0" cellpadding="0" style="margin-top:24px;"><tr><td bgcolor="#238a5a" style="border-radius:24px;text-align:center;"><a href="${escapeHtml(action.url)}" style="display:inline-block;padding:13px 22px;border:1px solid #238a5a;border-radius:24px;color:#ffffff;font-size:16px;font-weight:bold;text-decoration:none;">${escapeHtml(action.label)}</a></td></tr></table>` : ''}
${footer ? `<p style="margin:20px 0 0;font-size:13px;color:#52645b;">${escapeHtml(footer)}</p>` : ''}
</td></tr>
</table>
<p style="margin:16px 0 0;color:#52645b;font-size:12px;">FlockPal · A little care, every day.</p>
</td></tr>
</table>
</body></html>`,
});
@@ -1,60 +0,0 @@
import assert from 'node:assert/strict';
import { readFile } from 'node:fs/promises';
import { test } from 'node:test';
import sharp from 'sharp';
import { buildWeightReminderEmail, loadWeightReminderPortrait } from './weightReminderEmail.js';
import type { WeightReminder } from '../reminders/weightReminders.js';
const bird: WeightReminder = {
bird_id: 'bird-1', workspace_id: 1, bird_name: 'Kiwi & <Peep>', species: 'Cockatiel',
workspace_name: 'Our <Flock>', activity_at: '2026-09-01T12:00:00Z', recipient: 'owner@example.test',
photo_data_url: null, photo_object_key: null,
};
test('branded grouped email embeds distinct portraits and escapes dynamic content', async () => {
const mail = await buildWeightReminderEmail([bird, { ...bird, bird_id: 'bird-2', bird_name: 'Yoda' }], 'https://flockpal.test/?a=1&b=2');
assert.equal(mail.attachments?.length, 3);
assert.deepEqual(mail.attachments?.map(a => a.cid), ['flockpal-logo', 'weight-bird-0', 'weight-bird-1']);
for (const attachment of mail.attachments ?? []) {
assert.equal(attachment.contentDisposition, 'inline');
assert.ok(Buffer.isBuffer(attachment.content));
assert.ok(String(mail.html).includes(`cid:${attachment.cid}`));
}
assert.match(String(mail.html), /Kiwi &amp; &lt;Peep&gt;/);
assert.match(String(mail.html), /Our &lt;Flock&gt;/);
assert.match(String(mail.html), /a=1&amp;b=2/);
assert.match(String(mail.text), /Kiwi & <Peep>/);
});
test('database portrait is resized and invalid photos fall back to the default', async () => {
const source = await readFile(new URL('../../assets/yoda.png', import.meta.url));
const photo = await loadWeightReminderPortrait({ ...bird, photo_data_url: `data:image/png;base64,${source.toString('base64')}` });
const metadata = await sharp(photo).metadata();
assert.equal(metadata.width, 192);
assert.equal(metadata.height, 192);
assert.equal(metadata.format, 'jpeg');
assert.deepEqual(await loadWeightReminderPortrait({ ...bird, photo_data_url: 'data:image/png;base64,broken' }), await loadWeightReminderPortrait(bird));
});
test('private S3 portrait is downloaded and embedded rather than linked', async (t) => {
const env = { IMAGE_STORAGE_PROVIDER: 's3', S3_ENDPOINT: 'https://storage.example.test', S3_REGION: 'us-east-1', S3_BUCKET: 'portraits', S3_ACCESS_KEY_ID: 'test', S3_SECRET_ACCESS_KEY: 'test' };
const previous = Object.fromEntries(Object.keys(env).map(key => [key, process.env[key]]));
Object.assign(process.env, env);
try {
const source = await readFile(new URL('../../assets/yoda.png', import.meta.url));
t.mock.method(globalThis, 'fetch', async (url: string) => {
assert.match(String(url), /private-bird.png/);
return new Response(source);
});
const photo = await loadWeightReminderPortrait({ ...bird, photo_object_key: 'private-bird.png' });
assert.equal((await sharp(photo).metadata()).width, 192);
t.mock.restoreAll();
t.mock.method(globalThis, 'fetch', async () => new Response('', { status: 404 }));
assert.deepEqual(await loadWeightReminderPortrait({ ...bird, photo_object_key: 'missing.png' }), await loadWeightReminderPortrait(bird));
} finally {
for (const [key, value] of Object.entries(previous)) {
if (value === undefined) delete process.env[key];
else process.env[key] = value;
}
}
});
-44
View File
@@ -1,44 +0,0 @@
import { buildEmailLayout, escapeHtml } from './emailLayout.js';
import type { SendMailOptions } from 'nodemailer';
import type { WeightReminder } from '../reminders/weightReminders.js';
import { loadWeightReminderPortrait } from './birdPortrait.js';
export { loadWeightReminderPortrait } from './birdPortrait.js';
export const buildWeightReminderEmail = async (
reminders: WeightReminder[],
frontendUrl: string,
loadPortrait = loadWeightReminderPortrait,
): Promise<Pick<SendMailOptions, 'subject' | 'text' | 'html' | 'attachments'>> => {
if (!reminders.length) throw new Error('A weight reminder email requires at least one bird');
const flock = reminders[0].workspace_name;
const attachments: NonNullable<SendMailOptions['attachments']> = [];
const rows: string[] = [];
for (const [index, bird] of reminders.entries()) {
const cid = `weight-bird-${index}`;
attachments.push({ filename: `${cid}.jpg`, cid, content: await loadPortrait(bird), contentType: 'image/jpeg', contentDisposition: 'inline' });
rows.push(`<tr>
<td width="88" style="padding:16px 12px 16px 0;border-bottom:1px solid #d3e5d8;vertical-align:middle;">
<img src="cid:${cid}" width="76" height="76" alt="${escapeHtml(bird.bird_name)}" style="display:block;border:0;border-radius:16px;" />
</td>
<td style="padding:16px 0;border-bottom:1px solid #d3e5d8;vertical-align:middle;word-break:break-word;">
<p style="margin:0 0 4px;font-size:18px;font-weight:bold;color:#1f2a2a;">${escapeHtml(bird.bird_name)}</p>
<p style="margin:0;font-size:14px;color:#52645b;">${escapeHtml(bird.species)}</p>
<p style="margin:6px 0 0;font-size:13px;color:#63562d;">Ready for a weight check</p>
</td>
</tr>`);
}
const layout = await buildEmailLayout({
eyebrow: 'Daily weight reminder',
headline: 'A little check-in for your flock',
preheader: `A little check-in for ${flock}: it's time to log your birds' weights.`,
contentHtml: `<p style="margin:0 0 16px;font-size:16px;">These birds in <strong>${escapeHtml(flock)}</strong> haven't had a new weight entry in at least 48 hours.</p><table role="presentation" width="100%" cellspacing="0" cellpadding="0" style="border-collapse:collapse;table-layout:fixed;">${rows.join('')}</table>`,
action: { url: frontendUrl, label: 'Record their weights' },
footer: "You'll receive a daily reminder while weights are overdue. A new weight entry restarts the 48-hour clock.",
});
return {
subject: `Weight reminders for ${flock}`,
text: `Daily weight reminder — ${flock}\n\nThese birds haven't had a new weight entry in at least 48 hours:\n\n${reminders.map(bird => `- ${bird.bird_name} (${bird.species})`).join('\n')}\n\nOpen FlockPal to record their weights: ${frontendUrl}\n\nYou'll receive a daily reminder while weights are overdue.`,
...layout,
attachments: [...(layout.attachments ?? []), ...attachments],
};
};
+54
View File
@@ -0,0 +1,54 @@
import { db } from './db/client.js';
import { closeBirdMilestoneReminderQueue, getBirdMilestoneReminderQueueCounts } from './queues/birdMilestoneReminderQueue.js';
const timeoutMs = Number(process.env.HEALTHCHECK_TIMEOUT_MS ?? 5_000);
const withTimeout = async <T>(operation: Promise<T>, label: string): Promise<T> => {
let timeout: NodeJS.Timeout | undefined;
try {
return await Promise.race([
operation,
new Promise<never>((_resolve, reject) => {
timeout = setTimeout(() => reject(new Error(`${label} timed out`)), timeoutMs);
}),
]);
} finally {
if (timeout) {
clearTimeout(timeout);
}
}
};
const checkHttp = async (path: string) => {
const port = process.env.PORT ?? '5000';
const response = await withTimeout(fetch(`http://127.0.0.1:${port}${path}`), path);
if (!response.ok) {
throw new Error(`${path} returned ${response.status}`);
}
};
const checkWorkerDependencies = async () => {
await withTimeout(db.query('SELECT 1'), 'postgres');
await withTimeout(getBirdMilestoneReminderQueueCounts(), 'redis');
};
const mode = process.argv[2] ?? 'api-ready';
try {
if (mode === 'api-live') {
await checkHttp('/api/health/live');
} else if (mode === 'api-ready') {
await checkHttp('/api/health/ready');
} else if (mode === 'worker') {
await checkWorkerDependencies();
} else {
throw new Error(`Unknown healthcheck mode: ${mode}`);
}
} catch (error) {
console.error(error instanceof Error ? error.message : error);
process.exitCode = 1;
} finally {
await Promise.allSettled([closeBirdMilestoneReminderQueue(), db.close()]);
}
@@ -40,3 +40,5 @@ export const closeAdoptionReportQueue = async () => {
await adoptionReportQueue.close();
await adoptionReportQueueEvents.close();
};
export const getAdoptionReportQueueCounts = () => adoptionReportQueue.getJobCounts('waiting', 'active', 'delayed', 'completed', 'failed');
-42
View File
@@ -1,42 +0,0 @@
import { Queue } from 'bullmq';
import { getReminderDate } from '../reminders/reminderDate.js';
import { redisConnection } from './redisConnection.js';
export const weightReminderQueueName = 'weight-reminders';
export const weightReminderQueue = new Queue(weightReminderQueueName, {
connection: redisConnection,
defaultJobOptions: {
attempts: 3,
backoff: { type: 'exponential', delay: 60_000 },
removeOnComplete: 100,
removeOnFail: 1000,
},
});
export const enqueueDailyWeightReminder = (now = new Date()) => {
const runDate = getReminderDate(now);
return weightReminderQueue.add('check-overdue-weights', { runDate }, {
jobId: `weight-reminders-${runDate}`,
});
};
export const startWeightReminderScheduler = async () => {
// Remove the previous five-minute schedule during upgrades and when disabled.
await weightReminderQueue.removeJobScheduler('weight-reminders');
if (process.env.WEIGHT_REMINDERS_ENABLED === 'false') return () => {};
await weightReminderQueue.setGlobalConcurrency(1);
let lastRunDate = '';
const runIfNeeded = async () => {
const now = new Date();
const runDate = getReminderDate(now);
if (lastRunDate === runDate) return;
await enqueueDailyWeightReminder(now);
lastRunDate = runDate;
};
const check = () => {
void runIfNeeded().catch(error => console.error('Weight reminder scheduler failed', error));
};
const startup = setTimeout(check, 15_000);
const interval = setInterval(check, 60 * 60_000);
return () => { clearTimeout(startup); clearInterval(interval); };
};
@@ -1,21 +0,0 @@
import assert from 'node:assert/strict';
import { test } from 'node:test';
import { getReminderDate } from './reminderDate.js';
test('daily reminder dates use the configured zone across midnight and DST', () => {
const previous = process.env.MILESTONE_REMINDER_TIME_ZONE;
try {
process.env.MILESTONE_REMINDER_TIME_ZONE = 'America/New_York';
assert.equal(getReminderDate(new Date('2026-09-06T03:59:59Z')), '2026-09-05');
assert.equal(getReminderDate(new Date('2026-09-06T04:00:00Z')), '2026-09-06');
assert.equal(getReminderDate(new Date('2026-03-08T06:59:59Z')), '2026-03-08');
assert.equal(getReminderDate(new Date('2026-03-08T07:00:00Z')), '2026-03-08');
assert.equal(getReminderDate(new Date('2026-11-01T05:30:00Z')), '2026-11-01');
assert.equal(getReminderDate(new Date('2026-11-01T06:30:00Z')), '2026-11-01');
process.env.MILESTONE_REMINDER_TIME_ZONE = 'UTC';
assert.equal(getReminderDate(new Date('2026-09-06T03:59:59Z')), '2026-09-06');
} finally {
if (previous === undefined) delete process.env.MILESTONE_REMINDER_TIME_ZONE;
else process.env.MILESTONE_REMINDER_TIME_ZONE = previous;
}
});
-5
View File
@@ -1,5 +0,0 @@
export const getReminderTimeZone = () => process.env.MILESTONE_REMINDER_TIME_ZONE?.trim() || 'America/New_York';
export const getReminderDate = (now = new Date()) => new Intl.DateTimeFormat('en-CA', {
timeZone: getReminderTimeZone(), year: 'numeric', month: '2-digit', day: '2-digit',
}).format(now);
@@ -1,61 +0,0 @@
import assert from 'node:assert/strict';
import { test } from 'node:test';
import { runWeightReminders, type WeightReminder } from './weightReminders.js';
const bird = (id: string, workspace = 1, recipient = 'owner@example.com'): WeightReminder => ({
species: 'Cockatiel', photo_data_url: null, photo_object_key: null,
bird_id: id, workspace_id: workspace, recipient,
bird_name: id, workspace_name: `Flock ${workspace}`, activity_at: '2026-09-01T12:00:00Z',
});
test('groups overdue birds into one email per flock and recipient', async () => {
const sent: WeightReminder[][] = [];
const finished: boolean[] = [];
const result = await runWeightReminders(async (birds) => { sent.push(birds); return true; }, {
list: async () => [bird('a'), bird('b'), bird('c', 2), bird('a', 1, 'caregiver@example.com')],
claim: async () => true,
finish: async (_token, delivered) => { finished.push(delivered); },
});
assert.deepEqual(sent.map((group) => group.map((item) => item.bird_id)), [['a', 'b'], ['c'], ['a']]);
assert.deepEqual(finished, [true, true, true, true]);
assert.equal(result.sent, 3);
});
test('omits birds whose claim was lost or whose weight changed', async () => {
const sent: WeightReminder[][] = [];
await runWeightReminders(async (birds) => { sent.push(birds); return true; }, {
list: async () => [bird('a'), bird('b')],
claim: async (reminder) => reminder.bird_id === 'b', finish: async () => {},
});
assert.deepEqual(sent.map((group) => group.map((item) => item.bird_id)), [['b']]);
});
test('does not email when all claims are unavailable', async () => {
await runWeightReminders(async () => { assert.fail('Unexpected email'); }, {
list: async () => [bird('a')], claim: async () => false, finish: async () => {},
});
});
test('missing SMTP releases all claims without recording delivery', async () => {
const finished: boolean[] = [];
const result = await runWeightReminders(async () => false, {
list: async () => [bird('a'), bird('b')], claim: async () => true,
finish: async (_token, delivered) => { finished.push(delivered); },
});
assert.deepEqual(finished, [false, false]);
assert.equal(result.sent, 0);
});
test('SMTP failure releases claims and still processes other flocks', async () => {
const finished: boolean[] = [];
const result = await runWeightReminders(async (birds) => {
if (birds[0].workspace_id === 1) throw new Error('SMTP unavailable');
return true;
}, {
list: async () => [bird('a'), bird('b'), bird('c', 2)], claim: async () => true,
finish: async (_token, delivered) => { finished.push(delivered); },
});
assert.deepEqual(finished, [false, false, true]);
assert.equal(result.sent, 1);
assert.equal(result.failed, 1);
});
-126
View File
@@ -1,126 +0,0 @@
import { getReminderTimeZone } from './reminderDate.js';
import { randomUUID } from 'node:crypto';
import { db } from '../db/client.js';
export type WeightReminder = {
bird_id: string;
workspace_id: number;
bird_name: string;
species: string;
photo_data_url: string | null;
photo_object_key: string | null;
workspace_name: string;
activity_at: string;
recipient: string;
};
// Use entry creation time: recorded_on is a date and cannot measure elapsed hours.
// Editing an existing entry does not reset the reminder clock.
export const listDueWeightReminders = async () => {
const result = await db.query<WeightReminder>(`
WITH activity AS (
SELECT birds.id AS bird_id, birds.workspace_id, birds.name AS bird_name,
workspaces.name AS workspace_name,
GREATEST(birds.created_at, COALESCE(MAX(weight_records.created_at), birds.created_at)) AS activity_at
FROM birds
JOIN workspaces ON workspaces.id = birds.workspace_id
LEFT JOIN weight_records ON weight_records.bird_id = birds.id
WHERE birds.memorialized_at IS NULL
GROUP BY birds.id, workspaces.name
), recipients AS (
SELECT DISTINCT workspace_id, LOWER(TRIM(users.email)) AS recipient
FROM workspace_members
JOIN users ON users.id = workspace_members.user_id
WHERE accepted_at IS NOT NULL
AND role IN ('owner', 'assistant', 'caregiver')
)
SELECT activity.bird_id, activity.workspace_id, activity.bird_name, activity.workspace_name,
activity.activity_at::text, recipients.recipient, birds.species, birds.photo_data_url, birds.photo_object_key
FROM activity
JOIN recipients USING (workspace_id)
JOIN birds ON birds.id = activity.bird_id
WHERE activity_at <= CURRENT_TIMESTAMP - INTERVAL '48 hours'
AND recipients.recipient <> ''
AND NOT EXISTS (
SELECT 1 FROM weight_reminder_deliveries d
WHERE d.bird_id = activity.bird_id AND d.workspace_id = activity.workspace_id
AND d.activity_at = activity.activity_at AND d.recipient = recipients.recipient
AND ((d.delivered_at AT TIME ZONE $1)::date >= (CURRENT_TIMESTAMP AT TIME ZONE $1)::date
OR (d.delivered_at IS NULL AND d.claimed_at > CURRENT_TIMESTAMP - INTERVAL '15 minutes'))
)
ORDER BY activity.workspace_id, activity.bird_id, recipients.recipient
`, [getReminderTimeZone()]);
return result.rows;
};
export const claimWeightReminder = async (reminder: WeightReminder, token: string) => {
const result = await db.query(`
INSERT INTO weight_reminder_deliveries (bird_id, workspace_id, activity_at, recipient, claim_token)
SELECT $1, $2, $3, $4, $5
WHERE EXISTS (
SELECT 1 FROM birds
WHERE id = $1 AND workspace_id = $2 AND memorialized_at IS NULL
AND GREATEST(created_at, COALESCE((SELECT MAX(created_at) FROM weight_records WHERE bird_id = $1), created_at)) = $3::timestamptz
)
ON CONFLICT (bird_id, workspace_id, activity_at, recipient) DO UPDATE
SET claim_token = EXCLUDED.claim_token, claimed_at = CURRENT_TIMESTAMP, delivered_at = NULL
WHERE (weight_reminder_deliveries.delivered_at AT TIME ZONE $6)::date < (CURRENT_TIMESTAMP AT TIME ZONE $6)::date
OR (weight_reminder_deliveries.delivered_at IS NULL
AND weight_reminder_deliveries.claimed_at <= CURRENT_TIMESTAMP - INTERVAL '15 minutes')
RETURNING bird_id
`, [reminder.bird_id, reminder.workspace_id, reminder.activity_at, reminder.recipient, token, getReminderTimeZone()]);
return Boolean(result.rowCount);
};
export const finishWeightReminder = async (token: string, delivered: boolean) => {
if (delivered) {
await db.query('UPDATE weight_reminder_deliveries SET delivered_at = CURRENT_TIMESTAMP WHERE claim_token = $1', [token]);
} else {
await db.query('DELETE FROM weight_reminder_deliveries WHERE claim_token = $1 AND delivered_at IS NULL', [token]);
}
};
type Dependencies = {
list: typeof listDueWeightReminders;
claim: typeof claimWeightReminder;
finish: typeof finishWeightReminder;
};
export const runWeightReminders = async (
send: (reminders: WeightReminder[]) => Promise<boolean>,
dependencies: Dependencies = { list: listDueWeightReminders, claim: claimWeightReminder, finish: finishWeightReminder },
) => {
const reminders = await dependencies.list();
const result = { checked: reminders.length, sent: 0, skipped: 0, failed: 0 };
const groups = new Map<string, WeightReminder[]>();
for (const reminder of reminders) {
const key = JSON.stringify([reminder.workspace_id, reminder.recipient]);
groups.set(key, [...(groups.get(key) ?? []), reminder]);
}
for (const group of groups.values()) {
const claimed: { reminder: WeightReminder; token: string }[] = [];
let delivered = false;
try {
for (const reminder of group) {
const token = randomUUID();
if (await dependencies.claim(reminder, token)) claimed.push({ reminder, token });
else result.skipped += 1;
}
if (!claimed.length) continue;
delivered = await send(claimed.map(({ reminder }) => reminder));
for (const { token } of claimed) await dependencies.finish(token, delivered);
if (delivered) result.sent += 1;
else result.skipped += claimed.length;
} catch (error) {
result.failed += 1;
// Keep leases if SMTP accepted the email but saving delivery failed.
if (!delivered) {
for (const { token } of claimed) {
await dependencies.finish(token, false).catch((cleanupError) => console.error('Weight reminder claim cleanup failed', cleanupError));
}
}
console.error(`Weight reminder failed for flock ${group[0].workspace_id}`, error);
}
}
return result;
};
+34 -22
View File
@@ -61,17 +61,11 @@ const formatWeight = (value: string | number | null) => {
};
const genderLabel = (value: string) => {
if (value === 'female_dna') {
return 'Female (DNA confirmed)';
}
if (value === 'male_dna') {
return 'Male (DNA confirmed)';
}
if (value === 'female') {
return 'Female (assumed)';
return 'Female';
}
if (value === 'male') {
return 'Male (assumed)';
return 'Male';
}
return 'Unknown';
};
@@ -103,10 +97,26 @@ const fitText = (doc: PDFKit.PDFDocument, text: string, x: number, y: number, wi
return doc.y;
};
const drawFact = (doc: PDFKit.PDFDocument, label: string, value: string, x: number, y: number, width: number) => {
doc.roundedRect(x, y, width, 43, 6).fillAndStroke(colors.panel, colors.border);
const measureFactHeight = (doc: PDFKit.PDFDocument, value: string, width: number, minHeight = 43) => {
doc.font('Helvetica-Bold').fontSize(10);
const textHeight = doc.heightOfString(value, {
width: width - 16,
lineGap: 1,
});
return Math.max(minHeight, 27 + Math.min(textHeight, 38));
};
const drawFact = (doc: PDFKit.PDFDocument, label: string, value: string, x: number, y: number, width: number, height?: number) => {
const cardHeight = height ?? measureFactHeight(doc, value, width);
doc.roundedRect(x, y, width, cardHeight, 6).fillAndStroke(colors.panel, colors.border);
doc.fillColor(colors.muted).fontSize(7).font('Helvetica-Bold').text(label.toUpperCase(), x + 8, y + 8, { width: width - 16 });
doc.fillColor(colors.ink).fontSize(10).font('Helvetica-Bold').text(value, x + 8, y + 21, { width: width - 16, ellipsis: true });
doc.fillColor(colors.ink).fontSize(10).font('Helvetica-Bold').text(value, x + 8, y + 21, {
width: width - 16,
height: cardHeight - 27,
lineGap: 1,
ellipsis: true,
});
return cardHeight;
};
const drawTextCard = (doc: PDFKit.PDFDocument, label: string, value: string, x: number, y: number, width: number, height = 58) => {
@@ -144,8 +154,12 @@ const drawSimpleWeightChart = (doc: PDFKit.PDFDocument, weights: WeightRow[], bi
}
const latestDate = new Date(`${plottedWeights[plottedWeights.length - 1].recorded_on.slice(0, 10)}T00:00:00Z`);
const earliestDate = new Date(`${plottedWeights[0].recorded_on.slice(0, 10)}T00:00:00Z`);
const startDate = new Date(latestDate);
startDate.setUTCDate(startDate.getUTCDate() - 29);
startDate.setUTCDate(startDate.getUTCDate() - 13);
if (earliestDate > startDate) {
startDate.setTime(earliestDate.getTime());
}
const visibleWeights = plottedWeights.filter((entry) => {
const recordedOn = new Date(`${entry.recorded_on.slice(0, 10)}T00:00:00Z`);
return recordedOn >= startDate && recordedOn <= latestDate;
@@ -357,16 +371,14 @@ export const renderAdoptionReportPdf = async ({
y = page.margin;
}
y = drawSectionTitle(doc, 'Veterinary Clinic Info', y);
const vetFacts = [
['Clinic name', bird.vet_clinic_name || 'Not recorded'],
['Clinic address', bird.vet_clinic_address || 'Not recorded'],
['Account #', bird.vet_account_number || 'Not recorded'],
['Dr. name', bird.vet_doctor_name || 'Not recorded'],
];
vetFacts.forEach(([label, value], index) => {
drawFact(doc, label, value, page.margin + (index % 2) * (factWidth + factGap), y + Math.floor(index / 2) * 50, factWidth);
});
y += Math.ceil(vetFacts.length / 2) * 50 + 8;
drawFact(doc, 'Clinic name', bird.vet_clinic_name || 'Not recorded', page.margin, y, factWidth);
drawFact(doc, 'Account #', bird.vet_account_number || 'Not recorded', page.margin + factWidth + factGap, y, factWidth);
y += 50;
const clinicAddressHeight = measureFactHeight(doc, bird.vet_clinic_address || 'Not recorded', contentWidth, 58);
drawFact(doc, 'Clinic address', bird.vet_clinic_address || 'Not recorded', page.margin, y, contentWidth, clinicAddressHeight);
y += clinicAddressHeight + 7;
drawFact(doc, 'Dr. name', bird.vet_doctor_name || 'Not recorded', page.margin, y, factWidth);
y += 50;
y = drawSectionTitle(doc, 'Vet Visit History', y);
y = drawTable(
+5 -1
View File
@@ -1,8 +1,12 @@
import path from 'path';
import sharp from 'sharp';
import {
getBirdById,
listVetVisitsForBird,
listWeightsForBird,
} from '../repositories/birdRepository.js';
import { listFlockNotes } from '../repositories/auditRepository.js';
import { getBirdById, listVetVisitsForBird, listWeightsForBird } from '../repositories/birdRepository.js';
import { getS3ImageStorageConfig } from '../storage/imageStorageConfig.js';
import { getSignedS3ObjectUrl } from '../storage/s3Client.js';
import type { BirdRow } from '../types.js';
+36 -55
View File
@@ -6,7 +6,10 @@ import {
createBird,
createPendingBirdTransfer,
getBirdById,
getOpenBirdTransferCode,
getOpenBirdTransferCodeForBird,
listWeightsForBird,
markBirdTransferCodeCompleted,
transferBirdToWorkspace,
} from './birdRepository.js';
import { mockDb } from '../test/mockDb.js';
@@ -188,46 +191,6 @@ test('completePendingBirdTransfersForOwner moves pending birds and marks complet
],
},
{ rowCount: 1, rows: [] },
{
rowCount: 1,
rows: [
{
workspace_id: 10,
workspace_name: 'Original Flock',
owner_email: 'sender@example.com',
},
],
},
{
rowCount: 1,
rows: [
{
workspace_id: 22,
workspace_name: 'Receiving Flock',
owner_email: 'receiver@example.com',
},
],
},
{
rowCount: 1,
rows: [
{
id: 'timeline-1',
bird_id: 'bird-1',
event_type: 'transferred',
from_workspace_id: 10,
to_workspace_id: 22,
from_workspace_name: 'Original Flock',
to_workspace_name: 'Receiving Flock',
from_owner_email: 'sender@example.com',
to_owner_email: 'receiver@example.com',
location_label: 'Receiving Flock',
location_details: null,
created_by_user_id: 'user-1',
created_at: '2026-04-15T00:00:00.000Z',
},
],
},
);
const result = await completePendingBirdTransfersForOwner('receiver@example.com', 22);
@@ -237,19 +200,37 @@ test('completePendingBirdTransfersForOwner moves pending birds and marks complet
assert.deepEqual(calls[1].params, ['bird-1', 10, 22]);
assert.deepEqual(calls[2].params, ['transfer-1', 22]);
assert.match(calls[2].text, /completed_at = CURRENT_TIMESTAMP/);
assert.deepEqual(calls[5].params, [
'bird-1',
'transferred',
10,
22,
'Original Flock',
'Receiving Flock',
'sender@example.com',
'receiver@example.com',
null,
null,
null,
'user-1',
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('getOpenBirdTransferCodeForBird ignores consumed codes', async () => {
const { calls } = mockDb({ rowCount: 0, rows: [] });
const transferCode = await getOpenBirdTransferCodeForBird('bird-1', 10);
assert.equal(transferCode, null);
assert.deepEqual(calls[0].params, ['bird-1', 10]);
assert.match(calls[0].text, /completed_at IS NULL/);
assert.match(calls[0].text, /revoked_at IS NULL/);
});
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/);
});
+40 -205
View File
@@ -5,8 +5,6 @@ import type {
BirdMilestoneReminderDeliveryRow,
BirdMilestoneReminderType,
BirdRow,
BirdTimelineEventRow,
BirdTimelineEventType,
BirdTransferCodeRow,
LostBirdMatchRow,
MedicationAdministrationRow,
@@ -28,8 +26,6 @@ const birdSelectFields = `
birds.motivators,
birds.demotivators,
birds.favorite_snack,
birds.location_label,
birds.location_details,
birds.vet_clinic_name,
birds.vet_clinic_address,
birds.vet_account_number,
@@ -55,34 +51,6 @@ const birdSelectFields = `
latest.recorded_on::text AS latest_recorded_on
`;
type WorkspaceTimelineSnapshot = {
workspace_id: number;
workspace_name: string;
owner_email: string | null;
};
const getWorkspaceTimelineSnapshot = async (workspaceId: number) => {
const result = await db.query<WorkspaceTimelineSnapshot>(
`SELECT
workspaces.id AS workspace_id,
workspaces.name AS workspace_name,
COALESCE(workspaces.billing_email, owner_member.invite_email, owner_member.email) AS owner_email
FROM workspaces
LEFT JOIN LATERAL (
SELECT invite_email, email
FROM workspace_members
WHERE workspace_members.workspace_id = workspaces.id
AND workspace_members.role = 'owner'
ORDER BY accepted_at DESC NULLS LAST, created_at ASC
LIMIT 1
) owner_member ON TRUE
WHERE workspaces.id = $1`,
[workspaceId],
);
return result.rows[0] ?? null;
};
export const getBirdById = async (birdId: string, workspaceId: number) => {
const result = await db.query<BirdRow>(
`SELECT
@@ -166,102 +134,6 @@ export const listMemorializedBirds = async (workspaceId: number) => {
return result.rows;
};
export const createBirdTimelineEvent = async ({
birdId,
eventType,
fromWorkspaceId,
toWorkspaceId,
locationLabel,
locationDetails,
note,
eventDate,
createdByUserId,
}: {
birdId: string;
eventType: BirdTimelineEventType;
fromWorkspaceId?: number | null;
toWorkspaceId?: number | null;
locationLabel?: string | null;
locationDetails?: Record<string, unknown> | null;
note?: string | null;
eventDate?: string | null;
createdByUserId?: string | null;
}) => {
const [fromWorkspace, toWorkspace] = await Promise.all([
fromWorkspaceId ? getWorkspaceTimelineSnapshot(fromWorkspaceId) : Promise.resolve(null),
toWorkspaceId ? getWorkspaceTimelineSnapshot(toWorkspaceId) : Promise.resolve(null),
]);
const result = await db.query<BirdTimelineEventRow>(
`INSERT INTO bird_timeline_events (
bird_id,
event_type,
from_workspace_id,
to_workspace_id,
from_workspace_name,
to_workspace_name,
from_owner_email,
to_owner_email,
location_label,
note,
event_date,
created_by_user_id,
location_details
)
VALUES (
$1,
$2,
$3,
$4,
$5::varchar(160),
$6::varchar(160),
$7::varchar(320),
$8::varchar(320),
COALESCE($9::varchar(160), $6::varchar(160), $5::varchar(160)),
$10,
COALESCE($11::date, CURRENT_DATE),
$12,
$13
)
RETURNING id, bird_id, event_type, from_workspace_id, to_workspace_id, from_workspace_name, to_workspace_name, from_owner_email, to_owner_email, location_label, location_details, note, event_date::text, created_by_user_id, created_at`,
[
birdId,
eventType,
fromWorkspaceId ?? null,
toWorkspaceId ?? null,
fromWorkspace?.workspace_name ?? null,
toWorkspace?.workspace_name ?? null,
fromWorkspace?.owner_email ?? null,
toWorkspace?.owner_email ?? null,
locationLabel ?? null,
note ?? null,
eventDate ?? null,
createdByUserId ?? null,
locationDetails ?? null,
],
);
return result.rows[0] ?? null;
};
export const listBirdTimelineEvents = async (birdId: string, workspaceId: number) => {
const result = await db.query<BirdTimelineEventRow>(
`SELECT id, bird_id, event_type, from_workspace_id, to_workspace_id, from_workspace_name, to_workspace_name, from_owner_email, to_owner_email, location_label, location_details, note, event_date::text, created_by_user_id, created_at
FROM bird_timeline_events
WHERE bird_id = $1
AND EXISTS (
SELECT 1
FROM birds
WHERE birds.id = bird_timeline_events.bird_id
AND birds.workspace_id = $2
)
ORDER BY event_date DESC, created_at DESC`,
[birdId, workspaceId],
);
return result.rows;
};
export const findBirdsByBandId = async (tagId: string) => {
const result = await db.query<LostBirdMatchRow>(
`SELECT
@@ -495,8 +367,6 @@ export const createBird = async ({
motivators,
demotivators,
favoriteSnack,
locationLabel = null,
locationDetails = null,
vetClinicName = null,
vetClinicAddress = null,
vetAccountNumber = null,
@@ -522,8 +392,6 @@ export const createBird = async ({
motivators: string | null;
demotivators: string | null;
favoriteSnack: string | null;
locationLabel?: string | null;
locationDetails?: Record<string, unknown> | null;
vetClinicName?: string | null;
vetClinicAddress?: string | null;
vetAccountNumber?: string | null;
@@ -542,9 +410,9 @@ export const createBird = async ({
publicProfileEnabled?: boolean;
}) => {
const result = await db.query<BirdRow>(
`INSERT INTO birds (id, workspace_id, name, tag_id, species, motivators, demotivators, favorite_snack, location_label, location_details, vet_clinic_name, vet_clinic_address, vet_account_number, vet_doctor_name, gender, date_of_birth, gotcha_day, chart_color, photo_data_url, photo_object_key, photo_content_type, photo_updated_at, notify_on_dob, notify_on_gotcha_day, public_profile_code, public_profile_enabled)
VALUES (COALESCE($1::uuid, gen_random_uuid()), $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20, $21, $22, $23, $24, $25, $26)
RETURNING id, workspace_id, name, tag_id, species, motivators, demotivators, favorite_snack, location_label, location_details, vet_clinic_name, vet_clinic_address, vet_account_number, vet_doctor_name, gender, date_of_birth::text, gotcha_day::text, chart_color, photo_data_url, photo_object_key, photo_content_type, photo_updated_at, notify_on_dob, notify_on_gotcha_day, public_profile_code, public_profile_enabled, memorialized_at, memorialized_on::text, memorial_note, notify_on_memorial_day, created_at, NULL::text AS latest_weight_grams, NULL::text AS latest_recorded_on`,
`INSERT INTO birds (id, workspace_id, name, tag_id, species, motivators, demotivators, favorite_snack, vet_clinic_name, vet_clinic_address, vet_account_number, vet_doctor_name, gender, date_of_birth, gotcha_day, chart_color, photo_data_url, photo_object_key, photo_content_type, photo_updated_at, notify_on_dob, notify_on_gotcha_day, public_profile_code, public_profile_enabled)
VALUES (COALESCE($1::uuid, gen_random_uuid()), $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20, $21, $22, $23, $24)
RETURNING id, workspace_id, name, tag_id, species, motivators, demotivators, favorite_snack, vet_clinic_name, vet_clinic_address, vet_account_number, vet_doctor_name, gender, date_of_birth::text, gotcha_day::text, chart_color, photo_data_url, photo_object_key, photo_content_type, photo_updated_at, notify_on_dob, notify_on_gotcha_day, public_profile_code, public_profile_enabled, memorialized_at, memorialized_on::text, memorial_note, notify_on_memorial_day, created_at, NULL::text AS latest_weight_grams, NULL::text AS latest_recorded_on`,
[
birdId ?? null,
workspaceId,
@@ -554,8 +422,6 @@ export const createBird = async ({
motivators,
demotivators,
favoriteSnack,
locationLabel,
locationDetails,
vetClinicName,
vetClinicAddress,
vetAccountNumber,
@@ -587,8 +453,6 @@ export const updateBird = async ({
motivators,
demotivators,
favoriteSnack,
locationLabel,
locationDetails,
vetClinicName,
vetClinicAddress,
vetAccountNumber,
@@ -614,8 +478,6 @@ export const updateBird = async ({
motivators: string | null;
demotivators: string | null;
favoriteSnack: string | null;
locationLabel: string | null;
locationDetails?: Record<string, unknown> | null;
vetClinicName: string | null;
vetClinicAddress: string | null;
vetAccountNumber: string | null;
@@ -641,28 +503,26 @@ export const updateBird = async ({
motivators = $5,
demotivators = $6,
favorite_snack = $7,
location_label = $8,
vet_clinic_name = $9,
vet_clinic_address = $10,
vet_account_number = $11,
vet_doctor_name = $12,
gender = $13,
date_of_birth = $14,
gotcha_day = $15,
chart_color = $16,
photo_data_url = $17,
photo_object_key = $18,
photo_content_type = $19,
photo_updated_at = $20,
notify_on_dob = $21,
notify_on_gotcha_day = $22,
public_profile_code = $23,
public_profile_enabled = $24,
location_details = $25
vet_clinic_name = $8,
vet_clinic_address = $9,
vet_account_number = $10,
vet_doctor_name = $11,
gender = $12,
date_of_birth = $13,
gotcha_day = $14,
chart_color = $15,
photo_data_url = $16,
photo_object_key = $17,
photo_content_type = $18,
photo_updated_at = $19,
notify_on_dob = $20,
notify_on_gotcha_day = $21,
public_profile_code = $22,
public_profile_enabled = $23
WHERE id = $1
AND workspace_id = $26
AND workspace_id = $24
AND memorialized_at IS NULL
RETURNING id, workspace_id, name, tag_id, species, motivators, demotivators, favorite_snack, location_label, location_details, vet_clinic_name, vet_clinic_address, vet_account_number, vet_doctor_name, gender, date_of_birth::text, gotcha_day::text, chart_color, photo_data_url, photo_object_key, photo_content_type, photo_updated_at, notify_on_dob, notify_on_gotcha_day, public_profile_code, public_profile_enabled, memorialized_at, memorialized_on::text, memorial_note, notify_on_memorial_day, created_at,
RETURNING id, workspace_id, name, tag_id, species, motivators, demotivators, favorite_snack, vet_clinic_name, vet_clinic_address, vet_account_number, vet_doctor_name, gender, date_of_birth::text, gotcha_day::text, chart_color, photo_data_url, photo_object_key, photo_content_type, photo_updated_at, notify_on_dob, notify_on_gotcha_day, public_profile_code, public_profile_enabled, memorialized_at, memorialized_on::text, memorial_note, notify_on_memorial_day, created_at,
(
SELECT weight_grams::text
FROM weight_records
@@ -685,7 +545,6 @@ export const updateBird = async ({
motivators,
demotivators,
favoriteSnack,
locationLabel,
vetClinicName,
vetClinicAddress,
vetAccountNumber,
@@ -702,7 +561,6 @@ export const updateBird = async ({
notifyOnGotchaDay,
publicProfileCode,
publicProfileEnabled,
locationDetails ?? null,
workspaceId,
],
);
@@ -732,7 +590,7 @@ export const memorializeBird = async ({
WHERE id = $1
AND workspace_id = $2
AND memorialized_at IS NULL
RETURNING id, workspace_id, name, tag_id, species, motivators, demotivators, favorite_snack, location_label, location_details, vet_clinic_name, vet_clinic_address, vet_account_number, vet_doctor_name, gender, date_of_birth::text, gotcha_day::text, chart_color, photo_data_url, photo_object_key, photo_content_type, photo_updated_at, notify_on_dob, notify_on_gotcha_day, public_profile_code, public_profile_enabled, memorialized_at, memorialized_on::text, memorial_note, notify_on_memorial_day, created_at,
RETURNING id, workspace_id, name, tag_id, species, motivators, demotivators, favorite_snack, vet_clinic_name, vet_clinic_address, vet_account_number, vet_doctor_name, gender, date_of_birth::text, gotcha_day::text, chart_color, photo_data_url, photo_object_key, photo_content_type, photo_updated_at, notify_on_dob, notify_on_gotcha_day, public_profile_code, public_profile_enabled, memorialized_at, memorialized_on::text, memorial_note, notify_on_memorial_day, created_at,
(
SELECT weight_grams::text
FROM weight_records
@@ -768,7 +626,7 @@ export const updateMemorialReminderPreference = async ({
WHERE id = $1
AND workspace_id = $2
AND memorialized_at IS NOT NULL
RETURNING id, workspace_id, name, tag_id, species, motivators, demotivators, favorite_snack, location_label, location_details, vet_clinic_name, vet_clinic_address, vet_account_number, vet_doctor_name, gender, date_of_birth::text, gotcha_day::text, chart_color, photo_data_url, photo_object_key, photo_content_type, photo_updated_at, notify_on_dob, notify_on_gotcha_day, public_profile_code, public_profile_enabled, memorialized_at, memorialized_on::text, memorial_note, notify_on_memorial_day, created_at,
RETURNING id, workspace_id, name, tag_id, species, motivators, demotivators, favorite_snack, vet_clinic_name, vet_clinic_address, vet_account_number, vet_doctor_name, gender, date_of_birth::text, gotcha_day::text, chart_color, photo_data_url, photo_object_key, photo_content_type, photo_updated_at, notify_on_dob, notify_on_gotcha_day, public_profile_code, public_profile_enabled, memorialized_at, memorialized_on::text, memorial_note, notify_on_memorial_day, created_at,
(
SELECT weight_grams::text
FROM weight_records
@@ -808,7 +666,7 @@ export const transferBirdToWorkspace = async (birdId: string, sourceWorkspaceId:
WHERE id = $1
AND workspace_id = $2
AND memorialized_at IS NULL
RETURNING id, workspace_id, name, tag_id, species, motivators, demotivators, favorite_snack, location_label, location_details, vet_clinic_name, vet_clinic_address, vet_account_number, vet_doctor_name, gender, date_of_birth::text, gotcha_day::text, chart_color, photo_data_url, photo_object_key, photo_content_type, photo_updated_at, notify_on_dob, notify_on_gotcha_day, public_profile_code, public_profile_enabled, memorialized_at, memorialized_on::text, memorial_note, notify_on_memorial_day, created_at,
RETURNING id, workspace_id, name, tag_id, species, motivators, demotivators, favorite_snack, vet_clinic_name, vet_clinic_address, vet_account_number, vet_doctor_name, gender, date_of_birth::text, gotcha_day::text, chart_color, photo_data_url, photo_object_key, photo_content_type, photo_updated_at, notify_on_dob, notify_on_gotcha_day, public_profile_code, public_profile_enabled, memorialized_at, memorialized_on::text, memorial_note, notify_on_memorial_day, created_at,
(
SELECT weight_grams::text
FROM weight_records
@@ -904,17 +762,6 @@ export const completePendingBirdTransfersForOwner = async (ownerEmail: string, t
}
await markPendingBirdTransferCompleted(transfer.id, targetWorkspaceId);
try {
await createBirdTimelineEvent({
birdId: bird.id,
eventType: 'transferred',
fromWorkspaceId: transfer.source_workspace_id,
toWorkspaceId: targetWorkspaceId,
createdByUserId: transfer.requested_by_user_id,
});
} catch (timelineError) {
console.error('Unable to write bird timeline event', timelineError);
}
completed += 1;
} catch (error) {
failed += 1;
@@ -962,6 +809,22 @@ export const createBirdTransferCode = async ({
return result.rows[0] ?? null;
};
export const getOpenBirdTransferCodeForBird = async (birdId: string, sourceWorkspaceId: number) => {
const result = await db.query<BirdTransferCodeRow>(
`SELECT id, code, bird_id, source_workspace_id, requested_by_user_id, completed_at::text, completed_workspace_id, revoked_at::text, created_at
FROM bird_transfer_codes
WHERE bird_id = $1
AND source_workspace_id = $2
AND completed_at IS NULL
AND revoked_at IS NULL
ORDER BY created_at DESC
LIMIT 1`,
[birdId, sourceWorkspaceId],
);
return result.rows[0] ?? null;
};
export const getOpenBirdTransferCode = async (code: string) => {
const result = await db.query<
BirdRow & {
@@ -1048,34 +911,6 @@ export const createWeightForBird = async (birdId: string, weightGrams: number, r
return result.rows[0] ?? null;
};
export const updateWeightForBird = async (
weightId: string,
birdId: string,
weightGrams: number,
recordedOn: string,
notes: string | null,
) => {
const result = await db.query<WeightRow>(
`UPDATE weight_records
SET weight_grams = $3,
recorded_on = $4,
notes = $5
WHERE id = $1
AND bird_id = $2
AND id IN (
SELECT recent.id
FROM weight_records recent
WHERE recent.bird_id = $2
ORDER BY recent.recorded_on DESC, recent.created_at DESC
LIMIT 3
)
RETURNING id, bird_id, weight_grams, recorded_on::text, notes`,
[weightId, birdId, weightGrams, recordedOn, notes],
);
return result.rows[0] ?? null;
};
export const listVetVisitsForBird = async (birdId: string, workspaceId: number) => {
const result = await db.query<VetVisitRow>(
`SELECT id, bird_id, visited_on::text, clinic_name, reason, notes
@@ -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);
};
@@ -531,10 +531,6 @@ test('getPlatformAdminSummary counts memorialized birds separately', async () =>
rescue_birds: 5,
pending_rescues: 1,
daily_users: 2,
household_basic_subscriptions: 2,
household_plus_subscriptions: 1,
household_macaw_subscriptions: 0,
household_hyacinth_macaw_subscriptions: 1,
},
],
});
@@ -547,7 +543,4 @@ test('getPlatformAdminSummary counts memorialized birds separately', async () =>
assert.match(calls[0].text, /memorialized_at IS NOT NULL/);
assert.match(calls[0].text, /rescue_birds/);
assert.match(calls[0].text, /workspaces\.workspace_type = 'rescue'/);
assert.equal(summary?.household_basic_subscriptions, 2);
assert.match(calls[0].text, /billing_plan = 'household_basic'/);
assert.match(calls[0].text, /subscription_status IN \('active', 'trialing'\)/);
});
@@ -605,10 +605,6 @@ export const getPlatformAdminSummary = async () => {
rescue_birds: number;
pending_rescues: number;
daily_users: number;
household_basic_subscriptions: number;
household_plus_subscriptions: number;
household_macaw_subscriptions: number;
household_hyacinth_macaw_subscriptions: number;
}>(
`SELECT
(SELECT COUNT(*)::int FROM birds) AS total_birds,
@@ -618,11 +614,7 @@ export const getPlatformAdminSummary = async () => {
(SELECT COUNT(*)::int FROM workspaces WHERE workspace_type = 'rescue') AS rescue_workspaces,
(SELECT COUNT(*)::int FROM birds INNER JOIN workspaces ON workspaces.id = birds.workspace_id WHERE workspaces.workspace_type = 'rescue') AS rescue_birds,
(SELECT COUNT(*)::int FROM workspaces WHERE workspace_type = 'rescue' AND rescue_verification_status = 'pending') AS pending_rescues,
(SELECT COUNT(DISTINCT user_id)::int FROM auth_sessions WHERE created_at >= CURRENT_DATE) AS daily_users,
(SELECT COUNT(*)::int FROM workspaces WHERE billing_plan = 'household_basic' AND subscription_status IN ('active', 'trialing')) AS household_basic_subscriptions,
(SELECT COUNT(*)::int FROM workspaces WHERE billing_plan = 'household_plus' AND subscription_status IN ('active', 'trialing')) AS household_plus_subscriptions,
(SELECT COUNT(*)::int FROM workspaces WHERE billing_plan = 'household_macaw' AND subscription_status IN ('active', 'trialing')) AS household_macaw_subscriptions,
(SELECT COUNT(*)::int FROM workspaces WHERE billing_plan = 'household_hyacinth_macaw' AND subscription_status IN ('active', 'trialing')) AS household_hyacinth_macaw_subscriptions`,
(SELECT COUNT(DISTINCT user_id)::int FROM auth_sessions WHERE created_at >= CURRENT_DATE) AS daily_users`,
);
return result.rows[0];
+1 -52
View File
@@ -6,45 +6,16 @@ export type SubscriptionStatus = 'active' | 'trialing' | 'past_due' | 'canceled'
export type RescueVerificationStatus = 'not_required' | 'pending' | 'approved' | 'rejected';
export type ProviderKey = 'google' | 'microsoft' | 'apple';
export type IntegrationTokenScope = 'read_only' | 'read_write';
export type BirdGender = 'unknown' | 'male' | 'female' | 'male_dna' | 'female_dna';
export type BirdGender = 'unknown' | 'male' | 'female';
export type UserRow = {
id: string;
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;
@@ -130,8 +101,6 @@ export type BirdRow = {
motivators: string | null;
demotivators: string | null;
favorite_snack: string | null;
location_label: string | null;
location_details: Record<string, unknown> | null;
vet_clinic_name: string | null;
vet_clinic_address: string | null;
vet_account_number: string | null;
@@ -205,26 +174,6 @@ export type BirdTransferCodeRow = {
created_at: string;
};
export type BirdTimelineEventType = 'profile_created' | 'transferred' | 'location_updated' | 'owner_changed' | 'manual_note';
export type BirdTimelineEventRow = {
id: string;
bird_id: string;
event_type: BirdTimelineEventType;
from_workspace_id: number | null;
to_workspace_id: number | null;
from_workspace_name: string | null;
to_workspace_name: string | null;
from_owner_email: string | null;
to_owner_email: string | null;
location_label: string | null;
location_details: Record<string, unknown> | null;
note: string | null;
event_date: string;
created_by_user_id: string | null;
created_at: string;
};
export type WeightRow = {
id: string;
bird_id: string;
-18
View File
@@ -1,11 +1,8 @@
import { runWeightReminders } from './reminders/weightReminders.js';
import { weightReminderQueue, weightReminderQueueName, startWeightReminderScheduler } from './queues/weightReminderQueue.js';
import { Worker } from 'bullmq';
import { ensureSchema } from './db/schema.js';
import { db } from './db/client.js';
import {
sendWeightReminderNotification,
runBirdMilestoneReminders,
runMedicationReminders,
startBirdMilestoneReminderScheduler,
@@ -32,8 +29,6 @@ import {
import { redisConnection } from './queues/redisConnection.js';
import { renderAdoptionReportForBird } from './reports/adoptionReportJob.js';
let stopWeightReminderScheduler: (() => void) | undefined;
let weightReminderWorker: Worker | null = null;
let birdMilestoneWorker: Worker<BirdMilestoneReminderJobData, BirdMilestoneReminderJobResult> | null = null;
let medicationReminderWorker: Worker<MedicationReminderJobData, MedicationReminderJobResult> | null = null;
let adoptionReportWorker: Worker<AdoptionReportJobData, AdoptionReportJobResult> | null = null;
@@ -98,16 +93,6 @@ const startWorker = async () => {
console.error(`Adoption report job failed: id=${job?.id ?? 'unknown'}, birdId=${job?.data.birdId ?? 'unknown'}`, error);
});
weightReminderWorker = new Worker(weightReminderQueueName, async () => {
if (process.env.WEIGHT_REMINDERS_ENABLED === 'false') return;
const result = await runWeightReminders(sendWeightReminderNotification);
console.log('Weight reminder job completed', result);
return result;
}, { connection: redisConnection, concurrency: 1 });
weightReminderWorker.on('failed', (job, error) => {
console.error(`Weight reminder job failed: id=${job?.id ?? 'unknown'}`, error);
});
stopWeightReminderScheduler = await startWeightReminderScheduler();
startBirdMilestoneReminderScheduler();
startMedicationReminderScheduler();
console.log('FlockPal worker started.');
@@ -115,9 +100,6 @@ const startWorker = async () => {
const shutdown = async (signal: string) => {
console.log(`FlockPal worker received ${signal}; shutting down.`);
stopWeightReminderScheduler?.();
await weightReminderWorker?.close();
await weightReminderQueue.close();
await birdMilestoneWorker?.close();
await medicationReminderWorker?.close();
await adoptionReportWorker?.close();
@@ -1,26 +0,0 @@
services:
postgres:
image: postgres:16-alpine
environment:
POSTGRES_USER: flockpal_test
POSTGRES_PASSWORD: isolated_test_password
POSTGRES_DB: flockpal_weight_test
ports:
- '127.0.0.1:25432:5432'
tmpfs:
- /var/lib/postgresql/data
healthcheck:
test: ['CMD-SHELL', 'pg_isready -U flockpal_test -d flockpal_weight_test']
interval: 1s
timeout: 3s
retries: 30
redis:
image: redis:7-alpine
command: ['redis-server', '--save', '', '--appendonly', 'no']
ports:
- '127.0.0.1:26379:6379'
mail:
image: axllent/mailpit:latest
ports:
- '127.0.0.1:21025:1025'
- '127.0.0.1:28025:8025'
@@ -1,182 +0,0 @@
// Run only against disposable local Postgres, Redis, and Mailpit services.
// See docs/WEIGHT_REMINDER_TESTING.md for the isolated Compose setup.
import assert from 'node:assert/strict';
import { readFile } from 'node:fs/promises';
import { randomUUID } from 'node:crypto';
import { spawn } from 'node:child_process';
import { once } from 'node:events';
import { fileURLToPath } from 'node:url';
Object.assign(process.env, {
POSTGRES_HOST: '127.0.0.1', POSTGRES_PORT: '25432', POSTGRES_DB: 'flockpal_weight_test',
POSTGRES_USER: 'flockpal_test', POSTGRES_PASSWORD: 'isolated_test_password',
REDIS_URL: 'redis://127.0.0.1:26379',
SMTP_HOST: '127.0.0.1', SMTP_PORT: '21025', SMTP_SECURE: 'false',
SMTP_USER: '', SMTP_PASS: '', SMTP_FROM_EMAIL: 'reminders@flockpal.test', SMTP_FROM_NAME: 'FlockPal Test',
FRONTEND_URL: 'http://flockpal.test', MILESTONE_REMINDERS_ENABLED: 'false',
MEDICATION_REMINDERS_ENABLED: 'false', WEIGHT_REMINDERS_ENABLED: 'true',
MILESTONE_REMINDER_TIME_ZONE: 'America/New_York',
});
const { db } = await import('../dist/db/client.js');
const { ensureSchema } = await import('../dist/db/schema.js');
const { getReminderDate } = await import('../dist/reminders/reminderDate.js');
const { listDueWeightReminders, claimWeightReminder, finishWeightReminder } = await import('../dist/reminders/weightReminders.js');
const { weightReminderQueue, startWeightReminderScheduler, enqueueDailyWeightReminder } = await import('../dist/queues/weightReminderQueue.js');
const workers = [];
let logs = '';
const poll = async (check, label) => {
const deadline = Date.now() + 30_000;
while (Date.now() < deadline) {
if (await check()) return;
await new Promise(resolve => setTimeout(resolve, 100));
}
throw new Error(`Timed out: ${label}\n${logs}`);
};
const messages = async () => (await (await fetch('http://127.0.0.1:28025/api/v1/messages')).json()).messages;
const startWorker = () => {
const child = spawn(process.execPath, [fileURLToPath(new URL('../dist/worker.js', import.meta.url))], {
cwd: '/tmp', env: process.env, stdio: ['ignore', 'pipe', 'pipe'],
});
child.stdout.on('data', data => { logs += data; });
child.stderr.on('data', data => { logs += data; });
workers.push(child);
};
const stopWorkers = async () => {
const exits = workers.map(child => once(child, 'exit'));
for (const child of workers) child.kill('SIGTERM');
await Promise.all(exits);
workers.length = 0;
};
const drain = async () => {
await poll(async () => {
const counts = await weightReminderQueue.getJobCounts('active', 'waiting');
return !counts.active && !counts.waiting;
}, 'queue drain');
};
const runJob = async () => {
const job = await weightReminderQueue.add('integration-check', {});
await poll(async () => ['completed', 'failed'].includes(await job.getState()), 'manual job');
assert.equal(await job.getState(), 'completed');
return (await weightReminderQueue.getJob(job.id)).returnvalue;
};
try {
await ensureSchema();
await ensureSchema();
assert.equal((await db.query('SELECT COUNT(*)::int AS count FROM birds')).rows[0].count, 0, 'Use a fresh disposable database');
assert.equal((await messages()).length, 0, 'Use a fresh email catcher');
await db.query("INSERT INTO workspaces (id, name) VALUES (101, 'Test Flock'), (102, 'Other Flock')");
const ids = {};
for (const [role, accepted] of [['owner', true], ['assistant', true], ['caregiver', true], ['viewer', true], ['pending', false]]) {
const id = randomUUID(); ids[role] = id;
await db.query('INSERT INTO users (id, email, name) VALUES ($1, $2, $3)', [id, `${role}@example.test`, role]);
await db.query(`INSERT INTO workspace_members (workspace_id, user_id, invite_email, name, role, accepted_at)
VALUES (101, $1, $2, $3, $4, ${accepted ? 'CURRENT_TIMESTAMP' : 'NULL'})`, [id, `${role}@example.test`, role, role === 'pending' ? 'caregiver' : role]);
}
await db.query("INSERT INTO workspace_members (workspace_id, user_id, invite_email, name, role, accepted_at) VALUES (102, $1, 'owner@example.test', 'owner', 'owner', CURRENT_TIMESTAMP)", [ids.owner]);
const birds = {};
for (const [name, age, memorial, workspace] of [
['Kiwi & <Peep>', 72, false, 101], ['Boundary', 48, false, 101],
['No weights', null, false, 101], ['Recent', 47, false, 101],
['Memorial', 72, true, 101], ['Other bird', 72, false, 102],
]) {
const id = randomUUID(); birds[name] = id;
await db.query(`INSERT INTO birds (id, workspace_id, name, species, created_at, memorialized_at)
VALUES ($1, $2, $3, 'Cockatiel', CURRENT_TIMESTAMP - INTERVAL '100 hours', ${memorial ? 'CURRENT_TIMESTAMP' : 'NULL'})`, [id, workspace, name]);
if (age !== null) await db.query("INSERT INTO weight_records (bird_id, weight_grams, recorded_on, created_at) VALUES ($1, 90, CURRENT_DATE - 3, CURRENT_TIMESTAMP - $2 * INTERVAL '1 hour')", [id, age]);
}
const portrait = await readFile(new URL('../assets/yoda.png', import.meta.url));
await db.query('UPDATE birds SET photo_data_url = $1 WHERE id = $2', [`data:image/png;base64,${portrait.toString('base64')}`, birds['Kiwi & <Peep>']]);
const due = await listDueWeightReminders();
assert.equal(due.length, 10);
assert.deepEqual(new Set(due.map(b => b.recipient)), new Set(['owner@example.test', 'assistant@example.test', 'caregiver@example.test']));
const candidate = due[0];
const tokens = [randomUUID(), randomUUID()];
const claims = await Promise.all(tokens.map(token => claimWeightReminder(candidate, token)));
assert.equal(claims.filter(Boolean).length, 1, 'Only one concurrent claim wins');
await finishWeightReminder(tokens[claims.indexOf(true)], false);
console.log('PASS: schema initialization is repeatable; eligibility, roles, and concurrent claims');
// Simulate the schedule present before upgrading to daily reminders.
await weightReminderQueue.upsertJobScheduler('weight-reminders', { every: 300_000 }, { name: 'check-overdue-weights', data: {} });
startWorker(); startWorker();
await poll(async () => (await messages()).length === 4, 'initial grouped emails');
await drain();
const initial = await messages();
const bodies = await Promise.all(initial.map(async message => (await fetch(`http://127.0.0.1:28025/api/v1/message/${message.ID}`)).json()));
for (const body of bodies) {
if (body.Subject === 'Weight reminders for Test Flock') {
for (const name of ['Kiwi & <Peep>', 'Boundary', 'No weights']) assert.ok(body.Text.includes(name));
assert.ok(body.HTML.includes('Kiwi &amp; &lt;Peep&gt;'));
assert.ok(!body.Text.includes('Memorial'));
assert.ok(!body.Text.includes('Recent'));
assert.ok(!body.Text.includes('Other bird'));
} else {
assert.equal(body.Subject, 'Weight reminders for Other Flock');
assert.ok(body.Text.includes('Other bird'));
assert.ok(!body.Text.includes('Boundary'));
}
assert.equal(body.To.length, 1);
const inline = body.Inline ?? [];
assert.ok(inline.some(attachment => attachment.ContentID === 'flockpal-logo'));
assert.equal(inline.filter(attachment => attachment.ContentID.startsWith('weight-bird-')).length, body.Subject === 'Weight reminders for Test Flock' ? 3 : 1);
assert.ok(body.HTML.includes('Daily weight reminder'));
assert.ok(body.HTML.includes('Record their weights'));
}
assert.equal((await weightReminderQueue.getJobSchedulers()).length, 0);
await poll(async () => Boolean(await weightReminderQueue.getJob(`weight-reminders-${getReminderDate()}`)), 'startup daily scheduler');
const dailyJobs = await Promise.all([enqueueDailyWeightReminder(), enqueueDailyWeightReminder()]);
assert.equal(dailyJobs[0].id, dailyJobs[1].id);
await drain();
assert.equal(await weightReminderQueue.getGlobalConcurrency(), 1);
assert.equal((await runJob()).sent, 0);
assert.equal((await messages()).length, 4);
console.log('PASS: two real workers, one daily job, legacy schedule removed, grouped SMTP delivery, escaping, flock isolation, no immediate duplicates');
await db.query("UPDATE weight_reminder_deliveries SET delivered_at = CURRENT_TIMESTAMP");
assert.equal((await runJob()).sent, 0);
await db.query("UPDATE weight_reminder_deliveries SET delivered_at = ((CURRENT_TIMESTAMP AT TIME ZONE 'America/New_York')::date::timestamp AT TIME ZONE 'America/New_York') - INTERVAL '1 second'");
assert.equal((await runJob()).sent, 4);
assert.equal((await messages()).length, 8);
await db.query("INSERT INTO weight_records (bird_id, weight_grams, recorded_on) VALUES ($1, 91, CURRENT_DATE)", [birds.Boundary]);
await db.query("UPDATE weight_reminder_deliveries SET delivered_at = CURRENT_TIMESTAMP - INTERVAL '49 hours'");
assert.ok((await listDueWeightReminders()).every(b => b.bird_id !== birds.Boundary));
assert.equal((await runJob()).sent, 4);
console.log('PASS: no repeat on the same local date, daily repeat, fresh weight resets eligibility');
await stopWorkers();
await db.query("UPDATE weight_reminder_deliveries SET delivered_at = CURRENT_TIMESTAMP - INTERVAL '49 hours'");
const beforeFailures = (await messages()).length;
process.env.SMTP_HOST = '';
startWorker();
assert.equal((await runJob()).sent, 0);
assert.equal((await listDueWeightReminders()).length, 7);
await stopWorkers();
process.env.SMTP_HOST = '127.0.0.1';
process.env.SMTP_PORT = '21026'; // No SMTP listener: exercise a real refused connection.
startWorker();
const failed = await runJob();
assert.equal(failed.failed, 4);
assert.equal(failed.sent, 0);
assert.equal((await listDueWeightReminders()).length, 7);
assert.equal((await messages()).length, beforeFailures);
await stopWorkers();
process.env.SMTP_PORT = '21025';
startWorker();
await runJob();
await poll(async () => (await messages()).length === beforeFailures + 4, 'delivery after SMTP recovery');
await drain();
await stopWorkers();
console.log('PASS: missing SMTP, real SMTP connection failure, released claims, successful retry');
process.env.WEIGHT_REMINDERS_ENABLED = 'false';
await startWeightReminderScheduler();
assert.equal((await weightReminderQueue.getJobSchedulers()).length, 0);
console.log('PASS: graceful worker shutdown and disabled scheduler removal');
console.log('All Postgres / Redis / SMTP integration checks passed.');
} finally {
for (const child of workers) child.kill('SIGKILL');
await weightReminderQueue.close();
await db.close();
}
+18 -4
View File
@@ -55,12 +55,10 @@ services:
PHOTO_DELIVERY_MODE: ${PHOTO_DELIVERY_MODE:-proxy}
FRONTEND_URL: ${FRONTEND_URL:?set FRONTEND_URL for production}
BACKEND_URL: ${BACKEND_URL:?set BACKEND_URL for production}
MAPBOX_ACCESS_TOKEN: ${MAPBOX_ACCESS_TOKEN:-}
ADMIN_EMAILS: ${ADMIN_EMAILS:-}
RESCUE_STATUS_NOTIFICATION_EMAIL: ${RESCUE_STATUS_NOTIFICATION_EMAIL:-appadmin@flockpal.app}
RESCUE_ONBOARDING_WEBHOOK_URL: ${RESCUE_ONBOARDING_WEBHOOK_URL:-https://n8n.blaishome.online/webhook/395cd538-5e0d-4e89-8070-9e66f571b7ee}
MILESTONE_REMINDERS_ENABLED: ${MILESTONE_REMINDERS_ENABLED:-true}
WEIGHT_REMINDERS_ENABLED: ${WEIGHT_REMINDERS_ENABLED:-true}
MEDICATION_REMINDERS_ENABLED: ${MEDICATION_REMINDERS_ENABLED:-true}
MILESTONE_REMINDER_TIME_ZONE: ${MILESTONE_REMINDER_TIME_ZONE:-America/New_York}
GOOGLE_CLIENT_ID: ${GOOGLE_CLIENT_ID:-}
@@ -98,6 +96,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
@@ -138,12 +142,10 @@ services:
PHOTO_DELIVERY_MODE: ${PHOTO_DELIVERY_MODE:-proxy}
FRONTEND_URL: ${FRONTEND_URL:?set FRONTEND_URL for production}
BACKEND_URL: ${BACKEND_URL:?set BACKEND_URL for production}
MAPBOX_ACCESS_TOKEN: ${MAPBOX_ACCESS_TOKEN:-}
ADMIN_EMAILS: ${ADMIN_EMAILS:-}
RESCUE_STATUS_NOTIFICATION_EMAIL: ${RESCUE_STATUS_NOTIFICATION_EMAIL:-appadmin@flockpal.app}
RESCUE_ONBOARDING_WEBHOOK_URL: ${RESCUE_ONBOARDING_WEBHOOK_URL:-https://n8n.blaishome.online/webhook/395cd538-5e0d-4e89-8070-9e66f571b7ee}
MILESTONE_REMINDERS_ENABLED: ${MILESTONE_REMINDERS_ENABLED:-true}
WEIGHT_REMINDERS_ENABLED: ${WEIGHT_REMINDERS_ENABLED:-true}
MEDICATION_REMINDERS_ENABLED: ${MEDICATION_REMINDERS_ENABLED:-true}
MILESTONE_REMINDER_TIME_ZONE: ${MILESTONE_REMINDER_TIME_ZONE:-America/New_York}
SMTP_HOST: ${SMTP_HOST:-}
@@ -158,6 +160,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 +177,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
+1 -5
View File
@@ -53,12 +53,10 @@ services:
PHOTO_DELIVERY_MODE: ${PHOTO_DELIVERY_MODE:-proxy}
FRONTEND_URL: ${FRONTEND_URL:-http://localhost:3000}
BACKEND_URL: ${BACKEND_URL:-http://localhost:5000}
MAPBOX_ACCESS_TOKEN: ${MAPBOX_ACCESS_TOKEN:-}
ADMIN_EMAILS: ${ADMIN_EMAILS:-}
RESCUE_STATUS_NOTIFICATION_EMAIL: ${RESCUE_STATUS_NOTIFICATION_EMAIL:-appadmin@flockpal.app}
RESCUE_ONBOARDING_WEBHOOK_URL: ${RESCUE_ONBOARDING_WEBHOOK_URL:-https://n8n.blaishome.online/webhook/395cd538-5e0d-4e89-8070-9e66f571b7ee}
MILESTONE_REMINDERS_ENABLED: ${MILESTONE_REMINDERS_ENABLED:-true}
WEIGHT_REMINDERS_ENABLED: ${WEIGHT_REMINDERS_ENABLED:-true}
MEDICATION_REMINDERS_ENABLED: ${MEDICATION_REMINDERS_ENABLED:-true}
MILESTONE_REMINDER_TIME_ZONE: ${MILESTONE_REMINDER_TIME_ZONE:-America/New_York}
GOOGLE_CLIENT_ID: ${GOOGLE_CLIENT_ID:-}
@@ -131,12 +129,10 @@ services:
PHOTO_DELIVERY_MODE: ${PHOTO_DELIVERY_MODE:-proxy}
FRONTEND_URL: ${FRONTEND_URL:-http://localhost:3000}
BACKEND_URL: ${BACKEND_URL:-http://localhost:5000}
MAPBOX_ACCESS_TOKEN: ${MAPBOX_ACCESS_TOKEN:-}
ADMIN_EMAILS: ${ADMIN_EMAILS:-}
RESCUE_STATUS_NOTIFICATION_EMAIL: ${RESCUE_STATUS_NOTIFICATION_EMAIL:-appadmin@flockpal.app}
RESCUE_ONBOARDING_WEBHOOK_URL: ${RESCUE_ONBOARDING_WEBHOOK_URL:-https://n8n.blaishome.online/webhook/395cd538-5e0d-4e89-8070-9e66f571b7ee}
MILESTONE_REMINDERS_ENABLED: ${MILESTONE_REMINDERS_ENABLED:-true}
WEIGHT_REMINDERS_ENABLED: ${WEIGHT_REMINDERS_ENABLED:-true}
MEDICATION_REMINDERS_ENABLED: ${MEDICATION_REMINDERS_ENABLED:-true}
MILESTONE_REMINDER_TIME_ZONE: ${MILESTONE_REMINDER_TIME_ZONE:-America/New_York}
SMTP_HOST: ${SMTP_HOST:-}
@@ -164,7 +160,7 @@ services:
dockerfile: Dockerfile.dev
container_name: flockpal-frontend
environment:
VITE_API_BASE_URL: ${VITE_API_BASE_URL:-/api}
VITE_API_BASE_URL: ${VITE_API_BASE_URL:-http://localhost:5000/api}
depends_on:
- backend
ports:
+38 -5
View File
@@ -212,7 +212,7 @@ Role requirements are called out per endpoint below. If the signed-in member lac
"vetClinicAddress": "123 Feather Lane, Raleigh, NC",
"vetAccountNumber": "FP-1001",
"vetDoctorName": "Dr. Rivera",
"gender": "female_dna",
"gender": "female",
"dateOfBirth": "2023-05-10",
"gotchaDay": "2023-08-21",
"chartColor": "#cb3a35",
@@ -299,7 +299,7 @@ Role requirements are called out per endpoint below. If the signed-in member lac
- Dates use `YYYY-MM-DD`
- `workspaceType` is `standard` or `rescue`
- member `role` is `owner`, `assistant`, `caregiver`, or `viewer`
- bird `gender` is `unknown`, `male`, `female`, `male_dna`, or `female_dna`; `male` and `female` indicate assumed sex
- bird `gender` is `unknown`, `male`, or `female`
- bird `chartColor` must be a `#RRGGBB` hex color
- `photoDataUrl` must be a base64 `data:image/...` URL
- `weightGrams` must be a positive number up to `10000`
@@ -319,14 +319,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`
@@ -801,7 +834,7 @@ Request body:
"vetClinicAddress": "123 Feather Lane, Raleigh, NC",
"vetAccountNumber": "FP-1001",
"vetDoctorName": "Dr. Rivera",
"gender": "female_dna",
"gender": "female",
"dateOfBirth": "2023-05-10",
"gotchaDay": "2023-08-21",
"chartColor": "#cb3a35",
-34
View File
@@ -1,34 +0,0 @@
# Weight reminder tests
From the repository root, run the unit tests and builds:
```bash
npm ci --prefix backend
npm ci --prefix frontend
npm test --prefix backend
npm run build --prefix backend
npm run build --prefix frontend
```
The integration test uses real Postgres 16, Redis 7, two worker processes, and
Mailpit to capture SMTP messages locally. It requires Docker and free localhost
ports 25432, 26379, 21025, and 28025. Port 21026 must remain unused for the SMTP
failure check. Test addresses use `.test`; Mailpit does not relay mail externally.
```bash
docker compose -p flockpal-weight-test -f backend/test-integration/compose.weight-reminders.yml up -d --wait
node backend/test-integration/weightReminders.mjs
docker compose -p flockpal-weight-test -f backend/test-integration/compose.weight-reminders.yml down --volumes
```
Always run the last command when finished, including after a failed test. Start
fresh containers for each run. Postgres data is disposable and held in tmpfs.
The test overrides database, Redis, and SMTP environment variables to use only
these local services. It does not use the application's configured SMTP account.
Coverage includes repeatable schema initialization, overdue and recent weights,
birds without weights, memorial exclusions, accepted care roles, concurrent
claims, one daily job across two workers, removal of the old five-minute schedule, grouped emails, embedded branding and portraits, HTML escaping, flock
isolation, daily repeats, fresh weight resets, SMTP failures and recovery,
worker shutdown, and disabling the scheduler. Repeat timing is tested by aging
delivery timestamps rather than waiting two days.
-1
View File
@@ -7,7 +7,6 @@ RUN npm ci
COPY tsconfig*.json ./
COPY vite.config.ts ./
COPY index.html ./
COPY public ./public
COPY src ./src
RUN npm run build
-1
View File
@@ -5,7 +5,6 @@ RUN npm install
COPY tsconfig*.json ./
COPY vite.config.ts ./
COPY index.html ./
COPY public ./public
COPY src ./src
EXPOSE 3000
CMD ["npm", "run", "dev", "--", "--host"]
+6
View File
@@ -12,6 +12,12 @@ server {
add_header X-Frame-Options "SAMEORIGIN" always;
add_header Permissions-Policy "camera=(), microphone=(), geolocation=()" always;
location = /healthz {
access_log off;
add_header Content-Type text/plain;
return 200 "ok\n";
}
location / {
try_files $uri $uri/ /index.html;
}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 237 KiB

+694 -1692
View File
File diff suppressed because it is too large Load Diff
+15 -1037
View File
File diff suppressed because it is too large Load Diff
-6
View File
@@ -5,11 +5,5 @@ export default defineConfig({
plugins: [react()],
server: {
port: 3000,
proxy: {
'/api': {
target: 'http://backend:5000',
changeOrigin: true,
},
},
},
});