@stamhoofd/models 2.134.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.
Files changed (64) hide show
  1. package/dist/factories/EmailTemplateFactory.d.ts +4 -1
  2. package/dist/factories/EmailTemplateFactory.d.ts.map +1 -1
  3. package/dist/factories/EmailTemplateFactory.js +8 -0
  4. package/dist/factories/EmailTemplateFactory.js.map +1 -1
  5. package/dist/helpers/EmailBuilder.d.ts +34 -1
  6. package/dist/helpers/EmailBuilder.d.ts.map +1 -1
  7. package/dist/helpers/EmailBuilder.js +191 -133
  8. package/dist/helpers/EmailBuilder.js.map +1 -1
  9. package/dist/migrations/1783096205-member-last-registered-at.sql +3 -0
  10. package/dist/migrations/1783973645-orders-consumer-language.sql +2 -0
  11. package/dist/migrations/1783987708-email-templates-translations.sql +2 -0
  12. package/dist/migrations/1783987709-emails-translations.sql +2 -0
  13. package/dist/migrations/1783987710-email-recipients-language.sql +2 -0
  14. package/dist/migrations/1784037917-email-templates-language.sql +2 -0
  15. package/dist/migrations/1784037918-emails-language.sql +2 -0
  16. package/dist/models/CachedBalance.d.ts +11 -0
  17. package/dist/models/CachedBalance.d.ts.map +1 -1
  18. package/dist/models/CachedBalance.js +49 -1
  19. package/dist/models/CachedBalance.js.map +1 -1
  20. package/dist/models/Email.d.ts +46 -4
  21. package/dist/models/Email.d.ts.map +1 -1
  22. package/dist/models/Email.js +165 -24
  23. package/dist/models/Email.js.map +1 -1
  24. package/dist/models/EmailRecipient.d.ts +5 -0
  25. package/dist/models/EmailRecipient.d.ts.map +1 -1
  26. package/dist/models/EmailRecipient.js +7 -0
  27. package/dist/models/EmailRecipient.js.map +1 -1
  28. package/dist/models/EmailTemplate.d.ts +6 -1
  29. package/dist/models/EmailTemplate.d.ts.map +1 -1
  30. package/dist/models/EmailTemplate.js +13 -2
  31. package/dist/models/EmailTemplate.js.map +1 -1
  32. package/dist/models/Event.d.ts.map +1 -1
  33. package/dist/models/Event.js +11 -5
  34. package/dist/models/Event.js.map +1 -1
  35. package/dist/models/Member.d.ts +5 -0
  36. package/dist/models/Member.d.ts.map +1 -1
  37. package/dist/models/Member.js +22 -1
  38. package/dist/models/Member.js.map +1 -1
  39. package/dist/models/Order.d.ts +6 -0
  40. package/dist/models/Order.d.ts.map +1 -1
  41. package/dist/models/Order.js +36 -20
  42. package/dist/models/Order.js.map +1 -1
  43. package/dist/models/User.d.ts.map +1 -1
  44. package/dist/models/User.js +19 -6
  45. package/dist/models/User.js.map +1 -1
  46. package/package.json +4 -3
  47. package/src/factories/EmailTemplateFactory.ts +12 -1
  48. package/src/helpers/EmailBuilder.test.ts +246 -0
  49. package/src/helpers/EmailBuilder.ts +215 -144
  50. package/src/migrations/1783096205-member-last-registered-at.sql +3 -0
  51. package/src/migrations/1783973645-orders-consumer-language.sql +2 -0
  52. package/src/migrations/1783987708-email-templates-translations.sql +2 -0
  53. package/src/migrations/1783987709-emails-translations.sql +2 -0
  54. package/src/migrations/1783987710-email-recipients-language.sql +2 -0
  55. package/src/migrations/1784037917-email-templates-language.sql +2 -0
  56. package/src/migrations/1784037918-emails-language.sql +2 -0
  57. package/src/models/CachedBalance.ts +57 -1
  58. package/src/models/Email.ts +181 -26
  59. package/src/models/EmailRecipient.ts +7 -0
  60. package/src/models/EmailTemplate.ts +12 -2
  61. package/src/models/Event.ts +10 -6
  62. package/src/models/Member.ts +25 -1
  63. package/src/models/Order.ts +41 -24
  64. package/src/models/User.ts +31 -22
