@stamhoofd/models 2.137.4 → 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 (157) 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/Document.d.ts +0 -4
  34. package/dist/models/Document.d.ts.map +1 -1
  35. package/dist/models/Document.js +1 -75
  36. package/dist/models/Document.js.map +1 -1
  37. package/dist/models/DocumentTemplate.d.ts +0 -3
  38. package/dist/models/DocumentTemplate.d.ts.map +1 -1
  39. package/dist/models/DocumentTemplate.js +1 -63
  40. package/dist/models/DocumentTemplate.js.map +1 -1
  41. package/dist/models/Email.d.ts +1 -29
  42. package/dist/models/Email.d.ts.map +1 -1
  43. package/dist/models/Email.js +4 -823
  44. package/dist/models/Email.js.map +1 -1
  45. package/dist/models/EmailVerificationCode.d.ts +0 -5
  46. package/dist/models/EmailVerificationCode.d.ts.map +1 -1
  47. package/dist/models/EmailVerificationCode.js +0 -84
  48. package/dist/models/EmailVerificationCode.js.map +1 -1
  49. package/dist/models/Image.d.ts.map +1 -1
  50. package/dist/models/Image.js +11 -14
  51. package/dist/models/Image.js.map +1 -1
  52. package/dist/models/MFARecoveryCode.d.ts +17 -0
  53. package/dist/models/MFARecoveryCode.d.ts.map +1 -0
  54. package/dist/models/MFARecoveryCode.js +55 -0
  55. package/dist/models/MFARecoveryCode.js.map +1 -0
  56. package/dist/models/MFATOTP.d.ts +44 -0
  57. package/dist/models/MFATOTP.d.ts.map +1 -0
  58. package/dist/models/MFATOTP.js +116 -0
  59. package/dist/models/MFATOTP.js.map +1 -0
  60. package/dist/models/MFAToken.d.ts +49 -0
  61. package/dist/models/MFAToken.d.ts.map +1 -0
  62. package/dist/models/MFAToken.js +137 -0
  63. package/dist/models/MFAToken.js.map +1 -0
  64. package/dist/models/MemberPlatformMembership.d.ts +0 -8
  65. package/dist/models/MemberPlatformMembership.d.ts.map +1 -1
  66. package/dist/models/MemberPlatformMembership.js +1 -242
  67. package/dist/models/MemberPlatformMembership.js.map +1 -1
  68. package/dist/models/Order.d.ts +1 -32
  69. package/dist/models/Order.d.ts.map +1 -1
  70. package/dist/models/Order.js +1 -182
  71. package/dist/models/Order.js.map +1 -1
  72. package/dist/models/Organization.d.ts +1 -51
  73. package/dist/models/Organization.d.ts.map +1 -1
  74. package/dist/models/Organization.js +1 -530
  75. package/dist/models/Organization.js.map +1 -1
  76. package/dist/models/PasswordToken.d.ts +0 -8
  77. package/dist/models/PasswordToken.d.ts.map +1 -1
  78. package/dist/models/PasswordToken.js +0 -23
  79. package/dist/models/PasswordToken.js.map +1 -1
  80. package/dist/models/Platform.d.ts +28 -4
  81. package/dist/models/Platform.d.ts.map +1 -1
  82. package/dist/models/Platform.js +111 -50
  83. package/dist/models/Platform.js.map +1 -1
  84. package/dist/models/STPackage.d.ts +1 -6
  85. package/dist/models/STPackage.d.ts.map +1 -1
  86. package/dist/models/STPackage.js +1 -98
  87. package/dist/models/STPackage.js.map +1 -1
  88. package/dist/models/Token.d.ts +40 -1
  89. package/dist/models/Token.d.ts.map +1 -1
  90. package/dist/models/Token.js +68 -2
  91. package/dist/models/Token.js.map +1 -1
  92. package/dist/models/User.d.ts +25 -0
  93. package/dist/models/User.d.ts.map +1 -1
  94. package/dist/models/User.js +36 -0
  95. package/dist/models/User.js.map +1 -1
  96. package/dist/models/WebauthnChallenge.d.ts +27 -0
  97. package/dist/models/WebauthnChallenge.d.ts.map +1 -0
  98. package/dist/models/WebauthnChallenge.js +81 -0
  99. package/dist/models/WebauthnChallenge.js.map +1 -0
  100. package/dist/models/WebauthnCredential.d.ts +58 -0
  101. package/dist/models/WebauthnCredential.d.ts.map +1 -0
  102. package/dist/models/WebauthnCredential.js +144 -0
  103. package/dist/models/WebauthnCredential.js.map +1 -0
  104. package/dist/models/index.d.ts +5 -0
  105. package/dist/models/index.d.ts.map +1 -1
  106. package/dist/models/index.js +5 -0
  107. package/dist/models/index.js.map +1 -1
  108. package/package.json +3 -3
  109. package/src/helpers/Handlebars.ts +5 -9
  110. package/src/helpers/errorToSimpleErrors.ts +17 -0
  111. package/src/index.ts +0 -1
  112. package/src/migrations/1782902314-tokens-authenticated-at.sql +2 -0
  113. package/src/migrations/1782902315-create-mfa-totp-table.sql +13 -0
  114. package/src/migrations/1782902316-create-webauthn-credentials-table.sql +17 -0
  115. package/src/migrations/1782902317-create-mfa-recovery-codes-table.sql +10 -0
  116. package/src/migrations/1782902318-create-mfa-tokens-table.sql +13 -0
  117. package/src/migrations/1782902319-create-webauthn-challenges-table.sql +10 -0
  118. package/src/migrations/1784039947-mfa-totp-last-used-counter.sql +2 -0
  119. package/src/migrations/1784122354-webauthn-credential-provider.sql +3 -0
  120. package/src/migrations/1784500000-webauthn-credential-rp-id.sql +9 -0
  121. package/src/migrations/1785354091-platform-parent-tenant-id.sql +1 -0
  122. package/src/migrations/1785354092-platform-fees-tenant-id.sql +1 -0
  123. package/src/migrations/1785354093-platform-uri.sql +1 -0
  124. package/src/migrations/1785354094-platform-domain.sql +1 -0
  125. package/src/migrations/1785354095-platform-uri-unique.sql +1 -0
  126. package/src/migrations/1785354096-platform-domain-unique.sql +1 -0
  127. package/src/migrations/1785354097-platform-parent-tenant-id-index.sql +1 -0
  128. package/src/migrations/1785354098-platform-tenant-backfill.ts +14 -0
  129. package/src/migrations/1785417301-users-last-active-at.sql +2 -0
  130. package/src/models/Document.ts +1 -84
  131. package/src/models/DocumentTemplate.ts +1 -71
  132. package/src/models/Email.ts +5 -941
  133. package/src/models/EmailVerificationCode.ts +0 -96
  134. package/src/models/Image.ts +11 -14
  135. package/src/models/MFARecoveryCode.ts +52 -0
  136. package/src/models/MFATOTP.ts +112 -0
  137. package/src/models/MFAToken.ts +138 -0
  138. package/src/models/MemberPlatformMembership.ts +1 -285
  139. package/src/models/Order.ts +1 -204
  140. package/src/models/Organization.ts +2 -637
  141. package/src/models/PasswordToken.ts +0 -29
  142. package/src/models/Platform.test.ts +167 -3
  143. package/src/models/Platform.ts +125 -50
  144. package/src/models/STPackage.ts +1 -110
  145. package/src/models/Token.ts +73 -2
  146. package/src/models/User.ts +37 -0
  147. package/src/models/WebauthnChallenge.ts +80 -0
  148. package/src/models/WebauthnCredential.ts +130 -0
  149. package/src/models/index.ts +6 -0
  150. package/dist/helpers/EmailBuilder.d.ts +0 -121
  151. package/dist/helpers/EmailBuilder.d.ts.map +0 -1
  152. package/dist/helpers/EmailBuilder.js +0 -659
  153. package/dist/helpers/EmailBuilder.js.map +0 -1
  154. package/src/helpers/EmailBuilder.test.ts +0 -291
  155. package/src/helpers/EmailBuilder.ts +0 -818
  156. package/src/models/Email.test.ts +0 -1222
  157. package/src/models/MemberPlatformMembership.test.ts +0 -70
