@resolveio/server-lib 4.3.15 → 4.4.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.
@@ -37,8 +37,12 @@ var __generator = (this && this.__generator) || function (thisArg, body) {
37
37
  Object.defineProperty(exports, "__esModule", { value: true });
38
38
  var queue_method_collection_1 = require("../collections/queue-method.collection");
39
39
  var user_collection_1 = require("../collections/user.collection");
40
+ var report_builder_report_collection_1 = require("../collections/report-builder-report.collection");
40
41
  var simpl_schema_1 = require("simpl-schema");
41
42
  var mongoose_1 = require("mongoose");
43
+ var common_1 = require("../util/common");
44
+ var moment = require("moment");
45
+ var json2csv_1 = require("json2csv");
42
46
  function loadCronJobMethods(methodManager) {
43
47
  methodManager.methods({
44
48
  methodQueue: {
@@ -126,6 +130,700 @@ function loadCronJobMethods(methodManager) {
126
130
  resolve();
127
131
  });
128
132
  }
133
+ },
134
+ reportbuilderCronJob: {
135
+ skipQueue: true,
136
+ check: new simpl_schema_1.default({
137
+ data: {
138
+ type: Object,
139
+ blackbox: true
140
+ }
141
+ }),
142
+ function: function (data) {
143
+ var _this = this;
144
+ return new Promise(function (resolve, reject) { return __awaiter(_this, void 0, void 0, function () {
145
+ var report, fieldsObj_1, count_1, sortObj_1, rootOptions, filters_1, filterArrays_1;
146
+ var _this = this;
147
+ return __generator(this, function (_a) {
148
+ switch (_a.label) {
149
+ case 0: return [4 /*yield*/, report_builder_report_collection_1.ReportBuilderReports.findById(data['id_report'])];
150
+ case 1:
151
+ report = _a.sent();
152
+ report.fields_selected.forEach(function (field) {
153
+ var _a, _b;
154
+ var dotPath = field.fieldPath.replace(/\.\$/g, '');
155
+ var fieldData = dotPath.split('.');
156
+ field.fieldPathObj = null;
157
+ for (var i = fieldData.length - 1; i >= 0; i--) {
158
+ if (!field.fieldPathObj) {
159
+ field.fieldPathObj = (_a = {}, _a[fieldData[i]] = 1, _a);
160
+ }
161
+ else {
162
+ field.fieldPathObj = (_b = {}, _b[fieldData[i]] = field.fieldPathObj, _b);
163
+ }
164
+ }
165
+ });
166
+ if ((report.fields_selected && report.fields_selected.length) || (report.groups_row && report.groups_row.length)) {
167
+ fieldsObj_1 = {};
168
+ count_1 = 0;
169
+ report.fields_selected.forEach(function (field) {
170
+ if (field.collection_name === report.collection_root) {
171
+ fieldsObj_1 = common_1.mergeDeep(fieldsObj_1, field.fieldPathObj);
172
+ }
173
+ var sortIndex = report.fields_sort.findIndex(function (a) { return a.field === field['id']; });
174
+ if (sortIndex >= 0) {
175
+ report.fields_sort[sortIndex].field = ('f_' + count_1);
176
+ }
177
+ field['id'] = 'f_' + count_1;
178
+ count_1 += 1;
179
+ });
180
+ sortObj_1 = {};
181
+ if (report.fields_sort.length) {
182
+ report.fields_sort.forEach(function (sortField) {
183
+ if (sortField.field.startsWith('gr_') && (report.type === 'Tabular' || report.type === 'Dated')) {
184
+ sortObj_1['_id.' + sortField.field] = (sortField.order === 'asc' ? 1 : -1);
185
+ }
186
+ else {
187
+ sortObj_1[sortField.field] = (sortField.order === 'asc' ? 1 : -1);
188
+ }
189
+ });
190
+ }
191
+ else {
192
+ sortObj_1 = null;
193
+ }
194
+ rootOptions = {
195
+ limit: 0,
196
+ skip: 0,
197
+ fields: fieldsObj_1,
198
+ sort: sortObj_1
199
+ };
200
+ filters_1 = [];
201
+ report.fields_filter.filter(function (a) { return !a.field.includes('.$.'); }).forEach(function (filter) {
202
+ var _a, _b, _c, _d, _e, _f;
203
+ if (filter.condition && filter.field && filter.value !== null) {
204
+ if (filter.condition === 'bw') {
205
+ if (filter.fieldType === 'Date' && filter.is_rolling) {
206
+ var startDate = null;
207
+ var endDate = null;
208
+ if (filter.rolling_interval === 'Q1') {
209
+ startDate = moment().startOf('year').toDate();
210
+ endDate = moment().startOf('year').quarter(2).subtract(1, 'days').toDate();
211
+ }
212
+ else if (filter.rolling_interval === 'Q2') {
213
+ startDate = moment().startOf('year').quarter(2).toDate();
214
+ endDate = moment().startOf('year').quarter(3).subtract(1, 'days').toDate();
215
+ }
216
+ else if (filter.rolling_interval === 'Q3') {
217
+ startDate = moment().startOf('year').quarter(3).toDate();
218
+ endDate = moment().startOf('year').quarter(4).subtract(1, 'days').toDate();
219
+ }
220
+ else if (filter.rolling_interval === 'Q4') {
221
+ startDate = moment().startOf('year').quarter(4).toDate();
222
+ endDate = moment().endOf('year').toDate();
223
+ }
224
+ else if (filter.rolling_interval === 'Today') {
225
+ startDate = moment().startOf('day').toDate();
226
+ endDate = moment().endOf('day').toDate();
227
+ }
228
+ else if (filter.rolling_interval === 'Yesterday') {
229
+ startDate = moment().subtract(1, 'days').startOf('day').toDate();
230
+ endDate = moment().subtract(1, 'days').endOf('day').toDate();
231
+ }
232
+ else if (filter.rolling_interval === 'Week') {
233
+ startDate = moment().startOf('isoWeek').toDate();
234
+ endDate = moment().endOf('day').toDate();
235
+ }
236
+ else if (filter.rolling_interval === 'Last Week') {
237
+ endDate = moment().startOf('isoWeek').subtract(1, 'days').toDate();
238
+ startDate = moment(endDate).startOf('isoWeek').toDate();
239
+ }
240
+ else if (filter.rolling_interval === 'Month') {
241
+ startDate = moment().startOf('month').toDate();
242
+ endDate = moment().endOf('day').toDate();
243
+ }
244
+ else if (filter.rolling_interval === 'Last Month') {
245
+ endDate = moment().startOf('month').subtract(1, 'days').endOf('day').toDate();
246
+ startDate = moment(endDate).startOf('month').toDate();
247
+ }
248
+ else if (filter.rolling_interval === 'Last 30 Days') {
249
+ endDate = moment().endOf('day').toDate();
250
+ startDate = moment().subtract(30, 'days').startOf('day').toDate();
251
+ }
252
+ else if (filter.rolling_interval === 'Quarter') {
253
+ startDate = moment().startOf('year').quarter(moment().quarter()).toDate();
254
+ endDate = moment().endOf('day').toDate();
255
+ }
256
+ else if (filter.rolling_interval === 'Last Quarter') {
257
+ endDate = moment().startOf('year').quarter(moment().quarter()).subtract(1, 'days').endOf('day').toDate();
258
+ startDate = moment(endDate).startOf('quarter').toDate();
259
+ }
260
+ else if (filter.rolling_interval === 'Year') {
261
+ startDate = moment().startOf('year').toDate();
262
+ endDate = moment().endOf('day').toDate();
263
+ }
264
+ else if (filter.rolling_interval === 'Last Year') {
265
+ endDate = moment().startOf('year').subtract(1, 'days').endOf('day').toDate();
266
+ startDate = moment(endDate).startOf('year').toDate();
267
+ }
268
+ else if (filter.rolling_interval === 'All') {
269
+ startDate = new Date(2017, 0, 1, 0, 0, 0, 0);
270
+ endDate = moment().endOf('day').toDate();
271
+ }
272
+ filters_1.push((_a = {}, _a[filter.field] = { '$gte': startDate }, _a));
273
+ filters_1.push((_b = {}, _b[filter.field] = { '$lte': endDate }, _b));
274
+ }
275
+ else {
276
+ filters_1.push((_c = {}, _c[filter.field] = { '$gte': filter.value }, _c));
277
+ filters_1.push((_d = {}, _d[filter.field] = { '$lte': filter.highValue }, _d));
278
+ }
279
+ }
280
+ else {
281
+ if (Array.isArray(filter.value)) {
282
+ var or_1 = [];
283
+ filter.value.forEach(function (filt) {
284
+ var _a, _b;
285
+ or_1.push((_a = {}, _a[filter.field] = (_b = {}, _b['$' + filter.condition] = (Array.isArray(filt) ? filt[0] : filt), _b), _a));
286
+ });
287
+ filters_1.push({ $or: or_1 });
288
+ }
289
+ else {
290
+ filters_1.push((_e = {}, _e[filter.field] = (_f = {}, _f['$' + filter.condition] = filter.value, _f), _e));
291
+ }
292
+ }
293
+ }
294
+ });
295
+ filterArrays_1 = [];
296
+ report.fields_filter.filter(function (a) { return a.field.includes('.$.'); }).forEach(function (filter) {
297
+ var _a, _b, _c, _d, _e, _f;
298
+ if (filter.condition && filter.field && filter.value !== null) {
299
+ if (filter.condition === 'bw') {
300
+ if (filter.fieldType === 'Date' && filter.is_rolling) {
301
+ var startDate = null;
302
+ var endDate = null;
303
+ if (filter.rolling_interval === 'Q1') {
304
+ startDate = moment().startOf('year').toDate();
305
+ endDate = moment().startOf('year').quarter(2).subtract(1, 'days').toDate();
306
+ }
307
+ else if (filter.rolling_interval === 'Q2') {
308
+ startDate = moment().startOf('year').quarter(2).toDate();
309
+ endDate = moment().startOf('year').quarter(3).subtract(1, 'days').toDate();
310
+ }
311
+ else if (filter.rolling_interval === 'Q3') {
312
+ startDate = moment().startOf('year').quarter(3).toDate();
313
+ endDate = moment().startOf('year').quarter(4).subtract(1, 'days').toDate();
314
+ }
315
+ else if (filter.rolling_interval === 'Q4') {
316
+ startDate = moment().startOf('year').quarter(4).toDate();
317
+ endDate = moment().endOf('year').toDate();
318
+ }
319
+ else if (filter.rolling_interval === 'Today') {
320
+ startDate = moment().startOf('day').toDate();
321
+ endDate = moment().endOf('day').toDate();
322
+ }
323
+ else if (filter.rolling_interval === 'Yesterday') {
324
+ startDate = moment().subtract(1, 'days').startOf('day').toDate();
325
+ endDate = moment().subtract(1, 'days').endOf('day').toDate();
326
+ }
327
+ else if (filter.rolling_interval === 'Week') {
328
+ startDate = moment().startOf('isoWeek').toDate();
329
+ endDate = moment().endOf('day').toDate();
330
+ }
331
+ else if (filter.rolling_interval === 'Last Week') {
332
+ endDate = moment().startOf('isoWeek').subtract(1, 'days').toDate();
333
+ startDate = moment(endDate).startOf('isoWeek').toDate();
334
+ }
335
+ else if (filter.rolling_interval === 'Month') {
336
+ startDate = moment().startOf('month').toDate();
337
+ endDate = moment().endOf('day').toDate();
338
+ }
339
+ else if (filter.rolling_interval === 'Last Month') {
340
+ endDate = moment().startOf('month').subtract(1, 'days').endOf('day').toDate();
341
+ startDate = moment(endDate).startOf('month').toDate();
342
+ }
343
+ else if (filter.rolling_interval === 'Last 30 Days') {
344
+ endDate = moment().endOf('day').toDate();
345
+ startDate = moment().subtract(30, 'days').startOf('day').toDate();
346
+ }
347
+ else if (filter.rolling_interval === 'Quarter') {
348
+ startDate = moment().startOf('year').quarter(moment().quarter()).toDate();
349
+ endDate = moment().endOf('day').toDate();
350
+ }
351
+ else if (filter.rolling_interval === 'Last Quarter') {
352
+ endDate = moment().startOf('year').quarter(moment().quarter()).subtract(1, 'days').endOf('day').toDate();
353
+ startDate = moment(endDate).startOf('quarter').toDate();
354
+ }
355
+ else if (filter.rolling_interval === 'Year') {
356
+ startDate = moment().startOf('year').toDate();
357
+ endDate = moment().endOf('day').toDate();
358
+ }
359
+ else if (filter.rolling_interval === 'Last Year') {
360
+ endDate = moment().startOf('year').subtract(1, 'days').endOf('day').toDate();
361
+ startDate = moment(endDate).startOf('year').toDate();
362
+ }
363
+ else if (filter.rolling_interval === 'All') {
364
+ startDate = new Date(2017, 0, 1, 0, 0, 0, 0);
365
+ endDate = moment().endOf('day').toDate();
366
+ }
367
+ filterArrays_1.push((_a = {}, _a[filter.field] = { '$gte': startDate }, _a));
368
+ filterArrays_1.push((_b = {}, _b[filter.field] = { '$lte': endDate }, _b));
369
+ }
370
+ else {
371
+ filterArrays_1.push((_c = {}, _c[filter.field] = { '$gte': filter.value }, _c));
372
+ filterArrays_1.push((_d = {}, _d[filter.field] = { '$lte': filter.highValue }, _d));
373
+ }
374
+ }
375
+ else {
376
+ if (Array.isArray(filter.value)) {
377
+ var or_2 = [];
378
+ filter.value.forEach(function (filt) {
379
+ var _a, _b;
380
+ or_2.push((_a = {}, _a[filter.field.replace(/\.\$/g, '')] = (_b = {}, _b['$' + filter.condition] = (Array.isArray(filt) ? filt[0] : filt), _b), _a));
381
+ });
382
+ filterArrays_1.push({ $or: or_2 });
383
+ }
384
+ else {
385
+ filterArrays_1.push((_e = {}, _e[filter.field.replace(/\.\$/g, '')] = (_f = {}, _f['$' + filter.condition] = filter.value, _f), _e));
386
+ }
387
+ }
388
+ }
389
+ });
390
+ this.callMethodInternal.call(this, 'reportBuilderGetResults', report.type, report.collection_root, rootOptions, filters_1, filterArrays_1, report.fields_selected, report.groups_row, report.fields_total, report.fields_link, report.id_date_field || null, report.date_interval || null, function (err, res) {
391
+ if (res && res[0]) {
392
+ var fields_1 = [];
393
+ var results_1 = res[0].results;
394
+ var reportTotals = res[0].totals;
395
+ if (report.type === 'Tabular') {
396
+ report.fields_selected.forEach(function (field) {
397
+ if (field.fieldType === 'Number' && (field.leafType === 'Number' || field.leafType === 'Average' || field.leafType === 'Count' || field.leafType === 'Sum' || field.leafType === 'First' || field.leafType === 'Last' || field.leafType === 'Minimum' || field.leafType === 'Maximum')) {
398
+ results_1.filter(function (a) { return a[field.id]; }).forEach(function (result) {
399
+ result[field.id] = result[field.id].toLocaleString();
400
+ });
401
+ }
402
+ else if (field.fieldType === 'Number' && field.leafType === 'String') {
403
+ results_1.filter(function (a) { return a[field.id]; }).forEach(function (result) {
404
+ result[field.id] = result[field.id].toString();
405
+ });
406
+ }
407
+ else if (field.fieldType === 'Number' && field.leafType === 'Currency') {
408
+ results_1.filter(function (a) { return a[field.id]; }).forEach(function (result) {
409
+ result[field.id] = result[field.id].toLocaleString('en-US', { style: 'currency', currency: 'USD' });
410
+ });
411
+ }
412
+ else if (field.fieldType === 'Boolean' && field.leafType === 'Count') {
413
+ results_1.filter(function (a) { return a[field.id]; }).forEach(function (result) {
414
+ result[field.id] = result[field.id].toLocaleString();
415
+ });
416
+ }
417
+ else if (field.fieldType === 'Boolean' && field.leafType === 'String') {
418
+ results_1.filter(function (a) { return a[field.id]; }).forEach(function (result) {
419
+ result[field.id] = result[field.id] === true ? 'Yes' : 'No';
420
+ });
421
+ }
422
+ else if (field.fieldType === 'Boolean' && field.leafType === 'Number') {
423
+ results_1.filter(function (a) { return a[field.id]; }).forEach(function (result) {
424
+ result[field.id] = result[field.id] === true ? 1 : 0;
425
+ });
426
+ }
427
+ else if (field.fieldType === 'Date' && field.leafType === 'Count') {
428
+ results_1.filter(function (a) { return a[field.id]; }).forEach(function (result) {
429
+ result[field.id] = result[field.id].toLocaleString();
430
+ });
431
+ }
432
+ else if (field.fieldType === 'Date' && (field.leafType === 'Date')) {
433
+ results_1.filter(function (a) { return a[field.id]; }).forEach(function (result) {
434
+ result[field.id] = moment(result[field.id]).format('L');
435
+ });
436
+ }
437
+ else if (field.fieldType === 'Date' && field.leafType === 'Time') {
438
+ results_1.filter(function (a) { return a[field.id]; }).forEach(function (result) {
439
+ result[field.id] = moment(result[field.id]).format('LT');
440
+ });
441
+ }
442
+ else if (field.fieldType === 'Date' && (field.leafType === 'DateTime' || field.leafType === 'Minimum' || field.leafType === 'Maximum' || field.leafType === 'First' || field.leafType === 'Last')) {
443
+ results_1.filter(function (a) { return a[field.id]; }).forEach(function (result) {
444
+ result[field.id] = moment(result[field.id]).format('MM/DD/YYYY h:mm A');
445
+ });
446
+ }
447
+ else if (field.fieldType === 'Date' && field.leafType === 'Date_long') {
448
+ results_1.filter(function (a) { return a[field.id]; }).forEach(function (result) {
449
+ result[field.id] = moment(result[field.id]).format('LL');
450
+ });
451
+ }
452
+ else if (field.fieldType === 'Date' && field.leafType === 'DateTime_long') {
453
+ results_1.filter(function (a) { return a[field.id]; }).forEach(function (result) {
454
+ result[field.id] = moment(result[field.id]).format('LLL');
455
+ });
456
+ }
457
+ else if (field.fieldType === 'Date' && field.leafType === 'Number') {
458
+ results_1.filter(function (a) { return a[field.id]; }).forEach(function (result) {
459
+ result[field.id] = moment(result[field.id]).toDate().getTime();
460
+ });
461
+ }
462
+ });
463
+ report.groups_row.forEach(function (group) {
464
+ fields_1.push('_id.' + group.id);
465
+ });
466
+ report.fields_selected.forEach(function (selectedField) {
467
+ fields_1.push(selectedField.id);
468
+ });
469
+ var opts = { fields: fields_1 };
470
+ json2csv_1.parseAsync(results_1, opts)
471
+ .then(function (csv) {
472
+ var rows = csv.split(/(?:\r\n|\n)+/).filter(function (el) {
473
+ return el.length !== 0;
474
+ });
475
+ report.groups_row.forEach(function (group) {
476
+ rows[0] = rows[0].replace('_id.' + group.id, group.columnName);
477
+ });
478
+ report.fields_selected.forEach(function (selectedField) {
479
+ rows[0] = rows[0].replace(selectedField.id, selectedField.columnName);
480
+ });
481
+ var newCSV = '';
482
+ rows.forEach(function (row, index) {
483
+ newCSV += row;
484
+ if (index < rows.length - 1) {
485
+ newCSV += '\r\n';
486
+ }
487
+ });
488
+ data['emails'].forEach(function (email) {
489
+ _this.sendEmail(email, 'AAIMOS Scheduled Report - ' + report.report_name, '', "\n\t\t\t\t\t\t\t\t\t\t\t<b>AAIMOS Automated Report<b><br>\n\t\t\t\t\t\t\t\t\t\t\tReport Name: " + report.report_name + "<br>\n\t\t\t\t\t\t\t\t\t\t\tPrepared By: " + data['user'] + "<br><br>\n\t\t\t\t\t\t\t\t\t\t\tAttached are the results of this report in a CSV formatted file.<br><br>\n\t\t\t\t\t\t\t\t\t\t\tHave a great day!<br><br>\n\t\t\t\t\t\t\t\t\t\t\tResolveIO<br><br>", [
490
+ {
491
+ filename: report.report_name + '-' + moment().format('MM-DD-YYYY-hh-mm-A') + '.csv',
492
+ content: newCSV
493
+ }
494
+ ], _this.serverConfig['MAIL_FROM_REPORTS']);
495
+ });
496
+ })
497
+ .catch(function (errCSV) { return console.error(errCSV); });
498
+ }
499
+ else if (report.type === 'Dated') {
500
+ var lines_1 = [];
501
+ var tmpHeaders_1 = {};
502
+ report.groups_row.forEach(function (group) {
503
+ tmpHeaders_1[group.id] = group.columnName;
504
+ });
505
+ tmpHeaders_1[''] = '';
506
+ var datedUniqueDates_1 = [];
507
+ var datedUniqueGroups_1 = [];
508
+ if (report.date_interval === 'Quarterly') {
509
+ results_1.forEach(function (dataPt) {
510
+ if (dataPt._id.month < 4) {
511
+ dataPt._id.quarter = 1;
512
+ }
513
+ else if (dataPt._id.month < 7) {
514
+ dataPt._id.quarter = 2;
515
+ }
516
+ else if (dataPt._id.month < 10) {
517
+ dataPt._id.quarter = 3;
518
+ }
519
+ else {
520
+ dataPt._id.quarter = 4;
521
+ }
522
+ delete dataPt._id.month;
523
+ });
524
+ var _loop_1 = function (i) {
525
+ var dataPt = results_1[i];
526
+ if (results_1.filter(function (a) { return JSON.stringify(a._id) === JSON.stringify(dataPt._id); }).length > 1) {
527
+ var tmpData_1 = results_1.filter(function (a) { return JSON.stringify(a._id) === JSON.stringify(dataPt._id); })[0];
528
+ Object.keys(tmpData_1).filter(function (a) { return a !== '_id'; }).forEach(function (key) {
529
+ tmpData_1[key] += dataPt[key];
530
+ });
531
+ results_1.splice(i, 1);
532
+ }
533
+ };
534
+ for (var i = results_1.length - 1; i >= 1; i--) {
535
+ _loop_1(i);
536
+ }
537
+ }
538
+ var tmpResults = common_1.deepCopy(results_1);
539
+ tmpResults.forEach(function (result) {
540
+ delete result._id.day;
541
+ delete result._id.week;
542
+ delete result._id.month;
543
+ delete result._id.quarter;
544
+ delete result._id.year;
545
+ var tmp = {};
546
+ Object.keys(result._id).forEach(function (key) {
547
+ tmp[key] = result._id[key];
548
+ });
549
+ if (!datedUniqueGroups_1.filter(function (a) { return JSON.stringify(a) === JSON.stringify(tmp); }).length) {
550
+ datedUniqueGroups_1.push(tmp);
551
+ }
552
+ });
553
+ tmpResults = common_1.deepCopy(results_1);
554
+ tmpResults.forEach(function (result) {
555
+ Object.keys(result._id).filter(function (a) { return a !== 'day' && a !== 'week' && a !== 'month' && a !== 'quarter' && a !== 'year'; }).forEach(function (key) {
556
+ delete result._id[key];
557
+ });
558
+ var tmp = {};
559
+ Object.keys(result._id).forEach(function (key) {
560
+ tmp[key] = result._id[key];
561
+ });
562
+ if (!datedUniqueDates_1.filter(function (a) { return JSON.stringify(a) === JSON.stringify(tmp); }).length) {
563
+ datedUniqueDates_1.push(tmp);
564
+ }
565
+ });
566
+ datedUniqueDates_1.forEach(function (result) {
567
+ if (!result.year) {
568
+ result.dateString = 'No Date';
569
+ }
570
+ else {
571
+ if (report.date_interval === 'Daily') {
572
+ result.date = new Date(result.year, result.month, result.day, 0, 0, 0, 0);
573
+ result.dateString = moment(result.date).format('MMM DD YYYY');
574
+ }
575
+ else if (report.date_interval === 'Weekly') {
576
+ result.date = moment().day('Sunday').week(result.week + 1).toDate();
577
+ result.dateLast = moment().day('Saturday').week(result.week + 1).toDate();
578
+ result.dateString = 'Week #' + (result.week + 1) + ' ' + result.year + '(' + moment(result.date).format('MM/DD/YY') + ' - ' + moment(result.dateLast).format('MM/DD/YY') + ')';
579
+ }
580
+ else if (report.date_interval === 'Monthly') {
581
+ result.date = new Date(result.year, result.month, 0, 0, 0, 0, 0);
582
+ result.dateString = moment(result.date).format('MMM YYYY');
583
+ }
584
+ else if (report.date_interval === 'Quarterly') {
585
+ result.date = moment().quarter(result.quarter).year(result.year).toDate();
586
+ result.dateString = 'Q' + result.quarter + ' ' + result.year;
587
+ }
588
+ else if (report.date_interval === 'Yearly') {
589
+ result.date = new Date(result.year);
590
+ result.dateString = result.year.toString();
591
+ }
592
+ }
593
+ });
594
+ datedUniqueDates_1 = datedUniqueDates_1.filter(function (a) { return !a.date; }).concat(datedUniqueDates_1.filter(function (a) { return a.date; }).sort(function (a, b) { return a.date.getTime() - b.date.getTime(); }));
595
+ var reportTotalGroups_1 = [];
596
+ var reportTotalDates_1 = [];
597
+ var datedData_1 = [];
598
+ datedUniqueDates_1.forEach(function (date) {
599
+ var tmpData = [];
600
+ var tmpTotalDated = {};
601
+ var tmpTotalCnt = {};
602
+ var tmpTotalType = {};
603
+ datedUniqueGroups_1.forEach(function (group) {
604
+ var result = results_1.filter(function (a) {
605
+ var res = true;
606
+ Object.keys(date).filter(function (a) { return a !== 'date' && a !== 'dateLast' && a !== 'dateString'; }).forEach(function (key) {
607
+ if (a._id[key] !== date[key]) {
608
+ res = false;
609
+ }
610
+ });
611
+ Object.keys(group).forEach(function (key) {
612
+ if (a._id[key] !== group[key]) {
613
+ res = false;
614
+ }
615
+ });
616
+ return res;
617
+ })[0];
618
+ if (result) {
619
+ tmpData.push(result);
620
+ Object.keys(result._id).filter(function (a) { return a; }).forEach(function (key) {
621
+ if (report.fields_total.filter(function (a) { return a.fields.includes(key); }).length) {
622
+ if (!tmpTotalDated[key]) {
623
+ tmpTotalDated[key] = result._id[key];
624
+ }
625
+ else {
626
+ tmpTotalDated[key] += result._id[key];
627
+ }
628
+ if (!tmpTotalCnt[key]) {
629
+ tmpTotalCnt[key] = 1;
630
+ }
631
+ else {
632
+ tmpTotalCnt[key] += 1;
633
+ }
634
+ tmpTotalType[key] = report.fields_total.filter(function (a) { return a.fields.includes(key); })[0].type;
635
+ }
636
+ });
637
+ Object.keys(result).filter(function (a) { return a && a !== '_id'; }).forEach(function (key) {
638
+ if (report.fields_total.filter(function (a) { return a.fields.includes(key); }).length) {
639
+ if (!tmpTotalDated[key]) {
640
+ tmpTotalDated[key] = result[key];
641
+ }
642
+ else {
643
+ tmpTotalDated[key] += result[key];
644
+ }
645
+ if (!tmpTotalCnt[key]) {
646
+ tmpTotalCnt[key] = 1;
647
+ }
648
+ else {
649
+ tmpTotalCnt[key] += 1;
650
+ }
651
+ tmpTotalType[key] = report.fields_total.filter(function (a) { return a.fields.includes(key); })[0].type;
652
+ }
653
+ });
654
+ }
655
+ else {
656
+ tmpData.push(null);
657
+ }
658
+ });
659
+ Object.keys(tmpTotalType).forEach(function (totalKey) {
660
+ if (tmpTotalType[totalKey] === 'avg') {
661
+ tmpTotalDated[totalKey] = tmpTotalDated[totalKey] / tmpTotalCnt[totalKey];
662
+ }
663
+ tmpTotalDated[totalKey] = Math.round(tmpTotalDated[totalKey] * 100) / 100;
664
+ });
665
+ reportTotalDates_1.push(tmpTotalDated);
666
+ datedData_1.push(tmpData);
667
+ });
668
+ datedUniqueGroups_1.forEach(function (group) {
669
+ var tmpTotalGroup = {};
670
+ var filteredData = results_1.filter(function (a) {
671
+ var res = true;
672
+ Object.keys(group).filter(function (a) { return a !== 'date' && a !== 'dateLast' && a !== 'dateString' && a !== 'day' && a !== 'week' && a !== 'month' && a !== 'quarter' && a !== 'year'; }).forEach(function (key) {
673
+ if (a._id[key] !== group[key]) {
674
+ res = false;
675
+ }
676
+ });
677
+ return res;
678
+ });
679
+ report.fields_total.forEach(function (total) {
680
+ total.fields.forEach(function (field) {
681
+ if (filteredData.length) {
682
+ if (!tmpTotalGroup[field]) {
683
+ tmpTotalGroup[field] = filteredData.filter(function (a) { return a && a[field]; }).map(function (a) { return a[field]; }).reduce(function (a, b) { return a + b; }, 0);
684
+ }
685
+ else {
686
+ tmpTotalGroup[field] += filteredData.filter(function (a) { return a && a[field]; }).map(function (a) { return a[field]; }).reduce(function (a, b) { return a + b; }, 0);
687
+ }
688
+ if (total.type === 'avg') {
689
+ tmpTotalGroup[field] = Math.round(tmpTotalGroup[field] / filteredData.length * 100) / 100;
690
+ }
691
+ }
692
+ else {
693
+ tmpTotalGroup[field] = 0;
694
+ }
695
+ });
696
+ });
697
+ reportTotalGroups_1.push(tmpTotalGroup);
698
+ });
699
+ datedUniqueDates_1.forEach(function (date) {
700
+ tmpHeaders_1[date.dateString] = date.dateString;
701
+ });
702
+ tmpHeaders_1['Totals'] = 'Totals';
703
+ lines_1.push(tmpHeaders_1);
704
+ for (var i = 0; i <= datedUniqueGroups_1.length - 1; i++) {
705
+ var group = datedUniqueGroups_1[i];
706
+ for (var j = 0; j <= report.fields_selected.length - 1; j++) {
707
+ var field = report.fields_selected[j];
708
+ var tmp = {};
709
+ for (var k = 0; k <= report.groups_row.length - 1; k++) {
710
+ var groupRow = report.groups_row[k];
711
+ if (j === 0) {
712
+ tmp[group[groupRow.id]] = group[groupRow.id];
713
+ }
714
+ else {
715
+ tmp[group[groupRow.id]] = '';
716
+ }
717
+ }
718
+ tmp[field.columnName] = field.columnName;
719
+ for (var k = 0; k <= datedData_1.length - 1; k++) {
720
+ var result = datedData_1[k];
721
+ if (result[i]) {
722
+ tmp[i + ' ' + j + ' ' + k] = result[i][field.id];
723
+ }
724
+ else {
725
+ tmp[i + ' ' + j + ' ' + k] = '';
726
+ }
727
+ }
728
+ for (var k = 0; k <= report.fields_total.length - 1; k++) {
729
+ var total = report.fields_total[k];
730
+ if (total.fields.includes(field.id)) {
731
+ tmp['total' + i + ' ' + j + ' ' + k] = reportTotalGroups_1[i][field.id];
732
+ }
733
+ else {
734
+ tmp['total' + i + ' ' + j + ' ' + k] = '';
735
+ }
736
+ }
737
+ lines_1.push(tmp);
738
+ }
739
+ }
740
+ if (reportTotals) {
741
+ for (var j = 0; j <= report.fields_selected.length - 1; j++) {
742
+ var field = report.fields_selected[j];
743
+ var tmp = {};
744
+ for (var k = 0; k <= report.groups_row.length - 1; k++) {
745
+ var groupRow = report.groups_row[k];
746
+ for (var l = 0; l <= report.fields_total.length - 1; l++) {
747
+ var total = report.fields_total[l];
748
+ if (j === 0) {
749
+ tmp[total.type + k] = total.type + ' TOTALS';
750
+ }
751
+ else {
752
+ tmp[total.type + k] = '';
753
+ }
754
+ }
755
+ }
756
+ tmp[field.columnName] = field.columnName;
757
+ for (var k = 0; k <= datedData_1.length - 1; k++) {
758
+ var result = datedData_1[k];
759
+ for (var l = 0; l <= report.fields_total.length - 1; l++) {
760
+ var total = report.fields_total[l];
761
+ if (total.fields.includes(field.id)) {
762
+ tmp['total' + j + ' ' + k + ' ' + l] = reportTotalDates_1[k][field.id];
763
+ }
764
+ else {
765
+ tmp['total' + j + ' ' + k + ' ' + l] = '';
766
+ }
767
+ }
768
+ }
769
+ for (var k = 0; k <= report.groups_row.length - 1; k++) {
770
+ var groupRow = report.groups_row[k];
771
+ for (var l = 0; l <= report.fields_total.length - 1; l++) {
772
+ var total = report.fields_total[l];
773
+ if (total.fields.includes(groupRow.id)) {
774
+ tmp['totalreportTotals' + j + ' ' + k + ' ' + l] = reportTotals[total.id + groupRow.id];
775
+ }
776
+ }
777
+ }
778
+ for (var l = 0; l <= report.fields_total.length - 1; l++) {
779
+ var total = report.fields_total[l];
780
+ if (total.fields.includes(field.id)) {
781
+ tmp['totalreportTotals' + j + ' ' + l] = reportTotals[total.id + '_' + field.id];
782
+ }
783
+ }
784
+ lines_1.push(tmp);
785
+ }
786
+ }
787
+ var newCSV_1 = '';
788
+ lines_1.forEach(function (row, index) {
789
+ Object.keys(row).forEach(function (key, keyIndex) {
790
+ if (row[key] && typeof (row[key]) === 'string') {
791
+ row[key] = row[key].replace(new RegExp(/,/g), '');
792
+ }
793
+ newCSV_1 += row[key];
794
+ if (keyIndex < Object.keys(row).length - 1) {
795
+ newCSV_1 += ',';
796
+ }
797
+ });
798
+ if (index < lines_1.length - 1) {
799
+ newCSV_1 += '\r\n';
800
+ }
801
+ });
802
+ data['emails'].forEach(function (email) {
803
+ _this.sendEmail(email, 'AAIMOS Scheduled Report - ' + report.report_name, '', "\n\t\t\t\t\t\t\t\t\t\t<b>AAIMOS Automated Report<b><br>\n\t\t\t\t\t\t\t\t\t\tReport Name: " + report.report_name + "<br>\n\t\t\t\t\t\t\t\t\t\tPrepared By: " + data['user'] + "<br><br>\n\t\t\t\t\t\t\t\t\t\tAttached are the results of this report in a CSV formatted file.<br><br>\n\t\t\t\t\t\t\t\t\t\tHave a great day!<br><br>\n\t\t\t\t\t\t\t\t\t\tResolveIO<br><br>", [
804
+ {
805
+ filename: report.report_name + '-' + moment().format('MM-DD-YYYY-hh-mm-A') + '.csv',
806
+ content: newCSV_1
807
+ }
808
+ ], _this.serverConfig['MAIL_FROM_REPORTS']);
809
+ });
810
+ resolve();
811
+ }
812
+ }
813
+ else {
814
+ console.log(res);
815
+ _this.callMethodInternal.call(_this, 'insertErrorLog', 'Report Builder Cron Job - Report Builder Get Results', [
816
+ err
817
+ ]);
818
+ reject(err);
819
+ }
820
+ });
821
+ }
822
+ return [2 /*return*/];
823
+ }
824
+ });
825
+ }); });
826
+ }
129
827
  }
130
828
  });
131
829
  }