@stamhoofd/models 2.135.0 → 2.136.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/factories/EmailTemplateFactory.d.ts +4 -1
- package/dist/factories/EmailTemplateFactory.d.ts.map +1 -1
- package/dist/factories/EmailTemplateFactory.js +8 -0
- package/dist/factories/EmailTemplateFactory.js.map +1 -1
- package/dist/helpers/EmailBuilder.d.ts +34 -1
- package/dist/helpers/EmailBuilder.d.ts.map +1 -1
- package/dist/helpers/EmailBuilder.js +191 -133
- package/dist/helpers/EmailBuilder.js.map +1 -1
- package/dist/migrations/1783987708-email-templates-translations.sql +2 -0
- package/dist/migrations/1783987709-emails-translations.sql +2 -0
- package/dist/migrations/1783987710-email-recipients-language.sql +2 -0
- package/dist/migrations/1784037917-email-templates-language.sql +2 -0
- package/dist/migrations/1784037918-emails-language.sql +2 -0
- package/dist/models/CachedBalance.d.ts +11 -0
- package/dist/models/CachedBalance.d.ts.map +1 -1
- package/dist/models/CachedBalance.js +49 -1
- package/dist/models/CachedBalance.js.map +1 -1
- package/dist/models/Email.d.ts +46 -4
- package/dist/models/Email.d.ts.map +1 -1
- package/dist/models/Email.js +165 -24
- package/dist/models/Email.js.map +1 -1
- package/dist/models/EmailRecipient.d.ts +5 -0
- package/dist/models/EmailRecipient.d.ts.map +1 -1
- package/dist/models/EmailRecipient.js +7 -0
- package/dist/models/EmailRecipient.js.map +1 -1
- package/dist/models/EmailTemplate.d.ts +6 -1
- package/dist/models/EmailTemplate.d.ts.map +1 -1
- package/dist/models/EmailTemplate.js +13 -2
- package/dist/models/EmailTemplate.js.map +1 -1
- package/dist/models/Member.d.ts.map +1 -1
- package/dist/models/Member.js +6 -1
- package/dist/models/Member.js.map +1 -1
- package/dist/models/Order.d.ts.map +1 -1
- package/dist/models/Order.js +1 -0
- package/dist/models/Order.js.map +1 -1
- package/package.json +4 -3
- package/src/factories/EmailTemplateFactory.ts +12 -1
- package/src/helpers/EmailBuilder.test.ts +246 -0
- package/src/helpers/EmailBuilder.ts +215 -144
- package/src/migrations/1783987708-email-templates-translations.sql +2 -0
- package/src/migrations/1783987709-emails-translations.sql +2 -0
- package/src/migrations/1783987710-email-recipients-language.sql +2 -0
- package/src/migrations/1784037917-email-templates-language.sql +2 -0
- package/src/migrations/1784037918-emails-language.sql +2 -0
- package/src/models/CachedBalance.ts +57 -1
- package/src/models/Email.ts +181 -26
- package/src/models/EmailRecipient.ts +7 -0
- package/src/models/EmailTemplate.ts +12 -2
- package/src/models/Member.ts +8 -1
- package/src/models/Order.ts +1 -0
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import type { EmailBuilder, EmailInterfaceRecipient } from '@stamhoofd/email';
|
|
2
2
|
import { Email, EmailAddress } from '@stamhoofd/email';
|
|
3
|
-
import type { EmailRecipient as EmailRecipientStruct, EmailTemplateType, OrganizationEmail, Platform as PlatformStruct, Recipient } from '@stamhoofd/structures';
|
|
3
|
+
import type { EmailContent, EmailRecipient as EmailRecipientStruct, EmailTemplateType, OrganizationEmail, Platform as PlatformStruct, Recipient } from '@stamhoofd/structures';
|
|
4
4
|
import { BalanceItem as BalanceItemStruct, getAppHost, ReceivableBalanceType, replaceEmailHtml, replaceEmailText, Replacement } from '@stamhoofd/structures';
|
|
5
|
+
import type { Language } from '@stamhoofd/types/Language';
|
|
5
6
|
import { Formatter } from '@stamhoofd/utility';
|
|
6
7
|
|
|
7
8
|
import { SimpleError } from '@simonbackx/simple-errors';
|
|
@@ -228,6 +229,7 @@ async function getEmailBuilderForTemplate(organization: Organization | null, opt
|
|
|
228
229
|
...options,
|
|
229
230
|
subject: template.subject,
|
|
230
231
|
html: template.html,
|
|
232
|
+
translations: template.translations,
|
|
231
233
|
});
|
|
232
234
|
}
|
|
233
235
|
|
|
@@ -238,6 +240,12 @@ export type EmailBuilderOptions = {
|
|
|
238
240
|
replyTo?: EmailInterfaceRecipient | null;
|
|
239
241
|
subject: string;
|
|
240
242
|
html: string;
|
|
243
|
+
|
|
244
|
+
/**
|
|
245
|
+
* Full content overrides per language. Recipients with a language that has an override
|
|
246
|
+
* receive that content, all others receive the default subject/html.
|
|
247
|
+
*/
|
|
248
|
+
translations?: Map<Language, EmailContent>;
|
|
241
249
|
attachments?: { filename: string; path?: string; href?: string; content?: string | Buffer; contentType?: string; encoding?: string }[];
|
|
242
250
|
type?: 'transactional' | 'broadcast';
|
|
243
251
|
unsubscribeType?: 'all' | 'marketing';
|
|
@@ -301,7 +309,9 @@ export async function getEmailBuilder(organization: Organization | null, email:
|
|
|
301
309
|
continue;
|
|
302
310
|
}
|
|
303
311
|
|
|
304
|
-
|
|
312
|
+
// Localize the unsubscribe page to the recipient's language (Organization.i18n is always Dutch)
|
|
313
|
+
const unsubscribeLocale = organization ? getRecipientI18n(recipient, organization).locale : null;
|
|
314
|
+
const unsubscribeUrl = 'https://' + STAMHOOFD.domains.dashboard + '/' + (unsubscribeLocale ? (unsubscribeLocale + '/') : '') + 'unsubscribe?id=' + encodeURIComponent(unsubscribe.id) + '&token=' + encodeURIComponent(unsubscribe.token) + '&type=' + encodeURIComponent(email.unsubscribeType ?? 'all');
|
|
305
315
|
recipient.replacements.push(Replacement.create({
|
|
306
316
|
token: 'unsubscribeUrl',
|
|
307
317
|
value: unsubscribeUrl,
|
|
@@ -340,9 +350,28 @@ export async function getEmailBuilder(organization: Organization | null, email:
|
|
|
340
350
|
|
|
341
351
|
let emailIndex = 0;
|
|
342
352
|
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
353
|
+
// The subject and html can differ per recipient language
|
|
354
|
+
const contentCache = new Map<Language | null, { subject: string; html: string }>();
|
|
355
|
+
const resolveContent = (language: Language | null) => {
|
|
356
|
+
const cached = contentCache.get(language);
|
|
357
|
+
if (cached) {
|
|
358
|
+
return cached;
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
// Strict selection: only use a translation of this email, never fall back to
|
|
362
|
+
// a different template for a missing language (content correctness above language)
|
|
363
|
+
const translation = language !== null ? email.translations?.get(language) : undefined;
|
|
364
|
+
const subject = translation ? translation.subject : email.subject;
|
|
365
|
+
let html = translation ? translation.html : email.html;
|
|
366
|
+
|
|
367
|
+
for (const s of email.replaceAll ?? []) {
|
|
368
|
+
html = html.replaceAll(s.from, s.to);
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
const result = { subject, html };
|
|
372
|
+
contentCache.set(language, result);
|
|
373
|
+
return result;
|
|
374
|
+
};
|
|
346
375
|
|
|
347
376
|
if (queue.length === 0) {
|
|
348
377
|
if (email.callback) {
|
|
@@ -360,8 +389,9 @@ export async function getEmailBuilder(organization: Organization | null, email:
|
|
|
360
389
|
return undefined;
|
|
361
390
|
}
|
|
362
391
|
|
|
363
|
-
const
|
|
364
|
-
const
|
|
392
|
+
const content = resolveContent(recipient.language ?? null);
|
|
393
|
+
const replacedHtml = replaceEmailHtml(content.html, recipient.replacements);
|
|
394
|
+
const replacedSubject = replaceEmailText(content.subject, recipient.replacements);
|
|
365
395
|
|
|
366
396
|
emailIndex += 1;
|
|
367
397
|
|
|
@@ -552,6 +582,40 @@ export function stripRecipientReplacementsForWebDisplay(recipient: Recipient | E
|
|
|
552
582
|
}));
|
|
553
583
|
}
|
|
554
584
|
|
|
585
|
+
/**
|
|
586
|
+
* Build the I18n an email should be rendered in for a specific recipient.
|
|
587
|
+
*
|
|
588
|
+
* Falls back to the current (ambient) locale when the recipient has no language set — so flows
|
|
589
|
+
* that already established a locale (order emails wrapped in I18n.runWithLocale, or the request
|
|
590
|
+
* locale) keep working unchanged.
|
|
591
|
+
*/
|
|
592
|
+
export function getRecipientI18n(recipient: { language?: Language | null }, organization: Organization | null, options?: { allowedLanguages?: Language[] | null }): I18n {
|
|
593
|
+
let lang = recipient.language ?? $getLanguage();
|
|
594
|
+
if (options?.allowedLanguages && options.allowedLanguages.length) {
|
|
595
|
+
if (!options.allowedLanguages.includes(lang)) {
|
|
596
|
+
if (options.allowedLanguages.includes($getLanguage())) {
|
|
597
|
+
lang = $getLanguage();
|
|
598
|
+
} else {
|
|
599
|
+
lang = options.allowedLanguages[0];
|
|
600
|
+
}
|
|
601
|
+
}
|
|
602
|
+
}
|
|
603
|
+
return new I18n(lang, organization?.address.country ?? $getCountry());
|
|
604
|
+
}
|
|
605
|
+
|
|
606
|
+
/**
|
|
607
|
+
* Render everything inside `handler` in the recipient's language: all $t / $getLanguage /
|
|
608
|
+
* $getCountry calls (and therefore every generated replacement) use the recipient's locale.
|
|
609
|
+
*
|
|
610
|
+
* This is the single place that binds "a recipient" to "its language" when generating email
|
|
611
|
+
* content. Generate recipient replacements inside this wrapper so new replacements are localized
|
|
612
|
+
* automatically, and pass the provided i18n to helpers that take an explicit locale (e.g. getAppHost).
|
|
613
|
+
*/
|
|
614
|
+
export function runWithRecipientLocale<T>(recipient: { language?: Language | null }, organization: Organization | null, handler: (i18n: I18n) => T, options?: { allowedLanguages?: Language[] | null }): T {
|
|
615
|
+
const i18n = getRecipientI18n(recipient, organization, options);
|
|
616
|
+
return I18n.runWithLocale(i18n, () => handler(i18n));
|
|
617
|
+
}
|
|
618
|
+
|
|
555
619
|
/**
|
|
556
620
|
* @param options.forPreview if true, it will hide sensitive information in the preview that could leak information to admin users
|
|
557
621
|
*/
|
|
@@ -562,186 +626,193 @@ export async function fillRecipientReplacements(recipient: Recipient | EmailReci
|
|
|
562
626
|
replyTo: EmailInterfaceRecipient | null;
|
|
563
627
|
forPreview?: boolean;
|
|
564
628
|
forceRefresh?: boolean;
|
|
629
|
+
allowedLanguages?: Language[] | null;
|
|
565
630
|
}) {
|
|
566
631
|
if (!options.platform) {
|
|
567
632
|
options.platform = await Platform.getSharedPrivateStruct();
|
|
568
633
|
}
|
|
569
634
|
const { organization, platform, from, replyTo } = options;
|
|
570
|
-
let recipientUser: User | null | undefined = null;
|
|
571
|
-
recipient.replacements = recipient.replacements.slice();
|
|
572
|
-
if (options.forPreview) {
|
|
573
|
-
stripSensitiveRecipientReplacements(recipient, options);
|
|
574
|
-
}
|
|
575
635
|
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
636
|
+
// Render every recipient replacement (greeting, loginDetails, balance table, URLs...) in the
|
|
637
|
+
// recipient's own language, so translated emails are consistent end-to-end. Any replacement
|
|
638
|
+
// added below is localized automatically; helpers with an explicit locale get the same i18n.
|
|
639
|
+
await runWithRecipientLocale(recipient, organization, async (i18n) => {
|
|
640
|
+
let recipientUser: User | null | undefined = null;
|
|
641
|
+
recipient.replacements = recipient.replacements.slice();
|
|
642
|
+
if (options.forPreview) {
|
|
643
|
+
stripSensitiveRecipientReplacements(recipient, options);
|
|
644
|
+
}
|
|
582
645
|
|
|
583
|
-
if (!recipient.
|
|
646
|
+
if (!recipient.email && !recipient.userId) {
|
|
647
|
+
const signInUrl = 'https://' + (organization && STAMHOOFD.userMode === 'organization' ? getAppHost('registration', organization, false, i18n) : STAMHOOFD.domains.dashboard) + '/login';
|
|
584
648
|
recipient.replacements.push(Replacement.create({
|
|
585
|
-
token: '
|
|
586
|
-
value:
|
|
649
|
+
token: 'signInUrl',
|
|
650
|
+
value: signInUrl,
|
|
587
651
|
}));
|
|
588
|
-
|
|
589
|
-
|
|
652
|
+
|
|
653
|
+
if (!recipient.replacements.find(r => r.token === 'loginDetails')) {
|
|
654
|
+
recipient.replacements.push(Replacement.create({
|
|
655
|
+
token: 'loginDetails',
|
|
656
|
+
value: '',
|
|
657
|
+
}));
|
|
658
|
+
}
|
|
659
|
+
} else {
|
|
590
660
|
// Default signInUrl
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
661
|
+
recipientUser = recipient.userId ? await User.select().where('id', recipient.userId).first(false) : await User.getForAuthentication(organization?.id ?? null, recipient.email!, { allowWithoutAccount: true });
|
|
662
|
+
if (STAMHOOFD.userMode !== 'platform' && recipientUser && recipientUser.organizationId && recipientUser.organizationId !== (organization?.id ?? null)) {
|
|
663
|
+
console.warn('User organization does not match current organization, ignoring userId', recipient.userId, recipientUser.organizationId, organization?.id ?? null);
|
|
664
|
+
recipientUser = null;
|
|
665
|
+
}
|
|
596
666
|
|
|
597
|
-
|
|
598
|
-
|
|
667
|
+
let signInUrl: string;
|
|
668
|
+
if (!recipientUser || !recipientUser.hasAccount()) {
|
|
599
669
|
// We can create a special token
|
|
600
|
-
|
|
601
|
-
|
|
670
|
+
if (recipientUser) {
|
|
671
|
+
signInUrl = 'https://' + (organization && STAMHOOFD.userMode === 'organization' ? getAppHost('registration', organization, false, i18n) : STAMHOOFD.domains.dashboard) + '/account-aanmaken?email=' + encodeURIComponent(recipientUser?.email);
|
|
672
|
+
} else {
|
|
673
|
+
signInUrl = 'https://' + (organization && STAMHOOFD.userMode === 'organization' ? getAppHost('registration', organization, false, i18n) : STAMHOOFD.domains.dashboard) + '/account-aanmaken';
|
|
674
|
+
}
|
|
602
675
|
} else {
|
|
603
|
-
signInUrl = 'https://' + (organization && STAMHOOFD.userMode === 'organization' ? getAppHost('registration', organization, false) : STAMHOOFD.domains.dashboard) + '/
|
|
676
|
+
signInUrl = 'https://' + (organization && STAMHOOFD.userMode === 'organization' ? getAppHost('registration', organization, false, i18n) : STAMHOOFD.domains.dashboard) + '/login?email=' + encodeURIComponent(recipientUser.email);
|
|
604
677
|
}
|
|
605
|
-
} else {
|
|
606
|
-
signInUrl = 'https://' + (organization && STAMHOOFD.userMode === 'organization' ? getAppHost('registration', organization, false) : STAMHOOFD.domains.dashboard) + '/login?email=' + encodeURIComponent(recipientUser.email);
|
|
607
|
-
}
|
|
608
678
|
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
679
|
+
recipient.replacements.push(Replacement.create({
|
|
680
|
+
token: 'signInUrl',
|
|
681
|
+
value: signInUrl,
|
|
682
|
+
}));
|
|
683
|
+
}
|
|
614
684
|
|
|
615
|
-
|
|
685
|
+
if (options.forceRefresh) {
|
|
616
686
|
// Remove loginDetails to force refresh
|
|
617
|
-
|
|
618
|
-
|
|
687
|
+
recipient.replacements = recipient.replacements.filter(r => r.token !== 'loginDetails');
|
|
688
|
+
}
|
|
619
689
|
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
690
|
+
if (!recipient.replacements.find(r => r.token === 'loginDetails')) {
|
|
691
|
+
if (recipientUser) {
|
|
692
|
+
const emailEscaped = `<strong>${Formatter.escapeHtml(recipientUser.email)}</strong>`;
|
|
693
|
+
const suffixes: string[] = [];
|
|
694
|
+
const { Member } = await import('../models/Member.js');
|
|
695
|
+
const memberIds = await Member.getMemberIdsForUser(recipientUser);
|
|
696
|
+
const members = await Member.getByIDs(...memberIds);
|
|
697
|
+
if (members.length > 0) {
|
|
698
|
+
for (const member of members) {
|
|
699
|
+
suffixes.push(
|
|
700
|
+
$t('%1EC', {
|
|
701
|
+
firstName: Formatter.escapeHtml(member.firstName),
|
|
702
|
+
securityCode: `<span class="style-inline-code">${Formatter.escapeHtml(options.forPreview ? '••••' : Formatter.spaceString(member.details.securityCode ?? '', 4, '-'))}</span>`,
|
|
703
|
+
}),
|
|
704
|
+
);
|
|
705
|
+
}
|
|
706
|
+
} else {
|
|
707
|
+
console.log('No member found for user', recipientUser.id);
|
|
708
|
+
}
|
|
709
|
+
const suffix = suffixes.length > 0 ? (' ' + suffixes.join(' ')) : '';
|
|
710
|
+
recipient.replacements.push(
|
|
711
|
+
Replacement.create({
|
|
712
|
+
token: 'loginDetails',
|
|
713
|
+
value: '',
|
|
714
|
+
html: recipientUser.hasAccount()
|
|
715
|
+
? `<p class="description"><em>${$t('%1EA', { email: emailEscaped })}${suffix}</em></p>`
|
|
716
|
+
: `<p class="description"><em>${$t('%1EB', { email: emailEscaped })}${suffix}</em></p>`,
|
|
717
|
+
}),
|
|
718
|
+
);
|
|
719
|
+
} else {
|
|
720
|
+
if (recipient.email) {
|
|
721
|
+
const emailEscaped = `<strong>${Formatter.escapeHtml(recipient.email)}</strong>`;
|
|
722
|
+
console.log('No user found for email', recipient.email);
|
|
723
|
+
recipient.replacements.push(
|
|
724
|
+
Replacement.create({
|
|
725
|
+
token: 'loginDetails',
|
|
726
|
+
value: '',
|
|
727
|
+
html: `<p class="description"><em>${$t('%1EB', { email: emailEscaped })}</em></p>`,
|
|
728
|
+
}),
|
|
729
|
+
);
|
|
730
|
+
} else {
|
|
731
|
+
recipient.replacements.push(
|
|
732
|
+
Replacement.create({
|
|
733
|
+
token: 'loginDetails',
|
|
734
|
+
value: '',
|
|
735
|
+
html: '',
|
|
633
736
|
}),
|
|
634
737
|
);
|
|
635
738
|
}
|
|
636
|
-
} else {
|
|
637
|
-
console.log('No member found for user', recipientUser.id);
|
|
638
739
|
}
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
const
|
|
652
|
-
|
|
740
|
+
}
|
|
741
|
+
|
|
742
|
+
if (options.forceRefresh) {
|
|
743
|
+
// Remove loginDetails to force refresh
|
|
744
|
+
recipient.replacements = recipient.replacements.filter(r => r.token !== 'balanceTable' && r.token !== 'outstandingBalance');
|
|
745
|
+
}
|
|
746
|
+
|
|
747
|
+
// Load balance of this user
|
|
748
|
+
// todo: only if detected it is used
|
|
749
|
+
if (!recipient.replacements.find(r => r.token === 'balanceTable')) {
|
|
750
|
+
if (organization && recipientUser) {
|
|
751
|
+
const balanceItemModels = await CachedBalance.balanceForObjects(organization.id, [recipientUser.id], ReceivableBalanceType.user);
|
|
752
|
+
const balanceItems = balanceItemModels.map(i => i.getStructure());
|
|
753
|
+
|
|
754
|
+
// Get members
|
|
653
755
|
recipient.replacements.push(
|
|
654
756
|
Replacement.create({
|
|
655
|
-
token: '
|
|
757
|
+
token: 'outstandingBalance',
|
|
758
|
+
value: Formatter.price(balanceItems.reduce((sum, i) => sum + i.priceOpen, 0)),
|
|
759
|
+
}),
|
|
760
|
+
Replacement.create({
|
|
761
|
+
token: 'balanceTable',
|
|
656
762
|
value: '',
|
|
657
|
-
html:
|
|
763
|
+
html: BalanceItemStruct.getDetailsHTMLTable(balanceItems),
|
|
658
764
|
}),
|
|
659
765
|
);
|
|
660
766
|
} else {
|
|
661
767
|
recipient.replacements.push(
|
|
662
768
|
Replacement.create({
|
|
663
|
-
token: '
|
|
769
|
+
token: 'outstandingBalance',
|
|
770
|
+
value: Formatter.price(0),
|
|
771
|
+
}),
|
|
772
|
+
Replacement.create({
|
|
773
|
+
token: 'balanceTable',
|
|
664
774
|
value: '',
|
|
665
|
-
html:
|
|
775
|
+
html: BalanceItemStruct.getDetailsHTMLTable([]),
|
|
666
776
|
}),
|
|
667
777
|
);
|
|
668
778
|
}
|
|
669
779
|
}
|
|
670
|
-
}
|
|
671
|
-
|
|
672
|
-
if (options.forceRefresh) {
|
|
673
|
-
// Remove loginDetails to force refresh
|
|
674
|
-
recipient.replacements = recipient.replacements.filter(r => r.token !== 'balanceTable' && r.token !== 'outstandingBalance');
|
|
675
|
-
}
|
|
676
780
|
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
if (!recipient.replacements.find(r => r.token === 'balanceTable')) {
|
|
680
|
-
if (organization && recipientUser) {
|
|
681
|
-
const balanceItemModels = await CachedBalance.balanceForObjects(organization.id, [recipientUser.id], ReceivableBalanceType.user);
|
|
682
|
-
const balanceItems = balanceItemModels.map(i => i.getStructure());
|
|
683
|
-
|
|
684
|
-
// Get members
|
|
685
|
-
recipient.replacements.push(
|
|
686
|
-
Replacement.create({
|
|
687
|
-
token: 'outstandingBalance',
|
|
688
|
-
value: Formatter.price(balanceItems.reduce((sum, i) => sum + i.priceOpen, 0)),
|
|
689
|
-
}),
|
|
690
|
-
Replacement.create({
|
|
691
|
-
token: 'balanceTable',
|
|
692
|
-
value: '',
|
|
693
|
-
html: BalanceItemStruct.getDetailsHTMLTable(balanceItems),
|
|
694
|
-
}),
|
|
695
|
-
);
|
|
696
|
-
} else {
|
|
697
|
-
recipient.replacements.push(
|
|
698
|
-
Replacement.create({
|
|
699
|
-
token: 'outstandingBalance',
|
|
700
|
-
value: Formatter.price(0),
|
|
701
|
-
}),
|
|
702
|
-
Replacement.create({
|
|
703
|
-
token: 'balanceTable',
|
|
704
|
-
value: '',
|
|
705
|
-
html: BalanceItemStruct.getDetailsHTMLTable([]),
|
|
706
|
-
}),
|
|
707
|
-
);
|
|
708
|
-
}
|
|
709
|
-
}
|
|
781
|
+
if (from || replyTo) {
|
|
782
|
+
const fromAddress = replyTo?.email ?? from!.email;
|
|
710
783
|
|
|
711
|
-
|
|
712
|
-
|
|
784
|
+
if (fromAddress) {
|
|
785
|
+
recipient.replacements.push(Replacement.create({
|
|
786
|
+
token: 'fromAddress',
|
|
787
|
+
value: fromAddress,
|
|
788
|
+
}));
|
|
789
|
+
}
|
|
713
790
|
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
791
|
+
const name = replyTo?.name ?? from?.name;
|
|
792
|
+
if (name) {
|
|
793
|
+
recipient.replacements.push(Replacement.create({
|
|
794
|
+
token: 'fromName',
|
|
795
|
+
value: name,
|
|
796
|
+
}));
|
|
797
|
+
}
|
|
719
798
|
}
|
|
720
799
|
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
value: name,
|
|
726
|
-
}));
|
|
800
|
+
if (recipient instanceof EmailRecipient) {
|
|
801
|
+
recipient.replacements.push(...recipient.getRecipient().getDefaultReplacements());
|
|
802
|
+
} else {
|
|
803
|
+
recipient.replacements.push(...recipient.getDefaultReplacements());
|
|
727
804
|
}
|
|
728
|
-
}
|
|
729
805
|
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
}
|
|
806
|
+
if (organization) {
|
|
807
|
+
const extra = organization.meta.getEmailReplacements(organization);
|
|
808
|
+
recipient.replacements.push(...extra);
|
|
809
|
+
}
|
|
735
810
|
|
|
736
|
-
|
|
737
|
-
const extra =
|
|
811
|
+
// Defaults
|
|
812
|
+
const extra = platform.config.getEmailReplacements(platform);
|
|
738
813
|
recipient.replacements.push(...extra);
|
|
739
|
-
}
|
|
740
|
-
|
|
741
|
-
// Defaults
|
|
742
|
-
const extra = platform.config.getEmailReplacements(platform);
|
|
743
|
-
recipient.replacements.push(...extra);
|
|
744
814
|
|
|
745
|
-
|
|
746
|
-
|
|
815
|
+
// Remove duplicates
|
|
816
|
+
cleanReplacements(recipient.replacements);
|
|
817
|
+
}, options);
|
|
747
818
|
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { column } from '@simonbackx/simple-database';
|
|
1
|
+
import { column, Database } from '@simonbackx/simple-database';
|
|
2
2
|
import type { SQLWhere } from '@stamhoofd/sql';
|
|
3
3
|
import { QueryableModel, SQL, SQLAlias, SQLMin, SQLSelectAs, SQLSum, SQLWhereSign } from '@stamhoofd/sql';
|
|
4
4
|
import { BalanceItemStatus, BalanceItem as BalanceItemStruct, ReceivableBalanceType } from '@stamhoofd/structures';
|
|
@@ -103,6 +103,62 @@ export class CachedBalance extends QueryableModel {
|
|
|
103
103
|
return await query.fetch();
|
|
104
104
|
}
|
|
105
105
|
|
|
106
|
+
/**
|
|
107
|
+
* Delete cached balances that no longer have any balance item attached to them.
|
|
108
|
+
*
|
|
109
|
+
* A cached balance becomes orphaned when all the balance items of its object are moved or
|
|
110
|
+
* removed - e.g. when a member is merged into another member and their balance items are
|
|
111
|
+
* moved to the base member. The cached balance of the removed member then no longer
|
|
112
|
+
* corresponds to any balance item and should be cleaned up.
|
|
113
|
+
*
|
|
114
|
+
* Returns the number of deleted cached balances.
|
|
115
|
+
*/
|
|
116
|
+
static async deleteOrphaned(): Promise<number> {
|
|
117
|
+
const biTable = BalanceItem.table;
|
|
118
|
+
const memberUserTable = MemberUser.table;
|
|
119
|
+
|
|
120
|
+
// For each object type, a cached balance is orphaned when no balance item references its
|
|
121
|
+
// object (via the column that corresponds to the object type) within the same organization.
|
|
122
|
+
const orphanConditions: { objectType: ReceivableBalanceType; condition: string }[] = [
|
|
123
|
+
{
|
|
124
|
+
objectType: ReceivableBalanceType.member,
|
|
125
|
+
condition: `NOT EXISTS (SELECT 1 FROM \`${biTable}\` bi WHERE bi.organizationId = cb.organizationId AND bi.memberId = cb.objectId)`,
|
|
126
|
+
},
|
|
127
|
+
{
|
|
128
|
+
objectType: ReceivableBalanceType.registration,
|
|
129
|
+
condition: `NOT EXISTS (SELECT 1 FROM \`${biTable}\` bi WHERE bi.organizationId = cb.organizationId AND bi.registrationId = cb.objectId)`,
|
|
130
|
+
},
|
|
131
|
+
{
|
|
132
|
+
objectType: ReceivableBalanceType.organization,
|
|
133
|
+
condition: `NOT EXISTS (SELECT 1 FROM \`${biTable}\` bi WHERE bi.organizationId = cb.organizationId AND bi.payingOrganizationId = cb.objectId)`,
|
|
134
|
+
},
|
|
135
|
+
{
|
|
136
|
+
objectType: ReceivableBalanceType.userWithoutMembers,
|
|
137
|
+
condition: `NOT EXISTS (SELECT 1 FROM \`${biTable}\` bi WHERE bi.organizationId = cb.organizationId AND bi.userId = cb.objectId AND bi.memberId IS NULL)`,
|
|
138
|
+
},
|
|
139
|
+
{
|
|
140
|
+
// A user balance is the sum of the user's own balance items (without a member) and
|
|
141
|
+
// the balances of all members linked to that user, so it is only orphaned when
|
|
142
|
+
// neither of those exists.
|
|
143
|
+
objectType: ReceivableBalanceType.user,
|
|
144
|
+
condition: `NOT EXISTS (SELECT 1 FROM \`${biTable}\` bi WHERE bi.organizationId = cb.organizationId AND bi.userId = cb.objectId AND bi.memberId IS NULL)`
|
|
145
|
+
+ ` AND NOT EXISTS (SELECT 1 FROM \`${memberUserTable}\` mu JOIN \`${biTable}\` bi2 ON bi2.memberId = mu.membersId AND bi2.organizationId = cb.organizationId WHERE mu.usersId = cb.objectId)`,
|
|
146
|
+
},
|
|
147
|
+
];
|
|
148
|
+
|
|
149
|
+
let deleted = 0;
|
|
150
|
+
|
|
151
|
+
for (const { objectType, condition } of orphanConditions) {
|
|
152
|
+
const [result] = await Database.delete(
|
|
153
|
+
`DELETE cb FROM \`${this.table}\` cb WHERE cb.objectType = ? AND ${condition}`,
|
|
154
|
+
[objectType],
|
|
155
|
+
);
|
|
156
|
+
deleted += result.affectedRows;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
return deleted;
|
|
160
|
+
}
|
|
161
|
+
|
|
106
162
|
static async updateForObjects(organizationId: string, objectIds: string[], objectType: ReceivableBalanceType) {
|
|
107
163
|
if (objectIds.length === 0) {
|
|
108
164
|
return;
|