fix: Location Change to Organizer Default Conferencing App (#16379)

* Fix

* Dont include test files

* Fix location change

* Self review fixes

* Add unit test

* Add more test

* Add a bookingScenario as well
This commit is contained in:
Hariom Balhara authored and GitHub committed 2024-09-11 21:31:53 +09:00
1 parent 4d53f327d9
commit e362c37ff3
20 files changed
+1343 -296

No files matched your search

+2 -2
View File
@@ -2,7 +2,7 @@ import { useCallback, useState } from "react";
import { AppSettings } from "@calcom/app-store/_components/AppSettings";
import { InstallAppButton } from "@calcom/app-store/components";
import { getEventLocationTypeFromApp, type EventLocationType } from "@calcom/app-store/locations";
import { getLocationFromApp, type EventLocationType } from "@calcom/app-store/locations";
import type { CredentialOwner } from "@calcom/app-store/types";
import { AppSetDefaultLinkDialog } from "@calcom/features/apps/components/AppSetDefaultLinkDialog";
import { BulkEditDefaultForEventsModal } from "@calcom/features/eventtypes/components/BulkEditDefaultForEventsModal";
@@ -92,7 +92,7 @@ export const AppList = ({ data, handleDisconnect, variant, listClassName }: AppL
color="secondary"
StartIcon="video"
onClick={() => {
const locationType = getEventLocationTypeFromApp(item?.locationOption?.value ?? "");
const locationType = getLocationFromApp(item?.locationOption?.value ?? "");
if (locationType?.linkType === "static") {
setLocationType({ ...locationType, slug: appSlug });
} else {
+29 -17
View File
@@ -2,12 +2,8 @@ import Link from "next/link";
import { useState } from "react";
import { Controller, useFieldArray, useForm } from "react-hook-form";
import type { EventLocationType, getEventLocationValue } from "@calcom/app-store/locations";
import {
getEventLocationType,
getSuccessPageLocationMessage,
guessEventLocationType,
} from "@calcom/app-store/locations";
import type { getEventLocationValue } from "@calcom/app-store/locations";
import { getSuccessPageLocationMessage, guessEventLocationType } from "@calcom/app-store/locations";
import dayjs from "@calcom/dayjs";
// TODO: Use browser locale, implement Intl in Dayjs maybe?
import "@calcom/dayjs/locales";
@@ -284,20 +280,36 @@ function BookingListItem(booking: BookingItemProps) {
setIsOpenLocationDialog(false);
utils.viewer.bookings.invalidate();
},
onError: (e) => {
const errorMessages: Record<string, string> = {
UNAUTHORIZED: t("you_are_unauthorized_to_make_this_change_to_the_booking"),
BAD_REQUEST: e.message,
};
const message = errorMessages[e.data?.code as string] || t("location_update_failed");
showToast(message, "error");
},
});
const saveLocation = (
newLocationType: EventLocationType["type"],
details: {
[key: string]: string;
const saveLocation = async ({
newLocation,
credentialId,
}: {
newLocation: string;
/**
* It could be set for conferencing locations that support team level installations.
*/
credentialId: number | null;
}) => {
try {
await setLocationMutation.mutateAsync({
bookingId: booking.id,
newLocation,
credentialId,
});
} catch {
// Errors are shown through the mutation onError handler
}
) => {
let newLocation = newLocationType as string;
const eventLocationType = getEventLocationType(newLocationType);
if (eventLocationType?.organizerInputType) {
newLocation = details[Object.keys(details)[0]];
}
setLocationMutation.mutate({ bookingId: booking.id, newLocation, details });
};
// Getting accepted recurring dates to show
+65 -117
View File
@@ -1,9 +1,7 @@
import { ErrorMessage } from "@hookform/error-message";
import { zodResolver } from "@hookform/resolvers/zod";
import { isValidPhoneNumber } from "libphonenumber-js";
import { Trans } from "next-i18next";
import Link from "next/link";
import { useEffect } from "react";
import { useEffect, useState } from "react";
import { Controller, useForm, useWatch, useFormContext } from "react-hook-form";
import { z } from "zod";
@@ -12,25 +10,30 @@ import {
getEventLocationType,
getHumanReadableLocationValue,
getMessageForOrganizer,
isAttendeeInputRequired,
LocationType,
OrganizerDefaultConferencingAppType,
} from "@calcom/app-store/locations";
import CheckboxField from "@calcom/features/form/components/CheckboxField";
import type { LocationOption } from "@calcom/features/form/components/LocationSelect";
import LocationSelect from "@calcom/features/form/components/LocationSelect";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import type { RouterOutputs } from "@calcom/trpc/react";
import { trpc } from "@calcom/trpc/react";
import { Button, Icon, Input, Dialog, DialogContent, DialogFooter, Form, PhoneInput } from "@calcom/ui";
import { QueryCell } from "@lib/QueryCell";
type BookingItem = RouterOutputs["viewer"]["bookings"]["get"]["bookings"][number];
import { QueryCell } from "../../lib/QueryCell";
interface ISetLocationDialog {
saveLocation: (newLocationType: EventLocationType["type"], details: { [key: string]: string }) => void;
saveLocation: ({
newLocation,
credentialId,
}: {
newLocation: string;
credentialId: number | null;
}) => Promise<void>;
selection?: LocationOption;
booking?: BookingItem;
booking: {
location: string | null;
};
defaultValues?: LocationObject[];
setShowLocationModal: React.Dispatch<React.SetStateAction<boolean>>;
isOpenDialog: boolean;
@@ -100,8 +103,7 @@ export const EditLocationDialog = (props: ISetLocationDialog) => {
locationType: z.string(),
phone: z.string().optional().nullable(),
locationAddress: z.string().optional(),
credentialId: z.number().optional(),
teamName: z.string().optional(),
credentialId: z.number().nullable().optional(),
locationLink: z
.string()
.optional()
@@ -134,7 +136,6 @@ export const EditLocationDialog = (props: ISetLocationDialog) => {
}
return;
}),
displayLocationPublicly: z.boolean().optional(),
locationPhoneNumber: z
.string()
.nullable()
@@ -145,6 +146,8 @@ export const EditLocationDialog = (props: ISetLocationDialog) => {
.optional(),
});
const [isLocationUpdating, setIsLocationUpdating] = useState(false);
const locationFormMethods = useForm({
mode: "onSubmit",
resolver: zodResolver(locationFormSchema),
@@ -172,7 +175,10 @@ export const EditLocationDialog = (props: ISetLocationDialog) => {
}
);
const LocationOptions = (() => {
/**
* Depending on the location type that is selected, we show different input types or no input at all.
*/
const SelectedLocationInput = (() => {
if (eventLocationType && eventLocationType.organizerInputType && LocationInput) {
if (!eventLocationType.variable) {
console.error("eventLocationType.variable can't be undefined");
@@ -203,25 +209,6 @@ export const EditLocationDialog = (props: ISetLocationDialog) => {
as="p"
/>
</div>
{!booking && (
<div className="mt-3">
<Controller
name="displayLocationPublicly"
control={locationFormMethods.control}
render={() => (
<CheckboxField
data-testid="display-location"
defaultChecked={defaultLocation?.displayLocationPublicly}
description={t("display_location_label")}
onChange={(e) =>
locationFormMethods.setValue("displayLocationPublicly", e.target.checked)
}
informationIconText={t("display_location_info_badge")}
/>
)}
/>
</div>
)}
</div>
);
} else {
@@ -241,91 +228,51 @@ export const EditLocationDialog = (props: ISetLocationDialog) => {
<h3 className="text-emphasis text-lg font-medium leading-6" id="modal-title">
{t("edit_location")}
</h3>
{!booking && (
<p className="text-default text-sm">
<Trans i18nKey="cant_find_the_right_conferencing_app_visit_our_app_store">
Can&apos;t find the right conferencing app? Visit our
<Link
className="cursor-pointer text-blue-500 underline"
href="/apps/categories/conferencing">
App Store
</Link>
.
</Trans>
</p>
)}
</div>
<div className="mt-3 text-center sm:mt-0 sm:text-left" />
{booking && (
<>
<p className="text-emphasis mb-2 ml-1 mt-6 text-sm font-bold">{t("current_location")}:</p>
<p className="text-emphasis mb-2 ml-1 text-sm">
{getHumanReadableLocationValue(booking.location, t)}
</p>
</>
)}
<p className="text-emphasis mb-2 ml-1 mt-6 text-sm font-bold">{t("current_location")}:</p>
<p className="text-emphasis mb-2 ml-1 text-sm">
{getHumanReadableLocationValue(booking.location, t)}
</p>
<Form
form={locationFormMethods}
handleSubmit={async (values) => {
const { locationType: newLocation, displayLocationPublicly } = values;
let details = {};
if (newLocation === LocationType.InPerson) {
details = {
address: values.locationAddress,
};
}
const eventLocationType = getEventLocationType(newLocation);
// TODO: There can be a property that tells if it is to be saved in `link`
if (
newLocation === LocationType.Link ||
(!eventLocationType?.default && eventLocationType?.linkType === "static")
) {
details = { link: values.locationLink };
}
if (newLocation === LocationType.UserPhone) {
details = { hostPhoneNumber: values.locationPhoneNumber };
}
const { locationType: newLocationType } = values;
let newLocation;
// For the locations that require organizer to type-in some values, we need the value
if (eventLocationType?.organizerInputType) {
details = {
...details,
displayLocationPublicly,
};
newLocation = values[eventLocationType.variable];
} else {
// locationType itself can be used here e.g. For zoom we use the type itself which is "integrations:zoom". For Organizer's Default Conferencing App, it is OrganizerDefaultConferencingAppType constant
newLocation = newLocationType;
}
if (values.credentialId) {
details = {
...details,
credentialId: values.credentialId,
};
setIsLocationUpdating(true);
try {
await saveLocation({
newLocation,
credentialId: values.credentialId ?? null,
});
setIsLocationUpdating(false);
setShowLocationModal(false);
setSelectedLocation?.(undefined);
locationFormMethods.unregister([
"locationType",
"locationLink",
"locationAddress",
"locationPhoneNumber",
]);
} catch (error) {
// Let the user retry
setIsLocationUpdating(false);
}
if (values.teamName) {
details = {
...details,
teamName: values.teamName,
};
}
saveLocation(newLocation, details);
setShowLocationModal(false);
setSelectedLocation?.(undefined);
locationFormMethods.unregister([
"locationType",
"locationLink",
"locationAddress",
"locationPhoneNumber",
]);
}}>
<QueryCell
query={locationsQuery}
success={({ data }) => {
if (!data.length) return null;
const locationOptions = [...data].map((option) => {
let locationOptions = [...data].map((option) => {
if (teamId) {
// Let host's Default conferencing App option show for Team Event
return option;
@@ -335,13 +282,11 @@ export const EditLocationDialog = (props: ISetLocationDialog) => {
options: option.options.filter((o) => o.value !== OrganizerDefaultConferencingAppType),
};
});
if (booking) {
locationOptions.map((location) =>
location.options.filter(
(l) => !["phone", "attendeeInPerson", "somewhereElse"].includes(l.value)
)
);
}
locationOptions = locationOptions.map((locationOption) =>
filterLocationOptionsForBooking(locationOption)
);
return (
<Controller
name="locationType"
@@ -357,11 +302,7 @@ export const EditLocationDialog = (props: ISetLocationDialog) => {
onChange={(val) => {
if (val) {
locationFormMethods.setValue("locationType", val.value);
if (typeof val.credentialId === "number" && val.credentialId >= 0) {
locationFormMethods.setValue("credentialId", val.credentialId);
locationFormMethods.setValue("teamName", val.teamName ?? "");
}
locationFormMethods.setValue("credentialId", val.credentialId);
locationFormMethods.unregister([
"locationLink",
"locationAddress",
@@ -382,7 +323,7 @@ export const EditLocationDialog = (props: ISetLocationDialog) => {
);
}}
/>
{selectedLocation && LocationOptions}
{selectedLocation && SelectedLocationInput}
<DialogFooter className="relative">
<Button
onClick={() => {
@@ -396,7 +337,7 @@ export const EditLocationDialog = (props: ISetLocationDialog) => {
{t("cancel")}
</Button>
<Button data-testid="update-location" type="submit">
<Button data-testid="update-location" type="submit" disabled={isLocationUpdating}>
{t("update")}
</Button>
</DialogFooter>
@@ -407,3 +348,10 @@ export const EditLocationDialog = (props: ISetLocationDialog) => {
</Dialog>
);
};
function filterLocationOptionsForBooking<T extends { options: { value: string }[] }>(locationOption: T) {
return {
...locationOption,
options: locationOption.options.filter((o) => !isAttendeeInputRequired(o.value)),
};
}
@@ -0,0 +1,225 @@
import { render, screen, fireEvent, waitFor } from "@testing-library/react";
import * as React from "react";
import { vi } from "vitest";
import LocationSelect from "@calcom/features/form/components/LocationSelect";
import { QueryCell } from "../../../lib/QueryCell";
import { EditLocationDialog } from "../EditLocationDialog";
// // Mock the trpc hook
vi.mock("@calcom/trpc/react", () => ({
trpc: {
viewer: {
locationOptions: {
useQuery: vi.fn(),
},
},
},
}));
vi.mock("@calcom/lib/hooks/useLocale", () => ({
useLocale: () => ({ t: (key: string) => key }),
}));
vi.mock("../../../lib/QueryCell", () => ({
QueryCell: vi.fn(),
}));
vi.mock("@calcom/features/form/components/LocationSelect", () => {
return {
default: vi.fn(),
};
});
const AttendeePhoneNumberLabel = "Attendee Phone Number";
const OrganizerPhoneLabel = "Organizer Phone Number";
const CampfireLabel = "Campfire";
const ZoomVideoLabel = "Zoom Video";
const OrganizerDefaultConferencingAppLabel = "Organizer's default app";
describe("EditLocationDialog", () => {
const mockProps = {
saveLocation: vi.fn(),
setShowLocationModal: vi.fn(),
isOpenDialog: true,
};
beforeEach(() => {
vi.clearAllMocks();
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
QueryCell.mockImplementation(({ success }) => {
return success({
data: [
{
label: "Conferencing",
options: [
{
value: "integrations:campfire_video",
label: CampfireLabel,
disabled: false,
icon: "/app-store/campfire/icon.svg",
slug: "campfire",
credentialId: 2,
teamName: null,
},
{
value: "integrations:daily",
label: "Cal Video (Global)",
disabled: false,
icon: "/app-store/dailyvideo/icon.svg",
slug: "daily-video",
credentialId: 0,
teamName: "Global",
},
{
value: "integrations:zoom",
label: ZoomVideoLabel,
disabled: false,
icon: "/app-store/zoomvideo/icon.svg",
slug: "zoom",
credentialId: 1,
teamName: null,
},
{
label: "Organizer's default app",
value: "conferencing",
icon: "/link.svg",
},
],
},
{
label: "in person",
options: [
{
label: "In Person (Attendee Address)",
value: "attendeeInPerson",
icon: "/map-pin-dark.svg",
},
{
label: "In Person (Organizer Address)",
value: "inPerson",
icon: "/map-pin-dark.svg",
},
],
},
{
label: "Other",
options: [
{
label: "Custom attendee location",
value: "somewhereElse",
icon: "/message-pin.svg",
},
{
label: "Link meeting",
value: "link",
icon: "/link.svg",
},
],
},
{
label: "phone",
options: [
{
label: AttendeePhoneNumberLabel,
value: "phone",
icon: "/phone.svg",
},
{
label: OrganizerPhoneLabel,
value: "userPhone",
icon: "/phone.svg",
},
],
},
],
});
});
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
LocationSelect.mockImplementation(
// eslint-disable-next-line @typescript-eslint/no-explicit-any
({ options, defaultValue, onChange }: { options: any; defaultValue: any; onChange: any }) => {
return (
<select
data-testid="location-select"
defaultValue={defaultValue}
onChange={(e) => {
const selectedOption = options
// eslint-disable-next-line @typescript-eslint/no-explicit-any
.flatMap((opt: any) => opt.options || [opt])
// eslint-disable-next-line @typescript-eslint/no-explicit-any
.find((opt: any) => opt.value === e.target.value);
onChange(selectedOption);
}}>
{/* eslint-disable-next-line @typescript-eslint/no-explicit-any */}
{options.map((group: any) => (
<optgroup key={group.value} label={group.label}>
{/* eslint-disable-next-line @typescript-eslint/no-explicit-any */}
{(group.options || [group]).map((option: any) => (
<option key={option.value} value={option.value}>
{option.label}
</option>
))}
</optgroup>
))}
</select>
);
}
);
});
it("renders the dialog when open", () => {
// It shows whatever the location even if it isn't in the options list
render(<EditLocationDialog {...mockProps} booking={{ location: "Office" }} />);
expect(screen.getByText("edit_location")).toBeInTheDocument();
expect(screen.getByText("current_location:")).toBeInTheDocument();
expect(screen.getByText("Office")).toBeInTheDocument();
});
it("closes the dialog when cancel is clicked", async () => {
render(<EditLocationDialog {...mockProps} booking={{ location: "Office" }} />);
fireEvent.click(screen.getByText("cancel"));
expect(mockProps.setShowLocationModal).toHaveBeenCalledWith(false);
});
describe("Team Booking Case", () => {
it("should not show Attendee Phone Number but show Organizer Phone Number and dynamic link Conferencing apps", async () => {
render(<EditLocationDialog {...mockProps} booking={{ location: "Office" }} teamId={1} />);
expect(screen.queryByText(AttendeePhoneNumberLabel)).not.toBeInTheDocument();
expect(screen.queryByText(OrganizerPhoneLabel)).toBeInTheDocument();
expect(screen.queryByText(CampfireLabel)).toBeInTheDocument();
expect(screen.queryByText(ZoomVideoLabel)).toBeInTheDocument();
});
it("should update location to Organizer Default App", async () => {
render(<EditLocationDialog {...mockProps} booking={{ location: "Office" }} teamId={1} />);
const select = screen.getByRole("combobox");
fireEvent.change(select, { target: { value: "conferencing" } });
// Submit the form
fireEvent.click(screen.getByText("update"));
await waitFor(() => {
expect(mockProps.saveLocation).toHaveBeenCalledWith({
newLocation: "conferencing",
credentialId: null,
});
expect(mockProps.setShowLocationModal).toHaveBeenCalledWith(false);
});
});
});
describe("Non Team Booking Case", () => {
it("should not show Organizer's default app", async () => {
render(<EditLocationDialog {...mockProps} booking={{ location: "Office" }} />);
expect(screen.queryByText(OrganizerDefaultConferencingAppLabel)).not.toBeInTheDocument();
});
});
});