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,29 @@
|
||||
import type { SessionContextValue } from "next-auth/react";
|
||||
import Link from "next/link";
|
||||
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { TopBanner } from "@calcom/ui/components/top-banner";
|
||||
|
||||
export type AdminPasswordBannerProps = { data: SessionContextValue["data"] };
|
||||
|
||||
function AdminPasswordBanner({ data }: AdminPasswordBannerProps) {
|
||||
const { t } = useLocale();
|
||||
|
||||
if (data?.user.role !== "INACTIVE_ADMIN") return null;
|
||||
|
||||
return (
|
||||
<>
|
||||
<TopBanner
|
||||
text={t("invalid_admin_password", { user: data.user.username })}
|
||||
variant="warning"
|
||||
actions={
|
||||
<Link href="/settings/security/password" className="border-b border-b-black">
|
||||
{t("change_password_admin")}
|
||||
</Link>
|
||||
}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export default AdminPasswordBanner;
|
||||
@@ -0,0 +1,31 @@
|
||||
import Link from "next/link";
|
||||
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { type RouterOutputs } from "@calcom/trpc/react";
|
||||
import { TopBanner } from "@calcom/ui/components/top-banner";
|
||||
|
||||
export type CalendarCredentialBannerProps = {
|
||||
data: RouterOutputs["viewer"]["me"]["getUserTopBanners"]["calendarCredentialBanner"];
|
||||
};
|
||||
|
||||
function CalendarCredentialBanner({ data }: CalendarCredentialBannerProps) {
|
||||
const { t } = useLocale();
|
||||
|
||||
if (!data) return null;
|
||||
|
||||
return (
|
||||
<>
|
||||
<TopBanner
|
||||
text={`${t("something_went_wrong")} ${t("calendar_error")}`}
|
||||
variant="error"
|
||||
actions={
|
||||
<Link href="/apps/installed/calendar" className="border-b border-b-black">
|
||||
{t("check_here")}
|
||||
</Link>
|
||||
}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export default CalendarCredentialBanner;
|
||||
@@ -0,0 +1,47 @@
|
||||
import { useRouter } from "next/navigation";
|
||||
|
||||
import { type InvalidAppCredentialBannerProps } from "@calcom/features/users/types/invalidAppCredentials";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { type RouterOutputs } from "@calcom/trpc/react";
|
||||
import { TopBanner } from "@calcom/ui/components/top-banner";
|
||||
|
||||
export type InvalidAppCredentialBannersProps = {
|
||||
data: RouterOutputs["viewer"]["me"]["getUserTopBanners"]["invalidAppCredentialBanners"];
|
||||
};
|
||||
|
||||
export function InvalidAppCredentialBanners({ data }: InvalidAppCredentialBannersProps) {
|
||||
if (data.length === 0) {
|
||||
return null; // No need to show banner if the array is empty
|
||||
}
|
||||
|
||||
return (
|
||||
<div>
|
||||
{data.map((app) => (
|
||||
<InvalidAppCredentialBanner key={app.slug} name={app.name} slug={app.slug} />
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export type { InvalidAppCredentialBannerProps };
|
||||
|
||||
export function InvalidAppCredentialBanner({ name, slug }: InvalidAppCredentialBannerProps) {
|
||||
const { t } = useLocale();
|
||||
const router = useRouter();
|
||||
|
||||
const handleClick = () => {
|
||||
router.push(`/apps/${slug}`);
|
||||
};
|
||||
|
||||
return (
|
||||
<TopBanner
|
||||
text={` ${t("invalid_credential", { appName: name })} `}
|
||||
variant="warning"
|
||||
actions={
|
||||
<button className="border-b border-b-black" onClick={handleClick}>
|
||||
{t("invalid_credential_action")}
|
||||
</button>
|
||||
}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
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 { DialogTrigger, ConfirmationDialogContent } from "@calcom/ui/components/dialog";
|
||||
import { showToast } from "@calcom/ui/components/toast";
|
||||
|
||||
import type { UserTableUser } from "../types";
|
||||
|
||||
interface Props {
|
||||
users: Array<{ id: UserTableUser["id"] }>;
|
||||
onRemove: () => void;
|
||||
}
|
||||
|
||||
export function DeleteBulkUsers({ users, onRemove }: Props) {
|
||||
const { t } = useLocale();
|
||||
const selectedRows = users; // Get selected rows from table
|
||||
const utils = trpc.useUtils();
|
||||
const deleteMutation = trpc.viewer.organizations.bulkDeleteUsers.useMutation({
|
||||
onSuccess: () => {
|
||||
showToast("Deleted Users", "success");
|
||||
utils.viewer.organizations.listMembers.invalidate();
|
||||
},
|
||||
onError: (error) => {
|
||||
showToast(error.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_org")}
|
||||
confirmBtnText={t("remove")}
|
||||
isPending={deleteMutation.isPending}
|
||||
onConfirm={() => {
|
||||
deleteMutation.mutateAsync({
|
||||
userIds: selectedRows.map((user) => user.id),
|
||||
});
|
||||
onRemove();
|
||||
}}>
|
||||
<p className="mt-5">
|
||||
{t("remove_users_from_org_confirm", {
|
||||
userCount: selectedRows.length,
|
||||
})}
|
||||
</p>
|
||||
</ConfirmationDialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
import type { Table } from "@tanstack/react-table";
|
||||
import { useQueryState, parseAsBoolean } from "nuqs";
|
||||
|
||||
import { useCopy } from "@calcom/lib/hooks/useCopy";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { Button } from "@calcom/ui/components/button";
|
||||
|
||||
export function DynamicLink<T extends { username: string | null }>({
|
||||
table,
|
||||
domain,
|
||||
}: {
|
||||
table: Table<T>;
|
||||
domain: string;
|
||||
}) {
|
||||
const { t } = useLocale();
|
||||
const [dynamicLinkVisible, _] = useQueryState("dynamicLink", parseAsBoolean);
|
||||
const { copyToClipboard, isCopied } = useCopy();
|
||||
const numberOfSelectedRows = table.getSelectedRowModel().rows.length;
|
||||
const isVisible = numberOfSelectedRows >= 2 && dynamicLinkVisible;
|
||||
|
||||
const users = table
|
||||
.getSelectedRowModel()
|
||||
.flatRows.map((row) => row.original.username)
|
||||
.filter((u): u is string => u !== null);
|
||||
|
||||
const usersNameAsString = users.join("+");
|
||||
|
||||
const dynamicLinkOfSelectedUsers = `${domain}/${usersNameAsString}`;
|
||||
const domainWithoutHttps = dynamicLinkOfSelectedUsers.replace(/https?:\/\//g, "");
|
||||
|
||||
return (
|
||||
<>
|
||||
{isVisible ? (
|
||||
<div className="w-full gap-1 rounded-lg text-sm font-medium leading-none md:flex">
|
||||
<div className="items-center truncate p-2 md:max-w-[300px]">
|
||||
<p className="text-center md:text-left">{domainWithoutHttps}</p>
|
||||
</div>
|
||||
<div className="ml-auto flex items-center justify-center gap-1 md:justify-start">
|
||||
<Button
|
||||
variant="icon"
|
||||
StartIcon={isCopied ? "check" : "copy"}
|
||||
size="sm"
|
||||
onClick={() => copyToClipboard(dynamicLinkOfSelectedUsers)}
|
||||
color="secondary">
|
||||
<span className="sr-only">{!isCopied ? t("copy") : t("copied")}</span>
|
||||
</Button>
|
||||
<Button
|
||||
color="secondary"
|
||||
EndIcon="external-link"
|
||||
size="sm"
|
||||
href={dynamicLinkOfSelectedUsers}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer">
|
||||
Open
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,263 @@
|
||||
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 type { RouterOutputs } 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 { UserTableUser } from "../types";
|
||||
|
||||
interface Props {
|
||||
table: Table<UserTableUser>;
|
||||
orgTeams: RouterOutputs["viewer"]["organizations"]["getTeams"] | undefined;
|
||||
}
|
||||
|
||||
export function EventTypesList({ table, orgTeams }: Props) {
|
||||
const { t } = useLocale();
|
||||
const utils = trpc.useUtils();
|
||||
const teamIds = orgTeams?.map((team) => team.id);
|
||||
const { data } = trpc.viewer.eventTypes.getByViewer.useQuery({
|
||||
filters: { teamIds, schedulingTypes: [SchedulingType.ROUND_ROBIN] },
|
||||
});
|
||||
const addMutation = trpc.viewer.organizations.addMembersToEventTypes.useMutation({
|
||||
onError: (error) => {
|
||||
showToast(error.message, "error");
|
||||
},
|
||||
onSuccess: () => {
|
||||
showToast(
|
||||
`${selectedUsers.length} users added to ${Array.from(selectedEvents).length} events`,
|
||||
"success"
|
||||
);
|
||||
|
||||
utils.viewer.organizations.listMembers.invalidate();
|
||||
utils.viewer.eventTypes.invalidate();
|
||||
|
||||
// Clear the selected values
|
||||
setSelectedEvents(new Set());
|
||||
setSelectedTeams(new Set());
|
||||
table.toggleAllRowsSelected(false);
|
||||
},
|
||||
});
|
||||
const removeHostsMutation = trpc.viewer.organizations.removeHostsFromEventTypes.useMutation({
|
||||
onError: (error) => {
|
||||
showToast(error.message, "error");
|
||||
},
|
||||
onSuccess: () => {
|
||||
showToast(
|
||||
`${selectedUsers.length} users were removed from ${Array.from(removeHostFromEvents).length} events`,
|
||||
"success"
|
||||
);
|
||||
|
||||
utils.viewer.organizations.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 [selectedTeams, setSelectedTeams] = useState<Set<number>>(new Set());
|
||||
const [removeHostFromEvents, setRemoveHostFromEvents] = useState<Set<number>>(new Set());
|
||||
const teams = 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>
|
||||
{teams &&
|
||||
teams.map((team) => {
|
||||
const events = team.eventTypes;
|
||||
const teamId = team.teamId;
|
||||
|
||||
if (events.length === 0 || !teamId) return null;
|
||||
|
||||
const ids = events.map((event) => event.id);
|
||||
const areAllUsersHostForTeam = selectedUsers.every((user) =>
|
||||
events.every((event) => event.hosts.some((host) => host.userId === user.id))
|
||||
);
|
||||
const isSelected = ids.every(
|
||||
(id) =>
|
||||
selectedEvents.has(id) || (areAllUsersHostForTeam && !removeHostFromEvents.has(id))
|
||||
);
|
||||
return (
|
||||
<Fragment key={team.teamId}>
|
||||
<ListItem
|
||||
isTeam
|
||||
onSelect={() => {
|
||||
if (!isSelected) {
|
||||
// Add current team and its event
|
||||
addValue(selectedTeams, setSelectedTeams, [teamId]);
|
||||
addValue(selectedEvents, setSelectedEvents, ids);
|
||||
setRemoveHostFromEvents(new Set());
|
||||
} else {
|
||||
const eventIdsWhereAllUsersAreHosts = events
|
||||
.filter((event) =>
|
||||
selectedUsers.every((user) =>
|
||||
event.hosts.some((host) => host.userId === user.id)
|
||||
)
|
||||
)
|
||||
.map((event) => event.id);
|
||||
|
||||
addValue(
|
||||
removeHostFromEvents,
|
||||
setRemoveHostFromEvents,
|
||||
eventIdsWhereAllUsersAreHosts
|
||||
);
|
||||
// Remove selected team and its event
|
||||
removeValue(selectedEvents, setSelectedEvents, ids);
|
||||
removeValue(selectedTeams, setSelectedTeams, [teamId]);
|
||||
}
|
||||
}}
|
||||
isSelected={isSelected}
|
||||
text={team.profile.name || ""}
|
||||
key={team.profile.name}
|
||||
/>
|
||||
{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
|
||||
isTeam={false}
|
||||
onSelect={() => {
|
||||
if (!isSelected) {
|
||||
if (areAllUsersHostForEventType) {
|
||||
removeValue(removeHostFromEvents, setRemoveHostFromEvents, [event.id]);
|
||||
} else {
|
||||
// Add current event and its team
|
||||
addValue(selectedEvents, setSelectedEvents, [event.id]);
|
||||
addValue(selectedTeams, setSelectedTeams, [teamId]);
|
||||
}
|
||||
} else {
|
||||
if (areAllUsersHostForEventType) {
|
||||
// remove selected users as hosts
|
||||
addValue(removeHostFromEvents, setRemoveHostFromEvents, [event.id]);
|
||||
} else {
|
||||
// remove current event and its team
|
||||
removeValue(selectedEvents, setSelectedEvents, [event.id]);
|
||||
// if no event from current team is selected, remove the team
|
||||
setSelectedEvents((selectedEvents) => {
|
||||
if (!ids.some((id) => selectedEvents.has(id))) {
|
||||
setSelectedTeams((selectedTeams) => {
|
||||
const updatedTeams = new Set(selectedTeams);
|
||||
updatedTeams.delete(teamId);
|
||||
return updatedTeams;
|
||||
});
|
||||
}
|
||||
return selectedEvents;
|
||||
});
|
||||
}
|
||||
}
|
||||
}}
|
||||
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,
|
||||
teamIds: Array.from(selectedTeams),
|
||||
eventTypeIds: Array.from(selectedEvents),
|
||||
});
|
||||
}
|
||||
|
||||
if (removeHostFromEvents.size > 0) {
|
||||
removeHostsMutation.mutateAsync({
|
||||
userIds,
|
||||
eventTypeIds: Array.from(removeHostFromEvents),
|
||||
});
|
||||
}
|
||||
}}>
|
||||
{t("apply")}
|
||||
</Button>
|
||||
</div>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
interface ListItemProps {
|
||||
text: string;
|
||||
isSelected: boolean;
|
||||
onSelect: () => void;
|
||||
isTeam: boolean;
|
||||
}
|
||||
|
||||
const ListItem = ({ onSelect, text, isSelected, isTeam }: ListItemProps) => {
|
||||
return (
|
||||
<CommandItem
|
||||
key={text}
|
||||
onSelect={onSelect}
|
||||
className={classNames(isTeam && "text-subtle text-xs font-normal")}>
|
||||
{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,341 @@
|
||||
import type { Table } from "@tanstack/react-table";
|
||||
import { createContext, useContext, useState, useMemo, type PropsWithChildren } from "react";
|
||||
import type { Dispatch, SetStateAction } from "react";
|
||||
|
||||
import { DataTableSelectionBar, type ColumnFilter } from "@calcom/features/data-table";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import type { Attribute as _Attribute, AttributeOption } from "@calcom/prisma/client";
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
import classNames from "@calcom/ui/classNames";
|
||||
import { Alert } from "@calcom/ui/components/alert";
|
||||
import { Button } from "@calcom/ui/components/button";
|
||||
import {
|
||||
Command,
|
||||
CommandEmpty,
|
||||
CommandGroup,
|
||||
CommandInput,
|
||||
CommandItem,
|
||||
CommandList,
|
||||
} from "@calcom/ui/components/command";
|
||||
import { Input } 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";
|
||||
|
||||
import type { UserTableUser } from "../types";
|
||||
|
||||
interface Props {
|
||||
table: Table<UserTableUser>;
|
||||
filters: ColumnFilter[];
|
||||
}
|
||||
|
||||
type Attribute = _Attribute & { options: AttributeOption[] };
|
||||
|
||||
type AttributesContextType = {
|
||||
selectedAttribute: string | undefined;
|
||||
setSelectedAttribute: Dispatch<SetStateAction<string | undefined>>;
|
||||
foundAttributeInCache: Attribute | undefined;
|
||||
|
||||
selectedAttributeOptions: string[];
|
||||
setSelectedAttributeOptions: Dispatch<SetStateAction<string[]>>;
|
||||
|
||||
attributes: Attribute[] | undefined;
|
||||
};
|
||||
|
||||
const AttributesContext = createContext<AttributesContextType | null>(null);
|
||||
|
||||
function AttributesProvider({ children }: PropsWithChildren) {
|
||||
const { data: attributes } = trpc.viewer.attributes.list.useQuery();
|
||||
const [selectedAttribute, setSelectedAttribute] = useState<string>();
|
||||
const [selectedAttributeOptions, setSelectedAttributeOptions] = useState<string[]>([]);
|
||||
|
||||
const foundAttributeInCache = useMemo(
|
||||
() => attributes?.find((attr) => attr.id === selectedAttribute),
|
||||
[selectedAttribute, attributes]
|
||||
);
|
||||
|
||||
const value: AttributesContextType = {
|
||||
selectedAttribute,
|
||||
setSelectedAttribute,
|
||||
selectedAttributeOptions,
|
||||
setSelectedAttributeOptions,
|
||||
foundAttributeInCache,
|
||||
attributes,
|
||||
};
|
||||
|
||||
return <AttributesContext.Provider value={value}>{children}</AttributesContext.Provider>;
|
||||
}
|
||||
|
||||
function useAttributes() {
|
||||
const context = useContext(AttributesContext);
|
||||
if (!context) {
|
||||
throw new Error("useAttributes must be used within an AttributesProvider");
|
||||
}
|
||||
return context;
|
||||
}
|
||||
|
||||
function getTranslateableStringFromType(type: string) {
|
||||
switch (type) {
|
||||
case "SINGLE_SELECT":
|
||||
return "single_select";
|
||||
case "MULTI_SELECT":
|
||||
return "multi_select";
|
||||
case "TEXT":
|
||||
return "text";
|
||||
case "NUMBER":
|
||||
return "number";
|
||||
default:
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
function SelectedAttributeToAssign() {
|
||||
const { t } = useLocale();
|
||||
const {
|
||||
foundAttributeInCache: foundAttribute,
|
||||
selectedAttributeOptions,
|
||||
setSelectedAttributeOptions,
|
||||
} = useAttributes();
|
||||
|
||||
if (!foundAttribute) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const translateableType = getTranslateableStringFromType(foundAttribute.type);
|
||||
|
||||
const isSelectable = foundAttribute.type === "SINGLE_SELECT" || foundAttribute.type === "MULTI_SELECT";
|
||||
|
||||
return (
|
||||
<CommandList>
|
||||
<div className="flex items-center gap-2 border-b px-3 py-2">
|
||||
<span className="block">{foundAttribute.name}</span>
|
||||
{translateableType && <span className="text-muted block text-xs">({t(translateableType)})</span>}
|
||||
</div>
|
||||
<CommandGroup>
|
||||
{isSelectable ? (
|
||||
<>
|
||||
{foundAttribute.options.map((option) => {
|
||||
return (
|
||||
<CommandItem
|
||||
key={option.id}
|
||||
className="hover:cursor-pointer"
|
||||
onSelect={() => {
|
||||
if (foundAttribute.type === "SINGLE_SELECT") {
|
||||
setSelectedAttributeOptions([option.id]);
|
||||
} else {
|
||||
setSelectedAttributeOptions((prev: string[]) => {
|
||||
if (prev.includes(option.id)) {
|
||||
return prev.filter((id: string) => id !== option.id);
|
||||
}
|
||||
return [...prev, option.id];
|
||||
});
|
||||
}
|
||||
}}>
|
||||
<span>{option.value}</span>
|
||||
<div
|
||||
className={classNames(
|
||||
"ml-auto flex h-4 w-4 items-center justify-center rounded-sm border"
|
||||
)}>
|
||||
{selectedAttributeOptions?.includes(option.id) ? (
|
||||
<Icon name="check" className={classNames("h-4 w-4")} />
|
||||
) : null}
|
||||
</div>
|
||||
</CommandItem>
|
||||
);
|
||||
})}
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<CommandItem>
|
||||
<Input
|
||||
defaultValue={selectedAttributeOptions[0] || ""}
|
||||
type={foundAttribute.type === "TEXT" ? "text" : "number"}
|
||||
onBlur={(e) => {
|
||||
// trigger onBlur so it's set as Apply is pressed (but not onChange) which triggers
|
||||
// a re-render which also loses focus.
|
||||
setSelectedAttributeOptions([e.target.value]);
|
||||
}}
|
||||
/>
|
||||
</CommandItem>
|
||||
</>
|
||||
)}
|
||||
</CommandGroup>
|
||||
</CommandList>
|
||||
);
|
||||
}
|
||||
|
||||
function Content({ showMultiSelectWarning }: { showMultiSelectWarning: boolean }) {
|
||||
const { t } = useLocale();
|
||||
const {
|
||||
selectedAttribute,
|
||||
setSelectedAttribute,
|
||||
selectedAttributeOptions,
|
||||
setSelectedAttributeOptions,
|
||||
attributes,
|
||||
foundAttributeInCache,
|
||||
} = useAttributes();
|
||||
if (!selectedAttribute) {
|
||||
return (
|
||||
<>
|
||||
<CommandInput placeholder={t("search")} />
|
||||
<CommandList>
|
||||
<CommandEmpty>No attributes found</CommandEmpty>
|
||||
<CommandGroup>
|
||||
{attributes &&
|
||||
attributes.map((option) => {
|
||||
return (
|
||||
<CommandItem
|
||||
key={option.id}
|
||||
className="hover:cursor-pointer"
|
||||
onSelect={() => {
|
||||
setSelectedAttribute(option.id);
|
||||
setSelectedAttributeOptions([]);
|
||||
}}>
|
||||
<span>{option.name}</span>
|
||||
<div
|
||||
className={classNames("ml-auto flex h-4 w-4 items-center justify-center rounded-sm")}>
|
||||
<Icon name="chevron-right" className={classNames("h-4 w-4")} />
|
||||
</div>
|
||||
</CommandItem>
|
||||
);
|
||||
})}
|
||||
</CommandGroup>
|
||||
</CommandList>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
if (showMultiSelectWarning) {
|
||||
return (
|
||||
<div className="max-h-[300px] overflow-y-auto overflow-x-hidden px-3 py-2">
|
||||
<Alert
|
||||
severity="warning"
|
||||
message="You are mass assigning to a multi select. This will assign the attribute to all selected users and
|
||||
will not override existing values."
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (selectedAttribute) {
|
||||
return <SelectedAttributeToAssign />;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function MassAssignAttributesBulkActionComponent({ table, filters }: Props) {
|
||||
const {
|
||||
selectedAttribute,
|
||||
setSelectedAttribute,
|
||||
selectedAttributeOptions,
|
||||
setSelectedAttributeOptions,
|
||||
foundAttributeInCache,
|
||||
} = useAttributes();
|
||||
|
||||
const [showMultiSelectWarning, setShowMultiSelectWarning] = useState(false);
|
||||
const { t } = useLocale();
|
||||
const utils = trpc.useUtils();
|
||||
const bulkAssignAttributes = trpc.viewer.attributes.bulkAssignAttributes.useMutation({
|
||||
onSuccess: (success) => {
|
||||
setSelectedAttribute(undefined);
|
||||
setSelectedAttributeOptions([]);
|
||||
utils.viewer.organizations.listMembers.invalidate();
|
||||
showToast(success.message, "success");
|
||||
},
|
||||
onError: (error) => {
|
||||
showToast(`Error assigning attributes: ${error.message}`, "error");
|
||||
},
|
||||
});
|
||||
|
||||
return (
|
||||
<Popover
|
||||
onOpenChange={(open) => {
|
||||
if (!open) {
|
||||
setSelectedAttribute(undefined);
|
||||
setSelectedAttributeOptions([]);
|
||||
setShowMultiSelectWarning(false);
|
||||
}
|
||||
}}>
|
||||
<PopoverTrigger asChild>
|
||||
<DataTableSelectionBar.Button icon="tags" color="secondary">
|
||||
{t("add_attributes")}
|
||||
</DataTableSelectionBar.Button>
|
||||
</PopoverTrigger>
|
||||
{/* We dont really use shadows much - but its needed here */}
|
||||
<PopoverContent className="p-0 shadow-md" align="start" sideOffset={12}>
|
||||
<Command>
|
||||
<Content showMultiSelectWarning={showMultiSelectWarning} />
|
||||
</Command>
|
||||
<div className="my-1.5 flex w-full justify-end gap-2 p-1.5">
|
||||
{selectedAttribute ? (
|
||||
<>
|
||||
<Button
|
||||
color="secondary"
|
||||
className="rounded-md"
|
||||
size="sm"
|
||||
onClick={() => {
|
||||
setSelectedAttribute(undefined);
|
||||
setSelectedAttributeOptions([]);
|
||||
setShowMultiSelectWarning(false);
|
||||
}}>
|
||||
{t("clear")}
|
||||
</Button>
|
||||
<Button
|
||||
className="rounded-md"
|
||||
loading={bulkAssignAttributes.isPending}
|
||||
size="sm"
|
||||
onClick={() => {
|
||||
if (
|
||||
foundAttributeInCache &&
|
||||
foundAttributeInCache.type === "MULTI_SELECT" &&
|
||||
!showMultiSelectWarning
|
||||
) {
|
||||
setShowMultiSelectWarning(true);
|
||||
} else {
|
||||
if (!foundAttributeInCache) {
|
||||
return;
|
||||
}
|
||||
setShowMultiSelectWarning(false);
|
||||
let attributesToAssign;
|
||||
if (
|
||||
foundAttributeInCache?.type === "MULTI_SELECT" ||
|
||||
foundAttributeInCache?.type === "SINGLE_SELECT"
|
||||
) {
|
||||
attributesToAssign = [
|
||||
{
|
||||
id: foundAttributeInCache.id,
|
||||
options: selectedAttributeOptions.map((v) => ({
|
||||
value: v,
|
||||
})),
|
||||
},
|
||||
];
|
||||
} else {
|
||||
attributesToAssign = [
|
||||
{ id: foundAttributeInCache.id, value: selectedAttributeOptions[0] },
|
||||
];
|
||||
}
|
||||
|
||||
bulkAssignAttributes.mutate({
|
||||
attributes: attributesToAssign,
|
||||
userIds: table.getSelectedRowModel().rows.map((row) => row.original.id),
|
||||
});
|
||||
}
|
||||
}}>
|
||||
{t("apply")}
|
||||
</Button>
|
||||
</>
|
||||
) : null}
|
||||
</div>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
);
|
||||
}
|
||||
|
||||
export function MassAssignAttributesBulkAction({ table, filters }: Props) {
|
||||
return (
|
||||
<AttributesProvider>
|
||||
<MassAssignAttributesBulkActionComponent table={table} filters={filters} />
|
||||
</AttributesProvider>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,167 @@
|
||||
import type { Table } from "@tanstack/react-table";
|
||||
import type { Dispatch, SetStateAction } from "react";
|
||||
import { useState } from "react";
|
||||
|
||||
import { DataTableSelectionBar } from "@calcom/features/data-table";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
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 { UserTableUser } from "../types";
|
||||
|
||||
interface Props {
|
||||
table: Table<UserTableUser>;
|
||||
}
|
||||
|
||||
export function TeamListBulkAction({ table }: Props) {
|
||||
const { data: teams } = trpc.viewer.organizations.getTeams.useQuery();
|
||||
const [selectedValues, setSelectedValues] = useState<Set<number>>(new Set());
|
||||
const [removeFromTeams, setRemoveFromTeams] = useState<Set<number>>(new Set());
|
||||
const utils = trpc.useUtils();
|
||||
const mutation = trpc.viewer.organizations.addMembersToTeams.useMutation({
|
||||
onError: (error) => {
|
||||
showToast(error.message, "error");
|
||||
},
|
||||
onSuccess: (res) => {
|
||||
showToast(
|
||||
`${res.invitedTotalUsers} Users invited to ${Array.from(selectedValues).length} teams`,
|
||||
"success"
|
||||
);
|
||||
// Optimistically update the data from query trpc cache listMembers
|
||||
// We may need to set this data instead of invalidating. Will see how performance handles it
|
||||
utils.viewer.organizations.listMembers.invalidate();
|
||||
|
||||
// Clear the selected values
|
||||
setSelectedValues(new Set());
|
||||
table.toggleAllRowsSelected(false);
|
||||
},
|
||||
});
|
||||
|
||||
const removeMemberMutation = trpc.viewer.teams.removeMember.useMutation({
|
||||
onError: (error) => {
|
||||
showToast(error.message, "error");
|
||||
},
|
||||
onSuccess: () => {
|
||||
showToast(`${selectedUsers.length} Users removed from ${removeFromTeams.size} teams`, "success");
|
||||
|
||||
utils.viewer.organizations.listMembers.invalidate();
|
||||
|
||||
// Clear the selected values
|
||||
setRemoveFromTeams(new Set());
|
||||
table.toggleAllRowsSelected(false);
|
||||
},
|
||||
});
|
||||
|
||||
const { t } = useLocale();
|
||||
const selectedUsers = table.getSelectedRowModel().flatRows.map((row) => row.original);
|
||||
|
||||
// Add a value to the set
|
||||
const addValue = (set: Set<number>, setSet: Dispatch<SetStateAction<Set<number>>>, value: number) => {
|
||||
const updatedSet = new Set(set);
|
||||
updatedSet.add(value);
|
||||
setSet(updatedSet);
|
||||
};
|
||||
|
||||
// Remove value from the set
|
||||
const removeValue = (set: Set<number>, setSet: Dispatch<SetStateAction<Set<number>>>, value: number) => {
|
||||
const updatedSet = new Set(set);
|
||||
updatedSet.delete(value);
|
||||
setSet(updatedSet);
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<Popover>
|
||||
<PopoverTrigger asChild>
|
||||
<DataTableSelectionBar.Button icon="users" color="secondary">
|
||||
{t("add_to_team")}
|
||||
</DataTableSelectionBar.Button>
|
||||
</PopoverTrigger>
|
||||
{/* We dont really use shadows much - but its needed here */}
|
||||
<PopoverContent className="w-[200px] p-0 shadow-md" align="start" sideOffset={12}>
|
||||
<Command>
|
||||
<CommandInput placeholder={t("search")} />
|
||||
<CommandList>
|
||||
<CommandEmpty>No results found.</CommandEmpty>
|
||||
<CommandGroup>
|
||||
{teams &&
|
||||
teams.map((option) => {
|
||||
const areAllUsersInTeam = selectedUsers.every((user) =>
|
||||
user.teams.some((team) => team.id === option.id)
|
||||
);
|
||||
const isSelected =
|
||||
(selectedValues.has(option.id) || areAllUsersInTeam) && !removeFromTeams.has(option.id);
|
||||
|
||||
return (
|
||||
<CommandItem
|
||||
key={option.id}
|
||||
onSelect={() => {
|
||||
if (!isSelected) {
|
||||
if (areAllUsersInTeam) {
|
||||
removeValue(removeFromTeams, setRemoveFromTeams, option.id);
|
||||
} else {
|
||||
addValue(selectedValues, setSelectedValues, option.id);
|
||||
}
|
||||
} else {
|
||||
if (areAllUsersInTeam) {
|
||||
addValue(removeFromTeams, setRemoveFromTeams, option.id);
|
||||
} else {
|
||||
removeValue(selectedValues, setSelectedValues, option.id);
|
||||
}
|
||||
}
|
||||
}}>
|
||||
<span>{option.name}</span>
|
||||
<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>
|
||||
);
|
||||
})}
|
||||
</CommandGroup>
|
||||
</CommandList>
|
||||
</Command>
|
||||
<div className="my-1.5 flex w-full">
|
||||
<Button
|
||||
loading={mutation.isPending}
|
||||
className="ml-auto mr-1.5 rounded-md"
|
||||
size="sm"
|
||||
onClick={async () => {
|
||||
if (selectedValues.size > 0) {
|
||||
mutation.mutateAsync({
|
||||
userIds: selectedUsers.map((user) => user.id),
|
||||
teamIds: Array.from(selectedValues),
|
||||
});
|
||||
}
|
||||
|
||||
if (removeFromTeams.size > 0) {
|
||||
removeMemberMutation.mutateAsync({
|
||||
memberIds: selectedUsers.map((user) => user.id),
|
||||
teamIds: Array.from(removeFromTeams),
|
||||
isOrg: true,
|
||||
});
|
||||
}
|
||||
}}>
|
||||
{t("apply")}
|
||||
</Button>
|
||||
</div>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
import { useSession } from "next-auth/react";
|
||||
import type { Dispatch } from "react";
|
||||
|
||||
import MemberChangeRoleModal from "@calcom/web/modules/ee/teams/components/MemberChangeRoleModal";
|
||||
|
||||
import type { UserTableAction, UserTableState } from "./types";
|
||||
|
||||
export function ChangeUserRoleModal(props: { state: UserTableState; dispatch: Dispatch<UserTableAction> }) {
|
||||
const { data: session } = useSession();
|
||||
const orgId = session?.user.org?.id;
|
||||
if (!orgId || !props.state.changeMemberRole.user) return null;
|
||||
|
||||
return (
|
||||
<MemberChangeRoleModal
|
||||
isOpen={true}
|
||||
currentMember={props.state.changeMemberRole.user?.role}
|
||||
teamId={orgId}
|
||||
memberId={props.state.changeMemberRole.user?.id}
|
||||
initialRole={props.state.changeMemberRole.user?.role}
|
||||
onExit={() =>
|
||||
props.dispatch({
|
||||
type: "CLOSE_MODAL",
|
||||
})
|
||||
}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
import { useSession } from "next-auth/react";
|
||||
import type { Dispatch } from "react";
|
||||
|
||||
import { Dialog } from "@calcom/features/components/controlled-dialog";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
import { ConfirmationDialogContent } from "@calcom/ui/components/dialog";
|
||||
import { showToast } from "@calcom/ui/components/toast";
|
||||
|
||||
import type { UserTableAction, UserTableState } from "./types";
|
||||
|
||||
export function DeleteMemberModal({
|
||||
state,
|
||||
dispatch,
|
||||
}: {
|
||||
state: UserTableState;
|
||||
dispatch: Dispatch<UserTableAction>;
|
||||
}) {
|
||||
const { t } = useLocale();
|
||||
const { data: session } = useSession();
|
||||
const utils = trpc.useUtils();
|
||||
const removeMemberMutation = trpc.viewer.teams.removeMember.useMutation({
|
||||
onSuccess() {
|
||||
utils.viewer.organizations.listMembers.invalidate();
|
||||
utils.viewer.teams.get.invalidate();
|
||||
utils.viewer.eventTypes.invalidate();
|
||||
|
||||
showToast(t("success"), "success");
|
||||
|
||||
// Close the modal after successful deletion
|
||||
dispatch({ type: "CLOSE_MODAL" });
|
||||
},
|
||||
async onError(err) {
|
||||
showToast(err.message, "error");
|
||||
},
|
||||
});
|
||||
return (
|
||||
<Dialog
|
||||
open={state.deleteMember.showModal}
|
||||
onOpenChange={(open) =>
|
||||
!open &&
|
||||
dispatch({
|
||||
type: "CLOSE_MODAL",
|
||||
})
|
||||
}>
|
||||
<ConfirmationDialogContent
|
||||
variety="danger"
|
||||
title={t("remove_member")}
|
||||
confirmBtnText={t("confirm_remove_member")}
|
||||
onConfirm={() => {
|
||||
// Shouldn't ever happen just for type safety
|
||||
if (!session?.user.org?.id || !state?.deleteMember?.user?.id) return;
|
||||
|
||||
removeMemberMutation.mutate({
|
||||
teamIds: [session?.user.org.id],
|
||||
memberIds: [state?.deleteMember?.user.id],
|
||||
isOrg: true,
|
||||
});
|
||||
}}>
|
||||
{t("remove_member_confirmation_message")}
|
||||
</ConfirmationDialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
import { useRef, useState } from "react";
|
||||
|
||||
import { Badge } from "@calcom/ui/components/badge";
|
||||
import type { IconName } from "@calcom/ui/components/icon";
|
||||
import { Icon } from "@calcom/ui/components/icon";
|
||||
import { Tooltip } from "@calcom/ui/components/tooltip";
|
||||
|
||||
type DisplayInfoType = {
|
||||
label: string;
|
||||
icon?: IconName;
|
||||
value: string | string[];
|
||||
coloredBadges?: boolean;
|
||||
labelClassname?: string;
|
||||
valueClassname?: string;
|
||||
};
|
||||
|
||||
const badgeColors = ["warning", "success", "green", "gray", "blue", "red", "error"] as const;
|
||||
|
||||
const valueDefaultClassname = "text-emphasis inline-flex items-center gap-1 font-medium leading-5";
|
||||
|
||||
export function DisplayInfo({
|
||||
label,
|
||||
icon,
|
||||
value,
|
||||
coloredBadges,
|
||||
labelClassname,
|
||||
valueClassname = valueDefaultClassname,
|
||||
}: DisplayInfoType) {
|
||||
const displayAsBadges = Array.isArray(value);
|
||||
const scrollContainerRef = useRef<HTMLDivElement>(null);
|
||||
const [showLeftGradient, setShowLeftGradient] = useState(false);
|
||||
const [showRightGradient, setShowRightGradient] = useState(true);
|
||||
|
||||
const handleScroll = () => {
|
||||
const element = scrollContainerRef.current;
|
||||
if (!element) return;
|
||||
|
||||
setShowLeftGradient(element.scrollLeft > 0);
|
||||
|
||||
const isAtEnd = Math.abs(element.scrollWidth - element.clientWidth - element.scrollLeft) < 1;
|
||||
setShowRightGradient(!isAtEnd);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex items-center gap-6">
|
||||
<div className="flex w-[110px] items-center gap-2">
|
||||
{icon ? <Icon className="text-subtle h-4 w-4" name={icon} /> : null}
|
||||
<label className={labelClassname ? labelClassname : "text-subtle text-sm font-medium"}>{label}</label>
|
||||
</div>
|
||||
<div className="flex flex-1">
|
||||
{displayAsBadges ? (
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{value.map((v, idx) => {
|
||||
return coloredBadges ? (
|
||||
<Badge variant={badgeColors[idx % badgeColors.length]} key={v}>
|
||||
{v}
|
||||
</Badge>
|
||||
) : (
|
||||
<Badge variant="gray" key={v}>
|
||||
{v}
|
||||
</Badge>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
) : (
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="relative max-w-[280px]">
|
||||
<Tooltip content={value}>
|
||||
<div
|
||||
ref={scrollContainerRef}
|
||||
onScroll={handleScroll}
|
||||
className="no-scrollbar overflow-x-auto">
|
||||
<span className={`${valueClassname} whitespace-nowrap`}>{value}</span>
|
||||
</div>
|
||||
</Tooltip>
|
||||
{showLeftGradient && (
|
||||
<div className="from-default pointer-events-none absolute left-0 top-0 h-full w-8 bg-linear-to-r to-transparent" />
|
||||
)}
|
||||
{showRightGradient && (
|
||||
<div className="from-default pointer-events-none absolute right-0 top-0 h-full w-8 bg-linear-to-l to-transparent" />
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,502 @@
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { useSession } from "next-auth/react";
|
||||
import type { Dispatch } from "react";
|
||||
import { useMemo, useState } from "react";
|
||||
import { Controller, useForm, useFormContext } from "react-hook-form";
|
||||
import { z } from "zod";
|
||||
|
||||
import { TimezoneSelect } from "@calcom/features/components/timezone-select";
|
||||
import { timeZoneSchema } from "@calcom/lib/dayjs/timeZone.schema";
|
||||
import { emailSchema } from "@calcom/lib/emailSchema";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { MembershipRole } from "@calcom/prisma/enums";
|
||||
import { trpc, type RouterOutputs } from "@calcom/trpc/react";
|
||||
import { Avatar } from "@calcom/ui/components/avatar";
|
||||
import { Button } from "@calcom/ui/components/button";
|
||||
import { Divider } from "@calcom/ui/components/divider";
|
||||
import {
|
||||
InputField,
|
||||
TextAreaField,
|
||||
SelectField,
|
||||
Form,
|
||||
Label,
|
||||
TextField,
|
||||
ToggleGroup,
|
||||
} from "@calcom/ui/components/form";
|
||||
import { ImageUploader } from "@calcom/ui/components/image-uploader";
|
||||
import { SheetHeader, SheetBody, SheetFooter, SheetTitle } from "@calcom/ui/components/sheet";
|
||||
import { showToast } from "@calcom/ui/components/toast";
|
||||
|
||||
import type { UserTableAction } from "../types";
|
||||
import { useEditMode } from "./store";
|
||||
|
||||
interface MembershipOption {
|
||||
value: MembershipRole | string;
|
||||
label: string;
|
||||
isCustomRole?: boolean;
|
||||
}
|
||||
|
||||
const stringOrNumber = z.string().or(z.number());
|
||||
|
||||
const attributeSchema = z.object({
|
||||
id: z.string(),
|
||||
options: z
|
||||
.array(
|
||||
z.object({
|
||||
label: z.string().optional(),
|
||||
value: stringOrNumber.optional(),
|
||||
weight: z.number().optional(),
|
||||
createdByDSyncId: z.string().nullable().optional(),
|
||||
})
|
||||
)
|
||||
.optional(),
|
||||
value: stringOrNumber.optional(),
|
||||
});
|
||||
|
||||
const editSchema = z.object({
|
||||
name: z.string(),
|
||||
username: z.string(),
|
||||
email: emailSchema,
|
||||
avatar: z.string(),
|
||||
bio: z.string(),
|
||||
role: z.union([z.nativeEnum(MembershipRole), z.string()]),
|
||||
timeZone: timeZoneSchema,
|
||||
attributes: z.array(attributeSchema).optional(),
|
||||
});
|
||||
|
||||
type EditSchema = z.infer<typeof editSchema>;
|
||||
|
||||
export function EditForm({
|
||||
selectedUser,
|
||||
avatarUrl,
|
||||
domainUrl,
|
||||
dispatch,
|
||||
canEditAttributesForUser,
|
||||
}: {
|
||||
selectedUser: RouterOutputs["viewer"]["organizations"]["getUser"];
|
||||
avatarUrl: string;
|
||||
domainUrl: string;
|
||||
dispatch: Dispatch<UserTableAction>;
|
||||
canEditAttributesForUser?: boolean;
|
||||
}) {
|
||||
const setEditMode = useEditMode((state) => state.setEditMode);
|
||||
const [mutationLoading, setMutationLoading] = useState(false);
|
||||
const { t } = useLocale();
|
||||
const session = useSession();
|
||||
const org = session?.data?.user?.org;
|
||||
const utils = trpc.useUtils();
|
||||
const form = useForm<EditSchema>({
|
||||
resolver: zodResolver(editSchema),
|
||||
defaultValues: {
|
||||
name: selectedUser?.name ?? "",
|
||||
username: selectedUser?.username ?? "",
|
||||
email: selectedUser?.email ?? "",
|
||||
avatar: avatarUrl,
|
||||
bio: selectedUser?.bio ?? "",
|
||||
role: selectedUser?.role ?? "",
|
||||
timeZone: selectedUser?.timeZone ?? "",
|
||||
},
|
||||
});
|
||||
|
||||
const isOwner = org?.role === MembershipRole.OWNER;
|
||||
|
||||
const { data: teamRoles, isLoading: isLoadingRoles } = trpc.viewer.pbac.getTeamRoles.useQuery(
|
||||
// @ts-expect-error this query is only ran when we have an orgId so can ignore this
|
||||
{ teamId: org?.id },
|
||||
{
|
||||
enabled: !!org?.id, // Only enable the query when we have a valid team ID
|
||||
staleTime: 30000, // Cache for 30 seconds
|
||||
}
|
||||
);
|
||||
|
||||
const membershipOptions = useMemo<MembershipOption[]>(() => {
|
||||
// Add custom roles if they exist
|
||||
if (teamRoles?.length > 0) {
|
||||
const roles: MembershipOption[] = [];
|
||||
// Add custom roles
|
||||
teamRoles.forEach((role) => {
|
||||
roles.push({
|
||||
value: role.id,
|
||||
label: role.name,
|
||||
isCustomRole: true,
|
||||
});
|
||||
});
|
||||
|
||||
return roles;
|
||||
}
|
||||
|
||||
const options: MembershipOption[] = [
|
||||
{
|
||||
value: MembershipRole.MEMBER,
|
||||
label: t("member"),
|
||||
},
|
||||
{
|
||||
value: MembershipRole.ADMIN,
|
||||
label: t("admin"),
|
||||
},
|
||||
];
|
||||
|
||||
if (isOwner) {
|
||||
options.push({
|
||||
value: MembershipRole.OWNER,
|
||||
label: t("owner"),
|
||||
});
|
||||
}
|
||||
|
||||
return options;
|
||||
}, [t, isOwner, teamRoles]);
|
||||
|
||||
const mutation = trpc.viewer.organizations.updateUser.useMutation({
|
||||
onSuccess: () => {
|
||||
dispatch({ type: "CLOSE_MODAL" });
|
||||
utils.viewer.organizations.listMembers.invalidate();
|
||||
showToast(t("profile_updated_successfully"), "success");
|
||||
},
|
||||
onError: (error) => {
|
||||
showToast(error.message, "error");
|
||||
},
|
||||
onSettled: () => {
|
||||
/**
|
||||
* /We need to do this as the submit button lives out side
|
||||
* the form for some complicated reason so we can't relay on mutationState
|
||||
*/
|
||||
setMutationLoading(false);
|
||||
},
|
||||
});
|
||||
|
||||
const watchTimezone = form.watch("timeZone");
|
||||
|
||||
return (
|
||||
<>
|
||||
<Form
|
||||
form={form}
|
||||
className="flex h-full flex-col"
|
||||
handleSubmit={(values) => {
|
||||
setMutationLoading(true);
|
||||
mutation.mutate({
|
||||
userId: selectedUser?.id ?? "",
|
||||
role: values.role as MembershipRole,
|
||||
username: values.username,
|
||||
name: values.name,
|
||||
email: values.email,
|
||||
avatar: values.avatar,
|
||||
bio: values.bio,
|
||||
timeZone: values.timeZone,
|
||||
// @ts-expect-error they're there in local types but for some reason it errors?
|
||||
attributeOptions: values.attributes
|
||||
? { userId: selectedUser?.id ?? "", attributes: values.attributes }
|
||||
: undefined,
|
||||
});
|
||||
setEditMode(false);
|
||||
}}>
|
||||
<SheetHeader>
|
||||
<SheetTitle>{t("update_profile")}</SheetTitle>
|
||||
</SheetHeader>
|
||||
<SheetBody className="bg-cal-muted border-subtle mt-6 gap-4 rounded-xl border p-4">
|
||||
<div className="">
|
||||
<Controller
|
||||
control={form.control}
|
||||
name="avatar"
|
||||
render={({ field: { value } }) => (
|
||||
<div className="flex items-center">
|
||||
<Avatar alt={`${selectedUser?.name} avatar`} imageSrc={value} size="mdLg" />
|
||||
<div className="ml-4">
|
||||
<ImageUploader
|
||||
target="avatar"
|
||||
id="avatar-upload"
|
||||
buttonMsg={t("change_avatar")}
|
||||
buttonSize="sm"
|
||||
handleAvatarChange={(newAvatar) => {
|
||||
form.setValue("avatar", newAvatar, { shouldDirty: true });
|
||||
}}
|
||||
imageSrc={value || undefined}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
<Divider />
|
||||
<TextField label={t("name")} {...form.register("name")} className="mb-6" />
|
||||
<TextField label={t("username")} {...form.register("username")} className="mb-6" />
|
||||
<TextAreaField label={t("about")} {...form.register("bio")} className="min-h-24 mb-6" />
|
||||
<div className="mb-6">
|
||||
<Label>{t("role")}</Label>
|
||||
{teamRoles?.length > 0 ? (
|
||||
<SelectField
|
||||
defaultValue={membershipOptions.find(
|
||||
(option) => option.value === (selectedUser?.role ?? "MEMBER")
|
||||
)}
|
||||
value={membershipOptions.find((option) => option.value === form.watch("role"))}
|
||||
options={membershipOptions}
|
||||
onChange={(option) => {
|
||||
if (option) {
|
||||
form.setValue("role", option.value);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
) : (
|
||||
<ToggleGroup
|
||||
isFullWidth
|
||||
defaultValue={selectedUser?.role ?? "MEMBER"}
|
||||
value={form.watch("role")}
|
||||
options={membershipOptions}
|
||||
onValueChange={(value) => {
|
||||
form.setValue("role", value);
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
<div className="mb-6">
|
||||
<Label>{t("timezone")}</Label>
|
||||
<TimezoneSelect value={watchTimezone ?? "America/Los_Angeles"} />
|
||||
</div>
|
||||
{canEditAttributesForUser && (
|
||||
<>
|
||||
<Divider />
|
||||
<AttributesList selectedUserId={selectedUser?.id} />
|
||||
</>
|
||||
)}
|
||||
</SheetBody>
|
||||
<SheetFooter>
|
||||
<Button
|
||||
color="secondary"
|
||||
type="button"
|
||||
className="justify-center md:w-1/5"
|
||||
onClick={() => {
|
||||
setEditMode(false);
|
||||
}}>
|
||||
{t("cancel")}
|
||||
</Button>
|
||||
|
||||
<Button type="submit" className="w-full justify-center">
|
||||
{t("update")}
|
||||
</Button>
|
||||
</SheetFooter>
|
||||
</Form>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
type Attribute = z.infer<typeof attributeSchema>;
|
||||
|
||||
type DefaultValueType = {
|
||||
[key: `attributes.${number}`]: Attribute;
|
||||
};
|
||||
|
||||
function AttributesList(props: { selectedUserId: number }) {
|
||||
const { data: usersAttributes, isPending: usersAttributesPending } =
|
||||
trpc.viewer.attributes.getByUserId.useQuery({
|
||||
userId: props.selectedUserId,
|
||||
});
|
||||
const { data: attributes } = trpc.viewer.attributes.list.useQuery();
|
||||
const enabledAttributes = attributes?.filter((attr) => attr.enabled);
|
||||
|
||||
const { t } = useLocale();
|
||||
const { control, getFieldState } = useFormContext();
|
||||
|
||||
const getOptionsByAttributeId = (attributeId: string) => {
|
||||
const attribute = attributes?.find((attr) => attr.id === attributeId);
|
||||
return attribute
|
||||
? attribute.options.map((option) => ({
|
||||
value: option.id,
|
||||
label: option.value,
|
||||
}))
|
||||
: [];
|
||||
};
|
||||
|
||||
const defaultValues = useMemo<DefaultValueType>(() => {
|
||||
if (!usersAttributes || usersAttributesPending || !enabledAttributes) return {};
|
||||
|
||||
return enabledAttributes.reduce<DefaultValueType>((acc, enabledAttr, index) => {
|
||||
const attr = usersAttributes.find((attr) => attr.id === enabledAttr.id);
|
||||
const key = `attributes.${index}` as const;
|
||||
|
||||
if (!attr) {
|
||||
acc[key] = { id: enabledAttr.id, value: "", options: [] };
|
||||
} else if (attr.type === "MULTI_SELECT") {
|
||||
acc[key] = {
|
||||
id: attr.id,
|
||||
options: attr.options.map((option) => ({
|
||||
label: option.value,
|
||||
value: option.id,
|
||||
createdByDSyncId: option.createdByDSyncId ?? null,
|
||||
weight: option.weight ?? 100,
|
||||
})),
|
||||
};
|
||||
} else if (attr.type === "SINGLE_SELECT") {
|
||||
acc[key] = {
|
||||
id: attr.id,
|
||||
options: [
|
||||
{
|
||||
label: attr.options[0]?.value,
|
||||
value: attr.options[0]?.id,
|
||||
createdByDSyncId: attr.options[0]?.createdByDSyncId ?? null,
|
||||
weight: attr.options[0]?.weight ?? 100,
|
||||
},
|
||||
],
|
||||
};
|
||||
} else if (attr.type === "TEXT") {
|
||||
acc[key] = {
|
||||
id: attr.id,
|
||||
value: attr.options[0]?.value || "",
|
||||
};
|
||||
}
|
||||
return acc;
|
||||
}, {});
|
||||
}, [usersAttributes, usersAttributesPending, enabledAttributes]);
|
||||
|
||||
if (!enabledAttributes || !usersAttributes) return null;
|
||||
const attributeFieldState = getFieldState("attributes");
|
||||
|
||||
return (
|
||||
<div className="flex flex-col overflow-visible">
|
||||
<div className="flex flex-col gap-3 rounded-lg">
|
||||
{attributeFieldState.error && (
|
||||
<p className="text-error mb-2 block text-sm font-medium leading-none">
|
||||
{JSON.stringify(attributeFieldState.error)}
|
||||
</p>
|
||||
)}
|
||||
{enabledAttributes.map((attr, index) => (
|
||||
<Controller
|
||||
name={`attributes.${index}`}
|
||||
control={control}
|
||||
key={attr.id}
|
||||
defaultValue={defaultValues[`attributes.${index}`]}
|
||||
render={({ field: { value, ...field } }) => {
|
||||
const fieldValue = value as Attribute | undefined | null;
|
||||
return (
|
||||
<div className="flex w-full items-center justify-center" key={attr.id}>
|
||||
{["TEXT", "NUMBER"].includes(attr.type) && (
|
||||
<InputField
|
||||
{...field}
|
||||
containerClassName="w-full"
|
||||
labelClassName="text-emphasis mb-2 block text-sm font-medium leading-none"
|
||||
label={attr.name}
|
||||
type={attr.type === "TEXT" ? "text" : "number"}
|
||||
value={fieldValue?.value || ""}
|
||||
onChange={(e) => {
|
||||
field.onChange({
|
||||
id: attr.id,
|
||||
value: e.target.value,
|
||||
});
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
{["SINGLE_SELECT", "MULTI_SELECT"].includes(attr.type) && (
|
||||
<div className="w-full">
|
||||
<SelectField
|
||||
isDisabled={attr.isLocked}
|
||||
name={field.name}
|
||||
containerClassName="w-full"
|
||||
isMulti={attr.type === "MULTI_SELECT"}
|
||||
labelProps={{
|
||||
className: "text-emphasis mb-2 block text-sm font-medium leading-none",
|
||||
}}
|
||||
label={attr.name}
|
||||
options={getOptionsByAttributeId(attr.id)}
|
||||
value={attr.type === "MULTI_SELECT" ? fieldValue?.options : fieldValue?.options?.[0]}
|
||||
onChange={(value) => {
|
||||
if (!value) return;
|
||||
const valueAsArray = value instanceof Array ? value : [value];
|
||||
|
||||
const updatedOptions =
|
||||
attr.type === "MULTI_SELECT"
|
||||
? valueAsArray.map((v) => ({
|
||||
label: v.label,
|
||||
value: v.value,
|
||||
weight: v.weight || 100,
|
||||
}))
|
||||
: [
|
||||
{
|
||||
label: valueAsArray[0].label,
|
||||
value: valueAsArray[0].value,
|
||||
weight: valueAsArray[0].weight || 100,
|
||||
},
|
||||
];
|
||||
|
||||
field.onChange({
|
||||
id: attr.id,
|
||||
options: getOptionsEnsuringNotOwnedByCalcomNotRemoved({
|
||||
earlierOptions: fieldValue?.options || [],
|
||||
updatedOptions,
|
||||
}),
|
||||
});
|
||||
}}
|
||||
/>
|
||||
{attr.isWeightsEnabled && fieldValue?.options && (
|
||||
<div className="mt-3 stack-y-2">
|
||||
<Label>Weights</Label>
|
||||
<div className="">
|
||||
{fieldValue.options.map((option, idx) => {
|
||||
return (
|
||||
<>
|
||||
<div key={option.value} className="flex items-center justify-between">
|
||||
<Label
|
||||
htmlFor={`attributes.${index}.options.${idx}.weight`}
|
||||
className="text-subtle">
|
||||
{option.label}
|
||||
</Label>
|
||||
<InputField
|
||||
noLabel
|
||||
name={`attributes.${index}.options.${idx}.weight`}
|
||||
type="number"
|
||||
step={10}
|
||||
value={option.weight || 100}
|
||||
onChange={(e) => {
|
||||
const newWeight = parseFloat(e.target.value) || 1;
|
||||
const newOptions = fieldValue?.options?.map((opt, i) =>
|
||||
i === idx ? { ...opt, weight: newWeight } : opt
|
||||
);
|
||||
field.onChange({
|
||||
id: attr.id,
|
||||
options: newOptions,
|
||||
});
|
||||
}}
|
||||
addOnSuffix={<span className="text-subtle text-sm">%</span>}
|
||||
/>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
/**
|
||||
* Ensures that options that are not owned by cal.com are not removed
|
||||
* Such options are created by dsync and removed only through corresponding dsync
|
||||
*/
|
||||
function getOptionsEnsuringNotOwnedByCalcomNotRemoved<
|
||||
// Before assigning this option it can't have createdByDSyncId set
|
||||
TOptionToChoose extends { value: string | number | undefined },
|
||||
// Already set option can have createdByDSyncId set
|
||||
TOptionAlreadySet extends {
|
||||
value?: string | number | undefined;
|
||||
createdByDSyncId?: string | null | undefined;
|
||||
}
|
||||
>({
|
||||
earlierOptions,
|
||||
updatedOptions,
|
||||
}: {
|
||||
earlierOptions: TOptionAlreadySet[];
|
||||
updatedOptions: TOptionToChoose[];
|
||||
}) {
|
||||
const optionsNotOwnedByCalcom = earlierOptions.filter((option) => !!option.createdByDSyncId);
|
||||
|
||||
const newUniqueOptionsPlusNotOwnedByCalcom = [...optionsNotOwnedByCalcom, ...updatedOptions].filter(
|
||||
(option, index, self) => index === self.findIndex((o) => o.value === option.value && o.value)
|
||||
);
|
||||
|
||||
return newUniqueOptionsPlusNotOwnedByCalcom;
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
import type { Dispatch } from "react";
|
||||
import { shallow } from "zustand/shallow";
|
||||
|
||||
import { useOrgBranding } from "@calcom/ee/organizations/context/provider";
|
||||
import { WEBAPP_URL } from "@calcom/lib/constants";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
import { Avatar } from "@calcom/ui/components/avatar";
|
||||
import { Sheet, SheetContent, SheetBody, SheetHeader, SheetFooter } from "@calcom/ui/components/sheet";
|
||||
import { Loader } from "@calcom/ui/components/skeleton";
|
||||
|
||||
import type { UserTableAction, UserTableState } from "../types";
|
||||
import { DisplayInfo } from "./DisplayInfo";
|
||||
import { EditForm } from "./EditUserForm";
|
||||
import { OrganizationBanner } from "./OrganizationBanner";
|
||||
import { SheetFooterControls } from "./SheetFooterControls";
|
||||
import { useEditMode } from "./store";
|
||||
|
||||
function removeProtocol(url: string) {
|
||||
return url.replace(/^(https?:\/\/)/, "");
|
||||
}
|
||||
|
||||
export function EditUserSheet({
|
||||
state,
|
||||
dispatch,
|
||||
canViewAttributes,
|
||||
canEditAttributesForUser,
|
||||
canChangeMemberRole,
|
||||
}: {
|
||||
state: UserTableState;
|
||||
dispatch: Dispatch<UserTableAction>;
|
||||
canViewAttributes?: boolean;
|
||||
canEditAttributesForUser?: boolean;
|
||||
canChangeMemberRole?: boolean;
|
||||
}) {
|
||||
const { t } = useLocale();
|
||||
const { user: selectedUser } = state.editSheet;
|
||||
const orgBranding = useOrgBranding();
|
||||
const [editMode, setEditMode] = useEditMode((state) => [state.editMode, state.setEditMode], shallow);
|
||||
const { data: loadedUser, isPending } = trpc.viewer.organizations.getUser.useQuery(
|
||||
{
|
||||
userId: selectedUser?.id,
|
||||
},
|
||||
{
|
||||
enabled: !!selectedUser?.id,
|
||||
}
|
||||
);
|
||||
|
||||
const { data: usersAttributes, isPending: usersAttributesPending } =
|
||||
trpc.viewer.attributes.getByUserId.useQuery(
|
||||
{
|
||||
// @ts-expect-error We know it exists as it is only called when selectedUser is defined
|
||||
userId: selectedUser?.id,
|
||||
},
|
||||
{
|
||||
enabled: !!selectedUser?.id && !!canViewAttributes,
|
||||
}
|
||||
);
|
||||
|
||||
const avatarURL = `${orgBranding?.fullDomain ?? WEBAPP_URL}/${loadedUser?.username}/avatar.png`;
|
||||
|
||||
const schedulesNames = loadedUser?.schedules && loadedUser?.schedules.map((s) => s.name);
|
||||
const teamNames =
|
||||
loadedUser?.teams && loadedUser?.teams.map((t) => `${t.name} ${!t.accepted ? "(pending)" : ""}`);
|
||||
|
||||
return (
|
||||
<Sheet
|
||||
open={true}
|
||||
onOpenChange={() => {
|
||||
setEditMode(false);
|
||||
dispatch({ type: "CLOSE_MODAL" });
|
||||
}}>
|
||||
<SheetContent className="bg-default">
|
||||
{!isPending && loadedUser ? (
|
||||
<>
|
||||
{!editMode ? (
|
||||
<>
|
||||
<SheetHeader showCloseButton={false} className="w-full">
|
||||
<div className="border-sublte bg-default w-full rounded-xl border p-4">
|
||||
<OrganizationBanner />
|
||||
<div className="bg-default ml-3 w-fit translate-y-[-50%] rounded-full p-1 ring-1 ring-[#0000000F]">
|
||||
<Avatar asChild size="lg" alt={`${loadedUser?.name} avatar`} imageSrc={avatarURL} />
|
||||
</div>
|
||||
<h2 className="text-emphasis font-sans text-2xl font-semibold">
|
||||
{loadedUser?.name || "Nameless User"}
|
||||
</h2>
|
||||
<p className="text-subtle max-h-[3em] overflow-hidden text-ellipsis text-sm font-normal">
|
||||
{loadedUser?.bio || "This user does not have a bio..."}
|
||||
</p>
|
||||
</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={removeProtocol(
|
||||
`${orgBranding?.fullDomain ?? WEBAPP_URL}/${loadedUser?.username}`
|
||||
)}
|
||||
icon="external-link"
|
||||
/>
|
||||
<DisplayInfo label={t("email")} value={loadedUser?.email ?? ""} icon="at-sign" />
|
||||
<DisplayInfo label={t("role")} value={[loadedUser?.role ?? ""]} icon="fingerprint" />
|
||||
<DisplayInfo label={t("timezone")} value={loadedUser?.timeZone ?? ""} icon="clock" />
|
||||
<DisplayInfo
|
||||
label={t("teams")}
|
||||
value={!teamNames || teamNames.length === 0 ? "" : teamNames}
|
||||
icon="users"
|
||||
coloredBadges
|
||||
/>
|
||||
<DisplayInfo
|
||||
label={t("availability")}
|
||||
value={!schedulesNames || schedulesNames.length === 0 ? "" : schedulesNames}
|
||||
icon="calendar"
|
||||
/>
|
||||
</div>
|
||||
{canViewAttributes && usersAttributes && usersAttributes?.length > 0 && (
|
||||
<div className="mt-4 flex flex-col">
|
||||
<h3 className="text-emphasis mb-5 text-base font-semibold">{t("attributes")}</h3>
|
||||
<div className="stack-y-4 flex flex-col">
|
||||
{usersAttributes.map((attribute, index) => (
|
||||
<>
|
||||
<DisplayInfo
|
||||
key={index}
|
||||
label={attribute.name}
|
||||
value={
|
||||
["TEXT", "NUMBER", "SINGLE_SELECT"].includes(attribute.type)
|
||||
? attribute.options[0].value
|
||||
: attribute.options.map((option) => option.value)
|
||||
}
|
||||
/>
|
||||
</>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</SheetBody>
|
||||
<SheetFooter>
|
||||
<SheetFooterControls
|
||||
canEditAttributesForUser={canEditAttributesForUser}
|
||||
canChangeMemberRole={canChangeMemberRole}
|
||||
/>
|
||||
</SheetFooter>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<EditForm
|
||||
selectedUser={loadedUser}
|
||||
avatarUrl={loadedUser.avatarUrl ?? avatarURL}
|
||||
domainUrl={orgBranding?.fullDomain ?? WEBAPP_URL}
|
||||
dispatch={dispatch}
|
||||
canEditAttributesForUser={canEditAttributesForUser}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
) : (
|
||||
<Loader />
|
||||
)}
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
|
||||
export function OrganizationBanner() {
|
||||
const {
|
||||
data: currentOrganisation,
|
||||
isPending: isPendingOrg,
|
||||
error,
|
||||
} = trpc.viewer.organizations.listCurrent.useQuery(undefined, {});
|
||||
|
||||
return (
|
||||
<>
|
||||
<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: currentOrganisation && currentOrganisation?.bannerUrl ? "auto" : "110px",
|
||||
}}>
|
||||
{currentOrganisation && currentOrganisation?.bannerUrl && (
|
||||
<img src={currentOrganisation?.bannerUrl} alt="Organization Banner" className="rounded-lg" />
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { Button } from "@calcom/ui/components/button";
|
||||
import { SheetClose } from "@calcom/ui/components/sheet";
|
||||
|
||||
import { useEditMode } from "./store";
|
||||
|
||||
function EditModeFooter() {
|
||||
const { t } = useLocale();
|
||||
const setEditMode = useEditMode((state) => state.setEditMode);
|
||||
const isPending = useEditMode((state) => state.mutationLoading);
|
||||
|
||||
return (
|
||||
<>
|
||||
<Button
|
||||
color="secondary"
|
||||
type="button"
|
||||
className="justify-center"
|
||||
onClick={() => {
|
||||
setEditMode(false);
|
||||
}}>
|
||||
{t("cancel")}
|
||||
</Button>
|
||||
|
||||
<Button type="submit" loading={isPending} className="justify-center">
|
||||
{t("update")}
|
||||
</Button>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function MoreInfoFooter({
|
||||
canEditAttributesForUser,
|
||||
canChangeMemberRole,
|
||||
}: {
|
||||
canEditAttributesForUser?: boolean;
|
||||
canChangeMemberRole?: boolean;
|
||||
}) {
|
||||
const { t } = useLocale();
|
||||
const setEditMode = useEditMode((state) => state.setEditMode);
|
||||
|
||||
// Show edit button if user can change member role (edit user info) or edit attributes
|
||||
const canEdit = canChangeMemberRole || canEditAttributesForUser;
|
||||
|
||||
return (
|
||||
<>
|
||||
<SheetClose asChild>
|
||||
<Button color="secondary" type="button" className="justify-center">
|
||||
{t("close")}
|
||||
</Button>
|
||||
</SheetClose>
|
||||
{canEdit && (
|
||||
<Button
|
||||
type="button"
|
||||
className="justify-center"
|
||||
onClick={() => {
|
||||
setEditMode(true);
|
||||
}}
|
||||
key="EDIT_BUTTON"
|
||||
StartIcon="pencil">
|
||||
{t("edit")}
|
||||
</Button>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export function SheetFooterControls({
|
||||
canEditAttributesForUser,
|
||||
canChangeMemberRole,
|
||||
}: {
|
||||
canEditAttributesForUser?: boolean;
|
||||
canChangeMemberRole?: boolean;
|
||||
}) {
|
||||
const editMode = useEditMode((state) => state.editMode);
|
||||
return (
|
||||
<>
|
||||
{editMode ? (
|
||||
<EditModeFooter />
|
||||
) : (
|
||||
<MoreInfoFooter
|
||||
canEditAttributesForUser={canEditAttributesForUser}
|
||||
canChangeMemberRole={canChangeMemberRole}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import { create } from "zustand";
|
||||
|
||||
interface EditModeState {
|
||||
editMode: boolean;
|
||||
setEditMode: (editMode: boolean) => void;
|
||||
mutationLoading: boolean;
|
||||
setMutationLoading: (loading: boolean) => void;
|
||||
}
|
||||
|
||||
export const useEditMode = create<EditModeState>((set) => ({
|
||||
editMode: false,
|
||||
setEditMode: (editMode) => set({ editMode }),
|
||||
mutationLoading: false,
|
||||
setMutationLoading: (loading) => set({ mutationLoading: loading }),
|
||||
}));
|
||||
@@ -0,0 +1,52 @@
|
||||
import { signIn, useSession } from "next-auth/react";
|
||||
import type { Dispatch } from "react";
|
||||
|
||||
import { Dialog } from "@calcom/features/components/controlled-dialog";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { Button } from "@calcom/ui/components/button";
|
||||
import { DialogContent, DialogFooter, DialogClose } from "@calcom/ui/components/dialog";
|
||||
|
||||
import type { UserTableAction, UserTableState } from "./types";
|
||||
|
||||
export function ImpersonationMemberModal(props: {
|
||||
state: UserTableState;
|
||||
dispatch: Dispatch<UserTableAction>;
|
||||
}) {
|
||||
const { t } = useLocale();
|
||||
const { data: session } = useSession();
|
||||
const teamId = session?.user.org?.id;
|
||||
const user = props.state.impersonateMember.user;
|
||||
|
||||
if (!user || !teamId) return null;
|
||||
|
||||
return (
|
||||
<Dialog
|
||||
open={true}
|
||||
onOpenChange={() =>
|
||||
props.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: user.email,
|
||||
teamId: teamId,
|
||||
});
|
||||
props.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>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
import { useSession } from "next-auth/react";
|
||||
import type { Dispatch } from "react";
|
||||
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { CreationSource } from "@calcom/prisma/enums";
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
import { showToast } from "@calcom/ui/components/toast";
|
||||
import usePlatformMe from "@calcom/web/components/settings/platform/hooks/usePlatformMe";
|
||||
|
||||
import MemberInvitationModal from "~/ee/teams/components/MemberInvitationModal";
|
||||
|
||||
import type { UserTableAction } from "./types";
|
||||
|
||||
interface Props {
|
||||
dispatch: Dispatch<UserTableAction>;
|
||||
}
|
||||
|
||||
export function InviteMemberModal(props: Props) {
|
||||
const { data: session } = useSession();
|
||||
const { data: platformUser } = usePlatformMe();
|
||||
const utils = trpc.useUtils();
|
||||
const { t, i18n } = useLocale();
|
||||
const inviteMemberMutation = trpc.viewer.teams.inviteMember.useMutation({
|
||||
async onSuccess(data) {
|
||||
props.dispatch({ type: "CLOSE_MODAL" });
|
||||
// Need to figure out if invalidating here is the right approach - we could have already
|
||||
// loaded a bunch of data and idk how pagination works with invalidation. We may need to use
|
||||
// Optimistic updates here instead.
|
||||
await utils.viewer.organizations.listMembers.invalidate();
|
||||
|
||||
if (Array.isArray(data.usernameOrEmail)) {
|
||||
showToast(
|
||||
t("email_invite_team_bulk", {
|
||||
userCount: data.numUsersInvited,
|
||||
}),
|
||||
"success"
|
||||
);
|
||||
} else {
|
||||
showToast(
|
||||
t("email_invite_team", {
|
||||
email: data.usernameOrEmail,
|
||||
}),
|
||||
"success"
|
||||
);
|
||||
}
|
||||
},
|
||||
onError: (error) => {
|
||||
showToast(error.message, "error");
|
||||
},
|
||||
});
|
||||
|
||||
const orgId = session?.user.org?.id ?? platformUser?.organizationId;
|
||||
|
||||
if (!orgId) return null;
|
||||
|
||||
return (
|
||||
<MemberInvitationModal
|
||||
members={[]}
|
||||
isOpen={true}
|
||||
onExit={() => {
|
||||
props.dispatch({
|
||||
type: "CLOSE_MODAL",
|
||||
});
|
||||
}}
|
||||
teamId={orgId}
|
||||
isOrg={true}
|
||||
isPending={inviteMemberMutation.isPending}
|
||||
onSubmit={(values) => {
|
||||
inviteMemberMutation.mutate({
|
||||
teamId: orgId,
|
||||
language: i18n.language,
|
||||
role: values.role,
|
||||
usernameOrEmail: values.emailOrUsername,
|
||||
isPlatform: platformUser?.organization.isPlatform,
|
||||
creationSource: CreationSource.WEBAPP,
|
||||
});
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,321 @@
|
||||
"use client";
|
||||
|
||||
import { keepPreviousData } from "@tanstack/react-query";
|
||||
import { getCoreRowModel, getSortedRowModel, useReactTable, type ColumnDef } from "@tanstack/react-table";
|
||||
import { useMemo, useReducer, useState } from "react";
|
||||
|
||||
import {
|
||||
DataTableWrapper,
|
||||
DataTableProvider,
|
||||
DataTableToolbar,
|
||||
DataTableSelectionBar,
|
||||
DataTableFilters,
|
||||
DataTableSegment,
|
||||
useColumnFilters,
|
||||
useDataTable,
|
||||
} from "@calcom/features/data-table";
|
||||
import { useSegments } from "@calcom/features/data-table/hooks/useSegments";
|
||||
import { getUserAvatarUrl } from "@calcom/lib/getAvatarUrl";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
import { Avatar } from "@calcom/ui/components/avatar";
|
||||
import { Badge } from "@calcom/ui/components/badge";
|
||||
import { Checkbox } from "@calcom/ui/components/form";
|
||||
import { SkeletonText } from "@calcom/ui/components/skeleton";
|
||||
|
||||
import { DeleteBulkUsers } from "./BulkActions/DeleteBulkUsers";
|
||||
import { DeleteMemberModal } from "./DeleteMemberModal";
|
||||
import type { UserTableState, UserTableAction, PlatformManagedUserTableUser } from "./types";
|
||||
|
||||
const initialState: UserTableState = {
|
||||
changeMemberRole: {
|
||||
showModal: false,
|
||||
},
|
||||
deleteMember: {
|
||||
showModal: false,
|
||||
},
|
||||
impersonateMember: {
|
||||
showModal: false,
|
||||
},
|
||||
inviteMember: {
|
||||
showModal: false,
|
||||
},
|
||||
editSheet: {
|
||||
showModal: false,
|
||||
},
|
||||
};
|
||||
|
||||
const initalColumnVisibility = {
|
||||
select: true,
|
||||
member: true,
|
||||
role: true,
|
||||
teams: true,
|
||||
actions: true,
|
||||
};
|
||||
|
||||
type PlatformManagedUsersTableProps = {
|
||||
oAuthClientId: string;
|
||||
};
|
||||
|
||||
export function PlatformManagedUsersTable(props: PlatformManagedUsersTableProps) {
|
||||
return (
|
||||
<DataTableProvider
|
||||
useSegments={useSegments}
|
||||
defaultPageSize={25}
|
||||
tableIdentifier={`platform-managed-users-${props.oAuthClientId}`}>
|
||||
<UserListTableContent {...props} />
|
||||
</DataTableProvider>
|
||||
);
|
||||
}
|
||||
|
||||
function UserListTableContent({ oAuthClientId }: PlatformManagedUsersTableProps) {
|
||||
const { t } = useLocale();
|
||||
|
||||
const [state, dispatch] = useReducer(reducer, initialState);
|
||||
const [rowSelection, setRowSelection] = useState({});
|
||||
|
||||
const columnFilters = useColumnFilters();
|
||||
|
||||
const { pageIndex, pageSize, searchTerm } = useDataTable();
|
||||
const limit = pageSize;
|
||||
const offset = pageIndex * pageSize;
|
||||
|
||||
const { data, isPending } = trpc.viewer.organizations.listMembers.useQuery(
|
||||
{
|
||||
limit,
|
||||
offset,
|
||||
searchTerm,
|
||||
filters: columnFilters,
|
||||
oAuthClientId,
|
||||
},
|
||||
{
|
||||
placeholderData: keepPreviousData,
|
||||
enabled: !!oAuthClientId,
|
||||
}
|
||||
);
|
||||
|
||||
const totalRowCount = data?.meta?.totalRowCount ?? 0;
|
||||
|
||||
//we must flatten the array of arrays from the useInfiniteQuery hook
|
||||
const flatData = useMemo(() => data?.rows ?? [], [data]) as PlatformManagedUserTableUser[];
|
||||
|
||||
const columns = useMemo(() => {
|
||||
const cols: ColumnDef<PlatformManagedUserTableUser>[] = [
|
||||
// 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,
|
||||
size: 200,
|
||||
header: () => {
|
||||
return t("managed_users");
|
||||
},
|
||||
cell: ({ row }) => {
|
||||
if (isPending) {
|
||||
return <SkeletonText className="h-6 w-1/4" />;
|
||||
}
|
||||
const { username, email, avatarUrl } = row.original;
|
||||
return (
|
||||
<div className="flex items-center gap-2">
|
||||
<Avatar
|
||||
size="sm"
|
||||
alt={username || email}
|
||||
imageSrc={getUserAvatarUrl({
|
||||
avatarUrl,
|
||||
})}
|
||||
/>
|
||||
<div className="">
|
||||
<div
|
||||
data-testid={`member-${username}-username`}
|
||||
className="text-emphasis text-sm font-medium leading-none">
|
||||
{username || "No username"}
|
||||
</div>
|
||||
<div
|
||||
data-testid={`member-${username}-email`}
|
||||
className="text-subtle mt-1 text-sm leading-none">
|
||||
{email}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "role",
|
||||
accessorFn: (data) => data.role,
|
||||
header: t("role"),
|
||||
size: 100,
|
||||
cell: ({ row, table }) => {
|
||||
if (isPending) {
|
||||
return <SkeletonText className="h-6 w-1/4" />;
|
||||
}
|
||||
const { role, username } = row.original;
|
||||
return (
|
||||
<Badge
|
||||
data-testid={`member-${username}-role`}
|
||||
variant={role === "MEMBER" ? "gray" : "blue"}
|
||||
onClick={() => {
|
||||
table.getColumn("role")?.setFilterValue([role]);
|
||||
}}>
|
||||
{role}
|
||||
</Badge>
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "teams",
|
||||
accessorFn: (data) => data.teams.map((team) => team.name),
|
||||
header: t("teams"),
|
||||
size: 140,
|
||||
cell: ({ row, table }) => {
|
||||
if (isPending) {
|
||||
return <SkeletonText className="h-6 w-1/4" />;
|
||||
}
|
||||
const { teams, accepted, email, username } = row.original;
|
||||
// TODO: Implement click to filter
|
||||
return (
|
||||
<div className="flex h-full flex-wrap items-center gap-2">
|
||||
{accepted ? null : (
|
||||
<Badge
|
||||
data-testid2={`member-${username}-pending`}
|
||||
variant="red"
|
||||
className="text-xs"
|
||||
data-testid={`email-${email.replace("@", "")}-pending`}
|
||||
onClick={() => {
|
||||
table.getColumn("role")?.setFilterValue(["PENDING"]);
|
||||
}}>
|
||||
Pending
|
||||
</Badge>
|
||||
)}
|
||||
|
||||
{teams.map((team) => (
|
||||
<Badge
|
||||
key={team.id}
|
||||
variant="gray"
|
||||
onClick={() => {
|
||||
table.getColumn("teams")?.setFilterValue([team.name]);
|
||||
}}>
|
||||
{team.name}
|
||||
</Badge>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
},
|
||||
},
|
||||
];
|
||||
return cols;
|
||||
}, [isPending]);
|
||||
|
||||
const table = useReactTable({
|
||||
data: flatData,
|
||||
columns,
|
||||
enableRowSelection: true,
|
||||
debugTable: true,
|
||||
manualPagination: true,
|
||||
initialState: {
|
||||
columnVisibility: initalColumnVisibility,
|
||||
columnPinning: {
|
||||
left: ["select", "member"],
|
||||
},
|
||||
},
|
||||
defaultColumn: {
|
||||
size: 150,
|
||||
},
|
||||
state: {
|
||||
columnFilters,
|
||||
rowSelection,
|
||||
},
|
||||
getCoreRowModel: getCoreRowModel(),
|
||||
getSortedRowModel: getSortedRowModel(),
|
||||
onRowSelectionChange: setRowSelection,
|
||||
getRowId: (row) => `${row.id}`,
|
||||
});
|
||||
|
||||
function reducer(state: UserTableState, action: UserTableAction): UserTableState {
|
||||
switch (action.type) {
|
||||
case "SET_CHANGE_MEMBER_ROLE_ID":
|
||||
return { ...state, changeMemberRole: action.payload };
|
||||
case "SET_DELETE_ID":
|
||||
return { ...state, deleteMember: action.payload };
|
||||
case "SET_IMPERSONATE_ID":
|
||||
return { ...state, impersonateMember: action.payload };
|
||||
case "INVITE_MEMBER":
|
||||
return { ...state, inviteMember: action.payload };
|
||||
case "EDIT_USER_SHEET":
|
||||
return { ...state, editSheet: action.payload };
|
||||
case "CLOSE_MODAL":
|
||||
return {
|
||||
...state,
|
||||
changeMemberRole: { showModal: false },
|
||||
deleteMember: { showModal: false },
|
||||
impersonateMember: { showModal: false },
|
||||
inviteMember: { showModal: false },
|
||||
editSheet: { showModal: false },
|
||||
};
|
||||
default:
|
||||
return state;
|
||||
}
|
||||
}
|
||||
|
||||
const numberOfSelectedRows = useMemo(() => table.getSelectedRowModel().rows.length, [table]);
|
||||
|
||||
return (
|
||||
<>
|
||||
<DataTableWrapper<PlatformManagedUserTableUser>
|
||||
testId="managed-user-list-data-table"
|
||||
table={table}
|
||||
isPending={isPending}
|
||||
totalRowCount={data?.meta?.totalRowCount}
|
||||
paginationMode="standard"
|
||||
ToolbarLeft={
|
||||
<>
|
||||
<DataTableToolbar.SearchBar className="sm:max-w-64 max-w-full" />
|
||||
<DataTableFilters.ColumnVisibilityButton table={table} />
|
||||
<DataTableFilters.FilterBar table={table} />
|
||||
</>
|
||||
}
|
||||
ToolbarRight={
|
||||
<>
|
||||
<DataTableFilters.ClearFiltersButton />
|
||||
<DataTableSegment.SaveButton />
|
||||
<DataTableSegment.Select />
|
||||
</>
|
||||
}>
|
||||
{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>
|
||||
<DeleteBulkUsers
|
||||
users={table.getSelectedRowModel().flatRows.map((row) => row.original)}
|
||||
onRemove={() => table.toggleAllPageRowsSelected(false)}
|
||||
/>
|
||||
</DataTableSelectionBar.Root>
|
||||
)}
|
||||
</DataTableWrapper>
|
||||
{state.deleteMember.showModal && <DeleteMemberModal state={state} dispatch={dispatch} />}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,707 @@
|
||||
"use client";
|
||||
|
||||
import { keepPreviousData } from "@tanstack/react-query";
|
||||
import { getCoreRowModel, getSortedRowModel, useReactTable, type ColumnDef } from "@tanstack/react-table";
|
||||
import { useSession } from "next-auth/react";
|
||||
import { usePathname } from "next/navigation";
|
||||
import { useQueryState, parseAsBoolean } from "nuqs";
|
||||
import { useMemo, useReducer, useState } from "react";
|
||||
import { createPortal } from "react-dom";
|
||||
import posthog from "posthog-js";
|
||||
|
||||
import { checkAdminOrOwner } from "@calcom/features/auth/lib/checkAdminOrOwner";
|
||||
import {
|
||||
DataTableProvider,
|
||||
DataTableWrapper,
|
||||
DataTableToolbar,
|
||||
DataTableSelectionBar,
|
||||
DataTableFilters,
|
||||
DataTableSegment,
|
||||
useColumnFilters,
|
||||
ColumnFilterType,
|
||||
convertFacetedValuesToMap,
|
||||
useDataTable,
|
||||
} from "@calcom/features/data-table";
|
||||
import { useSegments } from "@calcom/features/data-table/hooks/useSegments";
|
||||
import { useOrgBranding } from "@calcom/features/ee/organizations/context/provider";
|
||||
import {
|
||||
generateCsvRawForMembersTable,
|
||||
generateHeaderFromReactTable,
|
||||
} from "@calcom/features/users/lib/UserListTableUtils";
|
||||
import { WEBAPP_URL } from "@calcom/lib/constants";
|
||||
import { downloadAsCsv } from "@calcom/lib/csvUtils";
|
||||
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 classNames from "@calcom/ui/classNames";
|
||||
import { Avatar } from "@calcom/ui/components/avatar";
|
||||
import { Badge } from "@calcom/ui/components/badge";
|
||||
import { Checkbox } from "@calcom/ui/components/form";
|
||||
import { showToast } from "@calcom/ui/components/toast";
|
||||
import { useGetUserAttributes } from "@calcom/web/components/settings/platform/hooks/useGetUserAttributes";
|
||||
|
||||
import { DeleteBulkUsers } from "./BulkActions/DeleteBulkUsers";
|
||||
import { DynamicLink } from "./BulkActions/DynamicLink";
|
||||
import { EventTypesList } from "./BulkActions/EventTypesList";
|
||||
import { MassAssignAttributesBulkAction } from "./BulkActions/MassAssignAttributes";
|
||||
import { TeamListBulkAction } from "./BulkActions/TeamList";
|
||||
import { ChangeUserRoleModal } from "./ChangeUserRoleModal";
|
||||
import { DeleteMemberModal } from "./DeleteMemberModal";
|
||||
import { EditUserSheet } from "./EditSheet/EditUserSheet";
|
||||
import { ImpersonationMemberModal } from "./ImpersonationMemberModal";
|
||||
import { InviteMemberModal } from "./InviteMemberModal";
|
||||
import { TableActions } from "./UserTableActions";
|
||||
import type { UserTableState, UserTableAction, UserTableUser, MemberPermissions } from "./types";
|
||||
|
||||
const initialState: UserTableState = {
|
||||
changeMemberRole: {
|
||||
showModal: false,
|
||||
},
|
||||
deleteMember: {
|
||||
showModal: false,
|
||||
},
|
||||
impersonateMember: {
|
||||
showModal: false,
|
||||
},
|
||||
inviteMember: {
|
||||
showModal: false,
|
||||
},
|
||||
editSheet: {
|
||||
showModal: false,
|
||||
},
|
||||
};
|
||||
|
||||
const initalColumnVisibility = {
|
||||
select: true,
|
||||
member: true,
|
||||
role: true,
|
||||
teams: true,
|
||||
createdAt: false,
|
||||
updatedAt: false,
|
||||
twoFactorEnabled: false,
|
||||
actions: true,
|
||||
};
|
||||
|
||||
function reducer(state: UserTableState, action: UserTableAction): UserTableState {
|
||||
switch (action.type) {
|
||||
case "SET_CHANGE_MEMBER_ROLE_ID":
|
||||
return { ...state, changeMemberRole: action.payload };
|
||||
case "SET_DELETE_ID":
|
||||
return { ...state, deleteMember: action.payload };
|
||||
case "SET_IMPERSONATE_ID":
|
||||
return { ...state, impersonateMember: action.payload };
|
||||
case "INVITE_MEMBER":
|
||||
return { ...state, inviteMember: action.payload };
|
||||
case "EDIT_USER_SHEET":
|
||||
return { ...state, editSheet: action.payload };
|
||||
case "CLOSE_MODAL":
|
||||
return {
|
||||
...state,
|
||||
changeMemberRole: { showModal: false },
|
||||
deleteMember: { showModal: false },
|
||||
impersonateMember: { showModal: false },
|
||||
inviteMember: { showModal: false },
|
||||
editSheet: { showModal: false },
|
||||
};
|
||||
default:
|
||||
return state;
|
||||
}
|
||||
}
|
||||
|
||||
export type UserListTableProps = {
|
||||
org: RouterOutputs["viewer"]["organizations"]["listCurrent"];
|
||||
teams: RouterOutputs["viewer"]["organizations"]["getTeams"];
|
||||
attributes?: RouterOutputs["viewer"]["attributes"]["list"];
|
||||
facetedTeamValues?: {
|
||||
roles: { id: string; name: string }[];
|
||||
teams: RouterOutputs["viewer"]["organizations"]["getTeams"];
|
||||
attributes: {
|
||||
id: string;
|
||||
name: string;
|
||||
options: {
|
||||
value: string;
|
||||
}[];
|
||||
}[];
|
||||
};
|
||||
permissions?: MemberPermissions;
|
||||
};
|
||||
|
||||
export function UserListTable(props: UserListTableProps) {
|
||||
const pathname = usePathname();
|
||||
if (!pathname) return null;
|
||||
return (
|
||||
<DataTableProvider tableIdentifier={pathname} useSegments={useSegments} defaultPageSize={25}>
|
||||
<UserListTableContent {...props} />
|
||||
</DataTableProvider>
|
||||
);
|
||||
}
|
||||
|
||||
function UserListTableContent({
|
||||
org,
|
||||
attributes,
|
||||
teams,
|
||||
facetedTeamValues,
|
||||
permissions,
|
||||
}: UserListTableProps) {
|
||||
const [dynamicLinkVisible, setDynamicLinkVisible] = useQueryState("dynamicLink", parseAsBoolean);
|
||||
const orgBranding = useOrgBranding();
|
||||
const domain = orgBranding?.fullDomain ?? WEBAPP_URL;
|
||||
const { t } = useLocale();
|
||||
|
||||
const { data: session } = useSession();
|
||||
const { isPlatformUser } = useGetUserAttributes();
|
||||
const [state, dispatch] = useReducer(reducer, initialState);
|
||||
const [isDownloading, setIsDownloading] = useState(false);
|
||||
const [rowSelection, setRowSelection] = useState({});
|
||||
|
||||
const columnFilters = useColumnFilters();
|
||||
|
||||
const { limit, offset, searchTerm, ctaContainerRef } = useDataTable();
|
||||
|
||||
const { data, isPending } = trpc.viewer.organizations.listMembers.useQuery(
|
||||
{
|
||||
limit,
|
||||
offset,
|
||||
searchTerm,
|
||||
expand: ["attributes"],
|
||||
filters: columnFilters,
|
||||
},
|
||||
{
|
||||
placeholderData: keepPreviousData,
|
||||
}
|
||||
);
|
||||
|
||||
const adminOrOwner = checkAdminOrOwner(org?.user?.role);
|
||||
|
||||
//we must flatten the array of arrays from the useInfiniteQuery hook
|
||||
const flatData = useMemo<UserTableUser[]>(() => data?.rows ?? [], [data]);
|
||||
|
||||
const memorisedColumns = useMemo(() => {
|
||||
// Use PBAC permissions if available, otherwise fall back to role-based check
|
||||
const tablePermissions = {
|
||||
canEdit: permissions?.canChangeMemberRole ?? adminOrOwner,
|
||||
canRemove: permissions?.canRemove ?? adminOrOwner,
|
||||
canResendInvitation: permissions?.canInvite ?? adminOrOwner,
|
||||
canImpersonate: permissions?.canImpersonate ?? adminOrOwner,
|
||||
};
|
||||
const generateAttributeColumns = () => {
|
||||
if (!attributes?.length) {
|
||||
return [];
|
||||
}
|
||||
const attributeColumns: ColumnDef<UserTableUser>[] =
|
||||
attributes?.map((attribute) => {
|
||||
// TODO: We need to normalize AttributeOption table first
|
||||
// so that we can have `number_value` column for numeric operations.
|
||||
// Currently, `value` column is used for both text and number attributes.
|
||||
//
|
||||
// const isNumber = attribute.type === "NUMBER";
|
||||
const isNumber = false;
|
||||
const isText = attribute.type === "TEXT";
|
||||
const isSingleSelect = attribute.type === "SINGLE_SELECT";
|
||||
// const isMultiSelect = attribute.type === "MULTI_SELECT";
|
||||
const filterType = isNumber
|
||||
? ColumnFilterType.NUMBER
|
||||
: isText
|
||||
? ColumnFilterType.TEXT
|
||||
: isSingleSelect
|
||||
? ColumnFilterType.SINGLE_SELECT
|
||||
: ColumnFilterType.MULTI_SELECT;
|
||||
|
||||
return {
|
||||
id: attribute.id,
|
||||
header: attribute.name,
|
||||
meta: {
|
||||
filter: { type: filterType },
|
||||
},
|
||||
size: 120,
|
||||
accessorFn: (data) => data.attributes?.find((attr) => attr.attributeId === attribute.id)?.value,
|
||||
cell: ({ row }) => {
|
||||
const attributeValues = row.original.attributes?.filter(
|
||||
(attr) => attr.attributeId === attribute.id
|
||||
);
|
||||
if (attributeValues?.length === 0) return null;
|
||||
return (
|
||||
<div className={classNames(isNumber ? "flex w-full justify-center" : "flex flex-wrap")}>
|
||||
{attributeValues?.map((attributeValue) => {
|
||||
const isAGroupOption = attributeValue.contains?.length > 0;
|
||||
const suffix = attribute.isWeightsEnabled
|
||||
? `${attributeValue.weight || 100}%`
|
||||
: undefined;
|
||||
return (
|
||||
<div className="mr-1 inline-flex shrink-0" key={attributeValue.id}>
|
||||
<Badge
|
||||
variant={isAGroupOption ? "orange" : "gray"}
|
||||
className={classNames(suffix && "rounded-r-none")}>
|
||||
{attributeValue.value}
|
||||
</Badge>
|
||||
|
||||
{suffix ? (
|
||||
<Badge
|
||||
variant={isAGroupOption ? "orange" : "gray"}
|
||||
style={{
|
||||
backgroundColor: "color-mix(in hsl, var(--cal-bg-emphasis), black 5%)",
|
||||
}}
|
||||
className="rounded-l-none">
|
||||
{suffix}
|
||||
</Badge>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
},
|
||||
};
|
||||
}) ?? [];
|
||||
return attributeColumns;
|
||||
};
|
||||
|
||||
const cols: ColumnDef<UserTableUser>[] = [
|
||||
// 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,
|
||||
enableColumnFilter: false,
|
||||
size: 200,
|
||||
header: t("members"),
|
||||
cell: ({ row }) => {
|
||||
const { username, email, avatarUrl } = row.original;
|
||||
return (
|
||||
<div className="flex items-center gap-2">
|
||||
<Avatar
|
||||
size="sm"
|
||||
alt={username || email}
|
||||
imageSrc={getUserAvatarUrl({
|
||||
avatarUrl,
|
||||
})}
|
||||
/>
|
||||
<div className="">
|
||||
<div
|
||||
data-testid={`member-${username}-username`}
|
||||
className="text-emphasis text-sm font-medium leading-none">
|
||||
{username || "No username"}
|
||||
</div>
|
||||
<div
|
||||
data-testid={`member-${username}-email`}
|
||||
className="text-subtle mt-1 text-sm leading-none">
|
||||
{email}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "role",
|
||||
accessorFn: (data) => data.role,
|
||||
header: t("role"),
|
||||
size: 100,
|
||||
meta: {
|
||||
filter: { type: ColumnFilterType.MULTI_SELECT },
|
||||
},
|
||||
cell: ({ row, table }) => {
|
||||
const { role, username, customRole } = row.original;
|
||||
const roleName = customRole?.name || role;
|
||||
return (
|
||||
<Badge
|
||||
data-testid={`member-${username}-role`}
|
||||
variant={role === "MEMBER" ? "gray" : "blue"}
|
||||
onClick={() => {
|
||||
table.getColumn("role")?.setFilterValue([role]);
|
||||
}}>
|
||||
{roleName}
|
||||
</Badge>
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "teams",
|
||||
accessorFn: (data) => data.teams.map((team) => team.name),
|
||||
header: t("teams"),
|
||||
size: 140,
|
||||
meta: {
|
||||
filter: { type: ColumnFilterType.MULTI_SELECT },
|
||||
},
|
||||
cell: ({ row, table }) => {
|
||||
const { teams, accepted, email, username } = row.original;
|
||||
// TODO: Implement click to filter
|
||||
return (
|
||||
<div className="flex h-full flex-wrap items-center gap-2">
|
||||
{accepted ? null : (
|
||||
<Badge
|
||||
data-testid2={`member-${username}-pending`}
|
||||
variant="red"
|
||||
className="text-xs"
|
||||
data-testid={`email-${email.replace("@", "")}-pending`}
|
||||
onClick={() => {
|
||||
table.getColumn("role")?.setFilterValue(["PENDING"]);
|
||||
}}>
|
||||
{t("pending")}
|
||||
</Badge>
|
||||
)}
|
||||
|
||||
{teams.map((team) => (
|
||||
<Badge
|
||||
key={team.id}
|
||||
variant="gray"
|
||||
onClick={() => {
|
||||
table.getColumn("teams")?.setFilterValue([team.name]);
|
||||
}}>
|
||||
{team.name}
|
||||
</Badge>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
},
|
||||
},
|
||||
...generateAttributeColumns(),
|
||||
{
|
||||
id: "lastActiveAt",
|
||||
accessorKey: "lastActiveAt",
|
||||
header: t("last_active"),
|
||||
enableSorting: false,
|
||||
enableColumnFilter: true,
|
||||
meta: {
|
||||
filter: {
|
||||
type: ColumnFilterType.DATE_RANGE,
|
||||
},
|
||||
},
|
||||
cell: ({ row }) => <div>{row.original.lastActiveAt}</div>,
|
||||
},
|
||||
{
|
||||
id: "createdAt",
|
||||
accessorKey: "createdAt",
|
||||
header: t("member_since"),
|
||||
enableSorting: false,
|
||||
enableColumnFilter: true,
|
||||
meta: {
|
||||
filter: {
|
||||
type: ColumnFilterType.DATE_RANGE,
|
||||
},
|
||||
},
|
||||
cell: ({ row }) => <div>{row.original.createdAt || ""}</div>,
|
||||
},
|
||||
{
|
||||
id: "updatedAt",
|
||||
accessorKey: "updatedAt",
|
||||
header: t("last_updated"),
|
||||
enableSorting: false,
|
||||
enableColumnFilter: true,
|
||||
meta: {
|
||||
filter: {
|
||||
type: ColumnFilterType.DATE_RANGE,
|
||||
},
|
||||
},
|
||||
cell: ({ row }) => <div>{row.original.updatedAt || ""}</div>,
|
||||
},
|
||||
{
|
||||
id: "twoFactorEnabled",
|
||||
accessorKey: "twoFactorEnabled",
|
||||
header: t("2fa"),
|
||||
enableHiding: adminOrOwner,
|
||||
enableSorting: false,
|
||||
enableColumnFilter: false,
|
||||
size: 80,
|
||||
cell: ({ row }) => {
|
||||
const { twoFactorEnabled } = row.original;
|
||||
if (!adminOrOwner || twoFactorEnabled === undefined) {
|
||||
return null;
|
||||
}
|
||||
return (
|
||||
<Badge variant={twoFactorEnabled ? "green" : "gray"}>
|
||||
{twoFactorEnabled ? t("enabled") : t("disabled")}
|
||||
</Badge>
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "actions",
|
||||
enableHiding: false,
|
||||
enableSorting: false,
|
||||
enableResizing: false,
|
||||
size: 80,
|
||||
cell: ({ row }) => {
|
||||
const user = row.original;
|
||||
const permissionsRaw = tablePermissions;
|
||||
const isSelf = user.id === session?.user.id;
|
||||
|
||||
const permissionsForUser = {
|
||||
canEdit:
|
||||
((permissionsRaw.canEdit ?? false) || (permissions?.canEditAttributesForUser ?? false)) &&
|
||||
user.accepted &&
|
||||
!isSelf,
|
||||
canRemove: (permissionsRaw.canRemove ?? false) && !isSelf,
|
||||
canImpersonate:
|
||||
user.accepted &&
|
||||
!user.disableImpersonation &&
|
||||
!isSelf &&
|
||||
!!org?.canAdminImpersonate &&
|
||||
(permissionsRaw.canImpersonate ?? false),
|
||||
canLeave: user.accepted && isSelf,
|
||||
canResendInvitation: (permissionsRaw.canResendInvitation ?? false) && !user.accepted,
|
||||
};
|
||||
|
||||
return (
|
||||
<TableActions
|
||||
user={user}
|
||||
permissionsForUser={permissionsForUser}
|
||||
dispatch={dispatch}
|
||||
domain={domain}
|
||||
/>
|
||||
);
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
return cols;
|
||||
}, [session?.user.id, adminOrOwner, dispatch, domain, attributes, org?.canAdminImpersonate, permissions]);
|
||||
|
||||
const table = useReactTable({
|
||||
data: flatData,
|
||||
columns: memorisedColumns,
|
||||
enableRowSelection: true,
|
||||
manualPagination: true,
|
||||
state: {
|
||||
rowSelection,
|
||||
},
|
||||
initialState: {
|
||||
columnVisibility: initalColumnVisibility,
|
||||
columnPinning: {
|
||||
left: ["select", "member"],
|
||||
right: ["actions"],
|
||||
},
|
||||
},
|
||||
defaultColumn: {
|
||||
size: 150,
|
||||
},
|
||||
getCoreRowModel: getCoreRowModel(),
|
||||
getSortedRowModel: getSortedRowModel(),
|
||||
onRowSelectionChange: setRowSelection,
|
||||
getRowId: (row) => `${row.id}`,
|
||||
getFacetedUniqueValues: (_, columnId) => () => {
|
||||
if (facetedTeamValues) {
|
||||
switch (columnId) {
|
||||
case "role":
|
||||
return convertFacetedValuesToMap(
|
||||
facetedTeamValues.roles.map((role) => ({
|
||||
label: role.name,
|
||||
value: role.id,
|
||||
}))
|
||||
);
|
||||
case "teams":
|
||||
return convertFacetedValuesToMap(
|
||||
facetedTeamValues.teams.map((team) => ({
|
||||
label: team.name,
|
||||
value: team.name,
|
||||
}))
|
||||
);
|
||||
default: {
|
||||
const attribute = facetedTeamValues.attributes.find((attr) => attr.id === columnId);
|
||||
if (attribute) {
|
||||
return convertFacetedValuesToMap(
|
||||
attribute?.options.map(({ value }) => ({
|
||||
label: value,
|
||||
value,
|
||||
})) ?? []
|
||||
);
|
||||
}
|
||||
return new Map();
|
||||
}
|
||||
}
|
||||
}
|
||||
return new Map();
|
||||
},
|
||||
});
|
||||
|
||||
const utils = trpc.useUtils();
|
||||
|
||||
const numberOfSelectedRows = table.getSelectedRowModel().rows.length;
|
||||
|
||||
const handleDownload = async () => {
|
||||
try {
|
||||
if (!org?.slug || !org?.name) {
|
||||
throw new Error("Org slug or name is missing.");
|
||||
}
|
||||
setIsDownloading(true);
|
||||
const headers = generateHeaderFromReactTable(table);
|
||||
if (!headers || !headers.length) {
|
||||
throw new Error("Header is missing.");
|
||||
}
|
||||
|
||||
// Fetch all pages
|
||||
let allRows: UserTableUser[] = [];
|
||||
let offset: number | undefined = 0;
|
||||
const limit = 100;
|
||||
|
||||
while (offset !== undefined) {
|
||||
const result = await utils.viewer.organizations.listMembers.fetch({
|
||||
limit,
|
||||
offset,
|
||||
searchTerm,
|
||||
expand: ["attributes"],
|
||||
filters: columnFilters,
|
||||
});
|
||||
|
||||
if (!result.rows?.length) {
|
||||
offset = undefined;
|
||||
continue;
|
||||
}
|
||||
|
||||
allRows = [...allRows, ...result.rows];
|
||||
offset = offset + limit;
|
||||
}
|
||||
|
||||
if (!allRows.length) {
|
||||
throw new Error("There are no members found.");
|
||||
}
|
||||
|
||||
const ATTRIBUTE_IDS = attributes?.map((attr) => attr.id) ?? [];
|
||||
const csvRaw = generateCsvRawForMembersTable(headers, allRows, ATTRIBUTE_IDS, domain);
|
||||
if (!csvRaw) {
|
||||
throw new Error("Generating CSV file failed.");
|
||||
}
|
||||
|
||||
const filename = `${org.name}_${new Date().toISOString().split("T")[0]}.csv`;
|
||||
downloadAsCsv(csvRaw, filename);
|
||||
} catch (error) {
|
||||
showToast(`Error: ${error}`, "error");
|
||||
} finally {
|
||||
setIsDownloading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<DataTableWrapper<UserTableUser>
|
||||
testId="user-list-data-table"
|
||||
table={table}
|
||||
isPending={isPending}
|
||||
totalRowCount={data?.meta?.totalRowCount}
|
||||
paginationMode="standard"
|
||||
ToolbarLeft={
|
||||
<>
|
||||
<DataTableToolbar.SearchBar />
|
||||
<DataTableFilters.ColumnVisibilityButton table={table} />
|
||||
<DataTableFilters.FilterBar table={table} />
|
||||
</>
|
||||
}
|
||||
ToolbarRight={
|
||||
<>
|
||||
<DataTableFilters.ClearFiltersButton />
|
||||
<DataTableSegment.SaveButton />
|
||||
<DataTableSegment.Select />
|
||||
</>
|
||||
}>
|
||||
{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 shrink-0 px-2 text-center text-xs leading-none sm:text-sm sm:font-medium">
|
||||
{t("number_selected", { count: numberOfSelectedRows })}
|
||||
</p>
|
||||
{!isPlatformUser ? (
|
||||
<>
|
||||
{permissions?.canChangeMemberRole && <TeamListBulkAction table={table} />}
|
||||
{numberOfSelectedRows >= 2 && (
|
||||
<DataTableSelectionBar.Button
|
||||
color="secondary"
|
||||
onClick={() => setDynamicLinkVisible(!dynamicLinkVisible)}
|
||||
icon="handshake">
|
||||
{t("group_meeting")}
|
||||
</DataTableSelectionBar.Button>
|
||||
)}
|
||||
{(permissions?.canEditAttributesForUser ?? adminOrOwner) && (
|
||||
<MassAssignAttributesBulkAction table={table} filters={columnFilters} />
|
||||
)}
|
||||
{(permissions?.canChangeMemberRole ?? adminOrOwner) && (
|
||||
<EventTypesList table={table} orgTeams={teams} />
|
||||
)}
|
||||
</>
|
||||
) : null}
|
||||
{(permissions?.canRemove ?? adminOrOwner) && (
|
||||
<DeleteBulkUsers
|
||||
users={table.getSelectedRowModel().flatRows.map((row) => row.original)}
|
||||
onRemove={() => table.toggleAllPageRowsSelected(false)}
|
||||
/>
|
||||
)}
|
||||
</DataTableSelectionBar.Root>
|
||||
)}
|
||||
</DataTableWrapper>
|
||||
|
||||
{state.deleteMember.showModal && <DeleteMemberModal state={state} dispatch={dispatch} />}
|
||||
{state.inviteMember.showModal && <InviteMemberModal dispatch={dispatch} />}
|
||||
{state.impersonateMember.showModal && <ImpersonationMemberModal dispatch={dispatch} state={state} />}
|
||||
{state.changeMemberRole.showModal && <ChangeUserRoleModal dispatch={dispatch} state={state} />}
|
||||
{state.editSheet.showModal && (
|
||||
<EditUserSheet
|
||||
dispatch={dispatch}
|
||||
state={state}
|
||||
canViewAttributes={permissions?.canViewAttributes}
|
||||
canEditAttributesForUser={permissions?.canEditAttributesForUser}
|
||||
canChangeMemberRole={permissions?.canChangeMemberRole ?? adminOrOwner}
|
||||
/>
|
||||
)}
|
||||
|
||||
{ctaContainerRef.current &&
|
||||
createPortal(
|
||||
<div className="flex items-center gap-2">
|
||||
<DataTableToolbar.CTA
|
||||
type="button"
|
||||
color="secondary"
|
||||
StartIcon="file-down"
|
||||
loading={isDownloading}
|
||||
onClick={() => handleDownload()}
|
||||
data-testid="export-members-button">
|
||||
{t("download")}
|
||||
</DataTableToolbar.CTA>
|
||||
{(permissions?.canInvite ?? adminOrOwner) && (
|
||||
<DataTableToolbar.CTA
|
||||
type="button"
|
||||
color="primary"
|
||||
StartIcon="plus"
|
||||
onClick={() => {
|
||||
dispatch({
|
||||
type: "INVITE_MEMBER",
|
||||
payload: {
|
||||
showModal: true,
|
||||
},
|
||||
});
|
||||
posthog.capture("add_organization_member_clicked")
|
||||
}}
|
||||
data-testid="new-organization-member-button">
|
||||
{t("add")}
|
||||
</DataTableToolbar.CTA>
|
||||
)}
|
||||
</div>,
|
||||
ctaContainerRef.current
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
"use client";
|
||||
|
||||
import { DataTableSkeleton } from "@calcom/features/data-table";
|
||||
import { CTA_CONTAINER_CLASS_NAME } from "@calcom/features/data-table/lib/utils";
|
||||
import { SkeletonButton, SkeletonContainer, SkeletonText } from "@calcom/ui/components/skeleton";
|
||||
|
||||
export function UserListTableSkeleton() {
|
||||
return (
|
||||
<SkeletonContainer>
|
||||
{/* Toolbar with search, filters, etc. */}
|
||||
<div className="grid w-full items-center gap-2 pb-4">
|
||||
<div className="flex w-full flex-col gap-2">
|
||||
<div className="flex w-full flex-wrap justify-between gap-2">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
{/* Search bar */}
|
||||
<div className="border-default bg-default flex h-9 w-52 items-center gap-1 rounded-md border px-3 py-2">
|
||||
<div className="flex items-center justify-center">
|
||||
<SkeletonText className="h-4 w-4" />
|
||||
</div>
|
||||
<SkeletonText className="h-4 w-40" />
|
||||
</div>
|
||||
|
||||
{/* Filters */}
|
||||
<SkeletonButton className="h-9 w-28" />
|
||||
</div>
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<SkeletonButton className="h-9 w-20" />
|
||||
<SkeletonButton className="h-9 w-24" />
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<SkeletonButton className="h-9 w-24" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* DataTable */}
|
||||
<DataTableSkeleton columns={7} rows={10} columnWidths={[30, 200, 100, 140, 120, 120, 80]} />
|
||||
|
||||
{/* CTA actions at the bottom */}
|
||||
<div className={`mt-4 flex items-center gap-2 ${CTA_CONTAINER_CLASS_NAME}`}>
|
||||
<SkeletonButton className="h-9 w-32" />
|
||||
<SkeletonButton className="h-9 w-24" />
|
||||
</div>
|
||||
</SkeletonContainer>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,217 @@
|
||||
import { useSession } from "next-auth/react";
|
||||
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
import classNames from "@calcom/ui/classNames";
|
||||
import { Button } from "@calcom/ui/components/button";
|
||||
import { ButtonGroup } from "@calcom/ui/components/buttonGroup";
|
||||
import {
|
||||
Dropdown,
|
||||
DropdownMenuTrigger,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuPortal,
|
||||
DropdownItem,
|
||||
DropdownMenuSeparator,
|
||||
} from "@calcom/ui/components/dropdown";
|
||||
import { showToast } from "@calcom/ui/components/toast";
|
||||
import { Tooltip } from "@calcom/ui/components/tooltip";
|
||||
|
||||
import type { UserTableUser, UserTableAction } from "./types";
|
||||
|
||||
export function TableActions({
|
||||
user,
|
||||
permissionsForUser,
|
||||
dispatch,
|
||||
domain,
|
||||
}: {
|
||||
user: UserTableUser;
|
||||
dispatch: React.Dispatch<UserTableAction>;
|
||||
domain: string;
|
||||
permissionsForUser: {
|
||||
canEdit: boolean;
|
||||
canRemove: boolean;
|
||||
canImpersonate: boolean;
|
||||
canResendInvitation: boolean;
|
||||
};
|
||||
}) {
|
||||
const { t, i18n } = useLocale();
|
||||
const { data: session } = useSession();
|
||||
const resendInvitationMutation = trpc.viewer.teams.resendInvitation.useMutation({
|
||||
onSuccess: () => {
|
||||
showToast(t("invitation_resent"), "success");
|
||||
},
|
||||
onError: (error) => {
|
||||
showToast(error.message, "error");
|
||||
},
|
||||
});
|
||||
|
||||
const usersProfileUrl = `${domain}/${user.username}`;
|
||||
|
||||
if (!session?.user.org?.id) return null;
|
||||
|
||||
const orgId = session?.user?.org?.id;
|
||||
|
||||
return (
|
||||
<div className="flex w-full justify-center">
|
||||
<ButtonGroup combined containerProps={{ className: "border-default hidden md:flex" }}>
|
||||
<Tooltip content={t("view_public_page")}>
|
||||
<Button
|
||||
target="_blank"
|
||||
href={usersProfileUrl}
|
||||
color="secondary"
|
||||
className={classNames(!permissionsForUser.canEdit ? "rounded-r-md" : "")}
|
||||
variant="icon"
|
||||
StartIcon="external-link"
|
||||
/>
|
||||
</Tooltip>
|
||||
{(permissionsForUser.canEdit || permissionsForUser.canRemove) && (
|
||||
<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>
|
||||
{permissionsForUser.canEdit && (
|
||||
<DropdownMenuItem>
|
||||
<DropdownItem
|
||||
type="button"
|
||||
onClick={() =>
|
||||
dispatch({
|
||||
type: "EDIT_USER_SHEET",
|
||||
payload: {
|
||||
user,
|
||||
showModal: true,
|
||||
},
|
||||
})
|
||||
}
|
||||
StartIcon="pencil">
|
||||
{t("edit")}
|
||||
</DropdownItem>
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
{permissionsForUser.canImpersonate && (
|
||||
<>
|
||||
<DropdownMenuItem>
|
||||
<DropdownItem
|
||||
type="button"
|
||||
onClick={() =>
|
||||
dispatch({
|
||||
type: "SET_IMPERSONATE_ID",
|
||||
payload: {
|
||||
user,
|
||||
showModal: true,
|
||||
},
|
||||
})
|
||||
}
|
||||
StartIcon="lock">
|
||||
{t("impersonate")}
|
||||
</DropdownItem>
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuSeparator />
|
||||
</>
|
||||
)}
|
||||
{permissionsForUser.canRemove && (
|
||||
<DropdownMenuItem>
|
||||
<DropdownItem
|
||||
type="button"
|
||||
onClick={() =>
|
||||
dispatch({
|
||||
type: "SET_DELETE_ID",
|
||||
payload: {
|
||||
user,
|
||||
showModal: true,
|
||||
},
|
||||
})
|
||||
}
|
||||
color="destructive"
|
||||
StartIcon="user-x">
|
||||
{t("remove")}
|
||||
</DropdownItem>
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
{permissionsForUser.canResendInvitation && (
|
||||
<DropdownMenuItem>
|
||||
<DropdownItem
|
||||
type="button"
|
||||
onClick={() => {
|
||||
resendInvitationMutation.mutate({
|
||||
teamId: orgId,
|
||||
language: i18n.language,
|
||||
email: user.email,
|
||||
isOrg: true,
|
||||
});
|
||||
}}
|
||||
StartIcon="send">
|
||||
{t("resend_invitation")}
|
||||
</DropdownItem>
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
</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 type="button" StartIcon="external-link">
|
||||
{t("view_public_page")}
|
||||
</DropdownItem>
|
||||
</DropdownMenuItem>
|
||||
{permissionsForUser.canEdit && (
|
||||
<>
|
||||
<DropdownMenuItem>
|
||||
<DropdownItem
|
||||
type="button"
|
||||
onClick={() =>
|
||||
dispatch({
|
||||
type: "EDIT_USER_SHEET",
|
||||
payload: {
|
||||
user,
|
||||
showModal: true,
|
||||
},
|
||||
})
|
||||
}
|
||||
StartIcon="pencil">
|
||||
{t("edit")}
|
||||
</DropdownItem>
|
||||
</DropdownMenuItem>
|
||||
</>
|
||||
)}
|
||||
{permissionsForUser.canRemove && (
|
||||
<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>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
import type { RouterOutputs } from "@calcom/trpc/react";
|
||||
|
||||
export type UserTableUser = RouterOutputs["viewer"]["organizations"]["listMembers"]["rows"][number];
|
||||
|
||||
export type PlatformManagedUserTableUser = Omit<
|
||||
UserTableUser,
|
||||
"lastActiveAt" | "attributes" | "completedOnboarding" | "disableImpersonation"
|
||||
>;
|
||||
|
||||
export type UserTablePayload = {
|
||||
showModal: boolean;
|
||||
user?: UserTableUser;
|
||||
};
|
||||
|
||||
export type PlatformUserTablePayload = {
|
||||
showModal: boolean;
|
||||
user?: PlatformManagedUserTableUser;
|
||||
};
|
||||
|
||||
export type UserTableState = {
|
||||
changeMemberRole: UserTablePayload;
|
||||
deleteMember: UserTablePayload;
|
||||
impersonateMember: UserTablePayload;
|
||||
inviteMember: UserTablePayload;
|
||||
editSheet: UserTablePayload & { user?: UserTableUser };
|
||||
};
|
||||
|
||||
export type PlatforManagedUserTableState = {
|
||||
deleteMember: UserTablePayload;
|
||||
};
|
||||
|
||||
export type UserTableAction =
|
||||
| {
|
||||
type:
|
||||
| "SET_CHANGE_MEMBER_ROLE_ID"
|
||||
| "SET_DELETE_ID"
|
||||
| "SET_IMPERSONATE_ID"
|
||||
| "INVITE_MEMBER"
|
||||
| "EDIT_USER_SHEET"
|
||||
| "INVITE_MEMBER";
|
||||
payload: UserTablePayload;
|
||||
}
|
||||
| {
|
||||
type: "CLOSE_MODAL";
|
||||
};
|
||||
|
||||
export type PlatformManagedUserTableAction =
|
||||
| {
|
||||
type: "SET_DELETE_ID";
|
||||
payload: PlatformUserTablePayload;
|
||||
}
|
||||
| {
|
||||
type: "CLOSE_MODAL";
|
||||
};
|
||||
|
||||
export interface MemberPermissions {
|
||||
canListMembers: boolean;
|
||||
canInvite: boolean;
|
||||
canChangeMemberRole: boolean;
|
||||
canRemove: boolean;
|
||||
canImpersonate: boolean;
|
||||
canEditAttributesForUser?: boolean;
|
||||
canViewAttributes?: boolean;
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
import { useFlagMap } from "@calcom/features/flags/context/provider";
|
||||
import { APP_NAME } from "@calcom/lib/constants";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
import { showToast } from "@calcom/ui/components/toast";
|
||||
import { TopBanner } from "@calcom/ui/components/top-banner";
|
||||
|
||||
export type VerifyEmailBannerProps = {
|
||||
data: boolean;
|
||||
};
|
||||
|
||||
function VerifyEmailBanner({ data }: VerifyEmailBannerProps) {
|
||||
const flags = useFlagMap();
|
||||
const { t } = useLocale();
|
||||
const mutation = trpc.viewer.auth.resendVerifyEmail.useMutation();
|
||||
|
||||
if (!data || !flags["email-verification"]) return null;
|
||||
|
||||
return (
|
||||
<>
|
||||
<TopBanner
|
||||
icon="mail"
|
||||
text={t("verify_email_banner_body", { appName: APP_NAME })}
|
||||
variant="warning"
|
||||
actions={
|
||||
<a
|
||||
className="underline hover:cursor-pointer"
|
||||
onClick={() => {
|
||||
mutation.mutate();
|
||||
showToast(t("email_sent"), "success");
|
||||
}}>
|
||||
{t("resend_email")}
|
||||
</a>
|
||||
}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export default VerifyEmailBanner;
|
||||
Reference in new issue
Block a user