@stamhoofd/models 2.5.0 → 2.6.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 (53) hide show
  1. package/dist/src/migrations/1722845608-registration-stock-reservations.sql +2 -0
  2. package/dist/src/migrations/1722845609-group-stock-reservations.sql +2 -0
  3. package/dist/src/migrations/1722852362-stripe-intents-account-id.sql +2 -0
  4. package/dist/src/migrations/1722852363-stripe-checkout-sessions-account-id.sql +2 -0
  5. package/dist/src/models/BalanceItem.d.ts +1 -0
  6. package/dist/src/models/BalanceItem.d.ts.map +1 -1
  7. package/dist/src/models/BalanceItem.js +36 -43
  8. package/dist/src/models/BalanceItem.js.map +1 -1
  9. package/dist/src/models/DocumentTemplate.js +1 -1
  10. package/dist/src/models/DocumentTemplate.js.map +1 -1
  11. package/dist/src/models/Event.d.ts +7 -0
  12. package/dist/src/models/Event.d.ts.map +1 -1
  13. package/dist/src/models/Event.js +28 -0
  14. package/dist/src/models/Event.js.map +1 -1
  15. package/dist/src/models/Group.d.ts +6 -3
  16. package/dist/src/models/Group.d.ts.map +1 -1
  17. package/dist/src/models/Group.js +29 -6
  18. package/dist/src/models/Group.js.map +1 -1
  19. package/dist/src/models/Member.d.ts +1 -1
  20. package/dist/src/models/Member.d.ts.map +1 -1
  21. package/dist/src/models/Member.js +12 -9
  22. package/dist/src/models/Member.js.map +1 -1
  23. package/dist/src/models/Payment.d.ts +5 -7
  24. package/dist/src/models/Payment.d.ts.map +1 -1
  25. package/dist/src/models/Payment.js +8 -13
  26. package/dist/src/models/Payment.js.map +1 -1
  27. package/dist/src/models/Registration.d.ts +17 -2
  28. package/dist/src/models/Registration.d.ts.map +1 -1
  29. package/dist/src/models/Registration.js +59 -7
  30. package/dist/src/models/Registration.js.map +1 -1
  31. package/dist/src/models/StripeCheckoutSession.d.ts +4 -0
  32. package/dist/src/models/StripeCheckoutSession.d.ts.map +1 -1
  33. package/dist/src/models/StripeCheckoutSession.js +7 -0
  34. package/dist/src/models/StripeCheckoutSession.js.map +1 -1
  35. package/dist/src/models/StripePaymentIntent.d.ts +4 -0
  36. package/dist/src/models/StripePaymentIntent.d.ts.map +1 -1
  37. package/dist/src/models/StripePaymentIntent.js +7 -0
  38. package/dist/src/models/StripePaymentIntent.js.map +1 -1
  39. package/package.json +2 -2
  40. package/src/migrations/1722845608-registration-stock-reservations.sql +2 -0
  41. package/src/migrations/1722845609-group-stock-reservations.sql +2 -0
  42. package/src/migrations/1722852362-stripe-intents-account-id.sql +2 -0
  43. package/src/migrations/1722852363-stripe-checkout-sessions-account-id.sql +2 -0
  44. package/src/models/BalanceItem.ts +40 -46
  45. package/src/models/DocumentTemplate.ts +1 -1
  46. package/src/models/Event.ts +31 -0
  47. package/src/models/Group.ts +36 -14
  48. package/src/models/Member.ts +13 -10
  49. package/src/models/Payment.ts +10 -16
  50. package/src/models/Registration.ts +71 -11
  51. package/src/models/StripeAccount.ts +1 -1
  52. package/src/models/StripeCheckoutSession.ts +6 -0
  53. package/src/models/StripePaymentIntent.ts +6 -0
