303 lines
11 KiB
TypeScript
303 lines
11 KiB
TypeScript
import type { PrismaClient } from "../generated/prisma/client/client.js";
|
|
import { renderSystemMessageEmail } from "@hivegrid/mail";
|
|
import { writeAdminSalesAudit } from "./admin-sales-core.server.js";
|
|
|
|
type AdminBookingReminderClient = Pick<PrismaClient, "$transaction" | "adminBookingReminder">;
|
|
|
|
export async function runAdminBookingReminderSweep(
|
|
client: AdminBookingReminderClient,
|
|
input: {
|
|
readonly now: Date;
|
|
readonly take?: number;
|
|
}
|
|
): Promise<{
|
|
readonly scanned: number;
|
|
readonly dispatched: number;
|
|
readonly failed: number;
|
|
}> {
|
|
const take = Math.min(Math.max(Math.floor(input.take ?? 250), 1), 1_000);
|
|
const due = await client.adminBookingReminder.findMany({
|
|
where: {
|
|
status: { in: ["pending", "failed"] },
|
|
scheduledFor: { lte: input.now },
|
|
attemptCount: { lt: 5 },
|
|
booking: {
|
|
status: { in: ["reserved", "confirmed", "provider_sync_failed"] },
|
|
startsAt: { gt: input.now },
|
|
},
|
|
},
|
|
orderBy: [{ scheduledFor: "asc" }, { id: "asc" }],
|
|
take,
|
|
select: { id: true },
|
|
});
|
|
|
|
let dispatched = 0;
|
|
let failed = 0;
|
|
for (const candidate of due) {
|
|
const result = await client
|
|
.$transaction(async (tx) => {
|
|
const claimed = await tx.adminBookingReminder.updateMany({
|
|
where: {
|
|
id: candidate.id,
|
|
status: { in: ["pending", "failed"] },
|
|
attemptCount: { lt: 5 },
|
|
},
|
|
data: { status: "processing", attemptCount: { increment: 1 } },
|
|
});
|
|
if (claimed.count !== 1) return "skipped" as const;
|
|
|
|
const reminder = await tx.adminBookingReminder.findUnique({
|
|
where: { id: candidate.id },
|
|
include: {
|
|
booking: {
|
|
include: {
|
|
meetingType: { select: { name: true } },
|
|
participants: {
|
|
where: { isOrganizer: false },
|
|
orderBy: [{ createdAt: "asc" }, { id: "asc" }],
|
|
take: 1,
|
|
select: { email: true, name: true, locale: true },
|
|
},
|
|
},
|
|
},
|
|
},
|
|
});
|
|
if (!reminder) return "skipped" as const;
|
|
|
|
const [mailbox, policy] = await Promise.all([
|
|
tx.adminMailbox.findFirst({
|
|
where: {
|
|
adminUserId: reminder.adminUserId,
|
|
status: "active",
|
|
archivedAt: null,
|
|
},
|
|
orderBy: [{ createdAt: "asc" }, { id: "asc" }],
|
|
select: { id: true },
|
|
}),
|
|
tx.adminEmailOutboundPolicy.findUnique({
|
|
where: { adminUserId: reminder.adminUserId },
|
|
select: {
|
|
configuredAt: true,
|
|
consentRulesConfigured: true,
|
|
dailySendLimit: true,
|
|
allowedWeekDays: true,
|
|
workdayStartMinutes: true,
|
|
workdayEndMinutes: true,
|
|
},
|
|
}),
|
|
]);
|
|
const participant = reminder.booking.participants[0];
|
|
if (!mailbox || !participant || !outboundConfigured(policy)) {
|
|
await tx.adminBookingReminder.update({
|
|
where: { id: reminder.id },
|
|
data: {
|
|
status: "failed",
|
|
lastErrorCode: !participant ? "participant_unavailable" : !mailbox ? "mailbox_unavailable" : "outbound_locked",
|
|
},
|
|
});
|
|
return "failed" as const;
|
|
}
|
|
|
|
const copy = buildAdminBookingReminderCopy({
|
|
locale: participant.locale,
|
|
participantName: participant.name,
|
|
meetingName: reminder.booking.meetingType.name,
|
|
startsAt: reminder.booking.startsAt,
|
|
timeZone: reminder.booking.bookerTimeZone,
|
|
});
|
|
await tx.adminScheduledEmail.upsert({
|
|
where: { idempotencyKey: `booking-reminder:${reminder.id}` },
|
|
create: {
|
|
adminUserId: reminder.adminUserId,
|
|
mailboxId: mailbox.id,
|
|
contactId: reminder.booking.contactId,
|
|
dealId: reminder.booking.dealId,
|
|
toAddresses: [participant.email],
|
|
subject: copy.subject,
|
|
bodyHtml: copy.html,
|
|
bodyText: copy.text,
|
|
scheduledFor: input.now,
|
|
timeZone: reminder.booking.bookerTimeZone,
|
|
status: "queued",
|
|
idempotencyKey: `booking-reminder:${reminder.id}`,
|
|
},
|
|
update: {},
|
|
});
|
|
await tx.adminBookingReminder.update({
|
|
where: { id: reminder.id },
|
|
data: {
|
|
status: "sent",
|
|
sentAt: input.now,
|
|
lastErrorCode: null,
|
|
},
|
|
});
|
|
await tx.adminActivity.create({
|
|
data: {
|
|
type: "meeting",
|
|
actorAdminUserId: reminder.adminUserId,
|
|
contactId: reminder.booking.contactId,
|
|
dealId: reminder.booking.dealId,
|
|
bookingId: reminder.booking.id,
|
|
summary: "Termin-Erinnerung an zentralen Mailpfad übergeben",
|
|
payload: {
|
|
reminderId: reminder.id,
|
|
offsetMinutes: reminder.offsetMinutes,
|
|
},
|
|
},
|
|
});
|
|
await writeAdminSalesAudit(tx, {
|
|
actor: {
|
|
adminUserId: reminder.adminUserId,
|
|
reason: "Automatische Termin-Erinnerung",
|
|
},
|
|
action: "admin.sales.booking.reminder.dispatched",
|
|
targetType: "AdminBookingReminder",
|
|
targetId: reminder.id,
|
|
after: {
|
|
bookingId: reminder.booking.id,
|
|
offsetMinutes: reminder.offsetMinutes,
|
|
},
|
|
});
|
|
return "dispatched" as const;
|
|
})
|
|
.catch(async () => {
|
|
await client.adminBookingReminder
|
|
.updateMany({
|
|
where: { id: candidate.id, status: "processing" },
|
|
data: {
|
|
status: "failed",
|
|
lastErrorCode: "delivery_queue_failed",
|
|
},
|
|
})
|
|
.catch(() => undefined);
|
|
return "failed" as const;
|
|
});
|
|
if (result === "dispatched") dispatched += 1;
|
|
if (result === "failed") failed += 1;
|
|
}
|
|
return { scanned: due.length, dispatched, failed };
|
|
}
|
|
|
|
function outboundConfigured(
|
|
policy: {
|
|
readonly configuredAt: Date | null;
|
|
readonly consentRulesConfigured: boolean;
|
|
readonly dailySendLimit: number;
|
|
readonly allowedWeekDays: readonly number[];
|
|
readonly workdayStartMinutes: number;
|
|
readonly workdayEndMinutes: number;
|
|
} | null
|
|
): boolean {
|
|
return Boolean(
|
|
policy?.configuredAt &&
|
|
policy.consentRulesConfigured &&
|
|
policy.dailySendLimit > 0 &&
|
|
policy.allowedWeekDays.length > 0 &&
|
|
policy.workdayStartMinutes < policy.workdayEndMinutes
|
|
);
|
|
}
|
|
|
|
type BookingReminderLocale = "de" | "en" | "pl" | "ru" | "uk" | "hu";
|
|
|
|
const bookingReminderLocaleTags: Readonly<Record<BookingReminderLocale, string>> = {
|
|
de: "de-DE",
|
|
en: "en-GB",
|
|
hu: "hu-HU",
|
|
pl: "pl-PL",
|
|
ru: "ru-RU",
|
|
uk: "uk-UA",
|
|
};
|
|
|
|
function normalizeBookingReminderLocale(locale: string | null): BookingReminderLocale {
|
|
const language = locale?.trim().toLowerCase().split(/[-_]/u)[0];
|
|
return language && language in bookingReminderLocaleTags ? (language as BookingReminderLocale) : "de";
|
|
}
|
|
|
|
export function buildAdminBookingReminderCopy(input: {
|
|
readonly locale: string | null;
|
|
readonly participantName: string;
|
|
readonly meetingName: string;
|
|
readonly startsAt: Date;
|
|
readonly timeZone: string;
|
|
}): { readonly subject: string; readonly text: string; readonly html: string } {
|
|
const locale = normalizeBookingReminderLocale(input.locale);
|
|
const startsAt = new Intl.DateTimeFormat(bookingReminderLocaleTags[locale], {
|
|
dateStyle: "full",
|
|
timeStyle: "short",
|
|
timeZone: input.timeZone,
|
|
}).format(input.startsAt);
|
|
const copy = {
|
|
de: {
|
|
subject: `Erinnerung: ${input.meetingName}`,
|
|
eyebrow: "Terminerinnerung",
|
|
title: `Bis bald, ${input.participantName}`,
|
|
intro: "Dein Termin steht bald an. Hier findest du die wichtigsten Informationen auf einen Blick.",
|
|
meetingLabel: "Termin",
|
|
timeLabel: "Beginn",
|
|
notice: "Falls sich etwas geändert hat, melde dich bitte direkt bei deinem Ansprechpartner.",
|
|
},
|
|
en: {
|
|
subject: `Reminder: ${input.meetingName}`,
|
|
eyebrow: "Appointment reminder",
|
|
title: `See you soon, ${input.participantName}`,
|
|
intro: "Your appointment is coming up. Here are the key details at a glance.",
|
|
meetingLabel: "Appointment",
|
|
timeLabel: "Starts",
|
|
notice: "If anything has changed, please contact your point of contact directly.",
|
|
},
|
|
hu: {
|
|
subject: `Emlékeztető: ${input.meetingName}`,
|
|
eyebrow: "Időpont-emlékeztető",
|
|
title: `Hamarosan találkozunk, ${input.participantName}`,
|
|
intro: "Hamarosan kezdődik az időpontod. Itt találod a legfontosabb részleteket.",
|
|
meetingLabel: "Időpont",
|
|
timeLabel: "Kezdés",
|
|
notice: "Ha közben változott valami, keresd közvetlenül a kapcsolattartódat.",
|
|
},
|
|
pl: {
|
|
subject: `Przypomnienie: ${input.meetingName}`,
|
|
eyebrow: "Przypomnienie o spotkaniu",
|
|
title: `Do zobaczenia wkrótce, ${input.participantName}`,
|
|
intro: "Twoje spotkanie odbędzie się już niedługo. Najważniejsze informacje znajdziesz poniżej.",
|
|
meetingLabel: "Spotkanie",
|
|
timeLabel: "Początek",
|
|
notice: "Jeśli coś się zmieniło, skontaktuj się bezpośrednio ze swoją osobą kontaktową.",
|
|
},
|
|
ru: {
|
|
subject: `Напоминание: ${input.meetingName}`,
|
|
eyebrow: "Напоминание о встрече",
|
|
title: `До скорой встречи, ${input.participantName}`,
|
|
intro: "Ваша встреча скоро начнётся. Ниже собраны основные сведения.",
|
|
meetingLabel: "Встреча",
|
|
timeLabel: "Начало",
|
|
notice: "Если что-то изменилось, свяжитесь напрямую со своим контактным лицом.",
|
|
},
|
|
uk: {
|
|
subject: `Нагадування: ${input.meetingName}`,
|
|
eyebrow: "Нагадування про зустріч",
|
|
title: `До скорої зустрічі, ${input.participantName}`,
|
|
intro: "Ваша зустріч уже скоро. Нижче зібрано найважливіші відомості.",
|
|
meetingLabel: "Зустріч",
|
|
timeLabel: "Початок",
|
|
notice: "Якщо щось змінилося, зверніться безпосередньо до своєї контактної особи.",
|
|
},
|
|
}[locale];
|
|
const rendered = renderSystemMessageEmail({
|
|
locale,
|
|
subject: copy.subject,
|
|
eyebrow: copy.eyebrow,
|
|
title: copy.title,
|
|
intro: copy.intro,
|
|
details: [
|
|
{ label: copy.meetingLabel, value: input.meetingName },
|
|
{ label: copy.timeLabel, value: startsAt },
|
|
],
|
|
notice: copy.notice,
|
|
});
|
|
return {
|
|
subject: copy.subject,
|
|
text: rendered.text,
|
|
html: rendered.html,
|
|
};
|
|
}
|