@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,9 +1,13 @@
1
1
  import { column } from '@simonbackx/simple-database';
2
- import type { BaseOrganization, EmailRecipient as EmailRecipientStruct, EmailTemplateType, PaginatedResponse, StamhoofdFilter, User as UserStruct } from '@stamhoofd/structures';
3
- import { EmailAttachment, EmailPreview, EmailRecipientFilter, EmailRecipientsStatus, EmailStatus, Email as EmailStruct, EmailWithRecipients, getExampleRecipient, isSoftEmailRecipientError, LimitedFilteredRequest, SortItemDirection } from '@stamhoofd/structures';
2
+ import type { BaseOrganization, EmailRecipient as EmailRecipientStruct, EmailTemplateType, PaginatedResponse, Replacement, StamhoofdFilter, User as UserStruct } from '@stamhoofd/structures';
3
+ import { EmailAttachment, EmailContent, EmailPreview, EmailRecipientFilter, EmailRecipientsStatus, EmailStatus, Email as EmailStruct, EmailWithRecipients, getEmailContentForLanguage, getExampleRecipient, isSoftEmailRecipientError, LanguageHelper, LimitedFilteredRequest, SortItemDirection } from '@stamhoofd/structures';
4
+ import { ExampleReplacements } from '@stamhoofd/structures/email/exampleReplacements.js';
5
+ import type { Country } from '@stamhoofd/types/Country';
6
+ import { Language } from '@stamhoofd/types/Language';
4
7
  import { v4 as uuidv4 } from 'uuid';
5
8
  import type { EmailRecipientFilterType } from '@stamhoofd/structures/email/EmailRecipientFilterType.js';
6
- import { AnyDecoder, ArrayDecoder } from '@simonbackx/simple-encoding';
9
+ import type { Decoder } from '@simonbackx/simple-encoding';
10
+ import { AnyDecoder, ArrayDecoder, EnumDecoder, MapDecoder } from '@simonbackx/simple-encoding';
7
11
  import { isSimpleError, isSimpleErrors, SimpleError, SimpleErrors } from '@simonbackx/simple-errors';
8
12
  import { I18n } from '@stamhoofd/backend-i18n/I18n';
9
13
  import type { EmailInterfaceRecipient } from '@stamhoofd/email';
@@ -11,7 +15,7 @@ import { Email as EmailClass } from '@stamhoofd/email';
11
15
  import type { QueueHandlerOptions } from '@stamhoofd/queues';
12
16
  import { isAbortedError, QueueHandler } from '@stamhoofd/queues';
13
17
  import { QueryableModel, readDynamicSQLExpression, SQL, SQLAlias, SQLCount, SQLSelectAs, SQLWhereSign } from '@stamhoofd/sql';
14
- import { canSendFromEmail, fillRecipientReplacements, getEmailBuilder, mergeReplacementsIfEqual, removeUnusedReplacements, stripRecipientReplacementsForWebDisplay, stripSensitiveRecipientReplacements } from '../helpers/EmailBuilder.js';
18
+ import { canSendFromEmail, fillRecipientReplacements, getEmailBuilder, mergeReplacementsIfEqual, removeUnusedReplacements, runWithRecipientLocale, stripRecipientReplacementsForWebDisplay, stripSensitiveRecipientReplacements } from '../helpers/EmailBuilder.js';
15
19
  import { EmailRecipient } from './EmailRecipient.js';
16
20
  import { EmailTemplate } from './EmailTemplate.js';
17
21
  import { Organization } from './Organization.js';
@@ -42,7 +46,7 @@ export type RecipientLoader<BeforeFetchAllResult = any> = {
42
46
  * The result of this function will be passed to the `fetch` function.
43
47
  */
44
48
  beforeFetchAll?: (request: LimitedFilteredRequest, subfilter: StamhoofdFilter | null) => Promise<BeforeFetchAllResult>;
45
- fetch(request: LimitedFilteredRequest, subfilter: StamhoofdFilter | null, beforeFetchAllResult?: BeforeFetchAllResult): Promise<PaginatedResponse<EmailRecipientStruct[], LimitedFilteredRequest>>;
49
+ fetch(request: LimitedFilteredRequest, subfilter: StamhoofdFilter | null, beforeFetchAllResult?: BeforeFetchAllResult, options?: { allowedLanguages?: Language[] | null }): Promise<PaginatedResponse<EmailRecipientStruct[], LimitedFilteredRequest>>;
46
50
  count(request: LimitedFilteredRequest, subfilter: StamhoofdFilter | null): Promise<number>;
47
51
  };
