-
-
Notifications
You must be signed in to change notification settings - Fork 310
/
GoogleAnalyticsSender.ts
412 lines (335 loc) 路 12 KB
/
GoogleAnalyticsSender.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
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
import { Plugin, PluginConfig, BaseApp, HandleRequest, Jovo, Util, User, JovoData, Analytics, JovoError, ErrorCode } from 'jovo-core';
import { JovoUser, App } from 'jovo-framework';
import * as util from 'util';
import { GoogleAssistant, GoogleActionRequest } from 'jovo-platform-googleassistant';
import * as ua from 'universal-analytics';
import _get = require('lodash.get');
import _merge = require('lodash.merge');
import { eventNames } from 'cluster';
import * as murmurhash from 'murmurhash';
import { DeveloperTrackingMethods } from './DeveloperTrackingMethods';
export interface Config extends PluginConfig {
trackingId: string;
}
export interface EventParameters {
eventCategory: string;
eventAction: string;
eventLabel?: string;
eventValue?: number;
documentPath?: string;
}
export interface TransactionParams {
ti: string;
tr?: string | number;
ts?: string | number;
tt?: string | number;
ta?: string;
p?: string;
[key: string]: any;
}
export interface ItemParams {
ip?: string | number;
iq?: string | number;
ic?: string;
in?: string;
iv?: string;
p?: string;
ti: string;
[key: string]: any;
}
//export class GoogleAnalyticsSender implements Plugin {
/**
* @public
*/
export class GoogleAnalyticsSender implements Analytics {
name?: string | undefined;
config: Config = {
trackingId: ""
};
constructor(config?: Config) {
if (config) {
this.config = _merge(this.config, config);
}
this.track = this.track.bind(this);
}
track(handleRequest: HandleRequest): void {
this.sendDataToGA.bind(this);
}
install(app: BaseApp): void {
if (!this.config.trackingId) {
throw new JovoError("Google Analytics tracking id was not found.",
ErrorCode.ERR_PLUGIN,
'jovo-analytics-googleanalytics',
"trackingId needs to be added to config.js. See https://www.jovo.tech/docs/analytics/dashbot for details.",
"You can find your tracking id in GoogleAnalytics by clicking: Admin -> Property Settings -> Tracking Id"
)
}
else {
console.log("tracking id is: " + this.config.trackingId);
app.middleware('platform.nlu')!.use(this.setJovoObjectAccess.bind(this));
app.middleware('after.response')!.use(this.sendDataToGA.bind(this));//use(this.track);
app.middleware('fail')!.use(this.sendErrorToGA.bind(this));
console.log("added GA events");
}
}
uninstall(parent?: any): void {
}
/**
* Sets the analytics variable to the instance of this object for making it accessable in skill code
* @param handleRequest
*/
setJovoObjectAccess(handleRequest: HandleRequest) {
const jovo = handleRequest.jovo;
if (!jovo) {
return this.throwJovoNotSetError();
}
jovo.$googleAnalytics = new DeveloperTrackingMethods(this, jovo);
}
/**
* Pageviews should allways send intent data -> method returns standard
*/
getCurrentPageParameters(jovo: Jovo): ua.PageviewParams {
if (!jovo) {
this.throwJovoNotSetError();
}
const intentName = jovo.getMappedIntentName() ? jovo.getMappedIntentName()! : jovo.$type.type!;
const standardPageviewParameters: ua.PageviewParams = {
dp: this.getPageName(jovo),
dh: jovo.$type.type!,
dt: intentName
};
return standardPageviewParameters;
}
/**
* SendEvent with parameters are custom
* @param visitor
* @param eventParameters
*/
sendIntentEvent(visitor: ua.Visitor, eventParameters: EventParameters) {
visitor
.event(
eventParameters,
)
.send();
}
sendEvent(jovo: Jovo, eventParameters: EventParameters) {
const visitor = this.initVisitor(jovo);
visitor
.event(
eventParameters,
)
.send();
}
sendTransaction(jovo: Jovo, transactionParams: TransactionParams) {
const visitor = this.initVisitor(jovo);
visitor
.transaction(
transactionParams,
)
.send();
}
sendItem(jovo: Jovo, itemParams : ItemParams) {
const visitor = this.initVisitor(jovo);
visitor
.transaction(
itemParams,
)
.send();
}
/**
* throws an error if jovo was not set
*/
throwJovoNotSetError() {
throw new JovoError("Could not make GooleAnalytics available to skill.",
ErrorCode.ERR_PLUGIN,
'jovo-analytics-googleanalytics',
"Jovo Instance was not available",
"Contact admin."
)
}
/**
* Generates Hash for User Id
* @param jovo
*/
getUserId(jovo: Jovo): string {
if (!jovo) {
this.throwJovoNotSetError();
}
//let idHash = murmurhash.v3(jovo.$user.getId()!) + murmurhash.v3(jovo.getDeviceId()!); //for local testing via different devices
const idHash = murmurhash.v3(jovo.$user.getId()!);
const uuid = idHash.toString();
return uuid;
}
/**
* Generates pageName from State and Intent Name
* @param jovo
*/
getPageName(jovo: Jovo) {
if (!jovo) {
this.throwJovoNotSetError();
}
const intentName = jovo.getMappedIntentName() ? jovo.getMappedIntentName()! : jovo.$type.type!;
const state = jovo.getState() ? jovo.getState() : "/";
return `${state}.${intentName}`;
}
/**
* Visitor initiation which sets needed fixed parameters
* @param jovo
*/
initVisitor(jovo: Jovo): ua.Visitor {
if (!jovo) {
this.throwJovoNotSetError();
}
const uuid = this.getUserId(jovo);
const visitor = ua(this.config.trackingId, uuid,
{
strictCidFormat: false,
});
//const visitor = ua(this.config.trackingId, {uid: uuid});
visitor.set('uid', uuid);
visitor.set("dataSource", jovo.getPlatformType()); //save segment information to seperate alexa and assistant data
visitor.set("userLanguage", jovo.getLocale());
visitor.set("cd1", uuid); //custom dimension for userId at hit scope (in GA)
//setting medium/source for referral
const launchType: string | undefined = _get(jovo.$request, 'request.launchRequestType'); //only referrer has a launchType property
if (launchType) {
visitor.set("campaignMedium", "referral");
visitor.set("campaignSource", _get(jovo.$request, 'request.metadata.referrer'));
}
return visitor;
}
sendCustomMetric(jovo: Jovo, indexInGA: number, value: string) {
const metricKey = "cm" + indexInGA;
jovo.$data[metricKey] = value;
}
sendUserTransaction(jovo: Jovo, transactionId: string) {
if (!jovo) {
this.throwJovoNotSetError();
}
this.initVisitor(jovo)
.transaction({ ti: transactionId, "tr": "1" });
}
/**
* User Events ties users to event category and action
* @param eventName maps to category -> eventGroup
* @param eventElement maps to action -> instance of eventGroup
*/
sendUserEvent(jovo: Jovo, eventCategory: string, eventElement = "defaultItem") {
if (!jovo) {
this.throwJovoNotSetError();
}
const visitor = this.initVisitor(jovo);
if (visitor) {
const eventParams: EventParameters = {
eventCategory: eventCategory,
eventAction: eventElement,
eventLabel: this.getUserId(jovo),
documentPath: this.getPageName(jovo)
};
this.sendIntentEvent(visitor, eventParams);
}
else {
console.error("Missing Google Analytics visitor. Is: " + visitor);
}
}
sendFlowErrors(jovo: Jovo) {
//Detect and Send Flow Errors
if (jovo.$request!.getIntentName() === "AMAZON.FallbackIntent" || jovo.$request!.getIntentName() === 'Default Fallback Intent') {
this.sendUserEvent(jovo, "FlowError", "nluUnhandled");
}
else if (jovo!.getRoute().path.endsWith("Unhandled")) {
this.sendUserEvent(jovo, "FlowError", "skillUnhandled");
}
}
/**
* Checks if session started or ended
* returns end, start, undefined
*/
getSessionTag(jovo: Jovo): string | undefined {
let sessionTag = undefined;
//Launch Request
if (jovo.isNewSession()) {
sessionTag = 'start'; //Set session start
}
//jovo.$type
if (jovo.getMappedIntentName() === 'END') {
sessionTag = 'end';
}
//end session if session Ended Request
if (jovo.$type === "END") {
sessionTag = 'end';
}
return sessionTag;
}
/**
* Auto send intent data after each response. Also setting sessions and flowErrors
* @param handleRequest
*/
sendDataToGA(handleRequest: HandleRequest) {
console.log("start sending data to GA...");
const jovo: Jovo = handleRequest.jovo!;
const visitor = this.initVisitor(jovo);
if (!visitor) {
console.error("Missing Google Analytics visitor. Is: " + visitor);
}
const sessionTag = this.getSessionTag(jovo);
if (sessionTag) {
visitor.set("sessionControl", sessionTag);
}
//Search for custom metrics set by user
if (jovo.$data) {
Object.entries(jovo.$data).forEach(entry => {
const dataKey = entry[0];
const dataValue = entry[1];
if (dataKey.startsWith("cm") && dataValue) { //check if custom dimension data and only add if value
visitor.set(dataKey, dataValue);
}
});
}
const intentName = jovo.getMappedIntentName() ? jovo.getMappedIntentName()! : jovo.$type.type!;
//send Intent Name + standard Info
visitor
.pageview(this.getCurrentPageParameters(jovo)!, (error) => {
error ? console.log("Error during sending pageview data: " + error!.message) : console.log("no Error sending Intent Data");
})
.send();
console.log("*****SENT DATA TO GOOGLE Analytics");
//Detect and Send Flow Errors
this.sendFlowErrors(jovo);
//send Slot data as events if there
if (jovo.$inputs) { //add all slot values
Object.entries(jovo.$inputs).forEach(entry => {
const slotName = entry[0];
const slotValue = entry[1];
if (slotValue.key) { //only add if input has value
const eventParameters: EventParameters = {
eventCategory: "SlotInput",
eventAction: slotValue.key, //slot value
eventLabel: slotName, //slot name
documentPath: this.getPageName(jovo)
};
this.sendIntentEvent(visitor, eventParameters);
console.log(`${slotName} has value ${slotValue.key} -> added`);
}
});
}
}
/**
* Auto send Exception to Google Analytics if Error
* @param handleRequest
*/
sendErrorToGA(handleRequest: HandleRequest) {
const jovo = handleRequest.jovo!;
const visitor = this.initVisitor(jovo);
if (!visitor) {
console.error("Missing Google Analytics visitor. Is: " + visitor);
}
visitor.set("sessionControl", "end");
visitor.
pageview(this.getCurrentPageParameters(jovo)!, (error) => {
error ? console.log(error!.message) : console.log("no Error sending Intent Data");
})
.exception(handleRequest.error!.name)
.send();
}
}