refactor: apply biome formatting to apps/web (#27692)
* refactor: apply biome formatting to apps/web (batch 1) Formats apps/web non-modules directories: - apps/web/app - apps/web/lib - apps/web/pages - apps/web/styles - apps/web/server - apps/web/test - Root-level .ts and .mjs files Co-Authored-By: Claude Opus 4.5 <[email protected]> * refactor: apply biome formatting to apps/web/modules (batch 2) Formats smaller apps/web/modules directories: - onboarding, data-table, users, apps, auth - integration-attribute-sync, shell, availability - feature-flags, team, webhooks, getting-started - feature-opt-in, troubleshooter, schedules, notifications - signup-view.tsx Co-Authored-By: Claude Opus 4.5 <[email protected]> * refactor: apply biome formatting to apps/web/modules (batch 3) Formats medium apps/web/modules directories: - bookings - event-types - insights - embed Co-Authored-By: Claude Opus 4.5 <[email protected]> * refactor: apply biome formatting to apps/web/modules/ee (batch 4) Formats apps/web/modules/ee directory. Co-Authored-By: Claude Opus 4.5 <[email protected]> * refactor: apply biome formatting to apps/web (batch 5) Formats remaining apps/web directories: - apps/web/modules/settings - apps/web/modules/booking-audit - apps/web/playwright Co-Authored-By: Claude Opus 4.5 <[email protected]> * refactor: apply biome formatting to apps/web/components (batch 6) Formats remaining apps/web/components files. Co-Authored-By: Claude Opus 4.5 <[email protected]> * refactor: apply biome formatting to new apps/web files from main Formats newly added/modified files from main merge: - WorkflowStepContainer.tsx (resolved merge conflicts) - Newly moved files (blocklist, form-builder, schedules, etc.) - Other files modified in main Co-Authored-By: Claude Opus 4.5 <[email protected]> * refactor: apply biome formatting to new apps/web files from main Co-Authored-By: Claude Opus 4.5 <[email protected]> --------- Co-authored-by: Claude Opus 4.5 <[email protected]> Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
This commit is contained in:
271 files changed
+3729
-4857
No files matched your search
@@ -1,6 +1,6 @@
|
||||
// Added as a separate route for now to ease the testing of the audit logs feature
|
||||
// It partially matches the figma design - https://www.figma.com/design/wleA2SR6rn60EK7ORxAfMy/Cal.com-New-Features?node-id=5641-6732&p=f
|
||||
// TOOD: Move it to the booking page side bar later
|
||||
// TOOD: Move it to the booking page side bar later
|
||||
import { ShellMainAppDir } from "app/(use-page-wrapper)/(main-nav)/ShellMainAppDir";
|
||||
import type { PageProps } from "app/_types";
|
||||
import { _generateMetadata, getTranslate } from "app/_utils";
|
||||
@@ -14,35 +14,34 @@ import { buildLegacyRequest } from "@lib/buildLegacyCtx";
|
||||
import { BookingHistoryPage } from "@calcom/web/modules/booking-audit/components/BookingHistoryPage";
|
||||
|
||||
export const generateMetadata = async ({ params }: { params: Promise<{ uid: string }> }) =>
|
||||
await _generateMetadata(
|
||||
(t) => t("booking_history"),
|
||||
(t) => t("booking_history_description"),
|
||||
undefined,
|
||||
undefined,
|
||||
`/booking/${(await params).uid}/logs`
|
||||
);
|
||||
await _generateMetadata(
|
||||
(t) => t("booking_history"),
|
||||
(t) => t("booking_history_description"),
|
||||
undefined,
|
||||
undefined,
|
||||
`/booking/${(await params).uid}/logs`
|
||||
);
|
||||
|
||||
const Page = async ({ params }: PageProps) => {
|
||||
const resolvedParams = await params;
|
||||
const bookingUid = resolvedParams.uid;
|
||||
const resolvedParams = await params;
|
||||
const bookingUid = resolvedParams.uid;
|
||||
|
||||
if (!bookingUid || typeof bookingUid !== "string") {
|
||||
redirect("/bookings/upcoming");
|
||||
}
|
||||
if (!bookingUid || typeof bookingUid !== "string") {
|
||||
redirect("/bookings/upcoming");
|
||||
}
|
||||
|
||||
const t = await getTranslate();
|
||||
const session = await getServerSession({ req: buildLegacyRequest(await headers(), await cookies()) });
|
||||
const t = await getTranslate();
|
||||
const session = await getServerSession({ req: buildLegacyRequest(await headers(), await cookies()) });
|
||||
|
||||
if (!session?.user?.id) {
|
||||
redirect("/auth/login");
|
||||
}
|
||||
if (!session?.user?.id) {
|
||||
redirect("/auth/login");
|
||||
}
|
||||
|
||||
return (
|
||||
<ShellMainAppDir heading={t("booking_history")} subtitle={t("booking_history_description")}>
|
||||
<BookingHistoryPage bookingUid={bookingUid} />
|
||||
</ShellMainAppDir>
|
||||
);
|
||||
return (
|
||||
<ShellMainAppDir heading={t("booking_history")} subtitle={t("booking_history_description")}>
|
||||
<BookingHistoryPage bookingUid={bookingUid} />
|
||||
</ShellMainAppDir>
|
||||
);
|
||||
};
|
||||
|
||||
export default Page;
|
||||
|
||||
@@ -5,11 +5,7 @@ import type { RouterOutputs } from "@calcom/trpc/react";
|
||||
import { eventTypesRouter } from "@calcom/trpc/server/routers/viewer/eventTypes/_router";
|
||||
import { buildLegacyRequest } from "@lib/buildLegacyCtx";
|
||||
import { createRouterCaller, getTRPCContext } from "app/_trpc/context";
|
||||
import type {
|
||||
PageProps,
|
||||
ReadonlyHeaders,
|
||||
ReadonlyRequestCookies,
|
||||
} from "app/_types";
|
||||
import type { PageProps, ReadonlyHeaders, ReadonlyRequestCookies } from "app/_types";
|
||||
import { _generateMetadata } from "app/_utils";
|
||||
import { unstable_cache } from "next/cache";
|
||||
import { cookies, headers } from "next/headers";
|
||||
@@ -26,26 +22,25 @@ const getCachedEventGroups: (
|
||||
userIds?: number[] | undefined;
|
||||
upIds?: string[] | undefined;
|
||||
}
|
||||
) => Promise<RouterOutputs["viewer"]["eventTypes"]["getUserEventGroups"]> =
|
||||
unstable_cache(
|
||||
async (
|
||||
headers: ReadonlyHeaders,
|
||||
cookies: ReadonlyRequestCookies,
|
||||
filters?: {
|
||||
teamIds?: number[] | undefined;
|
||||
userIds?: number[] | undefined;
|
||||
upIds?: string[] | undefined;
|
||||
}
|
||||
): Promise<RouterOutputs["viewer"]["eventTypes"]["getUserEventGroups"]> => {
|
||||
const eventTypesCaller = await createRouterCaller(
|
||||
eventTypesRouter,
|
||||
await getTRPCContext(headers, cookies)
|
||||
);
|
||||
return await eventTypesCaller.getUserEventGroups({ filters });
|
||||
},
|
||||
["viewer.eventTypes.getUserEventGroups"],
|
||||
{ revalidate: 3600 } // seconds
|
||||
);
|
||||
) => Promise<RouterOutputs["viewer"]["eventTypes"]["getUserEventGroups"]> = unstable_cache(
|
||||
async (
|
||||
headers: ReadonlyHeaders,
|
||||
cookies: ReadonlyRequestCookies,
|
||||
filters?: {
|
||||
teamIds?: number[] | undefined;
|
||||
userIds?: number[] | undefined;
|
||||
upIds?: string[] | undefined;
|
||||
}
|
||||
): Promise<RouterOutputs["viewer"]["eventTypes"]["getUserEventGroups"]> => {
|
||||
const eventTypesCaller = await createRouterCaller(
|
||||
eventTypesRouter,
|
||||
await getTRPCContext(headers, cookies)
|
||||
);
|
||||
return await eventTypesCaller.getUserEventGroups({ filters });
|
||||
},
|
||||
["viewer.eventTypes.getUserEventGroups"],
|
||||
{ revalidate: 3600 } // seconds
|
||||
);
|
||||
|
||||
const Page = async ({ searchParams }: PageProps): Promise<ReactElement> => {
|
||||
const _searchParams = await searchParams;
|
||||
@@ -71,23 +66,12 @@ const Page = async ({ searchParams }: PageProps): Promise<ReactElement> => {
|
||||
}
|
||||
|
||||
const filters = getTeamsFiltersFromQuery(_searchParams);
|
||||
const userEventGroupsData = await getCachedEventGroups(
|
||||
_headers,
|
||||
_cookies,
|
||||
filters
|
||||
);
|
||||
const userEventGroupsData = await getCachedEventGroups(_headers, _cookies, filters);
|
||||
|
||||
return (
|
||||
<EventTypesWrapper
|
||||
userEventGroupsData={userEventGroupsData}
|
||||
user={session.user}
|
||||
/>
|
||||
);
|
||||
return <EventTypesWrapper userEventGroupsData={userEventGroupsData} user={session.user} />;
|
||||
};
|
||||
|
||||
export const generateMetadata = async (): Promise<
|
||||
ReturnType<typeof _generateMetadata>
|
||||
> =>
|
||||
export const generateMetadata = async (): Promise<ReturnType<typeof _generateMetadata>> =>
|
||||
await _generateMetadata(
|
||||
(t) => t("event_types_page_title"),
|
||||
(t) => t("event_types_page_subtitle"),
|
||||
|
||||
@@ -15,7 +15,7 @@ export const TeamsCTA = () => {
|
||||
size="sm"
|
||||
type="button"
|
||||
onClick={() => {
|
||||
posthog.capture("add_team_button_clicked")
|
||||
posthog.capture("add_team_button_clicked");
|
||||
}}
|
||||
href={`${WEBAPP_URL}/settings/teams/new?returnTo=${WEBAPP_URL}/teams`}>
|
||||
{t("new")}
|
||||
|
||||
@@ -38,12 +38,15 @@ const ServerPage = async () => {
|
||||
const categoryQuery = appStore.map(({ categories }) => ({
|
||||
categories: categories || [],
|
||||
}));
|
||||
const categories = categoryQuery.reduce((c, app) => {
|
||||
for (const category of app.categories) {
|
||||
c[category] = c[category] ? c[category] + 1 : 1;
|
||||
}
|
||||
return c;
|
||||
}, {} as Record<string, number>);
|
||||
const categories = categoryQuery.reduce(
|
||||
(c, app) => {
|
||||
for (const category of app.categories) {
|
||||
c[category] = c[category] ? c[category] + 1 : 1;
|
||||
}
|
||||
return c;
|
||||
},
|
||||
{} as Record<string, number>
|
||||
);
|
||||
|
||||
const props = {
|
||||
categories: Object.entries(categories)
|
||||
|
||||
@@ -93,8 +93,7 @@ function Field({
|
||||
}
|
||||
: null
|
||||
}
|
||||
deleteField={router ? null : deleteField}
|
||||
>
|
||||
deleteField={router ? null : deleteField}>
|
||||
<FormCardBody>
|
||||
<div className="mb-3 w-full">
|
||||
<TextField
|
||||
@@ -114,17 +113,12 @@ function Field({
|
||||
hookForm.setValue(`${hookFieldNamespace}.label`, newLabel, {
|
||||
shouldDirty: true,
|
||||
});
|
||||
const currentIdentifier = hookForm.getValues(
|
||||
`${hookFieldNamespace}.identifier`
|
||||
);
|
||||
const currentIdentifier = hookForm.getValues(`${hookFieldNamespace}.identifier`);
|
||||
// Only auto-update identifier if it was auto-generated from the previous label
|
||||
// This preserves manual identifier changes
|
||||
const isIdentifierGeneratedFromPreviousLabel =
|
||||
currentIdentifier === getFieldIdentifier(previousLabel).toLowerCase();
|
||||
if (
|
||||
!currentIdentifier ||
|
||||
isIdentifierGeneratedFromPreviousLabel
|
||||
) {
|
||||
if (!currentIdentifier || isIdentifierGeneratedFromPreviousLabel) {
|
||||
hookForm.setValue(
|
||||
`${hookFieldNamespace}.identifier`,
|
||||
getFieldIdentifier(newLabel).toLowerCase(),
|
||||
@@ -142,19 +136,11 @@ function Field({
|
||||
name={`${hookFieldNamespace}.identifier`}
|
||||
required
|
||||
placeholder={t("identifies_name_field")}
|
||||
value={
|
||||
identifier ||
|
||||
routerField?.identifier ||
|
||||
label ||
|
||||
routerField?.label ||
|
||||
""
|
||||
}
|
||||
value={identifier || routerField?.identifier || label || routerField?.label || ""}
|
||||
onChange={(e) => {
|
||||
hookForm.setValue(
|
||||
`${hookFieldNamespace}.identifier`,
|
||||
e.target.value.toLowerCase(),
|
||||
{ shouldDirty: true }
|
||||
);
|
||||
hookForm.setValue(`${hookFieldNamespace}.identifier`, e.target.value.toLowerCase(), {
|
||||
shouldDirty: true,
|
||||
});
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
@@ -164,9 +150,7 @@ function Field({
|
||||
control={hookForm.control}
|
||||
defaultValue={routerField?.type}
|
||||
render={({ field: { value, onChange } }) => {
|
||||
const defaultValue = FieldTypes.find(
|
||||
(fieldType) => fieldType.value === value
|
||||
);
|
||||
const defaultValue = FieldTypes.find((fieldType) => fieldType.value === value);
|
||||
if (disableTypeChange) {
|
||||
return (
|
||||
<div className="data-testid-field-type">
|
||||
@@ -179,15 +163,9 @@ function Field({
|
||||
className={classNames(
|
||||
"h-8 w-full justify-between text-left text-sm",
|
||||
!!router && "bg-subtle cursor-not-allowed"
|
||||
)}
|
||||
>
|
||||
<span className="text-default">
|
||||
{defaultValue?.label || "Select field type"}
|
||||
</span>
|
||||
<Icon
|
||||
name="chevron-down"
|
||||
className="text-default h-4 w-4"
|
||||
/>
|
||||
)}>
|
||||
<span className="text-default">{defaultValue?.label || "Select field type"}</span>
|
||||
<Icon name="chevron-down" className="text-default h-4 w-4" />
|
||||
</Button>
|
||||
</Tooltip>
|
||||
</div>
|
||||
@@ -304,9 +282,7 @@ const FormEdit = ({
|
||||
<div className="w-full py-4 lg:py-8">
|
||||
<div ref={animationRef} className="flex w-full flex-col rounded-md">
|
||||
{hookFormFields.map((field, key) => {
|
||||
const existingField = Boolean(
|
||||
(form.fields || []).find((f) => f.id === field.id)
|
||||
);
|
||||
const existingField = Boolean((form.fields || []).find((f) => f.id === field.id));
|
||||
const hasFormResponses = (form._count?.responses ?? 0) > 0;
|
||||
return (
|
||||
<Field
|
||||
@@ -343,13 +319,7 @@ const FormEdit = ({
|
||||
</div>
|
||||
{hookFormFields.length ? (
|
||||
<div className={classNames("flex")}>
|
||||
<Button
|
||||
data-testid="add-field"
|
||||
type="button"
|
||||
StartIcon="plus"
|
||||
color="secondary"
|
||||
onClick={addField}
|
||||
>
|
||||
<Button data-testid="add-field" type="button" StartIcon="plus" color="secondary" onClick={addField}>
|
||||
Add question
|
||||
</Button>
|
||||
</div>
|
||||
@@ -389,12 +359,7 @@ const FormEdit = ({
|
||||
Fields are the form fields that the booker would see.
|
||||
</p>
|
||||
</div>
|
||||
<Button
|
||||
data-testid="add-field"
|
||||
onClick={addField}
|
||||
StartIcon="plus"
|
||||
className="mt-6"
|
||||
>
|
||||
<Button data-testid="add-field" onClick={addField} StartIcon="plus" className="mt-6">
|
||||
Add question
|
||||
</Button>
|
||||
</div>
|
||||
@@ -414,9 +379,7 @@ export default function FormEditPage({
|
||||
{...props}
|
||||
appUrl={appUrl}
|
||||
permissions={permissions}
|
||||
Page={({ hookForm, form }) => (
|
||||
<FormEdit appUrl={appUrl} hookForm={hookForm} form={form} />
|
||||
)}
|
||||
Page={({ hookForm, form }) => <FormEdit appUrl={appUrl} hookForm={hookForm} form={form} />}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
|
||||
+13
-13
@@ -88,8 +88,8 @@ function Page({ form }: { form: RoutingFormWithResponseCount }) {
|
||||
|
||||
setSelectedCredential(
|
||||
credentialOptions
|
||||
? credentialOptions.find((option) => option.value === salesforceAction?.credentialId) ??
|
||||
selectedCredential
|
||||
? (credentialOptions.find((option) => option.value === salesforceAction?.credentialId) ??
|
||||
selectedCredential)
|
||||
: selectedCredential
|
||||
);
|
||||
}
|
||||
@@ -128,17 +128,17 @@ function Page({ form }: { form: RoutingFormWithResponseCount }) {
|
||||
<div className="bg-default mt-2 rounded-xl px-2 py-2">
|
||||
<Label>Credential to use</Label>
|
||||
<Select
|
||||
size="sm"
|
||||
options={credentialOptions}
|
||||
value={selectedCredential}
|
||||
onChange={(option) => {
|
||||
if (!option) {
|
||||
return;
|
||||
}
|
||||
setSelectedCredential(option);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
size="sm"
|
||||
options={credentialOptions}
|
||||
value={selectedCredential}
|
||||
onChange={(option) => {
|
||||
if (!option) {
|
||||
return;
|
||||
}
|
||||
setSelectedCredential(option);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
|
||||
@@ -398,7 +398,7 @@ const Route = ({
|
||||
const [customEventTypeSlug, setCustomEventTypeSlug] = useState<string>(() => {
|
||||
const isCustom =
|
||||
!isRouter(route) && !eventOptions.find((eventOption) => eventOption.value === route.action.value);
|
||||
return isCustom && !isRouter(route) ? route.action.value.split("/").pop() ?? "" : "";
|
||||
return isCustom && !isRouter(route) ? (route.action.value.split("/").pop() ?? "") : "";
|
||||
});
|
||||
|
||||
useEnsureEventTypeIdInRedirectUrlAction({
|
||||
@@ -952,7 +952,7 @@ const buildState = <
|
||||
| {
|
||||
queryValue: AttributesQueryValue;
|
||||
config: AttributesQueryBuilderConfigWithRaqbFields;
|
||||
}
|
||||
},
|
||||
>({
|
||||
queryValue,
|
||||
config,
|
||||
|
||||
@@ -10,7 +10,7 @@ import { buildLegacyCtx } from "@lib/buildLegacyCtx";
|
||||
import { routingFormsComponents } from "./app-routing.client-config";
|
||||
|
||||
const normalizePages = (pages: string[] | string | undefined) => {
|
||||
const normalizedPages = Array.isArray(pages) ? pages : pages?.split("/") ?? [];
|
||||
const normalizedPages = Array.isArray(pages) ? pages : (pages?.split("/") ?? []);
|
||||
return normalizedPages[0];
|
||||
};
|
||||
|
||||
|
||||
@@ -42,10 +42,10 @@ const ServerPage = async ({ searchParams }: PageProps) => {
|
||||
provider === IdentityProvider.GOOGLE
|
||||
? "Google"
|
||||
: provider === IdentityProvider.CAL
|
||||
? "Email and Password"
|
||||
: provider === IdentityProvider.SAML
|
||||
? "SAML (like Okta)"
|
||||
: "your original login method";
|
||||
? "Email and Password"
|
||||
: provider === IdentityProvider.SAML
|
||||
? "SAML (like Okta)"
|
||||
: "your original login method";
|
||||
return t("account_managed_by_identity_provider_error", { provider: providerName });
|
||||
} else if (error === "saml-idp-not-authoritative") {
|
||||
return t("saml_idp_not_authoritative_error");
|
||||
|
||||
@@ -27,7 +27,9 @@ const ServerPage = async () => {
|
||||
|
||||
// If user has any team membership (pending or accepted), redirect them directly to personal onboarding
|
||||
// This handles the case where users sign up with an invite token (membership is auto-accepted)
|
||||
const hasTeamMembership = await MembershipRepository.hasAnyTeamMembershipByUserId({ userId: session.user.id });
|
||||
const hasTeamMembership = await MembershipRepository.hasAnyTeamMembershipByUserId({
|
||||
userId: session.user.id,
|
||||
});
|
||||
if (hasTeamMembership) {
|
||||
return redirect("/onboarding/personal/settings");
|
||||
}
|
||||
|
||||
@@ -32,4 +32,3 @@ const ServerPage = async () => {
|
||||
};
|
||||
|
||||
export default ServerPage;
|
||||
|
||||
@@ -32,4 +32,3 @@ const ServerPage = async () => {
|
||||
};
|
||||
|
||||
export default ServerPage;
|
||||
|
||||
@@ -31,7 +31,9 @@ const ServerPage = async (props: { searchParams: Promise<{ fromTeamOnboarding?:
|
||||
const searchParams = await props.searchParams;
|
||||
const fromTeamOnboarding = searchParams?.fromTeamOnboarding === "true";
|
||||
|
||||
return <PersonalSettingsView userEmail={userEmail} userName={userName} fromTeamOnboarding={fromTeamOnboarding} />;
|
||||
return (
|
||||
<PersonalSettingsView userEmail={userEmail} userName={userName} fromTeamOnboarding={fromTeamOnboarding} />
|
||||
);
|
||||
};
|
||||
|
||||
export default ServerPage;
|
||||
@@ -32,4 +32,3 @@ const ServerPage = async () => {
|
||||
};
|
||||
|
||||
export default ServerPage;
|
||||
|
||||
+1
-4
@@ -42,10 +42,7 @@ const Page = async ({ params }: { params: Params }) => {
|
||||
const org = await organizationRepository.adminFindById({ id: input.data.id });
|
||||
const t = await getTranslate();
|
||||
return (
|
||||
<SettingsHeader
|
||||
title={`${t("editing_org")}: ${org.name}`}
|
||||
description={t("admin_orgs_edit_description")}
|
||||
>
|
||||
<SettingsHeader title={`${t("editing_org")}: ${org.name}`} description={t("admin_orgs_edit_description")}>
|
||||
<LicenseRequired>
|
||||
<OrgForm org={org} />
|
||||
</LicenseRequired>
|
||||
|
||||
+1
-4
@@ -17,10 +17,7 @@ export const generateMetadata = async () =>
|
||||
const Page = async () => {
|
||||
const t = await getTranslate();
|
||||
return (
|
||||
<SettingsHeader
|
||||
title={t("organizations")}
|
||||
description={t("orgs_page_description")}
|
||||
>
|
||||
<SettingsHeader title={t("organizations")} description={t("orgs_page_description")}>
|
||||
<LicenseRequired>
|
||||
<AdminOrgTable />
|
||||
</LicenseRequired>
|
||||
|
||||
+1
-4
@@ -16,10 +16,7 @@ export const generateMetadata = async () =>
|
||||
const Page = async () => {
|
||||
const t = await getTranslate();
|
||||
return (
|
||||
<SettingsHeader
|
||||
title={t("workspace_platforms")}
|
||||
description={t("workspace_platforms_description")}
|
||||
>
|
||||
<SettingsHeader title={t("workspace_platforms")} description={t("workspace_platforms_description")}>
|
||||
<LicenseRequired>
|
||||
<WorkspacePlatformsPage />
|
||||
</LicenseRequired>
|
||||
|
||||
+1
-6
@@ -1052,12 +1052,7 @@ type SettingsLayoutProps = {
|
||||
permissions?: SettingsPermissions;
|
||||
} & ComponentProps<typeof Shell>;
|
||||
|
||||
function SettingsLayoutAppDirClient({
|
||||
children,
|
||||
teamFeatures,
|
||||
permissions,
|
||||
...rest
|
||||
}: SettingsLayoutProps) {
|
||||
function SettingsLayoutAppDirClient({ children, teamFeatures, permissions, ...rest }: SettingsLayoutProps) {
|
||||
const pathname = usePathname();
|
||||
const state = useState(false);
|
||||
const [sideContainerOpen, setSideContainerOpen] = state;
|
||||
|
||||
@@ -25,9 +25,7 @@ const Page = async () => {
|
||||
redirect("/auth/login?callbackUrl=/settings/developer/oauth");
|
||||
}
|
||||
|
||||
return (
|
||||
<OAuthClientsView />
|
||||
);
|
||||
return <OAuthClientsView />;
|
||||
};
|
||||
|
||||
export default Page;
|
||||
+4
-4
@@ -54,10 +54,10 @@ export function AdvancedPermissionGroup({
|
||||
const allPermissions = isAllResources
|
||||
? ["*.*"]
|
||||
: resourceConfig
|
||||
? Object.entries(resourceConfig)
|
||||
.filter(([action]) => action !== INTERNAL_DATAACCESS_KEY)
|
||||
.map(([action]) => `${resource}.${action}`)
|
||||
: [];
|
||||
? Object.entries(resourceConfig)
|
||||
.filter(([action]) => action !== INTERNAL_DATAACCESS_KEY)
|
||||
.map(([action]) => `${resource}.${action}`)
|
||||
: [];
|
||||
|
||||
// Check if all permissions for this resource are selected
|
||||
const isAllSelected = isAllResources
|
||||
|
||||
+3
-3
@@ -27,9 +27,9 @@ const Page = async () => {
|
||||
const organizationRepository = getOrganizationRepository();
|
||||
const otherTeams = organizationId
|
||||
? await organizationRepository.findTeamsInOrgIamNotPartOf({
|
||||
userId: session?.user.id,
|
||||
parentId: organizationId,
|
||||
})
|
||||
userId: session?.user.id,
|
||||
parentId: organizationId,
|
||||
})
|
||||
: [];
|
||||
|
||||
return (
|
||||
|
||||
+1
-3
@@ -1,8 +1,6 @@
|
||||
import { _generateMetadata, getTranslate } from "app/_utils";
|
||||
|
||||
import LegacyPage, {
|
||||
TeamMembersCTA,
|
||||
} from "~/ee/organizations/other-team-members-view";
|
||||
import LegacyPage, { TeamMembersCTA } from "~/ee/organizations/other-team-members-view";
|
||||
import SettingsHeader from "@calcom/features/settings/appDir/SettingsHeader";
|
||||
|
||||
import { validateUserHasOrg } from "../../../../actions/validateUserHasOrg";
|
||||
|
||||
@@ -23,9 +23,7 @@ const getData = withAppDirSsr<inferSSRProps<typeof getServerSideProps>>(getServe
|
||||
|
||||
const ServerPage = async ({ params, searchParams }: PageProps) => {
|
||||
await getData(buildLegacyCtx(await headers(), await cookies(), await params, await searchParams));
|
||||
return (
|
||||
<SettingsNewView />
|
||||
);
|
||||
return <SettingsNewView />;
|
||||
};
|
||||
|
||||
export default ServerPage;
|
||||
@@ -8,13 +8,7 @@ interface GeoContextValue {
|
||||
|
||||
const GeoContext = createContext<GeoContextValue | undefined>(undefined);
|
||||
|
||||
export function GeoProvider({
|
||||
country,
|
||||
children,
|
||||
}: {
|
||||
country: string;
|
||||
children: React.ReactNode;
|
||||
}) {
|
||||
export function GeoProvider({ country, children }: { country: string; children: React.ReactNode }) {
|
||||
return <GeoContext.Provider value={{ country }}>{children}</GeoContext.Provider>;
|
||||
}
|
||||
|
||||
|
||||
@@ -35,8 +35,8 @@ const url =
|
||||
typeof window !== "undefined"
|
||||
? "/api/trpc"
|
||||
: process.env.VERCEL_URL
|
||||
? `https://${process.env.VERCEL_URL}/api/trpc`
|
||||
: `${process.env.NEXT_PUBLIC_WEBAPP_URL}/api/trpc`;
|
||||
? `https://${process.env.VERCEL_URL}/api/trpc`
|
||||
: `${process.env.NEXT_PUBLIC_WEBAPP_URL}/api/trpc`;
|
||||
|
||||
export const trpcClient = trpc.createClient({
|
||||
links: [
|
||||
|
||||
@@ -9,9 +9,8 @@ import { ErrorWithCode } from "@calcom/lib/errors";
|
||||
import { getHttpStatusCode } from "@calcom/lib/server/getServerErrorFromUnknown";
|
||||
|
||||
async function handler(req: NextRequest) {
|
||||
const { code, client_id, client_secret, grant_type, redirect_uri, code_verifier } = await parseUrlFormData(
|
||||
req
|
||||
);
|
||||
const { code, client_id, client_secret, grant_type, redirect_uri, code_verifier } =
|
||||
await parseUrlFormData(req);
|
||||
|
||||
if (!process.env.CALENDSO_ENCRYPTION_KEY) {
|
||||
return NextResponse.json({ message: OAUTH_ERROR_REASONS["encryption_key_missing"] }, { status: 500 });
|
||||
|
||||
@@ -27,19 +27,27 @@ type InnerHandler = (body: Record<string, string>, status: UsernameStatus) => Pr
|
||||
var mockCapturedHandler: InnerHandler | null;
|
||||
|
||||
vi.mock("next/server", async () => {
|
||||
const { createNextServerMock } = await import("@calcom/features/auth/signup/handlers/__tests__/mocks/next.mocks");
|
||||
const { createNextServerMock } = await import(
|
||||
"@calcom/features/auth/signup/handlers/__tests__/mocks/next.mocks"
|
||||
);
|
||||
return createNextServerMock();
|
||||
});
|
||||
vi.mock("next/headers", async () => {
|
||||
const { createNextHeadersMock } = await import("@calcom/features/auth/signup/handlers/__tests__/mocks/next.mocks");
|
||||
const { createNextHeadersMock } = await import(
|
||||
"@calcom/features/auth/signup/handlers/__tests__/mocks/next.mocks"
|
||||
);
|
||||
return createNextHeadersMock();
|
||||
});
|
||||
vi.mock("@calcom/prisma", async () => {
|
||||
const { createPrismaMock } = await import("@calcom/features/auth/signup/handlers/__tests__/mocks/prisma.mocks");
|
||||
const { createPrismaMock } = await import(
|
||||
"@calcom/features/auth/signup/handlers/__tests__/mocks/prisma.mocks"
|
||||
);
|
||||
return createPrismaMock();
|
||||
});
|
||||
vi.mock("@calcom/prisma/client", async () => {
|
||||
const { createPrismaMock } = await import("@calcom/features/auth/signup/handlers/__tests__/mocks/prisma.mocks");
|
||||
const { createPrismaMock } = await import(
|
||||
"@calcom/features/auth/signup/handlers/__tests__/mocks/prisma.mocks"
|
||||
);
|
||||
return createPrismaMock();
|
||||
});
|
||||
vi.mock("@calcom/lib/logger", () => ({
|
||||
@@ -49,9 +57,13 @@ vi.mock("@calcom/lib/auth/hashPassword", () => ({ hashPassword: vi.fn().mockReso
|
||||
vi.mock("@calcom/lib/constants", () => ({ WEBAPP_URL: "http://localhost:3000" }));
|
||||
vi.mock("@calcom/lib/tracking", () => ({ getTrackingFromCookies: vi.fn().mockReturnValue({}) }));
|
||||
vi.mock("@calcom/app-store/stripepayment/lib/utils", () => ({ getPremiumMonthlyPlanPriceId: vi.fn() }));
|
||||
vi.mock("@calcom/features/auth/lib/getLocaleFromRequest", () => ({ getLocaleFromRequest: vi.fn().mockResolvedValue("en") }));
|
||||
vi.mock("@calcom/features/auth/lib/getLocaleFromRequest", () => ({
|
||||
getLocaleFromRequest: vi.fn().mockResolvedValue("en"),
|
||||
}));
|
||||
vi.mock("@calcom/features/auth/lib/verifyEmail", () => ({ sendEmailVerification: vi.fn() }));
|
||||
vi.mock("@calcom/features/auth/signup/utils/createOrUpdateMemberships", () => ({ createOrUpdateMemberships: vi.fn() }));
|
||||
vi.mock("@calcom/features/auth/signup/utils/createOrUpdateMemberships", () => ({
|
||||
createOrUpdateMemberships: vi.fn(),
|
||||
}));
|
||||
vi.mock("@calcom/features/auth/signup/utils/prefillAvatar", () => ({ prefillAvatar: vi.fn() }));
|
||||
vi.mock("@calcom/features/auth/signup/utils/validateUsername", () => ({
|
||||
validateAndGetCorrectedUsernameAndEmail: vi.fn().mockResolvedValue({ isValid: true, username: "testuser" }),
|
||||
@@ -70,7 +82,8 @@ vi.mock("@calcom/features/auth/signup/utils/organization", () => ({ joinAnyChild
|
||||
vi.mock("@calcom/features/auth/signup/utils/token", () => ({
|
||||
findTokenByToken: (...args: unknown[]) => mockFindTokenByToken(...args),
|
||||
throwIfTokenExpired: vi.fn(),
|
||||
validateAndGetCorrectedUsernameForTeam: (...args: unknown[]) => mockValidateAndGetCorrectedUsernameForTeam(...args),
|
||||
validateAndGetCorrectedUsernameForTeam: (...args: unknown[]) =>
|
||||
mockValidateAndGetCorrectedUsernameForTeam(...args),
|
||||
}));
|
||||
|
||||
// Capture inner handler from usernameHandler wrapper
|
||||
|
||||
@@ -15,15 +15,21 @@ const mockFindTokenByToken: Mock = vi.fn();
|
||||
const mockValidateAndGetCorrectedUsernameForTeam: Mock = vi.fn();
|
||||
|
||||
vi.mock("next/server", async () => {
|
||||
const { createNextServerMock } = await import("@calcom/features/auth/signup/handlers/__tests__/mocks/next.mocks");
|
||||
const { createNextServerMock } = await import(
|
||||
"@calcom/features/auth/signup/handlers/__tests__/mocks/next.mocks"
|
||||
);
|
||||
return createNextServerMock();
|
||||
});
|
||||
vi.mock("@calcom/prisma", async () => {
|
||||
const { createPrismaMock } = await import("@calcom/features/auth/signup/handlers/__tests__/mocks/prisma.mocks");
|
||||
const { createPrismaMock } = await import(
|
||||
"@calcom/features/auth/signup/handlers/__tests__/mocks/prisma.mocks"
|
||||
);
|
||||
return createPrismaMock();
|
||||
});
|
||||
vi.mock("@calcom/prisma/client", async () => {
|
||||
const { createPrismaMock } = await import("@calcom/features/auth/signup/handlers/__tests__/mocks/prisma.mocks");
|
||||
const { createPrismaMock } = await import(
|
||||
"@calcom/features/auth/signup/handlers/__tests__/mocks/prisma.mocks"
|
||||
);
|
||||
return createPrismaMock();
|
||||
});
|
||||
vi.mock("@calcom/lib/logger", () => ({
|
||||
@@ -32,9 +38,13 @@ vi.mock("@calcom/lib/logger", () => ({
|
||||
vi.mock("@calcom/lib/auth/hashPassword", () => ({ hashPassword: vi.fn().mockResolvedValue("hashed") }));
|
||||
vi.mock("@calcom/lib/slugify", () => ({ default: vi.fn((s: string) => s.toLowerCase()) }));
|
||||
vi.mock("@calcom/lib/constants", () => ({ IS_PREMIUM_USERNAME_ENABLED: false }));
|
||||
vi.mock("@calcom/lib/server/username", () => ({ isUsernameReservedDueToMigration: vi.fn().mockResolvedValue(false) }));
|
||||
vi.mock("@calcom/lib/server/username", () => ({
|
||||
isUsernameReservedDueToMigration: vi.fn().mockResolvedValue(false),
|
||||
}));
|
||||
vi.mock("@calcom/features/auth/lib/verifyEmail", () => ({ sendEmailVerification: vi.fn() }));
|
||||
vi.mock("@calcom/features/auth/signup/utils/createOrUpdateMemberships", () => ({ createOrUpdateMemberships: vi.fn() }));
|
||||
vi.mock("@calcom/features/auth/signup/utils/createOrUpdateMemberships", () => ({
|
||||
createOrUpdateMemberships: vi.fn(),
|
||||
}));
|
||||
vi.mock("@calcom/features/auth/signup/utils/validateUsername", () => ({
|
||||
validateAndGetCorrectedUsernameAndEmail: vi.fn().mockResolvedValue({ isValid: true, username: "testuser" }),
|
||||
}));
|
||||
@@ -43,7 +53,8 @@ vi.mock("@calcom/features/auth/signup/utils/prefillAvatar", () => ({ prefillAvat
|
||||
vi.mock("@calcom/features/auth/signup/utils/token", () => ({
|
||||
findTokenByToken: (...args: unknown[]) => mockFindTokenByToken(...args),
|
||||
throwIfTokenExpired: vi.fn(),
|
||||
validateAndGetCorrectedUsernameForTeam: (...args: unknown[]) => mockValidateAndGetCorrectedUsernameForTeam(...args),
|
||||
validateAndGetCorrectedUsernameForTeam: (...args: unknown[]) =>
|
||||
mockValidateAndGetCorrectedUsernameForTeam(...args),
|
||||
}));
|
||||
|
||||
// Import after mocks
|
||||
|
||||
@@ -100,7 +100,7 @@ export default async function handler(body: Record<string, string>) {
|
||||
}
|
||||
}
|
||||
|
||||
const organizationId = team.isOrganization ? team.id : team.parent?.id ?? null;
|
||||
const organizationId = team.isOrganization ? team.id : (team.parent?.id ?? null);
|
||||
|
||||
const existingUserByUsername = await prisma.user.findFirst({
|
||||
where: {
|
||||
@@ -200,10 +200,7 @@ export default async function handler(body: Record<string, string>) {
|
||||
if (isPrismaError(error) && error.code === "P2002") {
|
||||
const target = String(error.meta?.target ?? "");
|
||||
if (target.includes("email") || target.includes("username")) {
|
||||
return NextResponse.json(
|
||||
{ message: SIGNUP_ERROR_CODES.USER_ALREADY_EXISTS },
|
||||
{ status: 409 }
|
||||
);
|
||||
return NextResponse.json({ message: SIGNUP_ERROR_CODES.USER_ALREADY_EXISTS }, { status: 409 });
|
||||
}
|
||||
}
|
||||
throw error;
|
||||
|
||||
@@ -91,8 +91,7 @@ async function deleteHandler(req: NextRequest) {
|
||||
const user = await authMiddleware();
|
||||
const searchParams = Object.fromEntries(req.nextUrl.searchParams.entries());
|
||||
|
||||
const { integration, externalId, eventTypeId } =
|
||||
selectedCalendarSelectSchema.parse(searchParams);
|
||||
const { integration, externalId, eventTypeId } = selectedCalendarSelectSchema.parse(searchParams);
|
||||
|
||||
await SelectedCalendarRepository.delete({
|
||||
where: {
|
||||
|
||||
@@ -71,20 +71,20 @@ export async function handleCreateCredentials() {
|
||||
`Creating credentials for ${toProcessMembers.length} members out of ${delegatedMembers.length} delegated members in organization ${organization.id}`
|
||||
);
|
||||
|
||||
const credentialCreationPromises = toProcessMembers.map(async (member) => {
|
||||
try {
|
||||
const credentialData = buildCredentialCreateData({
|
||||
type: "google_calendar",
|
||||
key: {
|
||||
// The in-memory credential that we create for Delegation Credential has access_token as "NOOP_UNUSED_DELEGATION_TOKEN. This is to mark it is in DB, in case we need to identify that.
|
||||
access_token: "NOOP_UNUSED_DELEGATION_TOKEN_DB",
|
||||
},
|
||||
userId: member.userId,
|
||||
appId: "google-calendar",
|
||||
delegationCredentialId: delegationCredential.id,
|
||||
});
|
||||
await CredentialRepository.create(credentialData);
|
||||
log.info(`Created credential for member ${member.userId}`);
|
||||
const credentialCreationPromises = toProcessMembers.map(async (member) => {
|
||||
try {
|
||||
const credentialData = buildCredentialCreateData({
|
||||
type: "google_calendar",
|
||||
key: {
|
||||
// The in-memory credential that we create for Delegation Credential has access_token as "NOOP_UNUSED_DELEGATION_TOKEN. This is to mark it is in DB, in case we need to identify that.
|
||||
access_token: "NOOP_UNUSED_DELEGATION_TOKEN_DB",
|
||||
},
|
||||
userId: member.userId,
|
||||
appId: "google-calendar",
|
||||
delegationCredentialId: delegationCredential.id,
|
||||
});
|
||||
await CredentialRepository.create(credentialData);
|
||||
log.info(`Created credential for member ${member.userId}`);
|
||||
} catch (error) {
|
||||
log.error(`Error creating credential for member ${member.userId}:`, safeStringify(error));
|
||||
throw error;
|
||||
|
||||
@@ -12,12 +12,16 @@ const getPrimaryCalendarMock = vi.fn();
|
||||
vi.mock("@calcom/app-store/googlecalendar/lib/CalendarService", () => {
|
||||
return {
|
||||
__esModule: true,
|
||||
createGoogleCalendarServiceWithGoogleType: vi.fn().mockImplementation(function() { return {
|
||||
getPrimaryCalendar: getPrimaryCalendarMock,
|
||||
}; }),
|
||||
default: vi.fn().mockImplementation(function() { return {
|
||||
getPrimaryCalendar: getPrimaryCalendarMock,
|
||||
}; }),
|
||||
createGoogleCalendarServiceWithGoogleType: vi.fn().mockImplementation(function () {
|
||||
return {
|
||||
getPrimaryCalendar: getPrimaryCalendarMock,
|
||||
};
|
||||
}),
|
||||
default: vi.fn().mockImplementation(function () {
|
||||
return {
|
||||
getPrimaryCalendar: getPrimaryCalendarMock,
|
||||
};
|
||||
}),
|
||||
};
|
||||
});
|
||||
|
||||
|
||||
@@ -267,10 +267,13 @@ export async function handleCreateSelectedCalendars() {
|
||||
}
|
||||
|
||||
// Groups delegationUserCredentials by delegationCredentialId
|
||||
const groupedDelegationUserCredentials = allDelegationUserCredentials.reduce((acc, curr) => {
|
||||
acc[curr.delegationCredentialId] = [...(acc[curr.delegationCredentialId] || []), curr];
|
||||
return acc;
|
||||
}, {} as Record<string, typeof allDelegationUserCredentials>);
|
||||
const groupedDelegationUserCredentials = allDelegationUserCredentials.reduce(
|
||||
(acc, curr) => {
|
||||
acc[curr.delegationCredentialId] = [...(acc[curr.delegationCredentialId] || []), curr];
|
||||
return acc;
|
||||
},
|
||||
{} as Record<string, typeof allDelegationUserCredentials>
|
||||
);
|
||||
|
||||
let totalSuccess = 0;
|
||||
let totalFailures = 0;
|
||||
@@ -279,9 +282,8 @@ export async function handleCreateSelectedCalendars() {
|
||||
groupedDelegationUserCredentials
|
||||
)) {
|
||||
log.info(`Processing delegation user credentials for delegationCredentialId: ${delegationCredentialId}`);
|
||||
const delegationUserCredentialsToProcess = await getDelegationUserCredentialsToProcess(
|
||||
delegationUserCredentials
|
||||
);
|
||||
const delegationUserCredentialsToProcess =
|
||||
await getDelegationUserCredentialsToProcess(delegationUserCredentials);
|
||||
log.info(
|
||||
`Found ${delegationUserCredentialsToProcess.length} delegationUserCredentials to process for delegationCredentialId: ${delegationCredentialId}`
|
||||
);
|
||||
|
||||
@@ -47,9 +47,7 @@ describe("defaultResponderForAppDir", () => {
|
||||
});
|
||||
|
||||
it("should respond with status code 409 for NoAvailableUsersFound", async () => {
|
||||
const f = vi
|
||||
.fn()
|
||||
.mockRejectedValue(new Error(ErrorCode.NoAvailableUsersFound));
|
||||
const f = vi.fn().mockRejectedValue(new Error(ErrorCode.NoAvailableUsersFound));
|
||||
const req = { method: "GET", url: "/api/test" } as unknown as NextRequest;
|
||||
const params = Promise.resolve<Params>({});
|
||||
|
||||
@@ -65,9 +63,7 @@ describe("defaultResponderForAppDir", () => {
|
||||
});
|
||||
|
||||
it("should respond with a 429 status code for rate limit errors", async () => {
|
||||
const f = vi
|
||||
.fn()
|
||||
.mockRejectedValue(new TRPCError({ code: "TOO_MANY_REQUESTS" }));
|
||||
const f = vi.fn().mockRejectedValue(new TRPCError({ code: "TOO_MANY_REQUESTS" }));
|
||||
const req = { method: "POST", url: "/api/test" } as unknown as NextRequest;
|
||||
const params = Promise.resolve<Params>({});
|
||||
|
||||
|
||||
@@ -4,4 +4,4 @@ import getIP from "@calcom/lib/getIP";
|
||||
export async function GET(req: Request) {
|
||||
const requestorIp = getIP(req);
|
||||
return NextResponse.json({ ip: requestorIp });
|
||||
}
|
||||
}
|
||||
@@ -6,14 +6,16 @@ import { getOGImageVersion } from "@calcom/lib/OgImages";
|
||||
import { GET } from "../route";
|
||||
|
||||
vi.mock("next/og", () => ({
|
||||
ImageResponse: vi.fn().mockImplementation(function() { return {
|
||||
body: new ReadableStream({
|
||||
start(controller) {
|
||||
controller.enqueue(new Uint8Array([1, 2, 3, 4]));
|
||||
controller.close();
|
||||
},
|
||||
}),
|
||||
}; }),
|
||||
ImageResponse: vi.fn().mockImplementation(function () {
|
||||
return {
|
||||
body: new ReadableStream({
|
||||
start(controller) {
|
||||
controller.enqueue(new Uint8Array([1, 2, 3, 4]));
|
||||
controller.close();
|
||||
},
|
||||
}),
|
||||
};
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock("@calcom/lib/OgImages", async (importOriginal) => {
|
||||
|
||||
@@ -77,13 +77,11 @@ async function handler(req: NextRequest) {
|
||||
|
||||
const etag = await getOGImageVersion("meeting");
|
||||
const img = new ImageResponse(
|
||||
(
|
||||
<Meeting
|
||||
title={title}
|
||||
profile={{ name: meetingProfileName, image: meetingImage }}
|
||||
users={names.map((name, index) => ({ name, username: usernames[index] }))}
|
||||
/>
|
||||
),
|
||||
<Meeting
|
||||
title={title}
|
||||
profile={{ name: meetingProfileName, image: meetingImage }}
|
||||
users={names.map((name, index) => ({ name, username: usernames[index] }))}
|
||||
/>,
|
||||
ogConfig
|
||||
);
|
||||
|
||||
|
||||
@@ -76,10 +76,12 @@ const mockSendCreditBalanceLimitReachedEmails = vi.fn();
|
||||
const mockSendCreditBalanceLowWarningEmails = vi.fn();
|
||||
|
||||
vi.mock("@calcom/features/ee/billing/credit-service", () => ({
|
||||
CreditService: vi.fn().mockImplementation(function() { return {
|
||||
hasAvailableCredits: mockHasAvailableCredits,
|
||||
chargeCredits: mockChargeCredits,
|
||||
}; }),
|
||||
CreditService: vi.fn().mockImplementation(function () {
|
||||
return {
|
||||
hasAvailableCredits: mockHasAvailableCredits,
|
||||
chargeCredits: mockChargeCredits,
|
||||
};
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock("@calcom/emails/email-manager", () => ({
|
||||
@@ -92,15 +94,19 @@ const mockFindByPhoneNumber = vi.fn();
|
||||
const mockFindByProviderAgentId = vi.fn();
|
||||
|
||||
vi.mock("@calcom/features/calAIPhone/repositories/PrismaPhoneNumberRepository", () => ({
|
||||
PrismaPhoneNumberRepository: vi.fn().mockImplementation(function() { return {
|
||||
findByPhoneNumber: mockFindByPhoneNumber,
|
||||
}; }),
|
||||
PrismaPhoneNumberRepository: vi.fn().mockImplementation(function () {
|
||||
return {
|
||||
findByPhoneNumber: mockFindByPhoneNumber,
|
||||
};
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock("@calcom/features/calAIPhone/repositories/PrismaAgentRepository", () => ({
|
||||
PrismaAgentRepository: vi.fn().mockImplementation(function() { return {
|
||||
findByProviderAgentId: mockFindByProviderAgentId,
|
||||
}; }),
|
||||
PrismaAgentRepository: vi.fn().mockImplementation(function () {
|
||||
return {
|
||||
findByProviderAgentId: mockFindByProviderAgentId,
|
||||
};
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock("next/server", () => ({
|
||||
|
||||
@@ -12,10 +12,7 @@ import { notFound } from "next/navigation";
|
||||
*/
|
||||
const Page = (): JSX.Element => {
|
||||
// Gate this page to E2E test mode or dev only
|
||||
if (
|
||||
process.env.NEXT_PUBLIC_IS_E2E !== "1" &&
|
||||
process.env.NODE_ENV !== "development"
|
||||
) {
|
||||
if (process.env.NEXT_PUBLIC_IS_E2E !== "1" && process.env.NODE_ENV !== "development") {
|
||||
notFound();
|
||||
}
|
||||
|
||||
|
||||
@@ -41,8 +41,9 @@ function getPageInfo(pathname: string, host: string) {
|
||||
return {
|
||||
username: currentOrgDomain ?? "",
|
||||
pageType: PageType.ORG,
|
||||
url: `${WEBSITE_URL}/signup?callbackUrl=settings/organizations/new%3Fslug%3D${currentOrgDomain?.replace("/", "") ?? ""
|
||||
}`,
|
||||
url: `${WEBSITE_URL}/signup?callbackUrl=settings/organizations/new%3Fslug%3D${
|
||||
currentOrgDomain?.replace("/", "") ?? ""
|
||||
}`,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -162,8 +163,9 @@ export function NotFound({ host }: { host: string }) {
|
||||
<span className="focus:outline-none">
|
||||
<span className="absolute inset-0" aria-hidden="true" />
|
||||
{t("register")}{" "}
|
||||
<strong className="text-green-500">{`${pageType === PageType.TEAM ? `${new URL(WEBSITE_URL).host}/team/` : ""
|
||||
}${username}${pageType === PageType.ORG ? `.${subdomainSuffix()}` : ""}`}</strong>
|
||||
<strong className="text-green-500">{`${
|
||||
pageType === PageType.TEAM ? `${new URL(WEBSITE_URL).host}/team/` : ""
|
||||
}${username}${pageType === PageType.ORG ? `.${subdomainSuffix()}` : ""}`}</strong>
|
||||
</span>
|
||||
</span>
|
||||
</h3>
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
/**
|
||||
* PAGES ROUTER ONLY - Used exclusively by Next.js Pages Router
|
||||
*
|
||||
*
|
||||
* Currently only serves the /router endpoint (routing forms redirect page).
|
||||
* DO NOT add new features here - this file will be deprecated once we remove apps/web/pages.
|
||||
*
|
||||
*
|
||||
* For App Router, use PageWrapperAppDir.tsx instead.
|
||||
*/
|
||||
|
||||
|
||||
@@ -13,7 +13,6 @@ export type PageWrapperProps = Readonly<{
|
||||
}>;
|
||||
|
||||
function PageWrapper(props: PageWrapperProps) {
|
||||
|
||||
// On client side don't let nonce creep into DOM
|
||||
// It also avoids hydration warning that says that Client has the nonce value but server has "" because browser removes nonce attributes before DOM is built
|
||||
// See https://github.com/kentcdodds/nonce-hydration-issues
|
||||
|
||||
@@ -184,7 +184,9 @@ export const AppPage = ({
|
||||
enabled: !!dependencies,
|
||||
});
|
||||
|
||||
const disableInstall = dependencyData.data ? dependencyData.data.some((dependency) => !dependency.installed) : false;
|
||||
const disableInstall = dependencyData.data
|
||||
? dependencyData.data.some((dependency) => !dependency.installed)
|
||||
: false;
|
||||
|
||||
// const disableInstall = requiresGCal && !gCalInstalled.data;
|
||||
|
||||
|
||||
@@ -169,7 +169,11 @@ export function CalendarListContainer({
|
||||
})}
|
||||
description={t(`no_category_apps_description_calendar`)}
|
||||
buttonRaw={
|
||||
<Button EndIcon="external-link" color="secondary" data-testid="connect-calendar-apps" href="/apps/categories/calendar">
|
||||
<Button
|
||||
EndIcon="external-link"
|
||||
color="secondary"
|
||||
data-testid="connect-calendar-apps"
|
||||
href="/apps/categories/calendar">
|
||||
{t("connect_your_first_calendar")}
|
||||
</Button>
|
||||
}
|
||||
|
||||
@@ -23,24 +23,14 @@ export const InstallAppButtonChild = ({
|
||||
// Also, cal.ai(the only paid app at the moment) doesn't support team install either
|
||||
if (paid) {
|
||||
return (
|
||||
<Button
|
||||
data-testid="install-app-button"
|
||||
{...props}
|
||||
disabled={isDisabled}
|
||||
color="primary"
|
||||
size="base">
|
||||
<Button data-testid="install-app-button" {...props} disabled={isDisabled} color="primary" size="base">
|
||||
{paid.trial ? t("start_paid_trial") : t("subscribe")}
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Button
|
||||
data-testid="install-app-button"
|
||||
{...props}
|
||||
disabled={isDisabled}
|
||||
color="primary"
|
||||
size="base">
|
||||
<Button data-testid="install-app-button" {...props} disabled={isDisabled} color="primary" size="base">
|
||||
{multiInstall ? t("install_another") : t("install_app")}
|
||||
</Button>
|
||||
);
|
||||
|
||||
@@ -1,150 +1,150 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import z from "zod";
|
||||
|
||||
import { useBookingSuccessRedirect } from "@calcom/features/bookings/lib/bookingSuccessRedirect";
|
||||
import type { PaymentPageProps } from "@calcom/features/ee/payments/pages/payment";
|
||||
import { useCompatSearchParams } from "@calcom/lib/hooks/useCompatSearchParams";
|
||||
import { useCopy } from "@calcom/lib/hooks/useCopy";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
import { Button } from "@calcom/ui/components/button";
|
||||
import { Spinner } from "@calcom/ui/components/icon";
|
||||
import { showToast } from "@calcom/ui/components/toast";
|
||||
|
||||
interface IPaymentComponentProps {
|
||||
payment: {
|
||||
// Will be parsed on render
|
||||
data: unknown;
|
||||
};
|
||||
paymentPageProps: PaymentPageProps;
|
||||
}
|
||||
|
||||
// Create zod schema for data
|
||||
const PaymentBTCPayDataSchema = z.object({
|
||||
invoice: z.object({ checkoutLink: z.string() }).required(),
|
||||
});
|
||||
|
||||
export const BtcpayPaymentComponent = (props: IPaymentComponentProps) => {
|
||||
const { payment } = props;
|
||||
const { data } = payment;
|
||||
const [iframeLoaded, setIframeLoaded] = useState(false);
|
||||
const { copyToClipboard, isCopied } = useCopy();
|
||||
const wrongUrl = (
|
||||
<>
|
||||
<p className="mt-3 text-center">Couldn't obtain payment URL</p>
|
||||
</>
|
||||
);
|
||||
|
||||
const parsedData = PaymentBTCPayDataSchema.safeParse(data);
|
||||
if (!parsedData.success || !parsedData.data?.invoice?.checkoutLink) return wrongUrl;
|
||||
const checkoutUrl = parsedData.data.invoice.checkoutLink;
|
||||
const handleOpenInNewTab = () => {
|
||||
window.open(checkoutUrl, "_blank", "noopener,noreferrer");
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="mb-4 mt-8 flex h-full w-full flex-col items-center justify-center gap-4">
|
||||
<PaymentChecker {...props.paymentPageProps} />
|
||||
|
||||
{!iframeLoaded && (
|
||||
<div className="flex items-center justify-center">
|
||||
<Spinner className="mr-2 h-5 w-5" />
|
||||
<p>Loading payment page...</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className={`w-full ${iframeLoaded ? "block" : "hidden"}`}>
|
||||
<iframe
|
||||
src={checkoutUrl}
|
||||
title="BTCPay Payment"
|
||||
className="h-[1000px] w-full rounded-md border-0"
|
||||
onLoad={() => setIframeLoaded(true)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-row flex-wrap items-center justify-center gap-4">
|
||||
<Button
|
||||
size="sm"
|
||||
color="secondary"
|
||||
onClick={() => copyToClipboard(checkoutUrl)}
|
||||
className="text-subtle rounded-md"
|
||||
StartIcon={isCopied ? "clipboard-check" : "clipboard"}>
|
||||
Copy Payment Link
|
||||
</Button>
|
||||
|
||||
<Button onClick={handleOpenInNewTab}>Open in New Tab</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
type PaymentCheckerProps = PaymentPageProps;
|
||||
|
||||
function PaymentChecker(props: PaymentCheckerProps) {
|
||||
// TODO: move booking success code to a common lib function
|
||||
// TODO: subscribe rather than polling
|
||||
const searchParams = useCompatSearchParams();
|
||||
const bookingSuccessRedirect = useBookingSuccessRedirect();
|
||||
const utils = trpc.useUtils();
|
||||
const { t } = useLocale();
|
||||
|
||||
useEffect(() => {
|
||||
if (searchParams === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
// use closure to ensure non-nullability
|
||||
const sp = searchParams;
|
||||
const interval = setInterval(() => {
|
||||
(async () => {
|
||||
try {
|
||||
if (props.booking.status === "ACCEPTED") {
|
||||
return;
|
||||
}
|
||||
const { booking: bookingResult } = await utils.viewer.bookings.find.fetch({
|
||||
bookingUid: props.booking.uid,
|
||||
});
|
||||
|
||||
if (bookingResult?.paid) {
|
||||
showToast("Payment successful", "success");
|
||||
|
||||
const params: {
|
||||
uid: string;
|
||||
email: string | null;
|
||||
location: string;
|
||||
} = {
|
||||
uid: props.booking.uid,
|
||||
email: sp.get("email"),
|
||||
location: t("web_conferencing_details_to_follow"),
|
||||
};
|
||||
|
||||
bookingSuccessRedirect({
|
||||
successRedirectUrl: props.eventType.successRedirectUrl,
|
||||
query: params,
|
||||
booking: props.booking,
|
||||
forwardParamsSuccessRedirect: props.eventType.forwardParamsSuccessRedirect,
|
||||
});
|
||||
}
|
||||
} catch (e) {}
|
||||
})();
|
||||
}, 2000);
|
||||
|
||||
return () => clearInterval(interval);
|
||||
}, [
|
||||
bookingSuccessRedirect,
|
||||
props.booking,
|
||||
props.booking.id,
|
||||
props.booking.status,
|
||||
props.eventType.id,
|
||||
props.eventType.successRedirectUrl,
|
||||
props.eventType.forwardParamsSuccessRedirect,
|
||||
props.payment.success,
|
||||
searchParams,
|
||||
t,
|
||||
utils.viewer.bookings,
|
||||
]);
|
||||
|
||||
return null;
|
||||
}
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import z from "zod";
|
||||
|
||||
import { useBookingSuccessRedirect } from "@calcom/features/bookings/lib/bookingSuccessRedirect";
|
||||
import type { PaymentPageProps } from "@calcom/features/ee/payments/pages/payment";
|
||||
import { useCompatSearchParams } from "@calcom/lib/hooks/useCompatSearchParams";
|
||||
import { useCopy } from "@calcom/lib/hooks/useCopy";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
import { Button } from "@calcom/ui/components/button";
|
||||
import { Spinner } from "@calcom/ui/components/icon";
|
||||
import { showToast } from "@calcom/ui/components/toast";
|
||||
|
||||
interface IPaymentComponentProps {
|
||||
payment: {
|
||||
// Will be parsed on render
|
||||
data: unknown;
|
||||
};
|
||||
paymentPageProps: PaymentPageProps;
|
||||
}
|
||||
|
||||
// Create zod schema for data
|
||||
const PaymentBTCPayDataSchema = z.object({
|
||||
invoice: z.object({ checkoutLink: z.string() }).required(),
|
||||
});
|
||||
|
||||
export const BtcpayPaymentComponent = (props: IPaymentComponentProps) => {
|
||||
const { payment } = props;
|
||||
const { data } = payment;
|
||||
const [iframeLoaded, setIframeLoaded] = useState(false);
|
||||
const { copyToClipboard, isCopied } = useCopy();
|
||||
const wrongUrl = (
|
||||
<>
|
||||
<p className="mt-3 text-center">Couldn't obtain payment URL</p>
|
||||
</>
|
||||
);
|
||||
|
||||
const parsedData = PaymentBTCPayDataSchema.safeParse(data);
|
||||
if (!parsedData.success || !parsedData.data?.invoice?.checkoutLink) return wrongUrl;
|
||||
const checkoutUrl = parsedData.data.invoice.checkoutLink;
|
||||
const handleOpenInNewTab = () => {
|
||||
window.open(checkoutUrl, "_blank", "noopener,noreferrer");
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="mb-4 mt-8 flex h-full w-full flex-col items-center justify-center gap-4">
|
||||
<PaymentChecker {...props.paymentPageProps} />
|
||||
|
||||
{!iframeLoaded && (
|
||||
<div className="flex items-center justify-center">
|
||||
<Spinner className="mr-2 h-5 w-5" />
|
||||
<p>Loading payment page...</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className={`w-full ${iframeLoaded ? "block" : "hidden"}`}>
|
||||
<iframe
|
||||
src={checkoutUrl}
|
||||
title="BTCPay Payment"
|
||||
className="h-[1000px] w-full rounded-md border-0"
|
||||
onLoad={() => setIframeLoaded(true)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-row flex-wrap items-center justify-center gap-4">
|
||||
<Button
|
||||
size="sm"
|
||||
color="secondary"
|
||||
onClick={() => copyToClipboard(checkoutUrl)}
|
||||
className="text-subtle rounded-md"
|
||||
StartIcon={isCopied ? "clipboard-check" : "clipboard"}>
|
||||
Copy Payment Link
|
||||
</Button>
|
||||
|
||||
<Button onClick={handleOpenInNewTab}>Open in New Tab</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
type PaymentCheckerProps = PaymentPageProps;
|
||||
|
||||
function PaymentChecker(props: PaymentCheckerProps) {
|
||||
// TODO: move booking success code to a common lib function
|
||||
// TODO: subscribe rather than polling
|
||||
const searchParams = useCompatSearchParams();
|
||||
const bookingSuccessRedirect = useBookingSuccessRedirect();
|
||||
const utils = trpc.useUtils();
|
||||
const { t } = useLocale();
|
||||
|
||||
useEffect(() => {
|
||||
if (searchParams === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
// use closure to ensure non-nullability
|
||||
const sp = searchParams;
|
||||
const interval = setInterval(() => {
|
||||
(async () => {
|
||||
try {
|
||||
if (props.booking.status === "ACCEPTED") {
|
||||
return;
|
||||
}
|
||||
const { booking: bookingResult } = await utils.viewer.bookings.find.fetch({
|
||||
bookingUid: props.booking.uid,
|
||||
});
|
||||
|
||||
if (bookingResult?.paid) {
|
||||
showToast("Payment successful", "success");
|
||||
|
||||
const params: {
|
||||
uid: string;
|
||||
email: string | null;
|
||||
location: string;
|
||||
} = {
|
||||
uid: props.booking.uid,
|
||||
email: sp.get("email"),
|
||||
location: t("web_conferencing_details_to_follow"),
|
||||
};
|
||||
|
||||
bookingSuccessRedirect({
|
||||
successRedirectUrl: props.eventType.successRedirectUrl,
|
||||
query: params,
|
||||
booking: props.booking,
|
||||
forwardParamsSuccessRedirect: props.eventType.forwardParamsSuccessRedirect,
|
||||
});
|
||||
}
|
||||
} catch (e) {}
|
||||
})();
|
||||
}, 2000);
|
||||
|
||||
return () => clearInterval(interval);
|
||||
}, [
|
||||
bookingSuccessRedirect,
|
||||
props.booking,
|
||||
props.booking.id,
|
||||
props.booking.status,
|
||||
props.eventType.id,
|
||||
props.eventType.successRedirectUrl,
|
||||
props.eventType.forwardParamsSuccessRedirect,
|
||||
props.payment.success,
|
||||
searchParams,
|
||||
t,
|
||||
utils.viewer.bookings,
|
||||
]);
|
||||
|
||||
return null;
|
||||
}
|
||||
@@ -36,13 +36,15 @@ const EventTypeCard: FC<EventTypeCardProps> = ({
|
||||
userName,
|
||||
}) => {
|
||||
const parsedMetaData = EventTypeMetaDataSchema.safeParse(metadata);
|
||||
const multipleDuration = parsedMetaData.success && parsedMetaData.data?.multipleDuration
|
||||
? parsedMetaData.data.multipleDuration
|
||||
: [];
|
||||
const multipleDuration =
|
||||
parsedMetaData.success && parsedMetaData.data?.multipleDuration
|
||||
? parsedMetaData.data.multipleDuration
|
||||
: [];
|
||||
|
||||
const durations = multipleDuration.length > 0
|
||||
? [length, ...multipleDuration.filter((duration) => duration !== length)].sort()
|
||||
: [length];
|
||||
const durations =
|
||||
multipleDuration.length > 0
|
||||
? [length, ...multipleDuration.filter((duration) => duration !== length)].sort()
|
||||
: [length];
|
||||
return (
|
||||
<div
|
||||
data-testid={`select-event-type-${id}`}
|
||||
@@ -66,7 +68,6 @@ const EventTypeCard: FC<EventTypeCardProps> = ({
|
||||
// biome-ignore lint/security/noDangerouslySetInnerHtml: Content is sanitized via markdownToSafeHTML
|
||||
<div
|
||||
className="text-subtle line-clamp-4 wrap-break-word text-sm sm:max-w-[650px] [&>*:not(:first-child)]:hidden [&_a]:text-blue-500 [&_a]:underline [&_a]:hover:text-blue-600"
|
||||
|
||||
dangerouslySetInnerHTML={{
|
||||
__html: markdownToSafeHTML(description),
|
||||
}}
|
||||
@@ -120,7 +121,9 @@ const EventTypeGroup: FC<EventTypeGroupProps> = ({ groupIndex, userName, ...prop
|
||||
/>
|
||||
))
|
||||
) : (
|
||||
<div className="text-subtle bg-cal-muted w-full p-2 text-center text-sm">Team has no Events</div>
|
||||
<div className="text-subtle bg-cal-muted w-full p-2 text-center text-sm">
|
||||
Team has no Events
|
||||
</div>
|
||||
)}
|
||||
</ul>
|
||||
</ScrollableArea>
|
||||
|
||||
@@ -102,7 +102,8 @@ export default function PayPalSetup() {
|
||||
<a
|
||||
className="text-orange-600 underline"
|
||||
target="_blank"
|
||||
href="https://developer.paypal.com/api/rest/#link-getclientidandclientsecret" rel="noreferrer">
|
||||
href="https://developer.paypal.com/api/rest/#link-getclientidandclientsecret"
|
||||
rel="noreferrer">
|
||||
Link to Paypal developer API REST Setup Guide:
|
||||
https://developer.paypal.com/api/rest/#link-getclientidandclientsecret
|
||||
</a>
|
||||
@@ -121,7 +122,8 @@ export default function PayPalSetup() {
|
||||
<a
|
||||
target="_blank"
|
||||
href="https://developer.paypal.com/dashboard/applications/live"
|
||||
className="text-orange-600 underline" rel="noreferrer">
|
||||
className="text-orange-600 underline"
|
||||
rel="noreferrer">
|
||||
{t("here")}
|
||||
</a>
|
||||
.
|
||||
|
||||
@@ -8,7 +8,10 @@ import { Dialog } from "@calcom/features/components/controlled-dialog";
|
||||
import { dataTableQueryParamsSerializer } from "@calcom/features/data-table/lib/serializers";
|
||||
import { ColumnFilterType } from "@calcom/features/data-table/lib/types";
|
||||
import { useOrgBranding } from "@calcom/features/ee/organizations/context/provider";
|
||||
import { RoutingFormEmbedButton, RoutingFormEmbedDialog } from "@calcom/web/modules/embed/components/RoutingFormEmbed";
|
||||
import {
|
||||
RoutingFormEmbedButton,
|
||||
RoutingFormEmbedDialog,
|
||||
} from "@calcom/web/modules/embed/components/RoutingFormEmbed";
|
||||
import { EmbedDialogProvider } from "@calcom/features/embed/lib/hooks/useEmbedDialogCtx";
|
||||
import { WEBSITE_URL } from "@calcom/lib/constants";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
|
||||
@@ -804,20 +804,19 @@ const Attendee = (
|
||||
const { copyToClipboard, isCopied } = useCopy();
|
||||
|
||||
const noShowMutation = trpc.viewer.loggedInViewerRouter.markNoShow.useMutation({
|
||||
onSuccess: async (data) => {
|
||||
showToast(data.message, "success");
|
||||
await utils.viewer.bookings.invalidate();
|
||||
},
|
||||
onError: (err) => {
|
||||
showToast(err.message, "error");
|
||||
},
|
||||
});
|
||||
onSuccess: async (data) => {
|
||||
showToast(data.message, "success");
|
||||
await utils.viewer.bookings.invalidate();
|
||||
},
|
||||
onError: (err) => {
|
||||
showToast(err.message, "error");
|
||||
},
|
||||
});
|
||||
|
||||
const displayName = user?.name || name || user?.email || email;
|
||||
|
||||
const isTeamMemberOrHost =
|
||||
email === organizerEmail ||
|
||||
eventTypeHosts?.some((host) => host.user?.email === email);
|
||||
email === organizerEmail || eventTypeHosts?.some((host) => host.user?.email === email);
|
||||
const shouldHideEmail = hideOrganizerEmail && isTeamMemberOrHost;
|
||||
|
||||
return (
|
||||
@@ -858,7 +857,7 @@ const Attendee = (
|
||||
onClick={(e) => {
|
||||
e.preventDefault();
|
||||
const isEmailCopied = isSmsCalEmail(email);
|
||||
copyToClipboard(isEmailCopied ? email : phoneNumber ?? "");
|
||||
copyToClipboard(isEmailCopied ? email : (phoneNumber ?? ""));
|
||||
setOpenDropdown(false);
|
||||
showToast(isEmailCopied ? t("email_copied") : t("phone_number_copied"), "success");
|
||||
}}>
|
||||
@@ -1102,7 +1101,9 @@ const DisplayAttendees = ({
|
||||
|
||||
return (
|
||||
<div className="text-emphasis text-sm" onClick={(e) => e.stopPropagation()}>
|
||||
{user && <FirstAttendee user={user} currentEmail={currentEmail} hideOrganizerEmail={hideOrganizerEmail} />}
|
||||
{user && (
|
||||
<FirstAttendee user={user} currentEmail={currentEmail} hideOrganizerEmail={hideOrganizerEmail} />
|
||||
)}
|
||||
{attendees.length > 1 ? <span>, </span> : <span> {t("and")} </span>}
|
||||
<Attendee
|
||||
{...attendees[0]}
|
||||
|
||||
@@ -54,9 +54,7 @@ export function RoutingTraceSheet({ isOpen, setIsOpen, bookingUid }: RoutingTrac
|
||||
return (
|
||||
<div key={idx} className="relative flex gap-3 pb-6 last:pb-0">
|
||||
{/* Timeline connector line */}
|
||||
{!isLast && (
|
||||
<div className="border-subtle absolute left-4 top-8 bottom-0 border-l" />
|
||||
)}
|
||||
{!isLast && <div className="border-subtle absolute left-4 top-8 bottom-0 border-l" />}
|
||||
{/* Icon circle */}
|
||||
<div className="bg-default border-subtle relative z-10 flex h-8 w-8 flex-shrink-0 items-center justify-center rounded-full border">
|
||||
<DomainIcon domain={step.domain} />
|
||||
|
||||
@@ -278,8 +278,8 @@ export function BookingActionsDropdown({
|
||||
recurringEventId: booking.recurringEventId,
|
||||
})
|
||||
: action.id === "reject"
|
||||
? () => handleReject()
|
||||
: undefined,
|
||||
? () => handleReject()
|
||||
: undefined,
|
||||
})) as ActionType[];
|
||||
|
||||
const shouldShowEdit = shouldShowEditActions(actionContext);
|
||||
@@ -291,14 +291,14 @@ export function BookingActionsDropdown({
|
||||
action.id === "reschedule_request"
|
||||
? () => setIsOpenRescheduleDialog(true)
|
||||
: action.id === "reroute"
|
||||
? () => setRerouteDialogIsOpen(true)
|
||||
: action.id === "change_location"
|
||||
? () => setIsOpenLocationDialog(true)
|
||||
: action.id === "add_members"
|
||||
? () => setIsOpenAddGuestsDialog(true)
|
||||
: action.id === "reassign"
|
||||
? () => setIsOpenReassignDialog(true)
|
||||
: undefined,
|
||||
? () => setRerouteDialogIsOpen(true)
|
||||
: action.id === "change_location"
|
||||
? () => setIsOpenLocationDialog(true)
|
||||
: action.id === "add_members"
|
||||
? () => setIsOpenAddGuestsDialog(true)
|
||||
: action.id === "reassign"
|
||||
? () => setIsOpenReassignDialog(true)
|
||||
: undefined,
|
||||
})) as ActionType[];
|
||||
|
||||
const baseAfterEventActions = getAfterEventActions(actionContext);
|
||||
@@ -308,22 +308,22 @@ export function BookingActionsDropdown({
|
||||
action.id === "view_recordings"
|
||||
? () => setViewRecordingsDialogIsOpen(true)
|
||||
: action.id === "meeting_session_details"
|
||||
? () => setMeetingSessionDetailsDialogIsOpen(true)
|
||||
: action.id === "charge_card"
|
||||
? () => setChargeCardDialogIsOpen(true)
|
||||
: action.id === "no_show"
|
||||
? () => {
|
||||
if (attendeeList.length === 1) {
|
||||
const attendee = attendeeList[0];
|
||||
noShowMutation.mutate({
|
||||
bookingUid: booking.uid,
|
||||
attendees: [{ email: attendee.email, noShow: !attendee.noShow }],
|
||||
});
|
||||
return;
|
||||
}
|
||||
setIsNoShowDialogOpen(true);
|
||||
}
|
||||
: undefined,
|
||||
? () => setMeetingSessionDetailsDialogIsOpen(true)
|
||||
: action.id === "charge_card"
|
||||
? () => setChargeCardDialogIsOpen(true)
|
||||
: action.id === "no_show"
|
||||
? () => {
|
||||
if (attendeeList.length === 1) {
|
||||
const attendee = attendeeList[0];
|
||||
noShowMutation.mutate({
|
||||
bookingUid: booking.uid,
|
||||
attendees: [{ email: attendee.email, noShow: !attendee.noShow }],
|
||||
});
|
||||
return;
|
||||
}
|
||||
setIsNoShowDialogOpen(true);
|
||||
}
|
||||
: undefined,
|
||||
disabled:
|
||||
action.disabled ||
|
||||
(action.id === "no_show" && !(isBookingInPast || isOngoing)) ||
|
||||
|
||||
@@ -237,7 +237,15 @@ export function shouldShowIndividualReportButton(context: BookingActionContext):
|
||||
}
|
||||
|
||||
export function isActionDisabled(actionId: string, context: BookingActionContext): boolean {
|
||||
const { booking, isBookingInPast, isDisabledRescheduling, isDisabledCancelling, isAttendee, isCancelled, isRejected } = context;
|
||||
const {
|
||||
booking,
|
||||
isBookingInPast,
|
||||
isDisabledRescheduling,
|
||||
isDisabledCancelling,
|
||||
isAttendee,
|
||||
isCancelled,
|
||||
isRejected,
|
||||
} = context;
|
||||
|
||||
switch (actionId) {
|
||||
case "reschedule":
|
||||
|
||||
@@ -252,7 +252,9 @@ export const ReassignDialog = ({
|
||||
<strong className="mb-1 block">
|
||||
{isManagedEvent ? t("auto_reassign") : t("round_robin")}
|
||||
</strong>
|
||||
<p>{isManagedEvent ? t("auto_reassign_description") : t("round_robin_reassign_description")}</p>
|
||||
<p>
|
||||
{isManagedEvent ? t("auto_reassign_description") : t("round_robin_reassign_description")}
|
||||
</p>
|
||||
</RadioArea.Item>
|
||||
) : null}
|
||||
<RadioArea.Item
|
||||
@@ -295,42 +297,42 @@ export const ReassignDialog = ({
|
||||
</div>
|
||||
) : (
|
||||
teamMemberOptions.map((member) => (
|
||||
<label
|
||||
key={member.value}
|
||||
tabIndex={watchedTeamMemberId === member.value ? -1 : 0}
|
||||
role="radio"
|
||||
aria-checked={watchedTeamMemberId === member.value}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === "Enter" || e.key === " ") {
|
||||
e.preventDefault();
|
||||
form.setValue("teamMemberId", member.value);
|
||||
}
|
||||
}}
|
||||
className={classNames(
|
||||
"hover:bg-subtle focus:bg-subtle focus:ring-emphasis cursor-pointer items-center justify-between gap-0.5 rounded-sm py-2 outline-none focus:ring-2",
|
||||
watchedTeamMemberId === member.value && "bg-subtle"
|
||||
)}>
|
||||
<div className="flex flex-1 items-center space-x-3">
|
||||
<input
|
||||
type="radio"
|
||||
className="hidden"
|
||||
checked={watchedTeamMemberId === member.value}
|
||||
onChange={() => form.setValue("teamMemberId", member.value)}
|
||||
/>
|
||||
<div
|
||||
className={classNames(
|
||||
"h-3 w-3 shrink-0 rounded-full",
|
||||
member.status === "unavailable" ? "bg-red-500" : "bg-green-500"
|
||||
<label
|
||||
key={member.value}
|
||||
tabIndex={watchedTeamMemberId === member.value ? -1 : 0}
|
||||
role="radio"
|
||||
aria-checked={watchedTeamMemberId === member.value}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === "Enter" || e.key === " ") {
|
||||
e.preventDefault();
|
||||
form.setValue("teamMemberId", member.value);
|
||||
}
|
||||
}}
|
||||
className={classNames(
|
||||
"hover:bg-subtle focus:bg-subtle focus:ring-emphasis cursor-pointer items-center justify-between gap-0.5 rounded-sm py-2 outline-none focus:ring-2",
|
||||
watchedTeamMemberId === member.value && "bg-subtle"
|
||||
)}>
|
||||
<div className="flex flex-1 items-center space-x-3">
|
||||
<input
|
||||
type="radio"
|
||||
className="hidden"
|
||||
checked={watchedTeamMemberId === member.value}
|
||||
onChange={() => form.setValue("teamMemberId", member.value)}
|
||||
/>
|
||||
<div
|
||||
className={classNames(
|
||||
"h-3 w-3 shrink-0 rounded-full",
|
||||
member.status === "unavailable" ? "bg-red-500" : "bg-green-500"
|
||||
)}
|
||||
/>
|
||||
<span className="text-emphasis w-full text-sm">{member.label}</span>
|
||||
{watchedTeamMemberId === member.value && (
|
||||
<div className="place-self-end pr-2">
|
||||
<Icon name="check" className="text-emphasis h-4 w-4" />
|
||||
</div>
|
||||
)}
|
||||
/>
|
||||
<span className="text-emphasis w-full text-sm">{member.label}</span>
|
||||
{watchedTeamMemberId === member.value && (
|
||||
<div className="place-self-end pr-2">
|
||||
<Icon name="check" className="text-emphasis h-4 w-4" />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</label>
|
||||
</div>
|
||||
</label>
|
||||
))
|
||||
)}
|
||||
{teamMemberOptions.length > 0 && (
|
||||
|
||||
@@ -903,7 +903,7 @@ export const RerouteDialog = ({ isOpenDialog, setIsOpenDialog, booking }: Rerout
|
||||
|
||||
return (
|
||||
<Dialog open={isOpenDialog} onOpenChange={setIsOpenDialog}>
|
||||
<DialogContent preventCloseOnOutsideClick enableOverflow>
|
||||
<DialogContent preventCloseOnOutsideClick enableOverflow>
|
||||
<DialogHeader title={t("reroute_booking")} subtitle={t("reroute_booking_description")} />
|
||||
<RerouteDialogContentAndFooter
|
||||
booking={teamEventTypeBooking}
|
||||
|
||||
@@ -234,10 +234,8 @@ export function WrongAssignmentDialog(props: IWrongAssignmentDialog): JSX.Elemen
|
||||
},
|
||||
});
|
||||
|
||||
const { data: existingReport, isPending: isCheckingReport } = trpc.viewer.bookings.hasWrongAssignmentReport.useQuery(
|
||||
{ bookingUid },
|
||||
{ enabled: isOpenDialog }
|
||||
);
|
||||
const { data: existingReport, isPending: isCheckingReport } =
|
||||
trpc.viewer.bookings.hasWrongAssignmentReport.useQuery({ bookingUid }, { enabled: isOpenDialog });
|
||||
const alreadyReported = existingReport?.hasReport ?? false;
|
||||
|
||||
const teamIdForQuery = teamId ?? 0;
|
||||
@@ -329,7 +327,11 @@ export function WrongAssignmentDialog(props: IWrongAssignmentDialog): JSX.Elemen
|
||||
<Button type="button" color="secondary" onClick={handleCloseClick} disabled={isPending}>
|
||||
{t("close")}
|
||||
</Button>
|
||||
<Button type="submit" color="primary" disabled={isPending || alreadyReported || isCheckingReport} loading={isPending || isCheckingReport}>
|
||||
<Button
|
||||
type="submit"
|
||||
color="primary"
|
||||
disabled={isPending || alreadyReported || isCheckingReport}
|
||||
loading={isPending || isCheckingReport}>
|
||||
{t("submit")}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
|
||||
@@ -61,7 +61,7 @@ const EventReservationSchema: FC<EventReservationSchemaInterface> = ({
|
||||
? ({ "@type": "Person", name: organizer.name, email: organizer.email } as Person)
|
||||
: undefined,
|
||||
attendee: attendees?.map(
|
||||
(person) => ({ "@type": "Person", name: person.name, email: person.email } as Person)
|
||||
(person) => ({ "@type": "Person", name: person.name, email: person.email }) as Person
|
||||
),
|
||||
location: location || undefined,
|
||||
description: description || undefined,
|
||||
|
||||
@@ -48,7 +48,7 @@ export type AppProps = Omit<
|
||||
const getEmbedNamespace = (searchParams: ReadonlyURLSearchParams) => {
|
||||
// Mostly embed query param should be available on server. Use that there.
|
||||
// Use the most reliable detection on client
|
||||
return typeof window !== "undefined" ? window.getEmbedNamespace() : searchParams.get("embed") ?? null;
|
||||
return typeof window !== "undefined" ? window.getEmbedNamespace() : (searchParams.get("embed") ?? null);
|
||||
};
|
||||
|
||||
type CalcomThemeProps = Readonly<{
|
||||
|
||||
@@ -208,9 +208,9 @@ function getThemeProviderProps({
|
||||
const themeSupport = isBookingPage
|
||||
? ThemeSupport.Booking
|
||||
: // if isThemeSupported is explicitly false, we don't use theme there
|
||||
props.isThemeSupported === false
|
||||
? ThemeSupport.None
|
||||
: ThemeSupport.App;
|
||||
props.isThemeSupported === false
|
||||
? ThemeSupport.None
|
||||
: ThemeSupport.App;
|
||||
|
||||
const isBookingPageThemeSupportRequired = themeSupport === ThemeSupport.Booking;
|
||||
const themeBasis = props.themeBasis;
|
||||
@@ -237,10 +237,10 @@ function getThemeProviderProps({
|
||||
// Even though it's recommended to use different namespaces when you want to theme differently on the same page but if the embeds are on different pages, the problem can still arise
|
||||
`embed-theme-${embedNamespace}${appearanceIdSuffix}${embedExplicitlySetThemeSuffix}`
|
||||
: themeSupport === ThemeSupport.App
|
||||
? "app-theme"
|
||||
: isBookingPageThemeSupportRequired
|
||||
? `booking-theme${appearanceIdSuffix}`
|
||||
: undefined;
|
||||
? "app-theme"
|
||||
: isBookingPageThemeSupportRequired
|
||||
? `booking-theme${appearanceIdSuffix}`
|
||||
: undefined;
|
||||
|
||||
return {
|
||||
storageKey,
|
||||
|
||||
@@ -15,12 +15,15 @@ export const getServerSideProps = async (context: GetServerSidePropsContext) =>
|
||||
appStore = await getAppRegistry();
|
||||
}
|
||||
|
||||
const categories = appStore.reduce((c, app) => {
|
||||
for (const category of app.categories) {
|
||||
c[category] = c[category] ? c[category] + 1 : 1;
|
||||
}
|
||||
return c;
|
||||
}, {} as Record<string, number>);
|
||||
const categories = appStore.reduce(
|
||||
(c, app) => {
|
||||
for (const category of app.categories) {
|
||||
c[category] = c[category] ? c[category] + 1 : 1;
|
||||
}
|
||||
return c;
|
||||
},
|
||||
{} as Record<string, number>
|
||||
);
|
||||
|
||||
return {
|
||||
props: {
|
||||
|
||||
@@ -16,379 +16,578 @@ import { Prisma } from "@calcom/prisma/client";
|
||||
import { eventTypeBookingFields } from "@calcom/prisma/zod-utils";
|
||||
|
||||
import { STEPS } from "../../../../modules/apps/installation/[[...step]]/constants";
|
||||
import type { OnboardingPageProps, TEventTypeGroup, TEventType } from "../../../../modules/apps/installation/[[...step]]/step-view";
|
||||
import type {
|
||||
OnboardingPageProps,
|
||||
TEventTypeGroup,
|
||||
TEventType,
|
||||
} from "../../../../modules/apps/installation/[[...step]]/step-view";
|
||||
|
||||
const eventTypeSelect: Prisma.EventTypeSelect = {
|
||||
id: true, description: true, durationLimits: true, metadata: true, length: true, title: true,
|
||||
position: true, recurringEvent: true, requiresConfirmation: true, canSendCalVideoTranscriptionEmails: true,
|
||||
team: { select: { slug: true } }, schedulingType: true, teamId: true, users: { select: { username: true } },
|
||||
seatsPerTimeSlot: true, slug: true, locations: true, userId: true, destinationCalendar: true,
|
||||
bookingFields: true, calVideoSettings: true, parentId: true,
|
||||
id: true,
|
||||
description: true,
|
||||
durationLimits: true,
|
||||
metadata: true,
|
||||
length: true,
|
||||
title: true,
|
||||
position: true,
|
||||
recurringEvent: true,
|
||||
requiresConfirmation: true,
|
||||
canSendCalVideoTranscriptionEmails: true,
|
||||
team: { select: { slug: true } },
|
||||
schedulingType: true,
|
||||
teamId: true,
|
||||
users: { select: { username: true } },
|
||||
seatsPerTimeSlot: true,
|
||||
slug: true,
|
||||
locations: true,
|
||||
userId: true,
|
||||
destinationCalendar: true,
|
||||
bookingFields: true,
|
||||
calVideoSettings: true,
|
||||
parentId: true,
|
||||
};
|
||||
|
||||
type EventTypeFromDb = Prisma.EventTypeGetPayload<{
|
||||
select: typeof eventTypeSelect;
|
||||
select: typeof eventTypeSelect;
|
||||
}>;
|
||||
|
||||
type MinimalUser = {
|
||||
id: number;
|
||||
username: string | null;
|
||||
name: string | null;
|
||||
avatarUrl: string | null;
|
||||
id: number;
|
||||
username: string | null;
|
||||
name: string | null;
|
||||
avatarUrl: string | null;
|
||||
};
|
||||
|
||||
type MinimalTeam = {
|
||||
id: number;
|
||||
name: string;
|
||||
logoUrl: string | null;
|
||||
isOrganization: boolean;
|
||||
id: number;
|
||||
name: string;
|
||||
logoUrl: string | null;
|
||||
isOrganization: boolean;
|
||||
};
|
||||
|
||||
type RedirectResult = { redirect: { permanent: boolean; destination: string } };
|
||||
|
||||
const mapEventType = (item: EventTypeFromDb): TEventType => {
|
||||
let teamSlug = "";
|
||||
if (item.team) {
|
||||
teamSlug = `team/${item.team.slug}`;
|
||||
}
|
||||
const userSlug = item?.users?.[0]?.username;
|
||||
let urlPart = userSlug;
|
||||
if (teamSlug) {
|
||||
urlPart = teamSlug;
|
||||
}
|
||||
let teamSlug = "";
|
||||
if (item.team) {
|
||||
teamSlug = `team/${item.team.slug}`;
|
||||
}
|
||||
const userSlug = item?.users?.[0]?.username;
|
||||
let urlPart = userSlug;
|
||||
if (teamSlug) {
|
||||
urlPart = teamSlug;
|
||||
}
|
||||
|
||||
return {
|
||||
...item,
|
||||
URL: `${CAL_URL}/${urlPart}/${item.slug}`,
|
||||
selected: false,
|
||||
locations: item.locations as unknown as LocationObject[],
|
||||
bookingFields: eventTypeBookingFields.parse(item.bookingFields || []),
|
||||
};
|
||||
return {
|
||||
...item,
|
||||
URL: `${CAL_URL}/${urlPart}/${item.slug}`,
|
||||
selected: false,
|
||||
locations: item.locations as unknown as LocationObject[],
|
||||
bookingFields: eventTypeBookingFields.parse(item.bookingFields || []),
|
||||
};
|
||||
};
|
||||
|
||||
const getUser = async (userId: number): Promise<(MinimalUser & {
|
||||
teams: { id: number; name: string; logoUrl: string | null; isOrganization: boolean; parent: { id: number; name: string; logoUrl: string | null } | null }[];
|
||||
}) | null> => {
|
||||
const userRepo = new UserRepository(prisma);
|
||||
const userAdminTeams = await userRepo.getUserAdminTeams({ userId });
|
||||
|
||||
if (!userAdminTeams?.id) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const teams = userAdminTeams.teams.map(({ team }) => {
|
||||
const getUser = async (
|
||||
userId: number
|
||||
): Promise<
|
||||
| (MinimalUser & {
|
||||
teams: {
|
||||
id: number;
|
||||
name: string;
|
||||
logoUrl: string | null;
|
||||
isOrganization: boolean;
|
||||
parent: { id: number; name: string; logoUrl: string | null } | null;
|
||||
}[];
|
||||
})
|
||||
| null
|
||||
> => {
|
||||
const userRepo = new UserRepository(prisma);
|
||||
const userAdminTeams = await userRepo.getUserAdminTeams({ userId });
|
||||
|
||||
if (!userAdminTeams?.id) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const teams = userAdminTeams.teams.map(({ team }) => {
|
||||
const parentLogoUrl = team.parent?.logoUrl;
|
||||
const parentName = team.parent?.name;
|
||||
|
||||
|
||||
let logoUrl = "";
|
||||
if (team.parent) {
|
||||
logoUrl = getPlaceholderAvatar(parentLogoUrl, parentName);
|
||||
logoUrl = getPlaceholderAvatar(parentLogoUrl, parentName);
|
||||
} else {
|
||||
logoUrl = getPlaceholderAvatar(team.logoUrl, team.name);
|
||||
logoUrl = getPlaceholderAvatar(team.logoUrl, team.name);
|
||||
}
|
||||
return {
|
||||
...team,
|
||||
logoUrl,
|
||||
};
|
||||
});
|
||||
|
||||
return {
|
||||
...userAdminTeams,
|
||||
teams,
|
||||
};
|
||||
};
|
||||
|
||||
const getOrgSubTeams = async (parentId: number): Promise<{ id: number; name: string; logoUrl: string | null; isOrganization: boolean; parent: { id: number; name: string; logoUrl: string | null } | null }[]> => {
|
||||
const teams = await prisma.team.findMany({
|
||||
where: {
|
||||
parentId,
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
logoUrl: true,
|
||||
isOrganization: true,
|
||||
parent: {
|
||||
select: {
|
||||
logoUrl: true,
|
||||
name: true,
|
||||
id: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
return teams.map((team) => {
|
||||
const parentLogoUrl = team.parent?.logoUrl;
|
||||
const parentName = team.parent?.name;
|
||||
let logoUrl = "";
|
||||
if (team.parent) {
|
||||
logoUrl = getPlaceholderAvatar(parentLogoUrl, parentName);
|
||||
} else {
|
||||
logoUrl = getPlaceholderAvatar(team.logoUrl, team.name);
|
||||
}
|
||||
return {
|
||||
...team,
|
||||
logoUrl,
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
const getAppBySlug = async (appSlug: string): Promise<{ slug: string; keys: Prisma.JsonValue; enabled: boolean; dirName: string; } | null> => {
|
||||
const app = await prisma.app.findUnique({
|
||||
where: { slug: appSlug, enabled: true },
|
||||
select: { slug: true, keys: true, enabled: true, dirName: true },
|
||||
});
|
||||
return app;
|
||||
return {
|
||||
...userAdminTeams,
|
||||
teams,
|
||||
};
|
||||
};
|
||||
|
||||
const getTeamEventTypes = async (teamIds: number[], isConferencing: boolean, eventTypeSelect: Prisma.EventTypeSelect): Promise<TEventTypeGroup[]> => {
|
||||
const teams = await prisma.team.findMany({
|
||||
where: { id: { in: teamIds }, isOrganization: false },
|
||||
select: { id: true, name: true, logoUrl: true, slug: true, isOrganization: true, eventTypes: { select: eventTypeSelect } },
|
||||
});
|
||||
return teams.map((team) => {
|
||||
let filteredEventTypes = team.eventTypes;
|
||||
if (isConferencing) {
|
||||
filteredEventTypes = filterEventTypesWhereLocationUpdateIsAllowed(team.eventTypes);
|
||||
}
|
||||
return {
|
||||
teamId: team.id, slug: team.slug, name: team.name, isOrganisation: team.isOrganization,
|
||||
image: getPlaceholderAvatar(team.logoUrl, team.name),
|
||||
eventTypes: (filteredEventTypes as unknown as EventTypeFromDb[]).map(mapEventType).sort((a, b) => (b.position || 0) - (a.position || 0)),
|
||||
};
|
||||
});
|
||||
};
|
||||
|
||||
const getUserEventTypes = async (userId: number, isConferencing: boolean, eventTypeSelect: Prisma.EventTypeSelect): Promise<TEventTypeGroup[]> => {
|
||||
const user = await prisma.user.findUnique({
|
||||
where: { id: userId },
|
||||
select: { id: true, username: true, name: true, avatarUrl: true, eventTypes: { where: { teamId: null }, select: eventTypeSelect } },
|
||||
});
|
||||
|
||||
if (!user) return [];
|
||||
|
||||
let filteredEventTypes = user.eventTypes;
|
||||
if (isConferencing) {
|
||||
filteredEventTypes = filterEventTypesWhereLocationUpdateIsAllowed(user.eventTypes);
|
||||
const getOrgSubTeams = async (
|
||||
parentId: number
|
||||
): Promise<
|
||||
{
|
||||
id: number;
|
||||
name: string;
|
||||
logoUrl: string | null;
|
||||
isOrganization: boolean;
|
||||
parent: { id: number; name: string; logoUrl: string | null } | null;
|
||||
}[]
|
||||
> => {
|
||||
const teams = await prisma.team.findMany({
|
||||
where: {
|
||||
parentId,
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
logoUrl: true,
|
||||
isOrganization: true,
|
||||
parent: {
|
||||
select: {
|
||||
logoUrl: true,
|
||||
name: true,
|
||||
id: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
return teams.map((team) => {
|
||||
const parentLogoUrl = team.parent?.logoUrl;
|
||||
const parentName = team.parent?.name;
|
||||
let logoUrl = "";
|
||||
if (team.parent) {
|
||||
logoUrl = getPlaceholderAvatar(parentLogoUrl, parentName);
|
||||
} else {
|
||||
logoUrl = getPlaceholderAvatar(team.logoUrl, team.name);
|
||||
}
|
||||
return [{
|
||||
userId: user.id, slug: user.username, name: user.name, image: getPlaceholderAvatar(user.avatarUrl, user.name),
|
||||
eventTypes: (filteredEventTypes as unknown as EventTypeFromDb[]).map(mapEventType).sort((a, b) => (b.position || 0) - (a.position || 0)),
|
||||
}];
|
||||
return {
|
||||
...team,
|
||||
logoUrl,
|
||||
};
|
||||
});
|
||||
};
|
||||
|
||||
const getAppBySlug = async (
|
||||
appSlug: string
|
||||
): Promise<{ slug: string; keys: Prisma.JsonValue; enabled: boolean; dirName: string } | null> => {
|
||||
const app = await prisma.app.findUnique({
|
||||
where: { slug: appSlug, enabled: true },
|
||||
select: { slug: true, keys: true, enabled: true, dirName: true },
|
||||
});
|
||||
return app;
|
||||
};
|
||||
|
||||
const getTeamEventTypes = async (
|
||||
teamIds: number[],
|
||||
isConferencing: boolean,
|
||||
eventTypeSelect: Prisma.EventTypeSelect
|
||||
): Promise<TEventTypeGroup[]> => {
|
||||
const teams = await prisma.team.findMany({
|
||||
where: { id: { in: teamIds }, isOrganization: false },
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
logoUrl: true,
|
||||
slug: true,
|
||||
isOrganization: true,
|
||||
eventTypes: { select: eventTypeSelect },
|
||||
},
|
||||
});
|
||||
return teams.map((team) => {
|
||||
let filteredEventTypes = team.eventTypes;
|
||||
if (isConferencing) {
|
||||
filteredEventTypes = filterEventTypesWhereLocationUpdateIsAllowed(team.eventTypes);
|
||||
}
|
||||
return {
|
||||
teamId: team.id,
|
||||
slug: team.slug,
|
||||
name: team.name,
|
||||
isOrganisation: team.isOrganization,
|
||||
image: getPlaceholderAvatar(team.logoUrl, team.name),
|
||||
eventTypes: (filteredEventTypes as unknown as EventTypeFromDb[])
|
||||
.map(mapEventType)
|
||||
.sort((a, b) => (b.position || 0) - (a.position || 0)),
|
||||
};
|
||||
});
|
||||
};
|
||||
|
||||
const getUserEventTypes = async (
|
||||
userId: number,
|
||||
isConferencing: boolean,
|
||||
eventTypeSelect: Prisma.EventTypeSelect
|
||||
): Promise<TEventTypeGroup[]> => {
|
||||
const user = await prisma.user.findUnique({
|
||||
where: { id: userId },
|
||||
select: {
|
||||
id: true,
|
||||
username: true,
|
||||
name: true,
|
||||
avatarUrl: true,
|
||||
eventTypes: { where: { teamId: null }, select: eventTypeSelect },
|
||||
},
|
||||
});
|
||||
|
||||
if (!user) return [];
|
||||
|
||||
let filteredEventTypes = user.eventTypes;
|
||||
if (isConferencing) {
|
||||
filteredEventTypes = filterEventTypesWhereLocationUpdateIsAllowed(user.eventTypes);
|
||||
}
|
||||
return [
|
||||
{
|
||||
userId: user.id,
|
||||
slug: user.username,
|
||||
name: user.name,
|
||||
image: getPlaceholderAvatar(user.avatarUrl, user.name),
|
||||
eventTypes: (filteredEventTypes as unknown as EventTypeFromDb[])
|
||||
.map(mapEventType)
|
||||
.sort((a, b) => (b.position || 0) - (a.position || 0)),
|
||||
},
|
||||
];
|
||||
};
|
||||
|
||||
const getEventTypes = async ({
|
||||
userId,
|
||||
teamIds,
|
||||
isConferencing = false,
|
||||
userId,
|
||||
teamIds,
|
||||
isConferencing = false,
|
||||
}: {
|
||||
userId: number;
|
||||
teamIds?: number[];
|
||||
isConferencing?: boolean;
|
||||
userId: number;
|
||||
teamIds?: number[];
|
||||
isConferencing?: boolean;
|
||||
}): Promise<TEventTypeGroup[] | null> => {
|
||||
if (teamIds && teamIds.length > 0) {
|
||||
return getTeamEventTypes(teamIds, isConferencing, eventTypeSelect);
|
||||
}
|
||||
if (teamIds && teamIds.length > 0) {
|
||||
return getTeamEventTypes(teamIds, isConferencing, eventTypeSelect);
|
||||
}
|
||||
|
||||
return getUserEventTypes(userId, isConferencing, eventTypeSelect);
|
||||
return getUserEventTypes(userId, isConferencing, eventTypeSelect);
|
||||
};
|
||||
|
||||
const getAppInstallsBySlug = async (appSlug: string, userId: number, teamIds?: number[]): Promise<Prisma.CredentialGetPayload<Record<string, never>>[]> => {
|
||||
if (teamIds?.length) {
|
||||
return prisma.credential.findMany({
|
||||
where: {
|
||||
OR: [
|
||||
{ appId: appSlug, userId: userId },
|
||||
{ appId: appSlug, teamId: { in: teamIds } }
|
||||
]
|
||||
}
|
||||
});
|
||||
const getAppInstallsBySlug = async (
|
||||
appSlug: string,
|
||||
userId: number,
|
||||
teamIds?: number[]
|
||||
): Promise<Prisma.CredentialGetPayload<Record<string, never>>[]> => {
|
||||
if (teamIds?.length) {
|
||||
return prisma.credential.findMany({
|
||||
where: {
|
||||
OR: [
|
||||
{ appId: appSlug, userId: userId },
|
||||
{ appId: appSlug, teamId: { in: teamIds } },
|
||||
],
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
return prisma.credential.findMany({
|
||||
where: { appId: appSlug, userId: userId },
|
||||
});
|
||||
};
|
||||
|
||||
const handleAutoInstall = async (
|
||||
user: MinimalUser,
|
||||
appMetadata: import("@calcom/types/App").AppMeta,
|
||||
parsedAppSlug: string
|
||||
): Promise<number | null> => {
|
||||
try {
|
||||
const newCredential = await createDefaultInstallation({
|
||||
appType: appMetadata.type,
|
||||
user: { id: user.id },
|
||||
slug: parsedAppSlug,
|
||||
key: {},
|
||||
teamId: undefined,
|
||||
});
|
||||
return newCredential.id;
|
||||
} catch (error) {
|
||||
if (error instanceof Prisma.PrismaClientKnownRequestError && error.code === "P2002") {
|
||||
const existing = await prisma.credential.findFirst({
|
||||
where: { appId: parsedAppSlug, userId: user.id, teamId: null },
|
||||
select: { id: true },
|
||||
});
|
||||
return existing?.id ?? null;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
return prisma.credential.findMany({
|
||||
where: { appId: appSlug, userId: userId },
|
||||
});
|
||||
};
|
||||
const getEventTypeGroupsForStep = async (
|
||||
user: MinimalUser,
|
||||
userTeams: MinimalTeam[],
|
||||
parsedTeamIdParam: number | undefined,
|
||||
isOrg: boolean,
|
||||
isConferencing: boolean
|
||||
): Promise<TEventTypeGroup[] | null> => {
|
||||
let groups: TEventTypeGroup[] | null = null;
|
||||
if (isOrg) {
|
||||
groups = await getEventTypes({
|
||||
userId: user.id,
|
||||
teamIds: userTeams.map((item) => item.id),
|
||||
isConferencing,
|
||||
});
|
||||
} else if (parsedTeamIdParam) {
|
||||
groups = await getEventTypes({ userId: user.id, teamIds: [parsedTeamIdParam], isConferencing });
|
||||
} else {
|
||||
groups = await getEventTypes({ userId: user.id, isConferencing });
|
||||
}
|
||||
|
||||
const handleAutoInstall = async (user: MinimalUser, appMetadata: import("@calcom/types/App").AppMeta, parsedAppSlug: string): Promise<number | null> => {
|
||||
try {
|
||||
const newCredential = await createDefaultInstallation({
|
||||
appType: appMetadata.type,
|
||||
user: { id: user.id },
|
||||
slug: parsedAppSlug,
|
||||
key: {},
|
||||
teamId: undefined,
|
||||
});
|
||||
return newCredential.id;
|
||||
} catch (error) {
|
||||
if (error instanceof Prisma.PrismaClientKnownRequestError && error.code === "P2002") {
|
||||
const existing = await prisma.credential.findFirst({
|
||||
where: { appId: parsedAppSlug, userId: user.id, teamId: null },
|
||||
select: { id: true },
|
||||
});
|
||||
return existing?.id ?? null;
|
||||
if (isConferencing && groups) {
|
||||
const destinationCalendar = await prisma.destinationCalendar.findFirst({
|
||||
where: { userId: user.id, eventTypeId: null },
|
||||
});
|
||||
|
||||
groups.forEach((group) => {
|
||||
group.eventTypes = group.eventTypes.map((eventType) => {
|
||||
if (!eventType.destinationCalendar) {
|
||||
return { ...eventType, destinationCalendar };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
return eventType;
|
||||
});
|
||||
});
|
||||
}
|
||||
return groups;
|
||||
};
|
||||
|
||||
const getEventTypeGroupsForStep = async (user: MinimalUser, userTeams: MinimalTeam[], parsedTeamIdParam: number | undefined, isOrg: boolean, isConferencing: boolean): Promise<TEventTypeGroup[] | null> => {
|
||||
let groups: TEventTypeGroup[] | null = null;
|
||||
if (isOrg) {
|
||||
groups = await getEventTypes({ userId: user.id, teamIds: userTeams.map((item) => item.id), isConferencing });
|
||||
} else if (parsedTeamIdParam) {
|
||||
groups = await getEventTypes({ userId: user.id, teamIds: [parsedTeamIdParam], isConferencing });
|
||||
const getInitialStep = (
|
||||
parsedStepParam: string | undefined,
|
||||
hasTeams: boolean,
|
||||
showEventTypesStep: boolean,
|
||||
parsedAppSlug: string,
|
||||
isOAuth: boolean
|
||||
): { step: string | undefined; redirect?: RedirectResult } => {
|
||||
if (!hasTeams && parsedStepParam === AppOnboardingSteps.ACCOUNTS_STEP && showEventTypesStep && !isOAuth) {
|
||||
return {
|
||||
step: parsedStepParam,
|
||||
redirect: {
|
||||
redirect: { permanent: false, destination: `/apps/installation/event-types?slug=${parsedAppSlug}` },
|
||||
},
|
||||
};
|
||||
}
|
||||
let step = parsedStepParam;
|
||||
if (!parsedStepParam) {
|
||||
if (hasTeams) {
|
||||
step = AppOnboardingSteps.ACCOUNTS_STEP;
|
||||
} else {
|
||||
groups = await getEventTypes({ userId: user.id, isConferencing });
|
||||
step = isOAuth ? AppOnboardingSteps.ACCOUNTS_STEP : AppOnboardingSteps.EVENT_TYPES_STEP;
|
||||
}
|
||||
|
||||
if (isConferencing && groups) {
|
||||
const destinationCalendar = await prisma.destinationCalendar.findFirst({
|
||||
where: { userId: user.id, eventTypeId: null },
|
||||
});
|
||||
|
||||
groups.forEach((group) => {
|
||||
group.eventTypes = group.eventTypes.map((eventType) => {
|
||||
if (!eventType.destinationCalendar) {
|
||||
return { ...eventType, destinationCalendar };
|
||||
}
|
||||
return eventType;
|
||||
});
|
||||
});
|
||||
}
|
||||
return groups;
|
||||
}
|
||||
return { step };
|
||||
};
|
||||
|
||||
const getInitialStep = (parsedStepParam: string | undefined, hasTeams: boolean, showEventTypesStep: boolean, parsedAppSlug: string, isOAuth: boolean): { step: string | undefined; redirect?: RedirectResult } => {
|
||||
if (!hasTeams && parsedStepParam === AppOnboardingSteps.ACCOUNTS_STEP && showEventTypesStep && !isOAuth) {
|
||||
return {
|
||||
step: parsedStepParam,
|
||||
redirect: { redirect: { permanent: false, destination: `/apps/installation/event-types?slug=${parsedAppSlug}` } }
|
||||
};
|
||||
}
|
||||
let step = parsedStepParam;
|
||||
if (!parsedStepParam) {
|
||||
if (hasTeams) {
|
||||
step = AppOnboardingSteps.ACCOUNTS_STEP;
|
||||
} else {
|
||||
step = isOAuth ? AppOnboardingSteps.ACCOUNTS_STEP : AppOnboardingSteps.EVENT_TYPES_STEP;
|
||||
}
|
||||
}
|
||||
return { step };
|
||||
const getAppAndMetadata = async (
|
||||
parsedAppSlug: string
|
||||
): Promise<{
|
||||
app: { slug: string; keys: Prisma.JsonValue; enabled: boolean; dirName: string } | null;
|
||||
appMetadata: import("@calcom/types/App").AppMeta | null;
|
||||
redirect?: RedirectResult;
|
||||
}> => {
|
||||
const app = await getAppBySlug(parsedAppSlug);
|
||||
if (!app)
|
||||
return {
|
||||
app: null,
|
||||
appMetadata: null,
|
||||
redirect: { redirect: { permanent: false, destination: "/apps" } },
|
||||
};
|
||||
const appMetadata = appStoreMetadata[app.dirName as keyof typeof appStoreMetadata];
|
||||
if (!appMetadata)
|
||||
return {
|
||||
app: null,
|
||||
appMetadata: null,
|
||||
redirect: { redirect: { permanent: false, destination: "/apps" } },
|
||||
};
|
||||
return { app, appMetadata };
|
||||
};
|
||||
|
||||
const getAppAndMetadata = async (parsedAppSlug: string): Promise<{ app: { slug: string; keys: Prisma.JsonValue; enabled: boolean; dirName: string } | null; appMetadata: import("@calcom/types/App").AppMeta | null; redirect?: RedirectResult }> => {
|
||||
const app = await getAppBySlug(parsedAppSlug);
|
||||
if (!app) return { app: null, appMetadata: null, redirect: { redirect: { permanent: false, destination: "/apps" } } };
|
||||
const appMetadata = appStoreMetadata[app.dirName as keyof typeof appStoreMetadata];
|
||||
if (!appMetadata) return { app: null, appMetadata: null, redirect: { redirect: { permanent: false, destination: "/apps" } } };
|
||||
return { app, appMetadata };
|
||||
const getCredentialId = (
|
||||
parsedTeamIdParam: number | undefined,
|
||||
appInstalls: Prisma.CredentialGetPayload<Record<string, never>>[],
|
||||
userId: number
|
||||
): number | null => {
|
||||
if (parsedTeamIdParam) {
|
||||
return appInstalls.find((item) => item.teamId === parsedTeamIdParam)?.id ?? null;
|
||||
}
|
||||
return appInstalls.find((item) => item.userId === userId)?.id ?? null;
|
||||
};
|
||||
|
||||
const getCredentialId = (parsedTeamIdParam: number | undefined, appInstalls: Prisma.CredentialGetPayload<Record<string, never>>[], userId: number): number | null => {
|
||||
if (parsedTeamIdParam) {
|
||||
return appInstalls.find((item) => item.teamId === parsedTeamIdParam)?.id ?? null;
|
||||
const prepareUserTeams = async (
|
||||
user: MinimalUser & { teams: MinimalTeam[] },
|
||||
parsedTeamIdParam: number | undefined
|
||||
): Promise<{ userTeams: MinimalTeam[]; isOrg: boolean; redirect?: RedirectResult }> => {
|
||||
let userTeams = user.teams;
|
||||
let isOrg = false;
|
||||
if (parsedTeamIdParam) {
|
||||
const currentTeam = userTeams.find((team: MinimalTeam) => team.id === parsedTeamIdParam);
|
||||
if (!currentTeam?.id)
|
||||
return {
|
||||
userTeams: [],
|
||||
isOrg: false,
|
||||
redirect: { redirect: { permanent: false, destination: "/apps" } },
|
||||
};
|
||||
if (currentTeam.isOrganization) {
|
||||
userTeams = [...userTeams, ...(await getOrgSubTeams(parsedTeamIdParam))];
|
||||
isOrg = true;
|
||||
}
|
||||
return appInstalls.find((item) => item.userId === userId)?.id ?? null;
|
||||
}
|
||||
return { userTeams, isOrg };
|
||||
};
|
||||
|
||||
const prepareUserTeams = async (user: MinimalUser & { teams: MinimalTeam[] }, parsedTeamIdParam: number | undefined): Promise<{ userTeams: MinimalTeam[]; isOrg: boolean; redirect?: RedirectResult }> => {
|
||||
let userTeams = user.teams;
|
||||
let isOrg = false;
|
||||
if (parsedTeamIdParam) {
|
||||
const currentTeam = userTeams.find((team: MinimalTeam) => team.id === parsedTeamIdParam);
|
||||
if (!currentTeam?.id) return { userTeams: [], isOrg: false, redirect: { redirect: { permanent: false, destination: "/apps" } } };
|
||||
if (currentTeam.isOrganization) {
|
||||
userTeams = [...userTeams, ...await getOrgSubTeams(parsedTeamIdParam)];
|
||||
isOrg = true;
|
||||
}
|
||||
}
|
||||
return { userTeams, isOrg };
|
||||
const getCredential = async (
|
||||
parsedTeamIdParam: number | undefined,
|
||||
appInstalls: Prisma.CredentialGetPayload<Record<string, never>>[],
|
||||
user: MinimalUser & { teams: MinimalTeam[] },
|
||||
initialStep: string,
|
||||
appMetadata: import("@calcom/types/App").AppMeta,
|
||||
parsedAppSlug: string
|
||||
): Promise<{ credentialId: number | null; redirect?: RedirectResult }> => {
|
||||
let credentialId = getCredentialId(parsedTeamIdParam, appInstalls, user.id);
|
||||
if (
|
||||
!credentialId &&
|
||||
!user.teams.length &&
|
||||
initialStep === AppOnboardingSteps.EVENT_TYPES_STEP &&
|
||||
!appMetadata.isOAuth
|
||||
) {
|
||||
credentialId = await handleAutoInstall(user, appMetadata, parsedAppSlug);
|
||||
if (!credentialId)
|
||||
return { credentialId: null, redirect: { redirect: { permanent: false, destination: "/apps" } } };
|
||||
}
|
||||
return { credentialId };
|
||||
};
|
||||
|
||||
const getCredential = async (parsedTeamIdParam: number | undefined, appInstalls: Prisma.CredentialGetPayload<Record<string, never>>[], user: MinimalUser & { teams: MinimalTeam[] }, initialStep: string, appMetadata: import("@calcom/types/App").AppMeta, parsedAppSlug: string): Promise<{ credentialId: number | null; redirect?: RedirectResult }> => {
|
||||
let credentialId = getCredentialId(parsedTeamIdParam, appInstalls, user.id);
|
||||
if (!credentialId && !user.teams.length && initialStep === AppOnboardingSteps.EVENT_TYPES_STEP && !appMetadata.isOAuth) {
|
||||
credentialId = await handleAutoInstall(user, appMetadata, parsedAppSlug);
|
||||
if (!credentialId) return { credentialId: null, redirect: { redirect: { permanent: false, destination: "/apps" } } };
|
||||
}
|
||||
return { credentialId };
|
||||
};
|
||||
|
||||
const getTeamsInstalled = (hasTeams: boolean, userTeams: MinimalTeam[], appInstalls: Prisma.CredentialGetPayload<Record<string, never>>[]): import("../../../../modules/apps/installation/[[...step]]/step-view").TTeams => {
|
||||
if (!hasTeams) return [];
|
||||
return userTeams.map((team: MinimalTeam) => ({
|
||||
...team, alreadyInstalled: appInstalls.some((install) => !!install.teamId && install.teamId === team.id),
|
||||
}));
|
||||
const getTeamsInstalled = (
|
||||
hasTeams: boolean,
|
||||
userTeams: MinimalTeam[],
|
||||
appInstalls: Prisma.CredentialGetPayload<Record<string, never>>[]
|
||||
): import("../../../../modules/apps/installation/[[...step]]/step-view").TTeams => {
|
||||
if (!hasTeams) return [];
|
||||
return userTeams.map((team: MinimalTeam) => ({
|
||||
...team,
|
||||
alreadyInstalled: appInstalls.some((install) => !!install.teamId && install.teamId === team.id),
|
||||
}));
|
||||
};
|
||||
|
||||
const getParsedStep = (paramsStep: string | string[] | undefined): string | undefined => {
|
||||
if (Array.isArray(paramsStep)) return paramsStep[0];
|
||||
return paramsStep;
|
||||
if (Array.isArray(paramsStep)) return paramsStep[0];
|
||||
return paramsStep;
|
||||
};
|
||||
|
||||
const getInstallationParams = async (context: GetServerSidePropsContext): Promise<{ parsedAppSlug: string; parsedStepParam: string | undefined; parsedTeamIdParam: number | undefined; sessionId: number | null }> => {
|
||||
const { query, params, req } = context;
|
||||
const parsedAppSlug = z.coerce.string().parse(query?.slug);
|
||||
const parsedStepParam = z.string().optional().parse(getParsedStep(params?.step));
|
||||
const parsedTeamIdParam = z.coerce.number().optional().parse(query?.teamId);
|
||||
const session = await getServerSession({ req });
|
||||
const sessionId = (session?.user as { id?: number })?.id ?? null;
|
||||
return { parsedAppSlug, parsedStepParam, parsedTeamIdParam, sessionId };
|
||||
const getInstallationParams = async (
|
||||
context: GetServerSidePropsContext
|
||||
): Promise<{
|
||||
parsedAppSlug: string;
|
||||
parsedStepParam: string | undefined;
|
||||
parsedTeamIdParam: number | undefined;
|
||||
sessionId: number | null;
|
||||
}> => {
|
||||
const { query, params, req } = context;
|
||||
const parsedAppSlug = z.coerce.string().parse(query?.slug);
|
||||
const parsedStepParam = z.string().optional().parse(getParsedStep(params?.step));
|
||||
const parsedTeamIdParam = z.coerce.number().optional().parse(query?.teamId);
|
||||
const session = await getServerSession({ req });
|
||||
const sessionId = (session?.user as { id?: number })?.id ?? null;
|
||||
return { parsedAppSlug, parsedStepParam, parsedTeamIdParam, sessionId };
|
||||
};
|
||||
|
||||
export const getServerSideProps = async (context: GetServerSidePropsContext): Promise<GetServerSidePropsResult<OnboardingPageProps>> => {
|
||||
const { parsedAppSlug, parsedStepParam, parsedTeamIdParam, sessionId } = await getInstallationParams(context);
|
||||
if (!sessionId) return { redirect: { permanent: false, destination: "/auth/login" } };
|
||||
export const getServerSideProps = async (
|
||||
context: GetServerSidePropsContext
|
||||
): Promise<GetServerSidePropsResult<OnboardingPageProps>> => {
|
||||
const { parsedAppSlug, parsedStepParam, parsedTeamIdParam, sessionId } =
|
||||
await getInstallationParams(context);
|
||||
if (!sessionId) return { redirect: { permanent: false, destination: "/auth/login" } };
|
||||
|
||||
const { app, appMetadata, redirect: appRedirect } = await getAppAndMetadata(parsedAppSlug);
|
||||
if (appRedirect) return appRedirect;
|
||||
const { app, appMetadata, redirect: appRedirect } = await getAppAndMetadata(parsedAppSlug);
|
||||
if (appRedirect) return appRedirect;
|
||||
|
||||
const user = await getUser(sessionId);
|
||||
if (!user?.username || !appMetadata) return { redirect: { permanent: false, destination: "/apps" } };
|
||||
const appMetadataFinal = appMetadata;
|
||||
const user = await getUser(sessionId);
|
||||
if (!user?.username || !appMetadata) return { redirect: { permanent: false, destination: "/apps" } };
|
||||
const appMetadataFinal = appMetadata;
|
||||
|
||||
const showEventTypesStep = appMetadataFinal.extendsFeature === "EventType" || isConferencingApp(appMetadataFinal.categories);
|
||||
const { userTeams, isOrg, redirect: teamRedirect } = await prepareUserTeams(user, parsedTeamIdParam);
|
||||
if (teamRedirect) return teamRedirect;
|
||||
const { step: initialStep, redirect: stepRedirect } = getInitialStep(parsedStepParam, !!userTeams.length, showEventTypesStep, parsedAppSlug, !!appMetadataFinal.isOAuth);
|
||||
if (stepRedirect) return stepRedirect;
|
||||
if (!initialStep) {
|
||||
return { redirect: { permanent: false, destination: "/apps" } };
|
||||
const showEventTypesStep =
|
||||
appMetadataFinal.extendsFeature === "EventType" || isConferencingApp(appMetadataFinal.categories);
|
||||
const { userTeams, isOrg, redirect: teamRedirect } = await prepareUserTeams(user, parsedTeamIdParam);
|
||||
if (teamRedirect) return teamRedirect;
|
||||
const { step: initialStep, redirect: stepRedirect } = getInitialStep(
|
||||
parsedStepParam,
|
||||
!!userTeams.length,
|
||||
showEventTypesStep,
|
||||
parsedAppSlug,
|
||||
!!appMetadataFinal.isOAuth
|
||||
);
|
||||
if (stepRedirect) return stepRedirect;
|
||||
if (!initialStep) {
|
||||
return { redirect: { permanent: false, destination: "/apps" } };
|
||||
}
|
||||
|
||||
let initialStepValidated: (typeof STEPS)[number];
|
||||
try {
|
||||
initialStepValidated = z.enum(STEPS).parse(initialStep);
|
||||
} catch {
|
||||
return { redirect: { permanent: false, destination: "/apps" } };
|
||||
}
|
||||
|
||||
const appInstalls = await getAppInstallsBySlug(
|
||||
parsedAppSlug,
|
||||
user.id,
|
||||
userTeams.map(({ id }: MinimalTeam) => id)
|
||||
);
|
||||
const { credentialId, redirect: credRedirect } = await getCredential(
|
||||
parsedTeamIdParam,
|
||||
appInstalls,
|
||||
user,
|
||||
initialStepValidated,
|
||||
appMetadataFinal,
|
||||
parsedAppSlug
|
||||
);
|
||||
if (credRedirect) return credRedirect;
|
||||
|
||||
let eventTypeGroups = null;
|
||||
if (initialStepValidated === AppOnboardingSteps.EVENT_TYPES_STEP) {
|
||||
if (!showEventTypesStep) {
|
||||
return {
|
||||
redirect: {
|
||||
permanent: false,
|
||||
destination: `/apps/installed/${appMetadataFinal.categories[0]}?hl=${appMetadataFinal.slug}`,
|
||||
},
|
||||
};
|
||||
}
|
||||
eventTypeGroups = await getEventTypeGroupsForStep(
|
||||
user,
|
||||
userTeams,
|
||||
parsedTeamIdParam,
|
||||
isOrg,
|
||||
isConferencingApp(appMetadataFinal.categories)
|
||||
);
|
||||
if (!credentialId) return { redirect: { permanent: false, destination: "/apps" } };
|
||||
}
|
||||
|
||||
let initialStepValidated: (typeof STEPS)[number];
|
||||
try {
|
||||
initialStepValidated = z.enum(STEPS).parse(initialStep);
|
||||
} catch {
|
||||
return { redirect: { permanent: false, destination: "/apps" } };
|
||||
}
|
||||
const personalAccount = {
|
||||
id: user.id,
|
||||
name: user.name,
|
||||
avatarUrl: user.avatarUrl,
|
||||
alreadyInstalled: appInstalls.some((install) => !install.teamId && install.userId === user.id),
|
||||
};
|
||||
const teams = getTeamsInstalled(!!user.teams.length, userTeams, appInstalls);
|
||||
|
||||
const appInstalls = await getAppInstallsBySlug(parsedAppSlug, user.id, userTeams.map(({ id }: MinimalTeam) => id));
|
||||
const { credentialId, redirect: credRedirect } = await getCredential(parsedTeamIdParam, appInstalls, user, initialStepValidated, appMetadataFinal, parsedAppSlug);
|
||||
if (credRedirect) return credRedirect;
|
||||
|
||||
let eventTypeGroups = null;
|
||||
if (initialStepValidated === AppOnboardingSteps.EVENT_TYPES_STEP) {
|
||||
if (!showEventTypesStep) {
|
||||
return { redirect: { permanent: false, destination: `/apps/installed/${appMetadataFinal.categories[0]}?hl=${appMetadataFinal.slug}` } };
|
||||
}
|
||||
eventTypeGroups = await getEventTypeGroupsForStep(user, userTeams, parsedTeamIdParam, isOrg, isConferencingApp(appMetadataFinal.categories));
|
||||
if (!credentialId) return { redirect: { permanent: false, destination: "/apps" } };
|
||||
}
|
||||
|
||||
const personalAccount = {
|
||||
id: user.id, name: user.name, avatarUrl: user.avatarUrl,
|
||||
alreadyInstalled: appInstalls.some((install) => !install.teamId && install.userId === user.id),
|
||||
};
|
||||
const teams = getTeamsInstalled(!!user.teams.length, userTeams, appInstalls);
|
||||
|
||||
return {
|
||||
props: {
|
||||
app, appMetadata: appMetadataFinal, showEventTypesStep, step: initialStepValidated, personalAccount, teams,
|
||||
eventTypeGroups, userName: user.username, credentialId: credentialId || undefined,
|
||||
isConferencing: isConferencingApp(appMetadataFinal.categories), isOrg,
|
||||
installableOnTeams: !!appMetadataFinal?.concurrentMeetings || !isConferencingApp(appMetadataFinal.categories),
|
||||
} as OnboardingPageProps,
|
||||
};
|
||||
return {
|
||||
props: {
|
||||
app,
|
||||
appMetadata: appMetadataFinal,
|
||||
showEventTypesStep,
|
||||
step: initialStepValidated,
|
||||
personalAccount,
|
||||
teams,
|
||||
eventTypeGroups,
|
||||
userName: user.username,
|
||||
credentialId: credentialId || undefined,
|
||||
isConferencing: isConferencingApp(appMetadataFinal.categories),
|
||||
isOrg,
|
||||
installableOnTeams:
|
||||
!!appMetadataFinal?.concurrentMeetings || !isConferencingApp(appMetadataFinal.categories),
|
||||
} as OnboardingPageProps,
|
||||
};
|
||||
};
|
||||
@@ -82,8 +82,9 @@ async function getUserPageProps(context: GetServerSidePropsContext) {
|
||||
redirect: {
|
||||
permanent: false,
|
||||
// App Router doesn't have access to the current path directly, so we build it manually
|
||||
destination: `${redirectWithOriginAndSearchString.origin ?? ""}/d/${link}/${slug}${redirectWithOriginAndSearchString.searchString
|
||||
}`,
|
||||
destination: `${redirectWithOriginAndSearchString.origin ?? ""}/d/${link}/${slug}${
|
||||
redirectWithOriginAndSearchString.searchString
|
||||
}`,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -96,8 +96,8 @@ export function getThemeProviderProps({
|
||||
const themeSupport = isBookingPage
|
||||
? ThemeSupport.Booking
|
||||
: props.isThemeSupported === false
|
||||
? ThemeSupport.None
|
||||
: ThemeSupport.App;
|
||||
? ThemeSupport.None
|
||||
: ThemeSupport.App;
|
||||
|
||||
const themeQueryParam = searchParams?.get("theme") ?? "";
|
||||
const themeParsed = z.enum(["light", "dark", "system", "auto"]).safeParse(themeQueryParam);
|
||||
@@ -133,10 +133,10 @@ export function getThemeProviderProps({
|
||||
// Even though it's recommended to use different namespaces when you want to theme differently on the same page but if the embeds are on different pages, the problem can still arise
|
||||
`embed-theme-${embedNamespace}${appearanceIdSuffix}${embedExplicitlySetThemeSuffix}`
|
||||
: themeSupport === ThemeSupport.App
|
||||
? "app-theme"
|
||||
: isBookingPageThemeSupportRequired
|
||||
? `booking-theme${appearanceIdSuffix}`
|
||||
: undefined;
|
||||
? "app-theme"
|
||||
: isBookingPageThemeSupportRequired
|
||||
? `booking-theme${appearanceIdSuffix}`
|
||||
: undefined;
|
||||
|
||||
const themeProviderProps = {
|
||||
storageKey,
|
||||
|
||||
@@ -29,7 +29,7 @@ const createTestContext = (overrides?: {
|
||||
},
|
||||
},
|
||||
query: overrides?.query || {},
|
||||
} as unknown as GetServerSidePropsContext);
|
||||
}) as unknown as GetServerSidePropsContext;
|
||||
|
||||
const createTestRedirectParams = (overrides?: {
|
||||
slugs?: string[];
|
||||
|
||||
@@ -8,7 +8,11 @@ export const useSubscribeTeamToStripe = (
|
||||
onSuccess,
|
||||
onError,
|
||||
teamId,
|
||||
}: { teamId?: number | null; onSuccess: (redirectUrl: string) => void; onError: () => void } = {
|
||||
}: {
|
||||
teamId?: number | null;
|
||||
onSuccess: (redirectUrl: string) => void;
|
||||
onError: () => void;
|
||||
} = {
|
||||
onSuccess: () => {
|
||||
return;
|
||||
},
|
||||
|
||||
@@ -8,7 +8,11 @@ export const useUpgradeTeamSubscriptionInStripe = (
|
||||
onSuccess,
|
||||
onError,
|
||||
teamId,
|
||||
}: { teamId?: number | null; onSuccess: (redirectUrl: string) => void; onError: () => void } = {
|
||||
}: {
|
||||
teamId?: number | null;
|
||||
onSuccess: (redirectUrl: string) => void;
|
||||
onError: () => void;
|
||||
} = {
|
||||
onSuccess: () => {
|
||||
return;
|
||||
},
|
||||
|
||||
@@ -143,7 +143,11 @@ export const useSubscribeTeamToStripe = (
|
||||
onSuccess,
|
||||
onError,
|
||||
teamId,
|
||||
}: { teamId?: number | null; onSuccess: (redirectUrl: string) => void; onError: () => void } = {
|
||||
}: {
|
||||
teamId?: number | null;
|
||||
onSuccess: (redirectUrl: string) => void;
|
||||
onError: () => void;
|
||||
} = {
|
||||
onSuccess: () => {
|
||||
return;
|
||||
},
|
||||
@@ -180,7 +184,11 @@ export const useUpgradeTeamSubscriptionInStripe = (
|
||||
onSuccess,
|
||||
onError,
|
||||
teamId,
|
||||
}: { teamId?: number | null; onSuccess: (redirectUrl: string) => void; onError: () => void } = {
|
||||
}: {
|
||||
teamId?: number | null;
|
||||
onSuccess: (redirectUrl: string) => void;
|
||||
onError: () => void;
|
||||
} = {
|
||||
onSuccess: () => {
|
||||
return;
|
||||
},
|
||||
|
||||
@@ -62,14 +62,14 @@ export const getServerSideProps = async (context: GetServerSidePropsContext) =>
|
||||
session?.user?.id
|
||||
);
|
||||
|
||||
if (!eventData) {
|
||||
return {
|
||||
notFound: true,
|
||||
} as const;
|
||||
}
|
||||
|
||||
if (!eventData) {
|
||||
return {
|
||||
props: {
|
||||
notFound: true,
|
||||
} as const;
|
||||
}
|
||||
|
||||
return {
|
||||
props: {
|
||||
eventData,
|
||||
entity: eventData.entity,
|
||||
eventTypeId: eventData.id,
|
||||
|
||||
@@ -26,9 +26,8 @@ const querySchema = z.object({
|
||||
export const getServerSideProps = async (ctx: GetServerSidePropsContext) => {
|
||||
const prisma = await import("@calcom/prisma").then((mod) => mod.default);
|
||||
const featuresRepository = new FeaturesRepository(prisma);
|
||||
const emailVerificationEnabled = await featuresRepository.checkIfFeatureIsEnabledGlobally(
|
||||
"email-verification"
|
||||
);
|
||||
const emailVerificationEnabled =
|
||||
await featuresRepository.checkIfFeatureIsEnabledGlobally("email-verification");
|
||||
const signupDisabled = await featuresRepository.checkIfFeatureIsEnabledGlobally("disable-signup");
|
||||
const onboardingV3Enabled = await featuresRepository.checkIfFeatureIsEnabledGlobally("onboarding-v3");
|
||||
|
||||
@@ -200,22 +199,25 @@ export const getServerSideProps = async (ctx: GetServerSidePropsContext) => {
|
||||
props: {
|
||||
...props,
|
||||
token,
|
||||
prepopulateFormValues: !isOrgInviteByLink && isValidEmail
|
||||
? {
|
||||
email: verificationToken.identifier,
|
||||
username: isOrganizationOrATeamInOrganization
|
||||
? getOrgUsernameFromEmail(
|
||||
verificationToken.identifier,
|
||||
(isOrganization
|
||||
? tokenTeam.organizationSettings?.orgAutoAcceptEmail
|
||||
: parentOrgSettings?.orgAutoAcceptEmail) || ""
|
||||
)
|
||||
: slugify(username),
|
||||
}
|
||||
: null,
|
||||
prepopulateFormValues:
|
||||
!isOrgInviteByLink && isValidEmail
|
||||
? {
|
||||
email: verificationToken.identifier,
|
||||
username: isOrganizationOrATeamInOrganization
|
||||
? getOrgUsernameFromEmail(
|
||||
verificationToken.identifier,
|
||||
(isOrganization
|
||||
? tokenTeam.organizationSettings?.orgAutoAcceptEmail
|
||||
: parentOrgSettings?.orgAutoAcceptEmail) || ""
|
||||
)
|
||||
: slugify(username),
|
||||
}
|
||||
: null,
|
||||
orgSlug,
|
||||
orgAutoAcceptEmail: isOrgInviteByLink
|
||||
? tokenTeam?.organizationSettings?.orgAutoAcceptEmail ?? parentOrgSettings?.orgAutoAcceptEmail ?? null
|
||||
? (tokenTeam?.organizationSettings?.orgAutoAcceptEmail ??
|
||||
parentOrgSettings?.orgAutoAcceptEmail ??
|
||||
null)
|
||||
: null,
|
||||
},
|
||||
};
|
||||
|
||||
@@ -61,7 +61,12 @@ export const getServerSideProps = async (context: GetServerSidePropsContext) =>
|
||||
// Redirect if no routing form response and redirect URL is configured
|
||||
// Don't redirect if this is a reschedule flow or seated booking flow
|
||||
const hasRoutingFormResponse = query["cal.routingFormResponseId"] || query["cal.queuedFormResponseId"];
|
||||
if (!hasRoutingFormResponse && !rescheduleUid && !bookingUid && eventData.redirectUrlOnNoRoutingFormResponse) {
|
||||
if (
|
||||
!hasRoutingFormResponse &&
|
||||
!rescheduleUid &&
|
||||
!bookingUid &&
|
||||
eventData.redirectUrlOnNoRoutingFormResponse
|
||||
) {
|
||||
return {
|
||||
redirect: {
|
||||
destination: eventData.redirectUrlOnNoRoutingFormResponse,
|
||||
@@ -106,7 +111,11 @@ export const getServerSideProps = async (context: GetServerSidePropsContext) =>
|
||||
const log = logger.getSubLogger({ prefix: ["team-event-ssr", `${teamSlug}/${meetingSlug}`] });
|
||||
const featureRepo = new FeaturesRepository(prisma);
|
||||
const [eventHostsUserData, crmResult, teamHasApiV2Route, booking] = await Promise.all([
|
||||
getUsersData(team.isPrivate, eventTypeId, eventData.hosts.map((h) => h.user)).catch((err) => {
|
||||
getUsersData(
|
||||
team.isPrivate,
|
||||
eventTypeId,
|
||||
eventData.hosts.map((h) => h.user)
|
||||
).catch((err) => {
|
||||
log.error("Failed to get users data", err);
|
||||
throw err;
|
||||
}),
|
||||
|
||||
@@ -5,6 +5,5 @@ type GetSSRResult<TProps> =
|
||||
|
||||
type GetSSRFn<TProps> = (...args: any[]) => Promise<GetSSRResult<TProps>>;
|
||||
|
||||
export type inferSSRProps<TFn extends GetSSRFn<any>> = TFn extends GetSSRFn<infer TProps>
|
||||
? NonNullable<TProps>
|
||||
: never;
|
||||
export type inferSSRProps<TFn extends GetSSRFn<any>> =
|
||||
TFn extends GetSSRFn<infer TProps> ? NonNullable<TProps> : never;
|
||||
@@ -223,9 +223,9 @@ export async function getServerSideProps(context: GetServerSidePropsContext) {
|
||||
});
|
||||
|
||||
const isAttendee = sessionUserEmail
|
||||
? bookingObj.attendees?.some(
|
||||
? (bookingObj.attendees?.some(
|
||||
(attendee) => attendee.email.toLowerCase() === sessionUserEmail.toLowerCase()
|
||||
) ?? false
|
||||
) ?? false)
|
||||
: false;
|
||||
|
||||
// set meetingPassword for guests
|
||||
|
||||
@@ -66,7 +66,7 @@ function SingleAppPage(props: AppDataProps) {
|
||||
// privacy="https://zoom.us/privacy"
|
||||
body={
|
||||
<>
|
||||
{ }
|
||||
{}
|
||||
{/* biome-ignore lint/security/noDangerouslySetInnerHtml: Content is sanitized via markdownToSafeHTML */}
|
||||
<div dangerouslySetInnerHTML={{ __html: markdownToSafeHTML(source.content) }} />
|
||||
</>
|
||||
|
||||
@@ -136,87 +136,89 @@ export function AppCard({ app, credentials, searchText, userAdminTeams }: AppCar
|
||||
color="secondary"
|
||||
className="flex w-32 grow justify-center"
|
||||
href={`/apps/${app.slug}`}
|
||||
onClick={() => { posthog.capture("app_card_details_clicked", { slug: app.slug }) }}
|
||||
onClick={() => {
|
||||
posthog.capture("app_card_details_clicked", { slug: app.slug });
|
||||
}}
|
||||
data-testid={`app-store-app-card-${app.slug}`}>
|
||||
{t("details")}
|
||||
</Button>
|
||||
{app.isGlobal ||
|
||||
(credentials && credentials.length > 0 && allowedMultipleInstalls) ||
|
||||
(credentials && credentials.length > 0 && isRedirectApp(app.slug))
|
||||
(credentials && credentials.length > 0 && allowedMultipleInstalls) ||
|
||||
(credentials && credentials.length > 0 && isRedirectApp(app.slug))
|
||||
? !app.isGlobal && (
|
||||
<InstallAppButton
|
||||
type={app.type}
|
||||
teamsPlanRequired={app.teamsPlanRequired}
|
||||
disableInstall={!!app.dependencies && !app.dependencyData?.some((data) => !data.installed)}
|
||||
wrapperClassName="[@media(max-width:260px)]:w-full"
|
||||
render={({ useDefaultComponent, ...props }) => {
|
||||
if (useDefaultComponent) {
|
||||
props = {
|
||||
...props,
|
||||
onClick: () => {
|
||||
handleAppInstall();
|
||||
},
|
||||
loading: mutation.isPending,
|
||||
};
|
||||
} else {
|
||||
const originalOnClick = props.onClick;
|
||||
props = {
|
||||
...props,
|
||||
onClick: (e) => {
|
||||
posthog.capture("app_install_button_clicked", {
|
||||
slug: app.slug,
|
||||
app_type: app.type,
|
||||
is_redirect: isRedirectApp(app.slug),
|
||||
is_conferencing: isConferencing(app.categories || []),
|
||||
});
|
||||
originalOnClick?.(e);
|
||||
},
|
||||
};
|
||||
}
|
||||
return (
|
||||
<InstallAppButtonChild paid={app.paid} isRedirect={isRedirectApp(app.slug)} {...props} />
|
||||
);
|
||||
}}
|
||||
/>
|
||||
)
|
||||
<InstallAppButton
|
||||
type={app.type}
|
||||
teamsPlanRequired={app.teamsPlanRequired}
|
||||
disableInstall={!!app.dependencies && !app.dependencyData?.some((data) => !data.installed)}
|
||||
wrapperClassName="[@media(max-width:260px)]:w-full"
|
||||
render={({ useDefaultComponent, ...props }) => {
|
||||
if (useDefaultComponent) {
|
||||
props = {
|
||||
...props,
|
||||
onClick: () => {
|
||||
handleAppInstall();
|
||||
},
|
||||
loading: mutation.isPending,
|
||||
};
|
||||
} else {
|
||||
const originalOnClick = props.onClick;
|
||||
props = {
|
||||
...props,
|
||||
onClick: (e) => {
|
||||
posthog.capture("app_install_button_clicked", {
|
||||
slug: app.slug,
|
||||
app_type: app.type,
|
||||
is_redirect: isRedirectApp(app.slug),
|
||||
is_conferencing: isConferencing(app.categories || []),
|
||||
});
|
||||
originalOnClick?.(e);
|
||||
},
|
||||
};
|
||||
}
|
||||
return (
|
||||
<InstallAppButtonChild paid={app.paid} isRedirect={isRedirectApp(app.slug)} {...props} />
|
||||
);
|
||||
}}
|
||||
/>
|
||||
)
|
||||
: credentials &&
|
||||
!appInstalled && (
|
||||
<InstallAppButton
|
||||
type={app.type}
|
||||
wrapperClassName="[@media(max-width:260px)]:w-full"
|
||||
disableInstall={!!app.dependencies && app.dependencyData?.some((data) => !data.installed)}
|
||||
teamsPlanRequired={app.teamsPlanRequired}
|
||||
render={({ useDefaultComponent, ...props }) => {
|
||||
if (useDefaultComponent) {
|
||||
props = {
|
||||
...props,
|
||||
disabled: !!props.disabled,
|
||||
onClick: () => {
|
||||
handleAppInstall();
|
||||
},
|
||||
loading: mutation.isPending,
|
||||
};
|
||||
} else {
|
||||
const originalOnClick = props.onClick;
|
||||
props = {
|
||||
...props,
|
||||
onClick: (e) => {
|
||||
posthog.capture("app_install_button_clicked", {
|
||||
slug: app.slug,
|
||||
app_type: app.type,
|
||||
is_redirect: isRedirectApp(app.slug),
|
||||
is_conferencing: isConferencing(app.categories || []),
|
||||
});
|
||||
originalOnClick?.(e);
|
||||
},
|
||||
};
|
||||
}
|
||||
return (
|
||||
<InstallAppButtonChild paid={app.paid} isRedirect={isRedirectApp(app.slug)} {...props} />
|
||||
);
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
!appInstalled && (
|
||||
<InstallAppButton
|
||||
type={app.type}
|
||||
wrapperClassName="[@media(max-width:260px)]:w-full"
|
||||
disableInstall={!!app.dependencies && app.dependencyData?.some((data) => !data.installed)}
|
||||
teamsPlanRequired={app.teamsPlanRequired}
|
||||
render={({ useDefaultComponent, ...props }) => {
|
||||
if (useDefaultComponent) {
|
||||
props = {
|
||||
...props,
|
||||
disabled: !!props.disabled,
|
||||
onClick: () => {
|
||||
handleAppInstall();
|
||||
},
|
||||
loading: mutation.isPending,
|
||||
};
|
||||
} else {
|
||||
const originalOnClick = props.onClick;
|
||||
props = {
|
||||
...props,
|
||||
onClick: (e) => {
|
||||
posthog.capture("app_install_button_clicked", {
|
||||
slug: app.slug,
|
||||
app_type: app.type,
|
||||
is_redirect: isRedirectApp(app.slug),
|
||||
is_conferencing: isConferencing(app.categories || []),
|
||||
});
|
||||
originalOnClick?.(e);
|
||||
},
|
||||
};
|
||||
}
|
||||
return (
|
||||
<InstallAppButtonChild paid={app.paid} isRedirect={isRedirectApp(app.slug)} {...props} />
|
||||
);
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
<div className="max-w-44 absolute right-0 mr-4 flex flex-wrap justify-end gap-1">
|
||||
{appAdded > 0 && !isRedirectApp(app.slug) ? (
|
||||
|
||||
@@ -232,10 +232,7 @@ const OnboardingPage = ({
|
||||
};
|
||||
|
||||
return (
|
||||
<div
|
||||
key={pathname}
|
||||
className="text-emphasis min-h-screen px-4"
|
||||
data-testid="onboarding">
|
||||
<div key={pathname} className="text-emphasis min-h-screen px-4" data-testid="onboarding">
|
||||
<div className="mx-auto py-6 sm:px-4 md:py-24">
|
||||
<div className="relative">
|
||||
<div className="sm:mx-auto sm:w-full sm:max-w-[600px]" ref={formPortalRef}>
|
||||
|
||||
@@ -11,15 +11,8 @@ import { z } from "zod";
|
||||
|
||||
import { SAMLLogin } from "@calcom/web/modules/auth/components/SAMLLogin";
|
||||
import { ErrorCode } from "@calcom/features/auth/lib/ErrorCode";
|
||||
import {
|
||||
LastUsed,
|
||||
useLastUsed,
|
||||
} from "@calcom/web/modules/auth/hooks/useLastUsed";
|
||||
import {
|
||||
HOSTED_CAL_FEATURES,
|
||||
WEBAPP_URL,
|
||||
WEBSITE_URL,
|
||||
} from "@calcom/lib/constants";
|
||||
import { LastUsed, useLastUsed } from "@calcom/web/modules/auth/hooks/useLastUsed";
|
||||
import { HOSTED_CAL_FEATURES, WEBAPP_URL, WEBSITE_URL } from "@calcom/lib/constants";
|
||||
import { emailRegex } from "@calcom/lib/emailSchema";
|
||||
import { getSafeRedirectUrl } from "@calcom/lib/getSafeRedirectUrl";
|
||||
import { useCompatSearchParams } from "@calcom/lib/hooks/useCompatSearchParams";
|
||||
@@ -47,11 +40,7 @@ interface LoginValues {
|
||||
}
|
||||
|
||||
const GoogleIcon = () => (
|
||||
<img
|
||||
className="mr-2 w-4 h-4 text-subtle"
|
||||
src="/google-icon-colored.svg"
|
||||
alt="Continue with Google Icon"
|
||||
/>
|
||||
<img className="mr-2 w-4 h-4 text-subtle" src="/google-icon-colored.svg" alt="Continue with Google Icon" />
|
||||
);
|
||||
export type PageProps = inferSSRProps<typeof getServerSideProps>;
|
||||
export default function Login({
|
||||
@@ -71,17 +60,13 @@ export default function Login({
|
||||
.string()
|
||||
.min(1, `${t("error_required_field")}`)
|
||||
.regex(emailRegex, `${t("enter_valid_email")}`),
|
||||
...(totpEmail
|
||||
? {}
|
||||
: { password: z.string().min(1, `${t("error_required_field")}`) }),
|
||||
...(totpEmail ? {} : { password: z.string().min(1, `${t("error_required_field")}`) }),
|
||||
})
|
||||
// Passthrough other fields like totpCode
|
||||
.passthrough();
|
||||
const methods = useForm<LoginValues>({ resolver: zodResolver(formSchema) });
|
||||
const { register, formState } = methods;
|
||||
const [twoFactorRequired, setTwoFactorRequired] = useState(
|
||||
!!totpEmail || false
|
||||
);
|
||||
const [twoFactorRequired, setTwoFactorRequired] = useState(!!totpEmail || false);
|
||||
const [twoFactorLostAccess, setTwoFactorLostAccess] = useState(false);
|
||||
const [errorMessage, setErrorMessage] = useState<string | null>(null);
|
||||
const [lastUsed, setLastUsed] = useLastUsed();
|
||||
@@ -90,15 +75,9 @@ export default function Login({
|
||||
// [ErrorCode.SecondFactorRequired]: t("2fa_enabled_instructions"),
|
||||
// Don't leak information about whether an email is registered or not
|
||||
[ErrorCode.IncorrectEmailPassword]: t("incorrect_email_password"),
|
||||
[ErrorCode.IncorrectTwoFactorCode]: `${t("incorrect_2fa_code")} ${t(
|
||||
"please_try_again"
|
||||
)}`,
|
||||
[ErrorCode.InternalServerError]: `${t("something_went_wrong")} ${t(
|
||||
"please_try_again_and_contact_us"
|
||||
)}`,
|
||||
[ErrorCode.ThirdPartyIdentityProviderEnabled]: t(
|
||||
"account_created_with_identity_provider"
|
||||
),
|
||||
[ErrorCode.IncorrectTwoFactorCode]: `${t("incorrect_2fa_code")} ${t("please_try_again")}`,
|
||||
[ErrorCode.InternalServerError]: `${t("something_went_wrong")} ${t("please_try_again_and_contact_us")}`,
|
||||
[ErrorCode.ThirdPartyIdentityProviderEnabled]: t("account_created_with_identity_provider"),
|
||||
};
|
||||
|
||||
let callbackUrl = searchParams?.get("callbackUrl") || "";
|
||||
@@ -138,8 +117,7 @@ export default function Login({
|
||||
setErrorMessage(null);
|
||||
}}
|
||||
StartIcon="arrow-left"
|
||||
color="minimal"
|
||||
>
|
||||
color="minimal">
|
||||
{t("go_back")}
|
||||
</Button>
|
||||
{!twoFactorLostAccess ? (
|
||||
@@ -150,8 +128,7 @@ export default function Login({
|
||||
methods.setValue("totpCode", "");
|
||||
}}
|
||||
StartIcon="lock"
|
||||
color="minimal"
|
||||
>
|
||||
color="minimal">
|
||||
{t("lost_access")}
|
||||
</Button>
|
||||
) : null}
|
||||
@@ -163,8 +140,7 @@ export default function Login({
|
||||
onClick={() => {
|
||||
window.location.replace("/");
|
||||
}}
|
||||
color="minimal"
|
||||
>
|
||||
color="minimal">
|
||||
{t("cancel")}
|
||||
</Button>
|
||||
);
|
||||
@@ -182,18 +158,14 @@ export default function Login({
|
||||
else if (!res.error) {
|
||||
setLastUsed("credentials");
|
||||
router.push(callbackUrl);
|
||||
} else if (res.error === ErrorCode.SecondFactorRequired)
|
||||
setTwoFactorRequired(true);
|
||||
else if (res.error === ErrorCode.IncorrectBackupCode)
|
||||
setErrorMessage(t("incorrect_backup_code"));
|
||||
else if (res.error === ErrorCode.MissingBackupCodes)
|
||||
setErrorMessage(t("missing_backup_codes"));
|
||||
} else if (res.error === ErrorCode.SecondFactorRequired) setTwoFactorRequired(true);
|
||||
else if (res.error === ErrorCode.IncorrectBackupCode) setErrorMessage(t("incorrect_backup_code"));
|
||||
else if (res.error === ErrorCode.MissingBackupCodes) setErrorMessage(t("missing_backup_codes"));
|
||||
// fallback if error not found
|
||||
else setErrorMessage(errorMessages[res.error] || t("something_went_wrong"));
|
||||
};
|
||||
|
||||
const { data, isPending, error } =
|
||||
trpc.viewer.public.ssoConnections.useQuery();
|
||||
const { data, isPending, error } = trpc.viewer.public.ssoConnections.useQuery();
|
||||
|
||||
useEffect(
|
||||
function refactorMeWithoutEffect() {
|
||||
@@ -218,12 +190,10 @@ export default function Login({
|
||||
? !totpEmail
|
||||
? TwoFactorFooter
|
||||
: ExternalTotpFooter
|
||||
: process.env.NEXT_PUBLIC_DISABLE_SIGNUP !== "true" &&
|
||||
searchParams?.get("register") !== "false"
|
||||
? LoginFooter
|
||||
: null
|
||||
}
|
||||
>
|
||||
: process.env.NEXT_PUBLIC_DISABLE_SIGNUP !== "true" && searchParams?.get("register") !== "false"
|
||||
? LoginFooter
|
||||
: null
|
||||
}>
|
||||
<FormProvider {...methods}>
|
||||
{!twoFactorRequired && (
|
||||
<>
|
||||
@@ -241,8 +211,7 @@ export default function Login({
|
||||
await signIn("google", {
|
||||
callbackUrl,
|
||||
});
|
||||
}}
|
||||
>
|
||||
}}>
|
||||
<span>{t("signin_with_google")}</span>
|
||||
{lastUsed === "google" && <LastUsed />}
|
||||
</Button>
|
||||
@@ -270,31 +239,19 @@ export default function Login({
|
||||
</>
|
||||
)}
|
||||
|
||||
<form
|
||||
onSubmit={methods.handleSubmit(onSubmit)}
|
||||
noValidate
|
||||
data-testid="login-form"
|
||||
>
|
||||
<form onSubmit={methods.handleSubmit(onSubmit)} noValidate data-testid="login-form">
|
||||
<div>
|
||||
<input
|
||||
defaultValue={csrfToken || undefined}
|
||||
type="hidden"
|
||||
hidden
|
||||
{...register("csrfToken")}
|
||||
/>
|
||||
<input defaultValue={csrfToken || undefined} type="hidden" hidden {...register("csrfToken")} />
|
||||
</div>
|
||||
<div className="stack-y-6">
|
||||
<div
|
||||
className={classNames("stack-y-6", {
|
||||
hidden: twoFactorRequired,
|
||||
})}
|
||||
>
|
||||
})}>
|
||||
<EmailField
|
||||
id="email"
|
||||
label={t("email_address")}
|
||||
defaultValue={
|
||||
totpEmail || (searchParams?.get("email") as string)
|
||||
}
|
||||
defaultValue={totpEmail || (searchParams?.get("email") as string)}
|
||||
placeholder="[email protected]"
|
||||
required
|
||||
autoComplete="email"
|
||||
@@ -312,33 +269,23 @@ export default function Login({
|
||||
<Link
|
||||
href="/auth/forgot-password"
|
||||
tabIndex={-1}
|
||||
className="text-sm font-medium text-default"
|
||||
>
|
||||
className="text-sm font-medium text-default">
|
||||
{t("forgot")}
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{twoFactorRequired ? (
|
||||
!twoFactorLostAccess ? (
|
||||
<TwoFactor center />
|
||||
) : (
|
||||
<BackupCode center />
|
||||
)
|
||||
) : null}
|
||||
{twoFactorRequired ? !twoFactorLostAccess ? <TwoFactor center /> : <BackupCode center /> : null}
|
||||
|
||||
{errorMessage && <Alert severity="error" title={errorMessage} />}
|
||||
<Button
|
||||
type="submit"
|
||||
color="secondary"
|
||||
disabled={formState.isSubmitting}
|
||||
className="justify-center w-full"
|
||||
>
|
||||
className="justify-center w-full">
|
||||
<span>{twoFactorRequired ? t("submit") : t("sign_in")}</span>
|
||||
{lastUsed === "credentials" && !twoFactorRequired && (
|
||||
<LastUsed className="text-gray-600" />
|
||||
)}
|
||||
{lastUsed === "credentials" && !twoFactorRequired && <LastUsed className="text-gray-600" />}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
@@ -29,11 +29,8 @@ export function Authorize() {
|
||||
const state = searchParams?.get("state") as string;
|
||||
const scope = searchParams?.get("scope") as string;
|
||||
const code_challenge = searchParams?.get("code_challenge") as string;
|
||||
const code_challenge_method = searchParams?.get(
|
||||
"code_challenge_method"
|
||||
) as string;
|
||||
const show_account_selector =
|
||||
searchParams?.get("show_account_selector") === "true";
|
||||
const code_challenge_method = searchParams?.get("code_challenge_method") as string;
|
||||
const show_account_selector = searchParams?.get("show_account_selector") === "true";
|
||||
|
||||
const queryString = searchParams?.toString();
|
||||
|
||||
@@ -58,31 +55,26 @@ export function Authorize() {
|
||||
);
|
||||
|
||||
const { data, isPending: isPendingProfiles } =
|
||||
trpc.viewer.loggedInViewerRouter.teamsAndUserProfilesQuery.useQuery(
|
||||
undefined,
|
||||
{
|
||||
enabled: show_account_selector,
|
||||
}
|
||||
);
|
||||
|
||||
const generateAuthCodeMutation =
|
||||
trpc.viewer.oAuth.generateAuthCode.useMutation({
|
||||
onSuccess: (data) => {
|
||||
window.location.href =
|
||||
data.redirectUrl ??
|
||||
`${client?.redirectUri}?code=${data.authorizationCode}&state=${state}`;
|
||||
},
|
||||
onError: (error) => {
|
||||
if (client?.redirectUri) {
|
||||
redirectToOAuthError({
|
||||
redirectUri: client.redirectUri,
|
||||
trpcError: error,
|
||||
state,
|
||||
});
|
||||
}
|
||||
},
|
||||
trpc.viewer.loggedInViewerRouter.teamsAndUserProfilesQuery.useQuery(undefined, {
|
||||
enabled: show_account_selector,
|
||||
});
|
||||
|
||||
const generateAuthCodeMutation = trpc.viewer.oAuth.generateAuthCode.useMutation({
|
||||
onSuccess: (data) => {
|
||||
window.location.href =
|
||||
data.redirectUrl ?? `${client?.redirectUri}?code=${data.authorizationCode}&state=${state}`;
|
||||
},
|
||||
onError: (error) => {
|
||||
if (client?.redirectUri) {
|
||||
redirectToOAuthError({
|
||||
redirectUri: client.redirectUri,
|
||||
trpcError: error,
|
||||
state,
|
||||
});
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
const mappedProfiles = data
|
||||
? data
|
||||
.filter((profile) => !profile.readOnly)
|
||||
@@ -130,11 +122,7 @@ export function Authorize() {
|
||||
return <div>{getClientError.message}</div>;
|
||||
}
|
||||
|
||||
if (
|
||||
isPendingGetClient ||
|
||||
(show_account_selector && isPendingProfiles) ||
|
||||
status !== "authenticated"
|
||||
) {
|
||||
if (isPendingGetClient || (show_account_selector && isPendingProfiles) || status !== "authenticated") {
|
||||
return <></>;
|
||||
}
|
||||
|
||||
@@ -147,9 +135,7 @@ export function Authorize() {
|
||||
return (
|
||||
<div className="flex justify-center pt-32">
|
||||
<div className="flex items-center space-x-3">
|
||||
<span className="text-lg font-medium text-gray-700">
|
||||
{t("authorizing")}
|
||||
</span>
|
||||
<span className="text-lg font-medium text-gray-700">{t("authorizing")}</span>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
@@ -169,11 +155,7 @@ export function Authorize() {
|
||||
<div className="relative -ml-6 w-24 h-24">
|
||||
<div className="flex absolute inset-0 justify-center items-center">
|
||||
<div className="bg-default flex h-[70px] w-[70px] items-center justify-center rounded-full">
|
||||
<img
|
||||
src="/cal-com-icon.svg"
|
||||
alt="Logo"
|
||||
className="w-16 h-16 rounded-full"
|
||||
/>
|
||||
<img src="/cal-com-icon.svg" alt="Logo" className="w-16 h-16 rounded-full" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -202,9 +184,7 @@ export function Authorize() {
|
||||
)}
|
||||
{show_account_selector && (
|
||||
<>
|
||||
<div className="mb-1 text-sm font-medium">
|
||||
{t("select_account_team")}
|
||||
</div>
|
||||
<div className="mb-1 text-sm font-medium">{t("select_account_team")}</div>
|
||||
<Select
|
||||
isSearchable={true}
|
||||
id="account-select"
|
||||
@@ -257,9 +237,7 @@ export function Authorize() {
|
||||
<div className="mb-1 text-sm font-medium">
|
||||
{t("allow_client_to_do", { clientName: client.name })}
|
||||
</div>
|
||||
<div className="text-sm">
|
||||
{t("oauth_access_information", { appName: APP_NAME })}
|
||||
</div>{" "}
|
||||
<div className="text-sm">{t("oauth_access_information", { appName: APP_NAME })}</div>{" "}
|
||||
</div>
|
||||
</div>
|
||||
<div className="-mx-9 mb-4 border-b border-subtle border-" />
|
||||
@@ -274,11 +252,8 @@ export function Authorize() {
|
||||
if (state) {
|
||||
params.set("state", state);
|
||||
}
|
||||
window.location.href = `${
|
||||
client.redirectUri
|
||||
}${separator}${params.toString()}`;
|
||||
}}
|
||||
>
|
||||
window.location.href = `${client.redirectUri}${separator}${params.toString()}`;
|
||||
}}>
|
||||
{t("go_back")}
|
||||
</Button>
|
||||
<Button
|
||||
@@ -291,13 +266,11 @@ export function Authorize() {
|
||||
? selectedAccount?.value.substring(5)
|
||||
: undefined, // team account starts with /team/<slug>
|
||||
codeChallenge: code_challenge || undefined,
|
||||
codeChallengeMethod:
|
||||
(code_challenge_method as "S256") || undefined,
|
||||
codeChallengeMethod: (code_challenge_method as "S256") || undefined,
|
||||
state,
|
||||
});
|
||||
}}
|
||||
data-testid="allow-button"
|
||||
>
|
||||
data-testid="allow-button">
|
||||
{t("allow")}
|
||||
</Button>
|
||||
</div>
|
||||
@@ -335,9 +308,7 @@ function buildOAuthErrorRedirectUrl({
|
||||
errorParams.append("state", state);
|
||||
}
|
||||
|
||||
return `${redirectUri}${
|
||||
redirectUri.includes("?") ? "&" : "?"
|
||||
}${errorParams.toString()}`;
|
||||
return `${redirectUri}${redirectUri.includes("?") ? "&" : "?"}${errorParams.toString()}`;
|
||||
}
|
||||
|
||||
function redirectToOAuthError({
|
||||
|
||||
@@ -18,7 +18,7 @@ const EMAIL_CLIENTS = [
|
||||
{
|
||||
name: "Gmail",
|
||||
icon: "/email-clients/gmail.svg",
|
||||
href: 'https://mail.google.com/mail/u/0/#search/%22api%2Fauth%2Fverify-email%22',
|
||||
href: "https://mail.google.com/mail/u/0/#search/%22api%2Fauth%2Fverify-email%22",
|
||||
},
|
||||
{
|
||||
name: "Outlook",
|
||||
|
||||
@@ -176,8 +176,8 @@ export default function Verify({ EMAIL_FROM }: { EMAIL_FROM?: string }) {
|
||||
{hasPaymentFailed
|
||||
? t("your_payment_failed")
|
||||
: isPremiumUsername
|
||||
? t("payment_successful")
|
||||
: t("check_your_inbox")}
|
||||
? t("payment_successful")
|
||||
: t("check_your_inbox")}
|
||||
</h3>
|
||||
{hasPaymentFailed && <p className="my-6">{t("account_created_premium_not_reserved")}</p>}
|
||||
<p className="text-muted dark:text-subtle text-base font-normal">
|
||||
|
||||
@@ -193,8 +193,18 @@ export const AvailabilityCTA = ({ canViewTeamAvailability }: AvailabilityCTAProp
|
||||
|
||||
const toggleGroupOptions = [
|
||||
{ value: "mine", label: t("my_availability") },
|
||||
...(canViewTeamAvailability ? [{ value: "team", label: t("team_availability"), onClick: () => { posthog.capture("team_availability_toggle_clicked") } }] : []),
|
||||
]
|
||||
...(canViewTeamAvailability
|
||||
? [
|
||||
{
|
||||
value: "team",
|
||||
label: t("team_availability"),
|
||||
onClick: () => {
|
||||
posthog.capture("team_availability_toggle_clicked");
|
||||
},
|
||||
},
|
||||
]
|
||||
: []),
|
||||
];
|
||||
|
||||
// Get a new searchParams string by merging the current
|
||||
// searchParams with a provided key/value pair
|
||||
|
||||
@@ -6,7 +6,8 @@ import { Suspense } from "react";
|
||||
import { Loader } from "@calcom/ui/components/skeleton";
|
||||
|
||||
const TroubleshooterClientOnly = dynamic(
|
||||
() => import("@calcom/web/modules/troubleshooter/components/Troubleshooter").then((mod) => mod.Troubleshooter),
|
||||
() =>
|
||||
import("@calcom/web/modules/troubleshooter/components/Troubleshooter").then((mod) => mod.Troubleshooter),
|
||||
{
|
||||
ssr: false,
|
||||
}
|
||||
|
||||
@@ -208,7 +208,9 @@ export function BlockedEntriesTable<T extends BlocklistEntry>({
|
||||
isPending={isDeleting}
|
||||
onConfirm={confirmDelete}>
|
||||
{t(
|
||||
isSystem ? "remove_value_from_system_blocklist_description" : "remove_value_from_blocklist_description"
|
||||
isSystem
|
||||
? "remove_value_from_system_blocklist_description"
|
||||
: "remove_value_from_blocklist_description"
|
||||
)}
|
||||
</ConfirmationDialogContent>
|
||||
</Dialog>
|
||||
|
||||
@@ -98,8 +98,8 @@ export function BlocklistEntryDetailsSheet<T extends BlocklistEntry>({
|
||||
{detailsData.entry.source === "MANUAL"
|
||||
? t("manual")
|
||||
: detailsData.entry.source === "FREE_DOMAIN_POLICY"
|
||||
? t("free_domain_policy")
|
||||
: t("automatic")}
|
||||
? t("free_domain_policy")
|
||||
: t("automatic")}
|
||||
</p>
|
||||
</div>
|
||||
</>
|
||||
|
||||
@@ -160,7 +160,11 @@ export function CreateBlocklistEntryModal({
|
||||
</div>
|
||||
|
||||
<DialogFooter className="mt-6">
|
||||
<Button type="button" color="secondary" onClick={handleClose} disabled={isSubmitting || isPending}>
|
||||
<Button
|
||||
type="button"
|
||||
color="secondary"
|
||||
onClick={handleClose}
|
||||
disabled={isSubmitting || isPending}>
|
||||
{t("cancel")}
|
||||
</Button>
|
||||
<Button type="submit" loading={isSubmitting || isPending} disabled={isSubmitting || isPending}>
|
||||
|
||||
@@ -14,114 +14,114 @@ import Link from "next/link";
|
||||
import { useState } from "react";
|
||||
|
||||
interface BookingHistoryProps {
|
||||
bookingUid: string;
|
||||
bookingUid: string;
|
||||
}
|
||||
|
||||
type TranslationComponent = {
|
||||
type: "link";
|
||||
href: string;
|
||||
type: "link";
|
||||
href: string;
|
||||
};
|
||||
|
||||
type TranslationWithParams = {
|
||||
key: string;
|
||||
params?: Record<string, string | number>;
|
||||
components?: TranslationComponent[];
|
||||
key: string;
|
||||
params?: Record<string, string | number>;
|
||||
components?: TranslationComponent[];
|
||||
};
|
||||
|
||||
type AuditLog = {
|
||||
id: string;
|
||||
action: string;
|
||||
type: string;
|
||||
timestamp: string;
|
||||
source: string;
|
||||
displayJson?: Record<string, unknown> | null;
|
||||
actionDisplayTitle: TranslationWithParams;
|
||||
displayFields?: Array<{ labelKey: string; valueKey?: string; value?: string; values?: string[] }> | null;
|
||||
actor: {
|
||||
type: AuditActorType;
|
||||
displayName: string | null;
|
||||
displayEmail: string | null;
|
||||
displayAvatar: string | null;
|
||||
};
|
||||
impersonatedBy?: {
|
||||
displayName: string;
|
||||
displayEmail: string | null;
|
||||
displayAvatar: string | null;
|
||||
} | null;
|
||||
hasError?: boolean;
|
||||
id: string;
|
||||
action: string;
|
||||
type: string;
|
||||
timestamp: string;
|
||||
source: string;
|
||||
displayJson?: Record<string, unknown> | null;
|
||||
actionDisplayTitle: TranslationWithParams;
|
||||
displayFields?: Array<{ labelKey: string; valueKey?: string; value?: string; values?: string[] }> | null;
|
||||
actor: {
|
||||
type: AuditActorType;
|
||||
displayName: string | null;
|
||||
displayEmail: string | null;
|
||||
displayAvatar: string | null;
|
||||
};
|
||||
impersonatedBy?: {
|
||||
displayName: string;
|
||||
displayEmail: string | null;
|
||||
displayAvatar: string | null;
|
||||
} | null;
|
||||
hasError?: boolean;
|
||||
};
|
||||
|
||||
interface BookingLogsFiltersProps {
|
||||
searchTerm: string;
|
||||
onSearchChange: (value: string) => void;
|
||||
actorFilter: string | null;
|
||||
onActorFilterChange: (value: string | null) => void;
|
||||
actorOptions: Array<{ label: string; value: string }>;
|
||||
searchTerm: string;
|
||||
onSearchChange: (value: string) => void;
|
||||
actorFilter: string | null;
|
||||
onActorFilterChange: (value: string | null) => void;
|
||||
actorOptions: Array<{ label: string; value: string }>;
|
||||
}
|
||||
|
||||
interface BookingLogsTimelineProps {
|
||||
logs: AuditLog[];
|
||||
logs: AuditLog[];
|
||||
}
|
||||
|
||||
const ACTION_ICON_MAP: Record<string, IconName> = {
|
||||
CREATED: "calendar",
|
||||
CANCELLED: "ban",
|
||||
REJECTED: "ban",
|
||||
ACCEPTED: "check",
|
||||
RESCHEDULED: "pencil",
|
||||
RESCHEDULE_REQUESTED: "pencil",
|
||||
REASSIGNMENT: "user-check",
|
||||
ATTENDEE_ADDED: "user-check",
|
||||
ATTENDEE_REMOVED: "user-check",
|
||||
LOCATION_CHANGED: "map-pin",
|
||||
NO_SHOW_UPDATED: "ban",
|
||||
CREATED: "calendar",
|
||||
CANCELLED: "ban",
|
||||
REJECTED: "ban",
|
||||
ACCEPTED: "check",
|
||||
RESCHEDULED: "pencil",
|
||||
RESCHEDULE_REQUESTED: "pencil",
|
||||
REASSIGNMENT: "user-check",
|
||||
ATTENDEE_ADDED: "user-check",
|
||||
ATTENDEE_REMOVED: "user-check",
|
||||
LOCATION_CHANGED: "map-pin",
|
||||
NO_SHOW_UPDATED: "ban",
|
||||
} as const;
|
||||
|
||||
const ACTOR_ROLE_LABEL_MAP: Record<AuditActorType, string | null> = {
|
||||
GUEST: "guest",
|
||||
ATTENDEE: "attendee",
|
||||
SYSTEM: null,
|
||||
USER: null,
|
||||
APP: null,
|
||||
GUEST: "guest",
|
||||
ATTENDEE: "attendee",
|
||||
SYSTEM: null,
|
||||
USER: null,
|
||||
APP: null,
|
||||
} as const;
|
||||
|
||||
function BookingLogsFilters({
|
||||
searchTerm,
|
||||
onSearchChange,
|
||||
actorFilter,
|
||||
onActorFilterChange,
|
||||
actorOptions,
|
||||
searchTerm,
|
||||
onSearchChange,
|
||||
actorFilter,
|
||||
onActorFilterChange,
|
||||
actorOptions,
|
||||
}: BookingLogsFiltersProps) {
|
||||
const { t } = useLocale();
|
||||
const { t } = useLocale();
|
||||
|
||||
return (
|
||||
<div className="flex flex-wrap gap-2 items-start">
|
||||
<div className="flex-1 min-w-[200px]">
|
||||
<FilterSearchField
|
||||
size="sm"
|
||||
value={searchTerm}
|
||||
onChange={(e) => onSearchChange(e.target.value)}
|
||||
containerClassName=""
|
||||
/>
|
||||
</div>
|
||||
return (
|
||||
<div className="flex flex-wrap gap-2 items-start">
|
||||
<div className="flex-1 min-w-[200px]">
|
||||
<FilterSearchField
|
||||
size="sm"
|
||||
value={searchTerm}
|
||||
onChange={(e) => onSearchChange(e.target.value)}
|
||||
containerClassName=""
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="min-w-[140px]">
|
||||
<Select
|
||||
size="sm"
|
||||
value={
|
||||
actorFilter
|
||||
? { label: `${t("actor")}: ${actorFilter}`, value: actorFilter }
|
||||
: { label: `${t("actor")}: ${t("all")}`, value: "" }
|
||||
}
|
||||
onChange={(option) => {
|
||||
if (!option) return;
|
||||
onActorFilterChange(option.value || null);
|
||||
}}
|
||||
options={[{ label: t("all"), value: "" }, ...actorOptions]}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
<div className="min-w-[140px]">
|
||||
<Select
|
||||
size="sm"
|
||||
value={
|
||||
actorFilter
|
||||
? { label: `${t("actor")}: ${actorFilter}`, value: actorFilter }
|
||||
: { label: `${t("actor")}: ${t("all")}`, value: "" }
|
||||
}
|
||||
onChange={(option) => {
|
||||
if (!option) return;
|
||||
onActorFilterChange(option.value || null);
|
||||
}}
|
||||
options={[{ label: t("all"), value: "" }, ...actorOptions]}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -129,335 +129,338 @@ function BookingLogsFilters({
|
||||
* Handles translations with embedded components (e.g., links) for proper i18n support
|
||||
*/
|
||||
function ActionTitle({ actionDisplayTitle }: { actionDisplayTitle: TranslationWithParams }) {
|
||||
const { t } = useLocale();
|
||||
const { t } = useLocale();
|
||||
|
||||
if (actionDisplayTitle.components?.length) {
|
||||
return (
|
||||
<ServerTrans
|
||||
t={t}
|
||||
i18nKey={actionDisplayTitle.key}
|
||||
values={actionDisplayTitle.params}
|
||||
components={actionDisplayTitle.components.map((comp) =>
|
||||
comp.type === "link" ? (
|
||||
<Link key={comp.href} href={comp.href} className="text-emphasis underline hover:no-underline" />
|
||||
) : (
|
||||
<span key={comp.href} />
|
||||
)
|
||||
)}
|
||||
/>
|
||||
);
|
||||
}
|
||||
if (actionDisplayTitle.components?.length) {
|
||||
return (
|
||||
<ServerTrans
|
||||
t={t}
|
||||
i18nKey={actionDisplayTitle.key}
|
||||
values={actionDisplayTitle.params}
|
||||
components={actionDisplayTitle.components.map((comp) =>
|
||||
comp.type === "link" ? (
|
||||
<Link key={comp.href} href={comp.href} className="text-emphasis underline hover:no-underline" />
|
||||
) : (
|
||||
<span key={comp.href} />
|
||||
)
|
||||
)}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
return <>{t(actionDisplayTitle.key, actionDisplayTitle.params)}</>;
|
||||
return <>{t(actionDisplayTitle.key, actionDisplayTitle.params)}</>;
|
||||
}
|
||||
|
||||
interface JsonViewerProps {
|
||||
data: Record<string, unknown> | null;
|
||||
data: Record<string, unknown> | null;
|
||||
}
|
||||
|
||||
function JsonViewer({ data }: JsonViewerProps) {
|
||||
if (!data || Object.keys(data).length === 0) {
|
||||
return null;
|
||||
}
|
||||
if (!data || Object.keys(data).length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const jsonString = JSON.stringify(data, null, 2);
|
||||
const lines = jsonString.split("\n");
|
||||
const lineCount = lines.length;
|
||||
const lineNumberWidth = Math.max(2, Math.ceil(Math.log10(lineCount)) + 1);
|
||||
const jsonString = JSON.stringify(data, null, 2);
|
||||
const lines = jsonString.split("\n");
|
||||
const lineCount = lines.length;
|
||||
const lineNumberWidth = Math.max(2, Math.ceil(Math.log10(lineCount)) + 1);
|
||||
|
||||
return (
|
||||
<div className="bg-default p-3 rounded-md text-[10px] overflow-x-auto font-mono">
|
||||
{lines.map((line, idx) => (
|
||||
<div key={idx} className="flex gap-2">
|
||||
<span
|
||||
className="text-subtle select-none text-right shrink-0"
|
||||
style={{ minWidth: `${lineNumberWidth}ch` }}>
|
||||
{idx + 1}
|
||||
</span>
|
||||
<span className="text-default whitespace-pre-wrap break-all">{line || " "}</span>
|
||||
</div>
|
||||
))}
|
||||
return (
|
||||
<div className="bg-default p-3 rounded-md text-[10px] overflow-x-auto font-mono">
|
||||
{lines.map((line, idx) => (
|
||||
<div key={idx} className="flex gap-2">
|
||||
<span
|
||||
className="text-subtle select-none text-right shrink-0"
|
||||
style={{ minWidth: `${lineNumberWidth}ch` }}>
|
||||
{idx + 1}
|
||||
</span>
|
||||
<span className="text-default whitespace-pre-wrap break-all">{line || " "}</span>
|
||||
</div>
|
||||
);
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
interface DisplayFieldValueProps {
|
||||
field: {
|
||||
valueKey?: string;
|
||||
value?: string;
|
||||
values?: string[];
|
||||
};
|
||||
field: {
|
||||
valueKey?: string;
|
||||
value?: string;
|
||||
values?: string[];
|
||||
};
|
||||
}
|
||||
|
||||
function DisplayFieldValue({ field }: DisplayFieldValueProps) {
|
||||
const { t } = useLocale();
|
||||
const { t } = useLocale();
|
||||
|
||||
if (field.values) {
|
||||
return (
|
||||
<span className="flex flex-col">
|
||||
{field.values.map((v, i) => (
|
||||
<span className="p-0.5" key={i}>
|
||||
{v}
|
||||
</span>
|
||||
))}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
if (field.values) {
|
||||
return (
|
||||
<span className="flex flex-col">
|
||||
{field.values.map((v, i) => (
|
||||
<span className="p-0.5" key={i}>
|
||||
{v}
|
||||
</span>
|
||||
))}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
return <>{field.value ?? (field.valueKey ? t(field.valueKey) : "")}</>;
|
||||
return <>{field.value ?? (field.valueKey ? t(field.valueKey) : "")}</>;
|
||||
}
|
||||
|
||||
function BookingLogsTimeline({ logs }: BookingLogsTimelineProps) {
|
||||
const { t } = useLocale();
|
||||
const [expandedLogIds, setExpandedLogIds] = useState<Set<string>>(new Set());
|
||||
const [showJsonMap, setShowJsonMap] = useState<Record<string, boolean>>({});
|
||||
const { t } = useLocale();
|
||||
const [expandedLogIds, setExpandedLogIds] = useState<Set<string>>(new Set());
|
||||
const [showJsonMap, setShowJsonMap] = useState<Record<string, boolean>>({});
|
||||
|
||||
const toggleExpand = (logId: string) => {
|
||||
setExpandedLogIds((prev) => {
|
||||
const newSet = new Set(prev);
|
||||
if (newSet.has(logId)) {
|
||||
newSet.delete(logId);
|
||||
} else {
|
||||
newSet.add(logId);
|
||||
}
|
||||
return newSet;
|
||||
});
|
||||
};
|
||||
const toggleExpand = (logId: string) => {
|
||||
setExpandedLogIds((prev) => {
|
||||
const newSet = new Set(prev);
|
||||
if (newSet.has(logId)) {
|
||||
newSet.delete(logId);
|
||||
} else {
|
||||
newSet.add(logId);
|
||||
}
|
||||
return newSet;
|
||||
});
|
||||
};
|
||||
|
||||
const toggleJson = (logId: string) => {
|
||||
setShowJsonMap((prev) => ({
|
||||
...prev,
|
||||
[logId]: !prev[logId],
|
||||
}));
|
||||
};
|
||||
|
||||
if (logs.length === 0) {
|
||||
return (
|
||||
<div className="text-center py-12">
|
||||
<p className="text-muted">{t("no_audit_logs_found")}</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
const toggleJson = (logId: string) => {
|
||||
setShowJsonMap((prev) => ({
|
||||
...prev,
|
||||
[logId]: !prev[logId],
|
||||
}));
|
||||
};
|
||||
|
||||
if (logs.length === 0) {
|
||||
return (
|
||||
<div className="flex flex-col gap-0.5">
|
||||
{logs.map((log, index) => {
|
||||
const isLast = index === logs.length - 1;
|
||||
const isExpanded = expandedLogIds.has(log.id);
|
||||
const showJson = showJsonMap[log.id] || false;
|
||||
const actorRole = ACTOR_ROLE_LABEL_MAP[log.actor.type] ?? null;
|
||||
return (
|
||||
<div key={log.id} className="flex gap-1">
|
||||
<div className="flex flex-col items-center self-stretch">
|
||||
<div className="pt-2 shrink-0">
|
||||
<div className="bg-subtle rounded-[3.556px] p-1 flex items-center justify-center w-4 h-4">
|
||||
<Icon name={log.hasError ? "triangle-alert" : (ACTION_ICON_MAP[log.action] ?? "sparkles")} className={`h-3 w-3 ${log.hasError ? "text-attention" : "text-subtle"}`} />
|
||||
</div>
|
||||
</div>
|
||||
{!isLast && <div className="w-px bg-subtle flex-1 min-h-0" />}
|
||||
</div>
|
||||
|
||||
<div className="flex-1 rounded-lg py-2">
|
||||
<div className="px-3 mb-2">
|
||||
<div className="flex items-start justify-between gap-3">
|
||||
<div className="flex-1 min-w-0">
|
||||
<h3 className="text-sm font-medium leading-4 text-emphasis">
|
||||
<ActionTitle actionDisplayTitle={log.actionDisplayTitle} />
|
||||
</h3>
|
||||
<div className="flex items-center gap-1 mt-1 text-xs text-subtle">
|
||||
{log.actor.displayAvatar && (
|
||||
<Avatar
|
||||
size="xs"
|
||||
imageSrc={log.actor.displayAvatar}
|
||||
alt={log.actor.displayName || ""}
|
||||
/>
|
||||
)}
|
||||
<span>
|
||||
{log.actor.displayName}
|
||||
{actorRole && <span>{` (${t(actorRole)})`}</span>}
|
||||
</span>
|
||||
<span>•</span>
|
||||
<span>{dayjs(log.timestamp).fromNow()}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="px-3">
|
||||
<div className="bg-muted rounded-lg border border-muted">
|
||||
<div className="py-1">
|
||||
<Button
|
||||
color="minimal"
|
||||
size="sm"
|
||||
onClick={() => toggleExpand(log.id)}
|
||||
StartIcon={isExpanded ? "chevron-down" : "chevron-right"}
|
||||
className="justify-start text-xs font-medium text-subtle h-6">
|
||||
{isExpanded ? t("hide_details") : t("show_details")}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{isExpanded && (
|
||||
<div className="bg-default rounded-lg m-0.5 text-xs">
|
||||
{/* Render displayFields if available, otherwise show type */}
|
||||
{log.displayFields && log.displayFields.length > 0
|
||||
? log.displayFields.map((field, idx) => (
|
||||
<div
|
||||
key={idx}
|
||||
className="flex items-start gap-2 py-2 border-b px-3 border-subtle">
|
||||
<span className="font-medium text-emphasis w-[140px]">{t(field.labelKey)}</span>
|
||||
<span className="font-medium">
|
||||
<DisplayFieldValue field={field} />
|
||||
</span>
|
||||
</div>
|
||||
))
|
||||
: null}
|
||||
<div className="flex items-start gap-2 py-2 border-b px-3 border-subtle">
|
||||
<span className="font-medium text-emphasis w-[140px]">{t("actor")}</span>
|
||||
<span className="text-default">{log.actor.displayName || log.actor.type}</span>
|
||||
</div>
|
||||
{log.impersonatedBy && (
|
||||
<div className="flex items-start gap-2 py-2 border-b px-3 border-subtle">
|
||||
<span className="font-medium text-emphasis w-[140px]">
|
||||
{t("booking_audit_action.actor_impersonated_by", {
|
||||
actor: log.actor.displayName,
|
||||
})}
|
||||
</span>
|
||||
<span className="text-default">{log.impersonatedBy.displayName}</span>
|
||||
</div>
|
||||
)}
|
||||
<div className="flex items-start gap-2 py-2 border-b px-3 border-subtle">
|
||||
<span className="font-medium text-emphasis w-[140px]">
|
||||
{t("booking_audit_action.source")}
|
||||
</span>
|
||||
<span className="text-default">{log.source}</span>
|
||||
</div>
|
||||
<div className="flex items-start gap-2 py-2 px-3 border-b border-subtle">
|
||||
<span className="font-medium text-emphasis w-[140px]">{t("timestamp")}</span>
|
||||
<span className="text-default">
|
||||
{dayjs(log.timestamp).format("YYYY-MM-DD HH:mm:ss")}
|
||||
</span>
|
||||
</div>
|
||||
{log.displayJson && Object.keys(log.displayJson).length > 0 && (
|
||||
<div>
|
||||
<div className="flex flex-col items-start gap-2 py-1 px-3 border-b border-subtle">
|
||||
<Button
|
||||
color="minimal"
|
||||
size="sm"
|
||||
onClick={() => toggleJson(log.id)}
|
||||
StartIcon={showJson ? "chevron-down" : "chevron-right"}
|
||||
className="-ml-3 h-6 px-2 font-medium text-xs">
|
||||
{t("json")}
|
||||
</Button>
|
||||
</div>
|
||||
<div>{showJson && <JsonViewer data={log.displayJson} />}</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
<div className="text-center py-12">
|
||||
<p className="text-muted">{t("no_audit_logs_found")}</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-0.5">
|
||||
{logs.map((log, index) => {
|
||||
const isLast = index === logs.length - 1;
|
||||
const isExpanded = expandedLogIds.has(log.id);
|
||||
const showJson = showJsonMap[log.id] || false;
|
||||
const actorRole = ACTOR_ROLE_LABEL_MAP[log.actor.type] ?? null;
|
||||
return (
|
||||
<div key={log.id} className="flex gap-1">
|
||||
<div className="flex flex-col items-center self-stretch">
|
||||
<div className="pt-2 shrink-0">
|
||||
<div className="bg-subtle rounded-[3.556px] p-1 flex items-center justify-center w-4 h-4">
|
||||
<Icon
|
||||
name={log.hasError ? "triangle-alert" : (ACTION_ICON_MAP[log.action] ?? "sparkles")}
|
||||
className={`h-3 w-3 ${log.hasError ? "text-attention" : "text-subtle"}`}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
{!isLast && <div className="w-px bg-subtle flex-1 min-h-0" />}
|
||||
</div>
|
||||
|
||||
<div className="flex-1 rounded-lg py-2">
|
||||
<div className="px-3 mb-2">
|
||||
<div className="flex items-start justify-between gap-3">
|
||||
<div className="flex-1 min-w-0">
|
||||
<h3 className="text-sm font-medium leading-4 text-emphasis">
|
||||
<ActionTitle actionDisplayTitle={log.actionDisplayTitle} />
|
||||
</h3>
|
||||
<div className="flex items-center gap-1 mt-1 text-xs text-subtle">
|
||||
{log.actor.displayAvatar && (
|
||||
<Avatar
|
||||
size="xs"
|
||||
imageSrc={log.actor.displayAvatar}
|
||||
alt={log.actor.displayName || ""}
|
||||
/>
|
||||
)}
|
||||
<span>
|
||||
{log.actor.displayName}
|
||||
{actorRole && <span>{` (${t(actorRole)})`}</span>}
|
||||
</span>
|
||||
<span>•</span>
|
||||
<span>{dayjs(log.timestamp).fromNow()}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="px-3">
|
||||
<div className="bg-muted rounded-lg border border-muted">
|
||||
<div className="py-1">
|
||||
<Button
|
||||
color="minimal"
|
||||
size="sm"
|
||||
onClick={() => toggleExpand(log.id)}
|
||||
StartIcon={isExpanded ? "chevron-down" : "chevron-right"}
|
||||
className="justify-start text-xs font-medium text-subtle h-6">
|
||||
{isExpanded ? t("hide_details") : t("show_details")}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{isExpanded && (
|
||||
<div className="bg-default rounded-lg m-0.5 text-xs">
|
||||
{/* Render displayFields if available, otherwise show type */}
|
||||
{log.displayFields && log.displayFields.length > 0
|
||||
? log.displayFields.map((field, idx) => (
|
||||
<div
|
||||
key={idx}
|
||||
className="flex items-start gap-2 py-2 border-b px-3 border-subtle">
|
||||
<span className="font-medium text-emphasis w-[140px]">{t(field.labelKey)}</span>
|
||||
<span className="font-medium">
|
||||
<DisplayFieldValue field={field} />
|
||||
</span>
|
||||
</div>
|
||||
))
|
||||
: null}
|
||||
<div className="flex items-start gap-2 py-2 border-b px-3 border-subtle">
|
||||
<span className="font-medium text-emphasis w-[140px]">{t("actor")}</span>
|
||||
<span className="text-default">{log.actor.displayName || log.actor.type}</span>
|
||||
</div>
|
||||
{log.impersonatedBy && (
|
||||
<div className="flex items-start gap-2 py-2 border-b px-3 border-subtle">
|
||||
<span className="font-medium text-emphasis w-[140px]">
|
||||
{t("booking_audit_action.actor_impersonated_by", {
|
||||
actor: log.actor.displayName,
|
||||
})}
|
||||
</span>
|
||||
<span className="text-default">{log.impersonatedBy.displayName}</span>
|
||||
</div>
|
||||
)}
|
||||
<div className="flex items-start gap-2 py-2 border-b px-3 border-subtle">
|
||||
<span className="font-medium text-emphasis w-[140px]">
|
||||
{t("booking_audit_action.source")}
|
||||
</span>
|
||||
<span className="text-default">{log.source}</span>
|
||||
</div>
|
||||
<div className="flex items-start gap-2 py-2 px-3 border-b border-subtle">
|
||||
<span className="font-medium text-emphasis w-[140px]">{t("timestamp")}</span>
|
||||
<span className="text-default">
|
||||
{dayjs(log.timestamp).format("YYYY-MM-DD HH:mm:ss")}
|
||||
</span>
|
||||
</div>
|
||||
{log.displayJson && Object.keys(log.displayJson).length > 0 && (
|
||||
<div>
|
||||
<div className="flex flex-col items-start gap-2 py-1 px-3 border-b border-subtle">
|
||||
<Button
|
||||
color="minimal"
|
||||
size="sm"
|
||||
onClick={() => toggleJson(log.id)}
|
||||
StartIcon={showJson ? "chevron-down" : "chevron-right"}
|
||||
className="-ml-3 h-6 px-2 font-medium text-xs">
|
||||
{t("json")}
|
||||
</Button>
|
||||
</div>
|
||||
<div>{showJson && <JsonViewer data={log.displayJson} />}</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function useBookingLogsFilters(auditLogs: AuditLog[], searchTerm: string, actorFilter: string | null) {
|
||||
const filteredLogs = auditLogs.filter((log) => {
|
||||
const doesMatchDisplayFields = (): boolean => {
|
||||
return (
|
||||
log.displayFields?.some((field) => {
|
||||
const searchLower = searchTerm.toLowerCase();
|
||||
return (
|
||||
field.valueKey?.toLowerCase().includes(searchLower) ||
|
||||
field.labelKey?.toLowerCase().includes(searchLower) ||
|
||||
field.value?.toLowerCase().includes(searchLower) ||
|
||||
field.values?.some((v) => v.toLowerCase().includes(searchLower))
|
||||
);
|
||||
}) ?? false
|
||||
);
|
||||
};
|
||||
const filteredLogs = auditLogs.filter((log) => {
|
||||
const doesMatchDisplayFields = (): boolean => {
|
||||
return (
|
||||
log.displayFields?.some((field) => {
|
||||
const searchLower = searchTerm.toLowerCase();
|
||||
return (
|
||||
field.valueKey?.toLowerCase().includes(searchLower) ||
|
||||
field.labelKey?.toLowerCase().includes(searchLower) ||
|
||||
field.value?.toLowerCase().includes(searchLower) ||
|
||||
field.values?.some((v) => v.toLowerCase().includes(searchLower))
|
||||
);
|
||||
}) ?? false
|
||||
);
|
||||
};
|
||||
|
||||
const doesMatchActionDisplayTitle = (): boolean => {
|
||||
return (
|
||||
log.actionDisplayTitle.key?.toLowerCase().includes(searchTerm.toLowerCase()) ||
|
||||
Object.values(log.actionDisplayTitle.params ?? {}).some((param) =>
|
||||
param?.toString().toLowerCase().includes(searchTerm.toLowerCase())
|
||||
)
|
||||
);
|
||||
};
|
||||
const doesMatchActionDisplayTitle = (): boolean => {
|
||||
return (
|
||||
log.actionDisplayTitle.key?.toLowerCase().includes(searchTerm.toLowerCase()) ||
|
||||
Object.values(log.actionDisplayTitle.params ?? {}).some((param) =>
|
||||
param?.toString().toLowerCase().includes(searchTerm.toLowerCase())
|
||||
)
|
||||
);
|
||||
};
|
||||
|
||||
const matchesSearch =
|
||||
!searchTerm ||
|
||||
log.action.toLowerCase().includes(searchTerm.toLowerCase()) ||
|
||||
log.actor.displayName?.toLowerCase().includes(searchTerm.toLowerCase()) ||
|
||||
doesMatchDisplayFields() ||
|
||||
doesMatchActionDisplayTitle();
|
||||
const matchesSearch =
|
||||
!searchTerm ||
|
||||
log.action.toLowerCase().includes(searchTerm.toLowerCase()) ||
|
||||
log.actor.displayName?.toLowerCase().includes(searchTerm.toLowerCase()) ||
|
||||
doesMatchDisplayFields() ||
|
||||
doesMatchActionDisplayTitle();
|
||||
|
||||
const matchesActor = !actorFilter || log.actor.displayName === actorFilter;
|
||||
const matchesActor = !actorFilter || log.actor.displayName === actorFilter;
|
||||
|
||||
return matchesSearch && matchesActor;
|
||||
});
|
||||
return matchesSearch && matchesActor;
|
||||
});
|
||||
|
||||
const uniqueActorNames = Array.from(
|
||||
new Set(auditLogs.map((log) => log.actor.displayName).filter((name): name is string => Boolean(name)))
|
||||
);
|
||||
const uniqueActorNames = Array.from(
|
||||
new Set(auditLogs.map((log) => log.actor.displayName).filter((name): name is string => Boolean(name)))
|
||||
);
|
||||
|
||||
const actorOptions = uniqueActorNames.map((actorName) => ({
|
||||
label: actorName,
|
||||
value: actorName,
|
||||
}));
|
||||
const actorOptions = uniqueActorNames.map((actorName) => ({
|
||||
label: actorName,
|
||||
value: actorName,
|
||||
}));
|
||||
|
||||
return { filteredLogs, actorOptions };
|
||||
return { filteredLogs, actorOptions };
|
||||
}
|
||||
|
||||
export function BookingHistory({ bookingUid }: BookingHistoryProps) {
|
||||
const [searchTerm, setSearchTerm] = useState("");
|
||||
const [actorFilter, setActorFilter] = useState<string | null>(null);
|
||||
const { t } = useLocale();
|
||||
const { data, isLoading, error } = trpc.viewer.bookings.getBookingHistory.useQuery({
|
||||
bookingUid,
|
||||
});
|
||||
const [searchTerm, setSearchTerm] = useState("");
|
||||
const [actorFilter, setActorFilter] = useState<string | null>(null);
|
||||
const { t } = useLocale();
|
||||
const { data, isLoading, error } = trpc.viewer.bookings.getBookingHistory.useQuery({
|
||||
bookingUid,
|
||||
});
|
||||
|
||||
const auditLogs = data?.auditLogs || [];
|
||||
const auditLogs = data?.auditLogs || [];
|
||||
|
||||
const { filteredLogs, actorOptions } = useBookingLogsFilters(auditLogs, searchTerm, actorFilter);
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
<div className="flex items-center justify-center py-12">
|
||||
<div className="text-center">
|
||||
<p className="text-red-600 font-medium">{t("error_loading_booking_logs")}</p>
|
||||
<p className="text-sm text-gray-500 mt-2">{error.message}</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<SkeletonText className="h-12 w-full" />
|
||||
<SkeletonText className="h-24 w-full" />
|
||||
<SkeletonText className="h-24 w-full" />
|
||||
<SkeletonText className="h-24 w-full" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
const { filteredLogs, actorOptions } = useBookingLogsFilters(auditLogs, searchTerm, actorFilter);
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<BookingLogsFilters
|
||||
searchTerm={searchTerm}
|
||||
onSearchChange={setSearchTerm}
|
||||
actorFilter={actorFilter}
|
||||
onActorFilterChange={setActorFilter}
|
||||
actorOptions={actorOptions}
|
||||
/>
|
||||
|
||||
<BookingLogsTimeline logs={filteredLogs} />
|
||||
<div className="flex items-center justify-center py-12">
|
||||
<div className="text-center">
|
||||
<p className="text-red-600 font-medium">{t("error_loading_booking_logs")}</p>
|
||||
<p className="text-sm text-gray-500 mt-2">{error.message}</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<SkeletonText className="h-12 w-full" />
|
||||
<SkeletonText className="h-24 w-full" />
|
||||
<SkeletonText className="h-24 w-full" />
|
||||
<SkeletonText className="h-24 w-full" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<BookingLogsFilters
|
||||
searchTerm={searchTerm}
|
||||
onSearchChange={setSearchTerm}
|
||||
actorFilter={actorFilter}
|
||||
onActorFilterChange={setActorFilter}
|
||||
actorOptions={actorOptions}
|
||||
/>
|
||||
|
||||
<BookingLogsTimeline logs={filteredLogs} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -3,7 +3,7 @@
|
||||
import { BookingHistory } from "./BookingHistory";
|
||||
|
||||
interface BookingHistoryPageProps {
|
||||
bookingUid: string;
|
||||
bookingUid: string;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -11,5 +11,5 @@ interface BookingHistoryPageProps {
|
||||
* Adds page-specific styling and layout for the booking history view
|
||||
*/
|
||||
export function BookingHistoryPage({ bookingUid }: BookingHistoryPageProps) {
|
||||
return <BookingHistory bookingUid={bookingUid} />;
|
||||
return <BookingHistory bookingUid={bookingUid} />;
|
||||
}
|
||||
@@ -28,10 +28,7 @@ type AvailableTimeSlotsProps = {
|
||||
seatsPerTimeSlot?: number | null;
|
||||
showAvailableSeatsCount?: boolean | null;
|
||||
event: {
|
||||
data?: Pick<
|
||||
BookerEvent,
|
||||
"length" | "bookingFields" | "price" | "currency" | "metadata"
|
||||
> | null;
|
||||
data?: Pick<BookerEvent, "length" | "bookingFields" | "price" | "currency" | "metadata"> | null;
|
||||
};
|
||||
customClassNames?: {
|
||||
availableTimeSlotsContainer?: string;
|
||||
@@ -86,18 +83,15 @@ export const AvailableTimeSlots = ({
|
||||
}: AvailableTimeSlotsProps) => {
|
||||
const selectedDate = useBookerStoreContext((state) => state.selectedDate);
|
||||
|
||||
const setSeatedEventData = useBookerStoreContext(
|
||||
(state) => state.setSeatedEventData
|
||||
);
|
||||
const setSeatedEventData = useBookerStoreContext((state) => state.setSeatedEventData);
|
||||
const date = selectedDate || dayjs().format("YYYY-MM-DD");
|
||||
const [layout] = useBookerStoreContext((state) => [state.layout]);
|
||||
const isColumnView = layout === BookerLayouts.COLUMN_VIEW;
|
||||
const containerRef = useRef<HTMLDivElement | null>(null);
|
||||
const { setTentativeSelectedTimeslots, tentativeSelectedTimeslots } =
|
||||
useBookerStoreContext((state) => ({
|
||||
setTentativeSelectedTimeslots: state.setTentativeSelectedTimeslots,
|
||||
tentativeSelectedTimeslots: state.tentativeSelectedTimeslots,
|
||||
}));
|
||||
const { setTentativeSelectedTimeslots, tentativeSelectedTimeslots } = useBookerStoreContext((state) => ({
|
||||
setTentativeSelectedTimeslots: state.setTentativeSelectedTimeslots,
|
||||
tentativeSelectedTimeslots: state.tentativeSelectedTimeslots,
|
||||
}));
|
||||
|
||||
const onTentativeTimeSelect = ({
|
||||
time,
|
||||
@@ -135,22 +129,13 @@ export const AvailableTimeSlots = ({
|
||||
return [];
|
||||
}, [date, extraDays, nonEmptyScheduleDaysFromSelectedDate]);
|
||||
|
||||
const { slotsPerDay, toggleConfirmButton } = useSlotsForAvailableDates(
|
||||
dates,
|
||||
scheduleData?.slots
|
||||
);
|
||||
const { slotsPerDay, toggleConfirmButton } = useSlotsForAvailableDates(dates, scheduleData?.slots);
|
||||
|
||||
const overlayCalendarToggled =
|
||||
getQueryParam("overlayCalendar") === "true" ||
|
||||
localStorage.getItem("overlayCalendarSwitchDefault");
|
||||
getQueryParam("overlayCalendar") === "true" || localStorage.getItem("overlayCalendarSwitchDefault");
|
||||
|
||||
const onTimeSelect = useCallback(
|
||||
(
|
||||
time: string,
|
||||
attendees: number,
|
||||
seatsPerTimeSlot?: number | null,
|
||||
bookingUid?: string
|
||||
) => {
|
||||
(time: string, attendees: number, seatsPerTimeSlot?: number | null, bookingUid?: string) => {
|
||||
// Temporarily allow disabling it, till we are sure that it doesn't cause any significant load on the system
|
||||
if (PUBLIC_INVALIDATE_AVAILABLE_SLOTS_ON_BOOKING_FORM) {
|
||||
// Ensures that user has latest available slots when they are about to confirm the booking by filling up the details
|
||||
@@ -201,13 +186,7 @@ export const AvailableTimeSlots = ({
|
||||
);
|
||||
}
|
||||
},
|
||||
[
|
||||
overlayCalendarToggled,
|
||||
onTimeSelect,
|
||||
seatsPerTimeSlot,
|
||||
skipConfirmStep,
|
||||
toggleConfirmButton,
|
||||
]
|
||||
[overlayCalendarToggled, onTimeSelect, seatsPerTimeSlot, skipConfirmStep, toggleConfirmButton]
|
||||
);
|
||||
|
||||
return (
|
||||
@@ -217,8 +196,7 @@ export const AvailableTimeSlots = ({
|
||||
`flex`,
|
||||
hideAvailableTimesHeader && "hidden",
|
||||
`${customClassNames?.availableTimeSlotsContainer}`
|
||||
)}
|
||||
>
|
||||
)}>
|
||||
{isLoading ? (
|
||||
<div className="mb-3 h-8" />
|
||||
) : (
|
||||
@@ -229,19 +207,15 @@ export const AvailableTimeSlots = ({
|
||||
return (
|
||||
<AvailableTimesHeader
|
||||
customClassNames={{
|
||||
availableTimeSlotsHeaderContainer:
|
||||
customClassNames?.availableTimeSlotsHeaderContainer,
|
||||
availableTimeSlotsTitle:
|
||||
customClassNames?.availableTimeSlotsTitle,
|
||||
availableTimeSlotsTimeFormatToggle:
|
||||
customClassNames?.availableTimeSlotsTimeFormatToggle,
|
||||
availableTimeSlotsHeaderContainer: customClassNames?.availableTimeSlotsHeaderContainer,
|
||||
availableTimeSlotsTitle: customClassNames?.availableTimeSlotsTitle,
|
||||
availableTimeSlotsTimeFormatToggle: customClassNames?.availableTimeSlotsTimeFormatToggle,
|
||||
}}
|
||||
key={slots.date}
|
||||
date={dayjs(slots.date)}
|
||||
showTimeFormatToggle={!isColumnView && !isOOODay}
|
||||
availableMonth={
|
||||
dayjs(selectedDate).format("MM") !==
|
||||
dayjs(slots.date).format("MM")
|
||||
dayjs(selectedDate).format("MM") !== dayjs(slots.date).format("MM")
|
||||
? dayjs(slots.date).format("MMM")
|
||||
: undefined
|
||||
}
|
||||
@@ -257,19 +231,13 @@ export const AvailableTimeSlots = ({
|
||||
limitHeight && "no-scrollbar grow overflow-auto md:h-[400px]",
|
||||
!limitHeight && "flex h-full w-full flex-row gap-4",
|
||||
`${customClassNames?.availableTimeSlotsContainer}`
|
||||
)}
|
||||
>
|
||||
)}>
|
||||
{isLoading && // Shows exact amount of days as skeleton.
|
||||
Array.from({ length: 1 + (extraDays ?? 0) }).map((_, i) => (
|
||||
<AvailableTimesSkeleton key={i} />
|
||||
))}
|
||||
Array.from({ length: 1 + (extraDays ?? 0) }).map((_, i) => <AvailableTimesSkeleton key={i} />)}
|
||||
{!isLoading &&
|
||||
slotsPerDay.length > 0 &&
|
||||
slotsPerDay.map((slots) => (
|
||||
<div
|
||||
key={slots.date}
|
||||
className="no-scrollbar overflow-x-hidden! h-full w-full overflow-y-auto"
|
||||
>
|
||||
<div key={slots.date} className="no-scrollbar overflow-x-hidden! h-full w-full overflow-y-auto">
|
||||
<AvailableTimes
|
||||
className={customClassNames?.availableTimeSlotsContainer}
|
||||
customClassNames={customClassNames?.availableTimes}
|
||||
|
||||
@@ -295,10 +295,10 @@ export const BookEventForm = ({
|
||||
{rescheduleUid && bookingData
|
||||
? t("reschedule")
|
||||
: renderConfirmNotVerifyEmailButtonCond
|
||||
? isPaidEvent
|
||||
? t("pay_and_book")
|
||||
: t("confirm")
|
||||
: t("verify_email_button")}
|
||||
? isPaidEvent
|
||||
? t("pay_and_book")
|
||||
: t("confirm")
|
||||
: t("verify_email_button")}
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
|
||||
@@ -253,12 +253,12 @@ const BookerComponent = ({
|
||||
|
||||
const unavailableTimeSlots = isQuickAvailabilityCheckFeatureEnabled
|
||||
? allSelectedTimeslots.filter((slot) => {
|
||||
return !isTimeSlotAvailable({
|
||||
scheduleData: schedule?.data ?? null,
|
||||
slotToCheckInIso: slot,
|
||||
quickAvailabilityChecks: slots.quickAvailabilityChecks,
|
||||
});
|
||||
})
|
||||
return !isTimeSlotAvailable({
|
||||
scheduleData: schedule?.data ?? null,
|
||||
slotToCheckInIso: slot,
|
||||
quickAvailabilityChecks: slots.quickAvailabilityChecks,
|
||||
});
|
||||
})
|
||||
: [];
|
||||
|
||||
const slot = getQueryParam("slot");
|
||||
@@ -401,7 +401,7 @@ const BookerComponent = ({
|
||||
className={classNames(
|
||||
layout === BookerLayouts.MONTH_VIEW && "fixed top-4 z-10 ltr:right-4 rtl:left-4",
|
||||
(layout === BookerLayouts.COLUMN_VIEW || layout === BookerLayouts.WEEK_VIEW) &&
|
||||
"bg-default dark:bg-cal-muted sticky top-0 z-10"
|
||||
"bg-default dark:bg-cal-muted sticky top-0 z-10"
|
||||
)}>
|
||||
{isPlatform && layout === BookerLayouts.MONTH_VIEW ? (
|
||||
<></>
|
||||
@@ -503,7 +503,10 @@ const BookerComponent = ({
|
||||
visible={bookerState !== "booking" && layout === BookerLayouts.MONTH_VIEW}
|
||||
{...fadeInLeft}
|
||||
initial="visible"
|
||||
className={classNames("md:border-subtle -ml-px h-full shrink px-5 py-3 lg:w-(--booker-main-width)", hideEventTypeDetails ? "" : "md:border-l")}>
|
||||
className={classNames(
|
||||
"md:border-subtle -ml-px h-full shrink px-5 py-3 lg:w-(--booker-main-width)",
|
||||
hideEventTypeDetails ? "" : "md:border-l"
|
||||
)}>
|
||||
<DatePicker
|
||||
classNames={customClassNames?.datePickerCustomClassNames}
|
||||
event={event}
|
||||
@@ -539,7 +542,7 @@ const BookerComponent = ({
|
||||
className={classNames(
|
||||
"border-subtle rtl:border-default flex h-full w-full flex-col overflow-x-auto px-5 py-3 pb-0 rtl:border-r ltr:md:border-l",
|
||||
layout === BookerLayouts.MONTH_VIEW &&
|
||||
"h-full overflow-hidden md:w-(--booker-timeslots-width)",
|
||||
"h-full overflow-hidden md:w-(--booker-timeslots-width)",
|
||||
layout !== BookerLayouts.MONTH_VIEW && "sticky top-0"
|
||||
)}
|
||||
ref={timeslotsRef}
|
||||
|
||||
@@ -93,14 +93,23 @@ interface BookingDetailsSheetInnerProps {
|
||||
}
|
||||
|
||||
function useActiveSegment(bookingAuditEnabled: boolean) {
|
||||
const [activeSegment, setActiveSegmentInStore] = useBookingDetailsSheetStore((state) => [state.activeSegment, state.setActiveSegment]);
|
||||
const [activeSegment, setActiveSegmentInStore] = useBookingDetailsSheetStore((state) => [
|
||||
state.activeSegment,
|
||||
state.setActiveSegment,
|
||||
]);
|
||||
|
||||
const getDerivedActiveSegment = ({ activeSegment, bookingAuditEnabled }: { activeSegment: "info" | "history" | null, bookingAuditEnabled: boolean }) => {
|
||||
const getDerivedActiveSegment = ({
|
||||
activeSegment,
|
||||
bookingAuditEnabled,
|
||||
}: {
|
||||
activeSegment: "info" | "history" | null;
|
||||
bookingAuditEnabled: boolean;
|
||||
}) => {
|
||||
if (!bookingAuditEnabled && activeSegment === "history") {
|
||||
return "info";
|
||||
}
|
||||
return activeSegment ?? "info";
|
||||
}
|
||||
};
|
||||
|
||||
const derivedActiveSegment = getDerivedActiveSegment({ activeSegment, bookingAuditEnabled });
|
||||
|
||||
@@ -195,15 +204,15 @@ function BookingDetailsSheetInner({
|
||||
const recurringInfo =
|
||||
booking.recurringEventId && booking.eventType?.recurringEvent
|
||||
? {
|
||||
count: booking.eventType.recurringEvent.count,
|
||||
recurringEvent: booking.eventType.recurringEvent,
|
||||
}
|
||||
count: booking.eventType.recurringEvent.count,
|
||||
recurringEvent: booking.eventType.recurringEvent,
|
||||
}
|
||||
: null;
|
||||
|
||||
const customResponses = booking.responses
|
||||
? Object.entries(booking.responses as Record<string, unknown>)
|
||||
.filter(([fieldName]) => shouldShowFieldInCustomResponses(fieldName))
|
||||
.map(([question, answer]) => [question, answer] as [string, unknown])
|
||||
.filter(([fieldName]) => shouldShowFieldInCustomResponses(fieldName))
|
||||
.map(([question, answer]) => [question, answer] as [string, unknown])
|
||||
: [];
|
||||
|
||||
const reason = booking.assignmentReason?.[0];
|
||||
@@ -284,7 +293,10 @@ function BookingDetailsSheetInner({
|
||||
|
||||
{bookingAuditEnabled && (
|
||||
<SegmentedControl
|
||||
data={[{ value: "info", label: t("info") }, { value: "history", label: t("history") }]}
|
||||
data={[
|
||||
{ value: "info", label: t("info") },
|
||||
{ value: "history", label: t("history") },
|
||||
]}
|
||||
value={activeSegment}
|
||||
onChange={(value) => setActiveSegment(value)}
|
||||
/>
|
||||
|
||||
@@ -33,8 +33,8 @@ const useMoveToNextMonthOnNoAvailability = ({
|
||||
};
|
||||
}
|
||||
|
||||
const nonEmptyScheduleDaysInBrowsingMonth = nonEmptyScheduleDays.filter(
|
||||
(date) => dayjs(date).isSame(browsingDate, "month")
|
||||
const nonEmptyScheduleDaysInBrowsingMonth = nonEmptyScheduleDays.filter((date) =>
|
||||
dayjs(date).isSame(browsingDate, "month")
|
||||
);
|
||||
|
||||
const moveToNextMonthOnNoAvailability = () => {
|
||||
@@ -42,10 +42,7 @@ const useMoveToNextMonthOnNoAvailability = ({
|
||||
const browsingMonth = browsingDate.format("YYYY-MM");
|
||||
// Not meeting the criteria to move to next month
|
||||
// Has to be currentMonth and it must have all days unbookable
|
||||
if (
|
||||
currentMonth != browsingMonth ||
|
||||
nonEmptyScheduleDaysInBrowsingMonth.length
|
||||
) {
|
||||
if (currentMonth != browsingMonth || nonEmptyScheduleDaysInBrowsingMonth.length) {
|
||||
return;
|
||||
}
|
||||
onMonthChange(browsingDate.add(1, "month"));
|
||||
@@ -105,13 +102,12 @@ export const DatePicker = ({
|
||||
const nonEmptyScheduleDays = useNonEmptyScheduleDays(slots);
|
||||
const browsingDate = month ? dayjs(month) : dayjs().startOf("month");
|
||||
|
||||
const { moveToNextMonthOnNoAvailability } =
|
||||
useMoveToNextMonthOnNoAvailability({
|
||||
browsingDate,
|
||||
nonEmptyScheduleDays,
|
||||
onMonthChange,
|
||||
isLoading: isLoading ?? true,
|
||||
});
|
||||
const { moveToNextMonthOnNoAvailability } = useMoveToNextMonthOnNoAvailability({
|
||||
browsingDate,
|
||||
nonEmptyScheduleDays,
|
||||
onMonthChange,
|
||||
isLoading: isLoading ?? true,
|
||||
});
|
||||
moveToNextMonthOnNoAvailability();
|
||||
|
||||
// Determine if this is a compact sidebar view based on layout
|
||||
|
||||
@@ -45,7 +45,7 @@ export const LargeCalendar = ({
|
||||
|
||||
// HACK: force rerender when overlay events change
|
||||
// Sine we dont use react router here we need to force rerender (ATOM SUPPORT)
|
||||
useEffect(() => { }, [displayOverlay]);
|
||||
useEffect(() => {}, [displayOverlay]);
|
||||
|
||||
const overlayEventsForDate = useMemo(() => {
|
||||
if (!overlayEvents || !displayOverlay) return [];
|
||||
|
||||
@@ -39,12 +39,12 @@ export const SeatsAvailabilityText = ({
|
||||
count: availableSeats,
|
||||
})}`
|
||||
: isNearlyFull
|
||||
? t("seats_nearly_full")
|
||||
: isHalfFull
|
||||
? t("seats_half_full")
|
||||
: t("seats_available", {
|
||||
count: availableSeats,
|
||||
})}
|
||||
? t("seats_nearly_full")
|
||||
: isHalfFull
|
||||
? t("seats_half_full")
|
||||
: t("seats_available", {
|
||||
count: availableSeats,
|
||||
})}
|
||||
</span>
|
||||
);
|
||||
};
|
||||
@@ -29,10 +29,7 @@ type TimezoneSelectProps = Omit<
|
||||
};
|
||||
|
||||
const WebTimezoneSelect: ComponentType<TimezoneSelectProps> = dynamic(
|
||||
() =>
|
||||
import("@calcom/web/modules/timezone/components/TimezoneSelect").then(
|
||||
(mod) => mod.TimezoneSelect
|
||||
),
|
||||
() => import("@calcom/web/modules/timezone/components/TimezoneSelect").then((mod) => mod.TimezoneSelect),
|
||||
{
|
||||
ssr: false,
|
||||
loading: () => <LoadingState />,
|
||||
@@ -104,9 +101,7 @@ export const SlotSelectionModalHeader = ({
|
||||
<span className="text-default text-sm">{formattedDate.fullDate}</span>
|
||||
</div>
|
||||
|
||||
{event && (
|
||||
<EventDetails event={event} blocks={[EventDetailBlocks.DURATION]} />
|
||||
)}
|
||||
{event && <EventDetails event={event} blocks={[EventDetailBlocks.DURATION]} />}
|
||||
|
||||
<div className="mb-0 flex items-center gap-2 text-default text-sm">
|
||||
<Icon name="globe" className="h-4 w-4 shrink-0 text-subtle" />
|
||||
|
||||
@@ -3,4 +3,4 @@ vi.mock("../DryRunMessage", () => ({
|
||||
DryRunMessage: ({ isEmbed }: { isEmbed: boolean }) => (
|
||||
<div data-testid="dry-run-message">Mock Dry Run Message</div>
|
||||
),
|
||||
}));
|
||||
}));
|
||||
@@ -110,7 +110,9 @@ export const EventMetaBlock = ({
|
||||
))}
|
||||
</>
|
||||
)}
|
||||
<div className={classNames("relative z-10 max-w-full wrap-break-word", contentClassName)}>{children}</div>
|
||||
<div className={classNames("relative z-10 max-w-full wrap-break-word", contentClassName)}>
|
||||
{children}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -1,13 +1,12 @@
|
||||
import { useQueryState } from "nuqs";
|
||||
|
||||
export function useActiveSegmentFromUrl() {
|
||||
return useQueryState<"info" | "history">("activeSegment", {
|
||||
defaultValue: "info",
|
||||
parse: (value) => {
|
||||
if (!value) return "info";
|
||||
if (value === "history") return "history";
|
||||
return "info";
|
||||
},
|
||||
});
|
||||
return useQueryState<"info" | "history">("activeSegment", {
|
||||
defaultValue: "info",
|
||||
parse: (value) => {
|
||||
if (!value) return "info";
|
||||
if (value === "history") return "history";
|
||||
return "info";
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
@@ -309,8 +309,8 @@ export const useBookings = ({ event, hashedLink, bookingForm, metadata, isBookin
|
||||
const validDuration = event.data?.isDynamic
|
||||
? duration || event.data?.length
|
||||
: duration && event.data?.metadata?.multipleDuration?.includes(duration)
|
||||
? duration
|
||||
: event.data?.length;
|
||||
? duration
|
||||
: event.data?.length;
|
||||
|
||||
if (isRescheduling) {
|
||||
sdkActionManager?.fire("rescheduleBookingSuccessful", {
|
||||
|
||||
@@ -20,19 +20,22 @@ export function useEventTypes() {
|
||||
const individualEvents = eventTypes.filter((el) => !el.team);
|
||||
|
||||
// Group team events by team
|
||||
const teamEventsMap = eventTypes.reduce((acc, event) => {
|
||||
if (!event.team) return acc;
|
||||
const teamEventsMap = eventTypes.reduce(
|
||||
(acc, event) => {
|
||||
if (!event.team) return acc;
|
||||
|
||||
const teamId = event.team.id;
|
||||
if (!acc[teamId]) {
|
||||
acc[teamId] = {
|
||||
teamName: event.team.name,
|
||||
events: [],
|
||||
};
|
||||
}
|
||||
acc[teamId].events.push(event);
|
||||
return acc;
|
||||
}, {} as Record<number, { teamName: string; events: typeof eventTypes }>);
|
||||
const teamId = event.team.id;
|
||||
if (!acc[teamId]) {
|
||||
acc[teamId] = {
|
||||
teamName: event.team.name,
|
||||
events: [],
|
||||
};
|
||||
}
|
||||
acc[teamId].events.push(event);
|
||||
return acc;
|
||||
},
|
||||
{} as Record<number, { teamName: string; events: typeof eventTypes }>
|
||||
);
|
||||
|
||||
// Create flat array with section markers
|
||||
const flatArray: FacetedValue[] = [];
|
||||
|
||||
@@ -140,9 +140,12 @@ export const useSlots = (event: { id: number; length: number } | null) => {
|
||||
useEffect(() => {
|
||||
handleReserveSlot();
|
||||
|
||||
const interval = setInterval(() => {
|
||||
handleReserveSlot();
|
||||
}, parseInt(MINUTES_TO_BOOK) * 60 * 1000 - 2000);
|
||||
const interval = setInterval(
|
||||
() => {
|
||||
handleReserveSlot();
|
||||
},
|
||||
parseInt(MINUTES_TO_BOOK) * 60 * 1000 - 2000
|
||||
);
|
||||
|
||||
return () => {
|
||||
handleRemoveSlot();
|
||||
|
||||
Loaded 100 of 271 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user