Files
calendar/apps/web/modules/ee/teams/components/EditMemberSheet.tsx
T
Benny JooGitHubbenny@cal.com <sldisek783@gmail.com>benny@cal.com <sldisek783@gmail.com>benny@cal.com <sldisek783@gmail.com>benny@cal.com <sldisek783@gmail.com>benny@cal.com <sldisek783@gmail.com>benny@cal.com <sldisek783@gmail.com>Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
8afe87ff75 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: benny@cal.com <sldisek783@gmail.com>

* 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: benny@cal.com <sldisek783@gmail.com>

* 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: benny@cal.com <sldisek783@gmail.com>

* 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: benny@cal.com <sldisek783@gmail.com>

* fix: update test import path after migration

Co-Authored-By: benny@cal.com <sldisek783@gmail.com>

* fix: remove unnecessary test-setup import (already in vitest config)

Co-Authored-By: benny@cal.com <sldisek783@gmail.com>

* wip

* refactor: delete original files after migration to apps/web/modules

Co-Authored-By: benny@cal.com <sldisek783@gmail.com>

* 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: benny@cal.com <sldisek783@gmail.com>

* fix: fix AttributeForm test failures

Co-Authored-By: benny@cal.com <sldisek783@gmail.com>

* 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: benny@cal.com <sldisek783@gmail.com>

* 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: benny@cal.com <sldisek783@gmail.com>

* fix: correct UpgradeTeamsBadge import path to use package export

Co-Authored-By: benny@cal.com <sldisek783@gmail.com>

* 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: benny@cal.com <sldisek783@gmail.com>

* fix: update import paths to use /ee/ folder for workflows and organizations

Co-Authored-By: benny@cal.com <sldisek783@gmail.com>

* fix: update workflow component imports to use /ee/ folder

Co-Authored-By: benny@cal.com <sldisek783@gmail.com>

* fix: add missing types.ts for LocationInput.tsx

Co-Authored-By: benny@cal.com <sldisek783@gmail.com>

* fix: extract BookingRedirectForm type to shared location

Co-Authored-By: benny@cal.com <sldisek783@gmail.com>

* fix

* wip

* wip

* fix: update BookingRedirectForm import to use local types file

Co-Authored-By: benny@cal.com <sldisek783@gmail.com>

* wip

* fix

* fix

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2025-12-23 12:22:26 -03:00

296 lines
11 KiB
TypeScript

