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
+393
@@ -0,0 +1,393 @@
|
||||
import { createHmac } from "node:crypto";
|
||||
|
||||
import { hostMatches } from "@hivegrid/config";
|
||||
import {
|
||||
computeAdminBookingSlots,
|
||||
type AdminAnonymousBusyInterval,
|
||||
type AdminBookingHostAvailability,
|
||||
} from "@hivegrid/db/admin-booking-availability";
|
||||
import {
|
||||
AdminBookingError,
|
||||
createAdminBookingService,
|
||||
createPrismaAdminBookingRepository,
|
||||
type ReservedAdminBooking,
|
||||
} from "@hivegrid/db/admin-booking.server";
|
||||
import { resolveAdminBookingPageRlsIdentity } from "@hivegrid/db/rls-resolvers.server";
|
||||
import { runWithRlsContext } from "@hivegrid/db/rls-context.server";
|
||||
import { createFixedWindowRateLimiter } from "@hivegrid/shared-store";
|
||||
|
||||
import { getSharedStore } from "~/shared-store.server";
|
||||
import { getAdminBookingHost } from "~/utils/app/HostRouting.server";
|
||||
import { db } from "~/utils/db.server";
|
||||
import { createScopedLogger } from "~/utils/logger.server";
|
||||
import { getTrustedClientIp } from "~/utils/server/IpUtils";
|
||||
|
||||
import type { AdminBookingManageClaims } from "./admin-booking-manage-token.server";
|
||||
|
||||
const ISO_DATE = /^\d{4}-\d{2}-\d{2}$/u;
|
||||
const bookingLogger = createScopedLogger("admin-public-booking");
|
||||
|
||||
export type AdminPublicBookingQuestion = {
|
||||
readonly id: string;
|
||||
readonly label: string;
|
||||
readonly required: boolean;
|
||||
readonly type: "text" | "textarea" | "select";
|
||||
readonly options: readonly string[];
|
||||
};
|
||||
|
||||
export type AdminPublicBookingPage = {
|
||||
readonly pageId: string;
|
||||
readonly ownerAdminUserId: string;
|
||||
readonly slug: string;
|
||||
readonly title: string;
|
||||
readonly description: string | null;
|
||||
readonly meetingTypeName: string;
|
||||
readonly durationMinutes: number;
|
||||
readonly questions: readonly AdminPublicBookingQuestion[];
|
||||
readonly date: string;
|
||||
readonly slots: readonly {
|
||||
readonly startsAt: Date;
|
||||
readonly endsAt: Date;
|
||||
readonly availableHostAdminUserIds: readonly string[];
|
||||
}[];
|
||||
};
|
||||
|
||||
export type SubmitAdminPublicBookingInput = {
|
||||
readonly slug: string;
|
||||
readonly date: string;
|
||||
readonly startsAt: Date;
|
||||
readonly endsAt: Date;
|
||||
readonly firstName: string;
|
||||
readonly lastName: string;
|
||||
readonly email: string;
|
||||
readonly timeZone: string;
|
||||
readonly locale?: string | null;
|
||||
readonly answers: Readonly<Record<string, string>>;
|
||||
readonly submissionId: string;
|
||||
readonly manualHostAdminUserId?: string | null;
|
||||
readonly dealId?: string | null;
|
||||
readonly reschedule?: {
|
||||
readonly claims: AdminBookingManageClaims;
|
||||
readonly nonceHash: string;
|
||||
};
|
||||
};
|
||||
|
||||
export async function loadAdminPublicBookingPage(input: {
|
||||
readonly slug: string;
|
||||
readonly date: string;
|
||||
readonly now?: Date;
|
||||
}): Promise<AdminPublicBookingPage | null> {
|
||||
if (!ISO_DATE.test(input.date)) return null;
|
||||
const identity = await resolveAdminBookingPageRlsIdentity(input.slug, db);
|
||||
if (!identity) return null;
|
||||
const page = await runWithRlsContext({ userId: identity.userId }, () =>
|
||||
db.adminBookingPage.findFirst({
|
||||
where: {
|
||||
id: identity.resourceId,
|
||||
createdByAdminUserId: identity.userId,
|
||||
published: true,
|
||||
archivedAt: null,
|
||||
meetingType: { active: true, archivedAt: null },
|
||||
},
|
||||
include: { meetingType: true },
|
||||
})
|
||||
);
|
||||
if (!page) return null;
|
||||
|
||||
const now = input.now ?? new Date();
|
||||
const hosts = await Promise.all(
|
||||
page.meetingType.hostAdminUserIds.map((adminUserId) =>
|
||||
readHostAvailability({
|
||||
adminUserId,
|
||||
date: input.date,
|
||||
now,
|
||||
horizonDays: page.meetingType.bookingHorizonDays,
|
||||
})
|
||||
)
|
||||
);
|
||||
const slots = computeAdminBookingSlots({
|
||||
date: input.date,
|
||||
now,
|
||||
hosts,
|
||||
config: {
|
||||
durationMinutes: page.meetingType.durationMinutes,
|
||||
bufferBeforeMinutes: page.meetingType.bufferBeforeMinutes,
|
||||
bufferAfterMinutes: page.meetingType.bufferAfterMinutes,
|
||||
slotIncrementMinutes: page.meetingType.slotIncrementMinutes,
|
||||
minimumNoticeMinutes: page.meetingType.minimumNoticeMinutes,
|
||||
bookingHorizonDays: page.meetingType.bookingHorizonDays,
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
pageId: page.id,
|
||||
ownerAdminUserId: identity.userId,
|
||||
slug: page.slug,
|
||||
title: page.title,
|
||||
description: page.description,
|
||||
meetingTypeName: page.meetingType.name,
|
||||
durationMinutes: page.meetingType.durationMinutes,
|
||||
questions: parseQuestions(page.meetingType.intakeQuestions),
|
||||
date: input.date,
|
||||
slots,
|
||||
};
|
||||
}
|
||||
|
||||
export async function submitAdminPublicBooking(
|
||||
input: SubmitAdminPublicBookingInput,
|
||||
now: Date = new Date()
|
||||
): Promise<ReservedAdminBooking> {
|
||||
const page = await loadAdminPublicBookingPage({
|
||||
slug: input.slug,
|
||||
date: input.date,
|
||||
now,
|
||||
});
|
||||
if (!page) throw new AdminBookingError("page_unavailable");
|
||||
const slot = page.slots.find(
|
||||
(candidate) =>
|
||||
candidate.startsAt.getTime() === input.startsAt.getTime() &&
|
||||
candidate.endsAt.getTime() === input.endsAt.getTime()
|
||||
);
|
||||
if (!slot) throw new AdminBookingError("slot_taken");
|
||||
const allowedQuestionIds = new Set(
|
||||
page.questions.map((question) => question.id)
|
||||
);
|
||||
if (
|
||||
Object.keys(input.answers).some((id) => !allowedQuestionIds.has(id)) ||
|
||||
page.questions.some(
|
||||
(question) =>
|
||||
question.required && !input.answers[question.id]?.trim()
|
||||
)
|
||||
) {
|
||||
throw new AdminBookingError("invalid_answers");
|
||||
}
|
||||
const identity = {
|
||||
resourceId: page.pageId,
|
||||
userId: page.ownerAdminUserId,
|
||||
};
|
||||
return runWithRlsContext({ userId: identity.userId }, () =>
|
||||
createAdminBookingService({
|
||||
repository: createPrismaAdminBookingRepository(db, { now: () => now }),
|
||||
}).reserve({
|
||||
bookingPageId: identity.resourceId,
|
||||
startsAt: input.startsAt,
|
||||
endsAt: input.endsAt,
|
||||
bookerTimeZone: input.timeZone,
|
||||
bookerFirstName: input.firstName,
|
||||
bookerLastName: input.lastName,
|
||||
bookerEmail: input.email,
|
||||
bookerLocale: input.locale,
|
||||
intakeAnswers: input.answers,
|
||||
availableHostAdminUserIds: slot.availableHostAdminUserIds,
|
||||
manualHostAdminUserId: input.manualHostAdminUserId,
|
||||
dealId: input.dealId,
|
||||
idempotencyKey: `public-booking:${identity.resourceId}:${input.submissionId}`,
|
||||
manageTokenExpiresAt: new Date(
|
||||
Math.max(input.startsAt.getTime(), now.getTime()) + 30 * 86_400_000
|
||||
),
|
||||
...(input.reschedule
|
||||
? {
|
||||
reschedule: {
|
||||
previousBookingId: input.reschedule.claims.bookingId,
|
||||
manageTokenVersion: input.reschedule.claims.version,
|
||||
manageTokenExpiresAfter: now,
|
||||
manageNonceHash: input.reschedule.nonceHash,
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
export async function checkAdminPublicBookingRateLimit(input: {
|
||||
readonly request: Request;
|
||||
readonly slug: string;
|
||||
readonly email: string;
|
||||
readonly secret: string;
|
||||
}): Promise<{ readonly allowed: boolean; readonly retryAfterSeconds: number }> {
|
||||
const retryAfterSeconds = 900;
|
||||
try {
|
||||
if (input.secret.length < 32) throw new Error("invalid secret");
|
||||
const client = getTrustedClientIp(input.request) || "unknown";
|
||||
const key = createHmac("sha256", input.secret)
|
||||
.update(
|
||||
`admin-booking-v1\0${input.slug.trim().toLowerCase()}\0${client}\0${input.email.trim().toLowerCase()}`
|
||||
)
|
||||
.digest("hex");
|
||||
const decision = await createFixedWindowRateLimiter({
|
||||
store: getSharedStore(),
|
||||
prefix: "admin-booking-v1-submit",
|
||||
windowSeconds: retryAfterSeconds,
|
||||
max: 8,
|
||||
}).consume(key);
|
||||
return { allowed: decision.allowed, retryAfterSeconds };
|
||||
} catch (error) {
|
||||
bookingLogger.error(
|
||||
{
|
||||
event: "admin_booking.rate_limit_unavailable",
|
||||
errorName: error instanceof Error ? error.name : "UnknownError",
|
||||
},
|
||||
"Admin booking rate limit unavailable; request denied"
|
||||
);
|
||||
return { allowed: false, retryAfterSeconds };
|
||||
}
|
||||
}
|
||||
|
||||
export function isAdminPublicBookingHost(request: Request): boolean {
|
||||
const url = new URL(request.url);
|
||||
const actualHost = request.headers.get("host") ?? url.host;
|
||||
return hostMatches(actualHost, getAdminBookingHost());
|
||||
}
|
||||
|
||||
async function readHostAvailability(input: {
|
||||
readonly adminUserId: string;
|
||||
readonly date: string;
|
||||
readonly now: Date;
|
||||
readonly horizonDays: number;
|
||||
}): Promise<AdminBookingHostAvailability> {
|
||||
return runWithRlsContext({ userId: input.adminUserId }, async () => {
|
||||
const date = new Date(`${input.date}T00:00:00.000Z`);
|
||||
const rangeEnd = new Date(
|
||||
date.getTime() + Math.max(1, input.horizonDays) * 86_400_000
|
||||
);
|
||||
const [eligibleUser, rules, overrides, cursors, bookings] =
|
||||
await Promise.all([
|
||||
db.adminUser.findFirst({
|
||||
where: {
|
||||
id: input.adminUserId,
|
||||
status: "active",
|
||||
roles: {
|
||||
some: {
|
||||
role: {
|
||||
active: true,
|
||||
permissions: {
|
||||
some: {
|
||||
permission: {
|
||||
name: "admin_sales.booking.manage",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
select: { id: true },
|
||||
}),
|
||||
db.adminAvailabilityRule.findMany({
|
||||
where: { adminUserId: input.adminUserId, archivedAt: null },
|
||||
}),
|
||||
db.adminAvailabilityOverride.findMany({
|
||||
where: {
|
||||
adminUserId: input.adminUserId,
|
||||
archivedAt: null,
|
||||
date,
|
||||
},
|
||||
}),
|
||||
db.adminCalendarSyncCursor.findMany({
|
||||
where: {
|
||||
adminUserId: input.adminUserId,
|
||||
status: "active",
|
||||
calendarConnection: {
|
||||
status: "active",
|
||||
archivedAt: null,
|
||||
},
|
||||
},
|
||||
select: { busyIntervals: true },
|
||||
}),
|
||||
db.adminBooking.findMany({
|
||||
where: {
|
||||
adminUserId: input.adminUserId,
|
||||
status: { in: ["reserved", "confirmed"] },
|
||||
startsAt: { lt: rangeEnd },
|
||||
endsAt: { gt: date },
|
||||
},
|
||||
select: { startsAt: true, endsAt: true },
|
||||
}),
|
||||
]);
|
||||
const absent = overrides.some(
|
||||
(override) => override.kind === "unavailable"
|
||||
);
|
||||
return {
|
||||
adminUserId: input.adminUserId,
|
||||
eligible: Boolean(eligibleUser),
|
||||
absent,
|
||||
rules: rules.map((rule) => ({
|
||||
dayOfWeek: rule.dayOfWeek,
|
||||
startMinutes: rule.startMinutes,
|
||||
endMinutes: rule.endMinutes,
|
||||
timeZone: rule.timeZone,
|
||||
})),
|
||||
overrides: overrides.map((override) => ({
|
||||
date: input.date,
|
||||
kind: override.kind,
|
||||
startMinutes: override.startMinutes,
|
||||
endMinutes: override.endMinutes,
|
||||
timeZone: override.timeZone,
|
||||
})),
|
||||
busyIntervals: [
|
||||
...cursors.flatMap((cursor) =>
|
||||
parseBusyIntervals(cursor.busyIntervals)
|
||||
),
|
||||
...bookings,
|
||||
],
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
function parseBusyIntervals(value: unknown): AdminAnonymousBusyInterval[] {
|
||||
if (!Array.isArray(value)) return [];
|
||||
return value.flatMap((item) => {
|
||||
if (!item || typeof item !== "object") return [];
|
||||
const startsAt = new Date(
|
||||
"startsAt" in item && typeof item.startsAt === "string"
|
||||
? item.startsAt
|
||||
: Number.NaN
|
||||
);
|
||||
const endsAt = new Date(
|
||||
"endsAt" in item && typeof item.endsAt === "string"
|
||||
? item.endsAt
|
||||
: Number.NaN
|
||||
);
|
||||
return Number.isFinite(startsAt.getTime()) &&
|
||||
Number.isFinite(endsAt.getTime()) &&
|
||||
endsAt > startsAt
|
||||
? [{ startsAt, endsAt }]
|
||||
: [];
|
||||
});
|
||||
}
|
||||
|
||||
function parseQuestions(value: unknown): AdminPublicBookingQuestion[] {
|
||||
if (!Array.isArray(value)) return [];
|
||||
return value.flatMap((item) => {
|
||||
if (
|
||||
!item ||
|
||||
typeof item !== "object" ||
|
||||
!("id" in item) ||
|
||||
typeof item.id !== "string" ||
|
||||
!("label" in item) ||
|
||||
typeof item.label !== "string"
|
||||
) {
|
||||
return [];
|
||||
}
|
||||
const type =
|
||||
"type" in item &&
|
||||
(item.type === "textarea" || item.type === "select")
|
||||
? item.type
|
||||
: "text";
|
||||
return [
|
||||
{
|
||||
id: item.id,
|
||||
label: item.label,
|
||||
required: "required" in item && item.required === true,
|
||||
type,
|
||||
options:
|
||||
"options" in item && Array.isArray(item.options)
|
||||
? item.options.filter(
|
||||
(option: unknown): option is string =>
|
||||
typeof option === "string"
|
||||
)
|
||||
: [],
|
||||
},
|
||||
];
|
||||
});
|
||||
}
|
||||
Reference in new issue
Block a user