diff --git a/.env.example b/.env.example index 44efc09..bf76da6 100644 --- a/.env.example +++ b/.env.example @@ -42,3 +42,7 @@ STRIPE_PORTAL_RETURN_URL=http://localhost:3000/?billing=portal # Daily email for birds without a new weight entry in 48 hours; uses the milestone time zone. WEIGHT_REMINDERS_ENABLED=true + +# Optional absolute HTTPS image URL; defaults to FRONTEND_URL/email-background.png. +# Deploy frontend/public/email-background.png before sending the updated email templates. +EMAIL_BACKGROUND_URL= diff --git a/README.md b/README.md index 8a9c7f3..4a5e872 100644 --- a/README.md +++ b/README.md @@ -165,7 +165,9 @@ npm run worker The worker checks once per calendar day for living birds with no new weight entry in 48 hours. Each accepted owner, assistant, or caregiver receives one email per flock -listing all birds due for a reminder. Pending invitees and viewers are excluded. +listing all birds due for a reminder. The branded email embeds the FlockPal logo +and each bird's portrait (including private S3 photos), with the default portrait +used when a photo is missing or unavailable. Pending invitees and viewers are excluded. Reminders repeat daily while overdue; adding a new weight restarts the 48-hour clock. Birds without weights use their profile creation time. diff --git a/backend/assets/email-background.png b/backend/assets/email-background.png new file mode 100644 index 0000000..f3b74ae Binary files /dev/null and b/backend/assets/email-background.png differ diff --git a/backend/scripts/generate-email-background.mjs b/backend/scripts/generate-email-background.mjs new file mode 100644 index 0000000..4642d42 --- /dev/null +++ b/backend/scripts/generate-email-background.mjs @@ -0,0 +1,13 @@ +// Rebuild the email-safe PNG from the app's SVG tracks and background palette. +// Run from backend: node scripts/generate-email-background.mjs +import { readFile, writeFile } from 'node:fs/promises'; +import sharp from 'sharp'; +const css = await readFile(new URL('../../frontend/src/index.css', import.meta.url), 'utf8'); +const encoded = css.match(/background-image: url\("data:image\/svg\+xml,([^"\n]+)"\)/)?.[1]; +if (!encoded) throw new Error('App bird-track background was not found'); +const tracks = decodeURIComponent(encoded); +const gradients = `${[[14,10,22,'#de7c3a',.28],[82,12,20,'#35886e',.26],[24,84,22,'#ddb34e',.2],[86,78,24,'#2b765c',.24],[62,54,16,'#3072a0',.14]].map(([x,y,r,color,opacity],i)=>``).join('')}`; +const svg = `${gradients}${[0,1,2,3,4].map(i=>``).join('')}${tracks.replace(/^]*>/,'').replace(/<\/svg>$/,'')}`; +await writeFile(new URL('../assets/email-background.png', import.meta.url), await sharp(Buffer.from(svg)).png().toBuffer()); + +await writeFile(new URL('../../frontend/public/email-background.png', import.meta.url), await readFile(new URL('../assets/email-background.png', import.meta.url))); diff --git a/backend/src/app.ts b/backend/src/app.ts index ce01685..959d9d2 100644 --- a/backend/src/app.ts +++ b/backend/src/app.ts @@ -1,3 +1,5 @@ +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'; @@ -9,7 +11,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'; @@ -1395,12 +1397,14 @@ const sendMagicLink = async ({ '', 'This link expires in 15 minutes and can only be used once.', ].join('\n'), - html: ` -

Hi ${name || 'there'},

