refactor: Move trpc-dependent components from features to web [1] (#25859)
* refactor: migrate UnconfirmedBookingBadge from features to apps/web Move UnconfirmedBookingBadge.tsx from packages/features/bookings/ to apps/web/modules/bookings/components/ as part of the architectural refactor to remove trpc client imports from the features layer. Also removes unused preserveBookingsQueryParams function from Navigation.tsx. Co-Authored-By: [email protected] <[email protected]> * refactor: move shell navigation and badges to apps/web Move shell navigation components and trpc-using badges from packages/features to apps/web/modules to fix circular dependency: - Move navigation folder to apps/web/modules/shell/navigation/ - Move TeamInviteBadge.tsx to apps/web/modules/shell/ - Create Shell wrapper in apps/web that provides MobileNavigationContainer - Update all Shell imports in apps/web to use the new wrapper - Remove MobileNavigationContainer default from features Shell.tsx - Fix pre-existing lint warnings in touched files This establishes the pattern for migrating React components that use trpc hooks from the features layer to the web app layer, ensuring proper dependency direction: apps/web imports from packages/features, never the reverse. Co-Authored-By: [email protected] <[email protected]> * fix: move SideBar.tsx to apps/web to fix build error SideBar.tsx was importing Navigation from the moved navigation folder, causing a build error. Moving SideBar.tsx to apps/web and updating the features Shell to not have a default SidebarContainer fixes this. The web Shell wrapper now provides both the default SidebarContainer and MobileNavigationContainer, maintaining the injection pattern. Co-Authored-By: [email protected] <[email protected]> * revert * revert * revert * wip * wip * wip * wip * wip * wip * not used anywhere * wip * wip * wip * wip * fix * fix * wip * wip * wip * wip * wip * fix * fix * fix * fix * migrate * migrate admin-adpi * wip * feat: migrate organization settings components from packages/features to apps/web/modules - Migrate profile.tsx, appearance.tsx, general.tsx, privacy.tsx, guest-notifications.tsx, delegationCredential.tsx, other-team-members-view.tsx, other-team-profile-view.tsx - Migrate attributes directory (AttributesForm.tsx, DeleteAttributeModal.tsx, ListSkeleton.tsx, attributes-create-view.tsx, attributes-edit-view.tsx, attributes-list-view.tsx) - Migrate admin directory (AdminOrgEditPage.tsx, AdminOrgPage.tsx, WorkspacePlatformPage.tsx) - Update all page imports to use new paths from ~/settings/organizations/ - Update relative imports in migrated files to use @calcom/features paths - Fix lint warnings in migrated files Co-Authored-By: [email protected] <[email protected]> * fix: update test import path after migration Co-Authored-By: [email protected] <[email protected]> * fix: remove unnecessary test-setup import (already in vitest config) Co-Authored-By: [email protected] <[email protected]> * wip * refactor: delete original files after migration to apps/web/modules Co-Authored-By: [email protected] <[email protected]> * wip * wip * wip * wip * wip * wip * wip * wip * wip * wip * wip * wip * wip * fix * fix * fix * fix * wip * refactor more * wip * wip * wip * wip * wip * wip * wip * wip * wip * wip * mv * update import paths * wip * wip * fix * fix * fix * fix * fix * fix * fix * mv * mv * mv * fix * wip * wip * fix * fix * fix * fix: make test mocks resilient to vi.resetAllMocks() Co-Authored-By: [email protected] <[email protected]> * fix: fix AttributeForm test failures Co-Authored-By: [email protected] <[email protected]> * fix * fix * refactor: move ee files to apps/web/modules/ee/ folder - Move teams, workflows, and organizations folders to apps/web/modules/ee/ - Add LICENSE file to apps/web/modules/ee/ - Update all import paths from ~/teams/ to ~/ee/teams/ - Update all import paths from ~/settings/organizations/ to ~/ee/organizations/ - Remove duplicate MemberInvitationModal copy.tsx file Co-Authored-By: [email protected] <[email protected]> * fix: move useHasPaidPlan and dependent files to apps/web/modules - Move useHasPaidPlan.ts from packages/features/billing/hooks to apps/web/modules/billing/hooks - Move intercom files from packages/features/ee/support to apps/web/modules/ee/support - Move ContactMenuItem.tsx and dependencies (freshchat, helpscout, zendesk) to apps/web/modules/ee/support - Move ViewRecordingsDialog.tsx and RecordingListSkeleton to apps/web/modules/ee/video - Move CalVideoSettings.tsx to apps/web/modules/eventtypes/components/locations - Move CreateOrEditOutOfOfficeModal.tsx to apps/web/modules/settings/outOfOffice - Refactor UpgradeTeamsBadge to accept props and create wrapper in apps/web/modules/billing - Update all callers to use new file locations - Add eslint-disable comments for pre-existing lint warnings This fixes the tRPC server build failure caused by circular dependency where the server build was traversing into packages/features and pulling in React hooks that depend on @calcom/trpc/react types. Co-Authored-By: [email protected] <[email protected]> * fix: correct UpgradeTeamsBadge import path to use package export Co-Authored-By: [email protected] <[email protected]> * wip * wip * wip * wip * wip * wip * wip * wip * wip * wip * wip * wip * wip * wip * wip * fix * fix * fix * fix * fix * fix * fix * fix: pass plan state through SelectProps to UpgradeTeamsBadge - Add upgradeTeamsBadgeProps field to ExtendedOption type in Select component - Update OptionComponent to spread upgradeTeamsBadgeProps to UpgradeTeamsBadge - Update getOptions.ts to accept PlanState object and include upgradeTeamsBadgeProps - Update WorkflowStepContainer.tsx to pass planState to getWorkflowTriggerOptions/getWorkflowTemplateOptions - Update WorkflowDetailsPage.tsx to pass upgradeTeamsBadgeProps in transformed action options - Update AddActionDialog.tsx interface and mapping to include upgradeTeamsBadgeProps - Add eslint-disable comments for pre-existing React Hook dependency warnings This fixes the UpgradeTeamsBadge refactoring issue where the badge was always showing 'upgrade' text instead of the correct text based on plan state (trial_mode, inactive_team_plan, etc.) Co-Authored-By: [email protected] <[email protected]> * fix: update import paths to use /ee/ folder for workflows and organizations Co-Authored-By: [email protected] <[email protected]> * fix: update workflow component imports to use /ee/ folder Co-Authored-By: [email protected] <[email protected]> * fix: add missing types.ts for LocationInput.tsx Co-Authored-By: [email protected] <[email protected]> * fix: extract BookingRedirectForm type to shared location Co-Authored-By: [email protected] <[email protected]> * fix * wip * wip * fix: update BookingRedirectForm import to use local types file Co-Authored-By: [email protected] <[email protected]> * wip * fix * fix --------- Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
This commit is contained in:
1 parent
7847177e8b
commit
8afe87ff75
374 files changed
+1213
-1417
No files matched your search
@@ -1,56 +0,0 @@
|
||||
import { IS_SELF_HOSTED } from "@calcom/lib/constants";
|
||||
import hasKeyInMetadata from "@calcom/lib/hasKeyInMetadata";
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
|
||||
export function useHasPaidPlan() {
|
||||
if (IS_SELF_HOSTED) return { isPending: false, hasPaidPlan: true };
|
||||
|
||||
const { data, isPending: isPendingTeamQuery } = trpc.viewer.teams.hasTeamPlan.useQuery();
|
||||
|
||||
const { data: user, isPending: isPendingUserQuery } = trpc.viewer.me.get.useQuery();
|
||||
|
||||
const isPending = isPendingTeamQuery || isPendingUserQuery;
|
||||
|
||||
const isCurrentUsernamePremium =
|
||||
user && hasKeyInMetadata(user, "isPremium") ? !!user.metadata.isPremium : false;
|
||||
|
||||
const hasPaidPlan = data?.hasTeamPlan || isCurrentUsernamePremium;
|
||||
|
||||
return { isPending, hasPaidPlan, plan: data?.plan };
|
||||
}
|
||||
|
||||
export function useTeamInvites() {
|
||||
const listInvites = trpc.viewer.teams.listInvites.useQuery();
|
||||
|
||||
return { isPending: listInvites.isPending, listInvites: listInvites.data };
|
||||
}
|
||||
|
||||
export function useHasTeamPlan() {
|
||||
const { data: hasTeamPlan, isPending } = trpc.viewer.teams.hasTeamPlan.useQuery();
|
||||
|
||||
return { isPending, hasTeamPlan: hasTeamPlan?.hasTeamPlan };
|
||||
}
|
||||
|
||||
export function useHasEnterprisePlan() {
|
||||
// TODO: figure out how to get "has Enterprise / has Org" from the backend
|
||||
const { data: hasTeamPlan, isPending } = trpc.viewer.teams.hasTeamPlan.useQuery();
|
||||
|
||||
return { isPending, hasTeamPlan: hasTeamPlan?.hasTeamPlan };
|
||||
}
|
||||
|
||||
export function useHasActiveTeamPlan() {
|
||||
if (IS_SELF_HOSTED) return { isPending: false, hasActiveTeamPlan: true, isTrial: false };
|
||||
|
||||
const { data, isPending } = trpc.viewer.teams.hasActiveTeamPlan.useQuery();
|
||||
|
||||
return { isPending, hasActiveTeamPlan: !!data?.isActive, isTrial: !!data?.isTrial };
|
||||
}
|
||||
export function useHasActiveTeamPlanAsOwner() {
|
||||
if (IS_SELF_HOSTED) return { isPending: false, hasActiveTeamPlan: true, isTrial: false };
|
||||
|
||||
const { data, isPending } = trpc.viewer.teams.hasActiveTeamPlan.useQuery({ ownerOnly: true });
|
||||
|
||||
return { isPending, hasActiveTeamPlan: !!data?.isActive, isTrial: !!data?.isTrial };
|
||||
}
|
||||
|
||||
export default useHasPaidPlan;
|
||||
@@ -1,22 +0,0 @@
|
||||
import Link from "next/link";
|
||||
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
import { Badge } from "@calcom/ui/components/badge";
|
||||
|
||||
export default function UnconfirmedBookingBadge() {
|
||||
const { t } = useLocale();
|
||||
const { data: unconfirmedBookingCount } = trpc.viewer.me.bookingUnconfirmedCount.useQuery();
|
||||
if (!unconfirmedBookingCount) return null;
|
||||
return (
|
||||
<Link href="/bookings/unconfirmed">
|
||||
<Badge
|
||||
rounded
|
||||
title={t("unconfirmed_bookings_tooltip")}
|
||||
variant="orange"
|
||||
className="cursor-pointer hover:bg-orange-800 hover:text-orange-100">
|
||||
{unconfirmedBookingCount}
|
||||
</Badge>
|
||||
</Link>
|
||||
);
|
||||
}
|
||||
@@ -2,7 +2,6 @@ import { isValidPhoneNumber } from "libphonenumber-js/max";
|
||||
import { v4 as uuidv4 } from "uuid";
|
||||
|
||||
import { PrismaApiKeyRepository } from "@calcom/features/ee/api-keys/repositories/PrismaApiKeyRepository";
|
||||
import { replaceEventTypePlaceholders } from "@calcom/features/ee/workflows/components/agent-configuration/utils/promptUtils";
|
||||
import { EventTypeRepository } from "@calcom/features/eventtypes/repositories/eventTypeRepository";
|
||||
import { RETELL_AI_TEST_MODE, RETELL_AI_TEST_EVENT_TYPE_MAP } from "@calcom/lib/constants";
|
||||
import { timeZoneSchema } from "@calcom/lib/dayjs/timeZone.schema";
|
||||
@@ -22,6 +21,7 @@ import type { PhoneNumberRepositoryInterface } from "../../interfaces/PhoneNumbe
|
||||
import { RetellAIServiceMapper } from "../RetellAIServiceMapper";
|
||||
import type { RetellAIRepository, Language } from "../types";
|
||||
import { getLlmId } from "../types";
|
||||
import { replaceEventTypePlaceholders } from "../utils/promptUtils";
|
||||
|
||||
type Dependencies = {
|
||||
retellRepository: RetellAIRepository;
|
||||
|
||||
File renamed without changes.
@@ -1,9 +1,9 @@
|
||||
import { Dialog } from "@calcom/features/components/controlled-dialog";
|
||||
import { CreateANewTeamForm } from "@calcom/features/ee/teams/components";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
import { DialogContent } from "@calcom/ui/components/dialog";
|
||||
import { revalidateTeamsList } from "@calcom/web/app/(use-page-wrapper)/(main-nav)/teams/actions";
|
||||
import { CreateANewTeamForm } from "@calcom/web/modules/ee/teams/components/CreateANewTeamForm";
|
||||
|
||||
interface CreateTeamDialogProps {
|
||||
open: boolean;
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
export { CreateANewOrganizationForm } from "./CreateANewOrganizationForm";
|
||||
export { AboutOrganizationForm } from "./AboutOrganizationForm";
|
||||
export { AddNewTeamsForm } from "@calcom/web/modules/settings/organizations/new/_components/AddNewTeamsForm";
|
||||
export { AdminOnboardingHandover } from "./AdminOnboardingHandover";
|
||||
@@ -1,6 +1,5 @@
|
||||
import classNames from "classnames";
|
||||
|
||||
import TeamPill, { TeamRole } from "@calcom/ee/teams/components/TeamPill";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import type { RouterOutputs } from "@calcom/trpc/react";
|
||||
import { UserAvatar } from "@calcom/ui/components/avatar";
|
||||
@@ -14,6 +13,7 @@ import {
|
||||
DropdownMenuTrigger,
|
||||
} from "@calcom/ui/components/dropdown";
|
||||
import { Tooltip } from "@calcom/ui/components/tooltip";
|
||||
import TeamPill, { TeamRole } from "@calcom/web/modules/ee/teams/components/TeamPill";
|
||||
|
||||
interface Props {
|
||||
member: RouterOutputs["viewer"]["organizations"]["listOtherTeamMembers"]["rows"][number];
|
||||
|
||||
@@ -1,58 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import LicenseRequired from "@calcom/features/ee/common/components/LicenseRequired";
|
||||
import { UpgradeTip } from "@calcom/features/tips";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { Button } from "@calcom/ui/components/button";
|
||||
import { ButtonGroup } from "@calcom/ui/components/buttonGroup";
|
||||
import { Icon } from "@calcom/ui/components/icon";
|
||||
|
||||
export const AdminAPIView = () => {
|
||||
const { t } = useLocale();
|
||||
|
||||
const features = [
|
||||
{
|
||||
icon: <Icon name="terminal" className="h-5 w-5 text-pink-500" />,
|
||||
title: t("admin_api"),
|
||||
description: t("leverage_our_api"),
|
||||
},
|
||||
{
|
||||
icon: <Icon name="folder" className="h-5 w-5 text-red-500" />,
|
||||
title: `SCIM & ${t("directory_sync")}`,
|
||||
description: t("directory_sync_description"),
|
||||
},
|
||||
{
|
||||
icon: <Icon name="sparkles" className="h-5 w-5 text-blue-500" />,
|
||||
title: "Cal.ai",
|
||||
description: t("use_cal_ai_to_make_call_description"),
|
||||
},
|
||||
];
|
||||
return (
|
||||
<LicenseRequired>
|
||||
<div className="mt-8">
|
||||
<UpgradeTip
|
||||
plan="enterprise"
|
||||
title={t("enterprise_license")}
|
||||
description={t("create_your_enterprise_description")}
|
||||
features={features}
|
||||
background="/tips/enterprise"
|
||||
buttons={
|
||||
<div className="stack-y-2 rtl:space-x-reverse sm:space-x-2">
|
||||
<ButtonGroup>
|
||||
<Button color="primary" href="https://cal.com/sales" target="_blank">
|
||||
{t("contact_sales")}
|
||||
</Button>
|
||||
<Button color="minimal" href="https://cal.com/enterprise" target="_blank">
|
||||
{t("learn_more")}
|
||||
</Button>
|
||||
</ButtonGroup>
|
||||
</div>
|
||||
}>
|
||||
<>Create Org</>
|
||||
</UpgradeTip>
|
||||
</div>
|
||||
</LicenseRequired>
|
||||
);
|
||||
};
|
||||
|
||||
export default AdminAPIView;
|
||||
@@ -1,84 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useForm } from "react-hook-form";
|
||||
import type { z } from "zod";
|
||||
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import type { Team } from "@calcom/prisma/client";
|
||||
import type { orgSettingsSchema } from "@calcom/prisma/zod-utils";
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
import { Button } from "@calcom/ui/components/button";
|
||||
import { Form } from "@calcom/ui/components/form";
|
||||
import { TextField } from "@calcom/ui/components/form";
|
||||
import { showToast } from "@calcom/ui/components/toast";
|
||||
|
||||
type FormValues = {
|
||||
name: Team["name"];
|
||||
slug: Team["slug"];
|
||||
organizationSettings: z.infer<typeof orgSettingsSchema>;
|
||||
};
|
||||
|
||||
export const OrgForm = ({
|
||||
org,
|
||||
}: {
|
||||
org: FormValues & {
|
||||
id: Team["id"];
|
||||
};
|
||||
}) => {
|
||||
const { t } = useLocale();
|
||||
const router = useRouter();
|
||||
const utils = trpc.useUtils();
|
||||
const mutation = trpc.viewer.organizations.adminUpdate.useMutation({
|
||||
onSuccess: async () => {
|
||||
await Promise.all([
|
||||
utils.viewer.organizations.adminGetAll.invalidate(),
|
||||
utils.viewer.organizations.adminGet.invalidate({
|
||||
id: org.id,
|
||||
}),
|
||||
]);
|
||||
showToast(t("org_has_been_processed"), "success");
|
||||
router.replace(`/settings/admin/organizations`);
|
||||
},
|
||||
onError: (err) => {
|
||||
showToast(err.message, "error");
|
||||
},
|
||||
});
|
||||
|
||||
const form = useForm<FormValues>({
|
||||
defaultValues: org,
|
||||
});
|
||||
|
||||
const onSubmit = (values: FormValues) => {
|
||||
mutation.mutate({
|
||||
id: org.id,
|
||||
...values,
|
||||
organizationSettings: {
|
||||
...org.organizationSettings,
|
||||
orgAutoAcceptEmail: values.organizationSettings?.orgAutoAcceptEmail,
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<Form form={form} className="stack-y-4" handleSubmit={onSubmit}>
|
||||
<TextField label="Name" placeholder="example" required {...form.register("name")} />
|
||||
<TextField label="Slug" placeholder="example" required {...form.register("slug")} />
|
||||
<p className="text-default mt-2 text-sm">
|
||||
Changing the slug would delete the previous organization domain and DNS and setup new domain and DNS
|
||||
for the organization.
|
||||
</p>
|
||||
<TextField
|
||||
label="Domain for which invitations are auto-accepted"
|
||||
placeholder="abc.com"
|
||||
required
|
||||
{...form.register("organizationSettings.orgAutoAcceptEmail")}
|
||||
/>
|
||||
<Button type="submit" color="primary" loading={mutation.isPending}>
|
||||
{t("save")}
|
||||
</Button>
|
||||
</Form>
|
||||
);
|
||||
};
|
||||
|
||||
export default OrgForm;
|
||||
@@ -1,274 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
|
||||
import { Dialog } from "@calcom/features/components/controlled-dialog";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
import { Badge } from "@calcom/ui/components/badge";
|
||||
import { ConfirmationDialogContent } from "@calcom/ui/components/dialog";
|
||||
import { DropdownActions, Table } from "@calcom/ui/components/table";
|
||||
import { showToast } from "@calcom/ui/components/toast";
|
||||
|
||||
import { subdomainSuffix } from "../../../../organizations/lib/orgDomains";
|
||||
|
||||
const { Body, Cell, ColumnTitle, Header, Row } = Table;
|
||||
|
||||
export function AdminOrgTable() {
|
||||
const { t } = useLocale();
|
||||
const utils = trpc.useUtils();
|
||||
const [data] = trpc.viewer.organizations.adminGetAll.useSuspenseQuery();
|
||||
const updateMutation = trpc.viewer.organizations.adminUpdate.useMutation({
|
||||
onSuccess: async (_data, variables) => {
|
||||
showToast(t("org_has_been_processed"), "success");
|
||||
await invalidateQueries(utils, {
|
||||
orgId: variables.id,
|
||||
});
|
||||
},
|
||||
onError: (err) => {
|
||||
showToast(err.message, "error");
|
||||
},
|
||||
});
|
||||
|
||||
const deleteMutation = trpc.viewer.organizations.adminDelete.useMutation({
|
||||
onSuccess: async (res, variables) => {
|
||||
showToast(res.message, "success");
|
||||
await invalidateQueries(utils, variables);
|
||||
},
|
||||
onError: (err) => {
|
||||
console.error(err.message);
|
||||
showToast(t("org_error_processing"), "error");
|
||||
},
|
||||
});
|
||||
|
||||
const publishOrg = async (org: (typeof data)[number]) => {
|
||||
if (!org.metadata?.requestedSlug) {
|
||||
showToast(t("could_not_find_slug_to_publish_org"), "error");
|
||||
console.error("metadata.requestedSlug isn't set", org.metadata?.requestedSlug);
|
||||
return;
|
||||
}
|
||||
updateMutation.mutate({
|
||||
id: org.id,
|
||||
slug: org.metadata.requestedSlug,
|
||||
});
|
||||
};
|
||||
|
||||
const [orgToDelete, setOrgToDelete] = useState<(typeof data)[number] | null>(null);
|
||||
return (
|
||||
<div>
|
||||
<Table>
|
||||
<Header>
|
||||
<ColumnTitle widthClassNames="w-auto">{t("organization")}</ColumnTitle>
|
||||
<ColumnTitle widthClassNames="w-auto">{t("owner")}</ColumnTitle>
|
||||
<ColumnTitle widthClassNames="w-auto">{t("reviewed")}</ColumnTitle>
|
||||
<ColumnTitle widthClassNames="w-auto">{t("dns_configured")}</ColumnTitle>
|
||||
<ColumnTitle widthClassNames="w-auto">{t("published")}</ColumnTitle>
|
||||
<ColumnTitle widthClassNames="w-auto">{t("admin_api")}</ColumnTitle>
|
||||
<ColumnTitle widthClassNames="w-auto">
|
||||
<span className="sr-only">{t("edit")}</span>
|
||||
</ColumnTitle>
|
||||
</Header>
|
||||
<Body>
|
||||
{data.map((org) => (
|
||||
<Row key={org.id}>
|
||||
<Cell widthClassNames="w-auto">
|
||||
<div className="text-subtle font-medium">
|
||||
<span className="text-default">{org.name}</span>
|
||||
<br />
|
||||
<span className="text-muted">
|
||||
{org.slug}.{subdomainSuffix()}
|
||||
</span>
|
||||
</div>
|
||||
</Cell>
|
||||
<Cell widthClassNames="w-auto">
|
||||
<span className="break-all">
|
||||
{org.members.length ? org.members[0].user.email : "No members"}
|
||||
</span>
|
||||
</Cell>
|
||||
<Cell>
|
||||
<div className="space-x-2">
|
||||
{!org.organizationSettings?.isAdminReviewed ? (
|
||||
<Badge variant="red">{t("unreviewed")}</Badge>
|
||||
) : (
|
||||
<Badge variant="green">{t("reviewed")}</Badge>
|
||||
)}
|
||||
</div>
|
||||
</Cell>
|
||||
<Cell>
|
||||
<div className="space-x-2">
|
||||
{org.organizationSettings?.isOrganizationConfigured ? (
|
||||
<Badge variant="blue">{t("dns_configured")}</Badge>
|
||||
) : (
|
||||
<Badge variant="red">{t("dns_missing")}</Badge>
|
||||
)}
|
||||
</div>
|
||||
</Cell>
|
||||
<Cell>
|
||||
<div className="space-x-2">
|
||||
{!org.slug ? (
|
||||
<Badge variant="red">{t("unpublished")}</Badge>
|
||||
) : (
|
||||
<Badge variant="green">{t("published")}</Badge>
|
||||
)}
|
||||
</div>
|
||||
</Cell>
|
||||
<Cell>
|
||||
<div className="space-x-2">
|
||||
{!org.organizationSettings?.isAdminAPIEnabled ? (
|
||||
<Badge variant="red">{t("disabled")}</Badge>
|
||||
) : (
|
||||
<Badge variant="green">{t("enabled")}</Badge>
|
||||
)}
|
||||
</div>
|
||||
</Cell>
|
||||
<Cell widthClassNames="w-auto">
|
||||
<div className="flex w-full justify-end">
|
||||
<DropdownActions
|
||||
actions={[
|
||||
...(!org.organizationSettings?.isAdminReviewed
|
||||
? [
|
||||
{
|
||||
id: "review",
|
||||
label: t("review"),
|
||||
onClick: () => {
|
||||
updateMutation.mutate({
|
||||
id: org.id,
|
||||
organizationSettings: {
|
||||
isAdminReviewed: true,
|
||||
},
|
||||
});
|
||||
},
|
||||
icon: "check" as const,
|
||||
},
|
||||
]
|
||||
: []),
|
||||
...(!org.organizationSettings?.isOrganizationConfigured
|
||||
? [
|
||||
{
|
||||
id: "dns",
|
||||
label: t("mark_dns_configured"),
|
||||
onClick: () => {
|
||||
updateMutation.mutate({
|
||||
id: org.id,
|
||||
organizationSettings: {
|
||||
isOrganizationConfigured: true,
|
||||
},
|
||||
});
|
||||
},
|
||||
icon: "check-check" as const,
|
||||
},
|
||||
]
|
||||
: []),
|
||||
{
|
||||
id: "edit",
|
||||
label: t("edit"),
|
||||
href: `/settings/admin/organizations/${org.id}/edit`,
|
||||
icon: "pencil" as const,
|
||||
},
|
||||
...(!org.slug
|
||||
? [
|
||||
{
|
||||
id: "publish",
|
||||
label: t("publish"),
|
||||
onClick: () => {
|
||||
publishOrg(org);
|
||||
},
|
||||
icon: "book-open-check" as const,
|
||||
},
|
||||
]
|
||||
: []),
|
||||
{
|
||||
id: "api",
|
||||
label: org.organizationSettings?.isAdminAPIEnabled
|
||||
? t("revoke_admin_api")
|
||||
: t("grant_admin_api"),
|
||||
onClick: () => {
|
||||
updateMutation.mutate({
|
||||
id: org.id,
|
||||
organizationSettings: {
|
||||
isAdminAPIEnabled: !org.organizationSettings?.isAdminAPIEnabled,
|
||||
},
|
||||
});
|
||||
},
|
||||
icon: "terminal" as const,
|
||||
},
|
||||
{
|
||||
id: "delete",
|
||||
label: t("delete"),
|
||||
onClick: () => {
|
||||
setOrgToDelete(org);
|
||||
},
|
||||
icon: "trash" as const,
|
||||
},
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
</Cell>
|
||||
</Row>
|
||||
))}
|
||||
</Body>
|
||||
</Table>
|
||||
<DeleteOrgDialog
|
||||
org={orgToDelete}
|
||||
onClose={() => setOrgToDelete(null)}
|
||||
onConfirm={() => {
|
||||
if (!orgToDelete) return;
|
||||
deleteMutation.mutate({
|
||||
orgId: orgToDelete.id,
|
||||
});
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default AdminOrgTable;
|
||||
|
||||
const DeleteOrgDialog = ({
|
||||
org,
|
||||
onConfirm,
|
||||
onClose,
|
||||
}: {
|
||||
org: {
|
||||
id: number;
|
||||
name: string;
|
||||
} | null;
|
||||
onConfirm: () => void;
|
||||
onClose: () => void;
|
||||
}) => {
|
||||
const { t } = useLocale();
|
||||
if (!org) {
|
||||
return null;
|
||||
}
|
||||
return (
|
||||
// eslint-disable-next-line @typescript-eslint/no-empty-function -- noop
|
||||
<Dialog name="delete-user" open={!!org.id} onOpenChange={(open) => (open ? () => {} : onClose())}>
|
||||
<ConfirmationDialogContent
|
||||
title={t("admin_delete_organization_title", {
|
||||
organizationName: org.name,
|
||||
})}
|
||||
confirmBtnText={t("delete")}
|
||||
cancelBtnText={t("cancel")}
|
||||
variety="danger"
|
||||
onConfirm={onConfirm}>
|
||||
<ul className="ml-4 mt-5 list-disc stack-y-2">
|
||||
<li>{t("admin_delete_organization_description_1")}</li>
|
||||
<li>{t("admin_delete_organization_description_2")}</li>
|
||||
<li>{t("admin_delete_organization_description_3")}</li>
|
||||
<li>{t("admin_delete_organization_description_4")}</li>
|
||||
</ul>
|
||||
</ConfirmationDialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
};
|
||||
|
||||
async function invalidateQueries(utils: ReturnType<typeof trpc.useUtils>, data: { orgId: number }) {
|
||||
await utils.viewer.organizations.adminGetAll.invalidate();
|
||||
await utils.viewer.organizations.adminGet.invalidate({
|
||||
id: data.orgId,
|
||||
});
|
||||
// Due to some super weird reason, just invalidate doesn't work, so do refetch as well.
|
||||
await utils.viewer.organizations.adminGet.refetch({
|
||||
id: data.orgId,
|
||||
});
|
||||
}
|
||||
@@ -1,446 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { useState } from "react";
|
||||
import type { SubmitHandler } from "react-hook-form";
|
||||
import { useForm, useFormContext } from "react-hook-form";
|
||||
import { z } from "zod";
|
||||
|
||||
import { Dialog } from "@calcom/features/components/controlled-dialog";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { serviceAccountKeySchema } from "@calcom/prisma/zod-utils";
|
||||
import { trpc, type RouterOutputs } from "@calcom/trpc/react";
|
||||
import { Button } from "@calcom/ui/components/button";
|
||||
import { DialogContent, DialogFooter, DialogClose } from "@calcom/ui/components/dialog";
|
||||
import { Form } from "@calcom/ui/components/form";
|
||||
import { TextAreaField } from "@calcom/ui/components/form";
|
||||
import { TextField } from "@calcom/ui/components/form";
|
||||
import { Switch } from "@calcom/ui/components/form";
|
||||
import { DropdownActions, Table } from "@calcom/ui/components/table";
|
||||
import { showToast } from "@calcom/ui/components/toast";
|
||||
|
||||
const { Body, Cell, ColumnTitle, Header, Row } = Table;
|
||||
|
||||
type WorkspacePlatform = RouterOutputs["viewer"]["admin"]["workspacePlatform"]["list"][number];
|
||||
type EditType = "meta" | "serviceAccount";
|
||||
|
||||
type Props = {
|
||||
workspacePlatforms: WorkspacePlatform[];
|
||||
onAdd: () => void;
|
||||
onEdit: (platform: WorkspacePlatform, editType: EditType) => void;
|
||||
onToggle: (platform: WorkspacePlatform, checked: boolean) => void;
|
||||
isOpen: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
editingPlatform: WorkspacePlatform;
|
||||
isCreate: boolean;
|
||||
platform: WorkspacePlatform;
|
||||
platformId?: number;
|
||||
platforms: WorkspacePlatform[];
|
||||
};
|
||||
|
||||
const WorkspacePlatformsPage = () => {
|
||||
const { t } = useLocale();
|
||||
const [isDialogOpen, setIsDialogOpen] = useState(false);
|
||||
|
||||
const [editing, setEditing] = useState<
|
||||
{ platform: WorkspacePlatform; editType: EditType } | { platform: null; editType: EditType }
|
||||
>({ platform: null, editType: "meta" });
|
||||
|
||||
const utils = trpc.useUtils();
|
||||
const { data: workspacePlatforms, isPending, error } = trpc.viewer.admin.workspacePlatform.list.useQuery();
|
||||
const toggleEnabledMutation = trpc.viewer.admin.workspacePlatform.toggleEnabled.useMutation({
|
||||
onSuccess: () => {
|
||||
showToast(t("workspace_platform_updated_successfully"), "success");
|
||||
utils.viewer.admin.workspacePlatform.list.invalidate();
|
||||
},
|
||||
onError: (error) => {
|
||||
console.error(error);
|
||||
showToast(t("something_went_wrong"), "error");
|
||||
},
|
||||
});
|
||||
|
||||
if (error) {
|
||||
return <ErrorState />;
|
||||
}
|
||||
|
||||
if (isPending || !workspacePlatforms) return <LoadingState />;
|
||||
|
||||
return (
|
||||
<>
|
||||
<PageContent
|
||||
workspacePlatforms={workspacePlatforms}
|
||||
onAdd={handleAdd}
|
||||
onEdit={handleEdit}
|
||||
onToggle={handleToggle}
|
||||
/>
|
||||
{editing.editType === "meta" && (
|
||||
<CreateUpdatePlatformDialog
|
||||
isOpen={isDialogOpen}
|
||||
onOpenChange={setIsDialogOpen}
|
||||
editingPlatform={editing.platform || undefined}
|
||||
key={editing.platform?.id}
|
||||
/>
|
||||
)}
|
||||
{editing.editType === "serviceAccount" && (
|
||||
<UpdateServiceAccountFieldsDialog
|
||||
isOpen={isDialogOpen}
|
||||
onOpenChange={setIsDialogOpen}
|
||||
platformId={editing.platform?.id}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
|
||||
function handleAdd() {
|
||||
setEditing({ platform: null, editType: "meta" });
|
||||
setIsDialogOpen(true);
|
||||
}
|
||||
|
||||
function handleEdit(platform: Props["platform"], editType: "meta" | "serviceAccount" = "meta") {
|
||||
setEditing({ platform, editType });
|
||||
setIsDialogOpen(true);
|
||||
}
|
||||
|
||||
function handleToggle(platform: Props["platform"], checked: boolean) {
|
||||
toggleEnabledMutation.mutate({ ...platform, enabled: checked });
|
||||
}
|
||||
};
|
||||
|
||||
function LoadingState() {
|
||||
const { t } = useLocale();
|
||||
return <div>{t("loading")}...</div>;
|
||||
}
|
||||
|
||||
function ErrorState() {
|
||||
const { t } = useLocale();
|
||||
return <div>{t("something_went_wrong")}</div>;
|
||||
}
|
||||
|
||||
function PageContent({
|
||||
workspacePlatforms,
|
||||
onAdd,
|
||||
onEdit,
|
||||
onToggle,
|
||||
}: Pick<Props, "workspacePlatforms" | "onAdd" | "onEdit" | "onToggle">) {
|
||||
return (
|
||||
<div>
|
||||
{workspacePlatforms.length === 0 ? (
|
||||
<EmptyState onAdd={onAdd} />
|
||||
) : (
|
||||
<PlatformList platforms={workspacePlatforms} onEdit={onEdit} onToggle={onToggle} onAdd={onAdd} />
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function EmptyState({ onAdd }: Pick<Props, "onAdd">) {
|
||||
const { t } = useLocale();
|
||||
|
||||
return (
|
||||
<div className="flex flex-col items-center justify-center stack-y-4 py-10">
|
||||
<p className="text-gray-500">{t("no_workspace_platforms")}</p>
|
||||
<Button color="secondary" onClick={onAdd}>
|
||||
{t("add")}
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function PlatformList({
|
||||
platforms,
|
||||
onEdit,
|
||||
onToggle,
|
||||
onAdd,
|
||||
}: Pick<Props, "platforms" | "onEdit" | "onToggle" | "onAdd">) {
|
||||
const { t } = useLocale();
|
||||
|
||||
return (
|
||||
<>
|
||||
<Table>
|
||||
<Header>
|
||||
<ColumnTitle widthClassNames="w-1/4">{t("platform")}</ColumnTitle>
|
||||
<ColumnTitle widthClassNames="w-1/4">{t("slug")}</ColumnTitle>
|
||||
<ColumnTitle widthClassNames="w-1/4">{t("status")}</ColumnTitle>
|
||||
<ColumnTitle widthClassNames="w-1/4">
|
||||
<span className="sr-only">{t("actions")}</span>
|
||||
</ColumnTitle>
|
||||
</Header>
|
||||
<Body>
|
||||
{platforms.map((platform) => (
|
||||
<PlatformListItem key={platform.id} platform={platform} onEdit={onEdit} onToggle={onToggle} />
|
||||
))}
|
||||
</Body>
|
||||
</Table>
|
||||
<div className="mt-4 flex justify-end">
|
||||
<Button color="secondary" onClick={onAdd}>
|
||||
{t("add")}
|
||||
</Button>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function ServiceAccountFields() {
|
||||
const { t } = useLocale();
|
||||
const form = useFormContext();
|
||||
|
||||
return (
|
||||
<div className="stack-y-4">
|
||||
<TextAreaField
|
||||
required
|
||||
label={t("service_account_key")}
|
||||
{...form.register("defaultServiceAccountKey")}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function UpdateServiceAccountFieldsDialog({
|
||||
isOpen,
|
||||
onOpenChange,
|
||||
platformId,
|
||||
}: Pick<Props, "isOpen" | "onOpenChange" | "platformId">) {
|
||||
const { t } = useLocale();
|
||||
const utils = trpc.useUtils();
|
||||
type FormValues = { defaultServiceAccountKey: string };
|
||||
const form = useForm<FormValues>({
|
||||
defaultValues: {
|
||||
defaultServiceAccountKey: "",
|
||||
},
|
||||
resolver: zodResolver(z.object({ defaultServiceAccountKey: z.string() })),
|
||||
});
|
||||
|
||||
const updateServiceAccountMutation = trpc.viewer.admin.workspacePlatform.updateServiceAccount.useMutation({
|
||||
onSuccess: () => {
|
||||
showToast(t("service_account_updated_successfully"), "success");
|
||||
utils.viewer.admin.workspacePlatform.list.invalidate();
|
||||
onOpenChange(false);
|
||||
},
|
||||
onError: (error) => {
|
||||
showToast(error.message || t("something_went_wrong"), "error");
|
||||
},
|
||||
});
|
||||
|
||||
const onSubmit: SubmitHandler<FormValues> = (values) => {
|
||||
if (!platformId) return;
|
||||
|
||||
const parsedKey = JSON.parse(values.defaultServiceAccountKey);
|
||||
const validatedKey = serviceAccountKeySchema.safeParse(parsedKey);
|
||||
if (!validatedKey.success) {
|
||||
form.setError("defaultServiceAccountKey", { message: t("invalid_service_account_key") });
|
||||
return;
|
||||
}
|
||||
updateServiceAccountMutation.mutate({
|
||||
id: platformId,
|
||||
...values,
|
||||
defaultServiceAccountKey: validatedKey.data,
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open={isOpen} onOpenChange={onOpenChange}>
|
||||
<DialogContent title={t("edit_service_account_key")}>
|
||||
<Form form={form} handleSubmit={onSubmit}>
|
||||
<ServiceAccountFields />
|
||||
<DialogFooter>
|
||||
<Button type="button" color="minimal" onClick={() => onOpenChange(false)}>
|
||||
{t("cancel")}
|
||||
</Button>
|
||||
<Button type="submit" loading={updateServiceAccountMutation.isPending}>
|
||||
{t("update")}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</Form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
function PlatformListItem({ platform, onEdit, onToggle }: Pick<Props, "platform" | "onEdit" | "onToggle">) {
|
||||
const { t } = useLocale();
|
||||
|
||||
return (
|
||||
<Row>
|
||||
<Cell>
|
||||
<div className="text-subtle font-medium">
|
||||
<span className="text-default">{platform.name}</span>
|
||||
</div>
|
||||
</Cell>
|
||||
<Cell>
|
||||
<div className="text-subtle font-medium">
|
||||
<span className="text-muted">{platform.slug}</span>
|
||||
</div>
|
||||
</Cell>
|
||||
<Cell>
|
||||
<Switch checked={platform.enabled} onCheckedChange={(checked) => onToggle(platform, checked)} />
|
||||
</Cell>
|
||||
<Cell>
|
||||
<div className="flex justify-end">
|
||||
<DropdownActions
|
||||
actions={[
|
||||
{
|
||||
id: "edit",
|
||||
label: t("edit"),
|
||||
onClick: () => onEdit(platform, "meta"),
|
||||
icon: "pencil",
|
||||
},
|
||||
// {
|
||||
// id: "edit-service-account",
|
||||
// label: t("edit_service_account"),
|
||||
// onClick: () => onEdit(platform, "serviceAccount"),
|
||||
// icon: "pencil",
|
||||
// },
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
</Cell>
|
||||
</Row>
|
||||
);
|
||||
}
|
||||
|
||||
function CreatePlatformDialog({ isOpen, onOpenChange }: Pick<Props, "isOpen" | "onOpenChange">) {
|
||||
const { t } = useLocale();
|
||||
type FormValues = { name: string; description: string; slug: string; defaultServiceAccountKey?: string };
|
||||
const form = useForm<FormValues>({
|
||||
defaultValues: {
|
||||
name: "",
|
||||
description: "",
|
||||
slug: "",
|
||||
defaultServiceAccountKey: "",
|
||||
},
|
||||
resolver: zodResolver(
|
||||
z.object({
|
||||
name: z.string(),
|
||||
description: z.string(),
|
||||
slug: z.string(),
|
||||
defaultServiceAccountKey: z.string().optional(),
|
||||
})
|
||||
),
|
||||
});
|
||||
|
||||
const utils = trpc.useUtils();
|
||||
|
||||
const addMutation = trpc.viewer.admin.workspacePlatform.add.useMutation({
|
||||
onSuccess: async () => {
|
||||
showToast(t("workspace_platform_added_successfully"), "success");
|
||||
onOpenChange(false);
|
||||
await utils.viewer.admin.workspacePlatform.list.invalidate();
|
||||
},
|
||||
onError: (error) => {
|
||||
showToast(error.message, "error");
|
||||
},
|
||||
});
|
||||
|
||||
const onSubmit: SubmitHandler<FormValues> = (values) => {
|
||||
// Only validate service account key if it's provided
|
||||
if (values.defaultServiceAccountKey) {
|
||||
const parsedKey = JSON.parse(values.defaultServiceAccountKey);
|
||||
const validatedKey = serviceAccountKeySchema.safeParse(parsedKey);
|
||||
if (!validatedKey.success) {
|
||||
form.setError("defaultServiceAccountKey", { message: t("invalid_service_account_key") });
|
||||
return;
|
||||
}
|
||||
addMutation.mutate({
|
||||
...values,
|
||||
defaultServiceAccountKey: validatedKey.data,
|
||||
});
|
||||
} else {
|
||||
// Submit without service account key
|
||||
addMutation.mutate({
|
||||
name: values.name,
|
||||
description: values.description,
|
||||
slug: values.slug,
|
||||
enabled: true,
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open={isOpen} onOpenChange={onOpenChange}>
|
||||
<DialogContent enableOverflow title={t("add_workspace_platform")}>
|
||||
<Form form={form} handleSubmit={onSubmit}>
|
||||
<PlatformFormFields isCreate={true} />
|
||||
<DialogFooter>
|
||||
<DialogClose />
|
||||
<Button type="submit">{t("create")}</Button>
|
||||
</DialogFooter>
|
||||
</Form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
function UpdatePlatformDialog({
|
||||
isOpen,
|
||||
onOpenChange,
|
||||
editingPlatform,
|
||||
}: Pick<Props, "isOpen" | "onOpenChange" | "editingPlatform">) {
|
||||
const { t } = useLocale();
|
||||
type FormValues = { name: string; description: string };
|
||||
const form = useForm<FormValues>({
|
||||
defaultValues: {
|
||||
name: editingPlatform.name,
|
||||
description: editingPlatform.description,
|
||||
},
|
||||
});
|
||||
|
||||
const utils = trpc.useUtils();
|
||||
|
||||
const updateMutation = trpc.viewer.admin.workspacePlatform.update.useMutation({
|
||||
onSuccess: async () => {
|
||||
showToast(t("workspace_platform_updated_successfully"), "success");
|
||||
onOpenChange(false);
|
||||
await utils.viewer.admin.workspacePlatform.list.invalidate();
|
||||
},
|
||||
onError: function (error) {
|
||||
showToast(error.message, "error");
|
||||
},
|
||||
});
|
||||
|
||||
const onSubmit: SubmitHandler<FormValues> = (values) => {
|
||||
updateMutation.mutate({ ...values, id: editingPlatform.id });
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open={isOpen} onOpenChange={onOpenChange}>
|
||||
<DialogContent title={t("edit_workspace_platform")}>
|
||||
<Form form={form} handleSubmit={onSubmit}>
|
||||
<PlatformFormFields isCreate={false} />
|
||||
<DialogFooter>
|
||||
<DialogClose />
|
||||
<Button type="submit">{t("save")}</Button>
|
||||
</DialogFooter>
|
||||
</Form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
function PlatformFormFields({ isCreate }: Pick<Props, "isCreate">) {
|
||||
const { t } = useLocale();
|
||||
const form = useFormContext();
|
||||
|
||||
return (
|
||||
<div className="stack-y-4">
|
||||
<TextField required label={t("name")} {...form.register("name")} />
|
||||
<TextAreaField required label={t("description")} {...form.register("description")} />
|
||||
{isCreate && <TextField required label={t("slug")} {...form.register("slug")} />}
|
||||
{isCreate && false && <ServiceAccountFields />}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function CreateUpdatePlatformDialog({
|
||||
isOpen,
|
||||
onOpenChange,
|
||||
editingPlatform,
|
||||
}: Pick<Props, "isOpen" | "onOpenChange"> & { editingPlatform?: Props["editingPlatform"] }) {
|
||||
if (editingPlatform) {
|
||||
return (
|
||||
<UpdatePlatformDialog isOpen={isOpen} onOpenChange={onOpenChange} editingPlatform={editingPlatform} />
|
||||
);
|
||||
}
|
||||
return <CreatePlatformDialog isOpen={isOpen} onOpenChange={onOpenChange} />;
|
||||
}
|
||||
|
||||
export default WorkspacePlatformsPage;
|
||||
@@ -1,223 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { useSession } from "next-auth/react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useState, useEffect } from "react";
|
||||
import { useForm } from "react-hook-form";
|
||||
|
||||
import { checkAdminOrOwner } from "@calcom/features/auth/lib/checkAdminOrOwner";
|
||||
import BrandColorsForm from "@calcom/features/ee/components/BrandColorsForm";
|
||||
import { AppearanceSkeletonLoader } from "@calcom/features/ee/components/CommonSkeletonLoaders";
|
||||
import SectionBottomActions from "@calcom/features/settings/SectionBottomActions";
|
||||
import ThemeLabel from "@calcom/features/settings/ThemeLabel";
|
||||
import { DEFAULT_LIGHT_BRAND_COLOR, DEFAULT_DARK_BRAND_COLOR } from "@calcom/lib/constants";
|
||||
import { APP_NAME } from "@calcom/lib/constants";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
import type { RouterOutputs } from "@calcom/trpc/react";
|
||||
import { Button } from "@calcom/ui/components/button";
|
||||
import { Form } from "@calcom/ui/components/form";
|
||||
import { SettingsToggle } from "@calcom/ui/components/form";
|
||||
import { showToast } from "@calcom/ui/components/toast";
|
||||
|
||||
type BrandColorsFormValues = {
|
||||
brandColor: string;
|
||||
darkBrandColor: string;
|
||||
};
|
||||
|
||||
const OrgAppearanceView = ({
|
||||
currentOrg,
|
||||
}: {
|
||||
currentOrg: RouterOutputs["viewer"]["organizations"]["listCurrent"];
|
||||
isAdminOrOwner: boolean;
|
||||
}) => {
|
||||
const { t } = useLocale();
|
||||
const utils = trpc.useUtils();
|
||||
|
||||
const themeForm = useForm<{ theme: string | null | undefined }>({
|
||||
defaultValues: {
|
||||
theme: currentOrg?.theme,
|
||||
},
|
||||
});
|
||||
|
||||
const {
|
||||
formState: { isSubmitting: isOrgThemeSubmitting, isDirty: isOrgThemeDirty },
|
||||
reset: resetOrgThemeReset,
|
||||
} = themeForm;
|
||||
|
||||
const [hideBrandingValue, setHideBrandingValue] = useState(currentOrg?.hideBranding ?? false);
|
||||
const [allowSEOIndexingValue, setAllowSEOIndexingValue] = useState(
|
||||
currentOrg?.organizationSettings?.allowSEOIndexing ?? false
|
||||
);
|
||||
const [orgProfileRedirectsToVerifiedDomainValue, setOrgProfileRedirectsToVerifiedDomainValue] = useState(
|
||||
currentOrg?.organizationSettings?.orgProfileRedirectsToVerifiedDomain ?? false
|
||||
);
|
||||
|
||||
const brandColorsFormMethods = useForm<BrandColorsFormValues>({
|
||||
defaultValues: {
|
||||
brandColor: currentOrg?.brandColor || DEFAULT_LIGHT_BRAND_COLOR,
|
||||
darkBrandColor: currentOrg?.darkBrandColor || DEFAULT_DARK_BRAND_COLOR,
|
||||
},
|
||||
});
|
||||
|
||||
const mutation = trpc.viewer.organizations.update.useMutation({
|
||||
onError: (err) => {
|
||||
showToast(err.message, "error");
|
||||
},
|
||||
async onSuccess(res) {
|
||||
await utils.viewer.teams.get.invalidate();
|
||||
await utils.viewer.organizations.listCurrent.invalidate();
|
||||
|
||||
showToast(t("your_team_updated_successfully"), "success");
|
||||
if (res) {
|
||||
brandColorsFormMethods.reset({
|
||||
brandColor: res.data.brandColor as string,
|
||||
darkBrandColor: res.data.darkBrandColor as string,
|
||||
});
|
||||
resetOrgThemeReset({ theme: res.data.theme as string | undefined });
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
const onBrandColorsFormSubmit = (values: BrandColorsFormValues) => {
|
||||
mutation.mutate(values);
|
||||
};
|
||||
|
||||
return (
|
||||
<div>
|
||||
<Form
|
||||
form={themeForm}
|
||||
handleSubmit={({ theme }) => {
|
||||
if (theme === "light" || theme === "dark") {
|
||||
mutation.mutate({
|
||||
theme,
|
||||
});
|
||||
return;
|
||||
}
|
||||
mutation.mutate({
|
||||
theme: null,
|
||||
});
|
||||
}}>
|
||||
<div className="border-subtle mt-6 flex items-center rounded-t-xl border p-6 text-sm">
|
||||
<div>
|
||||
<p className="text-default text-base font-semibold">{t("theme")}</p>
|
||||
<p className="text-default">{t("theme_applies_note")}</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="border-subtle flex flex-col justify-between border-x px-6 py-8 sm:flex-row">
|
||||
<ThemeLabel
|
||||
variant="system"
|
||||
value="system"
|
||||
label={t("theme_system")}
|
||||
defaultChecked={currentOrg.theme === null}
|
||||
register={themeForm.register}
|
||||
/>
|
||||
<ThemeLabel
|
||||
variant="light"
|
||||
value="light"
|
||||
label={t("light")}
|
||||
defaultChecked={currentOrg.theme === "light"}
|
||||
register={themeForm.register}
|
||||
/>
|
||||
<ThemeLabel
|
||||
variant="dark"
|
||||
value="dark"
|
||||
label={t("dark")}
|
||||
defaultChecked={currentOrg.theme === "dark"}
|
||||
register={themeForm.register}
|
||||
/>
|
||||
</div>
|
||||
<SectionBottomActions className="mb-6" align="end">
|
||||
<Button
|
||||
disabled={isOrgThemeSubmitting || !isOrgThemeDirty}
|
||||
type="submit"
|
||||
data-testid="update-org-theme-btn"
|
||||
color="primary">
|
||||
{t("update")}
|
||||
</Button>
|
||||
</SectionBottomActions>
|
||||
</Form>
|
||||
|
||||
<Form
|
||||
form={brandColorsFormMethods}
|
||||
handleSubmit={(values) => {
|
||||
onBrandColorsFormSubmit(values);
|
||||
}}>
|
||||
<BrandColorsForm
|
||||
onSubmit={onBrandColorsFormSubmit}
|
||||
brandColor={currentOrg?.brandColor ?? DEFAULT_LIGHT_BRAND_COLOR}
|
||||
darkBrandColor={currentOrg?.darkBrandColor ?? DEFAULT_DARK_BRAND_COLOR}
|
||||
/>
|
||||
</Form>
|
||||
|
||||
<SettingsToggle
|
||||
toggleSwitchAtTheEnd={true}
|
||||
title={t("disable_cal_branding", { appName: APP_NAME })}
|
||||
disabled={mutation?.isPending}
|
||||
description={t("removes_cal_branding", { appName: APP_NAME })}
|
||||
checked={hideBrandingValue}
|
||||
onCheckedChange={(checked) => {
|
||||
setHideBrandingValue(checked);
|
||||
mutation.mutate({ hideBranding: checked });
|
||||
}}
|
||||
switchContainerClassName="mt-6"
|
||||
/>
|
||||
|
||||
<SettingsToggle
|
||||
data-testid={`${currentOrg?.id}-seo-indexing-switch`}
|
||||
toggleSwitchAtTheEnd={true}
|
||||
title={t("seo_indexing")}
|
||||
description={t("allow_seo_indexing")}
|
||||
disabled={mutation.isPending}
|
||||
checked={allowSEOIndexingValue}
|
||||
onCheckedChange={(checked) => {
|
||||
setAllowSEOIndexingValue(checked);
|
||||
mutation.mutate({ allowSEOIndexing: checked });
|
||||
}}
|
||||
switchContainerClassName="mt-6"
|
||||
/>
|
||||
|
||||
<SettingsToggle
|
||||
toggleSwitchAtTheEnd={true}
|
||||
title={t("disable_org_url_label")}
|
||||
description={t("disable_org_url_description", {
|
||||
orgSlug: currentOrg?.slug,
|
||||
destination: currentOrg?.organizationSettings?.orgAutoAcceptEmail,
|
||||
})}
|
||||
disabled={mutation.isPending}
|
||||
checked={orgProfileRedirectsToVerifiedDomainValue}
|
||||
onCheckedChange={(checked) => {
|
||||
setOrgProfileRedirectsToVerifiedDomainValue(checked);
|
||||
mutation.mutate({ orgProfileRedirectsToVerifiedDomain: checked });
|
||||
}}
|
||||
switchContainerClassName="mt-6"
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
const OrgAppearanceViewWrapper = () => {
|
||||
const router = useRouter();
|
||||
const { data: currentOrg, isPending, error } = trpc.viewer.organizations.listCurrent.useQuery();
|
||||
const session = useSession();
|
||||
const isAdminOrOwner = checkAdminOrOwner(session.data?.user?.org?.role);
|
||||
|
||||
useEffect(
|
||||
function refactorMeWithoutEffect() {
|
||||
if (error) {
|
||||
router.replace("/enterprise");
|
||||
}
|
||||
},
|
||||
[error]
|
||||
);
|
||||
|
||||
if (isPending) {
|
||||
return <AppearanceSkeletonLoader />;
|
||||
}
|
||||
|
||||
if (!currentOrg) return null;
|
||||
|
||||
return <OrgAppearanceView currentOrg={currentOrg} isAdminOrOwner={isAdminOrOwner} />;
|
||||
};
|
||||
|
||||
export default OrgAppearanceViewWrapper;
|
||||
@@ -1,489 +0,0 @@
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import React, { useState } from "react";
|
||||
import type { UseFormReturn, FieldArrayWithId } from "react-hook-form";
|
||||
import { Controller, useForm, useFieldArray } from "react-hook-form";
|
||||
import { z } from "zod";
|
||||
|
||||
import { Dialog } from "@calcom/features/components/controlled-dialog";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { InfoBadge } from "@calcom/ui/components/badge";
|
||||
import { Button } from "@calcom/ui/components/button";
|
||||
import { ConfirmationDialogContent } from "@calcom/ui/components/dialog";
|
||||
import { SettingsToggle, SelectField, Input, InputField, Form, Label } from "@calcom/ui/components/form";
|
||||
|
||||
const attributeFormSchema = z.object({
|
||||
attrName: z.string().min(1),
|
||||
isLocked: z.boolean().optional(),
|
||||
isWeightsEnabled: z.boolean().optional(),
|
||||
type: z.enum(["TEXT", "NUMBER", "SINGLE_SELECT", "MULTI_SELECT"]),
|
||||
options: z.array(
|
||||
z.object({
|
||||
value: z.string(),
|
||||
id: z.string().optional(),
|
||||
assignedUsers: z.number().optional(),
|
||||
isGroup: z.boolean().optional(),
|
||||
contains: z.array(z.string()).optional(),
|
||||
attributeOptionId: z.string().optional(),
|
||||
})
|
||||
),
|
||||
});
|
||||
|
||||
type AttributeFormValues = z.infer<typeof attributeFormSchema>;
|
||||
|
||||
const AttributeTypeOptions = [
|
||||
{ value: "TEXT", label: "Text" },
|
||||
{ value: "NUMBER", label: "Number" },
|
||||
{ value: "SINGLE_SELECT", label: "Single Select" },
|
||||
{ value: "MULTI_SELECT", label: "Multi Select" },
|
||||
];
|
||||
|
||||
interface AttributeFormProps {
|
||||
initialValues?: AttributeFormValues;
|
||||
onSubmit: (values: AttributeFormValues) => void;
|
||||
header: React.ReactNode;
|
||||
}
|
||||
|
||||
export function getGroupOptionUpdate({
|
||||
newGroupOptions,
|
||||
previousGroupOptions,
|
||||
subOption,
|
||||
allOptions,
|
||||
}: {
|
||||
newGroupOptions: { label: string; value: string | undefined }[];
|
||||
previousGroupOptions: { label: string; value: string | undefined }[];
|
||||
subOption: { attributeOptionId?: string };
|
||||
allOptions: { attributeOptionId?: string; contains?: string[] }[];
|
||||
}) {
|
||||
const nonGroupOptionId = subOption.attributeOptionId;
|
||||
if (!nonGroupOptionId) return {};
|
||||
// Find diff b/w previouslyChosenGroupOptions and chosenGroupOptions
|
||||
const removedGroupOptions = previousGroupOptions.filter(
|
||||
(option) => !newGroupOptions.map((o) => o.value).includes(option.value)
|
||||
);
|
||||
|
||||
const optionsUpdate: { [key: number]: string[] } = {};
|
||||
|
||||
// Update all groupOptions' contains as per the final state.
|
||||
newGroupOptions
|
||||
.filter((option): option is { label: string; value: string } => !!option.value)
|
||||
.forEach((newGroupOption) => {
|
||||
const { groupOption, index: indexOfGroupOptionInWatchedOptions } = getGroupOptionMatching({
|
||||
allOptions,
|
||||
toMatchWith: newGroupOption,
|
||||
});
|
||||
if (!groupOption) return;
|
||||
const existingContains = groupOption.contains;
|
||||
const newContains = [...(existingContains || []), nonGroupOptionId].filter(
|
||||
(value, index, self) => self.indexOf(value) === index
|
||||
);
|
||||
optionsUpdate[indexOfGroupOptionInWatchedOptions] = newContains;
|
||||
});
|
||||
|
||||
// Because certain groupOptions might have been removed, we need to update such groupOptions' contains as well.
|
||||
removedGroupOptions
|
||||
.filter((option): option is { label: string; value: string } => !!option.value)
|
||||
.forEach((removedGroupOption) => {
|
||||
const { groupOption, index: indexOfGroupOptionInWatchedOptions } = getGroupOptionMatching({
|
||||
allOptions,
|
||||
toMatchWith: removedGroupOption,
|
||||
});
|
||||
if (!groupOption) return;
|
||||
const existingContains = groupOption.contains || [];
|
||||
const newContains = existingContains.filter((value) => value !== nonGroupOptionId);
|
||||
optionsUpdate[indexOfGroupOptionInWatchedOptions] = newContains;
|
||||
});
|
||||
return optionsUpdate;
|
||||
|
||||
function getGroupOptionMatching({
|
||||
allOptions,
|
||||
toMatchWith,
|
||||
}: {
|
||||
allOptions: { attributeOptionId?: string; contains?: string[] }[];
|
||||
toMatchWith: { value: string };
|
||||
}) {
|
||||
const indexOfGroupOptionInWatchedOptions = allOptions.findIndex(
|
||||
(option) => option.attributeOptionId === toMatchWith.value
|
||||
);
|
||||
return {
|
||||
index: indexOfGroupOptionInWatchedOptions,
|
||||
groupOption:
|
||||
(allOptions[indexOfGroupOptionInWatchedOptions] as (typeof allOptions)[number] | undefined) ?? null,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
type AttributeOption = {
|
||||
value: string;
|
||||
id?: string;
|
||||
assignedUsers?: number;
|
||||
isGroup?: boolean;
|
||||
contains?: string[];
|
||||
attributeOptionId?: string;
|
||||
};
|
||||
|
||||
const NonGroupOption = ({
|
||||
option,
|
||||
index,
|
||||
form,
|
||||
removeOption,
|
||||
setDeleteOptionDialog,
|
||||
}: {
|
||||
option: AttributeOption;
|
||||
index: number;
|
||||
form: UseFormReturn<AttributeFormValues>;
|
||||
removeOption: (index: number) => void;
|
||||
setDeleteOptionDialog: (value: { id: number; open: boolean }) => void;
|
||||
}) => {
|
||||
const { t } = useLocale();
|
||||
return (
|
||||
<div key={option.id}>
|
||||
<div className="flex items-center gap-2" key={option.id}>
|
||||
<div className="flex w-full">
|
||||
<Input {...form.register(`options.${index}.value`)} placeholder={t("enter_option_value")} />
|
||||
</div>
|
||||
<Button
|
||||
type="button"
|
||||
variant="icon"
|
||||
StartIcon="x"
|
||||
color="minimal"
|
||||
className="mb-2"
|
||||
disabled={index === 0 && form.getValues("options").length === 1}
|
||||
onClick={() => {
|
||||
if (option.assignedUsers && option.assignedUsers > 0) {
|
||||
setDeleteOptionDialog({ id: index, open: true });
|
||||
} else {
|
||||
removeOption(index);
|
||||
}
|
||||
}}
|
||||
title={t("remove_option")}
|
||||
/>
|
||||
</div>
|
||||
<Input {...form.register(`options.${index}.id`)} className="hidden" />
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
const getNonGroupOptionsForSelect = (nonGroupOptions: AttributeOption[]) => {
|
||||
return nonGroupOptions
|
||||
.map((f) => ({
|
||||
label: f.value,
|
||||
value: f.attributeOptionId,
|
||||
}))
|
||||
.filter((option): option is { label: string; value: string } => !!option.value);
|
||||
};
|
||||
|
||||
const getSelectedNonGroupOptions = (option: AttributeOption, nonGroupOptions: AttributeOption[]) => {
|
||||
return option.contains
|
||||
?.map((containedId: string) => {
|
||||
const nonGroupOption = nonGroupOptions.find((opt) => opt.attributeOptionId === containedId);
|
||||
if (!nonGroupOption?.value || !nonGroupOption?.attributeOptionId) return null;
|
||||
return {
|
||||
label: nonGroupOption.value,
|
||||
value: nonGroupOption.attributeOptionId,
|
||||
};
|
||||
})
|
||||
.filter((val): val is { label: string; value: string } => val !== null);
|
||||
};
|
||||
|
||||
const GroupOption = ({
|
||||
option,
|
||||
index,
|
||||
form,
|
||||
removeOption,
|
||||
setDeleteOptionDialog,
|
||||
}: {
|
||||
option: AttributeOption;
|
||||
index: number;
|
||||
form: UseFormReturn<AttributeFormValues>;
|
||||
removeOption: (index: number) => void;
|
||||
setDeleteOptionDialog: (value: { id: number; open: boolean }) => void;
|
||||
}) => {
|
||||
const { t } = useLocale();
|
||||
const watchedOptions = form.getValues("options") as AttributeOption[];
|
||||
if (!watchedOptions) return null;
|
||||
|
||||
const watchedNonGroupOptions = watchedOptions.filter((field): field is AttributeOption => !field.isGroup);
|
||||
if (!watchedNonGroupOptions.length) return null;
|
||||
|
||||
const nonGroupOptionsSelectFieldOptions = getNonGroupOptionsForSelect(watchedNonGroupOptions);
|
||||
const nonGroupOptionsSelectFieldSelectedValue = getSelectedNonGroupOptions(option, watchedNonGroupOptions);
|
||||
|
||||
return (
|
||||
<div key={option.id}>
|
||||
<div className="mb-2 flex items-center gap-2" key={option.id}>
|
||||
<div className="flex w-full items-center justify-between gap-2">
|
||||
<Input {...form.register(`options.${index}.value`)} className="mb-0! w-36" />
|
||||
<SelectField
|
||||
isMulti
|
||||
placeholder={t("choose_an_option")}
|
||||
options={nonGroupOptionsSelectFieldOptions}
|
||||
value={nonGroupOptionsSelectFieldSelectedValue}
|
||||
onChange={(chosenNonGroupOptions) => {
|
||||
const newContains = chosenNonGroupOptions.map((opt) => opt.value);
|
||||
form.setValue(`options.${index}.contains`, newContains);
|
||||
}}
|
||||
containerClassName="w-full"
|
||||
/>
|
||||
</div>
|
||||
<Button
|
||||
type="button"
|
||||
variant="icon"
|
||||
StartIcon="x"
|
||||
color="minimal"
|
||||
className="mb-2"
|
||||
disabled={index === 0 && form.getValues("options").length === 1}
|
||||
onClick={() => {
|
||||
if (option.assignedUsers && option.assignedUsers > 0) {
|
||||
setDeleteOptionDialog({ id: index, open: true });
|
||||
} else {
|
||||
removeOption(index);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
<Input {...form.register(`options.${index}.id`)} className="hidden" />
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
const GroupOptions = ({
|
||||
fields,
|
||||
watchedOptions,
|
||||
form,
|
||||
removeOption,
|
||||
setDeleteOptionDialog,
|
||||
}: {
|
||||
fields: FieldArrayWithId<AttributeFormValues, "options", "id">[];
|
||||
watchedOptions: AttributeOption[];
|
||||
form: UseFormReturn<AttributeFormValues>;
|
||||
removeOption: (index: number) => void;
|
||||
setDeleteOptionDialog: (value: { id: number; open: boolean }) => void;
|
||||
}) => {
|
||||
const { t } = useLocale();
|
||||
return (
|
||||
<>
|
||||
<Label className="flex items-center">
|
||||
{t("group_options")}
|
||||
<InfoBadge content={t("group_options_description")} />
|
||||
</Label>
|
||||
<div>
|
||||
{fields.map((option, index) => {
|
||||
const isAGroupOption = option.isGroup;
|
||||
if (!isAGroupOption) return null;
|
||||
return (
|
||||
<GroupOption
|
||||
key={option.id}
|
||||
option={watchedOptions[index]}
|
||||
index={index}
|
||||
form={form}
|
||||
removeOption={removeOption}
|
||||
setDeleteOptionDialog={setDeleteOptionDialog}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export function AttributeForm({ initialValues, onSubmit, header }: AttributeFormProps) {
|
||||
const { t } = useLocale();
|
||||
const [deleteOptionDialog, setDeleteOptionDialog] = useState<{
|
||||
id: number | undefined;
|
||||
open: boolean;
|
||||
}>({
|
||||
id: undefined,
|
||||
open: false,
|
||||
});
|
||||
|
||||
// Needed because fields returned by useFieldArray have their own id field overriding the id field of the option object.
|
||||
const initialValuesEnsuringThatOptionIdIsNotInId = initialValues
|
||||
? {
|
||||
...initialValues,
|
||||
options: initialValues.options.map((option) => ({
|
||||
...option,
|
||||
// Set attributeOptionId equal to id field because 'id' property is used by useFieldArray
|
||||
attributeOptionId: option.id,
|
||||
// Also, set id to undefined to make it clear that this id is not used by us.
|
||||
id: undefined,
|
||||
})),
|
||||
}
|
||||
: undefined;
|
||||
|
||||
const form = useForm<AttributeFormValues>({
|
||||
resolver: zodResolver(attributeFormSchema),
|
||||
defaultValues: initialValuesEnsuringThatOptionIdIsNotInId || {
|
||||
attrName: "",
|
||||
options: [{ value: "", isGroup: false }],
|
||||
type: "TEXT",
|
||||
},
|
||||
});
|
||||
|
||||
const { fields, append, remove } = useFieldArray({
|
||||
control: form.control,
|
||||
name: "options",
|
||||
});
|
||||
|
||||
const removeOption = (index: number) => {
|
||||
// Update contains array of any group that has this option
|
||||
const optionToRemove = watchedOptions[index];
|
||||
if (!optionToRemove.isGroup && optionToRemove.attributeOptionId) {
|
||||
const updatedOptions = getUpdatedOptionsAfterRemovingNonGroupOption({
|
||||
optionToRemove,
|
||||
watchedOptions,
|
||||
});
|
||||
form.setValue("options", updatedOptions);
|
||||
}
|
||||
remove(index);
|
||||
};
|
||||
|
||||
const getUpdatedOptionsAfterRemovingNonGroupOption = ({
|
||||
optionToRemove,
|
||||
watchedOptions,
|
||||
}: {
|
||||
optionToRemove: AttributeOption;
|
||||
watchedOptions: AttributeOption[];
|
||||
}) => {
|
||||
const attributeOptionIdToRemove = optionToRemove.attributeOptionId;
|
||||
if (!attributeOptionIdToRemove) return watchedOptions;
|
||||
return watchedOptions.map((option) => {
|
||||
if (option.isGroup && option.contains) {
|
||||
return {
|
||||
...option,
|
||||
contains: option.contains.filter((id) => id !== attributeOptionIdToRemove),
|
||||
};
|
||||
}
|
||||
return option;
|
||||
});
|
||||
};
|
||||
|
||||
const watchedOptions = form.watch("options") as AttributeOption[];
|
||||
const watchedType = form.watch("type");
|
||||
return (
|
||||
<Form
|
||||
form={form}
|
||||
className="flex flex-col stack-y-4 lg:stack-y-6"
|
||||
handleSubmit={(values) => {
|
||||
onSubmit({
|
||||
...values,
|
||||
options: values.options.map(({ attributeOptionId, ...option }) => ({
|
||||
...option,
|
||||
// Set back attributeOptionId in id field
|
||||
id: attributeOptionId,
|
||||
})),
|
||||
});
|
||||
}}>
|
||||
{header}
|
||||
<Controller
|
||||
name="isLocked"
|
||||
render={({ field: { value, onChange } }) => {
|
||||
return (
|
||||
<SettingsToggle
|
||||
title={t("lock_attribute_for_assignment")}
|
||||
description={t("lock_attribute_for_assignment_description")}
|
||||
checked={value}
|
||||
onCheckedChange={(checked) => {
|
||||
onChange(checked);
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}}
|
||||
/>
|
||||
{["SINGLE_SELECT", "MULTI_SELECT"].includes(watchedType) && (
|
||||
<Controller
|
||||
name="isWeightsEnabled"
|
||||
render={({ field: { value, onChange } }) => {
|
||||
return (
|
||||
<SettingsToggle
|
||||
title={t("attribute_weight_enabled")}
|
||||
description={t("attribute_weight_enabled_description")}
|
||||
checked={value}
|
||||
onCheckedChange={(checked) => {
|
||||
onChange(checked);
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
<InputField label={t("name")} required {...form.register("attrName")} />
|
||||
<Controller
|
||||
name="type"
|
||||
render={({ field: { value, onChange } }) => (
|
||||
<SelectField
|
||||
label="Type"
|
||||
options={AttributeTypeOptions}
|
||||
onChange={(option) => {
|
||||
if (!option) return;
|
||||
onChange(option.value);
|
||||
}}
|
||||
value={AttributeTypeOptions.find((attr) => attr.value === value)}
|
||||
required
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
{["SINGLE_SELECT", "MULTI_SELECT"].includes(watchedType) && (
|
||||
<div className="bg-cal-muted border-muted mt-6 rounded-lg border p-6">
|
||||
<div className="flex flex-col gap-2">
|
||||
<div>
|
||||
<Label>{t("options")}</Label>
|
||||
<div>
|
||||
{fields.map((option, index) => {
|
||||
const isAGroupOption = option.isGroup;
|
||||
if (isAGroupOption) return null;
|
||||
return (
|
||||
<NonGroupOption
|
||||
key={option.id}
|
||||
option={watchedOptions[index]}
|
||||
index={index}
|
||||
form={form}
|
||||
removeOption={removeOption}
|
||||
setDeleteOptionDialog={setDeleteOptionDialog}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
<Button type="button" StartIcon="plus" color="secondary" onClick={() => append({ value: "" })}>
|
||||
{t("new_option")}
|
||||
</Button>
|
||||
</div>
|
||||
<div className="mt-6">
|
||||
<GroupOptions
|
||||
fields={fields}
|
||||
watchedOptions={watchedOptions}
|
||||
form={form}
|
||||
removeOption={removeOption}
|
||||
setDeleteOptionDialog={setDeleteOptionDialog}
|
||||
/>
|
||||
<Button
|
||||
type="button"
|
||||
StartIcon="plus"
|
||||
color="secondary"
|
||||
onClick={() => append({ value: "", isGroup: true })}>
|
||||
{t("new_group_option")}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
<Dialog
|
||||
open={deleteOptionDialog.open}
|
||||
onOpenChange={() => setDeleteOptionDialog({ id: undefined, open: false })}>
|
||||
<ConfirmationDialogContent
|
||||
title={t("delete_attribute")}
|
||||
confirmBtnText={t("delete")}
|
||||
onConfirm={() => {
|
||||
removeOption(deleteOptionDialog.id as number);
|
||||
setDeleteOptionDialog({ id: undefined, open: false });
|
||||
}}
|
||||
loadingText={t("deleting_attribute")}>
|
||||
<>
|
||||
{t("delete_attribute_description", {
|
||||
numberOfUsers: watchedOptions[deleteOptionDialog.id as number]?.assignedUsers || 0,
|
||||
})}
|
||||
</>
|
||||
</ConfirmationDialogContent>
|
||||
</Dialog>
|
||||
</Form>
|
||||
);
|
||||
}
|
||||
@@ -1,51 +0,0 @@
|
||||
import type { Dispatch, SetStateAction } from "react";
|
||||
|
||||
import { Dialog } from "@calcom/features/components/controlled-dialog";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import type { RouterOutputs } from "@calcom/trpc/react";
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
import { ConfirmationDialogContent } from "@calcom/ui/components/dialog";
|
||||
import { showToast } from "@calcom/ui/components/toast";
|
||||
import { revalidateAttributesList } from "@calcom/web/app/(use-page-wrapper)/settings/organizations/(org-user-only)/members/actions";
|
||||
|
||||
type AttributeItemProps = RouterOutputs["viewer"]["attributes"]["list"][number];
|
||||
|
||||
export function DeleteAttributeModal({
|
||||
attributeToDelete,
|
||||
setAttributeToDelete,
|
||||
}: {
|
||||
attributeToDelete: AttributeItemProps;
|
||||
setAttributeToDelete: Dispatch<SetStateAction<AttributeItemProps | undefined>>;
|
||||
}) {
|
||||
const { t } = useLocale();
|
||||
const utils = trpc.useUtils();
|
||||
|
||||
const deleteMutation = trpc.viewer.attributes.delete.useMutation({
|
||||
onSuccess: () => {
|
||||
showToast(t("attribute_deleted_successfully"), "success");
|
||||
utils.viewer.attributes.list.invalidate();
|
||||
revalidateAttributesList();
|
||||
},
|
||||
onError: (err) => {
|
||||
showToast(err.message, "error");
|
||||
},
|
||||
});
|
||||
|
||||
return (
|
||||
<Dialog open={true} onOpenChange={() => setAttributeToDelete(undefined)}>
|
||||
<ConfirmationDialogContent
|
||||
variety="danger"
|
||||
title={t("remove_attribute")}
|
||||
confirmBtnText={t("confirm_remove_attribute")}
|
||||
onConfirm={() => {
|
||||
deleteMutation.mutate({
|
||||
id: attributeToDelete.id,
|
||||
});
|
||||
}}>
|
||||
{t("remove_attribute_confirmation_message", {
|
||||
name: attributeToDelete.name,
|
||||
})}
|
||||
</ConfirmationDialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -1,22 +0,0 @@
|
||||
import { SkeletonText } from "@calcom/ui/components/skeleton";
|
||||
|
||||
export function ListSkeleton() {
|
||||
return (
|
||||
<ul className="focus-within:border-emphasis flex justify-between p-4">
|
||||
{Array.from({ length: 3 }).map((_, idx) => (
|
||||
<li key={idx}>
|
||||
<AttributeSkeleton />
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
);
|
||||
}
|
||||
|
||||
function AttributeSkeleton() {
|
||||
return (
|
||||
<div>
|
||||
<SkeletonText className="text-sm font-semibold leading-none" />
|
||||
<SkeletonText className="text-default inline-flex items-center gap-1 text-sm font-normal leading-none" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
-78
@@ -1,78 +0,0 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
|
||||
import "../../../../../../../ui/components/test-setup";
|
||||
import { getGroupOptionUpdate } from "../AttributesForm";
|
||||
|
||||
describe("getGroupOptionUpdate", () => {
|
||||
it("should add non-group option to new group's contains array", () => {
|
||||
const result = getGroupOptionUpdate({
|
||||
newGroupOptions: [{ label: "Group 1", value: "group1" }],
|
||||
previousGroupOptions: [],
|
||||
subOption: { attributeOptionId: "option1" },
|
||||
allOptions: [{ attributeOptionId: "group1", contains: [] }],
|
||||
});
|
||||
|
||||
expect(result).toEqual({
|
||||
0: ["option1"],
|
||||
});
|
||||
});
|
||||
|
||||
it("should remove non-group option from removed group's contains array", () => {
|
||||
const result = getGroupOptionUpdate({
|
||||
newGroupOptions: [],
|
||||
previousGroupOptions: [{ label: "Group 1", value: "group1" }],
|
||||
subOption: { attributeOptionId: "option1" },
|
||||
allOptions: [{ attributeOptionId: "group1", contains: ["option1", "option2"] }],
|
||||
});
|
||||
|
||||
expect(result).toEqual({
|
||||
0: ["option2"],
|
||||
});
|
||||
});
|
||||
|
||||
it("should handle multiple group updates simultaneously", () => {
|
||||
const result = getGroupOptionUpdate({
|
||||
newGroupOptions: [
|
||||
{ label: "Group 1", value: "group1" },
|
||||
{ label: "Group 2", value: "group2" },
|
||||
],
|
||||
previousGroupOptions: [{ label: "Group 3", value: "group3" }],
|
||||
subOption: { attributeOptionId: "option1" },
|
||||
allOptions: [
|
||||
{ attributeOptionId: "group1", contains: ["option2"] },
|
||||
{ attributeOptionId: "group2", contains: [] },
|
||||
{ attributeOptionId: "group3", contains: ["option1", "option3"] },
|
||||
],
|
||||
});
|
||||
|
||||
expect(result).toEqual({
|
||||
0: ["option2", "option1"],
|
||||
1: ["option1"],
|
||||
2: ["option3"],
|
||||
});
|
||||
});
|
||||
|
||||
it("should prevent duplicate entries in contains array", () => {
|
||||
const result = getGroupOptionUpdate({
|
||||
newGroupOptions: [{ label: "Group 1", value: "group1" }],
|
||||
previousGroupOptions: [],
|
||||
subOption: { attributeOptionId: "option1" },
|
||||
allOptions: [{ attributeOptionId: "group1", contains: ["option1"] }],
|
||||
});
|
||||
|
||||
expect(result).toEqual({
|
||||
0: ["option1"], // Should not have duplicate "option1"
|
||||
});
|
||||
});
|
||||
|
||||
it("should not consider a group option with undefined value", () => {
|
||||
const result = getGroupOptionUpdate({
|
||||
newGroupOptions: [{ label: "Group 1", value: undefined }],
|
||||
previousGroupOptions: [],
|
||||
subOption: { attributeOptionId: "option1" },
|
||||
allOptions: [{ attributeOptionId: "1", contains: ["option1"] }],
|
||||
});
|
||||
|
||||
expect(result).toEqual({});
|
||||
});
|
||||
});
|
||||
-202
@@ -1,202 +0,0 @@
|
||||
import { render, screen, waitFor } from "@testing-library/react";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
import * as Tooltip from "@radix-ui/react-tooltip";
|
||||
import React from "react";
|
||||
import type { Mock } from "vitest";
|
||||
import { vi } from "vitest";
|
||||
|
||||
import { Button } from "@calcom/ui/components/button";
|
||||
|
||||
import { AttributeForm } from "../AttributesForm";
|
||||
|
||||
vi.mock("@calcom/lib/hooks/useLocale", () => ({
|
||||
useLocale: vi.fn(() => ({
|
||||
t: (key: string) => key,
|
||||
})),
|
||||
}));
|
||||
|
||||
vi.mock("next/navigation", async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import("next/navigation")>();
|
||||
return {
|
||||
...actual,
|
||||
useRouter: vi.fn(() => ({
|
||||
push: vi.fn(() => {
|
||||
return;
|
||||
}),
|
||||
})),
|
||||
};
|
||||
});
|
||||
|
||||
type InitialOption = {
|
||||
id?: string;
|
||||
value: string;
|
||||
isGroup?: boolean;
|
||||
contains?: string[];
|
||||
attributeOptionId?: string;
|
||||
assignedUsers?: number;
|
||||
};
|
||||
|
||||
// Page Object Functions
|
||||
const AttributeFormActions = {
|
||||
setup: () => {
|
||||
const user = userEvent.setup();
|
||||
const mockOnSubmit = vi.fn();
|
||||
return { user, mockOnSubmit };
|
||||
},
|
||||
|
||||
render: (initialOptions: InitialOption[], mockOnSubmit: Mock) => {
|
||||
const wrapper = ({ children }: { children: React.ReactNode }) => (
|
||||
<Tooltip.Provider>{children}</Tooltip.Provider>
|
||||
);
|
||||
|
||||
return render(
|
||||
<AttributeForm
|
||||
onSubmit={mockOnSubmit}
|
||||
initialValues={{
|
||||
attrName: "Teams",
|
||||
type: "MULTI_SELECT",
|
||||
options: initialOptions,
|
||||
}}
|
||||
header={<Button type="submit">Save</Button>}
|
||||
/>,
|
||||
{ wrapper }
|
||||
);
|
||||
},
|
||||
|
||||
addOptionToGroup: async (user: ReturnType<typeof userEvent.setup>) => {
|
||||
const selects = await screen.findAllByText("choose_an_option");
|
||||
await user.click(selects[0]);
|
||||
},
|
||||
|
||||
selectOption: async (user: ReturnType<typeof userEvent.setup>, optionText: string) => {
|
||||
const option = await screen.findByText(optionText);
|
||||
await user.click(option);
|
||||
},
|
||||
|
||||
submitForm: async (user: ReturnType<typeof userEvent.setup>) => {
|
||||
const submitButton = screen.getByRole("button", { name: "Save" });
|
||||
await user.click(submitButton);
|
||||
},
|
||||
|
||||
deleteOption: async (user: ReturnType<typeof userEvent.setup>, index: number) => {
|
||||
const deleteButtons = screen.getAllByTitle("remove_option");
|
||||
await user.click(deleteButtons[index]);
|
||||
},
|
||||
|
||||
expectGroupContainsOptions: async (mockOnSubmit: Mock, groupValue: string, containsIds: string[]) => {
|
||||
await waitFor(() => {
|
||||
expect(mockOnSubmit).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
options: expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
value: groupValue,
|
||||
isGroup: true,
|
||||
contains: expect.arrayContaining(containsIds),
|
||||
}),
|
||||
]),
|
||||
})
|
||||
);
|
||||
});
|
||||
},
|
||||
|
||||
expectGroupNotContainsOptions: async (mockOnSubmit: Mock, groupValue: string, notContainsIds: string[]) => {
|
||||
await waitFor(() => {
|
||||
expect(mockOnSubmit).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
options: expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
value: groupValue,
|
||||
isGroup: true,
|
||||
contains: expect.not.arrayContaining(notContainsIds),
|
||||
}),
|
||||
]),
|
||||
})
|
||||
);
|
||||
});
|
||||
},
|
||||
|
||||
expectDeleteConfirmationDialog: () => {
|
||||
expect(screen.getByText("delete_attribute")).toBeInTheDocument();
|
||||
expect(screen.getByText("delete_attribute_description")).toBeInTheDocument();
|
||||
},
|
||||
|
||||
expectOptionToBeDeleted: async (mockOnSubmit: Mock, optionValue: string) => {
|
||||
await waitFor(() => {
|
||||
expect(mockOnSubmit).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
options: expect.not.arrayContaining([
|
||||
expect.objectContaining({
|
||||
value: optionValue,
|
||||
}),
|
||||
]),
|
||||
})
|
||||
);
|
||||
});
|
||||
},
|
||||
};
|
||||
|
||||
const initialOptionsWithAGroupHavingOptions: InitialOption[] = [
|
||||
{ id: "1", value: "Engineering", isGroup: false, attributeOptionId: "1" },
|
||||
{ id: "2", value: "Design", isGroup: false, attributeOptionId: "2" },
|
||||
{ id: "3", value: "Product", isGroup: false, attributeOptionId: "3" },
|
||||
{
|
||||
id: "4",
|
||||
value: "Tech Teams",
|
||||
isGroup: true,
|
||||
contains: ["1", "3"],
|
||||
attributeOptionId: "4",
|
||||
},
|
||||
];
|
||||
|
||||
const initialOptionsWithAGroupHavingNoOptions: InitialOption[] = [
|
||||
{ id: "1", value: "Engineering", isGroup: false, attributeOptionId: "1" },
|
||||
{ id: "2", value: "Design", isGroup: false, attributeOptionId: "2" },
|
||||
{ id: "3", value: "Product", isGroup: false, attributeOptionId: "3" },
|
||||
{
|
||||
id: "4",
|
||||
value: "Tech Teams",
|
||||
isGroup: true,
|
||||
contains: [],
|
||||
attributeOptionId: "4",
|
||||
},
|
||||
];
|
||||
|
||||
describe("AttributeForm", () => {
|
||||
describe("Group Options Handling", () => {
|
||||
it("should handle adding non-group options to existing group", async () => {
|
||||
const { user, mockOnSubmit } = AttributeFormActions.setup();
|
||||
AttributeFormActions.render(initialOptionsWithAGroupHavingNoOptions, mockOnSubmit);
|
||||
|
||||
await AttributeFormActions.addOptionToGroup(user);
|
||||
await AttributeFormActions.selectOption(user, "Design");
|
||||
await AttributeFormActions.submitForm(user);
|
||||
|
||||
await AttributeFormActions.expectGroupContainsOptions(mockOnSubmit, "Tech Teams", ["2"]);
|
||||
});
|
||||
|
||||
it("should handle removing options from group when the option is deleted", async () => {
|
||||
const { user, mockOnSubmit } = AttributeFormActions.setup();
|
||||
AttributeFormActions.render(initialOptionsWithAGroupHavingOptions, mockOnSubmit);
|
||||
|
||||
await AttributeFormActions.deleteOption(user, 0);
|
||||
await AttributeFormActions.submitForm(user);
|
||||
await AttributeFormActions.expectGroupNotContainsOptions(mockOnSubmit, "Tech Teams", ["1"]);
|
||||
await AttributeFormActions.expectOptionToBeDeleted(mockOnSubmit, "Engineering");
|
||||
});
|
||||
|
||||
it("should take confirmation before deleting option with assigned users", async () => {
|
||||
const { user, mockOnSubmit } = AttributeFormActions.setup();
|
||||
const optionsWithAssignedUsers = initialOptionsWithAGroupHavingOptions.map((opt) =>
|
||||
opt.value === "Engineering" ? { ...opt, assignedUsers: 5 } : opt
|
||||
);
|
||||
|
||||
AttributeFormActions.render(optionsWithAssignedUsers, mockOnSubmit);
|
||||
await AttributeFormActions.deleteOption(user, 0);
|
||||
AttributeFormActions.expectDeleteConfirmationDialog();
|
||||
const confirmationButton = screen.getByTestId("dialog-confirmation");
|
||||
await user.click(confirmationButton);
|
||||
await AttributeFormActions.submitForm(user);
|
||||
await AttributeFormActions.expectGroupNotContainsOptions(mockOnSubmit, "Tech Teams", ["1"]);
|
||||
});
|
||||
});
|
||||
});
|
||||
-90
@@ -1,90 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useFormContext } from "react-hook-form";
|
||||
import { z } from "zod";
|
||||
|
||||
import LicenseRequired from "@calcom/features/ee/common/components/LicenseRequired";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
import { Button } from "@calcom/ui/components/button";
|
||||
import { showToast } from "@calcom/ui/components/toast";
|
||||
import { revalidateAttributesList } from "@calcom/web/app/(use-page-wrapper)/settings/organizations/(org-user-only)/members/actions";
|
||||
|
||||
import { AttributeForm } from "./AttributesForm";
|
||||
|
||||
const CreateAttributeSchema = z.object({
|
||||
// Calling this name would make sense but conflicts with rhf "watch" "name" field
|
||||
attrName: z.string().min(1),
|
||||
type: z.enum(["TEXT", "NUMBER", "SINGLE_SELECT", "MULTI_SELECT"]),
|
||||
options: z.array(z.object({ value: z.string(), id: z.string() })),
|
||||
});
|
||||
|
||||
type FormValues = z.infer<typeof CreateAttributeSchema>;
|
||||
|
||||
function CreateAttributesPage() {
|
||||
const router = useRouter();
|
||||
const mutation = trpc.viewer.attributes.create.useMutation({
|
||||
onSuccess: () => {
|
||||
showToast("Attribute created successfully", "success");
|
||||
revalidateAttributesList();
|
||||
router.push("/settings/organizations/attributes");
|
||||
},
|
||||
onError: (err) => {
|
||||
showToast(err.message, "error");
|
||||
},
|
||||
});
|
||||
|
||||
return (
|
||||
<>
|
||||
<LicenseRequired>
|
||||
<AttributeForm
|
||||
header={<CreateAttributeHeader isPending={mutation.isPending} />}
|
||||
onSubmit={(values) => {
|
||||
const { attrName, ...rest } = values;
|
||||
mutation.mutate({
|
||||
...rest,
|
||||
name: attrName,
|
||||
});
|
||||
}}
|
||||
/>
|
||||
</LicenseRequired>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function CreateAttributeHeader(props: { isPending: boolean }) {
|
||||
const { t } = useLocale();
|
||||
const formContext = useFormContext<FormValues>();
|
||||
|
||||
const watchedTitle = formContext.watch("attrName");
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="mb-6 mt-6 flex grow items-center justify-between lg:mt-12">
|
||||
<div className="-ml-12 flex items-center gap-4">
|
||||
<Button
|
||||
variant="icon"
|
||||
StartIcon="arrow-left"
|
||||
color="minimal"
|
||||
href="/settings/organizations/attributes">
|
||||
<span className="sr-only">{t("back_to_attributes")}</span>
|
||||
</Button>
|
||||
<div className="font-cal text-cal flex space-x-1 text-xl font-semibold leading-none">
|
||||
<h1 className="text-emphasis">{t("attribute")}</h1>
|
||||
{watchedTitle && (
|
||||
<>
|
||||
<span className="text-subtle">/</span> <span className="text-emphasis">{watchedTitle}</span>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<Button type="submit" data-testid="create-attribute-button" loading={props.isPending}>
|
||||
{t("save")}
|
||||
</Button>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export default CreateAttributesPage;
|
||||
-112
@@ -1,112 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { useParams } from "next/navigation";
|
||||
import { useFormContext } from "react-hook-form";
|
||||
import { z } from "zod";
|
||||
|
||||
import LicenseRequired from "@calcom/features/ee/common/components/LicenseRequired";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
import { Button } from "@calcom/ui/components/button";
|
||||
import { showToast } from "@calcom/ui/components/toast";
|
||||
import { revalidateAttributesList } from "@calcom/web/app/(use-page-wrapper)/settings/organizations/(org-user-only)/members/actions";
|
||||
|
||||
import { AttributeForm } from "./AttributesForm";
|
||||
|
||||
const CreateAttributeSchema = z.object({
|
||||
// Calling this name would make sense but conflicts with rhf "watch" "name" field
|
||||
attrName: z.string().min(1),
|
||||
type: z.enum(["TEXT", "NUMBER", "SINGLE_SELECT", "MULTI_SELECT"]),
|
||||
options: z.array(z.object({ value: z.string(), id: z.string() })),
|
||||
});
|
||||
|
||||
type FormValues = z.infer<typeof CreateAttributeSchema>;
|
||||
|
||||
function CreateAttributesPage() {
|
||||
const utils = trpc.useUtils();
|
||||
const { t } = useLocale();
|
||||
// Get the attribute id from the url
|
||||
const params = useParams<{ id: string }>();
|
||||
const id = params?.id || "";
|
||||
// ensure string with zod
|
||||
const attribute = trpc.viewer.attributes.get.useQuery({ id });
|
||||
|
||||
const mutation = trpc.viewer.attributes.edit.useMutation({
|
||||
onSuccess: () => {
|
||||
showToast(t("attribute_edited_successfully"), "success");
|
||||
utils.viewer.attributes.get.invalidate({
|
||||
id,
|
||||
});
|
||||
utils.viewer.attributes.list.invalidate();
|
||||
revalidateAttributesList();
|
||||
},
|
||||
onError: (err) => {
|
||||
showToast(err.message, "error");
|
||||
},
|
||||
});
|
||||
|
||||
return (
|
||||
<>
|
||||
<LicenseRequired>
|
||||
{!attribute.isLoading && attribute.data ? (
|
||||
<AttributeForm
|
||||
initialValues={{
|
||||
attrName: attribute.data.name,
|
||||
type: attribute.data.type,
|
||||
options: attribute.data.options,
|
||||
isLocked: attribute.data.isLocked,
|
||||
isWeightsEnabled: attribute.data.isWeightsEnabled,
|
||||
}}
|
||||
header={<EditAttributeHeader isPending={mutation.isPending} />}
|
||||
onSubmit={(values) => {
|
||||
const { attrName, ...rest } = values;
|
||||
mutation.mutate({
|
||||
...rest,
|
||||
name: attrName,
|
||||
attributeId: id,
|
||||
});
|
||||
}}
|
||||
/>
|
||||
) : (
|
||||
<>Loading</>
|
||||
)}
|
||||
</LicenseRequired>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function EditAttributeHeader(props: { isPending: boolean }) {
|
||||
const { t } = useLocale();
|
||||
const formContext = useFormContext<FormValues>();
|
||||
|
||||
const watchedTitle = formContext.watch("attrName");
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="mb-6 mt-6 flex grow items-center justify-between lg:mt-12">
|
||||
<div className="-ml-12 flex items-center gap-4">
|
||||
<Button
|
||||
variant="icon"
|
||||
StartIcon="arrow-left"
|
||||
color="minimal"
|
||||
href="/settings/organizations/attributes">
|
||||
<span className="sr-only">{t("back_to_attributes")}</span>
|
||||
</Button>
|
||||
<div className="font-cal text-cal flex space-x-1 text-xl font-semibold leading-none">
|
||||
<h1 className="text-emphasis">{t("attribute")}</h1>
|
||||
{watchedTitle && (
|
||||
<>
|
||||
<span className="text-subtle">/</span> <span className="text-emphasis">{watchedTitle}</span>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<Button type="submit" data-testid="create-attribute-button" loading={props.isPending}>
|
||||
{t("save")}
|
||||
</Button>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export default CreateAttributesPage;
|
||||
-213
@@ -1,213 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import type { Dispatch, SetStateAction } from "react";
|
||||
import { useState } from "react";
|
||||
|
||||
import LicenseRequired from "@calcom/features/ee/common/components/LicenseRequired";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import type { RouterOutputs } from "@calcom/trpc/react";
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
import { Badge } from "@calcom/ui/components/badge";
|
||||
import { Button } from "@calcom/ui/components/button";
|
||||
import {
|
||||
Dropdown,
|
||||
DropdownMenuTrigger,
|
||||
DropdownMenuContent,
|
||||
DropdownItem,
|
||||
DropdownMenuItem,
|
||||
} from "@calcom/ui/components/dropdown";
|
||||
import { Switch } from "@calcom/ui/components/form";
|
||||
import { Icon } from "@calcom/ui/components/icon";
|
||||
import { showToast } from "@calcom/ui/components/toast";
|
||||
import { revalidateAttributesList } from "@calcom/web/app/(use-page-wrapper)/settings/organizations/(org-user-only)/members/actions";
|
||||
|
||||
import { DeleteAttributeModal } from "./DeleteAttributeModal";
|
||||
import { ListSkeleton } from "./ListSkeleton";
|
||||
|
||||
type AttributeItemProps = RouterOutputs["viewer"]["attributes"]["list"][number];
|
||||
|
||||
const TypeToLabelMap = {
|
||||
TEXT: "Text",
|
||||
NUMBER: "Number",
|
||||
SINGLE_SELECT: "Single-select",
|
||||
MULTI_SELECT: "Multi-select",
|
||||
};
|
||||
|
||||
function AttributeItem({
|
||||
attribute,
|
||||
setAttributeToDelete,
|
||||
permissions,
|
||||
}: {
|
||||
attribute: AttributeItemProps;
|
||||
setAttributeToDelete: Dispatch<SetStateAction<AttributeItemProps | undefined>>;
|
||||
permissions: { canEdit: boolean; canDelete: boolean };
|
||||
}) {
|
||||
const { t } = useLocale();
|
||||
const [isEnabled, setIsEnabled] = useState(attribute.enabled);
|
||||
const mutation = trpc.viewer.attributes.toggleActive.useMutation({
|
||||
onSuccess: () => {
|
||||
showToast(t("attribute_updated_successfully"), "success");
|
||||
revalidateAttributesList();
|
||||
},
|
||||
onError: (err) => {
|
||||
showToast(err.message, "error");
|
||||
},
|
||||
});
|
||||
|
||||
const handleToggle = (checked: boolean) => {
|
||||
// Optimistically update the local state
|
||||
setIsEnabled(checked);
|
||||
mutation.mutate(
|
||||
{ attributeId: attribute.id },
|
||||
{
|
||||
onError: (err) => {
|
||||
setIsEnabled(!checked);
|
||||
showToast(err.message, "error");
|
||||
},
|
||||
}
|
||||
);
|
||||
};
|
||||
|
||||
return (
|
||||
<ul className="focus-within:border-emphasis flex justify-between p-4" key={attribute.id}>
|
||||
<div>
|
||||
<h3 className="text-sm font-semibold leading-none">{attribute.name}</h3>
|
||||
<p className="text-default inline-flex items-center gap-1 text-sm font-normal leading-none">
|
||||
{TypeToLabelMap[attribute.type]}
|
||||
{attribute.options?.length > 0 && (
|
||||
<>
|
||||
<span className="text-muted">•</span>
|
||||
<span>{t("number_of_options", { count: attribute.options.length })}</span>
|
||||
</>
|
||||
)}
|
||||
{attribute.isWeightsEnabled && (
|
||||
<>
|
||||
<span className="text-muted">•</span>
|
||||
<Badge>{t("attribute_weight_enabled")}</Badge>
|
||||
</>
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex gap-4">
|
||||
{permissions.canEdit && <Switch checked={isEnabled} onCheckedChange={handleToggle} />}
|
||||
{(permissions.canEdit || permissions.canDelete) && (
|
||||
<Dropdown modal={false}>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button
|
||||
type="button"
|
||||
variant="icon"
|
||||
color="secondary"
|
||||
StartIcon="ellipsis"
|
||||
className="ltr:radix-state-open:rounded-r-md rtl:radix-state-open:rounded-l-md"
|
||||
/>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent className="min-w-[200px]">
|
||||
{permissions.canEdit && (
|
||||
<DropdownMenuItem>
|
||||
<DropdownItem
|
||||
type="button"
|
||||
StartIcon="pencil"
|
||||
href={`/settings/organizations/attributes/${attribute.id}/edit`}>
|
||||
{t("edit")}
|
||||
</DropdownItem>
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
{permissions.canDelete && (
|
||||
<DropdownMenuItem>
|
||||
<DropdownItem
|
||||
type="button"
|
||||
StartIcon="trash-2"
|
||||
color="destructive"
|
||||
className="rounded-t-none"
|
||||
onClick={() => setAttributeToDelete(attribute)}>
|
||||
{t("delete")}
|
||||
</DropdownItem>
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
</DropdownMenuContent>
|
||||
</Dropdown>
|
||||
)}
|
||||
</div>
|
||||
</ul>
|
||||
);
|
||||
}
|
||||
|
||||
function OrganizationAttributesPage({
|
||||
permissions,
|
||||
}: {
|
||||
permissions: { canEdit: boolean; canDelete: boolean; canCreate: boolean };
|
||||
}) {
|
||||
const { t } = useLocale();
|
||||
const { data, isLoading } = trpc.viewer.attributes.list.useQuery();
|
||||
const [attributeToDelete, setAttributeToDelete] = useState<AttributeItemProps>();
|
||||
if (isLoading) {
|
||||
return (
|
||||
<>
|
||||
<div className="border-subtle bg-default flex flex-col gap-4 rounded-lg border p-6">
|
||||
<ListSkeleton />
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<LicenseRequired>
|
||||
<div className="border-subtle bg-default flex flex-col gap-4 rounded-lg border p-6">
|
||||
{data && data?.length > 0 ? (
|
||||
<>
|
||||
<h2 className="text-emphasis text-base font-semibold leading-none">{t("custom")}</h2>
|
||||
<li className="border-subtle bg-default divide-subtle flex flex-col divide-y rounded-lg border">
|
||||
{data?.map((attribute) => (
|
||||
<AttributeItem
|
||||
setAttributeToDelete={setAttributeToDelete}
|
||||
attribute={attribute}
|
||||
permissions={{ canEdit: permissions.canEdit, canDelete: permissions.canDelete }}
|
||||
key={attribute.id}
|
||||
/>
|
||||
))}
|
||||
</li>
|
||||
{permissions.canCreate && (
|
||||
<Button
|
||||
className="w-fit"
|
||||
StartIcon="plus"
|
||||
color="minimal"
|
||||
href="/settings/organizations/attributes/create">
|
||||
{t("add")}
|
||||
</Button>
|
||||
)}
|
||||
</>
|
||||
) : (
|
||||
<div className="flex w-full flex-col items-center justify-center p-14">
|
||||
<div className="bg-emphasis text-emphasis flex h-16 w-16 items-center justify-center rounded-full p-2">
|
||||
<Icon name="tags" />
|
||||
</div>
|
||||
<h2 className="font-cal text-emphasis mt-6 text-xl font-semibold leading-none">
|
||||
{t("add_attributes")}
|
||||
</h2>
|
||||
|
||||
<p className="text-emphasis mt-3 text-sm font-normal leading-none">
|
||||
{t("add_attributes_description")}
|
||||
</p>
|
||||
{permissions.canCreate && (
|
||||
<Button
|
||||
className="mt-8"
|
||||
StartIcon="plus"
|
||||
color="secondary"
|
||||
href="/settings/organizations/attributes/create">
|
||||
{t("new_attribute")}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
{attributeToDelete && (
|
||||
<DeleteAttributeModal
|
||||
attributeToDelete={attributeToDelete}
|
||||
setAttributeToDelete={setAttributeToDelete}
|
||||
/>
|
||||
)}
|
||||
</LicenseRequired>
|
||||
);
|
||||
}
|
||||
|
||||
export default OrganizationAttributesPage;
|
||||
@@ -1,541 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { useForm, Controller, useFormContext } from "react-hook-form";
|
||||
|
||||
import { Dialog } from "@calcom/features/components/controlled-dialog";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import type { ServiceAccountKey } from "@calcom/lib/server/serviceAccountKey";
|
||||
import { serviceAccountKeySchema } from "@calcom/prisma/zod-utils";
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
import { Badge } from "@calcom/ui/components/badge";
|
||||
import { InfoBadge } from "@calcom/ui/components/badge";
|
||||
import { Button } from "@calcom/ui/components/button";
|
||||
import { DialogContent, DialogFooter, ConfirmationDialogContent } from "@calcom/ui/components/dialog";
|
||||
import { EmptyScreen } from "@calcom/ui/components/empty-screen";
|
||||
import { Form } from "@calcom/ui/components/form";
|
||||
import { TextAreaField } from "@calcom/ui/components/form";
|
||||
import { TextField } from "@calcom/ui/components/form";
|
||||
import { SelectField } from "@calcom/ui/components/form";
|
||||
import { Switch } from "@calcom/ui/components/form";
|
||||
import { SkeletonContainer, SkeletonText } from "@calcom/ui/components/skeleton";
|
||||
import { DropdownActions } from "@calcom/ui/components/table";
|
||||
import { showToast } from "@calcom/ui/components/toast";
|
||||
|
||||
interface DelegationItemProps {
|
||||
delegation: {
|
||||
id: string;
|
||||
domain: string;
|
||||
enabled: boolean;
|
||||
serviceAccountClientId: string | null;
|
||||
workspacePlatform: {
|
||||
name: string;
|
||||
slug: string;
|
||||
};
|
||||
};
|
||||
toggleDelegation: (delegation: DelegationItemProps["delegation"]) => void;
|
||||
onEdit: (delegation: DelegationItemProps["delegation"]) => void;
|
||||
onDelete: (id: string) => void;
|
||||
}
|
||||
|
||||
type WorkspacePlatform = {
|
||||
id: number;
|
||||
name: string;
|
||||
slug: string;
|
||||
};
|
||||
|
||||
function getWorkspacePlatformOptions(workspacePlatforms: WorkspacePlatform[]) {
|
||||
return workspacePlatforms.map((platform) => ({
|
||||
value: platform.slug,
|
||||
label: platform.name,
|
||||
}));
|
||||
}
|
||||
|
||||
const SkeletonLoader = () => {
|
||||
return (
|
||||
<SkeletonContainer>
|
||||
<div className="divide-subtle border-subtle stack-y-6 rounded-b-lg border border-t-0 px-6 py-4">
|
||||
<SkeletonText className="h-8 w-full" />
|
||||
<SkeletonText className="h-8 w-full" />
|
||||
</div>
|
||||
</SkeletonContainer>
|
||||
);
|
||||
};
|
||||
|
||||
function DelegationListItemActions({
|
||||
delegation,
|
||||
toggleDelegation,
|
||||
onEdit,
|
||||
onDelete,
|
||||
}: {
|
||||
delegation: DelegationItemProps["delegation"];
|
||||
toggleDelegation: DelegationItemProps["toggleDelegation"];
|
||||
onEdit: (delegation: DelegationItemProps["delegation"]) => void;
|
||||
onDelete: (id: string) => void;
|
||||
}) {
|
||||
const { t } = useLocale();
|
||||
|
||||
return (
|
||||
<div className="flex items-center space-x-2">
|
||||
<Switch checked={delegation.enabled} onCheckedChange={() => toggleDelegation(delegation)} />
|
||||
<DropdownActions
|
||||
actions={[
|
||||
{
|
||||
id: "edit",
|
||||
label: t("edit"),
|
||||
onClick: () => onEdit(delegation),
|
||||
icon: "pencil",
|
||||
},
|
||||
{
|
||||
id: "delete",
|
||||
label: t("delete"),
|
||||
disabled: true,
|
||||
onClick: () => onDelete(delegation.id),
|
||||
icon: "trash",
|
||||
},
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function DelegationListItem({ delegation, toggleDelegation, onEdit, onDelete }: DelegationItemProps) {
|
||||
const { t } = useLocale();
|
||||
return (
|
||||
<li className="border-subtle bg-default divide-subtle flex flex-col divide-y border">
|
||||
<div className="flex items-center justify-between space-x-2 p-4">
|
||||
<div className="flex flex-col items-start">
|
||||
<div className="flex items-center space-x-2">
|
||||
<span>{delegation.serviceAccountClientId}</span>
|
||||
<InfoBadge content={t("add_client_id_in_google_workspace_with_below_scope")} />
|
||||
</div>
|
||||
<span className="text-muted mt-2">https://www.googleapis.com/auth/calendar</span>
|
||||
<div className="mt-2 flex items-center space-x-2">
|
||||
<Badge variant="default">{delegation.workspacePlatform.name}</Badge>
|
||||
<Badge variant="gray">{delegation.domain}</Badge>
|
||||
</div>
|
||||
</div>
|
||||
<DelegationListItemActions
|
||||
delegation={delegation}
|
||||
toggleDelegation={toggleDelegation}
|
||||
onEdit={onEdit}
|
||||
onDelete={onDelete}
|
||||
/>
|
||||
</div>
|
||||
</li>
|
||||
);
|
||||
}
|
||||
|
||||
type CreateDelegationData = {
|
||||
domain: string;
|
||||
workspacePlatformSlug: string;
|
||||
enabled: boolean;
|
||||
serviceAccountKey: ServiceAccountKey;
|
||||
};
|
||||
|
||||
type CreateDelegationFormData = Omit<CreateDelegationData, "serviceAccountKey"> & {
|
||||
serviceAccountKey: string;
|
||||
};
|
||||
|
||||
type EditDelegationData = {
|
||||
id: string;
|
||||
domain: string;
|
||||
workspacePlatformSlug: string;
|
||||
enabled: boolean;
|
||||
};
|
||||
|
||||
function CreateDelegationDialog({
|
||||
isOpen,
|
||||
onClose,
|
||||
workspacePlatforms,
|
||||
handleCreate,
|
||||
}: {
|
||||
isOpen: boolean;
|
||||
onClose: () => void;
|
||||
workspacePlatforms: WorkspacePlatform[];
|
||||
handleCreate: (data: CreateDelegationData) => void;
|
||||
}) {
|
||||
const { t } = useLocale();
|
||||
|
||||
const form = useForm<CreateDelegationFormData>();
|
||||
|
||||
const handleSubmit = (values: CreateDelegationFormData) => {
|
||||
try {
|
||||
const parsedKey = JSON.parse(values.serviceAccountKey);
|
||||
const validatedKey = serviceAccountKeySchema.safeParse(parsedKey);
|
||||
|
||||
if (!validatedKey.success) {
|
||||
form.setError("serviceAccountKey", { message: t("invalid_service_account_key") });
|
||||
return;
|
||||
}
|
||||
|
||||
handleCreate({
|
||||
...values,
|
||||
serviceAccountKey: validatedKey.data,
|
||||
});
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
form.setError("serviceAccountKey", { message: t("invalid_service_account_key") });
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open={isOpen} onOpenChange={onClose}>
|
||||
<DialogContent enableOverflow title={t("add_delegation_credential")}>
|
||||
<Form form={form} handleSubmit={handleSubmit}>
|
||||
<DelegationFormFields workspacePlatforms={workspacePlatforms} isCreate={true} />
|
||||
<DialogFooter>
|
||||
<Button type="button" color="secondary" onClick={onClose}>
|
||||
{t("cancel")}
|
||||
</Button>
|
||||
<Button type="submit">{t("create")}</Button>
|
||||
</DialogFooter>
|
||||
</Form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
function EditDelegationDialog({
|
||||
isOpen,
|
||||
onClose,
|
||||
delegation,
|
||||
workspacePlatforms,
|
||||
handleEdit,
|
||||
}: {
|
||||
isOpen: boolean;
|
||||
onClose: () => void;
|
||||
delegation: DelegationItemProps["delegation"];
|
||||
workspacePlatforms: WorkspacePlatform[];
|
||||
handleEdit: (data: EditDelegationData) => void;
|
||||
}) {
|
||||
const { t } = useLocale();
|
||||
|
||||
const form = useForm<EditDelegationData>({
|
||||
defaultValues: {
|
||||
id: delegation.id,
|
||||
domain: delegation.domain,
|
||||
workspacePlatformSlug: delegation.workspacePlatform.slug,
|
||||
},
|
||||
});
|
||||
|
||||
return (
|
||||
<Dialog open={isOpen} onOpenChange={onClose}>
|
||||
<DialogContent title={t("edit_delegation_credential")}>
|
||||
<Form form={form} handleSubmit={handleEdit}>
|
||||
<DelegationFormFields workspacePlatforms={workspacePlatforms} isCreate={false} />
|
||||
<DialogFooter>
|
||||
<Button type="button" color="secondary" onClick={onClose}>
|
||||
{t("cancel")}
|
||||
</Button>
|
||||
<Button type="submit">{t("update")}</Button>
|
||||
</DialogFooter>
|
||||
</Form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
function DelegationFormFields({
|
||||
workspacePlatforms,
|
||||
isCreate,
|
||||
}: {
|
||||
workspacePlatforms: WorkspacePlatform[];
|
||||
isCreate: boolean;
|
||||
}) {
|
||||
const { t } = useLocale();
|
||||
const form = useFormContext();
|
||||
return (
|
||||
<div className="stack-y-4">
|
||||
<TextField label={t("domain")} {...form.register("domain")} />
|
||||
<Controller
|
||||
name="workspacePlatformSlug"
|
||||
control={form.control}
|
||||
render={({ field: { value, onChange } }) => {
|
||||
const platformOptions = getWorkspacePlatformOptions(workspacePlatforms);
|
||||
const selectedPlatform = platformOptions.find((opt) => opt.value === value);
|
||||
return (
|
||||
<SelectField
|
||||
required
|
||||
label={t("workspace_platform")}
|
||||
onChange={(option) => onChange(option?.value)}
|
||||
value={selectedPlatform}
|
||||
options={platformOptions}
|
||||
/>
|
||||
);
|
||||
}}
|
||||
/>
|
||||
{isCreate && (
|
||||
<TextAreaField
|
||||
required
|
||||
label={t("service_account_key")}
|
||||
placeholder="{...}"
|
||||
{...form.register("serviceAccountKey")}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function DelegationCredentialList() {
|
||||
const { t } = useLocale();
|
||||
const utils = trpc.useContext();
|
||||
const { data: delegations, isLoading, error } = trpc.viewer.delegationCredential.list.useQuery();
|
||||
|
||||
const updateMutation = trpc.viewer.delegationCredential.update.useMutation({
|
||||
onSuccess: () => utils.viewer.delegationCredential.list.invalidate(),
|
||||
onError: (error) => {
|
||||
showToast(error.message, "error");
|
||||
},
|
||||
});
|
||||
|
||||
const toggleEnabledMutation = trpc.viewer.delegationCredential.toggleEnabled.useMutation({
|
||||
onSuccess: (data) => {
|
||||
if (data) {
|
||||
showToast(
|
||||
data.enabled ? t("delegation_credential_enabled") : t("delegation_credential_disabled"),
|
||||
"success"
|
||||
);
|
||||
utils.viewer.delegationCredential.list.invalidate();
|
||||
}
|
||||
},
|
||||
onError: (error) => {
|
||||
showToast(error.message, "error");
|
||||
},
|
||||
});
|
||||
|
||||
const createMutation = trpc.viewer.delegationCredential.add.useMutation({
|
||||
onSuccess: () => utils.viewer.delegationCredential.list.invalidate(),
|
||||
onError: (error) => {
|
||||
showToast(error.message, "error");
|
||||
},
|
||||
});
|
||||
|
||||
const deleteMutation = trpc.viewer.delegationCredential.delete.useMutation({
|
||||
onSuccess: () => utils.viewer.delegationCredential.list.invalidate(),
|
||||
onError: (error) => {
|
||||
showToast(error.message, "error");
|
||||
},
|
||||
});
|
||||
|
||||
const onDelete = (id: string) => {
|
||||
deleteMutation.mutate({ id });
|
||||
};
|
||||
|
||||
const [delegationToToggle, setDelegationToToggle] = useState<DelegationItemProps["delegation"] | null>(
|
||||
null
|
||||
);
|
||||
|
||||
const toggleDelegation = (delegation: DelegationItemProps["delegation"]) => {
|
||||
setDelegationToToggle(delegation);
|
||||
};
|
||||
|
||||
const handleToggleConfirm = () => {
|
||||
if (delegationToToggle) {
|
||||
toggleEnabledMutation.mutate({
|
||||
id: delegationToToggle.id,
|
||||
enabled: !delegationToToggle.enabled,
|
||||
});
|
||||
setDelegationToToggle(null);
|
||||
}
|
||||
};
|
||||
|
||||
const [createEditDialog, setCreateEditDialog] = useState<{
|
||||
isOpen: boolean;
|
||||
delegation: DelegationItemProps["delegation"] | null;
|
||||
}>({
|
||||
isOpen: false,
|
||||
delegation: null,
|
||||
});
|
||||
|
||||
const { data: workspacePlatforms, isLoading: isLoadingWorkspacePlatforms } =
|
||||
trpc.viewer.delegationCredential.listWorkspacePlatforms.useQuery();
|
||||
|
||||
const enabledWorkspacePlatforms = workspacePlatforms?.filter((platform) => platform.enabled) || [];
|
||||
|
||||
const onEditClick = (delegation: DelegationItemProps["delegation"]) => {
|
||||
setCreateEditDialog({ isOpen: true, delegation });
|
||||
};
|
||||
|
||||
const onCreateClick = () => setCreateEditDialog({ isOpen: true, delegation: null });
|
||||
|
||||
const handleCreate = (data: CreateDelegationData) => {
|
||||
createMutation.mutate({
|
||||
domain: data.domain,
|
||||
workspacePlatformSlug: data.workspacePlatformSlug,
|
||||
serviceAccountKey: data.serviceAccountKey,
|
||||
});
|
||||
setCreateEditDialog({ isOpen: false, delegation: null });
|
||||
};
|
||||
|
||||
const handleEdit = (data: EditDelegationData) => {
|
||||
if (!createEditDialog.delegation) {
|
||||
return;
|
||||
}
|
||||
updateMutation.mutate({
|
||||
id: createEditDialog.delegation.id,
|
||||
domain: data.domain,
|
||||
workspacePlatformSlug: data.workspacePlatformSlug,
|
||||
});
|
||||
setCreateEditDialog({ isOpen: false, delegation: null });
|
||||
};
|
||||
|
||||
const AddDwDButton = () => {
|
||||
return (
|
||||
<Button type="button" color="secondary" StartIcon="plus" className="mt-6" onClick={onCreateClick}>
|
||||
{t("add_delegation_credential")}
|
||||
</Button>
|
||||
);
|
||||
};
|
||||
|
||||
if (isLoading || isLoadingWorkspacePlatforms) {
|
||||
return <SkeletonLoader />;
|
||||
}
|
||||
|
||||
if (error) {
|
||||
return <div>{t(error.message)}</div>;
|
||||
}
|
||||
|
||||
if (!delegations || !workspacePlatforms) {
|
||||
return <div>{t("something_went_wrong")}</div>;
|
||||
}
|
||||
|
||||
return (
|
||||
<div>
|
||||
{!!delegations?.length ? (
|
||||
<>
|
||||
<ul className="stack-y-2 [&>*:last-child]:rounded-b-xl">
|
||||
{delegations.map(
|
||||
(delegation) =>
|
||||
delegation && (
|
||||
<DelegationListItem
|
||||
key={delegation.id}
|
||||
delegation={delegation}
|
||||
toggleDelegation={toggleDelegation}
|
||||
onEdit={onEditClick}
|
||||
onDelete={onDelete}
|
||||
/>
|
||||
)
|
||||
)}
|
||||
</ul>
|
||||
{/* Disable till we thoroughly test multiple delegation credentials support */}
|
||||
{/* <AddDwDButton /> */}
|
||||
</>
|
||||
) : (
|
||||
<EmptyScreen
|
||||
Icon="link"
|
||||
headline={t("add_delegation_credential")}
|
||||
description={t("delegation_credential_description")}
|
||||
className="rounded-b-lg rounded-t-none border-t-0"
|
||||
buttonRaw={<AddDwDButton />}
|
||||
/>
|
||||
)}
|
||||
|
||||
{createEditDialog.delegation ? (
|
||||
<EditDelegationDialog
|
||||
isOpen={createEditDialog.isOpen}
|
||||
onClose={() => setCreateEditDialog({ isOpen: false, delegation: null })}
|
||||
delegation={createEditDialog.delegation}
|
||||
workspacePlatforms={enabledWorkspacePlatforms}
|
||||
handleEdit={handleEdit}
|
||||
/>
|
||||
) : (
|
||||
<CreateDelegationDialog
|
||||
isOpen={createEditDialog.isOpen}
|
||||
onClose={() => setCreateEditDialog({ isOpen: false, delegation: null })}
|
||||
workspacePlatforms={enabledWorkspacePlatforms}
|
||||
handleCreate={handleCreate}
|
||||
/>
|
||||
)}
|
||||
|
||||
<ToggleDelegationDialog
|
||||
delegation={delegationToToggle}
|
||||
onClose={() => setDelegationToToggle(null)}
|
||||
onConfirm={handleToggleConfirm}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function MembersThatWillBeAffectedOnDisablingDelegationCredential({
|
||||
delegationCredentialId,
|
||||
}: {
|
||||
delegationCredentialId: string;
|
||||
}) {
|
||||
const { t } = useLocale();
|
||||
const { data: affectedMembers, isLoading: isLoadingAffectedMembers } =
|
||||
trpc.viewer.delegationCredential.getAffectedMembersForDisable.useQuery({ id: delegationCredentialId });
|
||||
|
||||
return (
|
||||
<div className="mt-4">
|
||||
<strong>{t("members_affected_by_disabling_delegation_credential")}</strong>
|
||||
{isLoadingAffectedMembers ? (
|
||||
<div>{t("loading")}</div>
|
||||
) : affectedMembers?.length ? (
|
||||
<>
|
||||
<ul className="stack-y-1 list-disc p-1 pl-5 sm:w-80">
|
||||
{affectedMembers.slice(0, 5).map((m) => (
|
||||
<li className="text-muted text-sm" key={m.email}>
|
||||
{m.name ? `${m.name} (${m.email})` : m.email}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
{affectedMembers.length > 5 && (
|
||||
<p className="mt-2 text-sm text-gray-500">
|
||||
{t("and_count_more", { count: affectedMembers.length - 5 })}
|
||||
</p>
|
||||
)}
|
||||
</>
|
||||
) : (
|
||||
<div className="mt-2">{t("no_members_affected_by_disabling_delegation_credential")}</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
const ToggleDelegationDialog = ({
|
||||
delegation,
|
||||
onConfirm,
|
||||
onClose,
|
||||
}: {
|
||||
delegation: DelegationItemProps["delegation"] | null;
|
||||
onConfirm: () => void;
|
||||
onClose: () => void;
|
||||
}) => {
|
||||
const { t } = useLocale();
|
||||
|
||||
if (!delegation) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const isDisablingDelegation = delegation.enabled;
|
||||
|
||||
return (
|
||||
<Dialog
|
||||
name="toggle-delegation"
|
||||
open={!!delegation}
|
||||
onOpenChange={(open) => (!open ? onClose() : undefined)}>
|
||||
<ConfirmationDialogContent
|
||||
title={t(isDisablingDelegation ? "disable_delegation_credential" : "enable_delegation_credential")}
|
||||
confirmBtnText={t(isDisablingDelegation ? "disable" : "enable")}
|
||||
cancelBtnText={t("cancel")}
|
||||
variety={isDisablingDelegation ? "danger" : "success"}
|
||||
onConfirm={onConfirm}>
|
||||
<p className="mt-5">
|
||||
{t(
|
||||
isDisablingDelegation
|
||||
? "disable_delegation_credential_description"
|
||||
: "enable_delegation_credential_description"
|
||||
)}
|
||||
</p>
|
||||
{isDisablingDelegation && (
|
||||
<MembersThatWillBeAffectedOnDisablingDelegationCredential delegationCredentialId={delegation.id} />
|
||||
)}
|
||||
</ConfirmationDialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
};
|
||||
|
||||
export default function DelegationCredentialListPage() {
|
||||
return <DelegationCredentialList />;
|
||||
}
|
||||
@@ -1,239 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { useSession } from "next-auth/react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useEffect } from "react";
|
||||
import { Controller, useForm } from "react-hook-form";
|
||||
|
||||
import { TimezoneSelect } from "@calcom/features/components/timezone-select";
|
||||
import LicenseRequired from "@calcom/features/ee/common/components/LicenseRequired";
|
||||
import SectionBottomActions from "@calcom/features/settings/SectionBottomActions";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { nameOfDay } from "@calcom/lib/weekday";
|
||||
import type { RouterOutputs } from "@calcom/trpc/react";
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
import classNames from "@calcom/ui/classNames";
|
||||
import { Button } from "@calcom/ui/components/button";
|
||||
import { Form } from "@calcom/ui/components/form";
|
||||
import { Label } from "@calcom/ui/components/form";
|
||||
import { Select } from "@calcom/ui/components/form";
|
||||
import { SkeletonButton, SkeletonContainer, SkeletonText } from "@calcom/ui/components/skeleton";
|
||||
import { showToast } from "@calcom/ui/components/toast";
|
||||
|
||||
import { DisableAutofillOnBookingPageSwitch } from "../components/DisableAutofillOnBookingPageSwitch";
|
||||
import { DisablePhoneOnlySMSNotificationsSwitch } from "../components/DisablePhoneOnlySMSNotificationsSwitch";
|
||||
import { LockEventTypeSwitch } from "../components/LockEventTypeSwitch";
|
||||
import { NoSlotsNotificationSwitch } from "../components/NoSlotsNotificationSwitch";
|
||||
|
||||
const SkeletonLoader = () => {
|
||||
return (
|
||||
<SkeletonContainer>
|
||||
<div className="mb-8 mt-6 stack-y-6">
|
||||
<SkeletonText className="h-8 w-full" />
|
||||
<SkeletonText className="h-8 w-full" />
|
||||
<SkeletonText className="h-8 w-full" />
|
||||
<SkeletonText className="h-8 w-full" />
|
||||
|
||||
<SkeletonButton className="mr-6 h-8 w-20 rounded-md p-5" />
|
||||
</div>
|
||||
</SkeletonContainer>
|
||||
);
|
||||
};
|
||||
|
||||
interface GeneralViewProps {
|
||||
currentOrg: RouterOutputs["viewer"]["organizations"]["listCurrent"];
|
||||
localeProp: string;
|
||||
|
||||
permissions: {
|
||||
canRead: boolean;
|
||||
canEdit: boolean;
|
||||
};
|
||||
}
|
||||
|
||||
const OrgGeneralView = ({
|
||||
permissions,
|
||||
}: {
|
||||
permissions: {
|
||||
canRead: boolean;
|
||||
canEdit: boolean;
|
||||
};
|
||||
}) => {
|
||||
const { t } = useLocale();
|
||||
const router = useRouter();
|
||||
const session = useSession();
|
||||
|
||||
const {
|
||||
data: currentOrg,
|
||||
isPending,
|
||||
error,
|
||||
} = trpc.viewer.organizations.listCurrent.useQuery(undefined, {});
|
||||
|
||||
useEffect(
|
||||
function refactorMeWithoutEffect() {
|
||||
if (error) {
|
||||
router.replace("/enterprise");
|
||||
}
|
||||
},
|
||||
[error]
|
||||
);
|
||||
|
||||
if (isPending) return <SkeletonLoader />;
|
||||
if (!currentOrg) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<LicenseRequired>
|
||||
<GeneralView
|
||||
currentOrg={currentOrg}
|
||||
localeProp={session.data?.user.locale ?? "en"}
|
||||
permissions={permissions}
|
||||
/>
|
||||
|
||||
{permissions.canEdit && (
|
||||
<>
|
||||
<LockEventTypeSwitch currentOrg={currentOrg} />
|
||||
<NoSlotsNotificationSwitch currentOrg={currentOrg} />
|
||||
<DisablePhoneOnlySMSNotificationsSwitch currentOrg={currentOrg} />
|
||||
<DisableAutofillOnBookingPageSwitch currentOrg={currentOrg} />
|
||||
</>
|
||||
)}
|
||||
</LicenseRequired>
|
||||
);
|
||||
};
|
||||
|
||||
const GeneralView = ({ currentOrg, permissions, localeProp }: GeneralViewProps) => {
|
||||
const { t } = useLocale();
|
||||
|
||||
const mutation = trpc.viewer.organizations.update.useMutation({
|
||||
onSuccess: async () => {
|
||||
reset(getValues());
|
||||
showToast(t("settings_updated_successfully"), "success");
|
||||
},
|
||||
onError: () => {
|
||||
showToast(t("error_updating_settings"), "error");
|
||||
},
|
||||
});
|
||||
|
||||
const timeFormatOptions = [
|
||||
{ value: 12, label: t("12_hour") },
|
||||
{ value: 24, label: t("24_hour") },
|
||||
];
|
||||
|
||||
const weekStartOptions = [
|
||||
{ value: "Sunday", label: nameOfDay(localeProp, 0) },
|
||||
{ value: "Monday", label: nameOfDay(localeProp, 1) },
|
||||
{ value: "Tuesday", label: nameOfDay(localeProp, 2) },
|
||||
{ value: "Wednesday", label: nameOfDay(localeProp, 3) },
|
||||
{ value: "Thursday", label: nameOfDay(localeProp, 4) },
|
||||
{ value: "Friday", label: nameOfDay(localeProp, 5) },
|
||||
{ value: "Saturday", label: nameOfDay(localeProp, 6) },
|
||||
];
|
||||
|
||||
const formMethods = useForm({
|
||||
defaultValues: {
|
||||
timeZone: currentOrg.timeZone || "",
|
||||
timeFormat: {
|
||||
value: currentOrg.timeFormat || 12,
|
||||
label: timeFormatOptions.find((option) => option.value === currentOrg.timeFormat)?.label || 12,
|
||||
},
|
||||
weekStart: {
|
||||
value: currentOrg.weekStart,
|
||||
label:
|
||||
weekStartOptions.find((option) => option.value === currentOrg.weekStart)?.label ||
|
||||
nameOfDay(localeProp, 0),
|
||||
},
|
||||
},
|
||||
});
|
||||
const {
|
||||
formState: { isDirty, isSubmitting },
|
||||
reset,
|
||||
getValues,
|
||||
} = formMethods;
|
||||
const isDisabled = isSubmitting || !isDirty || !permissions.canEdit;
|
||||
return (
|
||||
<Form
|
||||
form={formMethods}
|
||||
handleSubmit={(values) => {
|
||||
mutation.mutate({
|
||||
...values,
|
||||
timeFormat: values.timeFormat.value,
|
||||
weekStart: values.weekStart.value,
|
||||
});
|
||||
}}>
|
||||
<div
|
||||
className={classNames(
|
||||
"border-subtle border-x border-y-0 px-4 py-8 sm:px-6",
|
||||
!permissions.canEdit && "rounded-b-lg border-y"
|
||||
)}>
|
||||
<Controller
|
||||
name="timeZone"
|
||||
control={formMethods.control}
|
||||
render={({ field: { value } }) => (
|
||||
<>
|
||||
<Label className="text-emphasis">
|
||||
<>{t("timezone")}</>
|
||||
</Label>
|
||||
<TimezoneSelect
|
||||
id="timezone"
|
||||
value={value}
|
||||
onChange={(event) => {
|
||||
if (event) formMethods.setValue("timeZone", event.value, { shouldDirty: true });
|
||||
}}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
/>
|
||||
<Controller
|
||||
name="timeFormat"
|
||||
control={formMethods.control}
|
||||
render={({ field: { value } }) => (
|
||||
<>
|
||||
<Label className="text-emphasis mt-6">
|
||||
<>{t("time_format")}</>
|
||||
</Label>
|
||||
<Select
|
||||
value={value}
|
||||
options={timeFormatOptions}
|
||||
onChange={(event) => {
|
||||
if (event) formMethods.setValue("timeFormat", { ...event }, { shouldDirty: true });
|
||||
}}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
/>
|
||||
<div className="text-gray text-default mt-2 flex items-center text-sm">
|
||||
{t("timeformat_profile_hint")}
|
||||
</div>
|
||||
<Controller
|
||||
name="weekStart"
|
||||
control={formMethods.control}
|
||||
render={({ field: { value } }) => (
|
||||
<>
|
||||
<Label className="text-emphasis mt-6">
|
||||
<>{t("start_of_week")}</>
|
||||
</Label>
|
||||
<Select
|
||||
value={value}
|
||||
options={weekStartOptions}
|
||||
onChange={(event) => {
|
||||
if (event) formMethods.setValue("weekStart", { ...event }, { shouldDirty: true });
|
||||
}}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{permissions?.canEdit && (
|
||||
<SectionBottomActions align="end">
|
||||
<Button disabled={isDisabled} color="primary" type="submit">
|
||||
{t("update")}
|
||||
</Button>
|
||||
</SectionBottomActions>
|
||||
)}
|
||||
</Form>
|
||||
);
|
||||
};
|
||||
|
||||
export default OrgGeneralView;
|
||||
@@ -1,65 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import LicenseRequired from "@calcom/features/ee/common/components/LicenseRequired";
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
import { SkeletonContainer, SkeletonText, SkeletonButton } from "@calcom/ui/components/skeleton";
|
||||
|
||||
import DisableGuestBookingEmailsSetting from "../components/DisableGuestBookingEmailsSetting";
|
||||
|
||||
const SkeletonLoader = () => {
|
||||
return (
|
||||
<SkeletonContainer>
|
||||
<div className="mb-8 mt-6 space-y-6">
|
||||
<SkeletonText className="h-8 w-full" />
|
||||
<SkeletonText className="h-8 w-full" />
|
||||
<SkeletonText className="h-8 w-full" />
|
||||
<SkeletonText className="h-8 w-full" />
|
||||
<SkeletonButton className="mr-6 h-8 w-20 rounded-md p-5" />
|
||||
</div>
|
||||
</SkeletonContainer>
|
||||
);
|
||||
};
|
||||
|
||||
const GuestNotificationsView = ({ permissions }: { permissions: { canRead: boolean; canEdit: boolean } }) => {
|
||||
const { data: currentOrg, isPending } = trpc.viewer.organizations.listCurrent.useQuery();
|
||||
const isInviteOpen = !currentOrg?.user.accepted;
|
||||
const isDisabled = !permissions.canEdit || isInviteOpen;
|
||||
|
||||
if (isPending) return <SkeletonLoader />;
|
||||
|
||||
if (!currentOrg) return null;
|
||||
|
||||
if (!currentOrg.organizationSettings) return null;
|
||||
|
||||
return (
|
||||
<LicenseRequired>
|
||||
<div className="space-y-8">
|
||||
<DisableGuestBookingEmailsSetting
|
||||
orgId={currentOrg.id}
|
||||
settings={{
|
||||
disableAttendeeConfirmationEmail:
|
||||
currentOrg.organizationSettings.disableAttendeeConfirmationEmail ?? false,
|
||||
disableAttendeeCancellationEmail:
|
||||
currentOrg.organizationSettings.disableAttendeeCancellationEmail ?? false,
|
||||
disableAttendeeRescheduledEmail:
|
||||
currentOrg.organizationSettings.disableAttendeeRescheduledEmail ?? false,
|
||||
disableAttendeeRequestEmail: currentOrg.organizationSettings.disableAttendeeRequestEmail ?? false,
|
||||
disableAttendeeReassignedEmail:
|
||||
currentOrg.organizationSettings.disableAttendeeReassignedEmail ?? false,
|
||||
disableAttendeeAwaitingPaymentEmail:
|
||||
currentOrg.organizationSettings.disableAttendeeAwaitingPaymentEmail ?? false,
|
||||
disableAttendeeRescheduleRequestEmail:
|
||||
currentOrg.organizationSettings.disableAttendeeRescheduleRequestEmail ?? false,
|
||||
disableAttendeeLocationChangeEmail:
|
||||
currentOrg.organizationSettings.disableAttendeeLocationChangeEmail ?? false,
|
||||
disableAttendeeNewEventEmail:
|
||||
currentOrg.organizationSettings.disableAttendeeNewEventEmail ?? false,
|
||||
}}
|
||||
readOnly={isDisabled}
|
||||
/>
|
||||
</div>
|
||||
</LicenseRequired>
|
||||
);
|
||||
};
|
||||
|
||||
export default GuestNotificationsView;
|
||||
@@ -1,261 +0,0 @@
|
||||
"use client";
|
||||
|
||||
// import { debounce } from "lodash";
|
||||
import { keepPreviousData } from "@tanstack/react-query";
|
||||
import { useSession } from "next-auth/react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useState, useEffect } from "react";
|
||||
|
||||
import MemberInvitationModal from "@calcom/ee/teams/components/MemberInvitationModal";
|
||||
import { checkAdminOrOwner } from "@calcom/features/auth/lib/checkAdminOrOwner";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { useParamsWithFallback } from "@calcom/lib/hooks/useParamsWithFallback";
|
||||
import { CreationSource } from "@calcom/prisma/enums";
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
import type { RouterOutputs } from "@calcom/trpc/react";
|
||||
import { Button } from "@calcom/ui/components/button";
|
||||
import { showToast } from "@calcom/ui/components/toast";
|
||||
import { revalidateTeamsList } from "@calcom/web/app/(use-page-wrapper)/(main-nav)/teams/actions";
|
||||
|
||||
import MakeTeamPrivateSwitch from "../../../teams/components/MakeTeamPrivateSwitch";
|
||||
import MemberListItem from "../components/MemberListItem";
|
||||
|
||||
type Members = RouterOutputs["viewer"]["organizations"]["listOtherTeamMembers"]["rows"];
|
||||
type Team = RouterOutputs["viewer"]["organizations"]["getOtherTeam"];
|
||||
|
||||
interface MembersListProps {
|
||||
members: Members | undefined;
|
||||
team: Team | undefined;
|
||||
fetchNextPage: () => void;
|
||||
hasNextPage: boolean | undefined;
|
||||
isFetchingNextPage: boolean | undefined;
|
||||
}
|
||||
|
||||
function MembersList(props: MembersListProps) {
|
||||
const { t } = useLocale();
|
||||
const { hasNextPage, members = [], team, fetchNextPage, isFetchingNextPage } = props;
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-y-3">
|
||||
{members?.length && team ? (
|
||||
<ul className="divide-subtle border-subtle divide-y rounded-md border">
|
||||
{members.map((member) => {
|
||||
return <MemberListItem key={member.id} member={member} />;
|
||||
})}
|
||||
</ul>
|
||||
) : null}
|
||||
{members?.length === 0 && (
|
||||
<div className="flex flex-col items-center justify-center">
|
||||
<p className="text-default text-sm font-bold">{t("no_members_found")}</p>
|
||||
</div>
|
||||
)}
|
||||
<div className="text-default p-4 text-center">
|
||||
<Button
|
||||
color="minimal"
|
||||
loading={isFetchingNextPage}
|
||||
disabled={!hasNextPage}
|
||||
onClick={() => fetchNextPage()}>
|
||||
{hasNextPage ? t("load_more_results") : t("no_more_results")}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export const memberInvitationModalRef = {
|
||||
current: null as null | ((show: boolean) => void),
|
||||
};
|
||||
|
||||
export const TeamMembersCTA = () => {
|
||||
const { t } = useLocale();
|
||||
const session = useSession();
|
||||
const { data: currentOrg } = trpc.viewer.organizations.listCurrent.useQuery(undefined, {
|
||||
enabled: !!session.data?.user?.org,
|
||||
});
|
||||
|
||||
const isOrgAdminOrOwner = currentOrg && checkAdminOrOwner(currentOrg.user.role);
|
||||
|
||||
if (!isOrgAdminOrOwner) return null;
|
||||
|
||||
return (
|
||||
<Button
|
||||
type="button"
|
||||
color="primary"
|
||||
StartIcon="plus"
|
||||
className="ml-auto"
|
||||
onClick={() => memberInvitationModalRef.current?.(true)}
|
||||
data-testid="new-member-button">
|
||||
{t("add")}
|
||||
</Button>
|
||||
);
|
||||
};
|
||||
|
||||
const MembersView = () => {
|
||||
const { t, i18n } = useLocale();
|
||||
const router = useRouter();
|
||||
const params = useParamsWithFallback();
|
||||
const teamId = Number(params.id);
|
||||
const utils = trpc.useUtils();
|
||||
// const [query, setQuery] = useState<string | undefined>("");
|
||||
// const [queryToFetch, setQueryToFetch] = useState<string | undefined>("");
|
||||
const limit = 20;
|
||||
const [showMemberInvitationModal, setShowMemberInvitationModal] = useState<boolean>(false);
|
||||
|
||||
const {
|
||||
data: team,
|
||||
isPending: isTeamLoading,
|
||||
error: otherTeamError,
|
||||
} = trpc.viewer.organizations.getOtherTeam.useQuery(
|
||||
{ teamId },
|
||||
{
|
||||
enabled: !Number.isNaN(teamId),
|
||||
}
|
||||
);
|
||||
const { data: orgMembersNotInThisTeam, isPending: isOrgListLoading } =
|
||||
trpc.viewer.organizations.getMembers.useQuery(
|
||||
{
|
||||
teamIdToExclude: teamId,
|
||||
distinctUser: true,
|
||||
},
|
||||
{
|
||||
enabled: !Number.isNaN(teamId),
|
||||
}
|
||||
);
|
||||
|
||||
const {
|
||||
fetchNextPage,
|
||||
isFetchingNextPage,
|
||||
hasNextPage,
|
||||
error: otherMembersError,
|
||||
data,
|
||||
} = trpc.viewer.organizations.listOtherTeamMembers.useInfiniteQuery(
|
||||
{ teamId, limit },
|
||||
{
|
||||
enabled: !Number.isNaN(teamId),
|
||||
getNextPageParam: (lastPage) => lastPage.nextCursor,
|
||||
placeholderData: keepPreviousData,
|
||||
}
|
||||
);
|
||||
|
||||
useEffect(
|
||||
function refactorMeWithoutEffect() {
|
||||
if (otherMembersError || otherTeamError) {
|
||||
router.replace("/enterprise");
|
||||
}
|
||||
},
|
||||
[router, otherMembersError, otherTeamError]
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
memberInvitationModalRef.current = setShowMemberInvitationModal;
|
||||
return () => {
|
||||
memberInvitationModalRef.current = null;
|
||||
};
|
||||
}, []);
|
||||
|
||||
const isPending = isTeamLoading || isOrgListLoading;
|
||||
const inviteMemberMutation = trpc.viewer.teams.inviteMember.useMutation({
|
||||
onSuccess: () => {
|
||||
utils.viewer.organizations.getMembers.invalidate();
|
||||
utils.viewer.organizations.listOtherTeams.invalidate();
|
||||
utils.viewer.teams.list.invalidate();
|
||||
revalidateTeamsList();
|
||||
utils.viewer.organizations.listOtherTeamMembers.invalidate();
|
||||
},
|
||||
});
|
||||
|
||||
return (
|
||||
<>
|
||||
{!isPending && (
|
||||
<>
|
||||
<div>
|
||||
<>
|
||||
{/* Currently failing due to re render and loose focus */}
|
||||
{/* <TextField
|
||||
type="search"
|
||||
autoComplete="false"
|
||||
onChange={(e) => {
|
||||
setQuery(e.target.value);
|
||||
debouncedFunction(e.target.value);
|
||||
}}
|
||||
value={query}
|
||||
placeholder={`${t("search")}...`}
|
||||
/> */}
|
||||
<MembersList
|
||||
members={data?.pages?.flatMap((page) => page.rows) ?? []}
|
||||
team={team}
|
||||
fetchNextPage={fetchNextPage}
|
||||
hasNextPage={hasNextPage}
|
||||
isFetchingNextPage={isFetchingNextPage}
|
||||
/>
|
||||
</>
|
||||
|
||||
{team && (
|
||||
<>
|
||||
<hr className="border-subtle my-8 mt-6" />
|
||||
<MakeTeamPrivateSwitch
|
||||
teamId={team.id}
|
||||
isPrivate={team.isPrivate}
|
||||
disabled={false}
|
||||
isOrg={false}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
{showMemberInvitationModal && team && (
|
||||
<MemberInvitationModal
|
||||
isPending={inviteMemberMutation.isPending}
|
||||
isOpen={showMemberInvitationModal}
|
||||
orgMembers={orgMembersNotInThisTeam}
|
||||
teamId={team.id}
|
||||
disableCopyLink={true}
|
||||
onExit={() => setShowMemberInvitationModal(false)}
|
||||
onSubmit={(values, resetFields) => {
|
||||
inviteMemberMutation.mutate(
|
||||
{
|
||||
teamId,
|
||||
language: i18n.language,
|
||||
role: values.role,
|
||||
usernameOrEmail: values.emailOrUsername,
|
||||
creationSource: CreationSource.WEBAPP,
|
||||
},
|
||||
{
|
||||
onSuccess: async (data) => {
|
||||
await utils.viewer.teams.get.invalidate();
|
||||
setShowMemberInvitationModal(false);
|
||||
|
||||
if (Array.isArray(data.usernameOrEmail)) {
|
||||
showToast(
|
||||
t("email_invite_team_bulk", {
|
||||
userCount: data.numUsersInvited,
|
||||
}),
|
||||
"success"
|
||||
);
|
||||
resetFields();
|
||||
} else {
|
||||
showToast(
|
||||
t("email_invite_team", {
|
||||
email: data.usernameOrEmail,
|
||||
}),
|
||||
"success"
|
||||
);
|
||||
}
|
||||
},
|
||||
onError: (error) => {
|
||||
showToast(error.message, "error");
|
||||
},
|
||||
}
|
||||
);
|
||||
}}
|
||||
onSettingsOpen={() => {
|
||||
setShowMemberInvitationModal(false);
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export default MembersView;
|
||||
@@ -1,351 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import Link from "next/link";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useEffect, useLayoutEffect, useState } from "react";
|
||||
import { Controller, useForm } from "react-hook-form";
|
||||
import { z } from "zod";
|
||||
|
||||
import { Dialog } from "@calcom/features/components/controlled-dialog";
|
||||
import { trackFormbricksAction } from "@calcom/features/formbricks/formbricks-client";
|
||||
import { IS_TEAM_BILLING_ENABLED_CLIENT, WEBAPP_URL } from "@calcom/lib/constants";
|
||||
import { getPlaceholderAvatar } from "@calcom/lib/defaultAvatarImage";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { useParamsWithFallback } from "@calcom/lib/hooks/useParamsWithFallback";
|
||||
import { md } from "@calcom/lib/markdownIt";
|
||||
import { markdownToSafeHTML } from "@calcom/lib/markdownToSafeHTML";
|
||||
import objectKeys from "@calcom/lib/objectKeys";
|
||||
import slugify from "@calcom/lib/slugify";
|
||||
import turndown from "@calcom/lib/turndownService";
|
||||
import type { Prisma } from "@calcom/prisma/client";
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
import { Avatar } from "@calcom/ui/components/avatar";
|
||||
import { Button, LinkIconButton } from "@calcom/ui/components/button";
|
||||
import { DialogTrigger, ConfirmationDialogContent } from "@calcom/ui/components/dialog";
|
||||
import { Editor } from "@calcom/ui/components/editor";
|
||||
import { Form } from "@calcom/ui/components/form";
|
||||
import { Label } from "@calcom/ui/components/form";
|
||||
import { TextField } from "@calcom/ui/components/form";
|
||||
import { ImageUploader } from "@calcom/ui/components/image-uploader";
|
||||
import { SkeletonContainer, SkeletonText } from "@calcom/ui/components/skeleton";
|
||||
import { showToast } from "@calcom/ui/components/toast";
|
||||
import { revalidateTeamDataCache } from "@calcom/web/app/(booking-page-wrapper)/team/[slug]/[type]/actions";
|
||||
|
||||
import { subdomainSuffix } from "../../../organizations/lib/orgDomains";
|
||||
|
||||
const regex = new RegExp("^[a-zA-Z0-9-]*$");
|
||||
|
||||
const teamProfileFormSchema = z.object({
|
||||
name: z.string(),
|
||||
slug: z
|
||||
.string()
|
||||
.regex(regex, {
|
||||
message: "Url can only have alphanumeric characters(a-z, 0-9) and hyphen(-) symbol.",
|
||||
})
|
||||
.min(1, { message: "Url cannot be left empty" }),
|
||||
logoUrl: z.string().nullable(),
|
||||
bio: z.string(),
|
||||
});
|
||||
|
||||
const OtherTeamProfileView = () => {
|
||||
const { t } = useLocale();
|
||||
const router = useRouter();
|
||||
const utils = trpc.useUtils();
|
||||
const [firstRender, setFirstRender] = useState(true);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
document.body.focus();
|
||||
}, []);
|
||||
|
||||
const mutation = trpc.viewer.teams.update.useMutation({
|
||||
onError: (err) => {
|
||||
showToast(err.message, "error");
|
||||
},
|
||||
async onSuccess() {
|
||||
await utils.viewer.teams.get.invalidate();
|
||||
if (team?.slug) {
|
||||
// Org admins editing another team's profile should purge the cached team data
|
||||
revalidateTeamDataCache({
|
||||
teamSlug: team.slug,
|
||||
orgSlug: team.parent?.slug ?? null,
|
||||
});
|
||||
}
|
||||
showToast(t("your_team_updated_successfully"), "success");
|
||||
},
|
||||
});
|
||||
|
||||
const form = useForm({
|
||||
resolver: zodResolver(teamProfileFormSchema),
|
||||
});
|
||||
const params = useParamsWithFallback();
|
||||
const teamId = Number(params.id);
|
||||
const {
|
||||
data: team,
|
||||
isPending,
|
||||
error: teamError,
|
||||
} = trpc.viewer.organizations.getOtherTeam.useQuery(
|
||||
{ teamId: teamId },
|
||||
{
|
||||
enabled: !Number.isNaN(teamId),
|
||||
}
|
||||
);
|
||||
useEffect(
|
||||
function refactorMeWithoutEffect() {
|
||||
if (teamError) {
|
||||
router.replace("/enterprise");
|
||||
}
|
||||
},
|
||||
[teamError]
|
||||
);
|
||||
|
||||
useEffect(
|
||||
function refactorMeWithoutEffect() {
|
||||
if (team) {
|
||||
form.setValue("name", team.name || "");
|
||||
form.setValue("slug", team.slug || "");
|
||||
form.setValue("logoUrl", team.logoUrl);
|
||||
form.setValue("bio", team.bio || "");
|
||||
if (team.slug === null && (team?.metadata as Prisma.JsonObject)?.requestedSlug) {
|
||||
form.setValue("slug", ((team?.metadata as Prisma.JsonObject)?.requestedSlug as string) || "");
|
||||
}
|
||||
}
|
||||
},
|
||||
[team]
|
||||
);
|
||||
|
||||
// This page can only be accessed by team admins (owner/admin)
|
||||
const isAdmin = true;
|
||||
|
||||
const permalink = `${WEBAPP_URL}/team/${team?.slug}`;
|
||||
|
||||
const isBioEmpty = !team || !team.bio || !team.bio.replace("<p><br></p>", "").length;
|
||||
|
||||
const deleteTeamMutation = trpc.viewer.organizations.deleteTeam.useMutation({
|
||||
async onSuccess() {
|
||||
await utils.viewer.organizations.listOtherTeams.invalidate();
|
||||
showToast(t("your_team_disbanded_successfully"), "success");
|
||||
router.push(`${WEBAPP_URL}/teams`);
|
||||
trackFormbricksAction("team_disbanded");
|
||||
},
|
||||
});
|
||||
|
||||
const publishMutation = trpc.viewer.teams.publish.useMutation({
|
||||
async onSuccess(data: { url?: string }) {
|
||||
if (data.url) {
|
||||
router.push(data.url);
|
||||
}
|
||||
},
|
||||
async onError(err) {
|
||||
showToast(err.message, "error");
|
||||
},
|
||||
});
|
||||
|
||||
function deleteTeam() {
|
||||
if (team?.id) deleteTeamMutation.mutate({ teamId: team.id });
|
||||
}
|
||||
|
||||
if (!team) return null;
|
||||
|
||||
return (
|
||||
<>
|
||||
{!isPending ? (
|
||||
<>
|
||||
{isAdmin ? (
|
||||
<Form
|
||||
form={form}
|
||||
handleSubmit={(values) => {
|
||||
if (team) {
|
||||
const variables = {
|
||||
logoUrl: values.logoUrl,
|
||||
name: values.name,
|
||||
slug: values.slug,
|
||||
bio: values.bio,
|
||||
};
|
||||
objectKeys(variables).forEach((key) => {
|
||||
if (variables[key as keyof typeof variables] === team?.[key]) delete variables[key];
|
||||
});
|
||||
mutation.mutate({ id: team.id, ...variables });
|
||||
}
|
||||
}}>
|
||||
<div className="flex items-center">
|
||||
<Controller
|
||||
control={form.control}
|
||||
name="logoUrl"
|
||||
render={({ field: { value, onChange } }) => (
|
||||
<>
|
||||
<Avatar alt="" imageSrc={getPlaceholderAvatar(value, team?.name)} size="lg" />
|
||||
<div className="ms-4">
|
||||
<ImageUploader
|
||||
target="logo"
|
||||
id="avatar-upload"
|
||||
buttonMsg={t("update")}
|
||||
handleAvatarChange={onChange}
|
||||
imageSrc={value}
|
||||
/>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<hr className="border-subtle my-8" />
|
||||
|
||||
<Controller
|
||||
control={form.control}
|
||||
name="name"
|
||||
render={({ field: { value, onChange } }) => (
|
||||
<div className="mt-8">
|
||||
<TextField
|
||||
name="name"
|
||||
label={t("team_name")}
|
||||
value={value}
|
||||
onChange={(e) => onChange(e?.target.value)}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
/>
|
||||
<Controller
|
||||
control={form.control}
|
||||
name="slug"
|
||||
render={({ field: { value, onChange } }) => (
|
||||
<div className="mt-8">
|
||||
<TextField
|
||||
name="slug"
|
||||
label={t("team_url")}
|
||||
value={value}
|
||||
addOnLeading={
|
||||
team?.parent ? `${team.parent.slug}.${subdomainSuffix()}/` : `${WEBAPP_URL}/team/`
|
||||
}
|
||||
onChange={(e) => {
|
||||
form.clearErrors("slug");
|
||||
onChange(slugify(e?.target.value, true));
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
/>
|
||||
<div className="mt-8">
|
||||
<Label>{t("about")}</Label>
|
||||
<Editor
|
||||
getText={() => md.render(form.getValues("bio") || "")}
|
||||
setText={(value: string) => form.setValue("bio", turndown(value))}
|
||||
excludedToolbarItems={["blockType"]}
|
||||
disableLists
|
||||
firstRender={firstRender}
|
||||
setFirstRender={setFirstRender}
|
||||
height="80px"
|
||||
/>
|
||||
</div>
|
||||
<p className="text-default mt-2 text-sm">{t("team_description")}</p>
|
||||
<Button color="primary" className="mt-8" type="submit" loading={mutation.isPending}>
|
||||
{t("update")}
|
||||
</Button>
|
||||
{IS_TEAM_BILLING_ENABLED_CLIENT &&
|
||||
team.slug === null &&
|
||||
(team.metadata as Prisma.JsonObject)?.requestedSlug && (
|
||||
<Button
|
||||
color="secondary"
|
||||
className="ml-2 mt-8"
|
||||
type="button"
|
||||
onClick={() => {
|
||||
publishMutation.mutate({ teamId: team.id });
|
||||
}}>
|
||||
Publish
|
||||
</Button>
|
||||
)}
|
||||
</Form>
|
||||
) : (
|
||||
<div className="flex">
|
||||
<div className="grow">
|
||||
<div>
|
||||
<Label className="text-emphasis">{t("team_name")}</Label>
|
||||
<p className="text-default text-sm">{team?.name}</p>
|
||||
</div>
|
||||
{team && !isBioEmpty && (
|
||||
<>
|
||||
<Label className="text-emphasis mt-5">{t("about")}</Label>
|
||||
<div
|
||||
className=" text-subtle wrap-break-word text-sm [&_a]:text-blue-500 [&_a]:underline [&_a]:hover:text-blue-600"
|
||||
// eslint-disable-next-line react/no-danger
|
||||
dangerouslySetInnerHTML={{ __html: markdownToSafeHTML(team.bio) }}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
<div className="">
|
||||
<Link href={permalink} passHref={true} target="_blank">
|
||||
<LinkIconButton Icon="external-link">{t("preview")}</LinkIconButton>
|
||||
</Link>
|
||||
<LinkIconButton
|
||||
Icon="link"
|
||||
onClick={() => {
|
||||
navigator.clipboard.writeText(permalink);
|
||||
showToast("Copied to clipboard", "success");
|
||||
}}>
|
||||
{t("copy_link_team")}
|
||||
</LinkIconButton>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
<hr className="border-subtle my-8 border" />
|
||||
|
||||
<div className="text-default mb-3 text-base font-semibold">{t("danger_zone")}</div>
|
||||
|
||||
<Dialog>
|
||||
<DialogTrigger asChild>
|
||||
<Button color="destructive" className="border" StartIcon="trash-2">
|
||||
{t("disband_team")}
|
||||
</Button>
|
||||
</DialogTrigger>
|
||||
<ConfirmationDialogContent
|
||||
variety="danger"
|
||||
title={t("disband_team")}
|
||||
confirmBtnText={t("confirm_disband_team")}
|
||||
onConfirm={() => {
|
||||
deleteTeam();
|
||||
}}>
|
||||
{t("disband_team_confirmation_message")}
|
||||
</ConfirmationDialogContent>
|
||||
</Dialog>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<SkeletonContainer as="form">
|
||||
<div className="flex items-center">
|
||||
<div className="ms-4">
|
||||
<SkeletonContainer>
|
||||
<div className="bg-emphasis h-16 w-16 rounded-full" />
|
||||
</SkeletonContainer>
|
||||
</div>
|
||||
</div>
|
||||
<hr className="border-subtle my-8" />
|
||||
<SkeletonContainer>
|
||||
<div className="mt-8">
|
||||
<SkeletonText className="h-6 w-48" />
|
||||
</div>
|
||||
</SkeletonContainer>
|
||||
<SkeletonContainer>
|
||||
<div className="mt-8">
|
||||
<SkeletonText className="h-6 w-48" />
|
||||
</div>
|
||||
</SkeletonContainer>
|
||||
<div className="mt-8">
|
||||
<SkeletonContainer>
|
||||
<div className="bg-emphasis h-24 rounded-md" />
|
||||
</SkeletonContainer>
|
||||
<SkeletonText className="mt-4 h-12 w-32" />
|
||||
</div>
|
||||
<SkeletonContainer>
|
||||
<div className="mt-8">
|
||||
<SkeletonText className="h-9 w-24" />
|
||||
</div>
|
||||
</SkeletonContainer>
|
||||
</SkeletonContainer>
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export default OtherTeamProfileView;
|
||||
@@ -1,73 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { usePathname } from "next/navigation";
|
||||
|
||||
import { DataTableProvider } from "@calcom/features/data-table";
|
||||
import { useSegments } from "@calcom/features/data-table/hooks/useSegments";
|
||||
import LicenseRequired from "@calcom/features/ee/common/components/LicenseRequired";
|
||||
import MakeTeamPrivateSwitch from "@calcom/features/ee/teams/components/MakeTeamPrivateSwitch";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
|
||||
import { BlocklistTable } from "~/settings/organizations/privacy/blocklist-table";
|
||||
|
||||
import OrgAutoJoinSetting from "../components/OrgAutoJoinSetting";
|
||||
|
||||
const PrivacyView = ({
|
||||
permissions,
|
||||
watchlistPermissions,
|
||||
}: {
|
||||
permissions: { canRead: boolean; canEdit: boolean };
|
||||
watchlistPermissions?: {
|
||||
canRead: boolean;
|
||||
canCreate: boolean;
|
||||
canDelete: boolean;
|
||||
};
|
||||
}) => {
|
||||
const pathname = usePathname();
|
||||
const { t } = useLocale();
|
||||
const { data: currentOrg } = trpc.viewer.organizations.listCurrent.useQuery();
|
||||
const isInviteOpen = !currentOrg?.user.accepted;
|
||||
const isDisabled = !permissions.canEdit || isInviteOpen;
|
||||
|
||||
if (!currentOrg) return null;
|
||||
|
||||
if (!pathname) return null;
|
||||
|
||||
return (
|
||||
<LicenseRequired>
|
||||
<div className="stack-y-8">
|
||||
<MakeTeamPrivateSwitch
|
||||
isOrg={true}
|
||||
teamId={currentOrg.id}
|
||||
isPrivate={currentOrg.isPrivate}
|
||||
disabled={isDisabled}
|
||||
/>
|
||||
|
||||
{currentOrg.organizationSettings?.orgAutoAcceptEmail && (
|
||||
<OrgAutoJoinSetting
|
||||
orgId={currentOrg.id}
|
||||
orgAutoJoinEnabled={!!currentOrg.organizationSettings.orgAutoJoinOnSignup}
|
||||
emailDomain={currentOrg.organizationSettings.orgAutoAcceptEmail}
|
||||
/>
|
||||
)}
|
||||
|
||||
{watchlistPermissions?.canRead && (
|
||||
<div>
|
||||
<div>
|
||||
<h2 className="text-emphasis text-base font-semibold">{t("organization_blocklist")}</h2>
|
||||
<p className="text-muted text-sm">{t("manage_blocked_emails_and_domains")}</p>
|
||||
</div>
|
||||
<div className="mt-2">
|
||||
<DataTableProvider tableIdentifier={pathname} useSegments={useSegments} defaultPageSize={25}>
|
||||
<BlocklistTable permissions={watchlistPermissions} />
|
||||
</DataTableProvider>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</LicenseRequired>
|
||||
);
|
||||
};
|
||||
|
||||
export default PrivacyView;
|
||||
@@ -1,446 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useEffect, useLayoutEffect, useState } from "react";
|
||||
import { Controller, useForm } from "react-hook-form";
|
||||
import { z } from "zod";
|
||||
|
||||
import LicenseRequired from "@calcom/features/ee/common/components/LicenseRequired";
|
||||
import { subdomainSuffix } from "@calcom/features/ee/organizations/lib/orgDomains";
|
||||
import OrgAppearanceViewWrapper from "@calcom/features/ee/organizations/pages/settings/appearance";
|
||||
import SectionBottomActions from "@calcom/features/settings/SectionBottomActions";
|
||||
import { getPlaceholderAvatar } from "@calcom/lib/defaultAvatarImage";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { md } from "@calcom/lib/markdownIt";
|
||||
import { markdownToSafeHTML } from "@calcom/lib/markdownToSafeHTML";
|
||||
import turndown from "@calcom/lib/turndownService";
|
||||
import type { Prisma } from "@calcom/prisma/client";
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
import { Avatar } from "@calcom/ui/components/avatar";
|
||||
import { Button } from "@calcom/ui/components/button";
|
||||
import { LinkIconButton } from "@calcom/ui/components/button";
|
||||
import { Editor } from "@calcom/ui/components/editor";
|
||||
import { Form } from "@calcom/ui/components/form";
|
||||
import { Label } from "@calcom/ui/components/form";
|
||||
import { TextField } from "@calcom/ui/components/form";
|
||||
import { Icon } from "@calcom/ui/components/icon";
|
||||
import { BannerUploader, ImageUploader } from "@calcom/ui/components/image-uploader";
|
||||
// if I include this in the above barrel import, I get a runtime error that the component is not exported.
|
||||
import { OrgBanner } from "@calcom/ui/components/organization-banner";
|
||||
import {
|
||||
SkeletonButton,
|
||||
SkeletonContainer,
|
||||
SkeletonText,
|
||||
SkeletonAvatar,
|
||||
} from "@calcom/ui/components/skeleton";
|
||||
import { showToast } from "@calcom/ui/components/toast";
|
||||
import { Tooltip } from "@calcom/ui/components/tooltip";
|
||||
|
||||
import { useOrgBranding } from "../../../organizations/context/provider";
|
||||
|
||||
const orgProfileFormSchema = z.object({
|
||||
name: z.string(),
|
||||
logoUrl: z.string().nullable(),
|
||||
banner: z.string().nullable(),
|
||||
calVideoLogo: z.string().nullable(),
|
||||
bio: z.string(),
|
||||
});
|
||||
|
||||
type FormValues = {
|
||||
id: number;
|
||||
name: string;
|
||||
logoUrl: string | null;
|
||||
banner: string | null;
|
||||
bio: string;
|
||||
slug: string;
|
||||
calVideoLogo: string | null;
|
||||
};
|
||||
|
||||
const SkeletonLoader = () => {
|
||||
return (
|
||||
<SkeletonContainer>
|
||||
<div className="border-subtle stack-y-6 rounded-b-xl border border-t-0 px-4 py-8">
|
||||
<div className="flex items-center">
|
||||
<SkeletonAvatar className="me-4 mt-0 h-16 w-16 px-4" />
|
||||
<SkeletonButton className="h-6 w-32 rounded-md p-5" />
|
||||
</div>
|
||||
<SkeletonText className="h-8 w-full" />
|
||||
<SkeletonText className="h-8 w-full" />
|
||||
<SkeletonText className="h-8 w-full" />
|
||||
|
||||
<SkeletonButton className="mr-6 h-8 w-20 rounded-md p-5" />
|
||||
</div>
|
||||
</SkeletonContainer>
|
||||
);
|
||||
};
|
||||
|
||||
const OrgProfileView = ({
|
||||
permissions,
|
||||
}: {
|
||||
permissions?: {
|
||||
canRead: boolean;
|
||||
canEdit: boolean;
|
||||
canDelete: boolean;
|
||||
};
|
||||
}) => {
|
||||
const { t } = useLocale();
|
||||
const router = useRouter();
|
||||
|
||||
const orgBranding = useOrgBranding();
|
||||
|
||||
useLayoutEffect(() => {
|
||||
document.body.focus();
|
||||
}, []);
|
||||
|
||||
const {
|
||||
data: currentOrganisation,
|
||||
isPending,
|
||||
error,
|
||||
} = trpc.viewer.organizations.listCurrent.useQuery(undefined, {});
|
||||
|
||||
useEffect(
|
||||
function refactorMeWithoutEffect() {
|
||||
if (error) {
|
||||
router.replace("/enterprise");
|
||||
}
|
||||
},
|
||||
[error, router]
|
||||
);
|
||||
|
||||
if (isPending || !orgBranding || !currentOrganisation) {
|
||||
return <SkeletonLoader />;
|
||||
}
|
||||
|
||||
const isBioEmpty =
|
||||
!currentOrganisation ||
|
||||
!currentOrganisation.bio ||
|
||||
!currentOrganisation.bio.replace("<p><br></p>", "").length;
|
||||
|
||||
const defaultValues: FormValues = {
|
||||
id: currentOrganisation?.id,
|
||||
name: currentOrganisation?.name || "",
|
||||
logoUrl: currentOrganisation?.logoUrl,
|
||||
banner: currentOrganisation?.bannerUrl || "",
|
||||
bio: currentOrganisation?.bio || "",
|
||||
calVideoLogo: currentOrganisation?.calVideoLogo || "",
|
||||
slug:
|
||||
currentOrganisation?.slug ||
|
||||
((currentOrganisation?.metadata as Prisma.JsonObject)?.requestedSlug as string) ||
|
||||
"",
|
||||
};
|
||||
|
||||
return (
|
||||
<LicenseRequired>
|
||||
<>
|
||||
{permissions?.canEdit ? (
|
||||
<>
|
||||
<OrgProfileForm defaultValues={defaultValues} />
|
||||
<OrgAppearanceViewWrapper />
|
||||
</>
|
||||
) : (
|
||||
<div className="border-subtle flex rounded-b-md border border-t-0 px-4 py-8 sm:px-6">
|
||||
<div className="grow">
|
||||
<div>
|
||||
<Label className="text-emphasis">{t("organization_name")}</Label>
|
||||
<p className="text-default text-sm">{currentOrganisation?.name}</p>
|
||||
</div>
|
||||
{!isBioEmpty && (
|
||||
<>
|
||||
<Label className="text-emphasis mt-5">{t("about")}</Label>
|
||||
<div
|
||||
className=" text-subtle wrap-break-word text-sm [&_a]:text-blue-500 [&_a]:underline [&_a]:hover:text-blue-600"
|
||||
// eslint-disable-next-line react/no-danger
|
||||
dangerouslySetInnerHTML={{
|
||||
__html: markdownToSafeHTML(currentOrganisation.bio || ""),
|
||||
}}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
<div className="">
|
||||
<LinkIconButton
|
||||
Icon="link"
|
||||
onClick={() => {
|
||||
navigator.clipboard.writeText(orgBranding.fullDomain);
|
||||
showToast("Copied to clipboard", "success");
|
||||
}}>
|
||||
{t("copy_link_org")}
|
||||
</LinkIconButton>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{/* LEAVE ORG should go above here ^ */}
|
||||
</>
|
||||
</LicenseRequired>
|
||||
);
|
||||
};
|
||||
|
||||
const OrgProfileForm = ({ defaultValues }: { defaultValues: FormValues }) => {
|
||||
const utils = trpc.useUtils();
|
||||
const { t } = useLocale();
|
||||
const [firstRender, setFirstRender] = useState(true);
|
||||
|
||||
const form = useForm({
|
||||
defaultValues,
|
||||
resolver: zodResolver(orgProfileFormSchema),
|
||||
});
|
||||
|
||||
const mutation = trpc.viewer.organizations.update.useMutation({
|
||||
onError: (err) => {
|
||||
// Handle JSON parsing errors from body size limit exceeded
|
||||
if (err.message.includes("Unexpected token") && err.message.includes("Body excee")) {
|
||||
showToast(t("converted_image_size_limit_exceed"), "error");
|
||||
return;
|
||||
}
|
||||
showToast(err.message, "error");
|
||||
},
|
||||
onSuccess: async (res) => {
|
||||
reset({
|
||||
logoUrl: res.data?.logoUrl,
|
||||
name: (res.data?.name || "") as string,
|
||||
bio: (res.data?.bio || "") as string,
|
||||
slug: defaultValues["slug"],
|
||||
banner: (res.data?.bannerUrl || "") as string,
|
||||
calVideoLogo: (res.data?.calVideoLogo || "") as string,
|
||||
});
|
||||
await utils.viewer.teams.get.invalidate();
|
||||
await utils.viewer.organizations.listCurrent.invalidate();
|
||||
showToast(t("your_organization_updated_sucessfully"), "success");
|
||||
},
|
||||
});
|
||||
|
||||
const {
|
||||
formState: { isSubmitting, isDirty },
|
||||
reset,
|
||||
} = form;
|
||||
|
||||
const isDisabled = isSubmitting || !isDirty;
|
||||
|
||||
const handleCopy = async (value: string) => {
|
||||
try {
|
||||
await navigator.clipboard.writeText(value);
|
||||
showToast(t("organization_id_copied"), "success");
|
||||
} catch (error) {
|
||||
showToast(t("error_copying_to_clipboard"), "error");
|
||||
}
|
||||
};
|
||||
return (
|
||||
<Form
|
||||
form={form}
|
||||
handleSubmit={(values) => {
|
||||
const variables = {
|
||||
logoUrl: values.logoUrl,
|
||||
name: values.name,
|
||||
slug: values.slug,
|
||||
bio: values.bio,
|
||||
banner: values.banner,
|
||||
calVideoLogo: values.calVideoLogo,
|
||||
};
|
||||
|
||||
mutation.mutate(variables);
|
||||
}}>
|
||||
<div className="border-subtle border-x px-4 py-8 sm:px-6">
|
||||
<div className="flex items-center">
|
||||
<Controller
|
||||
control={form.control}
|
||||
name="logoUrl"
|
||||
render={({ field: { value, onChange } }) => {
|
||||
const showRemoveLogoButton = value !== null;
|
||||
return (
|
||||
<>
|
||||
<Avatar
|
||||
data-testid="profile-upload-logo"
|
||||
alt={form.getValues("name")}
|
||||
imageSrc={getPlaceholderAvatar(value, form.getValues("name"))}
|
||||
size="lg"
|
||||
/>
|
||||
<div className="ms-4">
|
||||
<div className="flex gap-2">
|
||||
<ImageUploader
|
||||
target="logo"
|
||||
id="avatar-upload"
|
||||
buttonMsg={t("upload_logo")}
|
||||
handleAvatarChange={onChange}
|
||||
imageSrc={getPlaceholderAvatar(value, form.getValues("name"))}
|
||||
triggerButtonColor={showRemoveLogoButton ? "secondary" : "primary"}
|
||||
/>
|
||||
{showRemoveLogoButton && (
|
||||
<Button color="secondary" onClick={() => onChange(null)}>
|
||||
{t("remove")}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="my-4 flex flex-col gap-4">
|
||||
<Controller
|
||||
control={form.control}
|
||||
name="banner"
|
||||
render={({ field: { value, onChange } }) => {
|
||||
const showRemoveBannerButton = !!value;
|
||||
|
||||
return (
|
||||
<>
|
||||
<OrgBanner
|
||||
data-testid="profile-upload-banner"
|
||||
alt={`${defaultValues.name} Banner` || ""}
|
||||
className="grid min-h-[150px] w-full place-items-center rounded-md sm:min-h-[200px]"
|
||||
fallback={t("no_target", { target: "banner" })}
|
||||
imageSrc={value}
|
||||
/>
|
||||
<div className="ms-4">
|
||||
<div className="flex gap-2">
|
||||
<BannerUploader
|
||||
height={500}
|
||||
width={1500}
|
||||
target="banner"
|
||||
uploadInstruction={t("org_banner_instructions", { height: 500, width: 1500 })}
|
||||
id="banner-upload"
|
||||
buttonMsg={t("upload_banner")}
|
||||
handleAvatarChange={onChange}
|
||||
imageSrc={value || undefined}
|
||||
triggerButtonColor={showRemoveBannerButton ? "secondary" : "primary"}
|
||||
/>
|
||||
{showRemoveBannerButton && (
|
||||
<Button color="destructive" onClick={() => onChange(null)}>
|
||||
{t("remove")}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
<div className="mt-2 flex items-center">
|
||||
<Controller
|
||||
control={form.control}
|
||||
name="calVideoLogo"
|
||||
render={({ field: { value, onChange } }) => {
|
||||
const showRemoveLogoButton = !!value;
|
||||
return (
|
||||
<>
|
||||
<Avatar
|
||||
alt="calVideoLogo"
|
||||
imageSrc={value}
|
||||
fallback={<Icon name="plus" className="text-subtle h-6 w-6" />}
|
||||
size="lg"
|
||||
/>
|
||||
<div className="ms-4">
|
||||
<div className="flex gap-2">
|
||||
<ImageUploader
|
||||
target="avatar"
|
||||
id="cal-video-logo-upload"
|
||||
buttonMsg={t("upload_cal_video_logo")}
|
||||
handleAvatarChange={onChange}
|
||||
imageSrc={value || undefined}
|
||||
uploadInstruction={t("cal_video_logo_upload_instruction")}
|
||||
triggerButtonColor={showRemoveLogoButton ? "secondary" : "primary"}
|
||||
testId="cal-video-logo"
|
||||
/>
|
||||
{showRemoveLogoButton && (
|
||||
<Button color="secondary" onClick={() => onChange(null)}>
|
||||
{t("remove")}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<Controller
|
||||
control={form.control}
|
||||
name="name"
|
||||
render={({ field: { value } }) => (
|
||||
<div className="mt-8">
|
||||
<TextField
|
||||
name="name"
|
||||
label={t("organization_name")}
|
||||
value={value}
|
||||
onChange={(e) => {
|
||||
form.setValue("name", e?.target.value, { shouldDirty: true });
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
/>
|
||||
<Controller
|
||||
control={form.control}
|
||||
name="slug"
|
||||
render={({ field: { value } }) => (
|
||||
<div className="mt-8">
|
||||
<TextField
|
||||
name="slug"
|
||||
label={t("organization_url")}
|
||||
value={value}
|
||||
disabled
|
||||
addOnSuffix={`.${subdomainSuffix()}`}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
/>
|
||||
<Controller
|
||||
control={form.control}
|
||||
name="id"
|
||||
render={({ field: { value } }) => (
|
||||
<div className="mt-8">
|
||||
<TextField
|
||||
name="id"
|
||||
label={t("organization_id")}
|
||||
value={value}
|
||||
disabled={true}
|
||||
addOnSuffix={
|
||||
<Tooltip content={t("copy_to_clipboard")}>
|
||||
<Button
|
||||
color="minimal"
|
||||
size="sm"
|
||||
type="button"
|
||||
aria-label="copy organization id"
|
||||
onClick={() => handleCopy(value.toString())}>
|
||||
<Icon name="copy" className="ml-1 h-4 w-4" />
|
||||
</Button>
|
||||
</Tooltip>
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
/>
|
||||
<div className="mt-8">
|
||||
<Label>{t("about")}</Label>
|
||||
<Editor
|
||||
getText={() => md.render(form.getValues("bio") || "")}
|
||||
setText={(value: string) => form.setValue("bio", turndown(value), { shouldDirty: true })}
|
||||
excludedToolbarItems={["blockType"]}
|
||||
disableLists
|
||||
firstRender={firstRender}
|
||||
setFirstRender={setFirstRender}
|
||||
height="80px"
|
||||
/>
|
||||
</div>
|
||||
<p className="text-default mt-2 text-sm">{t("org_description")}</p>
|
||||
</div>
|
||||
<SectionBottomActions align="end">
|
||||
<Button
|
||||
data-testid="update-org-profile-button"
|
||||
color="primary"
|
||||
type="submit"
|
||||
loading={mutation.isPending}
|
||||
disabled={isDisabled}>
|
||||
{t("update")}
|
||||
</Button>
|
||||
</SectionBottomActions>
|
||||
</Form>
|
||||
);
|
||||
};
|
||||
|
||||
export default OrgProfileView;
|
||||
@@ -1,12 +1,12 @@
|
||||
"use client";
|
||||
|
||||
import { checkAdminOrOwner } from "@calcom/features/auth/lib/checkAdminOrOwner";
|
||||
import { UserListTable } from "@calcom/features/users/components/UserTable/UserListTable";
|
||||
import type { UserListTableProps } from "@calcom/features/users/components/UserTable/UserListTable";
|
||||
import { UserListTableSkeleton } from "@calcom/features/users/components/UserTable/UserListTableSkeleton";
|
||||
import NoPlatformPlan from "@calcom/web/components/settings/platform/dashboard/NoPlatformPlan";
|
||||
import { useGetUserAttributes } from "@calcom/web/components/settings/platform/hooks/useGetUserAttributes";
|
||||
import { PlatformPricing } from "@calcom/web/components/settings/platform/pricing/platform-pricing/index";
|
||||
import { UserListTable } from "@calcom/web/modules/users/components/UserTable/UserListTable";
|
||||
import type { UserListTableProps } from "@calcom/web/modules/users/components/UserTable/UserListTable";
|
||||
import { UserListTableSkeleton } from "@calcom/web/modules/users/components/UserTable/UserListTableSkeleton";
|
||||
|
||||
const PlatformMembersView = (props: Omit<UserListTableProps, "facetedTeamValues" | "attributes">) => {
|
||||
const { isUserLoading, isUserBillingDataLoading, isPlatformUser, isPaidUser, userBillingData, userOrgId } =
|
||||
|
||||
@@ -1,45 +0,0 @@
|
||||
import { useHasPaidPlan } from "@calcom/features/billing/hooks/useHasPaidPlan";
|
||||
import { JOIN_COMMUNITY } from "@calcom/lib/constants";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { UpgradeTeamsBadge } from "@calcom/ui/components/badge";
|
||||
import { Icon } from "@calcom/ui/components/icon";
|
||||
|
||||
import FreshChatMenuItem from "../lib/freshchat/FreshChatMenuItem";
|
||||
import HelpscoutMenuItem from "../lib/helpscout/HelpscoutMenuItem";
|
||||
import ZendeskMenuItem from "../lib/zendesk/ZendeskMenuItem";
|
||||
|
||||
interface ContactMenuItem {
|
||||
onHelpItemSelect: () => void;
|
||||
}
|
||||
|
||||
export default function ContactMenuItem(props: ContactMenuItem) {
|
||||
const { t } = useLocale();
|
||||
const { onHelpItemSelect } = props;
|
||||
const { hasPaidPlan } = useHasPaidPlan();
|
||||
return (
|
||||
<>
|
||||
{hasPaidPlan ? (
|
||||
<>
|
||||
<ZendeskMenuItem onHelpItemSelect={onHelpItemSelect} />
|
||||
<HelpscoutMenuItem onHelpItemSelect={onHelpItemSelect} />
|
||||
<FreshChatMenuItem onHelpItemSelect={onHelpItemSelect} />
|
||||
</>
|
||||
) : (
|
||||
<div className=" hover:text-emphasis text-default flex w-full cursor-not-allowed justify-between px-5 py-2 pr-4 text-sm font-medium">
|
||||
{t("premium_support")}
|
||||
<UpgradeTeamsBadge />
|
||||
</div>
|
||||
)}
|
||||
<a
|
||||
href={JOIN_COMMUNITY}
|
||||
target="_blank"
|
||||
className="hover:bg-subtle hover:text-emphasis text-default flex w-full px-5 py-2 pr-4 text-sm font-medium transition">
|
||||
{t("community_support")}{" "}
|
||||
<Icon
|
||||
name="external-link"
|
||||
className="group-hover:text-subtle text-muted ml-1 mt-px h-4 w-4 shrink-0 ltr:mr-3"
|
||||
/>
|
||||
</a>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -1,196 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import React, { useEffect, useState, useCallback } from "react";
|
||||
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import classNames from "@calcom/ui/classNames";
|
||||
import { Button } from "@calcom/ui/components/button";
|
||||
import { Label, TextArea } from "@calcom/ui/components/form";
|
||||
import { Icon } from "@calcom/ui/components/icon";
|
||||
import { Popover, PopoverContent, PopoverTrigger } from "@calcom/ui/components/popover";
|
||||
import { showToast } from "@calcom/ui/components/toast";
|
||||
|
||||
declare global {
|
||||
interface Window {
|
||||
Support?: {
|
||||
open: () => void;
|
||||
shouldShowTriggerButton: (showTrigger: boolean) => void;
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
export const IntercomContactForm = () => {
|
||||
const { t } = useLocale();
|
||||
const [isSubmitting, setIsSubmitting] = useState(false);
|
||||
const [isSubmitted, setIsSubmitted] = useState(false);
|
||||
const [message, setMessage] = useState("");
|
||||
const [isOpen, setIsOpen] = useState(false);
|
||||
const [showTrigger, setShowTrigger] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (typeof window !== "undefined" && !window.Support) {
|
||||
window.Support = {
|
||||
open: () => {
|
||||
setIsOpen(true);
|
||||
},
|
||||
shouldShowTriggerButton: (showTrigger) => {
|
||||
setShowTrigger(showTrigger);
|
||||
},
|
||||
};
|
||||
window.dispatchEvent(new Event("support:ready"));
|
||||
}
|
||||
|
||||
return () => {
|
||||
if (typeof window !== "undefined" && window.Support) {
|
||||
delete window.Support;
|
||||
}
|
||||
};
|
||||
}, []);
|
||||
|
||||
const onSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setIsSubmitting(true);
|
||||
|
||||
try {
|
||||
const response = await fetch("/api/support/conversation", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({ message }),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const errorData = await response.json();
|
||||
throw new Error(errorData.error || "Failed to send message");
|
||||
}
|
||||
|
||||
showToast(t("success"), "success");
|
||||
setIsSubmitting(false);
|
||||
setIsSubmitted(true);
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : t("something_went_wrong");
|
||||
showToast(message, "error");
|
||||
} finally {
|
||||
setIsSubmitting(false);
|
||||
}
|
||||
};
|
||||
|
||||
const contentRef = useCallback(
|
||||
(node: HTMLDivElement | null) => {
|
||||
if (!node) return;
|
||||
|
||||
const isSmall = window.innerWidth < 768;
|
||||
|
||||
if (isSmall) {
|
||||
setShowTrigger(false);
|
||||
}
|
||||
|
||||
const wrapper = node.parentElement;
|
||||
if (wrapper?.hasAttribute("data-radix-popper-content-wrapper")) {
|
||||
if (!showTrigger) {
|
||||
wrapper.style.left = "auto";
|
||||
wrapper.style.right = "0px";
|
||||
wrapper.style.bottom = "5rem";
|
||||
wrapper.style.top = "auto";
|
||||
} else {
|
||||
wrapper.style.left = "0px";
|
||||
wrapper.style.right = "auto";
|
||||
wrapper.style.bottom = "auto";
|
||||
wrapper.style.top = "0px";
|
||||
}
|
||||
}
|
||||
},
|
||||
[showTrigger]
|
||||
);
|
||||
|
||||
const resetForm = () => {
|
||||
setIsSubmitted(false);
|
||||
setMessage("");
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="fixed bottom-4 right-4 z-50 **:data-radix-popper-content-wrapper:bottom-4!">
|
||||
<Popover open={isOpen} onOpenChange={setIsOpen}>
|
||||
<PopoverTrigger
|
||||
asChild
|
||||
className={classNames("enabled:hover:bg-subtle bg-subtle shadow-none", !showTrigger && "hidden!")}>
|
||||
<Button
|
||||
onClick={() => setIsOpen(true)}
|
||||
className="bg-subtle text-emphasis flex h-12 w-12 items-center justify-center rounded-full border-none">
|
||||
<Icon name="message-circle" className="h-6 w-6" />
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
|
||||
<PopoverContent
|
||||
ref={contentRef}
|
||||
style={{ maxWidth: "450px", maxHeight: "650px" }}
|
||||
className={classNames(
|
||||
"!bg-cal-muted no-scrollbar mb-2 w-screen overflow-hidden overflow-y-scroll px-6 py-4 md:w-[450px]",
|
||||
showTrigger ? "mr-8" : "mr-0"
|
||||
)}>
|
||||
<div className="flex w-full justify-between">
|
||||
<p className="mb-5 text-lg font-semibold">{t("contact_support")}</p>
|
||||
<Button
|
||||
color="minimal"
|
||||
variant="button"
|
||||
StartIcon="x"
|
||||
size="sm"
|
||||
onClick={() => setIsOpen(false)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
{isSubmitted ? (
|
||||
<div className="py-4 text-center">
|
||||
<h4 className="mb-2 text-lg font-medium ">{t("message_sent")}</h4>
|
||||
<p className="text-subtle mb-4 text-sm">{t("support_message_sent_description")}</p>
|
||||
<Button color="primary" className="my-2" onClick={resetForm} variant="button" size="base">
|
||||
{t("send_another_message")}
|
||||
</Button>
|
||||
</div>
|
||||
) : (
|
||||
<form onSubmit={onSubmit} className="flex flex-col gap-4">
|
||||
<div>
|
||||
<Label htmlFor="message">{t("describe_the_issue")}</Label>
|
||||
<TextArea
|
||||
id="message"
|
||||
name="message"
|
||||
value={message}
|
||||
onChange={(e) => setMessage(e.target.value)}
|
||||
placeholder={t("support_message_placeholder")}
|
||||
required
|
||||
rows={4}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="mt-4 flex w-full items-center">
|
||||
<Button
|
||||
color="secondary"
|
||||
variant="button"
|
||||
type="submit"
|
||||
disabled={isSubmitting}
|
||||
className="w-full">
|
||||
<div className="flex w-full justify-center">
|
||||
{isSubmitting ? (
|
||||
<div className="flex items-center">
|
||||
<Icon name="loader" className="mr-2 h-4 w-4 animate-spin rounded-full" />
|
||||
{t("sending")}
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<Icon name="send" className="mr-2 h-4 w-4" />
|
||||
{t("send_message")}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
)}
|
||||
</div>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -1,30 +0,0 @@
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
|
||||
import { useFreshChat } from "./FreshChatProvider";
|
||||
import { isFreshChatEnabled } from "./FreshChatScript";
|
||||
|
||||
interface FreshChatMenuItemProps {
|
||||
onHelpItemSelect: () => void;
|
||||
}
|
||||
|
||||
export default function FreshChatMenuItem(props: FreshChatMenuItemProps) {
|
||||
const { onHelpItemSelect } = props;
|
||||
const { t } = useLocale();
|
||||
|
||||
const { setActive } = useFreshChat();
|
||||
|
||||
if (!isFreshChatEnabled) return null;
|
||||
|
||||
return (
|
||||
<>
|
||||
<button
|
||||
onClick={() => {
|
||||
setActive(true);
|
||||
onHelpItemSelect();
|
||||
}}
|
||||
className="hover:bg-subtle hover:text-emphasis text-default flex w-full px-5 py-2 pr-4 text-sm font-medium transition">
|
||||
{t("contact_support")}
|
||||
</button>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -1,25 +0,0 @@
|
||||
import type { ReactNode, Dispatch, SetStateAction } from "react";
|
||||
import { createContext, useState, useContext } from "react";
|
||||
|
||||
import FreshChatScript from "./FreshChatScript";
|
||||
|
||||
type FreshChatContextType = { active: boolean; setActive: Dispatch<SetStateAction<boolean>> };
|
||||
|
||||
const FreshChatContext = createContext<FreshChatContextType>({ active: false, setActive: () => undefined });
|
||||
|
||||
interface FreshChatProviderProps {
|
||||
children: ReactNode;
|
||||
}
|
||||
|
||||
export const useFreshChat = () => useContext(FreshChatContext);
|
||||
|
||||
export default function FreshChatProvider(props: FreshChatProviderProps) {
|
||||
const [active, setActive] = useState(false);
|
||||
|
||||
return (
|
||||
<FreshChatContext.Provider value={{ active, setActive }}>
|
||||
{props.children}
|
||||
{active && <FreshChatScript />}
|
||||
</FreshChatContext.Provider>
|
||||
);
|
||||
}
|
||||
@@ -1,43 +0,0 @@
|
||||
import Script from "next/script";
|
||||
import { z } from "zod";
|
||||
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
|
||||
const nonEmptySchema = z.string().min(1);
|
||||
declare global {
|
||||
interface Window {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
fcWidget: any;
|
||||
}
|
||||
}
|
||||
|
||||
// eslint-disable-next-line turbo/no-undeclared-env-vars
|
||||
const host = process.env.NEXT_PUBLIC_FRESHCHAT_HOST;
|
||||
// eslint-disable-next-line turbo/no-undeclared-env-vars
|
||||
const token = process.env.NEXT_PUBLIC_FRESHCHAT_TOKEN;
|
||||
|
||||
export const isFreshChatEnabled =
|
||||
nonEmptySchema.safeParse(host).success && nonEmptySchema.safeParse(token).success;
|
||||
|
||||
export default function FreshChatScript() {
|
||||
const { data } = trpc.viewer.me.get.useQuery();
|
||||
return (
|
||||
<Script
|
||||
id="fresh-chat-sdk"
|
||||
src="https://wchat.freshchat.com/js/widget.js"
|
||||
onLoad={() => {
|
||||
window.fcWidget.init({
|
||||
token,
|
||||
host,
|
||||
externalId: data?.id,
|
||||
lastName: data?.name,
|
||||
email: data?.email,
|
||||
meta: {
|
||||
username: data?.username,
|
||||
},
|
||||
open: true,
|
||||
});
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -1,37 +0,0 @@
|
||||
import { useState } from "react";
|
||||
import { HelpScout, useChat } from "react-live-chat-loader";
|
||||
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
|
||||
interface HelpscoutMenuItemProps {
|
||||
onHelpItemSelect: () => void;
|
||||
}
|
||||
|
||||
export default function HelpscoutMenuItem(props: HelpscoutMenuItemProps) {
|
||||
const { onHelpItemSelect } = props;
|
||||
const { t } = useLocale();
|
||||
const [active, setActive] = useState(false);
|
||||
|
||||
const [, loadChat] = useChat();
|
||||
|
||||
function handleClick() {
|
||||
setActive(true);
|
||||
loadChat({ open: true });
|
||||
onHelpItemSelect();
|
||||
}
|
||||
|
||||
// eslint-disable-next-line turbo/no-undeclared-env-vars
|
||||
if (!process.env.NEXT_PUBLIC_HELPSCOUT_KEY) return null;
|
||||
|
||||
return (
|
||||
<>
|
||||
<button
|
||||
onClick={handleClick}
|
||||
className="hover:bg-subtle hover:text-emphasis text-default flex w-full px-5 py-2 pr-4 text-sm font-medium transition">
|
||||
{t("contact_support")}
|
||||
</button>
|
||||
|
||||
{active && <HelpScout color="#292929" icon="message" horizontalPosition="right" zIndex="1" />}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
import { FC } from "react";
|
||||
import { LiveChatLoaderProvider } from "react-live-chat-loader";
|
||||
|
||||
const Provider: FC<{ children: React.ReactNode }> = ({ children }) => (
|
||||
<LiveChatLoaderProvider providerKey={process.env.NEXT_PUBLIC_HELPSCOUT_KEY || ""} provider="helpScout">
|
||||
<>{children}</>
|
||||
</LiveChatLoaderProvider>
|
||||
);
|
||||
|
||||
export default Provider;
|
||||
@@ -1,8 +0,0 @@
|
||||
import dynamic from "next/dynamic";
|
||||
import { Fragment } from "react";
|
||||
|
||||
const DynamicHelpscoutProvider = process.env.NEXT_PUBLIC_HELPSCOUT_KEY
|
||||
? dynamic(() => import("./provider"))
|
||||
: Fragment;
|
||||
|
||||
export default DynamicHelpscoutProvider;
|
||||
@@ -1,142 +0,0 @@
|
||||
import { safeStringify } from "@calcom/lib/safeStringify";
|
||||
|
||||
export interface Contact extends CreateContact {
|
||||
id: string;
|
||||
}
|
||||
|
||||
interface CreateContact {
|
||||
type: "contact" | "lead";
|
||||
external_id: string;
|
||||
email: string;
|
||||
name: string;
|
||||
custom_attributes?: object;
|
||||
}
|
||||
|
||||
interface IntercomResponse<T> {
|
||||
data?: T;
|
||||
error?: string;
|
||||
}
|
||||
|
||||
interface CreateConversation {
|
||||
from: {
|
||||
type: string;
|
||||
id: string;
|
||||
};
|
||||
body: string;
|
||||
}
|
||||
|
||||
const INTERCOM_API_ENDPOINT = "https://api.intercom.io";
|
||||
const INTERCOM_API_TOKEN = process.env.INTERCOM_API_TOKEN;
|
||||
export const intercom = {
|
||||
async getContactByEmail(email: string): Promise<IntercomResponse<Contact | null>> {
|
||||
try {
|
||||
const res = await fetch(`${INTERCOM_API_ENDPOINT}/contacts/search`, {
|
||||
method: "POST",
|
||||
body: JSON.stringify({
|
||||
query: {
|
||||
operator: "AND",
|
||||
value: [
|
||||
{
|
||||
field: "email",
|
||||
operator: "=",
|
||||
value: email,
|
||||
},
|
||||
],
|
||||
},
|
||||
pagination: {
|
||||
per_page: 1,
|
||||
},
|
||||
}),
|
||||
headers: {
|
||||
Authorization: `Bearer ${INTERCOM_API_TOKEN}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
const body = await res.json();
|
||||
return {
|
||||
error: body?.errors[0]?.message,
|
||||
};
|
||||
}
|
||||
|
||||
const { data } = (await res.json()) as { type: string; data: Contact[] };
|
||||
|
||||
if (data.length === 0) {
|
||||
return {
|
||||
data: null,
|
||||
};
|
||||
}
|
||||
return {
|
||||
data: data[0],
|
||||
};
|
||||
} catch (err) {
|
||||
console.error(`Unexpected error while fetching contact data from email: ${safeStringify(err)}`);
|
||||
return {
|
||||
error: "Unexpected error while fetching contact data from email",
|
||||
};
|
||||
}
|
||||
},
|
||||
async createContact(data: CreateContact): Promise<IntercomResponse<Contact>> {
|
||||
try {
|
||||
const res = await fetch(`${INTERCOM_API_ENDPOINT}/contacts`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
Authorization: `Bearer ${INTERCOM_API_TOKEN}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify(data),
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
const data = await res.json();
|
||||
console.error(`Error creating contact from email ${data.email}: `, safeStringify(data));
|
||||
return {
|
||||
error: data?.errors[0]?.message ?? "Error creating contact from email",
|
||||
};
|
||||
}
|
||||
|
||||
const contact = (await res.json()) as Contact;
|
||||
return {
|
||||
data: contact,
|
||||
};
|
||||
} catch (err) {
|
||||
console.error(`Unexpected error while creating contact from email: ${safeStringify(err)}`);
|
||||
return {
|
||||
error: "Unexpected error while creating contact from email",
|
||||
};
|
||||
}
|
||||
},
|
||||
async createConversation({ from, body }: CreateConversation): Promise<IntercomResponse<boolean>> {
|
||||
try {
|
||||
const response = await fetch(`https://api.intercom.io/conversations`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
Authorization: `Bearer ${INTERCOM_API_TOKEN}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
from,
|
||||
body,
|
||||
}),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const errorData = await response.json();
|
||||
console.error("Intercom API error:", safeStringify(errorData));
|
||||
return {
|
||||
error: `Intercom Err: ${errorData?.errors?.[0].message ?? "Error creating conversation"}`,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
data: true,
|
||||
};
|
||||
} catch (err) {
|
||||
console.error(`Unexpected error while creating conversation from email: ${safeStringify(err)}`);
|
||||
return {
|
||||
error: "Unexpected error while creating contact from email",
|
||||
};
|
||||
}
|
||||
},
|
||||
};
|
||||
@@ -1,93 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { useSession } from "next-auth/react";
|
||||
import { usePathname, useRouter, useSearchParams } from "next/navigation";
|
||||
import { useEffect, type FC } from "react";
|
||||
import { IntercomProvider } from "react-use-intercom";
|
||||
|
||||
import { useBootIntercom } from "@calcom/ee/support/lib/intercom/useIntercom";
|
||||
import useHasPaidPlan from "@calcom/features/billing/hooks/useHasPaidPlan";
|
||||
import { IntercomContactForm } from "@calcom/features/ee/support/components/IntercomContactForm";
|
||||
import { useFlagMap } from "@calcom/features/flags/context/provider";
|
||||
import useMediaQuery from "@calcom/lib/hooks/useMediaQuery";
|
||||
|
||||
declare global {
|
||||
interface Window {
|
||||
Support?: {
|
||||
open: () => void;
|
||||
shouldShowTriggerButton: (showTrigger: boolean) => void;
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
function IntercomBootstrap() {
|
||||
useBootIntercom();
|
||||
return null;
|
||||
}
|
||||
|
||||
const Provider: FC<{ children: React.ReactNode }> = ({ children }) => {
|
||||
const { hasPaidPlan } = useHasPaidPlan();
|
||||
const isMobile = useMediaQuery("(max-width: 768px)");
|
||||
const flagMap = useFlagMap();
|
||||
const searchParams = useSearchParams();
|
||||
const pathname = usePathname();
|
||||
const router = useRouter();
|
||||
const { data: session } = useSession();
|
||||
|
||||
const isBeingImpersonated = !!session?.user?.impersonatedBy?.id;
|
||||
|
||||
const shouldOpenSupport =
|
||||
pathname === "/event-types" && (searchParams?.has("openPlain") || searchParams?.has("openSupport"));
|
||||
|
||||
useEffect(() => {
|
||||
const handleSupportReady = () => {
|
||||
if (window.Support) {
|
||||
window.Support.shouldShowTriggerButton?.(!isMobile);
|
||||
|
||||
if (shouldOpenSupport) {
|
||||
window.Support.open();
|
||||
const url = new URL(window.location.href);
|
||||
url.searchParams.delete("openPlain");
|
||||
url.searchParams.delete("openSupport");
|
||||
router.replace(url.pathname + url.search);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
if (window.Support) {
|
||||
handleSupportReady();
|
||||
} else {
|
||||
window.addEventListener("support:ready", handleSupportReady);
|
||||
}
|
||||
|
||||
return () => {
|
||||
window.removeEventListener("support:ready", handleSupportReady);
|
||||
};
|
||||
//eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [shouldOpenSupport, isMobile]);
|
||||
|
||||
const isOnboardingPage = pathname?.startsWith("/getting-started");
|
||||
const isCalVideoPage = pathname?.startsWith("/video/");
|
||||
|
||||
if (isOnboardingPage || isCalVideoPage || isBeingImpersonated) {
|
||||
return <>{children}</>;
|
||||
}
|
||||
|
||||
if (flagMap["tiered-support-chat"] && !hasPaidPlan) {
|
||||
return (
|
||||
<>
|
||||
{children}
|
||||
<IntercomContactForm />
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<IntercomProvider appId={process.env.NEXT_PUBLIC_INTERCOM_APP_ID || ""}>
|
||||
<IntercomBootstrap />
|
||||
{children}
|
||||
</IntercomProvider>
|
||||
);
|
||||
};
|
||||
|
||||
export default Provider;
|
||||
@@ -1,8 +0,0 @@
|
||||
import dynamic from "next/dynamic";
|
||||
import { Fragment } from "react";
|
||||
|
||||
const DynamicIntercomProvider = process.env.NEXT_PUBLIC_INTERCOM_APP_ID
|
||||
? dynamic(() => import("./provider"), { ssr: false })
|
||||
: Fragment;
|
||||
|
||||
export default DynamicIntercomProvider;
|
||||
@@ -1,187 +0,0 @@
|
||||
import { noop } from "lodash";
|
||||
import { useEffect } from "react";
|
||||
import type { IntercomBootProps, IntercomProps } from "react-use-intercom";
|
||||
import { useIntercom as useIntercomLib } from "react-use-intercom";
|
||||
import { z } from "zod";
|
||||
|
||||
import dayjs from "@calcom/dayjs";
|
||||
import { useHasTeamPlan, useHasPaidPlan } from "@calcom/features/billing/hooks/useHasPaidPlan";
|
||||
import { useFlagMap } from "@calcom/features/flags/context/provider";
|
||||
import { WEBAPP_URL, WEBSITE_URL } from "@calcom/lib/constants";
|
||||
import useMediaQuery from "@calcom/lib/hooks/useMediaQuery";
|
||||
import { localStorage } from "@calcom/lib/webstorage";
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
|
||||
export const isInterComEnabled = z.string().min(1).safeParse(process.env.NEXT_PUBLIC_INTERCOM_APP_ID).success;
|
||||
|
||||
const useIntercomHook = isInterComEnabled
|
||||
? useIntercomLib
|
||||
: () => {
|
||||
return {
|
||||
boot: (_props: IntercomBootProps) => {},
|
||||
show: noop,
|
||||
shutdown: noop,
|
||||
update: (_props: Partial<IntercomProps>) => {},
|
||||
};
|
||||
};
|
||||
|
||||
export const useIntercom = () => {
|
||||
const hookData = useIntercomHook();
|
||||
const isMobile = useMediaQuery("(max-width: 768px)");
|
||||
const { data } = trpc.viewer.me.get.useQuery();
|
||||
const { data: statsData } = trpc.viewer.me.myStats.useQuery(undefined, {
|
||||
trpc: {
|
||||
context: {
|
||||
skipBatch: true,
|
||||
},
|
||||
},
|
||||
});
|
||||
const { hasPaidPlan, plan } = useHasPaidPlan();
|
||||
const { hasTeamPlan } = useHasTeamPlan();
|
||||
|
||||
const boot = async () => {
|
||||
if (!data || !statsData) return;
|
||||
let userHash;
|
||||
const req = await fetch(`/api/support/hash`);
|
||||
const res = await req.json();
|
||||
if (res?.hash) {
|
||||
userHash = res.hash;
|
||||
}
|
||||
|
||||
hookData.boot({
|
||||
...(data && data?.name && { name: data.name }),
|
||||
...(data && data?.email && { email: data.email }),
|
||||
...(data && data?.id && { userId: data.id }),
|
||||
createdAt: String(dayjs(data?.createdDate).unix()),
|
||||
zIndex: 10,
|
||||
...(userHash && { userHash }),
|
||||
hideDefaultLauncher: isMobile,
|
||||
customAttributes: {
|
||||
//keys should be snake cased
|
||||
user_name: data?.username,
|
||||
link: `${WEBSITE_URL}/${data?.username}`,
|
||||
admin_link: `${WEBAPP_URL}/settings/admin/users/${data?.id}/edit`,
|
||||
impersonate_user: `${WEBAPP_URL}/settings/admin/impersonation?username=${
|
||||
data?.email ?? data?.username
|
||||
}`,
|
||||
identity_provider: data?.identityProvider,
|
||||
timezone: data?.timeZone,
|
||||
locale: data?.locale,
|
||||
has_paid_plan: hasPaidPlan,
|
||||
has_team_plan: hasTeamPlan,
|
||||
metadata: data?.metadata,
|
||||
completed_onboarding: data.completedOnboarding,
|
||||
is_logged_in: !!data,
|
||||
sum_of_bookings: statsData?.sumOfBookings,
|
||||
sum_of_calendars: statsData?.sumOfCalendars,
|
||||
sum_of_teams: statsData?.sumOfTeams,
|
||||
has_orgs_plan: !!data?.organizationId,
|
||||
organization: data?.organization?.slug,
|
||||
sum_of_event_types: statsData?.sumOfEventTypes,
|
||||
sum_of_team_event_types: statsData?.sumOfTeamEventTypes,
|
||||
is_premium: data?.isPremium,
|
||||
Plan: plan,
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
const open = async () => {
|
||||
let userHash;
|
||||
|
||||
const req = await fetch(`/api/support/hash`);
|
||||
const res = await req.json();
|
||||
if (res?.hash) {
|
||||
userHash = res.hash;
|
||||
}
|
||||
|
||||
hookData.boot({
|
||||
...(data && data?.name && { name: data.name }),
|
||||
...(data && data?.email && { email: data.email }),
|
||||
...(data && data?.id && { userId: data.id }),
|
||||
createdAt: String(dayjs(data?.createdDate).unix()),
|
||||
...(userHash && { userHash }),
|
||||
hideDefaultLauncher: isMobile,
|
||||
zIndex: 10,
|
||||
customAttributes: {
|
||||
//keys should be snake cased
|
||||
user_name: data?.username,
|
||||
link: `${WEBSITE_URL}/${data?.username}`,
|
||||
admin_link: `${WEBAPP_URL}/settings/admin/users/${data?.id}/edit`,
|
||||
impersonate_user: `${WEBAPP_URL}/settings/admin/impersonation?username=${
|
||||
data?.email ?? data?.username
|
||||
}`,
|
||||
identity_provider: data?.identityProvider,
|
||||
timezone: data?.timeZone,
|
||||
locale: data?.locale,
|
||||
has_paid_plan: hasPaidPlan,
|
||||
has_team_plan: hasTeamPlan,
|
||||
metadata: data?.metadata,
|
||||
completed_onboarding: data?.completedOnboarding,
|
||||
is_logged_in: !!data,
|
||||
sum_of_bookings: statsData?.sumOfBookings,
|
||||
sum_of_calendars: statsData?.sumOfCalendars,
|
||||
sum_of_teams: statsData?.sumOfTeams,
|
||||
has_orgs_plan: !!data?.organizationId,
|
||||
organization: data?.organization?.slug,
|
||||
sum_of_event_types: statsData?.sumOfEventTypes,
|
||||
sum_of_team_event_types: statsData?.sumOfTeamEventTypes,
|
||||
is_premium: data?.isPremium,
|
||||
Plan: plan,
|
||||
},
|
||||
});
|
||||
hookData.show();
|
||||
};
|
||||
return { ...hookData, open, boot };
|
||||
};
|
||||
|
||||
declare global {
|
||||
interface Window {
|
||||
Support?: {
|
||||
open: () => void;
|
||||
shouldShowTriggerButton: (showTrigger: boolean) => void;
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
export const useBootIntercom = () => {
|
||||
const { hasPaidPlan } = useHasPaidPlan();
|
||||
const flagMap = useFlagMap();
|
||||
const { boot, open, update } = useIntercom();
|
||||
|
||||
const { data: user } = trpc.viewer.me.get.useQuery();
|
||||
const isTieredSupportEnabled = flagMap["tiered-support-chat"];
|
||||
const { data: statsData } = trpc.viewer.me.myStats.useQuery(undefined, {
|
||||
trpc: {
|
||||
context: {
|
||||
skipBatch: true,
|
||||
},
|
||||
},
|
||||
});
|
||||
useEffect(() => {
|
||||
// not using useMediaQuery as it toggles between true and false
|
||||
const showIntercom = localStorage.getItem("showIntercom");
|
||||
if (
|
||||
!isInterComEnabled ||
|
||||
showIntercom === "false" ||
|
||||
!user ||
|
||||
!statsData ||
|
||||
(!hasPaidPlan && isTieredSupportEnabled)
|
||||
)
|
||||
return;
|
||||
|
||||
boot();
|
||||
if (typeof window !== "undefined" && !window.Support) {
|
||||
window.Support = {
|
||||
open,
|
||||
shouldShowTriggerButton: (showTrigger: boolean) => {
|
||||
update({
|
||||
hideDefaultLauncher: !showTrigger,
|
||||
});
|
||||
},
|
||||
};
|
||||
window.dispatchEvent(new Event("support:ready"));
|
||||
}
|
||||
}, [user, statsData, hasPaidPlan, isTieredSupportEnabled]);
|
||||
};
|
||||
|
||||
export default useIntercom;
|
||||
@@ -1,35 +0,0 @@
|
||||
import Script from "next/script";
|
||||
import { useState } from "react";
|
||||
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
|
||||
// eslint-disable-next-line turbo/no-undeclared-env-vars
|
||||
const ZENDESK_KEY = process.env.NEXT_PUBLIC_ZENDESK_KEY;
|
||||
|
||||
interface ZendeskMenuItemProps {
|
||||
onHelpItemSelect: () => void;
|
||||
}
|
||||
|
||||
export default function ZendeskMenuItem(props: ZendeskMenuItemProps) {
|
||||
const { onHelpItemSelect } = props;
|
||||
const [active, setActive] = useState(false);
|
||||
const { t } = useLocale();
|
||||
|
||||
if (!ZENDESK_KEY) return null;
|
||||
|
||||
return (
|
||||
<>
|
||||
<button
|
||||
onClick={() => {
|
||||
setActive(true);
|
||||
onHelpItemSelect();
|
||||
}}
|
||||
className="hover:bg-subtle hover:text-emphasis text-default flex w-full px-5 py-2 pr-4 text-sm font-medium transition">
|
||||
{t("contact_support")}
|
||||
</button>
|
||||
{active && (
|
||||
<Script id="ze-snippet" src={`https://static.zdassets.com/ekr/snippet.js?key=${ZENDESK_KEY}`} />
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -1,265 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { keepPreviousData } from "@tanstack/react-query";
|
||||
import { useSession } from "next-auth/react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useState, useMemo } from "react";
|
||||
import posthog from "posthog-js";
|
||||
|
||||
import { checkAdminOrOwner } from "@calcom/features/auth/lib/checkAdminOrOwner";
|
||||
import { useOrgBranding } from "@calcom/features/ee/organizations/context/provider";
|
||||
import InviteLinkSettingsModal from "@calcom/features/ee/teams/components/InviteLinkSettingsModal";
|
||||
import { MemberInvitationModalWithoutMembers } from "@calcom/features/ee/teams/components/MemberInvitationModal";
|
||||
import { APP_NAME } from "@calcom/lib/constants";
|
||||
import { useCompatSearchParams } from "@calcom/lib/hooks/useCompatSearchParams";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { MembershipRole } from "@calcom/prisma/enums";
|
||||
import type { RouterOutputs } from "@calcom/trpc/react";
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
import classNames from "@calcom/ui/classNames";
|
||||
import { UserAvatar } from "@calcom/ui/components/avatar";
|
||||
import { Badge } from "@calcom/ui/components/badge";
|
||||
import { Button } from "@calcom/ui/components/button";
|
||||
import { SkeletonButton, SkeletonContainer, SkeletonText } from "@calcom/ui/components/skeleton";
|
||||
import { showToast } from "@calcom/ui/components/toast";
|
||||
|
||||
type TeamMember = RouterOutputs["viewer"]["teams"]["listMembers"]["members"][number];
|
||||
|
||||
const AddNewTeamMembers = ({ isOrg = false }: { isOrg?: boolean }) => {
|
||||
const searchParams = useCompatSearchParams();
|
||||
const session = useSession();
|
||||
|
||||
const teamId = searchParams?.get("id") ? Number(searchParams.get("id")) : -1;
|
||||
const teamQuery = trpc.viewer.teams.get.useQuery(
|
||||
{ teamId, isOrg },
|
||||
{ enabled: session.status === "authenticated" }
|
||||
);
|
||||
|
||||
if (session.status === "loading" || !teamQuery.data) return <AddNewTeamMemberSkeleton />;
|
||||
|
||||
return <AddNewTeamMembersForm teamId={teamId} isOrg={isOrg} />;
|
||||
};
|
||||
|
||||
export const AddNewTeamMembersForm = ({ teamId, isOrg }: { teamId: number; isOrg?: boolean }) => {
|
||||
const searchParams = useCompatSearchParams();
|
||||
const { t } = useLocale();
|
||||
|
||||
const router = useRouter();
|
||||
const orgBranding = useOrgBranding();
|
||||
|
||||
const showDialog = searchParams?.get("inviteModal") === "true";
|
||||
const [memberInviteModal, setMemberInviteModal] = useState(showDialog);
|
||||
const [inviteLinkSettingsModal, setInviteLinkSettingsModal] = useState(false);
|
||||
|
||||
const { data: team, isPending } = trpc.viewer.teams.get.useQuery({ teamId, isOrg }, { enabled: !!teamId });
|
||||
const { data: orgMembersNotInThisTeam } = trpc.viewer.organizations.getMembers.useQuery(
|
||||
{
|
||||
teamIdToExclude: teamId,
|
||||
distinctUser: true,
|
||||
},
|
||||
{
|
||||
enabled: orgBranding !== null,
|
||||
}
|
||||
);
|
||||
|
||||
const { data, fetchNextPage, isFetchingNextPage, hasNextPage } =
|
||||
trpc.viewer.teams.listMembers.useInfiniteQuery(
|
||||
{
|
||||
limit: 10,
|
||||
teamId,
|
||||
},
|
||||
{
|
||||
enabled: !!teamId,
|
||||
getNextPageParam: (lastPage) => lastPage.nextCursor,
|
||||
placeholderData: keepPreviousData,
|
||||
refetchOnWindowFocus: true,
|
||||
refetchOnMount: true,
|
||||
staleTime: 0,
|
||||
}
|
||||
);
|
||||
|
||||
const flatData = useMemo(() => data?.pages?.flatMap((page) => page.members) ?? [], [data]) as TeamMember[];
|
||||
const totalFetched = flatData.length;
|
||||
|
||||
const publishTeamMutation = trpc.viewer.teams.publish.useMutation({
|
||||
onSuccess(data) {
|
||||
router.push(data.url);
|
||||
},
|
||||
onError: (error) => {
|
||||
showToast(error.message, "error");
|
||||
},
|
||||
});
|
||||
|
||||
return (
|
||||
<>
|
||||
<div>
|
||||
<ul className="border-subtle rounded-md border" data-testid="pending-member-list">
|
||||
{flatData.map((member, index) => (
|
||||
<PendingMemberItem
|
||||
key={member.email}
|
||||
member={member}
|
||||
index={index}
|
||||
teamId={teamId}
|
||||
isOrg={isOrg}
|
||||
/>
|
||||
))}
|
||||
</ul>
|
||||
{totalFetched > 0 && (
|
||||
<div className="text-default text-center">
|
||||
<Button
|
||||
color="minimal"
|
||||
loading={isFetchingNextPage}
|
||||
disabled={!hasNextPage}
|
||||
onClick={() => fetchNextPage()}>
|
||||
{hasNextPage ? t("load_more_results") : t("no_more_results")}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
<Button
|
||||
color="secondary"
|
||||
data-testid="new-member-button"
|
||||
StartIcon="plus"
|
||||
onClick={() => setMemberInviteModal(true)}
|
||||
className={classNames("w-full justify-center", totalFetched > 0 && "mt-6")}>
|
||||
{isOrg ? t("add_org_members") : t("add_team_member")}
|
||||
</Button>
|
||||
</div>
|
||||
{isPending ? (
|
||||
<SkeletonButton />
|
||||
) : (
|
||||
<>
|
||||
<MemberInvitationModalWithoutMembers
|
||||
showMemberInvitationModal={memberInviteModal}
|
||||
orgMembers={orgMembersNotInThisTeam}
|
||||
teamId={teamId}
|
||||
token={team?.inviteToken?.token}
|
||||
hideInvitationModal={() => setMemberInviteModal(false)}
|
||||
onSettingsOpen={() => {
|
||||
setMemberInviteModal(false);
|
||||
setInviteLinkSettingsModal(true);
|
||||
}}
|
||||
/>
|
||||
{team?.inviteToken && (
|
||||
<InviteLinkSettingsModal
|
||||
isOpen={inviteLinkSettingsModal}
|
||||
teamId={team.id}
|
||||
token={team.inviteToken?.token}
|
||||
expiresInDays={team.inviteToken?.expiresInDays || undefined}
|
||||
onExit={() => {
|
||||
setInviteLinkSettingsModal(false);
|
||||
setMemberInviteModal(true);
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
<hr className="border-subtle my-6" />
|
||||
<Button
|
||||
data-testid="publish-button"
|
||||
EndIcon={!orgBranding || isOrg ? "arrow-right" : undefined}
|
||||
color="primary"
|
||||
className="w-full justify-center"
|
||||
disabled={publishTeamMutation.isPending}
|
||||
onClick={() => {
|
||||
posthog.capture("onboard_members_continue_clicked", {
|
||||
team_id: teamId,
|
||||
is_org: isOrg,
|
||||
members_count: totalFetched,
|
||||
});
|
||||
let uri = `/settings/teams/${teamId}/event-type`;
|
||||
if (isOrg) {
|
||||
uri = `/settings/organizations/${teamId}/add-teams`;
|
||||
}
|
||||
router.push(uri);
|
||||
}}>
|
||||
{t("continue")}
|
||||
</Button>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export default AddNewTeamMembers;
|
||||
|
||||
const AddNewTeamMemberSkeleton = () => {
|
||||
return (
|
||||
<SkeletonContainer className="border-subtle rounded-md border">
|
||||
<div className="flex w-full justify-between p-4">
|
||||
<div>
|
||||
<p className="text-emphasis text-sm font-medium">
|
||||
<SkeletonText className="h-4 w-56" />
|
||||
</p>
|
||||
<div className="mt-2.5 w-max">
|
||||
<SkeletonText className="h-5 w-28" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</SkeletonContainer>
|
||||
);
|
||||
};
|
||||
|
||||
const PendingMemberItem = (props: { member: TeamMember; index: number; teamId: number; isOrg?: boolean }) => {
|
||||
const { member, index, teamId } = props;
|
||||
const { t } = useLocale();
|
||||
const utils = trpc.useUtils();
|
||||
const session = useSession();
|
||||
const isAdminOrOwner = checkAdminOrOwner(session.data?.user?.org?.role);
|
||||
const bookerUrl = member.bookerUrl;
|
||||
const removeMemberMutation = trpc.viewer.teams.removeMember.useMutation({
|
||||
async onSuccess() {
|
||||
await utils.viewer.teams.get.invalidate();
|
||||
await utils.viewer.teams.listMembers.invalidate();
|
||||
await utils.viewer.eventTypes.invalidate();
|
||||
showToast(t("member_removed"), "success");
|
||||
},
|
||||
async onError(err) {
|
||||
showToast(err.message, "error");
|
||||
},
|
||||
});
|
||||
|
||||
return (
|
||||
<li
|
||||
key={member.email}
|
||||
className={classNames(
|
||||
"flex items-center justify-between p-6 text-sm",
|
||||
index !== 0 && "border-subtle border-t"
|
||||
)}
|
||||
data-testid="pending-member-item">
|
||||
<div className="mr-4 flex max-w-full space-x-2 overflow-hidden rtl:space-x-reverse">
|
||||
<UserAvatar size="mdLg" user={member} />
|
||||
<div className="max-w-full overflow-hidden">
|
||||
<div className="flex space-x-1">
|
||||
<p>{member.name || member.email || t("team_member")}</p>
|
||||
{/* Assume that the first member of the team is the creator */}
|
||||
{member.id === session.data?.user.id && <Badge variant="green">{t("you")}</Badge>}
|
||||
{!member.accepted && <Badge variant="orange">{t("pending")}</Badge>}
|
||||
{member.role === MembershipRole.MEMBER && <Badge variant="gray">{t("member")}</Badge>}
|
||||
|
||||
{member.role === MembershipRole.ADMIN && <Badge variant="gray">{t("admin")}</Badge>}
|
||||
{member.role === MembershipRole.OWNER && <Badge variant="gray">{t("owner")}</Badge>}
|
||||
</div>
|
||||
{member.username ? (
|
||||
<p className="text-default truncate">{`${bookerUrl}/${member.username}`}</p>
|
||||
) : (
|
||||
<p className="text-default truncate">{t("not_on_cal", { appName: APP_NAME })}</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
{(member.role !== "OWNER" || isAdminOrOwner) && member.id !== session.data?.user.id && (
|
||||
<Button
|
||||
data-testid="remove-member-button"
|
||||
StartIcon="trash-2"
|
||||
variant="icon"
|
||||
color="secondary"
|
||||
className="h-[36px] w-[36px]"
|
||||
onClick={() => {
|
||||
removeMemberMutation.mutate({
|
||||
teamIds: [teamId],
|
||||
memberIds: [member.id],
|
||||
isOrg: !!props.isOrg,
|
||||
});
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</li>
|
||||
);
|
||||
};
|
||||
@@ -1,180 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { Controller, useForm } from "react-hook-form";
|
||||
import posthog from "posthog-js";
|
||||
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import slugify from "@calcom/lib/slugify";
|
||||
import type { RouterOutputs } from "@calcom/trpc/react";
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
import { Alert } from "@calcom/ui/components/alert";
|
||||
import { Button } from "@calcom/ui/components/button";
|
||||
import { DialogFooter } from "@calcom/ui/components/dialog";
|
||||
import { Form } from "@calcom/ui/components/form";
|
||||
import { TextField } from "@calcom/ui/components/form";
|
||||
import { revalidateEventTypesList } from "@calcom/web/app/(use-page-wrapper)/(main-nav)/event-types/actions";
|
||||
import { revalidateTeamsList } from "@calcom/web/app/(use-page-wrapper)/(main-nav)/teams/actions";
|
||||
|
||||
import { useOrgBranding } from "../../organizations/context/provider";
|
||||
import { subdomainSuffix } from "../../organizations/lib/orgDomains";
|
||||
import type { NewTeamFormValues } from "../lib/types";
|
||||
|
||||
interface CreateANewTeamFormProps {
|
||||
onCancel: () => void;
|
||||
submitLabel: string;
|
||||
onSuccess: (data: RouterOutputs["viewer"]["teams"]["create"]) => void;
|
||||
inDialog?: boolean;
|
||||
slug?: string;
|
||||
}
|
||||
|
||||
export const CreateANewTeamForm = (props: CreateANewTeamFormProps) => {
|
||||
const { inDialog, onCancel, slug, submitLabel, onSuccess } = props;
|
||||
const { t, isLocaleReady } = useLocale();
|
||||
const [serverErrorMessage, setServerErrorMessage] = useState<string | null>(null);
|
||||
const orgBranding = useOrgBranding();
|
||||
|
||||
const newTeamFormMethods = useForm<NewTeamFormValues>({
|
||||
defaultValues: {
|
||||
slug,
|
||||
},
|
||||
});
|
||||
|
||||
const utils = trpc.useUtils();
|
||||
|
||||
const createTeamMutation = trpc.viewer.teams.create.useMutation({
|
||||
onSuccess: async (data) => {
|
||||
await utils.viewer.eventTypes.getUserEventGroups.invalidate();
|
||||
revalidateEventTypesList();
|
||||
revalidateTeamsList();
|
||||
onSuccess(data);
|
||||
},
|
||||
|
||||
onError: (err) => {
|
||||
if (err.message === "team_url_taken") {
|
||||
newTeamFormMethods.setError("slug", { type: "custom", message: t("url_taken") });
|
||||
} else {
|
||||
setServerErrorMessage(err.message);
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
const FormButtons = () => (
|
||||
<>
|
||||
<Button
|
||||
disabled={createTeamMutation.isPending}
|
||||
color="secondary"
|
||||
onClick={onCancel}
|
||||
className="w-full justify-center">
|
||||
{t("cancel")}
|
||||
</Button>
|
||||
<Button
|
||||
disabled={newTeamFormMethods.formState.isSubmitting || createTeamMutation.isPending}
|
||||
color="primary"
|
||||
EndIcon="arrow-right"
|
||||
type="submit"
|
||||
className="w-full justify-center"
|
||||
data-testid="continue-button">
|
||||
{t(submitLabel)}
|
||||
</Button>
|
||||
</>
|
||||
);
|
||||
|
||||
return (
|
||||
<>
|
||||
<Form
|
||||
form={newTeamFormMethods}
|
||||
handleSubmit={(v) => {
|
||||
if (!createTeamMutation.isPending) {
|
||||
posthog.capture("create_team_checkout_clicked", {
|
||||
team_name: v.name,
|
||||
team_slug: v.slug,
|
||||
});
|
||||
setServerErrorMessage(null);
|
||||
createTeamMutation.mutate(v);
|
||||
}
|
||||
}}>
|
||||
<div className="mb-8">
|
||||
{serverErrorMessage && (
|
||||
<div className="mb-4">
|
||||
<Alert severity="error" message={t(serverErrorMessage)} />
|
||||
</div>
|
||||
)}
|
||||
|
||||
<Controller
|
||||
name="name"
|
||||
control={newTeamFormMethods.control}
|
||||
defaultValue=""
|
||||
rules={{
|
||||
required: t("must_enter_team_name"),
|
||||
validate: (value) => value.trim().length > 0 || t("must_enter_team_name")
|
||||
}}
|
||||
render={({ field: { value } }) => (
|
||||
<>
|
||||
<TextField
|
||||
disabled={
|
||||
/* E2e is too fast and it tries to fill this way before the form is ready */
|
||||
!isLocaleReady || createTeamMutation.isPending
|
||||
}
|
||||
className="mt-2"
|
||||
placeholder="Acme Inc."
|
||||
name="name"
|
||||
label={t("team_name")}
|
||||
defaultValue={value}
|
||||
onChange={(e) => {
|
||||
newTeamFormMethods.setValue("name", e?.target.value);
|
||||
if (newTeamFormMethods.formState.touchedFields["slug"] === undefined) {
|
||||
newTeamFormMethods.setValue("slug", slugify(e?.target.value));
|
||||
}
|
||||
}}
|
||||
autoComplete="off"
|
||||
data-testid="team-name"
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="mb-8">
|
||||
<Controller
|
||||
name="slug"
|
||||
control={newTeamFormMethods.control}
|
||||
rules={{ required: t("team_url_required") }}
|
||||
render={({ field: { value } }) => (
|
||||
<TextField
|
||||
name="slug"
|
||||
placeholder="acme"
|
||||
label={t("team_url")}
|
||||
addOnLeading={`${
|
||||
orgBranding
|
||||
? `${orgBranding.fullDomain.replace("https://", "").replace("http://", "")}/`
|
||||
: `${subdomainSuffix()}/team/`
|
||||
}`}
|
||||
value={value}
|
||||
defaultValue={value}
|
||||
onChange={(e) => {
|
||||
newTeamFormMethods.setValue("slug", slugify(e?.target.value, true).replace(/\./g, ""), {
|
||||
shouldTouch: true,
|
||||
});
|
||||
newTeamFormMethods.clearErrors("slug");
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{inDialog ? (
|
||||
<DialogFooter>
|
||||
<div className="flex space-x-2 rtl:space-x-reverse">
|
||||
<FormButtons />
|
||||
</div>
|
||||
</DialogFooter>
|
||||
) : (
|
||||
<div className="flex space-x-2 rtl:space-x-reverse">
|
||||
<FormButtons />
|
||||
</div>
|
||||
)}
|
||||
</Form>
|
||||
</>
|
||||
);
|
||||
};
|
||||
@@ -1,62 +0,0 @@
|
||||
import { Dialog } from "@calcom/features/components/controlled-dialog";
|
||||
import { DataTableSelectionBar } from "@calcom/features/data-table";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
import type { RouterOutputs } from "@calcom/trpc/react";
|
||||
import { DialogTrigger, ConfirmationDialogContent } from "@calcom/ui/components/dialog";
|
||||
import { showToast } from "@calcom/ui/components/toast";
|
||||
|
||||
export type User = RouterOutputs["viewer"]["teams"]["listMembers"]["members"][number];
|
||||
|
||||
interface Props {
|
||||
users: User[];
|
||||
onRemove: () => void;
|
||||
isOrg: boolean;
|
||||
teamId: number;
|
||||
}
|
||||
|
||||
export default function DeleteBulkTeamMembers({ users, onRemove, isOrg, teamId }: Props) {
|
||||
const { t } = useLocale();
|
||||
const selectedRows = users; // Get selected rows from table
|
||||
const utils = trpc.useUtils();
|
||||
const deleteMutation = trpc.viewer.teams.removeMember.useMutation({
|
||||
async onSuccess() {
|
||||
await utils.viewer.teams.get.invalidate();
|
||||
await utils.viewer.eventTypes.invalidate();
|
||||
await utils.viewer.organizations.listMembers.invalidate();
|
||||
await utils.viewer.organizations.getMembers.invalidate();
|
||||
showToast("Deleted Users", "success");
|
||||
},
|
||||
async onError(err) {
|
||||
showToast(err.message, "error");
|
||||
},
|
||||
});
|
||||
return (
|
||||
<Dialog>
|
||||
<DialogTrigger asChild>
|
||||
<DataTableSelectionBar.Button icon="ban" color="destructive">
|
||||
{t("Delete")}
|
||||
</DataTableSelectionBar.Button>
|
||||
</DialogTrigger>
|
||||
<ConfirmationDialogContent
|
||||
variety="danger"
|
||||
title={t("remove_users_from_team")}
|
||||
confirmBtnText={t("remove")}
|
||||
isPending={deleteMutation.isPending}
|
||||
onConfirm={() => {
|
||||
deleteMutation.mutate({
|
||||
teamIds: [teamId],
|
||||
memberIds: selectedRows.map((user) => user.id),
|
||||
isOrg,
|
||||
});
|
||||
onRemove();
|
||||
}}>
|
||||
<p className="mt-5">
|
||||
{t("remove_users_from_team_confirm", {
|
||||
userCount: selectedRows.length,
|
||||
})}
|
||||
</p>
|
||||
</ConfirmationDialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -1,52 +0,0 @@
|
||||
import { useState } from "react";
|
||||
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
import { SettingsToggle } from "@calcom/ui/components/form";
|
||||
import { showToast } from "@calcom/ui/components/toast";
|
||||
|
||||
const DisableTeamImpersonation = ({
|
||||
teamId,
|
||||
memberId,
|
||||
disabled,
|
||||
}: {
|
||||
teamId: number;
|
||||
memberId: number;
|
||||
disabled: boolean;
|
||||
}) => {
|
||||
const { t } = useLocale();
|
||||
|
||||
const utils = trpc.useUtils();
|
||||
|
||||
const query = trpc.viewer.teams.getMembershipbyUser.useQuery({ teamId, memberId });
|
||||
|
||||
const mutation = trpc.viewer.teams.updateMembership.useMutation({
|
||||
onSuccess: async () => {
|
||||
showToast(t("your_user_profile_updated_successfully"), "success");
|
||||
await utils.viewer.teams.getMembershipbyUser.invalidate();
|
||||
},
|
||||
});
|
||||
const [allowImpersonation, setAllowImpersonation] = useState(
|
||||
query.data ? !query.data.disableImpersonation : true
|
||||
);
|
||||
if (query.isPending) return <></>;
|
||||
|
||||
return (
|
||||
<>
|
||||
<SettingsToggle
|
||||
toggleSwitchAtTheEnd={true}
|
||||
title={t("user_impersonation_heading")}
|
||||
labelClassName="text-sm"
|
||||
disabled={disabled || mutation?.isPending}
|
||||
description={t("team_impersonation_description")}
|
||||
checked={allowImpersonation}
|
||||
onCheckedChange={(_allowImpersonation) => {
|
||||
setAllowImpersonation(_allowImpersonation);
|
||||
mutation.mutate({ teamId, memberId, disableImpersonation: !_allowImpersonation });
|
||||
}}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export default DisableTeamImpersonation;
|
||||
@@ -1,327 +0,0 @@
|
||||
import { render } from "@testing-library/react";
|
||||
import React, { type ReactNode } from "react";
|
||||
import { vi } from "vitest";
|
||||
|
||||
import type { MemberPermissions } from "@calcom/features/users/components/UserTable/types";
|
||||
import { MembershipRole } from "@calcom/prisma/enums";
|
||||
|
||||
import { EditMemberSheet } from "./EditMemberSheet";
|
||||
import type { State, User } from "./MemberList";
|
||||
|
||||
// Mock dependencies
|
||||
vi.mock("@calcom/lib/hooks/useLocale", () => ({
|
||||
useLocale: () => ({
|
||||
t: (key: string) => key,
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock("@calcom/trpc/react", () => ({
|
||||
trpc: {
|
||||
viewer: {
|
||||
pbac: {
|
||||
getTeamRoles: {
|
||||
useQuery: () => ({
|
||||
data: undefined,
|
||||
isPending: false,
|
||||
}),
|
||||
},
|
||||
},
|
||||
teams: {
|
||||
getUserConnectedApps: {
|
||||
useQuery: () => ({
|
||||
data: {},
|
||||
isPending: false,
|
||||
}),
|
||||
},
|
||||
changeMemberRole: {
|
||||
useMutation: () => ({
|
||||
mutate: vi.fn(),
|
||||
mutateAsync: vi.fn(),
|
||||
}),
|
||||
},
|
||||
listMembers: {
|
||||
cancel: vi.fn(),
|
||||
getInfiniteData: vi.fn(),
|
||||
invalidate: vi.fn(),
|
||||
},
|
||||
get: {
|
||||
setData: vi.fn(),
|
||||
invalidate: vi.fn(),
|
||||
},
|
||||
},
|
||||
},
|
||||
useUtils: () => ({
|
||||
viewer: {
|
||||
teams: {
|
||||
listMembers: {
|
||||
cancel: vi.fn(),
|
||||
getInfiniteData: vi.fn(),
|
||||
invalidate: vi.fn(),
|
||||
},
|
||||
get: {
|
||||
setData: vi.fn(),
|
||||
invalidate: vi.fn(),
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
},
|
||||
}));
|
||||
|
||||
const mockSetEditMode = vi.fn();
|
||||
const mockSetMutationLoading = vi.fn();
|
||||
|
||||
vi.mock("@calcom/features/users/components/UserTable/EditSheet/store", () => ({
|
||||
useEditMode: vi.fn((selector) => {
|
||||
const state = {
|
||||
editMode: false,
|
||||
setEditMode: mockSetEditMode,
|
||||
mutationLoading: false,
|
||||
setMutationLoading: mockSetMutationLoading,
|
||||
};
|
||||
if (typeof selector === "function") {
|
||||
return selector(state);
|
||||
}
|
||||
return state;
|
||||
}),
|
||||
}));
|
||||
|
||||
// Mock SheetFooterControls to verify props
|
||||
let capturedProps: { canChangeMemberRole?: boolean; canEditAttributesForUser?: boolean }[] = [];
|
||||
vi.mock("@calcom/features/users/components/UserTable/EditSheet/SheetFooterControls", () => ({
|
||||
SheetFooterControls: (props: { canChangeMemberRole?: boolean; canEditAttributesForUser?: boolean }) => {
|
||||
capturedProps.push(props);
|
||||
return React.createElement("div", { "data-testid": "sheet-footer-controls" }, "SheetFooterControls");
|
||||
},
|
||||
}));
|
||||
|
||||
// Mock other UI components
|
||||
vi.mock("@calcom/ui/components/sheet", () => ({
|
||||
Sheet: ({ children }: { children: ReactNode }) =>
|
||||
React.createElement("div", { "data-testid": "sheet" }, children),
|
||||
SheetContent: ({ children }: { children: ReactNode }) =>
|
||||
React.createElement("div", { "data-testid": "sheet-content" }, children),
|
||||
SheetHeader: ({ children }: { children: ReactNode }) =>
|
||||
React.createElement("div", { "data-testid": "sheet-header" }, children),
|
||||
SheetBody: ({ children }: { children: ReactNode }) =>
|
||||
React.createElement("div", { "data-testid": "sheet-body" }, children),
|
||||
SheetFooter: ({ children }: { children: ReactNode }) =>
|
||||
React.createElement("div", { "data-testid": "sheet-footer" }, children),
|
||||
}));
|
||||
|
||||
vi.mock("@calcom/ui/components/form", () => ({
|
||||
Form: ({ children }: { children: ReactNode }) => React.createElement("form", null, children),
|
||||
ToggleGroup: () => React.createElement("div", { "data-testid": "toggle-group" }, "ToggleGroup"),
|
||||
Select: () => React.createElement("div", { "data-testid": "select" }, "Select"),
|
||||
}));
|
||||
|
||||
vi.mock("@calcom/ui/components/avatar", () => ({
|
||||
Avatar: () => React.createElement("div", { "data-testid": "avatar" }, "Avatar"),
|
||||
}));
|
||||
|
||||
vi.mock("@calcom/ui/components/skeleton", () => ({
|
||||
Skeleton: ({ children }: { children: ReactNode }) => React.createElement("div", null, children),
|
||||
Loader: () => React.createElement("div", { "data-testid": "loader" }, "Loading..."),
|
||||
}));
|
||||
|
||||
vi.mock("@calcom/features/users/components/UserTable/EditSheet/DisplayInfo", () => ({
|
||||
DisplayInfo: () => <div data-testid="display-info">DisplayInfo</div>,
|
||||
}));
|
||||
|
||||
describe("EditMemberSheet", () => {
|
||||
const mockDispatch = vi.fn();
|
||||
|
||||
// Create a minimal mock user that satisfies the User type
|
||||
const mockUser = {
|
||||
id: 1,
|
||||
name: "Test User",
|
||||
email: "[email protected]",
|
||||
username: "testuser",
|
||||
role: MembershipRole.MEMBER,
|
||||
accepted: true,
|
||||
avatarUrl: "",
|
||||
bookerUrl: "https://cal.com",
|
||||
lastActiveAt: "2024-01-01",
|
||||
customRoleId: null,
|
||||
} as User;
|
||||
|
||||
const mockState: State = {
|
||||
editSheet: {
|
||||
user: mockUser,
|
||||
showModal: true,
|
||||
},
|
||||
deleteMember: {
|
||||
showModal: false,
|
||||
},
|
||||
impersonateMember: {
|
||||
showModal: false,
|
||||
},
|
||||
teamAvailability: {
|
||||
showModal: false,
|
||||
},
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mockSetEditMode.mockClear();
|
||||
mockSetMutationLoading.mockClear();
|
||||
capturedProps = [];
|
||||
});
|
||||
|
||||
describe("Fix verification: canChangeMemberRole prop passing", () => {
|
||||
it("should pass canChangeMemberRole=true to SheetFooterControls when permissions.canChangeMemberRole is true", () => {
|
||||
const permissions: MemberPermissions = {
|
||||
canListMembers: false,
|
||||
canInvite: false,
|
||||
canChangeMemberRole: true,
|
||||
canRemove: false,
|
||||
canImpersonate: false,
|
||||
};
|
||||
|
||||
render(
|
||||
<EditMemberSheet
|
||||
state={mockState}
|
||||
dispatch={mockDispatch}
|
||||
currentMember={MembershipRole.OWNER}
|
||||
teamId={1}
|
||||
permissions={permissions}
|
||||
/>
|
||||
);
|
||||
|
||||
// Verify SheetFooterControls was called with canChangeMemberRole=true
|
||||
expect(capturedProps).toContainEqual(
|
||||
expect.objectContaining({
|
||||
canChangeMemberRole: true,
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it("should pass canChangeMemberRole=false to SheetFooterControls when permissions.canChangeMemberRole is false", () => {
|
||||
const permissions: MemberPermissions = {
|
||||
canListMembers: false,
|
||||
canInvite: false,
|
||||
canChangeMemberRole: false,
|
||||
canRemove: false,
|
||||
canImpersonate: false,
|
||||
};
|
||||
|
||||
render(
|
||||
<EditMemberSheet
|
||||
state={mockState}
|
||||
dispatch={mockDispatch}
|
||||
currentMember={MembershipRole.OWNER}
|
||||
teamId={1}
|
||||
permissions={permissions}
|
||||
/>
|
||||
);
|
||||
|
||||
// Verify SheetFooterControls was called with canChangeMemberRole=false
|
||||
expect(capturedProps).toContainEqual(
|
||||
expect.objectContaining({
|
||||
canChangeMemberRole: false,
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it("should pass canChangeMemberRole=undefined to SheetFooterControls when permissions is undefined", () => {
|
||||
render(
|
||||
<EditMemberSheet
|
||||
state={mockState}
|
||||
dispatch={mockDispatch}
|
||||
currentMember={MembershipRole.OWNER}
|
||||
teamId={1}
|
||||
permissions={undefined}
|
||||
/>
|
||||
);
|
||||
|
||||
// Verify SheetFooterControls was called with canChangeMemberRole=undefined
|
||||
expect(capturedProps).toContainEqual(
|
||||
expect.objectContaining({
|
||||
canChangeMemberRole: undefined,
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it("should pass canChangeMemberRole=undefined to SheetFooterControls when permissions object exists but canChangeMemberRole is undefined", () => {
|
||||
const permissions: Partial<MemberPermissions> = {
|
||||
canListMembers: true,
|
||||
canInvite: false,
|
||||
// canChangeMemberRole is intentionally omitted
|
||||
};
|
||||
|
||||
render(
|
||||
<EditMemberSheet
|
||||
state={mockState}
|
||||
dispatch={mockDispatch}
|
||||
currentMember={MembershipRole.OWNER}
|
||||
teamId={1}
|
||||
permissions={permissions as MemberPermissions}
|
||||
/>
|
||||
);
|
||||
|
||||
// Verify SheetFooterControls was called with canChangeMemberRole=undefined
|
||||
expect(capturedProps).toContainEqual(
|
||||
expect.objectContaining({
|
||||
canChangeMemberRole: undefined,
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it("should pass canEditAttributesForUser from permissions to SheetFooterControls", () => {
|
||||
const permissions: MemberPermissions = {
|
||||
canListMembers: false,
|
||||
canInvite: false,
|
||||
canChangeMemberRole: true,
|
||||
canRemove: false,
|
||||
canImpersonate: false,
|
||||
canEditAttributesForUser: true,
|
||||
};
|
||||
|
||||
render(
|
||||
<EditMemberSheet
|
||||
state={mockState}
|
||||
dispatch={mockDispatch}
|
||||
currentMember={MembershipRole.OWNER}
|
||||
teamId={1}
|
||||
permissions={permissions}
|
||||
/>
|
||||
);
|
||||
|
||||
// Verify SheetFooterControls was called with both props
|
||||
expect(capturedProps).toContainEqual(
|
||||
expect.objectContaining({
|
||||
canChangeMemberRole: true,
|
||||
canEditAttributesForUser: true,
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it("should correctly extract canChangeMemberRole from permissions object (verifies fix)", () => {
|
||||
// This test specifically verifies the fix where permissions?.canChangeMemberRole
|
||||
// is now correctly passed to SheetFooterControls
|
||||
const permissions: MemberPermissions = {
|
||||
canListMembers: false,
|
||||
canInvite: false,
|
||||
canChangeMemberRole: true, // This should be passed to SheetFooterControls
|
||||
canRemove: false,
|
||||
canImpersonate: false,
|
||||
};
|
||||
|
||||
render(
|
||||
<EditMemberSheet
|
||||
state={mockState}
|
||||
dispatch={mockDispatch}
|
||||
currentMember={MembershipRole.OWNER}
|
||||
teamId={1}
|
||||
permissions={permissions}
|
||||
/>
|
||||
);
|
||||
|
||||
expect(capturedProps).toContainEqual(
|
||||
expect.objectContaining({
|
||||
canChangeMemberRole: true,
|
||||
})
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,295 +0,0 @@
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import type { Dispatch } from "react";
|
||||
import { useMemo, useState } from "react";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { z } from "zod";
|
||||
import { shallow } from "zustand/shallow";
|
||||
|
||||
import { DisplayInfo } from "@calcom/features/users/components/UserTable/EditSheet/DisplayInfo";
|
||||
import { SheetFooterControls } from "@calcom/features/users/components/UserTable/EditSheet/SheetFooterControls";
|
||||
import { useEditMode } from "@calcom/features/users/components/UserTable/EditSheet/store";
|
||||
import type { MemberPermissions } from "@calcom/features/users/components/UserTable/types";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { MembershipRole } from "@calcom/prisma/enums";
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
import { Avatar } from "@calcom/ui/components/avatar";
|
||||
import { Form } from "@calcom/ui/components/form";
|
||||
import { ToggleGroup, Select } from "@calcom/ui/components/form";
|
||||
import { Icon } from "@calcom/ui/components/icon";
|
||||
import { Sheet, SheetContent, SheetFooter, SheetHeader, SheetBody } from "@calcom/ui/components/sheet";
|
||||
import { Skeleton, Loader } from "@calcom/ui/components/skeleton";
|
||||
import { showToast } from "@calcom/ui/components/toast";
|
||||
import { Tooltip } from "@calcom/ui/components/tooltip";
|
||||
|
||||
import { updateRoleInCache, getUpdatedUser } from "./MemberChangeRoleModal";
|
||||
import type { Action, State, User } from "./MemberList";
|
||||
|
||||
const formSchema = z.object({
|
||||
role: z.union([z.nativeEnum(MembershipRole), z.string()]), // Support both traditional roles and custom role IDs
|
||||
});
|
||||
|
||||
type FormSchema = z.infer<typeof formSchema>;
|
||||
|
||||
export function EditMemberSheet({
|
||||
state,
|
||||
dispatch,
|
||||
currentMember,
|
||||
teamId,
|
||||
permissions,
|
||||
}: {
|
||||
state: State;
|
||||
dispatch: Dispatch<Action>;
|
||||
currentMember: MembershipRole;
|
||||
teamId: number;
|
||||
permissions?: MemberPermissions;
|
||||
}) {
|
||||
const { t } = useLocale();
|
||||
const { user } = state.editSheet;
|
||||
const selectedUser = user as User;
|
||||
const [editMode, setEditMode, setMutationLoading] = useEditMode(
|
||||
(state) => [state.editMode, state.setEditMode, state.setMutationLoading],
|
||||
shallow
|
||||
);
|
||||
const [role, setRole] = useState<string>(selectedUser.customRoleId || selectedUser.role);
|
||||
const name =
|
||||
selectedUser.name ||
|
||||
(() => {
|
||||
const emailName = selectedUser.email.split("@")[0] as string;
|
||||
return emailName.charAt(0).toUpperCase() + emailName.slice(1);
|
||||
})();
|
||||
|
||||
const bookerUrl = selectedUser.bookerUrl;
|
||||
const utils = trpc.useUtils();
|
||||
const bookerUrlWithoutProtocol = bookerUrl.replace(/^https?:\/\//, "");
|
||||
const bookingLink = !!selectedUser.username ? `${bookerUrlWithoutProtocol}/${selectedUser.username}` : "";
|
||||
|
||||
// Load custom roles for the team
|
||||
const { data: customRoles, isPending: isLoadingRoles } = trpc.viewer.pbac.getTeamRoles.useQuery(
|
||||
{ teamId },
|
||||
{
|
||||
enabled: !!teamId,
|
||||
retry: false, // Don't retry if PBAC is not enabled
|
||||
}
|
||||
);
|
||||
|
||||
const options = useMemo(() => {
|
||||
// If we have custom roles, only show custom roles
|
||||
if (customRoles && customRoles.length > 0) {
|
||||
return customRoles.map((customRole) => ({
|
||||
label: customRole.name,
|
||||
value: customRole.id,
|
||||
}));
|
||||
}
|
||||
|
||||
// Otherwise, show traditional roles
|
||||
return [
|
||||
{
|
||||
label: t("member"),
|
||||
value: MembershipRole.MEMBER,
|
||||
},
|
||||
{
|
||||
label: t("admin"),
|
||||
value: MembershipRole.ADMIN,
|
||||
},
|
||||
{
|
||||
label: t("owner"),
|
||||
value: MembershipRole.OWNER,
|
||||
},
|
||||
].filter(({ value }) => value !== MembershipRole.OWNER || currentMember === MembershipRole.OWNER);
|
||||
}, [t, currentMember, customRoles]);
|
||||
|
||||
// Determine if we should use Select (when custom roles exist) or ToggleGroup (traditional only)
|
||||
const hasCustomRoles = customRoles && customRoles.length > 0;
|
||||
const shouldUseSelect = hasCustomRoles; // Use Select for custom roles, ToggleGroup for traditional roles
|
||||
|
||||
const form = useForm({
|
||||
resolver: zodResolver(formSchema),
|
||||
defaultValues: {
|
||||
role: selectedUser.customRoleId || selectedUser.role, // Use custom role ID if available, otherwise traditional role
|
||||
},
|
||||
});
|
||||
|
||||
const { data: getUserConnectedApps, isPending } = trpc.viewer.teams.getUserConnectedApps.useQuery({
|
||||
userIds: [selectedUser.id],
|
||||
teamId,
|
||||
});
|
||||
|
||||
const connectedApps = getUserConnectedApps?.[selectedUser.id];
|
||||
|
||||
const changeRoleMutation = trpc.viewer.teams.changeMemberRole.useMutation({
|
||||
onMutate: async ({ teamId, memberId, role }) => {
|
||||
await utils.viewer.teams.listMembers.cancel();
|
||||
const previousValue = utils.viewer.teams.listMembers.getInfiniteData({
|
||||
limit: 10,
|
||||
teamId,
|
||||
searchTerm: undefined,
|
||||
});
|
||||
|
||||
if (previousValue) {
|
||||
updateRoleInCache({
|
||||
utils,
|
||||
teamId,
|
||||
memberId,
|
||||
role: role as MembershipRole | string,
|
||||
searchTerm: undefined,
|
||||
customRoles,
|
||||
});
|
||||
}
|
||||
|
||||
return { previousValue };
|
||||
},
|
||||
onSuccess: async (_data, { role }) => {
|
||||
setRole(role as string);
|
||||
setMutationLoading(false);
|
||||
await utils.viewer.teams.get.invalidate();
|
||||
await utils.viewer.teams.listMembers.invalidate();
|
||||
showToast(t("profile_updated_successfully"), "success");
|
||||
setEditMode(false);
|
||||
|
||||
dispatch({
|
||||
type: "EDIT_USER_SHEET",
|
||||
payload: {
|
||||
showModal: true,
|
||||
user: getUpdatedUser(selectedUser, role, customRoles),
|
||||
},
|
||||
});
|
||||
},
|
||||
async onError(err) {
|
||||
showToast(err.message, "error");
|
||||
setMutationLoading(false);
|
||||
},
|
||||
});
|
||||
|
||||
function changeRole(values: FormSchema) {
|
||||
setMutationLoading(true);
|
||||
changeRoleMutation.mutate({
|
||||
teamId: teamId,
|
||||
memberId: user?.id as number,
|
||||
role: values.role,
|
||||
});
|
||||
}
|
||||
|
||||
const appList = (connectedApps || []).map(({ logo, name, externalId }) => {
|
||||
return logo ? (
|
||||
externalId ? (
|
||||
<div className="ltr:mr-2 rtl:ml-2 ">
|
||||
<Tooltip content={externalId}>
|
||||
<img className="h-5 w-5" src={logo} alt={`${name} logo`} />
|
||||
</Tooltip>
|
||||
</div>
|
||||
) : (
|
||||
<div className="ltr:mr-2 rtl:ml-2">
|
||||
<img className="h-5 w-5" src={logo} alt={`${name} logo`} />
|
||||
</div>
|
||||
)
|
||||
) : null;
|
||||
});
|
||||
|
||||
return (
|
||||
<Sheet
|
||||
open={true}
|
||||
onOpenChange={() => {
|
||||
setEditMode(false);
|
||||
dispatch({ type: "CLOSE_MODAL" });
|
||||
}}>
|
||||
<SheetContent className="bg-cal-muted">
|
||||
{!isPending && !isLoadingRoles ? (
|
||||
<Form form={form} handleSubmit={changeRole} className="flex h-full flex-col">
|
||||
<SheetHeader showCloseButton={false} className="w-full">
|
||||
<div className="border-sublte bg-default w-full rounded-xl border p-4">
|
||||
<div
|
||||
className="block w-full rounded-lg ring-1 ring-[#0000000F]"
|
||||
style={{
|
||||
background: "linear-gradient(to top right, var(--cal-bg-emphasis), var(--cal-bg))",
|
||||
height: "110px",
|
||||
}}
|
||||
/>
|
||||
<div className="bg-default ml-3 w-fit translate-y-[-50%] rounded-full p-1 ring-1 ring-[#0000000F]">
|
||||
<Avatar asChild size="lg" alt={`${name} avatar`} imageSrc={selectedUser.avatarUrl} />
|
||||
</div>
|
||||
<Skeleton as="p" waitForTranslation={false}>
|
||||
<h2 className="text-emphasis font-sans text-2xl font-semibold">
|
||||
{name || "Nameless User"}
|
||||
</h2>
|
||||
</Skeleton>
|
||||
<Skeleton as="p" waitForTranslation={false}>
|
||||
<p className="text-subtle max-h-[3em] overflow-hidden text-ellipsis text-sm font-normal">
|
||||
{selectedUser.bio ? selectedUser?.bio : t("user_has_no_bio")}
|
||||
</p>
|
||||
</Skeleton>
|
||||
</div>
|
||||
</SheetHeader>
|
||||
<SheetBody className="stack-y-4 flex flex-col p-4">
|
||||
<div className="stack-y-4 mb-4 flex flex-col">
|
||||
<h3 className="text-emphasis mb-1 text-base font-semibold">{t("profile")}</h3>
|
||||
<DisplayInfo label="Cal" value={bookingLink} icon="external-link" />
|
||||
<DisplayInfo label={t("email")} value={selectedUser.email} icon="at-sign" />
|
||||
{!editMode ? (
|
||||
<DisplayInfo
|
||||
label={t("role")}
|
||||
value={[selectedUser.customRole?.name || selectedUser.role]}
|
||||
icon="fingerprint"
|
||||
/>
|
||||
) : (
|
||||
<div className="flex items-center gap-6">
|
||||
<div className="flex w-[110px] items-center gap-2">
|
||||
<Icon className="h-4 w-4" name="fingerprint" />
|
||||
<label className="text-sm font-medium">{t("role")}</label>
|
||||
</div>
|
||||
<div className="flex flex-1">
|
||||
{shouldUseSelect ? (
|
||||
<Select
|
||||
value={options.find((option) => option.value === form.watch("role"))}
|
||||
onChange={(selectedOption: any) => {
|
||||
if (selectedOption) {
|
||||
form.setValue("role", selectedOption.value);
|
||||
}
|
||||
}}
|
||||
options={options}
|
||||
isDisabled={isLoadingRoles}
|
||||
placeholder={isLoadingRoles ? t("loading") : t("select_role")}
|
||||
className="flex-1"
|
||||
/>
|
||||
) : (
|
||||
<ToggleGroup
|
||||
isFullWidth
|
||||
defaultValue={role}
|
||||
value={form.watch("role")}
|
||||
options={options}
|
||||
onValueChange={(value: FormSchema["role"]) => {
|
||||
form.setValue("role", value);
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
<div className="flex items-center gap-6">
|
||||
<div className="flex w-[110px] items-center gap-2">
|
||||
<Icon className="text-subtle h-4 w-4" name="grid-3x3" />
|
||||
<label className="text-subtle text-sm font-medium">{t("apps")}</label>
|
||||
</div>
|
||||
<div className="flex flex-1">
|
||||
{!connectedApps ? (
|
||||
<div>{t("user_has_no_app_installed")}</div>
|
||||
) : (
|
||||
<div className="flex">{appList}</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</SheetBody>
|
||||
<SheetFooter className="mt-auto">
|
||||
<SheetFooterControls
|
||||
canChangeMemberRole={permissions?.canChangeMemberRole}
|
||||
canEditAttributesForUser={permissions?.canEditAttributesForUser}
|
||||
/>
|
||||
</SheetFooter>
|
||||
</Form>
|
||||
) : (
|
||||
<Loader />
|
||||
)}
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
);
|
||||
}
|
||||
@@ -1,203 +0,0 @@
|
||||
import type { Table } from "@tanstack/react-table";
|
||||
import type { Dispatch, SetStateAction } from "react";
|
||||
import { useState, Fragment } from "react";
|
||||
|
||||
import { DataTableSelectionBar } from "@calcom/features/data-table";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { SchedulingType } from "@calcom/prisma/enums";
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
import classNames from "@calcom/ui/classNames";
|
||||
import { Button } from "@calcom/ui/components/button";
|
||||
import {
|
||||
Command,
|
||||
CommandEmpty,
|
||||
CommandGroup,
|
||||
CommandInput,
|
||||
CommandItem,
|
||||
CommandList,
|
||||
} from "@calcom/ui/components/command";
|
||||
import { Icon } from "@calcom/ui/components/icon";
|
||||
import { Popover, PopoverContent, PopoverTrigger } from "@calcom/ui/components/popover";
|
||||
import { showToast } from "@calcom/ui/components/toast";
|
||||
|
||||
import type { User } from "./MemberList";
|
||||
|
||||
interface Props {
|
||||
table: Table<User>;
|
||||
teamId: number;
|
||||
}
|
||||
|
||||
export function EventTypesList({ table, teamId }: Props) {
|
||||
const { t } = useLocale();
|
||||
const utils = trpc.useUtils();
|
||||
const { data } = trpc.viewer.eventTypes.getByViewer.useQuery({
|
||||
filters: { teamIds: [teamId], schedulingTypes: [SchedulingType.ROUND_ROBIN] },
|
||||
});
|
||||
const addMutation = trpc.viewer.teams.addMembersToEventTypes.useMutation({
|
||||
onError: (error) => {
|
||||
showToast(error.message, "error");
|
||||
},
|
||||
onSuccess: () => {
|
||||
showToast(
|
||||
`${selectedUsers.length} users added to ${Array.from(selectedEvents).length} events`,
|
||||
"success"
|
||||
);
|
||||
|
||||
utils.viewer.teams.listMembers.invalidate();
|
||||
utils.viewer.eventTypes.invalidate();
|
||||
|
||||
// Clear the selected values
|
||||
setSelectedEvents(new Set());
|
||||
table.toggleAllRowsSelected(false);
|
||||
},
|
||||
});
|
||||
const removeHostsMutation = trpc.viewer.teams.removeHostsFromEventTypes.useMutation({
|
||||
onError: (error) => {
|
||||
showToast(error.message, "error");
|
||||
},
|
||||
onSuccess: () => {
|
||||
showToast(
|
||||
`${selectedUsers.length} users were removed from ${Array.from(removeHostFromEvents).length} events`,
|
||||
"success"
|
||||
);
|
||||
|
||||
utils.viewer.teams.listMembers.invalidate();
|
||||
utils.viewer.eventTypes.invalidate();
|
||||
|
||||
// Clear the selected values
|
||||
setRemoveHostFromEvents(new Set());
|
||||
table.toggleAllRowsSelected(false);
|
||||
},
|
||||
});
|
||||
const [selectedEvents, setSelectedEvents] = useState<Set<number>>(new Set());
|
||||
const [removeHostFromEvents, setRemoveHostFromEvents] = useState<Set<number>>(new Set());
|
||||
const eventTypeGroups = data?.eventTypeGroups;
|
||||
const selectedUsers = table.getSelectedRowModel().flatRows.map((row) => row.original);
|
||||
|
||||
// Add value array to the set
|
||||
const addValue = (set: Set<number>, setSet: Dispatch<SetStateAction<Set<number>>>, value: number[]) => {
|
||||
const updatedSet = new Set(set);
|
||||
value.forEach((v) => updatedSet.add(v));
|
||||
setSet(updatedSet);
|
||||
};
|
||||
|
||||
// Remove value array from the set
|
||||
const removeValue = (set: Set<number>, setSet: Dispatch<SetStateAction<Set<number>>>, value: number[]) => {
|
||||
const updatedSet = new Set(set);
|
||||
value.forEach((v) => updatedSet.delete(v));
|
||||
setSet(updatedSet);
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<Popover>
|
||||
<PopoverTrigger asChild>
|
||||
<DataTableSelectionBar.Button icon="link" color="secondary">
|
||||
{t("add_to_event_type")}
|
||||
</DataTableSelectionBar.Button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent className="w-[200px] p-0 shadow-md" align="start" sideOffset={12}>
|
||||
<Command>
|
||||
<CommandInput placeholder={t("search")} />
|
||||
<CommandList>
|
||||
<CommandEmpty>No results found.</CommandEmpty>
|
||||
<CommandGroup>
|
||||
{eventTypeGroups &&
|
||||
eventTypeGroups.map((data) => {
|
||||
const events = data.eventTypes;
|
||||
const teamId = data.teamId;
|
||||
|
||||
if (events.length === 0 || !teamId) return null;
|
||||
return (
|
||||
<Fragment key={teamId}>
|
||||
{events.map((event) => {
|
||||
const hosts = event.hosts;
|
||||
const areAllUsersHostForEventType = selectedUsers.every((user) =>
|
||||
hosts.some((host) => host.userId === user.id)
|
||||
);
|
||||
const isSelected =
|
||||
(selectedEvents.has(event.id) || areAllUsersHostForEventType) &&
|
||||
!removeHostFromEvents.has(event.id);
|
||||
return (
|
||||
<ListItem
|
||||
onSelect={() => {
|
||||
if (!isSelected) {
|
||||
if (areAllUsersHostForEventType) {
|
||||
removeValue(removeHostFromEvents, setRemoveHostFromEvents, [event.id]);
|
||||
} else {
|
||||
// Add current event
|
||||
addValue(selectedEvents, setSelectedEvents, [event.id]);
|
||||
}
|
||||
} else {
|
||||
if (areAllUsersHostForEventType) {
|
||||
// remove selected users as hosts
|
||||
addValue(removeHostFromEvents, setRemoveHostFromEvents, [event.id]);
|
||||
} else {
|
||||
// remove current event
|
||||
removeValue(selectedEvents, setSelectedEvents, [event.id]);
|
||||
}
|
||||
}
|
||||
}}
|
||||
key={event.id}
|
||||
text={event.title}
|
||||
isSelected={isSelected}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
</Fragment>
|
||||
);
|
||||
})}
|
||||
</CommandGroup>
|
||||
</CommandList>
|
||||
</Command>
|
||||
<div className="my-1.5 flex w-full">
|
||||
<Button
|
||||
className="ml-auto mr-1.5 rounded-md"
|
||||
size="sm"
|
||||
onClick={() => {
|
||||
const userIds = selectedUsers.map((user) => user.id);
|
||||
if (selectedEvents.size > 0) {
|
||||
addMutation.mutateAsync({
|
||||
userIds: userIds,
|
||||
eventTypeIds: Array.from(selectedEvents),
|
||||
teamId,
|
||||
});
|
||||
}
|
||||
|
||||
if (removeHostFromEvents.size > 0) {
|
||||
removeHostsMutation.mutateAsync({
|
||||
userIds,
|
||||
eventTypeIds: Array.from(removeHostFromEvents),
|
||||
teamId,
|
||||
});
|
||||
}
|
||||
}}>
|
||||
{t("apply")}
|
||||
</Button>
|
||||
</div>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
interface ListItemProps {
|
||||
text: string;
|
||||
isSelected: boolean;
|
||||
onSelect: () => void;
|
||||
}
|
||||
|
||||
const ListItem = ({ onSelect, text, isSelected }: ListItemProps) => {
|
||||
return (
|
||||
<CommandItem key={text} onSelect={onSelect}>
|
||||
{text}
|
||||
<div
|
||||
className={classNames(
|
||||
"border-subtle ml-auto flex h-4 w-4 items-center justify-center rounded-sm border",
|
||||
isSelected ? "text-emphasis" : "opacity-50 [&_svg]:invisible"
|
||||
)}>
|
||||
<Icon name="check" className={classNames("h-4 w-4")} />
|
||||
</div>
|
||||
</CommandItem>
|
||||
);
|
||||
};
|
||||
@@ -1,127 +0,0 @@
|
||||
import type { PropsWithChildren } from "react";
|
||||
import { useState } from "react";
|
||||
|
||||
import { useFlagMap } from "@calcom/features/flags/context/provider";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { useParamsWithFallback } from "@calcom/lib/hooks/useParamsWithFallback";
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
import { showToast } from "@calcom/ui/components/toast";
|
||||
import { Tooltip } from "@calcom/ui/components/tooltip";
|
||||
import { Button } from "@calcom/ui/components/button";
|
||||
|
||||
const GoogleIcon = () => (
|
||||
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<g clip-path="url(#clip0_4178_176214)">
|
||||
<path
|
||||
d="M8.31875 15.36C4.26 15.36 0.9575 12.0588 0.9575 8.00001C0.9575 3.94126 4.26 0.640015 8.31875 0.640015C10.1575 0.640015 11.9175 1.32126 13.2763 2.55876L13.5238 2.78501L11.0963 5.21251L10.8713 5.02001C10.1588 4.41001 9.2525 4.07376 8.31875 4.07376C6.15375 4.07376 4.39125 5.83501 4.39125 8.00001C4.39125 10.165 6.15375 11.9263 8.31875 11.9263C9.88 11.9263 11.1138 11.1288 11.695 9.77001H7.99875V6.45626L15.215 6.46626L15.2688 6.72001C15.645 8.50626 15.3438 11.1338 13.8188 13.0138C12.5563 14.57 10.7063 15.36 8.31875 15.36Z"
|
||||
fill="#6B7280"
|
||||
/>
|
||||
</g>
|
||||
<defs>
|
||||
<clipPath id="clip0_4178_176214">
|
||||
<rect width="16" height="16" fill="white" />
|
||||
</clipPath>
|
||||
</defs>
|
||||
</svg>
|
||||
);
|
||||
|
||||
function gotoUrl(url: string, newTab?: boolean) {
|
||||
if (newTab) {
|
||||
window.open(url, "_blank");
|
||||
return;
|
||||
}
|
||||
window.location.href = url;
|
||||
}
|
||||
|
||||
export function GoogleWorkspaceInviteButton(
|
||||
props: PropsWithChildren<{ onSuccess: (data: string[]) => void }>
|
||||
) {
|
||||
const featureFlags = useFlagMap();
|
||||
const utils = trpc.useUtils();
|
||||
const { t } = useLocale();
|
||||
const params = useParamsWithFallback();
|
||||
const teamId = Number(params.id);
|
||||
const [googleWorkspaceLoading, setGoogleWorkspaceLoading] = useState(false);
|
||||
const { data: credential } = trpc.viewer.googleWorkspace.checkForGWorkspace.useQuery();
|
||||
const { data: hasGcalInstalled } = trpc.viewer.apps.checkGlobalKeys.useQuery({
|
||||
slug: "google-calendar",
|
||||
});
|
||||
const mutation = trpc.viewer.googleWorkspace.getUsersFromGWorkspace.useMutation({
|
||||
onSuccess: (data) => {
|
||||
if (Array.isArray(data) && data.length !== 0) {
|
||||
props.onSuccess(data);
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
const removeConnectionMutation =
|
||||
trpc.viewer.googleWorkspace.removeCurrentGoogleWorkspaceConnection.useMutation({
|
||||
onSuccess: () => {
|
||||
showToast(t("app_removed_successfully"), "success");
|
||||
},
|
||||
});
|
||||
|
||||
if (featureFlags["google-workspace-directory"] == false || !hasGcalInstalled) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Show populate input button if they do
|
||||
if (credential && credential?.id) {
|
||||
return (
|
||||
<div className="flex gap-2">
|
||||
<Tooltip content={t("google_workspace_admin_tooltip")}>
|
||||
<Button
|
||||
color="secondary"
|
||||
onClick={() => {
|
||||
mutation.mutate();
|
||||
}}
|
||||
className="w-full justify-center gap-2"
|
||||
StartIcon="users"
|
||||
loading={mutation.isPending}>
|
||||
{t("import_from_google_workspace")}
|
||||
</Button>
|
||||
</Tooltip>
|
||||
<Tooltip content="Remove workspace connection">
|
||||
<Button
|
||||
color="secondary"
|
||||
loading={removeConnectionMutation.isPending}
|
||||
StartIcon="x"
|
||||
onClick={() => {
|
||||
removeConnectionMutation.mutate();
|
||||
utils.viewer.googleWorkspace.checkForGWorkspace.invalidate();
|
||||
}}
|
||||
variant="icon"
|
||||
/>
|
||||
</Tooltip>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// else show invite button
|
||||
return (
|
||||
<Button
|
||||
type="button"
|
||||
color="secondary"
|
||||
loading={googleWorkspaceLoading}
|
||||
CustomStartIcon={<GoogleIcon />}
|
||||
onClick={async () => {
|
||||
setGoogleWorkspaceLoading(true);
|
||||
const params = new URLSearchParams({
|
||||
teamId: teamId.toString(),
|
||||
});
|
||||
const res = await fetch(`/api/teams/googleworkspace/add?${params}`);
|
||||
|
||||
if (!res.ok) {
|
||||
const errorBody = await res.json();
|
||||
throw new Error(errorBody.message || "Something went wrong");
|
||||
}
|
||||
setGoogleWorkspaceLoading(false);
|
||||
|
||||
const json = await res.json();
|
||||
gotoUrl(json.url, json.newTab);
|
||||
}}
|
||||
className="justify-center gap-2">
|
||||
{t("connect_google_workspace")}
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
@@ -1,187 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { useAutoAnimate } from "@formkit/auto-animate/react";
|
||||
import { useMemo } from "react";
|
||||
import { useForm, useFieldArray, Controller } from "react-hook-form";
|
||||
|
||||
import { checkAdminOrOwner } from "@calcom/features/auth/lib/checkAdminOrOwner";
|
||||
import SectionBottomActions from "@calcom/features/settings/SectionBottomActions";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
import type { RouterOutputs } from "@calcom/trpc/react";
|
||||
import classNames from "@calcom/ui/classNames";
|
||||
import { Button } from "@calcom/ui/components/button";
|
||||
import { Form, Input, SettingsToggle } from "@calcom/ui/components/form";
|
||||
import { Icon } from "@calcom/ui/components/icon";
|
||||
import { showToast } from "@calcom/ui/components/toast";
|
||||
|
||||
interface ProfileViewProps {
|
||||
team: RouterOutputs["viewer"]["teams"]["get"];
|
||||
}
|
||||
|
||||
const OTHER_FIELD_ID = -1;
|
||||
|
||||
const InternalNotePresetsView = ({ team }: ProfileViewProps) => {
|
||||
const { t } = useLocale();
|
||||
const utils = trpc.useUtils();
|
||||
const { data: _loadedPresets } = trpc.viewer.teams.getInternalNotesPresets.useQuery({
|
||||
teamId: team?.id as number,
|
||||
});
|
||||
|
||||
const loadedPresets = useMemo(() => {
|
||||
return (_loadedPresets ?? []).map((preset) => ({
|
||||
...preset,
|
||||
cancellationReason: preset.cancellationReason ?? undefined,
|
||||
}));
|
||||
}, [_loadedPresets]);
|
||||
|
||||
const hasExistingPresets = loadedPresets.length > 0;
|
||||
|
||||
type FormValues = {
|
||||
presets: { id: number; name: string; cancellationReason?: string | undefined }[];
|
||||
};
|
||||
|
||||
const form = useForm<FormValues>({
|
||||
values: {
|
||||
presets: loadedPresets,
|
||||
},
|
||||
});
|
||||
|
||||
const { fields, append, remove, replace } = useFieldArray({
|
||||
control: form.control,
|
||||
name: "presets",
|
||||
});
|
||||
|
||||
const addNewPreset = () => {
|
||||
append({ id: OTHER_FIELD_ID, name: "" });
|
||||
};
|
||||
|
||||
const updatePresetsMutation = trpc.viewer.teams.updateInternalNotesPresets.useMutation({
|
||||
onSuccess: () => {
|
||||
showToast(t("internal_note_presets_updated_successfully"), "success");
|
||||
utils.viewer.teams.getInternalNotesPresets.invalidate();
|
||||
},
|
||||
onError: (error) => {
|
||||
showToast(error.message || t("something_went_wrong"), "error");
|
||||
},
|
||||
});
|
||||
|
||||
const onSubmit = async (data: FormValues) => {
|
||||
if (!team?.id) return;
|
||||
|
||||
updatePresetsMutation.mutate({
|
||||
teamId: team.id,
|
||||
presets: data.presets,
|
||||
});
|
||||
};
|
||||
|
||||
const [animateRef] = useAutoAnimate<HTMLDivElement>();
|
||||
|
||||
const isAdmin = team && checkAdminOrOwner(team.membership.role);
|
||||
|
||||
if (!isAdmin) {
|
||||
return (
|
||||
<div className="border-subtle rounded-md border p-5">
|
||||
<span className="text-default text-sm">{t("only_owner_change")}</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Form form={form} handleSubmit={(e) => onSubmit(e)}>
|
||||
<Controller
|
||||
name="presets"
|
||||
render={({ field: { value } }) => {
|
||||
const isChecked = hasExistingPresets || (value && value.length > 0);
|
||||
return (
|
||||
<SettingsToggle
|
||||
toggleSwitchAtTheEnd={true}
|
||||
labelClassName="text-sm"
|
||||
title={t("internal_note_presets")}
|
||||
description={t("internal_note_presets_description")}
|
||||
checked={isChecked}
|
||||
childrenClassName="lg:ml-0"
|
||||
onCheckedChange={async (active) => {
|
||||
if (active && !value?.length) {
|
||||
append({ id: OTHER_FIELD_ID, name: "" });
|
||||
} else {
|
||||
replace([]);
|
||||
if (!active && team?.id && hasExistingPresets) {
|
||||
updatePresetsMutation.mutate({
|
||||
teamId: team.id,
|
||||
presets: [],
|
||||
});
|
||||
}
|
||||
}
|
||||
}}
|
||||
switchContainerClassName={classNames(
|
||||
"border-subtle mt-6 rounded-lg border py-6 px-4 sm:px-6",
|
||||
isChecked && "rounded-b-none"
|
||||
)}>
|
||||
<div className="border-subtle border border-y-0 p-6">
|
||||
<div className="flex flex-col stack-y-4" ref={animateRef}>
|
||||
{fields.map((field, index) => (
|
||||
<div key={field.id} className="stack-y-2">
|
||||
<div className="flex items-center space-x-2">
|
||||
<Controller
|
||||
name={`presets.${index}.name`}
|
||||
control={form.control}
|
||||
render={({ field }) => (
|
||||
<Input
|
||||
type="text"
|
||||
{...field}
|
||||
placeholder={t("internal_booking_note")}
|
||||
className="mb-0!"
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
<Button
|
||||
type="button"
|
||||
color="destructive"
|
||||
variant="icon"
|
||||
onClick={() => remove(index)}
|
||||
disabled={fields.length === 1}>
|
||||
<Icon name="trash" className="h-4 w-5" />
|
||||
</Button>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Icon name="corner-down-right" className="h-4 w-4" />
|
||||
<Controller
|
||||
name={`presets.${index}.cancellationReason`}
|
||||
control={form.control}
|
||||
render={({ field }) => (
|
||||
<Input
|
||||
type="text"
|
||||
{...field}
|
||||
placeholder={t("internal_note_cancellation_reason")}
|
||||
className="mb-0!"
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
<Button
|
||||
type="button"
|
||||
color="minimal"
|
||||
StartIcon="plus"
|
||||
onClick={addNewPreset}
|
||||
className="mt-4">
|
||||
{t("add_preset")}
|
||||
</Button>
|
||||
</div>
|
||||
<SectionBottomActions align="end">
|
||||
<Button type="submit" color="primary" loading={updatePresetsMutation.isPending}>
|
||||
{t("update")}
|
||||
</Button>
|
||||
</SectionBottomActions>
|
||||
</SettingsToggle>
|
||||
);
|
||||
}}
|
||||
/>
|
||||
</Form>
|
||||
);
|
||||
};
|
||||
|
||||
export default InternalNotePresetsView;
|
||||
@@ -1,128 +0,0 @@
|
||||
import { useMemo } from "react";
|
||||
import { Controller, useForm } from "react-hook-form";
|
||||
|
||||
import { Dialog } from "@calcom/features/components/controlled-dialog";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
import { Button } from "@calcom/ui/components/button";
|
||||
import { DialogContent, DialogFooter } from "@calcom/ui/components/dialog";
|
||||
import { Form } from "@calcom/ui/components/form";
|
||||
import { Label } from "@calcom/ui/components/form";
|
||||
import { Select } from "@calcom/ui/components/form";
|
||||
import { showToast } from "@calcom/ui/components/toast";
|
||||
import { revalidateTeamsList } from "@calcom/web/app/(use-page-wrapper)/(main-nav)/teams/actions";
|
||||
|
||||
type InvitationLinkSettingsModalProps = {
|
||||
isOpen: boolean;
|
||||
teamId: number;
|
||||
token: string;
|
||||
expiresInDays?: number;
|
||||
onExit: () => void;
|
||||
};
|
||||
|
||||
export interface LinkSettingsForm {
|
||||
expiresInDays: number | undefined;
|
||||
}
|
||||
|
||||
export default function InviteLinkSettingsModal(props: InvitationLinkSettingsModalProps) {
|
||||
const { t } = useLocale();
|
||||
const trpcContext = trpc.useUtils();
|
||||
|
||||
const deleteInviteMutation = trpc.viewer.teams.deleteInvite.useMutation({
|
||||
onSuccess: () => {
|
||||
showToast(t("invite_link_deleted"), "success");
|
||||
trpcContext.viewer.teams.get.invalidate();
|
||||
trpcContext.viewer.teams.list.invalidate();
|
||||
revalidateTeamsList();
|
||||
props.onExit();
|
||||
},
|
||||
onError: (e) => {
|
||||
showToast(e.message, "error");
|
||||
},
|
||||
});
|
||||
|
||||
const setInviteExpirationMutation = trpc.viewer.teams.setInviteExpiration.useMutation({
|
||||
onSuccess: () => {
|
||||
showToast(t("invite_link_updated"), "success");
|
||||
trpcContext.viewer.teams.get.invalidate();
|
||||
trpcContext.viewer.teams.list.invalidate();
|
||||
revalidateTeamsList();
|
||||
},
|
||||
onError: (e) => {
|
||||
showToast(e.message, "error");
|
||||
},
|
||||
});
|
||||
|
||||
const expiresInDaysOption = useMemo(() => {
|
||||
return [
|
||||
{ value: 1, label: t("one_day") },
|
||||
{ value: 7, label: t("seven_days") },
|
||||
{ value: 30, label: t("thirty_days") },
|
||||
{ value: undefined, label: t("never_expires") },
|
||||
];
|
||||
}, [t]);
|
||||
|
||||
const linkSettingsFormMethods = useForm<LinkSettingsForm>({
|
||||
defaultValues: {
|
||||
expiresInDays: props.expiresInDays,
|
||||
},
|
||||
});
|
||||
|
||||
const handleSubmit = (values: LinkSettingsForm) => {
|
||||
setInviteExpirationMutation.mutate({
|
||||
token: props.token,
|
||||
expiresInDays: values.expiresInDays,
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog
|
||||
open={props.isOpen}
|
||||
onOpenChange={() => {
|
||||
props.onExit();
|
||||
linkSettingsFormMethods.reset();
|
||||
}}>
|
||||
<DialogContent type="creation" title="Invite link settings">
|
||||
<Form form={linkSettingsFormMethods} handleSubmit={handleSubmit}>
|
||||
<Controller
|
||||
name="expiresInDays"
|
||||
control={linkSettingsFormMethods.control}
|
||||
render={({ field: { onChange } }) => (
|
||||
<div className="-mt-2">
|
||||
<Label className="text-emphasis font-medium" htmlFor="expiresInDays">
|
||||
{t("link_expires_after")}
|
||||
</Label>
|
||||
<Select
|
||||
options={expiresInDaysOption}
|
||||
defaultValue={expiresInDaysOption.find((option) => option.value === props.expiresInDays)}
|
||||
className="w-full"
|
||||
onChange={(val) => onChange(val?.value)}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
/>
|
||||
<DialogFooter showDivider className="mt-10">
|
||||
<Button
|
||||
type="button"
|
||||
color="secondary"
|
||||
onClick={() => deleteInviteMutation.mutate({ token: props.token })}
|
||||
className="mr-auto"
|
||||
data-testid="copy-invite-link-button">
|
||||
{t("delete")}
|
||||
</Button>
|
||||
<Button type="button" color="minimal" onClick={props.onExit}>
|
||||
{t("back")}
|
||||
</Button>
|
||||
<Button
|
||||
type="submit"
|
||||
color="primary"
|
||||
className="me-2 ms-2"
|
||||
data-testid="invite-new-member-button">
|
||||
{t("save")}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</Form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -1,54 +0,0 @@
|
||||
import { useState } from "react";
|
||||
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
import { SettingsToggle } from "@calcom/ui/components/form";
|
||||
import { showToast } from "@calcom/ui/components/toast";
|
||||
|
||||
const MakeTeamPrivateSwitch = ({
|
||||
teamId,
|
||||
isPrivate,
|
||||
disabled,
|
||||
isOrg,
|
||||
}: {
|
||||
teamId: number;
|
||||
isPrivate: boolean;
|
||||
disabled: boolean;
|
||||
isOrg: boolean;
|
||||
}) => {
|
||||
const { t } = useLocale();
|
||||
|
||||
const utils = trpc.useUtils();
|
||||
|
||||
const mutation = trpc.viewer.teams.update.useMutation({
|
||||
onError: (err) => {
|
||||
showToast(err.message, "error");
|
||||
},
|
||||
async onSuccess() {
|
||||
await utils.viewer.teams.get.invalidate();
|
||||
showToast(t(isOrg ? "your_org_updated_successfully" : "your_team_updated_successfully"), "success");
|
||||
},
|
||||
});
|
||||
|
||||
const [isTeamPrivate, setTeamPrivate] = useState(isPrivate);
|
||||
|
||||
return (
|
||||
<>
|
||||
<SettingsToggle
|
||||
toggleSwitchAtTheEnd={true}
|
||||
title={t(isOrg ? "make_org_private" : "make_team_private")}
|
||||
labelClassName="text-sm"
|
||||
disabled={disabled || mutation?.isPending}
|
||||
description={t(isOrg ? "make_org_private_description" : "make_team_private_description")}
|
||||
checked={isTeamPrivate}
|
||||
onCheckedChange={(checked) => {
|
||||
setTeamPrivate(checked);
|
||||
mutation.mutate({ id: teamId, isPrivate: checked });
|
||||
}}
|
||||
data-testid="make-team-private-check"
|
||||
/>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export default MakeTeamPrivateSwitch;
|
||||
@@ -1,202 +0,0 @@
|
||||
import type { SyntheticEvent } from "react";
|
||||
import { useMemo, useState } from "react";
|
||||
|
||||
import { Dialog } from "@calcom/features/components/controlled-dialog";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { MembershipRole } from "@calcom/prisma/enums";
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
import { Button } from "@calcom/ui/components/button";
|
||||
import { DialogContent, DialogFooter } from "@calcom/ui/components/dialog";
|
||||
import { Select } from "@calcom/ui/components/form";
|
||||
|
||||
import type { User } from "./MemberList";
|
||||
|
||||
type MembershipRoleOption = {
|
||||
label: string;
|
||||
value: MembershipRole;
|
||||
};
|
||||
|
||||
export const getUpdatedUser = (
|
||||
member: User,
|
||||
role: MembershipRole | string,
|
||||
customRoles: { id: string; name: string }[] | undefined
|
||||
) => {
|
||||
const isTraditionalRole = Object.values(MembershipRole).includes(role as MembershipRole);
|
||||
|
||||
// Find the new custom role object if assigning a custom role
|
||||
const newCustomRole =
|
||||
!isTraditionalRole && customRoles ? customRoles.find((cr) => cr.id === role) || null : null;
|
||||
|
||||
return {
|
||||
...member,
|
||||
role: isTraditionalRole ? (role as MembershipRole) : member.role,
|
||||
customRoleId: isTraditionalRole ? null : (role as string),
|
||||
customRole: newCustomRole,
|
||||
};
|
||||
};
|
||||
|
||||
export const updateRoleInCache = ({
|
||||
utils,
|
||||
teamId,
|
||||
searchTerm,
|
||||
role,
|
||||
memberId,
|
||||
customRoles,
|
||||
}: {
|
||||
utils: ReturnType<typeof trpc.useUtils>;
|
||||
teamId: number;
|
||||
searchTerm: string | undefined;
|
||||
role: MembershipRole | string;
|
||||
memberId: number;
|
||||
customRoles?: { id: string; name: string }[];
|
||||
}) => {
|
||||
utils.viewer.teams.listMembers.setInfiniteData(
|
||||
{
|
||||
limit: 10,
|
||||
teamId,
|
||||
searchTerm,
|
||||
},
|
||||
(data) => {
|
||||
if (!data) {
|
||||
return {
|
||||
pages: [],
|
||||
pageParams: [],
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
...data,
|
||||
pages: data.pages.map((page) => ({
|
||||
...page,
|
||||
members: page.members.map((member) => {
|
||||
if (member.id === memberId) {
|
||||
return getUpdatedUser(member, role, customRoles);
|
||||
}
|
||||
return member;
|
||||
}),
|
||||
})),
|
||||
};
|
||||
}
|
||||
);
|
||||
};
|
||||
|
||||
export default function MemberChangeRoleModal(props: {
|
||||
isOpen: boolean;
|
||||
currentMember: MembershipRole;
|
||||
memberId: number;
|
||||
teamId: number;
|
||||
initialRole: MembershipRole;
|
||||
onExit: () => void;
|
||||
searchTerm?: string;
|
||||
}) {
|
||||
const { t } = useLocale();
|
||||
|
||||
const options = useMemo(() => {
|
||||
return [
|
||||
{
|
||||
label: t("member"),
|
||||
value: MembershipRole.MEMBER,
|
||||
},
|
||||
{
|
||||
label: t("admin"),
|
||||
value: MembershipRole.ADMIN,
|
||||
},
|
||||
{
|
||||
label: t("owner"),
|
||||
value: MembershipRole.OWNER,
|
||||
},
|
||||
].filter(({ value }) => value !== MembershipRole.OWNER || props.currentMember === MembershipRole.OWNER);
|
||||
}, [t, props.currentMember]);
|
||||
|
||||
const [role, setRole] = useState<MembershipRoleOption>(
|
||||
options.find((option) => option.value === props.initialRole) || {
|
||||
label: t("member"),
|
||||
value: MembershipRole.MEMBER,
|
||||
}
|
||||
);
|
||||
const [errorMessage, setErrorMessage] = useState("");
|
||||
const utils = trpc.useUtils();
|
||||
|
||||
const changeRoleMutation = trpc.viewer.teams.changeMemberRole.useMutation({
|
||||
onMutate: async ({ teamId, memberId, role }) => {
|
||||
await utils.viewer.teams.listMembers.cancel();
|
||||
const previousValue = utils.viewer.teams.listMembers.getInfiniteData({
|
||||
limit: 10,
|
||||
teamId,
|
||||
searchTerm: props.searchTerm,
|
||||
});
|
||||
|
||||
if (previousValue) {
|
||||
updateRoleInCache({ utils, teamId, memberId, role, searchTerm: props.searchTerm });
|
||||
}
|
||||
|
||||
return { previousValue };
|
||||
},
|
||||
async onSuccess() {
|
||||
await utils.viewer.teams.get.invalidate();
|
||||
await utils.viewer.organizations.listMembers.invalidate();
|
||||
|
||||
props.onExit();
|
||||
},
|
||||
async onError(err) {
|
||||
setErrorMessage(err.message);
|
||||
},
|
||||
});
|
||||
|
||||
function changeRole(e: SyntheticEvent) {
|
||||
e.preventDefault();
|
||||
|
||||
changeRoleMutation.mutate({
|
||||
teamId: props.teamId,
|
||||
memberId: props.memberId,
|
||||
role: role.value,
|
||||
});
|
||||
}
|
||||
return (
|
||||
<Dialog open={props.isOpen} onOpenChange={props.onExit}>
|
||||
<DialogContent type="creation">
|
||||
<>
|
||||
<div className="mb-4 sm:flex sm:items-start">
|
||||
<div className="text-center sm:text-left">
|
||||
<h3
|
||||
className="text-emphasis !font-cal text-semibold text-xl font-medium"
|
||||
id="modal-title">
|
||||
{t("change_member_role")}
|
||||
</h3>
|
||||
</div>
|
||||
</div>
|
||||
<form onSubmit={changeRole}>
|
||||
<div className="mb-4">
|
||||
<label className="text-default mb-2 block text-sm font-medium tracking-wide" htmlFor="role">
|
||||
{t("role")}
|
||||
</label>
|
||||
{/*<option value="OWNER">{t("owner")}</option> - needs dialog to confirm change of ownership */}
|
||||
<Select
|
||||
isSearchable={false}
|
||||
options={options}
|
||||
value={role}
|
||||
onChange={(option) => option && setRole(option)}
|
||||
id="role"
|
||||
className="border-default mt-1 block w-full rounded-md text-sm"
|
||||
/>
|
||||
</div>
|
||||
{errorMessage && (
|
||||
<p className="text-sm text-red-700">
|
||||
<span className="font-bold">Error: </span>
|
||||
{errorMessage}
|
||||
</p>
|
||||
)}
|
||||
<DialogFooter className="mt-12">
|
||||
<Button type="button" color="secondary" onClick={props.onExit}>
|
||||
{t("cancel")}
|
||||
</Button>
|
||||
<Button type="submit" color="primary" className="me-2 ms-2">
|
||||
{t("save")}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
</>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -1,561 +0,0 @@
|
||||
import { useSession } from "next-auth/react";
|
||||
import type { FormEvent } from "react";
|
||||
import { useMemo, useRef, useState } from "react";
|
||||
import { Controller, useForm } from "react-hook-form";
|
||||
import posthog from "posthog-js";
|
||||
|
||||
import TeamInviteFromOrg from "@calcom/ee/organizations/components/TeamInviteFromOrg";
|
||||
import { checkAdminOrOwner } from "@calcom/features/auth/lib/checkAdminOrOwner";
|
||||
import { Dialog } from "@calcom/features/components/controlled-dialog";
|
||||
import ServerTrans from "@calcom/lib/components/ServerTrans";
|
||||
import { IS_TEAM_BILLING_ENABLED_CLIENT, MAX_NB_INVITES } from "@calcom/lib/constants";
|
||||
import { useCompatSearchParams } from "@calcom/lib/hooks/useCompatSearchParams";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { MembershipRole } from "@calcom/prisma/enums";
|
||||
import { CreationSource } from "@calcom/prisma/enums";
|
||||
import type { RouterOutputs } from "@calcom/trpc/react";
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
import { isEmail } from "@calcom/trpc/server/routers/viewer/teams/util";
|
||||
import classNames from "@calcom/ui/classNames";
|
||||
import { Button } from "@calcom/ui/components/button";
|
||||
import { DialogContent, DialogFooter } from "@calcom/ui/components/dialog";
|
||||
import { TextAreaField } from "@calcom/ui/components/form";
|
||||
import { Form } from "@calcom/ui/components/form";
|
||||
import { Label } from "@calcom/ui/components/form";
|
||||
import { TextField } from "@calcom/ui/components/form";
|
||||
import { Select } from "@calcom/ui/components/form";
|
||||
import { ToggleGroup } from "@calcom/ui/components/form";
|
||||
import { Icon } from "@calcom/ui/components/icon";
|
||||
import { showToast } from "@calcom/ui/components/toast";
|
||||
import { revalidateTeamsList } from "@calcom/web/app/(use-page-wrapper)/(main-nav)/teams/actions";
|
||||
|
||||
import type { PendingMember } from "../lib/types";
|
||||
import { GoogleWorkspaceInviteButton } from "./GoogleWorkspaceInviteButton";
|
||||
|
||||
type MemberInvitationModalProps = {
|
||||
isOpen: boolean;
|
||||
onExit: () => void;
|
||||
orgMembers?: RouterOutputs["viewer"]["organizations"]["getMembers"];
|
||||
onSubmit: (values: NewMemberForm, resetFields: () => void) => void;
|
||||
onSettingsOpen?: () => void;
|
||||
teamId: number;
|
||||
members?: PendingMember[];
|
||||
token?: string;
|
||||
isPending?: boolean;
|
||||
disableCopyLink?: boolean;
|
||||
isOrg?: boolean;
|
||||
checkMembershipMutation?: boolean;
|
||||
};
|
||||
|
||||
type MembershipRoleOption = {
|
||||
value: MembershipRole;
|
||||
label: string;
|
||||
};
|
||||
|
||||
export interface NewMemberForm {
|
||||
emailOrUsername: string | string[];
|
||||
role: MembershipRole;
|
||||
}
|
||||
|
||||
type ModalMode = "INDIVIDUAL" | "BULK" | "ORGANIZATION";
|
||||
|
||||
interface FileEvent<T = Element> extends FormEvent<T> {
|
||||
target: EventTarget & T;
|
||||
}
|
||||
|
||||
function toggleElementInArray(value: string[] | string | undefined, element: string): string[] {
|
||||
const array = value ? (Array.isArray(value) ? value : [value]) : [];
|
||||
return array.includes(element) ? array.filter((item) => item !== element) : [...array, element];
|
||||
}
|
||||
|
||||
export default function MemberInvitationModal(props: MemberInvitationModalProps) {
|
||||
const { t } = useLocale();
|
||||
const { disableCopyLink = false, isOrg = false } = props;
|
||||
const trpcContext = trpc.useUtils();
|
||||
const session = useSession();
|
||||
const { data: currentOrg } = trpc.viewer.organizations.listCurrent.useQuery(undefined, {
|
||||
enabled: !!session.data?.user?.org,
|
||||
});
|
||||
|
||||
const checkIfMembershipExistsMutation = trpc.viewer.teams.checkIfMembershipExists.useMutation();
|
||||
|
||||
// Check current org role and not team role
|
||||
const isOrgAdminOrOwner = currentOrg && checkAdminOrOwner(currentOrg.user.role);
|
||||
|
||||
const canSeeOrganization = currentOrg?.isPrivate
|
||||
? isOrgAdminOrOwner
|
||||
: !!(props?.orgMembers && props.orgMembers?.length > 0 && isOrgAdminOrOwner);
|
||||
|
||||
const [modalImportMode, setModalInputMode] = useState<ModalMode>(
|
||||
canSeeOrganization ? "ORGANIZATION" : "INDIVIDUAL"
|
||||
);
|
||||
|
||||
const createInviteMutation = trpc.viewer.teams.createInvite.useMutation({
|
||||
async onSuccess() {
|
||||
trpcContext.viewer.teams.get.invalidate();
|
||||
trpcContext.viewer.teams.list.invalidate();
|
||||
revalidateTeamsList();
|
||||
},
|
||||
onError: (error) => {
|
||||
showToast(error.message, "error");
|
||||
},
|
||||
});
|
||||
|
||||
const options: MembershipRoleOption[] = useMemo(() => {
|
||||
const options: MembershipRoleOption[] = [
|
||||
{ value: MembershipRole.MEMBER, label: t("member") },
|
||||
{ value: MembershipRole.ADMIN, label: t("admin") },
|
||||
{ value: MembershipRole.OWNER, label: t("owner") },
|
||||
];
|
||||
|
||||
// Adjust options for organizations where the user isn't the owner
|
||||
if (isOrg && !isOrgAdminOrOwner) {
|
||||
return options.filter((option) => option.value !== MembershipRole.OWNER);
|
||||
}
|
||||
|
||||
return options;
|
||||
}, [t, isOrgAdminOrOwner, isOrg]);
|
||||
|
||||
const toggleGroupOptions = useMemo(() => {
|
||||
const array = [
|
||||
{
|
||||
value: "INDIVIDUAL",
|
||||
label: t("invite_team_individual_segment"),
|
||||
iconLeft: <Icon name="user" />,
|
||||
},
|
||||
{ value: "BULK", label: t("invite_team_bulk_segment"), iconLeft: <Icon name="users" /> },
|
||||
];
|
||||
if (canSeeOrganization) {
|
||||
array.unshift({
|
||||
value: "ORGANIZATION",
|
||||
label: t("organization"),
|
||||
iconLeft: <Icon name="building" />,
|
||||
});
|
||||
}
|
||||
return array;
|
||||
}, [t, canSeeOrganization]);
|
||||
|
||||
const newMemberFormMethods = useForm<NewMemberForm>();
|
||||
|
||||
const checkIfMembershipExists = (value: string) => {
|
||||
if (props.checkMembershipMutation) {
|
||||
return checkIfMembershipExistsMutation.mutateAsync({
|
||||
teamId: props.teamId,
|
||||
value,
|
||||
});
|
||||
} else {
|
||||
if (!props?.members?.length) return false;
|
||||
return (
|
||||
props?.members.some((member) => member?.username === value) ||
|
||||
props?.members.some((member) => member?.email === value)
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
const handleFileUpload = (e: FileEvent<HTMLInputElement>) => {
|
||||
if (!e.target.files?.length) {
|
||||
return;
|
||||
}
|
||||
const file = e.target.files[0];
|
||||
|
||||
if (file) {
|
||||
const reader = new FileReader();
|
||||
const emailRegex = /^([A-Z0-9_+-]+\.?)*[A-Z0-9_+-]@([A-Z0-9][A-Z0-9-]*\.)+[A-Z]{2,}$/i;
|
||||
reader.onload = (e) => {
|
||||
const contents = e?.target?.result as string;
|
||||
const lines = contents.split("\n");
|
||||
const validEmails = [];
|
||||
for (const line of lines) {
|
||||
const columns = line.split(/,|;|\|| /);
|
||||
for (const column of columns) {
|
||||
const email = column.trim().toLowerCase();
|
||||
|
||||
if (emailRegex.test(email)) {
|
||||
validEmails.push(email);
|
||||
break; // Stop checking columns if a valid email is found in this line
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
newMemberFormMethods.setValue("emailOrUsername", validEmails);
|
||||
};
|
||||
|
||||
reader.readAsText(file);
|
||||
}
|
||||
};
|
||||
|
||||
const resetFields = () => {
|
||||
newMemberFormMethods.reset();
|
||||
newMemberFormMethods.setValue("emailOrUsername", "");
|
||||
newMemberFormMethods.setValue("role", options[0].value);
|
||||
setModalInputMode("INDIVIDUAL");
|
||||
};
|
||||
|
||||
const importRef = useRef<HTMLInputElement | null>(null);
|
||||
|
||||
return (
|
||||
<Dialog
|
||||
name="inviteModal"
|
||||
open={props.isOpen}
|
||||
onOpenChange={() => {
|
||||
props.onExit();
|
||||
newMemberFormMethods.reset();
|
||||
}}>
|
||||
<DialogContent
|
||||
enableOverflow
|
||||
type="creation"
|
||||
title={t("invite_team_member")}
|
||||
description={
|
||||
IS_TEAM_BILLING_ENABLED_CLIENT && !currentOrg ? (
|
||||
<span className="text-subtle text-sm leading-tight">
|
||||
<ServerTrans
|
||||
t={t}
|
||||
i18nKey="invite_new_member_description"
|
||||
components={[
|
||||
<span key="invite_new_member_description" className="text-emphasis font-medium">
|
||||
cost an extra seat ($15/m)
|
||||
</span>,
|
||||
]}
|
||||
/>
|
||||
</span>
|
||||
) : null
|
||||
}>
|
||||
<div className="sm:max-h-9">
|
||||
<Label className="sr-only" htmlFor="role">
|
||||
{t("import_mode")}
|
||||
</Label>
|
||||
<ToggleGroup
|
||||
isFullWidth={true}
|
||||
className="flex-col sm:flex-row"
|
||||
onValueChange={(val) => {
|
||||
setModalInputMode(val as ModalMode);
|
||||
newMemberFormMethods.clearErrors();
|
||||
}}
|
||||
defaultValue={modalImportMode}
|
||||
options={toggleGroupOptions}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<Form form={newMemberFormMethods} handleSubmit={(values) => { props.onSubmit(values, resetFields); posthog.capture("teams_modal_invite_members_button_clicked") }}>
|
||||
<div className="mb-10 mt-6 space-y-6">
|
||||
{/* Individual Invite */}
|
||||
{modalImportMode === "INDIVIDUAL" && (
|
||||
<Controller
|
||||
name="emailOrUsername"
|
||||
control={newMemberFormMethods.control}
|
||||
rules={{
|
||||
required: t("enter_email"),
|
||||
validate: async (value) => {
|
||||
// orgs can only invite members by email
|
||||
if (typeof value === "string" && !isEmail(value)) return t("enter_email");
|
||||
if (typeof value === "string") {
|
||||
const doesInviteExists = await checkIfMembershipExists(value);
|
||||
return !doesInviteExists || t("member_already_invited");
|
||||
}
|
||||
},
|
||||
}}
|
||||
render={({ field: { onChange }, fieldState: { error } }) => (
|
||||
<>
|
||||
<TextField
|
||||
label={t("email")}
|
||||
id="inviteUser"
|
||||
name="inviteUser"
|
||||
placeholder="[email protected]"
|
||||
required
|
||||
onChange={(e) => onChange(e.target.value.trim().toLowerCase())}
|
||||
/>
|
||||
{error && <span className="text-sm text-red-800">{error.message}</span>}
|
||||
</>
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
{/* Bulk Invite */}
|
||||
{modalImportMode === "BULK" && (
|
||||
<div className="bg-cal-muted flex flex-col rounded-md p-4">
|
||||
<Controller
|
||||
name="emailOrUsername"
|
||||
control={newMemberFormMethods.control}
|
||||
rules={{
|
||||
required: t("enter_email"),
|
||||
validate: (value) => {
|
||||
if (Array.isArray(value) && value.some((email) => !isEmail(email)))
|
||||
return t("enter_emails");
|
||||
if (Array.isArray(value) && value.length > MAX_NB_INVITES)
|
||||
return t("too_many_invites", { nbUsers: MAX_NB_INVITES });
|
||||
if (typeof value === "string" && !isEmail(value)) return t("enter_email");
|
||||
},
|
||||
}}
|
||||
render={({ field: { onChange, value }, fieldState: { error } }) => (
|
||||
<>
|
||||
{/* TODO: Make this a fancy email input that styles on a successful email. */}
|
||||
<TextAreaField
|
||||
name="emails"
|
||||
label={t("invite_via_email")}
|
||||
rows={4}
|
||||
autoCorrect="off"
|
||||
placeholder="[email protected], [email protected]"
|
||||
required
|
||||
value={value}
|
||||
onChange={(e) => {
|
||||
const targetValues = e.target.value.split(/[\n,]/);
|
||||
const emails =
|
||||
targetValues.length === 1
|
||||
? targetValues[0].trim().toLocaleLowerCase()
|
||||
: targetValues.map((email) => email.trim().toLocaleLowerCase());
|
||||
|
||||
return onChange(emails);
|
||||
}}
|
||||
/>
|
||||
{error && <span className="text-sm text-red-800">{error.message}</span>}
|
||||
</>
|
||||
)}
|
||||
/>
|
||||
|
||||
<GoogleWorkspaceInviteButton
|
||||
onSuccess={(data) => {
|
||||
newMemberFormMethods.setValue("emailOrUsername", data);
|
||||
}}
|
||||
/>
|
||||
<Button
|
||||
type="button"
|
||||
color="secondary"
|
||||
onClick={() => {
|
||||
if (importRef.current) {
|
||||
importRef.current.click();
|
||||
}
|
||||
}}
|
||||
StartIcon="paperclip"
|
||||
className="mt-3 justify-center stroke-2">
|
||||
{t("upload_csv_file")}
|
||||
</Button>
|
||||
<input
|
||||
ref={importRef}
|
||||
hidden
|
||||
id="bulkInvite"
|
||||
type="file"
|
||||
accept=".csv"
|
||||
style={{ display: "none" }}
|
||||
onChange={handleFileUpload}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
{modalImportMode === "ORGANIZATION" && (
|
||||
<Controller
|
||||
name="emailOrUsername"
|
||||
control={newMemberFormMethods.control}
|
||||
rules={{
|
||||
required: t("enter_email_or_username"),
|
||||
}}
|
||||
render={({ field: { onChange, value } }) => (
|
||||
<>
|
||||
<TeamInviteFromOrg
|
||||
selectedEmails={value}
|
||||
handleOnChecked={(userEmail) => {
|
||||
// If 'value' is not an array, create a new array with 'userEmail' to allow future updates to the array.
|
||||
// If 'value' is an array, update the array by either adding or removing 'userEmail'.
|
||||
const newValue = toggleElementInArray(value, userEmail);
|
||||
onChange(newValue);
|
||||
}}
|
||||
orgMembers={props.orgMembers}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
<Controller
|
||||
name="role"
|
||||
control={newMemberFormMethods.control}
|
||||
defaultValue={options[0].value}
|
||||
render={({ field: { onChange } }) => (
|
||||
<div>
|
||||
<Label className="text-emphasis font-medium" htmlFor="role">
|
||||
{t("invite_as")}
|
||||
</Label>
|
||||
<Select
|
||||
id="role"
|
||||
defaultValue={options[0]}
|
||||
options={options}
|
||||
onChange={(val) => {
|
||||
if (val) onChange(val.value);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
/>
|
||||
{props.token && (
|
||||
<div className="flex">
|
||||
<Button
|
||||
type="button"
|
||||
color="minimal"
|
||||
className="me-2 ms-2"
|
||||
onClick={() => {
|
||||
if (props.onSettingsOpen) {
|
||||
props.onSettingsOpen();
|
||||
}
|
||||
newMemberFormMethods.reset();
|
||||
}}
|
||||
data-testid="edit-invite-link-button">
|
||||
{t("edit_invite_link")}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<DialogFooter showDivider>
|
||||
{!disableCopyLink && (
|
||||
<div className="grow">
|
||||
<Button
|
||||
type="button"
|
||||
color="minimal"
|
||||
variant="icon"
|
||||
onClick={async function () {
|
||||
try {
|
||||
// Required for Safari but also works on Chrome
|
||||
// Credits to https://wolfgangrittner.dev/how-to-use-clipboard-api-in-firefox/
|
||||
if (typeof ClipboardItem !== "undefined") {
|
||||
const inviteLinkClipbardItem = new ClipboardItem({
|
||||
//eslint-disable-next-line no-async-promise-executor
|
||||
"text/plain": new Promise(async (resolve) => {
|
||||
// Instead of doing async work and then writing to clipboard, do async work in clipboard API itself
|
||||
const { inviteLink } = await createInviteMutation.mutateAsync({
|
||||
teamId: props.teamId,
|
||||
token: props.token,
|
||||
});
|
||||
showToast(t("invite_link_copied"), "success");
|
||||
resolve(new Blob([inviteLink], { type: "text/plain" }));
|
||||
}),
|
||||
});
|
||||
await navigator.clipboard.write([inviteLinkClipbardItem]);
|
||||
} else {
|
||||
// Fallback for browsers that don't support ClipboardItem e.g. Firefox
|
||||
const { inviteLink } = await createInviteMutation.mutateAsync({
|
||||
teamId: props.teamId,
|
||||
token: props.token,
|
||||
});
|
||||
await navigator.clipboard.writeText(inviteLink);
|
||||
showToast(t("invite_link_copied"), "success");
|
||||
}
|
||||
} catch (e) {
|
||||
showToast(t("something_went_wrong_on_our_end"), "error");
|
||||
console.error(e);
|
||||
}
|
||||
}}
|
||||
className={classNames("gap-2", props.token && "opacity-50")}
|
||||
StartIcon="link"
|
||||
data-testid="copy-invite-link-button">
|
||||
<span className="hidden sm:inline">{t("copy_invite_link")}</span>
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
<Button
|
||||
type="button"
|
||||
color="minimal"
|
||||
onClick={() => {
|
||||
props.onExit();
|
||||
resetFields();
|
||||
}}>
|
||||
{t("cancel")}
|
||||
</Button>
|
||||
<Button
|
||||
loading={
|
||||
props.isPending || createInviteMutation.isPending || checkIfMembershipExistsMutation.isPending
|
||||
}
|
||||
type="submit"
|
||||
color="primary"
|
||||
className="me-2 ms-2"
|
||||
data-testid="invite-new-member-button">
|
||||
{t("send_invite")}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</Form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
export const MemberInvitationModalWithoutMembers = ({
|
||||
hideInvitationModal,
|
||||
showMemberInvitationModal,
|
||||
teamId,
|
||||
token,
|
||||
onSettingsOpen,
|
||||
...props
|
||||
}: Partial<MemberInvitationModalProps> & {
|
||||
hideInvitationModal: () => void;
|
||||
showMemberInvitationModal: boolean;
|
||||
teamId: number;
|
||||
token?: string;
|
||||
onSettingsOpen: () => void;
|
||||
}) => {
|
||||
const searchParams = useCompatSearchParams();
|
||||
const { t, i18n } = useLocale();
|
||||
const utils = trpc.useUtils();
|
||||
|
||||
const inviteMemberMutation = trpc.viewer.teams.inviteMember.useMutation();
|
||||
|
||||
const { data: orgMembersNotInThisTeam, isPending: isOrgListLoading } =
|
||||
trpc.viewer.organizations.getMembers.useQuery(
|
||||
{
|
||||
teamIdToExclude: teamId,
|
||||
distinctUser: true,
|
||||
},
|
||||
{
|
||||
enabled: searchParams !== null && !!teamId && !!showMemberInvitationModal,
|
||||
}
|
||||
);
|
||||
|
||||
return (
|
||||
<MemberInvitationModal
|
||||
{...props}
|
||||
isPending={inviteMemberMutation.isPending || isOrgListLoading}
|
||||
isOpen={showMemberInvitationModal}
|
||||
orgMembers={orgMembersNotInThisTeam}
|
||||
teamId={teamId}
|
||||
token={token}
|
||||
onExit={hideInvitationModal}
|
||||
checkMembershipMutation={true}
|
||||
onSubmit={(values, resetFields) => {
|
||||
inviteMemberMutation.mutate(
|
||||
{
|
||||
teamId,
|
||||
language: i18n.language,
|
||||
role: values.role,
|
||||
usernameOrEmail: values.emailOrUsername,
|
||||
creationSource: CreationSource.WEBAPP,
|
||||
},
|
||||
{
|
||||
onSuccess: async (data) => {
|
||||
await utils.viewer.teams.get.invalidate();
|
||||
await utils.viewer.teams.listMembers.invalidate();
|
||||
await utils.viewer.organizations.getMembers.invalidate();
|
||||
hideInvitationModal();
|
||||
|
||||
if (Array.isArray(data.usernameOrEmail)) {
|
||||
showToast(
|
||||
t("email_invite_team_bulk", {
|
||||
userCount: data.numUsersInvited,
|
||||
}),
|
||||
"success"
|
||||
);
|
||||
resetFields();
|
||||
} else {
|
||||
showToast(
|
||||
t("email_invite_team", {
|
||||
email: data.usernameOrEmail,
|
||||
}),
|
||||
"success"
|
||||
);
|
||||
}
|
||||
},
|
||||
onError: (error) => {
|
||||
showToast(error.message, "error");
|
||||
},
|
||||
}
|
||||
);
|
||||
}}
|
||||
onSettingsOpen={() => {
|
||||
hideInvitationModal();
|
||||
onSettingsOpen();
|
||||
}}
|
||||
/>
|
||||
);
|
||||
};
|
||||
@@ -1,838 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { keepPreviousData } from "@tanstack/react-query";
|
||||
import {
|
||||
getCoreRowModel,
|
||||
getFilteredRowModel,
|
||||
getSortedRowModel,
|
||||
useReactTable,
|
||||
type ColumnDef,
|
||||
} from "@tanstack/react-table";
|
||||
import classNames from "classnames";
|
||||
import { useSession } from "next-auth/react";
|
||||
import posthog from "posthog-js";
|
||||
import { signIn } from "next-auth/react";
|
||||
import { usePathname } from "next/navigation";
|
||||
import { useQueryState, parseAsBoolean } from "nuqs";
|
||||
import { useMemo, useReducer, useRef, useState } from "react";
|
||||
import type { Dispatch, SetStateAction } from "react";
|
||||
|
||||
import { Dialog } from "@calcom/features/components/controlled-dialog";
|
||||
import {
|
||||
DataTableProvider,
|
||||
DataTableToolbar,
|
||||
DataTableFilters,
|
||||
DataTableWrapper,
|
||||
DataTableSelectionBar,
|
||||
useDataTable,
|
||||
useFetchMoreOnBottomReached,
|
||||
useColumnFilters,
|
||||
convertFacetedValuesToMap,
|
||||
} from "@calcom/features/data-table";
|
||||
import { useOrgBranding } from "@calcom/features/ee/organizations/context/provider";
|
||||
import { DynamicLink } from "@calcom/features/users/components/UserTable/BulkActions/DynamicLink";
|
||||
import type { MemberPermissions } from "@calcom/features/users/components/UserTable/types";
|
||||
import { WEBAPP_URL } from "@calcom/lib/constants";
|
||||
import { getUserAvatarUrl } from "@calcom/lib/getAvatarUrl";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
import type { RouterOutputs } from "@calcom/trpc/react";
|
||||
import { Avatar } from "@calcom/ui/components/avatar";
|
||||
import { Badge } from "@calcom/ui/components/badge";
|
||||
import { Button } from "@calcom/ui/components/button";
|
||||
import { ButtonGroup } from "@calcom/ui/components/buttonGroup";
|
||||
import {
|
||||
DialogContent,
|
||||
DialogFooter,
|
||||
DialogClose,
|
||||
ConfirmationDialogContent,
|
||||
} from "@calcom/ui/components/dialog";
|
||||
import {
|
||||
Dropdown,
|
||||
DropdownItem,
|
||||
DropdownMenuPortal,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuTrigger,
|
||||
} from "@calcom/ui/components/dropdown";
|
||||
import { Checkbox } from "@calcom/ui/components/form";
|
||||
import { showToast } from "@calcom/ui/components/toast";
|
||||
import { Tooltip } from "@calcom/ui/components/tooltip";
|
||||
|
||||
import DeleteBulkTeamMembers from "./DeleteBulkTeamMembers";
|
||||
import { EditMemberSheet } from "./EditMemberSheet";
|
||||
import { EventTypesList } from "./EventTypesList";
|
||||
import TeamAvailabilityModal from "./TeamAvailabilityModal";
|
||||
|
||||
interface Props {
|
||||
team: NonNullable<RouterOutputs["viewer"]["teams"]["get"]>;
|
||||
isOrgAdminOrOwner: boolean | undefined;
|
||||
setShowMemberInvitationModal: Dispatch<SetStateAction<boolean>>;
|
||||
}
|
||||
|
||||
export type User = RouterOutputs["viewer"]["teams"]["listMembers"]["members"][number];
|
||||
|
||||
const checkIsOrg = (team: Props["team"]) => {
|
||||
return team.isOrganization;
|
||||
};
|
||||
|
||||
type Payload = {
|
||||
showModal: boolean;
|
||||
user?: User;
|
||||
};
|
||||
|
||||
export type State = {
|
||||
deleteMember: Payload;
|
||||
impersonateMember: Payload;
|
||||
editSheet: Payload;
|
||||
teamAvailability: Payload;
|
||||
};
|
||||
|
||||
export type Action =
|
||||
| {
|
||||
type:
|
||||
| "SET_DELETE_ID"
|
||||
| "SET_IMPERSONATE_ID"
|
||||
| "EDIT_USER_SHEET"
|
||||
| "TEAM_AVAILABILITY"
|
||||
| "INVITE_MEMBER";
|
||||
payload: Payload;
|
||||
}
|
||||
| {
|
||||
type: "CLOSE_MODAL";
|
||||
};
|
||||
|
||||
const initialState: State = {
|
||||
deleteMember: {
|
||||
showModal: false,
|
||||
},
|
||||
impersonateMember: {
|
||||
showModal: false,
|
||||
},
|
||||
editSheet: {
|
||||
showModal: false,
|
||||
},
|
||||
teamAvailability: {
|
||||
showModal: false,
|
||||
},
|
||||
};
|
||||
|
||||
const initalColumnVisibility = {
|
||||
select: true,
|
||||
member: true,
|
||||
role: true,
|
||||
teams: true,
|
||||
actions: true,
|
||||
};
|
||||
|
||||
function reducer(state: State, action: Action): State {
|
||||
switch (action.type) {
|
||||
case "SET_DELETE_ID":
|
||||
return { ...state, deleteMember: action.payload };
|
||||
case "SET_IMPERSONATE_ID":
|
||||
return { ...state, impersonateMember: action.payload };
|
||||
case "EDIT_USER_SHEET":
|
||||
return { ...state, editSheet: action.payload };
|
||||
case "TEAM_AVAILABILITY":
|
||||
return { ...state, teamAvailability: action.payload };
|
||||
case "CLOSE_MODAL":
|
||||
return {
|
||||
...state,
|
||||
deleteMember: { showModal: false },
|
||||
impersonateMember: { showModal: false },
|
||||
editSheet: { showModal: false },
|
||||
teamAvailability: { showModal: false },
|
||||
};
|
||||
default:
|
||||
return state;
|
||||
}
|
||||
}
|
||||
|
||||
interface Props {
|
||||
team: NonNullable<RouterOutputs["viewer"]["teams"]["get"]>;
|
||||
isOrgAdminOrOwner: boolean | undefined;
|
||||
setShowMemberInvitationModal: Dispatch<SetStateAction<boolean>>;
|
||||
facetedTeamValues?: {
|
||||
roles: { id: string; name: string }[];
|
||||
teams: RouterOutputs["viewer"]["teams"]["get"][];
|
||||
attributes: {
|
||||
id: string;
|
||||
name: string;
|
||||
options: {
|
||||
value: string;
|
||||
}[];
|
||||
}[];
|
||||
};
|
||||
permissions: MemberPermissions;
|
||||
}
|
||||
|
||||
export default function MemberList(props: Props) {
|
||||
const pathname = usePathname();
|
||||
if (!pathname) return null;
|
||||
return (
|
||||
<DataTableProvider tableIdentifier={pathname}>
|
||||
<MemberListContent {...props} />
|
||||
</DataTableProvider>
|
||||
);
|
||||
}
|
||||
|
||||
function MemberListContent(props: Props) {
|
||||
const { facetedTeamValues } = props;
|
||||
const [dynamicLinkVisible, setDynamicLinkVisible] = useQueryState("dynamicLink", parseAsBoolean);
|
||||
const { t, i18n } = useLocale();
|
||||
const { data: session } = useSession();
|
||||
|
||||
const utils = trpc.useUtils();
|
||||
const orgBranding = useOrgBranding();
|
||||
const domain = orgBranding?.fullDomain ?? WEBAPP_URL;
|
||||
|
||||
const tableContainerRef = useRef<HTMLDivElement>(null);
|
||||
const [state, dispatch] = useReducer(reducer, initialState);
|
||||
|
||||
const { searchTerm } = useDataTable();
|
||||
|
||||
const { data, isPending, hasNextPage, fetchNextPage, isFetching } =
|
||||
trpc.viewer.teams.listMembers.useInfiniteQuery(
|
||||
{
|
||||
limit: 10,
|
||||
searchTerm,
|
||||
teamId: props.team.id,
|
||||
// TODO: send `columnFilters` to server for server side filtering
|
||||
// filters: columnFilters,
|
||||
},
|
||||
{
|
||||
enabled: !!props.team.id,
|
||||
getNextPageParam: (lastPage) => lastPage.nextCursor,
|
||||
placeholderData: keepPreviousData,
|
||||
refetchOnWindowFocus: true,
|
||||
refetchOnMount: true,
|
||||
staleTime: 0,
|
||||
}
|
||||
);
|
||||
|
||||
const columnFilters = useColumnFilters();
|
||||
const [rowSelection, setRowSelection] = useState({});
|
||||
|
||||
const removeMemberFromCache = ({
|
||||
utils,
|
||||
memberId,
|
||||
teamId,
|
||||
searchTerm,
|
||||
}: {
|
||||
utils: ReturnType<typeof trpc.useUtils>;
|
||||
memberId: number;
|
||||
teamId: number;
|
||||
searchTerm: string;
|
||||
}) => {
|
||||
utils.viewer.teams.listMembers.setInfiniteData(
|
||||
{
|
||||
limit: 10,
|
||||
teamId,
|
||||
searchTerm,
|
||||
},
|
||||
(data) => {
|
||||
if (!data) {
|
||||
return {
|
||||
pages: [],
|
||||
pageParams: [],
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
...data,
|
||||
pages: data.pages.map((page) => ({
|
||||
...page,
|
||||
members: page.members.filter((member) => member.id !== memberId),
|
||||
})),
|
||||
};
|
||||
}
|
||||
);
|
||||
};
|
||||
|
||||
const removeMemberMutation = trpc.viewer.teams.removeMember.useMutation({
|
||||
onMutate: async ({ teamIds }) => {
|
||||
await utils.viewer.teams.listMembers.cancel();
|
||||
const previousValue = utils.viewer.teams.listMembers.getInfiniteData({
|
||||
limit: 10,
|
||||
teamId: teamIds[0],
|
||||
searchTerm,
|
||||
});
|
||||
|
||||
if (previousValue) {
|
||||
removeMemberFromCache({
|
||||
utils,
|
||||
memberId: state.deleteMember.user?.id as number,
|
||||
teamId: teamIds[0],
|
||||
searchTerm,
|
||||
});
|
||||
}
|
||||
return { previousValue };
|
||||
},
|
||||
async onSuccess() {
|
||||
await utils.viewer.teams.get.invalidate();
|
||||
await utils.viewer.eventTypes.invalidate();
|
||||
await utils.viewer.organizations.listMembers.invalidate();
|
||||
await utils.viewer.organizations.getMembers.invalidate();
|
||||
showToast(t("success"), "success");
|
||||
},
|
||||
async onError(err) {
|
||||
showToast(err.message, "error");
|
||||
},
|
||||
});
|
||||
|
||||
const resendInvitationMutation = trpc.viewer.teams.resendInvitation.useMutation({
|
||||
onSuccess: () => {
|
||||
showToast(t("invitation_resent"), "success");
|
||||
},
|
||||
onError: (error) => {
|
||||
showToast(error.message, "error");
|
||||
},
|
||||
});
|
||||
|
||||
// const ownersInTeam = () => {
|
||||
// const { members } = props.team;
|
||||
// const owners = members.filter((member) => member["role"] === MembershipRole.OWNER && member["accepted"]);
|
||||
// return owners.length;
|
||||
// };
|
||||
|
||||
const removeMember = () =>
|
||||
removeMemberMutation.mutate({
|
||||
teamIds: [props.team?.id],
|
||||
memberIds: [state.deleteMember.user?.id as number],
|
||||
isOrg: checkIsOrg(props.team),
|
||||
});
|
||||
|
||||
const totalRowCount = data?.pages?.[0]?.meta?.totalRowCount ?? 0;
|
||||
|
||||
const memorisedColumns = useMemo(() => {
|
||||
const cols: ColumnDef<User>[] = [
|
||||
// Disabling select for this PR: Will work on actions etc in a follow up
|
||||
{
|
||||
id: "select",
|
||||
enableHiding: false,
|
||||
enableSorting: false,
|
||||
enableResizing: false,
|
||||
size: 30,
|
||||
header: ({ table }) => (
|
||||
<Checkbox
|
||||
checked={table.getIsAllPageRowsSelected()}
|
||||
onCheckedChange={(value) => table.toggleAllPageRowsSelected(!!value)}
|
||||
aria-label="Select all"
|
||||
/>
|
||||
),
|
||||
cell: ({ row }) => (
|
||||
<Checkbox
|
||||
checked={row.getIsSelected()}
|
||||
onCheckedChange={(value) => row.toggleSelected(!!value)}
|
||||
aria-label="Select row"
|
||||
className="translate-y-[2px]"
|
||||
/>
|
||||
),
|
||||
},
|
||||
{
|
||||
id: "member",
|
||||
accessorFn: (data) => data.email,
|
||||
enableHiding: false,
|
||||
header: "Member",
|
||||
size: 250,
|
||||
cell: ({ row }) => {
|
||||
const { username, email, avatarUrl, accepted, name } = row.original;
|
||||
const memberName =
|
||||
name ||
|
||||
(() => {
|
||||
const emailName = email.split("@")[0];
|
||||
return emailName.charAt(0).toUpperCase() + emailName.slice(1);
|
||||
})();
|
||||
return (
|
||||
<div className="flex items-center gap-2">
|
||||
<Avatar
|
||||
size="sm"
|
||||
alt={username || email}
|
||||
imageSrc={getUserAvatarUrl({
|
||||
avatarUrl,
|
||||
})}
|
||||
/>
|
||||
<div data-testid={`member-${username}`}>
|
||||
<div data-testid="member-name" className="text-emphasis text-sm font-medium leading-none">
|
||||
{memberName}
|
||||
</div>
|
||||
<div
|
||||
data-testid={accepted ? "member-email" : `email-${email.replace("@", "")}-pending`}
|
||||
className="text-subtle mt-1 text-sm leading-none">
|
||||
{email}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
},
|
||||
filterFn: (rows, id, filterValue) => {
|
||||
const { data } = filterValue;
|
||||
const userEmail = rows.original.email;
|
||||
return data.includes(userEmail);
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "role",
|
||||
accessorFn: (data) => data.role,
|
||||
header: "Role",
|
||||
size: 100,
|
||||
cell: ({ row, table }) => {
|
||||
const { role, accepted, customRole } = row.original;
|
||||
const roleName = customRole?.name || role;
|
||||
const roleIdentifier = customRole?.id || role;
|
||||
return (
|
||||
<div className="flex h-full flex-wrap items-center gap-2">
|
||||
{!accepted && (
|
||||
<Badge
|
||||
data-testid="member-pending"
|
||||
variant="orange"
|
||||
className="text-xs"
|
||||
onClick={() => {
|
||||
table.getColumn("role")?.setFilterValue(["PENDING"]);
|
||||
}}>
|
||||
Pending
|
||||
</Badge>
|
||||
)}
|
||||
<Badge
|
||||
data-testid="member-role"
|
||||
variant={role === "MEMBER" ? "gray" : "blue"}
|
||||
onClick={() => {
|
||||
table.getColumn("role")?.setFilterValue([roleIdentifier]);
|
||||
}}>
|
||||
{roleName}
|
||||
</Badge>
|
||||
</div>
|
||||
);
|
||||
},
|
||||
filterFn: (rows, id, filterValue) => {
|
||||
const { data } = filterValue;
|
||||
const { role, accepted, customRole } = rows.original;
|
||||
const roleIdentifier = customRole?.id || role;
|
||||
|
||||
if (data.includes("PENDING")) {
|
||||
if (data.length === 1) return !accepted;
|
||||
else return !accepted || data.includes(roleIdentifier);
|
||||
}
|
||||
|
||||
// Show only the selected roles (check both traditional role and custom role ID)
|
||||
return data.includes(roleIdentifier);
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "lastActiveAt",
|
||||
header: "Last Active",
|
||||
cell: ({ row }) => <div>{row.original.lastActiveAt}</div>,
|
||||
},
|
||||
{
|
||||
id: "actions",
|
||||
size: 90,
|
||||
enableResizing: false,
|
||||
cell: ({ row }) => {
|
||||
const user = row.original;
|
||||
const isSelf = user.id === session?.user.id;
|
||||
// TODO(SEAN) In a follow up can we rename canChangeMemberRole to canEditMembers - role is a bit specific.
|
||||
const canChangeRole = props.permissions?.canChangeMemberRole ?? false;
|
||||
const canRemove = props.permissions?.canRemove ?? false;
|
||||
const canImpersonate = props.permissions?.canImpersonate ?? false;
|
||||
const canResendInvitation = props.permissions?.canInvite ?? false;
|
||||
const editMode =
|
||||
[canChangeRole, canRemove, canImpersonate, canResendInvitation].some(Boolean) && !isSelf;
|
||||
|
||||
const impersonationMode =
|
||||
canImpersonate &&
|
||||
!user.disableImpersonation &&
|
||||
user.accepted &&
|
||||
process.env.NEXT_PUBLIC_TEAM_IMPERSONATION === "true";
|
||||
return (
|
||||
<>
|
||||
{props.team.membership?.accepted && (
|
||||
<div className="flex items-center justify-end">
|
||||
<ButtonGroup combined containerProps={{ className: "border-default hidden md:flex" }}>
|
||||
{/* TODO: bring availability back. right now its ugly and broken
|
||||
<Tooltip
|
||||
content={
|
||||
user.accepted
|
||||
? t("team_view_user_availability")
|
||||
: t("team_view_user_availability_disabled")
|
||||
}>
|
||||
<Button
|
||||
disabled={!user.accepted}
|
||||
onClick={() =>
|
||||
user.accepted
|
||||
? dispatch({
|
||||
type: "TEAM_AVAILABILITY",
|
||||
payload: {
|
||||
user,
|
||||
showModal: true,
|
||||
},
|
||||
})
|
||||
: null
|
||||
}
|
||||
color="secondary"
|
||||
variant="icon"
|
||||
StartIcon="clock"
|
||||
/>
|
||||
</Tooltip> */}
|
||||
{!!user.accepted && (
|
||||
<Tooltip content={t("view_public_page")}>
|
||||
<Button
|
||||
target="_blank"
|
||||
href={`${user.bookerUrl}/${user.username}`}
|
||||
color="secondary"
|
||||
className={classNames(!editMode ? "rounded-r-md" : "")}
|
||||
variant="icon"
|
||||
StartIcon="external-link"
|
||||
disabled={!user.accepted}
|
||||
/>
|
||||
</Tooltip>
|
||||
)}
|
||||
{editMode && (
|
||||
<Dropdown>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button
|
||||
className="ltr:radix-state-open:rounded-r-(--btn-group-radius) rtl:radix-state-open:rounded-l-(--btn-group-radius)"
|
||||
color="secondary"
|
||||
variant="icon"
|
||||
StartIcon="ellipsis"
|
||||
/>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuPortal>
|
||||
<DropdownMenuContent>
|
||||
{canChangeRole ? (
|
||||
<DropdownMenuItem>
|
||||
<DropdownItem
|
||||
type="button"
|
||||
onClick={() =>
|
||||
dispatch({
|
||||
type: "EDIT_USER_SHEET",
|
||||
payload: {
|
||||
user,
|
||||
showModal: true,
|
||||
},
|
||||
})
|
||||
}
|
||||
StartIcon="pencil">
|
||||
{t("edit")}
|
||||
</DropdownItem>
|
||||
</DropdownMenuItem>
|
||||
) : null}
|
||||
{impersonationMode && (
|
||||
<>
|
||||
<DropdownMenuItem>
|
||||
<DropdownItem
|
||||
type="button"
|
||||
onClick={() =>
|
||||
dispatch({
|
||||
type: "SET_IMPERSONATE_ID",
|
||||
payload: {
|
||||
user,
|
||||
showModal: true,
|
||||
},
|
||||
})
|
||||
}
|
||||
StartIcon="lock">
|
||||
{t("impersonate")}
|
||||
</DropdownItem>
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuSeparator />
|
||||
</>
|
||||
)}
|
||||
{canResendInvitation && (
|
||||
<DropdownMenuItem>
|
||||
<DropdownItem
|
||||
type="button"
|
||||
onClick={() => {
|
||||
resendInvitationMutation.mutate({
|
||||
teamId: props.team?.id,
|
||||
email: user.email,
|
||||
language: i18n.language,
|
||||
});
|
||||
}}
|
||||
StartIcon="send">
|
||||
{t("resend_invitation")}
|
||||
</DropdownItem>
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
{canRemove ? (
|
||||
<DropdownMenuItem>
|
||||
<DropdownItem
|
||||
type="button"
|
||||
onClick={() =>
|
||||
dispatch({
|
||||
type: "SET_DELETE_ID",
|
||||
payload: {
|
||||
user,
|
||||
showModal: true,
|
||||
},
|
||||
})
|
||||
}
|
||||
color="destructive"
|
||||
StartIcon="user-x">
|
||||
{t("remove")}
|
||||
</DropdownItem>
|
||||
</DropdownMenuItem>
|
||||
) : null}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenuPortal>
|
||||
</Dropdown>
|
||||
)}
|
||||
</ButtonGroup>
|
||||
<div className="flex md:hidden">
|
||||
<Dropdown>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button type="button" variant="icon" color="minimal" StartIcon="ellipsis" />
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuPortal>
|
||||
<DropdownMenuContent>
|
||||
<DropdownMenuItem className="outline-none">
|
||||
<DropdownItem
|
||||
disabled={!user.accepted}
|
||||
href={!user.accepted ? undefined : `/${user.username}`}
|
||||
target="_blank"
|
||||
type="button"
|
||||
StartIcon="external-link">
|
||||
{t("view_public_page")}
|
||||
</DropdownItem>
|
||||
</DropdownMenuItem>
|
||||
{editMode && (
|
||||
<>
|
||||
<DropdownMenuItem>
|
||||
<DropdownItem
|
||||
type="button"
|
||||
onClick={() =>
|
||||
dispatch({
|
||||
type: "EDIT_USER_SHEET",
|
||||
payload: {
|
||||
user,
|
||||
showModal: true,
|
||||
},
|
||||
})
|
||||
}
|
||||
StartIcon="pencil">
|
||||
{t("edit")}
|
||||
</DropdownItem>
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem>
|
||||
<DropdownItem
|
||||
type="button"
|
||||
color="destructive"
|
||||
onClick={() =>
|
||||
dispatch({
|
||||
type: "SET_DELETE_ID",
|
||||
payload: {
|
||||
user,
|
||||
showModal: true,
|
||||
},
|
||||
})
|
||||
}
|
||||
StartIcon="user-x">
|
||||
{t("remove")}
|
||||
</DropdownItem>
|
||||
</DropdownMenuItem>
|
||||
</>
|
||||
)}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenuPortal>
|
||||
</Dropdown>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
return cols;
|
||||
}, [props.isOrgAdminOrOwner, dispatch, totalRowCount, session?.user.id]);
|
||||
//we must flatten the array of arrays from the useInfiniteQuery hook
|
||||
const flatData = useMemo(() => data?.pages?.flatMap((page) => page.members) ?? [], [data]) as User[];
|
||||
|
||||
const table = useReactTable({
|
||||
data: flatData,
|
||||
columns: memorisedColumns,
|
||||
enableRowSelection: true,
|
||||
debugTable: true,
|
||||
manualPagination: true,
|
||||
initialState: {
|
||||
columnVisibility: initalColumnVisibility,
|
||||
columnPinning: {
|
||||
right: ["actions"],
|
||||
},
|
||||
},
|
||||
state: {
|
||||
columnFilters,
|
||||
rowSelection,
|
||||
},
|
||||
onRowSelectionChange: setRowSelection,
|
||||
getCoreRowModel: getCoreRowModel(),
|
||||
getFilteredRowModel: getFilteredRowModel(),
|
||||
getSortedRowModel: getSortedRowModel(),
|
||||
getFacetedUniqueValues: (_, columnId) => () => {
|
||||
if (facetedTeamValues) {
|
||||
switch (columnId) {
|
||||
case "role": {
|
||||
// Include both traditional roles and PBAC custom roles
|
||||
const allRoles = facetedTeamValues.roles.map((role) => ({
|
||||
label: role.name,
|
||||
value: role.id,
|
||||
}));
|
||||
|
||||
return convertFacetedValuesToMap(allRoles);
|
||||
}
|
||||
default:
|
||||
return new Map();
|
||||
}
|
||||
}
|
||||
return new Map();
|
||||
},
|
||||
getRowId: (row) => `${row.id}`,
|
||||
});
|
||||
|
||||
useFetchMoreOnBottomReached({
|
||||
tableContainerRef,
|
||||
hasNextPage,
|
||||
fetchNextPage,
|
||||
isFetching,
|
||||
});
|
||||
|
||||
const numberOfSelectedRows = table.getSelectedRowModel().rows.length;
|
||||
|
||||
return (
|
||||
<>
|
||||
<DataTableWrapper
|
||||
testId="team-member-list-container"
|
||||
table={table}
|
||||
tableContainerRef={tableContainerRef}
|
||||
isPending={isPending}
|
||||
enableColumnResizing={true}
|
||||
paginationMode="infinite"
|
||||
hasNextPage={hasNextPage}
|
||||
fetchNextPage={fetchNextPage}
|
||||
isFetching={isFetching}
|
||||
totalRowCount={totalRowCount}
|
||||
ToolbarLeft={
|
||||
<>
|
||||
<DataTableToolbar.SearchBar />
|
||||
<DataTableFilters.ColumnVisibilityButton table={table} />
|
||||
<DataTableFilters.FilterBar table={table} />
|
||||
</>
|
||||
}
|
||||
ToolbarRight={
|
||||
<>
|
||||
<DataTableFilters.ClearFiltersButton />
|
||||
{props.permissions.canInvite && (
|
||||
<DataTableToolbar.CTA
|
||||
type="button"
|
||||
color="primary"
|
||||
StartIcon="plus"
|
||||
onClick={() => { props.setShowMemberInvitationModal(true); posthog.capture("teams_add_new_members_button_clicked") }}
|
||||
data-testid="new-member-button">
|
||||
{t("add")}
|
||||
</DataTableToolbar.CTA>
|
||||
)}
|
||||
</>
|
||||
}>
|
||||
{numberOfSelectedRows >= 2 && dynamicLinkVisible && (
|
||||
<DataTableSelectionBar.Root className="bottom-[7.3rem]! md:bottom-32!">
|
||||
<DynamicLink table={table} domain={domain} />
|
||||
</DataTableSelectionBar.Root>
|
||||
)}
|
||||
{numberOfSelectedRows > 0 && (
|
||||
<DataTableSelectionBar.Root className="bottom-16! justify-center md:w-max">
|
||||
<p className="text-brand-subtle px-2 text-center text-xs leading-none sm:text-sm sm:font-medium">
|
||||
{t("number_selected", { count: numberOfSelectedRows })}
|
||||
</p>
|
||||
{numberOfSelectedRows >= 2 && (
|
||||
<DataTableSelectionBar.Button
|
||||
color="secondary"
|
||||
onClick={() => setDynamicLinkVisible(!dynamicLinkVisible)}
|
||||
icon="handshake">
|
||||
{t("group_meeting")}
|
||||
</DataTableSelectionBar.Button>
|
||||
)}
|
||||
<EventTypesList table={table} teamId={props.team.id} />
|
||||
<DeleteBulkTeamMembers
|
||||
users={table.getSelectedRowModel().flatRows.map((row) => row.original)}
|
||||
onRemove={() => table.toggleAllPageRowsSelected(false)}
|
||||
isOrg={checkIsOrg(props.team)}
|
||||
teamId={props.team.id}
|
||||
/>
|
||||
</DataTableSelectionBar.Root>
|
||||
)}
|
||||
</DataTableWrapper>
|
||||
{state.deleteMember.showModal && (
|
||||
<Dialog
|
||||
open={true}
|
||||
onOpenChange={(open) =>
|
||||
!open &&
|
||||
dispatch({
|
||||
type: "CLOSE_MODAL",
|
||||
})
|
||||
}>
|
||||
<ConfirmationDialogContent
|
||||
variety="danger"
|
||||
title={t("remove_member")}
|
||||
confirmBtnText={t("confirm_remove_member")}
|
||||
onConfirm={removeMember}>
|
||||
{t("remove_member_confirmation_message")}
|
||||
</ConfirmationDialogContent>
|
||||
</Dialog>
|
||||
)}
|
||||
|
||||
{state.impersonateMember.showModal && state.impersonateMember.user?.username && (
|
||||
<Dialog
|
||||
open={true}
|
||||
onOpenChange={() =>
|
||||
dispatch({
|
||||
type: "CLOSE_MODAL",
|
||||
})
|
||||
}>
|
||||
<DialogContent type="creation" title={t("impersonate")} description={t("impersonation_user_tip")}>
|
||||
<form
|
||||
onSubmit={async (e) => {
|
||||
e.preventDefault();
|
||||
await signIn("impersonation-auth", {
|
||||
username: state.impersonateMember.user?.email,
|
||||
teamId: props.team.id,
|
||||
});
|
||||
dispatch({
|
||||
type: "CLOSE_MODAL",
|
||||
});
|
||||
}}>
|
||||
<DialogFooter showDivider className="mt-8">
|
||||
<DialogClose color="secondary">{t("cancel")}</DialogClose>
|
||||
<Button color="primary" type="submit">
|
||||
{t("impersonate")}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)}
|
||||
{state.teamAvailability.showModal && (
|
||||
<Dialog
|
||||
open={true}
|
||||
onOpenChange={() => {
|
||||
dispatch({
|
||||
type: "CLOSE_MODAL",
|
||||
});
|
||||
}}>
|
||||
<DialogContent type="creation" size="md">
|
||||
<TeamAvailabilityModal team={props.team} member={state.teamAvailability.user} />
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)}
|
||||
{state.editSheet.showModal && (
|
||||
<EditMemberSheet
|
||||
dispatch={dispatch}
|
||||
state={state}
|
||||
currentMember={props.team.membership.role}
|
||||
teamId={props.team.id}
|
||||
permissions={props.permissions}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -1,54 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { Controller } from "react-hook-form";
|
||||
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { RRResetInterval } from "@calcom/prisma/enums";
|
||||
import { Select } from "@calcom/ui/components/form";
|
||||
|
||||
const RoundRobinResetInterval = () => {
|
||||
const { t } = useLocale();
|
||||
|
||||
const intervalOptions: {
|
||||
value: RRResetInterval;
|
||||
label: string;
|
||||
}[] = [
|
||||
{
|
||||
value: RRResetInterval.MONTH,
|
||||
label: t("monthly"),
|
||||
},
|
||||
{
|
||||
value: RRResetInterval.DAY,
|
||||
label: t("daily"),
|
||||
},
|
||||
];
|
||||
|
||||
return (
|
||||
<Controller
|
||||
name="rrResetInterval"
|
||||
render={({ field: { value, onChange } }) => {
|
||||
return (
|
||||
<>
|
||||
<div className="">
|
||||
<h4 className="text-emphasis text-sm font-semibold leading-5">
|
||||
{t("reset_interval_weighted_rr")}
|
||||
</h4>
|
||||
<p className="text-default text-sm">{t("rr_reset_interval_description")}</p>
|
||||
<div className="mt-4 w-48">
|
||||
<Select
|
||||
options={intervalOptions}
|
||||
value={intervalOptions.find((opt) => opt.value === value)}
|
||||
onChange={(val) => {
|
||||
onChange(val?.value);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
export default RoundRobinResetInterval;
|
||||
@@ -1,106 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { useForm } from "react-hook-form";
|
||||
|
||||
import { checkAdminOrOwner } from "@calcom/features/auth/lib/checkAdminOrOwner";
|
||||
import SectionBottomActions from "@calcom/features/settings/SectionBottomActions";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { RRResetInterval, RRTimestampBasis } from "@calcom/prisma/enums";
|
||||
import type { RouterOutputs } from "@calcom/trpc/react";
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
import { Button } from "@calcom/ui/components/button";
|
||||
import { Form } from "@calcom/ui/components/form";
|
||||
import { showToast } from "@calcom/ui/components/toast";
|
||||
import { revalidateTeamDataCache } from "@calcom/web/app/(booking-page-wrapper)/team/[slug]/[type]/actions";
|
||||
|
||||
import RoundRobinResetInterval from "./RoundRobinResetInterval";
|
||||
import RoundRobinTimestampBasis from "./RoundRobinTimestampBasis";
|
||||
|
||||
interface RoundRobinSettingsProps {
|
||||
team: RouterOutputs["viewer"]["teams"]["get"];
|
||||
}
|
||||
|
||||
const RoundRobinSettings = ({ team }: RoundRobinSettingsProps) => {
|
||||
const { t } = useLocale();
|
||||
const isAdmin = team && checkAdminOrOwner(team.membership.role);
|
||||
const rrResetInterval = team?.rrResetInterval ?? undefined;
|
||||
const utils = trpc.useUtils();
|
||||
|
||||
const initialResetInterval = rrResetInterval ?? RRResetInterval.MONTH;
|
||||
const initialTimestampBasis = team?.rrTimestampBasis ?? RRTimestampBasis.CREATED_AT;
|
||||
|
||||
const form = useForm<{ rrResetInterval: RRResetInterval; rrTimestampBasis: RRTimestampBasis }>({
|
||||
defaultValues: {
|
||||
rrResetInterval: initialResetInterval,
|
||||
rrTimestampBasis: initialTimestampBasis,
|
||||
},
|
||||
});
|
||||
|
||||
const [watchedResetInterval, watchedTimestampBasis] = form.watch([
|
||||
"rrResetInterval",
|
||||
"rrTimestampBasis",
|
||||
]);
|
||||
const hasChanges =
|
||||
watchedResetInterval !== initialResetInterval || watchedTimestampBasis !== initialTimestampBasis;
|
||||
|
||||
const mutation = trpc.viewer.teams.update.useMutation({
|
||||
onError: (err) => {
|
||||
showToast(err.message, "error");
|
||||
},
|
||||
async onSuccess() {
|
||||
await utils.viewer.teams.get.invalidate();
|
||||
if (team?.slug) {
|
||||
// Rounb robin reset interval / basis governs host selection logic on the booking page.
|
||||
revalidateTeamDataCache({
|
||||
teamSlug: team.slug,
|
||||
orgSlug: team.parent?.slug ?? null,
|
||||
});
|
||||
}
|
||||
showToast(t("round_robin_settings_updated_successfully"), "success");
|
||||
},
|
||||
});
|
||||
|
||||
if (!isAdmin) {
|
||||
return (
|
||||
<div className="border-subtle rounded-md border p-5">
|
||||
<span className="text-default text-sm">{t("only_owner_change")}</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Form
|
||||
form={form}
|
||||
handleSubmit={(values) => {
|
||||
mutation.mutate({
|
||||
id: team.id,
|
||||
rrResetInterval: values.rrResetInterval,
|
||||
rrTimestampBasis: values.rrTimestampBasis,
|
||||
});
|
||||
}}>
|
||||
<div className="border-subtle mt-6 space-x-3 rounded-t-lg border border-b-0 px-4 py-6 pb-0 sm:px-6">
|
||||
{" "}
|
||||
<div>
|
||||
<h4 className="text-emphasis text-sm font-semibold leading-5">{t("round_robin")}</h4>
|
||||
<p className="text-default text-sm leading-tight">{t("round_robin_settings_description")}</p>
|
||||
<div className="-mx-4 mt-4 sm:-mx-6">
|
||||
<div className="border-subtle border-t px-6 py-6">
|
||||
<RoundRobinResetInterval />
|
||||
</div>
|
||||
<div className="border-subtle border-t" />
|
||||
<div className="border-subtle px-6 py-6">
|
||||
<RoundRobinTimestampBasis />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<SectionBottomActions align="end">
|
||||
<Button type="submit" disabled={!hasChanges} color="primary" loading={mutation.isPending}>
|
||||
{t("update")}
|
||||
</Button>
|
||||
</SectionBottomActions>
|
||||
</Form>
|
||||
);
|
||||
};
|
||||
|
||||
export default RoundRobinSettings;
|
||||
@@ -1,55 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { Controller } from "react-hook-form";
|
||||
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { RRTimestampBasis } from "@calcom/prisma/enums";
|
||||
import { Select } from "@calcom/ui/components/form";
|
||||
|
||||
const RoundRobinTimestampBasis = () => {
|
||||
const { t } = useLocale();
|
||||
|
||||
const timestampBasisOptions: {
|
||||
value: RRTimestampBasis;
|
||||
label: string;
|
||||
}[] = [
|
||||
{
|
||||
value: RRTimestampBasis.CREATED_AT,
|
||||
label: t("booking_creation_time"),
|
||||
},
|
||||
{
|
||||
value: RRTimestampBasis.START_TIME,
|
||||
label: t("meeting_start_time"),
|
||||
},
|
||||
];
|
||||
return (
|
||||
<Controller
|
||||
name="rrTimestampBasis"
|
||||
render={({ field: { value, onChange } }) => {
|
||||
return (
|
||||
<>
|
||||
<h4 className="text-emphasis text-sm font-semibold leading-5">
|
||||
{t("distribution_basis_weighted_rr")}
|
||||
</h4>
|
||||
<p className="text-default text-sm leading-tight">{t("timestamp_basis_description")}</p>
|
||||
<div className="mt-4 w-52">
|
||||
<Select
|
||||
options={timestampBasisOptions}
|
||||
value={timestampBasisOptions.find((opt) => opt.value === value)}
|
||||
onChange={(val) => {
|
||||
onChange(val?.value);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{value !== RRTimestampBasis.CREATED_AT && (
|
||||
<p className="text-attention mt-2 text-sm">{t("load_balancing_warning")}</p>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
export default RoundRobinTimestampBasis;
|
||||
@@ -1,15 +0,0 @@
|
||||
import { SkeletonText, SkeletonContainer } from "@calcom/ui/components/skeleton";
|
||||
|
||||
function SkeletonLoader() {
|
||||
return (
|
||||
<SkeletonContainer>
|
||||
<div className="mr-3">
|
||||
<SkeletonText className="h-4 w-28" />
|
||||
<SkeletonText className="mt-3 h-11 w-full" />
|
||||
<SkeletonText className="mt-2 h-11 w-full" />
|
||||
</div>
|
||||
</SkeletonContainer>
|
||||
);
|
||||
}
|
||||
|
||||
export default SkeletonLoader;
|
||||
@@ -1,40 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { SkeletonText } from "@calcom/ui/components/skeleton";
|
||||
|
||||
function SkeletonLoaderTeamList() {
|
||||
return (
|
||||
<div className="w-full">
|
||||
<ul className="bg-default divide-subtle border-subtle divide-y overflow-hidden rounded-md border">
|
||||
<SkeletonItem />
|
||||
<SkeletonItem />
|
||||
<SkeletonItem />
|
||||
</ul>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default SkeletonLoaderTeamList;
|
||||
|
||||
function SkeletonItem() {
|
||||
return (
|
||||
<li className="flex w-full items-center justify-between">
|
||||
<div className="flex items-center space-x-3 p-5 rtl:space-x-reverse">
|
||||
<SkeletonText className="h-8 w-8 rounded-full" />
|
||||
<div className="flex flex-col stack-y-2">
|
||||
<SkeletonText className="h-4 w-32" />
|
||||
<SkeletonText className="h-3 w-24" />
|
||||
</div>
|
||||
</div>
|
||||
<div className="p-5">
|
||||
<div className="flex items-center space-x-2 rtl:space-x-reverse">
|
||||
<SkeletonText className="h-4 w-16" />
|
||||
<div className="flex space-x-2 rtl:space-x-reverse">
|
||||
<SkeletonText className="h-8 w-8 rounded" />
|
||||
<SkeletonText className="h-8 w-8 rounded" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</li>
|
||||
);
|
||||
}
|
||||
@@ -1,107 +0,0 @@
|
||||
import { useEffect, useState } from "react";
|
||||
|
||||
import dayjs from "@calcom/dayjs";
|
||||
import { TimezoneSelect } from "@calcom/features/components/timezone-select";
|
||||
import type { ITimezone } from "@calcom/features/components/timezone-select";
|
||||
import LicenseRequired from "@calcom/features/ee/common/components/LicenseRequired";
|
||||
import { WEBAPP_URL } from "@calcom/lib/constants";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { CURRENT_TIMEZONE } from "@calcom/lib/timezoneConstants";
|
||||
import type { RouterOutputs } from "@calcom/trpc/react";
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
import { Avatar } from "@calcom/ui/components/avatar";
|
||||
import { Select, DatePicker } from "@calcom/ui/components/form";
|
||||
import { Label } from "@calcom/ui/components/form";
|
||||
|
||||
import TeamAvailabilityTimes from "./TeamAvailabilityTimes";
|
||||
|
||||
interface Props {
|
||||
team?: RouterOutputs["viewer"]["teams"]["get"];
|
||||
member?: RouterOutputs["viewer"]["teams"]["listMembers"]["members"][number];
|
||||
}
|
||||
|
||||
export default function TeamAvailabilityModal(props: Props) {
|
||||
const utils = trpc.useUtils();
|
||||
const [selectedDate, setSelectedDate] = useState(dayjs());
|
||||
const [selectedTimeZone, setSelectedTimeZone] = useState<ITimezone>(
|
||||
localStorage.getItem("timeOption.preferredTimeZone") || CURRENT_TIMEZONE
|
||||
);
|
||||
|
||||
const { t } = useLocale();
|
||||
|
||||
const [frequency, setFrequency] = useState<15 | 30 | 60>(30);
|
||||
|
||||
useEffect(() => {
|
||||
utils.viewer.teams.getMemberAvailability.invalidate();
|
||||
}, [utils, selectedTimeZone, selectedDate]);
|
||||
|
||||
return (
|
||||
<LicenseRequired>
|
||||
<>
|
||||
<div className="grid h-[400px] grid-cols-2 space-x-11 rtl:space-x-reverse">
|
||||
<div className="col-span-1">
|
||||
<div className="flex">
|
||||
<Avatar
|
||||
size="md"
|
||||
imageSrc={`${WEBAPP_URL}/${props.member?.username}/avatar.png`}
|
||||
alt={props.member?.name || ""}
|
||||
/>
|
||||
<div className="flex items-center justify-center ">
|
||||
<span className="text-subtle ml-2 text-base font-semibold leading-4">
|
||||
{props.member?.name}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<div className="text-brand-900 mb-5 mt-4 text-2xl font-semibold">{t("availability")}</div>
|
||||
<DatePicker
|
||||
minDate={new Date()}
|
||||
date={selectedDate.toDate() || dayjs().toDate()}
|
||||
onDatesChange={(newDate) => {
|
||||
setSelectedDate(dayjs(newDate));
|
||||
}}
|
||||
/>
|
||||
|
||||
<Label className="mt-4">{t("timezone")}</Label>
|
||||
<TimezoneSelect
|
||||
id="timeZone"
|
||||
autoFocus
|
||||
value={selectedTimeZone}
|
||||
className="w-64 rounded-md"
|
||||
onChange={(timezone) => setSelectedTimeZone(timezone.value)}
|
||||
classNamePrefix="react-select"
|
||||
/>
|
||||
</div>
|
||||
<div className="mt-3">
|
||||
<Label>{t("slot_length")}</Label>
|
||||
<Select
|
||||
options={[
|
||||
{ value: 15, label: "15 minutes" },
|
||||
{ value: 30, label: "30 minutes" },
|
||||
{ value: 60, label: "60 minutes" },
|
||||
]}
|
||||
isSearchable={false}
|
||||
classNamePrefix="react-select"
|
||||
className="w-64"
|
||||
value={{ value: frequency, label: `${frequency} minutes` }}
|
||||
onChange={(newFrequency) => setFrequency(newFrequency?.value ?? 30)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="col-span-1 max-h-[500px]">
|
||||
{props.team?.id && props.member && (
|
||||
<TeamAvailabilityTimes
|
||||
teamId={props.team.id}
|
||||
memberId={props.member.id}
|
||||
frequency={frequency}
|
||||
selectedDate={selectedDate}
|
||||
selectedTimeZone={selectedTimeZone}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
</LicenseRequired>
|
||||
);
|
||||
}
|
||||
@@ -1,80 +0,0 @@
|
||||
/* eslint-disable @typescript-eslint/ban-ts-comment */
|
||||
// @ts-nocheck
|
||||
|
||||
/* eslint-enable @typescript-eslint/ban-ts-comment */
|
||||
// TODO: Currently this file is not type checked as it's deprecated
|
||||
// it must be refactored if we want to restore TeamAvailability
|
||||
import classNames from "classnames";
|
||||
import React from "react";
|
||||
import type { ITimezone } from "react-timezone-select";
|
||||
|
||||
import type { Dayjs } from "@calcom/dayjs";
|
||||
import getSlots from "@calcom/features/schedules/lib/slots";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
|
||||
import SkeletonLoader from "./SkeletonLoaderAvailabilityTimes";
|
||||
|
||||
interface Props {
|
||||
teamId: number;
|
||||
memberId: number;
|
||||
selectedDate: Dayjs;
|
||||
selectedTimeZone: ITimezone;
|
||||
frequency: number;
|
||||
HeaderComponent?: React.ReactNode;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export default function TeamAvailabilityTimes(props: Props) {
|
||||
const { t } = useLocale();
|
||||
|
||||
const { data, isPending } = trpc.viewer.teams.getMemberAvailability.useQuery(
|
||||
{
|
||||
teamId: props.teamId,
|
||||
memberId: props.memberId,
|
||||
dateFrom: props.selectedDate.toString(),
|
||||
dateTo: props.selectedDate.add(1, "day").toString(),
|
||||
timezone: `${props.selectedTimeZone.toString()}`,
|
||||
},
|
||||
{
|
||||
refetchOnWindowFocus: false,
|
||||
}
|
||||
);
|
||||
|
||||
const slots = !isPending
|
||||
? getSlots({
|
||||
frequency: props.frequency,
|
||||
inviteeDate: props.selectedDate,
|
||||
workingHours: data?.workingHours || [],
|
||||
minimumBookingNotice: 0,
|
||||
offsetStart: 0,
|
||||
eventLength: props.frequency,
|
||||
organizerTimeZone: `${data?.timeZone}`,
|
||||
})
|
||||
: [];
|
||||
|
||||
return (
|
||||
<div className={classNames("min-w-60 grow pl-0", props.className)}>
|
||||
{props.HeaderComponent}
|
||||
{isPending && slots.length === 0 && <SkeletonLoader />}
|
||||
{!isPending && slots.length === 0 ? (
|
||||
<div className="flex flex-col items-center justify-center pt-4">
|
||||
<span className="text-subtle text-sm">{t("no_available_slots")}</span>
|
||||
</div>
|
||||
) : (
|
||||
<>{!isPending && <p className="text-default mb-3 text-sm">{t("time_available")}</p>}</>
|
||||
)}
|
||||
<div className="max-h-[390px] overflow-scroll">
|
||||
{slots.map((slot) => (
|
||||
<div key={slot.time.format()} className="flex flex-row items-center ">
|
||||
<a
|
||||
className="min-w-48 border-brand-default text-bookingdarker bg-default mb-2 mr-3 block grow rounded-md border py-2 text-center font-medium dark:border-transparent dark:bg-gray-600 "
|
||||
data-testid="time">
|
||||
{slot.time.tz(props.selectedTimeZone.toString()).format("HH:mm")}
|
||||
</a>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,164 +0,0 @@
|
||||
import type { ReactNode } from "react";
|
||||
import type { UseFormReturn } from "react-hook-form";
|
||||
|
||||
import { useIsPlatform } from "@calcom/atoms/hooks/useIsPlatform";
|
||||
import type { CreateEventTypeFormValues } from "@calcom/features/eventtypes/hooks/useCreateEventType";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import slugify from "@calcom/lib/slugify";
|
||||
import { SchedulingType } from "@calcom/prisma/enums";
|
||||
import classNames from "@calcom/ui/classNames";
|
||||
import { Alert } from "@calcom/ui/components/alert";
|
||||
import { Form } from "@calcom/ui/components/form";
|
||||
import { TextField } from "@calcom/ui/components/form";
|
||||
import { RadioAreaGroup as RadioArea } from "@calcom/ui/components/radio";
|
||||
import { Tooltip } from "@calcom/ui/components/tooltip";
|
||||
|
||||
type props = {
|
||||
permissions: {
|
||||
canCreateEventType: boolean;
|
||||
};
|
||||
teamSlug?: string | null;
|
||||
teamId: number;
|
||||
isPending: boolean;
|
||||
urlPrefix?: string;
|
||||
form: UseFormReturn<CreateEventTypeFormValues>;
|
||||
handleSubmit: (values: CreateEventTypeFormValues) => void;
|
||||
isManagedEventType: boolean;
|
||||
SubmitButton: (isPending: boolean) => ReactNode;
|
||||
};
|
||||
export const TeamEventTypeForm = ({
|
||||
permissions,
|
||||
teamSlug,
|
||||
teamId,
|
||||
form,
|
||||
urlPrefix,
|
||||
isPending,
|
||||
handleSubmit,
|
||||
isManagedEventType,
|
||||
SubmitButton,
|
||||
}: props) => {
|
||||
const isPlatform = useIsPlatform();
|
||||
|
||||
const { t } = useLocale();
|
||||
|
||||
const { register, setValue, formState } = form;
|
||||
const { canCreateEventType } = permissions;
|
||||
|
||||
return (
|
||||
<Form form={form} handleSubmit={handleSubmit}>
|
||||
<div className="mb-6 mt-1 stack-y-6">
|
||||
<TextField
|
||||
type="hidden"
|
||||
labelProps={{ style: { display: "none" } }}
|
||||
{...register("teamId", { valueAsNumber: true })}
|
||||
value={teamId}
|
||||
/>
|
||||
<TextField
|
||||
label={t("title")}
|
||||
placeholder={t("quick_chat")}
|
||||
data-testid="event-type-quick-chat"
|
||||
{...register("title")}
|
||||
onChange={(e) => {
|
||||
form.setValue("title", e?.target.value);
|
||||
if (formState.touchedFields["slug"] === undefined) {
|
||||
form.setValue("slug", slugify(e?.target.value));
|
||||
}
|
||||
}}
|
||||
/>
|
||||
{urlPrefix && urlPrefix.length >= 21 ? (
|
||||
<div>
|
||||
<TextField
|
||||
label={isPlatform ? "Slug" : `${t("url")}: ${urlPrefix}`}
|
||||
required
|
||||
addOnLeading={
|
||||
!isPlatform ? (
|
||||
<Tooltip content={!isManagedEventType ? `team/${teamSlug}` : t("username_placeholder")}>
|
||||
<span className="max-w-24 md:max-w-56">
|
||||
/{!isManagedEventType ? `team/${teamSlug}` : t("username_placeholder")}/
|
||||
</span>
|
||||
</Tooltip>
|
||||
) : undefined
|
||||
}
|
||||
{...register("slug")}
|
||||
onChange={(e) => {
|
||||
form.setValue("slug", slugify(e?.target.value), { shouldTouch: true });
|
||||
}}
|
||||
/>
|
||||
|
||||
{isManagedEventType && !isPlatform && (
|
||||
<p className="mt-2 text-sm text-gray-600">{t("managed_event_url_clarification")}</p>
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
<div>
|
||||
<TextField
|
||||
label={isPlatform ? "Slug" : t("url")}
|
||||
required
|
||||
addOnLeading={
|
||||
!isPlatform ? (
|
||||
<Tooltip
|
||||
content={`${urlPrefix}/${
|
||||
!isManagedEventType ? `team/${teamSlug}` : t("username_placeholder")
|
||||
}/`}>
|
||||
<span className="max-w-24 md:max-w-56">
|
||||
{urlPrefix}/{!isManagedEventType ? `team/${teamSlug}` : t("username_placeholder")}/
|
||||
</span>
|
||||
</Tooltip>
|
||||
) : undefined
|
||||
}
|
||||
{...register("slug")}
|
||||
onChange={(e) => {
|
||||
form.setValue("slug", slugify(e?.target.value), { shouldTouch: true });
|
||||
}}
|
||||
/>
|
||||
{isManagedEventType && !isPlatform && (
|
||||
<p className="mt-2 text-sm text-gray-600">{t("managed_event_url_clarification")}</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
<div className="mb-4">
|
||||
<label htmlFor="schedulingType" className="text-default block text-sm font-bold">
|
||||
{t("assignment")}
|
||||
</label>
|
||||
{formState.errors.schedulingType && (
|
||||
<Alert className="mt-1" severity="error" message={formState.errors.schedulingType.message} />
|
||||
)}
|
||||
<RadioArea.Group
|
||||
onValueChange={(val: SchedulingType) => {
|
||||
setValue("schedulingType", val);
|
||||
}}
|
||||
className={classNames("mt-1 flex gap-4", canCreateEventType && "flex-col")}>
|
||||
<RadioArea.Item
|
||||
{...register("schedulingType")}
|
||||
value={SchedulingType.COLLECTIVE}
|
||||
className={classNames("w-full text-sm", !canCreateEventType && "w-1/2")}
|
||||
classNames={{ container: classNames(canCreateEventType && "w-full") }}>
|
||||
<strong className="mb-1 block">{t("collective")}</strong>
|
||||
<p>{t("collective_description")}</p>
|
||||
</RadioArea.Item>
|
||||
<RadioArea.Item
|
||||
{...register("schedulingType")}
|
||||
value={SchedulingType.ROUND_ROBIN}
|
||||
className={classNames("text-sm", !canCreateEventType && "w-1/2")}
|
||||
classNames={{ container: classNames(canCreateEventType && "w-full") }}>
|
||||
<strong className="mb-1 block">{t("round_robin")}</strong>
|
||||
<p>{t("round_robin_description")}</p>
|
||||
</RadioArea.Item>
|
||||
{canCreateEventType && (
|
||||
<RadioArea.Item
|
||||
{...register("schedulingType")}
|
||||
value={SchedulingType.MANAGED}
|
||||
className={classNames("text-sm", !canCreateEventType && "w-1/2")}
|
||||
classNames={{ container: classNames(canCreateEventType && "w-full") }}
|
||||
data-testid="managed-event-type">
|
||||
<strong className="mb-1 block">{t("managed_event")}</strong>
|
||||
<p>{t("managed_event_description")}</p>
|
||||
</RadioArea.Item>
|
||||
)}
|
||||
</RadioArea.Group>
|
||||
</div>
|
||||
</div>
|
||||
{SubmitButton(isPending)}
|
||||
</Form>
|
||||
);
|
||||
};
|
||||
@@ -1,70 +0,0 @@
|
||||
import { useState } from "react";
|
||||
|
||||
import { trackFormbricksAction } from "@calcom/features/formbricks/formbricks-client";
|
||||
import type { MembershipRole } from "@calcom/prisma/enums";
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
import { showToast } from "@calcom/ui/components/toast";
|
||||
import { revalidateTeamsList } from "@calcom/web/app/(use-page-wrapper)/(main-nav)/teams/actions";
|
||||
|
||||
import TeamInviteListItem from "./TeamInviteListItem";
|
||||
|
||||
interface Props {
|
||||
teams: {
|
||||
id?: number;
|
||||
name?: string | null;
|
||||
slug?: string | null;
|
||||
bio?: string | null;
|
||||
hideBranding?: boolean | undefined;
|
||||
role: MembershipRole;
|
||||
logoUrl?: string | null;
|
||||
accepted: boolean;
|
||||
}[];
|
||||
}
|
||||
|
||||
export default function TeamInviteList(props: Props) {
|
||||
const utils = trpc.useUtils();
|
||||
|
||||
const [hideDropdown, setHideDropdown] = useState(false);
|
||||
|
||||
function selectAction(action: string, teamId: number) {
|
||||
switch (action) {
|
||||
case "disband":
|
||||
deleteTeam(teamId);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
const deleteTeamMutation = trpc.viewer.teams.delete.useMutation({
|
||||
async onSuccess() {
|
||||
await utils.viewer.teams.list.invalidate();
|
||||
revalidateTeamsList();
|
||||
await utils.viewer.teams.get.invalidate();
|
||||
await utils.viewer.organizations.listMembers.invalidate();
|
||||
trackFormbricksAction("team_disbanded");
|
||||
},
|
||||
async onError(err) {
|
||||
showToast(err.message, "error");
|
||||
},
|
||||
});
|
||||
|
||||
function deleteTeam(teamId: number) {
|
||||
deleteTeamMutation.mutate({ teamId });
|
||||
}
|
||||
|
||||
return (
|
||||
<div>
|
||||
<ul className="bg-default divide-subtle mb-8 divide-y rounded">
|
||||
{props.teams.map((team) => (
|
||||
<TeamInviteListItem
|
||||
key={team?.id as number}
|
||||
team={team}
|
||||
onActionSelect={(action: string) => selectAction(action, team?.id as number)}
|
||||
isPending={deleteTeamMutation.isPending}
|
||||
hideDropdown={hideDropdown}
|
||||
setHideDropdown={setHideDropdown}
|
||||
/>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,135 +0,0 @@
|
||||
import { getPlaceholderAvatar } from "@calcom/lib/defaultAvatarImage";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import type { MembershipRole } from "@calcom/prisma/enums";
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
import classNames from "@calcom/ui/classNames";
|
||||
import { Avatar } from "@calcom/ui/components/avatar";
|
||||
import { Button } from "@calcom/ui/components/button";
|
||||
import {
|
||||
Dropdown,
|
||||
DropdownItem,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
} from "@calcom/ui/components/dropdown";
|
||||
import { showToast } from "@calcom/ui/components/toast";
|
||||
import { revalidateTeamsList } from "@calcom/web/app/(use-page-wrapper)/(main-nav)/teams/actions";
|
||||
|
||||
interface Props {
|
||||
team: {
|
||||
id?: number;
|
||||
name?: string | null;
|
||||
slug?: string | null;
|
||||
bio?: string | null;
|
||||
logoUrl?: string | null;
|
||||
hideBranding?: boolean | undefined;
|
||||
role: MembershipRole;
|
||||
accepted: boolean;
|
||||
};
|
||||
key: number;
|
||||
onActionSelect: (text: string) => void;
|
||||
isPending?: boolean;
|
||||
hideDropdown: boolean;
|
||||
setHideDropdown: (value: boolean) => void;
|
||||
}
|
||||
|
||||
export default function TeamInviteListItem(props: Props) {
|
||||
const { t } = useLocale();
|
||||
const utils = trpc.useUtils();
|
||||
const team = props.team;
|
||||
|
||||
const acceptOrLeaveMutation = trpc.viewer.teams.acceptOrLeave.useMutation({
|
||||
onSuccess: async () => {
|
||||
showToast(t("success"), "success");
|
||||
await utils.viewer.teams.get.invalidate();
|
||||
await utils.viewer.teams.hasTeamPlan.invalidate();
|
||||
await utils.viewer.teams.list.invalidate();
|
||||
revalidateTeamsList();
|
||||
await utils.viewer.organizations.listMembers.invalidate();
|
||||
},
|
||||
});
|
||||
|
||||
function acceptOrLeave(accept: boolean) {
|
||||
acceptOrLeaveMutation.mutate({
|
||||
teamId: team?.id as number,
|
||||
accept,
|
||||
});
|
||||
}
|
||||
|
||||
const acceptInvite = () => acceptOrLeave(true);
|
||||
const declineInvite = () => acceptOrLeave(false);
|
||||
|
||||
const isInvitee = !props.team.accepted;
|
||||
|
||||
if (!team) return <></>;
|
||||
|
||||
const teamInfo = (
|
||||
<div className="flex">
|
||||
<Avatar
|
||||
size="mdLg"
|
||||
imageSrc={getPlaceholderAvatar(team.logoUrl, team.name)}
|
||||
alt="Team Logo"
|
||||
className=""
|
||||
/>
|
||||
<div className="ms-3 inline-block">
|
||||
<span className="text-emphasis text-sm font-semibold">{team.name}</span>
|
||||
<span className="text-default block text-sm leading-5">
|
||||
{t("invited_by_team", { teamName: team.name, role: t(team.role.toLocaleLowerCase()) })}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
return (
|
||||
<li className="bg-subtle border-emphasis divide-subtle divide-y rounded-md border px-5 py-4">
|
||||
<div
|
||||
className={classNames(
|
||||
"flex items-center justify-between",
|
||||
!isInvitee && "group hover:bg-neutral-50"
|
||||
)}>
|
||||
{teamInfo}
|
||||
<div>
|
||||
<>
|
||||
<div className="hidden sm:flex">
|
||||
<Button
|
||||
type="button"
|
||||
className="border-empthasis mr-3"
|
||||
variant="icon"
|
||||
color="secondary"
|
||||
onClick={declineInvite}
|
||||
StartIcon="ban"
|
||||
/>
|
||||
<Button
|
||||
type="button"
|
||||
className="border-empthasis"
|
||||
variant="icon"
|
||||
color="secondary"
|
||||
onClick={acceptInvite}
|
||||
StartIcon="check"
|
||||
/>
|
||||
</div>
|
||||
<div className="block sm:hidden">
|
||||
<Dropdown>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button type="button" color="minimal" variant="icon" StartIcon="ellipsis" />
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent>
|
||||
<DropdownMenuItem>
|
||||
<DropdownItem type="button" StartIcon="check" onClick={acceptInvite}>
|
||||
{t("accept")}
|
||||
</DropdownItem>
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem>
|
||||
<DropdownItem color="destructive" type="button" StartIcon="x" onClick={declineInvite}>
|
||||
{t("reject")}
|
||||
</DropdownItem>
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</Dropdown>
|
||||
</div>
|
||||
</>
|
||||
</div>
|
||||
</div>
|
||||
</li>
|
||||
);
|
||||
}
|
||||
@@ -1,174 +0,0 @@
|
||||
import { useState } from "react";
|
||||
|
||||
import { trackFormbricksAction } from "@calcom/features/formbricks/formbricks-client";
|
||||
import {
|
||||
ORG_SELF_SERVE_ENABLED,
|
||||
ORG_MINIMUM_PUBLISHED_TEAMS_SELF_SERVE_HELPER_DIALOGUE,
|
||||
} from "@calcom/lib/constants";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import type { RouterOutputs } from "@calcom/trpc/react";
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
import { Card } from "@calcom/ui/components/card";
|
||||
import { Icon } from "@calcom/ui/components/icon";
|
||||
import { showToast } from "@calcom/ui/components/toast";
|
||||
import { revalidateTeamsList } from "@calcom/web/app/(use-page-wrapper)/(main-nav)/teams/actions";
|
||||
|
||||
import TeamListItem from "./TeamListItem";
|
||||
|
||||
interface Props {
|
||||
teams: RouterOutputs["viewer"]["teams"]["list"];
|
||||
orgId: number | null;
|
||||
/**
|
||||
* True for teams that are pending invite acceptance
|
||||
*/
|
||||
pending?: boolean;
|
||||
}
|
||||
|
||||
export default function TeamList(props: Props) {
|
||||
const utils = trpc.useUtils();
|
||||
|
||||
const { t } = useLocale();
|
||||
const { orgId } = props;
|
||||
|
||||
const [hideDropdown, setHideDropdown] = useState(false);
|
||||
|
||||
function selectAction(action: string, teamId: number) {
|
||||
switch (action) {
|
||||
case "disband":
|
||||
deleteTeam(teamId);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
const deleteTeamMutation = trpc.viewer.teams.delete.useMutation({
|
||||
async onSuccess() {
|
||||
await utils.viewer.teams.list.invalidate();
|
||||
revalidateTeamsList();
|
||||
await utils.viewer.teams.hasTeamPlan.invalidate();
|
||||
trackFormbricksAction("team_disbanded");
|
||||
},
|
||||
async onError(err) {
|
||||
showToast(err.message, "error");
|
||||
},
|
||||
});
|
||||
|
||||
function deleteTeam(teamId: number) {
|
||||
deleteTeamMutation.mutate({ teamId });
|
||||
}
|
||||
|
||||
return (
|
||||
<ul className="bg-default divide-subtle border-subtle mb-2 divide-y overflow-hidden rounded-md border">
|
||||
{ORG_SELF_SERVE_ENABLED &&
|
||||
!props.pending &&
|
||||
!orgId &&
|
||||
props.teams.length >= ORG_MINIMUM_PUBLISHED_TEAMS_SELF_SERVE_HELPER_DIALOGUE &&
|
||||
props.teams.map(
|
||||
(team, i) =>
|
||||
team.role !== "MEMBER" &&
|
||||
i === 0 && (
|
||||
<div className="bg-subtle p-4" key={team.id}>
|
||||
<div className="grid-col-1 grid gap-2 md:grid-cols-3">
|
||||
<Card
|
||||
icon={<Icon name="building" className="h-5 w-5 text-red-700" />}
|
||||
variant="basic"
|
||||
title={props.teams.length === 1 ? t("you_have_one_team") : t("You have a lot of teams")}
|
||||
description={
|
||||
props.teams.length === 1
|
||||
? t("consider_consolidating_one_team_org")
|
||||
: t("consider_consolidating_multi_team_org")
|
||||
}
|
||||
actionButton={{
|
||||
href: `/settings/organizations/new`,
|
||||
child: t("set_up_your_organization"),
|
||||
"data-testid": "setup_your_org_action_button",
|
||||
}}
|
||||
/>
|
||||
<Card
|
||||
icon={<Icon name="paintbrush" className="h-5 w-5 text-orange-700" />}
|
||||
variant="basic"
|
||||
title={t("Get a clean subdomain")}
|
||||
description={t(
|
||||
"Right now, team member URLs are all over the place. Get a beautiful link and turn every email address into a scheduling link: [email protected] → acme.cal.com/anna"
|
||||
)}
|
||||
actionButton={{
|
||||
href: "https://www.youtube.com/watch?v=G0Jd2dp7064",
|
||||
child: t("learn_more"),
|
||||
}}
|
||||
/>
|
||||
<Card
|
||||
icon={<Icon name="chart-line" className="h-5 w-5 text-green-700" />}
|
||||
variant="basic"
|
||||
title={t("Admin tools and analytics")}
|
||||
description={t(
|
||||
"As an organization owner, you are in charge of every team account. You can make changes with admin-only tools and see organization wide analytics in one place."
|
||||
)}
|
||||
actionButton={{
|
||||
href: "https://go.cal.com/quote",
|
||||
child: t("learn_more"),
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
)}
|
||||
|
||||
{props.teams.map((team) => (
|
||||
<TeamListItem
|
||||
key={team?.id as number}
|
||||
team={team}
|
||||
orgId={orgId}
|
||||
onActionSelect={(action: string) => selectAction(action, team?.id as number)}
|
||||
isPending={deleteTeamMutation.isPending}
|
||||
hideDropdown={hideDropdown}
|
||||
setHideDropdown={setHideDropdown}
|
||||
/>
|
||||
))}
|
||||
{/* only show recommended steps when there is only one team */}
|
||||
{!props.pending && props.teams.length === 1 && (
|
||||
<>
|
||||
{props.teams.map(
|
||||
(team, i) =>
|
||||
team.role !== "MEMBER" &&
|
||||
i === 0 && (
|
||||
<div className="bg-subtle p-6" key={`listing${team.id}`}>
|
||||
<h3 className="text-emphasis mb-4 text-sm font-semibold">{t("recommended_next_steps")}</h3>
|
||||
<div className="grid-col-1 grid gap-2 md:grid-cols-3">
|
||||
<Card
|
||||
icon={<Icon name="user-plus" className="h-5 w-5 text-green-700" />}
|
||||
variant="basic"
|
||||
title={t("invite_team_member")}
|
||||
description={t("meetings_are_better_with_the_right")}
|
||||
actionButton={{
|
||||
href: `/settings/teams/${team.id}/members`,
|
||||
child: t("invite"),
|
||||
}}
|
||||
/>
|
||||
<Card
|
||||
icon={<Icon name="users" className="h-5 w-5 text-orange-700" />}
|
||||
variant="basic"
|
||||
title={t("collective_or_roundrobin")}
|
||||
description={t("book_your_team_members")}
|
||||
actionButton={{
|
||||
href: `/event-types?dialog=new&eventPage=team%2F${team.slug}&teamId=${team.id}`,
|
||||
child: t("create"),
|
||||
}}
|
||||
/>
|
||||
<Card
|
||||
icon={<Icon name="pencil" className="h-5 w-5 text-purple-700" />}
|
||||
variant="basic"
|
||||
title={t("appearance")}
|
||||
description={t("appearance_description")}
|
||||
actionButton={{
|
||||
href: `/settings/teams/${team.id}/appearance`,
|
||||
child: t("edit"),
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</ul>
|
||||
);
|
||||
}
|
||||
@@ -1,378 +0,0 @@
|
||||
import Link from "next/link";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useState } from "react";
|
||||
|
||||
import InviteLinkSettingsModal from "@calcom/ee/teams/components/InviteLinkSettingsModal";
|
||||
import { MemberInvitationModalWithoutMembers } from "@calcom/ee/teams/components/MemberInvitationModal";
|
||||
import { checkAdminOrOwner } from "@calcom/features/auth/lib/checkAdminOrOwner";
|
||||
import { Dialog } from "@calcom/features/components/controlled-dialog";
|
||||
import { getTeamUrlSync } from "@calcom/features/ee/organizations/lib/getTeamUrlSync";
|
||||
import { getPlaceholderAvatar } from "@calcom/lib/defaultAvatarImage";
|
||||
import { useCompatSearchParams } from "@calcom/lib/hooks/useCompatSearchParams";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { useRefreshData } from "@calcom/lib/hooks/useRefreshData";
|
||||
import { MembershipRole } from "@calcom/prisma/enums";
|
||||
import type { RouterOutputs } from "@calcom/trpc/react";
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
import classNames from "@calcom/ui/classNames";
|
||||
import { Avatar } from "@calcom/ui/components/avatar";
|
||||
import { Badge } from "@calcom/ui/components/badge";
|
||||
import { Button } from "@calcom/ui/components/button";
|
||||
import { ButtonGroup } from "@calcom/ui/components/buttonGroup";
|
||||
import { DialogTrigger, ConfirmationDialogContent } from "@calcom/ui/components/dialog";
|
||||
import {
|
||||
Dropdown,
|
||||
DropdownItem,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuTrigger,
|
||||
} from "@calcom/ui/components/dropdown";
|
||||
import { showToast } from "@calcom/ui/components/toast";
|
||||
import { Tooltip } from "@calcom/ui/components/tooltip";
|
||||
import { revalidateTeamsList } from "@calcom/web/app/(use-page-wrapper)/(main-nav)/teams/actions";
|
||||
|
||||
import { TeamRole } from "./TeamPill";
|
||||
|
||||
interface Props {
|
||||
team: RouterOutputs["viewer"]["teams"]["list"][number];
|
||||
orgId: number | null;
|
||||
key: number;
|
||||
onActionSelect: (text: string) => void;
|
||||
isPending?: boolean;
|
||||
hideDropdown: boolean;
|
||||
setHideDropdown: (value: boolean) => void;
|
||||
}
|
||||
|
||||
export default function TeamListItem(props: Props) {
|
||||
const searchParams = useCompatSearchParams();
|
||||
const { t } = useLocale();
|
||||
const utils = trpc.useUtils();
|
||||
const { team, orgId } = props;
|
||||
|
||||
const showDialog = searchParams?.get("inviteModal") === "true";
|
||||
const [openMemberInvitationModal, setOpenMemberInvitationModal] = useState(showDialog);
|
||||
const [openInviteLinkSettingsModal, setOpenInviteLinkSettingsModal] = useState(false);
|
||||
const refreshData = useRefreshData();
|
||||
|
||||
const acceptOrLeaveMutation = trpc.viewer.teams.acceptOrLeave.useMutation({
|
||||
onSuccess: (_data, variables) => {
|
||||
showToast(t("success"), "success");
|
||||
utils.viewer.teams.get.invalidate();
|
||||
utils.viewer.teams.list.invalidate();
|
||||
revalidateTeamsList();
|
||||
utils.viewer.teams.hasTeamPlan.invalidate();
|
||||
utils.viewer.teams.listInvites.invalidate();
|
||||
const userOrganizationId = orgId ?? undefined;
|
||||
const isSubTeamOfDifferentOrg = team.parentId ? team.parentId != userOrganizationId : false;
|
||||
const isDifferentOrg = team.isOrganization && team.id !== userOrganizationId;
|
||||
// If the user team being accepted is a sub-team of different organization or the different organization itself then page must be reloaded to let the session change reflect reliably everywhere.
|
||||
if (variables.accept && (isSubTeamOfDifferentOrg || isDifferentOrg)) {
|
||||
refreshData();
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
function acceptOrLeave(accept: boolean) {
|
||||
acceptOrLeaveMutation.mutate({
|
||||
teamId: team?.id as number,
|
||||
accept,
|
||||
});
|
||||
}
|
||||
|
||||
const acceptInvite = () => acceptOrLeave(true);
|
||||
const declineInvite = () => acceptOrLeave(false);
|
||||
|
||||
const isOwner = props.team.role === MembershipRole.OWNER;
|
||||
const isInvitee = !props.team.accepted;
|
||||
const isAdmin = checkAdminOrOwner(props.team.role);
|
||||
const { hideDropdown, setHideDropdown } = props;
|
||||
|
||||
const hideInvitationModal = () => {
|
||||
setOpenMemberInvitationModal(false);
|
||||
};
|
||||
|
||||
if (!team) return null;
|
||||
const teamUrl = team.isOrganization
|
||||
? getTeamUrlSync({ orgSlug: team.slug, teamSlug: null })
|
||||
: getTeamUrlSync({ orgSlug: team.parent ? team.parent.slug : null, teamSlug: team.slug });
|
||||
const teamInfo = (
|
||||
<div className="item-center flex truncate p-5">
|
||||
<Avatar
|
||||
size="md"
|
||||
imageSrc={getPlaceholderAvatar(team?.logoUrl || team?.parent?.logoUrl, team?.name as string)}
|
||||
alt="Team logo"
|
||||
className="inline-flex justify-center"
|
||||
/>
|
||||
<div className="ms-3 inline-block truncate">
|
||||
<span className="text-default text-sm font-bold">{team.name}</span>
|
||||
<span className="text-muted block text-xs">
|
||||
{team.slug ? `${teamUrl}` : <Badge>{t("upgrade")}</Badge>}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
return (
|
||||
<li>
|
||||
<MemberInvitationModalWithoutMembers
|
||||
hideInvitationModal={hideInvitationModal}
|
||||
showMemberInvitationModal={openMemberInvitationModal}
|
||||
teamId={team.id}
|
||||
token={team.inviteToken?.token}
|
||||
onSettingsOpen={() => setOpenInviteLinkSettingsModal(true)}
|
||||
/>
|
||||
{team.inviteToken && (
|
||||
<InviteLinkSettingsModal
|
||||
isOpen={openInviteLinkSettingsModal}
|
||||
teamId={team.id}
|
||||
token={team.inviteToken?.token}
|
||||
expiresInDays={team.inviteToken?.expiresInDays || undefined}
|
||||
onExit={() => {
|
||||
setOpenInviteLinkSettingsModal(false);
|
||||
setOpenMemberInvitationModal(true);
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
<div className={classNames("flex items-center justify-between", !isInvitee && "hover:bg-cal-muted group")}>
|
||||
{!isInvitee ? (
|
||||
team.slug ? (
|
||||
<Link
|
||||
data-testid="team-list-item-link"
|
||||
href={`/settings/teams/${team.id}/profile`}
|
||||
className="grow cursor-pointer truncate text-sm"
|
||||
title={`${team.name}`}>
|
||||
{teamInfo}
|
||||
</Link>
|
||||
) : (
|
||||
<TeamPublishSection teamId={team.id}>{teamInfo}</TeamPublishSection>
|
||||
)
|
||||
) : (
|
||||
teamInfo
|
||||
)}
|
||||
<div className="p-5">
|
||||
{isInvitee ? (
|
||||
<>
|
||||
<div className="hidden justify-center sm:flex">
|
||||
<Button type="button" color="secondary" onClick={declineInvite}>
|
||||
{t("reject")}
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
color="secondary"
|
||||
data-testid={`accept-invitation-${team.id}`}
|
||||
StartIcon="check"
|
||||
className="me-2 ms-2"
|
||||
onClick={acceptInvite}>
|
||||
{t("accept")}
|
||||
</Button>
|
||||
</div>
|
||||
<div className="block sm:hidden">
|
||||
<Dropdown>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button
|
||||
className="radix-state-open:rounded-r-md"
|
||||
type="button"
|
||||
color="secondary"
|
||||
variant="icon"
|
||||
StartIcon="ellipsis"
|
||||
/>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent>
|
||||
<DropdownMenuItem>
|
||||
<DropdownItem type="button" StartIcon="check" onClick={acceptInvite}>
|
||||
{t("accept")}
|
||||
</DropdownItem>
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem>
|
||||
<DropdownItem color="destructive" type="button" StartIcon="x" onClick={declineInvite}>
|
||||
{t("reject")}
|
||||
</DropdownItem>
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</Dropdown>
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
<div className="flex space-x-2 rtl:space-x-reverse">
|
||||
<TeamRole role={team.role} />
|
||||
<ButtonGroup combined>
|
||||
{team.slug && (
|
||||
<Tooltip content={t("copy_link_team")}>
|
||||
<Button
|
||||
color="secondary"
|
||||
onClick={() => {
|
||||
navigator.clipboard.writeText(
|
||||
`${getTeamUrlSync({
|
||||
orgSlug: team.parent ? team.parent.slug : null,
|
||||
teamSlug: team.slug,
|
||||
})}`
|
||||
);
|
||||
showToast(t("link_copied"), "success");
|
||||
}}
|
||||
variant="icon"
|
||||
StartIcon="link"
|
||||
/>
|
||||
</Tooltip>
|
||||
)}
|
||||
<Dropdown>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button
|
||||
className="ltr:radix-state-open:rounded-r-(--btn-group-radius) rtl:radix-state-open:rounded-l-(--btn-group-radius)"
|
||||
type="button"
|
||||
color="secondary"
|
||||
variant="icon"
|
||||
StartIcon="ellipsis"
|
||||
/>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent hidden={hideDropdown}>
|
||||
{isAdmin && (
|
||||
<DropdownMenuItem>
|
||||
<DropdownItem
|
||||
type="button"
|
||||
href={`/settings/teams/${team.id}/profile`}
|
||||
StartIcon="pencil">
|
||||
{t("edit_team") as string}
|
||||
</DropdownItem>
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
{!team.slug && <TeamPublishButton teamId={team.id} />}
|
||||
{team.slug && (
|
||||
<DropdownMenuItem>
|
||||
<DropdownItem
|
||||
type="button"
|
||||
target="_blank"
|
||||
href={`${getTeamUrlSync({
|
||||
orgSlug: team.parent ? team.parent.slug : null,
|
||||
teamSlug: team.slug,
|
||||
})}`}
|
||||
StartIcon="external-link">
|
||||
{t("preview_team") as string}
|
||||
</DropdownItem>
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
{isAdmin && (
|
||||
<DropdownMenuItem>
|
||||
<DropdownItem
|
||||
type="button"
|
||||
onClick={() => {
|
||||
setOpenMemberInvitationModal(true);
|
||||
}}
|
||||
StartIcon="send">
|
||||
{t("invite_team_member") as string}
|
||||
</DropdownItem>
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
<DropdownMenuSeparator />
|
||||
{isOwner && (
|
||||
<DropdownMenuItem>
|
||||
<Dialog open={hideDropdown} onOpenChange={setHideDropdown}>
|
||||
<DialogTrigger asChild>
|
||||
<DropdownItem
|
||||
color="destructive"
|
||||
type="button"
|
||||
StartIcon="trash"
|
||||
className="rounded-t-none"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
}}>
|
||||
{t("disband_team")}
|
||||
</DropdownItem>
|
||||
</DialogTrigger>
|
||||
<ConfirmationDialogContent
|
||||
variety="danger"
|
||||
title={t("disband_team")}
|
||||
confirmBtnText={t("confirm_disband_team")}
|
||||
isPending={props.isPending}
|
||||
onConfirm={() => {
|
||||
props.onActionSelect("disband");
|
||||
}}>
|
||||
{t("disband_team_confirmation_message")}
|
||||
</ConfirmationDialogContent>
|
||||
</Dialog>
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
|
||||
{!isOwner && (
|
||||
<DropdownMenuItem>
|
||||
<Dialog>
|
||||
<DialogTrigger asChild>
|
||||
<DropdownItem
|
||||
color="destructive"
|
||||
type="button"
|
||||
StartIcon="log-out"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
}}>
|
||||
{t("leave_team")}
|
||||
</DropdownItem>
|
||||
</DialogTrigger>
|
||||
<ConfirmationDialogContent
|
||||
variety="danger"
|
||||
title={t("leave_team")}
|
||||
confirmBtnText={t("confirm_leave_team")}
|
||||
onConfirm={declineInvite}>
|
||||
{t("leave_team_confirmation_message")}
|
||||
</ConfirmationDialogContent>
|
||||
</Dialog>
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
</DropdownMenuContent>
|
||||
</Dropdown>
|
||||
</ButtonGroup>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</li>
|
||||
);
|
||||
}
|
||||
|
||||
const TeamPublishButton = ({ teamId }: { teamId: number }) => {
|
||||
const { t } = useLocale();
|
||||
const router = useRouter();
|
||||
const publishTeamMutation = trpc.viewer.teams.publish.useMutation({
|
||||
onSuccess(data) {
|
||||
router.push(data.url);
|
||||
},
|
||||
onError: (error) => {
|
||||
showToast(error.message, "error");
|
||||
},
|
||||
});
|
||||
|
||||
return (
|
||||
<DropdownMenuItem>
|
||||
<DropdownItem
|
||||
type="button"
|
||||
onClick={() => {
|
||||
publishTeamMutation.mutate({ teamId });
|
||||
}}
|
||||
StartIcon="globe">
|
||||
{t("team_publish")}
|
||||
</DropdownItem>
|
||||
</DropdownMenuItem>
|
||||
);
|
||||
};
|
||||
|
||||
const TeamPublishSection = ({ children, teamId }: { children: React.ReactNode; teamId: number }) => {
|
||||
const router = useRouter();
|
||||
const publishTeamMutation = trpc.viewer.teams.publish.useMutation({
|
||||
onSuccess(data) {
|
||||
router.push(data.url);
|
||||
},
|
||||
onError: (error) => {
|
||||
showToast(error.message, "error");
|
||||
},
|
||||
});
|
||||
|
||||
return (
|
||||
<button
|
||||
className="block grow cursor-pointer truncate text-left text-sm"
|
||||
type="button"
|
||||
onClick={() => {
|
||||
publishTeamMutation.mutate({ teamId });
|
||||
}}>
|
||||
{children}
|
||||
</button>
|
||||
);
|
||||
};
|
||||
@@ -1,42 +0,0 @@
|
||||
import classNames from "classnames";
|
||||
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { MembershipRole } from "@calcom/prisma/enums";
|
||||
|
||||
type PillColor = "blue" | "green" | "red" | "orange";
|
||||
|
||||
interface Props extends React.HTMLAttributes<HTMLDivElement> {
|
||||
text: string;
|
||||
color?: PillColor;
|
||||
}
|
||||
|
||||
export default function TeamPill(props: Props) {
|
||||
const { color, text, ...rest } = props;
|
||||
return (
|
||||
<div
|
||||
className={classNames("text-medium self-center rounded-md px-1.5 py-1 text-xs ltr:mr-1 rtl:ml-1", {
|
||||
" bg-subtle text-emphasis": !color,
|
||||
" bg-cal-info text-info": color === "blue",
|
||||
" bg-error text-error ": color === "red",
|
||||
" bg-attention text-attention": color === "orange",
|
||||
})}
|
||||
{...rest}>
|
||||
{text}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
interface TeamRoleProps extends Omit<React.ComponentProps<typeof TeamPill>, "text"> {
|
||||
role: MembershipRole;
|
||||
}
|
||||
|
||||
export function TeamRole(props: TeamRoleProps) {
|
||||
const { t } = useLocale();
|
||||
const { role, ...rest } = props;
|
||||
const keys: Record<MembershipRole, PillColor | undefined> = {
|
||||
[MembershipRole.OWNER]: "blue",
|
||||
[MembershipRole.ADMIN]: "red",
|
||||
[MembershipRole.MEMBER]: undefined,
|
||||
};
|
||||
return <TeamPill text={t(role.toLowerCase())} color={keys[role]} {...rest} />;
|
||||
}
|
||||
@@ -1,181 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { useRouter, useSearchParams } from "next/navigation";
|
||||
import { useEffect, useMemo } from "react";
|
||||
|
||||
import SkeletonLoaderTeamList from "@calcom/features/ee/teams/components/SkeletonloaderTeamList";
|
||||
import { APP_NAME, WEBAPP_URL } from "@calcom/lib/constants";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import type { RouterOutputs } from "@calcom/trpc/react";
|
||||
import { Button } from "@calcom/ui/components/button";
|
||||
import { ButtonGroup } from "@calcom/ui/components/buttonGroup";
|
||||
import { EmptyScreen } from "@calcom/ui/components/empty-screen";
|
||||
import { Label } from "@calcom/ui/components/form";
|
||||
import { Icon } from "@calcom/ui/components/icon";
|
||||
import { showToast } from "@calcom/ui/components/toast";
|
||||
|
||||
import { UpgradeTip } from "../../../tips";
|
||||
import TeamList from "./TeamList";
|
||||
|
||||
type TeamsListingProps = {
|
||||
invitationAccepted: boolean;
|
||||
orgId: number | null;
|
||||
permissions: {
|
||||
canCreateTeam: boolean;
|
||||
};
|
||||
teams: RouterOutputs["viewer"]["teams"]["list"];
|
||||
teamNameFromInvite: string | null;
|
||||
errorMsgFromInvite: string | null;
|
||||
};
|
||||
|
||||
export function TeamsListing({
|
||||
invitationAccepted,
|
||||
orgId,
|
||||
permissions,
|
||||
teams: data,
|
||||
teamNameFromInvite,
|
||||
errorMsgFromInvite,
|
||||
}: TeamsListingProps) {
|
||||
const searchParams = useSearchParams();
|
||||
const token = searchParams?.get("token");
|
||||
const { t } = useLocale();
|
||||
const router = useRouter();
|
||||
|
||||
const teams = useMemo(() => data?.filter((m) => m.accepted && !m.isOrganization) || [], [data]);
|
||||
|
||||
const teamInvites = useMemo(() => data?.filter((m) => !m.accepted && !m.isOrganization) || [], [data]);
|
||||
|
||||
const organizationInvites = (data?.filter((m) => !m.accepted && m.isOrganization) || []).filter(
|
||||
(orgInvite) => {
|
||||
const isThereASubTeamOfTheOrganizationInInvites = teamInvites.find(
|
||||
(teamInvite) => teamInvite.parentId === orgInvite.id
|
||||
);
|
||||
// Accepting a subteam invite automatically accepts the invite for the parent organization. So, need to show such an organization's invite
|
||||
return !isThereASubTeamOfTheOrganizationInInvites;
|
||||
}
|
||||
);
|
||||
|
||||
const isCreateTeamButtonDisabled = !!(orgId && !permissions.canCreateTeam);
|
||||
|
||||
const features = [
|
||||
{
|
||||
icon: <Icon name="users" className="h-5 w-5 text-red-500" />,
|
||||
title: t("collective_scheduling"),
|
||||
description: t("make_it_easy_to_book"),
|
||||
},
|
||||
{
|
||||
icon: <Icon name="refresh-ccw" className="h-5 w-5 text-blue-500" />,
|
||||
title: t("round_robin"),
|
||||
description: t("find_the_best_person"),
|
||||
},
|
||||
{
|
||||
icon: <Icon name="user-plus" className="h-5 w-5 text-green-500" />,
|
||||
title: t("fixed_round_robin"),
|
||||
description: t("add_one_fixed_attendee"),
|
||||
},
|
||||
{
|
||||
icon: <Icon name="mail" className="h-5 w-5 text-orange-500" />,
|
||||
title: t("sms_attendee_action"),
|
||||
description: t("send_reminder_sms"),
|
||||
},
|
||||
{
|
||||
icon: <Icon name="video" className="h-5 w-5 text-purple-500" />,
|
||||
title: `Cal Video ${t("recordings_title")}`,
|
||||
description: t("upgrade_to_access_recordings_description"),
|
||||
},
|
||||
{
|
||||
icon: <Icon name="eye-off" className="h-5 w-5 text-indigo-500" />,
|
||||
title: t("disable_cal_branding", { appName: APP_NAME }),
|
||||
description: t("disable_cal_branding_description", { appName: APP_NAME }),
|
||||
},
|
||||
];
|
||||
|
||||
useEffect(() => {
|
||||
if (!token) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (errorMsgFromInvite) {
|
||||
showToast(errorMsgFromInvite, "error");
|
||||
return;
|
||||
}
|
||||
|
||||
if (invitationAccepted) {
|
||||
showToast(t("successfully_joined"), "success");
|
||||
return;
|
||||
}
|
||||
|
||||
if (teamNameFromInvite) {
|
||||
showToast(t("team_invite_received", { teamName: teamNameFromInvite }), "success");
|
||||
return;
|
||||
}
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<>
|
||||
{organizationInvites.length > 0 && (
|
||||
<div className="bg-subtle mb-6 rounded-md p-5">
|
||||
<Label className="text-emphasis pb-2 font-semibold">{t("pending_organization_invites")}</Label>
|
||||
<TeamList orgId={orgId} teams={organizationInvites} pending />
|
||||
</div>
|
||||
)}
|
||||
|
||||
{teamInvites.length > 0 && (
|
||||
<div className="bg-subtle mb-6 rounded-md p-5">
|
||||
<Label className="text-emphasis pb-2 font-semibold">{t("pending_invites")}</Label>
|
||||
<TeamList orgId={orgId} teams={teamInvites} pending />
|
||||
</div>
|
||||
)}
|
||||
|
||||
{teams.length > 0 && <TeamList orgId={orgId} teams={teams} />}
|
||||
|
||||
{teams.length === 0 && (
|
||||
<UpgradeTip
|
||||
plan="team"
|
||||
title={t("calcom_is_better_with_team", { appName: APP_NAME })}
|
||||
description={t("add_your_team_members")}
|
||||
features={features}
|
||||
background="/tips/teams"
|
||||
buttons={
|
||||
!orgId || permissions.canCreateTeam ? (
|
||||
<div className="stack-y-2 rtl:space-x-reverse sm:space-x-2">
|
||||
<ButtonGroup>
|
||||
<Button color="primary" href={`${WEBAPP_URL}/settings/teams/new`}>
|
||||
{t("create_team")}
|
||||
</Button>
|
||||
<Button color="minimal" href="https://go.cal.com/teams-video" target="_blank">
|
||||
{t("learn_more")}
|
||||
</Button>
|
||||
</ButtonGroup>
|
||||
</div>
|
||||
) : (
|
||||
<p>{t("org_admins_can_create_new_teams")}</p>
|
||||
)
|
||||
}
|
||||
isParentLoading={<SkeletonLoaderTeamList />}>
|
||||
<EmptyScreen
|
||||
Icon="users"
|
||||
headline={t("create_team_to_get_started")}
|
||||
description={t("create_first_team_and_invite_others")}
|
||||
buttonRaw={
|
||||
<Button
|
||||
color="secondary"
|
||||
data-testid="create-team-btn"
|
||||
disabled={!!isCreateTeamButtonDisabled}
|
||||
tooltip={
|
||||
isCreateTeamButtonDisabled ? t("org_admins_can_create_new_teams") : t("create_new_team")
|
||||
}
|
||||
onClick={() => router.push(`${WEBAPP_URL}/settings/teams/new?returnTo=${WEBAPP_URL}/teams`)}>
|
||||
{t(`create_new_team`)}
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
</UpgradeTip>
|
||||
)}
|
||||
|
||||
<p className="text-subtle mb-8 mt-4 flex w-full items-center gap-1 text-sm md:justify-center md:text-center">
|
||||
<Icon className="hidden sm:block" name="info" /> {t("tip_username_plus")}
|
||||
</p>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -1,47 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { useRouter } from "next/navigation";
|
||||
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
import type { RouterOutputs } from "@calcom/trpc/react";
|
||||
import { showToast } from "@calcom/ui/components/toast";
|
||||
import { TopBanner } from "@calcom/ui/components/top-banner";
|
||||
|
||||
export type TeamsUpgradeBannerProps = {
|
||||
data: RouterOutputs["viewer"]["me"]["getUserTopBanners"]["teamUpgradeBanner"];
|
||||
};
|
||||
|
||||
export function TeamsUpgradeBanner({ data }: TeamsUpgradeBannerProps) {
|
||||
const { t } = useLocale();
|
||||
const router = useRouter();
|
||||
|
||||
const publishTeamMutation = trpc.viewer.teams.publish.useMutation({
|
||||
onSuccess(data) {
|
||||
router.push(data.url);
|
||||
},
|
||||
onError: (error) => {
|
||||
showToast(error.message, "error");
|
||||
},
|
||||
});
|
||||
|
||||
if (!data) return null;
|
||||
const [membership] = data;
|
||||
if (!membership) return null;
|
||||
|
||||
return (
|
||||
<TopBanner
|
||||
text={t("team_upgrade_banner_description", { teamName: membership.team.name })}
|
||||
variant="warning"
|
||||
actions={
|
||||
<button
|
||||
className="border-b border-b-black"
|
||||
onClick={() => {
|
||||
publishTeamMutation.mutate({ teamId: membership.team.id });
|
||||
}}>
|
||||
{t("upgrade_banner_action")}
|
||||
</button>
|
||||
}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -1,139 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { usePathname, useRouter } from "next/navigation";
|
||||
|
||||
import { useCompatSearchParams } from "@calcom/lib/hooks/useCompatSearchParams";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { Avatar } from "@calcom/ui/components/avatar";
|
||||
import type { ButtonColor } from "@calcom/ui/components/button";
|
||||
import { Button } from "@calcom/ui/components/button";
|
||||
import {
|
||||
Dropdown,
|
||||
DropdownItem,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuLabel,
|
||||
DropdownMenuTrigger,
|
||||
} from "@calcom/ui/components/dropdown";
|
||||
|
||||
export interface Option {
|
||||
platform?: boolean;
|
||||
teamId: number | null | undefined; // if undefined, then it's a profile
|
||||
label: string | null;
|
||||
image: string | null;
|
||||
slug: string | null;
|
||||
}
|
||||
|
||||
export type CreateBtnProps = {
|
||||
options: Option[];
|
||||
createDialog?: () => JSX.Element;
|
||||
createFunction?: (teamId?: number, platform?: boolean) => void;
|
||||
subtitle?: string;
|
||||
buttonText?: string;
|
||||
isPending?: boolean;
|
||||
disableMobileButton?: boolean;
|
||||
"data-testid"?: string;
|
||||
color?: ButtonColor;
|
||||
};
|
||||
|
||||
/**
|
||||
* @deprecated use CreateButtonWithTeamsList instead
|
||||
*/
|
||||
export function CreateButton(props: CreateBtnProps) {
|
||||
const { t } = useLocale();
|
||||
const router = useRouter();
|
||||
const searchParams = useCompatSearchParams();
|
||||
const pathname = usePathname();
|
||||
|
||||
const {
|
||||
createDialog,
|
||||
options,
|
||||
isPending,
|
||||
createFunction,
|
||||
buttonText,
|
||||
disableMobileButton,
|
||||
subtitle,
|
||||
...restProps
|
||||
} = props;
|
||||
const CreateDialog = createDialog ? createDialog() : null;
|
||||
|
||||
const hasTeams = !!options.find((option) => option.teamId);
|
||||
const platform = !!options.find((option) => option.platform);
|
||||
|
||||
// inject selection data into url for correct router history
|
||||
const openModal = (option: Option) => {
|
||||
const _searchParams = new URLSearchParams(searchParams.toString());
|
||||
function setParamsIfDefined(key: string, value: string | number | boolean | null | undefined) {
|
||||
if (value !== undefined && value !== null) _searchParams.set(key, value.toString());
|
||||
}
|
||||
setParamsIfDefined("dialog", "new");
|
||||
setParamsIfDefined("eventPage", option.slug);
|
||||
setParamsIfDefined("teamId", option.teamId);
|
||||
if (!option.teamId) {
|
||||
_searchParams.delete("teamId");
|
||||
}
|
||||
router.push(`${pathname}?${_searchParams.toString()}`);
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
{!hasTeams && !platform ? (
|
||||
<Button
|
||||
size="sm"
|
||||
onClick={() =>
|
||||
!!CreateDialog
|
||||
? openModal(options[0])
|
||||
: createFunction
|
||||
? createFunction(options[0].teamId || undefined)
|
||||
: null
|
||||
}
|
||||
data-testid="create-button"
|
||||
StartIcon="plus"
|
||||
loading={isPending}
|
||||
variant={disableMobileButton ? "button" : "fab"}
|
||||
{...restProps}>
|
||||
{buttonText ? buttonText : t("new")}
|
||||
</Button>
|
||||
) : (
|
||||
<Dropdown>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button
|
||||
variant={disableMobileButton ? "button" : "fab"}
|
||||
StartIcon="plus"
|
||||
size="sm"
|
||||
data-testid="create-button-dropdown"
|
||||
loading={isPending}
|
||||
{...restProps}>
|
||||
{buttonText ? buttonText : t("new")}
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent sideOffset={14} align="end" className="scroll-bar max-h-60 overflow-y-auto">
|
||||
<DropdownMenuLabel>
|
||||
<div className="w-48 text-left text-xs">{subtitle}</div>
|
||||
</DropdownMenuLabel>
|
||||
{options.map((option, idx) => (
|
||||
<DropdownMenuItem key={option.label}>
|
||||
<DropdownItem
|
||||
type="button"
|
||||
data-testid={`option${option.teamId ? "-team" : ""}-${idx}`}
|
||||
CustomStartIcon={<Avatar alt={option.label || ""} imageSrc={option.image} size="sm" />}
|
||||
onClick={() =>
|
||||
!!CreateDialog
|
||||
? openModal(option)
|
||||
: createFunction
|
||||
? createFunction(option.teamId || undefined, option.platform)
|
||||
: null
|
||||
}>
|
||||
{" "}
|
||||
{/*improve this code */}
|
||||
<span>{option.label}</span>
|
||||
</DropdownItem>
|
||||
</DropdownMenuItem>
|
||||
))}
|
||||
</DropdownMenuContent>
|
||||
</Dropdown>
|
||||
)}
|
||||
{searchParams?.get("dialog") === "new" && CreateDialog}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -1,59 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import type { PermissionString } from "@calcom/features/pbac/domain/types/permission-registry";
|
||||
import type { MembershipRole } from "@calcom/prisma/enums";
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
|
||||
import type { CreateBtnProps, Option } from "./CreateButton";
|
||||
import { CreateButton } from "./CreateButton";
|
||||
|
||||
export function CreateButtonWithTeamsList(
|
||||
props: Omit<CreateBtnProps, "options"> & {
|
||||
onlyShowWithTeams?: boolean;
|
||||
onlyShowWithNoTeams?: boolean;
|
||||
isAdmin?: boolean;
|
||||
includeOrg?: boolean;
|
||||
withPermission?: {
|
||||
permission: PermissionString;
|
||||
fallbackRoles?: MembershipRole[];
|
||||
};
|
||||
}
|
||||
) {
|
||||
const query = trpc.viewer.loggedInViewerRouter.teamsAndUserProfilesQuery.useQuery({
|
||||
includeOrg: props.includeOrg,
|
||||
withPermission: props.withPermission
|
||||
? {
|
||||
permission: props.withPermission.permission,
|
||||
fallbackRoles: props.withPermission.fallbackRoles,
|
||||
}
|
||||
: undefined,
|
||||
});
|
||||
if (!query.data) return null;
|
||||
|
||||
const teamsAndUserProfiles: Option[] = query.data
|
||||
.filter((profile) => !profile.readOnly)
|
||||
.map((profile) => {
|
||||
return {
|
||||
teamId: profile.teamId,
|
||||
label: profile.name || profile.slug,
|
||||
image: profile.image,
|
||||
slug: profile.slug,
|
||||
};
|
||||
});
|
||||
|
||||
if (props.isAdmin) {
|
||||
teamsAndUserProfiles.push({
|
||||
platform: true,
|
||||
label: "Platform",
|
||||
image: null,
|
||||
slug: null,
|
||||
teamId: null,
|
||||
});
|
||||
}
|
||||
|
||||
if (props.onlyShowWithTeams && teamsAndUserProfiles.length < 2) return null;
|
||||
|
||||
if (props.onlyShowWithNoTeams && teamsAndUserProfiles.length > 1) return null;
|
||||
|
||||
return <CreateButton {...props} options={teamsAndUserProfiles} />;
|
||||
}
|
||||
-157
@@ -1,157 +0,0 @@
|
||||
/* eslint-disable @typescript-eslint/no-explicit-any */
|
||||
import { render, screen, fireEvent } from "@testing-library/react";
|
||||
import { vi } from "vitest";
|
||||
|
||||
import type { CreateBtnProps } from "./CreateButton";
|
||||
import { CreateButtonWithTeamsList } from "./CreateButtonWithTeamsList";
|
||||
|
||||
const mockRouter = {
|
||||
push: vi.fn((path: string) => {
|
||||
return;
|
||||
}),
|
||||
};
|
||||
|
||||
vi.mock("next/navigation", async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import("next/navigation")>();
|
||||
return {
|
||||
...actual,
|
||||
useRouter: vi.fn(() => mockRouter),
|
||||
};
|
||||
});
|
||||
|
||||
const runtimeMock = async (data: Array<any>) => {
|
||||
const updatedTrpc = {
|
||||
viewer: {
|
||||
loggedInViewerRouter: {
|
||||
teamsAndUserProfilesQuery: {
|
||||
useQuery() {
|
||||
return {
|
||||
data: data,
|
||||
};
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
const mockedLib = (await import("@calcom/trpc/react")) as any;
|
||||
mockedLib.trpc = updatedTrpc;
|
||||
};
|
||||
const renderCreateButton = (
|
||||
props: Omit<CreateBtnProps, "options"> & { onlyShowWithTeams?: boolean; onlyShowWithNoTeams?: boolean }
|
||||
) => {
|
||||
return render(<CreateButtonWithTeamsList {...props} />);
|
||||
};
|
||||
|
||||
describe("Create Button Tests", () => {
|
||||
describe("Create Button Tests With Valid Team", () => {
|
||||
beforeAll(async () => {
|
||||
// INFO: This needs to be here before the other calls to runtimeMock. For some reason,
|
||||
// when we moved this file from @calcom/ui, the imports started breaking, resulting in
|
||||
// errors of "Cannot set property 'trpc' of [object Module] which has only a getter"
|
||||
// TODO: Update this pattern to be more consistent. Using this direct mocking in the
|
||||
// functions below breaks some tests.
|
||||
vi.mock("@calcom/trpc/react", () => ({
|
||||
trpc: {
|
||||
viewer: {
|
||||
loggedInViewerRouter: {
|
||||
teamsAndUserProfilesQuery: {
|
||||
useQuery() {
|
||||
return {
|
||||
data: [
|
||||
{
|
||||
teamId: 1,
|
||||
name: "test",
|
||||
slug: "create-button-test",
|
||||
image: "image",
|
||||
},
|
||||
],
|
||||
};
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}));
|
||||
});
|
||||
test("Should render the create-button-dropdown button", () => {
|
||||
const createFunction = vi.fn();
|
||||
renderCreateButton({ createFunction });
|
||||
|
||||
const createButton = screen.getByTestId("create-button-dropdown");
|
||||
expect(createButton).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe("Create Button Tests With One Null Team", () => {
|
||||
beforeAll(async () => {
|
||||
await runtimeMock([
|
||||
{
|
||||
teamId: null,
|
||||
name: "test",
|
||||
slug: "create-button-test",
|
||||
image: "image",
|
||||
readOnly: false,
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
test("Should render only the create-button button", () => {
|
||||
const createFunction = vi.fn();
|
||||
renderCreateButton({ createFunction });
|
||||
|
||||
const createButton = screen.getByTestId("create-button");
|
||||
expect(screen.queryByTestId("create-button-dropdown")).not.toBeInTheDocument();
|
||||
expect(createButton).toBeInTheDocument();
|
||||
|
||||
fireEvent.click(createButton);
|
||||
expect(createFunction).toBeCalled();
|
||||
});
|
||||
|
||||
test("Should render nothing when teamsAndUserProfiles is less than 2 and onlyShowWithTeams is true", () => {
|
||||
renderCreateButton({ onlyShowWithTeams: true });
|
||||
|
||||
expect(screen.queryByTestId("create-button")).not.toBeInTheDocument();
|
||||
expect(screen.queryByTestId("create-button-dropdown")).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
describe("Create Button Tests With Multiple Null Teams", () => {
|
||||
beforeAll(async () => {
|
||||
await runtimeMock([
|
||||
{
|
||||
teamId: null,
|
||||
name: "test",
|
||||
slug: "create-button-test",
|
||||
image: "image",
|
||||
readOnly: false,
|
||||
},
|
||||
{
|
||||
teamId: null,
|
||||
name: "test2",
|
||||
slug: "create-button-test2",
|
||||
image: "image2",
|
||||
readOnly: false,
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
test("Should render only the create-button button", () => {
|
||||
const createFunction = vi.fn();
|
||||
renderCreateButton({ createFunction });
|
||||
|
||||
const createButton = screen.getByTestId("create-button");
|
||||
expect(screen.queryByTestId("create-button-dropdown")).not.toBeInTheDocument();
|
||||
expect(createButton).toBeInTheDocument();
|
||||
|
||||
fireEvent.click(createButton);
|
||||
expect(createFunction).toBeCalled();
|
||||
});
|
||||
|
||||
test("Should render nothing when teamsAndUserProfiles is greater than 1 and onlyShowWithNoTeams is true", () => {
|
||||
renderCreateButton({ onlyShowWithNoTeams: true });
|
||||
|
||||
expect(screen.queryByTestId("create-button")).not.toBeInTheDocument();
|
||||
expect(screen.queryByTestId("create-button-dropdown")).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,2 +0,0 @@
|
||||
export { CreateButton } from "./CreateButton";
|
||||
export { CreateButtonWithTeamsList } from "./CreateButtonWithTeamsList";
|
||||
@@ -1,3 +0,0 @@
|
||||
export { CreateANewTeamForm } from "./CreateANewTeamForm";
|
||||
export { TeamsListing } from "./TeamsListing";
|
||||
export { TeamsUpgradeBanner, type TeamsUpgradeBannerProps } from "./TeamsUpgradeBanner";
|
||||
@@ -1,236 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useState, useEffect } from "react";
|
||||
import { useForm } from "react-hook-form";
|
||||
|
||||
import { checkAdminOrOwner } from "@calcom/features/auth/lib/checkAdminOrOwner";
|
||||
import BrandColorsForm from "@calcom/features/ee/components/BrandColorsForm";
|
||||
import { AppearanceSkeletonLoader } from "@calcom/features/ee/components/CommonSkeletonLoaders";
|
||||
import SectionBottomActions from "@calcom/features/settings/SectionBottomActions";
|
||||
import { APP_NAME } from "@calcom/lib/constants";
|
||||
import { DEFAULT_LIGHT_BRAND_COLOR, DEFAULT_DARK_BRAND_COLOR } from "@calcom/lib/constants";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { useParamsWithFallback } from "@calcom/lib/hooks/useParamsWithFallback";
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
import type { RouterOutputs } from "@calcom/trpc/react";
|
||||
import { Button } from "@calcom/ui/components/button";
|
||||
import { Form } from "@calcom/ui/components/form";
|
||||
import { SettingsToggle } from "@calcom/ui/components/form";
|
||||
import { showToast } from "@calcom/ui/components/toast";
|
||||
import { revalidateTeamDataCache } from "@calcom/web/app/(booking-page-wrapper)/team/[slug]/[type]/actions";
|
||||
|
||||
import ThemeLabel from "../../../settings/ThemeLabel";
|
||||
|
||||
type BrandColorsFormValues = {
|
||||
brandColor: string;
|
||||
darkBrandColor: string;
|
||||
};
|
||||
|
||||
type ProfileViewProps = { team: RouterOutputs["viewer"]["teams"]["get"] };
|
||||
|
||||
const ProfileView = ({ team }: ProfileViewProps) => {
|
||||
const { t } = useLocale();
|
||||
const utils = trpc.useUtils();
|
||||
|
||||
const [hideBrandingValue, setHideBrandingValue] = useState(team?.hideBranding ?? false);
|
||||
const [hideBookATeamMember, setHideBookATeamMember] = useState(team?.hideBookATeamMember ?? false);
|
||||
const [hideTeamProfileLink, setHideTeamProfileLink] = useState(team?.hideTeamProfileLink ?? false);
|
||||
|
||||
const themeForm = useForm<{ theme: string | null | undefined }>({
|
||||
defaultValues: {
|
||||
theme: team?.theme,
|
||||
},
|
||||
});
|
||||
|
||||
const {
|
||||
formState: { isSubmitting: isThemeSubmitting, isDirty: isThemeDirty },
|
||||
reset: resetTheme,
|
||||
} = themeForm;
|
||||
|
||||
const brandColorsFormMethods = useForm<BrandColorsFormValues>({
|
||||
defaultValues: {
|
||||
brandColor: team?.brandColor || DEFAULT_LIGHT_BRAND_COLOR,
|
||||
darkBrandColor: team?.darkBrandColor || DEFAULT_DARK_BRAND_COLOR,
|
||||
},
|
||||
});
|
||||
|
||||
const { reset: resetBrandColors } = brandColorsFormMethods;
|
||||
|
||||
const mutation = trpc.viewer.teams.update.useMutation({
|
||||
onError: (err) => {
|
||||
showToast(err.message, "error");
|
||||
},
|
||||
async onSuccess(res) {
|
||||
await utils.viewer.teams.get.invalidate();
|
||||
if (res) {
|
||||
resetTheme({ theme: res.theme });
|
||||
resetBrandColors({
|
||||
brandColor: res.brandColor ?? DEFAULT_LIGHT_BRAND_COLOR,
|
||||
darkBrandColor: res.darkBrandColor ?? DEFAULT_DARK_BRAND_COLOR,
|
||||
});
|
||||
}
|
||||
|
||||
showToast(t("your_team_updated_successfully"), "success");
|
||||
if (res?.slug) {
|
||||
// Appearance changes (theme, colours, branding toggles) are read on the team booking page through
|
||||
// `getCachedTeamData` in `queries.ts`.
|
||||
await revalidateTeamDataCache({
|
||||
teamSlug: res?.slug,
|
||||
orgSlug: team?.parent?.slug ?? null,
|
||||
});
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
const onBrandColorsFormSubmit = (values: BrandColorsFormValues) => {
|
||||
mutation.mutate({ ...values, id: team.id });
|
||||
};
|
||||
|
||||
const isAdmin = team && checkAdminOrOwner(team.membership.role);
|
||||
|
||||
return (
|
||||
<>
|
||||
{isAdmin ? (
|
||||
<>
|
||||
<Form
|
||||
form={themeForm}
|
||||
handleSubmit={({ theme }) => {
|
||||
mutation.mutate({
|
||||
id: team.id,
|
||||
theme: theme === "light" || theme === "dark" ? theme : null,
|
||||
});
|
||||
}}>
|
||||
<div className="border-subtle mt-6 flex items-center rounded-t-xl border p-6 text-sm">
|
||||
<div>
|
||||
<p className="mt-0.5 text-base font-semibold leading-none">{t("theme")}</p>
|
||||
<p className="text-default text-sm leading-normal">{t("theme_applies_note")}</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="border-subtle flex flex-col justify-between border-x px-6 py-8 sm:flex-row">
|
||||
<ThemeLabel
|
||||
variant="system"
|
||||
value="system"
|
||||
label={t("theme_system")}
|
||||
defaultChecked={team.theme === null}
|
||||
register={themeForm.register}
|
||||
/>
|
||||
<ThemeLabel
|
||||
variant="light"
|
||||
value="light"
|
||||
label={t("light")}
|
||||
defaultChecked={team.theme === "light"}
|
||||
register={themeForm.register}
|
||||
/>
|
||||
<ThemeLabel
|
||||
variant="dark"
|
||||
value="dark"
|
||||
label={t("dark")}
|
||||
defaultChecked={team.theme === "dark"}
|
||||
register={themeForm.register}
|
||||
/>
|
||||
</div>
|
||||
<SectionBottomActions className="mb-6" align="end">
|
||||
<Button
|
||||
disabled={isThemeSubmitting || !isThemeDirty}
|
||||
type="submit"
|
||||
data-testid="update-org-theme-btn"
|
||||
color="primary">
|
||||
{t("update")}
|
||||
</Button>
|
||||
</SectionBottomActions>
|
||||
</Form>
|
||||
|
||||
<Form
|
||||
form={brandColorsFormMethods}
|
||||
handleSubmit={(values) => {
|
||||
onBrandColorsFormSubmit(values);
|
||||
}}>
|
||||
<BrandColorsForm
|
||||
onSubmit={onBrandColorsFormSubmit}
|
||||
brandColor={team?.brandColor ?? DEFAULT_LIGHT_BRAND_COLOR}
|
||||
darkBrandColor={team?.darkBrandColor ?? DEFAULT_DARK_BRAND_COLOR}
|
||||
/>
|
||||
</Form>
|
||||
|
||||
<div className="mt-6 flex flex-col gap-6">
|
||||
<SettingsToggle
|
||||
toggleSwitchAtTheEnd={true}
|
||||
title={t("disable_cal_branding", { appName: APP_NAME })}
|
||||
disabled={mutation?.isPending}
|
||||
description={t("removes_cal_branding", { appName: APP_NAME })}
|
||||
checked={hideBrandingValue}
|
||||
onCheckedChange={(checked) => {
|
||||
setHideBrandingValue(checked);
|
||||
mutation.mutate({ id: team.id, hideBranding: checked });
|
||||
}}
|
||||
/>
|
||||
|
||||
<SettingsToggle
|
||||
toggleSwitchAtTheEnd={true}
|
||||
title={t("hide_book_a_team_member")}
|
||||
disabled={mutation?.isPending}
|
||||
description={t("hide_book_a_team_member_description", { appName: APP_NAME })}
|
||||
checked={hideBookATeamMember ?? false}
|
||||
onCheckedChange={(checked) => {
|
||||
setHideBookATeamMember(checked);
|
||||
mutation.mutate({ id: team.id, hideBookATeamMember: checked });
|
||||
}}
|
||||
/>
|
||||
|
||||
<SettingsToggle
|
||||
toggleSwitchAtTheEnd={true}
|
||||
title={t("hide_team_profile_link")}
|
||||
disabled={mutation?.isPending}
|
||||
description={t("hide_team_profile_link_description")}
|
||||
checked={hideTeamProfileLink ?? false}
|
||||
onCheckedChange={(checked) => {
|
||||
setHideTeamProfileLink(checked);
|
||||
mutation.mutate({ id: team.id, hideTeamProfileLink: checked });
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
<div className="border-subtle rounded-md border p-5">
|
||||
<span className="text-default text-sm">{t("only_owner_change")}</span>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
const ProfileViewWrapper = () => {
|
||||
const router = useRouter();
|
||||
const params = useParamsWithFallback();
|
||||
|
||||
const { t } = useLocale();
|
||||
|
||||
const {
|
||||
data: team,
|
||||
isPending,
|
||||
error,
|
||||
} = trpc.viewer.teams.get.useQuery(
|
||||
{ teamId: Number(params.id) },
|
||||
{
|
||||
enabled: !!Number(params.id),
|
||||
}
|
||||
);
|
||||
|
||||
useEffect(
|
||||
function refactorMeWithoutEffect() {
|
||||
if (error) {
|
||||
router.replace("/teams");
|
||||
}
|
||||
},
|
||||
[error]
|
||||
);
|
||||
|
||||
if (isPending) return <AppearanceSkeletonLoader />;
|
||||
|
||||
if (!team) return null;
|
||||
|
||||
return <ProfileView team={team} />;
|
||||
};
|
||||
|
||||
export default ProfileViewWrapper;
|
||||
@@ -1,120 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { useSession } from "next-auth/react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useEffect, useState } from "react";
|
||||
|
||||
import { checkAdminOrOwner } from "@calcom/features/auth/lib/checkAdminOrOwner";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { useParamsWithFallback } from "@calcom/lib/hooks/useParamsWithFallback";
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
|
||||
import InviteLinkSettingsModal from "../components/InviteLinkSettingsModal";
|
||||
import { MemberInvitationModalWithoutMembers } from "../components/MemberInvitationModal";
|
||||
import MemberList from "../components/MemberList";
|
||||
import TeamInviteList from "../components/TeamInviteList";
|
||||
|
||||
const MembersView = () => {
|
||||
const { t } = useLocale();
|
||||
const [showMemberInvitationModal, setShowMemberInvitationModal] = useState(false);
|
||||
const [showInviteLinkSettingsModal, setInviteLinkSettingsModal] = useState(false);
|
||||
const router = useRouter();
|
||||
const session = useSession();
|
||||
const org = session?.data?.user.org;
|
||||
const params = useParamsWithFallback();
|
||||
|
||||
const teamId = Number(params.id);
|
||||
|
||||
const {
|
||||
data: team,
|
||||
isPending: isTeamsLoading,
|
||||
error: teamError,
|
||||
} = trpc.viewer.teams.get.useQuery(
|
||||
{ teamId },
|
||||
{
|
||||
enabled: !!teamId,
|
||||
}
|
||||
);
|
||||
useEffect(
|
||||
function refactorMeWithoutEffect() {
|
||||
if (teamError) {
|
||||
router.replace("/teams");
|
||||
}
|
||||
},
|
||||
[teamError]
|
||||
);
|
||||
|
||||
const isPending = isTeamsLoading;
|
||||
|
||||
const isInviteOpen = !team?.membership.accepted;
|
||||
|
||||
const isAdmin = team && checkAdminOrOwner(team.membership.role);
|
||||
|
||||
const isOrgAdminOrOwner = checkAdminOrOwner(org?.role);
|
||||
|
||||
const hideInvitationModal = () => {
|
||||
setShowMemberInvitationModal(false);
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
{!isPending && (
|
||||
<>
|
||||
<div>
|
||||
{team && (
|
||||
<>
|
||||
{isInviteOpen && (
|
||||
<TeamInviteList
|
||||
teams={[
|
||||
{
|
||||
id: team.id,
|
||||
accepted: team.membership.accepted || false,
|
||||
name: team.name,
|
||||
slug: team.slug,
|
||||
role: team.membership.role,
|
||||
},
|
||||
]}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
|
||||
{((team?.isPrivate && isAdmin) || !team?.isPrivate || isOrgAdminOrOwner) && team && (
|
||||
<div className="mb-6">
|
||||
<MemberList
|
||||
team={team}
|
||||
isOrgAdminOrOwner={isOrgAdminOrOwner}
|
||||
setShowMemberInvitationModal={setShowMemberInvitationModal}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
{showMemberInvitationModal && team && team.id && (
|
||||
<MemberInvitationModalWithoutMembers
|
||||
hideInvitationModal={hideInvitationModal}
|
||||
showMemberInvitationModal={showMemberInvitationModal}
|
||||
teamId={team.id}
|
||||
token={team.inviteToken?.token}
|
||||
onSettingsOpen={() => setInviteLinkSettingsModal(true)}
|
||||
/>
|
||||
)}
|
||||
|
||||
{showInviteLinkSettingsModal && team?.inviteToken && team.id && (
|
||||
<InviteLinkSettingsModal
|
||||
isOpen={showInviteLinkSettingsModal}
|
||||
teamId={team.id}
|
||||
token={team.inviteToken.token}
|
||||
expiresInDays={team.inviteToken.expiresInDays || undefined}
|
||||
onExit={() => {
|
||||
setInviteLinkSettingsModal(false);
|
||||
setShowMemberInvitationModal(true);
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export default MembersView;
|
||||
@@ -1,499 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { useSession } from "next-auth/react";
|
||||
import Link from "next/link";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useEffect, useLayoutEffect, useState } from "react";
|
||||
import { Controller, useForm } from "react-hook-form";
|
||||
import { z } from "zod";
|
||||
|
||||
import { checkAdminOrOwner } from "@calcom/features/auth/lib/checkAdminOrOwner";
|
||||
import { Dialog } from "@calcom/features/components/controlled-dialog";
|
||||
import { getTeamUrlSync } from "@calcom/features/ee/organizations/lib/getTeamUrlSync";
|
||||
import { trackFormbricksAction } from "@calcom/features/formbricks/formbricks-client";
|
||||
import SectionBottomActions from "@calcom/features/settings/SectionBottomActions";
|
||||
import { IS_TEAM_BILLING_ENABLED, WEBAPP_URL } from "@calcom/lib/constants";
|
||||
import { getPlaceholderAvatar } from "@calcom/lib/defaultAvatarImage";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { useParamsWithFallback } from "@calcom/lib/hooks/useParamsWithFallback";
|
||||
import { md } from "@calcom/lib/markdownIt";
|
||||
import { markdownToSafeHTML } from "@calcom/lib/markdownToSafeHTML";
|
||||
import objectKeys from "@calcom/lib/objectKeys";
|
||||
import slugify from "@calcom/lib/slugify";
|
||||
import turndown from "@calcom/lib/turndownService";
|
||||
import type { Prisma } from "@calcom/prisma/client";
|
||||
import type { RouterOutputs } from "@calcom/trpc/react";
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
import { Avatar } from "@calcom/ui/components/avatar";
|
||||
import { Button, LinkIconButton } from "@calcom/ui/components/button";
|
||||
import { DialogTrigger, ConfirmationDialogContent } from "@calcom/ui/components/dialog";
|
||||
import { Editor } from "@calcom/ui/components/editor";
|
||||
import { Form } from "@calcom/ui/components/form";
|
||||
import { Label } from "@calcom/ui/components/form";
|
||||
import { TextField } from "@calcom/ui/components/form";
|
||||
import { Icon } from "@calcom/ui/components/icon";
|
||||
import { ImageUploader } from "@calcom/ui/components/image-uploader";
|
||||
import {
|
||||
SkeletonButton,
|
||||
SkeletonContainer,
|
||||
SkeletonText,
|
||||
SkeletonAvatar,
|
||||
} from "@calcom/ui/components/skeleton";
|
||||
import { showToast } from "@calcom/ui/components/toast";
|
||||
import { Tooltip } from "@calcom/ui/components/tooltip";
|
||||
import { revalidateTeamDataCache } from "@calcom/web/app/(booking-page-wrapper)/team/[slug]/[type]/actions";
|
||||
import { revalidateEventTypesList } from "@calcom/web/app/(use-page-wrapper)/(main-nav)/event-types/actions";
|
||||
import { revalidateTeamsList } from "@calcom/web/app/(use-page-wrapper)/(main-nav)/teams/actions";
|
||||
|
||||
const regex = new RegExp("^[a-zA-Z0-9-]*$");
|
||||
|
||||
|
||||
|
||||
const SkeletonLoader = () => {
|
||||
return (
|
||||
<SkeletonContainer>
|
||||
<div className="border-subtle stack-y-6 rounded-b-xl border border-t-0 px-4 py-8">
|
||||
<div className="flex items-center">
|
||||
<SkeletonAvatar className="me-4 mt-0 h-16 w-16 px-4" />
|
||||
<SkeletonButton className="h-6 w-32 rounded-md p-5" />
|
||||
</div>
|
||||
<SkeletonText className="h-8 w-full" />
|
||||
<SkeletonText className="h-8 w-full" />
|
||||
<SkeletonText className="h-8 w-full" />
|
||||
|
||||
<SkeletonButton className="mr-6 h-8 w-20 rounded-md p-5" />
|
||||
</div>
|
||||
</SkeletonContainer>
|
||||
);
|
||||
};
|
||||
|
||||
const ProfileView = () => {
|
||||
const params = useParamsWithFallback();
|
||||
const teamId = Number(params.id);
|
||||
const { t } = useLocale();
|
||||
const router = useRouter();
|
||||
const utils = trpc.useUtils();
|
||||
const session = useSession();
|
||||
|
||||
useLayoutEffect(() => {
|
||||
document.body.focus();
|
||||
}, []);
|
||||
|
||||
const {
|
||||
data: team,
|
||||
isPending,
|
||||
error,
|
||||
} = trpc.viewer.teams.get.useQuery(
|
||||
{ teamId },
|
||||
{
|
||||
enabled: !!teamId,
|
||||
}
|
||||
);
|
||||
|
||||
useEffect(
|
||||
function refactorMeWithoutEffect() {
|
||||
if (error) {
|
||||
router.replace("/teams");
|
||||
}
|
||||
},
|
||||
[error]
|
||||
);
|
||||
const isAdmin = team && checkAdminOrOwner(team.membership.role);
|
||||
|
||||
const permalink = team
|
||||
? `${getTeamUrlSync({
|
||||
orgSlug: team.parent ? team.parent.slug : null,
|
||||
teamSlug: team.slug,
|
||||
})}`
|
||||
: "";
|
||||
|
||||
const isBioEmpty = !team || !team.bio || !team.bio.replace("<p><br></p>", "").length;
|
||||
|
||||
const deleteTeamMutation = trpc.viewer.teams.delete.useMutation({
|
||||
async onSuccess() {
|
||||
revalidateTeamsList();
|
||||
await utils.viewer.teams.list.invalidate();
|
||||
await utils.viewer.eventTypes.getUserEventGroups.invalidate();
|
||||
revalidateEventTypesList();
|
||||
await utils.viewer.eventTypes.getByViewer.invalidate();
|
||||
showToast(t("your_team_disbanded_successfully"), "success");
|
||||
router.push(`${WEBAPP_URL}/teams`);
|
||||
trackFormbricksAction("team_disbanded");
|
||||
},
|
||||
async onError(err) {
|
||||
showToast(err.message, "error");
|
||||
},
|
||||
});
|
||||
|
||||
const removeMemberMutation = trpc.viewer.teams.removeMember.useMutation({
|
||||
async onSuccess() {
|
||||
await utils.viewer.teams.get.invalidate();
|
||||
await utils.viewer.teams.list.invalidate();
|
||||
revalidateTeamsList();
|
||||
await utils.viewer.eventTypes.invalidate();
|
||||
showToast(t("success"), "success");
|
||||
},
|
||||
async onError(err) {
|
||||
showToast(err.message, "error");
|
||||
},
|
||||
});
|
||||
|
||||
function deleteTeam() {
|
||||
if (team?.id) deleteTeamMutation.mutate({ teamId: team.id });
|
||||
}
|
||||
|
||||
function leaveTeam() {
|
||||
if (team?.id && session.data)
|
||||
removeMemberMutation.mutate({
|
||||
teamIds: [team.id],
|
||||
memberIds: [session.data.user.id],
|
||||
});
|
||||
}
|
||||
|
||||
if (isPending) {
|
||||
return <SkeletonLoader />;
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
{isAdmin ? (
|
||||
<TeamProfileForm team={team} teamId={teamId} />
|
||||
) : (
|
||||
<div className="border-subtle flex rounded-b-xl border border-t-0 px-4 py-8 sm:px-6">
|
||||
<div className="grow">
|
||||
<div>
|
||||
<Label className="text-emphasis">{t("team_name")}</Label>
|
||||
<p className="text-default text-sm">{team?.name}</p>
|
||||
</div>
|
||||
{team && !isBioEmpty && (
|
||||
<>
|
||||
<Label className="text-emphasis mt-5">{t("about")}</Label>
|
||||
<div
|
||||
className=" text-subtle wrap-break-word text-sm [&_a]:text-blue-500 [&_a]:underline [&_a]:hover:text-blue-600"
|
||||
dangerouslySetInnerHTML={{ __html: markdownToSafeHTML(team.bio ?? null) }}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
<div>
|
||||
<Link href={permalink} passHref={true} target="_blank">
|
||||
<LinkIconButton Icon="external-link">{t("preview")}</LinkIconButton>
|
||||
</Link>
|
||||
<LinkIconButton
|
||||
Icon="link"
|
||||
onClick={() => {
|
||||
navigator.clipboard.writeText(permalink);
|
||||
showToast("Copied to clipboard", "success");
|
||||
}}>
|
||||
{t("copy_link_team")}
|
||||
</LinkIconButton>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="border-subtle mt-6 rounded-lg rounded-b-none border border-b-0 p-6">
|
||||
<Label className="mb-0 text-base font-semibold text-red-700">{t("danger_zone")}</Label>
|
||||
{team?.membership.role === "OWNER" && (
|
||||
<p className="text-subtle text-sm">{t("team_deletion_cannot_be_undone")}</p>
|
||||
)}
|
||||
</div>
|
||||
{team?.membership.role === "OWNER" ? (
|
||||
<Dialog>
|
||||
<SectionBottomActions align="end">
|
||||
<DialogTrigger asChild>
|
||||
<Button
|
||||
color="destructive"
|
||||
className="border"
|
||||
StartIcon="trash-2"
|
||||
data-testid="disband-team-button">
|
||||
{t("disband_team")}
|
||||
</Button>
|
||||
</DialogTrigger>
|
||||
</SectionBottomActions>
|
||||
<ConfirmationDialogContent
|
||||
variety="danger"
|
||||
title={t("disband_team")}
|
||||
confirmBtnText={t("confirm_disband_team")}
|
||||
onConfirm={() => {
|
||||
deleteTeam();
|
||||
}}>
|
||||
{t("disband_team_confirmation_message")}
|
||||
</ConfirmationDialogContent>
|
||||
</Dialog>
|
||||
) : (
|
||||
<Dialog>
|
||||
<SectionBottomActions align="end">
|
||||
<DialogTrigger asChild>
|
||||
<Button color="destructive" className="border" StartIcon="log-out">
|
||||
{t("leave_team")}
|
||||
</Button>
|
||||
</DialogTrigger>
|
||||
</SectionBottomActions>
|
||||
<ConfirmationDialogContent
|
||||
variety="danger"
|
||||
title={t("leave_team")}
|
||||
confirmBtnText={t("confirm_leave_team")}
|
||||
onConfirm={leaveTeam}>
|
||||
{t("leave_team_confirmation_message")}
|
||||
</ConfirmationDialogContent>
|
||||
</Dialog>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export type TeamProfileFormProps = {
|
||||
team: RouterOutputs["viewer"]["teams"]["get"];
|
||||
teamId: number;
|
||||
};
|
||||
|
||||
const TeamProfileForm = ({ team, teamId }: TeamProfileFormProps) => {
|
||||
const utils = trpc.useUtils();
|
||||
const { t } = useLocale();
|
||||
const router = useRouter();
|
||||
|
||||
const teamProfileFormSchema = z.object({
|
||||
id: z.number(),
|
||||
name: z
|
||||
.string()
|
||||
.trim()
|
||||
.min(1,t("must_enter_team_name")),
|
||||
slug: z
|
||||
.string()
|
||||
.regex(regex, {
|
||||
message: "Url can only have alphanumeric characters(a-z, 0-9) and hyphen(-) symbol.",
|
||||
})
|
||||
.min(1, t("team_url_required")),
|
||||
logo: z.string().nullable(),
|
||||
bio: z.string(),
|
||||
});
|
||||
|
||||
type FormValues = z.infer<typeof teamProfileFormSchema>;
|
||||
|
||||
const mutation = trpc.viewer.teams.update.useMutation({
|
||||
onError: (err) => {
|
||||
showToast(err.message, "error");
|
||||
},
|
||||
async onSuccess(res) {
|
||||
reset({
|
||||
logo: res?.logoUrl,
|
||||
name: (res?.name || "") as string,
|
||||
bio: (res?.bio || "") as string,
|
||||
slug: res?.slug as string,
|
||||
});
|
||||
await utils.viewer.teams.get.invalidate();
|
||||
await utils.viewer.eventTypes.getUserEventGroups.invalidate();
|
||||
revalidateEventTypesList();
|
||||
// TODO: Not all changes require list invalidation
|
||||
await utils.viewer.teams.list.invalidate();
|
||||
revalidateTeamsList();
|
||||
|
||||
if (res?.slug) {
|
||||
await revalidateTeamDataCache({
|
||||
teamSlug: res.slug,
|
||||
orgSlug: team?.parent?.slug ?? null,
|
||||
});
|
||||
}
|
||||
|
||||
showToast(t("your_team_updated_successfully"), "success");
|
||||
},
|
||||
});
|
||||
|
||||
const defaultValues: FormValues = {
|
||||
id: team?.id,
|
||||
name: team?.name || "",
|
||||
logo: team?.logo || "",
|
||||
bio: team?.bio || "",
|
||||
slug: team?.slug || ((team?.metadata as Prisma.JsonObject)?.requestedSlug as string) || "",
|
||||
};
|
||||
|
||||
const form = useForm({
|
||||
defaultValues,
|
||||
resolver: zodResolver(teamProfileFormSchema),
|
||||
});
|
||||
|
||||
const [firstRender, setFirstRender] = useState(true);
|
||||
|
||||
const {
|
||||
formState: { isSubmitting, isDirty },
|
||||
reset,
|
||||
} = form;
|
||||
|
||||
const isDisabled = isSubmitting || !isDirty;
|
||||
|
||||
const publishMutation = trpc.viewer.teams.publish.useMutation({
|
||||
async onSuccess(data: { url?: string }) {
|
||||
if (data.url) {
|
||||
router.push(data.url);
|
||||
}
|
||||
},
|
||||
async onError(err) {
|
||||
showToast(err.message, "error");
|
||||
},
|
||||
});
|
||||
|
||||
const handleCopy = async (value: string) => {
|
||||
try {
|
||||
await navigator.clipboard.writeText(value);
|
||||
showToast(t("team_id_copied"), "success");
|
||||
} catch {
|
||||
showToast(t("error_copying_to_clipboard"), "error");
|
||||
}
|
||||
};
|
||||
return (
|
||||
<Form
|
||||
form={form}
|
||||
handleSubmit={(values) => {
|
||||
if (team) {
|
||||
const variables = {
|
||||
name: values.name,
|
||||
slug: values.slug,
|
||||
bio: values.bio,
|
||||
logo: values.logo,
|
||||
};
|
||||
objectKeys(variables).forEach((key) => {
|
||||
if (variables[key as keyof typeof variables] === team?.[key]) delete variables[key];
|
||||
});
|
||||
mutation.mutate({ id: team.id, ...variables });
|
||||
}
|
||||
}}>
|
||||
<div className="border-subtle border-x px-4 py-8 sm:px-6">
|
||||
{!team.parent && (
|
||||
<div className="flex items-center pb-8">
|
||||
<Controller
|
||||
control={form.control}
|
||||
name="logo"
|
||||
render={({ field: { value, onChange } }) => {
|
||||
const showRemoveLogoButton = !!value;
|
||||
|
||||
return (
|
||||
<>
|
||||
<Avatar
|
||||
alt={form.getValues("name")}
|
||||
data-testid="profile-upload-logo"
|
||||
imageSrc={getPlaceholderAvatar(value, form.getValues("name"))}
|
||||
size="lg"
|
||||
/>
|
||||
<div className="ms-4 flex gap-2">
|
||||
<ImageUploader
|
||||
target="logo"
|
||||
id="avatar-upload"
|
||||
buttonMsg={t("upload_logo")}
|
||||
handleAvatarChange={onChange}
|
||||
triggerButtonColor={showRemoveLogoButton ? "secondary" : "primary"}
|
||||
imageSrc={getPlaceholderAvatar(value, form.getValues("name"))}
|
||||
/>
|
||||
{showRemoveLogoButton && (
|
||||
<Button color="secondary" onClick={() => onChange(null)}>
|
||||
{t("remove")}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<Controller
|
||||
control={form.control}
|
||||
name="name"
|
||||
render={({ field: { name, value, onChange } }) => (
|
||||
<TextField
|
||||
name={name}
|
||||
label={t("team_name")}
|
||||
value={value}
|
||||
onChange={(e) => onChange(e?.target.value)}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
<Controller
|
||||
control={form.control}
|
||||
name="slug"
|
||||
render={({ field: { value } }) => (
|
||||
<div className="mt-8">
|
||||
<TextField
|
||||
name="slug"
|
||||
label={t("team_url")}
|
||||
value={value}
|
||||
data-testid="team-url"
|
||||
addOnClassname="testid-leading-text-team-url"
|
||||
addOnLeading={`${getTeamUrlSync(
|
||||
{ orgSlug: team.parent ? team.parent.slug : null, teamSlug: null },
|
||||
{
|
||||
protocol: false,
|
||||
}
|
||||
)}`}
|
||||
onChange={(e) => {
|
||||
form.clearErrors("slug");
|
||||
form.setValue("slug", slugify(e?.target.value, true), { shouldDirty: true });
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
/>
|
||||
|
||||
<div className="mt-8">
|
||||
<TextField
|
||||
name="id"
|
||||
label={t("team_id")}
|
||||
value={teamId}
|
||||
disabled={true}
|
||||
addOnSuffix={
|
||||
<Tooltip content={t("copy_to_clipboard")}>
|
||||
<Button
|
||||
color="minimal"
|
||||
size="sm"
|
||||
type="button"
|
||||
aria-label="copy team id"
|
||||
onClick={() => handleCopy(teamId.toString())}>
|
||||
<Icon name="copy" className="ml-1 h-4 w-4" />
|
||||
</Button>
|
||||
</Tooltip>
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
<div className="mt-8">
|
||||
<Label>{t("about")}</Label>
|
||||
<Editor
|
||||
getText={() => md.render(form.getValues("bio") || "")}
|
||||
setText={(value: string) => form.setValue("bio", turndown(value), { shouldDirty: true })}
|
||||
excludedToolbarItems={["blockType"]}
|
||||
disableLists
|
||||
firstRender={firstRender}
|
||||
setFirstRender={setFirstRender}
|
||||
height="80px"
|
||||
/>
|
||||
</div>
|
||||
<p className="text-default mt-2 text-sm">{t("team_description")}</p>
|
||||
</div>
|
||||
<SectionBottomActions align="end">
|
||||
<Button
|
||||
color="primary"
|
||||
type="submit"
|
||||
loading={mutation.isPending}
|
||||
disabled={isDisabled}
|
||||
data-testid="update-team-profile">
|
||||
{t("update")}
|
||||
</Button>
|
||||
{IS_TEAM_BILLING_ENABLED &&
|
||||
team.slug === null &&
|
||||
(team.metadata as Prisma.JsonObject)?.requestedSlug && (
|
||||
<Button
|
||||
color="secondary"
|
||||
className="ml-2"
|
||||
type="button"
|
||||
onClick={() => {
|
||||
publishMutation.mutate({ teamId: team.id });
|
||||
}}>
|
||||
{t("team_publish")}
|
||||
</Button>
|
||||
)}
|
||||
</SectionBottomActions>
|
||||
</Form>
|
||||
);
|
||||
};
|
||||
|
||||
export default ProfileView;
|
||||
@@ -1,227 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { useSession } from "next-auth/react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useEffect } from "react";
|
||||
import { useForm, Controller } from "react-hook-form";
|
||||
|
||||
import { checkAdminOrOwner } from "@calcom/features/auth/lib/checkAdminOrOwner";
|
||||
import { AppearanceSkeletonLoader } from "@calcom/features/ee/components/CommonSkeletonLoaders";
|
||||
import { IntervalLimitsManager } from "@calcom/features/eventtypes/components/tabs/limits/EventLimitsTab";
|
||||
import SectionBottomActions from "@calcom/features/settings/SectionBottomActions";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { useParamsWithFallback } from "@calcom/lib/hooks/useParamsWithFallback";
|
||||
import type { IntervalLimit } from "@calcom/lib/intervalLimits/intervalLimitSchema";
|
||||
import { validateIntervalLimitOrder } from "@calcom/lib/intervalLimits/validateIntervalLimitOrder";
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
import type { RouterOutputs } from "@calcom/trpc/react";
|
||||
import classNames from "@calcom/ui/classNames";
|
||||
import { Button } from "@calcom/ui/components/button";
|
||||
import { Form } from "@calcom/ui/components/form";
|
||||
import { SettingsToggle } from "@calcom/ui/components/form";
|
||||
import { CheckboxField } from "@calcom/ui/components/form";
|
||||
import { showToast } from "@calcom/ui/components/toast";
|
||||
import { revalidateTeamDataCache } from "@calcom/web/app/(booking-page-wrapper)/team/[slug]/[type]/actions";
|
||||
|
||||
import DisableTeamImpersonation from "../components/DisableTeamImpersonation";
|
||||
import { default as InternalNotePresetsView } from "../components/InternalNotePresetsView";
|
||||
import MakeTeamPrivateSwitch from "../components/MakeTeamPrivateSwitch";
|
||||
import RoundRobinSettings from "../components/RoundRobinSettings";
|
||||
|
||||
type ProfileViewProps = { team: RouterOutputs["viewer"]["teams"]["get"] };
|
||||
|
||||
const BookingLimitsView = ({ team }: ProfileViewProps) => {
|
||||
const { t } = useLocale();
|
||||
const utils = trpc.useUtils();
|
||||
|
||||
const form = useForm<{ bookingLimits?: IntervalLimit; includeManagedEventsInLimits: boolean }>({
|
||||
defaultValues: {
|
||||
bookingLimits: team?.bookingLimits || undefined,
|
||||
includeManagedEventsInLimits: team?.includeManagedEventsInLimits ?? false,
|
||||
},
|
||||
});
|
||||
|
||||
const {
|
||||
formState: { isSubmitting, isDirty },
|
||||
reset,
|
||||
} = form;
|
||||
|
||||
const mutation = trpc.viewer.teams.update.useMutation({
|
||||
onError: (err) => {
|
||||
showToast(err.message, "error");
|
||||
},
|
||||
async onSuccess(res) {
|
||||
await utils.viewer.teams.get.invalidate();
|
||||
if (res) {
|
||||
reset({
|
||||
bookingLimits: res.bookingLimits,
|
||||
includeManagedEventsInLimits: res.includeManagedEventsInLimits,
|
||||
});
|
||||
}
|
||||
if (team?.slug) {
|
||||
// Booking limits are enforced during slot generation, which relies on the same cached team data.
|
||||
revalidateTeamDataCache({
|
||||
teamSlug: team.slug,
|
||||
orgSlug: team.parent?.slug ?? null,
|
||||
});
|
||||
}
|
||||
showToast(t("booking_limits_updated_successfully"), "success");
|
||||
},
|
||||
});
|
||||
|
||||
const isAdmin = team && checkAdminOrOwner(team.membership.role);
|
||||
|
||||
return (
|
||||
<>
|
||||
{isAdmin ? (
|
||||
<>
|
||||
<Form
|
||||
form={form}
|
||||
handleSubmit={(values) => {
|
||||
if (values.bookingLimits) {
|
||||
const isValid = validateIntervalLimitOrder(values.bookingLimits);
|
||||
if (!isValid) {
|
||||
reset();
|
||||
throw new Error(t("event_setup_booking_limits_error"));
|
||||
}
|
||||
}
|
||||
mutation.mutate({ ...values, id: team.id });
|
||||
}}>
|
||||
<Controller
|
||||
name="bookingLimits"
|
||||
render={({ field: { value } }) => {
|
||||
const isChecked = Object.keys(value ?? {}).length > 0;
|
||||
return (
|
||||
<SettingsToggle
|
||||
toggleSwitchAtTheEnd={true}
|
||||
labelClassName="text-sm"
|
||||
title={t("limit_booking_frequency")}
|
||||
description={t("limit_team_booking_frequency_description")}
|
||||
checked={isChecked}
|
||||
onCheckedChange={(active) => {
|
||||
if (active) {
|
||||
form.setValue("bookingLimits", {
|
||||
PER_DAY: 1,
|
||||
});
|
||||
} else {
|
||||
form.setValue("bookingLimits", {});
|
||||
form.setValue("includeManagedEventsInLimits", false);
|
||||
}
|
||||
const bookingLimits = form.getValues("bookingLimits");
|
||||
const includeManagedEventsInLimits = form.getValues("includeManagedEventsInLimits");
|
||||
|
||||
mutation.mutate({ bookingLimits, includeManagedEventsInLimits, id: team.id });
|
||||
}}
|
||||
switchContainerClassName={classNames(
|
||||
"border-subtle mt-6 rounded-lg border py-6 px-4 sm:px-6",
|
||||
isChecked && "rounded-b-none"
|
||||
)}
|
||||
childrenClassName="lg:ml-0">
|
||||
<div className="border-subtle border border-y-0 p-6">
|
||||
<Controller
|
||||
name="includeManagedEventsInLimits"
|
||||
render={({ field: { value, onChange } }) => (
|
||||
<CheckboxField
|
||||
description={t("count_managed_to_limit")}
|
||||
descriptionAsLabel
|
||||
onChange={(e) => onChange(e)}
|
||||
checked={value}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
|
||||
<div className="pt-6">
|
||||
<IntervalLimitsManager propertyName="bookingLimits" defaultLimit={1} step={1} />
|
||||
</div>
|
||||
</div>
|
||||
<SectionBottomActions className="mb-6" align="end">
|
||||
<Button disabled={isSubmitting || !isDirty} type="submit" color="primary">
|
||||
{t("update")}
|
||||
</Button>
|
||||
</SectionBottomActions>
|
||||
</SettingsToggle>
|
||||
);
|
||||
}}
|
||||
/>
|
||||
</Form>
|
||||
</>
|
||||
) : (
|
||||
<div className="border-subtle rounded-md border p-5">
|
||||
<span className="text-default text-sm">{t("only_owner_change")}</span>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
const PrivacySettingsView = ({ team }: ProfileViewProps) => {
|
||||
const session = useSession();
|
||||
const isAdmin = team && checkAdminOrOwner(team.membership.role);
|
||||
const isOrgAdminOrOwner = checkAdminOrOwner(session?.data?.user.org?.role);
|
||||
const isInviteOpen = !team?.membership.accepted;
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="mt-6">
|
||||
{team && session.data && (
|
||||
<DisableTeamImpersonation
|
||||
teamId={team.id}
|
||||
memberId={session.data.user.id}
|
||||
disabled={isInviteOpen}
|
||||
/>
|
||||
)}
|
||||
|
||||
{team && team.id && (isAdmin || isOrgAdminOrOwner) && (
|
||||
<div className="mt-6">
|
||||
<MakeTeamPrivateSwitch
|
||||
isOrg={false}
|
||||
teamId={team.id}
|
||||
isPrivate={team.isPrivate ?? false}
|
||||
disabled={isInviteOpen}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
const TeamSettingsViewWrapper = () => {
|
||||
const router = useRouter();
|
||||
const params = useParamsWithFallback();
|
||||
|
||||
const {
|
||||
data: team,
|
||||
isPending,
|
||||
error,
|
||||
} = trpc.viewer.teams.get.useQuery(
|
||||
{ teamId: Number(params.id) },
|
||||
{
|
||||
enabled: !!Number(params.id),
|
||||
}
|
||||
);
|
||||
|
||||
useEffect(
|
||||
function refactorMeWithoutEffect() {
|
||||
if (error) {
|
||||
router.replace("/teams");
|
||||
}
|
||||
},
|
||||
[error]
|
||||
);
|
||||
|
||||
if (isPending) return <AppearanceSkeletonLoader />;
|
||||
|
||||
if (!team) return null;
|
||||
|
||||
return (
|
||||
<>
|
||||
<BookingLimitsView team={team} />
|
||||
<PrivacySettingsView team={team} />
|
||||
<InternalNotePresetsView team={team} />
|
||||
<RoundRobinSettings team={team} />
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export default TeamSettingsViewWrapper;
|
||||
@@ -1,203 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { useRouter } from "next/navigation";
|
||||
import { Suspense, useEffect, useState } from "react";
|
||||
|
||||
import dayjs from "@calcom/dayjs";
|
||||
import { useHasTeamPlan } from "@calcom/features/billing/hooks/useHasPaidPlan";
|
||||
import { Dialog } from "@calcom/features/components/controlled-dialog";
|
||||
import LicenseRequired from "@calcom/features/ee/common/components/LicenseRequired";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import type { RecordingItemSchema } from "@calcom/prisma/zod-utils";
|
||||
import type { RouterOutputs } from "@calcom/trpc/react";
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
import type { PartialReference } from "@calcom/types/EventManager";
|
||||
import { Button } from "@calcom/ui/components/button";
|
||||
import { DialogContent, DialogFooter, DialogHeader, DialogClose } from "@calcom/ui/components/dialog";
|
||||
|
||||
import RecordingListSkeleton from "./components/RecordingListSkeleton";
|
||||
|
||||
type BookingItem = RouterOutputs["viewer"]["bookings"]["get"]["bookings"][number];
|
||||
|
||||
interface IViewRecordingsDialog {
|
||||
booking?: BookingItem;
|
||||
isOpenDialog: boolean;
|
||||
setIsOpenDialog: React.Dispatch<React.SetStateAction<boolean>>;
|
||||
timeFormat: number | null;
|
||||
}
|
||||
|
||||
function convertSecondsToMs(seconds: number) {
|
||||
// Bitwise Double Not is faster than Math.floor
|
||||
const minutes = ~~(seconds / 60);
|
||||
const extraSeconds = seconds % 60;
|
||||
return `${minutes}min ${extraSeconds}sec`;
|
||||
}
|
||||
|
||||
interface GetTimeSpanProps {
|
||||
startTime: string | undefined;
|
||||
endTime: string | undefined;
|
||||
locale: string;
|
||||
hour12: boolean;
|
||||
}
|
||||
|
||||
const getTimeSpan = ({ startTime, endTime, locale, hour12 }: GetTimeSpanProps) => {
|
||||
if (!startTime || !endTime) return "";
|
||||
|
||||
const formattedStartTime = new Intl.DateTimeFormat(locale, {
|
||||
hour: "numeric",
|
||||
minute: "numeric",
|
||||
hour12,
|
||||
}).format(new Date(startTime));
|
||||
|
||||
const formattedEndTime = new Intl.DateTimeFormat(locale, {
|
||||
hour: "numeric",
|
||||
minute: "numeric",
|
||||
hour12,
|
||||
}).format(new Date(endTime));
|
||||
|
||||
return `${formattedStartTime} - ${formattedEndTime}`;
|
||||
};
|
||||
|
||||
const useRecordingDownload = () => {
|
||||
const [recordingId, setRecordingId] = useState("");
|
||||
const { isFetching, data } = trpc.viewer.calVideo.getDownloadLinkOfCalVideoRecordings.useQuery(
|
||||
{
|
||||
recordingId,
|
||||
},
|
||||
{
|
||||
enabled: !!recordingId,
|
||||
gcTime: 0,
|
||||
refetchOnWindowFocus: false,
|
||||
refetchOnReconnect: false,
|
||||
retry: false,
|
||||
}
|
||||
);
|
||||
|
||||
useEffect(
|
||||
function refactorMeWithoutEffect() {
|
||||
if (data && data.download_link) {
|
||||
window.open(data.download_link, "_blank", "noopener,noreferrer");
|
||||
}
|
||||
},
|
||||
[data]
|
||||
);
|
||||
return {
|
||||
setRecordingId: (newRecordingId: string) => {
|
||||
if (recordingId === newRecordingId && data) {
|
||||
window.open(data.download_link, "_blank", "noopener,noreferrer");
|
||||
}
|
||||
if (!isFetching) {
|
||||
setRecordingId(newRecordingId);
|
||||
}
|
||||
},
|
||||
isFetching,
|
||||
recordingId,
|
||||
};
|
||||
};
|
||||
|
||||
const ViewRecordingsList = ({ roomName, hasTeamPlan }: { roomName: string; hasTeamPlan: boolean }) => {
|
||||
const { t } = useLocale();
|
||||
const { setRecordingId, isFetching, recordingId } = useRecordingDownload();
|
||||
const router = useRouter();
|
||||
|
||||
const { data: recordings } = trpc.viewer.calVideo.getCalVideoRecordings.useQuery(
|
||||
{ roomName },
|
||||
{
|
||||
suspense: true,
|
||||
}
|
||||
);
|
||||
|
||||
const handleDownloadClick = async (recordingId: string) => {
|
||||
// this would enable the getDownloadLinkOfCalVideoRecordings
|
||||
setRecordingId(recordingId);
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
{recordings && "data" in recordings && recordings?.data?.length > 0 ? (
|
||||
<div className="flex flex-col gap-3">
|
||||
{recordings.data.map((recording: RecordingItemSchema, index: number) => {
|
||||
return (
|
||||
<div
|
||||
className="border-subtle flex w-full items-center justify-between rounded-md border px-4 py-2"
|
||||
key={recording.id}>
|
||||
<div className="flex flex-col">
|
||||
<h1 className="text-sm font-semibold">
|
||||
{t("recording")} {index + 1}
|
||||
</h1>
|
||||
<p className="text-subtle text-sm font-normal">{convertSecondsToMs(recording.duration)}</p>
|
||||
</div>
|
||||
{hasTeamPlan ? (
|
||||
<Button
|
||||
StartIcon="download"
|
||||
className="ml-4 lg:ml-0"
|
||||
loading={isFetching && recordingId === recording.id}
|
||||
onClick={() => handleDownloadClick(recording.id)}>
|
||||
{t("download")}
|
||||
</Button>
|
||||
) : (
|
||||
<Button
|
||||
tooltip={t("upgrade_to_access_recordings_description")}
|
||||
className="ml-4 lg:ml-0"
|
||||
onClick={() => router.push("/teams")}>
|
||||
{t("upgrade")}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
) : (
|
||||
(!recordings || (recordings && "total_count" in recordings && recordings?.total_count === 0)) && (
|
||||
<p className="font-semibold">{t("no_recordings_found")}</p>
|
||||
)
|
||||
)}
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export const ViewRecordingsDialog = (props: IViewRecordingsDialog) => {
|
||||
const { t, i18n } = useLocale();
|
||||
const { isOpenDialog, setIsOpenDialog, booking, timeFormat } = props;
|
||||
|
||||
const { hasTeamPlan, isPending: isTeamPlanStatusLoading } = useHasTeamPlan();
|
||||
|
||||
const roomName =
|
||||
booking?.references?.find((reference: PartialReference) => reference.type === "daily_video")?.meetingId ??
|
||||
undefined;
|
||||
|
||||
const subtitle = `${booking?.title} - ${dayjs(booking?.startTime).format("ddd")} ${dayjs(
|
||||
booking?.startTime
|
||||
).format("D")}, ${dayjs(booking?.startTime).format("MMM")} ${getTimeSpan({
|
||||
startTime: booking?.startTime,
|
||||
endTime: booking?.endTime,
|
||||
locale: i18n.language,
|
||||
hour12: timeFormat === 12,
|
||||
})} `;
|
||||
|
||||
return (
|
||||
<Dialog open={isOpenDialog} onOpenChange={setIsOpenDialog}>
|
||||
<DialogContent enableOverflow>
|
||||
<DialogHeader title={t("recordings_title")} subtitle={subtitle} />
|
||||
{roomName ? (
|
||||
<LicenseRequired>
|
||||
{isTeamPlanStatusLoading ? (
|
||||
<RecordingListSkeleton />
|
||||
) : (
|
||||
<Suspense fallback={<RecordingListSkeleton />}>
|
||||
<ViewRecordingsList hasTeamPlan={!!hasTeamPlan} roomName={roomName} />
|
||||
</Suspense>
|
||||
)}
|
||||
</LicenseRequired>
|
||||
) : (
|
||||
<p className="font-semibold">{t("no_recordings_found")}</p>
|
||||
)}
|
||||
<DialogFooter>
|
||||
<DialogClose className="border" />
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
};
|
||||
|
||||
export default ViewRecordingsDialog;
|
||||
@@ -1,19 +0,0 @@
|
||||
import { SkeletonText, SkeletonButton } from "@calcom/ui/components/skeleton";
|
||||
|
||||
export default function RecordingListItemSkeleton() {
|
||||
return (
|
||||
<div className="flex w-full justify-between rounded-md border p-2">
|
||||
<div>
|
||||
<p className="text-emphasis pt-2 text-sm font-medium">
|
||||
<SkeletonText className="h-3 w-56" />
|
||||
</p>
|
||||
<div className="mt-1 w-max">
|
||||
<SkeletonText className="h-3 w-28" />
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center">
|
||||
<SkeletonButton className="h-5 w-28 rounded-md px-4 py-4" />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,15 +0,0 @@
|
||||
import { SkeletonContainer } from "@calcom/ui/components/skeleton";
|
||||
|
||||
import RecordingListItemSkeleton from "./RecordingListItemSkeleton";
|
||||
|
||||
export default function RecordingListSkeleton() {
|
||||
return (
|
||||
<SkeletonContainer>
|
||||
<div className="flex flex-col gap-3">
|
||||
<RecordingListItemSkeleton />
|
||||
<RecordingListItemSkeleton />
|
||||
<RecordingListItemSkeleton />
|
||||
</div>
|
||||
</SkeletonContainer>
|
||||
);
|
||||
}
|
||||
@@ -1,279 +0,0 @@
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { isValidPhoneNumber } from "libphonenumber-js/max";
|
||||
import type { Dispatch, SetStateAction } from "react";
|
||||
import { useState } from "react";
|
||||
import { Controller, useForm } from "react-hook-form";
|
||||
import { z } from "zod";
|
||||
|
||||
import { Dialog } from "@calcom/features/components/controlled-dialog";
|
||||
import PhoneInput from "@calcom/features/components/phone-input";
|
||||
import { SENDER_ID, SENDER_NAME } from "@calcom/lib/constants";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { WorkflowActions } from "@calcom/prisma/enums";
|
||||
import { Button } from "@calcom/ui/components/button";
|
||||
import { DialogContent, DialogFooter, DialogClose } from "@calcom/ui/components/dialog";
|
||||
import { EmailField } from "@calcom/ui/components/form";
|
||||
import { Select } from "@calcom/ui/components/form";
|
||||
import { CheckboxField } from "@calcom/ui/components/form";
|
||||
import { Form } from "@calcom/ui/components/form";
|
||||
import { Label } from "@calcom/ui/components/form";
|
||||
import { Input } from "@calcom/ui/components/form";
|
||||
import { Icon } from "@calcom/ui/components/icon";
|
||||
import { Tooltip } from "@calcom/ui/components/tooltip";
|
||||
|
||||
import { WORKFLOW_ACTIONS } from "../lib/constants";
|
||||
import { onlyLettersNumbersSpaces } from "../lib/schema";
|
||||
|
||||
interface IAddActionDialog {
|
||||
isOpenDialog: boolean;
|
||||
setIsOpenDialog: Dispatch<SetStateAction<boolean>>;
|
||||
addAction: (
|
||||
action: WorkflowActions,
|
||||
sendTo?: string,
|
||||
numberRequired?: boolean,
|
||||
senderId?: string,
|
||||
senderName?: string
|
||||
) => void;
|
||||
actionOptions: {
|
||||
label: string;
|
||||
value: WorkflowActions;
|
||||
needsCredits: boolean;
|
||||
creditsTeamId?: number;
|
||||
isOrganization?: boolean;
|
||||
needsTeamsUpgrade?: boolean;
|
||||
}[];
|
||||
}
|
||||
|
||||
interface ISelectActionOption {
|
||||
label: string;
|
||||
value: WorkflowActions;
|
||||
}
|
||||
|
||||
type AddActionFormValues = {
|
||||
action: WorkflowActions;
|
||||
sendTo?: string;
|
||||
numberRequired?: boolean;
|
||||
senderId?: string;
|
||||
senderName?: string;
|
||||
};
|
||||
|
||||
export const AddActionDialog = (props: IAddActionDialog) => {
|
||||
const { t } = useLocale();
|
||||
const { isOpenDialog, setIsOpenDialog, addAction, actionOptions } = props;
|
||||
const [isPhoneNumberNeeded, setIsPhoneNumberNeeded] = useState(false);
|
||||
const [isSenderIdNeeded, setIsSenderIdNeeded] = useState(false);
|
||||
const [isEmailAddressNeeded, setIsEmailAddressNeeded] = useState(false);
|
||||
|
||||
const formSchema = z.object({
|
||||
action: z.enum(WORKFLOW_ACTIONS),
|
||||
sendTo: z
|
||||
.string()
|
||||
.refine((val) => isValidPhoneNumber(val) || val.includes("@"))
|
||||
.optional(),
|
||||
numberRequired: z.boolean().optional(),
|
||||
senderId: z
|
||||
.string()
|
||||
.refine((val) => onlyLettersNumbersSpaces(val))
|
||||
.nullable(),
|
||||
senderName: z.string().nullable(),
|
||||
});
|
||||
|
||||
const form = useForm<AddActionFormValues>({
|
||||
mode: "onSubmit",
|
||||
defaultValues: {
|
||||
action: WorkflowActions.EMAIL_HOST,
|
||||
senderId: SENDER_ID,
|
||||
senderName: SENDER_NAME,
|
||||
},
|
||||
resolver: zodResolver(formSchema),
|
||||
});
|
||||
|
||||
const handleSelectAction = (newValue: ISelectActionOption | null) => {
|
||||
if (newValue) {
|
||||
form.setValue("action", newValue.value);
|
||||
if (newValue.value === WorkflowActions.SMS_NUMBER) {
|
||||
setIsPhoneNumberNeeded(true);
|
||||
setIsSenderIdNeeded(true);
|
||||
setIsEmailAddressNeeded(false);
|
||||
form.resetField("senderId", { defaultValue: SENDER_ID });
|
||||
} else if (newValue.value === WorkflowActions.EMAIL_ADDRESS) {
|
||||
setIsEmailAddressNeeded(true);
|
||||
setIsSenderIdNeeded(false);
|
||||
setIsPhoneNumberNeeded(false);
|
||||
} else if (newValue.value === WorkflowActions.SMS_ATTENDEE) {
|
||||
setIsSenderIdNeeded(true);
|
||||
setIsEmailAddressNeeded(false);
|
||||
setIsPhoneNumberNeeded(false);
|
||||
form.resetField("senderId", { defaultValue: SENDER_ID });
|
||||
} else if (newValue.value === WorkflowActions.WHATSAPP_NUMBER) {
|
||||
setIsSenderIdNeeded(false);
|
||||
setIsPhoneNumberNeeded(true);
|
||||
setIsEmailAddressNeeded(false);
|
||||
} else {
|
||||
setIsSenderIdNeeded(false);
|
||||
setIsEmailAddressNeeded(false);
|
||||
setIsPhoneNumberNeeded(false);
|
||||
}
|
||||
form.unregister("sendTo");
|
||||
form.unregister("numberRequired");
|
||||
form.clearErrors("action");
|
||||
form.clearErrors("sendTo");
|
||||
}
|
||||
};
|
||||
|
||||
if (!actionOptions) return null;
|
||||
|
||||
const canRequirePhoneNumber = (workflowStep: string) => {
|
||||
return (
|
||||
WorkflowActions.SMS_ATTENDEE === workflowStep || WorkflowActions.WHATSAPP_ATTENDEE === workflowStep
|
||||
);
|
||||
};
|
||||
|
||||
const showSender = (action: string) => {
|
||||
return (
|
||||
!isSenderIdNeeded &&
|
||||
!(WorkflowActions.WHATSAPP_NUMBER === action || WorkflowActions.WHATSAPP_ATTENDEE === action)
|
||||
);
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open={isOpenDialog} onOpenChange={setIsOpenDialog}>
|
||||
<DialogContent type="creation" title={t("add_action")}>
|
||||
<div className="-mt-3 space-x-3">
|
||||
<Form
|
||||
form={form}
|
||||
handleSubmit={(values) => {
|
||||
addAction(
|
||||
values.action,
|
||||
values.sendTo,
|
||||
values.numberRequired,
|
||||
values.senderId,
|
||||
values.senderName
|
||||
);
|
||||
form.unregister("sendTo");
|
||||
form.unregister("action");
|
||||
form.unregister("numberRequired");
|
||||
setIsOpenDialog(false);
|
||||
setIsPhoneNumberNeeded(false);
|
||||
setIsEmailAddressNeeded(false);
|
||||
setIsSenderIdNeeded(false);
|
||||
}}>
|
||||
<div className="stack-y-1">
|
||||
<Label htmlFor="label">{t("action")}:</Label>
|
||||
<Controller
|
||||
name="action"
|
||||
control={form.control}
|
||||
render={() => {
|
||||
return (
|
||||
<Select
|
||||
isSearchable={false}
|
||||
className="text-sm"
|
||||
menuPlacement="bottom"
|
||||
defaultValue={actionOptions[0]}
|
||||
onChange={handleSelectAction}
|
||||
options={actionOptions.map((option) => ({
|
||||
label: option.label,
|
||||
value: option.value,
|
||||
needsTeamsUpgrade: option.needsTeamsUpgrade,
|
||||
}))}
|
||||
isOptionDisabled={(option: {
|
||||
label: string;
|
||||
value: WorkflowActions;
|
||||
needsTeamsUpgrade?: boolean;
|
||||
}) => !!option.needsTeamsUpgrade}
|
||||
/>
|
||||
);
|
||||
}}
|
||||
/>
|
||||
{form.formState.errors.action && (
|
||||
<p className="mt-1 text-sm text-red-500">{form.formState.errors.action.message}</p>
|
||||
)}
|
||||
</div>
|
||||
{isPhoneNumberNeeded && (
|
||||
<div className="mt-5 stack-y-1">
|
||||
<Label htmlFor="sendTo">{t("phone_number")}</Label>
|
||||
<div className="mb-5 mt-1">
|
||||
<Controller
|
||||
control={form.control}
|
||||
name="sendTo"
|
||||
render={({ field: { value, onChange } }) => (
|
||||
<PhoneInput
|
||||
className="rounded-md"
|
||||
placeholder={t("enter_phone_number")}
|
||||
id="sendTo"
|
||||
required
|
||||
value={value}
|
||||
onChange={onChange}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
{form.formState.errors.sendTo && (
|
||||
<p className="mt-1 text-sm text-red-500">{form.formState.errors.sendTo.message}</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{isEmailAddressNeeded && (
|
||||
<div className="mt-5">
|
||||
<EmailField required label={t("email_address")} {...form.register("sendTo")} />
|
||||
</div>
|
||||
)}
|
||||
{isSenderIdNeeded && (
|
||||
<>
|
||||
<div className="mt-5">
|
||||
<div className="flex items-center">
|
||||
<Label>{t("sender_id")}</Label>
|
||||
<Tooltip content={t("sender_id_info")}>
|
||||
<span>
|
||||
<Icon name="info" className="mb-2 ml-2 mr-1 mt-0.5 h-4 w-4 text-gray-500" />
|
||||
</span>
|
||||
</Tooltip>
|
||||
</div>
|
||||
<Input type="text" placeholder={SENDER_ID} maxLength={11} {...form.register(`senderId`)} />
|
||||
</div>
|
||||
{form.formState.errors && form.formState?.errors?.senderId && (
|
||||
<p className="mt-1 text-xs text-red-500">{t("sender_id_error_message")}</p>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
{showSender(form.getValues("action")) && (
|
||||
<div className="mt-5">
|
||||
<Label>{t("sender_name")}</Label>
|
||||
<Input type="text" placeholder={SENDER_NAME} {...form.register(`senderName`)} />
|
||||
</div>
|
||||
)}
|
||||
{canRequirePhoneNumber(form.getValues("action")) && (
|
||||
<div className="mt-5">
|
||||
<Controller
|
||||
name="numberRequired"
|
||||
control={form.control}
|
||||
render={() => (
|
||||
<CheckboxField
|
||||
defaultChecked={form.getValues("numberRequired") || false}
|
||||
description={t("make_phone_number_required")}
|
||||
onChange={(e) => form.setValue("numberRequired", e.target.checked)}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
<DialogFooter showDivider noSticky className="mt-12">
|
||||
<DialogClose
|
||||
onClick={() => {
|
||||
setIsOpenDialog(false);
|
||||
form.unregister("sendTo");
|
||||
form.unregister("action");
|
||||
form.unregister("numberRequired");
|
||||
setIsPhoneNumberNeeded(false);
|
||||
setIsEmailAddressNeeded(false);
|
||||
setIsSenderIdNeeded(false);
|
||||
}}
|
||||
/>
|
||||
<Button type="submit">{t("add")}</Button>
|
||||
</DialogFooter>
|
||||
</Form>
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
};
|
||||
@@ -1,182 +0,0 @@
|
||||
import type { Dispatch } from "react";
|
||||
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { Badge } from "@calcom/ui/components/badge";
|
||||
import { Button } from "@calcom/ui/components/button";
|
||||
import { Icon } from "@calcom/ui/components/icon";
|
||||
import {
|
||||
Sheet,
|
||||
SheetContent,
|
||||
SheetBody,
|
||||
SheetHeader,
|
||||
SheetFooter,
|
||||
SheetClose,
|
||||
} from "@calcom/ui/components/sheet";
|
||||
|
||||
import type { CallDetailsAction, CallDetailsState } from "./types";
|
||||
|
||||
interface CallDetailsSheetProps {
|
||||
state: CallDetailsState;
|
||||
dispatch: Dispatch<CallDetailsAction>;
|
||||
}
|
||||
|
||||
export function CallDetailsSheet({ state, dispatch }: CallDetailsSheetProps) {
|
||||
const { t } = useLocale();
|
||||
const { selectedCall } = state.callDetailsSheet;
|
||||
|
||||
if (!selectedCall) return null;
|
||||
|
||||
const formatDuration = (durationMs: number) => {
|
||||
const totalSeconds = Math.round(durationMs / 1000);
|
||||
const minutes = Math.floor(totalSeconds / 60);
|
||||
const seconds = totalSeconds % 60;
|
||||
return `${minutes}:${seconds.toString().padStart(2, "0")}`;
|
||||
};
|
||||
|
||||
const formatTimestamp = (timestamp: number) => {
|
||||
const date = new Date(timestamp);
|
||||
return date.toLocaleString();
|
||||
};
|
||||
|
||||
return (
|
||||
<Sheet
|
||||
open={true}
|
||||
onOpenChange={() => {
|
||||
dispatch({ type: "CLOSE_MODAL" });
|
||||
}}>
|
||||
<SheetContent className="bg-default max-w-2xl overflow-y-auto">
|
||||
<SheetHeader showCloseButton={true}>
|
||||
<div className="mb-4 flex items-center justify-between">
|
||||
<div>
|
||||
<h2 className="text-emphasis font-sans text-xl font-semibold">{t("call_details")}</h2>
|
||||
<p className="text-subtle mt-1 text-sm">
|
||||
{t("call_id")}: {selectedCall.call_id}{" "}
|
||||
<Badge variant={selectedCall.call_status === "ended" ? "green" : "orange"}>
|
||||
{selectedCall.call_status}
|
||||
</Badge>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</SheetHeader>
|
||||
|
||||
<SheetBody className="flex flex-col stack-y-6 p-4">
|
||||
{/* Call Information */}
|
||||
<div className="stack-y-3">
|
||||
<h3 className="text-emphasis text-base font-semibold">{t("call_information")}</h3>
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div>
|
||||
<p className="text-subtle text-sm">{t("start_time")}</p>
|
||||
<p className="text-default text-sm font-medium">
|
||||
{selectedCall.start_timestamp ? formatTimestamp(selectedCall.start_timestamp) : t("unknown")}
|
||||
</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-subtle text-sm">{t("duration")}</p>
|
||||
<p className="text-default text-sm font-medium">{selectedCall.duration_ms ? formatDuration(selectedCall.duration_ms) : t("unknown")}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-subtle text-sm">{t("from")}</p>
|
||||
<p className="text-default text-sm font-medium">{"from_number" in selectedCall ? selectedCall.from_number || t("unknown") : t("unknown")}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-subtle text-sm">{t("to")}</p>
|
||||
<p className="text-default text-sm font-medium">{"to_number" in selectedCall ? selectedCall.to_number || t("unknown") : t("unknown")}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-subtle text-sm">{t("sentiment")}</p>
|
||||
<Badge
|
||||
variant={
|
||||
selectedCall.call_analysis?.user_sentiment === "Positive"
|
||||
? "green"
|
||||
: selectedCall.call_analysis?.user_sentiment === "Negative"
|
||||
? "red"
|
||||
: "gray"
|
||||
}>
|
||||
{selectedCall.call_analysis?.user_sentiment || "Unknown"}
|
||||
</Badge>
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-subtle text-sm">{t("disconnect_reason")}</p>
|
||||
<p className="text-default text-sm font-medium">
|
||||
{selectedCall.disconnection_reason?.replace(/_/g, " ")}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Call Summary */}
|
||||
{selectedCall.call_analysis?.call_summary && (
|
||||
<div className="stack-y-3">
|
||||
<h3 className="text-emphasis text-base font-semibold">{t("call_summary")}</h3>
|
||||
<p className="text-default text-sm">{selectedCall.call_analysis.call_summary}</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Recording Section */}
|
||||
<div className="stack-y-3">
|
||||
<h3 className="text-emphasis text-base font-semibold">{t("recording")}</h3>
|
||||
<div className="flex items-center gap-3">
|
||||
<audio controls className="h-11 w-[258px]" src={selectedCall.recording_url}>
|
||||
Your browser does not support the audio element.
|
||||
</audio>
|
||||
<Button color="minimal" href={selectedCall.recording_url} target="_blank" StartIcon="download">
|
||||
{t("download")}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Transcription */}
|
||||
<div className="stack-y-3">
|
||||
<h3 className="text-emphasis text-base font-semibold">{t("transcription")}</h3>
|
||||
<div className="border-subtle max-h-96 stack-y-3 overflow-y-auto rounded-md border p-4">
|
||||
{selectedCall.transcript ? (
|
||||
selectedCall.transcript
|
||||
.split("\n")
|
||||
.filter((line) => line.trim())
|
||||
.map((line, index) => {
|
||||
const isAgent = line.startsWith("Agent:");
|
||||
const isUser = line.startsWith("User:");
|
||||
const content = line.replace(/^(Agent:|User:)\s*/, "");
|
||||
|
||||
if (!isAgent && !isUser) return null;
|
||||
|
||||
return (
|
||||
<div key={index} className="stack-y-1">
|
||||
<div className="flex items-center gap-2">
|
||||
<Icon name="user" className={isAgent ? "text-info" : "text-success"} />
|
||||
<span className={`text-sm font-medium ${isAgent ? "text-info" : "text-success"}`}>
|
||||
{isAgent ? t("agent") : t("user")}
|
||||
</span>
|
||||
</div>
|
||||
<p className="text-default ml-7 text-sm">{content}</p>
|
||||
</div>
|
||||
);
|
||||
})
|
||||
) : (
|
||||
<p className="text-subtle text-sm">{t("no_transcript_available")}</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Event Details */}
|
||||
{selectedCall.retell_llm_dynamic_variables && (
|
||||
<div className="stack-y-3">
|
||||
<h3 className="text-emphasis text-base font-semibold">{t("event_details")}</h3>
|
||||
<div className="border-subtle bg-cal-muted rounded-md border p-4">
|
||||
<pre className="text-default overflow-x-auto text-xs">
|
||||
{JSON.stringify(selectedCall.retell_llm_dynamic_variables, null, 2)}
|
||||
</pre>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</SheetBody>
|
||||
|
||||
<SheetFooter>
|
||||
<SheetClose asChild>
|
||||
<Button color="secondary">{t("close")}</Button>
|
||||
</SheetClose>
|
||||
</SheetFooter>
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
);
|
||||
}
|
||||
@@ -1,58 +0,0 @@
|
||||
import type { Dispatch, SetStateAction } from "react";
|
||||
|
||||
import { Dialog } from "@calcom/features/components/controlled-dialog";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { HttpError } from "@calcom/lib/http-error";
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
import { ConfirmationDialogContent } from "@calcom/ui/components/dialog";
|
||||
import { showToast } from "@calcom/ui/components/toast";
|
||||
|
||||
interface IDeleteDialog {
|
||||
isOpenDialog: boolean;
|
||||
setIsOpenDialog: Dispatch<SetStateAction<boolean>>;
|
||||
workflowId: number;
|
||||
additionalFunction: () => Promise<boolean | void>;
|
||||
}
|
||||
|
||||
export const DeleteDialog = (props: IDeleteDialog) => {
|
||||
const { t } = useLocale();
|
||||
const { isOpenDialog, setIsOpenDialog, workflowId, additionalFunction } = props;
|
||||
const utils = trpc.useUtils();
|
||||
|
||||
const deleteMutation = trpc.viewer.workflows.delete.useMutation({
|
||||
onSuccess: async () => {
|
||||
await utils.viewer.workflows.filteredList.invalidate();
|
||||
additionalFunction();
|
||||
showToast(t("workflow_deleted_successfully"), "success");
|
||||
setIsOpenDialog(false);
|
||||
},
|
||||
onError: (err) => {
|
||||
if (err instanceof HttpError) {
|
||||
const message = `${err.statusCode}: ${err.message}`;
|
||||
showToast(message, "error");
|
||||
setIsOpenDialog(false);
|
||||
}
|
||||
if (err.data?.code === "UNAUTHORIZED") {
|
||||
const message = `${err.data.code}: You are not authorized to delete this workflow`;
|
||||
showToast(message, "error");
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
return (
|
||||
<Dialog open={isOpenDialog} onOpenChange={setIsOpenDialog}>
|
||||
<ConfirmationDialogContent
|
||||
isPending={deleteMutation.isPending}
|
||||
variety="danger"
|
||||
title={t("delete_workflow")}
|
||||
confirmBtnText={t("confirm_delete_workflow")}
|
||||
loadingText={t("confirm_delete_workflow")}
|
||||
onConfirm={(e) => {
|
||||
e.preventDefault();
|
||||
deleteMutation.mutate({ id: workflowId });
|
||||
}}>
|
||||
{t("delete_workflow_description")}
|
||||
</ConfirmationDialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
};
|
||||
@@ -1,166 +0,0 @@
|
||||
import { CreateButtonWithTeamsList } from "@calcom/features/ee/teams/components/createButton/CreateButtonWithTeamsList";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import cn from "@calcom/ui/classNames";
|
||||
import { EmptyScreen as ClassicEmptyScreen } from "@calcom/ui/components/empty-screen";
|
||||
import { Icon } from "@calcom/ui/components/icon";
|
||||
import type { IconName } from "@calcom/ui/components/icon";
|
||||
|
||||
import { WorkflowCreationDialog, useWorkflowCreation } from "./WorkflowCreationDialog";
|
||||
|
||||
type WorkflowExampleType = {
|
||||
icon: IconName;
|
||||
iconWrapperClassName?: string;
|
||||
title: string;
|
||||
description: string;
|
||||
image?: string;
|
||||
};
|
||||
|
||||
function WorkflowExample(props: WorkflowExampleType) {
|
||||
const { icon: iconName, title, description, iconWrapperClassName, image } = props;
|
||||
|
||||
return (
|
||||
<div className="bg-default border-subtle max-h-24 max-w-[600px] rounded-xl border border-solid p-2.5">
|
||||
<div className="flex">
|
||||
<div className="flex items-center justify-center">
|
||||
<div
|
||||
className={cn(
|
||||
"bg-emphasis dark:bg-default mr-4 flex h-10 w-10 items-center justify-center rounded-[10px]",
|
||||
iconWrapperClassName
|
||||
)}>
|
||||
{image ? (
|
||||
<img
|
||||
src={image}
|
||||
alt=""
|
||||
role="presentation"
|
||||
aria-hidden="true"
|
||||
className={cn("text-default h-5 w-5")}
|
||||
/>
|
||||
) : (
|
||||
<Icon name={iconName} className={cn("text-default h-5 w-5")} aria-hidden="true" />
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="m-auto w-full grow items-center justify-center ">
|
||||
<div className="text-semibold text-emphasis line-clamp-2 w-full text-sm font-semibold">{title}</div>
|
||||
<div className="text-default text-sm font-normal leading-none">{description}</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default function EmptyScreen(props: { isFilteredView: boolean }) {
|
||||
const { t } = useLocale();
|
||||
const { showDialog, setShowDialog, pendingTeamId, openDialog } = useWorkflowCreation();
|
||||
|
||||
const workflowsExamples: WorkflowExampleType[] = [
|
||||
{ icon: "smartphone", title: t("send_sms_reminder"), description: t("send_sms_reminder_description") },
|
||||
{
|
||||
icon: "smartphone",
|
||||
title: t("follow_up_with_no_shows"),
|
||||
description: t("follow_up_with_no_shows_description"),
|
||||
},
|
||||
{
|
||||
icon: "mail",
|
||||
title: t("remind_attendees_to_bring_id"),
|
||||
description: t("remind_attendees_to_bring_id_description"),
|
||||
},
|
||||
{
|
||||
icon: "mail",
|
||||
title: t("email_to_remind_booking"),
|
||||
description: t("email_to_remind_booking_description"),
|
||||
},
|
||||
{
|
||||
icon: "mail",
|
||||
title: t("custom_email_reminder"),
|
||||
description: t("custom_email_reminder_description"),
|
||||
},
|
||||
{
|
||||
icon: "smartphone",
|
||||
title: t("custom_sms_reminder"),
|
||||
description: t("custom_sms_reminder_description"),
|
||||
},
|
||||
];
|
||||
|
||||
const calAITemplates: WorkflowExampleType[] = [
|
||||
{
|
||||
icon: "phone-outgoing",
|
||||
title: t("call_to_confirm_booking"),
|
||||
description: t("cal_ai_phone_call_action_description"),
|
||||
iconWrapperClassName: "bg-[#2A2947]",
|
||||
image: "/call-outgoing.svg",
|
||||
},
|
||||
{
|
||||
icon: "phone-outgoing",
|
||||
title: t("follow_up_with_no_shows"),
|
||||
description: t("follow_up_with_no_shows_description"),
|
||||
iconWrapperClassName: "bg-[#2A2947]",
|
||||
image: "/call-outgoing.svg",
|
||||
},
|
||||
{
|
||||
icon: "phone-outgoing",
|
||||
title: t("remind_attendees_to_bring_id"),
|
||||
description: t("remind_attendees_to_bring_id_description"),
|
||||
iconWrapperClassName: "bg-[#2A2947]",
|
||||
image: "/call-outgoing.svg",
|
||||
},
|
||||
];
|
||||
// new workflow example when 'after meetings ends' trigger is implemented: Send custom thank you email to attendee after event (Smile icon),
|
||||
|
||||
if (props.isFilteredView) {
|
||||
return <ClassicEmptyScreen Icon="zap" headline={t("no_workflows")} description={t("change_filter")} />;
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="min-h-80 flex w-full flex-col items-center justify-center rounded-md ">
|
||||
<div className="bg-emphasis flex h-[72px] w-[72px] items-center justify-center rounded-full">
|
||||
<Icon name="zap" className="dark:text-default inline-block h-10 w-10 stroke-[1.3px]" />
|
||||
</div>
|
||||
<div className="max-w-[420px] text-center">
|
||||
<h2 className="text-semibold font-cal mt-6 text-xl dark:text-gray-300">{t("workflows")}</h2>
|
||||
<p className="text-default mt-3 line-clamp-2 text-sm font-normal leading-6 dark:text-gray-300">
|
||||
{t("no_workflows_description")}
|
||||
</p>
|
||||
<div className="mt-8 ">
|
||||
<CreateButtonWithTeamsList
|
||||
subtitle={t("new_workflow_subtitle").toUpperCase()}
|
||||
createFunction={openDialog}
|
||||
buttonText={t("create_workflow")}
|
||||
includeOrg={true}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col gap-4">
|
||||
<TemplateSection title={t("cal_ai_templates")} examples={calAITemplates} />
|
||||
<TemplateSection title={t("standard_templates")} examples={workflowsExamples} />
|
||||
</div>
|
||||
|
||||
<WorkflowCreationDialog open={showDialog} onOpenChange={setShowDialog} teamId={pendingTeamId} />
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
const TemplateSection = ({ title, examples }: { title: string; examples: WorkflowExampleType[] }) => {
|
||||
return (
|
||||
<div className="flex items-center justify-center">
|
||||
<div className="bg-cal-muted flex max-w-5xl flex-col rounded-md p-2">
|
||||
<h2 className="text-emphasis mb-2 text-base font-semibold">{title}</h2>
|
||||
<div className="grid grid-cols-1 items-center gap-2 lg:grid-cols-3">
|
||||
{examples.map((example: WorkflowExampleType, index: number) => (
|
||||
<WorkflowExample
|
||||
key={index}
|
||||
icon={example.icon}
|
||||
title={example.title}
|
||||
description={example.description}
|
||||
iconWrapperClassName={example.iconWrapperClassName}
|
||||
image={example.image}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -1,12 +0,0 @@
|
||||
import { SkeletonText, SkeletonContainer } from "@calcom/ui/components/skeleton";
|
||||
|
||||
function SkeletonLoader() {
|
||||
return (
|
||||
<SkeletonContainer>
|
||||
<SkeletonText className="mx-auto my-8 h-48 w-full max-w-4xl" />
|
||||
<SkeletonText className="mx-auto my-8 h-80 w-full max-w-4xl" />
|
||||
</SkeletonContainer>
|
||||
);
|
||||
}
|
||||
|
||||
export default SkeletonLoader;
|
||||
@@ -1,37 +0,0 @@
|
||||
import { SkeletonText, SkeletonAvatar } from "@calcom/ui/components/skeleton";
|
||||
|
||||
function SkeletonLoader() {
|
||||
return (
|
||||
<ul className="bg-default divide-subtle animate-pulse sm:overflow-hidden">
|
||||
<SkeletonItem />
|
||||
<SkeletonItem />
|
||||
</ul>
|
||||
);
|
||||
}
|
||||
|
||||
export default SkeletonLoader;
|
||||
|
||||
function SkeletonItem() {
|
||||
return (
|
||||
<li className="border-subtle group mb-4 flex h-[90px] w-full items-center justify-between rounded-md border px-4 py-4 sm:px-6">
|
||||
<div className="grow truncate text-sm">
|
||||
<div className="flex">
|
||||
<SkeletonAvatar className="h-10 w-10" />
|
||||
|
||||
<div className="ml-4 mt-1 flex flex-col stack-y-1">
|
||||
<SkeletonText className="h-5 w-20 sm:w-24" />
|
||||
<div className="flex">
|
||||
<SkeletonText className="h-4 w-16 ltr:mr-2 rtl:ml-2 sm:w-28" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="mt-0 flex shrink-0 sm:ml-5">
|
||||
<div className="flex justify-between space-x-2 rtl:space-x-reverse">
|
||||
<SkeletonText className="h-8 w-8 sm:w-16" />
|
||||
<SkeletonText className="h-8 w-8 sm:w-16" />
|
||||
</div>
|
||||
</div>
|
||||
</li>
|
||||
);
|
||||
}
|
||||
@@ -1,39 +0,0 @@
|
||||
import { Icon } from "@calcom/ui/components/icon";
|
||||
import { SkeletonText } from "@calcom/ui/components/skeleton";
|
||||
|
||||
function SkeletonLoader() {
|
||||
return (
|
||||
<ul className="divide-subtle border-subtle bg-default animate-pulse divide-y rounded-md border sm:overflow-hidden">
|
||||
<SkeletonItem />
|
||||
<SkeletonItem />
|
||||
<SkeletonItem />
|
||||
</ul>
|
||||
);
|
||||
}
|
||||
|
||||
export default SkeletonLoader;
|
||||
|
||||
function SkeletonItem() {
|
||||
return (
|
||||
<li className="group flex w-full items-center justify-between px-4 py-4 sm:px-6">
|
||||
<div className="grow truncate text-sm">
|
||||
<div className="flex">
|
||||
<div className="flex flex-col stack-y-2">
|
||||
<SkeletonText className="h-4 w-16 sm:w-24" />
|
||||
<div className="flex">
|
||||
<Icon name="bell" className="mr-1.5 mt-0.5 inline h-4 w-4 text-gray-200" />
|
||||
<SkeletonText className="h-4 w-16 ltr:mr-2 rtl:ml-2 sm:w-28" />
|
||||
<Icon name="link" className="mr-1.5 mt-0.5 inline h-4 w-4 text-gray-200" />
|
||||
<SkeletonText className="h-4 w-28 sm:w-36" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="mt-0 flex shrink-0 sm:ml-5">
|
||||
<div className="flex justify-between space-x-2 rtl:space-x-reverse">
|
||||
<SkeletonText className="h-8 w-8 sm:w-16" />
|
||||
</div>
|
||||
</div>
|
||||
</li>
|
||||
);
|
||||
}
|
||||
@@ -1,110 +0,0 @@
|
||||
import { useState } from "react";
|
||||
import type { UseFormReturn } from "react-hook-form";
|
||||
|
||||
import { Dialog } from "@calcom/features/components/controlled-dialog";
|
||||
import PhoneInput from "@calcom/features/components/phone-input";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
import { Button } from "@calcom/ui/components/button";
|
||||
import { DialogContent, DialogFooter } from "@calcom/ui/components/dialog";
|
||||
import { Label } from "@calcom/ui/components/form";
|
||||
import { Icon } from "@calcom/ui/components/icon";
|
||||
import { showToast } from "@calcom/ui/components/toast";
|
||||
|
||||
import { getEventTypeIdForCalAiTest } from "../lib/actionHelperFunctions";
|
||||
import type { FormValues } from "../pages/workflow";
|
||||
|
||||
interface TestPhoneCallDialogProps {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
agentId: string;
|
||||
teamId?: number;
|
||||
form: UseFormReturn<FormValues>;
|
||||
eventTypeIds?: number[];
|
||||
outboundEventTypeId?: number | null;
|
||||
}
|
||||
|
||||
export function TestPhoneCallDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
agentId,
|
||||
teamId,
|
||||
form,
|
||||
eventTypeIds = [],
|
||||
outboundEventTypeId,
|
||||
}: TestPhoneCallDialogProps) {
|
||||
const { t } = useLocale();
|
||||
const [testPhoneNumber, setTestPhoneNumber] = useState("");
|
||||
|
||||
const testCallMutation = trpc.viewer.aiVoiceAgent.testCall.useMutation({
|
||||
onSuccess: async (data) => {
|
||||
showToast(data?.message ?? t("call_initiated_successfully"), "success");
|
||||
onOpenChange(false);
|
||||
setTestPhoneNumber("");
|
||||
},
|
||||
onError: (error: { message: string }) => {
|
||||
showToast(t(error.message), "error");
|
||||
},
|
||||
});
|
||||
|
||||
const handleTestCall = () => {
|
||||
if (!testPhoneNumber) {
|
||||
showToast(t("please_enter_phone_number"), "error");
|
||||
return;
|
||||
}
|
||||
|
||||
const eventTypeValidation = getEventTypeIdForCalAiTest({
|
||||
trigger: form.getValues("trigger"),
|
||||
outboundEventTypeId,
|
||||
eventTypeIds,
|
||||
activeOnEventTypeId: form.getValues("activeOn")?.[0]?.value,
|
||||
t,
|
||||
});
|
||||
|
||||
if (eventTypeValidation.error || !eventTypeValidation.eventTypeId) {
|
||||
showToast(eventTypeValidation.error || t("no_event_type_selected"), "error");
|
||||
return;
|
||||
}
|
||||
|
||||
if (agentId) {
|
||||
testCallMutation.mutate({
|
||||
agentId: agentId,
|
||||
phoneNumber: testPhoneNumber,
|
||||
teamId: teamId,
|
||||
eventTypeId: eventTypeValidation.eventTypeId,
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent
|
||||
type="creation"
|
||||
title={t("test_cal_ai_agent")}
|
||||
description={t("make_test_call_to_verify_configuration")}>
|
||||
<div>
|
||||
<Label className="mb-1 block text-sm font-medium">{t("call_to")}:</Label>
|
||||
<PhoneInput
|
||||
placeholder={t("enter_phone_number_to_test_call")}
|
||||
value={testPhoneNumber}
|
||||
onChange={(val) => setTestPhoneNumber(val || "")}
|
||||
disabled={testCallMutation.isPending}
|
||||
/>
|
||||
</div>
|
||||
<DialogFooter showDivider>
|
||||
<Button type="button" color="secondary" onClick={() => onOpenChange(false)}>
|
||||
{t("cancel")}
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
onClick={handleTestCall}
|
||||
loading={testCallMutation.isPending}
|
||||
disabled={!testPhoneNumber}>
|
||||
<Icon name="phone" className="mr-2 h-4 w-4" />
|
||||
{t("make_test_call")}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -1,94 +0,0 @@
|
||||
import { useState } from "react";
|
||||
import { useFormContext } from "react-hook-form";
|
||||
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { TimeUnit } from "@calcom/prisma/enums";
|
||||
import { Icon } from "@calcom/ui/components/icon";
|
||||
import { TextField } from "@calcom/ui/components/form";
|
||||
import {
|
||||
Dropdown,
|
||||
DropdownItem,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
} from "@calcom/ui/components/dropdown";
|
||||
|
||||
const TIME_UNITS = [TimeUnit.DAY, TimeUnit.HOUR, TimeUnit.MINUTE] as const;
|
||||
|
||||
type Props = {
|
||||
disabled: boolean;
|
||||
defaultTime?: number;
|
||||
};
|
||||
|
||||
const TimeUnitAddonSuffix = ({
|
||||
DropdownItems,
|
||||
timeUnitOptions,
|
||||
}: {
|
||||
DropdownItems: JSX.Element;
|
||||
timeUnitOptions: { [x: string]: string };
|
||||
}) => {
|
||||
// because isDropdownOpen already triggers a render cycle we can use getValues()
|
||||
// instead of watch() function
|
||||
const form = useFormContext();
|
||||
const timeUnit = form.getValues("timeUnit") ?? TimeUnit.MINUTE;
|
||||
const [isDropdownOpen, setIsDropdownOpen] = useState(false);
|
||||
return (
|
||||
<Dropdown onOpenChange={setIsDropdownOpen}>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<button className="flex items-center">
|
||||
<div className="mr-1 w-3/5">{timeUnit ? timeUnitOptions[timeUnit] : "undefined"}</div>
|
||||
<div className="w-1/4 pt-1">
|
||||
{isDropdownOpen ? <Icon name="chevron-up" /> : <Icon name="chevron-down" />}
|
||||
</div>
|
||||
</button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent>{DropdownItems}</DropdownMenuContent>
|
||||
</Dropdown>
|
||||
);
|
||||
};
|
||||
|
||||
export const TimeTimeUnitInput = (props: Props) => {
|
||||
const form = useFormContext();
|
||||
|
||||
const { t } = useLocale();
|
||||
const timeUnitOptions = TIME_UNITS.reduce((acc, option) => {
|
||||
acc[option] = t(`${option.toLowerCase()}_timeUnit`);
|
||||
return acc;
|
||||
}, {} as { [x: string]: string });
|
||||
return (
|
||||
<div className="flex">
|
||||
<div className="grow">
|
||||
<TextField
|
||||
type="number"
|
||||
min="1"
|
||||
label=""
|
||||
disabled={props.disabled}
|
||||
defaultValue={form.getValues("time") ?? props.defaultTime ?? 24}
|
||||
className="rounded-r-none text-sm focus:ring-0"
|
||||
{...form.register("time", { valueAsNumber: true })}
|
||||
addOnSuffix={
|
||||
<TimeUnitAddonSuffix
|
||||
timeUnitOptions={timeUnitOptions}
|
||||
DropdownItems={
|
||||
<>
|
||||
{TIME_UNITS.map((timeUnit, index) => (
|
||||
<DropdownMenuItem key={index} className="outline-none">
|
||||
<DropdownItem
|
||||
key={index}
|
||||
type="button"
|
||||
onClick={() => {
|
||||
form.setValue("timeUnit", timeUnit, { shouldDirty: true });
|
||||
}}>
|
||||
{timeUnitOptions[timeUnit]}
|
||||
</DropdownItem>
|
||||
</DropdownMenuItem>
|
||||
))}
|
||||
</>
|
||||
}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -1,209 +0,0 @@
|
||||
import { getCoreRowModel, getSortedRowModel, useReactTable, type ColumnDef } from "@tanstack/react-table";
|
||||
import { usePathname } from "next/navigation";
|
||||
import { useMemo, useState } from "react";
|
||||
|
||||
import { DataTableProvider, DataTableWrapper } from "@calcom/features/data-table";
|
||||
import { useSegments } from "@calcom/features/data-table/hooks/useSegments";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
import { Button } from "@calcom/ui/components/button";
|
||||
import { Dialog, DialogContent, DialogHeader } from "@calcom/ui/components/dialog";
|
||||
import { Icon } from "@calcom/ui/components/icon";
|
||||
import { showToast } from "@calcom/ui/components/toast";
|
||||
|
||||
import { useVoicePreview } from "../hooks/useVoicePreview";
|
||||
|
||||
type Voice = {
|
||||
voice_id: string;
|
||||
voice_name: string;
|
||||
provider: "elevenlabs" | "openai" | "deepgram";
|
||||
gender: "male" | "female";
|
||||
accent?: string;
|
||||
age?: string;
|
||||
preview_audio_url?: string;
|
||||
};
|
||||
|
||||
type VoiceSelectionDialogProps = {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
selectedVoiceId?: string;
|
||||
onVoiceSelect: (voiceId: string) => void;
|
||||
};
|
||||
|
||||
function VoiceSelectionTable({
|
||||
selectedVoiceId,
|
||||
onVoiceSelect,
|
||||
}: {
|
||||
selectedVoiceId?: string;
|
||||
onVoiceSelect: (voiceId: string) => void;
|
||||
}) {
|
||||
const pathname = usePathname();
|
||||
if (!pathname) return null;
|
||||
return (
|
||||
<DataTableProvider tableIdentifier={pathname} useSegments={useSegments} defaultPageSize={1000}>
|
||||
<VoiceSelectionContent selectedVoiceId={selectedVoiceId} onVoiceSelect={onVoiceSelect} />
|
||||
</DataTableProvider>
|
||||
);
|
||||
}
|
||||
|
||||
function VoiceSelectionContent({
|
||||
selectedVoiceId,
|
||||
onVoiceSelect,
|
||||
}: {
|
||||
selectedVoiceId?: string;
|
||||
onVoiceSelect: (voiceId: string) => void;
|
||||
}) {
|
||||
const { t } = useLocale();
|
||||
const { playingVoiceId, handlePlayVoice } = useVoicePreview();
|
||||
const [rowSelection, setRowSelection] = useState({});
|
||||
|
||||
const { data: voices, isLoading } = trpc.viewer.aiVoiceAgent.listVoices.useQuery();
|
||||
|
||||
const handleUseVoice = (voiceId: string) => {
|
||||
onVoiceSelect(voiceId);
|
||||
showToast("Voice selected successfully", "success");
|
||||
};
|
||||
|
||||
const voiceData: Voice[] = useMemo(() => {
|
||||
if (!voices) return [];
|
||||
return voices;
|
||||
}, [voices]);
|
||||
|
||||
const columns = useMemo<ColumnDef<Voice>[]>(
|
||||
() => [
|
||||
{
|
||||
id: "voice",
|
||||
accessorKey: "voice_name",
|
||||
header: t("voice"),
|
||||
size: 200,
|
||||
cell: ({ row }) => (
|
||||
<div className="flex items-center gap-3">
|
||||
<Button
|
||||
type="button"
|
||||
variant="icon"
|
||||
color="secondary"
|
||||
size="sm"
|
||||
onClick={() => handlePlayVoice(row.original.preview_audio_url, row.original.voice_id)}
|
||||
className="rounded-full">
|
||||
{playingVoiceId === row.original.voice_id ? (
|
||||
<Icon name="pause" className="text-default h-3 w-3" />
|
||||
) : (
|
||||
<Icon name="play" className="text-default h-3 w-3" />
|
||||
)}
|
||||
</Button>
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="bg-subtle flex h-10 w-10 items-center justify-center rounded-full">
|
||||
<Icon name="user" className="text-default h-5 w-5" />
|
||||
</div>
|
||||
<span className="text-emphasis font-medium">{row.original.voice_name}</span>
|
||||
</div>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
id: "trait",
|
||||
accessorKey: "accent",
|
||||
header: t("trait"),
|
||||
size: 200,
|
||||
cell: ({ row }) => (
|
||||
<div className="flex gap-2 text-sm">
|
||||
{row.original.accent && (
|
||||
<span className="bg-subtle text-default rounded-md px-2 py-1 text-xs">
|
||||
{row.original.accent}
|
||||
</span>
|
||||
)}
|
||||
{row.original.gender && (
|
||||
<span className="bg-subtle text-default rounded-md px-2 py-1 text-xs">
|
||||
{row.original.gender}
|
||||
</span>
|
||||
)}
|
||||
{row.original.provider && (
|
||||
<span className="bg-subtle text-default rounded-md px-2 py-1 text-xs">
|
||||
{row.original.provider}
|
||||
</span>
|
||||
)}
|
||||
{row.original.age && (
|
||||
<span className="bg-subtle text-default rounded-md px-2 py-1 text-xs">{row.original.age}</span>
|
||||
)}
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
id: "voice_id",
|
||||
accessorKey: "voice_id",
|
||||
header: t("voice_id"),
|
||||
size: 200,
|
||||
cell: ({ row }) => <span className="text-muted font-mono text-sm">{row.original.voice_id}</span>,
|
||||
},
|
||||
{
|
||||
id: "actions",
|
||||
header: "",
|
||||
size: 120,
|
||||
cell: ({ row }) => (
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
color={selectedVoiceId === row.original.voice_id ? "primary" : "secondary"}
|
||||
onClick={() => handleUseVoice(row.original.voice_id)}
|
||||
className="whitespace-nowrap">
|
||||
{selectedVoiceId === row.original.voice_id ? <>{t("current_voice")}</> : t("use_voice")}
|
||||
</Button>
|
||||
),
|
||||
},
|
||||
],
|
||||
[t, playingVoiceId, selectedVoiceId]
|
||||
);
|
||||
|
||||
const table = useReactTable({
|
||||
data: voiceData,
|
||||
columns,
|
||||
enableRowSelection: false,
|
||||
manualPagination: false,
|
||||
state: {
|
||||
rowSelection,
|
||||
},
|
||||
getCoreRowModel: getCoreRowModel(),
|
||||
getSortedRowModel: getSortedRowModel(),
|
||||
onRowSelectionChange: setRowSelection,
|
||||
getRowId: (row) => row.voice_id,
|
||||
});
|
||||
|
||||
return (
|
||||
<div className="border-subtle max-h-[500px] overflow-auto rounded-lg border">
|
||||
<DataTableWrapper<Voice>
|
||||
testId="voice-selection-data-table"
|
||||
table={table}
|
||||
isPending={isLoading}
|
||||
totalRowCount={voiceData?.length || 0}
|
||||
paginationMode="standard"
|
||||
className="h-auto"
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function VoiceSelectionDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
selectedVoiceId,
|
||||
onVoiceSelect,
|
||||
}: VoiceSelectionDialogProps) {
|
||||
const { t } = useLocale();
|
||||
|
||||
const handleVoiceSelect = (voiceId: string) => {
|
||||
onVoiceSelect(voiceId);
|
||||
onOpenChange(false);
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent enableOverflow className="flex h-[80vh] flex-col p-6 sm:max-w-7xl">
|
||||
<DialogHeader title={t("select_voice")} subtitle={t("choose_a_voice_for_your_agent")} />
|
||||
|
||||
<div className="mt-4 min-h-0 flex-1 overflow-hidden">
|
||||
<VoiceSelectionTable selectedVoiceId={selectedVoiceId} onVoiceSelect={handleVoiceSelect} />
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -1,488 +0,0 @@
|
||||
import Link from "next/link";
|
||||
import { useState, useEffect, useRef, useCallback } from "react";
|
||||
import type { UseFormReturn } from "react-hook-form";
|
||||
import type { RetellWebClient } from "retell-client-js-sdk";
|
||||
|
||||
import { Dialog } from "@calcom/features/components/controlled-dialog";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
import { Alert } from "@calcom/ui/components/alert";
|
||||
import { Button } from "@calcom/ui/components/button";
|
||||
import { DialogContent, DialogFooter } from "@calcom/ui/components/dialog";
|
||||
import { Icon } from "@calcom/ui/components/icon";
|
||||
import { showToast } from "@calcom/ui/components/toast";
|
||||
import { Tooltip } from "@calcom/ui/components/tooltip";
|
||||
|
||||
import { getEventTypeIdForCalAiTest } from "../lib/actionHelperFunctions";
|
||||
import type { FormValues } from "../pages/workflow";
|
||||
|
||||
interface WebCallDialogProps {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
agentId: string;
|
||||
teamId?: number;
|
||||
isOrganization?: boolean;
|
||||
form: UseFormReturn<FormValues>;
|
||||
eventTypeIds?: number[];
|
||||
outboundEventTypeId?: number | null;
|
||||
}
|
||||
|
||||
interface TranscriptEntry {
|
||||
speaker: "agent" | "user";
|
||||
text: string;
|
||||
timestamp: Date;
|
||||
}
|
||||
|
||||
type CallStatus = "idle" | "connecting" | "active" | "ended" | "error";
|
||||
|
||||
export function WebCallDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
agentId,
|
||||
teamId,
|
||||
isOrganization = false,
|
||||
form,
|
||||
eventTypeIds = [],
|
||||
outboundEventTypeId,
|
||||
}: WebCallDialogProps) {
|
||||
const { t } = useLocale();
|
||||
const [callStatus, setCallStatus] = useState<CallStatus>("idle");
|
||||
const [transcript, setTranscript] = useState<TranscriptEntry[]>([]);
|
||||
const [isMuted, setIsMuted] = useState(false);
|
||||
const [callDuration, setCallDuration] = useState(0);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const retellWebClientRef = useRef<RetellWebClient | null>(null);
|
||||
const callStartTimeRef = useRef<Date | null>(null);
|
||||
const durationIntervalRef = useRef<NodeJS.Timeout | null>(null);
|
||||
const transcriptEndRef = useRef<HTMLDivElement>(null);
|
||||
const callStatusRef = useRef<CallStatus>("idle");
|
||||
|
||||
const { data: hasCredits, isLoading: creditsLoading } = trpc.viewer.credits.hasAvailableCredits.useQuery(
|
||||
{ teamId },
|
||||
{ enabled: open }
|
||||
);
|
||||
|
||||
const getBillingPath = () => {
|
||||
if (!teamId) return "/settings/billing";
|
||||
return isOrganization ? "/settings/organizations/billing" : `/settings/teams/${teamId}/billing`;
|
||||
};
|
||||
|
||||
const createWebCallMutation = trpc.viewer.aiVoiceAgent.createWebCall.useMutation({
|
||||
onSuccess: async (data) => {
|
||||
try {
|
||||
await startWebCall(data.accessToken);
|
||||
} catch (error) {
|
||||
console.error("Failed to start web call:", error);
|
||||
setCallStatus("error");
|
||||
setError(t("failed_to_start_web_call_try_again"));
|
||||
}
|
||||
},
|
||||
onError: (error: { message: string }) => {
|
||||
setCallStatus("error");
|
||||
setError(error.message);
|
||||
showToast(error.message, "error");
|
||||
},
|
||||
});
|
||||
|
||||
const startWebCall = async (accessToken: string) => {
|
||||
try {
|
||||
const { RetellWebClient } = await import("retell-client-js-sdk");
|
||||
|
||||
const retellWebClient = new RetellWebClient();
|
||||
retellWebClientRef.current = retellWebClient;
|
||||
|
||||
retellWebClient.on("call_started", () => {
|
||||
callStartTimeRef.current = new Date();
|
||||
callStatusRef.current = "active";
|
||||
setCallStatus("active");
|
||||
startDurationTimer();
|
||||
});
|
||||
|
||||
retellWebClient.on("call_ended", () => {
|
||||
setCallStatus("ended");
|
||||
stopDurationTimer();
|
||||
});
|
||||
|
||||
retellWebClient.on("agent_start_talking", () => {
|
||||
console.log("Agent started talking");
|
||||
});
|
||||
|
||||
retellWebClient.on("agent_stop_talking", () => {
|
||||
console.log("Agent stopped talking");
|
||||
});
|
||||
|
||||
retellWebClient.on("update", (update: { transcript?: Array<{ role: string; content: string }> }) => {
|
||||
console.log("📝 Received update event:", update);
|
||||
|
||||
if (update.transcript && Array.isArray(update.transcript)) {
|
||||
console.log("📜 Transcript array received:", update.transcript);
|
||||
|
||||
try {
|
||||
const newEntries: TranscriptEntry[] = update.transcript
|
||||
.map((entry) => {
|
||||
if (!entry.role || !entry.content) {
|
||||
console.warn("⚠️ Invalid transcript entry:", entry);
|
||||
return null;
|
||||
}
|
||||
const mappedEntry = {
|
||||
speaker: entry.role === "agent" ? "agent" : "user",
|
||||
text: entry.content,
|
||||
timestamp: new Date(),
|
||||
};
|
||||
console.log("✅ Mapped transcript entry:", mappedEntry);
|
||||
return mappedEntry;
|
||||
})
|
||||
.filter(Boolean) as TranscriptEntry[];
|
||||
|
||||
console.log("🔄 Setting transcript with entries:", newEntries.length, "entries");
|
||||
console.log("📋 Current transcript state has:", transcript.length, "entries");
|
||||
|
||||
setTranscript(newEntries);
|
||||
} catch (error) {
|
||||
console.error("❌ Error processing transcript update:", error);
|
||||
}
|
||||
} else {
|
||||
console.log(
|
||||
"🚫 No transcript data in update or transcript is not an array:",
|
||||
typeof update.transcript
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
retellWebClient.on("error", (error: Error | { message?: string }) => {
|
||||
console.error("Web call error:", error);
|
||||
setCallStatus("error");
|
||||
setError(t("call_encountered_error_try_again"));
|
||||
stopDurationTimer();
|
||||
});
|
||||
|
||||
setCallStatus("connecting");
|
||||
await retellWebClient.startCall({
|
||||
accessToken: accessToken,
|
||||
sampleRate: 24000,
|
||||
emitRawAudioSamples: false,
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("Error starting web call:", error);
|
||||
setCallStatus("error");
|
||||
setError(t("failed_initialize_web_call_microphone_permissions"));
|
||||
}
|
||||
};
|
||||
|
||||
const startDurationTimer = useCallback(() => {
|
||||
if (durationIntervalRef.current) {
|
||||
clearInterval(durationIntervalRef.current);
|
||||
durationIntervalRef.current = null;
|
||||
}
|
||||
|
||||
if (!callStartTimeRef.current) {
|
||||
return;
|
||||
}
|
||||
|
||||
durationIntervalRef.current = setInterval(() => {
|
||||
if (callStartTimeRef.current) {
|
||||
const now = Date.now();
|
||||
const startTime = callStartTimeRef.current.getTime();
|
||||
const duration = Math.floor((now - startTime) / 1000);
|
||||
if (duration >= 0) {
|
||||
setCallDuration(duration);
|
||||
}
|
||||
}
|
||||
}, 1000);
|
||||
}, []);
|
||||
|
||||
const stopDurationTimer = () => {
|
||||
if (durationIntervalRef.current) {
|
||||
clearInterval(durationIntervalRef.current);
|
||||
durationIntervalRef.current = null;
|
||||
}
|
||||
};
|
||||
|
||||
const handleStartCall = () => {
|
||||
const eventTypeValidation = getEventTypeIdForCalAiTest({
|
||||
trigger: form.getValues("trigger"),
|
||||
outboundEventTypeId,
|
||||
eventTypeIds,
|
||||
activeOnEventTypeId: form.getValues("activeOn")?.[0]?.value,
|
||||
t,
|
||||
});
|
||||
|
||||
if (eventTypeValidation.error || !eventTypeValidation.eventTypeId) {
|
||||
showToast(eventTypeValidation.error || t("no_event_type_selected"), "error");
|
||||
return;
|
||||
}
|
||||
|
||||
if (agentId) {
|
||||
setError(null);
|
||||
setTranscript([]);
|
||||
setCallDuration(0);
|
||||
createWebCallMutation.mutate({
|
||||
agentId: agentId,
|
||||
teamId: teamId,
|
||||
eventTypeId: eventTypeValidation.eventTypeId,
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const handleEndCall = async () => {
|
||||
if (retellWebClientRef.current && callStatus === "active") {
|
||||
try {
|
||||
await retellWebClientRef.current.stopCall();
|
||||
setCallStatus("ended");
|
||||
stopDurationTimer();
|
||||
} catch (error) {
|
||||
console.error("Error ending call:", error);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const handleToggleMute = async () => {
|
||||
if (retellWebClientRef.current && callStatus === "active") {
|
||||
try {
|
||||
if (isMuted) {
|
||||
await retellWebClientRef.current.unmute();
|
||||
} else {
|
||||
await retellWebClientRef.current.mute();
|
||||
}
|
||||
setIsMuted(!isMuted);
|
||||
} catch (error) {
|
||||
console.error("Error toggling mute:", error);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const formatDuration = (seconds: number) => {
|
||||
const mins = Math.floor(seconds / 60);
|
||||
const secs = seconds % 60;
|
||||
return `${mins.toString().padStart(2, "0")}:${secs.toString().padStart(2, "0")}`;
|
||||
};
|
||||
|
||||
const getStatusIcon = () => {
|
||||
switch (callStatus) {
|
||||
case "connecting":
|
||||
return <Icon name="loader" className="h-4 w-4 animate-spin rounded-full" />;
|
||||
case "active":
|
||||
return <Icon name="phone" className="text-success h-4 w-4" />;
|
||||
case "ended":
|
||||
return <Icon name="phone-off" className="text-muted h-4 w-4" />;
|
||||
case "error":
|
||||
return <Icon name="triangle-alert" className="text-error h-4 w-4" />;
|
||||
default:
|
||||
return <Icon name="phone" className="text-subtle h-4 w-4" />;
|
||||
}
|
||||
};
|
||||
|
||||
const getStatusText = () => {
|
||||
switch (callStatus) {
|
||||
case "connecting":
|
||||
return t("connecting_to_agent");
|
||||
case "active":
|
||||
return `${t("call_active")} - ${formatDuration(callDuration)}`;
|
||||
case "ended":
|
||||
return `${t("call_ended")} - ${formatDuration(callDuration)}`;
|
||||
case "error":
|
||||
return t("call_error");
|
||||
default:
|
||||
return t("ready_to_start_call");
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (transcriptEndRef.current) {
|
||||
transcriptEndRef.current.scrollIntoView({ behavior: "smooth" });
|
||||
}
|
||||
}, [transcript]);
|
||||
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
stopDurationTimer();
|
||||
if (retellWebClientRef.current && callStatus === "active") {
|
||||
try {
|
||||
retellWebClientRef.current.stopCall();
|
||||
} catch (error) {
|
||||
console.error("Error stopping call during cleanup:", error);
|
||||
}
|
||||
}
|
||||
};
|
||||
}, [callStatus]);
|
||||
|
||||
useEffect(() => {
|
||||
callStatusRef.current = callStatus;
|
||||
|
||||
if (callStatus === "active" && callStartTimeRef.current && !durationIntervalRef.current) {
|
||||
startDurationTimer();
|
||||
}
|
||||
}, [callStatus, startDurationTimer]);
|
||||
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
stopDurationTimer();
|
||||
};
|
||||
}, []);
|
||||
|
||||
const resetDialogState = () => {
|
||||
setCallStatus("idle");
|
||||
callStatusRef.current = "idle";
|
||||
setTranscript([]);
|
||||
setIsMuted(false);
|
||||
setCallDuration(0);
|
||||
setError(null);
|
||||
callStartTimeRef.current = null;
|
||||
stopDurationTimer();
|
||||
retellWebClientRef.current = null;
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog
|
||||
open={open}
|
||||
onOpenChange={(open) => {
|
||||
if (!open) {
|
||||
if (retellWebClientRef.current) {
|
||||
try {
|
||||
retellWebClientRef.current.stopCall();
|
||||
} catch (e) {
|
||||
console.error("Error stopping call on close:", e);
|
||||
}
|
||||
}
|
||||
resetDialogState();
|
||||
}
|
||||
onOpenChange(open);
|
||||
}}>
|
||||
<DialogContent
|
||||
enableOverflow
|
||||
type="creation"
|
||||
title={t("web_call")}
|
||||
description={t("test_your_agent_with_web_call")}>
|
||||
{!creditsLoading && (
|
||||
<Alert
|
||||
severity="info"
|
||||
CustomIcon="info"
|
||||
title={t("credits_required")}
|
||||
message={
|
||||
hasCredits ? (
|
||||
t("web_call_credits_info")
|
||||
) : (
|
||||
<>
|
||||
{t("web_call_no_credits")}{" "}
|
||||
<Link href={getBillingPath()} className="text-semantic-info underline">
|
||||
{t("purchase_credits")}
|
||||
</Link>
|
||||
</>
|
||||
)
|
||||
}
|
||||
/>
|
||||
)}
|
||||
<div className="mt-2 flex items-center justify-between rounded-lg border p-3">
|
||||
<div className="flex items-center gap-2">
|
||||
{getStatusIcon()}
|
||||
<span className="text-sm font-medium">{getStatusText()}</span>
|
||||
</div>
|
||||
{callStatus === "active" && (
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="bg-error h-2 w-2 animate-pulse rounded-full" />
|
||||
<span className="text-subtle text-xs">{t("live")}</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="mt-2 rounded-lg border p-3 placeholder:min-h-[300px]">
|
||||
<div className="mb-3 flex items-center justify-between">
|
||||
<h4 className="text-sm font-medium">{t("transcript")}</h4>
|
||||
{transcript.length > 0 && (
|
||||
<Button
|
||||
type="button"
|
||||
color="secondary"
|
||||
size="sm"
|
||||
variant="icon"
|
||||
onClick={() => setTranscript([])}
|
||||
disabled={callStatus === "active"}>
|
||||
<Icon name="trash" className="h-4 w-4" />
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="h-60 stack-y-3 overflow-y-auto p-2">
|
||||
{transcript.length === 0 ? (
|
||||
<div className="flex h-40 items-center justify-center text-center">
|
||||
<div>
|
||||
<Icon name="message-circle" className="text-subtle mx-auto h-8 w-8" />
|
||||
<p className="text-subtle mt-2 text-sm">
|
||||
{callStatus === "idle"
|
||||
? t("start_call_to_see_conversation")
|
||||
: t("waiting_for_conversation")}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
transcript.map((entry, index) => (
|
||||
<div
|
||||
key={index}
|
||||
className={`flex gap-2 ${entry.speaker === "agent" ? "justify-start" : "justify-end"}`}>
|
||||
<div
|
||||
className={`max-w-[80%] rounded-lg px-3 py-2 text-sm ${
|
||||
entry.speaker === "agent"
|
||||
? "border-brand bg-brand/10 text-brand-emphasis border"
|
||||
: "border-subtle bg-subtle text-emphasis border"
|
||||
}`}>
|
||||
<div className="mb-1 flex items-center gap-2">
|
||||
<span className="text-xs font-medium">
|
||||
{entry.speaker === "agent" ? t("ai_agent") : t("you")}
|
||||
</span>
|
||||
</div>
|
||||
<p>{entry.text}</p>
|
||||
</div>
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
<div ref={transcriptEndRef} />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{error && callStatus === "error" && (
|
||||
<div className="border-error bg-error/10 rounded-lg p-3">
|
||||
<div className="flex items-center gap-2">
|
||||
<Icon name="triangle-alert" className="text-error h-6 w-6" />
|
||||
<span className="text-error text-sm">{error}</span>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<DialogFooter showDivider className="mt-6">
|
||||
<div className="flex gap-2">
|
||||
{callStatus === "active" && (
|
||||
<Button type="button" color="secondary" onClick={handleToggleMute} variant="icon">
|
||||
<Icon name={isMuted ? "mic-off" : "mic"} className="h-4 w-4" />
|
||||
</Button>
|
||||
)}
|
||||
|
||||
{callStatus === "idle" ||
|
||||
callStatus === "error" ||
|
||||
callStatus === "ended" ||
|
||||
callStatus === "connecting" ? (
|
||||
<Tooltip content={!hasCredits ? t("credits_required_tooltip") : undefined}>
|
||||
<Button
|
||||
type="button"
|
||||
onClick={handleStartCall}
|
||||
loading={createWebCallMutation.isPending || callStatus === "connecting"}
|
||||
disabled={!hasCredits || createWebCallMutation.isPending || callStatus === "connecting"}>
|
||||
<Icon name="phone" className="mr-2 h-4 w-4" />
|
||||
{callStatus === "connecting" ? t("connecting") : t("start_web_call")}
|
||||
</Button>
|
||||
</Tooltip>
|
||||
) : (
|
||||
<Button
|
||||
type="button"
|
||||
color="destructive"
|
||||
onClick={handleEndCall}
|
||||
disabled={callStatus !== "active"}>
|
||||
<Icon name="phone-off" className="mr-2 h-4 w-4" />
|
||||
{t("end_call")}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -1,195 +0,0 @@
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useState } from "react";
|
||||
import posthog from "posthog-js";
|
||||
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { HttpError } from "@calcom/lib/http-error";
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
import cn from "@calcom/ui/classNames";
|
||||
import { Button } from "@calcom/ui/components/button";
|
||||
import { Dialog, DialogContent, DialogFooter } from "@calcom/ui/components/dialog";
|
||||
import { Icon } from "@calcom/ui/components/icon";
|
||||
import type { IconName } from "@calcom/ui/components/icon";
|
||||
import { RadioGroup, Radio, RadioIndicator } from "@calcom/ui/components/radio";
|
||||
import { showToast } from "@calcom/ui/components/toast";
|
||||
|
||||
type WorkflowOptionCardProps = {
|
||||
title: string;
|
||||
description: string;
|
||||
icon?: IconName;
|
||||
isSelected: boolean;
|
||||
onClick: () => void;
|
||||
iconWrapperClassName?: string;
|
||||
image?: string;
|
||||
value: "scratch" | "calai";
|
||||
};
|
||||
|
||||
function WorkflowOptionCard(props: WorkflowOptionCardProps) {
|
||||
const { title, description, icon, isSelected, onClick, image, iconWrapperClassName, value } = props;
|
||||
|
||||
return (
|
||||
<div
|
||||
data-testid={`workflow-option-card-${value}`}
|
||||
onClick={onClick}
|
||||
className={cn(
|
||||
`relative flex flex-1 cursor-pointer flex-col rounded-lg border p-4 transition-colors`,
|
||||
isSelected ? "border-brand-default" : "border-subtle hover:border-emphasis"
|
||||
)}>
|
||||
<div className="absolute right-3 top-3">
|
||||
<Radio value={value} aria-label={title}>
|
||||
<RadioIndicator />
|
||||
</Radio>
|
||||
</div>
|
||||
<div className="flex flex-col">
|
||||
<div
|
||||
className={cn(
|
||||
"mb-5 flex h-10 w-10 items-center justify-center rounded-lg border",
|
||||
iconWrapperClassName
|
||||
)}>
|
||||
{image ? (
|
||||
<img
|
||||
src={image}
|
||||
alt=""
|
||||
role="presentation"
|
||||
aria-hidden="true"
|
||||
className={cn("text-default h-5 w-5")}
|
||||
/>
|
||||
) : (
|
||||
<Icon name={icon || "circle-plus"} className={cn("text-default h-5 w-5")} aria-hidden="true" />
|
||||
)}
|
||||
</div>
|
||||
<h3 className="text-emphasis text-sm font-semibold">{title}</h3>
|
||||
<p className="text-subtle text-sm">{description}</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
type WorkflowCreationDialogProps = {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
teamId?: number;
|
||||
onSuccess?: () => void;
|
||||
};
|
||||
|
||||
export function WorkflowCreationDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
teamId,
|
||||
onSuccess,
|
||||
}: WorkflowCreationDialogProps) {
|
||||
const { t } = useLocale();
|
||||
const router = useRouter();
|
||||
const [selectedOption, setSelectedOption] = useState<"scratch" | "calai">("scratch");
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const handleOptionChange = (value: string) => {
|
||||
if (value === "scratch" || value === "calai") {
|
||||
setSelectedOption(value);
|
||||
}
|
||||
};
|
||||
|
||||
const createMutation = trpc.viewer.workflows.create.useMutation({
|
||||
onSuccess: async ({ workflow }) => {
|
||||
onOpenChange(false);
|
||||
if (onSuccess) {
|
||||
onSuccess();
|
||||
} else {
|
||||
router.replace(`/workflows/${workflow.id}`);
|
||||
}
|
||||
},
|
||||
onError: (err) => {
|
||||
if (err instanceof HttpError) {
|
||||
const message = `${err.statusCode}: ${err.message}`;
|
||||
showToast(message, "error");
|
||||
}
|
||||
|
||||
if (err.data?.code === "UNAUTHORIZED") {
|
||||
const message = `${err.data.code}: ${t("unauthorized_create_workflow")}`;
|
||||
showToast(message, "error");
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
const handleContinue = () => {
|
||||
if (selectedOption === "scratch") {
|
||||
createMutation.mutate({ teamId });
|
||||
} else if (selectedOption === "calai") {
|
||||
setIsLoading(true);
|
||||
const queryParams = new URLSearchParams({
|
||||
action: "calAi",
|
||||
templateWorkflowId: "wf-11",
|
||||
...(teamId && { teamId: teamId.toString() }),
|
||||
});
|
||||
router.push(`/workflow/new?${queryParams.toString()}`);
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent
|
||||
title={t("new_workflow_btn")}
|
||||
description={t("how_would_you_like_to_start")}
|
||||
type="creation"
|
||||
enableOverflow
|
||||
Icon="zap">
|
||||
<RadioGroup
|
||||
value={selectedOption}
|
||||
onValueChange={handleOptionChange}
|
||||
aria-label={t("new_workflow_btn")}>
|
||||
<div className="mt-6 flex gap-4">
|
||||
<WorkflowOptionCard
|
||||
title={t("start_from_scratch_title")}
|
||||
description={t("start_from_scratch_description")}
|
||||
icon="circle-plus"
|
||||
isSelected={selectedOption === "scratch"}
|
||||
onClick={() => setSelectedOption("scratch")}
|
||||
iconWrapperClassName="bg-cal-muted"
|
||||
value="scratch"
|
||||
/>
|
||||
<WorkflowOptionCard
|
||||
title={t("cal_ai_template_title")}
|
||||
description={t("cal_ai_template_description")}
|
||||
image="/call-outgoing.svg"
|
||||
isSelected={selectedOption === "calai"}
|
||||
onClick={() => setSelectedOption("calai")}
|
||||
iconWrapperClassName="bg-[#2A2947]"
|
||||
value="calai"
|
||||
/>
|
||||
</div>
|
||||
</RadioGroup>
|
||||
|
||||
<DialogFooter className="relative" showDivider>
|
||||
<Button type="button" color="minimal" onClick={() => onOpenChange(false)}>
|
||||
{t("cancel")}
|
||||
</Button>
|
||||
<Button
|
||||
data-testid="continue-button"
|
||||
type="button"
|
||||
onClick={handleContinue}
|
||||
loading={createMutation.isPending || isLoading}>
|
||||
{t("continue")}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
export function useWorkflowCreation() {
|
||||
const [showDialog, setShowDialog] = useState(false);
|
||||
const [pendingTeamId, setPendingTeamId] = useState<number | undefined>(undefined);
|
||||
|
||||
const openDialog = (teamId?: number) => {
|
||||
setPendingTeamId(teamId);
|
||||
setShowDialog(true);
|
||||
posthog.capture("create_new_workflow_button_clicked", { teamId });
|
||||
};
|
||||
|
||||
return {
|
||||
showDialog,
|
||||
setShowDialog,
|
||||
pendingTeamId,
|
||||
openDialog,
|
||||
};
|
||||
}
|
||||
@@ -1,325 +0,0 @@
|
||||
import { useSearchParams } from "next/navigation";
|
||||
import type { Dispatch, SetStateAction } from "react";
|
||||
import { useState, useEffect } from "react";
|
||||
import type { UseFormReturn } from "react-hook-form";
|
||||
|
||||
import { useHasActiveTeamPlan } from "@calcom/features/billing/hooks/useHasPaidPlan";
|
||||
import type { WorkflowPermissions } from "@calcom/features/workflows/repositories/WorkflowPermissionsRepository";
|
||||
import { SENDER_ID, SENDER_NAME, SCANNING_WORKFLOW_STEPS } from "@calcom/lib/constants";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { getTimeFormatStringFromUserTimeFormat } from "@calcom/lib/timeFormat";
|
||||
import { WorkflowActions } from "@calcom/prisma/enums";
|
||||
import { WorkflowTemplates } from "@calcom/prisma/enums";
|
||||
import { trpc, type RouterOutputs } from "@calcom/trpc/react";
|
||||
import { Button } from "@calcom/ui/components/button";
|
||||
import { FormCard, FormCardBody } from "@calcom/ui/components/card";
|
||||
import type { MultiSelectCheckboxesOptionType as Option } from "@calcom/ui/components/form";
|
||||
import { Icon } from "@calcom/ui/components/icon";
|
||||
|
||||
import { useAgentsData } from "../hooks/useAgentsData";
|
||||
import { isCalAIAction, isSMSAction, isFormTrigger, isWhatsappAction } from "../lib/actionHelperFunctions";
|
||||
import { ALLOWED_FORM_WORKFLOW_ACTIONS } from "../lib/constants";
|
||||
import emailReminderTemplate from "../lib/reminders/templates/emailReminderTemplate";
|
||||
import type { FormValues } from "../pages/workflow";
|
||||
import { AddActionDialog } from "./AddActionDialog";
|
||||
import WorkflowStepContainer from "./WorkflowStepContainer";
|
||||
|
||||
type User = RouterOutputs["viewer"]["me"]["get"];
|
||||
|
||||
interface Props {
|
||||
form: UseFormReturn<FormValues>;
|
||||
workflowId: number;
|
||||
selectedOptions: Option[];
|
||||
setSelectedOptions: Dispatch<SetStateAction<Option[]>>;
|
||||
teamId?: number;
|
||||
user: User;
|
||||
isOrg: boolean;
|
||||
allOptions: Option[];
|
||||
eventTypeOptions: Option[];
|
||||
onSaveWorkflow?: () => Promise<void>;
|
||||
permissions: WorkflowPermissions;
|
||||
}
|
||||
|
||||
export default function WorkflowDetailsPage(props: Props) {
|
||||
const {
|
||||
form,
|
||||
workflowId,
|
||||
selectedOptions,
|
||||
setSelectedOptions,
|
||||
teamId,
|
||||
isOrg,
|
||||
allOptions,
|
||||
eventTypeOptions,
|
||||
permissions,
|
||||
} = props;
|
||||
const { t, i18n } = useLocale();
|
||||
const { hasActiveTeamPlan } = useHasActiveTeamPlan();
|
||||
|
||||
const [isAddActionDialogOpen, setIsAddActionDialogOpen] = useState(false);
|
||||
const [isDeleteStepDialogOpen, setIsDeleteStepDialogOpen] = useState(false);
|
||||
|
||||
const [reload, setReload] = useState(false);
|
||||
const [updateTemplate, setUpdateTemplate] = useState(false);
|
||||
|
||||
const searchParams = useSearchParams();
|
||||
const eventTypeId = searchParams?.get("eventTypeId");
|
||||
|
||||
// Get base action options and transform them for form triggers
|
||||
const { data: baseActionOptions } = trpc.viewer.workflows.getWorkflowActionOptions.useQuery();
|
||||
|
||||
const transformedActionOptions = baseActionOptions
|
||||
? baseActionOptions
|
||||
.filter((option) => {
|
||||
const isFormWorkflowWithInvalidSteps =
|
||||
isFormTrigger(form.getValues("trigger")) &&
|
||||
!ALLOWED_FORM_WORKFLOW_ACTIONS.some((action) => action === option.value);
|
||||
|
||||
const isSelectAllCalAiAction = isCalAIAction(option.value) && form.watch("selectAll");
|
||||
|
||||
const isOrgCalAiAction = isCalAIAction(option.value) && isOrg;
|
||||
|
||||
if (isFormWorkflowWithInvalidSteps || isSelectAllCalAiAction || isOrgCalAiAction) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
})
|
||||
.map((option) => {
|
||||
let label = option.label;
|
||||
|
||||
// Transform labels for form triggers
|
||||
if (isFormTrigger(form.getValues("trigger"))) {
|
||||
if (option.value === WorkflowActions.EMAIL_ATTENDEE) {
|
||||
label = t("email_attendee_action_form");
|
||||
} else if (option.value === WorkflowActions.SMS_ATTENDEE) {
|
||||
label = t("sms_attendee_action_form");
|
||||
}
|
||||
}
|
||||
|
||||
const needsTeamsUpgrade = isFormTrigger(form.getValues("trigger")) && !hasActiveTeamPlan;
|
||||
|
||||
return {
|
||||
...option,
|
||||
label,
|
||||
creditsTeamId: teamId,
|
||||
isOrganization: isOrg,
|
||||
isCalAi: isCalAIAction(option.value),
|
||||
needsTeamsUpgrade,
|
||||
};
|
||||
})
|
||||
: [];
|
||||
|
||||
useEffect(() => {
|
||||
const matchingOption = allOptions.find((option) => option.value === eventTypeId);
|
||||
if (matchingOption && !selectedOptions.find((option) => option.value === eventTypeId)) {
|
||||
const newOptions = [...selectedOptions, matchingOption];
|
||||
setSelectedOptions(newOptions);
|
||||
form.setValue("activeOn", newOptions);
|
||||
}
|
||||
}, [eventTypeId]);
|
||||
|
||||
const addAction = (
|
||||
action: WorkflowActions,
|
||||
sendTo?: string,
|
||||
numberRequired?: boolean,
|
||||
sender?: string,
|
||||
senderName?: string
|
||||
) => {
|
||||
const steps = form.getValues("steps");
|
||||
const id =
|
||||
steps?.length > 0
|
||||
? steps.sort((a, b) => {
|
||||
return a.id - b.id;
|
||||
})[0].id - 1
|
||||
: 0;
|
||||
|
||||
const timeFormat = getTimeFormatStringFromUserTimeFormat(props.user.timeFormat);
|
||||
|
||||
const template = isFormTrigger(form.getValues("trigger"))
|
||||
? WorkflowTemplates.CUSTOM
|
||||
: WorkflowTemplates.REMINDER;
|
||||
|
||||
const { emailBody: reminderBody, emailSubject } =
|
||||
template !== WorkflowTemplates.CUSTOM
|
||||
? emailReminderTemplate({
|
||||
isEditingMode: true,
|
||||
locale: i18n.language,
|
||||
t,
|
||||
action,
|
||||
timeFormat,
|
||||
})
|
||||
: { emailBody: null, emailSubject: null };
|
||||
|
||||
const step = {
|
||||
id: id > 0 ? 0 : id, //id of new steps always <= 0
|
||||
action,
|
||||
stepNumber:
|
||||
steps && steps.length > 0
|
||||
? steps.sort((a, b) => {
|
||||
return a.stepNumber - b.stepNumber;
|
||||
})[steps.length - 1].stepNumber + 1
|
||||
: 1,
|
||||
sendTo: sendTo || null,
|
||||
workflowId: workflowId,
|
||||
reminderBody,
|
||||
emailSubject,
|
||||
template,
|
||||
numberRequired: numberRequired || false,
|
||||
sender: isSMSAction(action) ? sender || SENDER_ID : SENDER_ID,
|
||||
senderName: !isSMSAction(action) ? senderName || SENDER_NAME : SENDER_NAME,
|
||||
numberVerificationPending: false,
|
||||
includeCalendarEvent: false,
|
||||
verifiedAt: SCANNING_WORKFLOW_STEPS ? null : new Date(),
|
||||
agentId: null,
|
||||
inboundAgentId: null,
|
||||
};
|
||||
steps?.push(step);
|
||||
form.setValue("steps", steps);
|
||||
};
|
||||
|
||||
const { outboundAgentQueries: agentQueriesTrpc, inboundAgentQueries: inboundAgentQueriesTrpc } =
|
||||
useAgentsData(form);
|
||||
|
||||
return (
|
||||
<>
|
||||
<div>
|
||||
<FormCard
|
||||
className="mb-0 border-muted"
|
||||
collapsible={false}
|
||||
label={
|
||||
<div className="flex gap-2 items-center pt-1 pb-2">
|
||||
<div className="p-1 ml-1 rounded-lg border border-subtle text-subtle">
|
||||
<Icon name="zap" size="16" />
|
||||
</div>
|
||||
<div className="text-sm font-medium leading-none">{t("trigger")}</div>
|
||||
</div>
|
||||
}>
|
||||
<FormCardBody className="border-muted">
|
||||
<WorkflowStepContainer
|
||||
form={form}
|
||||
user={props.user}
|
||||
teamId={teamId}
|
||||
readOnly={permissions.readOnly}
|
||||
selectedOptions={selectedOptions}
|
||||
setSelectedOptions={setSelectedOptions}
|
||||
isOrganization={isOrg}
|
||||
allOptions={allOptions}
|
||||
eventTypeOptions={eventTypeOptions}
|
||||
onSaveWorkflow={props.onSaveWorkflow}
|
||||
actionOptions={transformedActionOptions}
|
||||
updateTemplate={updateTemplate}
|
||||
setUpdateTemplate={setUpdateTemplate}
|
||||
/>
|
||||
</FormCardBody>
|
||||
</FormCard>
|
||||
|
||||
<div className="mt-0! ml-7 h-3 w-2 border-l" />
|
||||
{form.getValues("steps") && (
|
||||
<div className="">
|
||||
{form.getValues("steps")?.map((step, index) => {
|
||||
const agentData = agentQueriesTrpc[index]?.data;
|
||||
const isAgentLoading = agentQueriesTrpc[index]?.isPending;
|
||||
const inboundAgentData = inboundAgentQueriesTrpc[index]?.data;
|
||||
const isInboundAgentLoading = inboundAgentQueriesTrpc[index]?.isPending;
|
||||
|
||||
return (
|
||||
<div key={index}>
|
||||
<FormCard
|
||||
key={step.id}
|
||||
className="mb-0 bg-cal-muted border-muted"
|
||||
collapsible={false}
|
||||
label={
|
||||
<div className="flex gap-2 items-center pt-1 pb-2">
|
||||
<div className="p-1 rounded-lg border border-subtle text-subtle">
|
||||
<Icon name="arrow-right" size="16" />
|
||||
</div>
|
||||
<div className="text-sm font-medium leading-none">{t("action")}</div>
|
||||
</div>
|
||||
}
|
||||
deleteField={
|
||||
!permissions.readOnly
|
||||
? {
|
||||
color: "destructive",
|
||||
check: () => true,
|
||||
disabled: !permissions.canUpdate,
|
||||
fn: () => {
|
||||
if (
|
||||
isCalAIAction(step.action) &&
|
||||
agentData?.outboundPhoneNumbers &&
|
||||
agentData.outboundPhoneNumbers.length > 0
|
||||
) {
|
||||
setIsDeleteStepDialogOpen(true);
|
||||
} else {
|
||||
const steps = form.getValues("steps");
|
||||
const updatedSteps = steps
|
||||
?.filter((currStep) => currStep.id !== step.id)
|
||||
.map((s) => {
|
||||
const updatedStep = s;
|
||||
if (step.stepNumber < updatedStep.stepNumber) {
|
||||
updatedStep.stepNumber = updatedStep.stepNumber - 1;
|
||||
}
|
||||
return updatedStep;
|
||||
});
|
||||
form.setValue("steps", updatedSteps);
|
||||
if (setReload) {
|
||||
setReload(!reload);
|
||||
}
|
||||
}
|
||||
},
|
||||
}
|
||||
: null
|
||||
}>
|
||||
<FormCardBody className="border-muted">
|
||||
<WorkflowStepContainer
|
||||
form={form}
|
||||
user={props.user}
|
||||
step={step}
|
||||
reload={reload}
|
||||
setReload={setReload}
|
||||
teamId={teamId}
|
||||
readOnly={permissions.readOnly}
|
||||
eventTypeOptions={eventTypeOptions}
|
||||
onSaveWorkflow={props.onSaveWorkflow}
|
||||
setIsDeleteStepDialogOpen={setIsDeleteStepDialogOpen}
|
||||
isDeleteStepDialogOpen={isDeleteStepDialogOpen}
|
||||
isAgentLoading={isAgentLoading}
|
||||
agentData={agentData}
|
||||
inboundAgentData={inboundAgentData}
|
||||
isInboundAgentLoading={isInboundAgentLoading}
|
||||
allOptions={allOptions}
|
||||
actionOptions={transformedActionOptions}
|
||||
updateTemplate={updateTemplate}
|
||||
setUpdateTemplate={setUpdateTemplate}
|
||||
/>
|
||||
</FormCardBody>
|
||||
</FormCard>
|
||||
{index !== form.getValues("steps").length - 1 && (
|
||||
<div className="border-default mt-0! ml-7 h-3 w-2 border-l" />
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
{!permissions.readOnly && (
|
||||
<>
|
||||
<div className="border-default mt-0! ml-7 h-3 w-2 border-l" />
|
||||
<Button
|
||||
type="button"
|
||||
onClick={() => setIsAddActionDialogOpen(true)}
|
||||
color="secondary"
|
||||
className="bg-default">
|
||||
{t("add_action")}
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<AddActionDialog
|
||||
isOpenDialog={isAddActionDialogOpen}
|
||||
setIsOpenDialog={setIsAddActionDialogOpen}
|
||||
addAction={addAction}
|
||||
actionOptions={transformedActionOptions}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -1,319 +0,0 @@
|
||||
import { useAutoAnimate } from "@formkit/auto-animate/react";
|
||||
import Link from "next/link";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useState } from "react";
|
||||
|
||||
import { getPlaceholderAvatar } from "@calcom/lib/defaultAvatarImage";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
import classNames from "@calcom/ui/classNames";
|
||||
import { ArrowButton } from "@calcom/ui/components/arrow-button";
|
||||
import { Avatar } from "@calcom/ui/components/avatar";
|
||||
import { Badge } from "@calcom/ui/components/badge";
|
||||
import { Button } from "@calcom/ui/components/button";
|
||||
import { ButtonGroup } from "@calcom/ui/components/buttonGroup";
|
||||
import {
|
||||
Dropdown,
|
||||
DropdownItem,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
} from "@calcom/ui/components/dropdown";
|
||||
import { Icon } from "@calcom/ui/components/icon";
|
||||
import { Tooltip } from "@calcom/ui/components/tooltip";
|
||||
|
||||
import { getActionIcon } from "../lib/getActionIcon";
|
||||
import { type WorkflowListType } from "../lib/types";
|
||||
import { DeleteDialog } from "./DeleteDialog";
|
||||
|
||||
/** @deprecated Use WorkflowListType from ../lib/types instead */
|
||||
export type WorkflowType = WorkflowListType;
|
||||
|
||||
interface Props {
|
||||
workflows: WorkflowType[] | undefined;
|
||||
}
|
||||
export default function WorkflowListPage({ workflows }: Props) {
|
||||
const { t } = useLocale();
|
||||
const utils = trpc.useUtils();
|
||||
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
|
||||
const [workflowToDeleteId, setwWorkflowToDeleteId] = useState(0);
|
||||
const [parent] = useAutoAnimate<HTMLUListElement>();
|
||||
const router = useRouter();
|
||||
|
||||
const mutation = trpc.viewer.workflows.workflowOrder.useMutation({
|
||||
onError: async (err) => {
|
||||
console.error(err.message);
|
||||
await utils.viewer.workflows.filteredList.cancel();
|
||||
await utils.viewer.workflows.filteredList.invalidate();
|
||||
},
|
||||
onSettled: () => {
|
||||
utils.viewer.workflows.filteredList.invalidate();
|
||||
},
|
||||
});
|
||||
|
||||
async function moveWorkflow(index: number, increment: 1 | -1) {
|
||||
const types = workflows!;
|
||||
|
||||
const newList = [...types];
|
||||
|
||||
const type = types[index];
|
||||
const tmp = types[index + increment];
|
||||
if (tmp) {
|
||||
newList[index] = tmp;
|
||||
newList[index + increment] = type;
|
||||
}
|
||||
|
||||
await utils.viewer.appRoutingForms.forms.cancel();
|
||||
|
||||
mutation.mutate({
|
||||
ids: newList?.map((type) => type.id),
|
||||
});
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
{workflows && workflows.length > 0 ? (
|
||||
<div className="bg-default border-subtle overflow-hidden rounded-md border sm:mx-0">
|
||||
<ul className="divide-subtle static! w-full divide-y" data-testid="workflow-list" ref={parent}>
|
||||
{workflows.map((workflow, index) => {
|
||||
const firstItem = workflows[0];
|
||||
const lastItem = workflows[workflows.length - 1];
|
||||
const dataTestId = `workflow-${workflow.name.toLowerCase().replaceAll(" ", "-")}`;
|
||||
return (
|
||||
<li
|
||||
key={workflow.id}
|
||||
data-testid={dataTestId}
|
||||
className="group flex w-full max-w-full items-center justify-between overflow-hidden">
|
||||
{!(firstItem && firstItem.id === workflow.id) && (
|
||||
<ArrowButton onClick={() => moveWorkflow(index, -1)} arrowDirection="up" />
|
||||
)}
|
||||
{!(lastItem && lastItem.id === workflow.id) && (
|
||||
<ArrowButton onClick={() => moveWorkflow(index, 1)} arrowDirection="down" />
|
||||
)}
|
||||
<div className="first-line:group hover:bg-cal-muted flex w-full items-center justify-between p-4 transition sm:px-6">
|
||||
<Link href={`/workflows/${workflow.id}`} className="grow cursor-pointer">
|
||||
<div className="rtl:space-x-reverse">
|
||||
<div className="flex">
|
||||
<div
|
||||
className={classNames(
|
||||
"max-w-56 text-emphasis truncate text-sm font-medium leading-6 md:max-w-max",
|
||||
workflow.name ? "text-emphasis" : "text-subtle"
|
||||
)}>
|
||||
{workflow.name
|
||||
? workflow.name
|
||||
: workflow.steps[0]
|
||||
? `Untitled (${`${t(`${workflow.steps[0].action.toLowerCase()}_action`)}`
|
||||
.charAt(0)
|
||||
.toUpperCase()}${`${t(
|
||||
`${workflow.steps[0].action.toLowerCase()}_action`
|
||||
)}`.slice(1)})`
|
||||
: "Untitled"}
|
||||
</div>
|
||||
<div>
|
||||
{(workflow.permissions?.readOnly ?? workflow.readOnly) && (
|
||||
<Badge variant="gray" className="ml-2 ">
|
||||
{t("readonly")}
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<ul className="mt-1 flex flex-wrap space-x-2 sm:flex-nowrap ">
|
||||
<li>
|
||||
<Badge variant="gray">
|
||||
<div>
|
||||
{getActionIcon(workflow.steps)}
|
||||
|
||||
<span className="mr-1">{t("triggers")}</span>
|
||||
{workflow.timeUnit && workflow.time && (
|
||||
<span className="mr-1">
|
||||
{t(`${workflow.timeUnit.toLowerCase()}`, { count: workflow.time })}
|
||||
</span>
|
||||
)}
|
||||
<span>{t(`${workflow.trigger.toLowerCase()}_trigger`)}</span>
|
||||
</div>
|
||||
</Badge>
|
||||
</li>
|
||||
<li>
|
||||
<Badge variant="gray">
|
||||
{/*active on all badge */}
|
||||
{workflow.isActiveOnAll ? (
|
||||
<div>
|
||||
<Icon name="link" className="mr-1.5 inline h-3 w-3" aria-hidden="true" />
|
||||
{workflow.isOrg ? t("active_on_all_teams") : t("active_on_all_event_types")}
|
||||
</div>
|
||||
) : workflow.activeOn && workflow.activeOn.length > 0 ? (
|
||||
//active on event types badge
|
||||
<Tooltip
|
||||
content={workflow.activeOn
|
||||
.filter((wf) => (workflow.teamId ? wf.eventType.parentId === null : true))
|
||||
.map((activeOn, key) => (
|
||||
<p key={key}>
|
||||
{activeOn.eventType.title}
|
||||
{activeOn.eventType._count.children > 0
|
||||
? ` (+${activeOn.eventType._count.children})`
|
||||
: ""}
|
||||
</p>
|
||||
))}>
|
||||
<div>
|
||||
<Icon name="link" className="mr-1.5 inline h-3 w-3" aria-hidden="true" />
|
||||
{t("active_on_event_types", {
|
||||
count: workflow.activeOn.filter((wf) =>
|
||||
workflow.teamId ? wf.eventType.parentId === null : true
|
||||
).length,
|
||||
})}
|
||||
</div>
|
||||
</Tooltip>
|
||||
) : workflow.activeOnTeams && workflow.activeOnTeams.length > 0 ? (
|
||||
//active on teams badge
|
||||
<Tooltip
|
||||
content={workflow.activeOnTeams.map((activeOn, key) => (
|
||||
<p key={key}>{activeOn.team.name}</p>
|
||||
))}>
|
||||
<div>
|
||||
<Icon name="link" className="mr-1.5 inline h-3 w-3" aria-hidden="true" />
|
||||
{t("active_on_teams", {
|
||||
count: workflow.activeOnTeams?.length,
|
||||
})}
|
||||
</div>
|
||||
</Tooltip>
|
||||
) : (
|
||||
// active on no teams or event types
|
||||
<div>
|
||||
<Icon name="link" className="mr-1.5 inline h-3 w-3" aria-hidden="true" />
|
||||
{workflow.isOrg ? t("no_active_teams") : t("no_active_event_types")}
|
||||
</div>
|
||||
)}
|
||||
</Badge>
|
||||
</li>
|
||||
<div className="block md:hidden">
|
||||
{workflow.team?.name && (
|
||||
<li>
|
||||
<Badge variant="gray">
|
||||
<>{workflow.team.name}</>
|
||||
</Badge>
|
||||
</li>
|
||||
)}
|
||||
</div>
|
||||
</ul>
|
||||
</div>
|
||||
</Link>
|
||||
<div>
|
||||
<div className="hidden md:block">
|
||||
{workflow.team?.name && (
|
||||
<Badge className="mb-2 mr-4 mt-1 p-px px-2" variant="gray">
|
||||
<Avatar
|
||||
alt={workflow.team?.name || ""}
|
||||
href={
|
||||
workflow.team?.id
|
||||
? `/settings/teams/${workflow.team?.id}/profile`
|
||||
: "/settings/my-account/profile"
|
||||
}
|
||||
imageSrc={getPlaceholderAvatar(
|
||||
workflow?.team.logo,
|
||||
workflow.team?.name as string
|
||||
)}
|
||||
size="xs"
|
||||
className="mt-[3px] inline-flex justify-center"
|
||||
/>
|
||||
<div>{workflow.team.name}</div>
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex shrink-0">
|
||||
<div className="hidden sm:block">
|
||||
<ButtonGroup combined>
|
||||
<Tooltip content={t("edit") as string}>
|
||||
<Button
|
||||
type="button"
|
||||
color="secondary"
|
||||
variant="icon"
|
||||
StartIcon="pencil"
|
||||
disabled={
|
||||
workflow.permissions ? !workflow.permissions?.canUpdate : workflow.readOnly
|
||||
}
|
||||
onClick={async () => await router.replace(`/workflows/${workflow.id}`)}
|
||||
data-testid="edit-button"
|
||||
/>
|
||||
</Tooltip>
|
||||
<Tooltip content={t("delete") as string}>
|
||||
<Button
|
||||
onClick={() => {
|
||||
setDeleteDialogOpen(true);
|
||||
setwWorkflowToDeleteId(workflow.id);
|
||||
}}
|
||||
color="destructive"
|
||||
variant="icon"
|
||||
disabled={
|
||||
workflow.permissions ? !workflow.permissions?.canDelete : workflow.readOnly
|
||||
}
|
||||
StartIcon="trash-2"
|
||||
data-testid="delete-button"
|
||||
/>
|
||||
</Tooltip>
|
||||
</ButtonGroup>
|
||||
</div>
|
||||
{(workflow.permissions?.canUpdate ||
|
||||
workflow.permissions?.canDelete ||
|
||||
(!workflow.permissions && !workflow.readOnly)) && (
|
||||
<div className="block sm:hidden">
|
||||
<Dropdown>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button type="button" color="minimal" variant="icon" StartIcon="ellipsis" />
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent>
|
||||
{(workflow.permissions
|
||||
? workflow.permissions?.canUpdate
|
||||
: !workflow.readOnly) && (
|
||||
<DropdownMenuItem>
|
||||
<DropdownItem
|
||||
type="button"
|
||||
StartIcon="pencil"
|
||||
onClick={async () => await router.replace(`/workflows/${workflow.id}`)}>
|
||||
{t("edit")}
|
||||
</DropdownItem>
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
{(workflow.permissions
|
||||
? workflow.permissions?.canDelete
|
||||
: !workflow.readOnly) && (
|
||||
<DropdownMenuItem>
|
||||
<DropdownItem
|
||||
type="button"
|
||||
color="destructive"
|
||||
StartIcon="trash-2"
|
||||
onClick={() => {
|
||||
setDeleteDialogOpen(true);
|
||||
setwWorkflowToDeleteId(workflow.id);
|
||||
}}>
|
||||
{t("delete")}
|
||||
</DropdownItem>
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
</DropdownMenuContent>
|
||||
</Dropdown>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
<DeleteDialog
|
||||
isOpenDialog={deleteDialogOpen}
|
||||
setIsOpenDialog={setDeleteDialogOpen}
|
||||
workflowId={workflowToDeleteId}
|
||||
additionalFunction={async () => {
|
||||
await utils.viewer.workflows.filteredList.invalidate();
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
) : (
|
||||
<></>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
-389
@@ -1,389 +0,0 @@
|
||||
import { useState } from "react";
|
||||
import type { UseFormReturn } from "react-hook-form";
|
||||
|
||||
import type { Language } from "@calcom/features/calAIPhone/providers/retellAI/types";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import type { RouterOutputs } from "@calcom/trpc/react";
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
import { Button } from "@calcom/ui/components/button";
|
||||
import {
|
||||
Dropdown,
|
||||
DropdownItem,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
} from "@calcom/ui/components/dropdown";
|
||||
import type { MultiSelectCheckboxesOptionType as Option } from "@calcom/ui/components/form";
|
||||
import { ToggleGroup } from "@calcom/ui/components/form";
|
||||
import {
|
||||
Sheet,
|
||||
SheetContent,
|
||||
SheetHeader,
|
||||
SheetTitle,
|
||||
SheetBody,
|
||||
SheetFooter,
|
||||
} from "@calcom/ui/components/sheet";
|
||||
import { showToast } from "@calcom/ui/components/toast";
|
||||
|
||||
import type { FormValues } from "../../pages/workflow";
|
||||
import { WebCallDialog } from "../WebCallDialog";
|
||||
import { IncomingCallsTab } from "./components/tabs/IncomingCallsTab";
|
||||
import { OutgoingCallsTab } from "./components/tabs/OutgoingCallsTab";
|
||||
import { PhoneNumberTab } from "./components/tabs/PhoneNumberTab";
|
||||
import { useAgentForms } from "./hooks/useAgentForms";
|
||||
import type { AgentFormValues } from "./types/schemas";
|
||||
import { restorePromptComplexity } from "./utils/promptUtils";
|
||||
|
||||
type AgentConfigurationSheetProps = {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
agentId?: string | null;
|
||||
inboundAgentId?: string | null;
|
||||
agentData?: RouterOutputs["viewer"]["aiVoiceAgent"]["get"];
|
||||
inboundAgentData?: RouterOutputs["viewer"]["aiVoiceAgent"]["get"];
|
||||
onUpdate: (data: AgentFormValues & { id: string }) => void;
|
||||
readOnly?: boolean;
|
||||
teamId?: number;
|
||||
isOrganization?: boolean;
|
||||
workflowId?: string;
|
||||
workflowStepId?: number;
|
||||
activeTab?: "outgoingCalls" | "phoneNumber" | "incomingCalls";
|
||||
form: UseFormReturn<FormValues>;
|
||||
eventTypeOptions?: Option[];
|
||||
};
|
||||
|
||||
export function AgentConfigurationSheet({
|
||||
open,
|
||||
activeTab: _activeTab,
|
||||
onOpenChange,
|
||||
agentId,
|
||||
inboundAgentId,
|
||||
agentData,
|
||||
inboundAgentData,
|
||||
readOnly = false,
|
||||
teamId,
|
||||
isOrganization = false,
|
||||
workflowId,
|
||||
workflowStepId,
|
||||
form,
|
||||
eventTypeOptions = [],
|
||||
}: AgentConfigurationSheetProps) {
|
||||
const { t } = useLocale();
|
||||
const utils = trpc.useUtils();
|
||||
|
||||
const [activeTab, setActiveTab] = useState<"outgoingCalls" | "phoneNumber" | "incomingCalls">(
|
||||
_activeTab ?? "outgoingCalls"
|
||||
);
|
||||
const [isWebCallDialogOpen, setIsWebCallDialogOpen] = useState(false);
|
||||
|
||||
const activeAgentId = activeTab === "incomingCalls" ? inboundAgentId : agentId;
|
||||
|
||||
const { outboundAgentForm, inboundAgentForm } = useAgentForms({ agentData, inboundAgentData });
|
||||
|
||||
const trigger = form.watch("trigger");
|
||||
|
||||
const updateAgentMutation = trpc.viewer.aiVoiceAgent.update.useMutation({
|
||||
onSuccess: async () => {
|
||||
if (activeAgentId) {
|
||||
await utils.viewer.aiVoiceAgent.get.invalidate({ id: activeAgentId });
|
||||
}
|
||||
},
|
||||
onError: (error: { message: string }) => {
|
||||
showToast(error.message, "error");
|
||||
},
|
||||
});
|
||||
|
||||
const handleAgentUpdate = async (data: AgentFormValues) => {
|
||||
if (!agentId) return;
|
||||
if (trigger === "FORM_SUBMITTED" && !data.outboundEventTypeId) {
|
||||
showToast(t("select_event_type_to_schedule_calls"), "error");
|
||||
return;
|
||||
}
|
||||
|
||||
const updatePayload = {
|
||||
generalPrompt: restorePromptComplexity(data.generalPrompt),
|
||||
beginMessage: data.beginMessage,
|
||||
language: data.language as Language,
|
||||
voiceId: data.voiceId,
|
||||
outboundEventTypeId: data.outboundEventTypeId,
|
||||
};
|
||||
|
||||
await updateAgentMutation.mutateAsync({
|
||||
id: agentId,
|
||||
teamId: teamId,
|
||||
...updatePayload,
|
||||
});
|
||||
};
|
||||
|
||||
const handleInboundAgentUpdate = async (data: AgentFormValues) => {
|
||||
if (!inboundAgentId) return;
|
||||
|
||||
const updatePayload = {
|
||||
generalPrompt: restorePromptComplexity(data.generalPrompt),
|
||||
beginMessage: data.beginMessage,
|
||||
language: data.language as Language,
|
||||
voiceId: data.voiceId,
|
||||
};
|
||||
|
||||
await updateAgentMutation.mutateAsync({
|
||||
id: inboundAgentId,
|
||||
teamId: teamId,
|
||||
...updatePayload,
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<Sheet open={open} onOpenChange={onOpenChange}>
|
||||
<SheetContent className="sm:max-w-xl">
|
||||
<SheetHeader showCloseButton={false} className="w-full">
|
||||
<SheetTitle className="mb-6">{t("cal_ai_agent_configuration")}</SheetTitle>
|
||||
<ToggleGroup
|
||||
onValueChange={(val) => {
|
||||
setActiveTab((val || "outgoingCalls") as "outgoingCalls" | "phoneNumber" | "incomingCalls");
|
||||
}}
|
||||
value={activeTab}
|
||||
options={[
|
||||
{ value: "outgoingCalls", label: t("outgoing_calls") },
|
||||
{ value: "phoneNumber", label: t("phone_number") },
|
||||
{ value: "incomingCalls", label: t("incoming_calls") },
|
||||
]}
|
||||
isFullWidth={true}
|
||||
/>
|
||||
</SheetHeader>
|
||||
<SheetBody className="px-0">
|
||||
{activeTab === "outgoingCalls" && (
|
||||
<OutgoingCallsTab
|
||||
outboundAgentForm={outboundAgentForm}
|
||||
readOnly={readOnly}
|
||||
eventTypeOptions={eventTypeOptions}
|
||||
trigger={trigger}
|
||||
/>
|
||||
)}
|
||||
|
||||
{activeTab === "phoneNumber" && (
|
||||
<PhoneNumberTab
|
||||
agentData={agentData}
|
||||
agentId={agentId}
|
||||
readOnly={readOnly}
|
||||
teamId={teamId}
|
||||
workflowId={workflowId}
|
||||
isOrganization={isOrganization}
|
||||
form={form}
|
||||
eventTypeIds={eventTypeOptions?.map((opt) => parseInt(opt.value, 10))}
|
||||
/>
|
||||
)}
|
||||
|
||||
{activeTab === "incomingCalls" && (
|
||||
<IncomingCallsTab
|
||||
agentData={agentData}
|
||||
inboundAgentData={inboundAgentData}
|
||||
inboundAgentId={inboundAgentId}
|
||||
inboundAgentForm={inboundAgentForm}
|
||||
form={form}
|
||||
eventTypeOptions={eventTypeOptions}
|
||||
readOnly={readOnly}
|
||||
teamId={teamId}
|
||||
workflowStepId={workflowStepId}
|
||||
/>
|
||||
)}
|
||||
</SheetBody>
|
||||
<SheetFooter>
|
||||
<div className="mr-auto">
|
||||
<Dropdown>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button
|
||||
color="secondary"
|
||||
className="rounded-[10px]"
|
||||
disabled={readOnly}
|
||||
EndIcon="chevron-down">
|
||||
{t("test_agent")}
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent>
|
||||
<DropdownMenuItem>
|
||||
<DropdownItem
|
||||
type="button"
|
||||
StartIcon="monitor"
|
||||
onClick={() => {
|
||||
setIsWebCallDialogOpen(true);
|
||||
}}>
|
||||
{t("web_call")}
|
||||
</DropdownItem>
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</Dropdown>
|
||||
</div>
|
||||
<Button
|
||||
className="justify-center"
|
||||
type="button"
|
||||
color="secondary"
|
||||
onClick={() => onOpenChange(false)}>
|
||||
{t("cancel")}
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
className="justify-center"
|
||||
onClick={() => {
|
||||
if (activeTab === "incomingCalls" && inboundAgentId) {
|
||||
inboundAgentForm.handleSubmit(handleInboundAgentUpdate)();
|
||||
} else if (activeTab === "outgoingCalls" && agentId) {
|
||||
outboundAgentForm.handleSubmit(handleAgentUpdate)();
|
||||
}
|
||||
}}
|
||||
disabled={
|
||||
readOnly ||
|
||||
updateAgentMutation.isPending ||
|
||||
(activeTab === "outgoingCalls" && !outboundAgentForm.formState.isDirty) ||
|
||||
(activeTab === "incomingCalls" && !inboundAgentForm.formState.isDirty) ||
|
||||
(activeTab === "outgoingCalls" && !agentId) ||
|
||||
(activeTab === "incomingCalls" && !inboundAgentId)
|
||||
}
|
||||
loading={updateAgentMutation.isPending}>
|
||||
{t("save")}
|
||||
</Button>
|
||||
</SheetFooter>
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
|
||||
{activeAgentId && (
|
||||
<WebCallDialog
|
||||
open={isWebCallDialogOpen}
|
||||
onOpenChange={setIsWebCallDialogOpen}
|
||||
agentId={activeAgentId}
|
||||
teamId={teamId}
|
||||
isOrganization={isOrganization}
|
||||
form={form}
|
||||
eventTypeIds={eventTypeOptions?.map((opt) => parseInt(opt.value, 10))}
|
||||
outboundEventTypeId={agentData?.outboundEventTypeId}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* <ToolsDialog
|
||||
open={toolDialogOpen}
|
||||
onOpenChange={setToolDialogOpen}
|
||||
toolDraft={toolDraft}
|
||||
setToolDraft={setToolDraft}
|
||||
onSave={handleToolDialogSave}
|
||||
isEditing={editingToolIndex !== null}
|
||||
/> */}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
// const ToolsDialog = ({
|
||||
// open,
|
||||
// onOpenChange,
|
||||
// toolDraft,
|
||||
// setToolDraft,
|
||||
// onSave,
|
||||
// isEditing,
|
||||
// }: {
|
||||
// open: boolean;
|
||||
// onOpenChange: (open: boolean) => void;
|
||||
// toolDraft: ToolDraft | null;
|
||||
// setToolDraft: (draft: ToolDraft) => void;
|
||||
// onSave: () => void;
|
||||
// isEditing: boolean;
|
||||
// }) => {
|
||||
// const { t } = useLocale();
|
||||
|
||||
// const TOOL_TYPES = [
|
||||
// { label: t("Check Availability"), value: "check_availability_cal" },
|
||||
// { label: t("Book Appointment"), value: "book_appointment_cal" },
|
||||
// { label: t("End Call"), value: "end_call" },
|
||||
// ];
|
||||
|
||||
// return (
|
||||
// <Dialog open={open} onOpenChange={onOpenChange}>
|
||||
// <DialogContent
|
||||
// enableOverflow
|
||||
// title={isEditing ? t("Edit Function") : t("Add Function")}
|
||||
// type="creation">
|
||||
// <div className="flex flex-col gap-4">
|
||||
// <div>
|
||||
// <Label>{t("Type")}</Label>
|
||||
// <Select
|
||||
// options={TOOL_TYPES}
|
||||
// value={TOOL_TYPES.find((opt) => opt.value === toolDraft?.type) || null}
|
||||
// onChange={(option) => setToolDraft((d: ToolDraft) => ({ ...d, type: option?.value || "" }))}
|
||||
// placeholder={t("Select function type")}
|
||||
// />
|
||||
// </div>
|
||||
// <div>
|
||||
// <Label>{t("Name")}</Label>
|
||||
// <TextField
|
||||
// required
|
||||
// value={toolDraft?.name || ""}
|
||||
// onChange={(e) => setToolDraft((d: ToolDraft) => ({ ...d, name: e.target.value }))}
|
||||
// placeholder={t("Enter function name")}
|
||||
// />
|
||||
// </div>
|
||||
// <div>
|
||||
// <Label>{t("Description")}</Label>
|
||||
// <TextArea
|
||||
// value={toolDraft?.description || ""}
|
||||
// onChange={(e) => setToolDraft((d: ToolDraft) => ({ ...d, description: e.target.value }))}
|
||||
// placeholder={t("Enter description (optional)")}
|
||||
// />
|
||||
// </div>
|
||||
// {(toolDraft?.type === "check_availability_cal" || toolDraft?.type === "book_appointment_cal") && (
|
||||
// <>
|
||||
// <div>
|
||||
// <Label>
|
||||
// {t("API Key (Cal.com)")}
|
||||
// <span className="text-red-500"> *</span>
|
||||
// </Label>
|
||||
// <TextField
|
||||
// required
|
||||
// value={toolDraft?.cal_api_key || ""}
|
||||
// onChange={(e) => setToolDraft((d: ToolDraft) => ({ ...d, cal_api_key: e.target.value }))}
|
||||
// placeholder={t("Enter Cal.com API key")}
|
||||
// />
|
||||
// </div>
|
||||
// <div>
|
||||
// <Label>
|
||||
// {t("Event Type ID (Cal.com)")}
|
||||
// <span className="text-red-500"> *</span>
|
||||
// </Label>
|
||||
// <TextField
|
||||
// required
|
||||
// value={toolDraft?.event_type_id || ""}
|
||||
// onChange={(e) =>
|
||||
// setToolDraft((d: ToolDraft) => ({
|
||||
// ...d,
|
||||
// event_type_id: e.target.value ? Number(e.target.value) : null,
|
||||
// }))
|
||||
// }
|
||||
// placeholder={t("Enter Event Type ID")}
|
||||
// type="number"
|
||||
// />
|
||||
// </div>
|
||||
// <div>
|
||||
// <Label>
|
||||
// {t("Timezone")}
|
||||
// <span className="text-red-500"> *</span>
|
||||
// </Label>
|
||||
// <TextField
|
||||
// required
|
||||
// value={toolDraft?.timezone || ""}
|
||||
// onChange={(e) => setToolDraft((d: ToolDraft) => ({ ...d, timezone: e.target.value }))}
|
||||
// placeholder={t("America/Los_Angeles")}
|
||||
// />
|
||||
// <p className="mt-1 text-xs text-subtle">{t("Required for Cal.com calendar integration")}</p>
|
||||
// </div>
|
||||
// </>
|
||||
// )}
|
||||
// </div>
|
||||
// <DialogFooter showDivider>
|
||||
// <Button type="button" color="secondary" onClick={() => onOpenChange(false)}>
|
||||
// {t("Cancel")}
|
||||
// </Button>
|
||||
// <Button type="button" onClick={onSave}>
|
||||
// {t("Save")}
|
||||
// </Button>
|
||||
// </DialogFooter>
|
||||
// </DialogContent>
|
||||
// </Dialog>
|
||||
// );
|
||||
// };
|
||||
-138
@@ -1,138 +0,0 @@
|
||||
import posthog from "posthog-js";
|
||||
|
||||
import { CAL_AI_PHONE_NUMBER_MONTHLY_PRICE } from "@calcom/lib/constants";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
import { Alert } from "@calcom/ui/components/alert";
|
||||
import { Button } from "@calcom/ui/components/button";
|
||||
import { Dialog } from "@calcom/ui/components/dialog";
|
||||
import { DialogContent, DialogHeader, DialogFooter as BaseDialogFooter } from "@calcom/ui/components/dialog";
|
||||
import { Label } from "@calcom/ui/components/form";
|
||||
import { showToast } from "@calcom/ui/components/toast";
|
||||
|
||||
interface BuyNumberDialogProps {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
agentId?: string | null;
|
||||
workflowId?: string;
|
||||
teamId?: number;
|
||||
}
|
||||
|
||||
export function BuyNumberDialog({ open, onOpenChange, agentId, workflowId, teamId }: BuyNumberDialogProps) {
|
||||
const { t } = useLocale();
|
||||
const utils = trpc.useUtils();
|
||||
|
||||
const buyNumberMutation = trpc.viewer.phoneNumber.buy.useMutation({
|
||||
onSuccess: async (data: { checkoutUrl?: string; message?: string; phoneNumber?: unknown }) => {
|
||||
if (data.checkoutUrl) {
|
||||
window.location.href = data.checkoutUrl;
|
||||
} else if (data.phoneNumber) {
|
||||
showToast(t("phone_number_purchased_successfully"), "success");
|
||||
posthog.capture("calai_phone_number_purchased");
|
||||
await utils.viewer.me.get.invalidate();
|
||||
onOpenChange(false);
|
||||
if (agentId) {
|
||||
utils.viewer.aiVoiceAgent.get.invalidate({ id: agentId });
|
||||
}
|
||||
} else {
|
||||
showToast(data.message || t("something_went_wrong"), "error");
|
||||
}
|
||||
},
|
||||
onError: (error: { message: string }) => {
|
||||
showToast(error.message, "error");
|
||||
},
|
||||
});
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent type="creation">
|
||||
<DialogHeader
|
||||
title={t("buy_a_new_number")}
|
||||
subtitle={t("buy_number_for_x_per_month", {
|
||||
priceInDollars: CAL_AI_PHONE_NUMBER_MONTHLY_PRICE,
|
||||
})}
|
||||
/>
|
||||
<div className="flex flex-col">
|
||||
<div>
|
||||
<div>
|
||||
<Alert
|
||||
className="mb-4"
|
||||
severity="info"
|
||||
message={t("only_us_phone_numbers_can_be_purchased_here")}
|
||||
/>
|
||||
<Label>{t("supported_call_destinations")}</Label>
|
||||
<div className="-mb-4 grid grid-cols-2 gap-x-8 gap-y-1 text-sm">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-xl">🇺🇸</span>
|
||||
<span className="text-default">United States</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-xl">🇮🇳</span>
|
||||
<span className="text-default">India</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-xl">🇦🇺</span>
|
||||
<span className="text-default">Australia</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-xl">🇩🇪</span>
|
||||
<span className="text-default">Germany</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-xl">🇪🇸</span>
|
||||
<span className="text-default">Spain</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-xl">🇬🇧</span>
|
||||
<span className="text-default">United Kingdom</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-xl">🇲🇽</span>
|
||||
<span className="text-default">Mexico</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-xl">🇫🇷</span>
|
||||
<span className="text-default">France</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-xl">🇯🇵</span>
|
||||
<span className="text-default">Japan</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-xl">🇨🇦</span>
|
||||
<span className="text-default">Canada</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-xl">🇮🇹</span>
|
||||
<span className="text-default">Italy</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<BaseDialogFooter showDivider className="relative">
|
||||
<Button onClick={() => onOpenChange(false)} color="secondary">
|
||||
{t("close")}
|
||||
</Button>
|
||||
<Button
|
||||
StartIcon="external-link"
|
||||
onClick={() => {
|
||||
if (!agentId || !workflowId) {
|
||||
return;
|
||||
}
|
||||
posthog.capture("calai_buy_number_button_clicked", { agentId, workflowId, teamId });
|
||||
buyNumberMutation.mutate({
|
||||
agentId: agentId,
|
||||
workflowId: workflowId,
|
||||
teamId: teamId ?? undefined,
|
||||
});
|
||||
}}
|
||||
loading={buyNumberMutation.isPending}
|
||||
disabled={buyNumberMutation.isPending}>
|
||||
{t("buy_us_number_button", { priceInDollars: CAL_AI_PHONE_NUMBER_MONTHLY_PRICE })}
|
||||
</Button>
|
||||
</BaseDialogFooter>
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
-93
@@ -1,93 +0,0 @@
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
import { ConfirmationDialogContent } from "@calcom/ui/components/dialog";
|
||||
import { Dialog as UIDialog } from "@calcom/ui/components/dialog";
|
||||
import { showToast } from "@calcom/ui/components/toast";
|
||||
|
||||
interface ConfirmationDialogsProps {
|
||||
cancellingNumberId: number | null;
|
||||
setCancellingNumberId: (id: number | null) => void;
|
||||
numberToDelete: string | null;
|
||||
setNumberToDelete: (number: string | null) => void;
|
||||
agentId?: string | null;
|
||||
}
|
||||
|
||||
export function ConfirmationDialogs({
|
||||
cancellingNumberId,
|
||||
setCancellingNumberId,
|
||||
numberToDelete,
|
||||
setNumberToDelete,
|
||||
agentId,
|
||||
}: ConfirmationDialogsProps) {
|
||||
const { t } = useLocale();
|
||||
const utils = trpc.useUtils();
|
||||
|
||||
const cancelSubscriptionMutation = trpc.viewer.phoneNumber.cancel.useMutation({
|
||||
onSuccess: async (data: { message?: string }) => {
|
||||
showToast(data.message || t("phone_number_subscription_cancelled_successfully"), "success");
|
||||
setCancellingNumberId(null);
|
||||
|
||||
await utils.viewer.me.get.invalidate();
|
||||
if (agentId) {
|
||||
await utils.viewer.aiVoiceAgent.get.invalidate({ id: agentId });
|
||||
}
|
||||
},
|
||||
onError: (error: { message: string }) => {
|
||||
showToast(error.message, "error");
|
||||
setCancellingNumberId(null);
|
||||
},
|
||||
});
|
||||
|
||||
const deletePhoneNumberMutation = trpc.viewer.phoneNumber.delete.useMutation({
|
||||
onSuccess: async () => {
|
||||
showToast(t("phone_number_deleted_successfully"), "success");
|
||||
setNumberToDelete(null);
|
||||
|
||||
if (agentId) {
|
||||
await utils.viewer.aiVoiceAgent.get.invalidate({ id: agentId });
|
||||
}
|
||||
},
|
||||
onError: (error: { message: string }) => {
|
||||
showToast(error.message, "error");
|
||||
setNumberToDelete(null);
|
||||
},
|
||||
});
|
||||
|
||||
const confirmCancelSubscription = () => {
|
||||
if (cancellingNumberId) {
|
||||
cancelSubscriptionMutation.mutate({ phoneNumberId: cancellingNumberId });
|
||||
}
|
||||
};
|
||||
|
||||
const confirmDeletePhoneNumber = () => {
|
||||
if (numberToDelete) {
|
||||
deletePhoneNumberMutation.mutate({ phoneNumber: numberToDelete });
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<UIDialog open={cancellingNumberId !== null} onOpenChange={() => setCancellingNumberId(null)}>
|
||||
<ConfirmationDialogContent
|
||||
isPending={cancelSubscriptionMutation.isPending}
|
||||
variety="danger"
|
||||
title={t("cancel_phone_number_subscription")}
|
||||
confirmBtnText={t("yes_cancel_subscription")}
|
||||
onConfirm={confirmCancelSubscription}>
|
||||
{t("cancel_phone_number_subscription_confirmation")}
|
||||
</ConfirmationDialogContent>
|
||||
</UIDialog>
|
||||
|
||||
<UIDialog open={numberToDelete !== null} onOpenChange={() => setNumberToDelete(null)}>
|
||||
<ConfirmationDialogContent
|
||||
isPending={deletePhoneNumberMutation.isPending}
|
||||
variety="danger"
|
||||
title={t("delete_phone_number")}
|
||||
confirmBtnText={t("yes_delete_phone_number")}
|
||||
onConfirm={confirmDeletePhoneNumber}>
|
||||
{t("delete_phone_number_confirmation")}
|
||||
</ConfirmationDialogContent>
|
||||
</UIDialog>
|
||||
</>
|
||||
);
|
||||
}
|
||||
Loaded 100 of 374 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user