@bluedot-innovation/models 4.0.0 → 5.0.0

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.
Files changed (160) hide show
  1. package/.eslintrc.js +42 -0
  2. package/.gitlab-ci.yml +43 -0
  3. package/CHANGELOG.md +156 -0
  4. package/Models.js +55 -10
  5. package/README.MD +36 -0
  6. package/__tests__/account/account.data.json +12 -0
  7. package/__tests__/account/account.rules.js +8 -0
  8. package/__tests__/account/account.spec.js +83 -0
  9. package/__tests__/action/message/messageAction.data.json +5 -0
  10. package/__tests__/action/message/messageAction.rules.json +3 -0
  11. package/__tests__/action/message/messageAction.spec.js +61 -0
  12. package/__tests__/action/url/urlAction.data.json +4 -0
  13. package/__tests__/action/url/urlAction.rules.json +3 -0
  14. package/__tests__/action/url/urlAction.spec.js +74 -0
  15. package/__tests__/beacon/beacon.data.json +15 -0
  16. package/__tests__/beacon/beacon.rules.json +13 -0
  17. package/__tests__/beacon/beacon.spec.js +104 -0
  18. package/__tests__/condition/beacon/beaconFilter.data.json +1 -0
  19. package/__tests__/condition/beacon/beaconFilter.rules.json +3 -0
  20. package/__tests__/condition/beacon/beaconFilter.spec.js +1 -0
  21. package/__tests__/condition/dayRange/dayRange.data.json +5 -0
  22. package/__tests__/condition/dayRange/dayRange.rules.json +3 -0
  23. package/__tests__/condition/dayRange/dayRange.spec.js +74 -0
  24. package/__tests__/condition/percentageCrossed/travelPath.data.json +5 -0
  25. package/__tests__/condition/percentageCrossed/travelPath.rules.json +3 -0
  26. package/__tests__/condition/percentageCrossed/travelPath.spec.js +62 -0
  27. package/__tests__/condition/speed/speed.data.json +5 -0
  28. package/__tests__/condition/speed/speed.rules.json +3 -0
  29. package/__tests__/condition/speed/speed.spec.js +73 -0
  30. package/__tests__/condition/timeActive/timeActive.data.json +5 -0
  31. package/__tests__/condition/timeActive/timeActive.rules.json +7 -0
  32. package/__tests__/condition/timeActive/timeActive.spec.js +94 -0
  33. package/__tests__/condition/travelDirection/travelDirection.data.json +5 -0
  34. package/__tests__/condition/travelDirection/travelDirection.rules.json +3 -0
  35. package/__tests__/condition/travelDirection/travelDirection.spec.js +132 -0
  36. package/__tests__/dailyStats/checkDailyStats.js +31 -0
  37. package/__tests__/geofeature/boundingBox/boundingBox.data.json +12 -0
  38. package/__tests__/geofeature/boundingBox/boundingBox.rules.json +3 -0
  39. package/__tests__/geofeature/boundingBox/boundingBox.spec.js +78 -0
  40. package/__tests__/geofeature/circle/circle.data.json +9 -0
  41. package/__tests__/geofeature/circle/circle.rules.json +3 -0
  42. package/__tests__/geofeature/circle/circle.spec.js +71 -0
  43. package/__tests__/geofeature/geoline/geoline.data.json +46 -0
  44. package/__tests__/geofeature/geoline/geoline.rules.json +3 -0
  45. package/__tests__/geofeature/geoline/geoline.spec.js +70 -0
  46. package/__tests__/geofeature/polygon/polygon.data.json +46 -0
  47. package/__tests__/geofeature/polygon/polygon.rules.json +3 -0
  48. package/__tests__/geofeature/polygon/polygon.spec.js +127 -0
  49. package/__tests__/geofeature/zoneBeacon/zoneBeacon.data.json +16 -0
  50. package/__tests__/geofeature/zoneBeacon/zoneBeacon.rules.json +13 -0
  51. package/__tests__/geofeature/zoneBeacon/zoneBeacon.spec.js +62 -0
  52. package/__tests__/monthlyStats/monthlyStats.data.json +29 -0
  53. package/__tests__/monthlyStats/monthlyStats.spec.js +66 -0
  54. package/__tests__/project/project.data.json +18 -0
  55. package/__tests__/project/project.rules.json +9 -0
  56. package/__tests__/project/project.spec.js +92 -0
  57. package/__tests__/ruleRequestAggregation/ruleRequestAggregation.data.json +8 -0
  58. package/__tests__/ruleRequestAggregation/ruleRequestAggregation.spec.js +69 -0
  59. package/__tests__/setup.js +7 -0
  60. package/__tests__/user/user.data.js +19 -0
  61. package/__tests__/user/user.rules.js +8 -0
  62. package/__tests__/user/user.spec.js +130 -0
  63. package/__tests__/utils/utils.spec.js +24 -0
  64. package/__tests__/zone/zone.action.spec.js +50 -0
  65. package/__tests__/zone/zone.condition.spec.js +94 -0
  66. package/__tests__/zone/zone.data.json +157 -0
  67. package/__tests__/zone/zone.geofeatures.spec.js +75 -0
  68. package/__tests__/zone/zone.spec.js +134 -0
  69. package/constants/errorMessages.js +2 -0
  70. package/helpers.js +117 -0
  71. package/models/Account.js +50 -0
  72. package/models/AdminPortalUser.js +10 -11
  73. package/models/Beacon.js +84 -32
  74. package/models/Contract.js +37 -38
  75. package/models/CustomerLogin.js +9 -10
  76. package/models/DBEvent.js +13 -14
  77. package/models/DailyStats.js +7 -7
  78. package/models/DeviceRulesRequest.js +27 -28
  79. package/models/MessageAction.js +28 -26
  80. package/models/MonthlyStats.js +35 -19
  81. package/models/NotificationLogEntry.js +7 -8
  82. package/models/POILocation.js +6 -7
  83. package/models/POILookup.js +8 -9
  84. package/models/POIResult.js +7 -8
  85. package/models/PartnerCustomer.js +12 -13
  86. package/models/PartnerPasswordReset.js +8 -9
  87. package/models/PartnerUser.js +10 -11
  88. package/models/Partners.js +11 -12
  89. package/models/Project.js +55 -0
  90. package/models/RuleRequestAggregation.js +33 -17
  91. package/models/SingleUseToken.js +7 -8
  92. package/models/TestDevice.js +11 -12
  93. package/models/TestDeviceCluster.js +9 -10
  94. package/models/TestInstance.js +9 -10
  95. package/models/TestScenario.js +9 -10
  96. package/models/TimeOfDayRange.js +16 -16
  97. package/models/UrlAction.js +46 -0
  98. package/models/User.js +61 -0
  99. package/models/Zone.js +126 -0
  100. package/models/ZoneUIState.js +18 -18
  101. package/models/conditions/DayRange.js +52 -0
  102. package/models/conditions/Speed.js +42 -0
  103. package/models/conditions/TimeActive.js +50 -0
  104. package/models/conditions/TravelDirection.js +67 -0
  105. package/models/conditions/TravelPath.js +36 -0
  106. package/models/geofeatures/BoundingBox.js +44 -0
  107. package/models/geofeatures/Circle.js +39 -0
  108. package/models/geofeatures/Geoline.js +34 -0
  109. package/models/geofeatures/Polygon.js +45 -0
  110. package/models/geofeatures/ZoneBeacon.js +28 -0
  111. package/package.json +30 -6
  112. package/schemas/MultiLineStringGeometry.js +14 -0
  113. package/schemas/Point.js +13 -0
  114. package/schemas/PointGeometry.js +14 -0
  115. package/schemas/PolygonGeometry.js +14 -0
  116. package/schemas/ProjectPermission.js +21 -0
  117. package/schemas/Webhook.js +27 -0
  118. package/utils/index.js +39 -0
  119. package/validators/checkDistanceBetweenVertices.js +21 -0
  120. package/yarn.lock +2796 -0
  121. package/models/AdminUser.js +0 -10
  122. package/models/Application.js +0 -38
  123. package/models/ApplicationNotificationAction.js +0 -30
  124. package/models/ApplicationUsage.js +0 -11
  125. package/models/BeaconFilter.js +0 -23
  126. package/models/BearingFilter.js +0 -19
  127. package/models/BoundingBox.js +0 -17
  128. package/models/Circle.js +0 -21
  129. package/models/ConfigurationParameters.js +0 -20
  130. package/models/Customer.js +0 -38
  131. package/models/DateRangeFilter.js +0 -20
  132. package/models/Fence.js +0 -21
  133. package/models/FormattedBeacon.js +0 -16
  134. package/models/FormattedCircle.js +0 -12
  135. package/models/FormattedConditions.js +0 -11
  136. package/models/FormattedDateRange.js +0 -11
  137. package/models/FormattedPercentageCrossed.js +0 -12
  138. package/models/FormattedPoint.js +0 -10
  139. package/models/FormattedPolygon.js +0 -11
  140. package/models/FormattedPolyline.js +0 -11
  141. package/models/FormattedRectangle.js +0 -12
  142. package/models/FormattedTimeActive.js +0 -17
  143. package/models/FormattedZone.js +0 -28
  144. package/models/GeoFence.js +0 -23
  145. package/models/Geofeature.js +0 -26
  146. package/models/PercentageCrossedFilter.js +0 -19
  147. package/models/Point.js +0 -20
  148. package/models/Polygon.js +0 -18
  149. package/models/Polyline.js +0 -18
  150. package/models/PropertyMapping.js +0 -17
  151. package/models/Reference.js +0 -19
  152. package/models/SequenceFilter.js +0 -18
  153. package/models/SimpleCheckInZone.js +0 -29
  154. package/models/SoundAction.js +0 -28
  155. package/models/SpeedFilter.js +0 -19
  156. package/models/TimeOfDayRangeFilter.js +0 -19
  157. package/models/URLAction.js +0 -31
  158. package/models/VibrationAction.js +0 -28
  159. package/models/property.js +0 -25
  160. package/package-lock.json.bak +0 -170
