@bluedot-innovation/models 6.1.2 → 6.2.0-alpha.1

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/.gitlab-ci.yml CHANGED
@@ -59,7 +59,7 @@ create_dev_indexes:
59
59
  - master
60
60
 
61
61
  script:
62
- - MONGO_DB_URI=$DEV_MONGO_DB_URI make deploy-db-changes
62
+ - ENVIRONMENT=dev MONGO_DB_URI=$DEV_MONGO_DB_URI make deploy-db-changes
63
63
 
64
64
  # Create any newly required indexes in the production dbs
65
65
  create_production_indexes:
@@ -72,6 +72,6 @@ create_production_indexes:
72
72
  - master
73
73
 
74
74
  script:
75
- - MONGO_DB_URI="$AU_MONGO_DB_URI" make deploy-db-changes
76
- - MONGO_DB_URI="$EU_MONGO_DB_URI" make deploy-db-changes
77
- - MONGO_DB_URI="$US_MONGO_DB_URI" make deploy-db-changes
75
+ - ENVIRONMENT=prod_au MONGO_DB_URI="$AU_MONGO_DB_URI" make deploy-db-changes
76
+ - ENVIRONMENT=prod_eu MONGO_DB_URI="$EU_MONGO_DB_URI" make deploy-db-changes
77
+ - ENVIRONMENT=prod_us MONGO_DB_URI="$US_MONGO_DB_URI" make deploy-db-changes
package/CHANGELOG.md CHANGED
@@ -1,3 +1,10 @@
1
+ ## 6.1.4
2
+ - Added eta fields to androidConfig and iosConfig
3
+ - Created mobileConfigInitialiser for updated config profiles in dbs
4
+
5
+ ## 6.1.3
6
+ - Add `beaconDiscoveyCycleSecs` and `beaconCooloffCycleSecs` to AndroidConfig schema
7
+
1
8
  ## 6.1.2
2
9
  - Updated zone destinationId to accept null values
3
10
  - Added zone destinationId validation on zone geofeatures
package/Makefile CHANGED
@@ -14,8 +14,12 @@ ifndef DB_NAME
14
14
  $(error 'DB_NAME is not set')
15
15
  endif
16
16
 
17
+ ifndef ENVIRONMENT
18
+ $(error 'ENVIRONMENT is not set')
19
+ endif
20
+
17
21
  ifndef MONGO_DB_URI
18
22
  $(error 'MONGO_DB_URI is not set')
19
23
  endif
20
24
 
21
- node utils/dbInitialiser.js
25
+ node utils/DbInitialiser/DbInitialiser.js
package/README.MD CHANGED
@@ -15,7 +15,7 @@ Minimum test coverage enforced:
15
15
 
16
16
  To check test coverage:
17
17
 
18
- run `npm test:coverage`
18
+ run `npm run test:coverage`
19
19
 
20
20
  To lint:
21
21
 
