/
properties.js
740 lines (663 loc) · 18.8 KB
/
properties.js
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
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
/**
* `modules/analytics-4` data store: properties.
*
* Site Kit by Google, Copyright 2021 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* 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.
*/
/**
* External dependencies
*/
import invariant from 'invariant';
/**
* Internal dependencies
*/
import API from 'googlesitekit-api';
import Data from 'googlesitekit-data';
import { CORE_USER } from '../../../googlesitekit/datastore/user/constants';
import { CORE_SITE } from '../../../googlesitekit/datastore/site/constants';
import { CORE_MODULES } from '../../../googlesitekit/modules/datastore/constants';
import { READ_SCOPE as TAGMANAGER_READ_SCOPE } from '../../tagmanager/datastore/constants';
import {
MODULES_ANALYTICS_4,
PROPERTY_CREATE,
MAX_WEBDATASTREAMS_PER_BATCH,
WEBDATASTREAM_CREATE,
} from './constants';
import { HOUR_IN_SECONDS, normalizeURL } from '../../../util';
import { createFetchStore } from '../../../googlesitekit/data/create-fetch-store';
import { isValidPropertySelection } from '../utils/validation';
import { actions as webDataStreamActions } from './webdatastreams';
import { isValidAccountID } from '../../analytics/util';
import { createValidatedAction } from '../../../googlesitekit/data/utils';
import { isFeatureEnabled } from '../../../features';
const { commonActions, createRegistryControl } = Data;
const fetchGetPropertyStore = createFetchStore( {
baseName: 'getProperty',
controlCallback( { propertyID } ) {
return API.get(
'modules',
'analytics-4',
'property',
{ propertyID },
{
useCache: false,
}
);
},
reducerCallback( state, property, { propertyID } ) {
return {
...state,
propertiesByID: {
...state.propertiesByID,
[ propertyID ]: property,
},
};
},
argsToParams( propertyID ) {
return { propertyID };
},
validateParams( { propertyID } = {} ) {
invariant( propertyID, 'propertyID is required.' );
},
} );
const fetchGetPropertiesStore = createFetchStore( {
baseName: 'getProperties',
controlCallback( { accountID } ) {
return API.get(
'modules',
'analytics-4',
'properties',
{ accountID },
{
useCache: false,
}
);
},
reducerCallback( state, properties, { accountID } ) {
return {
...state,
properties: {
...state.properties,
[ accountID ]: properties,
},
propertiesByID: properties.reduce(
( accum, property ) => ( {
...accum,
[ property._id ]: property,
} ),
state.propertiesByID || {}
),
};
},
argsToParams( accountID ) {
return { accountID };
},
validateParams( { accountID } = {} ) {
invariant( accountID, 'accountID is required.' );
},
} );
const fetchCreatePropertyStore = createFetchStore( {
baseName: 'createProperty',
controlCallback( { accountID } ) {
return API.set( 'modules', 'analytics-4', 'create-property', {
accountID,
} );
},
reducerCallback( state, property, { accountID } ) {
return {
...state,
properties: {
...state.properties,
[ accountID ]: [
...( state.properties[ accountID ] || [] ),
property,
],
},
};
},
argsToParams( accountID ) {
return { accountID };
},
validateParams( { accountID } = {} ) {
invariant( accountID, 'accountID is required.' );
},
} );
const fetchGetGoogleTagSettingsStore = createFetchStore( {
baseName: 'getGoogleTagSettings',
controlCallback( { measurementID } ) {
return API.get( 'modules', 'analytics-4', 'google-tag-settings', {
measurementID,
} );
},
reducerCallback( state, googleTagSettings ) {
return {
...state,
googleTagSettings,
};
},
argsToParams( measurementID ) {
return { measurementID };
},
validateParams( { measurementID } = {} ) {
invariant( measurementID, 'measurementID is required.' );
},
} );
// Actions
const WAIT_FOR_PROPERTIES = 'WAIT_FOR_PROPERTIES';
const MATCHING_ACCOUNT_PROPERTY = 'MATCHING_ACCOUNT_PROPERTY';
const SET_HAS_MISMATCHED_TAG = 'SET_HAS_MISMATCHED_GOOGLE_TAG_ID';
const baseInitialState = {
properties: {},
propertiesByID: {},
hasMismatchedTag: false,
isMatchingAccountProperty: false,
};
const baseActions = {
/**
* Creates a new GA4 property.
*
* @since 1.31.0
*
* @param {string} accountID Analytics account ID.
* @return {Object} Object with `response` and `error`.
*/
createProperty( accountID ) {
invariant( accountID, 'accountID is required.' );
return ( function* () {
const { response, error } =
yield fetchCreatePropertyStore.actions.fetchCreateProperty(
accountID
);
return { response, error };
} )();
},
/**
* Sets the given property and related fields in the store.
*
* @since 1.31.0
*
* @param {string} propertyID GA4 property ID.
* @return {Object} A Generator function.
*/
selectProperty: createValidatedAction(
( propertyID ) => {
invariant(
isValidPropertySelection( propertyID ),
'A valid propertyID selection is required.'
);
},
function* ( propertyID ) {
const registry = yield Data.commonActions.getRegistry();
registry
.dispatch( MODULES_ANALYTICS_4 )
.setPropertyID( propertyID );
registry
.dispatch( MODULES_ANALYTICS_4 )
.setWebDataStreamID( WEBDATASTREAM_CREATE );
registry
.dispatch( MODULES_ANALYTICS_4 )
.updateSettingsForMeasurementID( '' );
if ( PROPERTY_CREATE === propertyID ) {
return;
}
yield webDataStreamActions.waitForWebDataStreams( propertyID );
const webdatastream = registry
.select( MODULES_ANALYTICS_4 )
.getMatchingWebDataStreamByPropertyID( propertyID );
if ( webdatastream ) {
registry
.dispatch( MODULES_ANALYTICS_4 )
.setWebDataStreamID( webdatastream._id );
registry
.dispatch( MODULES_ANALYTICS_4 )
.updateSettingsForMeasurementID(
// eslint-disable-next-line sitekit/acronym-case
webdatastream.webStreamData.measurementId
);
}
}
),
/**
* Finds a matching property and returns it.
*
* @since 1.36.0
*
* @return {Object|null} Matching property on success, otherwise NULL.
*/
*findMatchedProperty() {
const registry = yield commonActions.getRegistry();
const accounts = yield Data.commonActions.await(
registry
.__experimentalResolveSelect( MODULES_ANALYTICS_4 )
.getAccountSummaries()
);
if ( ! Array.isArray( accounts ) || accounts.length === 0 ) {
return null;
}
const url = registry.select( CORE_SITE ).getReferenceSiteURL();
const propertyIDs = accounts.reduce(
( acc, { propertySummaries: properties } ) => [
...acc,
...( properties || [] ).map( ( { _id } ) => _id ),
],
[]
);
return yield Data.commonActions.await(
registry
.dispatch( MODULES_ANALYTICS_4 )
.matchPropertyByURL( propertyIDs, url )
);
},
/**
* Matches a property for provided accountID.
*
* @since 1.38.0
*
* @param {string} accountID GA4 account ID.
* @return {Object|null} Matched property object on success, otherwise NULL.
*/
*matchAccountProperty( accountID ) {
const registry = yield Data.commonActions.getRegistry();
yield baseActions.waitForProperties( accountID );
const referenceURL = registry.select( CORE_SITE ).getReferenceSiteURL();
const properties = registry
.select( MODULES_ANALYTICS_4 )
.getProperties( accountID );
const property = yield baseActions.matchPropertyByURL(
( properties || [] ).map( ( { _id } ) => _id ),
referenceURL
);
return property;
},
/**
* Matches and selects a property for provided accountID.
*
* @since 1.34.0
*
* @param {string} accountID GA4 account ID.
* @param {string} fallbackPropertyID A fallback propertyID to use if a matched property is not found.
* @return {Object|null} Matched property object on success, otherwise NULL.
*/
*matchAndSelectProperty( accountID, fallbackPropertyID = '' ) {
yield {
payload: { isMatchingAccountProperty: true },
type: MATCHING_ACCOUNT_PROPERTY,
};
const property = yield baseActions.matchAccountProperty( accountID );
const propertyID = property?._id || fallbackPropertyID;
if ( propertyID ) {
yield baseActions.selectProperty( propertyID );
}
yield {
payload: { isMatchingAccountProperty: false },
type: MATCHING_ACCOUNT_PROPERTY,
};
return property;
},
/**
* Matches a property by URL.
*
* @since 1.33.0
*
* @param {Array.<number>} properties Array of property IDs.
* @param {Array.<string>|string} url A list of URLs or a signle URL to match properties.
* @return {Object} A property object if found.
*/
*matchPropertyByURL( properties, url ) {
const registry = yield commonActions.getRegistry();
const urls = ( Array.isArray( url ) ? url : [ url ] )
.filter( ( item ) => typeof item === 'string' )
.map( normalizeURL );
for (
let i = 0;
i < properties.length;
i += MAX_WEBDATASTREAMS_PER_BATCH
) {
const chunk = properties.slice(
i,
i + MAX_WEBDATASTREAMS_PER_BATCH
);
const webdatastreams = yield commonActions.await(
registry
.__experimentalResolveSelect( MODULES_ANALYTICS_4 )
.getWebDataStreamsBatch( chunk )
);
for ( const propertyID in webdatastreams ) {
for ( const webdatastream of webdatastreams[ propertyID ] ) {
for ( const singleURL of urls ) {
if (
singleURL ===
normalizeURL(
// eslint-disable-next-line sitekit/acronym-case
webdatastream.webStreamData?.defaultUri
)
) {
return yield commonActions.await(
registry
.__experimentalResolveSelect(
MODULES_ANALYTICS_4
)
.getProperty( propertyID )
);
}
}
}
}
}
return null;
},
/**
* Matches a property by measurement ID.
*
* @since 1.33.0
*
* @param {Array.<number>} properties Array of property IDs.
* @param {Array.<string>|string} measurementID A list of measurement IDs or a signle measurement ID to match properties.
* @return {Object} A property object if found.
*/
*matchPropertyByMeasurementID( properties, measurementID ) {
const registry = yield commonActions.getRegistry();
const measurementIDs = Array.isArray( measurementID )
? measurementID
: [ measurementID ];
for (
let i = 0;
i < properties.length;
i += MAX_WEBDATASTREAMS_PER_BATCH
) {
const chunk = properties.slice(
i,
i + MAX_WEBDATASTREAMS_PER_BATCH
);
const webdatastreams = yield commonActions.await(
registry
.__experimentalResolveSelect( MODULES_ANALYTICS_4 )
.getWebDataStreamsBatch( chunk )
);
for ( const propertyID in webdatastreams ) {
for ( const webdatastream of webdatastreams[ propertyID ] ) {
for ( const singleMeasurementID of measurementIDs ) {
if (
singleMeasurementID ===
webdatastream.webStreamData?.measurementId // eslint-disable-line sitekit/acronym-case
) {
return yield commonActions.await(
registry
.__experimentalResolveSelect(
MODULES_ANALYTICS_4
)
.getProperty( propertyID )
);
}
}
}
}
}
return null;
},
/**
* Waits for properties to be loaded for an account.
*
* @since 1.34.0
*
* @param {string} accountID GA4 account ID.
*/
*waitForProperties( accountID ) {
yield {
payload: { accountID },
type: WAIT_FOR_PROPERTIES,
};
},
/**
* Updates settings for a given measurement ID.
*
* @since 1.94.0
*
* @param {string} measurementID Measurement ID.
*/
*updateSettingsForMeasurementID( measurementID ) {
const registry = yield commonActions.getRegistry();
registry
.dispatch( MODULES_ANALYTICS_4 )
.setMeasurementID( measurementID );
if ( ! isFeatureEnabled( 'gteSupport' ) ) {
return;
}
if ( ! measurementID ) {
registry.dispatch( MODULES_ANALYTICS_4 ).setSettings( {
googleTagAccountID: '',
googleTagContainerID: '',
googleTagID: '',
} );
return;
}
const { response, error } =
yield fetchGetGoogleTagSettingsStore.actions.fetchGetGoogleTagSettings(
measurementID
);
if ( error ) {
return;
}
const { googleTagAccountID, googleTagContainerID, googleTagID } =
response;
// Note that when plain actions are dispatched in a function where an await has occurred (this can be a regular async function that has awaited, or a generator function
// action that yields to an async action), they are handled asynchronously when they would normally be synchronous. This means that following the usual pattern of dispatching
// individual setter actions for the `googleTagAccountID`, `googleTagContainerID` and `googleTagID` settings each resulted in a rerender of the
// GoogleTagIDMismatchNotification component, thus resulting in an erroneous call to the GET:container-destinations endpoint with mismatched settings. To mitigate this, we
// dispatch a single action here to set all these settings at once. The same applies to the `setSettings()` call above.
// See issue https://github.com/google/site-kit-wp/issues/6784 and the PR https://github.com/google/site-kit-wp/pull/6814.
registry.dispatch( MODULES_ANALYTICS_4 ).setSettings( {
googleTagAccountID,
googleTagContainerID,
googleTagID,
} );
},
/**
* Sets if GA4 has mismatched Google Tag ID.
*
* @since 1.96.0
*
* @param {boolean} hasMismatchedTag If GA4 has mismatched Google Tag.
* @return {Object} Redux-style action.
*/
*setHasMismatchedGoogleTagID( hasMismatchedTag ) {
return {
type: SET_HAS_MISMATCHED_TAG,
payload: { hasMismatchedTag },
};
},
/**
* Syncs Google Tag settings.
*
* @since 1.95.0
*/
*syncGoogleTagSettings() {
if ( ! isFeatureEnabled( 'gteSupport' ) ) {
return;
}
const { select, dispatch, __experimentalResolveSelect } =
yield Data.commonActions.getRegistry();
const hasTagManagerReadScope = select( CORE_USER ).hasScope(
TAGMANAGER_READ_SCOPE
);
if ( ! hasTagManagerReadScope ) {
return;
}
// Wait for modules to be available before selecting.
yield Data.commonActions.await(
__experimentalResolveSelect( CORE_MODULES ).getModules()
);
const { isModuleConnected } = select( CORE_MODULES );
if ( ! isModuleConnected( 'analytics-4' ) ) {
return;
}
// Wait for module settings to be available before selecting.
yield Data.commonActions.await(
__experimentalResolveSelect( MODULES_ANALYTICS_4 ).getSettings()
);
const { getGoogleTagID, getMeasurementID, getGoogleTagLastSyncedAtMs } =
select( MODULES_ANALYTICS_4 );
const measurementID = getMeasurementID();
if ( ! measurementID ) {
return;
}
const googleTagLastSyncedAtMs = getGoogleTagLastSyncedAtMs();
if (
!! googleTagLastSyncedAtMs &&
Date.now() - googleTagLastSyncedAtMs < HOUR_IN_SECONDS * 1000
) {
return;
}
const googleTagID = getGoogleTagID();
if ( !! googleTagID ) {
const googleTagContainer = yield Data.commonActions.await(
__experimentalResolveSelect(
MODULES_ANALYTICS_4
).getGoogleTagContainer( measurementID )
);
if ( ! googleTagContainer ) {
return;
}
if ( ! googleTagContainer.tagIds.includes( googleTagID ) ) {
yield baseActions.setHasMismatchedGoogleTagID( true );
}
} else {
yield baseActions.updateSettingsForMeasurementID( measurementID );
}
dispatch( MODULES_ANALYTICS_4 ).setGoogleTagLastSyncedAtMs(
Date.now()
);
dispatch( MODULES_ANALYTICS_4 ).saveSettings();
},
};
const baseControls = {
[ WAIT_FOR_PROPERTIES ]: createRegistryControl(
( { __experimentalResolveSelect } ) => {
return async ( { payload } ) => {
const { accountID } = payload;
await __experimentalResolveSelect(
MODULES_ANALYTICS_4
).getProperties( accountID );
};
}
),
};
function baseReducer( state, { type, payload } ) {
switch ( type ) {
case MATCHING_ACCOUNT_PROPERTY:
return { ...state, ...payload };
case SET_HAS_MISMATCHED_TAG:
return {
...state,
hasMismatchedTag: payload.hasMismatchedTag,
};
default:
return state;
}
}
const baseResolvers = {
*getProperties( accountID ) {
if ( ! isValidAccountID( accountID ) ) {
return;
}
const registry = yield Data.commonActions.getRegistry();
// Only fetch properties if there are none in the store for the given account.
const properties = registry
.select( MODULES_ANALYTICS_4 )
.getProperties( accountID );
if ( properties === undefined ) {
yield fetchGetPropertiesStore.actions.fetchGetProperties(
accountID
);
}
},
*getProperty( propertyID ) {
const registry = yield Data.commonActions.getRegistry();
const property = registry
.select( MODULES_ANALYTICS_4 )
.getProperty( propertyID );
if ( property === undefined ) {
yield fetchGetPropertyStore.actions.fetchGetProperty( propertyID );
}
},
};
const baseSelectors = {
/**
* Gets all GA4 properties this account can access.
*
* @since 1.31.0
*
* @param {Object} state Data store's state.
* @param {string} accountID The GA4 Account ID to fetch properties for.
* @return {(Array.<Object>|undefined)} An array of GA4 properties; `undefined` if not loaded.
*/
getProperties( state, accountID ) {
return state.properties[ accountID ];
},
/**
* Gets a property with specific ID.
*
* @since 1.31.0
*
* @param {Object} state Data store's state.
* @param {string} propertyID The GA4 property ID to fetch property object for.
* @return {(Object|undefined)} A property object; `undefined` if not loaded.
*/
getProperty( state, propertyID ) {
return state.propertiesByID[ propertyID ];
},
/**
* Determines whether we are matching account property or not.
*
* @since n.e.x.t
*
* @param {Object} state Data store's state.
* @return {boolean} TRUE if we matching account property right now, otherwise FALSE.
*/
isMatchingAccountProperty( state ) {
return state.isMatchingAccountProperty;
},
/**
* Checks if GA4 has mismatched Google Tag ID.
*
* @since 1.96.0
*
* @param {Object} state Data store's state.
* @return {boolean} If GA4 has mismatched Google Tag ID.
*/
hasMismatchedGoogleTagID( state ) {
return state.hasMismatchedTag;
},
};
const store = Data.combineStores(
fetchCreatePropertyStore,
fetchGetPropertiesStore,
fetchGetPropertyStore,
fetchGetGoogleTagSettingsStore,
{
initialState: baseInitialState,
actions: baseActions,
controls: baseControls,
reducer: baseReducer,
resolvers: baseResolvers,
selectors: baseSelectors,
}
);
export const initialState = store.initialState;
export const actions = store.actions;
export const controls = store.controls;
export const reducer = store.reducer;
export const resolvers = store.resolvers;
export const selectors = store.selectors;
export default store;