fix: Across Org Scenarios - Wrong links for event and team (#12358)

Co-authored-by: sean-brydon <[email protected]>
This commit is contained in:
Hariom Balharaandsean-brydon authored and GitHub committed 2023-12-19 19:33:30 +10:00
1 parent f1caaad536
commit e5e0fa97eb
35 files changed
+570 -154

No files matched your search

@@ -60,6 +60,7 @@ import { getVideoCallUrlFromCalEvent } from "@calcom/lib/CalEventParser";
import { getDefaultEvent, getUsernameList } from "@calcom/lib/defaultEvents";
import { ErrorCode } from "@calcom/lib/errorCodes";
import { getErrorFromUnknown } from "@calcom/lib/errors";
import { getBookerBaseUrl } from "@calcom/lib/getBookerUrl/server";
import getPaymentAppData from "@calcom/lib/getPaymentAppData";
import { getTeamIdFromEventType } from "@calcom/lib/getTeamIdFromEventType";
import { HttpError } from "@calcom/lib/http-error";
@@ -69,7 +70,6 @@ import { handlePayment } from "@calcom/lib/payment/handlePayment";
import { getPiiFreeCalendarEvent, getPiiFreeEventType, getPiiFreeUser } from "@calcom/lib/piiFreeData";
import { safeStringify } from "@calcom/lib/safeStringify";
import { checkBookingLimits, checkDurationLimits, getLuckyUser } from "@calcom/lib/server";
import { getBookerUrl } from "@calcom/lib/server/getBookerUrl";
import { getTranslation } from "@calcom/lib/server/i18n";
import { slugify } from "@calcom/lib/slugify";
import { updateWebUser as syncServicesUpdateWebUser } from "@calcom/lib/sync/SyncServiceManager";
@@ -274,6 +274,7 @@ export const getEventTypesFromDB = async (eventTypeId: number) => {
select: {
id: true,
name: true,
parentId: true,
},
},
bookingFields: true,
@@ -1272,7 +1273,9 @@ async function handler(
const iCalSequence = getICalSequence(originalRescheduledBooking);
let evt: CalendarEvent = {
bookerUrl: await getBookerUrl(organizerUser),
bookerUrl: eventType.team
? await getBookerBaseUrl({ organizationId: eventType.team.parentId })
: await getBookerBaseUrl(organizerUser),
type: eventType.slug,
title: getEventName(eventNameObject), //this needs to be either forced in english, or fetched for each attendee and organizer separately
description: eventType.description,
@@ -8,6 +8,7 @@ import { ErrorCode } from "@calcom/lib/errorCodes";
import { SchedulingType } from "@calcom/prisma/enums";
import { BookingStatus } from "@calcom/prisma/enums";
import { test } from "@calcom/web/test/fixtures/fixtures";
import { createOrganization } from "@calcom/web/test/utils/bookingScenario/bookingScenario";
import {
createBookingScenario,
getGoogleCalendarCredential,
@@ -1085,6 +1086,219 @@ describe("handleNewBooking", () => {
},
timeout
);
describe("Team(T1) not part of any org but the organizer is part of an organization(O1)", () => {
test(
`succesfully creates a booking when all the hosts are free as per their schedules
- Destination calendars for event-type and non-first hosts are used to create calendar events
- Reschedule and Cancel link in email are not of the org domain because the team is not part of any org
`,
async ({ emails }) => {
const handleNewBooking = (await import("@calcom/features/bookings/lib/handleNewBooking")).default;
const org = await createOrganization({
name: "Test Org",
slug: "testorg",
});
const booker = getBooker({
email: "[email protected]",
name: "Booker",
});
const otherTeamMembers = [
{
name: "Other Team Member 1",
username: "other-team-member-1",
timeZone: Timezones["+5:30"],
// So, that it picks the first schedule from the list
defaultScheduleId: null,
email: "[email protected]",
id: 102,
// Has Evening shift
schedules: [TestData.schedules.IstEveningShift],
credentials: [getGoogleCalendarCredential()],
selectedCalendars: [TestData.selectedCalendars.google],
destinationCalendar: {
integration: TestData.apps["google-calendar"].type,
externalId: "[email protected]",
},
},
];
const organizer = getOrganizer({
name: "Organizer",
email: "[email protected]",
id: 101,
// So, that it picks the first schedule from the list
defaultScheduleId: null,
organizationId: org.id,
teams: [
{
membership: {
accepted: true,
},
team: {
id: 1,
name: "Team 1",
slug: "team-1",
},
},
],
// Has morning shift with some overlap with morning shift
schedules: [TestData.schedules.IstMorningShift],
credentials: [getGoogleCalendarCredential()],
selectedCalendars: [TestData.selectedCalendars.google],
destinationCalendar: {
integration: TestData.apps["google-calendar"].type,
externalId: "[email protected]",
},
});
await createBookingScenario(
getScenarioData({
webhooks: [
{
userId: organizer.id,
eventTriggers: ["BOOKING_CREATED"],
subscriberUrl: "http://my-webhook.example.com",
active: true,
eventTypeId: 1,
appId: null,
},
],
eventTypes: [
{
id: 1,
slotInterval: 45,
schedulingType: SchedulingType.COLLECTIVE,
length: 45,
users: [
{
id: 101,
},
{
id: 102,
},
],
// It is a team event but that team isn't part of any org
teamId: 1,
destinationCalendar: {
integration: TestData.apps["google-calendar"].type,
externalId: "[email protected]",
},
},
],
organizer,
usersApartFromOrganizer: otherTeamMembers,
apps: [TestData.apps["google-calendar"], TestData.apps["daily-video"]],
})
);
mockSuccessfulVideoMeetingCreation({
metadataLookupKey: appStoreMetadata.dailyvideo.dirName,
videoMeetingData: {
id: "MOCK_ID",
password: "MOCK_PASS",
url: `http://mock-dailyvideo.example.com/meeting-1`,
},
});
const calendarMock = mockCalendarToHaveNoBusySlots("googlecalendar", {
create: {
id: "MOCKED_GOOGLE_CALENDAR_EVENT_ID",
iCalUID: "MOCKED_GOOGLE_CALENDAR_ICS_ID",
},
});
const mockBookingData = getMockRequestDataForBooking({
data: {
// Try booking the first available free timeslot in both the users' schedules
start: `${getDate({ dateIncrement: 1 }).dateString}T11:30:00.000Z`,
end: `${getDate({ dateIncrement: 1 }).dateString}T11:45:00.000Z`,
eventTypeId: 1,
responses: {
email: booker.email,
name: booker.name,
location: { optionValue: "", value: BookingLocations.CalVideo },
},
},
});
const { req } = createMockNextJsRequest({
method: "POST",
body: mockBookingData,
});
const createdBooking = await handleNewBooking(req);
await expectBookingToBeInDatabase({
description: "",
location: BookingLocations.CalVideo,
responses: expect.objectContaining({
email: booker.email,
name: booker.name,
}),
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
uid: createdBooking.uid!,
eventTypeId: mockBookingData.eventTypeId,
status: BookingStatus.ACCEPTED,
references: [
{
type: appStoreMetadata.dailyvideo.type,
uid: "MOCK_ID",
meetingId: "MOCK_ID",
meetingPassword: "MOCK_PASS",
meetingUrl: "http://mock-dailyvideo.example.com/meeting-1",
},
{
type: TestData.apps["google-calendar"].type,
uid: "MOCKED_GOOGLE_CALENDAR_EVENT_ID",
meetingId: "MOCKED_GOOGLE_CALENDAR_EVENT_ID",
meetingPassword: "MOCK_PASSWORD",
meetingUrl: "https://UNUSED_URL",
},
],
});
expectWorkflowToBeTriggered();
expectSuccessfulCalendarEventCreationInCalendar(calendarMock, {
destinationCalendars: [
{
integration: TestData.apps["google-calendar"].type,
externalId: "[email protected]",
},
{
integration: TestData.apps["google-calendar"].type,
externalId: "[email protected]",
},
],
videoCallUrl: "http://mock-dailyvideo.example.com/meeting-1",
});
expectSuccessfulBookingCreationEmails({
booking: {
uid: createdBooking.uid!,
// All booking links are of WEBAPP_URL and not of the org because the team isn't part of the org
urlOrigin: WEBAPP_URL,
},
booker,
organizer,
otherTeamMembers,
emails,
iCalUID: "MOCKED_GOOGLE_CALENDAR_ICS_ID",
});
expectBookingCreatedWebhookToHaveBeenFired({
booker,
organizer,
location: BookingLocations.CalVideo,
subscriberUrl: "http://my-webhook.example.com",
videoCallUrl: `${WEBAPP_URL}/video/${createdBooking.uid}`,
});
},
timeout
);
});
});
test.todo("Round Robin booking");
@@ -95,7 +95,7 @@ export function subdomainSuffix() {
}
export function getOrgFullOrigin(slug: string, options: { protocol: boolean } = { protocol: true }) {
if (!slug) return WEBAPP_URL;
if (!slug) return WEBAPP_URL.replace("https://", "").replace("http://", "");
const orgFullOrigin = `${
options.protocol ? `${new URL(WEBAPP_URL).protocol}//` : ""
}${slug}.${subdomainSuffix()}`;
@@ -1,11 +1,9 @@
import classNames from "classnames";
import TeamPill, { TeamRole } from "@calcom/ee/teams/components/TeamPill";
import { useBookerUrl } from "@calcom/lib/hooks/useBookerUrl";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import type { RouterOutputs } from "@calcom/trpc/react";
import {
Avatar,
Button,
ButtonGroup,
Dropdown,
@@ -17,6 +15,8 @@ import {
} from "@calcom/ui";
import { ExternalLink, MoreHorizontal } from "@calcom/ui/components/icon";
import { UserAvatar } from "@components/ui/avatar/UserAvatar";
interface Props {
member: RouterOutputs["viewer"]["organizations"]["listOtherTeamMembers"]["rows"][number];
}
@@ -26,22 +26,17 @@ export default function MemberListItem(props: Props) {
const { member } = props;
const { user } = member;
const bookerUrl = useBookerUrl();
const name = user.name || user.username || user.email;
const bookerUrl = props.member.bookerUrl;
const bookerUrlWithoutProtocol = bookerUrl.replace(/^https?:\/\//, "");
const bookingLink = user.username && `${bookerUrlWithoutProtocol}/${user.username}`;
const name = user.name || user.username || user.email;
return (
<li className="divide-subtle divide-y px-5">
<div className="my-4 flex justify-between">
<div className="flex w-full flex-col justify-between overflow-hidden sm:flex-row">
<div className="flex">
<Avatar
size="sm"
imageSrc={`${bookerUrl}/${user.username}/avatar.png`}
alt={name || ""}
className="h-10 w-10 rounded-full"
/>
<UserAvatar size="sm" user={user} className="h-10 w-10 rounded-full" />
<div className="ms-3 inline-block overflow-hidden">
<div className="mb-1 flex">
@@ -6,24 +6,16 @@ import { useOrgBranding } from "@calcom/features/ee/organizations/context/provid
import InviteLinkSettingsModal from "@calcom/features/ee/teams/components/InviteLinkSettingsModal";
import MemberInvitationModal from "@calcom/features/ee/teams/components/MemberInvitationModal";
import { classNames } from "@calcom/lib";
import { APP_NAME, WEBAPP_URL } from "@calcom/lib/constants";
import { useBookerUrl } from "@calcom/lib/hooks/useBookerUrl";
import { APP_NAME } from "@calcom/lib/constants";
import { useCompatSearchParams } from "@calcom/lib/hooks/useCompatSearchParams";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { useTelemetry, telemetryEventTypes } from "@calcom/lib/telemetry";
import { MembershipRole } from "@calcom/prisma/enums";
import type { RouterOutputs } from "@calcom/trpc/react";
import { trpc } from "@calcom/trpc/react";
import {
Avatar,
Badge,
Button,
showToast,
SkeletonButton,
SkeletonContainer,
SkeletonText,
} from "@calcom/ui";
import { Badge, Button, showToast, SkeletonButton, SkeletonContainer, SkeletonText } from "@calcom/ui";
import { ArrowRight, Plus, Trash2 } from "@calcom/ui/components/icon";
import { UserAvatar } from "@calcom/web/components/ui/avatar/UserAvatar";
type TeamMember = RouterOutputs["viewer"]["teams"]["get"]["members"][number];
@@ -219,7 +211,7 @@ const PendingMemberItem = (props: { member: TeamMember; index: number; teamId: n
const { t } = useLocale();
const utils = trpc.useContext();
const session = useSession();
const bookerUrl = useBookerUrl();
const bookerUrl = member.bookerUrl;
const { data: currentOrg } = trpc.viewer.organizations.listCurrent.useQuery(undefined, {
enabled: !!session.data?.user?.org,
});
@@ -247,7 +239,7 @@ const PendingMemberItem = (props: { member: TeamMember; index: number; teamId: n
)}
data-testid="pending-member-item">
<div className="mr-4 flex max-w-full space-x-2 overflow-hidden rtl:space-x-reverse">
<Avatar size="mdLg" imageSrc={`${bookerUrl}/${member.username}/avatar.png`} alt="owner-avatar" />
<UserAvatar size="mdLg" user={member} />
<div className="max-w-full overflow-hidden">
<div className="flex space-x-1">
<p>{member.name || member.email || t("team_member")}</p>
@@ -258,7 +250,7 @@ const PendingMemberItem = (props: { member: TeamMember; index: number; teamId: n
{member.role === "ADMIN" && <Badge variant="default">{t("admin")}</Badge>}
</div>
{member.username ? (
<p className="text-default truncate">{`${WEBAPP_URL}/${member.username}`}</p>
<p className="text-default truncate">{`${bookerUrl}/${member.username}`}</p>
) : (
<p className="text-default truncate">{t("not_on_cal", { appName: APP_NAME })}</p>
)}
@@ -3,7 +3,6 @@ import { SendIcon } from "lucide-react";
import { signIn } from "next-auth/react";
import { useState } from "react";
import { useBookerUrl } from "@calcom/lib/hooks/useBookerUrl";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { MembershipRole } from "@calcom/prisma/enums";
import { teamMetadataSchema } from "@calcom/prisma/zod-utils";
@@ -120,7 +119,7 @@ export default function MemberListItem(props: Props) {
process.env.NEXT_PUBLIC_TEAM_IMPERSONATION === "true";
const resendInvitation = editMode && !props.member.accepted;
const bookerUrl = useBookerUrl();
const bookerUrl = props.member.bookerUrl;
const bookerUrlWithoutProtocol = bookerUrl.replace(/^https?:\/\//, "");
const bookingLink = !!props.member.username && `${bookerUrlWithoutProtocol}/${props.member.username}`;
const isAdmin = props.team && ["ADMIN", "OWNER"].includes(props.team.membership?.role);
@@ -6,6 +6,7 @@ import InviteLinkSettingsModal from "@calcom/ee/teams/components/InviteLinkSetti
import MemberInvitationModal from "@calcom/ee/teams/components/MemberInvitationModal";
import classNames from "@calcom/lib/classNames";
import { getPlaceholderAvatar } from "@calcom/lib/defaultAvatarImage";
import { getTeamUrlSync } from "@calcom/lib/getBookerUrl/client";
import { useCompatSearchParams } from "@calcom/lib/hooks/useCompatSearchParams";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { MembershipRole } from "@calcom/prisma/enums";
@@ -106,11 +107,9 @@ export default function TeamListItem(props: Props) {
<span className="text-default text-sm font-bold">{team.name}</span>
<span className="text-muted block text-xs">
{team.slug ? (
orgBranding ? (
`${orgBranding.fullDomain}/${team.slug}`
) : (
`${process.env.NEXT_PUBLIC_WEBSITE_URL}/team/${team.slug}`
)
`${getTeamUrlSync({ orgSlug: team.parent ? team.parent.slug : null, teamSlug: team.slug })}/${
team.slug
}`
) : (
<Badge>{t("upgrade")}</Badge>
)}
@@ -7,11 +7,10 @@ import { useLayoutEffect, useState } from "react";
import { Controller, useForm } from "react-hook-form";
import { z } from "zod";
import { useOrgBranding } from "@calcom/features/ee/organizations/context/provider";
import { getOrgFullOrigin } from "@calcom/features/ee/organizations/lib/orgDomains";
import SectionBottomActions from "@calcom/features/settings/SectionBottomActions";
import { IS_TEAM_BILLING_ENABLED, WEBAPP_URL } from "@calcom/lib/constants";
import { getPlaceholderAvatar } from "@calcom/lib/defaultAvatarImage";
import { getTeamUrlSync } from "@calcom/lib/getBookerUrl/client";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { useParamsWithFallback } from "@calcom/lib/hooks/useParamsWithFallback";
import { md } from "@calcom/lib/markdownIt";
@@ -269,7 +268,6 @@ const TeamProfileForm = ({ team }: TeamProfileFormProps) => {
});
const [firstRender, setFirstRender] = useState(true);
const orgBranding = useOrgBranding();
const {
formState: { isSubmitting, isDirty },
@@ -375,11 +373,14 @@ const TeamProfileForm = ({ team }: TeamProfileFormProps) => {
name="slug"
label={t("team_url")}
value={value}
addOnLeading={
team.parent && orgBranding
? `${getOrgFullOrigin(orgBranding?.slug, { protocol: false })}/`
: `${WEBAPP_URL}/team/`
}
data-testid="team-url"
addOnClassname="testid-leading-text-team-url"
addOnLeading={`${getTeamUrlSync(
{ orgSlug: team.parent ? team.parent.slug : null, teamSlug: null },
{
protocol: false,
}
)}`}
onChange={(e) => {
form.clearErrors("slug");
form.setValue("slug", slugify(e?.target.value, true), { shouldDirty: true });
@@ -1,8 +1,6 @@
import { useAutoAnimate } from "@formkit/auto-animate/react";
import type { Props } from "react-select";
import { useOrgBranding } from "@calcom/features/ee/organizations/context/provider";
import { getOrgFullOrigin } from "@calcom/features/ee/organizations/lib/orgDomains";
import { classNames } from "@calcom/lib";
import { CAL_URL } from "@calcom/lib/constants";
import { useLocale } from "@calcom/lib/hooks/useLocale";
@@ -15,6 +13,7 @@ export type ChildrenEventType = {
label: string;
created: boolean;
owner: {
avatar: string;
id: number;
email: string;
name: string;
@@ -36,7 +35,6 @@ export const ChildrenEventTypeSelect = ({
onChange: (value: readonly ChildrenEventType[]) => void;
}) => {
const { t } = useLocale();
const orgBranding = useOrgBranding();
const [animationRef] = useAutoAnimate<HTMLUListElement>();
return (
@@ -63,9 +61,7 @@ export const ChildrenEventTypeSelect = ({
<Avatar
size="mdLg"
className="overflow-visible"
imageSrc={`${orgBranding ? getOrgFullOrigin(orgBranding.slug) : CAL_URL}/${
children.owner.username
}/avatar.png`}
imageSrc={children.owner.avatar}
alt={children.owner.name || children.owner.email || ""}
/>
<div className="flex w-full flex-row justify-between">