@resolveio/server-lib 9.0.32 → 9.0.34

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 (193) hide show
  1. package/client-server-app.js +7 -48
  2. package/client-server-app.js.map +1 -1
  3. package/collections/app-status.collection.js +8 -11
  4. package/collections/app-status.collection.js.map +1 -1
  5. package/collections/app-version.collection.js +8 -11
  6. package/collections/app-version.collection.js.map +1 -1
  7. package/collections/counter.collection.js +8 -11
  8. package/collections/counter.collection.js.map +1 -1
  9. package/collections/cron-job-history.collection.js +9 -12
  10. package/collections/cron-job-history.collection.js.map +1 -1
  11. package/collections/cron-job.collection.js +8 -11
  12. package/collections/cron-job.collection.js.map +1 -1
  13. package/collections/email-history.collection.js +8 -11
  14. package/collections/email-history.collection.js.map +1 -1
  15. package/collections/email-verified.collection.js +9 -12
  16. package/collections/email-verified.collection.js.map +1 -1
  17. package/collections/file.collection.js +8 -11
  18. package/collections/file.collection.js.map +1 -1
  19. package/collections/flag.collection.js +8 -11
  20. package/collections/flag.collection.js.map +1 -1
  21. package/collections/log-method-latency.collection.js +11 -14
  22. package/collections/log-method-latency.collection.js.map +1 -1
  23. package/collections/log-subscription.collection.js +13 -16
  24. package/collections/log-subscription.collection.js.map +1 -1
  25. package/collections/log.collection.js +16 -19
  26. package/collections/log.collection.js.map +1 -1
  27. package/collections/logged-in-users.collection.js +9 -12
  28. package/collections/logged-in-users.collection.js.map +1 -1
  29. package/collections/method-call.collection.js +10 -13
  30. package/collections/method-call.collection.js.map +1 -1
  31. package/collections/method-response.collection.js +10 -13
  32. package/collections/method-response.collection.js.map +1 -1
  33. package/collections/monitor-cpu.collection.js +13 -16
  34. package/collections/monitor-cpu.collection.js.map +1 -1
  35. package/collections/monitor-https-inbound.collection.js +13 -16
  36. package/collections/monitor-https-inbound.collection.js.map +1 -1
  37. package/collections/monitor-https-outbound.collection.js +15 -18
  38. package/collections/monitor-https-outbound.collection.js.map +1 -1
  39. package/collections/monitor-memory.collection.js +12 -15
  40. package/collections/monitor-memory.collection.js.map +1 -1
  41. package/collections/monitor-mongo.collection.js +12 -15
  42. package/collections/monitor-mongo.collection.js.map +1 -1
  43. package/collections/notification.collection.js +8 -11
  44. package/collections/notification.collection.js.map +1 -1
  45. package/collections/queue-flag.collection.js +9 -12
  46. package/collections/queue-flag.collection.js.map +1 -1
  47. package/collections/queue-method.collection.js +9 -12
  48. package/collections/queue-method.collection.js.map +1 -1
  49. package/collections/queue-response.collection.js +9 -12
  50. package/collections/queue-response.collection.js.map +1 -1
  51. package/collections/report-builder-dashboard-builder.collection.js +10 -13
  52. package/collections/report-builder-dashboard-builder.collection.js.map +1 -1
  53. package/collections/report-builder-library.collection.js +11 -14
  54. package/collections/report-builder-library.collection.js.map +1 -1
  55. package/collections/report-builder-report.collection.js +11 -14
  56. package/collections/report-builder-report.collection.js.map +1 -1
  57. package/collections/user-group.collection.js +11 -14
  58. package/collections/user-group.collection.js.map +1 -1
  59. package/collections/user-guide.collection.js +8 -11
  60. package/collections/user-guide.collection.js.map +1 -1
  61. package/collections/user.collection.js +12 -15
  62. package/collections/user.collection.js.map +1 -1
  63. package/cron/cron.js +25 -25
  64. package/cron/cron.js.map +1 -1
  65. package/fixtures/cron-jobs.js +30 -80
  66. package/fixtures/cron-jobs.js.map +1 -1
  67. package/fixtures/init.js +9 -59
  68. package/fixtures/init.js.map +1 -1
  69. package/http/auth.js +344 -460
  70. package/http/auth.js.map +1 -1
  71. package/http/health.js +1 -5
  72. package/http/health.js.map +1 -1
  73. package/http/home.js +7 -11
  74. package/http/home.js.map +1 -1
  75. package/index.js +36 -98
  76. package/index.js.map +1 -1
  77. package/managers/cron.manager.js +78 -157
  78. package/managers/cron.manager.js.map +1 -1
  79. package/managers/method.manager.js +323 -303
  80. package/managers/method.manager.js.map +1 -1
  81. package/managers/mongo.manager.d.ts +14 -14
  82. package/managers/mongo.manager.js +794 -865
  83. package/managers/mongo.manager.js.map +1 -1
  84. package/managers/monitor.manager.js +171 -254
  85. package/managers/monitor.manager.js.map +1 -1
  86. package/managers/queue-method.manager.js +69 -166
  87. package/managers/queue-method.manager.js.map +1 -1
  88. package/managers/subscription.manager.js +515 -708
  89. package/managers/subscription.manager.js.map +1 -1
  90. package/methods/accounts.js +111 -183
  91. package/methods/accounts.js.map +1 -1
  92. package/methods/aws.js +156 -262
  93. package/methods/aws.js.map +1 -1
  94. package/methods/cloudconvert.js +100 -180
  95. package/methods/cloudconvert.js.map +1 -1
  96. package/methods/collections.js +114 -530
  97. package/methods/collections.js.map +1 -1
  98. package/methods/counters.js +29 -79
  99. package/methods/counters.js.map +1 -1
  100. package/methods/cron-jobs.js +819 -884
  101. package/methods/cron-jobs.js.map +1 -1
  102. package/methods/flags.js +1 -5
  103. package/methods/flags.js.map +1 -1
  104. package/methods/logs.js +258 -313
  105. package/methods/logs.js.map +1 -1
  106. package/methods/monitor.js +289 -348
  107. package/methods/monitor.js.map +1 -1
  108. package/methods/pdf.js +341 -340
  109. package/methods/pdf.js.map +1 -1
  110. package/methods/report-builder.js +565 -657
  111. package/methods/report-builder.js.map +1 -1
  112. package/methods/support.js +67 -185
  113. package/methods/support.js.map +1 -1
  114. package/models/app-status.model.js +1 -2
  115. package/models/app-version.model.js +1 -2
  116. package/models/billing-logged-in-users.model.js +1 -2
  117. package/models/collection-document.model.js +1 -2
  118. package/models/counter.model.js +1 -2
  119. package/models/cron-job-history.model.js +1 -2
  120. package/models/cron-job.model.js +1 -2
  121. package/models/dialog.model.js +1 -2
  122. package/models/email-history.model.js +1 -2
  123. package/models/email-verified.model.js +1 -2
  124. package/models/file.model.js +1 -2
  125. package/models/flag.model.js +1 -2
  126. package/models/log-method-latency.model.js +1 -2
  127. package/models/log-subscription.model.js +1 -2
  128. package/models/log.model.js +1 -2
  129. package/models/logged-in-users.model.js +1 -2
  130. package/models/method-call.model.js +1 -2
  131. package/models/method-response.model.js +1 -2
  132. package/models/method.model.js +1 -2
  133. package/models/monitor-cpu.model.js +1 -2
  134. package/models/monitor-https-inbound.model.js +1 -2
  135. package/models/monitor-https-outbound.model.js +1 -2
  136. package/models/monitor-memory.model.js +1 -2
  137. package/models/monitor-mongo.model.js +1 -2
  138. package/models/notification.model.js +1 -2
  139. package/models/pagination.model.js +2 -5
  140. package/models/pagination.model.js.map +1 -1
  141. package/models/permission.model.js +1 -2
  142. package/models/queue-method.model.js +1 -2
  143. package/models/queue-response.model.js +1 -2
  144. package/models/report-builder-dashboard-builder.model.js +1 -2
  145. package/models/report-builder-library.model.js +1 -2
  146. package/models/report-builder-report.model.js +1 -2
  147. package/models/report-builder.model.js +1 -2
  148. package/models/select-data-label.model.js +1 -2
  149. package/models/server-response.model.js +1 -2
  150. package/models/subscription.model.js +1 -2
  151. package/models/support-ticket.model.js +1 -2
  152. package/models/user-group.model.js +1 -2
  153. package/models/user-guide.model.js +1 -2
  154. package/models/user.model.js +1 -2
  155. package/package.json +1 -1
  156. package/public_api.js +70 -82
  157. package/public_api.js.map +1 -1
  158. package/publications/app-status.js +4 -8
  159. package/publications/app-status.js.map +1 -1
  160. package/publications/app-version.js +4 -8
  161. package/publications/app-version.js.map +1 -1
  162. package/publications/cron-jobs.js +9 -13
  163. package/publications/cron-jobs.js.map +1 -1
  164. package/publications/files.js +11 -15
  165. package/publications/files.js.map +1 -1
  166. package/publications/flags.js +7 -11
  167. package/publications/flags.js.map +1 -1
  168. package/publications/logs.js +31 -35
  169. package/publications/logs.js.map +1 -1
  170. package/publications/method-calls.js +4 -8
  171. package/publications/method-calls.js.map +1 -1
  172. package/publications/method-responses.js +4 -8
  173. package/publications/method-responses.js.map +1 -1
  174. package/publications/notifications.js +4 -8
  175. package/publications/notifications.js.map +1 -1
  176. package/publications/report-builder-dashboard-builders.js +8 -12
  177. package/publications/report-builder-dashboard-builders.js.map +1 -1
  178. package/publications/report-builder-libraries.js +16 -66
  179. package/publications/report-builder-libraries.js.map +1 -1
  180. package/publications/report-builder-reports.js +17 -21
  181. package/publications/report-builder-reports.js.map +1 -1
  182. package/publications/super-admin.js +3 -7
  183. package/publications/super-admin.js.map +1 -1
  184. package/publications/user-groups.js +4 -8
  185. package/publications/user-groups.js.map +1 -1
  186. package/publications/user-guides.js +4 -8
  187. package/publications/user-guides.js.map +1 -1
  188. package/server-app.js +393 -534
  189. package/server-app.js.map +1 -1
  190. package/util/common.js +55 -92
  191. package/util/common.js.map +1 -1
  192. package/util/schema-report-builder.js +76 -134
  193. package/util/schema-report-builder.js.map +1 -1
