Merge branch 'dev'
# Conflicts: # backend/src/app.ts # backend/src/db/schema.ts # backend/src/queues/adoptionReportQueue.ts # backend/src/reports/adoptionReport.ts # backend/src/reports/adoptionReportJob.ts # backend/src/repositories/birdRepository.ts # backend/src/types.ts # frontend/src/App.tsx # frontend/src/index.css
This commit is contained in:
commit
3ba6410972
19 files changed
+2150
-992
No files matched your search
+482
-197
@@ -12,9 +12,8 @@ import nodemailer, { type SendMailOptions } from 'nodemailer';
|
||||
import Stripe from 'stripe';
|
||||
import { z } from 'zod';
|
||||
|
||||
import { db } from './db/client.js';
|
||||
import { ensureSchema } from './db/schema.js';
|
||||
import { adoptionReportQueueEvents, enqueueAdoptionReportJob, getAdoptionReportQueueCounts } from './queues/adoptionReportQueue.js';
|
||||
import { adoptionReportQueueEvents, enqueueAdoptionReportJob } from './queues/adoptionReportQueue.js';
|
||||
import { enqueueBirdMilestoneReminderJob, getBirdMilestoneReminderQueueCounts } from './queues/birdMilestoneReminderQueue.js';
|
||||
import { enqueueMedicationReminderJob, getMedicationReminderQueueCounts } from './queues/medicationReminderQueue.js';
|
||||
import {
|
||||
@@ -38,6 +37,7 @@ import {
|
||||
completePendingBirdTransfersForOwner,
|
||||
createBird,
|
||||
createBirdMilestoneReminderDelivery,
|
||||
createBirdTimelineEvent,
|
||||
createMedicationReminderDelivery,
|
||||
createBirdTransferCode,
|
||||
createMedicationForBird,
|
||||
@@ -51,8 +51,8 @@ import {
|
||||
getBirdById,
|
||||
getBirdByPublicProfileCode,
|
||||
getOpenBirdTransferCode,
|
||||
getOpenBirdTransferCodeForBird,
|
||||
listBirds,
|
||||
listBirdTimelineEvents,
|
||||
listDueBirdMilestoneReminders,
|
||||
listDueMedicationReminders,
|
||||
listMemorializedBirds,
|
||||
@@ -98,7 +98,6 @@ import {
|
||||
getMembershipForUser,
|
||||
getNextWorkspaceId,
|
||||
getWorkspaceById,
|
||||
getWorkspaceBirdCount,
|
||||
getWorkspaceTotalBirdCount,
|
||||
listOwnedWorkspacesByOwnerEmail,
|
||||
listRescueWorkspacesForAdmin,
|
||||
@@ -114,14 +113,16 @@ import {
|
||||
upsertWorkspaceMember,
|
||||
} from './repositories/workspaceRepository.js';
|
||||
import type {
|
||||
AuthContext,
|
||||
AuditLogEntryRow,
|
||||
BillingInterval,
|
||||
BillingPlan,
|
||||
BirdGender,
|
||||
AuthContext,
|
||||
AuditLogEntryRow,
|
||||
BillingInterval,
|
||||
BillingPlan,
|
||||
BirdGender,
|
||||
BirdMilestoneReminderCandidateRow,
|
||||
BirdRow,
|
||||
FlockNoteRow,
|
||||
BirdRow,
|
||||
BirdTimelineEventType,
|
||||
BirdTimelineEventRow,
|
||||
FlockNoteRow,
|
||||
IntegrationTokenRow,
|
||||
LostBirdMatchRow,
|
||||
MedicationAdministrationRow,
|
||||
@@ -270,6 +271,26 @@ const birdProfileListSchema = z
|
||||
.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('')),
|
||||
@@ -277,11 +298,14 @@ const birdSchema = z.object({
|
||||
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(),
|
||||
@@ -301,6 +325,146 @@ 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) => {
|
||||
if (!value) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const city = value.city?.trim() || null;
|
||||
const region = value.region?.trim() || null;
|
||||
const country = value.country?.trim() || null;
|
||||
const countryCode = value.countryCode?.trim().toUpperCase() || null;
|
||||
const latitude = typeof value.latitude === 'number' ? Number(value.latitude.toFixed(4)) : null;
|
||||
const longitude = typeof value.longitude === 'number' ? Number(value.longitude.toFixed(4)) : null;
|
||||
const precision = value.precision ?? (city ? 'city' : region ? 'region' : country ? 'country' : null);
|
||||
const label = value.label?.trim() || [city, region, country].filter(Boolean).join(', ') || null;
|
||||
const provider = value.provider ?? null;
|
||||
const providerPlaceId = value.providerPlaceId?.trim() || null;
|
||||
|
||||
if (!label && !city && !region && !country && !countryCode && latitude === null && longitude === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
label,
|
||||
city,
|
||||
region,
|
||||
country,
|
||||
countryCode,
|
||||
latitude,
|
||||
longitude,
|
||||
precision,
|
||||
provider,
|
||||
providerPlaceId,
|
||||
verifiedAt: new Date().toISOString(),
|
||||
};
|
||||
};
|
||||
|
||||
const formatVerifiedLocationLabel = (details: ReturnType<typeof normalizeVerifiedLocationDetails>) =>
|
||||
details ? details.label || [details.city, details.region, details.country].filter(Boolean).join(', ') || null : null;
|
||||
|
||||
type VerifiedLocationSearchResult = NonNullable<ReturnType<typeof normalizeVerifiedLocationDetails>>;
|
||||
|
||||
type MapboxGeocodeFeature = {
|
||||
id?: string;
|
||||
geometry?: {
|
||||
coordinates?: [number, number];
|
||||
};
|
||||
properties?: {
|
||||
mapbox_id?: string;
|
||||
feature_type?: string;
|
||||
name?: string;
|
||||
full_address?: string;
|
||||
place_formatted?: string;
|
||||
coordinates?: {
|
||||
longitude?: number;
|
||||
latitude?: number;
|
||||
};
|
||||
context?: {
|
||||
place?: { name?: string };
|
||||
locality?: { name?: string };
|
||||
region?: { name?: string; region_code?: string; region_code_full?: string };
|
||||
country?: { name?: string; country_code?: string };
|
||||
};
|
||||
};
|
||||
};
|
||||
|
||||
type MapboxGeocodeResponse = {
|
||||
features?: MapboxGeocodeFeature[];
|
||||
message?: string;
|
||||
};
|
||||
|
||||
const mapboxAccessToken = process.env.MAPBOX_ACCESS_TOKEN?.trim() ?? '';
|
||||
const allowedMapboxLocationTypes = new Set(['place', 'locality', 'region', 'country']);
|
||||
const mapboxLocationCache = new Map<string, { expiresAt: number; results: VerifiedLocationSearchResult[] }>();
|
||||
const mapboxLocationCacheTtlMs = 24 * 60 * 60 * 1000;
|
||||
|
||||
const getMapboxContextName = (feature: MapboxGeocodeFeature, key: 'place' | 'locality' | 'region' | 'country') =>
|
||||
feature.properties?.context?.[key]?.name?.trim() || null;
|
||||
|
||||
const normalizeMapboxLocationFeature = (feature: MapboxGeocodeFeature): VerifiedLocationSearchResult | null => {
|
||||
const properties = feature.properties;
|
||||
const featureType = properties?.feature_type;
|
||||
|
||||
if (!featureType || !allowedMapboxLocationTypes.has(featureType)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const name = properties.name?.trim() || null;
|
||||
const contextPlace = getMapboxContextName(feature, 'place');
|
||||
const contextLocality = getMapboxContextName(feature, 'locality');
|
||||
const contextRegion = getMapboxContextName(feature, 'region');
|
||||
const contextCountry = getMapboxContextName(feature, 'country');
|
||||
const city = featureType === 'place' || featureType === 'locality' ? name : contextPlace || contextLocality;
|
||||
const region = featureType === 'region' ? name : contextRegion;
|
||||
const country = featureType === 'country' ? name : contextCountry;
|
||||
const countryCode = properties.context?.country?.country_code?.trim().toUpperCase() || null;
|
||||
const longitude = properties.coordinates?.longitude ?? feature.geometry?.coordinates?.[0] ?? null;
|
||||
const latitude = properties.coordinates?.latitude ?? feature.geometry?.coordinates?.[1] ?? null;
|
||||
const label = [city, region, country].filter(Boolean).join(', ') || properties.full_address || properties.place_formatted || name || null;
|
||||
const precision = featureType === 'country' ? 'country' : featureType === 'region' ? 'region' : 'city';
|
||||
|
||||
if (!label || typeof latitude !== 'number' || typeof longitude !== 'number') {
|
||||
return null;
|
||||
}
|
||||
|
||||
return normalizeVerifiedLocationDetails({
|
||||
label,
|
||||
city: city ?? '',
|
||||
region: region ?? '',
|
||||
country: country ?? '',
|
||||
countryCode: countryCode ?? '',
|
||||
latitude,
|
||||
longitude,
|
||||
precision,
|
||||
provider: 'mapbox',
|
||||
providerPlaceId: properties.mapbox_id || feature.id || '',
|
||||
});
|
||||
};
|
||||
|
||||
const weightSchema = z.object({
|
||||
weightGrams: z.coerce.number().positive().max(10000),
|
||||
recordedOn: dateStringSchema,
|
||||
@@ -637,11 +801,14 @@ const normalizeBird = (row: BirdRow) => ({
|
||||
motivators: row.motivators,
|
||||
demotivators: row.demotivators,
|
||||
favoriteSnack: row.favorite_snack,
|
||||
locationLabel: row.location_label,
|
||||
locationDetails: row.location_details,
|
||||
vetClinicName: row.vet_clinic_name,
|
||||
vetClinicAddress: row.vet_clinic_address,
|
||||
vetAccountNumber: row.vet_account_number,
|
||||
vetDoctorName: row.vet_doctor_name,
|
||||
gender: row.gender,
|
||||
hatchDay: row.date_of_birth,
|
||||
dateOfBirth: row.date_of_birth,
|
||||
gotchaDay: row.gotcha_day,
|
||||
chartColor: row.chart_color,
|
||||
@@ -664,39 +831,13 @@ const normalizeBird = (row: BirdRow) => ({
|
||||
|
||||
const createBirdTransferCodeValue = () => crypto.randomBytes(12).toString('base64url');
|
||||
|
||||
const ensureOpenBirdTransferCode = async (birdId: string, sourceWorkspaceId: number, requestedByUserId: string) => {
|
||||
const existingTransferCode = await getOpenBirdTransferCodeForBird(birdId, sourceWorkspaceId);
|
||||
|
||||
if (existingTransferCode) {
|
||||
return existingTransferCode;
|
||||
}
|
||||
|
||||
for (let attempt = 0; attempt < 3; attempt += 1) {
|
||||
try {
|
||||
return await createBirdTransferCode({
|
||||
code: createBirdTransferCodeValue(),
|
||||
birdId,
|
||||
sourceWorkspaceId,
|
||||
requestedByUserId,
|
||||
});
|
||||
} catch (error) {
|
||||
if (typeof error === 'object' && error && 'code' in error && error.code === '23505' && attempt < 2) {
|
||||
continue;
|
||||
}
|
||||
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
};
|
||||
|
||||
const normalizePublicBirdProfile = (row: BirdRow) => ({
|
||||
id: row.id,
|
||||
workspaceId: row.workspace_id,
|
||||
name: row.name,
|
||||
favoriteSnack: row.favorite_snack,
|
||||
gender: row.gender,
|
||||
hatchDay: row.date_of_birth,
|
||||
dateOfBirth: row.date_of_birth,
|
||||
photoDataUrl: getBirdPhotoUrl(row),
|
||||
});
|
||||
@@ -771,6 +912,24 @@ const normalizeAuditLogEntry = (row: AuditLogEntryRow) => ({
|
||||
createdAt: row.created_at,
|
||||
});
|
||||
|
||||
const normalizeBirdTimelineEvent = (row: BirdTimelineEventRow) => ({
|
||||
id: row.id,
|
||||
birdId: row.bird_id,
|
||||
eventType: row.event_type,
|
||||
fromWorkspaceId: row.from_workspace_id,
|
||||
toWorkspaceId: row.to_workspace_id,
|
||||
fromWorkspaceName: row.from_workspace_name,
|
||||
toWorkspaceName: row.to_workspace_name,
|
||||
fromOwnerEmail: row.from_owner_email,
|
||||
toOwnerEmail: row.to_owner_email,
|
||||
locationLabel: row.location_label,
|
||||
locationDetails: row.location_details,
|
||||
note: row.note,
|
||||
eventDate: row.event_date,
|
||||
createdByUserId: row.created_by_user_id,
|
||||
createdAt: row.created_at,
|
||||
});
|
||||
|
||||
const normalizeIntegrationToken = (row: IntegrationTokenRow) => ({
|
||||
id: row.id,
|
||||
userId: row.user_id,
|
||||
@@ -847,6 +1006,13 @@ const lostBirdReportLimiter = rateLimit({
|
||||
legacyHeaders: false,
|
||||
message: { error: 'Too many found bird reports. Please try again later.' },
|
||||
});
|
||||
const locationSearchLimiter = rateLimit({
|
||||
windowMs: 15 * 60 * 1000,
|
||||
limit: 40,
|
||||
standardHeaders: true,
|
||||
legacyHeaders: false,
|
||||
message: { error: 'Too many location searches. Please try again later.' },
|
||||
});
|
||||
app.post('/api/billing/stripe/webhook', express.raw({ type: 'application/json' }), async (req: Request, res: Response) => {
|
||||
if (!stripeWebhookSecret) {
|
||||
res.status(503).json({ error: 'Stripe webhook is not configured.' });
|
||||
@@ -993,26 +1159,6 @@ const subscriptionAllowsWrite = (workspace: WorkspaceRow) => {
|
||||
return workspace.subscription_status === 'active' || workspace.subscription_status === 'trialing';
|
||||
};
|
||||
|
||||
const getBillingPlanBirdLimit = (billingPlan: BillingPlan) => {
|
||||
if (billingPlan === 'rescue_free') {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (billingPlan === 'household_basic') {
|
||||
return 4;
|
||||
}
|
||||
|
||||
if (billingPlan === 'household_plus') {
|
||||
return 10;
|
||||
}
|
||||
|
||||
if (billingPlan === 'household_macaw') {
|
||||
return 16;
|
||||
}
|
||||
|
||||
return null;
|
||||
};
|
||||
|
||||
const mapStripeSubscriptionStatus = (status: Stripe.Subscription.Status): SubscriptionStatus => {
|
||||
if (status === 'active' || status === 'trialing' || status === 'past_due' || status === 'canceled' || status === 'unpaid') {
|
||||
return status;
|
||||
@@ -1403,6 +1549,37 @@ const deleteBirdPhotoObjectIfNeeded = async (objectKey: string | null) => {
|
||||
}
|
||||
};
|
||||
|
||||
const loadBirdReportPhotoBuffer = async (bird: BirdRow) => {
|
||||
if (!bird.photo_object_key) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const s3Config = getS3ImageStorageConfig();
|
||||
|
||||
if (!s3Config) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const signedUrl = getSignedS3ObjectUrl({
|
||||
config: s3Config,
|
||||
objectKey: bird.photo_object_key,
|
||||
expiresInSeconds: 5 * 60,
|
||||
});
|
||||
const imageResponse = await fetch(signedUrl);
|
||||
|
||||
if (!imageResponse.ok) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const contentType = imageResponse.headers.get('content-type') || bird.photo_content_type || '';
|
||||
|
||||
if (!/^image\/(?:png|jpe?g)$/i.test(contentType)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return Buffer.from(await imageResponse.arrayBuffer());
|
||||
};
|
||||
|
||||
const getDefaultBirdPhotoAttachment = () => {
|
||||
const defaultPhotoPath = path.join(process.cwd(), 'assets', 'yoda-default.png');
|
||||
|
||||
@@ -2267,59 +2444,6 @@ const ensureBirdWritable = (bird: BirdRow, res: Response) => {
|
||||
return false;
|
||||
};
|
||||
|
||||
type HealthCheckResult = {
|
||||
ok: boolean;
|
||||
latencyMs?: number;
|
||||
error?: string;
|
||||
};
|
||||
|
||||
const withHealthTimeout = async <T,>(operation: Promise<T>, timeoutMs = 2_000): Promise<T> => {
|
||||
let timeout: NodeJS.Timeout | undefined;
|
||||
|
||||
try {
|
||||
return await Promise.race([
|
||||
operation,
|
||||
new Promise<never>((_resolve, reject) => {
|
||||
timeout = setTimeout(() => reject(new Error('Health check timed out')), timeoutMs);
|
||||
}),
|
||||
]);
|
||||
} finally {
|
||||
if (timeout) {
|
||||
clearTimeout(timeout);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const checkPostgresHealth = async (): Promise<HealthCheckResult> => {
|
||||
const startedAt = Date.now();
|
||||
|
||||
try {
|
||||
await withHealthTimeout(db.query('SELECT 1'));
|
||||
return { ok: true, latencyMs: Date.now() - startedAt };
|
||||
} catch (error) {
|
||||
return {
|
||||
ok: false,
|
||||
latencyMs: Date.now() - startedAt,
|
||||
error: error instanceof Error ? error.message : 'Postgres health check failed',
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
const checkRedisHealth = async (): Promise<HealthCheckResult> => {
|
||||
const startedAt = Date.now();
|
||||
|
||||
try {
|
||||
await withHealthTimeout(getBirdMilestoneReminderQueueCounts());
|
||||
return { ok: true, latencyMs: Date.now() - startedAt };
|
||||
} catch (error) {
|
||||
return {
|
||||
ok: false,
|
||||
latencyMs: Date.now() - startedAt,
|
||||
error: error instanceof Error ? error.message : 'Redis health check failed',
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
const writeAuditLog = async (
|
||||
auth: AuthContext,
|
||||
action: string,
|
||||
@@ -2343,51 +2467,51 @@ const writeAuditLog = async (
|
||||
}
|
||||
};
|
||||
|
||||
const writeBirdTimelineEvent = async ({
|
||||
birdId,
|
||||
eventType,
|
||||
fromWorkspaceId,
|
||||
toWorkspaceId,
|
||||
locationLabel,
|
||||
locationDetails,
|
||||
note,
|
||||
eventDate,
|
||||
createdByUserId,
|
||||
}: {
|
||||
birdId: string;
|
||||
eventType: BirdTimelineEventType;
|
||||
fromWorkspaceId?: number | null;
|
||||
toWorkspaceId?: number | null;
|
||||
locationLabel?: string | null;
|
||||
locationDetails?: Record<string, unknown> | null;
|
||||
note?: string | null;
|
||||
eventDate?: string | null;
|
||||
createdByUserId?: string | null;
|
||||
}) => {
|
||||
try {
|
||||
await createBirdTimelineEvent({
|
||||
birdId,
|
||||
eventType,
|
||||
fromWorkspaceId,
|
||||
toWorkspaceId,
|
||||
locationLabel,
|
||||
locationDetails,
|
||||
note,
|
||||
eventDate,
|
||||
createdByUserId,
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Unable to write bird timeline event', error);
|
||||
}
|
||||
};
|
||||
|
||||
const isBillingOnlyWorkspaceUpdate = (
|
||||
workspace: WorkspaceRow,
|
||||
payload: z.infer<typeof workspaceSchema>,
|
||||
) => workspace.workspace_type === 'standard' && payload.workspaceType === 'standard' && payload.name === workspace.name;
|
||||
|
||||
app.get('/api/health/live', (_req: Request, res: Response) => {
|
||||
res.json({
|
||||
ok: true,
|
||||
service: 'flockpal-backend',
|
||||
status: 'live',
|
||||
uptimeSeconds: Math.round(process.uptime()),
|
||||
checkedAt: new Date().toISOString(),
|
||||
});
|
||||
});
|
||||
|
||||
app.get('/api/health/ready', async (_req: Request, res: Response) => {
|
||||
const [postgres, redis] = await Promise.all([checkPostgresHealth(), checkRedisHealth()]);
|
||||
const ok = postgres.ok && redis.ok;
|
||||
|
||||
res.status(ok ? 200 : 503).json({
|
||||
ok,
|
||||
service: 'flockpal-backend',
|
||||
status: ok ? 'ready' : 'degraded',
|
||||
checkedAt: new Date().toISOString(),
|
||||
dependencies: {
|
||||
postgres,
|
||||
redis,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
app.get('/api/health', async (_req: Request, res: Response) => {
|
||||
const [postgres, redis] = await Promise.all([checkPostgresHealth(), checkRedisHealth()]);
|
||||
const ok = postgres.ok && redis.ok;
|
||||
|
||||
res.status(ok ? 200 : 503).json({
|
||||
ok,
|
||||
service: 'flockpal-backend',
|
||||
status: ok ? 'ready' : 'degraded',
|
||||
checkedAt: new Date().toISOString(),
|
||||
dependencies: {
|
||||
postgres,
|
||||
redis,
|
||||
},
|
||||
});
|
||||
app.get('/api/health', (_req: Request, res: Response) => {
|
||||
res.json({ ok: true });
|
||||
});
|
||||
|
||||
app.get('/api/metrics', requireAuth, requireAdmin, async (_req: Request, res: Response, next: NextFunction) => {
|
||||
@@ -2419,7 +2543,6 @@ app.get('/api/metrics', requireAuth, requireAdmin, async (_req: Request, res: Re
|
||||
queues: {
|
||||
birdMilestoneReminders: birdMilestoneReminderQueueCounts,
|
||||
medicationReminders: medicationReminderQueueCounts,
|
||||
adoptionReports: await getAdoptionReportQueueCounts(),
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
@@ -2814,6 +2937,12 @@ app.get('/api/admin/summary', requireAuth, requireSessionAuth, requireAdmin, asy
|
||||
rescueBirds: Number(summary?.rescue_birds ?? 0),
|
||||
pendingRescues: Number(summary?.pending_rescues ?? 0),
|
||||
dailyUsers: Number(summary?.daily_users ?? 0),
|
||||
subscriptionsByPlan: {
|
||||
household_basic: Number(summary?.household_basic_subscriptions ?? 0),
|
||||
household_plus: Number(summary?.household_plus_subscriptions ?? 0),
|
||||
household_macaw: Number(summary?.household_macaw_subscriptions ?? 0),
|
||||
household_hyacinth_macaw: Number(summary?.household_hyacinth_macaw_subscriptions ?? 0),
|
||||
},
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
@@ -3433,6 +3562,61 @@ app.get('/api/audit-log', requireAuth, requireSessionAuth, requireWorkspaceRole(
|
||||
}
|
||||
});
|
||||
|
||||
app.get('/api/locations/search', requireAuth, locationSearchLimiter, async (req: Request, res: Response, next: NextFunction) => {
|
||||
const parsed = locationSearchSchema.safeParse(req.query);
|
||||
|
||||
if (!parsed.success) {
|
||||
res.status(400).json({ error: 'Enter at least 3 characters to search for a location.' });
|
||||
return;
|
||||
}
|
||||
|
||||
if (!mapboxAccessToken) {
|
||||
res.status(503).json({ error: 'Location search is not configured.' });
|
||||
return;
|
||||
}
|
||||
|
||||
const query = parsed.data.q.replace(/\s+/g, ' ').trim();
|
||||
const cacheKey = query.toLocaleLowerCase();
|
||||
const cached = mapboxLocationCache.get(cacheKey);
|
||||
|
||||
if (cached && cached.expiresAt > Date.now()) {
|
||||
res.json({ results: cached.results });
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const searchUrl = new URL('https://api.mapbox.com/search/geocode/v6/forward');
|
||||
searchUrl.searchParams.set('q', query);
|
||||
searchUrl.searchParams.set('access_token', mapboxAccessToken);
|
||||
searchUrl.searchParams.set('autocomplete', 'false');
|
||||
searchUrl.searchParams.set('types', 'place,locality,region,country');
|
||||
searchUrl.searchParams.set('limit', '3');
|
||||
searchUrl.searchParams.set('permanent', 'true');
|
||||
|
||||
const mapboxResponse = await fetch(searchUrl);
|
||||
const data = (await mapboxResponse.json().catch(() => null)) as MapboxGeocodeResponse | null;
|
||||
|
||||
if (!mapboxResponse.ok) {
|
||||
res.status(502).json({ error: data?.message || 'Location search failed.' });
|
||||
return;
|
||||
}
|
||||
|
||||
const results = (data?.features ?? [])
|
||||
.map(normalizeMapboxLocationFeature)
|
||||
.filter((result): result is VerifiedLocationSearchResult => result !== null)
|
||||
.filter((result, index, allResults) => allResults.findIndex((entry) => entry.providerPlaceId === result.providerPlaceId) === index);
|
||||
|
||||
mapboxLocationCache.set(cacheKey, {
|
||||
expiresAt: Date.now() + mapboxLocationCacheTtlMs,
|
||||
results,
|
||||
});
|
||||
|
||||
res.json({ results });
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
});
|
||||
|
||||
app.get('/api/birds', requireAuth, async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const [birds, memorializedBirds] = await Promise.all([
|
||||
@@ -3445,6 +3629,71 @@ app.get('/api/birds', requireAuth, async (req: Request, res: Response, next: Nex
|
||||
}
|
||||
});
|
||||
|
||||
app.get('/api/birds/:birdId/timeline', requireAuth, async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const bird = await getBirdById(req.params.birdId, req.auth!.workspace.id);
|
||||
|
||||
if (!bird) {
|
||||
res.status(404).json({ error: 'Bird not found.' });
|
||||
return;
|
||||
}
|
||||
|
||||
const events = await listBirdTimelineEvents(req.params.birdId, req.auth!.workspace.id);
|
||||
res.json({ events: events.map(normalizeBirdTimelineEvent) });
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
});
|
||||
|
||||
app.post(
|
||||
'/api/birds/:birdId/timeline',
|
||||
requireAuth,
|
||||
requireWriteAccess,
|
||||
requireSessionAuth,
|
||||
requireWorkspaceRole(['owner', 'assistant', 'caregiver']),
|
||||
async (req: Request, res: Response, next: NextFunction) => {
|
||||
const parsed = birdTimelineEventSchema.safeParse(req.body);
|
||||
|
||||
if (!parsed.success) {
|
||||
res.status(400).json({ error: 'Invalid timeline 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 locationDetails = normalizeVerifiedLocationDetails(parsed.data.locationDetails);
|
||||
const event = await createBirdTimelineEvent({
|
||||
birdId: bird.id,
|
||||
eventType: parsed.data.eventType as BirdTimelineEventType,
|
||||
toWorkspaceId: req.auth!.workspace.id,
|
||||
locationLabel: formatVerifiedLocationLabel(locationDetails) ?? emptyToNull(parsed.data.locationLabel),
|
||||
locationDetails,
|
||||
note: emptyToNull(parsed.data.note),
|
||||
eventDate: emptyToNull(parsed.data.eventDate),
|
||||
createdByUserId: req.auth!.user.id,
|
||||
});
|
||||
|
||||
await writeAuditLog(req.auth!, 'bird.timeline_event_created', 'bird', bird.id, bird.name, {
|
||||
eventType: parsed.data.eventType,
|
||||
});
|
||||
|
||||
res.status(201).json({ event: normalizeBirdTimelineEvent(event!) });
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
app.get('/api/birds/:birdId/photo', async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const token = typeof req.query.token === 'string' ? req.query.token : '';
|
||||
@@ -3516,29 +3765,13 @@ app.post('/api/birds', requireAuth, requireWriteAccess, requireWorkspaceRole(['o
|
||||
let uploadedObjectKeyToCleanup: string | null = null;
|
||||
|
||||
try {
|
||||
const birdLimit = getBillingPlanBirdLimit(req.auth!.workspace.billing_plan);
|
||||
|
||||
if (birdLimit !== null) {
|
||||
const currentBirdCount = await getWorkspaceBirdCount(req.auth!.workspace.id);
|
||||
|
||||
if (currentBirdCount >= birdLimit) {
|
||||
res.status(409).json({
|
||||
error: 'This flock has reached the bird limit for the selected plan. Upgrade the flock subscription or memorialize a bird before adding another.',
|
||||
code: 'billing_plan_bird_limit_reached',
|
||||
birdLimit,
|
||||
currentBirdCount,
|
||||
billingPlan: req.auth!.workspace.billing_plan,
|
||||
});
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
const birdId = crypto.randomUUID();
|
||||
const photoStorage = await resolveBirdPhotoStorage({
|
||||
birdId,
|
||||
workspaceId: req.auth!.workspace.id,
|
||||
photoDataUrl: emptyToNull(parsed.data.photoDataUrl),
|
||||
});
|
||||
const locationDetails = normalizeVerifiedLocationDetails(parsed.data.locationDetails);
|
||||
uploadedObjectKeyToCleanup = photoStorage.photoObjectKey;
|
||||
const bird = await createBird({
|
||||
birdId,
|
||||
@@ -3549,12 +3782,14 @@ app.post('/api/birds', requireAuth, requireWriteAccess, requireWorkspaceRole(['o
|
||||
motivators: emptyToNull(parsed.data.motivators),
|
||||
demotivators: emptyToNull(parsed.data.demotivators),
|
||||
favoriteSnack: emptyToNull(parsed.data.favoriteSnack),
|
||||
locationLabel: formatVerifiedLocationLabel(locationDetails) ?? emptyToNull(parsed.data.locationLabel),
|
||||
locationDetails,
|
||||
vetClinicName: emptyToNull(parsed.data.vetClinicName),
|
||||
vetClinicAddress: emptyToNull(parsed.data.vetClinicAddress),
|
||||
vetAccountNumber: emptyToNull(parsed.data.vetAccountNumber),
|
||||
vetDoctorName: emptyToNull(parsed.data.vetDoctorName),
|
||||
gender: (parsed.data.gender ?? 'unknown') as BirdGender,
|
||||
dateOfBirth: emptyToNull(parsed.data.dateOfBirth),
|
||||
dateOfBirth: emptyToNull(parsed.data.hatchDay || parsed.data.dateOfBirth),
|
||||
gotchaDay: emptyToNull(parsed.data.gotchaDay),
|
||||
chartColor: parsed.data.chartColor ?? '#cb3a35',
|
||||
photoDataUrl: photoStorage.photoDataUrl,
|
||||
@@ -3572,6 +3807,14 @@ app.post('/api/birds', requireAuth, requireWriteAccess, requireWorkspaceRole(['o
|
||||
species: bird!.species,
|
||||
tagId: bird!.tag_id,
|
||||
});
|
||||
await writeBirdTimelineEvent({
|
||||
birdId: bird!.id,
|
||||
eventType: 'profile_created',
|
||||
toWorkspaceId: req.auth!.workspace.id,
|
||||
locationLabel: bird!.location_label,
|
||||
locationDetails: bird!.location_details,
|
||||
createdByUserId: req.auth!.user.id,
|
||||
});
|
||||
res.status(201).json({ bird: normalizeBird(bird!) });
|
||||
} catch (error) {
|
||||
await deleteBirdPhotoObjectIfNeeded(uploadedObjectKeyToCleanup);
|
||||
@@ -3656,6 +3899,13 @@ app.post('/api/birds/:birdId/transfer', requireAuth, requireWriteAccess, require
|
||||
destinationOwnerEmail,
|
||||
destinationWorkspaceId: targetWorkspace.id,
|
||||
});
|
||||
await writeBirdTimelineEvent({
|
||||
birdId: bird.id,
|
||||
eventType: 'transferred',
|
||||
fromWorkspaceId: req.auth!.workspace.id,
|
||||
toWorkspaceId: targetWorkspace.id,
|
||||
createdByUserId: req.auth!.user.id,
|
||||
});
|
||||
res.json({ bird: normalizeBird(bird), destinationOwnerEmail, destinationWorkspace: normalizeWorkspace(targetWorkspace) });
|
||||
} catch (error) {
|
||||
if (typeof error === 'object' && error && 'code' in error && error.code === '23505') {
|
||||
@@ -3686,7 +3936,25 @@ app.post(
|
||||
return;
|
||||
}
|
||||
|
||||
const transferCode = await ensureOpenBirdTransferCode(sourceBird.id, req.auth!.workspace.id, req.auth!.user.id);
|
||||
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.');
|
||||
@@ -3708,30 +3976,6 @@ app.post(
|
||||
},
|
||||
);
|
||||
|
||||
app.get('/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;
|
||||
}
|
||||
|
||||
const transferCode = await getOpenBirdTransferCodeForBird(sourceBird.id, req.auth!.workspace.id);
|
||||
|
||||
res.json({
|
||||
transferCode: transferCode
|
||||
? {
|
||||
code: transferCode.code,
|
||||
bird: normalizeBird(sourceBird),
|
||||
}
|
||||
: null,
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
});
|
||||
|
||||
app.post(
|
||||
'/api/bird-transfer-codes/:code/accept',
|
||||
requireAuth,
|
||||
@@ -3772,6 +4016,13 @@ app.post(
|
||||
sourceWorkspaceName: transferCode.workspace_name,
|
||||
transferCodeId: transferCode.transfer_code_id,
|
||||
});
|
||||
await writeBirdTimelineEvent({
|
||||
birdId: bird.id,
|
||||
eventType: 'transferred',
|
||||
fromWorkspaceId: transferCode.source_workspace_id,
|
||||
toWorkspaceId: req.auth!.workspace.id,
|
||||
createdByUserId: req.auth!.user.id,
|
||||
});
|
||||
|
||||
res.json({ bird: normalizeBird(bird), sourceWorkspaceName: transferCode.workspace_name, workspace: normalizeWorkspace(req.auth!.workspace) });
|
||||
} catch (error) {
|
||||
@@ -3804,7 +4055,25 @@ app.post(
|
||||
return;
|
||||
}
|
||||
|
||||
const transferCode = await ensureOpenBirdTransferCode(sourceBird.id, req.auth!.workspace.id, req.auth!.user.id);
|
||||
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.');
|
||||
@@ -3872,6 +4141,7 @@ app.put('/api/birds/:birdId', requireAuth, requireWriteAccess, requireWorkspaceR
|
||||
});
|
||||
uploadedObjectKeyToCleanup =
|
||||
photoStorage.photoObjectKey && photoStorage.photoObjectKey !== existingBird.photo_object_key ? photoStorage.photoObjectKey : null;
|
||||
const locationDetails = normalizeVerifiedLocationDetails(parsed.data.locationDetails);
|
||||
const bird = await updateBird({
|
||||
birdId: req.params.birdId,
|
||||
workspaceId: req.auth!.workspace.id,
|
||||
@@ -3881,12 +4151,14 @@ app.put('/api/birds/:birdId', requireAuth, requireWriteAccess, requireWorkspaceR
|
||||
motivators: emptyToNull(parsed.data.motivators),
|
||||
demotivators: emptyToNull(parsed.data.demotivators),
|
||||
favoriteSnack: emptyToNull(parsed.data.favoriteSnack),
|
||||
locationLabel: formatVerifiedLocationLabel(locationDetails) ?? emptyToNull(parsed.data.locationLabel),
|
||||
locationDetails,
|
||||
vetClinicName: emptyToNull(parsed.data.vetClinicName),
|
||||
vetClinicAddress: emptyToNull(parsed.data.vetClinicAddress),
|
||||
vetAccountNumber: emptyToNull(parsed.data.vetAccountNumber),
|
||||
vetDoctorName: emptyToNull(parsed.data.vetDoctorName),
|
||||
gender: (parsed.data.gender ?? 'unknown') as BirdGender,
|
||||
dateOfBirth: emptyToNull(parsed.data.dateOfBirth),
|
||||
dateOfBirth: emptyToNull(parsed.data.hatchDay || parsed.data.dateOfBirth),
|
||||
gotchaDay: emptyToNull(parsed.data.gotchaDay),
|
||||
chartColor: parsed.data.chartColor ?? '#cb3a35',
|
||||
photoDataUrl: photoStorage.photoDataUrl,
|
||||
@@ -3910,6 +4182,19 @@ app.put('/api/birds/:birdId', requireAuth, requireWriteAccess, requireWorkspaceR
|
||||
previousName: existingBird.name,
|
||||
species: bird.species,
|
||||
});
|
||||
if (
|
||||
(existingBird.location_label ?? '') !== (bird.location_label ?? '') ||
|
||||
JSON.stringify(existingBird.location_details ?? null) !== JSON.stringify(bird.location_details ?? null)
|
||||
) {
|
||||
await writeBirdTimelineEvent({
|
||||
birdId: bird.id,
|
||||
eventType: 'location_updated',
|
||||
toWorkspaceId: req.auth!.workspace.id,
|
||||
locationLabel: bird.location_label,
|
||||
locationDetails: bird.location_details,
|
||||
createdByUserId: req.auth!.user.id,
|
||||
});
|
||||
}
|
||||
res.json({ bird: normalizeBird(bird) });
|
||||
} catch (error) {
|
||||
await deleteBirdPhotoObjectIfNeeded(uploadedObjectKeyToCleanup);
|
||||
|
||||
Reference in new issue
Block a user