refactor: Cal.diy (#28903)
* feat: Cal.diy — community-driven MIT-licensed fork of Cal.com This squashed commit contains all Cal.diy changes applied on top of calcom/cal.com main: - Rebrand Cal.com to Cal.diy across the entire codebase - Remove Enterprise Edition (EE) features, license checks, and AGPL restrictions - Switch license from AGPL-3.0 to MIT - Remove docs/ directory (migrated to Nextra at cal.diy) - Remove dead code: org tests, EE tips, platform nav, premium username, SAML/SSO, etc. - Clean up .env.example for self-hosted Cal.diy - Update Docker image references to calcom/cal.diy - Update README, CONTRIBUTING.md, and issue templates for Cal.diy community fork - Add PR welcome bot for Cal.diy contributors - Fix API v2 breaking changes oasdiff ignore entries - Replace Blacksmith CI runners with default GitHub Actions 3893 files changed, 20789 insertions(+), 411020 deletions(-) Co-Authored-By: [email protected] <[email protected]> * refactor: remove org-specific /organizations/:orgId endpoints from API v2 atoms controllers (#1701) Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * fix: revert Cal.diy Inc to Cal.com, Inc. in license files, copyright notices, and package metadata (#1702) Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * rip out org related comments in api v2 --------- Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
This commit is contained in:
1 parent
a17f28e9ab
commit
ab21c7f805
4080 files changed
+14403
-404922
No files matched your search
+69
-102
@@ -61,19 +61,13 @@ function hoursFromNow(hours: number): number {
|
||||
async function seedAuditLogsForBooking({
|
||||
bookingUid,
|
||||
userUuid,
|
||||
userId,
|
||||
attendeeId,
|
||||
attendeeEmail,
|
||||
eventTypeId,
|
||||
eventTypeLength,
|
||||
}: {
|
||||
bookingUid: string;
|
||||
userUuid: string;
|
||||
userId: number;
|
||||
attendeeId: number | undefined;
|
||||
attendeeEmail: string;
|
||||
eventTypeId: number;
|
||||
eventTypeLength: number;
|
||||
}): Promise<number> {
|
||||
const existingLogs = await prisma.bookingAudit.findFirst({
|
||||
where: { bookingUid },
|
||||
@@ -95,30 +89,7 @@ async function seedAuditLogsForBooking({
|
||||
attendeeActor = await createAttendeeActor(attendeeId);
|
||||
}
|
||||
|
||||
// Create the "rescheduled-to" booking so rescheduledToUid in audit logs points to a real booking
|
||||
const rescheduledToUid = uuidv4();
|
||||
const rescheduledStartTime = new Date(Date.now() + 2 * 24 * 60 * 60 * 1000); // 2 days from now (matches RESCHEDULED log's "new" times)
|
||||
const rescheduledEndTime = new Date(rescheduledStartTime.getTime() + eventTypeLength * 60 * 1000);
|
||||
|
||||
await prisma.booking.create({
|
||||
data: {
|
||||
uid: rescheduledToUid,
|
||||
title: "Audit Log Test Booking - Rescheduled",
|
||||
startTime: rescheduledStartTime,
|
||||
endTime: rescheduledEndTime,
|
||||
status: BookingStatus.ACCEPTED,
|
||||
userId,
|
||||
eventTypeId,
|
||||
fromReschedule: bookingUid,
|
||||
attendees: {
|
||||
create: {
|
||||
email: attendeeEmail,
|
||||
name: "James Wilson",
|
||||
timeZone: "UTC",
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const now = Date.now();
|
||||
let timestampOffset = 0;
|
||||
@@ -165,6 +136,41 @@ async function seedAuditLogsForBooking({
|
||||
},
|
||||
});
|
||||
|
||||
auditLogs.push({
|
||||
bookingUid,
|
||||
actorId: (attendeeActor ?? guestActor).id,
|
||||
action: "RESCHEDULE_REQUESTED",
|
||||
type: "RECORD_UPDATED",
|
||||
timestamp: nextTimestamp(),
|
||||
source: "WEBAPP",
|
||||
operationId: uuidv4(),
|
||||
data: {
|
||||
version: 1,
|
||||
fields: {
|
||||
rescheduleReason: "Conflict with another meeting",
|
||||
rescheduledRequestedBy: attendeeEmail,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
auditLogs.push({
|
||||
bookingUid,
|
||||
actorId: userActor.id,
|
||||
action: "RESCHEDULED",
|
||||
type: "RECORD_UPDATED",
|
||||
timestamp: nextTimestamp(),
|
||||
source: "WEBAPP",
|
||||
operationId: uuidv4(),
|
||||
data: {
|
||||
version: 1,
|
||||
fields: {
|
||||
startTime: { old: hoursFromNow(24), new: hoursFromNow(48) },
|
||||
endTime: { old: hoursFromNow(24.5), new: hoursFromNow(48.5) },
|
||||
rescheduledToUid: { old: null, new: rescheduledToUid },
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
auditLogs.push({
|
||||
bookingUid,
|
||||
actorId: userActor.id,
|
||||
@@ -293,6 +299,24 @@ async function seedAuditLogsForBooking({
|
||||
context: { impersonatedBy: userUuid },
|
||||
});
|
||||
|
||||
auditLogs.push({
|
||||
bookingUid,
|
||||
actorId: appActor.id,
|
||||
action: "CANCELLED",
|
||||
type: "RECORD_UPDATED",
|
||||
timestamp: nextTimestamp(),
|
||||
source: "WEBHOOK",
|
||||
operationId: uuidv4(),
|
||||
data: {
|
||||
version: 1,
|
||||
fields: {
|
||||
cancellationReason: "Payment failed - automatic cancellation",
|
||||
cancelledBy: "[email protected]",
|
||||
status: { old: BookingStatus.ACCEPTED, new: BookingStatus.CANCELLED },
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
auditLogs.push({
|
||||
bookingUid,
|
||||
actorId: userActor.id,
|
||||
@@ -352,59 +376,6 @@ async function seedAuditLogsForBooking({
|
||||
},
|
||||
});
|
||||
|
||||
auditLogs.push({
|
||||
bookingUid,
|
||||
actorId: appActor.id,
|
||||
action: "CANCELLED",
|
||||
type: "RECORD_UPDATED",
|
||||
timestamp: nextTimestamp(),
|
||||
source: "WEBHOOK",
|
||||
operationId: uuidv4(),
|
||||
data: {
|
||||
version: 1,
|
||||
fields: {
|
||||
cancellationReason: "Payment failed - automatic cancellation",
|
||||
cancelledBy: "[email protected]",
|
||||
status: { old: BookingStatus.ACCEPTED, new: BookingStatus.CANCELLED },
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
auditLogs.push({
|
||||
bookingUid,
|
||||
actorId: (attendeeActor ?? guestActor).id,
|
||||
action: "RESCHEDULE_REQUESTED",
|
||||
type: "RECORD_UPDATED",
|
||||
timestamp: nextTimestamp(),
|
||||
source: "WEBAPP",
|
||||
operationId: uuidv4(),
|
||||
data: {
|
||||
version: 1,
|
||||
fields: {
|
||||
rescheduleReason: "Conflict with another meeting",
|
||||
rescheduledRequestedBy: attendeeEmail,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
auditLogs.push({
|
||||
bookingUid,
|
||||
actorId: userActor.id,
|
||||
action: "RESCHEDULED",
|
||||
type: "RECORD_UPDATED",
|
||||
timestamp: nextTimestamp(),
|
||||
source: "WEBAPP",
|
||||
operationId: uuidv4(),
|
||||
data: {
|
||||
version: 1,
|
||||
fields: {
|
||||
startTime: { old: hoursFromNow(24), new: hoursFromNow(48) },
|
||||
endTime: { old: hoursFromNow(24.5), new: hoursFromNow(48.5) },
|
||||
rescheduledToUid: { old: null, new: rescheduledToUid },
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
for (const logData of auditLogs) {
|
||||
await prisma.bookingAudit.create({ data: logData });
|
||||
}
|
||||
@@ -452,7 +423,19 @@ export default async function seedBookingAuditLogs() {
|
||||
});
|
||||
console.log(" ✅ Enabled bookings-v3 globally");
|
||||
|
||||
// Enable booking-audit at team level for owner1-acme's organization
|
||||
if (organizationId) {
|
||||
await prisma.feature.upsert({
|
||||
where: { slug: "booking-audit" },
|
||||
create: {
|
||||
slug: "booking-audit",
|
||||
enabled: false,
|
||||
description: "Enable booking audit trails - Track all booking actions and changes for organizations",
|
||||
type: "OPERATIONAL",
|
||||
},
|
||||
update: {},
|
||||
});
|
||||
|
||||
await prisma.teamFeatures.upsert({
|
||||
where: { teamId_featureId: { teamId: organizationId, featureId: "booking-audit" } },
|
||||
create: {
|
||||
@@ -463,20 +446,7 @@ export default async function seedBookingAuditLogs() {
|
||||
},
|
||||
update: { enabled: true },
|
||||
});
|
||||
|
||||
console.log(` ✅ Enabled booking-audit for organization ${organizationId}`);
|
||||
|
||||
await prisma.teamFeatures.upsert({
|
||||
where: { teamId_featureId: { teamId: organizationId, featureId: "bookings-v3" } },
|
||||
create: {
|
||||
teamId: organizationId,
|
||||
featureId: "bookings-v3",
|
||||
enabled: true,
|
||||
assignedBy: "seed-script",
|
||||
},
|
||||
update: { enabled: true },
|
||||
});
|
||||
console.log(` ✅ Enabled bookings-v3 for organization ${organizationId}`);
|
||||
}
|
||||
|
||||
// Find an event type for this user to create a booking
|
||||
@@ -527,22 +497,19 @@ export default async function seedBookingAuditLogs() {
|
||||
const count = await seedAuditLogsForBooking({
|
||||
bookingUid: booking.uid,
|
||||
userUuid: user.uuid,
|
||||
userId: user.id,
|
||||
attendeeId: booking.attendees[0]?.id,
|
||||
attendeeEmail: booking.attendees[0]?.email ?? "[email protected]",
|
||||
eventTypeId: eventType.id,
|
||||
eventTypeLength: eventType.length,
|
||||
});
|
||||
|
||||
console.log(` ✅ Created ${count} audit log entries`);
|
||||
console.log(` View logs at: /bookings/upcoming?uid=${booking.uid}&activeSegment=history`);
|
||||
console.log(` View logs at: /booking/${booking.uid}/logs`);
|
||||
|
||||
console.log(`\n📊 Summary:`);
|
||||
console.log(` Booking UID: ${booking.uid}`);
|
||||
console.log(` Total audit log entries created: ${count}`);
|
||||
console.log(" Actions covered: CREATED, ACCEPTED, LOCATION_CHANGED, ATTENDEE_ADDED,");
|
||||
console.log(" ATTENDEE_REMOVED, REASSIGNMENT (x2), NO_SHOW_UPDATED (x2), REJECTED,");
|
||||
console.log(" SEAT_BOOKED, SEAT_RESCHEDULED, CANCELLED, RESCHEDULE_REQUESTED, RESCHEDULED");
|
||||
console.log(" Actions covered: CREATED, ACCEPTED, RESCHEDULE_REQUESTED, RESCHEDULED,");
|
||||
console.log(" LOCATION_CHANGED, ATTENDEE_ADDED, ATTENDEE_REMOVED, REASSIGNMENT (x2),");
|
||||
console.log(" NO_SHOW_UPDATED (x2), CANCELLED, REJECTED, SEAT_BOOKED, SEAT_RESCHEDULED");
|
||||
console.log(" Actor types: USER, ATTENDEE, GUEST, SYSTEM, APP");
|
||||
console.log(" Sources: WEBAPP, API_V1, API_V2, WEBHOOK, MAGIC_LINK, SYSTEM");
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,91 +0,0 @@
|
||||
/**
|
||||
* Run this script quickly as `npx dotenv -e .env -- npx tsx scripts/seed-load-test-form-reponses.ts` from the root of the repo.
|
||||
*/
|
||||
import { prisma } from "@calcom/prisma";
|
||||
import type { App_RoutingForms_Form } from "@calcom/prisma/client";
|
||||
|
||||
async function createTestForm(): Promise<App_RoutingForms_Form> {
|
||||
const user = await prisma.user.findFirstOrThrow({
|
||||
where: { email: "[email protected]" },
|
||||
});
|
||||
if (!user) {
|
||||
throw new Error("[email protected] not found");
|
||||
}
|
||||
const testForm =
|
||||
(await prisma.app_RoutingForms_Form.findFirst({
|
||||
where: { name: "Load Test Form" },
|
||||
})) ||
|
||||
(await prisma.app_RoutingForms_Form.create({
|
||||
data: {
|
||||
name: "Load Test Form",
|
||||
userId: user.id,
|
||||
fields: [
|
||||
{
|
||||
id: "test-field-1",
|
||||
type: "text",
|
||||
label: "Test Field",
|
||||
required: true,
|
||||
},
|
||||
],
|
||||
routes: [
|
||||
{
|
||||
id: "test-route-1",
|
||||
action: { type: "customPageMessage", value: "Thank you" },
|
||||
isFallback: true,
|
||||
queryValue: { id: "test-route-1", type: "group" },
|
||||
},
|
||||
],
|
||||
},
|
||||
}));
|
||||
|
||||
return testForm;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a form in Acme's owner-1 account and creates 300,000 responses in it.
|
||||
*/
|
||||
async function createBulkResponsesAndExport(): Promise<void> {
|
||||
const testForm = await createTestForm();
|
||||
console.log(`Using form: ${testForm.id}`);
|
||||
|
||||
const TOTAL_RESPONSES = 300000;
|
||||
const BATCH_SIZE = 1000;
|
||||
const NUM_BATCHES = Math.ceil(TOTAL_RESPONSES / BATCH_SIZE);
|
||||
|
||||
for (let batch = 0; batch < NUM_BATCHES; batch++) {
|
||||
const batchStart = batch * BATCH_SIZE;
|
||||
const batchEnd = Math.min((batch + 1) * BATCH_SIZE, TOTAL_RESPONSES);
|
||||
const batchSize = batchEnd - batchStart;
|
||||
|
||||
console.log(`Creating batch ${batch + 1}/${NUM_BATCHES} (responses ${batchStart + 1}-${batchEnd})...`);
|
||||
|
||||
// Create responses in parallel within each batch
|
||||
const responsePromises = Array.from({ length: batchSize }, (_, i) => {
|
||||
const responseIndex = batchStart + i;
|
||||
return prisma.app_RoutingForms_FormResponse.create({
|
||||
data: {
|
||||
formFillerId: `load-test-filler-${responseIndex}`,
|
||||
formId: testForm.id,
|
||||
response: {
|
||||
"test-field-1": {
|
||||
label: "Test Field",
|
||||
value: `Response ${responseIndex}`,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
await Promise.all(responsePromises);
|
||||
|
||||
console.log(`✓ Batch ${batch + 1} completed (${batchEnd}/${TOTAL_RESPONSES} total)`);
|
||||
|
||||
await new Promise((resolve) => setTimeout(resolve, 100));
|
||||
}
|
||||
|
||||
console.log(`\n✓ Successfully created ${TOTAL_RESPONSES} responses`);
|
||||
}
|
||||
|
||||
createBulkResponsesAndExport()
|
||||
.catch(console.error)
|
||||
.finally(() => prisma.$disconnect());
|
||||
@@ -1,706 +0,0 @@
|
||||
import { uuid } from "short-uuid";
|
||||
|
||||
import type { FeatureId } from "@calcom/features/flags/config";
|
||||
import { FeaturesRepository } from "@calcom/features/flags/features.repository";
|
||||
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
|
||||
const featuresRepository = new FeaturesRepository(prisma);
|
||||
await featuresRepository.setTeamFeatureState({
|
||||
teamId: organization.id,
|
||||
featureId: "pbac" as FeatureId,
|
||||
state: "enabled",
|
||||
assignedBy: "system (Seed script)",
|
||||
});
|
||||
|
||||
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: [
|
||||
"[email protected]",
|
||||
"[email protected]",
|
||||
"[email protected]",
|
||||
"[email protected]",
|
||||
"[email protected]",
|
||||
],
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
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: "[email protected]",
|
||||
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: "[email protected]",
|
||||
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: "[email protected]",
|
||||
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: "[email protected]",
|
||||
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: "[email protected]",
|
||||
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 === "[email protected]") {
|
||||
customRoleId = "owner_role";
|
||||
} else if (user.email === "[email protected]") {
|
||||
customRoleId = customRoles.teamCoordinator.id;
|
||||
} else if (user.email === "[email protected]") {
|
||||
customRoleId = customRoles.eventManager.id;
|
||||
} else if (user.email === "[email protected]") {
|
||||
customRoleId = customRoles.analytics.id;
|
||||
} else if (user.email === "[email protected]") {
|
||||
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> = {
|
||||
"[email protected]": "pbac-owner-2024!",
|
||||
"[email protected]": "events-2024!",
|
||||
"[email protected]": "analytics-2024!",
|
||||
"[email protected]": "coordinator-2024!",
|
||||
"[email protected]": "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 === "[email protected]") {
|
||||
return [];
|
||||
}
|
||||
|
||||
// Map email to role and return permissions
|
||||
const rolePermissionMap: Record<string, Array<{ resource: string; action: string }>> = {
|
||||
"[email protected]": [
|
||||
{ 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" },
|
||||
],
|
||||
"[email protected]": [
|
||||
{ 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" },
|
||||
],
|
||||
"[email protected]": [
|
||||
{ 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" },
|
||||
],
|
||||
"[email protected]": [
|
||||
{ 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();
|
||||
});
|
||||
}
|
||||
+5
-370
@@ -1,8 +1,4 @@
|
||||
import { faker } from "@faker-js/faker";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { uuid } from "short-uuid";
|
||||
import type z from "zod";
|
||||
|
||||
import process from "node:process";
|
||||
import dayjs from "@calcom/dayjs";
|
||||
import { hashPassword } from "@calcom/lib/auth/hashPassword";
|
||||
import { DEFAULT_SCHEDULE, getAvailabilityFromSchedule } from "@calcom/lib/availability";
|
||||
@@ -10,6 +6,8 @@ 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";
|
||||
import { uuid } from "short-uuid";
|
||||
import type z from "zod";
|
||||
|
||||
export async function createUserAndEventType({
|
||||
user,
|
||||
@@ -46,7 +44,7 @@ export async function createUserAndEventType({
|
||||
completedOnboarding: user.completedOnboarding ?? true,
|
||||
locale: "en",
|
||||
schedules:
|
||||
user.completedOnboarding ?? true
|
||||
(user.completedOnboarding ?? true)
|
||||
? {
|
||||
create: {
|
||||
name: "Working Hours",
|
||||
@@ -199,7 +197,7 @@ type OAuthClientInput = {
|
||||
};
|
||||
|
||||
export async function createOAuthClientForUser(userId: number, oAuthClient: OAuthClientInput) {
|
||||
const {enablePkce, ...restOfOAuthClient} = oAuthClient;
|
||||
const { enablePkce, ...restOfOAuthClient } = oAuthClient;
|
||||
await prisma.oAuthClient.create({
|
||||
data: {
|
||||
userId,
|
||||
@@ -444,366 +442,3 @@ export async function seedAttributes(teamId: number) {
|
||||
}
|
||||
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`);
|
||||
}
|
||||
+9
-173
@@ -1,12 +1,12 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import process from "node:process";
|
||||
import dailyMeta from "@calcom/app-store/dailyvideo/_metadata";
|
||||
import googleMeetMeta from "@calcom/app-store/googlevideo/_metadata";
|
||||
import zoomMeta from "@calcom/app-store/zoomvideo/_metadata";
|
||||
import dayjs from "@calcom/dayjs";
|
||||
import { hashAPIKey } from "@calcom/ee/api-keys/lib/apiKeys";
|
||||
import { getOrgFullOrigin } from "@calcom/ee/organizations/lib/orgDomains";
|
||||
import { hashPassword } from "@calcom/lib/auth/hashPassword";
|
||||
import { DEFAULT_SCHEDULE, getAvailabilityFromSchedule } from "@calcom/lib/availability";
|
||||
import { WEBAPP_URL } from "@calcom/lib/constants";
|
||||
import { prisma } from "@calcom/prisma";
|
||||
import type { Membership, Team, User, UserPermissionRole } from "@calcom/prisma/client";
|
||||
import { Prisma } from "@calcom/prisma/client";
|
||||
@@ -19,6 +19,10 @@ import mainAppStore from "./seed-app-store";
|
||||
import mainHugeEventTypesSeed from "./seed-huge-event-types";
|
||||
import { createOAuthClientForUser, createUserAndEventType } from "./seed-utils";
|
||||
|
||||
function hashAPIKey(apiKey: string): string {
|
||||
return createHash("sha256").update(apiKey).digest("hex");
|
||||
}
|
||||
|
||||
type PlatformUser = {
|
||||
email: string;
|
||||
password: string;
|
||||
@@ -389,13 +393,13 @@ async function createOrganizationAndAddMembersAndTeams({
|
||||
},
|
||||
},
|
||||
update: {
|
||||
toUrl: `${getOrgFullOrigin(orgData.slug)}/${member.orgProfile.username}`,
|
||||
toUrl: `${WEBAPP_URL}/${member.orgProfile.username}`,
|
||||
},
|
||||
create: {
|
||||
fromOrgId: 0,
|
||||
type: RedirectType.User,
|
||||
from: member.memberData.username,
|
||||
toUrl: `${getOrgFullOrigin(orgData.slug)}/${member.orgProfile.username}`,
|
||||
toUrl: `${WEBAPP_URL}/${member.orgProfile.username}`,
|
||||
},
|
||||
});
|
||||
|
||||
@@ -1585,175 +1589,7 @@ async function main() {
|
||||
],
|
||||
});
|
||||
|
||||
const seededForm = {
|
||||
id: "948ae412-d995-4865-875a-48302588de03",
|
||||
name: "Seeded Form - Pro",
|
||||
};
|
||||
|
||||
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`);
|
||||
} else {
|
||||
const proUser = await prisma.user.findFirst({
|
||||
where: {
|
||||
username: "pro",
|
||||
},
|
||||
});
|
||||
|
||||
if (!proUser) {
|
||||
console.log(`Skipping Routing Form - Seeding - Pro User not found`);
|
||||
} else {
|
||||
const multiSelectLegacyFieldId = "d2292635-9f12-17b1-9153-c3a854649182";
|
||||
await prisma.app_RoutingForms_Form.create({
|
||||
data: {
|
||||
id: seededForm.id,
|
||||
routes: [
|
||||
{
|
||||
id: "8a898988-89ab-4cde-b012-31823f708642",
|
||||
action: { type: "eventTypeRedirectUrl", value: "pro/30min" },
|
||||
queryValue: {
|
||||
id: "8a898988-89ab-4cde-b012-31823f708642",
|
||||
type: "group",
|
||||
children1: {
|
||||
"8988bbb8-0123-4456-b89a-b1823f70c5ff": {
|
||||
type: "rule",
|
||||
properties: {
|
||||
field: "c1296635-9f12-47b1-8153-c3a854649182",
|
||||
value: ["event-routing"],
|
||||
operator: "equal",
|
||||
valueSrc: ["value"],
|
||||
valueType: ["text"],
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "aa8aaba9-cdef-4012-b456-71823f70f7ef",
|
||||
action: {
|
||||
type: "customPageMessage",
|
||||
value: "Custom Page Result",
|
||||
},
|
||||
queryValue: {
|
||||
id: "aa8aaba9-cdef-4012-b456-71823f70f7ef",
|
||||
type: "group",
|
||||
children1: {
|
||||
"b99b8a89-89ab-4cde-b012-31823f718ff5": {
|
||||
type: "rule",
|
||||
properties: {
|
||||
field: "c1296635-9f12-47b1-8153-c3a854649182",
|
||||
value: ["custom-page"],
|
||||
operator: "equal",
|
||||
valueSrc: ["value"],
|
||||
valueType: ["text"],
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "a8ba9aab-4567-489a-bcde-f1823f71b4ad",
|
||||
action: { type: "externalRedirectUrl", value: "https://cal.com" },
|
||||
queryValue: {
|
||||
id: "a8ba9aab-4567-489a-bcde-f1823f71b4ad",
|
||||
type: "group",
|
||||
children1: {
|
||||
"998b9b9a-0123-4456-b89a-b1823f7232b9": {
|
||||
type: "rule",
|
||||
properties: {
|
||||
field: "c1296635-9f12-47b1-8153-c3a854649182",
|
||||
value: ["external-redirect"],
|
||||
operator: "equal",
|
||||
valueSrc: ["value"],
|
||||
valueType: ["text"],
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "aa8ba8b9-0123-4456-b89a-b182623406d8",
|
||||
action: {
|
||||
type: "customPageMessage",
|
||||
value: "Multiselect chosen",
|
||||
},
|
||||
queryValue: {
|
||||
id: "aa8ba8b9-0123-4456-b89a-b182623406d8",
|
||||
type: "group",
|
||||
children1: {
|
||||
"b98a8abb-cdef-4012-b456-718262343d27": {
|
||||
type: "rule",
|
||||
properties: {
|
||||
field: multiSelectLegacyFieldId,
|
||||
value: [["Option-2"]],
|
||||
operator: "multiselect_equals",
|
||||
valueSrc: ["value"],
|
||||
valueType: ["multiselect"],
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "898899aa-4567-489a-bcde-f1823f708646",
|
||||
action: { type: "customPageMessage", value: "Fallback Message" },
|
||||
isFallback: true,
|
||||
queryValue: {
|
||||
id: "898899aa-4567-489a-bcde-f1823f708646",
|
||||
type: "group",
|
||||
},
|
||||
},
|
||||
],
|
||||
fields: [
|
||||
{
|
||||
id: "c1296635-9f12-47b1-8153-c3a854649182",
|
||||
type: "text",
|
||||
label: "Test field",
|
||||
required: true,
|
||||
},
|
||||
{
|
||||
id: multiSelectLegacyFieldId,
|
||||
type: "multiselect",
|
||||
label: "Multi Select(with legacy `selectText`)",
|
||||
identifier: "multi",
|
||||
selectText: "Option-1\nOption-2",
|
||||
required: false,
|
||||
},
|
||||
{
|
||||
id: "d3292635-9f12-17b1-9153-c3a854649182",
|
||||
type: "multiselect",
|
||||
label: "Multi Select",
|
||||
identifier: "multi",
|
||||
options: [
|
||||
{
|
||||
id: "d1234635-9f12-17b1-9153-c3a854649182",
|
||||
label: "Option-1",
|
||||
},
|
||||
{
|
||||
id: "d1235635-9f12-17b1-9153-c3a854649182",
|
||||
label: "Option-2",
|
||||
},
|
||||
],
|
||||
required: false,
|
||||
},
|
||||
],
|
||||
user: {
|
||||
connect: {
|
||||
email_username: {
|
||||
username: "pro",
|
||||
email: "[email protected]",
|
||||
},
|
||||
},
|
||||
},
|
||||
name: seededForm.name,
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
// Routing forms feature removed - routing form seeding no longer needed
|
||||
|
||||
await ensureAcmeOwnerHasApiKeySeeded();
|
||||
await seedPerHostLocationsInAcmeOrg();
|
||||
|
||||
Reference in new issue
Block a user