-
Notifications
You must be signed in to change notification settings - Fork 14.6k
Expand file tree
/
Copy pathaiPhoneCallManager.ts
More file actions
335 lines (295 loc) · 10.1 KB
/
Copy pathaiPhoneCallManager.ts
File metadata and controls
335 lines (295 loc) · 10.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
import { v4 as uuidv4 } from "uuid";
import dayjs from "@calcom/dayjs";
import { FeaturesRepository } from "@calcom/features/flags/features.repository";
import tasker from "@calcom/features/tasker";
import { checkRateLimitAndThrowError } from "@calcom/lib/checkRateLimitAndThrowError";
import logger from "@calcom/lib/logger";
import prisma from "@calcom/prisma";
import { WorkflowMethods, WorkflowTriggerEvents } from "@calcom/prisma/enums";
import type { TimeUnit } from "@calcom/prisma/enums";
import { PhoneNumberSubscriptionStatus } from "@calcom/prisma/enums";
import type { BookingInfo } from "./smsReminderManager";
type timeUnitLowerCase = "day" | "hour" | "minute";
function extractPhoneNumber(responses: BookingInfo["responses"]): string | undefined {
if (!responses) return undefined;
// Priority 2: attendeePhoneNumber as fallback
const attendeePhoneResponse = responses.attendeePhoneNumber;
if (
attendeePhoneResponse &&
typeof attendeePhoneResponse === "object" &&
"value" in attendeePhoneResponse
) {
return attendeePhoneResponse.value as string;
}
return undefined;
}
interface CreateWorkflowReminderAndExtractPhoneArgs {
evt: BookingInfo;
workflowStepId: number;
scheduledDate: dayjs.Dayjs;
seatReferenceUid?: string;
}
interface CreateWorkflowReminderAndExtractPhoneResult {
workflowReminder: { id: number; uuid: string | null };
attendeePhoneNumber: string;
}
const createWorkflowReminderAndExtractPhone = async (
args: CreateWorkflowReminderAndExtractPhoneArgs
): Promise<CreateWorkflowReminderAndExtractPhoneResult> => {
const { evt, workflowStepId, scheduledDate, seatReferenceUid } = args;
// 1) Determine attendee phone first (fail early)
let attendeePhoneNumber = extractPhoneNumber(evt.responses);
if (!attendeePhoneNumber) {
const attendeePhone = evt.attendees?.[0]?.phoneNumber;
if (attendeePhone) {
attendeePhoneNumber = attendeePhone;
} else {
throw new Error(`No attendee phone number found for workflow step ${workflowStepId}`);
}
}
const workflowReminder = await prisma.workflowReminder.create({
data: {
bookingUid: evt.uid as string,
workflowStepId,
method: WorkflowMethods.AI_PHONE_CALL,
scheduledDate: scheduledDate.toDate(),
scheduled: true,
seatReferenceId: seatReferenceUid,
},
});
return { workflowReminder, attendeePhoneNumber };
};
interface ScheduleAIPhoneCallArgs {
evt: BookingInfo;
triggerEvent: WorkflowTriggerEvents;
timeSpan: {
time: number | null;
timeUnit: TimeUnit | null;
};
workflowStepId: number | undefined;
userId: number | null;
teamId: number | null;
seatReferenceUid?: string;
verifiedAt: Date | null;
}
export const scheduleAIPhoneCall = async (args: ScheduleAIPhoneCallArgs) => {
const { evt, triggerEvent, timeSpan, workflowStepId, userId, teamId, seatReferenceUid, verifiedAt } = args;
if (!verifiedAt || !workflowStepId) {
logger.warn(`Workflow step ${workflowStepId} not yet verified or not found`);
return;
}
// Get the workflow step to check if it has an agent configured
const workflowStep = await prisma.workflowStep.findUnique({
where: { id: workflowStepId },
select: {
agent: {
select: {
id: true,
providerAgentId: true,
outboundPhoneNumbers: {
select: {
phoneNumber: true,
subscriptionStatus: true,
},
},
},
},
},
});
const activePhoneNumbers = workflowStep?.agent?.outboundPhoneNumbers?.filter(
(phoneNumber) =>
phoneNumber.subscriptionStatus === PhoneNumberSubscriptionStatus.ACTIVE ||
phoneNumber.subscriptionStatus === null ||
phoneNumber.subscriptionStatus === undefined
);
if (!workflowStep?.agent) {
logger.warn(`No agent configured for workflow step ${workflowStepId}`);
return;
}
if (!workflowStep.agent.outboundPhoneNumbers?.length || !activePhoneNumbers?.length) {
logger.warn(`No active outbound phone number configured for agent ${workflowStep.agent.id}`);
return;
}
const featuresRepository = new FeaturesRepository(prisma);
const calAIVoiceAgents = await featuresRepository.checkIfFeatureIsEnabledGlobally("cal-ai-voice-agents");
if (!calAIVoiceAgents) {
logger.warn("Cal AI voice agents are disabled - skipping AI phone call scheduling");
return;
}
const { startTime, endTime } = evt;
const uid = evt.uid as string;
const currentDate = dayjs();
const timeUnit: timeUnitLowerCase | undefined = timeSpan.timeUnit?.toLocaleLowerCase() as timeUnitLowerCase;
let scheduledDate = null;
// Calculate when the AI phone call should be made
if (triggerEvent === WorkflowTriggerEvents.BEFORE_EVENT) {
scheduledDate = timeSpan.time && timeUnit ? dayjs(startTime).subtract(timeSpan.time, timeUnit) : null;
} else if (triggerEvent === WorkflowTriggerEvents.AFTER_EVENT) {
scheduledDate = timeSpan.time && timeUnit ? dayjs(endTime).add(timeSpan.time, timeUnit) : null;
}
// For immediate triggers (like NEW_EVENT, EVENT_CANCELLED, etc.), schedule immediately
if (!scheduledDate) {
scheduledDate = currentDate;
}
// Determine if we should execute immediately or schedule for later
const shouldExecuteImmediately =
// Immediate triggers (NEW_EVENT, EVENT_CANCELLED, etc.)
!timeSpan.time ||
!timeSpan.timeUnit ||
// Or if the scheduled time has already passed
(scheduledDate && currentDate.isAfter(scheduledDate));
if (!shouldExecuteImmediately) {
try {
const { workflowReminder, attendeePhoneNumber } = await createWorkflowReminderAndExtractPhone({
evt,
workflowStepId,
scheduledDate,
seatReferenceUid,
});
// Schedule the actual AI phone call
await scheduleAIPhoneCallTask({
workflowReminderId: workflowReminder.id,
scheduledDate: scheduledDate.toDate(),
agentId: workflowStep.agent.id,
phoneNumber: activePhoneNumbers[0].phoneNumber,
attendeePhoneNumber,
bookingUid: uid,
userId,
teamId,
providerAgentId: workflowStep.agent.providerAgentId,
referenceUid: workflowReminder.uuid || uuidv4(),
});
logger.info(`AI phone call scheduled for workflow step ${workflowStepId} at ${scheduledDate}`);
} catch (error) {
logger.error(`Error scheduling AI phone call with error ${error}`);
}
} else {
// Execute immediately
try {
const { workflowReminder, attendeePhoneNumber } = await createWorkflowReminderAndExtractPhone({
evt,
workflowStepId,
scheduledDate: currentDate,
seatReferenceUid,
});
// Schedule the actual AI phone call immediatel
// Should i execute the task immediately or schedule it for later?
await scheduleAIPhoneCallTask({
workflowReminderId: workflowReminder.id,
scheduledDate: currentDate.toDate(),
agentId: workflowStep.agent.id,
phoneNumber: activePhoneNumbers[0].phoneNumber,
attendeePhoneNumber,
bookingUid: uid,
userId,
teamId,
providerAgentId: workflowStep.agent.providerAgentId,
referenceUid: workflowReminder.uuid || uuidv4(),
});
logger.info(`AI phone call scheduled for immediate execution for workflow step ${workflowStepId}`);
} catch (error) {
logger.error(`Error scheduling immediate AI phone call with error ${error}`);
}
}
};
interface ScheduleAIPhoneCallTaskArgs {
workflowReminderId: number;
scheduledDate: Date;
agentId: string;
phoneNumber: string;
attendeePhoneNumber: string;
bookingUid: string;
userId: number | null;
teamId: number | null;
providerAgentId: string;
referenceUid: string;
}
const scheduleAIPhoneCallTask = async (args: ScheduleAIPhoneCallTaskArgs) => {
const {
workflowReminderId,
scheduledDate,
agentId,
phoneNumber,
attendeePhoneNumber,
bookingUid,
userId,
teamId,
providerAgentId,
referenceUid,
} = args;
const featuresRepository = new FeaturesRepository(prisma);
const calAIVoiceAgents = await featuresRepository.checkIfFeatureIsEnabledGlobally("cal-ai-voice-agents");
if (!calAIVoiceAgents) {
logger.warn("Cal AI voice agents are disabled - skipping AI phone call");
return;
}
if (userId) {
await checkRateLimitAndThrowError({
rateLimitingType: "core",
identifier: `ai-phone-call:${userId}`,
});
}
try {
await tasker.create(
"executeAIPhoneCall",
{
workflowReminderId,
agentId,
fromNumber: phoneNumber,
toNumber: attendeePhoneNumber,
bookingUid,
userId,
teamId,
providerAgentId,
},
{
scheduledAt: scheduledDate,
maxAttempts: 1,
referenceUid,
}
);
} catch (error) {
console.error("Error creating AI phone call task:", error);
throw error;
}
};
export const deleteScheduledAIPhoneCall = async (reminderId: number, referenceId: string | null) => {
const workflowReminder = await prisma.workflowReminder.findUnique({
where: {
id: reminderId,
},
});
if (!workflowReminder) {
logger.error("AI Phone Call workflow reminder not found");
return;
}
const { uuid } = workflowReminder;
const taskReferenceId = referenceId || uuid;
if (taskReferenceId) {
try {
const taskId = await tasker.cancelWithReference(taskReferenceId, "executeAIPhoneCall");
if (taskId) {
await prisma.workflowReminder.delete({
where: {
id: reminderId,
},
});
logger.info(`AI phone call reminder ${reminderId} cancelled and deleted`);
return;
}
} catch (error) {
logger.error(`Error canceling/deleting AI phone call reminder with tasker. Error: ${error}`);
}
}
// Fallback: If tasker cancellation fails or uuid is not found, just delete the reminder
try {
await prisma.workflowReminder.delete({
where: {
id: reminderId,
},
});
logger.info(`AI phone call reminder ${reminderId} deleted (no task to cancel)`);
} catch (error) {
logger.error(`Error deleting AI phone call reminder ${reminderId}: ${error}`);
}
};