-
Notifications
You must be signed in to change notification settings - Fork 70
Expand file tree
/
Copy pathcampaign-task.tsx
More file actions
364 lines (320 loc) · 13.6 KB
/
Copy pathcampaign-task.tsx
File metadata and controls
364 lines (320 loc) · 13.6 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
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
import React, {useState, useCallback, useRef, useEffect} from 'react';
import {Button} from '@momentum-design/components/dist/react';
import {withMetrics} from '@webex/cc-ui-logging';
import CampaignErrorDialog from '../CampaignErrorDialog/campaign-error-dialog';
import GlobalVariablesPanel from '../GlobalVariablesPanel/global-variables-panel';
import CampaignTaskPopover from './CampaignTaskPopover/campaign-task-popover';
import CampaignTaskListItem from './CampaignTaskListItem/campaign-task-list-item';
import {CampaignErrorType} from '../CampaignErrorDialog/campaign-error-dialog.types';
import {
CampaignTaskProps,
CampaignAutoAction,
CAMPAIGN_ACTION_ERROR_MAP,
CampaignErrorActionType,
CallAssociatedDataMap,
getCallerIdentifier,
} from '../task.types';
import {getAgentViewableGlobalVariables} from '../Task/task.utils';
import {CANCEL, CAMPAIGN_TASK_REGION_LABEL} from '../constants';
import {getAgentJoinTimestamp, getCampaignCpd} from '../TaskList/task-list.utils';
import './campaign-task.style.scss';
const LOG_MODULE = 'cc-components#campaign-task';
const CampaignTask: React.FC<CampaignTaskProps> = ({
task,
acceptPreviewContact,
skipPreviewContact,
removePreviewContact,
cancelPreviewContact,
isBrowser = false,
logger,
isAccepted = false,
agentId,
}) => {
const cpd = task.data.interaction.callProcessingDetails;
const campaignCpd = getCampaignCpd(cpd as unknown as Record<string, unknown>);
const interactionId = task.data.interactionId;
const timeoutTimestamp = campaignCpd.campaignPreviewOfferTimeout;
const autoAction = (campaignCpd.campaignPreviewAutoAction ?? '') as CampaignAutoAction | '';
const callAssociatedDetails = task.data.interaction.callAssociatedDetails;
const ani = callAssociatedDetails?.ani ?? '';
const dn = callAssociatedDetails?.dn ?? '';
const customerName = callAssociatedDetails?.customerName;
const outboundType = task.data.interaction.outboundType;
const title = customerName || getCallerIdentifier(ani, dn, outboundType);
const phoneNumber = getCallerIdentifier(ani, dn, outboundType);
const callAssociatedData = (task.data.interaction as unknown as {callAssociatedData?: CallAssociatedDataMap})
.callAssociatedData;
const latestGlobalVariables = getAgentViewableGlobalVariables(callAssociatedData);
// Persist and accumulate global variables across task updates.
// Each websocket event may only carry a subset of the full
// callAssociatedData, so we merge new variables into the ref by name
// instead of replacing the whole array. This ensures all global
// variables seen during the interaction are displayed — matching the
// regular desktop behaviour.
// When length === 0 we keep previous values (missing data, not a
// legitimate clearing — variables are never cleared mid-call).
// Reset when the interaction changes so stale CAD from a previous
// task is never shown on a new call.
const globalVariablesRef = useRef(latestGlobalVariables);
const prevInteractionIdRef = useRef(interactionId);
if (prevInteractionIdRef.current !== interactionId) {
prevInteractionIdRef.current = interactionId;
globalVariablesRef.current = latestGlobalVariables;
} else if (latestGlobalVariables.length > 0) {
const existingMap = new Map(globalVariablesRef.current.map((v) => [v.name, v]));
latestGlobalVariables.forEach((v) => existingMap.set(v.name, v));
globalVariablesRef.current = Array.from(existingMap.values());
}
const globalVariables = globalVariablesRef.current;
const [isAcceptClicked, setIsAcceptClicked] = useState<boolean>(isAccepted);
const [handleTimestamp, setHandleTimestamp] = useState<number | undefined>(
isAccepted ? (getAgentJoinTimestamp(task, agentId) ?? Date.now()) : undefined
);
const [isAcceptDisabled, setIsAcceptDisabled] = useState<boolean>(isAccepted);
const [isSkipButtonDisabled, setIsSkipButtonDisabled] = useState<boolean>(
isAccepted || campaignCpd.campaignPreviewSkipDisabled === 'true'
);
const [isRemoveButtonDisabled, setIsRemoveButtonDisabled] = useState<boolean>(
isAccepted || campaignCpd.campaignPreviewRemoveDisabled === 'true'
);
const [errorType, setErrorType] = useState<CampaignErrorType | null>(null);
const unmountedRef = useRef<boolean>(false);
useEffect(() => {
return () => {
unmountedRef.current = true;
};
}, []);
// Sync local state when the store-driven isAccepted prop changes.
// This handles the case where the store marks the campaign as accepted
// (e.g. via handleCampaignPreviewReservation) and the component was
// already mounted.
useEffect(() => {
if (isAccepted && !isAcceptClicked) {
setIsAcceptClicked(true);
setHandleTimestamp(getAgentJoinTimestamp(task, agentId) ?? Date.now());
setIsAcceptDisabled(true);
setIsSkipButtonDisabled(true);
setIsRemoveButtonDisabled(true);
}
}, [isAccepted]);
// Once the server-side joinTimestamp arrives, align handleTimestamp
// so the timer matches CallControlCAD exactly.
useEffect(() => {
if (!isAcceptClicked) return;
const joinTs = getAgentJoinTimestamp(task, agentId);
if (joinTs && joinTs !== handleTimestamp) {
setHandleTimestamp(joinTs);
}
}, [task, isAcceptClicked]);
// Reset local state when a new contact is offered on the same task (after skip/remove).
// The SDK emits TASK_CAMPAIGN_CONTACT_UPDATED with updated callProcessingDetails;
// we detect this by tracking the offerTimeout value which changes per contact.
const prevTimeoutRef = useRef<string | undefined>(timeoutTimestamp);
useEffect(() => {
// Only reset when a new contact is offered after skip/remove (not after accept).
// After accept the task data updates but should keep the accepted state.
if (!isAccepted && prevTimeoutRef.current !== undefined && timeoutTimestamp !== prevTimeoutRef.current) {
logger?.info('CC-Widgets: CampaignTask: New contact offered, resetting state', {
module: LOG_MODULE,
method: 'useEffect[timeoutTimestamp]',
});
setIsAcceptClicked(false);
setHandleTimestamp(undefined);
setIsAcceptDisabled(false);
setIsSkipButtonDisabled(campaignCpd.campaignPreviewSkipDisabled === 'true');
setIsRemoveButtonDisabled(campaignCpd.campaignPreviewRemoveDisabled === 'true');
setIsCancelDisabled(false);
setErrorType(null);
}
prevTimeoutRef.current = timeoutTimestamp;
}, [
timeoutTimestamp,
isAccepted,
campaignCpd.campaignPreviewSkipDisabled,
campaignCpd.campaignPreviewRemoveDisabled,
logger,
]);
const disableAllButtons = useCallback((): void => {
setIsAcceptDisabled(true);
setIsSkipButtonDisabled(true);
setIsRemoveButtonDisabled(true);
}, []);
const resetButtons = useCallback((): void => {
setIsAcceptClicked(false);
setIsAcceptDisabled(false);
setIsSkipButtonDisabled(campaignCpd.campaignPreviewSkipDisabled === 'true');
setIsRemoveButtonDisabled(campaignCpd.campaignPreviewRemoveDisabled === 'true');
}, [campaignCpd.campaignPreviewSkipDisabled, campaignCpd.campaignPreviewRemoveDisabled]);
const handleActionError = useCallback(
(action: CampaignErrorActionType, method: string, error: unknown): void => {
if (unmountedRef.current) return;
const errorMessage = error instanceof Error ? error.message : String(error);
logger?.error(`CC-Widgets: CampaignTask: ${action} failed: ${errorMessage}`, {
module: LOG_MODULE,
method,
});
setErrorType(CAMPAIGN_ACTION_ERROR_MAP[action]);
resetButtons();
},
[resetButtons, logger]
);
const handleAccept = useCallback((): void => {
if (isAcceptDisabled) return;
logger?.info('CC-Widgets: CampaignTask: Accept button clicked', {
module: LOG_MODULE,
method: 'handleAccept',
});
setIsAcceptClicked(true);
setHandleTimestamp(Date.now());
disableAllButtons();
acceptPreviewContact().catch((error: unknown) => handleActionError('ACCEPT', 'handleAccept', error));
}, [isAcceptDisabled, acceptPreviewContact, disableAllButtons, handleActionError, logger]);
const handleSkip = useCallback((): void => {
if (isSkipButtonDisabled) return;
logger?.info('CC-Widgets: CampaignTask: Skip button clicked', {
module: LOG_MODULE,
method: 'handleSkip',
});
disableAllButtons();
skipPreviewContact().catch((error: unknown) => handleActionError('SKIP', 'handleSkip', error));
}, [isSkipButtonDisabled, skipPreviewContact, disableAllButtons, handleActionError, logger]);
const handleRemove = useCallback((): void => {
if (isRemoveButtonDisabled) return;
logger?.info('CC-Widgets: CampaignTask: Remove button clicked', {
module: LOG_MODULE,
method: 'handleRemove',
});
disableAllButtons();
removePreviewContact().catch((error: unknown) => handleActionError('REMOVE', 'handleRemove', error));
}, [isRemoveButtonDisabled, removePreviewContact, disableAllButtons, handleActionError, logger]);
const handleTimeout = useCallback((): void => {
logger?.info('CC-Widgets: CampaignTask: Countdown expired, updating UI for auto-action', {
module: LOG_MODULE,
method: 'handleTimeout',
});
// Consistent with Agent Desktop: the UI only updates button states on
// timeout — the backend executes the actual auto-action on its own
// timer. Calling the API from the UI would double-fire the action and
// could auto-accept campaigns the agent never saw.
switch (autoAction) {
case 'ACCEPT':
setIsAcceptClicked(true);
setHandleTimestamp(Date.now());
disableAllButtons();
logger?.info('CC-Widgets: CampaignTask: Auto-accept UI state set, awaiting backend', {
module: LOG_MODULE,
method: 'handleTimeout',
});
break;
case 'SKIP':
case 'REMOVE':
disableAllButtons();
logger?.info(`CC-Widgets: CampaignTask: Auto-${autoAction.toLowerCase()} UI state set, awaiting backend`, {
module: LOG_MODULE,
method: 'handleTimeout',
});
break;
default:
logger?.warn('CC-Widgets: CampaignTask: No valid auto-action configured', {
module: LOG_MODULE,
method: 'handleTimeout',
});
break;
}
}, [autoAction, disableAllButtons, logger]);
const [isCancelDisabled, setIsCancelDisabled] = useState<boolean>(false);
const handleCancel = useCallback((): void => {
if (isCancelDisabled) return;
logger?.info('CC-Widgets: CampaignTask: Cancel button clicked', {
module: LOG_MODULE,
method: 'handleCancel',
});
setIsCancelDisabled(true);
disableAllButtons();
cancelPreviewContact().catch((error: unknown) => {
if (unmountedRef.current) return;
const errorMessage = error instanceof Error ? error.message : String(error);
logger?.error(`CC-Widgets: CampaignTask: Cancel failed: ${errorMessage}`, {
module: LOG_MODULE,
method: 'handleCancel',
});
setErrorType('CANCEL_FAILED');
setIsCancelDisabled(false);
resetButtons();
});
}, [isCancelDisabled, cancelPreviewContact, disableAllButtons, resetButtons, logger]);
const handleErrorClose = useCallback((): void => {
setErrorType(null);
}, []);
const campaignTaskTriggerId = `campaign-task-trigger-${interactionId}`;
const [taskListFallbackTimestamp] = useState<number>(() => Date.now());
const taskListHandleTimestamp =
handleTimestamp ??
getAgentJoinTimestamp(task, agentId) ??
task.data.interaction.createdTimestamp ??
taskListFallbackTimestamp;
return (
<section
className="campaign-task"
aria-label={CAMPAIGN_TASK_REGION_LABEL}
aria-busy={isAcceptClicked}
data-testid="campaign-task"
id={campaignTaskTriggerId}
>
<CampaignTaskPopover
task={task}
logger={logger}
triggerId={campaignTaskTriggerId}
isAcceptClicked={isAcceptClicked}
isAccepted={isAccepted}
isAcceptDisabled={isAcceptDisabled}
isSkipDisabled={isSkipButtonDisabled}
isRemoveDisabled={isRemoveButtonDisabled}
onAccept={handleAccept}
onSkip={handleSkip}
onRemove={handleRemove}
onTimeout={handleTimeout}
handleTimestamp={handleTimestamp}
/>
<CampaignTaskListItem
title={title}
phoneNumber={phoneNumber}
customerName={customerName}
timeoutTimestamp={timeoutTimestamp}
isAcceptClicked={isAcceptClicked}
isAccepted={isAccepted}
isAcceptDisabled={isAcceptDisabled}
isSkipDisabled={isSkipButtonDisabled}
isRemoveDisabled={isRemoveButtonDisabled}
onAccept={handleAccept}
onSkip={handleSkip}
onRemove={handleRemove}
onTimeout={handleTimeout}
handleTimestamp={taskListHandleTimestamp}
timerDisplayMode="handle-time"
logger={logger}
className="campaign-task-list-item"
/>
<div className="campaign-task-expanded" data-testid="campaign-task-expanded">
<GlobalVariablesPanel variables={globalVariables} />
{isBrowser && !isAccepted && (
<Button
variant="secondary"
color="negative"
onClick={handleCancel}
disabled={isCancelDisabled}
className="campaign-task-cancel-button"
aria-label={CANCEL}
data-testid="campaign-task-cancel-button"
prefixIcon="cancel-bold"
>
{CANCEL}
</Button>
)}
</div>
{errorType !== null && <CampaignErrorDialog errorType={errorType} isOpen={true} onClose={handleErrorClose} />}
</section>
);
};
const CampaignTaskWithMetrics = withMetrics(CampaignTask, 'CampaignTask');
export default CampaignTaskWithMetrics;