refactor: Cal.diy (#28903)
* feat: Cal.diy — community-driven MIT-licensed fork of Cal.com This squashed commit contains all Cal.diy changes applied on top of calcom/cal.com main: - Rebrand Cal.com to Cal.diy across the entire codebase - Remove Enterprise Edition (EE) features, license checks, and AGPL restrictions - Switch license from AGPL-3.0 to MIT - Remove docs/ directory (migrated to Nextra at cal.diy) - Remove dead code: org tests, EE tips, platform nav, premium username, SAML/SSO, etc. - Clean up .env.example for self-hosted Cal.diy - Update Docker image references to calcom/cal.diy - Update README, CONTRIBUTING.md, and issue templates for Cal.diy community fork - Add PR welcome bot for Cal.diy contributors - Fix API v2 breaking changes oasdiff ignore entries - Replace Blacksmith CI runners with default GitHub Actions 3893 files changed, 20789 insertions(+), 411020 deletions(-) Co-Authored-By: [email protected] <[email protected]> * refactor: remove org-specific /organizations/:orgId endpoints from API v2 atoms controllers (#1701) Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * fix: revert Cal.diy Inc to Cal.com, Inc. in license files, copyright notices, and package metadata (#1702) Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * rip out org related comments in api v2 --------- Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
This commit is contained in:
1 parent
a17f28e9ab
commit
ab21c7f805
4080 files changed
+14403
-404922
No files matched your search
@@ -1,8 +1,7 @@
|
||||
import Link from "next/link";
|
||||
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { type RouterOutputs } from "@calcom/trpc/react";
|
||||
import type { RouterOutputs } from "@calcom/trpc/react";
|
||||
import { TopBanner } from "@calcom/ui/components/top-banner";
|
||||
import Link from "next/link";
|
||||
|
||||
export type CalendarCredentialBannerProps = {
|
||||
data: RouterOutputs["viewer"]["me"]["getUserTopBanners"]["calendarCredentialBanner"];
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
import { useRouter } from "next/navigation";
|
||||
|
||||
import { type InvalidAppCredentialBannerProps } from "@calcom/features/users/types/invalidAppCredentials";
|
||||
import type { InvalidAppCredentialBannerProps } from "@calcom/features/users/types/invalidAppCredentials";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { type RouterOutputs } from "@calcom/trpc/react";
|
||||
import type { RouterOutputs } from "@calcom/trpc/react";
|
||||
import { TopBanner } from "@calcom/ui/components/top-banner";
|
||||
import { useRouter } from "next/navigation";
|
||||
|
||||
export type InvalidAppCredentialBannersProps = {
|
||||
data: RouterOutputs["viewer"]["me"]["getUserTopBanners"]["invalidAppCredentialBanners"];
|
||||
|
||||
@@ -0,0 +1,294 @@
|
||||
"use client";
|
||||
|
||||
import { formatToLocalizedDate } from "@calcom/lib/dayjs";
|
||||
import { getUserAvatarUrl } from "@calcom/lib/getAvatarUrl";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { defaultLocaleOption, localeOptions } from "@calcom/lib/i18n";
|
||||
import { nameOfDay } from "@calcom/lib/weekday";
|
||||
import { Avatar } from "@calcom/ui/components/avatar";
|
||||
import { Button } from "@calcom/ui/components/button";
|
||||
import { EmailField, Form, Label, Select, TextField } from "@calcom/ui/components/form";
|
||||
import { ImageUploader } from "@calcom/ui/components/image-uploader";
|
||||
import { TimezoneSelect } from "@calcom/web/modules/timezone/components/TimezoneSelect";
|
||||
import { noop } from "lodash";
|
||||
import { Controller, useForm } from "react-hook-form";
|
||||
|
||||
interface User {
|
||||
id: number;
|
||||
name: string | null;
|
||||
email: string;
|
||||
username: string | null;
|
||||
bio: string | null;
|
||||
timeZone: string;
|
||||
weekStart: string;
|
||||
theme: string | null;
|
||||
defaultScheduleId: number | null;
|
||||
locale: string | null;
|
||||
timeFormat: number | null;
|
||||
allowDynamicBooking: boolean | null;
|
||||
identityProvider: string | null;
|
||||
role: string | null;
|
||||
avatarUrl: string | null;
|
||||
createdDate?: string | Date;
|
||||
}
|
||||
|
||||
type Option<T extends string | number = string> = {
|
||||
value: T;
|
||||
label: string;
|
||||
};
|
||||
|
||||
type OptionValues = {
|
||||
locale: Option;
|
||||
timeFormat: Option<number>;
|
||||
timeZone: string;
|
||||
weekStart: Option;
|
||||
role: Option;
|
||||
identityProvider: Option;
|
||||
};
|
||||
|
||||
export type FormValues = Pick<
|
||||
User,
|
||||
| "avatarUrl"
|
||||
| "name"
|
||||
| "username"
|
||||
| "email"
|
||||
| "bio"
|
||||
| "createdDate"
|
||||
| "theme"
|
||||
| "defaultScheduleId"
|
||||
| "allowDynamicBooking"
|
||||
> &
|
||||
OptionValues;
|
||||
|
||||
export function UserForm({
|
||||
defaultValues,
|
||||
localeProp = "en",
|
||||
onSubmit = noop,
|
||||
submitLabel = "save",
|
||||
}: {
|
||||
defaultValues?: Pick<User, keyof FormValues>;
|
||||
localeProp?: string;
|
||||
onSubmit: (data: FormValues) => void;
|
||||
submitLabel?: string;
|
||||
}) {
|
||||
const { t } = useLocale();
|
||||
|
||||
const timeFormatOptions = [
|
||||
{ value: 12, label: t("12_hour") },
|
||||
{ value: 24, label: t("24_hour") },
|
||||
];
|
||||
|
||||
const weekStartOptions = [
|
||||
{ value: "Sunday", label: nameOfDay(localeProp, 0) },
|
||||
{ value: "Monday", label: nameOfDay(localeProp, 1) },
|
||||
{ value: "Tuesday", label: nameOfDay(localeProp, 2) },
|
||||
{ value: "Wednesday", label: nameOfDay(localeProp, 3) },
|
||||
{ value: "Thursday", label: nameOfDay(localeProp, 4) },
|
||||
{ value: "Friday", label: nameOfDay(localeProp, 5) },
|
||||
{ value: "Saturday", label: nameOfDay(localeProp, 6) },
|
||||
];
|
||||
|
||||
const userRoleOptions = [
|
||||
{ value: "USER", label: t("user") },
|
||||
{ value: "ADMIN", label: t("admin") },
|
||||
];
|
||||
|
||||
const identityProviderOptions = [
|
||||
{ value: "CAL", label: "CAL" },
|
||||
{ value: "GOOGLE", label: "GOOGLE" },
|
||||
];
|
||||
|
||||
const defaultLocale = defaultValues?.locale || defaultLocaleOption.value;
|
||||
|
||||
const form = useForm<FormValues>({
|
||||
defaultValues: {
|
||||
avatarUrl: defaultValues?.avatarUrl || null,
|
||||
name: defaultValues?.name,
|
||||
username: defaultValues?.username,
|
||||
email: defaultValues?.email,
|
||||
bio: defaultValues?.bio,
|
||||
theme: defaultValues?.theme || null,
|
||||
defaultScheduleId: defaultValues?.defaultScheduleId || null,
|
||||
allowDynamicBooking: defaultValues?.allowDynamicBooking ?? true,
|
||||
locale: {
|
||||
value: defaultLocale,
|
||||
label: new Intl.DisplayNames(defaultLocale, { type: "language" }).of(defaultLocale) || "",
|
||||
},
|
||||
timeFormat: {
|
||||
value: defaultValues?.timeFormat || 12,
|
||||
label: timeFormatOptions.find((option) => option.value === defaultValues?.timeFormat)?.label || "12",
|
||||
},
|
||||
timeZone: defaultValues?.timeZone || "",
|
||||
weekStart: {
|
||||
value: defaultValues?.weekStart || weekStartOptions[0].value,
|
||||
label:
|
||||
weekStartOptions.find((option) => option.value === defaultValues?.weekStart)?.label ||
|
||||
weekStartOptions[0].label,
|
||||
},
|
||||
role: {
|
||||
value: defaultValues?.role || userRoleOptions[0].value,
|
||||
label:
|
||||
userRoleOptions.find((option) => option.value === defaultValues?.role)?.label ||
|
||||
userRoleOptions[0].label,
|
||||
},
|
||||
identityProvider: {
|
||||
value: defaultValues?.identityProvider || identityProviderOptions[0].value,
|
||||
label:
|
||||
identityProviderOptions.find((option) => option.value === defaultValues?.identityProvider)?.label ||
|
||||
identityProviderOptions[0].label,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
return (
|
||||
<Form form={form} className="stack-y-4" handleSubmit={onSubmit}>
|
||||
<div className="flex items-center">
|
||||
<Controller
|
||||
control={form.control}
|
||||
name="avatarUrl"
|
||||
render={({ field: { value, onChange } }) => (
|
||||
<>
|
||||
<Avatar
|
||||
alt={form.getValues("name") || ""}
|
||||
imageSrc={getUserAvatarUrl({
|
||||
avatarUrl: value,
|
||||
})}
|
||||
size="lg"
|
||||
/>
|
||||
<div className="ml-4">
|
||||
<ImageUploader
|
||||
target="avatar"
|
||||
id="avatar-upload"
|
||||
buttonMsg="Change avatar"
|
||||
handleAvatarChange={onChange}
|
||||
imageSrc={getUserAvatarUrl({
|
||||
avatarUrl: value,
|
||||
})}
|
||||
/>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
{defaultValues?.createdDate && (
|
||||
<div>
|
||||
<Label className="text-default font-medium">{t("member_since")}</Label>
|
||||
<div className="text-default mt-1 text-sm">
|
||||
{formatToLocalizedDate(new Date(defaultValues.createdDate), localeProp)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
<Controller
|
||||
name="role"
|
||||
control={form.control}
|
||||
render={({ field: { onChange, value } }) => (
|
||||
<div>
|
||||
<Label className="text-default font-medium" htmlFor="role">
|
||||
{t("role")}
|
||||
</Label>
|
||||
<Select<{ label: string; value: string }>
|
||||
value={value}
|
||||
options={userRoleOptions}
|
||||
onChange={onChange}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
/>
|
||||
<Controller
|
||||
name="identityProvider"
|
||||
control={form.control}
|
||||
render={({ field: { onChange, value } }) => (
|
||||
<div>
|
||||
<Label className="text-default font-medium" htmlFor="identityProvider">
|
||||
{t("identity_provider")}
|
||||
</Label>
|
||||
<Select<{ label: string; value: string }>
|
||||
value={value}
|
||||
options={identityProviderOptions}
|
||||
onChange={onChange}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
/>
|
||||
<TextField label={t("name")} placeholder="example" required {...form.register("name")} />
|
||||
<TextField label={t("username")} placeholder="example" required {...form.register("username")} />
|
||||
<EmailField label={t("email")} placeholder="[email protected]" required {...form.register("email")} />
|
||||
<TextField label={t("about")} {...form.register("bio")} />
|
||||
<Controller
|
||||
name="locale"
|
||||
render={({ field: { value, onChange } }) => (
|
||||
<>
|
||||
<Label className="text-default">
|
||||
<>{t("language")}</>
|
||||
</Label>
|
||||
<Select<{ label: string; value: string }>
|
||||
className="capitalize"
|
||||
options={localeOptions}
|
||||
value={value}
|
||||
onChange={onChange}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
/>
|
||||
<Controller
|
||||
name="timeZone"
|
||||
control={form.control}
|
||||
render={({ field: { value } }) => (
|
||||
<>
|
||||
<Label className="text-default mt-8">
|
||||
<>{t("timezone")}</>
|
||||
</Label>
|
||||
<TimezoneSelect
|
||||
id="timezone"
|
||||
value={value}
|
||||
onChange={(event) => {
|
||||
if (event) form.setValue("timeZone", event.value);
|
||||
}}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
/>
|
||||
<Controller
|
||||
name="timeFormat"
|
||||
control={form.control}
|
||||
render={({ field: { value } }) => (
|
||||
<>
|
||||
<Label className="text-default mt-8">
|
||||
<>{t("time_format")}</>
|
||||
</Label>
|
||||
<Select
|
||||
value={value}
|
||||
options={timeFormatOptions}
|
||||
onChange={(event) => {
|
||||
if (event) form.setValue("timeFormat", { ...event });
|
||||
}}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
/>
|
||||
<Controller
|
||||
name="weekStart"
|
||||
control={form.control}
|
||||
render={({ field: { value } }) => (
|
||||
<>
|
||||
<Label className="text-default mt-8">
|
||||
<>{t("start_of_week")}</>
|
||||
</Label>
|
||||
<Select
|
||||
value={value}
|
||||
options={weekStartOptions}
|
||||
onChange={(event) => {
|
||||
if (event) form.setValue("weekStart", { ...event });
|
||||
}}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
/>
|
||||
|
||||
<br />
|
||||
<Button type="submit" color="primary">
|
||||
{t(submitLabel)}
|
||||
</Button>
|
||||
</Form>
|
||||
);
|
||||
}
|
||||
@@ -1,10 +1,9 @@
|
||||
import { Dialog } from "@calcom/features/components/controlled-dialog";
|
||||
import { DataTableSelectionBar } from "~/data-table/components";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
import { DialogTrigger, ConfirmationDialogContent } from "@calcom/ui/components/dialog";
|
||||
import { ConfirmationDialogContent, DialogTrigger } from "@calcom/ui/components/dialog";
|
||||
import { showToast } from "@calcom/ui/components/toast";
|
||||
|
||||
import { DataTableSelectionBar } from "~/data-table/components";
|
||||
import type { UserTableUser } from "../types";
|
||||
|
||||
interface Props {
|
||||
@@ -16,15 +15,12 @@ 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");
|
||||
},
|
||||
});
|
||||
const deleteMutation = {
|
||||
mutate: (..._args: unknown[]) => {},
|
||||
mutateAsync: async (..._args: unknown[]) => ({}),
|
||||
isPending: false,
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog>
|
||||
<DialogTrigger asChild>
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
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";
|
||||
import type { Table } from "@tanstack/react-table";
|
||||
import { parseAsBoolean, useQueryState } from "nuqs";
|
||||
|
||||
export function DynamicLink<T extends { username: string | null }>({
|
||||
table,
|
||||
|
||||
@@ -1,12 +1,7 @@
|
||||
import type { Table } from "@tanstack/react-table";
|
||||
import type { Dispatch, SetStateAction } from "react";
|
||||
import { useState, Fragment } from "react";
|
||||
|
||||
import { DataTableSelectionBar } from "~/data-table/components";
|
||||
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 { trpc } from "@calcom/trpc/react";
|
||||
import classNames from "@calcom/ui/classNames";
|
||||
import { Button } from "@calcom/ui/components/button";
|
||||
import {
|
||||
@@ -20,12 +15,15 @@ import {
|
||||
import { Popover, PopoverContent, PopoverTrigger } from "@calcom/ui/components/popover";
|
||||
import { showToast } from "@calcom/ui/components/toast";
|
||||
import { CheckIcon } from "@coss/ui/icons";
|
||||
|
||||
import type { Table } from "@tanstack/react-table";
|
||||
import type { Dispatch, SetStateAction } from "react";
|
||||
import { Fragment, useState } from "react";
|
||||
import { DataTableSelectionBar } from "~/data-table/components";
|
||||
import type { UserTableUser } from "../types";
|
||||
|
||||
interface Props {
|
||||
table: Table<UserTableUser>;
|
||||
orgTeams: RouterOutputs["viewer"]["organizations"]["getTeams"] | undefined;
|
||||
orgTeams: { id: number; slug: string; title: string }[] | undefined;
|
||||
}
|
||||
|
||||
export function EventTypesList({ table, orgTeams }: Props) {
|
||||
@@ -35,43 +33,18 @@ export function EventTypesList({ table, orgTeams }: Props) {
|
||||
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"
|
||||
);
|
||||
const addMutation = {
|
||||
mutate: (..._args: unknown[]) => {},
|
||||
mutateAsync: async (..._args: unknown[]) => ({}),
|
||||
isPending: false,
|
||||
};
|
||||
|
||||
utils.viewer.organizations.listMembers.invalidate();
|
||||
utils.viewer.eventTypes.invalidate();
|
||||
const removeHostsMutation = {
|
||||
mutate: (..._args: unknown[]) => {},
|
||||
mutateAsync: async (..._args: unknown[]) => ({}),
|
||||
isPending: false,
|
||||
};
|
||||
|
||||
// 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());
|
||||
|
||||
@@ -1,342 +0,0 @@
|
||||
import type { Table } from "@tanstack/react-table";
|
||||
import { createContext, useContext, useState, useMemo, type PropsWithChildren } from "react";
|
||||
import type { Dispatch, SetStateAction } from "react";
|
||||
|
||||
import { type ColumnFilter } from "@calcom/features/data-table";
|
||||
import { DataTableSelectionBar } from "~/data-table/components";
|
||||
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 { Popover, PopoverContent, PopoverTrigger } from "@calcom/ui/components/popover";
|
||||
import { showToast } from "@calcom/ui/components/toast";
|
||||
import { CheckIcon, ChevronRightIcon } from "@coss/ui/icons";
|
||||
|
||||
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) ? (
|
||||
<CheckIcon 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")}>
|
||||
<ChevronRightIcon 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>
|
||||
);
|
||||
}
|
||||
@@ -1,167 +0,0 @@
|
||||
import type { Table } from "@tanstack/react-table";
|
||||
import type { Dispatch, SetStateAction } from "react";
|
||||
import { useState } from "react";
|
||||
|
||||
import { DataTableSelectionBar } from "~/data-table/components";
|
||||
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 { Popover, PopoverContent, PopoverTrigger } from "@calcom/ui/components/popover";
|
||||
import { showToast } from "@calcom/ui/components/toast";
|
||||
import { CheckIcon } from "@coss/ui/icons";
|
||||
|
||||
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"
|
||||
)}>
|
||||
<CheckIcon 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>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -1,8 +1,5 @@
|
||||
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> }) {
|
||||
@@ -10,18 +7,5 @@ export function ChangeUserRoleModal(props: { state: UserTableState; dispatch: Di
|
||||
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",
|
||||
})
|
||||
}
|
||||
/>
|
||||
);
|
||||
return null;
|
||||
}
|
||||
@@ -1,12 +1,10 @@
|
||||
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 { useSession } from "next-auth/react";
|
||||
import type { Dispatch } from "react";
|
||||
import type { UserTableAction, UserTableState } from "./types";
|
||||
|
||||
export function DeleteMemberModal({
|
||||
@@ -19,21 +17,12 @@ export function DeleteMemberModal({
|
||||
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();
|
||||
const removeMemberMutation = {
|
||||
mutate: (..._args: unknown[]) => {},
|
||||
mutateAsync: async () => ({}),
|
||||
isPending: false,
|
||||
};
|
||||
|
||||
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}
|
||||
|
||||
@@ -1,32 +1,29 @@
|
||||
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/web/modules/timezone/components/TimezoneSelect";
|
||||
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 { trpc } 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,
|
||||
SelectField,
|
||||
TextAreaField,
|
||||
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 { SheetBody, SheetFooter, SheetHeader, SheetTitle } from "@calcom/ui/components/sheet";
|
||||
import { showToast } from "@calcom/ui/components/toast";
|
||||
|
||||
import { TimezoneSelect } from "@calcom/web/modules/timezone/components/TimezoneSelect";
|
||||
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 } from "react-hook-form";
|
||||
import { z } from "zod";
|
||||
import type { UserTableAction } from "../types";
|
||||
import { useEditMode } from "./store";
|
||||
|
||||
@@ -36,23 +33,6 @@ interface MembershipOption {
|
||||
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(),
|
||||
@@ -61,7 +41,6 @@ const editSchema = z.object({
|
||||
bio: z.string(),
|
||||
role: z.union([z.nativeEnum(MembershipRole), z.string()]),
|
||||
timeZone: timeZoneSchema,
|
||||
attributes: z.array(attributeSchema).optional(),
|
||||
});
|
||||
|
||||
type EditSchema = z.infer<typeof editSchema>;
|
||||
@@ -71,13 +50,11 @@ export function EditForm({
|
||||
avatarUrl,
|
||||
domainUrl,
|
||||
dispatch,
|
||||
canEditAttributesForUser,
|
||||
}: {
|
||||
selectedUser: RouterOutputs["viewer"]["organizations"]["getUser"];
|
||||
selectedUser: Record<string, unknown>;
|
||||
avatarUrl: string;
|
||||
domainUrl: string;
|
||||
dispatch: Dispatch<UserTableAction>;
|
||||
canEditAttributesForUser?: boolean;
|
||||
}) {
|
||||
const setEditMode = useEditMode((state) => state.setEditMode);
|
||||
const [mutationLoading, setMutationLoading] = useState(false);
|
||||
@@ -88,26 +65,18 @@ export function EditForm({
|
||||
const form = useForm<EditSchema>({
|
||||
resolver: zodResolver(editSchema),
|
||||
defaultValues: {
|
||||
name: selectedUser?.name ?? "",
|
||||
username: selectedUser?.username ?? "",
|
||||
email: selectedUser?.email ?? "",
|
||||
name: (selectedUser?.name as string) ?? "",
|
||||
username: (selectedUser?.username as string) ?? "",
|
||||
email: (selectedUser?.email as string) ?? "",
|
||||
avatar: avatarUrl,
|
||||
bio: selectedUser?.bio ?? "",
|
||||
role: selectedUser?.role ?? "",
|
||||
timeZone: selectedUser?.timeZone ?? "",
|
||||
bio: (selectedUser?.bio as string) ?? "",
|
||||
role: (selectedUser?.role as string) ?? "",
|
||||
timeZone: (selectedUser?.timeZone as string) ?? "",
|
||||
},
|
||||
});
|
||||
|
||||
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 teamRoles: { id: string; name: string }[] = [];
|
||||
|
||||
const membershipOptions = useMemo<MembershipOption[]>(() => {
|
||||
// Add custom roles if they exist
|
||||
@@ -146,23 +115,7 @@ export function EditForm({
|
||||
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 mutation = { mutate: (..._args: unknown[]) => {}, mutateAsync: async () => ({}), isPending: false };
|
||||
|
||||
const watchTimezone = form.watch("timeZone");
|
||||
|
||||
@@ -171,22 +124,9 @@ export function EditForm({
|
||||
<Form
|
||||
form={form}
|
||||
className="flex h-full flex-col"
|
||||
handleSubmit={(values) => {
|
||||
handleSubmit={() => {
|
||||
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,
|
||||
});
|
||||
setMutationLoading(false);
|
||||
setEditMode(false);
|
||||
}}>
|
||||
<SheetHeader>
|
||||
@@ -226,11 +166,11 @@ export function EditForm({
|
||||
{teamRoles?.length > 0 ? (
|
||||
<SelectField
|
||||
defaultValue={membershipOptions.find(
|
||||
(option) => option.value === (selectedUser?.role ?? "MEMBER")
|
||||
(option) => option.value === ((selectedUser?.role as string) ?? "MEMBER")
|
||||
)}
|
||||
value={membershipOptions.find((option) => option.value === form.watch("role"))}
|
||||
options={membershipOptions}
|
||||
onChange={(option) => {
|
||||
onChange={(option: MembershipOption | null) => {
|
||||
if (option) {
|
||||
form.setValue("role", option.value);
|
||||
}
|
||||
@@ -239,7 +179,7 @@ export function EditForm({
|
||||
) : (
|
||||
<ToggleGroup
|
||||
isFullWidth
|
||||
defaultValue={selectedUser?.role ?? "MEMBER"}
|
||||
defaultValue={(selectedUser?.role as string) ?? "MEMBER"}
|
||||
value={form.watch("role")}
|
||||
options={membershipOptions}
|
||||
onValueChange={(value) => {
|
||||
@@ -253,13 +193,6 @@ export function EditForm({
|
||||
<TimezoneSelect value={watchTimezone ?? "America/Los_Angeles"} />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{canEditAttributesForUser && (
|
||||
<>
|
||||
<Divider />
|
||||
<AttributesList selectedUserId={selectedUser?.id} />
|
||||
</>
|
||||
)}
|
||||
</SheetBody>
|
||||
<SheetFooter>
|
||||
<Button
|
||||
@@ -280,226 +213,3 @@ export function EditForm({
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
@@ -1,14 +1,11 @@
|
||||
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 { Sheet, SheetBody, SheetContent, SheetFooter, SheetHeader } from "@calcom/ui/components/sheet";
|
||||
import { Loader } from "@calcom/ui/components/skeleton";
|
||||
|
||||
import type { Dispatch } from "react";
|
||||
import { shallow } from "zustand/shallow";
|
||||
import type { UserTableAction, UserTableState } from "../types";
|
||||
import { DisplayInfo } from "./DisplayInfo";
|
||||
import { EditForm } from "./EditUserForm";
|
||||
@@ -35,34 +32,29 @@ export function EditUserSheet({
|
||||
}) {
|
||||
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 loadedUser = selectedUser as
|
||||
| (typeof selectedUser & {
|
||||
schedules?: { name: string }[];
|
||||
teams?: { name: string; accepted: boolean }[];
|
||||
bio?: string;
|
||||
avatarUrl?: string | null;
|
||||
role?: string;
|
||||
timeZone?: string;
|
||||
email?: string;
|
||||
username?: string;
|
||||
})
|
||||
| undefined;
|
||||
|
||||
type TeamWithAccepted = { name: string; accepted: boolean };
|
||||
|
||||
const avatarURL = `${WEBAPP_URL}/${loadedUser?.username}/avatar.png`;
|
||||
|
||||
const schedulesNames = loadedUser?.schedules?.map((s) => s.name);
|
||||
const teamNames = (loadedUser?.teams as TeamWithAccepted[] | undefined)?.map(
|
||||
(t) => `${t.name} ${!t.accepted ? "(pending)" : ""}`
|
||||
);
|
||||
|
||||
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}
|
||||
@@ -71,89 +63,62 @@ export function EditUserSheet({
|
||||
dispatch({ type: "CLOSE_MODAL" });
|
||||
}}>
|
||||
<SheetContent className="bg-default">
|
||||
{!isPending && loadedUser ? (
|
||||
<>
|
||||
{!editMode ? (
|
||||
<>
|
||||
<SheetHeader showCloseButton={false} className="w-full">
|
||||
<div className="border-subtle 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 -mt-8">
|
||||
{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>
|
||||
{loadedUser ? (
|
||||
!editMode ? (
|
||||
<>
|
||||
<SheetHeader showCloseButton={false} className="w-full">
|
||||
<div className="w-full rounded-xl border border-subtle bg-default p-4">
|
||||
<OrganizationBanner />
|
||||
<div className="ml-3 w-fit translate-y-[-50%] rounded-full bg-default p-1 ring-1 ring-[#0000000F]">
|
||||
<Avatar asChild size="lg" alt={`${loadedUser?.name} avatar`} imageSrc={avatarURL} />
|
||||
</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}
|
||||
<h2 className="-mt-8 font-sans font-semibold text-2xl text-emphasis">
|
||||
{loadedUser?.name || "Nameless User"}
|
||||
</h2>
|
||||
<p className="max-h-[3em] overflow-hidden text-ellipsis font-normal text-sm text-subtle">
|
||||
{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="mb-1 font-semibold text-base text-emphasis">{t("profile")}</h3>
|
||||
<DisplayInfo
|
||||
label="Cal"
|
||||
value={removeProtocol(`${WEBAPP_URL}/${loadedUser?.username}`)}
|
||||
icon="external-link"
|
||||
/>
|
||||
</SheetFooter>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<EditForm
|
||||
selectedUser={loadedUser}
|
||||
avatarUrl={loadedUser.avatarUrl ?? avatarURL}
|
||||
domainUrl={orgBranding?.fullDomain ?? WEBAPP_URL}
|
||||
dispatch={dispatch}
|
||||
<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>
|
||||
</SheetBody>
|
||||
<SheetFooter>
|
||||
<SheetFooterControls
|
||||
canEditAttributesForUser={canEditAttributesForUser}
|
||||
canChangeMemberRole={canChangeMemberRole}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
</SheetFooter>
|
||||
</>
|
||||
) : (
|
||||
<EditForm
|
||||
selectedUser={loadedUser}
|
||||
avatarUrl={loadedUser.avatarUrl ?? avatarURL}
|
||||
domainUrl={WEBAPP_URL}
|
||||
dispatch={dispatch}
|
||||
/>
|
||||
)
|
||||
) : (
|
||||
<Loader />
|
||||
)}
|
||||
|
||||
@@ -1,24 +1,11 @@
|
||||
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>
|
||||
</>
|
||||
<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",
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -1,52 +0,0 @@
|
||||
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>
|
||||
);
|
||||
}
|
||||
@@ -1,14 +1,9 @@
|
||||
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 { useSession } from "next-auth/react";
|
||||
import type { Dispatch } from "react";
|
||||
import type { UserTableAction } from "./types";
|
||||
|
||||
interface Props {
|
||||
@@ -17,64 +12,17 @@ interface Props {
|
||||
|
||||
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();
|
||||
const inviteMemberMutation = {
|
||||
mutate: (..._args: unknown[]) => {},
|
||||
mutateAsync: async () => ({}),
|
||||
isPending: false,
|
||||
};
|
||||
|
||||
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;
|
||||
const orgId = session?.user.org?.id;
|
||||
|
||||
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,
|
||||
});
|
||||
}}
|
||||
/>
|
||||
);
|
||||
return null;
|
||||
}
|
||||
@@ -1,20 +1,5 @@
|
||||
"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 { DataTableProvider } from "~/data-table/DataTableProvider";
|
||||
import { useColumnFilters } from "~/data-table/hooks/useColumnFilters";
|
||||
import { useDataTable } from "~/data-table/hooks/useDataTable";
|
||||
import {
|
||||
DataTableWrapper,
|
||||
DataTableToolbar,
|
||||
DataTableFilters,
|
||||
DataTableSegment,
|
||||
DataTableSelectionBar,
|
||||
} from "~/data-table/components";
|
||||
import { useSegments } from "~/data-table/hooks/useSegments";
|
||||
import { getUserAvatarUrl } from "@calcom/lib/getAvatarUrl";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
@@ -22,10 +7,23 @@ 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 { keepPreviousData } from "@tanstack/react-query";
|
||||
import { type ColumnDef, getCoreRowModel, getSortedRowModel, useReactTable } from "@tanstack/react-table";
|
||||
import { useMemo, useReducer, useState } from "react";
|
||||
import {
|
||||
DataTableFilters,
|
||||
DataTableSegment,
|
||||
DataTableSelectionBar,
|
||||
DataTableToolbar,
|
||||
DataTableWrapper,
|
||||
} from "~/data-table/components";
|
||||
import { DataTableProvider } from "~/data-table/DataTableProvider";
|
||||
import { useColumnFilters } from "~/data-table/hooks/useColumnFilters";
|
||||
import { useDataTable } from "~/data-table/hooks/useDataTable";
|
||||
import { useSegments } from "~/data-table/hooks/useSegments";
|
||||
import { DeleteBulkUsers } from "./BulkActions/DeleteBulkUsers";
|
||||
import { DeleteMemberModal } from "./DeleteMemberModal";
|
||||
import type { UserTableState, UserTableAction, PlatformManagedUserTableUser } from "./types";
|
||||
import type { PlatformManagedUserTableUser, UserTableAction, UserTableState } from "./types";
|
||||
|
||||
const initialState: UserTableState = {
|
||||
changeMemberRole: {
|
||||
@@ -80,19 +78,8 @@ function UserListTableContent({ oAuthClientId }: PlatformManagedUsersTableProps)
|
||||
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 data = { rows: [] as PlatformManagedUserTableUser[], meta: { totalRowCount: 0 } };
|
||||
const isPending = false;
|
||||
|
||||
const totalRowCount = data?.meta?.totalRowCount ?? 0;
|
||||
|
||||
@@ -186,7 +173,8 @@ function UserListTableContent({ oAuthClientId }: PlatformManagedUsersTableProps)
|
||||
},
|
||||
{
|
||||
id: "teams",
|
||||
accessorFn: (data) => data.teams.map((team) => team.name),
|
||||
accessorFn: (data) =>
|
||||
data.teams.map((team: { id: number; name: string; slug: string | null }) => team.name),
|
||||
header: t("teams"),
|
||||
size: 140,
|
||||
cell: ({ row, table }) => {
|
||||
@@ -210,7 +198,7 @@ function UserListTableContent({ oAuthClientId }: PlatformManagedUsersTableProps)
|
||||
</Badge>
|
||||
)}
|
||||
|
||||
{teams.map((team) => (
|
||||
{teams.map((team: { id: number; name: string; slug: string | null }) => (
|
||||
<Badge
|
||||
key={team.id}
|
||||
variant="gray"
|
||||
|
||||
@@ -2,16 +2,11 @@
|
||||
|
||||
import { checkAdminOrOwner } from "@calcom/features/auth/lib/checkAdminOrOwner";
|
||||
import { ColumnFilterType, convertFacetedValuesToMap, type FacetedValue } from "@calcom/features/data-table";
|
||||
import { DataTableProvider } from "~/data-table/DataTableProvider";
|
||||
import { useColumnFilters } from "~/data-table/hooks/useColumnFilters";
|
||||
import { useDataTable } from "~/data-table/hooks/useDataTable";
|
||||
import { useSegments } from "~/data-table/hooks/useSegments";
|
||||
import { useOrgBranding } from "@calcom/features/ee/organizations/context/provider";
|
||||
import type { MemberPermissions } from "@calcom/features/pbac/lib/team-member-permissions";
|
||||
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 { MembershipRole } from "@calcom/prisma/enums";
|
||||
import type { RouterOutputs } from "@calcom/trpc/react";
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
import type { FilterType } from "@calcom/types/data-table";
|
||||
@@ -20,7 +15,6 @@ 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 { LimitedBadges } from "@calcom/web/components/ui/LimitedBadges";
|
||||
import {
|
||||
generateCsvRawForMembersTable,
|
||||
@@ -48,15 +42,16 @@ import {
|
||||
DataTableToolbar,
|
||||
DataTableWrapper,
|
||||
} from "~/data-table/components";
|
||||
import { DataTableProvider } from "~/data-table/DataTableProvider";
|
||||
import { useColumnFilters } from "~/data-table/hooks/useColumnFilters";
|
||||
import { useDataTable } from "~/data-table/hooks/useDataTable";
|
||||
import { useSegments } from "~/data-table/hooks/useSegments";
|
||||
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 type { UserTableAction, UserTableState, UserTableUser } from "./types";
|
||||
import { TableActions } from "./UserTableActions";
|
||||
@@ -118,12 +113,30 @@ function reducer(state: UserTableState, action: UserTableAction): UserTableState
|
||||
}
|
||||
|
||||
type UserListTableProps = {
|
||||
org: RouterOutputs["viewer"]["organizations"]["listCurrent"];
|
||||
teams: RouterOutputs["viewer"]["organizations"]["getTeams"];
|
||||
attributes?: RouterOutputs["viewer"]["attributes"]["list"];
|
||||
org: { user?: { role?: string }; slug?: string; name?: string; canAdminImpersonate?: boolean };
|
||||
teams: {
|
||||
id: number;
|
||||
name: string;
|
||||
slug: string | null;
|
||||
logoUrl?: string | null;
|
||||
isOrganization?: boolean;
|
||||
}[];
|
||||
attributes?: {
|
||||
id: string;
|
||||
name: string;
|
||||
type: string;
|
||||
isWeightsEnabled?: boolean;
|
||||
options: { value: string; weight?: number }[];
|
||||
}[];
|
||||
facetedTeamValues?: {
|
||||
roles: { id: string; name: string }[];
|
||||
teams: RouterOutputs["viewer"]["organizations"]["getTeams"];
|
||||
teams: {
|
||||
id: number;
|
||||
name: string;
|
||||
slug: string | null;
|
||||
logoUrl?: string | null;
|
||||
isOrganization?: boolean;
|
||||
}[];
|
||||
attributes: {
|
||||
id: string;
|
||||
name: string;
|
||||
@@ -132,7 +145,17 @@ type UserListTableProps = {
|
||||
}[];
|
||||
}[];
|
||||
};
|
||||
permissions?: MemberPermissions;
|
||||
permissions?: {
|
||||
canRemoveMember: boolean;
|
||||
canChangeRole: boolean;
|
||||
canChangeMemberRole: boolean;
|
||||
canRemove: boolean;
|
||||
canInvite: boolean;
|
||||
canImpersonate: boolean;
|
||||
canResetPassword: boolean;
|
||||
canEditAttributesForUser: boolean;
|
||||
canViewAttributes: boolean;
|
||||
};
|
||||
};
|
||||
|
||||
function UserListTable(props: UserListTableProps): JSX.Element | null {
|
||||
@@ -153,12 +176,17 @@ function UserListTableContent({
|
||||
permissions,
|
||||
}: UserListTableProps): JSX.Element {
|
||||
const [dynamicLinkVisible, setDynamicLinkVisible] = useQueryState("dynamicLink", parseAsBoolean);
|
||||
const orgBranding = useOrgBranding();
|
||||
const domain = orgBranding?.fullDomain ?? WEBAPP_URL;
|
||||
const orgBranding = null as {
|
||||
slug?: string;
|
||||
name?: string;
|
||||
fullDomain?: string;
|
||||
canAdminImpersonate?: boolean;
|
||||
} | null;
|
||||
const domain = WEBAPP_URL;
|
||||
const { t } = useLocale();
|
||||
|
||||
const { data: session } = useSession();
|
||||
const { isPlatformUser } = useGetUserAttributes();
|
||||
const isPlatformUser = false;
|
||||
const [state, dispatch] = useReducer(reducer, initialState);
|
||||
const [isDownloading, setIsDownloading] = useState(false);
|
||||
const [rowSelection, setRowSelection] = useState({});
|
||||
@@ -167,20 +195,12 @@ function UserListTableContent({
|
||||
|
||||
const { limit, offset, searchTerm, ctaContainerRef } = useDataTable();
|
||||
|
||||
const { data, isPending } = trpc.viewer.organizations.listMembers.useQuery(
|
||||
{
|
||||
limit,
|
||||
offset,
|
||||
searchTerm,
|
||||
expand: ["attributes"],
|
||||
filters: columnFilters,
|
||||
},
|
||||
{
|
||||
placeholderData: keepPreviousData,
|
||||
}
|
||||
);
|
||||
const data = { rows: [] as UserTableUser[], meta: { totalRowCount: 0 } };
|
||||
const isPending = false;
|
||||
|
||||
const adminOrOwner = checkAdminOrOwner(org?.user?.role);
|
||||
const adminOrOwner = checkAdminOrOwner(
|
||||
org?.user?.role as import("@calcom/prisma/enums").MembershipRole | undefined
|
||||
);
|
||||
|
||||
//we must flatten the array of arrays from the useInfiniteQuery hook
|
||||
const flatData = useMemo<UserTableUser[]>(() => data?.rows ?? [], [data]);
|
||||
@@ -236,7 +256,7 @@ function UserListTableContent({
|
||||
return (
|
||||
<LimitedBadges
|
||||
items={attributeValues.map((attributeValue) => {
|
||||
const isAGroupOption = attributeValue.contains?.length > 0;
|
||||
const isAGroupOption = (attributeValue.contains?.length ?? 0) > 0;
|
||||
let weight = "";
|
||||
if (attribute.isWeightsEnabled) {
|
||||
weight = `${attributeValue.weight || 100}%`;
|
||||
@@ -316,12 +336,12 @@ function UserListTableContent({
|
||||
<div className="">
|
||||
<div
|
||||
data-testid={`member-${username}-username`}
|
||||
className="text-emphasis text-sm font-medium leading-none">
|
||||
className="font-medium text-emphasis text-sm leading-none">
|
||||
{displayName}
|
||||
</div>
|
||||
<div
|
||||
data-testid={`member-${username}-email`}
|
||||
className="text-subtle mt-1 text-sm leading-none">
|
||||
className="mt-1 text-sm text-subtle leading-none">
|
||||
{email}
|
||||
</div>
|
||||
</div>
|
||||
@@ -358,7 +378,16 @@ function UserListTableContent({
|
||||
},
|
||||
{
|
||||
id: "teams",
|
||||
accessorFn: (data: UserTableUser) => data.teams.map((team) => team.name),
|
||||
accessorFn: (data: UserTableUser) =>
|
||||
data.teams.map(
|
||||
(team: {
|
||||
id: number;
|
||||
name: string;
|
||||
slug: string | null;
|
||||
logoUrl?: string | null;
|
||||
isOrganization?: boolean;
|
||||
}) => team.name
|
||||
),
|
||||
header: t("teams"),
|
||||
size: 140,
|
||||
meta: {
|
||||
@@ -383,13 +412,21 @@ function UserListTableContent({
|
||||
)}
|
||||
|
||||
<LimitedBadges
|
||||
items={teams.map((team) => ({
|
||||
label: team.name,
|
||||
variant: "gray" as const,
|
||||
onClick: () => {
|
||||
table.getColumn("teams")?.setFilterValue([team.name]);
|
||||
},
|
||||
}))}
|
||||
items={teams.map(
|
||||
(team: {
|
||||
id: number;
|
||||
name: string;
|
||||
slug: string | null;
|
||||
logoUrl?: string | null;
|
||||
isOrganization?: boolean;
|
||||
}) => ({
|
||||
label: team.name,
|
||||
variant: "gray" as const,
|
||||
onClick: () => {
|
||||
table.getColumn("teams")?.setFilterValue([team.name]);
|
||||
},
|
||||
})
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
@@ -407,7 +444,9 @@ function UserListTableContent({
|
||||
type: ColumnFilterType.DATE_RANGE,
|
||||
},
|
||||
},
|
||||
cell: ({ row }: CellContext<UserTableUser, unknown>) => <div>{row.original.lastActiveAt}</div>,
|
||||
cell: ({ row }: CellContext<UserTableUser, unknown>) => (
|
||||
<div>{row.original.lastActiveAt?.toLocaleDateString() ?? ""}</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
id: "createdAt",
|
||||
@@ -420,7 +459,9 @@ function UserListTableContent({
|
||||
type: ColumnFilterType.DATE_RANGE,
|
||||
},
|
||||
},
|
||||
cell: ({ row }: CellContext<UserTableUser, unknown>) => <div>{row.original.createdAt || ""}</div>,
|
||||
cell: ({ row }: CellContext<UserTableUser, unknown>) => (
|
||||
<div>{row.original.createdAt?.toLocaleDateString() ?? ""}</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
id: "updatedAt",
|
||||
@@ -433,7 +474,9 @@ function UserListTableContent({
|
||||
type: ColumnFilterType.DATE_RANGE,
|
||||
},
|
||||
},
|
||||
cell: ({ row }: CellContext<UserTableUser, unknown>) => <div>{row.original.updatedAt || ""}</div>,
|
||||
cell: ({ row }: CellContext<UserTableUser, unknown>) => (
|
||||
<div>{row.original.updatedAt?.toLocaleDateString() ?? ""}</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
id: "completedOnboarding",
|
||||
@@ -494,7 +537,6 @@ function UserListTableContent({
|
||||
canRemove: (permissionsRaw.canRemove ?? false) && !isSelf,
|
||||
canImpersonate:
|
||||
user.accepted &&
|
||||
!user.disableImpersonation &&
|
||||
!isSelf &&
|
||||
!!org?.canAdminImpersonate &&
|
||||
(permissionsRaw.canImpersonate ?? false),
|
||||
@@ -596,13 +638,7 @@ function UserListTableContent({
|
||||
const limit = 100;
|
||||
|
||||
while (offset !== undefined) {
|
||||
const result = await utils.viewer.organizations.listMembers.fetch({
|
||||
limit,
|
||||
offset,
|
||||
searchTerm,
|
||||
expand: ["attributes"],
|
||||
filters: columnFilters,
|
||||
});
|
||||
const result = { rows: [] as UserTableUser[] };
|
||||
|
||||
if (!result.rows?.length) {
|
||||
offset = undefined;
|
||||
@@ -661,12 +697,17 @@ function UserListTableContent({
|
||||
)}
|
||||
{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">
|
||||
<p className="shrink-0 px-2 text-center text-brand-subtle text-xs leading-none sm:font-medium sm:text-sm">
|
||||
{t("number_selected", { count: numberOfSelectedRows })}
|
||||
</p>
|
||||
{!isPlatformUser && (
|
||||
<>
|
||||
{permissions?.canChangeMemberRole && <TeamListBulkAction table={table} />}
|
||||
{permissions?.canChangeMemberRole && (
|
||||
<DeleteBulkUsers
|
||||
users={table.getSelectedRowModel().flatRows.map((row) => row.original)}
|
||||
onRemove={() => table.toggleAllPageRowsSelected(false)}
|
||||
/>
|
||||
)}
|
||||
{numberOfSelectedRows >= 2 && (
|
||||
<DataTableSelectionBar.Button
|
||||
color="secondary"
|
||||
@@ -675,11 +716,11 @@ function UserListTableContent({
|
||||
{t("group_meeting")}
|
||||
</DataTableSelectionBar.Button>
|
||||
)}
|
||||
{(permissions?.canEditAttributesForUser ?? adminOrOwner) && (
|
||||
<MassAssignAttributesBulkAction table={table} filters={columnFilters} />
|
||||
)}
|
||||
{(permissions?.canChangeMemberRole ?? adminOrOwner) && (
|
||||
<EventTypesList table={table} orgTeams={teams} />
|
||||
<EventTypesList
|
||||
table={table}
|
||||
orgTeams={teams?.map((t) => ({ id: t.id, slug: t.slug ?? "", title: t.name }))}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
@@ -695,7 +736,7 @@ function UserListTableContent({
|
||||
|
||||
{state.deleteMember.showModal && <DeleteMemberModal state={state} dispatch={dispatch} />}
|
||||
{state.inviteMember.showModal && <InviteMemberModal dispatch={dispatch} />}
|
||||
{state.impersonateMember.showModal && <ImpersonationMemberModal dispatch={dispatch} state={state} />}
|
||||
{/* Impersonation modal removed (enterprise) */}
|
||||
{state.changeMemberRole.showModal && <ChangeUserRoleModal dispatch={dispatch} state={state} />}
|
||||
{state.editSheet.showModal && (
|
||||
<EditUserSheet
|
||||
|
||||
@@ -36,22 +36,17 @@ export function TableActions({
|
||||
}) {
|
||||
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 sendPasswordResetMutation = trpc.viewer.organizations.sendPasswordReset.useMutation({
|
||||
onSuccess: () => {
|
||||
showToast(t("password_reset_email_sent"), "success");
|
||||
},
|
||||
onError: (error) => {
|
||||
showToast(error.message, "error");
|
||||
},
|
||||
});
|
||||
const resendInvitationMutation = {
|
||||
mutate: (..._args: unknown[]) => {},
|
||||
mutateAsync: async () => ({}),
|
||||
isPending: false,
|
||||
};
|
||||
|
||||
const sendPasswordResetMutation = {
|
||||
mutate: (..._args: unknown[]) => {},
|
||||
mutateAsync: async () => ({}),
|
||||
isPending: false,
|
||||
};
|
||||
|
||||
const usersProfileUrl = `${domain}/${user.username}`;
|
||||
|
||||
|
||||
@@ -1,10 +1,31 @@
|
||||
import type { RouterOutputs } from "@calcom/trpc/react";
|
||||
|
||||
export type UserTableUser = RouterOutputs["viewer"]["organizations"]["listMembers"]["rows"][number];
|
||||
export type UserTableUser = {
|
||||
id: number;
|
||||
name: string | null;
|
||||
username: string | null;
|
||||
email: string;
|
||||
role: string;
|
||||
timeZone: string;
|
||||
bio: string | null;
|
||||
avatarUrl: string | null;
|
||||
accepted: boolean;
|
||||
completedOnboarding: boolean;
|
||||
lastActiveAt: Date | null;
|
||||
createdAt?: Date | null;
|
||||
updatedAt?: Date | null;
|
||||
customRole?: { name: string } | null;
|
||||
twoFactorEnabled?: boolean;
|
||||
teams: { id: number; name: string; slug: string | null }[];
|
||||
attributes: {
|
||||
attributeId: string;
|
||||
value: string;
|
||||
weight?: number;
|
||||
contains?: string[];
|
||||
}[];
|
||||
};
|
||||
|
||||
export type PlatformManagedUserTableUser = Omit<
|
||||
UserTableUser,
|
||||
"lastActiveAt" | "attributes" | "completedOnboarding" | "disableImpersonation"
|
||||
"lastActiveAt" | "attributes" | "completedOnboarding"
|
||||
>;
|
||||
|
||||
export type UserTablePayload = {
|
||||
|
||||
@@ -0,0 +1,241 @@
|
||||
"use client";
|
||||
|
||||
import { WEBAPP_URL } from "@calcom/lib/constants";
|
||||
import { useDebounce } from "@calcom/lib/hooks/useDebounce";
|
||||
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 { Button } from "@calcom/ui/components/button";
|
||||
import { ConfirmationDialogContent, Dialog } from "@calcom/ui/components/dialog";
|
||||
import { TextField } from "@calcom/ui/components/form";
|
||||
import { DropdownActions, Table } from "@calcom/ui/components/table";
|
||||
import { showToast } from "@calcom/ui/components/toast";
|
||||
import { keepPreviousData } from "@tanstack/react-query";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
|
||||
const { Cell, ColumnTitle, Header, Row } = Table;
|
||||
|
||||
const FETCH_LIMIT = 25;
|
||||
|
||||
export function UsersTable() {
|
||||
const { t } = useLocale();
|
||||
const tableContainerRef = useRef<HTMLDivElement>(null);
|
||||
const utils = trpc.useUtils();
|
||||
const [searchTerm, setSearchTerm] = useState<string>("");
|
||||
const debouncedSearchTerm = useDebounce(searchTerm, 500);
|
||||
const router = useRouter();
|
||||
|
||||
const [userToDelete, setUserToDelete] = useState<number | null>(null);
|
||||
|
||||
const deleteMutation = trpc.viewer.users.delete.useMutation({
|
||||
onSuccess: async () => {
|
||||
showToast(t("user_has_been_deleted"), "success");
|
||||
utils.viewer.admin.listPaginated.setInfiniteData({ limit: FETCH_LIMIT }, (cachedData) => {
|
||||
if (!cachedData) {
|
||||
return {
|
||||
pages: [],
|
||||
pageParams: [],
|
||||
};
|
||||
}
|
||||
return {
|
||||
...cachedData,
|
||||
pages: cachedData.pages.map((page) => ({
|
||||
...page,
|
||||
rows: page.rows.filter((row) => row.id !== userToDelete),
|
||||
})),
|
||||
};
|
||||
});
|
||||
},
|
||||
onError: (err) => {
|
||||
console.error(err.message);
|
||||
showToast(t("error_deleting_user"), "error");
|
||||
},
|
||||
onSettled: () => {
|
||||
setUserToDelete(null);
|
||||
},
|
||||
});
|
||||
|
||||
const { data, fetchNextPage, isFetching } = trpc.viewer.admin.listPaginated.useInfiniteQuery(
|
||||
{
|
||||
limit: FETCH_LIMIT,
|
||||
searchTerm: debouncedSearchTerm,
|
||||
},
|
||||
{
|
||||
getNextPageParam: (lastPage) => lastPage.nextCursor,
|
||||
placeholderData: keepPreviousData,
|
||||
refetchOnWindowFocus: false,
|
||||
}
|
||||
);
|
||||
|
||||
const sendPasswordResetEmail = trpc.viewer.admin.sendPasswordReset.useMutation({
|
||||
onSuccess: () => {
|
||||
showToast(t("password_reset_email_sent"), "success");
|
||||
},
|
||||
});
|
||||
|
||||
const removeTwoFactor = trpc.viewer.admin.removeTwoFactor.useMutation({
|
||||
onSuccess: () => {
|
||||
showToast(t("two_factor_removed"), "success");
|
||||
},
|
||||
});
|
||||
|
||||
const lockUserAccount = trpc.viewer.admin.lockUserAccount.useMutation({
|
||||
onSuccess: ({ locked }) => {
|
||||
showToast(locked ? t("user_locked") : t("user_unlocked"), "success");
|
||||
utils.viewer.admin.listPaginated.invalidate();
|
||||
},
|
||||
});
|
||||
|
||||
const flatData = useMemo(() => data?.pages?.flatMap((page) => page.rows) ?? [], [data]);
|
||||
const totalRowCount = data?.pages?.[0]?.meta?.totalRowCount ?? 0;
|
||||
const totalFetched = flatData.length;
|
||||
|
||||
const fetchMoreOnBottomReached = useCallback(
|
||||
(containerRefElement?: HTMLDivElement | null) => {
|
||||
if (containerRefElement) {
|
||||
const { scrollHeight, scrollTop, clientHeight } = containerRefElement;
|
||||
if (scrollHeight - scrollTop - clientHeight < 300 && !isFetching && totalFetched < totalRowCount) {
|
||||
fetchNextPage();
|
||||
}
|
||||
}
|
||||
},
|
||||
[fetchNextPage, isFetching, totalFetched, totalRowCount]
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
fetchMoreOnBottomReached(tableContainerRef.current);
|
||||
}, [fetchMoreOnBottomReached]);
|
||||
|
||||
return (
|
||||
<div>
|
||||
<TextField
|
||||
placeholder="username or email"
|
||||
label={t("search")}
|
||||
onChange={(e) => setSearchTerm(e.target.value)}
|
||||
/>
|
||||
<div
|
||||
className="border-subtle rounded-md border"
|
||||
ref={tableContainerRef}
|
||||
onScroll={() => fetchMoreOnBottomReached()}
|
||||
style={{
|
||||
height: "calc(100vh - 30vh)",
|
||||
overflow: "auto",
|
||||
}}>
|
||||
<Table>
|
||||
<Header>
|
||||
<ColumnTitle widthClassNames="w-auto">{t("user")}</ColumnTitle>
|
||||
<ColumnTitle>{t("timezone")}</ColumnTitle>
|
||||
<ColumnTitle>{t("role")}</ColumnTitle>
|
||||
<ColumnTitle widthClassNames="w-auto">
|
||||
<span className="sr-only">{t("edit")}</span>
|
||||
</ColumnTitle>
|
||||
</Header>
|
||||
|
||||
<tbody className="divide-subtle divide-y rounded-md">
|
||||
{flatData.map((user) => (
|
||||
<Row key={user.email}>
|
||||
<Cell widthClassNames="w-auto">
|
||||
<div className="min-h-10 flex">
|
||||
<Avatar
|
||||
size="md"
|
||||
alt={`Avatar of ${user.username || "Nameless"}`}
|
||||
imageSrc={`${WEBAPP_URL}/${user.username}/avatar.png`}
|
||||
/>
|
||||
<div className="text-subtle ml-4 font-medium">
|
||||
<div className="flex gap-3">
|
||||
<span className="text-default">{user.name}</span>
|
||||
<span>/{user.username}</span>
|
||||
{user.locked && <Badge variant="red">{t("locked")}</Badge>}
|
||||
</div>
|
||||
<span className="break-all">{user.email}</span>
|
||||
</div>
|
||||
</div>
|
||||
</Cell>
|
||||
<Cell>{user.timeZone}</Cell>
|
||||
<Cell>
|
||||
<Badge className="capitalize" variant={user.role === "ADMIN" ? "red" : "gray"}>
|
||||
{user.role.toLowerCase()}
|
||||
</Badge>
|
||||
</Cell>
|
||||
<Cell widthClassNames="w-auto">
|
||||
<div className="flex w-full justify-end">
|
||||
<DropdownActions
|
||||
actions={[
|
||||
{
|
||||
id: "edit",
|
||||
label: t("edit"),
|
||||
href: `/settings/admin/users/${user.id}/edit`,
|
||||
icon: "pencil" as const,
|
||||
},
|
||||
{
|
||||
id: "reset-password",
|
||||
label: t("reset_password"),
|
||||
onClick: () => sendPasswordResetEmail.mutate({ userId: user.id }),
|
||||
icon: "lock" as const,
|
||||
},
|
||||
{
|
||||
id: "lock-user",
|
||||
label: user.locked ? t("unlock_user_account") : t("lock_user_account"),
|
||||
onClick: () => lockUserAccount.mutate({ userId: user.id, locked: !user.locked }),
|
||||
icon: "lock" as const,
|
||||
},
|
||||
{
|
||||
id: "remove-2fa",
|
||||
label: t("remove_2fa"),
|
||||
color: "destructive" as const,
|
||||
onClick: () => removeTwoFactor.mutate({ userId: user.id }),
|
||||
icon: "shield" as const,
|
||||
},
|
||||
{
|
||||
id: "delete",
|
||||
label: t("delete"),
|
||||
color: "destructive" as const,
|
||||
onClick: () => setUserToDelete(user.id),
|
||||
icon: "trash" as const,
|
||||
},
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
</Cell>
|
||||
</Row>
|
||||
))}
|
||||
</tbody>
|
||||
</Table>
|
||||
<DeleteUserDialog
|
||||
user={userToDelete}
|
||||
onClose={() => setUserToDelete(null)}
|
||||
onConfirm={() => {
|
||||
if (!userToDelete) return;
|
||||
deleteMutation.mutate({ userId: userToDelete });
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function DeleteUserDialog({
|
||||
user,
|
||||
onConfirm,
|
||||
onClose,
|
||||
}: {
|
||||
user: number | null;
|
||||
onConfirm: () => void;
|
||||
onClose: () => void;
|
||||
}) {
|
||||
const { t } = useLocale();
|
||||
return (
|
||||
<Dialog open={!!user} onOpenChange={(open) => (open ? undefined : onClose())}>
|
||||
<ConfirmationDialogContent
|
||||
title={t("delete_user")}
|
||||
confirmBtnText={t("delete")}
|
||||
cancelBtnText={t("cancel")}
|
||||
variety="danger"
|
||||
onConfirm={onConfirm}>
|
||||
<p>{t("delete_user_confirmation")}</p>
|
||||
</ConfirmationDialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -1,12 +1,11 @@
|
||||
import type { Table } from "@tanstack/react-table";
|
||||
import { describe, it, expect, vi } from "vitest";
|
||||
|
||||
import { MembershipRole } from "@calcom/prisma/enums";
|
||||
import type { UserTableUser } from "@calcom/web/modules/users/components/UserTable/types";
|
||||
import {
|
||||
generateCsvRawForMembersTable,
|
||||
generateHeaderFromReactTable,
|
||||
} from "@calcom/web/modules/users/lib/UserListTableUtils";
|
||||
import { MembershipRole } from "@calcom/prisma/enums";
|
||||
import type { UserTableUser } from "@calcom/web/modules/users/components/UserTable/types";
|
||||
import type { Table } from "@tanstack/react-table";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
function createMockTable(data: UserTableUser[]): Table<UserTableUser> {
|
||||
return {
|
||||
@@ -65,24 +64,17 @@ describe("generate Csv for Org Users Table", () => {
|
||||
email: "[email protected]",
|
||||
timeZone: "UTC",
|
||||
role: MembershipRole.MEMBER,
|
||||
bio: null,
|
||||
avatarUrl: null,
|
||||
accepted: true,
|
||||
disableImpersonation: false,
|
||||
completedOnboarding: true,
|
||||
teams: [],
|
||||
attributes: [],
|
||||
lastActiveAt: new Date().toISOString(),
|
||||
lastActiveAt: new Date(),
|
||||
createdAt: null,
|
||||
updatedAt: null,
|
||||
customRole: {
|
||||
type: "SYSTEM",
|
||||
id: "member_role",
|
||||
name: "Member",
|
||||
description: "Default member role",
|
||||
teamId: null,
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
color: null,
|
||||
},
|
||||
};
|
||||
|
||||
@@ -109,13 +101,10 @@ describe("generate Csv for Org Users Table", () => {
|
||||
teams: [{ id: 1, name: "Team1", slug: "team1" }],
|
||||
attributes: [
|
||||
{
|
||||
id: "1",
|
||||
attributeId: "attr1",
|
||||
value: "value1",
|
||||
slug: "slug1",
|
||||
contains: [],
|
||||
weight: 0,
|
||||
isGroup: false,
|
||||
},
|
||||
],
|
||||
},
|
||||
@@ -142,22 +131,16 @@ describe("generate Csv for Org Users Table", () => {
|
||||
teams: [{ id: 1, name: "Team1", slug: "team1" }],
|
||||
attributes: [
|
||||
{
|
||||
id: "1",
|
||||
attributeId: "attr1",
|
||||
value: "value1",
|
||||
slug: "slug1",
|
||||
contains: [],
|
||||
weight: 0,
|
||||
isGroup: false,
|
||||
},
|
||||
{
|
||||
id: "2",
|
||||
attributeId: "attr1",
|
||||
value: "value2",
|
||||
slug: "slug1",
|
||||
contains: [],
|
||||
weight: 0,
|
||||
isGroup: false,
|
||||
},
|
||||
],
|
||||
},
|
||||
@@ -210,13 +193,10 @@ describe("generate Csv for Org Users Table", () => {
|
||||
teams: [{ id: 1, name: "Team,1", slug: "team1" }],
|
||||
attributes: [
|
||||
{
|
||||
id: "1",
|
||||
attributeId: "attr1",
|
||||
value: "value,1",
|
||||
slug: "slug1",
|
||||
contains: [],
|
||||
weight: 0,
|
||||
isGroup: false,
|
||||
},
|
||||
],
|
||||
},
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import type { Table } from "@tanstack/react-table";
|
||||
|
||||
import { sanitizeValue } from "@calcom/lib/csvUtils";
|
||||
import type { UserTableUser } from "@calcom/web/modules/users/components/UserTable/types";
|
||||
import type { Table } from "@tanstack/react-table";
|
||||
|
||||
export const generateHeaderFromReactTable = (table: Table<UserTableUser>): string[] | null => {
|
||||
const headerGroups = table.getHeaderGroups();
|
||||
@@ -59,7 +58,10 @@ export const generateCsvRawForMembersTable = (
|
||||
|
||||
// Create a map of attributeId to array of values
|
||||
const attributeMap = (attributes ?? []).reduce(
|
||||
(acc, attr) => {
|
||||
(
|
||||
acc: Record<string, (string | { value: string; weight?: number })[]>,
|
||||
attr: { attributeId: string; value: string; weight?: number }
|
||||
) => {
|
||||
if (!acc[attr.attributeId]) {
|
||||
acc[attr.attributeId] = [];
|
||||
}
|
||||
@@ -76,7 +78,7 @@ export const generateCsvRawForMembersTable = (
|
||||
email, // Members column
|
||||
`${orgDomain}/${username}`, // Link column
|
||||
role, // Role column
|
||||
sanitizeValue(teams.map((team) => team.name).join(",")), // Teams column
|
||||
sanitizeValue(teams.map((team: { id: number; name: string }) => team.name).join(",")), // Teams column
|
||||
];
|
||||
|
||||
// Add attribute columns
|
||||
@@ -85,7 +87,12 @@ export const generateCsvRawForMembersTable = (
|
||||
if (!attributes?.length) return "";
|
||||
|
||||
return sanitizeValue(
|
||||
attributes.map((attr) => (attr.weight ? `${attr.value} (${attr.weight}%)` : attr.value)).join(",")
|
||||
attributes
|
||||
.map((attr) => {
|
||||
if (typeof attr === "string") return attr;
|
||||
return attr.weight ? `${attr.value} (${attr.weight}%)` : attr.value;
|
||||
})
|
||||
.join(",")
|
||||
);
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
"use client";
|
||||
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
import { showToast } from "@calcom/ui/components/toast";
|
||||
import { usePathname, useRouter } from "next/navigation";
|
||||
import type { FormValues } from "../components/UserForm";
|
||||
import { UserForm } from "../components/UserForm";
|
||||
|
||||
export default function UsersAddView() {
|
||||
const { t } = useLocale();
|
||||
const pathname = usePathname();
|
||||
const router = useRouter();
|
||||
const utils = trpc.useUtils();
|
||||
|
||||
const mutation = trpc.viewer.users.add.useMutation({
|
||||
onSuccess: async () => {
|
||||
showToast(t("user_added_successfully"), "success");
|
||||
await utils.viewer.users.list.invalidate();
|
||||
if (pathname !== null) {
|
||||
router.replace(pathname.replace("/add", ""));
|
||||
}
|
||||
},
|
||||
onError: (err) => {
|
||||
console.error(err.message);
|
||||
showToast(t("error_adding_user"), "error");
|
||||
},
|
||||
});
|
||||
|
||||
return (
|
||||
<UserForm
|
||||
submitLabel="add"
|
||||
onSubmit={(values: FormValues) => {
|
||||
const data: Record<string, unknown> = {
|
||||
name: values.name,
|
||||
email: values.email,
|
||||
username: values.username,
|
||||
bio: values.bio,
|
||||
timeZone: values.timeZone,
|
||||
weekStart: values.weekStart?.value,
|
||||
theme: values.theme,
|
||||
defaultScheduleId: values.defaultScheduleId,
|
||||
locale: values.locale?.value,
|
||||
timeFormat: values.timeFormat?.value,
|
||||
allowDynamicBooking: values.allowDynamicBooking,
|
||||
identityProvider: values.identityProvider?.value,
|
||||
role: values.role?.value,
|
||||
avatarUrl: values.avatarUrl,
|
||||
};
|
||||
mutation.mutate(data as Parameters<typeof mutation.mutate>[0]);
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
"use client";
|
||||
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
import { showToast } from "@calcom/ui/components/toast";
|
||||
import { usePathname, useRouter } from "next/navigation";
|
||||
import type { FormValues } from "../components/UserForm";
|
||||
import { UserForm } from "../components/UserForm";
|
||||
|
||||
interface User {
|
||||
id: number;
|
||||
name: string | null;
|
||||
email: string;
|
||||
username: string | null;
|
||||
bio: string | null;
|
||||
timeZone: string;
|
||||
weekStart: string;
|
||||
theme: string | null;
|
||||
defaultScheduleId: number | null;
|
||||
locale: string | null;
|
||||
timeFormat: number | null;
|
||||
allowDynamicBooking: boolean | null;
|
||||
identityProvider: string | null;
|
||||
role: string | null;
|
||||
avatarUrl: string | null;
|
||||
createdDate?: string | Date;
|
||||
}
|
||||
|
||||
export function UsersEditView({ user }: { user: User }) {
|
||||
const { t } = useLocale();
|
||||
const pathname = usePathname();
|
||||
const router = useRouter();
|
||||
const utils = trpc.useUtils();
|
||||
|
||||
const mutation = trpc.viewer.users.update.useMutation({
|
||||
onSuccess: async () => {
|
||||
await Promise.all([utils.viewer.users.list.invalidate(), utils.viewer.users.get.invalidate()]);
|
||||
showToast(t("user_updated_successfully"), "success");
|
||||
router.replace(`${pathname?.split("/users/")[0]}/users`);
|
||||
},
|
||||
onError: (err) => {
|
||||
console.error(err.message);
|
||||
showToast(t("error_updating_user"), "error");
|
||||
},
|
||||
});
|
||||
|
||||
return (
|
||||
<UserForm
|
||||
key={JSON.stringify(user)}
|
||||
onSubmit={(values: FormValues) => {
|
||||
const data: Record<string, unknown> = {
|
||||
name: values.name,
|
||||
email: values.email,
|
||||
username: values.username,
|
||||
bio: values.bio,
|
||||
timeZone: values.timeZone,
|
||||
weekStart: values.weekStart?.value,
|
||||
theme: values.theme,
|
||||
defaultScheduleId: values.defaultScheduleId,
|
||||
locale: values.locale?.value,
|
||||
timeFormat: values.timeFormat?.value,
|
||||
allowDynamicBooking: values.allowDynamicBooking,
|
||||
identityProvider: values.identityProvider?.value,
|
||||
role: values.role?.value,
|
||||
avatarUrl: values.avatarUrl,
|
||||
userId: user.id,
|
||||
};
|
||||
if (user.username === data.username) delete data.username;
|
||||
mutation.mutate(data as Parameters<typeof mutation.mutate>[0]);
|
||||
}}
|
||||
defaultValues={user}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export default UsersEditView;
|
||||
@@ -0,0 +1,12 @@
|
||||
"use client";
|
||||
|
||||
import NoSSR from "@calcom/lib/components/NoSSR";
|
||||
import { UsersTable } from "../components/UsersTable";
|
||||
|
||||
export default function UsersListingView() {
|
||||
return (
|
||||
<NoSSR>
|
||||
<UsersTable />
|
||||
</NoSSR>
|
||||
);
|
||||
}
|
||||
@@ -1,19 +1,12 @@
|
||||
import { useRouterQuery } from "@calcom/lib/hooks/useRouterQuery";
|
||||
import { render } from "@testing-library/react";
|
||||
import { describe, it, vi } from "vitest";
|
||||
|
||||
import { getOrgFullOrigin } from "@calcom/ee/organizations/lib/orgDomains";
|
||||
import { useRouterQuery } from "@calcom/lib/hooks/useRouterQuery";
|
||||
|
||||
import UserPage from "./users-public-view";
|
||||
|
||||
vi.mock("@calcom/lib/constants", async () => {
|
||||
return await vi.importActual("@calcom/lib/constants");
|
||||
});
|
||||
|
||||
vi.mock("@calcom/ee/organizations/lib/orgDomains", () => ({
|
||||
getOrgFullOrigin: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("@calcom/lib/hooks/useRouterQuery", () => ({
|
||||
useRouterQuery: vi.fn(),
|
||||
}));
|
||||
@@ -66,7 +59,7 @@ function mockedUserPageComponentProps(props: Partial<React.ComponentProps<typeof
|
||||
}
|
||||
|
||||
describe("UserPage Component", () => {
|
||||
it("should render with no throw", () => {
|
||||
it("should render with no throw", async () => {
|
||||
const mockData = {
|
||||
props: mockedUserPageComponentProps({
|
||||
entity: {
|
||||
@@ -76,10 +69,6 @@ describe("UserPage Component", () => {
|
||||
}),
|
||||
};
|
||||
|
||||
vi.mocked(getOrgFullOrigin).mockImplementation((orgSlug: string | null) => {
|
||||
return `${orgSlug}.cal.local`;
|
||||
});
|
||||
|
||||
vi.mocked(useRouterQuery).mockReturnValue({
|
||||
uid: "uid",
|
||||
});
|
||||
|
||||
Reference in new issue
Block a user