Files
BarevClub/packages/services/src/reminders.ts
T
2026-10-17 19:45:51 +04:00

35 lines
1.5 KiB
TypeScript

import { HOUR } from '@barev/core';
import type { Ctx } from './context.ts';
const FINAL = ['CANCELLED', 'DONE', 'COMPLETED', 'PLAN_SENT'] as const;
/**
* MSG-2: напоминания за 24 часа и за 1 час. Отметка reminded*At делает обработку идемпотентной:
* воркер может запускать её каждую минуту. Заказы, созданные позже чем за 24 ч, получают только часовое.
*/
export async function dueReminders(ctx: Ctx): Promise<number> {
const now = ctx.now();
let sent = 0;
for (const hours of [24, 1] as const) {
const field = hours === 24 ? 'reminded24hAt' : 'reminded1hAt';
const due = await ctx.db.order.findMany({
where: {
status: { notIn: [...FINAL] },
[field]: null,
scheduledAt: { gt: now, lte: new Date(now.getTime() + hours * HOUR) },
// 24-часовое не шлём, если до начала уже меньше часа — придёт часовое
...(hours === 24 ? { NOT: { scheduledAt: { lte: new Date(now.getTime() + HOUR) } } } : {}),
},
select: { id: true },
});
for (const { id } of due) {
const { count } = await ctx.db.order.updateMany({ where: { id, [field]: null }, data: { [field]: now } });
if (count === 1) {
await ctx.notify.emit({ type: 'order.reminder', orderId: id, hours });
sent++;
}
}
}
return sent;
}