@@ -1,124 +1,66 @@
1
- "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
- var __generator = (this && this.__generator) || function (thisArg, body) {
12
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
13
- return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
14
- function verb(n) { return function (v) { return step([n, v]); }; }
15
- function step(op) {
16
- if (f) throw new TypeError("Generator is already executing.");
17
- while (_) try {
18
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
19
- if (y = 0, t) op = [op[0] & 2, t.value];
20
- switch (op[0]) {
21
- case 0: case 1: t = op; break;
22
- case 4: _.label++; return { value: op[1], done: false };
23
- case 5: _.label++; y = op[1]; op = [0]; continue;
24
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
25
- default:
26
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
27
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
28
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
29
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
30
- if (t[2]) _.ops.pop();
31
- _.trys.pop(); continue;
32
- }
33
- op = body.call(thisArg, _);
34
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
35
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
36
- }
37
- };
38
- Object.defineProperty(exports, "__esModule", { value: true });
39
- exports.loadReportBuilderMethods = void 0;
40
- var simpl_schema_1 = require("simpl-schema");
41
- var pagination_model_1 = require("../models/pagination.model");
42
- var index_1 = require("../index");
43
- var schema_report_builder_1 = require("../util/schema-report-builder");
44
- function loadReportBuilderMethods(methodManager) {
1
+ import SimpleSchema from 'simpl-schema';
2
+ import { PaginationOptionsSchema } from '../models/pagination.model';
3
+ import { ResolveIOServer } from '../index';
4
+ import { getReportLookupSchemas, buildTree, mongoCommand } from '../util/schema-report-builder';
5
+ export function loadReportBuilderMethods(methodManager) {
45
6
  methodManager.methods({
46
7
  reportBuilderBuildTree: {
47
8
  skipQueue: true,
48
- check: new simpl_schema_1.default({
9
+ check: new SimpleSchema({
49
10
  collection_root: {
50
11
  type: String
51
12
  }
52
13
  }),
53
14
  function: function (collection_root) {
54
- var _this = this;
55
- return new Promise(function (resolve, reject) { return __awaiter(_this, void 0, void 0, function () {
56
- var lookupSchemaData, lookupSchemaTree, treeItems;
57
- return __generator(this, function (_a) {
58
- lookupSchemaData = schema_report_builder_1.getReportLookupSchemas(collection_root).sort(function (a, b) { return a.collection_name.localeCompare(b.collection_name); });
59
- lookupSchemaTree = lookupSchemaData.filter(function (a) { return a.is_root === true; })[0].tree;
60
- treeItems = schema_report_builder_1.buildTree(collection_root, lookupSchemaTree);
61
- Object.keys(lookupSchemaTree).filter(function (a) { return a.endsWith('(Lookup)'); }).forEach(function (lookup) {
62
- var fieldPath = lookup.split('.');
63
- var field = null;
64
- fieldPath.forEach(function (path) {
65
- if (!field) {
66
- field = treeItems.filter(function (a) { return a.fieldName === path; })[0];
67
- }
68
- else {
69
- field = field.children.filter(function (a) { return a.fieldName === path; })[0];
70
- }
71
- });
72
- field.children = schema_report_builder_1.buildTree(lookupSchemaTree[lookup].lookup_collection, lookupSchemaData.filter(function (a) { return a.collection_name === lookupSchemaTree[lookup].lookup_collection; })[0].tree, field);
15
+ return new Promise(async (resolve, reject) => {
16
+ let lookupSchemaData = getReportLookupSchemas(collection_root).sort((a, b) => a.collection_name.localeCompare(b.collection_name));
17
+ let lookupSchemaTree = lookupSchemaData.filter(a => a.is_root === true)[0].tree;
18
+ let treeItems = buildTree(collection_root, lookupSchemaTree);
19
+ Object.keys(lookupSchemaTree).filter(a => a.endsWith('(Lookup)')).forEach(lookup => {
20
+ let fieldPath = lookup.split('.');
21
+ let field = null;
22
+ fieldPath.forEach(path => {
23
+ if (!field) {
24
+ field = treeItems.filter(a => a.fieldName === path)[0];
25
+ }
26
+ else {
27
+ field = field.children.filter(a => a.fieldName === path)[0];
28
+ }
73
29
  });
74
- // console.log('----------- Tree Items -----------', treeItems);
75
- resolve({ isLeaf: false, children: treeItems });
76
- return [2 /*return*/];
30
+ field.children = buildTree(lookupSchemaTree[lookup].lookup_collection, lookupSchemaData.filter(a => a.collection_name === lookupSchemaTree[lookup].lookup_collection)[0].tree, field);
77
31
  });
78
- }); });
32
+ // console.log('----------- Tree Items -----------', treeItems);
33
+ resolve({ isLeaf: false, children: treeItems });
34
+ });
79
35
  }
80
36
  },
81
37
  reportBuilderGetDistinctValue: {
82
38
  skipQueue: true,
83
- check: new simpl_schema_1.default({
39
+ check: new SimpleSchema({
84
40
  treeLeaf: {
85
41
  type: Object,
86
42
  blackbox: true
87
43
  }
88
44
  }),
89
45
  function: function (treeLeaf) {
90
- var _this = this;
91
- return new Promise(function (resolve, reject) { return __awaiter(_this, void 0, void 0, function () {
92
- var _a, _b;
93
- return __generator(this, function (_c) {
94
- switch (_c.label) {
95
- case 0:
96
- if (!(treeLeaf.fieldType === 'String')) return [3 /*break*/, 5];
97
- if (!treeLeaf.fieldPath.includes('(Lookup)')) return [3 /*break*/, 2];
98
- _a = resolve;
99
- return [4 /*yield*/, schema_report_builder_1.mongoCommand('distinct', treeLeaf.collection_name, treeLeaf.fieldPath.replace(/^.+\(.+\) \(Lookup\)\.\$\./g, '').replace(/\.\$/g, ''))];
100
- case 1:
101
- _a.apply(void 0, [_c.sent()]);
102
- return [3 /*break*/, 4];
103
- case 2:
104
- _b = resolve;
105
- return [4 /*yield*/, schema_report_builder_1.mongoCommand('distinct', treeLeaf.collection_name, treeLeaf.fieldPath.replace(/\.\$/g, ''))];
106
- case 3:
107
- _b.apply(void 0, [_c.sent()]);
108
- _c.label = 4;
109
- case 4: return [3 /*break*/, 6];
110
- case 5:
111
- resolve([]);
112
- _c.label = 6;
113
- case 6: return [2 /*return*/];
46
+ return new Promise(async (resolve, reject) => {
47
+ if (treeLeaf.fieldType === 'String') {
48
+ if (treeLeaf.fieldPath.includes('(Lookup)')) {
49
+ resolve(await mongoCommand('distinct', treeLeaf.collection_name, treeLeaf.fieldPath.replace(/^.+\(.+\) \(Lookup\)\.\$\./g, '').replace(/\.\$/g, '')));
114
50
  }
115
- });
116
- }); });
51
+ else {
52
+ resolve(await mongoCommand('distinct', treeLeaf.collection_name, treeLeaf.fieldPath.replace(/\.\$/g, '')));
53
+ }
54
+ }
55
+ else {
56
+ resolve([]);
57
+ }
58
+ });
117
59
  }
118
60
  },
119
61
  reportBuilderGetResults: {
120
62
  skipQueue: true,
121
- check: new simpl_schema_1.default({
63
+ check: new SimpleSchema({
122
64
  reportType: {
123
65
  type: String
124
66
  },
@@ -126,7 +68,7 @@ function loadReportBuilderMethods(methodManager) {
126
68
  type: String
127
69
  },
128
70
  options: {
129
- type: pagination_model_1.PaginationOptionsSchema
71
+ type: PaginationOptionsSchema
130
72
  },
131
73
  filters: {
132
74
  type: Array,
@@ -207,624 +149,590 @@ function loadReportBuilderMethods(methodManager) {
207
149
  optional: true
208
150
  }
209
151
  }),
210
- function: function (reportType, rootCollectionName, rootOptions, filters, filterArrays, filterArrayFields, selectedFields, customFields, groupsRow, fieldsTotal, fieldsLink, date_field, date_interval, displayType) {
211
- var _this = this;
212
- if (filters === void 0) { filters = []; }
213
- if (filterArrays === void 0) { filterArrays = []; }
214
- if (filterArrayFields === void 0) { filterArrayFields = []; }
215
- if (selectedFields === void 0) { selectedFields = []; }
216
- if (customFields === void 0) { customFields = []; }
217
- if (groupsRow === void 0) { groupsRow = []; }
218
- if (fieldsTotal === void 0) { fieldsTotal = []; }
219
- if (fieldsLink === void 0) { fieldsLink = []; }
220
- if (date_field === void 0) { date_field = ''; }
221
- if (date_interval === void 0) { date_interval = ''; }
222
- if (displayType === void 0) { displayType = ''; }
223
- return new Promise(function (resolve, reject) { return __awaiter(_this, void 0, void 0, function () {
224
- var modelCollection, query_1, initialQueryMatchCondition_1, sizes_1, divFields_1, queryMatchConditionLookup_1, queryGroup_1, queryProjection_1, _loop_1, i, res_1, err_1, tmpTotals_1, tmpRes;
225
- var _this = this;
226
- return __generator(this, function (_a) {
227
- switch (_a.label) {
228
- case 0:
229
- modelCollection = index_1.ResolveIOServer.getMongoManager().collection(rootCollectionName);
230
- if (!!modelCollection) return [3 /*break*/, 1];
231
- reject('Invalid collection');
232
- return [3 /*break*/, 6];
233
- case 1:
234
- query_1 = [];
235
- initialQueryMatchCondition_1 = {
236
- $and: []
237
- };
238
- // selectedFields.filter(a => a.collection_name === rootCollectionName).forEach(field => {
239
- // initialQueryMatchCondition['$and'].push({
240
- // $and: [
241
- // {[field.fieldPath.replace(/\.\$/g, '')]: {$exists: 1}},
242
- // // {[field.fieldPath.replace(/\.\$/g, '')]: {$ne: ''}},
243
- // {[field.fieldPath.replace(/\.\$/g, '')]: {$ne: null}},
244
- // ]
245
- // });
246
- // });
247
- if (filters.filter(function (a) { return (!a['$or'] && !Object.keys(a).some(function (b) { return b.includes('(Lookup)'); })) || (a['$or'] && !a['$or'].some(function (b) { return Object.keys(b).some(function (c) { return c.includes('(Lookup)'); }); })); }).length) {
248
- filters.filter(function (a) { return (!a['$or'] && !Object.keys(a).some(function (b) { return b.includes('(Lookup)'); })) || (a['$or'] && !a['$or'].some(function (b) { return Object.keys(b).some(function (c) { return c.includes('(Lookup)'); }); })); }).forEach(function (filter) {
249
- initialQueryMatchCondition_1['$and'].push(filter);
250
- });
152
+ function: function (reportType, rootCollectionName, rootOptions, filters = [], filterArrays = [], filterArrayFields = [], selectedFields = [], customFields = [], groupsRow = [], fieldsTotal = [], fieldsLink = [], date_field = '', date_interval = '', displayType = '') {
153
+ return new Promise(async (resolve, reject) => {
154
+ let modelCollection = ResolveIOServer.getMongoManager().collection(rootCollectionName);
155
+ if (!modelCollection) {
156
+ reject('Invalid collection');
157
+ }
158
+ else {
159
+ // Query
160
+ let query = [];
161
+ // Non-Lookup Match Filters
162
+ let initialQueryMatchCondition = {
163
+ $and: []
164
+ };
165
+ // selectedFields.filter(a => a.collection_name === rootCollectionName).forEach(field => {
166
+ // initialQueryMatchCondition['$and'].push({
167
+ // $and: [
168
+ // {[field.fieldPath.replace(/\.\$/g, '')]: {$exists: 1}},
169
+ // // {[field.fieldPath.replace(/\.\$/g, '')]: {$ne: ''}},
170
+ // {[field.fieldPath.replace(/\.\$/g, '')]: {$ne: null}},
171
+ // ]
172
+ // });
173
+ // });
174
+ if (filters.filter(a => (!a['$or'] && !Object.keys(a).some(b => b.includes('(Lookup)'))) || (a['$or'] && !a['$or'].some(b => Object.keys(b).some(c => c.includes('(Lookup)'))))).length) {
175
+ filters.filter(a => (!a['$or'] && !Object.keys(a).some(b => b.includes('(Lookup)'))) || (a['$or'] && !a['$or'].some(b => Object.keys(b).some(c => c.includes('(Lookup)'))))).forEach(filter => {
176
+ initialQueryMatchCondition['$and'].push(filter);
177
+ });
178
+ }
179
+ // Add filter to query
180
+ // if (filters.filter(a => (!a['$or'] && !Object.keys(a).some(b => b.includes('(Lookup)'))) || (a['$or'] && !a['$or'].some(b => Object.keys(b).some(c => c.includes('(Lookup)'))))).length || selectedFields.filter(a => !a.fieldPath.includes('(Lookup')).length) {
181
+ if (filters.filter(a => (!a['$or'] && !Object.keys(a).some(b => b.includes('(Lookup)'))) || (a['$or'] && !a['$or'].some(b => Object.keys(b).some(c => c.includes('(Lookup)'))))).length) {
182
+ query.push({
183
+ $match: initialQueryMatchCondition
184
+ });
185
+ }
186
+ // Add count
187
+ query.push({ $addFields: { count: { $sum: 1 } } });
188
+ let sizes = [];
189
+ filterArrayFields.filter(a => a.fieldPath).forEach(filterField => {
190
+ let fieldData = filterField.fieldPath.split('.$');
191
+ let fieldPath = '';
192
+ for (let i = 0; i < fieldData.length - 1; i++) {
193
+ fieldPath += fieldData[i];
194
+ if (fieldPath.split('.$')[fieldPath.split('.$').length - 1].includes('(Lookup)')) {
195
+ if (!query.some(a => a.$lookup && a.$lookup.as === filterField.lookup_as.replace(/\.\$/g, ''))) {
196
+ query.push({ $lookup: {
197
+ from: filterField.lookup_collection,
198
+ localField: filterField.lookup_local_key,
199
+ foreignField: filterField.lookup_foreign_key,
200
+ as: filterField.lookup_as.replace(/\.\$/g, '')
201
+ } });
202
+ sizes.push(filterField.lookup_as.replace(/\.\$\./g, '_').replace(/\./g, '_'));
203
+ query.push({ $addFields: { ['size_' + filterField.lookup_as.replace(/\.\$\./g, '_').replace(/\./g, '_')]: { $size: { $ifNull: ['$' + filterField.lookup_as.replace(/\.\$/g, '').replace(/\./g, '_'), []] } } } });
204
+ query.push({ '$unwind': { path: '$' + filterField.lookup_as.replace(/\.\$/g, ''), preserveNullAndEmptyArrays: true } });
205
+ }
251
206
  }
252
- // Add filter to query
253
- // if (filters.filter(a => (!a['$or'] && !Object.keys(a).some(b => b.includes('(Lookup)'))) || (a['$or'] && !a['$or'].some(b => Object.keys(b).some(c => c.includes('(Lookup)'))))).length || selectedFields.filter(a => !a.fieldPath.includes('(Lookup')).length) {
254
- if (filters.filter(function (a) { return (!a['$or'] && !Object.keys(a).some(function (b) { return b.includes('(Lookup)'); })) || (a['$or'] && !a['$or'].some(function (b) { return Object.keys(b).some(function (c) { return c.includes('(Lookup)'); }); })); }).length) {
255
- query_1.push({
256
- $match: initialQueryMatchCondition_1
257
- });
207
+ else {
208
+ if (!query.some(a => a.$addFields && Object.keys(a.$addFields).includes('size_' + fieldPath.replace(/\./g, '_')))) {
209
+ sizes.push(fieldPath.replace(/\./g, '_'));
210
+ query.push({ $addFields: { ['size_' + fieldPath.replace(/\./g, '_')]: { $size: { $ifNull: ['$' + fieldPath, []] } } } });
211
+ query.push({ '$unwind': { path: '$' + fieldPath, preserveNullAndEmptyArrays: true } });
212
+ }
258
213
  }
259
- // Add count
260
- query_1.push({ $addFields: { count: { $sum: 1 } } });
261
- sizes_1 = [];
262
- filterArrayFields.filter(function (a) { return a.fieldPath; }).forEach(function (filterField) {
263
- var _a, _b;
264
- var fieldData = filterField.fieldPath.split('.$');
265
- var fieldPath = '';
266
- for (var i = 0; i < fieldData.length - 1; i++) {
267
- fieldPath += fieldData[i];
268
- if (fieldPath.split('.$')[fieldPath.split('.$').length - 1].includes('(Lookup)')) {
269
- if (!query_1.some(function (a) { return a.$lookup && a.$lookup.as === filterField.lookup_as.replace(/\.\$/g, ''); })) {
270
- query_1.push({ $lookup: {
271
- from: filterField.lookup_collection,
272
- localField: filterField.lookup_local_key,
273
- foreignField: filterField.lookup_foreign_key,
274
- as: filterField.lookup_as.replace(/\.\$/g, '')
275
- } });
276
- sizes_1.push(filterField.lookup_as.replace(/\.\$\./g, '_').replace(/\./g, '_'));
277
- query_1.push({ $addFields: (_a = {}, _a['size_' + filterField.lookup_as.replace(/\.\$\./g, '_').replace(/\./g, '_')] = { $size: { $ifNull: ['$' + filterField.lookup_as.replace(/\.\$/g, '').replace(/\./g, '_'), []] } }, _a) });
278
- query_1.push({ '$unwind': { path: '$' + filterField.lookup_as.replace(/\.\$/g, ''), preserveNullAndEmptyArrays: true } });
279
- }
280
- }
281
- else {
282
- if (!query_1.some(function (a) { return a.$addFields && Object.keys(a.$addFields).includes('size_' + fieldPath.replace(/\./g, '_')); })) {
283
- sizes_1.push(fieldPath.replace(/\./g, '_'));
284
- query_1.push({ $addFields: (_b = {}, _b['size_' + fieldPath.replace(/\./g, '_')] = { $size: { $ifNull: ['$' + fieldPath, []] } }, _b) });
285
- query_1.push({ '$unwind': { path: '$' + fieldPath, preserveNullAndEmptyArrays: true } });
286
- }
214
+ }
215
+ });
216
+ // Groups - Lookups / Sizes / Unwinds
217
+ groupsRow.forEach(row => {
218
+ if (row.field.includes('$')) {
219
+ let fieldData = row.field.split('.$');
220
+ let fieldPath = '';
221
+ for (let i = 0; i < fieldData.length - 1; i++) {
222
+ fieldPath += fieldData[i];
223
+ if (fieldPath.split('.$')[fieldPath.split('.$').length - 1].includes('(Lookup)')) {
224
+ if (!query.some(a => a.$lookup && a.$lookup.as === row.treeItem.lookup_as.replace(/\.\$/g, ''))) {
225
+ query.push({ $lookup: {
226
+ from: row.treeItem.lookup_collection,
227
+ localField: row.treeItem.lookup_local_key,
228
+ foreignField: row.treeItem.lookup_foreign_key,
229
+ as: row.treeItem.lookup_as.replace(/\.\$/g, '')
230
+ } });
231
+ sizes.push(row.treeItem.lookup_as.replace(/\.\$\./g, '_').replace(/\./g, '_'));
232
+ query.push({ $addFields: { ['size_' + row.treeItem.lookup_as.replace(/\.\$\./g, '_').replace(/\./g, '_')]: { $size: { $ifNull: ['$' + row.treeItem.lookup_as.replace(/\.\$/g, '').replace(/\./g, '_'), []] } } } });
233
+ query.push({ '$unwind': { path: '$' + row.treeItem.lookup_as.replace(/\.\$/g, ''), preserveNullAndEmptyArrays: true } });
287
234
  }
288
235
  }
289
- });
290
- // Groups - Lookups / Sizes / Unwinds
291
- groupsRow.forEach(function (row) {
292
- var _a, _b;
293
- if (row.field.includes('$')) {
294
- var fieldData = row.field.split('.$');
295
- var fieldPath_1 = '';
296
- for (var i = 0; i < fieldData.length - 1; i++) {
297
- fieldPath_1 += fieldData[i];
298
- if (fieldPath_1.split('.$')[fieldPath_1.split('.$').length - 1].includes('(Lookup)')) {
299
- if (!query_1.some(function (a) { return a.$lookup && a.$lookup.as === row.treeItem.lookup_as.replace(/\.\$/g, ''); })) {
300
- query_1.push({ $lookup: {
301
- from: row.treeItem.lookup_collection,
302
- localField: row.treeItem.lookup_local_key,
303
- foreignField: row.treeItem.lookup_foreign_key,
304
- as: row.treeItem.lookup_as.replace(/\.\$/g, '')
305
- } });
306
- sizes_1.push(row.treeItem.lookup_as.replace(/\.\$\./g, '_').replace(/\./g, '_'));
307
- query_1.push({ $addFields: (_a = {}, _a['size_' + row.treeItem.lookup_as.replace(/\.\$\./g, '_').replace(/\./g, '_')] = { $size: { $ifNull: ['$' + row.treeItem.lookup_as.replace(/\.\$/g, '').replace(/\./g, '_'), []] } }, _a) });
308
- query_1.push({ '$unwind': { path: '$' + row.treeItem.lookup_as.replace(/\.\$/g, ''), preserveNullAndEmptyArrays: true } });
309
- }
310
- }
311
- else {
312
- if (!query_1.some(function (a) { return a.$addFields && Object.keys(a.$addFields).includes('size_' + fieldPath_1.replace(/\./g, '_')); })) {
313
- sizes_1.push(fieldPath_1.replace(/\./g, '_'));
314
- query_1.push({ $addFields: (_b = {}, _b['size_' + fieldPath_1.replace(/\./g, '_')] = { $size: { $ifNull: ['$' + fieldPath_1, []] } }, _b) });
315
- query_1.push({ '$unwind': { path: '$' + fieldPath_1, preserveNullAndEmptyArrays: true } });
316
- }
317
- }
236
+ else {
237
+ if (!query.some(a => a.$addFields && Object.keys(a.$addFields).includes('size_' + fieldPath.replace(/\./g, '_')))) {
238
+ sizes.push(fieldPath.replace(/\./g, '_'));
239
+ query.push({ $addFields: { ['size_' + fieldPath.replace(/\./g, '_')]: { $size: { $ifNull: ['$' + fieldPath, []] } } } });
240
+ query.push({ '$unwind': { path: '$' + fieldPath, preserveNullAndEmptyArrays: true } });
318
241
  }
319
242
  }
320
- });
321
- // Selected Fields - Lookups / Sizes / Unwinds
322
- selectedFields.forEach(function (field) {
323
- var _a, _b, _c;
324
- if (field.fieldPath.includes('$')) {
325
- var fieldData = field.fieldPath.split('.$');
326
- var fieldPath_2 = '';
327
- for (var i = 0; i < fieldData.length - 1; i++) {
328
- fieldPath_2 += fieldData[i];
329
- if (fieldPath_2.split('.$')[fieldPath_2.split('.$').length - 1].includes('(Lookup)')) {
330
- if (!query_1.some(function (a) { return a.$lookup && a.$lookup.as === field.lookup_as.replace(/\.\$/g, ''); })) {
331
- query_1.push({ $lookup: {
332
- from: field.lookup_collection,
333
- localField: field.lookup_local_key,
334
- foreignField: field.lookup_foreign_key,
335
- as: field.lookup_as.replace(/\.\$/g, '')
336
- } });
337
- sizes_1.push(field.lookup_as.replace(/\.\$\./g, '_').replace(/\./g, '_'));
338
- query_1.push({ $addFields: (_a = {}, _a['size_' + field.lookup_as.replace(/\.\$\./g, '_').replace(/\./g, '_')] = { $size: { $ifNull: ['$' + field.lookup_as.replace(/\.\$/g, '').replace(/\./g, '_'), []] } }, _a) });
339
- query_1.push({ '$unwind': { path: '$' + field.lookup_as.replace(/\.\$/g, ''), preserveNullAndEmptyArrays: true } });
340
- }
341
- else {
342
- if (!fieldData[i].includes('(Lookup)')) {
343
- if (!query_1.some(function (a) { return a.$addFields && Object.keys(a.$addFields).includes('size_' + fieldPath_2.replace(/\./g, '_')); })) {
344
- sizes_1.push(fieldPath_2.replace(/\./g, '_'));
345
- query_1.push({ $addFields: (_b = {}, _b['size_' + fieldPath_2.replace(/\./g, '_')] = { $size: { $ifNull: ['$' + fieldPath_2, []] } }, _b) });
346
- query_1.push({ '$unwind': { path: '$' + fieldPath_2, preserveNullAndEmptyArrays: true } });
347
- }
348
- }
349
- }
350
- }
351
- else {
352
- if (!query_1.some(function (a) { return a.$addFields && Object.keys(a.$addFields).includes('size_' + fieldPath_2.replace(/\./g, '_')); })) {
353
- sizes_1.push(fieldPath_2.replace(/\./g, '_'));
354
- query_1.push({ $addFields: (_c = {}, _c['size_' + fieldPath_2.replace(/\./g, '_')] = { $size: { $ifNull: ['$' + fieldPath_2, []] } }, _c) });
355
- }
356
- if (field.leafValueType !== 'Count' && !query_1.some(function (a) { return a.$unwind && a.$unwind.path === '$' + fieldPath_2; })) {
357
- query_1.push({ '$unwind': { path: '$' + fieldPath_2, preserveNullAndEmptyArrays: true } });
243
+ }
244
+ }
245
+ });
246
+ // Selected Fields - Lookups / Sizes / Unwinds
247
+ selectedFields.forEach(field => {
248
+ if (field.fieldPath.includes('$')) {
249
+ let fieldData = field.fieldPath.split('.$');
250
+ let fieldPath = '';
251
+ for (let i = 0; i < fieldData.length - 1; i++) {
252
+ fieldPath += fieldData[i];
253
+ if (fieldPath.split('.$')[fieldPath.split('.$').length - 1].includes('(Lookup)')) {
254
+ if (!query.some(a => a.$lookup && a.$lookup.as === field.lookup_as.replace(/\.\$/g, ''))) {
255
+ query.push({ $lookup: {
256
+ from: field.lookup_collection,
257
+ localField: field.lookup_local_key,
258
+ foreignField: field.lookup_foreign_key,
259
+ as: field.lookup_as.replace(/\.\$/g, '')
260
+ } });
261
+ sizes.push(field.lookup_as.replace(/\.\$\./g, '_').replace(/\./g, '_'));
262
+ query.push({ $addFields: { ['size_' + field.lookup_as.replace(/\.\$\./g, '_').replace(/\./g, '_')]: { $size: { $ifNull: ['$' + field.lookup_as.replace(/\.\$/g, '').replace(/\./g, '_'), []] } } } });
263
+ query.push({ '$unwind': { path: '$' + field.lookup_as.replace(/\.\$/g, ''), preserveNullAndEmptyArrays: true } });
264
+ }
265
+ else {
266
+ if (!fieldData[i].includes('(Lookup)')) {
267
+ if (!query.some(a => a.$addFields && Object.keys(a.$addFields).includes('size_' + fieldPath.replace(/\./g, '_')))) {
268
+ sizes.push(fieldPath.replace(/\./g, '_'));
269
+ query.push({ $addFields: { ['size_' + fieldPath.replace(/\./g, '_')]: { $size: { $ifNull: ['$' + fieldPath, []] } } } });
270
+ query.push({ '$unwind': { path: '$' + fieldPath, preserveNullAndEmptyArrays: true } });
358
271
  }
359
272
  }
360
273
  }
361
274
  }
362
- });
363
- divFields_1 = { $addFields: {} };
364
- fieldsTotal.filter(function (a) { return a.type === 'sum'; }).forEach(function (total) {
365
- selectedFields.filter(function (a) { return a.fieldType === 'Number' || a.leafValueType === 'Count'; }).forEach(function (field) {
366
- var multFields = [];
367
- if (!field.fieldPath.includes('.$')) {
368
- sizes_1.forEach(function (size) {
369
- multFields.push({ $cond: { if: { $gt: ['$size_' + size, 0] }, then: '$size_' + size, else: 1 } });
370
- });
371
- }
372
- else {
373
- sizes_1.filter(function (a) { return !field.fieldPath.replace(/\.\$\./g, '_').replace(/\./g, '_').includes(a) && !filterArrayFields.filter(function (a) { return a.fieldPath; }).some(function (b) { return b.fieldPath.replace(/\.\$\./g, '_').replace(/\./g, '_').includes(a); }) && !fieldsLink.some(function (b) { return b.field_first.replace(/\.\$\./g, '_').replace(/\./g, '_').includes(a) || b.field_second.replace(/\.\$\./g, '_').replace(/\./g, '_').includes(a); }); }).forEach(function (size) {
374
- multFields.push({ $cond: { if: { $gt: ['$size_' + size, 0] }, then: '$size_' + size, else: 1 } });
375
- });
376
- }
377
- if (multFields.length) {
378
- if (field.leafValueType === 'Count') {
379
- divFields_1.$addFields[total.id + '_' + field.id] = {
380
- $divide: ['$count', { $multiply: multFields }]
381
- };
382
- }
383
- else {
384
- divFields_1.$addFields[total.id + '_' + field.id] = {
385
- $divide: ['$' + field.fieldPath.replace(/\.\$/g, ''), { $multiply: multFields }]
386
- };
387
- }
275
+ else {
276
+ if (!query.some(a => a.$addFields && Object.keys(a.$addFields).includes('size_' + fieldPath.replace(/\./g, '_')))) {
277
+ sizes.push(fieldPath.replace(/\./g, '_'));
278
+ query.push({ $addFields: { ['size_' + fieldPath.replace(/\./g, '_')]: { $size: { $ifNull: ['$' + fieldPath, []] } } } });
388
279
  }
389
- else {
390
- if (field.leafValueType === 'Count') {
391
- divFields_1.$addFields[total.id + '_' + field.id] = '$count';
392
- }
393
- else {
394
- divFields_1.$addFields[total.id + '_' + field.id] = '$' + field.fieldPath.replace(/\.\$/g, '');
395
- }
280
+ if (field.leafValueType !== 'Count' && !query.some(a => a.$unwind && a.$unwind.path === '$' + fieldPath)) {
281
+ query.push({ '$unwind': { path: '$' + fieldPath, preserveNullAndEmptyArrays: true } });
396
282
  }
397
- });
398
- });
399
- selectedFields.filter(function (a) { return a.fieldType === 'Number' && a.leafValueType === 'Sum'; }).forEach(function (field) {
400
- var multFields = [];
401
- sizes_1.filter(function (a) { return !field.fieldPath.replace(/\.\$\./g, '_').replace(/\./g, '_').includes(a) && !groupsRow.some(function (b) { return b.field.replace(/\.\$\./g, '_').replace(/\./g, '_').includes(a); }) && !filterArrayFields.filter(function (a) { return a.fieldPath; }).some(function (b) { return b.fieldPath.replace(/\.\$\./g, '_').replace(/\./g, '_').includes(a); }) && !fieldsLink.some(function (b) { return b.field_first.replace(/\.\$\./g, '_').replace(/\./g, '_').includes(a) || b.field_second.replace(/\.\$\./g, '_').replace(/\./g, '_').includes(a); }); }).forEach(function (size) {
283
+ }
284
+ }
285
+ }
286
+ });
287
+ // Divide all number fields by sizes
288
+ let divFields = { $addFields: {} };
289
+ fieldsTotal.filter(a => a.type === 'sum').forEach(total => {
290
+ selectedFields.filter(a => a.fieldType === 'Number' || a.leafValueType === 'Count').forEach(field => {
291
+ let multFields = [];
292
+ if (!field.fieldPath.includes('.$')) {
293
+ sizes.forEach(size => {
402
294
  multFields.push({ $cond: { if: { $gt: ['$size_' + size, 0] }, then: '$size_' + size, else: 1 } });
403
295
  });
404
- if (multFields.length) {
405
- divFields_1.$addFields[field.fieldPath.replace(/\.\$/g, '')] = {
406
- $divide: ['$' + field.fieldPath.replace(/\.\$/g, ''), { $multiply: multFields }]
407
- };
408
- }
409
- });
410
- selectedFields.filter(function (a) { return a.leafValueType === 'Count'; }).forEach(function (field) {
411
- var multFields = [];
412
- sizes_1.filter(function (a) { return !field.fieldPath.replace(/\.\$\./g, '_').replace(/\./g, '_').includes(a) && !groupsRow.some(function (b) { return b.field.replace(/\.\$\./g, '_').replace(/\./g, '_').includes(a); }) && !filterArrayFields.filter(function (a) { return a.fieldPath; }).some(function (b) { return b.fieldPath.replace(/\.\$\./g, '_').replace(/\./g, '_').includes(a); }) && !fieldsLink.some(function (b) { return b.field_first.replace(/\.\$\./g, '_').replace(/\./g, '_').includes(a) || b.field_second.replace(/\.\$\./g, '_').replace(/\./g, '_').includes(a); }); }).forEach(function (size) {
296
+ }
297
+ else {
298
+ sizes.filter(a => !field.fieldPath.replace(/\.\$\./g, '_').replace(/\./g, '_').includes(a) && !filterArrayFields.filter(a => a.fieldPath).some(b => b.fieldPath.replace(/\.\$\./g, '_').replace(/\./g, '_').includes(a)) && !fieldsLink.some(b => b.field_first.replace(/\.\$\./g, '_').replace(/\./g, '_').includes(a) || b.field_second.replace(/\.\$\./g, '_').replace(/\./g, '_').includes(a))).forEach(size => {
413
299
  multFields.push({ $cond: { if: { $gt: ['$size_' + size, 0] }, then: '$size_' + size, else: 1 } });
414
300
  });
415
- if (multFields.length) {
416
- divFields_1.$addFields['count_' + field.fieldPath.replace(/\.\$/g, '')] = {
301
+ }
302
+ if (multFields.length) {
303
+ if (field.leafValueType === 'Count') {
304
+ divFields.$addFields[total.id + '_' + field.id] = {
417
305
  $divide: ['$count', { $multiply: multFields }]
418
306
  };
419
307
  }
420
308
  else {
421
- if (reportType !== 'Dated' && sizes_1.filter(function (a) { return field.fieldPath.replace(/\.\$\./g, '_').includes(a); }).length) {
422
- sizes_1.filter(function (a) { return field.fieldPath.replace(/\.\$\./g, '_').includes(a); }).forEach(function (size) {
423
- divFields_1.$addFields['count_' + field.fieldPath.replace(/\.\$/g, '')] = '$size_' + size;
424
- });
425
- }
426
- else {
427
- divFields_1.$addFields['count_' + field.fieldPath.replace(/\.\$/g, '')] = '$count';
428
- }
309
+ divFields.$addFields[total.id + '_' + field.id] = {
310
+ $divide: ['$' + field.fieldPath.replace(/\.\$/g, ''), { $multiply: multFields }]
311
+ };
429
312
  }
430
- });
431
- fieldsTotal.filter(function (a) { return a.type === 'avg'; }).forEach(function (total) {
432
- selectedFields.filter(function (a) { return a.fieldType === 'Number' || a.leafValueType === 'Count'; }).forEach(function (field) {
433
- divFields_1.$addFields[total.id + '_' + field.id] = '$' + field.fieldPath.replace(/\.\$/g, '');
434
- });
435
- });
436
- if (Object.keys(divFields_1.$addFields).length > 0) {
437
- query_1.push(divFields_1);
438
313
  }
439
- fieldsLink.filter(function (a) { return a.field_first && a.field_second; }).forEach(function (link) {
440
- var _a, _b;
441
- query_1.push({ $addFields: (_a = {}, _a[link.id] = { $cmp: ['$' + link.field_first.replace(/\.\$/g, ''), '$' + link.field_second.replace(/\.\$/g, '')] }, _a) });
442
- query_1.push({ $match: (_b = {}, _b[link.id] = 0, _b) });
443
- });
444
- customFields.forEach(function (cust) {
445
- cust.operations.filter(function (a) { return a.operation && !a.fields.some(function (b) { return (b.field === null || b.field === '') && b.value === null; }); }).forEach(function (operation, opIndex) {
446
- var _a, _b;
447
- var custFieldGroup = {};
448
- if (operation.operation === 'divide') {
449
- var condCheck_1 = [];
450
- operation.fields.filter(function (a) { return a.field || a.value !== null; }).forEach(function (field) {
451
- if (field.field) {
452
- condCheck_1.push({ $eq: ['$' + field.field.replace(/\.\$/g, ''), 0] });
453
- condCheck_1.push({ $eq: ['$' + field.field.replace(/\.\$/g, ''), null] });
454
- }
455
- else {
456
- condCheck_1.push({ $eq: [field.value, 0] });
457
- condCheck_1.push({ $eq: [field.value, null] });
458
- }
459
- });
460
- if (opIndex > 0) {
461
- condCheck_1.push({ $eq: ['$' + cust.selFieldId, 0] });
462
- condCheck_1.push({ $eq: ['$' + cust.selFieldId, null] });
463
- }
464
- var tmpOperationFields_1 = [];
465
- if (opIndex > 0) {
466
- tmpOperationFields_1.push('$' + cust.selFieldId);
467
- }
468
- operation.fields.filter(function (a) { return a.field || a.value !== null; }).forEach(function (field) {
469
- if (field.field) {
470
- tmpOperationFields_1.push('$' + field.field.replace(/\.\$/g, ''));
471
- }
472
- else {
473
- tmpOperationFields_1.push(field.value);
474
- }
475
- });
476
- custFieldGroup[cust.selFieldId] = {
477
- $cond: { if: { $or: condCheck_1 }, then: 0, else: (_a = {}, _a['$' + operation.operation] = tmpOperationFields_1, _a) }
478
- };
479
- }
480
- else {
481
- custFieldGroup[cust.selFieldId] = (_b = {},
482
- _b['$' + operation.operation] = [],
483
- _b);
484
- if (opIndex > 0) {
485
- custFieldGroup[cust.selFieldId]['$' + operation.operation].push({ $cond: { if: { $eq: ['$' + cust.selFieldId, null] }, then: 0, else: '$' + cust.selFieldId } });
486
- }
487
- var condOr_1 = [];
488
- operation.fields.filter(function (a) { return a.field || a.value !== null; }).forEach(function (field) {
489
- if (field.field) {
490
- condOr_1.push({ $eq: ['$' + field.field.replace(/\.\$/g, ''), null] });
491
- }
492
- else {
493
- condOr_1.push({ $eq: [field.value, null] });
494
- }
495
- });
496
- operation.fields.filter(function (a) { return a.field || a.value !== null; }).forEach(function (field) {
497
- if (field.field) {
498
- custFieldGroup[cust.selFieldId]['$' + operation.operation].push({ $cond: { if: { $or: condOr_1 }, then: 0, else: '$' + field.field.replace(/\.\$/g, '') } });
499
- }
500
- else {
501
- custFieldGroup[cust.selFieldId]['$' + operation.operation].push({ $cond: { if: { $or: condOr_1 }, then: 0, else: field.value } });
502
- }
503
- });
504
- }
505
- query_1.push({ $addFields: custFieldGroup });
506
- });
507
- });
508
- fieldsTotal.forEach(function (total) {
509
- customFields.forEach(function (field) {
510
- var _a;
511
- query_1.push({ $addFields: (_a = {}, _a[total.id + '_' + field.selFieldId] = '$' + field.selFieldId, _a) });
512
- });
513
- });
514
- queryMatchConditionLookup_1 = {
515
- $and: []
314
+ else {
315
+ if (field.leafValueType === 'Count') {
316
+ divFields.$addFields[total.id + '_' + field.id] = '$count';
317
+ }
318
+ else {
319
+ divFields.$addFields[total.id + '_' + field.id] = '$' + field.fieldPath.replace(/\.\$/g, '');
320
+ }
321
+ }
322
+ });
323
+ });
324
+ selectedFields.filter(a => a.fieldType === 'Number' && a.leafValueType === 'Sum').forEach(field => {
325
+ let multFields = [];
326
+ sizes.filter(a => !field.fieldPath.replace(/\.\$\./g, '_').replace(/\./g, '_').includes(a) && !groupsRow.some(b => b.field.replace(/\.\$\./g, '_').replace(/\./g, '_').includes(a)) && !filterArrayFields.filter(a => a.fieldPath).some(b => b.fieldPath.replace(/\.\$\./g, '_').replace(/\./g, '_').includes(a)) && !fieldsLink.some(b => b.field_first.replace(/\.\$\./g, '_').replace(/\./g, '_').includes(a) || b.field_second.replace(/\.\$\./g, '_').replace(/\./g, '_').includes(a))).forEach(size => {
327
+ multFields.push({ $cond: { if: { $gt: ['$size_' + size, 0] }, then: '$size_' + size, else: 1 } });
328
+ });
329
+ if (multFields.length) {
330
+ divFields.$addFields[field.fieldPath.replace(/\.\$/g, '')] = {
331
+ $divide: ['$' + field.fieldPath.replace(/\.\$/g, ''), { $multiply: multFields }]
332
+ };
333
+ }
334
+ });
335
+ selectedFields.filter(a => a.leafValueType === 'Count').forEach(field => {
336
+ let multFields = [];
337
+ sizes.filter(a => !field.fieldPath.replace(/\.\$\./g, '_').replace(/\./g, '_').includes(a) && !groupsRow.some(b => b.field.replace(/\.\$\./g, '_').replace(/\./g, '_').includes(a)) && !filterArrayFields.filter(a => a.fieldPath).some(b => b.fieldPath.replace(/\.\$\./g, '_').replace(/\./g, '_').includes(a)) && !fieldsLink.some(b => b.field_first.replace(/\.\$\./g, '_').replace(/\./g, '_').includes(a) || b.field_second.replace(/\.\$\./g, '_').replace(/\./g, '_').includes(a))).forEach(size => {
338
+ multFields.push({ $cond: { if: { $gt: ['$size_' + size, 0] }, then: '$size_' + size, else: 1 } });
339
+ });
340
+ if (multFields.length) {
341
+ divFields.$addFields['count_' + field.fieldPath.replace(/\.\$/g, '')] = {
342
+ $divide: ['$count', { $multiply: multFields }]
516
343
  };
517
- if (filters.filter(function (a) { return (!a['$or'] && Object.keys(a).some(function (b) { return b.includes('(Lookup)'); })) || (a['$or'] && a['$or'].some(function (b) { return Object.keys(b).some(function (c) { return c.includes('(Lookup)'); }); })); }).length) {
518
- filters.filter(function (a) { return (!a['$or'] && Object.keys(a).some(function (b) { return b.includes('(Lookup)'); })) || (a['$or'] && a['$or'].some(function (b) { return Object.keys(b).some(function (c) { return c.includes('(Lookup)'); }); })); }).forEach(function (filter) {
519
- queryMatchConditionLookup_1['$and'].push(filter);
344
+ }
345
+ else {
346
+ if (reportType !== 'Dated' && sizes.filter(a => field.fieldPath.replace(/\.\$\./g, '_').includes(a)).length) {
347
+ sizes.filter(a => field.fieldPath.replace(/\.\$\./g, '_').includes(a)).forEach(size => {
348
+ divFields.$addFields['count_' + field.fieldPath.replace(/\.\$/g, '')] = '$size_' + size;
520
349
  });
521
350
  }
522
- filterArrays.forEach(function (filter) {
523
- queryMatchConditionLookup_1['$and'].push(filter);
524
- });
525
- if (queryMatchConditionLookup_1.$and.length) {
526
- query_1.push({ $match: queryMatchConditionLookup_1 });
351
+ else {
352
+ divFields.$addFields['count_' + field.fieldPath.replace(/\.\$/g, '')] = '$count';
527
353
  }
528
- queryGroup_1 = {
529
- _id: {}
530
- };
531
- if (groupsRow.length || !displayType || displayType === 'grouped') {
532
- if (!groupsRow.length) {
533
- queryGroup_1._id = '$_id';
534
- }
535
- groupsRow.forEach(function (row) {
536
- queryGroup_1._id[row.id] = '$' + row.field.replace(/\.\$/g, '');
537
- if (date_field && date_interval) {
538
- if (date_interval === 'Daily') {
539
- queryGroup_1._id['day'] = { '$dayOfMonth': { 'date': '$' + date_field.replace(/\.\$/g, ''), 'timezone': _this.serverConfig['TIMEZONE'] } };
540
- queryGroup_1._id['month'] = { '$month': { 'date': '$' + date_field.replace(/\.\$/g, ''), 'timezone': _this.serverConfig['TIMEZONE'] } };
541
- queryGroup_1._id['year'] = { '$year': { 'date': '$' + date_field.replace(/\.\$/g, ''), 'timezone': _this.serverConfig['TIMEZONE'] } };
542
- }
543
- else if (date_interval === 'Weekly') {
544
- queryGroup_1._id['week'] = { '$isoWeek': { 'date': '$' + date_field.replace(/\.\$/g, ''), 'timezone': _this.serverConfig['TIMEZONE'] } };
545
- queryGroup_1._id['year'] = { '$isoWeekYear': { 'date': '$' + date_field.replace(/\.\$/g, ''), 'timezone': _this.serverConfig['TIMEZONE'] } };
546
- }
547
- else if (date_interval === 'Monthly') {
548
- queryGroup_1._id['month'] = { '$month': { 'date': '$' + date_field.replace(/\.\$/g, ''), 'timezone': _this.serverConfig['TIMEZONE'] } };
549
- queryGroup_1._id['year'] = { '$year': { 'date': '$' + date_field.replace(/\.\$/g, ''), 'timezone': _this.serverConfig['TIMEZONE'] } };
550
- }
551
- else if (date_interval === 'Quarterly') {
552
- queryGroup_1._id['month'] = { '$month': { 'date': '$' + date_field.replace(/\.\$/g, ''), 'timezone': _this.serverConfig['TIMEZONE'] } };
553
- queryGroup_1._id['year'] = { '$year': { 'date': '$' + date_field.replace(/\.\$/g, ''), 'timezone': _this.serverConfig['TIMEZONE'] } };
554
- }
555
- else if (date_interval === 'Yearly') {
556
- queryGroup_1._id['year'] = { '$year': { 'date': '$' + date_field.replace(/\.\$/g, ''), 'timezone': _this.serverConfig['TIMEZONE'] } };
557
- }
558
- }
559
- });
560
- selectedFields.forEach(function (field) {
561
- if (field.leafValueType === 'Average') {
562
- queryGroup_1[field.id] = { '$avg': '$' + field.fieldPath.replace(/\.\$/g, '') };
563
- }
564
- else if (field.leafValueType === 'Sum') {
565
- queryGroup_1[field.id] = { '$sum': '$' + field.fieldPath.replace(/\.\$/g, '') };
566
- }
567
- else if (field.leafValueType === 'Count') {
568
- if (reportType === 'Dated') {
569
- queryGroup_1[field.id] = { '$sum': '$count_' + field.fieldPath.replace(/\.\$/g, '') };
570
- }
571
- else {
572
- queryGroup_1[field.id] = { '$push': '$count_' + field.fieldPath.replace(/\.\$/g, '') };
573
- }
574
- }
575
- else if (field.leafValueType === 'Minimum') {
576
- queryGroup_1[field.id] = { '$min': '$' + field.fieldPath.replace(/\.\$/g, '') };
577
- }
578
- else if (field.leafValueType === 'Maximum') {
579
- queryGroup_1[field.id] = { '$max': '$' + field.fieldPath.replace(/\.\$/g, '') };
580
- }
581
- else if (field.leafValueType === 'First' || (!groupsRow.length && (!field.fieldPath.includes('.$') || field.fieldPath.includes('(Lookup)')))) {
582
- queryGroup_1[field.id] = { '$first': '$' + field.fieldPath.replace(/\.\$/g, '') };
583
- }
584
- else if (field.leafValueType === 'Last') {
585
- queryGroup_1[field.id] = { '$last': '$' + field.fieldPath.replace(/\.\$/g, '') };
586
- }
587
- else if (field.leafValueType === 'Unique') {
588
- queryGroup_1[field.id] = { '$addToSet': '$' + field.fieldPath.replace(/\.\$/g, '') };
354
+ }
355
+ });
356
+ fieldsTotal.filter(a => a.type === 'avg').forEach(total => {
357
+ selectedFields.filter(a => a.fieldType === 'Number' || a.leafValueType === 'Count').forEach(field => {
358
+ divFields.$addFields[total.id + '_' + field.id] = '$' + field.fieldPath.replace(/\.\$/g, '');
359
+ });
360
+ });
361
+ if (Object.keys(divFields.$addFields).length > 0) {
362
+ query.push(divFields);
363
+ }
364
+ fieldsLink.filter(a => a.field_first && a.field_second).forEach(link => {
365
+ query.push({ $addFields: { [link.id]: { $cmp: ['$' + link.field_first.replace(/\.\$/g, ''), '$' + link.field_second.replace(/\.\$/g, '')] } } });
366
+ query.push({ $match: { [link.id]: 0 } });
367
+ });
368
+ customFields.forEach(cust => {
369
+ cust.operations.filter(a => a.operation && !a.fields.some(b => (b.field === null || b.field === '') && b.value === null)).forEach((operation, opIndex) => {
370
+ let custFieldGroup = {};
371
+ if (operation.operation === 'divide') {
372
+ let condCheck = [];
373
+ operation.fields.filter(a => a.field || a.value !== null).forEach(field => {
374
+ if (field.field) {
375
+ condCheck.push({ $eq: ['$' + field.field.replace(/\.\$/g, ''), 0] });
376
+ condCheck.push({ $eq: ['$' + field.field.replace(/\.\$/g, ''), null] });
589
377
  }
590
378
  else {
591
- queryGroup_1[field.id] = { '$push': '$' + field.fieldPath.replace(/\.\$/g, '') };
379
+ condCheck.push({ $eq: [field.value, 0] });
380
+ condCheck.push({ $eq: [field.value, null] });
592
381
  }
593
382
  });
594
- customFields.forEach(function (cust) {
595
- if (cust.leafValueType === 'Average') {
596
- queryGroup_1[cust.selFieldId] = { '$avg': '$' + cust.selFieldId };
597
- }
598
- else if (cust.leafValueType === 'Sum') {
599
- queryGroup_1[cust.selFieldId] = { '$sum': '$' + cust.selFieldId };
600
- }
601
- else if (cust.leafValueType === 'Count') {
602
- if (reportType === 'Dated') {
603
- queryGroup_1[cust.selFieldId] = { '$sum': '$count_' + cust.selFieldId };
604
- }
605
- else {
606
- queryGroup_1[cust.selFieldId] = { '$push': '$count_' + cust.selFieldId };
607
- }
608
- }
609
- else if (cust.leafValueType === 'Minimum') {
610
- queryGroup_1[cust.selFieldId] = { '$min': '$' + cust.selFieldId };
611
- }
612
- else if (cust.leafValueType === 'Maximum') {
613
- queryGroup_1[cust.selFieldId] = { '$max': '$' + cust.selFieldId };
614
- }
615
- else if (cust.leafValueType === 'First') {
616
- queryGroup_1[cust.selFieldId] = { '$first': '$' + cust.selFieldId };
617
- }
618
- else if (cust.leafValueType === 'Last') {
619
- queryGroup_1[cust.selFieldId] = { '$last': '$' + cust.selFieldId };
620
- }
621
- else if (cust.leafValueType === 'Unique') {
622
- queryGroup_1[cust.selFieldId] = { '$addToSet': '$' + cust.selFieldId };
383
+ if (opIndex > 0) {
384
+ condCheck.push({ $eq: ['$' + cust.selFieldId, 0] });
385
+ condCheck.push({ $eq: ['$' + cust.selFieldId, null] });
386
+ }
387
+ let tmpOperationFields = [];
388
+ if (opIndex > 0) {
389
+ tmpOperationFields.push('$' + cust.selFieldId);
390
+ }
391
+ operation.fields.filter(a => a.field || a.value !== null).forEach(field => {
392
+ if (field.field) {
393
+ tmpOperationFields.push('$' + field.field.replace(/\.\$/g, ''));
623
394
  }
624
395
  else {
625
- queryGroup_1[cust.selFieldId] = { '$push': '$' + cust.selFieldId };
396
+ tmpOperationFields.push(field.value);
626
397
  }
627
398
  });
628
- // Totals
629
- if (fieldsTotal.length) {
630
- fieldsTotal.forEach(function (total) {
631
- selectedFields.filter(function (a) { return a.fieldType === 'Number' || a.leafValueType === 'Count'; }).forEach(function (field) {
632
- queryGroup_1[total.id + '_' + field.id] = { $sum: '$' + total.id + '_' + field.id };
633
- });
634
- customFields.forEach(function (field) {
635
- queryGroup_1[total.id + '_' + field.selFieldId] = { $sum: '$' + total.id + '_' + field.selFieldId };
636
- });
637
- });
638
- }
639
- query_1.push({ $group: queryGroup_1 });
399
+ custFieldGroup[cust.selFieldId] = {
400
+ $cond: { if: { $or: condCheck }, then: 0, else: { ['$' + operation.operation]: tmpOperationFields } }
401
+ };
640
402
  }
641
403
  else {
642
- queryProjection_1 = {
643
- _id: 1
404
+ custFieldGroup[cust.selFieldId] = {
405
+ ['$' + operation.operation]: []
644
406
  };
645
- selectedFields.forEach(function (field) {
646
- if (field.leafValueType === 'Average') {
647
- queryProjection_1[field.id] = { $avg: '$' + field.fieldPath.replace(/\.\$/g, '') };
648
- }
649
- else if (field.leafValueType === 'Sum') {
650
- queryProjection_1[field.id] = { $sum: '$' + field.fieldPath.replace(/\.\$/g, '') };
651
- }
652
- else if (field.leafValueType === 'Count') {
653
- queryProjection_1[field.id] = { $sum: 1 };
654
- }
655
- else if (field.leafValueType === 'Minimum') {
656
- queryProjection_1[field.id] = { $min: '$' + field.fieldPath.replace(/\.\$/g, '') };
657
- }
658
- else if (field.leafValueType === 'Maximum') {
659
- queryProjection_1[field.id] = { $max: '$' + field.fieldPath.replace(/\.\$/g, '') };
407
+ if (opIndex > 0) {
408
+ custFieldGroup[cust.selFieldId]['$' + operation.operation].push({ $cond: { if: { $eq: ['$' + cust.selFieldId, null] }, then: 0, else: '$' + cust.selFieldId } });
409
+ }
410
+ let condOr = [];
411
+ operation.fields.filter(a => a.field || a.value !== null).forEach(field => {
412
+ if (field.field) {
413
+ condOr.push({ $eq: ['$' + field.field.replace(/\.\$/g, ''), null] });
660
414
  }
661
415
  else {
662
- queryProjection_1[field.id] = '$' + field.fieldPath.replace(/\.\$/g, '');
416
+ condOr.push({ $eq: [field.value, null] });
663
417
  }
664
418
  });
665
- customFields.forEach(function (cust) {
666
- if (cust === 'Average') {
667
- queryProjection_1[cust.selFieldId] = { $avg: '$' + cust.selFieldId };
668
- }
669
- else if (cust === 'Sum') {
670
- queryProjection_1[cust.selFieldId] = { $sum: '$' + cust.selFieldId };
671
- }
672
- else if (cust === 'Count') {
673
- queryProjection_1[cust.selFieldId] = { $sum: 1 };
674
- }
675
- else if (cust === 'Minimum') {
676
- queryProjection_1[cust.selFieldId] = { $min: '$' + cust.selFieldId };
677
- }
678
- else if (cust === 'Maximum') {
679
- queryProjection_1[cust.selFieldId] = { $max: '$' + cust.selFieldId };
419
+ operation.fields.filter(a => a.field || a.value !== null).forEach(field => {
420
+ if (field.field) {
421
+ custFieldGroup[cust.selFieldId]['$' + operation.operation].push({ $cond: { if: { $or: condOr }, then: 0, else: '$' + field.field.replace(/\.\$/g, '') } });
680
422
  }
681
423
  else {
682
- queryProjection_1[cust.selFieldId] = '$' + cust.selFieldId;
424
+ custFieldGroup[cust.selFieldId]['$' + operation.operation].push({ $cond: { if: { $or: condOr }, then: 0, else: field.value } });
683
425
  }
684
426
  });
685
- //Totals
686
- if (fieldsTotal.length && (reportType === 'List' || reportType === 'Dated')) {
687
- fieldsTotal.forEach(function (total) {
688
- selectedFields.filter(function (a) { return a.fieldType === 'Number' || a.leafValueType === 'Count'; }).forEach(function (field) {
689
- var _a;
690
- queryProjection_1[total.id + '_' + field.id] = (_a = {}, _a['$' + total.type] = '$' + total.id + '_' + field.id, _a);
691
- });
692
- customFields.forEach(function (field) {
693
- var _a;
694
- queryProjection_1[total.id + '_' + field.selFieldId] = (_a = {}, _a['$' + total.type] = '$' + total.id + '_' + field.selFieldId, _a);
695
- });
696
- });
427
+ }
428
+ query.push({ $addFields: custFieldGroup });
429
+ });
430
+ });
431
+ fieldsTotal.forEach(total => {
432
+ customFields.forEach(field => {
433
+ query.push({ $addFields: { [total.id + '_' + field.selFieldId]: '$' + field.selFieldId } });
434
+ });
435
+ });
436
+ // Filters - Lookups / Arrays
437
+ let queryMatchConditionLookup = {
438
+ $and: []
439
+ };
440
+ if (filters.filter(a => (!a['$or'] && Object.keys(a).some(b => b.includes('(Lookup)'))) || (a['$or'] && a['$or'].some(b => Object.keys(b).some(c => c.includes('(Lookup)'))))).length) {
441
+ filters.filter(a => (!a['$or'] && Object.keys(a).some(b => b.includes('(Lookup)'))) || (a['$or'] && a['$or'].some(b => Object.keys(b).some(c => c.includes('(Lookup)'))))).forEach(filter => {
442
+ queryMatchConditionLookup['$and'].push(filter);
443
+ });
444
+ }
445
+ filterArrays.forEach(filter => {
446
+ queryMatchConditionLookup['$and'].push(filter);
447
+ });
448
+ if (queryMatchConditionLookup.$and.length) {
449
+ query.push({ $match: queryMatchConditionLookup });
450
+ }
451
+ // Group
452
+ let queryGroup = {
453
+ _id: {}
454
+ };
455
+ if (groupsRow.length || !displayType || displayType === 'grouped') {
456
+ if (!groupsRow.length) {
457
+ queryGroup._id = '$_id';
458
+ }
459
+ groupsRow.forEach(row => {
460
+ queryGroup._id[row.id] = '$' + row.field.replace(/\.\$/g, '');
461
+ if (date_field && date_interval) {
462
+ if (date_interval === 'Daily') {
463
+ queryGroup._id['day'] = { '$dayOfMonth': { 'date': '$' + date_field.replace(/\.\$/g, ''), 'timezone': this.serverConfig['TIMEZONE'] } };
464
+ queryGroup._id['month'] = { '$month': { 'date': '$' + date_field.replace(/\.\$/g, ''), 'timezone': this.serverConfig['TIMEZONE'] } };
465
+ queryGroup._id['year'] = { '$year': { 'date': '$' + date_field.replace(/\.\$/g, ''), 'timezone': this.serverConfig['TIMEZONE'] } };
466
+ }
467
+ else if (date_interval === 'Weekly') {
468
+ queryGroup._id['week'] = { '$isoWeek': { 'date': '$' + date_field.replace(/\.\$/g, ''), 'timezone': this.serverConfig['TIMEZONE'] } };
469
+ queryGroup._id['year'] = { '$isoWeekYear': { 'date': '$' + date_field.replace(/\.\$/g, ''), 'timezone': this.serverConfig['TIMEZONE'] } };
470
+ }
471
+ else if (date_interval === 'Monthly') {
472
+ queryGroup._id['month'] = { '$month': { 'date': '$' + date_field.replace(/\.\$/g, ''), 'timezone': this.serverConfig['TIMEZONE'] } };
473
+ queryGroup._id['year'] = { '$year': { 'date': '$' + date_field.replace(/\.\$/g, ''), 'timezone': this.serverConfig['TIMEZONE'] } };
474
+ }
475
+ else if (date_interval === 'Quarterly') {
476
+ queryGroup._id['month'] = { '$month': { 'date': '$' + date_field.replace(/\.\$/g, ''), 'timezone': this.serverConfig['TIMEZONE'] } };
477
+ queryGroup._id['year'] = { '$year': { 'date': '$' + date_field.replace(/\.\$/g, ''), 'timezone': this.serverConfig['TIMEZONE'] } };
478
+ }
479
+ else if (date_interval === 'Yearly') {
480
+ queryGroup._id['year'] = { '$year': { 'date': '$' + date_field.replace(/\.\$/g, ''), 'timezone': this.serverConfig['TIMEZONE'] } };
697
481
  }
698
- query_1.push({ $project: queryProjection_1 });
699
482
  }
700
- // SORT
701
- if (rootOptions.sort) {
702
- query_1.push({
703
- $sort: rootOptions.sort
483
+ });
484
+ selectedFields.forEach(field => {
485
+ if (field.leafValueType === 'Average') {
486
+ queryGroup[field.id] = { '$avg': '$' + field.fieldPath.replace(/\.\$/g, '') };
487
+ }
488
+ else if (field.leafValueType === 'Sum') {
489
+ queryGroup[field.id] = { '$sum': '$' + field.fieldPath.replace(/\.\$/g, '') };
490
+ }
491
+ else if (field.leafValueType === 'Count') {
492
+ if (reportType === 'Dated') {
493
+ queryGroup[field.id] = { '$sum': '$count_' + field.fieldPath.replace(/\.\$/g, '') };
494
+ }
495
+ else {
496
+ queryGroup[field.id] = { '$push': '$count_' + field.fieldPath.replace(/\.\$/g, '') };
497
+ }
498
+ }
499
+ else if (field.leafValueType === 'Minimum') {
500
+ queryGroup[field.id] = { '$min': '$' + field.fieldPath.replace(/\.\$/g, '') };
501
+ }
502
+ else if (field.leafValueType === 'Maximum') {
503
+ queryGroup[field.id] = { '$max': '$' + field.fieldPath.replace(/\.\$/g, '') };
504
+ }
505
+ else if (field.leafValueType === 'First' || (!groupsRow.length && (!field.fieldPath.includes('.$') || field.fieldPath.includes('(Lookup)')))) {
506
+ queryGroup[field.id] = { '$first': '$' + field.fieldPath.replace(/\.\$/g, '') };
507
+ }
508
+ else if (field.leafValueType === 'Last') {
509
+ queryGroup[field.id] = { '$last': '$' + field.fieldPath.replace(/\.\$/g, '') };
510
+ }
511
+ else if (field.leafValueType === 'Unique') {
512
+ queryGroup[field.id] = { '$addToSet': '$' + field.fieldPath.replace(/\.\$/g, '') };
513
+ }
514
+ else {
515
+ queryGroup[field.id] = { '$push': '$' + field.fieldPath.replace(/\.\$/g, '') };
516
+ }
517
+ });
518
+ customFields.forEach(cust => {
519
+ if (cust.leafValueType === 'Average') {
520
+ queryGroup[cust.selFieldId] = { '$avg': '$' + cust.selFieldId };
521
+ }
522
+ else if (cust.leafValueType === 'Sum') {
523
+ queryGroup[cust.selFieldId] = { '$sum': '$' + cust.selFieldId };
524
+ }
525
+ else if (cust.leafValueType === 'Count') {
526
+ if (reportType === 'Dated') {
527
+ queryGroup[cust.selFieldId] = { '$sum': '$count_' + cust.selFieldId };
528
+ }
529
+ else {
530
+ queryGroup[cust.selFieldId] = { '$push': '$count_' + cust.selFieldId };
531
+ }
532
+ }
533
+ else if (cust.leafValueType === 'Minimum') {
534
+ queryGroup[cust.selFieldId] = { '$min': '$' + cust.selFieldId };
535
+ }
536
+ else if (cust.leafValueType === 'Maximum') {
537
+ queryGroup[cust.selFieldId] = { '$max': '$' + cust.selFieldId };
538
+ }
539
+ else if (cust.leafValueType === 'First') {
540
+ queryGroup[cust.selFieldId] = { '$first': '$' + cust.selFieldId };
541
+ }
542
+ else if (cust.leafValueType === 'Last') {
543
+ queryGroup[cust.selFieldId] = { '$last': '$' + cust.selFieldId };
544
+ }
545
+ else if (cust.leafValueType === 'Unique') {
546
+ queryGroup[cust.selFieldId] = { '$addToSet': '$' + cust.selFieldId };
547
+ }
548
+ else {
549
+ queryGroup[cust.selFieldId] = { '$push': '$' + cust.selFieldId };
550
+ }
551
+ });
552
+ // Totals
553
+ if (fieldsTotal.length) {
554
+ fieldsTotal.forEach(total => {
555
+ selectedFields.filter(a => a.fieldType === 'Number' || a.leafValueType === 'Count').forEach(field => {
556
+ queryGroup[total.id + '_' + field.id] = { $sum: '$' + total.id + '_' + field.id };
557
+ });
558
+ customFields.forEach(field => {
559
+ queryGroup[total.id + '_' + field.selFieldId] = { $sum: '$' + total.id + '_' + field.selFieldId };
704
560
  });
561
+ });
562
+ }
563
+ query.push({ $group: queryGroup });
564
+ }
565
+ else {
566
+ //Projection
567
+ let queryProjection = {
568
+ _id: 1
569
+ };
570
+ selectedFields.forEach(field => {
571
+ if (field.leafValueType === 'Average') {
572
+ queryProjection[field.id] = { $avg: '$' + field.fieldPath.replace(/\.\$/g, '') };
705
573
  }
706
- if (reportType === 'Group' && groupsRow.length > 1) {
707
- _loop_1 = function (i) {
708
- var _a;
709
- var projQuery = { _id: 1 };
710
- projQuery[groupsRow[i].id] = {
711
- _id: (_a = {}, _a[groupsRow[i].id] = '$_id.' + groupsRow[i].id, _a)
712
- };
713
- if (i === groupsRow.length - 1) {
714
- selectedFields.forEach(function (field) {
715
- projQuery[groupsRow[i].id][field.id] = '$' + field.id;
716
- });
717
- customFields.forEach(function (field) {
718
- projQuery[groupsRow[i].id][field.selFieldId] = '$' + field.selFieldId;
719
- });
720
- }
721
- else {
722
- projQuery[groupsRow[i].id][groupsRow[i + 1].id] = '$' + groupsRow[i + 1].id;
574
+ else if (field.leafValueType === 'Sum') {
575
+ queryProjection[field.id] = { $sum: '$' + field.fieldPath.replace(/\.\$/g, '') };
576
+ }
577
+ else if (field.leafValueType === 'Count') {
578
+ queryProjection[field.id] = { $sum: 1 };
579
+ }
580
+ else if (field.leafValueType === 'Minimum') {
581
+ queryProjection[field.id] = { $min: '$' + field.fieldPath.replace(/\.\$/g, '') };
582
+ }
583
+ else if (field.leafValueType === 'Maximum') {
584
+ queryProjection[field.id] = { $max: '$' + field.fieldPath.replace(/\.\$/g, '') };
585
+ }
586
+ else {
587
+ queryProjection[field.id] = '$' + field.fieldPath.replace(/\.\$/g, '');
588
+ }
589
+ });
590
+ customFields.forEach(cust => {
591
+ if (cust === 'Average') {
592
+ queryProjection[cust.selFieldId] = { $avg: '$' + cust.selFieldId };
593
+ }
594
+ else if (cust === 'Sum') {
595
+ queryProjection[cust.selFieldId] = { $sum: '$' + cust.selFieldId };
596
+ }
597
+ else if (cust === 'Count') {
598
+ queryProjection[cust.selFieldId] = { $sum: 1 };
599
+ }
600
+ else if (cust === 'Minimum') {
601
+ queryProjection[cust.selFieldId] = { $min: '$' + cust.selFieldId };
602
+ }
603
+ else if (cust === 'Maximum') {
604
+ queryProjection[cust.selFieldId] = { $max: '$' + cust.selFieldId };
605
+ }
606
+ else {
607
+ queryProjection[cust.selFieldId] = '$' + cust.selFieldId;
608
+ }
609
+ });
610
+ //Totals
611
+ if (fieldsTotal.length && (reportType === 'List' || reportType === 'Dated')) {
612
+ fieldsTotal.forEach(total => {
613
+ selectedFields.filter(a => a.fieldType === 'Number' || a.leafValueType === 'Count').forEach(field => {
614
+ queryProjection[total.id + '_' + field.id] = { ['$' + total.type]: '$' + total.id + '_' + field.id };
615
+ });
616
+ customFields.forEach(field => {
617
+ queryProjection[total.id + '_' + field.selFieldId] = { ['$' + total.type]: '$' + total.id + '_' + field.selFieldId };
618
+ });
619
+ });
620
+ }
621
+ query.push({ $project: queryProjection });
622
+ }
623
+ // SORT
624
+ if (rootOptions.sort) {
625
+ query.push({
626
+ $sort: rootOptions.sort
627
+ });
628
+ }
629
+ if (reportType === 'Group' && groupsRow.length > 1) {
630
+ for (let i = groupsRow.length - 1; i >= 1; i--) {
631
+ let projQuery = { _id: 1 };
632
+ projQuery[groupsRow[i].id] = {
633
+ _id: { [groupsRow[i].id]: '$_id.' + groupsRow[i].id }
634
+ };
635
+ if (i === groupsRow.length - 1) {
636
+ selectedFields.forEach(field => {
637
+ projQuery[groupsRow[i].id][field.id] = '$' + field.id;
638
+ });
639
+ customFields.forEach(field => {
640
+ projQuery[groupsRow[i].id][field.selFieldId] = '$' + field.selFieldId;
641
+ });
642
+ }
643
+ else {
644
+ projQuery[groupsRow[i].id][groupsRow[i + 1].id] = '$' + groupsRow[i + 1].id;
645
+ }
646
+ fieldsTotal.forEach(totField => {
647
+ selectedFields.filter(b => b.fieldType === 'Number' || b.leafValueType === 'Count').forEach(selField => {
648
+ projQuery[totField.id + '_' + selField.id] = 1;
649
+ projQuery[groupsRow[i].id][totField.id + '_' + selField.id] = '$' + totField.id + '_' + selField.id;
650
+ });
651
+ customFields.forEach(field => {
652
+ projQuery[groupsRow[i].id][totField.id + '_' + field.selFieldId] = '$' + totField.id + '_' + field.selFieldId;
653
+ });
654
+ });
655
+ query.push({ $project: projQuery });
656
+ let grQuery = {
657
+ _id: {}
658
+ };
659
+ for (let j = 0; j < i; j++) {
660
+ grQuery._id[groupsRow[j].id] = '$_id.' + groupsRow[j].id;
661
+ }
662
+ grQuery[groupsRow[i].id] = {
663
+ $push: '$' + groupsRow[i].id
664
+ };
665
+ fieldsTotal.forEach(totField => {
666
+ selectedFields.filter(b => b.fieldType === 'Number' || b.leafValueType === 'Count').forEach(selField => {
667
+ grQuery[totField.id + '_' + selField.id] = { ['$' + totField.type]: '$' + totField.id + '_' + selField.id };
668
+ });
669
+ customFields.forEach(field => {
670
+ grQuery[totField.id + '_' + field.selFieldId] = { ['$' + totField.type]: '$' + totField.id + '_' + field.selFieldId };
671
+ });
672
+ });
673
+ query.push({ $group: grQuery });
674
+ if (rootOptions.sort) {
675
+ let sortKeys = Object.keys(rootOptions.sort);
676
+ let sort = {};
677
+ let groupString = '';
678
+ groupsRow.forEach((row, groupIndex) => {
679
+ if (groupIndex > 0) {
680
+ groupString += 'gr_' + (groupIndex + 1) + '.';
723
681
  }
724
- fieldsTotal.forEach(function (totField) {
725
- selectedFields.filter(function (b) { return b.fieldType === 'Number' || b.leafValueType === 'Count'; }).forEach(function (selField) {
726
- projQuery[totField.id + '_' + selField.id] = 1;
727
- projQuery[groupsRow[i].id][totField.id + '_' + selField.id] = '$' + totField.id + '_' + selField.id;
728
- });
729
- customFields.forEach(function (field) {
730
- projQuery[groupsRow[i].id][totField.id + '_' + field.selFieldId] = '$' + totField.id + '_' + field.selFieldId;
731
- });
732
- });
733
- query_1.push({ $project: projQuery });
734
- var grQuery = {
735
- _id: {}
736
- };
737
- for (var j = 0; j < i; j++) {
738
- grQuery._id[groupsRow[j].id] = '$_id.' + groupsRow[j].id;
682
+ if (sortKeys.includes('_id.gr_' + (groupIndex + 1))) {
683
+ sort[groupString + '_id.gr_' + (groupIndex + 1)] = rootOptions.sort['_id.gr_' + (groupIndex + 1)];
739
684
  }
740
- grQuery[groupsRow[i].id] = {
741
- $push: '$' + groupsRow[i].id
742
- };
743
- fieldsTotal.forEach(function (totField) {
744
- selectedFields.filter(function (b) { return b.fieldType === 'Number' || b.leafValueType === 'Count'; }).forEach(function (selField) {
745
- var _a;
746
- grQuery[totField.id + '_' + selField.id] = (_a = {}, _a['$' + totField.type] = '$' + totField.id + '_' + selField.id, _a);
747
- });
748
- customFields.forEach(function (field) {
749
- var _a;
750
- grQuery[totField.id + '_' + field.selFieldId] = (_a = {}, _a['$' + totField.type] = '$' + totField.id + '_' + field.selFieldId, _a);
751
- });
752
- });
753
- query_1.push({ $group: grQuery });
754
- if (rootOptions.sort) {
755
- var sortKeys_1 = Object.keys(rootOptions.sort);
756
- var sort_1 = {};
757
- var groupString_1 = '';
758
- groupsRow.forEach(function (row, groupIndex) {
759
- if (groupIndex > 0) {
760
- groupString_1 += 'gr_' + (groupIndex + 1) + '.';
761
- }
762
- if (sortKeys_1.includes('_id.gr_' + (groupIndex + 1))) {
763
- sort_1[groupString_1 + '_id.gr_' + (groupIndex + 1)] = rootOptions.sort['_id.gr_' + (groupIndex + 1)];
764
- }
765
- else {
766
- sort_1[groupString_1 + '_id.gr_' + (groupIndex + 1)] = 1;
767
- }
768
- });
769
- sortKeys_1.filter(function (a) { return !a.startsWith('_id.gr_'); }).forEach(function (key) {
770
- sort_1[groupString_1 + key] = rootOptions.sort[key];
771
- });
772
- query_1.push({ $sort: sort_1 });
685
+ else {
686
+ sort[groupString + '_id.gr_' + (groupIndex + 1)] = 1;
773
687
  }
774
- };
775
- for (i = groupsRow.length - 1; i >= 1; i--) {
776
- _loop_1(i);
777
- }
778
- }
779
- res_1 = null;
780
- _a.label = 2;
781
- case 2:
782
- _a.trys.push([2, 4, , 5]);
783
- return [4 /*yield*/, modelCollection.aggregate(query_1, { allowDiskUse: true })];
784
- case 3:
785
- res_1 = _a.sent();
786
- return [3 /*break*/, 5];
787
- case 4:
788
- err_1 = _a.sent();
789
- console.log(err_1);
790
- return [3 /*break*/, 5];
791
- case 5:
792
- tmpTotals_1 = {};
793
- if (res_1) {
794
- fieldsTotal.forEach(function (totField) {
795
- selectedFields.filter(function (b) { return b.fieldType === 'Number' || b.leafValueType === 'Count'; }).forEach(function (selField) {
796
- if (totField.type === 'sum') {
797
- tmpTotals_1[totField.id + '_' + selField.id] = res_1.map(function (a) { return a[totField.id + '_' + selField.id] || 0; }).reduce(function (a, b) { return a + b; }, 0);
798
- }
799
- else if (totField.type === 'avg') {
800
- tmpTotals_1[totField.id + '_' + selField.id] = Math.round(res_1.map(function (a) { return a[totField.id + '_' + selField.id] || 0; }).reduce(function (a, b) { return a + b; }, 0) / res_1.length);
801
- }
802
- });
803
- customFields.forEach(function (custField) {
804
- if (totField.type === 'sum') {
805
- tmpTotals_1[totField.id + '_' + custField.selFieldId] = res_1.map(function (a) { return a[totField.id + '_' + custField.selFieldId] || 0; }).reduce(function (a, b) { return a + b; }, 0);
806
- }
807
- else if (totField.type === 'avg') {
808
- tmpTotals_1[totField.id + '_' + custField.selFieldId] = Math.round(res_1.map(function (a) { return a[totField.id + '_' + custField.selFieldId] || 0; }).reduce(function (a, b) { return a + b; }, 0) / res_1.length);
809
- }
810
- });
811
688
  });
689
+ sortKeys.filter(a => !a.startsWith('_id.gr_')).forEach(key => {
690
+ sort[groupString + key] = rootOptions.sort[key];
691
+ });
692
+ query.push({ $sort: sort });
812
693
  }
813
- tmpRes = [{
814
- count: res_1 ? res_1.length : 0,
815
- results: res_1 ? (rootOptions.limit ? res_1.splice(0, rootOptions.limit) : res_1) : [],
816
- totals: tmpTotals_1
817
- }];
818
- resolve(tmpRes);
819
- _a.label = 6;
820
- case 6: return [2 /*return*/];
694
+ }
821
695
  }
822
- });
823
- }); });
696
+ // console.log('_____________ query __________'); console.log(query); console.log(JSON.stringify(query, null, 2));
697
+ let res = null;
698
+ try {
699
+ res = await modelCollection.aggregate(query, { allowDiskUse: true });
700
+ }
701
+ catch (err) {
702
+ console.log(err);
703
+ }
704
+ let tmpTotals = {};
705
+ if (res) {
706
+ fieldsTotal.forEach(totField => {
707
+ selectedFields.filter(b => b.fieldType === 'Number' || b.leafValueType === 'Count').forEach(selField => {
708
+ if (totField.type === 'sum') {
709
+ tmpTotals[totField.id + '_' + selField.id] = res.map(a => a[totField.id + '_' + selField.id] || 0).reduce((a, b) => a + b, 0);
710
+ }
711
+ else if (totField.type === 'avg') {
712
+ tmpTotals[totField.id + '_' + selField.id] = Math.round(res.map(a => a[totField.id + '_' + selField.id] || 0).reduce((a, b) => a + b, 0) / res.length);
713
+ }
714
+ });
715
+ customFields.forEach(custField => {
716
+ if (totField.type === 'sum') {
717
+ tmpTotals[totField.id + '_' + custField.selFieldId] = res.map(a => a[totField.id + '_' + custField.selFieldId] || 0).reduce((a, b) => a + b, 0);
718
+ }
719
+ else if (totField.type === 'avg') {
720
+ tmpTotals[totField.id + '_' + custField.selFieldId] = Math.round(res.map(a => a[totField.id + '_' + custField.selFieldId] || 0).reduce((a, b) => a + b, 0) / res.length);
721
+ }
722
+ });
723
+ });
724
+ }
725
+ let tmpRes = [{
726
+ count: res ? res.length : 0,
727
+ results: res ? (rootOptions.limit ? res.splice(0, rootOptions.limit) : res) : [],
728
+ totals: tmpTotals
729
+ }];
730
+ resolve(tmpRes);
731
+ }
732
+ });
824
733
  },
825
734
  }
826
735
  });
827
736
  }
828
- exports.loadReportBuilderMethods = loadReportBuilderMethods;
829
737
 
830
738
  //# sourceMappingURL=report-builder.js.map