refactor: webhooks (#2896)

* refactor: webhooks workflow

* chore: update delete modal content
This commit is contained in:
Aaryan Khandelwal 2023-11-27 17:15:48 +05:30 committed by sriram veeraghanta
parent 6e940399cb
commit 726f4668e0
29 changed files with 812 additions and 835 deletions

View File

@ -1,30 +1,31 @@
import React, { FC, useState } from "react";
import { useRouter } from "next/router";
import { Dialog, Transition } from "@headlessui/react";
// icons
import { AlertTriangle } from "lucide-react";
// ui
import { Button } from "@plane/ui";
// mobx store
import { useMobxStore } from "lib/mobx/store-provider";
// hooks
import useToast from "hooks/use-toast";
import { useMobxStore } from "lib/mobx/store-provider";
// ui
import { Button } from "@plane/ui";
interface IDeleteWebhook {
isOpen: boolean;
webhook_url: string;
onClose: () => void;
}
export const DeleteWebhookModal: FC<IDeleteWebhook> = (props) => {
const { isOpen, onClose } = props;
// states
const [isDeleting, setIsDeleting] = useState(false);
// router
const router = useRouter();
const { webhook: webhookStore } = useMobxStore();
// toast
const { setToastAlert } = useToast();
const [deleting, setDelete] = useState(false);
// mobx store
const {
webhook: { removeWebhook },
} = useMobxStore();
const { workspaceSlug, webhookId } = router.query;
@ -33,29 +34,27 @@ export const DeleteWebhookModal: FC<IDeleteWebhook> = (props) => {
};
const handleDelete = async () => {
setDelete(true);
if (!workspaceSlug || !webhookId) return;
webhookStore
.remove(workspaceSlug.toString(), webhookId.toString())
setIsDeleting(true);
removeWebhook(workspaceSlug.toString(), webhookId.toString())
.then(() => {
setToastAlert({
title: "Success",
type: "success",
message: "Successfully deleted",
title: "Success!",
message: "Webhook deleted successfully.",
});
router.replace(`/${workspaceSlug}/settings/webhooks/`);
})
.catch((error) => {
console.log(error);
.catch((error) =>
setToastAlert({
title: "Oops!",
type: "error",
message: error?.error,
});
})
.finally(() => {
setDelete(false);
});
title: "Error!",
message: error?.error ?? "Something went wrong. Please try again.",
})
)
.finally(() => setIsDeleting(false));
};
return (
@ -90,23 +89,21 @@ export const DeleteWebhookModal: FC<IDeleteWebhook> = (props) => {
<AlertTriangle className="h-6 w-6 text-red-600" aria-hidden="true" />
</span>
<span className="flex items-center justify-start">
<h3 className="text-xl font-medium 2xl:text-2xl">Delete Webhook</h3>
<h3 className="text-xl font-medium 2xl:text-2xl">Delete webhook</h3>
</span>
</div>
<span>
<p className="text-sm leading-7 text-custom-text-200">
Are you sure you want to delete workspace <span className="break-words font-semibold" />? All of the
data related to the workspace will be permanently removed. This action cannot be undone.
</p>
</span>
<p className="text-sm text-custom-text-200 mt-4">
Are you sure you want to delete this webhook? Future events will not be delivered to this webhook.
This action cannot be undone.
</p>
<div className="flex justify-end gap-2">
<Button variant="neutral-primary" onClick={onClose}>
Cancel
</Button>
<Button variant="danger" type="submit" onClick={handleDelete}>
{deleting ? "Deleting..." : "Delete Webhook"}
<Button variant="danger" onClick={handleDelete} loading={isDeleting}>
{isDeleting ? "Deleting..." : "Delete webhook"}
</Button>
</div>
</Dialog.Panel>

View File

@ -0,0 +1,28 @@
// next
import { useRouter } from "next/router";
import Image from "next/image";
// ui
import { Button } from "@plane/ui";
// assets
import EmptyWebhook from "public/empty-state/web-hook.svg";
export const WebhooksEmptyState = () => {
const router = useRouter();
return (
<div
className={`flex items-center justify-center mx-auto rounded-sm border border-custom-border-200 bg-custom-background-90 py-10 px-16 w-full`}
>
<div className="text-center flex flex-col items-center w-full">
<Image src={EmptyWebhook} className="w-52 sm:w-60" alt="empty" />
<h6 className="text-xl font-semibold mt-6 sm:mt-8 mb-3">No webhooks</h6>
<p className="text-custom-text-300 mb-7 sm:mb-8">
Create webhooks to receive real-time updates and automate actions
</p>
<Button className="flex items-center gap-1.5" onClick={() => router.push(`${router.asPath}/create/`)}>
Add webhook
</Button>
</div>
</div>
);
};

View File

@ -1,33 +0,0 @@
// next
import { useRouter } from "next/router";
import Image from "next/image";
// ui
import { Button } from "@plane/ui";
// assets
import EmptyWebhook from "public/empty-state/web-hook.svg";
export const EmptyWebhooks = () => {
const router = useRouter();
return (
<div className={`flex items-center justify-center mx-auto rounded-sm border border-custom-border-200 bg-custom-background-90 py-10 px-16 w-full`}>
<div className="text-center flex flex-col items-center w-full">
<Image src={EmptyWebhook} className="w-52 sm:w-60" alt="empty" />
<h6 className="text-xl font-semibold mt-6 sm:mt-8 mb-3">No Webhooks</h6>
{
<p className="text-custom-text-300 mb-7 sm:mb-8">
Create webhooks to receive real-time updates and automate actions
</p>
}
<Button
className="flex items-center gap-1.5"
onClick={() => {
router.push(`${router.asPath}/create/`);
}}
>
Add Webhook
</Button>
</div>
</div>
);
};

View File

@ -0,0 +1,48 @@
import { Disclosure, Transition } from "@headlessui/react";
import { ChevronDown, ChevronUp } from "lucide-react";
import { Button } from "@plane/ui";
type Props = {
openDeleteModal: () => void;
};
export const WebhookDeleteSection: React.FC<Props> = (props) => {
const { openDeleteModal } = props;
return (
<Disclosure as="div" className="border-t border-custom-border-200">
{({ open }) => (
<div className="w-full">
<Disclosure.Button as="button" type="button" className="flex items-center justify-between w-full py-4">
<span className="text-lg tracking-tight">Danger zone</span>
{open ? <ChevronUp className="h-5 w-5" /> : <ChevronDown className="h-5 w-5" />}
</Disclosure.Button>
<Transition
show={open}
enter="transition duration-100 ease-out"
enterFrom="transform opacity-0"
enterTo="transform opacity-100"
leave="transition duration-75 ease-out"
leaveFrom="transform opacity-100"
leaveTo="transform opacity-0"
>
<Disclosure.Panel>
<div className="flex flex-col gap-8">
<span className="text-sm tracking-tight">
Once a webhook is deleted, it cannot be restored. Future events will no longer be delivered to this
webhook.
</span>
<div>
<Button variant="danger" onClick={openDeleteModal}>
Delete webhook
</Button>
</div>
</div>
</Disclosure.Panel>
</Transition>
</div>
)}
</Disclosure>
);
};

View File

@ -1,50 +0,0 @@
import { Disclosure, Transition } from "@headlessui/react";
import { ChevronDown, ChevronUp } from "lucide-react";
import { Button } from "@plane/ui";
interface IWebHookEditForm {
setOpenDeleteModal: React.Dispatch<React.SetStateAction<boolean>>;
}
export const WebHookEditForm = ({ setOpenDeleteModal }: IWebHookEditForm) => (
<Disclosure as="div" className="border-t border-custom-border-200">
{({ open }) => (
<div className="w-full">
<Disclosure.Button as="button" type="button" className="flex items-center justify-between w-full py-4">
<span className="text-lg tracking-tight">Danger Zone</span>
{open ? <ChevronUp className="h-5 w-5" /> : <ChevronDown className="h-5 w-5" />}
</Disclosure.Button>
<Transition
show={open}
enter="transition duration-100 ease-out"
enterFrom="transform opacity-0"
enterTo="transform opacity-100"
leave="transition duration-75 ease-out"
leaveFrom="transform opacity-100"
leaveTo="transform opacity-0"
>
<Disclosure.Panel>
<div className="flex flex-col gap-8">
<span className="text-sm tracking-tight">
The danger zone of the workspace delete page is a critical area that requires careful consideration and
attention. When deleting a workspace, all of the data and resources within that workspace will be
permanently removed and cannot be recovered.
</span>
<div>
<Button
variant="danger"
onClick={() => {
setOpenDeleteModal(true);
}}
>
Delete Webhook
</Button>
</div>
</div>
</Disclosure.Panel>
</Transition>
</div>
)}
</Disclosure>
);

View File

@ -0,0 +1,44 @@
// types
import { TWebhookEventTypes } from "types";
type Props = {
value: string;
onChange: (value: TWebhookEventTypes) => void;
};
const WEBHOOK_EVENT_TYPES: { key: TWebhookEventTypes; label: string }[] = [
{
key: "all",
label: "Send me everything",
},
{
key: "individual",
label: "Select individual events",
},
];
export const WebhookOptions: React.FC<Props> = (props) => {
const { value, onChange } = props;
return (
<>
<h6 className="text-sm font-medium">Which events would you like to trigger this webhook?</h6>
<div className="space-y-3">
{WEBHOOK_EVENT_TYPES.map((option) => (
<div key={option.key} className="flex items-center gap-2">
<input
id={option.key}
type="radio"
value={option.key}
checked={value == option.key}
onChange={() => onChange(option.key)}
/>
<label className="text-sm" htmlFor={option.key}>
{option.label}
</label>
</div>
))}
</div>
</>
);
};

View File

@ -0,0 +1,167 @@
import React, { FC, useEffect, useState } from "react";
import { useRouter } from "next/router";
import { Controller, useForm } from "react-hook-form";
import { observer } from "mobx-react-lite";
// mobx store
import { useMobxStore } from "lib/mobx/store-provider";
// hooks
import useToast from "hooks/use-toast";
// components
import {
WebhookIndividualEventOptions,
WebhookInput,
WebhookOptions,
WebhookSecretKey,
WebhookToggle,
getCurrentHookAsCSV,
} from "components/web-hooks";
// ui
import { Button } from "@plane/ui";
// helpers
import { csvDownload } from "helpers/download.helper";
// types
import { IWebhook, TWebhookEventTypes } from "types";
type Props = {
data?: Partial<IWebhook>;
};
const initialWebhookPayload: Partial<IWebhook> = {
cycle: true,
issue: true,
issue_comment: true,
module: true,
project: true,
url: "",
};
export const WebhookForm: FC<Props> = observer((props) => {
const { data } = props;
// states
const [webhookEventType, setWebhookEventType] = useState<TWebhookEventTypes>("all");
// router
const router = useRouter();
const { workspaceSlug } = router.query;
// toast
const { setToastAlert } = useToast();
// mobx store
const {
webhook: { createWebhook, updateWebhook },
workspace: { currentWorkspace },
} = useMobxStore();
// use form
const {
handleSubmit,
control,
formState: { isSubmitting, errors },
} = useForm<IWebhook>({
defaultValues: { ...initialWebhookPayload, ...data },
});
const handleCreateWebhook = async (formData: IWebhook) => {
if (!workspaceSlug) return;
let payload: Partial<IWebhook> = {
url: formData.url,
};
if (webhookEventType === "all")
payload = {
...payload,
project: true,
cycle: true,
module: true,
issue: true,
issue_comment: true,
};
else
payload = {
...payload,
project: formData.project ?? false,
cycle: formData.cycle ?? false,
module: formData.module ?? false,
issue: formData.issue ?? false,
issue_comment: formData.issue_comment ?? false,
};
await createWebhook(workspaceSlug.toString(), payload)
.then(({ webHook, secretKey }) => {
setToastAlert({
type: "success",
title: "Success!",
message: "Webhook created successfully.",
});
const csvData = getCurrentHookAsCSV(currentWorkspace, webHook, secretKey);
csvDownload(csvData, `webhook-secret-key-${Date.now()}`);
if (webHook && webHook.id)
router.push({ pathname: `/${workspaceSlug}/settings/webhooks/${webHook.id}`, query: { isCreated: true } });
})
.catch((error) => {
setToastAlert({
type: "error",
title: "Error!",
message: error?.error ?? "Something went wrong. Please try again.",
});
});
};
const handleUpdateWebhook = async (formData: IWebhook) => {
if (!workspaceSlug || !data || !data.id) return;
const payload = {
url: formData?.url,
is_active: formData?.is_active,
project: formData?.project,
cycle: formData?.cycle,
module: formData?.module,
issue: formData?.issue,
issue_comment: formData?.issue_comment,
};
return await updateWebhook(workspaceSlug.toString(), data.id, payload);
};
const handleFormSubmit = async (formData: IWebhook) => {
if (data) await handleUpdateWebhook(formData);
else await handleCreateWebhook(formData);
};
useEffect(() => {
if (!data) return;
if (data.project && data.cycle && data.module && data.issue && data.issue_comment) setWebhookEventType("all");
else setWebhookEventType("individual");
}, [data]);
return (
<div className="space-y-6">
<div className="text-xl font-medium">{data ? "Webhook details" : "Create webhook"}</div>
<form className="space-y-8" onSubmit={handleSubmit(handleFormSubmit)}>
<div>
<Controller
control={control}
name="url"
rules={{
required: "URL is required",
}}
render={({ field: { onChange, value } }) => (
<WebhookInput value={value} onChange={onChange} hasError={Boolean(errors.url)} />
)}
/>
{errors.url && <div className="text-xs text-red-500">{errors.url.message}</div>}
</div>
{data && <WebhookToggle control={control} />}
<div className="space-y-3">
<WebhookOptions value={webhookEventType} onChange={(val) => setWebhookEventType(val)} />
</div>
{webhookEventType === "individual" && <WebhookIndividualEventOptions control={control} />}
{data && <WebhookSecretKey data={data} />}
<Button type="submit" loading={isSubmitting}>
{data ? (isSubmitting ? "Updating..." : "Update") : isSubmitting ? "Creating..." : "Create"}
</Button>
</form>
</div>
);
});

View File

@ -1,139 +0,0 @@
import { useState, FC } from "react";
import { useRouter } from "next/router";
import { Button } from "@plane/ui";
import { Copy, Eye, EyeOff, RefreshCw } from "lucide-react";
import { observer } from "mobx-react-lite";
// hooks
import useToast from "hooks/use-toast";
// store
import { RootStore } from "store/root";
import { useMobxStore } from "lib/mobx/store-provider";
// helpers
import { copyTextToClipboard } from "helpers/string.helper";
import { csvDownload } from "helpers/download.helper";
// utils
import { getCurrentHookAsCSV } from "../utils";
// enum
import { WebHookFormTypes } from "./index";
interface IGenerateKey {
type: WebHookFormTypes.CREATE | WebHookFormTypes.EDIT;
}
export const GenerateKey: FC<IGenerateKey> = observer((props) => {
const { type } = props;
// states
const [regenerating, setRegenerate] = useState(false);
const [shouldShowKey, setShouldShowKey] = useState(false);
// router
const router = useRouter();
const { workspaceSlug, webhookId } = router.query as { workspaceSlug: string; webhookId: string };
// store
const { webhook: webhookStore, workspace: workspaceStore }: RootStore = useMobxStore();
// hooks
const { setToastAlert } = useToast();
const handleCopySecret = () => {
if (webhookStore?.webhookSecretKey) {
copyTextToClipboard(webhookStore.webhookSecretKey);
setToastAlert({
title: "Success",
type: "success",
message: "Secret key copied",
});
} else {
setToastAlert({
title: "Oops",
type: "error",
message: "Error occurred while copying secret key",
});
}
};
function handleRegenerate() {
setRegenerate(true);
webhookStore
.regenerate(workspaceSlug, webhookId)
.then(() => {
setToastAlert({
title: "Success",
type: "success",
message: "Successfully regenerated",
});
const csvData = getCurrentHookAsCSV(
workspaceStore.currentWorkspace,
webhookStore.currentWebhook,
webhookStore.webhookSecretKey
);
csvDownload(csvData, `Secret-key-${Date.now()}`);
})
.catch((err) => {
setToastAlert({
title: "Oops!",
type: "error",
message: err?.error,
});
})
.finally(() => {
setRegenerate(false);
});
}
const toggleShowKey = () => {
setShouldShowKey((prevState) => !prevState);
};
const icons = [
{ Component: Copy, onClick: handleCopySecret, key: "copy" },
{ Component: shouldShowKey ? EyeOff : Eye, onClick: toggleShowKey, key: "eye" },
];
return (
<>
{(type === WebHookFormTypes.EDIT || (type === WebHookFormTypes.CREATE && webhookStore?.webhookSecretKey)) && (
<div className="space-y-2">
<div className="text-sm font-medium">Secret Key</div>
<div className="text-sm text-neutral-400">Genarate a token to sign-in the webhook payload</div>
<div className="flex gap-5 items-center">
<div className="relative flex items-center p-2 rounded w-full border border-custom-border-200">
<div className="flex w-full overflow-hidden h-7 px-2 font-medium select-none">
{webhookStore?.webhookSecretKey && shouldShowKey ? (
<div>{webhookStore?.webhookSecretKey}</div>
) : (
<div className="flex items-center gap-1.5">
{[...Array(41)].map((_, index) => (
<div key={index} className="w-[4px] h-[4px] bg-gray-300 rounded-full" />
))}
</div>
)}
</div>
{webhookStore?.webhookSecretKey && (
<>
{icons.map(({ Component, onClick, key }) => (
<div
className="w-7 h-7 flex-shrink-0 flex justify-center items-center cursor-pointer hover:bg-custom-background-80 rounded"
onClick={onClick}
key={key}
>
<Component className="text-custom-text-400 w-4 h-4" />
</div>
))}
</>
)}
</div>
<div>
{type != WebHookFormTypes.CREATE && (
<Button disabled={regenerating} onClick={handleRegenerate} variant="accent-primary" className="">
<RefreshCw className={`h-3 w-3`} />
{regenerating ? "Re-generating..." : "Re-genarate Key"}
</Button>
)}
</div>
</div>
</div>
)}
</>
);
});

View File

@ -0,0 +1,7 @@
export * from "./delete-section";
export * from "./event-types";
export * from "./form";
export * from "./individual-event-options";
export * from "./input";
export * from "./secret-key";
export * from "./toggle";

View File

@ -1,102 +0,0 @@
import React, { FC, useEffect, useState } from "react";
import { useForm } from "react-hook-form";
import { IWebhook, IExtendedWebhook } from "types";
import { GenerateKey } from "./generate-key";
import { observer } from "mobx-react-lite";
// components
import { DeleteWebhookModal } from "../delete-webhook-modal";
import { WebHookInput } from "./input";
import { WebHookToggle } from "./toggle";
import { WEBHOOK_EVENTS, WebHookOptions, WebhookTypes } from "./options";
import { WebHookIndividualOptions, individualWebhookOptions } from "./option";
import { WebHookSubmitButton } from "./submit";
import { WebHookEditForm } from "./edit-form";
export enum WebHookFormTypes {
EDIT = "edit",
CREATE = "create",
}
interface IWebHookForm {
type: WebHookFormTypes;
initialData: IWebhook;
onSubmit: (val: IExtendedWebhook) => void;
}
export const WebHookForm: FC<IWebHookForm> = observer((props) => {
const { type, initialData, onSubmit } = props;
// states
const [openDeleteModal, setOpenDeleteModal] = useState(false);
// use form
const {
reset,
watch,
handleSubmit,
control,
getValues,
formState: { isSubmitting, errors },
} = useForm<IExtendedWebhook>();
const checkWebhookEvent = (initialData: IWebhook) => {
const { project, module, cycle, issue, issue_comment } = initialData;
if (!project || !cycle || !module || !issue || !issue_comment) {
return WebhookTypes.INDIVIDUAL;
}
return WebhookTypes.ALL;
};
useEffect(() => {
if (initialData && reset) reset({ ...initialData, webhook_events: checkWebhookEvent(initialData) });
}, [initialData, reset]);
useEffect(() => {
if (!watch(WEBHOOK_EVENTS)) return;
const allWebhookOptions: { [key: string]: boolean } = {};
/**For Webhooks to return all the types */
if (watch(WEBHOOK_EVENTS) === WebhookTypes.ALL) {
individualWebhookOptions.forEach(({ name }) => {
allWebhookOptions[name] = true;
});
} /**For Webhooks to return selected individual types, retain the saved individual types */ else if (
watch(WEBHOOK_EVENTS) === WebhookTypes.INDIVIDUAL
) {
individualWebhookOptions.forEach(({ name }) => {
if (initialData[name] !== undefined) {
allWebhookOptions[name] = initialData[name]!;
} else {
allWebhookOptions[name] = true;
}
});
}
reset({ ...getValues(), ...allWebhookOptions });
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [watch && watch(WEBHOOK_EVENTS)]);
return (
<>
<DeleteWebhookModal
isOpen={openDeleteModal}
webhook_url=""
onClose={() => {
setOpenDeleteModal(false);
}}
/>
<form onSubmit={handleSubmit(onSubmit)}>
<div className="space-y-8 py-5">
<WebHookInput control={control} errors={errors} />
<WebHookToggle control={control} />
<div className="space-y-3">
<WebHookOptions control={control} />
{watch(WEBHOOK_EVENTS) === WebhookTypes.INDIVIDUAL && <WebHookIndividualOptions control={control} />}
</div>
<GenerateKey type={type} />
<WebHookSubmitButton isSubmitting={isSubmitting} type={type} />
{type === WebHookFormTypes.EDIT && <WebHookEditForm setOpenDeleteModal={setOpenDeleteModal} />}
</div>
</form>
</>
);
});

View File

@ -0,0 +1,69 @@
import { Control, Controller } from "react-hook-form";
import { IWebhook } from "types/webhook";
export const individualWebhookOptions: {
key: keyof IWebhook;
label: string;
description: string;
}[] = [
{
key: "project",
label: "Projects",
description: "Project created, updated or deleted.",
},
{
key: "cycle",
label: "Cycles",
description: "Cycle created, updated or deleted.",
},
{
key: "issue",
label: "Issues",
description: "Issue created, updated, deleted, added to a cycle or module.",
},
{
key: "module",
label: "Modules",
description: "Module created, updated or deleted.",
},
{
key: "issue_comment",
label: "Issue comments",
description: "Comment posted, updated or deleted.",
},
];
type Props = {
control: Control<IWebhook, any>;
};
export const WebhookIndividualEventOptions = ({ control }: Props) => (
<>
<div className="grid grid-cols-1 lg:grid-cols-2 gap-x-4 gap-y-8 px-6 mt-5">
{individualWebhookOptions.map((option) => (
<Controller
key={option.key}
control={control}
name={option.key}
render={({ field: { onChange, value } }) => (
<div>
<div className="flex items-center gap-2">
<input
id={option.key}
onChange={() => onChange(!value)}
type="checkbox"
name="selectIndividualEvents"
checked={value === true}
/>
<label className="text-sm" htmlFor={option.key}>
{option.label}
</label>
</div>
<p className="text-xs text-custom-text-300 ml-6 mt-0.5">{option.description}</p>
</div>
)}
/>
))}
</div>
</>
);

View File

@ -1,33 +1,26 @@
import { Control, Controller, FieldErrors } from "react-hook-form";
import { Input } from "@plane/ui";
import { IExtendedWebhook } from "types/webhook";
interface IWebHookInput {
control: Control<IExtendedWebhook, any>;
errors: FieldErrors<IExtendedWebhook>;
}
type Props = {
value: string;
onChange: (value: string) => void;
hasError: boolean;
};
export const WebhookInput: React.FC<Props> = (props) => {
const { value, onChange, hasError } = props;
export const WebHookInput = ({ control, errors }: IWebHookInput) => (
<div>
<div className="font-medium text-sm">URL</div>
<Controller
control={control}
name="url"
rules={{
required: "URL is Required",
validate: (value) => (/^(ftp|http|https):\/\/[^ "]+$/.test(value) ? true : "Enter a valid URL"),
}}
render={({ field: { onChange, value } }) => (
<Input
className="w-full h-11"
onChange={onChange}
value={value}
id="url"
autoComplete="off"
placeholder="Enter URL"
/>
)}
/>
{errors.url && <p className="py-2 text-sm text-red-500">{errors.url.message}</p>}
</div>
);
return (
<>
<h6 className="font-medium text-sm">Payload URL</h6>
<Input
type="url"
className="w-full h-11"
onChange={(e) => onChange(e.target.value)}
value={value}
autoComplete="off"
hasError={hasError}
placeholder="https://example.com/post"
autoFocus
/>
</>
);
};

View File

@ -1,70 +0,0 @@
import { Control, Controller } from "react-hook-form";
import { IWebhookIndividualOptions, IExtendedWebhook } from "types/webhook";
export enum IndividualWebhookTypes {
PROJECTS = "Projects",
MODULES = "Modules",
CYCLES = "Cycles",
ISSUES = "Issues",
ISSUE_COMMENTS = "Issue Comments",
}
export const individualWebhookOptions: IWebhookIndividualOptions[] = [
{
key: "project_toggle",
label: IndividualWebhookTypes.PROJECTS,
name: "project",
},
{
key: "cycle-toggle",
label: IndividualWebhookTypes.CYCLES,
name: "cycle",
},
{
key: "issue_toggle",
label: IndividualWebhookTypes.ISSUES,
name: "issue",
},
{
key: "module_toggle",
label: IndividualWebhookTypes.MODULES,
name: "module",
},
{
key: "issue_comment_toggle",
label: IndividualWebhookTypes.ISSUE_COMMENTS,
name: "issue_comment",
},
];
interface IWebHookIndividualOptions {
control: Control<IExtendedWebhook, any>;
}
export const WebHookIndividualOptions = ({ control }: IWebHookIndividualOptions) => (
<>
<div className="grid grid-cols-2 md:grid-cols-3 grid-flow-row gap-4 px-8 py-6 bg-custom-background-90">
{individualWebhookOptions.map(({ key, label, name }: IWebhookIndividualOptions) => (
<Controller
control={control}
name={name}
key={key}
render={({ field: { onChange, value } }) => (
<div className="relative flex items-center gap-2">
<input
id={key}
onChange={() => onChange(!value)}
type="checkbox"
name="selectIndividualEvents"
checked={value == true}
/>
<label className="text-sm" htmlFor={key}>
{label}
</label>
</div>
)}
/>
))}
</div>
</>
);

View File

@ -1,54 +0,0 @@
import { Control, Controller } from "react-hook-form";
import { IExtendedWebhook, IWebhookOptions } from "types/webhook";
export enum WebhookTypes {
ALL = "all",
INDIVIDUAL = "individual",
}
interface IWebHookOptionsProps {
control: Control<IExtendedWebhook, any>;
}
export const WEBHOOK_EVENTS = "webhook_events";
const webhookOptions: IWebhookOptions[] = [
{
key: WebhookTypes.ALL,
label: "Send everything",
name: WEBHOOK_EVENTS,
},
{
key: WebhookTypes.INDIVIDUAL,
label: "Select Individual events",
name: WEBHOOK_EVENTS,
},
];
export const WebHookOptions = ({ control }: IWebHookOptionsProps) => (
<>
<div className="text-sm font-medium">Which events do you like to trigger this webhook</div>
{webhookOptions.map(({ key, label, name }: IWebhookOptions) => (
<div className="flex items-center gap-2">
<Controller
control={control}
name={name}
key={key}
render={({ field: { onChange, value } }) => (
<input
id={key}
type="radio"
name={name}
value={key}
checked={value == key}
onChange={() => onChange(key)}
/>
)}
/>
<label className="text-sm" htmlFor={key}>
{label}
</label>
</div>
))}
</>
);

View File

@ -0,0 +1,135 @@
import { useState, FC } from "react";
import { useRouter } from "next/router";
import { Button, Tooltip } from "@plane/ui";
import { Copy, Eye, EyeOff, RefreshCw } from "lucide-react";
import { observer } from "mobx-react-lite";
// hooks
import useToast from "hooks/use-toast";
// store
import { useMobxStore } from "lib/mobx/store-provider";
// helpers
import { copyTextToClipboard } from "helpers/string.helper";
import { csvDownload } from "helpers/download.helper";
// utils
import { getCurrentHookAsCSV } from "../utils";
// types
import { IWebhook } from "types";
type Props = {
data: Partial<IWebhook>;
};
export const WebhookSecretKey: FC<Props> = observer((props) => {
const { data } = props;
// states
const [isRegenerating, setIsRegenerating] = useState(false);
const [shouldShowKey, setShouldShowKey] = useState(false);
// router
const router = useRouter();
const { workspaceSlug, webhookId } = router.query;
// store
const {
webhook: { currentWebhook, regenerateSecretKey, webhookSecretKey },
workspace: { currentWorkspace },
} = useMobxStore();
// hooks
const { setToastAlert } = useToast();
const handleCopySecretKey = () => {
if (!webhookSecretKey) return;
copyTextToClipboard(webhookSecretKey)
.then(() =>
setToastAlert({
type: "success",
title: "Success!",
message: "Secret key copied to clipboard.",
})
)
.catch(() =>
setToastAlert({
type: "error",
title: "Error!",
message: "Error occurred while copying secret key.",
})
);
};
const handleRegenerateSecretKey = () => {
if (!workspaceSlug || !webhookId) return;
setIsRegenerating(true);
regenerateSecretKey(workspaceSlug.toString(), webhookId.toString())
.then(() => {
setToastAlert({
type: "success",
title: "Success!",
message: "New key regenerated successfully.",
});
const csvData = getCurrentHookAsCSV(currentWorkspace, currentWebhook, webhookSecretKey);
csvDownload(csvData, `webhook-secret-key-${Date.now()}`);
})
.catch((err) =>
setToastAlert({
type: "error",
title: "Error!",
message: err?.error ?? "Something went wrong. Please try again.",
})
)
.finally(() => setIsRegenerating(false));
};
const toggleShowKey = () => setShouldShowKey((prevState) => !prevState);
const SECRET_KEY_OPTIONS = [
{ label: "View secret key", Icon: shouldShowKey ? EyeOff : Eye, onClick: toggleShowKey, key: "eye" },
{ label: "Copy secret key", Icon: Copy, onClick: handleCopySecretKey, key: "copy" },
];
return (
<>
{(data || webhookSecretKey) && (
<div className="space-y-2">
<div className="text-sm font-medium">Secret key</div>
<div className="text-xs text-custom-text-400">Generate a token to sign-in to the webhook payload</div>
<div className="flex items-center gap-4">
<div className="self-stretch flex items-center justify-between py-1.5 px-2 rounded min-w-[30rem] max-w-lg border border-custom-border-200">
<div className="overflow-hidden font-medium select-none">
{shouldShowKey ? (
<p className="text-xs">{webhookSecretKey}</p>
) : (
<div className="flex items-center gap-1.5">
{[...Array(30)].map((_, index) => (
<div key={index} className="w-1 h-1 bg-custom-text-400 rounded-full" />
))}
</div>
)}
</div>
{webhookSecretKey && (
<div className="flex items-center gap-2">
{SECRET_KEY_OPTIONS.map((option) => (
<Tooltip key={option.key} tooltipContent={option.label}>
<button type="button" className="flex-shrink-0 grid place-items-center" onClick={option.onClick}>
<option.Icon className="text-custom-text-400 h-3 w-3" />
</button>
</Tooltip>
))}
</div>
)}
</div>
{data && (
<div>
<Button onClick={handleRegenerateSecretKey} variant="accent-primary" loading={isRegenerating}>
<RefreshCw className="h-3 w-3" />
{isRegenerating ? "Re-generating..." : "Re-generate key"}
</Button>
</div>
)}
</div>
</div>
)}
</>
);
});

View File

@ -1,13 +0,0 @@
import { Button } from "@plane/ui";
import { WebHookFormTypes } from "./index";
interface IWebHookSubmitButton {
isSubmitting: boolean;
type: WebHookFormTypes;
}
export const WebHookSubmitButton = ({ isSubmitting, type }: IWebHookSubmitButton) => (
<Button type="submit" disabled={isSubmitting}>
{isSubmitting ? "processing..." : type === "create" ? "Create webhook" : "Save webhook"}
</Button>
);

View File

@ -1,14 +1,16 @@
import { Control, Controller } from "react-hook-form";
import { IExtendedWebhook } from "types/webhook";
// ui
import { ToggleSwitch } from "@plane/ui";
// types
import { IWebhook } from "types/webhook";
interface IWebHookToggle {
control: Control<IExtendedWebhook, any>;
control: Control<IWebhook, any>;
}
export const WebHookToggle = ({ control }: IWebHookToggle) => (
export const WebhookToggle = ({ control }: IWebHookToggle) => (
<div className="flex gap-6">
<div className="text-sm"> Enable webhook </div>
<div className="text-sm font-medium">Enable webhook</div>
<Controller
control={control}
name="is_active"

View File

@ -1,4 +1,6 @@
export * from "./empty-webhooks";
export * from "./webhooks-list";
export * from "./webhooks-list-item";
export * from "./form";
export * from "./delete-webhook-modal";
export * from "./empty-state";
export * from "./utils";
export * from "./webhooks-list-item";
export * from "./webhooks-list";

View File

@ -1,41 +1,40 @@
import { FC } from "react";
import { ToggleSwitch } from "@plane/ui";
import Link from "next/link";
import { RootStore } from "store/root";
import { useRouter } from "next/router";
// mobx store
import { useMobxStore } from "lib/mobx/store-provider";
// ui
import { ToggleSwitch } from "@plane/ui";
// types
import { IWebhook } from "types";
interface IWebhookListItem {
workspaceSlug: string;
webhook: IWebhook;
}
export const WebhooksListItem: FC<IWebhookListItem> = (props) => {
const { workspaceSlug, webhook } = props;
const { webhook } = props;
// router
const router = useRouter();
const { workspaceSlug } = router.query;
const { webhook: webhookStore }: RootStore = useMobxStore();
const {
webhook: { updateWebhook },
} = useMobxStore();
const handleToggle = () => {
if (webhook.id) {
webhookStore.update(workspaceSlug, webhook.id, { ...webhook, is_active: !webhook.is_active }).catch(() => {});
}
if (!workspaceSlug || !webhook.id) return;
updateWebhook(workspaceSlug.toString(), webhook.id, { is_active: !webhook.is_active });
};
return (
<div>
<div className="border-b border-custom-border-200">
<Link href={`/${workspaceSlug}/settings/webhooks/${webhook?.id}`}>
<div className="flex cursor-pointer justify-between px-3.5 py-[18px]">
<div>
<div className="text-base font-medium">{webhook?.url || "Webhook URL"}</div>
{/* <div className="text-base text-neutral-700">
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor
</div> */}
</div>
<div className="flex gap-4 items-center">
<ToggleSwitch value={webhook.is_active} onChange={handleToggle} />
</div>
</div>
<a className="flex items-center justify-between gap-4 px-3.5 py-[18px]">
<h5 className="text-base font-medium truncate">{webhook.url}</h5>
<ToggleSwitch value={webhook.is_active} onChange={handleToggle} />
</a>
</Link>
</div>
);

View File

@ -1,38 +1,19 @@
import { FC } from "react";
import Link from "next/link";
import { Button } from "@plane/ui";
import { useMobxStore } from "lib/mobx/store-provider";
import { RootStore } from "store/root";
import { observer } from "mobx-react-lite";
// mobx store
import { useMobxStore } from "lib/mobx/store-provider";
// components
import { WebhooksListItem } from "./webhooks-list-item";
interface IWebHookLists {
workspaceSlug: string;
}
export const WebhookLists: FC<IWebHookLists> = observer((props) => {
const { workspaceSlug } = props;
export const WebhooksList = observer(() => {
const {
webhook: { webhooks },
}: RootStore = useMobxStore();
} = useMobxStore();
return (
<>
<div className="flex items-center justify-between gap-4 py-3.5 border-b border-custom-border-200">
<div className="text-xl font-medium">Webhooks</div>
<Link href={`/${workspaceSlug}/settings/webhooks/create`}>
<Button variant="primary" size="sm">
Add webhook
</Button>
</Link>
</div>
<div className="divide-y divide-custom-border-200 overflow-y-scroll">
{Object.values(webhooks).map((item) => (
<WebhooksListItem workspaceSlug={workspaceSlug} webhook={item} key={item.id} />
))}
</div>
</>
<div className="h-full w-full overflow-y-auto">
{Object.values(webhooks ?? {}).map((webhook) => (
<WebhooksListItem key={webhook.id} webhook={webhook} />
))}
</div>
);
});

View File

@ -50,7 +50,7 @@ export const WorkspaceSettingsSidebar = () => {
{
label: "Exports",
href: `/${workspaceSlug}/settings/exports`,
access: EUserWorkspaceRoles.ADMIN,
access: EUserWorkspaceRoles.MEMBER,
},
{
label: "Webhooks",

View File

@ -16,7 +16,7 @@ const StoreWrapper: FC<IStoreWrapper> = observer((props) => {
const { children } = props;
// router
const router = useRouter();
const { workspaceSlug, projectId, cycleId, moduleId, globalViewId, viewId, inboxId } = router.query;
const { workspaceSlug, projectId, cycleId, moduleId, globalViewId, viewId, inboxId, webhookId } = router.query;
// store
const {
theme: { sidebarCollapsed, toggleSidebar },
@ -28,6 +28,7 @@ const StoreWrapper: FC<IStoreWrapper> = observer((props) => {
globalViews: { setGlobalViewId },
projectViews: { setViewId },
inbox: { setInboxId },
webhook: { setCurrentWebhookId },
appConfig: { fetchAppConfig },
} = useMobxStore();
// fetching application Config
@ -74,6 +75,7 @@ const StoreWrapper: FC<IStoreWrapper> = observer((props) => {
setGlobalViewId(globalViewId?.toString() ?? null);
setViewId(viewId?.toString() ?? null);
setInboxId(inboxId?.toString() ?? null);
setCurrentWebhookId(webhookId?.toString() ?? undefined);
}, [
workspaceSlug,
projectId,
@ -82,6 +84,7 @@ const StoreWrapper: FC<IStoreWrapper> = observer((props) => {
globalViewId,
viewId,
inboxId,
webhookId,
setWorkspaceSlug,
setProjectId,
setCycleId,
@ -89,6 +92,7 @@ const StoreWrapper: FC<IStoreWrapper> = observer((props) => {
setGlobalViewId,
setViewId,
setInboxId,
setCurrentWebhookId,
]);
return <>{children}</>;

View File

@ -31,12 +31,13 @@ const ApiTokensPage: NextPageWithLayout = observer(() => {
user: { currentWorkspaceRole },
} = useMobxStore();
const { data: tokens } = useSWR(
workspaceSlug && currentWorkspaceRole === 20 ? API_TOKENS_LIST(workspaceSlug.toString()) : null,
() => (workspaceSlug && currentWorkspaceRole === 20 ? apiTokenService.getApiTokens(workspaceSlug.toString()) : null)
const isAdmin = currentWorkspaceRole === 20;
const { data: tokens } = useSWR(workspaceSlug && isAdmin ? API_TOKENS_LIST(workspaceSlug.toString()) : null, () =>
workspaceSlug && isAdmin ? apiTokenService.getApiTokens(workspaceSlug.toString()) : null
);
if (currentWorkspaceRole !== 20)
if (!isAdmin)
return (
<div className="h-full w-full flex justify-center mt-10 p-4">
<p className="text-custom-text-300 text-sm">You are not authorized to access this page.</p>

View File

@ -1,77 +1,76 @@
import type { NextPage } from "next";
import { useEffect, useState } from "react";
import { useRouter } from "next/router";
import useSWR from "swr";
import { observer } from "mobx-react-lite";
// layout
import useSWR from "swr";
// mobx store
import { useMobxStore } from "lib/mobx/store-provider";
// layouts
import { AppLayout } from "layouts/app-layout";
import { WorkspaceSettingLayout } from "layouts/settings-layout";
// components
import { WorkspaceSettingHeader } from "components/headers";
import { WebHookForm } from "components/web-hooks";
// hooks
import { useMobxStore } from "lib/mobx/store-provider";
// types
import { RootStore } from "store/root";
import { IExtendedWebhook, IWebhook } from "types";
import { DeleteWebhookModal, WebhookDeleteSection, WebhookForm } from "components/web-hooks";
// ui
import { Spinner } from "@plane/ui";
import { useEffect } from "react";
import { WebHookFormTypes } from "components/web-hooks/form";
// types
import { NextPageWithLayout } from "types/app";
const Webhooks: NextPage = observer(() => {
const WebhookDetailsPage: NextPageWithLayout = observer(() => {
// states
const [deleteWebhookModal, setDeleteWebhookModal] = useState(false);
// router
const router = useRouter();
const { workspaceSlug, webhookId, isCreated } = router.query as {
workspaceSlug: string;
webhookId: string;
isCreated: string;
};
const { webhook: webhookStore }: RootStore = useMobxStore();
const { workspaceSlug, webhookId, isCreated } = router.query;
// mobx store
const {
webhook: { currentWebhook, clearSecretKey, fetchWebhookById },
user: { currentWorkspaceRole },
} = useMobxStore();
useEffect(() => {
if (isCreated !== "true") {
webhookStore.clearSecretKey();
}
}, []);
if (isCreated !== "true") clearSecretKey();
}, [clearSecretKey, isCreated]);
const { isLoading } = useSWR(
workspaceSlug && webhookId ? `WEBHOOKS_DETAIL_${workspaceSlug}_${webhookId}` : null,
workspaceSlug && webhookId
? async () => {
await webhookStore.fetchById(workspaceSlug, webhookId);
}
const isAdmin = currentWorkspaceRole === 20;
useSWR(
workspaceSlug && webhookId && isAdmin ? `WEBHOOK_DETAILS_${workspaceSlug}_${webhookId}` : null,
workspaceSlug && webhookId && isAdmin
? () => fetchWebhookById(workspaceSlug.toString(), webhookId.toString())
: null
);
const onSubmit = (data: IExtendedWebhook): Promise<IWebhook> => {
const payload = {
url: data?.url,
is_active: data?.is_active,
project: data?.project,
cycle: data?.cycle,
module: data?.module,
issue: data?.issue,
issue_comment: data?.issue_comment,
};
return webhookStore.update(workspaceSlug, webhookId, payload);
};
if (!isAdmin)
return (
<div className="h-full w-full flex justify-center mt-10 p-4">
<p className="text-custom-text-300 text-sm">You are not authorized to access this page.</p>
</div>
);
const initialPayload = webhookStore.currentWebhook as IWebhook;
if (!currentWebhook)
return (
<div className="h-full w-full grid place-items-center p-4">
<Spinner />
</div>
);
return (
<AppLayout header={<WorkspaceSettingHeader title="Webhook Settings" />}>
<WorkspaceSettingLayout>
<div className="w-full overflow-y-auto py-3 pr-4">
{isLoading ? (
<div className="flex w-full h-full items-center justify-center">
<Spinner />
</div>
) : (
<WebHookForm type={WebHookFormTypes.EDIT} initialData={initialPayload} onSubmit={onSubmit} />
)}
</div>
</WorkspaceSettingLayout>
</AppLayout>
<>
<DeleteWebhookModal isOpen={deleteWebhookModal} onClose={() => setDeleteWebhookModal(false)} />
<div className="w-full overflow-y-auto py-8 pr-9 space-y-8">
<WebhookForm data={currentWebhook} />
{currentWebhook && <WebhookDeleteSection openDeleteModal={() => setDeleteWebhookModal(true)} />}
</div>
</>
);
});
export default Webhooks;
WebhookDetailsPage.getLayout = function getLayout(page: React.ReactElement) {
return (
<AppLayout header={<WorkspaceSettingHeader title="Webhook settings" />}>
<WorkspaceSettingLayout>{page}</WorkspaceSettingLayout>
</AppLayout>
);
};
export default WebhookDetailsPage;

View File

@ -1,89 +1,43 @@
import React, { useEffect } from "react";
import { useRouter } from "next/router";
import type { NextPage } from "next";
import { AppLayout } from "layouts/app-layout";
import { WorkspaceSettingHeader } from "components/headers";
import { WorkspaceSettingLayout } from "layouts/settings-layout";
import { WebHookForm } from "components/web-hooks";
import { IWebhook, IExtendedWebhook } from "types";
import { RootStore } from "store/root";
import React from "react";
import { observer } from "mobx-react-lite";
// mobx store
import { useMobxStore } from "lib/mobx/store-provider";
import { csvDownload } from "helpers/download.helper";
import useToast from "hooks/use-toast";
import { WebHookFormTypes } from "components/web-hooks/form";
import { getCurrentHookAsCSV } from "components/web-hooks/utils";
// layouts
import { AppLayout } from "layouts/app-layout";
import { WorkspaceSettingLayout } from "layouts/settings-layout";
// components
import { WorkspaceSettingHeader } from "components/headers";
import { WebhookForm } from "components/web-hooks";
// types
import { NextPageWithLayout } from "types/app";
const Webhooks: NextPage = () => {
const router = useRouter();
const CreateWebhookPage: NextPageWithLayout = observer(() => {
const {
user: { currentWorkspaceRole },
} = useMobxStore();
const { workspaceSlug } = router.query as { workspaceSlug: string };
const isAdmin = currentWorkspaceRole === 20;
const initialWebhookPayload: IWebhook = {
url: "",
is_active: true,
created_at: "",
updated_at: "",
secret_key: "",
project: true,
issue_comment: true,
cycle: true,
module: true,
issue: true,
workspace: "",
};
const { webhook: webhookStore, workspace: workspaceStore }: RootStore = useMobxStore();
const { setToastAlert } = useToast();
const onSubmit = async (data: IExtendedWebhook) => {
const payload = {
url: data?.url,
is_active: data?.is_active,
project: data?.project,
cycle: data?.cycle,
module: data?.module,
issue: data?.issue,
issue_comment: data?.issue_comment,
};
return webhookStore
.create(workspaceSlug, payload)
.then(({ webHook, secretKey }) => {
setToastAlert({
title: "Success",
type: "success",
message: "Successfully created",
});
const csvData = getCurrentHookAsCSV(workspaceStore.currentWorkspace, webHook, secretKey);
csvDownload(csvData, `Secret-key-${Date.now()}`);
if (webHook && webHook.id) {
router.push({ pathname: `/${workspaceSlug}/settings/webhooks/${webHook.id}`, query: { isCreated: true } });
}
})
.catch((error) => {
setToastAlert({
title: "Oops!",
type: "error",
message: error?.error ?? "Something went wrong!",
});
});
};
useEffect(() => {
webhookStore.clearSecretKey();
}, []);
if (!isAdmin)
return (
<div className="h-full w-full flex justify-center mt-10 p-4">
<p className="text-custom-text-300 text-sm">You are not authorized to access this page.</p>
</div>
);
return (
<AppLayout header={<WorkspaceSettingHeader title="Webhook Settings" />}>
<WorkspaceSettingLayout>
<div className="w-full overflow-y-auto py-3 pr-4">
<WebHookForm type={WebHookFormTypes.CREATE} initialData={initialWebhookPayload} onSubmit={onSubmit} />
</div>
</WorkspaceSettingLayout>
<div className="w-full overflow-y-auto py-8 pr-9 pl-1">
<WebhookForm />
</div>
);
});
CreateWebhookPage.getLayout = function getLayout(page: React.ReactElement) {
return (
<AppLayout header={<WorkspaceSettingHeader title="Webhook settings" />}>
<WorkspaceSettingLayout>{page}</WorkspaceSettingLayout>
</AppLayout>
);
};
export default Webhooks;
export default CreateWebhookPage;

View File

@ -1,56 +1,80 @@
import React from "react";
import type { NextPage } from "next";
import Link from "next/link";
import { useRouter } from "next/router";
import useSWR from "swr";
import { observer } from "mobx-react-lite";
// layout
// mobx store
import { useMobxStore } from "lib/mobx/store-provider";
// layouts
import { AppLayout } from "layouts/app-layout";
import { WorkspaceSettingLayout } from "layouts/settings-layout";
// components
import { WorkspaceSettingHeader } from "components/headers";
import { WebhookLists, EmptyWebhooks } from "components/web-hooks";
// hooks
import { useMobxStore } from "lib/mobx/store-provider";
import { WebhooksList, WebhooksEmptyState } from "components/web-hooks";
// ui
import { Button, Spinner } from "@plane/ui";
// types
import { RootStore } from "store/root";
import { Spinner } from "@plane/ui";
import { NextPageWithLayout } from "types/app";
const WebhooksPage: NextPage = observer(() => {
const WebhooksListPage: NextPageWithLayout = observer(() => {
const router = useRouter();
const { workspaceSlug } = router.query as { workspaceSlug: string };
const { workspaceSlug } = router.query;
const {
webhook: { fetchWebhooks, webhooks, loader },
}: RootStore = useMobxStore();
webhook: { fetchWebhooks, webhooks },
user: { currentWorkspaceRole },
} = useMobxStore();
const isAdmin = currentWorkspaceRole === 20;
useSWR(
workspaceSlug ? `WEBHOOKS_LIST_${workspaceSlug}` : null,
workspaceSlug ? () => fetchWebhooks(workspaceSlug) : null
workspaceSlug && isAdmin ? `WEBHOOKS_LIST_${workspaceSlug}` : null,
workspaceSlug && isAdmin ? () => fetchWebhooks(workspaceSlug.toString()) : null
);
if (!isAdmin)
return (
<div className="h-full w-full flex justify-center mt-10 p-4">
<p className="text-custom-text-300 text-sm">You are not authorized to access this page.</p>
</div>
);
if (!webhooks)
return (
<div className="h-full w-full grid place-items-center p-4">
<Spinner />
</div>
);
return (
<AppLayout header={<WorkspaceSettingHeader title="Webhook Settings" />}>
<WorkspaceSettingLayout>
<div className="w-full overflow-y-auto py-3 pr-9">
{loader ? (
<div className="flex h-full w-ful items-center justify-center">
<Spinner />
</div>
) : (
<>
{Object.keys(webhooks).length > 0 ? (
<WebhookLists workspaceSlug={workspaceSlug} />
) : (
<div className="py-5 mx-auto">
<EmptyWebhooks />
</div>
)}
</>
)}
<div className="h-full w-full py-8 pr-9 overflow-hidden">
{Object.keys(webhooks).length > 0 ? (
<div className="h-full w-full flex flex-col">
<div className="flex items-center justify-between gap-4 pb-3.5 border-b border-custom-border-200">
<div className="text-xl font-medium">Webhooks</div>
<Link href={`/${workspaceSlug}/settings/webhooks/create`}>
<Button variant="primary" size="sm">
Add webhook
</Button>
</Link>
</div>
<WebhooksList />
</div>
</WorkspaceSettingLayout>
</AppLayout>
) : (
<div className="mx-auto">
<WebhooksEmptyState />
</div>
)}
</div>
);
});
export default WebhooksPage;
WebhooksListPage.getLayout = function getLayout(page: React.ReactElement) {
return (
<AppLayout header={<WorkspaceSettingHeader title="Webhook settings" />}>
<WorkspaceSettingLayout>{page}</WorkspaceSettingLayout>
</AppLayout>
);
};
export default WebhooksListPage;

View File

@ -10,7 +10,7 @@ export class WebhookService extends APIService {
super(API_BASE_URL);
}
async getAll(workspaceSlug: string): Promise<IWebhook[]> {
async fetchWebhooksList(workspaceSlug: string): Promise<IWebhook[]> {
return this.get(`/api/workspaces/${workspaceSlug}/webhooks/`)
.then((response) => response?.data)
.catch((error) => {
@ -18,15 +18,15 @@ export class WebhookService extends APIService {
});
}
async getById(workspaceSlug: string, webhook_id: string): Promise<IWebhook> {
return this.get(`/api/workspaces/${workspaceSlug}/webhooks/${webhook_id}/`)
async fetchWebhookDetails(workspaceSlug: string, webhookId: string): Promise<IWebhook> {
return this.get(`/api/workspaces/${workspaceSlug}/webhooks/${webhookId}/`)
.then((response) => response?.data)
.catch((error) => {
throw error?.response?.data;
});
}
async create(workspaceSlug: string, data: {}): Promise<IWebhook> {
async createWebhook(workspaceSlug: string, data: {}): Promise<IWebhook> {
return this.post(`/api/workspaces/${workspaceSlug}/webhooks/`, data)
.then((response) => response?.data)
.catch((error) => {
@ -34,24 +34,24 @@ export class WebhookService extends APIService {
});
}
async update(workspaceSlug: string, webhook_id: string, data: {}): Promise<IWebhook> {
return this.patch(`/api/workspaces/${workspaceSlug}/webhooks/${webhook_id}/`, data)
async updateWebhook(workspaceSlug: string, webhookId: string, data: {}): Promise<IWebhook> {
return this.patch(`/api/workspaces/${workspaceSlug}/webhooks/${webhookId}/`, data)
.then((response) => response?.data)
.catch((error) => {
throw error?.response?.data;
});
}
async remove(workspaceSlug: string, webhook_id: string): Promise<void> {
return this.delete(`/api/workspaces/${workspaceSlug}/webhooks/${webhook_id}/`)
async deleteWebhook(workspaceSlug: string, webhookId: string): Promise<void> {
return this.delete(`/api/workspaces/${workspaceSlug}/webhooks/${webhookId}/`)
.then((response) => response?.data)
.catch((error) => {
throw error?.response?.data;
});
}
async regenerate(workspaceSlug: string, webhook_id: string): Promise<IWebhook> {
return this.post(`/api/workspaces/${workspaceSlug}/webhooks/${webhook_id}/regenerate/`)
async regenerateSecretKey(workspaceSlug: string, webhookId: string): Promise<IWebhook> {
return this.post(`/api/workspaces/${workspaceSlug}/webhooks/${webhookId}/regenerate/`)
.then((response) => response?.data)
.catch((error) => {
throw error?.response?.data;

View File

@ -7,7 +7,7 @@ export interface IWebhookStore {
loader: boolean;
error: any | undefined;
webhooks: { [webhookId: string]: IWebhook };
webhooks: { [webhookId: string]: IWebhook } | null;
currentWebhookId: string | undefined;
webhookSecretKey: string | undefined;
@ -15,12 +15,16 @@ export interface IWebhookStore {
currentWebhook: IWebhook | undefined;
// actions
setCurrentWebhookId: (webhookId: string | undefined) => void;
fetchWebhooks: (workspaceSlug: string) => Promise<IWebhook[]>;
fetchById: (workspaceSlug: string, webhook_id: string) => Promise<IWebhook>;
create: (workspaceSlug: string, data: IWebhook) => Promise<{ webHook: IWebhook; secretKey: string | undefined }>;
update: (workspaceSlug: string, webhook_id: string, data: Partial<IWebhook>) => Promise<IWebhook>;
remove: (workspaceSlug: string, webhook_id: string) => Promise<void>;
regenerate: (
fetchWebhookById: (workspaceSlug: string, webhook_id: string) => Promise<IWebhook>;
createWebhook: (
workspaceSlug: string,
data: Partial<IWebhook>
) => Promise<{ webHook: IWebhook; secretKey: string | undefined }>;
updateWebhook: (workspaceSlug: string, webhook_id: string, data: Partial<IWebhook>) => Promise<IWebhook>;
removeWebhook: (workspaceSlug: string, webhook_id: string) => Promise<void>;
regenerateSecretKey: (
workspaceSlug: string,
webhook_id: string
) => Promise<{ webHook: IWebhook; secretKey: string | undefined }>;
@ -31,7 +35,7 @@ export class WebhookStore implements IWebhookStore {
loader: boolean = false;
error: any | undefined = undefined;
webhooks: { [webhookId: string]: IWebhook } = {};
webhooks: { [webhookId: string]: IWebhook } | null = null;
currentWebhookId: string | undefined = undefined;
webhookSecretKey: string | undefined = undefined;
@ -51,28 +55,35 @@ export class WebhookStore implements IWebhookStore {
currentWebhook: computed,
fetchWebhooks: action,
create: action,
fetchById: action,
update: action,
remove: action,
regenerate: action,
createWebhook: action,
fetchWebhookById: action,
updateWebhook: action,
removeWebhook: action,
regenerateSecretKey: action,
clearSecretKey: action,
});
this.rootStore = _rootStore;
this.webhookService = new WebhookService();
}
get currentWebhook() {
if (!this.currentWebhookId) return undefined;
const currentWebhook = this.webhooks ? this.webhooks[this.currentWebhookId] : undefined;
const currentWebhook = this.webhooks?.[this.currentWebhookId] ?? undefined;
return currentWebhook;
}
setCurrentWebhookId = (webhookId: string | undefined) => {
this.currentWebhookId = webhookId;
};
fetchWebhooks = async (workspaceSlug: string) => {
try {
this.loader = true;
this.error = undefined;
const webhookResponse = await this.webhookService.getAll(workspaceSlug);
const webhookResponse = await this.webhookService.fetchWebhooksList(workspaceSlug);
const webHookObject: { [webhookId: string]: IWebhook } = webhookResponse.reduce((accumulator, currentWebhook) => {
if (currentWebhook && currentWebhook.id) {
@ -91,102 +102,92 @@ export class WebhookStore implements IWebhookStore {
} catch (error) {
this.loader = false;
this.error = error;
throw error;
}
};
create = async (workspaceSlug: string, data: IWebhook) => {
createWebhook = async (workspaceSlug: string, data: Partial<IWebhook>) => {
try {
const webhookResponse = await this.webhookService.create(workspaceSlug, data);
const webhookResponse = await this.webhookService.createWebhook(workspaceSlug, data);
const _secretKey = webhookResponse?.secret_key;
delete webhookResponse?.secret_key;
const _webhooks = this.webhooks;
if (webhookResponse && webhookResponse.id) {
_webhooks[webhookResponse.id] = webhookResponse;
}
if (webhookResponse && webhookResponse.id && _webhooks) _webhooks[webhookResponse.id] = webhookResponse;
runInAction(() => {
this.webhookSecretKey = _secretKey || undefined;
this.webhooks = _webhooks;
this.currentWebhookId = webhookResponse.id;
});
return { webHook: webhookResponse, secretKey: _secretKey };
} catch (error) {
console.log(error);
throw error;
}
};
fetchById = async (workspaceSlug: string, webhook_id: string) => {
fetchWebhookById = async (workspaceSlug: string, webhook_id: string) => {
try {
const webhookResponse = await this.webhookService.getById(workspaceSlug, webhook_id);
const webhookResponse = await this.webhookService.fetchWebhookDetails(workspaceSlug, webhook_id);
const _webhooks = this.webhooks;
if (webhookResponse && webhookResponse.id) {
_webhooks[webhookResponse.id] = webhookResponse;
}
runInAction(() => {
this.currentWebhookId = webhook_id;
this.webhooks = _webhooks;
this.webhooks = {
...this.webhooks,
[webhookResponse.id]: webhookResponse,
};
});
return webhookResponse;
} catch (error) {
console.log(error);
throw error;
}
};
update = async (workspaceSlug: string, webhook_id: string, data: Partial<IWebhook>) => {
updateWebhook = async (workspaceSlug: string, webhook_id: string, data: Partial<IWebhook>) => {
try {
let _webhooks = this.webhooks;
if (webhook_id) {
if (webhook_id && _webhooks && this.webhooks)
_webhooks = { ..._webhooks, [webhook_id]: { ...this.webhooks[webhook_id], ...data } };
}
runInAction(() => {
this.webhooks = _webhooks;
});
const webhookResponse = await this.webhookService.update(workspaceSlug, webhook_id, data);
const webhookResponse = await this.webhookService.updateWebhook(workspaceSlug, webhook_id, data);
return webhookResponse;
} catch (error) {
console.log(error);
this.fetchWebhooks(workspaceSlug);
throw error;
}
};
remove = async (workspaceSlug: string, webhook_id: string) => {
removeWebhook = async (workspaceSlug: string, webhook_id: string) => {
try {
await this.webhookService.remove(workspaceSlug, webhook_id);
await this.webhookService.deleteWebhook(workspaceSlug, webhook_id);
const _webhooks = this.webhooks;
const _webhooks = this.webhooks ?? {};
delete _webhooks[webhook_id];
runInAction(() => {
this.webhooks = _webhooks;
});
} catch (error) {
console.log(error);
throw error;
}
};
regenerate = async (workspaceSlug: string, webhook_id: string) => {
regenerateSecretKey = async (workspaceSlug: string, webhook_id: string) => {
try {
const webhookResponse = await this.webhookService.regenerate(workspaceSlug, webhook_id);
const webhookResponse = await this.webhookService.regenerateSecretKey(workspaceSlug, webhook_id);
const _secretKey = webhookResponse?.secret_key;
delete webhookResponse?.secret_key;
const _webhooks = this.webhooks;
if (webhookResponse && webhookResponse.id) {
if (_webhooks && webhookResponse && webhookResponse.id) {
_webhooks[webhookResponse.id] = webhookResponse;
}
@ -196,7 +197,6 @@ export class WebhookStore implements IWebhookStore {
});
return { webHook: webhookResponse, secretKey: _secretKey };
} catch (error) {
console.log(error);
throw error;
}
};

View File

@ -1,31 +1,15 @@
export interface IWebhook {
id?: string;
secret_key?: string;
url: string;
created_at?: string;
updated_at?: string;
is_active: boolean;
project: boolean;
created_at: string;
cycle: boolean;
module: boolean;
id: string;
is_active: boolean;
issue: boolean;
issue_comment?: boolean;
workspace?: string;
issue_comment: boolean;
module: boolean;
project: boolean;
secret_key?: string;
updated_at: string;
url: string;
}
// this interface is used to handle the webhook form state
interface IExtendedWebhook extends IWebhook {
webhook_events: string;
}
export interface IWebhookIndividualOptions {
key: string;
label: string;
name: "project" | "cycle" | "module" | "issue" | "issue_comment";
}
export interface IWebhookOptions {
key: string;
label: string;
name: "webhook_events";
}
export type TWebhookEventTypes = "all" | "individual";