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:
Benny JooandDevin AI authored and GitHub committed 2026-04-15 09:52:36 -03:00
1 parent a17f28e9ab
commit ab21c7f805
4080 files changed
+14403 -404922

No files matched your search

@@ -1,7 +0,0 @@
"use client";
import LicenseView from "./license-view";
export default function AdminBillingView() {
return <LicenseView />;
}
@@ -1,84 +0,0 @@
"use client";
import { signIn } from "next-auth/react";
import { useSearchParams } from "next/navigation";
import { useRef, useEffect, useState } from "react";
import { WEBAPP_URL } from "@calcom/lib/constants";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { addRecentImpersonation } from "@calcom/lib/recentImpersonations";
import { Button } from "@calcom/ui/components/button";
import { PanelCard } from "@calcom/ui/components/card";
import { TextField } from "@calcom/ui/components/form";
import RecentImpersonationsList from "../../../components/settings/admin/RecentImpersonationsList";
const ImpersonationView = () => {
const { t } = useLocale();
const usernameRef = useRef<HTMLInputElement>(null);
const searchParams = useSearchParams();
const [refreshKey, setRefreshKey] = useState(0);
const username = searchParams?.get("username")?.toLowerCase();
useEffect(() => {
if (username) {
const enteredUsername = username.toLowerCase();
addRecentImpersonation(enteredUsername);
signIn("impersonation-auth", {
username: enteredUsername,
callbackUrl: `${WEBAPP_URL}/event-types`,
});
}
}, [username]);
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault();
const enteredUsername = usernameRef.current?.value.toLowerCase();
if (enteredUsername) {
addRecentImpersonation(enteredUsername);
setRefreshKey((prev) => prev + 1);
signIn("impersonation-auth", {
username: enteredUsername,
callbackUrl: `${WEBAPP_URL}/event-types`,
});
}
};
const handleQuickImpersonate = (username: string) => {
if (usernameRef.current) {
usernameRef.current.value = username;
}
addRecentImpersonation(username);
setRefreshKey((prev) => prev + 1);
signIn("impersonation-auth", {
username: username.toLowerCase(),
callbackUrl: `${WEBAPP_URL}/event-types`,
});
};
return (
<div className="flex flex-col gap-4">
<PanelCard title={t("user_impersonation_heading")} subtitle={t("impersonate_user_tip")}>
<form className="p-4" onSubmit={handleSubmit}>
<div className="flex items-center space-x-2 rtl:space-x-reverse">
<TextField
containerClassName="w-full"
name=""
addOnLeading={<>{process.env.NEXT_PUBLIC_WEBSITE_URL}/</>}
ref={usernameRef}
defaultValue={undefined}
data-testid="admin-impersonation-input"
/>
<Button type="submit" data-testid="impersonation-submit">
{t("impersonate")}
</Button>
</div>
</form>
</PanelCard>
<RecentImpersonationsList key={refreshKey} onImpersonate={handleQuickImpersonate} />
</div>
);
};
export default ImpersonationView;
@@ -1,85 +0,0 @@
"use client";
import { useState } from "react";
import { IS_CALCOM } from "@calcom/lib/constants";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { trpc } from "@calcom/trpc/react";
import { Button } from "@calcom/ui/components/button";
import { PanelCard } from "@calcom/ui/components/card";
import { TextField } from "@calcom/ui/components/form";
import { showToast } from "@calcom/ui/components/toast";
export default function LicenseView() {
const { t } = useLocale();
const [billingEmail, setBillingEmail] = useState("");
const resendEmailMutation = trpc.viewer.admin.resendPurchaseCompleteEmail.useMutation({
onSuccess: () => {
showToast(t("admin_license_resend_success"), "success");
},
onError: (error) => {
showToast(error.message || t("admin_license_resend_error"), "error");
},
});
const billingPortalMutation = trpc.viewer.admin.billingPortalLink.useMutation({
onSuccess: (data) => {
if (!data?.url) {
showToast(t("admin_license_portal_missing_url"), "error");
return;
}
window.open(data.url, "_blank", "noopener,noreferrer");
},
onError: (error) => {
showToast(error.message || t("admin_license_portal_error"), "error");
},
});
const showResendSection = IS_CALCOM;
return (
<div className="flex flex-col gap-4">
{showResendSection && (
<PanelCard title={t("admin_license_resend_title")} subtitle={t("admin_license_resend_description")}>
<div className="p-4">
<div className="flex flex-col gap-3 sm:flex-row sm:items-end">
<TextField
containerClassName="w-full"
label={t("admin_license_billing_email_label")}
name="billingEmail"
type="email"
placeholder={t("admin_license_billing_email_placeholder")}
value={billingEmail}
onChange={(event) => setBillingEmail(event.target.value)}
/>
<Button
type="button"
loading={resendEmailMutation.isPending}
disabled={!billingEmail.trim()}
onClick={() => {
resendEmailMutation.mutate({
billingEmail: billingEmail.trim(),
});
}}>
{t("admin_license_resend_button")}
</Button>
</div>
</div>
</PanelCard>
)}
<PanelCard title={t("admin_license_portal_title")} subtitle={t("admin_license_portal_description")}>
<div className="p-4">
<Button
type="button"
loading={billingPortalMutation.isPending}
onClick={() => billingPortalMutation.mutate({})}>
{t("admin_license_portal_button")}
</Button>
</div>
</PanelCard>
</div>
);
}
@@ -1,119 +0,0 @@
"use client";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { trpc } from "@calcom/trpc/react";
import { Alert } from "@calcom/ui/components/alert";
import { Button } from "@calcom/ui/components/button";
import { Form, TextField } from "@calcom/ui/components/form";
import { showToast } from "@calcom/ui/components/toast";
import { zodResolver } from "@hookform/resolvers/zod";
import type { TFunction } from "next-i18next";
import { useForm } from "react-hook-form";
import { z } from "zod";
export const getFormSchema = (t: TFunction) => {
return z.object({
teamId: z.number(),
targetOrgId: z.number(),
teamSlugInOrganization: z.string().min(1),
});
};
export default function MoveTeamToOrgView() {
const { t } = useLocale();
const formSchema = getFormSchema(t);
const formMethods = useForm({
mode: "onSubmit",
resolver: zodResolver(formSchema),
});
const moveTeamMutation = trpc.viewer.admin.moveTeamToOrg.useMutation({
onSuccess: (data) => {
showToast(t(data.message), "success", 10000);
},
onError: (error) => {
showToast(t(error.message), "error", 10000);
},
});
const { register } = formMethods;
return (
<div className="space-y-3">
<Form
className="space-y-3"
noValidate={true}
form={formMethods}
handleSubmit={async (values) => {
const parsedValues = formSchema.parse(values);
moveTeamMutation.mutate(parsedValues);
}}>
<div className="space-y-3">
<TextField
{...register("teamId", { valueAsNumber: true })}
type="number"
label={t("team_id")}
required
placeholder={t("move_team_to_org_team_id_placeholder")}
/>
<TextField
{...register("teamSlugInOrganization")}
label={t("move_team_to_org_new_slug")}
required
placeholder={t("move_team_to_org_new_slug_placeholder")}
/>
<TextField
{...register("targetOrgId", { valueAsNumber: true })}
type="number"
label={t("move_team_to_org_target_org_id")}
required
placeholder={t("move_team_to_org_target_org_id_placeholder")}
/>
<div className="mt-2 text-gray-600 text-sm">
{t("organization_migration_move_team_footnote")}
</div>
</div>
<Button type="submit" loading={moveTeamMutation.isPending}>
{t("organization_migration_move_team")}
</Button>
</Form>
{moveTeamMutation.isSuccess && moveTeamMutation.data && (
<Alert
className="mt-6"
severity="info"
CustomIcon="check"
title={t("move_team_to_org_migration_successful")}
message={
<div className="space-y-1">
<p>
<span className="font-medium">{t("team_id")}:</span> {moveTeamMutation.data.teamId}
</p>
{moveTeamMutation.data.oldTeamSlug && (
<p>
<span className="font-medium">{t("move_team_to_org_old_slug")}:</span>{" "}
{moveTeamMutation.data.oldTeamSlug}
</p>
)}
{moveTeamMutation.data.newTeamSlug && (
<p>
<span className="font-medium">{t("move_team_to_org_new_slug")}:</span>{" "}
{moveTeamMutation.data.newTeamSlug}
</p>
)}
<p>
<span className="font-medium">{t("organization_id")}:</span>{" "}
{moveTeamMutation.data.organizationId}
</p>
{moveTeamMutation.data.organizationSlug && (
<p>
<span className="font-medium">{t("move_team_to_org_organization_slug")}:</span>{" "}
{moveTeamMutation.data.organizationSlug}
</p>
)}
</div>
}
/>
)}
</div>
);
}
@@ -1,171 +0,0 @@
"use client";
import { WEBAPP_URL } from "@calcom/lib/constants";
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 { Dialog, DialogContent, DialogFooter, DialogHeader } from "@calcom/ui/components/dialog";
import { showToast } from "@calcom/ui/components/toast";
import { usePathname } from "next/navigation";
import { useSession } from "next-auth/react";
import { useMemo, useState } from "react";
import { ActiveUserBreakdown } from "~/settings/billing/components/ActiveUserBreakdown";
import BillingCredits from "~/settings/billing/components/BillingCredits";
import { InvoicesTable } from "~/settings/billing/components/InvoicesTable";
interface CtaRowProps {
title: string;
description: string;
children: React.ReactNode;
className?: string;
}
declare global {
interface Window {
Support?: {
open: () => void;
shouldShowTriggerButton: (showTrigger: boolean) => void;
};
}
}
export const CtaRow = ({ title, description, className, children }: CtaRowProps) => {
return (
<>
<section className={classNames("text-default flex flex-col sm:flex-row", className)}>
<div>
<h2 className="text-base font-semibold">{title}</h2>
<p>{description}</p>
</div>
<div className="shrink-0 pt-3 sm:ml-auto sm:pl-3 sm:pt-0">{children}</div>
</section>
</>
);
};
const BillingView = () => {
const pathname = usePathname();
const session = useSession();
const { t } = useLocale();
const returnTo = pathname;
const [showSkipTrialDialog, setShowSkipTrialDialog] = useState(false);
const utils = trpc.useUtils();
const teamIdNumber = useMemo(() => {
if (!pathname) return null;
if (pathname.includes("/teams/") && pathname.includes("/billing")) {
const teamIdMatch = pathname.match(/\/teams\/(\d+)\/billing/);
return teamIdMatch ? parseInt(teamIdMatch[1], 10) : null;
}
if (pathname.includes("/organizations/billing")) {
const orgId = session.data?.user?.org?.id;
return typeof orgId === "number" ? orgId : null;
}
return null;
}, [pathname, session.data?.user?.org?.id]);
const { data: subscriptionStatus, isLoading: isLoadingStatus } =
trpc.viewer.teams.getSubscriptionStatus.useQuery(
{ teamId: teamIdNumber ?? 0 },
{ enabled: !!teamIdNumber }
);
const skipTrialMutation = trpc.viewer.teams.skipTrialForTeam.useMutation({
onSuccess: () => {
showToast(t("trial_skipped_successfully"), "success");
setShowSkipTrialDialog(false);
// Invalidate the subscription status cache to hide the skip trial button
if (teamIdNumber) {
utils.viewer.teams.getSubscriptionStatus.invalidate({ teamId: teamIdNumber });
}
},
onError: (error) => {
showToast(error.message || t("error_skipping_trial"), "error");
},
});
const billingHref = teamIdNumber
? `/api/integrations/stripepayment/portal?teamId=${teamIdNumber}&returnTo=${WEBAPP_URL}${returnTo}`
: `/api/integrations/stripepayment/portal?returnTo=${WEBAPP_URL}${returnTo}`;
const onContactSupportClick = async () => {
if (window.Support) {
window.Support.open();
}
};
const handleSkipTrial = () => {
if (teamIdNumber) {
skipTrialMutation.mutate({ teamId: teamIdNumber });
}
};
const isTrialing = subscriptionStatus?.isTrialing && teamIdNumber;
return (
<>
<div className="border-subtle rounded-b-lg border border-t-0 px-4 py-8 sm:px-6">
<div className="bg-cal-muted border-muted rounded-xl border p-1">
<div className="bg-default border-muted flex rounded-[10px] border px-5 py-4">
<div className="flex w-full flex-col gap-1">
<h3 className="text-emphasis text-sm font-semibold leading-none">{t("manage_billing")}</h3>
<p className="text-subtle text-sm font-medium leading-tight">
{t("view_and_manage_billing_details")}
</p>
</div>
<Button color="primary" href={billingHref} target="_blank" size="sm" EndIcon="external-link">
{t("billing_portal")}
</Button>
</div>
{isTrialing && (
<div className="bg-default border-muted mt-1 flex rounded-[10px] border px-5 py-4">
<div className="flex w-full flex-col gap-1">
<h3 className="text-emphasis text-sm font-semibold leading-none">{t("skip_trial")}</h3>
<p className="text-subtle text-sm font-medium leading-tight">{t("skip_trial_description")}</p>
</div>
<Button
color="secondary"
size="sm"
onClick={() => setShowSkipTrialDialog(true)}
loading={isLoadingStatus}>
{t("skip_trial")}
</Button>
</div>
)}
<div className="flex items-center justify-between px-4 py-5">
<p className="text-subtle text-sm font-medium leading-tight">{t("need_help")}</p>
<Button color="secondary" size="sm" onClick={onContactSupportClick}>
{t("contact_support")}
</Button>
</div>
</div>
<BillingCredits />
{teamIdNumber && subscriptionStatus?.billingMode === "ACTIVE_USERS" && (
<ActiveUserBreakdown teamId={teamIdNumber} />
)}
<InvoicesTable />
</div>
<Dialog open={showSkipTrialDialog} onOpenChange={setShowSkipTrialDialog}>
<DialogContent>
<DialogHeader title={t("skip_trial_confirmation_title")} />
<p className="text-subtle text-sm">{t("skip_trial_confirmation_description")}</p>
<DialogFooter>
<Button color="minimal" onClick={() => setShowSkipTrialDialog(false)}>
{t("cancel")}
</Button>
<Button color="primary" onClick={handleSkipTrial} loading={skipTrialMutation.isPending}>
{t("skip_trial")}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</>
);
};
export default BillingView;
@@ -1,256 +0,0 @@
"use client";
import { useEffect, useState } from "react";
import dayjs from "@calcom/dayjs";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { trpc } from "@calcom/trpc/react";
import { Badge } from "@coss/ui/components/badge";
import { Button } from "@calcom/ui/components/button";
import { PanelCard } from "@calcom/ui/components/card";
import {
Sheet,
SheetContent,
SheetDescription,
SheetFooter,
SheetHeader,
SheetPanel,
SheetTitle,
SheetClose,
} from "@coss/ui/components/sheet";
import { Skeleton } from "@coss/ui/components/skeleton";
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "@coss/ui/components/table";
import { ActiveUserBreakdownSkeleton } from "./ActiveUserBreakdownSkeleton";
const PAGE_SIZE = 10;
export function ActiveUserBreakdown({ teamId }: { teamId: number }) {
const { data, isLoading } = trpc.viewer.teams.getActiveUserBreakdown.useQuery(
{ teamId },
{ enabled: !!teamId }
);
if (isLoading) return <ActiveUserBreakdownSkeleton />;
if (!data) return null;
return <ActiveUserBreakdownContent data={data} teamId={teamId} />;
}
type BreakdownData = {
activeUsers: Array<{ id: number; email: string; name: string | null; activeAs: "host" | "attendee" }>;
totalMembers: number;
activeHosts: number;
activeAttendees: number;
periodStart: string;
periodEnd: string;
pricePerSeat: number | null;
};
type SelectedUser = {
id: number;
email: string;
name: string | null;
activeAs: "host" | "attendee";
};
function ActiveUserBreakdownContent({ data, teamId }: { data: BreakdownData; teamId: number }) {
const { t } = useLocale();
const [currentPage, setCurrentPage] = useState(0);
const [selectedUser, setSelectedUser] = useState<SelectedUser | null>(null);
const { activeUsers, totalMembers, activeHosts, activeAttendees, periodStart, periodEnd } = data;
useEffect(() => {
setCurrentPage(0);
}, [activeUsers]);
const totalPages = Math.ceil(activeUsers.length / PAGE_SIZE);
const paginatedUsers = activeUsers.slice(currentPage * PAGE_SIZE, (currentPage + 1) * PAGE_SIZE);
const formattedStart = dayjs.utc(periodStart).format("MMM D, YYYY");
const formattedEnd = dayjs.utc(periodEnd).format("MMM D, YYYY");
return (
<>
<PanelCard
title={t("active_users_billing")}
subtitle={t("active_users_billing_description", {
start: formattedStart,
end: formattedEnd,
})}
className="mt-5">
<div className="px-5 py-3">
<p className="text-subtle text-sm font-medium">
{t("active_users_summary", {
hosts: activeHosts,
attendees: activeAttendees,
active: activeHosts + activeAttendees,
total: totalMembers,
})}
</p>
</div>
{activeUsers.length === 0 ? (
<div className="text-subtle p-6 text-center text-sm">{t("no_active_users")}</div>
) : (
<>
<div className="overflow-x-auto">
<Table>
<TableHeader>
<TableRow>
<TableHead>{t("name")}</TableHead>
<TableHead>{t("email")}</TableHead>
<TableHead>{t("status")}</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{paginatedUsers.map((user) => (
<TableRow
key={user.id}
className="cursor-pointer"
onClick={() => setSelectedUser(user)}>
<TableCell>{user.name || "-"}</TableCell>
<TableCell>{user.email}</TableCell>
<TableCell>
{user.activeAs === "host" ? (
<Badge variant="success">{t("active_as_host")}</Badge>
) : (
<Badge variant="info">{t("active_as_attendee")}</Badge>
)}
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</div>
{totalPages > 1 && (
<div className="border-muted flex items-center justify-end gap-2 border-t px-4 py-3">
<Button
color="secondary"
size="sm"
onClick={() => setCurrentPage(currentPage - 1)}
disabled={currentPage === 0}
StartIcon="arrow-left">
{t("previous")}
</Button>
<Button
color="secondary"
size="sm"
onClick={() => setCurrentPage(currentPage + 1)}
disabled={currentPage >= totalPages - 1}
EndIcon="arrow-right">
{t("next")}
</Button>
</div>
)}
</>
)}
</PanelCard>
<Sheet open={!!selectedUser} onOpenChange={(open) => !open && setSelectedUser(null)}>
<SheetContent side="right" variant="inset">
<SheetHeader>
<SheetTitle>{selectedUser?.name || selectedUser?.email}</SheetTitle>
<SheetDescription>
<span className="flex items-center gap-2">
{selectedUser?.email}
{selectedUser?.activeAs === "host" ? (
<Badge variant="success">{t("active_as_host")}</Badge>
) : (
<Badge variant="info">{t("active_as_attendee")}</Badge>
)}
</span>
</SheetDescription>
</SheetHeader>
<SheetPanel>
{selectedUser && (
<UserBookingsSheet
teamId={teamId}
userId={selectedUser.id}
activeAs={selectedUser.activeAs}
/>
)}
</SheetPanel>
<SheetFooter>
<SheetClose render={<Button color="secondary">{t("close")}</Button>} />
</SheetFooter>
</SheetContent>
</Sheet>
</>
);
}
function UserBookingsSheet({
teamId,
userId,
activeAs,
}: {
teamId: number;
userId: number;
activeAs: "host" | "attendee";
}) {
const { t } = useLocale();
const { data, isLoading } = trpc.viewer.teams.getActiveUserBookings.useQuery(
{ teamId, userId, activeAs },
{ enabled: true }
);
if (isLoading) {
return (
<div className="flex flex-col gap-3">
<Skeleton className="h-8 w-24" />
<Skeleton className="h-10 w-full" />
<Skeleton className="h-10 w-full" />
<Skeleton className="h-10 w-full" />
</div>
);
}
const bookings = data?.bookings ?? [];
return (
<div className="flex flex-col gap-4">
<div className="flex items-baseline gap-2">
<span className="text-2xl font-bold">{bookings.length}</span>
<span className="text-muted-foreground text-sm">
{bookings.length === 1 ? t("booking") : t("bookings")}
</span>
</div>
{bookings.length === 0 ? (
<p className="text-muted-foreground text-sm">{t("no_bookings")}</p>
) : (
<Table>
<TableHeader>
<TableRow>
<TableHead>{t("booking")}</TableHead>
<TableHead>{t("date")}</TableHead>
<TableHead>{activeAs === "host" ? t("attendees") : t("host")}</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{bookings.map((booking) => (
<TableRow key={booking.id}>
<TableCell className="font-medium">{booking.title}</TableCell>
<TableCell className="text-muted-foreground">
{dayjs.utc(booking.startTime).format("MMM D, YYYY h:mm A")}
</TableCell>
<TableCell className="text-muted-foreground">{booking.otherParty || "-"}</TableCell>
</TableRow>
))}
</TableBody>
</Table>
)}
</div>
);
}
@@ -1,29 +0,0 @@
"use client";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { PanelCard } from "@calcom/ui/components/card";
import { SkeletonText } from "@calcom/ui/components/skeleton";
export function ActiveUserBreakdownSkeleton() {
const { t } = useLocale();
return (
<PanelCard title={t("active_users_billing")} className="mt-5">
<div className="p-4">
<SkeletonText className="mb-4 h-4 w-64" />
<div className="mb-3 flex gap-4 border-b pb-3">
<SkeletonText className="h-4 w-32" />
<SkeletonText className="h-4 w-40" />
<SkeletonText className="h-4 w-20" />
</div>
{Array.from({ length: 5 }).map((_, i) => (
<div key={i} className="flex gap-4 py-3">
<SkeletonText className="h-4 w-32" />
<SkeletonText className="h-4 w-40" />
<SkeletonText className="h-4 w-20" />
</div>
))}
</div>
</PanelCard>
);
}
@@ -1,336 +0,0 @@
"use client";
import { useSession } from "next-auth/react";
import { useRouter, usePathname } from "next/navigation";
import { useState, useMemo } from "react";
import { useForm } from "react-hook-form";
import dayjs from "@calcom/dayjs";
import { useOrgBranding } from "@calcom/features/ee/organizations/context/provider";
import { IS_SMS_CREDITS_ENABLED } from "@calcom/lib/constants";
import { downloadAsCsv } from "@calcom/lib/csvUtils";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { useParamsWithFallback } from "@calcom/lib/hooks/useParamsWithFallback";
import { trpc } from "@calcom/trpc/react";
import classNames from "@calcom/ui/classNames";
import { Button } from "@calcom/ui/components/button";
import { Select } from "@calcom/ui/components/form";
import { TextField, Label, InputError } from "@calcom/ui/components/form";
import { ProgressBar } from "@calcom/ui/components/progress-bar";
import { InfoIcon } from "@coss/ui/icons";
import { showToast } from "@calcom/ui/components/toast";
import { Tooltip } from "@calcom/ui/components/tooltip";
import { MemberInvitationModalWithoutMembers } from "~/ee/teams/components/MemberInvitationModal";
import { LearnMoreLink } from "@calcom/features/eventtypes/components/LearnMoreLink";
import { BillingCreditsSkeleton } from "./BillingCreditsSkeleton";
type MonthOption = {
value: string;
label: string;
startDate: string;
endDate: string;
};
type CreditRowProps = {
label: string;
value: number;
isBold?: boolean;
underline?: "dashed" | "solid";
className?: string;
};
const CreditRow = ({ label, value, isBold = false, underline, className = "" }: CreditRowProps) => {
const numberFormatter = new Intl.NumberFormat();
return (
<div
className={classNames(
`my-1 flex justify-between`,
underline === "dashed"
? "border-subtle border-b border-dashed"
: underline === "solid"
? "border-subtle border-b border-solid"
: "mt-1",
className
)}>
<span
className={classNames("text-sm", isBold ? "font-semibold" : "font-medium leading-tight text-subtle")}>
{label}
</span>
<span
className={classNames(`text-sm`, isBold ? "font-semibold" : "font-medium leading-tight text-subtle")}>
{numberFormatter.format(value)}
</span>
</div>
);
};
const getMonthOptions = (): MonthOption[] => {
const options: MonthOption[] = [];
const minDate = dayjs.utc("2025-05-01");
let date = dayjs.utc();
let count = 0;
while ((date.isAfter(minDate) || date.isSame(minDate, "month")) && count < 12) {
const startDate = date.startOf("month");
const endDate = date.endOf("month");
options.push({
value: date.format("MMMM YYYY"),
label: date.format("MMMM YYYY"),
startDate: startDate.toISOString(),
endDate: endDate.toISOString(),
});
date = date.subtract(1, "month");
count++;
}
return options;
};
export default function BillingCredits() {
const { t } = useLocale();
const router = useRouter();
const pathname = usePathname();
const session = useSession();
const orgBranding = useOrgBranding();
const monthOptions = useMemo(() => getMonthOptions(), []);
const [selectedMonth, setSelectedMonth] = useState<MonthOption>(monthOptions[0]);
const [isDownloading, setIsDownloading] = useState(false);
const [showMemberInvitationModal, setShowMemberInvitationModal] = useState(false);
const utils = trpc.useUtils();
const {
register,
handleSubmit,
setValue,
formState: { errors },
} = useForm<{ quantity: number }>({ defaultValues: { quantity: 50 } });
const params = useParamsWithFallback();
const orgId = session.data?.user?.org?.id;
const orgSlug = session.data?.user?.org?.slug;
const parsedTeamId = Number(params.id);
const teamId: number | undefined = Number.isFinite(parsedTeamId)
? parsedTeamId
: typeof orgId === "number"
? orgId
: undefined;
const tokens = (pathname ?? "").split("/").filter(Boolean);
const settingsIndex = tokens.indexOf("settings");
const isOrgScopedPath =
settingsIndex >= 0 && ["organizations", "teams"].includes(tokens[settingsIndex + 1]);
const shouldRender = IS_SMS_CREDITS_ENABLED && !(orgId && !isOrgScopedPath && !orgBranding?.slug);
const { data: creditsData, isLoading } = trpc.viewer.credits.getAllCredits.useQuery(
{ teamId },
{ enabled: shouldRender }
);
const { data: teamPlanData } = trpc.viewer.teams.hasTeamPlan.useQuery(undefined, {
enabled: shouldRender && !teamId,
});
const isUserInTeam = teamPlanData?.hasTeamPlan ?? false;
if (!shouldRender) return null;
const buyCreditsMutation = trpc.viewer.credits.buyCredits.useMutation({
onSuccess: (data) => {
if (data.sessionUrl) {
router.push(data.sessionUrl);
}
},
onError: () => {
showToast(t("credit_purchase_failed"), "error");
},
});
const handleDownload = async () => {
setIsDownloading(true);
try {
const result = await utils.viewer.credits.downloadExpenseLog.fetch({
teamId,
startDate: selectedMonth.startDate,
endDate: selectedMonth.endDate,
});
if (result?.csvData) {
const filename = `credit-expense-log-${selectedMonth.value.toLowerCase().replace(" ", "-")}.csv`;
downloadAsCsv(result.csvData, filename);
} else {
showToast(t("error_downloading_expense_log"), "error");
}
} catch (error) {
showToast(t("error_downloading_expense_log"), "error");
} finally {
setIsDownloading(false);
}
};
if (isLoading && teamId) return <BillingCreditsSkeleton />;
if (!creditsData) return null;
// For personal billing page: hide credits section if user is part of a team and has no personal credits
if (!teamId && isUserInTeam && creditsData.credits.additionalCredits <= 0) {
return null;
}
const onSubmit = (data: { quantity: number }) => {
buyCreditsMutation.mutate({ quantity: data.quantity, teamId });
};
const totalCredits = creditsData.credits.totalMonthlyCredits ?? 0;
const totalUsed = creditsData.credits.totalCreditsUsedThisMonth ?? 0;
const teamCreditsPercentageUsed = totalCredits > 0 ? (totalUsed / totalCredits) * 100 : 0;
const numberFormatter = new Intl.NumberFormat();
return (
<>
<div className="p-1 mt-5 rounded-xl border bg-cal-muted border-muted">
<div className="flex flex-col gap-1 px-4 py-5">
<h2 className="text-base font-semibold leading-none text-default">{t("credits")}</h2>
<p className="text-sm font-medium leading-tight text-subtle">{t("view_and_manage_credits")}</p>
</div>
<div className="bg-default border-muted flex w-full rounded-[10px] border px-5 py-4">
<div className="w-full">
{totalCredits > 0 ? (
<>
<div className="mb-4">
<CreditRow
label={t("monthly_credits")}
value={totalCredits}
isBold={true}
underline="dashed"
/>
<CreditRow label={t("credits_used")} value={totalUsed} underline="solid" />
<CreditRow
label={t("total_credits_remaining")}
value={creditsData.credits.totalRemainingMonthlyCredits}
/>
<div className="mt-4">
<ProgressBar color="green" percentageValue={100 - teamCreditsPercentageUsed} />
</div>
{/*750 credits per tip*/}
<div className="flex flex-1 justify-between items-center mt-4">
<p className="text-sm font-medium leading-tight text-subtle">
{orgSlug ? t("credits_per_tip_org") : t("credits_per_tip_teams")}
</p>
<Button onClick={() => setShowMemberInvitationModal(true)} size="sm" color="secondary">
{t("add_members_no_ellipsis")}
</Button>
</div>
</div>
<div className="-mx-5 mt-5">
<hr className="border-subtle" />
</div>
</>
) : (
<></>
)}
{/*Auto Top-Up goes here when we have it*/}
{/*<div className="-mx-5 mt-5">
<hr className="border-subtle" />
</div>*/}
{/*Additional Credits*/}
<div className="flex mt-4">
<div className="mr-auto -mb-1 w-full">
<div className="flex justify-between">
<Label>{t("additional_credits")}</Label>
<div className="flex gap-1 items-center mb-2">
<p className="text-sm font-semibold leading-none">
<span className="font-medium text-subtle">{t("current_balance")}</span>{" "}
{numberFormatter.format(creditsData.credits.additionalCredits)}
</p>
<Tooltip content={t("view_additional_credits_expense_tip")}>
<InfoIcon className="text-emphasis h-3 w-3" />
</Tooltip>
</div>
</div>
{/* Users who are part of a team cannot buy personal credits */}
{teamId || !isUserInTeam ? (
<form onSubmit={handleSubmit(onSubmit)} className="flex gap-2 items-center w-full">
<TextField
required
type="number"
{...register("quantity", {
required: t("error_required_field"),
min: {
value: 50,
message: t("minimum_of_credits_required"),
},
valueAsNumber: true,
})}
label=""
containerClassName="w-full -mt-1"
size="sm"
onChange={(e) => setValue("quantity", Number(e.target.value))}
min={50}
addOnSuffix={<>{t("credits")}</>}
/>
<Button
color="secondary"
target="_blank"
size="sm"
type="submit"
data-testid="buy-credits">
{t("buy")}
</Button>
</form>
) : null}
{errors.quantity && <InputError message={errors.quantity.message ?? t("invalid_input")} />}
</div>
</div>
<div className="-mx-5 mt-5">
<hr className="border-subtle" />
</div>
{/*Download Expense Log*/}
<div className="flex mt-4">
<div className="mr-auto w-full">
<Label className="mb-4">{t("download_expense_log")}</Label>
<div className="mt-1 mr-2">
<Select
size="sm"
className="w-full"
innerClassNames={{
control: "font-medium text-emphasis",
}}
options={monthOptions}
value={selectedMonth}
onChange={(option) => option && setSelectedMonth(option)}
/>
</div>
</div>
<div className="mt-auto">
<Button onClick={handleDownload} loading={isDownloading} color="secondary" size="sm">
{t("download")}
</Button>
</div>
</div>
</div>
</div>
{/*Credit Worth Section*/}
<div className="px-5 py-4 text-sm font-medium leading-tight text-subtle">
<LearnMoreLink
t={t}
i18nKey="credit_worth_description"
href="https://cal.com/help/billing-and-usage/messaging-credits"
/>
</div>
</div>
{teamId && (
<MemberInvitationModalWithoutMembers
teamId={teamId}
showMemberInvitationModal={showMemberInvitationModal}
hideInvitationModal={() => setShowMemberInvitationModal(false)}
onSettingsOpen={() => {
return;
}}
/>
)}
</>
);
}
@@ -1,80 +0,0 @@
import { SkeletonText, SkeletonContainer, SkeletonButton } from "@calcom/ui/components/skeleton";
export function BillingCreditsSkeleton() {
return (
<SkeletonContainer>
<div className="bg-cal-muted border-muted mt-5 rounded-xl p-1">
<div className="flex flex-col gap-1 px-4 py-5">
<SkeletonText className="h-4 w-20" /> {/* Credits title */}
<SkeletonText className="h-4 w-48" /> {/* View and manage credits description */}
</div>
<div className="bg-default border-muted flex w-full rounded-[10px] px-5 py-4">
<div className="w-full">
{/* Credits section */}
<div className="mb-4">
{/* Monthly credits row */}
<div className="mt-1 flex justify-between">
<SkeletonText className="h-4 w-32" />
<SkeletonText className="h-4 w-20" />
</div>
{/* Additional credits row */}
<div className="mt-1 flex justify-between">
<SkeletonText className="h-4 w-36" />
<SkeletonText className="h-4 w-20" />
</div>
{/* Remaining row */}
<div className="mt-1 flex justify-between">
<SkeletonText className="h-4 w-24" />
<SkeletonText className="h-4 w-20" />
</div>
{/* Progress bar */}
<div className="mt-4">
<div className="h-2 w-full rounded-md bg-gray-200" />
</div>
{/* Credits per tip */}
<div className="mt-4 flex flex-1 justify-between">
<SkeletonText className="h-4 w-32" />
<SkeletonButton className="h-8 w-24 rounded-md" />
</div>
</div>
<div className="-mx-5 mt-5">
<hr className="border-subtle" />
</div>
{/* Additional Credits form */}
<div className="mt-4 flex">
<div className="-mb-1 mr-auto w-full">
<SkeletonText className="mb-2 h-4 w-32" /> {/* Additional credits label */}
<div className="flex w-full">
<SkeletonText className="h-9 w-full rounded-md" /> {/* Input field */}
</div>
</div>
<div className="ml-2 mt-auto">
<SkeletonButton className="h-9 w-12 rounded-md" /> {/* Buy button */}
</div>
</div>
<div className="-mx-5 mt-5">
<hr className="border-subtle" />
</div>
{/* Download Expense Log */}
<div className="mt-4 flex">
<div className="mr-auto w-full">
<SkeletonText className="mb-4 h-4 w-40" /> {/* Download expense log label */}
<div className="mr-2 mt-1">
<SkeletonText className="h-9 w-full rounded-md" /> {/* Select dropdown */}
</div>
</div>
<div className="mt-auto">
<SkeletonButton className="h-9 w-20 rounded-md" /> {/* Download button */}
</div>
</div>
</div>
</div>
{/* Credit Worth Section */}
<div className="text-subtle px-5 py-4">
<SkeletonText className="h-4 w-full" />
<SkeletonText className="mt-1 h-4 w-3/4" />
</div>
</div>
</SkeletonContainer>
);
}
@@ -1,235 +0,0 @@
"use client";
import { keepPreviousData } from "@tanstack/react-query";
import { usePathname } from "next/navigation";
import { useSession } from "next-auth/react";
import { useState, useEffect, useRef } from "react";
import dayjs from "@calcom/dayjs";
import { ColumnFilterType, ZDateRangeFilterValue, type FilterableColumn } from "@calcom/features/data-table";
import { DataTableProvider } from "~/data-table/DataTableProvider";
import { useFilterValue } from "~/data-table/hooks/useFilterValue";
import { useSegments } from "~/data-table/hooks/useSegments";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { trpc } from "@calcom/trpc/react";
import type { FilterType } from "@calcom/types/data-table";
import { Badge } from "@calcom/ui/components/badge";
import { Button } from "@calcom/ui/components/button";
import { PanelCard } from "@calcom/ui/components/card";
import { Icon } from "@calcom/ui/components/icon";
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "@calcom/ui/components/table/TableNew";
import { DateRangeFilter } from "~/data-table/components";
import { InvoicesTableSkeleton } from "./InvoicesTableSkeleton";
const DEFAULT_PAGE_SIZE = 10;
const createdAtColumn: Extract<FilterableColumn, { type: Extract<FilterType, "dr"> }> = {
id: "createdAt",
title: "Date",
type: ColumnFilterType.DATE_RANGE,
};
function formatCurrency(amount: number, currency: string) {
return new Intl.NumberFormat(undefined, {
style: "currency",
currency: currency.toUpperCase(),
}).format(amount / 100);
}
function getStatusBadgeColor(status: string | null): "green" | "orange" | "gray" | "red" {
switch (status) {
case "paid":
return "green";
case "open":
return "orange";
case "draft":
return "gray";
case "void":
case "uncollectible":
return "red";
default:
return "gray";
}
}
export function InvoicesTable() {
const pathname = usePathname();
if (!pathname) return null;
return (
<DataTableProvider tableIdentifier={`${pathname}-invoices`} useSegments={useSegments}>
<InvoicesTableContent />
</DataTableProvider>
);
}
function InvoicesTableContent() {
const { t } = useLocale();
const pathname = usePathname();
const session = useSession();
const [cursors, setCursors] = useState<(string | null)[]>([null]);
const [currentPage, setCurrentPage] = useState(0);
const dateRangeFilter = useFilterValue("createdAt", ZDateRangeFilterValue)?.data;
// Derive teamId from context (same logic as billing-view.tsx)
const getTeamIdFromContext = () => {
if (!pathname) return null;
if (pathname.includes("/teams/") && pathname.includes("/billing")) {
const teamIdMatch = pathname.match(/\/teams\/(\d+)\/billing/);
return teamIdMatch ? parseInt(teamIdMatch[1], 10) : null;
}
if (pathname.includes("/organizations/billing")) {
return session.data?.user?.org?.id ?? null;
}
return null;
};
const teamId = getTeamIdFromContext();
const startDate = dateRangeFilter?.startDate ? new Date(dateRangeFilter.startDate) : undefined;
const endDate = dateRangeFilter?.endDate ? new Date(dateRangeFilter.endDate) : undefined;
const { data, isLoading, isFetching } = trpc.viewer.teams.listInvoices.useQuery(
{
teamId: teamId!,
limit: DEFAULT_PAGE_SIZE,
cursor: cursors[currentPage],
startDate,
endDate,
},
{ enabled: !!teamId, placeholderData: keepPreviousData }
);
// Reset pagination when date filter changes
const isFirstRender = useRef(true);
useEffect(() => {
if (isFirstRender.current) {
isFirstRender.current = false;
return;
}
setCursors([null]);
setCurrentPage(0);
}, [dateRangeFilter?.startDate, dateRangeFilter?.endDate]);
if (!teamId) return null;
if (isLoading) return <InvoicesTableSkeleton />;
const handleNextPage = () => {
if (data?.nextCursor) {
setCursors((prev) => [...prev, data.nextCursor]);
setCurrentPage((prev) => prev + 1);
}
};
const handlePrevPage = () => {
if (currentPage > 0) {
setCurrentPage((prev) => prev - 1);
}
};
return (
<PanelCard
title={t("invoices")}
headerContent={<DateRangeFilter column={createdAtColumn} />}
className="mt-5">
{!data?.invoices.length && currentPage === 0 ? (
<div className="text-subtle p-6 text-center text-sm">{t("no_invoices_in_date_range")}</div>
) : (
<>
<div className="overflow-x-auto">
<Table>
<TableHeader>
<TableRow>
<TableHead>{t("date")}</TableHead>
<TableHead>{t("invoice_number")}</TableHead>
<TableHead>{t("amount")}</TableHead>
<TableHead>{t("status")}</TableHead>
<TableHead>{t("description")}</TableHead>
<TableHead className="text-right">{t("actions")}</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{data?.invoices.map((invoice) => (
<TableRow key={invoice.id}>
<TableCell>{dayjs.unix(invoice.created).format("MMM D, YYYY")}</TableCell>
<TableCell className="font-mono text-sm">
{invoice.number && invoice.hostedInvoiceUrl ? (
<a
href={invoice.hostedInvoiceUrl}
target="_blank"
rel="noopener noreferrer"
className="inline-flex items-center gap-1 text-blue-600 hover:text-blue-800 hover:underline">
{invoice.number}
<Icon name="external-link" className="h-3 w-3" />
</a>
) : (
invoice.number || "-"
)}
</TableCell>
<TableCell>
{formatCurrency(invoice.amountPaid || invoice.amountDue, invoice.currency)}
</TableCell>
<TableCell>
<Badge color={getStatusBadgeColor(invoice.status)}>
{invoice.status ? t(`invoice_status_${invoice.status}`) : "-"}
</Badge>
</TableCell>
<TableCell className="max-w-[200px] truncate">
{invoice.description || invoice.lineItems[0]?.description || "-"}
</TableCell>
<TableCell className="text-right">
{invoice.invoicePdf && (
<Button
variant="icon"
color="minimal"
href={invoice.invoicePdf}
target="_blank"
rel="noopener noreferrer"
StartIcon="download"
tooltip={t("download_pdf")}
/>
)}
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</div>
{/* Pagination */}
{(currentPage > 0 || data?.hasMore) && (
<div className="border-muted flex items-center justify-end gap-2 border-t px-4 py-3">
<Button
color="secondary"
size="sm"
onClick={handlePrevPage}
disabled={currentPage === 0 || isFetching}
StartIcon="arrow-left">
{t("previous")}
</Button>
<Button
color="secondary"
size="sm"
onClick={handleNextPage}
disabled={!data?.hasMore || isFetching}
EndIcon="arrow-right">
{t("next")}
</Button>
</div>
)}
</>
)}
</PanelCard>
);
}
@@ -1,38 +0,0 @@
"use client";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { PanelCard } from "@calcom/ui/components/card";
import { SkeletonText } from "@calcom/ui/components/skeleton";
export function InvoicesTableSkeleton() {
const { t } = useLocale();
return (
<PanelCard title={t("invoices")} className="mt-5">
<div className="p-4">
{/* Header row */}
<div className="mb-3 flex gap-4 border-b pb-3">
<SkeletonText className="h-4 w-20" />
<SkeletonText className="h-4 w-24" />
<SkeletonText className="h-4 w-16" />
<SkeletonText className="h-4 w-16" />
<SkeletonText className="h-4 flex-1" />
<SkeletonText className="h-4 w-24" />
<SkeletonText className="h-4 w-16" />
</div>
{/* Data rows */}
{Array.from({ length: 5 }).map((_, i) => (
<div key={i} className="flex gap-4 py-3">
<SkeletonText className="h-4 w-20" />
<SkeletonText className="h-4 w-24" />
<SkeletonText className="h-4 w-16" />
<SkeletonText className="h-4 w-16" />
<SkeletonText className="h-4 flex-1" />
<SkeletonText className="h-4 w-24" />
<SkeletonText className="h-4 w-8" />
</div>
))}
</div>
</PanelCard>
);
}
@@ -2,11 +2,10 @@
import { useEffect, useState } from "react";
import type { TApiKeys } from "~/ee/api-keys/components/ApiKeyListItem";
import LicenseRequired from "~/ee/common/components/LicenseRequired";
import type { TApiKeys } from "~/api-keys/api-keys/components/ApiKeyListItem";
import { Dialog } from "@calcom/features/components/controlled-dialog";
import ApiKeyDialogForm from "~/ee/api-keys/components/ApiKeyDialogForm";
import ApiKeyListItem from "~/ee/api-keys/components/ApiKeyListItem";
import ApiKeyDialogForm from "~/api-keys/api-keys/components/ApiKeyDialogForm";
import ApiKeyListItem from "~/api-keys/api-keys/components/ApiKeyListItem";
import SettingsHeader from "@calcom/features/settings/appDir/SettingsHeader";
import { APP_NAME } from "@calcom/lib/constants";
import { useLocale } from "@calcom/lib/hooks/useLocale";
@@ -66,35 +65,33 @@ const ApiKeysView = ({ apiKeys: data }: Props) => {
description={t("create_first_api_key_description", { appName: APP_NAME })}
CTA={<NewApiKeyButton />}
borderInShellHeader={true}>
<LicenseRequired>
<div>
{data?.length ? (
<>
<div className="border-subtle rounded-b-lg border border-t-0">
{data.map((apiKey, index) => (
<ApiKeyListItem
key={apiKey.id}
apiKey={apiKey}
lastItem={data.length === index + 1}
onEditClick={() => {
setApiKeyToEdit(apiKey);
setApiKeyModal(true);
}}
/>
))}
</div>
</>
) : (
<EmptyScreen
Icon="link"
headline={t("create_first_api_key")}
description={t("create_first_api_key_description", { appName: APP_NAME })}
className="rounded-b-lg rounded-t-none border-t-0"
buttonRaw={<NewApiKeyButton />}
/>
)}
</div>
</LicenseRequired>
<div>
{data?.length ? (
<>
<div className="border-subtle rounded-b-lg border border-t-0">
{data.map((apiKey, index) => (
<ApiKeyListItem
key={apiKey.id}
apiKey={apiKey}
lastItem={data.length === index + 1}
onEditClick={() => {
setApiKeyToEdit(apiKey);
setApiKeyModal(true);
}}
/>
))}
</div>
</>
) : (
<EmptyScreen
Icon="link"
headline={t("create_first_api_key")}
description={t("create_first_api_key_description", { appName: APP_NAME })}
className="rounded-b-lg rounded-t-none border-t-0"
buttonRaw={<NewApiKeyButton />}
/>
)}
</div>
<Dialog open={apiKeyModal} onOpenChange={setApiKeyModal}>
<DialogContent type="creation">
@@ -1,13 +0,0 @@
"use client";
import { CreateANewLicenseKeyForm } from "~/ee/deployment/components/CreateLicenseKeyForm";
export default function SettingsNewView() {
return (
<div className="bg-default flex min-h-screen items-start justify-center px-4 py-12">
<div className="w-full max-w-lg">
<CreateANewLicenseKeyForm />
</div>
</div>
);
}
@@ -27,7 +27,6 @@ import { SettingsToggle, ColorPicker, Form } from "@calcom/ui/components/form";
import { showToast } from "@calcom/ui/components/toast";
import { useCalcomTheme } from "@calcom/ui/styles";
import { UpgradeTeamsBadgeWebWrapper } from "~/billing/components/UpgradeTeamsBadgeWebWrapper";
const useBrandColors = (
currentTheme: string | null,
@@ -394,7 +393,7 @@ const AppearanceView = ({
disabled={!hasPaidPlan || mutation?.isPending}
description={t("removes_cal_branding", { appName: APP_NAME })}
checked={hasPaidPlan ? hideBrandingValue : false}
Badge={<UpgradeTeamsBadgeWebWrapper />}
Badge={undefined}
onCheckedChange={(checked) => {
setHideBrandingValue(checked);
mutation.mutate({ hideBranding: checked });
@@ -1,24 +0,0 @@
"use client";
import { FeaturesSettings } from "~/feature-opt-in/components/FeaturesSettings";
import SettingsHeader from "@calcom/features/settings/appDir/SettingsHeader";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import type { ReactElement } from "react";
import { useUserFeatureOptIn } from "~/feature-opt-in/hooks/useUserFeatureOptIn";
const FeaturesView = (): ReactElement => {
const { t } = useLocale();
const featureOptIn = useUserFeatureOptIn();
return (
<SettingsHeader
title={t("features")}
description={t("feature_opt_in_description")}
borderInShellHeader={true}>
<FeaturesSettings featureOptIn={featureOptIn} />
</SettingsHeader>
);
};
export default FeaturesView;
@@ -353,7 +353,7 @@ const GeneralView = ({ user, travelSchedules }: GeneralViewProps) => {
<SettingsToggle
toggleSwitchAtTheEnd={true}
title={t("monthly_digest_email")}
description={t("monthly_digest_email_for_teams")}
description={t("monthly_digest_email")}
disabled={mutation.isPending}
checked={isReceiveMonthlyDigestEmailChecked}
onCheckedChange={(checked) => {
@@ -2,7 +2,6 @@
import { ErrorCode } from "@calcom/features/auth/lib/ErrorCode";
import { Dialog } from "@calcom/features/components/controlled-dialog";
import { isCompanyEmail } from "@calcom/features/ee/organizations/lib/utils";
import SettingsHeader from "@calcom/features/settings/appDir/SettingsHeader";
import SectionBottomActions from "@calcom/features/settings/SectionBottomActions";
import { APP_NAME, FULL_NAME_LENGTH_MAX_LIMIT } from "@calcom/lib/constants";
@@ -71,7 +70,6 @@ const ProfileView = ({ user }: Props) => {
const utils = trpc.useUtils();
const session = useSession();
const { update } = session;
const [showSecondaryEmailModalOpen, setShowSecondaryEmailModalOpen] = useState(false);
const updateProfileMutation = trpc.viewer.me.updateProfile.useMutation({
onSuccess: async (res) => {
await update(res);
@@ -130,6 +128,7 @@ const ProfileView = ({ user }: Props) => {
const [confirmPasswordErrorMessage, setConfirmPasswordDeleteErrorMessage] = useState("");
const [showCreateAccountPasswordDialog, setShowCreateAccountPasswordDialog] = useState(false);
const [showAccountDisconnectWarning, setShowAccountDisconnectWarning] = useState(false);
const [showSecondaryEmailModalOpen, setShowSecondaryEmailModalOpen] = useState(false);
const [secondaryEmailAddErrorMessage, setSecondaryEmailAddErrorMessage] = useState("");
const [newlyAddedSecondaryEmail, setNewlyAddedSecondaryEmail] = useState<undefined | string>(undefined);
@@ -255,7 +254,7 @@ const ProfileView = ({ user }: Props) => {
!session.data?.user?.org?.id &&
!user.organization?.id &&
userEmail &&
isCompanyEmail(userEmail);
false;
return (
<SettingsHeader
@@ -314,9 +313,9 @@ const ProfileView = ({ user }: Props) => {
</div>
)}
<div className="border-subtle mt-6 rounded-lg rounded-b-none border border-b-0 p-6">
<Label className="mb-0 text-base font-semibold text-red-700">{t("danger_zone")}</Label>
<p className="text-subtle text-sm">{t("account_deletion_cannot_be_undone")}</p>
<div className="mt-6 rounded-lg rounded-b-none border border-subtle border-b-0 p-6">
<Label className="mb-0 font-semibold text-base text-red-700">{t("danger_zone")}</Label>
<p className="text-sm text-subtle">{t("account_deletion_cannot_be_undone")}</p>
</div>
{/* Delete account Dialog */}
<Dialog open={deleteAccountOpen} onOpenChange={setDeleteAccountOpen}>
@@ -332,40 +331,38 @@ const ProfileView = ({ user }: Props) => {
description={t("confirm_delete_account_modal", { appName: APP_NAME })}
type="creation"
Icon="triangle-alert">
<>
<div className="mb-10">
<p className="text-subtle mb-4 text-sm">{t("delete_account_confirmation_message")}</p>
{isCALIdentityProvider && (
<PasswordField
data-testid="password"
name="password"
id="password"
autoComplete="current-password"
required
label="Password"
ref={passwordRef}
/>
)}
<div className="mb-10">
<p className="mb-4 text-sm text-subtle">{t("delete_account_confirmation_message")}</p>
{isCALIdentityProvider && (
<PasswordField
data-testid="password"
name="password"
id="password"
autoComplete="current-password"
required
label="Password"
ref={passwordRef}
/>
)}
{user?.twoFactorEnabled && isCALIdentityProvider && (
<Form handleSubmit={onConfirm} className="pb-4" form={form}>
<TwoFactor center={false} />
</Form>
)}
{user?.twoFactorEnabled && isCALIdentityProvider && (
<Form handleSubmit={onConfirm} className="pb-4" form={form}>
<TwoFactor center={false} />
</Form>
)}
{hasDeleteErrors && <Alert severity="error" title={deleteErrorMessage} />}
</div>
<DialogFooter showDivider>
<DialogClose />
<Button
color="destructive"
data-testid="delete-account-confirm"
onClick={(e) => onConfirmButton(e)}
loading={deleteMeMutation.isPending}>
{t("delete_my_account")}
</Button>
</DialogFooter>
</>
{hasDeleteErrors && <Alert severity="error" title={deleteErrorMessage} />}
</div>
<DialogFooter showDivider>
<DialogClose />
<Button
color="destructive"
data-testid="delete-account-confirm"
onClick={(e) => onConfirmButton(e)}
loading={deleteMeMutation.isPending}>
{t("delete_my_account")}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
@@ -379,13 +376,13 @@ const ProfileView = ({ user }: Props) => {
<div className="mb-10">
<div className="mb-4 grid gap-2 md:grid-cols-2">
<div>
<span className="text-emphasis mb-2 block text-sm font-medium leading-none">
<span className="mb-2 block font-medium text-emphasis text-sm leading-none">
{t("old_email_address")}
</span>
<p className="text-subtle leading-none">{user.email}</p>
</div>
<div>
<span className="text-emphasis mb-2 block text-sm font-medium leading-none">
<span className="mb-2 block font-medium text-emphasis text-sm leading-none">
{t("new_email_address")}
</span>
<p className="text-subtle leading-none">{tempFormValues?.email}</p>
@@ -600,10 +597,8 @@ const ProfileForm = ({
handleAccountDisconnect(getUpdatedFormValues(formMethods.getValues()));
};
const { data: usersAttributes, isPending: usersAttributesPending } =
trpc.viewer.attributes.getByUserId.useQuery({
userId: user.id,
});
type UserAttribute = { id: string; name: string; type: string; options: { value: string }[] };
const usersAttributes = null as UserAttribute[] | null;
const {
formState: { isSubmitting, isDirty },
@@ -612,7 +607,7 @@ const ProfileForm = ({
const isDisabled = isSubmitting || !isDirty;
return (
<Form form={formMethods} handleSubmit={handleFormSubmit}>
<div className="border-subtle border-x px-4 pb-10 pt-8 sm:px-6">
<div className="border-subtle border-x px-4 pt-8 pb-10 sm:px-6">
<div className="flex items-center">
<Controller
control={formMethods.control}
@@ -623,7 +618,7 @@ const ProfileForm = ({
<>
<UserAvatar data-testid="profile-upload-avatar" previewSrc={value} size="lg" user={user} />
<div className="ms-4">
<h2 className="mb-2 text-sm font-medium">{t("profile_picture")}</h2>
<h2 className="mb-2 font-medium text-sm">{t("profile_picture")}</h2>
<div className="flex gap-2">
<ImageUploader
target="avatar"
@@ -653,7 +648,7 @@ const ProfileForm = ({
/>
</div>
{extraField}
<p className="text-subtle mt-1 flex gap-1 text-sm">
<p className="mt-1 flex gap-1 text-sm text-subtle">
<InfoIcon className="mt-0.5 shrink-0" />
<span className="flex-1">{t("tip_username_plus")}</span>
</p>
@@ -743,7 +738,7 @@ const ProfileForm = ({
<div className="flex items-center">
<span className="text-default text-sm capitalize">{user.identityProvider.toLowerCase()}</span>
{user.identityProviderEmail && (
<span className="text-default ml-2 text-sm">{user.identityProviderEmail}</span>
<span className="ml-2 text-default text-sm">{user.identityProviderEmail}</span>
)}
<div className="flex flex-1 justify-end">
<Button color="destructive" onClick={onDisconnect}>
@@ -1,15 +1,9 @@
"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,
@@ -20,13 +14,6 @@ const CreateNewOutOfOfficeEntryButton = ({
"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?.canUpdateTeams;
const params = useCompatSearchParams();
const selectedTab = params?.get("type") ?? OutOfOfficeTab.MINE;
return (
<Button
@@ -35,8 +22,7 @@ const CreateNewOutOfOfficeEntryButton = ({
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}>
data-testid={rest["data-testid"]}>
<span className="sr-only md:not-sr-only md:inline">{t("add")}</span>
</Button>
);
@@ -1,6 +1,3 @@
import { useMemo, useState } from "react";
import { Controller, useForm } from "react-hook-form";
import dayjs from "@calcom/dayjs";
import { Dialog } from "@calcom/features/components/controlled-dialog";
import { useCompatSearchParams } from "@calcom/lib/hooks/useCompatSearchParams";
@@ -12,17 +9,22 @@ import classNames from "@calcom/ui/classNames";
import { Alert } from "@calcom/ui/components/alert";
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 {
Checkbox,
DateRangePicker,
Input,
Label,
Select,
Switch,
TextArea,
} from "@calcom/ui/components/form";
import { showToast } from "@calcom/ui/components/toast";
import { useHasTeamPlan } from "@calcom/web/modules/billing/hooks/useHasPaidPlan";
import { UpgradeTeamsBadgeWebWrapper as UpgradeTeamsBadge } from "~/billing/components/UpgradeTeamsBadgeWebWrapper";
import { useMemo, useState } from "react";
import { Controller, useForm } from "react-hook-form";
import { OutOfOfficeTab } from "~/settings/outOfOffice/OutOfOfficeToggleGroup";
export type { BookingRedirectForm } from "~/settings/outOfOffice/types";
import type { BookingRedirectForm } from "~/settings/outOfOffice/types";
type Option = { value: number; label: string };
@@ -45,13 +47,19 @@ export const CreateOrEditOutOfOfficeEntryModal = ({
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 oooForMembers = undefined as
| {
data?: {
pages: {
members: { id: number; name: string | null; username: string | null; avatarUrl: string | null }[];
}[];
};
hasNextPage: boolean;
isFetchingNextPage: boolean;
fetchNextPage: () => void;
}
| undefined;
const oooMemberListOptions: {
value: number;
label: string;
@@ -65,41 +73,64 @@ export const CreateOrEditOutOfOfficeEntryModal = ({
},
]
: 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,
})) || [];
?.flatMap(
(page: {
members: { id: number; name: string | null; username: string | null; avatarUrl: string | null }[];
}) => page.members
)
?.filter(
(member: { id: number; name: string | null; username: string | null; avatarUrl: string | null }) =>
me?.data?.id !== member.id
)
.map(
(member: {
id: number;
name: string | null;
username: string | null;
avatarUrl: string | null;
}) => ({
value: member.id,
label: member.name || member.username || "",
avatarUrl: member.avatarUrl,
})
) || [];
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 redirectMembers = undefined as
| {
data?: {
pages: {
members: { id: number; name: string | null; username: string | null; avatarUrl: string | null }[];
}[];
};
hasNextPage: boolean;
isFetchingNextPage: boolean;
fetchNextPage: () => void;
}
| undefined;
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
?.flatMap(
(page: {
members: { id: number; name: string | null; username: string | null; avatarUrl: string | null }[];
}) => page.members
)
.map((member) => ({
value: member.id,
label: member.name || member.username || "",
avatarUrl: member.avatarUrl,
})) || [];
?.filter(
(member: { id: number; name: string | null; username: string | null; avatarUrl: string | null }) =>
me?.data?.id !== member.id
)
.map(
(member: { id: number; name: string | null; username: string | null; avatarUrl: string | null }) => ({
value: member.id,
label: member.name || member.username || "",
avatarUrl: member.avatarUrl,
})
) || [];
const { data: outOfOfficeReasonList, isPending: isReasonListPending } =
trpc.viewer.ooo.outOfOfficeReasonList.useQuery();
@@ -110,7 +141,7 @@ export const CreateOrEditOutOfOfficeEntryModal = ({
const [profileRedirect, setProfileRedirect] = useState(!!currentlyEditingOutOfOfficeEntry?.toTeamUserId);
const { hasTeamPlan } = useHasTeamPlan();
const hasTeamPlan = false;
const {
handleSubmit,
@@ -206,56 +237,10 @@ export const CreateOrEditOutOfOfficeEntryModal = ({
<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
currentlyEditingOutOfOfficeEntry ? t("edit_an_out_of_office") : t("create_an_out_of_office")
}
/>
{/* 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>
<Controller
control={control}
name="forUserId"
render={({ field: { onChange, value } }) => (
<Select
className="mt-2"
data-testid="ooofor_username_select"
isSearchable={true}
isDisabled={!!currentlyEditingOutOfOfficeEntry}
menuPlacement="bottom"
value={oooMemberListOptions.find((member) => member.value === value)}
placeholder={t("search")}
options={oooMemberListOptions}
onInputChange={(newValue) => setSearchMember(newValue)}
onChange={(selectedOption) => {
if (selectedOption?.value) {
onChange(selectedOption.value);
}
}}
onMenuScrollToBottom={() => {
if (oooForMembers.hasNextPage && !oooForMembers.isFetchingNextPage) {
oooForMembers.fetchNextPage();
}
}}
isLoading={oooForMembers.isFetchingNextPage}
/>
)}
/>
</div>
)}
<div>
<p className="text-emphasis mb-1 block text-sm font-medium capitalize">{t("dates")}</p>
<div>
@@ -383,11 +368,7 @@ export const CreateOrEditOutOfOfficeEntryModal = ({
}}
label={hasTeamPlan ? t("redirect_team_enabled") : t("redirect_team_disabled")}
/>
{!hasTeamPlan && (
<div className="mx-2" data-testid="upgrade-team-badge">
<UpgradeTeamsBadge />
</div>
)}
{!hasTeamPlan && <div className="mx-2" data-testid="upgrade-team-badge"></div>}
</div>
{profileRedirect && (
@@ -415,11 +396,11 @@ export const CreateOrEditOutOfOfficeEntryModal = ({
}
}}
onMenuScrollToBottom={() => {
if (redirectMembers.hasNextPage && !redirectMembers.isFetchingNextPage) {
redirectMembers.fetchNextPage();
if (redirectMembers?.hasNextPage && !redirectMembers?.isFetchingNextPage) {
redirectMembers?.fetchNextPage();
}
}}
isLoading={redirectMembers.isFetchingNextPage}
isLoading={redirectMembers?.isFetchingNextPage}
/>
)}
/>
@@ -1,5 +1,18 @@
"use client";
import dayjs from "@calcom/dayjs";
import { ColumnFilterType, ZDateRangeFilterValue } from "@calcom/features/data-table";
import SettingsHeader from "@calcom/features/settings/appDir/SettingsHeader";
import ServerTrans from "@calcom/lib/components/ServerTrans";
import { useCompatSearchParams } from "@calcom/lib/hooks/useCompatSearchParams";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { trpc } from "@calcom/trpc/react";
import { Button } from "@calcom/ui/components/button";
import { EmptyScreen } from "@calcom/ui/components/empty-screen";
import { SkeletonText } from "@calcom/ui/components/skeleton";
import { showToast } from "@calcom/ui/components/toast";
import { Tooltip } from "@calcom/ui/components/tooltip";
import { ClockIcon } from "@coss/ui/icons";
import { keepPreviousData } from "@tanstack/react-query";
import {
createColumnHelper,
@@ -9,36 +22,19 @@ import {
} from "@tanstack/react-table";
import { usePathname } from "next/navigation";
import { useEffect, useMemo, useRef, useState } from "react";
import dayjs from "@calcom/dayjs";
import { ColumnFilterType, ZDateRangeFilterValue } from "@calcom/features/data-table";
import {
DataTableFilters,
DataTableSegment,
DataTableToolbar,
DataTableWrapper,
} from "~/data-table/components";
import { DataTableProvider } from "~/data-table/DataTableProvider";
import { useDataTable } from "~/data-table/hooks/useDataTable";
import { useFilterValue } from "~/data-table/hooks/useFilterValue";
import {
DataTableWrapper,
DataTableToolbar,
DataTableFilters,
DataTableSegment,
} from "~/data-table/components";
import { useSegments } from "~/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 { SkeletonText } from "@calcom/ui/components/skeleton";
import { ClockIcon } from "@coss/ui/icons";
import { showToast } from "@calcom/ui/components/toast";
import { Tooltip } from "@calcom/ui/components/tooltip";
import CreateNewOutOfOfficeEntryButton from "./CreateNewOutOfOfficeEntryButton";
import type { BookingRedirectForm } from "./types";
import { OutOfOfficeTab, OutOfOfficeToggleGroup } from "./OutOfOfficeToggleGroup";
import type { BookingRedirectForm } from "./types";
interface OutOfOfficeEntry {
id: number;
@@ -118,7 +114,7 @@ function OutOfOfficeEntriesListContent({
trpc.viewer.ooo.outOfOfficeEntriesList.useInfiniteQuery(
{
limit: 10,
fetchTeamMembersEntries: selectedTab === OutOfOfficeTab.TEAM,
fetchTeamMembersEntries: false,
searchTerm,
endDateFilterStartRange: endDateRange?.startDate ?? undefined,
endDateFilterEndRange: endDateRange?.endDate ?? undefined,
@@ -169,50 +165,6 @@ function OutOfOfficeEntriesListContent({
},
},
}),
...(selectedTab === OutOfOfficeTab.TEAM
? [
columnHelper.display({
id: "member",
header: `Member`,
size: 220,
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})`,
@@ -329,7 +281,6 @@ function OutOfOfficeEntriesListContent({
onClick={() => {
deleteOutOfOfficeEntryMutation.mutate({
outOfOfficeUid: item.uuid,
userId: selectedTab === OutOfOfficeTab.TEAM ? item.user?.id : undefined,
});
}}
/>
@@ -372,7 +323,7 @@ function OutOfOfficeEntriesListContent({
<>
<DataTableWrapper
testId="ooo-list-data-table"
rowClassName={selectedTab === OutOfOfficeTab.MINE ? "hidden" : ""}
rowClassName=""
table={table}
isPending={isPending}
hasNextPage={hasNextPage}
@@ -397,18 +348,8 @@ function OutOfOfficeEntriesListContent({
EmptyView={
<EmptyScreen
className="mt-6"
headline={
searchTerm
? t("no_result_found_for", { searchTerm })
: 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")
}
headline={searchTerm ? t("no_result_found_for", { searchTerm }) : t("ooo_empty_title")}
description={t("ooo_empty_description")}
buttonRaw={<CreateNewOutOfOfficeEntryButton size="sm" onClick={onOpenCreateDialog} />}
customIcon={
<div className="mt-4 h-[102px]">
@@ -1,15 +1,13 @@
"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";
import { usePathname, useRouter } from "next/navigation";
import { useCallback, useMemo } from "react";
export enum OutOfOfficeTab {
MINE = "mine",
TEAM = "team",
HOLIDAYS = "holidays",
}
@@ -34,7 +32,6 @@ export const OutOfOfficeToggleGroup = () => {
const tabOptions = useMemo(
() => [
{ value: OutOfOfficeTab.MINE, label: t("my_ooo") },
{ value: OutOfOfficeTab.TEAM, label: t("team_ooo") },
{ value: OutOfOfficeTab.HOLIDAYS, label: t("holidays") },
],
[t]
@@ -1,173 +0,0 @@
"use client";
import { usePathname } from "next/navigation";
import { Dialog } from "@calcom/features/components/controlled-dialog";
import { WEBAPP_URL } from "@calcom/lib/constants";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { Button } from "@calcom/ui/components/button";
import { DialogTrigger, ConfirmationDialogContent } from "@calcom/ui/components/dialog";
import { showToast } from "@calcom/ui/components/toast";
import { PlatformPricing } from "@calcom/web/components/settings/platform/pricing/platform-pricing/index";
import { useUnsubscribeTeamToStripe } from "@lib/hooks/settings/platform/billing/useUnsubscribeTeamToStripe";
import NoPlatformPlan from "@components/settings/platform/dashboard/NoPlatformPlan";
import { useGetUserAttributes } from "@components/settings/platform/hooks/useGetUserAttributes";
import { CtaRow } from "~/settings/billing/billing-view";
import Shell from "~/shell/Shell";
declare global {
interface Window {
Support?: {
open: () => void;
shouldShowTriggerButton: (showTrigger: boolean) => void;
};
}
}
export default function PlatformBillingUpgrade() {
const pathname = usePathname();
const { t } = useLocale();
const { isUserLoading, isUserBillingDataLoading, isPlatformUser, userBillingData, isPaidUser, userOrgId } =
useGetUserAttributes();
const returnTo = pathname;
const teamId = `teamId=${userOrgId}`;
const billingHref = `/api/integrations/stripepayment/portal?returnTo=${WEBAPP_URL}${returnTo}&${teamId}`;
const onContactSupportClick = async () => {
if (window.Support) {
window.Support.open();
}
};
const { mutateAsync: removeTeamSubscription, isPending: isRemoveTeamSubscriptionLoading } =
useUnsubscribeTeamToStripe({
onSuccess: () => {
window.location.href = "/settings/platform/";
showToast(t("team_subscription_cancelled_successfully"), "success");
},
onError: () => {
showToast(t("team_subscription_cancellation_error"), "error");
},
teamId: userOrgId,
});
if (isUserLoading || (isUserBillingDataLoading && !userBillingData)) {
return <div className="m-5">{t("loading")}</div>;
}
if (isPlatformUser && !isPaidUser)
return (
<PlatformPricing
teamId={userOrgId}
heading={
<div className="mb-5 text-center text-2xl font-semibold">
<h1>{t("subscribe_to_platform")}</h1>
</div>
}
/>
);
if (!isPlatformUser)
return (
<div>
<Shell isPlatformUser={true} withoutMain={false} SidebarContainer={<></>}>
<NoPlatformPlan />
</Shell>
</div>
);
return (
<div>
<Shell
heading={t("platform_billing")}
title={t("platform_billing")}
withoutMain={false}
subtitle={t("manage_billing_description")}
isPlatformUser={true}>
<>
<div className="border-subtle stack-y-6 sm:stack-y-8 rounded-lg border px-6 py-8 text-sm">
<CtaRow
title={t("view_and_manage_billing_details")}
description={t("view_and_edit_billing_details")}>
<Button color="primary" href={billingHref} target="_blank" EndIcon="external-link">
{t("billing_portal")}
</Button>
</CtaRow>
<hr className="border-subtle" />
<CtaRow
title="Change plan"
description={t("Want to change your existing plan or check out other plans?")}>
<Button href="/settings/platform/plans" color="secondary">
Plans
</Button>
</CtaRow>
<hr className="border-subtle" />
<CtaRow title="Cancel subscription" description={t("Cancel your existing platform subscription")}>
<CancelSubscriptionButton
buttonClassName="hidden me-2 sm:inline"
isPending={isRemoveTeamSubscriptionLoading}
handleDelete={() => {
removeTeamSubscription();
}}
/>
</CtaRow>
<hr className="border-subtle" />
<CtaRow title={t("need_anything_else")} description={t("further_billing_help")}>
<Button color="secondary" onClick={onContactSupportClick}>
{t("contact_support")}
</Button>
</CtaRow>
</div>
</>
</Shell>
</div>
);
}
const CancelSubscriptionButton = ({
buttonClassName,
isPending,
onDeleteConfirmed,
handleDelete,
}: {
onDeleteConfirmed?: () => void;
buttonClassName: string;
handleDelete: () => void;
isPending: boolean;
}) => {
const { t } = useLocale();
return (
<Dialog>
<DialogTrigger asChild>
<Button color="destructive" className={buttonClassName}>
{t("cancel")}
</Button>
</DialogTrigger>
<ConfirmationDialogContent
isPending={isPending}
variety="danger"
title={t("cancel_subscription")}
confirmBtnText={t("confirm_subscription_cancellation")}
loadingText={t("confirm_subscription_cancellation")}
cancelBtnText={t("back")}
onConfirm={() => {
handleDelete();
onDeleteConfirmed?.();
}}>
{t("cancel_subscription_description")}
</ConfirmationDialogContent>
</Dialog>
);
};
@@ -1,97 +0,0 @@
"use client";
import { useMemo, useState } from "react";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { Label } from "@calcom/ui/components/form";
import { Select } from "@calcom/ui/components/form";
import { Skeleton, SkeletonContainer, SkeletonText } from "@calcom/ui/components/skeleton";
import { PlatformManagedUsersTable } from "@calcom/web/modules/users/components/UserTable/PlatformManagedUsersTable";
import { useOAuthClients } from "@lib/hooks/settings/platform/oauth-clients/useOAuthClients";
import Shell from "~/shell/Shell";
type OAuthClientOption = { label: string; value: string };
const ManagedUsersView = () => {
const { t } = useLocale();
const { data: OAuthClientsQueryData, error, isLoading: isOAuthClientLoading } = useOAuthClients();
const oAuthClientOptions: OAuthClientOption[] = useMemo(
() =>
OAuthClientsQueryData.map((client) => ({
label: client.name,
value: client.id,
})),
[OAuthClientsQueryData]
);
const [oAuthClient, setOAuthClient] = useState<OAuthClientOption | null>(oAuthClientOptions[0] || null);
const ManagedUsersSkeletonLoader = () => {
return (
<div className="flex">
<div className="w-1/4 p-4" />
<div className="flex-1 p-6">
<SkeletonContainer>
<div className="mb-4 flex justify-between">
<SkeletonText className="mb-2 h-6 w-1/3" />
<SkeletonText className="h-6 w-1/5" />
</div>
<div className="mb-4">
<SkeletonText className="h-8 w-1/2 rounded-md" />
</div>
<div className="border-subtle flex items-center border-b py-3">
<SkeletonText className="h-6 w-1/4" />
<SkeletonText className="ml-4 h-6 w-1/5" />
<SkeletonText className="ml-4 h-6 w-1/5" />
</div>
<div className="mt-4">
<SkeletonText className="mx-auto h-4 w-1/3" />
</div>
</SkeletonContainer>
</div>
</div>
);
};
if (isOAuthClientLoading) {
return <ManagedUsersSkeletonLoader />;
}
if (error) {
return <div className="m-5 text-red-500">{t("Failed to load OAuth clients.")}</div>;
}
if (!OAuthClientsQueryData.length) {
return (
<div className="m-5">{t("No OAuth clients available. Please create one to view managed users.")}</div>
);
}
return (
<Shell
heading={t("managed_users")}
subtitle={t("managed_users_description")}
title={t("managed_users")}
description={t("managed_users_description")}
withoutMain={false}
isPlatformUser={true}>
<Skeleton as={Label} loadingClassName="w-16" title={t("select_oAuth_client")}>
{t("select_oAuth_client")}
</Skeleton>
<Select
className="z-20 mb-4 w-40"
options={oAuthClientOptions}
value={oAuthClient}
isSearchable={false}
onChange={(client) => client && setOAuthClient(client)}
/>
{oAuthClient && <PlatformManagedUsersTable oAuthClientId={oAuthClient.value} />}
</Shell>
);
};
export default ManagedUsersView;
@@ -1,127 +0,0 @@
"use client";
import { useParams } from "next/navigation";
import { useRouter } from "next/navigation";
import { ErrorCode } from "@calcom/lib/errorCodes";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { PERMISSIONS_GROUPED_MAP } from "@calcom/platform-constants";
import { showToast } from "@calcom/ui/components/toast";
import { useOAuthClient } from "@lib/hooks/settings/platform/oauth-clients/useOAuthClient";
import { useUpdateOAuthClient } from "@lib/hooks/settings/platform/oauth-clients/useUpdateOAuthClient";
import NoPlatformPlan from "@components/settings/platform/dashboard/NoPlatformPlan";
import { useGetUserAttributes } from "@components/settings/platform/hooks/useGetUserAttributes";
import type { FormValues } from "@components/settings/platform/oauth-clients/oauth-client-form";
import { OAuthClientForm as EditOAuthClientForm } from "@components/settings/platform/oauth-clients/oauth-client-form";
import Shell from "~/shell/Shell";
export default function EditOAuthClient() {
const { t } = useLocale();
const router = useRouter();
const params = useParams<{ clientId: string }>();
const clientId = params?.clientId || "";
const { isUserLoading, isPlatformUser, isPaidUser } = useGetUserAttributes();
const { data, isFetched, isFetching, isError, refetch } = useOAuthClient(clientId);
const { mutateAsync: update, isPending: isUpdating } = useUpdateOAuthClient({
onSuccess: () => {
showToast(t("oauth_client_updated_successfully"), "success");
refetch();
router.push("/settings/platform/");
},
onError: () => {
showToast(ErrorCode.UpdatingOauthClientError, "error");
},
clientId,
});
const onSubmit = (data: FormValues) => {
let userPermissions = 0;
const userRedirectUris = data.redirectUris.map((uri) => uri.uri).filter((uri) => !!uri);
Object.keys(PERMISSIONS_GROUPED_MAP).forEach((key) => {
const entity = key as keyof typeof PERMISSIONS_GROUPED_MAP;
const entityKey = PERMISSIONS_GROUPED_MAP[entity].key;
const read = PERMISSIONS_GROUPED_MAP[entity].read;
const write = PERMISSIONS_GROUPED_MAP[entity].write;
if (data[`${entityKey}Read`]) userPermissions |= read;
if (data[`${entityKey}Write`]) userPermissions |= write;
});
update({
name: data.name,
// logo: data.logo,
redirectUris: userRedirectUris,
bookingRedirectUri: data.bookingRedirectUri,
bookingCancelRedirectUri: data.bookingCancelRedirectUri,
bookingRescheduleRedirectUri: data.bookingRescheduleRedirectUri,
areEmailsEnabled: data.areEmailsEnabled,
areDefaultEventTypesEnabled: data.areDefaultEventTypesEnabled,
areCalendarEventsEnabled: data.areCalendarEventsEnabled,
});
};
if (isUserLoading) return <div className="m-5">{t("loading")}</div>;
if (isPlatformUser && isPaidUser) {
return (
<div>
<Shell title={t("oAuth_client_updation_form")} isPlatformUser={true}>
<div className="m-2 md:mx-14 md:mx-5">
<div className="border-subtle mx-auto block justify-between rounded-t-lg border px-4 py-6 sm:flex sm:px-6">
<div className="flex w-full flex-col">
<h1 className="font-cal text-emphasis mb-1 text-xl font-semibold leading-5 tracking-wide">
{t("oAuth_client_updation_form")}
</h1>
<p className="text-default text-sm ltr:mr-4 rtl:ml-4">
{t("oAuth_client_updation_form_description")}
</p>
</div>
</div>
{(!clientId || (isFetched && !data)) && <p>{t("oauth_client_not_found")}</p>}
{isFetched && !!data && (
<EditOAuthClientForm
defaultValues={{
name: data?.name ?? "",
areEmailsEnabled: data.areEmailsEnabled ?? false,
areDefaultEventTypesEnabled: data.areDefaultEventTypesEnabled ?? false,
areCalendarEventsEnabled: data.areCalendarEventsEnabled,
redirectUris: data?.redirectUris?.map((uri) => ({ uri })) ?? [{ uri: "" }],
bookingRedirectUri: data?.bookingRedirectUri ?? "",
bookingCancelRedirectUri: data?.bookingCancelRedirectUri ?? "",
bookingRescheduleRedirectUri: data?.bookingRescheduleRedirectUri ?? "",
appsRead: data?.permissions.includes("APPS_READ"),
appsWrite: data?.permissions.includes("APPS_WRITE"),
bookingRead: data?.permissions.includes("BOOKING_READ"),
bookingWrite: data?.permissions.includes("BOOKING_WRITE"),
eventTypeRead: data?.permissions.includes("EVENT_TYPE_READ"),
eventTypeWrite: data?.permissions.includes("EVENT_TYPE_WRITE"),
profileRead: data?.permissions.includes("PROFILE_READ"),
profileWrite: data?.permissions.includes("PROFILE_WRITE"),
scheduleRead: data?.permissions.includes("SCHEDULE_READ"),
scheduleWrite: data?.permissions.includes("SCHEDULE_WRITE"),
}}
onSubmit={onSubmit}
isPending={isUpdating}
/>
)}
{isFetching && <p>{t("loading")}</p>}
{isError && <p>{t("something_went_wrong")}</p>}
</div>
</Shell>
</div>
);
}
return (
<div>
<Shell isPlatformUser={true} withoutMain={false} SidebarContainer={<></>}>
<NoPlatformPlan />
</Shell>
</div>
);
}
@@ -1,134 +0,0 @@
"use client";
import { useParams } from "next/navigation";
import { useRouter } from "next/navigation";
import { DEFAULT_WEBHOOK_VERSION } from "@calcom/features/webhooks/lib/interface/IWebhookRepository";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { WebhookTriggerEvents } from "@calcom/prisma/enums";
import { showToast } from "@calcom/ui/components/toast";
import {
useOAuthClientWebhooks,
useCreateOAuthClientWebhook,
useUpdateOAuthClientWebhook,
} from "@lib/hooks/settings/platform/oauth-clients/useOAuthClientWebhooks";
import NoPlatformPlan from "@components/settings/platform/dashboard/NoPlatformPlan";
import { useGetUserAttributes } from "@components/settings/platform/hooks/useGetUserAttributes";
import Shell from "~/shell/Shell";
import { WebhookForm } from "~/webhooks/components";
export default function EditOAuthClientWebhooks() {
const { t } = useLocale();
const router = useRouter();
const params = useParams<{ clientId: string }>();
const clientId = params?.clientId || "";
const { isUserLoading, isPlatformUser, isPaidUser } = useGetUserAttributes();
const {
data: webhooks,
status: webhooksStatus,
isFetched: isWebhooksFetched,
refetch: refetchWebhooks,
} = useOAuthClientWebhooks(clientId);
const webhookId = webhooks?.[0]?.id ?? "";
const webhook = webhooks?.[0];
const { mutateAsync: createWebhook } = useCreateOAuthClientWebhook(clientId);
const { mutateAsync: updateWebhook } = useUpdateOAuthClientWebhook(clientId);
if (isUserLoading) return <div className="m-5">{t("loading")}</div>;
if (isPlatformUser && isPaidUser) {
return (
<div>
<Shell title={t("webhook_update_form")} isPlatformUser={true}>
<div className="m-2 md:mx-5">
<div className="border-subtle mx-auto block justify-between rounded-t-lg border px-4 py-6 sm:flex sm:px-6">
<div className="flex w-full flex-col">
<h1 className="font-cal text-emphasis mb-1 text-xl font-semibold leading-5 tracking-wide">
{t("webhook_update_form")}
</h1>
<p className="text-default text-sm ltr:mr-4 rtl:ml-4">
{t("webhook_update_form_description")}
</p>
</div>
</div>
{webhooksStatus !== "success" && <p>{t("error_accessing_webhooks")}</p>}
{isWebhooksFetched && webhooksStatus === "success" && (
<WebhookForm
overrideTriggerOptions={[
{ value: WebhookTriggerEvents.BOOKING_CANCELLED, label: "booking_cancelled" },
{ value: WebhookTriggerEvents.BOOKING_CREATED, label: "booking_created" },
{ value: WebhookTriggerEvents.BOOKING_REJECTED, label: "booking_rejected" },
{ value: WebhookTriggerEvents.BOOKING_REQUESTED, label: "booking_requested" },
{ value: WebhookTriggerEvents.BOOKING_RESCHEDULED, label: "booking_rescheduled" },
{ value: WebhookTriggerEvents.BOOKING_NO_SHOW_UPDATED, label: "booking_no_show_updated" },
{ value: WebhookTriggerEvents.MEETING_ENDED, label: "meeting_ended" },
{ value: WebhookTriggerEvents.MEETING_STARTED, label: "meeting_started" },
{ value: WebhookTriggerEvents.RECORDING_READY, label: "recording_ready" },
{
value: WebhookTriggerEvents.RECORDING_TRANSCRIPTION_GENERATED,
label: "recording_transcription_generated",
},
]}
onSubmit={async (data) => {
try {
const body = {
active: data.active,
payloadTemplate: data.payloadTemplate ?? undefined,
subscriberUrl: data.subscriberUrl,
triggers: data.eventTriggers,
secret: data.secret ?? undefined,
version: data.version,
};
if (webhook) {
await updateWebhook({
webhookId,
body,
});
showToast(t("webhook_updated_successfully"), "success");
} else {
await createWebhook(body);
showToast(t("webhook_created_successfully"), "success");
}
await refetchWebhooks();
router.push("/settings/platform/");
} catch {
showToast(t(webhookId ? "webhook_update_failed" : "webhook_create_failed"), "error");
}
}}
onCancel={() => {
router.push("/settings/platform/");
}}
noRoutingFormTriggers={true}
webhook={
webhook
? {
...webhook,
eventTriggers: webhook.triggers,
secret: webhook.secret ?? null,
version: webhook.version ?? DEFAULT_WEBHOOK_VERSION,
}
: undefined
}
/>
)}
</div>
</Shell>
</div>
);
}
return (
<div>
<Shell isPlatformUser={true} withoutMain={false} SidebarContainer={<></>}>
<NoPlatformPlan />
</Shell>
</div>
);
}
@@ -1,92 +0,0 @@
"use client";
import { useRouter } from "next/navigation";
import { ErrorCode } from "@calcom/lib/errorCodes";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import type { PERMISSION_MAP } from "@calcom/platform-constants";
import { PERMISSIONS_GROUPED_MAP } from "@calcom/platform-constants/permissions";
import { showToast } from "@calcom/ui/components/toast";
import { useCreateOAuthClient } from "@lib/hooks/settings/platform/oauth-clients/useCreateOAuthClient";
import NoPlatformPlan from "@components/settings/platform/dashboard/NoPlatformPlan";
import { useGetUserAttributes } from "@components/settings/platform/hooks/useGetUserAttributes";
import type { FormValues } from "@components/settings/platform/oauth-clients/oauth-client-form";
import { OAuthClientForm } from "@components/settings/platform/oauth-clients/oauth-client-form";
import Shell from "~/shell/Shell";
export default function CreateOAuthClient() {
const router = useRouter();
const { t } = useLocale();
const { isUserLoading, isPlatformUser, isPaidUser } = useGetUserAttributes();
const { mutateAsync: save, isPending: isSaving } = useCreateOAuthClient({
onSuccess: () => {
showToast("OAuth client created successfully", "success");
router.push("/settings/platform/");
},
onError: () => {
showToast(ErrorCode.CreatingOauthClientError, "error");
},
});
const onSubmit = (data: FormValues) => {
const userPermissions: Array<keyof typeof PERMISSION_MAP> = [];
const userRedirectUris = data.redirectUris.map((uri) => uri.uri).filter((uri) => !!uri);
Object.keys(PERMISSIONS_GROUPED_MAP).forEach((key) => {
const entity = key as keyof typeof PERMISSIONS_GROUPED_MAP;
const entityKey = PERMISSIONS_GROUPED_MAP[entity].key;
if (data[`${entityKey}Read`]) userPermissions.push(`${entity}_READ`);
if (data[`${entityKey}Write`]) userPermissions.push(`${entity}_WRITE`);
});
save({
name: data.name,
permissions: userPermissions,
redirectUris: userRedirectUris,
bookingRedirectUri: data.bookingRedirectUri,
bookingCancelRedirectUri: data.bookingCancelRedirectUri,
bookingRescheduleRedirectUri: data.bookingRescheduleRedirectUri,
areEmailsEnabled: data.areEmailsEnabled,
areDefaultEventTypesEnabled: data.areDefaultEventTypesEnabled,
areCalendarEventsEnabled: data.areCalendarEventsEnabled,
});
};
if (isUserLoading) return <div className="m-5">{t("loading")}</div>;
if (isPlatformUser && isPaidUser) {
return (
<div>
<Shell title={t("oAuth_client_creation_form")} isPlatformUser={true}>
<div className="m-2 md:mx-5">
<div className="border-subtle mx-auto block justify-between rounded-t-lg border px-4 py-6 sm:flex sm:px-6">
<div className="flex w-full flex-col">
<h1 className="font-cal text-emphasis mb-1 text-xl font-semibold leading-5 tracking-wide">
{t("oAuth_client_creation_form")}
</h1>
<p className="text-default text-sm ltr:mr-4 rtl:ml-4">
{t("oAuth_client_creation_form_description")}
</p>
</div>
</div>
<OAuthClientForm isPending={isSaving} onSubmit={onSubmit} />
</div>
</Shell>
</div>
);
}
return (
<div>
<Shell isPlatformUser={true} withoutMain={false} SidebarContainer={<></>}>
<NoPlatformPlan />
</Shell>
</div>
);
}
@@ -1,41 +0,0 @@
"use client";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import NoPlatformPlan from "@components/settings/platform/dashboard/NoPlatformPlan";
import { useGetUserAttributes } from "@components/settings/platform/hooks/useGetUserAttributes";
import { PlatformPricing } from "@components/settings/platform/pricing/platform-pricing";
import Shell from "~/shell/Shell";
export default function PlatformPlans() {
const { t } = useLocale();
const { isUserLoading, isUserBillingDataLoading, isPlatformUser, isPaidUser, userBillingData, userOrgId } =
useGetUserAttributes();
if (isUserLoading || (isUserBillingDataLoading && !userBillingData)) {
return <div className="m-5">{t("loading")}</div>;
}
if (!isPlatformUser) return <NoPlatformPlan />;
return (
<div>
<Shell
backPath
isPlatformUser={true}
heading={
<h1 className="mx-2 mt-4 text-center text-xl md:text-2xl">
{t("currently_subscribed_to_plan", {
planFirstLetter: userBillingData?.plan[0],
planRest: userBillingData?.plan.slice(1).toLocaleLowerCase(),
})}
</h1>
}
withoutMain={false}
SidebarContainer={<></>}>
<PlatformPricing teamId={userOrgId} teamPlan={userBillingData?.plan.toLocaleLowerCase()} />
</Shell>
</div>
);
}
@@ -1,171 +0,0 @@
"use client";
import { QueryClientProvider, QueryClient } from "@tanstack/react-query";
import { usePathname } from "next/navigation";
import { useState, useEffect, useCallback } from "react";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { SkeletonText } from "@calcom/ui/components/skeleton";
import { showToast } from "@calcom/ui/components/toast";
import { useExternalRedirectHandler } from "@lib/hooks/settings/platform/billing/useExternalRedirectHandler";
import { useDeleteOAuthClient } from "@lib/hooks/settings/platform/oauth-clients/useDeleteOAuthClient";
import { useOAuthClients } from "@lib/hooks/settings/platform/oauth-clients/useOAuthClients";
import { HelpCards } from "@components/settings/platform/dashboard/HelpCards";
import NoPlatformPlan from "@components/settings/platform/dashboard/NoPlatformPlan";
import { OAuthClientsList } from "@components/settings/platform/dashboard/oauth-clients-list";
import { useGetUserAttributes } from "@components/settings/platform/hooks/useGetUserAttributes";
import { PlatformPricing } from "@components/settings/platform/pricing/platform-pricing";
import Shell from "~/shell/Shell";
const queryClient = new QueryClient();
const PlatformSkeletonLoader = () => (
<Shell
isPlatformUser={true}
withoutMain={false}
SidebarContainer={<></>}
heading={<SkeletonText className="h-6 w-36" />}
subtitle={<SkeletonText className="mt-1 h-4 w-64" />}
title={undefined}
description={undefined}>
<div className="mb-10">
<div className="border-subtle mx-auto block justify-between rounded-t-lg border px-4 py-6 sm:flex sm:px-6">
<div className="flex w-full flex-col gap-1">
<SkeletonText className="h-5 w-40" />
<SkeletonText className="h-4 w-56" />
</div>
<div className="mt-4 sm:mt-0">
<div className="bg-emphasis h-9 w-20 animate-pulse rounded-md" />
</div>
</div>
<div className="border-subtle divide-subtle divide-y rounded-b-lg border border-t-0">
{[0, 1].map((i) => (
<div key={i} className="flex w-full justify-between px-4 py-4 sm:px-6">
<div className="flex min-w-0 flex-1 flex-col gap-2">
<div className="flex gap-2">
<SkeletonText className="h-4 w-28" />
<SkeletonText className="h-4 w-48" />
</div>
<div className="flex gap-2">
<SkeletonText className="h-4 w-24" />
<SkeletonText className="h-4 w-40" />
</div>
<div className="flex gap-2">
<SkeletonText className="h-4 w-28" />
<SkeletonText className="h-4 w-28" />
<SkeletonText className="h-4 w-20" />
</div>
</div>
<div className="ml-4 flex shrink-0 items-start gap-3">
<div className="bg-emphasis h-8 w-20 animate-pulse rounded-md" />
<div className="bg-emphasis h-8 w-16 animate-pulse rounded-md" />
<div className="bg-emphasis h-8 w-16 animate-pulse rounded-md" />
</div>
</div>
))}
</div>
</div>
</Shell>
);
export default function Platform() {
const { t } = useLocale();
const [_initialClientId, setInitialClientId] = useState("");
const [_initialClientName, setInitialClientName] = useState("");
const pathname = usePathname();
const { data, isLoading: isOAuthClientLoading, refetch: refetchClients } = useOAuthClients();
const {
isUserLoading,
isUserBillingDataLoading,
isPlatformUser,
isPaidUser,
userBillingData,
userOrgId,
refetchTeamBilling,
refetchPlatformUser,
} = useGetUserAttributes();
const { mutateAsync, isPending: isDeleting } = useDeleteOAuthClient({
onSuccess: () => {
showToast(t("oauth_client_deletion_message"), "success");
refetchClients();
},
});
const handleDelete = async (id: string) => {
await mutateAsync({ id: id });
};
const refetchBillingState = useCallback(() => {
refetchTeamBilling();
refetchPlatformUser();
}, [refetchTeamBilling, refetchPlatformUser]);
useEffect(() => {
setInitialClientId(data[0]?.id);
setInitialClientName(data[0]?.name);
}, [data]);
useEffect(() => {
refetchBillingState();
}, [pathname, refetchTeamBilling, refetchPlatformUser, refetchBillingState]);
useExternalRedirectHandler(() => {
refetchBillingState();
});
if (isUserLoading || isOAuthClientLoading) return <PlatformSkeletonLoader />;
if (isUserBillingDataLoading && !userBillingData) {
return <PlatformSkeletonLoader />;
}
if (isPlatformUser && !isPaidUser)
return (
<PlatformPricing
teamId={userOrgId}
heading={
<div className="mb-5 text-center text-2xl font-semibold">
<h1>{t("subscribe_to_platform")}</h1>
</div>
}
/>
);
if (isPlatformUser) {
return (
<QueryClientProvider client={queryClient}>
<div>
<Shell
heading={t("platform")}
subtitle={t("platform_description")}
title={t("platform")}
description={t("platform_description")}
withoutMain={false}
isPlatformUser={true}>
<HelpCards />
<OAuthClientsList oauthClients={data} isDeleting={isDeleting} handleDelete={handleDelete} />
</Shell>
</div>
</QueryClientProvider>
);
}
return (
<div>
<Shell
// we want to hide org banner and have different sidebar tabs for platform clients
// hence we pass isPlatformUser boolean as prop
isPlatformUser={true}
withoutMain={false}
SidebarContainer={<></>}>
<NoPlatformPlan />
</Shell>
</div>
);
}
@@ -1,83 +0,0 @@
"use client";
import { useSession } from "next-auth/react";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { SkeletonContainer, SkeletonText } from "@calcom/ui/components/skeleton";
import { ComplianceDocumentCard } from "./compliance/ComplianceDocumentCard";
import { COMPLIANCE_DOCUMENTS, DOCUMENT_CATEGORIES } from "./compliance/compliance-documents";
const SkeletonLoader = () => {
return (
<SkeletonContainer>
<div className="border-subtle border border-t-0 px-4 py-8 sm:px-6">
<SkeletonText className="h-8 w-full" />
<SkeletonText className="mt-4 h-8 w-full" />
<SkeletonText className="mt-4 h-8 w-full" />
</div>
</SkeletonContainer>
);
};
const ComplianceView = () => {
const { t } = useLocale();
const session = useSession();
if (session.status === "loading") return <SkeletonLoader />;
// User has access to restricted documents if they're part of an organization
const hasRestrictedAccess = !!session.data?.user?.org?.id;
const dpaDocuments = COMPLIANCE_DOCUMENTS.filter((doc) => doc.category === DOCUMENT_CATEGORIES.DPA);
const reportDocuments = COMPLIANCE_DOCUMENTS.filter((doc) => doc.category === DOCUMENT_CATEGORIES.REPORTS);
const otherDocuments = COMPLIANCE_DOCUMENTS.filter((doc) => doc.category === DOCUMENT_CATEGORIES.OTHER);
return (
<div className="border-subtle space-y-8 rounded-b-xl border border-t-0 px-4 py-6 sm:px-6">
{/* DPA Section */}
<section>
<h2 className="text-emphasis mb-4 text-base font-semibold">{t("data_privacy")}</h2>
<div className="space-y-3">
{dpaDocuments.map((doc) => (
<ComplianceDocumentCard
key={doc.id}
document={doc}
hasAccess={!doc.restricted || hasRestrictedAccess}
/>
))}
</div>
</section>
{/* Reports Section */}
<section>
<h2 className="text-emphasis mb-4 text-base font-semibold">{t("compliance_reports")}</h2>
<div className="space-y-3">
{reportDocuments.map((doc) => (
<ComplianceDocumentCard
key={doc.id}
document={doc}
hasAccess={!doc.restricted || hasRestrictedAccess}
/>
))}
</div>
</section>
{/* Other Documents Section */}
<section>
<h2 className="text-emphasis mb-4 text-base font-semibold">{t("other_documents")}</h2>
<div className="space-y-3">
{otherDocuments.map((doc) => (
<ComplianceDocumentCard
key={doc.id}
document={doc}
hasAccess={!doc.restricted || hasRestrictedAccess}
/>
))}
</div>
</section>
</div>
);
};
export default ComplianceView;
@@ -1,66 +0,0 @@
"use client";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import classNames from "@calcom/ui/classNames";
import { Button } from "@calcom/ui/components/button";
import { Tooltip } from "@calcom/ui/components/tooltip";
import { FileTextIcon } from "@coss/ui/icons";
import type { ComplianceDocument } from "./compliance-documents";
interface ComplianceDocumentCardProps {
document: ComplianceDocument;
hasAccess: boolean;
}
export function ComplianceDocumentCard({ document, hasAccess }: ComplianceDocumentCardProps) {
const { t } = useLocale();
const getDownloadUrl = () => {
if (document.source.type === "url") {
return document.source.url;
}
// For B2 documents, use our API route
return `/api/compliance/download?id=${document.id}`;
};
const handleDownload = () => {
if (hasAccess) {
window.open(getDownloadUrl(), "_blank", "noopener,noreferrer");
}
};
return (
<div
className={classNames(
"border-subtle bg-default flex items-center justify-between rounded-lg border p-4",
!hasAccess && "opacity-60"
)}>
<div className="flex items-center gap-3">
<div className="bg-subtle flex h-10 w-10 items-center justify-center rounded-lg">
<FileTextIcon className="text-default h-5 w-5" />
</div>
<div>
<p className="text-emphasis text-sm font-medium">{t(document.name)}</p>
<p className="text-subtle text-sm">{t(document.description)}</p>
</div>
</div>
<div>
{hasAccess ? (
<Button color="secondary" onClick={handleDownload} StartIcon="download">
{t("download")}
</Button>
) : (
<Tooltip content={t("compliance_upgrade_tooltip")}>
<span>
<Button color="secondary" href="/settings/billing" StartIcon="lock">
{t("upgrade_to_access")}
</Button>
</span>
</Tooltip>
)}
</div>
</div>
);
}
@@ -1,56 +0,0 @@
export const DOCUMENT_CATEGORIES = {
DPA: "dpa",
REPORTS: "reports",
OTHER: "other",
} as const;
export type DocumentCategory = (typeof DOCUMENT_CATEGORIES)[keyof typeof DOCUMENT_CATEGORIES];
export type DocumentSource = { type: "url"; url: string } | { type: "b2"; fileName: string }; // fileName is the path in B2 bucket
export interface ComplianceDocument {
id: string;
name: string; // Translation key
description: string; // Translation key
source: DocumentSource;
category: DocumentCategory;
restricted: boolean; // true = Organizations/Enterprise only
}
export const COMPLIANCE_DOCUMENTS: ComplianceDocument[] = [
// DPA Section - External URL
{
id: "dpa",
name: "data_protection_agreement",
description: "dpa_description",
source: { type: "url", url: "https://go.cal.com/dpa" },
category: DOCUMENT_CATEGORIES.DPA,
restricted: false,
},
// Reports Section - B2 Storage
{
id: "soc2-report",
name: "soc2_report",
description: "soc2_report_description",
source: { type: "b2", fileName: "SOC2.pdf" },
category: DOCUMENT_CATEGORIES.REPORTS,
restricted: true,
},
{
id: "iso27001-cert",
name: "iso27001_certification",
description: "iso27001_description",
source: { type: "b2", fileName: "ISO27001-2022.pdf" },
category: DOCUMENT_CATEGORIES.REPORTS,
restricted: true,
},
// Other Documents - B2 Storage
{
id: "pentest-report",
name: "pentest_report",
description: "pentest_report_description",
source: { type: "b2", fileName: "pentest.pdf" },
category: DOCUMENT_CATEGORIES.OTHER,
restricted: true,
},
];
@@ -1,79 +0,0 @@
"use client";
import { useState } from "react";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { trpc } from "@calcom/trpc/react";
import type { RouterOutputs } from "@calcom/trpc/react";
import { SettingsToggle } from "@calcom/ui/components/form";
import { SkeletonText, SkeletonContainer } from "@calcom/ui/components/skeleton";
import { showToast } from "@calcom/ui/components/toast";
const SkeletonLoader = () => {
return (
<SkeletonContainer>
<div className="border-subtle stack-y-6 border border-t-0 px-4 py-8 sm:px-6">
<SkeletonText className="h-8 w-full" />
</div>
</SkeletonContainer>
);
};
const ProfileImpersonationView = ({ user }: { user: RouterOutputs["viewer"]["me"]["get"] }) => {
const { t } = useLocale();
const utils = trpc.useUtils();
const [disableImpersonation, setDisableImpersonation] = useState<boolean | undefined>(
user?.disableImpersonation
);
const mutation = trpc.viewer.me.updateProfile.useMutation({
onSuccess: () => {
showToast(t("profile_updated_successfully"), "success");
},
onSettled: () => {
utils.viewer.me.invalidate();
},
onMutate: async ({ disableImpersonation }) => {
await utils.viewer.me.get.cancel();
const previousValue = utils.viewer.me.get.getData();
setDisableImpersonation(disableImpersonation);
return { previousValue };
},
onError: (error, variables, context) => {
if (context?.previousValue) {
utils.viewer.me.get.setData(undefined, context.previousValue);
setDisableImpersonation(context.previousValue?.disableImpersonation);
}
showToast(`${t("error")}, ${error.message}`, "error");
},
});
return (
<>
<div>
<SettingsToggle
toggleSwitchAtTheEnd={true}
title={t("user_impersonation_heading")}
description={t("user_impersonation_description")}
checked={!disableImpersonation}
onCheckedChange={(checked) => {
mutation.mutate({ disableImpersonation: !checked });
}}
switchContainerClassName="rounded-t-none border-t-0"
disabled={mutation.isPending}
/>
</div>
</>
);
};
const ProfileImpersonationViewWrapper = () => {
const { data: user, isPending } = trpc.viewer.me.get.useQuery();
if (isPending || !user) return <SkeletonLoader />;
return <ProfileImpersonationView user={user} />;
};
export default ProfileImpersonationViewWrapper;
@@ -1,88 +0,0 @@
"use client";
import { useRouter } from "next/navigation";
import { useOrgBranding } from "@calcom/features/ee/organizations/context/provider";
import { useCreateEventType } from "~/event-types/hooks/useCreateEventType";
import { useCompatSearchParams } from "@calcom/lib/hooks/useCompatSearchParams";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { trpc } from "@calcom/trpc/react";
import { Button } from "@calcom/ui/components/button";
import { WizardLayout } from "@calcom/ui/components/layout";
import { showToast } from "@calcom/ui/components/toast";
import { TeamEventTypeForm } from "@calcom/features/ee/teams/components/TeamEventTypeForm";
type CreateTeamEventTypeProps = {
permissions: { canCreateEventType: boolean };
};
export const CreateTeamEventType = ({ permissions }: CreateTeamEventTypeProps) => {
const searchParams = useCompatSearchParams();
const { t } = useLocale();
const router = useRouter();
const teamId = searchParams?.get("id") ? Number(searchParams.get("id")) : -1;
const onSuccessMutation = () => {
router.push(`/settings/teams/${teamId}/profile`);
};
const onErrorMutation = (err: string) => {
showToast(err, "error");
};
const SubmitButton = (isPending: boolean) => {
return (
<Button
data-testid="finish-button"
type="submit"
color="primary"
className="w-full justify-center"
disabled={isPending}>
{t("finish")}
</Button>
);
};
const { data: team } = trpc.viewer.teams.get.useQuery(
{ teamId: teamId ?? -1, isOrg: false },
{ enabled: !!teamId }
);
const { form, createMutation, isManagedEventType } = useCreateEventType(onSuccessMutation, onErrorMutation);
const orgBranding = useOrgBranding();
const urlPrefix = orgBranding?.fullDomain ?? process.env.NEXT_PUBLIC_WEBSITE_URL;
return (
<TeamEventTypeForm
teamSlug={team?.slug}
teamId={teamId}
permissions={permissions}
urlPrefix={urlPrefix}
isPending={createMutation.isPending}
form={form}
isManagedEventType={isManagedEventType}
handleSubmit={(values) => {
createMutation.mutate(values);
}}
SubmitButton={SubmitButton}
/>
);
};
export const LayoutWrapper = ({ children }: { children: React.ReactNode }) => {
const router = useRouter();
const searchParams = useCompatSearchParams();
const teamId = searchParams?.get("id") ? Number(searchParams.get("id")) : -1;
return (
<WizardLayout
currentStep={3}
maxSteps={3}
isOptionalCallback={() => {
router.push(`/settings/teams/${teamId}/profile`);
}}>
{children}
</WizardLayout>
);
};
@@ -1,29 +0,0 @@
"use client";
import { FeaturesSettings } from "~/feature-opt-in/components/FeaturesSettings";
import SettingsHeader from "@calcom/features/settings/appDir/SettingsHeader";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import type { ReactElement } from "react";
import { useTeamFeatureOptIn } from "~/feature-opt-in/hooks/useTeamFeatureOptIn";
interface TeamFeaturesViewProps {
teamId: number;
canEdit: boolean;
}
const TeamFeaturesView = ({ teamId, canEdit }: TeamFeaturesViewProps): ReactElement => {
const { t } = useLocale();
const featureOptIn = useTeamFeatureOptIn(teamId);
return (
<SettingsHeader
title={t("features")}
description={t("feature_opt_in_team_description")}
borderInShellHeader={true}>
<FeaturesSettings featureOptIn={featureOptIn} canEdit={canEdit} />
</SettingsHeader>
);
};
export default TeamFeaturesView;
@@ -1,12 +0,0 @@
"use client";
import { WizardLayout } from "@calcom/ui/components/layout";
import AddNewTeamMembers from "@calcom/web/modules/ee/teams/components/AddNewTeamMembers";
export const LayoutWrapper = ({ children }: { children: React.ReactNode }) => (
<WizardLayout currentStep={2} maxSteps={3}>
{children}
</WizardLayout>
);
export default AddNewTeamMembers;
@@ -1,218 +0,0 @@
"use client";
import { useRouter, useSearchParams } from "next/navigation";
import posthog from "posthog-js";
import React, { useEffect, useRef, useState, type FormEvent } from "react";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import slugify from "@calcom/lib/slugify";
import { Avatar } from "@calcom/ui/components/avatar";
import { Button } from "@calcom/ui/components/button";
import { Label, TextField, TextArea } from "@calcom/ui/components/form";
import { ImageUploader } from "@calcom/ui/components/image-uploader";
import { showToast } from "@calcom/ui/components/toast";
import { OnboardingCard } from "~/onboarding/components/OnboardingCard";
import { OnboardingLayout } from "~/onboarding/components/OnboardingLayout";
import { OnboardingBrowserView } from "~/onboarding/components/onboarding-browser-view";
import { useCreateTeam } from "~/onboarding/hooks/useCreateTeam";
import { useOnboardingStore } from "~/onboarding/store/onboarding-store";
import { ValidatedTeamSlug } from "~/onboarding/teams/details/validated-team-slug";
type CreateNewTeamViewProps = {
userEmail: string;
};
export const CreateNewTeamView = ({ userEmail }: CreateNewTeamViewProps) => {
const router = useRouter();
const searchParams = useSearchParams();
const { t } = useLocale();
const store = useOnboardingStore();
const { teamDetails, teamBrand, setTeamDetails, setTeamBrand, resetOnboardingPreservingPlan } = store;
const bpParam = searchParams?.get("bp");
const billingPeriod = bpParam === "a" ? ("ANNUALLY" as const) : bpParam === "m" ? ("MONTHLY" as const) : undefined;
const { createTeam, isSubmitting } = useCreateTeam({
redirectBasePath: "/settings/teams/new",
isOnboarding: false,
billingPeriod,
});
const logoRef = useRef<HTMLInputElement>(null);
const [teamName, setTeamName] = useState("");
const [teamSlug, setTeamSlug] = useState("");
const [teamBio, setTeamBio] = useState("");
const [teamLogo, setTeamLogo] = useState<string>("");
const [isSlugValid, setIsSlugValid] = useState(false);
const [isSlugManuallyEdited, setIsSlugManuallyEdited] = useState(false);
// Reset onboarding store when entering the team creation flow from settings
useEffect(() => {
resetOnboardingPreservingPlan();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
useEffect(() => {
setTeamName(teamDetails.name);
setTeamSlug(teamDetails.slug);
setTeamBio(teamDetails.bio);
setTeamLogo(teamBrand.logo || "");
if (teamDetails.slug) {
setIsSlugManuallyEdited(true);
}
}, [teamDetails, teamBrand]);
useEffect(() => {
if (!isSlugManuallyEdited && teamName) {
const slugifiedName = slugify(teamName);
setTeamSlug(slugifiedName);
}
}, [teamName, isSlugManuallyEdited]);
const handleSlugChange = (value: string) => {
setTeamSlug(value);
setIsSlugManuallyEdited(true);
};
const handleLogoChange = (newLogo: string) => {
if (logoRef.current) {
logoRef.current.value = newLogo;
}
setTeamLogo(newLogo);
};
const handleContinue = async (e?: FormEvent) => {
e?.preventDefault();
if (!isSlugValid) {
return;
}
posthog.capture("settings_team_details_continue_clicked", {
has_logo: !!teamLogo,
has_bio: !!teamBio,
});
setTeamDetails({
name: teamName,
slug: teamSlug,
bio: teamBio,
});
setTeamBrand({
logo: teamLogo || null,
});
try {
await createTeam();
} catch (error) {
const message = error instanceof Error ? error.message : t("something_went_wrong");
showToast(message, "error");
}
};
const handleCancel = () => {
posthog.capture("settings_team_details_cancel_clicked");
resetOnboardingPreservingPlan();
router.push("/teams");
};
return (
<OnboardingLayout userEmail={userEmail} currentStep={1} totalSteps={3}>
{/* Left column - Main content */}
<div className="flex h-full w-full flex-col gap-4">
<form onSubmit={handleContinue} className="flex h-full w-full flex-col gap-4">
<OnboardingCard
title={t("create_your_team")}
subtitle={t("team_onboarding_details_subtitle")}
footer={
<div className="flex w-full items-center justify-end gap-4">
<Button
type="button"
color="minimal"
className="rounded-[10px]"
onClick={handleCancel}
disabled={isSubmitting}>
{t("cancel")}
</Button>
<Button
type="submit"
color="primary"
className="rounded-[10px]"
disabled={!isSlugValid || !teamName || !teamSlug || isSubmitting}>
{t("continue")}
</Button>
</div>
}>
<div className="flex h-full w-full flex-col gap-4">
{/* Team Profile Picture */}
<div className="flex w-full flex-col gap-2">
<Label className="text-emphasis text-sm font-medium leading-4">{t("team_logo")}</Label>
<div className="flex flex-row items-center justify-start gap-2 rtl:justify-end">
<div className="relative shrink-0">
<Avatar
size="lg"
imageSrc={teamLogo || undefined}
alt={teamName || "Team"}
className="border-2 border-white"
/>
</div>
<input ref={logoRef} type="hidden" name="logo" id="logo" defaultValue={teamLogo} />
<ImageUploader
target="avatar"
id="team-logo-upload"
buttonMsg={t("upload")}
handleAvatarChange={handleLogoChange}
imageSrc={teamLogo}
/>
</div>
<p className="text-subtle text-xs font-normal leading-3">{t("onboarding_logo_size_hint")}</p>
</div>
{/* Team Name */}
<div className="flex w-full flex-col gap-1.5">
<Label className="text-emphasis mb-0 text-sm font-medium leading-4">{t("team_name")}</Label>
<TextField
noLabel
name="name"
data-testid="team-name-input"
value={teamName}
onChange={(e) => setTeamName(e.target.value)}
placeholder="Acme Inc."
className="border-default h-7 rounded-[10px] border px-2 py-1.5 text-sm"
/>
</div>
{/* Team Slug */}
<ValidatedTeamSlug
value={teamSlug}
onChange={handleSlugChange}
onValidationChange={setIsSlugValid}
/>
{/* Team Bio */}
<div className="flex w-full flex-col gap-1.5">
<Label className="text-emphasis mb-0 text-sm font-medium leading-4">{t("team_bio")}</Label>
<TextArea
value={teamBio}
onChange={(e) => setTeamBio(e.target.value)}
placeholder={t("team_bio_placeholder")}
className="border-default max-h-[150px] min-h-[80px] rounded-[10px] border px-2 py-1.5 text-sm"
rows={3}
/>
</div>
</div>
</OnboardingCard>
</form>
</div>
{/* Right column - Browser view */}
<OnboardingBrowserView teamSlug={teamSlug} name={teamName} bio={teamBio} avatar={teamLogo || null} />
</OnboardingLayout>
);
};
export const LayoutWrapper = ({ children }: { children: React.ReactNode }) => {
return <>{children}</>;
};
export default CreateNewTeamView;
@@ -1,263 +0,0 @@
"use client";
import { useRouter, useSearchParams } from "next/navigation";
import React, { useRef, useState } from "react";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { Button } from "@calcom/ui/components/button";
import { Dialog, DialogContent } from "@calcom/ui/components/dialog";
import { Icon } from "@calcom/ui/components/icon";
import { Logo } from "@calcom/ui/components/logo";
import { showToast } from "@calcom/ui/components/toast";
import { useOnboardingStore, type Invite } from "~/onboarding/store/onboarding-store";
/**
* Parse a CSV line handling quoted fields that may contain commas.
* Example: '"Name, Inc",admin' -> ['Name, Inc', 'admin']
*/
function parseCSVLine(line: string): string[] {
const result: string[] = [];
let current = "";
let inQuotes = false;
for (let i = 0; i < line.length; i++) {
const char = line[i];
if (char === '"') {
inQuotes = !inQuotes;
} else if (char === "," && !inQuotes) {
result.push(current.trim());
current = "";
} else {
current += char;
}
}
result.push(current.trim());
return result;
}
type CSVUploadModalProps = {
isOpen: boolean;
onClose: () => void;
};
export const CSVUploadModal = ({ isOpen, onClose }: CSVUploadModalProps) => {
const { t } = useLocale();
const router = useRouter();
const searchParams = useSearchParams();
const store = useOnboardingStore();
const { setTeamInvites, teamDetails, teamId } = store;
const fileInputRef = useRef<HTMLInputElement>(null);
const [selectedFile, setSelectedFile] = useState<File | null>(null);
const [isUploading, setIsUploading] = useState(false);
const handleFileSelect = (event: React.ChangeEvent<HTMLInputElement>) => {
const file = event.target.files?.[0];
if (file) {
if (!file.name.endsWith(".csv")) {
showToast(t("please_upload_csv_file"), "error");
return;
}
setSelectedFile(file);
}
};
const handleDownloadTemplate = () => {
const headers = ["email", "role"];
const exampleRow = ["[email protected]", "MEMBER"];
const csvContent = [headers.join(","), exampleRow.join(",")].join("\n");
const blob = new Blob([csvContent], { type: "text/csv" });
const url = window.URL.createObjectURL(blob);
const link = document.createElement("a");
link.href = url;
link.download = "team_invite_template.csv";
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
window.URL.revokeObjectURL(url);
showToast(t("template_downloaded"), "success");
};
const handleUpload = async () => {
if (!selectedFile) {
showToast(t("please_select_file"), "error");
return;
}
setIsUploading(true);
try {
const text = await selectedFile.text();
const lines = text.split("\n").filter((line) => line.trim());
if (lines.length < 2) {
showToast(t("csv_file_empty"), "error");
setIsUploading(false);
return;
}
const headers = parseCSVLine(lines[0]).map((h) => h.toLowerCase());
const emailIndex = headers.indexOf("email");
const roleIndex = headers.indexOf("role");
if (emailIndex === -1) {
showToast(t("csv_missing_email_column"), "error");
setIsUploading(false);
return;
}
const parsedInvites = lines
.slice(1)
.map((line) => {
const values = parseCSVLine(line);
return {
email: values[emailIndex]?.trim(),
role: (roleIndex !== -1 ? values[roleIndex]?.trim().toUpperCase() : "MEMBER") as
| "MEMBER"
| "ADMIN",
};
})
.filter((invite) => invite.email && invite.email.length > 0);
if (parsedInvites.length === 0) {
showToast(t("csv_file_empty"), "error");
setIsUploading(false);
return;
}
const invites: Invite[] = parsedInvites.map((invite) => ({
email: invite.email,
team: teamDetails.name,
role: invite.role === "ADMIN" ? "ADMIN" : "MEMBER",
}));
setTeamInvites(invites);
showToast(t("csv_uploaded_successfully", { count: invites.length }), "success");
onClose();
// Navigate to email page to display the invites - use settings path
const teamIdParam = searchParams?.get("teamId") || teamId;
router.push(`/settings/teams/new/invite/email?teamId=${teamIdParam}`);
} catch (error) {
console.error("Error uploading CSV:", error);
showToast(t("error_uploading_csv"), "error");
} finally {
setIsUploading(false);
}
};
const handleClose = () => {
setSelectedFile(null);
if (fileInputRef.current) {
fileInputRef.current.value = "";
}
onClose();
};
return (
<Dialog open={isOpen} onOpenChange={handleClose}>
<DialogContent size="default" className="!p-0">
<div className="flex flex-col gap-4 p-6">
<div className="flex flex-col items-center gap-1">
<Logo className="h-10 w-auto" />
</div>
<div
className="relative mx-auto flex items-center justify-center"
style={{ width: 320, height: 180 }}>
<div
className="from-default to-muted border-subtle flex items-center justify-center rounded-2xl border bg-gradient-to-br p-8 shadow-sm"
style={{ width: 200, height: 150 }}>
{selectedFile ? (
<div className="flex flex-col items-center gap-3">
<div className="from-default to-muted border-subtle flex items-center justify-center rounded-full border bg-gradient-to-b p-4 shadow-sm">
<Icon name="file-text" className="text-emphasis" style={{ width: 32, height: 32 }} />
</div>
<div className="flex flex-col items-center gap-1">
<p className="text-emphasis text-sm font-medium">{selectedFile.name}</p>
<p className="text-subtle text-xs">{(selectedFile.size / 1024).toFixed(2)} KB</p>
</div>
</div>
) : (
<div className="flex flex-col items-center gap-3">
<div className="from-default to-muted border-subtle flex items-center justify-center rounded-full border bg-gradient-to-b p-4 shadow-sm">
<Icon
name="upload"
className="text-emphasis opacity-70"
style={{ width: 32, height: 32 }}
/>
</div>
<p className="text-subtle text-center text-sm">{t("upload_csv_subtitle")}</p>
</div>
)}
</div>
</div>
<div className="mb-2 flex flex-col gap-2 text-center">
<h2 className="font-heading text-emphasis text-2xl leading-none">{t("upload_csv_file")}</h2>
<p className="text-default text-sm leading-normal">{t("upload_csv_description")}</p>
</div>
<div className="mb-2 flex flex-col gap-3">
<div className="bg-cal-muted border-subtle flex items-center gap-3 rounded-lg border p-4">
<div className="from-default to-muted border-subtle flex items-center justify-center rounded-full border bg-gradient-to-b p-2 shadow-sm">
<Icon name="download" className="text-emphasis" style={{ width: 16, height: 16 }} />
</div>
<div className="flex-1">
<p className="text-emphasis text-sm font-medium">{t("need_template")}</p>
<p className="text-subtle text-xs">{t("download_csv_template_description")}</p>
</div>
<Button color="secondary" StartIcon="download" size="sm" onClick={handleDownloadTemplate}>
{t("download_template")}
</Button>
</div>
<div className="bg-cal-muted border-subtle flex items-center gap-3 rounded-lg border p-4">
<div className="from-default to-muted border-subtle flex items-center justify-center rounded-full border bg-gradient-to-b p-2 shadow-sm">
<Icon name="upload" className="text-emphasis" style={{ width: 16, height: 16 }} />
</div>
<div className="flex-1">
<p className="text-emphasis text-sm font-medium">{t("upload_your_file")}</p>
<p className="text-subtle text-xs">
{selectedFile ? selectedFile.name : t("upload_csv_description")}
</p>
</div>
<input
ref={fileInputRef}
type="file"
accept=".csv"
onChange={handleFileSelect}
className="hidden"
/>
<Button
color="secondary"
StartIcon={selectedFile ? "file-text" : "upload"}
size="sm"
onClick={() => fileInputRef.current?.click()}>
{t("choose_file")}
</Button>
</div>
</div>
</div>
<div className="bg-cal-muted border-subtle mt-6 flex items-center justify-between rounded-b-2xl border-t px-8 py-6">
<Button color="minimal" onClick={handleClose} disabled={isUploading}>
{t("cancel")}
</Button>
<Button
color="primary"
onClick={handleUpload}
disabled={!selectedFile || isUploading}
loading={isUploading}>
{t("upload")}
</Button>
</div>
</DialogContent>
</Dialog>
);
};
@@ -1,211 +0,0 @@
"use client";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { trpc } from "@calcom/trpc/react";
import { Button } from "@calcom/ui/components/button";
import { Form } from "@calcom/ui/components/form";
import { showToast } from "@calcom/ui/components/toast";
import { revalidateTeamsList } from "@calcom/web/app/(use-page-wrapper)/(main-nav)/teams/actions";
import { zodResolver } from "@hookform/resolvers/zod";
import { useRouter, useSearchParams } from "next/navigation";
import React, { useEffect } from "react";
import { useFieldArray, useForm } from "react-hook-form";
import { z } from "zod";
import { EmailInviteForm } from "~/onboarding/components/EmailInviteForm";
import { OnboardingCard } from "~/onboarding/components/OnboardingCard";
import { OnboardingLayout } from "~/onboarding/components/OnboardingLayout";
import { OnboardingInviteBrowserView } from "~/onboarding/components/onboarding-invite-browser-view";
import { RoleSelector } from "~/onboarding/components/RoleSelector";
import { useCreateTeam } from "~/onboarding/hooks/useCreateTeam";
import { type InviteRole, useOnboardingStore } from "~/onboarding/store/onboarding-store";
type TeamInviteEmailViewProps = {
userEmail: string;
};
type FormValues = {
invites: {
email: string;
role: InviteRole;
}[];
};
export const TeamInviteEmailView = ({ userEmail }: TeamInviteEmailViewProps) => {
const router = useRouter();
const searchParams = useSearchParams();
const { t, i18n } = useLocale();
const utils = trpc.useUtils();
const store = useOnboardingStore();
const { teamInvites, setTeamInvites, teamDetails, setTeamId, teamId, resetOnboardingPreservingPlan } =
store;
const [inviteRole, setInviteRole] = React.useState<InviteRole>("MEMBER");
const { inviteMembers, isSubmitting } = useCreateTeam({
redirectBasePath: "/settings/teams/new",
skipRedirectAfterInvite: true,
isOnboarding: false,
});
// Read teamId from query params and store it (from payment callback or redirect)
useEffect(() => {
const teamIdParam = searchParams?.get("teamId");
if (teamIdParam && !teamId) {
const parsedTeamId = parseInt(teamIdParam, 10);
if (!isNaN(parsedTeamId)) {
setTeamId(parsedTeamId);
}
}
}, [searchParams, setTeamId, teamId]);
const formSchema = z.object({
invites: z.array(
z.object({
email: z.union([z.literal(""), z.string().email(t("invalid_email_address"))]),
role: z.enum(["MEMBER", "ADMIN"]),
})
),
});
const form = useForm<FormValues>({
resolver: zodResolver(formSchema),
defaultValues: {
invites:
teamInvites.length > 0
? teamInvites.map((inv) => ({ email: inv.email, role: inv.role }))
: [{ email: "", role: inviteRole }],
},
});
const { fields, append, remove } = useFieldArray({
control: form.control,
name: "invites",
});
const handleContinue = async (data: FormValues) => {
const teamIdParam = searchParams?.get("teamId");
const parsedTeamId = !teamId ? parseInt(teamIdParam || "", 10) : teamId;
if (!parsedTeamId) {
console.log("Team ID is missing. Please go back and create your team first.");
showToast(
t("team_id_missing") || "Team ID is missing. Please go back and create your team first.",
"error"
);
return;
}
const invitesWithTeam = data.invites.map((invite) => ({
email: invite.email,
role: invite.role,
team: teamDetails.name,
}));
setTeamInvites(invitesWithTeam);
// Filter out empty emails and invite members
const validInvites = data.invites.filter((invite) => invite.email && invite.email.trim().length > 0);
if (validInvites.length > 0) {
try {
await inviteMembers(
validInvites.map((invite) => ({
email: invite.email,
role: invite.role,
})),
i18n.language
);
// Invalidate both server-side cache and client-side tRPC cache
await revalidateTeamsList();
await utils.viewer.teams.list.invalidate();
resetOnboardingPreservingPlan();
router.replace("/teams");
} catch (error) {
const errorMessage =
error instanceof Error ? error.message : t("something_went_wrong") || "Something went wrong";
showToast(errorMessage, "error");
}
} else {
// No invites, skip to teams page
await revalidateTeamsList();
await utils.viewer.teams.list.invalidate();
resetOnboardingPreservingPlan();
router.replace("/teams");
}
};
const handleSkip = async () => {
setTeamInvites([]);
await revalidateTeamsList();
await utils.viewer.teams.list.invalidate();
resetOnboardingPreservingPlan();
router.replace("/teams");
};
// Watch form values to pass to browser view for real-time updates
const watchedInvites = form.watch("invites");
const hasValidInvites = watchedInvites.some((invite) => {
return invite.email && invite.email.trim().length > 0;
});
return (
<OnboardingLayout userEmail={userEmail} currentStep={3} totalSteps={3}>
{/* Left column - Main content */}
<div className="flex h-full w-full flex-col gap-4">
<Form form={form} handleSubmit={handleContinue} className="flex h-full w-full flex-col gap-4">
<OnboardingCard
title={t("invite")}
subtitle={t("team_invite_subtitle")}
footer={
<div className="flex w-full items-center justify-end gap-4">
<div className="flex items-center gap-2">
<Button
type="button"
color="minimal"
className="rounded-[10px]"
onClick={handleSkip}
disabled={isSubmitting}
data-testid="skip-invite-button">
{t("onboarding_skip_for_now")}
</Button>
<Button
type="submit"
color="primary"
className="rounded-[10px]"
disabled={!hasValidInvites || isSubmitting}
loading={isSubmitting}>
{t("continue")}
</Button>
</div>
</div>
}>
<div className="flex w-full flex-col gap-4 px-1">
<div className="flex w-full flex-col gap-4">
<EmailInviteForm
fields={fields}
append={append}
remove={remove}
defaultRole={inviteRole}
emailPlaceholder="[email protected]"
/>
<RoleSelector
value={inviteRole}
onValueChange={(value) => {
setInviteRole(value);
fields.forEach((_, index) => {
form.setValue(`invites.${index}.role`, value);
});
}}
showInfoBadge
/>
</div>
</div>
</OnboardingCard>
</Form>
</div>
{/* Right column - Browser view */}
<OnboardingInviteBrowserView teamName={teamDetails.name} watchedInvites={watchedInvites} />
</OnboardingLayout>
);
};
@@ -1,128 +0,0 @@
"use client";
import { useRouter, useSearchParams } from "next/navigation";
import posthog from "posthog-js";
import React, { useEffect } from "react";
import { useFlags } from "@calcom/web/modules/feature-flags/hooks/useFlags";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { Button } from "@calcom/ui/components/button";
import { InviteOptions } from "~/onboarding/components/InviteOptions";
import { OnboardingCard } from "~/onboarding/components/OnboardingCard";
import { OnboardingLayout } from "~/onboarding/components/OnboardingLayout";
import { OnboardingInviteBrowserView } from "~/onboarding/components/onboarding-invite-browser-view";
import { useCreateTeam } from "~/onboarding/hooks/useCreateTeam";
import { useOnboardingStore } from "~/onboarding/store/onboarding-store";
import { CSVUploadModal } from "./csv-upload-modal";
type TeamInviteViewProps = {
userEmail: string;
};
export const TeamInviteView = ({ userEmail }: TeamInviteViewProps) => {
const router = useRouter();
const searchParams = useSearchParams();
const { t } = useLocale();
const flags = useFlags();
const store = useOnboardingStore();
const { setTeamInvites, teamDetails, setTeamId, teamId, resetOnboardingPreservingPlan } = store;
const { isSubmitting } = useCreateTeam({
redirectBasePath: "/settings/teams/new",
isOnboarding: false,
});
const [isCSVModalOpen, setIsCSVModalOpen] = React.useState(false);
// Read teamId from query params and store it (from payment callback)
useEffect(() => {
const teamIdParam = searchParams?.get("teamId");
if (teamIdParam) {
const parsedTeamId = parseInt(teamIdParam, 10);
if (!isNaN(parsedTeamId)) {
setTeamId(parsedTeamId);
}
}
}, [searchParams, setTeamId]);
const googleWorkspaceEnabled = flags["google-workspace-directory"];
const handleGoogleWorkspaceConnect = () => {
// TODO: Implement Google Workspace connection
console.log("Connect Google Workspace");
};
const handleInviteViaEmail = () => {
router.push(`/settings/teams/new/invite/email?teamId=${teamId}`);
};
const handleUploadCSV = () => {
setIsCSVModalOpen(true);
};
const handleCopyInviteLink = () => {
// Disabled for now as per requirements
console.log("Copy invite link - disabled");
};
const handleSkip = async () => {
posthog.capture("settings_team_invite_skip_clicked");
setTeamInvites([]);
resetOnboardingPreservingPlan();
// Redirect to teams page after skipping
router.push("/teams");
};
const handleBack = () => {
posthog.capture("settings_team_invite_back_clicked");
router.push("/settings/teams/new");
};
return (
<>
<OnboardingLayout userEmail={userEmail} currentStep={2} totalSteps={3}>
{/* Left column - Main content */}
<div className="flex w-full flex-col gap-4">
<OnboardingCard
title={t("invite")}
subtitle={t("onboarding_invite_subtitle")}
footer={
<div className="flex w-full items-center justify-between gap-4">
<Button
color="minimal"
className="rounded-[10px]"
onClick={handleBack}
disabled={isSubmitting}>
{t("back")}
</Button>
<div className="flex items-center gap-2">
<Button
color="minimal"
className="rounded-[10px]"
onClick={handleSkip}
disabled={isSubmitting}>
{t("onboarding_skip_for_now")}
</Button>
</div>
</div>
}>
<InviteOptions
onInviteViaEmail={handleInviteViaEmail}
onUploadCSV={handleUploadCSV}
onCopyInviteLink={handleCopyInviteLink}
onConnectGoogleWorkspace={googleWorkspaceEnabled ? handleGoogleWorkspaceConnect : undefined}
isSubmitting={isSubmitting}
/>
</OnboardingCard>
</div>
{/* Right column - Browser view */}
<OnboardingInviteBrowserView teamName={teamDetails.name} />
</OnboardingLayout>
{/* CSV Upload Modal */}
<CSVUploadModal isOpen={isCSVModalOpen} onClose={() => setIsCSVModalOpen(false)} />
</>
);
};