feat: availability in instant meeting (#16424)

* chore: save progress

* feat: add isAvailable functionality

* fix: type error

* chore: add in builder

* tests: add unit tests

* chore: improvements

* chore: tests

* chore

* chore: remove log

* fix: tets

---------

Co-authored-by: Morgan <[email protected]>
This commit is contained in:
Udit TakkarandMorgan authored and GitHub committed 2024-09-03 14:28:15 +00:00
1 parent b8d67c5a41
commit 6cd427bc78
17 files changed
+351 -12

No files matched your search

@@ -2201,6 +2201,7 @@
"member_removed": "Member removed",
"my_availability": "My Availability",
"team_availability": "Team Availability",
"instant_meeting_availability": "Instant meeting availability",
"backup_code": "Backup Code",
"backup_codes": "Backup Codes",
"backup_code_instructions": "Each backup code can be used exactly once to grant access without your authenticator.",
@@ -143,6 +143,7 @@ describe("handleChildrenEventTypes", () => {
users: { connect: [{ id: 4 }] },
lockTimeZoneToggleOnBookingPage: false,
requiresBookerEmailVerification: false,
instantMeetingScheduleId: undefined,
bookingLimits: undefined,
durationLimits: undefined,
recurringEvent: undefined,
@@ -199,6 +200,7 @@ describe("handleChildrenEventTypes", () => {
scheduleId: null,
lockTimeZoneToggleOnBookingPage: false,
requiresBookerEmailVerification: false,
instantMeetingScheduleId: undefined,
hashedLink: { create: { link: expect.any(String) } },
},
where: {
@@ -304,6 +306,7 @@ describe("handleChildrenEventTypes", () => {
recurringEvent: undefined,
eventTypeColor: undefined,
hashedLink: undefined,
instantMeetingScheduleId: undefined,
lockTimeZoneToggleOnBookingPage: false,
requiresBookerEmailVerification: false,
userId: 4,
@@ -357,6 +360,7 @@ describe("handleChildrenEventTypes", () => {
locations: [],
lockTimeZoneToggleOnBookingPage: false,
requiresBookerEmailVerification: false,
instantMeetingScheduleId: undefined,
},
where: {
userId_parentId: {
@@ -421,6 +425,7 @@ describe("handleChildrenEventTypes", () => {
recurringEvent: undefined,
eventTypeColor: undefined,
hashedLink: undefined,
instantMeetingScheduleId: undefined,
locations: [],
lockTimeZoneToggleOnBookingPage: false,
requiresBookerEmailVerification: false,
@@ -447,6 +452,7 @@ describe("handleChildrenEventTypes", () => {
lockTimeZoneToggleOnBookingPage: false,
requiresBookerEmailVerification: false,
hashedLink: undefined,
instantMeetingScheduleId: undefined,
},
where: {
userId_parentId: {
+1 -1
View File
@@ -439,7 +439,7 @@ const BookerComponent = ({
}}
/>
{bookerState !== "booking" && event.data?.isInstantEvent && (
{bookerState !== "booking" && event.data?.showInstantEventConnectNowModal && (
<div
className={classNames(
"animate-fade-in-up z-40 my-2 opacity-0",
+1 -1
View File
@@ -51,7 +51,7 @@ export type BookerEvent = Pick<
| "bookingFields"
| "seatsShowAvailabilityCount"
| "isInstantEvent"
> & { users: BookerEventUser[] } & { profile: BookerEventProfile };
> & { users: BookerEventUser[]; showInstantEventConnectNowModal: boolean } & { profile: BookerEventProfile };
export type ValidationErrors<T extends object> = { key: FieldPath<T>; error: ErrorOption }[];
@@ -210,6 +210,7 @@ export const EventType = (props: EventTypeSetupProps & { allActiveWorkflows?: Wo
instantMeetingExpiryTimeOffsetInSeconds: eventType.instantMeetingExpiryTimeOffsetInSeconds,
description: eventType.description ?? undefined,
schedule: eventType.schedule || undefined,
instantMeetingSchedule: eventType.instantMeetingSchedule || undefined,
bookingLimits: eventType.bookingLimits || undefined,
onlyShowFirstAvailableSlot: eventType.onlyShowFirstAvailableSlot || undefined,
durationLimits: eventType.durationLimits || undefined,
@@ -2,10 +2,12 @@ import type { Webhook } from "@prisma/client";
import { useSession } from "next-auth/react";
import { useState } from "react";
import { useFormContext, Controller } from "react-hook-form";
import { components } from "react-select";
import type { OptionProps, SingleValueProps } from "react-select";
import LicenseRequired from "@calcom/features/ee/common/components/LicenseRequired";
import useLockedFieldsManager from "@calcom/features/ee/managed-event-types/hooks/useLockedFieldsManager";
import type { EventTypeSetup, FormValues } from "@calcom/features/eventtypes/lib/types";
import type { EventTypeSetup, FormValues, AvailabilityOption } from "@calcom/features/eventtypes/lib/types";
import { WebhookForm } from "@calcom/features/webhooks/components";
import type { WebhookFormSubmitData } from "@calcom/features/webhooks/components/WebhookForm";
import WebhookListItem from "@calcom/features/webhooks/components/WebhookListItem";
@@ -24,6 +26,8 @@ import {
showToast,
TextField,
Label,
Select,
Badge,
} from "@calcom/ui";
type InstantEventControllerProps = {
@@ -32,6 +36,36 @@ type InstantEventControllerProps = {
isTeamEvent: boolean;
};
const Option = ({ ...props }: OptionProps<AvailabilityOption>) => {
const { label, isDefault } = props.data;
const { t } = useLocale();
return (
<components.Option {...props}>
<span>{label}</span>
{isDefault && (
<Badge variant="blue" className="ml-2">
{t("default")}
</Badge>
)}
</components.Option>
);
};
const SingleValue = ({ ...props }: SingleValueProps<AvailabilityOption>) => {
const { label, isDefault } = props.data;
const { t } = useLocale();
return (
<components.SingleValue {...props}>
<span>{label}</span>
{isDefault && (
<Badge variant="blue" className="ml-2">
{t("default")}
</Badge>
)}
</components.SingleValue>
);
};
export default function InstantEventController({
eventType,
paymentEnabled,
@@ -42,13 +76,28 @@ export default function InstantEventController({
const [instantEventState, setInstantEventState] = useState<boolean>(eventType?.isInstantEvent ?? false);
const formMethods = useFormContext<FormValues>();
const { shouldLockDisableProps } = useLockedFieldsManager({ eventType, translate: t, formMethods });
const { shouldLockDisableProps } = useLockedFieldsManager({
eventType,
translate: t,
formMethods,
});
const instantLocked = shouldLockDisableProps("isInstantEvent");
const isOrg = !!session.data?.user?.org?.id;
if (session.status === "loading") return <></>;
const { data, isPending } = trpc.viewer.availability.list.useQuery(undefined);
if (session.status === "loading" || isPending || !data) return <></>;
const schedules = data.schedules;
const options = schedules.map((schedule) => ({
value: schedule.id,
label: schedule.name,
isDefault: schedule.isDefault,
isManaged: false,
}));
return (
<LicenseRequired>
@@ -96,6 +145,32 @@ export default function InstantEventController({
<div className="border-subtle rounded-b-lg border border-t-0 p-6">
{instantEventState && (
<div className="flex flex-col gap-2">
<Controller
name="instantMeetingSchedule"
render={({ field: { onChange, value } }) => {
const optionValue: AvailabilityOption | undefined = options.find(
(option) => option.value === value
);
return (
<>
<Label>{t("instant_meeting_availability")}</Label>
<Select
placeholder={t("select")}
options={options}
isDisabled={shouldLockDisableProps("instantMeetingSchedule").disabled}
isSearchable={false}
onChange={(selected) => {
if (selected) onChange(selected.value);
}}
className="mb-4 block w-full min-w-0 flex-1 rounded-sm text-sm"
value={optionValue}
components={{ Option, SingleValue }}
isMulti={false}
/>
</>
);
}}
/>
<Controller
name="instantMeetingExpiryTimeOffsetInSeconds"
render={({ field: { value, onChange } }) => (
@@ -4,6 +4,7 @@ import { Prisma } from "@prisma/client";
import type { LocationObject } from "@calcom/app-store/locations";
import { privacyFilteredLocations } from "@calcom/app-store/locations";
import { getAppFromSlug } from "@calcom/app-store/utils";
import dayjs from "@calcom/dayjs";
import { getBookingFieldsWithSystemFields } from "@calcom/features/bookings/lib/getBookingFields";
import { getSlugOrRequestedSlug } from "@calcom/features/ee/organizations/lib/orgDomains";
import { isRecurringEvent, parseRecurringEvent } from "@calcom/lib";
@@ -120,11 +121,84 @@ const publicEventSelect = Prisma.validator<Prisma.EventTypeSelect>()({
timeZone: true,
},
},
instantMeetingSchedule: {
select: {
id: true,
timeZone: true,
},
},
hidden: true,
assignAllTeamMembers: true,
rescheduleWithSameRoundRobinHost: true,
});
export async function isCurrentlyAvailable({
prisma,
instantMeetingScheduleId,
availabilityTimezone,
length,
}: {
prisma: PrismaClient;
instantMeetingScheduleId: number;
availabilityTimezone: string;
length: number;
}): Promise<boolean> {
const now = dayjs().tz(availabilityTimezone);
const currentDay = now.day();
const meetingEndTime = now.add(length, "minute");
const res = await prisma.schedule.findUniqueOrThrow({
where: {
id: instantMeetingScheduleId,
},
select: {
availability: true,
},
});
const dateOverride = res.availability.find((a) => a.date && dayjs(a.date).isSame(now, "day"));
if (dateOverride) {
return !isAvailableInTimeSlot(dateOverride, now, meetingEndTime);
}
for (const availability of res.availability) {
if (!availability.date && availability.days.includes(currentDay)) {
const isAvailable = isAvailableInTimeSlot(availability, now, meetingEndTime);
if (isAvailable) {
return true;
}
}
}
return false;
}
function isAvailableInTimeSlot(
availability: { startTime: Date; endTime: Date; days: number[] },
now: dayjs.Dayjs,
meetingEndTime: dayjs.Dayjs
): boolean {
const startTime = dayjs(availability.startTime).utc().format("HH:mm");
const endTime = dayjs(availability.endTime).utc().format("HH:mm");
const periodStart = now
.startOf("day")
.hour(parseInt(startTime.split(":")[0]))
.minute(parseInt(startTime.split(":")[1]));
const periodEnd = now
.startOf("day")
.hour(parseInt(endTime.split(":")[0]))
.minute(parseInt(endTime.split(":")[1]));
const isWithinPeriod =
now.isBetween(periodStart, periodEnd, null, "[)") &&
meetingEndTime.isBetween(periodStart, periodEnd, null, "(]");
return isWithinPeriod;
}
// TODO: Convert it to accept a single parameter with structured data
export const getPublicEvent = async (
username: string,
@@ -216,6 +290,7 @@ export const getPublicEvent = async (
logoUrl: null,
},
isInstantEvent: false,
showInstantEventConnectNowModal: false,
};
}
@@ -334,6 +409,20 @@ export const getPublicEvent = async (
},
});
}
let showInstantEventConnectNowModal = eventWithUserProfiles.isInstantEvent;
if (eventWithUserProfiles.isInstantEvent && eventWithUserProfiles.instantMeetingSchedule?.id) {
const { id, timeZone } = eventWithUserProfiles.instantMeetingSchedule;
showInstantEventConnectNowModal = await isCurrentlyAvailable({
prisma,
instantMeetingScheduleId: id,
availabilityTimezone: timeZone ?? "Europe/London",
length: eventWithUserProfiles.length,
});
}
return {
...eventWithUserProfiles,
bookerLayouts: bookerLayoutsSchema.parse(eventMetaData?.bookerLayouts || null),
@@ -372,6 +461,7 @@ export const getPublicEvent = async (
isDynamic: false,
isInstantEvent: eventWithUserProfiles.isInstantEvent,
showInstantEventConnectNowModal,
aiPhoneCallConfig: eventWithUserProfiles.aiPhoneCallConfig,
assignAllTeamMembers: event.assignAllTeamMembers,
};
@@ -0,0 +1,134 @@
import { PrismaClient } from "@prisma/client";
import { describe, it, expect, vi, beforeAll } from "vitest";
import { isCurrentlyAvailable } from "./getPublicEvent";
const prisma = new PrismaClient();
beforeAll(() => {
vi.setSystemTime(new Date("2024-09-01T10:00:00Z"));
});
describe("isCurrentlyAvailable", () => {
it("should return true if the current time is within the availability period", async () => {
const mockAvailability = [
{
startTime: new Date("1970-01-01T09:00:00Z"),
endTime: new Date("1970-01-01T17:00:00Z"),
days: [0, 1, 2, 3, 4, 5, 6],
},
];
vi.spyOn(prisma.schedule, "findUniqueOrThrow").mockResolvedValue({
availability: mockAvailability,
});
const result = await isCurrentlyAvailable({
prisma,
instantMeetingScheduleId: 1,
availabilityTimezone: "Europe/London",
length: 30,
});
expect(result).toBe(true);
});
it("should return false if the current time is outside the availability period", async () => {
const mockAvailability = [
{
startTime: new Date("1970-01-01T09:00:00Z"),
endTime: new Date("1970-01-01T17:00:00Z"),
days: [1, 2, 3, 4, 5],
},
];
vi.spyOn(prisma.schedule, "findUniqueOrThrow").mockResolvedValue({
availability: mockAvailability,
});
const result = await isCurrentlyAvailable({
prisma,
instantMeetingScheduleId: 1,
availabilityTimezone: "Europe/London",
length: 30,
});
expect(result).toBe(false);
});
it("should return false if there is no availability for the current day", async () => {
const mockAvailability = [
{
startTime: new Date("1970-01-01T12:00:00Z"),
endTime: new Date("1970-01-01T17:00:00Z"),
days: [0],
},
];
vi.spyOn(prisma.schedule, "findUniqueOrThrow").mockResolvedValue({
availability: mockAvailability,
});
const result = await isCurrentlyAvailable({
prisma,
instantMeetingScheduleId: 1,
availabilityTimezone: "Europe/London",
length: 30,
});
expect(result).toBe(false);
});
it("should return false if the meeting end time is outside the availability period", async () => {
const mockAvailability = [
{
startTime: new Date("1970-01-01T09:00:00Z"),
endTime: new Date("1970-01-01T17:00:00Z"),
days: [1, 2, 3, 4, 5],
},
];
vi.spyOn(prisma.schedule, "findUniqueOrThrow").mockResolvedValue({
availability: mockAvailability,
});
const result = await isCurrentlyAvailable({
prisma,
instantMeetingScheduleId: 1,
availabilityTimezone: "Europe/London",
length: 60,
});
expect(result).toBe(false);
});
it("should return false when there's an override blocking availability", async () => {
const mockAvailability = [
{
startTime: new Date("1970-01-01T00:00:00Z"),
endTime: new Date("1970-01-01T23:59:59Z"),
days: [0, 1, 2, 3, 4, 5, 6],
},
// Date-specific override
{
date: new Date("2024-09-01"),
startTime: new Date("2024-09-01T09:00:00Z"),
endTime: new Date("2024-09-01T17:00:00Z"),
days: [],
},
];
vi.spyOn(prisma.schedule, "findUniqueOrThrow").mockResolvedValue({
availability: mockAvailability,
});
const result = await isCurrentlyAvailable({
prisma,
instantMeetingScheduleId: 1,
availabilityTimezone: "Europe/London",
length: 30,
});
expect(result).toBe(false);
});
});
@@ -104,6 +104,7 @@ export const getEventTypeById = async ({
const eventType = {
...restEventType,
schedule: rawEventType.schedule?.id || rawEventType.users[0]?.defaultScheduleId || null,
instantMeetingSchedule: rawEventType.instantMeetingSchedule?.id || null,
scheduleName: rawEventType.schedule?.name || null,
recurringEvent: parseRecurringEvent(restEventType.recurringEvent),
bookingLimits: parseBookingLimit(restEventType.bookingLimits),
+1
View File
@@ -36,6 +36,7 @@ export const eventTypeSelect = Prisma.validator<Prisma.EventTypeSelect>()({
seatsShowAttendees: true,
seatsShowAvailabilityCount: true,
scheduleId: true,
instantMeetingScheduleId: true,
price: true,
currency: true,
slotInterval: true,
@@ -521,6 +521,12 @@ export class EventTypeRepository {
name: true,
},
},
instantMeetingSchedule: {
select: {
id: true,
name: true,
},
},
hosts: {
select: {
isFixed: true,
+1
View File
@@ -86,6 +86,7 @@ export const buildEventType = (eventType?: Partial<EventType>): EventType => {
position: 1,
isInstantEvent: false,
instantMeetingExpiryTimeOffsetInSeconds: 90,
instantMeetingScheduleId: null,
locations: null,
length: 15,
offsetStart: 0,
@@ -0,0 +1,5 @@
-- AlterTable
ALTER TABLE "EventType" ADD COLUMN "instantMeetingScheduleId" INTEGER;
-- AddForeignKey
ALTER TABLE "EventType" ADD CONSTRAINT "EventType_instantMeetingScheduleId_fkey" FOREIGN KEY ("instantMeetingScheduleId") REFERENCES "Schedule"("id") ON DELETE SET NULL ON UPDATE CASCADE;
+10 -7
View File
@@ -138,6 +138,8 @@ model EventType {
durationLimits Json?
isInstantEvent Boolean @default(false)
instantMeetingExpiryTimeOffsetInSeconds Int @default(90)
instantMeetingScheduleId Int?
instantMeetingSchedule Schedule? @relation("InstantMeetingSchedule", fields: [instantMeetingScheduleId], references: [id])
assignAllTeamMembers Boolean @default(false)
useEventTypeDestinationCalendarEmail Boolean @default(false)
aiPhoneCallConfig AIPhoneCallConfiguration?
@@ -622,13 +624,14 @@ model Booking {
}
model Schedule {
id Int @id @default(autoincrement())
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
userId Int
eventType EventType[]
name String
timeZone String?
availability Availability[]
id Int @id @default(autoincrement())
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
userId Int
eventType EventType[]
instantMeetingEvents EventType[] @relation("InstantMeetingSchedule")
name String
timeZone String?
availability Availability[]
@@index([userId])
}
@@ -90,6 +90,7 @@ export const duplicateHandler = async ({ ctx, input }: DuplicateOptions) => {
// @ts-ignore - descriptionAsSafeHTML is added on the fly using a prisma middleware it shouldn't be used to create event type. Such a property doesn't exist on schema
descriptionAsSafeHTML: _descriptionAsSafeHTML,
secondaryEmailId,
instantMeetingScheduleId: _instantMeetingScheduleId,
...rest
} = eventType;
@@ -61,6 +61,7 @@ export const EventTypeUpdateInput = _EventTypeModel
)
.optional(),
schedule: z.number().nullable().optional(),
instantMeetingSchedule: z.number().nullable().optional(),
hashedLink: z.string(),
assignAllTeamMembers: z.boolean().optional(),
isRRWeightsEnabled: z.boolean().optional(),
@@ -51,6 +51,7 @@ export type UpdateEventTypeReturn = Awaited<ReturnType<typeof updateHandler>>;
export const updateHandler = async ({ ctx, input }: UpdateOptions) => {
const {
schedule,
instantMeetingSchedule,
periodType,
locations,
bookingLimits,
@@ -231,6 +232,18 @@ export const updateHandler = async ({ ctx, input }: UpdateOptions) => {
};
}
if (instantMeetingSchedule) {
data.instantMeetingSchedule = {
connect: {
id: instantMeetingSchedule,
},
};
} else if (schedule === null) {
data.instantMeetingSchedule = {
disconnect: true,
};
}
if (users?.length) {
data.users = {
set: [],