@openpeepshq/core 0.2.0 → 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 (58) hide show
  1. package/LICENSE +674 -0
  2. package/dist/accounts/mutations.js +9 -0
  3. package/dist/config/index.d.ts +3 -336
  4. package/dist/db/explorer/index.d.ts +1 -1
  5. package/dist/db/explorer/index.js +1 -1
  6. package/dist/db/pg/map/registry.js +3 -2
  7. package/dist/jams/export.d.ts +2 -0
  8. package/dist/jams/export.js +5 -0
  9. package/dist/jams/finders.d.ts +1 -0
  10. package/dist/jams/finders.js +1 -0
  11. package/dist/jams/health.d.ts +23 -0
  12. package/dist/jams/health.js +79 -7
  13. package/dist/jams/index.d.ts +1 -1
  14. package/dist/jams/index.js +10 -3
  15. package/dist/jams/token.js +6 -2
  16. package/dist/jams/waitingRoom.js +3 -1
  17. package/dist/media/garbageCollection.d.ts +109 -0
  18. package/dist/media/garbageCollection.js +603 -0
  19. package/dist/media/garbageCollectionJobs.d.ts +14 -0
  20. package/dist/media/garbageCollectionJobs.js +55 -0
  21. package/dist/media/index.d.ts +2 -0
  22. package/dist/media/index.js +4 -2
  23. package/dist/media/streaming.d.ts +2 -0
  24. package/dist/media/streaming.js +8 -0
  25. package/dist/notifications/defaultNotifications/index.js +2 -0
  26. package/dist/notifications/defaultNotifications/jamStarted/index.d.ts +1 -0
  27. package/dist/notifications/defaultNotifications/jamStarted/index.js +61 -13
  28. package/dist/notifications/defaultNotifications/waitlistOffer/index.d.ts +24 -0
  29. package/dist/notifications/defaultNotifications/waitlistOffer/index.js +40 -0
  30. package/dist/notifications/index.d.ts +1 -1
  31. package/dist/notifications/index.js +1 -1
  32. package/dist/plugins/pluginAuth.js +1 -0
  33. package/dist/posts/conversationQueries.d.ts +31 -0
  34. package/dist/posts/conversationQueries.js +150 -24
  35. package/dist/posts/finders.d.ts +9 -0
  36. package/dist/posts/finders.js +23 -3
  37. package/dist/posts/helpers/index.d.ts +10 -2
  38. package/dist/posts/helpers/index.js +6 -0
  39. package/dist/posts/index.d.ts +3 -1
  40. package/dist/posts/index.js +3 -1
  41. package/dist/posts/mapping.d.ts +14 -0
  42. package/dist/posts/mutations.d.ts +12 -6
  43. package/dist/posts/mutations.js +220 -68
  44. package/dist/posts/rsvpExport.d.ts +47 -0
  45. package/dist/posts/rsvpExport.js +178 -0
  46. package/dist/posts/unseenCounts.d.ts +6 -0
  47. package/dist/posts/unseenCounts.js +51 -1
  48. package/dist/posts/waitlist.d.ts +13 -0
  49. package/dist/posts/waitlist.js +75 -0
  50. package/dist/posts/waitlistOfferJobs.d.ts +10 -0
  51. package/dist/posts/waitlistOfferJobs.js +91 -0
  52. package/dist/profiles/index.js +6 -1
  53. package/dist/reports/mapping.d.ts +1 -1
  54. package/dist/server/index.d.ts +1 -0
  55. package/dist/stats/mapping.d.ts +1 -0
  56. package/dist/stripe/connection.js +1 -1
  57. package/dist/stripe/helpers.js +7 -3
  58. package/package.json +10 -9
@@ -3,11 +3,13 @@ export * from './mutations';
3
3
  export * from './mapping';
4
4
  export { CONTEXT_NODE_CAP, collectReplyClosureIds, loadReplyContextPosts, } from './contextClosure';
5
5
  export { loadThreadPreviewReplies, THREAD_PREVIEW_LIMIT, } from './threadPreview';
