@openpeepshq/core 0.1.35 → 0.2.1

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 (92) hide show
  1. package/dist/accounts/mutations.js +9 -0
  2. package/dist/analytics/report.d.ts +1 -1
  3. package/dist/config/defaults/logs.d.ts +4 -0
  4. package/dist/config/defaults/logs.js +5 -0
  5. package/dist/config/index.d.ts +3 -328
  6. package/dist/db/explorer/index.d.ts +1 -1
  7. package/dist/db/explorer/index.js +1 -1
  8. package/dist/db/pg/filters/posts.js +1 -1
  9. package/dist/db/pg/map/registry.js +3 -2
  10. package/dist/groups/finders.d.ts +2 -2
  11. package/dist/groups/helpers.d.ts +6 -6
  12. package/dist/groups/mapping.d.ts +4 -4
  13. package/dist/jams/export.d.ts +2 -0
  14. package/dist/jams/export.js +5 -0
  15. package/dist/jams/finders.d.ts +1 -0
  16. package/dist/jams/finders.js +1 -0
  17. package/dist/jams/health.d.ts +23 -0
  18. package/dist/jams/health.js +79 -7
  19. package/dist/jams/helpers.d.ts +2 -2
  20. package/dist/jams/index.d.ts +1 -1
  21. package/dist/jams/index.js +10 -3
  22. package/dist/jams/livekit.d.ts +2 -2
  23. package/dist/jams/mapping.d.ts +10 -10
  24. package/dist/jams/mutations.d.ts +2 -2
  25. package/dist/jams/token.js +6 -2
  26. package/dist/jams/waitingRoom.js +3 -1
  27. package/dist/log/index.d.ts +1 -0
  28. package/dist/log/index.js +1 -0
  29. package/dist/log/retention.d.ts +9 -0
  30. package/dist/log/retention.js +83 -0
  31. package/dist/log/retentionJobs.d.ts +17 -0
  32. package/dist/log/retentionJobs.js +50 -0
  33. package/dist/media/garbageCollection.d.ts +109 -0
  34. package/dist/media/garbageCollection.js +603 -0
  35. package/dist/media/garbageCollectionJobs.d.ts +14 -0
  36. package/dist/media/garbageCollectionJobs.js +55 -0
  37. package/dist/media/index.d.ts +2 -0
  38. package/dist/media/index.js +91 -12
  39. package/dist/media/streaming.d.ts +2 -0
  40. package/dist/media/streaming.js +8 -0
  41. package/dist/mediaAttachments/mapping.d.ts +1 -1
  42. package/dist/notifications/defaultNotifications/index.js +2 -0
  43. package/dist/notifications/defaultNotifications/jamModerator/index.js +25 -16
  44. package/dist/notifications/defaultNotifications/jamModerator/recipients.d.ts +2 -0
  45. package/dist/notifications/defaultNotifications/jamModerator/recipients.js +5 -0
  46. package/dist/notifications/defaultNotifications/jamStarted/index.d.ts +1 -0
  47. package/dist/notifications/defaultNotifications/jamStarted/index.js +61 -13
  48. package/dist/notifications/defaultNotifications/newGroupPost/index.js +3 -3
  49. package/dist/notifications/defaultNotifications/newGroupPost/recipients.d.ts +5 -0
  50. package/dist/notifications/defaultNotifications/newGroupPost/recipients.js +23 -0
  51. package/dist/notifications/defaultNotifications/waitlistOffer/index.d.ts +24 -0
  52. package/dist/notifications/defaultNotifications/waitlistOffer/index.js +40 -0
  53. package/dist/notifications/eventIcsAttachment.d.ts +6 -0
  54. package/dist/notifications/eventIcsAttachment.js +32 -0
  55. package/dist/notifications/helpers.d.ts +11 -1
  56. package/dist/notifications/helpers.js +26 -0
  57. package/dist/notifications/index.d.ts +1 -1
  58. package/dist/notifications/index.js +1 -1
  59. package/dist/notifications/jobs.js +6 -0
  60. package/dist/notifications/mutations.js +9 -1
  61. package/dist/plugins/pluginAuth.js +1 -0
  62. package/dist/posts/activity.d.ts +1 -1
  63. package/dist/posts/activity.js +1 -1
  64. package/dist/posts/conversationQueries.d.ts +31 -0
  65. package/dist/posts/conversationQueries.js +150 -24
  66. package/dist/posts/eventAgenda.js +4 -2
  67. package/dist/posts/finders.d.ts +15 -6
  68. package/dist/posts/finders.js +23 -3
  69. package/dist/posts/helpers/index.d.ts +34 -26
  70. package/dist/posts/helpers/index.js +6 -0
  71. package/dist/posts/index.d.ts +3 -1
  72. package/dist/posts/index.js +3 -1
  73. package/dist/posts/mapping.d.ts +112 -98
  74. package/dist/posts/mutations.d.ts +24 -18
  75. package/dist/posts/mutations.js +222 -72
  76. package/dist/posts/rsvpExport.d.ts +47 -0
  77. package/dist/posts/rsvpExport.js +178 -0
  78. package/dist/posts/unseenCounts.d.ts +6 -0
  79. package/dist/posts/unseenCounts.js +51 -1
  80. package/dist/posts/waitlist.d.ts +13 -0
  81. package/dist/posts/waitlist.js +75 -0
  82. package/dist/posts/waitlistOfferJobs.d.ts +10 -0
  83. package/dist/posts/waitlistOfferJobs.js +91 -0
  84. package/dist/profileSettings/mapping.d.ts +1 -0
  85. package/dist/profiles/index.js +6 -1
  86. package/dist/profiles/mapping.d.ts +10 -10
  87. package/dist/reports/mapping.d.ts +1 -1
  88. package/dist/server/index.d.ts +1 -0
  89. package/dist/stats/mapping.d.ts +7 -6
  90. package/dist/stripe/connection.js +1 -1
  91. package/dist/stripe/helpers.js +7 -3
  92. package/package.json +11 -10
