@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,5 +1,3 @@
1
- import type { GetEmailIdentityCommandOutput } from '@aws-sdk/client-sesv2';
2
- import { CreateEmailIdentityCommand, DeleteEmailIdentityCommand, GetEmailIdentityCommand, PutEmailIdentityFeedbackAttributesCommand, PutEmailIdentityMailFromAttributesCommand, SESv2Client } from '@aws-sdk/client-sesv2';
3
1
  import { column, Database } from '@simonbackx/simple-database';
4
2
  import { SimpleError } from '@simonbackx/simple-errors';
5
3
  import { I18n } from '@stamhoofd/backend-i18n/I18n';
@@ -7,17 +5,16 @@ import type { EmailInterfaceRecipient } from '@stamhoofd/email';
7
5
  import { QueueHandler } from '@stamhoofd/queues';
8
6
  import { QueryableModel, SQL, SQLWhereExists } from '@stamhoofd/sql';
9
7
  import type { OrganizationEmail, PrivatePaymentConfiguration } from '@stamhoofd/structures';
10
- import { AccessRight, Address, Company, DNSRecordStatus, EmailTemplateType, getAppHost, GroupType, OrganizationMetaData, OrganizationPrivateMetaData, Organization as OrganizationStruct, PaymentMethod, PaymentProvider, Recipient, Replacement, STPackageType, TransferSettings } from '@stamhoofd/structures';
8
+ import { AccessRight, Address, Company, getAppHost, GroupType, OrganizationMetaData, OrganizationPrivateMetaData, Organization as OrganizationStruct, PaymentMethod, PaymentProvider, Recipient, TransferSettings } from '@stamhoofd/structures';
11
9
  import type { PaymentMandate } from '@stamhoofd/structures/PaymentMandate.js';
12
- import { Country } from '@stamhoofd/types/Country';
13
10
  import { Language } from '@stamhoofd/types/Language';
14
11
  import { Formatter, Sorter } from '@stamhoofd/utility';
15
12
  import { v4 as uuidv4 } from 'uuid';
16
- import { validateDNSRecords } from '../helpers/DNSValidator.js';
17
13
  import { OrganizationServerMetaData } from '../structures/OrganizationServerMetaData.js';
18
14
  import { Event } from './Event.js';
19
15
  import { Group } from './Group.js';
20
16
  import { OrganizationRegistrationPeriod } from './OrganizationRegistrationPeriod.js';
17
+ import { Platform } from './Platform.js';
21
18
  import { Registration } from './Registration.js';
22
19
  import { StripeAccount } from './StripeAccount.js';
23
20
  import { Token } from './Token.js';
@@ -355,638 +352,6 @@ export class Organization extends QueryableModel {
355
352
  });
356
353
  }
357
354
 
