Team webhooks (#8917)

* allow event type specific webhooks for all event types

* first version of team webhooks

* add empty view

* design fixes when no teams + invalidate query on delete/update

* linke to new webhooks page with teamId in query

* make one button with dropdown instead of a button for every team

* add subtitle to dropdown

* add avatar fallback

* authorization when editing webhook

* fix event type webhooks

* fix authorization for delete handler

* code clean up

* fix disabled switch

* add migration

* fix subscriberUrlReservered function and fix authorization

* fix type error

* fix type error

* fix switch not updating

* make sure webhooks are triggered for the correct even types

* code clean up

* only show teams were user has write access

* make webhooks read-only for members

* fix comment

* fix type error

* fix webhook tests for team event types

* implement feedback

* code clean up from feedback

* code clean up (feedback)

* throw error if param missing in subscriberUrlReservered

* handle null/undefined values in getWebhooks itself

* better variable naming

* better check if webhook is readonly

* create assertPartOfTeamWithRequiredAccessLevel to remove duplicate code

---------

Co-authored-by: CarinaWolli <[email protected]>
Co-authored-by: alannnc <[email protected]>
This commit is contained in:
authored and GitHub committed 2023-05-23 01:15:29 +00:00
1 parent b83ee2d57d
commit 84efda07e9
33 files changed
+691 -211

No files matched your search

@@ -7,16 +7,13 @@ import useLockedFieldsManager from "@calcom/features/ee/managed-event-types/hook
import { WebhookForm } from "@calcom/features/webhooks/components";
import type { WebhookFormSubmitData } from "@calcom/features/webhooks/components/WebhookForm";
import WebhookListItem from "@calcom/features/webhooks/components/WebhookListItem";
import { APP_NAME } from "@calcom/lib/constants";
import { subscriberUrlReserved } from "@calcom/features/webhooks/lib/subscriberUrlReserved";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { trpc } from "@calcom/trpc/react";
import { Alert, Button, Dialog, DialogContent, EmptyScreen, showToast } from "@calcom/ui";
import { Plus, Lock } from "@calcom/ui/components/icon";
export const EventTeamWebhooksTab = ({
eventType,
team,
}: Pick<EventTypeSetupProps, "eventType" | "team">) => {
export const EventWebhooksTab = ({ eventType }: Pick<EventTypeSetupProps, "eventType">) => {
const { t } = useLocale();
const utils = trpc.useContext();
@@ -32,12 +29,6 @@ export const EventTeamWebhooksTab = ({
const [editModalOpen, setEditModalOpen] = useState(false);
const [webhookToEdit, setWebhookToEdit] = useState<Webhook>();
const subscriberUrlReserved = (subscriberUrl: string, id?: string): boolean => {
return !!webhooks?.find(
(webhook) => webhook.subscriberUrl === subscriberUrl && (!id || webhook.id !== id)
);
};
const editWebhookMutation = trpc.viewer.webhook.edit.useMutation({
async onSuccess() {
setEditModalOpen(false);
@@ -61,7 +52,14 @@ export const EventTeamWebhooksTab = ({
});
const onCreateWebhook = async (values: WebhookFormSubmitData) => {
if (subscriberUrlReserved(values.subscriberUrl, values.id)) {
if (
subscriberUrlReserved({
subscriberUrl: values.subscriberUrl,
id: values.id,
webhooks,
eventTypeId: eventType.id,
})
) {
showToast(t("webhook_subscriber_url_reserved"), "error");
return;
}
@@ -102,7 +100,7 @@ export const EventTeamWebhooksTab = ({
return (
<div>
{team && webhooks && !isLoading && (
{webhooks && !isLoading && (
<>
<div>
<div>
@@ -139,7 +137,7 @@ export const EventTeamWebhooksTab = ({
<EmptyScreen
Icon={TbWebhook}
headline={t("create_your_first_webhook")}
description={t("create_your_first_team_webhook_description", { appName: APP_NAME })}
description={t("first_event_type_webhook_description")}
buttonRaw={
isChildrenManagedEventType && !isManagedEventType ? (
<Button StartIcon={Lock} color="secondary" disabled>
@@ -176,7 +174,14 @@ export const EventTeamWebhooksTab = ({
apps={installedApps?.items.map((app) => app.slug)}
onCancel={() => setEditModalOpen(false)}
onSubmit={(values: WebhookFormSubmitData) => {
if (subscriberUrlReserved(values.subscriberUrl, webhookToEdit?.id || "")) {
if (
subscriberUrlReserved({
subscriberUrl: values.subscriberUrl,
id: values.id,
webhooks,
eventTypeId: eventType.id,
})
) {
showToast(t("webhook_subscriber_url_reserved"), "error");
return;
}
+14 -3
View File
@@ -33,14 +33,16 @@ const triggerWebhook = async ({
booking: {
userId: number | undefined;
eventTypeId: number | null;
teamId?: number | null;
};
}) => {
const eventTrigger: WebhookTriggerEvents = "RECORDING_READY";
// Send Webhook call if hooked to BOOKING.RECORDING_READY
const subscriberOptions = {
userId: booking.userId ?? 0,
eventTypeId: booking.eventTypeId ?? 0,
userId: booking.userId,
eventTypeId: booking.eventTypeId,
triggerEvent: eventTrigger,
teamId: booking.teamId,
};
const webhooks = await getWebhooks(subscriberOptions);
@@ -87,6 +89,11 @@ async function handler(req: NextApiRequest, res: NextApiResponse) {
location: true,
isRecorded: true,
eventTypeId: true,
eventType: {
select: {
teamId: true,
},
},
user: {
select: {
id: true,
@@ -164,7 +171,11 @@ async function handler(req: NextApiRequest, res: NextApiResponse) {
await triggerWebhook({
evt,
downloadLink,
booking: { userId: booking?.user?.id, eventTypeId: booking.eventTypeId },
booking: {
userId: booking?.user?.id,
eventTypeId: booking.eventTypeId,
teamId: booking.eventType?.teamId,
},
});
const isSendingEmailsAllowed = IS_SELF_HOSTED || session?.user?.belongsToActiveTeam;
+2 -2
View File
@@ -39,8 +39,8 @@ import { EventLimitsTab } from "@components/eventtype/EventLimitsTab";
import { EventRecurringTab } from "@components/eventtype/EventRecurringTab";
import { EventSetupTab } from "@components/eventtype/EventSetupTab";
import { EventTeamTab } from "@components/eventtype/EventTeamTab";
import { EventTeamWebhooksTab } from "@components/eventtype/EventTeamWebhooksTab";
import { EventTypeSingleLayout } from "@components/eventtype/EventTypeSingleLayout";
import { EventWebhooksTab } from "@components/eventtype/EventWebhooksTab";
import EventWorkflowsTab from "@components/eventtype/EventWorkfowsTab";
import { ssrInit } from "@server/lib/ssr";
@@ -309,7 +309,7 @@ const EventTypePage = (props: EventTypeSetupProps) => {
workflows={eventType.workflows.map((workflowOnEventType) => workflowOnEventType.workflow)}
/>
),
webhooks: <EventTeamWebhooksTab eventType={eventType} team={team} />,
webhooks: <EventWebhooksTab eventType={eventType} />,
} as const;
const handleSubmit = async (values: FormValues) => {
@@ -52,8 +52,21 @@ test.describe("Manage Booking Questions", () => {
// Considering there are many steps in it, it would need more than default test timeout
test.setTimeout(testInfo.timeout * 3);
const user = await createAndLoginUserWithEventTypes({ users });
const team = await prisma.team.findFirst({
where: {
members: {
some: {
userId: user.id,
},
},
},
select: {
id: true,
},
});
const webhookReceiver = await addWebhook(user);
const teamId = team?.id ?? 0;
const webhookReceiver = await addWebhook(undefined, teamId);
await test.step("Go to First Team Event", async () => {
const $eventTypes = page.locator("[data-testid=event-types]").nth(1).locator("li a");
@@ -79,7 +92,6 @@ async function runTestStepsCommonForTeamAndUserEventType(
bookerVariant: BookerVariants
) {
await page.click('[href$="tabName=advanced"]');
await test.step("Add Question and see that it's shown on Booking Page at appropriate position", async () => {
await addQuestionAndSave({
page,
@@ -391,19 +403,35 @@ async function saveEventType(page: Page) {
await page.locator("[data-testid=update-eventtype]").click();
}
async function addWebhook(user: Awaited<ReturnType<typeof createAndLoginUserWithEventTypes>>) {
async function addWebhook(
user?: Awaited<ReturnType<typeof createAndLoginUserWithEventTypes>>,
teamId?: number | null
) {
const webhookReceiver = createHttpServer();
await prisma.webhook.create({
data: {
id: uuid(),
userId: user.id,
subscriberUrl: webhookReceiver.url,
eventTriggers: [
WebhookTriggerEvents.BOOKING_CREATED,
WebhookTriggerEvents.BOOKING_CANCELLED,
WebhookTriggerEvents.BOOKING_RESCHEDULED,
],
},
});
const data: {
id: string;
subscriberUrl: string;
eventTriggers: WebhookTriggerEvents[];
userId?: number;
teamId?: number;
} = {
id: uuid(),
subscriberUrl: webhookReceiver.url,
eventTriggers: [
WebhookTriggerEvents.BOOKING_CREATED,
WebhookTriggerEvents.BOOKING_CANCELLED,
WebhookTriggerEvents.BOOKING_RESCHEDULED,
],
};
if (teamId) {
data.teamId = teamId;
} else if (user) {
data.userId = user.id;
}
await prisma.webhook.create({ data });
return webhookReceiver;
}
@@ -1824,5 +1824,7 @@
"disable_attendees_confirmation_emails": "Disable default confirmation emails for attendees",
"disable_attendees_confirmation_emails_description": "At least one workflow is active on this event type that sends an email to the attendees when the event is booked.",
"disable_host_confirmation_emails": "Disable default confirmation emails for host",
"disable_host_confirmation_emails_description": "At least one workflow is active on this event type that sends an email to the host when the event is booked."
"disable_host_confirmation_emails_description": "At least one workflow is active on this event type that sends an email to the host when the event is booked.",
"first_event_type_webhook_description": "Create your first webhook for this event type",
"create_for": "Create for"
}