117 lines
11 KiB
JavaScript
117 lines
11 KiB
JavaScript
// 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, education_opt_out) VALUES ($1, $2, 'Tester', TRUE)`, [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();
|
|
}
|