Skip to content

Scheduling infrastructure for absolutely everyone.

chore: routingform org attribute seed (#17510)

sean-brydon12c500530565
diff --git a/apps/api/v1/test/lib/utils/retrieveScopedAccessibleUsers.integration-test.ts b/apps/api/v1/test/lib/utils/retrieveScopedAccessibleUsers.integration-test.ts
index 2314aaa50d3..d670defc721 100644
--- a/apps/api/v1/test/lib/utils/retrieveScopedAccessibleUsers.integration-test.ts
+++ b/apps/api/v1/test/lib/utils/retrieveScopedAccessibleUsers.integration-test.ts
@@ -81,7 +81,7 @@ describe("retrieveScopedAccessibleUsers tests", () => {
where: { email: "[email protected]" },
});
- expect(accessibleUserIds.length).toBe(3);
+ expect(accessibleUserIds.length).toBe(11);
expect(accessibleUserIds).toContain(memberOneUser.id);
expect(accessibleUserIds).toContain(memberTwoUser.id);
expect(accessibleUserIds).toContain(adminUser.id);
diff --git a/packages/prisma/seed-insights.ts b/packages/prisma/seed-insights.ts
index 0a32a8c6ed6..32dc6d32cfd 100644
--- a/packages/prisma/seed-insights.ts
+++ b/packages/prisma/seed-insights.ts
@@ -6,6 +6,8 @@ import dayjs from "@calcom/dayjs";
import { hashPassword } from "@calcom/features/auth/lib/hashPassword";
import { BookingStatus } from "@calcom/prisma/enums";
+import { seedAttributes, seedRoutingFormResponses, seedRoutingForms } from "./seed-utils";
+
function getRandomRatingFeedback() {
const feedbacks = [
"Great chat!",
@@ -28,6 +30,7 @@ const shuffle = (
title: true;
length: true;
description: true;
+ teamId: true;
};
}>[],
usersIdsToPick?: number[]
@@ -83,65 +86,37 @@ const shuffle = (
const prisma = new PrismaClient();
async function main() {
- // First find if not then create everything
- let insightsAdmin = await prisma.user.findFirst({
+ // First find the organization we want to add insights to
+ const organization = await prisma.team.findFirst({
where: {
- email: "[email protected]",
+ slug: "acme",
+ organizationSettings: {
+ isOrganizationVerified: true,
+ orgAutoAcceptEmail: "acme.com",
+ isAdminAPIEnabled: true,
+ },
},
- });
-
- if (!insightsAdmin) {
- insightsAdmin = await prisma.user.create({
- data: {
- email: "[email protected]",
- password: {
- create: {
- hash: await hashPassword("insightsinsightsinsights...!"),
- },
+ include: {
+ members: {
+ include: {
+ // eslint-disable-next-line @calcom/eslint/no-prisma-include-true
+ user: true,
},
- name: "Insights Admin",
- role: "ADMIN",
- username: "insights-admin",
- completedOnboarding: true,
},
- });
-
- if (!insightsAdmin) {
- // Throw error
- throw new Error("Insights Admin not created");
- }
- }
-
- let insightsUser = await prisma.user.findFirst({
- where: {
- email: "[email protected]",
},
});
- if (!insightsUser) {
- insightsUser = await prisma.user.create({
- data: {
- email: "[email protected]",
- password: {
- create: {
- hash: await hashPassword("insightsuser"),
- },
- },
- name: "Insights User",
- role: "USER",
- username: "insights-user",
- completedOnboarding: true,
- },
- });
- if (!insightsUser) {
- // Throw error
- throw new Error("Insights Admin not created");
- }
+ 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.findFirst({
where: {
slug: "insights-team",
+ parentId: organization.id, // Make sure team is under the organization
},
});
@@ -150,190 +125,70 @@ async function main() {
data: {
name: "Insights",
slug: "insights-team",
+ parent: {
+ connect: {
+ id: organization.id,
+ },
+ },
},
});
+
+ // Add org members to insights team
await prisma.membership.createMany({
- data: [
- {
- teamId: insightsTeam.id,
- userId: insightsAdmin.id,
- role: "OWNER",
- accepted: true,
- },
- {
- teamId: insightsTeam.id,
- userId: insightsUser.id,
- role: "MEMBER",
- accepted: true,
- },
- ],
+ data: orgMembers.map((member) => ({
+ teamId: insightsTeam!.id,
+ userId: member.user.id,
+ role: member.role,
+ accepted: true,
+ })),
});
- if (!insightsTeam) {
- insightsTeam = await prisma.team.create({
- data: {
- name: "Insights",
- slug: "insights-team",
- },
- });
- }
-
- if (insightsAdmin && insightsTeam) {
- await prisma.team.update({
- where: {
- id: insightsTeam.id,
- },
- data: {
- members: {
- connect: {
- userId_teamId: {
- userId: insightsAdmin.id,
- teamId: insightsTeam.id,
- },
- },
- },
- },
- });
- }
}
+ // Create event types for the team
let teamEvents = await prisma.eventType.findMany({
where: {
teamId: insightsTeam.id,
},
- });
-
- const userSingleEventsAdmin = await prisma.eventType.findMany({
- where: {
- userId: insightsUser.id,
- },
- });
-
- const userSingleEvents = await prisma.eventType.findMany({
- where: {
- userId: insightsUser.id,
+ select: {
+ id: true,
+ title: true,
+ slug: true,
+ description: true,
+ length: true,
+ teamId: true,
+ userId: true,
},
});
- if (userSingleEventsAdmin.length === 0 && userSingleEvents.length === 0) {
- await prisma.eventType.create({
- data: {
- title: "Single Event Admin",
- slug: "single-event-admin",
- description: "Single Event Admin",
- length: 60,
- userId: insightsAdmin.id,
- users: {
- connect: {
- id: insightsAdmin.id,
- },
- },
- },
- });
- await prisma.eventType.create({
- data: {
- title: "Single Event",
- slug: "single-event",
- description: "Single Event",
- length: 60,
- userId: insightsUser.id,
- users: {
- connect: {
- id: insightsUser.id,
- },
- },
- },
- });
- const singleEventTypesAdmin = await prisma.eventType.findFirst({
- select: {
- id: true,
- userId: true,
- title: true,
- length: true,
- description: true,
- },
- where: {
- userId: insightsAdmin.id,
- },
- });
-
- const singleEventTypes = await prisma.eventType.findFirst({
- select: {
- id: true,
- userId: true,
- length: true,
- title: true,
- description: true,
- },
- where: {
- userId: insightsUser.id,
- },
- });
-
- if (!singleEventTypesAdmin || !singleEventTypes) {
- throw new Error("Could not create single event types");
- }
-
- const singleEvents = [singleEventTypesAdmin, singleEventTypes];
-
- // create bookings random for single event type
- const baseBookingSingle: Prisma.BookingCreateManyInput = {
- uid: "demoUIDSingle",
- title: "Single Event",
- description: "Single Event",
- startTime: dayjs().toISOString(),
- endTime: dayjs().toISOString(),
- // This gets overriden in shuffle
- userId: insightsUser.id,
- };
-
- // Validate if they are null of undefined throw error
- if (!insightsAdmin || !insightsUser || !insightsAdmin.id || !insightsUser.id) {
- throw new Error("Could not find user");
- }
-
- await prisma.booking.createMany({
- data: [
- ...new Array(10000)
- .fill(0)
- .map(() => shuffle({ ...baseBookingSingle }, dayjs().get("y") - 1, singleEvents)),
- ],
- });
-
- await prisma.booking.createMany({
- data: [
- ...new Array(10000)
- .fill(0)
- .map(() => shuffle({ ...baseBookingSingle }, dayjs().get("y") - 0, singleEvents)),
- ],
- });
- }
-
- if (teamEvents.length === 0) {
+ if (teamEvents?.length === 0) {
await prisma.eventType.createMany({
data: [
{
title: "Team Meeting",
- slug: "team-meeting",
+ slug: "team-sales",
description: "Team Meeting",
length: 60,
teamId: insightsTeam.id,
schedulingType: "ROUND_ROBIN",
+ assignAllTeamMembers: true,
},
{
title: "Team Lunch",
- slug: "team-lunch",
+ slug: "team-python",
description: "Team Lunch",
length: 30,
teamId: insightsTeam.id,
- schedulingType: "COLLECTIVE",
+ schedulingType: "ROUND_ROBIN",
+ assignAllTeamMembers: true,
},
{
- title: "Team Coffee",
- slug: "team-coffee",
+ title: "Team javascript",
+ slug: "team-javascript",
description: "Team Coffee",
length: 15,
teamId: insightsTeam.id,
- schedulingType: "COLLECTIVE",
+ schedulingType: "ROUND_ROBIN",
+ assignAllTeamMembers: true,
},
],
});
@@ -341,58 +196,85 @@ async function main() {
where: {
teamId: insightsTeam.id,
},
+ select: {
+ id: true,
+ title: true,
+ slug: true,
+ description: true,
+ length: true,
+ teamId: true,
+ userId: true,
+ },
});
}
- const baseBooking: Prisma.BookingCreateManyInput = {
+ // 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: insightsUser.id,
- eventTypeId: teamEvents[0].id,
+ userId: orgMembers[0].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, [
- insightsAdmin?.id ?? 0,
- insightsUser?.id ?? 0,
- ])
- ),
+ ...new Array(10000).fill(0).map(() =>
+ shuffle(
+ { ...baseBooking },
+ dayjs().get("y") - 2,
+ teamEvents,
+ orgMembers.map((m) => m.id)
+ )
+ ),
],
});
await prisma.booking.createMany({
data: [
- ...new Array(10000)
- .fill(0)
- .map(() =>
- shuffle({ ...baseBooking }, dayjs().get("y") - 1, teamEvents, [
- insightsAdmin?.id ?? 0,
- insightsUser?.id ?? 0,
- ])
- ),
+ ...new Array(10000).fill(0).map(() =>
+ shuffle(
+ { ...baseBooking },
+ dayjs().get("y") - 1,
+ teamEvents,
+ orgMembers.map((m) => m.id)
+ )
+ ),
],
});
await prisma.booking.createMany({
data: [
- ...new Array(10000)
- .fill(0)
- .map(() =>
- shuffle({ ...baseBooking }, dayjs().get("y"), teamEvents, [
- insightsAdmin?.id ?? 0,
- insightsUser?.id ?? 0,
- ])
- ),
+ ...new Array(10000).fill(0).map(() =>
+ shuffle(
+ { ...baseBooking },
+ dayjs().get("y"),
+ teamEvents,
+ orgMembers.map((m) => m.id)
+ )
+ ),
],
});
+
+ // 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 ?? orgMembers[0].user.id,
+ attributes
+ );
+
+ if (seededForm) {
+ await seedRoutingFormResponses(seededForm, attributes, insightsTeam.id);
+ }
}
main()
.then(async () => {
diff --git a/packages/prisma/seed-utils.ts b/packages/prisma/seed-utils.ts
index ef06d0822d4..e12efc4ca15 100644
--- a/packages/prisma/seed-utils.ts
+++ b/packages/prisma/seed-utils.ts
@@ -1,4 +1,5 @@
import type { Prisma, UserPermissionRole } from "@prisma/client";
+import { randomUUID } from "crypto";
import { uuid } from "short-uuid";
import type z from "zod";
@@ -264,3 +265,375 @@ export async function createTeamAndAddUsers(
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 }[] }[]
+) {
+ 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",
+ },
+ {
+ id: "8b2224b2-89ab-4cde-b012-31823f708642",
+ value: "team/insights-team/team-sales",
+ },
+ ],
+ formFieldFilled: {
+ id: "83316968-45bf-4c9d-b5d4-5368a8d2d2a8",
+ },
+ };
+
+ const form = await prisma.app_RoutingForms_Form.findUnique({
+ where: {
+ id: seededForm.id,
+ },
+ });
+ if (form) {
+ console.log(`Skipping Routing Form - Form Seed, "Seeded Form - Pro" already exists`);
+ return;
+ }
+
+ if (attributeRaw.length === 0) {
+ throw new Error("No attributes found - Please call seedAttributes first");
+ }
+
+ 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: 1133,
+ },
+ queryValue: {
+ id: "aaba9988-cdef-4012-b456-719300f53ef8",
+ type: "group",
+ },
+ 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: 1133,
+ },
+ queryValue: {
+ id: "aaba9948-cdef-4012-b456-719300f53ef8",
+ type: "group",
+ },
+ 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.formFieldFilled.id,
+ type: "multiselect",
+ label: "skills",
+ options: attributeRaw[2].options.map((opt) => ({
+ id: opt.id,
+ label: opt.value,
+ })),
+ 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;
+ }[];
+ formFieldFilled: {
+ 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: 250, // Limit to 250 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 shuffledOptions = [...attributeRaw[2].options].sort(() => Math.random() - 0.5);
+ const selectedSkills = shuffledOptions.slice(0, numSkills);
+
+ // Create the form response with the routedToBookingUid field set
+ const response = await prisma.app_RoutingForms_FormResponse.create({
+ data: {
+ formId: seededForm.id,
+ formFillerId: randomUUID(),
+ response: {
+ [seededForm.formFieldFilled.id]: {
+ label: "skills",
+ value: selectedSkills.map((opt) => opt.id),
+ },
+ },
+ },
+ });
+
+ // Update the response with the booking UID
+ await prisma.booking.update({
+ where: {
+ id: booking.id,
+ },
+ data: {
+ routedFromRoutingFormReponse: { connect: { id: response.id } },
+ },
+ });
+ }
+
+ console.log(`Created ${bookings.length} routing form responses`);
+}
diff --git a/packages/prisma/seed.ts b/packages/prisma/seed.ts
index 76642f85191..c97a39e11c2 100644
--- a/packages/prisma/seed.ts
+++ b/packages/prisma/seed.ts
@@ -1096,51 +1096,34 @@ async function main() {
},
],
},
- {
- memberData: {
- email: "[email protected]",
- password: {
- create: {
- hash: "member1-acme",
- },
- },
- username: "member1-acme",
- name: "Member 1",
- },
- orgMembership: {
- role: "MEMBER",
- accepted: true,
- },
- orgProfile: {
- username: "member1",
- },
- inTeams: [
- {
- slug: "team1",
- role: "ADMIN",
- },
- ],
- },
- {
+ ...Array.from({ length: 10 }, (_, i) => ({
memberData: {
- email: "[email protected]",
+ email: `member${i}[email protected]`,
password: {
create: {
- hash: "member2-acme",
+ hash: `member${i}-acme`,
},
},
- username: "member2-acme",
- name: "Member 2",
+ username: `member${i}-acme`,
+ name: `Member ${i}`,
},
orgMembership: {
- role: "MEMBER",
+ role: MembershipRole.MEMBER,
accepted: true,
},
orgProfile: {
- username: "member2",
+ username: `member${i}`,
},
- inTeams: [],
- },
+ inTeams:
+ i % 2 === 0
+ ? [
+ {
+ slug: "team1",
+ role: MembershipRole.MEMBER,
+ },
+ ]
+ : [],
+ })),
],
},
teams: [