358
- async updateDNSRecords() {
359
- const organization = this;
360
-
361
- // Check initial status
362
- let isValidRecords = true;
363
- for (const record of organization.privateMeta.dnsRecords) {
364
- if (record.status !== DNSRecordStatus.Valid) {
365
- isValidRecords = false;
366
- }
367
- }
368
-
369
- const { allValid } = await validateDNSRecords(organization.privateMeta.dnsRecords);
370
-
371
- if (organization.registerDomain ?? organization.privateMeta.pendingRegisterDomain) {
372
- const registerDomainRecord = (organization.privateMeta.pendingRegisterDomain ?? organization.registerDomain) + '.';
373
- const records = organization.privateMeta.dnsRecords.filter(r => r.name === registerDomainRecord);
374
- const areRegisterDomainRecordsValid = records.length === 0 || records.every(r => r.status === DNSRecordStatus.Valid);
375
-
376
- if (areRegisterDomainRecordsValid) {
377
- // We can setup the register domain if needed
378
- if (organization.privateMeta.pendingRegisterDomain !== null) {
379
- organization.registerDomain = organization.privateMeta.pendingRegisterDomain;
380
- organization.privateMeta.pendingRegisterDomain = null;
381
-
382
- console.log('Did set register domain for ' + this.id + ' to ' + organization.registerDomain);
383
- }
384
- } else {
385
- // Clear register domain
386
- if (organization.registerDomain) {
387
- // We need to clear it, to prevent sending e-mails with invalid links
388
- organization.privateMeta.pendingRegisterDomain = organization.privateMeta.pendingRegisterDomain ?? organization.registerDomain;
389
- organization.registerDomain = null;
390
-
391
- console.log('Cleared register domain for ' + this.id + ' because of invalid non txt records');
392
- }
393
- }
394
- }
395
-
396
- if (allValid) {
397
- if (organization.privateMeta.pendingMailDomain !== null) {
398
- organization.privateMeta.mailDomain = organization.privateMeta.pendingMailDomain;
399
- organization.privateMeta.pendingMailDomain = null;
400
- }
401
-
402
- const wasUnstable = organization.serverMeta.isDNSUnstable;
403
- organization.serverMeta.markDNSValid();
404
-
405
- const didSendDomainSetupMail = organization.serverMeta.didSendDomainSetupMail;
406
- const didSendWarning = organization.serverMeta.DNSRecordWarningCount > 0;
407
- organization.serverMeta.DNSRecordWarningCount = 0;
408
-
409
- const wasActive = this.privateMeta.mailDomainActive;
410
- await this.updateAWSMailIdenitity();
411
-
412
- // yay! Do not Save until after doing AWS changes
413
- await organization.save();
414
-
415
- if (wasUnstable && !organization.serverMeta.isDNSUnstable) {
416
- console.warn('DNS settings became stable for ' + this.name + ' ' + this.id);
417
-
418
- await this.sendEmailTemplate({
419
- type: EmailTemplateType.OrganizationStableDNS,
420
- bcc: true,
421
- });
422
- } else if (!wasActive && this.privateMeta.mailDomainActive && (!didSendDomainSetupMail || didSendWarning) && !organization.serverMeta.isDNSUnstable) {
423
- organization.serverMeta.didSendDomainSetupMail = true;
424
- await organization.save();
425
-
426
- if (!didSendDomainSetupMail) {
427
- await this.sendEmailTemplate({
428
- type: EmailTemplateType.OrganizationDNSSetupComplete,
429
- });
430
- } else {
431
- await this.sendEmailTemplate({
432
- type: EmailTemplateType.OrganizationValidDNS,
433
- });
434
- }
435
- }
436
- } else {
437
- // DNS settings gone broken
438
- if (organization.privateMeta.mailDomain) {
439
- organization.privateMeta.pendingMailDomain = organization.privateMeta.pendingMailDomain ?? organization.privateMeta.mailDomain;
440
- organization.privateMeta.mailDomain = null;
441
- }
442
-
443
- const wasDNSUnstable = organization.serverMeta.isDNSUnstable;
444
-
445
- organization.serverMeta.markDNSFailure();
446
-
447
- // disable AWS emails
448
- this.privateMeta.mailDomainActive = false;
449
-
450
- // save
451
- await organization.save();
452
-
453
- if (!wasDNSUnstable && organization.serverMeta.isDNSUnstable) {
454
- // DNS became instable
455
- console.warn('DNS settings became instable for ' + this.name + ' ' + this.id);
456
-
457
- await this.sendEmailTemplate({
458
- type: EmailTemplateType.OrganizationUnstableDNS,
459
- bcc: true,
460
- });
461
- } else if (!organization.serverMeta.isDNSUnstable && organization.serverMeta.didSendDomainSetupMail && organization.serverMeta.DNSRecordWarningCount == 0) {
462
- organization.serverMeta.DNSRecordWarningCount += 1;
463
- await organization.save();
464
-
465
- await this.sendEmailTemplate({
466
- type: EmailTemplateType.OrganizationInvalidDNS,
467
- });
468
- }
469
- }
470
- }
471
-
472
- async sendEmailTemplate(data: {
473
- type: EmailTemplateType;
474
- personal?: boolean;
475
- bcc?: boolean;
476
- }) {
477
- const recipients = await this.getAdminRecipients();
478
- const defaultI18n = new I18n(Language.Dutch, Country.Belgium);
479
- const i18n = this.i18n;
480
-
481
- const replaceAll = [
482
- {
483
- from: defaultI18n.localizedDomains.marketing(),
484
- to: i18n.localizedDomains.marketing(),
485
- },
486
- {
487
- from: defaultI18n.$t('%2a'),
488
- to: i18n.$t('%2a'),
489
- },
490
- {
491
- from: defaultI18n.$t('%19'),
492
- to: i18n.$t('%19'),
493
- },
494
- ];
495
-
496
- const { sendEmailTemplate } = await import('../helpers/EmailBuilder.js');
497
-
498
- // Create e-mail builder
499
- await sendEmailTemplate(null, {
500
- replaceAll,
501
- recipients,
502
- template: {
503
- type: data.type,
504
- },
505
- singleBcc: data.bcc ? { email: 'simon@stamhoofd.be' } : undefined,
506
- type: 'transactional',
507
- defaultReplacements: [
508
- Replacement.create({
509
- token: 'mailDomain',
510
- value: this.privateMeta.mailDomain ?? this.privateMeta.pendingMailDomain ?? '',
511
- }),
512
- Replacement.create({
513
- token: 'organizationName',
514
- value: this.name,
515
- }),
516
- ],
517
- unsubscribeType: 'marketing',
518
- fromStamhoofd: true,
519
- });
520
- }
521
-
522
- static get forbiddenEmailDomains() {
523
- return [
524
- STAMHOOFD.domains.dashboard,
525
- ...Object.values(STAMHOOFD.domains.defaultBroadcastEmail ?? {}),
526
- ...Object.values(STAMHOOFD.domains.defaultTransactionalEmail ?? {}),
527
- ];
528
- }
529
-
530
- async deleteAWSMailIdenitity(mailDomain: string) {
531
- // Protect specific domain names
532
- if (Organization.forbiddenEmailDomains.includes(mailDomain.toLowerCase())) {
533
- return;
534
- }
535
-
536
- if (STAMHOOFD.environment !== 'production') {
537
- // Temporary ignore this
538
- return;
539
- }
540
-
541
- const client = new SESv2Client({});
542
-
543
- // Check if mail identitiy already exists..
544
- try {
545
- const cmd = new GetEmailIdentityCommand({
546
- EmailIdentity: mailDomain,
547
- });
548
- const result = await client.send(cmd);
549
-
550
- if (result.VerifiedForSendingStatus === true) {
551
- console.log('Cant delete AWS mail idenitiy @' + this.id + ' for ' + mailDomain + ': already validated and might be in use by other organizations');
552
- return;
553
- }
554
-
555
- console.log('Deleting AWS mail identity @' + this.id + ' for ' + mailDomain);
556
-
557
- const deleteCmd = new DeleteEmailIdentityCommand({
558
- EmailIdentity: mailDomain,
559
- });
560
-
561
- await client.send(deleteCmd);
562
- console.log('Deleted AWS mail idenitiy @' + this.id + ' for ' + this.privateMeta.mailDomain);
563
- } catch (e) {
564
- console.error('Could not delete AWS email identitiy @' + this.id + ' for ' + this.privateMeta.mailDomain);
565
- console.error(e);
566
- }
567
- }
568
-
569
- /**
570
- * Create or update the AWS mail idenitiy and also update the active state of the mailDomain
571
- */
572
- async updateAWSMailIdenitity() {
573
- if (this.privateMeta.mailDomain === null) {
574
- return;
575
- }
576
-
577
- // Protect specific domain names
578
- if (['stamhoofd.be', 'stamhoofd.nl', 'stamhoofd.shop', 'stamhoofd.app', 'stamhoofd.email'].includes(this.privateMeta.mailDomain)) {
579
- console.error('Tried to validate AWS mail identity with protected domains @' + this.id);
580
- this.privateMeta.mailDomainActive = false;
581
- return;
582
- }
583
-
584
- if (STAMHOOFD.environment !== 'production') {
585
- // Temporary ignore this
586
- this.privateMeta.mailDomainActive = true;
587
- return;
588
- }
589
-
590
- const client = new SESv2Client({});
591
- const expectedConfigurationSetName = Formatter.slug(STAMHOOFD.platformName + '-domains');
592
-
593
- // Check if mail identitiy already exists..
594
- let exists = false;
595
- let existing: GetEmailIdentityCommandOutput | undefined = undefined;
596
- try {
597
- const cmd = new GetEmailIdentityCommand({
598
- EmailIdentity: this.privateMeta.mailDomain,
599
- });
600
-
601
- existing = await client.send(cmd);
602
- exists = true;
603
-
604
- console.log('AWS mail idenitiy exists already: just checking the verification status in AWS @' + this.id);
605
-
606
- if (existing.ConfigurationSetName !== expectedConfigurationSetName) {
607
- // Not allowed to use this identity
608
- this.privateMeta.mailDomainActive = false;
609
- console.error('Organization is not allowed to use email identity ' + this.privateMeta.mailDomain + ' @' + this.id + ', got ' + existing.ConfigurationSetName);
610
- return;
611
- }
612
-
613
- this.privateMeta.mailDomainActive = existing.VerifiedForSendingStatus ?? false;
614
-
615
- if (existing.VerifiedForSendingStatus !== true) {
616
- console.error('Not validated @' + this.id);
617
- }
618
-
619
- if (existing.VerifiedForSendingStatus !== true && existing.DkimAttributes?.Status === 'FAILED') {
620
- console.error('AWS failed to verify DKIM records. Triggering a forced recheck @' + this.id);
621
-
622
- const deleteCmd = new DeleteEmailIdentityCommand({
623
- EmailIdentity: this.privateMeta.mailDomain,
624
- });
625
- await client.send(deleteCmd);
626
-
627
- // Recreate it immediately
628
- exists = false;
629
- }
630
- } catch (e) {
631
- console.error(e);
632
- }
633
-
634
- if (!exists) {
635
- console.log('Creating email identity in AWS SES...');
636
-
637
- const cmd = new CreateEmailIdentityCommand({
638
- EmailIdentity: this.privateMeta.mailDomain,
639
- ConfigurationSetName: expectedConfigurationSetName,
640
- DkimSigningAttributes: {
641
- DomainSigningPrivateKey: this.serverMeta.privateDKIMKey!,
642
- DomainSigningSelector: Formatter.slug(STAMHOOFD.platformName),
643
- },
644
- Tags: [
645
- {
646
- Key: 'OrganizationId',
647
- Value: this.id,
648
- },
649
- {
650
- Key: 'Environment',
651
- Value: STAMHOOFD.environment ?? 'Unknown',
652
- },
653
- ],
654
- });
655
-
656
- const result = await client.send(cmd);
657
- this.privateMeta.mailDomainActive = result.VerifiedForSendingStatus ?? false;
658
-
659
- // Disable email forwarding of bounces and complaints
660
- // We handle this now with the configuration set
661
- const putFeedbackCmd = new PutEmailIdentityFeedbackAttributesCommand({
662
- EmailIdentity: this.privateMeta.mailDomain,
663
- EmailForwardingEnabled: false,
664
- });
665
-
666
- await client.send(putFeedbackCmd);
667
- }
668
-
669
- if (this.privateMeta.mailFromDomain && (!exists || (existing && (!existing.MailFromAttributes || existing.MailFromAttributes.MailFromDomain !== this.privateMeta.mailFromDomain)))) {
670
- // Also set a from domain, to fix SPF
671
- console.log('Setting mail from domain: ' + this.privateMeta.mailFromDomain + ' for ' + this.id);
672
-
673
- const cmd = new PutEmailIdentityMailFromAttributesCommand({
674
- EmailIdentity: this.privateMeta.mailDomain,
675
- BehaviorOnMxFailure: 'USE_DEFAULT_VALUE',
676
- MailFromDomain: this.privateMeta.mailFromDomain,
677
- });
678
-
679
- await client.send(cmd);
680
- }
681
- }
682
-
683
- async checkDrips() {
684
- const days7 = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000);
685
-
686
- // Welcome drip
687
- // Created maximum 7 days ago
688
- if (this.createdAt > days7 && !this.serverMeta.hasEmail(EmailTemplateType.OrganizationDripWelcome)) {
689
- await this.sendEmailTemplate({
690
- type: EmailTemplateType.OrganizationDripWelcome,
691
- personal: true,
692
- });
693
-
694
- this.serverMeta.addEmail(EmailTemplateType.OrganizationDripWelcome);
695
- await this.save();
696
-
697
- return; // Never send more than 1 drip email on the same day
698
- }
699
-
700
- // Webshop trial checkin
701
- if (!this.serverMeta.hasEmail(EmailTemplateType.OrganizationDripWebshopTrialCheckin)) {
702
- if (this.meta.packages.isWebshopsTrial) {
703
- const activeTime = this.meta.packages.getActiveTime(STPackageType.TrialWebshops);
704
- if (activeTime !== null && activeTime > 4 * 24 * 60 * 60 * 1000) {
705
- // 7 days checkin
706
- await this.sendEmailTemplate({
707
- type: EmailTemplateType.OrganizationDripWebshopTrialCheckin,
708
- personal: true,
709
- });
710
-
711
- this.serverMeta.addEmail(EmailTemplateType.OrganizationDripWebshopTrialCheckin);
712
- this.serverMeta.addEmail(EmailTemplateType.OrganizationDripMembersTrialCheckin); // also mark members checkin
713
- await this.save();
714
-
715
- return; // Never send more than 1 drip email on the same day
716
- }
717
- }
718
- }
719
-
720
- // Members trial checkin
721
- if (!this.serverMeta.hasEmail(EmailTemplateType.OrganizationDripMembersTrialCheckin)) {
722
- if (this.meta.packages.isMembersTrial) {
723
- const activeTime = this.meta.packages.getActiveTime(STPackageType.TrialMembers);
724
- if (activeTime !== null && activeTime > 4 * 24 * 60 * 60 * 1000) {
725
- // 7 days checkin
726
- await this.sendEmailTemplate({
727
- type: EmailTemplateType.OrganizationDripMembersTrialCheckin,
728
- personal: true,
729
- });
730
-
731
- this.serverMeta.addEmail(EmailTemplateType.OrganizationDripMembersTrialCheckin);
732
- this.serverMeta.addEmail(EmailTemplateType.OrganizationDripWebshopTrialCheckin); // Also mark webshop trial checkin
733
- await this.save();
734
-
735
- return; // Never send more than 1 drip email on the same day
736
- }
737
- }
738
- }
739
-
740
- // Webshop trial expired after 1 week
741
- if (!this.serverMeta.hasEmail(EmailTemplateType.OrganizationDripWebshopTrialExpired)) {
742
- if (!this.meta.packages.useWebshops) {
743
- const deactivatedTime = this.meta.packages.getDeactivatedTime(STPackageType.TrialWebshops);
744
- if (deactivatedTime !== null && deactivatedTime < 14 * 24 * 60 * 60 * 1000 && deactivatedTime > 7 * 24 * 60 * 60 * 1000) {
745
- await this.sendEmailTemplate({
746
- type: EmailTemplateType.OrganizationDripWebshopTrialExpired,
747
- personal: true,
748
- });
749
-
750
- this.serverMeta.addEmail(EmailTemplateType.OrganizationDripWebshopTrialExpired);
751
- this.serverMeta.addEmail(EmailTemplateType.OrganizationDripMembersTrialExpired); // also mark members
752
- await this.save();
753
-
754
- return; // Never send more than 1 drip email on the same day
755
- }
756
- }
757
- }
758
-
759
- if (!this.serverMeta.hasEmail(EmailTemplateType.OrganizationDripMembersTrialExpired)) {
760
- if (!this.meta.packages.useMembers) {
761
- const deactivatedTime = this.meta.packages.getDeactivatedTime(STPackageType.TrialMembers);
762
- if (deactivatedTime !== null && deactivatedTime < 14 * 24 * 60 * 60 * 1000 && deactivatedTime > 7 * 24 * 60 * 60 * 1000) {
763
- await this.sendEmailTemplate({
764
- type: EmailTemplateType.OrganizationDripMembersTrialExpired,
765
- personal: true,
766
- });
767
-
768
- this.serverMeta.addEmail(EmailTemplateType.OrganizationDripMembersTrialExpired);
769
- this.serverMeta.addEmail(EmailTemplateType.OrganizationDripWebshopTrialExpired); // also mark webshops
770
- await this.save();
771
-
772
- return; // Never send more than 1 drip email on the same day
773
- }
774
- }
775
- }
776
-
777
- // trial expired reminder (after 10 months)
778
- if (!this.serverMeta.hasEmail(EmailTemplateType.OrganizationDripTrialExpiredReminder)) {
779
- if (!this.meta.packages.isPaid && !this.meta.packages.wasPaid) {
780
- const deactivatedTime1 = this.meta.packages.getDeactivatedTime(STPackageType.TrialWebshops);
781
- const deactivatedTime2 = this.meta.packages.getDeactivatedTime(STPackageType.TrialMembers);
782
-
783
- const deactivatedTime = deactivatedTime1 && deactivatedTime2 ? Math.max(deactivatedTime1, deactivatedTime2) : (deactivatedTime1 ? deactivatedTime1 : deactivatedTime2);
784
-
785
- if (deactivatedTime !== null && deactivatedTime > 10 * 30 * 24 * 60 * 60 * 1000 && deactivatedTime < 13 * 31 * 24 * 60 * 60 * 1000) {
786
- await this.sendEmailTemplate({
787
- type: EmailTemplateType.OrganizationDripTrialExpiredReminder,
788
- personal: true,
789
- bcc: true,
790
- });
791
-
792
- this.serverMeta.addEmail(EmailTemplateType.OrganizationDripTrialExpiredReminder);
793
- await this.save();
794
-
795
- return; // Never send more than 1 drip email on the same day
796
- }
797
- }
798
- }
799
-
800
- if (!this.serverMeta.hasEmail(EmailTemplateType.OrganizationDripWebshopNotRenewed)) {
801
- if (!this.meta.packages.useWebshops) {
802
- const deactivatedTime = this.meta.packages.getDeactivatedTime(STPackageType.Webshops);
803
-
804
- if (deactivatedTime !== null && deactivatedTime > 30 * 24 * 60 * 60 * 1000 && deactivatedTime < 30 * 3 * 24 * 60 * 60 * 1000) {
805
- await this.sendEmailTemplate({
806
- type: EmailTemplateType.OrganizationDripWebshopNotRenewed,
807
- personal: true,
808
- bcc: true,
809
- });
810
-
811
- this.serverMeta.addEmail(EmailTemplateType.OrganizationDripWebshopNotRenewed);
812
- await this.save();
813
-
814
- return; // Never send more than 1 drip email on the same day
815
- }
816
- }
817
- }
818
-
819
- if (!this.serverMeta.hasEmail(EmailTemplateType.OrganizationDripMembersNotRenewed)) {
820
- if (!this.meta.packages.useMembers) {
821
- const deactivatedTime = this.meta.packages.getDeactivatedTime(STPackageType.Members);
822
-
823
- if (deactivatedTime !== null && deactivatedTime > 30 * 24 * 60 * 60 * 1000 && deactivatedTime < 30 * 3 * 24 * 60 * 60 * 1000) {
824
- await this.sendEmailTemplate({
825
- type: EmailTemplateType.OrganizationDripMembersNotRenewed,
826
- personal: true,
827
- bcc: true,
828
- });
829
-
830
- this.serverMeta.addEmail(EmailTemplateType.OrganizationDripMembersNotRenewed);
831
- await this.save();
832
-
833
- return; // Never send more than 1 drip email on the same day
834
- }
835
- }
836
- }
837
- }
838
-
839
- /**
840
- * E-mail address when we receive replies for organization@stamhoofd.email.
841
- * Note that this sould be private because it can contain personal e-mail addresses if the organization is not configured correctly
842
- */
843
- async getReplyEmails(): Promise<EmailInterfaceRecipient[]> {
844
- const sender: OrganizationEmail | undefined = this.privateMeta.emails.find(e => e.default) ?? this.privateMeta.emails[0];
845
-
846
- if (sender) {
847
- return [
848
- {
849
- name: sender.name,
850
- email: sender.email,
851
- },
852
- ];
853
- }
854
-
855
- return await this.getAdminToEmails();
856
- }
857
-
858
- async getAdmins() {
859
- // Circular reference fix
860
- const User = (await import('./User.js')).User;
861
- return await User.getAdmins(this.id, { verified: true });
862
- }
863
-
864
- /**
865
- * These email addresess are private
866
- */
867
- async getFullAdmins() {
868
- const admins = await this.getAdmins();
869
-
870
- // Only full access
871
- return admins.filter(a => a.permissions && a.permissions.forOrganization(this)?.hasFullAccess());
872
- }
873
-
874
- /**
875
- * These email addresess are private
876
- */
877
- async getFinanceAdmins() {
878
- const admins = await this.getAdmins();
879
- const filtered = admins.filter(a => a.permissions && (a.permissions.forOrganization(this)?.hasFullAccess() || a.permissions.forOrganization(this)?.hasAccessRight(AccessRight.OrganizationFinanceDirector)));
880
-
881
- // Only full access
882
- return filtered;
883
- }
884
-
885
- /**
886
- * These email addresess are private
887
- */
888
- async getAdminToEmails(): Promise<EmailInterfaceRecipient[]> {
889
- const filtered = await this.getFullAdmins();
890
-
891
- if (STAMHOOFD.environment === 'production') {
892
- if (filtered.length > 1) {
893
- // remove stamhoofd email addresses
894
- const f = filtered.flatMap(f => f.getEmailTo()).filter(e => !e.email.endsWith('@stamhoofd.be') && !e.email.endsWith('@stamhoofd.nl'));
895
- if (f.length > 0) {
896
- return f;
897
- }
898
- }
899
- }
900
-
901
- return filtered.flatMap(f => f.getEmailTo());
902
- }
903
-
904
- adminsToRecipients(admins: User[]) {
905
- return admins.flatMap((f) => {
906
- return Recipient.create({
907
- firstName: f.firstName,
908
- lastName: f.lastName,
909
- email: f.email,
910
- replacements: [],
911
- });
912
- });
913
- }
914
-
915
- /**
916
- * These email addresess are private
917
- */
918
- async getAdminRecipients(): Promise<Recipient[]> {
919
- const filtered = await this.getFullAdmins();
920
- return this.adminsToRecipients(filtered);
921
- }
922
-
923
- /**
924
- * These email addresess are private
925
- */
926
- async getFinanceAdminRecipients(): Promise<Recipient[]> {
927
- const filtered = await this.getFullAdmins();
928
- return this.adminsToRecipients(filtered);
929
- }
930
-
931
- /**
932
- * These email addresess are private
933
- */
934
- async getInvoicingToEmails() {
935
- // Circular reference fix
936
- const filtered = await this.getFinanceAdmins();
937
-
938
- if (filtered.length > 0) {
939
- return filtered.flatMap(f => f.getEmailTo()).map((recipient) => {
940
- if (!recipient.name) {
941
- return recipient.email;
942
- }
943
- const cleanedName = Formatter.emailSenderName(recipient.name);
944
- if (cleanedName.length < 2) {
945
- return recipient.email;
946
- }
947
- return '"' + cleanedName + '" <' + recipient.email + '>';
948
- }).join(', ');
949
- }
950
-
951
- return undefined;
952
- }
953
-
954
- /**
955
- * Returns one email for invoices. since in ubl we can only add one address.
956
- * We choose the oldest user that was active in the last 3 months (otherwise the oldest user if noone was active)
957
- */
958
- async getInvoicingToEmail(): Promise<string | undefined> {
959
- // Circular reference fix
960
- const admins = await this.getAdmins();
961
-
962
- const tokens = await Token.select().where('userId', admins.map(a => a.id)).fetch();
963
-
964
- // Sort by admins that were active in the last 3 months, then creation date
965
- const cutoffDate = new Date(Date.now() - 1000 * 60 * 60 * 24 * 31 * 3);
966
- admins.sort((a, b) => {
967
- const aTokens = tokens.filter(t => t.userId === a.id);
968
- const bTokens = tokens.filter(t => t.userId === b.id);
969
- const aActive = !!aTokens.find(t => t.updatedAt > cutoffDate);
970
- const bActive = !!bTokens.find(t => t.updatedAt > cutoffDate);
971
- return Sorter.stack(
972
- Sorter.byBooleanValue(aActive, bActive),
973
- Sorter.byDateValue(b.createdAt, a.createdAt),
974
- );
975
- });
976
-
977
- const filtered = admins.filter(a => a.verified && a.permissions && !a.email.endsWith('@stamhoofd.be') && (a.permissions.forOrganization(this)?.hasFullAccess() || a.permissions.forOrganization(this)?.hasAccessRight(AccessRight.OrganizationFinanceDirector)));
978
-
979
- if (filtered.length > 0) {
980
- return filtered.map(f => f.email)[0];
981
- }
982
- const filtered2 = admins.filter(a => a.verified && a.permissions && (a.permissions.forOrganization(this)?.hasFullAccess() || a.permissions.forOrganization(this)?.hasAccessRight(AccessRight.OrganizationFinanceDirector)));
983
-
984
- if (filtered2.length > 0) {
985
- return filtered2.map(f => f.email)[0];
986
- }
987
- return undefined;
988
- }
989
-
990
355
  /**
991
356
  * Return default e-mail address if no email addresses are set.
992
357
  */