@stamhoofd/models 2.137.5 → 2.138.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (118) hide show
  1. package/dist/helpers/Handlebars.d.ts.map +1 -1
  2. package/dist/helpers/Handlebars.js +1 -1
  3. package/dist/helpers/Handlebars.js.map +1 -1
  4. package/dist/helpers/errorToSimpleErrors.d.ts +3 -0
  5. package/dist/helpers/errorToSimpleErrors.d.ts.map +1 -0
  6. package/dist/helpers/errorToSimpleErrors.js +17 -0
  7. package/dist/helpers/errorToSimpleErrors.js.map +1 -0
  8. package/dist/index.d.ts +0 -1
  9. package/dist/index.d.ts.map +1 -1
  10. package/dist/index.js +0 -1
  11. package/dist/index.js.map +1 -1
  12. package/dist/migrations/1782902314-tokens-authenticated-at.sql +2 -0
  13. package/dist/migrations/1782902315-create-mfa-totp-table.sql +13 -0
  14. package/dist/migrations/1782902316-create-webauthn-credentials-table.sql +17 -0
  15. package/dist/migrations/1782902317-create-mfa-recovery-codes-table.sql +10 -0
  16. package/dist/migrations/1782902318-create-mfa-tokens-table.sql +13 -0
  17. package/dist/migrations/1782902319-create-webauthn-challenges-table.sql +10 -0
  18. package/dist/migrations/1784039947-mfa-totp-last-used-counter.sql +2 -0
  19. package/dist/migrations/1784122354-webauthn-credential-provider.sql +3 -0
  20. package/dist/migrations/1784500000-webauthn-credential-rp-id.sql +9 -0
  21. package/dist/migrations/1785354091-platform-parent-tenant-id.sql +1 -0
  22. package/dist/migrations/1785354092-platform-fees-tenant-id.sql +1 -0
  23. package/dist/migrations/1785354093-platform-uri.sql +1 -0
  24. package/dist/migrations/1785354094-platform-domain.sql +1 -0
  25. package/dist/migrations/1785354095-platform-uri-unique.sql +1 -0
  26. package/dist/migrations/1785354096-platform-domain-unique.sql +1 -0
  27. package/dist/migrations/1785354097-platform-parent-tenant-id-index.sql +1 -0
  28. package/dist/migrations/1785354098-platform-tenant-backfill.d.ts +4 -0
  29. package/dist/migrations/1785354098-platform-tenant-backfill.d.ts.map +1 -0
  30. package/dist/migrations/1785354098-platform-tenant-backfill.js +10 -0
  31. package/dist/migrations/1785354098-platform-tenant-backfill.js.map +1 -0
  32. package/dist/migrations/1785417301-users-last-active-at.sql +2 -0
  33. package/dist/models/Email.d.ts +0 -6
  34. package/dist/models/Email.d.ts.map +1 -1
  35. package/dist/models/Email.js +4 -625
  36. package/dist/models/Email.js.map +1 -1
  37. package/dist/models/MFARecoveryCode.d.ts +17 -0
  38. package/dist/models/MFARecoveryCode.d.ts.map +1 -0
  39. package/dist/models/MFARecoveryCode.js +55 -0
  40. package/dist/models/MFARecoveryCode.js.map +1 -0
  41. package/dist/models/MFATOTP.d.ts +44 -0
  42. package/dist/models/MFATOTP.d.ts.map +1 -0
  43. package/dist/models/MFATOTP.js +116 -0
  44. package/dist/models/MFATOTP.js.map +1 -0
  45. package/dist/models/MFAToken.d.ts +49 -0
  46. package/dist/models/MFAToken.d.ts.map +1 -0
  47. package/dist/models/MFAToken.js +137 -0
  48. package/dist/models/MFAToken.js.map +1 -0
  49. package/dist/models/Organization.d.ts +1 -38
  50. package/dist/models/Organization.d.ts.map +1 -1
  51. package/dist/models/Organization.js +1 -132
  52. package/dist/models/Organization.js.map +1 -1
  53. package/dist/models/Platform.d.ts +28 -4
  54. package/dist/models/Platform.d.ts.map +1 -1
  55. package/dist/models/Platform.js +109 -53
  56. package/dist/models/Platform.js.map +1 -1
  57. package/dist/models/Token.d.ts +40 -1
  58. package/dist/models/Token.d.ts.map +1 -1
  59. package/dist/models/Token.js +68 -2
  60. package/dist/models/Token.js.map +1 -1
  61. package/dist/models/User.d.ts +25 -0
  62. package/dist/models/User.d.ts.map +1 -1
  63. package/dist/models/User.js +36 -0
  64. package/dist/models/User.js.map +1 -1
  65. package/dist/models/WebauthnChallenge.d.ts +27 -0
  66. package/dist/models/WebauthnChallenge.d.ts.map +1 -0
  67. package/dist/models/WebauthnChallenge.js +81 -0
  68. package/dist/models/WebauthnChallenge.js.map +1 -0
  69. package/dist/models/WebauthnCredential.d.ts +58 -0
  70. package/dist/models/WebauthnCredential.d.ts.map +1 -0
  71. package/dist/models/WebauthnCredential.js +144 -0
  72. package/dist/models/WebauthnCredential.js.map +1 -0
  73. package/dist/models/index.d.ts +5 -0
  74. package/dist/models/index.d.ts.map +1 -1
  75. package/dist/models/index.js +5 -0
  76. package/dist/models/index.js.map +1 -1
  77. package/package.json +3 -3
  78. package/src/helpers/Handlebars.ts +5 -9
  79. package/src/helpers/errorToSimpleErrors.ts +17 -0
  80. package/src/index.ts +0 -1
  81. package/src/migrations/1782902314-tokens-authenticated-at.sql +2 -0
  82. package/src/migrations/1782902315-create-mfa-totp-table.sql +13 -0
  83. package/src/migrations/1782902316-create-webauthn-credentials-table.sql +17 -0
  84. package/src/migrations/1782902317-create-mfa-recovery-codes-table.sql +10 -0
  85. package/src/migrations/1782902318-create-mfa-tokens-table.sql +13 -0
  86. package/src/migrations/1782902319-create-webauthn-challenges-table.sql +10 -0
  87. package/src/migrations/1784039947-mfa-totp-last-used-counter.sql +2 -0
  88. package/src/migrations/1784122354-webauthn-credential-provider.sql +3 -0
  89. package/src/migrations/1784500000-webauthn-credential-rp-id.sql +9 -0
  90. package/src/migrations/1785354091-platform-parent-tenant-id.sql +1 -0
  91. package/src/migrations/1785354092-platform-fees-tenant-id.sql +1 -0
  92. package/src/migrations/1785354093-platform-uri.sql +1 -0
  93. package/src/migrations/1785354094-platform-domain.sql +1 -0
  94. package/src/migrations/1785354095-platform-uri-unique.sql +1 -0
  95. package/src/migrations/1785354096-platform-domain-unique.sql +1 -0
  96. package/src/migrations/1785354097-platform-parent-tenant-id-index.sql +1 -0
  97. package/src/migrations/1785354098-platform-tenant-backfill.ts +14 -0
  98. package/src/migrations/1785417301-users-last-active-at.sql +2 -0
  99. package/src/models/Email.ts +4 -713
  100. package/src/models/MFARecoveryCode.ts +52 -0
  101. package/src/models/MFATOTP.ts +112 -0
  102. package/src/models/MFAToken.ts +138 -0
  103. package/src/models/Organization.test.ts +0 -46
  104. package/src/models/Organization.ts +0 -154
  105. package/src/models/Platform.test.ts +167 -3
  106. package/src/models/Platform.ts +121 -53
  107. package/src/models/Token.ts +73 -2
  108. package/src/models/User.ts +37 -0
  109. package/src/models/WebauthnChallenge.ts +80 -0
  110. package/src/models/WebauthnCredential.ts +130 -0
  111. package/src/models/index.ts +6 -0
  112. package/dist/helpers/EmailBuilder.d.ts +0 -121
  113. package/dist/helpers/EmailBuilder.d.ts.map +0 -1
  114. package/dist/helpers/EmailBuilder.js +0 -659
  115. package/dist/helpers/EmailBuilder.js.map +0 -1
  116. package/src/helpers/EmailBuilder.test.ts +0 -291
  117. package/src/helpers/EmailBuilder.ts +0 -818
  118. package/src/models/Email.test.ts +0 -1222
