@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,23 +1,18 @@
1
1
  import { __decorate } from "tslib";
2
- import { CreateEmailIdentityCommand, DeleteEmailIdentityCommand, GetEmailIdentityCommand, PutEmailIdentityFeedbackAttributesCommand, PutEmailIdentityMailFromAttributesCommand, SESv2Client } from '@aws-sdk/client-sesv2';
3
2
  import { column, Database } from '@simonbackx/simple-database';
4
3
  import { SimpleError } from '@simonbackx/simple-errors';
5
4
  import { I18n } from '@stamhoofd/backend-i18n/I18n';
6
5
  import { QueueHandler } from '@stamhoofd/queues';
7
6
  import { QueryableModel, SQL, SQLWhereExists } from '@stamhoofd/sql';
8
- import { AccessRight, Address, Company, DNSRecordStatus, EmailTemplateType, getAppHost, GroupType, OrganizationMetaData, OrganizationPrivateMetaData, Organization as OrganizationStruct, PaymentMethod, PaymentProvider, Recipient, Replacement, STPackageType, TransferSettings } from '@stamhoofd/structures';
9
- import { Country } from '@stamhoofd/types/Country';
7
+ import { Address, Company, getAppHost, GroupType, OrganizationMetaData, OrganizationPrivateMetaData, Organization as OrganizationStruct, PaymentMethod, PaymentProvider, TransferSettings } from '@stamhoofd/structures';
10
8
  import { Language } from '@stamhoofd/types/Language';
11
- import { Formatter, Sorter } from '@stamhoofd/utility';
12
9
  import { v4 as uuidv4 } from 'uuid';
13
- import { validateDNSRecords } from '../helpers/DNSValidator.js';
14
10
  import { OrganizationServerMetaData } from '../structures/OrganizationServerMetaData.js';
15
11
  import { Event } from './Event.js';
16
12
  import { Group } from './Group.js';
17
13
  import { OrganizationRegistrationPeriod } from './OrganizationRegistrationPeriod.js';
18
14
  import { Registration } from './Registration.js';
19
15
  import { StripeAccount } from './StripeAccount.js';
20
- import { Token } from './Token.js';
21
16
  export class Organization extends QueryableModel {
22
17
  static table = 'organizations';
23
18
  // static cache = new ModelCache<Organization>();
@@ -243,530 +238,6 @@ export class Organization extends QueryableModel {
243
238
  hasFutureEvents: this.hasFutureEvents,
244
239
  });
245
240
  }
