@stamhoofd/models 2.137.4 → 2.138.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (157) hide show
  1. package/dist/helpers/Handlebars.d.ts.map +1 -1
  2. package/dist/helpers/Handlebars.js +1 -1
  3. package/dist/helpers/Handlebars.js.map +1 -1
  4. package/dist/helpers/errorToSimpleErrors.d.ts +3 -0
  5. package/dist/helpers/errorToSimpleErrors.d.ts.map +1 -0
  6. package/dist/helpers/errorToSimpleErrors.js +17 -0
  7. package/dist/helpers/errorToSimpleErrors.js.map +1 -0
  8. package/dist/index.d.ts +0 -1
  9. package/dist/index.d.ts.map +1 -1
  10. package/dist/index.js +0 -1
  11. package/dist/index.js.map +1 -1
  12. package/dist/migrations/1782902314-tokens-authenticated-at.sql +2 -0
  13. package/dist/migrations/1782902315-create-mfa-totp-table.sql +13 -0
  14. package/dist/migrations/1782902316-create-webauthn-credentials-table.sql +17 -0
  15. package/dist/migrations/1782902317-create-mfa-recovery-codes-table.sql +10 -0
  16. package/dist/migrations/1782902318-create-mfa-tokens-table.sql +13 -0
  17. package/dist/migrations/1782902319-create-webauthn-challenges-table.sql +10 -0
  18. package/dist/migrations/1784039947-mfa-totp-last-used-counter.sql +2 -0
  19. package/dist/migrations/1784122354-webauthn-credential-provider.sql +3 -0
  20. package/dist/migrations/1784500000-webauthn-credential-rp-id.sql +9 -0
  21. package/dist/migrations/1785354091-platform-parent-tenant-id.sql +1 -0
  22. package/dist/migrations/1785354092-platform-fees-tenant-id.sql +1 -0
  23. package/dist/migrations/1785354093-platform-uri.sql +1 -0
  24. package/dist/migrations/1785354094-platform-domain.sql +1 -0
  25. package/dist/migrations/1785354095-platform-uri-unique.sql +1 -0
  26. package/dist/migrations/1785354096-platform-domain-unique.sql +1 -0
  27. package/dist/migrations/1785354097-platform-parent-tenant-id-index.sql +1 -0
  28. package/dist/migrations/1785354098-platform-tenant-backfill.d.ts +4 -0
  29. package/dist/migrations/1785354098-platform-tenant-backfill.d.ts.map +1 -0
  30. package/dist/migrations/1785354098-platform-tenant-backfill.js +10 -0
  31. package/dist/migrations/1785354098-platform-tenant-backfill.js.map +1 -0
  32. package/dist/migrations/1785417301-users-last-active-at.sql +2 -0
  33. package/dist/models/Document.d.ts +0 -4
  34. package/dist/models/Document.d.ts.map +1 -1
  35. package/dist/models/Document.js +1 -75
  36. package/dist/models/Document.js.map +1 -1
  37. package/dist/models/DocumentTemplate.d.ts +0 -3
  38. package/dist/models/DocumentTemplate.d.ts.map +1 -1
  39. package/dist/models/DocumentTemplate.js +1 -63
  40. package/dist/models/DocumentTemplate.js.map +1 -1
  41. package/dist/models/Email.d.ts +1 -29
  42. package/dist/models/Email.d.ts.map +1 -1
  43. package/dist/models/Email.js +4 -823
  44. package/dist/models/Email.js.map +1 -1
  45. package/dist/models/EmailVerificationCode.d.ts +0 -5
  46. package/dist/models/EmailVerificationCode.d.ts.map +1 -1
  47. package/dist/models/EmailVerificationCode.js +0 -84
  48. package/dist/models/EmailVerificationCode.js.map +1 -1
  49. package/dist/models/Image.d.ts.map +1 -1
  50. package/dist/models/Image.js +11 -14
  51. package/dist/models/Image.js.map +1 -1
  52. package/dist/models/MFARecoveryCode.d.ts +17 -0
  53. package/dist/models/MFARecoveryCode.d.ts.map +1 -0
  54. package/dist/models/MFARecoveryCode.js +55 -0
  55. package/dist/models/MFARecoveryCode.js.map +1 -0
  56. package/dist/models/MFATOTP.d.ts +44 -0
  57. package/dist/models/MFATOTP.d.ts.map +1 -0
  58. package/dist/models/MFATOTP.js +116 -0
  59. package/dist/models/MFATOTP.js.map +1 -0
  60. package/dist/models/MFAToken.d.ts +49 -0
  61. package/dist/models/MFAToken.d.ts.map +1 -0
  62. package/dist/models/MFAToken.js +137 -0
  63. package/dist/models/MFAToken.js.map +1 -0
  64. package/dist/models/MemberPlatformMembership.d.ts +0 -8
  65. package/dist/models/MemberPlatformMembership.d.ts.map +1 -1
  66. package/dist/models/MemberPlatformMembership.js +1 -242
  67. package/dist/models/MemberPlatformMembership.js.map +1 -1
  68. package/dist/models/Order.d.ts +1 -32
  69. package/dist/models/Order.d.ts.map +1 -1
  70. package/dist/models/Order.js +1 -182
  71. package/dist/models/Order.js.map +1 -1
  72. package/dist/models/Organization.d.ts +1 -51
  73. package/dist/models/Organization.d.ts.map +1 -1
  74. package/dist/models/Organization.js +1 -530
  75. package/dist/models/Organization.js.map +1 -1
  76. package/dist/models/PasswordToken.d.ts +0 -8
  77. package/dist/models/PasswordToken.d.ts.map +1 -1
  78. package/dist/models/PasswordToken.js +0 -23
  79. package/dist/models/PasswordToken.js.map +1 -1
  80. package/dist/models/Platform.d.ts +28 -4
  81. package/dist/models/Platform.d.ts.map +1 -1
  82. package/dist/models/Platform.js +111 -50
  83. package/dist/models/Platform.js.map +1 -1
  84. package/dist/models/STPackage.d.ts +1 -6
  85. package/dist/models/STPackage.d.ts.map +1 -1
  86. package/dist/models/STPackage.js +1 -98
  87. package/dist/models/STPackage.js.map +1 -1
  88. package/dist/models/Token.d.ts +40 -1
  89. package/dist/models/Token.d.ts.map +1 -1
  90. package/dist/models/Token.js +68 -2
  91. package/dist/models/Token.js.map +1 -1
  92. package/dist/models/User.d.ts +25 -0
  93. package/dist/models/User.d.ts.map +1 -1
  94. package/dist/models/User.js +36 -0
  95. package/dist/models/User.js.map +1 -1
  96. package/dist/models/WebauthnChallenge.d.ts +27 -0
  97. package/dist/models/WebauthnChallenge.d.ts.map +1 -0
  98. package/dist/models/WebauthnChallenge.js +81 -0
  99. package/dist/models/WebauthnChallenge.js.map +1 -0
  100. package/dist/models/WebauthnCredential.d.ts +58 -0
  101. package/dist/models/WebauthnCredential.d.ts.map +1 -0
  102. package/dist/models/WebauthnCredential.js +144 -0
  103. package/dist/models/WebauthnCredential.js.map +1 -0
  104. package/dist/models/index.d.ts +5 -0
  105. package/dist/models/index.d.ts.map +1 -1
  106. package/dist/models/index.js +5 -0
  107. package/dist/models/index.js.map +1 -1
  108. package/package.json +3 -3
  109. package/src/helpers/Handlebars.ts +5 -9
  110. package/src/helpers/errorToSimpleErrors.ts +17 -0
  111. package/src/index.ts +0 -1
  112. package/src/migrations/1782902314-tokens-authenticated-at.sql +2 -0
  113. package/src/migrations/1782902315-create-mfa-totp-table.sql +13 -0
  114. package/src/migrations/1782902316-create-webauthn-credentials-table.sql +17 -0
  115. package/src/migrations/1782902317-create-mfa-recovery-codes-table.sql +10 -0
  116. package/src/migrations/1782902318-create-mfa-tokens-table.sql +13 -0
  117. package/src/migrations/1782902319-create-webauthn-challenges-table.sql +10 -0
  118. package/src/migrations/1784039947-mfa-totp-last-used-counter.sql +2 -0
  119. package/src/migrations/1784122354-webauthn-credential-provider.sql +3 -0
  120. package/src/migrations/1784500000-webauthn-credential-rp-id.sql +9 -0
  121. package/src/migrations/1785354091-platform-parent-tenant-id.sql +1 -0
  122. package/src/migrations/1785354092-platform-fees-tenant-id.sql +1 -0
  123. package/src/migrations/1785354093-platform-uri.sql +1 -0
  124. package/src/migrations/1785354094-platform-domain.sql +1 -0
  125. package/src/migrations/1785354095-platform-uri-unique.sql +1 -0
  126. package/src/migrations/1785354096-platform-domain-unique.sql +1 -0
  127. package/src/migrations/1785354097-platform-parent-tenant-id-index.sql +1 -0
  128. package/src/migrations/1785354098-platform-tenant-backfill.ts +14 -0
  129. package/src/migrations/1785417301-users-last-active-at.sql +2 -0
  130. package/src/models/Document.ts +1 -84
  131. package/src/models/DocumentTemplate.ts +1 -71
  132. package/src/models/Email.ts +5 -941
  133. package/src/models/EmailVerificationCode.ts +0 -96
  134. package/src/models/Image.ts +11 -14
  135. package/src/models/MFARecoveryCode.ts +52 -0
  136. package/src/models/MFATOTP.ts +112 -0
  137. package/src/models/MFAToken.ts +138 -0
  138. package/src/models/MemberPlatformMembership.ts +1 -285
  139. package/src/models/Order.ts +1 -204
  140. package/src/models/Organization.ts +2 -637
  141. package/src/models/PasswordToken.ts +0 -29
  142. package/src/models/Platform.test.ts +167 -3
  143. package/src/models/Platform.ts +125 -50
  144. package/src/models/STPackage.ts +1 -110
  145. package/src/models/Token.ts +73 -2
  146. package/src/models/User.ts +37 -0
  147. package/src/models/WebauthnChallenge.ts +80 -0
  148. package/src/models/WebauthnCredential.ts +130 -0
  149. package/src/models/index.ts +6 -0
  150. package/dist/helpers/EmailBuilder.d.ts +0 -121
  151. package/dist/helpers/EmailBuilder.d.ts.map +0 -1
  152. package/dist/helpers/EmailBuilder.js +0 -659
  153. package/dist/helpers/EmailBuilder.js.map +0 -1
  154. package/src/helpers/EmailBuilder.test.ts +0 -291
  155. package/src/helpers/EmailBuilder.ts +0 -818
  156. package/src/models/Email.test.ts +0 -1222
  157. package/src/models/MemberPlatformMembership.test.ts +0 -70
