@webex/contact-center 3.12.0-next.73 → 3.12.0-next.74

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (188) hide show
  1. package/AGENTS.md +438 -0
  2. package/ai-docs/README.md +131 -0
  3. package/ai-docs/RULES.md +455 -0
  4. package/ai-docs/patterns/event-driven-patterns.md +485 -0
  5. package/ai-docs/patterns/testing-patterns.md +480 -0
  6. package/ai-docs/patterns/typescript-patterns.md +365 -0
  7. package/ai-docs/templates/README.md +102 -0
  8. package/ai-docs/templates/documentation/create-agents-md.md +240 -0
  9. package/ai-docs/templates/documentation/create-architecture-md.md +295 -0
  10. package/ai-docs/templates/existing-service/bug-fix.md +254 -0
  11. package/ai-docs/templates/existing-service/feature-enhancement.md +450 -0
  12. package/ai-docs/templates/new-method/00-master.md +80 -0
  13. package/ai-docs/templates/new-method/01-requirements.md +232 -0
  14. package/ai-docs/templates/new-method/02-implementation.md +295 -0
  15. package/ai-docs/templates/new-method/03-tests.md +201 -0
  16. package/ai-docs/templates/new-method/04-validation.md +141 -0
  17. package/ai-docs/templates/new-service/00-master.md +109 -0
  18. package/ai-docs/templates/new-service/01-pre-questions.md +159 -0
  19. package/ai-docs/templates/new-service/02-code-generation.md +346 -0
  20. package/ai-docs/templates/new-service/03-integration.md +178 -0
  21. package/ai-docs/templates/new-service/04-test-generation.md +205 -0
  22. package/ai-docs/templates/new-service/05-validation.md +145 -0
  23. package/dist/cc.js +53 -38
  24. package/dist/cc.js.map +1 -1
  25. package/dist/config.js +6 -0
  26. package/dist/config.js.map +1 -1
  27. package/dist/constants.js +14 -1
  28. package/dist/constants.js.map +1 -1
  29. package/dist/index.js +13 -5
  30. package/dist/index.js.map +1 -1
  31. package/dist/metrics/behavioral-events.js +26 -0
  32. package/dist/metrics/behavioral-events.js.map +1 -1
  33. package/dist/metrics/constants.js +9 -3
  34. package/dist/metrics/constants.js.map +1 -1
  35. package/dist/services/ApiAiAssistant.js +74 -3
  36. package/dist/services/ApiAiAssistant.js.map +1 -1
  37. package/dist/services/config/Util.js +2 -2
  38. package/dist/services/config/Util.js.map +1 -1
  39. package/dist/services/config/types.js +25 -9
  40. package/dist/services/config/types.js.map +1 -1
  41. package/dist/services/core/Utils.js +74 -27
  42. package/dist/services/core/Utils.js.map +1 -1
  43. package/dist/services/core/websocket/WebSocketManager.js +2 -1
  44. package/dist/services/core/websocket/WebSocketManager.js.map +1 -1
  45. package/dist/services/core/websocket/types.js.map +1 -1
  46. package/dist/services/index.js +1 -1
  47. package/dist/services/index.js.map +1 -1
  48. package/dist/services/task/Task.js +688 -0
  49. package/dist/services/task/Task.js.map +1 -0
  50. package/dist/services/task/TaskFactory.js +45 -0
  51. package/dist/services/task/TaskFactory.js.map +1 -0
  52. package/dist/services/task/TaskManager.js +725 -612
  53. package/dist/services/task/TaskManager.js.map +1 -1
  54. package/dist/services/task/TaskUtils.js +162 -26
  55. package/dist/services/task/TaskUtils.js.map +1 -1
  56. package/dist/services/task/constants.js +6 -1
  57. package/dist/services/task/constants.js.map +1 -1
  58. package/dist/services/task/digital/Digital.js +77 -0
  59. package/dist/services/task/digital/Digital.js.map +1 -0
  60. package/dist/services/task/state-machine/TaskStateMachine.js +837 -0
  61. package/dist/services/task/state-machine/TaskStateMachine.js.map +1 -0
  62. package/dist/services/task/state-machine/actions.js +543 -0
  63. package/dist/services/task/state-machine/actions.js.map +1 -0
  64. package/dist/services/task/state-machine/constants.js +161 -0
  65. package/dist/services/task/state-machine/constants.js.map +1 -0
  66. package/dist/services/task/state-machine/guards.js +340 -0
  67. package/dist/services/task/state-machine/guards.js.map +1 -0
  68. package/dist/services/task/state-machine/index.js +53 -0
  69. package/dist/services/task/state-machine/index.js.map +1 -0
  70. package/dist/services/task/state-machine/types.js +54 -0
  71. package/dist/services/task/state-machine/types.js.map +1 -0
  72. package/dist/services/task/state-machine/uiControlsComputer.js +553 -0
  73. package/dist/services/task/state-machine/uiControlsComputer.js.map +1 -0
  74. package/dist/services/task/taskDataNormalizer.js +99 -0
  75. package/dist/services/task/taskDataNormalizer.js.map +1 -0
  76. package/dist/services/task/types.js +168 -16
  77. package/dist/services/task/types.js.map +1 -1
  78. package/dist/services/task/voice/Voice.js +1042 -0
  79. package/dist/services/task/voice/Voice.js.map +1 -0
  80. package/dist/services/task/voice/WebRTC.js +149 -0
  81. package/dist/services/task/voice/WebRTC.js.map +1 -0
  82. package/dist/types/cc.d.ts +19 -18
  83. package/dist/types/config.d.ts +6 -0
  84. package/dist/types/constants.d.ts +14 -1
  85. package/dist/types/index.d.ts +11 -5
  86. package/dist/types/metrics/constants.d.ts +7 -1
  87. package/dist/types/services/ApiAiAssistant.d.ts +11 -3
  88. package/dist/types/services/config/types.d.ts +113 -9
  89. package/dist/types/services/core/Utils.d.ts +23 -10
  90. package/dist/types/services/core/websocket/WebSocketManager.d.ts +1 -0
  91. package/dist/types/services/core/websocket/types.d.ts +1 -1
  92. package/dist/types/services/index.d.ts +1 -1
  93. package/dist/types/services/task/Task.d.ts +157 -0
  94. package/dist/types/services/task/TaskFactory.d.ts +12 -0
  95. package/dist/types/services/task/TaskUtils.d.ts +46 -2
  96. package/dist/types/services/task/constants.d.ts +5 -0
  97. package/dist/types/services/task/digital/Digital.d.ts +22 -0
  98. package/dist/types/services/task/state-machine/TaskStateMachine.d.ts +1144 -0
  99. package/dist/types/services/task/state-machine/actions.d.ts +10 -0
  100. package/dist/types/services/task/state-machine/constants.d.ts +107 -0
  101. package/dist/types/services/task/state-machine/guards.d.ts +90 -0
  102. package/dist/types/services/task/state-machine/index.d.ts +13 -0
  103. package/dist/types/services/task/state-machine/types.d.ts +267 -0
  104. package/dist/types/services/task/state-machine/uiControlsComputer.d.ts +9 -0
  105. package/dist/types/services/task/taskDataNormalizer.d.ts +10 -0
  106. package/dist/types/services/task/types.d.ts +551 -78
  107. package/dist/types/services/task/voice/Voice.d.ts +184 -0
  108. package/dist/types/services/task/voice/WebRTC.d.ts +53 -0
  109. package/dist/types/types.d.ts +92 -0
  110. package/dist/types/webex.d.ts +1 -0
  111. package/dist/types.js +85 -0
  112. package/dist/types.js.map +1 -1
  113. package/dist/webex.js +14 -2
  114. package/dist/webex.js.map +1 -1
  115. package/package.json +15 -12
  116. package/src/cc.ts +63 -43
  117. package/src/config.ts +6 -0
  118. package/src/constants.ts +14 -1
  119. package/src/index.ts +14 -5
  120. package/src/metrics/ai-docs/AGENTS.md +348 -0
  121. package/src/metrics/ai-docs/ARCHITECTURE.md +336 -0
  122. package/src/metrics/behavioral-events.ts +28 -0
  123. package/src/metrics/constants.ts +9 -4
  124. package/src/services/ApiAiAssistant.ts +104 -3
  125. package/src/services/agent/ai-docs/AGENTS.md +238 -0
  126. package/src/services/agent/ai-docs/ARCHITECTURE.md +302 -0
  127. package/src/services/ai-docs/AGENTS.md +384 -0
  128. package/src/services/config/Util.ts +2 -2
  129. package/src/services/config/ai-docs/AGENTS.md +253 -0
  130. package/src/services/config/ai-docs/ARCHITECTURE.md +424 -0
  131. package/src/services/config/types.ts +116 -10
  132. package/src/services/core/Utils.ts +85 -34
  133. package/src/services/core/ai-docs/AGENTS.md +379 -0
  134. package/src/services/core/ai-docs/ARCHITECTURE.md +696 -0
  135. package/src/services/core/websocket/WebSocketManager.ts +2 -0
  136. package/src/services/core/websocket/types.ts +1 -1
  137. package/src/services/index.ts +1 -1
  138. package/src/services/task/Task.ts +837 -0
  139. package/src/services/task/TaskFactory.ts +55 -0
  140. package/src/services/task/TaskManager.ts +738 -697
  141. package/src/services/task/TaskUtils.ts +205 -25
  142. package/src/services/task/ai-docs/AGENTS.md +455 -0
  143. package/src/services/task/ai-docs/ARCHITECTURE.md +585 -0
  144. package/src/services/task/constants.ts +5 -0
  145. package/src/services/task/digital/Digital.ts +95 -0
  146. package/src/services/task/state-machine/TaskStateMachine.ts +1077 -0
  147. package/src/services/task/state-machine/actions.ts +685 -0
  148. package/src/services/task/state-machine/ai-docs/AGENTS.md +495 -0
  149. package/src/services/task/state-machine/ai-docs/ARCHITECTURE.md +1135 -0
  150. package/src/services/task/state-machine/constants.ts +172 -0
  151. package/src/services/task/state-machine/guards.ts +406 -0
  152. package/src/services/task/state-machine/index.ts +28 -0
  153. package/src/services/task/state-machine/types.ts +241 -0
  154. package/src/services/task/state-machine/uiControlsComputer.ts +867 -0
  155. package/src/services/task/taskDataNormalizer.ts +137 -0
  156. package/src/services/task/types.ts +654 -85
  157. package/src/services/task/voice/Voice.ts +1267 -0
  158. package/src/services/task/voice/WebRTC.ts +187 -0
  159. package/src/types.ts +112 -1
  160. package/src/utils/AGENTS.md +276 -0
  161. package/src/webex.js +2 -0
  162. package/test/unit/spec/cc.ts +133 -3
  163. package/test/unit/spec/logger-proxy.ts +70 -0
  164. package/test/unit/spec/services/ApiAiAssistant.ts +122 -17
  165. package/test/unit/spec/services/WebCallingService.ts +7 -1
  166. package/test/unit/spec/services/config/index.ts +27 -27
  167. package/test/unit/spec/services/core/Utils.ts +335 -1
  168. package/test/unit/spec/services/core/websocket/WebSocketManager.ts +66 -40
  169. package/test/unit/spec/services/task/AutoWrapup.ts +63 -0
  170. package/test/unit/spec/services/task/Task.ts +477 -0
  171. package/test/unit/spec/services/task/TaskFactory.ts +62 -0
  172. package/test/unit/spec/services/task/TaskManager.ts +821 -1936
  173. package/test/unit/spec/services/task/TaskUtils.ts +206 -0
  174. package/test/unit/spec/services/task/digital/Digital.ts +105 -0
  175. package/test/unit/spec/services/task/state-machine/TaskStateMachine.ts +1825 -0
  176. package/test/unit/spec/services/task/state-machine/guards.ts +479 -0
  177. package/test/unit/spec/services/task/state-machine/types.ts +18 -0
  178. package/test/unit/spec/services/task/state-machine/uiControlsComputer.ts +2020 -0
  179. package/test/unit/spec/services/task/taskTestUtils.ts +87 -0
  180. package/test/unit/spec/services/task/voice/Voice.ts +631 -0
  181. package/test/unit/spec/services/task/voice/WebRTC.ts +235 -0
  182. package/umd/contact-center.min.js +2 -2
  183. package/umd/contact-center.min.js.map +1 -1
  184. package/dist/services/task/index.js +0 -1530
  185. package/dist/services/task/index.js.map +0 -1
  186. package/dist/types/services/task/index.d.ts +0 -650
  187. package/src/services/task/index.ts +0 -1806
  188. package/test/unit/spec/services/task/index.ts +0 -2205
