Compare commits
117
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
fc541f024d | ||
|
|
b5f875e077 | ||
|
|
3237cd7601 | ||
|
|
b1b89ad334 | ||
|
|
856753b012 | ||
|
|
5abc7f6174 | ||
|
|
b4254a68fa | ||
|
|
3d38093c9f | ||
|
|
c1ca4891fc | ||
|
|
7406d00687 | ||
|
|
6654ba4a55 | ||
|
|
ecad447d60 | ||
|
|
3ba6410972 | ||
|
|
a6eac3009d | ||
|
|
737a84a8b8 | ||
|
|
18fd76dc1f | ||
|
|
f627157a14 | ||
|
|
35bd87b8b5 | ||
|
|
14bc1c30a0 | ||
|
|
d03672fcdd | ||
|
|
46e07336ef | ||
|
|
bcaa8c4464 | ||
|
|
84d850a1ba | ||
|
|
0dfacc0d17 | ||
|
|
7ef20ab0fb | ||
|
|
9ddd85b5c4 | ||
|
|
a988d9662b | ||
|
|
4a43a450f3 | ||
|
|
56068e02a3 | ||
|
|
46605d8717 | ||
|
|
8f1144de1a | ||
|
|
53b75588a2 | ||
|
|
1849ecd73b | ||
|
|
53b7d34520 | ||
|
|
f65a4bed24 | ||
|
|
1140be8f32 | ||
|
|
4d3ab0b143 | ||
|
|
1e98d55cb5 | ||
|
|
454adc6f5e | ||
|
|
cc4a2382c6 | ||
|
|
ae8c4326b5 | ||
|
|
5735bb7735 | ||
|
|
88ff06237e | ||
|
|
fbb13561b0 | ||
|
|
b15861c856 | ||
|
|
2aeaa119f7 | ||
|
|
36690c0174 | ||
|
|
b76ad35c07 | ||
|
|
6918b55a58 | ||
|
|
49f1713e26 | ||
|
|
480bbe8fc7 | ||
|
|
bb589e3489 | ||
|
|
c3bec15c63 | ||
|
|
c9fa7e4246 | ||
|
|
0411ec5175 | ||
|
|
7b7171c109 | ||
|
|
c02bb4d6d8 | ||
|
|
603b4eee4d | ||
|
|
52008f5b43 | ||
|
|
5b57cdd6bf | ||
|
|
60eadf0847 | ||
|
|
682ccfd41f | ||
|
|
979a17132d | ||
|
|
cadbdc2a7f | ||
|
|
8e2f789e9b | ||
|
|
7e2d06c50b | ||
|
|
c2d518f864 | ||
|
|
c3297b5915 | ||
|
|
41dda33310 | ||
|
|
c98a5a2863 | ||
|
|
6c9017c3dc | ||
|
|
59c6b19ad6 | ||
|
|
aa1a4cf6ff | ||
|
|
5f0fad3cbb | ||
|
|
545fae59b2 | ||
|
|
6b11a73579 | ||
|
|
1f26255ebd | ||
|
|
14cdfe603d | ||
|
|
d5bb87910e | ||
|
|
d748d2db21 | ||
|
|
3053e3bef5 | ||
|
|
095c91e56d | ||
|
|
f2017068d5 | ||
|
|
c9702495a3 | ||
|
|
6ade13a8be | ||
|
|
e965cb55ef | ||
|
|
505a9b8496 | ||
|
|
c6dc5b22b8 | ||
|
|
d2763744eb | ||
|
|
841d0a9669 | ||
|
|
b4f6193395 | ||
|
|
9ee46e53e0 | ||
|
|
f16e88e2f0 | ||
|
|
016bc187d4 | ||
|
|
104f01f75d | ||
|
|
613b2c941c | ||
|
|
3ab3f48f19 | ||
|
|
d9822e6626 | ||
|
|
9e92e1212a | ||
|
|
96bc76ef0d | ||
|
|
fe4e69ceb5 | ||
|
|
c09e7f63ce | ||
|
|
306e3a8c85 | ||
|
|
568aee3e70 | ||
|
|
a502966293 | ||
|
|
b7186528c5 | ||
|
|
49d75f34be | ||
|
|
df3fcbf885 | ||
|
|
4715306d14 | ||
|
|
62afc94f2f | ||
|
|
e6211d7f5e | ||
|
|
cf3cd96384 | ||
|
|
38dcb7f49b | ||
|
|
1c0d57299d | ||
|
|
f2c506ec16 | ||
|
|
7514c7c306 | ||
|
|
0db90aab45 |
No files matched your search
@@ -0,0 +1,16 @@
|
||||
# CodeGraph data files
|
||||
# These are local to each machine and should not be committed
|
||||
|
||||
# Database
|
||||
*.db
|
||||
*.db-wal
|
||||
*.db-shm
|
||||
|
||||
# Cache
|
||||
cache/
|
||||
|
||||
# Logs
|
||||
*.log
|
||||
|
||||
# Hook markers
|
||||
.dirty
|
||||
+14
-3
@@ -14,6 +14,7 @@ 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
|
||||
@@ -29,9 +30,19 @@ STRIPE_PRICE_HOUSEHOLD_CONURE_YEARLY=
|
||||
STRIPE_PRICE_HOUSEHOLD_INDIANRINGNECK=
|
||||
STRIPE_PRICE_HOUSEHOLD_INDIANRINGNECK_MONTHLY=
|
||||
STRIPE_PRICE_HOUSEHOLD_INDIANRINGNECK_YEARLY=
|
||||
STRIPE_PRICE_HOUSEHOLD_MACAW=
|
||||
STRIPE_PRICE_HOUSEHOLD_MACAW_MONTHLY=
|
||||
STRIPE_PRICE_HOUSEHOLD_MACAW_YEARLY=
|
||||
STRIPE_PRICE_HOUSEHOLD_AFRICAN_GREY=
|
||||
STRIPE_PRICE_HOUSEHOLD_AFRICAN_GREY_MONTHLY=
|
||||
STRIPE_PRICE_HOUSEHOLD_AFRICAN_GREY_YEARLY=
|
||||
STRIPE_PRICE_HOUSEHOLD_HYACINTH_MACAW=
|
||||
STRIPE_PRICE_HOUSEHOLD_HYACINTH_MACAW_MONTHLY=
|
||||
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=
|
||||
@@ -0,0 +1,140 @@
|
||||
name: Deploy
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
- dev
|
||||
- develop
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
deploy-dev:
|
||||
if: ${{ github.event_name == 'push' && (github.ref_name == 'dev' || github.ref_name == 'develop') }}
|
||||
runs-on: ubuntu-latest
|
||||
container:
|
||||
volumes:
|
||||
- /docker/FlockPal-dev:/docker/FlockPal-dev
|
||||
steps:
|
||||
- name: Update dev checkout
|
||||
run: |
|
||||
set -e
|
||||
cd /docker/FlockPal-dev
|
||||
git fetch --all --prune
|
||||
git reset --hard "origin/${{ github.ref_name }}"
|
||||
git clean -fd
|
||||
|
||||
- name: Validate backend
|
||||
run: |
|
||||
set -e
|
||||
cd /docker/FlockPal-dev
|
||||
docker run --rm -v "$PWD/backend:/src:ro" -w /tmp/app node:22-alpine sh -lc "cp -a /src/. /tmp/app && npm ci && npm run build && npm test"
|
||||
|
||||
- name: Validate frontend
|
||||
run: |
|
||||
set -e
|
||||
cd /docker/FlockPal-dev
|
||||
docker run --rm -v "$PWD/frontend:/src:ro" -w /tmp/app node:22-alpine sh -lc "cp -a /src/. /tmp/app && npm ci && npm run build"
|
||||
|
||||
- name: Validate dev compose config
|
||||
run: |
|
||||
set -e
|
||||
cd /docker/FlockPal-dev
|
||||
docker compose -f docker-compose.dev.yaml config --quiet
|
||||
|
||||
- name: Deploy dev
|
||||
run: |
|
||||
set -e
|
||||
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 }}
|
||||
DEPLOY_ENVIRONMENT: dev
|
||||
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_LABEL="SUCCESS"
|
||||
else
|
||||
STATUS_LABEL="FAILED"
|
||||
fi
|
||||
|
||||
curl --fail --show-error --silent \
|
||||
-H "Content-Type: application/json" \
|
||||
-d "{\"content\":\"[${STATUS_LABEL}] FlockPal ${DEPLOY_ENVIRONMENT} deploy completed with status: ${JOB_STATUS}\\nBranch: ${{ github.ref_name }}\\nCommit: ${{ github.sha }}\\nRun: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}\"}" \
|
||||
"$DISCORD_WEBHOOK_URL" || echo "Discord notification failed."
|
||||
|
||||
deploy-prod:
|
||||
if: ${{ github.event_name == 'workflow_dispatch' || (github.event_name == 'push' && github.ref_name == 'main') }}
|
||||
runs-on: ubuntu-latest
|
||||
container:
|
||||
volumes:
|
||||
- /docker/FlockPal:/docker/FlockPal
|
||||
steps:
|
||||
- name: Update prod checkout
|
||||
run: |
|
||||
set -e
|
||||
cd /docker/FlockPal
|
||||
git fetch --all --prune
|
||||
git reset --hard "origin/${{ github.ref_name }}"
|
||||
git clean -fd
|
||||
|
||||
- name: Validate backend
|
||||
run: |
|
||||
set -e
|
||||
cd /docker/FlockPal
|
||||
docker run --rm -v "$PWD/backend:/src:ro" -w /tmp/app node:22-alpine sh -lc "cp -a /src/. /tmp/app && npm ci && npm run build && npm test"
|
||||
|
||||
- name: Validate frontend
|
||||
run: |
|
||||
set -e
|
||||
cd /docker/FlockPal
|
||||
docker run --rm -v "$PWD/frontend:/src:ro" -w /tmp/app node:22-alpine sh -lc "cp -a /src/. /tmp/app && npm ci && npm run build"
|
||||
|
||||
- name: Validate prod compose config
|
||||
run: |
|
||||
set -e
|
||||
cd /docker/FlockPal
|
||||
docker compose -f docker-compose.prod.yml config --quiet
|
||||
|
||||
- name: Deploy prod
|
||||
run: |
|
||||
set -e
|
||||
cd /docker/FlockPal
|
||||
docker compose -f docker-compose.prod.yml up -d --build --wait --wait-timeout 180
|
||||
|
||||
- name: Verify production API readiness
|
||||
run: |
|
||||
set -e
|
||||
cd /docker/FlockPal
|
||||
docker compose -f docker-compose.prod.yml exec -T backend node dist/healthcheck.js api-ready
|
||||
|
||||
- name: Notify Discord
|
||||
if: always()
|
||||
env:
|
||||
DISCORD_WEBHOOK_URL: ${{ secrets.DISCORD_WEBHOOK_URL }}
|
||||
JOB_STATUS: ${{ job.status }}
|
||||
DEPLOY_ENVIRONMENT: production
|
||||
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_LABEL="SUCCESS"
|
||||
else
|
||||
STATUS_LABEL="FAILED"
|
||||
fi
|
||||
|
||||
curl --fail --show-error --silent \
|
||||
-H "Content-Type: application/json" \
|
||||
-d "{\"content\":\"[${STATUS_LABEL}] FlockPal ${DEPLOY_ENVIRONMENT} deploy completed with status: ${JOB_STATUS}\\nBranch: ${{ github.ref_name }}\\nCommit: ${{ github.sha }}\\nRun: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}\"}" \
|
||||
"$DISCORD_WEBHOOK_URL" || echo "Discord notification failed."
|
||||
@@ -7,3 +7,4 @@ frontend/dist
|
||||
data/
|
||||
backups/
|
||||
.DS_Store
|
||||
docker-compose.dev.yaml
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 242 KiB |
@@ -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,6 +103,7 @@ 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`
|
||||
@@ -94,6 +112,8 @@ 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
|
||||
@@ -158,6 +178,34 @@ 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.
|
||||
@@ -203,8 +251,10 @@ Set these when the Stripe Checkout, Customer Portal, and webhook flow is enabled
|
||||
- `STRIPE_PRICE_HOUSEHOLD_CONURE_YEARLY`
|
||||
- `STRIPE_PRICE_HOUSEHOLD_INDIANRINGNECK_MONTHLY` or `STRIPE_PRICE_HOUSEHOLD_INDIANRINGNECK`
|
||||
- `STRIPE_PRICE_HOUSEHOLD_INDIANRINGNECK_YEARLY`
|
||||
- `STRIPE_PRICE_HOUSEHOLD_MACAW_MONTHLY` or `STRIPE_PRICE_HOUSEHOLD_MACAW`
|
||||
- `STRIPE_PRICE_HOUSEHOLD_MACAW_YEARLY`
|
||||
- `STRIPE_PRICE_HOUSEHOLD_AFRICAN_GREY_MONTHLY` or `STRIPE_PRICE_HOUSEHOLD_AFRICAN_GREY`
|
||||
- `STRIPE_PRICE_HOUSEHOLD_AFRICAN_GREY_YEARLY`
|
||||
- `STRIPE_PRICE_HOUSEHOLD_HYACINTH_MACAW_MONTHLY` or `STRIPE_PRICE_HOUSEHOLD_HYACINTH_MACAW`
|
||||
- `STRIPE_PRICE_HOUSEHOLD_HYACINTH_MACAW_YEARLY`
|
||||
- `STRIPE_CHECKOUT_SUCCESS_URL`
|
||||
- `STRIPE_CHECKOUT_CANCEL_URL`
|
||||
- `STRIPE_PORTAL_RETURN_URL`
|
||||
@@ -221,7 +271,7 @@ Recommended defaults:
|
||||
- Enable the proration behavior you want in the Customer Portal configuration. FlockPal treats Stripe as the source of truth for upgrade timing and proration outcomes.
|
||||
- Point the Stripe webhook endpoint at `https://your-backend-host/api/billing/stripe/webhook`.
|
||||
- Subscribe the webhook endpoint to at least `checkout.session.completed`, `customer.subscription.created`, `customer.subscription.updated`, and `customer.subscription.deleted`.
|
||||
- Use one Stripe Price per plan and billing interval. FlockPal maps Stripe price IDs back to `household_basic`, `household_plus`, and `household_macaw`.
|
||||
- Use one Stripe Price per plan and billing interval. FlockPal maps Stripe price IDs back to `household_basic`, `household_plus`, `household_macaw`, and `household_hyacinth_macaw`.
|
||||
- After Stripe redirects back to the app, FlockPal now performs a direct billing sync against Stripe and then refreshes the active session. Webhooks are still required so asynchronous subscription changes stay in sync later.
|
||||
|
||||
For local development with the Stripe CLI:
|
||||
@@ -239,3 +289,10 @@ This starter now includes the account and flock foundation for monetization, plu
|
||||
Stripe billing should be attached to `workspaces`, not `users`. Each flock has its own billing plan, subscription status, Stripe customer ID, and Stripe subscription ID, which lets one person own multiple household flocks with separate subscriptions while rescue flocks can stay on the free rescue path.
|
||||
|
||||
For account design, `standard` vs `rescue` is best treated as a flock type, not as a user role. If paid plans are added later, a separate `admin account mode` is usually less flexible than flock roles such as `owner`, `assistant`, `caregiver`, and `viewer`. That lets the same underlying account system work for both households and rescues without splitting product logic into unrelated account classes.
|
||||
|
||||
## Customer API documentation
|
||||
|
||||
Open `/api/docs/` on your FlockPal instance for the interactive integration API reference,
|
||||
or download `/api/openapi.json`. Locally, use `http://localhost:5000/api/docs/`.
|
||||
Create a token in Settings → Integration tokens and use **Authorize** to try requests.
|
||||
See [the API reference](docs/API_REFERENCE.md) for details.
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 237 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 234 KiB |
Generated
+1315
-1
File diff suppressed because it is too large.
Load diff
@@ -14,6 +14,7 @@
|
||||
"worker": "node dist/worker.js"
|
||||
},
|
||||
"dependencies": {
|
||||
"@asteasolutions/zod-to-openapi": "7.3.4",
|
||||
"@types/nodemailer": "^8.0.0",
|
||||
"bullmq": "^5.76.4",
|
||||
"cors": "2.8.5",
|
||||
@@ -23,16 +24,24 @@
|
||||
"helmet": "8.1.0",
|
||||
"morgan": "1.10.0",
|
||||
"nodemailer": "^8.0.5",
|
||||
"pdfkit": "^0.18.0",
|
||||
"pg": "8.13.1",
|
||||
"qrcode": "^1.5.4",
|
||||
"sharp": "^0.34.5",
|
||||
"stripe": "^22.0.2",
|
||||
"swagger-ui-express": "5.0.1",
|
||||
"zod": "3.24.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@apidevtools/swagger-parser": "13.1.0",
|
||||
"@types/cors": "2.8.17",
|
||||
"@types/express": "4.17.21",
|
||||
"@types/morgan": "1.9.9",
|
||||
"@types/node": "22.10.2",
|
||||
"@types/pdfkit": "^0.17.6",
|
||||
"@types/pg": "8.11.10",
|
||||
"@types/qrcode": "^1.5.6",
|
||||
"@types/swagger-ui-express": "4.1.8",
|
||||
"tsx": "4.19.2",
|
||||
"typescript": "5.7.2"
|
||||
}
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
// 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)));
|
||||
+1411
-268
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,40 @@
|
||||
import { z } from 'zod';
|
||||
|
||||
export const behaviorTypeSchema = z.object({
|
||||
name: z.string().trim().min(1).max(120),
|
||||
description: z.string().trim().max(2000).nullable().optional(),
|
||||
});
|
||||
export const behaviorOccurrenceSchema = z.object({
|
||||
behaviorTypeId: z.string().uuid(),
|
||||
occurredAt: z.string().datetime({ offset: true }),
|
||||
durationSeconds: z.number().finite().positive().max(31536000).nullable().optional(),
|
||||
severity: z.number().int().min(1).max(5).nullable().optional(),
|
||||
notes: z.string().trim().max(10000).nullable().optional(),
|
||||
});
|
||||
export const behaviorRangeSchema = z.object({
|
||||
from: z.string().datetime({ offset: true }),
|
||||
to: z.string().datetime({ offset: true }),
|
||||
behaviorTypeId: z.string().uuid().optional(),
|
||||
}).refine(({ from, to }) => Date.parse(to) > Date.parse(from) && Date.parse(to) - Date.parse(from) <= 32 * 86400000, {
|
||||
message: 'Choose a date range of up to 32 days, with to after from.',
|
||||
});
|
||||
export type BehaviorInput = z.infer<typeof behaviorOccurrenceSchema>;
|
||||
|
||||
export type BehaviorType = {
|
||||
id: string;
|
||||
name: string;
|
||||
description: string | null;
|
||||
createdAt: Date;
|
||||
};
|
||||
export type BehaviorOccurrence = {
|
||||
id: string;
|
||||
birdId: string;
|
||||
behaviorTypeId: string;
|
||||
behaviorName: string;
|
||||
occurredAt: Date;
|
||||
durationSeconds: number | null;
|
||||
severity: number | null;
|
||||
notes: string | null;
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
};
|
||||
@@ -0,0 +1,9 @@
|
||||
import { z } from 'zod';
|
||||
|
||||
export const unassignedBirdMatchSchema = z.object({
|
||||
tagId: z.string().trim().min(1).max(80).refine(
|
||||
(value) => !['unknown', 'not recorded', 'n/a', 'na', 'none'].includes(value.toLowerCase()),
|
||||
'Enter a known band ID.',
|
||||
),
|
||||
});
|
||||
export const claimBirdSchema = unassignedBirdMatchSchema.extend({ confirmHistory: z.literal(true) });
|
||||
@@ -23,6 +23,21 @@ export class DatabaseClient {
|
||||
return this.pool.query<T>(text, params);
|
||||
}
|
||||
|
||||
async transaction<T>(operation: (client: pg.PoolClient) => Promise<T>): Promise<T> {
|
||||
const client = await this.pool.connect();
|
||||
try {
|
||||
await client.query('BEGIN');
|
||||
const result = await operation(client);
|
||||
await client.query('COMMIT');
|
||||
return result;
|
||||
} catch (error) {
|
||||
await client.query('ROLLBACK');
|
||||
throw error;
|
||||
} finally {
|
||||
client.release();
|
||||
}
|
||||
}
|
||||
|
||||
async close() {
|
||||
await this.pool.end();
|
||||
}
|
||||
|
||||
+186
-7
@@ -61,10 +61,6 @@ export const ensureSchema = async (database: DatabaseClient = db) => {
|
||||
WHERE workspace_type = 'rescue'
|
||||
AND rescue_verification_status = 'not_required';
|
||||
|
||||
INSERT INTO workspaces (id, name, workspace_type, billing_plan)
|
||||
VALUES (1, 'My Flock', 'standard', 'household_basic')
|
||||
ON CONFLICT (id) DO NOTHING;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS workspace_members (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
workspace_id INTEGER NOT NULL REFERENCES workspaces(id) ON DELETE CASCADE,
|
||||
@@ -216,6 +212,15 @@ export const ensureSchema = async (database: DatabaseClient = db) => {
|
||||
name VARCHAR(120) NOT NULL,
|
||||
tag_id VARCHAR(80),
|
||||
species VARCHAR(120) NOT NULL,
|
||||
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),
|
||||
vet_doctor_name VARCHAR(160),
|
||||
gender VARCHAR(16) NOT NULL DEFAULT 'unknown',
|
||||
date_of_birth DATE,
|
||||
gotcha_day DATE,
|
||||
@@ -226,6 +231,8 @@ export const ensureSchema = async (database: DatabaseClient = db) => {
|
||||
photo_updated_at TIMESTAMPTZ,
|
||||
notify_on_dob BOOLEAN NOT NULL DEFAULT FALSE,
|
||||
notify_on_gotcha_day BOOLEAN NOT NULL DEFAULT FALSE,
|
||||
public_profile_code VARCHAR(32),
|
||||
public_profile_enabled BOOLEAN NOT NULL DEFAULT FALSE,
|
||||
memorialized_at TIMESTAMPTZ,
|
||||
memorialized_on DATE,
|
||||
memorial_note VARCHAR(1000),
|
||||
@@ -235,6 +242,15 @@ export const ensureSchema = async (database: DatabaseClient = db) => {
|
||||
|
||||
ALTER TABLE birds
|
||||
ADD COLUMN IF NOT EXISTS workspace_id INTEGER NOT NULL DEFAULT 1,
|
||||
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),
|
||||
ADD COLUMN IF NOT EXISTS vet_doctor_name VARCHAR(160),
|
||||
ADD COLUMN IF NOT EXISTS gender VARCHAR(16) NOT NULL DEFAULT 'unknown',
|
||||
ADD COLUMN IF NOT EXISTS date_of_birth DATE,
|
||||
ADD COLUMN IF NOT EXISTS gotcha_day DATE,
|
||||
@@ -245,13 +261,17 @@ export const ensureSchema = async (database: DatabaseClient = db) => {
|
||||
ADD COLUMN IF NOT EXISTS photo_updated_at TIMESTAMPTZ,
|
||||
ADD COLUMN IF NOT EXISTS notify_on_dob BOOLEAN NOT NULL DEFAULT FALSE,
|
||||
ADD COLUMN IF NOT EXISTS notify_on_gotcha_day BOOLEAN NOT NULL DEFAULT FALSE,
|
||||
ADD COLUMN IF NOT EXISTS public_profile_code VARCHAR(32),
|
||||
ADD COLUMN IF NOT EXISTS public_profile_enabled BOOLEAN NOT NULL DEFAULT FALSE,
|
||||
ADD COLUMN IF NOT EXISTS memorialized_at TIMESTAMPTZ,
|
||||
ADD COLUMN IF NOT EXISTS memorialized_on DATE,
|
||||
ADD COLUMN IF NOT EXISTS memorial_note VARCHAR(1000),
|
||||
ADD COLUMN IF NOT EXISTS notify_on_memorial_day BOOLEAN NOT NULL DEFAULT FALSE;
|
||||
|
||||
ALTER TABLE birds
|
||||
ALTER COLUMN tag_id DROP NOT NULL;
|
||||
ALTER COLUMN tag_id DROP NOT NULL,
|
||||
ALTER COLUMN workspace_id DROP NOT NULL,
|
||||
ALTER COLUMN workspace_id DROP DEFAULT;
|
||||
|
||||
UPDATE birds
|
||||
SET tag_id = NULL
|
||||
@@ -267,13 +287,19 @@ export const ensureSchema = async (database: DatabaseClient = db) => {
|
||||
END IF;
|
||||
END $$;
|
||||
|
||||
DELETE FROM workspaces
|
||||
WHERE id = 1
|
||||
AND name = 'My Flock'
|
||||
AND NOT EXISTS (SELECT 1 FROM workspace_members WHERE workspace_members.workspace_id = workspaces.id)
|
||||
AND NOT EXISTS (SELECT 1 FROM birds WHERE birds.workspace_id = workspaces.id);
|
||||
|
||||
ALTER TABLE birds
|
||||
DROP CONSTRAINT IF EXISTS birds_tag_id_key;
|
||||
|
||||
DROP INDEX IF EXISTS idx_birds_workspace_tag_id;
|
||||
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS idx_birds_workspace_tag_id
|
||||
ON birds (workspace_id, LOWER(tag_id))
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS idx_birds_global_tag_id
|
||||
ON birds (LOWER(BTRIM(tag_id)))
|
||||
WHERE tag_id IS NOT NULL
|
||||
AND BTRIM(tag_id) <> ''
|
||||
AND LOWER(BTRIM(tag_id)) NOT IN ('unknown', 'not recorded', 'n/a', 'na', 'none');
|
||||
@@ -297,6 +323,10 @@ export const ensureSchema = async (database: DatabaseClient = db) => {
|
||||
ON birds (photo_object_key)
|
||||
WHERE photo_object_key IS NOT NULL;
|
||||
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS idx_birds_public_profile_code
|
||||
ON birds (public_profile_code)
|
||||
WHERE public_profile_code IS NOT NULL;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS pending_bird_transfers (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
bird_id UUID NOT NULL REFERENCES birds(id) ON DELETE CASCADE,
|
||||
@@ -322,6 +352,95 @@ export const ensureSchema = async (database: DatabaseClient = db) => {
|
||||
ON pending_bird_transfers (bird_id)
|
||||
WHERE completed_at IS NULL;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS bird_transfer_codes (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
code VARCHAR(32) NOT NULL UNIQUE,
|
||||
bird_id UUID NOT NULL REFERENCES birds(id) ON DELETE CASCADE,
|
||||
source_workspace_id INTEGER NOT NULL REFERENCES workspaces(id) ON DELETE CASCADE,
|
||||
requested_by_user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
completed_at TIMESTAMPTZ,
|
||||
completed_workspace_id INTEGER REFERENCES workspaces(id) ON DELETE SET NULL,
|
||||
revoked_at TIMESTAMPTZ,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_bird_transfer_codes_open_bird
|
||||
ON bird_transfer_codes (bird_id, created_at DESC)
|
||||
WHERE completed_at IS NULL
|
||||
AND revoked_at IS NULL;
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_bird_transfer_codes_code_open
|
||||
ON bird_transfer_codes (code)
|
||||
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,
|
||||
bird_id UUID REFERENCES birds(id) ON DELETE SET NULL,
|
||||
title VARCHAR(160) NOT NULL,
|
||||
body TEXT NOT NULL,
|
||||
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
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_flock_notes_workspace_updated
|
||||
ON flock_notes (workspace_id, updated_at DESC);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_flock_notes_bird_updated
|
||||
ON flock_notes (bird_id, updated_at DESC)
|
||||
WHERE bird_id IS NOT NULL;
|
||||
|
||||
-- Bird-specific notes remain attached while their bird is between flocks.
|
||||
ALTER TABLE flock_notes ALTER COLUMN workspace_id DROP NOT NULL;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS audit_log_entries (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
workspace_id INTEGER NOT NULL REFERENCES workspaces(id) ON DELETE CASCADE,
|
||||
user_id UUID REFERENCES users(id) ON DELETE SET NULL,
|
||||
actor_name VARCHAR(160),
|
||||
actor_email VARCHAR(255),
|
||||
action VARCHAR(80) NOT NULL,
|
||||
entity_type VARCHAR(80) NOT NULL,
|
||||
entity_id VARCHAR(120),
|
||||
entity_name VARCHAR(255),
|
||||
details JSONB NOT NULL DEFAULT '{}'::jsonb,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_audit_log_entries_workspace_created
|
||||
ON audit_log_entries (workspace_id, created_at DESC);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_audit_log_entries_entity
|
||||
ON audit_log_entries (workspace_id, entity_type, entity_id, created_at DESC);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS weight_records (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
bird_id UUID NOT NULL REFERENCES birds(id) ON DELETE CASCADE,
|
||||
@@ -332,6 +451,17 @@ 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,
|
||||
@@ -353,6 +483,7 @@ export const ensureSchema = async (database: DatabaseClient = db) => {
|
||||
start_date DATE NOT NULL,
|
||||
end_date DATE,
|
||||
notes VARCHAR(1000),
|
||||
reminders_enabled BOOLEAN NOT NULL DEFAULT FALSE,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
CHECK (end_date IS NULL OR end_date >= start_date)
|
||||
);
|
||||
@@ -360,6 +491,9 @@ export const ensureSchema = async (database: DatabaseClient = db) => {
|
||||
ALTER TABLE medications
|
||||
ADD COLUMN IF NOT EXISTS dose_schedule JSONB NOT NULL DEFAULT '[{"key":"dose-1","label":"Dose","time":""}]'::jsonb;
|
||||
|
||||
ALTER TABLE medications
|
||||
ADD COLUMN IF NOT EXISTS reminders_enabled BOOLEAN NOT NULL DEFAULT FALSE;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS bird_milestone_reminder_deliveries (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
bird_id UUID NOT NULL REFERENCES birds(id) ON DELETE CASCADE,
|
||||
@@ -393,6 +527,17 @@ export const ensureSchema = async (database: DatabaseClient = db) => {
|
||||
ALTER TABLE medication_administrations
|
||||
ADD COLUMN IF NOT EXISTS administration_slot VARCHAR(80) NOT NULL DEFAULT 'dose-1';
|
||||
|
||||
CREATE TABLE IF NOT EXISTS medication_reminder_deliveries (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
medication_id UUID NOT NULL REFERENCES medications(id) ON DELETE CASCADE,
|
||||
bird_id UUID NOT NULL REFERENCES birds(id) ON DELETE CASCADE,
|
||||
workspace_id INTEGER NOT NULL REFERENCES workspaces(id) ON DELETE CASCADE,
|
||||
scheduled_on DATE NOT NULL,
|
||||
administration_slot VARCHAR(80) NOT NULL,
|
||||
delivered_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
UNIQUE (medication_id, scheduled_on, administration_slot)
|
||||
);
|
||||
|
||||
ALTER TABLE medication_administrations
|
||||
DROP CONSTRAINT IF EXISTS medication_administrations_medication_id_administered_on_key;
|
||||
|
||||
@@ -411,12 +556,46 @@ export const ensureSchema = async (database: DatabaseClient = db) => {
|
||||
CREATE INDEX IF NOT EXISTS idx_bird_milestone_reminder_deliveries_workspace
|
||||
ON bird_milestone_reminder_deliveries (workspace_id, delivered_on DESC);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_medication_reminder_deliveries_workspace
|
||||
ON medication_reminder_deliveries (workspace_id, scheduled_on DESC);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_medication_administrations_bird_administered_on
|
||||
ON medication_administrations (bird_id, administered_on DESC);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_medication_administrations_medication_date
|
||||
ON medication_administrations (medication_id, administered_on DESC, created_at DESC);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS behavior_types (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
workspace_id INTEGER REFERENCES workspaces(id) ON DELETE SET NULL,
|
||||
name VARCHAR(120) NOT NULL,
|
||||
is_default BOOLEAN NOT NULL DEFAULT FALSE,
|
||||
description TEXT,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS idx_behavior_types_workspace_name
|
||||
ON behavior_types (workspace_id, lower(name)) WHERE workspace_id IS NOT NULL;
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS idx_behavior_types_default_name
|
||||
ON behavior_types (lower(name)) WHERE is_default;
|
||||
INSERT INTO behavior_types (name, is_default) VALUES
|
||||
('Screaming / vocalization', TRUE), ('Biting / aggression', TRUE), ('Feather plucking', TRUE),
|
||||
('Repetitive behavior', TRUE), ('Excessive scratching', TRUE), ('Hiding / withdrawal', TRUE),
|
||||
('Unusual posture', TRUE), ('Food refusal', TRUE), ('Other', TRUE)
|
||||
ON CONFLICT DO NOTHING;
|
||||
CREATE TABLE IF NOT EXISTS behavior_occurrences (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
bird_id UUID NOT NULL REFERENCES birds(id) ON DELETE CASCADE,
|
||||
behavior_type_id UUID NOT NULL REFERENCES behavior_types(id),
|
||||
occurred_at TIMESTAMPTZ NOT NULL,
|
||||
duration_seconds DOUBLE PRECISION CHECK (duration_seconds > 0 AND duration_seconds <= 31536000),
|
||||
severity SMALLINT CHECK (severity BETWEEN 1 AND 5),
|
||||
notes TEXT,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_behavior_occurrences_bird_time ON behavior_occurrences (bird_id, occurred_at DESC);
|
||||
CREATE INDEX IF NOT EXISTS idx_behavior_occurrences_bird_type_time ON behavior_occurrences (bird_id, behavior_type_id, occurred_at DESC);
|
||||
|
||||
DO $$
|
||||
BEGIN
|
||||
IF EXISTS (
|
||||
|
||||
@@ -0,0 +1,117 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFile } from 'node:fs/promises';
|
||||
import { once } from 'node:events';
|
||||
import test from 'node:test';
|
||||
import express from 'express';
|
||||
import SwaggerParser from '@apidevtools/swagger-parser';
|
||||
import ts from 'typescript';
|
||||
import { customerOpenApi } from './openapi.js';
|
||||
import { mountApiDocs } from './router.js';
|
||||
import { birdSchema, medicationSchema } from '../schemas.js';
|
||||
|
||||
const appSource = await readFile(new URL('../app.ts', import.meta.url), 'utf8');
|
||||
const ast = ts.createSourceFile('app.ts', appSource, ts.ScriptTarget.Latest, true);
|
||||
|
||||
test('customer specification is valid OpenAPI and has unique operation IDs', async () => {
|
||||
await SwaggerParser.validate(JSON.parse(JSON.stringify(customerOpenApi)));
|
||||
const ids = Object.values(customerOpenApi.paths).flatMap((path) => Object.values(path!).map((operation) => operation.operationId));
|
||||
assert.equal(new Set(ids).size, ids.length);
|
||||
assert.deepEqual(customerOpenApi.servers, [{ url: '/api', description: 'This FlockPal instance' }]);
|
||||
});
|
||||
|
||||
test('documented operations exactly match customer integration routes and permissions', () => {
|
||||
const expected: string[] = [];
|
||||
for (const statement of ast.statements) {
|
||||
if (!ts.isExpressionStatement(statement) || !ts.isCallExpression(statement.expression)) continue;
|
||||
const call = statement.expression;
|
||||
if (!ts.isPropertyAccessExpression(call.expression) || call.expression.expression.getText(ast) !== 'app') continue;
|
||||
const method = call.expression.name.text;
|
||||
if (!['get', 'post', 'put', 'delete', 'patch'].includes(method)) continue;
|
||||
const [pathArg, ...args] = call.arguments;
|
||||
if (!pathArg || !ts.isStringLiteral(pathArg)) continue;
|
||||
const middleware = args.filter(ts.isIdentifier).map((arg) => arg.text);
|
||||
if (!middleware.includes('requireAuth') || middleware.includes('requireSessionAuth') || middleware.includes('requireAdmin')) continue;
|
||||
const path = pathArg.text.replace(/^\/api/, '').replace(/:(\w+)/g, '{$1}');
|
||||
expected.push(`${method} ${path}`);
|
||||
const operation = (customerOpenApi.paths[path] as Record<string, any> | undefined)?.[method];
|
||||
assert.ok(operation, `Missing ${method} ${path}`);
|
||||
assert.deepEqual(operation.security, [{ IntegrationToken: [] }]);
|
||||
if (middleware.includes('requireWriteAccess')) {
|
||||
assert.match(operation.description, /read_write/);
|
||||
assert.ok(operation.responses['402']);
|
||||
assert.ok(operation.responses['403']);
|
||||
}
|
||||
const roleCall = args.find((arg) => ts.isCallExpression(arg) && arg.expression.getText(ast) === 'requireWorkspaceRole');
|
||||
if (roleCall && ts.isCallExpression(roleCall)) {
|
||||
for (const match of roleCall.getText(ast).matchAll(/'([^']+)'/g)) assert.ok(operation.description.includes(match[1]));
|
||||
}
|
||||
}
|
||||
const actual = Object.entries(customerOpenApi.paths).flatMap(([path, item]) => Object.keys(item!).map((method) => `${method} ${path}`));
|
||||
assert.deepEqual(actual.sort(), expected.sort());
|
||||
assert.equal(actual.length, 35);
|
||||
});
|
||||
|
||||
test('response models cover the actual serialized fields', () => {
|
||||
const components = customerOpenApi.components!.schemas!;
|
||||
const names: Record<string, string> = { normalizeWorkspace: 'workspace', normalizeWorkspaceMember: 'member', normalizeBird: 'bird', normalizeWeight: 'weight', normalizeVetVisit: 'vetVisit', normalizeMedication: 'medication', normalizeMedicationAdministration: 'administration', normalizeFlockNote: 'note', normalizeBirdTimelineEvent: 'timeline' };
|
||||
for (const statement of ast.statements) {
|
||||
if (!ts.isVariableStatement(statement)) continue;
|
||||
for (const declaration of statement.declarationList.declarations) {
|
||||
const model = names[declaration.name.getText(ast)];
|
||||
if (!model) continue;
|
||||
const fn = declaration.initializer;
|
||||
assert.ok(fn && ts.isArrowFunction(fn) && ts.isParenthesizedExpression(fn.body));
|
||||
const body = fn.body.expression;
|
||||
assert.ok(ts.isObjectLiteralExpression(body));
|
||||
const keys = body.properties.map((property) => property.name!.getText(ast));
|
||||
const schema = components[model];
|
||||
assert.ok(schema && !('$ref' in schema));
|
||||
assert.deepEqual(Object.keys(schema.properties!).sort(), keys.sort(), model);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test('shared validators retain custom rules and document required request fields', () => {
|
||||
assert.equal(birdSchema.safeParse({ name: 'Yoda', species: 'Parrot', motivators: 'one\ntwo\nthree\nfour' }).success, false);
|
||||
assert.equal(medicationSchema.safeParse({ name: 'Medicine', dosage: '1 ml', frequency: 'once_daily', doseSchedule: [{ key: 'morning', label: 'Morning', time: '08:00' }], startDate: '2026-09-27', endDate: '2026-09-26' }).success, false);
|
||||
const bird = customerOpenApi.components!.schemas!.BirdInput;
|
||||
assert.ok(!('$ref' in bird));
|
||||
assert.deepEqual(bird.required, ['name', 'species']);
|
||||
});
|
||||
|
||||
test('Swagger UI, initialization, assets and specification are served locally with compatible CSP', async (t) => {
|
||||
const app = express();
|
||||
mountApiDocs(app);
|
||||
const server = app.listen(0, '127.0.0.1');
|
||||
await once(server, 'listening');
|
||||
t.after(() => new Promise<void>((resolve, reject) => server.close((error) => error ? reject(error) : resolve())));
|
||||
const address = server.address();
|
||||
assert.ok(address && typeof address !== 'string');
|
||||
const base = `http://127.0.0.1:${address.port}`;
|
||||
const page = await fetch(`${base}/api/docs/`);
|
||||
assert.equal(page.status, 200);
|
||||
const html = await page.text();
|
||||
assert.match(html, /FlockPal API Reference/);
|
||||
const csp = page.headers.get('content-security-policy')!;
|
||||
assert.match(csp, /script-src 'self'/);
|
||||
assert.match(csp, /connect-src 'self'/);
|
||||
assert.ok(!csp.includes('upgrade-insecure-requests'));
|
||||
for (const asset of ['swagger-ui.css', 'swagger-ui-bundle.js', 'swagger-ui-standalone-preset.js', 'swagger-ui-init.js']) {
|
||||
const response = await fetch(`${base}/api/docs/${asset}`);
|
||||
assert.equal(response.status, 200, asset);
|
||||
const content = await response.text();
|
||||
assert.ok(content.length > 0);
|
||||
if (asset === 'swagger-ui-init.js') {
|
||||
assert.match(content, /\/api\/openapi.json/);
|
||||
assert.match(content, /"persistAuthorization": false/);
|
||||
assert.match(content, /"validatorUrl": null/);
|
||||
}
|
||||
}
|
||||
const spec = await fetch(`${base}/api/openapi.json`);
|
||||
assert.equal(spec.status, 200);
|
||||
assert.match(spec.headers.get('content-type')!, /application\/json/);
|
||||
assert.deepEqual(await spec.json(), customerOpenApi);
|
||||
const redirect = await fetch(`${base}/api/docs`, { redirect: 'manual' });
|
||||
assert.equal(redirect.status, 301);
|
||||
assert.equal(redirect.headers.get('location'), '/api/docs/');
|
||||
});
|
||||
@@ -0,0 +1,134 @@
|
||||
import { unassignedBirdMatchSchema, claimBirdSchema } from '../birdMembershipSchemas.js';
|
||||
import { behaviorTypeSchema, behaviorOccurrenceSchema } from '../behaviorSchemas.js';
|
||||
import { z } from 'zod';
|
||||
import { extendZodWithOpenApi, OpenAPIRegistry, OpenApiGeneratorV3, type RouteConfig } from '@asteasolutions/zod-to-openapi';
|
||||
import { birdSchema, workspaceMemberSchema, workspaceRoleSchema, flockNoteSchema, locationSearchSchema,
|
||||
weightSchema, vetVisitSchema, medicationSchema, medicationAdministrationSchema } from '../schemas.js';
|
||||
import * as responses from './responses.js';
|
||||
|
||||
extendZodWithOpenApi(z);
|
||||
const registry = new OpenAPIRegistry();
|
||||
registry.registerComponent('securitySchemes', 'IntegrationToken', {
|
||||
type: 'http', scheme: 'bearer', bearerFormat: 'flpt_…',
|
||||
description: 'Paste your integration token, without the Bearer prefix. Create it in FlockPal Settings → Integration tokens.',
|
||||
});
|
||||
const models = Object.fromEntries(Object.entries(responses).map(([name, schema]) => [name, registry.register(name.replace('Response', ''), schema)]));
|
||||
const error = registry.register('Error', z.object({
|
||||
error: z.string(), code: z.string().optional(),
|
||||
details: z.object({ formErrors: z.array(z.string()), fieldErrors: z.record(z.array(z.string())) }).optional(),
|
||||
}));
|
||||
const json = (schema: z.ZodTypeAny, example?: unknown) => ({ 'application/json': { schema, ...(example ? { example } : {}) } });
|
||||
const errors: Record<number, string> = {
|
||||
400: 'Invalid request.', 401: 'Missing, expired, revoked, or invalid integration token.',
|
||||
402: 'Workspace is read-only: subscription must be active/trialing, or rescue verification approved.',
|
||||
403: 'Insufficient token scope or workspace role.', 404: 'Resource not found in this workspace, or cannot be changed.',
|
||||
409: 'Conflict: duplicate band/tag ID, duplicate weight date, or memorialized bird is read-only.',
|
||||
500: 'Internal server error.', 502: 'Location provider request failed.', 503: 'Location search is not configured.',
|
||||
};
|
||||
type Endpoint = {
|
||||
method: 'get' | 'post' | 'put' | 'delete'; path: string; summary: string; tag: string;
|
||||
response?: z.ZodTypeAny; body?: z.ZodTypeAny; example?: unknown; query?: z.AnyZodObject;
|
||||
description?: string; status?: number; errors?: number[]; roles?: string[];
|
||||
};
|
||||
const careRoles = ['owner', 'assistant', 'caregiver'];
|
||||
function endpoint(config: Endpoint) {
|
||||
const write = config.method !== 'get';
|
||||
const params = Object.fromEntries([...config.path.matchAll(/\{(\w+)\}/g)].map((match) => [match[1], z.string().uuid()]));
|
||||
const responseMap: RouteConfig['responses'] = {
|
||||
[config.status ?? (config.method === 'delete' ? 204 : config.method === 'post' ? 201 : 200)]: {
|
||||
description: config.method === 'delete' ? 'Deleted successfully. No response body.' : 'Success.',
|
||||
...(config.response ? { content: json(config.response) } : {}),
|
||||
},
|
||||
429: { description: 'Rate limit exceeded. General limit: 300 requests per 15 minutes per IP; location search additionally allows 40 per 15 minutes.',
|
||||
headers: { 'Retry-After': { schema: { type: 'string' }, description: 'Seconds until retry.' } },
|
||||
content: { 'text/html': { schema: { type: 'string' } }, 'application/json': { schema: error } } },
|
||||
};
|
||||
for (const status of new Set([401, 500, ...(write ? [402, 403] : []), ...(config.body || config.query ? [400] : []), ...(config.errors ?? [])])) {
|
||||
responseMap[status] = { description: errors[status], content: json(error) };
|
||||
}
|
||||
registry.registerPath({
|
||||
method: config.method, path: config.path, summary: config.summary, tags: [config.tag],
|
||||
operationId: `${config.method}_${config.path.replace(/[{}]/g, '').replace(/[^a-zA-Z0-9]+/g, '_').replace(/^_/, '')}`,
|
||||
description: [config.description, write ? `Requires a read_write token and an active writable workspace. Allowed roles: ${(config.roles ?? careRoles).join(', ')}.` : 'Accepts read_only or read_write integration tokens.'].filter(Boolean).join('\n\n'),
|
||||
security: [{ IntegrationToken: [] }],
|
||||
request: {
|
||||
...(Object.keys(params).length ? { params: z.object(params) } : {}),
|
||||
...(config.query ? { query: config.query } : {}),
|
||||
...(config.body ? { body: { required: true, content: json(config.body, config.example) } } : {}),
|
||||
},
|
||||
responses: responseMap,
|
||||
});
|
||||
}
|
||||
const one = (name: string, model: z.ZodTypeAny) => z.object({ [name]: model });
|
||||
const many = (name: string, model: z.ZodTypeAny) => one(name, z.array(model));
|
||||
endpoint({ method: 'get', path: '/workspace', summary: 'Get the token’s workspace', tag: 'Workspace', response: one('workspace', models.workspaceResponse) });
|
||||
endpoint({ method: 'get', path: '/workspace/members', summary: 'List workspace members', tag: 'Workspace', response: many('members', models.memberResponse) });
|
||||
endpoint({ method: 'post', path: '/workspace/members', summary: 'Add or update a workspace member', tag: 'Workspace', body: registry.register('MemberInput', workspaceMemberSchema), response: one('member', models.memberResponse), roles: ['owner', 'assistant'] });
|
||||
endpoint({ method: 'put', path: '/workspace/members/{memberId}', summary: 'Change a member’s role', tag: 'Workspace', body: z.object({ role: workspaceRoleSchema }), response: one('member', models.memberResponse), roles: ['owner', 'assistant'], errors: [404], description: 'Only the billing owner can promote collaborators to owner. Additional protections apply to changing your own or the billing owner’s membership.' });
|
||||
endpoint({ method: 'delete', path: '/workspace/members/{memberId}', summary: 'Remove a workspace member', tag: 'Workspace', roles: ['owner', 'assistant'], errors: [404], description: 'Protected memberships cannot be removed.' });
|
||||
endpoint({ method: 'get', path: '/notes', summary: 'List flock notes', tag: 'Notes', response: many('notes', models.noteResponse) });
|
||||
endpoint({ method: 'post', path: '/notes', summary: 'Create a flock note', tag: 'Notes', body: registry.register('NoteInput', flockNoteSchema), response: one('note', models.noteResponse), errors: [404], example: { body: 'Enjoyed a new enrichment activity today.' } });
|
||||
endpoint({ method: 'delete', path: '/notes/{noteId}', summary: 'Delete a flock note', tag: 'Notes', errors: [404] });
|
||||
endpoint({ method: 'get', path: '/locations/search', summary: 'Search for a location', tag: 'Locations', query: locationSearchSchema, response: many('results', models.locationResponse), errors: [502, 503], description: 'Search cities, regions, and countries. Requires 3–120 characters; returns up to three matches. Additional rate limit: 40 requests per 15 minutes per IP.' });
|
||||
endpoint({ method: 'get', path: '/birds/unassigned-match', summary: 'Check for an unassigned bird by band ID', tag: 'Birds', query: unassignedBirdMatchSchema, response: z.object({ available: z.boolean() }), errors: [403], description: 'Requires owner, assistant, or caregiver role. Returns only availability, not profile details. Matching ignores case and surrounding whitespace; partial and unknown IDs do not match.' });
|
||||
endpoint({ method: 'post', path: '/birds/claim', summary: 'Add an unassigned bird with its existing history', tag: 'Birds', body: claimBirdSchema, response: z.object({ bird: models.birdResponse, historyImported: z.literal(true) }), status: 200, errors: [409], description: 'Requires confirmHistory: true. Atomically assigns the existing bird to the current flock, preserving its ID, profile, photo, and history. Existing profile details are used. Birds already in a flock cannot be claimed.' });
|
||||
endpoint({ method: 'get', path: '/birds', summary: 'List active and memorialized birds', tag: 'Birds', response: z.object({ birds: z.array(models.birdResponse), memorializedBirds: z.array(models.birdResponse) }) });
|
||||
const birdInput = registry.register('BirdInput', birdSchema);
|
||||
const birdDescription = 'motivators and demotivators each allow up to three non-empty lines. hatchDay takes precedence over the legacy dateOfBirth field. photoDataUrl accepts an image data URL or HTTP(S) URL; returned photo links may expire.';
|
||||
endpoint({ method: 'post', path: '/birds', summary: 'Create a bird', tag: 'Birds', body: birdInput, response: one('bird', models.birdResponse), errors: [409], description: birdDescription, example: { name: 'Yoda', species: 'African grey' } });
|
||||
endpoint({ method: 'put', path: '/birds/{birdId}', summary: 'Update a bird', tag: 'Birds', body: birdInput, response: one('bird', models.birdResponse), errors: [404, 409], description: `Submit the full editable profile: omitted optional fields may be cleared or reset. ${birdDescription}` });
|
||||
endpoint({ method: 'delete', path: '/birds/{birdId}', summary: 'Remove a bird from its flock', tag: 'Birds', errors: [404, 409], description: 'Unassigns the bird without deleting its profile, photo, or care history. Bird-specific notes follow the bird; flock-wide notes and workspace audit logs stay in the old flock. Public sharing is disabled and pending transfers are revoked. An exact band ID match can later bring the bird and its history into a flock.' });
|
||||
endpoint({ method: 'get', path: '/birds/{birdId}/timeline', summary: 'List bird timeline events', tag: 'Birds', response: many('events', models.timelineResponse), errors: [404] });
|
||||
for (const resource of [
|
||||
{ path: 'weights', single: 'weight', plural: 'weights', id: 'weightId', tag: 'Weights', input: weightSchema, model: models.weightResponse },
|
||||
{ path: 'vet-visits', single: 'vetVisit', plural: 'vetVisits', id: 'visitId', tag: 'Vet visits', input: vetVisitSchema, model: models.vetVisitResponse },
|
||||
{ path: 'medications', single: 'medication', plural: 'medications', id: 'medicationId', tag: 'Medications', input: medicationSchema, model: models.medicationResponse },
|
||||
]) {
|
||||
const path = `/birds/{birdId}/${resource.path}`;
|
||||
const body = registry.register(`${resource.single}Input`, resource.input);
|
||||
const description = resource.path === 'medications' ? 'endDate must be on or after startDate. Supply 1–8 doseSchedule entries with unique application-defined keys; use a key as administrationSlot when recording a dose.' : undefined;
|
||||
endpoint({ method: 'get', path, summary: `List ${resource.tag.toLowerCase()}`, tag: resource.tag, response: many(resource.plural, resource.model),
|
||||
...(resource.path === 'weights' ? { query: z.object({ days: z.coerce.number().min(1).max(425).default(30) }), description: 'Lookback window in days; defaults to 30. Numeric values are clamped to 1–425. Returns an empty list when no matching records exist.' } : {}) });
|
||||
endpoint({ method: 'post', path, summary: `Create ${resource.single === 'vetVisit' ? 'a vet visit' : `a ${resource.single}`}`, tag: resource.tag, body, response: one(resource.single, resource.model), errors: [404, 409], description,
|
||||
...(resource.path === 'weights' ? { example: { weightGrams: 425, recordedOn: '2026-09-27', notes: 'Morning weight' } } : {}) });
|
||||
endpoint({ method: 'put', path: `${path}/{${resource.id}}`, summary: `Update ${resource.single === 'vetVisit' ? 'a vet visit' : `a ${resource.single}`}`, tag: resource.tag, body, response: one(resource.single, resource.model), errors: [404, 409],
|
||||
description: resource.path === 'weights' ? 'Only the three most recent weight records are editable. Older records return 404. One weight entry is allowed per bird per date.' : `Submit the full editable record; omitted optional fields may be reset. ${description ?? ''}` });
|
||||
if (resource.path !== 'weights') endpoint({ method: 'delete', path: `${path}/{${resource.id}}`, summary: `Delete ${resource.single === 'vetVisit' ? 'a vet visit' : 'a medication'}`, tag: resource.tag, errors: [404, 409] });
|
||||
}
|
||||
endpoint({ method: 'get', path: '/birds/{birdId}/medication-administrations', summary: 'List medication administrations', tag: 'Medications', response: many('administrations', models.administrationResponse) });
|
||||
endpoint({ method: 'post', path: '/birds/{birdId}/medications/{medicationId}/administrations', summary: 'Record or update a medication dose', tag: 'Medications', body: registry.register('AdministrationInput', medicationAdministrationSchema), response: one('administration', models.administrationResponse), errors: [404, 409], description: 'Creates or updates the record for this medication, date, and administrationSlot. Use a doseSchedule key for administrationSlot; it defaults to dose-1. Returns 201 for both creation and update.' });
|
||||
|
||||
const behaviorTypeResponse = registry.register('BehaviorType', z.object({
|
||||
id: z.string().uuid(), name: z.string(), description: z.string().nullable(), createdAt: z.string().datetime(),
|
||||
}));
|
||||
const behaviorResponse = registry.register('BehaviorOccurrence', z.object({
|
||||
id: z.string().uuid(), birdId: z.string().uuid(), behaviorTypeId: z.string().uuid(), behaviorName: z.string(),
|
||||
occurredAt: z.string().datetime(), durationSeconds: z.number().nullable(), severity: z.number().int().min(1).max(5).nullable(),
|
||||
notes: z.string().nullable(), createdAt: z.string().datetime(), updatedAt: z.string().datetime(),
|
||||
}));
|
||||
endpoint({ method: 'get', path: '/birds/{birdId}/behavior-types', summary: 'List available behavior types', tag: 'Behavior Journal', response: many('behaviorTypes', behaviorTypeResponse), errors: [400, 404], description: 'Includes common behaviors, flock custom behaviors, and behaviors in this bird’s transferred history.' });
|
||||
endpoint({ method: 'post', path: '/birds/{birdId}/behavior-types', summary: 'Create a reusable flock behavior type', tag: 'Behavior Journal', body: behaviorTypeSchema, response: one('behaviorType', behaviorTypeResponse), errors: [404, 409], description: 'Names are unique within the flock, ignoring case. An existing type is returned for a duplicate name.' });
|
||||
endpoint({ method: 'get', path: '/birds/{birdId}/behaviors', summary: 'List behavior occurrences in a date range', tag: 'Behavior Journal', response: many('occurrences', behaviorResponse), query: z.object({ from: z.string().datetime({ offset: true }), to: z.string().datetime({ offset: true }), behaviorTypeId: z.string().uuid().optional() }), errors: [404], description: 'From is inclusive; to is exclusive. The range must be positive and at most 32 days. Send local month boundaries with their UTC offsets or converted to UTC. Results are newest first; individual events are never aggregated.' });
|
||||
endpoint({ method: 'post', path: '/birds/{birdId}/behaviors', summary: 'Record a behavior occurrence', tag: 'Behavior Journal', body: behaviorOccurrenceSchema, response: one('occurrence', behaviorResponse), errors: [404, 409], description: 'Duration is optional and measured in seconds. Intensity is optional, from 1 to 5. Occurrence timestamps require a time zone offset.' });
|
||||
endpoint({ method: 'put', path: '/birds/{birdId}/behaviors/{occurrenceId}', summary: 'Edit a behavior occurrence', tag: 'Behavior Journal', body: behaviorOccurrenceSchema, response: one('occurrence', behaviorResponse), errors: [404, 409] });
|
||||
endpoint({ method: 'delete', path: '/birds/{birdId}/behaviors/{occurrenceId}', summary: 'Delete a behavior occurrence', tag: 'Behavior Journal', errors: [400, 404, 409] });
|
||||
|
||||
export const customerOpenApi = new OpenApiGeneratorV3(registry.definitions).generateDocument({
|
||||
openapi: '3.0.3',
|
||||
info: { title: 'FlockPal Customer API', version: '0.1.0', description: `Connect your flock to scripts and automation tools such as n8n.
|
||||
|
||||
### Getting started
|
||||
1. Sign in to FlockPal and open Settings → Integration tokens.
|
||||
2. Create a read_only token for reading, or read_write for changes. Copy the secret when shown; it is only displayed once.
|
||||
3. Click Authorize and paste the token (without the Bearer prefix). Requests send Authorization: Bearer flpt_….
|
||||
|
||||
Tokens are scoped to the workspace where they were created and use the creating user’s current membership permissions. Create separate tokens for other workspaces. Expired or revoked tokens return 401.
|
||||
|
||||
Writes require read_write scope, an allowed role, and an active/trialing subscription or approved rescue workspace. Memorialized birds are read-only. Try it out sends real requests to this FlockPal instance, including changes and deletions; authorization is not persisted across reloads.
|
||||
|
||||
This reference covers customer integration endpoints. Manage tokens, authentication, billing, transfers, and memorialization in the FlockPal application. Photo URLs returned by the API can be used directly and may expire.
|
||||
|
||||
The general rate limit is 300 requests per 15 minutes per IP; location search also has a 40-request limit. On 429, wait for Retry-After before retrying.` },
|
||||
servers: [{ url: '/api', description: 'This FlockPal instance' }],
|
||||
tags: ['Workspace', 'Birds', 'Weights', 'Vet visits', 'Medications', 'Notes', 'Locations', 'Behavior Journal'].map((name) => ({ name })),
|
||||
});
|
||||
@@ -0,0 +1,61 @@
|
||||
import { z } from 'zod';
|
||||
import { birdGenderSchema, workspaceRoleSchema } from '../schemas.js';
|
||||
|
||||
const id = z.string().uuid();
|
||||
const text = z.string().nullable();
|
||||
const date = z.string().regex(/^\d{4}-\d{2}-\d{2}$/);
|
||||
const timestamp = z.string().datetime({ offset: true });
|
||||
export const locationResponse = z.object({
|
||||
label: text, city: text, region: text, country: text, countryCode: text,
|
||||
latitude: z.number().nullable(), longitude: z.number().nullable(),
|
||||
precision: z.enum(['city', 'region', 'country']).nullable(), verifiedAt: timestamp, provider: z.literal('mapbox').nullable(), providerPlaceId: text,
|
||||
});
|
||||
export const workspaceResponse = z.object({
|
||||
id: z.number().int(), name: z.string(), workspaceType: z.enum(['standard', 'rescue']), billingEmail: text,
|
||||
billingPlan: z.enum(['rescue_free', 'household_basic', 'household_plus', 'household_macaw', 'household_hyacinth_macaw']),
|
||||
billingInterval: z.enum(['monthly', 'yearly']),
|
||||
subscriptionStatus: z.enum(['active', 'trialing', 'past_due', 'canceled', 'unpaid', 'none']),
|
||||
stripeCustomerId: text, stripeSubscriptionId: text,
|
||||
rescueVerificationStatus: z.enum(['not_required', 'pending', 'approved', 'rejected']),
|
||||
createdAt: timestamp, updatedAt: timestamp,
|
||||
});
|
||||
export const memberResponse = z.object({
|
||||
id, workspaceId: z.number().int(), userId: id.nullable(), inviteEmail: z.string(), name: z.string(),
|
||||
role: workspaceRoleSchema, acceptedAt: timestamp.nullable(), createdAt: timestamp,
|
||||
});
|
||||
export const birdResponse = z.object({
|
||||
id, workspaceId: z.number().int(), name: z.string(), tagId: text, species: z.string(),
|
||||
motivators: text, demotivators: text, favoriteSnack: text, locationLabel: text,
|
||||
locationDetails: locationResponse.nullable(), vetClinicName: text, vetClinicAddress: text,
|
||||
vetAccountNumber: text, vetDoctorName: text, gender: birdGenderSchema,
|
||||
hatchDay: date.nullable(), dateOfBirth: date.nullable(), gotchaDay: date.nullable(), chartColor: z.string(),
|
||||
photoDataUrl: text.describe('Photo URL or legacy data URL. Storage-backed URLs expire; refresh the bird list to obtain a new URL.'),
|
||||
photoObjectKey: text, photoContentType: text, photoUpdatedAt: timestamp.nullable(),
|
||||
notifyOnDob: z.boolean(), notifyOnGotchaDay: z.boolean(), publicProfileCode: text, publicProfileEnabled: z.boolean(),
|
||||
memorializedAt: timestamp.nullable(), memorializedOn: date.nullable(), memorialNote: text,
|
||||
notifyOnMemorialDay: z.boolean(), createdAt: timestamp,
|
||||
latestWeightGrams: z.number().nullable(), latestRecordedOn: date.nullable(),
|
||||
});
|
||||
export const weightResponse = z.object({ id, birdId: id, weightGrams: z.number(), recordedOn: date, notes: text });
|
||||
export const vetVisitResponse = z.object({ id, birdId: id, visitedOn: date, clinicName: z.string(), reason: z.string(), notes: text });
|
||||
export const medicationResponse = z.object({
|
||||
id, birdId: id, name: z.string(), dosage: z.string(),
|
||||
frequency: z.enum(['once_daily', 'twice_daily', 'every_8_hours', 'every_6_hours', 'as_needed']),
|
||||
doseSchedule: z.array(z.object({ key: z.string(), label: z.string(), time: z.string() })),
|
||||
route: text, startDate: date, endDate: date.nullable(), notes: text, remindersEnabled: z.boolean(),
|
||||
});
|
||||
export const administrationResponse = z.object({
|
||||
id, medicationId: id, birdId: id, administeredOn: date, administrationSlot: z.string(),
|
||||
status: z.enum(['administered', 'missed']), notes: text, createdByUserId: id.nullable(), createdAt: timestamp,
|
||||
});
|
||||
export const noteResponse = z.object({
|
||||
id, workspaceId: z.number().int(), birdId: id.nullable(), birdName: text, title: z.string(), body: z.string(),
|
||||
createdByUserId: id.nullable(), createdByName: text, createdAt: timestamp, updatedAt: timestamp,
|
||||
});
|
||||
export const timelineResponse = z.object({
|
||||
id, birdId: id, eventType: z.enum(['profile_created', 'transferred', 'location_updated', 'owner_changed', 'manual_note', 'removed_from_flock', 'joined_flock']),
|
||||
fromWorkspaceId: z.number().int().nullable(), toWorkspaceId: z.number().int().nullable(),
|
||||
fromWorkspaceName: text, toWorkspaceName: text, fromOwnerEmail: text, toOwnerEmail: text,
|
||||
locationLabel: text, locationDetails: locationResponse.nullable(), note: text, eventDate: date,
|
||||
createdByUserId: id.nullable(), createdAt: timestamp,
|
||||
});
|
||||
@@ -0,0 +1,24 @@
|
||||
import type { Express } from 'express';
|
||||
import helmet from 'helmet';
|
||||
import swaggerUi from 'swagger-ui-express';
|
||||
import { customerOpenApi } from './openapi.js';
|
||||
|
||||
// Mount before application middleware so docs do not consume API rate limits.
|
||||
// Swagger assets and initialization are served locally; no external validator is used.
|
||||
export function mountApiDocs(app: Express) {
|
||||
app.get('/api/openapi.json', helmet(), (_req, res) => res.json(customerOpenApi));
|
||||
app.use('/api/docs', helmet({
|
||||
contentSecurityPolicy: { directives: {
|
||||
'script-src': ["'self'"],
|
||||
'connect-src': ["'self'"],
|
||||
// Keep local HTTP development usable; production transport is handled by the proxy.
|
||||
'upgrade-insecure-requests': null,
|
||||
} },
|
||||
}), swaggerUi.serve, swaggerUi.setup(undefined, {
|
||||
customSiteTitle: 'FlockPal API Reference',
|
||||
swaggerOptions: {
|
||||
url: '/api/openapi.json', validatorUrl: null, persistAuthorization: false,
|
||||
displayRequestDuration: true, docExpansion: 'none',
|
||||
},
|
||||
}));
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
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')));
|
||||
};
|
||||
@@ -0,0 +1,36 @@
|
||||
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 <reminder>/);
|
||||
assert.match(html, /Medication time for Kiwi & Peep/);
|
||||
assert.match(html, /a=1&b=2/);
|
||||
assert.match(html, /Open <FlockPal>/);
|
||||
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/);
|
||||
});
|
||||
@@ -0,0 +1,48 @@
|
||||
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 => ({
|
||||
'&': '&', '<': '<', '>': '>', '"': '"', "'": ''',
|
||||
})[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>`,
|
||||
});
|
||||
@@ -0,0 +1,60 @@
|
||||
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 & <Peep>/);
|
||||
assert.match(String(mail.html), /Our <Flock>/);
|
||||
assert.match(String(mail.html), /a=1&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;
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,44 @@
|
||||
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],
|
||||
};
|
||||
};
|
||||
@@ -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()]);
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
import { Queue, QueueEvents, type Job } from 'bullmq';
|
||||
|
||||
import { redisConnection } from './redisConnection.js';
|
||||
|
||||
export type AdoptionReportJobData = {
|
||||
birdId: string;
|
||||
workspaceId: number;
|
||||
transferCode: string;
|
||||
printFriendly: boolean;
|
||||
};
|
||||
|
||||
export type AdoptionReportJobResult = {
|
||||
pdfBase64: string;
|
||||
};
|
||||
|
||||
export const adoptionReportQueueName = 'adoption-reports';
|
||||
|
||||
export const adoptionReportQueue = new Queue<AdoptionReportJobData, AdoptionReportJobResult>(adoptionReportQueueName, {
|
||||
connection: redisConnection,
|
||||
defaultJobOptions: {
|
||||
attempts: 2,
|
||||
backoff: {
|
||||
type: 'exponential',
|
||||
delay: 10_000,
|
||||
},
|
||||
removeOnComplete: 50,
|
||||
removeOnFail: 500,
|
||||
},
|
||||
});
|
||||
|
||||
export const adoptionReportQueueEvents = new QueueEvents(adoptionReportQueueName, {
|
||||
connection: redisConnection,
|
||||
});
|
||||
|
||||
export const enqueueAdoptionReportJob = (
|
||||
data: AdoptionReportJobData,
|
||||
): Promise<Job<AdoptionReportJobData, AdoptionReportJobResult>> => adoptionReportQueue.add('render-adoption-report', data);
|
||||
|
||||
export const closeAdoptionReportQueue = async () => {
|
||||
await adoptionReportQueue.close();
|
||||
await adoptionReportQueueEvents.close();
|
||||
};
|
||||
@@ -0,0 +1,55 @@
|
||||
import { Queue, type Job } from 'bullmq';
|
||||
|
||||
import { redisConnection } from './redisConnection.js';
|
||||
|
||||
export type MedicationReminderJobData = {
|
||||
runDate: string;
|
||||
currentTime: string;
|
||||
requestedBy: 'scheduler';
|
||||
};
|
||||
|
||||
export type MedicationReminderJobResult = {
|
||||
runDate: string;
|
||||
currentTime: string;
|
||||
checked: number;
|
||||
sent: number;
|
||||
skipped: number;
|
||||
failed: number;
|
||||
};
|
||||
|
||||
export const medicationReminderQueueName = 'medication-reminders';
|
||||
|
||||
export const medicationReminderQueue = new Queue<MedicationReminderJobData, MedicationReminderJobResult>(medicationReminderQueueName, {
|
||||
connection: redisConnection,
|
||||
defaultJobOptions: {
|
||||
attempts: 3,
|
||||
backoff: {
|
||||
type: 'exponential',
|
||||
delay: 60_000,
|
||||
},
|
||||
removeOnComplete: 100,
|
||||
removeOnFail: 1_000,
|
||||
},
|
||||
});
|
||||
|
||||
export const enqueueMedicationReminderJob = (
|
||||
runDate: string,
|
||||
currentTime: string,
|
||||
): Promise<Job<MedicationReminderJobData, MedicationReminderJobResult>> =>
|
||||
medicationReminderQueue.add(
|
||||
'run-medication-reminders',
|
||||
{
|
||||
runDate,
|
||||
currentTime,
|
||||
requestedBy: 'scheduler',
|
||||
},
|
||||
{
|
||||
jobId: `medication-reminders-${runDate}-${currentTime.slice(0, 2)}`,
|
||||
},
|
||||
);
|
||||
|
||||
export const closeMedicationReminderQueue = async () => {
|
||||
await medicationReminderQueue.close();
|
||||
};
|
||||
|
||||
export const getMedicationReminderQueueCounts = () => medicationReminderQueue.getJobCounts('waiting', 'active', 'delayed', 'completed', 'failed');
|
||||
@@ -0,0 +1,42 @@
|
||||
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); };
|
||||
};
|
||||
@@ -0,0 +1,21 @@
|
||||
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;
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,5 @@
|
||||
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);
|
||||
@@ -0,0 +1,61 @@
|
||||
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);
|
||||
});
|
||||
@@ -0,0 +1,126 @@
|
||||
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;
|
||||
};
|
||||
@@ -0,0 +1,422 @@
|
||||
import fs from 'fs';
|
||||
import PDFDocument from 'pdfkit';
|
||||
import QRCode from 'qrcode';
|
||||
|
||||
import type { BirdRow, FlockNoteRow, VetVisitRow, WeightRow } from '../types.js';
|
||||
|
||||
type AdoptionReportInput = {
|
||||
bird: BirdRow;
|
||||
weights: WeightRow[];
|
||||
vetVisits: VetVisitRow[];
|
||||
notes: FlockNoteRow[];
|
||||
transferCode: string;
|
||||
birdPhotoBuffer?: Buffer | null;
|
||||
assets: {
|
||||
logoPath: string;
|
||||
wordmarkPath: string;
|
||||
defaultBirdPhotoPath: string;
|
||||
};
|
||||
printFriendly?: boolean;
|
||||
};
|
||||
|
||||
const page = { width: 612, height: 792, margin: 42 };
|
||||
|
||||
const colors = {
|
||||
ink: '#1f2a2a',
|
||||
muted: '#5d5f59',
|
||||
red: '#cb3a35',
|
||||
green: '#238a5a',
|
||||
blue: '#2769b3',
|
||||
border: '#cfe0d5',
|
||||
panel: '#fbf7ee',
|
||||
paper: '#fffdf9',
|
||||
};
|
||||
|
||||
const formatDate = (value: string | null) => {
|
||||
if (!value) {
|
||||
return 'Not recorded';
|
||||
}
|
||||
return new Intl.DateTimeFormat('en-US', { month: 'short', day: 'numeric', year: 'numeric', timeZone: 'UTC' }).format(
|
||||
new Date(`${value.slice(0, 10)}T00:00:00Z`),
|
||||
);
|
||||
};
|
||||
|
||||
const formatDateTime = (value: string | null) => {
|
||||
if (!value) {
|
||||
return 'Not recorded';
|
||||
}
|
||||
return new Intl.DateTimeFormat('en-US', { month: 'short', day: 'numeric', year: 'numeric' }).format(new Date(value));
|
||||
};
|
||||
|
||||
const formatShortDate = (value: string | null) => {
|
||||
if (!value) {
|
||||
return 'No data yet';
|
||||
}
|
||||
return new Intl.DateTimeFormat('en-US', { month: 'short', day: 'numeric', timeZone: 'UTC' }).format(new Date(`${value.slice(0, 10)}T00:00:00Z`));
|
||||
};
|
||||
|
||||
const formatWeight = (value: string | number | null) => {
|
||||
const numericValue = value === null ? null : Number(value);
|
||||
return numericValue && Number.isFinite(numericValue) ? `${numericValue.toFixed(1)} g` : 'Pending';
|
||||
};
|
||||
|
||||
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)';
|
||||
}
|
||||
if (value === 'male') {
|
||||
return 'Male (assumed)';
|
||||
}
|
||||
return 'Unknown';
|
||||
};
|
||||
|
||||
const parseList = (value: string | null) =>
|
||||
(value ?? '')
|
||||
.split(/\r?\n|,/)
|
||||
.map((entry) => entry.trim())
|
||||
.filter(Boolean);
|
||||
|
||||
const dataUrlToBuffer = (value: string | null) => {
|
||||
if (!value) {
|
||||
return null;
|
||||
}
|
||||
const match = value.match(/^data:image\/(?:png|jpeg|jpg);base64,(.+)$/);
|
||||
return match ? Buffer.from(match[1], 'base64') : null;
|
||||
};
|
||||
|
||||
const collectPdf = (doc: PDFKit.PDFDocument) =>
|
||||
new Promise<Buffer>((resolve, reject) => {
|
||||
const chunks: Buffer[] = [];
|
||||
doc.on('data', (chunk: Buffer) => chunks.push(chunk));
|
||||
doc.on('end', () => resolve(Buffer.concat(chunks)));
|
||||
doc.on('error', reject);
|
||||
});
|
||||
|
||||
const fitText = (doc: PDFKit.PDFDocument, text: string, x: number, y: number, width: number, options: PDFKit.Mixins.TextOptions = {}) => {
|
||||
doc.text(text, x, y, { width, lineGap: 1.5, ...options });
|
||||
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);
|
||||
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 });
|
||||
};
|
||||
|
||||
const drawTextCard = (doc: PDFKit.PDFDocument, label: string, value: string, x: number, y: number, width: number, height = 58) => {
|
||||
doc.roundedRect(x, y, width, height, 6).fillAndStroke(colors.panel, colors.border);
|
||||
doc.fillColor(colors.blue).fontSize(8).font('Helvetica-Bold').text(label.toUpperCase(), x + 8, y + 8, { width: width - 16 });
|
||||
doc.fillColor(colors.ink).fontSize(9.2).font('Helvetica').text(value, x + 8, y + 23, {
|
||||
width: width - 16,
|
||||
height: height - 31,
|
||||
ellipsis: true,
|
||||
lineGap: 1.2,
|
||||
});
|
||||
};
|
||||
|
||||
const drawSectionTitle = (doc: PDFKit.PDFDocument, title: string, y: number) => {
|
||||
doc.fillColor(colors.green).font('Helvetica-Bold').fontSize(14).text(title, page.margin, y);
|
||||
doc.moveTo(page.margin, y + 19).lineTo(page.width - page.margin, y + 19).strokeColor(colors.border).lineWidth(1).stroke();
|
||||
return y + 27;
|
||||
};
|
||||
|
||||
const drawSimpleWeightChart = (doc: PDFKit.PDFDocument, weights: WeightRow[], birdColor: string, x: number, y: number, width: number, height: number) => {
|
||||
const plottedWeights = weights
|
||||
.slice()
|
||||
.sort((left, right) => left.recorded_on.localeCompare(right.recorded_on))
|
||||
.map((entry) => ({ ...entry, numericWeight: Number(entry.weight_grams) }))
|
||||
.filter((entry) => Number.isFinite(entry.numericWeight));
|
||||
|
||||
doc.roundedRect(x, y, width, height, 8).fillAndStroke('#fffdf9', colors.border);
|
||||
|
||||
if (!plottedWeights.length) {
|
||||
doc.fillColor(colors.muted).fontSize(10).text('Add more weight records to show a trend graph.', x + 14, y + height / 2 - 6, {
|
||||
width: width - 28,
|
||||
align: 'center',
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const latestDate = new Date(`${plottedWeights[plottedWeights.length - 1].recorded_on.slice(0, 10)}T00:00:00Z`);
|
||||
const startDate = new Date(latestDate);
|
||||
startDate.setUTCDate(startDate.getUTCDate() - 29);
|
||||
const visibleWeights = plottedWeights.filter((entry) => {
|
||||
const recordedOn = new Date(`${entry.recorded_on.slice(0, 10)}T00:00:00Z`);
|
||||
return recordedOn >= startDate && recordedOn <= latestDate;
|
||||
});
|
||||
const rawMinWeight = Math.min(...visibleWeights.map((entry) => entry.numericWeight));
|
||||
const rawMaxWeight = Math.max(...visibleWeights.map((entry) => entry.numericWeight));
|
||||
const rangePadding = Math.max((rawMaxWeight - rawMinWeight) * 0.12, 2);
|
||||
const minWeight = Math.max(0, rawMinWeight - rangePadding);
|
||||
const maxWeight = rawMaxWeight + rangePadding;
|
||||
const weightRange = Math.max(1, maxWeight - minWeight);
|
||||
const padding = { top: 16, right: 18, bottom: 32, left: 48 };
|
||||
const plotWidth = width - padding.left - padding.right;
|
||||
const plotHeight = height - padding.top - padding.bottom;
|
||||
const startMs = startDate.getTime();
|
||||
const endMs = latestDate.getTime();
|
||||
const dateRange = Math.max(endMs - startMs, 24 * 60 * 60 * 1000);
|
||||
const chartColor = /^#[0-9a-fA-F]{6}$/.test(birdColor) ? birdColor : colors.green;
|
||||
const midWeight = minWeight + (maxWeight - minWeight) / 2;
|
||||
const midDate = new Date((startMs + endMs) / 2);
|
||||
const yTicks = [
|
||||
{ label: `${maxWeight.toFixed(0)} g`, y: y + padding.top },
|
||||
{ label: `${midWeight.toFixed(0)} g`, y: y + padding.top + plotHeight / 2 },
|
||||
{ label: `${minWeight.toFixed(0)} g`, y: y + padding.top + plotHeight },
|
||||
];
|
||||
const xTicks = [
|
||||
{ label: formatShortDate(startDate.toISOString().slice(0, 10)), x: x + padding.left },
|
||||
{ label: formatShortDate(midDate.toISOString().slice(0, 10)), x: x + padding.left + plotWidth / 2 },
|
||||
{ label: formatShortDate(latestDate.toISOString().slice(0, 10)), x: x + padding.left + plotWidth },
|
||||
];
|
||||
|
||||
const points = visibleWeights.map((entry) => {
|
||||
const recordedOn = new Date(`${entry.recorded_on.slice(0, 10)}T00:00:00Z`);
|
||||
return {
|
||||
...entry,
|
||||
x: x + padding.left + ((recordedOn.getTime() - startMs) / dateRange) * plotWidth,
|
||||
y: y + padding.top + (1 - (entry.numericWeight - minWeight) / weightRange) * plotHeight,
|
||||
};
|
||||
});
|
||||
|
||||
doc.font('Helvetica').fontSize(7).fillColor(colors.muted);
|
||||
yTicks.forEach((tick) => {
|
||||
doc.text(tick.label, x + 4, tick.y - 3, { width: padding.left - 12, align: 'right' });
|
||||
doc
|
||||
.save()
|
||||
.dash(4, { space: 6 })
|
||||
.strokeColor('#d8e5ef')
|
||||
.lineWidth(0.8)
|
||||
.moveTo(x + padding.left, tick.y)
|
||||
.lineTo(x + width - padding.right, tick.y)
|
||||
.stroke()
|
||||
.restore();
|
||||
});
|
||||
doc.strokeColor('#c7cdca').lineWidth(1).moveTo(x + padding.left, y + padding.top + plotHeight).lineTo(x + width - padding.right, y + padding.top + plotHeight).stroke();
|
||||
xTicks.forEach((tick) => {
|
||||
doc.fillColor(colors.muted).fontSize(7).text(tick.label, tick.x - 28, y + height - 18, { width: 56, align: 'center' });
|
||||
});
|
||||
|
||||
points.forEach((entry, index) => {
|
||||
if (index === 0) {
|
||||
doc.moveTo(entry.x, entry.y);
|
||||
} else {
|
||||
doc.lineTo(entry.x, entry.y);
|
||||
}
|
||||
});
|
||||
if (points.length > 1) {
|
||||
doc.lineCap('round').strokeColor(chartColor).lineWidth(2.4).stroke();
|
||||
}
|
||||
|
||||
points.forEach((entry) => {
|
||||
doc.circle(entry.x, entry.y, 3.5).fillAndStroke(chartColor, '#fffdf9');
|
||||
});
|
||||
|
||||
const latestPoint = points[points.length - 1];
|
||||
const calloutOnLeft = latestPoint.x > x + width - padding.right - 84;
|
||||
const calloutX = calloutOnLeft ? latestPoint.x - 82 : latestPoint.x + 8;
|
||||
const calloutY = latestPoint.y < y + padding.top + 18 ? latestPoint.y + 8 : latestPoint.y - 22;
|
||||
doc.roundedRect(calloutX, calloutY, 74, 18, 5).fillAndStroke('#fffdf9', '#d9dedb');
|
||||
doc.fillColor(colors.ink).font('Helvetica-Bold').fontSize(7.5).text(`Latest ${formatWeight(latestPoint.numericWeight)}`, calloutX + 5, calloutY + 5, {
|
||||
width: 64,
|
||||
align: 'center',
|
||||
});
|
||||
};
|
||||
|
||||
const drawTable = (doc: PDFKit.PDFDocument, headers: string[], rows: string[][], x: number, y: number, widths: number[], rowHeight = 28) => {
|
||||
doc.font('Helvetica-Bold').fontSize(8).fillColor(colors.muted);
|
||||
headers.forEach((header, index) => {
|
||||
doc.text(header.toUpperCase(), x + widths.slice(0, index).reduce((sum, value) => sum + value, 0), y, { width: widths[index] - 8 });
|
||||
});
|
||||
y += 15;
|
||||
doc.moveTo(x, y - 4).lineTo(x + widths.reduce((sum, value) => sum + value, 0), y - 4).strokeColor(colors.border).stroke();
|
||||
|
||||
doc.font('Helvetica').fontSize(8.5).fillColor(colors.ink);
|
||||
rows.forEach((row) => {
|
||||
if (y + rowHeight > page.height - page.margin) {
|
||||
doc.addPage();
|
||||
y = page.margin;
|
||||
}
|
||||
row.forEach((value, index) => {
|
||||
doc.text(value, x + widths.slice(0, index).reduce((sum, columnWidth) => sum + columnWidth, 0), y, {
|
||||
width: widths[index] - 8,
|
||||
height: rowHeight - 6,
|
||||
ellipsis: true,
|
||||
});
|
||||
});
|
||||
y += rowHeight;
|
||||
doc.moveTo(x, y - 4).lineTo(x + widths.reduce((sum, value) => sum + value, 0), y - 4).strokeColor(colors.border).stroke();
|
||||
});
|
||||
|
||||
return y + 6;
|
||||
};
|
||||
|
||||
export const renderAdoptionReportPdf = async ({
|
||||
bird,
|
||||
weights,
|
||||
vetVisits,
|
||||
notes,
|
||||
transferCode,
|
||||
birdPhotoBuffer = null,
|
||||
assets,
|
||||
printFriendly = false,
|
||||
}: AdoptionReportInput) => {
|
||||
const doc = new PDFDocument({
|
||||
size: 'LETTER',
|
||||
margin: page.margin,
|
||||
info: { Title: `FlockPal Adoption Report - ${bird.name}`, Author: 'FlockPal', Subject: `Adoption report for ${bird.name}` },
|
||||
});
|
||||
const output = collectPdf(doc);
|
||||
|
||||
if (!printFriendly) {
|
||||
doc.rect(0, 0, page.width, page.height).fill(colors.paper);
|
||||
}
|
||||
|
||||
const logoPath = fs.existsSync(assets.logoPath) ? assets.logoPath : null;
|
||||
const wordmarkPath = fs.existsSync(assets.wordmarkPath) ? assets.wordmarkPath : logoPath;
|
||||
const defaultPhotoPath = fs.existsSync(assets.defaultBirdPhotoPath) ? assets.defaultBirdPhotoPath : null;
|
||||
const photoBuffer = birdPhotoBuffer ?? dataUrlToBuffer(bird.photo_data_url);
|
||||
const contentWidth = page.width - page.margin * 2;
|
||||
const headerY = page.margin;
|
||||
const headerHeight = 136;
|
||||
|
||||
doc.roundedRect(page.margin, headerY, contentWidth, headerHeight, 12).fillAndStroke(printFriendly ? '#ffffff' : '#f8f4e8', colors.border);
|
||||
if (logoPath) {
|
||||
doc.image(logoPath, page.margin + 10, headerY + 18, { fit: [92, 84], align: 'center', valign: 'center' });
|
||||
}
|
||||
|
||||
const photoX = page.margin + 235;
|
||||
const photoY = headerY + 13;
|
||||
if (photoBuffer) {
|
||||
doc.image(photoBuffer, photoX, photoY, { fit: [58, 58], align: 'center', valign: 'center' });
|
||||
} else if (defaultPhotoPath) {
|
||||
doc.image(defaultPhotoPath, photoX, photoY, { fit: [58, 58], align: 'center', valign: 'center' });
|
||||
}
|
||||
doc.roundedRect(photoX, photoY, 58, 58, 10).strokeColor('#ffffff').lineWidth(2).stroke();
|
||||
doc.fillColor(colors.red).font('Helvetica-Bold').fontSize(22).text(bird.name, page.margin + 140, headerY + 75, { width: 250, align: 'center' });
|
||||
doc.fillColor(colors.muted).font('Helvetica').fontSize(9).text('Adoption Report', page.margin + 140, headerY + 98, { width: 250, align: 'center' });
|
||||
|
||||
const qrDataUrl = await QRCode.toDataURL(transferCode, { margin: 1, width: 96, errorCorrectionLevel: 'H' });
|
||||
const qrBuffer = dataUrlToBuffer(qrDataUrl);
|
||||
const qrX = page.width - page.margin - 132;
|
||||
const qrWidth = 124;
|
||||
doc.fillColor(colors.green).font('Helvetica-Bold').fontSize(8).text('JOIN', qrX, headerY + 7, { width: qrWidth, align: 'center' });
|
||||
if (wordmarkPath) {
|
||||
doc.image(wordmarkPath, qrX + 7, headerY + 18, { fit: [110, 34], align: 'center', valign: 'center' });
|
||||
}
|
||||
doc.fillColor(colors.red).font('Helvetica-Bold').fontSize(7.5).text('Keep my story growing', qrX, headerY + 51, {
|
||||
width: qrWidth,
|
||||
align: 'center',
|
||||
});
|
||||
if (qrBuffer) {
|
||||
doc.image(qrBuffer, qrX + 37, headerY + 62, { width: 50 });
|
||||
}
|
||||
doc.fillColor(colors.green).font('Helvetica-Bold').fontSize(6.8).text('Scan to continue tracking in FlockPal', qrX, headerY + 114, {
|
||||
width: qrWidth,
|
||||
align: 'center',
|
||||
});
|
||||
doc.fillColor(colors.ink).font('Helvetica').fontSize(6.5).text(transferCode, qrX, headerY + 126, { width: qrWidth, align: 'center' });
|
||||
|
||||
let y = headerY + headerHeight + 16;
|
||||
const factGap = 8;
|
||||
const factWidth = (contentWidth - factGap) / 2;
|
||||
const facts = [
|
||||
['Species', bird.species],
|
||||
['Band/tag ID', bird.tag_id || 'Not recorded'],
|
||||
['Sex', genderLabel(bird.gender)],
|
||||
['Hatch day', formatDate(bird.date_of_birth)],
|
||||
['Favorite snack', bird.favorite_snack || 'Not recorded'],
|
||||
['Latest weight', bird.latest_weight_grams ? `${formatWeight(bird.latest_weight_grams)}${bird.latest_recorded_on ? ` on ${formatDate(bird.latest_recorded_on)}` : ''}` : 'Pending'],
|
||||
];
|
||||
facts.forEach(([label, value], index) => {
|
||||
drawFact(doc, label, value, page.margin + (index % 2) * (factWidth + factGap), y + Math.floor(index / 2) * 50, factWidth);
|
||||
});
|
||||
y += Math.ceil(facts.length / 2) * 50 + 8;
|
||||
|
||||
const motivators = parseList(bird.motivators);
|
||||
const demotivators = parseList(bird.demotivators);
|
||||
drawTextCard(doc, 'Motivators', motivators.length ? motivators.join(', ') : 'Not recorded', page.margin, y, factWidth);
|
||||
drawTextCard(
|
||||
doc,
|
||||
'Demotivators',
|
||||
demotivators.length ? demotivators.join(', ') : 'Not recorded',
|
||||
page.margin + factWidth + factGap,
|
||||
y,
|
||||
factWidth,
|
||||
);
|
||||
y += 72;
|
||||
|
||||
if (y > 610) {
|
||||
doc.addPage();
|
||||
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;
|
||||
|
||||
y = drawSectionTitle(doc, 'Vet Visit History', y);
|
||||
y = drawTable(
|
||||
doc,
|
||||
['Date', 'Clinic', 'Reason', 'Notes'],
|
||||
vetVisits.length ? vetVisits.map((visit) => [formatDate(visit.visited_on), visit.clinic_name, visit.reason, visit.notes || '']) : [['No vet visits recorded.', '', '', '']],
|
||||
page.margin,
|
||||
y,
|
||||
[70, 115, 120, contentWidth - 305],
|
||||
28,
|
||||
);
|
||||
|
||||
if (y > 575) {
|
||||
doc.addPage();
|
||||
y = page.margin;
|
||||
}
|
||||
y = drawSectionTitle(doc, 'Weight Graph', y);
|
||||
drawSimpleWeightChart(doc, weights, bird.chart_color, page.margin, y, contentWidth, 120);
|
||||
y += 140;
|
||||
|
||||
y = drawSectionTitle(doc, 'Weight History', y);
|
||||
y = drawTable(
|
||||
doc,
|
||||
['Date', 'Weight', 'Notes'],
|
||||
weights.length ? weights.map((entry) => [formatDate(entry.recorded_on), formatWeight(entry.weight_grams), entry.notes || '']) : [['No weights recorded.', '', '']],
|
||||
page.margin,
|
||||
y,
|
||||
[95, 70, contentWidth - 165],
|
||||
24,
|
||||
);
|
||||
|
||||
if (notes.length) {
|
||||
if (y > 635) {
|
||||
doc.addPage();
|
||||
y = page.margin;
|
||||
}
|
||||
y = drawSectionTitle(doc, 'Notes', y);
|
||||
notes.slice(0, 8).forEach((note) => {
|
||||
if (y > page.height - page.margin - 48) {
|
||||
doc.addPage();
|
||||
y = page.margin;
|
||||
}
|
||||
doc.fillColor(colors.muted).font('Helvetica-Bold').fontSize(8).text(formatDateTime(note.updated_at), page.margin, y);
|
||||
y = fitText(doc, note.body, page.margin, y + 12, contentWidth, { height: 44, ellipsis: true });
|
||||
y += 8;
|
||||
doc.moveTo(page.margin, y).lineTo(page.width - page.margin, y).strokeColor(colors.border).stroke();
|
||||
y += 8;
|
||||
});
|
||||
}
|
||||
|
||||
doc.end();
|
||||
return output;
|
||||
};
|
||||
@@ -0,0 +1,99 @@
|
||||
import path from 'path';
|
||||
import sharp from 'sharp';
|
||||
|
||||
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';
|
||||
import { renderAdoptionReportPdf } from './adoptionReport.js';
|
||||
|
||||
const adoptionReportWeightHistoryDays = 14;
|
||||
|
||||
const parseDataImage = (value: string | null) => {
|
||||
if (!value) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const match = value.match(/^data:image\/(?:png|jpeg|jpg|webp|gif);base64,(.+)$/);
|
||||
return match ? Buffer.from(match[1], 'base64') : null;
|
||||
};
|
||||
|
||||
const normalizeReportPhotoBuffer = async (imageBuffer: Buffer | null) => {
|
||||
if (!imageBuffer) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
return await sharp(imageBuffer).rotate().png().toBuffer();
|
||||
} catch (error) {
|
||||
console.warn('Unable to normalize bird photo for adoption report:', error);
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
const loadBirdReportPhotoBuffer = async (bird: BirdRow) => {
|
||||
if (!bird.photo_object_key) {
|
||||
return normalizeReportPhotoBuffer(parseDataImage(bird.photo_data_url));
|
||||
}
|
||||
|
||||
const s3Config = getS3ImageStorageConfig();
|
||||
|
||||
if (!s3Config) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const signedUrl = getSignedS3ObjectUrl({
|
||||
config: s3Config,
|
||||
objectKey: bird.photo_object_key,
|
||||
expiresInSeconds: 5 * 60,
|
||||
});
|
||||
const imageResponse = await fetch(signedUrl);
|
||||
|
||||
if (!imageResponse.ok) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return normalizeReportPhotoBuffer(Buffer.from(await imageResponse.arrayBuffer()));
|
||||
};
|
||||
|
||||
export const renderAdoptionReportForBird = async ({
|
||||
birdId,
|
||||
workspaceId,
|
||||
transferCode,
|
||||
printFriendly,
|
||||
}: {
|
||||
birdId: string;
|
||||
workspaceId: number;
|
||||
transferCode: string;
|
||||
printFriendly: boolean;
|
||||
}) => {
|
||||
const bird = await getBirdById(birdId, workspaceId);
|
||||
|
||||
if (!bird) {
|
||||
throw new Error('Bird not found.');
|
||||
}
|
||||
|
||||
const [weights, vetVisits, notes, birdPhotoBuffer] = await Promise.all([
|
||||
listWeightsForBird(bird.id, workspaceId, adoptionReportWeightHistoryDays),
|
||||
listVetVisitsForBird(bird.id, workspaceId),
|
||||
listFlockNotes(workspaceId),
|
||||
loadBirdReportPhotoBuffer(bird),
|
||||
]);
|
||||
const birdNotes = notes.filter((note) => note.bird_id === bird.id);
|
||||
|
||||
return renderAdoptionReportPdf({
|
||||
bird,
|
||||
weights,
|
||||
vetVisits,
|
||||
notes: birdNotes,
|
||||
transferCode,
|
||||
birdPhotoBuffer,
|
||||
printFriendly,
|
||||
assets: {
|
||||
logoPath: path.join(process.cwd(), 'assets', 'flockpal-logo.png'),
|
||||
wordmarkPath: path.join(process.cwd(), 'assets', 'flockpal-text.png'),
|
||||
defaultBirdPhotoPath: path.join(process.cwd(), 'assets', 'yoda-default.png'),
|
||||
},
|
||||
});
|
||||
};
|
||||
@@ -0,0 +1,133 @@
|
||||
import { db } from '../db/client.js';
|
||||
import type { AuditLogEntryRow, AuthContext, FlockNoteRow } from '../types.js';
|
||||
|
||||
type AuditLogInput = {
|
||||
workspaceId: number;
|
||||
auth?: AuthContext;
|
||||
action: string;
|
||||
entityType: string;
|
||||
entityId?: string | null;
|
||||
entityName?: string | null;
|
||||
details?: Record<string, unknown>;
|
||||
};
|
||||
|
||||
export const createAuditLogEntry = async ({
|
||||
workspaceId,
|
||||
auth,
|
||||
action,
|
||||
entityType,
|
||||
entityId = null,
|
||||
entityName = null,
|
||||
details = {},
|
||||
}: AuditLogInput) => {
|
||||
const result = await db.query<AuditLogEntryRow>(
|
||||
`INSERT INTO audit_log_entries (workspace_id, user_id, actor_name, actor_email, action, entity_type, entity_id, entity_name, details)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)
|
||||
RETURNING id, workspace_id, user_id, actor_name, actor_email, action, entity_type, entity_id, entity_name, details, created_at`,
|
||||
[
|
||||
workspaceId,
|
||||
auth?.user.id ?? null,
|
||||
auth?.user.name ?? null,
|
||||
auth?.user.email ?? null,
|
||||
action,
|
||||
entityType,
|
||||
entityId,
|
||||
entityName,
|
||||
JSON.stringify(details),
|
||||
],
|
||||
);
|
||||
|
||||
return result.rows[0] ?? null;
|
||||
};
|
||||
|
||||
export const listAuditLogEntries = async (workspaceId: number, limit = 100) => {
|
||||
const result = await db.query<AuditLogEntryRow>(
|
||||
`SELECT id, workspace_id, user_id, actor_name, actor_email, action, entity_type, entity_id, entity_name, details, created_at
|
||||
FROM audit_log_entries
|
||||
WHERE workspace_id = $1
|
||||
ORDER BY created_at DESC
|
||||
LIMIT $2`,
|
||||
[workspaceId, limit],
|
||||
);
|
||||
|
||||
return result.rows;
|
||||
};
|
||||
|
||||
export const listFlockNotes = async (workspaceId: number) => {
|
||||
const result = await db.query<FlockNoteRow>(
|
||||
`SELECT flock_notes.id,
|
||||
flock_notes.workspace_id,
|
||||
flock_notes.bird_id,
|
||||
birds.name AS bird_name,
|
||||
flock_notes.title,
|
||||
flock_notes.body,
|
||||
flock_notes.created_by_user_id,
|
||||
users.name AS created_by_name,
|
||||
flock_notes.created_at,
|
||||
flock_notes.updated_at
|
||||
FROM flock_notes
|
||||
LEFT JOIN birds ON birds.id = flock_notes.bird_id
|
||||
LEFT JOIN users ON users.id = flock_notes.created_by_user_id
|
||||
WHERE flock_notes.workspace_id = $1
|
||||
ORDER BY flock_notes.updated_at DESC`,
|
||||
[workspaceId],
|
||||
);
|
||||
|
||||
return result.rows;
|
||||
};
|
||||
|
||||
export const createFlockNote = async ({
|
||||
workspaceId,
|
||||
birdId,
|
||||
body,
|
||||
createdByUserId,
|
||||
}: {
|
||||
workspaceId: number;
|
||||
birdId: string | null;
|
||||
body: string;
|
||||
createdByUserId: string | null;
|
||||
}) => {
|
||||
const title = body.split(/\s+/).join(' ').slice(0, 160) || 'Note';
|
||||
const result = await db.query<FlockNoteRow>(
|
||||
`WITH inserted_note AS (
|
||||
INSERT INTO flock_notes (workspace_id, bird_id, title, body, created_by_user_id)
|
||||
SELECT $1, $2, $3, $4, $5
|
||||
WHERE $2::uuid IS NULL
|
||||
OR EXISTS (
|
||||
SELECT 1
|
||||
FROM birds
|
||||
WHERE birds.id = $2
|
||||
AND birds.workspace_id = $1
|
||||
)
|
||||
RETURNING id, workspace_id, bird_id, title, body, created_by_user_id, created_at, updated_at
|
||||
)
|
||||
SELECT inserted_note.id,
|
||||
inserted_note.workspace_id,
|
||||
inserted_note.bird_id,
|
||||
birds.name AS bird_name,
|
||||
inserted_note.title,
|
||||
inserted_note.body,
|
||||
inserted_note.created_by_user_id,
|
||||
users.name AS created_by_name,
|
||||
inserted_note.created_at,
|
||||
inserted_note.updated_at
|
||||
FROM inserted_note
|
||||
LEFT JOIN birds ON birds.id = inserted_note.bird_id
|
||||
LEFT JOIN users ON users.id = inserted_note.created_by_user_id`,
|
||||
[workspaceId, birdId, title, body, createdByUserId],
|
||||
);
|
||||
|
||||
return result.rows[0] ?? null;
|
||||
};
|
||||
|
||||
export const deleteFlockNote = async (noteId: string, workspaceId: number) => {
|
||||
const result = await db.query<{ id: string; title: string }>(
|
||||
`DELETE FROM flock_notes
|
||||
WHERE id = $1
|
||||
AND workspace_id = $2
|
||||
RETURNING id, title`,
|
||||
[noteId, workspaceId],
|
||||
);
|
||||
|
||||
return result.rows[0] ?? null;
|
||||
};
|
||||
@@ -0,0 +1,47 @@
|
||||
import { db } from '../db/client.js';
|
||||
import type { BehaviorInput, BehaviorType, BehaviorOccurrence } from '../behaviorSchemas.js';
|
||||
|
||||
const typeFields = `id, name, description, created_at AS "createdAt"`;
|
||||
const occurrenceFields = `o.id, o.bird_id AS "birdId", o.behavior_type_id AS "behaviorTypeId",
|
||||
t.name AS "behaviorName", o.occurred_at AS "occurredAt", o.duration_seconds AS "durationSeconds",
|
||||
o.severity, o.notes, o.created_at AS "createdAt", o.updated_at AS "updatedAt"`;
|
||||
|
||||
export async function listBehaviorTypes(workspaceId: number, birdId: string) {
|
||||
// Include types used by this bird before a flock transfer, without exposing other flock types.
|
||||
return (await db.query<BehaviorType>(`SELECT ${typeFields} FROM behavior_types t
|
||||
WHERE is_default OR workspace_id = $1 OR EXISTS (
|
||||
SELECT 1 FROM behavior_occurrences o JOIN birds b ON b.id = o.bird_id
|
||||
WHERE o.behavior_type_id = t.id AND b.id = $2 AND b.workspace_id = $1)
|
||||
ORDER BY name`, [workspaceId, birdId])).rows;
|
||||
}
|
||||
export async function createBehaviorType(workspaceId: number, name: string, description?: string | null) {
|
||||
return (await db.query<BehaviorType>(`INSERT INTO behavior_types (workspace_id, name, description) VALUES ($1, $2, $3)
|
||||
ON CONFLICT (workspace_id, lower(name)) WHERE workspace_id IS NOT NULL
|
||||
DO UPDATE SET name = behavior_types.name RETURNING ${typeFields}`, [workspaceId, name, description || null])).rows[0];
|
||||
}
|
||||
export async function listBehaviorOccurrences(birdId: string, workspaceId: number, from: string, to: string, typeId?: string) {
|
||||
return (await db.query<BehaviorOccurrence>(`SELECT ${occurrenceFields} FROM behavior_occurrences o
|
||||
JOIN birds b ON b.id = o.bird_id JOIN behavior_types t ON t.id = o.behavior_type_id
|
||||
WHERE b.id = $1 AND b.workspace_id = $2 AND o.occurred_at >= $3 AND o.occurred_at < $4
|
||||
AND ($5::uuid IS NULL OR o.behavior_type_id = $5) ORDER BY o.occurred_at DESC, o.id`,
|
||||
[birdId, workspaceId, from, to, typeId || null])).rows;
|
||||
}
|
||||
export async function saveBehaviorOccurrence(birdId: string, workspaceId: number, input: BehaviorInput, id?: string) {
|
||||
const params = [birdId, workspaceId, input.behaviorTypeId, input.occurredAt, input.durationSeconds ?? null, input.severity ?? null, input.notes || null];
|
||||
// Keep authorization in the mutation as well as the route to protect against concurrent transfers.
|
||||
const allowed = `EXISTS (SELECT 1 FROM birds b WHERE b.id = $1 AND b.workspace_id = $2 AND b.memorialized_at IS NULL)
|
||||
AND EXISTS (SELECT 1 FROM behavior_types t WHERE t.id = $3 AND
|
||||
(t.is_default OR t.workspace_id = $2 OR EXISTS
|
||||
(SELECT 1 FROM behavior_occurrences previous WHERE previous.bird_id = $1 AND previous.behavior_type_id = t.id)))`;
|
||||
const mutation = id
|
||||
? `UPDATE behavior_occurrences SET behavior_type_id = $3, occurred_at = $4, duration_seconds = $5,
|
||||
severity = $6, notes = $7, updated_at = CURRENT_TIMESTAMP WHERE bird_id = $1 AND id = $8 AND ${allowed} RETURNING *`
|
||||
: `INSERT INTO behavior_occurrences (bird_id, behavior_type_id, occurred_at, duration_seconds, severity, notes)
|
||||
SELECT $1, $3, $4, $5, $6, $7 WHERE ${allowed} RETURNING *`;
|
||||
return (await db.query<BehaviorOccurrence>(`WITH saved AS (${mutation}) SELECT ${occurrenceFields}
|
||||
FROM saved o JOIN behavior_types t ON t.id = o.behavior_type_id`, id ? [...params, id] : params)).rows[0];
|
||||
}
|
||||
export async function deleteBehaviorOccurrence(birdId: string, workspaceId: number, id: string) {
|
||||
return (await db.query<{ id: string }>(`DELETE FROM behavior_occurrences o USING birds b WHERE o.bird_id = b.id
|
||||
AND b.id = $1 AND b.workspace_id = $2 AND b.memorialized_at IS NULL AND o.id = $3 RETURNING o.id`, [birdId, workspaceId, id])).rows[0];
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
import { db } from '../db/client.js';
|
||||
|
||||
// Only reveal whether an exact normalized band match is available, never its profile or former flock.
|
||||
export async function hasUnassignedBird(tagId: string): Promise<boolean> {
|
||||
const result = await db.query<{ id: string }>(
|
||||
`SELECT id FROM birds WHERE workspace_id IS NULL AND memorialized_at IS NULL
|
||||
AND LOWER(BTRIM(tag_id)) = LOWER(BTRIM($1)) LIMIT 1`, [tagId],
|
||||
);
|
||||
return result.rows.length > 0;
|
||||
}
|
||||
|
||||
export async function removeBirdFromFlock(birdId: string, workspaceId: number, userId: string): Promise<boolean> {
|
||||
return db.transaction(async (client) => {
|
||||
const result = await client.query<{ id: string }>(
|
||||
`UPDATE birds SET workspace_id = NULL, public_profile_enabled = FALSE
|
||||
WHERE id = $1 AND workspace_id = $2 AND memorialized_at IS NULL RETURNING id`, [birdId, workspaceId],
|
||||
);
|
||||
if (!result.rows.length) return false;
|
||||
await client.query(`UPDATE flock_notes SET workspace_id = NULL WHERE bird_id = $1`, [birdId]);
|
||||
await client.query(`UPDATE bird_transfer_codes SET revoked_at = CURRENT_TIMESTAMP
|
||||
WHERE bird_id = $1 AND completed_at IS NULL AND revoked_at IS NULL`, [birdId]);
|
||||
await client.query(`DELETE FROM pending_bird_transfers WHERE bird_id = $1 AND completed_at IS NULL`, [birdId]);
|
||||
await client.query(`INSERT INTO bird_timeline_events
|
||||
(bird_id, event_type, from_workspace_id, from_workspace_name, note, created_by_user_id)
|
||||
SELECT $1, 'removed_from_flock', id, name, 'Removed from flock; profile and history retained.', $3
|
||||
FROM workspaces WHERE id = $2`, [birdId, workspaceId, userId]);
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
export async function claimUnassignedBird(tagId: string, workspaceId: number, userId: string): Promise<string | null> {
|
||||
return db.transaction(async (client) => {
|
||||
// The row lock and repeated unassigned predicate prevent competing flocks from claiming the same bird.
|
||||
const match = await client.query<{ id: string }>(
|
||||
`SELECT id FROM birds WHERE workspace_id IS NULL AND memorialized_at IS NULL
|
||||
AND LOWER(BTRIM(tag_id)) = LOWER(BTRIM($1)) FOR UPDATE`, [tagId],
|
||||
);
|
||||
if (!match.rows.length) return null;
|
||||
const birdId = match.rows[0].id;
|
||||
const claimed = await client.query(`UPDATE birds SET workspace_id = $2, public_profile_enabled = FALSE
|
||||
WHERE id = $1 AND workspace_id IS NULL RETURNING id`, [birdId, workspaceId]);
|
||||
if (!claimed.rows.length) return null;
|
||||
await client.query(`UPDATE flock_notes SET workspace_id = $2 WHERE bird_id = $1 AND workspace_id IS NULL`, [birdId, workspaceId]);
|
||||
await client.query(`INSERT INTO bird_timeline_events
|
||||
(bird_id, event_type, to_workspace_id, to_workspace_name, note, created_by_user_id)
|
||||
SELECT $1, 'joined_flock', id, name, 'Added by matching band ID; existing profile and history retained.', $3
|
||||
FROM workspaces WHERE id = $2`, [birdId, workspaceId, userId]);
|
||||
return birdId;
|
||||
});
|
||||
}
|
||||
@@ -6,7 +6,9 @@ import {
|
||||
createBird,
|
||||
createPendingBirdTransfer,
|
||||
getBirdById,
|
||||
getOpenBirdTransferCode,
|
||||
listWeightsForBird,
|
||||
markBirdTransferCodeCompleted,
|
||||
transferBirdToWorkspace,
|
||||
} from './birdRepository.js';
|
||||
import { mockDb } from '../test/mockDb.js';
|
||||
@@ -31,6 +33,9 @@ test('createBird returns the inserted bird row', async () => {
|
||||
name: 'Kiwi',
|
||||
tag_id: 'A-1',
|
||||
species: 'Cockatiel',
|
||||
motivators: 'Step-up practice',
|
||||
demotivators: 'Vacuum noise',
|
||||
favorite_snack: 'Millet',
|
||||
gender: 'female',
|
||||
date_of_birth: null,
|
||||
gotcha_day: null,
|
||||
@@ -50,6 +55,9 @@ test('createBird returns the inserted bird row', async () => {
|
||||
name: 'Kiwi',
|
||||
tagId: 'A-1',
|
||||
species: 'Cockatiel',
|
||||
motivators: 'Step-up practice',
|
||||
demotivators: 'Vacuum noise',
|
||||
favoriteSnack: 'Millet',
|
||||
gender: 'female',
|
||||
dateOfBirth: null,
|
||||
gotchaDay: null,
|
||||
@@ -62,6 +70,7 @@ test('createBird returns the inserted bird row', async () => {
|
||||
assert.equal(bird?.name, 'Kiwi');
|
||||
assert.equal(bird?.workspace_id, 10);
|
||||
assert.equal(bird?.gender, 'female');
|
||||
assert.equal(bird?.favorite_snack, 'Millet');
|
||||
});
|
||||
|
||||
test('listWeightsForBird scopes by bird, workspace, and day window', async () => {
|
||||
@@ -181,6 +190,46 @@ 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);
|
||||
@@ -190,4 +239,41 @@ 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('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/);
|
||||
});
|
||||
@@ -5,9 +5,14 @@ import type {
|
||||
BirdMilestoneReminderDeliveryRow,
|
||||
BirdMilestoneReminderType,
|
||||
BirdRow,
|
||||
BirdTimelineEventRow,
|
||||
BirdTimelineEventType,
|
||||
BirdTransferCodeRow,
|
||||
LostBirdMatchRow,
|
||||
MedicationAdministrationRow,
|
||||
MedicationDoseScheduleItem,
|
||||
MedicationReminderCandidateRow,
|
||||
MedicationReminderDeliveryRow,
|
||||
MedicationRow,
|
||||
PendingBirdTransferRow,
|
||||
VetVisitRow,
|
||||
@@ -20,6 +25,15 @@ const birdSelectFields = `
|
||||
birds.name,
|
||||
birds.tag_id,
|
||||
birds.species,
|
||||
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,
|
||||
birds.vet_doctor_name,
|
||||
birds.gender,
|
||||
birds.date_of_birth::text,
|
||||
birds.gotcha_day::text,
|
||||
@@ -30,6 +44,8 @@ const birdSelectFields = `
|
||||
birds.photo_updated_at,
|
||||
birds.notify_on_dob,
|
||||
birds.notify_on_gotcha_day,
|
||||
birds.public_profile_code,
|
||||
birds.public_profile_enabled,
|
||||
birds.memorialized_at,
|
||||
birds.memorialized_on::text,
|
||||
birds.memorial_note,
|
||||
@@ -39,6 +55,34 @@ 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
|
||||
@@ -59,6 +103,27 @@ export const getBirdById = async (birdId: string, workspaceId: number) => {
|
||||
return result.rows[0] ?? null;
|
||||
};
|
||||
|
||||
export const getBirdByPublicProfileCode = async (publicProfileCode: string) => {
|
||||
const result = await db.query<BirdRow>(
|
||||
`SELECT
|
||||
${birdSelectFields}
|
||||
FROM birds
|
||||
LEFT JOIN LATERAL (
|
||||
SELECT weight_grams, recorded_on
|
||||
FROM weight_records
|
||||
WHERE weight_records.bird_id = birds.id
|
||||
ORDER BY recorded_on DESC
|
||||
LIMIT 1
|
||||
) latest ON TRUE
|
||||
WHERE birds.public_profile_code = $1
|
||||
AND birds.public_profile_enabled = TRUE
|
||||
AND birds.memorialized_at IS NULL`,
|
||||
[publicProfileCode],
|
||||
);
|
||||
|
||||
return result.rows[0] ?? null;
|
||||
};
|
||||
|
||||
export const listBirds = async (workspaceId: number) => {
|
||||
const result = await db.query<BirdRow>(
|
||||
`SELECT
|
||||
@@ -101,6 +166,102 @@ 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
|
||||
@@ -252,12 +413,94 @@ export const createBirdMilestoneReminderDelivery = async ({
|
||||
return result.rows[0] ?? null;
|
||||
};
|
||||
|
||||
export const listDueMedicationReminders = async (runDate: string, currentTime: string) => {
|
||||
const result = await db.query<MedicationReminderCandidateRow>(
|
||||
`SELECT
|
||||
${birdSelectFields},
|
||||
workspaces.name AS workspace_name,
|
||||
medications.id AS medication_id,
|
||||
medications.name AS medication_name,
|
||||
medications.dosage,
|
||||
medications.frequency,
|
||||
medications.dose_schedule,
|
||||
medications.route,
|
||||
medications.start_date::text AS medication_start_date,
|
||||
medications.end_date::text AS medication_end_date,
|
||||
medications.notes AS medication_notes,
|
||||
$1::date::text AS scheduled_on,
|
||||
dose.key AS administration_slot,
|
||||
dose.label AS administration_label,
|
||||
dose.time AS administration_time
|
||||
FROM medications
|
||||
INNER JOIN birds ON birds.id = medications.bird_id
|
||||
INNER JOIN workspaces ON workspaces.id = birds.workspace_id
|
||||
CROSS JOIN LATERAL jsonb_to_recordset(medications.dose_schedule) AS dose(key text, label text, time text)
|
||||
LEFT JOIN LATERAL (
|
||||
SELECT weight_grams, recorded_on
|
||||
FROM weight_records
|
||||
WHERE weight_records.bird_id = birds.id
|
||||
ORDER BY recorded_on DESC
|
||||
LIMIT 1
|
||||
) latest ON TRUE
|
||||
WHERE medications.reminders_enabled = TRUE
|
||||
AND birds.memorialized_at IS NULL
|
||||
AND medications.start_date <= $1::date
|
||||
AND (medications.end_date IS NULL OR medications.end_date >= $1::date)
|
||||
AND COALESCE(NULLIF(BTRIM(dose.time), ''), '') <> ''
|
||||
AND dose.time <= $2
|
||||
AND NOT EXISTS (
|
||||
SELECT 1
|
||||
FROM medication_reminder_deliveries deliveries
|
||||
WHERE deliveries.medication_id = medications.id
|
||||
AND deliveries.scheduled_on = $1::date
|
||||
AND deliveries.administration_slot = dose.key
|
||||
)
|
||||
ORDER BY workspaces.name ASC, birds.name ASC, dose.time ASC, medications.name ASC`,
|
||||
[runDate, currentTime],
|
||||
);
|
||||
|
||||
return result.rows;
|
||||
};
|
||||
|
||||
export const createMedicationReminderDelivery = async ({
|
||||
medicationId,
|
||||
birdId,
|
||||
workspaceId,
|
||||
scheduledOn,
|
||||
administrationSlot,
|
||||
}: {
|
||||
medicationId: string;
|
||||
birdId: string;
|
||||
workspaceId: number;
|
||||
scheduledOn: string;
|
||||
administrationSlot: string;
|
||||
}) => {
|
||||
const result = await db.query<MedicationReminderDeliveryRow>(
|
||||
`INSERT INTO medication_reminder_deliveries (medication_id, bird_id, workspace_id, scheduled_on, administration_slot)
|
||||
VALUES ($1, $2, $3, $4, $5)
|
||||
ON CONFLICT (medication_id, scheduled_on, administration_slot) DO NOTHING
|
||||
RETURNING id, medication_id, bird_id, workspace_id, scheduled_on::text, administration_slot, delivered_at`,
|
||||
[medicationId, birdId, workspaceId, scheduledOn, administrationSlot],
|
||||
);
|
||||
|
||||
return result.rows[0] ?? null;
|
||||
};
|
||||
|
||||
export const createBird = async ({
|
||||
birdId,
|
||||
workspaceId,
|
||||
name,
|
||||
tagId,
|
||||
species,
|
||||
motivators,
|
||||
demotivators,
|
||||
favoriteSnack,
|
||||
locationLabel = null,
|
||||
locationDetails = null,
|
||||
vetClinicName = null,
|
||||
vetClinicAddress = null,
|
||||
vetAccountNumber = null,
|
||||
vetDoctorName = null,
|
||||
gender,
|
||||
dateOfBirth,
|
||||
gotchaDay,
|
||||
@@ -268,12 +511,23 @@ export const createBird = async ({
|
||||
photoUpdatedAt = null,
|
||||
notifyOnDob,
|
||||
notifyOnGotchaDay,
|
||||
publicProfileCode = null,
|
||||
publicProfileEnabled = false,
|
||||
}: {
|
||||
birdId?: string;
|
||||
workspaceId: number;
|
||||
name: string;
|
||||
tagId: string | null;
|
||||
species: string;
|
||||
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;
|
||||
vetDoctorName?: string | null;
|
||||
gender: BirdGender;
|
||||
dateOfBirth: string | null;
|
||||
gotchaDay: string | null;
|
||||
@@ -284,17 +538,28 @@ export const createBird = async ({
|
||||
photoUpdatedAt?: string | null;
|
||||
notifyOnDob: boolean;
|
||||
notifyOnGotchaDay: boolean;
|
||||
publicProfileCode?: string | null;
|
||||
publicProfileEnabled?: boolean;
|
||||
}) => {
|
||||
const result = await db.query<BirdRow>(
|
||||
`INSERT INTO birds (id, workspace_id, name, tag_id, species, 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)
|
||||
VALUES (COALESCE($1::uuid, gen_random_uuid()), $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15)
|
||||
RETURNING id, workspace_id, name, tag_id, species, 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, 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, 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`,
|
||||
[
|
||||
birdId ?? null,
|
||||
workspaceId,
|
||||
name,
|
||||
tagId,
|
||||
species,
|
||||
motivators,
|
||||
demotivators,
|
||||
favoriteSnack,
|
||||
locationLabel,
|
||||
locationDetails,
|
||||
vetClinicName,
|
||||
vetClinicAddress,
|
||||
vetAccountNumber,
|
||||
vetDoctorName,
|
||||
gender,
|
||||
dateOfBirth,
|
||||
gotchaDay,
|
||||
@@ -305,6 +570,8 @@ export const createBird = async ({
|
||||
photoUpdatedAt,
|
||||
notifyOnDob,
|
||||
notifyOnGotchaDay,
|
||||
publicProfileCode,
|
||||
publicProfileEnabled,
|
||||
],
|
||||
);
|
||||
|
||||
@@ -317,6 +584,15 @@ export const updateBird = async ({
|
||||
name,
|
||||
tagId,
|
||||
species,
|
||||
motivators,
|
||||
demotivators,
|
||||
favoriteSnack,
|
||||
locationLabel,
|
||||
locationDetails,
|
||||
vetClinicName,
|
||||
vetClinicAddress,
|
||||
vetAccountNumber,
|
||||
vetDoctorName,
|
||||
gender,
|
||||
dateOfBirth,
|
||||
gotchaDay,
|
||||
@@ -327,12 +603,23 @@ export const updateBird = async ({
|
||||
photoUpdatedAt = null,
|
||||
notifyOnDob,
|
||||
notifyOnGotchaDay,
|
||||
publicProfileCode,
|
||||
publicProfileEnabled,
|
||||
}: {
|
||||
birdId: string;
|
||||
workspaceId: number;
|
||||
name: string;
|
||||
tagId: string | null;
|
||||
species: string;
|
||||
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;
|
||||
vetDoctorName: string | null;
|
||||
gender: BirdGender;
|
||||
dateOfBirth: string | null;
|
||||
gotchaDay: string | null;
|
||||
@@ -343,26 +630,39 @@ export const updateBird = async ({
|
||||
photoUpdatedAt?: string | null;
|
||||
notifyOnDob: boolean;
|
||||
notifyOnGotchaDay: boolean;
|
||||
publicProfileCode: string | null;
|
||||
publicProfileEnabled: boolean;
|
||||
}) => {
|
||||
const result = await db.query<BirdRow>(
|
||||
`UPDATE birds
|
||||
SET name = $2,
|
||||
tag_id = $3,
|
||||
species = $4,
|
||||
gender = $5,
|
||||
date_of_birth = $6,
|
||||
gotcha_day = $7,
|
||||
chart_color = $8,
|
||||
photo_data_url = $9,
|
||||
photo_object_key = $10,
|
||||
photo_content_type = $11,
|
||||
photo_updated_at = $12,
|
||||
notify_on_dob = $13,
|
||||
notify_on_gotcha_day = $14
|
||||
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
|
||||
WHERE id = $1
|
||||
AND workspace_id = $15
|
||||
AND workspace_id = $26
|
||||
AND memorialized_at IS NULL
|
||||
RETURNING id, workspace_id, name, tag_id, species, 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, 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, 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,
|
||||
(
|
||||
SELECT weight_grams::text
|
||||
FROM weight_records
|
||||
@@ -382,6 +682,14 @@ export const updateBird = async ({
|
||||
name,
|
||||
tagId,
|
||||
species,
|
||||
motivators,
|
||||
demotivators,
|
||||
favoriteSnack,
|
||||
locationLabel,
|
||||
vetClinicName,
|
||||
vetClinicAddress,
|
||||
vetAccountNumber,
|
||||
vetDoctorName,
|
||||
gender,
|
||||
dateOfBirth,
|
||||
gotchaDay,
|
||||
@@ -392,6 +700,9 @@ export const updateBird = async ({
|
||||
photoUpdatedAt,
|
||||
notifyOnDob,
|
||||
notifyOnGotchaDay,
|
||||
publicProfileCode,
|
||||
publicProfileEnabled,
|
||||
locationDetails ?? null,
|
||||
workspaceId,
|
||||
],
|
||||
);
|
||||
@@ -421,7 +732,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, 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, 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, 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,
|
||||
(
|
||||
SELECT weight_grams::text
|
||||
FROM weight_records
|
||||
@@ -457,7 +768,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, 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, 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, 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,
|
||||
(
|
||||
SELECT weight_grams::text
|
||||
FROM weight_records
|
||||
@@ -478,18 +789,6 @@ export const updateMemorialReminderPreference = async ({
|
||||
return result.rows[0] ?? null;
|
||||
};
|
||||
|
||||
export const deleteBird = async (birdId: string, workspaceId: number) => {
|
||||
const result = await db.query<{ id: string }>(
|
||||
`DELETE FROM birds
|
||||
WHERE id = $1
|
||||
AND workspace_id = $2
|
||||
RETURNING id`,
|
||||
[birdId, workspaceId],
|
||||
);
|
||||
|
||||
return Boolean(result.rowCount);
|
||||
};
|
||||
|
||||
export const transferBirdToWorkspace = async (birdId: string, sourceWorkspaceId: number, targetWorkspaceId: number) => {
|
||||
const result = await db.query<BirdRow>(
|
||||
`UPDATE birds
|
||||
@@ -497,7 +796,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, 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, 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, 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,
|
||||
(
|
||||
SELECT weight_grams::text
|
||||
FROM weight_records
|
||||
@@ -593,12 +892,23 @@ 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;
|
||||
const message =
|
||||
typeof error === 'object' && error && 'code' in error && error.code === '23505'
|
||||
? 'The receiving flock already has a bird using the same band/tag ID.'
|
||||
? 'That band/tag ID is already in use in FlockPal.'
|
||||
: error instanceof Error
|
||||
? error.message
|
||||
: 'Unable to complete pending bird transfer.';
|
||||
@@ -609,6 +919,93 @@ export const completePendingBirdTransfersForOwner = async (ownerEmail: string, t
|
||||
return { completed, failed };
|
||||
};
|
||||
|
||||
export const createBirdTransferCode = async ({
|
||||
code,
|
||||
birdId,
|
||||
sourceWorkspaceId,
|
||||
requestedByUserId,
|
||||
}: {
|
||||
code: string;
|
||||
birdId: string;
|
||||
sourceWorkspaceId: number;
|
||||
requestedByUserId: string;
|
||||
}) => {
|
||||
await db.query(
|
||||
`UPDATE bird_transfer_codes
|
||||
SET revoked_at = CURRENT_TIMESTAMP
|
||||
WHERE bird_id = $1
|
||||
AND source_workspace_id = $2
|
||||
AND completed_at IS NULL
|
||||
AND revoked_at IS NULL`,
|
||||
[birdId, sourceWorkspaceId],
|
||||
);
|
||||
|
||||
const result = await db.query<BirdTransferCodeRow>(
|
||||
`INSERT INTO bird_transfer_codes (code, bird_id, source_workspace_id, requested_by_user_id)
|
||||
VALUES ($1, $2, $3, $4)
|
||||
RETURNING id, code, bird_id, source_workspace_id, requested_by_user_id, completed_at::text, completed_workspace_id, revoked_at::text, created_at`,
|
||||
[code, birdId, sourceWorkspaceId, requestedByUserId],
|
||||
);
|
||||
|
||||
return result.rows[0] ?? null;
|
||||
};
|
||||
|
||||
export const getOpenBirdTransferCode = async (code: string) => {
|
||||
const result = await db.query<
|
||||
BirdRow & {
|
||||
transfer_code_id: string;
|
||||
code: string;
|
||||
source_workspace_id: number;
|
||||
requested_by_user_id: string;
|
||||
completed_at: string | null;
|
||||
completed_workspace_id: number | null;
|
||||
revoked_at: string | null;
|
||||
transfer_code_created_at: string;
|
||||
workspace_name: string;
|
||||
}
|
||||
>(
|
||||
`SELECT
|
||||
bird_transfer_codes.id AS transfer_code_id,
|
||||
bird_transfer_codes.code,
|
||||
bird_transfer_codes.source_workspace_id,
|
||||
bird_transfer_codes.requested_by_user_id,
|
||||
bird_transfer_codes.completed_at::text,
|
||||
bird_transfer_codes.completed_workspace_id,
|
||||
bird_transfer_codes.revoked_at::text,
|
||||
bird_transfer_codes.created_at AS transfer_code_created_at,
|
||||
workspaces.name AS workspace_name,
|
||||
${birdSelectFields}
|
||||
FROM bird_transfer_codes
|
||||
INNER JOIN birds ON birds.id = bird_transfer_codes.bird_id
|
||||
INNER JOIN workspaces ON workspaces.id = bird_transfer_codes.source_workspace_id
|
||||
LEFT JOIN LATERAL (
|
||||
SELECT weight_grams, recorded_on
|
||||
FROM weight_records
|
||||
WHERE weight_records.bird_id = birds.id
|
||||
ORDER BY recorded_on DESC
|
||||
LIMIT 1
|
||||
) latest ON TRUE
|
||||
WHERE bird_transfer_codes.code = $1
|
||||
AND bird_transfer_codes.completed_at IS NULL
|
||||
AND bird_transfer_codes.revoked_at IS NULL
|
||||
AND birds.workspace_id = bird_transfer_codes.source_workspace_id
|
||||
AND birds.memorialized_at IS NULL`,
|
||||
[code],
|
||||
);
|
||||
|
||||
return result.rows[0] ?? null;
|
||||
};
|
||||
|
||||
export const markBirdTransferCodeCompleted = async (codeId: string, completedWorkspaceId: number) => {
|
||||
await db.query(
|
||||
`UPDATE bird_transfer_codes
|
||||
SET completed_at = CURRENT_TIMESTAMP,
|
||||
completed_workspace_id = $2
|
||||
WHERE id = $1`,
|
||||
[codeId, completedWorkspaceId],
|
||||
);
|
||||
};
|
||||
|
||||
export const listWeightsForBird = async (birdId: string, workspaceId: number, days: number) => {
|
||||
const result = await db.query<WeightRow>(
|
||||
`SELECT id, bird_id, weight_grams, recorded_on::text, notes
|
||||
@@ -639,6 +1036,34 @@ 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
|
||||
@@ -705,7 +1130,7 @@ export const deleteVetVisitForBird = async (visitId: string, birdId: string) =>
|
||||
|
||||
export const listMedicationsForBird = async (birdId: string, workspaceId: number) => {
|
||||
const result = await db.query<MedicationRow>(
|
||||
`SELECT id, bird_id, name, dosage, frequency, dose_schedule, route, start_date::text, end_date::text, notes
|
||||
`SELECT id, bird_id, name, dosage, frequency, dose_schedule, route, start_date::text, end_date::text, notes, reminders_enabled
|
||||
FROM medications
|
||||
WHERE bird_id = $1
|
||||
AND EXISTS (
|
||||
@@ -731,12 +1156,13 @@ export const createMedicationForBird = async (
|
||||
startDate: string,
|
||||
endDate: string | null,
|
||||
notes: string | null,
|
||||
remindersEnabled: boolean,
|
||||
) => {
|
||||
const result = await db.query<MedicationRow>(
|
||||
`INSERT INTO medications (bird_id, name, dosage, frequency, dose_schedule, route, start_date, end_date, notes)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)
|
||||
RETURNING id, bird_id, name, dosage, frequency, dose_schedule, route, start_date::text, end_date::text, notes`,
|
||||
[birdId, name, dosage, frequency, JSON.stringify(doseSchedule), route, startDate, endDate, notes],
|
||||
`INSERT INTO medications (bird_id, name, dosage, frequency, dose_schedule, route, start_date, end_date, notes, reminders_enabled)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)
|
||||
RETURNING id, bird_id, name, dosage, frequency, dose_schedule, route, start_date::text, end_date::text, notes, reminders_enabled`,
|
||||
[birdId, name, dosage, frequency, JSON.stringify(doseSchedule), route, startDate, endDate, notes, remindersEnabled],
|
||||
);
|
||||
|
||||
return result.rows[0] ?? null;
|
||||
@@ -753,6 +1179,7 @@ export const updateMedicationForBird = async (
|
||||
startDate: string,
|
||||
endDate: string | null,
|
||||
notes: string | null,
|
||||
remindersEnabled: boolean,
|
||||
) => {
|
||||
const result = await db.query<MedicationRow>(
|
||||
`UPDATE medications
|
||||
@@ -763,11 +1190,12 @@ export const updateMedicationForBird = async (
|
||||
route = $7,
|
||||
start_date = $8,
|
||||
end_date = $9,
|
||||
notes = $10
|
||||
notes = $10,
|
||||
reminders_enabled = $11
|
||||
WHERE id = $1
|
||||
AND bird_id = $2
|
||||
RETURNING id, bird_id, name, dosage, frequency, dose_schedule, route, start_date::text, end_date::text, notes`,
|
||||
[medicationId, birdId, name, dosage, frequency, JSON.stringify(doseSchedule), route, startDate, endDate, notes],
|
||||
RETURNING id, bird_id, name, dosage, frequency, dose_schedule, route, start_date::text, end_date::text, notes, reminders_enabled`,
|
||||
[medicationId, birdId, name, dosage, frequency, JSON.stringify(doseSchedule), route, startDate, endDate, notes, remindersEnabled],
|
||||
);
|
||||
|
||||
return result.rows[0] ?? null;
|
||||
|
||||
@@ -3,12 +3,15 @@ import test from 'node:test';
|
||||
|
||||
import {
|
||||
createWorkspace,
|
||||
deleteWorkspaceMember,
|
||||
deleteWorkspaceIfEmpty,
|
||||
ensureDefaultWorkspaceForUser,
|
||||
ensurePersonalWorkspaceForUser,
|
||||
findAlternateWorkspaceForUser,
|
||||
getPlatformAdminSummary,
|
||||
listOwnedWorkspacesByOwnerEmail,
|
||||
updateWorkspace,
|
||||
updateWorkspaceMemberRole,
|
||||
} from './workspaceRepository.js';
|
||||
import { mockDb } from '../test/mockDb.js';
|
||||
import type { UserRow } from '../types.js';
|
||||
@@ -34,6 +37,83 @@ test('ensurePersonalWorkspaceForUser returns an existing workspace without creat
|
||||
assert.match(calls[0].text, /FROM workspace_members/);
|
||||
});
|
||||
|
||||
test('ensurePersonalWorkspaceForUser creates a fresh workspace instead of claiming the legacy seed flock', async () => {
|
||||
const { calls } = mockDb(
|
||||
{
|
||||
rowCount: 0,
|
||||
rows: [],
|
||||
},
|
||||
{
|
||||
rowCount: 1,
|
||||
rows: [{ next_id: 43 }],
|
||||
},
|
||||
{
|
||||
rowCount: 1,
|
||||
rows: [],
|
||||
},
|
||||
{
|
||||
rowCount: 1,
|
||||
rows: [],
|
||||
},
|
||||
);
|
||||
|
||||
const workspaceId = await ensurePersonalWorkspaceForUser(user);
|
||||
|
||||
assert.equal(workspaceId, 43);
|
||||
assert.equal(calls.length, 4);
|
||||
assert.match(calls[1].text, /SELECT COALESCE\(MAX\(id\), 0\) \+ 1 AS next_id FROM workspaces/);
|
||||
assert.match(calls[2].text, /INSERT INTO workspaces/);
|
||||
assert.match(calls[3].text, /INSERT INTO workspace_members/);
|
||||
assert.deepEqual(calls[2].params, [43, "Owner's Flock", 'owner@example.com']);
|
||||
});
|
||||
|
||||
test('ensureDefaultWorkspaceForUser reuses an existing rescue workspace without creating a household flock', async () => {
|
||||
const { calls } = mockDb({
|
||||
rowCount: 1,
|
||||
rows: [{ workspace_id: 84 }],
|
||||
});
|
||||
|
||||
const workspaceId = await ensureDefaultWorkspaceForUser(user);
|
||||
|
||||
assert.equal(workspaceId, 84);
|
||||
assert.equal(calls.length, 1);
|
||||
assert.match(calls[0].text, /FROM workspace_members/);
|
||||
assert.doesNotMatch(calls[0].text, /workspaces\.workspace_type = 'standard'/);
|
||||
});
|
||||
|
||||
test('ensureDefaultWorkspaceForUser creates a household flock when the user has no workspace', async () => {
|
||||
const { calls } = mockDb(
|
||||
{
|
||||
rowCount: 0,
|
||||
rows: [],
|
||||
},
|
||||
{
|
||||
rowCount: 0,
|
||||
rows: [],
|
||||
},
|
||||
{
|
||||
rowCount: 1,
|
||||
rows: [{ next_id: 43 }],
|
||||
},
|
||||
{
|
||||
rowCount: 1,
|
||||
rows: [],
|
||||
},
|
||||
{
|
||||
rowCount: 1,
|
||||
rows: [],
|
||||
},
|
||||
);
|
||||
|
||||
const workspaceId = await ensureDefaultWorkspaceForUser(user);
|
||||
|
||||
assert.equal(workspaceId, 43);
|
||||
assert.equal(calls.length, 5);
|
||||
assert.match(calls[0].text, /FROM workspace_members/);
|
||||
assert.match(calls[1].text, /workspaces\.workspace_type = 'standard'/);
|
||||
assert.match(calls[3].text, /INSERT INTO workspaces/);
|
||||
});
|
||||
|
||||
test('createWorkspace inserts owner membership and returns the created workspace', async () => {
|
||||
const { calls } = mockDb(
|
||||
{ rowCount: 1, rows: [] },
|
||||
@@ -181,6 +261,263 @@ test('listOwnedWorkspacesByOwnerEmail resolves accepted owner flocks by email',
|
||||
assert.match(calls[0].text, /workspaces\.id <> \$2/);
|
||||
});
|
||||
|
||||
test('updateWorkspaceMemberRole changes a non-owner member role', async () => {
|
||||
const { calls } = mockDb({
|
||||
rowCount: 1,
|
||||
rows: [
|
||||
{
|
||||
id: 'member-1',
|
||||
workspace_id: 42,
|
||||
user_id: 'user-2',
|
||||
invite_email: 'helper@example.com',
|
||||
name: 'Helper',
|
||||
role: 'viewer',
|
||||
accepted_at: '2026-04-14T00:00:00.000Z',
|
||||
created_at: '2026-04-14T00:00:00.000Z',
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const member = await updateWorkspaceMemberRole({
|
||||
memberId: 'member-1',
|
||||
workspaceId: 42,
|
||||
role: 'viewer',
|
||||
requesterMemberId: 'owner-member',
|
||||
requesterIsBillingOwner: false,
|
||||
requesterRole: 'owner',
|
||||
billingEmail: 'billing@example.com',
|
||||
});
|
||||
|
||||
assert.equal(member?.role, 'viewer');
|
||||
assert.deepEqual(calls[0].params, ['member-1', 42, 'viewer', false, 'owner-member', 'billing@example.com', 'owner']);
|
||||
assert.match(calls[0].text, /UPDATE workspace_members/);
|
||||
assert.match(calls[0].text, /role <> 'owner'/);
|
||||
});
|
||||
|
||||
test('updateWorkspaceMemberRole returns null when no non-owner member matches', async () => {
|
||||
mockDb({
|
||||
rowCount: 0,
|
||||
rows: [],
|
||||
});
|
||||
|
||||
const member = await updateWorkspaceMemberRole({
|
||||
memberId: 'owner-member',
|
||||
workspaceId: 42,
|
||||
role: 'viewer',
|
||||
requesterMemberId: 'owner-member',
|
||||
requesterIsBillingOwner: false,
|
||||
requesterRole: 'owner',
|
||||
billingEmail: 'billing@example.com',
|
||||
});
|
||||
|
||||
assert.equal(member, null);
|
||||
});
|
||||
|
||||
test('updateWorkspaceMemberRole lets the billing owner change another owner role', async () => {
|
||||
const { calls } = mockDb({
|
||||
rowCount: 1,
|
||||
rows: [
|
||||
{
|
||||
id: 'other-owner',
|
||||
workspace_id: 42,
|
||||
user_id: 'user-2',
|
||||
invite_email: 'other@example.com',
|
||||
name: 'Other Owner',
|
||||
role: 'assistant',
|
||||
accepted_at: '2026-04-14T00:00:00.000Z',
|
||||
created_at: '2026-04-14T00:00:00.000Z',
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const member = await updateWorkspaceMemberRole({
|
||||
memberId: 'other-owner',
|
||||
workspaceId: 42,
|
||||
role: 'assistant',
|
||||
requesterMemberId: 'billing-owner',
|
||||
requesterIsBillingOwner: true,
|
||||
requesterRole: 'owner',
|
||||
billingEmail: 'billing@example.com',
|
||||
});
|
||||
|
||||
assert.equal(member?.role, 'assistant');
|
||||
assert.deepEqual(calls[0].params, ['other-owner', 42, 'assistant', true, 'billing-owner', 'billing@example.com', 'owner']);
|
||||
assert.match(calls[0].text, /id <> \$5/);
|
||||
});
|
||||
|
||||
test('updateWorkspaceMemberRole does not let the billing owner change their own owner role', async () => {
|
||||
mockDb({
|
||||
rowCount: 0,
|
||||
rows: [],
|
||||
});
|
||||
|
||||
const member = await updateWorkspaceMemberRole({
|
||||
memberId: 'billing-owner',
|
||||
workspaceId: 42,
|
||||
role: 'assistant',
|
||||
requesterMemberId: 'billing-owner',
|
||||
requesterIsBillingOwner: true,
|
||||
requesterRole: 'owner',
|
||||
billingEmail: 'billing@example.com',
|
||||
});
|
||||
|
||||
assert.equal(member, null);
|
||||
});
|
||||
|
||||
test('updateWorkspaceMemberRole lets a non-billing owner change another non-billing owner role', async () => {
|
||||
const { calls } = mockDb({
|
||||
rowCount: 1,
|
||||
rows: [
|
||||
{
|
||||
id: 'other-owner',
|
||||
workspace_id: 42,
|
||||
user_id: 'user-2',
|
||||
invite_email: 'other@example.com',
|
||||
name: 'Other Owner',
|
||||
role: 'assistant',
|
||||
accepted_at: '2026-04-14T00:00:00.000Z',
|
||||
created_at: '2026-04-14T00:00:00.000Z',
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const member = await updateWorkspaceMemberRole({
|
||||
memberId: 'other-owner',
|
||||
workspaceId: 42,
|
||||
role: 'assistant',
|
||||
requesterMemberId: 'non-billing-owner',
|
||||
requesterIsBillingOwner: false,
|
||||
requesterRole: 'owner',
|
||||
billingEmail: 'billing@example.com',
|
||||
});
|
||||
|
||||
assert.equal(member?.role, 'assistant');
|
||||
assert.deepEqual(calls[0].params, ['other-owner', 42, 'assistant', false, 'non-billing-owner', 'billing@example.com', 'owner']);
|
||||
assert.match(calls[0].text, /LOWER\(BTRIM\(COALESCE\(invite_email, email\)\)\) <> LOWER\(BTRIM\(\$6\)\)/);
|
||||
});
|
||||
|
||||
test('updateWorkspaceMemberRole does not let a non-billing owner change the billing owner role', async () => {
|
||||
mockDb({
|
||||
rowCount: 0,
|
||||
rows: [],
|
||||
});
|
||||
|
||||
const member = await updateWorkspaceMemberRole({
|
||||
memberId: 'billing-owner',
|
||||
workspaceId: 42,
|
||||
role: 'assistant',
|
||||
requesterMemberId: 'non-billing-owner',
|
||||
requesterIsBillingOwner: false,
|
||||
requesterRole: 'owner',
|
||||
billingEmail: 'billing@example.com',
|
||||
});
|
||||
|
||||
assert.equal(member, null);
|
||||
});
|
||||
|
||||
test('updateWorkspaceMemberRole lets the billing owner promote a non-owner to owner', async () => {
|
||||
const { calls } = mockDb({
|
||||
rowCount: 1,
|
||||
rows: [
|
||||
{
|
||||
id: 'member-1',
|
||||
workspace_id: 42,
|
||||
user_id: 'user-2',
|
||||
invite_email: 'helper@example.com',
|
||||
name: 'Helper',
|
||||
role: 'owner',
|
||||
accepted_at: '2026-04-14T00:00:00.000Z',
|
||||
created_at: '2026-04-14T00:00:00.000Z',
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const member = await updateWorkspaceMemberRole({
|
||||
memberId: 'member-1',
|
||||
workspaceId: 42,
|
||||
role: 'owner',
|
||||
requesterMemberId: 'billing-owner',
|
||||
requesterIsBillingOwner: true,
|
||||
requesterRole: 'owner',
|
||||
billingEmail: 'billing@example.com',
|
||||
});
|
||||
|
||||
assert.equal(member?.role, 'owner');
|
||||
assert.deepEqual(calls[0].params, ['member-1', 42, 'owner', true, 'billing-owner', 'billing@example.com', 'owner']);
|
||||
assert.match(calls[0].text, /\$3 <> 'owner'/);
|
||||
});
|
||||
|
||||
test('updateWorkspaceMemberRole does not let a non-billing owner promote a member to owner', async () => {
|
||||
mockDb({
|
||||
rowCount: 0,
|
||||
rows: [],
|
||||
});
|
||||
|
||||
const member = await updateWorkspaceMemberRole({
|
||||
memberId: 'member-1',
|
||||
workspaceId: 42,
|
||||
role: 'owner',
|
||||
requesterMemberId: 'non-billing-owner',
|
||||
requesterIsBillingOwner: false,
|
||||
requesterRole: 'owner',
|
||||
billingEmail: 'billing@example.com',
|
||||
});
|
||||
|
||||
assert.equal(member, null);
|
||||
});
|
||||
|
||||
test('deleteWorkspaceMember removes non-owner members without billing owner access', async () => {
|
||||
const { calls } = mockDb({
|
||||
rowCount: 1,
|
||||
rows: [{ id: 'member-1' }],
|
||||
});
|
||||
|
||||
const deleted = await deleteWorkspaceMember({
|
||||
memberId: 'member-1',
|
||||
workspaceId: 42,
|
||||
requesterMemberId: 'owner-member',
|
||||
requesterIsBillingOwner: false,
|
||||
});
|
||||
|
||||
assert.equal(deleted, true);
|
||||
assert.deepEqual(calls[0].params, ['member-1', 42, false, 'owner-member']);
|
||||
assert.match(calls[0].text, /role <> 'owner'/);
|
||||
});
|
||||
|
||||
test('deleteWorkspaceMember lets the billing owner remove another owner', async () => {
|
||||
const { calls } = mockDb({
|
||||
rowCount: 1,
|
||||
rows: [{ id: 'other-owner' }],
|
||||
});
|
||||
|
||||
const deleted = await deleteWorkspaceMember({
|
||||
memberId: 'other-owner',
|
||||
workspaceId: 42,
|
||||
requesterMemberId: 'billing-owner',
|
||||
requesterIsBillingOwner: true,
|
||||
});
|
||||
|
||||
assert.equal(deleted, true);
|
||||
assert.deepEqual(calls[0].params, ['other-owner', 42, true, 'billing-owner']);
|
||||
assert.match(calls[0].text, /id <> \$4/);
|
||||
});
|
||||
|
||||
test('deleteWorkspaceMember does not let the billing owner remove their own owner membership', async () => {
|
||||
mockDb({
|
||||
rowCount: 0,
|
||||
rows: [],
|
||||
});
|
||||
|
||||
const deleted = await deleteWorkspaceMember({
|
||||
memberId: 'billing-owner',
|
||||
workspaceId: 42,
|
||||
requesterMemberId: 'billing-owner',
|
||||
requesterIsBillingOwner: true,
|
||||
});
|
||||
|
||||
assert.equal(deleted, false);
|
||||
});
|
||||
|
||||
test('getPlatformAdminSummary counts memorialized birds separately', async () => {
|
||||
const { calls } = mockDb({
|
||||
rowCount: 1,
|
||||
@@ -194,6 +531,10 @@ 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,
|
||||
},
|
||||
],
|
||||
});
|
||||
@@ -206,4 +547,7 @@ 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'\)/);
|
||||
});
|
||||
@@ -91,39 +91,13 @@ export const ensurePersonalWorkspaceForUser = async (user: UserRow) => {
|
||||
return Number(existing.rows[0].workspace_id);
|
||||
}
|
||||
|
||||
const unclaimed = await db.query<{ workspace_id: number }>(
|
||||
`SELECT workspaces.id AS workspace_id
|
||||
FROM workspaces
|
||||
LEFT JOIN workspace_members ON workspace_members.workspace_id = workspaces.id
|
||||
WHERE workspaces.id = 1
|
||||
GROUP BY workspaces.id
|
||||
HAVING COUNT(workspace_members.id) = 0
|
||||
LIMIT 1`,
|
||||
);
|
||||
const workspaceId = await getNextWorkspaceId();
|
||||
|
||||
const workspaceId = unclaimed.rowCount ? Number(unclaimed.rows[0].workspace_id) : await getNextWorkspaceId();
|
||||
|
||||
if (!unclaimed.rowCount) {
|
||||
await db.query(
|
||||
`INSERT INTO workspaces (id, name, workspace_type, billing_plan, billing_interval, billing_email, subscription_status, rescue_verification_status)
|
||||
VALUES ($1, $2, 'standard', 'household_basic', 'monthly', $3, 'none', 'not_required')`,
|
||||
[workspaceId, `${user.name}'s Flock`, user.email],
|
||||
);
|
||||
} else {
|
||||
await db.query(
|
||||
`UPDATE workspaces
|
||||
SET name = $2,
|
||||
workspace_type = 'standard',
|
||||
billing_plan = 'household_basic',
|
||||
billing_interval = 'monthly',
|
||||
billing_email = $3,
|
||||
subscription_status = 'none',
|
||||
rescue_verification_status = 'not_required',
|
||||
updated_at = CURRENT_TIMESTAMP
|
||||
WHERE id = $1`,
|
||||
[workspaceId, `${user.name}'s Flock`, user.email],
|
||||
);
|
||||
}
|
||||
|
||||
await db.query(
|
||||
`INSERT INTO workspace_members (workspace_id, user_id, email, invite_email, name, role, accepted_at)
|
||||
@@ -140,6 +114,24 @@ export const ensurePersonalWorkspaceForUser = async (user: UserRow) => {
|
||||
return workspaceId;
|
||||
};
|
||||
|
||||
export const ensureDefaultWorkspaceForUser = async (user: UserRow) => {
|
||||
const existing = await db.query<{ workspace_id: number }>(
|
||||
`SELECT workspace_id
|
||||
FROM workspace_members
|
||||
INNER JOIN workspaces ON workspaces.id = workspace_members.workspace_id
|
||||
WHERE workspace_members.user_id = $1
|
||||
ORDER BY workspaces.created_at ASC
|
||||
LIMIT 1`,
|
||||
[user.id],
|
||||
);
|
||||
|
||||
if (existing.rowCount) {
|
||||
return Number(existing.rows[0].workspace_id);
|
||||
}
|
||||
|
||||
return ensurePersonalWorkspaceForUser(user);
|
||||
};
|
||||
|
||||
export const claimWorkspaceInvites = async (user: UserRow) => {
|
||||
await db.query(
|
||||
`UPDATE workspace_members
|
||||
@@ -372,23 +364,84 @@ export const upsertWorkspaceMember = async ({
|
||||
return result.rows[0] ?? null;
|
||||
};
|
||||
|
||||
export const deleteWorkspaceMember = async (memberId: string, workspaceId: number) => {
|
||||
export const deleteWorkspaceMember = async ({
|
||||
memberId,
|
||||
workspaceId,
|
||||
requesterMemberId,
|
||||
requesterIsBillingOwner,
|
||||
}: {
|
||||
memberId: string;
|
||||
workspaceId: number;
|
||||
requesterMemberId: string;
|
||||
requesterIsBillingOwner: boolean;
|
||||
}) => {
|
||||
const result = await db.query<{ id: string }>(
|
||||
`DELETE FROM workspace_members
|
||||
WHERE id = $1
|
||||
AND workspace_id = $2
|
||||
AND role <> 'owner'
|
||||
AND (
|
||||
role <> 'owner'
|
||||
OR (
|
||||
$3 = TRUE
|
||||
AND id <> $4
|
||||
)
|
||||
)
|
||||
RETURNING id`,
|
||||
[memberId, workspaceId],
|
||||
[memberId, workspaceId, requesterIsBillingOwner, requesterMemberId],
|
||||
);
|
||||
|
||||
return Boolean(result.rowCount);
|
||||
};
|
||||
|
||||
export const updateWorkspaceMemberRole = async ({
|
||||
memberId,
|
||||
workspaceId,
|
||||
role,
|
||||
requesterMemberId,
|
||||
requesterIsBillingOwner,
|
||||
requesterRole,
|
||||
billingEmail,
|
||||
}: {
|
||||
memberId: string;
|
||||
workspaceId: number;
|
||||
role: WorkspaceMemberRow['role'];
|
||||
requesterMemberId: string;
|
||||
requesterIsBillingOwner: boolean;
|
||||
requesterRole: WorkspaceMemberRow['role'];
|
||||
billingEmail: string;
|
||||
}) => {
|
||||
const result = await db.query<WorkspaceMemberRow>(
|
||||
`UPDATE workspace_members
|
||||
SET role = $3
|
||||
WHERE id = $1
|
||||
AND workspace_id = $2
|
||||
AND (
|
||||
$3 <> 'owner'
|
||||
OR $4 = TRUE
|
||||
)
|
||||
AND (
|
||||
role <> 'owner'
|
||||
OR (
|
||||
id <> $5
|
||||
AND (
|
||||
$4 = TRUE
|
||||
OR (
|
||||
$7 = 'owner'
|
||||
AND LOWER(BTRIM(COALESCE(invite_email, email))) <> LOWER(BTRIM($6))
|
||||
)
|
||||
)
|
||||
)
|
||||
)
|
||||
RETURNING id, workspace_id, user_id, COALESCE(invite_email, email) AS invite_email, name, role, accepted_at::text, created_at`,
|
||||
[memberId, workspaceId, role, requesterIsBillingOwner, requesterMemberId, billingEmail, requesterRole],
|
||||
);
|
||||
|
||||
return result.rows[0] ?? null;
|
||||
};
|
||||
|
||||
export const listRescueWorkspacesForAdmin = async () => {
|
||||
const result = await db.query<
|
||||
WorkspaceRow & {
|
||||
owner_email: string | null;
|
||||
bird_count: number;
|
||||
member_count: number;
|
||||
}
|
||||
@@ -406,17 +459,13 @@ export const listRescueWorkspacesForAdmin = async () => {
|
||||
workspaces.rescue_verification_status,
|
||||
workspaces.created_at,
|
||||
workspaces.updated_at,
|
||||
owner.invite_email AS owner_email,
|
||||
COUNT(DISTINCT birds.id)::int AS bird_count,
|
||||
COUNT(DISTINCT workspace_members.id)::int AS member_count
|
||||
FROM workspaces
|
||||
LEFT JOIN workspace_members owner
|
||||
ON owner.workspace_id = workspaces.id
|
||||
AND owner.role = 'owner'
|
||||
LEFT JOIN birds ON birds.workspace_id = workspaces.id
|
||||
LEFT JOIN workspace_members ON workspace_members.workspace_id = workspaces.id
|
||||
WHERE workspaces.workspace_type = 'rescue'
|
||||
GROUP BY workspaces.id, owner.invite_email
|
||||
GROUP BY workspaces.id
|
||||
ORDER BY
|
||||
CASE workspaces.rescue_verification_status
|
||||
WHEN 'pending' THEN 0
|
||||
@@ -556,6 +605,10 @@ 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,
|
||||
@@ -565,7 +618,11 @@ 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(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`,
|
||||
);
|
||||
|
||||
return result.rows[0];
|
||||
|
||||
@@ -0,0 +1,210 @@
|
||||
import { z } from 'zod';
|
||||
|
||||
// Shared runtime validation and API documentation schemas.
|
||||
export const dateStringSchema = z.string().regex(/^\d{4}-\d{2}-\d{2}$/);
|
||||
export const chartColorSchema = z.string().regex(/^#[0-9a-fA-F]{6}$/);
|
||||
export const photoDataUrlSchema = z
|
||||
.string()
|
||||
.regex(/^data:image\/(?:png|jpeg|jpg|webp|gif);base64,[A-Za-z0-9+/=]+$/)
|
||||
.max(1_500_000);
|
||||
export const photoUrlSchema = z.string().trim().url().max(2000);
|
||||
|
||||
export const magicLinkRequestSchema = z.object({
|
||||
name: z.string().trim().max(160).optional().or(z.literal('')),
|
||||
email: z.string().trim().email().max(255),
|
||||
redirectTo: z.string().trim().url().max(2000).optional().or(z.literal('')),
|
||||
});
|
||||
|
||||
export const switchWorkspaceSchema = z.object({
|
||||
workspaceId: z.coerce.number().int().positive(),
|
||||
});
|
||||
|
||||
export const workspaceTypeSchema = z.enum(['standard', 'rescue']);
|
||||
export const workspaceRoleSchema = z.enum(['owner', 'assistant', 'caregiver', 'viewer']);
|
||||
export const billingPlanSchema = z.enum(['household_basic', 'household_plus', 'household_macaw', 'household_hyacinth_macaw']);
|
||||
export const billingIntervalSchema = z.enum(['monthly', 'yearly']);
|
||||
export const integrationTokenScopeSchema = z.enum(['read_only', 'read_write']);
|
||||
export const birdGenderSchema = z.enum(['unknown', 'male', 'female', 'male_dna', 'female_dna']);
|
||||
export const rescueVerificationStatusSchema = z.enum(['pending', 'approved', 'rejected']);
|
||||
export const rescueOnboardingSchema = z.object({
|
||||
name: z.string().trim().max(160).optional().or(z.literal('')),
|
||||
city: z.string().trim().max(120).optional().or(z.literal('')),
|
||||
state: z.string().trim().max(80).optional().or(z.literal('')),
|
||||
ein: z.string().trim().max(32).optional().or(z.literal('')),
|
||||
website: z.string().trim().url().max(2000).optional().or(z.literal('')),
|
||||
});
|
||||
|
||||
export const workspaceSchema = z.object({
|
||||
name: z.string().trim().min(1).max(160),
|
||||
workspaceType: workspaceTypeSchema,
|
||||
billingEmail: z.string().trim().email().max(255).optional().or(z.literal('')),
|
||||
billingPlan: billingPlanSchema.optional(),
|
||||
billingInterval: billingIntervalSchema.optional(),
|
||||
rescueOnboarding: rescueOnboardingSchema.optional(),
|
||||
});
|
||||
|
||||
export const createWorkspaceSchema = z.object({
|
||||
name: z.string().trim().min(1).max(160),
|
||||
workspaceType: workspaceTypeSchema,
|
||||
billingEmail: z.string().trim().email().max(255).optional().or(z.literal('')),
|
||||
billingPlan: billingPlanSchema.optional(),
|
||||
billingInterval: billingIntervalSchema.optional(),
|
||||
rescueOnboarding: rescueOnboardingSchema.optional(),
|
||||
});
|
||||
|
||||
export const workspaceMemberSchema = z.object({
|
||||
name: z.string().trim().min(1).max(160),
|
||||
email: z.string().trim().email().max(255),
|
||||
role: workspaceRoleSchema,
|
||||
});
|
||||
|
||||
export const flockTransferSchema = z.object({
|
||||
destinationOwnerEmail: z.string().trim().email().max(255),
|
||||
});
|
||||
|
||||
export const lostBirdReportSchema = z.object({
|
||||
tagId: z.string().trim().min(1).max(80),
|
||||
finderName: z.string().trim().max(160).optional().or(z.literal('')),
|
||||
finderEmail: z.string().trim().email().max(255).optional().or(z.literal('')),
|
||||
foundLocation: z.string().trim().max(255).optional().or(z.literal('')),
|
||||
message: z.string().trim().max(1000).optional().or(z.literal('')),
|
||||
});
|
||||
|
||||
export const publicProfileCodeSchema = z.string().trim().regex(/^[A-Za-z0-9_-]{8,32}$/);
|
||||
export const birdTransferCodeSchema = z.string().trim().regex(/^[A-Za-z0-9_-]{12,32}$/);
|
||||
export const birdProfileListSchema = z
|
||||
.string()
|
||||
.trim()
|
||||
.max(1000)
|
||||
.refine(
|
||||
(value) => value.split(/\r?\n/).map((item) => item.trim()).filter(Boolean).length <= 3,
|
||||
'Use no more than three list items.',
|
||||
)
|
||||
.optional()
|
||||
.or(z.literal(''));
|
||||
|
||||
export const verifiedLocationDetailsSchema = z
|
||||
.object({
|
||||
label: z.string().trim().max(220).optional().or(z.literal('')),
|
||||
city: z.string().trim().max(120).optional().or(z.literal('')),
|
||||
region: z.string().trim().max(120).optional().or(z.literal('')),
|
||||
country: z.string().trim().max(120).optional().or(z.literal('')),
|
||||
countryCode: z.string().trim().max(2).optional().or(z.literal('')),
|
||||
latitude: z.coerce.number().min(-90).max(90).optional().nullable().or(z.literal('')),
|
||||
longitude: z.coerce.number().min(-180).max(180).optional().nullable().or(z.literal('')),
|
||||
precision: z.enum(['city', 'region', 'country']).optional(),
|
||||
provider: z.literal('mapbox').optional().nullable(),
|
||||
providerPlaceId: z.string().trim().max(220).optional().or(z.literal('')),
|
||||
})
|
||||
.optional()
|
||||
.nullable();
|
||||
|
||||
export const locationSearchSchema = z.object({
|
||||
q: z.string().trim().min(3).max(120),
|
||||
});
|
||||
|
||||
export const birdSchema = z.object({
|
||||
name: z.string().trim().min(1).max(120),
|
||||
tagId: z.string().trim().max(80).optional().or(z.literal('')),
|
||||
species: z.string().trim().min(1).max(120),
|
||||
motivators: birdProfileListSchema,
|
||||
demotivators: birdProfileListSchema,
|
||||
favoriteSnack: z.string().trim().max(160).optional().or(z.literal('')),
|
||||
locationLabel: z.string().trim().max(160).optional().or(z.literal('')),
|
||||
locationDetails: verifiedLocationDetailsSchema,
|
||||
vetClinicName: z.string().trim().max(160).optional().or(z.literal('')),
|
||||
vetClinicAddress: z.string().trim().max(500).optional().or(z.literal('')),
|
||||
vetAccountNumber: z.string().trim().max(120).optional().or(z.literal('')),
|
||||
vetDoctorName: z.string().trim().max(160).optional().or(z.literal('')),
|
||||
gender: birdGenderSchema.optional(),
|
||||
hatchDay: dateStringSchema.optional().or(z.literal('')),
|
||||
dateOfBirth: dateStringSchema.optional().or(z.literal('')),
|
||||
gotchaDay: dateStringSchema.optional().or(z.literal('')),
|
||||
chartColor: chartColorSchema.optional(),
|
||||
photoDataUrl: z.union([photoDataUrlSchema, photoUrlSchema, z.literal('')]).optional(),
|
||||
notifyOnDob: z.boolean().optional(),
|
||||
notifyOnGotchaDay: z.boolean().optional(),
|
||||
publicProfileEnabled: z.boolean().optional(),
|
||||
});
|
||||
|
||||
export const memorializeBirdSchema = z.object({
|
||||
memorializedOn: dateStringSchema,
|
||||
memorialNote: z.string().trim().max(1000).optional().or(z.literal('')),
|
||||
notifyOnMemorialDay: z.boolean().optional(),
|
||||
});
|
||||
|
||||
export const memorialReminderPreferenceSchema = z.object({
|
||||
notifyOnMemorialDay: z.boolean(),
|
||||
});
|
||||
|
||||
export const birdTimelineEventSchema = z
|
||||
.object({
|
||||
eventType: z.enum(['location_updated', 'owner_changed', 'manual_note']),
|
||||
eventDate: dateStringSchema.optional().or(z.literal('')),
|
||||
locationLabel: z.string().trim().max(160).optional().or(z.literal('')),
|
||||
locationDetails: verifiedLocationDetailsSchema,
|
||||
note: z.string().trim().max(500).optional().or(z.literal('')),
|
||||
})
|
||||
.refine(
|
||||
(value) =>
|
||||
value.eventType === 'owner_changed' ||
|
||||
Boolean(
|
||||
value.locationLabel?.trim() ||
|
||||
value.note?.trim() ||
|
||||
value.locationDetails?.city?.trim() ||
|
||||
value.locationDetails?.region?.trim() ||
|
||||
value.locationDetails?.country?.trim(),
|
||||
),
|
||||
'Add a location or note for this timeline item.',
|
||||
);
|
||||
|
||||
export const weightSchema = z.object({
|
||||
weightGrams: z.coerce.number().positive().max(10000),
|
||||
recordedOn: dateStringSchema,
|
||||
notes: z.string().trim().max(280).optional().or(z.literal('')),
|
||||
});
|
||||
|
||||
export const vetVisitSchema = z.object({
|
||||
visitedOn: dateStringSchema,
|
||||
clinicName: z.string().trim().min(1).max(160),
|
||||
reason: z.string().trim().min(1).max(160),
|
||||
notes: z.string().trim().max(1000).optional().or(z.literal('')),
|
||||
});
|
||||
|
||||
export const medicationSchema = z
|
||||
.object({
|
||||
name: z.string().trim().min(1).max(160),
|
||||
dosage: z.string().trim().min(1).max(160),
|
||||
frequency: z.enum(['once_daily', 'twice_daily', 'every_8_hours', 'every_6_hours', 'as_needed']),
|
||||
doseSchedule: z
|
||||
.array(
|
||||
z.object({
|
||||
key: z.string().trim().min(1).max(80),
|
||||
label: z.string().trim().min(1).max(80),
|
||||
time: z.string().trim().regex(/^$|^\d{2}:\d{2}$/),
|
||||
}),
|
||||
)
|
||||
.min(1)
|
||||
.max(8),
|
||||
route: z.string().trim().max(80).optional().or(z.literal('')),
|
||||
startDate: dateStringSchema,
|
||||
endDate: dateStringSchema.optional().or(z.literal('')),
|
||||
notes: z.string().trim().max(1000).optional().or(z.literal('')),
|
||||
remindersEnabled: z.boolean().optional(),
|
||||
})
|
||||
.refine((value) => !value.endDate || value.endDate >= value.startDate, {
|
||||
message: 'End date must be on or after start date.',
|
||||
path: ['endDate'],
|
||||
});
|
||||
|
||||
export const medicationAdministrationSchema = z.object({
|
||||
administeredOn: dateStringSchema,
|
||||
administrationSlot: z.string().trim().min(1).max(80).default('dose-1'),
|
||||
status: z.enum(['administered', 'missed']),
|
||||
notes: z.string().trim().max(500).optional().or(z.literal('')),
|
||||
});
|
||||
|
||||
export const flockNoteSchema = z.object({
|
||||
birdId: z.string().uuid().optional().nullable().or(z.literal('')),
|
||||
body: z.string().trim().min(1).max(5000),
|
||||
});
|
||||
@@ -5,7 +5,7 @@ import { deleteS3Object, putS3Object } from '../storage/s3Client.js';
|
||||
|
||||
type BirdPhotoMigrationRow = {
|
||||
id: string;
|
||||
workspace_id: number;
|
||||
workspace_id: number | null;
|
||||
name: string;
|
||||
photo_data_url: string;
|
||||
};
|
||||
|
||||
@@ -54,7 +54,7 @@ export const buildBirdPhotoObjectKey = ({
|
||||
extension,
|
||||
now = new Date(),
|
||||
}: {
|
||||
workspaceId: number;
|
||||
workspaceId: number | null;
|
||||
birdId: string;
|
||||
extension: string;
|
||||
now?: Date;
|
||||
@@ -63,7 +63,7 @@ export const buildBirdPhotoObjectKey = ({
|
||||
const safeExtension = extension.replace(/^\./, '').toLowerCase() || 'bin';
|
||||
const timestamp = now.toISOString().replace(/[:.]/g, '-');
|
||||
|
||||
return `${prefix}/workspace-${workspaceId}/${birdId}/${timestamp}.${safeExtension}`;
|
||||
return `${prefix}/${workspaceId === null ? 'unassigned' : `workspace-${workspaceId}`}/${birdId}/${timestamp}.${safeExtension}`;
|
||||
};
|
||||
|
||||
export const getImageExtensionFromContentType = (contentType: string) => {
|
||||
|
||||
+104
-3
@@ -1,12 +1,12 @@
|
||||
export type WorkspaceType = 'standard' | 'rescue';
|
||||
export type WorkspaceRole = 'owner' | 'assistant' | 'caregiver' | 'viewer';
|
||||
export type BillingPlan = 'rescue_free' | 'household_basic' | 'household_plus' | 'household_macaw';
|
||||
export type BillingPlan = 'rescue_free' | 'household_basic' | 'household_plus' | 'household_macaw' | 'household_hyacinth_macaw';
|
||||
export type BillingInterval = 'monthly' | 'yearly';
|
||||
export type SubscriptionStatus = 'active' | 'trialing' | 'past_due' | 'canceled' | 'unpaid' | 'none';
|
||||
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';
|
||||
export type BirdGender = 'unknown' | 'male' | 'female' | 'male_dna' | 'female_dna';
|
||||
|
||||
export type UserRow = {
|
||||
id: string;
|
||||
@@ -94,10 +94,19 @@ export type IntegrationTokenRow = {
|
||||
|
||||
export type BirdRow = {
|
||||
id: string;
|
||||
workspace_id: number;
|
||||
workspace_id: number | null;
|
||||
name: string;
|
||||
tag_id: string | null;
|
||||
species: string;
|
||||
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;
|
||||
vet_doctor_name: string | null;
|
||||
gender: BirdGender;
|
||||
date_of_birth: string | null;
|
||||
gotcha_day: string | null;
|
||||
@@ -108,6 +117,8 @@ export type BirdRow = {
|
||||
photo_updated_at: string | null;
|
||||
notify_on_dob: boolean;
|
||||
notify_on_gotcha_day: boolean;
|
||||
public_profile_code: string | null;
|
||||
public_profile_enabled: boolean;
|
||||
memorialized_at: string | null;
|
||||
memorialized_on: string | null;
|
||||
memorial_note: string | null;
|
||||
@@ -118,6 +129,7 @@ export type BirdRow = {
|
||||
};
|
||||
|
||||
export type LostBirdMatchRow = BirdRow & {
|
||||
workspace_id: number;
|
||||
workspace_name: string;
|
||||
workspace_billing_email: string | null;
|
||||
};
|
||||
@@ -125,6 +137,7 @@ export type LostBirdMatchRow = BirdRow & {
|
||||
export type BirdMilestoneReminderType = 'hatch_day' | 'gotcha_day' | 'memorial_day';
|
||||
|
||||
export type BirdMilestoneReminderCandidateRow = BirdRow & {
|
||||
workspace_id: number;
|
||||
workspace_name: string;
|
||||
reminder_type: BirdMilestoneReminderType;
|
||||
reminder_date: string;
|
||||
@@ -153,6 +166,38 @@ export type PendingBirdTransferRow = {
|
||||
created_at: string;
|
||||
};
|
||||
|
||||
export type BirdTransferCodeRow = {
|
||||
id: string;
|
||||
code: string;
|
||||
bird_id: string;
|
||||
source_workspace_id: number;
|
||||
requested_by_user_id: string;
|
||||
completed_at: string | null;
|
||||
completed_workspace_id: number | null;
|
||||
revoked_at: string | null;
|
||||
created_at: string;
|
||||
};
|
||||
|
||||
export type BirdTimelineEventType = 'profile_created' | 'transferred' | 'location_updated' | 'owner_changed' | 'manual_note' | 'removed_from_flock' | 'joined_flock';
|
||||
|
||||
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;
|
||||
@@ -181,6 +226,7 @@ export type MedicationRow = {
|
||||
start_date: string;
|
||||
end_date: string | null;
|
||||
notes: string | null;
|
||||
reminders_enabled: boolean;
|
||||
};
|
||||
|
||||
export type MedicationDoseScheduleItem = {
|
||||
@@ -189,6 +235,34 @@ export type MedicationDoseScheduleItem = {
|
||||
time: string;
|
||||
};
|
||||
|
||||
export type MedicationReminderCandidateRow = BirdRow & {
|
||||
workspace_id: number;
|
||||
workspace_name: string;
|
||||
medication_id: string;
|
||||
medication_name: string;
|
||||
dosage: string;
|
||||
frequency: string;
|
||||
dose_schedule: MedicationDoseScheduleItem[];
|
||||
route: string | null;
|
||||
medication_start_date: string;
|
||||
medication_end_date: string | null;
|
||||
medication_notes: string | null;
|
||||
scheduled_on: string;
|
||||
administration_slot: string;
|
||||
administration_label: string;
|
||||
administration_time: string;
|
||||
};
|
||||
|
||||
export type MedicationReminderDeliveryRow = {
|
||||
id: string;
|
||||
medication_id: string;
|
||||
bird_id: string;
|
||||
workspace_id: number;
|
||||
scheduled_on: string;
|
||||
administration_slot: string;
|
||||
delivered_at: string;
|
||||
};
|
||||
|
||||
export type MedicationAdministrationRow = {
|
||||
id: string;
|
||||
medication_id: string;
|
||||
@@ -201,6 +275,33 @@ export type MedicationAdministrationRow = {
|
||||
created_at: string;
|
||||
};
|
||||
|
||||
export type FlockNoteRow = {
|
||||
id: string;
|
||||
workspace_id: number;
|
||||
bird_id: string | null;
|
||||
bird_name: string | null;
|
||||
title: string;
|
||||
body: string;
|
||||
created_by_user_id: string | null;
|
||||
created_by_name: string | null;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
};
|
||||
|
||||
export type AuditLogEntryRow = {
|
||||
id: string;
|
||||
workspace_id: number;
|
||||
user_id: string | null;
|
||||
actor_name: string | null;
|
||||
actor_email: string | null;
|
||||
action: string;
|
||||
entity_type: string;
|
||||
entity_id: string | null;
|
||||
entity_name: string | null;
|
||||
details: Record<string, unknown>;
|
||||
created_at: string;
|
||||
};
|
||||
|
||||
export type AuthContext = {
|
||||
user: UserRow;
|
||||
session: AuthSessionRow;
|
||||
|
||||
+82
-1
@@ -1,17 +1,42 @@
|
||||
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 { runBirdMilestoneReminders, startBirdMilestoneReminderScheduler } from './app.js';
|
||||
import {
|
||||
sendWeightReminderNotification,
|
||||
runBirdMilestoneReminders,
|
||||
runMedicationReminders,
|
||||
startBirdMilestoneReminderScheduler,
|
||||
startMedicationReminderScheduler,
|
||||
} from './app.js';
|
||||
import {
|
||||
adoptionReportQueueName,
|
||||
closeAdoptionReportQueue,
|
||||
type AdoptionReportJobData,
|
||||
type AdoptionReportJobResult,
|
||||
} from './queues/adoptionReportQueue.js';
|
||||
import {
|
||||
birdMilestoneReminderQueueName,
|
||||
closeBirdMilestoneReminderQueue,
|
||||
type BirdMilestoneReminderJobData,
|
||||
type BirdMilestoneReminderJobResult,
|
||||
} from './queues/birdMilestoneReminderQueue.js';
|
||||
import {
|
||||
closeMedicationReminderQueue,
|
||||
medicationReminderQueueName,
|
||||
type MedicationReminderJobData,
|
||||
type MedicationReminderJobResult,
|
||||
} from './queues/medicationReminderQueue.js';
|
||||
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;
|
||||
|
||||
const startWorker = async () => {
|
||||
await ensureSchema();
|
||||
@@ -35,14 +60,70 @@ const startWorker = async () => {
|
||||
console.error(`Bird milestone reminder job failed: id=${job?.id ?? 'unknown'}`, error);
|
||||
});
|
||||
|
||||
medicationReminderWorker = new Worker<MedicationReminderJobData, MedicationReminderJobResult>(
|
||||
medicationReminderQueueName,
|
||||
async (job) => {
|
||||
const result = await runMedicationReminders(job.data.runDate, job.data.currentTime);
|
||||
console.log(
|
||||
`Medication reminder job completed for ${result.runDate} ${result.currentTime}: checked=${result.checked}, sent=${result.sent}, skipped=${result.skipped}, failed=${result.failed}`,
|
||||
);
|
||||
return result;
|
||||
},
|
||||
{
|
||||
connection: redisConnection,
|
||||
concurrency: 1,
|
||||
},
|
||||
);
|
||||
|
||||
medicationReminderWorker.on('failed', (job, error) => {
|
||||
console.error(`Medication reminder job failed: id=${job?.id ?? 'unknown'}`, error);
|
||||
});
|
||||
|
||||
adoptionReportWorker = new Worker<AdoptionReportJobData, AdoptionReportJobResult>(
|
||||
adoptionReportQueueName,
|
||||
async (job) => {
|
||||
const pdf = await renderAdoptionReportForBird(job.data);
|
||||
console.log(`Adoption report job completed: id=${job.id ?? 'unknown'}, birdId=${job.data.birdId}, bytes=${pdf.length}`);
|
||||
return {
|
||||
pdfBase64: pdf.toString('base64'),
|
||||
};
|
||||
},
|
||||
{
|
||||
connection: redisConnection,
|
||||
concurrency: 1,
|
||||
},
|
||||
);
|
||||
|
||||
adoptionReportWorker.on('failed', (job, error) => {
|
||||
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.');
|
||||
};
|
||||
|
||||
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();
|
||||
await closeBirdMilestoneReminderQueue();
|
||||
await closeMedicationReminderQueue();
|
||||
await closeAdoptionReportQueue();
|
||||
await db.close();
|
||||
process.exit(0);
|
||||
};
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
// Run against the disposable database described in docs/BEHAVIOR_JOURNAL.md.
|
||||
import assert from 'node:assert/strict';
|
||||
import { createHash, 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: '55439', POSTGRES_DB: 'behavior_test',
|
||||
POSTGRES_USER: 'postgres', POSTGRES_PASSWORD: 'behavior_test_only', PORT: '55440',
|
||||
MILESTONE_REMINDERS_ENABLED: 'false', MEDICATION_REMINDERS_ENABLED: 'false', WEIGHT_REMINDERS_ENABLED: 'false',
|
||||
});
|
||||
const { db } = await import('../dist/db/client.js');
|
||||
const { ensureSchema } = await import('../dist/db/schema.js');
|
||||
let server;
|
||||
let logs = '';
|
||||
try {
|
||||
await ensureSchema();
|
||||
await ensureSchema(); // Schema and seed must be safe to re-run.
|
||||
const workspace = 100000 + Math.floor(Math.random() * 1000000000);
|
||||
const otherWorkspace = workspace + 1;
|
||||
await db.query(`INSERT INTO workspaces (id, name, workspace_type, rescue_verification_status) VALUES ($1, 'Journal test', 'rescue', 'approved'), ($2, 'Other test', 'rescue', 'approved')`, [workspace, otherWorkspace]);
|
||||
const user = randomUUID();
|
||||
await db.query(`INSERT INTO users (id, email, name) VALUES ($1, $2, 'Journal tester')`, [user, `${user}@example.test`]);
|
||||
await db.query(`INSERT INTO workspace_members (workspace_id, user_id, invite_email, name, role, accepted_at) VALUES ($1, $2, 'journal@example.test', 'Journal tester', 'owner', NOW())`, [workspace, user]);
|
||||
const token = randomUUID();
|
||||
await db.query(`INSERT INTO auth_sessions (user_id, active_workspace_id, token_hash, expires_at) VALUES ($1, $2, $3, NOW() + INTERVAL '1 hour')`, [user, workspace, createHash('sha256').update(token).digest('hex')]);
|
||||
const bird = randomUUID(), otherBird = randomUUID(), secondBird = randomUUID();
|
||||
for (const [id, flock] of [[bird, workspace], [secondBird, workspace], [otherBird, otherWorkspace]]) {
|
||||
await db.query(`INSERT INTO birds (id, workspace_id, name, species) VALUES ($1, $2, 'Journal bird', 'Parrot')`, [id, flock]);
|
||||
}
|
||||
server = spawn(process.execPath, [fileURLToPath(new URL('../dist/app.js', import.meta.url))], { cwd: '/tmp', env: process.env, stdio: ['ignore', 'pipe', 'pipe'] });
|
||||
server.stdout.on('data', (data) => { logs += data; }); server.stderr.on('data', (data) => { logs += data; });
|
||||
for (let attempt = 0; attempt < 100 && !logs.includes('listening'); attempt++) await new Promise((resolve) => setTimeout(resolve, 100));
|
||||
assert.match(logs, /listening/, logs);
|
||||
async function api(path, method = 'GET', body, status = 200, authenticated = true) {
|
||||
const response = await fetch(`http://127.0.0.1:55440/api${path}`, { method, headers: { 'Content-Type': 'application/json', ...(authenticated ? { Authorization: `Bearer ${token}` } : {}) }, ...(body ? { body: JSON.stringify(body) } : {}) });
|
||||
const data = response.status === 204 ? null : await response.json();
|
||||
assert.equal(response.status, status, JSON.stringify(data)); return data;
|
||||
}
|
||||
const base = `/birds/${bird}`;
|
||||
const range = '?from=2026-10-01T00:00:00-04:00&to=2026-11-01T00:00:00-04:00';
|
||||
const types = (await api(`${base}/behavior-types`)).behaviorTypes;
|
||||
assert.equal(types.length, 9);
|
||||
const custom = (await api(`${base}/behavior-types`, 'POST', { name: 'Wing stretching', description: 'Observed stretching' }, 201)).behaviorType;
|
||||
const duplicate = (await api(`${base}/behavior-types`, 'POST', { name: 'wing stretching' }, 201)).behaviorType;
|
||||
assert.equal(custom.id, duplicate.id);
|
||||
const foreignType = (await db.query(`INSERT INTO behavior_types (workspace_id, name) VALUES ($1, 'Private behavior') RETURNING id`, [otherWorkspace])).rows[0].id;
|
||||
const input = { behaviorTypeId: custom.id, occurredAt: '2026-10-05T23:30:12.123-04:00', durationSeconds: 90, severity: 3, notes: 'Observed after play' };
|
||||
const first = (await api(`${base}/behaviors`, 'POST', input, 201)).occurrence;
|
||||
assert.equal(first.occurredAt, '2026-10-06T03:30:12.123Z');
|
||||
const second = (await api(`${base}/behaviors`, 'POST', { ...input, behaviorTypeId: types[0].id }, 201)).occurrence;
|
||||
await api(`${base}/behaviors`, 'POST', { ...input, occurredAt: '2026-11-01T00:00:00-04:00' }, 201);
|
||||
assert.equal((await api(`${base}/behaviors${range}`)).occurrences.length, 2);
|
||||
assert.equal((await api(`${base}/behaviors${range}&behaviorTypeId=${custom.id}`)).occurrences.length, 1);
|
||||
assert.equal((await api(`/birds/${secondBird}/behaviors${range}`)).occurrences.length, 0);
|
||||
const edited = (await api(`${base}/behaviors/${first.id}`, 'PUT', { ...input, notes: 'Edited note', severity: null, durationSeconds: null })).occurrence;
|
||||
assert.equal(edited.notes, 'Edited note'); assert.equal(edited.severity, null); assert.equal(edited.durationSeconds, null);
|
||||
assert.equal(edited.createdAt, first.createdAt); assert.equal(edited.occurredAt, first.occurredAt);
|
||||
for (const bad of [{ severity: 6 }, { durationSeconds: -1 }, { occurredAt: '2026-02-30T12:00:00Z' }, { occurredAt: '2026-10-05T12:00:00' }]) await api(`${base}/behaviors`, 'POST', { ...input, ...bad }, 400);
|
||||
await api(`${base}/behaviors`, 'POST', { ...input, behaviorTypeId: foreignType }, 404);
|
||||
await api(`/birds/${otherBird}/behavior-types`, 'GET', undefined, 404);
|
||||
await api(`/birds/${otherBird}/behaviors${range}`, 'GET', undefined, 404);
|
||||
await api(`/birds/${otherBird}/behaviors`, 'POST', input, 404);
|
||||
await api(`/birds/${secondBird}/behaviors/${first.id}`, 'PUT', input, 404);
|
||||
await api(`/birds/${secondBird}/behaviors/${first.id}`, 'DELETE', undefined, 404);
|
||||
await api(`${base}/behavior-types`, 'GET', undefined, 401, false);
|
||||
await api(`${base}/behaviors?from=invalid&to=invalid`, 'GET', undefined, 400);
|
||||
await db.query(`UPDATE workspace_members SET role = 'viewer' WHERE user_id = $1`, [user]);
|
||||
await api(`${base}/behaviors`, 'POST', input, 403);
|
||||
await api(`${base}/behaviors/${first.id}`, 'PUT', input, 403);
|
||||
await api(`${base}/behaviors/${first.id}`, 'DELETE', undefined, 403);
|
||||
await db.query(`UPDATE workspace_members SET role = 'owner' WHERE user_id = $1`, [user]);
|
||||
await db.query(`UPDATE workspaces SET rescue_verification_status = 'pending' WHERE id = $1`, [workspace]);
|
||||
await api(`${base}/behaviors`, 'POST', input, 402);
|
||||
await db.query(`UPDATE workspaces SET rescue_verification_status = 'approved' WHERE id = $1`, [workspace]);
|
||||
await db.query(`UPDATE birds SET memorialized_at = NOW() WHERE id = $1`, [bird]);
|
||||
await api(`${base}/behaviors`, 'POST', input, 409);
|
||||
await api(`${base}/behaviors/${first.id}`, 'DELETE', undefined, 409);
|
||||
await db.query(`UPDATE birds SET memorialized_at = NULL WHERE id = $1`, [bird]);
|
||||
await api(`${base}/behaviors/${second.id}`, 'DELETE', undefined, 204);
|
||||
assert.equal((await api(`${base}/behaviors${range}`)).occurrences.length, 1);
|
||||
// Transfer the bird: old flock loses access, new flock retains normalized history.
|
||||
await db.query(`UPDATE birds SET workspace_id = $1 WHERE id = $2`, [otherWorkspace, bird]);
|
||||
await api(`${base}/behaviors${range}`, 'GET', undefined, 404);
|
||||
await db.query(`INSERT INTO workspace_members (workspace_id, user_id, invite_email, name, role, accepted_at) VALUES ($1, $2, 'journal@example.test', 'Journal tester', 'owner', NOW())`, [otherWorkspace, user]);
|
||||
await db.query(`UPDATE auth_sessions SET active_workspace_id = $1 WHERE user_id = $2`, [otherWorkspace, user]);
|
||||
assert.equal((await api(`${base}/behaviors${range}`)).occurrences[0].behaviorName, 'Wing stretching');
|
||||
assert.ok((await api(`${base}/behavior-types`)).behaviorTypes.some((type) => type.id === custom.id));
|
||||
await api(`${base}/behaviors/${first.id}`, 'PUT', input);
|
||||
console.log('PASS: schema repeatability; defaults/custom types; create/edit/delete; bird/behavior/month filters; timestamp precision; auth/role/billing/memorial restrictions; flock isolation and transfer history.');
|
||||
} finally {
|
||||
if (server && server.exitCode === null) { const exited = once(server, 'exit'); server.kill('SIGTERM'); await exited; }
|
||||
await db.close();
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
// Uses only the disposable database and API ports documented in docs/BIRD_MEMBERSHIP.md.
|
||||
import assert from 'node:assert/strict';
|
||||
import { createHash, 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: '55439', POSTGRES_DB: 'behavior_test',
|
||||
POSTGRES_USER: 'postgres', POSTGRES_PASSWORD: 'behavior_test_only', PORT: '55440',
|
||||
MILESTONE_REMINDERS_ENABLED: 'false', MEDICATION_REMINDERS_ENABLED: 'false', WEIGHT_REMINDERS_ENABLED: 'false',
|
||||
});
|
||||
const { db } = await import('../dist/db/client.js');
|
||||
const { ensureSchema } = await import('../dist/db/schema.js');
|
||||
const { removeBirdFromFlock, claimUnassignedBird } = await import('../dist/repositories/birdMembershipRepository.js');
|
||||
let server;
|
||||
let output = '';
|
||||
try {
|
||||
await ensureSchema();
|
||||
await ensureSchema();
|
||||
const baseId = 100000 + Math.floor(Math.random() * 1000000000);
|
||||
const accounts = [];
|
||||
for (let i = 0; i < 3; i++) {
|
||||
const workspace = baseId + i, user = randomUUID(), token = randomUUID(), email = `${user}@example.test`;
|
||||
await db.query(`INSERT INTO workspaces (id, name, workspace_type, rescue_verification_status) VALUES ($1, $2, 'rescue', 'approved')`, [workspace, `Membership test ${i}`]);
|
||||
await db.query(`INSERT INTO users (id, email, name) VALUES ($1, $2, 'Tester')`, [user, email]);
|
||||
await db.query(`INSERT INTO workspace_members (workspace_id, user_id, invite_email, name, role, accepted_at) VALUES ($1, $2, $3, 'Tester', 'owner', NOW())`, [workspace, user, email]);
|
||||
await db.query(`INSERT INTO auth_sessions (user_id, active_workspace_id, token_hash, expires_at) VALUES ($1, $2, $3, NOW() + INTERVAL '1 hour')`, [user, workspace, createHash('sha256').update(token).digest('hex')]);
|
||||
accounts.push({ workspace, user, token });
|
||||
}
|
||||
const [source, destination, rival] = accounts;
|
||||
const bird = randomUUID(), tagId = `BAND-${randomUUID()}`, publicCode = randomUUID().slice(0, 20);
|
||||
const photo = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+a2ioAAAAASUVORK5CYII=';
|
||||
await db.query(`INSERT INTO birds (id, workspace_id, name, tag_id, species, photo_data_url, public_profile_code, public_profile_enabled)
|
||||
VALUES ($1, $2, 'Preserved bird', $3, 'Parrot', $4, $5, TRUE)`, [bird, source.workspace, tagId, photo, publicCode]);
|
||||
await db.query(`INSERT INTO weight_records (bird_id, weight_grams, recorded_on) VALUES ($1, 120, CURRENT_DATE)`, [bird]);
|
||||
await db.query(`INSERT INTO vet_visits (bird_id, visited_on, clinic_name, reason) VALUES ($1, CURRENT_DATE, 'Clinic', 'Checkup')`, [bird]);
|
||||
const med = (await db.query(`INSERT INTO medications (bird_id, name, dosage, frequency, start_date) VALUES ($1, 'Existing medication', '1 ml', 'Daily', CURRENT_DATE) RETURNING id`, [bird])).rows[0].id;
|
||||
await db.query(`INSERT INTO medication_administrations (medication_id, bird_id, administered_on, status) VALUES ($1, $2, CURRENT_DATE, 'administered')`, [med, bird]);
|
||||
const behaviorType = (await db.query(`INSERT INTO behavior_types (workspace_id, name) VALUES ($1, 'Existing custom behavior') RETURNING id`, [source.workspace])).rows[0].id;
|
||||
await db.query(`INSERT INTO behavior_occurrences (bird_id, behavior_type_id, occurred_at, notes) VALUES ($1, $2, NOW(), 'Existing occurrence')`, [bird, behaviorType]);
|
||||
const birdNote = (await db.query(`INSERT INTO flock_notes (workspace_id, bird_id, title, body) VALUES ($1, $2, 'Bird note', 'Keep with bird') RETURNING id`, [source.workspace, bird])).rows[0].id;
|
||||
await db.query(`INSERT INTO flock_notes (workspace_id, title, body) VALUES ($1, 'Flock only', 'Keep in source flock')`, [source.workspace]);
|
||||
const transferCode = randomUUID().slice(0, 20);
|
||||
await db.query(`INSERT INTO bird_transfer_codes (code, bird_id, source_workspace_id, requested_by_user_id) VALUES ($1, $2, $3, $4)`, [transferCode, bird, source.workspace, source.user]);
|
||||
await db.query(`INSERT INTO pending_bird_transfers (bird_id, source_workspace_id, destination_owner_email, requested_by_user_id) VALUES ($1, $2, 'pending@example.test', $3)`, [bird, source.workspace, source.user]);
|
||||
// A late failure must roll back the bird, notes, and transfer changes together.
|
||||
await assert.rejects(() => removeBirdFromFlock(bird, source.workspace, randomUUID()));
|
||||
assert.equal((await db.query(`SELECT workspace_id FROM birds WHERE id = $1`, [bird])).rows[0].workspace_id, source.workspace);
|
||||
assert.equal((await db.query(`SELECT revoked_at FROM bird_transfer_codes WHERE code = $1`, [transferCode])).rows[0].revoked_at, null);
|
||||
server = spawn(process.execPath, [fileURLToPath(new URL('../dist/app.js', import.meta.url))], { cwd: '/tmp', env: process.env, stdio: ['ignore', 'pipe', 'pipe'] });
|
||||
server.stdout.on('data', (data) => { output += data; }); server.stderr.on('data', (data) => { output += data; });
|
||||
for (let i = 0; i < 100 && !output.includes('listening'); i++) await new Promise((resolve) => setTimeout(resolve, 100));
|
||||
assert.match(output, /listening/, output);
|
||||
async function api(account, path, method = 'GET', body, status = 200) {
|
||||
const response = await fetch(`http://127.0.0.1:55440/api${path}`, { method, headers: { 'Content-Type': 'application/json', ...(account ? { Authorization: `Bearer ${account.token}` } : {}) }, ...(body ? { body: JSON.stringify(body) } : {}) });
|
||||
const data = response.status === 204 ? null : await response.json();
|
||||
if (status !== null) assert.equal(response.status, status, JSON.stringify(data));
|
||||
return { status: response.status, data };
|
||||
}
|
||||
const matchPath = `/birds/unassigned-match?${new URLSearchParams({ tagId })}`;
|
||||
assert.deepEqual((await api(destination, matchPath)).data, { available: false });
|
||||
await api(destination, '/birds/claim', 'POST', { tagId, confirmHistory: true }, 409);
|
||||
await api(destination, `/birds/${bird}`, 'DELETE', undefined, 404);
|
||||
await api(source, `/birds/${bird}`, 'DELETE', undefined, 204);
|
||||
const removed = (await db.query(`SELECT * FROM birds WHERE id = $1`, [bird])).rows[0];
|
||||
assert.equal(removed.workspace_id, null); assert.equal(removed.photo_data_url, photo); assert.equal(removed.public_profile_enabled, false);
|
||||
for (const table of ['weight_records', 'vet_visits', 'medications', 'medication_administrations', 'behavior_occurrences', 'flock_notes']) {
|
||||
assert.equal((await db.query(`SELECT COUNT(*)::int AS count FROM ${table} WHERE bird_id = $1`, [bird])).rows[0].count, 1, table);
|
||||
}
|
||||
assert.equal((await db.query(`SELECT workspace_id FROM flock_notes WHERE id = $1`, [birdNote])).rows[0].workspace_id, null);
|
||||
assert.ok((await db.query(`SELECT revoked_at FROM bird_transfer_codes WHERE code = $1`, [transferCode])).rows[0].revoked_at);
|
||||
assert.equal((await db.query(`SELECT COUNT(*)::int AS count FROM pending_bird_transfers WHERE bird_id = $1`, [bird])).rows[0].count, 0);
|
||||
assert.equal((await api(source, '/birds')).data.birds.length, 0);
|
||||
assert.equal((await api(source, '/notes')).data.notes.length, 1);
|
||||
assert.equal((await api(source, `/birds/${bird}/weights`)).data.weights.length, 0);
|
||||
await api(null, `/public/birds/${publicCode}`, 'GET', undefined, 404);
|
||||
assert.deepEqual((await api(destination, matchPath)).data, { available: true });
|
||||
await api(null, matchPath, 'GET', undefined, 401);
|
||||
await api(destination, '/birds/unassigned-match?tagId=unknown', 'GET', undefined, 400);
|
||||
assert.deepEqual((await api(destination, `/birds/unassigned-match?tagId=${encodeURIComponent(tagId.slice(0, -1))}`)).data, { available: false });
|
||||
await api(destination, '/birds/claim', 'POST', { tagId }, 400);
|
||||
await db.query(`UPDATE workspace_members SET role = 'viewer' WHERE user_id = $1`, [destination.user]);
|
||||
await api(destination, matchPath, 'GET', undefined, 403);
|
||||
await api(destination, '/birds/claim', 'POST', { tagId, confirmHistory: true }, 403);
|
||||
await db.query(`UPDATE workspace_members SET role = 'owner' WHERE user_id = $1`, [destination.user]);
|
||||
await db.query(`UPDATE workspaces SET rescue_verification_status = 'pending' WHERE id = $1`, [destination.workspace]);
|
||||
await api(destination, '/birds/claim', 'POST', { tagId, confirmHistory: true }, 402);
|
||||
await db.query(`UPDATE workspaces SET rescue_verification_status = 'approved' WHERE id = $1`, [destination.workspace]);
|
||||
assert.equal((await api(destination, '/birds', 'POST', { name: 'New name should not replace existing', species: 'Parrot', tagId }, 409)).data.code, 'bird_history_available');
|
||||
await assert.rejects(() => claimUnassignedBird(tagId, destination.workspace, randomUUID()));
|
||||
assert.equal((await db.query(`SELECT workspace_id FROM birds WHERE id = $1`, [bird])).rows[0].workspace_id, null);
|
||||
const claimed = (await api(destination, '/birds/claim', 'POST', { tagId: ` ${tagId.toLowerCase()} `, confirmHistory: true })).data;
|
||||
assert.equal(claimed.bird.id, bird); assert.equal(claimed.bird.name, 'Preserved bird'); assert.equal(claimed.historyImported, true); assert.equal(claimed.bird.photoDataUrl, photo);
|
||||
assert.equal((await api(destination, `/birds/${bird}/weights`)).data.weights.length, 1);
|
||||
assert.equal((await api(destination, `/birds/${bird}/vet-visits`)).data.vetVisits.length, 1);
|
||||
assert.equal((await api(destination, '/notes')).data.notes[0].id, birdNote);
|
||||
assert.equal((await api(source, '/notes')).data.notes.length, 1);
|
||||
assert.ok((await api(destination, `/birds/${bird}/behavior-types`)).data.behaviorTypes.some((type) => type.id === behaviorType));
|
||||
const timeline = (await api(destination, `/birds/${bird}/timeline`)).data.events;
|
||||
assert.ok(timeline.some((event) => event.eventType === 'removed_from_flock'));
|
||||
assert.ok(timeline.some((event) => event.eventType === 'joined_flock'));
|
||||
await api(source, `/birds/${bird}`, 'DELETE', undefined, 404);
|
||||
await api(rival, '/birds/claim', 'POST', { tagId, confirmHistory: true }, 409);
|
||||
// Remove again and race two different flocks. Exactly one claim must succeed.
|
||||
await api(destination, `/birds/${bird}`, 'DELETE', undefined, 204);
|
||||
const race = await Promise.all([source, rival].map((account) => api(account, '/birds/claim', 'POST', { tagId, confirmHistory: true }, null)));
|
||||
assert.deepEqual(race.map((result) => result.status).sort(), [200, 409]);
|
||||
const bandless = randomUUID();
|
||||
await db.query(`INSERT INTO birds (id, workspace_id, name, species) VALUES ($1, $2, 'No band', 'Parrot')`, [bandless, source.workspace]);
|
||||
await api(source, `/birds/${bandless}`, 'DELETE', undefined, 204);
|
||||
assert.equal((await db.query(`SELECT workspace_id FROM birds WHERE id = $1`, [bandless])).rows[0].workspace_id, null);
|
||||
console.log('PASS: reversible flock removal, retained profile/photo/all care records, notes isolation, sharing/transfer revocation, exact normalized band matching, explicit history consent, permissions, rollback, and concurrent claims.');
|
||||
} finally {
|
||||
if (server && server.exitCode === null) { const done = once(server, 'exit'); server.kill('SIGTERM'); await done; }
|
||||
await db.close();
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
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'
|
||||
@@ -0,0 +1,182 @@
|
||||
// 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 & <Peep>'));
|
||||
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();
|
||||
}
|
||||
+31
-3
@@ -43,6 +43,7 @@ services:
|
||||
POSTGRES_USER: ${POSTGRES_USER:-flockpal}
|
||||
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?set POSTGRES_PASSWORD for production}
|
||||
REDIS_URL: ${REDIS_URL:-redis://redis:6379}
|
||||
ADOPTION_REPORT_RENDER_TIMEOUT_MS: ${ADOPTION_REPORT_RENDER_TIMEOUT_MS:-45000}
|
||||
IMAGE_STORAGE_PROVIDER: ${IMAGE_STORAGE_PROVIDER:-database}
|
||||
S3_ENDPOINT: ${S3_ENDPOINT:-}
|
||||
S3_REGION: ${S3_REGION:-}
|
||||
@@ -54,10 +55,13 @@ 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:-}
|
||||
GOOGLE_CLIENT_SECRET: ${GOOGLE_CLIENT_SECRET:-}
|
||||
@@ -73,9 +77,12 @@ services:
|
||||
STRIPE_PRICE_HOUSEHOLD_INDIANRINGNECK: ${STRIPE_PRICE_HOUSEHOLD_INDIANRINGNECK:-}
|
||||
STRIPE_PRICE_HOUSEHOLD_INDIANRINGNECK_MONTHLY: ${STRIPE_PRICE_HOUSEHOLD_INDIANRINGNECK_MONTHLY:-}
|
||||
STRIPE_PRICE_HOUSEHOLD_INDIANRINGNECK_YEARLY: ${STRIPE_PRICE_HOUSEHOLD_INDIANRINGNECK_YEARLY:-}
|
||||
STRIPE_PRICE_HOUSEHOLD_MACAW: ${STRIPE_PRICE_HOUSEHOLD_MACAW:-}
|
||||
STRIPE_PRICE_HOUSEHOLD_MACAW_MONTHLY: ${STRIPE_PRICE_HOUSEHOLD_MACAW_MONTHLY:-}
|
||||
STRIPE_PRICE_HOUSEHOLD_MACAW_YEARLY: ${STRIPE_PRICE_HOUSEHOLD_MACAW_YEARLY:-}
|
||||
STRIPE_PRICE_HOUSEHOLD_AFRICAN_GREY: ${STRIPE_PRICE_HOUSEHOLD_AFRICAN_GREY:-}
|
||||
STRIPE_PRICE_HOUSEHOLD_AFRICAN_GREY_MONTHLY: ${STRIPE_PRICE_HOUSEHOLD_AFRICAN_GREY_MONTHLY:-}
|
||||
STRIPE_PRICE_HOUSEHOLD_AFRICAN_GREY_YEARLY: ${STRIPE_PRICE_HOUSEHOLD_AFRICAN_GREY_YEARLY:-}
|
||||
STRIPE_PRICE_HOUSEHOLD_HYACINTH_MACAW: ${STRIPE_PRICE_HOUSEHOLD_HYACINTH_MACAW:-}
|
||||
STRIPE_PRICE_HOUSEHOLD_HYACINTH_MACAW_MONTHLY: ${STRIPE_PRICE_HOUSEHOLD_HYACINTH_MACAW_MONTHLY:-}
|
||||
STRIPE_PRICE_HOUSEHOLD_HYACINTH_MACAW_YEARLY: ${STRIPE_PRICE_HOUSEHOLD_HYACINTH_MACAW_YEARLY:-}
|
||||
STRIPE_CHECKOUT_SUCCESS_URL: ${STRIPE_CHECKOUT_SUCCESS_URL:-${FRONTEND_URL}/?billing=success}
|
||||
STRIPE_CHECKOUT_CANCEL_URL: ${STRIPE_CHECKOUT_CANCEL_URL:-${FRONTEND_URL}/?billing=cancelled}
|
||||
STRIPE_PORTAL_RETURN_URL: ${STRIPE_PORTAL_RETURN_URL:-${FRONTEND_URL}/?billing=portal}
|
||||
@@ -91,6 +98,12 @@ services:
|
||||
condition: service_healthy
|
||||
redis:
|
||||
condition: service_healthy
|
||||
healthcheck:
|
||||
test: ["CMD", "node", "dist/healthcheck.js", "api-ready"]
|
||||
interval: 30s
|
||||
timeout: 10s
|
||||
retries: 3
|
||||
start_period: 30s
|
||||
labels:
|
||||
- traefik.enable=true
|
||||
- traefik.docker.network=traefik
|
||||
@@ -131,10 +144,13 @@ 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:-}
|
||||
SMTP_PORT: ${SMTP_PORT:-587}
|
||||
@@ -148,6 +164,12 @@ services:
|
||||
condition: service_healthy
|
||||
redis:
|
||||
condition: service_healthy
|
||||
healthcheck:
|
||||
test: ["CMD", "node", "dist/healthcheck.js", "worker"]
|
||||
interval: 30s
|
||||
timeout: 10s
|
||||
retries: 3
|
||||
start_period: 30s
|
||||
restart: unless-stopped
|
||||
|
||||
frontend:
|
||||
@@ -159,6 +181,12 @@ services:
|
||||
container_name: flockpal-frontend
|
||||
depends_on:
|
||||
- backend
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "wget -q -O /dev/null http://127.0.0.1/healthz"]
|
||||
interval: 30s
|
||||
timeout: 5s
|
||||
retries: 3
|
||||
start_period: 10s
|
||||
labels:
|
||||
- traefik.enable=true
|
||||
- traefik.docker.network=traefik
|
||||
|
||||
+21
-4
@@ -41,6 +41,7 @@ services:
|
||||
POSTGRES_USER: ${POSTGRES_USER:-flockpal}
|
||||
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-flockpal_dev_password}
|
||||
REDIS_URL: ${REDIS_URL:-redis://redis:6379}
|
||||
ADOPTION_REPORT_RENDER_TIMEOUT_MS: ${ADOPTION_REPORT_RENDER_TIMEOUT_MS:-45000}
|
||||
IMAGE_STORAGE_PROVIDER: ${IMAGE_STORAGE_PROVIDER:-database}
|
||||
S3_ENDPOINT: ${S3_ENDPOINT:-}
|
||||
S3_REGION: ${S3_REGION:-}
|
||||
@@ -52,10 +53,13 @@ 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:-}
|
||||
GOOGLE_CLIENT_SECRET: ${GOOGLE_CLIENT_SECRET:-}
|
||||
@@ -71,9 +75,12 @@ services:
|
||||
STRIPE_PRICE_HOUSEHOLD_INDIANRINGNECK: ${STRIPE_PRICE_HOUSEHOLD_INDIANRINGNECK:-}
|
||||
STRIPE_PRICE_HOUSEHOLD_INDIANRINGNECK_MONTHLY: ${STRIPE_PRICE_HOUSEHOLD_INDIANRINGNECK_MONTHLY:-}
|
||||
STRIPE_PRICE_HOUSEHOLD_INDIANRINGNECK_YEARLY: ${STRIPE_PRICE_HOUSEHOLD_INDIANRINGNECK_YEARLY:-}
|
||||
STRIPE_PRICE_HOUSEHOLD_MACAW: ${STRIPE_PRICE_HOUSEHOLD_MACAW:-}
|
||||
STRIPE_PRICE_HOUSEHOLD_MACAW_MONTHLY: ${STRIPE_PRICE_HOUSEHOLD_MACAW_MONTHLY:-}
|
||||
STRIPE_PRICE_HOUSEHOLD_MACAW_YEARLY: ${STRIPE_PRICE_HOUSEHOLD_MACAW_YEARLY:-}
|
||||
STRIPE_PRICE_HOUSEHOLD_AFRICAN_GREY: ${STRIPE_PRICE_HOUSEHOLD_AFRICAN_GREY:-}
|
||||
STRIPE_PRICE_HOUSEHOLD_AFRICAN_GREY_MONTHLY: ${STRIPE_PRICE_HOUSEHOLD_AFRICAN_GREY_MONTHLY:-}
|
||||
STRIPE_PRICE_HOUSEHOLD_AFRICAN_GREY_YEARLY: ${STRIPE_PRICE_HOUSEHOLD_AFRICAN_GREY_YEARLY:-}
|
||||
STRIPE_PRICE_HOUSEHOLD_HYACINTH_MACAW: ${STRIPE_PRICE_HOUSEHOLD_HYACINTH_MACAW:-}
|
||||
STRIPE_PRICE_HOUSEHOLD_HYACINTH_MACAW_MONTHLY: ${STRIPE_PRICE_HOUSEHOLD_HYACINTH_MACAW_MONTHLY:-}
|
||||
STRIPE_PRICE_HOUSEHOLD_HYACINTH_MACAW_YEARLY: ${STRIPE_PRICE_HOUSEHOLD_HYACINTH_MACAW_YEARLY:-}
|
||||
STRIPE_CHECKOUT_SUCCESS_URL: ${STRIPE_CHECKOUT_SUCCESS_URL:-http://localhost:3000/?billing=success}
|
||||
STRIPE_CHECKOUT_CANCEL_URL: ${STRIPE_CHECKOUT_CANCEL_URL:-http://localhost:3000/?billing=cancelled}
|
||||
STRIPE_PORTAL_RETURN_URL: ${STRIPE_PORTAL_RETURN_URL:-http://localhost:3000/?billing=portal}
|
||||
@@ -89,6 +96,12 @@ services:
|
||||
condition: service_healthy
|
||||
redis:
|
||||
condition: service_healthy
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "node -e \"fetch('http://127.0.0.1:5000/api/health/ready').then(r => { if (!r.ok) process.exit(1) }).catch(() => process.exit(1))\""]
|
||||
interval: 30s
|
||||
timeout: 10s
|
||||
retries: 3
|
||||
start_period: 30s
|
||||
ports:
|
||||
- "5000:5000"
|
||||
command: >
|
||||
@@ -97,6 +110,7 @@ services:
|
||||
volumes:
|
||||
- ./backend:/app
|
||||
- /app/node_modules
|
||||
restart: unless-stopped
|
||||
|
||||
worker:
|
||||
build:
|
||||
@@ -124,10 +138,13 @@ 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:-}
|
||||
SMTP_PORT: ${SMTP_PORT:-587}
|
||||
@@ -154,7 +171,7 @@ services:
|
||||
dockerfile: Dockerfile.dev
|
||||
container_name: flockpal-frontend
|
||||
environment:
|
||||
VITE_API_BASE_URL: ${VITE_API_BASE_URL:-http://localhost:5000/api}
|
||||
VITE_API_BASE_URL: ${VITE_API_BASE_URL:-/api}
|
||||
depends_on:
|
||||
- backend
|
||||
ports:
|
||||
|
||||
+128
-8
@@ -1,5 +1,30 @@
|
||||
# FlockPal API Reference
|
||||
|
||||
## Customer integration reference
|
||||
|
||||
The interactive customer API reference is available at **`/api/docs/`** on your
|
||||
FlockPal instance (locally, `http://localhost:5000/api/docs/`). Download the
|
||||
OpenAPI 3.0 specification at **`/api/openapi.json`**. There is also a link in
|
||||
Settings → Integration tokens.
|
||||
|
||||
Create an integration token in Settings, then paste it into Swagger's **Authorize**
|
||||
dialog without the `Bearer` prefix. Use `read_only` for reading or `read_write`
|
||||
for changes. Tokens apply to their originating workspace and the creator's
|
||||
current membership permissions. Swagger's **Try it out** makes real API requests.
|
||||
|
||||
The customer reference covers integration-token endpoints only. The broader
|
||||
application reference below also includes browser-session and administrative APIs.
|
||||
|
||||
### Maintaining the interactive reference
|
||||
|
||||
- Request validators live in `backend/src/schemas.ts` and are shared with route handlers.
|
||||
- Customer operations are explicitly registered in `backend/src/docs/openapi.ts`.
|
||||
- Response models live in `backend/src/docs/responses.ts`; update them when serialized responses change.
|
||||
- `backend/src/docs/openapi.test.ts` validates OpenAPI, compares customer coverage against actual route middleware, and checks locally served Swagger assets and security headers.
|
||||
- Run `npm run build` and `npm test` in `backend` after changes.
|
||||
- The Zod-to-OpenAPI dependency is pinned to the Zod 3-compatible release; upgrade both together.
|
||||
|
||||
|
||||
This document describes the HTTP API currently implemented in `backend/src/app.ts`.
|
||||
|
||||
## Base URLs
|
||||
@@ -208,7 +233,11 @@ Role requirements are called out per endpoint below. If the signed-in member lac
|
||||
"name": "Kiwi",
|
||||
"tagId": "FP-001",
|
||||
"species": "Cockatiel",
|
||||
"gender": "female",
|
||||
"vetClinicName": "Avian Care Center",
|
||||
"vetClinicAddress": "123 Feather Lane, Raleigh, NC",
|
||||
"vetAccountNumber": "FP-1001",
|
||||
"vetDoctorName": "Dr. Rivera",
|
||||
"gender": "female_dna",
|
||||
"dateOfBirth": "2023-05-10",
|
||||
"gotchaDay": "2023-08-21",
|
||||
"chartColor": "#cb3a35",
|
||||
@@ -295,7 +324,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`, or `female`
|
||||
- bird `gender` is `unknown`, `male`, `female`, `male_dna`, or `female_dna`; `male` and `female` indicate assumed sex
|
||||
- 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`
|
||||
@@ -315,14 +344,47 @@ Validation failures return `400` with this shape:
|
||||
|
||||
#### `GET /api/health`
|
||||
|
||||
Public health check.
|
||||
Public readiness-compatible health check. Verifies backend dependencies.
|
||||
|
||||
Response `200`:
|
||||
|
||||
```json
|
||||
{ "ok": true }
|
||||
{
|
||||
"ok": true,
|
||||
"service": "flockpal-backend",
|
||||
"status": "ready",
|
||||
"checkedAt": "2026-06-06T00:00:00.000Z",
|
||||
"dependencies": {
|
||||
"postgres": { "ok": true, "latencyMs": 3 },
|
||||
"redis": { "ok": true, "latencyMs": 4 }
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Response `503` when Postgres or Redis is unavailable.
|
||||
|
||||
#### `GET /api/health/live`
|
||||
|
||||
Public liveness check. Verifies the backend process is running without checking dependencies.
|
||||
|
||||
Response `200`:
|
||||
|
||||
```json
|
||||
{
|
||||
"ok": true,
|
||||
"service": "flockpal-backend",
|
||||
"status": "live",
|
||||
"uptimeSeconds": 120,
|
||||
"checkedAt": "2026-06-06T00:00:00.000Z"
|
||||
}
|
||||
```
|
||||
|
||||
#### `GET /api/health/ready`
|
||||
|
||||
Public readiness check. Verifies the backend can reach Postgres and Redis.
|
||||
|
||||
Response `200` uses the same shape as `GET /api/health`; response `503` means at least one dependency failed.
|
||||
|
||||
### Metrics
|
||||
|
||||
#### `GET /api/metrics`
|
||||
@@ -653,7 +715,7 @@ Request body:
|
||||
Notes:
|
||||
|
||||
- `workspaceType` must be `standard` or `rescue`
|
||||
- `billingPlan` may be `household_basic`, `household_plus`, or `household_macaw`
|
||||
- `billingPlan` may be `household_basic`, `household_plus`, `household_macaw`, or `household_hyacinth_macaw`
|
||||
- rescue workspaces are forced to `rescue_free`
|
||||
|
||||
Response `201`:
|
||||
@@ -793,7 +855,11 @@ Request body:
|
||||
"name": "Kiwi",
|
||||
"tagId": "FP-001",
|
||||
"species": "Cockatiel",
|
||||
"gender": "female",
|
||||
"vetClinicName": "Avian Care Center",
|
||||
"vetClinicAddress": "123 Feather Lane, Raleigh, NC",
|
||||
"vetAccountNumber": "FP-1001",
|
||||
"vetDoctorName": "Dr. Rivera",
|
||||
"gender": "female_dna",
|
||||
"dateOfBirth": "2023-05-10",
|
||||
"gotchaDay": "2023-08-21",
|
||||
"chartColor": "#cb3a35",
|
||||
@@ -805,7 +871,7 @@ Request body:
|
||||
|
||||
Notes:
|
||||
|
||||
- `dateOfBirth`, `gotchaDay`, and `photoDataUrl` may be omitted or sent as empty strings
|
||||
- `dateOfBirth`, `gotchaDay`, `photoDataUrl`, and veterinary info fields may be omitted or sent as empty strings
|
||||
- `chartColor` defaults to `#cb3a35`
|
||||
|
||||
Response `201`:
|
||||
@@ -889,9 +955,43 @@ Possible errors:
|
||||
- `409` if that owner email owns more than one receiving flock
|
||||
- `409` if the destination flock already has a bird using the same `tagId`
|
||||
|
||||
#### `POST /api/birds/:birdId/transfer-code`
|
||||
|
||||
Requires a browser session, write access, and role `owner` or `assistant`. Creates a unique transfer code for a bird. Creating a new open code for the same bird revokes earlier unused codes for that bird.
|
||||
|
||||
Response `201`:
|
||||
|
||||
```json
|
||||
{
|
||||
"transferCode": {
|
||||
"code": "secure-code",
|
||||
"bird": {}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
#### `POST /api/bird-transfer-codes/:code/accept`
|
||||
|
||||
Requires a browser session, write access, and role `owner` or `assistant`. Accepts a transfer code into the signed-in user's active flock.
|
||||
|
||||
Response `200`:
|
||||
|
||||
```json
|
||||
{
|
||||
"bird": {},
|
||||
"sourceWorkspaceName": "Previous Flock",
|
||||
"workspace": {}
|
||||
}
|
||||
```
|
||||
|
||||
Possible errors:
|
||||
|
||||
- `404` if the code does not exist, was revoked, was already used, or the bird is no longer available
|
||||
- `409` if the bird is already in the active flock or the active flock already has the same `tagId`
|
||||
|
||||
#### `DELETE /api/birds/:birdId`
|
||||
|
||||
Requires auth with write access and role `owner`, `assistant`, or `caregiver`. Deletes a bird.
|
||||
Requires auth with write access and role `owner`, `assistant`, or `caregiver`. Removes the bird from its current flock without deleting its profile, photo, or care history. Bird-specific notes stay with the bird. Public sharing is disabled and pending transfers are revoked. Workspace audit logs and flock-wide notes remain in the source flock.
|
||||
|
||||
Response `204` with no body.
|
||||
|
||||
@@ -899,6 +999,22 @@ Possible errors:
|
||||
|
||||
- `404` if the bird does not exist in the active workspace
|
||||
|
||||
#### `GET /api/birds/unassigned-match?tagId=…`
|
||||
|
||||
Requires auth and role `owner`, `assistant`, or `caregiver`. Returns `{ "available": true }` only for an unassigned, non-memorialized bird whose band ID matches exactly after trimming and ignoring letter case. No profile, history, or former-flock details are disclosed. Blank/unknown IDs return `400`; partial IDs do not match.
|
||||
|
||||
#### `POST /api/birds/claim`
|
||||
|
||||
Requires auth with write access and role `owner`, `assistant`, or `caregiver`.
|
||||
|
||||
```json
|
||||
{ "tagId": "BAND-123", "confirmHistory": true }
|
||||
```
|
||||
|
||||
Returns `200` with `{ "bird": { ... }, "historyImported": true }`. Adds the existing unassigned bird to the current flock using its saved profile and history. The bird's ID and photo are preserved; bird-specific notes follow it. Public sharing remains disabled until explicitly enabled. Competing requests are serialized so only one flock can claim a bird.
|
||||
|
||||
Returns `400` without explicit history confirmation, or `409` if no matching unassigned bird remains. Creating a new profile via `POST /api/birds` with an unassigned bird's band ID returns `409` with code `bird_history_available` instead of duplicating or overwriting its profile.
|
||||
|
||||
### Weights
|
||||
|
||||
#### `GET /api/birds/:birdId/weights`
|
||||
@@ -1224,3 +1340,7 @@ curl -X POST http://localhost:5000/api/auth/magic-link/request \
|
||||
curl http://localhost:5000/api/auth/session \
|
||||
-H 'Authorization: Bearer YOUR_SESSION_TOKEN'
|
||||
```
|
||||
|
||||
### Behavior Journal
|
||||
|
||||
Behavior types and occurrences are available under `/birds/{birdId}/behavior-types` and `/birds/{birdId}/behaviors`. The interactive reference documents request/response schemas and permissions. See [Behavior Journal](BEHAVIOR_JOURNAL.md) for timestamp semantics, flock scoping, and isolated workflow tests.
|
||||
@@ -0,0 +1,68 @@
|
||||
# Behavior Journal
|
||||
|
||||
Open **Flock → select a bird → Behavior Journal** (calendar tab). Select a behavior or create a custom one, confirm the current date/time, and save. Duration in seconds, intensity from 1–5, and notes are optional. Open a day's occurrence to see its details, edit it, or delete it with confirmation.
|
||||
|
||||
The bird and behavior selectors filter the journal. The calendar displays one month at a time, daily counts and up to three dots (plus a `+` for additional events). Select a day to review its individual events. The count above the calendar reflects the selected behavior and displayed month.
|
||||
|
||||
## Storage and access
|
||||
|
||||
The existing `ensureSchema` startup migration creates `behavior_types` and `behavior_occurrences` and idempotently seeds nine common behaviors. No separate migration command is required. Occurrences reference existing birds and normalized behavior types. They retain `TIMESTAMPTZ` occurrence, created, and updated timestamps; optional duration in seconds; optional intensity; and notes. Indexes support bird/date and bird/behavior/date queries.
|
||||
|
||||
Custom behavior names are reusable within a flock and unique ignoring case. Default types are explicitly marked so orphaned custom types never become public. A transferred bird retains its occurrences and the types used in those occurrences, even if its old flock is deleted. Other custom types from its former flock remain private.
|
||||
|
||||
Existing session/integration-token authentication, flock roles, subscription restrictions, memorialized-bird restrictions, and audit logging apply. Owners, assistants, and caregivers can record/edit/delete; viewers can read. Queries and mutations check the bird's current flock. Writes also check flock ownership and memorialization inside the SQL statement.
|
||||
|
||||
The browser uses its device time zone for entry and calendar grouping, consistently with local date/time controls. Month boundaries are converted to UTC for the API's inclusive `from`, exclusive `to` range. Stored timestamps are not replaced by dates or daily totals. An unchanged edit retains the original timestamp, including sub-second precision. During a daylight-saving repeated hour, a newly entered ambiguous local time uses the browser's earlier offset; an existing event retains its original instant when its time is unchanged.
|
||||
|
||||
This feature records observations and occurrence timing. It adds no diagnostic interpretation or behavioral analysis.
|
||||
|
||||
## API
|
||||
|
||||
The interactive API reference includes these endpoints:
|
||||
|
||||
| Method | Path | Purpose |
|
||||
| --- | --- | --- |
|
||||
| GET | `/api/birds/:birdId/behavior-types` | Available default, flock, and transferred-history types |
|
||||
| POST | `/api/birds/:birdId/behavior-types` | Create/reuse a custom type (`name`, optional `description`) |
|
||||
| GET | `/api/birds/:birdId/behaviors?from=…&to=…&behaviorTypeId=…` | Events in a positive range of at most 32 days; optional type filter |
|
||||
| POST | `/api/birds/:birdId/behaviors` | Create an occurrence |
|
||||
| PUT | `/api/birds/:birdId/behaviors/:occurrenceId` | Replace the editable fields |
|
||||
| DELETE | `/api/birds/:birdId/behaviors/:occurrenceId` | Delete an occurrence |
|
||||
|
||||
Occurrence input: `behaviorTypeId`, offset-bearing `occurredAt`, optional/null `durationSeconds` (positive, at most one year), `severity` (integer 1–5), and `notes` (at most 10,000 characters). Responses include the behavior name and timestamps, allowing complete details to open without another request.
|
||||
|
||||
## Isolated verification
|
||||
|
||||
Use a disposable copy/install when the local dependency or build directories belong to a container. Do not point these scripts at a real flock database. The integration scripts use fixed test-only database settings on port 55439 and API port 55440. They create fixtures with distinct flock IDs and leave them in the disposable database for inspection.
|
||||
|
||||
```sh
|
||||
docker run --detach --rm --name flockpal-behavior-test-db \
|
||||
-e POSTGRES_PASSWORD=behavior_test_only -e POSTGRES_DB=behavior_test \
|
||||
-p 127.0.0.1:55439:5432 postgres:16-alpine
|
||||
cd backend
|
||||
npm ci
|
||||
npm run build
|
||||
npm test
|
||||
node test-integration/behaviorJournal.mjs
|
||||
```
|
||||
|
||||
The API integration check covers schema repeatability, seeded/custom types, duplicate custom names, independent events, create/edit/delete, bird/behavior/month filters, timestamp precision, invalid inputs, unauthenticated requests, viewer/read-only/memorialized restrictions, cross-flock access, and transfer history.
|
||||
|
||||
For the optional browser check, install Playwright in a disposable frontend install (it is not an application dependency), with the built backend alongside it:
|
||||
|
||||
```sh
|
||||
cd ../frontend
|
||||
npm ci
|
||||
npm run build
|
||||
npm install --no-save --package-lock=false playwright
|
||||
npx playwright install chromium
|
||||
node test-integration/behaviorJournal.mjs
|
||||
```
|
||||
|
||||
The browser check starts and stops its own API and Vite server (port 55441). It covers the complete entry/custom behavior/edit/delete workflow, bird and behavior filters, day selection and daily counts, month navigation, local midnight and daylight-saving boundaries, and a 390px mobile layout. It writes screenshots to `/tmp/flockpal-behavior-mobile.png` and `/tmp/flockpal-behavior-desktop.png`.
|
||||
|
||||
After verification, stop only the disposable database:
|
||||
|
||||
```sh
|
||||
docker stop flockpal-behavior-test-db
|
||||
```
|
||||
@@ -0,0 +1,50 @@
|
||||
# Removing and re-adding a bird
|
||||
|
||||
**Remove from flock** now unassigns the bird. It does not delete the bird profile, photo, weights, vet visits, medication/dose records, Behavior Journal, timeline, or bird-specific notes.
|
||||
|
||||
The bird disappears from the old flock's lists and care-record access. Its public profile is disabled, open transfer codes are revoked, and pending transfers are cancelled. Existing reminders find birds through their current flock, so unassigned birds do not enter future reminder selections. Removal is recorded in the bird timeline and the old flock's audit log.
|
||||
|
||||
Bird-specific notes follow the bird. Flock-wide notes and workspace audit history stay with the original flock. Removal and claiming keep the bird's ID, so care history is preserved without copying or combining records.
|
||||
|
||||
## Adding an existing unassigned bird
|
||||
|
||||
In **Add bird**, enter the band ID. FlockPal checks for an unassigned, non-memorialized match after typing pauses. Matching follows the existing global band-ID convention: ignore surrounding whitespace and letter case, but otherwise require the entire ID. Blank/unknown placeholders and partial IDs cannot recover a bird.
|
||||
|
||||
A match displays a notice that the saved profile, photo, notes, and care history will be brought in, with an **Add bird with existing history** button. Confirmation is required. Saved profile details are used rather than overwriting them with draft fields. No new name or species is required for this path. Before confirmation, the lookup returns only availability, not the previous profile or flock details.
|
||||
|
||||
A bird already assigned to a flock cannot be claimed this way; use the existing transfer flow. Claims use a database row lock so simultaneous requests from different flocks cannot both succeed. Memorialized birds remain read-only.
|
||||
|
||||
Birds without band IDs can still be removed and retained, but they cannot be automatically recovered through the band-ID workflow. The removal confirmation explains this. Previously hard-deleted records cannot be restored by this change.
|
||||
|
||||
## Schema and API
|
||||
|
||||
The startup `ensureSchema` migration allows `birds.workspace_id` and bird-specific `flock_notes.workspace_id` to be null. Removal, note reassignment, transfer revocation, and timeline recording run in a transaction. Claiming and its note/timeline changes also run in a transaction. A failure rolls the entire change back.
|
||||
|
||||
The existing `DELETE /api/birds/:birdId` now removes flock membership and still returns `204`. New endpoints:
|
||||
|
||||
- `GET /api/birds/unassigned-match?tagId=…` returns `{ "available": true | false }`.
|
||||
- `POST /api/birds/claim` accepts `{ "tagId": "…", "confirmHistory": true }` and returns the existing bird plus `historyImported: true`.
|
||||
|
||||
Both require authenticated owner, assistant, or caregiver membership. Claiming also requires write access. Creating a new profile with an unassigned band's ID returns `409` / `bird_history_available`; it never overwrites history.
|
||||
|
||||
## Verification
|
||||
|
||||
Use the disposable PostgreSQL/API setup in [Behavior Journal testing](BEHAVIOR_JOURNAL.md#isolated-verification), then run:
|
||||
|
||||
```sh
|
||||
cd backend
|
||||
npm run build
|
||||
npm test
|
||||
node test-integration/birdMembership.mjs
|
||||
```
|
||||
|
||||
The integration check covers repeated schema startup, retained profile/photo/history, notes separation, source access removal, disabled sharing, transfer revocation, exact/case-insensitive band matching, explicit confirmation, role/billing restrictions, transaction rollback, and competing claims.
|
||||
|
||||
With Playwright installed in the disposable frontend install as described in that guide:
|
||||
|
||||
```sh
|
||||
cd frontend
|
||||
node test-integration/birdMembership.mjs
|
||||
```
|
||||
|
||||
The browser check exercises desktop removal, the mobile match notice, cancellation, confirmed recovery without replacement profile fields, and restored notes/timeline. It uses ports 55439–55441 and writes a notice screenshot to `/tmp/flockpal-existing-history-notice.png`. No real flock data is used.
|
||||
@@ -0,0 +1,34 @@
|
||||
# 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.
|
||||
@@ -7,6 +7,7 @@ RUN npm ci
|
||||
COPY tsconfig*.json ./
|
||||
COPY vite.config.ts ./
|
||||
COPY index.html ./
|
||||
COPY public ./public
|
||||
COPY src ./src
|
||||
RUN npm run build
|
||||
|
||||
|
||||
@@ -5,6 +5,7 @@ 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"]
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
Generated
+497
-1
@@ -8,8 +8,11 @@
|
||||
"name": "flockpal-frontend",
|
||||
"version": "0.1.0",
|
||||
"dependencies": {
|
||||
"@types/qrcode": "^1.5.6",
|
||||
"qrcode": "^1.5.4",
|
||||
"react": "18.3.1",
|
||||
"react-dom": "18.3.1"
|
||||
"react-dom": "18.3.1",
|
||||
"read-excel-file": "^9.0.9"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/react": "18.3.12",
|
||||
@@ -1144,6 +1147,15 @@
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@types/node": {
|
||||
"version": "25.9.1",
|
||||
"resolved": "https://registry.npmjs.org/@types/node/-/node-25.9.1.tgz",
|
||||
"integrity": "sha512-xfrlY7UD5rMJk3ZVJP8BNzS28J36YJg+xp+LPXV1TdWxr8uMH5A860QNxYDGQe/ylDSgjxE52Q9VnO7p75tJxg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"undici-types": ">=7.24.0 <7.24.7"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/prop-types": {
|
||||
"version": "15.7.15",
|
||||
"resolved": "https://registry.npmjs.org/@types/prop-types/-/prop-types-15.7.15.tgz",
|
||||
@@ -1151,6 +1163,15 @@
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@types/qrcode": {
|
||||
"version": "1.5.6",
|
||||
"resolved": "https://registry.npmjs.org/@types/qrcode/-/qrcode-1.5.6.tgz",
|
||||
"integrity": "sha512-te7NQcV2BOvdj2b1hCAHzAoMNuj65kNBMz0KBaxM6c3VGBOhU0dURQKOtH8CFNI/dsKkwlv32p26qYQTWoB5bw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@types/node": "*"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/react": {
|
||||
"version": "18.3.12",
|
||||
"resolved": "https://registry.npmjs.org/@types/react/-/react-18.3.12.tgz",
|
||||
@@ -1192,6 +1213,39 @@
|
||||
"vite": "^4.2.0 || ^5.0.0 || ^6.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@xmldom/xmldom": {
|
||||
"version": "0.9.10",
|
||||
"resolved": "https://registry.npmjs.org/@xmldom/xmldom/-/xmldom-0.9.10.tgz",
|
||||
"integrity": "sha512-A9gOqLdi6cV4ibazAjcQufGj0B1y/vDqYrcuP6d/6x8P27gRS8643Dj9o1dEKtB6O7fwxb2FgBmJS2mX7gpvdw==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=14.6"
|
||||
}
|
||||
},
|
||||
"node_modules/ansi-regex": {
|
||||
"version": "5.0.1",
|
||||
"resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz",
|
||||
"integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/ansi-styles": {
|
||||
"version": "4.3.0",
|
||||
"resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz",
|
||||
"integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"color-convert": "^2.0.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/chalk/ansi-styles?sponsor=1"
|
||||
}
|
||||
},
|
||||
"node_modules/baseline-browser-mapping": {
|
||||
"version": "2.10.16",
|
||||
"resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.10.16.tgz",
|
||||
@@ -1205,6 +1259,12 @@
|
||||
"node": ">=6.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/bluebird": {
|
||||
"version": "3.7.2",
|
||||
"resolved": "https://registry.npmjs.org/bluebird/-/bluebird-3.7.2.tgz",
|
||||
"integrity": "sha512-XpNj6GDQzdfW+r2Wnn7xiSAd7TM3jzkxGXBGTtWKuSXv1xUV+azxAm8jdWZN06QTQk+2N2XB9jRDkvbmQmcRtg==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/browserslist": {
|
||||
"version": "4.28.2",
|
||||
"resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.28.2.tgz",
|
||||
@@ -1239,6 +1299,15 @@
|
||||
"node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7"
|
||||
}
|
||||
},
|
||||
"node_modules/camelcase": {
|
||||
"version": "5.3.1",
|
||||
"resolved": "https://registry.npmjs.org/camelcase/-/camelcase-5.3.1.tgz",
|
||||
"integrity": "sha512-L28STB170nwWS63UjtlEOE3dldQApaJXZkOI1uMFfzf3rRuPegHaHesyee+YxQ+W6SvRDQV6UrdOdRiR153wJg==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=6"
|
||||
}
|
||||
},
|
||||
"node_modules/caniuse-lite": {
|
||||
"version": "1.0.30001786",
|
||||
"resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001786.tgz",
|
||||
@@ -1260,6 +1329,35 @@
|
||||
],
|
||||
"license": "CC-BY-4.0"
|
||||
},
|
||||
"node_modules/cliui": {
|
||||
"version": "6.0.0",
|
||||
"resolved": "https://registry.npmjs.org/cliui/-/cliui-6.0.0.tgz",
|
||||
"integrity": "sha512-t6wbgtoCXvAzst7QgXxJYqPt0usEfbgQdftEPbLL/cvv6HPE5VgvqCuAIDR0NgU52ds6rFwqrgakNLrHEjCbrQ==",
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"string-width": "^4.2.0",
|
||||
"strip-ansi": "^6.0.0",
|
||||
"wrap-ansi": "^6.2.0"
|
||||
}
|
||||
},
|
||||
"node_modules/color-convert": {
|
||||
"version": "2.0.1",
|
||||
"resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz",
|
||||
"integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"color-name": "~1.1.4"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=7.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/color-name": {
|
||||
"version": "1.1.4",
|
||||
"resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz",
|
||||
"integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/convert-source-map": {
|
||||
"version": "2.0.0",
|
||||
"resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz",
|
||||
@@ -1267,6 +1365,12 @@
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/core-util-is": {
|
||||
"version": "1.0.3",
|
||||
"resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.3.tgz",
|
||||
"integrity": "sha512-ZQBvi1DcpJ4GDqanjucZ2Hj3wEO5pZDS89BWbkcrvdxksJorwUDDZamX9ldFkp9aw2lmBDLgkObEA4DWNJ9FYQ==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/csstype": {
|
||||
"version": "3.2.3",
|
||||
"resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz",
|
||||
@@ -1292,6 +1396,30 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/decamelize": {
|
||||
"version": "1.2.0",
|
||||
"resolved": "https://registry.npmjs.org/decamelize/-/decamelize-1.2.0.tgz",
|
||||
"integrity": "sha512-z2S+W9X73hAUUki+N+9Za2lBlun89zigOyGrsax+KUQ6wKW4ZoWpEYBkGhQjwAjjDCkWxhY0VKEhk8wzY7F5cA==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=0.10.0"
|
||||
}
|
||||
},
|
||||
"node_modules/dijkstrajs": {
|
||||
"version": "1.0.3",
|
||||
"resolved": "https://registry.npmjs.org/dijkstrajs/-/dijkstrajs-1.0.3.tgz",
|
||||
"integrity": "sha512-qiSlmBq9+BCdCA/L46dw8Uy93mloxsPSbwnm5yrKn2vMPiy8KyAskTF6zuV/j5BMsmOGZDPs7KjU+mjb670kfA==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/duplexer2": {
|
||||
"version": "0.1.4",
|
||||
"resolved": "https://registry.npmjs.org/duplexer2/-/duplexer2-0.1.4.tgz",
|
||||
"integrity": "sha512-asLFVfWWtJ90ZyOUHMqk7/S2w2guQKxUI2itj3d92ADHhxUSbCMGi1f1cBcJ7xM1To+pE/Khbwo1yuNbMEPKeA==",
|
||||
"license": "BSD-3-Clause",
|
||||
"dependencies": {
|
||||
"readable-stream": "^2.0.2"
|
||||
}
|
||||
},
|
||||
"node_modules/electron-to-chromium": {
|
||||
"version": "1.5.331",
|
||||
"resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.331.tgz",
|
||||
@@ -1299,6 +1427,12 @@
|
||||
"dev": true,
|
||||
"license": "ISC"
|
||||
},
|
||||
"node_modules/emoji-regex": {
|
||||
"version": "8.0.0",
|
||||
"resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz",
|
||||
"integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/esbuild": {
|
||||
"version": "0.21.5",
|
||||
"resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.21.5.tgz",
|
||||
@@ -1348,6 +1482,39 @@
|
||||
"node": ">=6"
|
||||
}
|
||||
},
|
||||
"node_modules/fflate": {
|
||||
"version": "0.8.3",
|
||||
"resolved": "https://registry.npmjs.org/fflate/-/fflate-0.8.3.tgz",
|
||||
"integrity": "sha512-tbZNuJrLwGUp3zshBtdy4W+ORxZuIh8a5ilyIEQDC5rY1f3U20JMry0Ll3WBzU58EZKsEuJFXhb5gwv8CsPvgA==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/find-up": {
|
||||
"version": "4.1.0",
|
||||
"resolved": "https://registry.npmjs.org/find-up/-/find-up-4.1.0.tgz",
|
||||
"integrity": "sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"locate-path": "^5.0.0",
|
||||
"path-exists": "^4.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/fs-extra": {
|
||||
"version": "11.3.5",
|
||||
"resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-11.3.5.tgz",
|
||||
"integrity": "sha512-eKpRKAovdpZtR1WopLHxlBWvAgPny3c4gX1G5Jhwmmw4XJj0ifSD5qB5TOo8hmA0wlRKDAOAhEE1yVPgs6Fgcg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"graceful-fs": "^4.2.0",
|
||||
"jsonfile": "^6.0.1",
|
||||
"universalify": "^2.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=14.14"
|
||||
}
|
||||
},
|
||||
"node_modules/fsevents": {
|
||||
"version": "2.3.3",
|
||||
"resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz",
|
||||
@@ -1373,6 +1540,42 @@
|
||||
"node": ">=6.9.0"
|
||||
}
|
||||
},
|
||||
"node_modules/get-caller-file": {
|
||||
"version": "2.0.5",
|
||||
"resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz",
|
||||
"integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==",
|
||||
"license": "ISC",
|
||||
"engines": {
|
||||
"node": "6.* || 8.* || >= 10.*"
|
||||
}
|
||||
},
|
||||
"node_modules/graceful-fs": {
|
||||
"version": "4.2.11",
|
||||
"resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.11.tgz",
|
||||
"integrity": "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==",
|
||||
"license": "ISC"
|
||||
},
|
||||
"node_modules/inherits": {
|
||||
"version": "2.0.4",
|
||||
"resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz",
|
||||
"integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==",
|
||||
"license": "ISC"
|
||||
},
|
||||
"node_modules/is-fullwidth-code-point": {
|
||||
"version": "3.0.0",
|
||||
"resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz",
|
||||
"integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/isarray": {
|
||||
"version": "1.0.0",
|
||||
"resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz",
|
||||
"integrity": "sha512-VLghIWNM6ELQzo7zwmcg0NmTVyWKYjvIeM83yjp0wRDTmUnrM678fQbcKBo6n2CJEF0szoG//ytg+TKla89ALQ==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/js-tokens": {
|
||||
"version": "4.0.0",
|
||||
"resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz",
|
||||
@@ -1405,6 +1608,30 @@
|
||||
"node": ">=6"
|
||||
}
|
||||
},
|
||||
"node_modules/jsonfile": {
|
||||
"version": "6.2.1",
|
||||
"resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-6.2.1.tgz",
|
||||
"integrity": "sha512-zwOTdL3rFQ/lRdBnntKVOX6k5cKJwEc1HdilT71BWEu7J41gXIB2MRp+vxduPSwZJPWBxEzv4yH1wYLJGUHX4Q==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"universalify": "^2.0.0"
|
||||
},
|
||||
"optionalDependencies": {
|
||||
"graceful-fs": "^4.1.6"
|
||||
}
|
||||
},
|
||||
"node_modules/locate-path": {
|
||||
"version": "5.0.0",
|
||||
"resolved": "https://registry.npmjs.org/locate-path/-/locate-path-5.0.0.tgz",
|
||||
"integrity": "sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"p-locate": "^4.1.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/loose-envify": {
|
||||
"version": "1.4.0",
|
||||
"resolved": "https://registry.npmjs.org/loose-envify/-/loose-envify-1.4.0.tgz",
|
||||
@@ -1453,6 +1680,12 @@
|
||||
"node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1"
|
||||
}
|
||||
},
|
||||
"node_modules/node-int64": {
|
||||
"version": "0.4.0",
|
||||
"resolved": "https://registry.npmjs.org/node-int64/-/node-int64-0.4.0.tgz",
|
||||
"integrity": "sha512-O5lz91xSOeoXP6DulyHfllpq+Eg00MWitZIbtPfoSEvqIHdl5gfcY6hYzDWnj0qD5tz52PI08u9qUvSVeUBeHw==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/node-releases": {
|
||||
"version": "2.0.37",
|
||||
"resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.37.tgz",
|
||||
@@ -1460,6 +1693,51 @@
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/p-limit": {
|
||||
"version": "2.3.0",
|
||||
"resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.3.0.tgz",
|
||||
"integrity": "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"p-try": "^2.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=6"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/sindresorhus"
|
||||
}
|
||||
},
|
||||
"node_modules/p-locate": {
|
||||
"version": "4.1.0",
|
||||
"resolved": "https://registry.npmjs.org/p-locate/-/p-locate-4.1.0.tgz",
|
||||
"integrity": "sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"p-limit": "^2.2.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/p-try": {
|
||||
"version": "2.2.0",
|
||||
"resolved": "https://registry.npmjs.org/p-try/-/p-try-2.2.0.tgz",
|
||||
"integrity": "sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=6"
|
||||
}
|
||||
},
|
||||
"node_modules/path-exists": {
|
||||
"version": "4.0.0",
|
||||
"resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz",
|
||||
"integrity": "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/picocolors": {
|
||||
"version": "1.1.1",
|
||||
"resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz",
|
||||
@@ -1467,6 +1745,15 @@
|
||||
"dev": true,
|
||||
"license": "ISC"
|
||||
},
|
||||
"node_modules/pngjs": {
|
||||
"version": "5.0.0",
|
||||
"resolved": "https://registry.npmjs.org/pngjs/-/pngjs-5.0.0.tgz",
|
||||
"integrity": "sha512-40QW5YalBNfQo5yRYmiw7Yz6TKKVr3h6970B2YE+3fQpsWcrbj1PzJgxeJ19DRQjhMbKPIuMY8rFaXc8moolVw==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=10.13.0"
|
||||
}
|
||||
},
|
||||
"node_modules/postcss": {
|
||||
"version": "8.5.8",
|
||||
"resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.8.tgz",
|
||||
@@ -1496,6 +1783,29 @@
|
||||
"node": "^10 || ^12 || >=14"
|
||||
}
|
||||
},
|
||||
"node_modules/process-nextick-args": {
|
||||
"version": "2.0.1",
|
||||
"resolved": "https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-2.0.1.tgz",
|
||||
"integrity": "sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/qrcode": {
|
||||
"version": "1.5.4",
|
||||
"resolved": "https://registry.npmjs.org/qrcode/-/qrcode-1.5.4.tgz",
|
||||
"integrity": "sha512-1ca71Zgiu6ORjHqFBDpnSMTR2ReToX4l1Au1VFLyVeBTFavzQnv5JxMFr3ukHVKpSrSA2MCk0lNJSykjUfz7Zg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"dijkstrajs": "^1.0.1",
|
||||
"pngjs": "^5.0.0",
|
||||
"yargs": "^15.3.1"
|
||||
},
|
||||
"bin": {
|
||||
"qrcode": "bin/qrcode"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=10.13.0"
|
||||
}
|
||||
},
|
||||
"node_modules/react": {
|
||||
"version": "18.3.1",
|
||||
"resolved": "https://registry.npmjs.org/react/-/react-18.3.1.tgz",
|
||||
@@ -1531,6 +1841,50 @@
|
||||
"node": ">=0.10.0"
|
||||
}
|
||||
},
|
||||
"node_modules/read-excel-file": {
|
||||
"version": "9.0.9",
|
||||
"resolved": "https://registry.npmjs.org/read-excel-file/-/read-excel-file-9.0.9.tgz",
|
||||
"integrity": "sha512-FWwC3IypIQDVPTtO4pz0Sq6An7lQI17pXqCusaTX8yi3p9CCRtXx/SI3BtcPSTaLhwcwr9mI+KXSa/dWMmnvjQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@xmldom/xmldom": "^0.9.9",
|
||||
"fflate": "^0.8.2",
|
||||
"unzipper": "^0.12.3"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/readable-stream": {
|
||||
"version": "2.3.8",
|
||||
"resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.8.tgz",
|
||||
"integrity": "sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"core-util-is": "~1.0.0",
|
||||
"inherits": "~2.0.3",
|
||||
"isarray": "~1.0.0",
|
||||
"process-nextick-args": "~2.0.0",
|
||||
"safe-buffer": "~5.1.1",
|
||||
"string_decoder": "~1.1.1",
|
||||
"util-deprecate": "~1.0.1"
|
||||
}
|
||||
},
|
||||
"node_modules/require-directory": {
|
||||
"version": "2.1.1",
|
||||
"resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz",
|
||||
"integrity": "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=0.10.0"
|
||||
}
|
||||
},
|
||||
"node_modules/require-main-filename": {
|
||||
"version": "2.0.0",
|
||||
"resolved": "https://registry.npmjs.org/require-main-filename/-/require-main-filename-2.0.0.tgz",
|
||||
"integrity": "sha512-NKN5kMDylKuldxYLSUfrbo5Tuzh4hd+2E8NPPX02mZtn1VuREQToYe/ZdlJy+J3uCpfaiGF05e7B8W0iXbQHmg==",
|
||||
"license": "ISC"
|
||||
},
|
||||
"node_modules/rollup": {
|
||||
"version": "4.60.1",
|
||||
"resolved": "https://registry.npmjs.org/rollup/-/rollup-4.60.1.tgz",
|
||||
@@ -1576,6 +1930,12 @@
|
||||
"fsevents": "~2.3.2"
|
||||
}
|
||||
},
|
||||
"node_modules/safe-buffer": {
|
||||
"version": "5.1.2",
|
||||
"resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz",
|
||||
"integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/scheduler": {
|
||||
"version": "0.23.2",
|
||||
"resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.23.2.tgz",
|
||||
@@ -1595,6 +1955,12 @@
|
||||
"semver": "bin/semver.js"
|
||||
}
|
||||
},
|
||||
"node_modules/set-blocking": {
|
||||
"version": "2.0.0",
|
||||
"resolved": "https://registry.npmjs.org/set-blocking/-/set-blocking-2.0.0.tgz",
|
||||
"integrity": "sha512-KiKBS8AnWGEyLzofFfmvKwpdPzqiy16LvQfK3yv/fVH7Bj13/wl3JSR1J+rfgRE9q7xUJK4qvgS8raSOeLUehw==",
|
||||
"license": "ISC"
|
||||
},
|
||||
"node_modules/source-map-js": {
|
||||
"version": "1.2.1",
|
||||
"resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz",
|
||||
@@ -1605,6 +1971,41 @@
|
||||
"node": ">=0.10.0"
|
||||
}
|
||||
},
|
||||
"node_modules/string_decoder": {
|
||||
"version": "1.1.1",
|
||||
"resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz",
|
||||
"integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"safe-buffer": "~5.1.0"
|
||||
}
|
||||
},
|
||||
"node_modules/string-width": {
|
||||
"version": "4.2.3",
|
||||
"resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz",
|
||||
"integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"emoji-regex": "^8.0.0",
|
||||
"is-fullwidth-code-point": "^3.0.0",
|
||||
"strip-ansi": "^6.0.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/strip-ansi": {
|
||||
"version": "6.0.1",
|
||||
"resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz",
|
||||
"integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"ansi-regex": "^5.0.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/typescript": {
|
||||
"version": "5.6.3",
|
||||
"resolved": "https://registry.npmjs.org/typescript/-/typescript-5.6.3.tgz",
|
||||
@@ -1619,6 +2020,34 @@
|
||||
"node": ">=14.17"
|
||||
}
|
||||
},
|
||||
"node_modules/undici-types": {
|
||||
"version": "7.24.6",
|
||||
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.24.6.tgz",
|
||||
"integrity": "sha512-WRNW+sJgj5OBN4/0JpHFqtqzhpbnV0GuB+OozA9gCL7a993SmU+1JBZCzLNxYsbMfIeDL+lTsphD5jN5N+n0zg==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/universalify": {
|
||||
"version": "2.0.1",
|
||||
"resolved": "https://registry.npmjs.org/universalify/-/universalify-2.0.1.tgz",
|
||||
"integrity": "sha512-gptHNQghINnc/vTGIk0SOFGFNXw7JVrlRUtConJRlvaw6DuX0wO5Jeko9sWrMBhh+PsYAZ7oXAiOnf/UKogyiw==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 10.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/unzipper": {
|
||||
"version": "0.12.3",
|
||||
"resolved": "https://registry.npmjs.org/unzipper/-/unzipper-0.12.3.tgz",
|
||||
"integrity": "sha512-PZ8hTS+AqcGxsaQntl3IRBw65QrBI6lxzqDEL7IAo/XCEqRTKGfOX56Vea5TH9SZczRVxuzk1re04z/YjuYCJA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"bluebird": "~3.7.2",
|
||||
"duplexer2": "~0.1.4",
|
||||
"fs-extra": "^11.2.0",
|
||||
"graceful-fs": "^4.2.2",
|
||||
"node-int64": "^0.4.0"
|
||||
}
|
||||
},
|
||||
"node_modules/update-browserslist-db": {
|
||||
"version": "1.2.3",
|
||||
"resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.2.3.tgz",
|
||||
@@ -1650,6 +2079,12 @@
|
||||
"browserslist": ">= 4.21.0"
|
||||
}
|
||||
},
|
||||
"node_modules/util-deprecate": {
|
||||
"version": "1.0.2",
|
||||
"resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz",
|
||||
"integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/vite": {
|
||||
"version": "5.4.10",
|
||||
"resolved": "https://registry.npmjs.org/vite/-/vite-5.4.10.tgz",
|
||||
@@ -1710,12 +2145,73 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/which-module": {
|
||||
"version": "2.0.1",
|
||||
"resolved": "https://registry.npmjs.org/which-module/-/which-module-2.0.1.tgz",
|
||||
"integrity": "sha512-iBdZ57RDvnOR9AGBhML2vFZf7h8vmBjhoaZqODJBFWHVtKkDmKuHai3cx5PgVMrX5YDNp27AofYbAwctSS+vhQ==",
|
||||
"license": "ISC"
|
||||
},
|
||||
"node_modules/wrap-ansi": {
|
||||
"version": "6.2.0",
|
||||
"resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-6.2.0.tgz",
|
||||
"integrity": "sha512-r6lPcBGxZXlIcymEu7InxDMhdW0KDxpLgoFLcguasxCaJ/SOIZwINatK9KY/tf+ZrlywOKU0UDj3ATXUBfxJXA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"ansi-styles": "^4.0.0",
|
||||
"string-width": "^4.1.0",
|
||||
"strip-ansi": "^6.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/y18n": {
|
||||
"version": "4.0.3",
|
||||
"resolved": "https://registry.npmjs.org/y18n/-/y18n-4.0.3.tgz",
|
||||
"integrity": "sha512-JKhqTOwSrqNA1NY5lSztJ1GrBiUodLMmIZuLiDaMRJ+itFd+ABVE8XBjOvIWL+rSqNDC74LCSFmlb/U4UZ4hJQ==",
|
||||
"license": "ISC"
|
||||
},
|
||||
"node_modules/yallist": {
|
||||
"version": "3.1.1",
|
||||
"resolved": "https://registry.npmjs.org/yallist/-/yallist-3.1.1.tgz",
|
||||
"integrity": "sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==",
|
||||
"dev": true,
|
||||
"license": "ISC"
|
||||
},
|
||||
"node_modules/yargs": {
|
||||
"version": "15.4.1",
|
||||
"resolved": "https://registry.npmjs.org/yargs/-/yargs-15.4.1.tgz",
|
||||
"integrity": "sha512-aePbxDmcYW++PaqBsJ+HYUFwCdv4LVvdnhBy78E57PIor8/OVvhMrADFFEDh8DHDFRv/O9i3lPhsENjO7QX0+A==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"cliui": "^6.0.0",
|
||||
"decamelize": "^1.2.0",
|
||||
"find-up": "^4.1.0",
|
||||
"get-caller-file": "^2.0.1",
|
||||
"require-directory": "^2.1.1",
|
||||
"require-main-filename": "^2.0.0",
|
||||
"set-blocking": "^2.0.0",
|
||||
"string-width": "^4.2.0",
|
||||
"which-module": "^2.0.0",
|
||||
"y18n": "^4.0.0",
|
||||
"yargs-parser": "^18.1.2"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/yargs-parser": {
|
||||
"version": "18.1.3",
|
||||
"resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-18.1.3.tgz",
|
||||
"integrity": "sha512-o50j0JeToy/4K6OZcaQmW6lyXXKhq7csREXcDwk2omFPJEwUNOVtJKvmDr9EI1fAJZUyZcRF7kxGBWmRXudrCQ==",
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"camelcase": "^5.0.0",
|
||||
"decamelize": "^1.2.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=6"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -9,8 +9,11 @@
|
||||
"preview": "vite preview"
|
||||
},
|
||||
"dependencies": {
|
||||
"@types/qrcode": "^1.5.6",
|
||||
"qrcode": "^1.5.4",
|
||||
"react": "18.3.1",
|
||||
"react-dom": "18.3.1"
|
||||
"react-dom": "18.3.1",
|
||||
"read-excel-file": "^9.0.9"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/react": "18.3.12",
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 237 KiB |
+4115
-938
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,132 @@
|
||||
import { useEffect, useMemo, useState, type FormEvent } from 'react';
|
||||
import './behaviorJournal.css';
|
||||
|
||||
type BehaviorType = { id: string; name: string; description: string | null };
|
||||
type Occurrence = {
|
||||
id: string; birdId: string; behaviorTypeId: string; behaviorName: string; occurredAt: string;
|
||||
durationSeconds: number | null; severity: number | null; notes: string | null; createdAt: string; updatedAt: string;
|
||||
};
|
||||
type Props = {
|
||||
bird: { id: string; name: string }; birds: { id: string; name: string }[]; onSelectBird: (id: string) => void; token: string; writable: boolean;
|
||||
apiFetch: (path: string, token?: string, init?: RequestInit) => Promise<Response>;
|
||||
};
|
||||
const localDate = (date: Date) => `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
|
||||
const localTime = (date: Date) => `${localDate(date)}T${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}:${String(date.getSeconds()).padStart(2, '0')}`;
|
||||
const emptyForm = () => ({ behaviorTypeId: '', occurredAt: localTime(new Date()), duration: '', severity: '', notes: '' });
|
||||
|
||||
export function BehaviorJournal({ bird, birds, onSelectBird, token, writable, apiFetch }: Props) {
|
||||
const [month, setMonth] = useState(() => new Date(new Date().getFullYear(), new Date().getMonth(), 1));
|
||||
const [day, setDay] = useState(() => localDate(new Date()));
|
||||
const [filter, setFilter] = useState('');
|
||||
const [types, setTypes] = useState<BehaviorType[]>([]);
|
||||
const [entries, setEntries] = useState<Occurrence[]>([]);
|
||||
const [form, setForm] = useState(emptyForm);
|
||||
const [editing, setEditing] = useState<Occurrence | null>(null);
|
||||
const [showForm, setShowForm] = useState(false);
|
||||
const [customName, setCustomName] = useState('');
|
||||
const [customDescription, setCustomDescription] = useState('');
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
const [notice, setNotice] = useState('');
|
||||
const [revision, setRevision] = useState(0);
|
||||
const base = `/birds/${bird.id}`;
|
||||
|
||||
async function request(path: string, init?: RequestInit) {
|
||||
const response = await apiFetch(path, token, { ...init, headers: { 'Content-Type': 'application/json', ...init?.headers } });
|
||||
if (response.status === 204) return null;
|
||||
const data = await response.json();
|
||||
if (!response.ok) throw new Error(data.error || 'Unable to update the journal.');
|
||||
return data;
|
||||
}
|
||||
useEffect(() => {
|
||||
let active = true;
|
||||
setLoading(true); setError(''); setEntries([]);
|
||||
const query = new URLSearchParams({ from: month.toISOString(), to: new Date(month.getFullYear(), month.getMonth() + 1, 1).toISOString() });
|
||||
if (filter) query.set('behaviorTypeId', filter);
|
||||
Promise.all([request(`${base}/behavior-types`), request(`${base}/behaviors?${query}`)])
|
||||
.then(([typeData, occurrenceData]) => { if (active) { setTypes(typeData.behaviorTypes); setEntries(occurrenceData.occurrences); } })
|
||||
.catch((e) => { if (active) setError(e instanceof Error ? e.message : 'Unable to load journal.'); })
|
||||
.finally(() => { if (active) setLoading(false); });
|
||||
return () => { active = false; };
|
||||
}, [bird.id, token, month, filter, revision]);
|
||||
|
||||
const byDay = useMemo(() => {
|
||||
const result = new Map<string, Occurrence[]>();
|
||||
entries.forEach((entry) => { const key = localDate(new Date(entry.occurredAt)); result.set(key, [...(result.get(key) || []), entry]); });
|
||||
return result;
|
||||
}, [entries]);
|
||||
function navigate(offset: number) {
|
||||
const next = new Date(month.getFullYear(), month.getMonth() + offset, 1);
|
||||
setMonth(next); setDay(localDate(next));
|
||||
}
|
||||
function edit(entry: Occurrence) {
|
||||
setEditing(entry); setShowForm(true); setError(''); setNotice('');
|
||||
setForm({ behaviorTypeId: entry.behaviorTypeId, occurredAt: localTime(new Date(entry.occurredAt)), duration: entry.durationSeconds === null ? '' : String(entry.durationSeconds), severity: entry.severity === null ? '' : String(entry.severity), notes: entry.notes || '' });
|
||||
}
|
||||
async function save(event: FormEvent) {
|
||||
event.preventDefault(); setSaving(true); setError(''); setNotice('');
|
||||
try {
|
||||
let typeId = form.behaviorTypeId;
|
||||
if (typeId === 'custom') {
|
||||
const data = await request(`${base}/behavior-types`, { method: 'POST', body: JSON.stringify({ name: customName, description: customDescription }) });
|
||||
typeId = data.behaviorType.id;
|
||||
setTypes((previous) => [...previous.filter((type) => type.id !== typeId), data.behaviorType]);
|
||||
setForm((previous) => ({ ...previous, behaviorTypeId: typeId }));
|
||||
}
|
||||
// Preserve sub-second precision if the timestamp was not edited.
|
||||
const occurredAt = editing && form.occurredAt === localTime(new Date(editing.occurredAt)) ? editing.occurredAt : new Date(form.occurredAt).toISOString();
|
||||
await request(`${base}/behaviors${editing ? `/${editing.id}` : ''}`, { method: editing ? 'PUT' : 'POST', body: JSON.stringify({ behaviorTypeId: typeId, occurredAt, durationSeconds: form.duration === '' ? null : Number(form.duration), severity: form.severity === '' ? null : Number(form.severity), notes: form.notes || null }) });
|
||||
const savedDate = new Date(occurredAt);
|
||||
setMonth(new Date(savedDate.getFullYear(), savedDate.getMonth(), 1)); setDay(localDate(savedDate));
|
||||
setFilter(''); setShowForm(false); setEditing(null); setRevision((value) => value + 1); setNotice('Occurrence saved.');
|
||||
} catch (e) { setError(e instanceof Error ? e.message : 'Unable to save occurrence.'); }
|
||||
finally { setSaving(false); }
|
||||
}
|
||||
async function remove(entry: Occurrence) {
|
||||
if (!window.confirm(`Delete this ${entry.behaviorName} occurrence?`)) return;
|
||||
setSaving(true); setError(''); setNotice('');
|
||||
try {
|
||||
await request(`${base}/behaviors/${entry.id}`, { method: 'DELETE' });
|
||||
if (editing?.id === entry.id) { setShowForm(false); setEditing(null); }
|
||||
setRevision((value) => value + 1); setNotice('Occurrence deleted.');
|
||||
} catch (e) { setError(e instanceof Error ? e.message : 'Unable to delete occurrence.'); }
|
||||
finally { setSaving(false); }
|
||||
}
|
||||
const days = new Date(month.getFullYear(), month.getMonth() + 1, 0).getDate();
|
||||
return <section className="panel inset-panel behavior-journal" role="tabpanel" aria-label="Behavior Journal">
|
||||
<div className="panel-header"><div><p className="eyebrow">{bird.name}</p><h2>Behavior Journal</h2></div>
|
||||
{writable && <button type="button" className="primary-button" disabled={saving} onClick={() => { setForm(emptyForm()); setEditing(null); setCustomName(''); setCustomDescription(''); setShowForm(true); setError(''); setNotice(''); }}>Record behavior</button>}
|
||||
</div>
|
||||
<p className="muted">Record what you observed and review when it happened. Dates and times use your device’s local time zone.</p>
|
||||
{error && <p className="error-banner" role="alert">{error}</p>}
|
||||
{notice && <p className="success-banner" role="status">{notice}</p>}
|
||||
{showForm && writable && <form onSubmit={save} className="behavior-form">
|
||||
<h3>{editing ? 'Edit occurrence' : 'Record occurrence'}</h3>
|
||||
<fieldset disabled={saving}>
|
||||
<label>Behavior<select aria-label="Behavior" required value={form.behaviorTypeId} onChange={(e) => setForm({ ...form, behaviorTypeId: e.target.value })}><option value="">Select behavior</option>{types.map((type) => <option key={type.id} value={type.id}>{type.name}</option>)}<option value="custom">Create custom behavior…</option></select></label>
|
||||
{form.behaviorTypeId === 'custom' && <><label>Custom behavior name<input required maxLength={120} value={customName} onChange={(e) => setCustomName(e.target.value)} /></label><label>Description (optional)<input maxLength={2000} value={customDescription} onChange={(e) => setCustomDescription(e.target.value)} /></label></>}
|
||||
<label className="behavior-wide">Date and time<input type="datetime-local" step="1" required value={form.occurredAt} onChange={(e) => setForm({ ...form, occurredAt: e.target.value })} /></label>
|
||||
<label>Duration in seconds (optional)<input type="number" min="0.001" max="31536000" step="any" value={form.duration} onChange={(e) => setForm({ ...form, duration: e.target.value })} /></label>
|
||||
<label>Intensity (optional)<select aria-label="Intensity (optional)" value={form.severity} onChange={(e) => setForm({ ...form, severity: e.target.value })}><option value="">Not recorded</option>{[1, 2, 3, 4, 5].map((value) => <option key={value} value={value}>{value}{value === 1 ? ' — Low' : value === 5 ? ' — High' : ''}</option>)}</select></label>
|
||||
<label className="behavior-wide">Notes (optional)<textarea maxLength={10000} rows={3} value={form.notes} onChange={(e) => setForm({ ...form, notes: e.target.value })} /></label>
|
||||
<div className="behavior-actions"><button className="primary-button" type="submit">{saving ? 'Saving…' : 'Save occurrence'}</button><button className="secondary-button" type="button" onClick={() => { setShowForm(false); setEditing(null); }}>Cancel</button></div>
|
||||
</fieldset>
|
||||
</form>}
|
||||
<label>Bird<select aria-label="Bird" value={bird.id} disabled={saving} onChange={(e) => onSelectBird(e.target.value)}>{birds.map((item) => <option key={item.id} value={item.id}>{item.name}</option>)}</select></label>
|
||||
<label>Show behavior<select aria-label="Show behavior" value={filter} disabled={saving} onChange={(e) => setFilter(e.target.value)}><option value="">All behaviors</option>{types.map((type) => <option key={type.id} value={type.id}>{type.name}</option>)}</select></label>
|
||||
<div className="behavior-month"><button className="secondary-button" type="button" aria-label="Previous month" onClick={() => navigate(-1)}>‹</button><h3 aria-live="polite">{month.toLocaleDateString(undefined, { month: 'long', year: 'numeric' })}</h3><button className="secondary-button" type="button" aria-label="Next month" onClick={() => navigate(1)}>›</button></div>
|
||||
<p aria-live="polite">{loading ? 'Loading occurrences…' : `${entries.length} occurrence${entries.length === 1 ? '' : 's'} this month`}</p>
|
||||
<div className="behavior-calendar" aria-label="Monthly behavior occurrences" aria-busy={loading}>
|
||||
{['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'].map((label) => <span className="behavior-weekday" key={label}>{label}</span>)}
|
||||
{Array.from({ length: month.getDay() }, (_, index) => <span key={`blank-${index}`} />)}
|
||||
{Array.from({ length: days }, (_, index) => {
|
||||
const date = new Date(month.getFullYear(), month.getMonth(), index + 1); const key = localDate(date); const count = byDay.get(key)?.length || 0;
|
||||
return <button type="button" key={key} className={`behavior-day ${count ? 'has-occurrences' : ''}`} aria-pressed={key === day} aria-current={key === localDate(new Date()) ? 'date' : undefined} aria-label={`${date.toLocaleDateString()}: ${count} occurrences`} onClick={() => setDay(key)}><span>{index + 1}</span>{count > 0 && <><span className="behavior-dots" aria-hidden="true">{'●'.repeat(Math.min(count, 3))}{count > 3 ? '+' : ''}</span><small>{count}</small></>}</button>;
|
||||
})}
|
||||
</div>
|
||||
<h3>{new Date(`${day}T12:00:00`).toLocaleDateString(undefined, { dateStyle: 'long' })}</h3>
|
||||
{!loading && !(byDay.get(day)?.length) && <p className="muted">No occurrences recorded for this day{filter ? ' for the selected behavior' : ''}.</p>}
|
||||
{(byDay.get(day) || []).map((entry) => <details key={entry.id} className="behavior-entry"><summary><strong>{entry.behaviorName}</strong><span>{new Date(entry.occurredAt).toLocaleString()}</span>{entry.durationSeconds !== null && <span>Duration: {entry.durationSeconds} seconds</span>}{entry.severity !== null && <span>Intensity: {entry.severity}/5</span>}{entry.notes && <span className="behavior-note-preview">{entry.notes}</span>}</summary><div>{entry.notes && <p className="behavior-notes">{entry.notes}</p>}<p className="muted">Created: {new Date(entry.createdAt).toLocaleString()}<br />Updated: {new Date(entry.updatedAt).toLocaleString()}</p>{writable && <div className="behavior-actions"><button className="secondary-button" type="button" disabled={saving} onClick={() => edit(entry)}>Edit</button><button className="danger-button" type="button" disabled={saving} onClick={() => void remove(entry)}>Delete</button></div>}</div></details>)}
|
||||
</section>;
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 7.9 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 242 KiB |
@@ -0,0 +1,24 @@
|
||||
.behavior-journal { min-width: 0; }
|
||||
.behavior-journal > label + label { margin-top: .75rem; }
|
||||
.behavior-journal label { display: grid; gap: .4rem; }
|
||||
.behavior-month { display: flex; justify-content: space-between; align-items: center; gap: .5rem; margin-top: 1rem; }
|
||||
.behavior-calendar { display: grid; grid-template-columns: repeat(7, minmax(0, 1fr)); gap: .3rem; }
|
||||
.behavior-weekday { text-align: center; font-size: .8rem; }
|
||||
.behavior-day { min-height: 76px; min-width: 0; border: 1px solid #c5d4ce; border-radius: .6rem; background: #fff; color: #244338; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: .15rem; cursor: pointer; }
|
||||
.behavior-day.has-occurrences { background: #e4f2e9; }
|
||||
.behavior-day[aria-pressed="true"] { outline: 3px solid #326b56; outline-offset: -3px; }
|
||||
.behavior-day[aria-current="date"] > span:first-child { text-decoration: underline; font-weight: bold; }
|
||||
.behavior-dots { font-size: .65rem; letter-spacing: .04em; }
|
||||
.behavior-day:focus-visible { outline: 3px solid #1c5ba3; }
|
||||
.behavior-form { margin: 1rem 0; }
|
||||
.behavior-form fieldset { border: 0; padding: 0; display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 1rem; }
|
||||
.behavior-wide { grid-column: 1 / -1; }
|
||||
.behavior-form input, .behavior-form select, .behavior-form textarea { min-width: 0; width: 100%; box-sizing: border-box; }
|
||||
.behavior-form .behavior-actions { grid-column: 1 / -1; }
|
||||
.behavior-actions { display: flex; flex-wrap: wrap; gap: .5rem; }
|
||||
.behavior-entry { padding: 1rem; margin: .75rem 0; border: 1px solid #c5d4ce; border-radius: .6rem; }
|
||||
.behavior-entry summary { cursor: pointer; }
|
||||
.behavior-entry summary > span { display: block; margin-top: .3rem; }
|
||||
.behavior-note-preview { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.behavior-notes { white-space: pre-wrap; overflow-wrap: anywhere; }
|
||||
@media (max-width: 540px) { .behavior-form fieldset { grid-template-columns: 1fr; } .behavior-day { min-height: 64px; padding: .2rem; } .behavior-calendar { gap: .15rem; } .behavior-weekday { font-size: .7rem; } }
|
||||
+1529
-22
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,138 @@
|
||||
// Optional browser check. Requires Playwright in a disposable frontend install; see docs/BEHAVIOR_JOURNAL.md.
|
||||
import assert from 'node:assert/strict';
|
||||
import { randomUUID, createHash } from 'node:crypto';
|
||||
import { spawn } from 'node:child_process';
|
||||
import { once } from 'node:events';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { chromium } from 'playwright';
|
||||
Object.assign(process.env, {
|
||||
POSTGRES_HOST: '127.0.0.1', POSTGRES_PORT: '55439', POSTGRES_DB: 'behavior_test', POSTGRES_USER: 'postgres',
|
||||
POSTGRES_PASSWORD: 'behavior_test_only', PORT: '55440', FRONTEND_URL: 'http://127.0.0.1:55441',
|
||||
VITE_API_BASE_URL: 'http://127.0.0.1:55440/api',
|
||||
MILESTONE_REMINDERS_ENABLED: 'false', MEDICATION_REMINDERS_ENABLED: 'false', WEIGHT_REMINDERS_ENABLED: 'false',
|
||||
});
|
||||
const { db } = await import('../../backend/dist/db/client.js');
|
||||
const children = [];
|
||||
let browser;
|
||||
let page;
|
||||
async function start(path, args, marker) {
|
||||
let output = '';
|
||||
const child = spawn(process.execPath, [fileURLToPath(path), ...args], { cwd: fileURLToPath(new URL('../', import.meta.url)), env: process.env, stdio: ['ignore', 'pipe', 'pipe'] });
|
||||
children.push(child);
|
||||
child.stdout.on('data', (data) => { output += data; }); child.stderr.on('data', (data) => { output += data; });
|
||||
for (let i = 0; i < 100 && !output.includes(marker); i++) await new Promise((resolve) => setTimeout(resolve, 100));
|
||||
assert.ok(output.includes(marker), output);
|
||||
}
|
||||
try {
|
||||
const workspace = 100000 + Math.floor(Math.random() * 1000000000);
|
||||
const user = randomUUID(), bird = randomUUID(), secondBird = randomUUID(), token = randomUUID();
|
||||
await db.query(`INSERT INTO workspaces (id, name, workspace_type, rescue_verification_status) VALUES ($1, 'Browser test', 'rescue', 'approved')`, [workspace]);
|
||||
await db.query(`INSERT INTO users (id, email, name) VALUES ($1, $2, 'Browser tester')`, [user, `${user}@example.test`]);
|
||||
await db.query(`INSERT INTO workspace_members (workspace_id, user_id, invite_email, name, role, accepted_at) VALUES ($1, $2, $3, 'Browser tester', 'owner', NOW())`, [workspace, user, `${user}@example.test`]);
|
||||
await db.query(`INSERT INTO auth_sessions (user_id, active_workspace_id, token_hash, expires_at) VALUES ($1, $2, $3, NOW() + INTERVAL '1 hour')`, [user, workspace, createHash('sha256').update(token).digest('hex')]);
|
||||
await db.query(`INSERT INTO birds (id, workspace_id, name, species) VALUES ($1, $2, 'Piper', 'Parrot'), ($3, $2, 'Willow', 'Parrot')`, [bird, workspace, secondBird]);
|
||||
const type = (await db.query(`SELECT id FROM behavior_types WHERE is_default ORDER BY name LIMIT 1`)).rows[0].id;
|
||||
for (const timestamp of ['2026-10-01T03:59:59Z', '2026-10-01T04:00:00Z', '2026-11-01T05:30:00Z', '2026-11-01T06:30:00Z']) {
|
||||
await db.query(`INSERT INTO behavior_occurrences (bird_id, behavior_type_id, occurred_at) VALUES ($1, $2, $3)`, [bird, type, timestamp]);
|
||||
}
|
||||
await start(new URL('../../backend/dist/app.js', import.meta.url), [], 'listening');
|
||||
await start(new URL('../node_modules/vite/bin/vite.js', import.meta.url), ['--host', '127.0.0.1', '--port', '55441'], 'Local:');
|
||||
browser = await chromium.launch({ headless: true });
|
||||
const context = await browser.newContext({ timezoneId: 'America/New_York', viewport: { width: 1280, height: 1000 } });
|
||||
page = await context.newPage();
|
||||
const errors = []; page.on('pageerror', (e) => errors.push(e.message));
|
||||
await page.addInitScript((value) => localStorage.setItem('flockpal_auth_token', value), token);
|
||||
await page.clock.setFixedTime(new Date('2026-10-05T16:00:00Z'));
|
||||
await page.goto('http://127.0.0.1:55441');
|
||||
await page.getByRole('button', { name: 'Flock', exact: true }).click();
|
||||
await page.locator('.bird-card-select').filter({ hasText: 'Piper' }).click();
|
||||
await page.getByRole('tab', { name: 'Behavior Journal' }).click();
|
||||
const journal = page.getByRole('tabpanel', { name: 'Behavior Journal' });
|
||||
await journal.getByText('1 occurrence this month', { exact: true }).waitFor();
|
||||
await journal.getByRole('button', { name: 'Record behavior' }).click();
|
||||
assert.match(await journal.getByLabel('Date and time', { exact: true }).inputValue(), /^2026-10-05T12:00(:00)?$/);
|
||||
await journal.getByLabel('Behavior', { exact: true }).selectOption('custom');
|
||||
await journal.getByLabel('Custom behavior name').fill('Wing stretching');
|
||||
await journal.getByLabel('Description (optional)').fill('Wings extended');
|
||||
await journal.getByLabel('Date and time', { exact: true }).fill('2026-10-05T23:30:12');
|
||||
await journal.getByLabel('Duration in seconds (optional)').fill('90');
|
||||
await journal.getByLabel('Intensity (optional)').selectOption('3');
|
||||
await journal.getByLabel('Notes (optional)').fill('Observed after play');
|
||||
await journal.getByRole('button', { name: 'Save occurrence' }).click();
|
||||
await journal.getByText('Occurrence saved.', { exact: true }).waitFor();
|
||||
await journal.getByRole('button', { name: 'Record behavior' }).click();
|
||||
await journal.getByLabel('Behavior', { exact: true }).selectOption({ label: 'Wing stretching' });
|
||||
await journal.getByLabel('Date and time', { exact: true }).fill('2026-10-05T22:00');
|
||||
await journal.getByRole('button', { name: 'Save occurrence' }).click();
|
||||
await journal.getByText('3 occurrences this month', { exact: true }).waitFor();
|
||||
const day = journal.getByRole('button', { name: '10/5/2026: 2 occurrences', exact: true });
|
||||
await day.click(); assert.equal(await journal.locator('details').count(), 2);
|
||||
const entry = journal.locator('details').filter({ hasText: 'Observed after play' });
|
||||
await entry.locator('summary').click();
|
||||
await entry.getByRole('button', { name: 'Edit', exact: true }).click();
|
||||
await journal.getByLabel('Notes (optional)').fill('Edited observation');
|
||||
await journal.getByRole('button', { name: 'Save occurrence' }).click();
|
||||
await journal.getByText('Edited observation', { exact: true }).first().waitFor();
|
||||
await journal.getByLabel('Show behavior', { exact: true }).selectOption({ label: 'Wing stretching' });
|
||||
await journal.getByText('2 occurrences this month', { exact: true }).waitFor();
|
||||
await journal.getByRole('button', { name: 'Next month' }).click();
|
||||
await journal.getByText('0 occurrences this month', { exact: true }).waitFor();
|
||||
await journal.getByLabel('Show behavior', { exact: true }).selectOption('');
|
||||
await journal.getByText('2 occurrences this month', { exact: true }).waitFor();
|
||||
await journal.getByRole('button', { name: '11/1/2026: 2 occurrences', exact: true }).click();
|
||||
assert.equal(await journal.locator('details').count(), 2); // Both sides of fall-back belong to Nov 1.
|
||||
await journal.locator('details').first().locator('summary').click();
|
||||
await journal.locator('details').first().getByRole('button', { name: 'Edit', exact: true }).click();
|
||||
await journal.getByLabel('Notes (optional)').fill('Later repeated hour retained');
|
||||
await journal.getByRole('button', { name: 'Save occurrence' }).click();
|
||||
await journal.getByText('Occurrence saved.', { exact: true }).waitFor();
|
||||
const repeated = (await db.query(`SELECT occurred_at FROM behavior_occurrences WHERE bird_id = $1 AND notes = 'Later repeated hour retained'`, [bird])).rows[0];
|
||||
assert.equal(repeated.occurred_at.toISOString(), '2026-11-01T06:30:00.000Z');
|
||||
|
||||
await journal.getByRole('button', { name: 'Previous month' }).click();
|
||||
await journal.getByRole('button', { name: 'Previous month' }).click();
|
||||
await journal.getByText('1 occurrence this month', { exact: true }).waitFor(); // UTC Oct 1 before local midnight.
|
||||
await journal.getByRole('button', { name: 'Next month' }).click();
|
||||
await journal.getByRole('button', { name: '10/5/2026: 2 occurrences', exact: true }).click();
|
||||
await page.setViewportSize({ width: 390, height: 844 });
|
||||
await journal.scrollIntoViewIfNeeded();
|
||||
await page.screenshot({ path: '/tmp/flockpal-behavior-mobile.png', fullPage: true });
|
||||
assert.equal(await journal.evaluate((element) => element.scrollWidth <= element.clientWidth + 1), true, 'Journal must fit mobile width');
|
||||
const editedEntry = journal.locator('details').filter({ hasText: 'Edited observation' });
|
||||
await editedEntry.locator('summary').click();
|
||||
page.once('dialog', (dialog) => dialog.accept());
|
||||
await editedEntry.getByRole('button', { name: 'Delete', exact: true }).click();
|
||||
await journal.getByText('Occurrence deleted.', { exact: true }).waitFor();
|
||||
await journal.getByRole('button', { name: '10/5/2026: 1 occurrences', exact: true }).waitFor();
|
||||
await journal.getByLabel('Bird', { exact: true }).selectOption(secondBird);
|
||||
await journal.getByText('0 occurrences this month', { exact: true }).waitFor();
|
||||
await journal.getByLabel('Bird', { exact: true }).selectOption(bird);
|
||||
await journal.getByText('2 occurrences this month', { exact: true }).waitFor();
|
||||
await page.setViewportSize({ width: 1280, height: 1000 });
|
||||
await journal.scrollIntoViewIfNeeded();
|
||||
await page.screenshot({ path: '/tmp/flockpal-behavior-desktop.png', fullPage: true });
|
||||
const utcContext = await browser.newContext({ timezoneId: 'UTC', viewport: { width: 1280, height: 1000 } });
|
||||
const utcPage = await utcContext.newPage();
|
||||
await utcPage.addInitScript((value) => localStorage.setItem('flockpal_auth_token', value), token);
|
||||
await utcPage.clock.setFixedTime(new Date('2026-10-05T16:00:00Z'));
|
||||
await utcPage.goto('http://127.0.0.1:55441');
|
||||
await utcPage.getByRole('button', { name: 'Flock', exact: true }).click();
|
||||
await utcPage.locator('.bird-card-select').filter({ hasText: 'Piper' }).click();
|
||||
await utcPage.getByRole('tab', { name: 'Behavior Journal' }).click();
|
||||
const utcJournal = utcPage.getByRole('tabpanel', { name: 'Behavior Journal' });
|
||||
await utcJournal.getByText('3 occurrences this month', { exact: true }).waitFor();
|
||||
await utcJournal.getByRole('button', { name: '10/1/2026: 2 occurrences', exact: true }).waitFor();
|
||||
await utcContext.close();
|
||||
assert.deepEqual(errors, []);
|
||||
console.log('PASS: browser create/custom type/edit/delete, bird/behavior filters, month navigation, multiple events/day, local midnight and DST, and mobile layout.');
|
||||
} catch (error) {
|
||||
if (page) {
|
||||
console.error(await page.locator('.behavior-journal').innerText().catch(() => 'Journal unavailable'));
|
||||
await page.screenshot({ path: '/tmp/flockpal-behavior-failure.png', fullPage: true });
|
||||
}
|
||||
throw error;
|
||||
} finally {
|
||||
if (browser) await browser.close();
|
||||
for (const child of children.reverse()) if (child.exitCode === null) { const done = once(child, 'exit'); child.kill('SIGTERM'); await done; }
|
||||
await db.close();
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
// Optional browser integration check; use the disposable setup in docs/BIRD_MEMBERSHIP.md.
|
||||
import assert from 'node:assert/strict';
|
||||
import { randomUUID, createHash } from 'node:crypto';
|
||||
import { spawn } from 'node:child_process';
|
||||
import { once } from 'node:events';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { chromium } from 'playwright';
|
||||
Object.assign(process.env, {
|
||||
POSTGRES_HOST: '127.0.0.1', POSTGRES_PORT: '55439', POSTGRES_DB: 'behavior_test', POSTGRES_USER: 'postgres',
|
||||
POSTGRES_PASSWORD: 'behavior_test_only', PORT: '55440', FRONTEND_URL: 'http://127.0.0.1:55441',
|
||||
VITE_API_BASE_URL: 'http://127.0.0.1:55440/api',
|
||||
MILESTONE_REMINDERS_ENABLED: 'false', MEDICATION_REMINDERS_ENABLED: 'false', WEIGHT_REMINDERS_ENABLED: 'false',
|
||||
});
|
||||
const { db } = await import('../../backend/dist/db/client.js');
|
||||
const children = [];
|
||||
let browser;
|
||||
async function start(path, args, marker) {
|
||||
let output = '';
|
||||
const child = spawn(process.execPath, [fileURLToPath(path), ...args], { cwd: fileURLToPath(new URL('../', import.meta.url)), env: process.env, stdio: ['ignore', 'pipe', 'pipe'] });
|
||||
children.push(child);
|
||||
child.stdout.on('data', (data) => { output += data; }); child.stderr.on('data', (data) => { output += data; });
|
||||
for (let i = 0; i < 100 && !output.includes(marker); i++) await new Promise((resolve) => setTimeout(resolve, 100));
|
||||
assert.ok(output.includes(marker), output);
|
||||
}
|
||||
try {
|
||||
const accounts = [];
|
||||
const baseId = 100000 + Math.floor(Math.random() * 1000000000);
|
||||
for (let i = 0; i < 2; i++) {
|
||||
const workspace = baseId + i, user = randomUUID(), token = randomUUID(), email = `${user}@example.test`;
|
||||
await db.query(`INSERT INTO workspaces (id, name, workspace_type, rescue_verification_status) VALUES ($1, $2, 'rescue', 'approved')`, [workspace, `Browser membership ${i}`]);
|
||||
await db.query(`INSERT INTO users (id, email, name) VALUES ($1, $2, 'Browser tester')`, [user, email]);
|
||||
await db.query(`INSERT INTO workspace_members (workspace_id, user_id, invite_email, name, role, accepted_at) VALUES ($1, $2, $3, 'Browser tester', 'owner', NOW())`, [workspace, user, email]);
|
||||
await db.query(`INSERT INTO auth_sessions (user_id, active_workspace_id, token_hash, expires_at) VALUES ($1, $2, $3, NOW() + INTERVAL '1 hour')`, [user, workspace, createHash('sha256').update(token).digest('hex')]);
|
||||
accounts.push({ workspace, token });
|
||||
}
|
||||
const [source, destination] = accounts;
|
||||
const bird = randomUUID(), tagId = `FP-${randomUUID()}`;
|
||||
await db.query(`INSERT INTO birds (id, workspace_id, name, tag_id, species) VALUES ($1, $2, 'Piper', $3, 'Parrot')`, [bird, source.workspace, tagId]);
|
||||
await db.query(`INSERT INTO weight_records (bird_id, weight_grams, recorded_on) VALUES ($1, 120, CURRENT_DATE)`, [bird]);
|
||||
await db.query(`INSERT INTO flock_notes (workspace_id, bird_id, title, body) VALUES ($1, $2, 'Existing note', 'Enjoys morning play')`, [source.workspace, bird]);
|
||||
await start(new URL('../../backend/dist/app.js', import.meta.url), [], 'listening');
|
||||
await start(new URL('../node_modules/vite/bin/vite.js', import.meta.url), ['--host', '127.0.0.1', '--port', '55441'], 'Local:');
|
||||
browser = await chromium.launch({ headless: true });
|
||||
const sourcePage = await browser.newPage({ viewport: { width: 1280, height: 1000 } });
|
||||
await sourcePage.addInitScript((value) => localStorage.setItem('flockpal_auth_token', value), source.token);
|
||||
await sourcePage.goto('http://127.0.0.1:55441', { waitUntil: 'domcontentloaded' });
|
||||
await sourcePage.getByRole('button', { name: 'Flock', exact: true }).click();
|
||||
await sourcePage.locator('.bird-card-select').filter({ hasText: 'Piper' }).click();
|
||||
await sourcePage.getByRole('button', { name: 'Edit details for Piper' }).click();
|
||||
sourcePage.once('dialog', async (dialog) => { assert.match(dialog.message(), /history will be retained/); await dialog.accept(); });
|
||||
await sourcePage.getByRole('button', { name: 'Remove from flock', exact: true }).click();
|
||||
await sourcePage.locator('.bird-card-select').filter({ hasText: 'Piper' }).waitFor({ state: 'detached' });
|
||||
assert.equal((await db.query(`SELECT workspace_id FROM birds WHERE id = $1`, [bird])).rows[0].workspace_id, null);
|
||||
const page = await browser.newPage({ viewport: { width: 390, height: 844 } });
|
||||
const pageErrors = []; page.on('pageerror', (error) => pageErrors.push(error.message));
|
||||
await page.addInitScript((value) => localStorage.setItem('flockpal_auth_token', value), destination.token);
|
||||
await page.goto('http://127.0.0.1:55441', { waitUntil: 'domcontentloaded' });
|
||||
await page.getByRole('button', { name: 'Flock', exact: true }).click();
|
||||
await page.getByRole('button', { name: 'Add bird', exact: true }).click();
|
||||
const bandInput = page.getByLabel('Band ID, if known', { exact: true });
|
||||
await bandInput.fill(tagId.slice(0, -1));
|
||||
await page.getByText('Checking band ID for existing history…').waitFor({ state: 'hidden' });
|
||||
assert.equal(await page.getByRole('button', { name: 'Add bird with existing history' }).count(), 0);
|
||||
await bandInput.fill(` ${tagId.toLowerCase()} `);
|
||||
const claimButton = page.getByRole('button', { name: 'Add bird with existing history' });
|
||||
await claimButton.waitFor();
|
||||
assert.equal(await page.getByRole('button', { name: 'Save bird profile', exact: true }).isDisabled(), true);
|
||||
const notice = page.getByRole('status').filter({ hasText: 'This band ID matches' });
|
||||
assert.equal(await notice.evaluate((element) => element.scrollWidth <= element.clientWidth), true);
|
||||
await notice.screenshot({ path: '/tmp/flockpal-existing-history-notice.png' });
|
||||
page.once('dialog', async (dialog) => { assert.match(dialog.message(), /history will be brought in/); await dialog.dismiss(); });
|
||||
await claimButton.click();
|
||||
assert.equal((await db.query(`SELECT workspace_id FROM birds WHERE id = $1`, [bird])).rows[0].workspace_id, null);
|
||||
// Only a band ID is needed: no replacement name or species should be required to claim history.
|
||||
assert.equal(await page.getByLabel('Bird name', { exact: true }).inputValue(), '');
|
||||
page.on('dialog', (dialog) => dialog.accept());
|
||||
await claimButton.click();
|
||||
await page.getByRole('tab', { name: 'Weight', exact: true }).waitFor();
|
||||
assert.equal((await db.query(`SELECT workspace_id FROM birds WHERE id = $1`, [bird])).rows[0].workspace_id, destination.workspace);
|
||||
assert.equal((await db.query(`SELECT COUNT(*)::int AS count FROM birds WHERE LOWER(tag_id) = LOWER($1)`, [tagId])).rows[0].count, 1);
|
||||
await page.getByRole('tab', { name: 'Notes', exact: true }).click();
|
||||
await page.getByText('Enjoys morning play', { exact: true }).waitFor();
|
||||
await page.getByRole('tab', { name: 'Timeline', exact: true }).click();
|
||||
await page.getByText('Joined flock with history', { exact: true }).first().waitFor();
|
||||
assert.deepEqual(pageErrors, []);
|
||||
console.log('PASS: desktop removal retains history; mobile exact band match notice, cancellation, confirmation, claim without replacement fields, and restored notes/timeline.');
|
||||
} finally {
|
||||
if (browser) await browser.close();
|
||||
for (const child of children.reverse()) if (child.exitCode === null) { const done = once(child, 'exit'); child.kill('SIGTERM'); await done; }
|
||||
await db.close();
|
||||
}
|
||||
@@ -5,5 +5,11 @@ export default defineConfig({
|
||||
plugins: [react()],
|
||||
server: {
|
||||
port: 3000,
|
||||
proxy: {
|
||||
'/api': {
|
||||
target: 'http://backend:5000',
|
||||
changeOrigin: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
Reference in new issue
Block a user