@@ -32,7 +32,7 @@ export declare const retractReaction: (post: PostWithMeta, profile: Profile) =>
32
32
  };
33
33
  description?: string | undefined;
34
34
  blurhash?: string | undefined;
35
- status?: "failed" | "processing" | "ready" | undefined;
35
+ status?: "failed" | "ready" | "processing" | undefined;
36
36
  error?: string | undefined;
37
37
  }[] | undefined;
38
38
  customEmojis?: {
@@ -69,7 +69,7 @@ export declare const retractReaction: (post: PostWithMeta, profile: Profile) =>
69
69
  };
70
70
  description?: string | undefined;
71
71
  blurhash?: string | undefined;
72
- status?: "failed" | "processing" | "ready" | undefined;
72
+ status?: "failed" | "ready" | "processing" | undefined;
73
73
  error?: string | undefined;
74
74
  }[] | undefined;
75
75
  customEmojis?: {
@@ -107,7 +107,7 @@ export declare const retractReaction: (post: PostWithMeta, profile: Profile) =>
107
107
  };
108
108
  description?: string | undefined;
109
109
  blurhash?: string | undefined;
110
- status?: "failed" | "processing" | "ready" | undefined;
110
+ status?: "failed" | "ready" | "processing" | undefined;
111
111
  error?: string | undefined;
112
112
  }[] | undefined;
113
113
  customEmojis?: {
@@ -123,6 +123,7 @@ export declare const retractReaction: (post: PostWithMeta, profile: Profile) =>
123
123
  image?: string | undefined;
124
124
  end?: string | undefined;
125
125
  maxAttendees?: number | undefined;
126
+ waitlistOfferMinutes?: number | undefined;
126
127
  attendeeListPublic?: boolean | undefined;
127
128
  moderators?: string[] | undefined;
128
129
  jam?: {
@@ -189,7 +190,7 @@ export declare const retractReaction: (post: PostWithMeta, profile: Profile) =>
189
190
  };
190
191
  description?: string | undefined;
191
192
  blurhash?: string | undefined;
192
- status?: "failed" | "processing" | "ready" | undefined;
193
+ status?: "failed" | "ready" | "processing" | undefined;
193
194
  error?: string | undefined;
194
195
  }[] | undefined;
195
196
  customEmojis?: {
@@ -205,7 +206,7 @@ export declare const retractReaction: (post: PostWithMeta, profile: Profile) =>
205
206
  } | {
206
207
  type: "resource";
207
208
  title: string;
208
- resourceKind: "link" | "file" | "video" | "gallery" | "audio";
209
+ resourceKind: "file" | "link" | "video" | "gallery" | "audio";
209
210
  content?: string | undefined;
210
211
  sensitive?: boolean | undefined;
211
212
  spoilerText?: string | undefined;
@@ -226,7 +227,7 @@ export declare const retractReaction: (post: PostWithMeta, profile: Profile) =>
226
227
  };
227
228
  description?: string | undefined;
228
229
  blurhash?: string | undefined;
229
- status?: "failed" | "processing" | "ready" | undefined;
230
+ status?: "failed" | "ready" | "processing" | undefined;
230
231
  error?: string | undefined;
231
232
  }[] | undefined;
232
233
  customEmojis?: {
@@ -265,7 +266,7 @@ export declare const retractReaction: (post: PostWithMeta, profile: Profile) =>
265
266
  };
266
267
  description?: string | undefined;
267
268
  blurhash?: string | undefined;
268
- status?: "failed" | "processing" | "ready" | undefined;
269
+ status?: "failed" | "ready" | "processing" | undefined;
269
270
  error?: string | undefined;
