feat: Create Integration Attribute Sync records (#26007)
* 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: [email protected] <[email protected]> * 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: [email protected] <[email protected]> * fix: remove incorrect test that expected extra fields to pass through syncFormDataSchema Co-Authored-By: [email protected] <[email protected]> * Add indexes * Add aria label * Address feedback - consistent validation * Fix import paths for attribute types * 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: [email protected] <[email protected]> * feat: implement FeatureOptInService (#25805) * feat: implement FeatureOptInService WIP * clean up * feat: consolidate feature repositories and add updateFeatureForUser - Implement updateFeatureForUser in FeaturesRepository (similar to updateFeatureForTeam) - Move getUserFeatureState and getTeamFeatureState from PrismaFeatureOptInRepository to FeaturesRepository - Update FeatureOptInService to use only FeaturesRepository - Add setUserFeatureState and setTeamFeatureState methods to FeatureOptInService - Update _router.ts to remove PrismaFeatureOptInRepository usage - Remove PrismaFeatureOptInRepository.ts and FeatureOptInRepositoryInterface.ts - Update features.repository.interface.ts and features.repository.mock.ts - Add integration tests for updateFeatureForUser, getUserFeatureState, getTeamFeatureState - Update service.integration-test.ts to use FeaturesRepository Co-Authored-By: [email protected] <[email protected]> * refactor: rename updateFeatureForUser to setUserFeatureState Rename to match the convention used for setTeamFeatureState Co-Authored-By: [email protected] <[email protected]> * refactor: return FeatureState type from getUserFeatureState and getTeamFeatureState * fix integration tests * clean up logics * update services and router * refactor: change getUserFeatureState and getTeamFeatureState to accept featureIds array - Renamed getUserFeatureState to getUserFeatureStates - Renamed getTeamFeatureState to getTeamFeatureStates - Changed parameter from featureId: string to featureIds: string[] - Changed return type from FeatureState to Record<string, FeatureState> - Updated FeatureOptInService to use the new batch methods - Added tests for querying multiple features in a single call - Optimized listFeaturesForTeam to fetch all feature states in one query Co-Authored-By: [email protected] <[email protected]> * feat: add getFeatureStateForTeams for batch querying multiple teams - Added getFeatureStateForTeams method to query a single feature across multiple teams in one call - Updated FeatureOptInService.resolveFeatureStateAcrossTeams to use the new batch method - Replaces N+1 queries with a single database query for team states - Added comprehensive integration tests for the new method Co-Authored-By: [email protected] <[email protected]> * refactor: combine org and team state queries into single call - Include orgId in the teamIds array passed to getFeatureStateForTeams - Extract org state and team states from the combined result - Reduces database queries from 3 to 2 in resolveFeatureStateAcrossTeams Co-Authored-By: [email protected] <[email protected]> * refactor: use team.isOrganization and clarify computeEffectiveState comment Co-Authored-By: [email protected] <[email protected]> * refactor: use MembershipRepository.findAllByUserId with isOrganization Co-Authored-By: [email protected] <[email protected]> * feat: add featureId validation using isOptInFeature type guard Co-Authored-By: [email protected] <[email protected]> * less queries * add fallback value * fix type error * move files * add autoOptInFeatures column * use autoOptInFeatures flag within FeatureOptInService * add setUserAutoOptIn and setTeamAutoOptIn * fix computeEffectiveState logic * rewrite computeEffectiveState * clean up integration tests * clean up in afterEach * fix type error * refactor: use FeaturesRepository methods instead of direct Prisma calls Replace all manual userFeatures and teamFeatures Prisma operations with the new setUserFeatureState and setTeamFeatureState repository methods. Changes include: - Admin handlers (assignFeatureToTeam, unassignFeatureFromTeam) - Test fixtures and integration tests - Playwright fixtures - Development scripts This ensures consistent feature flag management through the repository pattern and supports the new tri-state semantics (enabled/disabled/inherit). Co-Authored-By: [email protected] <[email protected]> * clean up * fix the logic * extract some logic into applyAutoOptIn() * remove wrong code * refactor: convert setUserFeatureState and setTeamFeatureState to object params with discriminated union - Convert multiple positional parameters to single object parameter - Use discriminated union types: assignedBy required for enabled/disabled, omitted for inherit - Update all callers across repository, service, handlers, fixtures, and tests * fix type error * use Promise.all * fix --------- Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * Prevent duplicate field and attribute mappings * Add validation that attribute belongs to the org * fix: address Cubic AI review feedback - Add @@index([credentialId]) to IntegrationAttributeSync model for efficient cascade deletes and credential-based queries (confidence: 9/10) - Fix translation key from 'credential_required' to 'attribute_sync_credential_required' to match existing locale definition (confidence: 10/10) Co-Authored-By: [email protected] <[email protected]> * fix: address remaining cubic review feedback - RuleBuilder.tsx: Use unique IDs for React keys instead of array index to prevent reconciliation bugs when removing conditions - updateAttributeSync.handler.ts: Add early organization check before service calls for consistency - createAttributeSync.handler.ts: Add CredentialNotFoundError class for type-safe error handling instead of string matching - IntegrationAttributeSyncService.test.ts: Replace expect.fail() with proper Vitest rejects.toSatisfy() pattern Co-Authored-By: [email protected] <[email protected]> * Pull test file from main --------- Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> Co-authored-by: Eunjae Lee <[email protected]>
This commit is contained in:
40 files changed
+3524
-19
No files matched your search
@@ -10,6 +10,7 @@ import { aiVoiceAgentRouter } from "./aiVoiceAgent/_router";
|
||||
import { apiKeysRouter } from "./apiKeys/_router";
|
||||
import { appsRouter } from "./apps/_router";
|
||||
import { attributesRouter } from "./attributes/_router";
|
||||
import { attributeSyncRouter } from "./attribute-sync/_router";
|
||||
import { authRouter } from "./auth/_router";
|
||||
import { availabilityRouter } from "./availability/_router";
|
||||
import { bookingsRouter } from "./bookings/_router";
|
||||
@@ -83,6 +84,7 @@ export const viewerRouter = router({
|
||||
googleWorkspace: googleWorkspaceRouter,
|
||||
admin: adminRouter,
|
||||
attributes: attributesRouter,
|
||||
attributeSync: attributeSyncRouter,
|
||||
routingForms: routingFormsRouter,
|
||||
credits: creditsRouter,
|
||||
ooo: oooRouter,
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
import { router } from "../../../trpc";
|
||||
import { createAttributeSyncSchema } from "./createAttributeSync.schema";
|
||||
import { deleteAttributeSyncSchema } from "./deleteAttributeSync.schema";
|
||||
import { getAllAttributeSyncsSchema } from "./getAllAttributeSyncs.schema";
|
||||
import { updateAttributeSyncSchema } from "./updateAttributeSync.schema";
|
||||
import { createAttributePbacProcedure } from "./util";
|
||||
|
||||
export const attributeSyncRouter = router({
|
||||
getAllAttributeSyncs: createAttributePbacProcedure("organization.attributes.read")
|
||||
.input(getAllAttributeSyncsSchema)
|
||||
.query(async (opts) => {
|
||||
const { default: handler } = await import("./getAllAttributeSyncs.handler");
|
||||
return handler(opts);
|
||||
}),
|
||||
|
||||
createAttributeSync: createAttributePbacProcedure("organization.attributes.create")
|
||||
.input(createAttributeSyncSchema)
|
||||
.mutation(async (opts) => {
|
||||
const { default: handler } = await import("./createAttributeSync.handler");
|
||||
return handler(opts);
|
||||
}),
|
||||
|
||||
updateAttributeSync: createAttributePbacProcedure("organization.attributes.update")
|
||||
.input(updateAttributeSyncSchema)
|
||||
.mutation(async (opts) => {
|
||||
const { default: handler } = await import("./updateAttributeSync.handler");
|
||||
return handler(opts);
|
||||
}),
|
||||
|
||||
deleteAttributeSync: createAttributePbacProcedure("organization.attributes.delete")
|
||||
.input(deleteAttributeSyncSchema)
|
||||
.mutation(async (opts) => {
|
||||
const { default: handler } = await import("./deleteAttributeSync.handler");
|
||||
return handler(opts);
|
||||
}),
|
||||
});
|
||||
@@ -0,0 +1,65 @@
|
||||
import { getIntegrationAttributeSyncService } from "@calcom/ee/integration-attribute-sync/di/IntegrationAttributeSyncService.container";
|
||||
import {
|
||||
CredentialNotFoundError,
|
||||
DuplicateAttributeWithinSyncError,
|
||||
DuplicateAttributeAcrossSyncsError,
|
||||
} from "@calcom/ee/integration-attribute-sync/services/IntegrationAttributeSyncService";
|
||||
|
||||
import { TRPCError } from "@trpc/server";
|
||||
|
||||
import type { TrpcSessionUser } from "../../../types";
|
||||
import type { ZCreateAttributeSyncSchema } from "./createAttributeSync.schema";
|
||||
|
||||
type CreateAttributeSyncOptions = {
|
||||
ctx: {
|
||||
user: NonNullable<TrpcSessionUser>;
|
||||
};
|
||||
input: ZCreateAttributeSyncSchema;
|
||||
};
|
||||
|
||||
const createAttributeSyncHandler = async ({
|
||||
ctx,
|
||||
input,
|
||||
}: CreateAttributeSyncOptions) => {
|
||||
const org = ctx.user.organization;
|
||||
|
||||
if (!org?.id) {
|
||||
throw new TRPCError({
|
||||
code: "UNAUTHORIZED",
|
||||
message: "You need to be part of an organization to use this feature",
|
||||
});
|
||||
}
|
||||
|
||||
const integrationAttributeSyncService = getIntegrationAttributeSyncService();
|
||||
|
||||
try {
|
||||
return await integrationAttributeSyncService.createAttributeSync(
|
||||
input,
|
||||
org.id
|
||||
);
|
||||
} catch (error) {
|
||||
if (error instanceof CredentialNotFoundError) {
|
||||
throw new TRPCError({
|
||||
code: "NOT_FOUND",
|
||||
message: "Credential not found",
|
||||
});
|
||||
}
|
||||
if (error instanceof DuplicateAttributeWithinSyncError) {
|
||||
throw new TRPCError({
|
||||
code: "BAD_REQUEST",
|
||||
message:
|
||||
"Each attribute can only be mapped once per sync. Please remove duplicate attribute mappings.",
|
||||
});
|
||||
}
|
||||
if (error instanceof DuplicateAttributeAcrossSyncsError) {
|
||||
throw new TRPCError({
|
||||
code: "BAD_REQUEST",
|
||||
message:
|
||||
"An attribute is already mapped in another sync. Each attribute can only be synced from one source.",
|
||||
});
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
|
||||
export default createAttributeSyncHandler;
|
||||
@@ -0,0 +1,17 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import type { ICreateAttributeSyncInput } from "@calcom/features/ee/integration-attribute-sync/repositories/IIntegrationAttributeSyncRepository";
|
||||
import {
|
||||
attributeSyncRuleSchema,
|
||||
newFieldMappingSchema,
|
||||
} from "@calcom/features/ee/integration-attribute-sync/schemas/zod";
|
||||
|
||||
export const createAttributeSyncSchema: z.ZodType<ICreateAttributeSyncInput> = z.object({
|
||||
name: z.string().min(1, "Name is required"),
|
||||
credentialId: z.number(),
|
||||
rule: attributeSyncRuleSchema,
|
||||
syncFieldMappings: z.array(newFieldMappingSchema),
|
||||
enabled: z.boolean(),
|
||||
});
|
||||
|
||||
export type ZCreateAttributeSyncSchema = ICreateAttributeSyncInput;
|
||||
@@ -0,0 +1,29 @@
|
||||
import { getIntegrationAttributeSyncService } from "@calcom/ee/integration-attribute-sync/di/IntegrationAttributeSyncService.container";
|
||||
|
||||
import { TRPCError } from "@trpc/server";
|
||||
|
||||
import type { TrpcSessionUser } from "../../../types";
|
||||
import type { ZDeleteAttributeSyncSchema } from "./deleteAttributeSync.schema";
|
||||
|
||||
type DeleteAttributeSyncOptions = {
|
||||
ctx: {
|
||||
user: NonNullable<TrpcSessionUser>;
|
||||
};
|
||||
input: ZDeleteAttributeSyncSchema;
|
||||
};
|
||||
|
||||
const deleteAttributeSyncHandler = async ({ ctx, input }: DeleteAttributeSyncOptions) => {
|
||||
const currentUserOrgId = ctx.user.organizationId;
|
||||
const integrationAttributeSyncService = getIntegrationAttributeSyncService();
|
||||
|
||||
const integrationAttributeSync = await integrationAttributeSyncService.getById(input.id);
|
||||
|
||||
if (!integrationAttributeSync) throw new TRPCError({ code: "NOT_FOUND" });
|
||||
|
||||
if (integrationAttributeSync.organizationId !== currentUserOrgId) {
|
||||
throw new TRPCError({ code: "UNAUTHORIZED" });
|
||||
}
|
||||
await integrationAttributeSyncService.deleteById(input.id);
|
||||
};
|
||||
|
||||
export default deleteAttributeSyncHandler;
|
||||
@@ -0,0 +1,7 @@
|
||||
import { z } from "zod";
|
||||
|
||||
export const deleteAttributeSyncSchema = z.object({
|
||||
id: z.string(),
|
||||
});
|
||||
|
||||
export type ZDeleteAttributeSyncSchema = z.infer<typeof deleteAttributeSyncSchema>;
|
||||
@@ -0,0 +1,30 @@
|
||||
import { getIntegrationAttributeSyncService } from "@calcom/features/ee/integration-attribute-sync/di/IntegrationAttributeSyncService.container";
|
||||
|
||||
import { TRPCError } from "@trpc/server";
|
||||
|
||||
import type { TrpcSessionUser } from "../../../types";
|
||||
import type { ZGetAllAttributeSyncsSchema } from "./getAllAttributeSyncs.schema";
|
||||
|
||||
type GetAllAttributeSyncsOptions = {
|
||||
ctx: {
|
||||
user: NonNullable<TrpcSessionUser>;
|
||||
};
|
||||
input: ZGetAllAttributeSyncsSchema;
|
||||
};
|
||||
|
||||
const getAllAttributeSyncsHandler = async ({ ctx }: GetAllAttributeSyncsOptions) => {
|
||||
const org = ctx.user.organization;
|
||||
|
||||
if (!org?.id) {
|
||||
throw new TRPCError({
|
||||
code: "UNAUTHORIZED",
|
||||
message: "You need to be part of an organization to use this feature",
|
||||
});
|
||||
}
|
||||
|
||||
const service = getIntegrationAttributeSyncService();
|
||||
|
||||
return await service.getAllIntegrationAttributeSyncs(org.id);
|
||||
};
|
||||
|
||||
export default getAllAttributeSyncsHandler;
|
||||
@@ -0,0 +1,6 @@
|
||||
import { z } from "zod";
|
||||
|
||||
// No input required - organizationId comes from context
|
||||
export const getAllAttributeSyncsSchema = z.object({});
|
||||
|
||||
export type ZGetAllAttributeSyncsSchema = z.infer<typeof getAllAttributeSyncsSchema>;
|
||||
@@ -0,0 +1,65 @@
|
||||
import { getIntegrationAttributeSyncService } from "@calcom/ee/integration-attribute-sync/di/IntegrationAttributeSyncService.container";
|
||||
import {
|
||||
DuplicateAttributeWithinSyncError,
|
||||
DuplicateAttributeAcrossSyncsError,
|
||||
} from "@calcom/ee/integration-attribute-sync/services/IntegrationAttributeSyncService";
|
||||
|
||||
import { TRPCError } from "@trpc/server";
|
||||
|
||||
import type { TrpcSessionUser } from "../../../types";
|
||||
import { ZUpdateAttributeSyncSchema } from "./updateAttributeSync.schema";
|
||||
|
||||
type UpdateAttributeSyncOptions = {
|
||||
ctx: {
|
||||
user: NonNullable<TrpcSessionUser>;
|
||||
};
|
||||
input: ZUpdateAttributeSyncSchema;
|
||||
};
|
||||
|
||||
const updateAttributeSyncHandler = async ({
|
||||
ctx,
|
||||
input,
|
||||
}: UpdateAttributeSyncOptions) => {
|
||||
const org = ctx.user.organization;
|
||||
|
||||
if (!org?.id) {
|
||||
throw new TRPCError({
|
||||
code: "UNAUTHORIZED",
|
||||
message: "You need to be part of an organization to use this feature",
|
||||
});
|
||||
}
|
||||
|
||||
const integrationAttributeSyncService = getIntegrationAttributeSyncService();
|
||||
|
||||
// Verify the sync exists and belongs to the user's organization
|
||||
const integrationAttributeSync =
|
||||
await integrationAttributeSyncService.getById(input.id);
|
||||
|
||||
if (!integrationAttributeSync) throw new TRPCError({ code: "NOT_FOUND" });
|
||||
|
||||
if (integrationAttributeSync.organizationId !== org.id) {
|
||||
throw new TRPCError({ code: "UNAUTHORIZED" });
|
||||
}
|
||||
|
||||
try {
|
||||
await integrationAttributeSyncService.updateIncludeRulesAndMappings(input);
|
||||
} catch (error) {
|
||||
if (error instanceof DuplicateAttributeWithinSyncError) {
|
||||
throw new TRPCError({
|
||||
code: "BAD_REQUEST",
|
||||
message:
|
||||
"Each attribute can only be mapped once per sync. Please remove duplicate attribute mappings.",
|
||||
});
|
||||
}
|
||||
if (error instanceof DuplicateAttributeAcrossSyncsError) {
|
||||
throw new TRPCError({
|
||||
code: "BAD_REQUEST",
|
||||
message:
|
||||
"This attribute is already mapped in another sync. Each attribute can only be synced from one source.",
|
||||
});
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
|
||||
export default updateAttributeSyncHandler;
|
||||
@@ -0,0 +1,20 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import type { IUpdateAttributeSyncInput } from "@calcom/features/ee/integration-attribute-sync/repositories/IIntegrationAttributeSyncRepository";
|
||||
import {
|
||||
attributeSyncRuleSchema,
|
||||
fieldMappingWithOptionalIdSchema,
|
||||
} from "@calcom/features/ee/integration-attribute-sync/schemas/zod";
|
||||
|
||||
export const updateAttributeSyncSchema: z.ZodType<IUpdateAttributeSyncInput> = z.object({
|
||||
id: z.string(),
|
||||
name: z.string().min(1, "Name is required"),
|
||||
credentialId: z.number().optional(),
|
||||
enabled: z.boolean(),
|
||||
organizationId: z.number(),
|
||||
ruleId: z.string(),
|
||||
rule: attributeSyncRuleSchema,
|
||||
syncFieldMappings: z.array(fieldMappingWithOptionalIdSchema),
|
||||
});
|
||||
|
||||
export type ZUpdateAttributeSyncSchema = IUpdateAttributeSyncInput;
|
||||
@@ -0,0 +1,2 @@
|
||||
// Re-export the attribute PBAC procedure for reuse in attribute-sync endpoints
|
||||
export { createAttributePbacProcedure } from "../attributes/util";
|
||||
@@ -1,3 +1,4 @@
|
||||
import { TeamRepository } from "@calcom/features/ee/teams/repositories/TeamRepository";
|
||||
import { PermissionCheckService } from "@calcom/features/pbac/services/permission-check.service";
|
||||
import { prisma } from "@calcom/prisma";
|
||||
import { MembershipRole } from "@calcom/prisma/enums";
|
||||
@@ -34,10 +35,9 @@ export async function getTeamsHandler({ ctx }: GetTeamsHandler) {
|
||||
});
|
||||
}
|
||||
|
||||
const allOrgTeams = await prisma.team.findMany({
|
||||
where: {
|
||||
parentId: currentUserOrgId,
|
||||
},
|
||||
const teamRepository = new TeamRepository(prisma);
|
||||
const allOrgTeams = await teamRepository.findAllByParentId({
|
||||
parentId: currentUserOrgId,
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
|
||||
Reference in new issue
Block a user