refactor: remove @calcom/features dependency from @calcom/prisma (#23820)
This commit is contained in:
@@ -0,0 +1,91 @@
|
||||
/**
|
||||
* This script can be used to seed the database with a lot of data for performance testing.
|
||||
* TODO: Make it more structured and configurable from CLI
|
||||
* Run it as `npx ts-node --transpile-only ./seed-huge-event-types.ts`
|
||||
*/
|
||||
import { createTeamAndAddUsers, createUserAndEventType } from "./seed-utils";
|
||||
|
||||
const getEventTypes = (numberOfEventTypes: number) => {
|
||||
const eventTypes = Array<{
|
||||
title: string;
|
||||
slug: string;
|
||||
length: number;
|
||||
}>(numberOfEventTypes)
|
||||
.fill({
|
||||
title: "30min",
|
||||
slug: "30min",
|
||||
length: 30,
|
||||
})
|
||||
.map((event, index) => {
|
||||
return {
|
||||
...event,
|
||||
title: `30min-${index}`,
|
||||
slug: `30min-${index}`,
|
||||
};
|
||||
});
|
||||
return eventTypes;
|
||||
};
|
||||
|
||||
async function createTeamsWithEventTypes({
|
||||
owner,
|
||||
numberOfTeams,
|
||||
numberOfEventTypes,
|
||||
}: {
|
||||
owner: { id: number; username: string | null };
|
||||
numberOfTeams: number;
|
||||
numberOfEventTypes: number;
|
||||
}) {
|
||||
const members = [owner];
|
||||
for (let i = 0; i < 10; i++) {
|
||||
members.push(
|
||||
await createUserAndEventType({
|
||||
user: {
|
||||
email: `enterprise-member-${i + 1}@example.com`,
|
||||
name: `Enterprise Member ${i + 1}`,
|
||||
password: `enterprise-member-${i + 1}`,
|
||||
username: `enterprise-member-${i + 1}`,
|
||||
theme: "light",
|
||||
},
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
for (let i = 0; i < numberOfTeams; i++) {
|
||||
await createTeamAndAddUsers(
|
||||
{
|
||||
name: `Enterprise Team-${i + 1}`,
|
||||
slug: `enterprise-team-${i + 1}`,
|
||||
eventTypes: {
|
||||
createMany: {
|
||||
data: getEventTypes(numberOfEventTypes).map((eventType) => {
|
||||
return {
|
||||
...eventType,
|
||||
schedulingType: "COLLECTIVE",
|
||||
};
|
||||
}),
|
||||
},
|
||||
},
|
||||
createdAt: new Date(),
|
||||
},
|
||||
members.map((member) => ({
|
||||
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
|
||||
username: member.username!,
|
||||
id: member.id,
|
||||
}))
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export default async function main() {
|
||||
const owner = await createUserAndEventType({
|
||||
user: {
|
||||
email: `enterprise@example.com`,
|
||||
name: "Enterprise Owner",
|
||||
password: "enterprise",
|
||||
username: `enterprise`,
|
||||
theme: "light",
|
||||
},
|
||||
eventTypes: getEventTypes(100),
|
||||
});
|
||||
await createTeamsWithEventTypes({ owner, numberOfTeams: 10, numberOfEventTypes: 100 });
|
||||
}
|
||||
@@ -0,0 +1,543 @@
|
||||
import { faker } from "@faker-js/faker";
|
||||
import { v4 as uuidv4 } from "uuid";
|
||||
|
||||
import dayjs from "@calcom/dayjs";
|
||||
import { hashPassword } from "@calcom/lib/auth/hashPassword";
|
||||
import type { Prisma } from "@calcom/prisma/client";
|
||||
import { PrismaClient } from "@calcom/prisma/client";
|
||||
import { BookingStatus, AssignmentReasonEnum } from "@calcom/prisma/enums";
|
||||
|
||||
import { seedAttributes, seedRoutingFormResponses, seedRoutingForms } from "./seed-utils";
|
||||
|
||||
function getRandomRatingFeedback() {
|
||||
const feedbacks = [
|
||||
"Great chat!",
|
||||
"Okay-ish",
|
||||
"Quite Poor",
|
||||
"Excellent chat!",
|
||||
"Could be better",
|
||||
"Wonderful!",
|
||||
];
|
||||
return feedbacks[Math.floor(Math.random() * feedbacks.length)];
|
||||
}
|
||||
|
||||
const shuffle = (
|
||||
booking: any,
|
||||
year: number,
|
||||
eventTypesToPick: Prisma.EventTypeGetPayload<{
|
||||
select: {
|
||||
id: true;
|
||||
userId: true;
|
||||
title: true;
|
||||
length: true;
|
||||
description: true;
|
||||
teamId: true;
|
||||
};
|
||||
}>[],
|
||||
usersIdsToPick?: number[]
|
||||
) => {
|
||||
const startTime = dayjs(booking.startTime)
|
||||
.add(Math.floor(Math.random() * 365), "day")
|
||||
.add(Math.floor(Math.random() * 24), "hour")
|
||||
.add(Math.floor(Math.random() * 60), "minute")
|
||||
.set("y", year);
|
||||
const randomEvent = eventTypesToPick[Math.floor(Math.random() * eventTypesToPick.length)];
|
||||
|
||||
const endTime = dayjs(startTime).add(Math.floor(Math.random() * randomEvent.length), "minute");
|
||||
|
||||
booking.title = randomEvent.title;
|
||||
booking.description = randomEvent.description;
|
||||
booking.startTime = startTime.toISOString();
|
||||
booking.endTime = endTime.toISOString();
|
||||
booking.createdAt = startTime.subtract(1, "day").toISOString();
|
||||
|
||||
// Pick a random status
|
||||
const randomStatusIndex = Math.floor(Math.random() * Object.keys(BookingStatus).length);
|
||||
const statusKey = Object.keys(BookingStatus)[randomStatusIndex];
|
||||
|
||||
booking.status = BookingStatus[statusKey];
|
||||
|
||||
booking.rescheduled = Math.random() > 0.5 && Math.random() > 0.5 && Math.random() > 0.5;
|
||||
|
||||
if (booking.rescheduled) {
|
||||
booking.status = "CANCELLED";
|
||||
}
|
||||
const randomEventTypeId = randomEvent.id;
|
||||
|
||||
booking.eventTypeId = randomEventTypeId;
|
||||
booking.uid = uuidv4();
|
||||
|
||||
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 {
|
||||
booking.userId = randomEvent.userId;
|
||||
}
|
||||
|
||||
if (booking.userId === undefined || booking.userId === null) {
|
||||
console.log({ randomEvent, usersIdsToPick });
|
||||
console.log("This should not happen");
|
||||
}
|
||||
|
||||
booking.rating = Math.floor(Math.random() * 5) + 1; // Generates a random rating from 1 to 5
|
||||
booking.ratingFeedback = getRandomRatingFeedback(); // Random feedback from a predefined list
|
||||
booking.noShowHost = Math.random() < 0.5;
|
||||
|
||||
return booking;
|
||||
};
|
||||
|
||||
async function createAttendees(bookings: any[]) {
|
||||
for (const booking of bookings) {
|
||||
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(),
|
||||
};
|
||||
}),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async function seedBookingAssignments() {
|
||||
const assignmentReasons = [
|
||||
AssignmentReasonEnum.ROUTING_FORM_ROUTING,
|
||||
AssignmentReasonEnum.ROUTING_FORM_ROUTING_FALLBACK,
|
||||
AssignmentReasonEnum.REASSIGNED,
|
||||
AssignmentReasonEnum.REROUTED,
|
||||
AssignmentReasonEnum.SALESFORCE_ASSIGNMENT,
|
||||
];
|
||||
// Get all booking IDs
|
||||
const bookings = await prisma.booking.findMany({
|
||||
select: {
|
||||
id: true,
|
||||
},
|
||||
});
|
||||
|
||||
// Take 20% of bookings randomly
|
||||
const numberOfBookingsToAssign = Math.floor(bookings.length * 0.2);
|
||||
const randomBookings = bookings.sort(() => Math.random() - 0.5).slice(0, numberOfBookingsToAssign);
|
||||
|
||||
// Create assignment reasons for the random bookings
|
||||
await prisma.assignmentReason.createMany({
|
||||
data: randomBookings.map((booking) => ({
|
||||
bookingId: booking.id,
|
||||
reasonString: faker.lorem.sentence(),
|
||||
reasonEnum: assignmentReasons[Math.floor(Math.random() * assignmentReasons.length)],
|
||||
})),
|
||||
});
|
||||
}
|
||||
|
||||
const prisma = new PrismaClient();
|
||||
async function main() {
|
||||
// First find the organization we want to add insights to
|
||||
const organization = await prisma.team.findFirst({
|
||||
where: {
|
||||
slug: "acme",
|
||||
organizationSettings: {
|
||||
isOrganizationVerified: true,
|
||||
orgAutoAcceptEmail: "acme.com",
|
||||
isAdminAPIEnabled: true,
|
||||
},
|
||||
},
|
||||
include: {
|
||||
members: {
|
||||
include: {
|
||||
// eslint-disable-next-line @calcom/eslint/no-prisma-include-true
|
||||
user: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
if (!organization) {
|
||||
throw new Error("Organization 'Acme Inc' not found. Please run seed.ts first.");
|
||||
}
|
||||
|
||||
// Get all members of the organization
|
||||
const orgMembers = organization.members;
|
||||
|
||||
let insightsTeam = await prisma.team.findUnique({
|
||||
where: {
|
||||
slug_parentId: {
|
||||
slug: "insights-team",
|
||||
parentId: organization.id, // Make sure team is under the organization
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
if (!insightsTeam) {
|
||||
insightsTeam = await prisma.team.create({
|
||||
data: {
|
||||
name: "Insights",
|
||||
slug: "insights-team",
|
||||
parent: {
|
||||
connect: {
|
||||
id: organization.id,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
// Add org members to insights team
|
||||
await prisma.membership.createMany({
|
||||
data: orgMembers.map((member) => ({
|
||||
teamId: insightsTeam!.id,
|
||||
userId: member.user.id,
|
||||
role: member.role,
|
||||
accepted: true,
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
})),
|
||||
});
|
||||
}
|
||||
|
||||
const insightsTeamMembers = await prisma.membership.findMany({
|
||||
where: {
|
||||
teamId: insightsTeam.id,
|
||||
},
|
||||
include: {
|
||||
user: true,
|
||||
},
|
||||
});
|
||||
|
||||
// Create event types for the team
|
||||
let teamEvents = await prisma.eventType.findMany({
|
||||
where: {
|
||||
teamId: insightsTeam.id,
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
title: true,
|
||||
slug: true,
|
||||
description: true,
|
||||
length: true,
|
||||
teamId: true,
|
||||
userId: true,
|
||||
assignAllTeamMembers: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (teamEvents?.length === 0) {
|
||||
await prisma.eventType.createMany({
|
||||
data: [
|
||||
{
|
||||
title: "Team Meeting",
|
||||
slug: "team-sales",
|
||||
description: "Team Meeting",
|
||||
length: 60,
|
||||
teamId: insightsTeam.id,
|
||||
schedulingType: "ROUND_ROBIN",
|
||||
assignAllTeamMembers: true,
|
||||
},
|
||||
{
|
||||
title: "Team Lunch",
|
||||
slug: "team-python",
|
||||
description: "Team Lunch",
|
||||
length: 30,
|
||||
teamId: insightsTeam.id,
|
||||
schedulingType: "ROUND_ROBIN",
|
||||
assignAllTeamMembers: true,
|
||||
},
|
||||
{
|
||||
title: "Team javascript",
|
||||
slug: "team-javascript",
|
||||
description: "Team Coffee",
|
||||
length: 15,
|
||||
teamId: insightsTeam.id,
|
||||
schedulingType: "ROUND_ROBIN",
|
||||
assignAllTeamMembers: true,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
teamEvents = await prisma.eventType.findMany({
|
||||
where: {
|
||||
teamId: insightsTeam.id,
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
title: true,
|
||||
slug: true,
|
||||
description: true,
|
||||
length: true,
|
||||
teamId: true,
|
||||
userId: true,
|
||||
assignAllTeamMembers: true,
|
||||
},
|
||||
});
|
||||
|
||||
// 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);
|
||||
if (assignAllTeamMembersEvents.length > 0 && insightsTeamMembers.length > 0) {
|
||||
const hostRecords = assignAllTeamMembersEvents.flatMap((event) =>
|
||||
insightsTeamMembers.map((member) => ({
|
||||
userId: member.user.id,
|
||||
eventTypeId: event.id,
|
||||
isFixed: false,
|
||||
}))
|
||||
);
|
||||
if (hostRecords.length > 0) {
|
||||
await prisma.host.createMany({
|
||||
data: hostRecords,
|
||||
skipDuplicates: true,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const javascriptEventId = teamEvents.find((event) => event.slug === "team-javascript")?.id;
|
||||
const salesEventId = teamEvents.find((event) => event.slug === "team-sales")?.id;
|
||||
|
||||
// Create bookings for the team events
|
||||
const baseBooking = {
|
||||
uid: "demoUID",
|
||||
title: "Team Meeting should be changed in shuffle",
|
||||
description: "Team Meeting Should be changed in shuffle",
|
||||
startTime: dayjs().toISOString(),
|
||||
endTime: dayjs().toISOString(),
|
||||
userId: insightsTeamMembers[0].user.id, // Use first org member as default
|
||||
};
|
||||
|
||||
// Create past bookings -2y, -1y, -0y
|
||||
await prisma.booking.createMany({
|
||||
data: [
|
||||
...new Array(10000).fill(0).map(() =>
|
||||
shuffle(
|
||||
{ ...baseBooking },
|
||||
dayjs().get("y") - 2,
|
||||
teamEvents,
|
||||
insightsTeamMembers.map((m) => m.user.id)
|
||||
)
|
||||
),
|
||||
],
|
||||
});
|
||||
|
||||
await prisma.booking.createMany({
|
||||
data: [
|
||||
...new Array(10000).fill(0).map(() =>
|
||||
shuffle(
|
||||
{ ...baseBooking },
|
||||
dayjs().get("y") - 1,
|
||||
teamEvents,
|
||||
insightsTeamMembers.map((m) => m.user.id)
|
||||
)
|
||||
),
|
||||
],
|
||||
});
|
||||
|
||||
await prisma.booking.createMany({
|
||||
data: [
|
||||
...new Array(10000).fill(0).map(() =>
|
||||
shuffle(
|
||||
{ ...baseBooking },
|
||||
dayjs().get("y"),
|
||||
teamEvents,
|
||||
insightsTeamMembers.map((m) => m.user.id)
|
||||
)
|
||||
),
|
||||
],
|
||||
});
|
||||
|
||||
await createAttendees(await prisma.booking.findMany());
|
||||
|
||||
// Find owner of the organization
|
||||
const owner = orgMembers.find((m) => m.role === "OWNER" || m.role === "ADMIN");
|
||||
|
||||
// Then seed routing forms
|
||||
const attributes = await seedAttributes(organization.id);
|
||||
if (!attributes) {
|
||||
throw new Error("Attributes not found");
|
||||
}
|
||||
const seededForm = await seedRoutingForms(
|
||||
insightsTeam.id,
|
||||
owner?.user.id ?? insightsTeamMembers[0].user.id,
|
||||
attributes
|
||||
);
|
||||
|
||||
if (seededForm) {
|
||||
await seedRoutingFormResponses(seededForm, attributes, insightsTeam.id);
|
||||
}
|
||||
|
||||
await seedBookingAssignments();
|
||||
}
|
||||
main()
|
||||
.then(async () => {
|
||||
await prisma.$disconnect();
|
||||
})
|
||||
.catch(async (e) => {
|
||||
console.error(e);
|
||||
await prisma.user.deleteMany({
|
||||
where: {
|
||||
email: {
|
||||
in: ["insights@example", "insightsuser@example.com"],
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
await prisma.team.deleteMany({
|
||||
where: {
|
||||
slug: "insights",
|
||||
},
|
||||
});
|
||||
|
||||
await prisma.$disconnect();
|
||||
process.exit(1);
|
||||
});
|
||||
|
||||
/**
|
||||
* This will create many users in insights teams with bookings 1y in the past
|
||||
* Should be run after the main function is executed once
|
||||
*/
|
||||
async function createPerformanceData() {
|
||||
const createExtraMembers = false; // Turn ON to be executed
|
||||
let extraMembersIds;
|
||||
const insightsTeam = await prisma.team.findFirst({
|
||||
where: {
|
||||
slug: "insights-team",
|
||||
},
|
||||
});
|
||||
|
||||
if (createExtraMembers) {
|
||||
const insightsRandomUsers: Prisma.UserCreateManyArgs["data"] = [];
|
||||
const numInsightsUsers = 50; // Change this value to adjust the number of insights users to create
|
||||
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,
|
||||
};
|
||||
insightsRandomUsers.push(insightsUser);
|
||||
}
|
||||
|
||||
await prisma.user.createMany({
|
||||
data: insightsRandomUsers,
|
||||
});
|
||||
// Lets find the ids of the users we just created
|
||||
extraMembersIds = await prisma.user.findMany({
|
||||
where: {
|
||||
email: {
|
||||
in: insightsRandomUsers.map((user) => user.email),
|
||||
},
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
if (createExtraMembers) {
|
||||
if (insightsTeam === null) {
|
||||
console.log("This should not happen");
|
||||
throw new Error("Insights team id is undefined or null");
|
||||
}
|
||||
|
||||
await prisma.membership.createMany({
|
||||
data: extraMembersIds.map((memberId) => ({
|
||||
teamId: insightsTeam?.id ?? 1,
|
||||
userId: memberId.id,
|
||||
role: "MEMBER",
|
||||
accepted: true,
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
})),
|
||||
});
|
||||
|
||||
const updateMemberPromises = extraMembersIds.map((memberId) =>
|
||||
prisma.team.update({
|
||||
where: {
|
||||
id: insightsTeam?.id,
|
||||
},
|
||||
data: {
|
||||
members: {
|
||||
connect: {
|
||||
userId_teamId: {
|
||||
userId: memberId.id,
|
||||
teamId: insightsTeam?.id ?? 1,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
);
|
||||
|
||||
await Promise.all(updateMemberPromises);
|
||||
|
||||
// Create events for every Member id
|
||||
const createEvents = extraMembersIds.map((memberId) => ({
|
||||
title: `Single Event User - ${memberId.id}`,
|
||||
slug: `single-event-user-${memberId.id}`,
|
||||
description: `Single Event User - ${memberId.id}`,
|
||||
length: 30,
|
||||
userId: memberId.id,
|
||||
users: {
|
||||
connect: {
|
||||
id: memberId.id,
|
||||
},
|
||||
},
|
||||
}));
|
||||
const createEventPromises = createEvents.map((data) =>
|
||||
prisma.eventType.create({
|
||||
data,
|
||||
})
|
||||
);
|
||||
await Promise.all(createEventPromises);
|
||||
|
||||
// load the events we just created
|
||||
const singleEventsCreated = await prisma.eventType.findMany({
|
||||
where: {
|
||||
userId: {
|
||||
in: extraMembersIds.map((memberId) => memberId.id),
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
// Create bookings for every single event
|
||||
const baseBooking = {
|
||||
uid: "demo performance data booking",
|
||||
title: "Single Event Booking Perf",
|
||||
description: "Single Event Booking Perf",
|
||||
startTime: dayjs().toISOString(),
|
||||
endTime: dayjs().toISOString(),
|
||||
eventTypeId: singleEventsCreated[0].id,
|
||||
};
|
||||
|
||||
await prisma.booking.createMany({
|
||||
data: [
|
||||
...new Array(10000)
|
||||
.fill(0)
|
||||
.map(() => shuffle({ ...baseBooking }, dayjs().get("y"), singleEventsCreated)),
|
||||
],
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
createPerformanceData()
|
||||
.then(async () => {
|
||||
await prisma.$disconnect();
|
||||
})
|
||||
.catch(async (e) => {
|
||||
console.error(e);
|
||||
await prisma.user.deleteMany({
|
||||
where: {
|
||||
username: {
|
||||
contains: "insights-user-",
|
||||
},
|
||||
},
|
||||
});
|
||||
await prisma.$disconnect();
|
||||
process.exit(1);
|
||||
});
|
||||
@@ -0,0 +1,705 @@
|
||||
import { uuid } from "short-uuid";
|
||||
|
||||
import { hashPassword } from "@calcom/lib/auth/hashPassword";
|
||||
import { DEFAULT_SCHEDULE, getAvailabilityFromSchedule } from "@calcom/lib/availability";
|
||||
import prisma from "@calcom/prisma";
|
||||
import { MembershipRole, RoleType } from "@calcom/prisma/enums";
|
||||
|
||||
/**
|
||||
* Creates an organization with custom roles and PBAC (Permission-Based Access Control) enabled
|
||||
* This demonstrates how to set up fine-grained permissions for team members
|
||||
*/
|
||||
export async function createPBACOrganization() {
|
||||
console.log("🏢 Creating PBAC-enabled organization with custom roles...");
|
||||
|
||||
// Check if organization already exists
|
||||
const existingOrg = await prisma.team.findFirst({
|
||||
where: {
|
||||
slug: "pbac-demo-org",
|
||||
isOrganization: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (existingOrg) {
|
||||
console.log("⚠️ PBAC Demo Organization already exists, skipping creation");
|
||||
return {
|
||||
organization: existingOrg,
|
||||
customRoles: {},
|
||||
users: [],
|
||||
team: null,
|
||||
};
|
||||
}
|
||||
|
||||
// First, create the organization
|
||||
const organization = await prisma.team.create({
|
||||
data: {
|
||||
name: "PBAC Demo Organization",
|
||||
slug: "pbac-demo-org",
|
||||
isOrganization: true,
|
||||
metadata: {
|
||||
isOrganization: true,
|
||||
},
|
||||
organizationSettings: {
|
||||
create: {
|
||||
isOrganizationVerified: true,
|
||||
orgAutoAcceptEmail: "pbac-demo.com",
|
||||
isAdminAPIEnabled: true,
|
||||
isAdminReviewed: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
// Add the feature flag
|
||||
await prisma.teamFeatures.create({
|
||||
data: {
|
||||
featureId: "pbac",
|
||||
teamId: organization.id,
|
||||
assignedBy: "system (Seed script)",
|
||||
assignedAt: new Date(),
|
||||
},
|
||||
});
|
||||
|
||||
console.log(`✅ Created organization: ${organization.name} (ID: ${organization.id})`);
|
||||
|
||||
// Create custom roles with specific permissions
|
||||
const customRoles = await createCustomRoles(organization.id);
|
||||
|
||||
// Create users with different roles
|
||||
const users = await createUsersWithRoles(organization.id, customRoles);
|
||||
|
||||
// Create a team within the organization
|
||||
const team = await createTeamWithCustomRoles(organization.id, users, customRoles);
|
||||
|
||||
console.log("🎉 PBAC organization setup complete!");
|
||||
console.log(`Organization URL: ${process.env.NEXT_PUBLIC_WEBAPP_URL}/org/${organization.slug}`);
|
||||
|
||||
// Display created users with their credentials and permissions
|
||||
console.log("\n📋 Created Users - Login Credentials & Permissions:");
|
||||
console.log("=".repeat(80));
|
||||
users.forEach(({ user, role, customRole }) => {
|
||||
const password = getPasswordForUser(user.email);
|
||||
const permissions = getPermissionsForRole(user.email, customRoles);
|
||||
|
||||
console.log(`👤 ${user.name}`);
|
||||
console.log(` 📧 Email: ${user.email}`);
|
||||
console.log(` 🔑 Password: ${password}`);
|
||||
console.log(` 👔 Role: ${role}${customRole ? ` (${customRole})` : ""}`);
|
||||
|
||||
if (permissions.length > 0) {
|
||||
console.log(` 🔐 Permissions:`);
|
||||
permissions.forEach((permission) => {
|
||||
console.log(` • ${permission.resource}:${permission.action}`);
|
||||
});
|
||||
} else {
|
||||
console.log(` 🔐 Permissions: Full access (Owner role)`);
|
||||
}
|
||||
console.log("");
|
||||
});
|
||||
console.log("=".repeat(80));
|
||||
|
||||
return {
|
||||
organization,
|
||||
customRoles,
|
||||
users,
|
||||
team,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates custom roles with specific permissions for the organization
|
||||
*/
|
||||
async function createCustomRoles(organizationId: number) {
|
||||
console.log("🔐 Creating custom roles with PBAC permissions...");
|
||||
|
||||
// Check if roles already exist
|
||||
const existingRoles = await prisma.role.findMany({
|
||||
where: { teamId: organizationId },
|
||||
});
|
||||
|
||||
if (existingRoles.length > 0) {
|
||||
console.log("⚠️ Custom roles already exist for this organization, skipping creation");
|
||||
return {
|
||||
eventManager: existingRoles.find((r) => r.name === "Event Manager"),
|
||||
analytics: existingRoles.find((r) => r.name === "Analytics Specialist"),
|
||||
teamCoordinator: existingRoles.find((r) => r.name === "Team Coordinator"),
|
||||
supportAgent: existingRoles.find((r) => r.name === "Support Agent"),
|
||||
};
|
||||
}
|
||||
|
||||
// Event Manager Role - Can manage event types and bookings
|
||||
const eventManagerRole = await prisma.role.create({
|
||||
data: {
|
||||
id: `event_manager_${organizationId}`,
|
||||
name: "Event Manager",
|
||||
description: "Can create and manage event types, view bookings and recordings",
|
||||
color: "#3B82F6", // Blue
|
||||
teamId: organizationId,
|
||||
type: RoleType.CUSTOM,
|
||||
permissions: {
|
||||
create: [
|
||||
// Event Type permissions
|
||||
{ resource: "eventType", action: "create" },
|
||||
{ resource: "eventType", action: "read" },
|
||||
{ resource: "eventType", action: "update" },
|
||||
{ resource: "eventType", action: "delete" },
|
||||
|
||||
// Booking permissions
|
||||
{ resource: "booking", action: "read" },
|
||||
{ resource: "booking", action: "update" },
|
||||
{ resource: "booking", action: "readRecordings" },
|
||||
|
||||
// Team read access
|
||||
{ resource: "team", action: "read" },
|
||||
|
||||
// Availability override
|
||||
{ resource: "availability", action: "override" },
|
||||
],
|
||||
},
|
||||
},
|
||||
include: {
|
||||
permissions: true,
|
||||
},
|
||||
});
|
||||
// Analytics Specialist Role - Can view insights and reports
|
||||
const analyticsRole = await prisma.role.create({
|
||||
data: {
|
||||
id: `analytics_specialist_${organizationId}`,
|
||||
name: "Analytics Specialist",
|
||||
description: "Can view insights, reports, and booking analytics",
|
||||
color: "#10B981", // Green
|
||||
teamId: organizationId,
|
||||
type: RoleType.CUSTOM,
|
||||
permissions: {
|
||||
create: [
|
||||
// Insights permissions
|
||||
{ resource: "insights", action: "read" },
|
||||
|
||||
// Booking read access
|
||||
{ resource: "booking", action: "read" },
|
||||
{ resource: "booking", action: "readTeamBookings" },
|
||||
{ resource: "booking", action: "readOrgBookings" },
|
||||
|
||||
// Event Type read access
|
||||
{ resource: "eventType", action: "read" },
|
||||
|
||||
// Team and organization read access
|
||||
{ resource: "team", action: "read" },
|
||||
{ resource: "organization", action: "read" },
|
||||
{ resource: "organization", action: "listMembers" },
|
||||
|
||||
// Routing forms for conversion tracking
|
||||
{ resource: "routingForm", action: "read" },
|
||||
],
|
||||
},
|
||||
},
|
||||
include: {
|
||||
permissions: true,
|
||||
},
|
||||
});
|
||||
// Team Coordinator Role - Can manage team members and workflows
|
||||
const teamCoordinatorRole = await prisma.role.create({
|
||||
data: {
|
||||
id: `team_coordinator_${organizationId}`,
|
||||
name: "Team Coordinator",
|
||||
description: "Can invite/remove team members, manage workflows and routing forms",
|
||||
color: "#8B5CF6", // Purple
|
||||
teamId: organizationId,
|
||||
type: RoleType.CUSTOM,
|
||||
permissions: {
|
||||
create: [
|
||||
// Team management
|
||||
{ resource: "team", action: "read" },
|
||||
{ resource: "team", action: "update" },
|
||||
{ resource: "team", action: "invite" },
|
||||
{ resource: "team", action: "remove" },
|
||||
{ resource: "team", action: "changeMemberRole" },
|
||||
|
||||
// Organization member management
|
||||
{ resource: "organization", action: "read" },
|
||||
{ resource: "organization", action: "listMembers" },
|
||||
|
||||
// Workflow management
|
||||
{ resource: "workflow", action: "create" },
|
||||
{ resource: "workflow", action: "read" },
|
||||
{ resource: "workflow", action: "update" },
|
||||
{ resource: "workflow", action: "delete" },
|
||||
|
||||
// Routing form management
|
||||
{ resource: "routingForm", action: "create" },
|
||||
{ resource: "routingForm", action: "read" },
|
||||
{ resource: "routingForm", action: "update" },
|
||||
{ resource: "routingForm", action: "delete" },
|
||||
|
||||
// Basic booking access
|
||||
{ resource: "booking", action: "read" },
|
||||
{ resource: "eventType", action: "read" },
|
||||
],
|
||||
},
|
||||
},
|
||||
include: {
|
||||
permissions: true,
|
||||
},
|
||||
});
|
||||
// Support Agent Role - Limited access for customer support
|
||||
const supportAgentRole = await prisma.role.create({
|
||||
data: {
|
||||
id: `support_agent_${organizationId}`,
|
||||
name: "Support Agent",
|
||||
description: "Can view bookings and basic event information for customer support",
|
||||
color: "#F59E0B", // Amber
|
||||
teamId: organizationId,
|
||||
type: RoleType.CUSTOM,
|
||||
permissions: {
|
||||
create: [
|
||||
// Limited booking access
|
||||
{ resource: "booking", action: "read" },
|
||||
{ resource: "booking", action: "update" }, // For rescheduling/canceling
|
||||
|
||||
// Event Type read access
|
||||
{ resource: "eventType", action: "read" },
|
||||
|
||||
// Team read access
|
||||
{ resource: "team", action: "read" },
|
||||
|
||||
// Organization read access
|
||||
{ resource: "organization", action: "read" },
|
||||
],
|
||||
},
|
||||
},
|
||||
include: {
|
||||
permissions: true,
|
||||
},
|
||||
});
|
||||
console.log("✅ Created custom roles:");
|
||||
console.log(` - Event Manager (${eventManagerRole.permissions.length} permissions)`);
|
||||
console.log(` - Analytics Specialist (${analyticsRole.permissions.length} permissions)`);
|
||||
console.log(` - Team Coordinator (${teamCoordinatorRole.permissions.length} permissions)`);
|
||||
console.log(` - Support Agent (${supportAgentRole.permissions.length} permissions)`);
|
||||
|
||||
return {
|
||||
eventManager: eventManagerRole,
|
||||
analytics: analyticsRole,
|
||||
teamCoordinator: teamCoordinatorRole,
|
||||
supportAgent: supportAgentRole,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates users with different roles in the organization
|
||||
*/
|
||||
async function createUsersWithRoles(organizationId: number, customRoles: any) {
|
||||
console.log("👥 Creating users with custom roles...");
|
||||
|
||||
const users: Array<{
|
||||
user: any;
|
||||
role: MembershipRole;
|
||||
customRole: string | null;
|
||||
}> = [];
|
||||
|
||||
// Check if users already exist
|
||||
const existingUsers = await prisma.user.findMany({
|
||||
where: {
|
||||
email: {
|
||||
in: [
|
||||
"owner@pbac-demo.com",
|
||||
"events@pbac-demo.com",
|
||||
"analytics@pbac-demo.com",
|
||||
"coordinator@pbac-demo.com",
|
||||
"support@pbac-demo.com",
|
||||
],
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
if (existingUsers.length > 0) {
|
||||
console.log("⚠️ Some PBAC users already exist, skipping user creation");
|
||||
return existingUsers.map((user) => ({
|
||||
user,
|
||||
role: MembershipRole.MEMBER,
|
||||
customRole: null,
|
||||
}));
|
||||
}
|
||||
|
||||
// Organization Owner
|
||||
const owner = await createUser({
|
||||
email: "owner@pbac-demo.com",
|
||||
username: "pbac-owner",
|
||||
name: "Organization Owner",
|
||||
password: "pbac-owner-2024!",
|
||||
});
|
||||
|
||||
await createMembership({
|
||||
userId: owner.id,
|
||||
teamId: organizationId,
|
||||
role: MembershipRole.OWNER,
|
||||
customRoleId: null, // Uses default owner role
|
||||
});
|
||||
|
||||
await createProfile({
|
||||
userId: owner.id,
|
||||
organizationId,
|
||||
username: "owner",
|
||||
});
|
||||
|
||||
users.push({ user: owner, role: MembershipRole.OWNER, customRole: null });
|
||||
|
||||
// Event Manager
|
||||
const eventManager = await createUser({
|
||||
email: "events@pbac-demo.com",
|
||||
username: "pbac-events",
|
||||
name: "Event Manager",
|
||||
password: "events-2024!",
|
||||
});
|
||||
|
||||
await createMembership({
|
||||
userId: eventManager.id,
|
||||
teamId: organizationId,
|
||||
role: MembershipRole.MEMBER,
|
||||
customRoleId: customRoles.eventManager.id,
|
||||
});
|
||||
|
||||
await createProfile({
|
||||
userId: eventManager.id,
|
||||
organizationId,
|
||||
username: "events",
|
||||
});
|
||||
|
||||
users.push({ user: eventManager, role: MembershipRole.MEMBER, customRole: "Event Manager" });
|
||||
|
||||
// Analytics Specialist
|
||||
const analytics = await createUser({
|
||||
email: "analytics@pbac-demo.com",
|
||||
username: "pbac-analytics",
|
||||
name: "Analytics Specialist",
|
||||
password: "analytics-2024!",
|
||||
});
|
||||
|
||||
await createMembership({
|
||||
userId: analytics.id,
|
||||
teamId: organizationId,
|
||||
role: MembershipRole.MEMBER,
|
||||
customRoleId: customRoles.analytics.id,
|
||||
});
|
||||
|
||||
await createProfile({
|
||||
userId: analytics.id,
|
||||
organizationId,
|
||||
username: "analytics",
|
||||
});
|
||||
|
||||
users.push({ user: analytics, role: MembershipRole.MEMBER, customRole: "Analytics Specialist" });
|
||||
|
||||
// Team Coordinator
|
||||
const coordinator = await createUser({
|
||||
email: "coordinator@pbac-demo.com",
|
||||
username: "pbac-coordinator",
|
||||
name: "Team Coordinator",
|
||||
password: "coordinator-2024!",
|
||||
});
|
||||
|
||||
await createMembership({
|
||||
userId: coordinator.id,
|
||||
teamId: organizationId,
|
||||
role: MembershipRole.ADMIN,
|
||||
customRoleId: customRoles.teamCoordinator.id,
|
||||
});
|
||||
|
||||
await createProfile({
|
||||
userId: coordinator.id,
|
||||
organizationId,
|
||||
username: "coordinator",
|
||||
});
|
||||
|
||||
users.push({ user: coordinator, role: MembershipRole.ADMIN, customRole: "Team Coordinator" });
|
||||
|
||||
// Support Agent
|
||||
const support = await createUser({
|
||||
email: "support@pbac-demo.com",
|
||||
username: "pbac-support",
|
||||
name: "Support Agent",
|
||||
password: "support-2024!",
|
||||
});
|
||||
|
||||
await createMembership({
|
||||
userId: support.id,
|
||||
teamId: organizationId,
|
||||
role: MembershipRole.MEMBER,
|
||||
customRoleId: customRoles.supportAgent.id,
|
||||
});
|
||||
|
||||
await createProfile({
|
||||
userId: support.id,
|
||||
organizationId,
|
||||
username: "support",
|
||||
});
|
||||
|
||||
users.push({ user: support, role: MembershipRole.MEMBER, customRole: "Support Agent" });
|
||||
|
||||
console.log("✅ Created users with roles:");
|
||||
users.forEach(({ user, role, customRole }) => {
|
||||
console.log(` - ${user.name} (${user.email}) - ${role}${customRole ? ` + ${customRole}` : ""}`);
|
||||
});
|
||||
|
||||
return users;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a team within the organization with custom role assignments
|
||||
*/
|
||||
async function createTeamWithCustomRoles(organizationId: number, users: any[], customRoles: any) {
|
||||
console.log("🏢 Creating team with custom role assignments...");
|
||||
|
||||
const team = await prisma.team.create({
|
||||
data: {
|
||||
name: "Sales Team",
|
||||
slug: "sales-team",
|
||||
parentId: organizationId,
|
||||
metadata: {},
|
||||
},
|
||||
});
|
||||
|
||||
// Add team members with their custom roles
|
||||
for (const { user } of users) {
|
||||
let customRoleId: string | null = null;
|
||||
|
||||
// Assign appropriate roles for the team
|
||||
if (user.email === "owner@pbac-demo.com") {
|
||||
customRoleId = "owner_role";
|
||||
} else if (user.email === "coordinator@pbac-demo.com") {
|
||||
customRoleId = customRoles.teamCoordinator.id;
|
||||
} else if (user.email === "events@pbac-demo.com") {
|
||||
customRoleId = customRoles.eventManager.id;
|
||||
} else if (user.email === "analytics@pbac-demo.com") {
|
||||
customRoleId = customRoles.analytics.id;
|
||||
} else if (user.email === "support@pbac-demo.com") {
|
||||
customRoleId = customRoles.supportAgent.id;
|
||||
}
|
||||
|
||||
await prisma.membership.create({
|
||||
data: {
|
||||
userId: user.id,
|
||||
teamId: team.id,
|
||||
role: MembershipRole.MEMBER,
|
||||
customRoleId,
|
||||
accepted: true,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// Create some event types for the team
|
||||
await prisma.eventType.create({
|
||||
data: {
|
||||
title: "Sales Consultation",
|
||||
slug: "sales-consultation",
|
||||
length: 30,
|
||||
teamId: team.id,
|
||||
userId: users[0].user.id, // Owner as the creator
|
||||
users: {
|
||||
connect: users.map(({ user }) => ({ id: user.id })),
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
await prisma.eventType.create({
|
||||
data: {
|
||||
title: "Product Demo",
|
||||
slug: "product-demo",
|
||||
length: 45,
|
||||
teamId: team.id,
|
||||
userId: users[0].user.id, // Owner as the creator
|
||||
users: {
|
||||
connect: users.slice(0, 3).map(({ user }) => ({ id: user.id })), // First 3 users
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
console.log(`✅ Created team: ${team.name} with ${users.length} members`);
|
||||
console.log(`Team URL: ${process.env.NEXT_PUBLIC_WEBAPP_URL}/team/${team.slug}`);
|
||||
|
||||
return team;
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper function to create a user
|
||||
*/
|
||||
async function createUser(userData: { email: string; username: string; name: string; password: string }) {
|
||||
const user = await prisma.user.create({
|
||||
data: {
|
||||
email: userData.email,
|
||||
username: userData.username,
|
||||
name: userData.name,
|
||||
emailVerified: new Date(),
|
||||
completedOnboarding: true,
|
||||
locale: "en",
|
||||
schedules: {
|
||||
create: {
|
||||
name: "Working Hours",
|
||||
availability: {
|
||||
createMany: {
|
||||
data: getAvailabilityFromSchedule(DEFAULT_SCHEDULE),
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
await prisma.userPassword.create({
|
||||
data: {
|
||||
userId: user.id,
|
||||
hash: await hashPassword(userData.password),
|
||||
},
|
||||
});
|
||||
|
||||
return user;
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper function to create a membership
|
||||
*/
|
||||
async function createMembership({
|
||||
userId,
|
||||
teamId,
|
||||
role,
|
||||
customRoleId,
|
||||
}: {
|
||||
userId: number;
|
||||
teamId: number;
|
||||
role: MembershipRole;
|
||||
customRoleId: string | null;
|
||||
}) {
|
||||
return prisma.membership.create({
|
||||
data: {
|
||||
userId,
|
||||
teamId,
|
||||
role,
|
||||
customRoleId,
|
||||
accepted: true,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper function to create a profile
|
||||
*/
|
||||
async function createProfile({
|
||||
userId,
|
||||
organizationId,
|
||||
username,
|
||||
}: {
|
||||
userId: number;
|
||||
organizationId: number;
|
||||
username: string;
|
||||
}) {
|
||||
const profile = await prisma.profile.create({
|
||||
data: {
|
||||
uid: uuid(),
|
||||
userId,
|
||||
organizationId,
|
||||
username,
|
||||
},
|
||||
});
|
||||
|
||||
// Update user to point to this profile
|
||||
await prisma.user.update({
|
||||
where: { id: userId },
|
||||
data: { movedToProfileId: profile.id },
|
||||
});
|
||||
|
||||
return profile;
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper function to get password for a user based on their email
|
||||
*/
|
||||
function getPasswordForUser(email: string): string {
|
||||
const passwordMap: Record<string, string> = {
|
||||
"owner@pbac-demo.com": "pbac-owner-2024!",
|
||||
"events@pbac-demo.com": "events-2024!",
|
||||
"analytics@pbac-demo.com": "analytics-2024!",
|
||||
"coordinator@pbac-demo.com": "coordinator-2024!",
|
||||
"support@pbac-demo.com": "support-2024!",
|
||||
};
|
||||
|
||||
return passwordMap[email] || "unknown";
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper function to get permissions for a role based on user email
|
||||
*/
|
||||
function getPermissionsForRole(email: string, customRoles: any): Array<{ resource: string; action: string }> {
|
||||
// Owner has full access, no specific permissions to list
|
||||
if (email === "owner@pbac-demo.com") {
|
||||
return [];
|
||||
}
|
||||
|
||||
// Map email to role and return permissions
|
||||
const rolePermissionMap: Record<string, Array<{ resource: string; action: string }>> = {
|
||||
"events@pbac-demo.com": [
|
||||
{ resource: "eventType", action: "create" },
|
||||
{ resource: "eventType", action: "read" },
|
||||
{ resource: "eventType", action: "update" },
|
||||
{ resource: "eventType", action: "delete" },
|
||||
{ resource: "booking", action: "read" },
|
||||
{ resource: "booking", action: "update" },
|
||||
{ resource: "booking", action: "readRecordings" },
|
||||
{ resource: "team", action: "read" },
|
||||
{ resource: "availability", action: "override" },
|
||||
],
|
||||
"analytics@pbac-demo.com": [
|
||||
{ resource: "insights", action: "read" },
|
||||
{ resource: "booking", action: "read" },
|
||||
{ resource: "booking", action: "readTeamBookings" },
|
||||
{ resource: "booking", action: "readOrgBookings" },
|
||||
{ resource: "eventType", action: "read" },
|
||||
{ resource: "team", action: "read" },
|
||||
{ resource: "organization", action: "read" },
|
||||
{ resource: "organization", action: "listMembers" },
|
||||
{ resource: "routingForm", action: "read" },
|
||||
],
|
||||
"coordinator@pbac-demo.com": [
|
||||
{ resource: "team", action: "read" },
|
||||
{ resource: "team", action: "update" },
|
||||
{ resource: "team", action: "invite" },
|
||||
{ resource: "team", action: "remove" },
|
||||
{ resource: "team", action: "changeMemberRole" },
|
||||
{ resource: "organization", action: "read" },
|
||||
{ resource: "organization", action: "listMembers" },
|
||||
{ resource: "workflow", action: "create" },
|
||||
{ resource: "workflow", action: "read" },
|
||||
{ resource: "workflow", action: "update" },
|
||||
{ resource: "workflow", action: "delete" },
|
||||
{ resource: "routingForm", action: "create" },
|
||||
{ resource: "routingForm", action: "read" },
|
||||
{ resource: "routingForm", action: "update" },
|
||||
{ resource: "routingForm", action: "delete" },
|
||||
{ resource: "booking", action: "read" },
|
||||
{ resource: "eventType", action: "read" },
|
||||
],
|
||||
"support@pbac-demo.com": [
|
||||
{ resource: "booking", action: "read" },
|
||||
{ resource: "booking", action: "update" },
|
||||
{ resource: "eventType", action: "read" },
|
||||
{ resource: "team", action: "read" },
|
||||
{ resource: "organization", action: "read" },
|
||||
],
|
||||
};
|
||||
|
||||
return rolePermissionMap[email] || [];
|
||||
}
|
||||
// Run the function if this file is executed directly
|
||||
if (require.main === module) {
|
||||
createPBACOrganization()
|
||||
.then(() => {
|
||||
console.log("✅ PBAC organization created successfully!");
|
||||
process.exit(0);
|
||||
})
|
||||
.catch((error) => {
|
||||
console.error("❌ Error creating PBAC organization:", error);
|
||||
process.exit(1);
|
||||
})
|
||||
.finally(async () => {
|
||||
await prisma.$disconnect();
|
||||
});
|
||||
}
|
||||
@@ -11,7 +11,7 @@ import zoomMeta from "@calcom/app-store/zoomvideo/_metadata";
|
||||
import dayjs from "@calcom/dayjs";
|
||||
import { BookingStatus } from "@calcom/prisma/enums";
|
||||
|
||||
import { createUserAndEventType } from "../packages/prisma/seed-utils";
|
||||
import { createUserAndEventType } from "./seed-utils";
|
||||
|
||||
async function _createManyDifferentUsersWithDifferentEventTypesAndBookings({
|
||||
tillUser,
|
||||
@@ -322,4 +322,4 @@ async function createAUserWithManyBookings() {
|
||||
// startFrom: 10000,
|
||||
// });
|
||||
|
||||
createAUserWithManyBookings();
|
||||
createAUserWithManyBookings();
|
||||
|
||||
@@ -0,0 +1,787 @@
|
||||
import { faker } from "@faker-js/faker";
|
||||
import { randomUUID } from "crypto";
|
||||
import { uuid } from "short-uuid";
|
||||
import type z from "zod";
|
||||
|
||||
import dayjs from "@calcom/dayjs";
|
||||
import { hashPassword } from "@calcom/lib/auth/hashPassword";
|
||||
import { DEFAULT_SCHEDULE, getAvailabilityFromSchedule } from "@calcom/lib/availability";
|
||||
import prisma from "@calcom/prisma";
|
||||
import type { Prisma, UserPermissionRole } from "@calcom/prisma/client";
|
||||
import { MembershipRole } from "@calcom/prisma/enums";
|
||||
import type { teamMetadataSchema } from "@calcom/prisma/zod-utils";
|
||||
|
||||
export async function createUserAndEventType({
|
||||
user,
|
||||
eventTypes = [],
|
||||
credentials,
|
||||
}: {
|
||||
user: {
|
||||
email: string;
|
||||
password: string;
|
||||
username: string;
|
||||
name: string;
|
||||
completedOnboarding?: boolean;
|
||||
timeZone?: string;
|
||||
role?: UserPermissionRole;
|
||||
theme?: "dark" | "light";
|
||||
avatarUrl?: string | null;
|
||||
};
|
||||
eventTypes?: Array<
|
||||
Prisma.EventTypeUncheckedCreateInput & {
|
||||
_bookings?: Prisma.BookingCreateInput[];
|
||||
_numBookings?: number;
|
||||
}
|
||||
>;
|
||||
credentials?: ({
|
||||
type: string;
|
||||
key: Prisma.JsonObject;
|
||||
appId: string;
|
||||
} | null)[];
|
||||
}) {
|
||||
const { password: _password, ...restOfUser } = user;
|
||||
const userData = {
|
||||
...restOfUser,
|
||||
emailVerified: new Date(),
|
||||
completedOnboarding: user.completedOnboarding ?? true,
|
||||
locale: "en",
|
||||
schedules:
|
||||
user.completedOnboarding ?? true
|
||||
? {
|
||||
create: {
|
||||
name: "Working Hours",
|
||||
availability: {
|
||||
createMany: {
|
||||
data: getAvailabilityFromSchedule(DEFAULT_SCHEDULE),
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
: undefined,
|
||||
};
|
||||
|
||||
const theUser = await prisma.user.upsert({
|
||||
where: { email_username: { email: user.email, username: user.username } },
|
||||
update: userData,
|
||||
create: userData,
|
||||
});
|
||||
|
||||
await prisma.userPassword.upsert({
|
||||
where: { userId: theUser.id },
|
||||
update: {
|
||||
hash: await hashPassword(user.password),
|
||||
},
|
||||
create: {
|
||||
hash: await hashPassword(user.password),
|
||||
user: {
|
||||
connect: {
|
||||
id: theUser.id,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
console.log(
|
||||
`👤 Upserted '${user.username}' with email "${user.email}" & password "${user.password}". Booking page 👉 ${process.env.NEXT_PUBLIC_WEBAPP_URL}/${user.username}`
|
||||
);
|
||||
|
||||
for (const eventTypeInput of eventTypes) {
|
||||
const { _bookings, _numBookings, ...eventTypeData } = eventTypeInput;
|
||||
let bookingFields;
|
||||
if (_bookings && _numBookings) {
|
||||
throw new Error("You can't set both _bookings and _numBookings");
|
||||
} else if (_numBookings) {
|
||||
bookingFields = [...Array(_numBookings).keys()].map((i) => ({
|
||||
startTime: dayjs()
|
||||
.add(1, "day")
|
||||
.add(i * 5 + 0, "minutes")
|
||||
.toDate(),
|
||||
endTime: dayjs()
|
||||
.add(1, "day")
|
||||
.add(i * 5 + 30, "minutes")
|
||||
.toDate(),
|
||||
title: `${eventTypeInput.title}:${i + 1}`,
|
||||
uid: uuid(),
|
||||
}));
|
||||
} else {
|
||||
bookingFields = _bookings || [];
|
||||
}
|
||||
eventTypeData.userId = theUser.id;
|
||||
eventTypeData.users = { connect: { id: theUser.id } };
|
||||
|
||||
const eventType = await prisma.eventType.findFirst({
|
||||
where: {
|
||||
slug: eventTypeData.slug,
|
||||
users: {
|
||||
some: {
|
||||
id: eventTypeData.userId,
|
||||
},
|
||||
},
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (eventType) {
|
||||
console.log(
|
||||
`\t📆 Event type ${eventTypeData.slug} already seems seeded - ${process.env.NEXT_PUBLIC_WEBAPP_URL}/${user.username}/${eventTypeData.slug}`
|
||||
);
|
||||
continue;
|
||||
}
|
||||
const { id } = await prisma.eventType.create({
|
||||
data: eventTypeData,
|
||||
});
|
||||
|
||||
console.log(
|
||||
`\t📆 Event type ${eventTypeData.slug} with id ${id}, length ${eventTypeData.length}min - ${process.env.NEXT_PUBLIC_WEBAPP_URL}/${user.username}/${eventTypeData.slug}`
|
||||
);
|
||||
|
||||
for (const bookingInput of bookingFields) {
|
||||
await prisma.booking.create({
|
||||
data: {
|
||||
...bookingInput,
|
||||
user: {
|
||||
connect: {
|
||||
email: user.email,
|
||||
},
|
||||
},
|
||||
attendees: {
|
||||
create: {
|
||||
email: user.email,
|
||||
name: user.name,
|
||||
timeZone: "Europe/London",
|
||||
},
|
||||
},
|
||||
eventType: {
|
||||
connect: {
|
||||
id,
|
||||
},
|
||||
},
|
||||
status: bookingInput.status,
|
||||
iCalUID: "",
|
||||
},
|
||||
});
|
||||
console.log(
|
||||
`\t\t☎️ Created booking ${bookingInput.title} at ${new Date(
|
||||
bookingInput.startTime
|
||||
).toLocaleDateString()}`
|
||||
);
|
||||
}
|
||||
}
|
||||
console.log("👤 User with it's event-types and bookings created", theUser.email);
|
||||
|
||||
if (credentials) {
|
||||
for (const credential of credentials) {
|
||||
if (credential) {
|
||||
await prisma.credential.create({
|
||||
data: {
|
||||
...credential,
|
||||
userId: theUser.id,
|
||||
},
|
||||
});
|
||||
|
||||
console.log(`🔑 ${credential.type} credentials created for ${theUser.email}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
return theUser;
|
||||
}
|
||||
|
||||
export async function createTeamAndAddUsers(
|
||||
teamInput: Prisma.TeamCreateInput,
|
||||
users: { id: number; username: string; role?: MembershipRole }[] = []
|
||||
) {
|
||||
const checkUnpublishedTeam = async (slug: string) => {
|
||||
return await prisma.team.findFirst({
|
||||
where: {
|
||||
metadata: {
|
||||
path: ["requestedSlug"],
|
||||
equals: slug,
|
||||
},
|
||||
},
|
||||
});
|
||||
};
|
||||
const createTeam = async (team: Prisma.TeamCreateInput) => {
|
||||
try {
|
||||
const requestedSlug = (team.metadata as z.infer<typeof teamMetadataSchema>)?.requestedSlug;
|
||||
if (requestedSlug) {
|
||||
const unpublishedTeam = await checkUnpublishedTeam(requestedSlug);
|
||||
if (unpublishedTeam) {
|
||||
throw Error("Unique constraint failed on the fields");
|
||||
}
|
||||
}
|
||||
return await prisma.team.create({
|
||||
data: {
|
||||
...team,
|
||||
},
|
||||
include: {
|
||||
eventTypes: true,
|
||||
},
|
||||
});
|
||||
} catch (_err) {
|
||||
if (_err instanceof Error && _err.message.indexOf("Unique constraint failed on the fields") !== -1) {
|
||||
console.log(`Team '${team.name}' already exists, skipping.`);
|
||||
return;
|
||||
}
|
||||
throw _err;
|
||||
}
|
||||
};
|
||||
|
||||
const team = await createTeam(teamInput);
|
||||
if (!team) {
|
||||
return;
|
||||
}
|
||||
|
||||
console.log(
|
||||
`🏢 Created team '${teamInput.name}' - ${process.env.NEXT_PUBLIC_WEBAPP_URL}/team/${team.slug}`
|
||||
);
|
||||
|
||||
for (const eventType of team.eventTypes) {
|
||||
await prisma.eventType.update({
|
||||
where: {
|
||||
id: eventType.id,
|
||||
},
|
||||
data: {
|
||||
users: {
|
||||
connect: users.map((user) => ({ id: user.id })),
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
for (const user of users) {
|
||||
const { role = MembershipRole.OWNER, id, username } = user;
|
||||
await prisma.membership.create({
|
||||
data: {
|
||||
createdAt: new Date(),
|
||||
teamId: team.id,
|
||||
userId: id,
|
||||
role: role,
|
||||
accepted: true,
|
||||
},
|
||||
});
|
||||
console.log(`\t👤 Added '${teamInput.name}' membership for '${username}' with role '${role}'`);
|
||||
}
|
||||
|
||||
return team;
|
||||
}
|
||||
|
||||
export async function seedAttributes(teamId: number) {
|
||||
const mockAttributes = [
|
||||
{
|
||||
name: "Department",
|
||||
type: "SINGLE_SELECT",
|
||||
options: ["Engineering", "Sales", "Marketing", "Product", "Design"],
|
||||
},
|
||||
{
|
||||
name: "Location",
|
||||
type: "SINGLE_SELECT",
|
||||
options: ["New York", "London", "Tokyo", "Berlin", "Remote"],
|
||||
},
|
||||
{
|
||||
name: "Skills",
|
||||
type: "MULTI_SELECT",
|
||||
options: ["JavaScript", "React", "Node.js", "Python", "Design", "Sales"],
|
||||
},
|
||||
{
|
||||
name: "Years of Experience",
|
||||
type: "NUMBER",
|
||||
},
|
||||
{
|
||||
name: "Bio",
|
||||
type: "TEXT",
|
||||
},
|
||||
];
|
||||
// Check if attributes already exist
|
||||
const existingAttributes = await prisma.attribute.findMany({
|
||||
where: {
|
||||
teamId: teamId,
|
||||
name: {
|
||||
in: mockAttributes.map((attr) => attr.name),
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
if (existingAttributes.length > 0) {
|
||||
console.log(`Skipping attributes seed, attributes already exist`);
|
||||
return;
|
||||
}
|
||||
|
||||
// Get team members
|
||||
const memberships = await prisma.membership.findMany({
|
||||
where: {
|
||||
teamId: teamId,
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
userId: true,
|
||||
},
|
||||
});
|
||||
|
||||
console.log(`🎯 Creating attributes for team ${teamId}`);
|
||||
|
||||
const attributeRaw: { id: string; options: { id: string; value: string }[] }[] = [];
|
||||
|
||||
for (const attr of mockAttributes) {
|
||||
const attribute = await prisma.attribute.create({
|
||||
data: {
|
||||
name: attr.name,
|
||||
slug: attr.name.toLowerCase().replace(/ /g, "-"),
|
||||
type: attr.type as "TEXT" | "NUMBER" | "SINGLE_SELECT" | "MULTI_SELECT",
|
||||
teamId: teamId,
|
||||
enabled: true,
|
||||
options: attr.options
|
||||
? {
|
||||
create: attr.options.map((opt) => ({
|
||||
value: opt,
|
||||
slug: opt.toLowerCase().replace(/ /g, "-"),
|
||||
})),
|
||||
}
|
||||
: undefined,
|
||||
},
|
||||
include: {
|
||||
options: true,
|
||||
},
|
||||
});
|
||||
|
||||
attributeRaw.push({
|
||||
id: attribute.id,
|
||||
options: attribute.options.map((opt) => ({
|
||||
id: opt.id,
|
||||
value: opt.value,
|
||||
})),
|
||||
});
|
||||
|
||||
console.log(`\t📝 Created attribute: ${attr.name}`);
|
||||
|
||||
// Assign random values/options to members
|
||||
for (const member of memberships) {
|
||||
if (attr.type === "TEXT") {
|
||||
const mockText = `Sample ${attr.name.toLowerCase()} text for user ${member.userId}`;
|
||||
await prisma.attributeOption.create({
|
||||
data: {
|
||||
value: mockText,
|
||||
slug: mockText.toLowerCase().replace(/ /g, "-"),
|
||||
attribute: {
|
||||
connect: {
|
||||
id: attribute.id,
|
||||
},
|
||||
},
|
||||
assignedUsers: {
|
||||
create: {
|
||||
memberId: member.id,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
} else if (attr.type === "NUMBER") {
|
||||
const mockNumber = Math.floor(Math.random() * 10 + 1).toString();
|
||||
await prisma.attributeOption.create({
|
||||
data: {
|
||||
value: mockNumber,
|
||||
slug: mockNumber,
|
||||
attribute: {
|
||||
connect: {
|
||||
id: attribute.id,
|
||||
},
|
||||
},
|
||||
assignedUsers: {
|
||||
create: {
|
||||
memberId: member.id,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
} else if (attr.type === "SINGLE_SELECT" && attribute.options.length > 0) {
|
||||
const randomOption = attribute.options[Math.floor(Math.random() * attribute.options.length)];
|
||||
await prisma.attributeToUser.create({
|
||||
data: {
|
||||
memberId: member.id,
|
||||
attributeOptionId: randomOption.id,
|
||||
},
|
||||
});
|
||||
} else if (attr.type === "MULTI_SELECT" && attribute.options.length > 0) {
|
||||
// Assign 1-3 random options
|
||||
const numOptions = Math.floor(Math.random() * 3) + 1;
|
||||
const shuffledOptions = [...attribute.options].sort(() => Math.random() - 0.5);
|
||||
const selectedOptions = shuffledOptions.slice(0, numOptions);
|
||||
|
||||
for (const option of selectedOptions) {
|
||||
await prisma.attributeToUser.create({
|
||||
data: {
|
||||
memberId: member.id,
|
||||
attributeOptionId: option.id,
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
console.log(`\t✅ Assigned ${attr.name} values to ${memberships.length} members`);
|
||||
}
|
||||
return attributeRaw;
|
||||
}
|
||||
|
||||
export async function seedRoutingForms(
|
||||
teamId: number,
|
||||
userId: number,
|
||||
attributeRaw: { id: string; options: { id: string; value: string }[] }[],
|
||||
javascriptEventId: number,
|
||||
salesEventId: number
|
||||
) {
|
||||
const seededForm = {
|
||||
id: "948ae412-d995-4865-885a-48302588de03",
|
||||
name: `Seeded Form - Insights for ${teamId}`,
|
||||
routes: [
|
||||
{
|
||||
id: "8a898988-89ab-4cde-b012-31823f708642",
|
||||
value: "team/insights-team/team-javascript",
|
||||
eventTypeId: javascriptEventId,
|
||||
},
|
||||
{
|
||||
id: "8b2224b2-89ab-4cde-b012-31823f708642",
|
||||
value: "team/insights-team/team-sales",
|
||||
eventTypeId: salesEventId,
|
||||
},
|
||||
],
|
||||
formFieldLocation: {
|
||||
id: "674c169a-e40a-492c-b4bb-6f5213873bd6",
|
||||
},
|
||||
formFieldSkills: {
|
||||
id: "83316968-45bf-4c9d-b5d4-5368a8d2d2a8",
|
||||
},
|
||||
formFieldEmail: {
|
||||
id: "dd28ffcf-7029-401e-bddb-ce2e7496a1c1",
|
||||
},
|
||||
formFieldManager: {
|
||||
id: "57734f65-8bbb-4065-9e71-fb7f0b7485f8",
|
||||
},
|
||||
formFieldRating: {
|
||||
id: "f4e9fa6c-5c5d-4d8e-b15c-7f37e9d0c729",
|
||||
},
|
||||
};
|
||||
|
||||
const form = await prisma.app_RoutingForms_Form.findUnique({
|
||||
where: {
|
||||
id: seededForm.id,
|
||||
},
|
||||
});
|
||||
if (form) {
|
||||
console.log(`Skipping Routing Form - Form Seed, ${seededForm.name} already exists`);
|
||||
return;
|
||||
}
|
||||
|
||||
if (attributeRaw.length === 0) {
|
||||
throw new Error("No attributes found - Please call seedAttributes first");
|
||||
}
|
||||
|
||||
const formFieldSkillsOptions = attributeRaw[2].options.map((opt) => ({
|
||||
id: opt.id,
|
||||
label: opt.value,
|
||||
}));
|
||||
|
||||
const formFieldLocationOptions = attributeRaw[1].options.map((opt) => ({
|
||||
id: opt.id,
|
||||
label: opt.value,
|
||||
}));
|
||||
|
||||
await prisma.app_RoutingForms_Form.create({
|
||||
data: {
|
||||
id: seededForm.id,
|
||||
routes: [
|
||||
{
|
||||
id: seededForm.routes[0].id,
|
||||
action: {
|
||||
type: "eventTypeRedirectUrl",
|
||||
value: seededForm.routes[0].value,
|
||||
eventTypeId: seededForm.routes[0].eventTypeId,
|
||||
},
|
||||
queryValue: {
|
||||
id: "aaba9988-cdef-4012-b456-719300f53ef8",
|
||||
type: "group",
|
||||
children1: {
|
||||
"b98b98a8-0123-4456-b89a-b19300f55277": {
|
||||
type: "rule",
|
||||
properties: {
|
||||
field: seededForm.formFieldSkills.id,
|
||||
value: [
|
||||
formFieldSkillsOptions.filter((opt) => opt.label === "JavaScript").map((opt) => opt.id),
|
||||
],
|
||||
operator: "multiselect_equals",
|
||||
valueSrc: ["value"],
|
||||
valueType: ["multiselect"],
|
||||
valueError: [null],
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
attributesQueryValue: {
|
||||
id: "ab99bbb9-89ab-4cde-b012-319300f53ef8",
|
||||
type: "group",
|
||||
children1: {
|
||||
"b98b98a8-0123-4456-b89a-b19300f55277": {
|
||||
type: "rule",
|
||||
properties: {
|
||||
field: attributeRaw[2].id,
|
||||
value: [
|
||||
attributeRaw[2].options.filter((opt) => opt.value === "JavaScript").map((opt) => opt.id),
|
||||
],
|
||||
operator: "multiselect_some_in",
|
||||
valueSrc: ["value"],
|
||||
valueType: ["multiselect"],
|
||||
valueError: [null],
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
id: seededForm.routes[1].id,
|
||||
action: {
|
||||
type: "eventTypeRedirectUrl",
|
||||
value: seededForm.routes[1].value,
|
||||
eventTypeId: seededForm.routes[1].eventTypeId,
|
||||
},
|
||||
queryValue: {
|
||||
id: "aaba9948-cdef-4012-b456-719300f53ef8",
|
||||
type: "group",
|
||||
children1: {
|
||||
"c98b98a8-1123-4456-e89a-a19300f55277": {
|
||||
type: "rule",
|
||||
properties: {
|
||||
field: seededForm.formFieldSkills.id,
|
||||
value: [formFieldSkillsOptions.filter((opt) => opt.label === "Sales").map((opt) => opt.id)],
|
||||
operator: "multiselect_equals",
|
||||
valueSrc: ["value"],
|
||||
valueType: ["multiselect"],
|
||||
valueError: [null],
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
attributesQueryValue: {
|
||||
id: "ab988888-89ab-4cde-b012-319300f53ef8",
|
||||
type: "group",
|
||||
children1: {
|
||||
"b98b98a12-0123-4456-b89a-b19300f55277": {
|
||||
type: "rule",
|
||||
properties: {
|
||||
field: attributeRaw[2].id,
|
||||
value: [
|
||||
attributeRaw[2].options.filter((opt) => opt.value === "Sales").map((opt) => opt.id),
|
||||
],
|
||||
operator: "multiselect_some_in",
|
||||
valueSrc: ["value"],
|
||||
valueType: ["multiselect"],
|
||||
valueError: [null],
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
fallbackAttributesQueryValue: {
|
||||
id: "a9888488-4567-489a-bcde-f19300f53ef8",
|
||||
type: "group",
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "148899aa-4567-489a-bcde-f1823f708646",
|
||||
action: { type: "customPageMessage", value: "Fallback Message" },
|
||||
isFallback: true,
|
||||
queryValue: { id: "814899aa-4567-489a-bcde-f1823f708646", type: "group" },
|
||||
},
|
||||
],
|
||||
fields: [
|
||||
{
|
||||
id: seededForm.formFieldLocation.id,
|
||||
type: "select",
|
||||
label: "Location",
|
||||
options: formFieldLocationOptions,
|
||||
required: true,
|
||||
},
|
||||
{
|
||||
id: seededForm.formFieldSkills.id,
|
||||
type: "multiselect",
|
||||
label: "skills",
|
||||
options: formFieldSkillsOptions,
|
||||
required: true,
|
||||
},
|
||||
{
|
||||
id: seededForm.formFieldEmail.id,
|
||||
type: "email",
|
||||
label: "Email",
|
||||
required: true,
|
||||
},
|
||||
{
|
||||
id: seededForm.formFieldManager.id,
|
||||
type: "text",
|
||||
label: "Manager",
|
||||
required: true,
|
||||
},
|
||||
{
|
||||
id: seededForm.formFieldRating.id,
|
||||
type: "number",
|
||||
label: "Rating",
|
||||
required: true,
|
||||
},
|
||||
],
|
||||
team: {
|
||||
connect: {
|
||||
id: teamId,
|
||||
},
|
||||
},
|
||||
user: {
|
||||
connect: {
|
||||
id: userId,
|
||||
},
|
||||
},
|
||||
name: seededForm.name,
|
||||
},
|
||||
});
|
||||
return seededForm;
|
||||
}
|
||||
|
||||
type SeededForm = {
|
||||
id: string;
|
||||
name: string;
|
||||
routes: {
|
||||
id: string;
|
||||
value: string;
|
||||
}[];
|
||||
formFieldLocation: {
|
||||
id: string;
|
||||
};
|
||||
formFieldSkills: {
|
||||
id: string;
|
||||
};
|
||||
formFieldEmail: {
|
||||
id: string;
|
||||
};
|
||||
formFieldManager: {
|
||||
id: string;
|
||||
};
|
||||
formFieldRating: {
|
||||
id: string;
|
||||
};
|
||||
};
|
||||
|
||||
// id formFillerId formId response createdAt routedToBookingUid
|
||||
// 1 cm35rrf1x0001rqjskhydev9i 948ae412-d995-4865-885a-48302588de03 "{""83316968-45bf-4c9d-b5d4-5368a8d2d2a8"": {""label"": ""skills"", ""value"": [""8d841a71-3b96-4930-9e2d-57a3584ec21b""]}}" 2024-11-06 11:01:56.853
|
||||
|
||||
export async function seedRoutingFormResponses(
|
||||
seededForm: SeededForm,
|
||||
attributeRaw: { id: string; options: { id: string; value: string }[] }[],
|
||||
teamId: number
|
||||
) {
|
||||
// Get all bookings for this team
|
||||
const bookings = await prisma.booking.findMany({
|
||||
where: {
|
||||
eventType: {
|
||||
teamId: teamId,
|
||||
},
|
||||
},
|
||||
take: 1000, // Limit to 1000 responses
|
||||
select: {
|
||||
id: true,
|
||||
uid: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (bookings.length === 0) {
|
||||
console.log("No bookings found for team - skipping routing form responses");
|
||||
return;
|
||||
}
|
||||
|
||||
// Create routing form responses linked to random bookings
|
||||
for (const booking of bookings) {
|
||||
// Randomly select 1-3 skills from the form field options
|
||||
const numSkills = Math.floor(Math.random() * 3) + 1;
|
||||
const shuffledSkillOptions = [...attributeRaw[2].options].sort(() => Math.random() - 0.5);
|
||||
const selectedSkills = shuffledSkillOptions.slice(0, numSkills);
|
||||
|
||||
const selectedLocation =
|
||||
attributeRaw[1].options[Math.floor(Math.random() * attributeRaw[1].options.length)];
|
||||
|
||||
// Generate a random date within the last 30 days
|
||||
const randomDate = dayjs()
|
||||
.subtract(Math.floor(Math.random() * 30), "days")
|
||||
.subtract(Math.floor(Math.random() * 24), "hours")
|
||||
.subtract(Math.floor(Math.random() * 60), "minutes");
|
||||
|
||||
// Create the form response with the routedToBookingUid field set
|
||||
const response = await prisma.app_RoutingForms_FormResponse.create({
|
||||
data: {
|
||||
formId: seededForm.id,
|
||||
formFillerId: randomUUID(),
|
||||
createdAt: randomDate.toDate(),
|
||||
response: {
|
||||
[seededForm.formFieldLocation.id]: {
|
||||
label: "Location",
|
||||
value: selectedLocation.id,
|
||||
},
|
||||
[seededForm.formFieldSkills.id]: {
|
||||
label: "skills",
|
||||
value: selectedSkills.map((opt) => opt.id),
|
||||
},
|
||||
[seededForm.formFieldEmail.id]: {
|
||||
label: "Email",
|
||||
value: faker.internet.email(),
|
||||
},
|
||||
[seededForm.formFieldManager.id]: {
|
||||
label: "Manager",
|
||||
value: faker.person.fullName(),
|
||||
},
|
||||
[seededForm.formFieldRating.id]: {
|
||||
label: "Rating",
|
||||
value: Math.floor(Math.random() * 5) + 1,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
// Update the response with the booking UID
|
||||
await prisma.booking.update({
|
||||
where: {
|
||||
id: booking.id,
|
||||
},
|
||||
data: {
|
||||
routedFromRoutingFormReponse: { connect: { id: response.id } },
|
||||
startTime: randomDate.toDate(),
|
||||
endTime: randomDate.add(1, "hour").toDate(),
|
||||
createdAt: randomDate.toDate(),
|
||||
},
|
||||
});
|
||||
|
||||
await prisma.app_RoutingForms_FormResponse.create({
|
||||
data: {
|
||||
formId: seededForm.id,
|
||||
formFillerId: randomUUID(),
|
||||
createdAt: randomDate.subtract(2, "hour").toDate(),
|
||||
response: {
|
||||
[seededForm.formFieldLocation.id]: {
|
||||
label: "Location",
|
||||
value: selectedLocation.id,
|
||||
},
|
||||
[seededForm.formFieldSkills.id]: {
|
||||
label: "skills",
|
||||
value: selectedSkills.map((opt) => opt.id),
|
||||
},
|
||||
[seededForm.formFieldEmail.id]: {
|
||||
label: "Email",
|
||||
value: faker.internet.email(),
|
||||
},
|
||||
[seededForm.formFieldManager.id]: {
|
||||
label: "Manager",
|
||||
value: faker.person.fullName(),
|
||||
},
|
||||
[seededForm.formFieldRating.id]: {
|
||||
label: "Rating",
|
||||
value: Math.floor(Math.random() * 5) + 1,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
console.log(`Created ${bookings.length} routing form responses`);
|
||||
}
|
||||
+3
-3
@@ -6,7 +6,7 @@ import googleMeetMeta from "@calcom/app-store/googlevideo/_metadata";
|
||||
import zoomMeta from "@calcom/app-store/zoomvideo/_metadata";
|
||||
import dayjs from "@calcom/dayjs";
|
||||
import { getOrgFullOrigin } from "@calcom/ee/organizations/lib/orgDomains";
|
||||
import { hashPassword } from "@calcom/features/auth/lib/hashPassword";
|
||||
import { hashPassword } from "@calcom/lib/auth/hashPassword";
|
||||
import { DEFAULT_SCHEDULE, getAvailabilityFromSchedule } from "@calcom/lib/availability";
|
||||
import prisma from "@calcom/prisma";
|
||||
import type { Membership, Team, User, UserPermissionRole } from "@calcom/prisma/client";
|
||||
@@ -14,10 +14,10 @@ import { Prisma } from "@calcom/prisma/client";
|
||||
import { BookingStatus, MembershipRole, RedirectType, SchedulingType } from "@calcom/prisma/enums";
|
||||
import type { Ensure } from "@calcom/types/utils";
|
||||
|
||||
import mainHugeEventTypesSeed from "../packages/prisma/seed-huge-event-types";
|
||||
import { createUserAndEventType } from "../packages/prisma/seed-utils";
|
||||
import type { teamMetadataSchema } from "../packages/prisma/zod-utils";
|
||||
import mainAppStore from "./seed-app-store";
|
||||
import mainHugeEventTypesSeed from "./seed-huge-event-types";
|
||||
import { createUserAndEventType } from "./seed-utils";
|
||||
|
||||
type PlatformUser = {
|
||||
email: string;
|
||||
|
||||
Reference in New Issue
Block a user