@@ -1 +1 @@
1
- {"version":3,"file":"StripePaymentIntent.js","sourceRoot":"","sources":["../../../src/models/StripePaymentIntent.ts"],"names":[],"mappings":";;;;AAAA,iEAA2D;AAC3D,+BAAoC;AAEpC,MAAa,mBAAoB,SAAQ,uBAAK;IAA9C;;QAiBI,mBAAc,GAAkB,IAAI,CAAC;IACzC,CAAC;;AAlBD,kDAkBC;AAjBU,yBAAK,GAAG,wBAAwB,AAA3B,CAA4B;AAOxC;IALC,IAAA,wBAAM,EAAC;QACJ,OAAO,EAAE,IAAI,EAAE,IAAI,EAAE,QAAQ,EAAE,UAAU,CAAC,KAAK;YAC3C,OAAO,KAAK,aAAL,KAAK,cAAL,KAAK,GAAI,IAAA,SAAM,GAAE,CAAC;QAC7B,CAAC;KACJ,CAAC;+CACU;AAGZ;IADC,IAAA,wBAAM,EAAC,EAAE,IAAI,EAAE,QAAQ,EAAE,CAAC;sDACT;AAGlB;IADC,IAAA,wBAAM,EAAC,EAAE,IAAI,EAAE,QAAQ,EAAE,CAAC;2DACJ;AAGvB;IADC,IAAA,wBAAM,EAAC,EAAE,IAAI,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,CAAC;2DACN"}
1
+ {"version":3,"file":"StripePaymentIntent.js","sourceRoot":"","sources":["../../../src/models/StripePaymentIntent.ts"],"names":[],"mappings":";;;;AAAA,iEAA2D;AAC3D,+BAAoC;AAEpC,MAAa,mBAAoB,SAAQ,uBAAK;IAA9C;;QAiBI,mBAAc,GAAkB,IAAI,CAAC;QAErC;;WAEG;QAEH,cAAS,GAAgB,IAAI,CAAA;IACjC,CAAC;;AAxBD,kDAwBC;AAvBU,yBAAK,GAAG,wBAAwB,AAA3B,CAA4B;AAOxC;IALC,IAAA,wBAAM,EAAC;QACJ,OAAO,EAAE,IAAI,EAAE,IAAI,EAAE,QAAQ,EAAE,UAAU,CAAC,KAAK;YAC3C,OAAO,KAAK,aAAL,KAAK,cAAL,KAAK,GAAI,IAAA,SAAM,GAAE,CAAC;QAC7B,CAAC;KACJ,CAAC;+CACU;AAGZ;IADC,IAAA,wBAAM,EAAC,EAAE,IAAI,EAAE,QAAQ,EAAE,CAAC;sDACT;AAGlB;IADC,IAAA,wBAAM,EAAC,EAAE,IAAI,EAAE,QAAQ,EAAE,CAAC;2DACJ;AAGvB;IADC,IAAA,wBAAM,EAAC,EAAE,IAAI,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,CAAC;2DACN;AAMrC;IADC,IAAA,wBAAM,EAAC,EAAE,IAAI,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,CAAC;sDACd"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@stamhoofd/models",
3
- "version": "2.5.0",
3
+ "version": "2.6.0",
4
4
  "main": "./dist/src/index.js",
5
5
  "types": "./dist/src/index.d.ts",
6
6
  "license": "UNLICENCED",
@@ -27,5 +27,5 @@
27
27
  "devDependencies": {
28
28
  "@simonbackx/simple-database": "1.24.0"
29
29
  },
30
- "gitHead": "07cc26af0e3036e4ae4309a268fbf57b7f6ac2ed"
30
+ "gitHead": "7a3f9f6c08058dc8b671befbfad73184afdc6d7c"
31
31
  }
