* build basic database structure and basic design * create simple workflow list * add editing dots to list * add mutation to create workflows * add createMutation on submit + redirect to editing page * redirect to edit page when clicking on row * add functionality to delete workflow * add timeUnit + input validation * add empty screen view * add time before it triggers to description * add multi select with checkboxes * remove getServerSideProps * set default time period to 24 * fetch eventypes and display in dropdown * add functionality to update workflows + many-to-many relationship * fix all checked event types * add SMS reminders * fix bug with trigger + relocate sms template * clean code * add model for unscheduled reminders * fix selected eventTypes * fixing value to show how many event types selected * fix plural of event types in select * add onDelete cascade for all relations * fix errors * add functionality to send SMS to specific number * fix type error for timeUnit * set default value for time unit + fix type issues * remove console.logs * fix error in checking if scheduled date is more than 1h in advance * fix build errors * add migration for workflows * add basic UI for editing workflow steps * add formSchema * improve functionality to update a step * remove console logs * fix issue with active event types * allow null value for time and timeUnit * sort steps asc step number * add action to workflow (frontend) * add phone number input for SMS to specific number * use PhoneInput for number input + input validation * improve invalid input for phone number * improve UI of phoneInput * Improve design and validation * fix undefined error * set default action when adding action * include all team event types * fix phone number input for editing steps * fix update muation to add steps * remove console logs * fix order of steps * functionality to delete steps * add trigger when event is cancelled * add custom email body * sms and email reminder updates * add custom emails * add custom email subject * send reminder email to all attendees * update migration * fix default value for time and timeUnit * save email reminders to database * clean code * add custom template to SMS actions * schedule emails with sendgrid * clean code * add workflow templates * keep custom template saved when changing templates * create reminder template for email * add dot at the end of sentace for email template * fix merge error * fix issue that template was not saved * include sending emails for when event is cancelled * fix bug that email was always sent * add templates to sms reminders * add info that sending sms to attendees won't trigger for already exisitng bookings * only schedule sms for attendees when smsReminderNumber exists * only schedule sms for attendees when smsReminderNumber exists * set scheduled of workflow reminder to false when longer than 72 hours * add cron for email scheduling + fixes for for sms an email scheduling * adjust step number when deleting a step * cast to boolean with !! * update cron job for email reminders * update sms template * send reminder email not to guests * remove sendTo from workflow reminder * fixes sending sms without name + removing sendTo everywhere * fix undefined name in sms template * set user name to undefined for sending sms to a specific number * fix singular and plural for time unit * set to edit mode when changing action and custom template is selected * delete reminders when booking cancelled or not active anymore * fix type errors * fix error that deleted reminders twice * create booking reminders for existing bookings when eventType is set active * improve email and sms templates * use BookingInfo type instead of calendarEvent for reminder emails * schedule emails for already existing bookings * add and remove reminders for new active event types and cancelled events * connect add action button with last step * fix step container width for mobile view * helper functions that return options for select * fix typo and remove comment * clean code * add/improve error messages for forms * fix typo * clean code * improve email template * clean code * fix missing prop * save reference id when scheduling reminder * fix step not added because of changed id for new steps * small fixes + code cleanup * code cleanup * show error message when number is invalid * fix typo * fix phone number input when location is already phone * set multi select checkbox to read only * change email scheduling in cron job from 7 days to 72 hours * show active event types in workflow list * fix trigger information for workflow list * improve layout for small screens in workflow list * remove optional from zod type for workflow name * order workflows by id * use link icon to show active event types * fix plural and add translation for showing nr of active eventtypes * fix text for sms reminder template * add reminders for added steps * remove optional for activeOn * improve reminder templates * improve design of custom input fields * set edit mode to false when phone number isn't needed anymore * set sendTo in workflow step only for SMS_NUMBER action * set email body and subject only when custom template * only delete reminders that belong to workflow steps * improve text for new event book trigger * move reminders folder to workflows * fix issue that save button was sometimes enabled in edit mode * fix form issues for send to * delete all scheduled reminders when workflow is deleted * use enum for method * fix imports for workflow methods * add missing import * fix edit mode * create reminders when event is confirmed * add reminderScheduler to reduce duplicate code * make workflow enterprise and pro only feature * move all files to /ee/ folder * move package.json change to /ee/ folder * add pro badge to shell * set to edit mode to true if email subject is missing when action changes * fix loading bug * add migration * fix old imports * don't schedule reminders for opt-ins * fix style of email body * code clean up * Update yarn.lock * fix isLoading for active on dropdown * update import for prisma Co-authored-by: Omar López <zomars@me.com> * update imports * remove console * use session to check if user has valid license * use defaultHandler * clean up code * Create db-staging-snapshot.yml * move LisenceRequired inside shell * update import for FormValues * fix phone input design * fix disabled save button for edit mode * squah all migration into a single one * use isAfter and isBefore instead of isBetween * import dayjs from @calcom * validate phone number for sms reminders when booking event * Allows auto approvals for crowdin Co-authored-by: CarinaWolli <wollencarina@gmail.com> Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com> Co-authored-by: zomars <zomars@me.com>
324 lines
9.6 KiB
TypeScript
324 lines
9.6 KiB
TypeScript
import { Booking, BookingStatus, Prisma, SchedulingType, User } from "@prisma/client";
|
||
import type { NextApiRequest } from "next";
|
||
import { z } from "zod";
|
||
|
||
import EventManager from "@calcom/core/EventManager";
|
||
import { sendDeclinedEmails, sendScheduledEmails } from "@calcom/emails";
|
||
import { isPrismaObjOrUndefined, parseRecurringEvent } from "@calcom/lib";
|
||
import logger from "@calcom/lib/logger";
|
||
import { defaultHandler, defaultResponder } from "@calcom/lib/server";
|
||
import prisma from "@calcom/prisma";
|
||
import type { AdditionalInformation, CalendarEvent } from "@calcom/types/Calendar";
|
||
import { refund } from "@ee/lib/stripe/server";
|
||
import { scheduleWorkflowReminders } from "@ee/lib/workflows/reminders/reminderScheduler";
|
||
|
||
import { getSession } from "@lib/auth";
|
||
import { HttpError } from "@lib/core/http/error";
|
||
|
||
import { getTranslation } from "@server/lib/i18n";
|
||
|
||
const authorized = async (
|
||
currentUser: Pick<User, "id">,
|
||
booking: Pick<Booking, "eventTypeId" | "userId">
|
||
) => {
|
||
// if the organizer
|
||
if (booking.userId === currentUser.id) {
|
||
return true;
|
||
}
|
||
const eventType = await prisma.eventType.findUnique({
|
||
where: {
|
||
id: booking.eventTypeId || undefined,
|
||
},
|
||
select: {
|
||
schedulingType: true,
|
||
users: true,
|
||
},
|
||
});
|
||
if (
|
||
eventType?.schedulingType === SchedulingType.COLLECTIVE &&
|
||
eventType.users.find((user) => user.id === currentUser.id)
|
||
) {
|
||
return true;
|
||
}
|
||
return false;
|
||
};
|
||
|
||
const log = logger.getChildLogger({ prefix: ["[api] book:user"] });
|
||
|
||
const bookingConfirmPatchBodySchema = z.object({
|
||
confirmed: z.boolean(),
|
||
id: z.number(),
|
||
recurringEventId: z.string().optional(),
|
||
reason: z.string().optional(),
|
||
});
|
||
|
||
async function patchHandler(req: NextApiRequest) {
|
||
const session = await getSession({ req });
|
||
if (!session?.user?.id) {
|
||
throw new HttpError({ statusCode: 401, message: "Not authenticated" });
|
||
}
|
||
|
||
const {
|
||
id: bookingId,
|
||
recurringEventId,
|
||
reason: rejectionReason,
|
||
confirmed,
|
||
} = bookingConfirmPatchBodySchema.parse(req.body);
|
||
|
||
const currentUser = await prisma.user.findFirst({
|
||
rejectOnNotFound() {
|
||
throw new HttpError({ statusCode: 404, message: "User not found" });
|
||
},
|
||
where: {
|
||
id: session.user.id,
|
||
},
|
||
select: {
|
||
id: true,
|
||
credentials: {
|
||
orderBy: { id: "desc" as Prisma.SortOrder },
|
||
},
|
||
timeZone: true,
|
||
email: true,
|
||
name: true,
|
||
username: true,
|
||
destinationCalendar: true,
|
||
locale: true,
|
||
},
|
||
});
|
||
|
||
const tOrganizer = await getTranslation(currentUser.locale ?? "en", "common");
|
||
|
||
const booking = await prisma.booking.findFirst({
|
||
where: {
|
||
id: bookingId,
|
||
},
|
||
rejectOnNotFound() {
|
||
throw new HttpError({ statusCode: 404, message: "Booking not found" });
|
||
},
|
||
select: {
|
||
title: true,
|
||
description: true,
|
||
customInputs: true,
|
||
startTime: true,
|
||
endTime: true,
|
||
attendees: true,
|
||
eventTypeId: true,
|
||
eventType: {
|
||
select: {
|
||
id: true,
|
||
recurringEvent: true,
|
||
requiresConfirmation: true,
|
||
workflows: {
|
||
include: {
|
||
workflow: {
|
||
include: {
|
||
steps: true,
|
||
},
|
||
},
|
||
},
|
||
},
|
||
},
|
||
},
|
||
location: true,
|
||
userId: true,
|
||
id: true,
|
||
uid: true,
|
||
payment: true,
|
||
destinationCalendar: true,
|
||
paid: true,
|
||
recurringEventId: true,
|
||
status: true,
|
||
smsReminderNumber: true,
|
||
},
|
||
});
|
||
|
||
if (!(await authorized(currentUser, booking))) {
|
||
throw new HttpError({ statusCode: 401, message: "UNAUTHORIZED" });
|
||
}
|
||
|
||
const isConfirmed = booking.status === BookingStatus.ACCEPTED;
|
||
if (isConfirmed) {
|
||
throw new HttpError({ statusCode: 400, message: "booking already confirmed" });
|
||
}
|
||
|
||
/** When a booking that requires payment its being confirmed but doesn't have any payment,
|
||
* we shouldn’t save it on DestinationCalendars
|
||
*/
|
||
if (booking.payment.length > 0 && !booking.paid) {
|
||
await prisma.booking.update({
|
||
where: {
|
||
id: bookingId,
|
||
},
|
||
data: {
|
||
status: BookingStatus.ACCEPTED,
|
||
},
|
||
});
|
||
|
||
req.statusCode = 204;
|
||
return { message: "Booking confirmed" };
|
||
}
|
||
|
||
const attendeesListPromises = booking.attendees.map(async (attendee) => {
|
||
return {
|
||
name: attendee.name,
|
||
email: attendee.email,
|
||
timeZone: attendee.timeZone,
|
||
language: {
|
||
translate: await getTranslation(attendee.locale ?? "en", "common"),
|
||
locale: attendee.locale ?? "en",
|
||
},
|
||
};
|
||
});
|
||
|
||
const attendeesList = await Promise.all(attendeesListPromises);
|
||
|
||
const evt: CalendarEvent = {
|
||
type: booking.title,
|
||
title: booking.title,
|
||
description: booking.description,
|
||
customInputs: isPrismaObjOrUndefined(booking.customInputs),
|
||
startTime: booking.startTime.toISOString(),
|
||
endTime: booking.endTime.toISOString(),
|
||
organizer: {
|
||
email: currentUser.email,
|
||
name: currentUser.name || "Unnamed",
|
||
timeZone: currentUser.timeZone,
|
||
language: { translate: tOrganizer, locale: currentUser.locale ?? "en" },
|
||
},
|
||
attendees: attendeesList,
|
||
location: booking.location ?? "",
|
||
uid: booking.uid,
|
||
destinationCalendar: booking?.destinationCalendar || currentUser.destinationCalendar,
|
||
requiresConfirmation: booking?.eventType?.requiresConfirmation ?? false,
|
||
eventTypeId: booking.eventType?.id,
|
||
};
|
||
|
||
const recurringEvent = parseRecurringEvent(booking.eventType?.recurringEvent);
|
||
if (recurringEventId && recurringEvent) {
|
||
const groupedRecurringBookings = await prisma.booking.groupBy({
|
||
where: {
|
||
recurringEventId: booking.recurringEventId,
|
||
},
|
||
by: [Prisma.BookingScalarFieldEnum.recurringEventId],
|
||
_count: true,
|
||
});
|
||
// Overriding the recurring event configuration count to be the actual number of events booked for
|
||
// the recurring event (equal or less than recurring event configuration count)
|
||
recurringEvent.count = groupedRecurringBookings[0]._count;
|
||
// count changed, parsing again to get the new value in
|
||
evt.recurringEvent = parseRecurringEvent(recurringEvent);
|
||
}
|
||
|
||
if (confirmed) {
|
||
const eventManager = new EventManager(currentUser);
|
||
const scheduleResult = await eventManager.create(evt);
|
||
|
||
const results = scheduleResult.results;
|
||
|
||
if (results.length > 0 && results.every((res) => !res.success)) {
|
||
const error = {
|
||
errorCode: "BookingCreatingMeetingFailed",
|
||
message: "Booking failed",
|
||
};
|
||
|
||
log.error(`Booking ${currentUser.username} failed`, error, results);
|
||
} else {
|
||
const metadata: AdditionalInformation = {};
|
||
|
||
if (results.length) {
|
||
// TODO: Handle created event metadata more elegantly
|
||
metadata.hangoutLink = results[0].createdEvent?.hangoutLink;
|
||
metadata.conferenceData = results[0].createdEvent?.conferenceData;
|
||
metadata.entryPoints = results[0].createdEvent?.entryPoints;
|
||
}
|
||
try {
|
||
await sendScheduledEmails({ ...evt, additionalInformation: metadata });
|
||
} catch (error) {
|
||
log.error(error);
|
||
}
|
||
}
|
||
|
||
if (recurringEventId) {
|
||
// The booking to confirm is a recurring event and comes from /booking/recurring, proceeding to mark all related
|
||
// bookings as confirmed. Prisma updateMany does not support relations, so doing this in two steps for now.
|
||
const unconfirmedRecurringBookings = await prisma.booking.findMany({
|
||
where: {
|
||
recurringEventId,
|
||
status: BookingStatus.PENDING,
|
||
},
|
||
});
|
||
unconfirmedRecurringBookings.map(async (recurringBooking) => {
|
||
await prisma.booking.update({
|
||
where: {
|
||
id: recurringBooking.id,
|
||
},
|
||
data: {
|
||
status: BookingStatus.ACCEPTED,
|
||
references: {
|
||
create: scheduleResult.referencesToCreate,
|
||
},
|
||
},
|
||
});
|
||
});
|
||
} else {
|
||
// @NOTE: be careful with this as if any error occurs before this booking doesn't get confirmed
|
||
// Should perform update on booking (confirm) -> then trigger the rest handlers
|
||
await prisma.booking.update({
|
||
where: {
|
||
id: bookingId,
|
||
},
|
||
data: {
|
||
status: BookingStatus.ACCEPTED,
|
||
references: {
|
||
create: scheduleResult.referencesToCreate,
|
||
},
|
||
},
|
||
});
|
||
}
|
||
|
||
//Workflows - set reminders for confirmed events
|
||
if (booking.eventType?.workflows) {
|
||
await scheduleWorkflowReminders(booking.eventType.workflows, booking.smsReminderNumber, evt, false);
|
||
}
|
||
} else {
|
||
evt.rejectionReason = rejectionReason;
|
||
if (recurringEventId) {
|
||
// The booking to reject is a recurring event and comes from /booking/upcoming, proceeding to mark all related
|
||
// bookings as rejected.
|
||
await prisma.booking.updateMany({
|
||
where: {
|
||
recurringEventId,
|
||
status: BookingStatus.PENDING,
|
||
},
|
||
data: {
|
||
status: BookingStatus.REJECTED,
|
||
rejectionReason,
|
||
},
|
||
});
|
||
} else {
|
||
await refund(booking, evt); // No payment integration for recurring events for v1
|
||
await prisma.booking.update({
|
||
where: {
|
||
id: bookingId,
|
||
},
|
||
data: {
|
||
status: BookingStatus.REJECTED,
|
||
rejectionReason,
|
||
},
|
||
});
|
||
}
|
||
|
||
await sendDeclinedEmails(evt);
|
||
}
|
||
|
||
req.statusCode = 204;
|
||
return { message: "Booking " + confirmed ? "confirmed" : "rejected" };
|
||
}
|
||
|
||
export type BookConfirmPatchResponse = Awaited<ReturnType<typeof patchHandler>>;
|
||
|
||
export default defaultHandler({
|
||
// To prevent too much git diff until moved to another file
|
||
PATCH: Promise.resolve({ default: defaultResponder(patchHandler) }),
|
||
});
|