@@ -1,34 +1,16 @@
1
1
  import { __decorate } from "tslib";
2
2
  import { column } from '@simonbackx/simple-database';
3
- import { EmailAttachment, EmailContent, EmailRecipientFilter, EmailRecipientsStatus, EmailStatus, Email as EmailStruct, isSoftEmailRecipientError, LanguageHelper, LimitedFilteredRequest, SortItemDirection } from '@stamhoofd/structures';
3
+ import { EmailAttachment, EmailContent, EmailRecipientFilter, EmailRecipientsStatus, EmailStatus, Email as EmailStruct, LanguageHelper, LimitedFilteredRequest, SortItemDirection } from '@stamhoofd/structures';
4
4
  import { Language } from '@stamhoofd/types/Language';
5
5
  import { v4 as uuidv4 } from 'uuid';
6
6
  import { AnyDecoder, ArrayDecoder, EnumDecoder, MapDecoder } from '@simonbackx/simple-encoding';
7
- import { isSimpleError, isSimpleErrors, SimpleError, SimpleErrors } from '@simonbackx/simple-errors';
7
+ import { SimpleError, SimpleErrors } from '@simonbackx/simple-errors';
8
8
  import { I18n } from '@stamhoofd/backend-i18n/I18n';
9
- import { Email as EmailClass } from '@stamhoofd/email';
10
9
  import { isAbortedError, QueueHandler } from '@stamhoofd/queues';