246
- async updateDNSRecords() {
247
- const organization = this;
248
- // Check initial status
249
- let isValidRecords = true;
250
- for (const record of organization.privateMeta.dnsRecords) {
251
- if (record.status !== DNSRecordStatus.Valid) {
252
- isValidRecords = false;
253
- }
254
- }
255
- const { allValid } = await validateDNSRecords(organization.privateMeta.dnsRecords);
256
- if (organization.registerDomain ?? organization.privateMeta.pendingRegisterDomain) {
257
- const registerDomainRecord = (organization.privateMeta.pendingRegisterDomain ?? organization.registerDomain) + '.';
258
- const records = organization.privateMeta.dnsRecords.filter(r => r.name === registerDomainRecord);
259
- const areRegisterDomainRecordsValid = records.length === 0 || records.every(r => r.status === DNSRecordStatus.Valid);
260
- if (areRegisterDomainRecordsValid) {
261
- // We can setup the register domain if needed
262
- if (organization.privateMeta.pendingRegisterDomain !== null) {
263
- organization.registerDomain = organization.privateMeta.pendingRegisterDomain;
264
- organization.privateMeta.pendingRegisterDomain = null;
265
- console.log('Did set register domain for ' + this.id + ' to ' + organization.registerDomain);
266
- }
267
- }
268
- else {
269
- // Clear register domain
270
- if (organization.registerDomain) {
271
- // We need to clear it, to prevent sending e-mails with invalid links
272
- organization.privateMeta.pendingRegisterDomain = organization.privateMeta.pendingRegisterDomain ?? organization.registerDomain;
273
- organization.registerDomain = null;
274
- console.log('Cleared register domain for ' + this.id + ' because of invalid non txt records');
275
- }
276
- }
277
- }
278
- if (allValid) {
279
- if (organization.privateMeta.pendingMailDomain !== null) {
280
- organization.privateMeta.mailDomain = organization.privateMeta.pendingMailDomain;
281
- organization.privateMeta.pendingMailDomain = null;
282
- }
283
- const wasUnstable = organization.serverMeta.isDNSUnstable;
284
- organization.serverMeta.markDNSValid();
285
- const didSendDomainSetupMail = organization.serverMeta.didSendDomainSetupMail;
286
- const didSendWarning = organization.serverMeta.DNSRecordWarningCount > 0;
287
- organization.serverMeta.DNSRecordWarningCount = 0;
288
- const wasActive = this.privateMeta.mailDomainActive;
289
- await this.updateAWSMailIdenitity();
290
- // yay! Do not Save until after doing AWS changes
291
- await organization.save();
292
- if (wasUnstable && !organization.serverMeta.isDNSUnstable) {
293
- console.warn('DNS settings became stable for ' + this.name + ' ' + this.id);
294
- await this.sendEmailTemplate({
295
- type: EmailTemplateType.OrganizationStableDNS,
296
- bcc: true,
297
- });
298
- }
299
- else if (!wasActive && this.privateMeta.mailDomainActive && (!didSendDomainSetupMail || didSendWarning) && !organization.serverMeta.isDNSUnstable) {
300
- organization.serverMeta.didSendDomainSetupMail = true;
301
- await organization.save();
302
- if (!didSendDomainSetupMail) {
303
- await this.sendEmailTemplate({
304
- type: EmailTemplateType.OrganizationDNSSetupComplete,
305
- });
306
- }
307
- else {
308
- await this.sendEmailTemplate({
309
- type: EmailTemplateType.OrganizationValidDNS,
310
- });
311
- }
312
- }
313
- }
314
- else {
315
- // DNS settings gone broken
316
- if (organization.privateMeta.mailDomain) {
317
- organization.privateMeta.pendingMailDomain = organization.privateMeta.pendingMailDomain ?? organization.privateMeta.mailDomain;
318
- organization.privateMeta.mailDomain = null;
319
- }
320
- const wasDNSUnstable = organization.serverMeta.isDNSUnstable;
321
- organization.serverMeta.markDNSFailure();
322
- // disable AWS emails
323
- this.privateMeta.mailDomainActive = false;
324
- // save
325
- await organization.save();
326
- if (!wasDNSUnstable && organization.serverMeta.isDNSUnstable) {
327
- // DNS became instable
328
- console.warn('DNS settings became instable for ' + this.name + ' ' + this.id);
329
- await this.sendEmailTemplate({
330
- type: EmailTemplateType.OrganizationUnstableDNS,
331
- bcc: true,
332
- });
333
- }
334
- else if (!organization.serverMeta.isDNSUnstable && organization.serverMeta.didSendDomainSetupMail && organization.serverMeta.DNSRecordWarningCount == 0) {
335
- organization.serverMeta.DNSRecordWarningCount += 1;
336
- await organization.save();
337
- await this.sendEmailTemplate({
338
- type: EmailTemplateType.OrganizationInvalidDNS,
339
- });
340
- }
341
- }
342
- }
343
- async sendEmailTemplate(data) {
344
- const recipients = await this.getAdminRecipients();
345
- const defaultI18n = new I18n(Language.Dutch, Country.Belgium);
346
- const i18n = this.i18n;
347
- const replaceAll = [
348
- {
349
- from: defaultI18n.localizedDomains.marketing(),
350
- to: i18n.localizedDomains.marketing(),
351
- },
352
- {
353
- from: defaultI18n.$t('%2a'),
354
- to: i18n.$t('%2a'),
355
- },
356
- {
357
- from: defaultI18n.$t('%19'),
358
- to: i18n.$t('%19'),
359
- },
360
- ];
361
- const { sendEmailTemplate } = await import('../helpers/EmailBuilder.js');
362
- // Create e-mail builder
363
- await sendEmailTemplate(null, {
364
- replaceAll,
365
- recipients,
366
- template: {
367
- type: data.type,
368
- },
369
- singleBcc: data.bcc ? { email: 'simon@stamhoofd.be' } : undefined,
370
- type: 'transactional',
371
- defaultReplacements: [
372
- Replacement.create({
373
- token: 'mailDomain',
374
- value: this.privateMeta.mailDomain ?? this.privateMeta.pendingMailDomain ?? '',
375
- }),
376
- Replacement.create({
377
- token: 'organizationName',
378
- value: this.name,
379
- }),
380
- ],
381
- unsubscribeType: 'marketing',
382
- fromStamhoofd: true,
383
- });
384
- }
385
- static get forbiddenEmailDomains() {
386
- return [
387
- STAMHOOFD.domains.dashboard,
388
- ...Object.values(STAMHOOFD.domains.defaultBroadcastEmail ?? {}),
389
- ...Object.values(STAMHOOFD.domains.defaultTransactionalEmail ?? {}),
390
- ];
391
- }
392
- async deleteAWSMailIdenitity(mailDomain) {
393
- // Protect specific domain names
394
- if (Organization.forbiddenEmailDomains.includes(mailDomain.toLowerCase())) {
395
- return;
396
- }
397
- if (STAMHOOFD.environment !== 'production') {
398
- // Temporary ignore this
399
- return;
400
- }
401
- const client = new SESv2Client({});
402
- // Check if mail identitiy already exists..
403
- try {
404
- const cmd = new GetEmailIdentityCommand({
405
- EmailIdentity: mailDomain,
406
- });
407
- const result = await client.send(cmd);
408
- if (result.VerifiedForSendingStatus === true) {
409
- console.log('Cant delete AWS mail idenitiy @' + this.id + ' for ' + mailDomain + ': already validated and might be in use by other organizations');
410
- return;
411
- }
412
- console.log('Deleting AWS mail identity @' + this.id + ' for ' + mailDomain);
413
- const deleteCmd = new DeleteEmailIdentityCommand({
414
- EmailIdentity: mailDomain,
415
- });
416
- await client.send(deleteCmd);
417
- console.log('Deleted AWS mail idenitiy @' + this.id + ' for ' + this.privateMeta.mailDomain);
418
- }
419
- catch (e) {
420
- console.error('Could not delete AWS email identitiy @' + this.id + ' for ' + this.privateMeta.mailDomain);
421
- console.error(e);
422
- }
423
- }
424
- /**
425
- * Create or update the AWS mail idenitiy and also update the active state of the mailDomain
426
- */
427
- async updateAWSMailIdenitity() {
428
- if (this.privateMeta.mailDomain === null) {
429
- return;
430
- }
431
- // Protect specific domain names
432
- if (['stamhoofd.be', 'stamhoofd.nl', 'stamhoofd.shop', 'stamhoofd.app', 'stamhoofd.email'].includes(this.privateMeta.mailDomain)) {
433
- console.error('Tried to validate AWS mail identity with protected domains @' + this.id);
434
- this.privateMeta.mailDomainActive = false;
435
- return;
436
- }
437
- if (STAMHOOFD.environment !== 'production') {
438
- // Temporary ignore this
439
- this.privateMeta.mailDomainActive = true;
440
- return;
441
- }
442
- const client = new SESv2Client({});
443
- const expectedConfigurationSetName = Formatter.slug(STAMHOOFD.platformName + '-domains');
444
- // Check if mail identitiy already exists..
445
- let exists = false;
446
- let existing = undefined;
447
- try {
448
- const cmd = new GetEmailIdentityCommand({
449
- EmailIdentity: this.privateMeta.mailDomain,
450
- });
451
- existing = await client.send(cmd);
452
- exists = true;
453
- console.log('AWS mail idenitiy exists already: just checking the verification status in AWS @' + this.id);
454
- if (existing.ConfigurationSetName !== expectedConfigurationSetName) {
455
- // Not allowed to use this identity
456
- this.privateMeta.mailDomainActive = false;
457
- console.error('Organization is not allowed to use email identity ' + this.privateMeta.mailDomain + ' @' + this.id + ', got ' + existing.ConfigurationSetName);
458
- return;
459
- }
460
- this.privateMeta.mailDomainActive = existing.VerifiedForSendingStatus ?? false;
461
- if (existing.VerifiedForSendingStatus !== true) {
462
- console.error('Not validated @' + this.id);
463
- }
464
- if (existing.VerifiedForSendingStatus !== true && existing.DkimAttributes?.Status === 'FAILED') {
465
- console.error('AWS failed to verify DKIM records. Triggering a forced recheck @' + this.id);
466
- const deleteCmd = new DeleteEmailIdentityCommand({
467
- EmailIdentity: this.privateMeta.mailDomain,
468
- });
469
- await client.send(deleteCmd);
470
- // Recreate it immediately
471
- exists = false;
472
- }
473
- }
474
- catch (e) {
475
- console.error(e);
476
- }
477
- if (!exists) {
478
- console.log('Creating email identity in AWS SES...');
479
- const cmd = new CreateEmailIdentityCommand({
480
- EmailIdentity: this.privateMeta.mailDomain,
481
- ConfigurationSetName: expectedConfigurationSetName,
482
- DkimSigningAttributes: {
483
- DomainSigningPrivateKey: this.serverMeta.privateDKIMKey,
484
- DomainSigningSelector: Formatter.slug(STAMHOOFD.platformName),
485
- },
486
- Tags: [
487
- {
488
- Key: 'OrganizationId',
489
- Value: this.id,
490
- },
491
- {
492
- Key: 'Environment',
493
- Value: STAMHOOFD.environment ?? 'Unknown',
494
- },
495
- ],
496
- });
497
- const result = await client.send(cmd);
498
- this.privateMeta.mailDomainActive = result.VerifiedForSendingStatus ?? false;
499
- // Disable email forwarding of bounces and complaints
500
- // We handle this now with the configuration set
501
- const putFeedbackCmd = new PutEmailIdentityFeedbackAttributesCommand({
502
- EmailIdentity: this.privateMeta.mailDomain,
503
- EmailForwardingEnabled: false,
504
- });
505
- await client.send(putFeedbackCmd);
506
- }
507
- if (this.privateMeta.mailFromDomain && (!exists || (existing && (!existing.MailFromAttributes || existing.MailFromAttributes.MailFromDomain !== this.privateMeta.mailFromDomain)))) {
508
- // Also set a from domain, to fix SPF
509
- console.log('Setting mail from domain: ' + this.privateMeta.mailFromDomain + ' for ' + this.id);
510
- const cmd = new PutEmailIdentityMailFromAttributesCommand({
511
- EmailIdentity: this.privateMeta.mailDomain,
512
- BehaviorOnMxFailure: 'USE_DEFAULT_VALUE',
513
- MailFromDomain: this.privateMeta.mailFromDomain,
514
- });
515
- await client.send(cmd);
516
- }
517
- }
518
- async checkDrips() {
519
- const days7 = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000);
520
- // Welcome drip
521
- // Created maximum 7 days ago
522
- if (this.createdAt > days7 && !this.serverMeta.hasEmail(EmailTemplateType.OrganizationDripWelcome)) {
523
- await this.sendEmailTemplate({
524
- type: EmailTemplateType.OrganizationDripWelcome,
525
- personal: true,
526
- });
527
- this.serverMeta.addEmail(EmailTemplateType.OrganizationDripWelcome);
528
- await this.save();
529
- return; // Never send more than 1 drip email on the same day
530
- }
531
- // Webshop trial checkin
532
- if (!this.serverMeta.hasEmail(EmailTemplateType.OrganizationDripWebshopTrialCheckin)) {
533
- if (this.meta.packages.isWebshopsTrial) {
534
- const activeTime = this.meta.packages.getActiveTime(STPackageType.TrialWebshops);
535
- if (activeTime !== null && activeTime > 4 * 24 * 60 * 60 * 1000) {
536
- // 7 days checkin
537
- await this.sendEmailTemplate({
538
- type: EmailTemplateType.OrganizationDripWebshopTrialCheckin,
539
- personal: true,
540
- });
541
- this.serverMeta.addEmail(EmailTemplateType.OrganizationDripWebshopTrialCheckin);
542
- this.serverMeta.addEmail(EmailTemplateType.OrganizationDripMembersTrialCheckin); // also mark members checkin
543
- await this.save();
544
- return; // Never send more than 1 drip email on the same day
545
- }
546
- }
547
- }
548
- // Members trial checkin
549
- if (!this.serverMeta.hasEmail(EmailTemplateType.OrganizationDripMembersTrialCheckin)) {
550
- if (this.meta.packages.isMembersTrial) {
551
- const activeTime = this.meta.packages.getActiveTime(STPackageType.TrialMembers);
552
- if (activeTime !== null && activeTime > 4 * 24 * 60 * 60 * 1000) {
553
- // 7 days checkin
554
- await this.sendEmailTemplate({
555
- type: EmailTemplateType.OrganizationDripMembersTrialCheckin,
556
- personal: true,
557
- });
558
- this.serverMeta.addEmail(EmailTemplateType.OrganizationDripMembersTrialCheckin);
559
- this.serverMeta.addEmail(EmailTemplateType.OrganizationDripWebshopTrialCheckin); // Also mark webshop trial checkin
560
- await this.save();
561
- return; // Never send more than 1 drip email on the same day
562
- }
563
- }
564
- }
565
- // Webshop trial expired after 1 week
566
- if (!this.serverMeta.hasEmail(EmailTemplateType.OrganizationDripWebshopTrialExpired)) {
567
- if (!this.meta.packages.useWebshops) {
568
- const deactivatedTime = this.meta.packages.getDeactivatedTime(STPackageType.TrialWebshops);
569
- if (deactivatedTime !== null && deactivatedTime < 14 * 24 * 60 * 60 * 1000 && deactivatedTime > 7 * 24 * 60 * 60 * 1000) {
570
- await this.sendEmailTemplate({
571
- type: EmailTemplateType.OrganizationDripWebshopTrialExpired,
572
- personal: true,
573
- });
574
- this.serverMeta.addEmail(EmailTemplateType.OrganizationDripWebshopTrialExpired);
575
- this.serverMeta.addEmail(EmailTemplateType.OrganizationDripMembersTrialExpired); // also mark members
576
- await this.save();
577
- return; // Never send more than 1 drip email on the same day
578
- }
579
- }
580
- }
581
- if (!this.serverMeta.hasEmail(EmailTemplateType.OrganizationDripMembersTrialExpired)) {
582
- if (!this.meta.packages.useMembers) {
583
- const deactivatedTime = this.meta.packages.getDeactivatedTime(STPackageType.TrialMembers);
584
- if (deactivatedTime !== null && deactivatedTime < 14 * 24 * 60 * 60 * 1000 && deactivatedTime > 7 * 24 * 60 * 60 * 1000) {
585
- await this.sendEmailTemplate({
586
- type: EmailTemplateType.OrganizationDripMembersTrialExpired,
587
- personal: true,
588
- });
589
- this.serverMeta.addEmail(EmailTemplateType.OrganizationDripMembersTrialExpired);
590
- this.serverMeta.addEmail(EmailTemplateType.OrganizationDripWebshopTrialExpired); // also mark webshops
591
- await this.save();
592
- return; // Never send more than 1 drip email on the same day
593
- }
594
- }
595
- }
596
- // trial expired reminder (after 10 months)
597
- if (!this.serverMeta.hasEmail(EmailTemplateType.OrganizationDripTrialExpiredReminder)) {
598
- if (!this.meta.packages.isPaid && !this.meta.packages.wasPaid) {
599
- const deactivatedTime1 = this.meta.packages.getDeactivatedTime(STPackageType.TrialWebshops);
600
- const deactivatedTime2 = this.meta.packages.getDeactivatedTime(STPackageType.TrialMembers);
601
- const deactivatedTime = deactivatedTime1 && deactivatedTime2 ? Math.max(deactivatedTime1, deactivatedTime2) : (deactivatedTime1 ? deactivatedTime1 : deactivatedTime2);
602
- if (deactivatedTime !== null && deactivatedTime > 10 * 30 * 24 * 60 * 60 * 1000 && deactivatedTime < 13 * 31 * 24 * 60 * 60 * 1000) {
603
- await this.sendEmailTemplate({
604
- type: EmailTemplateType.OrganizationDripTrialExpiredReminder,
605
- personal: true,
606
- bcc: true,
607
- });
608
- this.serverMeta.addEmail(EmailTemplateType.OrganizationDripTrialExpiredReminder);
609
- await this.save();
610
- return; // Never send more than 1 drip email on the same day
611
- }
612
- }
613
- }
614
- if (!this.serverMeta.hasEmail(EmailTemplateType.OrganizationDripWebshopNotRenewed)) {
615
- if (!this.meta.packages.useWebshops) {
616
- const deactivatedTime = this.meta.packages.getDeactivatedTime(STPackageType.Webshops);
617
- if (deactivatedTime !== null && deactivatedTime > 30 * 24 * 60 * 60 * 1000 && deactivatedTime < 30 * 3 * 24 * 60 * 60 * 1000) {
618
- await this.sendEmailTemplate({
619
- type: EmailTemplateType.OrganizationDripWebshopNotRenewed,
620
- personal: true,
621
- bcc: true,
622
- });
623
- this.serverMeta.addEmail(EmailTemplateType.OrganizationDripWebshopNotRenewed);
624
- await this.save();
625
- return; // Never send more than 1 drip email on the same day
626
- }
627
- }
628
- }
629
- if (!this.serverMeta.hasEmail(EmailTemplateType.OrganizationDripMembersNotRenewed)) {
630
- if (!this.meta.packages.useMembers) {
631
- const deactivatedTime = this.meta.packages.getDeactivatedTime(STPackageType.Members);
632
- if (deactivatedTime !== null && deactivatedTime > 30 * 24 * 60 * 60 * 1000 && deactivatedTime < 30 * 3 * 24 * 60 * 60 * 1000) {
633
- await this.sendEmailTemplate({
634
- type: EmailTemplateType.OrganizationDripMembersNotRenewed,
635
- personal: true,
636
- bcc: true,
637
- });
638
- this.serverMeta.addEmail(EmailTemplateType.OrganizationDripMembersNotRenewed);
639
- await this.save();
640
- return; // Never send more than 1 drip email on the same day
641
- }
642
- }
643
- }
644
- }
645
- /**
646
- * E-mail address when we receive replies for organization@stamhoofd.email.
647
- * Note that this sould be private because it can contain personal e-mail addresses if the organization is not configured correctly
648
- */
649
- async getReplyEmails() {
650
- const sender = this.privateMeta.emails.find(e => e.default) ?? this.privateMeta.emails[0];
651
- if (sender) {
652
- return [
653
- {
654
- name: sender.name,
655
- email: sender.email,
656
- },
657
- ];
658
- }
659
- return await this.getAdminToEmails();
660
- }
661
- async getAdmins() {
662
- // Circular reference fix
663
- const User = (await import('./User.js')).User;
664
- return await User.getAdmins(this.id, { verified: true });
665
- }
666
- /**
667
- * These email addresess are private
668
- */
669
- async getFullAdmins() {
670
- const admins = await this.getAdmins();
671
- // Only full access
672
- return admins.filter(a => a.permissions && a.permissions.forOrganization(this)?.hasFullAccess());
673
- }
674
- /**
675
- * These email addresess are private
676
- */
677
- async getFinanceAdmins() {
678
- const admins = await this.getAdmins();
679
- const filtered = admins.filter(a => a.permissions && (a.permissions.forOrganization(this)?.hasFullAccess() || a.permissions.forOrganization(this)?.hasAccessRight(AccessRight.OrganizationFinanceDirector)));
680
- // Only full access
681
- return filtered;
682
- }
683
- /**
684
- * These email addresess are private
685
- */
686
- async getAdminToEmails() {
687
- const filtered = await this.getFullAdmins();
688
- if (STAMHOOFD.environment === 'production') {
689
- if (filtered.length > 1) {
690
- // remove stamhoofd email addresses
691
- const f = filtered.flatMap(f => f.getEmailTo()).filter(e => !e.email.endsWith('@stamhoofd.be') && !e.email.endsWith('@stamhoofd.nl'));
692
- if (f.length > 0) {
693
- return f;
694
- }
695
- }
696
- }
697
- return filtered.flatMap(f => f.getEmailTo());
698
- }
699
- adminsToRecipients(admins) {
700
- return admins.flatMap((f) => {
701
- return Recipient.create({
702
- firstName: f.firstName,
703
- lastName: f.lastName,
704
- email: f.email,
705
- replacements: [],
706
- });
707
- });
708
- }
709
- /**
710
- * These email addresess are private
711
- */
712
- async getAdminRecipients() {
713
- const filtered = await this.getFullAdmins();
714
- return this.adminsToRecipients(filtered);
715
- }
716
- /**
717
- * These email addresess are private
718
- */
719
- async getFinanceAdminRecipients() {
720
- const filtered = await this.getFullAdmins();
721
- return this.adminsToRecipients(filtered);
722
- }
723
- /**
724
- * These email addresess are private
725
- */
726
- async getInvoicingToEmails() {
727
- // Circular reference fix
728
- const filtered = await this.getFinanceAdmins();
729
- if (filtered.length > 0) {
730
- return filtered.flatMap(f => f.getEmailTo()).map((recipient) => {
731
- if (!recipient.name) {
732
- return recipient.email;
733
- }
734
- const cleanedName = Formatter.emailSenderName(recipient.name);
735
- if (cleanedName.length < 2) {
736
- return recipient.email;
737
- }
738
- return '"' + cleanedName + '" <' + recipient.email + '>';
739
- }).join(', ');
740
- }
741
- return undefined;
742
- }
743
- /**
744
- * Returns one email for invoices. since in ubl we can only add one address.
745
- * We choose the oldest user that was active in the last 3 months (otherwise the oldest user if noone was active)
746
- */
747
- async getInvoicingToEmail() {
748
- // Circular reference fix
749
- const admins = await this.getAdmins();
750
- const tokens = await Token.select().where('userId', admins.map(a => a.id)).fetch();
751
- // Sort by admins that were active in the last 3 months, then creation date
752
- const cutoffDate = new Date(Date.now() - 1000 * 60 * 60 * 24 * 31 * 3);
753
- admins.sort((a, b) => {
754
- const aTokens = tokens.filter(t => t.userId === a.id);
755
- const bTokens = tokens.filter(t => t.userId === b.id);
756
- const aActive = !!aTokens.find(t => t.updatedAt > cutoffDate);
757
- const bActive = !!bTokens.find(t => t.updatedAt > cutoffDate);
758
- return Sorter.stack(Sorter.byBooleanValue(aActive, bActive), Sorter.byDateValue(b.createdAt, a.createdAt));
759
- });
760
- 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)));
761
- if (filtered.length > 0) {
762
- return filtered.map(f => f.email)[0];
763
- }
764
- const filtered2 = admins.filter(a => a.verified && a.permissions && (a.permissions.forOrganization(this)?.hasFullAccess() || a.permissions.forOrganization(this)?.hasAccessRight(AccessRight.OrganizationFinanceDirector)));
765
- if (filtered2.length > 0) {
766
- return filtered2.map(f => f.email)[0];
767
- }
768
- return undefined;
769
- }
770
241
  /**
771
242
  * Return default e-mail address if no email addresses are set.
772
243
  */