refactor: remove @calcom/features dependency from @calcom/prisma (#23820)
This commit is contained in:
1 parent
f41aa234d7
commit
4011733271
30 files changed
+239
-241
No files matched your search
@@ -16,6 +16,7 @@ import createUsersAndConnectToOrg from "@calcom/features/ee/dsync/lib/users/crea
|
||||
import ImpersonationProvider from "@calcom/features/ee/impersonation/lib/ImpersonationProvider";
|
||||
import { getOrgFullOrigin, subdomainSuffix } from "@calcom/features/ee/organizations/lib/orgDomains";
|
||||
import { clientSecretVerifier, hostedCal, isSAMLLoginEnabled } from "@calcom/features/ee/sso/lib/saml";
|
||||
import { isPasswordValid } from "@calcom/lib/auth/isPasswordValid";
|
||||
import { checkRateLimitAndThrowError } from "@calcom/lib/checkRateLimitAndThrowError";
|
||||
import {
|
||||
GOOGLE_CALENDAR_SCOPES,
|
||||
@@ -46,7 +47,6 @@ import { teamMetadataSchema, userMetadata } from "@calcom/prisma/zod-utils";
|
||||
import { getOrgUsernameFromEmail } from "../signup/utils/getOrgUsernameFromEmail";
|
||||
import { ErrorCode } from "./ErrorCode";
|
||||
import { dub } from "./dub";
|
||||
import { isPasswordValid } from "./isPasswordValid";
|
||||
import CalComAdapter from "./next-auth-custom-adapter";
|
||||
import { verifyPassword } from "./verifyPassword";
|
||||
|
||||
|
||||
@@ -2,12 +2,12 @@ import { cookies, headers } from "next/headers";
|
||||
import { NextResponse } from "next/server";
|
||||
|
||||
import { getPremiumMonthlyPlanPriceId } from "@calcom/app-store/stripepayment/lib/utils";
|
||||
import { hashPassword } from "@calcom/features/auth/lib/hashPassword";
|
||||
import { sendEmailVerification } from "@calcom/features/auth/lib/verifyEmail";
|
||||
import { createOrUpdateMemberships } from "@calcom/features/auth/signup/utils/createOrUpdateMemberships";
|
||||
import { prefillAvatar } from "@calcom/features/auth/signup/utils/prefillAvatar";
|
||||
import { StripeBillingService } from "@calcom/features/ee/billing/stripe-billling-service";
|
||||
import { checkIfEmailIsBlockedInWatchlistController } from "@calcom/features/watchlist/operations/check-if-email-in-watchlist.controller";
|
||||
import { hashPassword } from "@calcom/lib/auth/hashPassword";
|
||||
import { WEBAPP_URL } from "@calcom/lib/constants";
|
||||
import { getLocaleFromRequest } from "@calcom/lib/getLocaleFromRequest";
|
||||
import { HttpError } from "@calcom/lib/http-error";
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import { NextResponse } from "next/server";
|
||||
|
||||
import { checkPremiumUsername } from "@calcom/ee/common/lib/checkPremiumUsername";
|
||||
import { hashPassword } from "@calcom/features/auth/lib/hashPassword";
|
||||
import { sendEmailVerification } from "@calcom/features/auth/lib/verifyEmail";
|
||||
import { createOrUpdateMemberships } from "@calcom/features/auth/signup/utils/createOrUpdateMemberships";
|
||||
import { hashPassword } from "@calcom/lib/auth/hashPassword";
|
||||
import { IS_PREMIUM_USERNAME_ENABLED } from "@calcom/lib/constants";
|
||||
import logger from "@calcom/lib/logger";
|
||||
import { isUsernameReservedDueToMigration } from "@calcom/lib/server/username";
|
||||
|
||||
@@ -3,6 +3,7 @@ import type { Dispatch, SetStateAction } from "react";
|
||||
import { Controller, useFormContext } from "react-hook-form";
|
||||
import type { z } from "zod";
|
||||
|
||||
import { getPaymentAppData } from "@calcom/app-store/_utils/payments/getPaymentAppData";
|
||||
import { useAtomsContext } from "@calcom/atoms/hooks/useAtomsContext";
|
||||
import { useIsPlatform } from "@calcom/atoms/hooks/useIsPlatform";
|
||||
import {
|
||||
@@ -31,8 +32,6 @@ import type {
|
||||
SettingsToggleClassNames,
|
||||
} from "@calcom/features/eventtypes/lib/types";
|
||||
import { FormBuilder } from "@calcom/features/form-builder/FormBuilder";
|
||||
import type { fieldSchema } from "@calcom/features/form-builder/schema";
|
||||
import type { EditableSchema } from "@calcom/features/form-builder/schema";
|
||||
import { BookerLayoutSelector } from "@calcom/features/settings/BookerLayoutSelector";
|
||||
import {
|
||||
DEFAULT_LIGHT_BRAND_COLOR,
|
||||
@@ -42,11 +41,12 @@ import {
|
||||
} from "@calcom/lib/constants";
|
||||
import { generateHashedLink } from "@calcom/lib/generateHashedLink";
|
||||
import { checkWCAGContrastColor } from "@calcom/lib/getBrandColours";
|
||||
import { getPaymentAppData } from "@calcom/app-store/_utils/payments/getPaymentAppData";
|
||||
import { extractHostTimezone } from "@calcom/lib/hashedLinksUtils";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import type { Prisma } from "@calcom/prisma/client";
|
||||
import { SchedulingType } from "@calcom/prisma/enums";
|
||||
import type { EditableSchema } from "@calcom/prisma/zod-utils";
|
||||
import type { fieldSchema } from "@calcom/prisma/zod-utils";
|
||||
import type { RouterOutputs } from "@calcom/trpc/react";
|
||||
import classNames from "@calcom/ui/classNames";
|
||||
import { Alert } from "@calcom/ui/components/alert";
|
||||
|
||||
@@ -8,6 +8,7 @@ import type {
|
||||
import Widgets from "@calcom/app-store/routing-forms/components/react-awesome-query-builder/widgets";
|
||||
import PhoneInput from "@calcom/features/components/phone-input";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import type { fieldSchema, variantsConfigSchema, FieldType } from "@calcom/prisma/zod-utils";
|
||||
import { AddressInput } from "@calcom/ui/components/address";
|
||||
import { InfoBadge } from "@calcom/ui/components/badge";
|
||||
import { Button } from "@calcom/ui/components/button";
|
||||
@@ -18,7 +19,6 @@ import { Tooltip } from "@calcom/ui/components/tooltip";
|
||||
|
||||
import { ComponentForField } from "./FormBuilderField";
|
||||
import { propsTypes } from "./propsTypes";
|
||||
import type { fieldSchema, FieldType, variantsConfigSchema } from "./schema";
|
||||
import { preprocessNameFieldDataWithVariant } from "./utils";
|
||||
|
||||
export const isValidValueProp: Record<Component["propsType"], (val: unknown) => boolean> = {
|
||||
|
||||
@@ -11,6 +11,7 @@ import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { md } from "@calcom/lib/markdownIt";
|
||||
import { markdownToSafeHTMLClient } from "@calcom/lib/markdownToSafeHTMLClient";
|
||||
import turndown from "@calcom/lib/turndownService";
|
||||
import { excludeOrRequireEmailSchema } from "@calcom/prisma/zod-utils";
|
||||
import classNames from "@calcom/ui/classNames";
|
||||
import { Badge } from "@calcom/ui/components/badge";
|
||||
import { Button } from "@calcom/ui/components/button";
|
||||
@@ -31,7 +32,7 @@ import { showToast } from "@calcom/ui/components/toast";
|
||||
|
||||
import { fieldTypesConfigMap } from "./fieldTypes";
|
||||
import { fieldsThatSupportLabelAsSafeHtml } from "./fieldsThatSupportLabelAsSafeHtml";
|
||||
import { type fieldsSchema, excludeOrRequireEmailSchema } from "./schema";
|
||||
import type { fieldsSchema } from "./schema";
|
||||
import { getFieldIdentifier } from "./utils/getFieldIdentifier";
|
||||
import { getConfig as getVariantsConfig } from "./utils/variantsConfig";
|
||||
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
import type z from "zod";
|
||||
|
||||
import type { FieldType } from "@calcom/prisma/zod-utils";
|
||||
|
||||
import { propsTypes } from "./propsTypes";
|
||||
import type { FieldType, fieldTypeConfigSchema } from "./schema";
|
||||
import type { fieldTypeConfigSchema } from "./schema";
|
||||
|
||||
const configMap: Record<FieldType, Omit<z.infer<typeof fieldTypeConfigSchema>, "propsType">> = {
|
||||
// This won't be stored in DB. It allows UI to be configured from the codebase for all existing booking fields stored in DB as well
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { FieldType } from "./schema";
|
||||
import type { FieldType } from "@calcom/prisma/zod-utils";
|
||||
|
||||
/**
|
||||
* Once a component supports `labelAsSafeHtml`, add it's field's type here
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import { getValidRhfFieldName } from "@calcom/lib/getValidRhfFieldName";
|
||||
import { fieldSchema, fieldTypeEnum, variantsConfigSchema, type FieldType } from "@calcom/prisma/zod-utils";
|
||||
|
||||
import { fieldTypesConfigMap } from "./fieldTypes";
|
||||
import { preprocessNameFieldDataWithVariant } from "./utils";
|
||||
@@ -8,154 +8,6 @@ import { getConfig as getVariantsConfig } from "./utils/variantsConfig";
|
||||
|
||||
const nonEmptyString = () => z.string().refine((value: string) => value.trim().length > 0);
|
||||
|
||||
const fieldTypeEnum = z.enum([
|
||||
"name",
|
||||
"text",
|
||||
"textarea",
|
||||
"number",
|
||||
"email",
|
||||
"phone",
|
||||
"address",
|
||||
"multiemail",
|
||||
"select",
|
||||
"multiselect",
|
||||
"checkbox",
|
||||
"radio",
|
||||
"radioInput",
|
||||
"boolean",
|
||||
"url",
|
||||
]);
|
||||
|
||||
export type FieldType = z.infer<typeof fieldTypeEnum>;
|
||||
|
||||
export const EditableSchema = z.enum([
|
||||
"system", // Can't be deleted, can't be hidden, name can't be edited, can't be marked optional
|
||||
"system-but-optional", // Can't be deleted. Name can't be edited. But can be hidden or be marked optional
|
||||
"system-but-hidden", // Can't be deleted, name can't be edited, will be shown
|
||||
"user", // Fully editable
|
||||
"user-readonly", // All fields are readOnly.
|
||||
]);
|
||||
|
||||
export const excludeOrRequireEmailSchema = z.string().superRefine((val, ctx) => {
|
||||
const allDomains = val.split(",").map((dom) => dom.trim());
|
||||
|
||||
const regex = /^(?:@?[a-z0-9-]+(?:\.[a-z]{2,})?)?(?:@[a-z0-9-]+\.[a-z]{2,})?$/;
|
||||
|
||||
/*
|
||||
Valid patterns - [ example, example.anything, [email protected] ]
|
||||
Invalid patterns - Patterns involving capital letter [ Example, Example.anything, [email protected] ]
|
||||
*/
|
||||
|
||||
const isValid = !allDomains.some((domain) => !regex.test(domain));
|
||||
|
||||
if (!isValid) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
message: "Enter valid domain or email",
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
const baseFieldSchema = z.object({
|
||||
name: z.string().transform(getValidRhfFieldName),
|
||||
type: fieldTypeEnum,
|
||||
// TODO: We should make at least one of `defaultPlaceholder` and `placeholder` required. Do the same for label.
|
||||
label: z.string().optional(),
|
||||
labelAsSafeHtml: z.string().optional(),
|
||||
|
||||
/**
|
||||
* It is the default label that will be used when a new field is created.
|
||||
* Note: It belongs in FieldsTypeConfig, so that changing defaultLabel in code can work for existing fields as well(for fields that are using the default label).
|
||||
* Supports translation
|
||||
*/
|
||||
defaultLabel: z.string().optional(),
|
||||
|
||||
placeholder: z.string().optional(),
|
||||
/**
|
||||
* It is the default placeholder that will be used when a new field is created.
|
||||
* Note: Same as defaultLabel, it belongs in FieldsTypeConfig
|
||||
* Supports translation
|
||||
*/
|
||||
defaultPlaceholder: z.string().optional(),
|
||||
required: z.boolean().default(false).optional(),
|
||||
/**
|
||||
* It is the list of options that is valid for a certain type of fields.
|
||||
*
|
||||
*/
|
||||
options: z
|
||||
.array(
|
||||
z.object({
|
||||
label: z.string(),
|
||||
value: z.string(),
|
||||
price: z.coerce.number().min(0).optional(),
|
||||
})
|
||||
)
|
||||
.optional(),
|
||||
/**
|
||||
* This is an alternate way to specify options when the options are stored elsewhere. Form Builder expects options to be present at `dataStore[getOptionsAt]`
|
||||
* This allows keeping a single source of truth in DB.
|
||||
*/
|
||||
getOptionsAt: z.string().optional(),
|
||||
|
||||
/**
|
||||
* For `radioInput` type of questions, it stores the input that is shown based on the user option selected.
|
||||
* e.g. If user is given a list of locations and he selects "Phone", then he will be shown a phone input
|
||||
*/
|
||||
optionsInputs: z
|
||||
.record(
|
||||
z.object({
|
||||
// Support all types as needed
|
||||
// Must be a subset of `fieldTypeEnum`.TODO: Enforce it in TypeScript
|
||||
type: z.enum(["address", "phone", "text"]),
|
||||
required: z.boolean().optional(),
|
||||
placeholder: z.string().optional(),
|
||||
})
|
||||
)
|
||||
.optional(),
|
||||
|
||||
/**
|
||||
* It is the minimum number of characters that can be entered in the field.
|
||||
* It is used for types with `supportsLengthCheck= true`.
|
||||
* @default 0
|
||||
* @requires supportsLengthCheck = true
|
||||
*/
|
||||
minLength: z.number().optional(),
|
||||
|
||||
/**
|
||||
* It is the maximum number of characters that can be entered in the field.
|
||||
* It is used for types with `supportsLengthCheck= true`.
|
||||
* @requires supportsLengthCheck = true
|
||||
*/
|
||||
maxLength: z.number().optional(),
|
||||
|
||||
// Emails that needs to be excluded
|
||||
excludeEmails: excludeOrRequireEmailSchema.optional(),
|
||||
// Emails that need to be required
|
||||
requireEmails: excludeOrRequireEmailSchema.optional(),
|
||||
// Price associated with the field which works like addons which users can add to the booking
|
||||
price: z.coerce.number().min(0).optional(),
|
||||
});
|
||||
|
||||
export const variantsConfigSchema = z.object({
|
||||
variants: z.record(
|
||||
z.object({
|
||||
/**
|
||||
* Variant Fields schema for a variant of the main field.
|
||||
* It doesn't support non text fields as of now
|
||||
**/
|
||||
fields: baseFieldSchema
|
||||
.omit({
|
||||
defaultLabel: true,
|
||||
defaultPlaceholder: true,
|
||||
options: true,
|
||||
getOptionsAt: true,
|
||||
optionsInputs: true,
|
||||
})
|
||||
.array(),
|
||||
})
|
||||
),
|
||||
});
|
||||
|
||||
export type ALL_VIEWS = "ALL_VIEWS";
|
||||
|
||||
// It is the config that is specific to a type and doesn't make sense in all fields individually. Any field with the type will automatically inherit this config.
|
||||
@@ -238,47 +90,6 @@ export const fieldTypeConfigSchema = z
|
||||
return true;
|
||||
});
|
||||
|
||||
/**
|
||||
* Main field Schema
|
||||
*/
|
||||
export const fieldSchema = baseFieldSchema.merge(
|
||||
z.object({
|
||||
variant: z.string().optional(),
|
||||
variantsConfig: variantsConfigSchema.optional(),
|
||||
|
||||
views: z
|
||||
.object({
|
||||
label: z.string(),
|
||||
id: z.string(),
|
||||
description: z.string().optional(),
|
||||
})
|
||||
.array()
|
||||
.optional(),
|
||||
|
||||
/**
|
||||
* It is used to hide fields such as location when there are less than two options
|
||||
*/
|
||||
hideWhenJustOneOption: z.boolean().default(false).optional(),
|
||||
|
||||
hidden: z.boolean().optional(),
|
||||
editable: EditableSchema.default("user").optional(),
|
||||
sources: z
|
||||
.array(
|
||||
z.object({
|
||||
// Unique ID for the `type`. If type is workflow, it's the workflow ID
|
||||
id: z.string(),
|
||||
type: z.union([z.literal("user"), z.literal("system"), z.string()]),
|
||||
label: z.string(),
|
||||
editUrl: z.string().optional(),
|
||||
// Mark if a field is required by this source or not. This allows us to set `field.required` based on all the sources' fieldRequired value
|
||||
fieldRequired: z.boolean().optional(),
|
||||
})
|
||||
)
|
||||
.optional(),
|
||||
disableOnPrefill: z.boolean().default(false).optional(),
|
||||
})
|
||||
);
|
||||
|
||||
export const fieldsSchema = z.array(fieldSchema);
|
||||
|
||||
export const fieldTypesSchemaMap: Partial<
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import type z from "zod";
|
||||
|
||||
import type { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import type { fieldSchema } from "@calcom/prisma/zod-utils";
|
||||
|
||||
import { fieldTypesConfigMap } from "../fieldTypes";
|
||||
import type { fieldSchema } from "../schema";
|
||||
|
||||
type ConfigVariants = NonNullable<ReturnType<typeof getConfig>>["variants"];
|
||||
type Field = z.infer<typeof fieldSchema>;
|
||||
|
||||
File renamed without changes.
File renamed without changes.
@@ -2,8 +2,8 @@ import prismock from "../../../../tests/libs/__mocks__/prisma";
|
||||
|
||||
import { describe, test, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
import { hashPassword } from "@calcom/features/auth/lib/hashPassword";
|
||||
import { checkIfEmailIsBlockedInWatchlistController } from "@calcom/features/watchlist/operations/check-if-email-in-watchlist.controller";
|
||||
import { hashPassword } from "@calcom/lib/auth/hashPassword";
|
||||
import { CreationSource } from "@calcom/prisma/enums";
|
||||
|
||||
import { UserRepository } from "../repository/user";
|
||||
@@ -20,7 +20,7 @@ vi.mock("@calcom/lib/server/i18n", () => {
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("@calcom/features/auth/lib/hashPassword", () => ({
|
||||
vi.mock("@calcom/lib/auth/hashPassword", () => ({
|
||||
hashPassword: vi.fn().mockResolvedValue("hashed-password"),
|
||||
}));
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { hashPassword } from "@calcom/features/auth/lib/hashPassword";
|
||||
import { checkIfEmailIsBlockedInWatchlistController } from "@calcom/features/watchlist/operations/check-if-email-in-watchlist.controller";
|
||||
import { hashPassword } from "@calcom/lib/auth/hashPassword";
|
||||
import logger from "@calcom/lib/logger";
|
||||
import prisma from "@calcom/prisma";
|
||||
import type { CreationSource, UserPermissionRole, IdentityProvider } from "@calcom/prisma/enums";
|
||||
|
||||
@@ -18,11 +18,10 @@
|
||||
"post-install": "yarn generate-schemas",
|
||||
"seed-app-store": "ts-node --transpile-only ../../scripts/seed-app-store.ts",
|
||||
"delete-app": "ts-node --transpile-only ./delete-app.ts",
|
||||
"seed-insights": "ts-node --transpile-only ./seed-insights.ts",
|
||||
"seed-pbac": "ts-node --transpile-only ./seed-pbac-organization.ts"
|
||||
"seed-insights": "ts-node --transpile-only ../../scripts/seed-insights.ts",
|
||||
"seed-pbac": "ts-node --transpile-only ../../scripts/seed-pbac-organization.ts"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@faker-js/faker": "9.2.0",
|
||||
"npm-run-all": "^4.1.5"
|
||||
},
|
||||
"dependencies": {
|
||||
@@ -46,4 +45,4 @@
|
||||
"prisma": {
|
||||
"seed": "ts-node --transpile-only ../../scripts/seed.ts"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,91 +0,0 @@
|
||||
/**
|
||||
* 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: `[email protected]`,
|
||||
name: "Enterprise Owner",
|
||||
password: "enterprise",
|
||||
username: `enterprise`,
|
||||
theme: "light",
|
||||
},
|
||||
eventTypes: getEventTypes(100),
|
||||
});
|
||||
await createTeamsWithEventTypes({ owner, numberOfTeams: 10, numberOfEventTypes: 100 });
|
||||
}
|
||||
@@ -1,543 +0,0 @@
|
||||
import { faker } from "@faker-js/faker";
|
||||
import { v4 as uuidv4 } from "uuid";
|
||||
|
||||
import dayjs from "@calcom/dayjs";
|
||||
import { hashPassword } from "@calcom/features/auth/lib/hashPassword";
|
||||
import { BookingStatus, AssignmentReasonEnum } from "@calcom/prisma/enums";
|
||||
|
||||
import type { Prisma } from "./client";
|
||||
import { PrismaClient } from "./client";
|
||||
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", "[email protected]"],
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
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);
|
||||
});
|
||||
@@ -1,706 +0,0 @@
|
||||
import { uuid } from "short-uuid";
|
||||
|
||||
import { hashPassword } from "@calcom/features/auth/lib/hashPassword";
|
||||
import { DEFAULT_SCHEDULE, getAvailabilityFromSchedule } from "@calcom/lib/availability";
|
||||
import { MembershipRole, RoleType } from "@calcom/prisma/enums";
|
||||
|
||||
import prisma from ".";
|
||||
|
||||
/**
|
||||
* 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: [
|
||||
"[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();
|
||||
});
|
||||
}
|
||||
@@ -1,788 +0,0 @@
|
||||
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/features/auth/lib/hashPassword";
|
||||
import { DEFAULT_SCHEDULE, getAvailabilityFromSchedule } from "@calcom/lib/availability";
|
||||
import { MembershipRole } from "@calcom/prisma/enums";
|
||||
|
||||
import prisma from ".";
|
||||
import type { Prisma, UserPermissionRole } from "./client";
|
||||
import type { teamMetadataSchema } from "./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`);
|
||||
}
|
||||
@@ -11,10 +11,9 @@ import type {
|
||||
ZodTypeAny,
|
||||
} from "zod";
|
||||
|
||||
import { isPasswordValid } from "@calcom/features/auth/lib/isPasswordValid";
|
||||
import type { FieldType as FormBuilderFieldType } from "@calcom/features/form-builder/schema";
|
||||
import { fieldsSchema as formBuilderFieldsSchema } from "@calcom/features/form-builder/schema";
|
||||
import { isPasswordValid } from "@calcom/lib/auth/isPasswordValid";
|
||||
import { emailSchema as emailRegexSchema, emailRegex } from "@calcom/lib/emailSchema";
|
||||
import { getValidRhfFieldName } from "@calcom/lib/getValidRhfFieldName";
|
||||
import type { IntervalLimit } from "@calcom/lib/intervalLimits/intervalLimitSchema";
|
||||
import { zodAttributesQueryValue } from "@calcom/lib/raqb/zod";
|
||||
import { slugify } from "@calcom/lib/slugify";
|
||||
@@ -135,10 +134,6 @@ export const eventTypeMetaDataSchemaWithoutApps = _eventTypeMetaDataSchemaWithou
|
||||
|
||||
export type EventTypeMetadata = z.infer<typeof EventTypeMetaDataSchema>;
|
||||
|
||||
export const eventTypeBookingFields = formBuilderFieldsSchema;
|
||||
export const BookingFieldTypeEnum = eventTypeBookingFields.element.shape.type.Enum;
|
||||
export type BookingFieldType = FormBuilderFieldType;
|
||||
|
||||
// Validation of user added bookingFields' responses happen using `getBookingResponsesSchema` which requires `eventType`.
|
||||
// So it is a dynamic validation and thus entire validation can't exist here
|
||||
// Note that this validation runs to validate prefill params as well, so it should consider that partial values can be there. e.g. `name` might be empty string
|
||||
@@ -768,3 +763,193 @@ export const serviceAccountKeySchema = z
|
||||
export type TServiceAccountKeySchema = z.infer<typeof serviceAccountKeySchema>;
|
||||
|
||||
export const rrSegmentQueryValueSchema = zodAttributesQueryValue.nullish();
|
||||
|
||||
// Routing Form Fields
|
||||
export const fieldTypeEnum = z.enum([
|
||||
"name",
|
||||
"text",
|
||||
"textarea",
|
||||
"number",
|
||||
"email",
|
||||
"phone",
|
||||
"address",
|
||||
"multiemail",
|
||||
"select",
|
||||
"multiselect",
|
||||
"checkbox",
|
||||
"radio",
|
||||
"radioInput",
|
||||
"boolean",
|
||||
"url",
|
||||
]);
|
||||
|
||||
export type FieldType = z.infer<typeof fieldTypeEnum>;
|
||||
|
||||
export const excludeOrRequireEmailSchema = z.string().superRefine((val, ctx) => {
|
||||
const allDomains = val.split(",").map((dom) => dom.trim());
|
||||
|
||||
const regex = /^(?:@?[a-z0-9-]+(?:\.[a-z]{2,})?)?(?:@[a-z0-9-]+\.[a-z]{2,})?$/;
|
||||
|
||||
/*
|
||||
Valid patterns - [ example, example.anything, [email protected] ]
|
||||
Invalid patterns - Patterns involving capital letter [ Example, Example.anything, [email protected] ]
|
||||
*/
|
||||
|
||||
const isValid = !allDomains.some((domain) => !regex.test(domain));
|
||||
|
||||
if (!isValid) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
message: "Enter valid domain or email",
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
export const EditableSchema = z.enum([
|
||||
"system", // Can't be deleted, can't be hidden, name can't be edited, can't be marked optional
|
||||
"system-but-optional", // Can't be deleted. Name can't be edited. But can be hidden or be marked optional
|
||||
"system-but-hidden", // Can't be deleted, name can't be edited, will be shown
|
||||
"user", // Fully editable
|
||||
"user-readonly", // All fields are readOnly.
|
||||
]);
|
||||
|
||||
export const baseFieldSchema = z.object({
|
||||
name: z.string().transform(getValidRhfFieldName),
|
||||
type: fieldTypeEnum,
|
||||
// TODO: We should make at least one of `defaultPlaceholder` and `placeholder` required. Do the same for label.
|
||||
label: z.string().optional(),
|
||||
labelAsSafeHtml: z.string().optional(),
|
||||
|
||||
/**
|
||||
* It is the default label that will be used when a new field is created.
|
||||
* Note: It belongs in FieldsTypeConfig, so that changing defaultLabel in code can work for existing fields as well(for fields that are using the default label).
|
||||
* Supports translation
|
||||
*/
|
||||
defaultLabel: z.string().optional(),
|
||||
|
||||
placeholder: z.string().optional(),
|
||||
/**
|
||||
* It is the default placeholder that will be used when a new field is created.
|
||||
* Note: Same as defaultLabel, it belongs in FieldsTypeConfig
|
||||
* Supports translation
|
||||
*/
|
||||
defaultPlaceholder: z.string().optional(),
|
||||
required: z.boolean().default(false).optional(),
|
||||
/**
|
||||
* It is the list of options that is valid for a certain type of fields.
|
||||
*
|
||||
*/
|
||||
options: z
|
||||
.array(
|
||||
z.object({
|
||||
label: z.string(),
|
||||
value: z.string(),
|
||||
price: z.coerce.number().min(0).optional(),
|
||||
})
|
||||
)
|
||||
.optional(),
|
||||
/**
|
||||
* This is an alternate way to specify options when the options are stored elsewhere. Form Builder expects options to be present at `dataStore[getOptionsAt]`
|
||||
* This allows keeping a single source of truth in DB.
|
||||
*/
|
||||
getOptionsAt: z.string().optional(),
|
||||
|
||||
/**
|
||||
* For `radioInput` type of questions, it stores the input that is shown based on the user option selected.
|
||||
* e.g. If user is given a list of locations and he selects "Phone", then he will be shown a phone input
|
||||
*/
|
||||
optionsInputs: z
|
||||
.record(
|
||||
z.object({
|
||||
// Support all types as needed
|
||||
// Must be a subset of `fieldTypeEnum`.TODO: Enforce it in TypeScript
|
||||
type: z.enum(["address", "phone", "text"]),
|
||||
required: z.boolean().optional(),
|
||||
placeholder: z.string().optional(),
|
||||
})
|
||||
)
|
||||
.optional(),
|
||||
|
||||
/**
|
||||
* It is the minimum number of characters that can be entered in the field.
|
||||
* It is used for types with `supportsLengthCheck= true`.
|
||||
* @default 0
|
||||
* @requires supportsLengthCheck = true
|
||||
*/
|
||||
minLength: z.number().optional(),
|
||||
|
||||
/**
|
||||
* It is the maximum number of characters that can be entered in the field.
|
||||
* It is used for types with `supportsLengthCheck= true`.
|
||||
* @requires supportsLengthCheck = true
|
||||
*/
|
||||
maxLength: z.number().optional(),
|
||||
|
||||
// Emails that needs to be excluded
|
||||
excludeEmails: excludeOrRequireEmailSchema.optional(),
|
||||
// Emails that need to be required
|
||||
requireEmails: excludeOrRequireEmailSchema.optional(),
|
||||
// Price associated with the field which works like addons which users can add to the booking
|
||||
price: z.coerce.number().min(0).optional(),
|
||||
});
|
||||
|
||||
export const variantsConfigSchema = z.object({
|
||||
variants: z.record(
|
||||
z.object({
|
||||
/**
|
||||
* Variant Fields schema for a variant of the main field.
|
||||
* It doesn't support non text fields as of now
|
||||
**/
|
||||
fields: baseFieldSchema
|
||||
.omit({
|
||||
defaultLabel: true,
|
||||
defaultPlaceholder: true,
|
||||
options: true,
|
||||
getOptionsAt: true,
|
||||
optionsInputs: true,
|
||||
})
|
||||
.array(),
|
||||
})
|
||||
),
|
||||
});
|
||||
|
||||
export const fieldSchema = baseFieldSchema.merge(
|
||||
z.object({
|
||||
variant: z.string().optional(),
|
||||
variantsConfig: variantsConfigSchema.optional(),
|
||||
|
||||
views: z
|
||||
.object({
|
||||
label: z.string(),
|
||||
id: z.string(),
|
||||
description: z.string().optional(),
|
||||
})
|
||||
.array()
|
||||
.optional(),
|
||||
|
||||
/**
|
||||
* It is used to hide fields such as location when there are less than two options
|
||||
*/
|
||||
hideWhenJustOneOption: z.boolean().default(false).optional(),
|
||||
|
||||
hidden: z.boolean().optional(),
|
||||
editable: EditableSchema.default("user").optional(),
|
||||
sources: z
|
||||
.array(
|
||||
z.object({
|
||||
// Unique ID for the `type`. If type is workflow, it's the workflow ID
|
||||
id: z.string(),
|
||||
type: z.union([z.literal("user"), z.literal("system"), z.string()]),
|
||||
label: z.string(),
|
||||
editUrl: z.string().optional(),
|
||||
// Mark if a field is required by this source or not. This allows us to set `field.required` based on all the sources' fieldRequired value
|
||||
fieldRequired: z.boolean().optional(),
|
||||
})
|
||||
)
|
||||
.optional(),
|
||||
disableOnPrefill: z.boolean().default(false).optional(),
|
||||
})
|
||||
);
|
||||
|
||||
export const eventTypeBookingFields = z.array(fieldSchema);
|
||||
export const BookingFieldTypeEnum = eventTypeBookingFields.element.shape.type.Enum;
|
||||
@@ -1,6 +1,6 @@
|
||||
import { hashPassword } from "@calcom/features/auth/lib/hashPassword";
|
||||
import { validPassword } from "@calcom/features/auth/lib/validPassword";
|
||||
import { verifyPassword } from "@calcom/features/auth/lib/verifyPassword";
|
||||
import { hashPassword } from "@calcom/lib/auth/hashPassword";
|
||||
import { prisma } from "@calcom/prisma";
|
||||
import { IdentityProvider } from "@calcom/prisma/enums";
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { createHash } from "crypto";
|
||||
|
||||
import { hashPassword } from "@calcom/features/auth/lib/hashPassword";
|
||||
import { verifyPassword } from "@calcom/features/auth/lib/verifyPassword";
|
||||
import { hashPassword } from "@calcom/lib/auth/hashPassword";
|
||||
import { prisma } from "@calcom/prisma";
|
||||
|
||||
import { TRPCError } from "@trpc/server";
|
||||
|
||||
Reference in new issue
Block a user