refactor: Move attribute and routing-forms code from app-store/lib to features (#26025)

* mv

* wip

* wip

* wip

* wip

* plural

* fix: resolve TypeScript type errors for attribute refactoring

- Add TransformedAttributeOption type to handle transformed contains field
- Update imports to use routing-forms Attribute type where needed
- Fix getValueOfAttributeOption to use TransformedAttributeOption type
- Update AttributeOptionValueWithType to use TransformedAttributeOption
- Fix pre-existing lint warnings (any -> unknown, proper type casting)

Co-Authored-By: [email protected] <[email protected]>

* fix

* cleanup

* cleanup

* fix

* fix

* fix

* fix

* fix

* fix: add explicit type annotation to reduce callback in getAttributes.ts

Co-Authored-By: [email protected] <[email protected]>

* fix: use RouterOutputs from @calcom/trpc/react for consistent type inference

- Update AppPage.tsx to use RouterOutputs from @calcom/trpc/react instead of inferRouterOutputs<AppRouter>
- Update MultiDisconnectIntegration.tsx to use the same RouterOutputs type source
- Add eslint-disable comments for pre-existing warnings (useEffect deps, img elements)

Co-Authored-By: [email protected] <[email protected]>

* fix: explicitly type attribute property in AttributeOptionAssignment

The attribute property from Pick<AttributeOption, 'attribute'> was typed as
'unknown' because Prisma relations don't have explicit types when picked.
This explicitly defines the attribute shape with id, type, and isLocked
properties that are used in assignValueToUser.ts.

Co-Authored-By: [email protected] <[email protected]>

* fix: remove unused assignedUsers from AttributeOptionAssignment Pick

The assignedUsers property was not being used in the code but was required
by the Pick type, causing a type mismatch when the actual data from the
database query didn't include it.

Co-Authored-By: [email protected] <[email protected]>

* fix: update import path for AttributeOptionAssignment and BulkAttributeAssigner types

The types.d.ts file was moved from packages/lib/service/attribute/ to
packages/app-store/routing-forms/types/. Updated the import path in utils.ts
to point to the new location.

Co-Authored-By: [email protected] <[email protected]>

* fix

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
This commit is contained in:
Benny JooandDevin AI authored and GitHub committed 2025-12-29 21:51:06 -03:00
1 parent 5f0e408d2f
commit 00e5770273
37 files changed
+130 -136

No files matched your search

@@ -0,0 +1,480 @@
import prismock from "../../../../tests/libs/__mocks__/prisma";
import { describe, expect, it, beforeEach } from "vitest";
import type { Attribute } from "@calcom/app-store/routing-forms/types/types";
import type { AttributeOption } from "@calcom/prisma/client";
import { AttributeType, MembershipRole } from "@calcom/prisma/enums";
import { getAttributesForTeam, getAttributesAssignmentData, getUsersAttributes } from "./getAttributes";
// Helper functions to create test data
async function createMockAttribute({
orgId,
options,
...attributeData
}: {
orgId: number;
id: string;
type: AttributeType;
name: string;
slug: string;
options: Pick<AttributeOption, "id" | "value" | "slug" | "contains" | "isGroup">[];
}) {
const attribute = await prismock.attribute.create({
data: {
...attributeData,
teamId: orgId,
enabled: true,
usersCanEditRelation: true,
isWeightsEnabled: false,
createdAt: new Date(),
updatedAt: new Date(),
},
});
await prismock.attributeOption.createMany({
data: options.map((option) => ({
...option,
attributeId: attribute.id,
})),
});
const result = await prismock.attribute.findUnique({
where: { id: attribute.id },
// eslint-disable-next-line @calcom/eslint/no-prisma-include-true
include: { options: true },
});
if (!result) {
throw new Error("Some error in creating mock attribute");
}
return result;
}
async function createMockUserHavingMembershipWithBothTeamAndOrg({
orgId,
teamId,
}: {
orgId: number;
teamId: number;
}) {
const user = await prismock.user.create({
data: {
name: "Test User",
email: "[email protected]",
},
});
// Create org membership
const orgMembership = await prismock.membership.create({
data: {
role: MembershipRole.MEMBER,
disableImpersonation: false,
accepted: true,
teamId: orgId,
userId: user.id,
},
});
// Create team membership
const teamMembership = await prismock.membership.create({
data: {
role: MembershipRole.MEMBER,
disableImpersonation: false,
accepted: true,
teamId: teamId,
userId: user.id,
},
});
return { user, teamMembership, orgMembership };
}
async function createMockTeam({ orgId }: { orgId: number | null }) {
return await prismock.team.create({
data: {
name: "Test Team",
slug: "test-team",
parentId: orgId,
},
});
}
async function createMockAttributeAssignment({
orgMembershipId,
attributeOptionId,
}: {
orgMembershipId: number;
attributeOptionId: string;
}) {
return await prismock.attributeToUser.create({
data: {
memberId: orgMembershipId,
attributeOptionId,
},
});
}
async function expectAttributeToMatch(attribute: Attribute, expected: Attribute) {
expect(attribute).toMatchObject({
id: expected.id,
name: expected.name,
slug: expected.slug,
type: expected.type,
});
}
async function expectAttributesToMatch(attributes: Attribute[], expected: Attribute[]) {
expect(attributes).toHaveLength(expected.length);
for (let i = 0; i < attributes.length; i++) {
expectAttributeToMatch(attributes[i], expected[i]);
}
}
describe("getAttributes", () => {
const orgId = 1001;
beforeEach(async () => {
// @ts-expect-error reset is a method on Prismock
await prismock.reset();
});
describe("getAttributesForTeam", () => {
it("should return empty array for team without parent (non-org team)", async () => {
const teamWithoutParent = await createMockTeam({ orgId: null });
await createMockAttribute({
orgId,
id: "attr1",
name: "Department",
slug: "department",
type: AttributeType.SINGLE_SELECT,
options: [
{ id: "opt1", value: "Engineering", slug: "engineering", isGroup: false, contains: [] },
{ id: "opt2", value: "Sales", slug: "sales", isGroup: false, contains: [] },
],
});
const attributes = await getAttributesForTeam({ teamId: teamWithoutParent.id });
expect(attributes).toHaveLength(0);
});
it("should return attributes assigned to team members", async () => {
const team = await createMockTeam({ orgId });
const { teamMembership } = await createMockUserHavingMembershipWithBothTeamAndOrg({
orgId,
teamId: team.id,
});
const attribute = await createMockAttribute({
orgId,
id: "attr1",
name: "Department",
slug: "department",
type: AttributeType.SINGLE_SELECT,
options: [
{ id: "opt1", value: "Engineering", slug: "engineering", isGroup: false, contains: [] },
{ id: "opt2", value: "Sales", slug: "sales", isGroup: false, contains: [] },
],
});
await createMockAttributeAssignment({
orgMembershipId: teamMembership.id,
attributeOptionId: "opt1",
});
const attributes = await getAttributesForTeam({ teamId: team.id });
expect(attributes).toHaveLength(1);
expect(attributes[0]).toMatchObject({
id: attribute.id,
name: attribute.name,
type: attribute.type,
});
});
});
describe("getAttributesAssignmentData", () => {
it("should return team members with their assigned attributes", async () => {
const team = await createMockTeam({ orgId });
const { user, orgMembership } = await createMockUserHavingMembershipWithBothTeamAndOrg({
orgId,
teamId: team.id,
});
const attr1 = await createMockAttribute({
orgId,
id: "attr1",
name: "Department",
slug: "department",
type: AttributeType.MULTI_SELECT,
options: [
{ id: "engineering-id", value: "Engineering", slug: "engineering", isGroup: false, contains: [] },
{ id: "sales-id", value: "Sales", slug: "sales", isGroup: false, contains: [] },
{
id: "engineering-and-sales-id",
value: "EngineeringAndSales",
slug: "engineering-and-sales",
isGroup: true,
contains: ["engineering-id", "sales-id"],
},
],
});
const attr2 = await createMockAttribute({
orgId,
id: "attr2",
name: "Territory",
slug: "territory",
type: AttributeType.SINGLE_SELECT,
options: [
{ id: "india-id", value: "India", slug: "india", isGroup: false, contains: [] },
{ id: "china-id", value: "China", slug: "china", isGroup: false, contains: [] },
],
});
// Unassigned attribute
const attr3 = await createMockAttribute({
orgId,
id: "attr3",
name: "Attr3",
slug: "attr3",
type: AttributeType.SINGLE_SELECT,
options: [
{ id: "opt1", value: "Opt1", slug: "opt1", isGroup: false, contains: [] },
{ id: "opt2", value: "Opt2", slug: "opt2", isGroup: false, contains: [] },
],
});
await createMockAttributeAssignment({
orgMembershipId: orgMembership.id,
// Assigning a group option that has its sub-options not assigned directly to the user
attributeOptionId: "engineering-and-sales-id",
});
await createMockAttributeAssignment({
orgMembershipId: orgMembership.id,
attributeOptionId: "india-id",
});
await createMockAttributeAssignment({
orgMembershipId: orgMembership.id,
attributeOptionId: "engineering-id",
});
const { attributesOfTheOrg, attributesAssignedToTeamMembersWithOptions } =
await getAttributesAssignmentData({ teamId: team.id, orgId });
expect(attributesAssignedToTeamMembersWithOptions).toHaveLength(1);
expect(attributesAssignedToTeamMembersWithOptions[0]).toEqual({
userId: user.id,
attributes: {
attr1: {
type: AttributeType.MULTI_SELECT,
attributeOption: [
{
isGroup: true,
value: "EngineeringAndSales",
contains: [
{
id: "engineering-id",
slug: "engineering",
value: "Engineering",
},
{ id: "sales-id", slug: "sales", value: "Sales" },
],
},
{
isGroup: false,
value: "Engineering",
contains: [],
},
],
},
attr2: {
type: AttributeType.SINGLE_SELECT,
attributeOption: { isGroup: false, value: "India", contains: [] },
},
// attr3 - unassigned isn't here
},
});
expectAttributesToMatch(attributesOfTheOrg, [attr1, attr2, attr3]);
});
it("should return contains correctly for group options that have sub-options not assigned directly to the user", async () => {
const team = await createMockTeam({ orgId });
const { user, orgMembership } = await createMockUserHavingMembershipWithBothTeamAndOrg({
orgId,
teamId: team.id,
});
const attr1 = await createMockAttribute({
orgId,
id: "attr1",
name: "Department",
slug: "department",
type: AttributeType.MULTI_SELECT,
options: [
{ id: "engineering-id", value: "Engineering", slug: "engineering", isGroup: false, contains: [] },
{ id: "sales-id", value: "Sales", slug: "sales", isGroup: false, contains: [] },
{
id: "engineering-and-sales-id",
value: "EngineeringAndSales",
slug: "engineering-and-sales",
isGroup: true,
contains: ["engineering-id", "sales-id"],
},
],
});
await createMockAttributeAssignment({
orgMembershipId: orgMembership.id,
// Assigning a group option that has its sub-options not assigned directly to the user
attributeOptionId: "engineering-and-sales-id",
});
const { attributesOfTheOrg, attributesAssignedToTeamMembersWithOptions } =
await getAttributesAssignmentData({ teamId: team.id, orgId });
expect(attributesAssignedToTeamMembersWithOptions).toHaveLength(1);
expect(attributesAssignedToTeamMembersWithOptions[0]).toEqual({
userId: user.id,
attributes: {
attr1: {
type: AttributeType.MULTI_SELECT,
attributeOption: {
isGroup: true,
value: "EngineeringAndSales",
contains: [
{
id: "engineering-id",
slug: "engineering",
value: "Engineering",
},
{ id: "sales-id", slug: "sales", value: "Sales" },
],
},
},
},
});
expectAttributesToMatch(attributesOfTheOrg, [attr1]);
});
it("should return no attributes for a different org", async () => {
const team = await createMockTeam({ orgId });
const otherOrgId = 1002;
const otherOrgsTeam = await createMockTeam({ orgId: otherOrgId });
const { orgMembership } = await createMockUserHavingMembershipWithBothTeamAndOrg({
orgId,
teamId: team.id,
});
await createMockAttribute({
orgId,
id: "attr1",
name: "Department",
slug: "department",
type: AttributeType.MULTI_SELECT,
options: [
{ id: "engineering-id", value: "Engineering", slug: "engineering", isGroup: false, contains: [] },
{ id: "sales-id", value: "Sales", slug: "sales", isGroup: false, contains: [] },
{
id: "engineering-and-sales-id",
value: "EngineeringAndSales",
slug: "engineering-and-sales",
isGroup: true,
contains: ["engineering-id", "sales-id"],
},
],
});
await createMockAttributeAssignment({
orgMembershipId: orgMembership.id,
// Assigning a group option that has its sub-options not assigned directly to the user
attributeOptionId: "engineering-and-sales-id",
});
const { attributesOfTheOrg, attributesAssignedToTeamMembersWithOptions } =
await getAttributesAssignmentData({ teamId: otherOrgsTeam.id, orgId: otherOrgId });
expect(attributesAssignedToTeamMembersWithOptions).toHaveLength(0);
// Because created attribute is of other org, it should not be returned
expect(attributesOfTheOrg).toHaveLength(0);
});
it("should handle multi-select attributes correctly", async () => {
const team = await createMockTeam({ orgId });
const { orgMembership } = await createMockUserHavingMembershipWithBothTeamAndOrg({
orgId,
teamId: team.id,
});
const attr1 = await createMockAttribute({
orgId,
id: "attr1",
name: "Skills",
slug: "skills",
type: AttributeType.MULTI_SELECT,
options: [
{ id: "opt1", value: "JavaScript", slug: "javascript", isGroup: false, contains: [] },
{ id: "opt2", value: "Python", slug: "python", isGroup: false, contains: [] },
],
});
// Assign multiple skills
await createMockAttributeAssignment({
orgMembershipId: orgMembership.id,
attributeOptionId: "opt1",
});
await createMockAttributeAssignment({
orgMembershipId: orgMembership.id,
attributeOptionId: "opt2",
});
const { attributesOfTheOrg, attributesAssignedToTeamMembersWithOptions } =
await getAttributesAssignmentData({ teamId: team.id, orgId });
expect(attributesAssignedToTeamMembersWithOptions).toHaveLength(1);
expect(attributesAssignedToTeamMembersWithOptions[0].attributes.attr1.attributeOption).toEqual([
{ value: "JavaScript", isGroup: false, contains: [] },
{ value: "Python", isGroup: false, contains: [] },
]);
expectAttributesToMatch(attributesOfTheOrg, [attr1]);
});
});
describe("getUsersAttributes", () => {
it("should return attributes assigned to specific user in team", async () => {
const team = await createMockTeam({ orgId });
const { user, orgMembership } = await createMockUserHavingMembershipWithBothTeamAndOrg({
orgId,
teamId: team.id,
});
const attribute = await createMockAttribute({
orgId,
id: "attr1",
name: "Department",
slug: "department",
type: AttributeType.SINGLE_SELECT,
options: [{ id: "opt1", value: "Engineering", slug: "engineering", isGroup: false, contains: [] }],
});
await createMockAttributeAssignment({
orgMembershipId: orgMembership.id,
attributeOptionId: "opt1",
});
const userAttributes = await getUsersAttributes({ userId: user.id, teamId: team.id });
expect(userAttributes).toHaveLength(1);
expect(userAttributes[0]).toMatchObject({
id: attribute.id,
name: attribute.name,
type: attribute.type,
});
});
});
});
@@ -0,0 +1,373 @@
// TODO: Queries in this file are not optimized. Need to optimize them.
import type { Attribute } from "@calcom/app-store/routing-forms/types/types";
import type { AttributeId, AttributeOptionValueWithType } from "@calcom/app-store/routing-forms/types/types";
import { PrismaAttributeRepository } from "@calcom/features/attributes/repositories/PrismaAttributeRepository";
import { PrismaAttributeToUserRepository } from "@calcom/features/attributes/repositories/PrismaAttributeToUserRepository";
import logger from "@calcom/lib/logger";
import { safeStringify } from "@calcom/lib/safeStringify";
import prisma from "@calcom/prisma";
import type { AttributeToUser } from "@calcom/prisma/client";
import type { AttributeType } from "@calcom/prisma/enums";
type UserId = number;
type OrgMembershipId = number;
type AttributeOptionId = string;
type AssignmentForTheTeam = {
userId: number;
attributeOption: {
id: string;
value: string;
slug: string;
contains: string[];
isGroup: boolean;
};
attribute: {
id: string;
name: string;
type: AttributeType;
};
};
type FullAttribute = {
name: string;
slug: string;
type: AttributeType;
id: string;
options: {
id: string;
value: string;
slug: string;
isGroup: boolean;
contains: string[];
}[];
};
async function _findMembershipsForBothOrgAndTeam({ orgId, teamId }: { orgId: number; teamId: number }) {
const memberships = await prisma.membership.findMany({
where: {
teamId: {
in: [orgId, teamId],
},
},
});
type Membership = (typeof memberships)[number];
const { teamMemberships, orgMemberships } = memberships.reduce<{
teamMemberships: Membership[];
orgMemberships: Membership[];
}>(
(acc, membership) => {
if (membership.teamId === teamId) {
acc.teamMemberships.push(membership);
} else if (membership.teamId === orgId) {
acc.orgMemberships.push(membership);
}
return acc;
},
{ teamMemberships: [], orgMemberships: [] }
);
return {
teamMemberships,
orgMemberships,
};
}
function _prepareAssignmentData({
assignmentsForTheTeam,
attributesOfTheOrg,
}: {
assignmentsForTheTeam: AssignmentForTheTeam[];
attributesOfTheOrg: Attribute[];
}) {
const teamMembersThatHaveOptionAssigned = assignmentsForTheTeam.reduce((acc, attributeToUser) => {
const userId = attributeToUser.userId;
const attributeOption = attributeToUser.attributeOption;
const attribute = attributeToUser.attribute;
if (!acc[userId]) {
acc[userId] = { userId, attributes: {} };
}
const attributes = acc[userId].attributes;
const currentAttributeOptionValue = attributes[attribute.id]?.attributeOption;
const newAttributeOptionValue = {
isGroup: attributeOption.isGroup,
value: attributeOption.value,
contains: tranformContains({ contains: attributeOption.contains, attribute }),
};
if (currentAttributeOptionValue instanceof Array) {
attributes[attribute.id].attributeOption = [...currentAttributeOptionValue, newAttributeOptionValue];
} else if (currentAttributeOptionValue) {
attributes[attribute.id].attributeOption = [
currentAttributeOptionValue,
{
isGroup: attributeOption.isGroup,
value: attributeOption.value,
contains: tranformContains({ contains: attributeOption.contains, attribute }),
},
];
} else {
// Set the first value
attributes[attribute.id] = {
type: attribute.type,
attributeOption: newAttributeOptionValue,
};
}
return acc;
}, {} as Record<UserId, { userId: UserId; attributes: Record<AttributeId, AttributeOptionValueWithType> }>);
return Object.values(teamMembersThatHaveOptionAssigned);
/**
* Transforms ["optionId1", "optionId2"] to [{
* id: "optionId1",
* value: "optionValue1",
* slug: "optionSlug1",
* }, {
* id: "optionId2",
* value: "optionValue2",
* slug: "optionSlug2",
* }]
*/
function tranformContains({
contains,
attribute,
}: {
contains: string[];
attribute: { id: string; name: string };
}) {
return contains
.map((optionId) => {
const allOptions = attributesOfTheOrg.find((_attribute) => _attribute.id === attribute.id)?.options;
const option = allOptions?.find((option) => option.id === optionId);
if (!option) {
console.error(
`Enriching "contains" for attribute ${
attribute.name
}: Option with id ${optionId} not found. Looked up in ${JSON.stringify(allOptions)}`
);
return null;
}
return {
id: option.id,
value: option.value,
slug: option.slug,
};
})
.filter((option): option is NonNullable<typeof option> => option !== null);
}
}
function _getAttributeFromAttributeOption({
allAttributesOfTheOrg,
attributeOptionId,
}: {
allAttributesOfTheOrg: Attribute[];
attributeOptionId: AttributeOptionId;
}) {
return allAttributesOfTheOrg.find((attribute) =>
attribute.options.some((option) => option.id === attributeOptionId)
);
}
function _getAttributeOptionFromAttributeOption({
allAttributesOfTheOrg,
attributeOptionId,
}: {
allAttributesOfTheOrg: FullAttribute[];
attributeOptionId: AttributeOptionId;
}) {
const matchingOption = allAttributesOfTheOrg.reduce((found, attribute) => {
if (found) return found;
return attribute.options.find((option) => option.id === attributeOptionId) || null;
}, null as null | (typeof allAttributesOfTheOrg)[number]["options"][number]);
return matchingOption;
}
async function _getOrgMembershipToUserIdForTeam({ orgId, teamId }: { orgId: number; teamId: number }) {
const { orgMemberships, teamMemberships } = await _findMembershipsForBothOrgAndTeam({
orgId,
teamId,
});
// Using map for performance lookup as it matters in the below loop working with 1000s of records
const orgMembershipsByUserId = new Map(orgMemberships.map((m) => [m.userId, m]));
/**
* Holds the records of orgMembershipId to userId for the sub-team's members only.
*/
const orgMembershipToUserIdForTeamMembers = new Map<OrgMembershipId, UserId>();
/**
* For an organization with 3000 users and 10 teams, with every team having around 300 members, the total memberships we get for a team are 3000+300 = 3300
* So, these are not a lot of records and we could afford to do in memory computations on them.
*/
teamMemberships.forEach((teamMembership) => {
const orgMembership = orgMembershipsByUserId.get(teamMembership.userId);
if (!orgMembership) {
console.error(
`Org membership not found for userId ${teamMembership.userId} in the organization's memberships`
);
return;
}
orgMembershipToUserIdForTeamMembers.set(orgMembership.id, orgMembership.userId);
});
return orgMembershipToUserIdForTeamMembers;
}
async function _queryAllData({ orgId, teamId }: { orgId: number; teamId: number }) {
const attributeRepo = new PrismaAttributeRepository(prisma);
const [orgMembershipToUserIdForTeamMembers, attributesOfTheOrg] = await Promise.all([
_getOrgMembershipToUserIdForTeam({ orgId, teamId }),
attributeRepo.findManyByOrgId({ orgId }),
]);
const orgMembershipIds = Array.from(orgMembershipToUserIdForTeamMembers.keys());
// Get all the attributes assigned to the members of the team
const attributesToUsersForTeam = await PrismaAttributeToUserRepository.findManyByOrgMembershipIds({
orgMembershipIds,
});
return {
attributesOfTheOrg,
attributesToUsersForTeam,
orgMembershipToUserIdForTeamMembers,
};
}
async function getAttributesAssignedToMembersOfTeam({ teamId, userId }: { teamId: number; userId?: number }) {
const log = logger.getSubLogger({ prefix: ["getAttributeToUserWithMembershipAndAttributes"] });
const whereClauseForAttributesAssignedToMembersOfTeam = {
options: {
some: {
assignedUsers: {
some: {
member: {
userId,
user: {
teams: {
some: {
teamId,
},
},
},
},
},
},
},
},
};
log.debug(
safeStringify({
teamId,
whereClauseForAttributesAssignedToMembersOfTeam,
})
);
const assignedAttributeOptions = await prisma.attribute.findMany({
where: whereClauseForAttributesAssignedToMembersOfTeam,
select: {
id: true,
name: true,
type: true,
isWeightsEnabled: true,
options: {
select: {
id: true,
value: true,
slug: true,
contains: true,
isGroup: true,
},
},
slug: true,
},
});
return assignedAttributeOptions;
}
function _buildAssignmentsForTeam({
attributesToUsersForTeam,
orgMembershipToUserIdForTeamMembers,
attributesOfTheOrg,
}: {
attributesToUsersForTeam: AttributeToUser[];
orgMembershipToUserIdForTeamMembers: Map<OrgMembershipId, UserId>;
attributesOfTheOrg: FullAttribute[];
}) {
return attributesToUsersForTeam
.map((attributeToUser) => {
const orgMembershipId = attributeToUser.memberId;
const userId = orgMembershipToUserIdForTeamMembers.get(orgMembershipId);
if (!userId) {
console.error(`No org membership found for membership id ${orgMembershipId}`);
return null;
}
const attribute = _getAttributeFromAttributeOption({
allAttributesOfTheOrg: attributesOfTheOrg,
attributeOptionId: attributeToUser.attributeOptionId,
});
const attributeOption = _getAttributeOptionFromAttributeOption({
allAttributesOfTheOrg: attributesOfTheOrg,
attributeOptionId: attributeToUser.attributeOptionId,
});
if (!attributeOption || !attribute) {
console.error(
`Attribute option with id ${attributeToUser.attributeOptionId} not found in the organization's attributes`
);
return null;
}
return {
...attributeToUser,
userId,
attribute,
attributeOption,
};
})
.filter((assignment): assignment is NonNullable<typeof assignment> => assignment !== null);
}
export async function getAttributesAssignmentData({ orgId, teamId }: { orgId: number; teamId: number }) {
const { attributesOfTheOrg, attributesToUsersForTeam, orgMembershipToUserIdForTeamMembers } =
await _queryAllData({
orgId,
teamId,
});
const assignmentsForTheTeam = _buildAssignmentsForTeam({
attributesToUsersForTeam,
orgMembershipToUserIdForTeamMembers,
attributesOfTheOrg,
});
const attributesAssignedToTeamMembersWithOptions = _prepareAssignmentData({
attributesOfTheOrg,
assignmentsForTheTeam,
});
return {
attributesOfTheOrg,
attributesAssignedToTeamMembersWithOptions,
};
}
export async function getAttributesForTeam({ teamId }: { teamId: number }) {
const attributes = await getAttributesAssignedToMembersOfTeam({ teamId });
return attributes satisfies Attribute[];
}
export async function getUsersAttributes({ userId, teamId }: { userId: number; teamId: number }) {
return await getAttributesAssignedToMembersOfTeam({ teamId, userId });
}
+21
View File
@@ -0,0 +1,21 @@
import { PrismaAttributeToUserRepository } from "@calcom/features/attributes/repositories/PrismaAttributeToUserRepository";
export const getWhereClauseForAttributeOptionsManagedByCalcom = () => {
// Neither created nor updated by DSync
return {
createdByDSyncId: null,
// An option created by Cal.com can be updated by DSync, in that case the ownership is transferred to DSync
updatedByDSyncId: null,
};
};
export const findAssignmentsForMember = async ({ memberId }: { memberId: number }) => {
const assignments = await PrismaAttributeToUserRepository.findManyIncludeAttribute({ memberId });
return assignments.map((assignment) => ({
...assignment,
attributeOption: {
...assignment.attributeOption,
label: assignment.attributeOption.value,
},
}));
};
@@ -0,0 +1,30 @@
import { prisma } from "@calcom/prisma";
import type { Prisma } from "@calcom/prisma/client";
export class PrismaAttributeOptionRepository {
static async findMany({ orgId }: { orgId: number }) {
return prisma.attributeOption.findMany({
where: {
attribute: {
teamId: orgId,
},
},
select: {
id: true,
value: true,
slug: true,
attributeId: true,
},
});
}
static async createMany({ createManyInput }: { createManyInput: Prisma.AttributeOptionCreateManyInput[] }) {
const { count } = await prisma.attributeOption.createMany({
data: createManyInput,
});
return {
count,
};
}
}
@@ -0,0 +1,99 @@
import type { PrismaClient } from "@calcom/prisma";
export class PrismaAttributeRepository {
constructor(private prismaClient: PrismaClient) {}
async findManyByNamesAndOrgIdIncludeOptions({
attributeNames,
orgId,
}: {
attributeNames: string[];
orgId: number;
}) {
return this.prismaClient.attribute.findMany({
where: {
name: { in: attributeNames, mode: "insensitive" },
teamId: orgId,
},
include: {
options: {
select: {
id: true,
value: true,
slug: true,
},
},
},
});
}
async findManyByOrgId({ orgId }: { orgId: number }) {
// It should be a faster query because of lesser number of attributes record and index on teamId
const result = await this.prismaClient.attribute.findMany({
where: {
teamId: orgId,
},
select: {
id: true,
name: true,
type: true,
slug: true,
options: true,
},
});
return result;
}
async findAllByOrgIdWithOptions({ orgId }: { orgId: number }) {
return await this.prismaClient.attribute.findMany({
where: {
teamId: orgId,
},
include: {
options: true,
},
});
}
async findUniqueWithWeights({
teamId,
attributeId,
isWeightsEnabled = true,
}: {
teamId: number;
attributeId: string;
isWeightsEnabled?: boolean;
}) {
return await this.prismaClient.attribute.findUnique({
where: {
id: attributeId,
teamId,
isWeightsEnabled,
},
select: {
id: true,
name: true,
slug: true,
type: true,
options: {
select: {
id: true,
value: true,
slug: true,
assignedUsers: {
select: {
member: {
select: {
userId: true,
},
},
weight: true,
},
},
},
},
},
});
}
}
@@ -0,0 +1,46 @@
import { prisma } from "@calcom/prisma";
import type { Prisma } from "@calcom/prisma/client";
export class PrismaAttributeToUserRepository {
static async createManySkipDuplicates(data: Prisma.AttributeToUserCreateManyInput[]) {
return await prisma.attributeToUser.createMany({ data, skipDuplicates: true });
}
static async deleteMany(where: Prisma.AttributeToUserWhereInput) {
if (Object.keys(where).length === 0) {
throw new Error("Empty where clause provided to deleteMany. Potential data loss risk.");
}
return await prisma.attributeToUser.deleteMany({ where });
}
static async findManyIncludeAttribute(where: Prisma.AttributeToUserWhereInput) {
return await prisma.attributeToUser.findMany({
where,
include: {
attributeOption: {
select: {
attribute: true,
value: true,
slug: true,
},
},
},
});
}
static async findManyByOrgMembershipIds({ orgMembershipIds }: { orgMembershipIds: number[] }) {
if (!orgMembershipIds.length) {
return [];
}
const attributesAssignedToTeamMembers = await prisma.attributeToUser.findMany({
where: {
memberId: {
in: orgMembershipIds,
},
},
});
return attributesAssignedToTeamMembers;
}
}
@@ -2,6 +2,7 @@ import { acrossQueryValueCompatiblity } from "@calcom/app-store/_utils/raqb/raqb
import type { FormResponse, Fields } from "@calcom/app-store/routing-forms/types/types";
import { zodRoutes } from "@calcom/app-store/routing-forms/zod";
import dayjs from "@calcom/dayjs";
import type { PrismaAttributeRepository } from "@calcom/features/attributes/repositories/PrismaAttributeRepository";
import type { BookingRepository } from "@calcom/features/bookings/repositories/BookingRepository";
import { getBusyCalendarTimes } from "@calcom/features/calendars/lib/CalendarManager";
import type { HostRepository } from "@calcom/features/host/repositories/HostRepository";
@@ -11,7 +12,6 @@ import type { UserRepository } from "@calcom/features/users/repositories/UserRep
import logger from "@calcom/lib/logger";
import { raqbQueryValueSchema } from "@calcom/lib/raqb/zod";
import { safeStringify } from "@calcom/lib/safeStringify";
import type { PrismaAttributeRepository } from "@calcom/lib/server/repository/PrismaAttributeRepository";
import type { Prisma } from "@calcom/prisma/client";
import type { User, Booking, SelectedCalendar } from "@calcom/prisma/client";
import type { AttributeType } from "@calcom/prisma/enums";
+2 -2
View File
@@ -1,6 +1,6 @@
import { DI_TOKENS } from "@calcom/features/di/tokens";
import { PrismaAttributeRepository } from "@calcom/lib/server/repository/PrismaAttributeRepository";
import { PrismaAttributeRepository } from "@calcom/features/attributes/repositories/PrismaAttributeRepository";
import { moduleLoader as prismaModuleLoader } from "@calcom/features/di/modules/Prisma";
import { DI_TOKENS } from "@calcom/features/di/tokens";
import { createModule, bindModuleToClassOnToken, type ModuleLoader } from "../di";
@@ -1,15 +1,17 @@
import { MembershipRepository } from "@calcom/features/membership/repositories/MembershipRepository";
import logger from "@calcom/lib/logger";
import { safeStringify } from "@calcom/lib/safeStringify";
import { PrismaAttributeOptionRepository } from "@calcom/lib/server/repository/PrismaAttributeOptionRepository";
import { PrismaAttributeRepository } from "@calcom/lib/server/repository/PrismaAttributeRepository";
import { findAssignmentsForMember } from "@calcom/lib/service/attribute/server/utils";
import type {
AttributeId,
AttributeName,
BulkAttributeAssigner,
AttributeOptionAssignment,
} from "@calcom/lib/service/attribute/types";
} from "@calcom/app-store/routing-forms/types/types";
import { findAssignmentsForMember } from "@calcom/features/attributes/lib/utils";
import { PrismaAttributeOptionRepository } from "@calcom/features/attributes/repositories/PrismaAttributeOptionRepository";
import { PrismaAttributeRepository } from "@calcom/features/attributes/repositories/PrismaAttributeRepository";
import { MembershipRepository } from "@calcom/features/membership/repositories/MembershipRepository";
import logger from "@calcom/lib/logger";
import { safeStringify } from "@calcom/lib/safeStringify";
import prisma from "@calcom/prisma";
import {
doesSupportMultipleValues,
isAssignmentForLockedAttribute,
@@ -17,8 +19,7 @@ import {
isAssignmentSame,
buildSlugFromValue,
canSetValueBeyondOptions,
} from "@calcom/lib/service/attribute/utils";
import prisma from "@calcom/prisma";
} from "./assignValueToUserUtils";
const log = logger.getSubLogger({ prefix: ["entity/attribute"] });
@@ -0,0 +1,89 @@
/**
* Utility functions for attribute service. Shared across server and client.
*/
import type {
AttributeOptionAssignment,
BulkAttributeAssigner,
} from "@calcom/app-store/routing-forms/types/types";
import slugify from "@calcom/lib/slugify";
import { AttributeType } from "@calcom/prisma/enums";
/**
* What is a pool?
* There can be two pools:
* 1. SCIM Pool - All assignments in this pool are created/updated by SCIM.
* 2. Cal.com User Pool - All assignments in this pool are created/updated by Cal.com Users.
*/
export const isAssignmentForTheSamePool = ({
assignment,
updater,
}: {
assignment: Pick<
AttributeOptionAssignment,
"createdByDSyncId" | "updatedByDSyncId" | "createdById" | "updatedById"
>;
updater: BulkAttributeAssigner;
}) => {
if ("dsyncId" in updater) {
// Cal.com user updated an assignment created by SCIM. It no longer belongs to the SCIM pool.
if (assignment.updatedById) {
return false;
}
// Either SCIM created the assignment or updated it
return !!assignment.updatedByDSyncId || !!assignment.createdByDSyncId;
}
// SCIM neither created nor updated the assignment, it has to belong to the only left pool(i.e. Cal.com User Pool)
return !assignment.createdByDSyncId && !assignment.updatedByDSyncId;
};
export const isAssignmentForLockedAttribute = ({
assignment,
}: {
assignment: {
attributeOption: {
attribute: {
isLocked: boolean;
};
};
};
}) => {
return assignment.attributeOption.attribute.isLocked;
};
export const isAssignmentSame = ({
existingAssignment,
newOption,
}: {
existingAssignment: { attributeOption: { label: string } };
newOption: { label: string };
}) => {
return existingAssignment.attributeOption.label.toLowerCase() === newOption.label.toLowerCase();
};
export const doesSupportMultipleValues = ({ attribute }: { attribute: { type: AttributeType } }) => {
return attribute.type === AttributeType.MULTI_SELECT;
};
export const buildSlugFromValue = ({ value }: { value: string }) => {
return slugify(value);
};
export const hasOptions = ({
attribute,
}: {
attribute: {
type: AttributeType;
};
}) => {
return attribute.type === AttributeType.MULTI_SELECT || attribute.type === AttributeType.SINGLE_SELECT;
};
export const canSetValueBeyondOptions = ({
attribute,
}: {
attribute: {
type: AttributeType;
};
}) => {
return !hasOptions({ attribute });
};
@@ -1,8 +1,8 @@
import { acrossQueryValueCompatiblity } from "@calcom/app-store/_utils/raqb/raqbUtils.server";
import type { FormResponse, Fields } from "@calcom/app-store/routing-forms/types/types";
import { zodRoutes } from "@calcom/app-store/routing-forms/zod";
import { getUsersAttributes } from "@calcom/features/attributes/lib/getAttributes";
import { withReporting } from "@calcom/lib/sentryWrapper";
import { getUsersAttributes } from "@calcom/lib/service/attribute/server/getAttributes";
import prisma from "@calcom/prisma";
import { AssignmentReasonEnum } from "@calcom/prisma/enums";
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,459 @@
import async from "async";
import type { ImmutableTree, JsonLogicResult, JsonTree } from "react-awesome-query-builder";
import type { Config } from "react-awesome-query-builder/lib";
import { Utils as QbUtils } from "react-awesome-query-builder/lib";
import { acrossQueryValueCompatiblity, raqbQueryValueUtils } from "@calcom/app-store/_utils/raqb/raqbUtils";
import type { Attribute } from "@calcom/app-store/routing-forms/types/types";
import { getAttributesAssignmentData } from "@calcom/features/attributes/lib/getAttributes";
import { RaqbLogicResult } from "@calcom/lib/raqb/evaluateRaqbLogic";
import jsonLogic from "@calcom/lib/raqb/jsonLogic";
import type { dynamicFieldValueOperands, AttributesQueryValue } from "@calcom/lib/raqb/types";
const {
getAttributesData: getAttributes,
getAttributesQueryBuilderConfigHavingListofLabels,
getAttributesQueryValue,
} = acrossQueryValueCompatiblity;
type TeamMemberWithAttributeOptionValuePerAttribute = Awaited<
ReturnType<typeof getAttributesAssignmentData>
>["attributesAssignedToTeamMembersWithOptions"][number];
type RunAttributeLogicData = {
attributesQueryValue: AttributesQueryValue | null;
attributesData: {
attributesOfTheOrg: Attribute[];
teamMembersWithAttributeOptionValuePerAttribute: TeamMemberWithAttributeOptionValuePerAttribute[];
};
dynamicFieldValueOperands?: dynamicFieldValueOperands;
};
type RunAttributeLogicOptions = {
concurrency: number;
enablePerf: boolean;
isPreview: boolean;
enableTroubleshooter: boolean;
};
export const enum TroubleshooterCase {
IS_A_ROUTER = "is-a-router",
NO_LOGIC_FOUND = "no-logic-found",
MATCH_RESULTS_READY = "match-results-ready",
MATCH_RESULTS_READY_WITH_FALLBACK = "match-results-ready-with-fallback",
MATCHES_ALL_MEMBERS_BECAUSE_OF_EMPTY_QUERY_VALUE = "matches-all-members-because-of-empty-query-value",
MATCHES_ALL_MEMBERS = "matches-all-members",
}
/**
* Performance wrapper for async functions
*/
async function asyncPerf<ReturnValue>(fn: () => Promise<ReturnValue>): Promise<[ReturnValue, number | null]> {
const start = performance.now();
const result = await fn();
const end = performance.now();
return [result, end - start];
}
/**
* Performance wrapper for sync functions
*/
function perf<ReturnValue>(fn: () => ReturnValue): [ReturnValue, number | null] {
const start = performance.now();
const result = fn();
const end = performance.now();
return [result, end - start];
}
function getErrorsFromImmutableTree(tree: ImmutableTree) {
const validatedQueryValue = QbUtils.getTree(tree);
if (!raqbQueryValueUtils.isQueryValueARuleGroup(validatedQueryValue)) {
return [];
}
if (!validatedQueryValue.children1) {
return [];
}
const errors: string[][] = [];
Object.values(validatedQueryValue.children1).map((rule) => {
if (rule.type !== "rule") {
return;
}
const valueError = rule.properties.valueError;
if (valueError) {
// Sometimes there are null values in it.
errors.push(valueError.filter(Boolean));
}
});
return errors;
}
function getJsonLogic({
attributesQueryValue,
attributesQueryBuilderConfig,
}: {
attributesQueryValue: AttributesQueryValue;
attributesQueryBuilderConfig: Config;
}) {
const state = {
tree: QbUtils.checkTree(
QbUtils.loadTree(attributesQueryValue as JsonTree),
// We know that attributesQueryBuilderConfig is a Config because getAttributesQueryBuilderConfigHavingListofLabels returns a Config. So, asserting it.
attributesQueryBuilderConfig as unknown as Config
),
config: attributesQueryBuilderConfig as unknown as Config,
};
const jsonLogicQuery = QbUtils.jsonLogicFormat(state.tree, state.config);
const logic = jsonLogicQuery.logic;
// Considering errors as warnings as we want to continue with the flow without throwing actual errors
// We expect fallback logic to take effect in case of errors in main logic
const warnings = getErrorsFromImmutableTree(state.tree).flat();
if (!logic) {
// If children1 is not empty, it means that some rules were added by use
if (attributesQueryValue.children1 && Object.keys(attributesQueryValue.children1).length > 0) {
// Possible reasons for this
// 1. The attribute option value used is not in the options list. Happens if 'Value of field' value is chosen and that field's response value doesn't exist in attribute options list.
return { logic, warnings: ["There is some error building the logic, please check the routes."] };
}
}
return { logic, warnings };
}
function buildTroubleshooterData({ type, data }: { type: TroubleshooterCase; data: Record<string, any> }) {
return {
troubleshooter: {
type,
data,
},
};
}
async function getLogicResultForAllMembers(
{
teamMembersWithAttributeOptionValuePerAttribute,
attributeJsonLogic,
attributesQueryValue,
}: {
teamMembersWithAttributeOptionValuePerAttribute: TeamMemberWithAttributeOptionValuePerAttribute[];
attributeJsonLogic: NonNullable<JsonLogicResult["logic"]>;
attributesQueryValue: AttributesQueryValue;
},
config: {
concurrency?: number;
enableTroubleshooter?: boolean;
} = {}
) {
const { concurrency = 2 } = config;
const teamMembersMatchingAttributeLogicMap = new Map<number, RaqbLogicResult>();
const attributesDataPerUser = new Map<number, ReturnType<typeof getAttributes>>();
await async.mapLimit<TeamMemberWithAttributeOptionValuePerAttribute, Promise<void>>(
teamMembersWithAttributeOptionValuePerAttribute,
concurrency,
async (member: TeamMemberWithAttributeOptionValuePerAttribute) => {
const attributesData = getAttributes({
attributesData: member.attributes,
attributesQueryValue,
});
attributesDataPerUser.set(member.userId, attributesData);
const result = jsonLogic.apply(attributeJsonLogic as any, attributesData)
? RaqbLogicResult.MATCH
: RaqbLogicResult.NO_MATCH;
if (result !== RaqbLogicResult.MATCH) {
return;
}
teamMembersMatchingAttributeLogicMap.set(member.userId, result);
}
);
return {
teamMembersMatchingAttributeLogicMap,
attributesDataPerUser,
};
}
async function runAttributeLogic(data: RunAttributeLogicData, options: RunAttributeLogicOptions) {
const {
attributesQueryValue: _attributesQueryValue,
attributesData: { attributesOfTheOrg, teamMembersWithAttributeOptionValuePerAttribute },
dynamicFieldValueOperands,
} = data;
const { concurrency, enablePerf, enableTroubleshooter } = options;
const attributesQueryValue = getAttributesQueryValue({
attributesQueryValue: _attributesQueryValue ?? null,
attributes: attributesOfTheOrg,
dynamicFieldValueOperands,
});
// TODO: Do we really need to do !attributesQueryValue check separately?
if (!attributesQueryValue || raqbQueryValueUtils.isQueryValueEmpty(attributesQueryValue as JsonTree)) {
return {
logicBuildingWarnings: null,
teamMembersMatchingAttributeLogic: null,
timeTaken: null,
...buildTroubleshooterData({
type: TroubleshooterCase.MATCHES_ALL_MEMBERS_BECAUSE_OF_EMPTY_QUERY_VALUE,
data: { attributesQueryValue },
}),
};
}
const [attributesQueryBuilderConfig, ttgetAttributesQueryBuilderConfigHavingListofLabels] = pf(() =>
getAttributesQueryBuilderConfigHavingListofLabels({
dynamicFieldValueOperands,
attributes: attributesOfTheOrg,
})
);
const { logic, warnings: logicBuildingWarnings } = getJsonLogic({
attributesQueryValue,
attributesQueryBuilderConfig: attributesQueryBuilderConfig as unknown as Config,
});
if (!logic) {
return {
teamMembersMatchingAttributeLogic: null,
logicBuildingWarnings: null,
timeTaken: {
ttgetAttributesQueryBuilderConfigHavingListofLabels,
},
...buildTroubleshooterData({
type: TroubleshooterCase.NO_LOGIC_FOUND,
data: {
attributesQueryValue,
attributesQueryBuilderConfig,
teamMembersWithAttributeOptionValuePerAttribute,
},
}),
};
}
const [
{ teamMembersMatchingAttributeLogicMap, attributesDataPerUser },
ttTeamMembersMatchingAttributeLogic,
] = await aPf(async () =>
getLogicResultForAllMembers(
{
teamMembersWithAttributeOptionValuePerAttribute,
attributeJsonLogic: logic,
attributesQueryValue,
},
{
concurrency,
enableTroubleshooter,
}
)
);
const teamMembersMatchingAttributeLogic = Array.from(teamMembersMatchingAttributeLogicMap).map((item) => ({
userId: item[0],
result: item[1],
}));
return {
teamMembersMatchingAttributeLogic,
logicBuildingWarnings,
timeTaken: {
ttgetAttributesQueryBuilderConfigHavingListofLabels,
ttTeamMembersMatchingAttributeLogic,
},
...buildTroubleshooterData({
type: TroubleshooterCase.MATCH_RESULTS_READY,
data: {
attributesDataPerUser,
attributesQueryValue,
attributesQueryBuilderConfig,
logic,
attributesOfTheOrg,
},
}),
};
function pf<ReturnValue>(fn: () => ReturnValue): [ReturnValue, number | null] {
if (!enablePerf) {
return [fn(), null];
}
return perf(fn);
}
async function aPf<ReturnValue>(fn: () => Promise<ReturnValue>): Promise<[ReturnValue, number | null]> {
if (!enablePerf) {
return [await fn(), null];
}
return asyncPerf(fn);
}
}
async function runMainAttributeLogic(data: RunAttributeLogicData, options: RunAttributeLogicOptions) {
const { teamMembersMatchingAttributeLogic, ...rest } = await runAttributeLogic(data, options);
return {
teamMembersMatchingMainAttributeLogic: teamMembersMatchingAttributeLogic,
...rest,
};
}
async function runFallbackAttributeLogic(data: RunAttributeLogicData, options: RunAttributeLogicOptions) {
const { teamMembersMatchingAttributeLogic, ...rest } = await runAttributeLogic(data, options);
return {
teamMembersMatchingFallbackLogic: teamMembersMatchingAttributeLogic,
...rest,
};
}
export async function getAttributesForLogic({ teamId, orgId }: { teamId: number; orgId: number }) {
const [result, ttAttributes] = await asyncPerf(async () => {
return getAttributesAssignmentData({ teamId, orgId });
});
return {
attributesOfTheOrg: result.attributesOfTheOrg,
teamMembersWithAttributeOptionValuePerAttribute: result.attributesAssignedToTeamMembersWithOptions,
timeTaken: ttAttributes,
};
}
export async function findTeamMembersMatchingAttributeLogic(
data: {
teamId: number;
orgId: number;
attributesQueryValue: AttributesQueryValue | null;
fallbackAttributesQueryValue?: AttributesQueryValue | null;
dynamicFieldValueOperands?: dynamicFieldValueOperands;
isPreview?: boolean;
},
options: {
enablePerf?: boolean;
concurrency?: number;
enableTroubleshooter?: boolean;
} = {}
) {
// Higher value of concurrency might not be performant as it might overwhelm the system. So, use a lower value as default.
const { enablePerf = false, concurrency = 2, enableTroubleshooter = false } = options;
// Any explicit value being passed should cause fallback to be considered. Even undefined
const considerFallback = "fallbackAttributesQueryValue" in data;
const {
teamId,
orgId,
attributesQueryValue,
fallbackAttributesQueryValue,
dynamicFieldValueOperands,
isPreview,
} = data;
const {
attributesOfTheOrg,
teamMembersWithAttributeOptionValuePerAttribute,
timeTaken: ttGetAttributesForLogic,
} = await getAttributesForLogic({
teamId,
orgId,
});
const runAttributeLogicOptions = {
concurrency,
enablePerf,
isPreview: !!isPreview,
enableTroubleshooter,
};
const runAttributeLogicData: Omit<RunAttributeLogicData, "attributesQueryValue"> = {
// Change it as per the main/fallback query
attributesData: {
attributesOfTheOrg,
teamMembersWithAttributeOptionValuePerAttribute,
},
dynamicFieldValueOperands,
};
const {
teamMembersMatchingMainAttributeLogic,
timeTaken: teamMembersMatchingMainAttributeLogicTimeTaken,
troubleshooter,
logicBuildingWarnings: mainAttributeLogicBuildingWarnings,
} = await runMainAttributeLogic(
{
...runAttributeLogicData,
attributesQueryValue: attributesQueryValue,
},
runAttributeLogicOptions
);
// It being null means that no logic was found and thus all members match. In such case, we don't fallback intentionally.
// This is the case when user added no rules so, he expects to match all members
if (!teamMembersMatchingMainAttributeLogic) {
return {
teamMembersMatchingAttributeLogic: null,
checkedFallback: false,
mainAttributeLogicBuildingWarnings,
fallbackAttributeLogicBuildingWarnings: [],
timeTaken: {
...teamMembersMatchingMainAttributeLogicTimeTaken,
ttGetAttributesForLogic,
},
...(enableTroubleshooter
? buildTroubleshooterData({
...troubleshooter,
})
: null),
};
}
const noMatchingMembersFound = !teamMembersMatchingMainAttributeLogic.length;
if (noMatchingMembersFound && considerFallback) {
const {
teamMembersMatchingFallbackLogic,
timeTaken: teamMembersMatchingFallbackLogicTimeTaken,
troubleshooter,
logicBuildingWarnings: fallbackAttributeLogicBuildingWarnings,
} = await runFallbackAttributeLogic(
{
...runAttributeLogicData,
attributesQueryValue: fallbackAttributesQueryValue ?? null,
},
runAttributeLogicOptions
);
return {
teamMembersMatchingAttributeLogic: teamMembersMatchingFallbackLogic,
checkedFallback: true,
fallbackAttributeLogicBuildingWarnings,
mainAttributeLogicBuildingWarnings,
timeTaken: {
...teamMembersMatchingFallbackLogicTimeTaken,
ttGetAttributesForLogic,
},
...(enableTroubleshooter
? buildTroubleshooterData({
...troubleshooter,
type: TroubleshooterCase.MATCH_RESULTS_READY_WITH_FALLBACK,
})
: null),
};
}
return {
teamMembersMatchingAttributeLogic: teamMembersMatchingMainAttributeLogic,
checkedFallback: false,
mainAttributeLogicBuildingWarnings,
fallbackAttributeLogicBuildingWarnings: [],
timeTaken: {
...teamMembersMatchingMainAttributeLogicTimeTaken,
ttGetAttributesForLogic,
},
...(enableTroubleshooter
? buildTroubleshooterData({
...troubleshooter,
type: TroubleshooterCase.MATCH_RESULTS_READY,
data: {
...troubleshooter.data,
attributesOfTheOrg,
},
})
: null),
};
}
@@ -7,7 +7,6 @@ import { beforeEach, describe, expect, it, vi } from "vitest";
import { getAbsoluteEventTypeRedirectUrlWithEmbedSupport } from "@calcom/app-store/routing-forms/getEventTypeRedirectUrl";
import { getResponseToStore } from "@calcom/app-store/routing-forms/lib/getResponseToStore";
import { getSerializableForm } from "@calcom/app-store/routing-forms/lib/getSerializableForm";
import { handleResponse } from "@calcom/app-store/routing-forms/lib/handleResponse";
import { findMatchingRoute } from "@calcom/app-store/routing-forms/lib/processRoute";
import { substituteVariables } from "@calcom/app-store/routing-forms/lib/substituteVariables";
import { orgDomainConfig } from "@calcom/features/ee/organizations/lib/orgDomains";
@@ -18,11 +17,12 @@ import { checkRateLimitAndThrowError } from "@calcom/lib/checkRateLimitAndThrowE
import { getRoutedUrl } from "./getRoutedUrl";
import { getUrlSearchParamsToForward } from "./getUrlSearchParamsToForward";
import { handleResponse } from "./handleResponse";
// Mock dependencies
vi.mock("./getUrlSearchParamsToForward");
vi.mock("./handleResponse");
vi.mock("@calcom/lib/checkRateLimitAndThrowError");
vi.mock("@calcom/app-store/routing-forms/lib/handleResponse");
vi.mock("@calcom/features/routing-forms/repositories/PrismaRoutingFormRepository");
vi.mock("@calcom/features/users/repositories/UserRepository", () => {
return {
@@ -10,7 +10,6 @@ import { getAbsoluteEventTypeRedirectUrlWithEmbedSupport } from "@calcom/app-sto
import { getResponseToStore } from "@calcom/app-store/routing-forms/lib/getResponseToStore";
import { getSerializableForm } from "@calcom/app-store/routing-forms/lib/getSerializableForm";
import { getServerTimingHeader } from "@calcom/app-store/routing-forms/lib/getServerTimingHeader";
import { handleResponse } from "@calcom/app-store/routing-forms/lib/handleResponse";
import { findMatchingRoute } from "@calcom/app-store/routing-forms/lib/processRoute";
import { substituteVariables } from "@calcom/app-store/routing-forms/lib/substituteVariables";
import type { FormResponse } from "@calcom/app-store/routing-forms/types/types";
@@ -28,6 +27,7 @@ import prisma from "@calcom/prisma";
import { TRPCError } from "@trpc/server";
import { getUrlSearchParamsToForward } from "./getUrlSearchParamsToForward";
import { handleResponse } from "./handleResponse";
const log = logger.getSubLogger({ prefix: ["[routing-forms]", "[router]"] });
const querySchema = z
@@ -0,0 +1,345 @@
import "@calcom/lib/__mocks__/logger";
import { prisma } from "@calcom/prisma/__mocks__/prisma";
import { beforeEach, describe, expect, it, vi } from "vitest";
import routerGetCrmContactOwnerEmail from "@calcom/app-store/routing-forms/lib/crmRouting/routerGetCrmContactOwnerEmail";
import type { TargetRoutingFormForResponse } from "@calcom/app-store/routing-forms/lib/formSubmissionUtils";
import { onSubmissionOfFormResponse } from "@calcom/app-store/routing-forms/lib/formSubmissionUtils";
import isRouter from "@calcom/app-store/routing-forms/lib/isRouter";
import { RoutingFormResponseRepository } from "@calcom/lib/server/repository/formResponse";
import { findTeamMembersMatchingAttributeLogic } from "./findTeamMembersMatchingAttributeLogic";
import { handleResponse } from "./handleResponse";
vi.mock("./findTeamMembersMatchingAttributeLogic", () => ({
findTeamMembersMatchingAttributeLogic: vi.fn(),
}));
vi.mock("@calcom/lib/server/repository/formResponse");
const mockRoutingFormResponseRepository = {
recordQueuedFormResponse: vi.fn(),
recordFormResponse: vi.fn(),
};
vi.mock("@calcom/app-store/routing-forms/lib/crmRouting/routerGetCrmContactOwnerEmail", () => ({
default: vi.fn(),
}));
vi.mock("@calcom/app-store/routing-forms/lib/formSubmissionUtils", () => ({
onSubmissionOfFormResponse: vi.fn(),
}));
vi.mock("@calcom/app-store/routing-forms/lib/isRouter", () => ({
default: vi.fn(),
}));
vi.mock("@calcom/lib/sentryWrapper", () => ({
withReporting: (fn: unknown) => fn,
}));
vi.mock("@calcom/prisma", () => ({
prisma,
}));
const mockForm: TargetRoutingFormForResponse = {
id: "form-id",
name: "Test Form",
fields: [
{
id: "name",
label: "Name",
type: "text" as const,
required: true,
identifier: "name",
placeholder: undefined,
selectText: undefined,
deleted: false,
},
{
id: "email",
label: "Email",
type: "email" as const,
required: true,
identifier: "email",
placeholder: undefined,
selectText: undefined,
deleted: false,
},
{
id: "guests",
label: "Guests",
type: "text" as const,
required: false,
identifier: "guests",
placeholder: undefined,
selectText: undefined,
deleted: false,
},
],
routes: [],
userId: 1,
teamId: 1,
user: {
id: 1,
email: "[email protected]",
timeFormat: null,
locale: null,
},
team: {
parentId: 2,
},
createdAt: "2023-01-01T00:00:00.000Z",
updatedAt: "2023-01-01T00:00:00.000Z",
description: null,
disabled: false,
settings: {
emailOwnerOnSubmission: false,
},
connectedForms: [],
routers: [],
teamMembers: [],
position: 0,
updatedById: null,
};
const mockResponse: Record<
string,
{
value: (string | number | string[]) & (string | number | string[] | undefined);
label: string;
identifier?: string | undefined;
}
> = {
name: { value: "John Doe", label: "Name" },
email: { value: "[email protected]", label: "Email" },
};
describe("handleResponse", () => {
beforeEach(() => {
vi.resetAllMocks();
vi.mocked(RoutingFormResponseRepository).mockImplementation(
// eslint-disable-next-line @typescript-eslint/no-explicit-any
() => mockRoutingFormResponseRepository as any
);
});
it("should throw an Error for missing required fields", async () => {
await expect(
handleResponse({
response: { email: { value: "[email protected]", label: "Email" } }, // Name is missing
form: mockForm,
identifierKeyedResponse: null,
formFillerId: "user1",
chosenRouteId: null,
isPreview: false,
})
).rejects.toThrow(/Missing required fields Name/);
});
it("should throw an Error for invalid email", async () => {
await expect(
handleResponse({
response: {
name: { value: "John Doe", label: "Name" },
email: { value: "invalid-email", label: "Email" },
},
form: mockForm,
identifierKeyedResponse: null,
formFillerId: "user1",
chosenRouteId: null,
isPreview: false,
})
).rejects.toThrow(/Invalid value for fields 'Email' with value 'invalid-email' should be valid email/);
});
it("should record form response when not in preview and not queued", async () => {
const dbFormResponse = {
id: 1,
uuid: "d8b4b7d2-3f45-4f67-9aa1-98c4b49cf283",
formId: mockForm.id,
response: mockResponse,
chosenRouteId: null,
formFillerId: "user1",
routedToBookingUid: null,
createdAt: new Date(),
updatedAt: new Date(),
};
vi.mocked(mockRoutingFormResponseRepository.recordFormResponse).mockResolvedValue(dbFormResponse);
const result = await handleResponse({
response: mockResponse,
form: mockForm,
identifierKeyedResponse: null,
formFillerId: "user1",
chosenRouteId: null,
isPreview: false,
});
expect(mockRoutingFormResponseRepository.recordFormResponse).toHaveBeenCalledWith({
formId: mockForm.id,
response: mockResponse,
chosenRouteId: null,
});
expect(onSubmissionOfFormResponse).toHaveBeenCalledWith({
form: mockForm,
formResponseInDb: dbFormResponse,
chosenRouteAction: null,
});
expect(result.formResponse).toEqual(dbFormResponse);
expect(result.queuedFormResponse).toBeNull();
});
it("should queue form response when queueFormResponse is true", async () => {
const queuedResponse = {
id: "queued-id",
formId: mockForm.id,
response: mockResponse,
chosenRouteId: null,
actualResponseId: null,
createdAt: new Date(),
updatedAt: new Date(),
};
vi.mocked(mockRoutingFormResponseRepository.recordQueuedFormResponse).mockResolvedValue(queuedResponse);
const result = await handleResponse({
response: mockResponse,
form: mockForm,
identifierKeyedResponse: null,
formFillerId: "user1",
chosenRouteId: null,
isPreview: false,
queueFormResponse: true,
});
expect(mockRoutingFormResponseRepository.recordQueuedFormResponse).toHaveBeenCalledWith({
formId: mockForm.id,
response: mockResponse,
chosenRouteId: null,
});
expect(mockRoutingFormResponseRepository.recordFormResponse).not.toHaveBeenCalled();
expect(onSubmissionOfFormResponse).not.toHaveBeenCalled();
expect(result.queuedFormResponse).toEqual(queuedResponse);
expect(result.formResponse).toBeNull();
});
describe("Preview mode", () => {
it("should send formResponse with id=0 and quueueFormResponse isn't true", async () => {
const result = await handleResponse({
response: mockResponse,
form: mockForm,
identifierKeyedResponse: null,
formFillerId: "user1",
chosenRouteId: null,
isPreview: true,
});
expect(mockRoutingFormResponseRepository.recordFormResponse).not.toHaveBeenCalled();
expect(onSubmissionOfFormResponse).not.toHaveBeenCalled();
expect(result.isPreview).toBe(true);
expect(result.formResponse).toBeDefined();
expect(result.formResponse?.id).toBe(0);
});
it("should send queuedFormResponse with id=00000000-0000-0000-0000-000000000000 when queueFormResponse is true", async () => {
const result = await handleResponse({
response: mockResponse,
form: mockForm,
identifierKeyedResponse: null,
formFillerId: "user1",
chosenRouteId: null,
isPreview: true,
queueFormResponse: true,
});
expect(mockRoutingFormResponseRepository.recordQueuedFormResponse).not.toHaveBeenCalled();
expect(result.isPreview).toBe(true);
expect(result.queuedFormResponse).toBeDefined();
expect(result.queuedFormResponse?.id).toBe("00000000-0000-0000-0000-000000000000");
expect(result.formResponse).toBeUndefined();
});
});
it("should handle chosen route and call routing logic", async () => {
const chosenRoute = {
id: "route1",
// eslint-disable-next-line @typescript-eslint/no-explicit-any
queryValue: { type: "group", children1: {} } as any,
action: {
type: "customPageMessage" as const,
value: "Thank you for your submission!",
},
attributeRoutingConfig: null,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
attributesQueryValue: { type: "group", children1: {} } as any,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
fallbackAttributesQueryValue: { type: "group", children1: {} } as any,
isFallback: false,
};
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const formWithRoute: TargetRoutingFormForResponse = { ...mockForm, routes: [chosenRoute as any] };
vi.mocked(routerGetCrmContactOwnerEmail).mockResolvedValue({
email: "[email protected]",
recordType: "contact",
crmAppSlug: "hubspot",
recordId: "123",
});
vi.mocked(findTeamMembersMatchingAttributeLogic).mockResolvedValue({
// eslint-disable-next-line @typescript-eslint/no-explicit-any
teamMembersMatchingAttributeLogic: [{ userId: 123, result: "MATCH" as any }],
checkedFallback: false,
fallbackAttributeLogicBuildingWarnings: [],
mainAttributeLogicBuildingWarnings: [],
timeTaken: {
ttGetAttributesForLogic: 50,
},
});
const result = await handleResponse({
response: mockResponse,
form: formWithRoute,
formFillerId: "user1",
chosenRouteId: "route1",
isPreview: false,
identifierKeyedResponse: {
name: "John Doe",
email: "[email protected]",
},
fetchCrm: true,
});
expect(routerGetCrmContactOwnerEmail).toHaveBeenCalled();
expect(findTeamMembersMatchingAttributeLogic).toHaveBeenCalled();
expect(result.crmContactOwnerEmail).toBe("[email protected]");
expect(result.teamMembersMatchingAttributeLogic).toEqual([123]);
});
it("should throw error if chosen route is a router", async () => {
const chosenRoute = {
id: "route1",
name: "A router",
description: "Router description",
isRouter: true as const,
routes: [],
};
vi.mocked(isRouter).mockReturnValue(true);
const formWithRoute: TargetRoutingFormForResponse = {
...mockForm,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
routes: [chosenRoute as any],
};
await expect(
handleResponse({
response: mockResponse,
form: formWithRoute,
identifierKeyedResponse: null,
formFillerId: "user1",
chosenRouteId: "route1",
isPreview: false,
})
).rejects.toThrow(/Chosen route is a router/);
});
});
@@ -0,0 +1,244 @@
import { z } from "zod";
import routerGetCrmContactOwnerEmail from "@calcom/app-store/routing-forms/lib/crmRouting/routerGetCrmContactOwnerEmail";
import {
onSubmissionOfFormResponse,
type TargetRoutingFormForResponse,
} from "@calcom/app-store/routing-forms/lib/formSubmissionUtils";
import isRouter from "@calcom/app-store/routing-forms/lib/isRouter";
import { emailSchema } from "@calcom/lib/emailSchema";
import { HttpError } from "@calcom/lib/http-error";
import logger from "@calcom/lib/logger";
import { safeStringify } from "@calcom/lib/safeStringify";
import { withReporting } from "@calcom/lib/sentryWrapper";
import { RoutingFormResponseRepository } from "@calcom/lib/server/repository/formResponse";
import { prisma } from "@calcom/prisma";
import { Prisma } from "@calcom/prisma/client";
import { findTeamMembersMatchingAttributeLogic } from "./findTeamMembersMatchingAttributeLogic";
const moduleLogger = logger.getSubLogger({ prefix: ["routing-forms/lib/handleResponse"] });
const _handleResponse = async ({
response,
identifierKeyedResponse,
form,
// Unused but probably should be used
// formFillerId,
chosenRouteId,
isPreview,
queueFormResponse,
fetchCrm,
}: {
response: Record<
string,
{
value: string | number | string[];
label: string;
identifier?: string;
}
>;
identifierKeyedResponse: Record<string, string | string[]> | null;
form: TargetRoutingFormForResponse;
formFillerId: string;
chosenRouteId: string | null;
isPreview: boolean;
queueFormResponse?: boolean;
fetchCrm?: boolean;
}) => {
try {
if (!form.fields) {
// There is no point in submitting a form that doesn't have fields defined
throw new HttpError({ statusCode: 400 });
}
const formTeamId = form.teamId;
const formOrgId = form.team?.parentId ?? null;
const serializableFormWithFields = {
...form,
fields: form.fields,
};
const missingFields = serializableFormWithFields.fields
.filter((field) => !(field.required ? response[field.id]?.value : true))
.map((f) => f.label);
if (missingFields.length) {
throw new HttpError({
statusCode: 400,
message: `Missing required fields ${missingFields.join(", ")}`,
});
}
const invalidFields = serializableFormWithFields.fields
.filter((field) => {
const fieldValue = response[field.id]?.value;
// The field isn't required at this point. Validate only if it's set
if (!fieldValue) {
return false;
}
let schema;
if (field.type === "email") {
schema = emailSchema;
} else if (field.type === "phone") {
schema = z.any();
} else {
schema = z.any();
}
return !schema.safeParse(fieldValue).success;
})
.map((f) => ({ label: f.label, type: f.type, value: response[f.id]?.value }));
if (invalidFields.length) {
throw new HttpError({
statusCode: 400,
message: `Invalid value for fields ${invalidFields
.map((f) => `'${f.label}' with value '${f.value}' should be valid ${f.type}`)
.join(", ")}`,
});
}
const chosenRoute = serializableFormWithFields.routes?.find((route) => route.id === chosenRouteId);
let teamMemberIdsMatchingAttributeLogic: number[] | null = null;
let crmContactOwnerEmail: string | null = null;
let crmContactOwnerRecordType: string | null = null;
let crmAppSlug: string | null = null;
let crmRecordId: string | null = null;
let timeTaken: Record<string, number | null> = {};
if (chosenRoute) {
if (isRouter(chosenRoute)) {
throw new HttpError({
statusCode: 400,
message: "Chosen route is a router",
});
}
const getRoutedMembers = async () =>
await Promise.all([
(async () => {
const contactOwnerQuery =
identifierKeyedResponse && fetchCrm
? await routerGetCrmContactOwnerEmail({
attributeRoutingConfig: chosenRoute.attributeRoutingConfig,
identifierKeyedResponse,
action: chosenRoute.action,
})
: null;
crmContactOwnerEmail = contactOwnerQuery?.email ?? null;
crmContactOwnerRecordType = contactOwnerQuery?.recordType ?? null;
crmAppSlug = contactOwnerQuery?.crmAppSlug ?? null;
crmRecordId = contactOwnerQuery?.recordId ?? null;
})(),
(async () => {
const teamMembersMatchingAttributeLogicWithResult =
formTeamId && formOrgId
? await findTeamMembersMatchingAttributeLogic(
{
dynamicFieldValueOperands: {
response,
fields: form.fields || [],
},
attributesQueryValue: chosenRoute.attributesQueryValue ?? null,
fallbackAttributesQueryValue: chosenRoute.fallbackAttributesQueryValue,
teamId: formTeamId,
orgId: formOrgId,
},
{
enablePerf: true,
}
)
: null;
moduleLogger.debug(
"teamMembersMatchingAttributeLogic",
safeStringify({ teamMembersMatchingAttributeLogicWithResult })
);
teamMemberIdsMatchingAttributeLogic =
teamMembersMatchingAttributeLogicWithResult?.teamMembersMatchingAttributeLogic
? teamMembersMatchingAttributeLogicWithResult.teamMembersMatchingAttributeLogic.map(
(member) => member.userId
)
: null;
timeTaken = teamMembersMatchingAttributeLogicWithResult?.timeTaken ?? {};
})(),
]);
await withReporting(getRoutedMembers, "getRoutedMembers")();
} else {
// It currently happens for a Router route. Such a route id isn't present in the form.routes
}
let dbFormResponse, queuedFormResponse;
if (!isPreview) {
const formResponseRepo = new RoutingFormResponseRepository(prisma);
if (queueFormResponse) {
queuedFormResponse = await formResponseRepo.recordQueuedFormResponse({
formId: form.id,
response,
chosenRouteId,
});
dbFormResponse = null;
} else {
dbFormResponse = await formResponseRepo.recordFormResponse({
formId: form.id,
response,
chosenRouteId,
});
queuedFormResponse = null;
await onSubmissionOfFormResponse({
form: serializableFormWithFields,
formResponseInDb: dbFormResponse,
chosenRouteAction: chosenRoute ? ("action" in chosenRoute ? chosenRoute.action : null) : null,
});
}
} else {
moduleLogger.debug("Dry run mode - Form response not stored and also webhooks and emails not sent");
if (queueFormResponse) {
queuedFormResponse = {
id: "00000000-0000-0000-0000-000000000000",
formId: form.id,
response,
};
} else {
// Create a mock response for dry run
dbFormResponse = {
id: 0,
formId: form.id,
response,
chosenRouteId,
createdAt: new Date(),
updatedAt: new Date(),
};
}
}
return {
isPreview: !!isPreview,
formResponse: dbFormResponse,
queuedFormResponse,
teamMembersMatchingAttributeLogic: teamMemberIdsMatchingAttributeLogic,
crmContactOwnerEmail,
crmContactOwnerRecordType,
crmAppSlug,
crmRecordId,
attributeRoutingConfig: chosenRoute
? "attributeRoutingConfig" in chosenRoute
? chosenRoute.attributeRoutingConfig
: null
: null,
timeTaken,
};
} catch (e) {
if (e instanceof Prisma.PrismaClientKnownRequestError) {
if (e.code === "P2002") {
throw new HttpError({
statusCode: 409,
message: "Form response already exists",
});
}
}
throw e;
}
};
export const handleResponse = withReporting(_handleResponse, "handleResponse");
@@ -1,5 +1,5 @@
import { findTeamMembersMatchingAttributeLogic } from "@calcom/app-store/_utils/raqb/findTeamMembersMatchingAttributeLogic";
import { enrichHostsWithDelegationCredentials } from "@calcom/app-store/delegationCredential";
import { findTeamMembersMatchingAttributeLogic } from "@calcom/features/routing-forms/lib/findTeamMembersMatchingAttributeLogic";
import getOrgIdFromMemberOrTeamId from "@calcom/lib/getOrgIdFromMemberOrTeamId";
import logger from "@calcom/lib/logger";
import type { AttributesQueryValue } from "@calcom/lib/raqb/types";