@google-cloud/nodejs-common 0.9.5-beta2 → 0.9.9-alpha

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.
package/README.md CHANGED
@@ -1,69 +1,78 @@
1
1
  # NodeJS Common Library
2
2
 
3
- <!--* freshness: { owner: 'lushu' reviewed: '2021-06-01' } *-->
4
-
5
- A NodeJs common library for other projects, e.g. [GMP and Google Ads
6
- Connector] and [Data Tasks Coordinator]. This library includes:
7
-
8
- 1. Authentication wrapper based on google auth library to support OAuth, JWT
9
- and ADC authentication;
10
-
11
- 1. Wrapper for some Google APIs for integration, mainly for [GMP and Google Ads
12
- Connector]:
13
-
14
- * Google Analytics data import
15
- * Google Analytics measurement protocol
16
- * Campaign Manager offline conversion upload
17
- * Search Ads 360 conversions upload
18
- * Google Ads click conversions upload
19
- * Google Ads customer match upload
20
- * Google Ads conversions scheduled uploads based on Google Sheets
21
- * Measurement Protocol Google Analytics 4
22
-
23
- 1. Wrapper for some Google APIs for reporting, mainly for [Data Tasks Coordinator]:
24
-
25
- * Google Ads reporting
26
- * Campaign Manager reporting
27
- * Search Ads 360 reporting
28
- * Display and Video 360 reporting
29
- * Ads Data Hub querying
30
-
31
- 1. Utilities wrapper class for Google Cloud Products:
32
-
33
- * **Firestore Access Object**: Firestore has two modes which are excluded
34
- to each other and can't be changed once selected in a Cloud
35
- Project[[2]]. This class, with its two successors offer a unified
36
- interface to operate data objects on either Firestore or Datastore.
37
-
38
- * **AutoMl Tables API**: Offers a unified entry to use this API based on
39
- Google Cloud client library combined with REST requests to service
40
- directly due to some functionalities missed in the client library.
41
-
42
- * **Pub/Sub Utilities**: Offers utilities functions to create topics and
43
- subscriptions for Pub/Sub, as well as the convenient way to publish a
44
- message.
45
-
46
- * **Storage Utilities**: Offers functions to manipulate the files on Cloud
47
- Storage. The main functions are:
48
-
49
- * Reading a given length (or slightly less) content without breaking a
50
- line;
51
- * Splitting a file into multiple files with the given length (or
52
- slightly less) without breaking a line;
53
- * Merging files into one file.
54
-
55
- * **Cloud Scheduler Adapter**: A wrapper to pause and resume Cloud
56
- Scheduler jobs.
57
-
58
- * **Cloud Functions Adapter**: Cloud Functions have different parameters
59
- in different environments, e.g. Node6 vs Node8[[1]]. This utility file
60
- offers an adapter to wrap a Node8 Cloud Functions into Node6 and Node8
61
- compatible functions.
62
-
3
+ <!--* freshness: { owner: 'lushu' reviewed: '2021-12-02' } *-->
4
+
5
+ A NodeJs common library for other projects, e.g. [GMP and Google Ads Connector]
6
+ and [Data Tasks Coordinator]. This library includes:
7
+
8
+ 1. Authentication wrapper based on google auth library to support OAuth, JWT and
9
+ ADC authentication;
10
+
11
+ 1. Wrapper for some Google APIs for integration, mainly
12
+ for [GMP and Google Ads Connector]:
13
+
14
+ * Google Analytics data import
15
+ * Google Analytics measurement protocol
16
+ * Campaign Manager offline conversion upload
17
+ * Search Ads 360 conversions upload
18
+ * Google Ads click conversions upload
19
+ * Google Ads customer match upload
20
+ * Google Ads conversions scheduled uploads based on Google Sheets
21
+ * Measurement Protocol Google Analytics 4
22
+
23
+ 1. Wrapper for some Google APIs for reporting, mainly
24
+ for [Data Tasks Coordinator]:
25
+
26
+ * Google Ads reporting
27
+ * Campaign Manager reporting
28
+ * Search Ads 360 reporting
29
+ * Display and Video 360 reporting
30
+ * YouTube Data API
31
+ * Ads Data Hub querying
32
+
33
+ 1. Utilities wrapper class for Google Cloud Products:
34
+
35
+ * **Firestore Access Object**: Firestore has two modes which are excluded to
36
+ each other and can't be changed once selected in a Cloud Project[[2]].
37
+ This class, with its two successors offer a unified interface to operate
38
+ data objects on either Firestore or Datastore.
39
+
40
+ * **AutoMl Tables API**: Offers a unified entry to use this API based on
41
+ Google Cloud client library combined with REST requests to service
42
+ directly due to some functionalities missed in the client library.
43
+
44
+ * **Vertex AI API**: Offers a unified entry to use this API based on Google
45
+ Cloud client library.
46
+
47
+ * **Pub/Sub Utilities**: Offers utilities functions to create topics and
48
+ subscriptions for Pub/Sub, as well as the convenient way to publish a
49
+ message.
50
+
51
+ * **Storage Utilities**: Offers functions to manipulate the files on Cloud
52
+ Storage. The main functions are:
53
+
54
+ * Reading a given length (or slightly less) content without breaking a
55
+ line;
56
+ * Splitting a file into multiple files with the given length (or
57
+ slightly less) without breaking a line;
58
+ * Merging files into one file.
59
+
60
+ * **Cloud Scheduler Adapter**: A wrapper to pause and resume Cloud Scheduler
61
+ jobs.
62
+
63
+ * **Cloud Functions Adapter**: Cloud Functions have different parameters in
64
+ different environments, e.g. Node6 vs Node8[[1]]. This utility file offers
65
+ an adapter to wrap a Node8 Cloud Functions into Node6 and Node8 compatible
66
+ functions.
67
+
63
68
  1. A share library for [Bash] to facilitate installation tasks.
