feat: Internal Notes for bookings (#18804)

* migration + migrate booking limit page to team settings

* new pages

* use settings toggle for displaying content

* get current team presets

* update mutation

* i18n for settings page

* remove redudant await

* cancelation UI for select

* handle other selection

* extract into a util

* inital cancelation reason flow

* fix i18n to be more readable

* add cancel reason logic

* nits

* improve copy

* ensure is teamMember and not isAdmin for getting internalNotes

* improvie spacing between elements

* fix types

* more type fixes

* correct types

* Update packages/features/bookings/lib/handleNewBooking/getEventTypesFromDB.ts

* use input component and remove mb-2 to allign with icon button

* Update packages/trpc/server/routers/viewer/teams/updateInternalNotesPresets.handler.ts

Co-authored-by: Eunjae Lee <[email protected]>

* nits

* type fixs

* fix type

* fix type

* fix nullable option lost in merge

---------

Co-authored-by: Eunjae Lee <[email protected]>
This commit is contained in:
sean-brydonandEunjae Lee authored and GitHub committed 2025-01-24 09:26:52 +00:00
1 parent 1fd4c3fd4c
commit 656d6dc195
22 files changed
+683 -22

No files matched your search

@@ -35,6 +35,7 @@ import { getAllWorkflowsFromEventType } from "@calcom/trpc/server/routers/viewer
import type { CalendarEvent } from "@calcom/types/Calendar";
import { getAllCredentials } from "./getAllCredentialsForUsersOnEvent/getAllCredentials";
import { handleInternalNote } from "./handleInternalNote";
import cancelAttendeeSeat from "./handleSeats/cancel/cancelAttendeeSeat";
const log = logger.getSubLogger({ prefix: ["handleCancelBooking"] });
@@ -137,9 +138,11 @@ async function getBookingToDelete(id: number | undefined, uid: string | undefine
});
}
export type BookingToDelete = Awaited<ReturnType<typeof getBookingToDelete>>;
export type CustomRequest = NextApiRequest & {
userId?: number;
bookingToDelete?: Awaited<ReturnType<typeof getBookingToDelete>>;
bookingToDelete?: BookingToDelete;
platformClientId?: string;
platformRescheduleUrl?: string;
platformCancelUrl?: string;
@@ -164,6 +167,7 @@ async function handler(req: CustomRequest) {
seatReferenceUid,
cancelledBy,
cancelSubsequentBookings,
internalNote,
} = bookingCancelInput.parse(req.body);
req.bookingToDelete = await getBookingToDelete(id, uid);
const {
@@ -560,6 +564,15 @@ async function handler(req: CustomRequest) {
log.error("An error occurred when deleting workflow reminders and webhook triggers", error);
});
if (internalNote && teamId) {
await handleInternalNote({
internalNote,
booking: bookingToDelete,
userId,
teamId: teamId,
});
}
const prismaPromises: Promise<unknown>[] = [bookingReferenceDeletes];
try {
@@ -0,0 +1,82 @@
import { HttpError } from "@calcom/lib/http-error";
import prisma from "@calcom/prisma";
import { type BookingToDelete } from "./handleCancelBooking";
type InternalNote = {
id: number;
name: string;
value?: string;
};
export async function handleInternalNote({
internalNote,
booking,
userId,
teamId,
}: {
internalNote: InternalNote;
booking: BookingToDelete;
userId: number;
teamId: number;
}) {
const userIsHost = booking?.eventType?.hosts.find((host) => {
if (host.user.id === userId) return true;
});
const userIsOwnerOfEventType = booking?.eventType?.owner?.id === userId;
if (!userIsHost && !userIsOwnerOfEventType) {
throw new HttpError({
statusCode: 403,
message: "You do not have permission to add an internal note to this booking.",
});
}
// "Other"
if (internalNote.id === -1) {
return prisma.bookingInternalNote.create({
data: {
booking: {
connect: {
id: booking.id,
},
},
text: internalNote.value,
createdBy: {
connect: {
id: userId,
},
},
},
});
}
// "Preset"
await prisma.internalNotePreset.findFirstOrThrow({
where: {
teamId: teamId,
id: internalNote.id,
},
});
return prisma.bookingInternalNote.create({
data: {
notePreset: {
connect: {
id: internalNote.id,
},
},
createdBy: {
connect: {
id: userId,
},
},
booking: {
connect: {
id: booking.id,
},
},
},
});
}
@@ -0,0 +1,185 @@
"use client";
import { useAutoAnimate } from "@formkit/auto-animate/react";
import { useMemo } from "react";
import { useForm, useFieldArray, Controller } from "react-hook-form";
import SectionBottomActions from "@calcom/features/settings/SectionBottomActions";
import { classNames } from "@calcom/lib";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { MembershipRole } from "@calcom/prisma/enums";
import { trpc } from "@calcom/trpc/react";
import type { RouterOutputs } from "@calcom/trpc/react";
import { Button, Form, SettingsToggle, showToast, Icon, Input } from "@calcom/ui";
interface ProfileViewProps {
team: RouterOutputs["viewer"]["teams"]["get"];
}
const OTHER_FIELD_ID = -1;
const InternalNotePresetsView = ({ team }: ProfileViewProps) => {
const { t } = useLocale();
const utils = trpc.useUtils();
const { data: _loadedPresets } = trpc.viewer.teams.getInternalNotesPresets.useQuery({
teamId: team?.id as number,
});
const loadedPresets = useMemo(() => {
return (_loadedPresets ?? []).map((preset) => ({
...preset,
cancellationReason: preset.cancellationReason ?? undefined,
}));
}, [_loadedPresets]);
const hasExistingPresets = loadedPresets.length > 0;
type FormValues = {
presets: { id: number; name: string; cancellationReason?: string | undefined }[];
};
const form = useForm<FormValues>({
values: {
presets: loadedPresets,
},
});
const { fields, append, remove, replace } = useFieldArray({
control: form.control,
name: "presets",
});
const addNewPreset = () => {
append({ id: OTHER_FIELD_ID, name: "" });
};
const updatePresetsMutation = trpc.viewer.teams.updateInternalNotesPresets.useMutation({
onSuccess: () => {
showToast(t("internal_note_presets_updated_successfully"), "success");
utils.viewer.teams.getInternalNotesPresets.invalidate();
},
onError: (error) => {
showToast(error.message || t("something_went_wrong"), "error");
},
});
const onSubmit = async (data: FormValues) => {
if (!team?.id) return;
updatePresetsMutation.mutate({
teamId: team.id,
presets: data.presets,
});
};
const [animateRef] = useAutoAnimate<HTMLDivElement>();
const isAdmin =
team && (team.membership.role === MembershipRole.OWNER || team.membership.role === MembershipRole.ADMIN);
if (!isAdmin) {
return (
<div className="border-subtle rounded-md border p-5">
<span className="text-default text-sm">{t("only_owner_change")}</span>
</div>
);
}
return (
<Form form={form} handleSubmit={(e) => onSubmit(e)}>
<Controller
name="presets"
render={({ field: { value } }) => {
const isChecked = hasExistingPresets || (value && value.length > 0);
return (
<SettingsToggle
toggleSwitchAtTheEnd={true}
labelClassName="text-sm"
title={t("internal_note_presets")}
description={t("internal_note_presets_description")}
checked={isChecked}
childrenClassName="lg:ml-0"
onCheckedChange={async (active) => {
if (active && !value?.length) {
append({ id: OTHER_FIELD_ID, name: "" });
} else {
replace([]);
if (!active && team?.id && hasExistingPresets) {
updatePresetsMutation.mutate({
teamId: team.id,
presets: [],
});
}
}
}}
switchContainerClassName={classNames(
"border-subtle mt-6 rounded-lg border py-6 px-4 sm:px-6",
isChecked && "rounded-b-none"
)}>
<div className="border-subtle border border-y-0 p-6">
<div className="flex flex-col space-y-4" ref={animateRef}>
{fields.map((field, index) => (
<div key={field.id} className="space-y-2">
<div className="flex items-center space-x-2">
<Controller
name={`presets.${index}.name`}
control={form.control}
render={({ field }) => (
<Input
type="text"
{...field}
placeholder={t("internal_booking_note")}
className="!mb-0"
/>
)}
/>
<Button
type="button"
color="destructive"
variant="icon"
onClick={() => remove(index)}
disabled={fields.length === 1}>
<Icon name="trash" className="h-4 w-5" />
</Button>
</div>
<div className="flex items-center gap-2">
<Icon name="corner-down-right" className="h-4 w-4" />
<Controller
name={`presets.${index}.cancellationReason`}
control={form.control}
render={({ field }) => (
<Input
type="text"
{...field}
placeholder={t("internal_note_cancellation_reason")}
className="!mb-0"
/>
)}
/>
</div>
</div>
))}
</div>
<Button
type="button"
color="minimal"
StartIcon="plus"
onClick={addNewPreset}
className="mt-4">
{t("add_preset")}
</Button>
</div>
<SectionBottomActions align="end">
<Button type="submit" color="primary" loading={updatePresetsMutation.isPending}>
{t("update")}
</Button>
</SectionBottomActions>
</SettingsToggle>
);
}}
/>
</Form>
);
};
export default InternalNotePresetsView;
@@ -16,6 +16,8 @@ import type { RouterOutputs } from "@calcom/trpc/react";
import type { IntervalLimit } from "@calcom/types/Calendar";
import { Button, CheckboxField, Form, SettingsToggle, showToast } from "@calcom/ui";
import { default as InternalNotePresetsView } from "../components/InternalNotePresetsView";
type ProfileViewProps = { team: RouterOutputs["viewer"]["teams"]["get"] };
const BookingLimitsView = ({ team }: ProfileViewProps) => {
@@ -136,7 +138,7 @@ const BookingLimitsView = ({ team }: ProfileViewProps) => {
);
};
const BookingLimitsViewWrapper = () => {
const TeamSettingsViewWrapper = () => {
const router = useRouter();
const params = useParamsWithFallback();
@@ -164,7 +166,12 @@ const BookingLimitsViewWrapper = () => {
if (!team) return null;
return <BookingLimitsView team={team} />;
return (
<>
<BookingLimitsView team={team} />
<InternalNotePresetsView team={team} />
</>
);
};
export default BookingLimitsViewWrapper;
export default TeamSettingsViewWrapper;
@@ -394,8 +394,8 @@ const TeamListCollapsible = () => {
</>
) : null}
<VerticalTabItem
name={t("booking_limits")}
href={`/settings/teams/${team.id}/bookingLimits`}
name={t("settings")}
href={`/settings/teams/${team.id}/settings`}
textClassNames="px-3 text-emphasis font-medium text-sm"
disableChevron
/>