270
271
  }[] | undefined;
271
272
  customEmojis?: {
@@ -302,7 +303,7 @@ export declare const retractReaction: (post: PostWithMeta, profile: Profile) =>
302
303
  };
303
304
  description?: string | undefined;
304
305
  blurhash?: string | undefined;
305
- status?: "failed" | "processing" | "ready" | undefined;
306
+ status?: "failed" | "ready" | "processing" | undefined;
306
307
  error?: string | undefined;
307
308
  }[] | undefined;
308
309
  customEmojis?: {
@@ -340,7 +341,7 @@ export declare const retractReaction: (post: PostWithMeta, profile: Profile) =>
340
341
  };
341
342
  description?: string | undefined;
342
343
  blurhash?: string | undefined;
343
- status?: "failed" | "processing" | "ready" | undefined;
344
+ status?: "failed" | "ready" | "processing" | undefined;
344
345
  error?: string | undefined;
345
346
  }[] | undefined;
346
347
  customEmojis?: {
@@ -356,6 +357,7 @@ export declare const retractReaction: (post: PostWithMeta, profile: Profile) =>
356
357
  image?: string | undefined;
357
358
  end?: string | undefined;
358
359
  maxAttendees?: number | undefined;
360
+ waitlistOfferMinutes?: number | undefined;
359
361
  attendeeListPublic?: boolean | undefined;
360
362
  moderators?: string[] | undefined;
361
363
  jam?: {
@@ -422,7 +424,7 @@ export declare const retractReaction: (post: PostWithMeta, profile: Profile) =>
422
424
  };
423
425
  description?: string | undefined;
424
426
  blurhash?: string | undefined;
425
- status?: "failed" | "processing" | "ready" | undefined;
427
+ status?: "failed" | "ready" | "processing" | undefined;
426
428
  error?: string | undefined;
427
429
  }[] | undefined;
428
430
  customEmojis?: {
@@ -438,7 +440,7 @@ export declare const retractReaction: (post: PostWithMeta, profile: Profile) =>
438
440
  } | {
439
441
  type: "resource";
440
442
  title: string;
441
- resourceKind: "link" | "file" | "video" | "gallery" | "audio";
443
+ resourceKind: "file" | "link" | "video" | "gallery" | "audio";
442
444
  content?: string | undefined;
443
445
  sensitive?: boolean | undefined;
444
446
  spoilerText?: string | undefined;
@@ -459,7 +461,7 @@ export declare const retractReaction: (post: PostWithMeta, profile: Profile) =>
459
461
  };
460
462
  description?: string | undefined;
461
463
  blurhash?: string | undefined;
462
- status?: "failed" | "processing" | "ready" | undefined;
464
+ status?: "failed" | "ready" | "processing" | undefined;
463
465
  error?: string | undefined;
464
466
  }[] | undefined;