@@ -1,659 +0,0 @@
1
- import { Email, EmailAddress } from '@stamhoofd/email';
2
- import { BalanceItem as BalanceItemStruct, getAppHost, ReceivableBalanceType, replaceEmailHtml, replaceEmailText, Replacement } from '@stamhoofd/structures';
3
- import { Formatter } from '@stamhoofd/utility';
4
- import { SimpleError } from '@simonbackx/simple-errors';
5
- import { I18n } from '@stamhoofd/backend-i18n/I18n';
6
- import { EmailRecipient } from '../models/EmailRecipient.js';
7
- import { CachedBalance } from '../models/CachedBalance.js';
8
- import { EmailTemplate } from '../models/EmailTemplate.js';
9
- import { Platform } from '../models/Platform.js';
10
- import { User } from '../models/User.js';
11
- export async function getEmailTemplate(data) {
12
- // Most specific template: for specific group
13
- const q = EmailTemplate.select()
14
- .where('type', data.type);
15
- if (data.group) {
16
- q.where('groupId', data.group.id);
17
- }
18
- if (data.organizationId) {
19
- q.where('organizationId', data.organizationId);
20
- }
21
- if (data.webshop) {
22
- q.where('webshopId', data.webshop.id);
23
- }
24
- let templates = await q.limit(1).fetch();
25
- // Specific for organization
26
- if (templates.length == 0 && (data.group?.id || data.webshop?.id) && data.organizationId) {
27
- templates = await EmailTemplate.select()
28
- .where('type', data.type)
29
- .where('organizationId', data.organizationId)
30
- .where('groupId', null)
31
- .where('webshopId', null)
32
- .limit(1)
33
- .fetch();
34
- }
35
- // Default for platform
36
- if (templates.length == 0 && (data.group?.id || data.webshop?.id || data.organizationId)) {
37
- templates = await EmailTemplate.select()
38
- .where('type', data.type)
39
- .where('organizationId', null)
40
- .where('groupId', null)
41
- .where('webshopId', null)
42
- .limit(1)
43
- .fetch();
44
- }
45
- if (templates.length == 0) {
46
- if (STAMHOOFD.environment === 'test') {
47
- return;
48
- }
49
- console.error('Could not find email template for type ' + data.type);
50
- return;
51
- }
52
- return templates[0];
53
- }
54
- export async function canSendFromEmail(fromAddress, organization) {
55
- if (organization) {
56
- if (organization.privateMeta.mailDomain && organization.privateMeta.mailDomainActive && fromAddress.endsWith('@' + organization.privateMeta.mailDomain)) {
57
- return true;
58
- }
59
- if (organization.id === (await Platform.getSharedPrivateStruct()).membershipOrganizationId) {
60
- return canSendFromEmail(fromAddress, null);
61
- }
62
- return false;
63
- }
64
- const transactionalDomains = Object.values(STAMHOOFD.domains.defaultTransactionalEmail ?? {});
65
- const broadcastDomains = Object.values(STAMHOOFD.domains.defaultBroadcastEmail ?? {});
66
- const domains = Formatter.uniqueArray([...transactionalDomains, ...broadcastDomains]);
67
- for (const domain of domains) {
68
- if (fromAddress.endsWith('@' + domain)) {
69
- return true;
70
- }
71
- }
72
- return false;
73
- }
74
- export async function getDefaultEmailFrom(organization, options) {
75
- // When choosing sending domain, prefer using the one with the highest reputation
76
- let preferEmailId = null;
77
- if (options.template.group) {
78
- preferEmailId = options.template.group.privateSettings.defaultEmailId;
79
- }
80
- if (options.template.webshop) {
81
- preferEmailId = options.template.webshop.privateMeta.defaultEmailId;
82
- }
83
- if (organization) {
84
- // Default email address for the chosen email type
85
- let from = organization.getDefaultFrom(organization.i18n, options.type ?? 'broadcast');
86
- const sender = (preferEmailId ? organization.privateMeta.emails.find(e => e.id === preferEmailId) : null) ?? organization.privateMeta.emails.find(e => e.default) ?? organization.privateMeta.emails[0];
87
- let replyTo = undefined;
88
- if (sender) {
89
- replyTo = {
90
- email: sender.email,
91
- name: sender.name,
92
- };
93
- // Can we send from this e-mail or reply-to?
94
- if (await canSendFromEmail(sender.email, organization)) {
95
- from = {
96
- email: sender.email,
97
- name: sender.name,
98
- };
99
- replyTo = undefined;
100
- }
101
- // Default to organization name
102
- if (!from.name) {
103
- from.name = organization.name;
104
- }
105
- if (replyTo) {
106
- if (!replyTo.name) {
107
- replyTo.name = organization.name;
108
- }
109
- }
110
- }
111
- return {
112
- from, replyTo,
113
- };
114
- }
115
- const platform = await Platform.getSharedPrivateStruct();
116
- // Default e-mail if no email addresses are configured
117
- const i18n = new I18n($getLanguage(), $getCountry());
118
- const transactionalDomain = i18n.localizedDomains.defaultTransactionalEmail();
119
- const broadcastDomain = i18n.localizedDomains.defaultBroadcastEmail();
120
- const domain = (options.type === 'transactional' ? transactionalDomain : broadcastDomain);
121
- let from = {
122
- email: 'hallo@' + domain,
123
- };
124
- // Platform
125
- const sender = (preferEmailId ? platform.privateConfig.emails.find(e => e.id === preferEmailId) : null) ?? platform.privateConfig.emails.find(e => e.default) ?? platform.privateConfig.emails[0];
126
- let replyTo = undefined;
127
- if (sender) {
128
- replyTo = {
129
- email: sender.email,
130
- name: sender.name,
131
- };
132
- // Are we allowed to send an e-mail from this domain?
133
- if (await canSendFromEmail(sender.email, null)) {
134
- // Allowed to send from
135
- from = {
136
- email: sender.email,
137
- name: sender.name,
138
- };
139
- replyTo = undefined;
140
- }
141
- // Default to platform name
142
- if (!from.name) {
143
- from.name = platform.config.name;
144
- }
145
- if (replyTo) {
146
- if (!replyTo.name) {
147
- replyTo.name = platform.config.name;
148
- }
149
- }
150
- }
151
- return {
152
- from, replyTo,
153
- };
154
- }
155
- export async function sendEmailTemplate(organization, options) {
156
- if (options.template.webshop) {
157
- options.defaultReplacements = [...(options.defaultReplacements ?? []), ...options.template.webshop.meta.getEmailReplacements()];
158
- }
159
- const builder = await getEmailBuilderForTemplate(organization, {
160
- ...options,
161
- ...(await getDefaultEmailFrom(organization, options)),
162
- });
163
- if (builder) {
164
- Email.schedule(builder);
165
- }
166
- }
167
- async function getEmailBuilderForTemplate(organization, options) {
168
- const template = await getEmailTemplate({
169
- ...options.template,
170
- organizationId: organization?.id ?? null,
171
- });
172
- if (!template) {
173
- if (STAMHOOFD.environment === 'production') {
174
- console.warn('No email template found for ' + options.template.type);
175
- }
176
- return undefined;
177
- }
178
- return await getEmailBuilder(organization, {
179
- ...options,
180
- subject: template.subject,
181
- html: template.html,
182
- translations: template.translations,
183
- });
184
- }
185
- /**
186
- * @param organization defines replacements and unsubsribe behaviour
187
- */
188
- export async function getEmailBuilder(organization, email) {
189
- const platform = await Platform.getSharedPrivateStruct();
190
- // Update recipients
191
- const cleaned = [];
192
- for (const recipient of email.recipients) {
193
- try {
194
- const unsubscribeGlobal = await EmailAddress.getWhereHardBounceOrSpam(recipient.email);
195
- if ((unsubscribeGlobal && (unsubscribeGlobal.hardBounce))) {
196
- // Ignore
197
- if (email.callback) {
198
- email.callback(new SimpleError({
199
- code: 'email_skipped_hard_bounce',
200
- message: 'Recipient has hard bounced',
201
- human: $t(`%ws`),
202
- }));
203
- }
204
- continue;
205
- }
206
- if (unsubscribeGlobal && (unsubscribeGlobal.markedAsSpam)) {
207
- // Ignore
208
- if (email.callback) {
209
- email.callback(new SimpleError({
210
- code: 'email_skipped_spam',
211
- message: 'Recipient has marked as spam',
212
- human: $t(`%wt`),
213
- }));
214
- }
215
- continue;
216
- }
217
- const unsubscribe = await EmailAddress.getOrCreate(recipient.email, email.fromStamhoofd || !organization ? null : organization.id);
218
- if (unsubscribe.unsubscribedAll || unsubscribe.hardBounce || unsubscribe.markedAsSpam || !unsubscribe.token || (unsubscribe.unsubscribedMarketing && email.unsubscribeType === 'marketing')) {
219
- // Ignore
220
- if (email.callback) {
221
- email.callback(new SimpleError({
222
- code: 'email_skipped_unsubscribed',
223
- message: unsubscribe.unsubscribedAll ? 'Recipient has unsubscribed' : (unsubscribe.hardBounce ? 'Recipient has hard bounced' : (unsubscribe.markedAsSpam ? 'Recipient has marked as spam' : 'Recipient has unsubscribed from marketing')),
224
- human: $t('%1E3'),
225
- }));
226
- }
227
- continue;
228
- }
229
- // Localize the unsubscribe page to the recipient's language (Organization.i18n is always Dutch)
230
- const unsubscribeLocale = organization ? getRecipientI18n(recipient, organization).locale : null;
231
- const unsubscribeUrl = 'https://' + STAMHOOFD.domains.dashboard + '/' + (unsubscribeLocale ? (unsubscribeLocale + '/') : '') + 'unsubscribe?id=' + encodeURIComponent(unsubscribe.id) + '&token=' + encodeURIComponent(unsubscribe.token) + '&type=' + encodeURIComponent(email.unsubscribeType ?? 'all');
232
- recipient.replacements.push(Replacement.create({
233
- token: 'unsubscribeUrl',
234
- value: unsubscribeUrl,
235
- }));
236
- // Override headers
237
- recipient.headers = {
238
- ...email.headers,
239
- 'List-Unsubscribe': STAMHOOFD.domains.defaultBroadcastEmail !== undefined ? '<mailto:unsubscribe+' + unsubscribe.id + '@' + STAMHOOFD.domains.defaultBroadcastEmail[''] + `>, <${unsubscribeUrl}>` : `<${unsubscribeUrl}>`,
240
- 'List-Unsubscribe-Post': 'List-Unsubscribe=One-Click',
241
- };
242
- cleaned.push(recipient);
243
- }
244
- catch (e) {
245
- console.error(e);
246
- }
247
- }
248
- email.recipients = cleaned;
249
- // Update recipients
250
- for (const recipient of email.recipients) {
251
- recipient.replacements = recipient.replacements.slice();
252
- if (email.defaultReplacements) {
253
- recipient.replacements.push(...email.defaultReplacements);
254
- }
255
- await fillRecipientReplacements(recipient, {
256
- organization,
257
- platform,
258
- from: email.from,
259
- replyTo: email.replyTo ?? null,
260
- });
261
- }
262
- const queue = email.recipients.slice();
263
- let emailIndex = 0;
264
- // The subject and html can differ per recipient language
265
- const contentCache = new Map();
266
- const resolveContent = (language) => {
267
- const cached = contentCache.get(language);
268
- if (cached) {
269
- return cached;
270
- }
271
- // Strict selection: only use a translation of this email, never fall back to
272
- // a different template for a missing language (content correctness above language)
273
- const translation = language !== null ? email.translations?.get(language) : undefined;
274
- const subject = translation ? translation.subject : email.subject;
275
- let html = translation ? translation.html : email.html;
276
- for (const s of email.replaceAll ?? []) {
277
- html = html.replaceAll(s.from, s.to);
278
- }
279
- const result = { subject, html };
280
- contentCache.set(language, result);
281
- return result;
282
- };
283
- if (queue.length === 0) {
284
- if (email.callback) {
285
- email.callback(new SimpleError({
286
- code: 'no_recipients',
287
- message: 'No recipients left',
288
- }));
289
- }
290
- }
291
- // Create e-mail builder
292
- const builder = () => {
293
- const recipient = queue.shift();
294
- if (!recipient) {
295
- return undefined;
296
- }
297
- const content = resolveContent(recipient.language ?? null);
298
- const replacedHtml = replaceEmailHtml(content.html, recipient.replacements);
299
- const replacedSubject = replaceEmailText(content.subject, recipient.replacements);
300
- emailIndex += 1;
301
- return {
302
- from: email.from,
303
- replyTo: email.replyTo ?? undefined,
304
- bcc: emailIndex === 1 && email.singleBcc ? [email.singleBcc] : undefined,
305
- to: [
306
- {
307
- // Name will get cleaned by email service
308
- name: (recipient.firstName ?? '') + ' ' + (recipient.lastName ?? ''),
309
- email: recipient.email,
310
- },
311
- ],
312
- subject: replacedSubject,
313
- html: replacedHtml ?? undefined,
314
- attachments: email.attachments,
315
- headers: recipient.headers,
316
- type: email.type,
317
- callback: email.callback,
318
- };
319
- };
320
- return builder;
321
- }
322
- export function mergeReplacement(replacementA, replacementB) {
323
- if (replacementA.token !== replacementB.token) {
324
- return false;
325
- }
326
- if (replacementA.token === 'greeting') {
327
- // Just take the first one
328
- return replacementA;
329
- }
330
- if (replacementA.token === 'unsubscribeUrl') {
331
- return replacementA;
332
- }
333
- if (replacementA.token === 'signInUrl') {
334
- return replacementA;
335
- }
336
- if (replacementA.token === 'loginDetails') {
337
- // loginDetails are always the same for the same user.
338
- return replacementA;
339
- }
340
- if (replacementA.token === 'objectName') {
341
- // Add comma if values are not the same
342
- const aa = replacementA.value.split(', ');
343
- return Replacement.create({
344
- token: 'objectName',
345
- value: Formatter.uniqueArray([...aa, ...replacementB.value.split(', ')]).join(', '),
346
- });
347
- }
348
- return false;
349
- }
350
- /**
351
- * Remove duplicates
352
- */
353
- export function cleanReplacements(replacements) {
354
- const foundIds = new Set();
355
- const cleaned = [];
356
- for (const r of replacements) {
357
- if (foundIds.has(r.token)) {
358
- continue;
359
- }
360
- foundIds.add(r.token);
361
- cleaned.push(r);
362
- }
363
- return cleaned;
364
- }
365
- export function removeUnusedReplacements(html, replacements) {
366
- const cleaned = [];
367
- for (const r of cleanReplacements(replacements)) {
368
- if (html.includes(`{{${r.token}}}`)) {
369
- cleaned.push(r);
370
- }
371
- }
372
- return cleaned;
373
- }
374
- export function mergeReplacementsIfEqual(replacementsA, replacementsB) {
375
- replacementsA = cleanReplacements(replacementsA);
376
- replacementsB = cleanReplacements(replacementsB);
377
- if (replacementsA.length !== replacementsB.length) {
378
- return false;
379
- }
380
- const merged = [];
381
- for (const rA of replacementsA) {
382
- const rB = replacementsB.find(r => r.token === rA.token);
383
- if (!rB) {
384
- return false;
385
- }
386
- if (rA.html === rB.html && rA.value === rB.value) {
387
- merged.push(rA);
388
- continue;
389
- }
390
- const m = mergeReplacement(rA, rB);
391
- if (!m) {
392
- return false;
393
- }
394
- merged.push(m);
395
- }
396
- return merged;
397
- }
398
- /**
399
- * Filter replacements for display in the backend.
400
- * @param options.forPreview if true, it will hide sensitive information in the preview that could leak information to admin users
401
- */
402
- export function stripSensitiveRecipientReplacements(recipient, options) {
403
- const { organization } = options;
404
- // Remove unsubscribeUrl and signInUrl if present
405
- recipient.replacements = recipient.replacements.filter(r => r.token !== 'unsubscribeUrl' && r.token !== 'signInUrl');
406
- if (options.willFill) {
407
- // Also strip loginDetails, balanceTable and outstandingBalance
408
- recipient.replacements = recipient.replacements.filter(r => r.token !== 'balanceTable' && r.token !== 'outstandingBalance' && r.token !== 'loginDetails');
409
- return;
410
- }
411
- // Add dummy unsubscribeUrl
412
- const dummyUnsubscribeUrl = 'https://' + (organization && STAMHOOFD.userMode === 'organization' ? getAppHost('registration', organization, false) : STAMHOOFD.domains.dashboard) + '/unsubscribe?token=example';
413
- recipient.replacements.push(Replacement.create({
414
- token: 'unsubscribeUrl',
415
- value: dummyUnsubscribeUrl,
416
- }));
417
- // dummy signInUrl
418
- const dummySignInUrl = 'https://' + (organization && STAMHOOFD.userMode === 'organization' ? getAppHost('registration', organization, false) : STAMHOOFD.domains.dashboard) + '/login';
419
- recipient.replacements.push(Replacement.create({
420
- token: 'signInUrl',
421
- value: dummySignInUrl,
422
- }));
423
- // Strip security codes (because we list ALL security codes, also from members a viewer might not have access to)
424
- recipient.replacements = recipient.replacements.map((r) => {
425
- if (r.token !== 'loginDetails') {
426
- return r;
427
- }
428
- return Replacement.create({
429
- ...r,
430
- // Strip <span class="style-inline-code">(.*)</span> and replace content with XXXX-XXXX-XXXX-XXXX
431
- html: r.html ? r.html.replace(/<span class="style-inline-code">.*?<\/span>/g, '<span class="style-inline-code">••••</span>') : r.html,
432
- });
433
- });
434
- }
435
- /**
436
- * Fill and hide replacements that don't make sense for web display to the user
437
- */
438
- export function stripRecipientReplacementsForWebDisplay(recipient, options) {
439
- const { organization } = options;
440
- // Remove unsubscribeUrl if present
441
- recipient.replacements = recipient.replacements.filter(r => r.token !== 'unsubscribeUrl' && r.token !== 'loginDetails' && r.token !== 'greeting');
442
- // Add dummy unsubscribeUrl
443
- const dummyUnsubscribeUrl = 'https://' + (organization && STAMHOOFD.userMode === 'organization' ? getAppHost('registration', organization, false) : STAMHOOFD.domains.dashboard);
444
- recipient.replacements.push(Replacement.create({
445
- token: 'unsubscribeUrl',
446
- value: dummyUnsubscribeUrl,
447
- }));
448
- recipient.replacements.push(Replacement.create({
449
- token: 'loginDetails',
450
- value: '',
451
- }));
452
- recipient.replacements.push(Replacement.create({
453
- token: 'greeting',
454
- value: $t('%1E9'),
455
- }));
456
- }
457
- /**
458
- * Build the I18n an email should be rendered in for a specific recipient.
459
- *
460
- * Falls back to the current (ambient) locale when the recipient has no language set — so flows
461
- * that already established a locale (order emails wrapped in I18n.runWithLocale, or the request
462
- * locale) keep working unchanged.
463
- */
464
- export function getRecipientI18n(recipient, organization, options) {
465
- let lang = recipient.language ?? $getLanguage();
466
- if (options?.allowedLanguages && options.allowedLanguages.length) {
467
- if (!options.allowedLanguages.includes(lang)) {
468
- if (options.allowedLanguages.includes($getLanguage())) {
469
- lang = $getLanguage();
470
- }
471
- else {
472
- lang = options.allowedLanguages[0];
473
- }
474
- }
475
- }
476
- return new I18n(lang, organization?.address.country ?? $getCountry());
477
- }
478
- /**
479
- * Render everything inside `handler` in the recipient's language: all $t / $getLanguage /
480
- * $getCountry calls (and therefore every generated replacement) use the recipient's locale.
481
- *
482
- * This is the single place that binds "a recipient" to "its language" when generating email
483
- * content. Generate recipient replacements inside this wrapper so new replacements are localized
484
- * automatically, and pass the provided i18n to helpers that take an explicit locale (e.g. getAppHost).
485
- */
486
- export function runWithRecipientLocale(recipient, organization, handler, options) {
487
- const i18n = getRecipientI18n(recipient, organization, options);
488
- return I18n.runWithLocale(i18n, () => handler(i18n));
489
- }
490
- /**
491
- * @param options.forPreview if true, it will hide sensitive information in the preview that could leak information to admin users
492
- */
493
- export async function fillRecipientReplacements(recipient, options) {
494
- if (!options.platform) {
495
- options.platform = await Platform.getSharedPrivateStruct();
496
- }
497
- const { organization, platform, from, replyTo } = options;
498
- // Render every recipient replacement (greeting, loginDetails, balance table, URLs...) in the
499
- // recipient's own language, so translated emails are consistent end-to-end. Any replacement
500
- // added below is localized automatically; helpers with an explicit locale get the same i18n.
501
- await runWithRecipientLocale(recipient, organization, async (i18n) => {
502
- let recipientUser = null;
503
- recipient.replacements = recipient.replacements.slice();
504
- if (options.forPreview) {
505
- stripSensitiveRecipientReplacements(recipient, options);
506
- }
507
- if (!recipient.email && !recipient.userId) {
508
- const signInUrl = 'https://' + (organization && STAMHOOFD.userMode === 'organization' ? getAppHost('registration', organization, false, i18n) : STAMHOOFD.domains.dashboard) + '/login';
509
- recipient.replacements.push(Replacement.create({
510
- token: 'signInUrl',
511
- value: signInUrl,
512
- }));
513
- if (!recipient.replacements.find(r => r.token === 'loginDetails')) {
514
- recipient.replacements.push(Replacement.create({
515
- token: 'loginDetails',
516
- value: '',
517
- }));
518
- }
519
- }
520
- else {
521
- // Default signInUrl
522
- recipientUser = recipient.userId ? await User.select().where('id', recipient.userId).first(false) : await User.getForAuthentication(organization?.id ?? null, recipient.email, { allowWithoutAccount: true });
523
- if (STAMHOOFD.userMode !== 'platform' && recipientUser && recipientUser.organizationId && recipientUser.organizationId !== (organization?.id ?? null)) {
524
- console.warn('User organization does not match current organization, ignoring userId', recipient.userId, recipientUser.organizationId, organization?.id ?? null);
525
- recipientUser = null;
526
- }
527
- let signInUrl;
528
- if (!recipientUser || !recipientUser.hasAccount()) {
529
- // We can create a special token
530
- if (recipientUser) {
531
- signInUrl = 'https://' + (organization && STAMHOOFD.userMode === 'organization' ? getAppHost('registration', organization, false, i18n) : STAMHOOFD.domains.dashboard) + '/account-aanmaken?email=' + encodeURIComponent(recipientUser?.email);
532
- }
533
- else {
534
- signInUrl = 'https://' + (organization && STAMHOOFD.userMode === 'organization' ? getAppHost('registration', organization, false, i18n) : STAMHOOFD.domains.dashboard) + '/account-aanmaken';
535
- }
536
- }
537
- else {
538
- signInUrl = 'https://' + (organization && STAMHOOFD.userMode === 'organization' ? getAppHost('registration', organization, false, i18n) : STAMHOOFD.domains.dashboard) + '/login?email=' + encodeURIComponent(recipientUser.email);
539
- }
540
- recipient.replacements.push(Replacement.create({
541
- token: 'signInUrl',
542
- value: signInUrl,
543
- }));
544
- }
545
- if (options.forceRefresh) {
546
- // Remove loginDetails to force refresh
547
- recipient.replacements = recipient.replacements.filter(r => r.token !== 'loginDetails');
548
- }
549
- if (!recipient.replacements.find(r => r.token === 'loginDetails')) {
550
- if (recipientUser) {
551
- const emailEscaped = `<strong>${Formatter.escapeHtml(recipientUser.email)}</strong>`;
552
- const suffixes = [];
553
- const { Member } = await import('../models/Member.js');
554
- const memberIds = await Member.getMemberIdsForUser(recipientUser);
555
- const members = await Member.getByIDs(...memberIds);
556
- if (members.length > 0) {
557
- for (const member of members) {
558
- suffixes.push($t('%1EC', {
559
- firstName: Formatter.escapeHtml(member.firstName),
560
- securityCode: `<span class="style-inline-code">${Formatter.escapeHtml(options.forPreview ? '••••' : Formatter.spaceString(member.details.securityCode ?? '', 4, '-'))}</span>`,
561
- }));
562
- }
563
- }
564
- else {
565
- console.log('No member found for user', recipientUser.id);
566
- }
567
- const suffix = suffixes.length > 0 ? (' ' + suffixes.join(' ')) : '';
568
- recipient.replacements.push(Replacement.create({
569
- token: 'loginDetails',
570
- value: '',
571
- html: recipientUser.hasAccount()
572
- ? `<p class="description"><em>${$t('%1EA', { email: emailEscaped })}${suffix}</em></p>`
573
- : `<p class="description"><em>${$t('%1EB', { email: emailEscaped })}${suffix}</em></p>`,
574
- }));
575
- }
576
- else {
577
- if (recipient.email) {
578
- const emailEscaped = `<strong>${Formatter.escapeHtml(recipient.email)}</strong>`;
579
- console.log('No user found for email', recipient.email);
580
- recipient.replacements.push(Replacement.create({
581
- token: 'loginDetails',
582
- value: '',
583
- html: `<p class="description"><em>${$t('%1EB', { email: emailEscaped })}</em></p>`,
584
- }));
585
- }
586
- else {
587
- recipient.replacements.push(Replacement.create({
588
- token: 'loginDetails',
589
- value: '',
590
- html: '',
591
- }));
592
- }
593
- }
594
- }
595
- if (options.forceRefresh) {
596
- // Remove loginDetails to force refresh
597
- recipient.replacements = recipient.replacements.filter(r => r.token !== 'balanceTable' && r.token !== 'outstandingBalance');
598
- }
599
- // Load balance of this user
600
- // todo: only if detected it is used
601
- if (!recipient.replacements.find(r => r.token === 'balanceTable')) {
602
- if (organization && recipientUser) {
603
- const balanceItemModels = await CachedBalance.balanceForObjects(organization.id, [recipientUser.id], ReceivableBalanceType.user);
604
- const balanceItems = balanceItemModels.map(i => i.getStructure());
605
- // Get members
606
- recipient.replacements.push(Replacement.create({
607
- token: 'outstandingBalance',
608
- value: Formatter.price(balanceItems.reduce((sum, i) => sum + i.priceOpen, 0)),
609
- }), Replacement.create({
610
- token: 'balanceTable',
611
- value: '',
612
- html: BalanceItemStruct.getDetailsHTMLTable(balanceItems),
613
- }));
614
- }
615
- else {
616
- recipient.replacements.push(Replacement.create({
617
- token: 'outstandingBalance',
618
- value: Formatter.price(0),
619
- }), Replacement.create({
620
- token: 'balanceTable',
621
- value: '',
622
- html: BalanceItemStruct.getDetailsHTMLTable([]),
623
- }));
624
- }
625
- }
626
- if (from || replyTo) {
627
- const fromAddress = replyTo?.email ?? from.email;
628
- if (fromAddress) {
629
- recipient.replacements.push(Replacement.create({
630
- token: 'fromAddress',
631
- value: fromAddress,
632
- }));
633
- }
634
- const name = replyTo?.name ?? from?.name;
635
- if (name) {
636
- recipient.replacements.push(Replacement.create({
637
- token: 'fromName',
638
- value: name,
639
- }));
640
- }
641
- }
642
- if (recipient instanceof EmailRecipient) {
643
- recipient.replacements.push(...recipient.getRecipient().getDefaultReplacements());
644
- }
645
- else {
646
- recipient.replacements.push(...recipient.getDefaultReplacements());
647
- }
648
- if (organization) {
649
- const extra = organization.meta.getEmailReplacements(organization);
650
- recipient.replacements.push(...extra);
651
- }
652
- // Defaults
653
- const extra = platform.config.getEmailReplacements(platform);
654
- recipient.replacements.push(...extra);
655
- // Remove duplicates
656
- cleanReplacements(recipient.replacements);
657
- }, options);
658
- }
659
- //# sourceMappingURL=EmailBuilder.js.map