@@ -0,0 +1,2 @@
1
+ ALTER TABLE `registrations`
2
+ ADD COLUMN `stockReservations` json NOT NULL DEFAULT ('{"value": [], "version": 0}');
@@ -0,0 +1,2 @@
1
+ ALTER TABLE `groups`
2
+ ADD COLUMN `stockReservations` json NOT NULL DEFAULT ('{"value": [], "version": 0}');
@@ -0,0 +1,2 @@
1
+ ALTER TABLE `stripe_payment_intents`
2
+ ADD COLUMN `accountId` varchar(100) NULL;
@@ -0,0 +1,2 @@
1
+ ALTER TABLE `stripe_checkout_sessions`
2
+ ADD COLUMN `accountId` varchar(100) NULL;
@@ -107,6 +107,12 @@ export class BalanceItem extends Model {
107
107
 
108
108
  async markPaid(payment: Payment, organization: Organization) {
109
109
  // status and pricePaid changes are handled inside balanceitempayment
110
+ if (this.dependingBalanceItemId) {
111
+ const depending = await BalanceItem.getByID(this.dependingBalanceItemId)
112
+ if (depending && depending.status === BalanceItemStatus.Hidden) {
113
+ await BalanceItem.reactivateItems([depending])
114
+ }
115
+ }
110
116
 
111
117
  // If registration
112
118
  if (this.registrationId) {
@@ -115,7 +121,7 @@ export class BalanceItem extends Model {
115
121
 
116
122
  if (registration) {
117
123
  // 1. Mark registration as being valid
118
- if (registration.registeredAt === null) {
124
+ if (registration.registeredAt === null || registration.deactivatedAt) {
119
125
  await registration.markValid()
120
126
 
121
127
  const {Group} = await import("./Group");
@@ -219,72 +225,48 @@ export class BalanceItem extends Model {
219
225
  }
220
226
 
221
227
  static async deleteItems(items: BalanceItem[]) {
222
- const {payments} = await BalanceItem.loadPayments(items)
228
+ const {balanceItemPayments} = await BalanceItem.loadPayments(items)
223
229
 
224
- // Load all balance items
225
- const {balanceItems, balanceItemPayments: allBalanceItemPayments} = await Payment.loadBalanceItems(payments)
226
- for (const payment of payments) {
227
- if (payment.status === PaymentStatus.Succeeded) {
228
- continue;
229
- }
230
- if (!(payment.method === PaymentMethod.PointOfSale || payment.method === PaymentMethod.Transfer || payment.method === PaymentMethod.Unknown)) {
231
- continue;
232
- }
233
- const bip = allBalanceItemPayments.filter(p => p.paymentId == payment.id)
234
- const bis = balanceItems.filter(b => b.status !== BalanceItemStatus.Hidden && bip.find(p => p.balanceItemId == b.id))
235
-
236
- const remainingAfterDelete = bis.filter(b => !items.find(i => i.id == b.id))
237
- if (remainingAfterDelete.length == 0) {
238
- // Delete payment
239
- payment.status = PaymentStatus.Failed
240
- payment._forceUpdatedAt = new Date(1900, 0, 1)
241
- await payment.save()
242
- }
243
- }
230
+ // todo: in the future we could automatically delete payments that are not needed anymore and weren't paid yet -> to prevent leaving ghost payments
231
+ // for now, an admin can manually cancel those payments
232
+ let needsUpdate = false
244
233
 
245
234
  // Set other items to zero (the balance item payments keep the real price)
246
235
  for (const item of items) {
236
+ needsUpdate = needsUpdate || (item.price > 0 && item.status !== BalanceItemStatus.Hidden)
237
+
247
238
  // Don't change status of items that are already paid or are partially paid
248
239
  // Not using item.paidPrice, since this is cached
249
- const bip = allBalanceItemPayments.filter(p => p.balanceItemId == item.id)
250
- const relatedPayments = payments.filter(p => bip.find(b => b.paymentId == p.id))
240
+ const bip = balanceItemPayments.filter(p => p.balanceItemId == item.id)
251
241
 
252
- if (relatedPayments.length === 0 || !relatedPayments.find(p => p.status === PaymentStatus.Succeeded)) {
253
- // No paid payments associated with this item
242
+ if (bip.length === 0) {
243
+ // No payments associated with this item
254
244
  item.status = BalanceItemStatus.Hidden
245
+ item.price = 0
246
+ await item.save()
247
+ } else {
248
+ item.price = 0
255
249
  await item.save()
256
250
  }
257
251
  }
252
+
253
+ if (needsUpdate) {
254
+ await this.updateOutstanding(items)
255
+ }
258
256
  }
259
257
 
260
258
  static async reactivateItems(items: BalanceItem[]) {
261
- // Set other items to zero (the balance item payments keep the real price)
259
+ let needsUpdate = false
262
260
  for (const item of items) {
263
261
  if (item.status === BalanceItemStatus.Hidden) {
264
262
  item.status = BalanceItemStatus.Pending
263
+ needsUpdate = needsUpdate || item.price > 0
265
264
  await item.save()
266
265
  }
267
266
  }
268
267
 
269
- const {payments} = await BalanceItem.loadPayments(items)
270
-
271
- // Load all balance items
272
- const {balanceItems, balanceItemPayments: allBalanceItemPayments} = await Payment.loadBalanceItems(payments)
273
- for (const payment of payments) {
274
- if (payment.status !== PaymentStatus.Failed) {
275
- continue;
276
- }
277
- if (!(payment.method === PaymentMethod.PointOfSale || payment.method === PaymentMethod.Transfer || payment.method === PaymentMethod.Unknown)) {
278
- continue;
279
- }
280
- const bip = allBalanceItemPayments.filter(p => p.paymentId == payment.id)
281
- const bis = balanceItems.filter(b => b.status !== BalanceItemStatus.Hidden && bip.find(p => p.balanceItemId == b.id))
282
-
283
- if (bis.length > 0) {
284
- // Undo failed
285
- payment.status = PaymentStatus.Created
286
- await payment.save()
287
- }
268
+ if (needsUpdate) {
269
+ await this.updateOutstanding(items)
288
270
  }
289
271
  }
290
272
 
@@ -322,6 +304,18 @@ export class BalanceItem extends Model {
322
304
  }
323
305
  }
324
306
 
307
+ static async updateOutstanding(items: BalanceItem[], organizationId?: string) {
308
+ const Member = (await import('./Member')).Member;
309
+
310
+ // Update outstanding amount of related members and registrations
311
+ const memberIds: string[] = Formatter.uniqueArray(items.map(p => p.memberId).filter(id => id !== null)) as any
312
+ await Member.updateOutstandingBalance(memberIds)
313
+
314
+ const {Registration} = await import('./Registration');
315
+ const registrationIds: string[] = Formatter.uniqueArray(items.map(p => p.registrationId).filter(id => id !== null)) as any
316
+ await Registration.updateOutstandingBalance(registrationIds, organizationId)
317
+ }
318
+
325
319
  static async loadPayments(items: BalanceItem[]) {
326
320
  if (items.length == 0) {
327
321
  return {balanceItemPayments: [], payments: []}
@@ -426,7 +426,7 @@ export class DocumentTemplate extends Model {
426
426
 
427
427
  for (const groupDefinition of this.privateSettings.groups) {
428
428
  // Get the registrations for this group with this cycle
429
- const registrations = await Member.getRegistrationWithMembersForGroup(groupDefinition.groupId, groupDefinition.cycle)
429
+ const registrations = await Member.getRegistrationWithMembersForGroup(groupDefinition.groupId)
430
430
 
431
431
  for (const registration of registrations) {
432
432
  const document = await this.generateForRegistration(registration)
@@ -55,6 +55,9 @@ export class Event extends Model {
55
55
  })
56
56
  updatedAt: Date
57
57
 
58
+ /**
59
+ * @deprecated
60
+ */
58
61
  getStructure(group?: Group|null) {
59
62
  return EventStruct.create({
60
63
  ...this,
@@ -62,10 +65,38 @@ export class Event extends Model {
62
65
  })
63
66
  }
64
67
 
68
+ /**
69
+ * @deprecated
70
+ */
65
71
  getPrivateStructure(group?: Group|null) {
66
72
  return EventStruct.create({
67
73
  ...this,
68
74
  group: group ? group.getPrivateStructure() : null
69
75
  })
70
76
  }
77
+
78
+ async syncGroupRequirements(group: Group|null) {
79
+ if (!group) {
80
+ return;
81
+ }
82
+
83
+ group.settings.requireDefaultAgeGroupIds = this.meta.defaultAgeGroupIds ?? []
84
+ group.settings.requireGroupIds = this.meta.groupIds ?? []
85
+
86
+ if (this.organizationId) {
87
+ // This is a not-national event, so require the organization
88
+ group.settings.requireOrganizationIds = this.meta.organizationTagIds ?? []
89
+ group.settings.requireOrganizationTags = []
90
+ group.settings.requirePlatformMembershipOn = null
91
+ } else {
92
+ group.settings.requireOrganizationTags = this.meta.organizationTagIds ?? []
93
+
94
+ // Everyone can register
95
+ group.settings.requireOrganizationIds = []
96
+
97
+ // But they need a valid platform membership
98
+ group.settings.requirePlatformMembershipOn = this.endDate
99
+ }
100
+ await group.save()
101
+ }
71
102
  }
@@ -1,9 +1,11 @@
1
1
  import { column, Database, ManyToOneRelation, Model, OneToManyRelation } from '@simonbackx/simple-database';
2
- import { GroupCategory, GroupPrivateSettings, GroupSettings, GroupStatus, Group as GroupStruct, GroupType } from '@stamhoofd/structures';
2
+ import { GroupCategory, GroupPrivateSettings, GroupSettings, GroupStatus, Group as GroupStruct, GroupType, StockReservation } from '@stamhoofd/structures';
3
3
  import { v4 as uuidv4 } from "uuid";
4
4
 
5
5
  import { Formatter } from '@stamhoofd/utility';
6
6
  import { Member, MemberWithRegistrations, OrganizationRegistrationPeriod, Payment, Registration, User } from './';
7
+ import { QueueHandler } from '@stamhoofd/queues';
8
+ import { ArrayDecoder } from '@simonbackx/simple-encoding';
7
9
 
8
10
  if (Member === undefined) {
9
11
  throw new Error("Import Member is undefined")
@@ -85,17 +87,20 @@ export class Group extends Model {
85
87
  })
86
88
  deletedAt: Date | null = null
87
89
 
88
- /**
89
- * Every time a new registration period starts, this number increases. This is used to mark all older registrations as 'out of date' automatically
90
- */
91
90
  @column({ type: "string" })
92
91
  status = GroupStatus.Open;
93
92
 
93
+ /**
94
+ * Editing this field is only allowed when running inside the QueueHandler
95
+ */
96
+ @column({ type: "json", decoder: new ArrayDecoder(StockReservation) })
97
+ stockReservations: StockReservation[] = []
98
+
94
99
  static async getAll(organizationId: string, periodId: string|null, active = true) {
95
100
  const w: any = periodId ? {periodId} : {}
96
101
  if (active) {
97
102
  // eslint-disable-next-line @typescript-eslint/no-unsafe-argument
98
- return await Group.where({ organizationId, deletedAt: null, ...w, status: {sign: '!=', value: GroupStatus.Archived} })
103
+ return await Group.where({ organizationId, deletedAt: null, ...w })
99
104
  }
100
105
  // eslint-disable-next-line @typescript-eslint/no-unsafe-argument
101
106
  return await Group.where({ organizationId, ...w })
@@ -216,18 +221,13 @@ export class Group extends Model {
216
221
 
217
222
  async updateOccupancy() {
218
223
  this.settings.registeredMembers = await Group.getCount(
219
- "groupId = ? and cycle = ? and waitingList = 0 and registeredAt is not null",
220
- [this.id, this.cycle]
224
+ "groupId = ? and registeredAt is not null AND deactivatedAt is null",
225
+ [this.id]
221
226
  )
222
227
 
223
228
  this.settings.reservedMembers = await Group.getCount(
224
- "groupId = ? and cycle = ? and ((waitingList = 0 and registeredAt is null AND reservedUntil >= ?) OR (waitingList = 1 and canRegister = 1))",
225
- [this.id, this.cycle, new Date()]
226
- )
227
-
228
- this.settings.waitingListSize = await Group.getCount(
229
- "groupId = ? and cycle = ? and waitingList = 1",
230
- [this.id, this.cycle, new Date()]
229
+ "groupId = ? and registeredAt is null AND (canRegister = 1 OR reservedUntil >= ?)",
230
+ [this.id, new Date()]
231
231
  )
232
232
  }
233
233
 
@@ -280,6 +280,28 @@ export class Group extends Model {
280
280
  }
281
281
  }
282
282
 
283
+ static async applyStockReservations(groupId: string, addStockReservations: StockReservation[], free = false) {
284
+ await QueueHandler.schedule('group-stock-update-'+groupId, async () => {
285
+ const updatedGroup = await Group.getByID(groupId)
286
+ if (!updatedGroup) {
287
+ throw new Error("Expected group")
288
+ }
289
+
290
+ if (!free) {
291
+ updatedGroup.stockReservations = StockReservation.added(updatedGroup.stockReservations, addStockReservations)
292
+ } else {
293
+ updatedGroup.stockReservations = StockReservation.removed(updatedGroup.stockReservations, addStockReservations)
294
+ }
295
+ await updatedGroup.save()
296
+ })
297
+
298
+ }
299
+
300
+ static async freeStockReservations(groupId: string, reservations: StockReservation[]) {
301
+ return await this.applyStockReservations(groupId, reservations, true)
302
+ }
303
+
304
+
283
305
  }
284
306
 
285
307
  Registration.group = new ManyToOneRelation(Group, "group")
@@ -1,6 +1,6 @@
1
1
  import { column, Database, ManyToManyRelation, ManyToOneRelation, Model, OneToManyRelation } from '@simonbackx/simple-database';
2
2
  import { SQL } from "@stamhoofd/sql";
3
- import { Member as MemberStruct, MemberDetails, MemberWithRegistrationsBlob, RegistrationWithMember as RegistrationWithMemberStruct, User as UserStruct, GroupStatus } from '@stamhoofd/structures';
3
+ import { Member as MemberStruct, MemberDetails, MemberWithRegistrationsBlob, RegistrationWithMember as RegistrationWithMemberStruct, User as UserStruct, GroupStatus, TinyMember } from '@stamhoofd/structures';
4
4
  import { Formatter, Sorter } from '@stamhoofd/utility';
5
5
  import { v4 as uuidv4 } from "uuid";
6
6
 
@@ -144,7 +144,7 @@ export class Member extends Model {
144
144
  }
145
145
  let query = `SELECT ${Member.getDefaultSelect()}, ${Registration.getDefaultSelect()} from \`${Member.table}\`\n`;
146
146
 
147
- query += `JOIN \`${Registration.table}\` ON \`${Registration.table}\`.\`${Member.registrations.foreignKey}\` = \`${Member.table}\`.\`${Member.primary.name}\` AND (\`${Registration.table}\`.\`registeredAt\` is not null OR \`${Registration.table}\`.\`waitingList\` = 1)\n`
147
+ query += `JOIN \`${Registration.table}\` ON \`${Registration.table}\`.\`${Member.registrations.foreignKey}\` = \`${Member.table}\`.\`${Member.primary.name}\` AND (\`${Registration.table}\`.\`registeredAt\` is not null OR \`${Registration.table}\`.\`canRegister\` = 1)\n`
148
148
 
149
149
  // We do an extra join because we also need to get the other registrations of each member (only one regitration has to match the query)
150
150
  query += `where \`${Registration.table}\`.\`${Registration.primary.name}\` IN (?)`
@@ -177,15 +177,15 @@ export class Member extends Model {
177
177
  /**
178
178
  * Fetch all registrations with members with their corresponding (valid) registrations
179
179
  */
180
- static async getRegistrationWithMembersForGroup(groupId: string, cycle: number): Promise<RegistrationWithMember[]> {
180
+ static async getRegistrationWithMembersForGroup(groupId: string): Promise<RegistrationWithMember[]> {
181
181
  let query = `SELECT ${Member.getDefaultSelect()}, ${Registration.getDefaultSelect()} from \`${Member.table}\`\n`;
182
182
 
183
- query += `JOIN \`${Registration.table}\` ON \`${Registration.table}\`.\`${Member.registrations.foreignKey}\` = \`${Member.table}\`.\`${Member.primary.name}\` AND (\`${Registration.table}\`.\`registeredAt\` is not null OR \`${Registration.table}\`.\`waitingList\` = 1)\n`
183
+ query += `JOIN \`${Registration.table}\` ON \`${Registration.table}\`.\`${Member.registrations.foreignKey}\` = \`${Member.table}\`.\`${Member.primary.name}\` AND (\`${Registration.table}\`.\`registeredAt\` is not null OR \`${Registration.table}\`.\`canRegister\` = 1)\n`
184
184
 
185
185
  // We do an extra join because we also need to get the other registrations of each member (only one regitration has to match the query)
186
- query += `where \`${Registration.table}\`.\`groupId\` = ? AND \`${Registration.table}\`.\`cycle\` = ?`
186
+ query += `where \`${Registration.table}\`.\`groupId\` = ?`
187
187
 
188
- const [results] = await Database.select(query, [groupId, cycle])
188
+ const [results] = await Database.select(query, [groupId])
189
189
  const registrations: RegistrationWithMember[] = []
190
190
 
191
191
  // In the future we might add a 'reverse' method on manytoone relation, instead of defining the new relation. But then we need to store 2 model types in the many to one relation.
@@ -261,7 +261,7 @@ export class Member extends Model {
261
261
  return []
262
262
  }
263
263
  let query = `SELECT ${Member.getDefaultSelect()}, ${Registration.getDefaultSelect()}, ${User.getDefaultSelect()} from \`${Member.table}\`\n`;
264
- query += `LEFT JOIN \`${Registration.table}\` ON \`${Registration.table}\`.\`${Member.registrations.foreignKey}\` = \`${Member.table}\`.\`${Member.primary.name}\` AND (\`${Registration.table}\`.\`registeredAt\` is not null OR \`${Registration.table}\`.\`waitingList\` = 1)\n`
264
+ query += `LEFT JOIN \`${Registration.table}\` ON \`${Registration.table}\`.\`${Member.registrations.foreignKey}\` = \`${Member.table}\`.\`${Member.primary.name}\` AND (\`${Registration.table}\`.\`registeredAt\` is not null OR \`${Registration.table}\`.\`canRegister\` = 1)\n`
265
265
  query += Member.users.joinQuery(Member.table, User.table)+"\n"
266
266
 
267
267
  // We do an extra join because we also need to get the other registrations of each member (only one regitration has to match the query)
@@ -380,7 +380,11 @@ export class Member extends Model {
380
380
  return RegistrationWithMemberStruct.create({
381
381
  ...registration.getStructure(),
382
382
  cycle: registration.cycle,
383
- member: MemberStruct.create(registration.member),
383
+ member: TinyMember.create({
384
+ id: registration.member.id,
385
+ firstName: registration.member.firstName,
386
+ lastName: registration.member.lastName,
387
+ }),
384
388
  })
385
389
  }
386
390
 
@@ -415,10 +419,9 @@ export class Member extends Model {
415
419
  }
416
420
 
417
421
  async updateMemberships(this: MemberWithRegistrations) {
418
- console.log('Updating memberships for member: ' + this.id)
419
422
  return await QueueHandler.schedule('updateMemberships-' + this.id, async () => {
420
423
  const platform = await Platform.getShared()
421
- const registrations = this.registrations.filter(r => r.group.periodId == platform.periodId && !r.waitingList && r.registeredAt && !r.deactivatedAt)
424
+ const registrations = this.registrations.filter(r => r.group.periodId == platform.periodId && r.registeredAt && !r.deactivatedAt)
422
425
 
423
426
  const defaultMemberships = registrations.flatMap(r => {
424
427
  if (!r.group.defaultAgeGroupId) {
@@ -110,39 +110,37 @@ export class Payment extends Model {
110
110
  }
111
111
 
112
112
  const {balanceItemPayments, balanceItems} = await Payment.loadBalanceItems(payments)
113
- const {registrations, orders, members, groups} = await Payment.loadBalanceItemRelations(balanceItems);
113
+ const {registrations, orders, groups} = await Payment.loadBalanceItemRelations(balanceItems);
114
114
 
115
- return this.getGeneralStructureFromRelations({
115
+ return await this.getGeneralStructureFromRelations({
116
116
  payments,
117
117
  registrations,
118
118
  orders,
119
- members,
120
119
  balanceItemPayments,
121
120
  balanceItems,
122
121
  groups
123
122
  }, includeSettlements)
124
123
  }
125
124
 
126
- static getGeneralStructureFromRelations({payments, registrations, orders, members, balanceItemPayments, balanceItems, groups}: {
125
+ static async getGeneralStructureFromRelations({payments, registrations, orders, balanceItemPayments, balanceItems, groups}: {
127
126
  payments: Payment[];
128
- registrations: import("./Registration").Registration[];
127
+ registrations: import("./Member").RegistrationWithMember[];
129
128
  orders: import("./Order").Order[];
130
- members: import("./Member").Member[];
131
129
  balanceItemPayments: import("./BalanceItemPayment").BalanceItemPayment[];
132
130
  balanceItems: import("./BalanceItem").BalanceItem[];
133
131
  groups: import("./Group").Group[];
134
- }, includeSettlements = false): PaymentGeneral[] {
132
+ }, includeSettlements = false): Promise<PaymentGeneral[]> {
135
133
  if (payments.length === 0) {
136
134
  return []
137
135
  }
136
+ const {Member} = (await import("./Member"));
138
137
 
139
138
  return payments.map(payment => {
140
139
  return PaymentGeneral.create({
141
140
  ...payment,
142
141
  balanceItemPayments: balanceItemPayments.filter(item => item.paymentId === payment.id).map((item) => {
143
142
  const balanceItem = balanceItems.find(b => b.id === item.balanceItemId)
144
- const registration = balanceItem?.registrationId && registrations.find(r => r.id === balanceItem.registrationId)
145
- const member = balanceItem?.memberId ? members.find(r => r.id === balanceItem.memberId) : undefined
143
+ const registration = balanceItem?.registrationId ? registrations.find(r => r.id === balanceItem.registrationId) : null
146
144
  const order = balanceItem?.orderId && orders.find(r => r.id === balanceItem.orderId)
147
145
  const group = registration ? groups.find(g => g.id === registration.groupId) : null
148
146
 
@@ -154,8 +152,7 @@ export class Payment extends Model {
154
152
  ...item,
155
153
  balanceItem: BalanceItemDetailed.create({
156
154
  ...balanceItem,
157
- registration: registration ? registration.setRelation(Registration.group, group!).getStructure() : null,
158
- member: member ? MemberStruct.create(member) : null,
155
+ registration: registration ? Member.getRegistrationWithMemberStructure(registration.setRelation(Registration.group, group!)) : null,
159
156
  order: order ? OrderStruct.create({...order, payment: null}) : null
160
157
  })
161
158
  })
@@ -195,22 +192,19 @@ export class Payment extends Model {
195
192
  }
196
193
 
197
194
  static async loadBalanceItemRelations(balanceItems: import("./BalanceItem").BalanceItem[]) {
198
- const {Registration} = await import("./Registration");
199
195
  const {Order} = await import("./Order");
200
196
  const {Member} = await import("./Member");
201
197
 
202
198
  // Load members and orders
203
199
  const registrationIds = Formatter.uniqueArray(balanceItems.flatMap(b => b.registrationId ? [b.registrationId] : []))
204
200
  const orderIds = Formatter.uniqueArray(balanceItems.flatMap(b => b.orderId ? [b.orderId] : []))
205
- const memberIds = Formatter.uniqueArray(balanceItems.flatMap(b => b.memberId ? [b.memberId] : []))
206
201
 
207
- const registrations = await Registration.getByIDs(...registrationIds)
202
+ const registrations = await Member.getRegistrationWithMembersByIDs(registrationIds)
208
203
  const orders = await Order.getByIDs(...orderIds)
209
- const members = await Member.getByIDs(...memberIds)
210
204
 
211
205
  const groupIds = Formatter.uniqueArray(registrations.map(r => r.groupId))
212
206
  const groups = await (await import("./Group")).Group.getByIDs(...groupIds)
213
207
 
214
- return {registrations, orders, members, groups}
208
+ return {registrations, orders, groups}
215
209
  }
216
210
  }
@@ -1,11 +1,13 @@
1
1
  import { column, Database, ManyToOneRelation, Model } from '@simonbackx/simple-database';
2
2
  import { Email } from '@stamhoofd/email';
3
- import { EmailTemplateType, PaymentMethod, PaymentMethodHelper, Recipient, Registration as RegistrationStructure, Replacement } from '@stamhoofd/structures';
3
+ import { EmailTemplateType, PaymentMethod, PaymentMethodHelper, Recipient, Registration as RegistrationStructure, Replacement, StockReservation } from '@stamhoofd/structures';
4
4
  import { Formatter } from '@stamhoofd/utility';
5
5
  import { v4 as uuidv4 } from "uuid";
6
6
 
7
7
  import { getEmailBuilder } from '../helpers/EmailBuilder';
8
- import { Document, EmailTemplate, Organization, User } from './';
8
+ import { Document, EmailTemplate, Group, Organization, User } from './';
9
+ import { ArrayDecoder } from '@simonbackx/simple-encoding';
10
+ import { QueueHandler } from '@stamhoofd/queues';
9
11
 
10
12
  export class Registration extends Model {
11
13
  static table = "registrations"
@@ -69,6 +71,9 @@ export class Registration extends Model {
69
71
  @column({ type: "datetime", nullable: true })
70
72
  reservedUntil: Date | null = null
71
73
 
74
+ /**
75
+ * @deprecated - replaced by group type
76
+ */
72
77
  @column({ type: "boolean" })
73
78
  waitingList = false
74
79
 
@@ -88,6 +93,12 @@ export class Registration extends Model {
88
93
  @column({ type: "integer" })
89
94
  pricePaid = 0
90
95
 
96
+ /**
97
+ * Set to null if no reservations are made, to help faster querying
98
+ */
99
+ @column({ type: "json", decoder: new ArrayDecoder(StockReservation), nullable: true })
100
+ stockReservations: StockReservation[] = []
101
+
91
102
  static group: ManyToOneRelation<"group", import('./Group').Group>
92
103
 
93
104
  getStructure(this: Registration & {group: import('./Group').Group}) {
@@ -101,7 +112,7 @@ export class Registration extends Model {
101
112
  /**
102
113
  * Update the outstanding balance of multiple members in one go (or all members)
103
114
  */
104
- static async updateOutstandingBalance(registrationIds: string[] | 'all', organizationId: string) {
115
+ static async updateOutstandingBalance(registrationIds: string[] | 'all', organizationId?: string) {
105
116
  if (registrationIds !== 'all' && registrationIds.length == 0) {
106
117
  return
107
118
  }
@@ -136,7 +147,7 @@ export class Registration extends Model {
136
147
 
137
148
  await Database.update(query, params)
138
149
 
139
- if (registrationIds !== 'all') {
150
+ if (registrationIds !== 'all' && organizationId) {
140
151
  await Document.updateForRegistrations(registrationIds, organizationId)
141
152
  }
142
153
  }
@@ -149,7 +160,7 @@ export class Registration extends Model {
149
160
  const query = `
150
161
  SELECT COUNT(DISTINCT \`${Registration.table}\`.memberId) as c FROM \`${Registration.table}\`
151
162
  JOIN \`groups\` ON \`groups\`.id = \`${Registration.table}\`.groupId
152
- WHERE \`groups\`.organizationId = ? AND \`${Registration.table}\`.cycle = \`groups\`.cycle AND \`groups\`.deletedAt is null AND \`groups\`.status != 'Archived' AND \`${Registration.table}\`.registeredAt is not null AND \`${Registration.table}\`.waitingList = 0`
163
+ WHERE \`groups\`.organizationId = ? AND \`${Registration.table}\`.cycle = \`groups\`.cycle AND \`groups\`.deletedAt is null AND \`${Registration.table}\`.registeredAt is not null AND \`${Registration.table}\`.deactivatedAt is null`
153
164
 
154
165
  const [results] = await Database.select(query, [organizationId])
155
166
  const count = results[0]['']['c'];
@@ -163,19 +174,17 @@ export class Registration extends Model {
163
174
  }
164
175
 
165
176
  async markValid(this: Registration) {
166
- if (this.registeredAt !== null) {
177
+ if (this.registeredAt !== null && this.deactivatedAt === null) {
167
178
  await this.save();
168
179
  return false;
169
180
  }
170
181
 
171
- if (this.waitingList && this.canRegister) {
172
- this.waitingList = false
173
- }
174
-
175
182
  this.reservedUntil = null
176
- this.registeredAt = new Date()
183
+ this.registeredAt = this.registeredAt ?? new Date()
184
+ this.deactivatedAt = null
177
185
  this.canRegister = false
178
186
  await this.save();
187
+ this.scheduleStockUpdate()
179
188
 
180
189
  await this.sendEmailTemplate({
181
190
  type: EmailTemplateType.RegistrationConfirmation
@@ -408,4 +417,55 @@ export class Registration extends Model {
408
417
 
409
418
  Email.schedule(builder)
410
419
  }
420
+
421
+ shouldIncludeStock() {
422
+ return (this.registeredAt !== null && this.deactivatedAt === null) || this.canRegister || (this.reservedUntil && this.reservedUntil > new Date())
423
+ }
424
+
425
+
426
+
427
+ /**
428
+ * Adds or removes the order to the stock of the webshop (if it wasn't already included). If amounts were changed, only those
429
+ * changes will get added
430
+ * Should always happen in the webshop-stock queue to prevent multiple webshop writes at the same time
431
+ * + in combination with validation and reading the webshop
432
+ */
433
+ scheduleStockUpdate() {
434
+ const id = this.id;
435
+
436
+ QueueHandler.cancel('registration-stock-update-'+id);
437
+ QueueHandler.schedule('registration-stock-update-'+id, async function(this: undefined) {
438
+ const updated = await Registration.getByID(id);
439
+
440
+ if (!updated) {
441
+ return;
442
+ }
443
+
444
+ // Start with clearing all the stock reservations we've already made
445
+ if (updated.stockReservations) {
446
+ const groupIds = Formatter.uniqueArray(updated.stockReservations.flatMap(r => r.objectType === 'Group' ? [r.objectId] : []));
447
+ for (const groupId of groupIds) {
448
+ const stocks = StockReservation.filter('Group', groupId, updated.stockReservations);
449
+
450
+ // Technically we don't need to await this, but okay...
451
+ await Group.freeStockReservations(groupId, stocks);
452
+ }
453
+ }
454
+
455
+ if (updated.shouldIncludeStock()) {
456
+ const myStockReservations: StockReservation[] = [];
457
+
458
+ // todo: build
459
+
460
+ updated.stockReservations = myStockReservations;
461
+ await updated.save();
462
+ } else {
463
+ if (updated.stockReservations.length) {
464
+ updated.stockReservations = [];
465
+ await updated.save();
466
+ }
467
+ }
468
+
469
+ }).catch(console.error)
470
+ }
411
471
  }
@@ -68,4 +68,4 @@ export class StripeAccount extends Model {
68
68
  bank_account_bank_name: account.external_accounts?.data[0]?.bank_name ?? this.meta.bank_account_bank_name ?? "",
69
69
  });
70
70
  }
71
- }
71
+ }
@@ -19,4 +19,10 @@ export class StripeCheckoutSession extends Model {
19
19
 
20
20
  @column({ type: "string", nullable: true })
21
21
  organizationId: string | null = null;
22
+
23
+ /**
24
+ * For direct charges, this should be set
25
+ */
26
+ @column({ type: "string", nullable: true })
27
+ accountId: string|null = null
22
28
  }
@@ -19,4 +19,10 @@ export class StripePaymentIntent extends Model {
19
19
 
20
20
  @column({ type: "string", nullable: true })
21
21
  organizationId: string | null = null;
22
+
23
+ /**
24
+ * For direct charges, this should be set
25
+ */
26
+ @column({ type: "string", nullable: true })
27
+ accountId: string|null = null
22
28
  }