@@ -41,9 +41,19 @@ When adding indexes to node_modules, they will not actually be created in the db
41
41
  production usage (see https://mongoosejs.com/docs/guide.html#autoIndex) as creating indexes with mongoose can lead to performance issues if done at the wrong
42
42
  time.
43
43
 
44
- To resolve this the file utils/dbInitialiser is used to perform any required db updates such as index creation. This creates the indexes
44
+ To resolve this the file utils/DbInitialiser/DbInitialiser is used to perform any required db updates such as index creation. This creates the indexes
45
45
  once and can be triggered at a time when load is not expected to be high in production. This has been added as a manual release stage as part of the
46
- CI/CD pipeline. If you need to add a new index, just add it to the indexes object in utils/dbInitialiser.
46
+ CI/CD pipeline. If you need to add a new index, just add it to the indexes object in utils/DbInitialiser/indexInitialiser.
47
47
 
48
48
  Indexes should still be added to the mongoose schemas as well, as these can be used in tests by triggering index creation with
49
49
  mockgoose using model.ensureIndexes(), and it provides another level of documentation.
50
+
51
+
52
+ ##### On Updating Mobile Config Use Case Profiles
53
+
54
+ The default mobile profiles for androidConfig and iosConfig are now defined in the utils/DbInitialiser/mobileConfigInitialiser
55
+ file. The mobileConfigProfiles object stores these values for each profile. If you need to add a new profile or change any of the
56
+ default values then update the mobileConfigProfiles object and these values will be updated in the dev environment on merge to
57
+ master, and updated in production when the manual release pipeline is triggered.
58
+
59
+ You can see what values have been added or updated by viewing the logs for the pipeline job after it has finished.
@@ -0,0 +1,98 @@
1
+ const mongoose = require('mongoose')
2
+ const {mobileConfigProfiles} = require('../../utils/DbInitialiser/mobileConfigInitialiser')
3
+ const {identifyDifferences} = require('../../utils/DbInitialiser/helpers')
4
+ const iosConfigSchema = require('../../schemas/IosConfig')
5
+ const androidConfigSchema = require('../../schemas/AndroidConfig')
6
+ const ConfigurationParametersSchema = require('../../models/ConfigurationParameters').Schema
7
+ const assert = require('chai').assert
8
+
9
+ describe("dbInitialiser settings", () => {
10
+ describe("mobileConfig profiles", () => {
11
+ Object.values(mobileConfigProfiles).map(profile => {
12
+ it(`should successfully validate ${profile.name} profile`, async () => {
13
+ const ConfigurationParameters = new mongoose.Document(profile, ConfigurationParametersSchema);
14
+ let validationError = await ConfigurationParameters.validate()
15
+ assert.notExists(validationError, "there should be no validation error")
16
+ })
17
+ })
18
+ })
19
+
20
+ describe("helper functions", () => {
21
+ describe("identifyDifferences function", () => {
22
+ it("should identify no differences for identical objects", () => {
23
+ const mockObjectToUpdate = {
24
+ testObjectProp: {
25
+ testInnerProp: "test"
26
+ },
27
+ testArrayProp: ['test1', 'test6'],
28
+ testNullProp: null
29
+ }
30
+ const mockDefaultObject = {
31
+ testObjectProp: {
32
+ testInnerProp: "test"
33
+ },
34
+ testArrayProp: ['test1', 'test6'],
35
+ testNullProp: null
36
+ }
37
+ const {
38
+ newFieldsToAdd,
39
+ existingFieldsToUpdate,
40
+ existingFieldsNotFoundInDefault
41
+ } = identifyDifferences(mockObjectToUpdate, mockDefaultObject);
42
+ assert.lengthOf(newFieldsToAdd, 0, "no new fields should be present")
43
+ assert.lengthOf(existingFieldsToUpdate, 0, "no existing fields should be updated")
44
+ assert.lengthOf(existingFieldsNotFoundInDefault, 0, "no existing fields should be found that don't exist in default")
45
+ })
46
+
47
+ it("should identify fields to update for objects with same keys and different values", () => {
48
+ const mockObjectToUpdate = {
49
+ testObjectProp: {
50
+ testInnerProp: "test"
51
+ },
52
+ testArrayProp: ['test1', 'test6'],
53
+ testNullProp: null
54
+ }
55
+
56
+ const mockDefaultObject = {
57
+ testObjectProp: {
58
+ testInnerProp: "different-value"
59
+ },
60
+ testArrayProp: ['test1', 'different-value'],
61
+ testNullProp: null
62
+ }
63
+ const {
64
+ newFieldsToAdd,
65
+ existingFieldsToUpdate,
66
+ existingFieldsNotFoundInDefault
67
+ } = identifyDifferences(mockObjectToUpdate, mockDefaultObject);
68
+ assert.lengthOf(newFieldsToAdd, 0, "no new fields should be present")
69
+ assert.lengthOf(existingFieldsToUpdate, 2, "two existing fields should be updated")
70
+ assert.lengthOf(existingFieldsNotFoundInDefault, 0, "no existing fields should be found that don't exist in default")
71
+ })
72
+
73
+ it("should identify existing fields not in default object when values are present in objectToUpdate but not default object", () => {
74
+ const mockObjectToUpdate = {
75
+ testObjectProp: {
76
+ testInnerProp: "test"
77
+ },
78
+ testArrayProp: ['test1', 'test6'],
79
+ testNullProp: null
80
+ }
81
+
82
+ const mockDefaultObject = {
83
+ testObjectProp: {
84
+ testInnerProp: "test"
85
+ }
86
+ }
87
+ const {
88
+ newFieldsToAdd,
89
+ existingFieldsToUpdate,
90
+ existingFieldsNotFoundInDefault
91
+ } = identifyDifferences(mockObjectToUpdate, mockDefaultObject);
92
+ assert.lengthOf(newFieldsToAdd, 0, "no new fields should be present")
93
+ assert.lengthOf(existingFieldsToUpdate, 0, "no existing fields should be updated")
94
+ assert.lengthOf(existingFieldsNotFoundInDefault, 2, "two existing fields should be found that don't exist in default")
95
+ })
96
+ })
97
+ })
98
+ })
@@ -22,10 +22,10 @@
22
22
  "iosSecretKey": "fZqphc1Vh2dqaIQEvz4APNbErZkW_AaaRmwE8BCmYpHZFc3n_ZKajTLgJgFqLNNN"
23
23
  }
24
24
  },
25
- "eta": {
25
+ "tempo": {
26
26
  "webhooks": [
27
27
  {
28
- "type": "eta",
28
+ "type": "tempo",
29
29
  "url": "https://webhooklistener.bluedotinnovation.com",
30
30
  "headers" : {
31
31
  "securityToken" : "value"
@@ -33,4 +33,4 @@
33
33
  }
34
34
  ]
35
35
  }
36
- }
36
+ }
@@ -81,7 +81,7 @@ testCase('Project', () => {
81
81
  })