@@ -1,44 +1,22 @@
1
1
  import { column } from '@simonbackx/simple-database';
2
- import type { BaseOrganization, EmailRecipient as EmailRecipientStruct, EmailTemplateType, PaginatedResponse, Replacement, StamhoofdFilter, User as UserStruct } from '@stamhoofd/structures';
3
- import { EmailAttachment, EmailContent, EmailPreview, EmailRecipientFilter, EmailRecipientsStatus, EmailStatus, Email as EmailStruct, EmailWithRecipients, getEmailContentForLanguage, getExampleRecipient, isSoftEmailRecipientError, LanguageHelper, LimitedFilteredRequest, SortItemDirection } from '@stamhoofd/structures';
4
- import { ExampleReplacements } from '@stamhoofd/structures/email/exampleReplacements.js';
2
+ import type { EmailRecipient as EmailRecipientStruct, EmailTemplateType, PaginatedResponse, StamhoofdFilter } from '@stamhoofd/structures';
3
+ import { EmailAttachment, EmailContent, EmailRecipientFilter, EmailRecipientsStatus, EmailStatus, Email as EmailStruct, LanguageHelper, LimitedFilteredRequest, SortItemDirection } from '@stamhoofd/structures';
5
4
  import type { Country } from '@stamhoofd/types/Country';
6
5
  import { Language } from '@stamhoofd/types/Language';
7
6
  import { v4 as uuidv4 } from 'uuid';
8
7
  import type { EmailRecipientFilterType } from '@stamhoofd/structures/email/EmailRecipientFilterType.js';
9
8
  import type { Decoder } from '@simonbackx/simple-encoding';
10
9
  import { AnyDecoder, ArrayDecoder, EnumDecoder, MapDecoder } from '@simonbackx/simple-encoding';
11
- import { isSimpleError, isSimpleErrors, SimpleError, SimpleErrors } from '@simonbackx/simple-errors';
10
+ import { SimpleError, SimpleErrors } from '@simonbackx/simple-errors';
12
11
  import { I18n } from '@stamhoofd/backend-i18n/I18n';
13
12
  import type { EmailInterfaceRecipient } from '@stamhoofd/email';
14
- import { Email as EmailClass } from '@stamhoofd/email';
15
13
  import type { QueueHandlerOptions } from '@stamhoofd/queues';
16
14
  import { isAbortedError, QueueHandler } from '@stamhoofd/queues';
17
- import { QueryableModel, readDynamicSQLExpression, SQL, SQLAlias, SQLCount, SQLSelectAs, SQLWhereSign } from '@stamhoofd/sql';
18
- import { canSendFromEmail, fillRecipientReplacements, getEmailBuilder, mergeReplacementsIfEqual, removeUnusedReplacements, runWithRecipientLocale, stripRecipientReplacementsForWebDisplay, stripSensitiveRecipientReplacements } from '../helpers/EmailBuilder.js';
15
+ import { QueryableModel, readDynamicSQLExpression, SQL, SQLAlias, SQLCount, SQLSelectAs } from '@stamhoofd/sql';
16
+ import { errorToSimpleErrors } from '../helpers/errorToSimpleErrors.js';
19
17
  import { EmailRecipient } from './EmailRecipient.js';
20
18
  import { EmailTemplate } from './EmailTemplate.js';
21
19
  import { Organization } from './Organization.js';
