feat: Use RoutingTraceService to write assignment reasons (#27225)
* Add DB schema * Init zod schema * Init RoutingTrace and PendingRoutingTrace repository interfaces * Create PrismaPendingRoutingTraceRepository * Init RoutingTraceService * Create RoutingTraceService container * User routing trace service in routing * Create RoutingTraceRepository and PrismaRoutingTraceRepoistory * Add findByFormResponseId and findByQueuedFormResponseId to PendingRoutingTraceRepository * Update DI containers * RoutingTraceService create process booking method * Use pending routing trace rather than URL params * Fix schema * Fix writing assignment reason for routed booking * Remove from service * Refactor RoutingTraceService to not rely on async local storage * Pass RoutingTraceService through routing call * Add attribute-logic-evaluated to routing trace step * Add routing trace to trpc endpoint * Add CRM routing trace step * Fix extracting routing trace to assignment reason * Add back CRM params to prevent refetching * test: Add unit tests for RoutingTraceService and repositories Co-Authored-By: [email protected] <[email protected]> * test: Add missing mock for RoutingTraceService in getRoutedUrl tests Also fix pre-existing lint issues in the test file: - Add explicit types to mockForm and mockSerializableForm variables - Add explicit type to url parameter in mockContext - Replace 'as any' with 'as unknown as InstanceType<typeof UserRepository>' Co-Authored-By: [email protected] <[email protected]> * Link pending form submission to routing trace * Clean up * Add lookup field assignment reasons * Rename to PendingRoutingTrace * Add migration file * fix: Update RoutingTraceService tests to use assignmentReasonRepository mock - Add getStepsCount() method back to RoutingTraceService - Add queuedFormResponseId support to processForBooking method - Update tests to use mockAssignmentReasonRepository instead of prisma mock - Remove test for missing routingTraceRepository (all deps now required) Co-Authored-By: [email protected] <[email protected]> * fix: Remove PII (organizer email) from log payload in RoutingTraceService Addresses Cubic AI review feedback with confidence 9/10. Logging PII violates sensitive information logging rules. Co-Authored-By: unknown <> * Write field values at the time of routing * Write attributes used to route * fix: Add CHECK constraint to ensure at least one response ID is set in routing trace tables Co-Authored-By: [email protected] <[email protected]> * fix: Address PR review comments for routing trace feature - Add checkedFallback to routing trace step data (Comment 11) - Extract hardcoded domain/step strings to constants (Comment 13) - Use @default(now()) for createdAt in PendingRoutingTrace and RoutingTrace (Comment 15) - Add DEFAULT CURRENT_TIMESTAMP to migration for createdAt fields Co-Authored-By: [email protected] <[email protected]> * fix: Use UTC-safe timezone expression for createdAt defaults in routing trace tables Addresses Cubic AI review feedback (confidence 9/10) to prevent timezone issues by using dbgenerated("timezone('UTC', now())") instead of bare now() for the createdAt fields in PendingRoutingTrace and RoutingTrace models. Co-Authored-By: unknown <> * fix: Align migration SQL with Prisma's expected timezone syntax Use 'UTC'::text cast in timezone() function to match Prisma's generated SQL. Co-Authored-By: unknown <> * fix: Revert migration SQL to match Prisma schema timezone syntax Remove ::text cast from timezone() function to match what Prisma generates from the schema definition. Co-Authored-By: unknown <> * fix: Use explicit ::text cast in timezone() for PostgreSQL compatibility PostgreSQL normalizes timezone('UTC', now()) to timezone('UTC'::text, now()) internally. Update both schema and migration to use the explicit cast to ensure they match and pass the migration check. Co-Authored-By: unknown <> * fix: Use CURRENT_TIMESTAMP for createdAt defaults (standard Cal.com pattern) Co-Authored-By: [email protected] <[email protected]> * fix: Use @default(now()) for createdAt in routing trace tables to match migration Co-Authored-By: [email protected] <[email protected]> --------- Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> Co-authored-by: Pedro Castro <[email protected]>
This commit is contained in:
24 files changed
+2152
-71
No files matched your search
@@ -0,0 +1,23 @@
|
||||
import { bindModuleToClassOnToken, createModule, type ModuleLoader } from "@calcom/features/di/di";
|
||||
import { moduleLoader as prismaModuleLoader } from "@calcom/features/di/modules/Prisma";
|
||||
|
||||
import { PrismaPendingRoutingTraceRepository } from "../repositories/PrismaPendingRoutingTraceRepository";
|
||||
import { ROUTING_TRACE_DI_TOKENS } from "./tokens";
|
||||
|
||||
export const pendingRoutingTraceRepositoryModule = createModule();
|
||||
const token = ROUTING_TRACE_DI_TOKENS.PENDING_ROUTING_TRACE_REPOSITORY;
|
||||
const moduleToken = ROUTING_TRACE_DI_TOKENS.PENDING_ROUTING_TRACE_REPOSITORY_MODULE;
|
||||
const loadModule = bindModuleToClassOnToken({
|
||||
module: pendingRoutingTraceRepositoryModule,
|
||||
moduleToken,
|
||||
token,
|
||||
classs: PrismaPendingRoutingTraceRepository,
|
||||
dep: prismaModuleLoader,
|
||||
});
|
||||
|
||||
export const moduleLoader: ModuleLoader = {
|
||||
token,
|
||||
loadModule,
|
||||
};
|
||||
|
||||
export type { PrismaPendingRoutingTraceRepository };
|
||||
@@ -0,0 +1,23 @@
|
||||
import { bindModuleToClassOnToken, createModule, type ModuleLoader } from "@calcom/features/di/di";
|
||||
import { moduleLoader as prismaModuleLoader } from "@calcom/features/di/modules/Prisma";
|
||||
|
||||
import { PrismaRoutingTraceRepository } from "../repositories/PrismaRoutingTraceRepository";
|
||||
import { ROUTING_TRACE_DI_TOKENS } from "./tokens";
|
||||
|
||||
export const routingTraceRepositoryModule = createModule();
|
||||
const token = ROUTING_TRACE_DI_TOKENS.ROUTING_TRACE_REPOSITORY;
|
||||
const moduleToken = ROUTING_TRACE_DI_TOKENS.ROUTING_TRACE_REPOSITORY_MODULE;
|
||||
const loadModule = bindModuleToClassOnToken({
|
||||
module: routingTraceRepositoryModule,
|
||||
moduleToken,
|
||||
token,
|
||||
classs: PrismaRoutingTraceRepository,
|
||||
dep: prismaModuleLoader,
|
||||
});
|
||||
|
||||
export const moduleLoader: ModuleLoader = {
|
||||
token,
|
||||
loadModule,
|
||||
};
|
||||
|
||||
export type { PrismaRoutingTraceRepository };
|
||||
@@ -0,0 +1,37 @@
|
||||
import { AssignmentReasonRepository } from "@calcom/features/assignment-reason/repositories/AssignmentReasonRepository";
|
||||
import { createContainer } from "@calcom/features/di/di";
|
||||
import prisma from "@calcom/prisma";
|
||||
|
||||
import type { IPendingRoutingTraceRepository } from "../repositories/PendingRoutingTraceRepository.interface";
|
||||
import type { IRoutingTraceRepository } from "../repositories/RoutingTraceRepository.interface";
|
||||
import { RoutingTraceService } from "../services/RoutingTraceService";
|
||||
import { moduleLoader as pendingRoutingTraceRepositoryModuleLoader } from "./PendingRoutingTraceRepository.module";
|
||||
import { moduleLoader as routingTraceRepositoryModuleLoader } from "./RoutingTraceRepository.module";
|
||||
|
||||
const routingTraceContainer = createContainer();
|
||||
|
||||
function getPendingRoutingTraceRepository(): IPendingRoutingTraceRepository {
|
||||
pendingRoutingTraceRepositoryModuleLoader.loadModule(routingTraceContainer);
|
||||
return routingTraceContainer.get<IPendingRoutingTraceRepository>(
|
||||
pendingRoutingTraceRepositoryModuleLoader.token
|
||||
);
|
||||
}
|
||||
|
||||
function getRoutingTraceRepository(): IRoutingTraceRepository {
|
||||
routingTraceRepositoryModuleLoader.loadModule(routingTraceContainer);
|
||||
return routingTraceContainer.get<IRoutingTraceRepository>(routingTraceRepositoryModuleLoader.token);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a RoutingTraceService instance with all required repositories.
|
||||
* Use this for processing pending traces during booking creation.
|
||||
*/
|
||||
export function getRoutingTraceService(): RoutingTraceService {
|
||||
return new RoutingTraceService({
|
||||
pendingRoutingTraceRepository: getPendingRoutingTraceRepository(),
|
||||
routingTraceRepository: getRoutingTraceRepository(),
|
||||
assignmentReasonRepository: new AssignmentReasonRepository(prisma),
|
||||
});
|
||||
}
|
||||
|
||||
export { RoutingTraceService };
|
||||
@@ -0,0 +1,8 @@
|
||||
export const ROUTING_TRACE_DI_TOKENS = {
|
||||
ROUTING_TRACE_SERVICE: Symbol("RoutingTraceService"),
|
||||
ROUTING_TRACE_SERVICE_MODULE: Symbol("RoutingTraceServiceModule"),
|
||||
PENDING_ROUTING_TRACE_REPOSITORY: Symbol("PendingRoutingTraceRepository"),
|
||||
PENDING_ROUTING_TRACE_REPOSITORY_MODULE: Symbol("PendingRoutingTraceRepositoryModule"),
|
||||
ROUTING_TRACE_REPOSITORY: Symbol("RoutingTraceRepository"),
|
||||
ROUTING_TRACE_REPOSITORY_MODULE: Symbol("RoutingTraceRepositoryModule"),
|
||||
};
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
import type {
|
||||
BaseRoutingTrace,
|
||||
RoutingTrace,
|
||||
} from "./RoutingTraceRepository.interface";
|
||||
|
||||
export interface RoutingTraceWithQueuedResponse extends BaseRoutingTrace {
|
||||
queuedFormResponseId: string;
|
||||
}
|
||||
|
||||
export interface PendingRoutingTraceRecord {
|
||||
id: string;
|
||||
createdAt: Date;
|
||||
trace: RoutingTrace;
|
||||
formResponseId: number | null;
|
||||
queuedFormResponseId: string | null;
|
||||
}
|
||||
|
||||
export interface IPendingRoutingTraceRepository {
|
||||
create(args: IPendingRoutingTraceRepositoryCreateArgs): Promise<void>;
|
||||
findByFormResponseId(formResponseId: number): Promise<PendingRoutingTraceRecord | null>;
|
||||
findByQueuedFormResponseId(queuedFormResponseId: string): Promise<PendingRoutingTraceRecord | null>;
|
||||
/** Link a pending trace (created with queuedFormResponseId) to a formResponseId when the queued response is processed */
|
||||
linkToFormResponse(args: {
|
||||
queuedFormResponseId: string;
|
||||
formResponseId: number;
|
||||
}): Promise<void>;
|
||||
}
|
||||
|
||||
interface BaseCreateArgs {
|
||||
trace: RoutingTrace;
|
||||
}
|
||||
|
||||
interface CreateWithFormResponse extends BaseCreateArgs {
|
||||
formResponseId: number;
|
||||
}
|
||||
|
||||
interface CreateWithQueuedFormResponse extends BaseCreateArgs {
|
||||
queuedFormResponseId: string;
|
||||
}
|
||||
|
||||
export type IPendingRoutingTraceRepositoryCreateArgs =
|
||||
| CreateWithFormResponse
|
||||
| CreateWithQueuedFormResponse;
|
||||
+208
@@ -0,0 +1,208 @@
|
||||
import type { PrismaClient } from "@calcom/prisma";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { PrismaPendingRoutingTraceRepository } from "./PrismaPendingRoutingTraceRepository";
|
||||
|
||||
describe("PrismaPendingRoutingTraceRepository", () => {
|
||||
let repository: PrismaPendingRoutingTraceRepository;
|
||||
|
||||
const mockPrisma = {
|
||||
pendingRoutingTrace: {
|
||||
create: vi.fn(),
|
||||
findUnique: vi.fn(),
|
||||
},
|
||||
} as unknown as PrismaClient;
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
repository = new PrismaPendingRoutingTraceRepository(mockPrisma);
|
||||
});
|
||||
|
||||
describe("create", () => {
|
||||
it("should create a pending routing trace with formResponseId", async () => {
|
||||
const trace = [
|
||||
{
|
||||
domain: "routing_form",
|
||||
step: "attribute-logic-evaluated",
|
||||
timestamp: Date.now(),
|
||||
data: { routeIsFallback: false },
|
||||
},
|
||||
];
|
||||
|
||||
vi.mocked(mockPrisma.pendingRoutingTrace.create).mockResolvedValue({
|
||||
id: "pending-1",
|
||||
createdAt: new Date(),
|
||||
trace,
|
||||
formResponseId: 123,
|
||||
queuedFormResponseId: null,
|
||||
});
|
||||
|
||||
await repository.create({
|
||||
trace,
|
||||
formResponseId: 123,
|
||||
});
|
||||
|
||||
expect(mockPrisma.pendingRoutingTrace.create).toHaveBeenCalledWith({
|
||||
data: {
|
||||
createdAt: expect.any(Date),
|
||||
trace,
|
||||
formResponseId: 123,
|
||||
queuedFormResponseId: undefined,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("should create a pending routing trace with queuedFormResponseId", async () => {
|
||||
const trace = [
|
||||
{
|
||||
domain: "routing_form",
|
||||
step: "attribute-logic-evaluated",
|
||||
timestamp: Date.now(),
|
||||
data: { routeIsFallback: true },
|
||||
},
|
||||
];
|
||||
|
||||
vi.mocked(mockPrisma.pendingRoutingTrace.create).mockResolvedValue({
|
||||
id: "pending-2",
|
||||
createdAt: new Date(),
|
||||
trace,
|
||||
formResponseId: null,
|
||||
queuedFormResponseId: "queued-123",
|
||||
});
|
||||
|
||||
await repository.create({
|
||||
trace,
|
||||
queuedFormResponseId: "queued-123",
|
||||
});
|
||||
|
||||
expect(mockPrisma.pendingRoutingTrace.create).toHaveBeenCalledWith({
|
||||
data: {
|
||||
createdAt: expect.any(Date),
|
||||
trace,
|
||||
formResponseId: undefined,
|
||||
queuedFormResponseId: "queued-123",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("should create a pending routing trace with empty trace array", async () => {
|
||||
const trace: never[] = [];
|
||||
|
||||
vi.mocked(mockPrisma.pendingRoutingTrace.create).mockResolvedValue({
|
||||
id: "pending-3",
|
||||
createdAt: new Date(),
|
||||
trace,
|
||||
formResponseId: 456,
|
||||
queuedFormResponseId: null,
|
||||
});
|
||||
|
||||
await repository.create({
|
||||
trace,
|
||||
formResponseId: 456,
|
||||
});
|
||||
|
||||
expect(mockPrisma.pendingRoutingTrace.create).toHaveBeenCalledWith({
|
||||
data: {
|
||||
createdAt: expect.any(Date),
|
||||
trace,
|
||||
formResponseId: 456,
|
||||
queuedFormResponseId: undefined,
|
||||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("findByFormResponseId", () => {
|
||||
it("should find a pending routing trace by formResponseId", async () => {
|
||||
const trace = [
|
||||
{
|
||||
domain: "routing_form",
|
||||
step: "attribute-logic-evaluated",
|
||||
timestamp: Date.now(),
|
||||
data: { routeIsFallback: false },
|
||||
},
|
||||
];
|
||||
|
||||
const mockResult = {
|
||||
id: "pending-1",
|
||||
createdAt: new Date("2025-01-01T10:00:00Z"),
|
||||
trace,
|
||||
formResponseId: 123,
|
||||
queuedFormResponseId: null,
|
||||
};
|
||||
|
||||
vi.mocked(mockPrisma.pendingRoutingTrace.findUnique).mockResolvedValue(mockResult);
|
||||
|
||||
const result = await repository.findByFormResponseId(123);
|
||||
|
||||
expect(mockPrisma.pendingRoutingTrace.findUnique).toHaveBeenCalledWith({
|
||||
where: { formResponseId: 123 },
|
||||
});
|
||||
expect(result).toEqual({
|
||||
id: "pending-1",
|
||||
createdAt: new Date("2025-01-01T10:00:00Z"),
|
||||
trace,
|
||||
formResponseId: 123,
|
||||
queuedFormResponseId: null,
|
||||
});
|
||||
});
|
||||
|
||||
it("should return null when no pending routing trace is found", async () => {
|
||||
vi.mocked(mockPrisma.pendingRoutingTrace.findUnique).mockResolvedValue(null);
|
||||
|
||||
const result = await repository.findByFormResponseId(999);
|
||||
|
||||
expect(mockPrisma.pendingRoutingTrace.findUnique).toHaveBeenCalledWith({
|
||||
where: { formResponseId: 999 },
|
||||
});
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("findByQueuedFormResponseId", () => {
|
||||
it("should find a pending routing trace by queuedFormResponseId", async () => {
|
||||
const trace = [
|
||||
{
|
||||
domain: "salesforce",
|
||||
step: "salesforce_assignment",
|
||||
timestamp: Date.now(),
|
||||
data: { email: "[email protected]" },
|
||||
},
|
||||
];
|
||||
|
||||
const mockResult = {
|
||||
id: "pending-2",
|
||||
createdAt: new Date("2025-01-02T10:00:00Z"),
|
||||
trace,
|
||||
formResponseId: null,
|
||||
queuedFormResponseId: "queued-456",
|
||||
};
|
||||
|
||||
vi.mocked(mockPrisma.pendingRoutingTrace.findUnique).mockResolvedValue(mockResult);
|
||||
|
||||
const result = await repository.findByQueuedFormResponseId("queued-456");
|
||||
|
||||
expect(mockPrisma.pendingRoutingTrace.findUnique).toHaveBeenCalledWith({
|
||||
where: { queuedFormResponseId: "queued-456" },
|
||||
});
|
||||
expect(result).toEqual({
|
||||
id: "pending-2",
|
||||
createdAt: new Date("2025-01-02T10:00:00Z"),
|
||||
trace,
|
||||
formResponseId: null,
|
||||
queuedFormResponseId: "queued-456",
|
||||
});
|
||||
});
|
||||
|
||||
it("should return null when no pending routing trace is found by queuedFormResponseId", async () => {
|
||||
vi.mocked(mockPrisma.pendingRoutingTrace.findUnique).mockResolvedValue(null);
|
||||
|
||||
const result = await repository.findByQueuedFormResponseId("non-existent");
|
||||
|
||||
expect(mockPrisma.pendingRoutingTrace.findUnique).toHaveBeenCalledWith({
|
||||
where: { queuedFormResponseId: "non-existent" },
|
||||
});
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,64 @@
|
||||
import type { PrismaClient } from "@calcom/prisma";
|
||||
import type { Prisma } from "@calcom/prisma/client";
|
||||
|
||||
import type { RoutingTrace } from "./RoutingTraceRepository.interface";
|
||||
import type {
|
||||
IPendingRoutingTraceRepository,
|
||||
IPendingRoutingTraceRepositoryCreateArgs,
|
||||
PendingRoutingTraceRecord,
|
||||
} from "./PendingRoutingTraceRepository.interface";
|
||||
|
||||
export class PrismaPendingRoutingTraceRepository
|
||||
implements IPendingRoutingTraceRepository
|
||||
{
|
||||
constructor(private readonly prisma: PrismaClient) {}
|
||||
|
||||
async create(args: IPendingRoutingTraceRepositoryCreateArgs): Promise<void> {
|
||||
await this.prisma.pendingRoutingTrace.create({
|
||||
data: {
|
||||
createdAt: new Date(),
|
||||
trace: args.trace as Prisma.InputJsonValue,
|
||||
formResponseId:
|
||||
"formResponseId" in args ? args.formResponseId : undefined,
|
||||
queuedFormResponseId:
|
||||
"queuedFormResponseId" in args
|
||||
? args.queuedFormResponseId
|
||||
: undefined,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async findByFormResponseId(formResponseId: number): Promise<PendingRoutingTraceRecord | null> {
|
||||
const result = await this.prisma.pendingRoutingTrace.findUnique({
|
||||
where: { formResponseId },
|
||||
});
|
||||
if (!result) return null;
|
||||
return {
|
||||
...result,
|
||||
trace: result.trace as RoutingTrace,
|
||||
};
|
||||
}
|
||||
|
||||
async findByQueuedFormResponseId(
|
||||
queuedFormResponseId: string
|
||||
): Promise<PendingRoutingTraceRecord | null> {
|
||||
const result = await this.prisma.pendingRoutingTrace.findUnique({
|
||||
where: { queuedFormResponseId },
|
||||
});
|
||||
if (!result) return null;
|
||||
return {
|
||||
...result,
|
||||
trace: result.trace as RoutingTrace,
|
||||
};
|
||||
}
|
||||
|
||||
async linkToFormResponse(args: {
|
||||
queuedFormResponseId: string;
|
||||
formResponseId: number;
|
||||
}): Promise<void> {
|
||||
await this.prisma.pendingRoutingTrace.update({
|
||||
where: { queuedFormResponseId: args.queuedFormResponseId },
|
||||
data: { formResponseId: args.formResponseId },
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,252 @@
|
||||
import type { PrismaClient } from "@calcom/prisma";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { PrismaRoutingTraceRepository } from "./PrismaRoutingTraceRepository";
|
||||
|
||||
describe("PrismaRoutingTraceRepository", () => {
|
||||
let repository: PrismaRoutingTraceRepository;
|
||||
|
||||
const mockPrisma = {
|
||||
routingTrace: {
|
||||
create: vi.fn(),
|
||||
},
|
||||
} as unknown as PrismaClient;
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
repository = new PrismaRoutingTraceRepository(mockPrisma);
|
||||
});
|
||||
|
||||
describe("create", () => {
|
||||
it("should create a routing trace with all fields", async () => {
|
||||
const trace = [
|
||||
{
|
||||
domain: "routing_form",
|
||||
step: "attribute-logic-evaluated",
|
||||
timestamp: Date.now(),
|
||||
data: { routeIsFallback: false },
|
||||
},
|
||||
];
|
||||
|
||||
const mockResult = {
|
||||
id: "trace-1",
|
||||
createdAt: new Date("2025-01-01T10:00:00Z"),
|
||||
trace,
|
||||
formResponseId: 123,
|
||||
queuedFormResponseId: null,
|
||||
bookingUid: "booking-uid-123",
|
||||
assignmentReasonId: 42,
|
||||
};
|
||||
|
||||
vi.mocked(mockPrisma.routingTrace.create).mockResolvedValue(mockResult);
|
||||
|
||||
const result = await repository.create({
|
||||
trace,
|
||||
formResponseId: 123,
|
||||
bookingUid: "booking-uid-123",
|
||||
assignmentReasonId: 42,
|
||||
});
|
||||
|
||||
expect(mockPrisma.routingTrace.create).toHaveBeenCalledWith({
|
||||
data: {
|
||||
createdAt: expect.any(Date),
|
||||
trace,
|
||||
formResponseId: 123,
|
||||
queuedFormResponseId: undefined,
|
||||
bookingUid: "booking-uid-123",
|
||||
assignmentReasonId: 42,
|
||||
},
|
||||
});
|
||||
expect(result).toEqual({
|
||||
id: "trace-1",
|
||||
createdAt: new Date("2025-01-01T10:00:00Z"),
|
||||
trace,
|
||||
formResponseId: 123,
|
||||
queuedFormResponseId: null,
|
||||
bookingUid: "booking-uid-123",
|
||||
assignmentReasonId: 42,
|
||||
});
|
||||
});
|
||||
|
||||
it("should create a routing trace with queuedFormResponseId", async () => {
|
||||
const trace = [
|
||||
{
|
||||
domain: "salesforce",
|
||||
step: "salesforce_assignment",
|
||||
timestamp: Date.now(),
|
||||
data: { email: "[email protected]" },
|
||||
},
|
||||
];
|
||||
|
||||
const mockResult = {
|
||||
id: "trace-2",
|
||||
createdAt: new Date("2025-01-02T10:00:00Z"),
|
||||
trace,
|
||||
formResponseId: null,
|
||||
queuedFormResponseId: "queued-456",
|
||||
bookingUid: "booking-uid-456",
|
||||
assignmentReasonId: 100,
|
||||
};
|
||||
|
||||
vi.mocked(mockPrisma.routingTrace.create).mockResolvedValue(mockResult);
|
||||
|
||||
const result = await repository.create({
|
||||
trace,
|
||||
queuedFormResponseId: "queued-456",
|
||||
bookingUid: "booking-uid-456",
|
||||
assignmentReasonId: 100,
|
||||
});
|
||||
|
||||
expect(mockPrisma.routingTrace.create).toHaveBeenCalledWith({
|
||||
data: {
|
||||
createdAt: expect.any(Date),
|
||||
trace,
|
||||
formResponseId: undefined,
|
||||
queuedFormResponseId: "queued-456",
|
||||
bookingUid: "booking-uid-456",
|
||||
assignmentReasonId: 100,
|
||||
},
|
||||
});
|
||||
expect(result).toEqual({
|
||||
id: "trace-2",
|
||||
createdAt: new Date("2025-01-02T10:00:00Z"),
|
||||
trace,
|
||||
formResponseId: null,
|
||||
queuedFormResponseId: "queued-456",
|
||||
bookingUid: "booking-uid-456",
|
||||
assignmentReasonId: 100,
|
||||
});
|
||||
});
|
||||
|
||||
it("should create a routing trace without assignmentReasonId", async () => {
|
||||
const trace = [
|
||||
{
|
||||
domain: "other_domain",
|
||||
step: "some_step",
|
||||
timestamp: Date.now(),
|
||||
data: {},
|
||||
},
|
||||
];
|
||||
|
||||
const mockResult = {
|
||||
id: "trace-3",
|
||||
createdAt: new Date("2025-01-03T10:00:00Z"),
|
||||
trace,
|
||||
formResponseId: 789,
|
||||
queuedFormResponseId: null,
|
||||
bookingUid: "booking-uid-789",
|
||||
assignmentReasonId: null,
|
||||
};
|
||||
|
||||
vi.mocked(mockPrisma.routingTrace.create).mockResolvedValue(mockResult);
|
||||
|
||||
const result = await repository.create({
|
||||
trace,
|
||||
formResponseId: 789,
|
||||
bookingUid: "booking-uid-789",
|
||||
});
|
||||
|
||||
expect(mockPrisma.routingTrace.create).toHaveBeenCalledWith({
|
||||
data: {
|
||||
createdAt: expect.any(Date),
|
||||
trace,
|
||||
formResponseId: 789,
|
||||
queuedFormResponseId: undefined,
|
||||
bookingUid: "booking-uid-789",
|
||||
assignmentReasonId: undefined,
|
||||
},
|
||||
});
|
||||
expect(result).toEqual({
|
||||
id: "trace-3",
|
||||
createdAt: new Date("2025-01-03T10:00:00Z"),
|
||||
trace,
|
||||
formResponseId: 789,
|
||||
queuedFormResponseId: null,
|
||||
bookingUid: "booking-uid-789",
|
||||
assignmentReasonId: null,
|
||||
});
|
||||
});
|
||||
|
||||
it("should create a routing trace with multiple trace steps", async () => {
|
||||
const trace = [
|
||||
{
|
||||
domain: "salesforce",
|
||||
step: "salesforce_assignment",
|
||||
timestamp: Date.now() - 1000,
|
||||
data: { email: "[email protected]", recordType: "Contact", recordId: "003ABC" },
|
||||
},
|
||||
{
|
||||
domain: "routing_form",
|
||||
step: "attribute-logic-evaluated",
|
||||
timestamp: Date.now(),
|
||||
data: { routeIsFallback: false },
|
||||
},
|
||||
];
|
||||
|
||||
const mockResult = {
|
||||
id: "trace-4",
|
||||
createdAt: new Date("2025-01-04T10:00:00Z"),
|
||||
trace,
|
||||
formResponseId: 111,
|
||||
queuedFormResponseId: null,
|
||||
bookingUid: "booking-uid-111",
|
||||
assignmentReasonId: 50,
|
||||
};
|
||||
|
||||
vi.mocked(mockPrisma.routingTrace.create).mockResolvedValue(mockResult);
|
||||
|
||||
const result = await repository.create({
|
||||
trace,
|
||||
formResponseId: 111,
|
||||
bookingUid: "booking-uid-111",
|
||||
assignmentReasonId: 50,
|
||||
});
|
||||
|
||||
expect(mockPrisma.routingTrace.create).toHaveBeenCalledWith({
|
||||
data: {
|
||||
createdAt: expect.any(Date),
|
||||
trace,
|
||||
formResponseId: 111,
|
||||
queuedFormResponseId: undefined,
|
||||
bookingUid: "booking-uid-111",
|
||||
assignmentReasonId: 50,
|
||||
},
|
||||
});
|
||||
expect(result.trace).toHaveLength(2);
|
||||
});
|
||||
|
||||
it("should create a routing trace with empty trace array", async () => {
|
||||
const trace: never[] = [];
|
||||
|
||||
const mockResult = {
|
||||
id: "trace-5",
|
||||
createdAt: new Date("2025-01-05T10:00:00Z"),
|
||||
trace,
|
||||
formResponseId: 222,
|
||||
queuedFormResponseId: null,
|
||||
bookingUid: "booking-uid-222",
|
||||
assignmentReasonId: null,
|
||||
};
|
||||
|
||||
vi.mocked(mockPrisma.routingTrace.create).mockResolvedValue(mockResult);
|
||||
|
||||
const result = await repository.create({
|
||||
trace,
|
||||
formResponseId: 222,
|
||||
bookingUid: "booking-uid-222",
|
||||
});
|
||||
|
||||
expect(mockPrisma.routingTrace.create).toHaveBeenCalledWith({
|
||||
data: {
|
||||
createdAt: expect.any(Date),
|
||||
trace,
|
||||
formResponseId: 222,
|
||||
queuedFormResponseId: undefined,
|
||||
bookingUid: "booking-uid-222",
|
||||
assignmentReasonId: undefined,
|
||||
},
|
||||
});
|
||||
expect(result.trace).toEqual([]);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,30 @@
|
||||
import type { PrismaClient } from "@calcom/prisma";
|
||||
import type { Prisma } from "@calcom/prisma/client";
|
||||
|
||||
import type {
|
||||
IRoutingTraceRepository,
|
||||
IRoutingTraceRepositoryCreateArgs,
|
||||
RoutingTrace,
|
||||
RoutingTraceRecord,
|
||||
} from "./RoutingTraceRepository.interface";
|
||||
|
||||
export class PrismaRoutingTraceRepository implements IRoutingTraceRepository {
|
||||
constructor(private readonly prisma: PrismaClient) {}
|
||||
|
||||
async create(args: IRoutingTraceRepositoryCreateArgs): Promise<RoutingTraceRecord> {
|
||||
const result = await this.prisma.routingTrace.create({
|
||||
data: {
|
||||
createdAt: new Date(),
|
||||
trace: args.trace as Prisma.InputJsonValue,
|
||||
formResponseId: args.formResponseId,
|
||||
queuedFormResponseId: args.queuedFormResponseId,
|
||||
bookingUid: args.bookingUid,
|
||||
assignmentReasonId: args.assignmentReasonId,
|
||||
},
|
||||
});
|
||||
return {
|
||||
...result,
|
||||
trace: result.trace as RoutingTrace,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
import z from "zod";
|
||||
import type { routingStepSchema } from "../schema/zod";
|
||||
|
||||
export type RoutingStep = z.infer<typeof routingStepSchema>;
|
||||
|
||||
export type RoutingTrace = RoutingStep[];
|
||||
|
||||
export interface BaseRoutingTrace {
|
||||
id: string;
|
||||
createdAt: Date;
|
||||
trace: string;
|
||||
}
|
||||
|
||||
export interface RoutingTraceWithFormResponse extends BaseRoutingTrace {
|
||||
formResponseId: string;
|
||||
}
|
||||
|
||||
export interface RoutingTraceRecord {
|
||||
id: string;
|
||||
createdAt: Date;
|
||||
trace: RoutingTrace;
|
||||
formResponseId: number | null;
|
||||
queuedFormResponseId: string | null;
|
||||
bookingUid: string | null;
|
||||
assignmentReasonId: number | null;
|
||||
}
|
||||
|
||||
export interface IRoutingTraceRepositoryCreateArgs {
|
||||
trace: RoutingTrace;
|
||||
formResponseId?: number;
|
||||
queuedFormResponseId?: string;
|
||||
bookingUid: string;
|
||||
assignmentReasonId?: number;
|
||||
}
|
||||
|
||||
export interface IRoutingTraceRepository {
|
||||
create(args: IRoutingTraceRepositoryCreateArgs): Promise<RoutingTraceRecord>;
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
import z from "zod";
|
||||
|
||||
export const routingStepSchema = z.object({
|
||||
domain: z.string(),
|
||||
step: z.string(),
|
||||
timestamp: z.number(),
|
||||
data: z.record(z.unknown()),
|
||||
});
|
||||
@@ -0,0 +1,663 @@
|
||||
import type { AssignmentReasonRepository } from "@calcom/features/assignment-reason/repositories/AssignmentReasonRepository";
|
||||
import { AssignmentReasonEnum } from "@calcom/prisma/enums";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import type {
|
||||
IPendingRoutingTraceRepository,
|
||||
PendingRoutingTraceRecord,
|
||||
} from "../repositories/PendingRoutingTraceRepository.interface";
|
||||
import type { IRoutingTraceRepository } from "../repositories/RoutingTraceRepository.interface";
|
||||
import { RoutingTraceService } from "./RoutingTraceService";
|
||||
|
||||
describe("RoutingTraceService", () => {
|
||||
let service: RoutingTraceService;
|
||||
let mockPendingRoutingTraceRepository: IPendingRoutingTraceRepository;
|
||||
let mockRoutingTraceRepository: IRoutingTraceRepository;
|
||||
let mockAssignmentReasonRepository: Pick<AssignmentReasonRepository, "createAssignmentReason">;
|
||||
|
||||
function createMockPendingRoutingTraceRepository(): IPendingRoutingTraceRepository {
|
||||
return {
|
||||
create: vi.fn(),
|
||||
findByFormResponseId: vi.fn(),
|
||||
findByQueuedFormResponseId: vi.fn(),
|
||||
};
|
||||
}
|
||||
|
||||
function createMockRoutingTraceRepository(): IRoutingTraceRepository {
|
||||
return {
|
||||
create: vi.fn(),
|
||||
};
|
||||
}
|
||||
|
||||
function createMockAssignmentReasonRepository(): Pick<AssignmentReasonRepository, "createAssignmentReason"> {
|
||||
return {
|
||||
createAssignmentReason: vi.fn(),
|
||||
};
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mockPendingRoutingTraceRepository = createMockPendingRoutingTraceRepository();
|
||||
mockRoutingTraceRepository = createMockRoutingTraceRepository();
|
||||
mockAssignmentReasonRepository = createMockAssignmentReasonRepository();
|
||||
service = new RoutingTraceService({
|
||||
pendingRoutingTraceRepository: mockPendingRoutingTraceRepository,
|
||||
routingTraceRepository: mockRoutingTraceRepository,
|
||||
assignmentReasonRepository: mockAssignmentReasonRepository as AssignmentReasonRepository,
|
||||
});
|
||||
});
|
||||
|
||||
describe("addStep", () => {
|
||||
it("should add a step to the routing trace", () => {
|
||||
service.addStep({
|
||||
domain: "routing_form",
|
||||
step: "attribute-logic-evaluated",
|
||||
data: { routeIsFallback: false },
|
||||
});
|
||||
|
||||
expect(service.getStepsCount()).toBe(1);
|
||||
});
|
||||
|
||||
it("should add multiple steps to the routing trace", () => {
|
||||
service.addStep({
|
||||
domain: "routing_form",
|
||||
step: "attribute-logic-evaluated",
|
||||
data: { routeIsFallback: false },
|
||||
});
|
||||
|
||||
service.addStep({
|
||||
domain: "salesforce",
|
||||
step: "salesforce_assignment",
|
||||
data: { email: "[email protected]" },
|
||||
});
|
||||
|
||||
expect(service.getStepsCount()).toBe(2);
|
||||
});
|
||||
|
||||
it("should add step with empty data by default", () => {
|
||||
service.addStep({
|
||||
domain: "test_domain",
|
||||
step: "test_step",
|
||||
});
|
||||
|
||||
expect(service.getStepsCount()).toBe(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe("getStepsCount", () => {
|
||||
it("should return 0 when no steps have been added", () => {
|
||||
expect(service.getStepsCount()).toBe(0);
|
||||
});
|
||||
|
||||
it("should return correct count after adding steps", () => {
|
||||
service.addStep({ domain: "test", step: "step1" });
|
||||
service.addStep({ domain: "test", step: "step2" });
|
||||
service.addStep({ domain: "test", step: "step3" });
|
||||
|
||||
expect(service.getStepsCount()).toBe(3);
|
||||
});
|
||||
});
|
||||
|
||||
describe("savePendingRoutingTrace", () => {
|
||||
it("should save pending trace with formResponseId", async () => {
|
||||
service.addStep({
|
||||
domain: "routing_form",
|
||||
step: "attribute-logic-evaluated",
|
||||
data: { routeIsFallback: false },
|
||||
});
|
||||
|
||||
await service.savePendingRoutingTrace({ formResponseId: 123 });
|
||||
|
||||
expect(mockPendingRoutingTraceRepository.create).toHaveBeenCalledWith({
|
||||
trace: expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
domain: "routing_form",
|
||||
step: "attribute-logic-evaluated",
|
||||
data: { routeIsFallback: false },
|
||||
}),
|
||||
]),
|
||||
formResponseId: 123,
|
||||
});
|
||||
});
|
||||
|
||||
it("should save pending trace with queuedFormResponseId", async () => {
|
||||
service.addStep({
|
||||
domain: "routing_form",
|
||||
step: "attribute-logic-evaluated",
|
||||
data: { routeIsFallback: true },
|
||||
});
|
||||
|
||||
await service.savePendingRoutingTrace({ queuedFormResponseId: "queued-123" });
|
||||
|
||||
expect(mockPendingRoutingTraceRepository.create).toHaveBeenCalledWith({
|
||||
trace: expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
domain: "routing_form",
|
||||
step: "attribute-logic-evaluated",
|
||||
data: { routeIsFallback: true },
|
||||
}),
|
||||
]),
|
||||
queuedFormResponseId: "queued-123",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("processForBooking", () => {
|
||||
const baseProcessArgs = {
|
||||
bookingId: 1,
|
||||
bookingUid: "booking-uid-123",
|
||||
organizerEmail: "[email protected]",
|
||||
isRerouting: false,
|
||||
};
|
||||
|
||||
it("should return null if no pending trace is found", async () => {
|
||||
vi.mocked(mockPendingRoutingTraceRepository.findByFormResponseId).mockResolvedValue(null);
|
||||
|
||||
const result = await service.processForBooking({
|
||||
...baseProcessArgs,
|
||||
formResponseId: 123,
|
||||
});
|
||||
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
|
||||
it("should return null if no pending trace is found for queuedFormResponseId", async () => {
|
||||
vi.mocked(mockPendingRoutingTraceRepository.findByQueuedFormResponseId).mockResolvedValue(null);
|
||||
|
||||
const result = await service.processForBooking({
|
||||
...baseProcessArgs,
|
||||
queuedFormResponseId: "queued-123",
|
||||
});
|
||||
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
|
||||
describe("routing form assignment", () => {
|
||||
it("should extract ROUTING_FORM_ROUTING assignment reason", async () => {
|
||||
const pendingTrace: PendingRoutingTraceRecord = {
|
||||
id: "pending-1",
|
||||
createdAt: new Date(),
|
||||
trace: [
|
||||
{
|
||||
domain: "routing_form",
|
||||
step: "attribute-logic-evaluated",
|
||||
timestamp: Date.now(),
|
||||
data: { routeIsFallback: false },
|
||||
},
|
||||
],
|
||||
formResponseId: 123,
|
||||
queuedFormResponseId: null,
|
||||
};
|
||||
|
||||
vi.mocked(mockPendingRoutingTraceRepository.findByFormResponseId).mockResolvedValue(pendingTrace);
|
||||
vi.mocked(mockAssignmentReasonRepository.createAssignmentReason).mockResolvedValue({
|
||||
id: 1,
|
||||
bookingId: 1,
|
||||
reasonEnum: AssignmentReasonEnum.ROUTING_FORM_ROUTING,
|
||||
reasonString: "",
|
||||
});
|
||||
vi.mocked(mockRoutingTraceRepository.create).mockResolvedValue({
|
||||
id: "trace-1",
|
||||
createdAt: new Date(),
|
||||
trace: pendingTrace.trace,
|
||||
formResponseId: 123,
|
||||
queuedFormResponseId: null,
|
||||
bookingUid: "booking-uid-123",
|
||||
assignmentReasonId: 1,
|
||||
});
|
||||
|
||||
const result = await service.processForBooking({
|
||||
...baseProcessArgs,
|
||||
formResponseId: 123,
|
||||
});
|
||||
|
||||
expect(result).toEqual({
|
||||
assignmentReason: {
|
||||
reasonEnum: AssignmentReasonEnum.ROUTING_FORM_ROUTING,
|
||||
reasonString: "",
|
||||
},
|
||||
});
|
||||
expect(mockAssignmentReasonRepository.createAssignmentReason).toHaveBeenCalledWith({
|
||||
bookingId: 1,
|
||||
reasonEnum: AssignmentReasonEnum.ROUTING_FORM_ROUTING,
|
||||
reasonString: "",
|
||||
});
|
||||
});
|
||||
|
||||
it("should extract ROUTING_FORM_ROUTING_FALLBACK assignment reason when routeIsFallback is true", async () => {
|
||||
const pendingTrace: PendingRoutingTraceRecord = {
|
||||
id: "pending-1",
|
||||
createdAt: new Date(),
|
||||
trace: [
|
||||
{
|
||||
domain: "routing_form",
|
||||
step: "attribute-logic-evaluated",
|
||||
timestamp: Date.now(),
|
||||
data: { routeIsFallback: true },
|
||||
},
|
||||
],
|
||||
formResponseId: 123,
|
||||
queuedFormResponseId: null,
|
||||
};
|
||||
|
||||
vi.mocked(mockPendingRoutingTraceRepository.findByFormResponseId).mockResolvedValue(pendingTrace);
|
||||
vi.mocked(mockAssignmentReasonRepository.createAssignmentReason).mockResolvedValue({
|
||||
id: 1,
|
||||
bookingId: 1,
|
||||
reasonEnum: AssignmentReasonEnum.ROUTING_FORM_ROUTING_FALLBACK,
|
||||
reasonString: "",
|
||||
});
|
||||
vi.mocked(mockRoutingTraceRepository.create).mockResolvedValue({
|
||||
id: "trace-1",
|
||||
createdAt: new Date(),
|
||||
trace: pendingTrace.trace,
|
||||
formResponseId: 123,
|
||||
queuedFormResponseId: null,
|
||||
bookingUid: "booking-uid-123",
|
||||
assignmentReasonId: 1,
|
||||
});
|
||||
|
||||
const result = await service.processForBooking({
|
||||
...baseProcessArgs,
|
||||
formResponseId: 123,
|
||||
});
|
||||
|
||||
expect(result).toEqual({
|
||||
assignmentReason: {
|
||||
reasonEnum: AssignmentReasonEnum.ROUTING_FORM_ROUTING_FALLBACK,
|
||||
reasonString: "",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("should extract REROUTED assignment reason when isRerouting is true", async () => {
|
||||
const pendingTrace: PendingRoutingTraceRecord = {
|
||||
id: "pending-1",
|
||||
createdAt: new Date(),
|
||||
trace: [
|
||||
{
|
||||
domain: "routing_form",
|
||||
step: "attribute-logic-evaluated",
|
||||
timestamp: Date.now(),
|
||||
data: { routeIsFallback: false },
|
||||
},
|
||||
],
|
||||
formResponseId: 123,
|
||||
queuedFormResponseId: null,
|
||||
};
|
||||
|
||||
vi.mocked(mockPendingRoutingTraceRepository.findByFormResponseId).mockResolvedValue(pendingTrace);
|
||||
vi.mocked(mockAssignmentReasonRepository.createAssignmentReason).mockResolvedValue({
|
||||
id: 1,
|
||||
bookingId: 1,
|
||||
reasonEnum: AssignmentReasonEnum.REROUTED,
|
||||
reasonString: "Rerouted by [email protected]",
|
||||
});
|
||||
vi.mocked(mockRoutingTraceRepository.create).mockResolvedValue({
|
||||
id: "trace-1",
|
||||
createdAt: new Date(),
|
||||
trace: pendingTrace.trace,
|
||||
formResponseId: 123,
|
||||
queuedFormResponseId: null,
|
||||
bookingUid: "booking-uid-123",
|
||||
assignmentReasonId: 1,
|
||||
});
|
||||
|
||||
const result = await service.processForBooking({
|
||||
...baseProcessArgs,
|
||||
formResponseId: 123,
|
||||
isRerouting: true,
|
||||
reroutedByEmail: "[email protected]",
|
||||
});
|
||||
|
||||
expect(result).toEqual({
|
||||
assignmentReason: {
|
||||
reasonEnum: AssignmentReasonEnum.REROUTED,
|
||||
reasonString: "Rerouted by [email protected]",
|
||||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("salesforce assignment", () => {
|
||||
it("should extract SALESFORCE_ASSIGNMENT when organizer matches CRM contact owner", async () => {
|
||||
const pendingTrace: PendingRoutingTraceRecord = {
|
||||
id: "pending-1",
|
||||
createdAt: new Date(),
|
||||
trace: [
|
||||
{
|
||||
domain: "salesforce",
|
||||
step: "salesforce_assignment",
|
||||
timestamp: Date.now(),
|
||||
data: {
|
||||
email: "[email protected]",
|
||||
recordType: "Contact",
|
||||
recordId: "003ABC123",
|
||||
},
|
||||
},
|
||||
],
|
||||
formResponseId: 123,
|
||||
queuedFormResponseId: null,
|
||||
};
|
||||
|
||||
vi.mocked(mockPendingRoutingTraceRepository.findByFormResponseId).mockResolvedValue(pendingTrace);
|
||||
vi.mocked(mockAssignmentReasonRepository.createAssignmentReason).mockResolvedValue({
|
||||
id: 1,
|
||||
bookingId: 1,
|
||||
reasonEnum: AssignmentReasonEnum.SALESFORCE_ASSIGNMENT,
|
||||
reasonString: "Salesforce contact owner: [email protected] (Contact ID: 003ABC123)",
|
||||
});
|
||||
vi.mocked(mockRoutingTraceRepository.create).mockResolvedValue({
|
||||
id: "trace-1",
|
||||
createdAt: new Date(),
|
||||
trace: pendingTrace.trace,
|
||||
formResponseId: 123,
|
||||
queuedFormResponseId: null,
|
||||
bookingUid: "booking-uid-123",
|
||||
assignmentReasonId: 1,
|
||||
});
|
||||
|
||||
const result = await service.processForBooking({
|
||||
...baseProcessArgs,
|
||||
formResponseId: 123,
|
||||
});
|
||||
|
||||
expect(result).toEqual({
|
||||
assignmentReason: {
|
||||
reasonEnum: AssignmentReasonEnum.SALESFORCE_ASSIGNMENT,
|
||||
reasonString: "Salesforce contact owner: [email protected] (Contact ID: 003ABC123)",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("should use account lookup field reason string when rrSkipToAccountLookupField is true", async () => {
|
||||
const pendingTrace: PendingRoutingTraceRecord = {
|
||||
id: "pending-1",
|
||||
createdAt: new Date(),
|
||||
trace: [
|
||||
{
|
||||
domain: "salesforce",
|
||||
step: "salesforce_assignment",
|
||||
timestamp: Date.now(),
|
||||
data: {
|
||||
email: "[email protected]",
|
||||
recordType: "Account",
|
||||
recordId: "001ABC123",
|
||||
rrSkipToAccountLookupField: true,
|
||||
rrSKipToAccountLookupFieldName: "Account_Owner__c",
|
||||
},
|
||||
},
|
||||
],
|
||||
formResponseId: 123,
|
||||
queuedFormResponseId: null,
|
||||
};
|
||||
|
||||
vi.mocked(mockPendingRoutingTraceRepository.findByFormResponseId).mockResolvedValue(pendingTrace);
|
||||
vi.mocked(mockAssignmentReasonRepository.createAssignmentReason).mockResolvedValue({
|
||||
id: 1,
|
||||
bookingId: 1,
|
||||
reasonEnum: AssignmentReasonEnum.SALESFORCE_ASSIGNMENT,
|
||||
reasonString:
|
||||
"Salesforce account lookup field: Account_Owner__c - [email protected] (Account ID: 001ABC123)",
|
||||
});
|
||||
vi.mocked(mockRoutingTraceRepository.create).mockResolvedValue({
|
||||
id: "trace-1",
|
||||
createdAt: new Date(),
|
||||
trace: pendingTrace.trace,
|
||||
formResponseId: 123,
|
||||
queuedFormResponseId: null,
|
||||
bookingUid: "booking-uid-123",
|
||||
assignmentReasonId: 1,
|
||||
});
|
||||
|
||||
const result = await service.processForBooking({
|
||||
...baseProcessArgs,
|
||||
formResponseId: 123,
|
||||
});
|
||||
|
||||
expect(result).toEqual({
|
||||
assignmentReason: {
|
||||
reasonEnum: AssignmentReasonEnum.SALESFORCE_ASSIGNMENT,
|
||||
reasonString:
|
||||
"Salesforce account lookup field: Account_Owner__c - [email protected] (Account ID: 001ABC123)",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("should fall back to routing form assignment when organizer does not match CRM contact owner", async () => {
|
||||
const pendingTrace: PendingRoutingTraceRecord = {
|
||||
id: "pending-1",
|
||||
createdAt: new Date(),
|
||||
trace: [
|
||||
{
|
||||
domain: "salesforce",
|
||||
step: "salesforce_assignment",
|
||||
timestamp: Date.now(),
|
||||
data: {
|
||||
email: "[email protected]",
|
||||
recordType: "Contact",
|
||||
recordId: "003ABC123",
|
||||
},
|
||||
},
|
||||
{
|
||||
domain: "routing_form",
|
||||
step: "attribute-logic-evaluated",
|
||||
timestamp: Date.now(),
|
||||
data: { routeIsFallback: false },
|
||||
},
|
||||
],
|
||||
formResponseId: 123,
|
||||
queuedFormResponseId: null,
|
||||
};
|
||||
|
||||
vi.mocked(mockPendingRoutingTraceRepository.findByFormResponseId).mockResolvedValue(pendingTrace);
|
||||
vi.mocked(mockAssignmentReasonRepository.createAssignmentReason).mockResolvedValue({
|
||||
id: 1,
|
||||
bookingId: 1,
|
||||
reasonEnum: AssignmentReasonEnum.ROUTING_FORM_ROUTING,
|
||||
reasonString: "",
|
||||
});
|
||||
vi.mocked(mockRoutingTraceRepository.create).mockResolvedValue({
|
||||
id: "trace-1",
|
||||
createdAt: new Date(),
|
||||
trace: pendingTrace.trace,
|
||||
formResponseId: 123,
|
||||
queuedFormResponseId: null,
|
||||
bookingUid: "booking-uid-123",
|
||||
assignmentReasonId: 1,
|
||||
});
|
||||
|
||||
const result = await service.processForBooking({
|
||||
...baseProcessArgs,
|
||||
formResponseId: 123,
|
||||
});
|
||||
|
||||
expect(result).toEqual({
|
||||
assignmentReason: {
|
||||
reasonEnum: AssignmentReasonEnum.ROUTING_FORM_ROUTING,
|
||||
reasonString: "",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("should handle case-insensitive email matching for CRM assignment", async () => {
|
||||
const pendingTrace: PendingRoutingTraceRecord = {
|
||||
id: "pending-1",
|
||||
createdAt: new Date(),
|
||||
trace: [
|
||||
{
|
||||
domain: "salesforce",
|
||||
step: "salesforce_assignment",
|
||||
timestamp: Date.now(),
|
||||
data: {
|
||||
email: "[email protected]",
|
||||
recordType: "Contact",
|
||||
recordId: "003ABC123",
|
||||
},
|
||||
},
|
||||
],
|
||||
formResponseId: 123,
|
||||
queuedFormResponseId: null,
|
||||
};
|
||||
|
||||
vi.mocked(mockPendingRoutingTraceRepository.findByFormResponseId).mockResolvedValue(pendingTrace);
|
||||
vi.mocked(mockAssignmentReasonRepository.createAssignmentReason).mockResolvedValue({
|
||||
id: 1,
|
||||
bookingId: 1,
|
||||
reasonEnum: AssignmentReasonEnum.SALESFORCE_ASSIGNMENT,
|
||||
reasonString: "Salesforce contact owner: [email protected] (Contact ID: 003ABC123)",
|
||||
});
|
||||
vi.mocked(mockRoutingTraceRepository.create).mockResolvedValue({
|
||||
id: "trace-1",
|
||||
createdAt: new Date(),
|
||||
trace: pendingTrace.trace,
|
||||
formResponseId: 123,
|
||||
queuedFormResponseId: null,
|
||||
bookingUid: "booking-uid-123",
|
||||
assignmentReasonId: 1,
|
||||
});
|
||||
|
||||
const result = await service.processForBooking({
|
||||
...baseProcessArgs,
|
||||
formResponseId: 123,
|
||||
});
|
||||
|
||||
expect(result?.assignmentReason?.reasonEnum).toBe(AssignmentReasonEnum.SALESFORCE_ASSIGNMENT);
|
||||
});
|
||||
});
|
||||
|
||||
it("should create permanent routing trace with assignment reason", async () => {
|
||||
const pendingTrace: PendingRoutingTraceRecord = {
|
||||
id: "pending-1",
|
||||
createdAt: new Date(),
|
||||
trace: [
|
||||
{
|
||||
domain: "routing_form",
|
||||
step: "attribute-logic-evaluated",
|
||||
timestamp: Date.now(),
|
||||
data: { routeIsFallback: false },
|
||||
},
|
||||
],
|
||||
formResponseId: 123,
|
||||
queuedFormResponseId: null,
|
||||
};
|
||||
|
||||
vi.mocked(mockPendingRoutingTraceRepository.findByFormResponseId).mockResolvedValue(pendingTrace);
|
||||
vi.mocked(mockAssignmentReasonRepository.createAssignmentReason).mockResolvedValue({
|
||||
id: 42,
|
||||
bookingId: 1,
|
||||
reasonEnum: AssignmentReasonEnum.ROUTING_FORM_ROUTING,
|
||||
reasonString: "",
|
||||
});
|
||||
vi.mocked(mockRoutingTraceRepository.create).mockResolvedValue({
|
||||
id: "trace-1",
|
||||
createdAt: new Date(),
|
||||
trace: pendingTrace.trace,
|
||||
formResponseId: 123,
|
||||
queuedFormResponseId: null,
|
||||
bookingUid: "booking-uid-123",
|
||||
assignmentReasonId: 42,
|
||||
});
|
||||
|
||||
await service.processForBooking({
|
||||
...baseProcessArgs,
|
||||
formResponseId: 123,
|
||||
});
|
||||
|
||||
expect(mockRoutingTraceRepository.create).toHaveBeenCalledWith({
|
||||
trace: pendingTrace.trace,
|
||||
formResponseId: 123,
|
||||
queuedFormResponseId: undefined,
|
||||
bookingUid: "booking-uid-123",
|
||||
assignmentReasonId: 42,
|
||||
});
|
||||
});
|
||||
|
||||
it("should handle pending trace without assignment reason data", async () => {
|
||||
const pendingTrace: PendingRoutingTraceRecord = {
|
||||
id: "pending-1",
|
||||
createdAt: new Date(),
|
||||
trace: [
|
||||
{
|
||||
domain: "other_domain",
|
||||
step: "some_step",
|
||||
timestamp: Date.now(),
|
||||
data: {},
|
||||
},
|
||||
],
|
||||
formResponseId: 123,
|
||||
queuedFormResponseId: null,
|
||||
};
|
||||
|
||||
vi.mocked(mockPendingRoutingTraceRepository.findByFormResponseId).mockResolvedValue(pendingTrace);
|
||||
vi.mocked(mockRoutingTraceRepository.create).mockResolvedValue({
|
||||
id: "trace-1",
|
||||
createdAt: new Date(),
|
||||
trace: pendingTrace.trace,
|
||||
formResponseId: 123,
|
||||
queuedFormResponseId: null,
|
||||
bookingUid: "booking-uid-123",
|
||||
assignmentReasonId: null,
|
||||
});
|
||||
|
||||
const result = await service.processForBooking({
|
||||
...baseProcessArgs,
|
||||
formResponseId: 123,
|
||||
});
|
||||
|
||||
expect(result).toEqual({
|
||||
assignmentReason: undefined,
|
||||
});
|
||||
expect(mockAssignmentReasonRepository.createAssignmentReason).not.toHaveBeenCalled();
|
||||
expect(mockRoutingTraceRepository.create).toHaveBeenCalledWith({
|
||||
trace: pendingTrace.trace,
|
||||
formResponseId: 123,
|
||||
queuedFormResponseId: undefined,
|
||||
bookingUid: "booking-uid-123",
|
||||
assignmentReasonId: undefined,
|
||||
});
|
||||
});
|
||||
|
||||
it("should process pending trace found by queuedFormResponseId", async () => {
|
||||
const pendingTrace: PendingRoutingTraceRecord = {
|
||||
id: "pending-1",
|
||||
createdAt: new Date(),
|
||||
trace: [
|
||||
{
|
||||
domain: "routing_form",
|
||||
step: "attribute-logic-evaluated",
|
||||
timestamp: Date.now(),
|
||||
data: { routeIsFallback: false },
|
||||
},
|
||||
],
|
||||
formResponseId: null,
|
||||
queuedFormResponseId: "queued-123",
|
||||
};
|
||||
|
||||
vi.mocked(mockPendingRoutingTraceRepository.findByQueuedFormResponseId).mockResolvedValue(pendingTrace);
|
||||
vi.mocked(mockAssignmentReasonRepository.createAssignmentReason).mockResolvedValue({
|
||||
id: 1,
|
||||
bookingId: 1,
|
||||
reasonEnum: AssignmentReasonEnum.ROUTING_FORM_ROUTING,
|
||||
reasonString: "",
|
||||
});
|
||||
vi.mocked(mockRoutingTraceRepository.create).mockResolvedValue({
|
||||
id: "trace-1",
|
||||
createdAt: new Date(),
|
||||
trace: pendingTrace.trace,
|
||||
formResponseId: null,
|
||||
queuedFormResponseId: "queued-123",
|
||||
bookingUid: "booking-uid-123",
|
||||
assignmentReasonId: 1,
|
||||
});
|
||||
|
||||
const result = await service.processForBooking({
|
||||
...baseProcessArgs,
|
||||
queuedFormResponseId: "queued-123",
|
||||
});
|
||||
|
||||
expect(mockPendingRoutingTraceRepository.findByQueuedFormResponseId).toHaveBeenCalledWith("queued-123");
|
||||
expect(result?.assignmentReason?.reasonEnum).toBe(AssignmentReasonEnum.ROUTING_FORM_ROUTING);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,269 @@
|
||||
import type { AssignmentReasonRepository } from "@calcom/features/assignment-reason/repositories/AssignmentReasonRepository";
|
||||
import logger from "@calcom/lib/logger";
|
||||
import { AssignmentReasonEnum } from "@calcom/prisma/enums";
|
||||
|
||||
import type { IPendingRoutingTraceRepository } from "../repositories/PendingRoutingTraceRepository.interface";
|
||||
import type {
|
||||
IRoutingTraceRepository,
|
||||
RoutingStep,
|
||||
RoutingTrace,
|
||||
} from "../repositories/RoutingTraceRepository.interface";
|
||||
|
||||
export const ROUTING_TRACE_DOMAINS = {
|
||||
SALESFORCE: "salesforce",
|
||||
ROUTING_FORM: "routing_form",
|
||||
} as const;
|
||||
|
||||
export const ROUTING_TRACE_STEPS = {
|
||||
SALESFORCE_ASSIGNMENT: "salesforce_assignment",
|
||||
ATTRIBUTE_LOGIC_EVALUATED: "attribute-logic-evaluated",
|
||||
} as const;
|
||||
|
||||
interface IRoutingTraceServiceDeps {
|
||||
pendingRoutingTraceRepository: IPendingRoutingTraceRepository;
|
||||
routingTraceRepository: IRoutingTraceRepository;
|
||||
assignmentReasonRepository: AssignmentReasonRepository;
|
||||
}
|
||||
|
||||
export interface ProcessRoutingTraceResult {
|
||||
assignmentReason?: {
|
||||
reasonEnum: AssignmentReasonEnum;
|
||||
reasonString: string;
|
||||
};
|
||||
}
|
||||
|
||||
export class RoutingTraceService {
|
||||
private routingTraceSteps: RoutingStep[] = [];
|
||||
|
||||
constructor(private readonly deps: IRoutingTraceServiceDeps) {}
|
||||
|
||||
/** For debugging - get the number of steps recorded */
|
||||
getStepsCount(): number {
|
||||
return this.routingTraceSteps.length;
|
||||
}
|
||||
|
||||
/** To be called by the domain specific routing trace services */
|
||||
addStep({
|
||||
domain,
|
||||
step,
|
||||
data = {},
|
||||
}: {
|
||||
domain: string;
|
||||
step: string;
|
||||
data?: Record<string, unknown>;
|
||||
}) {
|
||||
this.routingTraceSteps.push({ domain, step, timestamp: Date.now(), data });
|
||||
}
|
||||
|
||||
/** Save pending trace when routing form is submitted (before booking is created) */
|
||||
async savePendingRoutingTrace(
|
||||
args: { formResponseId: number } | { queuedFormResponseId: string }
|
||||
) {
|
||||
await this.deps.pendingRoutingTraceRepository.create({
|
||||
trace: this.routingTraceSteps,
|
||||
...args,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Process pending routing trace for a booking.
|
||||
* Looks up the pending trace, extracts assignment reason, creates permanent trace.
|
||||
*/
|
||||
async processForBooking(args: {
|
||||
formResponseId?: number;
|
||||
queuedFormResponseId?: string;
|
||||
bookingId: number;
|
||||
bookingUid: string;
|
||||
organizerEmail: string;
|
||||
isRerouting: boolean;
|
||||
reroutedByEmail?: string | null;
|
||||
}): Promise<ProcessRoutingTraceResult | null> {
|
||||
const { formResponseId, queuedFormResponseId, bookingId, bookingUid, organizerEmail, isRerouting, reroutedByEmail } = args;
|
||||
|
||||
// 1. Look up pending trace by formResponseId or queuedFormResponseId
|
||||
let pendingTrace = null;
|
||||
if (formResponseId) {
|
||||
pendingTrace = await this.deps.pendingRoutingTraceRepository.findByFormResponseId(formResponseId);
|
||||
} else if (queuedFormResponseId) {
|
||||
pendingTrace = await this.deps.pendingRoutingTraceRepository.findByQueuedFormResponseId(queuedFormResponseId);
|
||||
}
|
||||
|
||||
if (!pendingTrace) {
|
||||
logger.warn("Could not find pending routing trace for form response", { formResponseId, queuedFormResponseId, bookingId });
|
||||
return null;
|
||||
}
|
||||
|
||||
// 2. Extract assignment reason from trace
|
||||
const assignmentReasonData = this.extractAssignmentReasonFromTrace(
|
||||
pendingTrace.trace,
|
||||
{
|
||||
organizerEmail,
|
||||
isRerouting,
|
||||
reroutedByEmail,
|
||||
}
|
||||
);
|
||||
|
||||
let assignmentReasonId: number | undefined;
|
||||
|
||||
// 3. Create assignment reason record if we have trace-based data
|
||||
if (assignmentReasonData) {
|
||||
const createdReason = await this.deps.assignmentReasonRepository.createAssignmentReason({
|
||||
bookingId,
|
||||
reasonEnum: assignmentReasonData.reasonEnum,
|
||||
reasonString: assignmentReasonData.reasonString,
|
||||
});
|
||||
assignmentReasonId = createdReason.id;
|
||||
}
|
||||
|
||||
// 4. Create permanent routing trace
|
||||
await this.deps.routingTraceRepository.create({
|
||||
trace: pendingTrace.trace,
|
||||
formResponseId: pendingTrace.formResponseId ?? undefined,
|
||||
queuedFormResponseId: pendingTrace.queuedFormResponseId ?? undefined,
|
||||
bookingUid,
|
||||
assignmentReasonId,
|
||||
});
|
||||
|
||||
return {
|
||||
assignmentReason: assignmentReasonData
|
||||
? {
|
||||
reasonEnum: assignmentReasonData.reasonEnum,
|
||||
reasonString: assignmentReasonData.reasonString,
|
||||
}
|
||||
: undefined,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract assignment reason from trace steps.
|
||||
* Priority: CRM (Salesforce) > Routing Form
|
||||
* CRM assignment is only used if the booking organizer matches the CRM contact owner.
|
||||
*/
|
||||
private extractAssignmentReasonFromTrace(
|
||||
trace: RoutingTrace,
|
||||
context: {
|
||||
organizerEmail: string;
|
||||
isRerouting: boolean;
|
||||
reroutedByEmail?: string | null;
|
||||
}
|
||||
): { reasonEnum: AssignmentReasonEnum; reasonString: string } | null {
|
||||
const crmAssignmentStep = trace.find(
|
||||
(step) =>
|
||||
step.domain === ROUTING_TRACE_DOMAINS.SALESFORCE &&
|
||||
step.step === ROUTING_TRACE_STEPS.SALESFORCE_ASSIGNMENT
|
||||
);
|
||||
|
||||
if (crmAssignmentStep && crmAssignmentStep.data) {
|
||||
const {
|
||||
email,
|
||||
recordType,
|
||||
recordId,
|
||||
rrSkipToAccountLookupField,
|
||||
rrSKipToAccountLookupFieldName,
|
||||
} = crmAssignmentStep.data as {
|
||||
email?: string;
|
||||
recordType?: string | null;
|
||||
recordId?: string;
|
||||
rrSkipToAccountLookupField?: boolean;
|
||||
rrSKipToAccountLookupFieldName?: string | null;
|
||||
};
|
||||
|
||||
// Only use CRM assignment if the booking organizer matches the contact owner
|
||||
if (
|
||||
email &&
|
||||
email.toLowerCase() === context.organizerEmail.toLowerCase()
|
||||
) {
|
||||
return {
|
||||
reasonEnum: AssignmentReasonEnum.SALESFORCE_ASSIGNMENT,
|
||||
reasonString: this.buildSalesforceReasonString({
|
||||
email,
|
||||
recordType: recordType ?? "Contact", // Default to Contact if not specified
|
||||
recordId,
|
||||
rrSkipToAccountLookupField,
|
||||
rrSKipToAccountLookupFieldName,
|
||||
}),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
const routingFormStep = trace.find(
|
||||
(step) =>
|
||||
step.domain === ROUTING_TRACE_DOMAINS.ROUTING_FORM &&
|
||||
step.step === ROUTING_TRACE_STEPS.ATTRIBUTE_LOGIC_EVALUATED
|
||||
);
|
||||
|
||||
if (routingFormStep && routingFormStep.data) {
|
||||
const { routeIsFallback, attributeRoutingDetails } = routingFormStep.data as {
|
||||
routeIsFallback?: boolean;
|
||||
attributeRoutingDetails?: Array<{ attributeName: string; attributeValue: string }>;
|
||||
};
|
||||
|
||||
const reasonEnum = context.isRerouting
|
||||
? AssignmentReasonEnum.REROUTED
|
||||
: routeIsFallback
|
||||
? AssignmentReasonEnum.ROUTING_FORM_ROUTING_FALLBACK
|
||||
: AssignmentReasonEnum.ROUTING_FORM_ROUTING;
|
||||
|
||||
return {
|
||||
reasonEnum,
|
||||
reasonString: this.buildRoutingFormReasonString({
|
||||
isRerouting: context.isRerouting,
|
||||
reroutedByEmail: context.reroutedByEmail,
|
||||
attributeRoutingDetails,
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
logger.warn("Could not extract assignment reason from routing trace - no matching steps found", {
|
||||
traceSteps: trace.map((s) => `${s.domain}:${s.step}`),
|
||||
});
|
||||
return null;
|
||||
}
|
||||
|
||||
private buildRoutingFormReasonString(data: {
|
||||
isRerouting: boolean;
|
||||
reroutedByEmail?: string | null;
|
||||
attributeRoutingDetails?: Array<{ attributeName: string; attributeValue: string }>;
|
||||
}): string {
|
||||
const { isRerouting, reroutedByEmail, attributeRoutingDetails } = data;
|
||||
|
||||
const reroutingPart = isRerouting && reroutedByEmail ? `Rerouted by ${reroutedByEmail}` : "";
|
||||
|
||||
const attributesPart =
|
||||
attributeRoutingDetails && attributeRoutingDetails.length > 0
|
||||
? attributeRoutingDetails
|
||||
.map(({ attributeName, attributeValue }) => `${attributeName}: ${attributeValue}`)
|
||||
.join(", ")
|
||||
: "";
|
||||
|
||||
// Combine both parts, matching main branch behavior
|
||||
return `${reroutingPart} ${attributesPart}`.trim();
|
||||
}
|
||||
|
||||
private buildSalesforceReasonString(data: {
|
||||
email: string;
|
||||
recordType: string;
|
||||
recordId?: string;
|
||||
rrSkipToAccountLookupField?: boolean;
|
||||
rrSKipToAccountLookupFieldName?: string | null;
|
||||
}): string {
|
||||
const {
|
||||
email,
|
||||
recordType,
|
||||
recordId,
|
||||
rrSkipToAccountLookupField,
|
||||
rrSKipToAccountLookupFieldName,
|
||||
} = data;
|
||||
|
||||
if (rrSkipToAccountLookupField && rrSKipToAccountLookupFieldName) {
|
||||
return `Salesforce account lookup field: ${rrSKipToAccountLookupFieldName} - ${email}${
|
||||
recordId ? ` (Account ID: ${recordId})` : ""
|
||||
}`;
|
||||
}
|
||||
|
||||
const recordLabel = recordType.toLowerCase();
|
||||
return `Salesforce ${recordLabel} owner: ${email}${
|
||||
recordId ? ` (${recordType} ID: ${recordId})` : ""
|
||||
}`;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user