@@ -0,0 +1,75 @@
1
+ let mongoose = require('mongoose')
2
+
3
+ mongoose.Promise = global.Promise
4
+
5
+ let ZoneModel = require('../../Models').Zone(mongoose)
6
+ let testCase = require('mocha').describe
7
+ let assertions = require('mocha').it
8
+ let chai = require('chai')
9
+ let assert = chai.assert
10
+ let mocha = require('mocha')
11
+ let beforeEach = mocha.beforeEach
12
+
13
+ let zone
14
+
15
+ beforeEach(() => {
16
+ zone = JSON.parse(JSON.stringify(require('./zone.data.json')))
17
+ // remove conditions as it's not tested
18
+ delete zone.conditions
19
+
20
+ // geofeatures are tested individually so we only need to try one in Zones' test
21
+ zone.geofeatures = zone.geofeatures.filter(x => x.type.match(/beacon/i))
22
+
23
+ // remove customData
24
+ delete zone.customData
25
+
26
+ // remove actions
27
+ delete zone.actions
28
+ })
29
+
30
+ testCase('Zone - Action', () => {
31
+ testCase('Valid Zone - Action', () => {
32
+ assertions('should not throw an error when a valid geofeature is instantiated within a zone', (done) => {
33
+ let Zone = new ZoneModel(zone)
34
+ Zone.validate((err, res) => {
35
+ console.log(err)
36
+ assert.notExists(res)
37
+ assert(err === null, 'err should be null')
38
+ done()
39
+ })
40
+ })
41
+ })
42
+
43
+ testCase('Invalid Zone - Action', () => {
44
+ assertions('should throw an error when an invalid geofeature is instantiated within a zone', (done) => {
45
+ delete zone.geofeatures[0].name
46
+ let Zone = new ZoneModel(zone)
47
+ Zone.validate((err, res) => {
48
+ assert.exists(err, 'err object should exist')
49
+ assert.isObject(err)
50
+ assert('geofeatures.0.name' in err.errors)
51
+ done()
52
+ })
53
+ })
54
+ assertions('should throw an error when an invalid geofeature (complex validation) is instantiated within a zone', (done) => {
55
+ delete zone.geofeatures[0].minor
56
+ let Zone = new ZoneModel(zone)
57
+ Zone.validate((err, res) => {
58
+ assert.exists(err, 'err object should exist')
59
+ assert.isObject(err)
60
+ assert('geofeatures.0.beaconType' in err.errors)
61
+ done()
62
+ })
63
+ })
64
+ assertions('should throw an error when an no geofeature is instantiated within a zone', (done) => {
65
+ zone.geofeatures = []
66
+ let Zone = new ZoneModel(zone)
67
+ Zone.validate((err, res) => {
68
+ assert.exists(err, 'err object should exist')
69
+ assert.isObject(err)
70
+ assert('geofeatures' in err.errors)
71
+ done()
72
+ })
73
+ })
74
+ })
75
+ })
@@ -0,0 +1,134 @@
1
+ let ZoneModel = require('../../Models').Zone(mongoose)
2
+ let ZoneModelBuiltInMongoose = require('../../Models').Zone()
3
+
4
+ let zone
5
+
6
+ beforeEach(() => {
7
+ zone = JSON.parse(JSON.stringify(require('./zone.data.json')))
8
+ })
9
+
10
+ describe('Zone', () => {
11
+ describe('Valid Zone ', () => {
12
+ it('should validate a valid zone ', (done) => {
13
+ let Zone = new ZoneModel(zone)
14
+ Zone.validate((err, res) => {
15
+ assert.notExists(res)
16
+ assert(err === null, 'err equals null')
17
+ done()
18
+ })
19
+ })
20
+
21
+ it('should validate a valid zone ', (done) => {
22
+ let Zone = new ZoneModelBuiltInMongoose(zone)
23
+ Zone.validate((err, res) => {
24
+ assert.notExists(res)
25
+ assert(err === null, 'err equals null')
26
+ done()
27
+ })
28
+ })
29
+
30
+ it('should instantiate a circle', (done) => {
31
+ zone.geofeatures = zone.geofeatures.filter(gf => gf.type.match(/^circle$/))
32
+ let Zone = new ZoneModel(zone)
33
+ Zone.validate((err, res) => {
34
+ assert.notExists(res)
35
+ assert(err === null, 'err equals null')
36
+ done()
37
+ })
38
+ })
39
+
40
+ it('should instantiate a bounding box', (done) => {
41
+ zone.geofeatures = zone.geofeatures.filter(gf => gf.type.match(/^boundingBox$/))
42
+ let Zone = new ZoneModel(zone)
43
+ Zone.validate((err, res) => {
44
+ assert.notExists(res)
45
+ assert(err === null, 'err equals null')
46
+ done()
47
+ })
48
+ })
49
+
50
+ it('should instantiate a polygon', (done) => {
51
+ zone.geofeatures = zone.geofeatures.filter(gf => gf.type.match(/^polygon$/))
52
+ let Zone = new ZoneModel(zone)
53
+ Zone.validate((err, res) => {
54
+ assert.notExists(res)
55
+ assert(err === null, 'err equals null')
56
+ done()
57
+ })
58
+ })
59
+
60
+ it('should instantiate a geoline', (done) => {
61
+ zone.geofeatures = zone.geofeatures.filter(gf => gf.type.match(/^geoline$/))
62
+ let Zone = new ZoneModel(zone)
63
+ Zone.validate((err, res) => {
64
+ assert.notExists(res)
65
+ assert(err === null, 'err equals null')
66
+ done()
67
+ })
68
+ })
69
+ })
70
+
71
+ describe('Invalid Zone ', () => {
72
+ it('should throw an error when validating an invalid zone ', (done) => {
73
+ delete zone.name
74
+ let Zone = new ZoneModel(zone)
75
+ Zone.validate((err, res) => {
76
+ assert.exists(err, 'err object should exist')
77
+ assert.isObject(err)
78
+ done()
79
+ })
80
+ })
81
+
82
+ it('should throw an error when action is invalid', (done) => {
83
+ delete zone.actions[1].url
84
+ let Zone = new ZoneModel(zone)
85
+ Zone.validate((err, res) => {
86
+ assert.exists(err, 'err object should exist')
87
+ assert.isObject(err)
88
+ assert('actions.1.url' in err.errors, `errors should have a 'actions.1.url' property`)
89
+ done()
90
+ })
91
+ })
92
+
93
+ it('should throw an error when a condition is invalid', (done) => {
94
+ zone.conditions[0].startDate = 'abc'
95
+ let Zone = new ZoneModel(zone)
96
+ Zone.validate((err, res) => {
97
+ assert.exists(err, 'err object should exist')
98
+ assert.isObject(err)
99
+ assert('conditions.0.startDate' in err.errors, `errors should have a 'conditions.0.startDate' property`)
100
+ done()
101
+ })
102
+ })
103
+
104
+ it('should throw an error when validating an invalid customData key ', (done) => {
105
+ zone.customData["name#3"] = "A Custom action3"
106
+ let Zone = new ZoneModel(zone)
107
+ Zone.validate((err, res) => {
108
+ assert.exists(err, 'err object should exist')
109
+ assert.isObject(err)
110
+ done()
111
+ })
112
+ })
113
+
114
+ it('should throw an error when it contains both a beacon and a travelDirection condition', (done) => {
115
+ zone.conditions.push(require('../condition/travelDirection/travelDirection.data.json'));
116
+ let Zone = new ZoneModel(zone)
117
+ Zone.validate((err, res) => {
118
+ assert.exists(err, 'err object should exist')
119
+ assert(err instanceof Error, "Should throw error.")
120
+ done()
121
+ })
122
+ })
123
+
124
+ it('should throw an error when it contains both a beacon and a speed condition', (done) => {
125
+ zone.conditions.push(require('../condition/speed/speed.data.json'));
126
+ let Zone = new ZoneModel(zone)
127
+ Zone.validate((err, res) => {
128
+ assert.exists(err, 'err object should exist')
129
+ assert(err instanceof Error, "Should throw error.")
130
+ done()
131
+ })
132
+ })
133
+ })
134
+ })
@@ -0,0 +1,2 @@
1
+ exports.VERTICES_TOO_CLOSE = 'For any given vertex, the next 2 vertices cannot be too close to it.'
2
+ exports.CANT_HAVE_THREE_OR_MORE_VERTICES = 'A polygon must have 3 or more vertices.'
package/helpers.js ADDED
@@ -0,0 +1,117 @@
1
+ var equal = require('deep-equal');
2
+ const { clean } = require('./utils');
3
+
4
+ let helpers = {}
5
+
6
+ helpers.validateUUIDv4 = function (id) {
7
+ const expression = '^[0-9A-F]{8}-[0-9A-F]{4}-4[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$'
8
+ const regex = new RegExp(expression, 'i')
9
+ return regex.test(id)
10
+ }
11
+
12
+ helpers.validateEmail = function (value) {
13
+ const regex = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
14
+ return regex.test(value);
15
+ }
16
+
17
+ helpers.threeOrMoreVertices = function(vertices) {
18
+ return vertices.length >= 3;
19
+ }
20
+
21
+ helpers.validateCustomData = function (data) {
22
+ const customDataKeys = Object.keys(data)
23
+ let hasValidationErrors = false
24
+
25
+ customDataKeys.forEach(key => {
26
+ const alphaNumericValidation = new RegExp(/^[\w\s]+$/)
27
+ if(!alphaNumericValidation.test(key)){
28
+ hasValidationErrors = true
29
+ }
30
+ })
31
+
32
+ const checkDuplicateKeys = [...new Set(customDataKeys)]
33
+ if(customDataKeys.length > checkDuplicateKeys.length) {
34
+ hasValidationErrors = true
35
+ }
36
+
37
+ return !hasValidationErrors
38
+ }
39
+
40
+ helpers.checkDuplicateKeys = function (data) {
41
+ const customDataKeys = Object.keys(data)
42
+ let hasValidationErrors = false
43
+
44
+ const duplicateKeys = [...new Set(customDataKeys)]
45
+ if(customDataKeys.length > duplicateKeys.length) {
46
+ hasValidationErrors = true
47
+ }
48
+
49
+ return !hasValidationErrors
50
+ }
51
+
52
+ helpers.checkIsDifferent = function(propertyName) {
53
+ return function(propertyA) {
54
+ const propertyB = this[propertyName];
55
+
56
+ if (equal(clean(propertyA), clean(propertyB))) {
57
+ return false;
58
+ }
59
+
60
+ return true
61
+ }
62
+ }
63
+
64
+ helpers.checkConditionsSuitableForBeacon = function(zone, next) {
65
+ let hasBeacons = false;
66
+ if( zone.geofeatures && zone.geofeatures.length ) {
67
+ for( let geofeature of zone.geofeatures ) {
68
+ if( geofeature.type === "beacon" ) {
69
+ hasBeacons = true;
70
+ break;
71
+ }
72
+ }
73
+ }
74
+ if( !hasBeacons )
75
+ return next(); // No beacons.
76
+ if( !zone.conditions || !zone.conditions.length )
77
+ return next(); // No conditions.
78
+ for( let condition of zone.conditions ) {
79
+ if( condition.type === "travelDirection" ) {
80
+ return next(new Error("Zone cannot both contain a beacon and have a Travel Direction condition."))
81
+ }
82
+ if( condition.type === "speed" ) {
83
+ return next(new Error("Zone cannot both contain a beacon and have a Speed condition."))
84
+ }
85
+ }
86
+ next();
87
+ }
88
+
89
+ helpers.checkMinimumGeofeaturesValidForZone = function(zone, next) {
90
+ if( !zone.geofeatures )
91
+ return next();
92
+ if( !zone.conditions || !zone.conditions.length )
93
+ return next(); // No conditions.
94
+ for( let condition of zone.conditions ) {
95
+ if( condition.type === "travelPath" && condition.minimumGeofeaturesCrossed > zone.geofeatures.length ) {
96
+ return next(new Error("Zone must not have minimumGeofeaturesCrossed higher than geofeatures count"))
97
+ }
98
+ }
99
+ next();
100
+ }
101
+
102
+ helpers.validateTravelPathConditionCount = function(zone, next) {
103
+ if( !zone.conditions )
104
+ return next();
105
+ if( !zone.conditions || !zone.conditions.length )
106
+ return next(); // No conditions.
107
+
108
+ let numberOfTravelPathConditions = 0
109
+
110
+ for( let condition of zone.conditions ) {
111
+ if( condition.type === "travelPath" ) numberOfTravelPathConditions ++
112
+ if ( numberOfTravelPathConditions > 1 ) return next(new Error("Zone must not have more than 1 travel path condition"))
113
+ }
114
+ next();
115
+ }
116
+
117
+ module.exports = helpers
@@ -0,0 +1,50 @@
1
+ /**
2
+ * Created by Richard Tan on 27/02/18.
3
+ * Copyright : Bluedot Innovation.
4
+ */
5
+
6
+ let mongoose = require('mongoose')
7
+ // let Schema = mongoose.Schema
8
+ let StateEnum = require('@bluedot-innovation/enums').StateEnum
9
+ let uuidv4 = require('uuid/v4')
10
+ let patcher = require('mongoose-json-patch')
11
+ const helpers = require('../helpers')
12
+
13
+ let AccountSchema = new mongoose.Schema({
14
+ _id: {type: String, default: uuidv4},
15
+ customerApiKey: {type: String, default: uuidv4}, // Backwards compatability
16
+ name: {type: String, required: true},
17
+ createdBy: {
18
+ // type: Schema.Types.ObjectId,
19
+ type: String,
20
+ validator: helpers.validateUUIDv4,
21
+ required: true,
22
+ // Adding a default to allow the lambdas to pass until we know who
23
+ // the createdBy will be.
24
+ default: uuidv4
25
+ },
26
+ state: {type: String, default: StateEnum.active},
27
+ poiCredits: Number,
28
+ integrations: Object,
29
+ features: Object,
30
+ creationTime: {type: Date, default: Date.now},
31
+ lastUpdateTime: {type: Date, default: Date.now}
32
+ },
33
+ {collection: 'account'})
34
+
35
+ AccountSchema.plugin(patcher)
36
+
37
+ // optional mongoose
38
+ let model = (mongooseInstance) => {
39
+ let Account
40
+ if (mongooseInstance) {
41
+ Account = mongooseInstance.model('Account', AccountSchema)
42
+ } else {
43
+ Account = mongoose.model('Account', AccountSchema)
44
+ }
45
+
46
+ return Account
47
+ }
48
+
49
+ // Exports Mongoose Model, Mongoose Schema, JSON schema (required locally for discriminators)
50
+ module.exports = { Model: model, Schema: AccountSchema }
@@ -2,25 +2,24 @@
2
2
  * Copyright : Bluedot Innovations.