22
- import { Platform } from './Platform.js';
23
- import { User } from './User.js';
24
-
25
- type Attachment = { filename: string; path?: string; href?: string; content?: string | Buffer; contentType?: string; encoding?: string };
26
-
27
- function errorToSimpleErrors(e: unknown) {
28
- if (isSimpleErrors(e)) {
29
- return e;
30
- } else if (isSimpleError(e)) {
31
- return new SimpleErrors(e);
32
- } else {
33
- return new SimpleErrors(
34
- new SimpleError({
35
- code: 'unknown_error',
36
- message: ((typeof e === 'object' && e !== null && 'message' in e && typeof e.message === 'string') ? e.message : 'Unknown error'),
37
- human: $t(`%1ED`),
38
- }),
39
- );
40
- }
41
- }
42
20
 
43
21
  export type RecipientLoader<BeforeFetchAllResult = any> = {
44
22
  /**
@@ -636,445 +614,6 @@ export class Email extends QueryableModel {
636
614
  });
637
615
  }
638
616
 
639
- async queueForSending(waitForSending = false) {
640
- console.log('Queueing email for sending', this.id);
641
- this.throwIfNotReadyToSend();
642
- this.throwIfNoUnsubscribeButton();
643
- await this.lock(async (upToDate) => {
644
- if (upToDate.status === EmailStatus.Draft) {
645
- upToDate.status = EmailStatus.Queued;
646
- }
647
- if (upToDate.status === EmailStatus.Failed) {
648
- // Retry failed email
649
- upToDate.status = EmailStatus.Queued;
650
- }
651
- await upToDate.save();
652
- });
653
- if (waitForSending) {
654
- return await this.resumeSending();
655
- } else {
656
- this.resumeSending().catch(console.error);
657
- }
658
- return this;
659
- }
660
-
661
- private async loadAttachments(): Promise<Attachment[]> {
662
- const attachments: Attachment[] = [];
663
- for (const attachment of this.attachments) {
664
- if (!attachment.content && !attachment.file) {
665
- console.warn('Attachment without content found, skipping', attachment);
666
- continue;
667
- }
668
-
669
- let filename = $t('%180');
670
-
671
- if (attachment.contentType === 'application/pdf') {
672
- // tmp solution for pdf only
673
- filename += '.pdf';
674
- }
675
-
676
- if (attachment.file?.name) {
677
- filename = attachment.file.name.toLowerCase().replace(/[^a-z0-9.]+/g, '-').replace(/^-+/, '').replace(/-+$/, '');
678
- }
679
-
680
- // Correct file name if needed
681
- if (attachment.filename) {
682
- filename = attachment.filename.toLowerCase().replace(/[^a-z0-9.]+/g, '-').replace(/^-+/, '').replace(/-+$/, '');
683
- }
684
-
685
- if (attachment.content) {
686
- attachments.push({
687
- filename: filename,
688
- content: attachment.content,
689
- contentType: attachment.contentType ?? undefined,
690
- encoding: 'base64',
691
- });
692
- } else {
693
- // 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
694
- const withSigned = await attachment.file!.withSignedUrl();
695
- if (!withSigned || !withSigned.signedUrl) {
696
- throw new SimpleError({
697
- code: 'attachment_not_found',
698
- message: 'Attachment not found',
699
- human: $t(`%181`),
700
- });
701
- }
702
-
703
- const filePath = withSigned.signedUrl;
704
- let fileBuffer: Buffer | null;
705
- try {
706
- const response = await fetch(filePath);
707
- fileBuffer = Buffer.from(await response.arrayBuffer());
708
- } catch (e) {
709
- throw new SimpleError({
710
- code: 'attachment_not_found',
711
- message: 'Attachment not found',
712
- human: $t(`%181`),
713
- });
714
- }
715
-
716
- attachments.push({
717
- filename: filename,
718
- contentType: attachment.contentType ?? undefined,
719
- content: fileBuffer,
720
- });
721
- }
722
- }
723
- return attachments;
724
- }
725
-
726
- private async sendSingleRecipient(recipient: EmailRecipient, organization: Organization | null, data: { from: EmailInterfaceRecipient; replyTo: EmailInterfaceRecipient | null; attachments: Attachment[] }) {
727
- let promiseResolve: (value: void | PromiseLike<void>) => void;
728
- const promise = new Promise<void>((resolve) => {
729
- promiseResolve = resolve;
730
- });
731
-
732
- const virtualRecipient = recipient.getRecipient();
733
-
734
- let resolved = false;
735
- const callback = async (error: Error | null) => {
736
- if (resolved) {
737
- return;
738
- }
739
- resolved = true;
740
-
741
- try {
742
- if (error === null) {
743
- // Mark saved
744
- recipient.sentAt = new Date();
745
- recipient.failErrorMessage = null;
746
-
747
- if (recipient.failError) {
748
- recipient.previousFailError = recipient.failError;
749
- }
750
- recipient.failError = null;
751
-
752
- // Update repacements that have been generated
753
- recipient.replacements = virtualRecipient.replacements;
754
- await recipient.save();
755
- } else {
756
- recipient.failCount += 1;
757
- recipient.failErrorMessage = error.message;
758
- if (recipient.failError) {
759
- recipient.previousFailError = recipient.failError;
760
- }
761
- recipient.failError = errorToSimpleErrors(error);
762
- recipient.firstFailedAt = recipient.firstFailedAt ?? new Date();
763
- recipient.lastFailedAt = new Date();
764
- await recipient.save();
765
- }
766
- } catch (e) {
767
- console.error(e);
768
- }
769
- promiseResolve();
770
- };
771
-
772
- // Do send the email
773
- // Create e-mail builder
774
- const builder = await getEmailBuilder(organization ?? null, {
775
- recipients: [
776
- virtualRecipient,
777
- ],
778
- from: data.from,
779
- replyTo: data.replyTo,
780
- subject: this.subject!,
781
- html: this.html!,
782
- translations: this.translations,
783
- type: this.emailType ? 'transactional' : 'broadcast',
784
- attachments: data.attachments,
785
- callback(error: Error | null) {
786
- callback(error).catch(console.error);
787
- },
788
- headers: {
789
- 'X-Email-Id': this.id,
790
- 'X-Email-Recipient-Id': recipient.id,
791
- },
792
- });
793
- EmailClass.schedule(builder);
794
- return await promise;
795
- }
796
-
797
- async resumeSending(singleRecipientId: string | null = null): Promise<Email | null> {
798
- const id = this.id;
799
- return await QueueHandler.schedule('send-email', async ({ abort }) => {
800
- return await this.lock(async function (upToDate: Email) {
801
- if (upToDate.status === EmailStatus.Sent) {
802
- // Already done
803
- // In other cases -> queue has stopped and we can retry
804
- if (!singleRecipientId) {
805
- console.log('Email already sent, skipping...', upToDate.id);
806
- return upToDate;
807
- }
808
- } else {
809
- if (singleRecipientId) {
810
- // Not possible
811
- throw new SimpleError({
812
- code: 'invalid_state',
813
- message: 'Cannot retry single recipient for email that is not yet sent',
814
- });
815
- }
816
-
817
- if (upToDate.status === EmailStatus.Sending) {
818
- // This is an automatic retry.
819
- if (upToDate.emailType) {
820
- // Not eligible for retry
821
- upToDate.status = EmailStatus.Failed;
822
- await upToDate.save();
823
- return upToDate;
824
- }
825
- if (upToDate.createdAt < new Date(new Date().getTime() - 1000 * 60 * 60 * 24 * 2)) {
826
- // Too long
827
- console.error('Email has been sending for too long. Marking as failed...', upToDate.id);
828
- upToDate.status = EmailStatus.Failed;
829
- await upToDate.save();
830
- return upToDate;
831
- }
832
- } else if (upToDate.status !== EmailStatus.Queued) {
833
- console.error('Email is not queued or sending, cannot send', upToDate.id, upToDate.status);
834
- return upToDate;
835
- }
836
- }
837
-
838
- const organization = upToDate.organizationId ? await Organization.getByID(upToDate.organizationId) : null;
839
- let from = upToDate.getDefaultFromAddress(organization);
840
- let replyTo: EmailInterfaceRecipient | null = upToDate.getFromAddress();
841
- let succeededCount = 0;
842
- let softFailedCount = 0;
843
- let failedCount = 0;
844
-
845
- try {
846
- upToDate.throwIfNotReadyToSend();
847
- upToDate.throwIfNoUnsubscribeButton();
848
-
849
- if (!from) {
850
- throw new SimpleError({
851
- code: 'invalid_field',
852
- message: 'Missing from',
853
- human: $t(`%ww`),
854
- });
855
- }
856
-
857
- // Can we send from this e-mail or reply-to?
858
- if (upToDate.fromAddress && await canSendFromEmail(upToDate.fromAddress, organization ?? null)) {
859
- from = upToDate.getFromAddress();
860
- replyTo = null;
861
- }
862
-
863
- abort.throwIfAborted();
864
-
865
- if (!singleRecipientId) {
866
- upToDate.status = EmailStatus.Sending;
867
- }
868
- upToDate.sentAt = upToDate.sentAt ?? new Date();
869
- await upToDate.save();
870
-
871
- // Create recipients if not yet created
872
- await upToDate.buildRecipients();
873
- abort.throwIfAborted();
874
-
875
- // Refresh model
876
- const c = (await Email.getByID(id))!;
877
- if (!c) {
878
- throw new SimpleError({
879
- code: 'not_found',
880
- message: 'Email not found',
881
- human: $t(`%wz`),
882
- });
883
- }
884
- upToDate.copyFrom(c);
885
-
886
- if (upToDate.recipientsStatus !== EmailRecipientsStatus.Created) {
887
- throw new SimpleError({
888
- code: 'recipients_not_created',
889
- message: 'Failed to create recipients',
890
- human: $t(`%x0`),
891
- });
892
- }
893
-
894
- // Create a buffer of all attachments
895
- if (upToDate.sendAsEmail === true) {
896
- const attachments = await upToDate.loadAttachments();
897
-
898
- // Start actually sending in batches of recipients that are not yet sent
899
- let idPointer = '';
900
- const batchSize = 100;
901
- let isSavingStatus = false;
902
- let lastStatusSave = new Date();
903
-
904
- async function saveStatus() {
905
- if (singleRecipientId) {
906
- // Don't save during looping
907
- return;
908
- }
909
-
910
- if (!upToDate) {
911
- return;
912
- }
913
- if (isSavingStatus) {
914
- return;
915
- }
916
- if ((new Date().getTime() - lastStatusSave.getTime()) < 1000 * 5) {
917
- // Save at most every 5 seconds
918
- return;
919
- }
920
- if (succeededCount < upToDate.succeededCount || softFailedCount < upToDate.softFailedCount || failedCount < upToDate.failedCount) {
921
- // Do not update on retries
922
- return;
923
- }
924
-
925
- lastStatusSave = new Date();
926
- isSavingStatus = true;
927
- upToDate.succeededCount = succeededCount;
928
- upToDate.softFailedCount = softFailedCount;
929
- upToDate.failedCount = failedCount;
930
-
931
- try {
932
- await upToDate.save();
933
- } finally {
934
- isSavingStatus = false;
935
- }
936
- }
937
-
938
- while (true) {
939
- abort.throwIfAborted();
940
- const data = await SQL.select()
941
- .from('email_recipients')
942
- .where('emailId', upToDate.id)
943
- .where('id', SQLWhereSign.Greater, idPointer)
944
- .orderBy(SQL.column('id'), 'ASC')
945
- .limit(batchSize)
946
- .fetch();
947
-
948
- const recipients = EmailRecipient.fromRows(data, 'email_recipients');
949
-
950
- if (recipients.length === 0) {
951
- break;
952
- }
953
-
954
- const sendingPromises: Promise<void>[] = [];
955
- let skipped = 0;
956
-
957
- for (const recipient of recipients) {
958
- idPointer = recipient.id;
959
-
960
- if (recipient.sentAt) {
961
- succeededCount += 1;
962
- await saveStatus();
963
- skipped++;
964
- continue;
965
- }
966
-
967
- if (!recipient.email) {
968
- skipped++;
969
- continue;
970
- }
971
-
972
- if (recipient.duplicateOfRecipientId) {
973
- skipped++;
974
- continue;
975
- }
976
-
977
- if (singleRecipientId) {
978
- if (recipient.id !== singleRecipientId) {
979
- // Failed or soft-failed
980
- if (recipient.failError && isSoftEmailRecipientError(recipient.failError)) {
981
- softFailedCount += 1;
982
- } else {
983
- failedCount += 1;
984
- }
985
- skipped++;
986
- await saveStatus();
987
- continue;
988
- }
989
- }
990
-
991
- const promise = upToDate.sendSingleRecipient(recipient, organization ?? null, {
992
- from,
993
- replyTo,
994
- attachments,
995
- });
996
- sendingPromises.push(promise.then(async () => {
997
- if (recipient.sentAt) {
998
- succeededCount += 1;
999
- await saveStatus();
1000
- } else {
1001
- // Failed or soft-failed
1002
- if (recipient.failError && isSoftEmailRecipientError(recipient.failError)) {
1003
- softFailedCount += 1;
1004
- } else {
1005
- failedCount += 1;
1006
- }
1007
- await saveStatus();
1008
- }
1009
- }));
1010
- }
1011
-
1012
- if (sendingPromises.length > 0 || skipped > 0) {
1013
- await Promise.all(sendingPromises);
1014
- } else {
1015
- break;
1016
- }
1017
- }
1018
- }
1019
- } catch (e) {
1020
- if (!upToDate) {
1021
- throw e;
1022
- }
1023
-
1024
- if (!singleRecipientId) {
1025
- upToDate.succeededCount = succeededCount;
1026
- upToDate.softFailedCount = softFailedCount;
1027
- upToDate.failedCount = failedCount;
1028
-
1029
- if (isAbortedError(e) || ((isSimpleError(e) || isSimpleErrors(e)) && e.hasCode('SHUTDOWN'))) {
1030
- // Keep sending status: we'll resume after the reboot
1031
- await upToDate.save();
1032
- throw e;
1033
- }
1034
-
1035
- upToDate.emailErrors = errorToSimpleErrors(e);
1036
- upToDate.status = EmailStatus.Failed;
1037
- await upToDate.save();
1038
- }
1039
- throw e;
1040
- }
1041
-
1042
- if (!singleRecipientId) {
1043
- if (upToDate.sendAsEmail && upToDate.emailRecipientsCount === 0 && upToDate.userId === null) {
1044
- // We only delete automated emails (email type) if they have no recipients
1045
- console.log('No recipients found for email ', upToDate.id, ' deleting...');
1046
- await upToDate.delete();
1047
- return null;
1048
- }
1049
-
1050
- console.log('Finished sending email', upToDate.id);
1051
- // Mark email as sent
1052
-
1053
- if (upToDate.sendAsEmail && !upToDate.showInMemberPortal && (succeededCount + failedCount + softFailedCount) === 0) {
1054
- upToDate.status = EmailStatus.Failed;
1055
- upToDate.emailErrors = new SimpleErrors(
1056
- new SimpleError({
1057
- code: 'no_recipients',
1058
- message: 'No recipients',
1059
- human: $t(`%1EG`),
1060
- }),
1061
- );
1062
- } else {
1063
- upToDate.status = EmailStatus.Sent;
1064
- upToDate.emailErrors = null;
1065
- }
1066
- }
1067
-
1068
- upToDate.succeededCount = succeededCount;
1069
- upToDate.softFailedCount = softFailedCount;
1070
- upToDate.failedCount = failedCount;
1071
-
1072
- await upToDate.save();
1073
- return upToDate;
1074
- });
1075
- });
1076
- }
1077
-
1078
617
  async updateCount() {
1079
618
  // First reset
1080
619
  const id = this.id;
@@ -1177,256 +716,6 @@ export class Email extends QueryableModel {
1177
716
  return this.language ? [this.language, ...this.translations.keys()] : null;
1178
717
  }
1179
718
 
1180
- async buildRecipients() {
1181
- const id = this.id;
1182
- await QueueHandler.schedule('email-build-recipients-' + this.id, async function ({ abort }) {
1183
- const upToDate = await Email.getByID(id);
1184
-
1185
- if (!upToDate || !upToDate.id) {
1186
- return;
1187
- }
1188
-
1189
- if (upToDate.recipientsStatus === EmailRecipientsStatus.Created) {
1190
- return;
1191
- }
1192
-
1193
- if (upToDate.status === EmailStatus.Sent) {
1194
- return;
1195
- }
1196
-
1197
- abort.throwIfAborted();
1198
- const organization = upToDate.organizationId ? (await Organization.getByID(upToDate.organizationId) ?? null) : null;
1199
- if (upToDate.organizationId && !organization) {
1200
- throw new SimpleError({
1201
- code: 'organization_not_found',
1202
- message: 'Organization not found',
1203
- human: $t(`%1NV`),
1204
- });
1205
- }
1206
- const platform = await Platform.getSharedPrivateStruct();
1207
-
1208
- console.log('Building recipients for email', id);
1209
-
1210
- // If it is already creating -> something went wrong (e.g. server restart) and we can safely try again
1211
-
1212
- upToDate.recipientsStatus = EmailRecipientsStatus.Creating;
1213
- await upToDate.save();
1214
-
1215
- const membersSet = new Set<string>();
1216
- const emailsSet = new Set<string>();
1217
- const combinedHtml = upToDate.getCombinedHtml();
1218
-
1219
- let count = 0;
1220
- let countWithoutEmail = 0;
1221
-
1222
- try {
1223
- // Delete all recipients
1224
- await SQL
1225
- .delete()
1226
- .from(
1227
- SQL.table('email_recipients'),
1228
- )
1229
- .where(SQL.column('emailId'), upToDate.id);
1230
-
1231
- abort.throwIfAborted();
1232
-
1233
- for (const subfilter of upToDate.recipientFilter.filters) {
1234
- // Create recipients
1235
- const loader = Email.recipientLoaders.get(subfilter.type);
1236
-
1237
- if (!loader) {
1238
- throw new Error('Loader for type ' + subfilter.type + ' has not been initialised on the Email model');
1239
- }
1240
-
1241
- let request: LimitedFilteredRequest | null = new LimitedFilteredRequest({
1242
- filter: subfilter.filter,
1243
- sort: [{ key: 'id', order: SortItemDirection.ASC }],
1244
- limit: 100,
1245
- search: subfilter.search,
1246
- });
1247
-
1248
- const beforeFetchAllResult = loader.beforeFetchAll ? await loader.beforeFetchAll(request, subfilter.subfilter) : undefined;
1249
-
1250
- while (request) {
1251
- abort.throwIfAborted();
1252
- const response = await loader.fetch(request, subfilter.subfilter, beforeFetchAllResult, { allowedLanguages: upToDate.getLanguages() });
1253
-
1254
- for (const item of response.results) {
1255
- if (!item.email && !item.memberId && !item.userId) {
1256
- continue;
1257
- }
1258
-
1259
- const recipient = new EmailRecipient();
1260
- recipient.emailType = upToDate.emailType;
1261
- recipient.objectId = item.objectId;
1262
- recipient.emailId = upToDate.id;
1263
- recipient.email = item.email;
1264
- recipient.firstName = item.firstName;
1265
- recipient.lastName = item.lastName;
1266
- recipient.language = item.language ?? null;
1267
- recipient.replacements = item.replacements;
1268
- recipient.memberId = item.memberId ?? null;
1269
- recipient.userId = item.userId ?? null;
1270
- recipient.organizationId = upToDate.organizationId ?? null;
1271
-
1272
- await fillRecipientReplacements(recipient, {
1273
- platform,
1274
- organization,
1275
- from: upToDate.getFromAddress(),
1276
- replyTo: null,
1277
- forPreview: false,
1278
- allowedLanguages: upToDate.getLanguages(),
1279
- });
1280
- recipient.replacements = removeUnusedReplacements(combinedHtml, recipient.replacements);
1281
-
1282
- let duplicateOfRecipientId: string | null = null;
1283
- if (item.email && emailsSet.has(item.email)) {
1284
- console.log('Found duplicate email recipient', item.email);
1285
-
1286
- // Try to merge
1287
- const existing = await EmailRecipient.select()
1288
- .where('emailId', upToDate.id)
1289
- .where('email', item.email)
1290
- .where('duplicateOfRecipientId', null)
1291
- .fetch();
1292
-
1293
- for (const other of existing) {
1294
- const merged = mergeReplacementsIfEqual(other.replacements, recipient.replacements);
1295
- if (merged !== false) {
1296
- console.log('Found mergeable duplicate email recipient', item.email, other.id);
1297
- duplicateOfRecipientId = other.id;
1298
-
1299
- other.replacements = merged;
1300
- other.firstName = other.firstName || item.firstName;
1301
- other.lastName = other.lastName || item.lastName;
1302
- await other.save();
1303
-
1304
- recipient.replacements = merged;
1305
-
1306
- break;
1307
- } else {
1308
- console.log('Could not merge duplicate email recipient', item.email, other.id, 'keeping both', other.replacements, item.replacements);
1309
- }
1310
- }
1311
- }
1312
- recipient.duplicateOfRecipientId = duplicateOfRecipientId;
1313
-
1314
- await recipient.save();
1315
-
1316
- if (recipient.memberId) {
1317
- membersSet.add(recipient.memberId);
1318
- }
1319
-
1320
- if (recipient.email) {
1321
- emailsSet.add(recipient.email);
1322
- }
1323
-
1324
- if (!recipient.email || duplicateOfRecipientId) {
1325
- countWithoutEmail += 1;
1326
- } else {
1327
- count += 1;
1328
- }
1329
- }
1330
-
1331
- request = response.next ?? null;
1332
- }
1333
- }
1334
-
1335
- upToDate.recipientsStatus = EmailRecipientsStatus.Created;
1336
- upToDate.emailRecipientsCount = count;
1337
- upToDate.otherRecipientsCount = countWithoutEmail;
1338
- upToDate.recipientsErrors = null;
1339
- upToDate.membersCount = membersSet.size;
1340
- await upToDate.save();
1341
- } catch (e: unknown) {
1342
- console.error('Failed to build recipients for email', id);
1343
- console.error(e);
1344
- upToDate.recipientsStatus = EmailRecipientsStatus.NotCreated;
1345
- upToDate.recipientsErrors = errorToSimpleErrors(e);
1346
- await upToDate.save();
1347
- }
1348
- });
1349
- }
1350
-
1351
- async buildExampleRecipient(isNewlyCreated = false) {
1352
- const id = this.id;
1353
- await QueueHandler.schedule('email-build-recipients-' + this.id, async function () {
1354
- const upToDate = await Email.getByID(id);
1355
-
1356
- if (!upToDate || upToDate.sentAt || !upToDate.id) {
1357
- return;
1358
- }
1359
-
1360
- if (upToDate.recipientsStatus !== EmailRecipientsStatus.NotCreated) {
1361
- return;
1362
- }
1363
-
1364
- try {
1365
- // Delete all recipients
1366
- if (!isNewlyCreated) {
1367
- await SQL
1368
- .delete()
1369
- .from(
1370
- SQL.table('email_recipients'),
1371
- )
1372
- .where(SQL.column('emailId'), upToDate.id);
1373
- }
1374
-
1375
- for (const subfilter of upToDate.recipientFilter.filters) {
1376
- // Create recipients
1377
- const loader = Email.recipientLoaders.get(subfilter.type);
1378
-
1379
- if (!loader) {
1380
- throw new Error('Loader for type ' + subfilter.type + ' has not been initialised on the Email model');
1381
- }
1382
-
1383
- let request: LimitedFilteredRequest | null = new LimitedFilteredRequest({
1384
- filter: subfilter.filter,
1385
- sort: [{ key: 'id', order: SortItemDirection.ASC }],
1386
- limit: 10,
1387
- search: subfilter.search,
1388
- });
1389
-
1390
- const beforeFetchAllResult = loader.beforeFetchAll ? await loader.beforeFetchAll(request, subfilter.subfilter) : undefined;
1391
-
1392
- while (request) {
1393
- const response = await loader.fetch(request, subfilter.subfilter, beforeFetchAllResult, { allowedLanguages: upToDate.getLanguages() });
1394
-
1395
- // Note: it is possible that a result in the database doesn't return a recipient (in memory filtering)
1396
- // so we do need pagination
1397
-
1398
- for (const item of response.results) {
1399
- const recipient = new EmailRecipient();
1400
- recipient.emailType = upToDate.emailType;
1401
- recipient.emailId = upToDate.id;
1402
- recipient.objectId = item.objectId;
1403
- recipient.email = item.email;
1404
- recipient.firstName = item.firstName;
1405
- recipient.lastName = item.lastName;
1406
- recipient.language = item.language ?? null;
1407
- recipient.replacements = item.replacements;
1408
- recipient.memberId = item.memberId ?? null;
1409
- recipient.userId = item.userId ?? null;
1410
- recipient.organizationId = upToDate.organizationId ?? null;
1411
- await recipient.save();
1412
-
1413
- if (recipient.email || recipient.userId) {
1414
- return;
1415
- }
1416
- }
1417
-
1418
- request = null;
1419
- }
1420
- }
1421
-
1422
- console.warn('No example recipient found for email', id);
1423
- } catch (e) {
1424
- console.error('Failed to build example recipient for email', id);
1425
- console.error(e);
1426
- }
1427
- });
1428
- }
1429
-
1430
719
  getStructure() {
1431
720
  return EmailStruct.create(this);
1432
721
  }
@@ -1455,229 +744,4 @@ export class Email extends QueryableModel {
1455
744
  }
1456
745
  return [...languages].filter(language => new I18n(language, country).language === language);
1457
746
  }
1458
-
1459
- /**
1460
- * @param options.allLanguages Also fill exampleRecipients: the same recipient with its
1461
- * replacements generated in each supported language. Only use this for detail endpoints,
1462
- * it repeats the replacement queries for every language.
1463
- */
1464
- async getPreviewStructure(options: { allLanguages?: boolean } = {}) {
1465
- const emailRecipient = await EmailRecipient.select()
1466
- .where('emailId', this.id)
1467
- .where('email', '!=', null)
1468
- .first(false);
1469
-
1470
- let baseRow: EmailRecipientStruct | undefined;
1471
-
1472
- if (emailRecipient) {
1473
- baseRow = await emailRecipient.getStructure();
1474
- }
1475
-
1476
- if (!baseRow) {
1477
- baseRow = getExampleRecipient();
1478
- }
1479
-
1480
- const organization = this.organizationId ? (await Organization.getByID(this.organizationId))! : null;
1481
- const allowedLanguages = this.getLanguages();
1482
-
1483
- const fillRow = async (row: EmailRecipientStruct) => {
1484
- const virtualRecipient = row.getRecipient();
1485
-
1486
- await fillRecipientReplacements(virtualRecipient, {
1487
- organization,
1488
- from: this.getFromAddress(),
1489
- replyTo: null,
1490
- forPreview: true,
1491
- forceRefresh: !this.sentAt,
1492
- allowedLanguages,
1493
- });
1494
- row.replacements = virtualRecipient.replacements;
1495
- return row;
1496
- };
1497
-
1498
- const recipientRow = await fillRow(baseRow.clone());
1499
-
1500
- // The same recipient in every supported language: the replacements are regenerated in
1501
- // each language (the recipient's own language is ignored), so the composer can show
1502
- // example values in the language that is being edited
1503
- const exampleRecipients = new Map<Language, EmailRecipientStruct>();
1504
- if (allowedLanguages && allowedLanguages.length > 1) {
1505
- // The same country the recipient locale will resolve to (see getRecipientI18n)
1506
- const country = organization?.address?.country ?? $getCountry();
1507
- for (const language of allowedLanguages) {
1508
- const i18n = new I18n(language, country);
1509
- await I18n.runWithLocale(i18n, async () => {
1510
- const clone = baseRow.clone();
1511
- clone.language = language;
1512
-
1513
- if (baseRow.language !== language) {
1514
- // Todo: this can be improved
1515
- // Replace all replacements with defaults
1516
- for (const replacement of clone.replacements) {
1517
- const example: Replacement | undefined = ExampleReplacements.all[replacement.token];
1518
- if (example) {
1519
- replacement.html = example.html;
1520
- replacement.value = example.value;
1521
- }
1522
- }
1523
-
1524
- clone.replacements = clone.replacements.filter(r => !['organizationName'].includes(r.token));
1525
- }
1526
-
1527
- const rr = await fillRow(clone);
1528
- exampleRecipients.set(language, rr);
1529
- });
1530
- }
1531
- }
1532
-
1533
- let user: UserStruct | null = null;
1534
- if (this.userId) {
1535
- const u = await User.getByID(this.userId);
1536
- if (u) {
1537
- user = u.getStructure();
1538
- }
1539
- }
1540
-
1541
- let organizationStruct: BaseOrganization | null = null;
1542
- if (organization) {
1543
- organizationStruct = organization.getBaseStructure();
1544
- }
1545
-
1546
- return EmailPreview.create({
1547
- ...this,
1548
- user,
1549
- organization: organizationStruct,
1550
- exampleRecipient: recipientRow,
1551
- exampleRecipients,
1552
- });
1553
- }
1554
-
1555
- /**
1556
- * Whether the email has content in this language (strict: the default content only counts
1557
- * for its own language, see getEmailContentForLanguage)
1558
- */
1559
- hasContentForLanguage(language: Language): boolean {
1560
- return language === this.language || this.translations.has(language);
1561
- }
1562
-
1563
- /**
1564
- * @param options.language The language the caller is viewing in (from the request headers).
1565
- * Recipients are returned in this language when the email has content for it, otherwise in
1566
- * the language they received the email in.
1567
- */
1568
- async getStructureForUser(user: User, memberIds: string[], options: { language?: Language | null } = {}) {
1569
- const emailRecipients = await EmailRecipient.select()
1570
- .where('emailId', this.id)
1571
- .where('memberId', memberIds)
1572
- .fetch();
1573
- const organization = this.organizationId ? (await Organization.getByID(this.organizationId))! : null;
1574
-
1575
- const recipientsMap: Map<string, EmailRecipient> = new Map();
1576
- for (const memberId of memberIds) {
1577
- const preferred = emailRecipients.find(e => e.memberId === memberId && (e.userId === user.id || e.email === user.email));
1578
- if (preferred) {
1579
- recipientsMap.set(preferred.duplicateOfRecipientId ?? preferred.id, preferred);
1580
- continue;
1581
- }
1582
-
1583
- const byMember = emailRecipients.find(e => e.memberId === memberId && e.userId === null && e.email === null);
1584
- if (byMember) {
1585
- recipientsMap.set(byMember.duplicateOfRecipientId ?? byMember.id, byMember);
1586
- continue;
1587
- }
1588
- const anyData = emailRecipients.find(e => e.memberId === memberId);
1589
- if (anyData) {
1590
- recipientsMap.set(anyData.duplicateOfRecipientId ?? anyData.id, anyData);
1591
- continue;
1592
- }
1593
- }
1594
-
1595
- // Remove duplicates that are marked as the same recipient
1596
- const cleanedRecipients: EmailRecipient[] = [...recipientsMap.values()];
1597
- const structures = await EmailRecipient.getStructures(cleanedRecipients);
1598
-
1599
- for (const struct of structures) {
1600
- if (!(struct.userId === user.id || struct.email === user.email) && !((struct.userId === null && struct.email === null))) {
1601
- stripSensitiveRecipientReplacements(struct, {
1602
- organization,
1603
- willFill: true,
1604
- });
1605
- }
1606
-
1607
- struct.firstName = user.firstName;
1608
- struct.lastName = user.lastName;
1609
- struct.email = user.email;
1610
- struct.userId = user.id;
1611
-
1612
- // Show the email in the language the caller is viewing in, but only when the email
1613
- // has content for it: otherwise keep the language the recipient received it in
1614
- // (better correct content in the wrong language than wrong content in the right language)
1615
- if (options.language && this.hasContentForLanguage(options.language)) {
1616
- struct.language = options.language;
1617
- }
1618
-
1619
- // We always refresh the data when we display it on the web (so everything is up to date)
1620
- // The replacements are regenerated in struct.language, so they match the displayed content
1621
- await fillRecipientReplacements(struct, {
1622
- organization,
1623
- from: this.getFromAddress(),
1624
- replyTo: null,
1625
- forPreview: false,
1626
- forceRefresh: true,
1627
- allowedLanguages: this.getLanguages(),
1628
- });
1629
- runWithRecipientLocale(struct, organization, () => {
1630
- stripRecipientReplacementsForWebDisplay(struct, {
1631
- organization,
1632
- });
1633
- });
1634
- if (this.html) {
1635
- struct.replacements = removeUnusedReplacements(this.getCombinedHtml(), struct.replacements);
1636
- }
1637
- }
1638
-
1639
- // Loop structures and remove if they have exactly the same content
1640
- // We do this here, because it is possible the user didn't receive any emails, so
1641
- // the merging at time of sending the emails didn't happen (uniqueness happened on email)
1642
- const uniqueStructures: EmailRecipientStruct[] = [];
1643
- for (const struct of structures) {
1644
- let found = false;
1645
- for (const unique of uniqueStructures) {
1646
- const merged = mergeReplacementsIfEqual(unique.replacements, struct.replacements);
1647
- if (merged !== false) {
1648
- unique.replacements = merged;
1649
- found = true;
1650
- break;
1651
- }
1652
- }
1653
-
1654
- if (!found) {
1655
- uniqueStructures.push(struct);
1656
- }
1657
- }
1658
-
1659
- let organizationStruct: BaseOrganization | null = null;
1660
- if (organization) {
1661
- organizationStruct = organization.getBaseStructure();
1662
- }
1663
-
1664
- return EmailWithRecipients.create({
1665
- ...this,
1666
- organization: organizationStruct,
1667
- recipients: uniqueStructures,
1668
-
1669
- // Remove private-like data
1670
- softBouncesCount: 0,
1671
- failedCount: 0,
1672
- emailErrors: null,
1673
- recipientsErrors: null,
1674
- succeededCount: 1,
1675
- emailRecipientsCount: 1,
1676
- hardBouncesCount: 0,
1677
- spamComplaintsCount: 0,
1678
- recipientFilter: EmailRecipientFilter.create({}),
1679
- membersCount: 1,
1680
- otherRecipientsCount: 0,
1681
- });
1682
- }
1683
747
  }