@@ -1,1806 +0,0 @@
1
- import EventEmitter from 'events';
2
- import {CALL_EVENT_KEYS, LocalMicrophoneStream} from '@webex/calling';
3
- import {CallId} from '@webex/calling/dist/types/common/types';
4
- import {generateTaskErrorObject, calculateDestAgentId, calculateDestType} from '../core/Utils';
5
- import {Failure} from '../core/GlobalTypes';
6
- import {LoginOption} from '../../types';
7
- import {TASK_FILE} from '../../constants';
8
- import {METHODS, KEYS_TO_NOT_DELETE} from './constants';
9
- import routingContact from './contact';
10
- import LoggerProxy from '../../logger-proxy';
11
- import {
12
- ITask,
13
- TaskResponse,
14
- TaskData,
15
- TaskId,
16
- TASK_EVENTS,
17
- WrapupPayLoad,
18
- ResumeRecordingPayload,
19
- ConsultPayload,
20
- ConsultEndPayload,
21
- TransferPayLoad,
22
- DESTINATION_TYPE,
23
- ConsultTransferPayLoad,
24
- MEDIA_CHANNEL,
25
- } from './types';
26
- import WebCallingService from '../WebCallingService';
27
- import MetricsManager from '../../metrics/MetricsManager';
28
- import {METRIC_EVENT_NAMES} from '../../metrics/constants';
29
- import AutoWrapup from './AutoWrapup';
30
- import {WrapupData} from '../config/types';
31
-
32
- /**
33
- * Task class represents a contact center task/interaction that can be managed by an agent.
34
- * This class provides all the necessary methods to manage tasks in a contact center environment,
35
- * handling various call control operations and task lifecycle management.
36
- *
37
- * - Task Lifecycle Management:
38
- * - {@link accept} - Accept incoming task
39
- * - {@link decline} - Decline incoming task
40
- * - {@link end} - End active task
41
- * - Media Controls:
42
- * - {@link toggleMute} - Mute/unmute microphone for voice tasks
43
- * - {@link hold} - Place task on hold
44
- * - {@link resume} - Resume held task
45
- * - Recording Controls:
46
- * - {@link pauseRecording} - Pause task recording
47
- * - {@link resumeRecording} - Resume paused recording
48
- * - Task Transfer & Consultation:
49
- * - {@link consult} - Initiate consultation with another agent/queue
50
- * - {@link endConsult} - End ongoing consultation
51
- * - {@link transfer} - Transfer task to another agent/queue
52
- * - {@link consultTransfer} - Transfer after consultation
53
- * - Task Completion:
54
- * - {@link wrapup} - Complete task wrap-up
55
- *
56
- * Key events emitted by Task instances (see {@link TASK_EVENTS} for details):
57
- *
58
- * - Task Lifecycle:
59
- * - task:incoming — New task is being offered
60
- * - task:assigned — Task assigned to agent
61
- * - task:unassigned — Task unassigned from agent
62
- * - task:end — Task has ended
63
- * - task:wrapup — Task entered wrap-up state
64
- * - task:wrappedup — Task wrap-up completed
65
- * - task:rejected — Task was rejected/unanswered
66
- * - task:hydrate — Task data populated
67
- *
68
- * - Media & Controls:
69
- * - task:media — Voice call media track received
70
- * - task:hold — Task placed on hold
71
- * - task:unhold — Task resumed from hold
72
- *
73
- * - Consultation & Transfer:
74
- * - task:consultCreated — Consultation initiated
75
- * - task:consulting — Consultation in progress
76
- * - task:consultAccepted — Consultation accepted
77
- * - task:consultEnd — Consultation ended
78
- * - task:consultQueueCancelled — Queue consultation cancelled
79
- * - task:consultQueueFailed — Queue consultation failed
80
- * - task:offerConsult — Consultation offered
81
- * - task:offerContact — New contact offered
82
- *
83
- * - Recording:
84
- * - task:recordingPaused — Recording paused
85
- * - task:recordingPauseFailed — Recording pause failed
86
- * - task:recordingResumed — Recording resumed
87
- * - task:recordingResumeFailed — Recording resume failed
88
- *
89
- * @implements {ITask}
90
- * @example
91
- * ```typescript
92
- * // 1. Initialize task
93
- * const task = new Task(contact, webCallingService, taskData);
94
- *
95
- * // 2. Set up event listeners
96
- * task.on('task:media', (track) => {
97
- * // Handle voice call media
98
- * const audioElement = document.getElementById('remote-audio');
99
- * audioElement.srcObject = new MediaStream([track]);
100
- * });
101
- *
102
- * task.on('task:hold', () => {
103
- * console.log('Task is on hold');
104
- * // Update UI to show hold state
105
- * });
106
- *
107
- * task.on('task:end', () => {
108
- * console.log('Task ended');
109
- * if (task.data.wrapUpRequired) {
110
- * // Show wrap-up form
111
- * }
112
- * });
113
- *
114
- * // 3. Example task operations
115
- * await task.accept(); // Accept incoming task
116
- * await task.hold(); // Place on hold
117
- * await task.resume(); // Resume from hold
118
- * await task.end(); // End task
119
- *
120
- * // 4. Handle wrap-up if required
121
- * await task.wrapup({
122
- * auxCodeId: 'RESOLVED',
123
- * wrapUpReason: 'Customer issue resolved'
124
- * });
125
- * ```
126
- */
127
-
128
- export default class Task extends EventEmitter implements ITask {
129
- private contact: ReturnType<typeof routingContact>;
130
- private localAudioStream: LocalMicrophoneStream;
131
- private webCallingService: WebCallingService;
132
- public data: TaskData;
133
- private metricsManager: MetricsManager;
134
- public webCallMap: Record<TaskId, CallId>;
135
- private wrapupData: WrapupData;
136
- public autoWrapup?: AutoWrapup;
137
- private agentId: string;
138
-
139
- /**
140
- * Creates a new Task instance which provides the following features:
141
- * @param contact - The routing contact service instance
142
- * @param webCallingService - The web calling service instance
143
- * @param data - Initial task data
144
- * @param wrapupData - Wrap-up configuration data
145
- */
146
- public constructor(
147
- contact: ReturnType<typeof routingContact>,
148
- webCallingService: WebCallingService,
149
- data: TaskData,
150
- wrapupData: WrapupData,
151
- agentId: string
152
- ) {
153
- super();
154
- this.contact = contact;
155
- this.data = data;
156
- this.webCallingService = webCallingService;
157
- this.webCallMap = {};
158
- this.wrapupData = wrapupData;
159
- this.metricsManager = MetricsManager.getInstance();
160
- this.registerWebCallListeners();
161
- this.setupAutoWrapupTimer();
162
- this.agentId = agentId;
163
- }
164
-
165
- /**
166
- * Sets up the automatic wrap-up timer if wrap-up is required
167
- * @private
168
- */
169
- private setupAutoWrapupTimer() {
170
- if (
171
- this.data.wrapUpRequired && // only when wrapup required
172
- !this.autoWrapup && // if autoWrapup is not already set
173
- this.wrapupData && // wrapupData is not defined
174
- this.wrapupData.wrapUpProps // wrapUpProps is defined
175
- ) {
176
- const wrapUpProps = this.wrapupData.wrapUpProps;
177
- if (!wrapUpProps || wrapUpProps.autoWrapup === false) {
178
- LoggerProxy.info(`Auto wrap-up is not required for this task`, {
179
- module: TASK_FILE,
180
- method: METHODS.SETUP_AUTO_WRAPUP_TIMER,
181
- interactionId: this.data.interactionId,
182
- });
183
-
184
- return;
185
- }
186
- const defaultWrapupReason =
187
- wrapUpProps.wrapUpReasonList?.find((r) => r.isDefault) ?? wrapUpProps.wrapUpReasonList?.[0];
188
- if (!defaultWrapupReason) {
189
- LoggerProxy.error('No wrap-up reason configured', {
190
- module: TASK_FILE,
191
- method: METHODS.SETUP_AUTO_WRAPUP_TIMER,
192
- });
193
-
194
- return;
195
- }
196
- const intervalMs = wrapUpProps.autoWrapupInterval;
197
- if (!intervalMs || intervalMs <= 0) {
198
- LoggerProxy.error(`Invalid auto wrap-up interval: ${intervalMs}`, {
199
- module: TASK_FILE,
200
- method: METHODS.SETUP_AUTO_WRAPUP_TIMER,
201
- });
202
- }
203
- this.autoWrapup = new AutoWrapup(intervalMs, wrapUpProps.allowCancelAutoWrapup);
204
- this.autoWrapup.start(async () => {
205
- LoggerProxy.info(`Auto wrap-up timer triggered`, {
206
- module: TASK_FILE,
207
- method: METHODS.SETUP_AUTO_WRAPUP_TIMER,
208
- interactionId: this.data.interactionId,
209
- });
210
- await this.wrapup({
211
- wrapUpReason: defaultWrapupReason.name,
212
- auxCodeId: defaultWrapupReason.id,
213
- });
214
- });
215
- }
216
- }
217
-
218
- /**
219
- * Cancels the automatic wrap-up timer if it's running
220
- * @public - Public so it can be called externally when needed
221
- * Note: This is supported only in single session mode. Not supported in multi-session mode.
222
- */
223
- public cancelAutoWrapupTimer() {
224
- this.autoWrapup?.clear();
225
- this.autoWrapup = undefined;
226
- LoggerProxy.info(`Auto wrap-up timer cancelled`, {
227
- module: TASK_FILE,
228
- method: METHODS.CANCEL_AUTO_WRAPUP_TIMER,
229
- interactionId: this.data?.interactionId,
230
- });
231
- }
232
-
233
- /**
234
- * @ignore
235
- * @private
236
- */
237
- private handleRemoteMedia = (track: MediaStreamTrack) => {
238
- this.emit(TASK_EVENTS.TASK_MEDIA, track);
239
- };
240
-
241
- /**
242
- * @ignore
243
- * @private
244
- */
245
- private registerWebCallListeners() {
246
- this.webCallingService.on(CALL_EVENT_KEYS.REMOTE_MEDIA, this.handleRemoteMedia);
247
- }
248
-
249
- /**
250
- * @ignore
251
- */
252
- public unregisterWebCallListeners() {
253
- this.webCallingService.off(CALL_EVENT_KEYS.REMOTE_MEDIA, this.handleRemoteMedia);
254
- }
255
-
256
- /**
257
- * Updates the task data with new information
258
- * @param updatedData - New task data to merge with existing data
259
- * @param shouldOverwrite - If true, completely replace data instead of merging
260
- * @returns The updated task instance
261
- * @example
262
- * ```typescript
263
- * task.updateTaskData(newData);
264
- * task.updateTaskData(newData, true); // completely replace data
265
- * ```
266
- */
267
- public updateTaskData = (updatedData: TaskData, shouldOverwrite = false) => {
268
- this.data = shouldOverwrite ? updatedData : this.reconcileData(this.data, updatedData);
269
- this.setupAutoWrapupTimer();
270
-
271
- return this;
272
- };
273
-
274
- /**
275
- * Recursively merges old data with new data
276
- * @private
277
- */
278
- private reconcileData(oldData: TaskData, newData: TaskData): TaskData {
279
- // Remove keys from oldData that are not in newData
280
- Object.keys(oldData).forEach((key) => {
281
- if (!(key in newData) && !KEYS_TO_NOT_DELETE.includes(key as string)) {
282
- delete oldData[key];
283
- }
284
- });
285
-
286
- // Merge or update keys from newData
287
- Object.keys(newData).forEach((key) => {
288
- if (
289
- newData[key] &&
290
- typeof newData[key] === 'object' &&
291
- !Array.isArray(newData[key]) &&
292
- oldData[key] &&
293
- typeof oldData[key] === 'object' &&
294
- !Array.isArray(oldData[key])
295
- ) {
296
- this.reconcileData(oldData[key], newData[key]);
297
- } else {
298
- oldData[key] = newData[key];
299
- }
300
- });
301
-
302
- return oldData;
303
- }
304
-
305
- /**
306
- * Agent accepts the incoming task.
307
- * After accepting, the task will emit task:assigned event and for voice calls,
308
- * a task:media event with the audio stream.
309
- *
310
- * @returns Promise<TaskResponse>
311
- * @throws Error if accepting task fails or media requirements not met
312
- * @example
313
- * ```typescript
314
- * // Set up event handlers before accepting
315
- * task.on(TASK_EVENTS.TASK_ASSIGNED, () => {
316
- * console.log('Task assigned, ID:', task.data.interactionId);
317
- * // Update UI to show active task
318
- * });
319
- *
320
- * // For voice calls, handle media
321
- * task.on(TASK_EVENTS.TASK_MEDIA, (track) => {
322
- * const audioElement = document.getElementById('remote-audio');
323
- * audioElement.srcObject = new MediaStream([track]);
324
- * });
325
- *
326
- * // Accept the task
327
- * try {
328
- * await task.accept();
329
- * console.log('Successfully accepted task');
330
- * } catch (error) {
331
- * console.error('Failed to accept task:', error);
332
- * // Handle error (e.g., show error message to agent)
333
- * }
334
- * ```
335
- */
336
- public async accept(): Promise<TaskResponse> {
337
- try {
338
- LoggerProxy.info(`Accepting task`, {
339
- module: TASK_FILE,
340
- method: METHODS.ACCEPT,
341
- interactionId: this.data.interactionId,
342
- });
343
- this.metricsManager.timeEvent([
344
- METRIC_EVENT_NAMES.TASK_ACCEPT_SUCCESS,
345
- METRIC_EVENT_NAMES.TASK_ACCEPT_FAILED,
346
- ]);
347
-
348
- if (this.data.interaction.mediaType !== MEDIA_CHANNEL.TELEPHONY) {
349
- const response = await this.contact.accept({interactionId: this.data.interactionId});
350
- LoggerProxy.log(`Task accepted successfully`, {
351
- module: TASK_FILE,
352
- method: METHODS.ACCEPT,
353
- trackingId: response.trackingId,
354
- interactionId: this.data.interactionId,
355
- });
356
- this.metricsManager.trackEvent(
357
- METRIC_EVENT_NAMES.TASK_ACCEPT_SUCCESS,
358
- {
359
- taskId: this.data.interactionId,
360
- ...MetricsManager.getCommonTrackingFieldForAQMResponse(this.data),
361
- },
362
- ['operational', 'behavioral', 'business']
363
- );
364
-
365
- return response;
366
- }
367
-
368
- if (this.webCallingService.loginOption === LoginOption.BROWSER) {
369
- const constraints = {audio: true};
370
-
371
- const localStream = await navigator.mediaDevices.getUserMedia(constraints);
372
- const audioTrack = localStream.getAudioTracks()[0];
373
- this.localAudioStream = new LocalMicrophoneStream(new MediaStream([audioTrack]));
374
- this.webCallingService.answerCall(this.localAudioStream, this.data.interactionId);
375
- this.metricsManager.trackEvent(
376
- METRIC_EVENT_NAMES.TASK_ACCEPT_SUCCESS,
377
- {
378
- taskId: this.data.interactionId,
379
- ...MetricsManager.getCommonTrackingFieldForAQMResponse(this.data),
380
- },
381
- ['operational', 'behavioral', 'business']
382
- );
383
-
384
- LoggerProxy.log(`Task accepted successfully with webrtc calling`, {
385
- module: TASK_FILE,
386
- method: METHODS.ACCEPT,
387
- interactionId: this.data.interactionId,
388
- });
389
- }
390
-
391
- return Promise.resolve(); // TODO: reject for extension as part of refactor
392
- } catch (error) {
393
- const err = generateTaskErrorObject(error, METHODS.ACCEPT, TASK_FILE);
394
- const taskErrorProps = {
395
- trackingId: err.data?.trackingId,
396
- errorMessage: err.data?.message,
397
- errorType: err.data?.errorType,
398
- errorData: err.data?.errorData,
399
- reasonCode: err.data?.reasonCode,
400
- };
401
- this.metricsManager.trackEvent(
402
- METRIC_EVENT_NAMES.TASK_ACCEPT_FAILED,
403
- {
404
- taskId: this.data.interactionId,
405
- error: error.toString(),
406
- ...taskErrorProps,
407
- ...MetricsManager.getCommonTrackingFieldForAQMResponseFailed(error.details as Failure),
408
- },
409
- ['operational', 'behavioral', 'business']
410
- );
411
- throw err;
412
- }
413
- }
414
-
415
- /**
416
- * Agent can mute/unmute their microphone during a WebRTC task.
417
- * This method toggles between muted and unmuted states for the local audio stream.
418
- *
419
- * @returns Promise<void> - Resolves when mute/unmute operation completes
420
- * @throws Error if toggling mute state fails or audio stream is not available
421
- * @example
422
- * ```typescript
423
- * // Toggle mute state
424
- * task.toggleMute()
425
- * .then(() => console.log('Mute state toggled successfully'))
426
- * .catch(error => console.error('Failed to toggle mute:', error));
427
- * ```
428
- */
429
- public async toggleMute() {
430
- try {
431
- LoggerProxy.info(`Toggling mute state`, {
432
- module: TASK_FILE,
433
- method: METHODS.TOGGLE_MUTE,
434
- interactionId: this.data.interactionId,
435
- });
436
-
437
- this.webCallingService.muteUnmuteCall(this.localAudioStream);
438
-
439
- LoggerProxy.log(
440
- `Mute state toggled successfully isCallMuted: ${this.webCallingService.isCallMuted()}`,
441
- {
442
- module: TASK_FILE,
443
- method: METHODS.TOGGLE_MUTE,
444
- interactionId: this.data.interactionId,
445
- }
446
- );
447
-
448
- return Promise.resolve();
449
- } catch (error) {
450
- const err = generateTaskErrorObject(error, METHODS.TOGGLE_MUTE, TASK_FILE);
451
- throw err;
452
- }
453
- }
454
-
455
- /**
456
- * Declines the incoming task. This will reject the task and notify the routing system.
457
- * For voice calls, this is equivalent to declining the incoming call.
458
- *
459
- * @returns Promise<TaskResponse>
460
- * @throws Error if the decline operation fails
461
- * @example
462
- * ```typescript
463
- * // Decline an incoming task
464
- * task.decline()
465
- * .then(() => console.log('Task declined successfully'))
466
- * .catch(error => console.error('Failed to decline task:', error));
467
- * ```
468
- */
469
- public async decline(): Promise<TaskResponse> {
470
- try {
471
- LoggerProxy.info(`Declining task`, {
472
- module: TASK_FILE,
473
- method: METHODS.DECLINE,
474
- interactionId: this.data.interactionId,
475
- });
476
- this.metricsManager.timeEvent([
477
- METRIC_EVENT_NAMES.TASK_DECLINE_SUCCESS,
478
- METRIC_EVENT_NAMES.TASK_DECLINE_FAILED,
479
- ]);
480
-
481
- this.webCallingService.declineCall(this.data.interactionId);
482
- this.unregisterWebCallListeners();
483
-
484
- this.metricsManager.trackEvent(
485
- METRIC_EVENT_NAMES.TASK_DECLINE_SUCCESS,
486
- {taskId: this.data.interactionId},
487
- ['operational', 'behavioral']
488
- );
489
-
490
- LoggerProxy.log(`Task declined successfully`, {
491
- module: TASK_FILE,
492
- method: METHODS.DECLINE,
493
- interactionId: this.data.interactionId,
494
- });
495
-
496
- return Promise.resolve();
497
- } catch (error) {
498
- const err = generateTaskErrorObject(error, METHODS.DECLINE, TASK_FILE);
499
- const taskErrorProps = {
500
- trackingId: err.data?.trackingId,
501
- errorMessage: err.data?.message,
502
- errorType: err.data?.errorType,
503
- errorData: err.data?.errorData,
504
- reasonCode: err.data?.reasonCode,
505
- };
506
- this.metricsManager.trackEvent(
507
- METRIC_EVENT_NAMES.TASK_DECLINE_FAILED,
508
- {
509
- taskId: this.data.interactionId,
510
- error: error.toString(),
511
- ...taskErrorProps,
512
- ...MetricsManager.getCommonTrackingFieldForAQMResponseFailed(error.details || {}),
513
- },
514
- ['operational', 'behavioral']
515
- );
516
- throw err;
517
- }
518
- }
519
-
520
- /**
521
- * Puts the current task/interaction on hold.
522
- * Emits task:hold event when successful. For voice tasks, this mutes the audio.
523
- *
524
- * @param mediaResourceId - Optional media resource ID to use for the hold operation. If not provided, uses the task's current mediaResourceId
525
- * @returns Promise<TaskResponse>
526
- * @throws Error if hold operation fails
527
- * @example
528
- * ```typescript
529
- * // Set up hold event handler
530
- * task.on(TASK_EVENTS.TASK_HOLD, () => {
531
- * console.log('Task is now on hold');
532
- * // Update UI to show hold state (e.g., enable resume button, show hold indicator)
533
- * document.getElementById('resume-btn').disabled = false;
534
- * document.getElementById('hold-indicator').style.display = 'block';
535
- * });
536
- *
537
- * // Place task on hold
538
- * try {
539
- * await task.hold();
540
- * console.log('Successfully placed task on hold');
541
- * } catch (error) {
542
- * console.error('Failed to place task on hold:', error);
543
- * // Handle error (e.g., show error message, reset UI state)
544
- * }
545
- *
546
- * // Place task on hold with custom mediaResourceId
547
- * try {
548
- * await task.hold('custom-media-resource-id');
549
- * console.log('Successfully placed task on hold with custom mediaResourceId');
550
- * } catch (error) {
551
- * console.error('Failed to place task on hold:', error);
552
- * }
553
- * ```
554
- */
555
- public async hold(mediaResourceId?: string): Promise<TaskResponse> {
556
- try {
557
- LoggerProxy.info(`Holding task`, {
558
- module: TASK_FILE,
559
- method: METHODS.HOLD,
560
- interactionId: this.data.interactionId,
561
- });
562
-
563
- this.metricsManager.timeEvent([
564
- METRIC_EVENT_NAMES.TASK_HOLD_SUCCESS,
565
- METRIC_EVENT_NAMES.TASK_HOLD_FAILED,
566
- ]);
567
-
568
- const {mainInteractionId} = this.data.interaction;
569
- const defaultMediaResourceId =
570
- this.data.interaction.media[mainInteractionId]?.mediaResourceId;
571
- const effectiveMediaResourceId = mediaResourceId ?? defaultMediaResourceId;
572
-
573
- const response = await this.contact.hold({
574
- interactionId: this.data.interactionId,
575
- data: {mediaResourceId: effectiveMediaResourceId},
576
- });
577
-
578
- this.metricsManager.trackEvent(
579
- METRIC_EVENT_NAMES.TASK_HOLD_SUCCESS,
580
- {
581
- ...MetricsManager.getCommonTrackingFieldForAQMResponse(response),
582
- taskId: this.data.interactionId,
583
- mediaResourceId: effectiveMediaResourceId,
584
- },
585
- ['operational', 'behavioral']
586
- );
587
-
588
- LoggerProxy.log(`Task placed on hold successfully`, {
589
- module: TASK_FILE,
590
- method: METHODS.HOLD,
591
- trackingId: response.trackingId,
592
- interactionId: this.data.interactionId,
593
- });
594
-
595
- return response;
596
- } catch (error) {
597
- const err = generateTaskErrorObject(error, METHODS.HOLD, TASK_FILE);
598
- const taskErrorProps = {
599
- trackingId: err.data?.trackingId,
600
- errorMessage: err.data?.message,
601
- errorType: err.data?.errorType,
602
- errorData: err.data?.errorData,
603
- reasonCode: err.data?.reasonCode,
604
- };
605
- const defaultMediaResourceId =
606
- this.data.interaction.media[this.data.interaction.mainInteractionId]?.mediaResourceId;
607
- const effectiveMediaResourceId = mediaResourceId ?? defaultMediaResourceId;
608
-
609
- this.metricsManager.trackEvent(
610
- METRIC_EVENT_NAMES.TASK_HOLD_FAILED,
611
- {
612
- taskId: this.data.interactionId,
613
- mediaResourceId: effectiveMediaResourceId,
614
- error: error.toString(),
615
- ...taskErrorProps,
616
- ...MetricsManager.getCommonTrackingFieldForAQMResponseFailed(error.details || {}),
617
- },
618
- ['operational', 'behavioral']
619
- );
620
- throw err;
621
- }
622
- }
623
-
624
- /**
625
- * Resumes the task/interaction that was previously put on hold.
626
- * Emits task:resume event when successful. For voice tasks, this restores the audio.
627
- *
628
- * @param mediaResourceId - Optional media resource ID to use for the resume operation. If not provided, uses the task's current mediaResourceId from interaction media
629
- * @returns Promise<TaskResponse>
630
- * @throws Error if resume operation fails
631
- * @example
632
- * ```typescript
633
- * // Set up resume event handler
634
- * task.on(TASK_EVENTS.TASK_RESUME, () => {
635
- * console.log('Task resumed from hold');
636
- * // Update UI to show active state
637
- * document.getElementById('hold-btn').disabled = false;
638
- * document.getElementById('hold-indicator').style.display = 'none';
639
- * });
640
- *
641
- * // Resume task from hold
642
- * try {
643
- * await task.resume();
644
- * console.log('Successfully resumed task from hold');
645
- * } catch (error) {
646
- * console.error('Failed to resume task:', error);
647
- * // Handle error (e.g., show error message)
648
- * }
649
- *
650
- * // Resume task from hold with custom mediaResourceId
651
- * try {
652
- * await task.resume('custom-media-resource-id');
653
- * console.log('Successfully resumed task from hold with custom mediaResourceId');
654
- * } catch (error) {
655
- * console.error('Failed to resume task:', error);
656
- * }
657
- * ```
658
- */
659
- public async resume(mediaResourceId?: string): Promise<TaskResponse> {
660
- try {
661
- LoggerProxy.info(`Resuming task`, {
662
- module: TASK_FILE,
663
- method: METHODS.RESUME,
664
- interactionId: this.data.interactionId,
665
- });
666
- const {mainInteractionId} = this.data.interaction;
667
- const defaultMediaResourceId =
668
- this.data.interaction.media[mainInteractionId]?.mediaResourceId;
669
- const effectiveMediaResourceId = mediaResourceId ?? defaultMediaResourceId;
670
-
671
- this.metricsManager.timeEvent([
672
- METRIC_EVENT_NAMES.TASK_RESUME_SUCCESS,
673
- METRIC_EVENT_NAMES.TASK_RESUME_FAILED,
674
- ]);
675
-
676
- const response = await this.contact.unHold({
677
- interactionId: this.data.interactionId,
678
- data: {mediaResourceId: effectiveMediaResourceId},
679
- });
680
-
681
- this.metricsManager.trackEvent(
682
- METRIC_EVENT_NAMES.TASK_RESUME_SUCCESS,
683
- {
684
- taskId: this.data.interactionId,
685
- mainInteractionId,
686
- mediaResourceId: effectiveMediaResourceId,
687
- ...MetricsManager.getCommonTrackingFieldForAQMResponse(response),
688
- },
689
- ['operational', 'behavioral']
690
- );
691
-
692
- LoggerProxy.log(`Task resumed successfully`, {
693
- module: TASK_FILE,
694
- method: METHODS.RESUME,
695
- trackingId: response.trackingId,
696
- interactionId: this.data.interactionId,
697
- });
698
-
699
- return response;
700
- } catch (error) {
701
- const err = generateTaskErrorObject(error, METHODS.RESUME, TASK_FILE);
702
- const mainInteractionId = this.data.interaction?.mainInteractionId;
703
- const defaultMediaResourceId = mainInteractionId
704
- ? this.data.interaction.media[mainInteractionId]?.mediaResourceId
705
- : '';
706
- const effectiveMediaResourceId = mediaResourceId ?? defaultMediaResourceId;
707
-
708
- const taskErrorProps = {
709
- trackingId: err.data?.trackingId,
710
- errorMessage: err.data?.message,
711
- errorType: err.data?.errorType,
712
- errorData: err.data?.errorData,
713
- reasonCode: err.data?.reasonCode,
714
- };
715
- this.metricsManager.trackEvent(
716
- METRIC_EVENT_NAMES.TASK_RESUME_FAILED,
717
- {
718
- taskId: this.data.interactionId,
719
- mainInteractionId,
720
- mediaResourceId: effectiveMediaResourceId,
721
- ...taskErrorProps,
722
- ...MetricsManager.getCommonTrackingFieldForAQMResponseFailed(error.details || {}),
723
- },
724
- ['operational', 'behavioral']
725
- );
726
- throw err;
727
- }
728
- }
729
-
730
- /**
731
- * Ends the task/interaction with the customer.
732
- * Emits task:end event when successful. If task requires wrap-up,
733
- * this will be indicated in the task:end event data.
734
- *
735
- * @returns Promise<TaskResponse>
736
- * @throws Error if ending task fails
737
- * @example
738
- * ```typescript
739
- * // Set up task end event handler
740
- * task.on(TASK_EVENTS.TASK_END, (data) => {
741
- * console.log('Task ended:', task.data.interactionId);
742
- *
743
- * if (data.wrapUpRequired) {
744
- * // Show wrap-up form
745
- * showWrapupForm();
746
- * } else {
747
- * // Clean up and prepare for next task
748
- * cleanupTask();
749
- * }
750
- * });
751
- *
752
- * // End the task
753
- * try {
754
- * await task.end();
755
- * console.log('Task end request successful');
756
- * } catch (error) {
757
- * console.error('Failed to end task:', error);
758
- * // Handle error (e.g., show error message, retry option)
759
- * }
760
- *
761
- * function showWrapupForm() {
762
- * // Show wrap-up UI with required codes
763
- * document.getElementById('wrapup-form').style.display = 'block';
764
- * }
765
- *
766
- * function cleanupTask() {
767
- * // Reset UI state
768
- * document.getElementById('active-task').style.display = 'none';
769
- * document.getElementById('controls').style.display = 'none';
770
- * }
771
- * ```
772
- */
773
- public async end(): Promise<TaskResponse> {
774
- try {
775
- LoggerProxy.info(`Ending task`, {
776
- module: TASK_FILE,
777
- method: METHODS.END,
778
- interactionId: this.data.interactionId,
779
- });
780
-
781
- this.metricsManager.timeEvent([
782
- METRIC_EVENT_NAMES.TASK_END_SUCCESS,
783
- METRIC_EVENT_NAMES.TASK_END_FAILED,
784
- ]);
785
-
786
- const response = await this.contact.end({interactionId: this.data.interactionId});
787
-
788
- this.metricsManager.trackEvent(
789
- METRIC_EVENT_NAMES.TASK_END_SUCCESS,
790
- {
791
- taskId: this.data.interactionId,
792
- ...MetricsManager.getCommonTrackingFieldForAQMResponse(response),
793
- },
794
- ['operational', 'behavioral', 'business']
795
- );
796
-
797
- LoggerProxy.log(`Task ended successfully`, {
798
- module: TASK_FILE,
799
- method: METHODS.END,
800
- trackingId: response.trackingId,
801
- interactionId: this.data.interactionId,
802
- });
803
-
804
- return response;
805
- } catch (error) {
806
- const err = generateTaskErrorObject(error, METHODS.END, TASK_FILE);
807
- const taskErrorProps = {
808
- trackingId: err.data?.trackingId,
809
- errorMessage: err.data?.message,
810
- errorType: err.data?.errorType,
811
- errorData: err.data?.errorData,
812
- reasonCode: err.data?.reasonCode,
813
- };
814
- this.metricsManager.trackEvent(
815
- METRIC_EVENT_NAMES.TASK_END_FAILED,
816
- {
817
- taskId: this.data.interactionId,
818
- ...taskErrorProps,
819
- ...MetricsManager.getCommonTrackingFieldForAQMResponseFailed(error.details || {}),
820
- },
821
- ['operational', 'behavioral', 'business']
822
- );
823
- throw err;
824
- }
825
- }
826
-
827
- /**
828
- * Wraps up the task/interaction with the customer.
829
- * This is called after task:end event if wrapUpRequired is true.
830
- * Emits task:wrappedup event when successful.
831
- *
832
- * @param wrapupPayload - WrapupPayLoad containing:
833
- * - auxCodeId: Required ID for the wrap-up code
834
- * - wrapUpReason: Required description of wrap-up reason
835
- * @returns Promise<TaskResponse>
836
- * @throws Error if task data is unavailable, auxCodeId is missing, or wrapUpReason is missing
837
- * @example
838
- * ```typescript
839
- * // Set up wrap-up events
840
- * task.on(TASK_EVENTS.TASK_WRAPUP, () => {
841
- * console.log('Task ready for wrap-up');
842
- * // Show wrap-up form
843
- * document.getElementById('wrapup-form').style.display = 'block';
844
- * });
845
- *
846
- * task.on(TASK_EVENTS.TASK_WRAPPEDUP, () => {
847
- * console.log('Task wrap-up completed');
848
- * // Clean up UI
849
- * document.getElementById('wrapup-form').style.display = 'none';
850
- * });
851
- *
852
- * // Submit wrap-up
853
- * try {
854
- * const wrapupPayload = {
855
- * auxCodeId: selectedCode, // e.g., 'ISSUE_RESOLVED'
856
- * wrapUpReason: 'Customer issue resolved successfully'
857
- * };
858
- * await task.wrapup(wrapupPayload);
859
- * console.log('Successfully submitted wrap-up');
860
- * } catch (error) {
861
- * console.error('Failed to submit wrap-up:', error);
862
- * // Handle validation errors
863
- * if (error.message.includes('required')) {
864
- * // Show validation error to agent
865
- * }
866
- * }
867
- * ```
868
- */
869
- public async wrapup(wrapupPayload: WrapupPayLoad): Promise<TaskResponse> {
870
- try {
871
- this.cancelAutoWrapupTimer();
872
- LoggerProxy.info(`Wrapping up task`, {
873
- module: TASK_FILE,
874
- method: METHODS.WRAPUP,
875
- interactionId: this.data.interactionId,
876
- });
877
-
878
- this.metricsManager.timeEvent([
879
- METRIC_EVENT_NAMES.TASK_WRAPUP_SUCCESS,
880
- METRIC_EVENT_NAMES.TASK_WRAPUP_FAILED,
881
- ]);
882
-
883
- if (!this.data) {
884
- throw new Error('No task data available');
885
- }
886
- if (!wrapupPayload.auxCodeId || wrapupPayload.auxCodeId.length === 0) {
887
- throw new Error('AuxCodeId is required');
888
- }
889
- if (!wrapupPayload.wrapUpReason || wrapupPayload.wrapUpReason.length === 0) {
890
- throw new Error('WrapUpReason is required');
891
- }
892
-
893
- const response = await this.contact.wrapup({
894
- interactionId: this.data.interactionId,
895
- data: wrapupPayload,
896
- });
897
-
898
- this.metricsManager.trackEvent(
899
- METRIC_EVENT_NAMES.TASK_WRAPUP_SUCCESS,
900
- {
901
- taskId: this.data.interactionId,
902
- wrapUpCode: wrapupPayload.auxCodeId,
903
- wrapUpReason: wrapupPayload.wrapUpReason,
904
- ...MetricsManager.getCommonTrackingFieldForAQMResponse(response),
905
- },
906
- ['operational', 'behavioral', 'business']
907
- );
908
-
909
- LoggerProxy.log(`Task wrapped up successfully`, {
910
- module: TASK_FILE,
911
- method: METHODS.WRAPUP,
912
- trackingId: response.trackingId,
913
- interactionId: this.data.interactionId,
914
- });
915
-
916
- return response;
917
- } catch (error) {
918
- const err = generateTaskErrorObject(error, METHODS.WRAPUP, TASK_FILE);
919
- const taskErrorProps = {
920
- trackingId: err.data?.trackingId,
921
- errorMessage: err.data?.message,
922
- errorType: err.data?.errorType,
923
- errorData: err.data?.errorData,
924
- reasonCode: err.data?.reasonCode,
925
- };
926
- this.metricsManager.trackEvent(
927
- METRIC_EVENT_NAMES.TASK_WRAPUP_FAILED,
928
- {
929
- taskId: this.data.interactionId,
930
- wrapUpCode: wrapupPayload.auxCodeId,
931
- wrapUpReason: wrapupPayload.wrapUpReason,
932
- ...taskErrorProps,
933
- ...MetricsManager.getCommonTrackingFieldForAQMResponseFailed(error.details || {}),
934
- },
935
- ['operational', 'behavioral', 'business']
936
- );
937
- throw err;
938
- }
939
- }
940
-
941
- /**
942
- * Pauses the recording for the current voice task.
943
- * Emits task:recordingPaused event when successful.
944
- *
945
- * @returns Promise<TaskResponse>
946
- * @throws Error if pause recording fails
947
- * @example
948
- * ```typescript
949
- * // Set up recording events
950
- * task.on(TASK_EVENTS.TASK_RECORDING_PAUSED, () => {
951
- * console.log('Recording paused');
952
- * // Update UI to show recording paused state
953
- * document.getElementById('recording-status').textContent = 'Recording Paused';
954
- * document.getElementById('pause-recording-btn').style.display = 'none';
955
- * document.getElementById('resume-recording-btn').style.display = 'block';
956
- * });
957
- *
958
- * task.on(TASK_EVENTS.TASK_RECORDING_PAUSE_FAILED, (error) => {
959
- * console.error('Failed to pause recording:', error);
960
- * // Show error to agent
961
- * });
962
- *
963
- * // Pause recording
964
- * try {
965
- * await task.pauseRecording();
966
- * console.log('Pause recording request sent');
967
- * } catch (error) {
968
- * console.error('Error sending pause recording request:', error);
969
- * // Handle error
970
- * }
971
- * ```
972
- */
973
- public async pauseRecording(): Promise<TaskResponse> {
974
- try {
975
- LoggerProxy.info(`Pausing recording`, {
976
- module: TASK_FILE,
977
- method: METHODS.PAUSE_RECORDING,
978
- interactionId: this.data.interactionId,
979
- });
980
-
981
- this.metricsManager.timeEvent([
982
- METRIC_EVENT_NAMES.TASK_PAUSE_RECORDING_SUCCESS,
983
- METRIC_EVENT_NAMES.TASK_PAUSE_RECORDING_FAILED,
984
- ]);
985
-
986
- const result = await this.contact.pauseRecording({interactionId: this.data.interactionId});
987
-
988
- this.metricsManager.trackEvent(
989
- METRIC_EVENT_NAMES.TASK_PAUSE_RECORDING_SUCCESS,
990
- {
991
- taskId: this.data.interactionId,
992
- ...MetricsManager.getCommonTrackingFieldForAQMResponse(result),
993
- },
994
- ['operational', 'behavioral', 'business']
995
- );
996
-
997
- LoggerProxy.log(`Recording paused successfully`, {
998
- module: TASK_FILE,
999
- method: METHODS.PAUSE_RECORDING,
1000
- trackingId: result.trackingId,
1001
- interactionId: this.data.interactionId,
1002
- });
1003
-
1004
- return result;
1005
- } catch (error) {
1006
- const err = generateTaskErrorObject(error, METHODS.PAUSE_RECORDING, TASK_FILE);
1007
- const taskErrorProps = {
1008
- trackingId: err.data?.trackingId,
1009
- errorMessage: err.data?.message,
1010
- errorType: err.data?.errorType,
1011
- errorData: err.data?.errorData,
1012
- reasonCode: err.data?.reasonCode,
1013
- };
1014
- this.metricsManager.trackEvent(
1015
- METRIC_EVENT_NAMES.TASK_PAUSE_RECORDING_FAILED,
1016
- {
1017
- taskId: this.data.interactionId,
1018
- error: error.toString(),
1019
- ...taskErrorProps,
1020
- ...MetricsManager.getCommonTrackingFieldForAQMResponseFailed(error.details || {}),
1021
- },
1022
- ['operational', 'behavioral', 'business']
1023
- );
1024
- throw err;
1025
- }
1026
- }
1027
-
1028
- /**
1029
- * Resumes the recording for the voice task that was previously paused.
1030
- * Emits task:recordingResumed event when successful.
1031
- *
1032
- * @param resumeRecordingPayload - Configuration for resuming recording:
1033
- * - autoResumed: Indicates if resume was automatic (defaults to false)
1034
- * @returns Promise<TaskResponse>
1035
- * @throws Error if resume recording fails
1036
- * @example
1037
- * ```typescript
1038
- * // Set up recording resume events
1039
- * task.on(TASK_EVENTS.TASK_RECORDING_RESUMED, () => {
1040
- * console.log('Recording resumed');
1041
- * // Update UI to show active recording state
1042
- * document.getElementById('recording-status').textContent = 'Recording Active';
1043
- * document.getElementById('pause-recording-btn').style.display = 'block';
1044
- * document.getElementById('resume-recording-btn').style.display = 'none';
1045
- * });
1046
- *
1047
- * task.on(TASK_EVENTS.TASK_RECORDING_RESUME_FAILED, (error) => {
1048
- * console.error('Failed to resume recording:', error);
1049
- * // Show error to agent
1050
- * });
1051
- *
1052
- * // Resume recording
1053
- * try {
1054
- * const resumePayload = {
1055
- * autoResumed: false // Set to true if triggered by system
1056
- * };
1057
- * await task.resumeRecording(resumePayload);
1058
- * console.log('Resume recording request sent');
1059
- * } catch (error) {
1060
- * console.error('Error sending resume recording request:', error);
1061
- * // Handle error
1062
- * }
1063
- * ```
1064
- */
1065
- public async resumeRecording(
1066
- resumeRecordingPayload: ResumeRecordingPayload
1067
- ): Promise<TaskResponse> {
1068
- try {
1069
- LoggerProxy.info(`Resuming recording`, {
1070
- module: TASK_FILE,
1071
- method: METHODS.RESUME_RECORDING,
1072
- interactionId: this.data.interactionId,
1073
- });
1074
-
1075
- this.metricsManager.timeEvent([
1076
- METRIC_EVENT_NAMES.TASK_RESUME_RECORDING_SUCCESS,
1077
- METRIC_EVENT_NAMES.TASK_RESUME_RECORDING_FAILED,
1078
- ]);
1079
-
1080
- resumeRecordingPayload ??= {autoResumed: false};
1081
-
1082
- const result = await this.contact.resumeRecording({
1083
- interactionId: this.data.interactionId,
1084
- data: resumeRecordingPayload,
1085
- });
1086
-
1087
- this.metricsManager.trackEvent(
1088
- METRIC_EVENT_NAMES.TASK_RESUME_RECORDING_SUCCESS,
1089
- {
1090
- taskId: this.data.interactionId,
1091
- ...MetricsManager.getCommonTrackingFieldForAQMResponse(result),
1092
- },
1093
- ['operational', 'behavioral', 'business']
1094
- );
1095
-
1096
- LoggerProxy.log(`Recording resumed successfully`, {
1097
- module: TASK_FILE,
1098
- method: METHODS.RESUME_RECORDING,
1099
- trackingId: result.trackingId,
1100
- interactionId: this.data.interactionId,
1101
- });
1102
-
1103
- return result;
1104
- } catch (error) {
1105
- const err = generateTaskErrorObject(error, METHODS.RESUME_RECORDING, TASK_FILE);
1106
- const taskErrorProps = {
1107
- trackingId: err.data?.trackingId,
1108
- errorMessage: err.data?.message,
1109
- errorType: err.data?.errorType,
1110
- errorData: err.data?.errorData,
1111
- reasonCode: err.data?.reasonCode,
1112
- };
1113
- this.metricsManager.trackEvent(
1114
- METRIC_EVENT_NAMES.TASK_RESUME_RECORDING_FAILED,
1115
- {
1116
- taskId: this.data.interactionId,
1117
- error: error.toString(),
1118
- ...taskErrorProps,
1119
- ...MetricsManager.getCommonTrackingFieldForAQMResponseFailed(error.details || {}),
1120
- },
1121
- ['operational', 'behavioral', 'business']
1122
- );
1123
- throw err;
1124
- }
1125
- }
1126
-
1127
- /**
1128
- * Consults another agent or queue on an ongoing task for further assistance.
1129
- * During consultation, the original customer is typically placed on hold while
1130
- * the agent seeks guidance from another agent or queue.
1131
- *
1132
- * @param consultPayload - Configuration for the consultation containing:
1133
- * - to: ID of the agent or queue to consult with
1134
- * - destinationType: Type of destination (AGENT, QUEUE, etc.)
1135
- * - holdParticipants: Whether to hold other participants (defaults to true)
1136
- * @returns Promise<TaskResponse> - Resolves with consultation result
1137
- * @throws Error if consultation fails or invalid parameters provided
1138
- * @example
1139
- * ```typescript
1140
- * // Consult with another agent
1141
- * const consultPayload = {
1142
- * to: 'agentId123',
1143
- * destinationType: DESTINATION_TYPE.AGENT,
1144
- * holdParticipants: true
1145
- * };
1146
- * task.consult(consultPayload)
1147
- * .then(response => console.log('Consultation started successfully'))
1148
- * .catch(error => console.error('Failed to start consultation:', error));
1149
- *
1150
- * // Consult with a queue
1151
- * const queueConsultPayload = {
1152
- * to: 'salesQueue123',
1153
- * destinationType: DESTINATION_TYPE.QUEUE
1154
- * };
1155
- * task.consult(queueConsultPayload)
1156
- * .then(response => console.log('Queue consultation started'))
1157
- * .catch(error => console.error('Failed to start queue consultation:', error));
1158
- * ```
1159
- */
1160
- public async consult(consultPayload: ConsultPayload): Promise<TaskResponse> {
1161
- try {
1162
- LoggerProxy.info(`Starting consult`, {
1163
- module: TASK_FILE,
1164
- method: METHODS.CONSULT,
1165
- interactionId: this.data.interactionId,
1166
- });
1167
-
1168
- this.metricsManager.timeEvent([
1169
- METRIC_EVENT_NAMES.TASK_CONSULT_START_SUCCESS,
1170
- METRIC_EVENT_NAMES.TASK_CONSULT_START_FAILED,
1171
- ]);
1172
-
1173
- const result = await this.contact.consult({
1174
- interactionId: this.data.interactionId,
1175
- data: consultPayload,
1176
- });
1177
-
1178
- this.metricsManager.trackEvent(
1179
- METRIC_EVENT_NAMES.TASK_CONSULT_START_SUCCESS,
1180
- {
1181
- taskId: this.data.interactionId,
1182
- destination: consultPayload.to,
1183
- destinationType: consultPayload.destinationType,
1184
- ...MetricsManager.getCommonTrackingFieldForAQMResponse(result),
1185
- },
1186
- ['operational', 'behavioral', 'business']
1187
- );
1188
-
1189
- LoggerProxy.log(`Consult started successfully to ${consultPayload.to}`, {
1190
- module: TASK_FILE,
1191
- method: METHODS.CONSULT,
1192
- trackingId: result.trackingId,
1193
- interactionId: this.data.interactionId,
1194
- });
1195
-
1196
- return result;
1197
- } catch (error) {
1198
- const err = generateTaskErrorObject(error, METHODS.CONSULT, TASK_FILE);
1199
- const taskErrorProps = {
1200
- trackingId: err.data?.trackingId,
1201
- errorMessage: err.data?.message,
1202
- errorType: err.data?.errorType,
1203
- errorData: err.data?.errorData,
1204
- reasonCode: err.data?.reasonCode,
1205
- };
1206
- this.metricsManager.trackEvent(
1207
- METRIC_EVENT_NAMES.TASK_CONSULT_START_FAILED,
1208
- {
1209
- taskId: this.data.interactionId,
1210
- destination: consultPayload.to,
1211
- destinationType: consultPayload.destinationType,
1212
- error: error.toString(),
1213
- ...taskErrorProps,
1214
- ...MetricsManager.getCommonTrackingFieldForAQMResponseFailed(error.details || {}),
1215
- },
1216
- ['operational', 'behavioral', 'business']
1217
- );
1218
- throw err;
1219
- }
1220
- }
1221
-
1222
- /**
1223
- * Ends an ongoing consultation session for the task.
1224
- * This terminates the consultation while maintaining the original customer connection.
1225
- *
1226
- * @param consultEndPayload - Configuration for ending the consultation containing:
1227
- * - isConsult: Must be true to indicate this is a consultation end
1228
- * - taskId: ID of the task being consulted on
1229
- * - queueId: (Optional) Queue ID if this was a queue consultation
1230
- * - isSecondaryEpDnAgent: (Optional) Indicates if this involves a secondary entry point
1231
- * @returns Promise<TaskResponse> - Resolves when consultation is ended
1232
- * @throws Error if ending consultation fails or invalid parameters provided
1233
- * @example
1234
- * ```typescript
1235
- * // End a direct agent consultation
1236
- * const consultEndPayload = {
1237
- * isConsult: true,
1238
- * taskId: 'task123'
1239
- * };
1240
- * task.endConsult(consultEndPayload)
1241
- * .then(response => console.log('Consultation ended successfully'))
1242
- * .catch(error => console.error('Failed to end consultation:', error));
1243
- *
1244
- * // End a queue consultation
1245
- * const queueConsultEndPayload = {
1246
- * isConsult: true,
1247
- * taskId: 'task123',
1248
- * queueId: 'queue123'
1249
- * };
1250
- * task.endConsult(queueConsultEndPayload)
1251
- * .then(response => console.log('Queue consultation ended'))
1252
- * .catch(error => console.error('Failed to end queue consultation:', error));
1253
- * ```
1254
- */
1255
- public async endConsult(consultEndPayload: ConsultEndPayload): Promise<TaskResponse> {
1256
- try {
1257
- LoggerProxy.info(`Ending consult`, {
1258
- module: TASK_FILE,
1259
- method: METHODS.END_CONSULT,
1260
- interactionId: this.data.interactionId,
1261
- });
1262
-
1263
- this.metricsManager.timeEvent([
1264
- METRIC_EVENT_NAMES.TASK_CONSULT_END_SUCCESS,
1265
- METRIC_EVENT_NAMES.TASK_CONSULT_END_FAILED,
1266
- ]);
1267
-
1268
- const result = await this.contact.consultEnd({
1269
- interactionId: this.data.interactionId,
1270
- data: consultEndPayload,
1271
- });
1272
-
1273
- this.metricsManager.trackEvent(
1274
- METRIC_EVENT_NAMES.TASK_CONSULT_END_SUCCESS,
1275
- {
1276
- taskId: this.data.interactionId,
1277
- ...MetricsManager.getCommonTrackingFieldForAQMResponse(result),
1278
- },
1279
- ['operational', 'behavioral', 'business']
1280
- );
1281
-
1282
- LoggerProxy.log(`Consult ended successfully`, {
1283
- module: TASK_FILE,
1284
- method: METHODS.END_CONSULT,
1285
- trackingId: result.trackingId,
1286
- interactionId: this.data.interactionId,
1287
- });
1288
-
1289
- return result;
1290
- } catch (error) {
1291
- const err = generateTaskErrorObject(error, METHODS.END_CONSULT, TASK_FILE);
1292
- const taskErrorProps = {
1293
- trackingId: err.data?.trackingId,
1294
- errorMessage: err.data?.message,
1295
- errorType: err.data?.errorType,
1296
- errorData: err.data?.errorData,
1297
- reasonCode: err.data?.reasonCode,
1298
- };
1299
- this.metricsManager.trackEvent(
1300
- METRIC_EVENT_NAMES.TASK_CONSULT_END_FAILED,
1301
- {
1302
- taskId: this.data.interactionId,
1303
- error: error.toString(),
1304
- ...taskErrorProps,
1305
- ...MetricsManager.getCommonTrackingFieldForAQMResponseFailed(error.details || {}),
1306
- },
1307
- ['operational', 'behavioral', 'business']
1308
- );
1309
- throw err;
1310
- }
1311
- }
1312
-
1313
- /**
1314
- * Transfer the task to an agent directly or to a queue.
1315
- * This is a blind transfer that immediately redirects the task to the specified destination.
1316
- *
1317
- * @param transferPayload - Transfer configuration containing:
1318
- * - to: ID of the agent or queue to transfer to
1319
- * - destinationType: Type of destination (AGENT, QUEUE, etc.)
1320
- * @returns Promise<TaskResponse> - Resolves when transfer is completed
1321
- * @throws Error if transfer fails or invalid parameters provided
1322
- * @example
1323
- * ```typescript
1324
- * // Transfer to a queue
1325
- * const queueTransferPayload = {
1326
- * to: 'salesQueue123',
1327
- * destinationType: DESTINATION_TYPE.QUEUE
1328
- * };
1329
- * task.transfer(queueTransferPayload)
1330
- * .then(response => console.log('Task transferred to queue successfully'))
1331
- * .catch(error => console.error('Failed to transfer to queue:', error));
1332
- *
1333
- * // Transfer to an agent
1334
- * const agentTransferPayload = {
1335
- * to: 'agentId123',
1336
- * destinationType: DESTINATION_TYPE.AGENT
1337
- * };
1338
- * task.transfer(agentTransferPayload)
1339
- * .then(response => console.log('Task transferred to agent successfully'))
1340
- * .catch(error => console.error('Failed to transfer to agent:', error));
1341
- * ```
1342
- */
1343
- public async transfer(transferPayload: TransferPayLoad): Promise<TaskResponse> {
1344
- try {
1345
- LoggerProxy.info(`Transferring task to ${transferPayload.to}`, {
1346
- module: TASK_FILE,
1347
- method: METHODS.TRANSFER,
1348
- interactionId: this.data.interactionId,
1349
- });
1350
-
1351
- this.metricsManager.timeEvent([
1352
- METRIC_EVENT_NAMES.TASK_TRANSFER_SUCCESS,
1353
- METRIC_EVENT_NAMES.TASK_TRANSFER_FAILED,
1354
- ]);
1355
-
1356
- let result: TaskResponse;
1357
- if (transferPayload.destinationType === DESTINATION_TYPE.QUEUE) {
1358
- result = await this.contact.vteamTransfer({
1359
- interactionId: this.data.interactionId,
1360
- data: transferPayload,
1361
- });
1362
- } else {
1363
- result = await this.contact.blindTransfer({
1364
- interactionId: this.data.interactionId,
1365
- data: transferPayload,
1366
- });
1367
- }
1368
-
1369
- this.metricsManager.trackEvent(
1370
- METRIC_EVENT_NAMES.TASK_TRANSFER_SUCCESS,
1371
- {
1372
- taskId: this.data.interactionId,
1373
- destination: transferPayload.to,
1374
- destinationType: transferPayload.destinationType,
1375
- isConsultTransfer: false,
1376
- ...MetricsManager.getCommonTrackingFieldForAQMResponse(result),
1377
- },
1378
- ['operational', 'behavioral', 'business']
1379
- );
1380
-
1381
- LoggerProxy.log(`Task transferred successfully to ${transferPayload.to}`, {
1382
- module: TASK_FILE,
1383
- method: METHODS.TRANSFER,
1384
- trackingId: result.trackingId,
1385
- interactionId: this.data.interactionId,
1386
- });
1387
-
1388
- return result;
1389
- } catch (error) {
1390
- const err = generateTaskErrorObject(error, METHODS.TRANSFER, TASK_FILE);
1391
- const taskErrorProps = {
1392
- trackingId: err.data?.trackingId,
1393
- errorMessage: err.data?.message,
1394
- errorType: err.data?.errorType,
1395
- errorData: err.data?.errorData,
1396
- reasonCode: err.data?.reasonCode,
1397
- };
1398
- this.metricsManager.trackEvent(
1399
- METRIC_EVENT_NAMES.TASK_TRANSFER_FAILED,
1400
- {
1401
- taskId: this.data.interactionId,
1402
- destination: transferPayload.to,
1403
- destinationType: transferPayload.destinationType,
1404
- isConsultTransfer: false,
1405
- error: error.toString(),
1406
- ...taskErrorProps,
1407
- ...MetricsManager.getCommonTrackingFieldForAQMResponseFailed(error.details || {}),
1408
- },
1409
- ['operational', 'behavioral', 'business']
1410
- );
1411
- throw err;
1412
- }
1413
- }
1414
-
1415
- /**
1416
- * Transfer the task to the party that was consulted.
1417
- * This completes a consultative transfer where the agent first consulted with the target
1418
- * before transferring the task. For queue consultations, the transfer is automatically
1419
- * directed to the agent who accepted the consultation.
1420
- *
1421
- * @param consultTransferPayload - Configuration for the consultation transfer containing:
1422
- * - to: ID of the agent or queue to transfer to
1423
- * - destinationType: Type of destination (AGENT, QUEUE, etc. from CONSULT_TRANSFER_DESTINATION_TYPE)
1424
- * @returns Promise<TaskResponse> - Resolves when consultation transfer is completed
1425
- * @throws Error if transfer fails, no agent has accepted a queue consultation, or other validation errors
1426
- * @example
1427
- * ```typescript
1428
- * // Complete consultation transfer to an agent
1429
- * const agentConsultTransfer = {
1430
- * to: 'agentId123',
1431
- * destinationType: CONSULT_TRANSFER_DESTINATION_TYPE.AGENT
1432
- * };
1433
- * task.consultTransfer(agentConsultTransfer)
1434
- * .then(response => console.log('Consultation transfer to agent completed'))
1435
- * .catch(error => console.error('Failed to complete agent consultation transfer:', error));
1436
- *
1437
- * // Complete consultation transfer to a queue agent
1438
- * const queueConsultTransfer = {
1439
- * to: 'queue123',
1440
- * destinationType: CONSULT_TRANSFER_DESTINATION_TYPE.QUEUE
1441
- * };
1442
- * task.consultTransfer(queueConsultTransfer)
1443
- * .then(response => console.log('Consultation transfer to queue agent completed'))
1444
- * .catch(error => console.error('Failed to complete queue consultation transfer:', error));
1445
- * ```
1446
- */
1447
- public async consultTransfer(
1448
- consultTransferPayload?: ConsultTransferPayLoad
1449
- ): Promise<TaskResponse> {
1450
- // Get the destination agent ID using custom logic from participants data
1451
- const destAgentId = calculateDestAgentId(this.data.interaction, this.agentId);
1452
-
1453
- // Resolve the target id (queue consult transfers go to the accepted agent)
1454
- if (!destAgentId) {
1455
- throw new Error('No agent has accepted this queue consult yet');
1456
- }
1457
-
1458
- LoggerProxy.info(
1459
- `Initiating consult transfer to ${consultTransferPayload?.to || destAgentId}`,
1460
- {
1461
- module: TASK_FILE,
1462
- method: METHODS.CONSULT_TRANSFER,
1463
- interactionId: this.data.interactionId,
1464
- }
1465
- );
1466
-
1467
- // Derive destination type from the participant's type property
1468
- const destType = calculateDestType(this.data.interaction, this.agentId);
1469
- // By default we always use the computed destAgentId as the target id
1470
- const consultTransferRequest: ConsultTransferPayLoad = {
1471
- to: destAgentId,
1472
- destinationType: destType,
1473
- };
1474
- try {
1475
- const result = await this.contact.consultTransfer({
1476
- interactionId: this.data.interactionId,
1477
- data: consultTransferRequest,
1478
- });
1479
-
1480
- this.metricsManager.trackEvent(
1481
- METRIC_EVENT_NAMES.TASK_TRANSFER_SUCCESS,
1482
- {
1483
- taskId: this.data.interactionId,
1484
- destination: consultTransferRequest.to,
1485
- destinationType: consultTransferRequest.destinationType,
1486
- isConsultTransfer: true,
1487
- ...MetricsManager.getCommonTrackingFieldForAQMResponse(result),
1488
- },
1489
- ['operational', 'behavioral', 'business']
1490
- );
1491
-
1492
- LoggerProxy.log(
1493
- `Consult transfer completed successfully to ${consultTransferPayload?.to || destAgentId}`,
1494
- {
1495
- module: TASK_FILE,
1496
- method: METHODS.CONSULT_TRANSFER,
1497
- trackingId: result.trackingId,
1498
- interactionId: this.data.interactionId,
1499
- }
1500
- );
1501
-
1502
- return result;
1503
- } catch (error) {
1504
- const err = generateTaskErrorObject(error, METHODS.CONSULT_TRANSFER, TASK_FILE);
1505
- const taskErrorProps = {
1506
- trackingId: err.data?.trackingId,
1507
- errorMessage: err.data?.message,
1508
- errorType: err.data?.errorType,
1509
- errorData: err.data?.errorData,
1510
- reasonCode: err.data?.reasonCode,
1511
- };
1512
- this.metricsManager.trackEvent(
1513
- METRIC_EVENT_NAMES.TASK_TRANSFER_FAILED,
1514
- {
1515
- taskId: this.data.interactionId,
1516
- destination: destAgentId || '',
1517
- destinationType: destType,
1518
- isConsultTransfer: true,
1519
- error: error.toString(),
1520
- ...taskErrorProps,
1521
- ...MetricsManager.getCommonTrackingFieldForAQMResponseFailed(error.details || {}),
1522
- },
1523
- ['operational', 'behavioral', 'business']
1524
- );
1525
- throw err;
1526
- }
1527
- }
1528
-
1529
- /**
1530
- * Starts a consultation conference by merging the consultation call with the main call
1531
- *
1532
- * Creates a three-way conference between the agent, customer, and consulted party
1533
- * Extracts required consultation data from the current task data
1534
- * On success, emits a `task:conferenceStarted` event
1535
- *
1536
- * @returns Promise<TaskResponse> - Response from the consultation conference API
1537
- * @throws Error if the operation fails or if consultation data is invalid
1538
- *
1539
- * @example
1540
- * ```typescript
1541
- * try {
1542
- * await task.consultConference();
1543
- * console.log('Conference started successfully');
1544
- * } catch (error) {
1545
- * console.error('Failed to start conference:', error);
1546
- * }
1547
- * ```
1548
- */
1549
- public async consultConference(): Promise<TaskResponse> {
1550
- // Get the destination agent ID dynamically from participants
1551
- // This handles multi-party conference scenarios, CBT (Capacity Based Team), and EP-DN cases
1552
- const destAgentId = calculateDestAgentId(this.data.interaction, this.agentId);
1553
-
1554
- // Validate that we have a destination agent (for queue consult scenarios)
1555
- if (!destAgentId) {
1556
- throw new Error('No agent has accepted this queue consult yet');
1557
- }
1558
-
1559
- // Get the destination agent ID for fetching destination type
1560
- // This helps determine the correct participant type for CBT (Capacity Based Team) and EP-DN scenarios
1561
- const destAgentType = calculateDestType(this.data.interaction, this.agentId);
1562
-
1563
- // Extract consultation conference data from task data (used in both try and catch)
1564
- const consultationData = {
1565
- agentId: this.agentId,
1566
- to: destAgentId,
1567
- destinationType: destAgentType || this.data.destinationType || 'agent',
1568
- };
1569
-
1570
- try {
1571
- LoggerProxy.info(`Initiating consult conference to ${destAgentId}`, {
1572
- module: TASK_FILE,
1573
- method: METHODS.CONSULT_CONFERENCE,
1574
- interactionId: this.data.interactionId,
1575
- });
1576
-
1577
- const response = await this.contact.consultConference({
1578
- interactionId: this.data.interactionId,
1579
- data: consultationData,
1580
- });
1581
-
1582
- // Track success metrics (following consultTransfer pattern)
1583
- this.metricsManager.trackEvent(
1584
- METRIC_EVENT_NAMES.TASK_CONFERENCE_START_SUCCESS,
1585
- {
1586
- taskId: this.data.interactionId,
1587
- destination: consultationData.to,
1588
- destinationType: consultationData.destinationType,
1589
- agentId: consultationData.agentId,
1590
- ...MetricsManager.getCommonTrackingFieldForAQMResponse(response),
1591
- },
1592
- ['operational', 'behavioral', 'business']
1593
- );
1594
-
1595
- LoggerProxy.log(`Consult conference started successfully`, {
1596
- module: TASK_FILE,
1597
- method: METHODS.CONSULT_CONFERENCE,
1598
- interactionId: this.data.interactionId,
1599
- });
1600
-
1601
- return response;
1602
- } catch (error) {
1603
- const err = generateTaskErrorObject(error, METHODS.CONSULT_CONFERENCE, TASK_FILE);
1604
- const taskErrorProps = {
1605
- trackingId: err.data?.trackingId,
1606
- errorMessage: err.data?.message,
1607
- errorType: err.data?.errorType,
1608
- errorData: err.data?.errorData,
1609
- reasonCode: err.data?.reasonCode,
1610
- };
1611
-
1612
- this.metricsManager.trackEvent(
1613
- METRIC_EVENT_NAMES.TASK_CONFERENCE_START_FAILED,
1614
- {
1615
- taskId: this.data.interactionId,
1616
- destination: consultationData.to,
1617
- destinationType: consultationData.destinationType,
1618
- agentId: consultationData.agentId,
1619
- error: error.toString(),
1620
- ...taskErrorProps,
1621
- ...MetricsManager.getCommonTrackingFieldForAQMResponseFailed(error.details || {}),
1622
- },
1623
- ['operational', 'behavioral', 'business']
1624
- );
1625
-
1626
- LoggerProxy.error(`Failed to start consult conference`, {
1627
- module: TASK_FILE,
1628
- method: METHODS.CONSULT_CONFERENCE,
1629
- interactionId: this.data.interactionId,
1630
- });
1631
-
1632
- throw err;
1633
- }
1634
- }
1635
-
1636
- /**
1637
- * Exits the current conference by removing the agent from the conference call
1638
- *
1639
- * Exits the agent from the conference, leaving the customer and consulted party connected
1640
- * On success, emits a `task:conferenceEnded` event
1641
- *
1642
- * @returns Promise<TaskResponse> - Response from the conference exit API
1643
- * @throws Error if the operation fails or if no active conference exists
1644
- *
1645
- * @example
1646
- * ```typescript
1647
- * try {
1648
- * await task.exitConference();
1649
- * console.log('Successfully exited conference');
1650
- * } catch (error) {
1651
- * console.error('Failed to exit conference:', error);
1652
- * }
1653
- * ```
1654
- */
1655
- public async exitConference(): Promise<TaskResponse> {
1656
- try {
1657
- LoggerProxy.info(`Exiting consult conference`, {
1658
- module: TASK_FILE,
1659
- method: METHODS.EXIT_CONFERENCE,
1660
- interactionId: this.data.interactionId,
1661
- });
1662
-
1663
- // Validate that interaction ID exists
1664
- if (!this.data.interactionId) {
1665
- throw new Error('Invalid interaction ID');
1666
- }
1667
-
1668
- const response = await this.contact.exitConference({
1669
- interactionId: this.data.interactionId,
1670
- });
1671
-
1672
- // Track success metrics (following consultTransfer pattern)
1673
- this.metricsManager.trackEvent(
1674
- METRIC_EVENT_NAMES.TASK_CONFERENCE_END_SUCCESS,
1675
- {
1676
- taskId: this.data.interactionId,
1677
- ...MetricsManager.getCommonTrackingFieldForAQMResponse(response),
1678
- },
1679
- ['operational', 'behavioral', 'business']
1680
- );
1681
-
1682
- LoggerProxy.log(`Consult conference exited successfully`, {
1683
- module: TASK_FILE,
1684
- method: METHODS.EXIT_CONFERENCE,
1685
- interactionId: this.data.interactionId,
1686
- });
1687
-
1688
- return response;
1689
- } catch (error) {
1690
- const err = generateTaskErrorObject(error, METHODS.EXIT_CONFERENCE, TASK_FILE);
1691
- const taskErrorProps = {
1692
- trackingId: err.data?.trackingId,
1693
- errorMessage: err.data?.message,
1694
- errorType: err.data?.errorType,
1695
- errorData: err.data?.errorData,
1696
- reasonCode: err.data?.reasonCode,
1697
- };
1698
-
1699
- // Track failure metrics (following consultTransfer pattern)
1700
- this.metricsManager.trackEvent(
1701
- METRIC_EVENT_NAMES.TASK_CONFERENCE_END_FAILED,
1702
- {
1703
- taskId: this.data.interactionId,
1704
- error: error.toString(),
1705
- ...taskErrorProps,
1706
- ...MetricsManager.getCommonTrackingFieldForAQMResponseFailed(error.details || {}),
1707
- },
1708
- ['operational', 'behavioral', 'business']
1709
- );
1710
-
1711
- LoggerProxy.error(`Failed to exit consult conference`, {
1712
- module: TASK_FILE,
1713
- method: METHODS.EXIT_CONFERENCE,
1714
- interactionId: this.data.interactionId,
1715
- });
1716
-
1717
- throw err;
1718
- }
1719
- }
1720
-
1721
- /**
1722
- * Transfers the current conference to another agent
1723
- *
1724
- * Moves the entire conference (including all participants) to a new agent,
1725
- * while the current agent exits and goes to wrapup
1726
- * On success, the current agent receives `task:conferenceEnded` event
1727
- *
1728
- * @returns Promise<TaskResponse> - Response from the conference transfer API
1729
- * @throws Error if the operation fails or if no active conference exists
1730
- *
1731
- * @example
1732
- * ```typescript
1733
- * try {
1734
- * await task.transferConference();
1735
- * console.log('Conference transferred successfully');
1736
- * } catch (error) {
1737
- * console.error('Failed to transfer conference:', error);
1738
- * }
1739
- * ```
1740
- */
1741
- public async transferConference(): Promise<TaskResponse> {
1742
- try {
1743
- LoggerProxy.info(`Transferring conference`, {
1744
- module: TASK_FILE,
1745
- method: METHODS.TRANSFER_CONFERENCE,
1746
- interactionId: this.data.interactionId,
1747
- });
1748
-
1749
- // Validate that interaction ID exists
1750
- if (!this.data.interactionId) {
1751
- throw new Error('Invalid interaction ID');
1752
- }
1753
-
1754
- const response = await this.contact.conferenceTransfer({
1755
- interactionId: this.data.interactionId,
1756
- });
1757
-
1758
- // Track success metrics (following consultTransfer pattern)
1759
- this.metricsManager.trackEvent(
1760
- METRIC_EVENT_NAMES.TASK_CONFERENCE_TRANSFER_SUCCESS,
1761
- {
1762
- taskId: this.data.interactionId,
1763
- ...MetricsManager.getCommonTrackingFieldForAQMResponse(response),
1764
- },
1765
- ['operational', 'behavioral', 'business']
1766
- );
1767
-
1768
- LoggerProxy.log(`Conference transferred successfully`, {
1769
- module: TASK_FILE,
1770
- method: METHODS.TRANSFER_CONFERENCE,
1771
- interactionId: this.data.interactionId,
1772
- });
1773
-
1774
- return response;
1775
- } catch (error) {
1776
- const err = generateTaskErrorObject(error, METHODS.TRANSFER_CONFERENCE, TASK_FILE);
1777
- const taskErrorProps = {
1778
- trackingId: err.data?.trackingId,
1779
- errorMessage: err.data?.message,
1780
- errorType: err.data?.errorType,
1781
- errorData: err.data?.errorData,
1782
- reasonCode: err.data?.reasonCode,
1783
- };
1784
-
1785
- // Track failure metrics (following consultTransfer pattern)
1786
- this.metricsManager.trackEvent(
1787
- METRIC_EVENT_NAMES.TASK_CONFERENCE_TRANSFER_FAILED,
1788
- {
1789
- taskId: this.data.interactionId,
1790
- error: error.toString(),
1791
- ...taskErrorProps,
1792
- ...MetricsManager.getCommonTrackingFieldForAQMResponseFailed(error.details || {}),
1793
- },
1794
- ['operational', 'behavioral', 'business']
1795
- );
1796
-
1797
- LoggerProxy.error(`Failed to transfer conference`, {
1798
- module: TASK_FILE,
1799
- method: METHODS.TRANSFER_CONFERENCE,
1800
- interactionId: this.data.interactionId,
1801
- });
1802
-
1803
- throw err;
1804
- }
1805
- }
1806
- }