Added missing weight emails
This commit is contained in:
1 parent
b4254a68fa
commit
5abc7f6174
13 files changed
+501
No files matched your search
@@ -0,0 +1,60 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { test } from 'node:test';
|
||||
import { runWeightReminders, type WeightReminder } from './weightReminders.js';
|
||||
|
||||
const bird = (id: string, workspace = 1, recipient = 'owner@example.com'): WeightReminder => ({
|
||||
bird_id: id, workspace_id: workspace, recipient,
|
||||
bird_name: id, workspace_name: `Flock ${workspace}`, activity_at: '2026-09-01T12:00:00Z',
|
||||
});
|
||||
|
||||
test('groups overdue birds into one email per flock and recipient', async () => {
|
||||
const sent: WeightReminder[][] = [];
|
||||
const finished: boolean[] = [];
|
||||
const result = await runWeightReminders(async (birds) => { sent.push(birds); return true; }, {
|
||||
list: async () => [bird('a'), bird('b'), bird('c', 2), bird('a', 1, 'caregiver@example.com')],
|
||||
claim: async () => true,
|
||||
finish: async (_token, delivered) => { finished.push(delivered); },
|
||||
});
|
||||
assert.deepEqual(sent.map((group) => group.map((item) => item.bird_id)), [['a', 'b'], ['c'], ['a']]);
|
||||
assert.deepEqual(finished, [true, true, true, true]);
|
||||
assert.equal(result.sent, 3);
|
||||
});
|
||||
|
||||
test('omits birds whose claim was lost or whose weight changed', async () => {
|
||||
const sent: WeightReminder[][] = [];
|
||||
await runWeightReminders(async (birds) => { sent.push(birds); return true; }, {
|
||||
list: async () => [bird('a'), bird('b')],
|
||||
claim: async (reminder) => reminder.bird_id === 'b', finish: async () => {},
|
||||
});
|
||||
assert.deepEqual(sent.map((group) => group.map((item) => item.bird_id)), [['b']]);
|
||||
});
|
||||
|
||||
test('does not email when all claims are unavailable', async () => {
|
||||
await runWeightReminders(async () => { assert.fail('Unexpected email'); }, {
|
||||
list: async () => [bird('a')], claim: async () => false, finish: async () => {},
|
||||
});
|
||||
});
|
||||
|
||||
test('missing SMTP releases all claims without recording delivery', async () => {
|
||||
const finished: boolean[] = [];
|
||||
const result = await runWeightReminders(async () => false, {
|
||||
list: async () => [bird('a'), bird('b')], claim: async () => true,
|
||||
finish: async (_token, delivered) => { finished.push(delivered); },
|
||||
});
|
||||
assert.deepEqual(finished, [false, false]);
|
||||
assert.equal(result.sent, 0);
|
||||
});
|
||||
|
||||
test('SMTP failure releases claims and still processes other flocks', async () => {
|
||||
const finished: boolean[] = [];
|
||||
const result = await runWeightReminders(async (birds) => {
|
||||
if (birds[0].workspace_id === 1) throw new Error('SMTP unavailable');
|
||||
return true;
|
||||
}, {
|
||||
list: async () => [bird('a'), bird('b'), bird('c', 2)], claim: async () => true,
|
||||
finish: async (_token, delivered) => { finished.push(delivered); },
|
||||
});
|
||||
assert.deepEqual(finished, [false, false, true]);
|
||||
assert.equal(result.sent, 1);
|
||||
assert.equal(result.failed, 1);
|
||||
});
|
||||
@@ -0,0 +1,121 @@
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { db } from '../db/client.js';
|
||||
|
||||
export type WeightReminder = {
|
||||
bird_id: string;
|
||||
workspace_id: number;
|
||||
bird_name: string;
|
||||
workspace_name: string;
|
||||
activity_at: string;
|
||||
recipient: string;
|
||||
};
|
||||
|
||||
// Use entry creation time: recorded_on is a date and cannot measure elapsed hours.
|
||||
// Editing an existing entry does not reset the reminder clock.
|
||||
export const listDueWeightReminders = async () => {
|
||||
const result = await db.query<WeightReminder>(`
|
||||
WITH activity AS (
|
||||
SELECT birds.id AS bird_id, birds.workspace_id, birds.name AS bird_name,
|
||||
workspaces.name AS workspace_name,
|
||||
GREATEST(birds.created_at, COALESCE(MAX(weight_records.created_at), birds.created_at)) AS activity_at
|
||||
FROM birds
|
||||
JOIN workspaces ON workspaces.id = birds.workspace_id
|
||||
LEFT JOIN weight_records ON weight_records.bird_id = birds.id
|
||||
WHERE birds.memorialized_at IS NULL
|
||||
GROUP BY birds.id, workspaces.name
|
||||
), recipients AS (
|
||||
SELECT DISTINCT workspace_id, LOWER(TRIM(users.email)) AS recipient
|
||||
FROM workspace_members
|
||||
JOIN users ON users.id = workspace_members.user_id
|
||||
WHERE accepted_at IS NOT NULL
|
||||
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
|
||||
FROM activity
|
||||
JOIN recipients USING (workspace_id)
|
||||
WHERE activity_at <= CURRENT_TIMESTAMP - INTERVAL '48 hours'
|
||||
AND recipients.recipient <> ''
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM weight_reminder_deliveries d
|
||||
WHERE d.bird_id = activity.bird_id AND d.workspace_id = activity.workspace_id
|
||||
AND d.activity_at = activity.activity_at AND d.recipient = recipients.recipient
|
||||
AND (d.delivered_at > CURRENT_TIMESTAMP - INTERVAL '48 hours'
|
||||
OR (d.delivered_at IS NULL AND d.claimed_at > CURRENT_TIMESTAMP - INTERVAL '15 minutes'))
|
||||
)
|
||||
ORDER BY activity.workspace_id, activity.bird_id, recipients.recipient
|
||||
`);
|
||||
return result.rows;
|
||||
};
|
||||
|
||||
export const claimWeightReminder = async (reminder: WeightReminder, token: string) => {
|
||||
const result = await db.query(`
|
||||
INSERT INTO weight_reminder_deliveries (bird_id, workspace_id, activity_at, recipient, claim_token)
|
||||
SELECT $1, $2, $3, $4, $5
|
||||
WHERE EXISTS (
|
||||
SELECT 1 FROM birds
|
||||
WHERE id = $1 AND workspace_id = $2 AND memorialized_at IS NULL
|
||||
AND GREATEST(created_at, COALESCE((SELECT MAX(created_at) FROM weight_records WHERE bird_id = $1), created_at)) = $3::timestamptz
|
||||
)
|
||||
ON CONFLICT (bird_id, workspace_id, activity_at, recipient) DO UPDATE
|
||||
SET claim_token = EXCLUDED.claim_token, claimed_at = CURRENT_TIMESTAMP, delivered_at = NULL
|
||||
WHERE weight_reminder_deliveries.delivered_at <= CURRENT_TIMESTAMP - INTERVAL '48 hours'
|
||||
OR (weight_reminder_deliveries.delivered_at IS NULL
|
||||
AND weight_reminder_deliveries.claimed_at <= CURRENT_TIMESTAMP - INTERVAL '15 minutes')
|
||||
RETURNING bird_id
|
||||
`, [reminder.bird_id, reminder.workspace_id, reminder.activity_at, reminder.recipient, token]);
|
||||
return Boolean(result.rowCount);
|
||||
};
|
||||
|
||||
export const finishWeightReminder = async (token: string, delivered: boolean) => {
|
||||
if (delivered) {
|
||||
await db.query('UPDATE weight_reminder_deliveries SET delivered_at = CURRENT_TIMESTAMP WHERE claim_token = $1', [token]);
|
||||
} else {
|
||||
await db.query('DELETE FROM weight_reminder_deliveries WHERE claim_token = $1 AND delivered_at IS NULL', [token]);
|
||||
}
|
||||
};
|
||||
|
||||
type Dependencies = {
|
||||
list: typeof listDueWeightReminders;
|
||||
claim: typeof claimWeightReminder;
|
||||
finish: typeof finishWeightReminder;
|
||||
};
|
||||
|
||||
export const runWeightReminders = async (
|
||||
send: (reminders: WeightReminder[]) => Promise<boolean>,
|
||||
dependencies: Dependencies = { list: listDueWeightReminders, claim: claimWeightReminder, finish: finishWeightReminder },
|
||||
) => {
|
||||
const reminders = await dependencies.list();
|
||||
const result = { checked: reminders.length, sent: 0, skipped: 0, failed: 0 };
|
||||
const groups = new Map<string, WeightReminder[]>();
|
||||
for (const reminder of reminders) {
|
||||
const key = JSON.stringify([reminder.workspace_id, reminder.recipient]);
|
||||
groups.set(key, [...(groups.get(key) ?? []), reminder]);
|
||||
}
|
||||
for (const group of groups.values()) {
|
||||
const claimed: { reminder: WeightReminder; token: string }[] = [];
|
||||
let delivered = false;
|
||||
try {
|
||||
for (const reminder of group) {
|
||||
const token = randomUUID();
|
||||
if (await dependencies.claim(reminder, token)) claimed.push({ reminder, token });
|
||||
else result.skipped += 1;
|
||||
}
|
||||
if (!claimed.length) continue;
|
||||
delivered = await send(claimed.map(({ reminder }) => reminder));
|
||||
for (const { token } of claimed) await dependencies.finish(token, delivered);
|
||||
if (delivered) result.sent += 1;
|
||||
else result.skipped += claimed.length;
|
||||
} catch (error) {
|
||||
result.failed += 1;
|
||||
// Keep leases if SMTP accepted the email but saving delivery failed.
|
||||
if (!delivered) {
|
||||
for (const { token } of claimed) {
|
||||
await dependencies.finish(token, false).catch((cleanupError) => console.error('Weight reminder claim cleanup failed', cleanupError));
|
||||
}
|
||||
}
|
||||
console.error(`Weight reminder failed for flock ${group[0].workspace_id}`, error);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
};
|
||||
Reference in new issue
Block a user