3
3
  */
4
4
 
5
- var mongoose = require('mongoose');
6
- var Enums = require('@bluedot-innovation/enums');
5
+ let mongoose = require('mongoose')
6
+ let Enums = require('@bluedot-innovation/enums')
7
7
 
8
- var AdminPortalUser = mongoose.model('AdminPortalUser', new mongoose.Schema(
8
+ let AdminPortalUser = mongoose.model('AdminPortalUser', new mongoose.Schema(
9
9
  {
10
10
  emailAddress: String,
11
11
  password: String,
12
12
  firstName: String,
13
13
  lastName: String,
14
- state: {type:String, default: Enums.StateEnum.active},
15
- "creationTime" : {type: Date, default: Date.now},
16
- "dataSource" : {type:String, select: false, default : 'AdminPortal'},
14
+ state: {type: String, default: Enums.StateEnum.active},
15
+ 'creationTime': {type: Date, default: Date.now},
16
+ 'dataSource': {type: String, select: false, default: 'AdminPortal'},
17
17
  adminId: String,
18
18
  secret: String
19
19
  },
20
20
  {
21
- collection : 'adminPortalUser'
22
- }
23
- )
24
- );
21
+ collection: 'adminPortalUser'
22
+ })
23
+ )
25
24
 
26
- module.exports = AdminPortalUser;
25
+ module.exports = AdminPortalUser
package/models/Beacon.js CHANGED
@@ -1,36 +1,88 @@
1
- /**
2
- * Created by Arun on 10/09/2014.
3
- * Copyright : Bluedot Innovations.
4
- * Owner :
5
- */
6
- var mongoose = require('mongoose');
7
- var StateEnum = require('@bluedot-innovation/enums').StateEnum;
8
-
9
- Schema = mongoose.Schema;
10
- var BeaconSchema = new mongoose.Schema({
11
- "_id" : {type: String},
12
- "creationTime" : {type: Date, default: Date.now},
13
- "lastUpdateTime" : {type: Date, default: Date.now},
14
- "state": {type: String, default: StateEnum.active},
15
- "range": Number,
16
- "major": Number,
17
- "minor": Number,
18
- "description": String,
19
- "txPower": Number,
20
- "name": String,
21
- "macAddress": String,
22
- "proximityUUID": String,
23
- "customerId": String,
24
- "beaconType": String,
25
- "altitude": Number,
26
- "altitudeAccuracy": Number,
27
- "dataSource" : {type:String, select: false, default : 'openApi'},
28
- "geometry" : {type: Schema.Types.Mixed, default: {}}
1
+ const { BeaconEnum, StateEnum } = require('@bluedot-innovation/enums')
2
+ const PointGeometry = require('../schemas/PointGeometry')
3
+ const patcher = require('mongoose-json-patch')
4
+ const Point = require('../schemas/Point')
5
+ const mongoose = require('mongoose')
6
+ const uuidv4 = require('uuid/v4')
7
+
8
+ let schema = {
9
+ _id: {type: String, default: uuidv4},
10
+ name: {type: String, required: [true, 'name is required.']},
11
+ description: {type: String, default: ''},
12
+ creationTime: {type: Date, default: Date.now},
13
+ lastUpdateTime: {type: Date, default: Date.now},
14
+ state: {type: String, default: StateEnum.active},
15
+ beaconType: {
16
+ type: String,
17
+ required: true,
18
+ enum: [BeaconEnum.IOS, BeaconEnum.ANDROID, BeaconEnum.BOTH],
19
+ validate: {
20
+ isAsync: true,
21
+ validator: validateBeaconType,
22
+ msg: 'Async validation. Not used'
23
+ }
29
24
  },
30
- { collection : 'beacon' }
31
- );
25
+ location: {type: Point, required: true},
26
+ geometry: {type: PointGeometry},
27
+ accountId: {type: String, required: true},
28
+ // These must be unique
29
+ major: {type: Number, validate: [{validator: validateMajorMinor, msg: 'Major needs to be within range(0-65535)'}]},
30
+ minor: {type: Number, validate: [{validator: validateMajorMinor, msg: 'Minor needs to be within range(0-65535)'}]},
31
+ txPower: {type: Number},
32
+ macAddress: {type: String},
33
+ proximityUUID: {type: String}
34
+ }
35
+
36
+ let BeaconSchema = new mongoose.Schema(schema, {collection: 'beacon', autoIndex: false})
37
+
38
+ BeaconSchema.index({ macAddress: 1 })
39
+ BeaconSchema.index({ proximityUUID: 1, major: 1, minor: 1 })
40
+ BeaconSchema.index({ accountId: 1, geometry: '2dsphere' })
41
+
42
+ BeaconSchema.plugin(patcher)
43
+
44
+ // mongoose validator helper plugin
45
+ BeaconSchema.post('validate', function (doc) {
46
+ // Beacon Schema post validate hook
47
+ this.lastUpdateTime = Date.now()
48
+ Object.assign(this.errors || {}, this.errors || {}, this.customErrors)
49
+ })
50
+
51
+ function validateMajorMinor (v) {
52
+ 'use strict'
53
+ return v >= 0 && v <= 65535
54
+ }
55
+
56
+ function validateBeaconType (v, callback) {
57
+ 'use strict'
58
+ const beaconType = v
59
+ const { minor, major, macAddress, proximityUUID } = this;
60
+
61
+ let androidRegex = new RegExp(/(android)/ig)
62
+ let iosRegex = new RegExp(/(ios)/ig)
63
+ let bothRegex = new RegExp(/(both)/ig)
64
+
65
+ if (androidRegex.test(beaconType)) {
66
+ callback((!!macAddress), "Beacon type 'Android' must have a mac address")
67
+ } else if (iosRegex.test(beaconType)) {
68
+ callback((!!proximityUUID && !!minor && !!major), "Beacon type 'IOS' must have 'proximityUUID', 'minor' and 'major' values")
69
+ } else if (bothRegex.test(beaconType)) {
70
+ callback((!!proximityUUID && !!minor && !!major && !!macAddress), "Beacon type 'Both' must have all of 'proximityUUID', 'minor', 'major', and 'mac address' values")
71
+ } else {
72
+ callback(true)
73
+ }
74
+ }
32
75
 
33
- var Beacon = mongoose.model('Beacon', BeaconSchema);
76
+ // optional mongoose
77
+ let model = (mongooseInstance) => {
78
+ const instance = mongooseInstance || mongoose
79
+ let Beacon = instance.model('Beacon', BeaconSchema)
34
80
 
35
- module.exports = Beacon;
81
+ Beacon.on('index', function (error) {
82
+ console.log(error.message)
83
+ })
36
84
 
85
+ return Beacon
86
+ }
87
+ // Exports Mongoose Model, Mongoose Schema, JSON schema (required locally for discriminators)
88
+ module.exports = { Model: model, Schema: BeaconSchema, beaconSchema: schema }
@@ -3,43 +3,42 @@
3
3
  * Copyright : Bluedot Innovations.
4
4
  * Owner :
5
5
  */
6
- var mongoose = require('mongoose');
6
+ let mongoose = require('mongoose')
7
7
 
8
- var Contract = mongoose.model('Contract', new mongoose.Schema(
9
- {
10
- customerId: String,
11
- organisationName: String,
12
- addressLine1: String,
13
- addressLine2: String,
14
- addressCity: String,
15
- addressRegion: String,
16
- addressPostcode: String,
17
- addressCountry: String,
18
- billingFirstName: String,
19
- billingLastName: String,
20
- billingTaxNumber: String,
21
- billingEmail: String,
22
- tradingName: String,
23
- salesforceUrl: String,
24
- startDate : {type: Date, default: Date.now},
25
- endDate : {type: Date, default: Date.now},
26
- frequency : mongoose.Schema.Types.Number,
27
- monthEntries: [],
28
- currency: {type: String, default: "USD"},
29
- currencyRate: Number,
30
- template: String,
31
- addedBy: String,
32
- lastEditedBy: String,
33
- xeroContactId: String,
34
- state: String,
35
- creationTime : {type: Date, default: Date.now},
36
- lastUpdateTime : {type: Date, default: Date.now},
37
- dataSource : {type:String, select: false, default : 'adminPortal'}
38
- },
39
- {
40
- collection : 'contract'
41
- }
42
- )
43
- );
8
+ let Contract = mongoose.model('Contract', new mongoose.Schema(
9
+ {
10
+ customerId: String,
11
+ organisationName: String,
12
+ addressLine1: String,
13
+ addressLine2: String,
14
+ addressCity: String,
15
+ addressRegion: String,
16
+ addressPostcode: String,
17
+ addressCountry: String,
18
+ billingFirstName: String,
19
+ billingLastName: String,
20
+ billingTaxNumber: String,
21
+ billingEmail: String,
22
+ tradingName: String,
23
+ salesforceUrl: String,
24
+ startDate: {type: Date, default: Date.now},
25
+ endDate: {type: Date, default: Date.now},
26
+ frequency: mongoose.Schema.Types.Number,
27
+ monthEntries: [],
28
+ currency: {type: String, default: 'USD'},
29
+ currencyRate: Number,
30
+ template: String,
31
+ addedBy: String,
32
+ lastEditedBy: String,
33
+ xeroContactId: String,
34
+ state: String,
35
+ creationTime: {type: Date, default: Date.now},
36
+ lastUpdateTime: {type: Date, default: Date.now},
37
+ dataSource: {type: String, select: false, default: 'adminPortal'}
38
+ },
39
+ {
40
+ collection: 'contract'
41
+ })
42
+ )
44
43
 
45
- module.exports = Contract;
44
+ module.exports = Contract
@@ -2,8 +2,8 @@
2
2
  * Created by andrewstirling on 20/6/17.
3
3
  */
4
4
 
5
- var mongoose = require('mongoose');
6
- var StateEnum = require('@bluedot-innovation/enums').StateEnum;
5
+ var mongoose = require('mongoose')
6
+ var StateEnum = require('@bluedot-innovation/enums').StateEnum
7
7
 
8
8
  var CustomerLogin = mongoose.model('CustomerLogin', new mongoose.Schema(
9
9
  {
@@ -19,16 +19,15 @@ var CustomerLogin = mongoose.model('CustomerLogin', new mongoose.Schema(
19
19
  integrations: {},
20
20
  resetToken: String,
21
21
  lastLoginTime: Date,
22
- state: {type:String, default: StateEnum.active},
23
- creationTime : {type: Date, default: Date.now},
24
- lastUpdateTime : {type: Date, default: Date.now},
22
+ state: {type: String, default: StateEnum.active},
23
+ creationTime: {type: Date, default: Date.now},
24
+ lastUpdateTime: {type: Date, default: Date.now},
25
25
  createdBy: String,
26
26
  lastUpdatedBy: String
27
27
  },
28
28
  {
29
- collection : 'customerLogin'
30
- }
31
- )
32
- );
29
+ collection: 'customerLogin'
30
+ })
31
+ )
33
32
 
34
- module.exports = CustomerLogin;
33
+ module.exports = CustomerLogin