@@ -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
- const unsubscribeUrl = 'https://' + STAMHOOFD.domains.dashboard + '/' + (organization ? (organization.i18n.locale + '/') : '') + 'unsubscribe?id=' + encodeURIComponent(unsubscribe.id) + '&token=' + encodeURIComponent(unsubscribe.token) + '&type=' + encodeURIComponent(email.unsubscribeType ?? 'all');
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
- for (const s of email.replaceAll ?? []) {
344
- email.html = email.html.replaceAll(s.from, s.to);
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 replacedHtml = replaceEmailHtml(email.html, recipient.replacements);
364
- const replacedSubject = replaceEmailText(email.subject, recipient.replacements);
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
- if (!recipient.email && !recipient.userId) {
577
- const signInUrl = 'https://' + (organization && STAMHOOFD.userMode === 'organization' ? getAppHost('registration', organization, false) : STAMHOOFD.domains.dashboard) + '/login';
578
- recipient.replacements.push(Replacement.create({
579
- token: 'signInUrl',
580
- value: signInUrl,
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.replacements.find(r => r.token === 'loginDetails')) {
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: 'loginDetails',
586
- value: '',
649
+ token: 'signInUrl',
650
+ value: signInUrl,
587
651
  }));
588
- }
589
- } else {
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
- recipientUser = recipient.userId ? await User.select().where('id', recipient.userId).first(false) : await User.getForAuthentication(organization?.id ?? null, recipient.email!, { allowWithoutAccount: true });
592
- if (STAMHOOFD.userMode !== 'platform' && recipientUser && recipientUser.organizationId && recipientUser.organizationId !== (organization?.id ?? null)) {
593
- console.warn('User organization does not match current organization, ignoring userId', recipient.userId, recipientUser.organizationId, organization?.id ?? null);
594
- recipientUser = null;
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
- let signInUrl: string;
598
- if (!recipientUser || !recipientUser.hasAccount()) {
667
+ let signInUrl: string;
668
+ if (!recipientUser || !recipientUser.hasAccount()) {
599
669
  // We can create a special token
600
- if (recipientUser) {
601
- signInUrl = 'https://' + (organization && STAMHOOFD.userMode === 'organization' ? getAppHost('registration', organization, false) : STAMHOOFD.domains.dashboard) + '/account-aanmaken?email=' + encodeURIComponent(recipientUser?.email);
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) + '/account-aanmaken';
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
- recipient.replacements.push(Replacement.create({
610
- token: 'signInUrl',
611
- value: signInUrl,
612
- }));
613
- }
679
+ recipient.replacements.push(Replacement.create({
680
+ token: 'signInUrl',
681
+ value: signInUrl,
682
+ }));
683
+ }
614
684
 
615
- if (options.forceRefresh) {
685
+ if (options.forceRefresh) {
616
686
  // Remove loginDetails to force refresh
617
- recipient.replacements = recipient.replacements.filter(r => r.token !== 'loginDetails');
618
- }
687
+ recipient.replacements = recipient.replacements.filter(r => r.token !== 'loginDetails');
688
+ }
619
689
 
620
- if (!recipient.replacements.find(r => r.token === 'loginDetails')) {
621
- if (recipientUser) {
622
- const emailEscaped = `<strong>${Formatter.escapeHtml(recipientUser.email)}</strong>`;
623
- const suffixes: string[] = [];
624
- const { Member } = await import('../models/Member.js');
625
- const memberIds = await Member.getMemberIdsForUser(recipientUser);
626
- const members = await Member.getByIDs(...memberIds);
627
- if (members.length > 0) {
628
- for (const member of members) {
629
- suffixes.push(
630
- $t('%1EC', {
631
- firstName: Formatter.escapeHtml(member.firstName),
632
- securityCode: `<span class="style-inline-code">${Formatter.escapeHtml(options.forPreview ? '••••' : Formatter.spaceString(member.details.securityCode ?? '', 4, '-'))}</span>`,
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
- const suffix = suffixes.length > 0 ? (' ' + suffixes.join(' ')) : '';
640
- recipient.replacements.push(
641
- Replacement.create({
642
- token: 'loginDetails',
643
- value: '',
644
- html: recipientUser.hasAccount()
645
- ? `<p class="description"><em>${$t('%1EA', { email: emailEscaped })}${suffix}</em></p>`
646
- : `<p class="description"><em>${$t('%1EB', { email: emailEscaped })}${suffix}</em></p>`,
647
- }),
648
- );
649
- } else {
650
- if (recipient.email) {
651
- const emailEscaped = `<strong>${Formatter.escapeHtml(recipient.email)}</strong>`;
652
- console.log('No user found for email', recipient.email);
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: 'loginDetails',
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: `<p class="description"><em>${$t('%1EB', { email: emailEscaped })}</em></p>`,
763
+ html: BalanceItemStruct.getDetailsHTMLTable(balanceItems),
658
764
  }),
659
765
  );
660
766
  } else {
661
767
  recipient.replacements.push(
662
768
  Replacement.create({
663
- token: 'loginDetails',
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
- // Load balance of this user
678
- // todo: only if detected it is used
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
- if (from || replyTo) {
712
- const fromAddress = replyTo?.email ?? from!.email;
784
+ if (fromAddress) {
785
+ recipient.replacements.push(Replacement.create({
786
+ token: 'fromAddress',
787
+ value: fromAddress,
788
+ }));
789
+ }
713
790
 
714
- if (fromAddress) {
715
- recipient.replacements.push(Replacement.create({
716
- token: 'fromAddress',
717
- value: fromAddress,
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
- const name = replyTo?.name ?? from?.name;
722
- if (name) {
723
- recipient.replacements.push(Replacement.create({
724
- token: 'fromName',
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
- if (recipient instanceof EmailRecipient) {
731
- recipient.replacements.push(...recipient.getRecipient().getDefaultReplacements());
732
- } else {
733
- recipient.replacements.push(...recipient.getDefaultReplacements());
734
- }
806
+ if (organization) {
807
+ const extra = organization.meta.getEmailReplacements(organization);
808
+ recipient.replacements.push(...extra);
809
+ }
735
810
 
736
- if (organization) {
737
- const extra = organization.meta.getEmailReplacements(organization);
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
- // Remove duplicates
746
- cleanReplacements(recipient.replacements);
815
+ // Remove duplicates
816
+ cleanReplacements(recipient.replacements);
817
+ }, options);
747
818
  }
@@ -0,0 +1,3 @@
1
+ ALTER TABLE `members`
2
+ ADD COLUMN `lastRegisteredAt` datetime NULL AFTER `updatedAt`,
3
+ ADD INDEX `lastRegisteredAt` (`lastRegisteredAt`) USING BTREE;
@@ -0,0 +1,2 @@
1
+ ALTER TABLE `webshop_orders`
2
+ ADD COLUMN `consumerLanguage` varchar(36) NOT NULL DEFAULT 'nl' AFTER `status`;
@@ -0,0 +1,2 @@
1
+ ALTER TABLE `email_templates`
2
+ ADD COLUMN `translations` json NOT NULL DEFAULT ('{"value": {}, "version": 0}');
@@ -0,0 +1,2 @@
1
+ ALTER TABLE `emails`
2
+ ADD COLUMN `translations` json NOT NULL DEFAULT ('{"value": {}, "version": 0}');
@@ -0,0 +1,2 @@
1
+ ALTER TABLE `email_recipients`
2
+ ADD COLUMN `language` varchar(2) NULL DEFAULT NULL;
@@ -0,0 +1,2 @@
1
+ ALTER TABLE `email_templates`
2
+ ADD COLUMN `language` varchar(2) NULL DEFAULT NULL;
@@ -0,0 +1,2 @@
1
+ ALTER TABLE `emails`
2
+ ADD COLUMN `language` varchar(2) NULL DEFAULT NULL;
@@ -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;