feat: Implements maxLeadThreshold (#17643)

* feat: Implements maxLeadThreshold which puts a maximum to the amount of lead a given host is allowed to be ahead

* Refactor getLuckyUser + implement in handleNewBooking + move logic to repo

* Decoupled @prisma from findQualifiedHosts

* Fix deep type error

* Add maxLeadThreshold to builder.ts

* Removed a console.log :O + fix handleChildrenEventTypes input

* Add distribution UI to enable balanced distribution/maximize availability

* 0-1-2 instead of 0-1-2-3 (3 bookings instead of 4)
This commit is contained in:
Alex van Andel authored and GitHub committed 2024-11-15 15:54:02 +00:00
1 parent c6aa57177a
commit f76696032e
26 files changed
+626 -123

No files matched your search

@@ -57,7 +57,7 @@ import logger from "@calcom/lib/logger";
import { handlePayment } from "@calcom/lib/payment/handlePayment";
import { getPiiFreeCalendarEvent, getPiiFreeEventType } from "@calcom/lib/piiFreeData";
import { safeStringify } from "@calcom/lib/safeStringify";
import { DistributionMethod, getLuckyUser } from "@calcom/lib/server/getLuckyUser";
import { getLuckyUser } from "@calcom/lib/server/getLuckyUser";
import { getTranslation } from "@calcom/lib/server/i18n";
import { WorkflowRepository } from "@calcom/lib/server/repository/workflow";
import { getTimeFormatStringFromUserTimeFormat } from "@calcom/lib/timeFormat";
@@ -469,7 +469,7 @@ async function handler(
const newLuckyUser = isSameRoundRobinHost
? freeUsers.find((user) => user.id === originalRescheduledBookingUserId)
: await getLuckyUser(DistributionMethod.PRIORITIZE_AVAILABILITY, {
: await getLuckyUser({
// find a lucky user that is not already in the luckyUsers array
availableUsers: freeUsers,
allRRHosts: eventTypeWithUsers.hosts.filter((host) => !host.isFixed),
@@ -53,6 +53,7 @@ export const getEventTypesFromDB = async (eventTypeId: number) => {
lockTimeZoneToggleOnBookingPage: true,
requiresConfirmation: true,
requiresBookerEmailVerification: true,
maxLeadThreshold: true,
minimumBookingNotice: true,
userId: true,
price: true,
@@ -2,6 +2,7 @@ import type { Prisma } from "@prisma/client";
import type { IncomingMessage } from "http";
import type { Logger } from "tslog";
import { filterHostsByLeadThreshold } from "@calcom/lib/bookings/filterHostsByLeadThreshold";
import { HttpError } from "@calcom/lib/http-error";
import { getPiiFreeUser } from "@calcom/lib/piiFreeData";
import { safeStringify } from "@calcom/lib/safeStringify";
@@ -16,9 +17,13 @@ import type { NewBookingEventType } from "./types";
type Users = (Awaited<ReturnType<typeof loadUsers>>[number] & {
isFixed?: boolean;
metadata?: Prisma.JsonValue;
createdAt?: Date;
})[];
type EventType = Pick<NewBookingEventType, "hosts" | "users" | "id" | "userId" | "schedulingType">;
type EventType = Pick<
NewBookingEventType,
"hosts" | "users" | "id" | "userId" | "schedulingType" | "maxLeadThreshold"
>;
type InputProps = {
req: IncomingMessage;
@@ -79,7 +84,7 @@ export async function loadAndValidateUsers({
}
if (!users) throw new HttpError({ statusCode: 404, message: "eventTypeUser.notFound" });
// map fixed users
users = users.map((user) => ({
...user,
isFixed:
@@ -88,6 +93,22 @@ export async function loadAndValidateUsers({
: user.isFixed || eventType.schedulingType !== SchedulingType.ROUND_ROBIN,
}));
const qualifiedHosts = await filterHostsByLeadThreshold({
eventTypeId: eventType.id,
hosts: eventType.hosts.map((host) => ({
isFixed: host.isFixed,
createdAt: host.createdAt,
email: host.user.email,
user: host.user,
})),
maxLeadThreshold: eventType.maxLeadThreshold,
});
if (qualifiedHosts.length) {
// remove users that are not in the qualified hosts array
const qualifiedHostIds = new Set(qualifiedHosts.map((qualifiedHost) => qualifiedHost.user.id));
users = users.filter((user) => qualifiedHostIds.has(user.id));
}
logger.debug(
"Concerned users",
safeStringify({
@@ -46,13 +46,19 @@ export const loadUsers = async ({
const loadUsersByEventType = async (eventType: EventType): Promise<NewBookingEventType["users"]> => {
const hosts = eventType.hosts || [];
const users = hosts.map(({ user, isFixed, priority, weight }) => ({
const users = hosts.map(({ user, isFixed, priority, weight, createdAt }) => ({
...user,
isFixed,
priority,
weight,
createdAt,
}));
return users.length ? users : eventType.users;
return users.length
? users
: eventType.users.map((user) => ({
...user,
createdAt: null,
}));
};
const loadDynamicUsers = async (dynamicUserList: string[], currentOrgDomain: string | null) => {
@@ -225,7 +225,6 @@ export default async function handleChildrenEventTypes({
const updatePayloadFiltered = Object.entries(updatePayload)
.filter(([key, _]) => key !== "children")
.reduce((newObj, [key, value]) => ({ ...newObj, [key]: value }), {});
console.log({ unlockedFieldProps });
// Update event types for old users
const oldEventTypes = await prisma.$transaction(
oldUserIds.map((userId) => {
@@ -21,7 +21,6 @@ import { SENDER_NAME } from "@calcom/lib/constants";
import { getBookerBaseUrl } from "@calcom/lib/getBookerUrl/server";
import logger from "@calcom/lib/logger";
import { getLuckyUser } from "@calcom/lib/server";
import { DistributionMethod } from "@calcom/lib/server/getLuckyUser";
import { getTranslation } from "@calcom/lib/server/i18n";
import { getTimeFormatStringFromUserTimeFormat } from "@calcom/lib/timeFormat";
import { prisma } from "@calcom/prisma";
@@ -126,7 +125,7 @@ export const roundRobinReassignment = async ({
roundRobinReassignLogger
);
const reassignedRRHost = await getLuckyUser(DistributionMethod.PRIORITIZE_AVAILABILITY, {
const reassignedRRHost = await getLuckyUser({
availableUsers,
eventType: {
id: eventType.id,
@@ -19,7 +19,7 @@ import type {
} from "@calcom/features/eventtypes/lib/types";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { SchedulingType } from "@calcom/prisma/enums";
import { Label, Select, SettingsToggle } from "@calcom/ui";
import { Label, Select, SettingsToggle, RadioGroup as RadioArea } from "@calcom/ui";
export type EventTeamAssignmentTabBaseProps = Pick<EventTypeSetupProps, "teamMembers" | "team" | "eventType">;
@@ -333,7 +333,6 @@ const Hosts = ({
assignAllTeamMembers: boolean;
setAssignAllTeamMembers: Dispatch<SetStateAction<boolean>>;
}) => {
const { t } = useLocale();
const {
control,
setValue,
@@ -498,6 +497,44 @@ export const EventTeamAssignmentTab = ({ team, teamMembers, eventType }: EventTe
/>
</div>
</div>
<div className="border-subtle mt-4 flex flex-col rounded-md">
<div className="border-subtle rounded-t-md border p-6 pb-5">
<Label className="mb-1 text-sm font-semibold">{t("rr_distribution_method")}</Label>
<p className="text-subtle max-w-full break-words text-sm leading-tight">
{t("rr_distribution_method_description")}
</p>
</div>
<div className="border-subtle rounded-b-md border border-t-0 p-6">
<Controller
name="maxLeadThreshold"
render={({ field: { value, onChange } }) => (
<RadioArea.Group
onValueChange={(val) => {
if (val === "loadBalancing") onChange(3);
else onChange(null);
}}
className="mt-1 flex flex-col gap-4">
<RadioArea.Item
value="maximizeAvailability"
checked={value === null}
className="w-full text-sm"
classNames={{ container: "w-full" }}>
<strong className="mb-1 block">{t("rr_distribution_method_availability_title")}</strong>
<p>{t("rr_distribution_method_availability_description")}</p>
</RadioArea.Item>
<RadioArea.Item
value="loadBalancing"
checked={value !== null}
className="text-sm"
classNames={{ container: "w-full" }}>
<strong className="mb-1 block">{t("rr_distribution_method_balanced_title")}</strong>
<p>{t("rr_distribution_method_balanced_description")}</p>
</RadioArea.Item>
</RadioArea.Group>
)}
/>
</div>
</div>
<Hosts
assignAllTeamMembers={assignAllTeamMembers}
setAssignAllTeamMembers={setAssignAllTeamMembers}
@@ -137,6 +137,7 @@ export type FormValues = {
forwardParamsSuccessRedirect: boolean | null;
secondaryEmailId?: number;
isRRWeightsEnabled: boolean;
maxLeadThreshold?: number;
};
export type LocationFormValues = Pick<FormValues, "id" | "locations" | "bookingFields" | "seatsPerTimeSlot">;