64
69
 
65
70
  [GMP and Google Ads Connector]:https://github.com/GoogleCloudPlatform/cloud-for-marketing/tree/master/marketing-analytics/activation/gmp-googleads-connector
71
+
66
72
  [Data Tasks Coordinator]:https://github.com/GoogleCloudPlatform/cloud-for-marketing/tree/master/marketing-analytics/activation/data-tasks-coordinator
73
+
67
74
  [1]:https://cloud.google.com/functions/docs/writing/background#functions-writing-background-hello-pubsub-node8-10
75
+
68
76
  [2]:https://cloud.google.com/datastore/docs/concepts/overview#comparison_with_traditional_databases
77
+
69
78
  [Bash]:https://www.gnu.org/software/bash/
@@ -743,8 +743,8 @@ select_dataset_location() {
743
743
  "ASIA_PACIFIC"
744
744
  )
745
745
  local MULTI_REGIONAL=(
746
- "Data centers within member states of the European Union (EU)"
747
- "Data centers in the United States (US)"
746
+ "Data centers within member states of the European Union (eu)"
747
+ "Data centers in the United States (us)"
748
748
  )
749
749
  local AMERICAS=(
750
750
  "${NORTH_AMERICA[@]}"
@@ -1199,21 +1199,17 @@ create_or_update_sink() {
1199
1199
  local existingFilter
1200
1200
  existingFilter=$(gcloud logging sinks list --filter="name:${sinkName}" \
1201
1201
  --format="value(filter)")
1202
- if [[ "${existingFilter}" != "${logFilter}" ]]; then
1203
- local action
1204
- if [[ -z "${existingFilter}" ]]; then
1205
- action="create"
1206
- printf '%s\n' " Logging Export [${sinkName}] doesn't exist. Creating..."
1207
- else
1208
- action="update"
1209
- printf '%s\n' " Logging Export [${sinkName}] exists with a different \
1210
- filter. Updating..."
1211
- fi
1212
- gcloud -q logging sinks ${action} "${sinkName}" "${sinkDestAndFlags[@]}" \
1213
- --log-filter="${logFilter}"
1202
+ local action
1203
+ if [[ -z "${existingFilter}" ]]; then
1204
+ action="create"
1205
+ printf '%s\n' " Logging Export [${sinkName}] doesn't exist. Creating..."
1214
1206
  else
1215
- printf '%s\n' " Logging Export [${sinkName}] exists. Continue..."
1207
+ action="update"
1208
+ printf '%s\n' " Logging Export [${sinkName}] exists with a different \
1209
+ filter. Updating..."
1216
1210
  fi
1211
+ gcloud -q logging sinks ${action} "${sinkName}" "${sinkDestAndFlags[@]}" \
1212
+ --log-filter="${logFilter}"
1217
1213
  if [[ $? -gt 0 ]];then
1218
1214
  printf '%s\n' "Failed to create or update Logs router sink."
1219
1215
  return 1
@@ -1833,9 +1829,8 @@ get_cloud_functions_service_account() {
1833
1829
  # None.
1834
1830
  #######################################
1835
1831
  check_firestore_existence() {
1836
- local firestore_status
1837
- firestore_status=$(gcloud firestore operations list 2>&1)
1838
- while [[ ${firestore_status} =~ .*NOT_FOUND.* ]]; do
1832
+ gcloud firestore indexes fields list >/dev/null 2>&1
1833
+ while [[ $? -gt 0 ]]; do
1839
1834
  cat <<EOF
1840
1835
  Cannot find Firestore or Datastore in current project. Please visit \
1841
1836
  https://console.cloud.google.com/firestore?project=${GCP_PROJECT} to create a \
@@ -1846,7 +1841,7 @@ EOF
1846
1841
  local any
1847
1842
  read -n1 -s any
1848
1843
  printf '\n'
1849
- firestore_status=$(gcloud firestore operations list 2>&1)
1844
+ gcloud firestore indexes fields list >/dev/null 2>&1
1850
1845
  done
1851
1846
  }
1852
1847
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@google-cloud/nodejs-common",
3
- "version": "0.9.5-beta2",
3
+ "version": "0.9.9-alpha",
4
4
  "description": "A NodeJs common library for solutions based on Cloud Functions",
5
5
  "author": "Google Inc.",
6
6
  "license": "Apache-2.0",
@@ -16,20 +16,20 @@
16
16
  },
17
17
  "homepage": "https://github.com/GoogleCloudPlatform/cloud-for-marketing/blob/master/marketing-analytics/activation/common-libs/nodejs-common/README.md",
18
18
  "dependencies": {
19
- "@google-cloud/aiplatform": "^1.10.1",
20
- "@google-cloud/automl": "^2.4.2",
21
- "@google-cloud/bigquery": "^5.6.0",
22
- "@google-cloud/datastore": "^6.4.0",
23
- "@google-cloud/firestore": "^4.12.2",
24
- "@google-cloud/logging-winston": "^4.0.5",
25
- "@google-cloud/pubsub": "^2.12.0",
26
- "@google-cloud/storage": "^5.8.5",
27
- "gaxios": "^4.3.0",
28
- "google-ads-api": "^8.1.0",
29
- "google-ads-node": "^6.1.3",
30
- "google-auth-library": "^7.1.0",
31
- "googleapis": "^74.2.0",
32
- "soap": "^0.38.0",
19
+ "@google-cloud/aiplatform": "^1.13.0",
20
+ "@google-cloud/automl": "^2.5.1",
21
+ "@google-cloud/bigquery": "^5.9.2",
22
+ "@google-cloud/datastore": "^6.6.2",
23
+ "@google-cloud/firestore": "^4.15.1",
24
+ "@google-cloud/logging-winston": "^4.1.1",
25
+ "@google-cloud/pubsub": "^2.18.2",
26
+ "@google-cloud/storage": "^5.16.0",
27
+ "gaxios": "^4.3.2",
28
+ "google-ads-api": "^9.0.0",
29
+ "google-ads-node": "^7.0.0",
30
+ "google-auth-library": "^7.10.2",
31
+ "googleapis": "^91.0.0",
32
+ "soap": "^0.43.0",
33
33
  "winston": "^3.3.3",
34
34
  "lodash": "^4.17.21"
35
35
  },
@@ -41,25 +41,77 @@ const {
41
41
  },
42
42
  } = googleAdsLib;
43
43
  const {GoogleAdsApi} = require('google-ads-api');
44
+ const lodash = require('lodash');
45
+
44
46
  const AuthClient = require('./auth_client.js');
45
47
  const {getLogger, BatchResult,} = require('../components/utils.js');
46
48
 
47
49
  /** @type {!ReadonlyArray<string>} */
48
50
  const API_SCOPES = Object.freeze(['https://www.googleapis.com/auth/adwords',]);
49
51
 
52
+ /**
53
+ * List of properties that will be taken from the data file as elements of a
54
+ * conversion.
55
+ * @see https://developers.google.com/google-ads/api/reference/rpc/latest/ClickConversion
56
+ * @type {Array<string>}
57
+ */
58
+ const PICKED_PROPERTIES = [
59
+ 'external_attribution_data',
60
+ 'cart_data',
61
+ 'user_identifiers',
62
+ 'gclid',
63
+ 'conversion_action',
64
+ 'conversion_date_time',
65
+ 'conversion_value',
66
+ 'currency_code',
67
+ 'order_id',
68
+ ];
69
+
70
+ /**
71
+ * Kinds of UserIdentifier.
72
+ * @see https://developers.google.com/google-ads/api/reference/rpc/latest/UserIdentifier
73
+ * @type {Array<string>}
74
+ */
75
+ const IDENTIFIERS = [
76
+ 'hashed_email',
77
+ 'hashed_phone_number',
78
+ 'mobile_id',
79
+ 'third_party_user_id',
80
+ 'address_info',
81
+ ];
82
+
50
83
  /**
51
84
  * Configuration for uploading click conversions for Google Ads, includes:
52
85
  * gclid, conversion_action, conversion_date_time, conversion_value,
53
- * currency_code, order_id, external_attribution_data
86
+ * currency_code, order_id, external_attribution_data, etc.
87
+ * @see PICKED_PROPERTIES
88
+ *
89
+ * Other properties that will be used to build the conversions but not picked by
90
+ * the value directly including:
91
+ * 1. 'user_identifier_source', source of the user identifier. If there is user
92
+ * identifiers information in the conversion, this property should be set as
93
+ * 'FIRST_PARTY'.
94
+ * @see IDENTIFIERS
95
+ * @see https://developers.google.com/google-ads/api/reference/rpc/latest/UserIdentifier?hl=en
96
+ * 2. 'custom_variable_tags', the tags of conversion custom variables. To upload
97
+ * custom variables, 'conversion_custom_variable_id' is required rather than the
98
+ * 'tag'. So the invoker is expected to use the function
99
+ * 'getConversionCustomVariableId' to get the ids and pass in as a
100
+ * map(customVariables) of <tag, id> pairs before uploading conversions.
101
+ *
54
102
  * @see https://developers.google.com/google-ads/api/reference/rpc/latest/ClickConversion
55
103
  * @typedef {{
104
+ * external_attribution_data: (GoogleAdsApi.ExternalAttributionData|undefined),
105
+ * cart_data: (object|undefined),
56
106
  * gclid: string,
57
107
  * conversion_action: string,
58
108
  * conversion_date_time: string,
59
109
  * conversion_value: number,
60
110
  * currency_code:(string|undefined),
61
111
  * order_id: (string|undefined),
62
- * external_attribution_data: (GoogleAdsApi.ExternalAttributionData|undefined),
112
+ * user_identifier_source:(UserIdentifierSource|undefined),
113
+ * custom_variable_tags:(!Array<string>|undefined),
114
+ * customVariables:(!object<string,string>|undefined),
63
115
  * }}
64
116
  */
65
117
  let ClickConversionConfig;
@@ -219,10 +271,8 @@ class GoogleAds {
219
271
  */
220
272
  return async (lines, batchId) => {
221
273
  /** @type {!Array<ClickConversionConfig>} */
222
- const conversions = lines.map((line) => {
223
- const record = JSON.parse(line);
224
- return Object.assign({}, adsConfig, record);
225
- });
274
+ const conversions = lines.map(
275
+ (line) => buildClickConversionFromLine(line, adsConfig, customerId));
226
276
  /** @const {BatchResult} */
227
277
  const batchResult = {
228
278
  result: true,
@@ -346,7 +396,6 @@ class GoogleAds {
346
396
  * failure.
347
397
  * groupedFailed - a hashmap of failed the lines. The key is the reason, the
348
398
  * value is the array of failed lines due to this reason.
349
- * TODO: Confirm how to surface and handle groupedFailed.
350
399
  * @param {!BatchResult} batchResult
351
400
  * @param {!Array<!GoogleAdsFailure>} failures
352
401
  * @param {!Array<string>} lines The original input data.
@@ -404,6 +453,26 @@ class GoogleAds {
404
453
  return customer.conversionUploads.uploadClickConversions(request);
405
454
  }
406
455
 
456
+ /**
457
+ * Returns the id of Conversion Custom Variable with the given tag.
458
+ * @param {string} tag Custom Variable tag.
459
+ * @param {string} customerId
460
+ * @param {string} loginCustomerId Login customer account ID (Mcc Account id).
461
+ * @return {Promise<number|undefined>} Returns undefined if can't find tag.
462
+ */
463
+ async getConversionCustomVariableId(tag, customerId, loginCustomerId) {
464
+ const customer = this.getGoogleAdsApiCustomer_(loginCustomerId, customerId);
465
+ const customVariables = await customer.query(`
466
+ SELECT conversion_custom_variable.id,
467
+ conversion_custom_variable.tag
468
+ FROM conversion_custom_variable
469
+ WHERE conversion_custom_variable.tag = "${tag}" LIMIT 1
470
+ `);
471
+ if (customVariables.length > 0) {
472
+ return customVariables[0].conversion_custom_variable.id;
473
+ }
474
+ }
475
+
407
476
  /**
408
477
  * Returns the function to send out a request to Google Ads API with
409
478
  * user ids for Customer Match upload
@@ -535,6 +604,43 @@ class GoogleAds {
535
604
 
536
605
  }
537
606
 
607
+ /**
608
+ * Returns a conversion object based the given config and line data.
609
+ * @param {string} line A JSON string of a conversion data.
610
+ * @param {ClickConversionConfig} config Default click conversion params
611
+ * @param {string} customerId
612
+ * @return {object} A conversion
613
+ */
614
+ const buildClickConversionFromLine = (line, config, customerId) => {
615
+ const {customVariables, user_identifier_source} = config;
616
+ const record = JSON.parse(line);
617
+ const conversion = lodash.merge(lodash.pick(config, PICKED_PROPERTIES),
618
+ lodash.pick(record, PICKED_PROPERTIES));
619
+ if (customVariables) {
620
+ const tags = Object.keys(customVariables);
621
+ conversion.custom_variables = tags.map((tag) => {
622
+ return {
623
+ conversion_custom_variable:
624
+ `customers/${customerId}/conversionCustomVariables/${customVariables[tag]}`,
625
+ value: record[tag],
626
+ };
627
+ });
628
+ }
629
+ const user_identifiers = [];
630
+ IDENTIFIERS.forEach((identifier) => {
631
+ if (record[identifier]) {
632
+ user_identifiers.push({
633
+ user_identifier_source,
634
+ [identifier]: record[identifier],
635
+ });
636
+ }
637
+ });
638
+ if (user_identifiers.length > 0) {
639
+ conversion.user_identifiers = user_identifiers;
640
+ }
641
+ return conversion;
642
+ }
643
+
538
644
  module.exports = {
539
645
  ClickConversionConfig,
540
646
  CustomerMatchRecord,
@@ -542,4 +648,5 @@ module.exports = {
542
648
  GoogleAds,
543
649
  ReportQueryConfig,
544
650
  GoogleAdsField,
651
+ buildClickConversionFromLine,
545
652
  };