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;
}
}