Merge dev into production release without education
This commit is contained in:
commit
fc541f024d
50 files changed
+2986
-458
No files matched your search
@@ -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();
|
||||
}
|
||||
Reference in new issue
Block a user