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
@@ -0,0 +1,42 @@
|
||||
The Cal.com Commercial License (the “Commercial License”)
|
||||
Copyright (c) 2020-present Cal.com, Inc
|
||||
|
||||
With regard to the Cal.com Software:
|
||||
|
||||
This software and associated documentation files (the "Software") may only be
|
||||
used in production, if you (and any entity that you represent) have agreed to,
|
||||
and are in compliance with, the Cal.com Subscription Terms available
|
||||
at https://cal.com/terms, or other agreements governing
|
||||
the use of the Software, as mutually agreed by you and Cal.com, Inc ("Cal.com"),
|
||||
and otherwise have a valid Cal.com Enterprise Edition subscription ("Commercial Subscription")
|
||||
for the correct number of hosts as defined in the "Commercial Terms ("Hosts"). Subject to the foregoing sentence,
|
||||
you are free to modify this Software and publish patches to the Software. You agree
|
||||
that Cal.com and/or its licensors (as applicable) retain all right, title and interest in
|
||||
and to all such modifications and/or patches, and all such modifications and/or
|
||||
patches may only be used, copied, modified, displayed, distributed, or otherwise
|
||||
exploited with a valid Commercial Subscription for the correct number of hosts.
|
||||
Notwithstanding the foregoing, you may copy and modify the Software for development
|
||||
and testing purposes, without requiring a subscription. You agree that Cal.com and/or
|
||||
its licensors (as applicable) retain all right, title and interest in and to all such
|
||||
modifications. You are not granted any other rights beyond what is expressly stated herein.
|
||||
Subject to the foregoing, it is forbidden to copy, merge, publish, distribute, sublicense,
|
||||
and/or sell the Software.
|
||||
|
||||
This Commercial License applies only to the part of this Software that is not distributed under
|
||||
the AGPLv3 license. Any part of this Software distributed under the MIT license or which
|
||||
is served client-side as an image, font, cascading stylesheet (CSS), file which produces
|
||||
or is compiled, arranged, augmented, or combined into client-side JavaScript, in whole or
|
||||
in part, is copyrighted under the AGPLv3 license. The full text of this Commercial License shall
|
||||
be included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
|
||||
For all third party components incorporated into the Cal.com Software, those
|
||||
components are licensed under the original license provided by the owner of the
|
||||
applicable component.
|
||||
@@ -0,0 +1,59 @@
|
||||
"use client";
|
||||
|
||||
import LicenseRequired from "@calcom/features/ee/common/components/LicenseRequired";
|
||||
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";
|
||||
|
||||
import { UpgradeTip } from "~/shell/UpgradeTip";
|
||||
|
||||
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;
|
||||
@@ -0,0 +1,84 @@
|
||||
"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;
|
||||
@@ -0,0 +1,273 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
|
||||
import { Dialog } from "@calcom/features/components/controlled-dialog";
|
||||
import { subdomainSuffix } from "@calcom/features/ee/organizations/lib/orgDomains";
|
||||
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";
|
||||
|
||||
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="stack-y-2 ml-4 mt-5 list-disc">
|
||||
<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,
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,446 @@
|
||||
"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="stack-y-4 flex flex-col items-center justify-center 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;
|
||||
@@ -0,0 +1,223 @@
|
||||
"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;
|
||||
@@ -0,0 +1,489 @@
|
||||
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>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
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>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
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>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
|
||||
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({});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,205 @@
|
||||
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: () => ({
|
||||
t: (key: string) => key,
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock("@calcom/lib/hooks/useCompatSearchParams", () => ({
|
||||
useCompatSearchParams: () => new URLSearchParams(),
|
||||
}));
|
||||
|
||||
vi.mock("next/navigation", async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import("next/navigation")>();
|
||||
return {
|
||||
...actual,
|
||||
useRouter: () => ({
|
||||
push: vi.fn(),
|
||||
}),
|
||||
usePathname: () => "/settings/organizations/attributes",
|
||||
};
|
||||
});
|
||||
|
||||
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"]);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,90 @@
|
||||
"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;
|
||||
@@ -0,0 +1,112 @@
|
||||
"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;
|
||||
@@ -0,0 +1,213 @@
|
||||
"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;
|
||||
@@ -0,0 +1,541 @@
|
||||
"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 />;
|
||||
}
|
||||
@@ -0,0 +1,238 @@
|
||||
"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 { DisableAutofillOnBookingPageSwitch } from "@calcom/features/ee/organizations/pages/components/DisableAutofillOnBookingPageSwitch";
|
||||
import { DisablePhoneOnlySMSNotificationsSwitch } from "@calcom/features/ee/organizations/pages/components/DisablePhoneOnlySMSNotificationsSwitch";
|
||||
import { LockEventTypeSwitch } from "@calcom/features/ee/organizations/pages/components/LockEventTypeSwitch";
|
||||
import { NoSlotsNotificationSwitch } from "@calcom/features/ee/organizations/pages/components/NoSlotsNotificationSwitch";
|
||||
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";
|
||||
|
||||
const SkeletonLoader = () => {
|
||||
return (
|
||||
<SkeletonContainer>
|
||||
<div className="stack-y-6 mb-8 mt-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;
|
||||
@@ -0,0 +1,65 @@
|
||||
"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 "@calcom/features/ee/organizations/pages/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;
|
||||
@@ -0,0 +1,264 @@
|
||||
"use client";
|
||||
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useState } from "react";
|
||||
import { Controller, useFieldArray, useForm } from "react-hook-form";
|
||||
import { z } from "zod";
|
||||
|
||||
import { useOnboarding } from "@calcom/features/ee/organizations/lib/onboardingStore";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import slugify from "@calcom/lib/slugify";
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
import classNames from "@calcom/ui/classNames";
|
||||
import { Button } from "@calcom/ui/components/button";
|
||||
import { CheckboxField } from "@calcom/ui/components/form";
|
||||
import { Form } from "@calcom/ui/components/form";
|
||||
import { TextField } from "@calcom/ui/components/form";
|
||||
import { Icon } from "@calcom/ui/components/icon";
|
||||
import { SkeletonText, SkeletonContainer, SkeletonButton } from "@calcom/ui/components/skeleton";
|
||||
|
||||
const schema = z.object({
|
||||
teams: z.array(
|
||||
z.object({
|
||||
name: z.string().trim(),
|
||||
})
|
||||
),
|
||||
moveTeams: z.array(
|
||||
z.object({
|
||||
id: z.number(),
|
||||
shouldMove: z.boolean(),
|
||||
newSlug: z.string().optional(),
|
||||
})
|
||||
),
|
||||
});
|
||||
|
||||
export const AddNewTeamsForm = () => {
|
||||
const { data: teams, isLoading } = trpc.viewer.teams.listOwnedTeams.useQuery();
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<SkeletonContainer as="div" className="stack-y-6">
|
||||
<div className="stack-y-4">
|
||||
<SkeletonText className="h-4 w-32" />
|
||||
<div className="stack-y-2">
|
||||
{[...Array(2)].map((_, i) => (
|
||||
<div key={i} className="flex items-center space-x-2">
|
||||
<SkeletonText className="h-5 w-5" />
|
||||
<SkeletonText className="h-8 w-full" />
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<div className="stack-y-4">
|
||||
<SkeletonText className="h-4 w-32" />
|
||||
<div className="stack-y-2">
|
||||
{[...Array(3)].map((_, i) => (
|
||||
<SkeletonText key={i} className="h-10 w-full" />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<SkeletonButton className="w-full" />
|
||||
</SkeletonContainer>
|
||||
);
|
||||
}
|
||||
|
||||
return <AddNewTeamsFormChild teams={(teams ?? []).map(({ id, name, slug }) => ({ id, name, slug }))} />;
|
||||
};
|
||||
|
||||
const AddNewTeamsFormChild = ({ teams }: { teams: { id: number; name: string; slug: string | null }[] }) => {
|
||||
const { t } = useLocale();
|
||||
const router = useRouter();
|
||||
const [counter, setCounter] = useState(1);
|
||||
const { useOnboardingStore } = useOnboarding();
|
||||
const { slug: orgSlug, setTeams, teams: teamsFromStore } = useOnboardingStore();
|
||||
const teamsToCreateFromStore = teamsFromStore.filter((team) => !team.isBeingMigrated);
|
||||
const teamsToMigrateFromStore = teamsFromStore.filter((team) => team.isBeingMigrated);
|
||||
const form = useForm({
|
||||
defaultValues: {
|
||||
teams: teamsToCreateFromStore.length ? teamsToCreateFromStore : [{ name: "" }],
|
||||
moveTeams: teams.map((team) => {
|
||||
const teamToMigrateInStore = teamsToMigrateFromStore.find((t) => t.id === team.id);
|
||||
const slugConflictsWithOrg = team.slug === orgSlug;
|
||||
return {
|
||||
id: team.id,
|
||||
// The team with conflicting slug must be moved
|
||||
shouldMove: slugConflictsWithOrg || !!teamToMigrateInStore,
|
||||
newSlug: teamToMigrateInStore?.slug || getSuggestedSlug({ teamSlug: team.slug, orgSlug }),
|
||||
name: team.name,
|
||||
};
|
||||
}),
|
||||
}, // Set initial values
|
||||
resolver: async (data) => {
|
||||
try {
|
||||
const validatedData = await schema.parseAsync(data);
|
||||
return { values: validatedData, errors: {} };
|
||||
} catch (error) {
|
||||
if (error instanceof z.ZodError) {
|
||||
return {
|
||||
values: {
|
||||
teams: [],
|
||||
},
|
||||
errors: error.formErrors.fieldErrors,
|
||||
};
|
||||
}
|
||||
return { values: {}, errors: { teams: { message: "Error validating input" } } };
|
||||
}
|
||||
},
|
||||
});
|
||||
const { register, control, watch, getValues, setValue } = form;
|
||||
const { fields, append, remove } = useFieldArray({
|
||||
control,
|
||||
name: "teams",
|
||||
});
|
||||
|
||||
const handleCounterIncrease = () => {
|
||||
if (counter >= 0 && counter < 5) {
|
||||
setCounter((prevCounter) => prevCounter + 1);
|
||||
append({ name: "" });
|
||||
}
|
||||
};
|
||||
|
||||
const handleRemoveInput = (index: number) => {
|
||||
remove(index);
|
||||
setCounter((prevCounter) => prevCounter - 1);
|
||||
};
|
||||
|
||||
const handleFormSubmit = () => {
|
||||
const fields = getValues("teams");
|
||||
const moveTeams = getValues("moveTeams");
|
||||
|
||||
const teamsBeingMoved = moveTeams.map((team) => {
|
||||
return {
|
||||
id: team.id,
|
||||
isBeingMigrated: team.shouldMove,
|
||||
slug: team.newSlug,
|
||||
name: team.name,
|
||||
};
|
||||
});
|
||||
|
||||
const newTeams = fields
|
||||
.map((team) => {
|
||||
return {
|
||||
id: -1,
|
||||
isBeingMigrated: false,
|
||||
slug: getSuggestedSlug({ teamSlug: team.name, orgSlug }),
|
||||
name: team.name,
|
||||
};
|
||||
})
|
||||
.filter((team) => team.slug !== "");
|
||||
|
||||
setTeams([...teamsBeingMoved, ...newTeams]);
|
||||
router.push(`/settings/organizations/new/onboard-members`);
|
||||
};
|
||||
|
||||
const moveTeams = watch("moveTeams");
|
||||
return (
|
||||
<>
|
||||
<Form form={form} handleSubmit={handleFormSubmit}>
|
||||
{moveTeams.length ? (
|
||||
<>
|
||||
<label className="text-emphasis mb-2 block text-sm font-medium leading-none">
|
||||
Move existing teams
|
||||
</label>
|
||||
<ul className="mb-8 stack-y-4">
|
||||
{moveTeams.map((team, index) => {
|
||||
const currentTeam = teams.find((t) => t.id === team.id);
|
||||
// If the team slug conflicts with the org slug, this team must be moved
|
||||
const slugConflictsWithOrg = currentTeam?.slug === orgSlug;
|
||||
return (
|
||||
<li key={team.id}>
|
||||
<Controller
|
||||
name={`moveTeams.${index}.shouldMove`}
|
||||
render={({ field: { value, onChange } }) => (
|
||||
<CheckboxField
|
||||
defaultValue={value}
|
||||
checked={value || slugConflictsWithOrg}
|
||||
onChange={onChange}
|
||||
description={currentTeam?.name ?? ""}
|
||||
// Must not allow toggling off if the slug conflicts with the org slug
|
||||
disabled={slugConflictsWithOrg}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
{moveTeams[index].shouldMove ? (
|
||||
<TextField
|
||||
placeholder="New Slug"
|
||||
defaultValue={teams.find((t) => t.id === team.id)?.slug ?? ""}
|
||||
{...register(`moveTeams.${index}.newSlug`)}
|
||||
onChange={(e) => {
|
||||
const slug = slugify(e.target.value, true);
|
||||
setValue(`moveTeams.${index}.newSlug`, slug);
|
||||
}}
|
||||
className="mt-2"
|
||||
label=""
|
||||
/>
|
||||
) : null}
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
</>
|
||||
) : null}
|
||||
<label className="text-emphasis mb-2 block text-sm font-medium leading-none">Add New Teams</label>
|
||||
{fields.map((field, index) => (
|
||||
<div className={classNames("relative", index > 0 ? "mb-2" : "")} key={field.id}>
|
||||
<TextField
|
||||
key={field.id}
|
||||
{...register(`teams.${index}.name`)}
|
||||
data-testid={`team.${index}.name`}
|
||||
label=""
|
||||
addOnClassname="bg-transparent p-0 border-l-0"
|
||||
className={index > 0 ? "mb-2" : ""}
|
||||
placeholder={t(`org_team_names_example_${index + 1}`)}
|
||||
addOnSuffix={
|
||||
index > 0 && (
|
||||
<Button
|
||||
color="minimal"
|
||||
className="group/remove mx-2 px-0 hover:bg-transparent"
|
||||
onClick={() => handleRemoveInput(index)}
|
||||
aria-label="Remove Team">
|
||||
<Icon
|
||||
name="x"
|
||||
className="bg-subtle text group-hover/remove:text-inverted group-hover/remove:bg-inverted h-5 w-5 rounded-full p-1"
|
||||
/>
|
||||
</Button>
|
||||
)
|
||||
}
|
||||
minLength={2}
|
||||
maxLength={63}
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
{counter === 5 && <p className="text-subtle my-2 text-sm">{t("org_max_team_warnings")}</p>}
|
||||
{counter < 5 && (
|
||||
<Button
|
||||
StartIcon="plus"
|
||||
color="secondary"
|
||||
onClick={handleCounterIncrease}
|
||||
aria-label={t("add_a_team")}
|
||||
className="my-1"
|
||||
data-testId="add_a_team">
|
||||
{t("add_a_team")}
|
||||
</Button>
|
||||
)}
|
||||
<Button
|
||||
EndIcon="arrow-right"
|
||||
type="submit"
|
||||
color="primary"
|
||||
className="mt-6 w-full justify-center"
|
||||
data-testId="continue_or_checkout">
|
||||
{t("continue")}
|
||||
</Button>
|
||||
</Form>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
const getSuggestedSlug = ({ teamSlug, orgSlug }: { teamSlug: string | null; orgSlug: string | null }) => {
|
||||
// If there is no orgSlug, we can't suggest a slug
|
||||
if (!teamSlug || !orgSlug) {
|
||||
return teamSlug;
|
||||
}
|
||||
|
||||
return teamSlug.replace(`${orgSlug}-`, "").replace(`-${orgSlug}`, "");
|
||||
};
|
||||
@@ -0,0 +1,248 @@
|
||||
"use client";
|
||||
|
||||
import { useSession } from "next-auth/react";
|
||||
import { useState } from "react";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { z } from "zod";
|
||||
|
||||
import { setShowNewOrgModalFlag } from "@calcom/features/ee/organizations/hooks/useWelcomeModal";
|
||||
import { useOnboarding } from "@calcom/features/ee/organizations/lib/onboardingStore";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import type { RouterOutputs } from "@calcom/trpc/react";
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
import { Alert } from "@calcom/ui/components/alert";
|
||||
import { Avatar } from "@calcom/ui/components/avatar";
|
||||
import { Badge } from "@calcom/ui/components/badge";
|
||||
import { Button } from "@calcom/ui/components/button";
|
||||
import { TextField } from "@calcom/ui/components/form";
|
||||
import { SkeletonButton, SkeletonContainer, SkeletonText } from "@calcom/ui/components/skeleton";
|
||||
import { showToast } from "@calcom/ui/components/toast";
|
||||
import { Tooltip } from "@calcom/ui/components/tooltip";
|
||||
|
||||
type TeamMember = RouterOutputs["viewer"]["teams"]["listMembers"]["members"][number];
|
||||
|
||||
const AddNewTeamMembers = () => {
|
||||
const session = useSession();
|
||||
|
||||
if (session.status === "loading") {
|
||||
return <SkeletonContainer>Loading...</SkeletonContainer>;
|
||||
}
|
||||
return <AddNewTeamMembersForm />;
|
||||
};
|
||||
|
||||
const useOrgCreation = () => {
|
||||
const { t } = useLocale();
|
||||
const session = useSession();
|
||||
const utils = trpc.useUtils();
|
||||
const [serverErrorMessage, setServerErrorMessage] = useState("");
|
||||
const { useOnboardingStore } = useOnboarding();
|
||||
const { reset } = useOnboardingStore();
|
||||
|
||||
// Single mutation for all flows (billing, self-hosted, admin)
|
||||
const intentToCreateOrgMutation = trpc.viewer.organizations.intentToCreateOrg.useMutation({
|
||||
onSuccess: async (data) => {
|
||||
reset({
|
||||
onboardingId: data.organizationOnboardingId,
|
||||
});
|
||||
|
||||
if (data.checkoutUrl) {
|
||||
// Billing enabled - redirect to Stripe
|
||||
window.location.href = data.checkoutUrl;
|
||||
} else if (data.organizationId) {
|
||||
// Self-hosted - org already created, redirect to organizations
|
||||
await utils.viewer.organizations.listCurrent.invalidate();
|
||||
await session.update();
|
||||
reset();
|
||||
// Set flag to show welcome modal (using both query param and sessionStorage for reliability)
|
||||
setShowNewOrgModalFlag();
|
||||
window.location.href = `${window.location.origin}/settings/organizations/profile?newOrganizationModal=true`;
|
||||
} else {
|
||||
// Unexpected state
|
||||
setServerErrorMessage("Unexpected response from server");
|
||||
}
|
||||
},
|
||||
onError: (error) => {
|
||||
setServerErrorMessage(t(error.message));
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
mutation: intentToCreateOrgMutation,
|
||||
mutate: intentToCreateOrgMutation.mutate,
|
||||
isPending: intentToCreateOrgMutation.isPending,
|
||||
errorMessage: serverErrorMessage,
|
||||
};
|
||||
};
|
||||
|
||||
export const AddNewTeamMembersForm = () => {
|
||||
const { t } = useLocale();
|
||||
const { useOnboardingStore, isBillingEnabled } = useOnboarding();
|
||||
const {
|
||||
addInvitedMember,
|
||||
removeInvitedMember,
|
||||
orgOwnerEmail,
|
||||
teams,
|
||||
invitedMembers,
|
||||
logo,
|
||||
bio,
|
||||
name,
|
||||
slug,
|
||||
billingPeriod,
|
||||
seats,
|
||||
pricePerSeat,
|
||||
brandColor,
|
||||
bannerUrl,
|
||||
} = useOnboardingStore();
|
||||
const orgCreation = useOrgCreation();
|
||||
|
||||
const teamIds = teams.filter((team) => team.isBeingMigrated && team.id > 0).map((team) => team.id);
|
||||
|
||||
const results = trpc.useQueries((t) => teamIds.map((teamId) => t.viewer.teams.listMembers({ teamId })));
|
||||
|
||||
const isLoading = results.some((result) => result.isLoading);
|
||||
|
||||
// Combine all members and remove duplicates
|
||||
const uniqueMembers = results
|
||||
.reduce<TeamMember[]>((acc, result) => {
|
||||
if (result.data?.members) {
|
||||
return [...acc, ...result.data.members];
|
||||
}
|
||||
return acc;
|
||||
}, [])
|
||||
.filter((member, index, self) => index === self.findIndex((m) => m.email === member.email));
|
||||
|
||||
const { register, handleSubmit, reset } = useForm<{ email: string }>();
|
||||
|
||||
const onSubmit = handleSubmit((data) => {
|
||||
const parsedEmail = z.string().email().safeParse(data.email);
|
||||
if (!parsedEmail.success) {
|
||||
return;
|
||||
}
|
||||
|
||||
const normalizedEmail = parsedEmail.data.toLowerCase();
|
||||
|
||||
// Check if email exists in either invitedMembers or uniqueMembers
|
||||
const isInvited = invitedMembers.some((member) => member.email.toLowerCase() === normalizedEmail);
|
||||
const isExisting = uniqueMembers?.some((member) => member.email.toLowerCase() === normalizedEmail);
|
||||
|
||||
if (isInvited || isExisting) {
|
||||
showToast(t("member_already_invited"), "error");
|
||||
return;
|
||||
}
|
||||
|
||||
addInvitedMember({ email: normalizedEmail });
|
||||
reset();
|
||||
});
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<SkeletonContainer as="div" className="stack-y-6">
|
||||
<SkeletonText className="h-8 w-full" />
|
||||
<SkeletonText className="h-8 w-full" />
|
||||
<SkeletonButton className="mr-6 h-8 w-20 rounded-md p-5" />
|
||||
</SkeletonContainer>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
{orgCreation.errorMessage && (
|
||||
<div className="mb-4">
|
||||
<Alert severity="error" message={orgCreation.errorMessage} />
|
||||
</div>
|
||||
)}
|
||||
<div className="stack-y-6">
|
||||
<div className="flex space-x-3">
|
||||
<form onSubmit={onSubmit} className="flex w-full items-end space-x-2">
|
||||
<div className="grow">
|
||||
<TextField
|
||||
label={t("email")}
|
||||
type="email"
|
||||
{...register("email", { required: true })}
|
||||
placeholder="[email protected]"
|
||||
/>
|
||||
</div>
|
||||
<Button type="submit" StartIcon="plus" color="secondary" data-testid="invite-new-member-button">
|
||||
{t("add")}
|
||||
</Button>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
{(invitedMembers.length > 0 || uniqueMembers?.length > 0) && (
|
||||
<ul
|
||||
className="border-subtle divide-subtle max-h-[300px] divide-y overflow-y-auto rounded-md border"
|
||||
data-testid="pending-member-list">
|
||||
{invitedMembers.map((member) => (
|
||||
<li key={member.email} className="flex items-center justify-between px-5 py-2">
|
||||
<div className="flex items-center space-x-3">
|
||||
<Avatar size="sm" alt={member.email} />
|
||||
<div className="flex gap-1">
|
||||
<Tooltip content={member.email}>
|
||||
<span className="text-subtle max-w-[250px] truncate text-sm">{member.email}</span>
|
||||
</Tooltip>
|
||||
<Badge variant="gray">{t("pending")}</Badge>
|
||||
</div>
|
||||
</div>
|
||||
<Button
|
||||
variant="icon"
|
||||
size="sm"
|
||||
color="minimal"
|
||||
StartIcon="x"
|
||||
onClick={() => removeInvitedMember(member.email)}
|
||||
/>
|
||||
</li>
|
||||
))}
|
||||
{uniqueMembers?.map((member) => (
|
||||
<li key={member.email} className="flex items-center justify-between px-5 py-2">
|
||||
<div className="flex items-center space-x-3">
|
||||
<Avatar size="sm" alt={member.email} imageSrc={member.avatarUrl} />
|
||||
<div className="flex gap-1">
|
||||
<Tooltip content={member.email}>
|
||||
<span className="text-emphasis text-sm font-medium">{member.name || member.email}</span>
|
||||
</Tooltip>
|
||||
{/* TODO: We should show the team name here instead of "migrating from team" */}
|
||||
<Badge variant="green">{t("migrating_from_team")}</Badge>
|
||||
</div>
|
||||
</div>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="mt-3 flex items-center justify-end">
|
||||
<Button
|
||||
data-testid="publish-button"
|
||||
onClick={() => {
|
||||
// Submit ALL data to intentToCreateOrg
|
||||
if (!name || !slug || !orgOwnerEmail) {
|
||||
console.error("Required fields missing", { name, slug, orgOwnerEmail });
|
||||
showToast(t("required_fields_missing"), "error");
|
||||
return;
|
||||
}
|
||||
|
||||
orgCreation.mutate({
|
||||
name,
|
||||
slug,
|
||||
orgOwnerEmail,
|
||||
seats,
|
||||
pricePerSeat,
|
||||
billingPeriod,
|
||||
creationSource: "WEBAPP" as const,
|
||||
logo,
|
||||
bio,
|
||||
brandColor,
|
||||
bannerUrl,
|
||||
teams,
|
||||
invitedMembers,
|
||||
});
|
||||
}}
|
||||
loading={orgCreation.isPending}>
|
||||
{isBillingEnabled ? t("checkout") : t("create")}
|
||||
</Button>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export default AddNewTeamMembers;
|
||||
@@ -0,0 +1,35 @@
|
||||
"use client";
|
||||
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { Alert } from "@calcom/ui/components/alert";
|
||||
import { WizardLayout } from "@calcom/ui/components/layout";
|
||||
|
||||
interface OrganizationWizardLayoutProps {
|
||||
children: React.ReactNode;
|
||||
currentStep: number;
|
||||
maxSteps?: number;
|
||||
isOptionalCallback?: () => void;
|
||||
footer?: React.ReactNode;
|
||||
}
|
||||
|
||||
export function OrganizationWizardLayout({
|
||||
children,
|
||||
currentStep,
|
||||
maxSteps = 5,
|
||||
isOptionalCallback,
|
||||
footer,
|
||||
}: OrganizationWizardLayoutProps) {
|
||||
const { t } = useLocale();
|
||||
|
||||
const defaultFooter = <Alert severity="warning" message={t("organization_trial_workspace_warning")} />;
|
||||
|
||||
return (
|
||||
<WizardLayout
|
||||
currentStep={currentStep}
|
||||
maxSteps={maxSteps}
|
||||
isOptionalCallback={isOptionalCallback}
|
||||
footer={footer ?? defaultFooter}>
|
||||
{children}
|
||||
</WizardLayout>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
"use client";
|
||||
|
||||
import { useRouter, useSearchParams } from "next/navigation";
|
||||
import { useEffect, useState } from "react";
|
||||
|
||||
import { useOnboarding } from "@calcom/features/ee/organizations/lib/onboardingStore";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
import { Button } from "@calcom/ui/components/button";
|
||||
import { Icon } from "@calcom/ui/components/icon";
|
||||
|
||||
const PaymentStatusView = () => {
|
||||
const { t } = useLocale();
|
||||
const router = useRouter();
|
||||
const searchParams = useSearchParams();
|
||||
const paymentStatus = searchParams?.get("paymentStatus");
|
||||
const paymentError = searchParams?.get("error");
|
||||
const { useOnboardingStore } = useOnboarding();
|
||||
const [organizationCreated, setOrganizationCreated] = useState<boolean>(false);
|
||||
const { name } = useOnboardingStore();
|
||||
|
||||
const { data: organization } = trpc.viewer.organizations.listCurrent.useQuery(undefined, {
|
||||
refetchInterval: 2000, // Poll every 2 seconds until org is created
|
||||
enabled: !organizationCreated,
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (organization) {
|
||||
setOrganizationCreated(true);
|
||||
// Organization is created, redirect to next step
|
||||
router.push(`/settings/organizations?newOrganizationModal=true`);
|
||||
}
|
||||
}, [organization, router, useOnboardingStore]);
|
||||
|
||||
if (paymentStatus === "failed" || paymentError) {
|
||||
return (
|
||||
<div className="flex min-h-[500px] flex-col items-center justify-center stack-y-6 px-4 sm:px-6">
|
||||
<div className="flex h-12 w-12 items-center justify-center rounded-full bg-red-100">
|
||||
<Icon name="x" className="h-6 w-6 text-red-600" />
|
||||
</div>
|
||||
<div className="text-center">
|
||||
<h1 className="font-cal text-emphasis text-2xl">{t("payment_failed")}</h1>
|
||||
<p className="text-default mt-2 text-sm">{paymentError || t("payment_failed_description")}</p>
|
||||
</div>
|
||||
<Button color="secondary" href="/settings/organizations/new/onboard-members">
|
||||
{t("try_again")}
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex min-h-[500px] flex-col items-center justify-center stack-y-6 px-4 sm:px-6">
|
||||
<div className="flex h-12 w-12 items-center justify-center rounded-full bg-green-100">
|
||||
<Icon name="check" className="h-6 w-6 text-green-600 dark:text-green-400" />
|
||||
</div>
|
||||
<div className="text-center">
|
||||
<h1 className="font-cal text-emphasis text-2xl">{t("payment_successful")}</h1>
|
||||
<p className="text-default mt-2 text-sm">{t("creating_your_organization", { orgName: name })}</p>
|
||||
<p className="text-subtle mt-1 text-sm">{t("this_may_take_a_few_seconds")}</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default PaymentStatusView;
|
||||
@@ -0,0 +1,11 @@
|
||||
"use client";
|
||||
|
||||
import { AboutOrganizationForm } from "@calcom/features/ee/organizations/components";
|
||||
|
||||
import { OrganizationWizardLayout } from "./_components/OrganizationWizardLayout";
|
||||
|
||||
export const LayoutWrapper = ({ children }: { children: React.ReactNode }) => {
|
||||
return <OrganizationWizardLayout currentStep={2}>{children}</OrganizationWizardLayout>;
|
||||
};
|
||||
|
||||
export default AboutOrganizationForm;
|
||||
@@ -0,0 +1,10 @@
|
||||
"use client";
|
||||
|
||||
import { AddNewTeamsForm } from "./_components/AddNewTeamsForm";
|
||||
import { OrganizationWizardLayout } from "./_components/OrganizationWizardLayout";
|
||||
|
||||
export const LayoutWrapper = ({ children }: { children: React.ReactNode }) => {
|
||||
return <OrganizationWizardLayout currentStep={3}>{children}</OrganizationWizardLayout>;
|
||||
};
|
||||
|
||||
export default AddNewTeamsForm;
|
||||
@@ -0,0 +1,27 @@
|
||||
"use client";
|
||||
|
||||
import { CreateANewOrganizationForm } from "@calcom/features/ee/organizations/components";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { Alert } from "@calcom/ui/components/alert";
|
||||
import { useGetUserAttributes } from "@calcom/web/components/settings/platform/hooks/useGetUserAttributes";
|
||||
|
||||
import { OrganizationWizardLayout } from "./_components/OrganizationWizardLayout";
|
||||
|
||||
export const LayoutWrapper = ({ children }: { children: React.ReactNode }) => {
|
||||
const { t } = useLocale();
|
||||
const { isPlatformUser } = useGetUserAttributes();
|
||||
|
||||
if (isPlatformUser) {
|
||||
return (
|
||||
<div className="flex h-full min-h-screen items-center justify-center">
|
||||
<div className="max-w-lg">
|
||||
<Alert severity="warning" title={t("platform_customer_cant_create_organization")} />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return <OrganizationWizardLayout currentStep={1}>{children}</OrganizationWizardLayout>;
|
||||
};
|
||||
|
||||
export default CreateANewOrganizationForm;
|
||||
@@ -0,0 +1,39 @@
|
||||
graph TD
|
||||
Start[Start] --> AboutOrg[About Organization Form]
|
||||
AboutOrg -->|Set Name, Logo, Bio| Teams[Add Teams]
|
||||
Teams -->|Create/Migrate Teams| Members[Add Team Members]
|
||||
Members -->|Add Members & Invite| Payment[Payment]
|
||||
Payment -->|Create Payment Intent| StripeCheckout[Stripe Checkout]
|
||||
StripeCheckout -->|Success| PaymentSuccess[Payment Success View]
|
||||
StripeCheckout -->|Failure| Payment
|
||||
|
||||
subgraph "About Organization"
|
||||
AboutOrg -->|Store in onboardingStore| OrgData[Organization Data]
|
||||
OrgData -->|"Name, Logo, Bio"| ValidateSlug[Validate Slug]
|
||||
end
|
||||
|
||||
subgraph "Teams Setup"
|
||||
Teams -->|Store in onboardingStore| TeamData[Teams Data]
|
||||
TeamData -->|"Create New/Migrate"| TeamMembers[Team Members]
|
||||
end
|
||||
|
||||
subgraph "Members Setup"
|
||||
Members -->|Store in onboardingStore| MemberData[Members Data]
|
||||
MemberData -->|"Invited/Migrating"| MembersList[Members List]
|
||||
end
|
||||
|
||||
subgraph "Payment Process"
|
||||
Payment -->|Create Intent| PaymentData[Payment Data]
|
||||
PaymentData -->|"Billing Period, Price/Seat"| StripeSession[Stripe Session]
|
||||
end
|
||||
|
||||
subgraph "Webhook Handling"
|
||||
StripeCheckout -->|invoice.paid| WebhookHandler[Webhook Handler]
|
||||
WebhookHandler -->|Process Payment| OrgCreation[Create Organization]
|
||||
OrgCreation --> Complete[Complete]
|
||||
end
|
||||
|
||||
style Start fill:#f9f,stroke:#333,stroke-width:2px
|
||||
style Complete fill:#9f9,stroke:#333,stroke-width:2px
|
||||
style StripeCheckout fill:#fdd,stroke:#333,stroke-width:2px
|
||||
style WebhookHandler fill:#ddf,stroke:#333,stroke-width:2px
|
||||
@@ -0,0 +1,10 @@
|
||||
"use client";
|
||||
|
||||
import AddNewTeamMembers from "./_components/OnboardMembersView";
|
||||
import { OrganizationWizardLayout } from "./_components/OrganizationWizardLayout";
|
||||
|
||||
export const LayoutWrapper = ({ children }: { children: React.ReactNode }) => {
|
||||
return <OrganizationWizardLayout currentStep={4}>{children}</OrganizationWizardLayout>;
|
||||
};
|
||||
|
||||
export default AddNewTeamMembers;
|
||||
@@ -0,0 +1,14 @@
|
||||
"use client";
|
||||
|
||||
import { AdminOnboardingHandover } from "@calcom/features/ee/organizations/components";
|
||||
import { WizardLayout } from "@calcom/ui/components/layout";
|
||||
|
||||
export const LayoutWrapper = ({ children }: { children: React.ReactNode }) => {
|
||||
return (
|
||||
<WizardLayout currentStep={2} maxSteps={2}>
|
||||
{children}
|
||||
</WizardLayout>
|
||||
);
|
||||
};
|
||||
|
||||
export default AdminOnboardingHandover;
|
||||
@@ -0,0 +1,11 @@
|
||||
"use client";
|
||||
|
||||
import PaymentStatusView from "~/ee/organizations/new/_components/PaymentStatusView";
|
||||
|
||||
import { OrganizationWizardLayout } from "./_components/OrganizationWizardLayout";
|
||||
|
||||
export const LayoutWrapper = ({ children }: { children: React.ReactNode }) => {
|
||||
return <OrganizationWizardLayout currentStep={5}>{children}</OrganizationWizardLayout>;
|
||||
};
|
||||
|
||||
export default PaymentStatusView;
|
||||
@@ -0,0 +1,111 @@
|
||||
"use client";
|
||||
|
||||
import { useRouter, useSearchParams } from "next/navigation";
|
||||
import { useEffect } from "react";
|
||||
|
||||
import { useOnboarding } from "@calcom/features/ee/organizations/lib/onboardingStore";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { Alert } from "@calcom/ui/components/alert";
|
||||
import { SkeletonContainer, SkeletonText } from "@calcom/ui/components/skeleton";
|
||||
|
||||
import { OrganizationWizardLayout } from "./_components/OrganizationWizardLayout";
|
||||
|
||||
export const LayoutWrapper = ({ children }: { children: React.ReactNode }) => {
|
||||
return <OrganizationWizardLayout currentStep={1}>{children}</OrganizationWizardLayout>;
|
||||
};
|
||||
|
||||
const ResumeOnboardingView = () => {
|
||||
const { t } = useLocale();
|
||||
const router = useRouter();
|
||||
const searchParams = useSearchParams();
|
||||
const onboardingIdParam = searchParams?.get("onboardingId");
|
||||
|
||||
const { dbOnboarding, isLoadingOrgOnboarding, useOnboardingStore } = useOnboarding();
|
||||
const { reset } = useOnboardingStore();
|
||||
|
||||
useEffect(() => {
|
||||
if (isLoadingOrgOnboarding) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!onboardingIdParam) {
|
||||
router.push("/settings/organizations/new");
|
||||
return;
|
||||
}
|
||||
|
||||
if (!dbOnboarding) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (dbOnboarding.isComplete) {
|
||||
router.push("/settings/organizations");
|
||||
return;
|
||||
}
|
||||
|
||||
// Load onboarding data into store
|
||||
reset({
|
||||
onboardingId: dbOnboarding.id,
|
||||
name: dbOnboarding.name,
|
||||
slug: dbOnboarding.slug,
|
||||
orgOwnerEmail: dbOnboarding.orgOwnerEmail,
|
||||
billingPeriod: dbOnboarding.billingPeriod,
|
||||
seats: dbOnboarding.seats,
|
||||
pricePerSeat: dbOnboarding.pricePerSeat,
|
||||
logo: dbOnboarding.logo,
|
||||
bio: dbOnboarding.bio,
|
||||
brandColor: dbOnboarding.brandColor,
|
||||
bannerUrl: dbOnboarding.bannerUrl,
|
||||
});
|
||||
|
||||
// Redirect to next step (About page)
|
||||
router.push("/settings/organizations/new/about");
|
||||
}, [dbOnboarding, isLoadingOrgOnboarding, onboardingIdParam, reset, router]);
|
||||
|
||||
if (isLoadingOrgOnboarding) {
|
||||
return (
|
||||
<SkeletonContainer className="stack-y-4">
|
||||
<SkeletonText className="h-8 w-full" />
|
||||
<SkeletonText className="h-4 w-3/4" />
|
||||
<SkeletonText className="h-4 w-1/2" />
|
||||
</SkeletonContainer>
|
||||
);
|
||||
}
|
||||
|
||||
if (!onboardingIdParam) {
|
||||
return (
|
||||
<Alert
|
||||
data-testid="error"
|
||||
severity="error"
|
||||
title={t("error")}
|
||||
message={t("no_onboarding_id_provided")}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
if (!dbOnboarding) {
|
||||
return (
|
||||
<Alert data-testid="error" severity="error" title={t("error")} message={t("onboarding_not_found")} />
|
||||
);
|
||||
}
|
||||
|
||||
if (dbOnboarding.isComplete) {
|
||||
return (
|
||||
<Alert
|
||||
data-testid="error"
|
||||
severity="info"
|
||||
title={t("onboarding_already_complete")}
|
||||
message={t("onboarding_already_complete_description")}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
// Loading state while redirecting
|
||||
return (
|
||||
<SkeletonContainer className="stack-y-4">
|
||||
<SkeletonText className="h-8 w-full" />
|
||||
<SkeletonText className="h-4 w-3/4" />
|
||||
</SkeletonContainer>
|
||||
);
|
||||
};
|
||||
|
||||
export default ResumeOnboardingView;
|
||||
@@ -0,0 +1,261 @@
|
||||
"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 { checkAdminOrOwner } from "@calcom/features/auth/lib/checkAdminOrOwner";
|
||||
import MemberListItem from "@calcom/features/ee/organizations/pages/components/MemberListItem";
|
||||
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 "~/ee/teams/components/MakeTeamPrivateSwitch";
|
||||
import MemberInvitationModal from "~/ee/teams/components/MemberInvitationModal";
|
||||
|
||||
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;
|
||||
@@ -0,0 +1,350 @@
|
||||
"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 { subdomainSuffix } from "@calcom/features/ee/organizations/lib/orgDomains";
|
||||
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";
|
||||
|
||||
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"
|
||||
|
||||
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;
|
||||
@@ -0,0 +1,72 @@
|
||||
"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 OrgAutoJoinSetting from "@calcom/features/ee/organizations/pages/components/OrgAutoJoinSetting";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
|
||||
import { BlocklistTable } from "~/ee/organizations/privacy/blocklist-table";
|
||||
import MakeTeamPrivateSwitch from "~/ee/teams/components/MakeTeamPrivateSwitch";
|
||||
|
||||
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;
|
||||
@@ -0,0 +1,72 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
|
||||
import { DataTableToolbar } from "@calcom/features/data-table";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { Button } from "@calcom/ui/components/button";
|
||||
import { ToggleGroup } from "@calcom/ui/components/form";
|
||||
|
||||
import PendingReportsBadge from "./components/PendingReportsBadge";
|
||||
import { BlockedEntriesTable } from "./components/blocked-entries-table";
|
||||
import { CreateBlocklistEntryModal } from "./components/create-blocklist-entry-modal";
|
||||
import { PendingReportsTable } from "./components/pending-reports-table";
|
||||
|
||||
type ViewType = "blocked" | "pending";
|
||||
|
||||
interface BlocklistTableProps {
|
||||
permissions?: {
|
||||
canRead: boolean;
|
||||
canCreate: boolean;
|
||||
canDelete: boolean;
|
||||
};
|
||||
}
|
||||
|
||||
export function BlocklistTable({ permissions }: BlocklistTableProps) {
|
||||
const { t } = useLocale();
|
||||
const [activeView, setActiveView] = useState<ViewType>("blocked");
|
||||
const [showCreateModal, setShowCreateModal] = useState(false);
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="mb-4 flex items-center justify-between">
|
||||
<div className="flex items-center gap-2">
|
||||
<ToggleGroup
|
||||
value={activeView}
|
||||
onValueChange={(value) => {
|
||||
if (value) setActiveView(value as ViewType);
|
||||
}}
|
||||
options={[
|
||||
{ value: "blocked", label: t("blocked") },
|
||||
{
|
||||
value: "pending",
|
||||
label: (
|
||||
<span className="flex items-center">
|
||||
{t("pending")}
|
||||
<PendingReportsBadge />
|
||||
</span>
|
||||
),
|
||||
},
|
||||
]}
|
||||
/>
|
||||
<DataTableToolbar.SearchBar />
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
{permissions?.canCreate && (
|
||||
<Button color="primary" StartIcon="plus" onClick={() => setShowCreateModal(true)}>
|
||||
{t("add")}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{activeView === "blocked" ? (
|
||||
<BlockedEntriesTable permissions={permissions} onAddClick={() => setShowCreateModal(true)} />
|
||||
) : (
|
||||
<PendingReportsTable />
|
||||
)}
|
||||
|
||||
<CreateBlocklistEntryModal isOpen={showCreateModal} onClose={() => setShowCreateModal(false)} />
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
import { Badge } from "@calcom/ui/components/badge";
|
||||
|
||||
export default function PendingReportsBadge() {
|
||||
const { data: pendingReportsCount } = trpc.viewer.organizations.pendingReportsCount.useQuery();
|
||||
if (!pendingReportsCount) return null;
|
||||
return (
|
||||
<Badge rounded variant="orange" className="ml-1">
|
||||
{pendingReportsCount}
|
||||
</Badge>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
import type { ColumnDef } from "@tanstack/react-table";
|
||||
import { useMemo } from "react";
|
||||
|
||||
import type { RouterOutputs } from "@calcom/trpc/react";
|
||||
import { Badge } from "@calcom/ui/components/badge";
|
||||
import { Button } from "@calcom/ui/components/button";
|
||||
import {
|
||||
Dropdown,
|
||||
DropdownItem,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
} from "@calcom/ui/components/dropdown";
|
||||
|
||||
type BlocklistEntry = RouterOutputs["viewer"]["organizations"]["listWatchlistEntries"]["rows"][number];
|
||||
|
||||
interface UseBlockedEntriesColumnsProps {
|
||||
t: (key: string) => string;
|
||||
canDelete?: boolean;
|
||||
onViewDetails: (entry: BlocklistEntry) => void;
|
||||
onDelete: (entry: BlocklistEntry) => void;
|
||||
}
|
||||
|
||||
export function useBlockedEntriesColumns({
|
||||
t,
|
||||
canDelete,
|
||||
onViewDetails,
|
||||
onDelete,
|
||||
}: UseBlockedEntriesColumnsProps) {
|
||||
return useMemo<ColumnDef<BlocklistEntry>[]>(
|
||||
() => [
|
||||
{
|
||||
id: "email_slash_domain",
|
||||
header: t("email_slash_domain"),
|
||||
accessorKey: "value",
|
||||
enableHiding: false,
|
||||
cell: ({ row }) => <span className="text-emphasis">{row.original.value}</span>,
|
||||
},
|
||||
{
|
||||
id: "type",
|
||||
header: t("type"),
|
||||
accessorKey: "type",
|
||||
size: 100,
|
||||
cell: ({ row }) => (
|
||||
<Badge variant="blue">{row.original.type === "EMAIL" ? t("email") : t("domain")}</Badge>
|
||||
),
|
||||
},
|
||||
{
|
||||
id: "createdBy",
|
||||
header: t("blocked_by"),
|
||||
size: 180,
|
||||
cell: ({ row }) => {
|
||||
const audit = row.original.latestAudit as
|
||||
| { changedByUserId: number | null }
|
||||
| {
|
||||
changedByUser?: { id: number; email: string; name: string | null } | undefined;
|
||||
changedByUserId: number | null;
|
||||
}
|
||||
| null;
|
||||
const email =
|
||||
(audit && "changedByUser" in audit ? audit.changedByUser?.email : undefined) ?? undefined;
|
||||
return <span className="text-default">{email ?? "—"}</span>;
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "actions",
|
||||
header: "",
|
||||
size: 90,
|
||||
minSize: 90,
|
||||
maxSize: 90,
|
||||
enableHiding: false,
|
||||
enableSorting: false,
|
||||
enableResizing: false,
|
||||
cell: ({ row }) => {
|
||||
const entry = row.original;
|
||||
return (
|
||||
<div className="flex items-center justify-end">
|
||||
<Dropdown modal={false}>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button type="button" variant="icon" color="secondary" StartIcon="ellipsis" />
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent>
|
||||
<DropdownMenuItem>
|
||||
<DropdownItem type="button" StartIcon="eye" onClick={() => onViewDetails(entry)}>
|
||||
{t("view_details")}
|
||||
</DropdownItem>
|
||||
</DropdownMenuItem>
|
||||
{canDelete && (
|
||||
<DropdownMenuItem>
|
||||
<DropdownItem
|
||||
type="button"
|
||||
color="destructive"
|
||||
StartIcon="trash"
|
||||
onClick={() => onDelete(entry)}>
|
||||
{t("remove_from_blocklist")}
|
||||
</DropdownItem>
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
</DropdownMenuContent>
|
||||
</Dropdown>
|
||||
</div>
|
||||
);
|
||||
},
|
||||
},
|
||||
],
|
||||
[t, canDelete, onViewDetails, onDelete]
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,165 @@
|
||||
"use client";
|
||||
|
||||
import { keepPreviousData } from "@tanstack/react-query";
|
||||
import { getCoreRowModel, getSortedRowModel, useReactTable } from "@tanstack/react-table";
|
||||
import { useMemo, useState } from "react";
|
||||
|
||||
import { DataTableWrapper, useDataTable } from "@calcom/features/data-table";
|
||||
import { IS_CALCOM } 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 { ConfirmationDialogContent, Dialog, DialogClose } from "@calcom/ui/components/dialog";
|
||||
import { EmptyScreen } from "@calcom/ui/components/empty-screen";
|
||||
import { showToast } from "@calcom/ui/components/toast";
|
||||
|
||||
import { useBlockedEntriesColumns } from "./blocked-entries-columns";
|
||||
import { BlocklistEntryDetailsSheet } from "./blocklist-entry-details-sheet";
|
||||
|
||||
type BlocklistEntry = RouterOutputs["viewer"]["organizations"]["listWatchlistEntries"]["rows"][number];
|
||||
|
||||
interface BlockedEntriesTableProps {
|
||||
permissions?: {
|
||||
canRead: boolean;
|
||||
canCreate: boolean;
|
||||
canDelete: boolean;
|
||||
};
|
||||
onAddClick: () => void;
|
||||
}
|
||||
|
||||
export function BlockedEntriesTable({ permissions, onAddClick }: BlockedEntriesTableProps) {
|
||||
const { t } = useLocale();
|
||||
const { limit, offset, searchTerm } = useDataTable();
|
||||
|
||||
const [showDetailsSheet, setShowDetailsSheet] = useState(false);
|
||||
const [selectedEntry, setSelectedEntry] = useState<BlocklistEntry | null>(null);
|
||||
const [entryToDelete, setEntryToDelete] = useState<BlocklistEntry | null>(null);
|
||||
const [showDeleteDialog, setShowDeleteDialog] = useState(false);
|
||||
|
||||
const { data, isPending } = trpc.viewer.organizations.listWatchlistEntries.useQuery(
|
||||
{
|
||||
limit,
|
||||
offset,
|
||||
searchTerm,
|
||||
},
|
||||
{
|
||||
placeholderData: keepPreviousData,
|
||||
}
|
||||
);
|
||||
|
||||
const utils = trpc.useUtils();
|
||||
|
||||
const deleteWatchlistEntry = trpc.viewer.organizations.deleteWatchlistEntry.useMutation({
|
||||
onSuccess: async () => {
|
||||
await utils.viewer.organizations.listWatchlistEntries.invalidate();
|
||||
showToast(t("blocklist_entry_deleted"), "success");
|
||||
setShowDeleteDialog(false);
|
||||
setEntryToDelete(null);
|
||||
},
|
||||
onError: (error) => {
|
||||
showToast(error.message, "error");
|
||||
},
|
||||
});
|
||||
|
||||
const handleViewDetails = (entry: BlocklistEntry) => {
|
||||
setSelectedEntry(entry);
|
||||
setShowDetailsSheet(true);
|
||||
};
|
||||
|
||||
const handleDelete = (entry: BlocklistEntry) => {
|
||||
setEntryToDelete(entry);
|
||||
setShowDeleteDialog(true);
|
||||
};
|
||||
|
||||
const confirmDelete = () => {
|
||||
if (entryToDelete) {
|
||||
deleteWatchlistEntry.mutate({ id: entryToDelete.id });
|
||||
}
|
||||
};
|
||||
|
||||
const columns = useBlockedEntriesColumns({
|
||||
t,
|
||||
canDelete: permissions?.canDelete,
|
||||
onViewDetails: handleViewDetails,
|
||||
onDelete: handleDelete,
|
||||
});
|
||||
|
||||
const totalRowCount = data?.meta?.totalRowCount ?? 0;
|
||||
const flatData = useMemo(() => data?.rows ?? [], [data]);
|
||||
|
||||
const table = useReactTable({
|
||||
data: flatData,
|
||||
columns,
|
||||
getCoreRowModel: getCoreRowModel(),
|
||||
getSortedRowModel: getSortedRowModel(),
|
||||
manualPagination: true,
|
||||
pageCount: Math.ceil(totalRowCount / limit),
|
||||
});
|
||||
|
||||
return (
|
||||
<>
|
||||
<DataTableWrapper
|
||||
table={table}
|
||||
isPending={isPending}
|
||||
variant="default"
|
||||
paginationMode="standard"
|
||||
EmptyView={
|
||||
<EmptyScreen
|
||||
customIcon={<img className="mb-6" src="/slash-icon-cards.svg" />}
|
||||
headline={searchTerm ? t("no_result_found_for", { searchTerm }) : t("pbac_resource_blocklist")}
|
||||
description={t("add_people_to_blocklist")}
|
||||
className="bg-muted mb-16"
|
||||
iconWrapperClassName="bg-default"
|
||||
dashedBorder={false}
|
||||
buttonRaw={
|
||||
<div className="flex gap-2">
|
||||
<Button
|
||||
StartIcon="plus"
|
||||
onClick={onAddClick}
|
||||
color="primary"
|
||||
disabled={!permissions?.canCreate}>
|
||||
{t("add")}
|
||||
</Button>
|
||||
{IS_CALCOM && (
|
||||
<Button
|
||||
StartIcon="book"
|
||||
color="secondary"
|
||||
onClick={() =>
|
||||
window.open("https://cal.com/help/security/blocklist", "_blank", "noopener,noreferrer")
|
||||
}>
|
||||
{t("docs")}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
}
|
||||
/>
|
||||
}
|
||||
totalRowCount={totalRowCount}
|
||||
/>
|
||||
|
||||
<BlocklistEntryDetailsSheet
|
||||
entry={selectedEntry}
|
||||
isOpen={showDetailsSheet}
|
||||
onClose={() => {
|
||||
setShowDetailsSheet(false);
|
||||
setSelectedEntry(null);
|
||||
}}
|
||||
handleDeleteBlocklistEntry={handleDelete}
|
||||
/>
|
||||
|
||||
<Dialog open={showDeleteDialog} onOpenChange={setShowDeleteDialog}>
|
||||
<ConfirmationDialogContent
|
||||
variety="danger"
|
||||
title={t("remove_value_from_blocklist", { value: entryToDelete?.value })}
|
||||
confirmBtn={
|
||||
<DialogClose color="destructive" onClick={confirmDelete}>
|
||||
{t("remove")}
|
||||
</DialogClose>
|
||||
}>
|
||||
{t("remove_value_from_blocklist_description")}
|
||||
</ConfirmationDialogContent>
|
||||
</Dialog>
|
||||
</>
|
||||
);
|
||||
}
|
||||
+157
@@ -0,0 +1,157 @@
|
||||
"use client";
|
||||
|
||||
import { format } from "date-fns";
|
||||
import Link from "next/link";
|
||||
|
||||
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 { Icon } from "@calcom/ui/components/icon";
|
||||
import {
|
||||
Sheet,
|
||||
SheetContent,
|
||||
SheetBody,
|
||||
SheetHeader,
|
||||
SheetTitle,
|
||||
SheetFooter,
|
||||
} from "@calcom/ui/components/sheet";
|
||||
import { SkeletonText } from "@calcom/ui/components/skeleton";
|
||||
|
||||
type BlocklistEntry = RouterOutputs["viewer"]["organizations"]["listWatchlistEntries"]["rows"][number];
|
||||
|
||||
interface BlocklistEntryDetailsSheetProps {
|
||||
entry: BlocklistEntry | null;
|
||||
isOpen: boolean;
|
||||
onClose: () => void;
|
||||
handleDeleteBlocklistEntry: (entry: BlocklistEntry) => void;
|
||||
}
|
||||
|
||||
export function BlocklistEntryDetailsSheet({
|
||||
entry,
|
||||
isOpen,
|
||||
onClose,
|
||||
handleDeleteBlocklistEntry,
|
||||
}: BlocklistEntryDetailsSheetProps) {
|
||||
const { t } = useLocale();
|
||||
|
||||
const { data, isLoading } = trpc.viewer.organizations.getWatchlistEntryDetails.useQuery(
|
||||
{ id: entry?.id ?? "" },
|
||||
{
|
||||
enabled: !!entry?.id && isOpen,
|
||||
}
|
||||
);
|
||||
|
||||
return (
|
||||
<Sheet
|
||||
open={isOpen}
|
||||
onOpenChange={(open) => {
|
||||
if (!open) onClose();
|
||||
}}>
|
||||
<SheetContent className="px-0 pb-0 sm:max-w-xl sm:px-0 sm:pb-0">
|
||||
<SheetHeader className="px-6">
|
||||
<SheetTitle>{entry?.value}</SheetTitle>
|
||||
</SheetHeader>
|
||||
|
||||
<SheetBody className="px-6">
|
||||
{isLoading ? (
|
||||
<div className="mt-3 stack-y-3">
|
||||
<SkeletonText className="h-6 w-32" />
|
||||
<SkeletonText className="h-40 w-full" />
|
||||
</div>
|
||||
) : data?.entry ? (
|
||||
<div className="mt-3 stack-y-6">
|
||||
<div className="bg-subtle rounded-xl p-1">
|
||||
<h2 className="text-default p-5 text-sm font-semibold">{t("details")}</h2>
|
||||
|
||||
<div className="bg-default stack-y-3 rounded-xl p-5">
|
||||
<div>
|
||||
<label className="text-default block text-sm font-semibold">
|
||||
{data.entry.type === "EMAIL" ? t("email") : t("domain")}
|
||||
</label>
|
||||
<p className="text-subtle text-sm">{data.entry.value}</p>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="text-default block text-sm font-semibold">{t("type")}</label>
|
||||
<p className="text-subtle text-sm">
|
||||
{data.entry.type === "EMAIL" ? t("email") : t("domain")}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="text-default block text-sm font-semibold">{t("blocked_by")}</label>
|
||||
<p className="text-subtle text-sm">{data.auditHistory[0]?.changedByUser?.email || "—"}</p>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="text-default block text-sm font-semibold">{t("description")}</label>
|
||||
<p className="text-subtle text-sm">
|
||||
{data.entry.description || t("no_description_provided")}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{data.entry.bookingReports && data.entry.bookingReports.length > 0 && (
|
||||
<div>
|
||||
<label className="text-default block text-sm font-semibold">
|
||||
{t("related_booking")}
|
||||
</label>
|
||||
|
||||
{data.entry.bookingReports.map((report) => {
|
||||
return (
|
||||
<Link key={report.booking.uid} href={`/booking/${report.booking.uid}`}>
|
||||
<div className="text-subtle flex items-center gap-1 text-sm">
|
||||
{report.booking.title}
|
||||
<Icon name="external-link" className="h-4 w-4" />
|
||||
</div>
|
||||
</Link>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="bg-subtle rounded-xl p-1">
|
||||
<h2 className="text-default p-5 text-sm font-semibold">{t("history")}</h2>
|
||||
{data.auditHistory.length > 0 ? (
|
||||
<div className="stack-y-3">
|
||||
{data.auditHistory.map((audit) => (
|
||||
<div key={audit.id} className="bg-default border-subtle rounded-xl border p-4">
|
||||
<div className="flex items-start justify-between">
|
||||
<div>
|
||||
<span className="text-default text-sm font-semibold">
|
||||
{audit.changedByUser?.name || audit.changedByUser?.email || "—"}
|
||||
</span>
|
||||
<span className="text-subtle text-sm"> {t("added")}</span>
|
||||
<div className="text-default mt-1 text-sm font-semibold">{audit.value}</div>
|
||||
</div>
|
||||
<span className="text-subtle text-sm">
|
||||
{format(new Date(audit.changedAt), "MMM d, h:mm a")}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<p className="text-subtle text-sm">{t("no_audit_history")}</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="text-muted mt-8 text-center">{t("blocklist_entry_not_found")}</div>
|
||||
)}
|
||||
</SheetBody>
|
||||
<SheetFooter className="bg-muted px-6 py-5">
|
||||
<Button
|
||||
type="button"
|
||||
color="secondary"
|
||||
onClick={() => entry && handleDeleteBlocklistEntry(entry)}
|
||||
disabled={!entry}>
|
||||
{t("remove_from_blocklist")}
|
||||
</Button>
|
||||
</SheetFooter>
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
);
|
||||
}
|
||||
+208
@@ -0,0 +1,208 @@
|
||||
"use client";
|
||||
|
||||
import Link from "next/link";
|
||||
import { Controller, useForm } from "react-hook-form";
|
||||
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { WatchlistType } 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 { Dialog, DialogContent, DialogFooter, DialogHeader } from "@calcom/ui/components/dialog";
|
||||
import { ToggleGroup } from "@calcom/ui/components/form";
|
||||
import { Icon } from "@calcom/ui/components/icon";
|
||||
import { showToast } from "@calcom/ui/components/toast";
|
||||
|
||||
type BookingReport = RouterOutputs["viewer"]["organizations"]["listBookingReports"]["rows"][number];
|
||||
|
||||
interface BookingReportEntryDetailsModalProps {
|
||||
entry: BookingReport | null;
|
||||
isOpen: boolean;
|
||||
onClose: () => void;
|
||||
}
|
||||
|
||||
interface FormData {
|
||||
blockType: WatchlistType;
|
||||
}
|
||||
|
||||
export function BookingReportEntryDetailsModal({
|
||||
entry,
|
||||
isOpen,
|
||||
onClose,
|
||||
}: BookingReportEntryDetailsModalProps) {
|
||||
const { t } = useLocale();
|
||||
const utils = trpc.useUtils();
|
||||
|
||||
const {
|
||||
control,
|
||||
handleSubmit,
|
||||
reset,
|
||||
formState: { isSubmitting },
|
||||
} = useForm<FormData>({
|
||||
defaultValues: {
|
||||
blockType: WatchlistType.EMAIL,
|
||||
},
|
||||
});
|
||||
|
||||
const addToWatchlist = trpc.viewer.organizations.addToWatchlist.useMutation({
|
||||
onSuccess: async () => {
|
||||
await utils.viewer.organizations.listBookingReports.invalidate();
|
||||
await utils.viewer.organizations.listWatchlistEntries.invalidate();
|
||||
showToast(t("blocklist_entry_created"), "success");
|
||||
onClose();
|
||||
reset();
|
||||
},
|
||||
onError: (error) => {
|
||||
showToast(error.message, "error");
|
||||
},
|
||||
});
|
||||
|
||||
const dismissBookingReport = trpc.viewer.organizations.dismissBookingReport.useMutation({
|
||||
onSuccess: async () => {
|
||||
await utils.viewer.organizations.listBookingReports.invalidate();
|
||||
showToast(t("booking_report_dismissed"), "success");
|
||||
onClose();
|
||||
reset();
|
||||
},
|
||||
onError: (error) => {
|
||||
showToast(error.message, "error");
|
||||
},
|
||||
});
|
||||
|
||||
const onSubmit = (data: FormData) => {
|
||||
if (!entry) return;
|
||||
|
||||
addToWatchlist.mutate({
|
||||
reportIds: [entry.id],
|
||||
type: data.blockType,
|
||||
});
|
||||
};
|
||||
|
||||
const handleDismiss = () => {
|
||||
if (!entry) return;
|
||||
|
||||
dismissBookingReport.mutate({
|
||||
reportId: entry.id,
|
||||
});
|
||||
};
|
||||
|
||||
const handleGoBack = () => {
|
||||
onClose();
|
||||
reset();
|
||||
};
|
||||
|
||||
const reasonMap: Record<string, string> = {
|
||||
SPAM: t("spam"),
|
||||
DONT_KNOW_PERSON: t("dont_know_person"),
|
||||
OTHER: t("other"),
|
||||
};
|
||||
|
||||
if (!entry) return null;
|
||||
|
||||
return (
|
||||
<Dialog open={isOpen} onOpenChange={onClose}>
|
||||
<DialogContent enableOverflow>
|
||||
<DialogHeader title={t("review_report") + ` - ${entry.bookerEmail}`} />
|
||||
<form onSubmit={handleSubmit(onSubmit)}>
|
||||
<div className="stack-y-5">
|
||||
<div className="bg-subtle rounded-xl p-1">
|
||||
<h2 className="text-emphasis px-5 py-4 text-base font-semibold">{t("details")}</h2>
|
||||
<div className="bg-default stack-y-4 rounded-xl p-5">
|
||||
<div>
|
||||
<label className="text-emphasis mb-1 block text-sm font-semibold">{t("email")}</label>
|
||||
<p className="text-subtle text-sm">{entry.bookerEmail}</p>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="text-emphasis mb-1 block text-sm font-semibold">{t("reason")}</label>
|
||||
<p className="text-subtle text-sm">{reasonMap[entry.reason] || entry.reason}</p>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="text-emphasis mb-1 block text-sm font-semibold">{t("reported_by")}</label>
|
||||
<p className="text-subtle text-sm">{entry.reporter?.email || "—"}</p>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="text-emphasis mb-1 block text-sm font-semibold">{t("description")}</label>
|
||||
<p className="text-subtle text-sm">{entry.description || t("no_description_provided")}</p>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="text-emphasis mb-1 block text-sm font-semibold">
|
||||
{t("related_booking")}
|
||||
</label>
|
||||
<Link href={`/booking/${entry.booking.uid}`}>
|
||||
<div className="text-subtle flex items-center gap-1 text-sm">
|
||||
{entry.booking.title}
|
||||
<Icon name="external-link" className="h-4 w-4" />
|
||||
</div>
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<h2 className="text-emphasis mb-2 text-base font-semibold">
|
||||
{t("what_would_you_like_to_block")}
|
||||
</h2>
|
||||
<Controller
|
||||
name="blockType"
|
||||
control={control}
|
||||
render={({ field }) => (
|
||||
<ToggleGroup
|
||||
value={field.value}
|
||||
onValueChange={(value) => {
|
||||
if (value) field.onChange(value);
|
||||
}}
|
||||
options={[
|
||||
{
|
||||
value: WatchlistType.EMAIL,
|
||||
label: t("block_this_email"),
|
||||
iconLeft: <Icon name="mail" className="h-4 w-4" />,
|
||||
},
|
||||
{
|
||||
value: WatchlistType.DOMAIN,
|
||||
label: t("block_all_from_domain"),
|
||||
iconLeft: <Icon name="globe" className="h-4 w-4" />,
|
||||
},
|
||||
]}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<DialogFooter className="mt-6">
|
||||
<div className="flex w-full items-center justify-between">
|
||||
<Button
|
||||
type="button"
|
||||
color="minimal"
|
||||
onClick={handleGoBack}
|
||||
disabled={isSubmitting || addToWatchlist.isPending || dismissBookingReport.isPending}>
|
||||
{t("go_back")}
|
||||
</Button>
|
||||
|
||||
<div className="flex gap-2">
|
||||
<Button
|
||||
type="button"
|
||||
color="secondary"
|
||||
onClick={handleDismiss}
|
||||
loading={dismissBookingReport.isPending}
|
||||
disabled={isSubmitting || addToWatchlist.isPending || dismissBookingReport.isPending}>
|
||||
{t("dont_block")}
|
||||
</Button>
|
||||
<Button
|
||||
type="submit"
|
||||
loading={isSubmitting || addToWatchlist.isPending}
|
||||
disabled={isSubmitting || addToWatchlist.isPending || dismissBookingReport.isPending}>
|
||||
{t("add_to_blocklist")}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
+172
@@ -0,0 +1,172 @@
|
||||
"use client";
|
||||
|
||||
import { Controller, useForm } from "react-hook-form";
|
||||
|
||||
import { domainRegex, emailRegex } from "@calcom/lib/emailSchema";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { WatchlistType } from "@calcom/prisma/enums";
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
import { Button } from "@calcom/ui/components/button";
|
||||
import { Dialog, DialogContent, DialogFooter, DialogHeader } from "@calcom/ui/components/dialog";
|
||||
import { Input, Label, TextArea, ToggleGroup } from "@calcom/ui/components/form";
|
||||
import { Icon } from "@calcom/ui/components/icon";
|
||||
import { showToast } from "@calcom/ui/components/toast";
|
||||
|
||||
interface CreateBlocklistEntryModalProps {
|
||||
isOpen: boolean;
|
||||
onClose: () => void;
|
||||
}
|
||||
|
||||
interface FormData {
|
||||
type: WatchlistType;
|
||||
value: string;
|
||||
description?: string;
|
||||
}
|
||||
|
||||
export function CreateBlocklistEntryModal({ isOpen, onClose }: CreateBlocklistEntryModalProps) {
|
||||
const { t } = useLocale();
|
||||
const utils = trpc.useUtils();
|
||||
|
||||
const {
|
||||
control,
|
||||
handleSubmit,
|
||||
watch,
|
||||
setValue,
|
||||
reset,
|
||||
formState: { errors, isSubmitting },
|
||||
} = useForm<FormData>({
|
||||
defaultValues: {
|
||||
type: WatchlistType.EMAIL,
|
||||
value: "",
|
||||
description: "",
|
||||
},
|
||||
});
|
||||
|
||||
const watchType = watch("type");
|
||||
|
||||
const createWatchlistEntry = trpc.viewer.organizations.createWatchlistEntry.useMutation({
|
||||
onSuccess: async () => {
|
||||
await utils.viewer.organizations.listWatchlistEntries.invalidate();
|
||||
showToast(t("blocklist_entry_created"), "success");
|
||||
onClose();
|
||||
reset();
|
||||
},
|
||||
onError: (error) => {
|
||||
showToast(error.message, "error");
|
||||
},
|
||||
});
|
||||
|
||||
const onSubmit = (data: FormData) => {
|
||||
createWatchlistEntry.mutate({
|
||||
type: data.type,
|
||||
value: data.value,
|
||||
description: data.description,
|
||||
});
|
||||
};
|
||||
|
||||
const validateValue = (value: string) => {
|
||||
if (!value) return t("required");
|
||||
|
||||
if (watchType === WatchlistType.EMAIL) {
|
||||
if (!emailRegex.test(value)) {
|
||||
return t("invalid_email_address");
|
||||
}
|
||||
} else if (watchType === WatchlistType.DOMAIN) {
|
||||
if (!domainRegex.test(value)) {
|
||||
return t("invalid_domain_format");
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
};
|
||||
|
||||
const typeOptions = [
|
||||
{ label: t("email"), value: WatchlistType.EMAIL, iconLeft: <Icon name="mail" className="h-4 w-4" /> },
|
||||
{ label: t("domain"), value: WatchlistType.DOMAIN, iconLeft: <Icon name="globe" className="h-4 w-4" /> },
|
||||
];
|
||||
|
||||
return (
|
||||
<Dialog open={isOpen} onOpenChange={onClose}>
|
||||
<DialogContent enableOverflow>
|
||||
<DialogHeader title={t("add_to_blocklist")} />
|
||||
<form onSubmit={handleSubmit(onSubmit)}>
|
||||
<div className="stack-y-4">
|
||||
<div>
|
||||
<Label htmlFor="type" className="text-emphasis mb-2 block text-sm font-medium">
|
||||
{t("what_would_you_like_to_block")}
|
||||
</Label>
|
||||
<Controller
|
||||
name="type"
|
||||
control={control}
|
||||
rules={{ required: t("field_required") }}
|
||||
render={({ field }) => (
|
||||
<ToggleGroup
|
||||
value={field.value}
|
||||
onValueChange={(value) => {
|
||||
if (value) {
|
||||
field.onChange(value);
|
||||
setValue("value", "");
|
||||
}
|
||||
}}
|
||||
options={typeOptions}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
{errors.type && <p className="text-destructive mt-1 text-sm">{errors.type.message}</p>}
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Label htmlFor="value" className="text-emphasis mb-2 block text-sm font-medium">
|
||||
{watchType === WatchlistType.EMAIL ? t("email") : t("domain_name")}{" "}
|
||||
</Label>
|
||||
<Controller
|
||||
name="value"
|
||||
control={control}
|
||||
rules={{
|
||||
required: t("field_required"),
|
||||
validate: validateValue,
|
||||
}}
|
||||
render={({ field }) => (
|
||||
<Input
|
||||
{...field}
|
||||
placeholder={watchType === WatchlistType.EMAIL ? "[email protected]" : "spammer.com"}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
{errors.value && <p className="text-destructive mt-1 text-sm">{errors.value.message}</p>}
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Label htmlFor="description" className="text-emphasis mb-2 block text-sm font-medium">
|
||||
{t("description")} <span className="text-muted font-normal">{t("optional")}</span>
|
||||
</Label>
|
||||
<Controller
|
||||
name="description"
|
||||
control={control}
|
||||
render={({ field }) => (
|
||||
<TextArea {...field} placeholder={t("reason_for_adding_to_blocklist")} rows={3} />
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<DialogFooter className="mt-6">
|
||||
<Button
|
||||
type="button"
|
||||
color="secondary"
|
||||
onClick={onClose}
|
||||
disabled={isSubmitting || createWatchlistEntry.isPending}>
|
||||
{t("cancel")}
|
||||
</Button>
|
||||
<Button
|
||||
type="submit"
|
||||
loading={isSubmitting || createWatchlistEntry.isPending}
|
||||
disabled={isSubmitting || createWatchlistEntry.isPending}>
|
||||
{t("add_to_blocklist")}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
import type { ColumnDef } from "@tanstack/react-table";
|
||||
import { useMemo } from "react";
|
||||
|
||||
import type { RouterOutputs } from "@calcom/trpc/react";
|
||||
import { Badge } from "@calcom/ui/components/badge";
|
||||
import { Button } from "@calcom/ui/components/button";
|
||||
import {
|
||||
Dropdown,
|
||||
DropdownItem,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
} from "@calcom/ui/components/dropdown";
|
||||
|
||||
type BookingReport = RouterOutputs["viewer"]["organizations"]["listBookingReports"]["rows"][number];
|
||||
|
||||
interface UsePendingReportsColumnsProps {
|
||||
t: (key: string) => string;
|
||||
onViewDetails: (entry: BookingReport) => void;
|
||||
}
|
||||
|
||||
export function usePendingReportsColumns({ t, onViewDetails }: UsePendingReportsColumnsProps) {
|
||||
return useMemo<ColumnDef<BookingReport>[]>(
|
||||
() => [
|
||||
{
|
||||
id: "emailOrDomain",
|
||||
header: t("email_slash_domain"),
|
||||
accessorKey: "bookerEmail",
|
||||
enableHiding: false,
|
||||
size: 250,
|
||||
cell: ({ row }) => {
|
||||
const email = row.original.bookerEmail;
|
||||
return (
|
||||
<div className="flex flex-col">
|
||||
<span className="text-emphasis font-medium">{email}</span>
|
||||
</div>
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "reportedBy",
|
||||
header: t("reported_by"),
|
||||
accessorFn: (row) => row.reporter?.email ?? "-",
|
||||
size: 250,
|
||||
cell: ({ row }) => <span className="text-default">{row.original.reporter?.email ?? "-"}</span>,
|
||||
},
|
||||
{
|
||||
id: "reason",
|
||||
header: t("reason"),
|
||||
size: 150,
|
||||
cell: ({ row }) => {
|
||||
const reason = t(row.original.reason.toLowerCase());
|
||||
const capitalizedReason = reason.charAt(0).toUpperCase() + reason.slice(1);
|
||||
|
||||
return <Badge variant="blue">{capitalizedReason}</Badge>;
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "actions",
|
||||
header: "",
|
||||
size: 90,
|
||||
minSize: 90,
|
||||
maxSize: 90,
|
||||
enableHiding: false,
|
||||
enableSorting: false,
|
||||
enableResizing: false,
|
||||
cell: ({ row }) => {
|
||||
const entry = row.original;
|
||||
return (
|
||||
<div className="flex items-center justify-end">
|
||||
<Dropdown modal={false}>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button type="button" variant="icon" color="secondary" StartIcon="ellipsis" />
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent>
|
||||
<DropdownMenuItem>
|
||||
<DropdownItem type="button" StartIcon="eye" onClick={() => onViewDetails(entry)}>
|
||||
{t("view_details")}
|
||||
</DropdownItem>
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</Dropdown>
|
||||
</div>
|
||||
);
|
||||
},
|
||||
},
|
||||
],
|
||||
[t, onViewDetails]
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
"use client";
|
||||
|
||||
import { keepPreviousData } from "@tanstack/react-query";
|
||||
import { getCoreRowModel, getSortedRowModel, useReactTable } from "@tanstack/react-table";
|
||||
import { useMemo, useState } from "react";
|
||||
|
||||
import { DataTableWrapper, useDataTable } 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 { EmptyScreen } from "@calcom/ui/components/empty-screen";
|
||||
|
||||
import { BookingReportEntryDetailsModal } from "./booking-report-entry-details-modal";
|
||||
import { usePendingReportsColumns } from "./pending-reports-columns";
|
||||
|
||||
type BookingReport = RouterOutputs["viewer"]["organizations"]["listBookingReports"]["rows"][number];
|
||||
|
||||
export function PendingReportsTable() {
|
||||
const { t } = useLocale();
|
||||
const { limit, offset, searchTerm } = useDataTable();
|
||||
|
||||
const [showReviewDialog, setShowReviewDialog] = useState(false);
|
||||
const [selectedReport, setSelectedReport] = useState<BookingReport | null>(null);
|
||||
|
||||
const { data, isPending } = trpc.viewer.organizations.listBookingReports.useQuery(
|
||||
{
|
||||
limit,
|
||||
offset,
|
||||
searchTerm,
|
||||
filters: { hasWatchlist: false, status: ["PENDING"] },
|
||||
},
|
||||
{
|
||||
placeholderData: keepPreviousData,
|
||||
}
|
||||
);
|
||||
|
||||
const handleViewDetails = (entry: BookingReport) => {
|
||||
setSelectedReport(entry);
|
||||
setShowReviewDialog(true);
|
||||
};
|
||||
|
||||
const columns = usePendingReportsColumns({
|
||||
t,
|
||||
onViewDetails: handleViewDetails,
|
||||
});
|
||||
|
||||
const totalRowCount = data?.meta?.totalRowCount ?? 0;
|
||||
const flatData = useMemo(() => data?.rows ?? [], [data]);
|
||||
|
||||
const table = useReactTable({
|
||||
data: flatData,
|
||||
columns,
|
||||
getCoreRowModel: getCoreRowModel(),
|
||||
getSortedRowModel: getSortedRowModel(),
|
||||
manualPagination: true,
|
||||
pageCount: Math.ceil(totalRowCount / limit),
|
||||
});
|
||||
|
||||
return (
|
||||
<>
|
||||
<DataTableWrapper
|
||||
table={table}
|
||||
isPending={isPending}
|
||||
variant="default"
|
||||
paginationMode="standard"
|
||||
EmptyView={
|
||||
<EmptyScreen
|
||||
customIcon={<img className="mb-6" src="/slash-icon-cards.svg" />}
|
||||
headline={t("no_pending_reports")}
|
||||
className="bg-muted mb-16"
|
||||
iconWrapperClassName="bg-default"
|
||||
dashedBorder={false}
|
||||
/>
|
||||
}
|
||||
totalRowCount={totalRowCount}
|
||||
/>
|
||||
|
||||
<BookingReportEntryDetailsModal
|
||||
entry={selectedReport}
|
||||
isOpen={showReviewDialog}
|
||||
onClose={() => {
|
||||
setShowReviewDialog(false);
|
||||
setSelectedReport(null);
|
||||
}}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,446 @@
|
||||
"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 { useOrgBranding } from "@calcom/features/ee/organizations/context/provider";
|
||||
import { subdomainSuffix } from "@calcom/features/ee/organizations/lib/orgDomains";
|
||||
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 OrgAppearanceViewWrapper from "./appearance";
|
||||
|
||||
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"
|
||||
|
||||
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;
|
||||
@@ -0,0 +1,47 @@
|
||||
import { JOIN_COMMUNITY } from "@calcom/lib/constants";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { Icon } from "@calcom/ui/components/icon";
|
||||
import { useHasPaidPlan } from "@calcom/web/modules/billing/hooks/useHasPaidPlan";
|
||||
|
||||
import { UpgradeTeamsBadgeWebWrapper } from "~/billing/components/UpgradeTeamsBadgeWebWrapper";
|
||||
|
||||
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")}
|
||||
<UpgradeTeamsBadgeWebWrapper />
|
||||
</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"
|
||||
rel="noreferrer">
|
||||
{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>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,196 @@
|
||||
"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>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,30 @@
|
||||
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>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
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>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
const host = process.env.NEXT_PUBLIC_FRESHCHAT_HOST;
|
||||
|
||||
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,
|
||||
});
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
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();
|
||||
}
|
||||
|
||||
|
||||
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" />}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
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;
|
||||
@@ -0,0 +1,8 @@
|
||||
import dynamic from "next/dynamic";
|
||||
import { Fragment } from "react";
|
||||
|
||||
const DynamicHelpscoutProvider = process.env.NEXT_PUBLIC_HELPSCOUT_KEY
|
||||
? dynamic(() => import("./provider"))
|
||||
: Fragment;
|
||||
|
||||
export default DynamicHelpscoutProvider;
|
||||
@@ -0,0 +1,142 @@
|
||||
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",
|
||||
};
|
||||
}
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,94 @@
|
||||
"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 { useFlagMap } from "@calcom/features/flags/context/provider";
|
||||
import useMediaQuery from "@calcom/lib/hooks/useMediaQuery";
|
||||
import { useHasPaidPlan } from "@calcom/web/modules/billing/hooks/useHasPaidPlan";
|
||||
import { useBootIntercom } from "@calcom/web/modules/ee/support/lib/intercom/useIntercom";
|
||||
|
||||
import { IntercomContactForm } from "~/ee/support/components/IntercomContactForm";
|
||||
|
||||
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;
|
||||
@@ -0,0 +1,8 @@
|
||||
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;
|
||||
@@ -0,0 +1,188 @@
|
||||
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 { 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";
|
||||
import { useHasTeamPlan, useHasPaidPlan } from "@calcom/web/modules/billing/hooks/useHasPaidPlan";
|
||||
|
||||
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"));
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [user, statsData, hasPaidPlan, isTieredSupportEnabled]);
|
||||
};
|
||||
|
||||
export default useIntercom;
|
||||
@@ -0,0 +1,35 @@
|
||||
import Script from "next/script";
|
||||
import { useState } from "react";
|
||||
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
|
||||
|
||||
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}`} />
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,266 @@
|
||||
"use client";
|
||||
|
||||
import { keepPreviousData } from "@tanstack/react-query";
|
||||
import { useSession } from "next-auth/react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import posthog from "posthog-js";
|
||||
import { useState, useMemo } from "react";
|
||||
|
||||
import { checkAdminOrOwner } from "@calcom/features/auth/lib/checkAdminOrOwner";
|
||||
import { useOrgBranding } from "@calcom/features/ee/organizations/context/provider";
|
||||
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";
|
||||
import InviteLinkSettingsModal from "@calcom/web/modules/ee/teams/components/InviteLinkSettingsModal";
|
||||
|
||||
import { MemberInvitationModalWithoutMembers } from "~/ee/teams/components/MemberInvitationModal";
|
||||
|
||||
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>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,179 @@
|
||||
"use client";
|
||||
|
||||
import posthog from "posthog-js";
|
||||
import { useState } from "react";
|
||||
import { Controller, useForm } from "react-hook-form";
|
||||
|
||||
import { useOrgBranding } from "@calcom/features/ee/organizations/context/provider";
|
||||
import { subdomainSuffix } from "@calcom/features/ee/organizations/lib/orgDomains";
|
||||
import type { NewTeamFormValues } from "@calcom/features/ee/teams/lib/types";
|
||||
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";
|
||||
|
||||
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>
|
||||
</>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,62 @@
|
||||
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>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
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;
|
||||
@@ -0,0 +1,334 @@
|
||||
import { render } from "@testing-library/react";
|
||||
import React, { type ReactNode } from "react";
|
||||
import { vi } from "vitest";
|
||||
|
||||
import { MembershipRole } from "@calcom/prisma/enums";
|
||||
import { EditMemberSheet } from "@calcom/web/modules/ee/teams/components/EditMemberSheet";
|
||||
import type { MemberPermissions } from "@calcom/web/modules/users/components/UserTable/types";
|
||||
|
||||
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/web/modules/users/components/UserTable/EditSheet/store", () => ({
|
||||
useEditMode: (
|
||||
selector: (state: {
|
||||
editMode: boolean;
|
||||
setEditMode: typeof mockSetEditMode;
|
||||
mutationLoading: boolean;
|
||||
setMutationLoading: typeof mockSetMutationLoading;
|
||||
}) => unknown
|
||||
) => {
|
||||
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/web/modules/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/web/modules/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,
|
||||
})
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,295 @@
|
||||
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 { 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 { DisplayInfo } from "@calcom/web/modules/users/components/UserTable/EditSheet/DisplayInfo";
|
||||
import { SheetFooterControls } from "@calcom/web/modules/users/components/UserTable/EditSheet/SheetFooterControls";
|
||||
import { useEditMode } from "@calcom/web/modules/users/components/UserTable/EditSheet/store";
|
||||
import type { MemberPermissions } from "@calcom/web/modules/users/components/UserTable/types";
|
||||
|
||||
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>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,203 @@
|
||||
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>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,127 @@
|
||||
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 { Button } from "@calcom/ui/components/button";
|
||||
import { showToast } from "@calcom/ui/components/toast";
|
||||
import { Tooltip } from "@calcom/ui/components/tooltip";
|
||||
|
||||
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>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,187 @@
|
||||
"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;
|
||||
@@ -0,0 +1,128 @@
|
||||
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>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
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;
|
||||
@@ -0,0 +1,199 @@
|
||||
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 "@calcom/web/modules/ee/teams/components/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>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,566 @@
|
||||
import { useSession } from "next-auth/react";
|
||||
import posthog from "posthog-js";
|
||||
import type { FormEvent } from "react";
|
||||
import { useMemo, useRef, useState } from "react";
|
||||
import { Controller, useForm } from "react-hook-form";
|
||||
|
||||
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 type { PendingMember } from "@calcom/features/ee/teams/lib/types";
|
||||
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 { 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();
|
||||
}}
|
||||
/>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,841 @@
|
||||
"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 { signIn } from "next-auth/react";
|
||||
import { usePathname } from "next/navigation";
|
||||
import { useQueryState, parseAsBoolean } from "nuqs";
|
||||
import posthog from "posthog-js";
|
||||
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 { 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 TeamAvailabilityModal from "@calcom/web/modules/ee/teams/components/TeamAvailabilityModal";
|
||||
import { DynamicLink } from "@calcom/web/modules/users/components/UserTable/BulkActions/DynamicLink";
|
||||
import type { MemberPermissions } from "@calcom/web/modules/users/components/UserTable/types";
|
||||
|
||||
import DeleteBulkTeamMembers from "./DeleteBulkTeamMembers";
|
||||
import { EditMemberSheet } from "./EditMemberSheet";
|
||||
import { EventTypesList } from "./EventTypesList";
|
||||
|
||||
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}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
"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;
|
||||
@@ -0,0 +1,106 @@
|
||||
"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;
|
||||
@@ -0,0 +1,55 @@
|
||||
"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;
|
||||
@@ -0,0 +1,15 @@
|
||||
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;
|
||||
@@ -0,0 +1,40 @@
|
||||
"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>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
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>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
/* 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>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
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>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,70 @@
|
||||
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>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
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>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,174 @@
|
||||
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>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,383 @@
|
||||
import Link from "next/link";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useState } from "react";
|
||||
|
||||
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 { MemberInvitationModalWithoutMembers } from "~/ee/teams/components/MemberInvitationModal";
|
||||
|
||||
import InviteLinkSettingsModal from "./InviteLinkSettingsModal";
|
||||
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>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,42 @@
|
||||
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} />;
|
||||
}
|
||||
@@ -0,0 +1,182 @@
|
||||
"use client";
|
||||
|
||||
import { useRouter, useSearchParams } from "next/navigation";
|
||||
import { useEffect, useMemo } from "react";
|
||||
|
||||
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 SkeletonLoaderTeamList from "~/ee/teams/components/SkeletonloaderTeamList";
|
||||
import { UpgradeTip } from "~/shell/UpgradeTip";
|
||||
|
||||
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>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
"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>
|
||||
}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
"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}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
"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
@@ -0,0 +1,157 @@
|
||||
/* 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();
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,2 @@
|
||||
export { CreateButton } from "./CreateButton";
|
||||
export { CreateButtonWithTeamsList } from "./CreateButtonWithTeamsList";
|
||||
@@ -0,0 +1,235 @@
|
||||
"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 ThemeLabel from "@calcom/features/settings/ThemeLabel";
|
||||
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";
|
||||
|
||||
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;
|
||||
@@ -0,0 +1,76 @@
|
||||
"use client";
|
||||
|
||||
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 type { MemberPermissions } from "@calcom/web/modules/users/components/UserTable/types";
|
||||
|
||||
import { MemberInvitationModalWithoutMembers } from "~/ee/teams/components/MemberInvitationModal";
|
||||
|
||||
import MemberList from "../components/MemberList";
|
||||
|
||||
interface TeamMembersViewProps {
|
||||
team: NonNullable<RouterOutputs["viewer"]["teams"]["get"]>;
|
||||
facetedTeamValues?: {
|
||||
roles: { id: string; name: string }[];
|
||||
teams: RouterOutputs["viewer"]["teams"]["get"][];
|
||||
attributes: {
|
||||
id: string;
|
||||
name: string;
|
||||
options: {
|
||||
value: string;
|
||||
}[];
|
||||
}[];
|
||||
};
|
||||
attributes?: {
|
||||
id: string;
|
||||
name: string;
|
||||
options: {
|
||||
value: string;
|
||||
}[];
|
||||
}[];
|
||||
permissions: MemberPermissions;
|
||||
}
|
||||
|
||||
export const TeamMembersView = ({ team, facetedTeamValues, permissions }: TeamMembersViewProps) => {
|
||||
const { t } = useLocale();
|
||||
const [showMemberInvitationModal, setShowMemberInvitationModal] = useState(false);
|
||||
const [_showInviteLinkSettingsModal, setShowInviteLinkSettingsModal] = useState(false);
|
||||
|
||||
// Use PBAC permissions - server-side permission check should be done in parent component
|
||||
const canLoggedInUserSeeMembers = permissions?.canListMembers ?? false;
|
||||
|
||||
return (
|
||||
<LicenseRequired>
|
||||
<div>
|
||||
{canLoggedInUserSeeMembers && (
|
||||
<div className="mb-6">
|
||||
<MemberList
|
||||
team={team}
|
||||
isOrgAdminOrOwner={false}
|
||||
setShowMemberInvitationModal={setShowMemberInvitationModal}
|
||||
facetedTeamValues={facetedTeamValues}
|
||||
permissions={permissions}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
{!canLoggedInUserSeeMembers && (
|
||||
<div className="border-subtle rounded-xl border p-6" data-testid="members-privacy-warning">
|
||||
<h2 className="text-default">{t("only_admin_can_see_members_of_team")}</h2>
|
||||
</div>
|
||||
)}
|
||||
{showMemberInvitationModal && team && team.id && (
|
||||
<MemberInvitationModalWithoutMembers
|
||||
hideInvitationModal={() => setShowMemberInvitationModal(false)}
|
||||
showMemberInvitationModal={showMemberInvitationModal}
|
||||
teamId={team.id}
|
||||
token={team.inviteToken?.token}
|
||||
onSettingsOpen={() => setShowInviteLinkSettingsModal(true)}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</LicenseRequired>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,499 @@
|
||||
"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;
|
||||
@@ -0,0 +1,227 @@
|
||||
"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 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 { IntervalLimitsManager } from "@calcom/web/modules/event-types/components/tabs/limits/EventLimitsTab";
|
||||
|
||||
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;
|
||||
@@ -0,0 +1,203 @@
|
||||
"use client";
|
||||
|
||||
import { useRouter } from "next/navigation";
|
||||
import { Suspense, useEffect, useState } from "react";
|
||||
|
||||
import dayjs from "@calcom/dayjs";
|
||||
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 { useHasTeamPlan } from "@calcom/web/modules/billing/hooks/useHasPaidPlan";
|
||||
|
||||
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;
|
||||
@@ -0,0 +1,19 @@
|
||||
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>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
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>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,284 @@
|
||||
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 { WORKFLOW_ACTIONS } from "@calcom/features/ee/workflows/lib/constants";
|
||||
import { onlyLettersNumbersSpaces } from "@calcom/features/ee/workflows/lib/schema";
|
||||
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";
|
||||
|
||||
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;
|
||||
upgradeTeamsBadgeProps?: {
|
||||
hasPaidPlan?: boolean;
|
||||
hasActiveTeamPlan?: boolean;
|
||||
isTrial?: 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,
|
||||
upgradeTeamsBadgeProps: option.upgradeTeamsBadgeProps,
|
||||
}))}
|
||||
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="stack-y-1 mt-5">
|
||||
<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>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,189 @@
|
||||
import type { Dispatch } from "react";
|
||||
|
||||
import type { CallDetailsAction, CallDetailsState } from "@calcom/features/ee/workflows/lib/types";
|
||||
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";
|
||||
|
||||
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="stack-y-6 flex flex-col 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 stack-y-3 max-h-96 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>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
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>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,167 @@
|
||||
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 { CreateButtonWithTeamsList } from "~/ee/teams/components/createButton/CreateButtonWithTeamsList";
|
||||
|
||||
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 line-clamp-2 mt-3 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>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,12 @@
|
||||
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;
|
||||
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