6
- export { listConversationPreviews, getConversationThread, findLatestThreadPostId, listLeftConversations, } from './conversationQueries';
6
+ export { listConversationPreviews, getConversationThread, getOneToOneConversation, listOneToOneConversationPostIds, listOneToOneConversationRootLeaves, findLatestThreadPostId, listLeftConversations, } from './conversationQueries';
7
7
  export * from './helpers';
8
8
  export { bumpConversationActivity, findReplyRootId } from './activity';
9
9
  export { registerRsvpConfirmationEmail } from './rsvpConfirmationEmail';
10
+ export { exportEventRsvpsCsv } from './rsvpExport';
10
11
  export { rebuildEventOccurrences, clearEventOccurrences, backfillMissingEventOccurrences, rebuildRecurringEventOccurrences, } from './eventOccurrences';
11
12
  export { listEventAgenda } from './eventAgenda';
12
13
  export { eventOccurrenceQueue, eventOccurrenceWorker, ensureEventOccurrenceSchedule, } from './eventOccurrenceJobs';
13
14
  export { pollEndQueue, pollEndWorker, schedulePollEnd, cancelPollEnd, } from './pollEndJobs';
15
+ export { waitlistOfferQueue, waitlistOfferWorker } from './waitlistOfferJobs';
@@ -3,11 +3,13 @@ export * from './mutations.js';
3
3
  export * from './mapping.js';
4
4
  export { CONTEXT_NODE_CAP, collectReplyClosureIds, loadReplyContextPosts, } from './contextClosure.js';
5
5
  export { loadThreadPreviewReplies, THREAD_PREVIEW_LIMIT, } from './threadPreview.js';
6
- export { listConversationPreviews, getConversationThread, findLatestThreadPostId, listLeftConversations, } from './conversationQueries.js';
6
+ export { listConversationPreviews, getConversationThread, getOneToOneConversation, listOneToOneConversationPostIds, listOneToOneConversationRootLeaves, findLatestThreadPostId, listLeftConversations, } from './conversationQueries.js';
7
7
  export * from './helpers/index.js';
8
8
  export { bumpConversationActivity, findReplyRootId } from './activity.js';
9
9
  export { registerRsvpConfirmationEmail } from './rsvpConfirmationEmail.js';
10
+ export { exportEventRsvpsCsv } from './rsvpExport.js';
10
11
  export { rebuildEventOccurrences, clearEventOccurrences, backfillMissingEventOccurrences, rebuildRecurringEventOccurrences, } from './eventOccurrences.js';
11
12
  export { listEventAgenda } from './eventAgenda.js';
12
13
  export { eventOccurrenceQueue, eventOccurrenceWorker, ensureEventOccurrenceSchedule, } from './eventOccurrenceJobs.js';
13
14
  export { pollEndQueue, pollEndWorker, schedulePollEnd, cancelPollEnd, } from './pollEndJobs.js';
