@stamhoofd/models 2.137.5 → 2.138.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (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,42 +1,22 @@
1
1
  import { column } from '@simonbackx/simple-database';
2
2
  import type { EmailRecipient as EmailRecipientStruct, EmailTemplateType, PaginatedResponse, StamhoofdFilter } from '@stamhoofd/structures';
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 type { Country } from '@stamhoofd/types/Country';
5
5
  import { Language } from '@stamhoofd/types/Language';
6
6
  import { v4 as uuidv4 } from 'uuid';
7
7
  import type { EmailRecipientFilterType } from '@stamhoofd/structures/email/EmailRecipientFilterType.js';
8
8
  import type { Decoder } from '@simonbackx/simple-encoding';
9
9
  import { AnyDecoder, ArrayDecoder, EnumDecoder, MapDecoder } from '@simonbackx/simple-encoding';
10
- import { isSimpleError, isSimpleErrors, SimpleError, SimpleErrors } from '@simonbackx/simple-errors';
10
+ import { SimpleError, SimpleErrors } from '@simonbackx/simple-errors';
11
11
  import { I18n } from '@stamhoofd/backend-i18n/I18n';
12
12
  import type { EmailInterfaceRecipient } from '@stamhoofd/email';
13
- import { Email as EmailClass } from '@stamhoofd/email';
14
13
  import type { QueueHandlerOptions } from '@stamhoofd/queues';
15
14
  import { isAbortedError, QueueHandler } from '@stamhoofd/queues';
16
- import { QueryableModel, readDynamicSQLExpression, SQL, SQLAlias, SQLCount, SQLSelectAs, SQLWhereSign } from '@stamhoofd/sql';
17
- import { canSendFromEmail, fillRecipientReplacements, getEmailBuilder, mergeReplacementsIfEqual, removeUnusedReplacements } from '../helpers/EmailBuilder.js';
15
+ import { QueryableModel, readDynamicSQLExpression, SQL, SQLAlias, SQLCount, SQLSelectAs } from '@stamhoofd/sql';
16
+ import { errorToSimpleErrors } from '../helpers/errorToSimpleErrors.js';
18
17
  import { EmailRecipient } from './EmailRecipient.js';
19
18
  import { EmailTemplate } from './EmailTemplate.js';
20
19
  import { Organization } from './Organization.js';
21
- import { Platform } from './Platform.js';
22
-
23
- type Attachment = { filename: string; path?: string; href?: string; content?: string | Buffer; contentType?: string; encoding?: string };
24
-
25
- function errorToSimpleErrors(e: unknown) {
26
- if (isSimpleErrors(e)) {
27
- return e;
28
- } else if (isSimpleError(e)) {
29
- return new SimpleErrors(e);
30
- } else {
31
- return new SimpleErrors(
32
- new SimpleError({
33
- code: 'unknown_error',
34
- message: ((typeof e === 'object' && e !== null && 'message' in e && typeof e.message === 'string') ? e.message : 'Unknown error'),
35
- human: $t(`%1ED`),
36
- }),
37
- );
38
- }
39
- }
40
20
 
41
21
  export type RecipientLoader<BeforeFetchAllResult = any> = {
42
22
  /**
@@ -634,445 +614,6 @@ export class Email extends QueryableModel {
634
614
  });
635
615
  }
636
616
 
637
- async queueForSending(waitForSending = false) {
638
- console.log('Queueing email for sending', this.id);
639
- this.throwIfNotReadyToSend();
640
- this.throwIfNoUnsubscribeButton();
641
- await this.lock(async (upToDate) => {
642
- if (upToDate.status === EmailStatus.Draft) {
643
- upToDate.status = EmailStatus.Queued;
644
- }
645
- if (upToDate.status === EmailStatus.Failed) {
646
- // Retry failed email
647
- upToDate.status = EmailStatus.Queued;
648
- }
649
- await upToDate.save();
650
- });
651
- if (waitForSending) {
652
- return await this.resumeSending();
653
- } else {
654
- this.resumeSending().catch(console.error);
655
- }
656
- return this;
657
- }
658
-
659
- private async loadAttachments(): Promise<Attachment[]> {
660
- const attachments: Attachment[] = [];
661
- for (const attachment of this.attachments) {
662
- if (!attachment.content && !attachment.file) {
663
- console.warn('Attachment without content found, skipping', attachment);
664
- continue;
665
- }
666
-
667
- let filename = $t('%180');
668
-
669
- if (attachment.contentType === 'application/pdf') {
670
- // tmp solution for pdf only
671
- filename += '.pdf';
672
- }
673
-
674
- if (attachment.file?.name) {
675
- filename = attachment.file.name.toLowerCase().replace(/[^a-z0-9.]+/g, '-').replace(/^-+/, '').replace(/-+$/, '');
676
- }
677
-
678
- // Correct file name if needed
679
- if (attachment.filename) {
680
- filename = attachment.filename.toLowerCase().replace(/[^a-z0-9.]+/g, '-').replace(/^-+/, '').replace(/-+$/, '');
681
- }
682
-
683
- if (attachment.content) {
684
- attachments.push({
685
- filename: filename,
686
- content: attachment.content,
687
- contentType: attachment.contentType ?? undefined,
688
- encoding: 'base64',
689
- });
690
- } else {
691
- // 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
692
- const withSigned = await attachment.file!.withSignedUrl();
693
- if (!withSigned || !withSigned.signedUrl) {
694
- throw new SimpleError({
695
- code: 'attachment_not_found',
696
- message: 'Attachment not found',
697
- human: $t(`%181`),
698
- });
699
- }
700
-
701
- const filePath = withSigned.signedUrl;
702
- let fileBuffer: Buffer | null;
703
- try {
704
- const response = await fetch(filePath);
705
- fileBuffer = Buffer.from(await response.arrayBuffer());
706
- } catch (e) {
707
- throw new SimpleError({
708
- code: 'attachment_not_found',
709
- message: 'Attachment not found',
710
- human: $t(`%181`),
711
- });
712
- }
713
-
714
- attachments.push({
715
- filename: filename,
716
- contentType: attachment.contentType ?? undefined,
717
- content: fileBuffer,
718
- });
719
- }
720
- }
721
- return attachments;
722
- }
723
-
724
- private async sendSingleRecipient(recipient: EmailRecipient, organization: Organization | null, data: { from: EmailInterfaceRecipient; replyTo: EmailInterfaceRecipient | null; attachments: Attachment[] }) {
725
- let promiseResolve: (value: void | PromiseLike<void>) => void;
726
- const promise = new Promise<void>((resolve) => {
727
- promiseResolve = resolve;
728
- });
729
-
730
- const virtualRecipient = recipient.getRecipient();
731
-
732
- let resolved = false;
733
- const callback = async (error: Error | null) => {
734
- if (resolved) {
735
- return;
736
- }
737
- resolved = true;
738
-
739
- try {
740
- if (error === null) {
741
- // Mark saved
742
- recipient.sentAt = new Date();
743
- recipient.failErrorMessage = null;
744
-
745
- if (recipient.failError) {
746
- recipient.previousFailError = recipient.failError;
747
- }
748
- recipient.failError = null;
749
-
750
- // Update repacements that have been generated
751
- recipient.replacements = virtualRecipient.replacements;
752
- await recipient.save();
753
- } else {
754
- recipient.failCount += 1;
755
- recipient.failErrorMessage = error.message;
756
- if (recipient.failError) {
757
- recipient.previousFailError = recipient.failError;
758
- }
759
- recipient.failError = errorToSimpleErrors(error);
760
- recipient.firstFailedAt = recipient.firstFailedAt ?? new Date();
761
- recipient.lastFailedAt = new Date();
762
- await recipient.save();
763
- }
764
- } catch (e) {
765
- console.error(e);
766
- }
767
- promiseResolve();
768
- };
769
-
770
- // Do send the email
771
- // Create e-mail builder
772
- const builder = await getEmailBuilder(organization ?? null, {
773
- recipients: [
774
- virtualRecipient,
775
- ],
776
- from: data.from,
777
- replyTo: data.replyTo,
778
- subject: this.subject!,
779
- html: this.html!,
780
- translations: this.translations,
781
- type: this.emailType ? 'transactional' : 'broadcast',
782
- attachments: data.attachments,
783
- callback(error: Error | null) {
784
- callback(error).catch(console.error);
785
- },
786
- headers: {
787
- 'X-Email-Id': this.id,
788
- 'X-Email-Recipient-Id': recipient.id,
789
- },
790
- });
791
- EmailClass.schedule(builder);
792
- return await promise;
793
- }
794
-
795
- async resumeSending(singleRecipientId: string | null = null): Promise<Email | null> {
796
- const id = this.id;
797
- return await QueueHandler.schedule('send-email', async ({ abort }) => {
798
- return await this.lock(async function (upToDate: Email) {
799
- if (upToDate.status === EmailStatus.Sent) {
800
- // Already done
801
- // In other cases -> queue has stopped and we can retry
802
- if (!singleRecipientId) {
803
- console.log('Email already sent, skipping...', upToDate.id);
804
- return upToDate;
805
- }
806
- } else {
807
- if (singleRecipientId) {
808
- // Not possible
809
- throw new SimpleError({
810
- code: 'invalid_state',
811
- message: 'Cannot retry single recipient for email that is not yet sent',
812
- });
813
- }
814
-
815
- if (upToDate.status === EmailStatus.Sending) {
816
- // This is an automatic retry.
817
- if (upToDate.emailType) {
818
- // Not eligible for retry
819
- upToDate.status = EmailStatus.Failed;
820
- await upToDate.save();
821
- return upToDate;
822
- }
823
- if (upToDate.createdAt < new Date(new Date().getTime() - 1000 * 60 * 60 * 24 * 2)) {
824
- // Too long
825
- console.error('Email has been sending for too long. Marking as failed...', upToDate.id);
826
- upToDate.status = EmailStatus.Failed;
827
- await upToDate.save();
828
- return upToDate;
829
- }
830
- } else if (upToDate.status !== EmailStatus.Queued) {
831
- console.error('Email is not queued or sending, cannot send', upToDate.id, upToDate.status);
832
- return upToDate;
833
- }
834
- }
835
-
836
- const organization = upToDate.organizationId ? await Organization.getByID(upToDate.organizationId) : null;
837
- let from = upToDate.getDefaultFromAddress(organization);
838
- let replyTo: EmailInterfaceRecipient | null = upToDate.getFromAddress();
839
- let succeededCount = 0;
840
- let softFailedCount = 0;
841
- let failedCount = 0;
842
-
843
- try {
844
- upToDate.throwIfNotReadyToSend();
845
- upToDate.throwIfNoUnsubscribeButton();
846
-
847
- if (!from) {
848
- throw new SimpleError({
849
- code: 'invalid_field',
850
- message: 'Missing from',
851
- human: $t(`%ww`),
852
- });
853
- }
854
-
855
- // Can we send from this e-mail or reply-to?
856
- if (upToDate.fromAddress && await canSendFromEmail(upToDate.fromAddress, organization ?? null)) {
857
- from = upToDate.getFromAddress();
858
- replyTo = null;
859
- }
860
-
861
- abort.throwIfAborted();
862
-
863
- if (!singleRecipientId) {
864
- upToDate.status = EmailStatus.Sending;
865
- }
866
- upToDate.sentAt = upToDate.sentAt ?? new Date();
867
- await upToDate.save();
868
-
869
- // Create recipients if not yet created
870
- await upToDate.buildRecipients();
871
- abort.throwIfAborted();
872
-
873
- // Refresh model
874
- const c = (await Email.getByID(id))!;
875
- if (!c) {
876
- throw new SimpleError({
877
- code: 'not_found',
878
- message: 'Email not found',
879
- human: $t(`%wz`),
880
- });
881
- }
882
- upToDate.copyFrom(c);
883
-
884
- if (upToDate.recipientsStatus !== EmailRecipientsStatus.Created) {
885
- throw new SimpleError({
886
- code: 'recipients_not_created',
887
- message: 'Failed to create recipients',
888
- human: $t(`%x0`),
889
- });
890
- }
891
-
892
- // Create a buffer of all attachments
893
- if (upToDate.sendAsEmail === true) {
894
- const attachments = await upToDate.loadAttachments();
895
-
896
- // Start actually sending in batches of recipients that are not yet sent
897
- let idPointer = '';
898
- const batchSize = 100;
899
- let isSavingStatus = false;
900
- let lastStatusSave = new Date();
901
-
902
- async function saveStatus() {
903
- if (singleRecipientId) {
904
- // Don't save during looping
905
- return;
906
- }
907
-
908
- if (!upToDate) {
909
- return;
910
- }
911
- if (isSavingStatus) {
912
- return;
913
- }
914
- if ((new Date().getTime() - lastStatusSave.getTime()) < 1000 * 5) {
915
- // Save at most every 5 seconds
916
- return;
917
- }
918
- if (succeededCount < upToDate.succeededCount || softFailedCount < upToDate.softFailedCount || failedCount < upToDate.failedCount) {
919
- // Do not update on retries
920
- return;
921
- }
922
-
923
- lastStatusSave = new Date();
924
- isSavingStatus = true;
925
- upToDate.succeededCount = succeededCount;
926
- upToDate.softFailedCount = softFailedCount;
927
- upToDate.failedCount = failedCount;
928
-
929
- try {
930
- await upToDate.save();
931
- } finally {
932
- isSavingStatus = false;
933
- }
934
- }
935
-
936
- while (true) {
937
- abort.throwIfAborted();
938
- const data = await SQL.select()
939
- .from('email_recipients')
940
- .where('emailId', upToDate.id)
941
- .where('id', SQLWhereSign.Greater, idPointer)
942
- .orderBy(SQL.column('id'), 'ASC')
943
- .limit(batchSize)
944
- .fetch();
945
-
946
- const recipients = EmailRecipient.fromRows(data, 'email_recipients');
947
-
948
- if (recipients.length === 0) {
949
- break;
950
- }
951
-
952
- const sendingPromises: Promise<void>[] = [];
953
- let skipped = 0;
954
-
955
- for (const recipient of recipients) {
956
- idPointer = recipient.id;
957
-
958
- if (recipient.sentAt) {
959
- succeededCount += 1;
960
- await saveStatus();
961
- skipped++;
962
- continue;
963
- }
964
-
965
- if (!recipient.email) {
966
- skipped++;
967
- continue;
968
- }
969
-
970
- if (recipient.duplicateOfRecipientId) {
971
- skipped++;
972
- continue;
973
- }
974
-
975
- if (singleRecipientId) {
976
- if (recipient.id !== singleRecipientId) {
977
- // Failed or soft-failed
978
- if (recipient.failError && isSoftEmailRecipientError(recipient.failError)) {
979
- softFailedCount += 1;
980
- } else {
981
- failedCount += 1;
982
- }
983
- skipped++;
984
- await saveStatus();
985
- continue;
986
- }
987
- }
988
-
989
- const promise = upToDate.sendSingleRecipient(recipient, organization ?? null, {
990
- from,
991
- replyTo,
992
- attachments,
993
- });
994
- sendingPromises.push(promise.then(async () => {
995
- if (recipient.sentAt) {
996
- succeededCount += 1;
997
- await saveStatus();
998
- } else {
999
- // Failed or soft-failed
1000
- if (recipient.failError && isSoftEmailRecipientError(recipient.failError)) {
1001
- softFailedCount += 1;
1002
- } else {
1003
- failedCount += 1;
1004
- }
1005
- await saveStatus();
1006
- }
1007
- }));
1008
- }
1009
-
1010
- if (sendingPromises.length > 0 || skipped > 0) {
1011
- await Promise.all(sendingPromises);
1012
- } else {
1013
- break;
1014
- }
1015
- }
1016
- }
1017
- } catch (e) {
1018
- if (!upToDate) {
1019
- throw e;
1020
- }
1021
-
1022
- if (!singleRecipientId) {
1023
- upToDate.succeededCount = succeededCount;
1024
- upToDate.softFailedCount = softFailedCount;
1025
- upToDate.failedCount = failedCount;
1026
-
1027
- if (isAbortedError(e) || ((isSimpleError(e) || isSimpleErrors(e)) && e.hasCode('SHUTDOWN'))) {
1028
- // Keep sending status: we'll resume after the reboot
1029
- await upToDate.save();
1030
- throw e;
1031
- }
1032
-
1033
- upToDate.emailErrors = errorToSimpleErrors(e);
1034
- upToDate.status = EmailStatus.Failed;
1035
- await upToDate.save();
1036
- }
1037
- throw e;
1038
- }
1039
-
1040
- if (!singleRecipientId) {
1041
- if (upToDate.sendAsEmail && upToDate.emailRecipientsCount === 0 && upToDate.userId === null) {
1042
- // We only delete automated emails (email type) if they have no recipients
1043
- console.log('No recipients found for email ', upToDate.id, ' deleting...');
1044
- await upToDate.delete();
1045
- return null;
1046
- }
1047
-
1048
- console.log('Finished sending email', upToDate.id);
1049
- // Mark email as sent
1050
-
1051
- if (upToDate.sendAsEmail && !upToDate.showInMemberPortal && (succeededCount + failedCount + softFailedCount) === 0) {
1052
- upToDate.status = EmailStatus.Failed;
1053
- upToDate.emailErrors = new SimpleErrors(
1054
- new SimpleError({
1055
- code: 'no_recipients',
1056
- message: 'No recipients',
1057
- human: $t(`%1EG`),
1058
- }),
1059
- );
1060
- } else {
1061
- upToDate.status = EmailStatus.Sent;
1062
- upToDate.emailErrors = null;
1063
- }
1064
- }
1065
-
1066
- upToDate.succeededCount = succeededCount;
1067
- upToDate.softFailedCount = softFailedCount;
1068
- upToDate.failedCount = failedCount;
1069
-
1070
- await upToDate.save();
1071
- return upToDate;
1072
- });
1073
- });
1074
- }
1075
-
1076
617
  async updateCount() {
1077
618
  // First reset
1078
619
  const id = this.id;
@@ -1175,256 +716,6 @@ export class Email extends QueryableModel {
1175
716
  return this.language ? [this.language, ...this.translations.keys()] : null;
1176
717
  }
1177
718
 
1178
- async buildRecipients() {
1179
- const id = this.id;
1180
- await QueueHandler.schedule('email-build-recipients-' + this.id, async function ({ abort }) {
1181
- const upToDate = await Email.getByID(id);
1182
-
1183
- if (!upToDate || !upToDate.id) {
1184
- return;
1185
- }
1186
-
1187
- if (upToDate.recipientsStatus === EmailRecipientsStatus.Created) {
1188
- return;
1189
- }
1190
-
1191
- if (upToDate.status === EmailStatus.Sent) {
1192
- return;
1193
- }
1194
-
1195
- abort.throwIfAborted();
1196
- const organization = upToDate.organizationId ? (await Organization.getByID(upToDate.organizationId) ?? null) : null;
1197
- if (upToDate.organizationId && !organization) {
1198
- throw new SimpleError({
1199
- code: 'organization_not_found',
1200
- message: 'Organization not found',
1201
- human: $t(`%1NV`),
1202
- });
1203
- }
1204
- const platform = await Platform.getSharedPrivateStruct();
1205
-
1206
- console.log('Building recipients for email', id);
1207
-
1208
- // If it is already creating -> something went wrong (e.g. server restart) and we can safely try again
1209
-
1210
- upToDate.recipientsStatus = EmailRecipientsStatus.Creating;
1211
- await upToDate.save();
1212
-
1213
- const membersSet = new Set<string>();
1214
- const emailsSet = new Set<string>();
1215
- const combinedHtml = upToDate.getCombinedHtml();
1216
-
1217
- let count = 0;
1218
- let countWithoutEmail = 0;
1219
-
1220
- try {
1221
- // Delete all recipients
1222
- await SQL
1223
- .delete()
1224
- .from(
1225
- SQL.table('email_recipients'),
1226
- )
1227
- .where(SQL.column('emailId'), upToDate.id);
1228
-
1229
- abort.throwIfAborted();
1230
-
1231
- for (const subfilter of upToDate.recipientFilter.filters) {
1232
- // Create recipients
1233
- const loader = Email.recipientLoaders.get(subfilter.type);
1234
-
1235
- if (!loader) {
1236
- throw new Error('Loader for type ' + subfilter.type + ' has not been initialised on the Email model');
1237
- }
1238
-
1239
- let request: LimitedFilteredRequest | null = new LimitedFilteredRequest({
1240
- filter: subfilter.filter,
1241
- sort: [{ key: 'id', order: SortItemDirection.ASC }],
1242
- limit: 100,
1243
- search: subfilter.search,
1244
- });
1245
-
1246
- const beforeFetchAllResult = loader.beforeFetchAll ? await loader.beforeFetchAll(request, subfilter.subfilter) : undefined;
1247
-
1248
- while (request) {
1249
- abort.throwIfAborted();
1250
- const response = await loader.fetch(request, subfilter.subfilter, beforeFetchAllResult, { allowedLanguages: upToDate.getLanguages() });
1251
-
1252
- for (const item of response.results) {
1253
- if (!item.email && !item.memberId && !item.userId) {
1254
- continue;
1255
- }
1256
-
1257
- const recipient = new EmailRecipient();
1258
- recipient.emailType = upToDate.emailType;
1259
- recipient.objectId = item.objectId;
1260
- recipient.emailId = upToDate.id;
1261
- recipient.email = item.email;
1262
- recipient.firstName = item.firstName;
1263
- recipient.lastName = item.lastName;
1264
- recipient.language = item.language ?? null;
1265
- recipient.replacements = item.replacements;
1266
- recipient.memberId = item.memberId ?? null;
1267
- recipient.userId = item.userId ?? null;
1268
- recipient.organizationId = upToDate.organizationId ?? null;
1269
-
1270
- await fillRecipientReplacements(recipient, {
1271
- platform,
1272
- organization,
1273
- from: upToDate.getFromAddress(),
1274
- replyTo: null,
1275
- forPreview: false,
1276
- allowedLanguages: upToDate.getLanguages(),
1277
- });
1278
- recipient.replacements = removeUnusedReplacements(combinedHtml, recipient.replacements);
1279
-
1280
- let duplicateOfRecipientId: string | null = null;
1281
- if (item.email && emailsSet.has(item.email)) {
1282
- console.log('Found duplicate email recipient', item.email);
1283
-
1284
- // Try to merge
1285
- const existing = await EmailRecipient.select()
1286
- .where('emailId', upToDate.id)
1287
- .where('email', item.email)
1288
- .where('duplicateOfRecipientId', null)
1289
- .fetch();
1290
-
1291
- for (const other of existing) {
1292
- const merged = mergeReplacementsIfEqual(other.replacements, recipient.replacements);
1293
- if (merged !== false) {
1294
- console.log('Found mergeable duplicate email recipient', item.email, other.id);
1295
- duplicateOfRecipientId = other.id;
1296
-
1297
- other.replacements = merged;
1298
- other.firstName = other.firstName || item.firstName;
1299
- other.lastName = other.lastName || item.lastName;
1300
- await other.save();
1301
-
1302
- recipient.replacements = merged;
1303
-
1304
- break;
1305
- } else {
1306
- console.log('Could not merge duplicate email recipient', item.email, other.id, 'keeping both', other.replacements, item.replacements);
1307
- }
1308
- }
1309
- }
1310
- recipient.duplicateOfRecipientId = duplicateOfRecipientId;
1311
-
1312
- await recipient.save();
1313
-
1314
- if (recipient.memberId) {
1315
- membersSet.add(recipient.memberId);
1316
- }
1317
-
1318
- if (recipient.email) {
1319
- emailsSet.add(recipient.email);
1320
- }
1321
-
1322
- if (!recipient.email || duplicateOfRecipientId) {
1323
- countWithoutEmail += 1;
1324
- } else {
1325
- count += 1;
1326
- }
1327
- }
1328
-
1329
- request = response.next ?? null;
1330
- }
1331
- }
1332
-
1333
- upToDate.recipientsStatus = EmailRecipientsStatus.Created;
1334
- upToDate.emailRecipientsCount = count;
1335
- upToDate.otherRecipientsCount = countWithoutEmail;
1336
- upToDate.recipientsErrors = null;
1337
- upToDate.membersCount = membersSet.size;
1338
- await upToDate.save();
1339
- } catch (e: unknown) {
1340
- console.error('Failed to build recipients for email', id);
1341
- console.error(e);
1342
- upToDate.recipientsStatus = EmailRecipientsStatus.NotCreated;
1343
- upToDate.recipientsErrors = errorToSimpleErrors(e);
1344
- await upToDate.save();
1345
- }
1346
- });
1347
- }
1348
-
1349
- async buildExampleRecipient(isNewlyCreated = false) {
1350
- const id = this.id;
1351
- await QueueHandler.schedule('email-build-recipients-' + this.id, async function () {
1352
- const upToDate = await Email.getByID(id);
1353
-
1354
- if (!upToDate || upToDate.sentAt || !upToDate.id) {
1355
- return;
1356
- }
1357
-
1358
- if (upToDate.recipientsStatus !== EmailRecipientsStatus.NotCreated) {
1359
- return;
1360
- }
1361
-
1362
- try {
1363
- // Delete all recipients
1364
- if (!isNewlyCreated) {
1365
- await SQL
1366
- .delete()
1367
- .from(
1368
- SQL.table('email_recipients'),
1369
- )
1370
- .where(SQL.column('emailId'), upToDate.id);
1371
- }
1372
-
1373
- for (const subfilter of upToDate.recipientFilter.filters) {
1374
- // Create recipients
1375
- const loader = Email.recipientLoaders.get(subfilter.type);
1376
-
1377
- if (!loader) {
1378
- throw new Error('Loader for type ' + subfilter.type + ' has not been initialised on the Email model');
1379
- }
1380
-
1381
- let request: LimitedFilteredRequest | null = new LimitedFilteredRequest({
1382
- filter: subfilter.filter,
1383
- sort: [{ key: 'id', order: SortItemDirection.ASC }],
1384
- limit: 10,
1385
- search: subfilter.search,
1386
- });
1387
-
1388
- const beforeFetchAllResult = loader.beforeFetchAll ? await loader.beforeFetchAll(request, subfilter.subfilter) : undefined;
1389
-
1390
- while (request) {
1391
- const response = await loader.fetch(request, subfilter.subfilter, beforeFetchAllResult, { allowedLanguages: upToDate.getLanguages() });
1392
-
1393
- // Note: it is possible that a result in the database doesn't return a recipient (in memory filtering)
1394
- // so we do need pagination
1395
-
1396
- for (const item of response.results) {
1397
- const recipient = new EmailRecipient();
1398
- recipient.emailType = upToDate.emailType;
1399
- recipient.emailId = upToDate.id;
1400
- recipient.objectId = item.objectId;
1401
- recipient.email = item.email;
1402
- recipient.firstName = item.firstName;
1403
- recipient.lastName = item.lastName;
1404
- recipient.language = item.language ?? null;
1405
- recipient.replacements = item.replacements;
1406
- recipient.memberId = item.memberId ?? null;
1407
- recipient.userId = item.userId ?? null;
1408
- recipient.organizationId = upToDate.organizationId ?? null;
1409
- await recipient.save();
1410
-
1411
- if (recipient.email || recipient.userId) {
1412
- return;
1413
- }
1414
- }
1415
-
1416
- request = null;
1417
- }
1418
- }
1419
-
1420
- console.warn('No example recipient found for email', id);
1421
- } catch (e) {
1422
- console.error('Failed to build example recipient for email', id);
1423
- console.error(e);
1424
- }
1425
- });
1426
- }
1427
-
1428
719
  getStructure() {
1429
720
  return EmailStruct.create(this);
1430
721
  }