@dhyasama/totem-models 12.3.0 → 12.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.
package/lib/Financials.js CHANGED
@@ -330,59 +330,55 @@ module.exports = function(mongoose, config) {
330
330
  // Statics operate on the entire collection
331
331
  //////////////////////////////////////////////////////
332
332
 
333
- Financials.statics.addMetrics = function updateProperty(snapshotUUID, metrics, cb) {
333
+ Financials.statics.addMetrics = async function updateProperty(snapshotUUID, metrics, cb) {
334
334
 
335
- const self = this;
336
- const filter = { 'snapshots.uuid': snapshotUUID };
337
- const update = { '$push': { 'snapshots.$.metrics': { $each: metrics } } };
338
- const options = { 'upsert': false, 'new': true };
335
+ try {
336
+ const filter = { 'snapshots.uuid': snapshotUUID };
337
+ const update = { '$push': { 'snapshots.$.metrics': { $each: metrics } } };
338
+ const options = { 'upsert': false, 'new': true };
339
339
 
340
- self.updateOne(filter, update, options).then(function(result) { cb(null, result); }).catch(function(err) { cb(err); });
340
+ const result = await this.updateOne(filter, update, options);
341
+ return cb(null, result);
342
+ } catch(err) {
343
+ return cb(err);
344
+ }
341
345
 
342
346
  };
343
347
 
344
- Financials.statics.addNewMetrics = function addNewMetrics(financialsId, snapshotUUID, metricsToAdd, cb) {
348
+ Financials.statics.addNewMetrics = async function addNewMetrics(financialsId, snapshotUUID, metricsToAdd, cb) {
345
349
 
346
- const self = this;
347
-
348
- self.findOne({ _id: financialsId, 'snapshots.uuid': snapshotUUID })
349
- .then(financials => {
350
+ try {
351
+ const financials = await this.findOne({ _id: financialsId, 'snapshots.uuid': snapshotUUID });
350
352
 
351
- if (!financials) { throw new Error('financials not found'); }
353
+ if (!financials) { throw new Error('financials not found'); }
352
354
 
353
- const snapshot = financials.snapshots.find(snap => snap.uuid === snapshotUUID);
354
- if (!snapshot) { throw new Error('Snapshot not found'); }
355
+ const snapshot = financials.snapshots.find(snap => snap.uuid === snapshotUUID);
356
+ if (!snapshot) { throw new Error('Snapshot not found'); }
355
357
 
356
- const existingMetricNames = new Set(snapshot.metrics.map(metric => metric.name));
357
- const newMetrics = metricsToAdd.filter(metric => !existingMetricNames.has(metric.name));
358
+ const existingMetricNames = new Set(snapshot.metrics.map(metric => metric.name));
359
+ const newMetrics = metricsToAdd.filter(metric => !existingMetricNames.has(metric.name));
358
360
 
359
- if (newMetrics.length === 0) {
360
- console.log('No new metrics to add');
361
- return;
362
- }
363
-
364
- return self.findOneAndUpdate(
365
- { _id: financialsId, 'snapshots.uuid': snapshotUUID },
366
- { $push: { 'snapshots.$.metrics': { $each: newMetrics } } },
367
- { new: true }
368
- );
369
-
370
- })
371
- .then(result => {
372
- if (result) { console.log('Metrics added successfully'); }
361
+ if (newMetrics.length === 0) {
362
+ console.log('No new metrics to add');
373
363
  return cb();
374
- })
375
- .catch(error => {
376
- console.error('Error adding metrics:', error);
377
- return cb(error);
378
- });
364
+ }
379
365
 
380
- }
366
+ const result = await this.findOneAndUpdate(
367
+ { _id: financialsId, 'snapshots.uuid': snapshotUUID },
368
+ { $push: { 'snapshots.$.metrics': { $each: newMetrics } } },
369
+ { new: true }
370
+ );
371
+
372
+ if (result) { console.log('Metrics added successfully'); }
373
+ return cb();
374
+ } catch(error) {
375
+ console.error('Error adding metrics:', error);
376
+ return cb(error);
377
+ }
381
378
 
382
- Financials.statics.upsertMetrics = function upsertMetrics(financialsId, snapshotUUID, metricsToUpdate, cb) {
379
+ }
383
380
 
384
- const self = this;
385
- const session = mongoose.startSession();
381
+ Financials.statics.upsertMetrics = async function upsertMetrics(financialsId, snapshotUUID, metricsToUpdate, cb) {
386
382
 
387
383
  const metricWasAdded = (updatedDocument, snapshotUUID, metric) => {
388
384
 
@@ -412,7 +408,9 @@ module.exports = function(mongoose, config) {
412
408
  console.log('Upserting metrics for snapshot', snapshotUUID)
413
409
  console.log('Metrics to upsert:', metricsToUpdate)
414
410
 
415
- session.then(async _session => {
411
+ const _session = await mongoose.startSession();
412
+
413
+ try {
416
414
 
417
415
  _session.startTransaction();
418
416
 
@@ -421,13 +419,13 @@ module.exports = function(mongoose, config) {
421
419
  // Fetch the current document to read existing metric values before overwriting
422
420
  let currentDoc = null;
423
421
  try {
424
- currentDoc = await self.findOne({ _id: financialsId, 'snapshots.uuid': snapshotUUID }, null, { session: _session });
422
+ currentDoc = await this.findOne({ _id: financialsId, 'snapshots.uuid': snapshotUUID }, null, { session: _session });
425
423
  } catch (e) {
426
424
  console.log('Could not fetch current metrics for previous state:', e);
427
425
  }
428
426
  const currentSnapshot = currentDoc ? currentDoc.snapshots.find(s => s.uuid === snapshotUUID) : null;
429
427
 
430
- const promises = metricsToUpdate.map(metric => {
428
+ const promises = metricsToUpdate.map(async metric => {
431
429
 
432
430
  console.log('Upserting metric:', metric);
433
431
  console.log('Upserting metric name:', metric.name);
@@ -463,7 +461,7 @@ module.exports = function(mongoose, config) {
463
461
  $set['snapshots.$.metrics.$[metric].previous'] = previousState;
464
462
  }
465
463
 
466
- return self.findOneAndUpdate(
464
+ const result = await this.findOneAndUpdate(
467
465
  {
468
466
  _id: financialsId,
469
467
  snapshots: {
@@ -492,179 +490,172 @@ module.exports = function(mongoose, config) {
492
490
  new: true,
493
491
  session: _session
494
492
  }
495
- ).then(result => {
496
-
497
- //console.log('Upsert result:', result)
498
-
499
- if (!metricWasAdded(result, snapshotUUID, metric)) {
500
- console.log('Metric not added')
501
- // If the metric doesn't exist, push it to the array
502
- return self.findOneAndUpdate(
503
- { _id: financialsId, 'snapshots.uuid': snapshotUUID },
504
- { $push: { 'snapshots.$.metrics': metric } },
505
- { new: true, session: _session }
506
- ).then(result => {
507
- console.log('Result of second findOneAndUpdate:', result);
508
- return result;
509
- });
510
- }
493
+ );
511
494
 
512
- return result;
495
+ //console.log('Upsert result:', result)
496
+
497
+ if (!metricWasAdded(result, snapshotUUID, metric)) {
498
+ console.log('Metric not added')
499
+ // If the metric doesn't exist, push it to the array
500
+ const pushResult = await this.findOneAndUpdate(
501
+ { _id: financialsId, 'snapshots.uuid': snapshotUUID },
502
+ { $push: { 'snapshots.$.metrics': metric } },
503
+ { new: true, session: _session }
504
+ );
505
+ console.log('Result of second findOneAndUpdate:', pushResult);
506
+ return pushResult;
507
+ }
508
+
509
+ return result;
513
510
 
514
- });
515
511
  });
516
512
 
517
- Promise.all(promises)
518
- .then(() => {
519
- return _session.commitTransaction();
520
- })
521
- .then(() => {
522
- _session.endSession();
523
- console.log('Upsert complete.');
524
- return cb();
525
- })
526
- .catch(error => {
527
- _session.abortTransaction().then(() => {
528
- _session.endSession();
529
- console.error(error);
530
- return cb(error);
531
- });
532
- });
533
- });
513
+ await Promise.all(promises);
514
+ await _session.commitTransaction();
515
+ _session.endSession();
516
+ console.log('Upsert complete.');
517
+ return cb();
518
+
519
+ } catch(error) {
520
+ await _session.abortTransaction();
521
+ _session.endSession();
522
+ console.error(error);
523
+ return cb(error);
524
+ }
534
525
 
535
526
  }
536
527
 
537
- Financials.statics.undoMetrics = function undoMetrics(financialsId, snapshotUUID, metricsToUndo, cb) {
528
+ Financials.statics.undoMetrics = async function undoMetrics(financialsId, snapshotUUID, metricsToUndo, cb) {
538
529
 
539
- const self = this;
540
- const session = mongoose.startSession();
530
+ const _session = await mongoose.startSession();
541
531
 
542
- session.then(async _session => {
532
+ _session.startTransaction();
543
533
 
544
- _session.startTransaction();
534
+ try {
545
535
 
546
- try {
536
+ const currentDoc = await this.findOne({ _id: financialsId, 'snapshots.uuid': snapshotUUID }, null, { session: _session });
537
+ if (!currentDoc) { throw new Error('Financials not found'); }
547
538
 
548
- const currentDoc = await self.findOne({ _id: financialsId, 'snapshots.uuid': snapshotUUID }, null, { session: _session });
549
- if (!currentDoc) { throw new Error('Financials not found'); }
539
+ const snapshot = currentDoc.snapshots.find(s => s.uuid === snapshotUUID);
540
+ if (!snapshot) { throw new Error('Snapshot not found'); }
550
541
 
551
- const snapshot = currentDoc.snapshots.find(s => s.uuid === snapshotUUID);
552
- if (!snapshot) { throw new Error('Snapshot not found'); }
542
+ const promises = metricsToUndo.map(metricId => {
553
543
 
554
- const promises = metricsToUndo.map(metricId => {
544
+ const currentMetric = snapshot.metrics.find(m => m.name === metricId.name && m.scenario === metricId.scenario);
545
+ if (!currentMetric || !currentMetric.previous) {
546
+ console.log('No previous state for metric:', metricId.name, metricId.scenario);
547
+ return Promise.resolve();
548
+ }
555
549
 
556
- const currentMetric = snapshot.metrics.find(m => m.name === metricId.name && m.scenario === metricId.scenario);
557
- if (!currentMetric || !currentMetric.previous) {
558
- console.log('No previous state for metric:', metricId.name, metricId.scenario);
559
- return Promise.resolve();
560
- }
550
+ const prev = currentMetric.previous;
551
+ const prefix = 'snapshots.$.metrics.$[metric]';
561
552
 
562
- const prev = currentMetric.previous;
563
- const prefix = 'snapshots.$.metrics.$[metric]';
553
+ // Restore fields that had values; unset fields that were null (didn't exist before)
554
+ const $set = {};
555
+ const $unset = { [prefix + '.previous']: 1 };
564
556
 
565
- // Restore fields that had values; unset fields that were null (didn't exist before)
566
- const $set = {};
567
- const $unset = { [prefix + '.previous']: 1 };
557
+ const fields = ['value', 'breakdown', 'calculation', 'sources', 'verified'];
558
+ fields.forEach(field => {
559
+ if (prev[field] != null) {
560
+ $set[prefix + '.' + field] = prev[field];
561
+ } else {
562
+ $unset[prefix + '.' + field] = 1;
563
+ }
564
+ });
568
565
 
569
- const fields = ['value', 'breakdown', 'calculation', 'sources', 'verified'];
570
- fields.forEach(field => {
571
- if (prev[field] != null) {
572
- $set[prefix + '.' + field] = prev[field];
573
- } else {
574
- $unset[prefix + '.' + field] = 1;
575
- }
576
- });
566
+ // History is always restored (empty array if it was empty)
567
+ $set[prefix + '.history'] = prev.history || [];
577
568
 
578
- // History is always restored (empty array if it was empty)
579
- $set[prefix + '.history'] = prev.history || [];
580
-
581
- return self.findOneAndUpdate(
582
- {
583
- _id: financialsId,
584
- snapshots: {
585
- $elemMatch: {
586
- uuid: snapshotUUID,
587
- metrics: {
588
- $elemMatch: {
589
- name: metricId.name,
590
- scenario: metricId.scenario
591
- }
569
+ return this.findOneAndUpdate(
570
+ {
571
+ _id: financialsId,
572
+ snapshots: {
573
+ $elemMatch: {
574
+ uuid: snapshotUUID,
575
+ metrics: {
576
+ $elemMatch: {
577
+ name: metricId.name,
578
+ scenario: metricId.scenario
592
579
  }
593
580
  }
594
581
  }
595
- },
596
- {
597
- $set: $set,
598
- $unset: $unset
599
- },
600
- {
601
- arrayFilters: [{ 'metric.name': metricId.name, 'metric.scenario': metricId.scenario }],
602
- new: true,
603
- session: _session
604
582
  }
605
- );
606
-
607
- });
608
-
609
- await Promise.all(promises);
610
- await _session.commitTransaction();
611
- _session.endSession();
612
- console.log('Undo complete.');
613
- return cb();
583
+ },
584
+ {
585
+ $set: $set,
586
+ $unset: $unset
587
+ },
588
+ {
589
+ arrayFilters: [{ 'metric.name': metricId.name, 'metric.scenario': metricId.scenario }],
590
+ new: true,
591
+ session: _session
592
+ }
593
+ );
614
594
 
615
- } catch (error) {
616
- await _session.abortTransaction();
617
- _session.endSession();
618
- console.error(error);
619
- return cb(error);
620
- }
595
+ });
621
596
 
622
- });
597
+ await Promise.all(promises);
598
+ await _session.commitTransaction();
599
+ _session.endSession();
600
+ console.log('Undo complete.');
601
+ return cb();
602
+
603
+ } catch (error) {
604
+ await _session.abortTransaction();
605
+ _session.endSession();
606
+ console.error(error);
607
+ return cb(error);
608
+ }
623
609
 
624
610
  }
625
611
 
626
- Financials.statics.getAll = function getAll(options, cb) {
627
-
628
- const self = this;
612
+ Financials.statics.getAll = async function getAll(options, cb) {
629
613
 
630
- let query = self.find({});
614
+ try {
615
+ let query = this.find({});
631
616
 
632
- query.populate('organization', 'name logoUrl');
633
- query.populate('customer', 'name logoUrl customer');
617
+ query.populate('organization', 'name logoUrl');
618
+ query.populate('customer', 'name logoUrl customer');
634
619
 
635
- query.exec().then(function(result) { cb(null, result); }).catch(function(err) { cb(err); });
620
+ const result = await query;
621
+ return cb(null, result);
622
+ } catch(err) {
623
+ return cb(err);
624
+ }
636
625
 
637
626
  };
638
627
 
639
- Financials.statics.getByOrg = function getByOrg(customerId, orgId, cb) {
628
+ Financials.statics.getByOrg = async function getByOrg(customerId, orgId, cb) {
640
629
 
641
- var self = this;
642
-
643
- var query = self.findOne({
644
- 'customer': customerId,
645
- 'organization': orgId
646
- }).populate({
647
- path: 'snapshots.documents.document',
648
- match: { customer: customerId }
649
- });
630
+ try {
631
+ var query = this.findOne({
632
+ 'customer': customerId,
633
+ 'organization': orgId
634
+ }).populate({
635
+ path: 'snapshots.documents.document',
636
+ match: { customer: customerId }
637
+ });
650
638
 
651
- query.exec().then(function(result) { cb(null, result); }).catch(function(err) { cb(err); });
639
+ const result = await query;
640
+ return cb(null, result);
641
+ } catch(err) {
642
+ return cb(err);
643
+ }
652
644
 
653
645
  };
654
646
 
655
- Financials.statics.getByUUID = function getByUUID(uuid, cb) {
656
-
657
- let self = this;
647
+ Financials.statics.getByUUID = async function getByUUID(uuid, cb) {
658
648
 
659
- let query = self.findOne({
660
- 'snapshots.uuid': uuid
661
- });
649
+ try {
650
+ let query = this.findOne({
651
+ 'snapshots.uuid': uuid
652
+ });
662
653
 
663
- query.populate('organization', 'name logoUrl website');
664
- query.populate('customer');
665
- query.populate('snapshots.documents.document');
654
+ query.populate('organization', 'name logoUrl website');
655
+ query.populate('customer');
656
+ query.populate('snapshots.documents.document');
666
657
 
667
- query.exec().then(function(result) {
658
+ const result = await query;
668
659
  if (!result) {
669
660
  return cb(null, null);
670
661
  }
@@ -681,32 +672,34 @@ module.exports = function(mongoose, config) {
681
672
  });
682
673
 
683
674
  return cb(null, result);
684
-
685
- }).catch(function(err) { cb(err); });
675
+ } catch(err) {
676
+ return cb(err);
677
+ }
686
678
 
687
679
  };
688
680
 
689
- Financials.statics.getByPostmarkMessageId = function getByPostmarkMessageId(postmarkMessageId, cb) {
690
-
691
- var self = this;
692
-
693
- var query = self.findOne({
694
- $or: [
695
- { 'snapshots.notifications.company.initial.postmarkMessageId': postmarkMessageId },
696
- { 'snapshots.notifications.company.reminders.postmarkMessageId': postmarkMessageId },
697
- { 'snapshots.notifications.company.rejections.postmarkMessageId': postmarkMessageId },
698
- { 'snapshots.notifications.stakeholders.initial.postmarkMessageId': postmarkMessageId },
699
- { 'snapshots.notifications.stakeholders.reminders.postmarkMessageId': postmarkMessageId }
700
- ]
701
- });
681
+ Financials.statics.getByPostmarkMessageId = async function getByPostmarkMessageId(postmarkMessageId, cb) {
682
+
683
+ try {
684
+ var query = this.findOne({
685
+ $or: [
686
+ { 'snapshots.notifications.company.initial.postmarkMessageId': postmarkMessageId },
687
+ { 'snapshots.notifications.company.reminders.postmarkMessageId': postmarkMessageId },
688
+ { 'snapshots.notifications.company.rejections.postmarkMessageId': postmarkMessageId },
689
+ { 'snapshots.notifications.stakeholders.initial.postmarkMessageId': postmarkMessageId },
690
+ { 'snapshots.notifications.stakeholders.reminders.postmarkMessageId': postmarkMessageId }
691
+ ]
692
+ });
702
693
 
703
- query.exec().then(function(result) { cb(null, result); }).catch(function(err) { cb(err); });
694
+ const result = await query;
695
+ return cb(null, result);
696
+ } catch(err) {
697
+ return cb(err);
698
+ }
704
699
 
705
700
  };
706
701
 
707
- Financials.statics.getByPostmarkMessageId2 = function getByPostmarkMessageId2(notificationType, postmarkMessageId, cb) {
708
-
709
- const self = this;
702
+ Financials.statics.getByPostmarkMessageId2 = async function getByPostmarkMessageId2(notificationType, postmarkMessageId, cb) {
710
703
 
711
704
  const notificationTypes = [
712
705
  'company.initial',
@@ -720,70 +713,78 @@ module.exports = function(mongoose, config) {
720
713
  if (!postmarkMessageId) { throw new Error('postmarkMessageId is required'); }
721
714
  if (!notificationTypes.includes(notificationType)) { throw new Error('notificationType is required'); }
722
715
 
723
- const key = 'snapshots.notifications.' + notificationType + '.postmarkMessageId';
716
+ try {
717
+ const key = 'snapshots.notifications.' + notificationType + '.postmarkMessageId';
724
718
 
725
- const query = self.findOne({
726
- key: postmarkMessageId
727
- });
719
+ const query = this.findOne({
720
+ key: postmarkMessageId
721
+ });
728
722
 
729
- query.exec().then(function(result) { cb(null, result); }).catch(function(err) { cb(err); });
723
+ const result = await query;
724
+ return cb(null, result);
725
+ } catch(err) {
726
+ return cb(err);
727
+ }
730
728
 
731
729
  };
732
730
 
733
- Financials.statics.getDocument = function getDocument(documentId, cb) {
731
+ Financials.statics.getDocument = async function getDocument(documentId, cb) {
734
732
 
735
733
  if (!cb) { throw new Error('cb is required'); }
736
734
  if (!documentId) { return cb(new Error('documentId is required'), null); }
737
735
  if (!mongoose.Types.ObjectId.isValid(documentId)) { return cb(new Error('documentId is not a valid ObjectId'), null); }
738
736
 
739
- const self = this;
740
-
741
- self.aggregate([
742
- { $unwind: '$snapshots' },
743
- { $unwind: '$snapshots.documents' },
744
- { $match: { 'snapshots.documents.document': new mongoose.Types.ObjectId(documentId) } },
745
- {
746
- $project: {
747
- _id: 1,
748
- snapshot: '$snapshots',
749
- document: '$snapshots.documents',
750
- organization: '$organization',
751
- customer: '$customer'
737
+ try {
738
+ const result = await this.aggregate([
739
+ { $unwind: '$snapshots' },
740
+ { $unwind: '$snapshots.documents' },
741
+ { $match: { 'snapshots.documents.document': new mongoose.Types.ObjectId(documentId) } },
742
+ {
743
+ $project: {
744
+ _id: 1,
745
+ snapshot: '$snapshots',
746
+ document: '$snapshots.documents',
747
+ organization: '$organization',
748
+ customer: '$customer'
749
+ }
752
750
  }
753
- }
754
- ]).exec().then(function(result) {
751
+ ]);
752
+
755
753
  if (!result || result.length === 0) return cb(null, null);
756
754
  else return cb(null, result[0]);
757
- }).catch(function(err) { cb(err); });
755
+ } catch(err) {
756
+ return cb(err);
757
+ }
758
758
 
759
759
  };
760
760
 
761
- Financials.statics.getSnapshot = function getSnapshot(snapshotUUID, cb) {
761
+ Financials.statics.getSnapshot = async function getSnapshot(snapshotUUID, cb) {
762
762
 
763
763
  if (!cb) { throw new Error('cb is required'); }
764
764
  if (!snapshotUUID) { return cb(new Error('snapshotUUID is required'), null); }
765
765
 
766
- const self = this;
767
-
768
- self.aggregate([
769
- { $unwind: '$snapshots' },
770
- { $match: { 'snapshots.uuid': snapshotUUID } },
771
- {
772
- $project: {
773
- _id: 1,
774
- snapshot: '$snapshots'
766
+ try {
767
+ const result = await this.aggregate([
768
+ { $unwind: '$snapshots' },
769
+ { $match: { 'snapshots.uuid': snapshotUUID } },
770
+ {
771
+ $project: {
772
+ _id: 1,
773
+ snapshot: '$snapshots'
774
+ }
775
775
  }
776
- }
777
- ]).exec().then(function(result) {
776
+ ]);
777
+
778
778
  if (!result || result.length === 0) return cb(null, null);
779
779
  else return cb(null, result[0]);
780
- }).catch(function(err) { cb(err); });
780
+ } catch(err) {
781
+ return cb(err);
782
+ }
781
783
 
782
784
  };
783
785
 
784
- Financials.statics.getRecurringToSend = function getRecurringToSend(options, cb) {
786
+ Financials.statics.getRecurringToSend = async function getRecurringToSend(options, cb) {
785
787
 
786
- const self = this;
787
788
  const now = new Date();
788
789
 
789
790
  if (!cb) { throw new Error('cb is required'); }
@@ -791,34 +792,38 @@ module.exports = function(mongoose, config) {
791
792
  if (!options.startTime) { return cb(new Error('options.startTime is required'), null); }
792
793
  if (!options.endTime) { return cb(new Error('options.endTime is required'), null); }
793
794
 
794
- let query = self.find({
795
- 'recurring.send.sendOn': { $lte: now },
796
- 'recurring.adminReminders.sent': false
797
- });
798
-
799
- query.exec().then(function(result) {return cb(null, result);
795
+ try {
796
+ let query = this.find({
797
+ 'recurring.send.sendOn': { $lte: now },
798
+ 'recurring.adminReminders.sent': false
799
+ });
800
800
 
801
- }).catch(function(err) { cb(err); });
801
+ const result = await query;
802
+ return cb(null, result);
803
+ } catch(err) {
804
+ return cb(err);
805
+ }
802
806
 
803
807
  };
804
808
 
805
- Financials.statics.getCompanyInitialToSend = function getCompanyInitialToSend(cb) {
809
+ Financials.statics.getCompanyInitialToSend = async function getCompanyInitialToSend(cb) {
806
810
 
807
- var self = this;
808
811
  var now = new Date();
809
812
 
810
- var query = self.find({
811
- 'snapshots': {
812
- $elemMatch: {
813
- 'notifications.company.initial.sendTo': { $gt: [] },
814
- 'notifications.company.initial.sendOn': { $lte: now },
815
- 'notifications.company.initial.sentOn': null,
816
- 'status': { $nin: ['Pending', 'Completed', 'Archived'] }
813
+ try {
814
+ var query = this.find({
815
+ 'snapshots': {
816
+ $elemMatch: {
817
+ 'notifications.company.initial.sendTo': { $gt: [] },
818
+ 'notifications.company.initial.sendOn': { $lte: now },
819
+ 'notifications.company.initial.sentOn': null,
820
+ 'status': { $nin: ['Pending', 'Completed', 'Archived'] }
821
+ }
817
822
  }
818
- }
819
- });
823
+ });
820
824
 
821
- query.exec().then(function(result) {var results = [];
825
+ const result = await query;
826
+ var results = [];
822
827
 
823
828
  _.each(result, function(financial) {
824
829
 
@@ -849,28 +854,30 @@ module.exports = function(mongoose, config) {
849
854
  });
850
855
 
851
856
  return cb(null, results);
852
-
853
- }).catch(function(err) { cb(err); });
857
+ } catch(err) {
858
+ return cb(err);
859
+ }
854
860
 
855
861
  };
856
862
 
857
- Financials.statics.getCompanyReminderToSend = function getCompanyReminderToSend(cb) {
863
+ Financials.statics.getCompanyReminderToSend = async function getCompanyReminderToSend(cb) {
858
864
 
859
- var self = this;
860
865
  var now = new Date();
861
866
 
862
- var query = self.find({
863
- 'snapshots': {
864
- $elemMatch: {
865
- 'notifications.company.reminders.sendTo': { $gt: [] },
866
- 'notifications.company.reminders.sendOn': { $lte: now },
867
- 'notifications.company.reminders.sentOn': null,
868
- 'status': { $nin: ['Pending', 'Completed', 'Archived'] }
867
+ try {
868
+ var query = this.find({
869
+ 'snapshots': {
870
+ $elemMatch: {
871
+ 'notifications.company.reminders.sendTo': { $gt: [] },
872
+ 'notifications.company.reminders.sendOn': { $lte: now },
873
+ 'notifications.company.reminders.sentOn': null,
874
+ 'status': { $nin: ['Pending', 'Completed', 'Archived'] }
875
+ }
869
876
  }
870
- }
871
- });
877
+ });
872
878
 
873
- query.exec().then(function(result) {var results = [];
879
+ const result = await query;
880
+ var results = [];
874
881
 
875
882
  _.each(result, function(financial) {
876
883
 
@@ -905,28 +912,30 @@ module.exports = function(mongoose, config) {
905
912
  });
906
913
 
907
914
  return cb(null, results);
908
-
909
- }).catch(function(err) { cb(err); });
915
+ } catch(err) {
916
+ return cb(err);
917
+ }
910
918
 
911
919
  };
912
920
 
913
- Financials.statics.getCompanyRejectionToSend = function getCompanyRejectionToSend(cb) {
921
+ Financials.statics.getCompanyRejectionToSend = async function getCompanyRejectionToSend(cb) {
914
922
 
915
- var self = this;
916
923
  var now = new Date();
917
924
 
918
- var query = self.find({
919
- 'snapshots': {
920
- $elemMatch: {
921
- 'notifications.company.rejections.sendTo': { $gt: [] },
922
- 'notifications.company.rejections.sendOn': { $lte: now },
923
- 'notifications.company.rejections.sentOn': null,
924
- 'status': { $nin: ['Pending', 'Completed', 'Archived'] }
925
+ try {
926
+ var query = this.find({
927
+ 'snapshots': {
928
+ $elemMatch: {
929
+ 'notifications.company.rejections.sendTo': { $gt: [] },
930
+ 'notifications.company.rejections.sendOn': { $lte: now },
931
+ 'notifications.company.rejections.sentOn': null,
932
+ 'status': { $nin: ['Pending', 'Completed', 'Archived'] }
933
+ }
925
934
  }
926
- }
927
- });
935
+ });
928
936
 
929
- query.exec().then(function(result) {var results = [];
937
+ const result = await query;
938
+ var results = [];
930
939
 
931
940
  _.each(result, function(financial) {
932
941
 
@@ -937,7 +946,7 @@ module.exports = function(mongoose, config) {
937
946
  var hasSendTo = rejection.sendTo && rejection.sendTo.length > 0;
938
947
  var hasSendOnLessThanNow = rejection.sendOn && rejection.sendOn < now;
939
948
  var hasSentOn = rejection.sentOn;
940
-
949
+
941
950
  var conditions = hasSendTo && hasSendOnLessThanNow && !hasSentOn;
942
951
 
943
952
  if(conditions) {
@@ -961,29 +970,31 @@ module.exports = function(mongoose, config) {
961
970
  });
962
971
 
963
972
  return cb(null, results);
964
-
965
- }).catch(function(err) { cb(err); });
973
+ } catch(err) {
974
+ return cb(err);
975
+ }
966
976
 
967
977
  };
968
978
 
969
- Financials.statics.getStakeholderInitialToSend = function getStakeholderInitialToSend(cb) {
979
+ Financials.statics.getStakeholderInitialToSend = async function getStakeholderInitialToSend(cb) {
970
980
 
971
- const self = this;
972
981
  const now = new Date();
973
982
 
974
- // This will get each financial doc with a snapshot that matches the query
975
- // Note that all snapshots in that doc will be returned, even ones that don't match the query
976
- const query = self.find({
977
- 'snapshots': {
978
- $elemMatch: {
979
- 'notifications.stakeholders.sendTo.email': { $ne: null },
980
- 'notifications.stakeholders.initial.sendOn': { $lte: now },
981
- 'notifications.stakeholders.initial.sentOn': null
983
+ try {
984
+ // This will get each financial doc with a snapshot that matches the query
985
+ // Note that all snapshots in that doc will be returned, even ones that don't match the query
986
+ const query = this.find({
987
+ 'snapshots': {
988
+ $elemMatch: {
989
+ 'notifications.stakeholders.sendTo.email': { $ne: null },
990
+ 'notifications.stakeholders.initial.sendOn': { $lte: now },
991
+ 'notifications.stakeholders.initial.sentOn': null
992
+ }
982
993
  }
983
- }
984
- });
994
+ });
985
995
 
986
- query.exec().then(function(financials) {financials = financials || [];
996
+ let financials = await query;
997
+ financials = financials || [];
987
998
 
988
999
  let results = [];
989
1000
 
@@ -1023,28 +1034,30 @@ module.exports = function(mongoose, config) {
1023
1034
  });
1024
1035
 
1025
1036
  return cb(null, results);
1026
-
1027
- }).catch(function(err) { cb(err); });
1037
+ } catch(err) {
1038
+ return cb(err);
1039
+ }
1028
1040
 
1029
1041
  };
1030
1042
 
1031
- Financials.statics.getStakeholderReminderToSend = function getStakeholderReminderToSend(cb) {
1043
+ Financials.statics.getStakeholderReminderToSend = async function getStakeholderReminderToSend(cb) {
1032
1044
 
1033
- var self = this;
1034
1045
  var now = new Date();
1035
1046
 
1036
- var query = self.find({
1037
- 'snapshots': {
1038
- $elemMatch: {
1039
- 'notifications.stakeholders.sendTo.email': { $ne: null },
1040
- 'notifications.stakeholders.sendTo.organization': { $ne: null },
1041
- 'notifications.stakeholders.reminders.sendOn': { $lte: now },
1042
- 'notifications.stakeholders.reminders.sentOn': null
1047
+ try {
1048
+ var query = this.find({
1049
+ 'snapshots': {
1050
+ $elemMatch: {
1051
+ 'notifications.stakeholders.sendTo.email': { $ne: null },
1052
+ 'notifications.stakeholders.sendTo.organization': { $ne: null },
1053
+ 'notifications.stakeholders.reminders.sendOn': { $lte: now },
1054
+ 'notifications.stakeholders.reminders.sentOn': null
1055
+ }
1043
1056
  }
1044
- }
1045
- });
1057
+ });
1046
1058
 
1047
- query.exec().then(function(result) {var results = [];
1059
+ const result = await query;
1060
+ var results = [];
1048
1061
 
1049
1062
  _.each(result, function(financial) {
1050
1063
 
@@ -1078,105 +1091,125 @@ module.exports = function(mongoose, config) {
1078
1091
  });
1079
1092
 
1080
1093
  return cb(null, results);
1081
-
1082
- }).catch(function(err) { cb(err); });
1094
+ } catch(err) {
1095
+ return cb(err);
1096
+ }
1083
1097
 
1084
1098
  };
1085
1099
 
1086
- Financials.statics.getForCustomer = function getForCustomer(customerId, options, cb) {
1087
-
1088
- var self = this;
1100
+ Financials.statics.getForCustomer = async function getForCustomer(customerId, options, cb) {
1089
1101
 
1090
- var query = self.find({
1091
- 'customer': customerId
1092
- });
1102
+ try {
1103
+ var query = this.find({
1104
+ 'customer': customerId
1105
+ });
1093
1106
 
1094
- var dateRangeQuery = {};
1095
- if (options.startDate) {
1096
- var startDate = new Date(options.startDate);
1097
- dateRangeQuery['$gte'] = startDate;
1098
- }
1107
+ var dateRangeQuery = {};
1108
+ if (options.startDate) {
1109
+ var startDate = new Date(options.startDate);
1110
+ dateRangeQuery['$gte'] = startDate;
1111
+ }
1099
1112
 
1100
- if (options.endDate) {
1101
- var endDate = new Date(options.endDate);
1102
- dateRangeQuery['$lte'] = endDate;
1103
- }
1113
+ if (options.endDate) {
1114
+ var endDate = new Date(options.endDate);
1115
+ dateRangeQuery['$lte'] = endDate;
1116
+ }
1104
1117
 
1105
- if (options.startDate || options.endDate) {
1106
- query.where('snapshots').elemMatch({
1107
- submittedOn: dateRangeQuery
1108
- });
1109
- }
1118
+ if (options.startDate || options.endDate) {
1119
+ query.where('snapshots').elemMatch({
1120
+ submittedOn: dateRangeQuery
1121
+ });
1122
+ }
1110
1123
 
1111
- query.exec().then(function(result) { cb(null, result); }).catch(function(err) { cb(err); });
1124
+ const result = await query;
1125
+ return cb(null, result);
1126
+ } catch(err) {
1127
+ return cb(err);
1128
+ }
1112
1129
 
1113
1130
  };
1114
1131
 
1115
- Financials.statics.getToSend = function getToSend(uuid, cb) {
1132
+ Financials.statics.getToSend = async function getToSend(uuid, cb) {
1116
1133
 
1117
- var self = this;
1118
-
1119
- var query = self.findOne({
1120
- 'snapshots.uuid': uuid
1121
- });
1134
+ try {
1135
+ var query = this.findOne({
1136
+ 'snapshots.uuid': uuid
1137
+ });
1122
1138
 
1123
- query.populate('organization', 'name logoUrl');
1124
- query.populate('customer', 'name logoUrl customer');
1125
- query.populate('snapshots.notifications.stakeholders.sendTo.organization', 'name logoUrl customer');
1139
+ query.populate('organization', 'name logoUrl');
1140
+ query.populate('customer', 'name logoUrl customer');
1141
+ query.populate('snapshots.notifications.stakeholders.sendTo.organization', 'name logoUrl customer');
1126
1142
 
1127
- query.exec().then(function(result) { cb(null, result); }).catch(function(err) { cb(err); });
1143
+ const result = await query;
1144
+ return cb(null, result);
1145
+ } catch(err) {
1146
+ return cb(err);
1147
+ }
1128
1148
 
1129
1149
  };
1130
1150
 
1131
- Financials.statics.getOverdue = function getOverdue(cb) {
1151
+ Financials.statics.getOverdue = async function getOverdue(cb) {
1132
1152
 
1133
- const self = this;
1134
-
1135
- const query = self.find({
1136
- 'snapshots': {
1137
- $elemMatch: {
1138
- 'status': { $nin: ['Completed', 'Archived', 'Overdue'] },
1139
- 'dueOn': { $lte: new Date() }
1153
+ try {
1154
+ const query = this.find({
1155
+ 'snapshots': {
1156
+ $elemMatch: {
1157
+ 'status': { $nin: ['Completed', 'Archived', 'Overdue'] },
1158
+ 'dueOn': { $lte: new Date() }
1159
+ }
1140
1160
  }
1141
- }
1142
- });
1161
+ });
1143
1162
 
1144
- query.exec().then(function(result) { cb(null, result); }).catch(function(err) { cb(err); });
1163
+ const result = await query;
1164
+ return cb(null, result);
1165
+ } catch(err) {
1166
+ return cb(err);
1167
+ }
1145
1168
 
1146
1169
  };
1147
1170
 
1148
- Financials.statics.updateProperty = function updateProperty(id, key, value, cb) {
1171
+ Financials.statics.updateProperty = async function updateProperty(id, key, value, cb) {
1149
1172
 
1150
- const self = this;
1151
- const filter = { '_id': id };
1152
- const update = { $set: { key: value } };
1153
- const options = { 'upsert': false, 'new': true };
1173
+ try {
1174
+ const filter = { '_id': id };
1175
+ const update = { $set: { key: value } };
1176
+ const options = { 'upsert': false, 'new': true };
1154
1177
 
1155
- self.findOneAndUpdate(filter, update, options).then(function(result) { cb(null, result); }).catch(function(err) { cb(err); });
1178
+ const result = await this.findOneAndUpdate(filter, update, options);
1179
+ return cb(null, result);
1180
+ } catch(err) {
1181
+ return cb(err);
1182
+ }
1156
1183
 
1157
1184
  };
1158
1185
 
1159
- Financials.statics.removeSheetFinancials = function removeSheetFinancials(customerId, cb) {
1186
+ Financials.statics.removeSheetFinancials = async function removeSheetFinancials(customerId, cb) {
1160
1187
 
1161
1188
  // this is only used to wipe out financials created by the google sheet import process
1162
1189
  // we do NOT want to delete any financials submitted via forms generated directly from the app
1163
1190
 
1164
- var self = this;
1165
-
1166
- self
1167
- .updateMany(
1191
+ try {
1192
+ const result = await this.updateMany(
1168
1193
  { customer: customerId },
1169
- { $pull : { snapshots: { submittedBy: 'Totem Sheet' } } },
1170
- { multi : true }
1171
- ).exec().then(function(result) { cb(null, result); }).catch(function(err) { cb(err); });
1194
+ { $pull : { snapshots: { submittedBy: 'Totem Sheet' } } }
1195
+ );
1196
+ return cb(null, result);
1197
+ } catch(err) {
1198
+ return cb(err);
1199
+ }
1172
1200
 
1173
1201
  };
1174
1202
 
1175
- Financials.statics.upsert = function upsert(financials, cb) {
1203
+ Financials.statics.upsert = async function upsert(financials, cb) {
1176
1204
 
1177
1205
  if (!financials) { return cb(new Error('financials is required'), null); }
1178
1206
 
1179
- financials.save().then(function(result) { cb(null, result); }).catch(function(err) { cb(err); });
1207
+ try {
1208
+ const result = await financials.save();
1209
+ return cb(null, result);
1210
+ } catch(err) {
1211
+ return cb(err);
1212
+ }
1180
1213
 
1181
1214
  };
1182
1215