+22





![kodiakhq[bot]](/avatar/78f03f45def735066748285e1c83c542df49e7b0562b0a8da815d5b24845d135?size=40)



Omar López
CarinaWolli
Peer Richelsen
kodiakhq[bot]
Alex van Andel
gitstart
Júlio Piubello da Silva Cabral
Alan
Joe Au-Yeung
Carina Wollendorfer
Hariom Balhara
Syed Ali Shahbaz
Leo Giovanetti
Bailey Pumfleet
GitStart
Arthur Cruz
Mitchell Moore
Agusti Fernandez Pardo
Agusti Fernandez Pardo
sean-brydon
andreaestefania12
Miguel Nieto A
Hashen
buschco
iamkun
github-actions[bot]
Crowdin Bot
Ankit Gordhandas
depfu[bot]
Ken Miller
Arun Kumar
Shrey Gupta
01631e808f
* Turbo fixes * Make apps single pages public * fixed /booking skeleton (#2722) * fixed /booking skeleton * nit * Type fixes * Test fixes * Update playwright.config.ts * More test fixes * Update dynamic-booking-pages.test.ts * add invite link to Zapier setup page (#2696) * add invite link and toaster to zapier setup page * create env variable for invite link and save in database * fetch invite link form getStaticProps * add getStaticPath method * clean code * Moves app setup and index page * Moves Loader to ui * Trying new way to handle dynamic app store pages * Cleanup * Update tailwind.config.js * zapier invite link fixes * Tests fixes Co-authored-by: CarinaWolli <[email protected]> Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com> Co-authored-by: zomars <[email protected]> * Add more embed events (#2719) * Add more embed events * Add more embed events Co-authored-by: Peer Richelsen <[email protected]> * adds availability select loader (#2718) * Improve logs and Fix unwanted 500 to reduce noise in logs (#2674) * Improve logs * Fix unintentional 500 Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com> * Change date format for RecurringBookings (#2707) * Change date format for RecurringBookings * Missing bookingId query param Co-authored-by: Leo Giovanetti <[email protected]> Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com> * added giphy description (#2730) * fixes #2732 (#2732) * Hotfix : Fix Infinite loading of Bookings (#2729) * Add more embed events * Add more embed events * Fix nextCursor calculation logic Co-authored-by: Peer Richelsen <[email protected]> * Hotfix: Success page for recurring event (#2725) * Merge pull request #2672 from calcom/main v1.5.4 * Turbo fixes * Make apps single pages public * Fix preview.html not built and thus served during depooy (#2713) * Hotfix: Success page layout broken due to duplicate "When" (#2716) * Update BookingPage.tsx * Reverting unchaged lines * Fixing recurrenceRule for ICS files Co-authored-by: Omar López <[email protected]> Co-authored-by: Hariom Balhara <[email protected]> * Fix preview.html not built and thus served during depooy (#2727) Co-authored-by: Omar López <[email protected]> * Allow deletion of a disabled event (#2737) * allows deletion of disabled event * some visual fixes Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com> * Multiple E2E improvements * Parallelizes some tests * Update booking-pages.test.ts * E2E and paid bookings fixes * Add 'free' and 'workingElsewhere' as a non-blocking event (#2652) * Add 'free' and 'workingElsewhere' to non-blocking event - this will allow bookings at these times * Update CalendarService.ts Co-authored-by: zomars <[email protected]> Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com> * TODO marks blocking test to be fixed * Update testUtils.ts * Update testUtils.ts * getBusyTimes consolidation * Fixes delete-me test * E2E fixing attemps * Adjusting Zapier endpoints for publishing integration (#2728) * add /me endpoint for zapier API testing * remove cacellationReason from listBookings response Co-authored-by: CarinaWolli <[email protected]> Co-authored-by: Peer Richelsen <[email protected]> Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com> Co-authored-by: Omar López <[email protected]> * Fix reschedule not happening in calendar if two calendards are there (#2733) Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com> Co-authored-by: Peer Richelsen <[email protected]> * Increases timeout temporarily * Merge pull request #2745 from calcom/apps/multiple-categories Allow apps to belong to multiple categories * Build fixes * Populate msteams key in db (#2743) * Populate msteams key in db * Fix calendar credentials to teams * Clarify account dialog Co-authored-by: Omar López <[email protected]> Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com> Co-authored-by: Bailey Pumfleet <[email protected]> * Improving Email DRYness (#2486) * Email DRY * WIP * Improve email DRYness Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com> * E2E fixtures (#2747) * Sign in button should be changed or disabled after click #2654 (#2749) Co-authored-by: gitstart <[email protected]> * Fixing ESLint warnings (#2723) * Fixing warnings * Reverting and disabling ESLint in some cases * Reverting Next Images * Reverting file, bad merge * Targeting ESLint to line * Additional warnings * New warning squished * More tweaks and major fixes * Uneeded conf Co-authored-by: Omar López <[email protected]> * Fix/avoid multiple schedule deletions (#2602) * Prevents users from deleting the same schedule multiple times due to delay before the schedule disappears. It also applies the same fix to team disband. Schedule deletion:  Team disband:  Fixes issue [#2569](https://github.com/calcom/cal.com/issues/2569) Bug fix (non-breaking change which fixes an issue) **apps/web/components/LightLoader.tsx** → this file was created in order to make a light color loading spinner available. It's necessary when we need to display a loading spinner above dark backgrounds. **apps/web/components/availability/ScheduleListItem.tsx** → this component was created in order to give a schedule list item its own state. * Removing a "setTimeout" that was only used for testing purposes * Adding a code review suggestion to my modifications * Changing loading style * Cleanup * Avoids using unnecessary state * Revert "Adding a code review suggestion to my modifications" This reverts commit b5e40062d71157ca1d9384fb1f5c30d50625809d. * Reverts some changes * Renames isLoading Co-authored-by: Alex van Andel <[email protected]> Co-authored-by: Omar López <[email protected]> * Added check on create eventtype to see is user has slug that already exists (#2757) * Added check on create eventtype to see is user has slug that already exists, added error check on onError * revert yarn.lock back * Catches prisma known error instead of making an additional query Co-authored-by: zomars <[email protected]> * Fix white border (#2761) * fix: remove hardcoded redirect in signin url email verification (#2764) Co-authored-by: Agusti Fernandez Pardo <[email protected]> * Bad UX when user wants to set the default Event Type Title #2245 (#2760) Co-authored-by: gitstart <[email protected]> * Skip sending emails in E2E * Users Phone Number Option (#2669) * Users Phone Number Option * Implemented improvments * Add validation to form Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com> Co-authored-by: zomars <[email protected]> * Fix/unpaid unconfirmed (#2553) * Fix merge errors * Errors prettier/prettier * Update apps/web/pages/api/book/event.ts Co-authored-by: Miguel Nieto A <[email protected]> * Update apps/web/pages/api/book/event.ts Co-authored-by: Miguel Nieto A <[email protected]> * Update apps/web/pages/api/integrations.ts Co-authored-by: Miguel Nieto A <[email protected]> * Fix merge errors * Errors prettier/prettier * Update apps/web/pages/api/book/confirm.ts Co-authored-by: alannnc <[email protected]> * Modal window before delete stripe integration * ESLint Report * Test fixes Co-authored-by: Miguel Nieto A <[email protected]> Co-authored-by: alannnc <[email protected]> Co-authored-by: zomars <[email protected]> * Mutually exclusive options (#2755) Co-authored-by: Omar López <[email protected]> Co-authored-by: Peer Richelsen <[email protected]> Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com> * Readd steps to create a new user #2665 (#2759) Co-authored-by: gitstart <[email protected]> * remove redundant conditional expressions (#2756) * remove redundant conditional expressions * remove redundant conditional expression Co-authored-by: Syed Ali Shahbaz <[email protected]> * Fix adds redirect callback that support app.cal.com (#2768) * Fix adds redirect callback that support app.cal.com * Update apps/web/pages/api/auth/[...nextauth].tsx Check origin of website and baseurl Co-authored-by: Omar López <[email protected]> * fix: lint issue extra space removed Co-authored-by: Agusti Fernandez Pardo <[email protected]> Co-authored-by: Omar López <[email protected]> Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com> * respect local set timezone and update url on mismatch (#2506) * ensure `timeZone()` will make its way to the URL fixes https://github.com/calcom/cal.com/issues/2482 * keep `timeZone()` and the offset from URL in sync Co-authored-by: Syed Ali Shahbaz <[email protected]> Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com> * Squashed commit of the following: commit27540b09ceAuthor: Agusti Fernandez Pardo <[email protected]> Date: Mon May 16 17:34:13 2022 +0200 fix: remove hardcoded redirect in signin url email verification (#2764) Co-authored-by: Agusti Fernandez Pardo <[email protected]> commitae15a7d739Author: Hariom Balhara <[email protected]> Date: Tue May 10 14:30:43 2022 +0530 Fix time issue commit2a5a89fe50Author: Leo Giovanetti <[email protected]> Date: Wed May 11 10:21:46 2022 -0300 Missing fix for success page commit2ce1e78053Author: Leo Giovanetti <[email protected]> Date: Wed May 11 10:12:59 2022 -0300 Hotfix: Success page for recurring event (#2725) * Merge pull request #2672 from calcom/main v1.5.4 * Turbo fixes * Make apps single pages public * Fix preview.html not built and thus served during depooy (#2713) * Hotfix: Success page layout broken due to duplicate "When" (#2716) * Update BookingPage.tsx * Reverting unchaged lines * Fixing recurrenceRule for ICS files Co-authored-by: Omar López <[email protected]> Co-authored-by: Hariom Balhara <[email protected]> commit2d6d1cb444Author: Hariom Balhara <[email protected]> Date: Tue May 10 14:49:46 2022 +0530 Hotfix: Success page layout broken due to duplicate "When" (#2716) commitef68f4f4f8Author: Hariom Balhara <[email protected]> Date: Tue May 10 10:54:20 2022 +0530 Fix preview.html not built and thus served during depooy (#2713) commit18c28cc3fdAuthor: zomars <[email protected]> Date: Mon May 9 16:17:07 2022 -0600 Make apps single pages public commitd40e8caff9Author: zomars <[email protected]> Date: Mon May 9 16:08:03 2022 -0600 Turbo fixes commit3161cc4d45Merge:ed808c3be4099a477dAuthor: zomars <[email protected]> Date: Mon May 9 14:58:33 2022 -0600 Merge branch 'main' into production commited808c3be6Author: Omar López <[email protected]> Date: Mon May 9 14:56:23 2022 -0600 Merge pull request #2672 from calcom/main v1.5.4 * Typo * Typo * Update apps/web/pages/apps/categories/[category].tsx * Apply suggestions from code review * Alert to describe exclusion of options (#2770) * Alert to describe exclusion of options * Update apps/web/pages/event-types/[type].tsx Co-authored-by: Omar López <[email protected]> * Update apps/web/components/eventtype/RecurringEventController.tsx Co-authored-by: Omar López <[email protected]> * Formatting Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com> Co-authored-by: Omar López <[email protected]> * fix: split time correctly if the local working hours are just across mid night (#2766) Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com> * Update crowdin.yml * New Crowdin translations by Github Action (#2773) * New Crowdin translations by Github Action * Update vital.json * Update vital.json Co-authored-by: Crowdin Bot <[email protected]> Co-authored-by: Omar López <[email protected]> * Add Google cal extneral calendar id to booking reference (#2671) * Set google cal event id to use our uid * Save calendar external id to bookingRef * Pass external calendar ids to update and delete * Create migration * Fix type errors * Fix prisma url Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com> Co-authored-by: Omar López <[email protected]> * v1.6 * v1.6 * 2FA submit disabled (#2790) * fixing the hyperlink for open startup (#2777) Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com> * Add login event (#2784) Co-authored-by: Bailey Pumfleet <[email protected]> * Fixes infinite loop * Fixes infinite loop * Fixes infinite loop * Update all Yarn dependencies (2022-05-16) (#2769) * Update all Yarn dependencies (2022-05-16) * Upgrade dependencies * Removes deprecated packages * Upgrades deps * Updates submodules * Update yarn.lock * Linting * Linting * Update website * Build fixes * TODO: fix this * Module resolving * Type fixes * Intercom fixes on SSG * Fixes infinite loop * Upgrades to React 18 * Type fixes * Locks node version to 14 * Upgrades daily-js * Readds missing types * Upgrades playwright * Noop when intercom is not installed * Update website * Removed yarn.lock in favor of monorepo Co-authored-by: depfu[bot] <23717796+depfu[bot]@users.noreply.github.com> Co-authored-by: zomars <[email protected]> * Create ci.yml * Update ci.yml * Reintroduces typescript-eslint Buckle up! * Type fixes * Update ci.yml * Update api * Update admin * Reusable inferSSRProps * Linting * Linting * Prisma fixes * Update ci.yml * Cache testing * Update e2e.yml * Update DatePicker.tsx * Update e2e.yml * Revert "Linting" This reverts commitadf817766e. * Revert "Linting" This reverts commit1b59dacd64. * Linting * Update e2e.yml * Ci updates * Add team Id to hash url (#2803) * Fix missing tabs - Embed (#2804) * Fix missing tabs * Fix Eslint error * Fix Eslint errors * Add import statement (#2812) * Add import statement * Update apps/docs/next.config.js Co-authored-by: Omar López <[email protected]> * Show success page if booking was deleted on calendar (#2808) * Add exception to 410 * Fix type error * Add GoogelCalError type * only show invite link for app.cal.dev (#2807) Co-authored-by: CarinaWolli <[email protected]> Co-authored-by: Omar López <[email protected]> * fix: update eslint config to test .ts and .js separately (#2805) * fix: update eslint config * fix: update ts ignore * fix: update eslint config * Update TeamAvailabilityScreen.tsx * Type fixes * Update useIntercom.ts Co-authored-by: Omar López <[email protected]> * fix: sync api to latest commit (#2810) Co-authored-by: Agusti Fernandez Pardo <[email protected]> Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com> * Embed React improvements (#2782) * Add off support. Add getApi export. * Add publish command * Add embed-snippet in prod deps * Update README * Update package.json Co-authored-by: Bailey Pumfleet <[email protected]> Co-authored-by: zomars <[email protected]> Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com> * Consolidates test-results * Add vscode tasks.json (#2801) Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com> * save additional inputs as json + view details of booking (#2796) * move custom inputs from description to own json object * show custom inputs on success page * fix type error * add custom inputs to email and webhook * add custom inputs to all emails * add values for custom inputs when rescheduling * add custom input everywhere description is shown * fix bug with boolean value * fix issues with null values * disable custom inputs and add notes for organizer * don't show custom input with empty string * don't show custom inputs with empty string in calender event and email * add link to booking details page * redirect to success page to see booking details * add functionality to cancel and reschedule booking * fix bookings that require confirmation * clean code * fix infinite lopp in useEffect of success page * show web conference details message when integration as location * improve design of cancelling event * clean code * disable darkmode for organizer on booking details page * fix dark mode for cancelling booking * fix build error * Fixes infinite loop * Fixes infinite loop * Fixes infinite loop * Update all Yarn dependencies (2022-05-16) (#2769) * Update all Yarn dependencies (2022-05-16) * Upgrade dependencies * Removes deprecated packages * Upgrades deps * Updates submodules * Update yarn.lock * Linting * Linting * Update website * Build fixes * TODO: fix this * Module resolving * Type fixes * Intercom fixes on SSG * Fixes infinite loop * Upgrades to React 18 * Type fixes * Locks node version to 14 * Upgrades daily-js * Readds missing types * Upgrades playwright * Noop when intercom is not installed * Update website * Removed yarn.lock in favor of monorepo Co-authored-by: depfu[bot] <23717796+depfu[bot]@users.noreply.github.com> Co-authored-by: zomars <[email protected]> * Create ci.yml * Update ci.yml * Reintroduces typescript-eslint Buckle up! * Type fixes * Update ci.yml * Update api * Update admin * Reusable inferSSRProps * Linting * Linting * Prisma fixes * Update ci.yml * Cache testing * Update e2e.yml * Update DatePicker.tsx * Update e2e.yml * Revert "Linting" This reverts commitadf817766e. * Revert "Linting" This reverts commit1b59dacd64. * Linting * Update e2e.yml * Ci updates * Add team Id to hash url (#2803) * Fix missing tabs - Embed (#2804) * Fix missing tabs * Fix Eslint error * Fix Eslint errors * Add import statement (#2812) * Add import statement * Update apps/docs/next.config.js Co-authored-by: Omar López <[email protected]> * Show success page if booking was deleted on calendar (#2808) * Add exception to 410 * Fix type error * Add GoogelCalError type * only show invite link for app.cal.dev (#2807) Co-authored-by: CarinaWolli <[email protected]> Co-authored-by: Omar López <[email protected]> * fix: update eslint config to test .ts and .js separately (#2805) * fix: update eslint config * fix: update ts ignore * fix: update eslint config * Update TeamAvailabilityScreen.tsx * Type fixes * Update useIntercom.ts Co-authored-by: Omar López <[email protected]> * fix: sync api to latest commit (#2810) Co-authored-by: Agusti Fernandez Pardo <[email protected]> Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com> * Embed React improvements (#2782) * Add off support. Add getApi export. * Add publish command * Add embed-snippet in prod deps * Update README * Update package.json Co-authored-by: Bailey Pumfleet <[email protected]> Co-authored-by: zomars <[email protected]> Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com> * Consolidates test-results * Type fixes * Abstracts minimal booking select * Type fixes * Update listBookings.ts * Update common.json * Update bookingReminder.ts * Consolidates isOutOfBounds * Update webhookResponse-chromium.txt * Update TableActions.tsx * Type fixes * Update BookingPage.tsx * Update webhookResponse-chromium.txt Co-authored-by: CarinaWolli <[email protected]> Co-authored-by: Alex van Andel <[email protected]> Co-authored-by: Bailey Pumfleet <[email protected]> Co-authored-by: zomars <[email protected]> Co-authored-by: depfu[bot] <23717796+depfu[bot]@users.noreply.github.com> Co-authored-by: sean-brydon <[email protected]> Co-authored-by: Hariom Balhara <[email protected]> Co-authored-by: Joe Au-Yeung <[email protected]> Co-authored-by: iamkun <[email protected]> Co-authored-by: Agusti Fernandez Pardo <[email protected]> Co-authored-by: Agusti Fernandez Pardo <[email protected]> Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com> * Update check-types.yml * adding organizer as attendee to google calendar events (#2779) * Fix auto-select and close of dropdown (#2819) * fixes dynamic color and typefix for tfunction after react upgrade (#2821) * New Crowdin translations by Github Action (#2791) Co-authored-by: Crowdin Bot <[email protected]> * Relocates admin to console # Conflicts: # apps/admin * Relocates admin to console * Fix login submit (#2849) * fix: long string overflowing calendar div (#2842) Co-authored-by: gitstart <[email protected]> Co-authored-by: Júlio Piubello da Silva Cabral <[email protected]> * Adding labels (#2783) Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com> * Wrong username is identified if query params are present and user doesn't exist (#2838) Co-authored-by: gitstart <[email protected]> Co-authored-by: Júlio Piubello da Silva Cabral <[email protected]> * Meet/Zoom Email Clarification (#2828) * Add clarificaiton to email * Update apps/web/lib/emails/templates/organizer-scheduled-email.ts * Add to attendee scheduled email Co-authored-by: Omar López <[email protected]> Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com> * Request the inclusion Assuncion Time Zone (#2840) Co-authored-by: gitstart <[email protected]> Co-authored-by: Júlio Piubello da Silva Cabral <[email protected]> * Fix UI of dialog (#2788) * removed large mandatory height and scroll * added z index using css * cleanup * fixed TS errors * extract dialog out of dropdown * Adds custom loading text to confirmation dialog * rename update * utilizing mutation loading state Co-authored-by: Peer Richelsen <[email protected]> Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com> * Hotfix: Fixing Security Issues (#2848) * Fixing Privilege Escalation * Fixing critical obj ref in availability * Fixing reschedule security issue Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com> Co-authored-by: Peer Richelsen <[email protected]> * Merge production to main * Update vital.json * Update vital.json * Fix login page CTA disabled state (#2832) * fix(ui/login): better disabled state for login CTA The fix involves tracking the form submission with a dedicated state `submitInProgress` with React. `formState` from `react-hook-form` does not take time taken for the network call into account. For example, if the api takes 5 seconds to complete, we would expect the `formState.isSubmitting` to be true for `5` seconds. But, surprisingly this is not the case and `formState` from `react-hook-form` resolves immediately after it makes a successful connection to the endpoint. A dedicated state (with `useState`) is introduced that is enabled when the user clicks on the login CTA, and disabled when the api call is resolved, either successfully or with an error. * Update login.tsx * Update login.tsx * Fixes isSubmitting state Co-authored-by: zomars <[email protected]> * Playwright binaries shouldn't be on deps * Playwright binaries shouldn't be on deps * Fix infinite renders on event-type edit page (#2820) * Updates submodules * Makes sure to hash post-install cache * Add seats to event types (#2485) * Add seatsPerTimeSlot to event type schema * Add seats per time slot to event type form * Book event and render seats * Pass booking uid for seats * Disable requires confirmation if seats are enabled * Fix type errors * Update submodules * Fix type errors * Fix type errors * Fix duplicate string * Fix duplicate string * Fix schema and migration file * Fix render seats * Fix bookinguid typos * Remove console.log * Fix type error * Fix mobile formatting * Update apps/web/lib/hooks/useSlots.ts Co-authored-by: Omar López <[email protected]> * Update apps/web/lib/hooks/useSlots.ts Co-authored-by: Omar López <[email protected]> * Added translation for seats available text Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com> Co-authored-by: zomars <[email protected]> Co-authored-by: alannnc <[email protected]> * Redesign help menu item (#2710) * Seperate help menu item and contact menu item * Add menu items * Install react-popover * Render contact only if support keys are present * Adjust contact support links * Add translations * Add embed changes * Adjust menu if helped is pressed * Add items to help menu * Change button color on selection * Create endpoint * Create feedback table * Create migration file * Write feedback to db * Remove logs * Add response message * Send feedback email * Disable submit if no rating and after submit * Add translations * Fix padding * Clean up * Clean up * Add user feedback email to .env example * Lint fixes and styles * Changed onClick function to a named function and fix style * Fix ids order * Removed commented code and changed textarea id and name * Fix id orders * Change to AND operator Co-authored-by: Omar López <[email protected]> * Add user relation to feedback Co-authored-by: Omar López <[email protected]> * Add migration files * Change rating to strings * Change rating to strings * Fix type errors * WIP success & error messages * Change success and error to boolans * Style messages * Add await Co-authored-by: Omar López <[email protected]> * Remove duplicate string * Refactor import statement Co-authored-by: Omar López <[email protected]> * Change opacity of emojis * added [email protected] email for feedback * Add success toast * Update .env.example Co-authored-by: Omar López <[email protected]> * Add tCRP route * tCRP send email * tCRP send email Co-authored-by: Alan <[email protected]> Co-authored-by: Omar López <[email protected]> Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com> Co-authored-by: Peer Richelsen <[email protected]> * fixed labels for seats, removes shadow from event-type inputs (#2862) * fixed labels for seats * minor fixes, removed shadow from all event-type inputs * Render input field on pro accounts (#2859) Co-authored-by: Joe Au-Yeung <[email protected]> * Submodule sync * sec-001 fixes (#2866) (#2867) * sec-001 fixes (#2866) * sec-001 fixes * Typo * Fixes paid bookings # Conflicts: # apps/web/ee/components/stripe/Payment.tsx * Hotfix: Fixing Security Issues (#2848) (#2850) * sec-001 fixes (#2866) * sec-001 fixes * Typo * Fixes paid bookings * fixes issues with date of recurring events on booking detail page (#2872) * fixes date not showing for confirmed recurring event * only show all events on upcoming bookings Co-authored-by: CarinaWolli <[email protected]> * Resolve if can't find event on google cal (#2860) * Resolve if can't find event on google cal * Change order of console.error Co-authored-by: Omar López <[email protected]> Co-authored-by: Omar López <[email protected]> Co-authored-by: Peer Richelsen <[email protected]> * Disable Impersonation Option (#2880) * Disable Impersonation * Update Description Copy Co-authored-by: Peer Richelsen <[email protected]> * Fix deleted event when on different cal (404) (#2882) * Fix/email shows false (#2879) * Webhook sec fixes (#2883) * Webhook sec fixes * Revert changes * Feat/Display location information publicly (#2752) * Updating checkbox field to reflect new designs * Include Infobadge option checkbox * Checkbox Field + i18n * Default checked - true * Sync with router * Extracting Types * Update filtering logic * Add UI to booking page * Default address/link * Update hashedlink page * Tidy up * Video icon * Add nullish check * Update to use RHF controller Co-authored-by: Peer Richelsen <[email protected]> Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com> * Fix 500 errors if data is invalid (#2886) * Check in middleware to ensure authorization for all endpoints (#2885) Co-authored-by: Alex van Andel <[email protected]> * Fix bug to check opt in bookings (#2889) * Fix bug to check opt in bookings * Implemented value, onChange instead of form access Co-authored-by: Alex van Andel <[email protected]> * remove unused imports (#2892) * Cascades impersonations on user delete (#2891) Co-authored-by: Alex van Andel <[email protected]> * Ensures json fields on each call (#2893) Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com> * Redundant conditional expression (#2894) * remove redundant conditional expressions * remove redundant conditional expressions * License server (#2379) * WIP License server * WIP * Moves locations to App Store and Core * LocationType fixes * Runs db migrations post-deploy * WIP * WIP * Cleanup * WIP * WIP * Decouples translations from NavTabs * Adds admin submodule * Adds admin submodule * Sync dependencies * WIP * WIP * Updates submodules * Renames package * Updates submodules * Adds scripts for console * Updates license checker URL * Updates admin * Adds staging/prod admin console links * Update yarn.lock * Update NavTabs.tsx * WIP * Update admin * WIP * Adds hint to InputField * Update admin * Adds turbo admin dependecies * Update admin * Prevents redirection on form submit * Form warning fixes * Update admin * Form fixes * Update yarn.lock * Update admin * Update admin * Update admin * Adds withLicenseRequired HOC * Adds LicenseRequired to EE components * Admin deploy fix? * Updates submodules * Use relative inside lib * type fixes * Fixes turbo race condition * Relocates admin to console * Relocates admin to console * Update console * Update api * Update turbo.json * Update ErrorBoundary.tsx * Update defaultEvents.ts * Update checkLicense.ts * Update yarn.lock * Skip on E2E Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com> * Update turbo.json * Reverts license check on payment Since it's a public page * Submodule sync * fix: overflowing text on teams page - using tailwind line-clamp (#2843) Co-authored-by: gitstart <[email protected]> Co-authored-by: Júlio Piubello da Silva Cabral <[email protected]> * Fix @calcom/embed-react installation with TS project (#2870) * Fix failing builds (#2908) * Update turbo.json * 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 <[email protected]> * 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 <[email protected]> Co-authored-by: Alan <[email protected]> Co-authored-by: Omar López <[email protected]> Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com> * added checkly and twitch badges * Update README.md * areas of expertise test * Update CONTRIBUTING.md * Update README.md (#2912) * Update CONTRIBUTING.md * Update CONTRIBUTING.md * Update CONTRIBUTING.md * Update CONTRIBUTING.md * Update CONTRIBUTING.md * Update CONTRIBUTING.md * remove unsed imports (#2895) Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com> * Fix event-type preview links on Vercel Previews (#2919) * Fix website url * Fix avatar paths everywhere * Fix linting errors Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com> * Cleanup & removed usages of sparingly used Text/ files (#2904) * Update CONTRIBUTING.md * Update CONTRIBUTING.md * Fixed typo in CheckboxField and wrapped description in <label> (#2924) * Fixed typo in CheckboxField and wrapped description in <label> * Make functionality identical to before * Fixed use of infomationIconText * Fix lint error (needs refactor, out of scope) * Payment amount input leading 0 (#2836) Co-authored-by: gitstart <[email protected]> Co-authored-by: Júlio Piubello da Silva Cabral <[email protected]> * Allow less than 6 bookings and add proper min validation of 2+ (#2921) Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com> * fix(app-store): Giphy Ux fixes (#2746) * fix(app-store): Giphy Ux fixes * Add search placeholder * Min height image on event type page * Use regex in zod validation and fix design issues for figma row 1 * Add paddings as per discussion with Ciarán * Fix getGiphyApiKey nomenclature * Update apps/web/public/static/locales/en/common.json * Update regex to be more readable and allow enter to search Co-authored-by: Omar López <[email protected]> Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com> Co-authored-by: Joe Au-Yeung <[email protected]> * Add embed tests in CI (#2887) * Add embed tests in CI * Update e2e-embed.yml * Run quick tests only * Ignore certain folders * Add embed-react tests as well * Fix commands * Dont run unit tests * Update playwright.config.ts * Update playwright.config.ts * Update playwright.config.ts * Create correct artifcats * Create correct artifcats * Fi ignore path * Update package.json * Add back embed-react typecheck Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com> * remove subtitle (#2925) Co-authored-by: CarinaWolli <[email protected]> Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com> * Fix booking detail page for cancelled events (#2905) * fix booking detail page for cancelled events * Fix typo * fix bug when now attendees exist in booking Co-authored-by: CarinaWolli <[email protected]> Co-authored-by: Alan <[email protected]> * v1.6.2 * Add reschedule reason to DB and emails (#2909) * Write reschedule reason to db * Add reschedule reason to emails * Add reschedule reason to request reschedule email * Add reschedule reason to request reschedule email * Add reschedule reason to request reschedule email * Add reschedule reason to request reschedule email * Write reschedule reason to db * Add reschedule reason to emails * No longer using rescheduleReason in favor of cancellationReason * Update apps emails accordingly with reschedule reason * Update reschedule.test.ts Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com> Co-authored-by: Alan <[email protected]> Co-authored-by: zomars <[email protected]> * Update website * Update HelpMenuItem.tsx * Update event.ts Co-authored-by: Peer Richelsen <[email protected]> Co-authored-by: Carina Wollendorfer <[email protected]> Co-authored-by: CarinaWolli <[email protected]> Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com> Co-authored-by: Hariom Balhara <[email protected]> Co-authored-by: Syed Ali Shahbaz <[email protected]> Co-authored-by: Joe Au-Yeung <[email protected]> Co-authored-by: Leo Giovanetti <[email protected]> Co-authored-by: Alex van Andel <[email protected]> Co-authored-by: Bailey Pumfleet <[email protected]> Co-authored-by: GitStart <[email protected]> Co-authored-by: gitstart <[email protected]> Co-authored-by: Arthur Cruz <[email protected]> Co-authored-by: Mitchell Moore <[email protected]> Co-authored-by: Agusti Fernandez Pardo <[email protected]> Co-authored-by: Agusti Fernandez Pardo <[email protected]> Co-authored-by: sean-brydon <[email protected]> Co-authored-by: andreaestefania12 <[email protected]> Co-authored-by: Miguel Nieto A <[email protected]> Co-authored-by: alannnc <[email protected]> Co-authored-by: Hashen <[email protected]> Co-authored-by: buschco <[email protected]> Co-authored-by: iamkun <[email protected]> Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> Co-authored-by: Crowdin Bot <[email protected]> Co-authored-by: Ankit Gordhandas <[email protected]> Co-authored-by: depfu[bot] <23717796+depfu[bot]@users.noreply.github.com> Co-authored-by: Ken Miller <[email protected]> Co-authored-by: Júlio Piubello da Silva Cabral <[email protected]> Co-authored-by: Arun Kumar <[email protected]> Co-authored-by: Shrey Gupta <[email protected]>
876 lines
27 KiB
TypeScript
876 lines
27 KiB
TypeScript
import { BookingStatus, Credential, Prisma, SchedulingType, WebhookTriggerEvents } from "@prisma/client";
|
||
import async from "async";
|
||
import dayjs from "dayjs";
|
||
import dayjsBusinessTime from "dayjs-business-days2";
|
||
import isBetween from "dayjs/plugin/isBetween";
|
||
import timezone from "dayjs/plugin/timezone";
|
||
import utc from "dayjs/plugin/utc";
|
||
import type { NextApiRequest, NextApiResponse } from "next";
|
||
import rrule from "rrule";
|
||
import short from "short-uuid";
|
||
import { v5 as uuidv5 } from "uuid";
|
||
|
||
import EventManager from "@calcom/core/EventManager";
|
||
import { isPrismaObjOrUndefined } from "@calcom/lib";
|
||
import { getDefaultEvent, getGroupName, getUsernameList } from "@calcom/lib/defaultEvents";
|
||
import { getErrorFromUnknown } from "@calcom/lib/errors";
|
||
import logger from "@calcom/lib/logger";
|
||
import type { BufferedBusyTime } from "@calcom/types/BufferedBusyTime";
|
||
import type { AdditionInformation, CalendarEvent, RecurringEvent } from "@calcom/types/Calendar";
|
||
import type { EventResult, PartialReference } from "@calcom/types/EventManager";
|
||
import { handlePayment } from "@ee/lib/stripe/server";
|
||
|
||
import {
|
||
sendAttendeeRequestEmail,
|
||
sendOrganizerRequestEmail,
|
||
sendRescheduledEmails,
|
||
sendScheduledEmails,
|
||
} from "@lib/emails/email-manager";
|
||
import { ensureArray } from "@lib/ensureArray";
|
||
import { getEventName } from "@lib/event";
|
||
import getBusyTimes from "@lib/getBusyTimes";
|
||
import isOutOfBounds from "@lib/isOutOfBounds";
|
||
import prisma from "@lib/prisma";
|
||
import { BookingCreateBody } from "@lib/types/booking";
|
||
import sendPayload from "@lib/webhooks/sendPayload";
|
||
import getSubscribers from "@lib/webhooks/subscriptions";
|
||
|
||
import { getTranslation } from "@server/lib/i18n";
|
||
|
||
import verifyAccount from "../../../web3/utils/verifyAccount";
|
||
|
||
dayjs.extend(dayjsBusinessTime);
|
||
dayjs.extend(utc);
|
||
dayjs.extend(isBetween);
|
||
dayjs.extend(timezone);
|
||
|
||
const translator = short();
|
||
const log = logger.getChildLogger({ prefix: ["[api] book:user"] });
|
||
|
||
type BufferedBusyTimes = BufferedBusyTime[];
|
||
|
||
/**
|
||
* Refreshes a Credential with fresh data from the database.
|
||
*
|
||
* @param credential
|
||
*/
|
||
async function refreshCredential(credential: Credential): Promise<Credential> {
|
||
const newCredential = await prisma.credential.findUnique({
|
||
where: {
|
||
id: credential.id,
|
||
},
|
||
});
|
||
|
||
if (!newCredential) {
|
||
return credential;
|
||
} else {
|
||
return newCredential;
|
||
}
|
||
}
|
||
|
||
/**
|
||
* Refreshes the given set of credentials.
|
||
*
|
||
* @param credentials
|
||
*/
|
||
async function refreshCredentials(credentials: Array<Credential>): Promise<Array<Credential>> {
|
||
return await async.mapLimit(credentials, 5, refreshCredential);
|
||
}
|
||
|
||
function isAvailable(busyTimes: BufferedBusyTimes, time: dayjs.ConfigType, length: number): boolean {
|
||
// Check for conflicts
|
||
let t = true;
|
||
|
||
if (Array.isArray(busyTimes) && busyTimes.length > 0) {
|
||
busyTimes.forEach((busyTime) => {
|
||
const startTime = dayjs(busyTime.start);
|
||
const endTime = dayjs(busyTime.end);
|
||
|
||
// Check if time is between start and end times
|
||
if (dayjs(time).isBetween(startTime, endTime, null, "[)")) {
|
||
t = false;
|
||
}
|
||
|
||
// Check if slot end time is between start and end time
|
||
if (dayjs(time).add(length, "minutes").isBetween(startTime, endTime)) {
|
||
t = false;
|
||
}
|
||
|
||
// Check if startTime is between slot
|
||
if (startTime.isBetween(dayjs(time), dayjs(time).add(length, "minutes"))) {
|
||
t = false;
|
||
}
|
||
});
|
||
}
|
||
|
||
return t;
|
||
}
|
||
|
||
const userSelect = Prisma.validator<Prisma.UserArgs>()({
|
||
select: {
|
||
id: true,
|
||
email: true,
|
||
name: true,
|
||
username: true,
|
||
timeZone: true,
|
||
credentials: true,
|
||
bufferTime: true,
|
||
destinationCalendar: true,
|
||
locale: true,
|
||
},
|
||
});
|
||
|
||
const getUserNameWithBookingCounts = async (eventTypeId: number, selectedUserNames: string[]) => {
|
||
const users = await prisma.user.findMany({
|
||
where: {
|
||
username: { in: selectedUserNames },
|
||
eventTypes: {
|
||
some: {
|
||
id: eventTypeId,
|
||
},
|
||
},
|
||
},
|
||
select: {
|
||
id: true,
|
||
username: true,
|
||
locale: true,
|
||
},
|
||
});
|
||
|
||
const userNamesWithBookingCounts = await Promise.all(
|
||
users.map(async (user) => ({
|
||
username: user.username,
|
||
bookingCount: await prisma.booking.count({
|
||
where: {
|
||
user: {
|
||
id: user.id,
|
||
},
|
||
startTime: {
|
||
gt: new Date(),
|
||
},
|
||
eventTypeId,
|
||
},
|
||
}),
|
||
}))
|
||
);
|
||
|
||
return userNamesWithBookingCounts;
|
||
};
|
||
|
||
const getEventTypesFromDB = async (eventTypeId: number) => {
|
||
const eventType = await prisma.eventType.findUnique({
|
||
rejectOnNotFound: true,
|
||
where: {
|
||
id: eventTypeId,
|
||
},
|
||
select: {
|
||
users: userSelect,
|
||
team: {
|
||
select: {
|
||
id: true,
|
||
name: true,
|
||
},
|
||
},
|
||
title: true,
|
||
length: true,
|
||
eventName: true,
|
||
schedulingType: true,
|
||
description: true,
|
||
periodType: true,
|
||
periodStartDate: true,
|
||
periodEndDate: true,
|
||
periodDays: true,
|
||
periodCountCalendarDays: true,
|
||
requiresConfirmation: true,
|
||
userId: true,
|
||
price: true,
|
||
currency: true,
|
||
metadata: true,
|
||
destinationCalendar: true,
|
||
hideCalendarNotes: true,
|
||
seatsPerTimeSlot: true,
|
||
recurringEvent: true,
|
||
},
|
||
});
|
||
|
||
return {
|
||
...eventType,
|
||
recurringEvent: (eventType.recurringEvent || undefined) as RecurringEvent,
|
||
};
|
||
};
|
||
|
||
type User = Prisma.UserGetPayload<typeof userSelect>;
|
||
|
||
type ExtendedBookingCreateBody = BookingCreateBody & {
|
||
noEmail?: boolean;
|
||
recurringCount?: number;
|
||
rescheduleReason?: string;
|
||
};
|
||
|
||
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
|
||
const { recurringCount, noEmail, ...reqBody } = req.body as ExtendedBookingCreateBody;
|
||
|
||
// handle dynamic user
|
||
const dynamicUserList = Array.isArray(reqBody.user)
|
||
? getGroupName(req.body.user)
|
||
: getUsernameList(reqBody.user as string);
|
||
const hasHashedBookingLink = reqBody.hasHashedBookingLink;
|
||
const eventTypeSlug = reqBody.eventTypeSlug;
|
||
const eventTypeId = reqBody.eventTypeId;
|
||
const tAttendees = await getTranslation(reqBody.language ?? "en", "common");
|
||
const tGuests = await getTranslation("en", "common");
|
||
log.debug(`Booking eventType ${eventTypeId} started`);
|
||
|
||
const isTimeInPast = (time: string): boolean => {
|
||
return dayjs(time).isBefore(new Date(), "day");
|
||
};
|
||
|
||
if (isTimeInPast(reqBody.start)) {
|
||
const error = {
|
||
errorCode: "BookingDateInPast",
|
||
message: "Attempting to create a meeting in the past.",
|
||
};
|
||
|
||
log.error(`Booking ${eventTypeId} failed`, error);
|
||
return res.status(400).json(error);
|
||
}
|
||
|
||
const eventType = !eventTypeId ? getDefaultEvent(eventTypeSlug) : await getEventTypesFromDB(eventTypeId);
|
||
if (!eventType) return res.status(404).json({ message: "eventType.notFound" });
|
||
|
||
let users = !eventTypeId
|
||
? await prisma.user.findMany({
|
||
where: {
|
||
username: {
|
||
in: dynamicUserList,
|
||
},
|
||
},
|
||
...userSelect,
|
||
})
|
||
: eventType.users;
|
||
|
||
/* If this event was pre-relationship migration */
|
||
if (!users.length && eventType.userId) {
|
||
const eventTypeUser = await prisma.user.findUnique({
|
||
where: {
|
||
id: eventType.userId,
|
||
},
|
||
...userSelect,
|
||
});
|
||
if (!eventTypeUser) return res.status(404).json({ message: "eventTypeUser.notFound" });
|
||
users.push(eventTypeUser);
|
||
}
|
||
|
||
const organizer = await prisma.user.findUnique({
|
||
where: {
|
||
id: users[0].id,
|
||
},
|
||
select: {
|
||
locale: true,
|
||
},
|
||
});
|
||
|
||
const tOrganizer = await getTranslation(organizer?.locale ?? "en", "common");
|
||
|
||
if (eventType.schedulingType === SchedulingType.ROUND_ROBIN) {
|
||
const bookingCounts = await getUserNameWithBookingCounts(
|
||
eventTypeId,
|
||
ensureArray(reqBody.user) || users.map((user) => user.username)
|
||
);
|
||
|
||
users = getLuckyUsers(users, bookingCounts);
|
||
}
|
||
|
||
const invitee = [
|
||
{
|
||
email: reqBody.email,
|
||
name: reqBody.name,
|
||
timeZone: reqBody.timeZone,
|
||
language: { translate: tAttendees, locale: reqBody.language ?? "en" },
|
||
},
|
||
];
|
||
const guests = (reqBody.guests || []).map((guest) => {
|
||
const g = {
|
||
email: guest,
|
||
name: "",
|
||
timeZone: reqBody.timeZone,
|
||
language: { translate: tGuests, locale: "en" },
|
||
};
|
||
return g;
|
||
});
|
||
|
||
// For seats, if the booking already exists then we want to add the new attendee to the existing booking
|
||
if (reqBody.bookingUid) {
|
||
if (!eventType.seatsPerTimeSlot)
|
||
return res.status(404).json({ message: "Event type does not have seats" });
|
||
|
||
const booking = await prisma.booking.findUnique({
|
||
where: {
|
||
uid: reqBody.bookingUid,
|
||
},
|
||
include: {
|
||
attendees: true,
|
||
},
|
||
});
|
||
if (!booking) return res.status(404).json({ message: "Booking not found" });
|
||
|
||
if (eventType.seatsPerTimeSlot <= booking.attendees.length)
|
||
return res.status(409).json({ message: "Booking seats are full" });
|
||
|
||
if (booking.attendees.some((attendee) => attendee.email === invitee[0].email))
|
||
return res.status(409).json({ message: "Already signed up for time slot" });
|
||
|
||
await prisma.booking.update({
|
||
where: {
|
||
uid: reqBody.bookingUid,
|
||
},
|
||
data: {
|
||
attendees: {
|
||
create: {
|
||
email: invitee[0].email,
|
||
name: invitee[0].name,
|
||
timeZone: invitee[0].timeZone,
|
||
locale: invitee[0].language.locale,
|
||
},
|
||
},
|
||
},
|
||
});
|
||
return res.status(201).json(booking);
|
||
}
|
||
|
||
const teamMemberPromises =
|
||
eventType.schedulingType === SchedulingType.COLLECTIVE
|
||
? users.slice(1).map(async function (user) {
|
||
return {
|
||
email: user.email || "",
|
||
name: user.name || "",
|
||
timeZone: user.timeZone,
|
||
language: {
|
||
translate: await getTranslation(user.locale ?? "en", "common"),
|
||
locale: user.locale ?? "en",
|
||
},
|
||
};
|
||
})
|
||
: [];
|
||
|
||
const teamMembers = await Promise.all(teamMemberPromises);
|
||
|
||
const attendeesList = [...invitee, ...guests, ...teamMembers];
|
||
|
||
const seed = `${users[0].username}:${dayjs(req.body.start).utc().format()}:${new Date().getTime()}`;
|
||
const uid = translator.fromUUID(uuidv5(seed, uuidv5.URL));
|
||
|
||
const eventNameObject = {
|
||
attendeeName: reqBody.name || "Nameless",
|
||
eventType: eventType.title,
|
||
eventName: eventType.eventName,
|
||
host: users[0].name || "Nameless",
|
||
t: tOrganizer,
|
||
};
|
||
|
||
const additionalNotes = reqBody.notes;
|
||
|
||
const customInputs = {} as NonNullable<CalendarEvent["customInputs"]>;
|
||
|
||
if (reqBody.customInputs.length > 0) {
|
||
reqBody.customInputs.forEach(({ label, value }) => {
|
||
customInputs[label] = value;
|
||
});
|
||
}
|
||
|
||
const evt: CalendarEvent = {
|
||
type: eventType.title,
|
||
title: getEventName(eventNameObject), //this needs to be either forced in english, or fetched for each attendee and organizer separately
|
||
description: eventType.description,
|
||
additionalNotes,
|
||
customInputs,
|
||
startTime: reqBody.start,
|
||
endTime: reqBody.end,
|
||
organizer: {
|
||
name: users[0].name || "Nameless",
|
||
email: users[0].email || "Email-less",
|
||
timeZone: users[0].timeZone,
|
||
language: { translate: tOrganizer, locale: organizer?.locale ?? "en" },
|
||
},
|
||
attendees: attendeesList,
|
||
location: reqBody.location, // Will be processed by the EventManager later.
|
||
/** For team events & dynamic collective events, we will need to handle each member destinationCalendar eventually */
|
||
destinationCalendar: eventType.destinationCalendar || users[0].destinationCalendar,
|
||
hideCalendarNotes: eventType.hideCalendarNotes,
|
||
};
|
||
|
||
if (eventType.schedulingType === SchedulingType.COLLECTIVE) {
|
||
evt.team = {
|
||
members: users.map((user) => user.name || user.username || "Nameless"),
|
||
name: eventType.team?.name || "Nameless",
|
||
}; // used for invitee emails
|
||
}
|
||
|
||
if (reqBody.recurringEventId && eventType.recurringEvent) {
|
||
// 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)
|
||
eventType.recurringEvent = Object.assign({}, eventType.recurringEvent, { count: recurringCount });
|
||
}
|
||
|
||
// Initialize EventManager with credentials
|
||
const rescheduleUid = reqBody.rescheduleUid;
|
||
async function getOriginalRescheduledBooking(uid: string) {
|
||
return prisma.booking.findFirst({
|
||
where: {
|
||
uid,
|
||
status: {
|
||
in: [BookingStatus.ACCEPTED, BookingStatus.CANCELLED],
|
||
},
|
||
},
|
||
include: {
|
||
attendees: {
|
||
select: {
|
||
name: true,
|
||
email: true,
|
||
locale: true,
|
||
timeZone: true,
|
||
},
|
||
},
|
||
user: {
|
||
select: {
|
||
id: true,
|
||
name: true,
|
||
email: true,
|
||
locale: true,
|
||
timeZone: true,
|
||
},
|
||
},
|
||
payment: true,
|
||
},
|
||
});
|
||
}
|
||
type BookingType = Prisma.PromiseReturnType<typeof getOriginalRescheduledBooking>;
|
||
let originalRescheduledBooking: BookingType = null;
|
||
if (rescheduleUid) {
|
||
originalRescheduledBooking = await getOriginalRescheduledBooking(rescheduleUid);
|
||
}
|
||
|
||
async function createBooking() {
|
||
// @TODO: check as metadata
|
||
if (req.body.web3Details) {
|
||
const { web3Details } = req.body;
|
||
await verifyAccount(web3Details.userSignature, web3Details.userWallet);
|
||
}
|
||
|
||
if (originalRescheduledBooking) {
|
||
evt.title = originalRescheduledBooking?.title || evt.title;
|
||
evt.description = originalRescheduledBooking?.description || evt.additionalNotes;
|
||
evt.location = originalRescheduledBooking?.location;
|
||
}
|
||
|
||
const eventTypeRel = !eventTypeId
|
||
? {}
|
||
: {
|
||
connect: {
|
||
id: eventTypeId,
|
||
},
|
||
};
|
||
|
||
const dynamicEventSlugRef = !eventTypeId ? eventTypeSlug : null;
|
||
const dynamicGroupSlugRef = !eventTypeId ? (reqBody.user as string).toLowerCase() : null;
|
||
|
||
const newBookingData: Prisma.BookingCreateInput = {
|
||
uid,
|
||
title: evt.title,
|
||
startTime: dayjs(evt.startTime).toDate(),
|
||
endTime: dayjs(evt.endTime).toDate(),
|
||
description: evt.additionalNotes,
|
||
customInputs: isPrismaObjOrUndefined(evt.customInputs),
|
||
confirmed: (!eventType.requiresConfirmation && !eventType.price) || !!rescheduleUid,
|
||
location: evt.location,
|
||
eventType: eventTypeRel,
|
||
attendees: {
|
||
createMany: {
|
||
data: evt.attendees.map((attendee) => {
|
||
//if attendee is team member, it should fetch their locale not booker's locale
|
||
//perhaps make email fetch request to see if his locale is stored, else
|
||
const retObj = {
|
||
name: attendee.name,
|
||
email: attendee.email,
|
||
timeZone: attendee.timeZone,
|
||
locale: attendee.language.locale,
|
||
};
|
||
return retObj;
|
||
}),
|
||
},
|
||
},
|
||
dynamicEventSlugRef,
|
||
dynamicGroupSlugRef,
|
||
user: {
|
||
connect: {
|
||
id: users[0].id,
|
||
},
|
||
},
|
||
destinationCalendar: evt.destinationCalendar
|
||
? {
|
||
connect: { id: evt.destinationCalendar.id },
|
||
}
|
||
: undefined,
|
||
};
|
||
if (reqBody.recurringEventId) {
|
||
newBookingData.recurringEventId = reqBody.recurringEventId;
|
||
}
|
||
if (originalRescheduledBooking) {
|
||
newBookingData["paid"] = originalRescheduledBooking.paid;
|
||
newBookingData["fromReschedule"] = originalRescheduledBooking.uid;
|
||
if (newBookingData.attendees?.createMany?.data) {
|
||
newBookingData.attendees.createMany.data = originalRescheduledBooking.attendees;
|
||
}
|
||
}
|
||
const createBookingObj = {
|
||
include: {
|
||
user: {
|
||
select: { email: true, name: true, timeZone: true },
|
||
},
|
||
attendees: true,
|
||
payment: true,
|
||
},
|
||
data: newBookingData,
|
||
};
|
||
|
||
if (originalRescheduledBooking?.paid && originalRescheduledBooking?.payment) {
|
||
const bookingPayment = originalRescheduledBooking?.payment?.find((payment) => payment.success);
|
||
|
||
if (bookingPayment) {
|
||
createBookingObj.data.payment = {
|
||
connect: { id: bookingPayment.id },
|
||
};
|
||
}
|
||
}
|
||
|
||
/* Validate if there is any stripe_payment credential for this user */
|
||
const stripePaymentCredential = await prisma.credential.findFirst({
|
||
where: {
|
||
type: "stripe_payment",
|
||
userId: users[0].id,
|
||
},
|
||
select: {
|
||
id: true,
|
||
},
|
||
});
|
||
/** eventType doesn’t require payment then we create a booking
|
||
* OR
|
||
* stripePaymentCredential is found and price is higher than 0 then we create a booking
|
||
*/
|
||
if (!eventType.price || (stripePaymentCredential && eventType.price > 0)) {
|
||
return prisma.booking.create(createBookingObj);
|
||
}
|
||
// stripePaymentCredential not found and eventType requires payment we return null
|
||
return null;
|
||
}
|
||
|
||
let results: EventResult[] = [];
|
||
let referencesToCreate: PartialReference[] = [];
|
||
let user: User | null = null;
|
||
|
||
/** Let's start checking for availability */
|
||
for (const currentUser of users) {
|
||
if (!currentUser) {
|
||
console.error(`currentUser not found`);
|
||
return;
|
||
}
|
||
if (!user) user = currentUser;
|
||
|
||
const selectedCalendars = await prisma.selectedCalendar.findMany({
|
||
where: {
|
||
userId: currentUser.id,
|
||
},
|
||
});
|
||
|
||
const busyTimes = await getBusyTimes({
|
||
credentials: currentUser.credentials,
|
||
startTime: reqBody.start,
|
||
endTime: reqBody.end,
|
||
eventTypeId,
|
||
userId: currentUser.id,
|
||
selectedCalendars,
|
||
});
|
||
|
||
console.log("calendarBusyTimes==>>>", busyTimes);
|
||
|
||
const bufferedBusyTimes = busyTimes.map((a) => ({
|
||
start: dayjs(a.start).subtract(currentUser.bufferTime, "minute").toString(),
|
||
end: dayjs(a.end).add(currentUser.bufferTime, "minute").toString(),
|
||
}));
|
||
|
||
let isAvailableToBeBooked = true;
|
||
try {
|
||
if (eventType.recurringEvent) {
|
||
const allBookingDates = new rrule({
|
||
dtstart: new Date(reqBody.start),
|
||
...eventType.recurringEvent,
|
||
}).all();
|
||
// Go through each date for the recurring event and check if each one's availability
|
||
isAvailableToBeBooked = allBookingDates
|
||
.map((aDate) => isAvailable(bufferedBusyTimes, aDate, eventType.length)) // <-- array of booleans
|
||
.reduce((acc, value) => acc && value, true); // <-- checks boolean array applying "AND" to each value and the current one, starting in true
|
||
} else {
|
||
isAvailableToBeBooked = isAvailable(bufferedBusyTimes, reqBody.start, eventType.length);
|
||
}
|
||
} catch {
|
||
log.debug({
|
||
message: "Unable set isAvailableToBeBooked. Using true. ",
|
||
});
|
||
}
|
||
|
||
if (!isAvailableToBeBooked) {
|
||
const error = {
|
||
errorCode: "BookingUserUnAvailable",
|
||
message: `${currentUser.name} is unavailable at this time.`,
|
||
};
|
||
|
||
log.debug(`Booking ${currentUser.name} failed`, error);
|
||
res.status(409).json(error);
|
||
return;
|
||
}
|
||
|
||
let timeOutOfBounds = false;
|
||
|
||
try {
|
||
timeOutOfBounds = isOutOfBounds(reqBody.start, {
|
||
periodType: eventType.periodType,
|
||
periodDays: eventType.periodDays,
|
||
periodEndDate: eventType.periodEndDate,
|
||
periodStartDate: eventType.periodStartDate,
|
||
periodCountCalendarDays: eventType.periodCountCalendarDays,
|
||
});
|
||
} catch {
|
||
log.debug({
|
||
message: "Unable set timeOutOfBounds. Using false. ",
|
||
});
|
||
}
|
||
|
||
if (timeOutOfBounds) {
|
||
const error = {
|
||
errorCode: "BookingUserUnAvailable",
|
||
message: `${currentUser.name} is unavailable at this time.`,
|
||
};
|
||
|
||
log.debug(`Booking ${currentUser.name} failed`, error);
|
||
res.status(400).json(error);
|
||
return;
|
||
}
|
||
}
|
||
|
||
type Booking = Prisma.PromiseReturnType<typeof createBooking>;
|
||
let booking: Booking | null = null;
|
||
try {
|
||
booking = await createBooking();
|
||
evt.uid = booking?.uid ?? null;
|
||
} catch (_err) {
|
||
const err = getErrorFromUnknown(_err);
|
||
log.error(`Booking ${eventTypeId} failed`, "Error when saving booking to db", err.message);
|
||
if (err.code === "P2002") {
|
||
res.status(409).json({ message: "booking.conflict" });
|
||
return;
|
||
}
|
||
res.status(500).end();
|
||
return;
|
||
}
|
||
|
||
if (!user) throw Error("Can't continue, user not found.");
|
||
|
||
// After polling videoBusyTimes, credentials might have been changed due to refreshment, so query them again.
|
||
const credentials = await refreshCredentials(user.credentials);
|
||
const eventManager = new EventManager({ ...user, credentials });
|
||
|
||
if (originalRescheduledBooking?.uid) {
|
||
// Use EventManager to conditionally use all needed integrations.
|
||
const updateManager = await eventManager.update(
|
||
evt,
|
||
originalRescheduledBooking.uid,
|
||
booking?.id,
|
||
reqBody.rescheduleReason
|
||
);
|
||
// This gets overridden when updating the event - to check if notes have been hidden or not. We just reset this back
|
||
// to the default description when we are sending the emails.
|
||
evt.description = eventType.description;
|
||
|
||
results = updateManager.results;
|
||
referencesToCreate = updateManager.referencesToCreate;
|
||
if (results.length > 0 && results.some((res) => !res.success)) {
|
||
const error = {
|
||
errorCode: "BookingReschedulingMeetingFailed",
|
||
message: "Booking Rescheduling failed",
|
||
};
|
||
|
||
log.error(`Booking ${user.name} failed`, error, results);
|
||
} else {
|
||
const metadata: AdditionInformation = {};
|
||
|
||
if (results.length) {
|
||
// TODO: Handle created event metadata more elegantly
|
||
const [updatedEvent] = Array.isArray(results[0].updatedEvent)
|
||
? results[0].updatedEvent
|
||
: [results[0].updatedEvent];
|
||
if (updatedEvent) {
|
||
metadata.hangoutLink = updatedEvent.hangoutLink;
|
||
metadata.conferenceData = updatedEvent.conferenceData;
|
||
metadata.entryPoints = updatedEvent.entryPoints;
|
||
}
|
||
}
|
||
|
||
if (noEmail !== true) {
|
||
await sendRescheduledEmails(
|
||
{
|
||
...evt,
|
||
additionInformation: metadata,
|
||
additionalNotes, // Resets back to the additionalNote input and not the override value
|
||
cancellationReason: reqBody.rescheduleReason,
|
||
},
|
||
reqBody.recurringEventId ? (eventType.recurringEvent as RecurringEvent) : {}
|
||
);
|
||
}
|
||
}
|
||
// If it's not a reschedule, doesn't require confirmation and there's no price,
|
||
// Create a booking
|
||
} else if (!eventType.requiresConfirmation && !eventType.price) {
|
||
// Use EventManager to conditionally use all needed integrations.
|
||
const createManager = await eventManager.create(evt);
|
||
|
||
// This gets overridden when creating the event - to check if notes have been hidden or not. We just reset this back
|
||
// to the default description when we are sending the emails.
|
||
evt.description = eventType.description;
|
||
|
||
results = createManager.results;
|
||
referencesToCreate = createManager.referencesToCreate;
|
||
if (results.length > 0 && results.every((res) => !res.success)) {
|
||
const error = {
|
||
errorCode: "BookingCreatingMeetingFailed",
|
||
message: "Booking failed",
|
||
};
|
||
|
||
log.error(`Booking ${user.username} failed`, error, results);
|
||
} else {
|
||
const metadata: AdditionInformation = {};
|
||
|
||
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;
|
||
}
|
||
if (noEmail !== true) {
|
||
await sendScheduledEmails(
|
||
{
|
||
...evt,
|
||
additionInformation: metadata,
|
||
additionalNotes,
|
||
customInputs,
|
||
},
|
||
reqBody.recurringEventId ? (eventType.recurringEvent as RecurringEvent) : {}
|
||
);
|
||
}
|
||
}
|
||
}
|
||
|
||
if (eventType.requiresConfirmation && !rescheduleUid && noEmail !== true) {
|
||
await sendOrganizerRequestEmail(
|
||
{ ...evt, additionalNotes },
|
||
reqBody.recurringEventId ? (eventType.recurringEvent as RecurringEvent) : {}
|
||
);
|
||
await sendAttendeeRequestEmail(
|
||
{ ...evt, additionalNotes },
|
||
attendeesList[0],
|
||
reqBody.recurringEventId ? (eventType.recurringEvent as RecurringEvent) : {}
|
||
);
|
||
}
|
||
|
||
if (
|
||
!Number.isNaN(eventType.price) &&
|
||
eventType.price > 0 &&
|
||
!originalRescheduledBooking?.paid &&
|
||
!!booking
|
||
) {
|
||
try {
|
||
const [firstStripeCredential] = user.credentials.filter((cred) => cred.type == "stripe_payment");
|
||
|
||
if (!firstStripeCredential) return res.status(500).json({ message: "Missing payment credentials" });
|
||
|
||
if (!booking.user) booking.user = user;
|
||
const payment = await handlePayment(evt, eventType, firstStripeCredential, booking);
|
||
|
||
res.status(201).json({ ...booking, message: "Payment required", paymentUid: payment.uid });
|
||
return;
|
||
} catch (e) {
|
||
log.error(`Creating payment failed`, e);
|
||
res.status(500).json({ message: "Payment Failed" });
|
||
return;
|
||
}
|
||
}
|
||
|
||
log.debug(`Booking ${user.username} completed`);
|
||
|
||
const eventTrigger: WebhookTriggerEvents = rescheduleUid ? "BOOKING_RESCHEDULED" : "BOOKING_CREATED";
|
||
const subscriberOptions = {
|
||
userId: user.id,
|
||
eventTypeId,
|
||
triggerEvent: eventTrigger,
|
||
};
|
||
|
||
// Send Webhook call if hooked to BOOKING_CREATED & BOOKING_RESCHEDULED
|
||
const subscribers = await getSubscribers(subscriberOptions);
|
||
console.log("evt:", {
|
||
...evt,
|
||
metadata: reqBody.metadata,
|
||
});
|
||
const promises = subscribers.map((sub) =>
|
||
sendPayload(eventTrigger, new Date().toISOString(), sub, {
|
||
...evt,
|
||
rescheduleUid,
|
||
metadata: reqBody.metadata,
|
||
}).catch((e) => {
|
||
console.error(`Error executing webhook for event: ${eventTrigger}, URL: ${sub.subscriberUrl}`, e);
|
||
})
|
||
);
|
||
await Promise.all(promises);
|
||
// Avoid passing referencesToCreate with id unique constrain values
|
||
// refresh hashed link if used
|
||
const urlSeed = `${users[0].username}:${dayjs(req.body.start).utc().format()}`;
|
||
const hashedUid = translator.fromUUID(uuidv5(urlSeed, uuidv5.URL));
|
||
|
||
if (hasHashedBookingLink) {
|
||
await prisma.hashedLink.update({
|
||
where: {
|
||
link: reqBody.hashedLink as string,
|
||
},
|
||
data: {
|
||
link: hashedUid,
|
||
},
|
||
});
|
||
}
|
||
if (booking) {
|
||
await prisma.booking.update({
|
||
where: {
|
||
uid: booking.uid,
|
||
},
|
||
data: {
|
||
references: {
|
||
createMany: {
|
||
data: referencesToCreate,
|
||
},
|
||
},
|
||
},
|
||
});
|
||
// booking successful
|
||
return res.status(201).json(booking);
|
||
}
|
||
return res.status(400).json({ message: "There is not a stripe_payment credential" });
|
||
}
|
||
|
||
export function getLuckyUsers(
|
||
users: User[],
|
||
bookingCounts: Prisma.PromiseReturnType<typeof getUserNameWithBookingCounts>
|
||
) {
|
||
if (!bookingCounts.length) users.slice(0, 1);
|
||
|
||
const [firstMostAvailableUser] = bookingCounts.sort((a, b) => (a.bookingCount > b.bookingCount ? 1 : -1));
|
||
const luckyUser = users.find((user) => user.username === firstMostAvailableUser?.username);
|
||
return luckyUser ? [luckyUser] : users;
|
||
}
|