@stamhoofd/models 2.137.3 → 2.137.5

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 (56) hide show
  1. package/dist/models/Document.d.ts +0 -4
  2. package/dist/models/Document.d.ts.map +1 -1
  3. package/dist/models/Document.js +1 -75
  4. package/dist/models/Document.js.map +1 -1
  5. package/dist/models/DocumentTemplate.d.ts +0 -3
  6. package/dist/models/DocumentTemplate.d.ts.map +1 -1
  7. package/dist/models/DocumentTemplate.js +1 -63
  8. package/dist/models/DocumentTemplate.js.map +1 -1
  9. package/dist/models/Email.d.ts +1 -23
  10. package/dist/models/Email.d.ts.map +1 -1
  11. package/dist/models/Email.js +2 -200
  12. package/dist/models/Email.js.map +1 -1
  13. package/dist/models/EmailVerificationCode.d.ts +0 -5
  14. package/dist/models/EmailVerificationCode.d.ts.map +1 -1
  15. package/dist/models/EmailVerificationCode.js +0 -84
  16. package/dist/models/EmailVerificationCode.js.map +1 -1
  17. package/dist/models/Image.d.ts.map +1 -1
  18. package/dist/models/Image.js +11 -14
  19. package/dist/models/Image.js.map +1 -1
  20. package/dist/models/MemberPlatformMembership.d.ts +0 -8
  21. package/dist/models/MemberPlatformMembership.d.ts.map +1 -1
  22. package/dist/models/MemberPlatformMembership.js +1 -242
  23. package/dist/models/MemberPlatformMembership.js.map +1 -1
  24. package/dist/models/Order.d.ts +1 -32
  25. package/dist/models/Order.d.ts.map +1 -1
  26. package/dist/models/Order.js +1 -182
  27. package/dist/models/Order.js.map +1 -1
  28. package/dist/models/Organization.d.ts +1 -14
  29. package/dist/models/Organization.d.ts.map +1 -1
  30. package/dist/models/Organization.js +10 -408
  31. package/dist/models/Organization.js.map +1 -1
  32. package/dist/models/PasswordToken.d.ts +0 -8
  33. package/dist/models/PasswordToken.d.ts.map +1 -1
  34. package/dist/models/PasswordToken.js +0 -23
  35. package/dist/models/PasswordToken.js.map +1 -1
  36. package/dist/models/Platform.d.ts.map +1 -1
  37. package/dist/models/Platform.js +7 -2
  38. package/dist/models/Platform.js.map +1 -1
  39. package/dist/models/STPackage.d.ts +1 -6
  40. package/dist/models/STPackage.d.ts.map +1 -1
  41. package/dist/models/STPackage.js +1 -98
  42. package/dist/models/STPackage.js.map +1 -1
  43. package/package.json +3 -3
  44. package/src/models/Document.ts +1 -84
  45. package/src/models/DocumentTemplate.ts +1 -71
  46. package/src/models/Email.ts +3 -230
  47. package/src/models/EmailVerificationCode.ts +0 -96
  48. package/src/models/Image.ts +11 -14
  49. package/src/models/MemberPlatformMembership.ts +1 -285
  50. package/src/models/Order.ts +1 -204
  51. package/src/models/Organization.test.ts +46 -0
  52. package/src/models/Organization.ts +10 -491
  53. package/src/models/PasswordToken.ts +0 -29
  54. package/src/models/Platform.ts +9 -2
  55. package/src/models/STPackage.ts +1 -110
  56. package/src/models/MemberPlatformMembership.test.ts +0 -70
@@ -1,7 +1,6 @@
1
1
  import { column } from '@simonbackx/simple-database';
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';
2
+ import type { EmailRecipient as EmailRecipientStruct, EmailTemplateType, PaginatedResponse, StamhoofdFilter } from '@stamhoofd/structures';
3
+ import { EmailAttachment, EmailContent, EmailRecipientFilter, EmailRecipientsStatus, EmailStatus, Email as EmailStruct, isSoftEmailRecipientError, LanguageHelper, LimitedFilteredRequest, SortItemDirection } from '@stamhoofd/structures';
5
4
  import type { Country } from '@stamhoofd/types/Country';
6
5
  import { Language } from '@stamhoofd/types/Language';
7
6
  import { v4 as uuidv4 } from 'uuid';
@@ -15,12 +14,11 @@ import { Email as EmailClass } from '@stamhoofd/email';
15
14
  import type { QueueHandlerOptions } from '@stamhoofd/queues';
16
15
  import { isAbortedError, QueueHandler } from '@stamhoofd/queues';
17
16
  import { QueryableModel, readDynamicSQLExpression, SQL, SQLAlias, SQLCount, SQLSelectAs, SQLWhereSign } from '@stamhoofd/sql';