15
+ export { waitlistOfferQueue, waitlistOfferWorker } from './waitlistOfferJobs.js';
@@ -126,6 +126,7 @@ export declare const threadPreviewMappingForProfile: (profile?: {
126
126
  image?: string | undefined;
127
127
  end?: string | undefined;
128
128
  maxAttendees?: number | undefined;
129
+ waitlistOfferMinutes?: number | undefined;
129
130
  attendeeListPublic?: boolean | undefined;
130
131
  moderators?: string[] | undefined;
131
132
  jam?: {
@@ -371,6 +372,7 @@ export declare const postsWithReplyCountMapping: Mapping<{
371
372
  image?: string | undefined;
372
373
  end?: string | undefined;
373
374
  maxAttendees?: number | undefined;
375
+ waitlistOfferMinutes?: number | undefined;
374
376
  attendeeListPublic?: boolean | undefined;
375
377
  moderators?: string[] | undefined;
376
378
  jam?: {
@@ -611,6 +613,7 @@ export declare const postsWithReplyCountMapping: Mapping<{
611
613
  image?: string | undefined;
612
614
  end?: string | undefined;
613
615
  maxAttendees?: number | undefined;
616
+ waitlistOfferMinutes?: number | undefined;
614
617
  attendeeListPublic?: boolean | undefined;
615
618
  moderators?: string[] | undefined;
616
619
  jam?: {
@@ -855,6 +858,7 @@ export declare const postsWithReplyCountMapping: Mapping<{
855
858
  image?: string | undefined;
856
859
  end?: string | undefined;
857
860
  maxAttendees?: number | undefined;
861
+ waitlistOfferMinutes?: number | undefined;
858
862
  attendeeListPublic?: boolean | undefined;
859
863
  moderators?: string[] | undefined;
860
864
  jam?: {
@@ -1096,6 +1100,7 @@ export declare const postsWithReplyToCountMapping: Mapping<{
1096
1100
  image?: string | undefined;
1097
1101
  end?: string | undefined;
1098
1102
  maxAttendees?: number | undefined;
1103
+ waitlistOfferMinutes?: number | undefined;
1099
1104
  attendeeListPublic?: boolean | undefined;
1100
1105
  moderators?: string[] | undefined;
1101
1106
  jam?: {
@@ -1336,6 +1341,7 @@ export declare const postsWithReplyToCountMapping: Mapping<{
1336
1341
  image?: string | undefined;
1337
1342
  end?: string | undefined;
1338
1343
  maxAttendees?: number | undefined;
1344
+ waitlistOfferMinutes?: number | undefined;
1339
1345
  attendeeListPublic?: boolean | undefined;
1340
1346
  moderators?: string[] | undefined;
1341
1347
  jam?: {
@@ -1580,6 +1586,7 @@ export declare const postsWithReplyToCountMapping: Mapping<{
1580
1586
  image?: string | undefined;
1581
1587
  end?: string | undefined;
1582
1588
  maxAttendees?: number | undefined;
1589
+ waitlistOfferMinutes?: number | undefined;
1583
1590
  attendeeListPublic?: boolean | undefined;
1584
1591
  moderators?: string[] | undefined;
1585
1592
  jam?: {
@@ -1821,6 +1828,7 @@ export declare const postsMapping: Mapping<{
1821
1828
  image?: string | undefined;
1822
1829
  end?: string | undefined;
1823
1830
  maxAttendees?: number | undefined;
1831
+ waitlistOfferMinutes?: number | undefined;
1824
1832
  attendeeListPublic?: boolean | undefined;
1825
1833
  moderators?: string[] | undefined;
1826
1834
  jam?: {
@@ -2059,6 +2067,7 @@ export declare const postsAuthMapping: Mapping<{
2059
2067
  image?: string | undefined;
2060
2068
  end?: string | undefined;
2061
2069
  maxAttendees?: number | undefined;
2070
+ waitlistOfferMinutes?: number | undefined;
2062
2071
  attendeeListPublic?: boolean | undefined;
2063
2072
  moderators?: string[] | undefined;
2064
2073
  jam?: {
@@ -2298,6 +2307,7 @@ export declare const postsMappingForProfile: (profile?: {
2298
2307
  image?: string | undefined;
2299
2308
  end?: string | undefined;
2300
2309
  maxAttendees?: number | undefined;
2310
+ waitlistOfferMinutes?: number | undefined;
2301
2311
  attendeeListPublic?: boolean | undefined;
2302
2312
  moderators?: string[] | undefined;
2303
2313
  jam?: {
@@ -2537,6 +2547,7 @@ export declare const postContextMappingForProfile: (profile?: {
2537
2547
  image?: string | undefined;
2538
2548
  end?: string | undefined;
2539
2549
  maxAttendees?: number | undefined;
2550
+ waitlistOfferMinutes?: number | undefined;
2540
2551
  attendeeListPublic?: boolean | undefined;
2541
2552
  moderators?: string[] | undefined;
2542
2553
  jam?: {
@@ -2775,6 +2786,7 @@ export declare const conversationLeavesMapping: Mapping<{
2775
2786
  image?: string | undefined;
2776
2787
  end?: string | undefined;
2777
2788
  maxAttendees?: number | undefined;
2789
+ waitlistOfferMinutes?: number | undefined;
2778
2790
  attendeeListPublic?: boolean | undefined;
2779
2791
  moderators?: string[] | undefined;
2780
2792
  jam?: {
@@ -3014,6 +3026,7 @@ export declare const conversationLeavesMappingForProfile: (profile?: {
3014
3026
  image?: string | undefined;
3015
3027
  end?: string | undefined;
3016
3028
  maxAttendees?: number | undefined;
3029
+ waitlistOfferMinutes?: number | undefined;
3017
3030
  attendeeListPublic?: boolean | undefined;
3018
3031
  moderators?: string[] | undefined;
3019
3032
  jam?: {
@@ -3251,6 +3264,7 @@ export declare const postIdsMapping: Mapping<{
3251
3264
  image?: string | undefined;
3252
3265
  end?: string | undefined;
3253
3266
  maxAttendees?: number | undefined;
3267
+ waitlistOfferMinutes?: number | undefined;
3254
3268
  attendeeListPublic?: boolean | undefined;
3255
3269
  moderators?: string[] | undefined;
3256
3270
  jam?: {
@@ -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?: {
@@ -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?: {
@@ -485,8 +487,10 @@ export declare const retractReaction: (post: PostWithMeta, profile: Profile) =>
485
487
  } | {
486
488
  type: "rsvp";
487
489
  data: {
488
- response: "no" | "yes" | "tentative" | "removed";
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 = {}) => {
@@ -209,6 +211,40 @@ const rsvpOccurrenceIds = (data) => {
209
211
  return [data.recurrenceId];
210
212
  return undefined;
211
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
+ };
212
248
  export const rsvpRespond = async (profile, post, data) => {
213
249
  if (profile.id === post.profile.id) {
214
250
  return;
@@ -222,64 +258,106 @@ export const rsvpRespond = async (profile, post, data) => {
222
258
  if (data.response === 'removed') {
223
259
  throw forbidden({ errorKey: 'error.rsvpRemovedForbidden' });
224
260
  }
225
- if (getEffectiveRsvp(post, profile.id)?.response === 'removed') {
226
- throw forbidden({ errorKey: 'error.rsvpRemoved' });
227
- }
228
261
  const occurrenceIds = rsvpOccurrenceIds(data);
229
- const maxAttendees = post.data.maxAttendees;
230
- if (maxAttendees) {
231
- if (data.response === 'tentative') {
232
- throw unprocessableRequest({
233
- errorKey: 'error.eventTentativeNotAllowed',
234
- });
262
+ if (!post.data.maxAttendees) {
263
+ if (getEffectiveRsvp(post, profile.id)?.response === 'removed') {
264
+ throw forbidden({ errorKey: 'error.rsvpRemoved' });
235
265
  }
236
- if (data.response === 'yes') {
237
- if (!occurrenceIds && post.data.recurrence) {
238
- if (seriesYesBlockedByCapacity(post, profile.id)) {
239
- throw unprocessableRequest({ errorKey: 'error.eventAtCapacity' });
240
- }
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' });
241
280
  }
242
- else {
243
- const ids = occurrenceIds ?? [undefined];
244
- for (const recurrenceId of ids) {
245
- const currentRsvp = getEffectiveRsvp(post, profile.id, recurrenceId);
246
- if (currentRsvp?.response !== 'yes' &&
247
- countYesRsvps(post, recurrenceId) >= maxAttendees) {
248
- throw unprocessableRequest({ errorKey: 'error.eventAtCapacity' });
249
- }
250
- }
281
+ if (getEffectiveRsvp(loaded, profile.id)?.response === 'removed') {
282
+ throw forbidden({ errorKey: 'error.rsvpRemoved' });
251
283
  }
252
- }
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
+ });
253
324
  }
254
- const { db } = await allpeepDb();
255
- const previousResponses = occurrenceIds
256
- ? occurrenceIds.map((id) => getEffectiveRsvp(post, profile.id, id)?.response)
257
- : undefined;
258
- const previousResponse = previousResponses
259
- ? previousResponses.every(attendingRsvp)
260
- ? previousResponses[0]
261
- : previousResponses.find((response) => !attendingRsvp(response))
262
- : [...(post.rsvps ?? [])]
263
- .filter((rsvp) => rsvp.profile.id === profile.id)
264
- .filter((rsvp) => !rsvp.recurrenceId)
265
- .sort((a, b) => (a.createdAt < b.createdAt ? 1 : -1))[0]?.response;
266
- const writes = occurrenceIds
267
- ? 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: {
268
336
  response: data.response,
269
- recurrenceId,
270
- }))
271
- : 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();
272
350
  for (const entry of writes) {
273
351
  await entryConnector(db, profile, post, {
274
352
  type: 'rsvp',
275
353
  data: entry,
276
354
  });
277
355
  }
278
- const cancel = rsvpCancelNotice(post, profile.id, data.response, occurrenceIds);
356
+ const cancel = rsvpCancelNotice(post, profile.id, response, occurrenceIds);
279
357
  hub.emit('rsvpCreated', profile, post, {
280
358
  type: 'rsvp',
281
359
  data: {
282
- response: data.response,
360
+ response,
283
361
  ...(occurrenceIds?.length === 1
284
362
  ? { recurrenceId: occurrenceIds[0] }
285
363
  : {}),
@@ -296,30 +374,80 @@ export const rsvpManageByOrganizer = async (actingProfile, targetProfile, post,
296
374
  if (targetProfile.id === post.profile.id) {
297
375
  throw forbidden({ errorKey: 'forbidden' });
298
376
  }
299
- if (post.type !== 'event') {
377
+ if (post.type !== 'event' || post.data?.type !== 'event') {
300
378
  throw unprocessableRequest({ errorKey: 'error.unprocessableRequest' });
301
379
  }
302
380
  const data = { response, recurrenceId };
303
- const { db } = await allpeepDb();
304
- const previousResponse = [...(post.rsvps ?? [])]
305
- .filter((rsvp) => rsvp.profile.id === targetProfile.id)
306
- .filter((rsvp) => recurrenceId
307
- ? sameRecurrenceId(rsvp.recurrenceId, recurrenceId) ||
308
- !rsvp.recurrenceId
309
- : !rsvp.recurrenceId)
310
- .sort((a, b) => (a.createdAt < b.createdAt ? 1 : -1))[0]?.response;
311
- await entryConnector(db, targetProfile, post, {
312
- type: 'rsvp',
313
- data,
314
- });
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;
315
436
  hub.emit('rsvpCreated', targetProfile, post, {
316
437
  type: 'rsvp',
317
438
  data,
318
439
  previousResponse,
319
440
  });
320
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;
321
449
  /**
322
- * Remove a profile from a direct-message conversation thread.
450
+ * Remove a profile from a direct-message conversation.
323
451
  *
324
452
  * - Creates a system "X left" post (empty content) with the *remaining*
325
453
  * participants as audience. The leaving user is excluded so future
@@ -330,29 +458,53 @@ export const rsvpManageByOrganizer = async (actingProfile, targetProfile, post,
330
458
  * - The conversation post-creation endpoint detects leavers (author not in
331
459
  * their own post's audience) to block further posting and exclude them
332
460
  * from future replies' audience.
333
- * - For 1:1 DMs (no remaining participants), removes the user from every
334
- * post's audience so the thread vanishes from their inbox.
335
- * - The leaving user can still find the thread in the "Archived" conversations
336
- * 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.
337
467
  */
338
468
  export const leaveConversation = async (rootPost, profile) => {
339
469
  const { db } = await allpeepDb();
340
- 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);
341
478
  const [lastPost] = lastPostId === rootPost.id
342
479
  ? [rootPost]
343
480
  : await findPostsForAuth([lastPostId]);
344
481
  if (!lastPost)
345
482
  return;
346
483
  const remainingAudience = lastPost.audience?.filter((p) => p.id !== profile.id) ?? [];
347
- 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) {
348
500
  await createPost({ type: 'note', content: '' }, profile, { type: 'note', visibility: 'direct', creatorId: profile.id }, {
349
501
  inReplyToId: lastPost.id,
350
502
  audience: remainingAudience,
351
503
  });
352
504
  }
353
505
  else {
354
- // 1:1 DM — remove the user from every post's audience so the
355
- // 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.
356
508
  await db.execute(sql `
357
509
  WITH RECURSIVE t AS (
358
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 {};