11
- import { QueryableModel, readDynamicSQLExpression, SQL, SQLAlias, SQLCount, SQLSelectAs, SQLWhereSign } from '@stamhoofd/sql';
12
- import { canSendFromEmail, fillRecipientReplacements, getEmailBuilder, mergeReplacementsIfEqual, removeUnusedReplacements } from '../helpers/EmailBuilder.js';
10
+ import { QueryableModel, readDynamicSQLExpression, SQL, SQLAlias, SQLCount, SQLSelectAs } from '@stamhoofd/sql';
11
+ import { errorToSimpleErrors } from '../helpers/errorToSimpleErrors.js';
13
12
  import { EmailRecipient } from './EmailRecipient.js';
14
13
  import { EmailTemplate } from './EmailTemplate.js';
15
- import { Organization } from './Organization.js';
16
- import { Platform } from './Platform.js';
17
- function errorToSimpleErrors(e) {
18
- if (isSimpleErrors(e)) {
19
- return e;
20
- }
21
- else if (isSimpleError(e)) {
22
- return new SimpleErrors(e);
23
- }
24
- else {
25
- return new SimpleErrors(new SimpleError({
26
- code: 'unknown_error',
27
- message: ((typeof e === 'object' && e !== null && 'message' in e && typeof e.message === 'string') ? e.message : 'Unknown error'),
28
- human: $t(`%1ED`),
29
- }));
30
- }
31
- }
32
14
  export class Email extends QueryableModel {
33
15
  static table = 'emails';
34
16
  id;
@@ -443,405 +425,6 @@ export class Email extends QueryableModel {
443
425
  .update();
444
426
  });
445
427
  }
