refactor: api v2 schedules (#14870)

* api: createSchedule refactor - still need to handle overrides

* createSchedule: handle overrides

* createSchedule: default schedule e2e test fix and pad hours:minutes

* get default schedule, by id and all schedules

* update schedule

* refactor: update handler delete only if overrides or availabilities given

* remove comment

* refactor: move schedules inputs, outputs to platform-types + e2e tests refactor

* refactor e2e

* fix: overrides and test

* fix managed user create

* my brain is fried but refactor good

* WIP: transform api schedule for atom

* WIP: transform api schedule for atom

* WIP: transform api schedule for atom

* fix: re-export atom transformer from lib

* fix: format schedule for api from atom

* fix ts ignore

* refactor: move schedule hooks into hooks/schedules

* feat: useSchedules hook to get count of user schedules

* tests: setup atom tests & test transformScheduleForAtom

* rename transformers

* test transformAtomScheduleForApi

* reset scheduel update handler for trpc

* fix: import path

* refactor: transformers

* swagger docs fix

* get rid of unused availabilities module

* get rid of eslint-disable-next-line in schedules repository

* refactor: remove crypto from atoms vite rollupOptions

* refactor: comment schedules repository update logic
This commit is contained in:
Lauris Skraucis authored and GitHub committed 2024-05-16 15:20:13 +03:00
1 parent ca05e701a8
commit c25c835b76
55 files changed
+1391 -1209

No files matched your search

+3 -3
View File
@@ -128,10 +128,10 @@ export function getWorkingHours(
}
export function availabilityAsString(
availability: Availability,
availability: Pick<Availability, "days" | "startTime" | "endTime">,
{ locale, hour12 }: { locale?: string; hour12?: boolean }
) {
const weekSpan = (availability: Availability) => {
const weekSpan = (availability: Pick<Availability, "days" | "startTime" | "endTime">) => {
const days = availability.days.slice(1).reduce(
(days, day) => {
if (days[days.length - 1].length === 1 && days[days.length - 1][0] === day - 1) {
@@ -153,7 +153,7 @@ export function availabilityAsString(
.join(", ");
};
const timeSpan = (availability: Availability) => {
const timeSpan = (availability: Pick<Availability, "days" | "startTime" | "endTime">) => {
return `${new Intl.DateTimeFormat(locale, { hour: "numeric", minute: "numeric", hour12 }).format(
new Date(availability.startTime.toISOString().slice(0, -1))
)} - ${new Intl.DateTimeFormat(locale, { hour: "numeric", minute: "numeric", hour12 }).format(
+1 -1
View File
@@ -1 +1 @@
export * from "./client/transformers";
export * from "./transformers";
@@ -1,33 +1,25 @@
import type { Availability as AvailabilityModel, Schedule as ScheduleModel } from "@prisma/client";
import type { Availability } from "@prisma/client";
import dayjs from "@calcom/dayjs";
import { getWorkingHours } from "@calcom/lib/availability";
import { yyyymmdd } from "@calcom/lib/date-fns";
import type { Schedule, TimeRange } from "@calcom/types/schedule";
export type ScheduleWithAvailabilities = ScheduleModel & { availability: AvailabilityModel[] };
type ScheduleAvailability = Pick<Availability, "days" | "startTime" | "endTime">[];
type ScheduleOverride = Pick<Availability, "date" | "startTime" | "endTime">[];
export type ScheduleWithAvailabilitiesForWeb = Pick<ScheduleModel, "id" | "name"> & {
isManaged: boolean;
workingHours: ReturnType<typeof transformWorkingHoursForClient>;
schedule: AvailabilityModel[];
availability: ReturnType<typeof transformAvailabilityForClient>;
timeZone: string;
dateOverrides: ReturnType<typeof transformDateOverridesForClient>;
isDefault: boolean;
isLastSchedule: boolean;
readOnly: boolean;
};
export function transformWorkingHoursForClient(schedule: ScheduleWithAvailabilities) {
export function transformWorkingHoursForAtom(schedule: {
timeZone: string | null;
availability: ScheduleAvailability;
}) {
return getWorkingHours(
{ timeZone: schedule.timeZone || undefined, utcOffset: 0 },
schedule.availability || []
);
}
export function transformAvailabilityForClient(schedule: ScheduleWithAvailabilities) {
return transformScheduleToAvailabilityForClient(schedule).map((a) =>
export function transformAvailabilityForAtom(schedule: { availability: ScheduleAvailability }) {
return transformScheduleToAvailabilityForAtom(schedule).map((a) =>
a.map((startAndEnd) => ({
...startAndEnd,
end: new Date(startAndEnd.end.toISOString().replace("23:59:00.000Z", "23:59:59.999Z")),
@@ -35,7 +27,10 @@ export function transformAvailabilityForClient(schedule: ScheduleWithAvailabilit
);
}
export function transformDateOverridesForClient(schedule: ScheduleWithAvailabilities, timeZone: string) {
export function transformDateOverridesForAtom(
schedule: { availability: ScheduleOverride },
timeZone: string
) {
return schedule.availability.reduce((acc, override) => {
// only iff future date override
if (!override.date || dayjs.tz(override.date, timeZone).isBefore(dayjs(), "day")) {
@@ -67,9 +62,7 @@ export function transformDateOverridesForClient(schedule: ScheduleWithAvailabili
}, [] as { ranges: TimeRange[] }[]);
}
export const transformScheduleToAvailabilityForClient = (
schedule: Partial<ScheduleModel> & { availability: AvailabilityModel[] }
) => {
export const transformScheduleToAvailabilityForAtom = (schedule: { availability: ScheduleAvailability }) => {
return schedule.availability.reduce(
(schedule: Schedule, availability) => {
availability.days.forEach((day) => {
@@ -0,0 +1,54 @@
import type { ScheduleAvailabilityInput } from "@calcom/platform-types";
import type { ScheduleOverrideInput } from "@calcom/platform-types";
import type { WeekDay } from "@calcom/platform-types";
export function transformApiScheduleAvailability(inputAvailability: ScheduleAvailabilityInput[]) {
return inputAvailability.map((availability) => ({
days: availability.days.map(transformDayToNumber),
startTime: createDateFromHoursMinutes(availability.startTime),
endTime: createDateFromHoursMinutes(availability.endTime),
}));
}
export function transformApiScheduleOverrides(inputOverrides: ScheduleOverrideInput[]) {
return inputOverrides.map((override) => ({
date: new Date(override.date),
startTime: createDateFromHoursMinutes(override.startTime),
endTime: createDateFromHoursMinutes(override.endTime),
}));
}
function createDateFromHoursMinutes(hoursMinutes: string): Date {
const parts = hoursMinutes.split(":");
if (parts.length < 2) {
throw new Error("Invalid time format. Please use 'hh:mm'.");
}
const hours = parseInt(parts[0], 10);
const minutes = parseInt(parts[1], 10);
if (isNaN(hours) || hours < 0 || hours > 23) {
throw new Error("Hours must be a number between 0 and 23.");
}
if (isNaN(minutes) || minutes < 0 || minutes > 59) {
throw new Error("Minutes must be a number between 0 and 59.");
}
const utcDate = new Date(Date.UTC(1970, 0, 1, hours, minutes));
return utcDate;
}
function transformDayToNumber(day: WeekDay): number {
const weekMap: { [key in WeekDay]: number } = {
Sunday: 0,
Monday: 1,
Tuesday: 2,
Wednesday: 3,
Thursday: 4,
Friday: 5,
Saturday: 6,
};
return weekMap[day];
}
@@ -0,0 +1,2 @@
export * from "./for-atom";
export * from "./from-api";
@@ -62,6 +62,8 @@ export type CustomClassNames = {
};
};
export type Availability = Pick<Schedule, "days" | "startTime" | "endTime">;
type AvailabilitySettingsProps = {
skeletonLabel?: string;
schedule: {
@@ -73,7 +75,7 @@ type AvailabilitySettingsProps = {
workingHours: WorkingHours[];
dateOverrides: { ranges: TimeRange[] }[];
timeZone: string;
schedule: Schedule[];
schedule: Availability[];
};
travelSchedules?: RouterOutputs["viewer"]["getTravelSchedules"];
handleDelete: () => void;
@@ -274,7 +276,9 @@ export function AvailabilitySettings({
schedule.schedule
.filter((availability) => !!availability.days.length)
.map((availability) => (
<span key={availability.id} className={cn(customClassNames?.subtitlesClassName)}>
<span
key={availability.startTime.valueOf().toString()}
className={cn(customClassNames?.subtitlesClassName)}>
{availabilityAsString(availability, { locale: i18n.language, hour12: timeFormat === 12 })}
<br />
</span>
@@ -0,0 +1,127 @@
import type { ScheduleOutput } from "@calcom/platform-types";
import type { User } from "@calcom/prisma/client";
import { transformApiScheduleForAtom } from "./transformApiScheduleForAtom";
const SCHEDULE_OWNER_ID = 256;
describe("transformScheduleForAtom", () => {
const user: Pick<User, "id" | "defaultScheduleId" | "timeZone"> = {
id: SCHEDULE_OWNER_ID,
defaultScheduleId: 139,
timeZone: "America/New_York",
};
beforeEach(() => {
jest.resetAllMocks();
});
it("should return null if user is not provided", () => {
const schedule: ScheduleOutput | null = {
id: 139,
ownerId: SCHEDULE_OWNER_ID,
name: "Default",
timeZone: "America/Cancun",
availability: [
{
days: ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"],
startTime: "09:00",
endTime: "17:00",
},
],
isDefault: true,
overrides: [],
};
expect(transformApiScheduleForAtom(undefined, schedule, 1)).toBeNull();
});
it("should return null if schedule is not provided", () => {
expect(transformApiScheduleForAtom(user, null, 1)).toBeNull();
});
it("should transform schedule correctly", () => {
const schedule: ScheduleOutput = {
id: 139,
ownerId: SCHEDULE_OWNER_ID,
name: "Default",
timeZone: "America/Cancun",
availability: [
{
days: ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"],
startTime: "09:00",
endTime: "17:00",
},
],
isDefault: true,
overrides: [],
};
const expectedResult = {
id: 139,
name: "Default",
isManaged: false,
workingHours: [
{
days: [1, 2, 3, 4, 5],
startTime: 540,
endTime: 1020,
userId: 256,
},
],
schedule: [
{
userId: 256,
scheduleId: 139,
days: [1, 2, 3, 4, 5],
startTime: new Date(Date.UTC(1970, 0, 1, 9, 0)),
endTime: new Date(Date.UTC(1970, 0, 1, 17, 0)),
date: null,
},
],
availability: [
[],
[
{
start: new Date("2024-05-14T09:00:00.000Z"),
end: new Date("2024-05-14T17:00:00.000Z"),
},
],
[
{
start: new Date("2024-05-14T09:00:00.000Z"),
end: new Date("2024-05-14T17:00:00.000Z"),
},
],
[
{
start: new Date("2024-05-14T09:00:00.000Z"),
end: new Date("2024-05-14T17:00:00.000Z"),
},
],
[
{
start: new Date("2024-05-14T09:00:00.000Z"),
end: new Date("2024-05-14T17:00:00.000Z"),
},
],
[
{
start: new Date("2024-05-14T09:00:00.000Z"),
end: new Date("2024-05-14T17:00:00.000Z"),
},
],
[],
],
timeZone: "America/Cancun",
dateOverrides: [],
isDefault: true,
isLastSchedule: true,
readOnly: false,
};
const result = transformApiScheduleForAtom(user, schedule, 1);
expect(result).toEqual(expectedResult);
});
});
@@ -0,0 +1,59 @@
import {
transformAvailabilityForAtom,
transformDateOverridesForAtom,
transformApiScheduleAvailability,
transformApiScheduleOverrides,
transformWorkingHoursForAtom,
} from "@calcom/lib/schedules/transformers";
import type { ScheduleOutput } from "@calcom/platform-types";
import type { User } from "@calcom/prisma/client";
export function transformApiScheduleForAtom(
user: Pick<User, "id" | "defaultScheduleId" | "timeZone"> | undefined,
schedule: ScheduleOutput | null | undefined,
userSchedulesCount: number
) {
if (!user || !schedule) {
return null;
}
const transformedSchedule = {
...schedule,
availability: transformApiScheduleAvailability(schedule.availability),
overrides: transformApiScheduleOverrides(schedule.overrides),
};
const combined = [...transformedSchedule.availability, ...transformedSchedule.overrides];
const availability = combined.map((entry) => {
return {
...entry,
userId: schedule.ownerId,
scheduleId: schedule.id,
days: "days" in entry ? entry.days : [],
date: "date" in entry ? entry.date : null,
};
});
const atomSchedule = {
...schedule,
availability,
userId: schedule.ownerId,
};
const timeZone = schedule.timeZone || user.timeZone;
const defaultScheduleId = user.defaultScheduleId;
return {
id: schedule.id,
name: schedule.name,
isManaged: schedule.ownerId !== user.id,
workingHours: transformWorkingHoursForAtom(atomSchedule),
schedule: availability,
availability: transformAvailabilityForAtom(atomSchedule),
timeZone,
dateOverrides: transformDateOverridesForAtom(atomSchedule, timeZone),
isDefault: defaultScheduleId === schedule.id,
isLastSchedule: userSchedulesCount <= 1,
readOnly: schedule.ownerId !== user.id,
};
}
@@ -0,0 +1,72 @@
import type { UpdateScheduleInput } from "@calcom/platform-types";
import type { AvailabilityFormValues } from "../types";
import { transformAtomScheduleForApi } from "./transformAtomScheduleForApi";
describe("transformAtomScheduleForApi", () => {
it("should transform atom schedule correctly to API format", () => {
const input: AvailabilityFormValues = {
name: "Default",
schedule: [
[],
[
{
start: new Date("2024-05-14T09:00:00.000Z"),
end: new Date("2024-05-14T17:00:00.000Z"),
},
],
[
{
start: new Date("2024-05-14T09:00:00.000Z"),
end: new Date("2024-05-14T17:00:00.000Z"),
},
],
[
{
start: new Date("2024-05-14T09:00:00.000Z"),
end: new Date("2024-05-14T17:00:00.000Z"),
},
],
[
{
start: new Date("2024-05-14T09:00:00.000Z"),
end: new Date("2024-05-14T17:00:00.000Z"),
},
],
[
{
start: new Date("2024-05-14T11:00:00.000Z"),
end: new Date("2024-05-14T12:00:00.000Z"),
},
],
[],
],
dateOverrides: [],
timeZone: "America/Cancun",
isDefault: true,
};
const expectedOutput: UpdateScheduleInput = {
name: "Default",
timeZone: "America/Cancun",
isDefault: true,
availability: [
{
days: ["Monday", "Tuesday", "Wednesday", "Thursday"],
startTime: "09:00",
endTime: "17:00",
},
{
days: ["Friday"],
startTime: "11:00",
endTime: "12:00",
},
],
overrides: [],
};
const result = transformAtomScheduleForApi(input);
expect(result).toEqual(expectedOutput);
});
});
@@ -0,0 +1,62 @@
import type { ScheduleAvailabilityInput, UpdateScheduleInput, WeekDay } from "@calcom/platform-types";
import type { AvailabilityFormValues } from "../types";
export function transformAtomScheduleForApi(body: AvailabilityFormValues): UpdateScheduleInput {
const { name, schedule, dateOverrides, timeZone, isDefault } = body;
const overrides =
dateOverrides.flatMap(
(dateOverridesRanges) =>
dateOverridesRanges?.ranges?.map((range) => ({
date: `${range.start.getUTCFullYear}-${range.start.getUTCMonth}-${range.start.getUTCDate}`,
startTime: `${range.start.getUTCHours}-${range.start.getUTCMinutes}`,
endTime: `${range.end.getUTCHours}-${range.end.getUTCMinutes}`,
})) ?? []
) ?? [];
const availability = formatScheduleTime(schedule);
return { name, timeZone, isDefault, availability, overrides };
}
function formatScheduleTime(
weekSchedule: AvailabilityFormValues["schedule"]
): UpdateScheduleInput["availability"] {
const daysOfWeek: WeekDay[] = [
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday",
];
const formattedSchedule = weekSchedule.map((daySchedule, index) =>
daySchedule.map((event) => ({
startTime: convertToHHMM(event.start.toISOString()),
endTime: convertToHHMM(event.end.toISOString()),
days: [daysOfWeek[index]],
}))
);
const timeMap: { [key: string]: ScheduleAvailabilityInput } = {};
formattedSchedule.flat().forEach((event) => {
const timeKey = `${event.startTime}-${event.endTime}`;
if (!timeMap[timeKey]) {
timeMap[timeKey] = { startTime: event.startTime, endTime: event.endTime, days: [] };
}
timeMap[timeKey].days.push(...event.days);
});
return Object.values(timeMap);
}
function convertToHHMM(isoDate: string): string {
const date = new Date(isoDate);
const hours = date.getUTCHours().toString().padStart(2, "0");
const minutes = date.getUTCMinutes().toString().padStart(2, "0");
return `${hours}:${minutes}`;
}
@@ -1,16 +1,18 @@
import type { ScheduleLabelsType } from "@calcom/features/schedules/components/Schedule";
import type { ScheduleWithAvailabilitiesForWeb, UpdateScheduleOutputType } from "@calcom/platform-libraries";
import type { ApiErrorResponse, ApiResponse, ApiSuccessResponse } from "@calcom/platform-types";
import type { ApiErrorResponse, ApiResponse, ScheduleOutput } from "@calcom/platform-types";
import useClientSchedule from "../../hooks/useClientSchedule";
import useDeleteSchedule from "../../hooks/useDeleteSchedule";
import useDeleteSchedule from "../../hooks/schedules/useDeleteSchedule";
import { useSchedule } from "../../hooks/schedules/useSchedule";
import { useSchedules } from "../../hooks/schedules/useSchedules";
import useUpdateSchedule from "../../hooks/schedules/useUpdateSchedule";
import { useMe } from "../../hooks/useMe";
import useUpdateSchedule from "../../hooks/useUpdateSchedule";
import { AtomsWrapper } from "../../src/components/atoms-wrapper";
import { useToast } from "../../src/components/ui/use-toast";
import type { Schedule } from "../AvailabilitySettings";
import type { Availability } from "../AvailabilitySettings";
import type { CustomClassNames } from "../AvailabilitySettings";
import { AvailabilitySettings } from "../AvailabilitySettings";
import { transformApiScheduleForAtom } from "../atom-api-transformers/transformApiScheduleForAtom";
import { transformAtomScheduleForApi } from "../atom-api-transformers/transformAtomScheduleForApi";
import type { AvailabilityFormValues } from "../types";
type PlatformAvailabilitySettingsWrapperProps = {
@@ -19,7 +21,7 @@ type PlatformAvailabilitySettingsWrapperProps = {
tooltips: Partial<ScheduleLabelsType>;
};
customClassNames?: Partial<CustomClassNames>;
onUpdateSuccess?: (res: ApiResponse<UpdateScheduleOutputType>) => void;
onUpdateSuccess?: (res: ApiResponse<ScheduleOutput>) => void;
onUpdateError?: (err: ApiErrorResponse) => void;
onDeleteSuccess?: (res: ApiResponse) => void;
onDeleteError?: (err: ApiErrorResponse) => void;
@@ -35,10 +37,10 @@ export const PlatformAvailabilitySettingsWrapper = ({
onUpdateSuccess,
disableEditableHeading = false,
}: PlatformAvailabilitySettingsWrapperProps) => {
const { isLoading, data: schedule } = useClientSchedule(id);
const mySchedule = schedule as ApiSuccessResponse<ScheduleWithAvailabilitiesForWeb>;
const { isLoading, data: schedule } = useSchedule(id);
const { data: schedules } = useSchedules();
const { data: me } = useMe();
const userSchedule = mySchedule?.data;
const atomSchedule = transformApiScheduleForAtom(me?.data, schedule, schedules?.length || 0);
const { timeFormat } = me?.data || { timeFormat: null };
const { toast } = useToast();
@@ -77,48 +79,43 @@ export const PlatformAvailabilitySettingsWrapper = ({
};
const handleUpdate = async (id: number, body: AvailabilityFormValues) => {
const transformedDateOverrides =
body.dateOverrides.flatMap(
(dateOverridesRanges) =>
dateOverridesRanges?.ranges?.map((range) => ({ start: range.start, end: range.end })) ?? []
) ?? [];
await updateSchedule({ ...body, scheduleId: id, dateOverrides: transformedDateOverrides });
const updateBody = transformAtomScheduleForApi(body);
updateSchedule({ id, ...updateBody });
};
if (isLoading) return <div className="px-10 py-4 text-xl">Loading...</div>;
if (!userSchedule) return <div className="px-10 py-4 text-xl">No user schedule present</div>;
if (!atomSchedule) return <div className="px-10 py-4 text-xl">No user schedule present</div>;
return (
<AtomsWrapper>
<AvailabilitySettings
disableEditableHeading={disableEditableHeading}
handleDelete={() => {
userSchedule.id && handleDelete(userSchedule.id);
atomSchedule.id && handleDelete(atomSchedule.id);
}}
handleSubmit={async (data) => {
userSchedule.id && handleUpdate(userSchedule.id, data);
atomSchedule.id && handleUpdate(atomSchedule.id, data);
}}
weekStart="Sunday"
timeFormat={timeFormat}
isLoading={isLoading}
schedule={{
name: userSchedule.name,
id: userSchedule.id,
isLastSchedule: userSchedule.isLastSchedule,
isDefault: userSchedule.isDefault,
workingHours: userSchedule.workingHours,
dateOverrides: userSchedule.dateOverrides,
timeZone: userSchedule.timeZone,
availability: userSchedule.availability,
name: atomSchedule.name,
id: atomSchedule.id,
isLastSchedule: atomSchedule.isLastSchedule,
isDefault: atomSchedule.isDefault,
workingHours: atomSchedule.workingHours,
dateOverrides: atomSchedule.dateOverrides,
timeZone: atomSchedule.timeZone,
availability: atomSchedule.availability,
schedule:
userSchedule.schedule.reduce(
(acc: Schedule[], avail: Schedule) => [
atomSchedule.schedule.reduce(
(acc: Availability[], avail: Availability) => [
...acc,
{ ...avail, startTime: new Date(avail.startTime), endTime: new Date(avail.endTime) },
{ days: avail.days, startTime: new Date(avail.startTime), endTime: new Date(avail.endTime) },
],
[] as Schedule[]
[]
) || [],
}}
isDeleting={isDeletionInProgress}
@@ -4,8 +4,8 @@ import { SUCCESS_STATUS } from "@calcom/platform-constants";
import { V2_ENDPOINTS } from "@calcom/platform-constants";
import type { ApiResponse, ApiErrorResponse } from "@calcom/platform-types";
import http from "../lib/http";
import { QUERY_KEY } from "./useClientSchedule";
import http from "../../lib/http";
import { QUERY_KEY } from "./useSchedule";
interface IUseDeleteScheduleProps {
onSuccess?: (res: ApiResponse) => void;
@@ -0,0 +1,26 @@
import { useQuery } from "@tanstack/react-query";
import { V2_ENDPOINTS, SUCCESS_STATUS } from "@calcom/platform-constants";
import type { GetScheduleOutput } from "@calcom/platform-types";
import http from "../../lib/http";
export const QUERY_KEY = "user-schedule";
export const useSchedule = (id?: string) => {
const pathname = id ? `/${V2_ENDPOINTS.availability}/${id}` : `/${V2_ENDPOINTS.availability}/default`;
const { isLoading, error, data } = useQuery({
queryKey: [QUERY_KEY, id],
queryFn: () => {
return http.get<GetScheduleOutput>(pathname).then((res) => {
if (res.data.status === SUCCESS_STATUS) {
return res.data.data;
}
throw new Error(res.data.error?.message);
});
},
});
return { isLoading, error, data };
};
@@ -0,0 +1,26 @@
import { useQuery } from "@tanstack/react-query";
import { V2_ENDPOINTS, SUCCESS_STATUS } from "@calcom/platform-constants";
import type { GetSchedulesOutput } from "@calcom/platform-types";
import http from "../../lib/http";
export const QUERY_KEY = "user-schedules";
export const useSchedules = () => {
const pathname = `/${V2_ENDPOINTS.availability}`;
const { isLoading, error, data } = useQuery({
queryKey: [QUERY_KEY],
queryFn: () => {
return http.get<GetSchedulesOutput>(pathname).then((res) => {
if (res.data.status === SUCCESS_STATUS) {
return res.data.data;
}
throw new Error(res.data.error?.message);
});
},
});
return { isLoading, error, data };
};
@@ -2,14 +2,14 @@ import { useMutation, useQueryClient } from "@tanstack/react-query";
import { SUCCESS_STATUS } from "@calcom/platform-constants";
import { V2_ENDPOINTS } from "@calcom/platform-constants";
import type { UpdateScheduleOutputType } from "@calcom/platform-libraries";
import type { ApiResponse, UpdateScheduleInput, ApiErrorResponse } from "@calcom/platform-types";
import type { ScheduleOutput } from "@calcom/platform-types";
import http from "../lib/http";
import { QUERY_KEY as ScheduleQueryKey } from "./useClientSchedule";
import http from "../../lib/http";
import { QUERY_KEY as ScheduleQueryKey } from "./useSchedule";
interface IPUpdateOAuthClient {
onSuccess?: (res: ApiResponse<UpdateScheduleOutputType>) => void;
onSuccess?: (res: ApiResponse<ScheduleOutput>) => void;
onError?: (err: ApiErrorResponse) => void;
}
@@ -25,15 +25,11 @@ const useUpdateSchedule = (
) => {
const queryClient = useQueryClient();
const mutation = useMutation<
ApiResponse<UpdateScheduleOutputType>,
unknown,
UpdateScheduleInput & { scheduleId: number }
>({
const mutation = useMutation<ApiResponse<ScheduleOutput>, unknown, UpdateScheduleInput & { id: number }>({
mutationFn: (data) => {
const pathname = `/${V2_ENDPOINTS.availability}/${data.scheduleId}?for=atom`;
const pathname = `/${V2_ENDPOINTS.availability}/${data.id}?for=atom`;
return http.patch<ApiResponse<UpdateScheduleOutputType>>(pathname, data).then((res) => {
return http.patch<ApiResponse<ScheduleOutput>>(pathname, data).then((res) => {
return res.data;
});
},
@@ -1,31 +0,0 @@
import { useQuery } from "@tanstack/react-query";
import { V2_ENDPOINTS, SUCCESS_STATUS } from "@calcom/platform-constants";
import type { ScheduleWithAvailabilitiesForWeb } from "@calcom/platform-libraries";
import type { ApiResponse } from "@calcom/platform-types";
import http from "../lib/http";
export const QUERY_KEY = "user-schedule";
const useClientSchedule = (id?: string) => {
const pathname = id
? `/${V2_ENDPOINTS.availability}/${id}?for=atom`
: `/${V2_ENDPOINTS.availability}/default?for=atom`;
const { isLoading, error, data } = useQuery({
queryKey: [QUERY_KEY, id],
queryFn: () => {
return http.get<ApiResponse<ScheduleWithAvailabilitiesForWeb>>(pathname).then((res) => {
if (res.data.status === SUCCESS_STATUS) {
return res.data;
}
throw new Error(res.data.error.message);
});
},
});
return { isLoading, error, data };
};
export default useClientSchedule;
+9
View File
@@ -0,0 +1,9 @@
{
"moduleFileExtensions": ["js", "json", "ts"],
"rootDir": ".",
"testEnvironment": "node",
"testRegex": ".*\\.spec\\.ts$",
"transform": {
"^.+\\.ts$": "ts-jest"
}
}
+6 -2
View File
@@ -8,7 +8,8 @@
"scripts": {
"dev": "yarn vite build --watch & npx tailwindcss -i ./globals.css -o ./globals.min.css --postcss --minify --watch",
"build": "yarn vite build && npx tailwindcss -i ./globals.css -o ./globals.min.css --postcss --minify && mkdir ./dist/packages/prisma-client && cp -rf ../../../node_modules/.prisma/client/*.d.ts ./dist/packages/prisma-client",
"publish": "rm -rf dist && yarn build && npm publish --access public"
"publish": "rm -rf dist && yarn build && npm publish --access public",
"test": "jest"
},
"devDependencies": {
"@rollup/plugin-node-resolve": "^15.0.1",
@@ -52,12 +53,15 @@
"@radix-ui/react-slot": "^1.0.2",
"@radix-ui/react-toast": "^1.1.5",
"@tanstack/react-query": "^5.17.15",
"@types/jest": "^29.5.12",
"class-variance-authority": "^0.4.0",
"clsx": "^2.0.0",
"jest": "^29.7.0",
"lucide-react": "^0.364.0",
"react-use": "^17.4.2",
"tailwind-merge": "^1.13.2",
"tailwindcss": "^3.3.3",
"tailwindcss-animate": "^1.0.6"
"tailwindcss-animate": "^1.0.6",
"ts-jest": "^29.1.2"
}
}
+6 -8
View File
@@ -48,14 +48,12 @@ export type { ConnectedDestinationCalendars } from "@calcom/lib/getConnectedDest
export { getBusyCalendarTimes } from "@calcom/core/CalendarManager";
export {
transformWorkingHoursForClient,
transformAvailabilityForClient,
transformDateOverridesForClient,
} from "@calcom/lib/schedules/client/transformers";
export type {
ScheduleWithAvailabilities,
ScheduleWithAvailabilitiesForWeb,
} from "@calcom/lib/schedules/client/transformers";
transformWorkingHoursForAtom,
transformAvailabilityForAtom,
transformDateOverridesForAtom,
transformApiScheduleAvailability,
transformApiScheduleOverrides,
} from "@calcom/lib/schedules/transformers";
export type {
BookingCreateBody,
BookingResponse,
-115
View File
@@ -1,115 +0,0 @@
import { ApiProperty as DocsProperty, ApiProperty } from "@nestjs/swagger";
import { Type } from "class-transformer";
import { IsString, IsBoolean, IsOptional, ValidateNested, IsArray, IsDate } from "class-validator";
import { DateTime } from "luxon";
import { z } from "zod";
const scheduleSchema = z.object({
id: z.number().int(),
userId: z.number().int(),
name: z.string(),
timeZone: z.string().nullish(),
});
const availabilitySchema = z.object({
id: z.number().int(),
days: z.number().int().array(),
startTime: z.date(),
endTime: z.date(),
});
export const schemaScheduleResponse = z
.object({})
.merge(scheduleSchema)
.merge(
z.object({
availability: z
.array(availabilitySchema)
.transform((availabilities) =>
availabilities.map((availability) => ({
...availability,
startTime: DateTime.fromJSDate(availability.startTime).toUTC().toFormat("HH:mm:ss"),
endTime: DateTime.fromJSDate(availability.endTime).toUTC().toFormat("HH:mm:ss"),
}))
)
.optional(),
})
);
export type ScheduleResponse = z.infer<typeof schemaScheduleResponse>;
class ScheduleItem {
@IsString()
start!: Date;
@IsString()
end!: Date;
}
class DateOverride {
@IsDate()
@Type(() => Date)
start!: Date;
@IsDate()
@Type(() => Date)
end!: Date;
}
export class UpdateScheduleInput {
@IsString()
@IsOptional()
@DocsProperty()
timeZone?: string;
@IsString()
@IsOptional()
@DocsProperty()
name?: string;
@IsBoolean()
@IsOptional()
@DocsProperty()
isDefault?: boolean;
@IsOptional()
@ValidateNested({ each: true })
@Type(() => ScheduleItem)
@DocsProperty()
@IsArray()
@ApiProperty({
type: [[ScheduleItem]],
example: [
[],
[{ start: "2022-01-01T00:00:00.000Z", end: "2022-01-02T00:00:00.000Z" }],
[],
[],
[],
[],
[],
],
isArray: true,
})
schedule?: ScheduleItem[][];
@IsOptional()
@ValidateNested({ each: true })
@Type(() => DateOverride)
@IsArray()
@DocsProperty()
@ApiProperty({
type: [DateOverride],
example: [
[],
[{ start: "2022-01-01T00:00:00.000Z", end: "2022-01-02T00:00:00.000Z" }],
[],
[],
[],
[],
[],
],
isArray: true,
required: false,
})
dateOverrides?: DateOverride[];
}
@@ -0,0 +1,13 @@
export const WEEK_DAYS = [
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday",
"Sunday",
] as const;
export type WeekDay = (typeof WEEK_DAYS)[number];
export const TIME_FORMAT_HH_MM = /^([01]\d|2[0-3]):([0-5]\d)$/;
@@ -0,0 +1,3 @@
export * from "./inputs";
export * from "./outputs";
export * from "./constants";
@@ -0,0 +1,97 @@
import { ApiProperty } from "@nestjs/swagger";
import { Type } from "class-transformer";
import {
IsBoolean,
IsOptional,
IsString,
ValidateNested,
IsArray,
Matches,
IsISO8601,
IsTimeZone,
IsIn,
} from "class-validator";
import type { WeekDay } from "../constants";
import { TIME_FORMAT_HH_MM, WEEK_DAYS } from "../constants";
export class ScheduleAvailabilityInput {
@IsArray()
@IsIn(WEEK_DAYS, { each: true })
@ApiProperty({ example: ["Monday", "Tuesday"] })
days!: WeekDay[];
@IsString()
@Matches(TIME_FORMAT_HH_MM, { message: "startTime must be a valid time format HH:MM" })
@ApiProperty({ example: "09:00" })
startTime!: string;
@IsString()
@Matches(TIME_FORMAT_HH_MM, { message: "endTime must be a valid time format HH:MM" })
@ApiProperty({ example: "10:00" })
endTime!: string;
}
export class ScheduleOverrideInput {
@IsISO8601({ strict: true })
@ApiProperty({ example: "2024-05-20" })
date!: string;
@IsString()
@Matches(TIME_FORMAT_HH_MM, { message: "startTime must be a valid time format HH:MM" })
@ApiProperty({ example: "12:00" })
startTime!: string;
@IsString()
@Matches(TIME_FORMAT_HH_MM, { message: "endTime must be a valid time format HH:MM" })
@ApiProperty({ example: "13:00" })
endTime!: string;
}
export class CreateScheduleInput {
@IsString()
@ApiProperty({ example: "One-on-one coaching" })
name!: string;
@IsTimeZone()
@ApiProperty({ example: "Europe/Rome" })
timeZone!: string;
@IsArray()
@IsOptional()
@ValidateNested({ each: true })
@Type(() => ScheduleAvailabilityInput)
@ApiProperty({
type: [ScheduleAvailabilityInput],
example: [
{
days: ["Monday", "Tuesday"],
startTime: "09:00",
endTime: "10:00",
},
],
required: false,
})
availability?: ScheduleAvailabilityInput[];
@IsBoolean()
@ApiProperty({ example: true })
isDefault!: boolean;
@IsArray()
@IsOptional()
@ValidateNested({ each: true })
@Type(() => ScheduleOverrideInput)
@ApiProperty({
type: [ScheduleOverrideInput],
example: [
{
date: "2024-05-20",
startTime: "12:00",
endTime: "14:00",
},
],
required: false,
})
overrides?: ScheduleOverrideInput[];
}
@@ -0,0 +1,2 @@
export * from "./create-schedule.input";
export * from "./update-schedule.input";
@@ -0,0 +1,56 @@
import { ApiProperty } from "@nestjs/swagger";
import { Type } from "class-transformer";
import { IsString, IsBoolean, IsOptional, ValidateNested, IsArray, IsTimeZone } from "class-validator";
import { ScheduleAvailabilityInput, ScheduleOverrideInput } from "./create-schedule.input";
export class UpdateScheduleInput {
@IsString()
@IsOptional()
@ApiProperty({ example: "One-on-one coaching", required: false })
name?: string;
@IsTimeZone()
@IsOptional()
@ApiProperty({ example: "Europe/Rome", required: false })
timeZone?: string;
@IsArray()
@IsOptional()
@ValidateNested({ each: true })
@Type(() => ScheduleAvailabilityInput)
@ApiProperty({
type: [ScheduleAvailabilityInput],
example: [
{
days: ["Monday", "Tuesday"],
startTime: "09:00",
endTime: "10:00",
},
],
required: false,
})
availability?: ScheduleAvailabilityInput[];
@IsBoolean()
@IsOptional()
@ApiProperty({ example: true, required: false })
isDefault?: boolean;
@IsArray()
@IsOptional()
@ValidateNested({ each: true })
@Type(() => ScheduleOverrideInput)
@ApiProperty({
type: [ScheduleOverrideInput],
example: [
{
date: "2024-05-20",
startTime: "12:00",
endTime: "14:00",
},
],
required: false,
})
overrides?: ScheduleOverrideInput[];
}
@@ -0,0 +1,21 @@
import { ApiProperty } from "@nestjs/swagger";
import { Type } from "class-transformer";
import { IsEnum, IsNotEmptyObject, ValidateNested } from "class-validator";
import { SUCCESS_STATUS, ERROR_STATUS } from "@calcom/platform-constants";
import { ScheduleOutput } from "./schedule.output";
export class CreateScheduleOutput {
@ApiProperty({ example: SUCCESS_STATUS, enum: [SUCCESS_STATUS, ERROR_STATUS] })
@IsEnum([SUCCESS_STATUS, ERROR_STATUS])
status!: typeof SUCCESS_STATUS | typeof ERROR_STATUS;
@ApiProperty({
type: ScheduleOutput,
})
@IsNotEmptyObject()
@ValidateNested()
@Type(() => ScheduleOutput)
data!: ScheduleOutput;
}
@@ -0,0 +1,10 @@
import { ApiProperty } from "@nestjs/swagger";
import { IsEnum } from "class-validator";
import { SUCCESS_STATUS, ERROR_STATUS } from "@calcom/platform-constants";
export class DeleteScheduleOutput {
@ApiProperty({ example: SUCCESS_STATUS, enum: [SUCCESS_STATUS, ERROR_STATUS] })
@IsEnum([SUCCESS_STATUS, ERROR_STATUS])
status!: typeof SUCCESS_STATUS | typeof ERROR_STATUS;
}
@@ -0,0 +1,21 @@
import { ApiProperty } from "@nestjs/swagger";
import { Type } from "class-transformer";
import { IsEnum, IsNotEmptyObject, ValidateNested } from "class-validator";
import { SUCCESS_STATUS, ERROR_STATUS } from "@calcom/platform-constants";
import { ScheduleOutput } from "./schedule.output";
export class GetDefaultScheduleOutput {
@ApiProperty({ example: SUCCESS_STATUS, enum: [SUCCESS_STATUS, ERROR_STATUS] })
@IsEnum([SUCCESS_STATUS, ERROR_STATUS])
status!: typeof SUCCESS_STATUS | typeof ERROR_STATUS;
@ApiProperty({
type: ScheduleOutput,
})
@IsNotEmptyObject()
@ValidateNested()
@Type(() => ScheduleOutput)
data!: ScheduleOutput | null;
}
@@ -0,0 +1,23 @@
import { ApiProperty } from "@nestjs/swagger";
import { Type } from "class-transformer";
import { IsEnum, IsNotEmptyObject, ValidateNested } from "class-validator";
import { SUCCESS_STATUS, ERROR_STATUS } from "@calcom/platform-constants";
import { ScheduleOutput } from "./schedule.output";
export class GetScheduleOutput {
@ApiProperty({ example: SUCCESS_STATUS, enum: [SUCCESS_STATUS, ERROR_STATUS] })
@IsEnum([SUCCESS_STATUS, ERROR_STATUS])
status!: typeof SUCCESS_STATUS | typeof ERROR_STATUS;
@ApiProperty({
type: ScheduleOutput,
})
@IsNotEmptyObject()
@ValidateNested()
@Type(() => ScheduleOutput)
data!: ScheduleOutput | null;
error?: Error;
}
@@ -0,0 +1,22 @@
import { ApiProperty } from "@nestjs/swagger";
import { Type } from "class-transformer";
import { IsArray, IsEnum, IsNotEmptyObject, ValidateNested } from "class-validator";
import { SUCCESS_STATUS, ERROR_STATUS } from "@calcom/platform-constants";
import { ScheduleOutput } from "./schedule.output";
export class GetSchedulesOutput {
@ApiProperty({ example: SUCCESS_STATUS, enum: [SUCCESS_STATUS, ERROR_STATUS] })
@IsEnum([SUCCESS_STATUS, ERROR_STATUS])
status!: typeof SUCCESS_STATUS | typeof ERROR_STATUS;
@ApiProperty({ type: [ScheduleOutput] })
@IsNotEmptyObject()
@ValidateNested({ each: true })
@Type(() => ScheduleOutput)
@IsArray()
data!: ScheduleOutput[];
error?: Error;
}
@@ -0,0 +1,7 @@
export * from "./schedule.output";
export * from "./get-schedule.output";
export * from "./get-schedules.output";
export * from "./get-default-schedule.output";
export * from "./create-schedule.output";
export * from "./update-schedule.output";
export * from "./delete-schedule.output";
@@ -0,0 +1,66 @@
import { ApiProperty } from "@nestjs/swagger";
import { Type } from "class-transformer";
import {
IsBoolean,
IsOptional,
IsString,
ValidateNested,
IsArray,
IsTimeZone,
IsNumber,
} from "class-validator";
import { ScheduleAvailabilityInput, ScheduleOverrideInput } from "../inputs/create-schedule.input";
export class ScheduleOutput {
@IsNumber()
@ApiProperty({ example: 254 })
id!: number;
@IsNumber()
@ApiProperty({ example: 478 })
ownerId!: number;
@IsString()
@ApiProperty({ example: "One-on-one coaching" })
name!: string;
@IsTimeZone()
@ApiProperty({ example: "Europe/Rome" })
timeZone!: string;
@IsArray()
@ValidateNested({ each: true })
@Type(() => ScheduleAvailabilityInput)
@ApiProperty({
type: [ScheduleAvailabilityInput],
example: [
{
days: ["Monday", "Tuesday"],
startTime: "09:00",
endTime: "10:00",
},
],
})
availability!: ScheduleAvailabilityInput[];
@IsBoolean()
@ApiProperty({ example: true })
isDefault!: boolean;
@IsArray()
@IsOptional()
@ValidateNested({ each: true })
@Type(() => ScheduleOverrideInput)
@ApiProperty({
type: [ScheduleOverrideInput],
example: [
{
date: "2024-05-20",
startTime: "12:00",
endTime: "13:00",
},
],
})
overrides!: ScheduleOverrideInput[];
}
@@ -0,0 +1,23 @@
import { ApiProperty } from "@nestjs/swagger";
import { Type } from "class-transformer";
import { IsEnum, IsNotEmptyObject, ValidateNested } from "class-validator";
import { SUCCESS_STATUS, ERROR_STATUS } from "@calcom/platform-constants";
import { ScheduleOutput } from "./schedule.output";
export class UpdateScheduleOutput {
@ApiProperty({ example: SUCCESS_STATUS, enum: [SUCCESS_STATUS, ERROR_STATUS] })
@IsEnum([SUCCESS_STATUS, ERROR_STATUS])
status!: typeof SUCCESS_STATUS | typeof ERROR_STATUS;
@ApiProperty({
type: ScheduleOutput,
})
@IsNotEmptyObject()
@ValidateNested()
@Type(() => ScheduleOutput)
data!: ScheduleOutput;
error?: Error;
}
@@ -1,8 +1,7 @@
import type { ScheduleWithAvailabilitiesForWeb } from "@calcom/lib";
import {
transformAvailabilityForClient,
transformDateOverridesForClient,
transformWorkingHoursForClient,
transformAvailabilityForAtom,
transformDateOverridesForAtom,
transformWorkingHoursForAtom,
} from "@calcom/lib";
import { hasReadPermissionsForUserId } from "@calcom/lib/hasEditPermissionForUser";
import { prisma } from "@calcom/prisma";
@@ -20,7 +19,7 @@ type GetOptions = {
input: TGetInputSchema;
};
export const getHandler = async ({ ctx, input }: GetOptions): Promise<ScheduleWithAvailabilitiesForWeb> => {
export const getHandler = async ({ ctx, input }: GetOptions) => {
const { user } = ctx;
const schedule = await prisma.schedule.findUnique({
@@ -66,11 +65,11 @@ export const getHandler = async ({ ctx, input }: GetOptions): Promise<ScheduleWi
id: schedule.id,
name: schedule.name,
isManaged: schedule.userId !== user.id,
workingHours: transformWorkingHoursForClient(schedule),
workingHours: transformWorkingHoursForAtom(schedule),
schedule: schedule.availability,
availability: transformAvailabilityForClient(schedule),
availability: transformAvailabilityForAtom(schedule),
timeZone,
dateOverrides: transformDateOverridesForClient(schedule, timeZone),
dateOverrides: transformDateOverridesForAtom(schedule, timeZone),
isDefault: !input.scheduleId || user.defaultScheduleId === schedule.id,
isLastSchedule: schedulesCount <= 1,
readOnly: schedule.userId !== user.id && !input.isManagedEventType,
@@ -1,4 +1,4 @@
import { transformScheduleToAvailabilityForClient } from "@calcom/lib";
import { transformScheduleToAvailabilityForAtom } from "@calcom/lib";
import { getAvailabilityFromSchedule } from "@calcom/lib/availability";
import { hasEditPermissionForUserID } from "@calcom/lib/hasEditPermissionForUser";
import { prisma } from "@calcom/prisma";
@@ -118,7 +118,7 @@ export const updateHandler = async ({ input, ctx }: UpdateOptions) => {
},
});
const userAvailability = transformScheduleToAvailabilityForClient(schedule);
const userAvailability = transformScheduleToAvailabilityForAtom(schedule);
return {
schedule,