@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.
- package/dist/helpers/Handlebars.d.ts.map +1 -1
- package/dist/helpers/Handlebars.js +1 -1
- package/dist/helpers/Handlebars.js.map +1 -1
- package/dist/helpers/errorToSimpleErrors.d.ts +3 -0
- package/dist/helpers/errorToSimpleErrors.d.ts.map +1 -0
- package/dist/helpers/errorToSimpleErrors.js +17 -0
- package/dist/helpers/errorToSimpleErrors.js.map +1 -0
- package/dist/index.d.ts +0 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +0 -1
- package/dist/index.js.map +1 -1
- package/dist/migrations/1782902314-tokens-authenticated-at.sql +2 -0
- package/dist/migrations/1782902315-create-mfa-totp-table.sql +13 -0
- package/dist/migrations/1782902316-create-webauthn-credentials-table.sql +17 -0
- package/dist/migrations/1782902317-create-mfa-recovery-codes-table.sql +10 -0
- package/dist/migrations/1782902318-create-mfa-tokens-table.sql +13 -0
- package/dist/migrations/1782902319-create-webauthn-challenges-table.sql +10 -0
- package/dist/migrations/1784039947-mfa-totp-last-used-counter.sql +2 -0
- package/dist/migrations/1784122354-webauthn-credential-provider.sql +3 -0
- package/dist/migrations/1784500000-webauthn-credential-rp-id.sql +9 -0
- package/dist/migrations/1785354091-platform-parent-tenant-id.sql +1 -0
- package/dist/migrations/1785354092-platform-fees-tenant-id.sql +1 -0
- package/dist/migrations/1785354093-platform-uri.sql +1 -0
- package/dist/migrations/1785354094-platform-domain.sql +1 -0
- package/dist/migrations/1785354095-platform-uri-unique.sql +1 -0
- package/dist/migrations/1785354096-platform-domain-unique.sql +1 -0
- package/dist/migrations/1785354097-platform-parent-tenant-id-index.sql +1 -0
- package/dist/migrations/1785354098-platform-tenant-backfill.d.ts +4 -0
- package/dist/migrations/1785354098-platform-tenant-backfill.d.ts.map +1 -0
- package/dist/migrations/1785354098-platform-tenant-backfill.js +10 -0
- package/dist/migrations/1785354098-platform-tenant-backfill.js.map +1 -0
- package/dist/migrations/1785417301-users-last-active-at.sql +2 -0
- package/dist/models/Document.d.ts +0 -4
- package/dist/models/Document.d.ts.map +1 -1
- package/dist/models/Document.js +1 -75
- package/dist/models/Document.js.map +1 -1
- package/dist/models/DocumentTemplate.d.ts +0 -3
- package/dist/models/DocumentTemplate.d.ts.map +1 -1
- package/dist/models/DocumentTemplate.js +1 -63
- package/dist/models/DocumentTemplate.js.map +1 -1
- package/dist/models/Email.d.ts +1 -29
- package/dist/models/Email.d.ts.map +1 -1
- package/dist/models/Email.js +4 -823
- package/dist/models/Email.js.map +1 -1
- package/dist/models/EmailVerificationCode.d.ts +0 -5
- package/dist/models/EmailVerificationCode.d.ts.map +1 -1
- package/dist/models/EmailVerificationCode.js +0 -84
- package/dist/models/EmailVerificationCode.js.map +1 -1
- package/dist/models/Image.d.ts.map +1 -1
- package/dist/models/Image.js +11 -14
- package/dist/models/Image.js.map +1 -1
- package/dist/models/MFARecoveryCode.d.ts +17 -0
- package/dist/models/MFARecoveryCode.d.ts.map +1 -0
- package/dist/models/MFARecoveryCode.js +55 -0
- package/dist/models/MFARecoveryCode.js.map +1 -0
- package/dist/models/MFATOTP.d.ts +44 -0
- package/dist/models/MFATOTP.d.ts.map +1 -0
- package/dist/models/MFATOTP.js +116 -0
- package/dist/models/MFATOTP.js.map +1 -0
- package/dist/models/MFAToken.d.ts +49 -0
- package/dist/models/MFAToken.d.ts.map +1 -0
- package/dist/models/MFAToken.js +137 -0
- package/dist/models/MFAToken.js.map +1 -0
- package/dist/models/MemberPlatformMembership.d.ts +0 -8
- package/dist/models/MemberPlatformMembership.d.ts.map +1 -1
- package/dist/models/MemberPlatformMembership.js +1 -242
- package/dist/models/MemberPlatformMembership.js.map +1 -1
- package/dist/models/Order.d.ts +1 -32
- package/dist/models/Order.d.ts.map +1 -1
- package/dist/models/Order.js +1 -182
- package/dist/models/Order.js.map +1 -1
- package/dist/models/Organization.d.ts +1 -51
- package/dist/models/Organization.d.ts.map +1 -1
- package/dist/models/Organization.js +1 -530
- package/dist/models/Organization.js.map +1 -1
- package/dist/models/PasswordToken.d.ts +0 -8
- package/dist/models/PasswordToken.d.ts.map +1 -1
- package/dist/models/PasswordToken.js +0 -23
- package/dist/models/PasswordToken.js.map +1 -1
- package/dist/models/Platform.d.ts +28 -4
- package/dist/models/Platform.d.ts.map +1 -1
- package/dist/models/Platform.js +111 -50
- package/dist/models/Platform.js.map +1 -1
- package/dist/models/STPackage.d.ts +1 -6
- package/dist/models/STPackage.d.ts.map +1 -1
- package/dist/models/STPackage.js +1 -98
- package/dist/models/STPackage.js.map +1 -1
- package/dist/models/Token.d.ts +40 -1
- package/dist/models/Token.d.ts.map +1 -1
- package/dist/models/Token.js +68 -2
- package/dist/models/Token.js.map +1 -1
- package/dist/models/User.d.ts +25 -0
- package/dist/models/User.d.ts.map +1 -1
- package/dist/models/User.js +36 -0
- package/dist/models/User.js.map +1 -1
- package/dist/models/WebauthnChallenge.d.ts +27 -0
- package/dist/models/WebauthnChallenge.d.ts.map +1 -0
- package/dist/models/WebauthnChallenge.js +81 -0
- package/dist/models/WebauthnChallenge.js.map +1 -0
- package/dist/models/WebauthnCredential.d.ts +58 -0
- package/dist/models/WebauthnCredential.d.ts.map +1 -0
- package/dist/models/WebauthnCredential.js +144 -0
- package/dist/models/WebauthnCredential.js.map +1 -0
- package/dist/models/index.d.ts +5 -0
- package/dist/models/index.d.ts.map +1 -1
- package/dist/models/index.js +5 -0
- package/dist/models/index.js.map +1 -1
- package/package.json +3 -3
- package/src/helpers/Handlebars.ts +5 -9
- package/src/helpers/errorToSimpleErrors.ts +17 -0
- package/src/index.ts +0 -1
- package/src/migrations/1782902314-tokens-authenticated-at.sql +2 -0
- package/src/migrations/1782902315-create-mfa-totp-table.sql +13 -0
- package/src/migrations/1782902316-create-webauthn-credentials-table.sql +17 -0
- package/src/migrations/1782902317-create-mfa-recovery-codes-table.sql +10 -0
- package/src/migrations/1782902318-create-mfa-tokens-table.sql +13 -0
- package/src/migrations/1782902319-create-webauthn-challenges-table.sql +10 -0
- package/src/migrations/1784039947-mfa-totp-last-used-counter.sql +2 -0
- package/src/migrations/1784122354-webauthn-credential-provider.sql +3 -0
- package/src/migrations/1784500000-webauthn-credential-rp-id.sql +9 -0
- package/src/migrations/1785354091-platform-parent-tenant-id.sql +1 -0
- package/src/migrations/1785354092-platform-fees-tenant-id.sql +1 -0
- package/src/migrations/1785354093-platform-uri.sql +1 -0
- package/src/migrations/1785354094-platform-domain.sql +1 -0
- package/src/migrations/1785354095-platform-uri-unique.sql +1 -0
- package/src/migrations/1785354096-platform-domain-unique.sql +1 -0
- package/src/migrations/1785354097-platform-parent-tenant-id-index.sql +1 -0
- package/src/migrations/1785354098-platform-tenant-backfill.ts +14 -0
- package/src/migrations/1785417301-users-last-active-at.sql +2 -0
- package/src/models/Document.ts +1 -84
- package/src/models/DocumentTemplate.ts +1 -71
- package/src/models/Email.ts +5 -941
- package/src/models/EmailVerificationCode.ts +0 -96
- package/src/models/Image.ts +11 -14
- package/src/models/MFARecoveryCode.ts +52 -0
- package/src/models/MFATOTP.ts +112 -0
- package/src/models/MFAToken.ts +138 -0
- package/src/models/MemberPlatformMembership.ts +1 -285
- package/src/models/Order.ts +1 -204
- package/src/models/Organization.ts +2 -637
- package/src/models/PasswordToken.ts +0 -29
- package/src/models/Platform.test.ts +167 -3
- package/src/models/Platform.ts +125 -50
- package/src/models/STPackage.ts +1 -110
- package/src/models/Token.ts +73 -2
- package/src/models/User.ts +37 -0
- package/src/models/WebauthnChallenge.ts +80 -0
- package/src/models/WebauthnCredential.ts +130 -0
- package/src/models/index.ts +6 -0
- package/dist/helpers/EmailBuilder.d.ts +0 -121
- package/dist/helpers/EmailBuilder.d.ts.map +0 -1
- package/dist/helpers/EmailBuilder.js +0 -659
- package/dist/helpers/EmailBuilder.js.map +0 -1
- package/src/helpers/EmailBuilder.test.ts +0 -291
- package/src/helpers/EmailBuilder.ts +0 -818
- package/src/models/Email.test.ts +0 -1222
- package/src/models/MemberPlatformMembership.test.ts +0 -70
package/dist/models/Email.js
CHANGED
|
@@ -1,36 +1,16 @@
|
|
|
1
1
|
import { __decorate } from "tslib";
|
|
2
2
|
import { column } from '@simonbackx/simple-database';
|
|
3
|
-
import { EmailAttachment, EmailContent,
|
|
4
|
-
import { ExampleReplacements } from '@stamhoofd/structures/email/exampleReplacements.js';
|
|
3
|
+
import { EmailAttachment, EmailContent, EmailRecipientFilter, EmailRecipientsStatus, EmailStatus, Email as EmailStruct, LanguageHelper, LimitedFilteredRequest, SortItemDirection } from '@stamhoofd/structures';
|
|
5
4
|
import { Language } from '@stamhoofd/types/Language';
|
|
6
5
|
import { v4 as uuidv4 } from 'uuid';
|
|
7
6
|
import { AnyDecoder, ArrayDecoder, EnumDecoder, MapDecoder } from '@simonbackx/simple-encoding';
|
|
8
|
-
import {
|
|
7
|
+
import { SimpleError, SimpleErrors } from '@simonbackx/simple-errors';
|
|
9
8
|
import { I18n } from '@stamhoofd/backend-i18n/I18n';
|
|
10
|
-
import { Email as EmailClass } from '@stamhoofd/email';
|
|
11
9
|
import { isAbortedError, QueueHandler } from '@stamhoofd/queues';
|
|
12
|
-
import { QueryableModel, readDynamicSQLExpression, SQL, SQLAlias, SQLCount, SQLSelectAs
|
|
13
|
-
import {
|
|
10
|
+
import { QueryableModel, readDynamicSQLExpression, SQL, SQLAlias, SQLCount, SQLSelectAs } from '@stamhoofd/sql';
|
|
11
|
+
import { errorToSimpleErrors } from '../helpers/errorToSimpleErrors.js';
|
|
14
12
|
import { EmailRecipient } from './EmailRecipient.js';
|
|
15
13
|
import { EmailTemplate } from './EmailTemplate.js';
|
|
16
|
-
import { Organization } from './Organization.js';
|
|
17
|
-
import { Platform } from './Platform.js';
|
|
18
|
-
import { User } from './User.js';
|
|
19
|
-
function errorToSimpleErrors(e) {
|
|
20
|
-
if (isSimpleErrors(e)) {
|
|
21
|
-
return e;
|
|
22
|
-
}
|
|
23
|
-
else if (isSimpleError(e)) {
|
|
24
|
-
return new SimpleErrors(e);
|
|
25
|
-
}
|
|
26
|
-
else {
|
|
27
|
-
return new SimpleErrors(new SimpleError({
|
|
28
|
-
code: 'unknown_error',
|
|
29
|
-
message: ((typeof e === 'object' && e !== null && 'message' in e && typeof e.message === 'string') ? e.message : 'Unknown error'),
|
|
30
|
-
human: $t(`%1ED`),
|
|
31
|
-
}));
|
|
32
|
-
}
|
|
33
|
-
}
|
|
34
14
|
export class Email extends QueryableModel {
|
|
35
15
|
static table = 'emails';
|
|
36
16
|
id;
|
|
@@ -445,405 +425,6 @@ export class Email extends QueryableModel {
|
|
|
445
425
|
.update();
|
|
446
426
|
});
|
|
447
427
|
}
|
|
448
|
-
async queueForSending(waitForSending = false) {
|
|
449
|
-
console.log('Queueing email for sending', this.id);
|
|
450
|
-
this.throwIfNotReadyToSend();
|
|
451
|
-
this.throwIfNoUnsubscribeButton();
|
|
452
|
-
await this.lock(async (upToDate) => {
|
|
453
|
-
if (upToDate.status === EmailStatus.Draft) {
|
|
454
|
-
upToDate.status = EmailStatus.Queued;
|
|
455
|
-
}
|
|
456
|
-
if (upToDate.status === EmailStatus.Failed) {
|
|
457
|
-
// Retry failed email
|
|
458
|
-
upToDate.status = EmailStatus.Queued;
|
|
459
|
-
}
|
|
460
|
-
await upToDate.save();
|
|
461
|
-
});
|
|
462
|
-
if (waitForSending) {
|
|
463
|
-
return await this.resumeSending();
|
|
464
|
-
}
|
|
465
|
-
else {
|
|
466
|
-
this.resumeSending().catch(console.error);
|
|
467
|
-
}
|
|
468
|
-
return this;
|
|
469
|
-
}
|
|
470
|
-
async loadAttachments() {
|
|
471
|
-
const attachments = [];
|
|
472
|
-
for (const attachment of this.attachments) {
|
|
473
|
-
if (!attachment.content && !attachment.file) {
|
|
474
|
-
console.warn('Attachment without content found, skipping', attachment);
|
|
475
|
-
continue;
|
|
476
|
-
}
|
|
477
|
-
let filename = $t('%180');
|
|
478
|
-
if (attachment.contentType === 'application/pdf') {
|
|
479
|
-
// tmp solution for pdf only
|
|
480
|
-
filename += '.pdf';
|
|
481
|
-
}
|
|
482
|
-
if (attachment.file?.name) {
|
|
483
|
-
filename = attachment.file.name.toLowerCase().replace(/[^a-z0-9.]+/g, '-').replace(/^-+/, '').replace(/-+$/, '');
|
|
484
|
-
}
|
|
485
|
-
// Correct file name if needed
|
|
486
|
-
if (attachment.filename) {
|
|
487
|
-
filename = attachment.filename.toLowerCase().replace(/[^a-z0-9.]+/g, '-').replace(/^-+/, '').replace(/-+$/, '');
|
|
488
|
-
}
|
|
489
|
-
if (attachment.content) {
|
|
490
|
-
attachments.push({
|
|
491
|
-
filename: filename,
|
|
492
|
-
content: attachment.content,
|
|
493
|
-
contentType: attachment.contentType ?? undefined,
|
|
494
|
-
encoding: 'base64',
|
|
495
|
-
});
|
|
496
|
-
}
|
|
497
|
-
else {
|
|
498
|
-
// 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
|
|
499
|
-
const withSigned = await attachment.file.withSignedUrl();
|
|
500
|
-
if (!withSigned || !withSigned.signedUrl) {
|
|
501
|
-
throw new SimpleError({
|
|
502
|
-
code: 'attachment_not_found',
|
|
503
|
-
message: 'Attachment not found',
|
|
504
|
-
human: $t(`%181`),
|
|
505
|
-
});
|
|
506
|
-
}
|
|
507
|
-
const filePath = withSigned.signedUrl;
|
|
508
|
-
let fileBuffer;
|
|
509
|
-
try {
|
|
510
|
-
const response = await fetch(filePath);
|
|
511
|
-
fileBuffer = Buffer.from(await response.arrayBuffer());
|
|
512
|
-
}
|
|
513
|
-
catch (e) {
|
|
514
|
-
throw new SimpleError({
|
|
515
|
-
code: 'attachment_not_found',
|
|
516
|
-
message: 'Attachment not found',
|
|
517
|
-
human: $t(`%181`),
|
|
518
|
-
});
|
|
519
|
-
}
|
|
520
|
-
attachments.push({
|
|
521
|
-
filename: filename,
|
|
522
|
-
contentType: attachment.contentType ?? undefined,
|
|
523
|
-
content: fileBuffer,
|
|
524
|
-
});
|
|
525
|
-
}
|
|
526
|
-
}
|
|
527
|
-
return attachments;
|
|
528
|
-
}
|
|
529
|
-
async sendSingleRecipient(recipient, organization, data) {
|
|
530
|
-
let promiseResolve;
|
|
531
|
-
const promise = new Promise((resolve) => {
|
|
532
|
-
promiseResolve = resolve;
|
|
533
|
-
});
|
|
534
|
-
const virtualRecipient = recipient.getRecipient();
|
|
535
|
-
let resolved = false;
|
|
536
|
-
const callback = async (error) => {
|
|
537
|
-
if (resolved) {
|
|
538
|
-
return;
|
|
539
|
-
}
|
|
540
|
-
resolved = true;
|
|
541
|
-
try {
|
|
542
|
-
if (error === null) {
|
|
543
|
-
// Mark saved
|
|
544
|
-
recipient.sentAt = new Date();
|
|
545
|
-
recipient.failErrorMessage = null;
|
|
546
|
-
if (recipient.failError) {
|
|
547
|
-
recipient.previousFailError = recipient.failError;
|
|
548
|
-
}
|
|
549
|
-
recipient.failError = null;
|
|
550
|
-
// Update repacements that have been generated
|
|
551
|
-
recipient.replacements = virtualRecipient.replacements;
|
|
552
|
-
await recipient.save();
|
|
553
|
-
}
|
|
554
|
-
else {
|
|
555
|
-
recipient.failCount += 1;
|
|
556
|
-
recipient.failErrorMessage = error.message;
|
|
557
|
-
if (recipient.failError) {
|
|
558
|
-
recipient.previousFailError = recipient.failError;
|
|
559
|
-
}
|
|
560
|
-
recipient.failError = errorToSimpleErrors(error);
|
|
561
|
-
recipient.firstFailedAt = recipient.firstFailedAt ?? new Date();
|
|
562
|
-
recipient.lastFailedAt = new Date();
|
|
563
|
-
await recipient.save();
|
|
564
|
-
}
|
|
565
|
-
}
|
|
566
|
-
catch (e) {
|
|
567
|
-
console.error(e);
|
|
568
|
-
}
|
|
569
|
-
promiseResolve();
|
|
570
|
-
};
|
|
571
|
-
// Do send the email
|
|
572
|
-
// Create e-mail builder
|
|
573
|
-
const builder = await getEmailBuilder(organization ?? null, {
|
|
574
|
-
recipients: [
|
|
575
|
-
virtualRecipient,
|
|
576
|
-
],
|
|
577
|
-
from: data.from,
|
|
578
|
-
replyTo: data.replyTo,
|
|
579
|
-
subject: this.subject,
|
|
580
|
-
html: this.html,
|
|
581
|
-
translations: this.translations,
|
|
582
|
-
type: this.emailType ? 'transactional' : 'broadcast',
|
|
583
|
-
attachments: data.attachments,
|
|
584
|
-
callback(error) {
|
|
585
|
-
callback(error).catch(console.error);
|
|
586
|
-
},
|
|
587
|
-
headers: {
|
|
588
|
-
'X-Email-Id': this.id,
|
|
589
|
-
'X-Email-Recipient-Id': recipient.id,
|
|
590
|
-
},
|
|
591
|
-
});
|
|
592
|
-
EmailClass.schedule(builder);
|
|
593
|
-
return await promise;
|
|
594
|
-
}
|
|
595
|
-
async resumeSending(singleRecipientId = null) {
|
|
596
|
-
const id = this.id;
|
|
597
|
-
return await QueueHandler.schedule('send-email', async ({ abort }) => {
|
|
598
|
-
return await this.lock(async function (upToDate) {
|
|
599
|
-
if (upToDate.status === EmailStatus.Sent) {
|
|
600
|
-
// Already done
|
|
601
|
-
// In other cases -> queue has stopped and we can retry
|
|
602
|
-
if (!singleRecipientId) {
|
|
603
|
-
console.log('Email already sent, skipping...', upToDate.id);
|
|
604
|
-
return upToDate;
|
|
605
|
-
}
|
|
606
|
-
}
|
|
607
|
-
else {
|
|
608
|
-
if (singleRecipientId) {
|
|
609
|
-
// Not possible
|
|
610
|
-
throw new SimpleError({
|
|
611
|
-
code: 'invalid_state',
|
|
612
|
-
message: 'Cannot retry single recipient for email that is not yet sent',
|
|
613
|
-
});
|
|
614
|
-
}
|
|
615
|
-
if (upToDate.status === EmailStatus.Sending) {
|
|
616
|
-
// This is an automatic retry.
|
|
617
|
-
if (upToDate.emailType) {
|
|
618
|
-
// Not eligible for retry
|
|
619
|
-
upToDate.status = EmailStatus.Failed;
|
|
620
|
-
await upToDate.save();
|
|
621
|
-
return upToDate;
|
|
622
|
-
}
|
|
623
|
-
if (upToDate.createdAt < new Date(new Date().getTime() - 1000 * 60 * 60 * 24 * 2)) {
|
|
624
|
-
// Too long
|
|
625
|
-
console.error('Email has been sending for too long. Marking as failed...', upToDate.id);
|
|
626
|
-
upToDate.status = EmailStatus.Failed;
|
|
627
|
-
await upToDate.save();
|
|
628
|
-
return upToDate;
|
|
629
|
-
}
|
|
630
|
-
}
|
|
631
|
-
else if (upToDate.status !== EmailStatus.Queued) {
|
|
632
|
-
console.error('Email is not queued or sending, cannot send', upToDate.id, upToDate.status);
|
|
633
|
-
return upToDate;
|
|
634
|
-
}
|
|
635
|
-
}
|
|
636
|
-
const organization = upToDate.organizationId ? await Organization.getByID(upToDate.organizationId) : null;
|
|
637
|
-
let from = upToDate.getDefaultFromAddress(organization);
|
|
638
|
-
let replyTo = upToDate.getFromAddress();
|
|
639
|
-
let succeededCount = 0;
|
|
640
|
-
let softFailedCount = 0;
|
|
641
|
-
let failedCount = 0;
|
|
642
|
-
try {
|
|
643
|
-
upToDate.throwIfNotReadyToSend();
|
|
644
|
-
upToDate.throwIfNoUnsubscribeButton();
|
|
645
|
-
if (!from) {
|
|
646
|
-
throw new SimpleError({
|
|
647
|
-
code: 'invalid_field',
|
|
648
|
-
message: 'Missing from',
|
|
649
|
-
human: $t(`%ww`),
|
|
650
|
-
});
|
|
651
|
-
}
|
|
652
|
-
// Can we send from this e-mail or reply-to?
|
|
653
|
-
if (upToDate.fromAddress && await canSendFromEmail(upToDate.fromAddress, organization ?? null)) {
|
|
654
|
-
from = upToDate.getFromAddress();
|
|
655
|
-
replyTo = null;
|
|
656
|
-
}
|
|
657
|
-
abort.throwIfAborted();
|
|
658
|
-
if (!singleRecipientId) {
|
|
659
|
-
upToDate.status = EmailStatus.Sending;
|
|
660
|
-
}
|
|
661
|
-
upToDate.sentAt = upToDate.sentAt ?? new Date();
|
|
662
|
-
await upToDate.save();
|
|
663
|
-
// Create recipients if not yet created
|
|
664
|
-
await upToDate.buildRecipients();
|
|
665
|
-
abort.throwIfAborted();
|
|
666
|
-
// Refresh model
|
|
667
|
-
const c = (await Email.getByID(id));
|
|
668
|
-
if (!c) {
|
|
669
|
-
throw new SimpleError({
|
|
670
|
-
code: 'not_found',
|
|
671
|
-
message: 'Email not found',
|
|
672
|
-
human: $t(`%wz`),
|
|
673
|
-
});
|
|
674
|
-
}
|
|
675
|
-
upToDate.copyFrom(c);
|
|
676
|
-
if (upToDate.recipientsStatus !== EmailRecipientsStatus.Created) {
|
|
677
|
-
throw new SimpleError({
|
|
678
|
-
code: 'recipients_not_created',
|
|
679
|
-
message: 'Failed to create recipients',
|
|
680
|
-
human: $t(`%x0`),
|
|
681
|
-
});
|
|
682
|
-
}
|
|
683
|
-
// Create a buffer of all attachments
|
|
684
|
-
if (upToDate.sendAsEmail === true) {
|
|
685
|
-
const attachments = await upToDate.loadAttachments();
|
|
686
|
-
// Start actually sending in batches of recipients that are not yet sent
|
|
687
|
-
let idPointer = '';
|
|
688
|
-
const batchSize = 100;
|
|
689
|
-
let isSavingStatus = false;
|
|
690
|
-
let lastStatusSave = new Date();
|
|
691
|
-
async function saveStatus() {
|
|
692
|
-
if (singleRecipientId) {
|
|
693
|
-
// Don't save during looping
|
|
694
|
-
return;
|
|
695
|
-
}
|
|
696
|
-
if (!upToDate) {
|
|
697
|
-
return;
|
|
698
|
-
}
|
|
699
|
-
if (isSavingStatus) {
|
|
700
|
-
return;
|
|
701
|
-
}
|
|
702
|
-
if ((new Date().getTime() - lastStatusSave.getTime()) < 1000 * 5) {
|
|
703
|
-
// Save at most every 5 seconds
|
|
704
|
-
return;
|
|
705
|
-
}
|
|
706
|
-
if (succeededCount < upToDate.succeededCount || softFailedCount < upToDate.softFailedCount || failedCount < upToDate.failedCount) {
|
|
707
|
-
// Do not update on retries
|
|
708
|
-
return;
|
|
709
|
-
}
|
|
710
|
-
lastStatusSave = new Date();
|
|
711
|
-
isSavingStatus = true;
|
|
712
|
-
upToDate.succeededCount = succeededCount;
|
|
713
|
-
upToDate.softFailedCount = softFailedCount;
|
|
714
|
-
upToDate.failedCount = failedCount;
|
|
715
|
-
try {
|
|
716
|
-
await upToDate.save();
|
|
717
|
-
}
|
|
718
|
-
finally {
|
|
719
|
-
isSavingStatus = false;
|
|
720
|
-
}
|
|
721
|
-
}
|
|
722
|
-
while (true) {
|
|
723
|
-
abort.throwIfAborted();
|
|
724
|
-
const data = await SQL.select()
|
|
725
|
-
.from('email_recipients')
|
|
726
|
-
.where('emailId', upToDate.id)
|
|
727
|
-
.where('id', SQLWhereSign.Greater, idPointer)
|
|
728
|
-
.orderBy(SQL.column('id'), 'ASC')
|
|
729
|
-
.limit(batchSize)
|
|
730
|
-
.fetch();
|
|
731
|
-
const recipients = EmailRecipient.fromRows(data, 'email_recipients');
|
|
732
|
-
if (recipients.length === 0) {
|
|
733
|
-
break;
|
|
734
|
-
}
|
|
735
|
-
const sendingPromises = [];
|
|
736
|
-
let skipped = 0;
|
|
737
|
-
for (const recipient of recipients) {
|
|
738
|
-
idPointer = recipient.id;
|
|
739
|
-
if (recipient.sentAt) {
|
|
740
|
-
succeededCount += 1;
|
|
741
|
-
await saveStatus();
|
|
742
|
-
skipped++;
|
|
743
|
-
continue;
|
|
744
|
-
}
|
|
745
|
-
if (!recipient.email) {
|
|
746
|
-
skipped++;
|
|
747
|
-
continue;
|
|
748
|
-
}
|
|
749
|
-
if (recipient.duplicateOfRecipientId) {
|
|
750
|
-
skipped++;
|
|
751
|
-
continue;
|
|
752
|
-
}
|
|
753
|
-
if (singleRecipientId) {
|
|
754
|
-
if (recipient.id !== singleRecipientId) {
|
|
755
|
-
// Failed or soft-failed
|
|
756
|
-
if (recipient.failError && isSoftEmailRecipientError(recipient.failError)) {
|
|
757
|
-
softFailedCount += 1;
|
|
758
|
-
}
|
|
759
|
-
else {
|
|
760
|
-
failedCount += 1;
|
|
761
|
-
}
|
|
762
|
-
skipped++;
|
|
763
|
-
await saveStatus();
|
|
764
|
-
continue;
|
|
765
|
-
}
|
|
766
|
-
}
|
|
767
|
-
const promise = upToDate.sendSingleRecipient(recipient, organization ?? null, {
|
|
768
|
-
from,
|
|
769
|
-
replyTo,
|
|
770
|
-
attachments,
|
|
771
|
-
});
|
|
772
|
-
sendingPromises.push(promise.then(async () => {
|
|
773
|
-
if (recipient.sentAt) {
|
|
774
|
-
succeededCount += 1;
|
|
775
|
-
await saveStatus();
|
|
776
|
-
}
|
|
777
|
-
else {
|
|
778
|
-
// Failed or soft-failed
|
|
779
|
-
if (recipient.failError && isSoftEmailRecipientError(recipient.failError)) {
|
|
780
|
-
softFailedCount += 1;
|
|
781
|
-
}
|
|
782
|
-
else {
|
|
783
|
-
failedCount += 1;
|
|
784
|
-
}
|
|
785
|
-
await saveStatus();
|
|
786
|
-
}
|
|
787
|
-
}));
|
|
788
|
-
}
|
|
789
|
-
if (sendingPromises.length > 0 || skipped > 0) {
|
|
790
|
-
await Promise.all(sendingPromises);
|
|
791
|
-
}
|
|
792
|
-
else {
|
|
793
|
-
break;
|
|
794
|
-
}
|
|
795
|
-
}
|
|
796
|
-
}
|
|
797
|
-
}
|
|
798
|
-
catch (e) {
|
|
799
|
-
if (!upToDate) {
|
|
800
|
-
throw e;
|
|
801
|
-
}
|
|
802
|
-
if (!singleRecipientId) {
|
|
803
|
-
upToDate.succeededCount = succeededCount;
|
|
804
|
-
upToDate.softFailedCount = softFailedCount;
|
|
805
|
-
upToDate.failedCount = failedCount;
|
|
806
|
-
if (isAbortedError(e) || ((isSimpleError(e) || isSimpleErrors(e)) && e.hasCode('SHUTDOWN'))) {
|
|
807
|
-
// Keep sending status: we'll resume after the reboot
|
|
808
|
-
await upToDate.save();
|
|
809
|
-
throw e;
|
|
810
|
-
}
|
|
811
|
-
upToDate.emailErrors = errorToSimpleErrors(e);
|
|
812
|
-
upToDate.status = EmailStatus.Failed;
|
|
813
|
-
await upToDate.save();
|
|
814
|
-
}
|
|
815
|
-
throw e;
|
|
816
|
-
}
|
|
817
|
-
if (!singleRecipientId) {
|
|
818
|
-
if (upToDate.sendAsEmail && upToDate.emailRecipientsCount === 0 && upToDate.userId === null) {
|
|
819
|
-
// We only delete automated emails (email type) if they have no recipients
|
|
820
|
-
console.log('No recipients found for email ', upToDate.id, ' deleting...');
|
|
821
|
-
await upToDate.delete();
|
|
822
|
-
return null;
|
|
823
|
-
}
|
|
824
|
-
console.log('Finished sending email', upToDate.id);
|
|
825
|
-
// Mark email as sent
|
|
826
|
-
if (upToDate.sendAsEmail && !upToDate.showInMemberPortal && (succeededCount + failedCount + softFailedCount) === 0) {
|
|
827
|
-
upToDate.status = EmailStatus.Failed;
|
|
828
|
-
upToDate.emailErrors = new SimpleErrors(new SimpleError({
|
|
829
|
-
code: 'no_recipients',
|
|
830
|
-
message: 'No recipients',
|
|
831
|
-
human: $t(`%1EG`),
|
|
832
|
-
}));
|
|
833
|
-
}
|
|
834
|
-
else {
|
|
835
|
-
upToDate.status = EmailStatus.Sent;
|
|
836
|
-
upToDate.emailErrors = null;
|
|
837
|
-
}
|
|
838
|
-
}
|
|
839
|
-
upToDate.succeededCount = succeededCount;
|
|
840
|
-
upToDate.softFailedCount = softFailedCount;
|
|
841
|
-
upToDate.failedCount = failedCount;
|
|
842
|
-
await upToDate.save();
|
|
843
|
-
return upToDate;
|
|
844
|
-
});
|
|
845
|
-
});
|
|
846
|
-
}
|
|
847
428
|
async updateCount() {
|
|
848
429
|
// First reset
|
|
849
430
|
const id = this.id;
|
|
@@ -926,210 +507,6 @@ export class Email extends QueryableModel {
|
|
|
926
507
|
getLanguages() {
|
|
927
508
|
return this.language ? [this.language, ...this.translations.keys()] : null;
|
|
928
509
|
}
|
|
929
|
-
async buildRecipients() {
|
|
930
|
-
const id = this.id;
|
|
931
|
-
await QueueHandler.schedule('email-build-recipients-' + this.id, async function ({ abort }) {
|
|
932
|
-
const upToDate = await Email.getByID(id);
|
|
933
|
-
if (!upToDate || !upToDate.id) {
|
|
934
|
-
return;
|
|
935
|
-
}
|
|
936
|
-
if (upToDate.recipientsStatus === EmailRecipientsStatus.Created) {
|
|
937
|
-
return;
|
|
938
|
-
}
|
|
939
|
-
if (upToDate.status === EmailStatus.Sent) {
|
|
940
|
-
return;
|
|
941
|
-
}
|
|
942
|
-
abort.throwIfAborted();
|
|
943
|
-
const organization = upToDate.organizationId ? (await Organization.getByID(upToDate.organizationId) ?? null) : null;
|
|
944
|
-
if (upToDate.organizationId && !organization) {
|
|
945
|
-
throw new SimpleError({
|
|
946
|
-
code: 'organization_not_found',
|
|
947
|
-
message: 'Organization not found',
|
|
948
|
-
human: $t(`%1NV`),
|
|
949
|
-
});
|
|
950
|
-
}
|
|
951
|
-
const platform = await Platform.getSharedPrivateStruct();
|
|
952
|
-
console.log('Building recipients for email', id);
|
|
953
|
-
// If it is already creating -> something went wrong (e.g. server restart) and we can safely try again
|
|
954
|
-
upToDate.recipientsStatus = EmailRecipientsStatus.Creating;
|
|
955
|
-
await upToDate.save();
|
|
956
|
-
const membersSet = new Set();
|
|
957
|
-
const emailsSet = new Set();
|
|
958
|
-
const combinedHtml = upToDate.getCombinedHtml();
|
|
959
|
-
let count = 0;
|
|
960
|
-
let countWithoutEmail = 0;
|
|
961
|
-
try {
|
|
962
|
-
// Delete all recipients
|
|
963
|
-
await SQL
|
|
964
|
-
.delete()
|
|
965
|
-
.from(SQL.table('email_recipients'))
|
|
966
|
-
.where(SQL.column('emailId'), upToDate.id);
|
|
967
|
-
abort.throwIfAborted();
|
|
968
|
-
for (const subfilter of upToDate.recipientFilter.filters) {
|
|
969
|
-
// Create recipients
|
|
970
|
-
const loader = Email.recipientLoaders.get(subfilter.type);
|
|
971
|
-
if (!loader) {
|
|
972
|
-
throw new Error('Loader for type ' + subfilter.type + ' has not been initialised on the Email model');
|
|
973
|
-
}
|
|
974
|
-
let request = new LimitedFilteredRequest({
|
|
975
|
-
filter: subfilter.filter,
|
|
976
|
-
sort: [{ key: 'id', order: SortItemDirection.ASC }],
|
|
977
|
-
limit: 100,
|
|
978
|
-
search: subfilter.search,
|
|
979
|
-
});
|
|
980
|
-
const beforeFetchAllResult = loader.beforeFetchAll ? await loader.beforeFetchAll(request, subfilter.subfilter) : undefined;
|
|
981
|
-
while (request) {
|
|
982
|
-
abort.throwIfAborted();
|
|
983
|
-
const response = await loader.fetch(request, subfilter.subfilter, beforeFetchAllResult, { allowedLanguages: upToDate.getLanguages() });
|
|
984
|
-
for (const item of response.results) {
|
|
985
|
-
if (!item.email && !item.memberId && !item.userId) {
|
|
986
|
-
continue;
|
|
987
|
-
}
|
|
988
|
-
const recipient = new EmailRecipient();
|
|
989
|
-
recipient.emailType = upToDate.emailType;
|
|
990
|
-
recipient.objectId = item.objectId;
|
|
991
|
-
recipient.emailId = upToDate.id;
|
|
992
|
-
recipient.email = item.email;
|
|
993
|
-
recipient.firstName = item.firstName;
|
|
994
|
-
recipient.lastName = item.lastName;
|
|
995
|
-
recipient.language = item.language ?? null;
|
|
996
|
-
recipient.replacements = item.replacements;
|
|
997
|
-
recipient.memberId = item.memberId ?? null;
|
|
998
|
-
recipient.userId = item.userId ?? null;
|
|
999
|
-
recipient.organizationId = upToDate.organizationId ?? null;
|
|
1000
|
-
await fillRecipientReplacements(recipient, {
|
|
1001
|
-
platform,
|
|
1002
|
-
organization,
|
|
1003
|
-
from: upToDate.getFromAddress(),
|
|
1004
|
-
replyTo: null,
|
|
1005
|
-
forPreview: false,
|
|
1006
|
-
allowedLanguages: upToDate.getLanguages(),
|
|
1007
|
-
});
|
|
1008
|
-
recipient.replacements = removeUnusedReplacements(combinedHtml, recipient.replacements);
|
|
1009
|
-
let duplicateOfRecipientId = null;
|
|
1010
|
-
if (item.email && emailsSet.has(item.email)) {
|
|
1011
|
-
console.log('Found duplicate email recipient', item.email);
|
|
1012
|
-
// Try to merge
|
|
1013
|
-
const existing = await EmailRecipient.select()
|
|
1014
|
-
.where('emailId', upToDate.id)
|
|
1015
|
-
.where('email', item.email)
|
|
1016
|
-
.where('duplicateOfRecipientId', null)
|
|
1017
|
-
.fetch();
|
|
1018
|
-
for (const other of existing) {
|
|
1019
|
-
const merged = mergeReplacementsIfEqual(other.replacements, recipient.replacements);
|
|
1020
|
-
if (merged !== false) {
|
|
1021
|
-
console.log('Found mergeable duplicate email recipient', item.email, other.id);
|
|
1022
|
-
duplicateOfRecipientId = other.id;
|
|
1023
|
-
other.replacements = merged;
|
|
1024
|
-
other.firstName = other.firstName || item.firstName;
|
|
1025
|
-
other.lastName = other.lastName || item.lastName;
|
|
1026
|
-
await other.save();
|
|
1027
|
-
recipient.replacements = merged;
|
|
1028
|
-
break;
|
|
1029
|
-
}
|
|
1030
|
-
else {
|
|
1031
|
-
console.log('Could not merge duplicate email recipient', item.email, other.id, 'keeping both', other.replacements, item.replacements);
|
|
1032
|
-
}
|
|
1033
|
-
}
|
|
1034
|
-
}
|
|
1035
|
-
recipient.duplicateOfRecipientId = duplicateOfRecipientId;
|
|
1036
|
-
await recipient.save();
|
|
1037
|
-
if (recipient.memberId) {
|
|
1038
|
-
membersSet.add(recipient.memberId);
|
|
1039
|
-
}
|
|
1040
|
-
if (recipient.email) {
|
|
1041
|
-
emailsSet.add(recipient.email);
|
|
1042
|
-
}
|
|
1043
|
-
if (!recipient.email || duplicateOfRecipientId) {
|
|
1044
|
-
countWithoutEmail += 1;
|
|
1045
|
-
}
|
|
1046
|
-
else {
|
|
1047
|
-
count += 1;
|
|
1048
|
-
}
|
|
1049
|
-
}
|
|
1050
|
-
request = response.next ?? null;
|
|
1051
|
-
}
|
|
1052
|
-
}
|
|
1053
|
-
upToDate.recipientsStatus = EmailRecipientsStatus.Created;
|
|
1054
|
-
upToDate.emailRecipientsCount = count;
|
|
1055
|
-
upToDate.otherRecipientsCount = countWithoutEmail;
|
|
1056
|
-
upToDate.recipientsErrors = null;
|
|
1057
|
-
upToDate.membersCount = membersSet.size;
|
|
1058
|
-
await upToDate.save();
|
|
1059
|
-
}
|
|
1060
|
-
catch (e) {
|
|
1061
|
-
console.error('Failed to build recipients for email', id);
|
|
1062
|
-
console.error(e);
|
|
1063
|
-
upToDate.recipientsStatus = EmailRecipientsStatus.NotCreated;
|
|
1064
|
-
upToDate.recipientsErrors = errorToSimpleErrors(e);
|
|
1065
|
-
await upToDate.save();
|
|
1066
|
-
}
|
|
1067
|
-
});
|
|
1068
|
-
}
|
|
1069
|
-
async buildExampleRecipient(isNewlyCreated = false) {
|
|
1070
|
-
const id = this.id;
|
|
1071
|
-
await QueueHandler.schedule('email-build-recipients-' + this.id, async function () {
|
|
1072
|
-
const upToDate = await Email.getByID(id);
|
|
1073
|
-
if (!upToDate || upToDate.sentAt || !upToDate.id) {
|
|
1074
|
-
return;
|
|
1075
|
-
}
|
|
1076
|
-
if (upToDate.recipientsStatus !== EmailRecipientsStatus.NotCreated) {
|
|
1077
|
-
return;
|
|
1078
|
-
}
|
|
1079
|
-
try {
|
|
1080
|
-
// Delete all recipients
|
|
1081
|
-
if (!isNewlyCreated) {
|
|
1082
|
-
await SQL
|
|
1083
|
-
.delete()
|
|
1084
|
-
.from(SQL.table('email_recipients'))
|
|
1085
|
-
.where(SQL.column('emailId'), upToDate.id);
|
|
1086
|
-
}
|
|
1087
|
-
for (const subfilter of upToDate.recipientFilter.filters) {
|
|
1088
|
-
// Create recipients
|
|
1089
|
-
const loader = Email.recipientLoaders.get(subfilter.type);
|
|
1090
|
-
if (!loader) {
|
|
1091
|
-
throw new Error('Loader for type ' + subfilter.type + ' has not been initialised on the Email model');
|
|
1092
|
-
}
|
|
1093
|
-
let request = new LimitedFilteredRequest({
|
|
1094
|
-
filter: subfilter.filter,
|
|
1095
|
-
sort: [{ key: 'id', order: SortItemDirection.ASC }],
|
|
1096
|
-
limit: 10,
|
|
1097
|
-
search: subfilter.search,
|
|
1098
|
-
});
|
|
1099
|
-
const beforeFetchAllResult = loader.beforeFetchAll ? await loader.beforeFetchAll(request, subfilter.subfilter) : undefined;
|
|
1100
|
-
while (request) {
|
|
1101
|
-
const response = await loader.fetch(request, subfilter.subfilter, beforeFetchAllResult, { allowedLanguages: upToDate.getLanguages() });
|
|
1102
|
-
// Note: it is possible that a result in the database doesn't return a recipient (in memory filtering)
|
|
1103
|
-
// so we do need pagination
|
|
1104
|
-
for (const item of response.results) {
|
|
1105
|
-
const recipient = new EmailRecipient();
|
|
1106
|
-
recipient.emailType = upToDate.emailType;
|
|
1107
|
-
recipient.emailId = upToDate.id;
|
|
1108
|
-
recipient.objectId = item.objectId;
|
|
1109
|
-
recipient.email = item.email;
|
|
1110
|
-
recipient.firstName = item.firstName;
|
|
1111
|
-
recipient.lastName = item.lastName;
|
|
1112
|
-
recipient.language = item.language ?? null;
|
|
1113
|
-
recipient.replacements = item.replacements;
|
|
1114
|
-
recipient.memberId = item.memberId ?? null;
|
|
1115
|
-
recipient.userId = item.userId ?? null;
|
|
1116
|
-
recipient.organizationId = upToDate.organizationId ?? null;
|
|
1117
|
-
await recipient.save();
|
|
1118
|
-
if (recipient.email || recipient.userId) {
|
|
1119
|
-
return;
|
|
1120
|
-
}
|
|
1121
|
-
}
|
|
1122
|
-
request = null;
|
|
1123
|
-
}
|
|
1124
|
-
}
|
|
1125
|
-
console.warn('No example recipient found for email', id);
|
|
1126
|
-
}
|
|
1127
|
-
catch (e) {
|
|
1128
|
-
console.error('Failed to build example recipient for email', id);
|
|
1129
|
-
console.error(e);
|
|
1130
|
-
}
|
|
1131
|
-
});
|
|
1132
|
-
}
|
|
1133
510
|
getStructure() {
|
|
1134
511
|
return EmailStruct.create(this);
|
|
1135
512
|
}
|
|
@@ -1157,202 +534,6 @@ export class Email extends QueryableModel {
|
|
|
1157
534
|
}
|
|
1158
535
|
return [...languages].filter(language => new I18n(language, country).language === language);
|
|
1159
536
|
}
|
|
1160
|
-
/**
|
|
1161
|
-
* @param options.allLanguages Also fill exampleRecipients: the same recipient with its
|
|
1162
|
-
* replacements generated in each supported language. Only use this for detail endpoints,
|
|
1163
|
-
* it repeats the replacement queries for every language.
|
|
1164
|
-
*/
|
|
1165
|
-
async getPreviewStructure(options = {}) {
|
|
1166
|
-
const emailRecipient = await EmailRecipient.select()
|
|
1167
|
-
.where('emailId', this.id)
|
|
1168
|
-
.where('email', '!=', null)
|
|
1169
|
-
.first(false);
|
|
1170
|
-
let baseRow;
|
|
1171
|
-
if (emailRecipient) {
|
|
1172
|
-
baseRow = await emailRecipient.getStructure();
|
|
1173
|
-
}
|
|
1174
|
-
if (!baseRow) {
|
|
1175
|
-
baseRow = getExampleRecipient();
|
|
1176
|
-
}
|
|
1177
|
-
const organization = this.organizationId ? (await Organization.getByID(this.organizationId)) : null;
|
|
1178
|
-
const allowedLanguages = this.getLanguages();
|
|
1179
|
-
const fillRow = async (row) => {
|
|
1180
|
-
const virtualRecipient = row.getRecipient();
|
|
1181
|
-
await fillRecipientReplacements(virtualRecipient, {
|
|
1182
|
-
organization,
|
|
1183
|
-
from: this.getFromAddress(),
|
|
1184
|
-
replyTo: null,
|
|
1185
|
-
forPreview: true,
|
|
1186
|
-
forceRefresh: !this.sentAt,
|
|
1187
|
-
allowedLanguages,
|
|
1188
|
-
});
|
|
1189
|
-
row.replacements = virtualRecipient.replacements;
|
|
1190
|
-
return row;
|
|
1191
|
-
};
|
|
1192
|
-
const recipientRow = await fillRow(baseRow.clone());
|
|
1193
|
-
// The same recipient in every supported language: the replacements are regenerated in
|
|
1194
|
-
// each language (the recipient's own language is ignored), so the composer can show
|
|
1195
|
-
// example values in the language that is being edited
|
|
1196
|
-
const exampleRecipients = new Map();
|
|
1197
|
-
if (allowedLanguages && allowedLanguages.length > 1) {
|
|
1198
|
-
// The same country the recipient locale will resolve to (see getRecipientI18n)
|
|
1199
|
-
const country = organization?.address?.country ?? $getCountry();
|
|
1200
|
-
for (const language of allowedLanguages) {
|
|
1201
|
-
const i18n = new I18n(language, country);
|
|
1202
|
-
await I18n.runWithLocale(i18n, async () => {
|
|
1203
|
-
const clone = baseRow.clone();
|
|
1204
|
-
clone.language = language;
|
|
1205
|
-
if (baseRow.language !== language) {
|
|
1206
|
-
// Todo: this can be improved
|
|
1207
|
-
// Replace all replacements with defaults
|
|
1208
|
-
for (const replacement of clone.replacements) {
|
|
1209
|
-
const example = ExampleReplacements.all[replacement.token];
|
|
1210
|
-
if (example) {
|
|
1211
|
-
replacement.html = example.html;
|
|
1212
|
-
replacement.value = example.value;
|
|
1213
|
-
}
|
|
1214
|
-
}
|
|
1215
|
-
clone.replacements = clone.replacements.filter(r => !['organizationName'].includes(r.token));
|
|
1216
|
-
}
|
|
1217
|
-
const rr = await fillRow(clone);
|
|
1218
|
-
exampleRecipients.set(language, rr);
|
|
1219
|
-
});
|
|
1220
|
-
}
|
|
1221
|
-
}
|
|
1222
|
-
let user = null;
|
|
1223
|
-
if (this.userId) {
|
|
1224
|
-
const u = await User.getByID(this.userId);
|
|
1225
|
-
if (u) {
|
|
1226
|
-
user = u.getStructure();
|
|
1227
|
-
}
|
|
1228
|
-
}
|
|
1229
|
-
let organizationStruct = null;
|
|
1230
|
-
if (organization) {
|
|
1231
|
-
organizationStruct = organization.getBaseStructure();
|
|
1232
|
-
}
|
|
1233
|
-
return EmailPreview.create({
|
|
1234
|
-
...this,
|
|
1235
|
-
user,
|
|
1236
|
-
organization: organizationStruct,
|
|
1237
|
-
exampleRecipient: recipientRow,
|
|
1238
|
-
exampleRecipients,
|
|
1239
|
-
});
|
|
1240
|
-
}
|
|
1241
|
-
/**
|
|
1242
|
-
* Whether the email has content in this language (strict: the default content only counts
|
|
1243
|
-
* for its own language, see getEmailContentForLanguage)
|
|
1244
|
-
*/
|
|
1245
|
-
hasContentForLanguage(language) {
|
|
1246
|
-
return language === this.language || this.translations.has(language);
|
|
1247
|
-
}
|
|
1248
|
-
/**
|
|
1249
|
-
* @param options.language The language the caller is viewing in (from the request headers).
|
|
1250
|
-
* Recipients are returned in this language when the email has content for it, otherwise in
|
|
1251
|
-
* the language they received the email in.
|
|
1252
|
-
*/
|
|
1253
|
-
async getStructureForUser(user, memberIds, options = {}) {
|
|
1254
|
-
const emailRecipients = await EmailRecipient.select()
|
|
1255
|
-
.where('emailId', this.id)
|
|
1256
|
-
.where('memberId', memberIds)
|
|
1257
|
-
.fetch();
|
|
1258
|
-
const organization = this.organizationId ? (await Organization.getByID(this.organizationId)) : null;
|
|
1259
|
-
const recipientsMap = new Map();
|
|
1260
|
-
for (const memberId of memberIds) {
|
|
1261
|
-
const preferred = emailRecipients.find(e => e.memberId === memberId && (e.userId === user.id || e.email === user.email));
|
|
1262
|
-
if (preferred) {
|
|
1263
|
-
recipientsMap.set(preferred.duplicateOfRecipientId ?? preferred.id, preferred);
|
|
1264
|
-
continue;
|
|
1265
|
-
}
|
|
1266
|
-
const byMember = emailRecipients.find(e => e.memberId === memberId && e.userId === null && e.email === null);
|
|
1267
|
-
if (byMember) {
|
|
1268
|
-
recipientsMap.set(byMember.duplicateOfRecipientId ?? byMember.id, byMember);
|
|
1269
|
-
continue;
|
|
1270
|
-
}
|
|
1271
|
-
const anyData = emailRecipients.find(e => e.memberId === memberId);
|
|
1272
|
-
if (anyData) {
|
|
1273
|
-
recipientsMap.set(anyData.duplicateOfRecipientId ?? anyData.id, anyData);
|
|
1274
|
-
continue;
|
|
1275
|
-
}
|
|
1276
|
-
}
|
|
1277
|
-
// Remove duplicates that are marked as the same recipient
|
|
1278
|
-
const cleanedRecipients = [...recipientsMap.values()];
|
|
1279
|
-
const structures = await EmailRecipient.getStructures(cleanedRecipients);
|
|
1280
|
-
for (const struct of structures) {
|
|
1281
|
-
if (!(struct.userId === user.id || struct.email === user.email) && !((struct.userId === null && struct.email === null))) {
|
|
1282
|
-
stripSensitiveRecipientReplacements(struct, {
|
|
1283
|
-
organization,
|
|
1284
|
-
willFill: true,
|
|
1285
|
-
});
|
|
1286
|
-
}
|
|
1287
|
-
struct.firstName = user.firstName;
|
|
1288
|
-
struct.lastName = user.lastName;
|
|
1289
|
-
struct.email = user.email;
|
|
1290
|
-
struct.userId = user.id;
|
|
1291
|
-
// Show the email in the language the caller is viewing in, but only when the email
|
|
1292
|
-
// has content for it: otherwise keep the language the recipient received it in
|
|
1293
|
-
// (better correct content in the wrong language than wrong content in the right language)
|
|
1294
|
-
if (options.language && this.hasContentForLanguage(options.language)) {
|
|
1295
|
-
struct.language = options.language;
|
|
1296
|
-
}
|
|
1297
|
-
// We always refresh the data when we display it on the web (so everything is up to date)
|
|
1298
|
-
// The replacements are regenerated in struct.language, so they match the displayed content
|
|
1299
|
-
await fillRecipientReplacements(struct, {
|
|
1300
|
-
organization,
|
|
1301
|
-
from: this.getFromAddress(),
|
|
1302
|
-
replyTo: null,
|
|
1303
|
-
forPreview: false,
|
|
1304
|
-
forceRefresh: true,
|
|
1305
|
-
allowedLanguages: this.getLanguages(),
|
|
1306
|
-
});
|
|
1307
|
-
runWithRecipientLocale(struct, organization, () => {
|
|
1308
|
-
stripRecipientReplacementsForWebDisplay(struct, {
|
|
1309
|
-
organization,
|
|
1310
|
-
});
|
|
1311
|
-
});
|
|
1312
|
-
if (this.html) {
|
|
1313
|
-
struct.replacements = removeUnusedReplacements(this.getCombinedHtml(), struct.replacements);
|
|
1314
|
-
}
|
|
1315
|
-
}
|
|
1316
|
-
// Loop structures and remove if they have exactly the same content
|
|
1317
|
-
// We do this here, because it is possible the user didn't receive any emails, so
|
|
1318
|
-
// the merging at time of sending the emails didn't happen (uniqueness happened on email)
|
|
1319
|
-
const uniqueStructures = [];
|
|
1320
|
-
for (const struct of structures) {
|
|
1321
|
-
let found = false;
|
|
1322
|
-
for (const unique of uniqueStructures) {
|
|
1323
|
-
const merged = mergeReplacementsIfEqual(unique.replacements, struct.replacements);
|
|
1324
|
-
if (merged !== false) {
|
|
1325
|
-
unique.replacements = merged;
|
|
1326
|
-
found = true;
|
|
1327
|
-
break;
|
|
1328
|
-
}
|
|
1329
|
-
}
|
|
1330
|
-
if (!found) {
|
|
1331
|
-
uniqueStructures.push(struct);
|
|
1332
|
-
}
|
|
1333
|
-
}
|
|
1334
|
-
let organizationStruct = null;
|
|
1335
|
-
if (organization) {
|
|
1336
|
-
organizationStruct = organization.getBaseStructure();
|
|
1337
|
-
}
|
|
1338
|
-
return EmailWithRecipients.create({
|
|
1339
|
-
...this,
|
|
1340
|
-
organization: organizationStruct,
|
|
1341
|
-
recipients: uniqueStructures,
|
|
1342
|
-
// Remove private-like data
|
|
1343
|
-
softBouncesCount: 0,
|
|
1344
|
-
failedCount: 0,
|
|
1345
|
-
emailErrors: null,
|
|
1346
|
-
recipientsErrors: null,
|
|
1347
|
-
succeededCount: 1,
|
|
1348
|
-
emailRecipientsCount: 1,
|
|
1349
|
-
hardBouncesCount: 0,
|
|
1350
|
-
spamComplaintsCount: 0,
|
|
1351
|
-
recipientFilter: EmailRecipientFilter.create({}),
|
|
1352
|
-
membersCount: 1,
|
|
1353
|
-
otherRecipientsCount: 0,
|
|
1354
|
-
});
|
|
1355
|
-
}
|
|
1356
537
|
}
|
|
1357
538
|
__decorate([
|
|
1358
539
|
column({
|