446
- async queueForSending(waitForSending = false) {
447
- console.log('Queueing email for sending', this.id);
448
- this.throwIfNotReadyToSend();
449
- this.throwIfNoUnsubscribeButton();
450
- await this.lock(async (upToDate) => {
451
- if (upToDate.status === EmailStatus.Draft) {
452
- upToDate.status = EmailStatus.Queued;
453
- }
454
- if (upToDate.status === EmailStatus.Failed) {
455
- // Retry failed email
456
- upToDate.status = EmailStatus.Queued;
457
- }
458
- await upToDate.save();
459
- });
460
- if (waitForSending) {
461
- return await this.resumeSending();
462
- }
463
- else {
464
- this.resumeSending().catch(console.error);
465
- }
466
- return this;
467
- }
468
- async loadAttachments() {
469
- const attachments = [];
470
- for (const attachment of this.attachments) {
471
- if (!attachment.content && !attachment.file) {
472
- console.warn('Attachment without content found, skipping', attachment);
473
- continue;
474
- }
475
- let filename = $t('%180');
476
- if (attachment.contentType === 'application/pdf') {
477
- // tmp solution for pdf only
478
- filename += '.pdf';
479
- }
480
- if (attachment.file?.name) {
481
- filename = attachment.file.name.toLowerCase().replace(/[^a-z0-9.]+/g, '-').replace(/^-+/, '').replace(/-+$/, '');
482
- }
483
- // Correct file name if needed
484
- if (attachment.filename) {
485
- filename = attachment.filename.toLowerCase().replace(/[^a-z0-9.]+/g, '-').replace(/^-+/, '').replace(/-+$/, '');
486
- }
487
- if (attachment.content) {
488
- attachments.push({
489
- filename: filename,
490
- content: attachment.content,
491
- contentType: attachment.contentType ?? undefined,
492
- encoding: 'base64',
493
- });
494
- }
495
- else {
496
- // Note: because we send lots of emails, we better download the file here so we can reuse it in every email instead of downloading it every time
497
- const withSigned = await attachment.file.withSignedUrl();
498
- if (!withSigned || !withSigned.signedUrl) {
499
- throw new SimpleError({
500
- code: 'attachment_not_found',
501
- message: 'Attachment not found',
502
- human: $t(`%181`),
503
- });
504
- }
505
- const filePath = withSigned.signedUrl;
506
- let fileBuffer;
507
- try {
508
- const response = await fetch(filePath);
509
- fileBuffer = Buffer.from(await response.arrayBuffer());
510
- }
511
- catch (e) {
512
- throw new SimpleError({
513
- code: 'attachment_not_found',
514
- message: 'Attachment not found',
515
- human: $t(`%181`),
516
- });
517
- }
518
- attachments.push({
519
- filename: filename,
520
- contentType: attachment.contentType ?? undefined,
521
- content: fileBuffer,
522
- });
523
- }
524
- }
525
- return attachments;
526
- }
527
- async sendSingleRecipient(recipient, organization, data) {
528
- let promiseResolve;
529
- const promise = new Promise((resolve) => {
530
- promiseResolve = resolve;
531
- });
532
- const virtualRecipient = recipient.getRecipient();
533
- let resolved = false;
534
- const callback = async (error) => {
535
- if (resolved) {
536
- return;
537
- }
538
- resolved = true;
539
- try {
540
- if (error === null) {
541
- // Mark saved
542
- recipient.sentAt = new Date();
543
- recipient.failErrorMessage = null;
544
- if (recipient.failError) {
545
- recipient.previousFailError = recipient.failError;
546
- }
547
- recipient.failError = null;
548
- // Update repacements that have been generated
549
- recipient.replacements = virtualRecipient.replacements;
550
- await recipient.save();
551
- }
552
- else {
553
- recipient.failCount += 1;
554
- recipient.failErrorMessage = error.message;
555
- if (recipient.failError) {
556
- recipient.previousFailError = recipient.failError;
557
- }
558
- recipient.failError = errorToSimpleErrors(error);
559
- recipient.firstFailedAt = recipient.firstFailedAt ?? new Date();
560
- recipient.lastFailedAt = new Date();
561
- await recipient.save();
562
- }
563
- }
564
- catch (e) {
565
- console.error(e);
566
- }
567
- promiseResolve();
568
- };
569
- // Do send the email
570
- // Create e-mail builder
571
- const builder = await getEmailBuilder(organization ?? null, {
572
- recipients: [
573
- virtualRecipient,
574
- ],
575
- from: data.from,
576
- replyTo: data.replyTo,
577
- subject: this.subject,
578
- html: this.html,
579
- translations: this.translations,
580
- type: this.emailType ? 'transactional' : 'broadcast',
581
- attachments: data.attachments,
582
- callback(error) {
583
- callback(error).catch(console.error);
584
- },
585
- headers: {
586
- 'X-Email-Id': this.id,
587
- 'X-Email-Recipient-Id': recipient.id,
588
- },
589
- });
590
- EmailClass.schedule(builder);
591
- return await promise;
592
- }
593
- async resumeSending(singleRecipientId = null) {
594
- const id = this.id;
595
- return await QueueHandler.schedule('send-email', async ({ abort }) => {
596
- return await this.lock(async function (upToDate) {
597
- if (upToDate.status === EmailStatus.Sent) {
598
- // Already done
599
- // In other cases -> queue has stopped and we can retry
600
- if (!singleRecipientId) {
601
- console.log('Email already sent, skipping...', upToDate.id);
602
- return upToDate;
603
- }
604
- }
605
- else {
606
- if (singleRecipientId) {
607
- // Not possible
608
- throw new SimpleError({
609
- code: 'invalid_state',
610
- message: 'Cannot retry single recipient for email that is not yet sent',
611
- });
612
- }
613
- if (upToDate.status === EmailStatus.Sending) {
614
- // This is an automatic retry.
615
- if (upToDate.emailType) {
616
- // Not eligible for retry
617
- upToDate.status = EmailStatus.Failed;
618
- await upToDate.save();
619
- return upToDate;
620
- }
621
- if (upToDate.createdAt < new Date(new Date().getTime() - 1000 * 60 * 60 * 24 * 2)) {
622
- // Too long
623
- console.error('Email has been sending for too long. Marking as failed...', upToDate.id);
624
- upToDate.status = EmailStatus.Failed;
625
- await upToDate.save();
626
- return upToDate;
627
- }
628
- }
629
- else if (upToDate.status !== EmailStatus.Queued) {
630
- console.error('Email is not queued or sending, cannot send', upToDate.id, upToDate.status);
631
- return upToDate;
632
- }
633
- }
634
- const organization = upToDate.organizationId ? await Organization.getByID(upToDate.organizationId) : null;
635
- let from = upToDate.getDefaultFromAddress(organization);
636
- let replyTo = upToDate.getFromAddress();
637
- let succeededCount = 0;
638
- let softFailedCount = 0;
639
- let failedCount = 0;
640
- try {
641
- upToDate.throwIfNotReadyToSend();
642
- upToDate.throwIfNoUnsubscribeButton();
643
- if (!from) {
644
- throw new SimpleError({
645
- code: 'invalid_field',
646
- message: 'Missing from',
647
- human: $t(`%ww`),
648
- });
649
- }
650
- // Can we send from this e-mail or reply-to?
651
- if (upToDate.fromAddress && await canSendFromEmail(upToDate.fromAddress, organization ?? null)) {
652
- from = upToDate.getFromAddress();
653
- replyTo = null;
654
- }
655
- abort.throwIfAborted();
656
- if (!singleRecipientId) {
657
- upToDate.status = EmailStatus.Sending;
658
- }
659
- upToDate.sentAt = upToDate.sentAt ?? new Date();
660
- await upToDate.save();
661
- // Create recipients if not yet created
662
- await upToDate.buildRecipients();
663
- abort.throwIfAborted();
664
- // Refresh model
665
- const c = (await Email.getByID(id));
666
- if (!c) {
667
- throw new SimpleError({
668
- code: 'not_found',
669
- message: 'Email not found',
670
- human: $t(`%wz`),
671
- });
672
- }
673
- upToDate.copyFrom(c);
674
- if (upToDate.recipientsStatus !== EmailRecipientsStatus.Created) {
675
- throw new SimpleError({
676
- code: 'recipients_not_created',
677
- message: 'Failed to create recipients',
678
- human: $t(`%x0`),
679
- });
680
- }
681
- // Create a buffer of all attachments
682
- if (upToDate.sendAsEmail === true) {
683
- const attachments = await upToDate.loadAttachments();
684
- // Start actually sending in batches of recipients that are not yet sent
685
- let idPointer = '';
686
- const batchSize = 100;
687
- let isSavingStatus = false;
688
- let lastStatusSave = new Date();
689
- async function saveStatus() {
690
- if (singleRecipientId) {
691
- // Don't save during looping
692
- return;
693
- }
694
- if (!upToDate) {
695
- return;
696
- }
697
- if (isSavingStatus) {
698
- return;
699
- }
700
- if ((new Date().getTime() - lastStatusSave.getTime()) < 1000 * 5) {
701
- // Save at most every 5 seconds
702
- return;
703
- }
704
- if (succeededCount < upToDate.succeededCount || softFailedCount < upToDate.softFailedCount || failedCount < upToDate.failedCount) {
705
- // Do not update on retries
706
- return;
707
- }
708
- lastStatusSave = new Date();
709
- isSavingStatus = true;
710
- upToDate.succeededCount = succeededCount;
711
- upToDate.softFailedCount = softFailedCount;
712
- upToDate.failedCount = failedCount;
713
- try {
714
- await upToDate.save();
715
- }
716
- finally {
717
- isSavingStatus = false;
718
- }
719
- }
720
- while (true) {
721
- abort.throwIfAborted();
722
- const data = await SQL.select()
723
- .from('email_recipients')
724
- .where('emailId', upToDate.id)
725
- .where('id', SQLWhereSign.Greater, idPointer)
726
- .orderBy(SQL.column('id'), 'ASC')
727
- .limit(batchSize)
728
- .fetch();
729
- const recipients = EmailRecipient.fromRows(data, 'email_recipients');
730
- if (recipients.length === 0) {
731
- break;
732
- }
733
- const sendingPromises = [];
734
- let skipped = 0;
735
- for (const recipient of recipients) {
736
- idPointer = recipient.id;
737
- if (recipient.sentAt) {
738
- succeededCount += 1;
739
- await saveStatus();
740
- skipped++;
741
- continue;
742
- }
743
- if (!recipient.email) {
744
- skipped++;
745
- continue;
746
- }
747
- if (recipient.duplicateOfRecipientId) {
748
- skipped++;
749
- continue;
750
- }
751
- if (singleRecipientId) {
752
- if (recipient.id !== singleRecipientId) {
753
- // Failed or soft-failed
754
- if (recipient.failError && isSoftEmailRecipientError(recipient.failError)) {
755
- softFailedCount += 1;
756
- }
757
- else {
758
- failedCount += 1;
759
- }
760
- skipped++;
761
- await saveStatus();
762
- continue;
763
- }
764
- }
765
- const promise = upToDate.sendSingleRecipient(recipient, organization ?? null, {
766
- from,
767
- replyTo,
768
- attachments,
769
- });
770
- sendingPromises.push(promise.then(async () => {
771
- if (recipient.sentAt) {
772
- succeededCount += 1;
773
- await saveStatus();
774
- }
775
- else {
776
- // Failed or soft-failed
777
- if (recipient.failError && isSoftEmailRecipientError(recipient.failError)) {
778
- softFailedCount += 1;
779
- }
780
- else {
781
- failedCount += 1;
782
- }
783
- await saveStatus();
784
- }
785
- }));
786
- }
787
- if (sendingPromises.length > 0 || skipped > 0) {
788
- await Promise.all(sendingPromises);
789
- }
790
- else {
791
- break;
792
- }
793
- }
794
- }
795
- }
796
- catch (e) {
797
- if (!upToDate) {
798
- throw e;
799
- }
800
- if (!singleRecipientId) {
801
- upToDate.succeededCount = succeededCount;
802
- upToDate.softFailedCount = softFailedCount;
803
- upToDate.failedCount = failedCount;
804
- if (isAbortedError(e) || ((isSimpleError(e) || isSimpleErrors(e)) && e.hasCode('SHUTDOWN'))) {
805
- // Keep sending status: we'll resume after the reboot
806
- await upToDate.save();
807
- throw e;
808
- }
809
- upToDate.emailErrors = errorToSimpleErrors(e);
810
- upToDate.status = EmailStatus.Failed;
811
- await upToDate.save();
812
- }
813
- throw e;
814
- }
815
- if (!singleRecipientId) {
816
- if (upToDate.sendAsEmail && upToDate.emailRecipientsCount === 0 && upToDate.userId === null) {
817
- // We only delete automated emails (email type) if they have no recipients
818
- console.log('No recipients found for email ', upToDate.id, ' deleting...');
819
- await upToDate.delete();
820
- return null;
821
- }
822
- console.log('Finished sending email', upToDate.id);
823
- // Mark email as sent
824
- if (upToDate.sendAsEmail && !upToDate.showInMemberPortal && (succeededCount + failedCount + softFailedCount) === 0) {
825
- upToDate.status = EmailStatus.Failed;
826
- upToDate.emailErrors = new SimpleErrors(new SimpleError({
827
- code: 'no_recipients',
828
- message: 'No recipients',
829
- human: $t(`%1EG`),
830
- }));
831
- }
832
- else {
833
- upToDate.status = EmailStatus.Sent;
834
- upToDate.emailErrors = null;
835
- }
836
- }
837
- upToDate.succeededCount = succeededCount;
838
- upToDate.softFailedCount = softFailedCount;
839
- upToDate.failedCount = failedCount;
840
- await upToDate.save();
841
- return upToDate;
842
- });
843
- });
844
- }
845
428
  async updateCount() {
846
429
  // First reset
847
430
  const id = this.id;
@@ -924,210 +507,6 @@ export class Email extends QueryableModel {
924
507
  getLanguages() {
925
508
  return this.language ? [this.language, ...this.translations.keys()] : null;
926
509
  }
927
- async buildRecipients() {
928
- const id = this.id;
929
- await QueueHandler.schedule('email-build-recipients-' + this.id, async function ({ abort }) {
930
- const upToDate = await Email.getByID(id);
931
- if (!upToDate || !upToDate.id) {
932
- return;
933
- }
934
- if (upToDate.recipientsStatus === EmailRecipientsStatus.Created) {
935
- return;
936
- }
937
- if (upToDate.status === EmailStatus.Sent) {
938
- return;
939
- }
940
- abort.throwIfAborted();
941
- const organization = upToDate.organizationId ? (await Organization.getByID(upToDate.organizationId) ?? null) : null;
942
- if (upToDate.organizationId && !organization) {
943
- throw new SimpleError({
944
- code: 'organization_not_found',
945
- message: 'Organization not found',
946
- human: $t(`%1NV`),
947
- });
948
- }
949
- const platform = await Platform.getSharedPrivateStruct();
950
- console.log('Building recipients for email', id);
951
- // If it is already creating -> something went wrong (e.g. server restart) and we can safely try again
952
- upToDate.recipientsStatus = EmailRecipientsStatus.Creating;
953
- await upToDate.save();
954
- const membersSet = new Set();
955
- const emailsSet = new Set();
956
- const combinedHtml = upToDate.getCombinedHtml();
957
- let count = 0;
958
- let countWithoutEmail = 0;
959
- try {
960
- // Delete all recipients
961
- await SQL
962
- .delete()
963
- .from(SQL.table('email_recipients'))
964
- .where(SQL.column('emailId'), upToDate.id);
965
- abort.throwIfAborted();
966
- for (const subfilter of upToDate.recipientFilter.filters) {
967
- // Create recipients
968
- const loader = Email.recipientLoaders.get(subfilter.type);
969
- if (!loader) {
970
- throw new Error('Loader for type ' + subfilter.type + ' has not been initialised on the Email model');
971
- }
972
- let request = new LimitedFilteredRequest({
973
- filter: subfilter.filter,
974
- sort: [{ key: 'id', order: SortItemDirection.ASC }],
975
- limit: 100,
976
- search: subfilter.search,
977
- });
978
- const beforeFetchAllResult = loader.beforeFetchAll ? await loader.beforeFetchAll(request, subfilter.subfilter) : undefined;
979
- while (request) {
980
- abort.throwIfAborted();
981
- const response = await loader.fetch(request, subfilter.subfilter, beforeFetchAllResult, { allowedLanguages: upToDate.getLanguages() });
982
- for (const item of response.results) {
983
- if (!item.email && !item.memberId && !item.userId) {
984
- continue;
985
- }
986
- const recipient = new EmailRecipient();
987
- recipient.emailType = upToDate.emailType;
988
- recipient.objectId = item.objectId;
989
- recipient.emailId = upToDate.id;
990
- recipient.email = item.email;
991
- recipient.firstName = item.firstName;
992
- recipient.lastName = item.lastName;
993
- recipient.language = item.language ?? null;
994
- recipient.replacements = item.replacements;
995
- recipient.memberId = item.memberId ?? null;
996
- recipient.userId = item.userId ?? null;
997
- recipient.organizationId = upToDate.organizationId ?? null;
998
- await fillRecipientReplacements(recipient, {
999
- platform,
1000
- organization,
1001
- from: upToDate.getFromAddress(),
1002
- replyTo: null,
1003
- forPreview: false,
1004
- allowedLanguages: upToDate.getLanguages(),
1005
- });
1006
- recipient.replacements = removeUnusedReplacements(combinedHtml, recipient.replacements);
1007
- let duplicateOfRecipientId = null;
1008
- if (item.email && emailsSet.has(item.email)) {
1009
- console.log('Found duplicate email recipient', item.email);
1010
- // Try to merge
1011
- const existing = await EmailRecipient.select()
1012
- .where('emailId', upToDate.id)
1013
- .where('email', item.email)
1014
- .where('duplicateOfRecipientId', null)
1015
- .fetch();
1016
- for (const other of existing) {
1017
- const merged = mergeReplacementsIfEqual(other.replacements, recipient.replacements);
1018
- if (merged !== false) {
1019
- console.log('Found mergeable duplicate email recipient', item.email, other.id);
1020
- duplicateOfRecipientId = other.id;
1021
- other.replacements = merged;
1022
- other.firstName = other.firstName || item.firstName;
1023
- other.lastName = other.lastName || item.lastName;
1024
- await other.save();
1025
- recipient.replacements = merged;
1026
- break;
1027
- }
1028
- else {
1029
- console.log('Could not merge duplicate email recipient', item.email, other.id, 'keeping both', other.replacements, item.replacements);
1030
- }
1031
- }
1032
- }
1033
- recipient.duplicateOfRecipientId = duplicateOfRecipientId;
1034
- await recipient.save();
1035
- if (recipient.memberId) {
1036
- membersSet.add(recipient.memberId);
1037
- }
1038
- if (recipient.email) {
1039
- emailsSet.add(recipient.email);
1040
- }
1041
- if (!recipient.email || duplicateOfRecipientId) {
1042
- countWithoutEmail += 1;
1043
- }
1044
- else {
1045
- count += 1;
1046
- }
1047
- }
1048
- request = response.next ?? null;
1049
- }
1050
- }
1051
- upToDate.recipientsStatus = EmailRecipientsStatus.Created;
1052
- upToDate.emailRecipientsCount = count;
1053
- upToDate.otherRecipientsCount = countWithoutEmail;
1054
- upToDate.recipientsErrors = null;
1055
- upToDate.membersCount = membersSet.size;
1056
- await upToDate.save();
1057
- }
1058
- catch (e) {
1059
- console.error('Failed to build recipients for email', id);
1060
- console.error(e);
1061
- upToDate.recipientsStatus = EmailRecipientsStatus.NotCreated;
1062
- upToDate.recipientsErrors = errorToSimpleErrors(e);
1063
- await upToDate.save();
1064
- }
1065
- });
1066
- }
1067
- async buildExampleRecipient(isNewlyCreated = false) {
1068
- const id = this.id;
1069
- await QueueHandler.schedule('email-build-recipients-' + this.id, async function () {
1070
- const upToDate = await Email.getByID(id);
1071
- if (!upToDate || upToDate.sentAt || !upToDate.id) {
1072
- return;
1073
- }
1074
- if (upToDate.recipientsStatus !== EmailRecipientsStatus.NotCreated) {
1075
- return;
1076
- }
1077
- try {
1078
- // Delete all recipients
1079
- if (!isNewlyCreated) {
1080
- await SQL
1081
- .delete()
1082
- .from(SQL.table('email_recipients'))
1083
- .where(SQL.column('emailId'), upToDate.id);
1084
- }
1085
- for (const subfilter of upToDate.recipientFilter.filters) {
1086
- // Create recipients
1087
- const loader = Email.recipientLoaders.get(subfilter.type);
1088
- if (!loader) {
1089
- throw new Error('Loader for type ' + subfilter.type + ' has not been initialised on the Email model');
1090
- }
1091
- let request = new LimitedFilteredRequest({
1092
- filter: subfilter.filter,
1093
- sort: [{ key: 'id', order: SortItemDirection.ASC }],
1094
- limit: 10,
1095
- search: subfilter.search,
1096
- });
1097
- const beforeFetchAllResult = loader.beforeFetchAll ? await loader.beforeFetchAll(request, subfilter.subfilter) : undefined;
1098
- while (request) {
1099
- const response = await loader.fetch(request, subfilter.subfilter, beforeFetchAllResult, { allowedLanguages: upToDate.getLanguages() });
1100
- // Note: it is possible that a result in the database doesn't return a recipient (in memory filtering)
1101
- // so we do need pagination
1102
- for (const item of response.results) {
1103
- const recipient = new EmailRecipient();
1104
- recipient.emailType = upToDate.emailType;
1105
- recipient.emailId = upToDate.id;
1106
- recipient.objectId = item.objectId;
1107
- recipient.email = item.email;
1108
- recipient.firstName = item.firstName;
1109
- recipient.lastName = item.lastName;
1110
- recipient.language = item.language ?? null;
1111
- recipient.replacements = item.replacements;
1112
- recipient.memberId = item.memberId ?? null;
1113
- recipient.userId = item.userId ?? null;
1114
- recipient.organizationId = upToDate.organizationId ?? null;
1115
- await recipient.save();
1116
- if (recipient.email || recipient.userId) {
1117
- return;
1118
- }
1119
- }
1120
- request = null;
1121
- }
1122
- }
1123
- console.warn('No example recipient found for email', id);
1124
- }
1125
- catch (e) {
1126
- console.error('Failed to build example recipient for email', id);
1127
- console.error(e);
1128
- }
1129
- });
1130
- }
1131
510
  getStructure() {
1132
511
  return EmailStruct.create(this);
1133
512
  }