feat: scope Telegram reminder tracking to recipients

- keep delegated recipient slots independent\n- bind callback cleanup to the recipient account
This commit is contained in:
Marc-André Bombeck committed 2026-08-06 04:38:09 +02:00
1 parent 5807879439
commit fa46f27b01
6 files changed
+99 -51

No files matched your search

@@ -15,7 +15,6 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
const sendTelegramMessageMock = vi.fn();
const deleteMessageMock = vi.fn();
const findUniqueMock = vi.fn();
const deleteMock = vi.fn();
const upsertMock = vi.fn();
const userFindUniqueMock = vi.fn();
@@ -31,7 +30,6 @@ vi.mock("@/lib/db", () => ({
},
telegramReminderMessage: {
findUnique: (...args: unknown[]) => findUniqueMock(...args),
delete: (...args: unknown[]) => deleteMock(...args),
upsert: (...args: unknown[]) => upsertMock(...args),
},
},
@@ -79,7 +77,6 @@ describe("sendViaTelegram — per-slot delete scope (H2)", () => {
sendTelegramMessageMock.mockResolvedValue({ ok: true, messageId: 999 });
deleteMessageMock.mockResolvedValue(undefined);
findUniqueMock.mockResolvedValue(null);
deleteMock.mockResolvedValue(undefined);
upsertMock.mockResolvedValue(undefined);
userFindUniqueMock.mockResolvedValue({ locale: "en" });
scheduleTelegramAutoDeleteMock.mockResolvedValue(undefined);
@@ -107,7 +104,7 @@ describe("sendViaTelegram — per-slot delete scope (H2)", () => {
});
});
it("deletes only the matching slot's ledger row, leaving sibling slots untouched", async () => {
it("replaces only the matching slot's remote message, leaving its tracking row for update", async () => {
// The 20:00 slot has a prior row; the lookup returns it.
findUniqueMock.mockResolvedValue({
chatId: "chat-1",
@@ -118,20 +115,22 @@ describe("sendViaTelegram — per-slot delete scope (H2)", () => {
// The Telegram message for the old 20:00 row is deleted...
expect(deleteMessageMock).toHaveBeenCalledWith("bot-token", "chat-1", 123);
// ...and exactly that single ledger row is removed (scoped delete, not deleteMany).
expect(deleteMock).toHaveBeenCalledTimes(1);
expect(deleteMock).toHaveBeenCalledWith({
where: {
recipientUserId_medicationId_scheduleId_date_phase_timeOfDay: {
recipientUserId: "user-1",
medicationId: "med-1",
scheduleId: "sched-1",
date: "2025-06-10",
phase: "YELLOW",
timeOfDay: "20:00",
// The tracking row stays in place so the recipient-scoped upsert updates
// it rather than creating a second row when the chat binding changes.
expect(upsertMock).toHaveBeenCalledWith(
expect.objectContaining({
where: {
recipientUserId_medicationId_scheduleId_date_phase_timeOfDay: {
recipientUserId: "user-1",
medicationId: "med-1",
scheduleId: "sched-1",
date: "2025-06-10",
phase: "YELLOW",
timeOfDay: "20:00",
},
},
},
});
}),
);
});
it("does not delete anything when no prior row exists for the slot", async () => {
@@ -140,7 +139,6 @@ describe("sendViaTelegram — per-slot delete scope (H2)", () => {
await sendViaTelegram(config, reminderPayload());
expect(deleteMessageMock).not.toHaveBeenCalled();
expect(deleteMock).not.toHaveBeenCalled();
// It still sends + tracks the new message.
expect(sendTelegramMessageMock).toHaveBeenCalledTimes(1);
expect(upsertMock).toHaveBeenCalledTimes(1);
@@ -155,7 +153,6 @@ describe("sendViaTelegram — per-slot delete scope (H2)", () => {
);
expect(findUniqueMock).not.toHaveBeenCalled();
expect(deleteMock).not.toHaveBeenCalled();
});
it("keeps two recipients' identical subject slots independent", async () => {
+8 -14
View File
@@ -52,7 +52,7 @@ export interface TelegramSendResult extends SendOutcome {
/**
* Delete the existing Telegram reminder message for a single dose slot
* before re-sending it. v1.7.0 SB-SCHED-4 — scoped to the exact slot
* `{ medicationId, scheduleId, date, phase, timeOfDay }` (the same
* `{ recipientUserId, medicationId, scheduleId, date, phase, timeOfDay }` (the same
* composite the tracking upsert keys on), NOT the whole medication. A
* medication with `timesOfDay = ["08:00","20:00"]` has two distinct
* ledger rows per day; the pre-v1.7 whole-medication wipe deleted the
@@ -62,6 +62,7 @@ export interface TelegramSendResult extends SendOutcome {
*/
async function deleteExistingReminders(
botToken: string,
recipientUserId: string,
medicationId: string,
scheduleId: string,
date: string,
@@ -71,7 +72,8 @@ async function deleteExistingReminders(
try {
const existing = await prisma.telegramReminderMessage.findUnique({
where: {
medicationId_scheduleId_date_phase_timeOfDay: {
recipientUserId_medicationId_scheduleId_date_phase_timeOfDay: {
recipientUserId,
medicationId,
scheduleId,
date,
@@ -89,17 +91,6 @@ async function deleteExistingReminders(
// Best-effort: message may already be deleted
}
await prisma.telegramReminderMessage.delete({
where: {
medicationId_scheduleId_date_phase_timeOfDay: {
medicationId,
scheduleId,
date,
phase,
timeOfDay,
},
},
});
} catch (err) {
getEvent()?.addWarning(`Failed to delete existing reminders: ${err}`);
}
@@ -136,6 +127,7 @@ export async function sendViaTelegram(
if (medicationId && scheduleId && phase && date) {
await deleteExistingReminders(
config.botToken,
userId,
medicationId,
scheduleId,
date,
@@ -220,7 +212,8 @@ export async function sendViaTelegram(
try {
await prisma.telegramReminderMessage.upsert({
where: {
medicationId_scheduleId_date_phase_timeOfDay: {
recipientUserId_medicationId_scheduleId_date_phase_timeOfDay: {
recipientUserId: userId,
medicationId,
scheduleId,
date,
@@ -229,6 +222,7 @@ export async function sendViaTelegram(
},
},
create: {
recipientUserId: userId,
medicationId,
scheduleId,
chatId: config.chatId,
+14 -6
View File
@@ -90,10 +90,17 @@ function resolveBotLocale(value: string | null | undefined): Locale {
return "de";
}
async function cleanupReminderTracking(medicationId: string): Promise<void> {
async function cleanupReminderTracking(
recipientUserId: string,
medicationId: string,
): Promise<void> {
try {
await prisma.telegramReminderMessage.deleteMany({
where: { medicationId },
where: {
recipientUserId,
medicationId,
medication: { userId: recipientUserId },
},
});
} catch {
// Best-effort cleanup
@@ -153,6 +160,7 @@ async function resolveReminderSlot(input: {
}): Promise<Date | null> {
const reminder = await prisma.telegramReminderMessage.findFirst({
where: {
recipientUserId: input.userId,
medicationId: input.medicationId,
chatId: input.chatId,
messageId: input.messageId,
@@ -398,7 +406,7 @@ export async function handleCallback(update: TelegramUpdate) {
if (messageId) {
await deleteMessage(botToken, chatId, messageId);
}
await cleanupReminderTracking(medicationId);
await cleanupReminderTracking(user.id, medicationId);
} else if (data.startsWith("snooze:")) {
// Format: "snooze:{medicationId}:{minutes}"
const parts = data.split(":");
@@ -443,7 +451,7 @@ export async function handleCallback(update: TelegramUpdate) {
if (messageId) {
await deleteMessage(botToken, chatId, messageId);
}
await cleanupReminderTracking(medicationId);
await cleanupReminderTracking(user.id, medicationId);
} else if (data.startsWith("skip:")) {
const medicationId = data.slice("skip:".length).trim();
if (!medicationId) {
@@ -586,7 +594,7 @@ export async function handleCallback(update: TelegramUpdate) {
if (messageId) {
await deleteMessage(botToken, chatId, messageId);
}
await cleanupReminderTracking(medicationId);
await cleanupReminderTracking(user.id, medicationId);
} else if (data.startsWith("ack:")) {
const medicationId = data.slice("ack:".length).trim();
if (!medicationId) {
@@ -613,7 +621,7 @@ export async function handleCallback(update: TelegramUpdate) {
if (messageId) {
await deleteMessage(botToken, chatId, messageId);
}
await cleanupReminderTracking(medicationId);
await cleanupReminderTracking(user.id, medicationId);
} else if (data.startsWith("add:")) {
// Format: "add:{medicationId}" or "add:{medicationId}:umid:{userMsgId}"
const withoutPrefix = data.slice("add:".length);