cal.pub0.org/packages/trpc/server/routers/viewer/bookings.tsx

960 lines
32 KiB
TypeScript
Raw Normal View History

import type { BookingReference, EventType, User, WebhookTriggerEvents } from "@prisma/client";
import { BookingStatus, MembershipRole, Prisma, SchedulingType, WorkflowMethods } from "@prisma/client";
import type { TFunction } from "next-i18next";
Change location of booking (#2658) * add functionality to change location in booking and send out mail * add i18n * change location with dropdown like in event-types * small fixes and code clean up * clean code * improve format of current Location string * clean code * clear selection when dialog closed * added mutation and changed props (first working verison) * clean code * clean code * clean code * clean code * fix typo * change maxHeight of select * use useWatch for selectedLocation * pass default values with props * set current location directly in useState * clear selected values when updating location * fix trpc query for credentialst * change icons for editing booking * improve naming of variables * remove unnecessary orderBy * use locationOptionsToString method * fix current location naming for Cal Video * add phone input * save phone number as location of booking * remove input field for phone number for event-types * fix redirection issue * show previous selected location in event-type * remove attendee number from selection for booking * make first letter of location lowercase * remove input field for attendee phone number * clear Errors when changing location type * set location details to optional * clean code * fixing issue that dropdown doesn't close when dialog opens * clean code * make overflow visibile in dialog * fix existing bug with address not showing in event-type settings * fix issue with losing focus after validation * close rejection dialog * small spelling fixes * fix issue with LocationChangeEmail * fix failing E2E test * fix failing E2E test * fix E2E test * bug fix for saving user phone, and other minor changes * merge main * improve text * fix UI of booking list * Delete admin * remove selection after update and submit * add translation for error message * add default values for checkbox * add "your phone number" to locations on booking page * remove duplicate attributes from viewer.bookings Co-authored-by: Omar López <zomars@me.com> * check if user is authorized to make changes to booking * remove location string * clan code for displayLocaitonPublicly checkbox * fetch locationOptions on server side * remove trpc query for credentials * fix phone number input * fix labels of host and attendee phone number for booking page * Migrates edit location to tRPC * Link elemnt should only be used in `a` tags * Adds missin router * Migrates locationOptions to tRPC query * Type fixes Co-authored-by: CarinaWolli <wollencarina@gmail.com> Co-authored-by: Alan <alannnc@gmail.com> Co-authored-by: Omar López <zomars@me.com> Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
2022-05-27 23:27:41 +00:00
import { z } from "zod";
feat/payment-service-6438-cal-767 (#6677) * WIP paymentService * Changes for payment Service * Fix for stripe payment flow * Remove logs/comments * Refactored refund for stripe app * Move stripe handlePayment to own lib * Move stripe delete payments to paymentService * lint fix * Change handleRefundError as generic function * remove log * remove logs * remove logs * Return stripe default export to lib/server * Fixing types * Fix types * Upgrades typescript * Update yarn lock * Typings * Hotfix: ping,riverside,whereby and around not showing up in list (#6712) * Hotfix: ping,riverside,whereby and around not showing up in list (#6712) (#6713) * Adds deployment settings to DB (#6706) * WIP * Adds DeploymentTheme * Add missing migrations * Adds client extensions for deployment * Cleanup * Revert "lint fix" This reverts commit e1a2e4a357e58e6673c47399888ae2e00d1351a6. * Add validation * Revert changes removed in force push * Removing abstract class and just leaving interface implementation * Fix types for handlePayments * Fix payment test appStore import * Fix stripe metadata in event type * Move migration to separate PR * Revert "Move migration to separate PR" This reverts commit 48aa64e0724a522d3cc2fefaaaee5792ee9cd9e6. * Update packages/prisma/migrations/20230125175109_remove_type_from_payment_and_add_app_relationship/migration.sql Co-authored-by: Omar López <zomars@me.com> --------- Co-authored-by: zomars <zomars@me.com> Co-authored-by: Hariom Balhara <hariombalhara@gmail.com>
2023-02-08 20:36:22 +00:00
import appStore from "@calcom/app-store";
import { getCalendar } from "@calcom/app-store/_utils/getCalendar";
AppStore CLI: Making video app creation a breeze with major cleanup of locations code throughout (#3825) * Fix breadcrumb colors * HorizontalTabs * Team List Item WIP * Horizontal Tabs * Cards * Remove team list item WIP * Login Page * Add welcome back i118n * EventType page work * Update EventType Icons * WIP Availability * Horizontal Tab Work * Add build command for in root * Update build DIr/command * Add Edit Button + change buttons to v2 * Availablitiy page * Fix IPAD * Make mobile look a little nicer * WIP bookingshell * Remove list items from breaking build * Add Embed ModalBox for routing forms * Mian bulk of Booking Page. * Few updates to components * Fix chormatic feedback * Add duplicate form support * Fix duplication logic * Change to feathericons everywhere and other fixes * Dont allow routes for fallback route * Fix banner * Fix Empty Screen * Text area + embded window fixes * Semi fix avatar * Fix all TS issues * Fix tests * Troubleshoot container + Active on count * Support routing using query params * Improve mobile * NITS * Fix padding on input * Support multiselect in router endpoint * Fix the issue where app goes in embed mode after viewing embed once * Fix icons * Add router url tests * Add Responses download and form toggling tests * Add required validation test * Change Icons everywhere * App typeform app * Improvements in cli * Starting to move event types settings to tabs * Begin migration to single page form * Single page tabs * Limits Page * Advanced tab * Add RHF to dependancies * Add typeform how-to-use page * Add typeform how-to-use page and screenshots * Most of advanced tab * Solved RHF mismtach * Build fixes * RHF conditionals fixes * Improved legibility * Fix TS error * Add missing image * Update CliApp.tsx * Major refactor/organisation into optional V2 UI * Portal EditLocationModal * Fix dialoug form * Update imports * Auto Animate + custom inputs WIP * Custom Inputs * WIP Apps * Fixing stories imports * Stripe app * Remove duplicate dialog * Remove duplicate dialog * Major locations cleanup, 10s of bug fixes and app-store improvements * Fix missing pieces * More fixes * Fix embed URL * Fix app toggles + number of active apps * Fix container padding on disabledBorder prop * Removes strict * more fixes * EventType Team page WIP * Fix embed * NIT * Add Darkmode gray color * V2 Shell WIP * Fix headings on shell V2 * Fix mobile layout with V2 shell * V2 create event type button * Checked Team Select * Hidden to happen on save - not on toggle * Team Attendee Select animation * Fix scheduling type and remove multi select label * Fix overflow on teams url * Revert console * Revert api * Fix Embed TS errors * Fix TS errors * Fix Eslint errors * Fix TS errors for UI * Fix ESLINT error * Fix TS errors * Add missing import * Fix CLI * Add a default placeholder * Remove hardcoded daily:integrations * Fix message for payment page * Revert api and console to main * Update README * Fix TS errors * Fix Lint warnings * Fix Tests * Fix conflict issues * Fix conflict issues Co-authored-by: sean-brydon <55134778+sean-brydon@users.noreply.github.com> Co-authored-by: Peer Richelsen <peeroke@gmail.com> Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com> Co-authored-by: zomars <zomars@me.com>
2022-08-26 00:48:50 +00:00
import { DailyLocationType } from "@calcom/app-store/locations";
import { cancelScheduledJobs } from "@calcom/app-store/zapier/lib/nodeScheduler";
Change location of booking (#2658) * add functionality to change location in booking and send out mail * add i18n * change location with dropdown like in event-types * small fixes and code clean up * clean code * improve format of current Location string * clean code * clear selection when dialog closed * added mutation and changed props (first working verison) * clean code * clean code * clean code * clean code * fix typo * change maxHeight of select * use useWatch for selectedLocation * pass default values with props * set current location directly in useState * clear selected values when updating location * fix trpc query for credentialst * change icons for editing booking * improve naming of variables * remove unnecessary orderBy * use locationOptionsToString method * fix current location naming for Cal Video * add phone input * save phone number as location of booking * remove input field for phone number for event-types * fix redirection issue * show previous selected location in event-type * remove attendee number from selection for booking * make first letter of location lowercase * remove input field for attendee phone number * clear Errors when changing location type * set location details to optional * clean code * fixing issue that dropdown doesn't close when dialog opens * clean code * make overflow visibile in dialog * fix existing bug with address not showing in event-type settings * fix issue with losing focus after validation * close rejection dialog * small spelling fixes * fix issue with LocationChangeEmail * fix failing E2E test * fix failing E2E test * fix E2E test * bug fix for saving user phone, and other minor changes * merge main * improve text * fix UI of booking list * Delete admin * remove selection after update and submit * add translation for error message * add default values for checkbox * add "your phone number" to locations on booking page * remove duplicate attributes from viewer.bookings Co-authored-by: Omar López <zomars@me.com> * check if user is authorized to make changes to booking * remove location string * clan code for displayLocaitonPublicly checkbox * fetch locationOptions on server side * remove trpc query for credentials * fix phone number input * fix labels of host and attendee phone number for booking page * Migrates edit location to tRPC * Link elemnt should only be used in `a` tags * Adds missin router * Migrates locationOptions to tRPC query * Type fixes Co-authored-by: CarinaWolli <wollencarina@gmail.com> Co-authored-by: Alan <alannnc@gmail.com> Co-authored-by: Omar López <zomars@me.com> Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
2022-05-27 23:27:41 +00:00
import EventManager from "@calcom/core/EventManager";
import { CalendarEventBuilder } from "@calcom/core/builders/CalendarEvent/builder";
import { CalendarEventDirector } from "@calcom/core/builders/CalendarEvent/director";
import { deleteMeeting } from "@calcom/core/videoClient";
2022-06-28 20:40:58 +00:00
import dayjs from "@calcom/dayjs";
import { deleteScheduledEmailReminder } from "@calcom/ee/workflows/lib/reminders/emailReminderManager";
import { deleteScheduledSMSReminder } from "@calcom/ee/workflows/lib/reminders/smsReminderManager";
import { sendDeclinedEmails, sendLocationChangeEmails, sendRequestRescheduleEmail } from "@calcom/emails";
import { handleConfirmation } from "@calcom/features/bookings/lib/handleConfirmation";
import getWebhooks from "@calcom/features/webhooks/lib/getWebhooks";
import sendPayload from "@calcom/features/webhooks/lib/sendPayload";
import { isPrismaObjOrUndefined, parseRecurringEvent } from "@calcom/lib";
Change location of booking (#2658) * add functionality to change location in booking and send out mail * add i18n * change location with dropdown like in event-types * small fixes and code clean up * clean code * improve format of current Location string * clean code * clear selection when dialog closed * added mutation and changed props (first working verison) * clean code * clean code * clean code * clean code * fix typo * change maxHeight of select * use useWatch for selectedLocation * pass default values with props * set current location directly in useState * clear selected values when updating location * fix trpc query for credentialst * change icons for editing booking * improve naming of variables * remove unnecessary orderBy * use locationOptionsToString method * fix current location naming for Cal Video * add phone input * save phone number as location of booking * remove input field for phone number for event-types * fix redirection issue * show previous selected location in event-type * remove attendee number from selection for booking * make first letter of location lowercase * remove input field for attendee phone number * clear Errors when changing location type * set location details to optional * clean code * fixing issue that dropdown doesn't close when dialog opens * clean code * make overflow visibile in dialog * fix existing bug with address not showing in event-type settings * fix issue with losing focus after validation * close rejection dialog * small spelling fixes * fix issue with LocationChangeEmail * fix failing E2E test * fix failing E2E test * fix E2E test * bug fix for saving user phone, and other minor changes * merge main * improve text * fix UI of booking list * Delete admin * remove selection after update and submit * add translation for error message * add default values for checkbox * add "your phone number" to locations on booking page * remove duplicate attributes from viewer.bookings Co-authored-by: Omar López <zomars@me.com> * check if user is authorized to make changes to booking * remove location string * clan code for displayLocaitonPublicly checkbox * fetch locationOptions on server side * remove trpc query for credentials * fix phone number input * fix labels of host and attendee phone number for booking page * Migrates edit location to tRPC * Link elemnt should only be used in `a` tags * Adds missin router * Migrates locationOptions to tRPC query * Type fixes Co-authored-by: CarinaWolli <wollencarina@gmail.com> Co-authored-by: Alan <alannnc@gmail.com> Co-authored-by: Omar López <zomars@me.com> Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
2022-05-27 23:27:41 +00:00
import logger from "@calcom/lib/logger";
import { getTranslation } from "@calcom/lib/server";
import { bookingMinimalSelect } from "@calcom/prisma";
import { bookingConfirmPatchBodySchema } from "@calcom/prisma/zod-utils";
import type { AdditionalInformation, CalendarEvent, Person } from "@calcom/types/Calendar";
Change location of booking (#2658) * add functionality to change location in booking and send out mail * add i18n * change location with dropdown like in event-types * small fixes and code clean up * clean code * improve format of current Location string * clean code * clear selection when dialog closed * added mutation and changed props (first working verison) * clean code * clean code * clean code * clean code * fix typo * change maxHeight of select * use useWatch for selectedLocation * pass default values with props * set current location directly in useState * clear selected values when updating location * fix trpc query for credentialst * change icons for editing booking * improve naming of variables * remove unnecessary orderBy * use locationOptionsToString method * fix current location naming for Cal Video * add phone input * save phone number as location of booking * remove input field for phone number for event-types * fix redirection issue * show previous selected location in event-type * remove attendee number from selection for booking * make first letter of location lowercase * remove input field for attendee phone number * clear Errors when changing location type * set location details to optional * clean code * fixing issue that dropdown doesn't close when dialog opens * clean code * make overflow visibile in dialog * fix existing bug with address not showing in event-type settings * fix issue with losing focus after validation * close rejection dialog * small spelling fixes * fix issue with LocationChangeEmail * fix failing E2E test * fix failing E2E test * fix E2E test * bug fix for saving user phone, and other minor changes * merge main * improve text * fix UI of booking list * Delete admin * remove selection after update and submit * add translation for error message * add default values for checkbox * add "your phone number" to locations on booking page * remove duplicate attributes from viewer.bookings Co-authored-by: Omar López <zomars@me.com> * check if user is authorized to make changes to booking * remove location string * clan code for displayLocaitonPublicly checkbox * fetch locationOptions on server side * remove trpc query for credentials * fix phone number input * fix labels of host and attendee phone number for booking page * Migrates edit location to tRPC * Link elemnt should only be used in `a` tags * Adds missin router * Migrates locationOptions to tRPC query * Type fixes Co-authored-by: CarinaWolli <wollencarina@gmail.com> Co-authored-by: Alan <alannnc@gmail.com> Co-authored-by: Omar López <zomars@me.com> Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
2022-05-27 23:27:41 +00:00
import { TRPCError } from "@trpc/server";
import { authedProcedure, router } from "../../trpc";
export type PersonAttendeeCommonFields = Pick<
User,
"id" | "email" | "name" | "locale" | "timeZone" | "username"
>;
Change location of booking (#2658) * add functionality to change location in booking and send out mail * add i18n * change location with dropdown like in event-types * small fixes and code clean up * clean code * improve format of current Location string * clean code * clear selection when dialog closed * added mutation and changed props (first working verison) * clean code * clean code * clean code * clean code * fix typo * change maxHeight of select * use useWatch for selectedLocation * pass default values with props * set current location directly in useState * clear selected values when updating location * fix trpc query for credentialst * change icons for editing booking * improve naming of variables * remove unnecessary orderBy * use locationOptionsToString method * fix current location naming for Cal Video * add phone input * save phone number as location of booking * remove input field for phone number for event-types * fix redirection issue * show previous selected location in event-type * remove attendee number from selection for booking * make first letter of location lowercase * remove input field for attendee phone number * clear Errors when changing location type * set location details to optional * clean code * fixing issue that dropdown doesn't close when dialog opens * clean code * make overflow visibile in dialog * fix existing bug with address not showing in event-type settings * fix issue with losing focus after validation * close rejection dialog * small spelling fixes * fix issue with LocationChangeEmail * fix failing E2E test * fix failing E2E test * fix E2E test * bug fix for saving user phone, and other minor changes * merge main * improve text * fix UI of booking list * Delete admin * remove selection after update and submit * add translation for error message * add default values for checkbox * add "your phone number" to locations on booking page * remove duplicate attributes from viewer.bookings Co-authored-by: Omar López <zomars@me.com> * check if user is authorized to make changes to booking * remove location string * clan code for displayLocaitonPublicly checkbox * fetch locationOptions on server side * remove trpc query for credentials * fix phone number input * fix labels of host and attendee phone number for booking page * Migrates edit location to tRPC * Link elemnt should only be used in `a` tags * Adds missin router * Migrates locationOptions to tRPC query * Type fixes Co-authored-by: CarinaWolli <wollencarina@gmail.com> Co-authored-by: Alan <alannnc@gmail.com> Co-authored-by: Omar López <zomars@me.com> Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
2022-05-27 23:27:41 +00:00
// Common data for all endpoints under webhook
const commonBookingSchema = z.object({
bookingId: z.number(),
});
const bookingsProcedure = authedProcedure.input(commonBookingSchema).use(async ({ ctx, input, next }) => {
// Endpoints that just read the logged in user's data - like 'list' don't necessary have any input
const { bookingId } = input;
const booking = await ctx.prisma.booking.findFirst({
where: {
id: bookingId,
AND: [
{
OR: [
/* If user is organizer */
{ userId: ctx.user.id },
/* Or part of a collective booking */
{
eventType: {
schedulingType: SchedulingType.COLLECTIVE,
users: {
some: {
id: ctx.user.id,
},
},
},
},
],
},
],
},
include: {
attendees: true,
eventType: true,
destinationCalendar: true,
references: true,
user: {
include: {
destinationCalendar: true,
credentials: true,
},
},
},
});
if (!booking) throw new TRPCError({ code: "UNAUTHORIZED" });
return next({ ctx: { booking } });
});
export const bookingsRouter = router({
get: authedProcedure
.input(
z.object({
filters: z.object({
teamIds: z.number().array().optional(),
userIds: z.number().array().optional(),
status: z.enum(["upcoming", "recurring", "past", "cancelled", "unconfirmed"]),
eventTypeIds: z.number().array().optional(),
}),
limit: z.number().min(1).max(100).nullish(),
cursor: z.number().nullish(), // <-- "cursor" needs to exist when using useInfiniteQuery, but can be any type
})
)
.query(async ({ ctx, input }) => {
// using offset actually because cursor pagination requires a unique column
// for orderBy, but we don't use a unique column in our orderBy
const take = input.limit ?? 10;
const skip = input.cursor ?? 0;
const { prisma, user } = ctx;
const bookingListingByStatus = input.filters.status;
const bookingListingFilters: Record<typeof bookingListingByStatus, Prisma.BookingWhereInput> = {
upcoming: {
endTime: { gte: new Date() },
// These changes are needed to not show confirmed recurring events,
// as rescheduling or cancel for recurring event bookings should be
// handled separately for each occurrence
OR: [
{
recurringEventId: { not: null },
status: { notIn: [BookingStatus.PENDING, BookingStatus.CANCELLED, BookingStatus.REJECTED] },
},
{
recurringEventId: { equals: null },
status: { notIn: [BookingStatus.CANCELLED, BookingStatus.REJECTED] },
},
],
},
recurring: {
endTime: { gte: new Date() },
AND: [
{ NOT: { recurringEventId: { equals: null } } },
{ status: { notIn: [BookingStatus.CANCELLED, BookingStatus.REJECTED] } },
],
},
past: {
endTime: { lte: new Date() },
AND: [
{ NOT: { status: { equals: BookingStatus.CANCELLED } } },
{ NOT: { status: { equals: BookingStatus.REJECTED } } },
],
},
cancelled: {
OR: [
{ status: { equals: BookingStatus.CANCELLED } },
{ status: { equals: BookingStatus.REJECTED } },
],
},
unconfirmed: {
endTime: { gte: new Date() },
OR: [
{
recurringEventId: { not: null },
status: { equals: BookingStatus.PENDING },
},
{
status: { equals: BookingStatus.PENDING },
},
],
},
};
const bookingListingOrderby: Record<
typeof bookingListingByStatus,
Prisma.BookingOrderByWithAggregationInput
> = {
upcoming: { startTime: "asc" },
recurring: { startTime: "asc" },
past: { startTime: "desc" },
cancelled: { startTime: "desc" },
unconfirmed: { startTime: "asc" },
};
// TODO: Fix record typing
const bookingWhereInputFilters: Record<string, Prisma.BookingWhereInput> = {
teamIds: {
AND: [
{
eventType: {
team: {
id: {
in: input.filters?.teamIds,
},
},
},
},
],
},
userIds: {
AND: [
{
eventType: {
users: {
some: {
id: {
in: input.filters?.userIds,
},
},
},
},
},
],
},
};
const filtersCombined: Prisma.BookingWhereInput[] =
input.filters &&
Object.keys(input.filters).map((key) => {
return bookingWhereInputFilters[key];
});
const passedBookingsStatusFilter = bookingListingFilters[bookingListingByStatus];
const orderBy = bookingListingOrderby[bookingListingByStatus];
const bookingsQuery = await prisma.booking.findMany({
where: {
OR: [
{
userId: user.id,
},
{
attendees: {
some: {
email: user.email,
},
},
},
{
eventType: {
team: {
members: {
some: {
userId: user.id,
role: {
in: ["ADMIN", "OWNER"],
},
},
},
},
},
},
],
AND: [passedBookingsStatusFilter, ...(filtersCombined ?? [])],
},
select: {
...bookingMinimalSelect,
uid: true,
recurringEventId: true,
location: true,
eventType: {
select: {
slug: true,
id: true,
eventName: true,
price: true,
recurringEvent: true,
team: {
select: {
name: true,
},
},
},
},
status: true,
paid: true,
user: {
select: {
id: true,
name: true,
email: true,
},
},
rescheduled: true,
Cal Video (Daily) Recording (#6039) * feat: wip Signed-off-by: Udit Takkar <udit.07814802719@cse.mait.ac.in> * feat: add download recording button Signed-off-by: Udit Takkar <udit.07814802719@cse.mait.ac.in> * moved video recording into /ee/, wrapped in LicenseRequired * fix: security issues in downloading recording updates designs Signed-off-by: Udit Takkar <udit.07814802719@cse.mait.ac.in> * feat: add upgradation banner Signed-off-by: Udit Takkar <udit.07814802719@cse.mait.ac.in> * chore: remove default room Signed-off-by: Udit Takkar <udit.07814802719@cse.mait.ac.in> * chore: fix type error Signed-off-by: Udit Takkar <udit.07814802719@cse.mait.ac.in> * fix: add type in get recording Signed-off-by: Udit Takkar <udit.07814802719@cse.mait.ac.in> * fix: add suggestions and zod type for recording Signed-off-by: Udit Takkar <udit.07814802719@cse.mait.ac.in> * fix: add types in getRecordings Signed-off-by: Udit Takkar <udit.07814802719@cse.mait.ac.in> * fix: type error Signed-off-by: Udit Takkar <udit.07814802719@cse.mait.ac.in> * fix: type error Signed-off-by: Udit Takkar <udit.07814802719@cse.mait.ac.in> * fix: finally all type errors fixed Signed-off-by: Udit Takkar <udit.07814802719@cse.mait.ac.in> * Server side validation for users in team plans for recordings * fix: remove any type Signed-off-by: Udit Takkar <udit.07814802719@cse.mait.ac.in> * fix: type error Signed-off-by: Udit Takkar <udit.07814802719@cse.mait.ac.in> Signed-off-by: Udit Takkar <udit.07814802719@cse.mait.ac.in> Co-authored-by: Peer Richelsen <peeroke@gmail.com> Co-authored-by: Peer Richelsen <peer@cal.com> Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com> Co-authored-by: Alan <alannnc@gmail.com>
2022-12-27 21:03:39 +00:00
references: true,
},
orderBy,
take: take + 1,
skip,
});
const recurringInfoBasic = await prisma.booking.groupBy({
by: ["recurringEventId"],
_min: {
startTime: true,
},
_count: {
recurringEventId: true,
},
where: {
recurringEventId: {
not: { equals: null },
},
userId: user.id,
},
});
const recurringInfoExtended = await prisma.booking.groupBy({
by: ["recurringEventId", "status", "startTime"],
_min: {
startTime: true,
},
where: {
recurringEventId: {
not: { equals: null },
},
userId: user.id,
},
});
const recurringInfo = recurringInfoBasic.map(
(
2023-03-02 18:23:33 +00:00
info: (typeof recurringInfoBasic)[number]
): {
recurringEventId: string | null;
count: number;
firstDate: Date | null;
bookings: {
[key: string]: Date[];
};
} => {
const bookings = recurringInfoExtended
.filter((ext) => ext.recurringEventId === info.recurringEventId)
.reduce(
(prev, curr) => {
prev[curr.status].push(curr.startTime);
return prev;
},
{ ACCEPTED: [], CANCELLED: [], REJECTED: [], PENDING: [] } as {
[key in BookingStatus]: Date[];
}
);
return {
recurringEventId: info.recurringEventId,
count: info._count.recurringEventId,
firstDate: info._min.startTime,
bookings,
};
}
);
const bookings = bookingsQuery.map((booking) => {
return {
...booking,
eventType: {
...booking.eventType,
recurringEvent: parseRecurringEvent(booking.eventType?.recurringEvent),
},
startTime: booking.startTime.toISOString(),
endTime: booking.endTime.toISOString(),
};
});
const bookingsFetched = bookings.length;
let nextCursor: typeof skip | null = skip;
if (bookingsFetched > take) {
nextCursor += bookingsFetched;
} else {
nextCursor = null;
}
return {
bookings,
recurringInfo,
nextCursor,
};
}),
requestReschedule: authedProcedure
.input(
z.object({
bookingId: z.string(),
rescheduleReason: z.string().optional(),
})
)
.mutation(async ({ ctx, input }) => {
const { user, prisma } = ctx;
const { bookingId, rescheduleReason: cancellationReason } = input;
const bookingToReschedule = await prisma.booking.findFirstOrThrow({
select: {
id: true,
uid: true,
userId: true,
title: true,
description: true,
startTime: true,
endTime: true,
eventTypeId: true,
eventType: true,
location: true,
attendees: true,
references: true,
customInputs: true,
dynamicEventSlugRef: true,
dynamicGroupSlugRef: true,
destinationCalendar: true,
smsReminderNumber: true,
scheduledJobs: true,
workflowReminders: true,
},
where: {
uid: bookingId,
NOT: {
status: {
in: [BookingStatus.CANCELLED, BookingStatus.REJECTED],
},
},
},
});
if (!bookingToReschedule.userId) {
throw new TRPCError({ code: "FORBIDDEN", message: "Booking to reschedule doesn't have an owner" });
}
if (!bookingToReschedule.eventType) {
throw new TRPCError({ code: "FORBIDDEN", message: "EventType not found for current booking." });
}
const bookingBelongsToTeam = !!bookingToReschedule.eventType?.teamId;
const userTeams = await prisma.user.findUniqueOrThrow({
where: {
id: user.id,
},
select: {
teams: true,
},
});
if (bookingBelongsToTeam && bookingToReschedule.eventType?.teamId) {
const userTeamIds = userTeams.teams.map((item) => item.teamId);
if (userTeamIds.indexOf(bookingToReschedule?.eventType?.teamId) === -1) {
throw new TRPCError({ code: "FORBIDDEN", message: "User isn't a member on the team" });
}
}
if (!bookingBelongsToTeam && bookingToReschedule.userId !== user.id) {
throw new TRPCError({ code: "FORBIDDEN", message: "User isn't owner of the current booking" });
}
if (bookingToReschedule) {
let event: Partial<EventType> = {};
if (bookingToReschedule.eventTypeId) {
event = await prisma.eventType.findFirstOrThrow({
select: {
title: true,
users: true,
schedulingType: true,
recurringEvent: true,
},
where: {
id: bookingToReschedule.eventTypeId,
},
});
}
await prisma.booking.update({
where: {
id: bookingToReschedule.id,
},
data: {
rescheduled: true,
cancellationReason,
status: BookingStatus.CANCELLED,
updatedAt: dayjs().toISOString(),
},
});
// delete scheduled jobs of previous booking
cancelScheduledJobs(bookingToReschedule);
//cancel workflow reminders of previous booking
bookingToReschedule.workflowReminders.forEach((reminder) => {
if (reminder.method === WorkflowMethods.EMAIL) {
deleteScheduledEmailReminder(reminder.id, reminder.referenceId);
} else if (reminder.method === WorkflowMethods.SMS) {
deleteScheduledSMSReminder(reminder.id, reminder.referenceId);
}
});
const [mainAttendee] = bookingToReschedule.attendees;
// @NOTE: Should we assume attendees language?
const tAttendees = await getTranslation(mainAttendee.locale ?? "en", "common");
const usersToPeopleType = (
users: PersonAttendeeCommonFields[],
selectedLanguage: TFunction
): Person[] => {
return users?.map((user) => {
return {
email: user.email || "",
name: user.name || "",
username: user?.username || "",
language: { translate: selectedLanguage, locale: user.locale || "en" },
timeZone: user?.timeZone,
};
});
};
const userTranslation = await getTranslation(user.locale ?? "en", "common");
const [userAsPeopleType] = usersToPeopleType([user], userTranslation);
const builder = new CalendarEventBuilder();
builder.init({
title: bookingToReschedule.title,
type: event && event.title ? event.title : bookingToReschedule.title,
startTime: bookingToReschedule.startTime.toISOString(),
endTime: bookingToReschedule.endTime.toISOString(),
attendees: usersToPeopleType(
// username field doesn't exists on attendee but could be in the future
bookingToReschedule.attendees as unknown as PersonAttendeeCommonFields[],
tAttendees
),
organizer: userAsPeopleType,
});
const director = new CalendarEventDirector();
director.setBuilder(builder);
director.setExistingBooking(bookingToReschedule);
cancellationReason && director.setCancellationReason(cancellationReason);
if (event) {
await director.buildForRescheduleEmail();
} else {
await director.buildWithoutEventTypeForRescheduleEmail();
}
// Handling calendar and videos cancellation
// This can set previous time as available, until virtual calendar is done
const credentialsMap = new Map();
user.credentials.forEach((credential) => {
credentialsMap.set(credential.type, credential);
});
const bookingRefsFiltered: BookingReference[] = bookingToReschedule.references.filter(
(ref) => !!credentialsMap.get(ref.type)
);
bookingRefsFiltered.forEach((bookingRef) => {
if (bookingRef.uid) {
if (bookingRef.type.endsWith("_calendar")) {
const calendar = getCalendar(credentialsMap.get(bookingRef.type));
return calendar?.deleteEvent(
bookingRef.uid,
builder.calendarEvent,
bookingRef.externalCalendarId
);
} else if (bookingRef.type.endsWith("_video")) {
return deleteMeeting(credentialsMap.get(bookingRef.type), bookingRef.uid);
}
}
});
// Send emails
await sendRequestRescheduleEmail(builder.calendarEvent, {
rescheduleLink: builder.rescheduleLink,
});
const evt: CalendarEvent = {
title: bookingToReschedule?.title,
type: event && event.title ? event.title : bookingToReschedule.title,
description: bookingToReschedule?.description || "",
customInputs: isPrismaObjOrUndefined(bookingToReschedule.customInputs),
startTime: bookingToReschedule?.startTime ? dayjs(bookingToReschedule.startTime).format() : "",
endTime: bookingToReschedule?.endTime ? dayjs(bookingToReschedule.endTime).format() : "",
organizer: userAsPeopleType,
attendees: usersToPeopleType(
// username field doesn't exists on attendee but could be in the future
bookingToReschedule.attendees as unknown as PersonAttendeeCommonFields[],
tAttendees
),
uid: bookingToReschedule?.uid,
location: bookingToReschedule?.location,
destinationCalendar:
bookingToReschedule?.destinationCalendar || bookingToReschedule?.destinationCalendar,
cancellationReason: `Please reschedule. ${cancellationReason}`, // TODO::Add i18-next for this
};
// Send webhook
const eventTrigger: WebhookTriggerEvents = "BOOKING_CANCELLED";
// Send Webhook call if hooked to BOOKING.CANCELLED
const subscriberOptions = {
userId: bookingToReschedule.userId,
eventTypeId: (bookingToReschedule.eventTypeId as number) || 0,
triggerEvent: eventTrigger,
};
const webhooks = await getWebhooks(subscriberOptions);
const promises = webhooks.map((webhook) =>
sendPayload(webhook.secret, eventTrigger, new Date().toISOString(), webhook, {
...evt,
smsReminderNumber: bookingToReschedule.smsReminderNumber || undefined,
}).catch((e) => {
console.error(
`Error executing webhook for event: ${eventTrigger}, URL: ${webhook.subscriberUrl}`,
e
);
})
);
await Promise.all(promises);
}
Change location of booking (#2658) * add functionality to change location in booking and send out mail * add i18n * change location with dropdown like in event-types * small fixes and code clean up * clean code * improve format of current Location string * clean code * clear selection when dialog closed * added mutation and changed props (first working verison) * clean code * clean code * clean code * clean code * fix typo * change maxHeight of select * use useWatch for selectedLocation * pass default values with props * set current location directly in useState * clear selected values when updating location * fix trpc query for credentialst * change icons for editing booking * improve naming of variables * remove unnecessary orderBy * use locationOptionsToString method * fix current location naming for Cal Video * add phone input * save phone number as location of booking * remove input field for phone number for event-types * fix redirection issue * show previous selected location in event-type * remove attendee number from selection for booking * make first letter of location lowercase * remove input field for attendee phone number * clear Errors when changing location type * set location details to optional * clean code * fixing issue that dropdown doesn't close when dialog opens * clean code * make overflow visibile in dialog * fix existing bug with address not showing in event-type settings * fix issue with losing focus after validation * close rejection dialog * small spelling fixes * fix issue with LocationChangeEmail * fix failing E2E test * fix failing E2E test * fix E2E test * bug fix for saving user phone, and other minor changes * merge main * improve text * fix UI of booking list * Delete admin * remove selection after update and submit * add translation for error message * add default values for checkbox * add "your phone number" to locations on booking page * remove duplicate attributes from viewer.bookings Co-authored-by: Omar López <zomars@me.com> * check if user is authorized to make changes to booking * remove location string * clan code for displayLocaitonPublicly checkbox * fetch locationOptions on server side * remove trpc query for credentials * fix phone number input * fix labels of host and attendee phone number for booking page * Migrates edit location to tRPC * Link elemnt should only be used in `a` tags * Adds missin router * Migrates locationOptions to tRPC query * Type fixes Co-authored-by: CarinaWolli <wollencarina@gmail.com> Co-authored-by: Alan <alannnc@gmail.com> Co-authored-by: Omar López <zomars@me.com> Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
2022-05-27 23:27:41 +00:00
}),
editLocation: bookingsProcedure
.input(
commonBookingSchema.extend({
newLocation: z.string().transform((val) => val || DailyLocationType),
})
)
.mutation(async ({ ctx, input }) => {
Change location of booking (#2658) * add functionality to change location in booking and send out mail * add i18n * change location with dropdown like in event-types * small fixes and code clean up * clean code * improve format of current Location string * clean code * clear selection when dialog closed * added mutation and changed props (first working verison) * clean code * clean code * clean code * clean code * fix typo * change maxHeight of select * use useWatch for selectedLocation * pass default values with props * set current location directly in useState * clear selected values when updating location * fix trpc query for credentialst * change icons for editing booking * improve naming of variables * remove unnecessary orderBy * use locationOptionsToString method * fix current location naming for Cal Video * add phone input * save phone number as location of booking * remove input field for phone number for event-types * fix redirection issue * show previous selected location in event-type * remove attendee number from selection for booking * make first letter of location lowercase * remove input field for attendee phone number * clear Errors when changing location type * set location details to optional * clean code * fixing issue that dropdown doesn't close when dialog opens * clean code * make overflow visibile in dialog * fix existing bug with address not showing in event-type settings * fix issue with losing focus after validation * close rejection dialog * small spelling fixes * fix issue with LocationChangeEmail * fix failing E2E test * fix failing E2E test * fix E2E test * bug fix for saving user phone, and other minor changes * merge main * improve text * fix UI of booking list * Delete admin * remove selection after update and submit * add translation for error message * add default values for checkbox * add "your phone number" to locations on booking page * remove duplicate attributes from viewer.bookings Co-authored-by: Omar López <zomars@me.com> * check if user is authorized to make changes to booking * remove location string * clan code for displayLocaitonPublicly checkbox * fetch locationOptions on server side * remove trpc query for credentials * fix phone number input * fix labels of host and attendee phone number for booking page * Migrates edit location to tRPC * Link elemnt should only be used in `a` tags * Adds missin router * Migrates locationOptions to tRPC query * Type fixes Co-authored-by: CarinaWolli <wollencarina@gmail.com> Co-authored-by: Alan <alannnc@gmail.com> Co-authored-by: Omar López <zomars@me.com> Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
2022-05-27 23:27:41 +00:00
const { bookingId, newLocation: location } = input;
const { booking } = ctx;
try {
const organizer = await ctx.prisma.user.findFirstOrThrow({
Change location of booking (#2658) * add functionality to change location in booking and send out mail * add i18n * change location with dropdown like in event-types * small fixes and code clean up * clean code * improve format of current Location string * clean code * clear selection when dialog closed * added mutation and changed props (first working verison) * clean code * clean code * clean code * clean code * fix typo * change maxHeight of select * use useWatch for selectedLocation * pass default values with props * set current location directly in useState * clear selected values when updating location * fix trpc query for credentialst * change icons for editing booking * improve naming of variables * remove unnecessary orderBy * use locationOptionsToString method * fix current location naming for Cal Video * add phone input * save phone number as location of booking * remove input field for phone number for event-types * fix redirection issue * show previous selected location in event-type * remove attendee number from selection for booking * make first letter of location lowercase * remove input field for attendee phone number * clear Errors when changing location type * set location details to optional * clean code * fixing issue that dropdown doesn't close when dialog opens * clean code * make overflow visibile in dialog * fix existing bug with address not showing in event-type settings * fix issue with losing focus after validation * close rejection dialog * small spelling fixes * fix issue with LocationChangeEmail * fix failing E2E test * fix failing E2E test * fix E2E test * bug fix for saving user phone, and other minor changes * merge main * improve text * fix UI of booking list * Delete admin * remove selection after update and submit * add translation for error message * add default values for checkbox * add "your phone number" to locations on booking page * remove duplicate attributes from viewer.bookings Co-authored-by: Omar López <zomars@me.com> * check if user is authorized to make changes to booking * remove location string * clan code for displayLocaitonPublicly checkbox * fetch locationOptions on server side * remove trpc query for credentials * fix phone number input * fix labels of host and attendee phone number for booking page * Migrates edit location to tRPC * Link elemnt should only be used in `a` tags * Adds missin router * Migrates locationOptions to tRPC query * Type fixes Co-authored-by: CarinaWolli <wollencarina@gmail.com> Co-authored-by: Alan <alannnc@gmail.com> Co-authored-by: Omar López <zomars@me.com> Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
2022-05-27 23:27:41 +00:00
where: {
id: booking.userId || 0,
},
select: {
name: true,
email: true,
timeZone: true,
locale: true,
},
});
const tOrganizer = await getTranslation(organizer.locale ?? "en", "common");
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 = {
title: booking.title || "",
type: (booking.eventType?.title as string) || booking?.title || "",
description: booking.description || "",
startTime: booking.startTime ? dayjs(booking.startTime).format() : "",
endTime: booking.endTime ? dayjs(booking.endTime).format() : "",
organizer: {
email: organizer.email,
name: organizer.name ?? "Nameless",
timeZone: organizer.timeZone,
language: { translate: tOrganizer, locale: organizer.locale ?? "en" },
},
attendees: attendeesList,
uid: booking.uid,
recurringEvent: parseRecurringEvent(booking.eventType?.recurringEvent),
Change location of booking (#2658) * add functionality to change location in booking and send out mail * add i18n * change location with dropdown like in event-types * small fixes and code clean up * clean code * improve format of current Location string * clean code * clear selection when dialog closed * added mutation and changed props (first working verison) * clean code * clean code * clean code * clean code * fix typo * change maxHeight of select * use useWatch for selectedLocation * pass default values with props * set current location directly in useState * clear selected values when updating location * fix trpc query for credentialst * change icons for editing booking * improve naming of variables * remove unnecessary orderBy * use locationOptionsToString method * fix current location naming for Cal Video * add phone input * save phone number as location of booking * remove input field for phone number for event-types * fix redirection issue * show previous selected location in event-type * remove attendee number from selection for booking * make first letter of location lowercase * remove input field for attendee phone number * clear Errors when changing location type * set location details to optional * clean code * fixing issue that dropdown doesn't close when dialog opens * clean code * make overflow visibile in dialog * fix existing bug with address not showing in event-type settings * fix issue with losing focus after validation * close rejection dialog * small spelling fixes * fix issue with LocationChangeEmail * fix failing E2E test * fix failing E2E test * fix E2E test * bug fix for saving user phone, and other minor changes * merge main * improve text * fix UI of booking list * Delete admin * remove selection after update and submit * add translation for error message * add default values for checkbox * add "your phone number" to locations on booking page * remove duplicate attributes from viewer.bookings Co-authored-by: Omar López <zomars@me.com> * check if user is authorized to make changes to booking * remove location string * clan code for displayLocaitonPublicly checkbox * fetch locationOptions on server side * remove trpc query for credentials * fix phone number input * fix labels of host and attendee phone number for booking page * Migrates edit location to tRPC * Link elemnt should only be used in `a` tags * Adds missin router * Migrates locationOptions to tRPC query * Type fixes Co-authored-by: CarinaWolli <wollencarina@gmail.com> Co-authored-by: Alan <alannnc@gmail.com> Co-authored-by: Omar López <zomars@me.com> Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
2022-05-27 23:27:41 +00:00
location,
destinationCalendar: booking?.destinationCalendar || booking?.user?.destinationCalendar,
};
const eventManager = new EventManager(ctx.user);
const updatedResult = await eventManager.updateLocation(evt, booking);
const results = updatedResult.results;
Change location of booking (#2658) * add functionality to change location in booking and send out mail * add i18n * change location with dropdown like in event-types * small fixes and code clean up * clean code * improve format of current Location string * clean code * clear selection when dialog closed * added mutation and changed props (first working verison) * clean code * clean code * clean code * clean code * fix typo * change maxHeight of select * use useWatch for selectedLocation * pass default values with props * set current location directly in useState * clear selected values when updating location * fix trpc query for credentialst * change icons for editing booking * improve naming of variables * remove unnecessary orderBy * use locationOptionsToString method * fix current location naming for Cal Video * add phone input * save phone number as location of booking * remove input field for phone number for event-types * fix redirection issue * show previous selected location in event-type * remove attendee number from selection for booking * make first letter of location lowercase * remove input field for attendee phone number * clear Errors when changing location type * set location details to optional * clean code * fixing issue that dropdown doesn't close when dialog opens * clean code * make overflow visibile in dialog * fix existing bug with address not showing in event-type settings * fix issue with losing focus after validation * close rejection dialog * small spelling fixes * fix issue with LocationChangeEmail * fix failing E2E test * fix failing E2E test * fix E2E test * bug fix for saving user phone, and other minor changes * merge main * improve text * fix UI of booking list * Delete admin * remove selection after update and submit * add translation for error message * add default values for checkbox * add "your phone number" to locations on booking page * remove duplicate attributes from viewer.bookings Co-authored-by: Omar López <zomars@me.com> * check if user is authorized to make changes to booking * remove location string * clan code for displayLocaitonPublicly checkbox * fetch locationOptions on server side * remove trpc query for credentials * fix phone number input * fix labels of host and attendee phone number for booking page * Migrates edit location to tRPC * Link elemnt should only be used in `a` tags * Adds missin router * Migrates locationOptions to tRPC query * Type fixes Co-authored-by: CarinaWolli <wollencarina@gmail.com> Co-authored-by: Alan <alannnc@gmail.com> Co-authored-by: Omar López <zomars@me.com> Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
2022-05-27 23:27:41 +00:00
if (results.length > 0 && results.every((res) => !res.success)) {
const error = {
errorCode: "BookingUpdateLocationFailed",
message: "Updating location failed",
};
logger.error(`Booking ${ctx.user.username} failed`, error, results);
} else {
await ctx.prisma.booking.update({
where: {
id: bookingId,
},
data: {
location,
references: {
create: updatedResult.referencesToCreate,
},
},
});
const metadata: AdditionalInformation = {};
Change location of booking (#2658) * add functionality to change location in booking and send out mail * add i18n * change location with dropdown like in event-types * small fixes and code clean up * clean code * improve format of current Location string * clean code * clear selection when dialog closed * added mutation and changed props (first working verison) * clean code * clean code * clean code * clean code * fix typo * change maxHeight of select * use useWatch for selectedLocation * pass default values with props * set current location directly in useState * clear selected values when updating location * fix trpc query for credentialst * change icons for editing booking * improve naming of variables * remove unnecessary orderBy * use locationOptionsToString method * fix current location naming for Cal Video * add phone input * save phone number as location of booking * remove input field for phone number for event-types * fix redirection issue * show previous selected location in event-type * remove attendee number from selection for booking * make first letter of location lowercase * remove input field for attendee phone number * clear Errors when changing location type * set location details to optional * clean code * fixing issue that dropdown doesn't close when dialog opens * clean code * make overflow visibile in dialog * fix existing bug with address not showing in event-type settings * fix issue with losing focus after validation * close rejection dialog * small spelling fixes * fix issue with LocationChangeEmail * fix failing E2E test * fix failing E2E test * fix E2E test * bug fix for saving user phone, and other minor changes * merge main * improve text * fix UI of booking list * Delete admin * remove selection after update and submit * add translation for error message * add default values for checkbox * add "your phone number" to locations on booking page * remove duplicate attributes from viewer.bookings Co-authored-by: Omar López <zomars@me.com> * check if user is authorized to make changes to booking * remove location string * clan code for displayLocaitonPublicly checkbox * fetch locationOptions on server side * remove trpc query for credentials * fix phone number input * fix labels of host and attendee phone number for booking page * Migrates edit location to tRPC * Link elemnt should only be used in `a` tags * Adds missin router * Migrates locationOptions to tRPC query * Type fixes Co-authored-by: CarinaWolli <wollencarina@gmail.com> Co-authored-by: Alan <alannnc@gmail.com> Co-authored-by: Omar López <zomars@me.com> Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
2022-05-27 23:27:41 +00:00
if (results.length) {
metadata.hangoutLink = results[0].updatedEvent?.hangoutLink;
metadata.conferenceData = results[0].updatedEvent?.conferenceData;
metadata.entryPoints = results[0].updatedEvent?.entryPoints;
Change location of booking (#2658) * add functionality to change location in booking and send out mail * add i18n * change location with dropdown like in event-types * small fixes and code clean up * clean code * improve format of current Location string * clean code * clear selection when dialog closed * added mutation and changed props (first working verison) * clean code * clean code * clean code * clean code * fix typo * change maxHeight of select * use useWatch for selectedLocation * pass default values with props * set current location directly in useState * clear selected values when updating location * fix trpc query for credentialst * change icons for editing booking * improve naming of variables * remove unnecessary orderBy * use locationOptionsToString method * fix current location naming for Cal Video * add phone input * save phone number as location of booking * remove input field for phone number for event-types * fix redirection issue * show previous selected location in event-type * remove attendee number from selection for booking * make first letter of location lowercase * remove input field for attendee phone number * clear Errors when changing location type * set location details to optional * clean code * fixing issue that dropdown doesn't close when dialog opens * clean code * make overflow visibile in dialog * fix existing bug with address not showing in event-type settings * fix issue with losing focus after validation * close rejection dialog * small spelling fixes * fix issue with LocationChangeEmail * fix failing E2E test * fix failing E2E test * fix E2E test * bug fix for saving user phone, and other minor changes * merge main * improve text * fix UI of booking list * Delete admin * remove selection after update and submit * add translation for error message * add default values for checkbox * add "your phone number" to locations on booking page * remove duplicate attributes from viewer.bookings Co-authored-by: Omar López <zomars@me.com> * check if user is authorized to make changes to booking * remove location string * clan code for displayLocaitonPublicly checkbox * fetch locationOptions on server side * remove trpc query for credentials * fix phone number input * fix labels of host and attendee phone number for booking page * Migrates edit location to tRPC * Link elemnt should only be used in `a` tags * Adds missin router * Migrates locationOptions to tRPC query * Type fixes Co-authored-by: CarinaWolli <wollencarina@gmail.com> Co-authored-by: Alan <alannnc@gmail.com> Co-authored-by: Omar López <zomars@me.com> Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
2022-05-27 23:27:41 +00:00
}
try {
await sendLocationChangeEmails({ ...evt, additionalInformation: metadata });
Change location of booking (#2658) * add functionality to change location in booking and send out mail * add i18n * change location with dropdown like in event-types * small fixes and code clean up * clean code * improve format of current Location string * clean code * clear selection when dialog closed * added mutation and changed props (first working verison) * clean code * clean code * clean code * clean code * fix typo * change maxHeight of select * use useWatch for selectedLocation * pass default values with props * set current location directly in useState * clear selected values when updating location * fix trpc query for credentialst * change icons for editing booking * improve naming of variables * remove unnecessary orderBy * use locationOptionsToString method * fix current location naming for Cal Video * add phone input * save phone number as location of booking * remove input field for phone number for event-types * fix redirection issue * show previous selected location in event-type * remove attendee number from selection for booking * make first letter of location lowercase * remove input field for attendee phone number * clear Errors when changing location type * set location details to optional * clean code * fixing issue that dropdown doesn't close when dialog opens * clean code * make overflow visibile in dialog * fix existing bug with address not showing in event-type settings * fix issue with losing focus after validation * close rejection dialog * small spelling fixes * fix issue with LocationChangeEmail * fix failing E2E test * fix failing E2E test * fix E2E test * bug fix for saving user phone, and other minor changes * merge main * improve text * fix UI of booking list * Delete admin * remove selection after update and submit * add translation for error message * add default values for checkbox * add "your phone number" to locations on booking page * remove duplicate attributes from viewer.bookings Co-authored-by: Omar López <zomars@me.com> * check if user is authorized to make changes to booking * remove location string * clan code for displayLocaitonPublicly checkbox * fetch locationOptions on server side * remove trpc query for credentials * fix phone number input * fix labels of host and attendee phone number for booking page * Migrates edit location to tRPC * Link elemnt should only be used in `a` tags * Adds missin router * Migrates locationOptions to tRPC query * Type fixes Co-authored-by: CarinaWolli <wollencarina@gmail.com> Co-authored-by: Alan <alannnc@gmail.com> Co-authored-by: Omar López <zomars@me.com> Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
2022-05-27 23:27:41 +00:00
} catch (error) {
console.log("Error sending LocationChangeEmails");
}
}
} catch {
throw new TRPCError({ code: "INTERNAL_SERVER_ERROR" });
}
return { message: "Location updated" };
}),
confirm: bookingsProcedure.input(bookingConfirmPatchBodySchema).mutation(async ({ ctx, input }) => {
const { user, prisma } = ctx;
const { bookingId, recurringEventId, reason: rejectionReason, confirmed } = input;
const tOrganizer = await getTranslation(user.locale ?? "en", "common");
2022-12-22 00:48:15 +00:00
const booking = await prisma.booking.findUniqueOrThrow({
where: {
id: bookingId,
},
select: {
title: true,
description: true,
customInputs: true,
startTime: true,
endTime: true,
attendees: true,
eventTypeId: true,
eventType: {
select: {
id: true,
feat/payment-service-6438-cal-767 (#6677) * WIP paymentService * Changes for payment Service * Fix for stripe payment flow * Remove logs/comments * Refactored refund for stripe app * Move stripe handlePayment to own lib * Move stripe delete payments to paymentService * lint fix * Change handleRefundError as generic function * remove log * remove logs * remove logs * Return stripe default export to lib/server * Fixing types * Fix types * Upgrades typescript * Update yarn lock * Typings * Hotfix: ping,riverside,whereby and around not showing up in list (#6712) * Hotfix: ping,riverside,whereby and around not showing up in list (#6712) (#6713) * Adds deployment settings to DB (#6706) * WIP * Adds DeploymentTheme * Add missing migrations * Adds client extensions for deployment * Cleanup * Revert "lint fix" This reverts commit e1a2e4a357e58e6673c47399888ae2e00d1351a6. * Add validation * Revert changes removed in force push * Removing abstract class and just leaving interface implementation * Fix types for handlePayments * Fix payment test appStore import * Fix stripe metadata in event type * Move migration to separate PR * Revert "Move migration to separate PR" This reverts commit 48aa64e0724a522d3cc2fefaaaee5792ee9cd9e6. * Update packages/prisma/migrations/20230125175109_remove_type_from_payment_and_add_app_relationship/migration.sql Co-authored-by: Omar López <zomars@me.com> --------- Co-authored-by: zomars <zomars@me.com> Co-authored-by: Hariom Balhara <hariombalhara@gmail.com>
2023-02-08 20:36:22 +00:00
owner: true,
teamId: true,
recurringEvent: true,
title: true,
requiresConfirmation: true,
currency: true,
length: true,
description: true,
price: 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,
scheduledJobs: true,
},
});
const authorized = async () => {
// if the organizer
if (booking.userId === user.id) {
return true;
}
const eventType = await prisma.eventType.findUnique({
where: {
id: booking.eventTypeId || undefined,
},
select: {
id: true,
schedulingType: true,
users: true,
},
});
if (
eventType?.schedulingType === SchedulingType.COLLECTIVE &&
eventType.users.find((user) => user.id === user.id)
) {
return true;
}
return false;
};
if (!(await authorized())) throw new TRPCError({ code: "UNAUTHORIZED", message: "UNAUTHORIZED" });
const isConfirmed = booking.status === BookingStatus.ACCEPTED;
if (isConfirmed) throw new TRPCError({ code: "BAD_REQUEST", message: "Booking already confirmed" });
// If booking requires payment and is not paid, we don't allow confirmation
if (confirmed && booking.payment.length > 0 && !booking.paid) {
await prisma.booking.update({
where: {
id: bookingId,
},
data: {
status: BookingStatus.ACCEPTED,
},
});
return { message: "Booking confirmed", status: BookingStatus.ACCEPTED };
}
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.eventType?.title || booking.title,
title: booking.title,
description: booking.description,
customInputs: isPrismaObjOrUndefined(booking.customInputs),
startTime: booking.startTime.toISOString(),
endTime: booking.endTime.toISOString(),
organizer: {
email: user.email,
name: user.name || "Unnamed",
timeZone: user.timeZone,
language: { translate: tOrganizer, locale: user.locale ?? "en" },
},
attendees: attendeesList,
location: booking.location ?? "",
uid: booking.uid,
destinationCalendar: booking?.destinationCalendar || user.destinationCalendar,
requiresConfirmation: booking?.eventType?.requiresConfirmation ?? false,
eventTypeId: booking.eventType?.id,
};
const recurringEvent = parseRecurringEvent(booking.eventType?.recurringEvent);
if (recurringEventId) {
if (
!(await prisma.booking.findFirst({
where: {
recurringEventId,
id: booking.id,
},
}))
) {
// FIXME: It might be best to retrieve recurringEventId from the booking itself.
throw new TRPCError({
code: "UNAUTHORIZED",
message: "Recurring event id doesn't belong to the booking",
});
}
}
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) {
await handleConfirmation({ user, evt, recurringEventId, prisma, bookingId, booking });
} 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 {
// handle refunds
if (!!booking.payment.length) {
const successPayment = booking.payment.find((payment) => payment.success);
if (!successPayment) {
// Disable paymentLink for this booking
} else {
let eventTypeOwnerId;
if (booking.eventType?.owner) {
eventTypeOwnerId = booking.eventType.owner.id;
} else if (booking.eventType?.teamId) {
const teamOwner = await prisma.membership.findFirst({
where: {
teamId: booking.eventType.teamId,
role: MembershipRole.OWNER,
},
select: {
userId: true,
},
});
eventTypeOwnerId = teamOwner?.userId;
}
if (!eventTypeOwnerId) {
throw new Error("Event Type owner not found for obtaining payment app credentials");
}
const paymentAppCredentials = await prisma.credential.findMany({
where: {
userId: eventTypeOwnerId,
appId: successPayment.appId,
},
select: {
key: true,
appId: true,
app: {
select: {
categories: true,
dirName: true,
},
},
feat/payment-service-6438-cal-767 (#6677) * WIP paymentService * Changes for payment Service * Fix for stripe payment flow * Remove logs/comments * Refactored refund for stripe app * Move stripe handlePayment to own lib * Move stripe delete payments to paymentService * lint fix * Change handleRefundError as generic function * remove log * remove logs * remove logs * Return stripe default export to lib/server * Fixing types * Fix types * Upgrades typescript * Update yarn lock * Typings * Hotfix: ping,riverside,whereby and around not showing up in list (#6712) * Hotfix: ping,riverside,whereby and around not showing up in list (#6712) (#6713) * Adds deployment settings to DB (#6706) * WIP * Adds DeploymentTheme * Add missing migrations * Adds client extensions for deployment * Cleanup * Revert "lint fix" This reverts commit e1a2e4a357e58e6673c47399888ae2e00d1351a6. * Add validation * Revert changes removed in force push * Removing abstract class and just leaving interface implementation * Fix types for handlePayments * Fix payment test appStore import * Fix stripe metadata in event type * Move migration to separate PR * Revert "Move migration to separate PR" This reverts commit 48aa64e0724a522d3cc2fefaaaee5792ee9cd9e6. * Update packages/prisma/migrations/20230125175109_remove_type_from_payment_and_add_app_relationship/migration.sql Co-authored-by: Omar López <zomars@me.com> --------- Co-authored-by: zomars <zomars@me.com> Co-authored-by: Hariom Balhara <hariombalhara@gmail.com>
2023-02-08 20:36:22 +00:00
},
});
feat/payment-service-6438-cal-767 (#6677) * WIP paymentService * Changes for payment Service * Fix for stripe payment flow * Remove logs/comments * Refactored refund for stripe app * Move stripe handlePayment to own lib * Move stripe delete payments to paymentService * lint fix * Change handleRefundError as generic function * remove log * remove logs * remove logs * Return stripe default export to lib/server * Fixing types * Fix types * Upgrades typescript * Update yarn lock * Typings * Hotfix: ping,riverside,whereby and around not showing up in list (#6712) * Hotfix: ping,riverside,whereby and around not showing up in list (#6712) (#6713) * Adds deployment settings to DB (#6706) * WIP * Adds DeploymentTheme * Add missing migrations * Adds client extensions for deployment * Cleanup * Revert "lint fix" This reverts commit e1a2e4a357e58e6673c47399888ae2e00d1351a6. * Add validation * Revert changes removed in force push * Removing abstract class and just leaving interface implementation * Fix types for handlePayments * Fix payment test appStore import * Fix stripe metadata in event type * Move migration to separate PR * Revert "Move migration to separate PR" This reverts commit 48aa64e0724a522d3cc2fefaaaee5792ee9cd9e6. * Update packages/prisma/migrations/20230125175109_remove_type_from_payment_and_add_app_relationship/migration.sql Co-authored-by: Omar López <zomars@me.com> --------- Co-authored-by: zomars <zomars@me.com> Co-authored-by: Hariom Balhara <hariombalhara@gmail.com>
2023-02-08 20:36:22 +00:00
const paymentAppCredential = paymentAppCredentials.find((credential) => {
return credential.appId === successPayment.appId;
});
feat/payment-service-6438-cal-767 (#6677) * WIP paymentService * Changes for payment Service * Fix for stripe payment flow * Remove logs/comments * Refactored refund for stripe app * Move stripe handlePayment to own lib * Move stripe delete payments to paymentService * lint fix * Change handleRefundError as generic function * remove log * remove logs * remove logs * Return stripe default export to lib/server * Fixing types * Fix types * Upgrades typescript * Update yarn lock * Typings * Hotfix: ping,riverside,whereby and around not showing up in list (#6712) * Hotfix: ping,riverside,whereby and around not showing up in list (#6712) (#6713) * Adds deployment settings to DB (#6706) * WIP * Adds DeploymentTheme * Add missing migrations * Adds client extensions for deployment * Cleanup * Revert "lint fix" This reverts commit e1a2e4a357e58e6673c47399888ae2e00d1351a6. * Add validation * Revert changes removed in force push * Removing abstract class and just leaving interface implementation * Fix types for handlePayments * Fix payment test appStore import * Fix stripe metadata in event type * Move migration to separate PR * Revert "Move migration to separate PR" This reverts commit 48aa64e0724a522d3cc2fefaaaee5792ee9cd9e6. * Update packages/prisma/migrations/20230125175109_remove_type_from_payment_and_add_app_relationship/migration.sql Co-authored-by: Omar López <zomars@me.com> --------- Co-authored-by: zomars <zomars@me.com> Co-authored-by: Hariom Balhara <hariombalhara@gmail.com>
2023-02-08 20:36:22 +00:00
if (!paymentAppCredential) {
throw new Error("Payment app credentials not found");
}
feat/payment-service-6438-cal-767 (#6677) * WIP paymentService * Changes for payment Service * Fix for stripe payment flow * Remove logs/comments * Refactored refund for stripe app * Move stripe handlePayment to own lib * Move stripe delete payments to paymentService * lint fix * Change handleRefundError as generic function * remove log * remove logs * remove logs * Return stripe default export to lib/server * Fixing types * Fix types * Upgrades typescript * Update yarn lock * Typings * Hotfix: ping,riverside,whereby and around not showing up in list (#6712) * Hotfix: ping,riverside,whereby and around not showing up in list (#6712) (#6713) * Adds deployment settings to DB (#6706) * WIP * Adds DeploymentTheme * Add missing migrations * Adds client extensions for deployment * Cleanup * Revert "lint fix" This reverts commit e1a2e4a357e58e6673c47399888ae2e00d1351a6. * Add validation * Revert changes removed in force push * Removing abstract class and just leaving interface implementation * Fix types for handlePayments * Fix payment test appStore import * Fix stripe metadata in event type * Move migration to separate PR * Revert "Move migration to separate PR" This reverts commit 48aa64e0724a522d3cc2fefaaaee5792ee9cd9e6. * Update packages/prisma/migrations/20230125175109_remove_type_from_payment_and_add_app_relationship/migration.sql Co-authored-by: Omar López <zomars@me.com> --------- Co-authored-by: zomars <zomars@me.com> Co-authored-by: Hariom Balhara <hariombalhara@gmail.com>
2023-02-08 20:36:22 +00:00
// Posible to refactor TODO:
const paymentApp = appStore[paymentAppCredential?.app?.dirName as keyof typeof appStore];
if (!(paymentApp && "lib" in paymentApp && "PaymentService" in paymentApp.lib)) {
console.warn(`payment App service of type ${paymentApp} is not implemented`);
return null;
}
feat/payment-service-6438-cal-767 (#6677) * WIP paymentService * Changes for payment Service * Fix for stripe payment flow * Remove logs/comments * Refactored refund for stripe app * Move stripe handlePayment to own lib * Move stripe delete payments to paymentService * lint fix * Change handleRefundError as generic function * remove log * remove logs * remove logs * Return stripe default export to lib/server * Fixing types * Fix types * Upgrades typescript * Update yarn lock * Typings * Hotfix: ping,riverside,whereby and around not showing up in list (#6712) * Hotfix: ping,riverside,whereby and around not showing up in list (#6712) (#6713) * Adds deployment settings to DB (#6706) * WIP * Adds DeploymentTheme * Add missing migrations * Adds client extensions for deployment * Cleanup * Revert "lint fix" This reverts commit e1a2e4a357e58e6673c47399888ae2e00d1351a6. * Add validation * Revert changes removed in force push * Removing abstract class and just leaving interface implementation * Fix types for handlePayments * Fix payment test appStore import * Fix stripe metadata in event type * Move migration to separate PR * Revert "Move migration to separate PR" This reverts commit 48aa64e0724a522d3cc2fefaaaee5792ee9cd9e6. * Update packages/prisma/migrations/20230125175109_remove_type_from_payment_and_add_app_relationship/migration.sql Co-authored-by: Omar López <zomars@me.com> --------- Co-authored-by: zomars <zomars@me.com> Co-authored-by: Hariom Balhara <hariombalhara@gmail.com>
2023-02-08 20:36:22 +00:00
const PaymentService = paymentApp.lib.PaymentService;
const paymentInstance = new PaymentService(paymentAppCredential);
const paymentData = await paymentInstance.refund(successPayment.id);
if (!paymentData.refunded) {
throw new Error("Payment could not be refunded");
}
}
feat/payment-service-6438-cal-767 (#6677) * WIP paymentService * Changes for payment Service * Fix for stripe payment flow * Remove logs/comments * Refactored refund for stripe app * Move stripe handlePayment to own lib * Move stripe delete payments to paymentService * lint fix * Change handleRefundError as generic function * remove log * remove logs * remove logs * Return stripe default export to lib/server * Fixing types * Fix types * Upgrades typescript * Update yarn lock * Typings * Hotfix: ping,riverside,whereby and around not showing up in list (#6712) * Hotfix: ping,riverside,whereby and around not showing up in list (#6712) (#6713) * Adds deployment settings to DB (#6706) * WIP * Adds DeploymentTheme * Add missing migrations * Adds client extensions for deployment * Cleanup * Revert "lint fix" This reverts commit e1a2e4a357e58e6673c47399888ae2e00d1351a6. * Add validation * Revert changes removed in force push * Removing abstract class and just leaving interface implementation * Fix types for handlePayments * Fix payment test appStore import * Fix stripe metadata in event type * Move migration to separate PR * Revert "Move migration to separate PR" This reverts commit 48aa64e0724a522d3cc2fefaaaee5792ee9cd9e6. * Update packages/prisma/migrations/20230125175109_remove_type_from_payment_and_add_app_relationship/migration.sql Co-authored-by: Omar López <zomars@me.com> --------- Co-authored-by: zomars <zomars@me.com> Co-authored-by: Hariom Balhara <hariombalhara@gmail.com>
2023-02-08 20:36:22 +00:00
}
// end handle refunds.
feat/payment-service-6438-cal-767 (#6677) * WIP paymentService * Changes for payment Service * Fix for stripe payment flow * Remove logs/comments * Refactored refund for stripe app * Move stripe handlePayment to own lib * Move stripe delete payments to paymentService * lint fix * Change handleRefundError as generic function * remove log * remove logs * remove logs * Return stripe default export to lib/server * Fixing types * Fix types * Upgrades typescript * Update yarn lock * Typings * Hotfix: ping,riverside,whereby and around not showing up in list (#6712) * Hotfix: ping,riverside,whereby and around not showing up in list (#6712) (#6713) * Adds deployment settings to DB (#6706) * WIP * Adds DeploymentTheme * Add missing migrations * Adds client extensions for deployment * Cleanup * Revert "lint fix" This reverts commit e1a2e4a357e58e6673c47399888ae2e00d1351a6. * Add validation * Revert changes removed in force push * Removing abstract class and just leaving interface implementation * Fix types for handlePayments * Fix payment test appStore import * Fix stripe metadata in event type * Move migration to separate PR * Revert "Move migration to separate PR" This reverts commit 48aa64e0724a522d3cc2fefaaaee5792ee9cd9e6. * Update packages/prisma/migrations/20230125175109_remove_type_from_payment_and_add_app_relationship/migration.sql Co-authored-by: Omar López <zomars@me.com> --------- Co-authored-by: zomars <zomars@me.com> Co-authored-by: Hariom Balhara <hariombalhara@gmail.com>
2023-02-08 20:36:22 +00:00
await prisma.booking.update({
where: {
id: bookingId,
},
data: {
status: BookingStatus.REJECTED,
rejectionReason,
},
});
}
await sendDeclinedEmails(evt);
}
const message = "Booking " + confirmed ? "confirmed" : "rejected";
const status = confirmed ? BookingStatus.ACCEPTED : BookingStatus.REJECTED;
return { message, status };
}),
});