Refresh HiveGrid Cloud reference snapshot
This commit is contained in:
1 parent
5e99e14772
commit
7f88026f79
5955 files changed
+1177325
-188362
No files matched your search
+171
-19
@@ -8,10 +8,14 @@
|
||||
|
||||
import { formatInTimeZone } from "date-fns-tz";
|
||||
import { logActivity, type ActivityType } from "@hivegrid/activity";
|
||||
import { publishOutboxEvent, type OutboxPublisherTransaction } from "@hivegrid/db/outbox";
|
||||
import { notify, type NotificationClient } from "@hivegrid/foundation";
|
||||
import { renderSystemMessageEmail, type SystemMessageDetail } from "@hivegrid/mail";
|
||||
import { getMailTranslator, type MailTranslator } from "~/locale/mail-translator.server";
|
||||
import { db } from "~/utils/db.server";
|
||||
import { sendEmailMailjet } from "~/modules/emails/services/MailjetEmailService";
|
||||
import { assertTransition, statusAfter, notifiesCustomer, type LifecycleAction } from "./bookingTransitions";
|
||||
import { buildBookingCancelledWorkflowEvent, buildCalendarCreatedWorkflowEvent } from "./bookingAutomationEvents.server";
|
||||
|
||||
const MINUTE_MS = 60_000;
|
||||
|
||||
@@ -27,6 +31,7 @@ interface AppointmentForAction {
|
||||
internalCalendarEventId: string | null;
|
||||
intakeAnswers: unknown;
|
||||
pageTitle: string;
|
||||
bookingPageSlug: string;
|
||||
durationMinutes: number;
|
||||
tenantName: string;
|
||||
}
|
||||
@@ -45,7 +50,7 @@ async function loadAppointmentForAction(tenantId: string, appointmentId: string)
|
||||
timezone: true,
|
||||
internalCalendarEventId: true,
|
||||
intakeAnswers: true,
|
||||
bookingPage: { select: { title: true, durationMinutes: true } },
|
||||
bookingPage: { select: { title: true, slug: true, durationMinutes: true } },
|
||||
},
|
||||
});
|
||||
if (!row) {
|
||||
@@ -64,6 +69,7 @@ async function loadAppointmentForAction(tenantId: string, appointmentId: string)
|
||||
internalCalendarEventId: row.internalCalendarEventId,
|
||||
intakeAnswers: row.intakeAnswers,
|
||||
pageTitle: row.bookingPage.title,
|
||||
bookingPageSlug: row.bookingPage.slug,
|
||||
durationMinutes: row.bookingPage.durationMinutes,
|
||||
tenantName: tenant?.name ?? "",
|
||||
};
|
||||
@@ -77,7 +83,21 @@ function bookerEmail(intakeAnswers: unknown): string | null {
|
||||
return null;
|
||||
}
|
||||
|
||||
async function recordActivity(tenantId: string, appt: AppointmentForAction, activityType: ActivityType, summaryText: string, actorUserId: string | null): Promise<void> {
|
||||
function bookerLocale(intakeAnswers: unknown): string | null {
|
||||
if (intakeAnswers && typeof intakeAnswers === "object" && "locale" in intakeAnswers) {
|
||||
const locale = (intakeAnswers as { locale?: unknown }).locale;
|
||||
return typeof locale === "string" && locale.trim() ? locale.trim() : null;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
async function recordActivity(
|
||||
tenantId: string,
|
||||
appt: AppointmentForAction,
|
||||
activityType: ActivityType,
|
||||
summaryText: string,
|
||||
actorUserId: string | null
|
||||
): Promise<void> {
|
||||
if (!appt.kontaktId) {
|
||||
return;
|
||||
}
|
||||
@@ -95,39 +115,114 @@ async function recordActivity(tenantId: string, appt: AppointmentForAction, acti
|
||||
|
||||
async function notifyProvider(tenantId: string, providerUserId: string, messageKey: string, appointmentId: string): Promise<void> {
|
||||
await notify(
|
||||
{ tenantId, userId: providerUserId, channel: "IN_APP", category: "bookings", messageKey, sourceKey: `${messageKey}:${appointmentId}`, payloadMetadata: { appointmentId } },
|
||||
{
|
||||
tenantId,
|
||||
userId: providerUserId,
|
||||
channel: "IN_APP",
|
||||
category: "bookings",
|
||||
messageKey,
|
||||
sourceKey: `${messageKey}:${appointmentId}`,
|
||||
payloadMetadata: { appointmentId },
|
||||
},
|
||||
db as unknown as NotificationClient
|
||||
).catch(() => undefined);
|
||||
}
|
||||
|
||||
async function sendLifecycleMail(appt: AppointmentForAction, subject: string, body: string): Promise<boolean> {
|
||||
async function sendLifecycleMail(
|
||||
appt: AppointmentForAction,
|
||||
input: {
|
||||
readonly kind: "cancelled" | "reassigned" | "rescheduled";
|
||||
readonly newWhen?: string;
|
||||
readonly reason?: string;
|
||||
}
|
||||
): Promise<boolean> {
|
||||
const to = bookerEmail(appt.intakeAnswers);
|
||||
if (!to) {
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
await sendEmailMailjet({ data: { to, subject, body: body.replace(/\r?\n/gu, "<br/>") } });
|
||||
const { t, locale } = await getMailTranslator(bookerLocale(appt.intakeAnswers));
|
||||
const content = lifecycleMailContent(t, appt, input);
|
||||
const rendered = renderSystemMessageEmail({
|
||||
locale,
|
||||
subject: content.subject,
|
||||
previewText: content.intro,
|
||||
eyebrow: content.eyebrow,
|
||||
title: content.title,
|
||||
intro: content.intro,
|
||||
details: content.details,
|
||||
notice: content.notice,
|
||||
noticeTone: content.notice ? "info" : undefined,
|
||||
});
|
||||
await sendEmailMailjet({
|
||||
data: {
|
||||
to,
|
||||
subject: content.subject,
|
||||
body: rendered.html,
|
||||
text: rendered.text,
|
||||
},
|
||||
});
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function lifecycleMailContent(
|
||||
t: MailTranslator,
|
||||
appt: AppointmentForAction,
|
||||
input: {
|
||||
readonly kind: "cancelled" | "reassigned" | "rescheduled";
|
||||
readonly newWhen?: string;
|
||||
readonly reason?: string;
|
||||
}
|
||||
): {
|
||||
readonly subject: string;
|
||||
readonly eyebrow: string;
|
||||
readonly title: string;
|
||||
readonly intro: string;
|
||||
readonly details: readonly SystemMessageDetail[];
|
||||
readonly notice?: string;
|
||||
} {
|
||||
const prefix = `booking.${input.kind}`;
|
||||
const details: SystemMessageDetail[] = [{ label: t(`${prefix}.fields.appointment`), value: appt.pageTitle }];
|
||||
if (input.kind === "rescheduled") {
|
||||
details.push({ label: t(`${prefix}.fields.previous`), value: whenLabel(appt) }, { label: t(`${prefix}.fields.new`), value: input.newWhen ?? "" });
|
||||
} else {
|
||||
details.push({ label: t(`${prefix}.fields.when`), value: whenLabel(appt) });
|
||||
}
|
||||
return {
|
||||
subject: t(`${prefix}.subject`, { title: appt.pageTitle }),
|
||||
eyebrow: t(`${prefix}.eyebrow`),
|
||||
title: t(`${prefix}.title`),
|
||||
intro: t(`${prefix}.intro`),
|
||||
details,
|
||||
notice: input.reason ? t(`${prefix}.reason`, { reason: input.reason }) : undefined,
|
||||
};
|
||||
}
|
||||
|
||||
function whenLabel(appt: AppointmentForAction): string {
|
||||
return formatInTimeZone(appt.startAt, appt.timezone, "dd.MM.yyyy HH:mm");
|
||||
}
|
||||
|
||||
/** Mark a past appointment as held (M06 D). */
|
||||
export async function markAppointmentHeld(tenantId: string, appointmentId: string, actorUserId: string): Promise<void> {
|
||||
await applyStatusOnly(tenantId, appointmentId, "mark_held", actorUserId, "appointment_held", "als stattgefunden markiert");
|
||||
await applyStatusOnly(tenantId, appointmentId, "mark_held", actorUserId, "appointment_held", "activity.runtime.booking.held");
|
||||
}
|
||||
|
||||
/** Mark an appointment as no-show (M06 D). */
|
||||
export async function markAppointmentNoShow(tenantId: string, appointmentId: string, actorUserId: string): Promise<void> {
|
||||
await applyStatusOnly(tenantId, appointmentId, "mark_no_show", actorUserId, "appointment_no_show", "als nicht erschienen markiert");
|
||||
await applyStatusOnly(tenantId, appointmentId, "mark_no_show", actorUserId, "appointment_no_show", "activity.runtime.booking.noShow");
|
||||
}
|
||||
|
||||
async function applyStatusOnly(tenantId: string, appointmentId: string, action: LifecycleAction, actorUserId: string, activityType: ActivityType, summaryVerb: string): Promise<void> {
|
||||
async function applyStatusOnly(
|
||||
tenantId: string,
|
||||
appointmentId: string,
|
||||
action: LifecycleAction,
|
||||
actorUserId: string,
|
||||
activityType: ActivityType,
|
||||
summaryKey: string
|
||||
): Promise<void> {
|
||||
const appt = await loadAppointmentForAction(tenantId, appointmentId);
|
||||
if (!appt) {
|
||||
return;
|
||||
@@ -137,35 +232,64 @@ async function applyStatusOnly(tenantId: string, appointmentId: string, action:
|
||||
if (next) {
|
||||
await db.appointment.update({ where: { id: appt.id }, data: { status: next } });
|
||||
}
|
||||
await recordActivity(tenantId, appt, activityType, `Termin ${appt.pageTitle} (${whenLabel(appt)}) ${summaryVerb}`, actorUserId);
|
||||
await recordActivity(tenantId, appt, activityType, summaryKey, actorUserId);
|
||||
}
|
||||
|
||||
/** Cancel an appointment with a reason + auto-mail (M06 D / I). */
|
||||
export async function cancelAppointment(input: { tenantId: string; appointmentId: string; reason: string; byKind: "customer" | "provider" | "system"; actorUserId: string | null }): Promise<void> {
|
||||
export async function cancelAppointment(input: {
|
||||
tenantId: string;
|
||||
appointmentId: string;
|
||||
reason: string;
|
||||
byKind: "customer" | "provider" | "system";
|
||||
actorUserId: string | null;
|
||||
}): Promise<void> {
|
||||
const appt = await loadAppointmentForAction(input.tenantId, input.appointmentId);
|
||||
if (!appt) {
|
||||
return;
|
||||
}
|
||||
assertTransition(appt.status, "cancel");
|
||||
const cancelledAt = new Date();
|
||||
await db.$transaction(async (tx) => {
|
||||
await tx.appointment.update({
|
||||
where: { id: appt.id },
|
||||
data: { status: "cancelled", cancelledAt: new Date(), cancelledByKind: input.byKind, cancellationReason: input.reason },
|
||||
data: { status: "cancelled", cancelledAt, cancelledByKind: input.byKind, cancellationReason: input.reason },
|
||||
});
|
||||
if (appt.internalCalendarEventId) {
|
||||
// Free the slot: archive the local mirror so it stops blocking availability.
|
||||
await tx.calendarEvent.update({ where: { id: appt.internalCalendarEventId }, data: { archivedAt: new Date(), isBusyForAvailability: false } });
|
||||
}
|
||||
await publishOutboxEvent(
|
||||
tx as unknown as OutboxPublisherTransaction,
|
||||
buildBookingCancelledWorkflowEvent({
|
||||
tenantId: input.tenantId,
|
||||
appointmentId: appt.id,
|
||||
bookingPageId: appt.bookingPageId,
|
||||
bookingPageSlug: appt.bookingPageSlug,
|
||||
providerUserId: appt.providerUserId,
|
||||
cancelledByKind: input.byKind,
|
||||
cancellationReason: input.reason,
|
||||
cancelledAt,
|
||||
actorUserId: input.actorUserId,
|
||||
})
|
||||
);
|
||||
});
|
||||
await sendLifecycleMail(appt, `Termin storniert: ${appt.pageTitle}`, `Dein Termin am ${whenLabel(appt)} wurde storniert.\nGrund: ${input.reason}`);
|
||||
await recordActivity(input.tenantId, appt, "appointment_cancelled", `Termin ${appt.pageTitle} (${whenLabel(appt)}) storniert: ${input.reason}`, input.actorUserId);
|
||||
await sendLifecycleMail(appt, {
|
||||
kind: "cancelled",
|
||||
reason: input.reason,
|
||||
});
|
||||
await recordActivity(input.tenantId, appt, "appointment_cancelled", "activity.runtime.booking.cancelled", input.actorUserId);
|
||||
if (notifiesCustomer("cancel")) {
|
||||
await notifyProvider(input.tenantId, appt.providerUserId, "bookings.status.cancelled", appt.id);
|
||||
}
|
||||
}
|
||||
|
||||
/** Reschedule to a new start time: supersede the old appointment with a successor (M06 D). */
|
||||
export async function rescheduleAppointment(input: { tenantId: string; appointmentId: string; newStartAt: Date; actorUserId: string }): Promise<{ newAppointmentId: string }> {
|
||||
export async function rescheduleAppointment(input: {
|
||||
tenantId: string;
|
||||
appointmentId: string;
|
||||
newStartAt: Date;
|
||||
actorUserId: string;
|
||||
}): Promise<{ newAppointmentId: string }> {
|
||||
const appt = await loadAppointmentForAction(input.tenantId, input.appointmentId);
|
||||
if (!appt) {
|
||||
throw new Error("appointment_not_found");
|
||||
@@ -194,16 +318,42 @@ export async function rescheduleAppointment(input: { tenantId: string; appointme
|
||||
select: { id: true },
|
||||
});
|
||||
const calendarEvent = await tx.calendarEvent.create({
|
||||
data: { tenantId: input.tenantId, userId: appt.providerUserId, source: "hivegrid_internal", title: appt.pageTitle, startsAt: input.newStartAt, endsAt: newEndAt, isBusyForAvailability: true, internalEntityLink: { type: "booking_appointment", id: successor.id } },
|
||||
data: {
|
||||
tenantId: input.tenantId,
|
||||
userId: appt.providerUserId,
|
||||
source: "hivegrid_internal",
|
||||
title: appt.pageTitle,
|
||||
startsAt: input.newStartAt,
|
||||
endsAt: newEndAt,
|
||||
isBusyForAvailability: true,
|
||||
internalEntityLink: { type: "booking_appointment", id: successor.id },
|
||||
},
|
||||
select: { id: true },
|
||||
});
|
||||
await tx.appointment.update({ where: { id: successor.id }, data: { internalCalendarEventId: calendarEvent.id } });
|
||||
await publishOutboxEvent(
|
||||
tx as unknown as OutboxPublisherTransaction,
|
||||
buildCalendarCreatedWorkflowEvent({
|
||||
tenantId: input.tenantId,
|
||||
calendarEventId: calendarEvent.id,
|
||||
userId: input.actorUserId,
|
||||
calendarKey: "hauptkalender",
|
||||
eventKind: "termin",
|
||||
source: "booking_reschedule",
|
||||
sourceEntityId: successor.id,
|
||||
startsAt: input.newStartAt,
|
||||
endsAt: newEndAt,
|
||||
})
|
||||
);
|
||||
return successor.id;
|
||||
});
|
||||
|
||||
const newWhen = formatInTimeZone(input.newStartAt, appt.timezone, "dd.MM.yyyy HH:mm");
|
||||
await sendLifecycleMail(appt, `Termin verschoben: ${appt.pageTitle}`, `Dein Termin wurde von ${whenLabel(appt)} auf ${newWhen} verschoben.`);
|
||||
await recordActivity(input.tenantId, appt, "appointment_rescheduled", `Termin ${appt.pageTitle} verschoben von ${whenLabel(appt)} auf ${newWhen}`, input.actorUserId);
|
||||
await sendLifecycleMail(appt, {
|
||||
kind: "rescheduled",
|
||||
newWhen,
|
||||
});
|
||||
await recordActivity(input.tenantId, appt, "appointment_rescheduled", "activity.runtime.booking.rescheduled", input.actorUserId);
|
||||
await notifyProvider(input.tenantId, appt.providerUserId, "bookings.status.rescheduled", newAppointmentId);
|
||||
return { newAppointmentId };
|
||||
}
|
||||
@@ -222,7 +372,9 @@ export async function reassignAppointment(input: { tenantId: string; appointment
|
||||
await tx.calendarEvent.update({ where: { id: appt.internalCalendarEventId }, data: { userId: input.newProviderUserId } });
|
||||
}
|
||||
});
|
||||
await sendLifecycleMail(appt, `Termin: neuer Ansprechpartner — ${appt.pageTitle}`, `Dein Termin am ${whenLabel(appt)} wird von einem anderen Mitarbeiter betreut.`);
|
||||
await recordActivity(input.tenantId, appt, "appointment_rescheduled", `Termin ${appt.pageTitle} (${whenLabel(appt)}) neu zugewiesen`, input.actorUserId);
|
||||
await sendLifecycleMail(appt, {
|
||||
kind: "reassigned",
|
||||
});
|
||||
await recordActivity(input.tenantId, appt, "appointment_rescheduled", "activity.runtime.booking.reassigned", input.actorUserId);
|
||||
await notifyProvider(input.tenantId, input.newProviderUserId, "bookings.status.scheduled", appt.id);
|
||||
}
|
||||
+62
-7
@@ -13,14 +13,18 @@
|
||||
|
||||
import { formatInTimeZone } from "date-fns-tz";
|
||||
import { logActivity } from "@hivegrid/activity";
|
||||
import { publishOutboxEvent, type OutboxPublisherTransaction } from "@hivegrid/db/outbox";
|
||||
import { db } from "~/utils/db.server";
|
||||
import { createLead } from "~/utils/integrations/leads/leadService.server";
|
||||
import { sendEmailMailjet } from "~/modules/emails/services/MailjetEmailService";
|
||||
import { renderSystemMessageEmail } from "@hivegrid/mail";
|
||||
import { getMailTranslator } from "~/locale/mail-translator.server";
|
||||
import type { PublicBookingPage } from "../db/booking.db.server";
|
||||
import { findKontaktIdByEmail } from "../db/booking.db.server";
|
||||
import { loadSlotsForDate } from "./SlotQueryService.server";
|
||||
import { pickFirstAvailableProvider } from "./slotEngine";
|
||||
import { buildIcs, icsToBase64 } from "./ics";
|
||||
import { buildBookingBookedWorkflowEvents } from "./bookingAutomationEvents.server";
|
||||
|
||||
const MINUTE_MS = 60_000;
|
||||
|
||||
@@ -59,6 +63,7 @@ export interface BookingSubmitInput {
|
||||
readonly date: string;
|
||||
/** Booker's IANA timezone (for display + the appointment record). */
|
||||
readonly viewerTimeZone: string;
|
||||
readonly locale?: string;
|
||||
readonly intake: BookingIntake;
|
||||
readonly now: Date;
|
||||
}
|
||||
@@ -129,6 +134,7 @@ export async function submitBooking(input: BookingSubmitInput): Promise<BookingS
|
||||
email: input.intake.email.trim(),
|
||||
telefon: input.intake.telefon?.trim() ?? null,
|
||||
gdprAccepted: true,
|
||||
locale: input.locale ?? "de",
|
||||
};
|
||||
const eventTitle = renderTemplate(page.internalEventTitleTemplate ?? "{{booking_page.title}}", {
|
||||
"booking_page.title": page.title,
|
||||
@@ -206,6 +212,19 @@ export async function submitBooking(input: BookingSubmitInput): Promise<BookingS
|
||||
where: { id: appointment.id },
|
||||
data: { internalCalendarEventId: calendarEvent.id, formSubmissionId: formSubmission?.id ?? null },
|
||||
});
|
||||
for (const event of buildBookingBookedWorkflowEvents({
|
||||
tenantId: page.tenantId,
|
||||
appointmentId: appointment.id,
|
||||
bookingPageId: page.pageId,
|
||||
bookingPageSlug: page.slug,
|
||||
providerUserId,
|
||||
calendarEventId: calendarEvent.id,
|
||||
startAt,
|
||||
endAt,
|
||||
kontaktId,
|
||||
})) {
|
||||
await publishOutboxEvent(tx as unknown as OutboxPublisherTransaction, event);
|
||||
}
|
||||
return appointment.id;
|
||||
},
|
||||
{ isolationLevel: "Serializable" }
|
||||
@@ -238,7 +257,7 @@ export async function submitBooking(input: BookingSubmitInput): Promise<BookingS
|
||||
}
|
||||
|
||||
// 4) Activity on the contact/lead (M06 J.4). Best-effort — never break the booking.
|
||||
const activitySubject = kontaktId ? ({ type: "contact" as const, id: kontaktId }) : leadId ? ({ type: "lead" as const, id: leadId }) : null;
|
||||
const activitySubject = kontaktId ? { type: "contact" as const, id: kontaktId } : leadId ? { type: "lead" as const, id: leadId } : null;
|
||||
if (activitySubject) {
|
||||
await logActivity({
|
||||
tenantId: page.tenantId,
|
||||
@@ -247,15 +266,26 @@ export async function submitBooking(input: BookingSubmitInput): Promise<BookingS
|
||||
activityType: "appointment_scheduled",
|
||||
subjectType: activitySubject.type,
|
||||
subjectId: activitySubject.id,
|
||||
summaryText: `Termin ${page.title} am ${formatInTimeZone(startAt, input.viewerTimeZone, "dd.MM.yyyy HH:mm")} gebucht`,
|
||||
metadata: { appointmentId, bookingPageId: page.pageId, leadId, kontaktId },
|
||||
summaryText: "activity.runtime.booking.scheduled",
|
||||
metadata: {
|
||||
appointmentId,
|
||||
bookingPageId: page.pageId,
|
||||
bookingPageTitle: page.title,
|
||||
startAt: startAt.toISOString(),
|
||||
timezone: input.viewerTimeZone,
|
||||
leadId,
|
||||
kontaktId,
|
||||
},
|
||||
}).catch(() => undefined);
|
||||
}
|
||||
|
||||
// 5) Confirmation mail + .ics (best-effort, M06 I.3).
|
||||
const icsBase64 = await sendConfirmation({ input, providerUserId, startAt, endAt, appointmentId }).catch(async () => {
|
||||
await db.appointment
|
||||
.update({ where: { id: appointmentId }, data: { notesInternal: `Bestätigungsmail an ${input.intake.email} konnte nicht versendet werden — Endkunde bitte direkt informieren.` } })
|
||||
.update({
|
||||
where: { id: appointmentId },
|
||||
data: { notesInternal: `Bestätigungsmail an ${input.intake.email} konnte nicht versendet werden — Endkunde bitte direkt informieren.` },
|
||||
})
|
||||
.catch(() => undefined);
|
||||
return buildBookingIcs({ input, providerUserId, startAt, endAt, appointmentId });
|
||||
});
|
||||
@@ -279,8 +309,14 @@ function buildBookingIcs(args: { input: BookingSubmitInput; providerUserId: stri
|
||||
return icsToBase64(ics);
|
||||
}
|
||||
|
||||
async function sendConfirmation(args: { input: BookingSubmitInput; providerUserId: string; startAt: Date; endAt: Date; appointmentId: string }): Promise<string> {
|
||||
const { input, startAt, endAt } = args;
|
||||
async function sendConfirmation(args: {
|
||||
input: BookingSubmitInput;
|
||||
providerUserId: string;
|
||||
startAt: Date;
|
||||
endAt: Date;
|
||||
appointmentId: string;
|
||||
}): Promise<string> {
|
||||
const { input, startAt } = args;
|
||||
const { page } = input;
|
||||
const icsBase64 = buildBookingIcs(args);
|
||||
|
||||
@@ -298,12 +334,31 @@ async function sendConfirmation(args: { input: BookingSubmitInput; providerUserI
|
||||
};
|
||||
const subject = renderTemplate(page.confirmationEmailSubject, vars);
|
||||
const body = renderTemplate(page.confirmationEmailBody, vars);
|
||||
const { t, locale } = await getMailTranslator(input.locale);
|
||||
const rendered = renderSystemMessageEmail({
|
||||
locale,
|
||||
brand: { tenantName: page.tenantName },
|
||||
subject,
|
||||
previewText: t("booking.confirmation.previewText", { company: page.tenantName }),
|
||||
eyebrow: t("booking.confirmation.eyebrow"),
|
||||
title: t("booking.confirmation.title"),
|
||||
intro: body,
|
||||
details: [
|
||||
{ label: t("booking.confirmation.fields.appointment"), value: page.title },
|
||||
{ label: t("booking.confirmation.fields.date"), value: vars["appointment.date"] ?? "" },
|
||||
{ label: t("booking.confirmation.fields.time"), value: t("booking.confirmation.timeValue", { time: vars["appointment.time"] ?? "" }) },
|
||||
{ label: t("booking.confirmation.fields.duration"), value: t("booking.confirmation.durationValue", { minutes: page.durationMinutes }) },
|
||||
{ label: t("booking.confirmation.fields.company"), value: page.tenantName },
|
||||
],
|
||||
notice: t("booking.confirmation.notice"),
|
||||
});
|
||||
|
||||
await sendEmailMailjet({
|
||||
data: {
|
||||
to: input.intake.email.trim(),
|
||||
subject,
|
||||
body: body.replace(/\r?\n/gu, "<br/>"),
|
||||
body: rendered.html,
|
||||
text: rendered.text,
|
||||
tenantId: page.tenantId,
|
||||
attachments: [{ filename: "termin.ics", content: icsBase64, disposition: "attachment" }],
|
||||
},
|
||||
|
||||
+91
@@ -0,0 +1,91 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
db: {
|
||||
availabilityRule: { findMany: vi.fn() },
|
||||
availabilityException: { findMany: vi.fn() },
|
||||
appointment: { findMany: vi.fn() },
|
||||
calendarEvent: { findMany: vi.fn() },
|
||||
},
|
||||
computeSlots: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/db.server", () => ({ db: mocks.db }));
|
||||
vi.mock("./slotEngine", () => ({ computeSlots: mocks.computeSlots }));
|
||||
|
||||
import { loadSlotsForDate } from "./SlotQueryService.server";
|
||||
|
||||
describe("SlotQueryService.server", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mocks.db.availabilityRule.findMany.mockResolvedValue([]);
|
||||
mocks.db.availabilityException.findMany.mockResolvedValue([]);
|
||||
mocks.db.appointment.findMany.mockResolvedValue([]);
|
||||
mocks.db.calendarEvent.findMany.mockResolvedValue([]);
|
||||
mocks.computeSlots.mockReturnValue([]);
|
||||
});
|
||||
|
||||
it("loads any number of providers with four bulk queries", async () => {
|
||||
const startAt = new Date("2026-07-20T09:00:00.000Z");
|
||||
const endAt = new Date("2026-07-20T10:00:00.000Z");
|
||||
mocks.db.availabilityRule.findMany.mockResolvedValue([
|
||||
{ providerUserId: "provider_2", dayOfWeek: "monday", startTime: "09:00", endTime: "17:00", timezone: "Europe/Berlin" },
|
||||
]);
|
||||
mocks.db.appointment.findMany.mockResolvedValue([{ providerUserId: "provider_1", startAt, endAt }]);
|
||||
mocks.db.calendarEvent.findMany.mockResolvedValue([
|
||||
{ userId: "provider_2", startsAt: startAt, endsAt: endAt, isBusyForAvailability: true, archivedAt: null },
|
||||
]);
|
||||
|
||||
await loadSlotsForDate({
|
||||
tenantId: "tenant_1",
|
||||
providerUserIds: ["provider_1", "provider_2"],
|
||||
date: "2026-07-20",
|
||||
now: new Date("2026-07-10T00:00:00.000Z"),
|
||||
config: {
|
||||
durationMinutes: 30,
|
||||
bufferBeforeMinutes: 0,
|
||||
bufferAfterMinutes: 0,
|
||||
slotIncrementMinutes: 15,
|
||||
minNoticeHours: 4,
|
||||
maxAdvanceDays: 60,
|
||||
},
|
||||
});
|
||||
|
||||
expect(mocks.db.availabilityRule.findMany).toHaveBeenCalledTimes(1);
|
||||
expect(mocks.db.availabilityException.findMany).toHaveBeenCalledTimes(1);
|
||||
expect(mocks.db.appointment.findMany).toHaveBeenCalledTimes(1);
|
||||
expect(mocks.db.calendarEvent.findMany).toHaveBeenCalledTimes(1);
|
||||
expect(mocks.db.availabilityRule.findMany).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ where: { tenantId: "tenant_1", providerUserId: { in: ["provider_1", "provider_2"] } } }),
|
||||
);
|
||||
expect(mocks.computeSlots).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
providers: [
|
||||
expect.objectContaining({ providerUserId: "provider_1", busyIntervals: [{ from: startAt, to: endAt }] }),
|
||||
expect.objectContaining({ providerUserId: "provider_2", rules: [expect.objectContaining({ dayOfWeek: "monday" })], busyIntervals: [{ from: startAt, to: endAt }] }),
|
||||
],
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("short-circuits without querying when no provider is configured", async () => {
|
||||
await expect(
|
||||
loadSlotsForDate({
|
||||
tenantId: "tenant_1",
|
||||
providerUserIds: [],
|
||||
date: "2026-07-20",
|
||||
now: new Date("2026-07-10T00:00:00.000Z"),
|
||||
config: {
|
||||
durationMinutes: 30,
|
||||
bufferBeforeMinutes: 0,
|
||||
bufferAfterMinutes: 0,
|
||||
slotIncrementMinutes: 15,
|
||||
minNoticeHours: 4,
|
||||
maxAdvanceDays: 60,
|
||||
},
|
||||
}),
|
||||
).resolves.toEqual([]);
|
||||
expect(mocks.db.availabilityRule.findMany).not.toHaveBeenCalled();
|
||||
expect(mocks.computeSlots).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
+49
-25
@@ -37,44 +37,68 @@ function dayWindow(date: string): { from: Date; to: Date } {
|
||||
return { from: new Date(midnightUtc - DAY_MS), to: new Date(midnightUtc + 2 * DAY_MS) };
|
||||
}
|
||||
|
||||
/** Load one provider's rules, exceptions and busy intervals for the day. */
|
||||
async function loadProviderInput(tenantId: string, providerUserId: string, date: string): Promise<ProviderAvailabilityInput> {
|
||||
function groupByProvider<T>(rows: readonly T[], providerId: (row: T) => string): Map<string, T[]> {
|
||||
const grouped = new Map<string, T[]>();
|
||||
for (const row of rows) {
|
||||
const id = providerId(row);
|
||||
const group = grouped.get(id);
|
||||
if (group) group.push(row);
|
||||
else grouped.set(id, [row]);
|
||||
}
|
||||
return grouped;
|
||||
}
|
||||
|
||||
/** Load all providers' rules, exceptions and busy intervals in four queries. */
|
||||
async function loadProviderInputs(tenantId: string, providerUserIds: readonly string[], date: string): Promise<ProviderAvailabilityInput[]> {
|
||||
const window = dayWindow(date);
|
||||
|
||||
const [rules, exceptions, appointments, events] = await Promise.all([
|
||||
db.availabilityRule.findMany({
|
||||
where: { tenantId, providerUserId },
|
||||
select: { dayOfWeek: true, startTime: true, endTime: true, timezone: true },
|
||||
where: { tenantId, providerUserId: { in: [...providerUserIds] } },
|
||||
select: { providerUserId: true, dayOfWeek: true, startTime: true, endTime: true, timezone: true },
|
||||
}),
|
||||
db.availabilityException.findMany({
|
||||
where: { tenantId, providerUserId, date: new Date(`${date}T00:00:00Z`) },
|
||||
select: { date: true, kind: true, startTime: true, endTime: true, timezone: true },
|
||||
where: { tenantId, providerUserId: { in: [...providerUserIds] }, date: new Date(`${date}T00:00:00Z`) },
|
||||
select: { providerUserId: true, date: true, kind: true, startTime: true, endTime: true, timezone: true },
|
||||
}),
|
||||
db.appointment.findMany({
|
||||
where: { tenantId, providerUserId, status: { in: [...OCCUPYING_STATUSES] }, startAt: { gte: window.from, lte: window.to } },
|
||||
select: { startAt: true, endAt: true },
|
||||
where: { tenantId, providerUserId: { in: [...providerUserIds] }, status: { in: [...OCCUPYING_STATUSES] }, startAt: { gte: window.from, lte: window.to } },
|
||||
select: { providerUserId: true, startAt: true, endAt: true },
|
||||
}),
|
||||
db.calendarEvent.findMany({
|
||||
where: { tenantId, userId: providerUserId, isBusyForAvailability: true, archivedAt: null, startsAt: { gte: window.from, lte: window.to } },
|
||||
select: { startsAt: true, endsAt: true, isBusyForAvailability: true, archivedAt: true },
|
||||
where: { tenantId, userId: { in: [...providerUserIds] }, isBusyForAvailability: true, archivedAt: null, startsAt: { gte: window.from, lte: window.to } },
|
||||
select: { userId: true, startsAt: true, endsAt: true, isBusyForAvailability: true, archivedAt: true },
|
||||
}),
|
||||
]);
|
||||
|
||||
const appointmentBusy: BusyInterval[] = appointments.map((a) => ({ from: a.startAt, to: a.endAt }));
|
||||
const calendarBusy = extractBusyIntervals(events);
|
||||
const rulesByProvider = groupByProvider(rules, (row) => row.providerUserId);
|
||||
const exceptionsByProvider = groupByProvider(exceptions, (row) => row.providerUserId);
|
||||
const appointmentsByProvider = groupByProvider(appointments, (row) => row.providerUserId);
|
||||
const eventsByProvider = groupByProvider(events, (row) => row.userId);
|
||||
|
||||
return {
|
||||
providerUserId,
|
||||
rules: rules.map((r) => ({ dayOfWeek: r.dayOfWeek as BookingWeekday, startTime: r.startTime, endTime: r.endTime, timezone: r.timezone })) satisfies SlotRuleInput[],
|
||||
exceptions: exceptions.map((e) => ({
|
||||
date,
|
||||
kind: e.kind as SlotExceptionInput["kind"],
|
||||
startTime: e.startTime,
|
||||
endTime: e.endTime,
|
||||
timezone: e.timezone,
|
||||
})) satisfies SlotExceptionInput[],
|
||||
busyIntervals: [...appointmentBusy, ...calendarBusy],
|
||||
};
|
||||
return providerUserIds.map((providerUserId) => {
|
||||
const providerAppointments = appointmentsByProvider.get(providerUserId) ?? [];
|
||||
const appointmentBusy: BusyInterval[] = providerAppointments.map((appointment) => ({ from: appointment.startAt, to: appointment.endAt }));
|
||||
const calendarBusy = extractBusyIntervals(eventsByProvider.get(providerUserId) ?? []);
|
||||
|
||||
return {
|
||||
providerUserId,
|
||||
rules: (rulesByProvider.get(providerUserId) ?? []).map((rule) => ({
|
||||
dayOfWeek: rule.dayOfWeek as BookingWeekday,
|
||||
startTime: rule.startTime,
|
||||
endTime: rule.endTime,
|
||||
timezone: rule.timezone,
|
||||
})) satisfies SlotRuleInput[],
|
||||
exceptions: (exceptionsByProvider.get(providerUserId) ?? []).map((exception) => ({
|
||||
date,
|
||||
kind: exception.kind as SlotExceptionInput["kind"],
|
||||
startTime: exception.startTime,
|
||||
endTime: exception.endTime,
|
||||
timezone: exception.timezone,
|
||||
})) satisfies SlotExceptionInput[],
|
||||
busyIntervals: [...appointmentBusy, ...calendarBusy],
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
/** Compute the bookable slots for a booking page's providers on a given local day. */
|
||||
@@ -82,6 +106,6 @@ export async function loadSlotsForDate(input: SlotQueryInput): Promise<ComputedS
|
||||
if (input.providerUserIds.length === 0) {
|
||||
return [];
|
||||
}
|
||||
const providers = await Promise.all(input.providerUserIds.map((id) => loadProviderInput(input.tenantId, id, input.date)));
|
||||
const providers = await loadProviderInputs(input.tenantId, input.providerUserIds, input.date);
|
||||
return computeSlots({ date: input.date, now: input.now, providers, config: input.config });
|
||||
}
|
||||
+18
-8
@@ -11,15 +11,25 @@ function readArtifact(relativePath: string): string {
|
||||
|
||||
describe("booking DB rollout artifacts", () => {
|
||||
test("hard double-booking guard uses an idempotent exclusion constraint for active appointments", () => {
|
||||
const sql = readArtifact("prisma/rls/booking-constraints.sql");
|
||||
// tsrange, not tstzrange: startAt/endAt are TIMESTAMP(3) (UTC by
|
||||
// convention) and the timestamp->timestamptz cast is only STABLE, which
|
||||
// Postgres rejects inside index expressions (42P17).
|
||||
const reviewedArtifact = readArtifact("prisma/rls/booking-constraints.sql");
|
||||
const baseline = readArtifact("prisma/migrations/00000000000000_hivegrid_baseline/migration.sql");
|
||||
|
||||
expect(sql).toContain("CREATE EXTENSION IF NOT EXISTS btree_gist");
|
||||
expect(sql).toContain("appointment_no_overlap");
|
||||
expect(sql).toContain('EXCLUDE USING gist');
|
||||
expect(sql).toContain('"providerUserId" WITH =');
|
||||
expect(sql).toContain('tstzrange("startAt", "endAt", \'\'[)\'\') WITH &&');
|
||||
expect(sql).toContain("WHERE (status IN (''scheduled'', ''held''))");
|
||||
expect(sql).toContain("23P01");
|
||||
expect(reviewedArtifact).toContain("CREATE EXTENSION IF NOT EXISTS btree_gist");
|
||||
expect(reviewedArtifact).toContain("23P01");
|
||||
expect(baseline).toContain("CREATE EXTENSION IF NOT EXISTS btree_gist");
|
||||
expect(baseline).toContain("appointment_no_overlap");
|
||||
expect(baseline).toContain("EXCLUDE USING gist");
|
||||
// Tenant-scoped on purpose: the slot engine is tenant-scoped and demo
|
||||
// tenants share provider users — a tenant-agnostic constraint leaked
|
||||
// cross-tenant busy state and broke the 2026-07-17 staging rollout.
|
||||
expect(baseline).toContain('"tenantId" WITH =');
|
||||
expect(baseline).toContain('"providerUserId" WITH =');
|
||||
expect(baseline).toContain('tsrange("startAt", "endAt", \'[)\'::text) WITH &&');
|
||||
expect(baseline).not.toContain("tstzrange(");
|
||||
expect(baseline).toContain("status = ANY (ARRAY['scheduled'::public.\"AppointmentStatus\", 'held'::public.\"AppointmentStatus\"])");
|
||||
});
|
||||
|
||||
test("booking RLS artifact covers every tenant-scoped booking table and fails closed without tenant GUC", () => {
|
||||
|
||||
+1
@@ -17,6 +17,7 @@ describe("booking post-booking server wiring", () => {
|
||||
expect(source).toContain("appointmentId");
|
||||
expect(source).toContain("data: { leadId }");
|
||||
expect(source).toContain('type: "lead" as const');
|
||||
expect(source).toContain('summaryText: "activity.runtime.booking.scheduled"');
|
||||
});
|
||||
|
||||
test("public booking persists a FormSubmission when an intake form is configured", () => {
|
||||
|
||||
+78
@@ -0,0 +1,78 @@
|
||||
import { describe, expect, test } from "vitest";
|
||||
|
||||
import { buildBookingBookedWorkflowEvents, buildBookingCancelledWorkflowEvent, buildCalendarCreatedWorkflowEvent } from "./bookingAutomationEvents.server";
|
||||
|
||||
const START = new Date("2026-08-03T08:00:00.000Z");
|
||||
const END = new Date("2026-08-03T09:00:00.000Z");
|
||||
|
||||
describe("booking automation workflow events", () => {
|
||||
test("builds one booked and one calendar-created event from the committed booking", () => {
|
||||
const events = buildBookingBookedWorkflowEvents({
|
||||
tenantId: "tenant-1",
|
||||
appointmentId: "appointment-1",
|
||||
bookingPageId: "page-1",
|
||||
bookingPageSlug: "beratung",
|
||||
providerUserId: "user-1",
|
||||
calendarEventId: "calendar-1",
|
||||
startAt: START,
|
||||
endAt: END,
|
||||
kontaktId: "kontakt-1",
|
||||
});
|
||||
|
||||
expect(events).toEqual([
|
||||
expect.objectContaining({
|
||||
type: "workflow.trigger.event",
|
||||
dispatchKey: "workflow-trigger:booking:appointment-1:booked",
|
||||
payload: expect.objectContaining({
|
||||
event: "booking.appointment_booked",
|
||||
data: expect.objectContaining({ appointmentId: "appointment-1", appointmentType: "beratung", providerUserId: "user-1" }),
|
||||
}),
|
||||
}),
|
||||
expect.objectContaining({
|
||||
dispatchKey: "workflow-trigger:calendar:calendar-1:created",
|
||||
payload: expect.objectContaining({
|
||||
event: "calendar.event_created",
|
||||
data: expect.objectContaining({ calendarKey: "hauptkalender", eventKind: "termin" }),
|
||||
}),
|
||||
}),
|
||||
]);
|
||||
});
|
||||
|
||||
test("keeps cancellation actor and timestamp in the idempotent event", () => {
|
||||
const cancelledAt = new Date("2026-08-03T07:30:00.000Z");
|
||||
expect(
|
||||
buildBookingCancelledWorkflowEvent({
|
||||
tenantId: "tenant-1",
|
||||
appointmentId: "appointment-1",
|
||||
bookingPageId: "page-1",
|
||||
bookingPageSlug: "wartung",
|
||||
providerUserId: "user-1",
|
||||
cancelledByKind: "customer",
|
||||
cancellationReason: "Keine Zeit",
|
||||
cancelledAt,
|
||||
actorUserId: null,
|
||||
})
|
||||
).toMatchObject({
|
||||
dispatchKey: `workflow-trigger:booking:appointment-1:cancelled:${cancelledAt.getTime()}`,
|
||||
payload: { event: "booking.appointment_cancelled", data: { cancelledByKind: "customer", appointmentType: "wartung" }, userId: null },
|
||||
});
|
||||
});
|
||||
|
||||
test("builds reusable calendar-created events for non-booking sources", () => {
|
||||
expect(
|
||||
buildCalendarCreatedWorkflowEvent({
|
||||
tenantId: "tenant-1",
|
||||
calendarEventId: "calendar-2",
|
||||
userId: "user-2",
|
||||
calendarKey: "urlaubskalender",
|
||||
eventKind: "termin",
|
||||
source: "leave",
|
||||
sourceEntityId: "leave-1",
|
||||
startsAt: START,
|
||||
endsAt: END,
|
||||
})
|
||||
).toMatchObject({
|
||||
payload: { event: "calendar.event_created", data: { calendarKey: "urlaubskalender", source: "leave" }, userId: "user-2" },
|
||||
});
|
||||
});
|
||||
});
|
||||
+78
@@ -0,0 +1,78 @@
|
||||
import { buildWorkflowTriggerOutboxEvent } from "@hivegrid/queue";
|
||||
import { buildCalendarCreatedWorkflowEvent } from "~/services/automation/automation.producer-events.server";
|
||||
|
||||
export { buildCalendarCreatedWorkflowEvent } from "~/services/automation/automation.producer-events.server";
|
||||
|
||||
export function buildBookingBookedWorkflowEvents(input: {
|
||||
readonly tenantId: string;
|
||||
readonly appointmentId: string;
|
||||
readonly bookingPageId: string;
|
||||
readonly bookingPageSlug: string;
|
||||
readonly providerUserId: string;
|
||||
readonly calendarEventId: string;
|
||||
readonly startAt: Date;
|
||||
readonly endAt: Date;
|
||||
readonly kontaktId: string | null;
|
||||
}) {
|
||||
return [
|
||||
buildWorkflowTriggerOutboxEvent({
|
||||
tenantId: input.tenantId,
|
||||
event: "booking.appointment_booked",
|
||||
data: {
|
||||
appointmentId: input.appointmentId,
|
||||
bookingPageId: input.bookingPageId,
|
||||
bookingPageSlug: input.bookingPageSlug,
|
||||
appointmentType: input.bookingPageSlug,
|
||||
terminart: input.bookingPageSlug,
|
||||
providerUserId: input.providerUserId,
|
||||
mitarbeiter: input.providerUserId,
|
||||
startAt: input.startAt.toISOString(),
|
||||
endAt: input.endAt.toISOString(),
|
||||
kontaktId: input.kontaktId,
|
||||
},
|
||||
userId: null,
|
||||
sourceId: `booking:${input.appointmentId}:booked`,
|
||||
}),
|
||||
buildCalendarCreatedWorkflowEvent({
|
||||
tenantId: input.tenantId,
|
||||
calendarEventId: input.calendarEventId,
|
||||
userId: input.providerUserId,
|
||||
calendarKey: "hauptkalender",
|
||||
eventKind: "termin",
|
||||
source: "booking",
|
||||
sourceEntityId: input.appointmentId,
|
||||
startsAt: input.startAt,
|
||||
endsAt: input.endAt,
|
||||
}),
|
||||
] as const;
|
||||
}
|
||||
|
||||
export function buildBookingCancelledWorkflowEvent(input: {
|
||||
readonly tenantId: string;
|
||||
readonly appointmentId: string;
|
||||
readonly bookingPageId: string;
|
||||
readonly bookingPageSlug: string;
|
||||
readonly providerUserId: string;
|
||||
readonly cancelledByKind: "customer" | "provider" | "system";
|
||||
readonly cancellationReason: string;
|
||||
readonly cancelledAt: Date;
|
||||
readonly actorUserId: string | null;
|
||||
}) {
|
||||
return buildWorkflowTriggerOutboxEvent({
|
||||
tenantId: input.tenantId,
|
||||
event: "booking.appointment_cancelled",
|
||||
data: {
|
||||
appointmentId: input.appointmentId,
|
||||
bookingPageId: input.bookingPageId,
|
||||
bookingPageSlug: input.bookingPageSlug,
|
||||
appointmentType: input.bookingPageSlug,
|
||||
terminart: input.bookingPageSlug,
|
||||
providerUserId: input.providerUserId,
|
||||
cancelledByKind: input.cancelledByKind,
|
||||
cancellationReason: input.cancellationReason,
|
||||
cancelledAt: input.cancelledAt.toISOString(),
|
||||
},
|
||||
userId: input.actorUserId,
|
||||
sourceId: `booking:${input.appointmentId}:cancelled:${input.cancelledAt.getTime()}`,
|
||||
});
|
||||
}
|
||||
Reference in new issue
Block a user