import { zodResolver } from "@hookform/resolvers/zod";
import type { Dispatch } from "react";
import { useMemo, useState } from "react";
import { useForm } from "react-hook-form";
import { z } from "zod";
import { shallow } from "zustand/shallow";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { MembershipRole } from "@calcom/prisma/enums";
import { trpc } from "@calcom/trpc/react";
import { Avatar } from "@calcom/ui/components/avatar";
import { Form } from "@calcom/ui/components/form";
import { ToggleGroup, Select } from "@calcom/ui/components/form";
import { Icon } from "@calcom/ui/components/icon";
import { Sheet, SheetContent, SheetFooter, SheetHeader, SheetBody } from "@calcom/ui/components/sheet";
import { Skeleton, Loader } from "@calcom/ui/components/skeleton";
import { showToast } from "@calcom/ui/components/toast";
import { Tooltip } from "@calcom/ui/components/tooltip";
import { DisplayInfo } from "@calcom/web/modules/users/components/UserTable/EditSheet/DisplayInfo";
import { SheetFooterControls } from "@calcom/web/modules/users/components/UserTable/EditSheet/SheetFooterControls";
import { useEditMode } from "@calcom/web/modules/users/components/UserTable/EditSheet/store";
import type { MemberPermissions } from "@calcom/web/modules/users/components/UserTable/types";
import { updateRoleInCache, getUpdatedUser } from "./MemberChangeRoleModal";
import type { Action, State, User } from "./MemberList";
const formSchema = z.object({
role: z.union([z.nativeEnum(MembershipRole), z.string()]), // Support both traditional roles and custom role IDs
});
type FormSchema = z.infer<typeof formSchema>;
export function EditMemberSheet({
state,
dispatch,
currentMember,
teamId,
permissions,
}: {
state: State;
dispatch: Dispatch<Action>;
currentMember: MembershipRole;
teamId: number;
permissions?: MemberPermissions;
}) {
const { t } = useLocale();
const { user } = state.editSheet;
const selectedUser = user as User;
const [editMode, setEditMode, setMutationLoading] = useEditMode(
(state) => [state.editMode, state.setEditMode, state.setMutationLoading],
shallow
);
const [role, setRole] = useState<string>(selectedUser.customRoleId || selectedUser.role);
const name =
selectedUser.name ||
(() => {
const emailName = selectedUser.email.split("@")[0] as string;
return emailName.charAt(0).toUpperCase() + emailName.slice(1);
})();
const bookerUrl = selectedUser.bookerUrl;
const utils = trpc.useUtils();
const bookerUrlWithoutProtocol = bookerUrl.replace(/^https?:\/\//, "");
const bookingLink = selectedUser.username ? `${bookerUrlWithoutProtocol}/${selectedUser.username}` : "";
// Load custom roles for the team
const { data: customRoles, isPending: isLoadingRoles } = trpc.viewer.pbac.getTeamRoles.useQuery(
{ teamId },
{
enabled: !!teamId,
retry: false, // Don't retry if PBAC is not enabled
}
);
const options = useMemo(() => {
// If we have custom roles, only show custom roles
if (customRoles && customRoles.length > 0) {
return customRoles.map((customRole) => ({
label: customRole.name,
value: customRole.id,
}));
}
// Otherwise, show traditional roles
return [
{
label: t("member"),
value: MembershipRole.MEMBER,
},
{
label: t("admin"),
value: MembershipRole.ADMIN,
},
{
label: t("owner"),
value: MembershipRole.OWNER,
},
].filter(({ value }) => value !== MembershipRole.OWNER || currentMember === MembershipRole.OWNER);
}, [t, currentMember, customRoles]);
// Determine if we should use Select (when custom roles exist) or ToggleGroup (traditional only)
const hasCustomRoles = customRoles && customRoles.length > 0;
const shouldUseSelect = hasCustomRoles; // Use Select for custom roles, ToggleGroup for traditional roles
const form = useForm({
resolver: zodResolver(formSchema),
defaultValues: {
role: selectedUser.customRoleId || selectedUser.role, // Use custom role ID if available, otherwise traditional role
},
});
const { data: getUserConnectedApps, isPending } = trpc.viewer.teams.getUserConnectedApps.useQuery({
userIds: [selectedUser.id],
teamId,
});
const connectedApps = getUserConnectedApps?.[selectedUser.id];
const changeRoleMutation = trpc.viewer.teams.changeMemberRole.useMutation({
onMutate: async ({ teamId, memberId, role }) => {
await utils.viewer.teams.listMembers.cancel();
const previousValue = utils.viewer.teams.listMembers.getInfiniteData({
limit: 10,
teamId,
searchTerm: undefined,
});
if (previousValue) {
updateRoleInCache({
utils,
teamId,
memberId,
role: role as MembershipRole | string,
searchTerm: undefined,
customRoles,
});
}
return { previousValue };
},
onSuccess: async (_data, { role }) => {
setRole(role as string);
setMutationLoading(false);
await utils.viewer.teams.get.invalidate();
await utils.viewer.teams.listMembers.invalidate();
showToast(t("profile_updated_successfully"), "success");
setEditMode(false);
dispatch({
type: "EDIT_USER_SHEET",
payload: {
showModal: true,
user: getUpdatedUser(selectedUser, role, customRoles),
},
});
},
async onError(err) {
showToast(err.message, "error");
setMutationLoading(false);
},
});
function changeRole(values: FormSchema) {
setMutationLoading(true);
changeRoleMutation.mutate({
teamId: teamId,
memberId: user?.id as number,
role: values.role,
});
}
const appList = (connectedApps || []).map(({ logo, name, externalId }) => {
return logo ? (
externalId ? (
<div className="ltr:mr-2 rtl:ml-2 ">
<Tooltip content={externalId}>
<img className="h-5 w-5" src={logo} alt={`${name} logo`} />
</Tooltip>
</div>
) : (
<div className="ltr:mr-2 rtl:ml-2">
<img className="h-5 w-5" src={logo} alt={`${name} logo`} />
</div>
)
) : null;
});
return (
<Sheet
open={true}
onOpenChange={() => {
setEditMode(false);
dispatch({ type: "CLOSE_MODAL" });
}}>
<SheetContent className="bg-cal-muted">
{!isPending && !isLoadingRoles ? (
<Form form={form} handleSubmit={changeRole} className="flex h-full flex-col">
<SheetHeader showCloseButton={false} className="w-full">
<div className="border-sublte bg-default w-full rounded-xl border p-4">
<div
className="block w-full rounded-lg ring-1 ring-[#0000000F]"
style={{
background: "linear-gradient(to top right, var(--cal-bg-emphasis), var(--cal-bg))",
height: "110px",
}}
/>
<div className="bg-default ml-3 w-fit translate-y-[-50%] rounded-full p-1 ring-1 ring-[#0000000F]">
<Avatar asChild size="lg" alt={`${name} avatar`} imageSrc={selectedUser.avatarUrl} />
</div>
<Skeleton as="p" waitForTranslation={false}>
<h2 className="text-emphasis font-sans text-2xl font-semibold">
{name || "Nameless User"}
</h2>
</Skeleton>
<Skeleton as="p" waitForTranslation={false}>
<p className="text-subtle max-h-[3em] overflow-hidden text-ellipsis text-sm font-normal">
{selectedUser.bio ? selectedUser?.bio : t("user_has_no_bio")}
</p>
</Skeleton>
</div>
</SheetHeader>
<SheetBody className="stack-y-4 flex flex-col p-4">
<div className="stack-y-4 mb-4 flex flex-col">
<h3 className="text-emphasis mb-1 text-base font-semibold">{t("profile")}</h3>
<DisplayInfo label="Cal" value={bookingLink} icon="external-link" />
<DisplayInfo label={t("email")} value={selectedUser.email} icon="at-sign" />
{!editMode ? (
<DisplayInfo
label={t("role")}
value={[selectedUser.customRole?.name || selectedUser.role]}
icon="fingerprint"
/>
) : (
<div className="flex items-center gap-6">
<div className="flex w-[110px] items-center gap-2">
<Icon className="h-4 w-4" name="fingerprint" />
<label className="text-sm font-medium">{t("role")}</label>
</div>
<div className="flex flex-1">
{shouldUseSelect ? (
<Select
value={options.find((option) => option.value === form.watch("role"))}
onChange={(selectedOption: any) => {
if (selectedOption) {
form.setValue("role", selectedOption.value);
}
}}
options={options}
isDisabled={isLoadingRoles}
placeholder={isLoadingRoles ? t("loading") : t("select_role")}
className="flex-1"
/>
) : (
<ToggleGroup
isFullWidth
defaultValue={role}
value={form.watch("role")}
options={options}
onValueChange={(value: FormSchema["role"]) => {
form.setValue("role", value);
}}
/>
)}
</div>
</div>
)}
<div className="flex items-center gap-6">
<div className="flex w-[110px] items-center gap-2">
<Icon className="text-subtle h-4 w-4" name="grid-3x3" />
<label className="text-subtle text-sm font-medium">{t("apps")}</label>
</div>
<div className="flex flex-1">
{!connectedApps ? (
<div>{t("user_has_no_app_installed")}</div>
) : (
<div className="flex">{appList}</div>
)}
</div>
</div>
</div>
</SheetBody>
<SheetFooter className="mt-auto">
<SheetFooterControls
canChangeMemberRole={permissions?.canChangeMemberRole}
canEditAttributesForUser={permissions?.canEditAttributesForUser}
/>
</SheetFooter>
</Form>
) : (
<Loader />
)}
</SheetContent>
</Sheet>
);
}