Change location of booking (#2658)

* add functionality to change location in booking and send out mail

* add i18n

* change location with dropdown like in event-types

* small fixes and code clean up

* clean code

* improve format of current Location string

* clean code

* clear selection when dialog closed

* added mutation and changed props (first working verison)

* clean code

* clean code

* clean code

* clean code

* fix typo

* change maxHeight of select

* use useWatch for selectedLocation

* pass default values with props

* set current location directly in useState

* clear selected values when updating location

* fix trpc query for credentialst

* change icons for editing booking

* improve naming of variables

* remove unnecessary orderBy

* use locationOptionsToString method

* fix current location naming for Cal Video

* add phone input

* save phone number as location of booking

* remove input field for phone number for event-types

* fix redirection issue

* show previous selected location in event-type

* remove attendee number from selection for booking

* make first letter of location lowercase

* remove input field for attendee phone number

* clear Errors when changing location type

* set location details to optional

* clean code

* fixing issue that dropdown doesn't close when dialog opens

* clean code

* make overflow visibile in dialog

* fix existing bug with address not showing in event-type settings

* fix issue with losing focus after validation

* close rejection dialog

* small spelling fixes

* fix issue with LocationChangeEmail

* fix failing E2E test

* fix failing E2E test

* fix E2E test

* bug fix for saving user phone, and other minor changes

* merge main

* improve text

* fix UI of booking list

* Delete admin

* remove selection after update and submit

* add translation for error message

* add default values for checkbox

* add "your phone number" to locations on booking page

* remove duplicate attributes from viewer.bookings

Co-authored-by: Omar López <[email protected]>

* check if user is authorized to make changes to booking

* remove location string

* clan code for displayLocaitonPublicly checkbox

* fetch locationOptions on server side

* remove trpc query for credentials

* fix phone number input

* fix labels of host and attendee phone number for booking page

* Migrates edit location to tRPC

* Link elemnt should only be used in `a` tags

* Adds missin router

* Migrates locationOptions to tRPC query

* Type fixes

Co-authored-by: CarinaWolli <[email protected]>
Co-authored-by: Alan <[email protected]>
Co-authored-by: Omar López <[email protected]>
Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
This commit is contained in:
authored and GitHub committed 2022-05-27 23:27:41 +00:00
1 parent b869e70a7f
commit 7b01bae829
19 files changed
+1165 -351

No files matched your search

+34 -6
View File
@@ -4,7 +4,7 @@ import _ from "lodash";
import { JSONObject } from "superjson/dist/types";
import { z } from "zod";
import getApps from "@calcom/app-store/utils";
import getApps, { getLocationOptions } from "@calcom/app-store/utils";
import { getCalendarCredentials, getConnectedCalendars } from "@calcom/core/CalendarManager";
import { checkPremiumUsername } from "@calcom/ee/lib/core/checkPremiumUsername";
import { bookingMinimalSelect } from "@calcom/prisma";
@@ -13,19 +13,22 @@ import { RecurringEvent } from "@calcom/types/Calendar";
import { checkRegularUsername } from "@lib/core/checkRegularUsername";
import { sendFeedbackEmail } from "@lib/emails/email-manager";
import jackson from "@lib/jackson";
import prisma from "@lib/prisma";
import {
isSAMLLoginEnabled,
samlTenantID,
samlProductID,
isSAMLAdmin,
hostedCal,
tenantPrefix,
isSAMLAdmin,
isSAMLLoginEnabled,
samlProductID,
samlTenantID,
samlTenantProduct,
tenantPrefix,
} from "@lib/saml";
import slugify from "@lib/slugify";
import { getTranslation } from "@server/lib/i18n";
import { apiKeysRouter } from "@server/routers/viewer/apiKeys";
import { availabilityRouter } from "@server/routers/viewer/availability";
import { bookingsRouter } from "@server/routers/viewer/bookings";
import { eventTypesRouter } from "@server/routers/viewer/eventTypes";
import { TRPCError } from "@trpc/server";
@@ -921,11 +924,36 @@ const loggedInViewerRouter = createProtectedRouter()
if (process.env.SEND_FEEDBACK_EMAIL && comment) sendFeedbackEmail(feedback);
},
})
.query("locationOptions", {
async resolve({ ctx }) {
const credentials = await prisma.credential.findMany({
where: {
userId: ctx.user.id,
},
select: {
id: true,
type: true,
key: true,
userId: true,
appId: true,
},
});
const integrations = getApps(credentials);
const t = await getTranslation(ctx.user.locale ?? "en", "common");
const locationOptions = getLocationOptions(integrations, t);
return locationOptions;
},
});
export const viewerRouter = createRouter()
.merge(publicViewerRouter)
.merge(loggedInViewerRouter)
.merge("bookings.", bookingsRouter)
.merge("eventTypes.", eventTypesRouter)
.merge("availability.", availabilityRouter)
.merge("teams.", viewerTeamsRouter)
+154
View File
@@ -0,0 +1,154 @@
import { SchedulingType } from "@prisma/client";
import dayjs from "dayjs";
import { z } from "zod";
import EventManager from "@calcom/core/EventManager";
import logger from "@calcom/lib/logger";
import { getTranslation } from "@calcom/lib/server/i18n";
import type { AdditionInformation, CalendarEvent } from "@calcom/types/Calendar";
import { sendLocationChangeEmails } from "@lib/emails/email-manager";
import { createProtectedRouter } from "@server/createRouter";
import { TRPCError } from "@trpc/server";
// Common data for all endpoints under webhook
const commonBookingSchema = z.object({
bookingId: z.number(),
});
export const bookingsRouter = createProtectedRouter()
.middleware(async ({ ctx, rawInput, next }) => {
// Endpoints that just read the logged in user's data - like 'list' don't necessary have any input
if (!rawInput) return next({ ctx: { ...ctx, booking: null } });
const webhookIdAndEventTypeId = commonBookingSchema.safeParse(rawInput);
if (!webhookIdAndEventTypeId.success) throw new TRPCError({ code: "PARSE_ERROR" });
const { bookingId } = webhookIdAndEventTypeId.data;
const booking = await ctx.prisma.booking.findFirst({
where: {
OR: [
/* If user is organizer */
{ userId: ctx.user.id, id: bookingId },
/* Or part of a collective booking */
{
eventType: {
schedulingType: SchedulingType.COLLECTIVE,
users: {
some: {
id: ctx.user.id,
},
},
},
},
],
},
include: {
attendees: true,
eventType: true,
user: {
include: { destinationCalendar: true },
},
destinationCalendar: true,
},
});
return next({ ctx: { ...ctx, booking } });
})
.middleware(async ({ ctx, next }) => {
// So TS doesn't compain in the previous middleware.
// This means the user doesn't have access to this booking
if (!ctx.booking) throw new TRPCError({ code: "UNAUTHORIZED" });
// Booking here is non-nullable anymore
return next({ ctx: { ...ctx, booking: ctx.booking } });
})
.mutation("editLocation", {
input: commonBookingSchema.extend({
newLocation: z.string(),
}),
async resolve({ ctx, input }) {
const { bookingId, newLocation: location } = input;
const { booking } = ctx;
try {
await ctx.prisma.booking.update({
where: { id: bookingId },
data: { location },
});
const organizer = await ctx.prisma.user.findFirst({
where: {
id: booking.userId || 0,
},
select: {
name: true,
email: true,
timeZone: true,
locale: true,
},
rejectOnNotFound: true,
});
const tOrganizer = await getTranslation(organizer.locale ?? "en", "common");
const attendeesListPromises = booking.attendees.map(async (attendee) => {
return {
name: attendee.name,
email: attendee.email,
timeZone: attendee.timeZone,
language: {
translate: await getTranslation(attendee.locale ?? "en", "common"),
locale: attendee.locale ?? "en",
},
};
});
const attendeesList = await Promise.all(attendeesListPromises);
const evt: CalendarEvent = {
title: booking.title || "",
type: (booking.eventType?.title as string) || booking?.title || "",
description: booking.description || "",
startTime: booking.startTime ? dayjs(booking.startTime).format() : "",
endTime: booking.endTime ? dayjs(booking.endTime).format() : "",
organizer: {
email: organizer.email,
name: organizer.name ?? "Nameless",
timeZone: organizer.timeZone,
language: { translate: tOrganizer, locale: organizer.locale ?? "en" },
},
attendees: attendeesList,
uid: booking.uid,
location,
destinationCalendar: booking?.destinationCalendar || booking?.user?.destinationCalendar,
};
const eventManager = new EventManager(ctx.user);
const scheduleResult = await eventManager.create(evt);
const results = scheduleResult.results;
if (results.length > 0 && results.every((res) => !res.success)) {
const error = {
errorCode: "BookingUpdateLocationFailed",
message: "Updating location failed",
};
logger.error(`Booking ${ctx.user.username} failed`, error, results);
} else {
const metadata: AdditionInformation = {};
if (results.length) {
metadata.hangoutLink = results[0].createdEvent?.hangoutLink;
metadata.conferenceData = results[0].createdEvent?.conferenceData;
metadata.entryPoints = results[0].createdEvent?.entryPoints;
}
try {
await sendLocationChangeEmails({ ...evt, additionInformation: metadata });
} catch (error) {
console.log("Error sending LocationChangeEmails");
}
}
} catch {
throw new TRPCError({ code: "INTERNAL_SERVER_ERROR" });
}
return { message: "Location updated" };
},
});