Added adoption report and transfer code
This commit is contained in:
+121
-3
@@ -35,6 +35,7 @@ import {
|
||||
completePendingBirdTransfersForOwner,
|
||||
createBird,
|
||||
createBirdMilestoneReminderDelivery,
|
||||
createBirdTransferCode,
|
||||
createMedicationForBird,
|
||||
createPendingBirdTransfer,
|
||||
findBirdsByBandId,
|
||||
@@ -45,6 +46,7 @@ import {
|
||||
deleteVetVisitForBird,
|
||||
getBirdById,
|
||||
getBirdByPublicProfileCode,
|
||||
getOpenBirdTransferCode,
|
||||
listBirds,
|
||||
listDueBirdMilestoneReminders,
|
||||
listMemorializedBirds,
|
||||
@@ -53,6 +55,7 @@ import {
|
||||
listVetVisitsForBird,
|
||||
listWeightsForBird,
|
||||
memorializeBird,
|
||||
markBirdTransferCodeCompleted,
|
||||
transferBirdToWorkspace,
|
||||
updateBird,
|
||||
updateMemorialReminderPreference,
|
||||
@@ -244,6 +247,7 @@ const lostBirdReportSchema = z.object({
|
||||
});
|
||||
|
||||
const publicProfileCodeSchema = z.string().trim().regex(/^[A-Za-z0-9_-]{8,32}$/);
|
||||
const birdTransferCodeSchema = z.string().trim().regex(/^[A-Za-z0-9_-]{12,32}$/);
|
||||
const birdProfileListSchema = z
|
||||
.string()
|
||||
.trim()
|
||||
@@ -646,6 +650,8 @@ const normalizeBird = (row: BirdRow) => ({
|
||||
latestRecordedOn: row.latest_recorded_on,
|
||||
});
|
||||
|
||||
const createBirdTransferCodeValue = () => crypto.randomBytes(12).toString('base64url');
|
||||
|
||||
const normalizePublicBirdProfile = (row: BirdRow) => ({
|
||||
id: row.id,
|
||||
workspaceId: row.workspace_id,
|
||||
@@ -3154,7 +3160,7 @@ app.post('/api/birds', requireAuth, requireWriteAccess, requireWorkspaceRole(['o
|
||||
await deleteBirdPhotoObjectIfNeeded(uploadedObjectKeyToCleanup);
|
||||
|
||||
if (typeof error === 'object' && error && 'code' in error && error.code === '23505') {
|
||||
res.status(409).json({ error: 'That band/tag ID is already in use in this flock.' });
|
||||
res.status(409).json({ error: 'That band/tag ID is already in use in FlockPal.' });
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -3236,7 +3242,7 @@ app.post('/api/birds/:birdId/transfer', requireAuth, requireWriteAccess, require
|
||||
res.json({ bird: normalizeBird(bird), destinationOwnerEmail, destinationWorkspace: normalizeWorkspace(targetWorkspace) });
|
||||
} catch (error) {
|
||||
if (typeof error === 'object' && error && 'code' in error && error.code === '23505') {
|
||||
res.status(409).json({ error: 'That band/tag ID is already in use in the destination flock.' });
|
||||
res.status(409).json({ error: 'That band/tag ID is already in use in FlockPal.' });
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -3244,6 +3250,118 @@ app.post('/api/birds/:birdId/transfer', requireAuth, requireWriteAccess, require
|
||||
}
|
||||
});
|
||||
|
||||
app.post(
|
||||
'/api/birds/:birdId/transfer-code',
|
||||
requireAuth,
|
||||
requireWriteAccess,
|
||||
requireSessionAuth,
|
||||
requireWorkspaceRole(['owner', 'assistant']),
|
||||
async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const sourceBird = await getBirdById(req.params.birdId, req.auth!.workspace.id);
|
||||
|
||||
if (!sourceBird) {
|
||||
res.status(404).json({ error: 'Bird not found.' });
|
||||
return;
|
||||
}
|
||||
|
||||
if (!ensureBirdWritable(sourceBird, res)) {
|
||||
return;
|
||||
}
|
||||
|
||||
let transferCode = null;
|
||||
|
||||
for (let attempt = 0; attempt < 3; attempt += 1) {
|
||||
try {
|
||||
transferCode = await createBirdTransferCode({
|
||||
code: createBirdTransferCodeValue(),
|
||||
birdId: sourceBird.id,
|
||||
sourceWorkspaceId: req.auth!.workspace.id,
|
||||
requestedByUserId: req.auth!.user.id,
|
||||
});
|
||||
break;
|
||||
} catch (error) {
|
||||
if (typeof error === 'object' && error && 'code' in error && error.code === '23505' && attempt < 2) {
|
||||
continue;
|
||||
}
|
||||
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
if (!transferCode) {
|
||||
throw new Error('Unable to create bird transfer code.');
|
||||
}
|
||||
|
||||
await writeAuditLog(req.auth!, 'bird.transfer_code_created', 'bird', sourceBird.id, sourceBird.name, {
|
||||
transferCodeId: transferCode.id,
|
||||
});
|
||||
|
||||
res.status(201).json({
|
||||
transferCode: {
|
||||
code: transferCode.code,
|
||||
bird: normalizeBird(sourceBird),
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
app.post(
|
||||
'/api/bird-transfer-codes/:code/accept',
|
||||
requireAuth,
|
||||
requireWriteAccess,
|
||||
requireSessionAuth,
|
||||
requireWorkspaceRole(['owner', 'assistant']),
|
||||
async (req: Request, res: Response, next: NextFunction) => {
|
||||
const parsed = birdTransferCodeSchema.safeParse(req.params.code);
|
||||
|
||||
if (!parsed.success) {
|
||||
res.status(404).json({ error: 'Bird transfer code not found.' });
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const transferCode = await getOpenBirdTransferCode(parsed.data);
|
||||
|
||||
if (!transferCode) {
|
||||
res.status(404).json({ error: 'Bird transfer code not found or already used.' });
|
||||
return;
|
||||
}
|
||||
|
||||
if (transferCode.source_workspace_id === req.auth!.workspace.id) {
|
||||
res.status(409).json({ error: 'This bird is already in your active flock.' });
|
||||
return;
|
||||
}
|
||||
|
||||
const bird = await transferBirdToWorkspace(transferCode.id, transferCode.source_workspace_id, req.auth!.workspace.id);
|
||||
|
||||
if (!bird) {
|
||||
res.status(404).json({ error: 'Bird is no longer available for transfer.' });
|
||||
return;
|
||||
}
|
||||
|
||||
await markBirdTransferCodeCompleted(transferCode.transfer_code_id, req.auth!.workspace.id);
|
||||
await writeAuditLog(req.auth!, 'bird.transfer_code_accepted', 'bird', bird.id, bird.name, {
|
||||
sourceWorkspaceId: transferCode.source_workspace_id,
|
||||
sourceWorkspaceName: transferCode.workspace_name,
|
||||
transferCodeId: transferCode.transfer_code_id,
|
||||
});
|
||||
|
||||
res.json({ bird: normalizeBird(bird), sourceWorkspaceName: transferCode.workspace_name, workspace: normalizeWorkspace(req.auth!.workspace) });
|
||||
} catch (error) {
|
||||
if (typeof error === 'object' && error && 'code' in error && error.code === '23505') {
|
||||
res.status(409).json({ error: 'That band/tag ID is already in use in FlockPal.' });
|
||||
return;
|
||||
}
|
||||
|
||||
next(error);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
app.put('/api/birds/:birdId', requireAuth, requireWriteAccess, requireWorkspaceRole(['owner', 'assistant', 'caregiver']), async (req: Request, res: Response, next: NextFunction) => {
|
||||
const parsed = birdSchema.safeParse(req.body);
|
||||
|
||||
@@ -3317,7 +3435,7 @@ app.put('/api/birds/:birdId', requireAuth, requireWriteAccess, requireWorkspaceR
|
||||
await deleteBirdPhotoObjectIfNeeded(uploadedObjectKeyToCleanup);
|
||||
|
||||
if (typeof error === 'object' && error && 'code' in error && error.code === '23505') {
|
||||
res.status(409).json({ error: 'That band/tag ID is already in use in this flock.' });
|
||||
res.status(409).json({ error: 'That band/tag ID is already in use in FlockPal.' });
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
@@ -292,8 +292,8 @@ export const ensureSchema = async (database: DatabaseClient = db) => {
|
||||
|
||||
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');
|
||||
@@ -346,6 +346,28 @@ 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 flock_notes (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
workspace_id INTEGER NOT NULL REFERENCES workspaces(id) ON DELETE CASCADE,
|
||||
|
||||
@@ -5,6 +5,7 @@ import type {
|
||||
BirdMilestoneReminderDeliveryRow,
|
||||
BirdMilestoneReminderType,
|
||||
BirdRow,
|
||||
BirdTransferCodeRow,
|
||||
LostBirdMatchRow,
|
||||
MedicationAdministrationRow,
|
||||
MedicationDoseScheduleItem,
|
||||
@@ -691,7 +692,7 @@ export const completePendingBirdTransfersForOwner = async (ownerEmail: string, t
|
||||
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.';
|
||||
@@ -702,6 +703,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
|
||||
|
||||
@@ -162,6 +162,18 @@ 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 WeightRow = {
|
||||
id: string;
|
||||
bird_id: string;
|
||||
|
||||
Reference in New Issue
Block a user