-
Notifications
You must be signed in to change notification settings - Fork 0
/
exampleServiceDesk.ts
383 lines (358 loc) · 12.5 KB
/
exampleServiceDesk.ts
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
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
/**
* (C) Copyright IBM Corp. 2020.
*
* Licensed under the MIT License (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* https://opensource.org/licenses/MIT
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
*/
import { ErrorType } from '../types/errors';
import { MessageRequest, MessageResponse } from '../types/message';
import { User } from '../types/profiles';
import { ServiceDesk, ServiceDeskFactoryParameters, ServiceDeskStateFromWAC } from '../types/serviceDesk';
import { AgentProfile, ServiceDeskCallback } from '../types/serviceDeskCallback';
import { stringToMessageResponseFormat } from '../utils';
/**
* This class returns startChat, endChat, sendMessageToAgent, updateState, userTyping, userReadMessages and
* areAnyAgentsOnline to be exposed to web chat through src/buildEntry.ts.
*/
class ExampleServiceDesk implements ServiceDesk {
agentProfile: AgentProfile;
callback: ServiceDeskCallback;
user: User;
sessionID: string;
constructor(parameters: ServiceDeskFactoryParameters) {
this.callback = parameters.callback;
this.user = { id: '' };
this.sessionID = '';
this.agentProfile = EXAMPLE_AGENT_PROFILE;
}
// Public ServiceDesk Methods
/**
* Instructs the service desk to start a new chat. This should be called immediately after the service desk
* instance has been created. It will make the appropriate calls to the service desk and begin communicating back
* to the calling code using the callback produce to the instance. This may only be called once per instance.
*
* @param connectMessage The original server message response that caused the connection to an agent. It will
* contain specific information to send to the service desk as part of the connection. This can includes things
* like a message to display to a human agent.
* @returns Returns a Promise that resolves when the service desk has successfully started a new chat. This does
* not necessarily mean that an agent has joined the conversation or has read any messages sent by the user.
*/
async startChat(connectMessage: MessageResponse): Promise<void> {
// In your real implementation you will want to grab this.user and this.sessionID to make available to your service desk.
return runSteps(this, sendConnectToAgent(this, connectMessage));
}
/**
* Tells the service desk to terminate the chat.
*
* @returns Returns a Promise that resolves when the service desk has successfully handled the call.
*/
async endChat(): Promise<void> {
this.agentProfile = EXAMPLE_AGENT_PROFILE;
}
/**
* Sends a message to the agent in the service desk.
*
* @param message The message from the user.
* @param messageID The unique ID of the message assigned by the widget.
* @returns Returns a Promise that resolves when the service desk has successfully handled the call.
*/
async sendMessageToAgent(message: MessageRequest, messageID: string): Promise<void> {
return runSteps(this, sendMessageToUser(this, message));
}
/**
* Informs the service desk of a change in the state of the web chat that is relevant to the service desks. These
* values may change at any time.
*
* @param state The current values of pieces of state from the main chat.
*/
updateState(state: ServiceDeskStateFromWAC): void {
this.user = { id: state.userID };
this.sessionID = state.sessionID;
}
}
/**
* Each mockStep specifies a time to wait before processing and a callback. These are passed as an array for us to
* simply mock multi-step behavior.
*/
interface MockStep {
/**
* The amount of time in milliseconds to wait after the previous step.
*/
delay: number;
/**
* The callback to call to run this step.
*/
callback: (instance: ExampleServiceDesk) => void;
/**
* Indicates if this step should return the given promise from the sendMessageToAgent function. This should be on
* the last step.
*/
returnPromise?: Promise<void>;
}
const JIM_ID = 'jim';
const MCCOY_ID = 'leonard';
const EXAMPLE_AGENT_PROFILE: AgentProfile = {
id: JIM_ID,
nickname: 'Kirk',
};
const EXAMPLE_AGENT_PROFILE_2: AgentProfile = {
id: MCCOY_ID,
nickname: 'McCoy',
};
// Messages
const STRINGS = {
hello_leonard: 'Hello, I am Dr. Leonard McCoy. How can I help?',
hello_jim: 'Hello, I am Captain James T. Kirk. How can I help?',
instructions: `You can send the following messages to get a specific response from me:<br/>
<u><b>help</b></u>: I will repeat these instructions.
<u><b>someone else</b></u>: I will transfer you to someone else.
<u><b>disconnect and reconnect</b></u>: I will simulate the service desk connect disconnecting and then reconnecting.
<u><b>end chat</b></u>: I will simulate the agent ending the chat.
`,
random_leonard: [
`I'm a doctor, not a physicist!`,
`I'm a doctor, not an engineer!`,
`I'm a doctor, not a veterinarian!`,
],
random_jim: [
`You know the greatest danger facing us is ourselves, an irrational fear of the unknown. But there's no such thing as the unknown - only things temporarily hidden, temporarily not understood.`,
`There's another way to survive — mutual trust and help.`,
`Fire photon torpedoes!`,
],
};
/**
* A switch statement that routes the request to either one of our hard coded examples or to a random returned message.
*/
function sendMessageToUser(instance: ExampleServiceDesk, message: MessageRequest): MockStep[] {
instance.callback.agentTyping(false);
switch (message?.input?.text?.toLowerCase()) {
case 'help':
return sendInstructions(instance);
case 'someone else':
return sendTransferAgent(instance);
case 'disconnect and reconnect':
return sendDisconnectAndReconnect(instance);
case 'end chat':
return sendEndChat(instance);
default:
return sendRandomMessage(instance);
}
}
/**
* Mocks creating a new session, letting web chat know that there is a wait, having the agent join and then sending
* some messages back to web chat.
*/
function sendConnectToAgent(instance: ExampleServiceDesk, connectMessage: MessageResponse): MockStep[] {
// You can use pre:send and pre:receive to build up a history of the previous message to send to the agent.
// See https://web-chat.global.assistant.watson.cloud.ibm.com/docs.html?to=api-events
console.log('Agent was sent the following info', connectMessage);
return [
{
delay: 1000,
callback: (instance: ExampleServiceDesk) => {
instance.callback.updateAgentAvailability({ estimated_wait_time: 1 });
},
},
{
delay: 5000,
callback: (instance: ExampleServiceDesk) => {
instance.callback.agentJoined(instance.agentProfile);
instance.callback.agentTyping(true);
},
},
{
delay: 1000,
callback: (instance: ExampleServiceDesk) => {
instance.callback.agentTyping(false);
instance.callback.sendMessageToUser(
stringToMessageResponseFormat(getHelloMessage(instance)),
instance.agentProfile.id,
);
},
},
{
delay: 1000,
callback: (instance: ExampleServiceDesk) => {
instance.callback.agentTyping(true);
},
},
{
delay: 1000,
callback: (instance: ExampleServiceDesk) => {
instance.callback.agentTyping(false);
instance.callback.sendMessageToUser(
stringToMessageResponseFormat(STRINGS.instructions),
instance.agentProfile.id,
);
},
},
];
}
/**
* Returns mock steps to send the instructions back to the web chat.
*/
function sendInstructions(instance: ExampleServiceDesk): MockStep[] {
return [
{
delay: 1000,
callback: (instance: ExampleServiceDesk) => {
instance.callback.agentReadMessages();
instance.callback.agentTyping(true);
},
},
{
delay: 1000,
callback: (instance: ExampleServiceDesk) => {
instance.callback.agentTyping(false);
instance.callback.sendMessageToUser(
stringToMessageResponseFormat(STRINGS.instructions),
instance.agentProfile.id,
);
},
},
];
}
/**
* Sends a random mock message back.
*/
function sendRandomMessage(instance: ExampleServiceDesk): MockStep[] {
return [
{
delay: 500,
callback: (instance: ExampleServiceDesk) => {
instance.callback.agentReadMessages();
instance.callback.agentTyping(true);
},
},
{
delay: 2000,
callback: (instance: ExampleServiceDesk) => {
instance.callback.agentTyping(false);
instance.callback.sendMessageToUser(
stringToMessageResponseFormat(randomMessage(instance)),
instance.agentProfile.id,
);
},
},
];
}
/**
* This example has two agents. This method will mock a transfer between them.
*/
function sendTransferAgent(instance: ExampleServiceDesk): MockStep[] {
return [
{
delay: 500,
callback: (instance: ExampleServiceDesk) => {
instance.callback.beginTransferToAnotherAgent();
},
},
{
delay: 1000,
callback: (instance: ExampleServiceDesk) => {
// Set the agentProfile on the class to be able to reference.
instance.agentProfile = instance.agentProfile.id === JIM_ID ? EXAMPLE_AGENT_PROFILE_2 : EXAMPLE_AGENT_PROFILE;
// Let web chat know a new agent has joined.
instance.callback.agentJoined(instance.agentProfile);
instance.callback.agentTyping(true);
},
},
{
delay: 2000,
callback: (instance: ExampleServiceDesk) => {
instance.callback.agentTyping(false);
instance.callback.sendMessageToUser(
stringToMessageResponseFormat(getHelloMessage(instance)),
instance.agentProfile.id,
);
},
},
{
delay: 500,
callback: (instance: ExampleServiceDesk) => {
instance.callback.agentTyping(true);
},
},
{
delay: 2000,
callback: (instance: ExampleServiceDesk) => {
instance.callback.agentTyping(false);
instance.callback.sendMessageToUser(
stringToMessageResponseFormat(STRINGS.instructions),
instance.agentProfile.id,
);
},
},
];
}
/**
* Sends the error status back to web chat mocking the service desk disconnecting and reconnecting.
*/
function sendDisconnectAndReconnect(instance: ExampleServiceDesk): MockStep[] {
return [
{
delay: 1000,
callback: (instance: ExampleServiceDesk) => {
instance.callback.setErrorStatus({ type: ErrorType.DISCONNECTED, isDisconnected: true });
},
},
{
delay: 3000,
callback: (instance: ExampleServiceDesk) => {
instance.callback.setErrorStatus({ type: ErrorType.DISCONNECTED, isDisconnected: false });
},
},
];
}
/**
* Calls the instance.callback.agentLeftChat() method to make the web chat aware that the agent has left.
*/
function sendEndChat(instance: ExampleServiceDesk): MockStep[] {
return [
{
delay: 0,
callback: (instance: ExampleServiceDesk) => {
// This method will let web chat know the agent has ended the chat.
instance.callback.agentEndedChat();
},
},
];
}
/**
* Returns a random message depending on which agent is active.
*/
function randomMessage(instance: ExampleServiceDesk): string {
const items = instance.agentProfile.id === JIM_ID ? STRINGS.random_jim : STRINGS.random_leonard;
const index = Math.floor(Math.random() * items.length);
const message = items[index];
return message;
}
/**
* Returns the hello message string depending on which agent is active.
*/
function getHelloMessage(instance: ExampleServiceDesk): string {
return instance.agentProfile.id === JIM_ID ? STRINGS.hello_jim : STRINGS.hello_leonard;
}
/**
* This function will run a series of steps to simulate some interaction between the agent and a user with pauses
* in between each step as defined.
*/
function runSteps(instance: ExampleServiceDesk, steps: MockStep[]): Promise<void> {
let totalTime = 0;
steps.forEach((step) => {
totalTime += step.delay;
setTimeout(() => {
step.callback(instance);
}, totalTime);
});
const lastStep = steps[steps.length - 1];
return lastStep.returnPromise || Promise.resolve();
}
export { ExampleServiceDesk };