feat: OOO booking-forwarding (#12653)

* feat-profile-forwarding

* fix for promises of handling

* fix badge success color

* clean up

* fix suggested changes

* Changed design on booking-forward pages and moar test

* taking care of suggested changes, trpc errors and code cleaning

* improve text

* fix conflicting data-testid

* fix unique data-testid

* fix error css-global, email button styles, error conditional

* rename files to match functionality, remove away ui

* Add translations and migration

* remove log

* small fixes + improvements

* fix styles to match new design

* merge fixes

* Fix styles dark mode

* Solving merge conflicts from earlier

* Fix/change test to match new elements

* use trash icon button insted of dots (design issues)

* only send email if toUserId is set

* Fix date picker dark mode

* merge with remote

* removed status field from table and email its now for notify

* small text improvement in email

* check for team plan not paid plan

* fixes and clean up due to removing status

* fix old send request name to new behaviour

* more naming improvements and text

* remove status from handle-type

* code clean up

* fix type error

---------

Co-authored-by: Peer Richelsen <[email protected]>
Co-authored-by: Carina Wollendorfer <[email protected]>
Co-authored-by: CarinaWolli <[email protected]>
This commit is contained in:
authored and GitHub committed 2024-01-10 17:04:02 +00:00
1 parent dfaa6d28e4
commit 96af17d8d7
24 files changed
+1249 -62

No files matched your search

@@ -12,6 +12,7 @@ import { ZGetCalVideoRecordingsInputSchema } from "./getCalVideoRecordings.schem
import { ZGetDownloadLinkOfCalVideoRecordingsInputSchema } from "./getDownloadLinkOfCalVideoRecordings.schema";
import { ZIntegrationsInputSchema } from "./integrations.schema";
import { ZLocationOptionsInputSchema } from "./locationOptions.schema";
import { ZOutOfOfficeInputSchema, ZOutOfOfficeDelete } from "./outOfOffice.schema";
import { ZRoutingFormOrderInputSchema } from "./routingFormOrder.schema";
import { ZSetDestinationCalendarInputSchema } from "./setDestinationCalendar.schema";
import { ZSubmitFeedbackInputSchema } from "./submitFeedback.schema";
@@ -47,6 +48,9 @@ type AppsRouterHandlerCache = {
teamsAndUserProfilesQuery?: typeof import("./teamsAndUserProfilesQuery.handler").teamsAndUserProfilesQuery;
getUserTopBanners?: typeof import("./getUserTopBanners.handler").getUserTopBannersHandler;
connectAndJoin?: typeof import("./connectAndJoin.handler").Handler;
outOfOfficeCreate?: typeof import("./outOfOffice.handler").outOfOfficeCreate;
outOfOfficeEntriesList?: typeof import("./outOfOffice.handler").outOfOfficeEntriesList;
outOfOfficeEntryDelete?: typeof import("./outOfOffice.handler").outOfOfficeEntryDelete;
};
const UNSTABLE_HANDLER_CACHE: AppsRouterHandlerCache = {};
@@ -434,7 +438,6 @@ export const loggedInViewerRouter = router({
return UNSTABLE_HANDLER_CACHE.teamsAndUserProfilesQuery({ ctx });
}),
connectAndJoin: authedProcedure.input(ZConnectAndJoinInputSchema).mutation(async ({ ctx, input }) => {
if (!UNSTABLE_HANDLER_CACHE.connectAndJoin) {
UNSTABLE_HANDLER_CACHE.connectAndJoin = (await import("./connectAndJoin.handler")).Handler;
@@ -447,4 +450,44 @@ export const loggedInViewerRouter = router({
return UNSTABLE_HANDLER_CACHE.connectAndJoin({ ctx, input });
}),
outOfOfficeCreate: authedProcedure.input(ZOutOfOfficeInputSchema).mutation(async ({ ctx, input }) => {
if (!UNSTABLE_HANDLER_CACHE.outOfOfficeCreate) {
UNSTABLE_HANDLER_CACHE.outOfOfficeCreate = (await import("./outOfOffice.handler")).outOfOfficeCreate;
}
// Unreachable code but required for type safety
if (!UNSTABLE_HANDLER_CACHE.outOfOfficeCreate) {
throw new Error("Failed to load handler");
}
return UNSTABLE_HANDLER_CACHE.outOfOfficeCreate({ ctx, input });
}),
outOfOfficeEntriesList: authedProcedure.query(async ({ ctx }) => {
if (!UNSTABLE_HANDLER_CACHE.outOfOfficeEntriesList) {
UNSTABLE_HANDLER_CACHE.outOfOfficeEntriesList = (
await import("./outOfOffice.handler")
).outOfOfficeEntriesList;
}
// Unreachable code but required for type safety
if (!UNSTABLE_HANDLER_CACHE.outOfOfficeEntriesList) {
throw new Error("Failed to load handler");
}
return UNSTABLE_HANDLER_CACHE.outOfOfficeEntriesList({ ctx });
}),
outOfOfficeEntryDelete: authedProcedure.input(ZOutOfOfficeDelete).mutation(async ({ ctx, input }) => {
if (!UNSTABLE_HANDLER_CACHE.outOfOfficeEntryDelete) {
UNSTABLE_HANDLER_CACHE.outOfOfficeEntryDelete = (
await import("./outOfOffice.handler")
).outOfOfficeEntryDelete;
}
// Unreachable code but required for type safety
if (!UNSTABLE_HANDLER_CACHE.outOfOfficeEntryDelete) {
throw new Error("Failed to load handler");
}
return UNSTABLE_HANDLER_CACHE.outOfOfficeEntryDelete({ ctx, input });
}),
});
@@ -0,0 +1,239 @@
import { v4 as uuidv4 } from "uuid";
import dayjs from "@calcom/dayjs";
import { sendBookingRedirectNotification } from "@calcom/emails";
import { getTranslation } from "@calcom/lib/server";
import prisma from "@calcom/prisma";
import type { TrpcSessionUser } from "@calcom/trpc/server/trpc";
import { TRPCError } from "@trpc/server";
import type { TOutOfOfficeDelete, TOutOfOfficeInputSchema } from "./outOfOffice.schema";
type TBookingRedirect = {
ctx: {
user: NonNullable<TrpcSessionUser>;
};
input: TOutOfOfficeInputSchema;
};
export const outOfOfficeCreate = async ({ ctx, input }: TBookingRedirect) => {
if (!input.startDate || !input.endDate) {
throw new TRPCError({ code: "BAD_REQUEST", message: "start_date_and_end_date_required" });
}
const inputStartTime = dayjs(input.startDate).startOf("day");
const inputEndTime = dayjs(input.endDate).endOf("day");
const offset = dayjs(inputStartTime).utcOffset();
// If start date is after end date throw error
if (inputStartTime.isAfter(inputEndTime)) {
throw new TRPCError({ code: "BAD_REQUEST", message: "start_date_must_be_before_end_date" });
}
// If start date is before to today throw error
// Since this validation is done using server tz, we need to account for the offset
if (
inputStartTime.isBefore(
dayjs()
.startOf("day")
.subtract(Math.abs(offset) * 60, "minute")
)
) {
throw new TRPCError({ code: "BAD_REQUEST", message: "start_date_must_be_in_the_future" });
}
let toUserId;
if (input.toTeamUserId) {
const user = await prisma.user.findUnique({
where: {
id: input.toTeamUserId,
},
select: {
id: true,
},
});
if (!user) {
throw new TRPCError({ code: "NOT_FOUND", message: "user_not_found" });
}
toUserId = user?.id;
}
// Validate if OOO entry for these dates already exists
const outOfOfficeEntry = await prisma.outOfOfficeEntry.findFirst({
where: {
AND: [
{ userId: ctx.user.id },
{
OR: [
{
start: {
lt: inputEndTime.toISOString(), //existing start is less than or equal to input end time
},
end: {
gt: inputStartTime.toISOString(), //existing end is greater than or equal to input start time
},
},
{
//existing start is within the new input range
start: {
gt: inputStartTime.toISOString(),
lt: inputEndTime.toISOString(),
},
},
{
//existing end is within the new input range
end: {
gt: inputStartTime.toISOString(),
lt: inputEndTime.toISOString(),
},
},
],
},
],
},
});
// don't allow overlapping entries
if (outOfOfficeEntry) {
throw new TRPCError({ code: "CONFLICT", message: "out_of_office_entry_already_exists" });
}
// Prevent infinite redirects but consider time ranges
const existingOutOfOfficeEntry = await prisma.outOfOfficeEntry.findFirst({
select: {
userId: true,
toUserId: true,
},
where: {
userId: toUserId,
toUserId: ctx.user.id,
// Check for time overlap or collision
OR: [
// Outside of range
{
AND: [
{ start: { lte: inputEndTime.toISOString() } },
{ end: { gte: inputStartTime.toISOString() } },
],
},
// Inside of range
{
AND: [
{ start: { gte: inputStartTime.toISOString() } },
{ end: { lte: inputEndTime.toISOString() } },
],
},
],
},
});
// don't allow infinite redirects
if (existingOutOfOfficeEntry) {
throw new TRPCError({ code: "BAD_REQUEST", message: "booking_redirect_infinite_not_allowed" });
}
const createdRedirect = await prisma.outOfOfficeEntry.create({
data: {
uuid: uuidv4(),
start: dayjs(input.startDate).startOf("day").toISOString(),
end: dayjs(input.endDate).endOf("day").toISOString(),
userId: ctx.user.id,
toUserId: toUserId,
createdAt: new Date(),
updatedAt: new Date(),
},
});
if (toUserId) {
// await send email to notify user
const userToNotify = await prisma.user.findFirst({
where: {
id: toUserId,
},
select: {
email: true,
},
});
const t = await getTranslation(ctx.user.locale ?? "en", "common");
const formattedStartDate = new Intl.DateTimeFormat("en-US").format(createdRedirect.start);
const formattedEndDate = new Intl.DateTimeFormat("en-US").format(createdRedirect.end);
if (userToNotify?.email) {
await sendBookingRedirectNotification({
language: t,
fromEmail: ctx.user.email,
toEmail: userToNotify.email,
toName: ctx.user.username || "",
dates: `${formattedStartDate} - ${formattedEndDate}`,
});
}
}
return {};
};
type TBookingRedirectDelete = {
ctx: {
user: NonNullable<TrpcSessionUser>;
};
input: TOutOfOfficeDelete;
};
export const outOfOfficeEntryDelete = async ({ ctx, input }: TBookingRedirectDelete) => {
if (!input.outOfOfficeUid) {
throw new TRPCError({ code: "BAD_REQUEST", message: "out_of_office_id_required" });
}
// Validate outOfOfficeEntry belongs to the user deleting it
const outOfOfficeEntry = await prisma.outOfOfficeEntry.findFirst({
select: {
uuid: true,
userId: true,
},
where: {
uuid: input.outOfOfficeUid,
userId: ctx.user.id,
},
});
if (!outOfOfficeEntry) {
throw new TRPCError({ code: "NOT_FOUND", message: "booking_redirect_not_found" });
}
await prisma.outOfOfficeEntry.delete({
where: {
uuid: input.outOfOfficeUid,
},
});
return {};
};
export const outOfOfficeEntriesList = async ({ ctx }: { ctx: { user: NonNullable<TrpcSessionUser> } }) => {
const outOfOfficeEntries = await prisma.outOfOfficeEntry.findMany({
where: {
userId: ctx.user.id,
end: {
gte: new Date().toISOString(),
},
},
orderBy: {
start: "desc",
},
select: {
id: true,
uuid: true,
start: true,
end: true,
toUserId: true,
toUser: {
select: {
username: true,
},
},
},
});
return outOfOfficeEntries;
};
@@ -0,0 +1,15 @@
import { z } from "zod";
export const ZOutOfOfficeInputSchema = z.object({
startDate: z.string(),
endDate: z.string(),
toTeamUserId: z.number().nullable(),
});
export type TOutOfOfficeInputSchema = z.infer<typeof ZOutOfOfficeInputSchema>;
export const ZOutOfOfficeDelete = z.object({
outOfOfficeUid: z.string(),
});
export type TOutOfOfficeDelete = z.infer<typeof ZOutOfOfficeDelete>;