Merge dev into production release without education
This commit is contained in:
commit
fc541f024d
50 files changed
+2986
-458
No files matched your search
+203
-396
@@ -1,3 +1,46 @@
|
||||
import { unassignedBirdMatchSchema, claimBirdSchema } from './birdMembershipSchemas.js';
|
||||
import { hasUnassignedBird, removeBirdFromFlock, claimUnassignedBird } from './repositories/birdMembershipRepository.js';
|
||||
import { behaviorTypeSchema, behaviorOccurrenceSchema, behaviorRangeSchema } from './behaviorSchemas.js';
|
||||
import { listBehaviorTypes, createBehaviorType, listBehaviorOccurrences, saveBehaviorOccurrence, deleteBehaviorOccurrence } from './repositories/behaviorRepository.js';
|
||||
import {
|
||||
dateStringSchema,
|
||||
chartColorSchema,
|
||||
photoDataUrlSchema,
|
||||
photoUrlSchema,
|
||||
magicLinkRequestSchema,
|
||||
switchWorkspaceSchema,
|
||||
workspaceTypeSchema,
|
||||
workspaceRoleSchema,
|
||||
billingPlanSchema,
|
||||
billingIntervalSchema,
|
||||
integrationTokenScopeSchema,
|
||||
birdGenderSchema,
|
||||
rescueVerificationStatusSchema,
|
||||
rescueOnboardingSchema,
|
||||
workspaceSchema,
|
||||
createWorkspaceSchema,
|
||||
workspaceMemberSchema,
|
||||
flockTransferSchema,
|
||||
lostBirdReportSchema,
|
||||
publicProfileCodeSchema,
|
||||
birdTransferCodeSchema,
|
||||
birdProfileListSchema,
|
||||
verifiedLocationDetailsSchema,
|
||||
locationSearchSchema,
|
||||
birdSchema,
|
||||
memorializeBirdSchema,
|
||||
memorialReminderPreferenceSchema,
|
||||
birdTimelineEventSchema,
|
||||
weightSchema,
|
||||
vetVisitSchema,
|
||||
medicationSchema,
|
||||
medicationAdministrationSchema,
|
||||
flockNoteSchema,
|
||||
} from './schemas.js';
|
||||
import { mountApiDocs } from './docs/router.js';
|
||||
import { buildEmailLayout } from './emails/emailLayout.js';
|
||||
import { buildWeightReminderEmail } from './emails/weightReminderEmail.js';
|
||||
import type { WeightReminder } from './reminders/weightReminders.js';
|
||||
import crypto from 'crypto';
|
||||
import { existsSync } from 'fs';
|
||||
import path from 'path';
|
||||
@@ -8,7 +51,7 @@ import express, { type NextFunction, type Request, type Response } from 'express
|
||||
import rateLimit from 'express-rate-limit';
|
||||
import helmet from 'helmet';
|
||||
import morgan from 'morgan';
|
||||
import nodemailer, { type SendMailOptions } from 'nodemailer';
|
||||
import nodemailer from 'nodemailer';
|
||||
import Stripe from 'stripe';
|
||||
import { z } from 'zod';
|
||||
|
||||
@@ -46,7 +89,6 @@ import {
|
||||
findBirdsByBandId,
|
||||
createVetVisitForBird,
|
||||
createWeightForBird,
|
||||
deleteBird,
|
||||
deleteMedicationForBird,
|
||||
deleteVetVisitForBird,
|
||||
getBirdById,
|
||||
@@ -190,163 +232,6 @@ const allowedOrigins = Array.from(
|
||||
),
|
||||
);
|
||||
|
||||
const dateStringSchema = z.string().regex(/^\d{4}-\d{2}-\d{2}$/);
|
||||
const chartColorSchema = z.string().regex(/^#[0-9a-fA-F]{6}$/);
|
||||
const photoDataUrlSchema = z
|
||||
.string()
|
||||
.regex(/^data:image\/(?:png|jpeg|jpg|webp|gif);base64,[A-Za-z0-9+/=]+$/)
|
||||
.max(1_500_000);
|
||||
const photoUrlSchema = z.string().trim().url().max(2000);
|
||||
|
||||
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('')),
|
||||
});
|
||||
|
||||
const switchWorkspaceSchema = z.object({
|
||||
workspaceId: z.coerce.number().int().positive(),
|
||||
});
|
||||
|
||||
const workspaceTypeSchema = z.enum(['standard', 'rescue']);
|
||||
const workspaceRoleSchema = z.enum(['owner', 'assistant', 'caregiver', 'viewer']);
|
||||
const billingPlanSchema = z.enum(['household_basic', 'household_plus', 'household_macaw', 'household_hyacinth_macaw']);
|
||||
const billingIntervalSchema = z.enum(['monthly', 'yearly']);
|
||||
const integrationTokenScopeSchema = z.enum(['read_only', 'read_write']);
|
||||
const birdGenderSchema = z.enum(['unknown', 'male', 'female', 'male_dna', 'female_dna']);
|
||||
const rescueVerificationStatusSchema = z.enum(['pending', 'approved', 'rejected']);
|
||||
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('')),
|
||||
});
|
||||
|
||||
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(),
|
||||
});
|
||||
|
||||
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(),
|
||||
});
|
||||
|
||||
const workspaceMemberSchema = z.object({
|
||||
name: z.string().trim().min(1).max(160),
|
||||
email: z.string().trim().email().max(255),
|
||||
role: workspaceRoleSchema,
|
||||
});
|
||||
|
||||
const flockTransferSchema = z.object({
|
||||
destinationOwnerEmail: z.string().trim().email().max(255),
|
||||
});
|
||||
|
||||
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('')),
|
||||
});
|
||||
|
||||
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()
|
||||
.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(''));
|
||||
|
||||
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();
|
||||
|
||||
const locationSearchSchema = z.object({
|
||||
q: z.string().trim().min(3).max(120),
|
||||
});
|
||||
|
||||
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(),
|
||||
});
|
||||
|
||||
const memorializeBirdSchema = z.object({
|
||||
memorializedOn: dateStringSchema,
|
||||
memorialNote: z.string().trim().max(1000).optional().or(z.literal('')),
|
||||
notifyOnMemorialDay: z.boolean().optional(),
|
||||
});
|
||||
|
||||
const memorialReminderPreferenceSchema = z.object({
|
||||
notifyOnMemorialDay: z.boolean(),
|
||||
});
|
||||
|
||||
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.',
|
||||
);
|
||||
|
||||
type VerifiedLocationDetailsInput = z.infer<typeof verifiedLocationDetailsSchema>;
|
||||
|
||||
const normalizeVerifiedLocationDetails = (value: VerifiedLocationDetailsInput) => {
|
||||
@@ -466,57 +351,6 @@ const normalizeMapboxLocationFeature = (feature: MapboxGeocodeFeature): Verified
|
||||
});
|
||||
};
|
||||
|
||||
const weightSchema = z.object({
|
||||
weightGrams: z.coerce.number().positive().max(10000),
|
||||
recordedOn: dateStringSchema,
|
||||
notes: z.string().trim().max(280).optional().or(z.literal('')),
|
||||
});
|
||||
|
||||
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('')),
|
||||
});
|
||||
|
||||
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'],
|
||||
});
|
||||
|
||||
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('')),
|
||||
});
|
||||
|
||||
const flockNoteSchema = z.object({
|
||||
birdId: z.string().uuid().optional().nullable().or(z.literal('')),
|
||||
body: z.string().trim().min(1).max(5000),
|
||||
});
|
||||
|
||||
const integrationTokenCreateSchema = z.object({
|
||||
name: z.string().trim().min(1).max(160),
|
||||
scope: integrationTokenScopeSchema.default('read_write'),
|
||||
@@ -978,6 +812,7 @@ const oauthProviders = {
|
||||
};
|
||||
|
||||
app.disable('x-powered-by');
|
||||
mountApiDocs(app);
|
||||
app.use(helmet({ crossOriginResourcePolicy: false }));
|
||||
app.use(
|
||||
cors({
|
||||
@@ -1340,12 +1175,14 @@ const sendMagicLink = async ({
|
||||
'',
|
||||
'This link expires in 15 minutes and can only be used once.',
|
||||
].join('\n'),
|
||||
html: `
|
||||
<p>Hi ${name || 'there'},</p>
|
||||
...await buildEmailLayout({ eyebrow: 'Sign in', headline: 'Your FlockPal sign-in link',
|
||||
contentHtml: `
|
||||
<p>Hi ${escapeHtml(name || 'there')},</p>
|
||||
<p>Use this secure link to sign in to FlockPal:</p>
|
||||
<p><a href="${magicLinkUrl}">Sign in to FlockPal</a></p>
|
||||
<p>This link expires in 15 minutes and can only be used once.</p>
|
||||
`,
|
||||
`,
|
||||
action: { url: magicLinkUrl, label: 'Sign in to FlockPal' },
|
||||
}),
|
||||
});
|
||||
|
||||
return {
|
||||
@@ -1416,27 +1253,6 @@ const getMilestoneYearCount = (reminder: BirdMilestoneReminderCandidateRow) => {
|
||||
return Number.isFinite(sourceYear) ? Math.max(0, reminder.reminder_year - sourceYear) : 0;
|
||||
};
|
||||
|
||||
const getFlockPalLogoAttachment = () => {
|
||||
const logoPath = path.join(process.cwd(), 'assets', 'flockpal-logo.png');
|
||||
|
||||
if (!existsSync(logoPath)) {
|
||||
console.warn(`Unable to load FlockPal email logo from ${logoPath}`);
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
filename: 'flockpal-logo.png',
|
||||
path: logoPath,
|
||||
cid: 'flockpal-logo',
|
||||
contentDisposition: 'inline' as const,
|
||||
};
|
||||
};
|
||||
|
||||
const getEmailTrackPatternDataUrl = () => {
|
||||
const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="680" height="188" viewBox="0 0 680 188"><defs><linearGradient id="wash" x1="0" y1="0" x2="1" y2="1"><stop offset="0" stop-color="#fef5e7"/><stop offset=".52" stop-color="#e9ddba"/><stop offset="1" stop-color="#d9eadf"/></linearGradient><symbol id="track" viewBox="0 0 160 160"><rect x="66" y="12" width="28" height="136" rx="14" transform="rotate(30 80 80)"/><rect x="66" y="12" width="28" height="136" rx="14" transform="rotate(-30 80 80)"/></symbol></defs><rect width="680" height="188" fill="url(#wash)"/><g opacity=".68"><use href="#track" x="20" y="16" width="88" height="88" fill="#5bb3b7" transform="rotate(-12 64 60)"/><use href="#track" x="126" y="74" width="78" height="78" fill="#7eb773" transform="rotate(18 165 113)"/><use href="#track" x="232" y="20" width="104" height="104" fill="#f3a24a" transform="rotate(-26 284 72)"/><use href="#track" x="378" y="72" width="86" height="86" fill="#898b93" transform="rotate(28 421 115)"/><use href="#track" x="492" y="18" width="98" height="98" fill="#b9c945" transform="rotate(-18 541 67)"/><use href="#track" x="592" y="84" width="66" height="66" fill="#5bb3b7" transform="rotate(34 625 117)"/></g><g opacity=".32"><use href="#track" x="66" y="112" width="46" height="46" fill="#f3a24a" transform="rotate(36 89 135)"/><use href="#track" x="190" y="122" width="42" height="42" fill="#5bb3b7" transform="rotate(-20 211 143)"/><use href="#track" x="344" y="18" width="44" height="44" fill="#7eb773" transform="rotate(18 366 40)"/><use href="#track" x="474" y="126" width="48" height="48" fill="#f3a24a" transform="rotate(-34 498 150)"/><use href="#track" x="626" y="18" width="42" height="42" fill="#898b93" transform="rotate(22 647 39)"/></g></svg>`;
|
||||
return `data:image/svg+xml,${encodeURIComponent(svg)}`;
|
||||
};
|
||||
|
||||
const parseDataImage = (dataUrl: string) => {
|
||||
const match = /^data:(image\/[a-zA-Z0-9.+-]+);base64,(.+)$/.exec(dataUrl);
|
||||
if (!match) {
|
||||
@@ -1581,22 +1397,6 @@ const loadBirdReportPhotoBuffer = async (bird: BirdRow) => {
|
||||
return Buffer.from(await imageResponse.arrayBuffer());
|
||||
};
|
||||
|
||||
const getDefaultBirdPhotoAttachment = () => {
|
||||
const defaultPhotoPath = path.join(process.cwd(), 'assets', 'yoda-default.png');
|
||||
|
||||
if (!existsSync(defaultPhotoPath)) {
|
||||
console.warn(`Unable to load default bird photo from ${defaultPhotoPath}`);
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
filename: 'yoda-default.png',
|
||||
path: defaultPhotoPath,
|
||||
cid: 'flockpal-default-bird-photo',
|
||||
contentDisposition: 'inline' as const,
|
||||
};
|
||||
};
|
||||
|
||||
const sendRescueStatusNotification = async ({
|
||||
workspace,
|
||||
ownerEmail,
|
||||
@@ -1646,7 +1446,8 @@ const sendRescueStatusNotification = async ({
|
||||
to: rescueStatusNotificationEmail,
|
||||
subject,
|
||||
text: lines.join('\n'),
|
||||
html: `
|
||||
...await buildEmailLayout({ eyebrow: 'Rescue status', headline: 'Rescue flock update',
|
||||
contentHtml: `
|
||||
<p>A rescue flock was ${eventLabel}.</p>
|
||||
<ul>
|
||||
<li><strong>Rescue flock:</strong> ${escapedWorkspaceName}</li>
|
||||
@@ -1656,7 +1457,9 @@ const sendRescueStatusNotification = async ({
|
||||
<li><strong>Flock ID:</strong> ${workspace.id}</li>
|
||||
</ul>
|
||||
${escapedNote ? `<p><strong>Note:</strong> ${escapedNote}</p>` : ''}
|
||||
`,
|
||||
`,
|
||||
action: { url: frontendBaseUrl, label: 'Open FlockPal' },
|
||||
}),
|
||||
});
|
||||
|
||||
return { delivered: true };
|
||||
@@ -1795,13 +1598,15 @@ const issueBirdTransferInvite = async ({
|
||||
to: email,
|
||||
subject,
|
||||
text,
|
||||
html: `
|
||||
...await buildEmailLayout({ eyebrow: 'Bird transfer', headline: 'A bird is joining your flock',
|
||||
contentHtml: `
|
||||
<p>Hi there,</p>
|
||||
<p><strong>${escapeHtml(sourceWorkspaceName)}</strong> wants to transfer <strong>${escapeHtml(birdName)}</strong> to your FlockPal account.</p>
|
||||
<p>Use this secure invite link to sign in or create your account. FlockPal will automatically create your receiving flock and complete any pending bird transfers for this email.</p>
|
||||
<p><a href="${magicLinkUrl}">Accept bird transfer in FlockPal</a></p>
|
||||
<p>This link expires in 15 minutes and can only be used once.</p>
|
||||
`,
|
||||
`,
|
||||
action: { url: magicLinkUrl, label: 'Accept bird transfer' },
|
||||
}),
|
||||
});
|
||||
|
||||
return {
|
||||
@@ -1857,7 +1662,8 @@ const sendLostBirdReportNotification = async ({
|
||||
replyTo: emptyToNull(report.finderEmail) ?? undefined,
|
||||
subject,
|
||||
text: lines.join('\n'),
|
||||
html: `
|
||||
...await buildEmailLayout({ eyebrow: 'Found bird report', headline: 'A possible match for your bird',
|
||||
contentHtml: `
|
||||
<p>A possible found bird report was submitted for <strong>${escapeHtml(bird.name)}</strong>.</p>
|
||||
<ul>
|
||||
<li><strong>Band ID:</strong> ${escapeHtml(bird.tag_id ?? 'Not recorded')}</li>
|
||||
@@ -1869,7 +1675,9 @@ const sendLostBirdReportNotification = async ({
|
||||
<li><strong>Message:</strong> ${escapeHtml(message)}</li>
|
||||
</ul>
|
||||
<p>FlockPal does not verify found bird reports. Please use care before sharing personal information or arranging a pickup.</p>
|
||||
`,
|
||||
`,
|
||||
action: { url: frontendBaseUrl, label: 'Open FlockPal' },
|
||||
}),
|
||||
});
|
||||
|
||||
return { delivered: true };
|
||||
@@ -1945,7 +1753,7 @@ const buildMedicationReminderCopy = (reminder: MedicationReminderCandidateRow) =
|
||||
return {
|
||||
subject: `${reminder.medication_name} reminder for ${reminder.name}`,
|
||||
eyebrow: 'Medication Reminder',
|
||||
headline: `${slotLabel} time for ${reminder.name}`,
|
||||
headline: `Medication time for ${reminder.name}`,
|
||||
intro: `${reminder.name} is due for ${reminder.medication_name} at ${doseTime}.`,
|
||||
body: `Dose: ${reminder.dosage}${route}.`,
|
||||
detailLabel: `${slotLabel} at ${doseTime}`,
|
||||
@@ -1966,32 +1774,6 @@ const sendBirdMilestoneReminderNotification = async ({
|
||||
}
|
||||
|
||||
const copy = buildBirdMilestoneReminderCopy(reminder);
|
||||
const attachments: NonNullable<SendMailOptions['attachments']> = [];
|
||||
const logoAttachment = getFlockPalLogoAttachment();
|
||||
const trackPatternDataUrl = getEmailTrackPatternDataUrl();
|
||||
const uploadedBirdPhoto = reminder.photo_data_url ? parseDataImage(reminder.photo_data_url) : null;
|
||||
const defaultBirdPhoto = uploadedBirdPhoto ? null : getDefaultBirdPhotoAttachment();
|
||||
const birdPhotoCid = uploadedBirdPhoto ? 'bird-photo' : defaultBirdPhoto ? defaultBirdPhoto.cid : '';
|
||||
|
||||
if (logoAttachment) {
|
||||
attachments.push(logoAttachment);
|
||||
}
|
||||
|
||||
if (uploadedBirdPhoto) {
|
||||
attachments.push({
|
||||
filename: `${reminder.name.replace(/[^a-z0-9_-]+/gi, '-').toLowerCase() || 'bird'}-photo`,
|
||||
content: uploadedBirdPhoto.content,
|
||||
contentType: uploadedBirdPhoto.contentType,
|
||||
cid: birdPhotoCid,
|
||||
contentDisposition: 'inline',
|
||||
});
|
||||
} else if (defaultBirdPhoto) {
|
||||
attachments.push(defaultBirdPhoto);
|
||||
}
|
||||
|
||||
const birdPhotoHtml = birdPhotoCid
|
||||
? `<img src="cid:${birdPhotoCid}" alt="${escapeHtml(reminder.name)}" style="display: block; width: 148px; height: 148px; border-radius: 28px; object-fit: cover; border: 4px solid #fff8ef; box-shadow: 0 14px 30px rgba(38, 51, 49, 0.18);" />`
|
||||
: `<div style="display: grid; place-items: center; width: 148px; height: 148px; border-radius: 28px; background: linear-gradient(135deg, #fff8ef, #eaf7ef); border: 4px solid #fff8ef; box-shadow: 0 14px 30px rgba(38, 51, 49, 0.18); color: #238a5a; font-size: 64px; font-weight: 800;">${escapeHtml(reminder.name.slice(0, 1).toUpperCase())}</div>`;
|
||||
const lines = [
|
||||
copy.headline,
|
||||
'',
|
||||
@@ -2016,43 +1798,18 @@ const sendBirdMilestoneReminderNotification = async ({
|
||||
bcc: uniqueRecipients,
|
||||
subject: copy.subject,
|
||||
text: lines.join('\n'),
|
||||
attachments,
|
||||
html: `
|
||||
<div style="margin: 0; padding: 28px; background-color: #fef5e7; background-image: url('${trackPatternDataUrl}'), radial-gradient(circle at 14% 10%, rgba(222, 124, 58, 0.24), transparent 22%), radial-gradient(circle at 82% 12%, rgba(53, 136, 110, 0.22), transparent 20%), linear-gradient(180deg, #fef5e7 0%, #e9ddba 46%, #d9eadf 100%); background-repeat: repeat, no-repeat, no-repeat, no-repeat; font-family: Arial, sans-serif; color: #1f2a2a; line-height: 1.6;">
|
||||
<div style="max-width: 680px; margin: 0 auto 18px;">
|
||||
<img src="${trackPatternDataUrl}" alt="" style="display: block; width: 100%; max-width: 680px; height: auto; border-radius: 26px;" />
|
||||
</div>
|
||||
<div style="max-width: 680px; margin: 0 auto; overflow: hidden; border-radius: 30px; background-color: #e7f4e9; background-image: linear-gradient(135deg, rgba(255, 255, 255, 0.44), transparent 42%), linear-gradient(180deg, rgba(235, 247, 237, 0.98), rgba(211, 235, 220, 0.96)); border: 1px solid rgba(53, 129, 98, 0.34); box-shadow: 0 22px 44px rgba(89, 48, 42, 0.14);">
|
||||
<div style="padding: 24px 28px; background-color: #edf8ef; background-image: linear-gradient(135deg, rgba(255, 255, 255, 0.46), transparent 46%), linear-gradient(180deg, rgba(242, 250, 243, 0.98), rgba(220, 241, 226, 0.94)); border-bottom: 1px solid rgba(53, 129, 98, 0.18);">
|
||||
${
|
||||
logoAttachment
|
||||
? '<img src="cid:flockpal-logo" alt="FlockPal" style="display: block; width: 180px; max-width: 72%; height: auto;" />'
|
||||
: '<strong style="display: block; color: #238a5a; font-size: 22px;">FlockPal</strong>'
|
||||
}
|
||||
</div>
|
||||
<div style="padding: 30px 28px;">
|
||||
<table role="presentation" width="100%" cellspacing="0" cellpadding="0" style="border-collapse: collapse;">
|
||||
<tr>
|
||||
<td style="vertical-align: top; padding: 0 24px 20px 0; width: 160px;">
|
||||
${birdPhotoHtml}
|
||||
</td>
|
||||
<td style="vertical-align: top; padding: 0 0 20px;">
|
||||
<h1 style="margin: 0 0 12px; color: #1f2a2a; font-size: 30px; line-height: 1.12;">${escapeHtml(copy.headline)}</h1>
|
||||
<p style="margin: 0; color: #63562d; font-size: 17px;">${escapeHtml(copy.intro)}</p>
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
<p style="margin: 4px 0 18px; font-size: 16px;">${escapeHtml(copy.body)}</p>
|
||||
<p style="margin: 0;">
|
||||
<a href="${frontendBaseUrl}" style="display: inline-block; padding: 12px 18px; border-radius: 999px; background: linear-gradient(135deg, #238a5a, #2f8f98); color: #ffffff; text-decoration: none; font-weight: 700; box-shadow: 0 12px 24px rgba(72, 97, 62, 0.16);">Open FlockPal</a>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<div style="max-width: 680px; margin: 18px auto 0;">
|
||||
<img src="${trackPatternDataUrl}" alt="" style="display: block; width: 100%; max-width: 680px; height: auto; border-radius: 26px;" />
|
||||
</div>
|
||||
</div>
|
||||
`,
|
||||
...await buildEmailLayout({
|
||||
bird: reminder,
|
||||
eyebrow: copy.eyebrow,
|
||||
headline: copy.headline,
|
||||
preheader: copy.intro,
|
||||
contentHtml: `<p style="margin:0 0 16px;font-size:16px;">${escapeHtml(copy.intro)}</p>
|
||||
<p>${escapeHtml(copy.body)}</p>
|
||||
<p><strong>${escapeHtml(reminder.name)}</strong> · ${escapeHtml(reminder.species)}</p>
|
||||
<p>${escapeHtml(`${copy.eventName}: ${copy.milestoneLabel}`)}</p>
|
||||
`,
|
||||
action: { url: frontendBaseUrl, label: 'Open FlockPal' },
|
||||
}),
|
||||
});
|
||||
|
||||
return { delivered: true };
|
||||
@@ -2072,35 +1829,6 @@ const sendMedicationReminderNotification = async ({
|
||||
}
|
||||
|
||||
const copy = buildMedicationReminderCopy(reminder);
|
||||
const attachments: NonNullable<SendMailOptions['attachments']> = [];
|
||||
const logoAttachment = getFlockPalLogoAttachment();
|
||||
const trackPatternDataUrl = getEmailTrackPatternDataUrl();
|
||||
const uploadedBirdPhoto = reminder.photo_data_url ? parseDataImage(reminder.photo_data_url) : null;
|
||||
const defaultBirdPhoto = uploadedBirdPhoto ? null : getDefaultBirdPhotoAttachment();
|
||||
const birdPhotoCid = uploadedBirdPhoto ? 'bird-photo' : defaultBirdPhoto ? defaultBirdPhoto.cid : '';
|
||||
|
||||
if (logoAttachment) {
|
||||
attachments.push(logoAttachment);
|
||||
}
|
||||
|
||||
if (uploadedBirdPhoto) {
|
||||
attachments.push({
|
||||
filename: `${reminder.name.replace(/[^a-z0-9_-]+/gi, '-').toLowerCase() || 'bird'}-photo`,
|
||||
content: uploadedBirdPhoto.content,
|
||||
contentType: uploadedBirdPhoto.contentType,
|
||||
cid: birdPhotoCid,
|
||||
contentDisposition: 'inline',
|
||||
});
|
||||
} else if (defaultBirdPhoto) {
|
||||
attachments.push(defaultBirdPhoto);
|
||||
}
|
||||
|
||||
const birdPhotoHtml = birdPhotoCid
|
||||
? `<img src="cid:${birdPhotoCid}" alt="${escapeHtml(reminder.name)}" style="display: block; width: 148px; height: 148px; border-radius: 28px; object-fit: cover; border: 4px solid #fff8ef; box-shadow: 0 14px 30px rgba(38, 51, 49, 0.18);" />`
|
||||
: `<div style="display: grid; place-items: center; width: 148px; height: 148px; border-radius: 28px; background: linear-gradient(135deg, #fff8ef, #eaf7ef); border: 4px solid #fff8ef; box-shadow: 0 14px 30px rgba(38, 51, 49, 0.18); color: #238a5a; font-size: 64px; font-weight: 800;">${escapeHtml(reminder.name.slice(0, 1).toUpperCase())}</div>`;
|
||||
const medicationNotesHtml = reminder.medication_notes
|
||||
? `<p style="margin: 0 0 18px; font-size: 15px; color: #63562d;"><strong>Medication notes:</strong> ${escapeHtml(reminder.medication_notes)}</p>`
|
||||
: '';
|
||||
const lines = [
|
||||
copy.headline,
|
||||
'',
|
||||
@@ -2127,46 +1855,18 @@ const sendMedicationReminderNotification = async ({
|
||||
bcc: uniqueRecipients,
|
||||
subject: copy.subject,
|
||||
text: lines.join('\n'),
|
||||
attachments,
|
||||
html: `
|
||||
<div style="margin: 0; padding: 28px; background-color: #fef5e7; background-image: url('${trackPatternDataUrl}'), radial-gradient(circle at 14% 10%, rgba(222, 124, 58, 0.24), transparent 22%), radial-gradient(circle at 82% 12%, rgba(53, 136, 110, 0.22), transparent 20%), linear-gradient(180deg, #fef5e7 0%, #e9ddba 46%, #d9eadf 100%); background-repeat: repeat, no-repeat, no-repeat, no-repeat; font-family: Arial, sans-serif; color: #1f2a2a; line-height: 1.6;">
|
||||
<div style="max-width: 680px; margin: 0 auto 18px;">
|
||||
<img src="${trackPatternDataUrl}" alt="" style="display: block; width: 100%; max-width: 680px; height: auto; border-radius: 26px;" />
|
||||
</div>
|
||||
<div style="max-width: 680px; margin: 0 auto; overflow: hidden; border-radius: 30px; background-color: #e7f4e9; background-image: linear-gradient(135deg, rgba(255, 255, 255, 0.44), transparent 42%), linear-gradient(180deg, rgba(235, 247, 237, 0.98), rgba(211, 235, 220, 0.96)); border: 1px solid rgba(53, 129, 98, 0.34); box-shadow: 0 22px 44px rgba(89, 48, 42, 0.14);">
|
||||
<div style="padding: 24px 28px; background-color: #edf8ef; background-image: linear-gradient(135deg, rgba(255, 255, 255, 0.46), transparent 46%), linear-gradient(180deg, rgba(242, 250, 243, 0.98), rgba(220, 241, 226, 0.94)); border-bottom: 1px solid rgba(53, 129, 98, 0.18);">
|
||||
${
|
||||
logoAttachment
|
||||
? '<img src="cid:flockpal-logo" alt="FlockPal" style="display: block; width: 180px; max-width: 72%; height: auto;" />'
|
||||
: '<strong style="display: block; color: #238a5a; font-size: 22px;">FlockPal</strong>'
|
||||
}
|
||||
</div>
|
||||
<div style="padding: 30px 28px;">
|
||||
<table role="presentation" width="100%" cellspacing="0" cellpadding="0" style="border-collapse: collapse;">
|
||||
<tr>
|
||||
<td style="vertical-align: top; padding: 0 24px 20px 0; width: 160px;">
|
||||
${birdPhotoHtml}
|
||||
</td>
|
||||
<td style="vertical-align: top; padding: 0 0 20px;">
|
||||
<p style="margin: 0 0 8px; color: #238a5a; font-size: 13px; font-weight: 800; text-transform: uppercase; letter-spacing: 0.08em;">${escapeHtml(copy.eyebrow)}</p>
|
||||
<h1 style="margin: 0 0 12px; color: #1f2a2a; font-size: 30px; line-height: 1.12;">${escapeHtml(copy.headline)}</h1>
|
||||
<p style="margin: 0; color: #63562d; font-size: 17px;">${escapeHtml(copy.intro)}</p>
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
<p style="margin: 4px 0 10px; font-size: 16px;">${escapeHtml(copy.body)}</p>
|
||||
<p style="margin: 0 0 18px; font-size: 15px; color: #63562d;"><strong>Schedule:</strong> ${escapeHtml(copy.detailLabel)}</p>
|
||||
${medicationNotesHtml}
|
||||
<p style="margin: 0;">
|
||||
<a href="${frontendBaseUrl}" style="display: inline-block; padding: 12px 18px; border-radius: 999px; background: linear-gradient(135deg, #238a5a, #2f8f98); color: #ffffff; text-decoration: none; font-weight: 700; box-shadow: 0 12px 24px rgba(72, 97, 62, 0.16);">Open FlockPal</a>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<div style="max-width: 680px; margin: 18px auto 0;">
|
||||
<img src="${trackPatternDataUrl}" alt="" style="display: block; width: 100%; max-width: 680px; height: auto; border-radius: 26px;" />
|
||||
</div>
|
||||
</div>
|
||||
`,
|
||||
...await buildEmailLayout({
|
||||
bird: reminder,
|
||||
eyebrow: copy.eyebrow,
|
||||
headline: copy.headline,
|
||||
preheader: copy.intro,
|
||||
contentHtml: `<p style="margin:0 0 16px;font-size:16px;">${escapeHtml(copy.intro)}</p>
|
||||
<p>${escapeHtml(copy.body)}</p>
|
||||
<p><strong>${escapeHtml(reminder.name)}</strong> · ${escapeHtml(reminder.species)}</p>
|
||||
<p>${escapeHtml(copy.detailLabel)}</p>
|
||||
${reminder.medication_notes ? `<p><strong>Medication notes:</strong> ${escapeHtml(reminder.medication_notes)}</p>` : ''}`,
|
||||
action: { url: frontendBaseUrl, label: 'Open FlockPal' },
|
||||
}),
|
||||
});
|
||||
|
||||
return { delivered: true };
|
||||
@@ -2216,6 +1916,17 @@ export const runBirdMilestoneReminders = async (runDate = getDateInTimeZone()) =
|
||||
};
|
||||
};
|
||||
|
||||
export const sendWeightReminderNotification = async (reminders: WeightReminder[]): Promise<boolean> => {
|
||||
if (!mailTransport || !reminders.length) return false;
|
||||
const first = reminders[0];
|
||||
const result = await mailTransport.sendMail({
|
||||
from: smtpFromName ? `"${smtpFromName}" <${smtpFromEmail}>` : smtpFromEmail,
|
||||
to: first.recipient,
|
||||
...await buildWeightReminderEmail(reminders, frontendBaseUrl),
|
||||
});
|
||||
return result.accepted.length > 0;
|
||||
};
|
||||
|
||||
export const runMedicationReminders = async (runDate = getDateInTimeZone(), currentTime = getTimeInTimeZone()) => {
|
||||
const reminders = await listDueMedicationReminders(runDate, currentTime);
|
||||
let sent = 0;
|
||||
@@ -3636,6 +3347,27 @@ app.get('/api/locations/search', requireAuth, locationSearchLimiter, async (req:
|
||||
}
|
||||
});
|
||||
|
||||
app.get('/api/birds/unassigned-match', requireAuth, requireWorkspaceRole(['owner', 'assistant', 'caregiver']), async (req: Request, res: Response, next: NextFunction) => {
|
||||
const parsed = unassignedBirdMatchSchema.safeParse(req.query);
|
||||
if (!parsed.success) { res.status(400).json({ error: 'Enter a known band ID.' }); return; }
|
||||
try {
|
||||
res.json({ available: await hasUnassignedBird(parsed.data.tagId) });
|
||||
} catch (error) { next(error); }
|
||||
});
|
||||
|
||||
app.post('/api/birds/claim', requireAuth, requireWriteAccess, requireWorkspaceRole(['owner', 'assistant', 'caregiver']), async (req: Request, res: Response, next: NextFunction) => {
|
||||
const parsed = claimBirdSchema.safeParse(req.body);
|
||||
if (!parsed.success) { res.status(400).json({ error: 'A known band ID and confirmation to bring in existing history are required.' }); return; }
|
||||
try {
|
||||
const birdId = await claimUnassignedBird(parsed.data.tagId, req.auth!.workspace.id, req.auth!.user.id);
|
||||
if (!birdId) { res.status(409).json({ error: 'No unassigned bird is available with that band ID. It may already have joined a flock.' }); return; }
|
||||
const bird = await getBirdById(birdId, req.auth!.workspace.id);
|
||||
if (!bird) { res.status(409).json({ error: 'The bird is no longer in this flock. Refresh the flock to continue.' }); return; }
|
||||
await writeAuditLog(req.auth!, 'bird.claimed', 'bird', bird.id, bird.name, { tagId: bird.tag_id });
|
||||
res.status(200).json({ bird: normalizeBird(bird), historyImported: true });
|
||||
} catch (error) { next(error); }
|
||||
});
|
||||
|
||||
app.get('/api/birds', requireAuth, async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const [birds, memorializedBirds] = await Promise.all([
|
||||
@@ -3784,6 +3516,11 @@ app.post('/api/birds', requireAuth, requireWriteAccess, requireWorkspaceRole(['o
|
||||
let uploadedObjectKeyToCleanup: string | null = null;
|
||||
|
||||
try {
|
||||
const tagId = normalizeBandId(parsed.data.tagId);
|
||||
if (tagId && await hasUnassignedBird(tagId)) {
|
||||
res.status(409).json({ code: 'bird_history_available', error: 'An unassigned bird has this band ID. Confirm adding the existing bird with its history instead of creating a new profile.' });
|
||||
return;
|
||||
}
|
||||
const birdId = crypto.randomUUID();
|
||||
const photoStorage = await resolveBirdPhotoStorage({
|
||||
birdId,
|
||||
@@ -4240,16 +3977,15 @@ app.delete('/api/birds/:birdId', requireAuth, requireWriteAccess, requireWorkspa
|
||||
return;
|
||||
}
|
||||
|
||||
const deleted = await deleteBird(req.params.birdId, req.auth!.workspace.id);
|
||||
const removed = await removeBirdFromFlock(req.params.birdId, req.auth!.workspace.id, req.auth!.user.id);
|
||||
|
||||
if (!deleted) {
|
||||
res.status(404).json({ error: 'Bird not found.' });
|
||||
if (!removed) {
|
||||
res.status(404).json({ error: 'Bird not found or no longer removable.' });
|
||||
return;
|
||||
}
|
||||
|
||||
await writeAuditLog(req.auth!, 'bird.deleted', 'bird', bird.id, bird.name);
|
||||
await writeAuditLog(req.auth!, 'bird.removed_from_flock', 'bird', bird.id, bird.name);
|
||||
res.status(204).send();
|
||||
await deleteBirdPhotoObjectIfNeeded(bird.photo_object_key);
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
@@ -4326,6 +4062,77 @@ app.patch('/api/birds/:birdId/memorial-reminders', requireAuth, requireWriteAcce
|
||||
}
|
||||
});
|
||||
|
||||
// Behavior types are flock-scoped; occurrences follow their bird across flock transfers.
|
||||
app.get('/api/birds/:birdId/behavior-types', requireAuth, async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
if (!z.string().uuid().safeParse(req.params.birdId).success) { res.status(400).json({ error: 'Invalid bird ID.' }); return; }
|
||||
const bird = await getBirdById(req.params.birdId, req.auth!.workspace.id);
|
||||
if (!bird) { res.status(404).json({ error: 'Bird not found.' }); return; }
|
||||
res.json({ behaviorTypes: await listBehaviorTypes(req.auth!.workspace.id, bird.id) });
|
||||
} catch (error) { next(error); }
|
||||
});
|
||||
app.post('/api/birds/:birdId/behavior-types', requireAuth, requireWriteAccess, requireWorkspaceRole(['owner', 'assistant', 'caregiver']), async (req: Request, res: Response, next: NextFunction) => {
|
||||
const parsed = behaviorTypeSchema.safeParse(req.body);
|
||||
if (!parsed.success || !z.string().uuid().safeParse(req.params.birdId).success) { res.status(400).json({ error: 'Invalid behavior type payload.' }); return; }
|
||||
try {
|
||||
const bird = await getBirdById(req.params.birdId, req.auth!.workspace.id);
|
||||
if (!bird) { res.status(404).json({ error: 'Bird not found.' }); return; }
|
||||
if (!ensureBirdWritable(bird, res)) return;
|
||||
const behaviorType = await createBehaviorType(req.auth!.workspace.id, parsed.data.name, parsed.data.description);
|
||||
await writeAuditLog(req.auth!, 'behavior_type.created', 'behavior_type', behaviorType.id, parsed.data.name);
|
||||
res.status(201).json({ behaviorType });
|
||||
} catch (error) { next(error); }
|
||||
});
|
||||
app.get('/api/birds/:birdId/behaviors', requireAuth, async (req: Request, res: Response, next: NextFunction) => {
|
||||
const parsed = behaviorRangeSchema.safeParse(req.query);
|
||||
if (!parsed.success || !z.string().uuid().safeParse(req.params.birdId).success) { res.status(400).json({ error: 'Invalid behavior date range or bird ID.' }); return; }
|
||||
try {
|
||||
const bird = await getBirdById(req.params.birdId, req.auth!.workspace.id);
|
||||
if (!bird) { res.status(404).json({ error: 'Bird not found.' }); return; }
|
||||
res.json({ occurrences: await listBehaviorOccurrences(bird.id, req.auth!.workspace.id, parsed.data.from, parsed.data.to, parsed.data.behaviorTypeId) });
|
||||
} catch (error) { next(error); }
|
||||
});
|
||||
app.post('/api/birds/:birdId/behaviors', requireAuth, requireWriteAccess, requireWorkspaceRole(['owner', 'assistant', 'caregiver']), async (req: Request, res: Response, next: NextFunction) => {
|
||||
if (!z.string().uuid().safeParse(req.params.birdId).success) { res.status(400).json({ error: 'Invalid ID.' }); return; }
|
||||
const parsed = behaviorOccurrenceSchema.safeParse(req.body);
|
||||
if (!parsed.success) { res.status(400).json({ error: 'Invalid behavior payload.', details: parsed.error.flatten() }); return; }
|
||||
try {
|
||||
const bird = await getBirdById(req.params.birdId, req.auth!.workspace.id);
|
||||
if (!bird) { res.status(404).json({ error: 'Bird not found.' }); return; }
|
||||
if (!ensureBirdWritable(bird, res)) return;
|
||||
const occurrence = await saveBehaviorOccurrence(bird.id, req.auth!.workspace.id, parsed.data);
|
||||
if (!occurrence) { res.status(404).json({ error: 'Occurrence or behavior type not found, or bird is no longer editable.' }); return; }
|
||||
await writeAuditLog(req.auth!, 'behavior.created', 'behavior_occurrence', occurrence.id, bird.name, { birdId: bird.id });
|
||||
res.status(201).json({ occurrence });
|
||||
} catch (error) { next(error); }
|
||||
});
|
||||
app.put('/api/birds/:birdId/behaviors/:occurrenceId', requireAuth, requireWriteAccess, requireWorkspaceRole(['owner', 'assistant', 'caregiver']), async (req: Request, res: Response, next: NextFunction) => {
|
||||
if (!z.string().uuid().safeParse(req.params.birdId).success || !z.string().uuid().safeParse(req.params.occurrenceId).success) { res.status(400).json({ error: 'Invalid ID.' }); return; }
|
||||
const parsed = behaviorOccurrenceSchema.safeParse(req.body);
|
||||
if (!parsed.success) { res.status(400).json({ error: 'Invalid behavior payload.', details: parsed.error.flatten() }); return; }
|
||||
try {
|
||||
const bird = await getBirdById(req.params.birdId, req.auth!.workspace.id);
|
||||
if (!bird) { res.status(404).json({ error: 'Bird not found.' }); return; }
|
||||
if (!ensureBirdWritable(bird, res)) return;
|
||||
const occurrence = await saveBehaviorOccurrence(bird.id, req.auth!.workspace.id, parsed.data, req.params.occurrenceId);
|
||||
if (!occurrence) { res.status(404).json({ error: 'Occurrence or behavior type not found, or bird is no longer editable.' }); return; }
|
||||
await writeAuditLog(req.auth!, 'behavior.updated', 'behavior_occurrence', occurrence.id, bird.name, { birdId: bird.id });
|
||||
res.status(200).json({ occurrence });
|
||||
} catch (error) { next(error); }
|
||||
});
|
||||
app.delete('/api/birds/:birdId/behaviors/:occurrenceId', requireAuth, requireWriteAccess, requireWorkspaceRole(['owner', 'assistant', 'caregiver']), async (req: Request, res: Response, next: NextFunction) => {
|
||||
if (!z.string().uuid().safeParse(req.params.birdId).success || !z.string().uuid().safeParse(req.params.occurrenceId).success) { res.status(400).json({ error: 'Invalid ID.' }); return; }
|
||||
try {
|
||||
const bird = await getBirdById(req.params.birdId, req.auth!.workspace.id);
|
||||
if (!bird) { res.status(404).json({ error: 'Bird not found.' }); return; }
|
||||
if (!ensureBirdWritable(bird, res)) return;
|
||||
const occurrence = await deleteBehaviorOccurrence(bird.id, req.auth!.workspace.id, req.params.occurrenceId);
|
||||
if (!occurrence) { res.status(404).json({ error: 'Occurrence or behavior type not found, or bird is no longer editable.' }); return; }
|
||||
await writeAuditLog(req.auth!, 'behavior.deleted', 'behavior_occurrence', occurrence.id, bird.name, { birdId: bird.id });
|
||||
res.status(204).send();
|
||||
} catch (error) { next(error); }
|
||||
});
|
||||
|
||||
app.get('/api/birds/:birdId/weights', requireAuth, async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const days = Math.min(Math.max(Number(req.query.days ?? 30), 1), 425);
|
||||
|
||||
Reference in new issue
Block a user