465
467
  customEmojis?: {
@@ -485,8 +487,10 @@ export declare const retractReaction: (post: PostWithMeta, profile: Profile) =>
485
487
  } | {
486
488
  type: "rsvp";
487
489
  data: {
488
- response: "removed" | "no" | "yes" | "tentative";
490
+ response: "no" | "yes" | "tentative" | "removed" | "waitlist";
489
491
  recurrenceId?: string | undefined;
492
+ waitlistJoinedAt?: string | undefined;
493
+ offerExpiresAt?: string | undefined;
490
494
  };
491
495
  } | {
492
496
  type: "reaction";
@@ -515,7 +519,7 @@ export declare const vote: (profile: Profile, post: PostWithMeta, data: Answer)
515
519
  export declare const rsvpRespond: (profile: Profile, post: PostWithMeta, data: RsvpRequest) => Promise<void>;
516
520
  export declare const rsvpManageByOrganizer: (actingProfile: Profile, targetProfile: Profile, post: PostWithMeta, response: Extract<RsvpResponse, "removed" | "yes">, recurrenceId?: string) => Promise<void>;
517
521
  /**
518
- * Remove a profile from a direct-message conversation thread.
522
+ * Remove a profile from a direct-message conversation.
519
523
  *
520
524
  * - Creates a system "X left" post (empty content) with the *remaining*
521
525
  * participants as audience. The leaving user is excluded so future
@@ -526,9 +530,11 @@ export declare const rsvpManageByOrganizer: (actingProfile: Profile, targetProfi
526
530
  * - The conversation post-creation endpoint detects leavers (author not in
527
531
  * their own post's audience) to block further posting and exclude them
528
532
  * from future replies' audience.
529
- * - For 1:1 DMs (no remaining participants), removes the user from every
530
- * post's audience so the thread vanishes from their inbox.
531
- * - The leaving user can still find the thread in the "Archived" conversations
532
- * tab, detected by posts they authored but are not in.
533
+ * - A 1:1 conversation can span several roots, so each root's thread gets
534
+ * its own "left" post — otherwise the leaver's inbox would keep the
535
+ * threads whose newest post is still in their audience.
536
+ * - When the newest post's audience holds no one but the leaver (everyone
537
+ * else already left), removes the leaver from every post's audience of
538
+ * that root's thread instead of posting again.
533
539
  */
534
540
  export declare const leaveConversation: (rootPost: PostWithMeta, profile: ProfileWithMeta) => Promise<void>;
@@ -7,17 +7,19 @@ import { audienceConnector, bookmarkConnector, bookmarkDisconnector, entryConnec
7
7
  import { postsMapping, repostRelation } from './mapping.js';
8
8
  import { bumpConversationActivity } from './activity.js';
9
9
  import { findGroup } from '../groups/finders.js';
10
- import { findLatestThreadPostId } from './conversationQueries.js';
11
- import { findPostsForAuth } from './finders.js';
10
+ import { findLatestThreadPostId, listOneToOneConversationRootLeaves, } from './conversationQueries.js';
11
+ import { findPost, findPostsForAuth } from './finders.js';
12
12
  import { profilesCache } from '../profiles/cache.js';
13
13
  import { findOrCreateHashtag } from '../hashtags/index.js';
14
14
  import { hub } from '../events/index.js';
15
15
  import { listUnseenGroupPostIds } from './unseenCounts.js';
16
- import { AP_LIKE_REACTION, canManageEventRsvps, countYesRsvps, eventDataForDbUpdate, getEffectiveRsvp, instanceRsvpIdsForProfile, overlaySeriesRsvpEntries, normalizeEventDataForSave, passThroughUndefined, rsvpCancelNotice, sameRecurrenceId, seriesYesBlockedByCapacity, } from '@openpeepshq/common/lib';
16
+ import { AP_LIKE_REACTION, canManageEventRsvps, capacityRsvpDecision, eventDataForDbUpdate, getEffectiveRsvp, instanceRsvpIdsForProfile, isOneToOneDm, normalizeEventDataForSave, overlaySeriesRsvpEntries, participantIds, passThroughUndefined, rsvpCancelNotice, sameRecurrenceId, } from '@openpeepshq/common/lib';
17
17
  import { forbidden, unprocessableRequest } from '../errors/index.js';
18
18
  import { areBlocked, hasBlockAmong } from '../profiles/blocks.js';
19
19
  import { rebuildEventOccurrences, clearEventOccurrences, } from './eventOccurrences.js';
20
20
  import { cancelPollEnd, schedulePollEnd } from './pollEndJobs.js';
21
+ import { publishWaitlistPlans } from './waitlistOfferJobs.js';
22
+ import { capacitySyncTargets, syncCapacityOccurrences, withRsvpCapacityLock, } from './waitlist.js';
21
23
  import { config } from '../config/index.js';
22
24
  import { localObjectScalars } from '../federation/identity.js';
23
25
  export const createPost = async (data, profile, postData, relations = {}) => {
@@ -137,15 +139,13 @@ export const updatePost = async (post, profile, data) => {
137
139
  else {
138
140
  await cancelPollEnd(post.id);
139
141
  }
140
- hub.emit('postUpdated', newPost);
142
+ hub.emit('postUpdated', newPost, previousEvent?.jam?.moderators ?? []);
141
143
  return newPost;
142
144
  };
143
145
  export const reactToPost = async (post, profile, data) => allpeepDb().then(({ db }) => entryConnector(db, profile, post, {
144
146
  type: 'reaction',
145
147
  data: { reaction: data.reaction },
146
- })
147
- .then(() => bumpConversationActivity(db, post.id))
148
- .then(() => hub.emit('reactionCreated', profile, post, {
148
+ }).then(() => hub.emit('reactionCreated', profile, post, {
149
149
  type: 'reaction',
150
150
  ...data,
151
151
  })));
@@ -211,6 +211,40 @@ const rsvpOccurrenceIds = (data) => {
211
211
  return [data.recurrenceId];
212
212
  return undefined;
213
213
  };
214
+ const latestOwnResponse = (post, profileId, occurrenceIds) => {
215
+ const previousResponses = occurrenceIds
216
+ ? occurrenceIds.map((id) => getEffectiveRsvp(post, profileId, id)?.response)
217
+ : undefined;
218
+ if (previousResponses) {
219
+ return previousResponses.every(attendingRsvp)
220
+ ? previousResponses[0]
221
+ : previousResponses.find((response) => !attendingRsvp(response));
222
+ }
223
+ return [...(post.rsvps ?? [])]
224
+ .filter((rsvp) => rsvp.profile.id === profileId)
225
+ .filter((rsvp) => !rsvp.recurrenceId)
226
+ .sort((a, b) => (a.createdAt < b.createdAt ? 1 : -1))[0]?.response;
227
+ };
228
+ const rsvpWrites = (post, profileId, response, occurrenceIds) => {
229
+ if (response === 'waitlist') {
230
+ const waitlistJoinedAt = new Date().toISOString();
231
+ return occurrenceIds?.length
232
+ ? occurrenceIds.map((recurrenceId) => ({
233
+ response,
234
+ recurrenceId,
235
+ waitlistJoinedAt,
236
+ }))
237
+ : [{ response, waitlistJoinedAt }];
238
+ }
239
+ return occurrenceIds
240
+ ? occurrenceIds.map((recurrenceId) => ({ response, recurrenceId }))
241
+ : overlaySeriesRsvpEntries(response, instanceRsvpIdsForProfile(post, profileId));
242
+ };
243
+ const publishCapacityPlans = async (postId, fromProfileId, plans) => {
244
+ if (!plans.length)
245
+ return;
246
+ await publishWaitlistPlans(postId, fromProfileId, plans).catch(() => undefined);
247
+ };
214
248
  export const rsvpRespond = async (profile, post, data) => {
215
249
  if (profile.id === post.profile.id) {
216
250
  return;
@@ -224,64 +258,106 @@ export const rsvpRespond = async (profile, post, data) => {
224
258
  if (data.response === 'removed') {
225
259
  throw forbidden({ errorKey: 'error.rsvpRemovedForbidden' });
226
260
  }
227
- if (getEffectiveRsvp(post, profile.id)?.response === 'removed') {
228
- throw forbidden({ errorKey: 'error.rsvpRemoved' });
229
- }
230
261
  const occurrenceIds = rsvpOccurrenceIds(data);
231
- const maxAttendees = post.data.maxAttendees;
232
- if (maxAttendees) {
233
- if (data.response === 'tentative') {
234
- throw unprocessableRequest({
235
- errorKey: 'error.eventTentativeNotAllowed',
236
- });
262
+ if (!post.data.maxAttendees) {
263
+ if (getEffectiveRsvp(post, profile.id)?.response === 'removed') {
264
+ throw forbidden({ errorKey: 'error.rsvpRemoved' });
237
265
  }
238
- if (data.response === 'yes') {
239
- if (!occurrenceIds && post.data.recurrence) {
240
- if (seriesYesBlockedByCapacity(post, profile.id)) {
241
- throw unprocessableRequest({ errorKey: 'error.eventAtCapacity' });
242
- }
266
+ if (data.response === 'waitlist') {
267
+ throw unprocessableRequest({ errorKey: 'error.eventWaitlistNotOpen' });
268
+ }
269
+ await writeRsvpResponse(profile, post, data.response, occurrenceIds);
270
+ return;
271
+ }
272
+ const plans = [];
273
+ let emitted;
274
+ let failure;
275
+ try {
276
+ await withRsvpCapacityLock(post.id, async () => {
277
+ const loaded = await findPost(post.id);
278
+ if (!loaded || loaded.data?.type !== 'event') {
279
+ throw unprocessableRequest({ errorKey: 'error.unprocessableRequest' });
243
280
  }
244
- else {
245
- const ids = occurrenceIds ?? [undefined];
246
- for (const recurrenceId of ids) {
247
- const currentRsvp = getEffectiveRsvp(post, profile.id, recurrenceId);
248
- if (currentRsvp?.response !== 'yes' &&
249
- countYesRsvps(post, recurrenceId) >= maxAttendees) {
250
- throw unprocessableRequest({ errorKey: 'error.eventAtCapacity' });
251
- }
252
- }
281
+ if (getEffectiveRsvp(loaded, profile.id)?.response === 'removed') {
282
+ throw forbidden({ errorKey: 'error.rsvpRemoved' });
253
283
  }
254
- }
284
+ const prepared = await syncCapacityOccurrences(loaded.id, capacitySyncTargets(loaded, occurrenceIds));
285
+ plans.push(...prepared.plans);
286
+ const fresh = prepared.post;
287
+ if (!fresh || fresh.data?.type !== 'event') {
288
+ throw unprocessableRequest({ errorKey: 'error.unprocessableRequest' });
289
+ }
290
+ const decision = capacityRsvpDecision(fresh, profile.id, data.response, occurrenceIds);
291
+ if (!decision.ok) {
292
+ throw unprocessableRequest({ errorKey: decision.errorKey });
293
+ }
294
+ if (decision.occurrenceIds && decision.occurrenceIds.length === 0) {
295
+ return;
296
+ }
297
+ const writeIds = decision.occurrenceIds;
298
+ const previousResponse = latestOwnResponse(fresh, profile.id, writeIds);
299
+ const writes = rsvpWrites(fresh, profile.id, data.response, writeIds);
300
+ const { db } = await allpeepDb();
301
+ for (const entry of writes) {
302
+ await entryConnector(db, profile, fresh, {
303
+ type: 'rsvp',
304
+ data: entry,
305
+ });
306
+ }
307
+ const cancel = rsvpCancelNotice(fresh, profile.id, data.response, writeIds);
308
+ const settled = await syncCapacityOccurrences(fresh.id, capacitySyncTargets(fresh, writeIds));
309
+ plans.push(...settled.plans);
310
+ if (data.response === 'yes') {
311
+ const claimed = writeIds?.length ? writeIds : [undefined];
312
+ plans.push({
313
+ requeues: [],
314
+ withdraws: [],
315
+ offers: [],
316
+ clearOffers: claimed.map((recurrenceId) => ({
317
+ profileId: profile.id,
318
+ recurrenceId,
319
+ })),
320
+ });
321
+ }
322
+ emitted = { previousResponse, occurrenceIds: writeIds, cancel };
323
+ });
255
324
  }
256
- const { db } = await allpeepDb();
257
- const previousResponses = occurrenceIds
258
- ? occurrenceIds.map((id) => getEffectiveRsvp(post, profile.id, id)?.response)
259
- : undefined;
260
- const previousResponse = previousResponses
261
- ? previousResponses.every(attendingRsvp)
262
- ? previousResponses[0]
263
- : previousResponses.find((response) => !attendingRsvp(response))
264
- : [...(post.rsvps ?? [])]
265
- .filter((rsvp) => rsvp.profile.id === profile.id)
266
- .filter((rsvp) => !rsvp.recurrenceId)
267
- .sort((a, b) => (a.createdAt < b.createdAt ? 1 : -1))[0]?.response;
268
- const writes = occurrenceIds
269
- ? occurrenceIds.map((recurrenceId) => ({
325
+ catch (err) {
326
+ failure = err;
327
+ }
328
+ await publishCapacityPlans(post.id, post.profile.id, plans);
329
+ if (failure)
330
+ throw failure;
331
+ if (!emitted)
332
+ return;
333
+ hub.emit('rsvpCreated', profile, post, {
334
+ type: 'rsvp',
335
+ data: {
270
336
  response: data.response,
271
- recurrenceId,
272
- }))
273
- : overlaySeriesRsvpEntries(data.response, instanceRsvpIdsForProfile(post, profile.id));
337
+ ...(emitted.occurrenceIds?.length === 1
338
+ ? { recurrenceId: emitted.occurrenceIds[0] }
339
+ : {}),
340
+ },
341
+ occurrenceIds: emitted.occurrenceIds,
342
+ previousResponse: emitted.previousResponse,
343
+ ...(emitted.cancel ? { cancel: emitted.cancel } : {}),
344
+ });
345
+ };
346
+ const writeRsvpResponse = async (profile, post, response, occurrenceIds) => {
347
+ const previousResponse = latestOwnResponse(post, profile.id, occurrenceIds);
348
+ const writes = rsvpWrites(post, profile.id, response, occurrenceIds);
349
+ const { db } = await allpeepDb();
274
350
  for (const entry of writes) {
275
351
  await entryConnector(db, profile, post, {
276
352
  type: 'rsvp',
277
353
  data: entry,
278
354
  });
279
355
  }
280
- const cancel = rsvpCancelNotice(post, profile.id, data.response, occurrenceIds);
356
+ const cancel = rsvpCancelNotice(post, profile.id, response, occurrenceIds);
281
357
  hub.emit('rsvpCreated', profile, post, {
282
358
  type: 'rsvp',
283
359
  data: {
284
- response: data.response,
360
+ response,
285
361
  ...(occurrenceIds?.length === 1
286
362
  ? { recurrenceId: occurrenceIds[0] }
287
363
  : {}),
@@ -298,30 +374,80 @@ export const rsvpManageByOrganizer = async (actingProfile, targetProfile, post,
298
374
  if (targetProfile.id === post.profile.id) {
299
375
  throw forbidden({ errorKey: 'forbidden' });
300
376
  }
301
- if (post.type !== 'event') {
377
+ if (post.type !== 'event' || post.data?.type !== 'event') {
302
378
  throw unprocessableRequest({ errorKey: 'error.unprocessableRequest' });
303
379
  }
304
380
  const data = { response, recurrenceId };
305
- const { db } = await allpeepDb();
306
- const previousResponse = [...(post.rsvps ?? [])]
307
- .filter((rsvp) => rsvp.profile.id === targetProfile.id)
308
- .filter((rsvp) => recurrenceId
309
- ? sameRecurrenceId(rsvp.recurrenceId, recurrenceId) ||
310
- !rsvp.recurrenceId
311
- : !rsvp.recurrenceId)
312
- .sort((a, b) => (a.createdAt < b.createdAt ? 1 : -1))[0]?.response;
313
- await entryConnector(db, targetProfile, post, {
314
- type: 'rsvp',
315
- data,
316
- });
381
+ // Capacity events now enforce waitlist capacity checks even for organizer-managed
382
+ // RSVPs: an organizer cannot force 'yes' beyond the capacity window when the
383
+ // waitlist is active. Non-capacity events skip the lock entirely.
384
+ const capacity = !!post.data.maxAttendees;
385
+ if (!capacity) {
386
+ const { db } = await allpeepDb();
387
+ const previousResponse = organizerPreviousResponse(post, targetProfile.id, recurrenceId);
388
+ await entryConnector(db, targetProfile, post, { type: 'rsvp', data });
389
+ hub.emit('rsvpCreated', targetProfile, post, {
390
+ type: 'rsvp',
391
+ data,
392
+ previousResponse,
393
+ });
394
+ return;
395
+ }
396
+ const plans = [];
397
+ let previousResponse;
398
+ let failure;
399
+ try {
400
+ await withRsvpCapacityLock(post.id, async () => {
401
+ const loaded = await findPost(post.id);
402
+ if (!loaded || loaded.data?.type !== 'event') {
403
+ throw unprocessableRequest({ errorKey: 'error.unprocessableRequest' });
404
+ }
405
+ const targets = capacitySyncTargets(loaded, recurrenceId ? [recurrenceId] : undefined);
406
+ const prepared = await syncCapacityOccurrences(loaded.id, targets);
407
+ plans.push(...prepared.plans);
408
+ const fresh = prepared.post ?? loaded;
409
+ if (response === 'yes') {
410
+ const decision = capacityRsvpDecision(fresh, targetProfile.id, 'yes', recurrenceId ? [recurrenceId] : undefined);
411
+ if (!decision.ok) {
412
+ throw unprocessableRequest({ errorKey: decision.errorKey });
413
+ }
414
+ }
415
+ previousResponse = organizerPreviousResponse(fresh, targetProfile.id, recurrenceId);
416
+ const { db } = await allpeepDb();
417
+ await entryConnector(db, targetProfile, fresh, { type: 'rsvp', data });
418
+ const settled = await syncCapacityOccurrences(fresh.id, targets);
419
+ plans.push(...settled.plans);
420
+ if (response === 'yes') {
421
+ plans.push({
422
+ requeues: [],
423
+ withdraws: [],
424
+ offers: [],
425
+ clearOffers: [{ profileId: targetProfile.id, recurrenceId }],
426
+ });
427
+ }
428
+ });
429
+ }
430
+ catch (err) {
431
+ failure = err;
432
+ }
433
+ await publishCapacityPlans(post.id, post.profile.id, plans);
434
+ if (failure)
435
+ throw failure;
317
436
  hub.emit('rsvpCreated', targetProfile, post, {
318
437
  type: 'rsvp',
319
438
  data,
320
439
  previousResponse,
321
440
  });
322
441
  };
442
+ const organizerPreviousResponse = (post, profileId, recurrenceId) => [...(post.rsvps ?? [])]
443
+ .filter((rsvp) => rsvp.profile.id === profileId)
444
+ .filter((rsvp) => recurrenceId
445
+ ? sameRecurrenceId(rsvp.recurrenceId, recurrenceId) ||
446
+ !rsvp.recurrenceId
447
+ : !rsvp.recurrenceId)
448
+ .sort((a, b) => (a.createdAt < b.createdAt ? 1 : -1))[0]?.response;
323
449
  /**
324
- * Remove a profile from a direct-message conversation thread.
450
+ * Remove a profile from a direct-message conversation.
325
451
  *
326
452
  * - Creates a system "X left" post (empty content) with the *remaining*
327
453
  * participants as audience. The leaving user is excluded so future
@@ -332,29 +458,53 @@ export const rsvpManageByOrganizer = async (actingProfile, targetProfile, post,
332
458
  * - The conversation post-creation endpoint detects leavers (author not in
333
459
  * their own post's audience) to block further posting and exclude them
334
460
  * from future replies' audience.
335
- * - For 1:1 DMs (no remaining participants), removes the user from every
336
- * post's audience so the thread vanishes from their inbox.
337
- * - The leaving user can still find the thread in the "Archived" conversations
338
- * tab, detected by posts they authored but are not in.
461
+ * - A 1:1 conversation can span several roots, so each root's thread gets
462
+ * its own "left" post — otherwise the leaver's inbox would keep the
463
+ * threads whose newest post is still in their audience.
464
+ * - When the newest post's audience holds no one but the leaver (everyone
465
+ * else already left), removes the leaver from every post's audience of
466
+ * that root's thread instead of posting again.
339
467
  */
340
468
  export const leaveConversation = async (rootPost, profile) => {
341
469
  const { db } = await allpeepDb();
342
- const lastPostId = await findLatestThreadPostId(rootPost.id);
470
+ const participants = [...participantIds(rootPost)];
471
+ const isOneToOne = isOneToOneDm(rootPost);
472
+ const rootLeaves = isOneToOne
473
+ ? await listOneToOneConversationRootLeaves(db, participants[0], participants[1])
474
+ : [];
475
+ const lastPostId = rootLeaves.length
476
+ ? rootLeaves.reduce((latest, { leafId }) => (leafId > latest ? leafId : latest), rootPost.id)
477
+ : await findLatestThreadPostId(rootPost.id);
343
478
  const [lastPost] = lastPostId === rootPost.id
344
479
  ? [rootPost]
345
480
  : await findPostsForAuth([lastPostId]);
346
481
  if (!lastPost)
347
482
  return;
348
483
  const remainingAudience = lastPost.audience?.filter((p) => p.id !== profile.id) ?? [];
349
- if (remainingAudience.length > 0) {
484
+ if (isOneToOne) {
485
+ // Terminate every root's thread with the system "left" post so the
486
+ // conversation vanishes from the leaver's inbox under all roots. The
487
+ // fallback below covers a pair whose root does not match the pair
488
+ // condition (e.g. legacy rows) and falls back to the requested thread.
489
+ const leaves = rootLeaves.length
490
+ ? rootLeaves
491
+ : [{ rootId: rootPost.id, leafId: lastPostId }];
492
+ for (const { leafId } of leaves) {
493
+ await createPost({ type: 'note', content: '' }, profile, { type: 'note', visibility: 'direct', creatorId: profile.id }, {
494
+ inReplyToId: leafId,
495
+ audience: remainingAudience,
496
+ });
497
+ }
498
+ }
499
+ else if (remainingAudience.length > 0) {
350
500
  await createPost({ type: 'note', content: '' }, profile, { type: 'note', visibility: 'direct', creatorId: profile.id }, {
351
501
  inReplyToId: lastPost.id,
352
502
  audience: remainingAudience,
353
503
  });
354
504
  }
355
505
  else {
356
- // 1:1 DM — remove the user from every post's audience so the
357
- // thread no longer appears in their inbox.
506
+ // No one remains in the newest post's audience — remove the leaver from
507
+ // every post's audience so the thread no longer appears in their inbox.
358
508
  await db.execute(sql `
359
509
  WITH RECURSIVE t AS (
360
510
  SELECT ${rootPost.id}::text AS id, 0 AS depth
@@ -0,0 +1,47 @@
1
+ import type { Event, PublicPost, RsvpResponse } from '@openpeepshq/common/types';
2
+ export type RsvpAttendanceLabel = 'attended' | 'registered' | 'no-show' | '';
3
+ /**
4
+ * Join records are the attendance log. Until someone has joined, the column
5
+ * stays off so a jam that has not started is not full of invented no-shows.
6
+ */
7
+ export declare const rsvpAttendanceLabel: (input: {
8
+ response: RsvpResponse;
9
+ attended: boolean;
10
+ eventEnded: boolean;
11
+ }) => RsvpAttendanceLabel;
12
+ /**
13
+ * Member email lives on the controlling account, and more than one account
14
+ * can control a profile. Guests store the address they typed on the profile.
15
+ */
16
+ export declare const rsvpContactEmail: (input: {
17
+ profileType: string | undefined;
18
+ guestEmail: string;
19
+ accountEmails: readonly string[];
20
+ }) => string;
21
+ export declare const rsvpExportEventEnded: (event: Event, occurrenceId: string | undefined, now: Date) => boolean;
22
+ export type RsvpExportRow = {
23
+ name: string;
24
+ email: string;
25
+ status: RsvpResponse;
26
+ rsvpAt: string;
27
+ memberId: string;
28
+ occurrence: string;
29
+ attendance: RsvpAttendanceLabel;
30
+ };
31
+ type RsvpExportColumns = {
32
+ includeOccurrence: boolean;
33
+ includeAttendance: boolean;
34
+ };
35
+ export declare const rsvpExportCsv: (rows: RsvpExportRow[], columns: RsvpExportColumns) => string;
36
+ export declare const assembleRsvpExportCsv: (input: {
37
+ post: PublicPost;
38
+ occurrenceId?: string;
39
+ emailsByProfileId: ReadonlyMap<string, string>;
40
+ attendeeIds?: ReadonlySet<string>;
41
+ now?: Date;
42
+ }) => string;
43
+ export declare const exportEventRsvpsCsv: (post: PublicPost, options?: {
44
+ occurrenceId?: string;
45
+ now?: Date;
46
+ }) => Promise<string>;
47
+ export {};