18
- import { canSendFromEmail, fillRecipientReplacements, getEmailBuilder, mergeReplacementsIfEqual, removeUnusedReplacements, runWithRecipientLocale, stripRecipientReplacementsForWebDisplay, stripSensitiveRecipientReplacements } from '../helpers/EmailBuilder.js';
17
+ import { canSendFromEmail, fillRecipientReplacements, getEmailBuilder, mergeReplacementsIfEqual, removeUnusedReplacements } from '../helpers/EmailBuilder.js';
19
18
  import { EmailRecipient } from './EmailRecipient.js';
20
19
  import { EmailTemplate } from './EmailTemplate.js';
21
20
  import { Organization } from './Organization.js';
22
21
  import { Platform } from './Platform.js';
23
- import { User } from './User.js';
24
22
 
25
23
  type Attachment = { filename: string; path?: string; href?: string; content?: string | Buffer; contentType?: string; encoding?: string };
26
24
 
@@ -1455,229 +1453,4 @@ export class Email extends QueryableModel {
1455
1453
  }
1456
1454
  return [...languages].filter(language => new I18n(language, country).language === language);
1457
1455
  }
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 } = {}) {
1465
- const emailRecipient = await EmailRecipient.select()
1466
- .where('emailId', this.id)
1467
- .where('email', '!=', null)
1468
- .first(false);
1469
-
1470
- let baseRow: EmailRecipientStruct | undefined;
1471
-
1472
- if (emailRecipient) {
1473
- baseRow = await emailRecipient.getStructure();
1474
- }
1475
-
1476
- if (!baseRow) {
1477
- baseRow = getExampleRecipient();
1478
- }
1479
-
1480
- const organization = this.organizationId ? (await Organization.getByID(this.organizationId))! : null;
1481
- const allowedLanguages = this.getLanguages();
1482
-
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
- }
1532
-
1533
- let user: UserStruct | null = null;
1534
- if (this.userId) {
1535
- const u = await User.getByID(this.userId);
1536
- if (u) {
1537
- user = u.getStructure();
1538
- }
1539
- }
1540
-
1541
- let organizationStruct: BaseOrganization | null = null;
1542
- if (organization) {
1543
- organizationStruct = organization.getBaseStructure();
1544
- }
1545
-
1546
- return EmailPreview.create({
1547
- ...this,
1548
- user,
1549
- organization: organizationStruct,
1550
- exampleRecipient: recipientRow,
1551
- exampleRecipients,
1552
- });
1553
- }
1554
-
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 } = {}) {
1569
- const emailRecipients = await EmailRecipient.select()
1570
- .where('emailId', this.id)
1571
- .where('memberId', memberIds)
1572
- .fetch();
1573
- const organization = this.organizationId ? (await Organization.getByID(this.organizationId))! : null;
1574
-
1575
- const recipientsMap: Map<string, EmailRecipient> = new Map();
1576
- for (const memberId of memberIds) {
1577
- const preferred = emailRecipients.find(e => e.memberId === memberId && (e.userId === user.id || e.email === user.email));
1578
- if (preferred) {
1579
- recipientsMap.set(preferred.duplicateOfRecipientId ?? preferred.id, preferred);
1580
- continue;
1581
- }
1582
-
1583
- const byMember = emailRecipients.find(e => e.memberId === memberId && e.userId === null && e.email === null);
1584
- if (byMember) {
1585
- recipientsMap.set(byMember.duplicateOfRecipientId ?? byMember.id, byMember);
1586
- continue;
1587
- }
1588
- const anyData = emailRecipients.find(e => e.memberId === memberId);
1589
- if (anyData) {
1590
- recipientsMap.set(anyData.duplicateOfRecipientId ?? anyData.id, anyData);
1591
- continue;
1592
- }
1593
- }
1594
-
1595
- // Remove duplicates that are marked as the same recipient
1596
- const cleanedRecipients: EmailRecipient[] = [...recipientsMap.values()];
1597
- const structures = await EmailRecipient.getStructures(cleanedRecipients);
1598
-
1599
- for (const struct of structures) {
1600
- if (!(struct.userId === user.id || struct.email === user.email) && !((struct.userId === null && struct.email === null))) {
1601
- stripSensitiveRecipientReplacements(struct, {
1602
- organization,
1603
- willFill: true,
1604
- });
1605
- }
1606
-
1607
- struct.firstName = user.firstName;
1608
- struct.lastName = user.lastName;
1609
- struct.email = user.email;
1610
- struct.userId = user.id;
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
-
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
1621
- await fillRecipientReplacements(struct, {
1622
- organization,
1623
- from: this.getFromAddress(),
1624
- replyTo: null,
1625
- forPreview: false,
1626
- forceRefresh: true,
1627
- allowedLanguages: this.getLanguages(),
1628
- });
1629
- runWithRecipientLocale(struct, organization, () => {
1630
- stripRecipientReplacementsForWebDisplay(struct, {
1631
- organization,
1632
- });
1633
- });
1634
- if (this.html) {
1635
- struct.replacements = removeUnusedReplacements(this.getCombinedHtml(), struct.replacements);
1636
- }
1637
- }
1638
-
1639
- // Loop structures and remove if they have exactly the same content
1640
- // We do this here, because it is possible the user didn't receive any emails, so
1641
- // the merging at time of sending the emails didn't happen (uniqueness happened on email)
1642
- const uniqueStructures: EmailRecipientStruct[] = [];
1643
- for (const struct of structures) {
1644
- let found = false;
1645
- for (const unique of uniqueStructures) {
1646
- const merged = mergeReplacementsIfEqual(unique.replacements, struct.replacements);
1647
- if (merged !== false) {
1648
- unique.replacements = merged;
1649
- found = true;
1650
- break;
1651
- }
1652
- }
1653
-
1654
- if (!found) {
1655
- uniqueStructures.push(struct);
1656
- }
1657
- }
1658
-
1659
- let organizationStruct: BaseOrganization | null = null;
1660
- if (organization) {
1661
- organizationStruct = organization.getBaseStructure();
1662
- }
1663
-
1664
- return EmailWithRecipients.create({
1665
- ...this,
1666
- organization: organizationStruct,
1667
- recipients: uniqueStructures,
1668
-
1669
- // Remove private-like data
1670
- softBouncesCount: 0,
1671
- failedCount: 0,
1672
- emailErrors: null,
1673
- recipientsErrors: null,
1674
- succeededCount: 1,
1675
- emailRecipientsCount: 1,
1676
- hardBouncesCount: 0,
1677
- spamComplaintsCount: 0,
1678
- recipientFilter: EmailRecipientFilter.create({}),
1679
- membersCount: 1,
1680
- otherRecipientsCount: 0,
1681
- });
1682
- }
1683
1456
  }
