refactor: Move trpc-dependent components from features to web [1] (#25859)

* refactor: migrate UnconfirmedBookingBadge from features to apps/web

Move UnconfirmedBookingBadge.tsx from packages/features/bookings/ to
apps/web/modules/bookings/components/ as part of the architectural
refactor to remove trpc client imports from the features layer.

Also removes unused preserveBookingsQueryParams function from Navigation.tsx.

Co-Authored-By: [email protected] <[email protected]>

* refactor: move shell navigation and badges to apps/web

Move shell navigation components and trpc-using badges from
packages/features to apps/web/modules to fix circular dependency:

- Move navigation folder to apps/web/modules/shell/navigation/
- Move TeamInviteBadge.tsx to apps/web/modules/shell/
- Create Shell wrapper in apps/web that provides MobileNavigationContainer
- Update all Shell imports in apps/web to use the new wrapper
- Remove MobileNavigationContainer default from features Shell.tsx
- Fix pre-existing lint warnings in touched files

This establishes the pattern for migrating React components that use
trpc hooks from the features layer to the web app layer, ensuring
proper dependency direction: apps/web imports from packages/features,
never the reverse.

Co-Authored-By: [email protected] <[email protected]>

* fix: move SideBar.tsx to apps/web to fix build error

SideBar.tsx was importing Navigation from the moved navigation folder,
causing a build error. Moving SideBar.tsx to apps/web and updating the
features Shell to not have a default SidebarContainer fixes this.

The web Shell wrapper now provides both the default SidebarContainer
and MobileNavigationContainer, maintaining the injection pattern.

Co-Authored-By: [email protected] <[email protected]>

* revert

* revert

* revert

* wip

* wip

* wip

* wip

* wip

* wip

* not used anywhere

* wip

* wip

* wip

* wip

* fix

* fix

* wip

* wip

* wip

* wip

* wip

* fix

* fix

* fix

* fix

* migrate

* migrate admin-adpi

* wip

* feat: migrate organization settings components from packages/features to apps/web/modules

- Migrate profile.tsx, appearance.tsx, general.tsx, privacy.tsx, guest-notifications.tsx, delegationCredential.tsx, other-team-members-view.tsx, other-team-profile-view.tsx
- Migrate attributes directory (AttributesForm.tsx, DeleteAttributeModal.tsx, ListSkeleton.tsx, attributes-create-view.tsx, attributes-edit-view.tsx, attributes-list-view.tsx)
- Migrate admin directory (AdminOrgEditPage.tsx, AdminOrgPage.tsx, WorkspacePlatformPage.tsx)
- Update all page imports to use new paths from ~/settings/organizations/
- Update relative imports in migrated files to use @calcom/features paths
- Fix lint warnings in migrated files

Co-Authored-By: [email protected] <[email protected]>

* fix: update test import path after migration

Co-Authored-By: [email protected] <[email protected]>

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

Co-Authored-By: [email protected] <[email protected]>

* wip

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

Co-Authored-By: [email protected] <[email protected]>

* wip

* wip

* wip

* wip

* wip

* wip

* wip

* wip

* wip

* wip

* wip

* wip

* wip

* fix

* fix

* fix

* fix

* wip

* refactor more

* wip

* wip

* wip

* wip

* wip

* wip

* wip

* wip

* wip

* wip

* mv

* update import paths

* wip

* wip

* fix

* fix

* fix

* fix

* fix

* fix

* fix

* mv

* mv

* mv

* fix

* wip

* wip

* fix

* fix

* fix

* fix: make test mocks resilient to vi.resetAllMocks()

Co-Authored-By: [email protected] <[email protected]>

* fix: fix AttributeForm test failures

Co-Authored-By: [email protected] <[email protected]>

* fix

* fix

* refactor: move ee files to apps/web/modules/ee/ folder

- Move teams, workflows, and organizations folders to apps/web/modules/ee/
- Add LICENSE file to apps/web/modules/ee/
- Update all import paths from ~/teams/ to ~/ee/teams/
- Update all import paths from ~/settings/organizations/ to ~/ee/organizations/
- Remove duplicate MemberInvitationModal copy.tsx file

Co-Authored-By: [email protected] <[email protected]>

* fix: move useHasPaidPlan and dependent files to apps/web/modules

- Move useHasPaidPlan.ts from packages/features/billing/hooks to apps/web/modules/billing/hooks
- Move intercom files from packages/features/ee/support to apps/web/modules/ee/support
- Move ContactMenuItem.tsx and dependencies (freshchat, helpscout, zendesk) to apps/web/modules/ee/support
- Move ViewRecordingsDialog.tsx and RecordingListSkeleton to apps/web/modules/ee/video
- Move CalVideoSettings.tsx to apps/web/modules/eventtypes/components/locations
- Move CreateOrEditOutOfOfficeModal.tsx to apps/web/modules/settings/outOfOffice
- Refactor UpgradeTeamsBadge to accept props and create wrapper in apps/web/modules/billing
- Update all callers to use new file locations
- Add eslint-disable comments for pre-existing lint warnings

This fixes the tRPC server build failure caused by circular dependency where
the server build was traversing into packages/features and pulling in React
hooks that depend on @calcom/trpc/react types.

Co-Authored-By: [email protected] <[email protected]>

* fix: correct UpgradeTeamsBadge import path to use package export

Co-Authored-By: [email protected] <[email protected]>

* wip

* wip

* wip

* wip

* wip

* wip

* wip

* wip

* wip

* wip

* wip

* wip

* wip

* wip

* wip

* fix

* fix

* fix

* fix

* fix

* fix

* fix

* fix: pass plan state through SelectProps to UpgradeTeamsBadge

- Add upgradeTeamsBadgeProps field to ExtendedOption type in Select component
- Update OptionComponent to spread upgradeTeamsBadgeProps to UpgradeTeamsBadge
- Update getOptions.ts to accept PlanState object and include upgradeTeamsBadgeProps
- Update WorkflowStepContainer.tsx to pass planState to getWorkflowTriggerOptions/getWorkflowTemplateOptions
- Update WorkflowDetailsPage.tsx to pass upgradeTeamsBadgeProps in transformed action options
- Update AddActionDialog.tsx interface and mapping to include upgradeTeamsBadgeProps
- Add eslint-disable comments for pre-existing React Hook dependency warnings

This fixes the UpgradeTeamsBadge refactoring issue where the badge was always showing
'upgrade' text instead of the correct text based on plan state (trial_mode, inactive_team_plan, etc.)

Co-Authored-By: [email protected] <[email protected]>

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

Co-Authored-By: [email protected] <[email protected]>

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

Co-Authored-By: [email protected] <[email protected]>

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

Co-Authored-By: [email protected] <[email protected]>

* fix: extract BookingRedirectForm type to shared location

Co-Authored-By: [email protected] <[email protected]>

* fix

* wip

* wip

* fix: update BookingRedirectForm import to use local types file

Co-Authored-By: [email protected] <[email protected]>

* wip

* fix

* fix

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
This commit is contained in:
Benny JooandDevin AI authored and GitHub committed 2025-12-23 12:22:26 -03:00
1 parent 7847177e8b
commit 8afe87ff75
374 files changed
+1213 -1417

No files matched your search

@@ -1,45 +0,0 @@
"use client";
import { checkAdminOrOwner } from "@calcom/features/auth/lib/checkAdminOrOwner";
import { useCompatSearchParams } from "@calcom/lib/hooks/useCompatSearchParams";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { trpc } from "@calcom/trpc/react";
import useMeQuery from "@calcom/trpc/react/hooks/useMeQuery";
import type { ButtonProps } from "@calcom/ui/components/button";
import { Button } from "@calcom/ui/components/button";
import { OutOfOfficeTab } from "./OutOfOfficeToggleGroup";
const CreateNewOutOfOfficeEntryButton = ({
size,
onClick,
...rest
}: {
size?: ButtonProps["size"];
onClick: () => void;
"data-testid"?: string;
}) => {
const { t } = useLocale();
const me = useMeQuery();
const { data: orgData } = trpc.viewer.organizations.listCurrent.useQuery();
const isOrgAdminOrOwner = orgData && checkAdminOrOwner(orgData.user.role);
const hasTeamOOOAdminAccess = isOrgAdminOrOwner || me?.data?.isTeamAdminOrOwner;
const params = useCompatSearchParams();
const selectedTab = params?.get("type") ?? OutOfOfficeTab.MINE;
return (
<Button
color="primary"
size={size ?? "base"}
className="flex items-center justify-between px-2 md:px-4"
StartIcon="plus"
onClick={onClick}
data-testid={rest["data-testid"]}
disabled={selectedTab === OutOfOfficeTab.TEAM && !hasTeamOOOAdminAccess}>
<span className="sr-only md:not-sr-only md:inline">{t("add")}</span>
</Button>
);
};
export default CreateNewOutOfOfficeEntryButton;
@@ -1,528 +0,0 @@
import { useMemo, useState } from "react";
import { Controller, useForm } from "react-hook-form";
import dayjs from "@calcom/dayjs";
import { useHasTeamPlan } from "@calcom/features/billing/hooks/useHasPaidPlan";
import { Dialog } from "@calcom/features/components/controlled-dialog";
import { useCompatSearchParams } from "@calcom/lib/hooks/useCompatSearchParams";
import { useDebounce } from "@calcom/lib/hooks/useDebounce";
import { useInViewObserver } from "@calcom/lib/hooks/useInViewObserver";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { trpc } from "@calcom/trpc/react";
import useMeQuery from "@calcom/trpc/react/hooks/useMeQuery";
import classNames from "@calcom/ui/classNames";
import { Alert } from "@calcom/ui/components/alert";
import { UpgradeTeamsBadge } from "@calcom/ui/components/badge";
import { Button } from "@calcom/ui/components/button";
import { DialogContent, DialogFooter, DialogHeader } from "@calcom/ui/components/dialog";
import { DateRangePicker, TextArea, Input, Checkbox } from "@calcom/ui/components/form";
import { Label } from "@calcom/ui/components/form";
import { Select } from "@calcom/ui/components/form";
import { Switch } from "@calcom/ui/components/form";
import { showToast } from "@calcom/ui/components/toast";
import { OutOfOfficeTab } from "./OutOfOfficeToggleGroup";
export type BookingRedirectForm = {
dateRange: { startDate: Date; endDate: Date };
startDateOffset: number;
endDateOffset: number;
toTeamUserId: number | null;
reasonId: number;
notes?: string;
showNotePublicly?: boolean;
uuid?: string | null;
forUserId: number | null;
forUserName?: string;
forUserAvatar?: string;
toUserName?: string;
};
type Option = { value: number; label: string };
export const CreateOrEditOutOfOfficeEntryModal = ({
openModal,
closeModal,
currentlyEditingOutOfOfficeEntry,
}: {
openModal: boolean;
closeModal: () => void;
currentlyEditingOutOfOfficeEntry: BookingRedirectForm | null;
}) => {
const { t } = useLocale();
const utils = trpc.useUtils();
const me = useMeQuery();
const searchParams = useCompatSearchParams();
const oooType = searchParams?.get("type") ?? OutOfOfficeTab.MINE;
const [searchMember, setSearchMember] = useState("");
const debouncedSearchMember = useDebounce(searchMember, 500);
const oooForMembers = trpc.viewer.teams.legacyListMembers.useInfiniteQuery(
{ limit: 10, searchText: debouncedSearchMember, adminOrOwnedTeamsOnly: true },
{
enabled: oooType === OutOfOfficeTab.TEAM,
getNextPageParam: (lastPage) => lastPage.nextCursor,
}
);
const oooMemberListOptions: {
value: number;
label: string;
avatarUrl: string | null;
}[] = currentlyEditingOutOfOfficeEntry
? [
{
value: currentlyEditingOutOfOfficeEntry.forUserId || -1,
label: currentlyEditingOutOfOfficeEntry.forUserName || "",
avatarUrl: currentlyEditingOutOfOfficeEntry.forUserAvatar || "",
},
]
: oooForMembers?.data?.pages
.flatMap((page) => page.members)
?.filter((member) => me?.data?.id !== member.id)
.map((member) => ({
value: member.id,
label: member.name || member.username || "",
avatarUrl: member.avatarUrl,
})) || [];
const { ref: observerRefMember } = useInViewObserver(() => {
if (oooForMembers.hasNextPage && !oooForMembers.isFetching) {
oooForMembers.fetchNextPage();
}
}, document.querySelector('[role="dialog"]'));
const [searchRedirectMember, setSearchRedirectMember] = useState("");
const debouncedSearchRedirect = useDebounce(searchRedirectMember, 500);
const redirectMembers = trpc.viewer.teams.legacyListMembers.useInfiniteQuery(
{
limit: 10,
searchText: debouncedSearchRedirect,
adminOrOwnedTeamsOnly: oooType === OutOfOfficeTab.TEAM,
},
{
enabled: true,
getNextPageParam: (lastPage) => lastPage.nextCursor,
}
);
const redirectToMemberListOptions: {
value: number;
label: string;
avatarUrl: string | null;
}[] =
redirectMembers?.data?.pages
.flatMap((page) => page.members)
?.filter((member) =>
oooType === OutOfOfficeTab.MINE ? me?.data?.id !== member.id : oooType === OutOfOfficeTab.TEAM
)
.map((member) => ({
value: member.id,
label: member.name || member.username || "",
avatarUrl: member.avatarUrl,
})) || [];
const { ref: observerRefRedirect } = useInViewObserver(() => {
if (redirectMembers.hasNextPage && !redirectMembers.isFetching) {
redirectMembers.fetchNextPage();
}
}, document.querySelector('[role="dialog"]'));
const { data: outOfOfficeReasonList, isPending: isReasonListPending } =
trpc.viewer.ooo.outOfOfficeReasonList.useQuery();
const reasonList = (outOfOfficeReasonList || []).map((reason) => ({
label: `${reason.emoji} ${reason.userId === null ? t(reason.reason) : reason.reason}`,
value: reason.id,
}));
const [profileRedirect, setProfileRedirect] = useState(!!currentlyEditingOutOfOfficeEntry?.toTeamUserId);
const { hasTeamPlan } = useHasTeamPlan();
const {
handleSubmit,
setValue,
control,
register,
watch,
formState: { isSubmitting },
getValues,
} = useForm<BookingRedirectForm>({
defaultValues: currentlyEditingOutOfOfficeEntry
? currentlyEditingOutOfOfficeEntry
: {
dateRange: {
startDate: dayjs().startOf("d").toDate(),
endDate: dayjs().startOf("d").add(2, "d").toDate(),
},
startDateOffset: dayjs().utcOffset(),
endDateOffset: dayjs().utcOffset(),
toTeamUserId: null,
reasonId: 1,
forUserId: null,
showNotePublicly: false,
},
});
const watchedTeamUserId = watch("toTeamUserId");
const watchForUserId = watch("forUserId");
const watchedDateRange = watch("dateRange");
const watchedNotes = watch("notes");
const hasValidNotes = Boolean(watchedNotes?.trim());
// Fetch user's holiday settings to show warning if OOO dates overlap with holidays
const { data: holidaySettings } = trpc.viewer.holidays.getUserSettings.useQuery({});
// Check if selected dates overlap with any enabled holidays
const overlappingHolidays = useMemo(() => {
if (!holidaySettings?.countryCode || !watchedDateRange?.startDate || !watchedDateRange?.endDate) {
return [];
}
// Filter holidays that are enabled and fall within the date range
const startStr = dayjs(watchedDateRange.startDate).format("YYYY-MM-DD");
const endStr = dayjs(watchedDateRange.endDate).format("YYYY-MM-DD");
return (holidaySettings.holidays || [])
.filter((h) => h.enabled && h.date >= startStr && h.date <= endStr)
.map((h) => ({ date: h.date, holiday: { id: h.id, name: h.name } }));
}, [holidaySettings, watchedDateRange]);
const createOrEditOutOfOfficeEntry = trpc.viewer.ooo.outOfOfficeCreateOrUpdate.useMutation({
onSuccess: () => {
showToast(
currentlyEditingOutOfOfficeEntry
? t("success_edited_entry_out_of_office")
: t("success_entry_created"),
"success"
);
utils.viewer.ooo.outOfOfficeEntriesList.invalidate();
closeModal();
},
onError: (error) => {
showToast(t(error.message), "error");
},
});
return (
<Dialog
open={openModal}
onOpenChange={(open) => {
if (!open) {
closeModal();
}
}}>
<DialogContent
enableOverflow
onOpenAutoFocus={(event) => {
event.preventDefault();
}}>
<form
id="create-or-edit-ooo-form"
onSubmit={handleSubmit((data) => {
if (!data.dateRange.endDate) {
showToast(t("end_date_not_selected"), "error");
} else {
createOrEditOutOfOfficeEntry.mutate({
...data,
startDateOffset: -1 * data.dateRange.startDate.getTimezoneOffset(),
endDateOffset: -1 * data.dateRange.endDate.getTimezoneOffset(),
});
}
})}>
<div className="h-full px-1">
<DialogHeader
title={
currentlyEditingOutOfOfficeEntry
? t("edit_an_out_of_office")
: oooType === "team"
? t("create_ooo_dialog_team_title")
: t("create_an_out_of_office")
}
subtitle={
oooType === "team"
? currentlyEditingOutOfOfficeEntry
? t("edit_ooo_dialog_team_subtitle")
: t("create_ooo_dialog_team_subtitle")
: undefined
}
/>
{/* In case of Team, Select Member for whom OOO is created */}
{oooType === OutOfOfficeTab.TEAM && (
<>
<div className="mb-4">
<Label className="text-emphasis mt-6">{t("select_team_member")}</Label>
<div className="mt-2">
<Input
type="text"
placeholder={t("search")}
onChange={(e) => setSearchMember(e.target.value)}
value={searchMember}
disabled={!!currentlyEditingOutOfOfficeEntry}
/>
<div
className={`scroll-bar bg-default mt-2 flex ${
currentlyEditingOutOfOfficeEntry ? "h-[45px]" : "h-[150px]"
} flex-col gap-0.5 overflow-y-scroll rounded-[10px] border p-1`}>
{oooMemberListOptions.map((member) => (
<label
key={member.value}
aria-disabled={!!currentlyEditingOutOfOfficeEntry}
data-testid={`ooofor_username_select_${member.value}`}
tabIndex={watchForUserId === member.value ? -1 : 0}
role="radio"
aria-checked={watchForUserId === member.value}
onKeyDown={(e) => {
if (e.key === "Enter" || e.key === " ") {
e.preventDefault();
setValue("forUserId", member.value, { shouldDirty: true });
}
}}
className={classNames(
"cursor-not-allowed items-center justify-between gap-0.5 rounded-sm py-2 outline-none",
watchForUserId === member.value && "bg-subtle",
!currentlyEditingOutOfOfficeEntry &&
"hover:bg-subtle focus:bg-subtle focus:ring-emphasis cursor-pointer focus:ring-2"
)}>
<div className="flex flex-1 items-center space-x-3">
<input
type="radio"
disabled={!!currentlyEditingOutOfOfficeEntry}
className="hidden"
checked={watchForUserId === member.value}
onChange={() => setValue("forUserId", member.value, { shouldDirty: true })}
/>
<span className="text-emphasis w-full px-2 text-sm">{member.label}</span>
</div>
</label>
))}
{!currentlyEditingOutOfOfficeEntry && (
<div className="text-default text-center" ref={observerRefMember}>
<Button
color="minimal"
loading={oooForMembers.isFetchingNextPage}
disabled={!oooForMembers.hasNextPage}
onClick={() => oooForMembers.fetchNextPage()}>
{oooForMembers.hasNextPage ? t("load_more_results") : t("no_more_results")}
</Button>
</div>
)}
</div>
</div>
</div>
</>
)}
<div>
<p className="text-emphasis mb-1 block text-sm font-medium capitalize">{t("dates")}</p>
<div>
<Controller
name="dateRange"
control={control}
render={({ field: { onChange, value } }) => (
<DateRangePicker
minDate={null}
dates={{ startDate: value.startDate, endDate: value.endDate }}
onDatesChange={(values) => {
onChange(values);
}}
strictlyBottom={true}
allowPastDates={true}
/>
)}
/>
</div>
{/* Holiday overlap warning */}
{overlappingHolidays.length > 0 && (
<Alert
className="mt-2"
severity="info"
title={t("holiday_overlap_info")}
message={
overlappingHolidays.length === 1
? t("holiday_overlap_message_single", {
holiday: overlappingHolidays[0].holiday.name,
date: dayjs(overlappingHolidays[0].date).format("D MMM"),
})
: t("holiday_overlap_message_multiple", {
count: overlappingHolidays.length,
holidays: overlappingHolidays
.slice(0, 3)
.map((h) => h.holiday.name)
.join(", "),
})
}
/>
)}
</div>
{/* Reason Select */}
<div className="mt-4 w-full">
<div className="">
<p className="text-emphasis block text-sm font-medium">{t("reason")}</p>
<Controller
control={control}
name="reasonId"
render={({ field: { onChange, value } }) => (
<Select<Option>
className="mb-0 mt-1 text-white"
name="reason"
data-testid="reason_select"
value={reasonList.find((reason) => reason.value === value)}
placeholder={t("ooo_select_reason")}
options={reasonList}
onChange={(selectedOption) => {
if (selectedOption?.value) {
onChange(selectedOption.value);
}
}}
/>
)}
/>
</div>
</div>
{/* Notes input */}
<div className="mt-4">
<p className="text-emphasis text-sm font-medium">{t("notes")}</p>
<TextArea
data-testid="notes_input"
className="border-subtle mt-2 h-10 w-full rounded-lg border px-2"
placeholder={t("additional_notes")}
{...register("notes")}
onChange={(e) => {
const newNotes = e?.target.value;
setValue("notes", newNotes);
if (!newNotes?.trim()) {
setValue("showNotePublicly", false);
}
}}
/>
<Controller
control={control}
name="showNotePublicly"
render={({ field: { value, onChange } }) => (
<div className="mt-2 flex items-center">
<Checkbox
id="show-note-publicly"
data-testid="show-note-publicly-checkbox"
checked={value ?? false}
onCheckedChange={onChange}
disabled={!hasValidNotes}
/>
<label
htmlFor="show-note-publicly"
className={classNames(
"ml-2 text-sm",
hasValidNotes ? "text-emphasis cursor-pointer" : "text-muted cursor-not-allowed"
)}>
{t("show_note_publicly_description")}
</label>
</div>
)}
/>
</div>
<div className="bg-cal-muted my-4 rounded-xl p-5">
<div className="flex flex-row">
<Switch
disabled={!hasTeamPlan}
data-testid="profile-redirect-switch"
checked={profileRedirect}
id="profile-redirect-switch"
onCheckedChange={(state) => {
setProfileRedirect(state);
if (!state) {
setValue("toTeamUserId", null);
}
}}
label={hasTeamPlan ? t("redirect_team_enabled") : t("redirect_team_disabled")}
/>
{!hasTeamPlan && (
<div className="mx-2" data-testid="upgrade-team-badge">
<UpgradeTeamsBadge />
</div>
)}
</div>
{profileRedirect && (
<div className="mb-2">
<Label className="text-emphasis mt-6">{t("select_team_member")}</Label>
<div className="mt-2">
<Input
type="text"
placeholder={t("search")}
onChange={(e) => setSearchRedirectMember(e.target.value)}
value={searchRedirectMember}
/>
<div className="scroll-bar bg-default mt-2 flex h-[150px] flex-col gap-0.5 overflow-y-scroll rounded-[10px] border p-1">
{redirectToMemberListOptions
.filter((member) => member.value !== getValues("forUserId"))
.map((member) => (
<label
key={member.value}
data-testid={`team_username_select_${member.value}`}
tabIndex={watchedTeamUserId === member.value ? -1 : 0}
role="radio"
aria-checked={watchedTeamUserId === member.value}
onKeyDown={(e) => {
if (e.key === "Enter" || e.key === " ") {
e.preventDefault();
setValue("toTeamUserId", member.value, { shouldDirty: true });
}
}}
className={classNames(
"hover:bg-subtle focus:bg-subtle focus:ring-emphasis cursor-pointer items-center justify-between gap-0.5 rounded-sm py-2 outline-none focus:ring-2",
watchedTeamUserId === member.value && "bg-subtle"
)}>
<div className="flex flex-1 items-center space-x-3">
<input
type="radio"
className="hidden"
checked={watchedTeamUserId === member.value}
onChange={() => setValue("toTeamUserId", member.value, { shouldDirty: true })}
/>
<span className="text-emphasis w-full px-2 text-sm">{member.label}</span>
</div>
</label>
))}
<div className="text-default text-center" ref={observerRefRedirect}>
<Button
color="minimal"
loading={redirectMembers.isFetchingNextPage}
disabled={!redirectMembers.hasNextPage}
onClick={() => redirectMembers.fetchNextPage()}>
{redirectMembers.hasNextPage ? t("load_more_results") : t("no_more_results")}
</Button>
</div>
</div>
</div>
</div>
)}
</div>
</div>
<DialogFooter showDivider noSticky>
<div className="flex">
<Button
color="minimal"
type="button"
onClick={() => {
closeModal();
}}
className="mr-1">
{t("cancel")}
</Button>
<Button
form="create-or-edit-ooo-form"
color="primary"
type="submit"
disabled={isSubmitting || isReasonListPending}
data-testid="create-or-edit-entry-ooo-redirect">
{currentlyEditingOutOfOfficeEntry ? t("save") : t("create")}
</Button>
</div>
</DialogFooter>
</form>
</DialogContent>
</Dialog>
);
};
@@ -1,424 +0,0 @@
"use client";
import { keepPreviousData } from "@tanstack/react-query";
import {
createColumnHelper,
getCoreRowModel,
getFilteredRowModel,
useReactTable,
} from "@tanstack/react-table";
import { usePathname } from "next/navigation";
import { useEffect, useMemo, useRef, useState } from "react";
import dayjs from "@calcom/dayjs";
import {
DataTableWrapper,
DataTableToolbar,
DataTableProvider,
ColumnFilterType,
useDataTable,
useFilterValue,
ZDateRangeFilterValue,
DataTableFilters,
DataTableSegment,
} from "@calcom/features/data-table";
import { useSegments } from "@calcom/features/data-table/hooks/useSegments";
import SettingsHeader from "@calcom/features/settings/appDir/SettingsHeader";
import ServerTrans from "@calcom/lib/components/ServerTrans";
import { getUserAvatarUrl } from "@calcom/lib/getAvatarUrl";
import { useCompatSearchParams } from "@calcom/lib/hooks/useCompatSearchParams";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { trpc } from "@calcom/trpc/react";
import { Avatar } from "@calcom/ui/components/avatar";
import { Button } from "@calcom/ui/components/button";
import { EmptyScreen } from "@calcom/ui/components/empty-screen";
import { Icon } from "@calcom/ui/components/icon";
import { SkeletonText } from "@calcom/ui/components/skeleton";
import { showToast } from "@calcom/ui/components/toast";
import { Tooltip } from "@calcom/ui/components/tooltip";
import CreateNewOutOfOfficeEntryButton from "./CreateNewOutOfOfficeEntryButton";
import type { BookingRedirectForm } from "./CreateOrEditOutOfOfficeModal";
import { OutOfOfficeTab, OutOfOfficeToggleGroup } from "./OutOfOfficeToggleGroup";
interface OutOfOfficeEntry {
id: number;
uuid: string;
start: Date;
end: Date;
toUserId: number | null;
toUser: {
username: string;
name: string;
} | null;
reason: {
id: number;
emoji: string;
reason: string;
userId: number;
} | null;
notes: string | null;
showNotePublicly: boolean | null;
user: { id: number; avatarUrl: string; username: string; email: string; name: string } | null;
canEditAndDelete: boolean;
}
export default function OutOfOfficeEntriesList({
onOpenCreateDialog,
onOpenEditDialog,
}: {
onOpenCreateDialog: () => void;
onOpenEditDialog: (entry: BookingRedirectForm) => void;
}) {
const { t } = useLocale();
const pathname = usePathname();
if (!pathname) return null;
return (
<SettingsHeader
title={t("out_of_office")}
description={t("out_of_office_description")}
CTA={
<div className="flex gap-2">
<OutOfOfficeToggleGroup />
<CreateNewOutOfOfficeEntryButton data-testid="add_entry_ooo" onClick={onOpenCreateDialog} />
</div>
}>
<DataTableProvider tableIdentifier={pathname} useSegments={useSegments}>
<OutOfOfficeEntriesListContent
onOpenCreateDialog={onOpenCreateDialog}
onOpenEditDialog={onOpenEditDialog}
/>
</DataTableProvider>
</SettingsHeader>
);
}
function OutOfOfficeEntriesListContent({
onOpenCreateDialog,
onOpenEditDialog,
}: {
onOpenCreateDialog: () => void;
onOpenEditDialog: (entry: BookingRedirectForm) => void;
}) {
const { t } = useLocale();
const tableContainerRef = useRef<HTMLDivElement>(null);
const [deletedEntry, setDeletedEntry] = useState(0);
const { searchTerm } = useDataTable();
const searchParams = useCompatSearchParams();
const selectedTab = searchParams?.get("type") ?? OutOfOfficeTab.MINE;
const endDateRange = useFilterValue("dateRange", ZDateRangeFilterValue)?.data;
const { data, isPending, fetchNextPage, isFetching, refetch, hasNextPage } =
trpc.viewer.ooo.outOfOfficeEntriesList.useInfiniteQuery(
{
limit: 10,
fetchTeamMembersEntries: selectedTab === OutOfOfficeTab.TEAM,
searchTerm,
endDateFilterStartRange: endDateRange?.startDate ?? undefined,
endDateFilterEndRange: endDateRange?.endDate ?? undefined,
},
{
getNextPageParam: (lastPage) => lastPage.nextCursor,
placeholderData: keepPreviousData,
}
);
useEffect(() => {
refetch();
}, [deletedEntry, selectedTab, refetch]);
const totalRowCount = data?.pages?.[0]?.meta?.totalRowCount ?? 0;
const flatData = useMemo(
() =>
isPending || isFetching ? new Array(5).fill(null) : data?.pages?.flatMap((page) => page.rows) ?? [],
[data, selectedTab, isPending, isFetching, searchTerm]
) as OutOfOfficeEntry[];
const memoColumns = useMemo(() => {
const columnHelper = createColumnHelper<OutOfOfficeEntry>();
return [
columnHelper.accessor((row) => row, {
id: "dateRange",
header: t("date_range"),
enableColumnFilter: true,
enableSorting: false,
cell: () => null,
filterFn: () => true,
meta: {
filter: {
type: ColumnFilterType.DATE_RANGE,
dateRangeOptions: {
range: "past",
},
},
},
}),
...(selectedTab === OutOfOfficeTab.TEAM
? [
columnHelper.display({
id: "member",
header: `Member`,
size: 300,
cell: ({ row }) => {
if (!row.original || !row.original.user || isPending || isFetching) {
return <SkeletonText className="h-8 w-full" />;
}
const { avatarUrl, username, email, name } = row.original.user;
const memberName =
name ||
(() => {
const emailName = email.split("@")[0];
return emailName.charAt(0).toUpperCase() + emailName.slice(1);
})();
return (
<div className="flex items-center gap-2">
<Avatar
size="sm"
alt={username || email}
imageSrc={getUserAvatarUrl({
avatarUrl,
})}
/>
<div className="">
<div
data-testid={`ooo-member-${username}-username`}
className="text-emphasis text-sm font-medium leading-none">
{memberName}
</div>
<div
data-testid={`ooo-member-${username}-email`}
className="text-subtle mt-1 text-sm leading-none">
{email}
</div>
</div>
</div>
);
},
}),
]
: []),
columnHelper.display({
id: "outOfOffice",
header: `${t("out_of_office")} (${totalRowCount})`,
size: selectedTab === OutOfOfficeTab.TEAM ? 370 : 660,
cell: ({ row }) => {
const item = row.original;
return (
<>
{row.original && !isPending && !isFetching ? (
<div
className="flex flex-row justify-between p-2"
data-testid={`table-redirect-${item.toUser?.username || "n-a"}`}>
<div className="flex flex-row items-center">
<div className="flex h-10 w-10 items-center justify-center rounded-full bg-gray-50">
{item?.reason?.emoji || "🏝️"}
</div>
<div className="ml-2 flex flex-col">
<p className="px-2 font-bold">
{dayjs.utc(item.start).format("ll")} - {dayjs.utc(item.end).format("ll")}
</p>
<p className="px-2">
{item.toUser?.username ? (
<ServerTrans
t={t}
i18nKey="ooo_forwarding_to"
values={{
username: item.toUser?.username,
}}
components={[<span key="ooo-username" className="text-subtle font-bold" />]}
/>
) : (
<>{t("ooo_not_forwarding")}</>
)}
</p>
{item.notes && (
<p className="px-2">
<span className="text-subtle">{t("notes")}: </span>
<span data-testid={`ooo-entry-note-${item.toUser?.username || "n-a"}`}>
{item.notes}
</span>
</p>
)}
</div>
</div>
</div>
) : (
<SkeletonText className="h-8 w-full" />
)}
</>
);
},
}),
columnHelper.display({
id: "actions",
size: 90,
cell: ({ row }) => {
const item = row.original;
return (
<>
{row.original && !isPending && !isFetching ? (
<div className="flex flex-row items-center justify-end gap-x-2" data-testid="ooo-actions">
<Tooltip content={t("edit")}>
<Button
className="self-center rounded-lg border"
type="button"
color="secondary"
variant="icon"
data-testid={`ooo-edit-${item.toUser?.username || "n-a"}`}
StartIcon="pencil"
onClick={() => {
const startDateOffset = -1 * item.start.getTimezoneOffset();
const endDateOffset = -1 * item.end.getTimezoneOffset();
const outOfOfficeEntryData: BookingRedirectForm = {
uuid: item.uuid,
dateRange: {
startDate: dayjs(item.start).subtract(startDateOffset, "minute").toDate(),
endDate: dayjs(item.end).subtract(endDateOffset, "minute").startOf("d").toDate(),
},
startDateOffset,
endDateOffset,
toTeamUserId: item.toUserId,
reasonId: item.reason?.id ?? 1,
notes: item.notes ?? undefined,
showNotePublicly: item.showNotePublicly ?? false,
forUserId: item.user?.id || null,
forUserName:
item.user?.name ||
(item.user?.email &&
(() => {
const emailName = item.user?.email.split("@")[0];
return emailName.charAt(0).toUpperCase() + emailName.slice(1);
})()),
forUserAvatar: item.user?.avatarUrl,
toUserName: item.toUser?.name || item.toUser?.username,
};
onOpenEditDialog(outOfOfficeEntryData);
}}
disabled={isPending || isFetching || !item.canEditAndDelete}
/>
</Tooltip>
<Tooltip content={t("delete")}>
<Button
className="self-center rounded-lg border"
type="button"
color="destructive"
variant="icon"
disabled={
deleteOutOfOfficeEntryMutation.isPending ||
isPending ||
isFetching ||
!item.canEditAndDelete
}
StartIcon="trash-2"
data-testid={`ooo-delete-${item.toUser?.username || "n-a"}`}
onClick={() => {
deleteOutOfOfficeEntryMutation.mutate({
outOfOfficeUid: item.uuid,
userId: selectedTab === OutOfOfficeTab.TEAM ? item.user?.id : undefined,
});
}}
/>
</Tooltip>
</div>
) : (
<SkeletonText className="h-8 w-full" />
)}
</>
);
},
}),
];
}, [selectedTab, isPending, isFetching, onOpenEditDialog, t]);
const table = useReactTable({
data: flatData,
columns: memoColumns,
initialState: {
columnVisibility: {
dateRange: false,
},
},
enableRowSelection: false,
manualPagination: true,
getCoreRowModel: getCoreRowModel(),
getFilteredRowModel: getFilteredRowModel(),
});
const deleteOutOfOfficeEntryMutation = trpc.viewer.ooo.outOfOfficeEntryDelete.useMutation({
onSuccess: () => {
showToast(t("success_deleted_entry_out_of_office"), "success");
setDeletedEntry((previousValue) => previousValue + 1);
},
onError: () => {
showToast(`An error occurred`, "error");
},
});
return (
<>
<DataTableWrapper
testId="ooo-list-data-table"
rowClassName={selectedTab === OutOfOfficeTab.MINE ? "hidden" : ""}
table={table}
isPending={isPending}
hasNextPage={hasNextPage}
fetchNextPage={fetchNextPage}
isFetching={isFetching}
totalRowCount={totalRowCount}
tableContainerRef={tableContainerRef}
paginationMode="infinite"
ToolbarLeft={
<>
<DataTableToolbar.SearchBar />
<DataTableFilters.FilterBar table={table} />
</>
}
ToolbarRight={
<>
<DataTableFilters.ClearFiltersButton />
<DataTableSegment.SaveButton />
<DataTableSegment.Select />
</>
}
EmptyView={
<EmptyScreen
className="mt-6"
headline={selectedTab === OutOfOfficeTab.TEAM ? t("ooo_team_empty_title") : t("ooo_empty_title")}
description={
selectedTab === OutOfOfficeTab.TEAM
? t("ooo_team_empty_description")
: t("ooo_empty_description")
}
buttonRaw={<CreateNewOutOfOfficeEntryButton size="sm" onClick={onOpenCreateDialog} />}
customIcon={
<div className="mt-4 h-[102px]">
<div className="flex h-full flex-col items-center justify-center p-2 md:mt-0 md:p-0">
<div className="relative">
<div className="dark:bg-darkgray-50 absolute -left-3 -top-3 -z-20 h-[70px] w-[70px] -rotate-24 rounded-3xl border-2 border-[#e5e7eb] p-8 opacity-40 dark:opacity-80">
<div className="w-12" />
</div>
<div className="dark:bg-darkgray-50 absolute -top-3 left-3 -z-10 h-[70px] w-[70px] rotate-24 rounded-3xl border-2 border-[#e5e7eb] p-8 opacity-60 dark:opacity-90">
<div className="w-12" />
</div>
<div className="dark:bg-darkgray-50 text-inverted relative z-0 flex h-[70px] w-[70px] items-center justify-center rounded-3xl border-2 border-[#e5e7eb] bg-white">
<Icon name="clock" size={28} className="text-black" />
<div className="dark:bg-darkgray-50 absolute right-4 top-5 h-[12px] w-[12px] rotate-56 bg-white text-lg font-bold" />
<span className="absolute right-4 top-3 font-sans text-sm font-extrabold text-black">
z
</span>
</div>
</div>
</div>
</div>
}
/>
}
/>
</>
);
}
@@ -1,77 +0,0 @@
"use client";
import { usePathname, useRouter } from "next/navigation";
import { useCallback, useMemo } from "react";
import { useCompatSearchParams } from "@calcom/embed-core/src/useCompatSearchParams";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { Select, ToggleGroup } from "@calcom/ui/components/form";
export enum OutOfOfficeTab {
MINE = "mine",
TEAM = "team",
HOLIDAYS = "holidays",
}
export const OutOfOfficeToggleGroup = () => {
const { t } = useLocale();
const searchParams = useCompatSearchParams();
const router = useRouter();
const pathname = usePathname();
const createQueryString = useCallback(
(name: string, value: string) => {
const params = new URLSearchParams(searchParams ?? undefined);
params.set(name, value);
return params.toString();
},
[searchParams]
);
const selectedTab = searchParams?.get("type") ?? OutOfOfficeTab.MINE;
const tabOptions = useMemo(
() => [
{ value: OutOfOfficeTab.MINE, label: t("my_ooo") },
{ value: OutOfOfficeTab.TEAM, label: t("team_ooo") },
{ value: OutOfOfficeTab.HOLIDAYS, label: t("holidays") },
],
[t]
);
const handleTabChange = useCallback(
(value: string | null) => {
if (!value) return;
const newQuery = createQueryString("type", value);
router.push(`${pathname}?${newQuery}`);
},
[createQueryString, pathname, router]
);
const selectedOption = useMemo(
() => tabOptions.find((opt) => opt.value === selectedTab) ?? tabOptions[0],
[selectedTab, tabOptions]
);
return (
<>
{/* Mobile: Select dropdown */}
<div className="md:hidden">
<Select
className="w-[120px]"
value={selectedOption}
onChange={(option) => handleTabChange(option?.value ?? null)}
options={tabOptions}
/>
</div>
{/* Desktop: Toggle group */}
<ToggleGroup
className="hidden md:flex"
defaultValue={selectedTab}
onValueChange={handleTabChange}
options={tabOptions}
/>
</>
);
};