Files
cal.diy/packages/trpc/server/routers/viewer/featureOptIn/_router.ts
T
6501743e5e feat: Add attribute sync logic from Salesforce (#26517)
* Add db schema

* Add `CredentialRepository.findByTeamIdAndSlugs`

* Add enabled app slugs for attribute syncing

* Create repository for `IntegrationAttributeSync`

* Create zod schemas

* Create `AttributeSyncUserRuleOutputMapper`

* Create `IntegrationAttributeSyncService`

* Create DI contianer

* Create trpc endpoints

* Create page

* Include team name in `CredentialRepository.findByTeamIdAndSlugs`

* Update schema and relations

* Update types and schemas

* Add more methods to IntegrationAttributeSyncRepository

* Add more services to `IntegrationAttributeSyncService`
- getById
- Init updateIncludeRulesAndMappings

* Refactor `getTeams.handler` to use repository

* Create `createAttributeSync` trpc endpoint

* Create `updateAttributeSync` trpc endpoint

* Add router to trpc

* Create attribute sync child components

* Pass custom actions to `FormCard`

* Create `IntegrationAttributeSyncCard`

* Pass inital props via server side

* Fix prop

* Only refetch on mutation

* Fixes

* Add form error when duplicate field and attribute combo

* Add `updateTransactionWithRUleAndMappings` logic

* Adjust zod schemas

* Service add `updateIncludeRulesAndMappings`

* Pass orgId from server to component

* Rename types

* Add deleteById method to repository

* Add name to integrationAttributeSync

* Add deleteById method to service

* Rename method

* Add deleteAttributeSync trpc endpoint

* Make the IntegrationAttributeSyncCard a dummy component

* test: add tests for IntegrationAttributeSync feature

Co-Authored-By: joe@cal.com <j.auyeung419@gmail.com>

* Move creating a attribute sync record to the service

* Add i18n strings

* Safe select credential in find by id and team

* Fix default credentialId value in form

* Update repository return types

* Add i18n string

* Make credentialId optional for form schema

* Fix label

* Add cascade deletes

* Add verification that syncs belong to org

* Create mapper for repository output

* Type fixes

* Remove old test file

* Pass `attributeOptions` from parent to children

* Infer types from zod schema

* Type fixes

* Type fix

* Clean up

* Add i18n strings

* Remove unused file

* Address feedback

* Add migration file

* Address feedback

* Add validation for new integration values

* Remove unused router

* Move away from z.infer to z.ZodType

* Clean up comments

* Type fix

* Type fixes

* Type fix

* fix: add passthrough to syncFormDataSchema to preserve extra fields

Co-Authored-By: joe@cal.com <j.auyeung419@gmail.com>

* fix: remove incorrect test that expected extra fields to pass through syncFormDataSchema

Co-Authored-By: joe@cal.com <j.auyeung419@gmail.com>

* Add endpoint for SF to call

* Create scratch org config

* Create sf cli scripts

* Create package logic

* Update README

* Remove unused file

* Add indexes

* Add aria label

* Address feedback - consistent validation

* Fix import paths for attribute types

* Add `CredentialRepository.findByAppIdAndKeyValue`

* Get credential by instance URL

* Verify incoming sfdc orgId matches credential sfdc orgId

* Rename method

* Get user name integration syncs

* refactor: change attributeSyncRules array to singular attributeSyncRule

The database schema enforces a one-to-one relationship between
IntegrationAttributeSync and AttributeSyncRule (via @unique constraint),
and the UI only supports a single rule. This change makes the TypeScript
type match the database schema and UI behavior.

Changes:
- Update IntegrationAttributeSync interface to use attributeSyncRule: AttributeSyncRule | null
- Update mapper to return singular rule instead of wrapping in array
- Update UI component to access sync.attributeSyncRule directly
- Update IIntegrationAttributeSyncUpdateParams Omit type
- Update tests to use attributeSyncRule: null instead of attributeSyncRules: []

Co-Authored-By: joe@cal.com <j.auyeung419@gmail.com>

* Convert `membershipRepository.findAllByUserId` to a normal method

* Add temp files to git ignore

* Init  and process team conditions

* Biome formatting

* Add `AttributeService` to get user attributes

* Add DI container for AttributeService

* AttributeSyncService evaluate attribute conditions

* Create DI container for attributeSyncService

* Return result for full condition

* Evaluate if attribute sync should apply to user

* Add  method

* Change PrismaAttributeOptionRepository to instance methods

* Init AttributeSyncFieldMappingsService and process attribute syncs

* Add AttributeSyncFieldMappingService DI container

* Refactor orgId to organizationId

* Add membership validation to sync field service

* AttributeSYncFieldMappingService use repository methods

* AttributeSyncFieldMappingService.processMappings add mapping logic

* Add DI tokens

* user-sync endpoint to implement attribute syncing

* Validate team belongs to org for rule

* test: add tests for AttributeSyncRuleService, AttributeSyncFieldMappingService, and AttributeService

Co-Authored-By: joe@cal.com <j.auyeung419@gmail.com>

* Remove duplicate migration file

* Fix merge conflict

* fix: resolve type errors in attribute sync feature (#26814)

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* Rename  variable

* Fix log typo

* Fix file name

* Add error logging

* Use credential teamId

* fix: add missing mockTeamRepository and team validation to tests

Co-Authored-By: joe@cal.com <j.auyeung419@gmail.com>

* Fix naming

* Fix file import

* Type fix

* Pass MembershipRepository as a dep in AttributeSyncFieldMappingService

* Type fix

* fix: add mockMembershipRepository to AttributeSyncFieldMappingService tests

Co-Authored-By: joe@cal.com <j.auyeung419@gmail.com>

* Update packages/app-store/salesforce/api/user-sync.ts

Add error handling when getting orgId from stored salesforce id

Co-authored-by: cubic-dev-ai[bot] <191113872+cubic-dev-ai[bot]@users.noreply.github.com>

* fix: address Cubic code review comments

- PrismaAttributeRepository: use nested select instead of include: true for options
- CredentialRepository: use this.primaClient instead of global prisma, use select instead of include for relations
- AttributeSyncFieldMappingService: optimize O(n*m) complexity with Map lookup for O(1) access

Co-Authored-By: joe@cal.com <j.auyeung419@gmail.com>

* Fix typo in CredentialRepository

* Update README

* Update sfdx-project

* Add SFDC package tests

* fix: improve Salesforce Apex test assertions to verify actual behavior

- Enhanced CalComHttpMock to track HTTP callout invocations and capture requests
- Updated UserUpdateHandlerTest to verify HTTP callouts are made with correct data
- Updated CalComCalloutQueueableTest to verify HTTP callouts are made correctly
- Replaced System.assert(true, ...) with meaningful assertions that verify:
  - Correct number of HTTP callouts
  - Request body contains expected fields
  - Request method is POST

Addresses Cubic AI review feedback (confidence 9/10 issues only)

Co-Authored-By: unknown <>

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-authored-by: Hariom Balhara <hariombalhara@gmail.com>
Co-authored-by: cubic-dev-ai[bot] <191113872+cubic-dev-ai[bot]@users.noreply.github.com>
2026-01-15 09:19:57 -05:00

239 lines
7.3 KiB
TypeScript

import type { ZodEnum } from "zod";
import { z } from "zod";
import { getFeatureOptInService } from "@calcom/features/di/containers/FeatureOptInService";
import { TeamRepository } from "@calcom/features/ee/teams/repositories/TeamRepository";
import { isOptInFeature } from "@calcom/features/feature-opt-in/config";
import { FeaturesRepository } from "@calcom/features/flags/features.repository";
import { MembershipRepository } from "@calcom/features/membership/repositories/MembershipRepository";
import { prisma } from "@calcom/prisma";
import { TRPCError } from "@trpc/server";
import authedProcedure from "../../../procedures/authedProcedure";
import { router } from "../../../trpc";
import { createOrgPbacProcedure, createTeamPbacProcedure } from "../../../procedures/pbacProcedures";
const featureStateSchema: ZodEnum<["enabled", "disabled", "inherit"]> = z.enum(["enabled", "disabled", "inherit"]);
const featureOptInService = getFeatureOptInService();
const featuresRepository = new FeaturesRepository(prisma);
const teamRepository = new TeamRepository(prisma);
const membershipRepository = new MembershipRepository(prisma);
/**
* Helper to get user's org and team IDs from their memberships.
* Returns orgId (if user belongs to an org) and teamIds (non-org teams).
*/
async function getUserOrgAndTeamIds(userId: number): Promise<{ orgId: number | null; teamIds: number[] }> {
const memberships = await membershipRepository.findAllByUserId({
userId,
filters: { accepted: true },
});
let orgId: number | null = null;
const teamIds: number[] = [];
for (const membership of memberships) {
if (membership.team.isOrganization) {
orgId = membership.teamId;
} else {
teamIds.push(membership.teamId);
}
}
return { orgId, teamIds };
}
export const featureOptInRouter = router({
/**
* Get all opt-in features with states for current user.
* This considers all teams/orgs the user belongs to.
*/
listForUser: authedProcedure.query(async ({ ctx }) => {
const { orgId, teamIds } = await getUserOrgAndTeamIds(ctx.user.id);
return featureOptInService.listFeaturesForUser({
userId: ctx.user.id,
orgId,
teamIds,
});
}),
/**
* Get all opt-in features with states for a team settings page.
* Used by team admins to configure feature opt-in for their team.
* Also returns the organization state if the team belongs to an organization.
*/
listForTeam: createTeamPbacProcedure("featureOptIn.read").query(async ({ input }) => {
// Get the team's parent organization ID (if any)
const parentOrg = await teamRepository.findParentOrganizationByTeamId(input.teamId);
const parentOrgId = parentOrg?.id ?? null;
return featureOptInService.listFeaturesForTeam({ teamId: input.teamId, parentOrgId, scope: "team" });
}),
/**
* Get all opt-in features with states for organization settings page.
* Used by org admins to configure feature opt-in for their organization.
*/
listForOrganization: createOrgPbacProcedure("featureOptIn.read").query(async ({ ctx }) => {
// Organizations use the same listFeaturesForTeam since they're stored in TeamFeatures
// Pass scope: "org" to filter features that are scoped to organizations
return featureOptInService.listFeaturesForTeam({ teamId: ctx.organizationId, scope: "org" });
}),
/**
* Set user's feature state.
*/
setUserState: authedProcedure
.input(
z.object({
slug: z.string(),
state: featureStateSchema,
})
)
.mutation(async ({ ctx, input }) => {
if (!isOptInFeature(input.slug)) {
throw new TRPCError({
code: "BAD_REQUEST",
message: "Invalid slug. This feature is not opt-in configurable.",
});
}
await featureOptInService.setUserFeatureState({
userId: ctx.user.id,
featureId: input.slug,
state: input.state,
assignedBy: ctx.user.id,
});
return { success: true };
}),
/**
* Set team's feature state (requires team admin).
*/
setTeamState: createTeamPbacProcedure("featureOptIn.update")
.input(
z.object({
slug: z.string(),
state: featureStateSchema,
})
)
.mutation(async ({ ctx, input }) => {
if (!isOptInFeature(input.slug)) {
throw new TRPCError({
code: "BAD_REQUEST",
message: "Invalid slug. This feature is not opt-in configurable.",
});
}
await featureOptInService.setTeamFeatureState({
teamId: input.teamId,
featureId: input.slug,
state: input.state,
assignedBy: ctx.user.id,
scope: "team",
});
return { success: true };
}),
/**
* Set organization's feature state (requires org admin).
*/
setOrganizationState: createOrgPbacProcedure("featureOptIn.update")
.input(
z.object({
slug: z.string(),
state: featureStateSchema,
})
)
.mutation(async ({ ctx, input }) => {
if (!isOptInFeature(input.slug)) {
throw new TRPCError({
code: "BAD_REQUEST",
message: "Invalid slug. This feature is not opt-in configurable.",
});
}
// Organizations use the same TeamFeatures table
await featureOptInService.setTeamFeatureState({
teamId: ctx.organizationId,
featureId: input.slug,
state: input.state,
assignedBy: ctx.user.id,
scope: "org",
});
return { success: true };
}),
/**
* Get user's auto opt-in preference.
*/
getUserAutoOptIn: authedProcedure.query(async ({ ctx }) => {
const autoOptIn = await featuresRepository.getUserAutoOptIn(ctx.user.id);
return { autoOptIn };
}),
/**
* Set user's auto opt-in preference.
*/
setUserAutoOptIn: authedProcedure
.input(
z.object({
autoOptIn: z.boolean(),
})
)
.mutation(async ({ ctx, input }) => {
await featuresRepository.setUserAutoOptIn(ctx.user.id, input.autoOptIn);
return { success: true };
}),
/**
* Get team's auto opt-in preference (requires team admin).
*/
getTeamAutoOptIn: createTeamPbacProcedure("featureOptIn.read").query(async ({ input }) => {
const result = await featuresRepository.getTeamsAutoOptIn([input.teamId]);
return { autoOptIn: result[input.teamId] ?? false };
}),
/**
* Set team's auto opt-in preference (requires team admin).
*/
setTeamAutoOptIn: createTeamPbacProcedure("featureOptIn.update")
.input(
z.object({
autoOptIn: z.boolean(),
})
)
.mutation(async ({ input }) => {
await featuresRepository.setTeamAutoOptIn(input.teamId, input.autoOptIn);
return { success: true };
}),
/**
* Get organization's auto opt-in preference (requires org admin).
*/
getOrganizationAutoOptIn: createOrgPbacProcedure("featureOptIn.read").query(async ({ ctx }) => {
const result = await featuresRepository.getTeamsAutoOptIn([ctx.organizationId]);
return { autoOptIn: result[ctx.organizationId] ?? false };
}),
/**
* Set organization's auto opt-in preference (requires org admin).
*/
setOrganizationAutoOptIn: createOrgPbacProcedure("featureOptIn.update")
.input(
z.object({
autoOptIn: z.boolean(),
})
)
.mutation(async ({ ctx, input }) => {
await featuresRepository.setTeamAutoOptIn(ctx.organizationId, input.autoOptIn);
return { success: true };
}),
});