82
82
  assertions(`should not validate if one of webhooks have a type orther than 'trigger'`, (done) => {
83
83
  project.webhooks.push({
84
- "type": "eta",
84
+ "type": "tempo",
85
85
  "url": "https://webhooklistener.bluedotinnovation.com",
86
86
  "headers" : {
87
87
  "securityToken" : "value"
@@ -94,8 +94,8 @@ testCase('Project', () => {
94
94
  done()
95
95
  })
96
96
  })
97
- assertions(`should not validate if one of eta webhooks have a type orther than 'eta'`, (done) => {
98
- project.eta.webhooks.push({
97
+ assertions(`should not validate if one of tempo webhooks have a type orther than 'tempo'`, (done) => {
98
+ project.tempo.webhooks.push({
99
99
  "type": "trigger",
100
100
  "url": "https://webhooklistener.bluedotinnovation.com",
101
101
  "headers" : {
@@ -105,7 +105,7 @@ testCase('Project', () => {
105
105
  let Project = new ProjectModel(project)
106
106
  Project.validate((err, res) => {
107
107
  assert.exists(err)
108
- assert.match(err.message, /eta.webhooks should contain eta webhooks only/)
108
+ assert.match(err.message, /tempo.webhooks should contain tempo webhooks only/)
109
109
  done()
110
110
  })
111
111
  })
@@ -94,8 +94,8 @@ describe('Zone', () => {
94
94
  assert.strictEqual(zone.tags[1], "1")
95
95
  })
96
96
 
97
- it('should save without errors when eta.destinationId is null', (done) => {
98
- zone.eta = {
97
+ it('should save without errors when tempo.destinationId is null', (done) => {
98
+ zone.tempo = {
99
99
  "destinationId": null
100
100
  }
101
101
  let Zone = new ZoneModel(zone)
@@ -106,11 +106,11 @@ describe('Zone', () => {
106
106
  })
107
107
  })
108
108
 
109
- const validEtaGeofeatureTypes = ['boundingBox', 'circle', 'polygon']
109
+ const validTempoGeofeatureTypes = ['boundingBox', 'circle', 'polygon']
110
110
 
111
- validEtaGeofeatureTypes.map(type => {
112
- it(`should save without errors when eta.destinationId is set and there is a single ${type} geofeature`, (done) => {
113
- zone.eta = {
111
+ validTempoGeofeatureTypes.map(type => {
112
+ it(`should save without errors when tempo.destinationId is set and there is a single ${type} geofeature`, (done) => {
113
+ zone.tempo = {
114
114
  "destinationId": "test-destination-id"
115
115
  }
116
116
  zone.geofeatures = zone.geofeatures.filter(gf => gf.type.match(new RegExp(type)))
@@ -419,8 +419,8 @@ describe('Zone', () => {
419
419
  })
420
420
  })
421
421
 
422
- it('should throw an error when eta.destinationId is longer than 128 characters', (done) => {
423
- zone.eta = {
422
+ it('should throw an error when tempo.destinationId is longer than 128 characters', (done) => {
423
+ zone.tempo = {
424
424
  "destinationId": 'Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry standard dummy text ever since the 1500s'
425
425
  }
426
426
  let Zone = new ZoneModel(zone)
@@ -431,11 +431,11 @@ describe('Zone', () => {
431
431
  })
432
432
  })
433
433
 
434
- const invalidEtaGeofeatures = ['geoline', 'beacon']
434
+ const invalidTempoGeofeatures = ['geoline', 'beacon']
435
435
 
436
- invalidEtaGeofeatures.map(type => {
437
- it(`should throw an error when eta.destinationId is set and there is a single ${type} geofeature`, (done) => {
438
- zone.eta = {
436
+ invalidTempoGeofeatures.map(type => {
437
+ it(`should throw an error when tempo.destinationId is set and there is a single ${type} geofeature`, (done) => {
438
+ zone.tempo = {
439
439
  "destinationId": "test-destination-id"
440
440
  }
441
441
  zone.geofeatures = zone.geofeatures.filter(gf => gf.type.match(new RegExp(type)))
@@ -448,8 +448,8 @@ describe('Zone', () => {
448
448
  })
449
449
  })
450
450
 
451
- it('should throw an error when eta.destinationId is set and there is more than one geofeature', (done) => {
452
- zone.eta = {
451
+ it('should throw an error when tempo.destinationId is set and there is more than one geofeature', (done) => {
452
+ zone.tempo = {
453
453
  "destinationId": "test-destination-id"
454
454
  }
455
455
  let Zone = new ZoneModel(zone)
package/helpers.js CHANGED
@@ -240,15 +240,15 @@ helpers.ensureNonEmptyGeofeatures = function(zone, next){
240
240
  next()
241
241
  }
242
242
 
243
- helpers.validateEtaDestinationIdLength = function(etaDestinationId) {
244
- if(etaDestinationId){
245
- return !(etaDestinationId.length > 128)
243
+ helpers.validateTempoDestinationIdLength = function(tempoDestinationId) {
244
+ if(tempoDestinationId){
245
+ return !(tempoDestinationId.length > 128)
246
246
  }
247
247
  return true
248
248
  }
249
249
 
250
- helpers.validateEtaDestinationSingleGeofeature = function(etaDestinationId) {
251
- if(etaDestinationId){
250
+ helpers.validateTempoDestinationSingleGeofeature = function(tempoDestinationId) {
251
+ if(tempoDestinationId){
252
252
  const geofeatures = this.ownerDocument().geofeatures
253
253
  if(!geofeatures.length){
254
254
  return false
@@ -258,9 +258,9 @@ helpers.validateEtaDestinationSingleGeofeature = function(etaDestinationId) {
258
258
  return true
259
259
  }
260
260
 
261
- helpers.validateEtaDestinationIdGeofeatureType = function(etaDestinationId) {
261
+ helpers.validateTempoDestinationIdGeofeatureType = function(tempoDestinationId) {
262
262
  const geofeatures = this.ownerDocument().geofeatures
263
- if(etaDestinationId && geofeatures.length){
263
+ if(tempoDestinationId && geofeatures.length){
264
264
  return !(geofeatures[0].type === 'geoline' || geofeatures[0].type === 'beacon')
265
265
  }
266
266
  return true
@@ -273,11 +273,11 @@ helpers.validateTriggerWebhooks = function(webhooks) {
273
273
  return !notTrigger
274
274
  }
275
275
 
276
- helpers.validateEtaWebhooks = function(webhooks) {
277
- const notEta = webhooks.some(webhook => {
278
- return webhook.type && webhook.type != 'eta'
276
+ helpers.validateTempoWebhooks = function(webhooks) {
277
+ const notTempo = webhooks.some(webhook => {
278
+ return webhook.type && webhook.type != 'tempo'
279
279
  })
280
- return !notEta
280
+ return !notTempo
281
281
  }
282
282
 
283
283
  module.exports = helpers
package/models/Project.js CHANGED
@@ -15,7 +15,7 @@ let IntegrationSchema = require('../schemas/Integration')
15
15
  let WebhookSchema = require('../schemas/Webhook')
16
16
  let iosConfig = require('../schemas/IosConfig')
17
17
  let androidConfig = require('../schemas/AndroidConfig')
18
- let projectEtaSchema = require('../schemas/ProjectEta')
18
+ let projectTempoSchema = require('../schemas/ProjectTempo')
19
19
 
20
20
  let webhooksValidators = [
21
21
  {validator: helpers.validateNotNull},
@@ -47,7 +47,7 @@ let ProjectSchema = new mongoose.Schema({
47
47
  firebaseApiKey: {type: String, validate: helpers.validateNotNull},
48
48
  apiKey: {type: String},
49
49
  integrations: IntegrationSchema,
50
- eta: projectEtaSchema
50
+ tempo: projectTempoSchema
51
51
  },
52
52
  {collection: 'project'})
53
53
 
package/models/Zone.js CHANGED
@@ -22,7 +22,7 @@ let travelDirectionRawSchema = require('./conditions/TravelDirection').rawSchema
22
22
  let travelPathRawSchema = require('./conditions/TravelPath').rawSchema
23
23
  let timeActiveRawSchema = require('./conditions/TimeActive').rawSchema
24
24
 
25
- let zoneEtaSchema = require('../schemas/ZoneEta')
25
+ let zoneTempoSchema = require('../schemas/ZoneTempo')
26
26
 
27
27
  let uuidv4 = require('uuid/v4')
28
28
  let patcher = require('@bluedot-innovation/mongoose-json-patch')
@@ -120,18 +120,18 @@ let zoneSchema = new Schema({
120
120
  projectId: {type: String, required: true, validate: {validator: helpers.validateUUIDv4, message: 'Invalid Project Id.'}},
121
121
  state: {type: String, default: StateEnum.ACTIVE, select: false},
122
122
  accountId: {type: String, required: true, validate: {isAsync: false, validator: helpers.validateUUIDv4, msg: 'default error message'}},
123
- eta: zoneEtaSchema
123
+ tempo: zoneTempoSchema
124
124
  }, {collection: 'zone', autoIndex: false})
125
125
 
126
126
  zoneSchema.index(
127
127
  {
128
128
  projectId: 1,
129
- 'eta.destinationId': 1
129
+ 'tempo.destinationId': 1
130
130
  },
131
131
  {
132
132
  unique: true,
133
- partialFilterExpression: { 'eta.destinationId': { $exists:true, $type:"string" } },
134
- name: "destinationUniqueWithinProject"
133
+ partialFilterExpression: { 'tempo.destinationId': { $exists:true, $type:"string" } },
134
+ name: "tempoDestinationUniqueWithinProject"
135
135
  })
136
136
 
137
137
  // Mongoose-json-patch
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bluedot-innovation/models",
3
- "version": "6.1.2",
3
+ "version": "6.2.0-alpha.1",
4
4
  "main": "Models.js",
5
5
  "scripts": {
6
6
  "lint": "./node_modules/.bin/eslint -c .eslintrc.js ./models/*.js ./__tests__/**/*.js ./__tests__/**/**/*.js ./schemas/*.js",
@@ -23,6 +23,7 @@
23
23
  "eslint-plugin-promise": "^3.6.0",
24
24
  "eslint-plugin-standard": "^3.0.1",
25
25
  "mocha": "^4.0.1",
26
+ "mongodb": "^3.5.8",
26
27
  "nyc": "^11.3.0",
27
28
  "prettier": "^1.13.5",
28
29
  "sinon": "^4.1.2"
@@ -36,7 +37,6 @@
36
37
  "deep-equal": "^1.0.1",
37
38
  "fast-deep-equal": "^2.0.1",
38
39
  "lodash.clonedeep": "4.5.0",
39
- "mongodb": "^3.5.7",
40
40
  "mongoose": "^5.7.13",
41
41
  "uuid": "^3.1.0"
42
42
  }
@@ -1,10 +1,10 @@
1
1
  let mongoose = require('mongoose')
2
- let AccountEtaSchema = require('./AccountEta')
2
+ let AccountTempoSchema = require('./AccountTempo')
3
3
 
4
4
  let AccountFeaturesSchema = new mongoose.Schema({
5
- eta: AccountEtaSchema
5
+ tempo: AccountTempoSchema
6
6
  }, {
7
7
  _id: false
8
8
  })
9
9
 
10
- module.exports = AccountFeaturesSchema
10
+ module.exports = AccountFeaturesSchema
@@ -1,9 +1,9 @@
1
1
  let mongoose = require('mongoose')
2
2
 
3
- let AccountEtaSchema = new mongoose.Schema({
3
+ let AccountTempoSchema = new mongoose.Schema({
4
4
  enabled: {type: Boolean}
5
5
  }, {
6
6
  _id: false
7
7
  })
8
8
 
9
- module.exports = AccountEtaSchema
9
+ module.exports = AccountTempoSchema
@@ -1,12 +1,13 @@
1
1
  let mongoose = require('mongoose')
2
- let validators = require('../utils/validators')
3
- let telemetrySchema = require('./Telemetry')
2
+ let TempoConfigSchema = require('./TempoConfig')
4
3
 
5
4
  let useCaseTypeEnum = {
6
5
  values: ['Default', 'Retail', 'Automotive'],
7
6
  message: 'enum validator failed for path `{PATH}` with value `{VALUE}`'
8
7
  }
9
8
 
9
+ // Further information here: https://bluedotinnovation.atlassian.net/wiki/spaces/ENG/pages/223150126/Remote+Config+details
10
+
10
11
  let AndroidSchema = new mongoose.Schema({
11
12
  triggeringOnWifiAccuracyThreshold: {type: Number, required: true},
12
13
  triggeringOnGpsAccuracyThreshold: {type: Number, required: true},
@@ -16,11 +17,14 @@ let AndroidSchema = new mongoose.Schema({
16
17
  beaconReevaluationDistance: {type: Number, required: true},
17
18
  beaconActivationCoefficient: {type: Number, required: true},
18
19
  beaconActivationDistance: {type: Number, required: true},
20
+ beaconDiscoveyCycleSecs: {type: Number, required: true, default: 20}, // The typo in `Discovey` is intentional to match the SDK
21
+ beaconCooloffCycleSecs: {type: Number, required: true, default: 10},
19
22
  filteringEnabled: {type: Boolean, default: false},
20
23
  applicationLoggingEnabled: {type: Boolean, default: false}, //Local logging on the device
21
24
  useCaseType : {type: String, enum: useCaseTypeEnum, default: "Default"},
22
25
  maximumPageSize: {type: Number},
23
- enableAlarmClock: {type: Boolean, default: false}
26
+ enableAlarmClock: {type: Boolean, default: false},
27
+ tempo: TempoConfigSchema
24
28
  }, {
25
29
  _id: false
26
30
  })
@@ -3,6 +3,7 @@ let validators = require('../utils/validators')
3
3
  let telemetrySchema = require('./Telemetry')
4
4
  let accuracySuppressionSchema = require('./AccuracySuppression')
5
5
  let starvationDetectionSchema = require('./StarvationDetection')
6
+ let TempoConfigSchema = require('./TempoConfig')
6
7
 
7
8
  let useCaseTypeEnum = {
8
9
  values: ['Default', 'Retail', 'Automotive'],
@@ -40,7 +41,8 @@ let IosSchema = new mongoose.Schema({
40
41
  starvationDetector: starvationDetectionSchema,
41
42
  triggerEngine: {type: String, enum: triggerEngineEnum, default: "BD"},
42
43
  disableBackgroundLocation: {type: String, enum: disableBackgroundLocationEnum, default: "None"},
43
- maximumPageSize: {type: Number}
44
+ maximumPageSize: {type: Number},
45
+ tempo: TempoConfigSchema
44
46
  }, {
45
47
  _id: false
46
48
  })
@@ -4,13 +4,13 @@ let helpers = require('../helpers')
4
4
 
5
5
  let webhooksValidators = [
6
6
  {validator: helpers.validateNotNull},
7
- {validator: helpers.validateEtaWebhooks, msg: 'eta.webhooks should contain eta webhooks only'}
7
+ {validator: helpers.validateTempoWebhooks, msg: 'tempo.webhooks should contain tempo webhooks only'}
8
8
  ];
9
9
 
10
- let ProjectEtaSchema = new mongoose.Schema({
10
+ let ProjectTempoSchema = new mongoose.Schema({
11
11
  webhooks: {type:[WebhookSchema], validate: webhooksValidators}
12
12
  }, {
13
13
  _id: false
14
14
  })
15
15
 
16
- module.exports = ProjectEtaSchema
16
+ module.exports = ProjectTempoSchema
@@ -0,0 +1,10 @@
1
+ const mongoose = require('mongoose');
2
+
3
+ let TempoConfigSchema = new mongoose.Schema({
4
+ tempoUpdateInterval: {type: Number, required: true, default: 30},
5
+ tempoTimeoutPeriod: {type: Number, required: true, default: 1800}
6
+ }, {
7
+ _id: false
8
+ })
9
+
10
+ module.exports = TempoConfigSchema
@@ -2,7 +2,7 @@ let mongoose = require('mongoose')
2
2
  let validators = require('../utils/validators')
3
3
 
4
4
  let WebhookSchema = new mongoose.Schema({
5
- type: {type: String, enum: ['trigger', 'eta'], required: [true, 'webhook type is required']}, // configurationChanged, trigger
5
+ type: {type: String, enum: ['trigger', 'tempo'], required: [true, 'webhook type is required']}, // configurationChanged, trigger
6
6
  url: {type: String, required: [true, 'URL is required'], validate: {isAsync: false, validator: validators.validateUrl, msg: 'Please enter a valid URL'}},
7
7
  headers: {type: mongoose.Schema.Types.Mixed, validate: { isAsync: false, validator: validateHeaderlength, msg: 'Header object can only have 1 key <-> value pair' }}
8
8
  }, {
@@ -0,0 +1,14 @@
1
+ let mongoose = require('mongoose')
2
+ let helpers = require('../helpers')
3
+
4
+ let ZoneTempoSchema = new mongoose.Schema({
5
+ destinationId: {type: String, validate: [
6
+ { validator: helpers.validateTempoDestinationIdLength, msg: 'destinationId must be less than 129 characters long' },
7
+ { validator: helpers.validateTempoDestinationSingleGeofeature, msg: 'destinationId can only be set on zones with a single geofeature' },
8
+ { validator: helpers.validateTempoDestinationIdGeofeatureType, msg: 'destinationId cannot be set on zones with a geoline or beacon' }
9
+ ]}
10
+ }, {
11
+ _id: false
12
+ })
13
+
14
+ module.exports = ZoneTempoSchema
@@ -0,0 +1,31 @@
1
+ const MongoClient = require('mongodb').MongoClient
2
+ const {createAllIndexesIfNotExists} = require("./indexInitialiser");
3
+ const {updateMobileConfigParametersProfiles} = require("./mobileConfigInitialiser");
4
+
5
+ const MONGO_DB_URI = process.env.MONGO_DB_URI
6
+ const DB_NAME = process.env.DB_NAME
7
+ const ENVIRONMENT = process.env.ENVIRONMENT
8
+ const client = new MongoClient(MONGO_DB_URI, { useUnifiedTopology: true })
9
+
10
+ console.log(`Using DB_NAME:${DB_NAME} in ENVIRONMENT:${ENVIRONMENT}`)
11
+
12
+ client.connect(async error => {
13
+ if(error){
14
+ console.log("Failed to connect to Mongo DB", error)
15
+ process.exit(1)
16
+ }
17
+ console.log("Connected to Mongo DB")
18
+
19
+ const db = client.db(DB_NAME)
20
+
21
+ try{
22
+ await createAllIndexesIfNotExists(db)
23
+ await updateMobileConfigParametersProfiles(db)
24
+ }catch(error){
25
+ console.log(error)
26
+ await client.close()
27
+ process.exit(1)
28
+ }
29
+
30
+ await client.close()
31
+ })
@@ -0,0 +1,58 @@
1
+ const deepEqual = require('deep-equal')
2
+
3
+ /*
4
+ This function identifies differences between a stored object and the saved values that should be applied
5
+ Allows you to identify what changes are being made when updating default values in the DB, for example for
6
+ androidConfig or iosConfig settings. Also warns of any fields present in the db that are not in the saved
7
+ default values as these should all be present.
8
+ */
9
+ const identifyDifferences = (objectToUpdate, defaultObject, path = "") => {
10
+ const fieldsToUpdate = [];
11
+ const fieldsToAdd = [];
12
+ const fieldsNotFoundInDefault = [];
13
+ Object.entries(objectToUpdate).forEach(([key, value]) => {
14
+ if(key === "_id"){
15
+ return
16
+ }
17
+ const newDefaultValue = defaultObject[key];
18
+ const newPath = path ? path + "." + key : key
19
+ if(newDefaultValue !== undefined){
20
+ if(newDefaultValue !== null && typeof newDefaultValue === 'object'){
21
+ if(Array.isArray(newDefaultValue)){
22
+ const previousArrayValue = objectToUpdate[key];
23
+ if(!deepEqual(newDefaultValue, previousArrayValue)){
24
+ fieldsToUpdate.push({key: newPath, value: newDefaultValue, previousValue: previousArrayValue});
25
+ }
26
+ }else{
27
+ const {
28
+ newFieldsToAdd,
29
+ existingFieldsToUpdate,
30
+ existingFieldsNotFoundInDefault
31
+ } = identifyDifferences(objectToUpdate[key], newDefaultValue, newPath)
32
+ fieldsToUpdate.push(...existingFieldsToUpdate);
33
+ fieldsToAdd.push(...newFieldsToAdd);
34
+ fieldsNotFoundInDefault.push(...existingFieldsNotFoundInDefault);
35
+ }
36
+ }else if(objectToUpdate[key] !== defaultObject[key]){
37
+ fieldsToUpdate.push({key: newPath, value: defaultObject[key], previousValue: objectToUpdate[key]});
38
+ }
39
+ }else{
40
+ fieldsNotFoundInDefault.push({key: newPath, value: objectToUpdate[key]});
41
+ }
42
+ });
43
+ Object.entries(defaultObject).forEach(([key, value]) => {
44
+ const newPath = path ? path + "." + key : key
45
+ if(objectToUpdate[key] === undefined){
46
+ fieldsToAdd.push({key: newPath, value})
47
+ }
48
+ });
49
+ return {
50
+ newFieldsToAdd: fieldsToAdd,
51
+ existingFieldsToUpdate: fieldsToUpdate,
52
+ existingFieldsNotFoundInDefault: fieldsNotFoundInDefault
53
+ }
54
+ }
55
+
56
+ module.exports = {
57
+ identifyDifferences
58
+ }
@@ -1,5 +1,3 @@
1
- const MongoClient = require('mongodb').MongoClient
2
-
3
1
  /*
4
2
  Add indexes here, rest of the code should not require updating
5
3
  For adding indexes to a new collection create a new array with key=collectionName
@@ -12,12 +10,12 @@ const indexes = {
12
10
  {
13
11
  fields: {
14
12
  projectId: 1,
15
- 'eta.destinationId': 1
13
+ 'tempo.destinationId': 1
16
14
  },
17
15
  options: {
18
16
  unique: true,
19
- partialFilterExpression: { 'eta.destinationId': { $exists:true, $type:"string" } },
20
- name: "destinationUniqueWithinProject"
17
+ partialFilterExpression: { 'tempo.destinationId': { $exists:true, $type:"string" } },
18
+ name: "tempoDestinationUniqueWithinProject"
21
19
  }
22
20
  }
23
21
  ]
@@ -71,28 +69,6 @@ const createAllIndexesIfNotExists = db => {
71
69
  })
72
70
  }
73
71
 
74
- const MONGO_DB_URI = process.env.MONGO_DB_URI
75
- const DB_NAME = process.env.DB_NAME
76
- const client = new MongoClient(MONGO_DB_URI, { useUnifiedTopology: true })
77
-
78
- console.log(`Using DB_NAME:${DB_NAME}`)
79
-
80
- client.connect(async error => {
81
- if(error){
82
- console.log("Failed to connect to Mongo DB", error)
83
- process.exit(1)
84
- }
85
- console.log("Connected to Mongo DB")
86
-
87
- const db = client.db(DB_NAME)
88
-
89
- try{
90
- await createAllIndexesIfNotExists(db)
91
- }catch(error){
92
- console.log(error)
93
- await client.close()
94
- process.exit(1)
95
- }
96
-
97
- await client.close()
98
- })
72
+ module.exports = {
73
+ createAllIndexesIfNotExists
74
+ }
@@ -0,0 +1,173 @@
1
+ const {identifyDifferences} = require("./helpers");
2
+
3
+ const defaultAndroidConfig = {
4
+ maximumPageSize: 256,
5
+ useCaseType: 'Default',
6
+ applicationLoggingEnabled: false,
7
+ filteringEnabled: false,
8
+ endpointUrl: 'https://www.pointapi.bluedot.com.au/pointapi-v1/',
9
+ beaconCooloffCycleSecs: 10,
10
+ beaconDiscoveyCycleSecs: 20, // Typo intentional to match typo in SDK
11
+ beaconActivationDistance: 30,
12
+ beaconActivationCoefficient: 0.5,
13
+ beaconReevaluationDistance: 25,
14
+ checkoutDistanceAccuracy: 50,
15
+ checkoutTimeAccuracy: 60,
16
+ trackingOnGpsAccuracyThreshold: 200,
17
+ triggeringOnGpsAccuracyThreshold: 20,
18
+ triggeringOnWifiAccuracyThreshold: 100,
19
+ enableAlarmClock: false,
20
+ tempo: {
21
+ tempoUpdateInterval: 30,
22
+ tempoTimeoutPeriod: 1800
23
+ }
24
+ };
25
+
26
+ const defaultIosConfig = {
27
+ useCaseType: 'Default',
28
+ triggerEngine: 'BD',
29
+ maximumPageSize: 256,
30
+ starvationDetector: {
31
+ starvationDetectorMinAllowedStarvationTimeInterval: 30,
32
+ starvationDetectorSecsAllowedPerMetre: 0.0225,
33
+ starvationDetectorEnabled: false
34
+ },
35
+ accuracySuppression: {
36
+ accuracySuppressionGracePeriod: 600,
37
+ accuracySuppressionMinAccuracyTimeInterval: 60,
38
+ accuracySuppressionMinAccuracy: 3000,
39
+ accuracySuppressionMaxAccuracyTimeInterval: 30,
40
+ accuracySuppressionMaxAccuracy: 5,
41
+ accuracySuppressionEnabled: false
42
+ },
43
+ applicationLoggingEnabled: false,
44
+ filteringEnabled: false,
45
+ endpointUrl: 'https://www.pointapi.bluedot.com.au/pointapi-v1/',
46
+ triggeringOnPollingLocationFarthestThreshold: 5000,
47
+ triggeringOnPollingLocationFurtherThreshold: 3000,
48
+ triggeringOnPollingLocationBasicThreshold: 1000,
49
+ focalDistanceAccuracyCoefficient: 0.9,
50
+ periodicPollingEnabled: true,
51
+ beaconActivationDistance: 30,
52
+ beaconActivationCoefficient: 0.5,
53
+ beaconReevaluationDistance: 10,
54
+ checkoutDistanceAccuracy: 50,
55
+ checkoutTimeAccuracy: 60,
56
+ trackingOnGpsAccuracyThreshold: 400,
57
+ triggeringOnGpsAccuracyThreshold: 30,
58
+ triggeringOnWifiAccuracyThreshold: 70,
59
+ tempo: {
60
+ tempoUpdateInterval: 30,
61
+ tempoTimeoutPeriod: 1800
62
+ },
63
+ accelerometerEnablementThreshold: 1000
64
+ }
65
+
66
+ const mobileConfigProfiles = {
67
+ default: {
68
+ name: 'default',
69
+ androidConfig: defaultAndroidConfig,
70
+ iosConfig: defaultIosConfig
71
+ },
72
+ retail: {
73
+ name: 'retail',
74
+ androidConfig: {
75
+ ...defaultAndroidConfig,
76
+ useCaseType: `Retail`
77
+ },
78
+ iosConfig: {
79
+ ...defaultIosConfig,
80
+ useCaseType: `Retail`,
81
+ triggerEngine: `Hybrid`,
82
+ trackingOnGpsAccuracyThreshold: 200,
83
+ //accelerometerEnablementThreshold: undefined //TODO: Check this
84
+ }
85
+ },
86
+ automotive: {
87
+ name: 'automotive',
88
+ androidConfig: {
89
+ ...defaultAndroidConfig,
90
+ useCaseType: "Automotive",
91
+ maximumPageSize: 512,
92
+ trackingOnGpsAccuracyThreshold: 1111
93
+ },
94
+ iosConfig: {
95
+ ...defaultIosConfig,
96
+ useCaseType: 'Automotive',
97
+ maximumPageSize: 512,
98
+ triggeringOnPollingLocationFarthestThreshold: 120000,
99
+ triggeringOnPollingLocationFurtherThreshold: 110000,
100
+ triggeringOnPollingLocationBasicThreshold: 99000,
101
+ periodicPollingEnabled: false,
102
+ trackingOnGpsAccuracyThreshold: 3000,
103
+ //accelerometerEnablementThreshold: undefined //TODO: Check this
104
+ }
105
+ }
106
+ }
107
+
108
+ const updateConfigParams = async (configurationParametersCollection, profileToUpdate, existingProfile) => {
109
+ console.log(`Checking profile: ${profileToUpdate.name}`)
110
+ const {newFieldsToAdd, existingFieldsToUpdate, existingFieldsNotFoundInDefault} = identifyDifferences(existingProfile, profileToUpdate)
111
+ if(existingFieldsToUpdate.length){
112
+ console.log(`Fields to update: ${JSON.stringify(existingFieldsToUpdate)}`)
113
+ }
114
+ if(newFieldsToAdd.length){
115
+ console.log(`Fields to add: ${JSON.stringify(newFieldsToAdd)}`)
116
+ }
117
+ // Any values present in the DB but not found in this profile will not be overwritten but should be added
118
+ // to the profile to ensure they are kept common across all environments
119
+ if(existingFieldsNotFoundInDefault.length){
120
+ console.log(`Fields not found in default: ${JSON.stringify(existingFieldsNotFoundInDefault)}`)
121
+ }
122
+ if(existingFieldsToUpdate.length || newFieldsToAdd.length){
123
+ console.log(`Need to update: ${profileToUpdate.name}`)
124
+ const setModifications = {};
125
+ existingFieldsToUpdate.forEach(({key, value}) => {
126
+ setModifications[key] = value
127
+ })
128
+ newFieldsToAdd.forEach(({key, value}) => {
129
+ setModifications[key] = value
130
+ })
131
+ const updateModifications = {
132
+ $set: setModifications
133
+ }
134
+ console.log(`Update query: ${JSON.stringify(updateModifications)}`)
135
+ await configurationParametersCollection.updateOne({name: profileToUpdate.name}, updateModifications)
136
+ console.log(`Profile ${profileToUpdate.name} has been updated`)
137
+ }else{
138
+ console.log(`Profile ${profileToUpdate.name} already matches saved settings`)
139
+ }
140
+ }
141
+
142
+ const createConfigParams = async (configurationParametersCollection, profileToCreate) => {
143
+ console.log(`Need to create: ${profileToCreate.name}`)
144
+ await configurationParametersCollection.insertOne(profileToCreate)
145
+ console.log(`Profile ${profileToCreate.name} created`)
146
+ }
147
+
148
+ const updateMobileConfigParametersProfiles = db => {
149
+ const configCollection = db.collection('configurationParameters');
150
+ const updateConfigPromises = Object.values(mobileConfigProfiles).map(async useCaseSettings => {
151
+ const foundProfile = await configCollection.find({name: useCaseSettings.name}).toArray()
152
+ if(foundProfile.length === 0){
153
+ return createConfigParams(configCollection, useCaseSettings)
154
+ }else if(foundProfile.length === 1){
155
+ return updateConfigParams(configCollection, useCaseSettings, foundProfile[0])
156
+ }else{
157
+ throw new Error(`Multiple configuration profiles (${foundProfile.length}) found with target name: ${useCaseSettings.name}`)
158
+ }
159
+ })
160
+
161
+ // We want to execute all profile update promises, then if there are any errors throw an error
162
+ return Promise.allSettled(updateConfigPromises).then(results => {
163
+ const hasErrors = results.find(result => result.status === "rejected")
164
+ if(hasErrors){
165
+ throw new Error("An error occurred updating mobile config profiles")
166
+ }
167
+ })
168
+ }
169
+
170
+ module.exports = {
171
+ mobileConfigProfiles,
172
+ updateMobileConfigParametersProfiles
173
+ }
@@ -1,14 +0,0 @@
1
- let mongoose = require('mongoose')
2
- let helpers = require('../helpers')
3
-
4
- let ZoneEtaSchema = new mongoose.Schema({
5
- destinationId: {type: String, validate: [
6
- { validator: helpers.validateEtaDestinationIdLength, msg: 'destinationId must be less than 129 characters long' },
7
- { validator: helpers.validateEtaDestinationSingleGeofeature, msg: 'destinationId can only be set on zones with a single geofeature' },
8
- { validator: helpers.validateEtaDestinationIdGeofeatureType, msg: 'destinationId cannot be set on zones with a geoline or beacon' }
9
- ]}
10
- }, {
11
- _id: false
12
- })
13
-
14
- module.exports = ZoneEtaSchema