48
52
 
@@ -105,6 +109,14 @@ export class Email extends QueryableModel {
105
109
  @column({ type: 'string', nullable: true })
106
110
  text: string | null = null;
107
111
 
112
+ /** Full content overrides per language. The default content (subject/html/text/json) is used for all recipients without a matching override. Never contains `language` itself */
113
+ @column({ type: 'json', decoder: new MapDecoder(new EnumDecoder(Language), EmailContent as Decoder<EmailContent>) })
114
+ translations: Map<Language, EmailContent> = new Map();
115
+
116
+ /** The language of the default content (subject/html/text/json); null when the content is untranslated */
117
+ @column({ type: 'string', nullable: true })
118
+ language: Language | null = null;
119
+
108
120
  @column({ type: 'string', nullable: true })
109
121
  fromAddress: string | null = null;
110
122
 
@@ -257,6 +269,16 @@ export class Email extends QueryableModel {
257
269
  });
258
270
  }
259
271
 
272
+ for (const [language, content] of this.translations) {
273
+ if (content.subject.length === 0 || content.text.length === 0 || content.html.length === 0) {
274
+ throw new SimpleError({
275
+ code: 'invalid_field',
276
+ message: 'Missing subject, text or html in translation ' + language,
277
+ human: $t('%Ze9', { language: LanguageHelper.getName(language) }),
278
+ });
279
+ }
280
+ }
281
+
260
282
  if (this.fromAddress == null || this.fromAddress.length == 0) {
261
283
  throw new SimpleError({
262
284
  code: 'invalid_field',
@@ -308,6 +330,17 @@ export class Email extends QueryableModel {
308
330
  }
309
331
  }
310
332
 
333
+ for (const [language, content] of this.translations) {
334
+ if ((content.html && !content.html.includes(replacement)) || (content.text && !content.text.includes(replacement))) {
335
+ throw new SimpleError({
336
+ code: 'missing_unsubscribe_button',
337
+ message: 'Missing unsubscribe button in translation ' + language,
338
+ human: $t(`%DS`),
339
+ field: 'translations',
340
+ });
341
+ }
342
+ }
343
+
311
344
  if (this.text) {
312
345
  // Check email contains an unsubscribe button
313
346
  if (!this.text.includes(replacement)) {
@@ -437,9 +470,26 @@ export class Email extends QueryableModel {
437
470
  this.subject = defaultTemplate.subject;
438
471
  this.json = defaultTemplate.json;
439
472
 
473
+ if (this.language !== null && this.language !== defaultTemplate.language) {
474
+ const content = defaultTemplate.translations.get(this.language);
475
+ if (content) {
476
+ this.html = content.html;
477
+ this.text = content.text;
478
+ this.subject = content.subject;
479
+ this.json = content.json;
480
+ }
481
+ }
482
+
440
483
  return true;
441
484
  }
442
485
 
486
+ /**
487
+ * The html of all languages combined - only used to check which replacements are in use.
488
+ */
489
+ getCombinedHtml(): string {
490
+ return [this.html ?? '', ...[...this.translations.values()].map(content => content.html)].join(' ');
491
+ }
492
+
443
493
  async lock<T>(callback: (upToDate: Email, options: QueueHandlerOptions) => Promise<T> | T): Promise<T> {
444
494
  if (!this.id) {
445
495
  await this.save();
@@ -729,6 +779,7 @@ export class Email extends QueryableModel {
729
779
  replyTo: data.replyTo,
730
780
  subject: this.subject!,
731
781
  html: this.html!,
782
+ translations: this.translations,
732
783
  type: this.emailType ? 'transactional' : 'broadcast',
733
784
  attachments: data.attachments,
734
785
  callback(error: Error | null) {
@@ -1122,6 +1173,10 @@ export class Email extends QueryableModel {
1122
1173
  }).catch(console.error);
1123
1174
  }
1124
1175
 
1176
+ getLanguages() {
1177
+ return this.language ? [this.language, ...this.translations.keys()] : null;
1178
+ }
1179
+
1125
1180
  async buildRecipients() {
1126
1181
  const id = this.id;
1127
1182
  await QueueHandler.schedule('email-build-recipients-' + this.id, async function ({ abort }) {
@@ -1159,6 +1214,7 @@ export class Email extends QueryableModel {
1159
1214
 
1160
1215
  const membersSet = new Set<string>();
1161
1216
  const emailsSet = new Set<string>();
1217
+ const combinedHtml = upToDate.getCombinedHtml();
1162
1218
 
1163
1219
  let count = 0;
1164
1220
  let countWithoutEmail = 0;
@@ -1193,7 +1249,7 @@ export class Email extends QueryableModel {
1193
1249
 
1194
1250
  while (request) {
1195
1251
  abort.throwIfAborted();
1196
- const response = await loader.fetch(request, subfilter.subfilter, beforeFetchAllResult);
1252
+ const response = await loader.fetch(request, subfilter.subfilter, beforeFetchAllResult, { allowedLanguages: upToDate.getLanguages() });
1197
1253
 
1198
1254
  for (const item of response.results) {
1199
1255
  if (!item.email && !item.memberId && !item.userId) {
@@ -1207,6 +1263,7 @@ export class Email extends QueryableModel {
1207
1263
  recipient.email = item.email;
1208
1264
  recipient.firstName = item.firstName;
1209
1265
  recipient.lastName = item.lastName;
1266
+ recipient.language = item.language ?? null;
1210
1267
  recipient.replacements = item.replacements;
1211
1268
  recipient.memberId = item.memberId ?? null;
1212
1269
  recipient.userId = item.userId ?? null;
@@ -1218,8 +1275,9 @@ export class Email extends QueryableModel {
1218
1275
  from: upToDate.getFromAddress(),
1219
1276
  replyTo: null,
1220
1277
  forPreview: false,
1278
+ allowedLanguages: upToDate.getLanguages(),
1221
1279
  });
1222
- recipient.replacements = removeUnusedReplacements(upToDate.html ?? '', recipient.replacements);
1280
+ recipient.replacements = removeUnusedReplacements(combinedHtml, recipient.replacements);
1223
1281
 
1224
1282
  let duplicateOfRecipientId: string | null = null;
1225
1283
  if (item.email && emailsSet.has(item.email)) {
@@ -1332,7 +1390,7 @@ export class Email extends QueryableModel {
1332
1390
  const beforeFetchAllResult = loader.beforeFetchAll ? await loader.beforeFetchAll(request, subfilter.subfilter) : undefined;
1333
1391
 
1334
1392
  while (request) {
1335
- const response = await loader.fetch(request, subfilter.subfilter, beforeFetchAllResult);
1393
+ const response = await loader.fetch(request, subfilter.subfilter, beforeFetchAllResult, { allowedLanguages: upToDate.getLanguages() });
1336
1394
 
1337
1395
  // Note: it is possible that a result in the database doesn't return a recipient (in memory filtering)
1338
1396
  // so we do need pagination
@@ -1345,6 +1403,7 @@ export class Email extends QueryableModel {
1345
1403
  recipient.email = item.email;
1346
1404
  recipient.firstName = item.firstName;
1347
1405
  recipient.lastName = item.lastName;
1406
+ recipient.language = item.language ?? null;
1348
1407
  recipient.replacements = item.replacements;
1349
1408
  recipient.memberId = item.memberId ?? null;
1350
1409
  recipient.userId = item.userId ?? null;
@@ -1372,33 +1431,104 @@ export class Email extends QueryableModel {
1372
1431
  return EmailStruct.create(this);
1373
1432
  }
1374
1433
 
1375
- async getPreviewStructure() {
1434
+ /**
1435
+ * The languages an example recipient should be generated for: every language the platform
1436
+ * supports (the composer can add translations for those), plus every language the email
1437
+ * already has content for.
1438
+ *
1439
+ * Languages the I18n would correct to a different language (no longer supported for this
1440
+ * country) are excluded: their example values would be generated in the corrected language,
1441
+ * which is more misleading than falling back to the single example recipient.
1442
+ */
1443
+ getExampleRecipientLanguages(country: Country): Language[] {
1444
+ const languages = new Set<Language>();
1445
+ for (const list of Object.values(I18n.validLocales)) {
1446
+ for (const language of list) {
1447
+ languages.add(language);
1448
+ }
1449
+ }
1450
+ if (this.language) {
1451
+ languages.add(this.language);
1452
+ }
1453
+ for (const language of this.translations.keys()) {
1454
+ languages.add(language);
1455
+ }
1456
+ return [...languages].filter(language => new I18n(language, country).language === language);
1457
+ }
1458
+
1459
+ /**
1460
+ * @param options.allLanguages Also fill exampleRecipients: the same recipient with its
1461
+ * replacements generated in each supported language. Only use this for detail endpoints,
1462
+ * it repeats the replacement queries for every language.
1463
+ */
1464
+ async getPreviewStructure(options: { allLanguages?: boolean } = {}) {
1376
1465
  const emailRecipient = await EmailRecipient.select()
1377
1466
  .where('emailId', this.id)
1378
1467
  .where('email', '!=', null)
1379
1468
  .first(false);
1380
1469
 
1381
- let recipientRow: EmailRecipientStruct | undefined;
1470
+ let baseRow: EmailRecipientStruct | undefined;
1382
1471
 
1383
1472
  if (emailRecipient) {
1384
- recipientRow = await emailRecipient.getStructure();
1473
+ baseRow = await emailRecipient.getStructure();
1385
1474
  }
1386
1475
 
1387
- if (!recipientRow) {
1388
- recipientRow = getExampleRecipient();
1476
+ if (!baseRow) {
1477
+ baseRow = getExampleRecipient();
1389
1478
  }
1390
1479
 
1391
- const virtualRecipient = recipientRow.getRecipient();
1392
1480
  const organization = this.organizationId ? (await Organization.getByID(this.organizationId))! : null;
1481
+ const allowedLanguages = this.getLanguages();
1393
1482
 
1394
- await fillRecipientReplacements(virtualRecipient, {
1395
- organization,
1396
- from: this.getFromAddress(),
1397
- replyTo: null,
1398
- forPreview: true,
1399
- forceRefresh: !this.sentAt,
1400
- });
1401
- recipientRow.replacements = virtualRecipient.replacements;
1483
+ const fillRow = async (row: EmailRecipientStruct) => {
1484
+ const virtualRecipient = row.getRecipient();
1485
+
1486
+ await fillRecipientReplacements(virtualRecipient, {
1487
+ organization,
1488
+ from: this.getFromAddress(),
1489
+ replyTo: null,
1490
+ forPreview: true,
1491
+ forceRefresh: !this.sentAt,
1492
+ allowedLanguages,
1493
+ });
1494
+ row.replacements = virtualRecipient.replacements;
1495
+ return row;
1496
+ };
1497
+
1498
+ const recipientRow = await fillRow(baseRow.clone());
1499
+
1500
+ // The same recipient in every supported language: the replacements are regenerated in
1501
+ // each language (the recipient's own language is ignored), so the composer can show
1502
+ // example values in the language that is being edited
1503
+ const exampleRecipients = new Map<Language, EmailRecipientStruct>();
1504
+ if (allowedLanguages && allowedLanguages.length > 1) {
1505
+ // The same country the recipient locale will resolve to (see getRecipientI18n)
1506
+ const country = organization?.address?.country ?? $getCountry();
1507
+ for (const language of allowedLanguages) {
1508
+ const i18n = new I18n(language, country);
1509
+ await I18n.runWithLocale(i18n, async () => {
1510
+ const clone = baseRow.clone();
1511
+ clone.language = language;
1512
+
1513
+ if (baseRow.language !== language) {
1514
+ // Todo: this can be improved
1515
+ // Replace all replacements with defaults
1516
+ for (const replacement of clone.replacements) {
1517
+ const example: Replacement | undefined = ExampleReplacements.all[replacement.token];
1518
+ if (example) {
1519
+ replacement.html = example.html;
1520
+ replacement.value = example.value;
1521
+ }
1522
+ }
1523
+
1524
+ clone.replacements = clone.replacements.filter(r => !['organizationName'].includes(r.token));
1525
+ }
1526
+
1527
+ const rr = await fillRow(clone);
1528
+ exampleRecipients.set(language, rr);
1529
+ });
1530
+ }
1531
+ }
1402
1532
 
1403
1533
  let user: UserStruct | null = null;
1404
1534
  if (this.userId) {
@@ -1418,10 +1548,24 @@ export class Email extends QueryableModel {
1418
1548
  user,
1419
1549
  organization: organizationStruct,
1420
1550
  exampleRecipient: recipientRow,
1551
+ exampleRecipients,
1421
1552
  });
1422
1553
  }
1423
1554
 
1424
- async getStructureForUser(user: User, memberIds: string[]) {
1555
+ /**
1556
+ * Whether the email has content in this language (strict: the default content only counts
1557
+ * for its own language, see getEmailContentForLanguage)
1558
+ */
1559
+ hasContentForLanguage(language: Language): boolean {
1560
+ return language === this.language || this.translations.has(language);
1561
+ }
1562
+
1563
+ /**
1564
+ * @param options.language The language the caller is viewing in (from the request headers).
1565
+ * Recipients are returned in this language when the email has content for it, otherwise in
1566
+ * the language they received the email in.
1567
+ */
1568
+ async getStructureForUser(user: User, memberIds: string[], options: { language?: Language | null } = {}) {
1425
1569
  const emailRecipients = await EmailRecipient.select()
1426
1570
  .where('emailId', this.id)
1427
1571
  .where('memberId', memberIds)
@@ -1465,19 +1609,30 @@ export class Email extends QueryableModel {
1465
1609
  struct.email = user.email;
1466
1610
  struct.userId = user.id;
1467
1611
 
1612
+ // Show the email in the language the caller is viewing in, but only when the email
1613
+ // has content for it: otherwise keep the language the recipient received it in
1614
+ // (better correct content in the wrong language than wrong content in the right language)
1615
+ if (options.language && this.hasContentForLanguage(options.language)) {
1616
+ struct.language = options.language;
1617
+ }
1618
+
1468
1619
  // We always refresh the data when we display it on the web (so everything is up to date)
1620
+ // The replacements are regenerated in struct.language, so they match the displayed content
1469
1621
  await fillRecipientReplacements(struct, {
1470
1622
  organization,
1471
1623
  from: this.getFromAddress(),
1472
1624
  replyTo: null,
1473
1625
  forPreview: false,
1474
1626
  forceRefresh: true,
1627
+ allowedLanguages: this.getLanguages(),
1475
1628
  });
1476
- stripRecipientReplacementsForWebDisplay(struct, {
1477
- organization,
1629
+ runWithRecipientLocale(struct, organization, () => {
1630
+ stripRecipientReplacementsForWebDisplay(struct, {
1631
+ organization,
1632
+ });
1478
1633
  });
1479
1634
  if (this.html) {
1480
- struct.replacements = removeUnusedReplacements(this.html, struct.replacements);
1635
+ struct.replacements = removeUnusedReplacements(this.getCombinedHtml(), struct.replacements);
1481
1636
  }
1482
1637
  }
1483
1638
 
@@ -1,5 +1,6 @@
1
1
  import { column } from '@simonbackx/simple-database';
2
2
  import { EmailRecipient as EmailRecipientStruct, Recipient, Replacement, TinyMember } from '@stamhoofd/structures';
3
+ import type { Language } from '@stamhoofd/types/Language';
3
4
  import { v4 as uuidv4 } from 'uuid';
4
5
 
5
6
  import { ArrayDecoder } from '@simonbackx/simple-encoding';
@@ -44,6 +45,12 @@ export class EmailRecipient extends QueryableModel {
44
45
  @column({ type: 'string', nullable: true })
45
46
  email: string | null = null;
46
47
 
48
+ /**
49
+ * Preferred language of this recipient, used to select the email content translation.
50
+ */
51
+ @column({ type: 'string', nullable: true })
52
+ language: Language | null = null;
53
+
47
54
  @column({ type: 'json', decoder: new ArrayDecoder(Replacement) })
48
55
  replacements: Replacement[] = [];
49
56
 
@@ -1,8 +1,10 @@
1
1
  import { column } from '@simonbackx/simple-database';
2
- import { AnyDecoder } from '@simonbackx/simple-encoding';
2
+ import type { Decoder } from '@simonbackx/simple-encoding';
3
+ import { AnyDecoder, EnumDecoder, MapDecoder } from '@simonbackx/simple-encoding';
3
4
  import { QueryableModel } from '@stamhoofd/sql';
4
5
  import type { EmailTemplateType } from '@stamhoofd/structures';
5
- import { EmailTemplate as EmailTemplateStruct } from '@stamhoofd/structures';
6
+ import { EmailContent, EmailTemplate as EmailTemplateStruct } from '@stamhoofd/structures';
7
+ import { Language } from '@stamhoofd/types/Language';
6
8
  import { v4 as uuidv4 } from 'uuid';
7
9
 
8
10
  /**
@@ -44,6 +46,14 @@ export class EmailTemplate extends QueryableModel {
44
46
  @column({ type: 'string' })
45
47
  text: string;
46
48
 
49
+ /** Full content overrides per language. The default content (subject/html/text/json) is used for all languages without an override. Never contains `language` itself */
50
+ @column({ type: 'json', decoder: new MapDecoder(new EnumDecoder(Language), EmailContent as Decoder<EmailContent>) })
51
+ translations: Map<Language, EmailContent> = new Map();
52
+
53
+ /** The language of the default content (subject/html/text/json); null when the content is untranslated */
54
+ @column({ type: 'string', nullable: true })
55
+ language: Language | null = null;
56
+
47
57
  @column({
48
58
  type: 'datetime', beforeSave() {
49
59
  const date = new Date();
@@ -101,18 +101,22 @@ export class Event extends QueryableModel {
101
101
  }
102
102
 
103
103
  if (this.organizationId) {
104
- // This is a not-national event, so require the organization
105
- group.settings.requireOrganizationIds = [this.organizationId];
104
+ // This is a not-national event, so require the organization (unless non-members are allowed)
105
+ group.settings.requireOrganizationIds = this.meta.allowNonMembers ? [] : [this.organizationId];
106
106
  group.settings.requireOrganizationTags = [];
107
107
  group.settings.requirePlatformMembershipOn = null;
108
108
  } else {
109
- group.settings.requireOrganizationTags = this.meta.organizationTagIds ?? [];
110
-
111
109
  // Everyone can register
112
110
  group.settings.requireOrganizationIds = [];
113
111
 
114
- // But they need a valid platform membership
115
- group.settings.requirePlatformMembershipOn = this.endDate;
112
+ if (this.meta.allowNonMembers) {
113
+ group.settings.requireOrganizationTags = [];
114
+ group.settings.requirePlatformMembershipOn = null;
115
+ } else {
116
+ group.settings.requireOrganizationTags = this.meta.organizationTagIds ?? [];
117
+ // But they need a valid platform membership
118
+ group.settings.requirePlatformMembershipOn = this.endDate;
119
+ }
116
120
  }
117
121
  await group.save();
118
122
 
@@ -112,6 +112,12 @@ export class Member extends QueryableModel {
112
112
  skipUpdate: true,
113
113
  })
114
114
  updatedAt: Date;
115
+
116
+ /**
117
+ * The last time the member was registered.
118
+ */
119
+ @column({ type: 'datetime', nullable: true })
120
+ lastRegisteredAt: Date | null = null;
115
121
  // #endregion
116
122
 
117
123
  static registrations = new OneToManyRelation(Member, Registration, 'registrations', 'memberId');
@@ -431,7 +437,14 @@ export class Member extends QueryableModel {
431
437
  ids.push(id);
432
438
  }
433
439
 
434
- return await this.getByIDs(...ids);
440
+ const members = await this.getByIDs(...ids);
441
+
442
+ const member = members.find(r => r.id === id);
443
+ if (member) {
444
+ return members.filter(r => r.organizationId === member.organizationId);
445
+ }
446
+
447
+ return members;
435
448
  }
436
449
 
437
450
  /**
@@ -518,4 +531,15 @@ export class Member extends QueryableModel {
518
531
 
519
532
  return true;
520
533
  }
534
+
535
+ async tryUpdateLastRegisteredAt(registration: Registration) {
536
+ if (registration.registeredAt === null) {
537
+ return;
538
+ }
539
+
540
+ if (this.lastRegisteredAt === null || this.lastRegisteredAt < registration.registeredAt) {
541
+ this.lastRegisteredAt = new Date(registration.registeredAt.getTime());
542
+ await this.save();
543
+ }
544
+ }
521
545
  }
@@ -1,7 +1,9 @@
1
1
  import type { ManyToOneRelation } from '@simonbackx/simple-database';
2
2
  import { column } from '@simonbackx/simple-database';
3
3
  import { SimpleError } from '@simonbackx/simple-errors';
4
+ import { I18n } from '@stamhoofd/backend-i18n/I18n';
4
5
  import { QueueHandler } from '@stamhoofd/queues';
6
+ import { Language } from '@stamhoofd/types/Language';
5
7
  import { QueryableModel, SQL } from '@stamhoofd/sql';
6
8
  import type { TransferSettings, WebshopTimeSlot } from '@stamhoofd/structures';
7
9
  import { BalanceItemPaymentWithPayment, BalanceItemPaymentWithPrivatePayment, BalanceItemWithPayments, BalanceItemWithPrivatePayments, EmailTemplateType, OrderData, OrderStatus, Order as OrderStruct, PaymentMethod, PaymentStatus, Payment as PaymentStruct, PrivateOrder, PrivatePayment, ProductType, Recipient, Replacement, WebshopPreview, WebshopStatus, WebshopTicketType } from '@stamhoofd/structures';
@@ -75,6 +77,13 @@ export class Order extends QueryableModel {
75
77
  @column({ type: 'string' })
76
78
  status = OrderStatus.Created;
77
79
 
80
+ /**
81
+ * The language the customer used while placing the order, so future emails to this order
82
+ * are rendered in the same language.
83
+ */
84
+ @column({ type: 'string' })
85
+ consumerLanguage: Language = Language.Dutch;
86
+
78
87
  /**
79
88
  * Cached value for faster in database filtering
80
89
  */
@@ -119,9 +128,9 @@ export class Order extends QueryableModel {
119
128
  getUrl(this: Order & { webshop: Webshop & { organization: Organization } }) {
120
129
  // Country locales are disabled on webshops (always the same country). But we need to add the language if it isn't the same as the organization default language
121
130
  let locale = '';
122
- // eslint-disable-next-line @typescript-eslint/no-unsafe-enum-comparison
123
- if (this.data.consumerLanguage !== this.webshop.organization.i18n.language) {
124
- locale = '/' + this.data.consumerLanguage;
131
+
132
+ if (this.consumerLanguage !== this.webshop.organization.i18n.language) {
133
+ locale = '/' + this.consumerLanguage;
125
134
  }
126
135
 
127
136
  return 'https://' + this.webshop.getHost() + locale + '/order/' + this.id;
@@ -794,6 +803,7 @@ export class Order extends QueryableModel {
794
803
  number: this.number,
795
804
  data: this.data,
796
805
  status: this.status,
806
+ consumerLanguage: this.consumerLanguage,
797
807
  balanceItems: [],
798
808
  createdAt: this.createdAt,
799
809
  updatedAt: this.updatedAt,
@@ -900,28 +910,35 @@ export class Order extends QueryableModel {
900
910
  return;
901
911
  }
902
912
 
903
- let recipient = (await this.getStructure()).getRecipient(
904
- this.webshop.organization.getBaseStructure(),
905
- WebshopPreview.create(this.webshop),
906
- );
907
-
908
- if (data.to) {
909
- // Clear first and last name
910
- recipient.firstName = null;
911
- recipient.lastName = null;
912
- recipient.replacements = recipient.replacements.filter(r => !['firstName', 'lastName'].includes(r.token));
913
- data.to.merge(recipient);
914
- recipient = data.to;
915
- }
913
+ // Render all $t's (recipient replacements, order tables, template...) in the language
914
+ // the customer used while placing the order, instead of the current request language.
915
+ const i18n = new I18n(this.consumerLanguage, this.webshop.organization.address.country);
916
916
 
917
- // Create e-mail builder
918
- await sendEmailTemplate(this.webshop.organization, {
919
- recipients: [recipient],
920
- template: {
921
- type: data.type,
922
- webshop: this.webshop,
923
- },
924
- type: 'transactional',
917
+ await I18n.runWithLocale(i18n, async () => {
918
+ let recipient = (await this.getStructure()).getRecipient(
919
+ this.webshop.organization.getBaseStructure(),
920
+ WebshopPreview.create(this.webshop),
921
+ );
922
+
923
+ if (data.to) {
924
+ // Clear first and last name
925
+ recipient.firstName = null;
926
+ recipient.lastName = null;
927
+ recipient.language = this.webshop.meta.defaultLanguage;
928
+ recipient.replacements = recipient.replacements.filter(r => !['firstName', 'lastName'].includes(r.token));
929
+ data.to.merge(recipient);
930
+ recipient = data.to;
931
+ }
932
+
933
+ // Create e-mail builder
934
+ await sendEmailTemplate(this.webshop.organization, {
935
+ recipients: [recipient],
936
+ template: {
937
+ type: data.type,
938
+ webshop: this.webshop,
939
+ },
940
+ type: 'transactional',
941
+ });
925
942
  });
926
943
  }
927
944