+ ...await buildEmailLayout({ eyebrow: 'Sign in', headline: 'Your FlockPal sign-in link', + contentHtml: ` +

Hi ${escapeHtml(name || 'there')},

Use this secure link to sign in to FlockPal:

-

Sign in to FlockPal

This link expires in 15 minutes and can only be used once.

- `, +`, + action: { url: magicLinkUrl, label: 'Sign in to FlockPal' }, + }), }); return { @@ -1471,27 +1475,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 = ``; - return `data:image/svg+xml,${encodeURIComponent(svg)}`; -}; - const parseDataImage = (dataUrl: string) => { const match = /^data:(image\/[a-zA-Z0-9.+-]+);base64,(.+)$/.exec(dataUrl); if (!match) { @@ -1636,22 +1619,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, @@ -1701,7 +1668,8 @@ const sendRescueStatusNotification = async ({ to: rescueStatusNotificationEmail, subject, text: lines.join('\n'), - html: ` + ...await buildEmailLayout({ eyebrow: 'Rescue status', headline: 'Rescue flock update', + contentHtml: `

A rescue flock was ${eventLabel}.

${escapedNote ? `

Note: ${escapedNote}

` : ''} - `, +`, + action: { url: frontendBaseUrl, label: 'Open FlockPal' }, + }), }); return { delivered: true }; @@ -1850,13 +1820,15 @@ const issueBirdTransferInvite = async ({ to: email, subject, text, - html: ` + ...await buildEmailLayout({ eyebrow: 'Bird transfer', headline: 'A bird is joining your flock', + contentHtml: `

Hi there,

${escapeHtml(sourceWorkspaceName)} wants to transfer ${escapeHtml(birdName)} to your FlockPal account.

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.

-

Accept bird transfer in FlockPal

This link expires in 15 minutes and can only be used once.

- `, +`, + action: { url: magicLinkUrl, label: 'Accept bird transfer' }, + }), }); return { @@ -1912,7 +1884,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: `

A possible found bird report was submitted for ${escapeHtml(bird.name)}.

FlockPal does not verify found bird reports. Please use care before sharing personal information or arranging a pickup.

- `, +`, + action: { url: frontendBaseUrl, label: 'Open FlockPal' }, + }), }); return { delivered: true }; @@ -2000,7 +1975,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}`, @@ -2021,32 +1996,6 @@ const sendBirdMilestoneReminderNotification = async ({ } const copy = buildBirdMilestoneReminderCopy(reminder); - const attachments: NonNullable = []; - 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 - ? `${escapeHtml(reminder.name)}` - : `
${escapeHtml(reminder.name.slice(0, 1).toUpperCase())}
`; const lines = [ copy.headline, '', @@ -2071,43 +2020,18 @@ const sendBirdMilestoneReminderNotification = async ({ bcc: uniqueRecipients, subject: copy.subject, text: lines.join('\n'), - attachments, - html: ` -
-
- -
-
-
- ${ - logoAttachment - ? 'FlockPal' - : 'FlockPal' - } -
-
- - - - - -
- ${birdPhotoHtml} - -

${escapeHtml(copy.headline)}

-

${escapeHtml(copy.intro)}

-
-

${escapeHtml(copy.body)}

-

- Open FlockPal -

-
-
-
- -
-
- `, + ...await buildEmailLayout({ + bird: reminder, + eyebrow: copy.eyebrow, + headline: copy.headline, + preheader: copy.intro, + contentHtml: `

${escapeHtml(copy.intro)}

+

${escapeHtml(copy.body)}

+

${escapeHtml(reminder.name)} · ${escapeHtml(reminder.species)}

+

${escapeHtml(`${copy.eventName}: ${copy.milestoneLabel}`)}

+ `, + action: { url: frontendBaseUrl, label: 'Open FlockPal' }, + }), }); return { delivered: true }; @@ -2127,35 +2051,6 @@ const sendMedicationReminderNotification = async ({ } const copy = buildMedicationReminderCopy(reminder); - const attachments: NonNullable = []; - 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 - ? `${escapeHtml(reminder.name)}` - : `
${escapeHtml(reminder.name.slice(0, 1).toUpperCase())}
`; - const medicationNotesHtml = reminder.medication_notes - ? `

Medication notes: ${escapeHtml(reminder.medication_notes)}

` - : ''; const lines = [ copy.headline, '', @@ -2182,46 +2077,18 @@ const sendMedicationReminderNotification = async ({ bcc: uniqueRecipients, subject: copy.subject, text: lines.join('\n'), - attachments, - html: ` -
-
- -
-
-
- ${ - logoAttachment - ? 'FlockPal' - : 'FlockPal' - } -
-
- - - - - -
- ${birdPhotoHtml} - -

${escapeHtml(copy.eyebrow)}

-

${escapeHtml(copy.headline)}

-

${escapeHtml(copy.intro)}

-
-

${escapeHtml(copy.body)}

-

Schedule: ${escapeHtml(copy.detailLabel)}

- ${medicationNotesHtml} -

- Open FlockPal -

-
-
-
- -
-
- `, + ...await buildEmailLayout({ + bird: reminder, + eyebrow: copy.eyebrow, + headline: copy.headline, + preheader: copy.intro, + contentHtml: `

${escapeHtml(copy.intro)}

+

${escapeHtml(copy.body)}

+

${escapeHtml(reminder.name)} · ${escapeHtml(reminder.species)}

+

${escapeHtml(copy.detailLabel)}

+ ${reminder.medication_notes ? `

Medication notes: ${escapeHtml(reminder.medication_notes)}

` : ''}`, + action: { url: frontendBaseUrl, label: 'Open FlockPal' }, + }), }); return { delivered: true }; @@ -2277,9 +2144,7 @@ export const sendWeightReminderNotification = async (reminders: WeightReminder[] const result = await mailTransport.sendMail({ from: smtpFromName ? `"${smtpFromName}" <${smtpFromEmail}>` : smtpFromEmail, to: first.recipient, - subject: `Weight reminders for ${first.workspace_name}`, - text: `These birds in ${first.workspace_name} haven't had a new weight entry in at least 48 hours:\n\n${reminders.map((bird) => `- ${bird.bird_name}`).join('\n')}\n\nOpen FlockPal to record their weights: ${frontendBaseUrl}`, - html: `

These birds in ${escapeHtml(first.workspace_name)} haven't had a new weight entry in at least 48 hours:

Open FlockPal to record their weights

`, + ...await buildWeightReminderEmail(reminders, frontendBaseUrl), }); return result.accepted.length > 0; }; diff --git a/backend/src/emails/birdPortrait.ts b/backend/src/emails/birdPortrait.ts new file mode 100644 index 0000000..cf03dfb --- /dev/null +++ b/backend/src/emails/birdPortrait.ts @@ -0,0 +1,29 @@ +import { readFile } from 'node:fs/promises'; +import sharp from 'sharp'; +import type { WeightReminder } from '../reminders/weightReminders.js'; +import { getS3ImageStorageConfig } from '../storage/imageStorageConfig.js'; +import { getSignedS3ObjectUrl } from '../storage/s3Client.js'; + +const asset = (name: string) => new URL(`../../assets/${name}`, import.meta.url); +const thumbnail = (content: Buffer) => sharp(content).rotate().resize(192, 192, { fit: 'cover' }).jpeg({ quality: 80 }).toBuffer(); + +export const loadWeightReminderPortrait = async (bird: Pick): Promise => { + try { + if (bird.photo_object_key) { + const config = getS3ImageStorageConfig(); + if (config) { + const response = await fetch(getSignedS3ObjectUrl({ config, objectKey: bird.photo_object_key, expiresInSeconds: 300 }), { + signal: AbortSignal.timeout(10_000), + }); + if (!response.ok) throw new Error(`Photo storage returned ${response.status}`); + return await thumbnail(Buffer.from(await response.arrayBuffer())); + } + } + const match = bird.photo_data_url?.match(/^data:image\/(?:png|jpe?g|webp|gif);base64,(.+)$/); + if (match) return await thumbnail(Buffer.from(match[1], 'base64')); + } catch { + console.warn(`Unable to load weight reminder portrait for bird ${bird.bird_id}; using default portrait.`); + } + return thumbnail(await readFile(asset('yoda-default.png'))); +}; + diff --git a/backend/src/emails/emailLayout.test.ts b/backend/src/emails/emailLayout.test.ts new file mode 100644 index 0000000..00754e2 --- /dev/null +++ b/backend/src/emails/emailLayout.test.ts @@ -0,0 +1,36 @@ +import assert from 'node:assert/strict'; +import { test } from 'node:test'; +import { buildEmailLayout } from './emailLayout.js'; + +test('shared layout escapes copy and embeds the app background and bird portrait', async () => { + const mail = await buildEmailLayout({ + backgroundUrl: 'https://flockpal.test/email-background.png', + eyebrow: 'Medication ', headline: 'Medication time for Kiwi & Peep', + contentHtml: '

Morning at 8:00 AM

', + action: { url: 'https://flockpal.test/?a=1&b=2', label: 'Open ' }, + bird: { id: 'bird-1', name: 'Kiwi & Peep', photo_data_url: null, photo_object_key: null }, + }); + const html = String(mail.html); + assert.match(html, /Medication <reminder>/); + assert.match(html, /Medication time for Kiwi & Peep/); + assert.match(html, /a=1&b=2/); + assert.match(html, /Open <FlockPal>/); + assert.match(html, /Morning at 8:00 AM/); + assert.match(html, /background="https:\/\/flockpal.test\/email-background.png"/); + assert.match(html, /background-image:url\('https:\/\/flockpal.test\/email-background.png'\)/); + assert.doesNotMatch(html, /flockpal-pattern|cid:flockpal-background/); + assert.doesNotMatch(html, /48-hour|weights are overdue|data:image/); + for (const attachment of mail.attachments ?? []) { + assert.ok(html.includes(`cid:${attachment.cid}`)); + assert.equal(attachment.contentDisposition, 'inline'); + assert.ok(Buffer.isBuffer(attachment.content)); + } + assert.equal((html.match(//g) ?? []).length); + assert.equal((html.match(//g) ?? []).length); +}); + +test('transactional layout omits optional portrait, action and reminder footer', async () => { + const mail = await buildEmailLayout({ eyebrow: 'Rescue status', headline: 'Flock update', contentHtml: '

Status changed

' }); + assert.equal(mail.attachments?.length, 1); + assert.doesNotMatch(String(mail.html), /bird-portrait| value.replace(/[&<>"']/g, char => ({ + '&': '&', '<': '<', '>': '>', '"': '"', "'": ''', +})[char]!); +const asset = (name: string) => new URL(`../../assets/${name}`, import.meta.url); + +export const buildEmailLayout = async ({ eyebrow, headline, preheader = headline, contentHtml, action, footer, bird, backgroundUrl = process.env.EMAIL_BACKGROUND_URL || new URL('/email-background.png', process.env.FRONTEND_URL || 'http://localhost:3000').href }: { + eyebrow: string; + headline: string; + preheader?: string; + /** Trusted markup; escape all dynamic values before passing them. */ + contentHtml: string; + action?: { url: string; label: string }; + footer?: string; + backgroundUrl?: string; + bird?: { id: string; name: string; photo_data_url: string | null; photo_object_key: string | null }; +}): Promise> => ({ + attachments: [ + { filename: 'flockpal-logo.png', cid: 'flockpal-logo', contentType: 'image/png', contentDisposition: 'inline', content: await sharp(await readFile(asset('flockpal-logo.png'))).resize({ width: 480 }).png().toBuffer() }, + ...(bird ? [{ filename: 'bird-portrait.jpg', cid: 'bird-portrait', contentType: 'image/jpeg', contentDisposition: 'inline' as const, content: await loadWeightReminderPortrait({ bird_id: bird.id, photo_data_url: bird.photo_data_url, photo_object_key: bird.photo_object_key }) }] : []), + ], + html: ` + +
${escapeHtml(preheader)}
+ + +
+ + + +
+ FlockPal +
+

${escapeHtml(eyebrow)}

+

${escapeHtml(headline)}

+ ${bird ? `${escapeHtml(bird.name)}` : ''} + ${contentHtml} + ${action ? `
${escapeHtml(action.label)}
` : ''} + ${footer ? `

${escapeHtml(footer)}

` : ''} +
+

FlockPal · A little care, every day.

+
+`, +}); diff --git a/backend/src/emails/weightReminderEmail.test.ts b/backend/src/emails/weightReminderEmail.test.ts new file mode 100644 index 0000000..f73be08 --- /dev/null +++ b/backend/src/emails/weightReminderEmail.test.ts @@ -0,0 +1,60 @@ +import assert from 'node:assert/strict'; +import { readFile } from 'node:fs/promises'; +import { test } from 'node:test'; +import sharp from 'sharp'; +import { buildWeightReminderEmail, loadWeightReminderPortrait } from './weightReminderEmail.js'; +import type { WeightReminder } from '../reminders/weightReminders.js'; + +const bird: WeightReminder = { + bird_id: 'bird-1', workspace_id: 1, bird_name: 'Kiwi & ', species: 'Cockatiel', + workspace_name: 'Our ', activity_at: '2026-09-01T12:00:00Z', recipient: 'owner@example.test', + photo_data_url: null, photo_object_key: null, +}; + +test('branded grouped email embeds distinct portraits and escapes dynamic content', async () => { + const mail = await buildWeightReminderEmail([bird, { ...bird, bird_id: 'bird-2', bird_name: 'Yoda' }], 'https://flockpal.test/?a=1&b=2'); + assert.equal(mail.attachments?.length, 3); + assert.deepEqual(mail.attachments?.map(a => a.cid), ['flockpal-logo', 'weight-bird-0', 'weight-bird-1']); + for (const attachment of mail.attachments ?? []) { + assert.equal(attachment.contentDisposition, 'inline'); + assert.ok(Buffer.isBuffer(attachment.content)); + assert.ok(String(mail.html).includes(`cid:${attachment.cid}`)); + } + assert.match(String(mail.html), /Kiwi & <Peep>/); + assert.match(String(mail.html), /Our <Flock>/); + assert.match(String(mail.html), /a=1&b=2/); + assert.match(String(mail.text), /Kiwi & /); +}); + +test('database portrait is resized and invalid photos fall back to the default', async () => { + const source = await readFile(new URL('../../assets/yoda.png', import.meta.url)); + const photo = await loadWeightReminderPortrait({ ...bird, photo_data_url: `data:image/png;base64,${source.toString('base64')}` }); + const metadata = await sharp(photo).metadata(); + assert.equal(metadata.width, 192); + assert.equal(metadata.height, 192); + assert.equal(metadata.format, 'jpeg'); + assert.deepEqual(await loadWeightReminderPortrait({ ...bird, photo_data_url: 'data:image/png;base64,broken' }), await loadWeightReminderPortrait(bird)); +}); + +test('private S3 portrait is downloaded and embedded rather than linked', async (t) => { + const env = { IMAGE_STORAGE_PROVIDER: 's3', S3_ENDPOINT: 'https://storage.example.test', S3_REGION: 'us-east-1', S3_BUCKET: 'portraits', S3_ACCESS_KEY_ID: 'test', S3_SECRET_ACCESS_KEY: 'test' }; + const previous = Object.fromEntries(Object.keys(env).map(key => [key, process.env[key]])); + Object.assign(process.env, env); + try { + const source = await readFile(new URL('../../assets/yoda.png', import.meta.url)); + t.mock.method(globalThis, 'fetch', async (url: string) => { + assert.match(String(url), /private-bird.png/); + return new Response(source); + }); + const photo = await loadWeightReminderPortrait({ ...bird, photo_object_key: 'private-bird.png' }); + assert.equal((await sharp(photo).metadata()).width, 192); + t.mock.restoreAll(); + t.mock.method(globalThis, 'fetch', async () => new Response('', { status: 404 })); + assert.deepEqual(await loadWeightReminderPortrait({ ...bird, photo_object_key: 'missing.png' }), await loadWeightReminderPortrait(bird)); + } finally { + for (const [key, value] of Object.entries(previous)) { + if (value === undefined) delete process.env[key]; + else process.env[key] = value; + } + } +}); diff --git a/backend/src/emails/weightReminderEmail.ts b/backend/src/emails/weightReminderEmail.ts new file mode 100644 index 0000000..c0ec647 --- /dev/null +++ b/backend/src/emails/weightReminderEmail.ts @@ -0,0 +1,44 @@ +import { buildEmailLayout, escapeHtml } from './emailLayout.js'; +import type { SendMailOptions } from 'nodemailer'; +import type { WeightReminder } from '../reminders/weightReminders.js'; +import { loadWeightReminderPortrait } from './birdPortrait.js'; +export { loadWeightReminderPortrait } from './birdPortrait.js'; + +export const buildWeightReminderEmail = async ( + reminders: WeightReminder[], + frontendUrl: string, + loadPortrait = loadWeightReminderPortrait, +): Promise> => { + if (!reminders.length) throw new Error('A weight reminder email requires at least one bird'); + const flock = reminders[0].workspace_name; + const attachments: NonNullable = []; + const rows: string[] = []; + for (const [index, bird] of reminders.entries()) { + const cid = `weight-bird-${index}`; + attachments.push({ filename: `${cid}.jpg`, cid, content: await loadPortrait(bird), contentType: 'image/jpeg', contentDisposition: 'inline' }); + rows.push(` + + ${escapeHtml(bird.bird_name)} + + +

${escapeHtml(bird.bird_name)}

+

${escapeHtml(bird.species)}

+

Ready for a weight check

+ + `); + } + const layout = await buildEmailLayout({ + eyebrow: 'Daily weight reminder', + headline: 'A little check-in for your flock', + preheader: `A little check-in for ${flock}: it's time to log your birds' weights.`, + contentHtml: `

These birds in ${escapeHtml(flock)} haven't had a new weight entry in at least 48 hours.

${rows.join('')}
`, + action: { url: frontendUrl, label: 'Record their weights' }, + footer: "You'll receive a daily reminder while weights are overdue. A new weight entry restarts the 48-hour clock.", + }); + return { + subject: `Weight reminders for ${flock}`, + text: `Daily weight reminder — ${flock}\n\nThese birds haven't had a new weight entry in at least 48 hours:\n\n${reminders.map(bird => `- ${bird.bird_name} (${bird.species})`).join('\n')}\n\nOpen FlockPal to record their weights: ${frontendUrl}\n\nYou'll receive a daily reminder while weights are overdue.`, + ...layout, + attachments: [...(layout.attachments ?? []), ...attachments], + }; +}; diff --git a/backend/src/reminders/weightReminders.test.ts b/backend/src/reminders/weightReminders.test.ts index e3a73cd..f4af9ed 100644 --- a/backend/src/reminders/weightReminders.test.ts +++ b/backend/src/reminders/weightReminders.test.ts @@ -3,6 +3,7 @@ import { test } from 'node:test'; import { runWeightReminders, type WeightReminder } from './weightReminders.js'; const bird = (id: string, workspace = 1, recipient = 'owner@example.com'): WeightReminder => ({ + species: 'Cockatiel', photo_data_url: null, photo_object_key: null, bird_id: id, workspace_id: workspace, recipient, bird_name: id, workspace_name: `Flock ${workspace}`, activity_at: '2026-09-01T12:00:00Z', }); diff --git a/backend/src/reminders/weightReminders.ts b/backend/src/reminders/weightReminders.ts index da76e56..cf90f07 100644 --- a/backend/src/reminders/weightReminders.ts +++ b/backend/src/reminders/weightReminders.ts @@ -6,6 +6,9 @@ export type WeightReminder = { bird_id: string; workspace_id: number; bird_name: string; + species: string; + photo_data_url: string | null; + photo_object_key: string | null; workspace_name: string; activity_at: string; recipient: string; @@ -32,9 +35,10 @@ export const listDueWeightReminders = async () => { AND role IN ('owner', 'assistant', 'caregiver') ) SELECT activity.bird_id, activity.workspace_id, activity.bird_name, activity.workspace_name, - activity.activity_at::text, recipients.recipient + activity.activity_at::text, recipients.recipient, birds.species, birds.photo_data_url, birds.photo_object_key FROM activity JOIN recipients USING (workspace_id) + JOIN birds ON birds.id = activity.bird_id WHERE activity_at <= CURRENT_TIMESTAMP - INTERVAL '48 hours' AND recipients.recipient <> '' AND NOT EXISTS ( diff --git a/backend/test-integration/weightReminders.mjs b/backend/test-integration/weightReminders.mjs index 13e6907..f907213 100644 --- a/backend/test-integration/weightReminders.mjs +++ b/backend/test-integration/weightReminders.mjs @@ -1,6 +1,7 @@ // Run only against disposable local Postgres, Redis, and Mailpit services. // See docs/WEIGHT_REMINDER_TESTING.md for the isolated Compose setup. import assert from 'node:assert/strict'; +import { readFile } from 'node:fs/promises'; import { randomUUID } from 'node:crypto'; import { spawn } from 'node:child_process'; import { once } from 'node:events'; @@ -83,6 +84,8 @@ try { VALUES ($1, $2, $3, 'Cockatiel', CURRENT_TIMESTAMP - INTERVAL '100 hours', ${memorial ? 'CURRENT_TIMESTAMP' : 'NULL'})`, [id, workspace, name]); if (age !== null) await db.query("INSERT INTO weight_records (bird_id, weight_grams, recorded_on, created_at) VALUES ($1, 90, CURRENT_DATE - 3, CURRENT_TIMESTAMP - $2 * INTERVAL '1 hour')", [id, age]); } + const portrait = await readFile(new URL('../assets/yoda.png', import.meta.url)); + await db.query('UPDATE birds SET photo_data_url = $1 WHERE id = $2', [`data:image/png;base64,${portrait.toString('base64')}`, birds['Kiwi & ']]); const due = await listDueWeightReminders(); assert.equal(due.length, 10); assert.deepEqual(new Set(due.map(b => b.recipient)), new Set(['owner@example.test', 'assistant@example.test', 'caregiver@example.test'])); @@ -113,6 +116,11 @@ try { assert.ok(!body.Text.includes('Boundary')); } assert.equal(body.To.length, 1); + const inline = body.Inline ?? []; + assert.ok(inline.some(attachment => attachment.ContentID === 'flockpal-logo')); + assert.equal(inline.filter(attachment => attachment.ContentID.startsWith('weight-bird-')).length, body.Subject === 'Weight reminders for Test Flock' ? 3 : 1); + assert.ok(body.HTML.includes('Daily weight reminder')); + assert.ok(body.HTML.includes('Record their weights')); } assert.equal((await weightReminderQueue.getJobSchedulers()).length, 0); await poll(async () => Boolean(await weightReminderQueue.getJob(`weight-reminders-${getReminderDate()}`)), 'startup daily scheduler'); diff --git a/docs/WEIGHT_REMINDER_TESTING.md b/docs/WEIGHT_REMINDER_TESTING.md index ecbef01..c185a41 100644 --- a/docs/WEIGHT_REMINDER_TESTING.md +++ b/docs/WEIGHT_REMINDER_TESTING.md @@ -28,7 +28,7 @@ these local services. It does not use the application's configured SMTP account. Coverage includes repeatable schema initialization, overdue and recent weights, birds without weights, memorial exclusions, accepted care roles, concurrent -claims, one daily job across two workers, removal of the old five-minute schedule, grouped emails, HTML escaping, flock +claims, one daily job across two workers, removal of the old five-minute schedule, grouped emails, embedded branding and portraits, HTML escaping, flock isolation, daily repeats, fresh weight resets, SMTP failures and recovery, worker shutdown, and disabling the scheduler. Repeat timing is tested by aging delivery timestamps rather than waiting two days. diff --git a/frontend/public/email-background.png b/frontend/public/email-background.png new file mode 100644 index 0000000..f3b74ae Binary files /dev/null and b/frontend/public/email-background.png differ