🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
refactor(web): Clean up `DeleteOrganizationButton` (#16639)
Ben Bachem4aba8a577f43
diff --git a/web/src/__tests__/organization-settings-pages.clienttest.tsx b/web/src/__tests__/organization-settings-pages.clienttest.tsxindex 51068191c3..5b8292cf2d 100644--- a/web/src/__tests__/organization-settings-pages.clienttest.tsx+++ b/web/src/__tests__/organization-settings-pages.clienttest.tsx@@ -36,9 +36,9 @@ vi.mock("@/src/components/SettingsDangerZone", () => ({}));vi.mock(- "@/src/features/organizations/components/DeleteOrganizationButton",+ "@/src/features/organizations/components/DeleteOrganizationDialogController",() => ({- DeleteOrganizationButton: () => null,+ DeleteOrganizationDialogController: () => null,}),);diff --git a/web/src/features/organizations/components/DeleteOrganizationButton.tsx b/web/src/features/organizations/components/DeleteOrganizationButton.tsxdeleted file mode 100644index 8387cf1d3f..0000000000--- a/web/src/features/organizations/components/DeleteOrganizationButton.tsx+++ /dev/null@@ -1,131 +0,0 @@-/* eslint-disable @repo/no-abstracted-overlay-trigger */-import { Button } from "@/src/components/ui/button";-import {- Dialog,- DialogBody,- DialogContent,- DialogDescription,- DialogFooter,- DialogHeader,- DialogTitle,- DialogTrigger,-} from "@/src/components/ui/dialog";-import {- Form,- FormControl,- FormField,- FormItem,- FormMessage,-} from "@/src/components/ui/form";-import { Input } from "@/src/components/ui/input";-import { api, reportNonTrpcError } from "@/src/utils/api";-import * as z from "zod";-import { useForm } from "react-hook-form";-import { zodResolver } from "@hookform/resolvers/zod";-import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";-import { useQueryOrganization } from "@/src/features/organizations/hooks";-import { useHasOrganizationAccess } from "@/src/features/rbac/utils/checkOrganizationAccess";-import { showSuccessToast } from "@/src/features/notifications/showSuccessToast"; // Import success toast function-import { env } from "@/src/env.mjs";--export function DeleteOrganizationButton() {- const capture = usePostHogClientCapture();-- const organization = useQueryOrganization();- const confirmMessage =- organization?.name.replaceAll(" ", "-").toLowerCase() ?? "organization";-- const formSchema = z.object({- name: z.string().includes(confirmMessage, {- message: `Please confirm with "${confirmMessage}"`,- }),- });-- const hasAccess = useHasOrganizationAccess({- organizationId: organization?.id,- scope: "organization:delete",- });-- const deleteOrganization = api.organizations.delete.useMutation();- const hasProjects = !!organization && organization.projects.length > 0;-- const form = useForm({- resolver: zodResolver(formSchema),- defaultValues: {- name: "",- },- });-- const onSubmit = async () => {- if (!organization || hasProjects) return;- try {- await deleteOrganization.mutateAsync({- orgId: organization.id,- });- capture("organization_settings:delete_organization");- showSuccessToast({- title: "Organization Deleted",- description: "The organization has been successfully deleted.",- });- await new Promise((resolve) => setTimeout(resolve, 5000)); // Delay for 5 seconds- window.location.href = env.NEXT_PUBLIC_BASE_PATH ?? "/"; // Browser reload to refresh jwt- } catch (error) {- // tRPC failures were already classified + toasted by the react-query- // default onError; only report failures of the post-success work here.- reportNonTrpcError(error, "organizations");- }- };-- return (- <Dialog>- <DialogTrigger asChild>- <Button variant="destructive-secondary" disabled={!hasAccess}>- Delete Organization- </Button>- </DialogTrigger>- <DialogContent className="sm:max-w-[425px]">- <DialogHeader>- <DialogTitle className="text-lg font-bold">- Delete Organization- </DialogTitle>- <DialogDescription>- {hasProjects- ? "You can only delete an organization if it has no projects associated with it. Please delete or transfer all projects first. Deleting projects may take a few minutes."- : `To confirm, type "${confirmMessage}" in the input box `}- </DialogDescription>- </DialogHeader>- <Form {...form}>- <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-8">- {!hasProjects && (- <DialogBody>- <FormField- control={form.control}- name="name"- render={({ field }) => (- <FormItem>- <FormControl>- <Input placeholder={confirmMessage} {...field} />- </FormControl>- <FormMessage />- </FormItem>- )}- />- </DialogBody>- )}- <DialogFooter>- <Button- type="submit"- variant="destructive"- loading={deleteOrganization.isPending}- disabled={hasProjects}- className="w-full"- >- Delete Organization- </Button>- </DialogFooter>- </form>- </Form>- </DialogContent>- </Dialog>- );-}diff --git a/web/src/features/organizations/components/DeleteOrganizationDialog.stories.tsx b/web/src/features/organizations/components/DeleteOrganizationDialog.stories.tsxnew file mode 100644index 0000000000..6801fb074d--- /dev/null+++ b/web/src/features/organizations/components/DeleteOrganizationDialog.stories.tsx@@ -0,0 +1,67 @@+import { expect, fn, userEvent, within } from "storybook/test";+import { type ComponentProps } from "react";++import preview from "../../../../.storybook/preview";+import { Dialog, DialogContent } from "@/src/components/ui/dialog";++import { DeleteOrganizationDialogContent } from "./DeleteOrganizationDialogContent";++const defaultArgs = {+ confirmMessage: "acme",+ hasProjects: false,+ isPending: false,+ onConfirm: fn(),+} satisfies ComponentProps<typeof DeleteOrganizationDialogContent>;++const renderDialog = (+ args: ComponentProps<typeof DeleteOrganizationDialogContent>,+) => (+ <Dialog open onOpenChange={fn()}>+ <DialogContent className="sm:max-w-[425px]">+ <DeleteOrganizationDialogContent {...args} />+ </DialogContent>+ </Dialog>+);++const meta = preview.meta({+ component: DeleteOrganizationDialogContent,+});++export default meta;++export const Default = meta.story({+ args: defaultArgs,+ render: renderDialog,+});++export const WithProjects = meta.story({+ args: {+ ...defaultArgs,+ hasProjects: true,+ },+ render: renderDialog,+});++export const Loading = meta.story({+ args: {+ ...defaultArgs,+ isPending: true,+ },+ render: renderDialog,+});++export const ConfirmsDeletion = meta.story({+ name: "(Test) Confirms deletion",+ args: defaultArgs,+ render: renderDialog,+ play: async ({ args, canvasElement }) => {+ const body = within(canvasElement.ownerDocument.body);++ await userEvent.type(body.getByPlaceholderText("acme"), "acme");+ await userEvent.click(+ body.getByRole("button", { name: "Delete Organization" }),+ );++ await expect(args.onConfirm).toHaveBeenCalledOnce();+ },+});diff --git a/web/src/features/organizations/components/DeleteOrganizationDialogContent.tsx b/web/src/features/organizations/components/DeleteOrganizationDialogContent.tsxnew file mode 100644index 0000000000..85604ec681--- /dev/null+++ b/web/src/features/organizations/components/DeleteOrganizationDialogContent.tsx@@ -0,0 +1,97 @@+import { zodResolver } from "@hookform/resolvers/zod";+import * as z from "zod";+import { useForm } from "react-hook-form";++import { Button } from "@/src/components/ui/button";+import {+ DialogBody,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from "@/src/components/ui/dialog";+import {+ Form,+ FormControl,+ FormField,+ FormItem,+ FormMessage,+} from "@/src/components/ui/form";+import { Input } from "@/src/components/ui/input";++export interface DeleteOrganizationDialogContentProps {+ confirmMessage: string;+ hasProjects: boolean;+ isPending: boolean;+ onConfirm: () => void | Promise<void>;+}++export function DeleteOrganizationDialogContent({+ confirmMessage,+ hasProjects,+ isPending,+ onConfirm,+}: DeleteOrganizationDialogContentProps) {+ const formSchema = z.object({+ name: z.string().includes(confirmMessage, {+ message: `Please confirm with "${confirmMessage}"`,+ }),+ });+ const form = useForm({+ resolver: zodResolver(formSchema),+ defaultValues: {+ name: "",+ },+ });++ const onSubmit = () => {+ if (hasProjects) return;+ return onConfirm();+ };++ return (+ <>+ <DialogHeader>+ <DialogTitle className="text-lg font-bold">+ Delete Organization+ </DialogTitle>+ <DialogDescription>+ {hasProjects+ ? "You can only delete an organization if it has no projects associated with it. Please delete or transfer all projects first. Deleting projects may take a few minutes."+ : `To confirm, type "${confirmMessage}" in the input box `}+ </DialogDescription>+ </DialogHeader>+ <Form {...form}>+ <form onSubmit={form.handleSubmit(onSubmit)}>+ {!hasProjects && (+ <DialogBody>+ <FormField+ control={form.control}+ name="name"+ render={({ field }) => (+ <FormItem>+ <FormControl>+ <Input placeholder={confirmMessage} {...field} />+ </FormControl>+ <FormMessage />+ </FormItem>+ )}+ />+ </DialogBody>+ )}+ <DialogFooter>+ <Button+ type="submit"+ variant="destructive"+ loading={isPending}+ disabled={hasProjects}+ className="w-full"+ >+ Delete Organization+ </Button>+ </DialogFooter>+ </form>+ </Form>+ </>+ );+}diff --git a/web/src/features/organizations/components/DeleteOrganizationDialogController.tsx b/web/src/features/organizations/components/DeleteOrganizationDialogController.tsxnew file mode 100644index 0000000000..a19ba21640--- /dev/null+++ b/web/src/features/organizations/components/DeleteOrganizationDialogController.tsx@@ -0,0 +1,78 @@+import { type ReactNode, useState } from "react";++import { Dialog, DialogContent } from "@/src/components/ui/dialog";+import { DeleteOrganizationDialogContent } from "@/src/features/organizations/components/DeleteOrganizationDialogContent";+import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";+import { useQueryOrganization } from "@/src/features/organizations/hooks";+import { useHasOrganizationAccess } from "@/src/features/rbac/utils/checkOrganizationAccess";+import { showSuccessToast } from "@/src/features/notifications/showSuccessToast";+import { api, reportNonTrpcError } from "@/src/utils/api";+import { env } from "@/src/env.mjs";++type DeleteOrganizationDialogControllerProps = {+ children: (control: {+ disabled: { reason: string } | undefined;+ openDialog: () => void;+ }) => ReactNode;+};++export function DeleteOrganizationDialogController({+ children,+}: DeleteOrganizationDialogControllerProps) {+ const [open, setOpen] = useState(false);+ const capture = usePostHogClientCapture();+ const organization = useQueryOrganization();+ const confirmMessage =+ organization?.name.replaceAll(" ", "-").toLowerCase() ?? "organization";+ const hasAccess = useHasOrganizationAccess({+ organizationId: organization?.id,+ scope: "organization:delete",+ });+ const deleteOrganization = api.organizations.delete.useMutation();+ const hasProjects = !!organization && organization.projects.length > 0;++ const disabled = hasAccess+ ? undefined+ : { reason: "You don't have permission to delete this organization." };++ const openDialog = () => {+ if (!hasAccess) return;+ setOpen(true);+ };++ const onSubmit = async () => {+ if (!organization || hasProjects) return;+ try {+ await deleteOrganization.mutateAsync({+ orgId: organization.id,+ });+ capture("organization_settings:delete_organization");+ showSuccessToast({+ title: "Organization Deleted",+ description: "The organization has been successfully deleted.",+ });+ await new Promise((resolve) => setTimeout(resolve, 5000));+ window.location.href = env.NEXT_PUBLIC_BASE_PATH ?? "/";+ } catch (error) {+ // tRPC failures were already classified + toasted by the react-query+ // default onError; only report failures of the post-success work here.+ reportNonTrpcError(error, "organizations");+ }+ };++ return (+ <>+ {children({ disabled, openDialog })}+ <Dialog open={hasAccess && open} onOpenChange={setOpen}>+ <DialogContent className="sm:max-w-[425px]">+ <DeleteOrganizationDialogContent+ confirmMessage={confirmMessage}+ hasProjects={hasProjects}+ isPending={deleteOrganization.isPending}+ onConfirm={onSubmit}+ />+ </DialogContent>+ </Dialog>+ </>+ );+}diff --git a/web/src/pages/organization/[organizationId]/settings/index.tsx b/web/src/pages/organization/[organizationId]/settings/index.tsxindex 33a0014c37..2986f63dec 100644--- a/web/src/pages/organization/[organizationId]/settings/index.tsx+++ b/web/src/pages/organization/[organizationId]/settings/index.tsx@@ -1,13 +1,14 @@import { PagedSettingsContainer } from "@/src/components/PagedSettingsContainer";import Header from "@/src/components/layouts/header";+import { Button } from "@/src/components/ui/button";import { MembershipInvitesPage } from "@/src/features/rbac/components/MembershipInvitesPage";import { MembersTable } from "@/src/features/rbac/components/MembersTable";import { JSONView } from "@/src/components/ui/CodeJsonViewer";import RenameOrganization from "@/src/features/organizations/components/RenameOrganization";+import { DeleteOrganizationDialogController } from "@/src/features/organizations/components/DeleteOrganizationDialogController";import { useQueryOrganization } from "@/src/features/organizations/hooks";import { useRouter } from "next/router";import { SettingsDangerZone } from "@/src/components/SettingsDangerZone";-import { DeleteOrganizationButton } from "@/src/features/organizations/components/DeleteOrganizationButton";import { BillingSettings } from "@/src/ee/features/billing/components/BillingSettings";import { useHasEntitlement, usePlan } from "@/src/features/entitlements/hooks";import ContainerPage from "@/src/components/layouts/container-page";@@ -108,7 +109,19 @@ export const getOrganizationSettingsPages = ({title: "Delete this organization",description:"Once you delete an organization, there is no going back. Please be certain.",- button: <DeleteOrganizationButton />,+ button: (+ <DeleteOrganizationDialogController>+ {({ disabled, openDialog }) => (+ <Button+ variant="destructive-secondary"+ disabled={disabled !== undefined}+ onClick={openDialog}+ >+ Delete Organization+ </Button>+ )}+ </DeleteOrganizationDialogController>+ ),},]}/>