feat(bookings): improve bookings redesign (#25251)

* use booking.uid instead of booking.id for url param

* show timezone on calendar

* fix type

* restore horizontal tab and remove header and subtitle

* clean up sidebar items

* fix event propagation from attendees

* fetch all statuses except for cancelled on calendar view

* clean up styles of the badges on BookingListItem

* fix useMediaQuery

* add close button to the header

* add assignment reason to the details sheet

* use separator row

* use ToggleGroup for the top bookings tab

* move ViewToggleButton

* resize the action button

* remove wrong prop

* fix type error

* fix type error

* hide view toggle button on mobile (and fix the breakpoint)

* remove unused e2e tests

* fix e2e tests

* hide toggle button when feature flag is off

* update skeleton

* improve attendees on booking list item and slide over

* improve attendee dropdown

* fix type error

* move query to containers

* select attendee email

* infinite fetching for calendar view

* update styles

* fix compatibility

* fix: add backward compatibility for status field in getAllUserBookings

* increase calendar height

* fix type error

* support Member filter only for admin / owners

* add debug log (TEMP)

* add event border color

* show Reject / Accept buttons on BookingDetailsSheet

* move description section to the top

* update When section

* update style of Who section

* add CancelBookingDialog WIP

* fix CancelBookingDialog

* increase clickable area

* add schedule info section WIP

* fix flaky reject button

* fixing reschedule info WIP

* add fromReschedule index to Booking

* improve rescheduled information

* improve reassignment

* fix type error

* fix unit test

* respect user's weekStart value on the booking calendar view

* update debug log

* improve payment section

* clean up

* fix log message

* reposition filters on list view

* fix bookings controller api2 e2e test

* clean up file by extracting logic into custom hooks

* rename files

* merge BookingCalendar into its container

* extract logic into separate hook files

* remove redundant logic

* rearrange items on calendar view

* add WeekPicker

* extract filter button

* responsive header on list view

* horizontal scroll for ToggleGroup WIP

* fix type error

* fix cancelling recurring event

* address feedback

* fix e2e tests

* fix unit test

* fix e2e tests

* make hover style more visible for ToggleGroup

* fix margin on CancelBookingDialog

* update styles on the slide over (mostly font weight)

* update style of CancelBookingDialog

* update styles

* update margin top for the header

* refactor getBookingDetails handler

* fix gap in who section

* auto-filter the current user on the calendar view

* calculate calendar height considering top banners

* improve booking details sheet interaction without overlay

* update calendar event styles

* update reject dialog style

* put uid first in the query params

* fix class name

* memoize functions in useMediaQuery

* query attendee with id instead of email

* update margins

* replace TRPCError with ErrorWithCode

* move calculation outside loop

* remove dead code
This commit is contained in:
Eunjae Lee authored and GitHub committed 2025-12-10 13:40:04 +00:00
1 parent 41b71d845c
commit 3986d61f40
90 files changed
+3741 -2079

No files matched your search

+494 -108
View File
@@ -3,9 +3,10 @@ import { v4 as uuidv4 } from "uuid";
import dayjs from "@calcom/dayjs";
import { hashPassword } from "@calcom/lib/auth/hashPassword";
import { RefundPolicy } from "@calcom/lib/payment/types";
import { prisma } from "@calcom/prisma";
import type { Prisma } from "@calcom/prisma/client";
import { BookingStatus, AssignmentReasonEnum } from "@calcom/prisma/enums";
import { BookingStatus, AssignmentReasonEnum, PaymentOption } from "@calcom/prisma/enums";
import { seedAttributes, seedRoutingFormResponses, seedRoutingForms } from "./seed-utils";
@@ -35,8 +36,18 @@ function getRandomRatingFeedback() {
return feedbacks[Math.floor(Math.random() * feedbacks.length)];
}
type BookingInput = {
uid: string;
title: string;
description: string;
startTime: string;
endTime: string;
userId: number;
[key: string]: unknown;
};
const shuffle = (
booking: any,
booking: BookingInput,
year: number,
eventTypesToPick: Prisma.EventTypeGetPayload<{
select: {
@@ -46,6 +57,7 @@ const shuffle = (
length: true;
description: true;
teamId: true;
recurringEvent: true;
};
}>[],
usersIdsToPick?: number[]
@@ -60,7 +72,7 @@ const shuffle = (
const endTime = dayjs(startTime).add(Math.floor(Math.random() * randomEvent.length), "minute");
booking.title = randomEvent.title;
booking.description = randomEvent.description;
booking.description = randomEvent.description || "";
booking.startTime = startTime.toISOString();
booking.endTime = endTime.toISOString();
booking.createdAt = startTime.subtract(1, "day").toISOString();
@@ -80,13 +92,11 @@ const shuffle = (
if (usersIdsToPick && usersIdsToPick.length > 0) {
// Pick a random user from all available users instead of just two
booking.userId = usersIdsToPick[Math.floor(Math.random() * usersIdsToPick.length)];
} else {
} else if (randomEvent.userId) {
booking.userId = randomEvent.userId;
}
if (booking.userId === undefined || booking.userId === null) {
} else {
console.log({ randomEvent, usersIdsToPick });
console.log("This should not happen");
throw new Error("No valid userId available for booking");
}
booking.rating = Math.floor(Math.random() * 5) + 1; // Generates a random rating from 1 to 5
@@ -125,24 +135,40 @@ const shuffle = (
return booking;
};
async function createAttendees(bookings: any[]) {
for (const booking of bookings) {
type BookingWithId = {
id: number;
};
async function createAttendees(bookings: BookingWithId[]) {
// Batch create all attendees at once
const allAttendees = bookings.flatMap((booking) =>
Array(Math.floor(Math.random() * 4))
.fill(null)
.map(() => ({
bookingId: booking.id,
timeZone: faker.location.timeZone(),
email: faker.internet.email(),
name: faker.person.fullName(),
}))
);
if (allAttendees.length > 0) {
await prisma.attendee.createMany({
data: Array(Math.floor(Math.random() * 4))
.fill(null)
.map(() => {
return {
bookingId: booking.id,
timeZone: faker.location.timeZone(),
email: faker.internet.email(),
name: faker.person.fullName(),
};
}),
data: allAttendees,
});
}
}
async function createPayments(bookings: any[]) {
type BookingWithEventType = {
id: number;
paid: boolean;
eventType?: {
price?: number;
currency?: string;
};
};
async function _createPayments(bookings: BookingWithEventType[]) {
// Filter for paid bookings
const paidBookings = bookings.filter((booking) => booking.paid);
@@ -178,8 +204,61 @@ async function createPayments(bookings: any[]) {
console.log(`Successfully created payments for ${paidBookings.length} bookings`);
}
async function createPaidEventTypeAndBookings(organizationId: number) {
console.log("Creating paid event type and bookings...");
type PaymentScenario = {
status: BookingStatus;
paid: boolean;
success: boolean;
refunded: boolean;
paymentOption?: PaymentOption;
startTime: dayjs.Dayjs;
cancellationReason?: string;
scenarioName: string;
};
type BookingWithPaymentData = {
id: number;
eventType?: {
price?: number;
currency?: string;
};
paymentSuccess: boolean;
paymentRefunded: boolean;
paymentOption: PaymentOption;
};
async function createPaymentsForScenarios(bookings: BookingWithPaymentData[]) {
console.log(`Creating payments for ${bookings.length} bookings with diverse scenarios...`);
// Batch create all payments at once
const paymentData = bookings.map((booking) => {
const amount = booking.eventType?.price || 5000;
const currency = booking.eventType?.currency || "usd";
const paymentOption = booking.paymentOption || PaymentOption.ON_BOOKING;
return {
uid: uuidv4(),
appId: "stripe",
bookingId: booking.id,
amount,
fee: Math.floor(amount * 0.029) + 30,
currency,
success: booking.paymentSuccess,
refunded: booking.paymentRefunded,
paymentOption,
data: {},
externalId: `ch_${uuidv4().substring(0, 24)}`,
};
});
await prisma.payment.createMany({
data: paymentData,
});
console.log(`Successfully created payments for ${bookings.length} bookings`);
}
async function createDiversePaymentBookings(organizationId: number) {
console.log("\n=== Creating diverse payment event types and bookings ===");
// Find the insights team
const insightsTeam = await prisma.team.findFirst({
@@ -190,7 +269,7 @@ async function createPaidEventTypeAndBookings(organizationId: number) {
});
if (!insightsTeam) {
console.log("Insights team not found, skipping paid event type creation");
console.log("Insights team not found, skipping payment event type creation");
return;
}
@@ -205,108 +284,401 @@ async function createPaidEventTypeAndBookings(organizationId: number) {
});
if (insightsTeamMembers.length === 0) {
console.log("No team members found, skipping paid event type creation");
console.log("No team members found, skipping payment event type creation");
return;
}
// Check if paid event type already exists
let paidEventType = await prisma.eventType.findFirst({
where: {
slug: "paid-consultation",
teamId: insightsTeam.id,
// Create multiple event types with different pricing and refund policies
const eventTypeConfigs = [
{
slug: "standard-consultation",
title: "Standard Consultation",
price: 5000,
refundPolicy: RefundPolicy.ALWAYS,
description: "1-hour consultation with full refund policy",
},
});
{
slug: "premium-consultation",
title: "Premium Consultation",
price: 10000,
refundPolicy: RefundPolicy.DAYS,
refundDaysCount: 7,
description: "Premium 1-hour consultation with 7-day refund window",
},
{
slug: "non-refundable-session",
title: "Non-Refundable Session",
price: 7500,
refundPolicy: RefundPolicy.NEVER,
description: "1-hour session - non-refundable",
},
{
slug: "consultation-with-hold",
title: "Consultation with Payment Hold",
price: 5000,
refundPolicy: RefundPolicy.ALWAYS,
paymentOption: PaymentOption.HOLD,
description: "1-hour consultation with payment hold option",
},
];
// Create paid event type if it doesn't exist
if (!paidEventType) {
paidEventType = await prisma.eventType.create({
data: {
title: "Paid Consultation",
slug: "paid-consultation",
description: "1-hour paid consultation session",
length: 60,
type EventTypeWithRequiredFields = Prisma.EventTypeGetPayload<{
select: {
id: true;
title: true;
slug: true;
description: true;
length: true;
price: true;
currency: true;
metadata: true;
};
}>;
const createdEventTypes: EventTypeWithRequiredFields[] = [];
for (const config of eventTypeConfigs) {
let eventType = await prisma.eventType.findFirst({
where: {
slug: config.slug,
teamId: insightsTeam.id,
schedulingType: "ROUND_ROBIN",
assignAllTeamMembers: true,
price: 5000, // $50.00
currency: "usd",
metadata: {
apps: {
stripe: {
price: 5000,
currency: "usd",
enabled: true,
},
},
},
},
select: {
id: true,
title: true,
slug: true,
description: true,
length: true,
price: true,
currency: true,
metadata: true,
},
});
// Create Host records for all team members
await prisma.host.createMany({
data: insightsTeamMembers.map((member) => ({
userId: member.user.id,
eventTypeId: paidEventType!.id,
isFixed: false,
})),
skipDuplicates: true,
});
if (!eventType) {
type StripeMetadata = {
price: number;
currency: string;
enabled: boolean;
refundPolicy: RefundPolicy;
refundDaysCount?: number;
paymentOption?: PaymentOption;
};
console.log(`Created paid event type: ${paidEventType.title}`);
const stripeConfig: StripeMetadata = {
price: config.price,
currency: "usd",
enabled: true,
refundPolicy: config.refundPolicy,
};
if (config.refundDaysCount) {
stripeConfig.refundDaysCount = config.refundDaysCount;
}
if (config.paymentOption) {
stripeConfig.paymentOption = config.paymentOption;
}
const metadata: Prisma.InputJsonValue = {
apps: {
stripe: stripeConfig,
},
};
const createdEventType = await prisma.eventType.create({
data: {
title: config.title,
slug: config.slug,
description: config.description,
length: 60,
teamId: insightsTeam.id,
schedulingType: "ROUND_ROBIN",
assignAllTeamMembers: true,
price: config.price,
currency: "usd",
metadata,
},
select: {
id: true,
title: true,
slug: true,
description: true,
length: true,
price: true,
currency: true,
metadata: true,
},
});
// Create Host records for all team members
await prisma.host.createMany({
data: insightsTeamMembers.map((member) => ({
userId: member.user.id,
eventTypeId: createdEventType.id,
isFixed: false,
})),
skipDuplicates: true,
});
console.log(`Created event type: ${createdEventType.title}`);
eventType = createdEventType;
}
createdEventTypes.push(eventType);
}
// Create 100 paid bookings
const baseBooking = {
uid: "demoUID",
title: "Paid Consultation",
description: "1-hour paid consultation session",
startTime: dayjs().toISOString(),
endTime: dayjs().toISOString(),
userId: insightsTeamMembers[0].user.id,
// Define payment scenarios with specific distributions
const scenarios: {
eventTypeIndex: number;
count: number;
scenario: Partial<PaymentScenario>;
}[] = [
// Scenario 1: Successful paid bookings (20%)
{
eventTypeIndex: 0,
count: 20,
scenario: {
status: BookingStatus.ACCEPTED,
paid: true,
success: true,
refunded: false,
startTime: dayjs().add(7, "days"),
scenarioName: "Successful Paid",
},
},
// Scenario 2: Awaiting payment (15%)
{
eventTypeIndex: 0,
count: 15,
scenario: {
status: BookingStatus.ACCEPTED,
paid: true,
success: false,
refunded: false,
startTime: dayjs().add(5, "days"),
scenarioName: "Awaiting Payment",
},
},
// Scenario 3: Awaiting payment with HOLD option (10%)
{
eventTypeIndex: 3,
count: 10,
scenario: {
status: BookingStatus.PENDING,
paid: true,
success: false,
refunded: false,
paymentOption: PaymentOption.HOLD,
startTime: dayjs().add(3, "days"),
scenarioName: "Awaiting Payment (HOLD)",
},
},
// Scenario 4: Cancelled with refund completed (10%)
{
eventTypeIndex: 0,
count: 10,
scenario: {
status: BookingStatus.CANCELLED,
paid: true,
success: true,
refunded: true,
startTime: dayjs().subtract(2, "days"),
cancellationReason: "Customer requested refund",
scenarioName: "Cancelled - Refunded",
},
},
// Scenario 5: Cancelled with ALWAYS policy (10%)
{
eventTypeIndex: 0,
count: 10,
scenario: {
status: BookingStatus.CANCELLED,
paid: true,
success: true,
refunded: false,
startTime: dayjs().subtract(1, "days"),
cancellationReason: "Change of plans",
scenarioName: "Cancelled - ALWAYS policy (no refund yet)",
},
},
// Scenario 6: Cancelled with NEVER policy (10%)
{
eventTypeIndex: 2,
count: 10,
scenario: {
status: BookingStatus.CANCELLED,
paid: true,
success: true,
refunded: false,
startTime: dayjs().subtract(3, "days"),
cancellationReason: "Emergency cancellation",
scenarioName: "Cancelled - NEVER policy",
},
},
// Scenario 7: Cancelled DAYS policy - within window (10%)
{
eventTypeIndex: 1,
count: 10,
scenario: {
status: BookingStatus.CANCELLED,
paid: true,
success: true,
refunded: false,
startTime: dayjs().add(5, "days"),
cancellationReason: "Need to reschedule",
scenarioName: "Cancelled - DAYS policy (within window)",
},
},
// Scenario 8: Cancelled DAYS policy - expired (10%)
{
eventTypeIndex: 1,
count: 10,
scenario: {
status: BookingStatus.CANCELLED,
paid: true,
success: true,
refunded: false,
startTime: dayjs().subtract(10, "days"),
cancellationReason: "Late cancellation",
scenarioName: "Cancelled - DAYS policy (expired window)",
},
},
// Scenario 9: Cancelled without success (5%)
{
eventTypeIndex: 0,
count: 5,
scenario: {
status: BookingStatus.CANCELLED,
paid: true,
success: false,
refunded: false,
startTime: dayjs().add(2, "days"),
cancellationReason: "Payment failed, cancelled",
scenarioName: "Cancelled - No payment success",
},
},
];
// Create bookings for each scenario
type ScenarioBooking = {
uid: string;
title: string;
description: string;
startTime: string;
endTime: string;
createdAt: string;
status: BookingStatus;
eventTypeId: number;
userId: number;
paid: boolean;
rescheduled: boolean;
cancellationReason: string | null;
paymentSuccess: boolean;
paymentRefunded: boolean;
paymentOption: PaymentOption;
scenarioName: string;
};
console.log(`Creating 100 paid bookings for event type: ${paidEventType.title}`);
const allScenarioBookings: ScenarioBooking[] = [];
for (const { eventTypeIndex, count, scenario } of scenarios) {
const eventType = createdEventTypes[eventTypeIndex];
for (let i = 0; i < count; i++) {
const startTime = scenario.startTime!;
const endTime = dayjs(startTime).add(60, "minutes");
allScenarioBookings.push({
uid: uuidv4(),
title: eventType.title,
description: eventType.description || "",
startTime: startTime.toISOString(),
endTime: endTime.toISOString(),
createdAt: startTime.subtract(1, "day").toISOString(),
status: scenario.status!,
eventTypeId: eventType.id,
userId: insightsTeamMembers[Math.floor(Math.random() * insightsTeamMembers.length)].user.id,
paid: scenario.paid!,
rescheduled: false,
cancellationReason: scenario.cancellationReason || null,
// Store payment details temporarily for payment creation
paymentSuccess: scenario.success!,
paymentRefunded: scenario.refunded!,
paymentOption: scenario.paymentOption || PaymentOption.ON_BOOKING,
scenarioName: scenario.scenarioName!,
});
}
console.log(`Prepared ${count} bookings for scenario: ${scenario.scenarioName}`);
}
console.log(`Creating ${allScenarioBookings.length} bookings across all scenarios...`);
// Insert all bookings
await prisma.booking.createMany({
data: [
...new Array(100).fill(0).map(() => {
const booking = shuffle(
{ ...baseBooking },
dayjs().get("y"),
[paidEventType!],
insightsTeamMembers.map((m) => m.user.id)
);
// Override status for paid bookings - they should always be accepted
booking.status = "ACCEPTED";
booking.paid = true;
booking.rescheduled = false;
return booking;
}),
],
data: allScenarioBookings.map((booking) => {
// Remove temporary payment fields before inserting
const {
paymentSuccess: _ps,
paymentRefunded: _pr,
paymentOption: _po,
scenarioName: _sn,
...bookingData
} = booking;
return bookingData;
}),
});
// Get the paid bookings we just created
const paidBookings = await prisma.booking.findMany({
// Get created bookings with event types
// Use a more specific query to get only the bookings we just created
const eventTypeIds = createdEventTypes.map((et) => et.id);
const createdBookings = await prisma.booking.findMany({
where: {
eventTypeId: paidEventType.id,
paid: true,
eventTypeId: { in: eventTypeIds },
paid: true, // Only get paid bookings since we created them with paid: true
},
include: {
eventType: {
select: {
price: true,
currency: true,
metadata: true,
},
},
},
orderBy: {
id: "desc", // Order by ID is faster than createdAt
},
take: allScenarioBookings.length,
});
// Create attendees for paid bookings
await createAttendees(paidBookings);
// Match created bookings with scenario data to restore payment fields
const bookingsForPayments: BookingWithPaymentData[] = createdBookings
.slice(0, allScenarioBookings.length)
.map((booking, index) => {
const scenarioBooking = allScenarioBookings[allScenarioBookings.length - 1 - index]; // Reverse order since we sorted desc
return {
id: booking.id,
eventType: booking.eventType || undefined,
paymentSuccess: scenarioBooking.paymentSuccess,
paymentRefunded: scenarioBooking.paymentRefunded,
paymentOption: scenarioBooking.paymentOption,
};
});
// Create payments for paid bookings
await createPayments(paidBookings);
// Create attendees for all bookings
await createAttendees(createdBookings);
console.log(`Successfully created ${paidBookings.length} paid bookings with payments`);
// Create payments with appropriate states for each scenario
await createPaymentsForScenarios(bookingsForPayments);
console.log(`Successfully created ${allScenarioBookings.length} bookings with diverse payment scenarios`);
console.log("\nScenario distribution:");
scenarios.forEach(({ count, scenario }) => {
console.log(` - ${scenario.scenarioName}: ${count} bookings`);
});
console.log("=== Diverse payment bookings creation completed ===\n");
}
async function seedBookingAssignments() {
@@ -518,7 +890,7 @@ async function main() {
// After creating or fetching teamEvents and insightsTeamMembers
// Create Host records for all team members for each event with assignAllTeamMembers true
const assignAllTeamMembersEvents = teamEvents.filter((event) => (event as any).assignAllTeamMembers);
const assignAllTeamMembersEvents = teamEvents.filter((event) => event.assignAllTeamMembers);
if (assignAllTeamMembersEvents.length > 0 && insightsTeamMembers.length > 0) {
const hostRecords = assignAllTeamMembersEvents.flatMap((event) =>
insightsTeamMembers.map((member) => ({
@@ -550,9 +922,11 @@ async function main() {
};
// Create past bookings -2y, -1y, -0y
// NOTE: Reduced from 10000 to 1000 to avoid transaction timeout
// Increase these numbers back to 10000 if you need more data for performance testing
await prisma.booking.createMany({
data: [
...new Array(10000).fill(0).map(() =>
...new Array(1000).fill(0).map(() =>
shuffle(
{ ...baseBooking },
dayjs().get("y") - 2,
@@ -565,7 +939,7 @@ async function main() {
await prisma.booking.createMany({
data: [
...new Array(10000).fill(0).map(() =>
...new Array(1000).fill(0).map(() =>
shuffle(
{ ...baseBooking },
dayjs().get("y") - 1,
@@ -578,7 +952,7 @@ async function main() {
await prisma.booking.createMany({
data: [
...new Array(10000).fill(0).map(() =>
...new Array(1000).fill(0).map(() =>
shuffle(
{ ...baseBooking },
dayjs().get("y"),
@@ -600,10 +974,15 @@ async function main() {
if (!attributes) {
throw new Error("Attributes not found");
}
if (!javascriptEventId || !salesEventId) {
throw new Error("Required event types not found");
}
const seededForm = await seedRoutingForms(
insightsTeam.id,
owner?.user.id ?? insightsTeamMembers[0].user.id,
attributes
attributes,
javascriptEventId,
salesEventId
);
if (seededForm) {
@@ -612,8 +991,8 @@ async function main() {
await seedBookingAssignments();
// Create paid event type and bookings separately
await createPaidEventTypeAndBookings(organization.id);
// Create diverse payment scenarios for testing
await createDiversePaymentBookings(organization.id);
}
async function runMain() {
@@ -652,18 +1031,15 @@ async function createPerformanceData() {
});
if (createExtraMembers) {
const insightsRandomUsers: Prisma.UserCreateManyArgs["data"] = [];
const insightsRandomUsers: { email: string; name: string; username: string }[] = [];
const numInsightsUsers = 50; // Change this value to adjust the number of insights users to create
const passwordHash = await hashPassword("insightsuser");
for (let i = 0; i < numInsightsUsers; i++) {
const timestamp = Date.now();
const email = `insightsuser${timestamp}@example.com`;
const insightsUser = {
email,
password: {
create: {
hash: await hashPassword("insightsuser"),
},
},
name: `Insights User ${timestamp}`,
username: `insights-user-${timestamp}`,
completedOnboarding: true,
@@ -674,6 +1050,7 @@ async function createPerformanceData() {
await prisma.user.createMany({
data: insightsRandomUsers,
});
// Lets find the ids of the users we just created
extraMembersIds = await prisma.user.findMany({
where: {
@@ -685,6 +1062,14 @@ async function createPerformanceData() {
id: true,
},
});
// Create passwords for all users
await prisma.userPassword.createMany({
data: extraMembersIds.map((user) => ({
userId: user.id,
hash: passwordHash,
})),
});
}
if (createExtraMembers) {
@@ -761,6 +1146,7 @@ async function createPerformanceData() {
startTime: dayjs().toISOString(),
endTime: dayjs().toISOString(),
eventTypeId: singleEventsCreated[0].id,
userId: extraMembersIds[0].id,
};
await prisma.booking.createMany({