@@ -1,15 +1,10 @@
1
1
  import { column } from '@simonbackx/simple-database';
2
2
  import { SimpleError } from '@simonbackx/simple-errors';
3
- import type { I18n } from '@stamhoofd/backend-i18n';
4
3
  import { QueryableModel } from '@stamhoofd/sql';
5
- import { appToUri, EmailTemplateType, getAppHost, Recipient, Replacement } from '@stamhoofd/structures';
6
4
  import basex from 'base-x';
7
5
  import crypto from 'crypto';
8
6
  import { v4 as uuidv4 } from 'uuid';
9
- import { sendEmailTemplate } from '../helpers/EmailBuilder.js';
10
- import { Platform } from './Platform.js';
11
7
  import type { User } from './User.js';
12
- import type { Organization } from './Organization.js';
13
8
 
14
9
  const ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';
15
10
  const bs58 = basex(ALPHABET);
@@ -120,11 +115,6 @@ export class EmailVerificationCode extends QueryableModel {
120
115
  this.expiresAt = new Date(new Date().getTime() + 1000 * 60 * 60 * 12);
121
116
  }
122
117
 
123
- getEmailVerificationUrl(user: User, organization: Organization | null, i18n: I18n) {
124
- const host = getAppHost('verify-email', organization, !!user.permissions, i18n);
125
- return 'https://' + host + '?code=' + encodeURIComponent(this.code) + '&token=' + encodeURIComponent(this.token) + '&email=' + encodeURIComponent(this.email);
126
- }
127
-
128
118
  /**
129
119
  * Return true if this token is still valid (used for automatic polling in code view)
130
120
  */
@@ -234,92 +224,6 @@ export class EmailVerificationCode extends QueryableModel {
234
224
  }
235
225
  }
236
226
 
237
- async send(user: User, organization: Organization | null, i18n: I18n, withCode = true) {
238
- const url = this.getEmailVerificationUrl(user, organization, i18n);
239
-
240
- const name = organization?.name ?? (await Platform.getSharedPrivateStruct()).config.name;
241
-
242
- const replacements: Replacement[] = [
243
- Replacement.create({
244
- token: 'organizationName',
245
- value: name,
246
- }),
247
- Replacement.create({
248
- token: 'confirmEmailUrl',
249
- value: url,
250
- }),
251
- ];
252
-
253
- if (withCode) {
254
- const formattedCode = this.code.substr(0, 3) + ' ' + this.code.substr(3);
255
-
256
- await sendEmailTemplate(organization, {
257
- recipients: [
258
- Recipient.create({
259
- email: this.email,
260
- replacements: [
261
- ...replacements,
262
- Replacement.create({
263
- token: 'confirmEmailCode',
264
- value: formattedCode,
265
- }),
266
- ],
267
- }),
268
- ],
269
- template: {
270
- type: EmailTemplateType.VerifyEmail,
271
- },
272
- type: 'transactional',
273
- });
274
- } else {
275
- await sendEmailTemplate(organization, {
276
- recipients: [
277
- Recipient.create({
278
- email: this.email,
279
- replacements,
280
- }),
281
- ],
282
- template: {
283
- type: EmailTemplateType.VerifyEmailWithoutCode,
284
- },
285
- type: 'transactional',
286
- });
287
- }
288
- }
289
-
290
- static async resend(organization: Organization | null, token: string, i18n: I18n) {
291
- const verificationCodes = await this.where({
292
- token,
293
- organizationId: organization
294
- ? {
295
- sign: 'IN',
296
- value: [organization.id, null],
297
- }
298
- : null,
299
- }, { limit: 1 });
300
-
301
- if (verificationCodes.length == 0) {
302
- console.log("Can't resend code, no coded found for token", token);
303
- // TODO: maybe send a note via email
304
- return;
305
- }
306
-
307
- const verificationCode = verificationCodes[0];
308
-
309
- if (verificationCode.expiresAt < new Date()) {
310
- // Don't report error, could be brute forced
311
- console.log("Can't resend code, token is expired", token);
312
- return;
313
- }
314
-
315
- const { User } = await import('./User.js');
316
- const user = await User.getByID(verificationCode.userId);
317
- if (!user) {
318
- return;
319
- }
320
- await verificationCode.send(user, organization, i18n);
321
- }
322
-
323
227
  /**
324
228
  * Create or reuse a verification code for a given email address
325
229
  * If needed, it will update the code.
@@ -4,7 +4,7 @@ import { ArrayDecoder } from '@simonbackx/simple-encoding';
4
4
  import { SimpleError } from '@simonbackx/simple-errors';
5
5
  import { QueryableModel } from '@stamhoofd/sql';
6
6
  import type { ResolutionRequest } from '@stamhoofd/structures';
7
- import { File, Resolution } from '@stamhoofd/structures';
7
+ import { File, Resolution, supportedImageTypes } from '@stamhoofd/structures';
8
8
  import sharp from 'sharp';
9
9
  import { v4 as uuidv4 } from 'uuid';
10
10
 
@@ -51,20 +51,14 @@ export class Image extends QueryableModel {
51
51
  });
52
52
  }
53
53
 
54
- let fileType = 'png';
55
- if (type == 'image/jpeg' || type == 'image/jpg') {
56
- fileType = 'jpg';
57
- }
58
- if (type == 'image/webp') {
59
- fileType = 'webp';
60
- }
61
- if (type === 'image/svg+xml' || type === 'image/svg') {
62
- fileType = 'svg';
63
- }
54
+ // Fall back to png for content types we don't recognize: sharp detects the real format itself, so
55
+ // this only decides how we store the file
56
+ const imageType = (type ? supportedImageTypes.resolveUpload({ contentType: type }) : null) ?? { contentType: 'image/png', extension: 'png' };
57
+ const fileType = imageType.extension;
64
58
 
65
59
  console.log('creating image', fileType, type, resolutions);
66
60
 
67
- const supportsTransparency = fileType == 'png' || fileType == 'svg' || fileType == 'webp';
61
+ const supportsTransparency = fileType !== 'jpg';
68
62
  const promises: Promise<{ data: Buffer;info: sharp.OutputInfo }>[] = [];
69
63
 
70
64
  if (resolutions.length) {
@@ -78,7 +72,7 @@ export class Image extends QueryableModel {
78
72
  width: r.width ?? undefined,
79
73
  height: r.height ?? undefined,
80
74
  fit: r.fit,
81
- withoutEnlargement: type !== 'image/svg+xml',
75
+ withoutEnlargement: fileType !== 'svg',
82
76
  };
83
77
 
84
78
  let t = sharpStream.resize(size);
@@ -181,7 +175,10 @@ export class Image extends QueryableModel {
181
175
  Bucket: STAMHOOFD.SPACES_BUCKET,
182
176
  Key: key,
183
177
  Body: fileContent,
184
- ContentType: type ?? 'image/jpeg',
178
+ // Never store the content type reported by the uploader: this is the only file we store
179
+ // unaltered, so it should never be rendered by a browser
180
+ ContentType: imageType.contentType,
181
+ ContentDisposition: 'attachment',
185
182
  ACL: 'private',
186
183
  });
187
184
  uploadPromises.push(client.send(cmd));